@readium/navigator 2.4.0-alpha.7 → 2.4.0-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -111,7 +111,7 @@ const f = class f {
|
|
|
111
111
|
}
|
|
112
112
|
};
|
|
113
113
|
f.NONE = new f("none"), f.ANNOTATIONS = new f("annotations"), f.ARIA = new f("ARIA"), f.INDEX = new f("index"), f.PAGE_BREAK_MARKERS = new f("pageBreakMarkers"), f.PAGE_NAVIGATION = new f("pageNavigation"), f.PRINT_PAGE_NUMBERS = new f("printPageNumbers"), f.READING_ORDER = new f("readingOrder"), f.STRUCTURAL_NAVIGATION = new f("structuralNavigation"), f.TABLE_OF_CONTENTS = new f("tableOfContents"), f.TAGGED_PDF = new f("taggedPDF"), f.ALTERNATIVE_TEXT = new f("alternativeText"), f.AUDIO_DESCRIPTION = new f("audioDescription"), f.CAPTIONS = new f("captions"), f.CLOSED_CAPTIONS = new f("closedCaptions"), f.DESCRIBED_MATH = new f("describedMath"), f.LONG_DESCRIPTION = new f("longDescription"), f.OPEN_CAPTIONS = new f("openCaptions"), f.SIGN_LANGUAGE = new f("signLanguage"), f.TRANSCRIPT = new f("transcript"), f.DISPLAY_TRANSFORMABILITY = new f("displayTransformability"), f.SYNCHRONIZED_AUDIO_TEXT = new f("synchronizedAudioText"), f.TIMING_CONTROL = new f("timingControl"), f.UNLOCKED = new f("unlocked"), f.CHEM_ML = new f("ChemML"), f.LATEX = new f("latex"), f.LATEX_CHEMISTRY = new f("latex-chemistry"), f.MATH_ML = new f("MathML"), f.MATH_ML_CHEMISTRY = new f("MathML-chemistry"), f.TTS_MARKUP = new f("ttsMarkup"), f.HIGH_CONTRAST_AUDIO = new f("highContrastAudio"), f.HIGH_CONTRAST_DISPLAY = new f("highContrastDisplay"), f.LARGE_PRINT = new f("largePrint"), f.BRAILLE = new f("braille"), f.TACTILE_GRAPHIC = new f("tactileGraphic"), f.TACTILE_OBJECT = new f("tactileObject"), f.FULL_RUBY_ANNOTATIONS = new f("fullRubyAnnotations"), f.HORIZONTAL_WRITING = new f("horizontalWriting"), f.RUBY_ANNOTATIONS = new f("rubyAnnotations"), f.VERTICAL_WRITING = new f("verticalWriting"), f.WITH_ADDITIONAL_WORD_SEGMENTATION = new f("withAdditionalWordSegmentation"), f.WITHOUT_ADDITIONAL_WORD_SEGMENTATION = new f("withoutAdditionalWordSegmentation");
|
|
114
|
-
let
|
|
114
|
+
let Nt = f;
|
|
115
115
|
const C = class C {
|
|
116
116
|
constructor(t) {
|
|
117
117
|
this.value = t;
|
|
@@ -938,8 +938,8 @@ class B {
|
|
|
938
938
|
duration: W(t.duration),
|
|
939
939
|
bitrate: W(t.bitrate),
|
|
940
940
|
languages: Li(t.language),
|
|
941
|
-
alternates:
|
|
942
|
-
children:
|
|
941
|
+
alternates: Ft.deserialize(t.alternate),
|
|
942
|
+
children: Ft.deserialize(t.children)
|
|
943
943
|
});
|
|
944
944
|
}
|
|
945
945
|
/**
|
|
@@ -997,7 +997,7 @@ class B {
|
|
|
997
997
|
});
|
|
998
998
|
}
|
|
999
999
|
}
|
|
1000
|
-
class
|
|
1000
|
+
class Ft {
|
|
1001
1001
|
/**
|
|
1002
1002
|
* Creates a [Links].
|
|
1003
1003
|
*/
|
|
@@ -1009,7 +1009,7 @@ class Nt {
|
|
|
1009
1009
|
*/
|
|
1010
1010
|
static deserialize(t) {
|
|
1011
1011
|
if (t && Array.isArray(t))
|
|
1012
|
-
return new
|
|
1012
|
+
return new Ft(
|
|
1013
1013
|
t.map((e) => B.deserialize(e)).filter((e) => e !== void 0)
|
|
1014
1014
|
);
|
|
1015
1015
|
}
|
|
@@ -1091,7 +1091,7 @@ class Nt {
|
|
|
1091
1091
|
return this.items.filter((t) => t.type);
|
|
1092
1092
|
}
|
|
1093
1093
|
}
|
|
1094
|
-
var Oi = /* @__PURE__ */ ((s) => (s.EPUB = "https://readium.org/webpub-manifest/profiles/epub", s.AUDIOBOOK = "https://readium.org/webpub-manifest/profiles/audiobook", s.DIVINA = "https://readium.org/webpub-manifest/profiles/divina", s.PDF = "https://readium.org/webpub-manifest/profiles/pdf", s))(Oi || {}),
|
|
1094
|
+
var Oi = /* @__PURE__ */ ((s) => (s.EPUB = "https://readium.org/webpub-manifest/profiles/epub", s.AUDIOBOOK = "https://readium.org/webpub-manifest/profiles/audiobook", s.DIVINA = "https://readium.org/webpub-manifest/profiles/divina", s.PDF = "https://readium.org/webpub-manifest/profiles/pdf", s))(Oi || {}), F = /* @__PURE__ */ ((s) => (s.ltr = "ltr", s.rtl = "rtl", s))(F || {});
|
|
1095
1095
|
j.prototype.getContains = function() {
|
|
1096
1096
|
return new Set(this.otherProperties.contains || []);
|
|
1097
1097
|
};
|
|
@@ -2012,7 +2012,7 @@ function Mi(s, t, e) {
|
|
|
2012
2012
|
if (r === o)
|
|
2013
2013
|
continue;
|
|
2014
2014
|
const a = V(r.top, o.top, t) && V(r.bottom, o.bottom, t), l = V(r.left, o.left, t) && V(r.right, o.right, t);
|
|
2015
|
-
if (a && !l &&
|
|
2015
|
+
if (a && !l && Ni(r, o, t)) {
|
|
2016
2016
|
const u = s.filter((y) => y !== r && y !== o), m = Ln(r, o);
|
|
2017
2017
|
return u.push(m), Mi(
|
|
2018
2018
|
u,
|
|
@@ -2058,7 +2058,7 @@ function Ui(s) {
|
|
|
2058
2058
|
for (let t = 0; t < s.length; t++)
|
|
2059
2059
|
for (let e = t + 1; e < s.length; e++) {
|
|
2060
2060
|
const i = s[t], n = s[e];
|
|
2061
|
-
if (i !== n &&
|
|
2061
|
+
if (i !== n && Ni(i, n, -1)) {
|
|
2062
2062
|
let r = [], o;
|
|
2063
2063
|
const a = ei(i, n);
|
|
2064
2064
|
if (a.length === 1)
|
|
@@ -2135,7 +2135,7 @@ function Tn(s, t) {
|
|
|
2135
2135
|
width: Math.max(0, i - e)
|
|
2136
2136
|
};
|
|
2137
2137
|
}
|
|
2138
|
-
function
|
|
2138
|
+
function Ni(s, t, e) {
|
|
2139
2139
|
return (s.left < t.right || e >= 0 && V(s.left, t.right, e)) && (t.left < s.right || e >= 0 && V(t.left, s.right, e)) && (s.top < t.bottom || e >= 0 && V(s.top, t.bottom, e)) && (t.top < s.bottom || e >= 0 && V(t.top, s.bottom, e));
|
|
2140
2140
|
}
|
|
2141
2141
|
function V(s, t, e) {
|
|
@@ -2147,7 +2147,7 @@ function Te(s) {
|
|
|
2147
2147
|
Object.hasOwn(e, i) && !Number.isNaN(Number.parseInt(i)) && (t[e[i]] = e.getPropertyValue(e[i]));
|
|
2148
2148
|
return t;
|
|
2149
2149
|
}
|
|
2150
|
-
function
|
|
2150
|
+
function Fi(s, t) {
|
|
2151
2151
|
const e = Te(s);
|
|
2152
2152
|
Object.keys(e).forEach((i) => {
|
|
2153
2153
|
t.hasOwnProperty(i) || te(s, i);
|
|
@@ -2239,7 +2239,7 @@ const ct = { r: 255, g: 255, b: 255, a: 1 }, st = /* @__PURE__ */ new Map(), An
|
|
|
2239
2239
|
const e = pe(s, t), i = ni(e, { r: 255, g: 255, b: 255, a: 1 }), n = ni(e, { r: 0, g: 0, b: 0, a: 1 });
|
|
2240
2240
|
return i > n;
|
|
2241
2241
|
}, Mn = (s, t = null) => me(s, t) ? "white" : "black", ri = "#FFFF00", Un = () => "Highlight" in window, si = ["IMG", "IMAGE", "AUDIO", "VIDEO", "SVG"];
|
|
2242
|
-
class
|
|
2242
|
+
class Nn {
|
|
2243
2243
|
/**
|
|
2244
2244
|
* Creates a DecorationGroup object
|
|
2245
2245
|
* @param id Unique HTML ID-adhering name of the group
|
|
@@ -2430,7 +2430,7 @@ const wt = class wt extends ft {
|
|
|
2430
2430
|
mount(t, e) {
|
|
2431
2431
|
return this.wnd = t, e.register("decorate", wt.moduleName, (i, n) => {
|
|
2432
2432
|
const r = i;
|
|
2433
|
-
r.decoration && r.decoration.locator && (r.decoration.locator = H.deserialize(r.decoration.locator)), this.groups.has(r.group) || this.groups.set(r.group, new
|
|
2433
|
+
r.decoration && r.decoration.locator && (r.decoration.locator = H.deserialize(r.decoration.locator)), this.groups.has(r.group) || this.groups.set(r.group, new Nn(
|
|
2434
2434
|
t,
|
|
2435
2435
|
e,
|
|
2436
2436
|
`readium-decoration-${this.lastGroupId++}`,
|
|
@@ -2531,7 +2531,7 @@ function Ii(s) {
|
|
|
2531
2531
|
const t = s.document.createElement("style");
|
|
2532
2532
|
t.appendChild(s.document.createTextNode("*{}")), s.document.body.appendChild(t), s.document.body.removeChild(t);
|
|
2533
2533
|
}
|
|
2534
|
-
function
|
|
2534
|
+
function Fn(s) {
|
|
2535
2535
|
return s < 0.5 ? 2 * s * s : -1 + (4 - 2 * s) * s;
|
|
2536
2536
|
}
|
|
2537
2537
|
function T(s) {
|
|
@@ -2711,7 +2711,7 @@ const hi = "readium-column-snapper-style", Gn = 200, U = class U extends Et {
|
|
|
2711
2711
|
), c = this.snapOffset(a + h), u = c > this.scrollOffset() ? "right" : "left";
|
|
2712
2712
|
if (this.checkSuspiciousSnap(u, Math.abs(c - this.scrollOffset())), t && c !== this.scrollOffset()) {
|
|
2713
2713
|
this.snappingCancelled = !1;
|
|
2714
|
-
const m = (b, _, z, Q) => z > Q ? _ : b + (_ - b) *
|
|
2714
|
+
const m = (b, _, z, Q) => z > Q ? _ : b + (_ - b) * Fn(z / Q), y = (
|
|
2715
2715
|
/*Math.abs(startX - (this.useTransform ? currentOffset : 0)) < 10 ? 1 : */
|
|
2716
2716
|
Gn * o
|
|
2717
2717
|
);
|
|
@@ -3622,7 +3622,7 @@ const _t = class _t extends ft {
|
|
|
3622
3622
|
), Reflect.defineProperty(t.navigator, "epubReadingSystem", {
|
|
3623
3623
|
value: {
|
|
3624
3624
|
name: "readium-ts-toolkit",
|
|
3625
|
-
version: "2.4.0-alpha.
|
|
3625
|
+
version: "2.4.0-alpha.8",
|
|
3626
3626
|
hasFeature: (n, r = "") => {
|
|
3627
3627
|
switch (n) {
|
|
3628
3628
|
case "dom-manipulation":
|
|
@@ -3687,7 +3687,7 @@ const di = "readium-viewport", K = class K extends Ht {
|
|
|
3687
3687
|
}), e.register("get_properties", K.moduleName, (n, r) => {
|
|
3688
3688
|
Te(t), r(!0);
|
|
3689
3689
|
}), e.register("update_properties", K.moduleName, (n, r) => {
|
|
3690
|
-
n["--RS__viewportWidth"] = `${t.innerWidth}px`,
|
|
3690
|
+
n["--RS__viewportWidth"] = `${t.innerWidth}px`, Fi(t, n), r(!0);
|
|
3691
3691
|
}), e.register("set_property", K.moduleName, (n, r) => {
|
|
3692
3692
|
const o = n;
|
|
3693
3693
|
Pt(t, o[0], o[1]), r(!0);
|
|
@@ -3763,7 +3763,7 @@ const Z = class Z extends ft {
|
|
|
3763
3763
|
), e.register("get_properties", Z.moduleName, (i, n) => {
|
|
3764
3764
|
Te(t), n(!0);
|
|
3765
3765
|
}), e.register("update_properties", Z.moduleName, (i, n) => {
|
|
3766
|
-
|
|
3766
|
+
Fi(t, i), n(!0);
|
|
3767
3767
|
}), e.register("set_property", Z.moduleName, (i, n) => {
|
|
3768
3768
|
const r = i;
|
|
3769
3769
|
Pt(t, r[0], r[1]), n(!0);
|
|
@@ -3984,13 +3984,13 @@ class ji extends er {
|
|
|
3984
3984
|
* Moves to the left content portion (eg. page) relative to the reading progression direction.
|
|
3985
3985
|
*/
|
|
3986
3986
|
goLeft(t = !1, e) {
|
|
3987
|
-
this.readingProgression ===
|
|
3987
|
+
this.readingProgression === F.ltr ? this.goBackward(t, e) : this.readingProgression === F.rtl && this.goForward(t, e);
|
|
3988
3988
|
}
|
|
3989
3989
|
/**
|
|
3990
3990
|
* Moves to the right content portion (eg. page) relative to the reading progression direction.
|
|
3991
3991
|
*/
|
|
3992
3992
|
goRight(t = !1, e) {
|
|
3993
|
-
this.readingProgression ===
|
|
3993
|
+
this.readingProgression === F.ltr ? this.goForward(t, e) : this.readingProgression === F.rtl && this.goBackward(t, e);
|
|
3994
3994
|
}
|
|
3995
3995
|
}
|
|
3996
3996
|
class ir {
|
|
@@ -4758,7 +4758,7 @@ function fr(s, t) {
|
|
|
4758
4758
|
function yr(s, t) {
|
|
4759
4759
|
return s == null || t == null || s >= t ? s : void 0;
|
|
4760
4760
|
}
|
|
4761
|
-
function
|
|
4761
|
+
function N(s) {
|
|
4762
4762
|
return typeof s == "string" ? s : s === null ? null : void 0;
|
|
4763
4763
|
}
|
|
4764
4764
|
function P(s) {
|
|
@@ -4792,7 +4792,7 @@ function Ki(s) {
|
|
|
4792
4792
|
}
|
|
4793
4793
|
class xt {
|
|
4794
4794
|
constructor(t = {}) {
|
|
4795
|
-
this.fontFamily =
|
|
4795
|
+
this.fontFamily = N(t.fontFamily), this.fontWeight = q(t.fontWeight, it.range), this.hyphens = P(t.hyphens), this.iOSPatch = P(t.iOSPatch), this.iPadOSPatch = P(t.iPadOSPatch), this.letterSpacing = v(t.letterSpacing), this.ligatures = P(t.ligatures), this.lineHeight = v(t.lineHeight), this.noRuby = P(t.noRuby), this.paragraphIndent = v(t.paragraphIndent), this.paragraphSpacing = v(t.paragraphSpacing), this.textAlign = ie(t.textAlign, J), this.textNormalization = P(t.textNormalization), this.wordSpacing = v(t.wordSpacing), this.zoom = q(t.zoom, Zt.range);
|
|
4796
4796
|
}
|
|
4797
4797
|
static serialize(t) {
|
|
4798
4798
|
const { ...e } = t;
|
|
@@ -4815,7 +4815,7 @@ class xt {
|
|
|
4815
4815
|
}
|
|
4816
4816
|
class Sr {
|
|
4817
4817
|
constructor(t) {
|
|
4818
|
-
this.fontFamily =
|
|
4818
|
+
this.fontFamily = N(t.fontFamily) || null, this.fontWeight = q(t.fontWeight, it.range) || null, this.hyphens = P(t.hyphens) ?? null, this.iOSPatch = t.iOSPatch === !1 ? !1 : (L.OS.iOS || L.OS.iPadOS) && L.iOSRequest === "mobile", this.iPadOSPatch = t.iPadOSPatch === !1 ? !1 : L.OS.iPadOS && L.iOSRequest === "desktop", this.letterSpacing = v(t.letterSpacing) || null, this.ligatures = P(t.ligatures) ?? null, this.lineHeight = v(t.lineHeight) || null, this.noRuby = P(t.noRuby) ?? !1, this.paragraphIndent = v(t.paragraphIndent) ?? null, this.paragraphSpacing = v(t.paragraphSpacing) ?? null, this.textAlign = ie(t.textAlign, J) || null, this.textNormalization = P(t.textNormalization) ?? !1, this.wordSpacing = v(t.wordSpacing) || null, this.zoom = q(t.zoom, Zt.range) || 1, this.experiments = Ki(t.experiments) ?? null;
|
|
4819
4819
|
}
|
|
4820
4820
|
}
|
|
4821
4821
|
class gi {
|
|
@@ -4961,7 +4961,7 @@ class fi {
|
|
|
4961
4961
|
}
|
|
4962
4962
|
get isDisplayTransformable() {
|
|
4963
4963
|
return this.metadata?.accessibility?.feature?.some(
|
|
4964
|
-
(t) => t.value ===
|
|
4964
|
+
(t) => t.value === Nt.DISPLAY_TRANSFORMABILITY.value
|
|
4965
4965
|
) ?? !1;
|
|
4966
4966
|
}
|
|
4967
4967
|
get fontFamily() {
|
|
@@ -5681,7 +5681,7 @@ onmessage = function(event) {
|
|
|
5681
5681
|
time: performance.now() - startTime
|
|
5682
5682
|
})
|
|
5683
5683
|
}
|
|
5684
|
-
`,
|
|
5684
|
+
`, Ne = class Ne {
|
|
5685
5685
|
constructor(t, e) {
|
|
5686
5686
|
this.callbacks = /* @__PURE__ */ new Map(), this.worker = t, this.blobUrl = e, this.worker.onmessage = (i) => {
|
|
5687
5687
|
const n = i.data, r = n.id, o = this.callbacks.get(n.id);
|
|
@@ -5706,8 +5706,8 @@ onmessage = function(event) {
|
|
|
5706
5706
|
this.worker.terminate(), URL.revokeObjectURL(this.blobUrl);
|
|
5707
5707
|
}
|
|
5708
5708
|
};
|
|
5709
|
-
|
|
5710
|
-
let Jt =
|
|
5709
|
+
Ne.workerScript = xr;
|
|
5710
|
+
let Jt = Ne;
|
|
5711
5711
|
function Ue(s) {
|
|
5712
5712
|
return typeof window < "u" && console ? console[s] : (...t) => {
|
|
5713
5713
|
};
|
|
@@ -6133,7 +6133,7 @@ class Ur extends ji {
|
|
|
6133
6133
|
}
|
|
6134
6134
|
get hasDisplayTransformability() {
|
|
6135
6135
|
return this.pub.metadata?.accessibility?.feature?.some(
|
|
6136
|
-
(t) => t.value ===
|
|
6136
|
+
(t) => t.value === Nt.DISPLAY_TRANSFORMABILITY.value
|
|
6137
6137
|
) ?? !1;
|
|
6138
6138
|
}
|
|
6139
6139
|
eventListener(t, e) {
|
|
@@ -6363,7 +6363,7 @@ class Ur extends ji {
|
|
|
6363
6363
|
});
|
|
6364
6364
|
}
|
|
6365
6365
|
}
|
|
6366
|
-
const ps = Ur,
|
|
6366
|
+
const ps = Ur, Nr = (s) => {
|
|
6367
6367
|
const t = s.join(" ");
|
|
6368
6368
|
return [
|
|
6369
6369
|
// 'self' is useless because the document is loaded from a blob: URL
|
|
@@ -6412,17 +6412,14 @@ class on {
|
|
|
6412
6412
|
}
|
|
6413
6413
|
async buildHtmlFrame(t = !1) {
|
|
6414
6414
|
if (!this.currentResource) throw new Error("No resource loaded");
|
|
6415
|
-
const e = await this.currentResource.link(), i = await this.currentResource.
|
|
6415
|
+
const e = await this.currentResource.link(), i = await this.currentResource.readAsXML();
|
|
6416
6416
|
if (!i) throw new Error(`Failed reading item ${e.href}`);
|
|
6417
|
-
const n =
|
|
6418
|
-
|
|
6419
|
-
|
|
6420
|
-
|
|
6421
|
-
if (r) {
|
|
6422
|
-
const o = r.querySelector("div");
|
|
6423
|
-
throw new Error(`Failed parsing item ${e.href}: ${o?.textContent || r.textContent}`);
|
|
6417
|
+
const n = i.querySelector("parsererror");
|
|
6418
|
+
if (n) {
|
|
6419
|
+
const r = n.querySelector("div");
|
|
6420
|
+
throw new Error(`Failed parsing item ${e.href}: ${r?.textContent || n.textContent}`);
|
|
6424
6421
|
}
|
|
6425
|
-
return this.injector && await this.injector.injectForDocument(
|
|
6422
|
+
return this.injector && await this.injector.injectForDocument(i, e), this.finalizeDOM(i, this.pub.baseURL, e.toURL(this.baseURL) || "", e.mediaType, t, this.cssProperties);
|
|
6426
6423
|
}
|
|
6427
6424
|
async buildImageFrame() {
|
|
6428
6425
|
if (!this.currentResource) throw new Error("No resource loaded");
|
|
@@ -6471,7 +6468,7 @@ class on {
|
|
|
6471
6468
|
c.href = i, c.dataset.readium = "true", t.head.firstChild.before(c);
|
|
6472
6469
|
}
|
|
6473
6470
|
const h = t.createElement("meta");
|
|
6474
|
-
return h.httpEquiv = "Content-Security-Policy", h.content =
|
|
6471
|
+
return h.httpEquiv = "Content-Security-Policy", h.content = Nr(l), h.dataset.readium = "true", t.head.firstChild.before(h), URL.createObjectURL(
|
|
6475
6472
|
new Blob([new XMLSerializer().serializeToString(t)], {
|
|
6476
6473
|
type: n.isHTML ? n.string : "application/xhtml+xml"
|
|
6477
6474
|
// Fallback to XHTML
|
|
@@ -6479,7 +6476,7 @@ class on {
|
|
|
6479
6476
|
);
|
|
6480
6477
|
}
|
|
6481
6478
|
}
|
|
6482
|
-
class
|
|
6479
|
+
class Fr {
|
|
6483
6480
|
constructor(t, e = {}, i = []) {
|
|
6484
6481
|
this.hidden = !0, this.destroyed = !1, this.currModules = [], this.frame = document.createElement("iframe"), this.frame.sandbox.value = "allow-same-origin allow-scripts", this.frame.classList.add("readium-navigator-iframe"), this.frame.style.visibility = "hidden", this.frame.style.setProperty("aria-hidden", "true"), this.frame.style.opacity = "0", this.frame.style.position = "absolute", this.frame.style.pointerEvents = "none", this.frame.style.transition = "visibility 0s, opacity 0.1s linear", this.source = t, this.contentProtectionConfig = { ...e }, this.keyboardPeripheralsConfig = [...i];
|
|
6485
6482
|
}
|
|
@@ -6631,7 +6628,7 @@ class Dr {
|
|
|
6631
6628
|
injector: this.injector
|
|
6632
6629
|
}
|
|
6633
6630
|
));
|
|
6634
|
-
const b = new
|
|
6631
|
+
const b = new Fr(await this.blobs.get(d).build(), this.contentProtectionConfig, this.keyboardPeripheralsConfig);
|
|
6635
6632
|
d !== o && await b.hide(), this.container.appendChild(b.iframe), await b.load(i), this.pool.set(d, b);
|
|
6636
6633
|
};
|
|
6637
6634
|
try {
|
|
@@ -6687,7 +6684,7 @@ class Dr {
|
|
|
6687
6684
|
}
|
|
6688
6685
|
class Ir {
|
|
6689
6686
|
constructor(t, e, i, n = {}, r = []) {
|
|
6690
|
-
this.frameIsAppended = !1, this.currModules = [], this.
|
|
6687
|
+
this.frameIsAppended = !1, this.currModules = [], this.viewportSize = void 0, this.cachedPage = void 0, this.peripherals = t, this.debugHref = i, this.contentProtectionConfig = { ...n }, this.keyboardPeripheralsConfig = [...r], this.frame = document.createElement("iframe"), this.frame.sandbox.value = "allow-same-origin allow-scripts", this.frame.classList.add("readium-navigator-iframe"), this.frame.classList.add("blank"), this.frame.scrolling = "no", this.frame.style.visibility = "hidden", this.frame.style.setProperty("aria-hidden", "true"), this.frame.style.display = "none", this.frame.style.position = "absolute", this.frame.style.pointerEvents = "none", this.frame.style.transformOrigin = "0 0", this.frame.style.transform = "scale(1)", this.frame.style.background = "#fff", this.frame.style.touchAction = "none", this.frame.dataset.originalHref = i, this.source = "about:blank", this.wrapper = document.createElement("div"), this.wrapper.style.position = "relative", this.wrapper.style.float = this.wrapper.style.cssFloat = e === F.rtl ? "right" : "left";
|
|
6691
6688
|
}
|
|
6692
6689
|
async load(t, e) {
|
|
6693
6690
|
return this.frameIsAppended || (this.wrapper.appendChild(this.frame), this.frameIsAppended = !0), this.source === e && this.loadPromise && [...this.currModules].sort().join("|") === [...t].sort().join("|") ? this.loadPromise : (this.loaded && this.source !== e && this.window.stop(), this.source = e, this.loadPromise = new Promise((i, n) => {
|
|
@@ -6724,7 +6721,7 @@ class Ir {
|
|
|
6724
6721
|
}
|
|
6725
6722
|
// Parses the page size from the viewport meta tag of the loaded resource.
|
|
6726
6723
|
loadPageSize() {
|
|
6727
|
-
if (this.
|
|
6724
|
+
if (this.viewportSize) return this.viewportSize;
|
|
6728
6725
|
const t = this.frame.contentWindow, e = t.document.head.querySelector(
|
|
6729
6726
|
"meta[name=viewport]"
|
|
6730
6727
|
);
|
|
@@ -6734,12 +6731,12 @@ class Ir {
|
|
|
6734
6731
|
for (; n = i.exec(e.content); )
|
|
6735
6732
|
n[1] === "width" ? r = Number.parseFloat(n[2]) : n[1] === "height" && (o = Number.parseFloat(n[2]));
|
|
6736
6733
|
if (r > 0 && o > 0)
|
|
6737
|
-
return { width: r, height: o };
|
|
6734
|
+
return this.viewportSize = { width: r, height: o }, this.viewportSize;
|
|
6738
6735
|
}
|
|
6739
|
-
return
|
|
6736
|
+
return {
|
|
6740
6737
|
width: t.document.body.scrollWidth,
|
|
6741
6738
|
height: t.document.body.scrollHeight
|
|
6742
|
-
}
|
|
6739
|
+
};
|
|
6743
6740
|
}
|
|
6744
6741
|
update(t) {
|
|
6745
6742
|
if (!this.loaded) return;
|
|
@@ -7159,7 +7156,7 @@ class jr {
|
|
|
7159
7156
|
"center"
|
|
7160
7157
|
) : (
|
|
7161
7158
|
// Center it
|
|
7162
|
-
((this.shift ? 0 : 1) + n - this.nLandscape) % 2 ? t.metadata.readingProgression ===
|
|
7159
|
+
((this.shift ? 0 : 1) + n - this.nLandscape) % 2 ? t.metadata.readingProgression === F.rtl ? "right" : "left" : t.metadata.readingProgression === F.rtl ? "left" : "right"
|
|
7163
7160
|
)
|
|
7164
7161
|
})), (r || i.properties?.otherProperties.addBlank) && this.nLandscape++;
|
|
7165
7162
|
}), e && (this.spreads = []), this.buildSpreads(t.readingOrder);
|
|
@@ -7189,7 +7186,7 @@ class jr {
|
|
|
7189
7186
|
const Ei = 8, Ci = 5, $r = 300, Xr = 15e3, Yr = 250, qr = 150, Kr = 500;
|
|
7190
7187
|
class Zr {
|
|
7191
7188
|
constructor(t, e, i, n, r, o) {
|
|
7192
|
-
if (this.pool = /* @__PURE__ */ new Map(), this.blobs = /* @__PURE__ */ new Map(), this.inprogress = /* @__PURE__ */ new Map(), this.delayedShow = /* @__PURE__ */ new Map(), this.delayedTimeout = /* @__PURE__ */ new Map(), this.previousFrames = [], this.injector = null, this.width = 0, this.height = 0, this.transform = "", this.currentSlide = 0, this.spread = !0, this.orientationInternal = -1, this.container = t, this.positions = e, this.pub = i, this.injector = n ?? null, this.contentProtectionConfig = r || {}, this.keyboardPeripheralsConfig = o || [], this.spreadPresentation = i.metadata.otherMetadata?.spread || Ee.auto, this.pub.metadata.effectiveReadingProgression !==
|
|
7189
|
+
if (this.pool = /* @__PURE__ */ new Map(), this.blobs = /* @__PURE__ */ new Map(), this.inprogress = /* @__PURE__ */ new Map(), this.delayedShow = /* @__PURE__ */ new Map(), this.delayedTimeout = /* @__PURE__ */ new Map(), this.previousFrames = [], this.injector = null, this.width = 0, this.height = 0, this.transform = "", this.currentSlide = 0, this.spread = !0, this.orientationInternal = -1, this.container = t, this.positions = e, this.pub = i, this.injector = n ?? null, this.contentProtectionConfig = r || {}, this.keyboardPeripheralsConfig = o || [], this.spreadPresentation = i.metadata.otherMetadata?.spread || Ee.auto, this.pub.metadata.effectiveReadingProgression !== F.rtl && this.pub.metadata.effectiveReadingProgression !== F.ltr)
|
|
7193
7190
|
throw Error("Unsupported reading progression for EPUB");
|
|
7194
7191
|
this.spreader = new jr(this.pub), this.containerHeightCached = t.clientHeight, this.bookElement = document.createElement("div"), this.bookElement.ariaLabel = "Book", this.bookElement.tabIndex = -1, this.updateBookStyle(!0), this.spineElement = document.createElement("div"), this.spineElement.ariaLabel = "Spine", this.bookElement.appendChild(this.spineElement), this.container.appendChild(this.bookElement), this.updateSpineStyle(!0), this.peripherals = new Gr(this);
|
|
7195
7192
|
const a = document.createDocumentFragment();
|
|
@@ -7230,7 +7227,7 @@ class Zr {
|
|
|
7230
7227
|
this.width = this.bookElement.clientWidth, this.height = this.bookElement.clientHeight;
|
|
7231
7228
|
}
|
|
7232
7229
|
get rtl() {
|
|
7233
|
-
return this.pub.metadata.effectiveReadingProgression ===
|
|
7230
|
+
return this.pub.metadata.effectiveReadingProgression === F.rtl;
|
|
7234
7231
|
}
|
|
7235
7232
|
get single() {
|
|
7236
7233
|
return !this.spread || this.portrait;
|
|
@@ -7425,8 +7422,8 @@ class Zr {
|
|
|
7425
7422
|
let Q = !1;
|
|
7426
7423
|
const hn = window.setTimeout(async () => {
|
|
7427
7424
|
this.delayedTimeout.set(d, 0);
|
|
7428
|
-
const cn = this.makeSpread(this.reAlign(p)), dn = this.spreadPosition(cn, b),
|
|
7429
|
-
await
|
|
7425
|
+
const cn = this.makeSpread(this.reAlign(p)), dn = this.spreadPosition(cn, b), Fe = this.pool.get(d);
|
|
7426
|
+
await Fe.load(i, await this.blobs.get(d).build(!0)), this.peripherals.isScaled || await Fe.show(dn), this.delayedShow.delete(d), Q = !0, _();
|
|
7430
7427
|
}, $r);
|
|
7431
7428
|
setTimeout(() => {
|
|
7432
7429
|
!Q && this.delayedShow.has(d) && z(`Offscreen load timeout: ${d}`);
|
|
@@ -7507,7 +7504,7 @@ class Zr {
|
|
|
7507
7504
|
}
|
|
7508
7505
|
class Ot {
|
|
7509
7506
|
constructor(t = {}) {
|
|
7510
|
-
this.backgroundColor =
|
|
7507
|
+
this.backgroundColor = N(t.backgroundColor), this.blendFilter = P(t.blendFilter), this.constraint = v(t.constraint), this.columnCount = v(t.columnCount), this.darkenFilter = pt(t.darkenFilter), this.deprecatedFontSize = P(t.deprecatedFontSize), this.fontFamily = N(t.fontFamily), this.fontSize = q(t.fontSize, Gt.range), this.fontSizeNormalize = P(t.fontSizeNormalize), this.fontOpticalSizing = P(t.fontOpticalSizing), this.fontWeight = q(t.fontWeight, it.range), this.fontWidth = q(t.fontWidth, jt.range), this.hyphens = P(t.hyphens), this.invertFilter = pt(t.invertFilter), this.invertGaijiFilter = pt(t.invertGaijiFilter), this.iOSPatch = P(t.iOSPatch), this.iPadOSPatch = P(t.iPadOSPatch), this.letterSpacing = v(t.letterSpacing), this.ligatures = P(t.ligatures), this.lineHeight = v(t.lineHeight), this.linkColor = N(t.linkColor), this.noRuby = P(t.noRuby), this.pageGutter = v(t.pageGutter), this.paragraphIndent = v(t.paragraphIndent), this.paragraphSpacing = v(t.paragraphSpacing), this.scroll = P(t.scroll), this.scrollPaddingTop = v(t.scrollPaddingTop), this.scrollPaddingBottom = v(t.scrollPaddingBottom), this.scrollPaddingLeft = v(t.scrollPaddingLeft), this.scrollPaddingRight = v(t.scrollPaddingRight), this.selectionBackgroundColor = N(t.selectionBackgroundColor), this.selectionTextColor = N(t.selectionTextColor), this.textAlign = ie(t.textAlign, J), this.textColor = N(t.textColor), this.textNormalization = P(t.textNormalization), this.visitedColor = N(t.visitedColor), this.wordSpacing = v(t.wordSpacing), this.optimalLineLength = v(t.optimalLineLength), this.maximalLineLength = v(t.maximalLineLength), this.minimalLineLength = v(t.minimalLineLength);
|
|
7511
7508
|
}
|
|
7512
7509
|
static serialize(t) {
|
|
7513
7510
|
const { ...e } = t;
|
|
@@ -7530,7 +7527,7 @@ class Ot {
|
|
|
7530
7527
|
}
|
|
7531
7528
|
class Jr {
|
|
7532
7529
|
constructor(t) {
|
|
7533
|
-
this.backgroundColor =
|
|
7530
|
+
this.backgroundColor = N(t.backgroundColor) || null, this.blendFilter = P(t.blendFilter) ?? !1, this.constraint = v(t.constraint) || 0, this.columnCount = v(t.columnCount) || null, this.darkenFilter = pt(t.darkenFilter) ?? !1, this.deprecatedFontSize = P(t.deprecatedFontSize), (this.deprecatedFontSize === !1 || this.deprecatedFontSize === null) && (this.deprecatedFontSize = !CSS.supports("zoom", "1")), this.fontFamily = N(t.fontFamily) || null, this.fontSize = q(t.fontSize, Gt.range) || 1, this.fontSizeNormalize = P(t.fontSizeNormalize) ?? !1, this.fontOpticalSizing = P(t.fontOpticalSizing) ?? null, this.fontWeight = q(t.fontWeight, it.range) || null, this.fontWidth = q(t.fontWidth, jt.range) || null, this.hyphens = P(t.hyphens) ?? null, this.invertFilter = pt(t.invertFilter) ?? !1, this.invertGaijiFilter = pt(t.invertGaijiFilter) ?? !1, this.iOSPatch = t.iOSPatch === !1 ? !1 : (L.OS.iOS || L.OS.iPadOS) && L.iOSRequest === "mobile", this.iPadOSPatch = t.iPadOSPatch === !1 ? !1 : L.OS.iPadOS && L.iOSRequest === "desktop", this.letterSpacing = v(t.letterSpacing) || null, this.ligatures = P(t.ligatures) ?? null, this.lineHeight = v(t.lineHeight) || null, this.linkColor = N(t.linkColor) || null, this.noRuby = P(t.noRuby) ?? !1, this.pageGutter = le(v(t.pageGutter), 20), this.paragraphIndent = v(t.paragraphIndent) ?? null, this.paragraphSpacing = v(t.paragraphSpacing) ?? null, this.scroll = P(t.scroll) ?? !1, this.scrollPaddingTop = v(t.scrollPaddingTop) ?? null, this.scrollPaddingBottom = v(t.scrollPaddingBottom) ?? null, this.scrollPaddingLeft = v(t.scrollPaddingLeft) ?? null, this.scrollPaddingRight = v(t.scrollPaddingRight) ?? null, this.selectionBackgroundColor = N(t.selectionBackgroundColor) || null, this.selectionTextColor = N(t.selectionTextColor) || null, this.textAlign = ie(t.textAlign, J) || null, this.textColor = N(t.textColor) || null, this.textNormalization = P(t.textNormalization) ?? !1, this.visitedColor = N(t.visitedColor) || null, this.wordSpacing = v(t.wordSpacing) || null, this.optimalLineLength = v(t.optimalLineLength) || 65, this.maximalLineLength = le(yr(t.maximalLineLength, this.optimalLineLength), 80), this.minimalLineLength = le(fr(t.minimalLineLength, this.optimalLineLength), 40), this.experiments = Ki(t.experiments) || null;
|
|
7534
7531
|
}
|
|
7535
7532
|
}
|
|
7536
7533
|
const Qr = "#FFFFFF", ts = "#121212", es = "#0000EE", is = "#551A8B", ns = "#b4d8fe", rs = "inherit", lt = {
|
|
@@ -7683,7 +7680,7 @@ class xi {
|
|
|
7683
7680
|
return new A({
|
|
7684
7681
|
initialValue: this.preferences.hyphens,
|
|
7685
7682
|
effectiveValue: this.settings.hyphens || !1,
|
|
7686
|
-
isEffective: this.layout !== S.fixed && this.metadata?.effectiveReadingProgression ===
|
|
7683
|
+
isEffective: this.layout !== S.fixed && this.metadata?.effectiveReadingProgression === F.ltr && this.preferences.hyphens !== null,
|
|
7687
7684
|
onChange: (t) => {
|
|
7688
7685
|
this.updatePreference("hyphens", t || null);
|
|
7689
7686
|
}
|
|
@@ -9661,9 +9658,9 @@ class ln extends ji {
|
|
|
9661
9658
|
}
|
|
9662
9659
|
} else console.log("Clicked on", o);
|
|
9663
9660
|
} else {
|
|
9664
|
-
if (this._layout === S.fixed && this.framePool.doNotDisturb && (n.doNotDisturb = !0), this._layout === S.fixed && (this.currentProgression ===
|
|
9661
|
+
if (this._layout === S.fixed && this.framePool.doNotDisturb && (n.doNotDisturb = !0), this._layout === S.fixed && (this.currentProgression === F.rtl || this.currentProgression === F.ltr) && this.framePool.currentFrames.length > 1) {
|
|
9665
9662
|
const l = this.framePool.currentFrames;
|
|
9666
|
-
n.targetFrameSrc === l[this.currentProgression ===
|
|
9663
|
+
n.targetFrameSrc === l[this.currentProgression === F.rtl ? 0 : 1]?.source && (n.x += (l[this.currentProgression === F.rtl ? 1 : 0]?.iframe.contentWindow?.innerWidth ?? 0) * window.devicePixelRatio);
|
|
9667
9664
|
}
|
|
9668
9665
|
if (t === "click" ? this.listeners.click(n) : this.listeners.tap(n)) break;
|
|
9669
9666
|
const a = (this._cframes.length === 2 ? this._cframes[0].window.innerWidth + this._cframes[1].window.innerWidth : this._cframes[0].window.innerWidth) * window.devicePixelRatio / 4;
|
|
@@ -10094,7 +10091,7 @@ export {
|
|
|
10094
10091
|
Gr as FXLPeripherals,
|
|
10095
10092
|
jr as FXLSpreader,
|
|
10096
10093
|
Ct as FrameComms,
|
|
10097
|
-
|
|
10094
|
+
Fr as FrameManager,
|
|
10098
10095
|
Dr as FramePoolManager,
|
|
10099
10096
|
Wr as HorizontalThird,
|
|
10100
10097
|
tn as Injector,
|
|
@@ -10130,7 +10127,7 @@ export {
|
|
|
10130
10127
|
fr as ensureLessThanOrEqual,
|
|
10131
10128
|
yr as ensureMoreThanOrEqual,
|
|
10132
10129
|
v as ensureNonNegative,
|
|
10133
|
-
|
|
10130
|
+
N as ensureString,
|
|
10134
10131
|
q as ensureValueInRange,
|
|
10135
10132
|
Me as experiments,
|
|
10136
10133
|
ot as filterRangeConfig,
|
package/dist/index.umd.cjs
CHANGED
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
body::-webkit-scrollbar {
|
|
56
56
|
display: none; /* for Chrome, Safari, and Opera */
|
|
57
57
|
}
|
|
58
|
-
`,e.document.head.appendChild(i),this.resizeObserver=new ResizeObserver(()=>{this.resizeDebounce&&this.wnd.clearTimeout(this.resizeDebounce),this.isResizing=!0,this.resizeDebounce=this.wnd.setTimeout(()=>{this.isResizing=!1,this.resizeDebounce=null,this.reportProgress()},50)}),this.resizeObserver.observe(e.document.body),e.addEventListener("scroll",this.handleScroll,{passive:!0}),t.register("force_webkit_recalc",D.moduleName,()=>{Oi(this.wnd);const n=this.doc().scrollTop;n>1?this.doc().scrollTop=n-1:this.doc().scrollTop=n+1,this.doc().scrollTop=n}),t.register("go_progression",D.moduleName,(n,r)=>{const s=n;if(s<0||s>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*s,this.reportProgress(),T(this.wnd),r(!0)})}),t.register("go_id",D.moduleName,(n,r)=>{const s=e.document.getElementById(n);if(!s){r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=s.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),T(this.wnd),r(!0)})}),t.register("go_text",D.moduleName,(n,r)=>{let s;Array.isArray(n)&&(n.length>1&&(s=n[1]),n=n[0]);const a=re.deserialize(n),l=qe(this.wnd.document,new B({href:e.location.href,type:"text/html",text:a,locations:s?new A({otherLocations:new Map([["cssSelector",s]])}):void 0}));if(!l){r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=l.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),T(this.wnd),r(!0)})}),t.register("go_start",D.moduleName,(n,r)=>{if(this.doc().scrollTop===0)return r(!1);this.doc().scrollTop=0,this.reportProgress(),r(!0)}),t.register("go_end",D.moduleName,(n,r)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return r(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),r(!0)}),t.register("unfocus",D.moduleName,(n,r)=>{T(this.wnd),r(!0)}),t.register("scroll_protection",D.moduleName,(n,r)=>{this.enableScrollProtection(),r(!0)}),t.register(["go_next","go_prev"],D.moduleName,(n,r)=>r(!1)),t.register("focus",D.moduleName,(n,r)=>{this.reportProgress(),r(!0)}),t.register("first_visible_locator",D.moduleName,(n,r)=>{const s=Et(e,!0);this.comms.send("first_visible_locator",s.serialize()),r(!0)}),t.log("ScrollSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(D.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),e.document.getElementById(Ii)?.remove(),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("ScrollSnapper Unmounted"),!0}};D.moduleName="scroll_snapper";let Rt=D;const W=class W extends ke{constructor(){super(...arguments),this.patternAnalyzer=null,this.lastScrollTime=0,this.isScrollProtectionEnabled=!1,this.initialScrollHandled=!1,this.isScrolling=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce=null,this.handleScroll=e=>{if(this.comms.ready&&!this.isResizing){if(!this.initialScrollHandled){this.lastScrollTop=this.doc().scrollTop,this.initialScrollHandled=!0,this.reportProgress();return}this.isScrolling||(this.isScrolling=!0,this.wnd.requestAnimationFrame(()=>{this.reportProgress();const t=this.doc().scrollTop,i=t-this.lastScrollTop;if(this.lastScrollTop=t,this.isScrollProtectionEnabled&&Math.abs(i)>5){const n=Date.now(),r=n-(this.lastScrollTime||n);if(this.patternAnalyzer&&this.patternAnalyzer.analyze(i>0?"down":"up",Math.abs(i),r)){const a=e.target&&"tagName"in e.target?{tagName:e.target.tagName}:null;this.comms?.send("content_protection",{type:"suspicious_scrolling",timestamp:Date.now(),scrollDelta:i,scrollDirection:i>0?"down":"up",targetElement:a})}this.lastScrollTime=n}this.comms.send("scroll",i),this.isScrolling=!1}))}}}doc(){return this.wnd.document.scrollingElement}reportProgress(){if(!this.comms.ready)return;const e=Math.ceil(this.doc().scrollTop),t=this.doc().scrollHeight,i=this.wnd.innerHeight,n=Math.max(0,Math.min(1,e/t)),r=Math.max(0,Math.min(1,(e+i)/t));this.comms.send("progress",{start:n,end:r})}enableScrollProtection(){this.patternAnalyzer||(this.patternAnalyzer=new kt(Mi),this.isScrollProtectionEnabled=!0,this.comms?.log("Scroll protection enabled"))}mount(e,t){return this.wnd=e,this.comms=t,this.initialScrollHandled=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce&&(this.wnd.clearTimeout(this.resizeDebounce),this.resizeDebounce=null),this.resizeObserver=new ResizeObserver(()=>{this.resizeDebounce&&this.wnd.clearTimeout(this.resizeDebounce),this.isResizing=!0,this.resizeDebounce=this.wnd.setTimeout(()=>{this.isResizing=!1,this.resizeDebounce=null,this.reportProgress()},50)}),this.resizeObserver.observe(e.document.body),e.addEventListener("scroll",this.handleScroll,{passive:!0}),t.register("force_webkit_recalc",W.moduleName,()=>{Oi(this.wnd);const i=this.doc().scrollTop;i>1?this.doc().scrollTop=i-1:this.doc().scrollTop=i+1,this.doc().scrollTop=i}),t.register("go_progression",W.moduleName,(i,n)=>{const r=i;if(r<0||r>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*r,this.reportProgress(),T(this.wnd),n(!0)})}),t.register("go_id",W.moduleName,(i,n)=>{const r=e.document.getElementById(i);if(!r){n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=r.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),T(this.wnd),n(!0)})}),t.register("go_text",W.moduleName,(i,n)=>{let r;Array.isArray(i)&&(i.length>1&&(r=i[1]),i=i[0]);const s=re.deserialize(i),a=qe(this.wnd.document,new B({href:e.location.href,type:"text/html",text:s,locations:r?new A({otherLocations:new Map([["cssSelector",r]])}):void 0}));if(!a){n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=a.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),T(this.wnd),n(!0)})}),t.register("go_start",W.moduleName,(i,n)=>{if(this.doc().scrollTop===0)return n(!1);this.doc().scrollTop=0,this.reportProgress(),n(!0)}),t.register("go_end",W.moduleName,(i,n)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return n(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),n(!0)}),t.register("unfocus",W.moduleName,(i,n)=>{T(this.wnd),n(!0)}),t.register("scroll_protection",W.moduleName,(i,n)=>{this.enableScrollProtection(),n(!0)}),t.register(["go_next","go_prev"],W.moduleName,(i,n)=>n(!1)),t.register("focus",W.moduleName,(i,n)=>{this.reportProgress(),n(!0)}),t.register("first_visible_locator",W.moduleName,(i,n)=>{const r=Et(e,!0);t.send("first_visible_locator",r.serialize()),n(!0)}),t.log("WebPubSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(W.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("WebPubSnapper Unmounted"),!0}};W.moduleName="webpub_snapper";let Lt=W;class fr{constructor(e,t){this.window=e,this.copyHistory=[],this.lastSelectionLength=0,this.lastSelectionTime=0,this.options=t}cleanupOldHistory(e){this.copyHistory=this.copyHistory.filter(i=>e-i.timestamp<1e4),this.copyHistory.length>this.options.historySize&&(this.copyHistory=this.copyHistory.slice(-this.options.historySize))}isSuspiciousPattern(e){return this.copyHistory.length<3?!1:this.copyHistory.filter(n=>e-n.timestamp<2e3).length>=3?!0:this.copyHistory.slice().sort((n,r)=>n.timestamp-r.timestamp).every((n,r,s)=>r===0?!0:n.length>s[r-1].length*1.5)}shouldAllowCopy(e){if(!this.options.enabled)return!0;const t=this.window.getSelection();if(!t)return!0;const n=t.toString().length,r=this.window.document.body.innerText.length,s=Date.now();if(this.cleanupOldHistory(s),n<this.options.minThreshold)return this.copyHistory.push({timestamp:s,length:n,wasBlocked:!1}),!0;const l=s-this.lastSelectionTime<100&&n>this.lastSelectionLength*1.5,c=Math.min(r*this.options.maxSelectionPercent,this.options.absoluteMaxChars),h=this.isSuspiciousPattern(s),u=n>c||l||h;return this.copyHistory.push({timestamp:s,length:n,wasBlocked:u}),u?(e?.preventDefault(),!1):(this.lastSelectionLength=n,this.lastSelectionTime=s,!0)}destroy(){this.lastSelectionLength=0,this.lastSelectionTime=0,this.copyHistory=[],this.options.enabled=!1}}class yr{constructor(e=Ni){this.options=e,this.events=[],this.selectionStartTime=0,this.lastSelectionTime=0,this.lastSelectionPosition=0,this.selectionPatterns=[],this.lastSelectedText=""}analyze(e){if(!e)return this.clear(),!1;const t=e.toString();if(t.length===0)return this.clear(),!1;if(e.type!=="Range"||!e.rangeCount)return!1;const i=Date.now();if(t.length<=50||t===this.lastSelectedText)return!1;if(this.selectionStartTime===0)return this.selectionStartTime=i,this.lastSelectedText=t,!1;if(i-this.selectionStartTime<500)return!1;i-this.lastSelectionTime>1e3&&(this.lastSelectionTime=i),this.selectionStartTime===0&&(this.selectionStartTime=i),this.lastSelectedText=t;const r=this.analyzeSelectionPattern(e,i);return this.cleanup(i),r}analyzeSelectionPattern(e,t){if(!e.rangeCount)return!1;const i=e.getRangeAt(0),n=i.toString(),r=(t-this.selectionStartTime)/1e3;if(n.length/Math.max(1,r)>this.options.maxSelectionsPerSecond)return!0;const a=i.startOffset,l=Math.abs(a-this.lastSelectionPosition);return this.selectionPatterns.push(l),this.selectionPatterns.length>this.options.historySize&&(this.selectionPatterns.shift(),this.calculateVariance(this.selectionPatterns)<this.options.minVariance)?!0:(this.lastSelectionPosition=a,!1)}calculateVariance(e){if(e.length===0)return 0;const t=e.reduce((i,n)=>i+n,0)/e.length;return e.reduce((i,n)=>i+Math.pow(n-t,2),0)/e.length}cleanup(e){this.events=this.events.filter(t=>e-t.timestamp<=1e3)}clear(){this.events=[],this.selectionStartTime=0,this.lastSelectionTime=0,this.lastSelectionPosition=0,this.selectionPatterns=[],this.lastSelectedText=""}}class Ui{match(e,t){for(const i of t){const n=e.keyCode===i.keyCode,r=i.ctrl===void 0||e.ctrlKey===i.ctrl,s=i.shift===void 0||e.shiftKey===i.shift,a=i.alt===void 0||e.altKey===i.alt,l=i.meta===void 0||e.metaKey===i.meta;if(n&&r&&s&&a&&l)return!0}return!1}createKeyHandler(e,t){return i=>{this.match(i,e)&&(i.preventDefault(),i.stopPropagation(),t(i))}}createActivityEvent(e,t,i,n){let r;if(n){const s=n.getSelection(),a=s?.toString()||"",c=(a&&s?.rangeCount?s.getRangeAt(0)?.getClientRects():null)?.[0];c&&a&&(r={text:a,x:c.x,y:c.y,width:c.width,height:c.height})}return{type:t,timestamp:Date.now(),key:e.key,code:e.code,keyCode:e.keyCode,ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey,metaKey:e.metaKey,targetFrameSrc:i,selectedText:r}}createKeyboardHandlers(e,t,i,n){const r=[];return t.forEach(s=>{r.push(...s.keyCombos.map(a=>({...a,handler:l=>{const c=s.type,h=this.createActivityEvent(l,c,e,n);i(h)}})))}),r}createUnifiedHandler(e,t,i,n){const r=this.createKeyboardHandlers(e,t,i,n);return s=>{for(const a of r)if(this.match(s,[a])){s.preventDefault(),s.stopPropagation(),a.handler(s);return}}}}const we=class we extends ue{constructor(){super(...arguments),this.configApplied=!1,this.cleanupCallbacks=[],this.pointerMoved=!1,this.isContextMenuEnabled=!1,this.isDragAndDropEnabled=!1,this.isSelectionMonitoringEnabled=!1,this.isBulkCopyProtectionEnabled=!1,this.selectionAnalyzer=null,this.currentSelection=null,this.bulkCopyProtector=null,this.keyManager=new Ui,this.keyDownHandler=null,this.preventBulkCopy=e=>{if(!this.isBulkCopyProtectionEnabled||!this.bulkCopyProtector)return!0;if(!this.bulkCopyProtector.shouldAllowCopy(e)){e.preventDefault();const t=this.wnd.getSelection(),i=t?.toString()||"",r=(i?t?.getRangeAt(0)?.getClientRects():null)?.[0],s={type:"bulk_copy",timestamp:Date.now(),clipboardTypes:e.clipboardData?.types?[...e.clipboardData.types]:[],selectedText:r?{text:i,x:r.x,y:r.y,width:r.width,height:r.height}:void 0,selectionLength:i.length,targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",s),!1}return!0},this.handleSelection=e=>{if(!this.isSelectionMonitoringEnabled||!this.wnd||!this.selectionAnalyzer)return;const t=this.wnd.getSelection();if(t){if(this.currentSelection=t.toString(),this.selectionAnalyzer.analyze(t)&&this.currentSelection){const n=this.wnd.getSelection(),r=n?.toString()||"",a=(r&&n?.rangeCount?n.getRangeAt(0)?.getClientRects():null)?.[0],l={type:"suspicious_selection",timestamp:Date.now(),selectionLength:r.length,selectedText:{text:r,x:a?.x??0,y:a?.y??0,width:a?.width??0,height:a?.height??0},eventType:e?.type||"selectionchange",targetFrameSrc:this.wnd.location.href};this.comms?.send("content_protection",l)}}else this.currentSelection=null},this.onDragStart=e=>{if(this.isDragAndDropEnabled){e.preventDefault();const t={type:"drag_detected",timestamp:Date.now(),dataTransferTypes:e.dataTransfer?.types?[...e.dataTransfer.types]:[],targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",t),!1}else return!0},this.onDrop=e=>{if(this.isDragAndDropEnabled){e.preventDefault();const t=e.dataTransfer,i={type:"drop_detected",timestamp:Date.now(),dataTransferTypes:t?.types?[...t.types]:[],fileCount:t?.files?.length||0,targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",i),!1}else return!0},this.onContext=e=>{if(this.isContextMenuEnabled){e.preventDefault();const t=this.wnd.getSelection(),i=t?.toString()||"",r=(i&&t?.rangeCount?t.getRangeAt(0)?.getClientRects():null)?.[0],s={timestamp:Date.now(),clientX:e.clientX,clientY:e.clientY,...r&&{selectedText:{text:i,x:r.x,y:r.y,width:r.width,height:r.height}},targetFrameSrc:this.wnd.location.href};this.comms?.send("context_menu",s)}},this.onPointerUp=this.onPointUp.bind(this),this.onPointerMove=this.onPointMove.bind(this),this.onPointerDown=this.onPointDown.bind(this),this.onClicker=this.onClick.bind(this)}addContextMenuPrevention(){this.isContextMenuEnabled||!this.wnd||(this.wnd.document.addEventListener("contextmenu",this.onContext),this.isContextMenuEnabled=!0)}removeContextMenuPrevention(){!this.isContextMenuEnabled||!this.wnd||(this.wnd.document.removeEventListener("contextmenu",this.onContext),this.isContextMenuEnabled=!1)}addDragAndDropPrevention(){this.isDragAndDropEnabled||!this.wnd||(this.wnd.document.addEventListener("dragstart",this.onDragStart),this.wnd.document.addEventListener("drop",this.onDrop),this.isDragAndDropEnabled=!0)}removeDragAndDropPrevention(){!this.isDragAndDropEnabled||!this.wnd||(this.wnd.document.removeEventListener("dragstart",this.onDragStart),this.wnd.document.removeEventListener("drop",this.onDrop),this.isDragAndDropEnabled=!1)}enableKeyboardPeripherals(e=[]){this.disableKeyboardPeripherals();const t=i=>{this.comms?.send("keyboard_peripherals",i)};this.keyDownHandler=this.keyManager.createUnifiedHandler(this.wnd.location.href,e,t,this.wnd),this.wnd&&this.wnd.document.addEventListener("keydown",this.keyDownHandler,{capture:!0})}disableKeyboardPeripherals(){this.wnd&&this.keyDownHandler&&(this.wnd.document.removeEventListener("keydown",this.keyDownHandler,{capture:!0}),this.keyDownHandler=null)}addBulkCopyProtection(e={}){if(this.isBulkCopyProtectionEnabled||!this.wnd)return;const t=mr,i=e?{...t,...e}:t;this.bulkCopyProtector=new fr(this.wnd,i),this.wnd.document.addEventListener("copy",this.preventBulkCopy,!0),this.wnd.document.addEventListener("cut",this.preventBulkCopy,!0),this.isBulkCopyProtectionEnabled=!0}removeBulkCopyProtection(){!this.isBulkCopyProtectionEnabled||!this.wnd||(this.wnd.document.removeEventListener("copy",this.preventBulkCopy,!0),this.wnd.document.removeEventListener("cut",this.preventBulkCopy,!0),this.bulkCopyProtector?.destroy(),this.bulkCopyProtector=null,this.isBulkCopyProtectionEnabled=!1)}addSelectionMonitoring(e){if(this.isSelectionMonitoringEnabled||!this.wnd)return;const t=e||Ni;this.selectionAnalyzer=new yr(t),this.wnd.document.addEventListener("selectionchange",this.handleSelection),this.isSelectionMonitoringEnabled=!0}removeSelectionMonitoring(){!this.isSelectionMonitoringEnabled||!this.wnd||(this.wnd.document.removeEventListener("selectionchange",this.handleSelection),this.selectionAnalyzer?.clear(),this.selectionAnalyzer=null,this.isSelectionMonitoringEnabled=!1)}onPointUp(e){const t=this.wnd.getSelection();if(t&&t.toString()?.length>0){const n=t.getRangeAt(0)?.getClientRects();if(!n||n.length===0)return;const r=n[0],s={text:t.toString(),x:r.x,y:r.y,width:r.width,height:r.height,targetFrameSrc:this.wnd?.location?.href};this.comms.send("text_selected",s)}if(this.pointerMoved){this.pointerMoved=!1;return}if(!t?.isCollapsed||!e.isPrimary)return;const i=this.wnd.devicePixelRatio;e.preventDefault(),this.comms.send(e.pointerType==="touch"?"tap":"click",{defaultPrevented:e.defaultPrevented,x:e.clientX*i,y:e.clientY*i,targetFrameSrc:this.wnd.location.href,targetElement:e.target.outerHTML,interactiveElement:Ti(e.target)?.outerHTML,cssSelector:this.wnd._readium_cssSelectorGenerator.getCssSelector(e.target)}),this.pointerMoved=!1}onPointMove(e){if(e.movementY!==void 0&&e.movementX!==void 0){(Math.abs(e.movementX)>1||Math.abs(e.movementY)>1)&&(this.pointerMoved=!0);return}this.pointerMoved=!0}onPointDown(){this.pointerMoved=!1}onClick(e){if(e.preventDefault(),!e.isTrusted){const t=new PointerEvent("pointerup",{isPrimary:!0,pointerType:"mouse",clientX:e.clientX,clientY:e.clientY});Object.defineProperty(t,"target",{writable:!1,value:e.target}),Object.defineProperty(t,"defaultPrevented",{writable:!1,value:e.defaultPrevented}),this.onPointUp(t)}}registerProtectionHandlers(){this.comms?.register("peripherals_protection",we.moduleName,(e,t)=>{const i=e;if(!this.configApplied){if(this.configApplied=!0,i.monitorSelection){const n=typeof i.monitorSelection=="boolean"?void 0:i.monitorSelection;this.addSelectionMonitoring(n),this.comms?.log("Selection monitoring enabled")}typeof i.protectCopy=="object"?(this.addBulkCopyProtection({enabled:!0,...i.protectCopy}),this.comms?.log("Copy protection enabled (limited)")):i.protectCopy===!0&&(this.addBulkCopyProtection({enabled:!0,maxSelectionPercent:0,minThreshold:0,absoluteMaxChars:0}),this.comms?.log("Copy protection enabled")),i.disableContextMenu&&(this.addContextMenuPrevention(),this.comms?.log("Context menu protection enabled")),i.disableDragAndDrop&&(this.addDragAndDropPrevention(),this.comms?.log("Drag and drop protection enabled"))}t(!0)}),this.comms?.register("keyboard_peripherals",we.moduleName,(e,t)=>{const i=e;i&&i.length>0&&(this.enableKeyboardPeripherals(i),this.comms?.log(`Keyboard peripherals enabled: ${i.map(n=>n.type).join(", ")}`)),t(!0)})}mount(e,t){return this.wnd=e,this.comms=t,this.registerProtectionHandlers(),e.document.addEventListener("pointerdown",this.onPointerDown),e.document.addEventListener("pointerup",this.onPointerUp),e.document.addEventListener("pointermove",this.onPointerMove),e.document.addEventListener("click",this.onClicker),t.log("Peripherals Mounted"),!0}unmount(e,t){return this.removeBulkCopyProtection(),this.removeSelectionMonitoring(),this.removeContextMenuPrevention(),this.removeDragAndDropPrevention(),this.disableKeyboardPeripherals(),this.cleanupCallbacks.forEach(i=>i()),this.cleanupCallbacks=[],e.document.removeEventListener("pointerdown",this.onPointerDown),e.document.removeEventListener("pointerup",this.onPointerUp),e.document.removeEventListener("pointermove",this.onPointerMove),e.document.removeEventListener("click",this.onClicker),t.unregisterAll(we.moduleName),this.configApplied=!1,t.log("Peripherals Unmounted"),!0}};we.moduleName="peripherals";let At=we;const He=class He extends ue{constructor(){super(...arguments),this.mediaPlayingCount=0,this.allAnimations=new Set}wndOnErr(e){this.comms?.send("error",{message:e.message,filename:e.filename,lineno:e.lineno,colno:e.colno})}unblock(e){for(e._readium_blockEvents=!1;e._readium_blockedEvents?.length>0;){const t=e._readium_blockedEvents.shift();switch(t[0]){case 0:Reflect.apply(t[1],t[2],t[3]);break;case 1:const i=t[1],n=t[2];e.removeEventListener(i.type,e._readium_eventBlocker,!0);const r=new Event(i.type,{bubbles:i.bubbles,cancelable:i.cancelable});n?n.dispatchEvent(r):e.dispatchEvent(r);break}}}onMediaPlayEvent(){this.mediaPlayingCount++,this.comms?.send("media_play",this.mediaPlayingCount)}onMediaPauseEvent(){this.mediaPlayingCount>0&&this.mediaPlayingCount--,this.comms?.send("media_pause",this.mediaPlayingCount)}pauseAllMedia(e){const t=e.document.querySelectorAll("audio,video");for(let i=0;i<t.length;i++)t[i].pause()}mount(e,t){this.comms=t,e.addEventListener("error",this.wndOnErr,!1),Reflect.defineProperty(e.navigator,"epubReadingSystem",{value:{name:"readium-ts-toolkit",version:"2.4.0-alpha.7",hasFeature:(n,r="")=>{switch(n){case"dom-manipulation":return!0;case"layout-changes":return!0;case"touch-events":return!0;case"mouse-events":return!0;case"keyboard-events":return!0;case"spine-scripting":return!0;case"embedded-web-content":return!0;default:return!1}}},writable:!1}),"getAnimations"in e.document&&e.document.getAnimations().forEach(n=>{n.cancel(),this.allAnimations.add(n)}),t.register("activate",He.moduleName,(n,r)=>{this.allAnimations.forEach(s=>{s.cancel(),s.play()}),r(!0)}),t.register("unfocus",He.moduleName,(n,r)=>{this.pauseAllMedia(e),this.allAnimations.forEach(s=>s.pause()),r(!0)});const i=e.document.querySelectorAll("audio,video");for(let n=0;n<i.length;n++){const r=i[n];r.addEventListener("play",this.onMediaPlayEvent,{passive:!0}),r.addEventListener("pause",this.onMediaPauseEvent,{passive:!0})}return t.log("Setup Mounted"),!0}unmount(e,t){return e.removeEventListener("error",this.wndOnErr),e.removeEventListener("play",this.onMediaPlayEvent),e.removeEventListener("pause",this.onMediaPauseEvent),this.allAnimations.forEach(i=>i.cancel()),this.allAnimations.clear(),t.log("Setup Unmounted"),!0}};He.moduleName="setup";let Qe=He;const Di="readium-viewport",Q=class Q extends Qe{onViewportWidthChanged(e){const t=e.target;Ce(t,"--RS__viewportWidth",`${t.innerWidth}px`)}mount(e,t){if(!super.mount(e,t))return!1;const i=e.document.createElement("meta");return i.dataset.readium="true",i.setAttribute("name","viewport"),i.setAttribute("id",Di),i.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"),e.document.head.appendChild(i),e.addEventListener("orientationchange",this.onViewportWidthChanged),e.addEventListener("resize",this.onViewportWidthChanged),this.onViewportWidthChanged({target:e}),t.register("get_properties",Q.moduleName,(n,r)=>{bt(e),r(!0)}),t.register("update_properties",Q.moduleName,(n,r)=>{n["--RS__viewportWidth"]=`${e.innerWidth}px`,wi(e,n),r(!0)}),t.register("set_property",Q.moduleName,(n,r)=>{const s=n;Ce(e,s[0],s[1]),r(!0)}),t.register("remove_property",Q.moduleName,(n,r)=>{Ke(e,n),r(!0)}),t.register("activate",Q.moduleName,(n,r)=>{this.unblock(e),r(!0)}),t.log("ReflowableSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(Q.moduleName),e.document.head.querySelector(`#${Di}`)?.remove(),e.removeEventListener("orientationchange",this.onViewportWidthChanged),t.log("ReflowableSetup Unmounted"),super.unmount(e,t)}};Q.moduleName="reflowable_setup";let Ot=Q;const Wi="readium-fixed-style",J=class J extends Qe{mount(e,t){if(!super.mount(e,t))return!1;e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="paginated");const i=e.document.createElement("style");return i.id=Wi,i.dataset.readium="true",i.textContent=`
|
|
58
|
+
`,e.document.head.appendChild(i),this.resizeObserver=new ResizeObserver(()=>{this.resizeDebounce&&this.wnd.clearTimeout(this.resizeDebounce),this.isResizing=!0,this.resizeDebounce=this.wnd.setTimeout(()=>{this.isResizing=!1,this.resizeDebounce=null,this.reportProgress()},50)}),this.resizeObserver.observe(e.document.body),e.addEventListener("scroll",this.handleScroll,{passive:!0}),t.register("force_webkit_recalc",D.moduleName,()=>{Oi(this.wnd);const n=this.doc().scrollTop;n>1?this.doc().scrollTop=n-1:this.doc().scrollTop=n+1,this.doc().scrollTop=n}),t.register("go_progression",D.moduleName,(n,r)=>{const s=n;if(s<0||s>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*s,this.reportProgress(),T(this.wnd),r(!0)})}),t.register("go_id",D.moduleName,(n,r)=>{const s=e.document.getElementById(n);if(!s){r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=s.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),T(this.wnd),r(!0)})}),t.register("go_text",D.moduleName,(n,r)=>{let s;Array.isArray(n)&&(n.length>1&&(s=n[1]),n=n[0]);const a=re.deserialize(n),l=qe(this.wnd.document,new B({href:e.location.href,type:"text/html",text:a,locations:s?new A({otherLocations:new Map([["cssSelector",s]])}):void 0}));if(!l){r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=l.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),T(this.wnd),r(!0)})}),t.register("go_start",D.moduleName,(n,r)=>{if(this.doc().scrollTop===0)return r(!1);this.doc().scrollTop=0,this.reportProgress(),r(!0)}),t.register("go_end",D.moduleName,(n,r)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return r(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),r(!0)}),t.register("unfocus",D.moduleName,(n,r)=>{T(this.wnd),r(!0)}),t.register("scroll_protection",D.moduleName,(n,r)=>{this.enableScrollProtection(),r(!0)}),t.register(["go_next","go_prev"],D.moduleName,(n,r)=>r(!1)),t.register("focus",D.moduleName,(n,r)=>{this.reportProgress(),r(!0)}),t.register("first_visible_locator",D.moduleName,(n,r)=>{const s=Et(e,!0);this.comms.send("first_visible_locator",s.serialize()),r(!0)}),t.log("ScrollSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(D.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),e.document.getElementById(Ii)?.remove(),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("ScrollSnapper Unmounted"),!0}};D.moduleName="scroll_snapper";let Rt=D;const W=class W extends ke{constructor(){super(...arguments),this.patternAnalyzer=null,this.lastScrollTime=0,this.isScrollProtectionEnabled=!1,this.initialScrollHandled=!1,this.isScrolling=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce=null,this.handleScroll=e=>{if(this.comms.ready&&!this.isResizing){if(!this.initialScrollHandled){this.lastScrollTop=this.doc().scrollTop,this.initialScrollHandled=!0,this.reportProgress();return}this.isScrolling||(this.isScrolling=!0,this.wnd.requestAnimationFrame(()=>{this.reportProgress();const t=this.doc().scrollTop,i=t-this.lastScrollTop;if(this.lastScrollTop=t,this.isScrollProtectionEnabled&&Math.abs(i)>5){const n=Date.now(),r=n-(this.lastScrollTime||n);if(this.patternAnalyzer&&this.patternAnalyzer.analyze(i>0?"down":"up",Math.abs(i),r)){const a=e.target&&"tagName"in e.target?{tagName:e.target.tagName}:null;this.comms?.send("content_protection",{type:"suspicious_scrolling",timestamp:Date.now(),scrollDelta:i,scrollDirection:i>0?"down":"up",targetElement:a})}this.lastScrollTime=n}this.comms.send("scroll",i),this.isScrolling=!1}))}}}doc(){return this.wnd.document.scrollingElement}reportProgress(){if(!this.comms.ready)return;const e=Math.ceil(this.doc().scrollTop),t=this.doc().scrollHeight,i=this.wnd.innerHeight,n=Math.max(0,Math.min(1,e/t)),r=Math.max(0,Math.min(1,(e+i)/t));this.comms.send("progress",{start:n,end:r})}enableScrollProtection(){this.patternAnalyzer||(this.patternAnalyzer=new kt(Mi),this.isScrollProtectionEnabled=!0,this.comms?.log("Scroll protection enabled"))}mount(e,t){return this.wnd=e,this.comms=t,this.initialScrollHandled=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce&&(this.wnd.clearTimeout(this.resizeDebounce),this.resizeDebounce=null),this.resizeObserver=new ResizeObserver(()=>{this.resizeDebounce&&this.wnd.clearTimeout(this.resizeDebounce),this.isResizing=!0,this.resizeDebounce=this.wnd.setTimeout(()=>{this.isResizing=!1,this.resizeDebounce=null,this.reportProgress()},50)}),this.resizeObserver.observe(e.document.body),e.addEventListener("scroll",this.handleScroll,{passive:!0}),t.register("force_webkit_recalc",W.moduleName,()=>{Oi(this.wnd);const i=this.doc().scrollTop;i>1?this.doc().scrollTop=i-1:this.doc().scrollTop=i+1,this.doc().scrollTop=i}),t.register("go_progression",W.moduleName,(i,n)=>{const r=i;if(r<0||r>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*r,this.reportProgress(),T(this.wnd),n(!0)})}),t.register("go_id",W.moduleName,(i,n)=>{const r=e.document.getElementById(i);if(!r){n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=r.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),T(this.wnd),n(!0)})}),t.register("go_text",W.moduleName,(i,n)=>{let r;Array.isArray(i)&&(i.length>1&&(r=i[1]),i=i[0]);const s=re.deserialize(i),a=qe(this.wnd.document,new B({href:e.location.href,type:"text/html",text:s,locations:r?new A({otherLocations:new Map([["cssSelector",r]])}):void 0}));if(!a){n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=a.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),T(this.wnd),n(!0)})}),t.register("go_start",W.moduleName,(i,n)=>{if(this.doc().scrollTop===0)return n(!1);this.doc().scrollTop=0,this.reportProgress(),n(!0)}),t.register("go_end",W.moduleName,(i,n)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return n(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),n(!0)}),t.register("unfocus",W.moduleName,(i,n)=>{T(this.wnd),n(!0)}),t.register("scroll_protection",W.moduleName,(i,n)=>{this.enableScrollProtection(),n(!0)}),t.register(["go_next","go_prev"],W.moduleName,(i,n)=>n(!1)),t.register("focus",W.moduleName,(i,n)=>{this.reportProgress(),n(!0)}),t.register("first_visible_locator",W.moduleName,(i,n)=>{const r=Et(e,!0);t.send("first_visible_locator",r.serialize()),n(!0)}),t.log("WebPubSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(W.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("WebPubSnapper Unmounted"),!0}};W.moduleName="webpub_snapper";let Lt=W;class fr{constructor(e,t){this.window=e,this.copyHistory=[],this.lastSelectionLength=0,this.lastSelectionTime=0,this.options=t}cleanupOldHistory(e){this.copyHistory=this.copyHistory.filter(i=>e-i.timestamp<1e4),this.copyHistory.length>this.options.historySize&&(this.copyHistory=this.copyHistory.slice(-this.options.historySize))}isSuspiciousPattern(e){return this.copyHistory.length<3?!1:this.copyHistory.filter(n=>e-n.timestamp<2e3).length>=3?!0:this.copyHistory.slice().sort((n,r)=>n.timestamp-r.timestamp).every((n,r,s)=>r===0?!0:n.length>s[r-1].length*1.5)}shouldAllowCopy(e){if(!this.options.enabled)return!0;const t=this.window.getSelection();if(!t)return!0;const n=t.toString().length,r=this.window.document.body.innerText.length,s=Date.now();if(this.cleanupOldHistory(s),n<this.options.minThreshold)return this.copyHistory.push({timestamp:s,length:n,wasBlocked:!1}),!0;const l=s-this.lastSelectionTime<100&&n>this.lastSelectionLength*1.5,c=Math.min(r*this.options.maxSelectionPercent,this.options.absoluteMaxChars),h=this.isSuspiciousPattern(s),u=n>c||l||h;return this.copyHistory.push({timestamp:s,length:n,wasBlocked:u}),u?(e?.preventDefault(),!1):(this.lastSelectionLength=n,this.lastSelectionTime=s,!0)}destroy(){this.lastSelectionLength=0,this.lastSelectionTime=0,this.copyHistory=[],this.options.enabled=!1}}class yr{constructor(e=Ni){this.options=e,this.events=[],this.selectionStartTime=0,this.lastSelectionTime=0,this.lastSelectionPosition=0,this.selectionPatterns=[],this.lastSelectedText=""}analyze(e){if(!e)return this.clear(),!1;const t=e.toString();if(t.length===0)return this.clear(),!1;if(e.type!=="Range"||!e.rangeCount)return!1;const i=Date.now();if(t.length<=50||t===this.lastSelectedText)return!1;if(this.selectionStartTime===0)return this.selectionStartTime=i,this.lastSelectedText=t,!1;if(i-this.selectionStartTime<500)return!1;i-this.lastSelectionTime>1e3&&(this.lastSelectionTime=i),this.selectionStartTime===0&&(this.selectionStartTime=i),this.lastSelectedText=t;const r=this.analyzeSelectionPattern(e,i);return this.cleanup(i),r}analyzeSelectionPattern(e,t){if(!e.rangeCount)return!1;const i=e.getRangeAt(0),n=i.toString(),r=(t-this.selectionStartTime)/1e3;if(n.length/Math.max(1,r)>this.options.maxSelectionsPerSecond)return!0;const a=i.startOffset,l=Math.abs(a-this.lastSelectionPosition);return this.selectionPatterns.push(l),this.selectionPatterns.length>this.options.historySize&&(this.selectionPatterns.shift(),this.calculateVariance(this.selectionPatterns)<this.options.minVariance)?!0:(this.lastSelectionPosition=a,!1)}calculateVariance(e){if(e.length===0)return 0;const t=e.reduce((i,n)=>i+n,0)/e.length;return e.reduce((i,n)=>i+Math.pow(n-t,2),0)/e.length}cleanup(e){this.events=this.events.filter(t=>e-t.timestamp<=1e3)}clear(){this.events=[],this.selectionStartTime=0,this.lastSelectionTime=0,this.lastSelectionPosition=0,this.selectionPatterns=[],this.lastSelectedText=""}}class Ui{match(e,t){for(const i of t){const n=e.keyCode===i.keyCode,r=i.ctrl===void 0||e.ctrlKey===i.ctrl,s=i.shift===void 0||e.shiftKey===i.shift,a=i.alt===void 0||e.altKey===i.alt,l=i.meta===void 0||e.metaKey===i.meta;if(n&&r&&s&&a&&l)return!0}return!1}createKeyHandler(e,t){return i=>{this.match(i,e)&&(i.preventDefault(),i.stopPropagation(),t(i))}}createActivityEvent(e,t,i,n){let r;if(n){const s=n.getSelection(),a=s?.toString()||"",c=(a&&s?.rangeCount?s.getRangeAt(0)?.getClientRects():null)?.[0];c&&a&&(r={text:a,x:c.x,y:c.y,width:c.width,height:c.height})}return{type:t,timestamp:Date.now(),key:e.key,code:e.code,keyCode:e.keyCode,ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey,metaKey:e.metaKey,targetFrameSrc:i,selectedText:r}}createKeyboardHandlers(e,t,i,n){const r=[];return t.forEach(s=>{r.push(...s.keyCombos.map(a=>({...a,handler:l=>{const c=s.type,h=this.createActivityEvent(l,c,e,n);i(h)}})))}),r}createUnifiedHandler(e,t,i,n){const r=this.createKeyboardHandlers(e,t,i,n);return s=>{for(const a of r)if(this.match(s,[a])){s.preventDefault(),s.stopPropagation(),a.handler(s);return}}}}const we=class we extends ue{constructor(){super(...arguments),this.configApplied=!1,this.cleanupCallbacks=[],this.pointerMoved=!1,this.isContextMenuEnabled=!1,this.isDragAndDropEnabled=!1,this.isSelectionMonitoringEnabled=!1,this.isBulkCopyProtectionEnabled=!1,this.selectionAnalyzer=null,this.currentSelection=null,this.bulkCopyProtector=null,this.keyManager=new Ui,this.keyDownHandler=null,this.preventBulkCopy=e=>{if(!this.isBulkCopyProtectionEnabled||!this.bulkCopyProtector)return!0;if(!this.bulkCopyProtector.shouldAllowCopy(e)){e.preventDefault();const t=this.wnd.getSelection(),i=t?.toString()||"",r=(i?t?.getRangeAt(0)?.getClientRects():null)?.[0],s={type:"bulk_copy",timestamp:Date.now(),clipboardTypes:e.clipboardData?.types?[...e.clipboardData.types]:[],selectedText:r?{text:i,x:r.x,y:r.y,width:r.width,height:r.height}:void 0,selectionLength:i.length,targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",s),!1}return!0},this.handleSelection=e=>{if(!this.isSelectionMonitoringEnabled||!this.wnd||!this.selectionAnalyzer)return;const t=this.wnd.getSelection();if(t){if(this.currentSelection=t.toString(),this.selectionAnalyzer.analyze(t)&&this.currentSelection){const n=this.wnd.getSelection(),r=n?.toString()||"",a=(r&&n?.rangeCount?n.getRangeAt(0)?.getClientRects():null)?.[0],l={type:"suspicious_selection",timestamp:Date.now(),selectionLength:r.length,selectedText:{text:r,x:a?.x??0,y:a?.y??0,width:a?.width??0,height:a?.height??0},eventType:e?.type||"selectionchange",targetFrameSrc:this.wnd.location.href};this.comms?.send("content_protection",l)}}else this.currentSelection=null},this.onDragStart=e=>{if(this.isDragAndDropEnabled){e.preventDefault();const t={type:"drag_detected",timestamp:Date.now(),dataTransferTypes:e.dataTransfer?.types?[...e.dataTransfer.types]:[],targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",t),!1}else return!0},this.onDrop=e=>{if(this.isDragAndDropEnabled){e.preventDefault();const t=e.dataTransfer,i={type:"drop_detected",timestamp:Date.now(),dataTransferTypes:t?.types?[...t.types]:[],fileCount:t?.files?.length||0,targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",i),!1}else return!0},this.onContext=e=>{if(this.isContextMenuEnabled){e.preventDefault();const t=this.wnd.getSelection(),i=t?.toString()||"",r=(i&&t?.rangeCount?t.getRangeAt(0)?.getClientRects():null)?.[0],s={timestamp:Date.now(),clientX:e.clientX,clientY:e.clientY,...r&&{selectedText:{text:i,x:r.x,y:r.y,width:r.width,height:r.height}},targetFrameSrc:this.wnd.location.href};this.comms?.send("context_menu",s)}},this.onPointerUp=this.onPointUp.bind(this),this.onPointerMove=this.onPointMove.bind(this),this.onPointerDown=this.onPointDown.bind(this),this.onClicker=this.onClick.bind(this)}addContextMenuPrevention(){this.isContextMenuEnabled||!this.wnd||(this.wnd.document.addEventListener("contextmenu",this.onContext),this.isContextMenuEnabled=!0)}removeContextMenuPrevention(){!this.isContextMenuEnabled||!this.wnd||(this.wnd.document.removeEventListener("contextmenu",this.onContext),this.isContextMenuEnabled=!1)}addDragAndDropPrevention(){this.isDragAndDropEnabled||!this.wnd||(this.wnd.document.addEventListener("dragstart",this.onDragStart),this.wnd.document.addEventListener("drop",this.onDrop),this.isDragAndDropEnabled=!0)}removeDragAndDropPrevention(){!this.isDragAndDropEnabled||!this.wnd||(this.wnd.document.removeEventListener("dragstart",this.onDragStart),this.wnd.document.removeEventListener("drop",this.onDrop),this.isDragAndDropEnabled=!1)}enableKeyboardPeripherals(e=[]){this.disableKeyboardPeripherals();const t=i=>{this.comms?.send("keyboard_peripherals",i)};this.keyDownHandler=this.keyManager.createUnifiedHandler(this.wnd.location.href,e,t,this.wnd),this.wnd&&this.wnd.document.addEventListener("keydown",this.keyDownHandler,{capture:!0})}disableKeyboardPeripherals(){this.wnd&&this.keyDownHandler&&(this.wnd.document.removeEventListener("keydown",this.keyDownHandler,{capture:!0}),this.keyDownHandler=null)}addBulkCopyProtection(e={}){if(this.isBulkCopyProtectionEnabled||!this.wnd)return;const t=mr,i=e?{...t,...e}:t;this.bulkCopyProtector=new fr(this.wnd,i),this.wnd.document.addEventListener("copy",this.preventBulkCopy,!0),this.wnd.document.addEventListener("cut",this.preventBulkCopy,!0),this.isBulkCopyProtectionEnabled=!0}removeBulkCopyProtection(){!this.isBulkCopyProtectionEnabled||!this.wnd||(this.wnd.document.removeEventListener("copy",this.preventBulkCopy,!0),this.wnd.document.removeEventListener("cut",this.preventBulkCopy,!0),this.bulkCopyProtector?.destroy(),this.bulkCopyProtector=null,this.isBulkCopyProtectionEnabled=!1)}addSelectionMonitoring(e){if(this.isSelectionMonitoringEnabled||!this.wnd)return;const t=e||Ni;this.selectionAnalyzer=new yr(t),this.wnd.document.addEventListener("selectionchange",this.handleSelection),this.isSelectionMonitoringEnabled=!0}removeSelectionMonitoring(){!this.isSelectionMonitoringEnabled||!this.wnd||(this.wnd.document.removeEventListener("selectionchange",this.handleSelection),this.selectionAnalyzer?.clear(),this.selectionAnalyzer=null,this.isSelectionMonitoringEnabled=!1)}onPointUp(e){const t=this.wnd.getSelection();if(t&&t.toString()?.length>0){const n=t.getRangeAt(0)?.getClientRects();if(!n||n.length===0)return;const r=n[0],s={text:t.toString(),x:r.x,y:r.y,width:r.width,height:r.height,targetFrameSrc:this.wnd?.location?.href};this.comms.send("text_selected",s)}if(this.pointerMoved){this.pointerMoved=!1;return}if(!t?.isCollapsed||!e.isPrimary)return;const i=this.wnd.devicePixelRatio;e.preventDefault(),this.comms.send(e.pointerType==="touch"?"tap":"click",{defaultPrevented:e.defaultPrevented,x:e.clientX*i,y:e.clientY*i,targetFrameSrc:this.wnd.location.href,targetElement:e.target.outerHTML,interactiveElement:Ti(e.target)?.outerHTML,cssSelector:this.wnd._readium_cssSelectorGenerator.getCssSelector(e.target)}),this.pointerMoved=!1}onPointMove(e){if(e.movementY!==void 0&&e.movementX!==void 0){(Math.abs(e.movementX)>1||Math.abs(e.movementY)>1)&&(this.pointerMoved=!0);return}this.pointerMoved=!0}onPointDown(){this.pointerMoved=!1}onClick(e){if(e.preventDefault(),!e.isTrusted){const t=new PointerEvent("pointerup",{isPrimary:!0,pointerType:"mouse",clientX:e.clientX,clientY:e.clientY});Object.defineProperty(t,"target",{writable:!1,value:e.target}),Object.defineProperty(t,"defaultPrevented",{writable:!1,value:e.defaultPrevented}),this.onPointUp(t)}}registerProtectionHandlers(){this.comms?.register("peripherals_protection",we.moduleName,(e,t)=>{const i=e;if(!this.configApplied){if(this.configApplied=!0,i.monitorSelection){const n=typeof i.monitorSelection=="boolean"?void 0:i.monitorSelection;this.addSelectionMonitoring(n),this.comms?.log("Selection monitoring enabled")}typeof i.protectCopy=="object"?(this.addBulkCopyProtection({enabled:!0,...i.protectCopy}),this.comms?.log("Copy protection enabled (limited)")):i.protectCopy===!0&&(this.addBulkCopyProtection({enabled:!0,maxSelectionPercent:0,minThreshold:0,absoluteMaxChars:0}),this.comms?.log("Copy protection enabled")),i.disableContextMenu&&(this.addContextMenuPrevention(),this.comms?.log("Context menu protection enabled")),i.disableDragAndDrop&&(this.addDragAndDropPrevention(),this.comms?.log("Drag and drop protection enabled"))}t(!0)}),this.comms?.register("keyboard_peripherals",we.moduleName,(e,t)=>{const i=e;i&&i.length>0&&(this.enableKeyboardPeripherals(i),this.comms?.log(`Keyboard peripherals enabled: ${i.map(n=>n.type).join(", ")}`)),t(!0)})}mount(e,t){return this.wnd=e,this.comms=t,this.registerProtectionHandlers(),e.document.addEventListener("pointerdown",this.onPointerDown),e.document.addEventListener("pointerup",this.onPointerUp),e.document.addEventListener("pointermove",this.onPointerMove),e.document.addEventListener("click",this.onClicker),t.log("Peripherals Mounted"),!0}unmount(e,t){return this.removeBulkCopyProtection(),this.removeSelectionMonitoring(),this.removeContextMenuPrevention(),this.removeDragAndDropPrevention(),this.disableKeyboardPeripherals(),this.cleanupCallbacks.forEach(i=>i()),this.cleanupCallbacks=[],e.document.removeEventListener("pointerdown",this.onPointerDown),e.document.removeEventListener("pointerup",this.onPointerUp),e.document.removeEventListener("pointermove",this.onPointerMove),e.document.removeEventListener("click",this.onClicker),t.unregisterAll(we.moduleName),this.configApplied=!1,t.log("Peripherals Unmounted"),!0}};we.moduleName="peripherals";let At=we;const He=class He extends ue{constructor(){super(...arguments),this.mediaPlayingCount=0,this.allAnimations=new Set}wndOnErr(e){this.comms?.send("error",{message:e.message,filename:e.filename,lineno:e.lineno,colno:e.colno})}unblock(e){for(e._readium_blockEvents=!1;e._readium_blockedEvents?.length>0;){const t=e._readium_blockedEvents.shift();switch(t[0]){case 0:Reflect.apply(t[1],t[2],t[3]);break;case 1:const i=t[1],n=t[2];e.removeEventListener(i.type,e._readium_eventBlocker,!0);const r=new Event(i.type,{bubbles:i.bubbles,cancelable:i.cancelable});n?n.dispatchEvent(r):e.dispatchEvent(r);break}}}onMediaPlayEvent(){this.mediaPlayingCount++,this.comms?.send("media_play",this.mediaPlayingCount)}onMediaPauseEvent(){this.mediaPlayingCount>0&&this.mediaPlayingCount--,this.comms?.send("media_pause",this.mediaPlayingCount)}pauseAllMedia(e){const t=e.document.querySelectorAll("audio,video");for(let i=0;i<t.length;i++)t[i].pause()}mount(e,t){this.comms=t,e.addEventListener("error",this.wndOnErr,!1),Reflect.defineProperty(e.navigator,"epubReadingSystem",{value:{name:"readium-ts-toolkit",version:"2.4.0-alpha.8",hasFeature:(n,r="")=>{switch(n){case"dom-manipulation":return!0;case"layout-changes":return!0;case"touch-events":return!0;case"mouse-events":return!0;case"keyboard-events":return!0;case"spine-scripting":return!0;case"embedded-web-content":return!0;default:return!1}}},writable:!1}),"getAnimations"in e.document&&e.document.getAnimations().forEach(n=>{n.cancel(),this.allAnimations.add(n)}),t.register("activate",He.moduleName,(n,r)=>{this.allAnimations.forEach(s=>{s.cancel(),s.play()}),r(!0)}),t.register("unfocus",He.moduleName,(n,r)=>{this.pauseAllMedia(e),this.allAnimations.forEach(s=>s.pause()),r(!0)});const i=e.document.querySelectorAll("audio,video");for(let n=0;n<i.length;n++){const r=i[n];r.addEventListener("play",this.onMediaPlayEvent,{passive:!0}),r.addEventListener("pause",this.onMediaPauseEvent,{passive:!0})}return t.log("Setup Mounted"),!0}unmount(e,t){return e.removeEventListener("error",this.wndOnErr),e.removeEventListener("play",this.onMediaPlayEvent),e.removeEventListener("pause",this.onMediaPauseEvent),this.allAnimations.forEach(i=>i.cancel()),this.allAnimations.clear(),t.log("Setup Unmounted"),!0}};He.moduleName="setup";let Qe=He;const Di="readium-viewport",Q=class Q extends Qe{onViewportWidthChanged(e){const t=e.target;Ce(t,"--RS__viewportWidth",`${t.innerWidth}px`)}mount(e,t){if(!super.mount(e,t))return!1;const i=e.document.createElement("meta");return i.dataset.readium="true",i.setAttribute("name","viewport"),i.setAttribute("id",Di),i.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"),e.document.head.appendChild(i),e.addEventListener("orientationchange",this.onViewportWidthChanged),e.addEventListener("resize",this.onViewportWidthChanged),this.onViewportWidthChanged({target:e}),t.register("get_properties",Q.moduleName,(n,r)=>{bt(e),r(!0)}),t.register("update_properties",Q.moduleName,(n,r)=>{n["--RS__viewportWidth"]=`${e.innerWidth}px`,wi(e,n),r(!0)}),t.register("set_property",Q.moduleName,(n,r)=>{const s=n;Ce(e,s[0],s[1]),r(!0)}),t.register("remove_property",Q.moduleName,(n,r)=>{Ke(e,n),r(!0)}),t.register("activate",Q.moduleName,(n,r)=>{this.unblock(e),r(!0)}),t.log("ReflowableSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(Q.moduleName),e.document.head.querySelector(`#${Di}`)?.remove(),e.removeEventListener("orientationchange",this.onViewportWidthChanged),t.log("ReflowableSetup Unmounted"),super.unmount(e,t)}};Q.moduleName="reflowable_setup";let Ot=Q;const Wi="readium-fixed-style",J=class J extends Qe{mount(e,t){if(!super.mount(e,t))return!1;e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="paginated");const i=e.document.createElement("style");return i.id=Wi,i.dataset.readium="true",i.textContent=`
|
|
59
59
|
html, body {
|
|
60
60
|
text-size-adjust: none;
|
|
61
61
|
-ms-text-size-adjust: none;
|
|
@@ -398,9 +398,9 @@ onmessage = function(event) {
|
|
|
398
398
|
transform: translateY(-50%);
|
|
399
399
|
}
|
|
400
400
|
}
|
|
401
|
-
`,document.head.appendChild(t),this.styleElement=t,this.beforePrintHandler=i=>(i.preventDefault(),this.onPrintAttempt?.(),!1),window.addEventListener("beforeprint",this.beforePrintHandler)}destroy(){this.beforePrintHandler&&(window.removeEventListener("beforeprint",this.beforePrintHandler),this.beforePrintHandler=null),this.styleElement?.parentNode&&(this.styleElement.parentNode.removeChild(this.styleElement),this.styleElement=null)}}class Gr{constructor(e={}){this.onContextMenuBlocked=e.onContextMenuBlocked,this.contextMenuHandler=this.handleContextMenu.bind(this),document.addEventListener("contextmenu",this.contextMenuHandler,!0),window.addEventListener("unload",()=>this.destroy())}handleContextMenu(e){e.preventDefault(),e.stopPropagation();const t={type:"context_menu",timestamp:Date.now(),clientX:e.clientX,clientY:e.clientY,targetFrameSrc:""};return this.onContextMenuBlocked&&this.onContextMenuBlocked(t),!1}destroy(){this.contextMenuHandler&&(document.removeEventListener("contextmenu",this.contextMenuHandler,!0),this.contextMenuHandler=void 0)}}const Ie="readium:navigator:suspiciousActivity";class cn{dispatchSuspiciousActivity(e,t){const i=new CustomEvent(Ie,{detail:{type:e,timestamp:Date.now(),...t}});window.dispatchEvent(i)}constructor(e={}){e.monitorDevTools&&(this.devToolsDetector=new Br({onDetected:()=>{this.dispatchSuspiciousActivity("developer_tools",{targetFrameSrc:"",key:"",code:"",keyCode:-1,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1})}})),e.checkAutomation&&(this.automationDetector=new Nr({onDetected:t=>{this.dispatchSuspiciousActivity("automation_detected",{tool:t})}})),e.checkIFrameEmbedding&&(this.iframeEmbeddingDetector=new Vr({onDetected:t=>{this.dispatchSuspiciousActivity("iframe_embedding_detected",{isCrossOrigin:t})}})),e.protectPrinting?.disable&&(this.printProtector=new jr({...e.protectPrinting,onPrintAttempt:()=>{this.dispatchSuspiciousActivity("print",{})}})),e.disableContextMenu&&(this.contextMenuProtector=new Gr({onContextMenuBlocked:t=>{this.dispatchSuspiciousActivity("context_menu",t)}}))}destroy(){this.automationDetector?.destroy(),this.devToolsDetector?.destroy(),this.iframeEmbeddingDetector?.destroy(),this.printProtector?.destroy(),this.contextMenuProtector?.destroy()}}const Ue="readium:navigator:keyboardPeripheral";class hn{constructor(e={}){this.keyManager=new Ui,this.setupKeyboardPeripherals(e.keyboardPeripherals||[])}setupKeyboardPeripherals(e){if(e.length>0){const t=i=>{const n=new CustomEvent(Ue,{detail:i});window.dispatchEvent(n)};this.keydownHandler=this.keyManager.createUnifiedHandler("",e,t),this.keydownHandler&&document.addEventListener("keydown",this.keydownHandler,!0)}window.addEventListener("unload",()=>this.destroy())}destroy(){this.keydownHandler&&(document.removeEventListener("keydown",this.keydownHandler,!0),this.keydownHandler=void 0)}}const Xr=o=>({frameLoaded:o.frameLoaded||(()=>{}),positionChanged:o.positionChanged||(()=>{}),tap:o.tap||(()=>!1),click:o.click||(()=>!1),zoom:o.zoom||(()=>{}),scroll:o.scroll||(()=>{}),customEvent:o.customEvent||(()=>{}),handleLocator:o.handleLocator||(()=>!1),textSelected:o.textSelected||(()=>{}),contentProtection:o.contentProtection||(()=>{}),contextMenu:o.contextMenu||(()=>{}),peripheral:o.peripheral||(()=>{})});class dn extends Mt{constructor(e,t,i,n=void 0,r={preferences:{},defaults:{}}){super(),this.currentIndex=0,this._preferencesEditor=null,this._injector=null,this._navigatorProtector=null,this._keyboardPeripheralsManager=null,this._suspiciousActivityListener=null,this._keyboardPeripheralListener=null,this.webViewport={readingOrder:[],progressions:new Map,positions:null},this.pub=t,this.container=e,this.listeners=Xr(i),this._preferences=new be(r.preferences),this._defaults=new en(r.defaults),this._settings=new Ut(this._preferences,this._defaults,this.hasDisplayTransformability),this._css=new Ji({rsProperties:new Ki({experiments:this._settings.experiments||null}),userProperties:new Ft({zoom:this._settings.zoom})});const s=Mr(t.readingOrder.items),a=r.injectables||{rules:[],allowedDomains:[]};if(this._injector=new Ht({rules:[...s,...a.rules],allowedDomains:a.allowedDomains}),this._contentProtection=r.contentProtection||{},this._keyboardPeripherals=this.mergeKeyboardPeripherals(this._contentProtection,r.keyboardPeripherals||[]),(this._contentProtection.disableContextMenu||this._contentProtection.checkAutomation||this._contentProtection.checkIFrameEmbedding||this._contentProtection.monitorDevTools||this._contentProtection.protectPrinting?.disable)&&(this._navigatorProtector=new cn(this._contentProtection),this._suspiciousActivityListener=l=>{const c=l;this.listeners.contentProtection(c.detail.type,c.detail)},window.addEventListener(Ie,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new hn({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=l=>{const c=l.detail;this.listeners.peripheral(c)},window.addEventListener(Ue,this._keyboardPeripheralListener)),n&&typeof n.copyWithLocations=="function"){this.currentLocation=n;const l=this.pub.readingOrder.findIndexWithHref(n.href);l>=0&&(this.currentIndex=l)}else this.currentLocation=this.createCurrentLocator()}async load(){await this.updateCSS(!1);const e=this.compileCSSProperties(this._css);this.framePool=new qi(this.container,e,this._injector,this._contentProtection,this._keyboardPeripherals),await this.apply()}get settings(){return Object.freeze({...this._settings})}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new Wt(this._preferences,this.settings,this.pub.metadata)),this._preferencesEditor}async submitPreferences(e){this._preferences=this._preferences.merging(e),await this.applyPreferences()}async applyPreferences(){this._settings=new Ut(this._preferences,this._defaults,this.hasDisplayTransformability),this._preferencesEditor!==null&&(this._preferencesEditor=new Wt(this._preferences,this.settings,this.pub.metadata)),await this.updateCSS(!0)}async updateCSS(e){this._css.update(this._settings),e&&await this.commitCSS(this._css)}compileCSSProperties(e){const t={};for(const[i,n]of Object.entries(e.rsProperties.toCSSProperties()))t[i]=n;for(const[i,n]of Object.entries(e.userProperties.toCSSProperties()))t[i]=n;return t}async commitCSS(e){const t=this.compileCSSProperties(e);this.framePool.setCSSProperties(t)}get _cframes(){return this.framePool.currentFrames}get hasDisplayTransformability(){return this.pub.metadata?.accessibility?.feature?.some(e=>e.value===Be.DISPLAY_TRANSFORMABILITY.value)??!1}eventListener(e,t){switch(e){case"_pong":this.listeners.frameLoaded(this.framePool.currentFrames[0].iframe.contentWindow),this.listeners.positionChanged(this.currentLocation);break;case"first_visible_locator":const i=B.deserialize(t);if(!i)break;this.currentLocation=new B({href:this.currentLocation.href,type:this.currentLocation.type,title:this.currentLocation.title,locations:i?.locations,text:i?.text}),this.listeners.positionChanged(this.currentLocation);break;case"text_selected":this.listeners.textSelected(t);break;case"click":case"tap":const n=t;if(n.interactiveElement){const s=new DOMParser().parseFromString(n.interactiveElement,"text/html").body.children[0];if(s.nodeType===s.ELEMENT_NODE&&s.nodeName==="A"&&s.hasAttribute("href")){const a=s.attributes.getNamedItem("href")?.value;if(a.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[a.substring(1)]}),!1,()=>{});else if(a.startsWith("mailto:")||a.startsWith("tel:"))this.listeners.handleLocator(new V({href:a}).locator);else try{let l;if(a.startsWith("http://")||a.startsWith("https://"))l=a;else if(this.currentLocation.href.startsWith("http://")||this.currentLocation.href.startsWith("https://")){const h=new URL(this.currentLocation.href);l=new URL(a,h).href}else l=tt.join(tt.dirname(this.currentLocation.href),a);const c=this.pub.readingOrder.findWithHref(l);c?this.goLink(c,!1,()=>{}):(console.warn(`Internal link not found in readingOrder: ${l}`),this.listeners.handleLocator(new V({href:a}).locator))}catch(l){console.warn(`Couldn't resolve internal link for ${a}: ${l}`),this.listeners.handleLocator(new V({href:a}).locator)}}else console.log("Clicked on",s)}else if(e==="click"?this.listeners.click(n):this.listeners.tap(n))break;break;case"scroll":this.listeners.scroll(t);break;case"zoom":this.listeners.zoom(t);break;case"progress":this.syncLocation(t);break;case"content_protection":const r=t;this.listeners.contentProtection(r.type,r);break;case"context_menu":this.listeners.contextMenu(t);break;case"keyboard_peripherals":this.listeners.peripheral(t);break;case"log":console.log(this.framePool.currentFrames[0]?.source?.split("/")[3],...t);break;default:this.listeners.customEvent(e,t);break}}determineModules(){return Array.from(et.keys()).filter(t=>_r.includes(t))}attachListener(){this.framePool.currentFrames[0]?.msg&&(this.framePool.currentFrames[0].msg.listener=(e,t)=>{this.eventListener(e,t)})}async apply(){if(await this.framePool.update(this.pub,this.currentLocation,this.determineModules()),this.attachListener(),this.pub.readingOrder.findIndexWithHref(this.currentLocation.href)<0)throw Error("Link for "+this.currentLocation.href+" not found!")}async destroy(){this._suspiciousActivityListener&&window.removeEventListener(Ie,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(Ue,this._keyboardPeripheralListener),this._navigatorProtector?.destroy(),this._keyboardPeripheralsManager?.destroy(),await this.framePool?.destroy()}async changeResource(e){if(e===0)return!1;const t=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),i=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,t+e));return i===t?!1:(this.currentIndex=i,this.currentLocation=this.createCurrentLocator(),await this.apply(),!0)}updateViewport(e){this.webViewport.readingOrder=[],this.webViewport.progressions.clear(),this.webViewport.positions=null,this.currentLocation&&(this.webViewport.readingOrder.push(this.currentLocation.href),this.webViewport.progressions.set(this.currentLocation.href,e),this.currentLocation.locations?.position!==void 0&&(this.webViewport.positions=[this.currentLocation.locations.position]))}async syncLocation(e){const t=e;this.currentLocation&&(this.currentLocation=this.currentLocation.copyWithLocations({progression:t.start})),this.updateViewport(t),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(e,t){this.changeResource(-1).then(i=>{t(i)})}goForward(e,t){this.changeResource(1).then(i=>{t(i)})}get currentLocator(){return this.currentLocation}get viewport(){return this.webViewport}get isScrollStart(){const e=this.viewport.readingOrder[0];return this.viewport.progressions.get(e)?.start===0}get isScrollEnd(){const e=this.viewport.readingOrder[this.viewport.readingOrder.length-1];return this.viewport.progressions.get(e)?.end===1}get canGoBackward(){const e=this.pub.readingOrder.items[0]?.href;return!(this.viewport.progressions.has(e)&&this.viewport.progressions.get(e)?.start===0)}get canGoForward(){const e=this.pub.readingOrder.items[this.pub.readingOrder.items.length-1]?.href;return!(this.viewport.progressions.has(e)&&this.viewport.progressions.get(e)?.end===1)}get readingProgression(){return this.pub.metadata.effectiveReadingProgression}get publication(){return this.pub}async loadLocator(e,t){let i=!1,n=typeof e.locations.getCssSelector=="function"&&e.locations.getCssSelector();if(e.text?.highlight?i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_text",n?[e.text?.serialize(),n]:e.text?.serialize(),h=>l(h))}):n&&(i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_text",["",n],h=>l(h))})),i){t(i);return}const r=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(r&&(i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_id",r,h=>l(h))})),i){t(i);return}const s=e?.locations?.progression;s&&s>0?i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_progression",s,h=>l(h))}):i=!0,t(i)}go(e,t,i){const n=e.href.split("#")[0];if(!this.pub.readingOrder.findWithHref(n))return i(this.listeners.handleLocator(e));const s=this.pub.readingOrder.findIndexWithHref(n);s>=0&&(this.currentIndex=s),this.currentLocation=this.createCurrentLocator(),this.apply().then(()=>this.loadLocator(e,a=>i(a))).then(()=>{this.attachListener()})}goLink(e,t,i){return this.go(e.locator,t,i)}createCurrentLocator(){const t=this.pub.readingOrder.items[this.currentIndex];if(!t)throw new Error("No current resource available");const n=this.currentLocation&&this.currentLocation.href===t.href&&this.currentLocation.locations.progression?this.currentLocation.locations.progression:0;return this.pub.manifest.locatorFromLink(t)||new B({href:t.href,type:t.type||"text/html",locations:new A({fragments:[],progression:n,position:this.currentIndex+1})})}}const $r=dn,qr=o=>{const e=o.join(" ");return["upgrade-insecure-requests",`default-src ${e} blob:`,"connect-src 'none'",`script-src ${e} blob: 'unsafe-inline'`,`style-src ${e} blob: 'unsafe-inline'`,`img-src ${e} blob: data:`,`font-src ${e} blob: data:`,`object-src ${e} blob:`,`child-src ${e}`,"form-action 'none'"].join("; ")};class un{constructor(e,t,i,n){this.pub=e,this.baseURL=t,this.item=i,this.injector=null,this.item=i,this.cssProperties=n.cssProperties,this.injector=n.injector??null}reset(){this.currentUrl&&URL.revokeObjectURL(this.currentUrl),this.currentUrl=void 0,this.currentResource?.close(),this.currentResource=void 0}async build(e=!1){if(this.currentUrl)return this.currentUrl;this.currentResource=this.pub.get(this.item);const t=await this.currentResource.link();if(!this.currentResource)return"about:blank";if(t.mediaType.isHTML){const i=await this.buildHtmlFrame(e);return this.currentUrl=i,i}else if(t.mediaType.isBitmap||t.mediaType.equals(g.SVG)){const i=await this.buildImageFrame();return this.currentUrl=i,i}else throw Error("Unsupported frame mediatype "+t.mediaType.string)}async buildHtmlFrame(e=!1){if(!this.currentResource)throw new Error("No resource loaded");const t=await this.currentResource.link(),i=await this.currentResource.readAsString();if(!i)throw new Error(`Failed reading item ${t.href}`);const n=new DOMParser().parseFromString(i,t.mediaType.string),r=n.querySelector("parsererror");if(r){const s=r.querySelector("div");throw new Error(`Failed parsing item ${t.href}: ${s?.textContent||r.textContent}`)}return this.injector&&await this.injector.injectForDocument(n,t),this.finalizeDOM(n,this.pub.baseURL,t.toURL(this.baseURL)||"",t.mediaType,e,this.cssProperties)}async buildImageFrame(){if(!this.currentResource)throw new Error("No resource loaded");const e=await this.currentResource.link(),t=e.toURL(this.baseURL)||"",i=document.implementation.createHTMLDocument(e.title||e.href);if((e?.height||0)>0&&(e?.width||0)>0){const s=i.createElement("meta");s.name="viewport",s.content=`width=${e.width}, height=${e.height}`,s.dataset.readium="true",i.head.appendChild(s)}const n=document.createElement("img");n.src=t||"",n.alt=e.title||"",n.decoding="async",i.body.appendChild(n),this.injector&&await this.injector.injectForDocument(i,new V({href:"readium-image-frame.xhtml",type:g.XHTML.string}));const r=i.createElement("style");return r.dataset.readium="true",r.textContent=`
|
|
401
|
+
`,document.head.appendChild(t),this.styleElement=t,this.beforePrintHandler=i=>(i.preventDefault(),this.onPrintAttempt?.(),!1),window.addEventListener("beforeprint",this.beforePrintHandler)}destroy(){this.beforePrintHandler&&(window.removeEventListener("beforeprint",this.beforePrintHandler),this.beforePrintHandler=null),this.styleElement?.parentNode&&(this.styleElement.parentNode.removeChild(this.styleElement),this.styleElement=null)}}class Gr{constructor(e={}){this.onContextMenuBlocked=e.onContextMenuBlocked,this.contextMenuHandler=this.handleContextMenu.bind(this),document.addEventListener("contextmenu",this.contextMenuHandler,!0),window.addEventListener("unload",()=>this.destroy())}handleContextMenu(e){e.preventDefault(),e.stopPropagation();const t={type:"context_menu",timestamp:Date.now(),clientX:e.clientX,clientY:e.clientY,targetFrameSrc:""};return this.onContextMenuBlocked&&this.onContextMenuBlocked(t),!1}destroy(){this.contextMenuHandler&&(document.removeEventListener("contextmenu",this.contextMenuHandler,!0),this.contextMenuHandler=void 0)}}const Ie="readium:navigator:suspiciousActivity";class cn{dispatchSuspiciousActivity(e,t){const i=new CustomEvent(Ie,{detail:{type:e,timestamp:Date.now(),...t}});window.dispatchEvent(i)}constructor(e={}){e.monitorDevTools&&(this.devToolsDetector=new Br({onDetected:()=>{this.dispatchSuspiciousActivity("developer_tools",{targetFrameSrc:"",key:"",code:"",keyCode:-1,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1})}})),e.checkAutomation&&(this.automationDetector=new Nr({onDetected:t=>{this.dispatchSuspiciousActivity("automation_detected",{tool:t})}})),e.checkIFrameEmbedding&&(this.iframeEmbeddingDetector=new Vr({onDetected:t=>{this.dispatchSuspiciousActivity("iframe_embedding_detected",{isCrossOrigin:t})}})),e.protectPrinting?.disable&&(this.printProtector=new jr({...e.protectPrinting,onPrintAttempt:()=>{this.dispatchSuspiciousActivity("print",{})}})),e.disableContextMenu&&(this.contextMenuProtector=new Gr({onContextMenuBlocked:t=>{this.dispatchSuspiciousActivity("context_menu",t)}}))}destroy(){this.automationDetector?.destroy(),this.devToolsDetector?.destroy(),this.iframeEmbeddingDetector?.destroy(),this.printProtector?.destroy(),this.contextMenuProtector?.destroy()}}const Ue="readium:navigator:keyboardPeripheral";class hn{constructor(e={}){this.keyManager=new Ui,this.setupKeyboardPeripherals(e.keyboardPeripherals||[])}setupKeyboardPeripherals(e){if(e.length>0){const t=i=>{const n=new CustomEvent(Ue,{detail:i});window.dispatchEvent(n)};this.keydownHandler=this.keyManager.createUnifiedHandler("",e,t),this.keydownHandler&&document.addEventListener("keydown",this.keydownHandler,!0)}window.addEventListener("unload",()=>this.destroy())}destroy(){this.keydownHandler&&(document.removeEventListener("keydown",this.keydownHandler,!0),this.keydownHandler=void 0)}}const Xr=o=>({frameLoaded:o.frameLoaded||(()=>{}),positionChanged:o.positionChanged||(()=>{}),tap:o.tap||(()=>!1),click:o.click||(()=>!1),zoom:o.zoom||(()=>{}),scroll:o.scroll||(()=>{}),customEvent:o.customEvent||(()=>{}),handleLocator:o.handleLocator||(()=>!1),textSelected:o.textSelected||(()=>{}),contentProtection:o.contentProtection||(()=>{}),contextMenu:o.contextMenu||(()=>{}),peripheral:o.peripheral||(()=>{})});class dn extends Mt{constructor(e,t,i,n=void 0,r={preferences:{},defaults:{}}){super(),this.currentIndex=0,this._preferencesEditor=null,this._injector=null,this._navigatorProtector=null,this._keyboardPeripheralsManager=null,this._suspiciousActivityListener=null,this._keyboardPeripheralListener=null,this.webViewport={readingOrder:[],progressions:new Map,positions:null},this.pub=t,this.container=e,this.listeners=Xr(i),this._preferences=new be(r.preferences),this._defaults=new en(r.defaults),this._settings=new Ut(this._preferences,this._defaults,this.hasDisplayTransformability),this._css=new Ji({rsProperties:new Ki({experiments:this._settings.experiments||null}),userProperties:new Ft({zoom:this._settings.zoom})});const s=Mr(t.readingOrder.items),a=r.injectables||{rules:[],allowedDomains:[]};if(this._injector=new Ht({rules:[...s,...a.rules],allowedDomains:a.allowedDomains}),this._contentProtection=r.contentProtection||{},this._keyboardPeripherals=this.mergeKeyboardPeripherals(this._contentProtection,r.keyboardPeripherals||[]),(this._contentProtection.disableContextMenu||this._contentProtection.checkAutomation||this._contentProtection.checkIFrameEmbedding||this._contentProtection.monitorDevTools||this._contentProtection.protectPrinting?.disable)&&(this._navigatorProtector=new cn(this._contentProtection),this._suspiciousActivityListener=l=>{const c=l;this.listeners.contentProtection(c.detail.type,c.detail)},window.addEventListener(Ie,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new hn({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=l=>{const c=l.detail;this.listeners.peripheral(c)},window.addEventListener(Ue,this._keyboardPeripheralListener)),n&&typeof n.copyWithLocations=="function"){this.currentLocation=n;const l=this.pub.readingOrder.findIndexWithHref(n.href);l>=0&&(this.currentIndex=l)}else this.currentLocation=this.createCurrentLocator()}async load(){await this.updateCSS(!1);const e=this.compileCSSProperties(this._css);this.framePool=new qi(this.container,e,this._injector,this._contentProtection,this._keyboardPeripherals),await this.apply()}get settings(){return Object.freeze({...this._settings})}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new Wt(this._preferences,this.settings,this.pub.metadata)),this._preferencesEditor}async submitPreferences(e){this._preferences=this._preferences.merging(e),await this.applyPreferences()}async applyPreferences(){this._settings=new Ut(this._preferences,this._defaults,this.hasDisplayTransformability),this._preferencesEditor!==null&&(this._preferencesEditor=new Wt(this._preferences,this.settings,this.pub.metadata)),await this.updateCSS(!0)}async updateCSS(e){this._css.update(this._settings),e&&await this.commitCSS(this._css)}compileCSSProperties(e){const t={};for(const[i,n]of Object.entries(e.rsProperties.toCSSProperties()))t[i]=n;for(const[i,n]of Object.entries(e.userProperties.toCSSProperties()))t[i]=n;return t}async commitCSS(e){const t=this.compileCSSProperties(e);this.framePool.setCSSProperties(t)}get _cframes(){return this.framePool.currentFrames}get hasDisplayTransformability(){return this.pub.metadata?.accessibility?.feature?.some(e=>e.value===Be.DISPLAY_TRANSFORMABILITY.value)??!1}eventListener(e,t){switch(e){case"_pong":this.listeners.frameLoaded(this.framePool.currentFrames[0].iframe.contentWindow),this.listeners.positionChanged(this.currentLocation);break;case"first_visible_locator":const i=B.deserialize(t);if(!i)break;this.currentLocation=new B({href:this.currentLocation.href,type:this.currentLocation.type,title:this.currentLocation.title,locations:i?.locations,text:i?.text}),this.listeners.positionChanged(this.currentLocation);break;case"text_selected":this.listeners.textSelected(t);break;case"click":case"tap":const n=t;if(n.interactiveElement){const s=new DOMParser().parseFromString(n.interactiveElement,"text/html").body.children[0];if(s.nodeType===s.ELEMENT_NODE&&s.nodeName==="A"&&s.hasAttribute("href")){const a=s.attributes.getNamedItem("href")?.value;if(a.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[a.substring(1)]}),!1,()=>{});else if(a.startsWith("mailto:")||a.startsWith("tel:"))this.listeners.handleLocator(new V({href:a}).locator);else try{let l;if(a.startsWith("http://")||a.startsWith("https://"))l=a;else if(this.currentLocation.href.startsWith("http://")||this.currentLocation.href.startsWith("https://")){const h=new URL(this.currentLocation.href);l=new URL(a,h).href}else l=tt.join(tt.dirname(this.currentLocation.href),a);const c=this.pub.readingOrder.findWithHref(l);c?this.goLink(c,!1,()=>{}):(console.warn(`Internal link not found in readingOrder: ${l}`),this.listeners.handleLocator(new V({href:a}).locator))}catch(l){console.warn(`Couldn't resolve internal link for ${a}: ${l}`),this.listeners.handleLocator(new V({href:a}).locator)}}else console.log("Clicked on",s)}else if(e==="click"?this.listeners.click(n):this.listeners.tap(n))break;break;case"scroll":this.listeners.scroll(t);break;case"zoom":this.listeners.zoom(t);break;case"progress":this.syncLocation(t);break;case"content_protection":const r=t;this.listeners.contentProtection(r.type,r);break;case"context_menu":this.listeners.contextMenu(t);break;case"keyboard_peripherals":this.listeners.peripheral(t);break;case"log":console.log(this.framePool.currentFrames[0]?.source?.split("/")[3],...t);break;default:this.listeners.customEvent(e,t);break}}determineModules(){return Array.from(et.keys()).filter(t=>_r.includes(t))}attachListener(){this.framePool.currentFrames[0]?.msg&&(this.framePool.currentFrames[0].msg.listener=(e,t)=>{this.eventListener(e,t)})}async apply(){if(await this.framePool.update(this.pub,this.currentLocation,this.determineModules()),this.attachListener(),this.pub.readingOrder.findIndexWithHref(this.currentLocation.href)<0)throw Error("Link for "+this.currentLocation.href+" not found!")}async destroy(){this._suspiciousActivityListener&&window.removeEventListener(Ie,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(Ue,this._keyboardPeripheralListener),this._navigatorProtector?.destroy(),this._keyboardPeripheralsManager?.destroy(),await this.framePool?.destroy()}async changeResource(e){if(e===0)return!1;const t=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),i=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,t+e));return i===t?!1:(this.currentIndex=i,this.currentLocation=this.createCurrentLocator(),await this.apply(),!0)}updateViewport(e){this.webViewport.readingOrder=[],this.webViewport.progressions.clear(),this.webViewport.positions=null,this.currentLocation&&(this.webViewport.readingOrder.push(this.currentLocation.href),this.webViewport.progressions.set(this.currentLocation.href,e),this.currentLocation.locations?.position!==void 0&&(this.webViewport.positions=[this.currentLocation.locations.position]))}async syncLocation(e){const t=e;this.currentLocation&&(this.currentLocation=this.currentLocation.copyWithLocations({progression:t.start})),this.updateViewport(t),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(e,t){this.changeResource(-1).then(i=>{t(i)})}goForward(e,t){this.changeResource(1).then(i=>{t(i)})}get currentLocator(){return this.currentLocation}get viewport(){return this.webViewport}get isScrollStart(){const e=this.viewport.readingOrder[0];return this.viewport.progressions.get(e)?.start===0}get isScrollEnd(){const e=this.viewport.readingOrder[this.viewport.readingOrder.length-1];return this.viewport.progressions.get(e)?.end===1}get canGoBackward(){const e=this.pub.readingOrder.items[0]?.href;return!(this.viewport.progressions.has(e)&&this.viewport.progressions.get(e)?.start===0)}get canGoForward(){const e=this.pub.readingOrder.items[this.pub.readingOrder.items.length-1]?.href;return!(this.viewport.progressions.has(e)&&this.viewport.progressions.get(e)?.end===1)}get readingProgression(){return this.pub.metadata.effectiveReadingProgression}get publication(){return this.pub}async loadLocator(e,t){let i=!1,n=typeof e.locations.getCssSelector=="function"&&e.locations.getCssSelector();if(e.text?.highlight?i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_text",n?[e.text?.serialize(),n]:e.text?.serialize(),h=>l(h))}):n&&(i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_text",["",n],h=>l(h))})),i){t(i);return}const r=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(r&&(i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_id",r,h=>l(h))})),i){t(i);return}const s=e?.locations?.progression;s&&s>0?i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_progression",s,h=>l(h))}):i=!0,t(i)}go(e,t,i){const n=e.href.split("#")[0];if(!this.pub.readingOrder.findWithHref(n))return i(this.listeners.handleLocator(e));const s=this.pub.readingOrder.findIndexWithHref(n);s>=0&&(this.currentIndex=s),this.currentLocation=this.createCurrentLocator(),this.apply().then(()=>this.loadLocator(e,a=>i(a))).then(()=>{this.attachListener()})}goLink(e,t,i){return this.go(e.locator,t,i)}createCurrentLocator(){const t=this.pub.readingOrder.items[this.currentIndex];if(!t)throw new Error("No current resource available");const n=this.currentLocation&&this.currentLocation.href===t.href&&this.currentLocation.locations.progression?this.currentLocation.locations.progression:0;return this.pub.manifest.locatorFromLink(t)||new B({href:t.href,type:t.type||"text/html",locations:new A({fragments:[],progression:n,position:this.currentIndex+1})})}}const $r=dn,qr=o=>{const e=o.join(" ");return["upgrade-insecure-requests",`default-src ${e} blob:`,"connect-src 'none'",`script-src ${e} blob: 'unsafe-inline'`,`style-src ${e} blob: 'unsafe-inline'`,`img-src ${e} blob: data:`,`font-src ${e} blob: data:`,`object-src ${e} blob:`,`child-src ${e}`,"form-action 'none'"].join("; ")};class un{constructor(e,t,i,n){this.pub=e,this.baseURL=t,this.item=i,this.injector=null,this.item=i,this.cssProperties=n.cssProperties,this.injector=n.injector??null}reset(){this.currentUrl&&URL.revokeObjectURL(this.currentUrl),this.currentUrl=void 0,this.currentResource?.close(),this.currentResource=void 0}async build(e=!1){if(this.currentUrl)return this.currentUrl;this.currentResource=this.pub.get(this.item);const t=await this.currentResource.link();if(!this.currentResource)return"about:blank";if(t.mediaType.isHTML){const i=await this.buildHtmlFrame(e);return this.currentUrl=i,i}else if(t.mediaType.isBitmap||t.mediaType.equals(g.SVG)){const i=await this.buildImageFrame();return this.currentUrl=i,i}else throw Error("Unsupported frame mediatype "+t.mediaType.string)}async buildHtmlFrame(e=!1){if(!this.currentResource)throw new Error("No resource loaded");const t=await this.currentResource.link(),i=await this.currentResource.readAsXML();if(!i)throw new Error(`Failed reading item ${t.href}`);const n=i.querySelector("parsererror");if(n){const r=n.querySelector("div");throw new Error(`Failed parsing item ${t.href}: ${r?.textContent||n.textContent}`)}return this.injector&&await this.injector.injectForDocument(i,t),this.finalizeDOM(i,this.pub.baseURL,t.toURL(this.baseURL)||"",t.mediaType,e,this.cssProperties)}async buildImageFrame(){if(!this.currentResource)throw new Error("No resource loaded");const e=await this.currentResource.link(),t=e.toURL(this.baseURL)||"",i=document.implementation.createHTMLDocument(e.title||e.href);if((e?.height||0)>0&&(e?.width||0)>0){const s=i.createElement("meta");s.name="viewport",s.content=`width=${e.width}, height=${e.height}`,s.dataset.readium="true",i.head.appendChild(s)}const n=document.createElement("img");n.src=t||"",n.alt=e.title||"",n.decoding="async",i.body.appendChild(n),this.injector&&await this.injector.injectForDocument(i,new V({href:"readium-image-frame.xhtml",type:g.XHTML.string}));const r=i.createElement("style");return r.dataset.readium="true",r.textContent=`
|
|
402
402
|
html, body { width: 100%; height: 100%; margin: 0; padding: 0; font-size: 0; }
|
|
403
|
-
img { margin: 0; padding: 0; border: 0; }`,i.head.appendChild(r),this.finalizeDOM(i,this.pub.baseURL,t,e.mediaType,!0)}setProperties(e,t){for(const i in e){const n=e[i];n&&t.documentElement.style.setProperty(i,n)}}finalizeDOM(e,t,i,n,r=!1,s){if(!e)return"";const a=this.injector?.getAllowedDomains?.()||[];t=t?.split("?")[0];const l=[...new Set([...t?[t]:[],...a])].filter(Boolean);if(s&&!r&&this.setProperties(s,e),e.body.querySelectorAll("img").forEach(h=>{h.setAttribute("fetchpriority","high"),h.setAttribute("referrerpolicy","origin")}),n.isHTML&&this.pub.metadata.languages?.[0]){const h=this.pub.metadata.languages[0];if(n===g.XHTML){const u=document.documentElement.lang||document.documentElement.getAttribute("xml:lang"),m=document.body.lang||document.body.getAttribute("xml:lang");m&&!u?(document.documentElement.lang=m,document.documentElement.setAttribute("xml:lang",m),document.body.removeAttribute("xml:lang"),document.body.removeAttribute("lang")):u||(document.documentElement.lang=h,document.documentElement.setAttribute("xml:lang",h))}else n===g.HTML&&!document.documentElement.lang&&(document.documentElement.lang=h)}if(i!==void 0){const h=e.createElement("base");h.href=i,h.dataset.readium="true",e.head.firstChild.before(h)}const c=e.createElement("meta");return c.httpEquiv="Content-Security-Policy",c.content=qr(l),c.dataset.readium="true",e.head.firstChild.before(c),URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(e)],{type:n.isHTML?n.string:"application/xhtml+xml"}))}}class pn{constructor(e,t={},i=[]){this.hidden=!0,this.destroyed=!1,this.currModules=[],this.frame=document.createElement("iframe"),this.frame.sandbox.value="allow-same-origin allow-scripts",this.frame.classList.add("readium-navigator-iframe"),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transition="visibility 0s, opacity 0.1s linear",this.source=e,this.contentProtectionConfig={...t},this.keyboardPeripheralsConfig=[...i]}async load(e){return new Promise((t,i)=>{if(this.loader){const n=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{t(n)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new ge(n,e),this.currModules=e,this.comms=void 0;try{t(n)}catch{}return}this.frame.onload=()=>{const n=this.frame.contentWindow;this.loader=new ge(n,e),this.currModules=e;try{t(n)}catch{}},this.frame.onerror=n=>{try{i(n)}catch{}},this.frame.contentWindow.location.replace(this.source)})}applyContentProtection(){this.comms||this.comms.resume(),this.comms.send("peripherals_protection",this.contentProtectionConfig),this.keyboardPeripheralsConfig&&this.keyboardPeripheralsConfig.length>0&&this.comms.send("keyboard_peripherals",this.keyboardPeripheralsConfig),this.contentProtectionConfig.monitorScrollingExperimental&&this.comms.send("scroll_protection",{}),this.contentProtectionConfig.protectPrinting&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async destroy(){await this.hide(),this.loader?.destroy(),this.frame.remove(),this.destroyed=!0}async hide(){if(!this.destroyed){if(this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.pointerEvents="none",this.hidden=!0,this.frame.parentElement)return this.comms===void 0||!this.comms.ready?void 0:new Promise((e,t)=>{this.comms?.send("unfocus",void 0,i=>{this.comms?.halt(),e()})});this.comms?.halt()}}async show(e){if(this.destroyed)throw Error("Trying to show frame when it doesn't exist");if(!this.frame.parentElement)throw Error("Trying to show frame that is not attached to the DOM");return this.comms?this.comms.resume():this.comms=new fe(this.frame.contentWindow,this.source),new Promise((t,i)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{this.applyContentProtection();const n=()=>{this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("opacity"),this.frame.style.removeProperty("pointer-events"),this.hidden=!1,$.UA.WebKit&&this.comms?.send("force_webkit_recalc",void 0),t()};e!==void 0?this.comms?.send("go_progression",e,n):n()})})})}setCSSProperties(e){this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?this.comms?.resume():this.comms=new fe(this.frame.contentWindow,this.source)),this.comms?.send("update_properties",e),this.hidden&&this.comms?.halt())}get iframe(){if(this.destroyed)throw Error("Trying to use frame when it doesn't exist");return this.frame}get realSize(){if(this.destroyed)throw Error("Trying to use frame client rect when it doesn't exist");return this.frame.getBoundingClientRect()}get window(){if(this.destroyed||!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get atLeft(){return this.window.scrollX<5}get atRight(){return this.window.scrollX>this.window.document.scrollingElement.scrollWidth-this.window.innerWidth-5}get msg(){return this.comms}get ldr(){return this.loader}}const mn=5,gn=3;class fn{constructor(e,t,i,n,r,s){this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.pendingUpdates=new Map,this.injector=null,this.container=e,this.positions=t,this.currentCssProperties=i,this.injector=n??null,this.contentProtectionConfig=r||{},this.keyboardPeripheralsConfig=s||[]}async destroy(){let e=this.inprogress.values(),t=e.next();const i=[];for(;t.value;)i.push(t.value),t=e.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let n=this.pool.values(),r=n.next();for(;r.value;)await r.value.destroy(),r=n.next();this.pool.clear(),this.blobs.forEach(s=>s.reset()),this.blobs.clear(),this.injector?.dispose(),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}async update(e,t,i,n=!1){let r=this.positions.findIndex(l=>l.locations.position===t.locations.position);if(r<0)throw Error(`Locator not found in position list: ${t.locations.position} > ${this.positions.reduce((l,c)=>c.locations.position||0>l?c.locations.position||0:l,0)}`);const s=this.positions[r].href;this.inprogress.has(s)&&await this.inprogress.get(s);const a=new Promise(async(l,c)=>{const h=[],u=[];this.positions.forEach((d,p)=>{(p>r+mn||p<r-mn)&&(h.includes(d.href)||h.push(d.href)),p<r+gn&&p>r-gn&&(u.includes(d.href)||u.push(d.href))}),h.forEach(async d=>{u.includes(d)||this.pool.has(d)&&(await this.pool.get(d)?.destroy(),this.pool.delete(d),this.pendingUpdates.has(d)&&this.pendingUpdates.set(d,{inPool:!1}))}),this.currentBaseURL!==void 0&&e.baseURL!==this.currentBaseURL&&(this.blobs.forEach(d=>d.reset()),this.blobs.clear()),this.currentBaseURL=e.baseURL;const m=async d=>{if(n&&(this.blobs.forEach(P=>P.reset()),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(d)&&this.pendingUpdates.get(d)?.inPool===!1){const P=this.blobs.get(d);P&&(P.reset(),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const P=this.pool.get(d);if(!this.blobs.has(d))await P.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await P.load(i);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;this.blobs.has(d)||this.blobs.set(d,new un(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}));const S=new pn(await this.blobs.get(d).build(),this.contentProtectionConfig,this.keyboardPeripheralsConfig);d!==s&&await S.hide(),this.container.appendChild(S.iframe),await S.load(i),this.pool.set(d,S)};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const b=this.pool.get(s);(b?.source!==this._currentFrame?.source||n)&&(await this._currentFrame?.hide(),b&&await b.load(i),b&&await b.show(t.locations.progression),this._currentFrame=b),l()});this.inprogress.set(s,a),await a,this.inprogress.delete(s)}setCSSProperties(e){if(!((i,n)=>{const r=Object.keys(i),s=Object.keys(n);if(r.length!==s.length)return!1;for(const a of r)if(i[a]!==n[a])return!1;return!0})(this.currentCssProperties||{},e)){this.currentCssProperties=e,this.pool.forEach(i=>{i.setCSSProperties(e)});for(const i of this.blobs.keys())this.pendingUpdates.set(i,{inPool:this.pool.has(i)})}}get currentFrames(){return[this._currentFrame]}get currentBounds(){const e={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(t=>{if(!t)return;const i=t.realSize;e.x=Math.min(e.x,i.x),e.y=Math.min(e.y,i.y),e.width+=i.width,e.height=Math.max(e.height,i.height),e.top=Math.min(e.top,i.top),e.right=Math.min(e.right,i.right),e.bottom=Math.min(e.bottom,i.bottom),e.left=Math.min(e.left,i.left)}),e}}class yn{constructor(e,t,i,n={},r=[]){this.frameIsAppended=!1,this.currModules=[],this.pageSize=void 0,this.cachedPage=void 0,this.peripherals=e,this.debugHref=i,this.contentProtectionConfig={...n},this.keyboardPeripheralsConfig=[...r],this.frame=document.createElement("iframe"),this.frame.sandbox.value="allow-same-origin allow-scripts",this.frame.classList.add("readium-navigator-iframe"),this.frame.classList.add("blank"),this.frame.scrolling="no",this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.display="none",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transformOrigin="0 0",this.frame.style.transform="scale(1)",this.frame.style.background="#fff",this.frame.style.touchAction="none",this.frame.dataset.originalHref=i,this.source="about:blank",this.wrapper=document.createElement("div"),this.wrapper.style.position="relative",this.wrapper.style.float=this.wrapper.style.cssFloat=t===N.rtl?"right":"left"}async load(e,t){return this.frameIsAppended||(this.wrapper.appendChild(this.frame),this.frameIsAppended=!0),this.source===t&&this.loadPromise&&[...this.currModules].sort().join("|")===[...e].sort().join("|")?this.loadPromise:(this.loaded&&this.source!==t&&this.window.stop(),this.source=t,this.loadPromise=new Promise((i,n)=>{if(this.loader&&this.loaded){const r=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{i(r),this.loadPromise=void 0}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new ge(r,e),this.currModules=e,this.comms=void 0;try{i(r),this.loadPromise=void 0}catch{}return}this.frame.addEventListener("load",()=>{const r=this.frame.contentWindow;this.loader=new ge(r,e),this.currModules=e,this.peripherals.observe(this.wrapper),this.peripherals.observe(r);try{i(r)}catch{}},{once:!0}),this.frame.addEventListener("error",r=>{try{n(r.error),this.loadPromise=void 0}catch{}},{once:!0}),this.frame.style.removeProperty("display"),this.frame.contentWindow.location.replace(this.source)}),this.loadPromise)}loadPageSize(){if(this.pageSize)return this.pageSize;const e=this.frame.contentWindow,t=e.document.head.querySelector("meta[name=viewport]");if(t){const i=/(\w+) *= *([^\s,]+)/g;let n,r=0,s=0;for(;n=i.exec(t.content);)n[1]==="width"?r=Number.parseFloat(n[2]):n[1]==="height"&&(s=Number.parseFloat(n[2]));if(r>0&&s>0)return{width:r,height:s}}return this.pageSize={width:e.document.body.scrollWidth,height:e.document.body.scrollHeight},this.pageSize}update(e){if(!this.loaded)return;const t=this.loadPageSize();this.frame.style.height=`${t.height}px`,this.frame.style.width=`${t.width}px`;const i=Math.min(this.wrapper.clientWidth/t.width,this.wrapper.clientHeight/t.height);this.frame.style.transform=`scale(${i})`;const n=this.frame.getBoundingClientRect(),r=this.wrapper.clientHeight-n.height;if(this.frame.style.top=`${r/2}px`,e===G.left){const s=this.wrapper.clientWidth-n.width;this.frame.style.left=`${s}px`}else if(e===G.center){const s=this.wrapper.clientWidth-n.width;this.frame.style.left=`${s/2}px`}else this.frame.style.left="0px";this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("pointer-events"),this.frame.classList.remove("blank"),this.frame.classList.add("loaded")}async destroy(){await this.unfocus(),this.loader?.destroy(),this.wrapper.remove()}async unload(){if(this.loaded)return this.deselect(),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.pointerEvents="none",this.frame.classList.add("blank"),this.frame.classList.remove("loaded"),this.comms?.halt(),this.loader?.destroy(),this.comms=void 0,this.frame.blur(),new Promise((e,t)=>{this.frame.addEventListener("load",()=>{try{this.showPromise=void 0,e()}catch{}},{once:!0}),this.frame.addEventListener("error",i=>{try{this.showPromise=void 0,t(i.error)}catch{}},{once:!0}),this.source="about:blank",this.frame.contentWindow.location.replace("about:blank"),this.frame.style.display="none"})}deselect(){this.frame.contentWindow?.getSelection()?.removeAllRanges()}async unfocus(){if(this.frame.parentElement)return this.comms===void 0?void 0:new Promise((e,t)=>{this.comms?.send("unfocus",void 0,i=>{this.comms?.halt(),this.showPromise=void 0,e()})});this.comms?.halt()}applyContentProtection(){this.comms||this.comms.resume(),this.comms.send("peripherals_protection",this.contentProtectionConfig),this.keyboardPeripheralsConfig&&this.keyboardPeripheralsConfig.length>0&&this.comms.send("keyboard_peripherals",this.keyboardPeripheralsConfig),this.contentProtectionConfig.protectPrinting&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async show(e){if(!this.frame.parentElement){console.warn("Trying to show frame that is not attached to the DOM");return}if(!this.loaded){this.showPromise=void 0;return}return this.showPromise?(this.cachedPage!==e&&(this.update(e),this.cachedPage=e),this.showPromise):(this.cachedPage=e,this.comms?this.comms.resume():this.comms=new fe(this.frame.contentWindow,this.source),this.showPromise=new Promise((t,i)=>{this.comms.send("focus",void 0,n=>{this.update(this.cachedPage),this.applyContentProtection(),t()})}),this.showPromise)}async activate(){return new Promise((e,t)=>{if(!this.comms)return e();this.comms?.send("activate",void 0,()=>{e()})})}get element(){return this.wrapper}get iframe(){return this.frame}get realSize(){return this.frame.getBoundingClientRect()}get loaded(){return this.frame.contentWindow&&this.frame.contentWindow.location.href!=="about:blank"}set width(e){const t=`${e}%`;this.wrapper.style.width!==t&&(this.wrapper.style.width=t)}set height(e){const t=`${e}px`;this.wrapper.style.height!==t&&(this.wrapper.style.height=t)}get window(){if(!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get atLeft(){return this.window.scrollX<5}get atRight(){return this.window.scrollX>this.window.document.scrollingElement.scrollWidth-this.window.innerWidth-5}get msg(){return this.comms}get ldr(){return this.loader}}var bn=(o=>(o[o.Left=0]="Left",o[o.Center=1]="Center",o[o.Right=2]="Right",o))(bn||{}),vn=(o=>(o[o.Top=0]="Top",o[o.Middle=1]="Middle",o[o.Bottom=2]="Bottom",o))(vn||{});class Sn{constructor(){this.outerWidth=0,this.outerHeight=0,this.HTML=document.documentElement,this.Head=document.head,this.Body=document.body}refreshOuterPixels(e){$.OS.iOS||(this.outerHeight=window.outerHeight-window.innerHeight,$.OS.Android&&$.UA.Chrome&&window.screen.height>window.innerHeight&&(this.outerHeight=(window.screen.height-window.innerHeight)/1.5),this.outerWidth=window.outerWidth-window.innerWidth)}getBibiEventCoord(e,t=0){const i={X:0,Y:0};return/^touch/.test(e.type)?(i.X=e.touches[t].screenX,i.Y=e.touches[t].screenY):(i.X=e.screenX,i.Y=e.screenY),(e.target.ownerDocument?.documentElement||e.target.documentElement)===this.HTML&&(i.X-=this.HTML.scrollLeft+this.Body.scrollLeft,i.Y-=this.HTML.scrollTop+this.Body.scrollTop),i.X-=this.outerWidth,i.Y-=this.outerHeight,i}getTouchDistance(e){if(e.touches.length!==2)return 0;const t=e.touches[0].screenX-this.outerWidth,i=e.touches[0].screenY-this.outerHeight,n=e.touches[1].screenX-this.outerWidth,r=e.touches[1].screenY-this.outerHeight;return Math.sqrt(Math.pow(n-t,2)+Math.pow(r-i,2))}getTouchCenter(e){if(e.touches.length!==2)return null;const t=this.HTML.scrollLeft+this.Body.scrollLeft,i=this.HTML.scrollTop+this.Body.scrollTop,n=e.touches[0].screenX-this.outerWidth-t,r=e.touches[0].screenY-this.outerHeight-i,s=e.touches[1].screenX-this.outerWidth-t,a=e.touches[1].screenY-this.outerHeight-i;return{X:(n+s)/2,Y:(r+a)/2}}getBibiEvent(e){if(!e)return{Coord:null,Division:null,Ratio:null,Target:null};const t=this.getBibiEventCoord(e);let i=.3;const n={X:t.X/window.innerWidth,Y:t.Y/window.innerHeight};let r,s,a,l;a=r=i,l=s=1-i;const c={X:null,Y:null};return n.X<a?c.X=0:l<n.X?c.X=2:c.X=1,n.Y<r?c.Y=0:s<n.Y?c.Y=2:c.Y=1,{Target:e.target,Coord:t,Ratio:n,Division:c}}}class Yr{constructor(){this._DOM={show:!1,pinchTarget:document.createElement("div"),touch1:document.createElement("div"),touch2:document.createElement("div"),center:document.createElement("div"),stats:document.createElement("div")},this._DOM.show=!0,this._DOM.pinchTarget.style.zIndex=this._DOM.stats.style.zIndex=this._DOM.center.style.zIndex=this._DOM.touch1.style.zIndex=this._DOM.touch2.style.zIndex="100000",this._DOM.pinchTarget.style.position=this._DOM.stats.style.position=this._DOM.center.style.position=this._DOM.touch1.style.position=this._DOM.touch2.style.position="absolute",this._DOM.pinchTarget.style.borderRadius=this._DOM.center.style.borderRadius=this._DOM.touch1.style.borderRadius=this._DOM.touch2.style.borderRadius="50%",this._DOM.pinchTarget.style.pointerEvents=this._DOM.stats.style.pointerEvents=this._DOM.center.style.pointerEvents=this._DOM.touch1.style.pointerEvents=this._DOM.touch2.style.pointerEvents="none",this._DOM.pinchTarget.style.display=this._DOM.center.style.display=this._DOM.touch1.style.display=this._DOM.touch2.style.display="none",this._DOM.pinchTarget.style.paddingTop=this._DOM.center.style.paddingTop="10px",this._DOM.pinchTarget.style.width=this._DOM.pinchTarget.style.height=this._DOM.center.style.width=this._DOM.center.style.height="10px",this._DOM.pinchTarget.style.backgroundColor="green",this._DOM.center.style.backgroundColor="red",this._DOM.touch1.style.backgroundColor=this._DOM.touch2.style.backgroundColor="blue",this._DOM.touch1.style.height=this._DOM.touch2.style.height="20px",this._DOM.touch1.style.width=this._DOM.touch2.style.width="20px",this._DOM.touch1.style.paddingTop=this._DOM.touch2.style.paddingTop="20px",this._DOM.touch1.textContent="1",this._DOM.touch2.textContent="2",this._DOM.stats.style.padding="20px",this._DOM.stats.style.backgroundColor="rgba(0,0,0,0.5)",this._DOM.stats.style.color="white",this._DOM.stats.textContent="[stats]",document.body.appendChild(this._DOM.stats),document.body.appendChild(this._DOM.center),document.body.appendChild(this._DOM.touch1),document.body.appendChild(this._DOM.touch2),document.body.appendChild(this._DOM.pinchTarget)}get show(){return this.DOM.show}get DOM(){return this._DOM}}const _n=6,Vt=1.02,wn=50;class Pn{constructor(e,t=!1){this.dragState=0,this.minimumMoved=!1,this.pan={startX:0,endX:0,startY:0,overscrollX:0,overscrollY:0,letItGo:!1,preventClick:!1,translateX:0,translateY:0,touchID:0},this.pinch={startDistance:0,startScale:0,target:{X:0,Y:0},touchN:0,startTranslate:{X:0,Y:0}},this._scale=1,this.scaleDebouncer=0,this.frameBounds=null,this.debugger=null,this.btouchstartHandler=this.touchstartHandler.bind(this),this.btouchendHandler=this.touchendHandler.bind(this),this.btouchmoveHandler=this.touchmoveHandler.bind(this),this.bdblclickHandler=this.dblclickHandler.bind(this),this.bmousedownHandler=this.mousedownHandler.bind(this),this.bmouseupHandler=this.mouseupHandler.bind(this),this.bmousemoveHandler=this.mousemoveHandler.bind(this),this.moveFrame=0,this.manager=e,this.coordinator=new Sn,this.attachEvents(),t&&(this.debugger=new Yr)}get scale(){return this._scale}set scale(e){isNaN(e)&&(e=1),window.clearTimeout(this.scaleDebouncer),this.scaleDebouncer=window.setTimeout(()=>{this.dragState===0&&this.scale<Vt&&(this.pan.translateX=0,this.pan.translateY=0,this.clearPan(),this.manager.updateBookStyle()),this.manager.listener("zoom",e)},100),this._scale=e}attachEvents(){this.observe(this.manager.spineElement),this.pan={startX:0,startY:0,endX:0,overscrollX:0,overscrollY:0,letItGo:!1,preventClick:!1,translateX:0,translateY:0,touchID:0},this.pinch={startDistance:0,startScale:0,target:{X:0,Y:0},startTranslate:{X:0,Y:0},touchN:0}}clearPan(){this.pan.letItGo=!1,this.pan.touchID=0,this.pan.endX=0,this.pan.overscrollX=0,this.pan.overscrollY=0}clearPinch(){this.pinch={startDistance:0,startScale:this.pinch.startScale,target:{X:0,Y:0},touchN:0,startTranslate:{X:0,Y:0}}}observe(e){e.addEventListener("touchstart",this.btouchstartHandler),e.addEventListener("touchend",this.btouchendHandler),e.addEventListener("touchmove",this.btouchmoveHandler,{passive:!0}),e.addEventListener("dblclick",this.bdblclickHandler,{passive:!0}),e.addEventListener("mousedown",this.bmousedownHandler),e.addEventListener("mouseup",this.bmouseupHandler),e.addEventListener("mousemove",this.bmousemoveHandler)}clickHandler(e){}touchstartHandler(e){if(["TEXTAREA","OPTION","INPUT","SELECT"].indexOf(e.target.nodeName)!==-1)return;switch(e.stopPropagation(),this.frameBounds=this.manager.currentBounds,this.coordinator.refreshOuterPixels(this.frameBounds),e.touches.length){case 3:return;case 2:{e.preventDefault(),this.pinch.startDistance=this.coordinator.getTouchDistance(e);const n=this.startTouch(e);this.pan.startX=n.X,this.pan.startY=n.Y,this.dragState=2,this.manager.updateBookStyle(!0),this.isScaled?(this.pinch.target.X-=this.pan.translateX*(this.pinch.startScale/this.scale),this.pinch.target.Y-=this.pan.translateY*(this.pinch.startScale/this.scale),this.pinch.target={X:0,Y:0},this.pinch.startScale=1/this.scale):(this.pinch.target={X:0,Y:0},this.pinch.startScale=this.scale),this.pinch.startTranslate={X:this.pan.translateX,Y:this.pan.translateY},this.debugger?.show&&(this.debugger.DOM.touch2.style.display="",this.debugger.DOM.center.style.display="",this.debugger.DOM.pinchTarget.style.display="");return}case 1:this.pan.touchID=e.touches[0].identifier,this.debugger?.show&&(this.debugger.DOM.touch1.style.display="");default:this.dragState<1&&(this.dragState=1),this.manager.updateBookStyle(!0)}this.manager.updateSpineStyle(!1);const i=this.startTouch(e);this.pan.startX=i.X,this.pan.startY=i.Y}startTouch(e){const t=this.coordinator.getTouchCenter(e)||this.coordinator.getBibiEventCoord(e);return{X:t.X-this.manager.width/2-this.pan.translateX*this.scale+this.manager.width/2,Y:t.Y-this.manager.height/2-this.pan.translateY*this.scale+this.manager.height/2}}touchendHandler(e){if(e.stopPropagation(),!e.touches||e.touches.length===0)this.pan.endX&&!this.isScaled?(this.pinch.touchN&&(this.pan.endX=this.pan.startX),this.updateAfterDrag()):!this.pinch.touchN&&Math.abs(this.pan.overscrollX)>wn&&Math.abs(this.pan.overscrollY)<wn/2&&(this.pan.startX=0,this.pan.endX=-this.pan.overscrollX,this.updateAfterDrag()),this.dragState=0,this.minimumMoved=!1,this.clearPinch(),this.debugger?.show&&(this.debugger.DOM.center.style.display="none",this.debugger.DOM.touch1.style.display="none",this.debugger.DOM.touch2.style.display="none");else if(e.touches.length===1){this.dragState=1,e.touches[0].identifier!==this.pan.touchID&&(this.pan.touchID=e.touches[0].identifier),this.debugger?.show&&(this.debugger.DOM.center.style.display="none",this.debugger.DOM.touch2.style.display="none",this.debugger.DOM.pinchTarget.style.display="none");const t=this.startTouch(e);this.pan.startX=t.X,this.pan.startY=t.Y}window.setTimeout(()=>{this.manager.updateBookStyle(!0),this.dragState===0&&(this.scale<Vt&&(this.pan.translateX=0,this.pan.translateY=0),this.clearPan()),this.manager.updateBookStyle(!0)},50)}touchmoveHandler(e){e.stopPropagation();const t=this.coordinator.getBibiEventCoord(e);Math.abs(this.pan.startY-t.Y)+Math.abs(this.pan.startX-t.X)>5&&(this.minimumMoved||(this.manager.deselect(),this.minimumMoved=!0),this.dragState<1&&(this.dragState=1));const i=this.coordinator?.getTouchDistance(e);let n=!1;const r=this.scale;if(this.dragState===2&&i){if(this.pinch.touchN++,this.pinch.touchN<4)return;let s=i/this.pinch.startDistance*this.scale;s>=_n&&(s=_n),s<=Vt&&(s=1),this.scale=s,this.pinch.startDistance=i,n=!0}if(this.pan.letItGo===!1&&(this.pan.letItGo=Math.abs(this.pan.startY-t.Y)<Math.abs(this.pan.startX-t.X)),this.debugger?.show&&(this.debugger.DOM.touch1.style.top=`${t.Y-10}px`,this.debugger.DOM.touch1.style.left=`${t.X-10}px`,this.debugger.DOM.touch1.innerText=`${t.X.toFixed(2)},${t.Y.toFixed(2)}`),this.dragState>0&&this.isScaled||this.dragState>1){if(this.dragState===1){const l={X:t.X-this.manager.width/2,Y:t.Y-this.manager.height/2};this.pan.translateX=(l.X-(this.pan.startX-this.manager.width/2))*1/this.scale,this.pan.translateY=(l.Y-(this.pan.startY-this.manager.height/2))*1/this.scale}else if(this.dragState===2){const l=this.coordinator.getTouchCenter(e);if(this.debugger?.show){this.debugger.DOM.center.style.top=`${l.Y-5}px`,this.debugger.DOM.center.style.left=`${l.X-5}px`,this.debugger.DOM.center.innerText=`${l.X.toFixed(2)},${l.Y.toFixed(2)}`;const b=this.coordinator.getBibiEventCoord(e,1);this.debugger.DOM.touch2.style.top=`${b.Y-10}px`,this.debugger.DOM.touch2.style.left=`${b.X-10}px`,this.debugger.DOM.touch2.innerText=`${b.X.toFixed(2)},${b.Y.toFixed(2)}`}l.X-=this.manager.width/2,l.Y-=this.manager.height/2;let c=-l.X/r;c+=l.X/this.scale,this.pinch.target.X+=c,l.X+=this.pinch.target.X*this.scale/this.pinch.startScale;let h=-l.Y/r;h+=l.Y/this.scale,this.pinch.target.Y+=h,l.Y+=this.pinch.target.Y*this.scale/this.pinch.startScale;let u=(l.X-(this.pan.startX-this.manager.width/2))*1/this.scale,m=(l.Y-(this.pan.startY-this.manager.height/2))*1/this.scale;this.pan.translateX=u,this.pan.translateY=m,this.debugger?.show&&(this.debugger.DOM.pinchTarget.style.left=`${this.pinch.target.X*this.scale/this.pinch.startScale-5+this.manager.width/2}px`,this.debugger.DOM.pinchTarget.style.top=`${this.pinch.target.Y*this.scale/this.pinch.startScale-5+this.manager.height/2}px`,this.debugger.DOM.pinchTarget.innerText=`${(this.pinch.target.X*this.scale/this.pinch.startScale).toFixed(2)},${(this.pinch.target.Y*this.scale/this.pinch.startScale).toFixed(2)}`)}const s=this.frameBounds.width/6,a=this.frameBounds.height/6;this.pan.translateX<-s&&(this.pan.overscrollX=-(s+this.pan.translateX),this.pan.translateX=-s),this.pan.translateY<-a&&(this.pan.overscrollY=-(a+this.pan.translateY),this.pan.translateY=-a),this.pan.translateX>s&&(this.pan.overscrollX=s-this.pan.translateX,this.pan.translateX=s),this.pan.translateY>a&&(this.pan.overscrollY=a-this.pan.translateY,this.pan.translateY=a),n=!0,this.debugger?.show&&(this.debugger.DOM.stats.innerText=`TX: ${this.pan.translateX.toFixed(2)}
|
|
403
|
+
img { margin: 0; padding: 0; border: 0; }`,i.head.appendChild(r),this.finalizeDOM(i,this.pub.baseURL,t,e.mediaType,!0)}setProperties(e,t){for(const i in e){const n=e[i];n&&t.documentElement.style.setProperty(i,n)}}finalizeDOM(e,t,i,n,r=!1,s){if(!e)return"";const a=this.injector?.getAllowedDomains?.()||[];t=t?.split("?")[0];const l=[...new Set([...t?[t]:[],...a])].filter(Boolean);if(s&&!r&&this.setProperties(s,e),e.body.querySelectorAll("img").forEach(h=>{h.setAttribute("fetchpriority","high"),h.setAttribute("referrerpolicy","origin")}),n.isHTML&&this.pub.metadata.languages?.[0]){const h=this.pub.metadata.languages[0];if(n===g.XHTML){const u=document.documentElement.lang||document.documentElement.getAttribute("xml:lang"),m=document.body.lang||document.body.getAttribute("xml:lang");m&&!u?(document.documentElement.lang=m,document.documentElement.setAttribute("xml:lang",m),document.body.removeAttribute("xml:lang"),document.body.removeAttribute("lang")):u||(document.documentElement.lang=h,document.documentElement.setAttribute("xml:lang",h))}else n===g.HTML&&!document.documentElement.lang&&(document.documentElement.lang=h)}if(i!==void 0){const h=e.createElement("base");h.href=i,h.dataset.readium="true",e.head.firstChild.before(h)}const c=e.createElement("meta");return c.httpEquiv="Content-Security-Policy",c.content=qr(l),c.dataset.readium="true",e.head.firstChild.before(c),URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(e)],{type:n.isHTML?n.string:"application/xhtml+xml"}))}}class pn{constructor(e,t={},i=[]){this.hidden=!0,this.destroyed=!1,this.currModules=[],this.frame=document.createElement("iframe"),this.frame.sandbox.value="allow-same-origin allow-scripts",this.frame.classList.add("readium-navigator-iframe"),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transition="visibility 0s, opacity 0.1s linear",this.source=e,this.contentProtectionConfig={...t},this.keyboardPeripheralsConfig=[...i]}async load(e){return new Promise((t,i)=>{if(this.loader){const n=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{t(n)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new ge(n,e),this.currModules=e,this.comms=void 0;try{t(n)}catch{}return}this.frame.onload=()=>{const n=this.frame.contentWindow;this.loader=new ge(n,e),this.currModules=e;try{t(n)}catch{}},this.frame.onerror=n=>{try{i(n)}catch{}},this.frame.contentWindow.location.replace(this.source)})}applyContentProtection(){this.comms||this.comms.resume(),this.comms.send("peripherals_protection",this.contentProtectionConfig),this.keyboardPeripheralsConfig&&this.keyboardPeripheralsConfig.length>0&&this.comms.send("keyboard_peripherals",this.keyboardPeripheralsConfig),this.contentProtectionConfig.monitorScrollingExperimental&&this.comms.send("scroll_protection",{}),this.contentProtectionConfig.protectPrinting&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async destroy(){await this.hide(),this.loader?.destroy(),this.frame.remove(),this.destroyed=!0}async hide(){if(!this.destroyed){if(this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.pointerEvents="none",this.hidden=!0,this.frame.parentElement)return this.comms===void 0||!this.comms.ready?void 0:new Promise((e,t)=>{this.comms?.send("unfocus",void 0,i=>{this.comms?.halt(),e()})});this.comms?.halt()}}async show(e){if(this.destroyed)throw Error("Trying to show frame when it doesn't exist");if(!this.frame.parentElement)throw Error("Trying to show frame that is not attached to the DOM");return this.comms?this.comms.resume():this.comms=new fe(this.frame.contentWindow,this.source),new Promise((t,i)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{this.applyContentProtection();const n=()=>{this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("opacity"),this.frame.style.removeProperty("pointer-events"),this.hidden=!1,$.UA.WebKit&&this.comms?.send("force_webkit_recalc",void 0),t()};e!==void 0?this.comms?.send("go_progression",e,n):n()})})})}setCSSProperties(e){this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?this.comms?.resume():this.comms=new fe(this.frame.contentWindow,this.source)),this.comms?.send("update_properties",e),this.hidden&&this.comms?.halt())}get iframe(){if(this.destroyed)throw Error("Trying to use frame when it doesn't exist");return this.frame}get realSize(){if(this.destroyed)throw Error("Trying to use frame client rect when it doesn't exist");return this.frame.getBoundingClientRect()}get window(){if(this.destroyed||!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get atLeft(){return this.window.scrollX<5}get atRight(){return this.window.scrollX>this.window.document.scrollingElement.scrollWidth-this.window.innerWidth-5}get msg(){return this.comms}get ldr(){return this.loader}}const mn=5,gn=3;class fn{constructor(e,t,i,n,r,s){this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.pendingUpdates=new Map,this.injector=null,this.container=e,this.positions=t,this.currentCssProperties=i,this.injector=n??null,this.contentProtectionConfig=r||{},this.keyboardPeripheralsConfig=s||[]}async destroy(){let e=this.inprogress.values(),t=e.next();const i=[];for(;t.value;)i.push(t.value),t=e.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let n=this.pool.values(),r=n.next();for(;r.value;)await r.value.destroy(),r=n.next();this.pool.clear(),this.blobs.forEach(s=>s.reset()),this.blobs.clear(),this.injector?.dispose(),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}async update(e,t,i,n=!1){let r=this.positions.findIndex(l=>l.locations.position===t.locations.position);if(r<0)throw Error(`Locator not found in position list: ${t.locations.position} > ${this.positions.reduce((l,c)=>c.locations.position||0>l?c.locations.position||0:l,0)}`);const s=this.positions[r].href;this.inprogress.has(s)&&await this.inprogress.get(s);const a=new Promise(async(l,c)=>{const h=[],u=[];this.positions.forEach((d,p)=>{(p>r+mn||p<r-mn)&&(h.includes(d.href)||h.push(d.href)),p<r+gn&&p>r-gn&&(u.includes(d.href)||u.push(d.href))}),h.forEach(async d=>{u.includes(d)||this.pool.has(d)&&(await this.pool.get(d)?.destroy(),this.pool.delete(d),this.pendingUpdates.has(d)&&this.pendingUpdates.set(d,{inPool:!1}))}),this.currentBaseURL!==void 0&&e.baseURL!==this.currentBaseURL&&(this.blobs.forEach(d=>d.reset()),this.blobs.clear()),this.currentBaseURL=e.baseURL;const m=async d=>{if(n&&(this.blobs.forEach(P=>P.reset()),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(d)&&this.pendingUpdates.get(d)?.inPool===!1){const P=this.blobs.get(d);P&&(P.reset(),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const P=this.pool.get(d);if(!this.blobs.has(d))await P.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await P.load(i);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;this.blobs.has(d)||this.blobs.set(d,new un(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}));const S=new pn(await this.blobs.get(d).build(),this.contentProtectionConfig,this.keyboardPeripheralsConfig);d!==s&&await S.hide(),this.container.appendChild(S.iframe),await S.load(i),this.pool.set(d,S)};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const b=this.pool.get(s);(b?.source!==this._currentFrame?.source||n)&&(await this._currentFrame?.hide(),b&&await b.load(i),b&&await b.show(t.locations.progression),this._currentFrame=b),l()});this.inprogress.set(s,a),await a,this.inprogress.delete(s)}setCSSProperties(e){if(!((i,n)=>{const r=Object.keys(i),s=Object.keys(n);if(r.length!==s.length)return!1;for(const a of r)if(i[a]!==n[a])return!1;return!0})(this.currentCssProperties||{},e)){this.currentCssProperties=e,this.pool.forEach(i=>{i.setCSSProperties(e)});for(const i of this.blobs.keys())this.pendingUpdates.set(i,{inPool:this.pool.has(i)})}}get currentFrames(){return[this._currentFrame]}get currentBounds(){const e={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(t=>{if(!t)return;const i=t.realSize;e.x=Math.min(e.x,i.x),e.y=Math.min(e.y,i.y),e.width+=i.width,e.height=Math.max(e.height,i.height),e.top=Math.min(e.top,i.top),e.right=Math.min(e.right,i.right),e.bottom=Math.min(e.bottom,i.bottom),e.left=Math.min(e.left,i.left)}),e}}class yn{constructor(e,t,i,n={},r=[]){this.frameIsAppended=!1,this.currModules=[],this.viewportSize=void 0,this.cachedPage=void 0,this.peripherals=e,this.debugHref=i,this.contentProtectionConfig={...n},this.keyboardPeripheralsConfig=[...r],this.frame=document.createElement("iframe"),this.frame.sandbox.value="allow-same-origin allow-scripts",this.frame.classList.add("readium-navigator-iframe"),this.frame.classList.add("blank"),this.frame.scrolling="no",this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.display="none",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transformOrigin="0 0",this.frame.style.transform="scale(1)",this.frame.style.background="#fff",this.frame.style.touchAction="none",this.frame.dataset.originalHref=i,this.source="about:blank",this.wrapper=document.createElement("div"),this.wrapper.style.position="relative",this.wrapper.style.float=this.wrapper.style.cssFloat=t===N.rtl?"right":"left"}async load(e,t){return this.frameIsAppended||(this.wrapper.appendChild(this.frame),this.frameIsAppended=!0),this.source===t&&this.loadPromise&&[...this.currModules].sort().join("|")===[...e].sort().join("|")?this.loadPromise:(this.loaded&&this.source!==t&&this.window.stop(),this.source=t,this.loadPromise=new Promise((i,n)=>{if(this.loader&&this.loaded){const r=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{i(r),this.loadPromise=void 0}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new ge(r,e),this.currModules=e,this.comms=void 0;try{i(r),this.loadPromise=void 0}catch{}return}this.frame.addEventListener("load",()=>{const r=this.frame.contentWindow;this.loader=new ge(r,e),this.currModules=e,this.peripherals.observe(this.wrapper),this.peripherals.observe(r);try{i(r)}catch{}},{once:!0}),this.frame.addEventListener("error",r=>{try{n(r.error),this.loadPromise=void 0}catch{}},{once:!0}),this.frame.style.removeProperty("display"),this.frame.contentWindow.location.replace(this.source)}),this.loadPromise)}loadPageSize(){if(this.viewportSize)return this.viewportSize;const e=this.frame.contentWindow,t=e.document.head.querySelector("meta[name=viewport]");if(t){const i=/(\w+) *= *([^\s,]+)/g;let n,r=0,s=0;for(;n=i.exec(t.content);)n[1]==="width"?r=Number.parseFloat(n[2]):n[1]==="height"&&(s=Number.parseFloat(n[2]));if(r>0&&s>0)return this.viewportSize={width:r,height:s},this.viewportSize}return{width:e.document.body.scrollWidth,height:e.document.body.scrollHeight}}update(e){if(!this.loaded)return;const t=this.loadPageSize();this.frame.style.height=`${t.height}px`,this.frame.style.width=`${t.width}px`;const i=Math.min(this.wrapper.clientWidth/t.width,this.wrapper.clientHeight/t.height);this.frame.style.transform=`scale(${i})`;const n=this.frame.getBoundingClientRect(),r=this.wrapper.clientHeight-n.height;if(this.frame.style.top=`${r/2}px`,e===G.left){const s=this.wrapper.clientWidth-n.width;this.frame.style.left=`${s}px`}else if(e===G.center){const s=this.wrapper.clientWidth-n.width;this.frame.style.left=`${s/2}px`}else this.frame.style.left="0px";this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("pointer-events"),this.frame.classList.remove("blank"),this.frame.classList.add("loaded")}async destroy(){await this.unfocus(),this.loader?.destroy(),this.wrapper.remove()}async unload(){if(this.loaded)return this.deselect(),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.pointerEvents="none",this.frame.classList.add("blank"),this.frame.classList.remove("loaded"),this.comms?.halt(),this.loader?.destroy(),this.comms=void 0,this.frame.blur(),new Promise((e,t)=>{this.frame.addEventListener("load",()=>{try{this.showPromise=void 0,e()}catch{}},{once:!0}),this.frame.addEventListener("error",i=>{try{this.showPromise=void 0,t(i.error)}catch{}},{once:!0}),this.source="about:blank",this.frame.contentWindow.location.replace("about:blank"),this.frame.style.display="none"})}deselect(){this.frame.contentWindow?.getSelection()?.removeAllRanges()}async unfocus(){if(this.frame.parentElement)return this.comms===void 0?void 0:new Promise((e,t)=>{this.comms?.send("unfocus",void 0,i=>{this.comms?.halt(),this.showPromise=void 0,e()})});this.comms?.halt()}applyContentProtection(){this.comms||this.comms.resume(),this.comms.send("peripherals_protection",this.contentProtectionConfig),this.keyboardPeripheralsConfig&&this.keyboardPeripheralsConfig.length>0&&this.comms.send("keyboard_peripherals",this.keyboardPeripheralsConfig),this.contentProtectionConfig.protectPrinting&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async show(e){if(!this.frame.parentElement){console.warn("Trying to show frame that is not attached to the DOM");return}if(!this.loaded){this.showPromise=void 0;return}return this.showPromise?(this.cachedPage!==e&&(this.update(e),this.cachedPage=e),this.showPromise):(this.cachedPage=e,this.comms?this.comms.resume():this.comms=new fe(this.frame.contentWindow,this.source),this.showPromise=new Promise((t,i)=>{this.comms.send("focus",void 0,n=>{this.update(this.cachedPage),this.applyContentProtection(),t()})}),this.showPromise)}async activate(){return new Promise((e,t)=>{if(!this.comms)return e();this.comms?.send("activate",void 0,()=>{e()})})}get element(){return this.wrapper}get iframe(){return this.frame}get realSize(){return this.frame.getBoundingClientRect()}get loaded(){return this.frame.contentWindow&&this.frame.contentWindow.location.href!=="about:blank"}set width(e){const t=`${e}%`;this.wrapper.style.width!==t&&(this.wrapper.style.width=t)}set height(e){const t=`${e}px`;this.wrapper.style.height!==t&&(this.wrapper.style.height=t)}get window(){if(!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get atLeft(){return this.window.scrollX<5}get atRight(){return this.window.scrollX>this.window.document.scrollingElement.scrollWidth-this.window.innerWidth-5}get msg(){return this.comms}get ldr(){return this.loader}}var bn=(o=>(o[o.Left=0]="Left",o[o.Center=1]="Center",o[o.Right=2]="Right",o))(bn||{}),vn=(o=>(o[o.Top=0]="Top",o[o.Middle=1]="Middle",o[o.Bottom=2]="Bottom",o))(vn||{});class Sn{constructor(){this.outerWidth=0,this.outerHeight=0,this.HTML=document.documentElement,this.Head=document.head,this.Body=document.body}refreshOuterPixels(e){$.OS.iOS||(this.outerHeight=window.outerHeight-window.innerHeight,$.OS.Android&&$.UA.Chrome&&window.screen.height>window.innerHeight&&(this.outerHeight=(window.screen.height-window.innerHeight)/1.5),this.outerWidth=window.outerWidth-window.innerWidth)}getBibiEventCoord(e,t=0){const i={X:0,Y:0};return/^touch/.test(e.type)?(i.X=e.touches[t].screenX,i.Y=e.touches[t].screenY):(i.X=e.screenX,i.Y=e.screenY),(e.target.ownerDocument?.documentElement||e.target.documentElement)===this.HTML&&(i.X-=this.HTML.scrollLeft+this.Body.scrollLeft,i.Y-=this.HTML.scrollTop+this.Body.scrollTop),i.X-=this.outerWidth,i.Y-=this.outerHeight,i}getTouchDistance(e){if(e.touches.length!==2)return 0;const t=e.touches[0].screenX-this.outerWidth,i=e.touches[0].screenY-this.outerHeight,n=e.touches[1].screenX-this.outerWidth,r=e.touches[1].screenY-this.outerHeight;return Math.sqrt(Math.pow(n-t,2)+Math.pow(r-i,2))}getTouchCenter(e){if(e.touches.length!==2)return null;const t=this.HTML.scrollLeft+this.Body.scrollLeft,i=this.HTML.scrollTop+this.Body.scrollTop,n=e.touches[0].screenX-this.outerWidth-t,r=e.touches[0].screenY-this.outerHeight-i,s=e.touches[1].screenX-this.outerWidth-t,a=e.touches[1].screenY-this.outerHeight-i;return{X:(n+s)/2,Y:(r+a)/2}}getBibiEvent(e){if(!e)return{Coord:null,Division:null,Ratio:null,Target:null};const t=this.getBibiEventCoord(e);let i=.3;const n={X:t.X/window.innerWidth,Y:t.Y/window.innerHeight};let r,s,a,l;a=r=i,l=s=1-i;const c={X:null,Y:null};return n.X<a?c.X=0:l<n.X?c.X=2:c.X=1,n.Y<r?c.Y=0:s<n.Y?c.Y=2:c.Y=1,{Target:e.target,Coord:t,Ratio:n,Division:c}}}class Yr{constructor(){this._DOM={show:!1,pinchTarget:document.createElement("div"),touch1:document.createElement("div"),touch2:document.createElement("div"),center:document.createElement("div"),stats:document.createElement("div")},this._DOM.show=!0,this._DOM.pinchTarget.style.zIndex=this._DOM.stats.style.zIndex=this._DOM.center.style.zIndex=this._DOM.touch1.style.zIndex=this._DOM.touch2.style.zIndex="100000",this._DOM.pinchTarget.style.position=this._DOM.stats.style.position=this._DOM.center.style.position=this._DOM.touch1.style.position=this._DOM.touch2.style.position="absolute",this._DOM.pinchTarget.style.borderRadius=this._DOM.center.style.borderRadius=this._DOM.touch1.style.borderRadius=this._DOM.touch2.style.borderRadius="50%",this._DOM.pinchTarget.style.pointerEvents=this._DOM.stats.style.pointerEvents=this._DOM.center.style.pointerEvents=this._DOM.touch1.style.pointerEvents=this._DOM.touch2.style.pointerEvents="none",this._DOM.pinchTarget.style.display=this._DOM.center.style.display=this._DOM.touch1.style.display=this._DOM.touch2.style.display="none",this._DOM.pinchTarget.style.paddingTop=this._DOM.center.style.paddingTop="10px",this._DOM.pinchTarget.style.width=this._DOM.pinchTarget.style.height=this._DOM.center.style.width=this._DOM.center.style.height="10px",this._DOM.pinchTarget.style.backgroundColor="green",this._DOM.center.style.backgroundColor="red",this._DOM.touch1.style.backgroundColor=this._DOM.touch2.style.backgroundColor="blue",this._DOM.touch1.style.height=this._DOM.touch2.style.height="20px",this._DOM.touch1.style.width=this._DOM.touch2.style.width="20px",this._DOM.touch1.style.paddingTop=this._DOM.touch2.style.paddingTop="20px",this._DOM.touch1.textContent="1",this._DOM.touch2.textContent="2",this._DOM.stats.style.padding="20px",this._DOM.stats.style.backgroundColor="rgba(0,0,0,0.5)",this._DOM.stats.style.color="white",this._DOM.stats.textContent="[stats]",document.body.appendChild(this._DOM.stats),document.body.appendChild(this._DOM.center),document.body.appendChild(this._DOM.touch1),document.body.appendChild(this._DOM.touch2),document.body.appendChild(this._DOM.pinchTarget)}get show(){return this.DOM.show}get DOM(){return this._DOM}}const _n=6,Vt=1.02,wn=50;class Pn{constructor(e,t=!1){this.dragState=0,this.minimumMoved=!1,this.pan={startX:0,endX:0,startY:0,overscrollX:0,overscrollY:0,letItGo:!1,preventClick:!1,translateX:0,translateY:0,touchID:0},this.pinch={startDistance:0,startScale:0,target:{X:0,Y:0},touchN:0,startTranslate:{X:0,Y:0}},this._scale=1,this.scaleDebouncer=0,this.frameBounds=null,this.debugger=null,this.btouchstartHandler=this.touchstartHandler.bind(this),this.btouchendHandler=this.touchendHandler.bind(this),this.btouchmoveHandler=this.touchmoveHandler.bind(this),this.bdblclickHandler=this.dblclickHandler.bind(this),this.bmousedownHandler=this.mousedownHandler.bind(this),this.bmouseupHandler=this.mouseupHandler.bind(this),this.bmousemoveHandler=this.mousemoveHandler.bind(this),this.moveFrame=0,this.manager=e,this.coordinator=new Sn,this.attachEvents(),t&&(this.debugger=new Yr)}get scale(){return this._scale}set scale(e){isNaN(e)&&(e=1),window.clearTimeout(this.scaleDebouncer),this.scaleDebouncer=window.setTimeout(()=>{this.dragState===0&&this.scale<Vt&&(this.pan.translateX=0,this.pan.translateY=0,this.clearPan(),this.manager.updateBookStyle()),this.manager.listener("zoom",e)},100),this._scale=e}attachEvents(){this.observe(this.manager.spineElement),this.pan={startX:0,startY:0,endX:0,overscrollX:0,overscrollY:0,letItGo:!1,preventClick:!1,translateX:0,translateY:0,touchID:0},this.pinch={startDistance:0,startScale:0,target:{X:0,Y:0},startTranslate:{X:0,Y:0},touchN:0}}clearPan(){this.pan.letItGo=!1,this.pan.touchID=0,this.pan.endX=0,this.pan.overscrollX=0,this.pan.overscrollY=0}clearPinch(){this.pinch={startDistance:0,startScale:this.pinch.startScale,target:{X:0,Y:0},touchN:0,startTranslate:{X:0,Y:0}}}observe(e){e.addEventListener("touchstart",this.btouchstartHandler),e.addEventListener("touchend",this.btouchendHandler),e.addEventListener("touchmove",this.btouchmoveHandler,{passive:!0}),e.addEventListener("dblclick",this.bdblclickHandler,{passive:!0}),e.addEventListener("mousedown",this.bmousedownHandler),e.addEventListener("mouseup",this.bmouseupHandler),e.addEventListener("mousemove",this.bmousemoveHandler)}clickHandler(e){}touchstartHandler(e){if(["TEXTAREA","OPTION","INPUT","SELECT"].indexOf(e.target.nodeName)!==-1)return;switch(e.stopPropagation(),this.frameBounds=this.manager.currentBounds,this.coordinator.refreshOuterPixels(this.frameBounds),e.touches.length){case 3:return;case 2:{e.preventDefault(),this.pinch.startDistance=this.coordinator.getTouchDistance(e);const n=this.startTouch(e);this.pan.startX=n.X,this.pan.startY=n.Y,this.dragState=2,this.manager.updateBookStyle(!0),this.isScaled?(this.pinch.target.X-=this.pan.translateX*(this.pinch.startScale/this.scale),this.pinch.target.Y-=this.pan.translateY*(this.pinch.startScale/this.scale),this.pinch.target={X:0,Y:0},this.pinch.startScale=1/this.scale):(this.pinch.target={X:0,Y:0},this.pinch.startScale=this.scale),this.pinch.startTranslate={X:this.pan.translateX,Y:this.pan.translateY},this.debugger?.show&&(this.debugger.DOM.touch2.style.display="",this.debugger.DOM.center.style.display="",this.debugger.DOM.pinchTarget.style.display="");return}case 1:this.pan.touchID=e.touches[0].identifier,this.debugger?.show&&(this.debugger.DOM.touch1.style.display="");default:this.dragState<1&&(this.dragState=1),this.manager.updateBookStyle(!0)}this.manager.updateSpineStyle(!1);const i=this.startTouch(e);this.pan.startX=i.X,this.pan.startY=i.Y}startTouch(e){const t=this.coordinator.getTouchCenter(e)||this.coordinator.getBibiEventCoord(e);return{X:t.X-this.manager.width/2-this.pan.translateX*this.scale+this.manager.width/2,Y:t.Y-this.manager.height/2-this.pan.translateY*this.scale+this.manager.height/2}}touchendHandler(e){if(e.stopPropagation(),!e.touches||e.touches.length===0)this.pan.endX&&!this.isScaled?(this.pinch.touchN&&(this.pan.endX=this.pan.startX),this.updateAfterDrag()):!this.pinch.touchN&&Math.abs(this.pan.overscrollX)>wn&&Math.abs(this.pan.overscrollY)<wn/2&&(this.pan.startX=0,this.pan.endX=-this.pan.overscrollX,this.updateAfterDrag()),this.dragState=0,this.minimumMoved=!1,this.clearPinch(),this.debugger?.show&&(this.debugger.DOM.center.style.display="none",this.debugger.DOM.touch1.style.display="none",this.debugger.DOM.touch2.style.display="none");else if(e.touches.length===1){this.dragState=1,e.touches[0].identifier!==this.pan.touchID&&(this.pan.touchID=e.touches[0].identifier),this.debugger?.show&&(this.debugger.DOM.center.style.display="none",this.debugger.DOM.touch2.style.display="none",this.debugger.DOM.pinchTarget.style.display="none");const t=this.startTouch(e);this.pan.startX=t.X,this.pan.startY=t.Y}window.setTimeout(()=>{this.manager.updateBookStyle(!0),this.dragState===0&&(this.scale<Vt&&(this.pan.translateX=0,this.pan.translateY=0),this.clearPan()),this.manager.updateBookStyle(!0)},50)}touchmoveHandler(e){e.stopPropagation();const t=this.coordinator.getBibiEventCoord(e);Math.abs(this.pan.startY-t.Y)+Math.abs(this.pan.startX-t.X)>5&&(this.minimumMoved||(this.manager.deselect(),this.minimumMoved=!0),this.dragState<1&&(this.dragState=1));const i=this.coordinator?.getTouchDistance(e);let n=!1;const r=this.scale;if(this.dragState===2&&i){if(this.pinch.touchN++,this.pinch.touchN<4)return;let s=i/this.pinch.startDistance*this.scale;s>=_n&&(s=_n),s<=Vt&&(s=1),this.scale=s,this.pinch.startDistance=i,n=!0}if(this.pan.letItGo===!1&&(this.pan.letItGo=Math.abs(this.pan.startY-t.Y)<Math.abs(this.pan.startX-t.X)),this.debugger?.show&&(this.debugger.DOM.touch1.style.top=`${t.Y-10}px`,this.debugger.DOM.touch1.style.left=`${t.X-10}px`,this.debugger.DOM.touch1.innerText=`${t.X.toFixed(2)},${t.Y.toFixed(2)}`),this.dragState>0&&this.isScaled||this.dragState>1){if(this.dragState===1){const l={X:t.X-this.manager.width/2,Y:t.Y-this.manager.height/2};this.pan.translateX=(l.X-(this.pan.startX-this.manager.width/2))*1/this.scale,this.pan.translateY=(l.Y-(this.pan.startY-this.manager.height/2))*1/this.scale}else if(this.dragState===2){const l=this.coordinator.getTouchCenter(e);if(this.debugger?.show){this.debugger.DOM.center.style.top=`${l.Y-5}px`,this.debugger.DOM.center.style.left=`${l.X-5}px`,this.debugger.DOM.center.innerText=`${l.X.toFixed(2)},${l.Y.toFixed(2)}`;const b=this.coordinator.getBibiEventCoord(e,1);this.debugger.DOM.touch2.style.top=`${b.Y-10}px`,this.debugger.DOM.touch2.style.left=`${b.X-10}px`,this.debugger.DOM.touch2.innerText=`${b.X.toFixed(2)},${b.Y.toFixed(2)}`}l.X-=this.manager.width/2,l.Y-=this.manager.height/2;let c=-l.X/r;c+=l.X/this.scale,this.pinch.target.X+=c,l.X+=this.pinch.target.X*this.scale/this.pinch.startScale;let h=-l.Y/r;h+=l.Y/this.scale,this.pinch.target.Y+=h,l.Y+=this.pinch.target.Y*this.scale/this.pinch.startScale;let u=(l.X-(this.pan.startX-this.manager.width/2))*1/this.scale,m=(l.Y-(this.pan.startY-this.manager.height/2))*1/this.scale;this.pan.translateX=u,this.pan.translateY=m,this.debugger?.show&&(this.debugger.DOM.pinchTarget.style.left=`${this.pinch.target.X*this.scale/this.pinch.startScale-5+this.manager.width/2}px`,this.debugger.DOM.pinchTarget.style.top=`${this.pinch.target.Y*this.scale/this.pinch.startScale-5+this.manager.height/2}px`,this.debugger.DOM.pinchTarget.innerText=`${(this.pinch.target.X*this.scale/this.pinch.startScale).toFixed(2)},${(this.pinch.target.Y*this.scale/this.pinch.startScale).toFixed(2)}`)}const s=this.frameBounds.width/6,a=this.frameBounds.height/6;this.pan.translateX<-s&&(this.pan.overscrollX=-(s+this.pan.translateX),this.pan.translateX=-s),this.pan.translateY<-a&&(this.pan.overscrollY=-(a+this.pan.translateY),this.pan.translateY=-a),this.pan.translateX>s&&(this.pan.overscrollX=s-this.pan.translateX,this.pan.translateX=s),this.pan.translateY>a&&(this.pan.overscrollY=a-this.pan.translateY,this.pan.translateY=a),n=!0,this.debugger?.show&&(this.debugger.DOM.stats.innerText=`TX: ${this.pan.translateX.toFixed(2)}
|
|
404
404
|
TY: ${this.pan.translateY.toFixed(2)}
|
|
405
405
|
Zoom: ${this.scale.toFixed(2)}
|
|
406
406
|
Overscroll: ${this.pan.overscrollX.toFixed(2)},${this.pan.overscrollY.toFixed(2)}`)}if(n){this.manager.updateBookStyle();return}if(this.dragState>0&&this.pan.letItGo){this.pan.endX=t.X;const a=this.manager.currentSlide*(this.manager.width/this.manager.perPage),l=this.pan.endX-this.pan.startX,c=this.manager.rtl?a+l:a-l;cancelAnimationFrame(this.moveFrame),this.moveFrame=requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.manager.spineElement.style.transform=`translate3d(${(this.manager.rtl?1:-1)*c}px, 0, 0)`})})}}dblclickHandler(e){clearTimeout(this.dtimer),this.pdblclick=!0,this.dtimer=window.setTimeout(()=>this.pdblclick=!1,200),!this.disableDblClick&&this.isScaled&&(this.scale=1)}get isScaled(){return this.scale>1}addTouch(e){e.touches=[{pageX:e.pageX,pageY:e.pageY}]}mousedownHandler(e){this.isScaled&&(this.addTouch(e),this.touchstartHandler(e))}mouseupHandler(e){this.isScaled&&this.touchendHandler(e)}mousemoveHandler(e){this.isScaled&&e.buttons>0&&(e.preventDefault(),this.addTouch(e),this.touchmoveHandler(e))}updateAfterDrag(){const e=(this.manager.rtl?-1:1)*(this.pan.endX-this.pan.startX),t=Math.abs(e);e>0&&t>this.manager.threshold&&this.manager.slength>this.manager.perPage?this.manager.listener("no_less",void 0):e<0&&t>this.manager.threshold&&this.manager.slength>this.manager.perPage&&this.manager.listener("no_more",void 0),this.manager.slideToCurrent(!0,!0)}}var st=(o=>(o.auto="auto",o.landscape="landscape",o.portrait="portrait",o))(st||{}),at=(o=>(o.auto="auto",o.both="both",o.none="none",o.landscape="landscape",o))(at||{});class Cn{constructor(e){this.shift=!0,this.spreads=[],this.nLandscape=0,this.index(e),this.testShift(e),console.log(`Indexed ${this.spreads.length} spreads for ${e.readingOrder.items.length} items`)}index(e,t=!1){this.nLandscape=0,e.readingOrder.items.forEach((i,n)=>{t||(e.readingOrder.items[n]=i.addProperties({number:n+1,isImage:i.type?.indexOf("image/")===0}));const r=i.properties?.otherProperties.orientation==="landscape";(!i.properties?.page||t)&&(i.properties=i.properties?.add({page:r?"center":((this.shift?0:1)+n-this.nLandscape)%2?e.metadata.readingProgression===N.rtl?"right":"left":e.metadata.readingProgression===N.rtl?"left":"right"})),(r||i.properties?.otherProperties.addBlank)&&this.nLandscape++}),t&&(this.spreads=[]),this.buildSpreads(e.readingOrder)}testShift(e){let t=!1;this.spreads.forEach((i,n)=>{if(i.length>1)return;const r=i[0],s=r.properties?.otherProperties.orientation;n===0&&(s==="landscape"||s!=="portrait"&&((r.width||0)>(r.height||0)||r.properties?.otherProperties.spread==="both"))&&(this.shift=!1),t&&r.properties?.page===G.center&&this.spreads[n-1][0].addProperties({addBlank:!0}),s==="portrait"&&r.properties?.page!=="center"&&r.properties?.otherProperties.number>1?t=!0:t=!1}),this.shift||this.index(e,!0)}buildSpreads(e){let t=[];e.items.forEach((i,n)=>{!n&&this.shift?this.spreads.push([i]):i.properties?.page===G.center?(t.length>0&&this.spreads.push(t),this.spreads.push([i]),t=[]):t.length>=2?(this.spreads.push(t),t=[i]):t.push(i)}),t.length>0&&this.spreads.push(t)}currentSpread(e,t){return this.spreads[Math.min(Math.floor(e/t),this.spreads.length-1)]}findByLink(e){return this.spreads.find(t=>t.includes(e))||void 0}}const En=8,kn=5,Kr=300,Jr=15e3,Zr=250,Qr=150,eo=500;class xn{constructor(e,t,i,n,r,s){if(this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.delayedShow=new Map,this.delayedTimeout=new Map,this.previousFrames=[],this.injector=null,this.width=0,this.height=0,this.transform="",this.currentSlide=0,this.spread=!0,this.orientationInternal=-1,this.container=e,this.positions=t,this.pub=i,this.injector=n??null,this.contentProtectionConfig=r||{},this.keyboardPeripheralsConfig=s||[],this.spreadPresentation=i.metadata.otherMetadata?.spread||at.auto,this.pub.metadata.effectiveReadingProgression!==N.rtl&&this.pub.metadata.effectiveReadingProgression!==N.ltr)throw Error("Unsupported reading progression for EPUB");this.spreader=new Cn(this.pub),this.containerHeightCached=e.clientHeight,this.bookElement=document.createElement("div"),this.bookElement.ariaLabel="Book",this.bookElement.tabIndex=-1,this.updateBookStyle(!0),this.spineElement=document.createElement("div"),this.spineElement.ariaLabel="Spine",this.bookElement.appendChild(this.spineElement),this.container.appendChild(this.bookElement),this.updateSpineStyle(!0),this.peripherals=new Pn(this);const a=document.createDocumentFragment();this.pub.readingOrder.items.forEach(l=>{const c=new yn(this.peripherals,this.pub.metadata.effectiveReadingProgression,l.href,this.contentProtectionConfig,this.keyboardPeripheralsConfig);this.pool.set(l.href,c),c.width=100/this.length*(l.properties?.otherProperties.orientation===st.landscape||l.properties?.otherProperties.addBlank?this.perPage:1),c.height=this.height,a.appendChild(c.wrapper)}),this.spineElement.appendChild(a)}set listener(e){this._listener=e}get listener(){return this._listener}get doNotDisturb(){return this.peripherals.pan.touchID>0}resizeHandler(e=!0,t=!0){this.currentSlide+this.perPage>this.length&&(this.currentSlide=this.length<=this.perPage?0:this.length-1),this.containerHeightCached=this.container.clientHeight,this.orientationInternal=-1,this.updateSpineStyle(!0),e&&(this.currentSlide=this.reAlign(),this.slideToCurrent(!t,t)),clearTimeout(this.resizeTimeout),this.resizeTimeout=window.setTimeout(()=>{const i=100/this.length,n=new Map(this.pub.readingOrder.items.map(r=>[r.href,r]));this.pool.forEach((r,s)=>{const a=n.get(s);a&&requestAnimationFrame(()=>{if(r.width=i*(a.properties?.otherProperties.orientation===st.landscape||a.properties?.otherProperties.addBlank?this.perPage:1),r.height=this.height,!r.loaded)return;const l=this.spreader.findByLink(a);r.update(this.spreadPosition(l,a))})})},Zr)}updateDimensions(){this.width=this.bookElement.clientWidth,this.height=this.bookElement.clientHeight}get rtl(){return this.pub.metadata.effectiveReadingProgression===N.rtl}get single(){return!this.spread||this.portrait}get perPage(){return this.spread&&!this.portrait?2:1}get threshold(){return 50}get portrait(){return this.spreadPresentation===at.none?!0:(this.orientationInternal===-1&&(this.orientationInternal=this.containerHeightCached>this.container.clientWidth?1:0),this.orientationInternal===1)}updateSpineStyle(e,t=!0){let i="0";this.updateDimensions(),this.perPage>1&&(i=`${this.width/2}px`);const n={transition:e?`all ${t?Qr:eo}ms ease-out`:"all 0ms ease-out",marginRight:this.rtl?i:"0",marginLeft:this.rtl?"0":i,width:`${this.width/this.perPage*this.length}px`,transform:this.transform,contain:"content"};Object.assign(this.spineElement.style,n)}updateBookStyle(e=!1){if(e){const t={overflow:"hidden",direction:this.pub.metadata.effectiveReadingProgression,cursor:"",height:"100%",width:"100%",position:"relative",outline:"none",transition:this.peripherals?.dragState?"none":"transform .15s ease-in-out",touchAction:"none"};Object.assign(this.bookElement.style,t)}this.bookElement.style.transform=`scale(${this.peripherals?.scale||1})`+(this.peripherals?` translate3d(${this.peripherals.pan.translateX}px, ${this.peripherals.pan.translateY}px, 0px)`:"")}goTo(e){if(this.slength<=this.perPage)return;e=this.reAlign(e);const t=this.currentSlide;this.currentSlide=Math.min(Math.max(e,0),this.length-1),t!==this.currentSlide&&this.slideToCurrent(!1)}onChange(){this.peripherals.scale=1,this.updateBookStyle()}get offset(){return(this.rtl?1:-1)*this.currentSlide*(this.width/this.perPage)}get length(){if(this.single)return this.slength;const e=this.slength+this.nLandscape;return this.shift&&e%2===0?e+1:e}get slength(){return this.pub.readingOrder.items.length||0}get shift(){return this.spreader.shift}get nLandscape(){return this.spreader.nLandscape}setPerPage(e){e===null?this.spread=!0:e===1?this.spread=!1:this.spread=!0,requestAnimationFrame(()=>this.resizeHandler(!0))}slideToCurrent(e,t=!0){if(this.updateDimensions(),e)requestAnimationFrame(()=>{requestAnimationFrame(()=>{const i=`translate3d(${this.offset}px, 0, 0)`;this.spineElement.style.transform!==i&&(this.transform=i,this.updateSpineStyle(!0,t),this.deselect())})});else{const i=`translate3d(${this.offset}px, 0, 0)`;if(this.spineElement.style.transform===i)return;this.transform=i,this.updateSpineStyle(!1),this.deselect()}}bounce(e=!1){requestAnimationFrame(()=>{this.transform=`translate3d(${this.offset+50*(e?1:-1)}px, 0, 0)`,this.updateSpineStyle(!0,!0),setTimeout(()=>{this.transform=`translate3d(${this.offset}px, 0, 0)`,this.updateSpineStyle(!0,!0)},100)})}next(e=1){if(this.slength<=this.perPage)return!1;const t=this.currentSlide;return this.currentSlide=Math.min(this.currentSlide+e,this.length-1),this.perPage>1&&this.currentSlide%2&&this.currentSlide--,this.currentSlide===t&&(this.currentSlide+1,this.length),t!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(this.rtl),!1)}prev(e=1){if(this.slength<=this.perPage)return!1;const t=this.currentSlide;return this.currentSlide=Math.max(this.currentSlide-e,0),this.perPage>1&&this.currentSlide%2&&this.currentSlide++,t!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(!this.rtl),!1)}get ownerWindow(){return this.container.ownerDocument.defaultView||window}async destroy(){let e=this.inprogress.values(),t=e.next();const i=[];for(;t.value;)i.push(t.value),t=e.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let n=this.pool.values(),r=n.next();for(;r.value;)await r.value.destroy(),r=n.next();this.pool.clear(),this.blobs.forEach(s=>s.reset()),this.blobs.clear(),this.injector?.dispose(),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}makeSpread(e){return this.perPage<2?[this.pub.readingOrder.items[e]]:this.spreader.currentSpread(e,this.perPage)}reAlign(e=this.currentSlide){return e%2&&!this.single&&e++,e}spreadPosition(e,t){return this.perPage<2||e.length<2?G.center:t.href===e[0].href?this.rtl?G.right:G.left:this.rtl?G.left:G.right}async waitForItem(e){if(this.inprogress.has(e)&&await this.inprogress.get(e),this.delayedShow.has(e)){const t=this.delayedTimeout.get(e);t>0?clearTimeout(t):await this.delayedShow.get(e),this.delayedTimeout.set(e,0),this.delayedShow.delete(e)}}async cancelShowing(e){if(this.delayedShow.has(e)){const t=this.delayedTimeout.get(e);t>0&&clearTimeout(t),this.delayedShow.delete(e)}}async update(e,t,i,n=!1){let r=this.pub.readingOrder.items.findIndex(l=>l.href===t.href);if(r<0)throw Error("Href not found in reading order");this.currentSlide!==r&&(this.currentSlide=this.reAlign(r),this.slideToCurrent(!0));const s=this.makeSpread(this.currentSlide);this.perPage>1&&r++;for(const l of s)await this.waitForItem(l.href);const a=new Promise(async(l,c)=>{const h=[],u=[];this.positions.forEach((d,p)=>{(p>r+En||p<r-En)&&(h.includes(d.href)||h.push(d.href)),p<r+kn&&p>r-kn&&(u.includes(d.href)||u.push(d.href))}),h.forEach(async d=>{u.includes(d)||this.pool.has(d)&&(this.cancelShowing(d),await this.pool.get(d)?.unload(),this.blobs.get(d)?.reset())}),this.currentBaseURL!==void 0&&e.baseURL!==this.currentBaseURL&&(this.blobs.forEach(d=>d.reset()),this.blobs.clear()),this.currentBaseURL=e.baseURL;const m=async d=>{const p=e.readingOrder.findIndexWithHref(d),S=e.readingOrder.items[p];S&&(this.blobs.has(d)||this.blobs.set(d,new un(e,this.currentBaseURL||"",S,{injector:this.injector})),this.delayedShow.has(d)||this.delayedShow.set(d,new Promise((P,U)=>{let ne=!1;const go=window.setTimeout(async()=>{this.delayedTimeout.set(d,0);const fo=this.makeSpread(this.reAlign(p)),yo=this.spreadPosition(fo,S),In=this.pool.get(d);await In.load(i,await this.blobs.get(d).build(!0)),this.peripherals.isScaled||await In.show(yo),this.delayedShow.delete(d),ne=!0,P()},Kr);setTimeout(()=>{!ne&&this.delayedShow.has(d)&&U(`Offscreen load timeout: ${d}`)},Jr),this.delayedTimeout.set(d,go)})))};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const b=[];for(const d of s){const p=this.pool.get(d.href),S=this.blobs.get(d.href);S&&(this.cancelShowing(d.href),await p.load(i,await S.build(!0)),await p.show(this.spreadPosition(s,d)),this.previousFrames.push(p),await p.activate(),b.push(p))}for(;this.previousFrames.length>0;){const d=this.previousFrames.shift();d&&!b.includes(d)&&await d.unfocus()}this.previousFrames=b,l()});for(const l of s)this.inprogress.set(l.href,a);await a;for(const l of s)this.inprogress.delete(l.href)}get currentFrames(){if(this.perPage<2){const t=this.pub.readingOrder.items[this.currentSlide];return[this.pool.get(t.href)]}return this.spreader.currentSpread(this.currentSlide,this.perPage).map(t=>this.pool.get(t.href))}get currentBounds(){const e={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(t=>{if(!t)return;const i=t.realSize;e.x=Math.min(e.x,i.x),e.y=Math.min(e.y,i.y),e.width+=i.width,e.height=Math.max(e.height,i.height),e.top=Math.min(e.top,i.top),e.right=Math.min(e.right,i.right),e.bottom=Math.min(e.bottom,i.bottom),e.left=Math.min(e.left,i.left)}),e}get viewport(){const e={readingOrder:[],progressions:new Map,positions:null};return this.spreader.currentSpread(this.currentSlide,this.perPage).forEach(i=>{e.readingOrder.push(i.href),e.progressions.set(i.href,{start:0,end:1})}),e.positions=this.getCurrentNumbers(),e}getCurrentNumbers(){if(this.perPage<2)return[this.pub.readingOrder.items[this.currentSlide].properties?.otherProperties.number];const e=this.spreader.currentSpread(this.currentSlide,this.perPage);return e.length>1?[e[0].properties?.otherProperties.number,e[e.length-1].properties?.otherProperties.number]:[e[0].properties?.otherProperties.number]}deselect(){this.currentFrames?.forEach(e=>e?.deselect())}}class Se{constructor(e={}){this.backgroundColor=M(e.backgroundColor),this.blendFilter=C(e.blendFilter),this.constraint=_(e.constraint),this.columnCount=_(e.columnCount),this.darkenFilter=le(e.darkenFilter),this.deprecatedFontSize=C(e.deprecatedFontSize),this.fontFamily=M(e.fontFamily),this.fontSize=q(e.fontSize,xe.range),this.fontSizeNormalize=C(e.fontSizeNormalize),this.fontOpticalSizing=C(e.fontOpticalSizing),this.fontWeight=q(e.fontWeight,Z.range),this.fontWidth=q(e.fontWidth,Re.range),this.hyphens=C(e.hyphens),this.invertFilter=le(e.invertFilter),this.invertGaijiFilter=le(e.invertGaijiFilter),this.iOSPatch=C(e.iOSPatch),this.iPadOSPatch=C(e.iPadOSPatch),this.letterSpacing=_(e.letterSpacing),this.ligatures=C(e.ligatures),this.lineHeight=_(e.lineHeight),this.linkColor=M(e.linkColor),this.noRuby=C(e.noRuby),this.pageGutter=_(e.pageGutter),this.paragraphIndent=_(e.paragraphIndent),this.paragraphSpacing=_(e.paragraphSpacing),this.scroll=C(e.scroll),this.scrollPaddingTop=_(e.scrollPaddingTop),this.scrollPaddingBottom=_(e.scrollPaddingBottom),this.scrollPaddingLeft=_(e.scrollPaddingLeft),this.scrollPaddingRight=_(e.scrollPaddingRight),this.selectionBackgroundColor=M(e.selectionBackgroundColor),this.selectionTextColor=M(e.selectionTextColor),this.textAlign=Fe(e.textAlign,K),this.textColor=M(e.textColor),this.textNormalization=C(e.textNormalization),this.visitedColor=M(e.visitedColor),this.wordSpacing=_(e.wordSpacing),this.optimalLineLength=_(e.optimalLineLength),this.maximalLineLength=_(e.maximalLineLength),this.minimalLineLength=_(e.minimalLineLength)}static serialize(e){const{...t}=e;return JSON.stringify(t)}static deserialize(e){try{const t=JSON.parse(e);return new Se(t)}catch(t){return console.error("Failed to deserialize preferences:",t),null}}merging(e){const t={...this};for(const i of Object.keys(e))e[i]!==void 0&&(i!=="maximalLineLength"||e[i]===null||e[i]>=(e.optimalLineLength??t.optimalLineLength??65))&&(i!=="minimalLineLength"||e[i]===null||e[i]<=(e.optimalLineLength??t.optimalLineLength??65))&&(t[i]=e[i]);return new Se(t)}}class Rn{constructor(e){this.backgroundColor=M(e.backgroundColor)||null,this.blendFilter=C(e.blendFilter)??!1,this.constraint=_(e.constraint)||0,this.columnCount=_(e.columnCount)||null,this.darkenFilter=le(e.darkenFilter)??!1,this.deprecatedFontSize=C(e.deprecatedFontSize),(this.deprecatedFontSize===!1||this.deprecatedFontSize===null)&&(this.deprecatedFontSize=!CSS.supports("zoom","1")),this.fontFamily=M(e.fontFamily)||null,this.fontSize=q(e.fontSize,xe.range)||1,this.fontSizeNormalize=C(e.fontSizeNormalize)??!1,this.fontOpticalSizing=C(e.fontOpticalSizing)??null,this.fontWeight=q(e.fontWeight,Z.range)||null,this.fontWidth=q(e.fontWidth,Re.range)||null,this.hyphens=C(e.hyphens)??null,this.invertFilter=le(e.invertFilter)??!1,this.invertGaijiFilter=le(e.invertGaijiFilter)??!1,this.iOSPatch=e.iOSPatch===!1?!1:(L.OS.iOS||L.OS.iPadOS)&&L.iOSRequest==="mobile",this.iPadOSPatch=e.iPadOSPatch===!1?!1:L.OS.iPadOS&&L.iOSRequest==="desktop",this.letterSpacing=_(e.letterSpacing)||null,this.ligatures=C(e.ligatures)??null,this.lineHeight=_(e.lineHeight)||null,this.linkColor=M(e.linkColor)||null,this.noRuby=C(e.noRuby)??!1,this.pageGutter=nt(_(e.pageGutter),20),this.paragraphIndent=_(e.paragraphIndent)??null,this.paragraphSpacing=_(e.paragraphSpacing)??null,this.scroll=C(e.scroll)??!1,this.scrollPaddingTop=_(e.scrollPaddingTop)??null,this.scrollPaddingBottom=_(e.scrollPaddingBottom)??null,this.scrollPaddingLeft=_(e.scrollPaddingLeft)??null,this.scrollPaddingRight=_(e.scrollPaddingRight)??null,this.selectionBackgroundColor=M(e.selectionBackgroundColor)||null,this.selectionTextColor=M(e.selectionTextColor)||null,this.textAlign=Fe(e.textAlign,K)||null,this.textColor=M(e.textColor)||null,this.textNormalization=C(e.textNormalization)??!1,this.visitedColor=M(e.visitedColor)||null,this.wordSpacing=_(e.wordSpacing)||null,this.optimalLineLength=_(e.optimalLineLength)||65,this.maximalLineLength=nt(Qi(e.maximalLineLength,this.optimalLineLength),80),this.minimalLineLength=nt(Zi(e.minimalLineLength,this.optimalLineLength),40),this.experiments=It(e.experiments)||null}}const _e={RS__backgroundColor:"#FFFFFF",RS__textColor:"#121212",RS__linkColor:"#0000EE",RS__visitedColor:"#551A8B",RS__selectionBackgroundColor:"#b4d8fe",RS__selectionTextColor:"inherit"};class jt{constructor(e,t,i){this.preferences=e,this.settings=t,this.metadata=i,this.layout=this.metadata?.effectiveLayout||v.reflowable}clear(){this.preferences=new Se({optimalLineLength:65})}updatePreference(e,t){this.preferences[e]=t}get backgroundColor(){return new O({initialValue:this.preferences.backgroundColor,effectiveValue:this.settings.backgroundColor||_e.RS__backgroundColor,isEffective:this.preferences.backgroundColor!==null,onChange:e=>{this.updatePreference("backgroundColor",e||null)}})}get blendFilter(){return new z({initialValue:this.preferences.blendFilter,effectiveValue:this.settings.blendFilter||!1,isEffective:this.preferences.blendFilter!==null,onChange:e=>{this.updatePreference("blendFilter",e||null)}})}get columnCount(){return new O({initialValue:this.preferences.columnCount,effectiveValue:this.settings.columnCount||null,isEffective:this.layout!==v.fixed&&!this.settings.scroll,onChange:e=>{this.updatePreference("columnCount",e||null)}})}get constraint(){return new O({initialValue:this.preferences.constraint,effectiveValue:this.preferences.constraint||0,isEffective:!0,onChange:e=>{this.updatePreference("constraint",e||null)}})}get darkenFilter(){return new R({initialValue:typeof this.preferences.darkenFilter=="boolean"?100:this.preferences.darkenFilter,effectiveValue:typeof this.settings.darkenFilter=="boolean"?100:this.settings.darkenFilter||0,isEffective:this.settings.darkenFilter!==null,onChange:e=>{this.updatePreference("darkenFilter",e||null)},supportedRange:se.range,step:se.step})}get deprecatedFontSize(){return new z({initialValue:this.preferences.deprecatedFontSize,effectiveValue:CSS.supports("zoom","1")?this.settings.deprecatedFontSize||!1:!0,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("deprecatedFontSize",e||null)}})}get fontFamily(){return new O({initialValue:this.preferences.fontFamily,effectiveValue:this.settings.fontFamily||null,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("fontFamily",e||null)}})}get fontSize(){return new R({initialValue:this.preferences.fontSize,effectiveValue:this.settings.fontSize||1,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("fontSize",e||null)},supportedRange:xe.range,step:xe.step})}get fontSizeNormalize(){return new z({initialValue:this.preferences.fontSizeNormalize,effectiveValue:this.settings.fontSizeNormalize||!1,isEffective:this.layout!==v.fixed&&this.preferences.fontSizeNormalize!==null,onChange:e=>{this.updatePreference("fontSizeNormalize",e||null)}})}get fontOpticalSizing(){return new z({initialValue:this.preferences.fontOpticalSizing,effectiveValue:this.settings.fontOpticalSizing||!0,isEffective:this.layout!==v.fixed&&this.preferences.fontOpticalSizing!==null,onChange:e=>{this.updatePreference("fontOpticalSizing",e||null)}})}get fontWeight(){return new R({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.layout!==v.fixed&&this.preferences.fontWeight!==null,onChange:e=>{this.updatePreference("fontWeight",e||null)},supportedRange:Z.range,step:Z.step})}get fontWidth(){return new R({initialValue:this.preferences.fontWidth,effectiveValue:this.settings.fontWidth||100,isEffective:this.layout!==v.fixed&&this.preferences.fontWidth!==null,onChange:e=>{this.updatePreference("fontWidth",e||null)},supportedRange:Re.range,step:Re.step})}get hyphens(){return new z({initialValue:this.preferences.hyphens,effectiveValue:this.settings.hyphens||!1,isEffective:this.layout!==v.fixed&&this.metadata?.effectiveReadingProgression===N.ltr&&this.preferences.hyphens!==null,onChange:e=>{this.updatePreference("hyphens",e||null)}})}get invertFilter(){return new R({initialValue:typeof this.preferences.invertFilter=="boolean"?100:this.preferences.invertFilter,effectiveValue:typeof this.settings.invertFilter=="boolean"?100:this.settings.invertFilter||0,isEffective:this.settings.invertFilter!==null,onChange:e=>{this.updatePreference("invertFilter",e||null)},supportedRange:se.range,step:se.step})}get invertGaijiFilter(){return new R({initialValue:typeof this.preferences.invertGaijiFilter=="boolean"?100:this.preferences.invertGaijiFilter,effectiveValue:typeof this.settings.invertGaijiFilter=="boolean"?100:this.settings.invertGaijiFilter||0,isEffective:this.preferences.invertGaijiFilter!==null,onChange:e=>{this.updatePreference("invertGaijiFilter",e||null)},supportedRange:se.range,step:se.step})}get iOSPatch(){return new z({initialValue:this.preferences.iOSPatch,effectiveValue:this.settings.iOSPatch||!1,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("iOSPatch",e||null)}})}get iPadOSPatch(){return new z({initialValue:this.preferences.iPadOSPatch,effectiveValue:this.settings.iPadOSPatch||!1,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("iPadOSPatch",e||null)}})}get letterSpacing(){return new R({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.layout!==v.fixed&&this.preferences.letterSpacing!==null,onChange:e=>{this.updatePreference("letterSpacing",e||null)},supportedRange:Le.range,step:Le.step})}get ligatures(){return new z({initialValue:this.preferences.ligatures,effectiveValue:this.settings.ligatures||!0,isEffective:(()=>{if(this.preferences.ligatures===null||this.layout===v.fixed)return!1;const e=this.metadata?.languages?.[0]?.toLowerCase();return!(e&&["zh","ja","ko","mn-mong"].some(t=>e.startsWith(t)))})(),onChange:e=>{this.updatePreference("ligatures",e||null)}})}get lineHeight(){return new R({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.layout!==v.fixed&&this.preferences.lineHeight!==null,onChange:e=>{this.updatePreference("lineHeight",e||null)},supportedRange:Ae.range,step:Ae.step})}get linkColor(){return new O({initialValue:this.preferences.linkColor,effectiveValue:this.settings.linkColor||_e.RS__linkColor,isEffective:this.layout!==v.fixed&&this.preferences.linkColor!==null,onChange:e=>{this.updatePreference("linkColor",e||null)}})}get maximalLineLength(){return new R({initialValue:this.preferences.maximalLineLength,effectiveValue:this.settings.maximalLineLength,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("maximalLineLength",e)},supportedRange:ae.range,step:ae.step})}get minimalLineLength(){return new R({initialValue:this.preferences.minimalLineLength,effectiveValue:this.settings.minimalLineLength,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("minimalLineLength",e)},supportedRange:ae.range,step:ae.step})}get noRuby(){return new z({initialValue:this.preferences.noRuby,effectiveValue:this.settings.noRuby||!1,isEffective:this.layout!==v.fixed&&this.metadata?.languages?.includes("ja")||!1,onChange:e=>{this.updatePreference("noRuby",e||null)}})}get optimalLineLength(){return new R({initialValue:this.preferences.optimalLineLength,effectiveValue:this.settings.optimalLineLength,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("optimalLineLength",e)},supportedRange:ae.range,step:ae.step})}get pageGutter(){return new O({initialValue:this.preferences.pageGutter,effectiveValue:this.settings.pageGutter,isEffective:this.layout!==v.fixed&&!this.settings.scroll,onChange:e=>{this.updatePreference("pageGutter",e||null)}})}get paragraphIndent(){return new R({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.layout!==v.fixed&&this.preferences.paragraphIndent!==null,onChange:e=>{this.updatePreference("paragraphIndent",e||null)},supportedRange:Oe.range,step:Oe.step})}get paragraphSpacing(){return new R({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.layout!==v.fixed&&this.preferences.paragraphSpacing!==null,onChange:e=>{this.updatePreference("paragraphSpacing",e||null)},supportedRange:Te.range,step:Te.step})}get scroll(){return new z({initialValue:this.preferences.scroll,effectiveValue:this.settings.scroll||!1,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("scroll",e||null)}})}get scrollPaddingTop(){return new O({initialValue:this.preferences.scrollPaddingTop,effectiveValue:this.settings.scrollPaddingTop||0,isEffective:this.layout!==v.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingTop!==null,onChange:e=>{this.updatePreference("scrollPaddingTop",e||null)}})}get scrollPaddingBottom(){return new O({initialValue:this.preferences.scrollPaddingBottom,effectiveValue:this.settings.scrollPaddingBottom||0,isEffective:this.layout!==v.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingBottom!==null,onChange:e=>{this.updatePreference("scrollPaddingBottom",e||null)}})}get scrollPaddingLeft(){return new O({initialValue:this.preferences.scrollPaddingLeft,effectiveValue:this.settings.scrollPaddingLeft||0,isEffective:this.layout!==v.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingLeft!==null,onChange:e=>{this.updatePreference("scrollPaddingLeft",e||null)}})}get scrollPaddingRight(){return new O({initialValue:this.preferences.scrollPaddingRight,effectiveValue:this.settings.scrollPaddingRight||0,isEffective:this.layout!==v.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingRight!==null,onChange:e=>{this.updatePreference("scrollPaddingRight",e||null)}})}get selectionBackgroundColor(){return new O({initialValue:this.preferences.selectionBackgroundColor,effectiveValue:this.settings.selectionBackgroundColor||_e.RS__selectionBackgroundColor,isEffective:this.layout!==v.fixed&&this.preferences.selectionBackgroundColor!==null,onChange:e=>{this.updatePreference("selectionBackgroundColor",e||null)}})}get selectionTextColor(){return new O({initialValue:this.preferences.selectionTextColor,effectiveValue:this.settings.selectionTextColor||_e.RS__selectionTextColor,isEffective:this.layout!==v.fixed&&this.preferences.selectionTextColor!==null,onChange:e=>{this.updatePreference("selectionTextColor",e||null)}})}get textAlign(){return new Dt({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||K.start,isEffective:this.layout!==v.fixed&&this.preferences.textAlign!==null,onChange:e=>{this.updatePreference("textAlign",e||null)},supportedValues:Object.values(K)})}get textColor(){return new O({initialValue:this.preferences.textColor,effectiveValue:this.settings.textColor||_e.RS__textColor,isEffective:this.layout!==v.fixed&&this.preferences.textColor!==null,onChange:e=>{this.updatePreference("textColor",e||null)}})}get textNormalization(){return new z({initialValue:this.preferences.textNormalization,effectiveValue:this.settings.textNormalization||!1,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("textNormalization",e||null)}})}get visitedColor(){return new O({initialValue:this.preferences.visitedColor,effectiveValue:this.settings.visitedColor||_e.RS__visitedColor,isEffective:this.layout!==v.fixed&&this.preferences.visitedColor!==null,onChange:e=>{this.updatePreference("visitedColor",e||null)}})}get wordSpacing(){return new R({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.layout!==v.fixed&&this.preferences.wordSpacing!==null,onChange:e=>{this.updatePreference("wordSpacing",e||null)},supportedRange:ze.range,step:ze.step})}}class Gt{constructor(e,t){this.backgroundColor=e.backgroundColor||t.backgroundColor||null,this.blendFilter=typeof e.blendFilter=="boolean"?e.blendFilter:t.blendFilter??null,this.columnCount=e.columnCount!==void 0?e.columnCount:t.columnCount!==void 0?t.columnCount:null,this.constraint=e.constraint||t.constraint,this.darkenFilter=typeof e.darkenFilter=="boolean"?e.darkenFilter:t.darkenFilter??null,this.deprecatedFontSize=typeof e.deprecatedFontSize=="boolean"?e.deprecatedFontSize:t.deprecatedFontSize??null,this.fontFamily=e.fontFamily||t.fontFamily||null,this.fontSize=e.fontSize!==void 0?e.fontSize:t.fontSize!==void 0?t.fontSize:null,this.fontSizeNormalize=typeof e.fontSizeNormalize=="boolean"?e.fontSizeNormalize:t.fontSizeNormalize??null,this.fontOpticalSizing=typeof e.fontOpticalSizing=="boolean"?e.fontOpticalSizing:t.fontOpticalSizing??null,this.fontWeight=e.fontWeight!==void 0?e.fontWeight:t.fontWeight!==void 0?t.fontWeight:null,this.fontWidth=e.fontWidth!==void 0?e.fontWidth:t.fontWidth!==void 0?t.fontWidth:null,this.hyphens=typeof e.hyphens=="boolean"?e.hyphens:t.hyphens??null,this.invertFilter=typeof e.invertFilter=="boolean"?e.invertFilter:t.invertFilter??null,this.invertGaijiFilter=typeof e.invertGaijiFilter=="boolean"?e.invertGaijiFilter:t.invertGaijiFilter??null,this.iOSPatch=this.deprecatedFontSize||e.iOSPatch===!1?!1:e.iOSPatch===!0?(L.OS.iOS||L.OS.iPadOS)&&L.iOSRequest==="mobile":t.iOSPatch,this.iPadOSPatch=this.deprecatedFontSize||e.iPadOSPatch===!1?!1:e.iPadOSPatch===!0?L.OS.iPadOS&&L.iOSRequest==="desktop":t.iPadOSPatch,this.letterSpacing=e.letterSpacing!==void 0?e.letterSpacing:t.letterSpacing!==void 0?t.letterSpacing:null,this.ligatures=typeof e.ligatures=="boolean"?e.ligatures:t.ligatures??null,this.lineHeight=e.lineHeight!==void 0?e.lineHeight:t.lineHeight!==void 0?t.lineHeight:null,this.linkColor=e.linkColor||t.linkColor||null,this.maximalLineLength=e.maximalLineLength===null?null:e.maximalLineLength||t.maximalLineLength||null,this.minimalLineLength=e.minimalLineLength===null?null:e.minimalLineLength||t.minimalLineLength||null,this.noRuby=typeof e.noRuby=="boolean"?e.noRuby:t.noRuby??null,this.optimalLineLength=e.optimalLineLength||t.optimalLineLength,this.pageGutter=e.pageGutter!==void 0?e.pageGutter:t.pageGutter!==void 0?t.pageGutter:null,this.paragraphIndent=e.paragraphIndent!==void 0?e.paragraphIndent:t.paragraphIndent!==void 0?t.paragraphIndent:null,this.paragraphSpacing=e.paragraphSpacing!==void 0?e.paragraphSpacing:t.paragraphSpacing!==void 0?t.paragraphSpacing:null,this.scroll=typeof e.scroll=="boolean"?e.scroll:t.scroll??null,this.scrollPaddingTop=e.scrollPaddingTop!==void 0?e.scrollPaddingTop:t.scrollPaddingTop!==void 0?t.scrollPaddingTop:null,this.scrollPaddingBottom=e.scrollPaddingBottom!==void 0?e.scrollPaddingBottom:t.scrollPaddingBottom!==void 0?t.scrollPaddingBottom:null,this.scrollPaddingLeft=e.scrollPaddingLeft!==void 0?e.scrollPaddingLeft:t.scrollPaddingLeft!==void 0?t.scrollPaddingLeft:null,this.scrollPaddingRight=e.scrollPaddingRight!==void 0?e.scrollPaddingRight:t.scrollPaddingRight!==void 0?t.scrollPaddingRight:null,this.selectionBackgroundColor=e.selectionBackgroundColor||t.selectionBackgroundColor||null,this.selectionTextColor=e.selectionTextColor||t.selectionTextColor||null,this.textAlign=e.textAlign||t.textAlign||null,this.textColor=e.textColor||t.textColor||null,this.textNormalization=typeof e.textNormalization=="boolean"?e.textNormalization:t.textNormalization??null,this.visitedColor=e.visitedColor||t.visitedColor||null,this.wordSpacing=e.wordSpacing!==void 0?e.wordSpacing:t.wordSpacing!==void 0?t.wordSpacing:null,this.experiments=t.experiments||null}}function lt(o){const e=getComputedStyle(o),t=parseFloat(e.paddingLeft||"0"),i=parseFloat(e.paddingRight||"0");return o.clientWidth-t-i}class Xt extends Ne{constructor(e){super(),this.a11yNormalize=e.a11yNormalize??null,this.backgroundColor=e.backgroundColor??null,this.blendFilter=e.blendFilter??null,this.bodyHyphens=e.bodyHyphens??null,this.colCount=e.colCount??null,this.darkenFilter=e.darkenFilter??null,this.deprecatedFontSize=e.deprecatedFontSize??null,this.fontFamily=e.fontFamily??null,this.fontOpticalSizing=e.fontOpticalSizing??null,this.fontSize=e.fontSize??null,this.fontSizeNormalize=e.fontSizeNormalize??null,this.fontWeight=e.fontWeight??null,this.fontWidth=e.fontWidth??null,this.invertFilter=e.invertFilter??null,this.invertGaijiFilter=e.invertGaijiFilter??null,this.iOSPatch=e.iOSPatch??null,this.iPadOSPatch=e.iPadOSPatch??null,this.letterSpacing=e.letterSpacing??null,this.ligatures=e.ligatures??null,this.lineHeight=e.lineHeight??null,this.lineLength=e.lineLength??null,this.linkColor=e.linkColor??null,this.noRuby=e.noRuby??null,this.paraIndent=e.paraIndent??null,this.paraSpacing=e.paraSpacing??null,this.selectionBackgroundColor=e.selectionBackgroundColor??null,this.selectionTextColor=e.selectionTextColor??null,this.textAlign=e.textAlign??null,this.textColor=e.textColor??null,this.view=e.view??null,this.visitedColor=e.visitedColor??null,this.wordSpacing=e.wordSpacing??null}toCSSProperties(){const e={};return this.a11yNormalize&&(e["--USER__a11yNormalize"]=this.toFlag("a11y")),this.backgroundColor&&(e["--USER__backgroundColor"]=this.backgroundColor),this.blendFilter&&(e["--USER__blendFilter"]=this.toFlag("blend")),this.bodyHyphens&&(e["--USER__bodyHyphens"]=this.bodyHyphens),this.colCount&&(e["--USER__colCount"]=this.toUnitless(this.colCount)),this.darkenFilter===!0?e["--USER__darkenFilter"]=this.toFlag("darken"):typeof this.darkenFilter=="number"&&(e["--USER__darkenFilter"]=this.toPercentage(this.darkenFilter)),this.deprecatedFontSize&&(e["--USER__fontSizeImplementation"]=this.toFlag("deprecatedFontSize")),this.fontFamily&&(e["--USER__fontFamily"]=this.fontFamily),this.fontOpticalSizing!=null&&(e["--USER__fontOpticalSizing"]=this.fontOpticalSizing),this.fontSize!=null&&(e["--USER__fontSize"]=this.toPercentage(this.fontSize,!0)),this.fontSizeNormalize&&(e["--USER__fontSizeNormalize"]=this.toFlag("normalize")),this.fontWeight!=null&&(e["--USER__fontWeight"]=this.toUnitless(this.fontWeight)),this.fontWidth!=null&&(e["--USER__fontWidth"]=typeof this.fontWidth=="string"?this.fontWidth:this.toUnitless(this.fontWidth)),this.invertFilter===!0?e["--USER__invertFilter"]=this.toFlag("invert"):typeof this.invertFilter=="number"&&(e["--USER__invertFilter"]=this.toPercentage(this.invertFilter)),this.invertGaijiFilter===!0?e["--USER__invertGaiji"]=this.toFlag("invertGaiji"):typeof this.invertGaijiFilter=="number"&&(e["--USER__invertGaiji"]=this.toPercentage(this.invertGaijiFilter)),this.iOSPatch&&(e["--USER__iOSPatch"]=this.toFlag("iOSPatch")),this.iPadOSPatch&&(e["--USER__iPadOSPatch"]=this.toFlag("iPadOSPatch")),this.letterSpacing!=null&&(e["--USER__letterSpacing"]=this.toRem(this.letterSpacing)),this.ligatures&&(e["--USER__ligatures"]=this.ligatures),this.lineHeight!=null&&(e["--USER__lineHeight"]=this.toUnitless(this.lineHeight)),this.lineLength!=null&&(e["--USER__lineLength"]=this.toPx(this.lineLength)),this.linkColor&&(e["--USER__linkColor"]=this.linkColor),this.noRuby&&(e["--USER__noRuby"]=this.toFlag("noRuby")),this.paraIndent!=null&&(e["--USER__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(e["--USER__paraSpacing"]=this.toRem(this.paraSpacing)),this.selectionBackgroundColor&&(e["--USER__selectionBackgroundColor"]=this.selectionBackgroundColor),this.selectionTextColor&&(e["--USER__selectionTextColor"]=this.selectionTextColor),this.textAlign&&(e["--USER__textAlign"]=this.textAlign),this.textColor&&(e["--USER__textColor"]=this.textColor),this.view&&(e["--USER__view"]=this.toFlag(this.view)),this.visitedColor&&(e["--USER__visitedColor"]=this.visitedColor),this.wordSpacing!=null&&(e["--USER__wordSpacing"]=this.toRem(this.wordSpacing)),e}}class Ln extends Ne{constructor(e){super(),this.backgroundColor=e.backgroundColor??null,this.baseFontFamily=e.baseFontFamily??null,this.baseFontSize=e.baseFontSize??null,this.baseLineHeight=e.baseLineHeight??null,this.boxSizingMedia=e.boxSizingMedia??null,this.boxSizingTable=e.boxSizingTable??null,this.colWidth=e.colWidth??null,this.colCount=e.colCount??null,this.colGap=e.colGap??null,this.codeFontFamily=e.codeFontFamily??null,this.compFontFamily=e.compFontFamily??null,this.defaultLineLength=e.defaultLineLength??null,this.flowSpacing=e.flowSpacing??null,this.humanistTf=e.humanistTf??null,this.linkColor=e.linkColor??null,this.maxMediaWidth=e.maxMediaWidth??null,this.maxMediaHeight=e.maxMediaHeight??null,this.modernTf=e.modernTf??null,this.monospaceTf=e.monospaceTf??null,this.noOverflow=e.noOverflow??null,this.noVerticalPagination=e.noVerticalPagination??null,this.oldStyleTf=e.oldStyleTf??null,this.pageGutter=e.pageGutter??null,this.paraIndent=e.paraIndent??null,this.paraSpacing=e.paraSpacing??null,this.primaryColor=e.primaryColor??null,this.scrollPaddingBottom=e.scrollPaddingBottom??null,this.scrollPaddingLeft=e.scrollPaddingLeft??null,this.scrollPaddingRight=e.scrollPaddingRight??null,this.scrollPaddingTop=e.scrollPaddingTop??null,this.sansSerifJa=e.sansSerifJa??null,this.sansSerifJaV=e.sansSerifJaV??null,this.sansTf=e.sansTf??null,this.secondaryColor=e.secondaryColor??null,this.selectionBackgroundColor=e.selectionBackgroundColor??null,this.selectionTextColor=e.selectionTextColor??null,this.serifJa=e.serifJa??null,this.serifJaV=e.serifJaV??null,this.textColor=e.textColor??null,this.typeScale=e.typeScale??null,this.visitedColor=e.visitedColor??null,this.experiments=e.experiments??null}toCSSProperties(){const e={};return this.backgroundColor&&(e["--RS__backgroundColor"]=this.backgroundColor),this.baseFontFamily&&(e["--RS__baseFontFamily"]=this.baseFontFamily),this.baseFontSize!=null&&(e["--RS__baseFontSize"]=this.toRem(this.baseFontSize)),this.baseLineHeight!=null&&(e["--RS__baseLineHeight"]=this.toUnitless(this.baseLineHeight)),this.boxSizingMedia&&(e["--RS__boxSizingMedia"]=this.boxSizingMedia),this.boxSizingTable&&(e["--RS__boxSizingTable"]=this.boxSizingTable),this.colWidth!=null&&(e["--RS__colWidth"]=this.colWidth),this.colCount!=null&&(e["--RS__colCount"]=this.toUnitless(this.colCount)),this.colGap!=null&&(e["--RS__colGap"]=this.toPx(this.colGap)),this.codeFontFamily&&(e["--RS__codeFontFamily"]=this.codeFontFamily),this.compFontFamily&&(e["--RS__compFontFamily"]=this.compFontFamily),this.defaultLineLength!=null&&(e["--RS__defaultLineLength"]=this.toPx(this.defaultLineLength)),this.flowSpacing!=null&&(e["--RS__flowSpacing"]=this.toRem(this.flowSpacing)),this.humanistTf&&(e["--RS__humanistTf"]=this.humanistTf),this.linkColor&&(e["--RS__linkColor"]=this.linkColor),this.maxMediaWidth&&(e["--RS__maxMediaWidth"]=this.toVw(this.maxMediaWidth)),this.maxMediaHeight&&(e["--RS__maxMediaHeight"]=this.toVh(this.maxMediaHeight)),this.modernTf&&(e["--RS__modernTf"]=this.modernTf),this.monospaceTf&&(e["--RS__monospaceTf"]=this.monospaceTf),this.noOverflow&&(e["--RS__disableOverflow"]=this.toFlag("noOverflow")),this.noVerticalPagination&&(e["--RS__disablePagination"]=this.toFlag("noVerticalPagination")),this.oldStyleTf&&(e["--RS__oldStyleTf"]=this.oldStyleTf),this.pageGutter!=null&&(e["--RS__pageGutter"]=this.toPx(this.pageGutter)),this.paraIndent!=null&&(e["--RS__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(e["--RS__paraSpacing"]=this.toRem(this.paraSpacing)),this.primaryColor&&(e["--RS__primaryColor"]=this.primaryColor),this.sansSerifJa&&(e["--RS__sans-serif-ja"]=this.sansSerifJa),this.sansSerifJaV&&(e["--RS__sans-serif-ja-v"]=this.sansSerifJaV),this.sansTf&&(e["--RS__sansTf"]=this.sansTf),this.scrollPaddingBottom!=null&&(e["--RS__scrollPaddingBottom"]=this.toPx(this.scrollPaddingBottom)),this.scrollPaddingLeft!=null&&(e["--RS__scrollPaddingLeft"]=this.toPx(this.scrollPaddingLeft)),this.scrollPaddingRight!=null&&(e["--RS__scrollPaddingRight"]=this.toPx(this.scrollPaddingRight)),this.scrollPaddingTop!=null&&(e["--RS__scrollPaddingTop"]=this.toPx(this.scrollPaddingTop)),this.secondaryColor&&(e["--RS__secondaryColor"]=this.secondaryColor),this.selectionBackgroundColor&&(e["--RS__selectionBackgroundColor"]=this.selectionBackgroundColor),this.selectionTextColor&&(e["--RS__selectionTextColor"]=this.selectionTextColor),this.serifJa&&(e["--RS__serif-ja"]=this.serifJa),this.serifJaV&&(e["--RS__serif-ja-v"]=this.serifJaV),this.textColor&&(e["--RS__textColor"]=this.textColor),this.typeScale&&(e["--RS__typeScale"]=this.toUnitless(this.typeScale)),this.visitedColor&&(e["--RS__visitedColor"]=this.visitedColor),this.experiments&&this.experiments.forEach(t=>{e["--RS__"+t]=it[t].value}),e}}class An{constructor(e){this.rsProperties=e.rsProperties,this.userProperties=e.userProperties,this.lineLengths=e.lineLengths,this.container=e.container,this.containerParent=e.container.parentElement||document.documentElement,this.constraint=e.constraint,this.cachedColCount=e.userProperties.colCount,this.effectiveContainerWidth=lt(this.containerParent)}update(e){this.cachedColCount=e.columnCount,e.constraint!==this.constraint&&(this.constraint=e.constraint),e.pageGutter!==this.rsProperties.pageGutter&&(this.rsProperties.pageGutter=e.pageGutter),e.scrollPaddingBottom!==this.rsProperties.scrollPaddingBottom&&(this.rsProperties.scrollPaddingBottom=e.scrollPaddingBottom),e.scrollPaddingLeft!==this.rsProperties.scrollPaddingLeft&&(this.rsProperties.scrollPaddingLeft=e.scrollPaddingLeft),e.scrollPaddingRight!==this.rsProperties.scrollPaddingRight&&(this.rsProperties.scrollPaddingRight=e.scrollPaddingRight),e.scrollPaddingTop!==this.rsProperties.scrollPaddingTop&&(this.rsProperties.scrollPaddingTop=e.scrollPaddingTop),e.experiments!==this.rsProperties.experiments&&(this.rsProperties.experiments=e.experiments),this.lineLengths.update({fontFace:e.fontFamily,letterSpacing:e.letterSpacing,padding:e.scroll?(e.scrollPaddingLeft||0)+(e.scrollPaddingRight||0):(e.pageGutter||0)*2,wordSpacing:e.wordSpacing,optimalChars:e.optimalLineLength,minChars:e.minimalLineLength,maxChars:e.maximalLineLength});const t=this.updateLayout(e.fontSize,e.deprecatedFontSize||e.iOSPatch,e.scroll,e.columnCount);t?.effectiveContainerWidth&&(this.effectiveContainerWidth=t?.effectiveContainerWidth);const i={a11yNormalize:e.textNormalization,backgroundColor:e.backgroundColor,blendFilter:e.blendFilter,bodyHyphens:typeof e.hyphens!="boolean"?null:e.hyphens?"auto":"none",colCount:t?.colCount,darkenFilter:e.darkenFilter,deprecatedFontSize:e.deprecatedFontSize,fontFamily:e.fontFamily,fontOpticalSizing:typeof e.fontOpticalSizing!="boolean"?null:e.fontOpticalSizing?"auto":"none",fontSize:e.fontSize,fontSizeNormalize:e.fontSizeNormalize,fontWeight:e.fontWeight,fontWidth:e.fontWidth,invertFilter:e.invertFilter,invertGaijiFilter:e.invertGaijiFilter,iOSPatch:e.iOSPatch,iPadOSPatch:e.iPadOSPatch,letterSpacing:e.letterSpacing,ligatures:typeof e.ligatures!="boolean"?null:e.ligatures?"common-ligatures":"none",lineHeight:e.lineHeight,lineLength:t?.effectiveLineLength,linkColor:e.linkColor,noRuby:e.noRuby,paraIndent:e.paragraphIndent,paraSpacing:e.paragraphSpacing,selectionBackgroundColor:e.selectionBackgroundColor,selectionTextColor:e.selectionTextColor,textAlign:e.textAlign,textColor:e.textColor,view:typeof e.scroll!="boolean"?null:e.scroll?"scroll":"paged",visitedColor:e.visitedColor,wordSpacing:e.wordSpacing};this.userProperties=new Xt(i)}updateLayout(e,t,i,n){return i??this.userProperties.view==="scroll"?this.computeScrollLength(e,t):this.paginate(e,t,n)}getCompensatedMetrics(e,t){const i=e||this.userProperties.fontSize||1,n=i<1?1/i:t?i:1;return{zoomFactor:i,zoomCompensation:n,optimal:Math.round(this.lineLengths.optimalLineLength)*i,minimal:this.lineLengths.minimalLineLength!==null?Math.round(this.lineLengths.minimalLineLength*i):null,maximal:this.lineLengths.maximalLineLength!==null?Math.round(this.lineLengths.maximalLineLength*i):null}}paginate(e,t,i){const n=Math.round(lt(this.containerParent)-this.constraint),r=this.getCompensatedMetrics(e,t),{zoomCompensation:s,optimal:a,minimal:l,maximal:c}=r,h=()=>n>=a&&c!==null?Math.min(Math.round(c*s),n):n;let u=1,m=n;if(i===void 0)return{colCount:void 0,effectiveContainerWidth:m,effectiveLineLength:Math.round(m/u*s)};if(i===null)if(n>=a&&c!==null){u=Math.floor(n/a);const b=Math.round(u*(c*s));m=Math.min(b,n)}else m=h();else if(i>1){const b=Math.round(i*(l!==null?l:a));if(n>=b)if(u=i,c===null)m=n;else{const d=Math.round(u*(c*s));m=Math.min(d,n)}else if(l!==null&&n<Math.round(i*l))if(u=Math.floor(n/l),u<=1)u=1,m=h();else{const d=Math.round(u*(a*s));m=Math.min(d,n)}else{u=i;const d=Math.round(u*(a*s));m=Math.min(d,n)}}else u=1,m=h();return{colCount:u,effectiveContainerWidth:m,effectiveLineLength:Math.round(m/u/(e&&e>=1?e:1)*s)}}computeScrollLength(e,t){const i=Math.round(lt(this.containerParent)-this.constraint),n=this.getCompensatedMetrics(e&&(e<1||t)?e:1,t),r=n.zoomCompensation,s=n.optimal,a=n.maximal;let l,c=i,h=Math.round(s*r);if(a===null)h=i;else{const u=Math.min(Math.round(a*r),i);h=t?u:Math.round(u*r)}return{colCount:l,effectiveContainerWidth:c,effectiveLineLength:h}}setContainerWidth(){this.container.style.width=`${this.effectiveContainerWidth}px`}resizeHandler(){const e=this.updateLayout(this.userProperties.fontSize,this.userProperties.deprecatedFontSize||this.userProperties.iOSPatch,this.userProperties.view==="scroll",this.cachedColCount);this.userProperties.colCount=e.colCount,this.userProperties.lineLength=e.effectiveLineLength,this.effectiveContainerWidth=e.effectiveContainerWidth,this.container.style.width=`${this.effectiveContainerWidth}px`}}const to=`/*!
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@readium/navigator",
|
|
3
|
-
"version": "2.4.0-alpha.
|
|
3
|
+
"version": "2.4.0-alpha.8",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Next generation SDK for publications in Web Apps",
|
|
6
6
|
"author": "readium",
|
|
@@ -55,8 +55,8 @@
|
|
|
55
55
|
"typescript-plugin-css-modules": "^5.2.0",
|
|
56
56
|
"user-agent-data-types": "^0.4.2",
|
|
57
57
|
"vite": "^7.3.1",
|
|
58
|
-
"@readium/
|
|
59
|
-
"@readium/
|
|
58
|
+
"@readium/navigator-html-injectables": "2.3.0",
|
|
59
|
+
"@readium/shared": "2.1.5"
|
|
60
60
|
},
|
|
61
61
|
"scripts": {
|
|
62
62
|
"clean": "rimraf types dist",
|
|
@@ -76,14 +76,8 @@ export default class FrameBlobBuilder {
|
|
|
76
76
|
|
|
77
77
|
// Load the HTML resource
|
|
78
78
|
const link = await this.currentResource.link();
|
|
79
|
-
const
|
|
80
|
-
if(!
|
|
81
|
-
|
|
82
|
-
const doc = new DOMParser().parseFromString(
|
|
83
|
-
txt,
|
|
84
|
-
link.mediaType.string as DOMParserSupportedType
|
|
85
|
-
);
|
|
86
|
-
|
|
79
|
+
const doc = await this.currentResource.readAsXML() as HTMLDocument;
|
|
80
|
+
if(!doc) throw new Error(`Failed reading item ${link.href}`);
|
|
87
81
|
const perror = doc.querySelector("parsererror");
|
|
88
82
|
if (perror) {
|
|
89
83
|
const details = perror.querySelector("div");
|
|
@@ -21,7 +21,7 @@ export class FXLFrameManager {
|
|
|
21
21
|
public debugHref: string;
|
|
22
22
|
private loadPromise: Promise<Window> | undefined;
|
|
23
23
|
private showPromise: Promise<void> | undefined;
|
|
24
|
-
private
|
|
24
|
+
private viewportSize: { width: number, height: number } | undefined = undefined;
|
|
25
25
|
|
|
26
26
|
constructor(
|
|
27
27
|
peripherals: FXLPeripherals,
|
|
@@ -108,7 +108,7 @@ export class FXLFrameManager {
|
|
|
108
108
|
|
|
109
109
|
// Parses the page size from the viewport meta tag of the loaded resource.
|
|
110
110
|
loadPageSize(): { width: number, height: number } {
|
|
111
|
-
if(this.
|
|
111
|
+
if(this.viewportSize) return this.viewportSize;
|
|
112
112
|
const wnd = this.frame.contentWindow!;
|
|
113
113
|
|
|
114
114
|
// Try to get the page size from the viewport meta tag
|
|
@@ -125,16 +125,17 @@ export class FXLFrameManager {
|
|
|
125
125
|
else if(match[1] === "height")
|
|
126
126
|
height = Number.parseFloat(match[2]);
|
|
127
127
|
}
|
|
128
|
-
if(width > 0 && height > 0)
|
|
129
|
-
|
|
128
|
+
if(width > 0 && height > 0) {
|
|
129
|
+
this.viewportSize = { width, height };
|
|
130
|
+
return this.viewportSize;
|
|
131
|
+
}
|
|
130
132
|
}
|
|
131
133
|
|
|
132
134
|
// Otherwise get it from the size of the loaded content
|
|
133
|
-
|
|
135
|
+
return {
|
|
134
136
|
width: wnd.document.body.scrollWidth,
|
|
135
137
|
height: wnd.document.body.scrollHeight
|
|
136
|
-
}
|
|
137
|
-
return this.pageSize;
|
|
138
|
+
}
|
|
138
139
|
}
|
|
139
140
|
|
|
140
141
|
update(page?: Page) {
|
|
@@ -17,7 +17,7 @@ export declare class FXLFrameManager {
|
|
|
17
17
|
debugHref: string;
|
|
18
18
|
private loadPromise;
|
|
19
19
|
private showPromise;
|
|
20
|
-
private
|
|
20
|
+
private viewportSize;
|
|
21
21
|
constructor(peripherals: FXLPeripherals, direction: ReadingProgression, debugHref: string, contentProtectionConfig?: IContentProtectionConfig, keyboardPeripheralsConfig?: IKeyboardPeripheralsConfig);
|
|
22
22
|
load(modules: ModuleName[], source: string): Promise<Window>;
|
|
23
23
|
loadPageSize(): {
|