@readium/navigator 2.4.0-alpha.0 → 2.4.0-alpha.2
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 +61 -52
- package/dist/index.umd.cjs +4 -2
- package/package.json +1 -1
- package/src/epub/frame/FrameBlobBuilder.ts +48 -15
package/dist/index.js
CHANGED
|
@@ -154,7 +154,7 @@ x.NONE = new x("none"), x.DOCUMENTED = new x("documented"), x.LEGAL = new x("leg
|
|
|
154
154
|
let Be = x;
|
|
155
155
|
const Ve = ["en", "ar", "da", "fr", "it", "pt_PT", "sv"], un = /* @__PURE__ */ JSON.parse(`{"format":{"audiobook":"Audiobook","audiobookJSON":"Audiobook Manifest","cbz":"Comic Book Archive","divina":"Divina Publication","divinaJSON":"Divina Publication Manifest","epub":"EPUB","lcpa":"LCP Protected Audiobook","lcpdf":"LCP Protected PDF","lcpl":"LCP License Document","pdf":"PDF","rwp":"Readium Web Publication","rwpm":"Readium Web Publication Manifest","zab":"Audiobook Archive","zip":"ZIP Archive"},"kind":{"audiobook_one":"audiobook","audiobook_other":"audiobooks","book_one":"book","book_other":"books","comic_one":"comic","comic_other":"comics","document_one":"document","document_other":"documents"},"metadata":{"accessibility":{"display-guide":{"accessibility-summary":{"no-metadata":"No information is available","publisher-contact":"For more information about the accessibility of this product, please contact the publisher: ","title":"Accessibility summary"},"additional-accessibility-information":{"aria":{"compact":"ARIA roles included","descriptive":"Content is enhanced with ARIA roles to optimize organization and facilitate navigation"},"audio-descriptions":"Audio descriptions","braille":"Braille","color-not-sole-means-of-conveying-information":"Color is not the sole means of conveying information","dyslexia-readability":"Dyslexia readability","full-ruby-annotations":"Full ruby annotations","high-contrast-between-foreground-and-background-audio":"High contrast between foreground and background audio","high-contrast-between-text-and-background":"High contrast between foreground text and background","large-print":"Large print","page-breaks":{"compact":"Page breaks included","descriptive":"Page breaks included from the original print source"},"ruby-annotations":"Some Ruby annotations","sign-language":"Sign language","tactile-graphics":{"compact":"Tactile graphics included","descriptive":"Tactile graphics have been integrated to facilitate access to visual elements for blind people"},"tactile-objects":"Tactile 3D objects","text-to-speech-hinting":"Text-to-speech hinting provided","title":"Additional accessibility information","ultra-high-contrast-between-text-and-background":"Ultra high contrast between text and background","visible-page-numbering":"Visible page numbering","without-background-sounds":"Without background sounds"},"conformance":{"a":{"compact":"This publication meets minimum accessibility standards","descriptive":"The publication contains a conformance statement that it meets the EPUB Accessibility and WCAG 2 Level A standard"},"aa":{"compact":"This publication meets accepted accessibility standards","descriptive":"The publication contains a conformance statement that it meets the EPUB Accessibility and WCAG 2 Level AA standard"},"aaa":{"compact":"This publication exceeds accepted accessibility standards","descriptive":"The publication contains a conformance statement that it meets the EPUB Accessibility and WCAG 2 Level AAA standard"},"certifier":"The publication was certified by ","certifier-credentials":"The certifier's credential is ","details":{"certification-info":"The publication was certified on ","certifier-report":"For more information refer to the certifier's report","claim":"This publication claims to meet","epub-accessibility-1-0":"EPUB Accessibility 1.0","epub-accessibility-1-1":"EPUB Accessibility 1.1","level-a":"Level A","level-aa":"Level AA","level-aaa":"Level AAA","wcag-2-0":{"compact":"WCAG 2.0","descriptive":"Web Content Accessibility Guidelines (WCAG) 2.0"},"wcag-2-1":{"compact":"WCAG 2.1","descriptive":"Web Content Accessibility Guidelines (WCAG) 2.1"},"wcag-2-2":{"compact":"WCAG 2.2","descriptive":"Web Content Accessibility Guidelines (WCAG) 2.2"}},"details-title":"Detailed conformance information","no":"No information is available","title":"Conformance","unknown-standard":"Conformance to accepted standards for accessibility of this publication cannot be determined"},"hazards":{"flashing":{"compact":"Flashing content","descriptive":"The publication contains flashing content that can cause photosensitive seizures"},"flashing-none":{"compact":"No flashing hazards","descriptive":"The publication does not contain flashing content that can cause photosensitive seizures"},"flashing-unknown":{"compact":"Flashing hazards not known","descriptive":"The presence of flashing content that can cause photosensitive seizures could not be determined"},"motion":{"compact":"Motion simulation","descriptive":"The publication contains motion simulations that can cause motion sickness"},"motion-none":{"compact":"No motion simulation hazards","descriptive":"The publication does not contain motion simulations that can cause motion sickness"},"motion-unknown":{"compact":"Motion simulation hazards not known","descriptive":"The presence of motion simulations that can cause motion sickness could not be determined"},"no-metadata":"No information is available","none":{"compact":"No hazards","descriptive":"The publication contains no hazards"},"sound":{"compact":"Sounds","descriptive":"The publication contains sounds that can cause sensitivity issues"},"sound-none":{"compact":"No sound hazards","descriptive":"The publication does not contain sounds that can cause sensitivity issues"},"sound-unknown":{"compact":"Sound hazards not known","descriptive":"The presence of sounds that can cause sensitivity issues could not be determined"},"title":"Hazards","unknown":"The presence of hazards is unknown"},"legal-considerations":{"exempt":{"compact":"Claims an accessibility exemption in some jurisdictions","descriptive":"This publication claims an accessibility exemption in some jurisdictions"},"no-metadata":"No information is available","title":"Legal considerations"},"navigation":{"index":{"compact":"Index","descriptive":"Index with links to referenced entries"},"no-metadata":"No information is available","page-navigation":{"compact":"Go to page","descriptive":"Page list to go to pages from the print source version"},"structural":{"compact":"Headings","descriptive":"Elements such as headings, tables, etc for structured navigation"},"title":"Navigation","toc":{"compact":"Table of contents","descriptive":"Table of contents to all chapters of the text via links"}},"rich-content":{"accessible-chemistry-as-latex":{"compact":"Chemical formulas in LaTeX","descriptive":"Chemical formulas in accessible format (LaTeX)"},"accessible-chemistry-as-mathml":{"compact":"Chemical formulas in MathML","descriptive":"Chemical formulas in accessible format (MathML)"},"accessible-math-as-latex":{"compact":"Math as LaTeX","descriptive":"Math formulas in accessible format (LaTeX)"},"accessible-math-described":"Text descriptions of math are provided","closed-captions":{"compact":"Videos have closed captions","descriptive":"Videos included in publications have closed captions"},"extended-descriptions":"Information-rich images are described by extended descriptions","math-as-mathml":{"compact":"Math as MathML","descriptive":"Math formulas in accessible format (MathML)"},"open-captions":{"compact":"Videos have open captions","descriptive":"Videos included in publications have open captions"},"title":"Rich content","transcript":"Transcript(s) provided","unknown":"No information is available"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{"compact":"Has alternative text","descriptive":"Has alternative text descriptions for images"},"no-metadata":"No information about nonvisual reading is available","none":{"compact":"Not readable in read aloud or dynamic braille","descriptive":"The content is not readable as read aloud speech or dynamic braille"},"not-fully":{"compact":"Not fully readable in read aloud or dynamic braille","descriptive":"Not all of the content will be readable as read aloud speech or dynamic braille"},"readable":{"compact":"Readable in read aloud or dynamic braille","descriptive":"All content can be read as read aloud speech or dynamic braille"}},"prerecorded-audio":{"complementary":{"compact":"Prerecorded audio clips","descriptive":"Prerecorded audio clips are embedded in the content"},"no-metadata":"No information about prerecorded audio is available","only":{"compact":"Prerecorded audio only","descriptive":"Audiobook with no text alternative"},"synchronized":{"compact":"Prerecorded audio synchronized with text","descriptive":"All the content is available as prerecorded audio synchronized with text"}},"title":"Ways of reading","visual-adjustments":{"modifiable":{"compact":"Appearance can be modified","descriptive":"Appearance of the text and page layout can be modified according to the capabilities of the reading system (font family and font size, spaces between paragraphs, sentences, words, and letters, as well as color of background and text)"},"unknown":"No information about appearance modifiability is available","unmodifiable":{"compact":"Appearance cannot be modified","descriptive":"Text and page layout cannot be modified as the reading experience is close to a print version, but reading systems can still provide zooming options"}}}}},"altIdentifier_one":"alternate identifier","altIdentifier_other":"alternate identifiers","artist_one":"artist","artist_other":"artists","author_one":"author","author_other":"authors","collection_one":"editorial collection","collection_other":"editorial collections","colorist_one":"colorist","colorist_other":"colorists","contributor_one":"contributor","contributor_other":"contributors","description":"description","duration":"duration","editor_one":"editor","editor_other":"editors","identifier_one":"identifier","identifier_other":"identifiers","illustrator_one":"illustrator","illustrator_other":"illustrators","imprint_one":"imprint","imprint_other":"imprints","inker_one":"inker","inker_other":"inkers","language_one":"language","language_other":"languages","letterer_one":"letterer","letterer_other":"letterers","modified":"modification date","narrator_one":"narrator","narrator_other":"narrators","numberOfPages":"print length","penciler_one":"penciler","penciler_other":"pencilers","published":"publication date","publisher_one":"publisher","publisher_other":"publishers","series_one":"series","series_other":"series","subject_one":"subject","subject_other":"subjects","subtitle":"subtitle","title":"title","translator_one":"translator","translator_other":"translators"}}`), pn = {
|
|
156
156
|
publication: un
|
|
157
|
-
},
|
|
157
|
+
}, je = {
|
|
158
158
|
fr: () => import("./fr-C5HEel98.js"),
|
|
159
159
|
ar: () => import("./ar-DyHX_uy2.js"),
|
|
160
160
|
da: () => import("./da-Dct0PS3E.js"),
|
|
@@ -165,10 +165,10 @@ const Ve = ["en", "ar", "da", "fr", "it", "pt_PT", "sv"], un = /* @__PURE__ */ J
|
|
|
165
165
|
sv: () => import("./sv-BfzAFsVN.js")
|
|
166
166
|
// 'tr': () => import('@edrlab/thorium-locales/publication-metadata/tr.json'),
|
|
167
167
|
// 'uk': () => import('@edrlab/thorium-locales/publication-metadata/uk.json')
|
|
168
|
-
},
|
|
168
|
+
}, Ge = pn?.publication?.metadata?.accessibility?.["display-guide"] || {};
|
|
169
169
|
class dt {
|
|
170
170
|
constructor() {
|
|
171
|
-
this.currentLocaleCode = "en", this.locale =
|
|
171
|
+
this.currentLocaleCode = "en", this.locale = Ge, this.loadedLocales = {}, this.loadedLocales.en = Ge;
|
|
172
172
|
}
|
|
173
173
|
static getInstance() {
|
|
174
174
|
return dt.instance || (dt.instance = new dt()), dt.instance;
|
|
@@ -184,9 +184,9 @@ class dt {
|
|
|
184
184
|
if (t in this.loadedLocales)
|
|
185
185
|
return !0;
|
|
186
186
|
try {
|
|
187
|
-
if (!(t in
|
|
187
|
+
if (!(t in je))
|
|
188
188
|
return console.warn(`Locale file not found for: ${t}`), !1;
|
|
189
|
-
const n = (await
|
|
189
|
+
const n = (await je[t]()).default?.publication?.metadata?.accessibility?.["display-guide"];
|
|
190
190
|
return n ? (this.loadedLocales[t] = n, !0) : (console.warn(`No accessibility strings found in locale ${t}`), !1);
|
|
191
191
|
} catch (e) {
|
|
192
192
|
return console.warn(`Failed to load locale ${t}:`, e), !1;
|
|
@@ -272,8 +272,8 @@ class Ce {
|
|
|
272
272
|
return this.compression !== void 0 && (t.compression = this.compression), this.originalLength !== void 0 && (t.originalLength = this.originalLength), this.profile !== void 0 && (t.profile = this.profile), this.scheme !== void 0 && (t.scheme = this.scheme), t;
|
|
273
273
|
}
|
|
274
274
|
}
|
|
275
|
-
var
|
|
276
|
-
let
|
|
275
|
+
var j = /* @__PURE__ */ ((s) => (s.left = "left", s.right = "right", s.center = "center", s))(j || {});
|
|
276
|
+
let G = class ce {
|
|
277
277
|
constructor(t) {
|
|
278
278
|
this.otherProperties = t;
|
|
279
279
|
}
|
|
@@ -303,7 +303,7 @@ let j = class ce {
|
|
|
303
303
|
return new ce(e);
|
|
304
304
|
}
|
|
305
305
|
};
|
|
306
|
-
Object.defineProperty(
|
|
306
|
+
Object.defineProperty(G.prototype, "encryption", {
|
|
307
307
|
get: function() {
|
|
308
308
|
return Ce.deserialize(this.otherProperties.encrypted);
|
|
309
309
|
}
|
|
@@ -931,7 +931,7 @@ class V {
|
|
|
931
931
|
type: t.type,
|
|
932
932
|
title: t.title,
|
|
933
933
|
rels: t.rel ? Array.isArray(t.rel) ? new Set(t.rel) : /* @__PURE__ */ new Set([t.rel]) : void 0,
|
|
934
|
-
properties:
|
|
934
|
+
properties: G.deserialize(t.properties),
|
|
935
935
|
height: W(t.height),
|
|
936
936
|
width: W(t.width),
|
|
937
937
|
size: W(t.size),
|
|
@@ -980,7 +980,7 @@ class V {
|
|
|
980
980
|
*/
|
|
981
981
|
addProperties(t) {
|
|
982
982
|
const e = V.deserialize(this.serialize());
|
|
983
|
-
return e.properties = e.properties ? e.properties?.add(t) : new
|
|
983
|
+
return e.properties = e.properties ? e.properties?.add(t) : new G(t), e;
|
|
984
984
|
}
|
|
985
985
|
/**
|
|
986
986
|
* Creates a [Locator] from a reading order [Link].
|
|
@@ -1092,7 +1092,7 @@ class Ft {
|
|
|
1092
1092
|
}
|
|
1093
1093
|
}
|
|
1094
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
|
+
G.prototype.getContains = function() {
|
|
1096
1096
|
return new Set(this.otherProperties.contains || []);
|
|
1097
1097
|
};
|
|
1098
1098
|
class Dt {
|
|
@@ -1320,27 +1320,27 @@ class ke {
|
|
|
1320
1320
|
return this.since !== void 0 && (t.since = this.since.toISOString()), this.until !== void 0 && (t.until = this.until.toISOString()), t;
|
|
1321
1321
|
}
|
|
1322
1322
|
}
|
|
1323
|
-
|
|
1323
|
+
G.prototype.getNumberOfItems = function() {
|
|
1324
1324
|
return W(this.otherProperties.numberOfItems);
|
|
1325
1325
|
};
|
|
1326
|
-
|
|
1326
|
+
G.prototype.getPrice = function() {
|
|
1327
1327
|
return Re.deserialize(this.otherProperties.price);
|
|
1328
1328
|
};
|
|
1329
|
-
|
|
1329
|
+
G.prototype.getIndirectAcquisitions = function() {
|
|
1330
1330
|
const s = this.otherProperties.indirectAcquisition;
|
|
1331
1331
|
if (s && Array.isArray(s))
|
|
1332
1332
|
return s.map((t) => St.deserialize(t)).filter((t) => t !== void 0);
|
|
1333
1333
|
};
|
|
1334
|
-
|
|
1334
|
+
G.prototype.getHolds = function() {
|
|
1335
1335
|
return Le.deserialize(this.otherProperties.holds);
|
|
1336
1336
|
};
|
|
1337
|
-
|
|
1337
|
+
G.prototype.getCopies = function() {
|
|
1338
1338
|
return Oe.deserialize(this.otherProperties.copies);
|
|
1339
1339
|
};
|
|
1340
|
-
|
|
1340
|
+
G.prototype.getAvailability = function() {
|
|
1341
1341
|
return ke.deserialize(this.otherProperties.availability);
|
|
1342
1342
|
};
|
|
1343
|
-
|
|
1343
|
+
G.prototype.getAuthenticate = function() {
|
|
1344
1344
|
return V.deserialize(this.otherProperties.authenticate);
|
|
1345
1345
|
};
|
|
1346
1346
|
const fn = "CssSelectorGenerator";
|
|
@@ -2667,7 +2667,7 @@ class ze {
|
|
|
2667
2667
|
this.history = [], this.consistentScrollCount = 0;
|
|
2668
2668
|
}
|
|
2669
2669
|
}
|
|
2670
|
-
const hi = "readium-column-snapper-style",
|
|
2670
|
+
const hi = "readium-column-snapper-style", jn = 200, U = class U extends Et {
|
|
2671
2671
|
constructor() {
|
|
2672
2672
|
super(...arguments), this.isSnapProtectionEnabled = !1, this.patternAnalyzer = null, this.lastTurnTime = 0, this.shakeTimeout = 0, this.snappingCancelled = !1, this.alreadyScrollLeft = 0, this.overscroll = 0, this.cachedScrollWidth = 0, this.touchState = 0, this.startingX = void 0, this.endingX = void 0, this.onTouchStarter = this.onTouchStart.bind(this), this.onTouchEnder = this.onTouchEnd.bind(this), this.onWidthChanger = this.onWidthChange.bind(this), this.onTouchMover = this.onTouchMove.bind(this);
|
|
2673
2673
|
}
|
|
@@ -2713,7 +2713,7 @@ const hi = "readium-column-snapper-style", Gn = 200, U = class U extends Et {
|
|
|
2713
2713
|
this.snappingCancelled = !1;
|
|
2714
2714
|
const m = (b, v, L, Q) => L > Q ? v : b + (v - b) * Fn(L / Q), y = (
|
|
2715
2715
|
/*Math.abs(startX - (this.useTransform ? currentOffset : 0)) < 10 ? 1 : */
|
|
2716
|
-
|
|
2716
|
+
jn * o
|
|
2717
2717
|
);
|
|
2718
2718
|
let d;
|
|
2719
2719
|
const p = (b) => {
|
|
@@ -3188,7 +3188,7 @@ const I = class I extends Et {
|
|
|
3188
3188
|
};
|
|
3189
3189
|
I.moduleName = "webpub_snapper";
|
|
3190
3190
|
let Se = I;
|
|
3191
|
-
class
|
|
3191
|
+
class Gn {
|
|
3192
3192
|
constructor(t, e) {
|
|
3193
3193
|
this.window = t, this.copyHistory = [], this.lastSelectionLength = 0, this.lastSelectionTime = 0, this.options = e;
|
|
3194
3194
|
}
|
|
@@ -3270,7 +3270,7 @@ class $n {
|
|
|
3270
3270
|
this.events = [], this.selectionStartTime = 0, this.lastSelectionTime = 0, this.lastSelectionPosition = 0, this.selectionPatterns = [], this.lastSelectedText = "";
|
|
3271
3271
|
}
|
|
3272
3272
|
}
|
|
3273
|
-
class
|
|
3273
|
+
class ji {
|
|
3274
3274
|
/**
|
|
3275
3275
|
* Checks if the given keyboard event matches any of the provided key combinations
|
|
3276
3276
|
*/
|
|
@@ -3350,7 +3350,7 @@ class Gi {
|
|
|
3350
3350
|
}
|
|
3351
3351
|
const ut = class ut extends ft {
|
|
3352
3352
|
constructor() {
|
|
3353
|
-
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
|
|
3353
|
+
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 ji(), this.keyDownHandler = null, this.preventBulkCopy = (t) => {
|
|
3354
3354
|
if (!this.isBulkCopyProtectionEnabled || !this.bulkCopyProtector)
|
|
3355
3355
|
return !0;
|
|
3356
3356
|
if (!this.bulkCopyProtector.shouldAllowCopy(t)) {
|
|
@@ -3472,7 +3472,7 @@ const ut = class ut extends ft {
|
|
|
3472
3472
|
addBulkCopyProtection(t = {}) {
|
|
3473
3473
|
if (this.isBulkCopyProtectionEnabled || !this.wnd) return;
|
|
3474
3474
|
const e = Vn, i = t ? { ...e, ...t } : e;
|
|
3475
|
-
this.bulkCopyProtector = new
|
|
3475
|
+
this.bulkCopyProtector = new Gn(this.wnd, i), this.wnd.document.addEventListener("copy", this.preventBulkCopy, !0), this.wnd.document.addEventListener("cut", this.preventBulkCopy, !0), this.isBulkCopyProtectionEnabled = !0;
|
|
3476
3476
|
}
|
|
3477
3477
|
removeBulkCopyProtection() {
|
|
3478
3478
|
!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);
|
|
@@ -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.1",
|
|
3626
3626
|
hasFeature: (n, r = "") => {
|
|
3627
3627
|
switch (n) {
|
|
3628
3628
|
case "dom-manipulation":
|
|
@@ -3979,7 +3979,7 @@ class er {
|
|
|
3979
3979
|
return i;
|
|
3980
3980
|
}
|
|
3981
3981
|
}
|
|
3982
|
-
class
|
|
3982
|
+
class Gi extends er {
|
|
3983
3983
|
/**
|
|
3984
3984
|
* Moves to the left content portion (eg. page) relative to the reading progression direction.
|
|
3985
3985
|
*/
|
|
@@ -4648,13 +4648,13 @@ var J = /* @__PURE__ */ ((s) => (s.start = "start", s.left = "left", s.right = "
|
|
|
4648
4648
|
const ot = {
|
|
4649
4649
|
range: [0, 100],
|
|
4650
4650
|
step: 1
|
|
4651
|
-
},
|
|
4651
|
+
}, jt = {
|
|
4652
4652
|
range: [0.7, 4],
|
|
4653
4653
|
step: 0.05
|
|
4654
4654
|
}, it = {
|
|
4655
4655
|
range: [100, 1e3],
|
|
4656
4656
|
step: 100
|
|
4657
|
-
},
|
|
4657
|
+
}, Gt = {
|
|
4658
4658
|
range: [50, 250],
|
|
4659
4659
|
step: 10
|
|
4660
4660
|
}, $t = {
|
|
@@ -6007,7 +6007,7 @@ class rn {
|
|
|
6007
6007
|
const Lt = "readium:navigator:keyboardPeripheral";
|
|
6008
6008
|
class sn {
|
|
6009
6009
|
constructor(t = {}) {
|
|
6010
|
-
this.keyManager = new
|
|
6010
|
+
this.keyManager = new ji(), this.setupKeyboardPeripherals(t.keyboardPeripherals || []);
|
|
6011
6011
|
}
|
|
6012
6012
|
setupKeyboardPeripherals(t) {
|
|
6013
6013
|
if (t.length > 0) {
|
|
@@ -6053,7 +6053,7 @@ const Mr = (s) => ({
|
|
|
6053
6053
|
peripheral: s.peripheral || (() => {
|
|
6054
6054
|
})
|
|
6055
6055
|
});
|
|
6056
|
-
class Ur extends
|
|
6056
|
+
class Ur extends Gi {
|
|
6057
6057
|
constructor(t, e, i, n = void 0, r = { preferences: {}, defaults: {} }) {
|
|
6058
6058
|
super(), this.currentIndex = 0, this._preferencesEditor = null, this._injector = null, this._navigatorProtector = null, this._keyboardPeripheralsManager = null, this._suspiciousActivityListener = null, this._keyboardPeripheralListener = null, this.webViewport = {
|
|
6059
6059
|
readingOrder: [],
|
|
@@ -6413,8 +6413,17 @@ class on {
|
|
|
6413
6413
|
return this.injector && await this.injector.injectForDocument(i, this.item), this.finalizeDOM(i, this.pub.baseURL, (await this.pub.get(this.item).link()).toURL(this.baseURL) || "", this.item.mediaType, t, this.cssProperties);
|
|
6414
6414
|
}
|
|
6415
6415
|
async buildImageFrame() {
|
|
6416
|
-
const t =
|
|
6417
|
-
|
|
6416
|
+
const t = await this.pub.get(this.item).link(), e = t.toURL(this.baseURL) || "", i = document.implementation.createHTMLDocument(this.item.title || this.item.href);
|
|
6417
|
+
if ((t?.height || 0) > 0 && (t?.width || 0) > 0) {
|
|
6418
|
+
const o = i.createElement("meta");
|
|
6419
|
+
o.name = "viewport", o.content = `width=${t.width}, height=${t.height}`, o.dataset.readium = "true", i.head.appendChild(o);
|
|
6420
|
+
}
|
|
6421
|
+
const n = document.createElement("img");
|
|
6422
|
+
n.src = e || "", n.alt = this.item.title || "", n.decoding = "async", i.body.appendChild(n), this.injector && await this.injector.injectForDocument(i, this.item);
|
|
6423
|
+
const r = i.createElement("style");
|
|
6424
|
+
return r.dataset.readium = "true", r.textContent = `
|
|
6425
|
+
html, body { width: 100%; height: 100%; margin: 0; padding: 0; font-size: 0; }
|
|
6426
|
+
img { margin: 0; padding: 0; border: 0; }`, i.head.appendChild(r), this.finalizeDOM(i, this.pub.baseURL, e, this.item.mediaType, !0);
|
|
6418
6427
|
}
|
|
6419
6428
|
setProperties(t, e) {
|
|
6420
6429
|
for (const i in t) {
|
|
@@ -6729,10 +6738,10 @@ class Ir {
|
|
|
6729
6738
|
const i = Math.min(this.wrapper.clientWidth / e.width, this.wrapper.clientHeight / e.height);
|
|
6730
6739
|
this.frame.style.transform = `scale(${i})`;
|
|
6731
6740
|
const n = this.frame.getBoundingClientRect(), r = this.wrapper.clientHeight - n.height;
|
|
6732
|
-
if (this.frame.style.top = `${r / 2}px`, t ===
|
|
6741
|
+
if (this.frame.style.top = `${r / 2}px`, t === j.left) {
|
|
6733
6742
|
const o = this.wrapper.clientWidth - n.width;
|
|
6734
6743
|
this.frame.style.left = `${o}px`;
|
|
6735
|
-
} else if (t ===
|
|
6744
|
+
} else if (t === j.center) {
|
|
6736
6745
|
const o = this.wrapper.clientWidth - n.width;
|
|
6737
6746
|
this.frame.style.left = `${o / 2}px`;
|
|
6738
6747
|
} else
|
|
@@ -6901,7 +6910,7 @@ class Vr {
|
|
|
6901
6910
|
}
|
|
6902
6911
|
}
|
|
6903
6912
|
const _i = 6, he = 1.02, Pi = 50;
|
|
6904
|
-
class
|
|
6913
|
+
class jr {
|
|
6905
6914
|
constructor(t, e = !1) {
|
|
6906
6915
|
this.dragState = 0, this.minimumMoved = !1, this.pan = {
|
|
6907
6916
|
startX: 0,
|
|
@@ -7122,7 +7131,7 @@ Overscroll: ${this.pan.overscrollX.toFixed(2)},${this.pan.overscrollY.toFixed(2)
|
|
|
7122
7131
|
}
|
|
7123
7132
|
}
|
|
7124
7133
|
var Pe = /* @__PURE__ */ ((s) => (s.auto = "auto", s.landscape = "landscape", s.portrait = "portrait", s))(Pe || {}), Ee = /* @__PURE__ */ ((s) => (s.auto = "auto", s.both = "both", s.none = "none", s.landscape = "landscape", s))(Ee || {});
|
|
7125
|
-
class
|
|
7134
|
+
class Gr {
|
|
7126
7135
|
// TODO getter
|
|
7127
7136
|
constructor(t) {
|
|
7128
7137
|
this.shift = !0, this.spreads = [], this.nLandscape = 0, this.index(t), this.testShift(t), console.log(`Indexed ${this.spreads.length} spreads for ${t.readingOrder.items.length} items`);
|
|
@@ -7151,13 +7160,13 @@ class jr {
|
|
|
7151
7160
|
if (i.length > 1)
|
|
7152
7161
|
return;
|
|
7153
7162
|
const r = i[0], o = r.properties?.otherProperties.orientation;
|
|
7154
|
-
n === 0 && (o === "landscape" || o !== "portrait" && ((r.width || 0) > (r.height || 0) || r.properties?.otherProperties.spread === "both")) && (this.shift = !1), e && r.properties?.page ===
|
|
7163
|
+
n === 0 && (o === "landscape" || o !== "portrait" && ((r.width || 0) > (r.height || 0) || r.properties?.otherProperties.spread === "both")) && (this.shift = !1), e && r.properties?.page === j.center && this.spreads[n - 1][0].addProperties({ addBlank: !0 }), o === "portrait" && r.properties?.page !== "center" && r.properties?.otherProperties.number > 1 ? e = !0 : e = !1;
|
|
7155
7164
|
}), this.shift || this.index(t, !0);
|
|
7156
7165
|
}
|
|
7157
7166
|
buildSpreads(t) {
|
|
7158
7167
|
let e = [];
|
|
7159
7168
|
t.items.forEach((i, n) => {
|
|
7160
|
-
!n && this.shift ? this.spreads.push([i]) : i.properties?.page ===
|
|
7169
|
+
!n && this.shift ? this.spreads.push([i]) : i.properties?.page === j.center ? (e.length > 0 && this.spreads.push(e), this.spreads.push([i]), e = []) : e.length >= 2 ? (this.spreads.push(e), e = [i]) : e.push(i);
|
|
7161
7170
|
}), e.length > 0 && this.spreads.push(e);
|
|
7162
7171
|
}
|
|
7163
7172
|
currentSpread(t, e) {
|
|
@@ -7172,7 +7181,7 @@ class Zr {
|
|
|
7172
7181
|
constructor(t, e, i, n, r, o) {
|
|
7173
7182
|
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)
|
|
7174
7183
|
throw Error("Unsupported reading progression for EPUB");
|
|
7175
|
-
this.spreader = new
|
|
7184
|
+
this.spreader = new Gr(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 jr(this), this.pub.readingOrder.items.forEach((a) => {
|
|
7176
7185
|
const l = new Ir(this.peripherals, this.pub.metadata.effectiveReadingProgression, a.href, this.contentProtectionConfig, this.keyboardPeripheralsConfig);
|
|
7177
7186
|
this.spineElement.appendChild(l.element), this.pool.set(a.href, l), l.width = 100 / this.length * (a.properties?.otherProperties.orientation === Pe.landscape || a.properties?.otherProperties.addBlank ? this.perPage : 1), l.height = this.height;
|
|
7178
7187
|
});
|
|
@@ -7360,7 +7369,7 @@ class Zr {
|
|
|
7360
7369
|
return t % 2 && !this.single && t++, t;
|
|
7361
7370
|
}
|
|
7362
7371
|
spreadPosition(t, e) {
|
|
7363
|
-
return this.perPage < 2 || t.length < 2 ?
|
|
7372
|
+
return this.perPage < 2 || t.length < 2 ? j.center : e.href === t[0].href ? this.rtl ? j.right : j.left : this.rtl ? j.left : j.right;
|
|
7364
7373
|
}
|
|
7365
7374
|
async waitForItem(t) {
|
|
7366
7375
|
if (this.inprogress.has(t) && await this.inprogress.get(t), this.delayedShow.has(t)) {
|
|
@@ -7490,7 +7499,7 @@ class Zr {
|
|
|
7490
7499
|
}
|
|
7491
7500
|
class Ot {
|
|
7492
7501
|
constructor(t = {}) {
|
|
7493
|
-
this.backgroundColor = N(t.backgroundColor), this.blendFilter = P(t.blendFilter), this.constraint = _(t.constraint), this.columnCount = _(t.columnCount), this.darkenFilter = pt(t.darkenFilter), this.deprecatedFontSize = P(t.deprecatedFontSize), this.fontFamily = N(t.fontFamily), this.fontSize = q(t.fontSize,
|
|
7502
|
+
this.backgroundColor = N(t.backgroundColor), this.blendFilter = P(t.blendFilter), this.constraint = _(t.constraint), this.columnCount = _(t.columnCount), this.darkenFilter = pt(t.darkenFilter), this.deprecatedFontSize = P(t.deprecatedFontSize), this.fontFamily = N(t.fontFamily), this.fontSize = q(t.fontSize, jt.range), this.fontSizeNormalize = P(t.fontSizeNormalize), this.fontOpticalSizing = P(t.fontOpticalSizing), this.fontWeight = q(t.fontWeight, it.range), this.fontWidth = q(t.fontWidth, Gt.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 = _(t.letterSpacing), this.ligatures = P(t.ligatures), this.lineHeight = _(t.lineHeight), this.linkColor = N(t.linkColor), this.noRuby = P(t.noRuby), this.pageGutter = _(t.pageGutter), this.paragraphIndent = _(t.paragraphIndent), this.paragraphSpacing = _(t.paragraphSpacing), this.scroll = P(t.scroll), this.scrollPaddingTop = _(t.scrollPaddingTop), this.scrollPaddingBottom = _(t.scrollPaddingBottom), this.scrollPaddingLeft = _(t.scrollPaddingLeft), this.scrollPaddingRight = _(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 = _(t.wordSpacing), this.optimalLineLength = _(t.optimalLineLength), this.maximalLineLength = _(t.maximalLineLength), this.minimalLineLength = _(t.minimalLineLength);
|
|
7494
7503
|
}
|
|
7495
7504
|
static serialize(t) {
|
|
7496
7505
|
const { ...e } = t;
|
|
@@ -7513,7 +7522,7 @@ class Ot {
|
|
|
7513
7522
|
}
|
|
7514
7523
|
class Jr {
|
|
7515
7524
|
constructor(t) {
|
|
7516
|
-
this.backgroundColor = N(t.backgroundColor) || null, this.blendFilter = P(t.blendFilter) ?? !1, this.constraint = _(t.constraint) || 0, this.columnCount = _(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,
|
|
7525
|
+
this.backgroundColor = N(t.backgroundColor) || null, this.blendFilter = P(t.blendFilter) ?? !1, this.constraint = _(t.constraint) || 0, this.columnCount = _(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, jt.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, Gt.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 : (O.OS.iOS || O.OS.iPadOS) && O.iOSRequest === "mobile", this.iPadOSPatch = t.iPadOSPatch === !1 ? !1 : O.OS.iPadOS && O.iOSRequest === "desktop", this.letterSpacing = _(t.letterSpacing) || null, this.ligatures = P(t.ligatures) ?? null, this.lineHeight = _(t.lineHeight) || null, this.linkColor = N(t.linkColor) || null, this.noRuby = P(t.noRuby) ?? !1, this.pageGutter = le(_(t.pageGutter), 20), this.paragraphIndent = _(t.paragraphIndent) ?? null, this.paragraphSpacing = _(t.paragraphSpacing) ?? null, this.scroll = P(t.scroll) ?? !1, this.scrollPaddingTop = _(t.scrollPaddingTop) ?? null, this.scrollPaddingBottom = _(t.scrollPaddingBottom) ?? null, this.scrollPaddingLeft = _(t.scrollPaddingLeft) ?? null, this.scrollPaddingRight = _(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 = _(t.wordSpacing) || null, this.optimalLineLength = _(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;
|
|
7517
7526
|
}
|
|
7518
7527
|
}
|
|
7519
7528
|
const Qr = "#FFFFFF", ts = "#121212", es = "#0000EE", is = "#551A8B", ns = "#b4d8fe", rs = "inherit", lt = {
|
|
@@ -7614,8 +7623,8 @@ class xi {
|
|
|
7614
7623
|
onChange: (t) => {
|
|
7615
7624
|
this.updatePreference("fontSize", t || null);
|
|
7616
7625
|
},
|
|
7617
|
-
supportedRange:
|
|
7618
|
-
step:
|
|
7626
|
+
supportedRange: jt.range,
|
|
7627
|
+
step: jt.step
|
|
7619
7628
|
});
|
|
7620
7629
|
}
|
|
7621
7630
|
get fontSizeNormalize() {
|
|
@@ -7658,8 +7667,8 @@ class xi {
|
|
|
7658
7667
|
onChange: (t) => {
|
|
7659
7668
|
this.updatePreference("fontWidth", t || null);
|
|
7660
7669
|
},
|
|
7661
|
-
supportedRange:
|
|
7662
|
-
step:
|
|
7670
|
+
supportedRange: Gt.range,
|
|
7671
|
+
step: Gt.step
|
|
7663
7672
|
});
|
|
7664
7673
|
}
|
|
7665
7674
|
get hyphens() {
|
|
@@ -9453,7 +9462,7 @@ const us = (s) => ({
|
|
|
9453
9462
|
peripheral: s.peripheral || (() => {
|
|
9454
9463
|
})
|
|
9455
9464
|
});
|
|
9456
|
-
class ln extends
|
|
9465
|
+
class ln extends Gi {
|
|
9457
9466
|
constructor(t, e, i, n = [], r = void 0, o = { preferences: {}, defaults: {} }) {
|
|
9458
9467
|
super(), this._preferencesEditor = null, this._injector = null, this._navigatorProtector = null, this._keyboardPeripheralsManager = null, this._suspiciousActivityListener = null, this._keyboardPeripheralListener = null, this.reflowViewport = {
|
|
9459
9468
|
readingOrder: [],
|
|
@@ -10074,8 +10083,8 @@ export {
|
|
|
10074
10083
|
Br as FXLCoordinator,
|
|
10075
10084
|
Ir as FXLFrameManager,
|
|
10076
10085
|
Zr as FXLFramePoolManager,
|
|
10077
|
-
|
|
10078
|
-
|
|
10086
|
+
jr as FXLPeripherals,
|
|
10087
|
+
Gr as FXLSpreader,
|
|
10079
10088
|
Ct as FrameComms,
|
|
10080
10089
|
Fr as FrameManager,
|
|
10081
10090
|
Dr as FramePoolManager,
|
|
@@ -10093,7 +10102,7 @@ export {
|
|
|
10093
10102
|
J as TextAlignment,
|
|
10094
10103
|
an as UserProperties,
|
|
10095
10104
|
Hr as VerticalThird,
|
|
10096
|
-
|
|
10105
|
+
Gi as VisualNavigator,
|
|
10097
10106
|
ms as WebAudioEngine,
|
|
10098
10107
|
ir as WebPubBlobBuilder,
|
|
10099
10108
|
gr as WebPubCSS,
|
|
@@ -10117,9 +10126,9 @@ export {
|
|
|
10117
10126
|
q as ensureValueInRange,
|
|
10118
10127
|
Me as experiments,
|
|
10119
10128
|
ot as filterRangeConfig,
|
|
10120
|
-
|
|
10129
|
+
jt as fontSizeRangeConfig,
|
|
10121
10130
|
it as fontWeightRangeConfig,
|
|
10122
|
-
|
|
10131
|
+
Gt as fontWidthRangeConfig,
|
|
10123
10132
|
$t as letterSpacingRangeConfig,
|
|
10124
10133
|
Xt as lineHeightRangeConfig,
|
|
10125
10134
|
at as lineLengthRangeConfig,
|
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(),z(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(),z(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=Ye(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(),z(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)=>{z(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(Fi)?.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(),z(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(),z(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=Ye(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(),z(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)=>{z(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,h=Math.min(r*this.options.maxSelectionPercent,this.options.absoluteMaxChars),c=this.isSuspiciousPattern(s),u=n>h||l||c;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 Ii{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()||"",h=(a&&s?.rangeCount?s.getRangeAt(0)?.getClientRects():null)?.[0];h&&a&&(r={text:a,x:h.x,y:h.y,width:h.width,height:h.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 h=s.type,c=this.createActivityEvent(l,h,e,n);i(c)}})))}),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 Ii,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.0",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(),z(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(),z(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=Ye(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(),z(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)=>{z(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(Fi)?.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(),z(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(),z(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=Ye(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(),z(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)=>{z(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,h=Math.min(r*this.options.maxSelectionPercent,this.options.absoluteMaxChars),c=this.isSuspiciousPattern(s),u=n>h||l||c;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 Ii{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()||"",h=(a&&s?.rangeCount?s.getRangeAt(0)?.getClientRects():null)?.[0];h&&a&&(r={text:a,x:h.x,y:h.y,width:h.width,height:h.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 h=s.type,c=this.createActivityEvent(l,h,e,n);i(c)}})))}),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 Ii,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.1",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,7 +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 Fe="readium:navigator:suspiciousActivity";class cn{dispatchSuspiciousActivity(e,t){const i=new CustomEvent(Fe,{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 Ie="readium:navigator:keyboardPeripheral";class hn{constructor(e={}){this.keyManager=new Ii,this.setupKeyboardPeripherals(e.keyboardPeripherals||[])}setupKeyboardPeripherals(e){if(e.length>0){const t=i=>{const n=new CustomEvent(Ie,{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 It(this._preferences,this._defaults,this.hasDisplayTransformability),this._css=new Ji({rsProperties:new Ki({experiments:this._settings.experiments||null}),userProperties:new Ut({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 h=l;this.listeners.contentProtection(h.detail.type,h.detail)},window.addEventListener(Fe,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new hn({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=l=>{const h=l.detail;this.listeners.peripheral(h)},window.addEventListener(Ie,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 Yi(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 It(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 c=new URL(this.currentLocation.href);l=new URL(a,c).href}else l=tt.join(tt.dirname(this.currentLocation.href),a);const h=this.pub.readingOrder.findWithHref(l);h?this.goLink(h,!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(Fe,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(Ie,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,h)=>{this.framePool.currentFrames[0].msg.send("go_text",n?[e.text?.serialize(),n]:e.text?.serialize(),c=>l(c))}):n&&(i=await new Promise((l,h)=>{this.framePool.currentFrames[0].msg.send("go_text",["",n],c=>l(c))})),i){t(i);return}const r=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(r&&(i=await new Promise((l,h)=>{this.framePool.currentFrames[0].msg.send("go_id",r,c=>l(c))})),i){t(i);return}const s=e?.locations?.progression;s&&s>0?i=await new Promise((l,h)=>{this.framePool.currentFrames[0].msg.send("go_progression",s,c=>l(c))}):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,Yr=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}async build(e=!1){if(this.item.mediaType.isHTML)return await this.buildHtmlFrame(e);if(this.item.mediaType.isBitmap||this.item.mediaType.equals(g.SVG))return await this.buildImageFrame();throw Error("Unsupported frame mediatype "+this.item.mediaType.string)}async buildHtmlFrame(e=!1){const t=await this.pub.get(this.item).readAsString();if(!t)throw new Error(`Failed reading item ${this.item.href}`);const i=new DOMParser().parseFromString(t,this.item.mediaType.string),n=i.querySelector("parsererror");if(n){const r=n.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${r?.textContent||n.textContent}`)}return this.injector&&await this.injector.injectForDocument(i,this.item),this.finalizeDOM(i,this.pub.baseURL,(await this.pub.get(this.item).link()).toURL(this.baseURL)||"",this.item.mediaType,e,this.cssProperties)}async buildImageFrame(){const e=(await this.pub.get(this.item).link()).toURL(this.baseURL)||"",t=document.implementation.createHTMLDocument(this.item.title||this.item.href),i=document.createElement("img");return i.src=e||"",i.alt=this.item.title||"",i.decoding="async",t.body.appendChild(i),this.finalizeDOM(t,this.pub.baseURL,e,this.item.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(c=>{c.setAttribute("fetchpriority","high"),c.setAttribute("referrerpolicy","origin")}),n.isHTML&&this.pub.metadata.languages?.[0]){const c=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=c,document.documentElement.setAttribute("xml:lang",c))}else n===g.HTML&&!document.documentElement.lang&&(document.documentElement.lang=c)}if(i!==void 0){const c=e.createElement("base");c.href=i,c.dataset.readium="true",e.head.firstChild.before(c)}const h=e.createElement("meta");return h.httpEquiv="Content-Security-Policy",h.content=Yr(l),h.dataset.readium="true",e.head.firstChild.before(h),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=>{this.injector?.releaseBlobUrl?.(s),URL.revokeObjectURL(s)}),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,h)=>h.locations.position||0>l?h.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,h)=>{const c=[],u=[];this.positions.forEach((d,p)=>{(p>r+mn||p<r-mn)&&(c.includes(d.href)||c.push(d.href)),p<r+gn&&p>r-gn&&(u.includes(d.href)||u.push(d.href))}),c.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=>{this.injector?.releaseBlobUrl?.(d),URL.revokeObjectURL(d)}),this.blobs.clear()),this.currentBaseURL=e.baseURL;const m=async d=>{if(n&&(this.blobs.forEach(_=>{this.injector?.releaseBlobUrl?.(_),URL.revokeObjectURL(_)}),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(d)&&this.pendingUpdates.get(d)?.inPool===!1){const _=this.blobs.get(d);_&&(this.injector?.releaseBlobUrl?.(_),URL.revokeObjectURL(_),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const _=this.pool.get(d);if(!this.blobs.has(d))await _.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await _.load(i);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;if(!this.blobs.has(d)){const O=await new un(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}).build();this.blobs.set(d,O)}const S=new pn(this.blobs.get(d),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){h(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.currModules=[],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===U.rtl?"right":"left",this.wrapper.appendChild(this.frame)}async load(e,t){return 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(){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{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 h={X:null,Y:null};return n.X<a?h.X=0:l<n.X?h.X=2:h.X=1,n.Y<r?h.Y=0:s<n.Y?h.Y=2:h.Y=1,{Target:e.target,Coord:t,Ratio:n,Division:h}}}class qr{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 qr)}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 h=-l.X/r;h+=l.X/this.scale,this.pinch.target.X+=h,l.X+=this.pinch.target.X*this.scale/this.pinch.startScale;let c=-l.Y/r;c+=l.Y/this.scale,this.pinch.target.Y+=c,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)}
|
|
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 Fe="readium:navigator:suspiciousActivity";class cn{dispatchSuspiciousActivity(e,t){const i=new CustomEvent(Fe,{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 Ie="readium:navigator:keyboardPeripheral";class hn{constructor(e={}){this.keyManager=new Ii,this.setupKeyboardPeripherals(e.keyboardPeripherals||[])}setupKeyboardPeripherals(e){if(e.length>0){const t=i=>{const n=new CustomEvent(Ie,{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 It(this._preferences,this._defaults,this.hasDisplayTransformability),this._css=new Ji({rsProperties:new Ki({experiments:this._settings.experiments||null}),userProperties:new Ut({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 h=l;this.listeners.contentProtection(h.detail.type,h.detail)},window.addEventListener(Fe,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new hn({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=l=>{const h=l.detail;this.listeners.peripheral(h)},window.addEventListener(Ie,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 Yi(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 It(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 c=new URL(this.currentLocation.href);l=new URL(a,c).href}else l=tt.join(tt.dirname(this.currentLocation.href),a);const h=this.pub.readingOrder.findWithHref(l);h?this.goLink(h,!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(Fe,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(Ie,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,h)=>{this.framePool.currentFrames[0].msg.send("go_text",n?[e.text?.serialize(),n]:e.text?.serialize(),c=>l(c))}):n&&(i=await new Promise((l,h)=>{this.framePool.currentFrames[0].msg.send("go_text",["",n],c=>l(c))})),i){t(i);return}const r=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(r&&(i=await new Promise((l,h)=>{this.framePool.currentFrames[0].msg.send("go_id",r,c=>l(c))})),i){t(i);return}const s=e?.locations?.progression;s&&s>0?i=await new Promise((l,h)=>{this.framePool.currentFrames[0].msg.send("go_progression",s,c=>l(c))}):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,Yr=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}async build(e=!1){if(this.item.mediaType.isHTML)return await this.buildHtmlFrame(e);if(this.item.mediaType.isBitmap||this.item.mediaType.equals(g.SVG))return await this.buildImageFrame();throw Error("Unsupported frame mediatype "+this.item.mediaType.string)}async buildHtmlFrame(e=!1){const t=await this.pub.get(this.item).readAsString();if(!t)throw new Error(`Failed reading item ${this.item.href}`);const i=new DOMParser().parseFromString(t,this.item.mediaType.string),n=i.querySelector("parsererror");if(n){const r=n.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${r?.textContent||n.textContent}`)}return this.injector&&await this.injector.injectForDocument(i,this.item),this.finalizeDOM(i,this.pub.baseURL,(await this.pub.get(this.item).link()).toURL(this.baseURL)||"",this.item.mediaType,e,this.cssProperties)}async buildImageFrame(){const e=await this.pub.get(this.item).link(),t=e.toURL(this.baseURL)||"",i=document.implementation.createHTMLDocument(this.item.title||this.item.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=this.item.title||"",n.decoding="async",i.body.appendChild(n),this.injector&&await this.injector.injectForDocument(i,this.item);const r=i.createElement("style");return r.dataset.readium="true",r.textContent=`
|
|
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,this.item.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(c=>{c.setAttribute("fetchpriority","high"),c.setAttribute("referrerpolicy","origin")}),n.isHTML&&this.pub.metadata.languages?.[0]){const c=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=c,document.documentElement.setAttribute("xml:lang",c))}else n===g.HTML&&!document.documentElement.lang&&(document.documentElement.lang=c)}if(i!==void 0){const c=e.createElement("base");c.href=i,c.dataset.readium="true",e.head.firstChild.before(c)}const h=e.createElement("meta");return h.httpEquiv="Content-Security-Policy",h.content=Yr(l),h.dataset.readium="true",e.head.firstChild.before(h),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=>{this.injector?.releaseBlobUrl?.(s),URL.revokeObjectURL(s)}),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,h)=>h.locations.position||0>l?h.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,h)=>{const c=[],u=[];this.positions.forEach((d,p)=>{(p>r+mn||p<r-mn)&&(c.includes(d.href)||c.push(d.href)),p<r+gn&&p>r-gn&&(u.includes(d.href)||u.push(d.href))}),c.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=>{this.injector?.releaseBlobUrl?.(d),URL.revokeObjectURL(d)}),this.blobs.clear()),this.currentBaseURL=e.baseURL;const m=async d=>{if(n&&(this.blobs.forEach(_=>{this.injector?.releaseBlobUrl?.(_),URL.revokeObjectURL(_)}),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(d)&&this.pendingUpdates.get(d)?.inPool===!1){const _=this.blobs.get(d);_&&(this.injector?.releaseBlobUrl?.(_),URL.revokeObjectURL(_),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const _=this.pool.get(d);if(!this.blobs.has(d))await _.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await _.load(i);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;if(!this.blobs.has(d)){const O=await new un(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}).build();this.blobs.set(d,O)}const S=new pn(this.blobs.get(d),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){h(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.currModules=[],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===U.rtl?"right":"left",this.wrapper.appendChild(this.frame)}async load(e,t){return 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(){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{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 h={X:null,Y:null};return n.X<a?h.X=0:l<n.X?h.X=2:h.X=1,n.Y<r?h.Y=0:s<n.Y?h.Y=2:h.Y=1,{Target:e.target,Coord:t,Ratio:n,Division:h}}}class qr{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 qr)}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 h=-l.X/r;h+=l.X/this.scale,this.pinch.target.X+=h,l.X+=this.pinch.target.X*this.scale/this.pinch.startScale;let c=-l.Y/r;c+=l.Y/this.scale,this.pinch.target.Y+=c,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)}
|
|
402
404
|
TY: ${this.pan.translateY.toFixed(2)}
|
|
403
405
|
Zoom: ${this.scale.toFixed(2)}
|
|
404
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,h=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)*h}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===U.rtl?"right":"left":e.metadata.readingProgression===U.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!==U.rtl&&this.pub.metadata.effectiveReadingProgression!==U.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),this.pub.readingOrder.items.forEach(a=>{const l=new yn(this.peripherals,this.pub.metadata.effectiveReadingProgression,a.href,this.contentProtectionConfig,this.keyboardPeripheralsConfig);this.spineElement.appendChild(l.element),this.pool.set(a.href,l),l.width=100/this.length*(a.properties?.otherProperties.orientation===st.landscape||a.properties?.otherProperties.addBlank?this.perPage:1),l.height=this.height})}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(()=>{this.pool.forEach((i,n)=>{let r=this.pub.readingOrder.items.findIndex(l=>l.href===n);const s=this.pub.readingOrder.items[r];if(i.width=100/this.length*(s.properties?.otherProperties.orientation===st.landscape||s.properties?.otherProperties.addBlank?this.perPage:1),i.height=this.height,!i.loaded)return;const a=this.spreader.findByLink(s);i.update(this.spreadPosition(a,s))})},Zr)}updateDimensions(){this.width=this.bookElement.clientWidth,this.height=this.bookElement.clientHeight}get rtl(){return this.pub.metadata.effectiveReadingProgression===U.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=>URL.revokeObjectURL(s)),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,h)=>{const c=[],u=[];this.positions.forEach((d,p)=>{(p>r+En||p<r-En)&&(c.includes(d.href)||c.push(d.href)),p<r+kn&&p>r-kn&&(u.includes(d.href)||u.push(d.href))}),c.forEach(async d=>{u.includes(d)||this.pool.has(d)&&(this.cancelShowing(d),await this.pool.get(d)?.unload())}),this.currentBaseURL!==void 0&&e.baseURL!==this.currentBaseURL&&(this.blobs.forEach(d=>URL.revokeObjectURL(d)),this.blobs.clear()),this.currentBaseURL=e.baseURL;const m=async d=>{const p=e.readingOrder.findIndexWithHref(d),S=e.readingOrder.items[p];if(S){if(!this.blobs.has(d)){const O=await new un(e,this.currentBaseURL||"",S,{injector:this.injector}).build(!0);this.blobs.set(d,O)}this.delayedShow.has(d)||this.delayedShow.set(d,new Promise((_,O)=>{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),Fn=this.pool.get(d);await Fn.load(i,this.blobs.get(d)),this.peripherals.isScaled||await Fn.show(yo),this.delayedShow.delete(d),ne=!0,_()},Kr);setTimeout(()=>{!ne&&this.delayedShow.has(d)&&O(`Offscreen load timeout: ${d}`)},Jr),this.delayedTimeout.set(d,go)}))}};try{await Promise.all(u.map(d=>m(d)))}catch(d){h(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,S),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=N(e.backgroundColor),this.blendFilter=C(e.blendFilter),this.constraint=w(e.constraint),this.columnCount=w(e.columnCount),this.darkenFilter=le(e.darkenFilter),this.deprecatedFontSize=C(e.deprecatedFontSize),this.fontFamily=N(e.fontFamily),this.fontSize=Y(e.fontSize,xe.range),this.fontSizeNormalize=C(e.fontSizeNormalize),this.fontOpticalSizing=C(e.fontOpticalSizing),this.fontWeight=Y(e.fontWeight,Z.range),this.fontWidth=Y(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=w(e.letterSpacing),this.ligatures=C(e.ligatures),this.lineHeight=w(e.lineHeight),this.linkColor=N(e.linkColor),this.noRuby=C(e.noRuby),this.pageGutter=w(e.pageGutter),this.paragraphIndent=w(e.paragraphIndent),this.paragraphSpacing=w(e.paragraphSpacing),this.scroll=C(e.scroll),this.scrollPaddingTop=w(e.scrollPaddingTop),this.scrollPaddingBottom=w(e.scrollPaddingBottom),this.scrollPaddingLeft=w(e.scrollPaddingLeft),this.scrollPaddingRight=w(e.scrollPaddingRight),this.selectionBackgroundColor=N(e.selectionBackgroundColor),this.selectionTextColor=N(e.selectionTextColor),this.textAlign=Ue(e.textAlign,K),this.textColor=N(e.textColor),this.textNormalization=C(e.textNormalization),this.visitedColor=N(e.visitedColor),this.wordSpacing=w(e.wordSpacing),this.optimalLineLength=w(e.optimalLineLength),this.maximalLineLength=w(e.maximalLineLength),this.minimalLineLength=w(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=N(e.backgroundColor)||null,this.blendFilter=C(e.blendFilter)??!1,this.constraint=w(e.constraint)||0,this.columnCount=w(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=N(e.fontFamily)||null,this.fontSize=Y(e.fontSize,xe.range)||1,this.fontSizeNormalize=C(e.fontSizeNormalize)??!1,this.fontOpticalSizing=C(e.fontOpticalSizing)??null,this.fontWeight=Y(e.fontWeight,Z.range)||null,this.fontWidth=Y(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=w(e.letterSpacing)||null,this.ligatures=C(e.ligatures)??null,this.lineHeight=w(e.lineHeight)||null,this.linkColor=N(e.linkColor)||null,this.noRuby=C(e.noRuby)??!1,this.pageGutter=nt(w(e.pageGutter),20),this.paragraphIndent=w(e.paragraphIndent)??null,this.paragraphSpacing=w(e.paragraphSpacing)??null,this.scroll=C(e.scroll)??!1,this.scrollPaddingTop=w(e.scrollPaddingTop)??null,this.scrollPaddingBottom=w(e.scrollPaddingBottom)??null,this.scrollPaddingLeft=w(e.scrollPaddingLeft)??null,this.scrollPaddingRight=w(e.scrollPaddingRight)??null,this.selectionBackgroundColor=N(e.selectionBackgroundColor)||null,this.selectionTextColor=N(e.selectionTextColor)||null,this.textAlign=Ue(e.textAlign,K)||null,this.textColor=N(e.textColor)||null,this.textNormalization=C(e.textNormalization)??!1,this.visitedColor=N(e.visitedColor)||null,this.wordSpacing=w(e.wordSpacing)||null,this.optimalLineLength=w(e.optimalLineLength)||65,this.maximalLineLength=nt(Qi(e.maximalLineLength,this.optimalLineLength),80),this.minimalLineLength=nt(Zi(e.minimalLineLength,this.optimalLineLength),40),this.experiments=Ft(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 T({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 M({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 T({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 T({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 M({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 T({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 M({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 M({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 M({initialValue:this.preferences.hyphens,effectiveValue:this.settings.hyphens||!1,isEffective:this.layout!==v.fixed&&this.metadata?.effectiveReadingProgression===U.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 M({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 M({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 M({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 T({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 M({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 T({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 M({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 T({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 T({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 T({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 T({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 T({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 T({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 T({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 M({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 T({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:h}=r,c=()=>n>=a&&h!==null?Math.min(Math.round(h*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&&h!==null){u=Math.floor(n/a);const b=Math.round(u*(h*s));m=Math.min(b,n)}else m=c();else if(i>1){const b=Math.round(i*(l!==null?l:a));if(n>=b)if(u=i,h===null)m=n;else{const d=Math.round(u*(h*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=c();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=c();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,h=i,c=Math.round(s*r);if(a===null)c=i;else{const u=Math.min(Math.round(a*r),i);c=t?u:Math.round(u*r)}return{colCount:l,effectiveContainerWidth:h,effectiveLineLength:c}}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
|
@@ -39,11 +39,12 @@ export default class FrameBlobBuider {
|
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
public async build(fxl = false): Promise<string> {
|
|
42
|
-
|
|
43
|
-
|
|
42
|
+
const link = await this.pub.get(this.item).link();
|
|
43
|
+
if(!link.mediaType.isHTML) {
|
|
44
|
+
if(link.mediaType.isBitmap || link.mediaType.equals(MediaType.SVG)) {
|
|
44
45
|
return await this.buildImageFrame();
|
|
45
46
|
} else
|
|
46
|
-
throw Error("Unsupported frame mediatype " +
|
|
47
|
+
throw Error("Unsupported frame mediatype " + link.mediaType.string);
|
|
47
48
|
} else {
|
|
48
49
|
return await this.buildHtmlFrame(fxl);
|
|
49
50
|
}
|
|
@@ -51,39 +52,71 @@ export default class FrameBlobBuider {
|
|
|
51
52
|
|
|
52
53
|
private async buildHtmlFrame(fxl = false): Promise<string> {
|
|
53
54
|
// Load the HTML resource
|
|
54
|
-
const
|
|
55
|
-
|
|
55
|
+
const resource = this.pub.get(this.item);
|
|
56
|
+
const link = await resource.link();
|
|
57
|
+
const txt = await resource.readAsString();
|
|
58
|
+
if(!txt) throw new Error(`Failed reading item ${link.href}`);
|
|
56
59
|
|
|
57
60
|
const doc = new DOMParser().parseFromString(
|
|
58
61
|
txt,
|
|
59
|
-
|
|
62
|
+
link.mediaType.string as DOMParserSupportedType
|
|
60
63
|
);
|
|
61
|
-
|
|
64
|
+
|
|
62
65
|
const perror = doc.querySelector("parsererror");
|
|
63
66
|
if (perror) {
|
|
64
67
|
const details = perror.querySelector("div");
|
|
65
|
-
throw new Error(`Failed parsing item ${
|
|
68
|
+
throw new Error(`Failed parsing item ${link.href}: ${details?.textContent || perror.textContent}`);
|
|
66
69
|
}
|
|
67
70
|
|
|
68
71
|
// Apply resource injections if injection service is provided
|
|
69
72
|
if (this.injector) {
|
|
70
|
-
await this.injector.injectForDocument(doc,
|
|
73
|
+
await this.injector.injectForDocument(doc, link);
|
|
71
74
|
}
|
|
72
75
|
|
|
73
|
-
return this.finalizeDOM(doc, this.pub.baseURL,
|
|
76
|
+
return this.finalizeDOM(doc, this.pub.baseURL, link.toURL(this.baseURL) || "", link.mediaType, fxl, this.cssProperties);
|
|
74
77
|
}
|
|
75
78
|
|
|
76
79
|
private async buildImageFrame(): Promise<string> {
|
|
77
|
-
const
|
|
80
|
+
const link = await this.pub.get(this.item).link();
|
|
81
|
+
const burl = link.toURL(this.baseURL) || ""
|
|
82
|
+
|
|
83
|
+
// Rudimentary image display in an HTML doc
|
|
84
|
+
const doc = document.implementation.createHTMLDocument(link.title || link.href);
|
|
85
|
+
|
|
86
|
+
// Add viewport if available
|
|
87
|
+
if((link?.height || 0) > 0 && (link?.width || 0) > 0) {
|
|
88
|
+
const viewportMeta = doc.createElement("meta");
|
|
89
|
+
viewportMeta.name = "viewport";
|
|
90
|
+
viewportMeta.content = `width=${link.width}, height=${link.height}`;
|
|
91
|
+
viewportMeta.dataset.readium = "true";
|
|
92
|
+
doc.head.appendChild(viewportMeta);
|
|
93
|
+
}
|
|
78
94
|
|
|
79
|
-
// Rudimentary image display
|
|
80
|
-
const doc = document.implementation.createHTMLDocument(this.item.title || this.item.href);
|
|
81
95
|
const simg = document.createElement("img");
|
|
82
96
|
simg.src = burl || "";
|
|
83
|
-
simg.alt =
|
|
97
|
+
simg.alt = link.title || "";
|
|
84
98
|
simg.decoding = "async";
|
|
85
99
|
doc.body.appendChild(simg);
|
|
86
|
-
|
|
100
|
+
|
|
101
|
+
// Apply resource injections if injection service is provided
|
|
102
|
+
if (this.injector) {
|
|
103
|
+
await this.injector.injectForDocument(doc, new Link({
|
|
104
|
+
// Temporary solution to address injector only expecting (X)HTML
|
|
105
|
+
// documents for injection, which we are technically providing
|
|
106
|
+
href: "readium-image-frame.xhtml",
|
|
107
|
+
type: MediaType.XHTML.string
|
|
108
|
+
}));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Add image style
|
|
112
|
+
const sstyle = doc.createElement("style");
|
|
113
|
+
sstyle.dataset.readium = "true";
|
|
114
|
+
sstyle.textContent = `
|
|
115
|
+
html, body { width: 100%; height: 100%; margin: 0; padding: 0; font-size: 0; }
|
|
116
|
+
img { margin: 0; padding: 0; border: 0; }`;
|
|
117
|
+
doc.head.appendChild(sstyle);
|
|
118
|
+
|
|
119
|
+
return this.finalizeDOM(doc, this.pub.baseURL, burl, link.mediaType, true);
|
|
87
120
|
}
|
|
88
121
|
|
|
89
122
|
private setProperties(cssProperties: { [key: string]: string }, doc: Document) {
|