@readium/navigator 2.2.1 → 2.2.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 +651 -634
- package/dist/index.umd.cjs +17 -17
- package/package.json +1 -1
- package/src/webpub/WebPubNavigator.ts +19 -4
- package/src/webpub/preferences/WebPubPreferencesEditor.ts +18 -12
- package/src/webpub/preferences/WebPubSettings.ts +59 -57
- package/types/src/webpub/WebPubNavigator.d.ts +7 -0
- package/types/src/webpub/preferences/WebPubPreferencesEditor.d.ts +1 -0
- package/types/src/webpub/preferences/WebPubSettings.d.ts +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(B,j){typeof exports=="object"&&typeof module<"u"?j(exports):typeof define=="function"&&define.amd?define(["exports"],j):(B=typeof globalThis<"u"?globalThis:B||self,j(B.navigator={}))})(this,(function(B){"use strict";const j=class wt{constructor(t){if(typeof t=="string"){if(!wt.VALID_MODES.has(t.toLowerCase()))return;this.value=t.toLowerCase()}else{const e=t.filter(i=>wt.VALID_MODES.has(i.toLowerCase()));if(e.length===0)return;this.value=Array.from(new Set(e))}}static deserialize(t){if(!t)return;if(typeof t=="string")return new wt(t);if(!Array.isArray(t))return;const e=t.filter(i=>i?wt.VALID_MODES.has(i.toLowerCase()):!1);if(e.length!==0)return new wt(e)}serialize(){return this.value}};j.VALID_MODES=new Set(["auditory","tactile","textual","visual"]),j.AUDITORY=new j("auditory"),j.TACTILE=new j("tactile"),j.TEXTUAL=new j("textual"),j.VISUAL=new j("visual");const p=class BA{constructor(t){this.value=t}static deserialize(t){if(!(!t||typeof t!="string"))return new BA(t)}serialize(){return this.value}};p.NONE=new p("none"),p.ANNOTATIONS=new p("annotations"),p.ARIA=new p("ARIA"),p.INDEX=new p("index"),p.PAGE_BREAK_MARKERS=new p("pageBreakMarkers"),p.PAGE_NAVIGATION=new p("pageNavigation"),p.PRINT_PAGE_NUMBERS=new p("printPageNumbers"),p.READING_ORDER=new p("readingOrder"),p.STRUCTURAL_NAVIGATION=new p("structuralNavigation"),p.TABLE_OF_CONTENTS=new p("tableOfContents"),p.TAGGED_PDF=new p("taggedPDF"),p.ALTERNATIVE_TEXT=new p("alternativeText"),p.AUDIO_DESCRIPTION=new p("audioDescription"),p.CAPTIONS=new p("captions"),p.CLOSED_CAPTIONS=new p("closedCaptions"),p.DESCRIBED_MATH=new p("describedMath"),p.LONG_DESCRIPTION=new p("longDescription"),p.OPEN_CAPTIONS=new p("openCaptions"),p.SIGN_LANGUAGE=new p("signLanguage"),p.TRANSCRIPT=new p("transcript"),p.DISPLAY_TRANSFORMABILITY=new p("displayTransformability"),p.SYNCHRONIZED_AUDIO_TEXT=new p("synchronizedAudioText"),p.TIMING_CONTROL=new p("timingControl"),p.UNLOCKED=new p("unlocked"),p.CHEM_ML=new p("ChemML"),p.LATEX=new p("latex"),p.LATEX_CHEMISTRY=new p("latex-chemistry"),p.MATH_ML=new p("MathML"),p.MATH_ML_CHEMISTRY=new p("MathML-chemistry"),p.TTS_MARKUP=new p("ttsMarkup"),p.HIGH_CONTRAST_AUDIO=new p("highContrastAudio"),p.HIGH_CONTRAST_DISPLAY=new p("highContrastDisplay"),p.LARGE_PRINT=new p("largePrint"),p.BRAILLE=new p("braille"),p.TACTILE_GRAPHIC=new p("tactileGraphic"),p.TACTILE_OBJECT=new p("tactileObject"),p.FULL_RUBY_ANNOTATIONS=new p("fullRubyAnnotations"),p.HORIZONTAL_WRITING=new p("horizontalWriting"),p.RUBY_ANNOTATIONS=new p("rubyAnnotations"),p.VERTICAL_WRITING=new p("verticalWriting"),p.WITH_ADDITIONAL_WORD_SEGMENTATION=new p("withAdditionalWordSegmentation"),p.WITHOUT_ADDITIONAL_WORD_SEGMENTATION=new p("withoutAdditionalWordSegmentation");let v=p;var w=(r=>(r.reflowable="reflowable",r.fixed="fixed",r.scrolled="scrolled",r))(w||{});class $t{constructor(t){this.algorithm=t.algorithm,this.compression=t.compression,this.originalLength=t.originalLength,this.profile=t.profile,this.scheme=t.scheme}static deserialize(t){if(t&&t.algorithm)return new $t({algorithm:t.algorithm,compression:t.compression,originalLength:t.originalLength,profile:t.profile,scheme:t.scheme})}serialize(){const t={algorithm:this.algorithm};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}}var k=(r=>(r.left="left",r.right="right",r.center="center",r))(k||{});let J=class be{constructor(t){this.otherProperties=t}get page(){return this.otherProperties.page}static deserialize(t){if(t)return new be(t)}serialize(){return this.otherProperties}add(t){const e=Object.assign({},this.otherProperties);for(const i in t)e[i]=t[i];return new be(e)}};Object.defineProperty(J.prototype,"encryption",{get:function(){return $t.deserialize(this.otherProperties.encrypted)}});function UA(r){return r&&Array.isArray(r)?r:void 0}function De(r){return r&&typeof r=="string"?[r]:UA(r)}function He(r){return typeof r=="string"?new Date(r):void 0}function xt(r){return isNaN(r)?void 0:r}function T(r){return xt(r)!==void 0&&Math.sign(r)>=0?r:void 0}function yA(r){const t=new Array;return r.forEach(e=>t.push(e)),t}class d{constructor(t){let e,i,A=t.mediaType.replace(/\s/g,"").split(";");const n=A[0].split("/");if(n.length===2){if(e=n[0].toLowerCase().trim(),i=n[1].toLowerCase().trim(),e.length===0||i.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const s={};for(let u=1;u<A.length;u++){const M=A[u].split("=");if(M.length===2){const l=M[0].toLocaleLowerCase(),f=l==="charset"?M[1].toUpperCase():M[1];s[l]=f}}const o={},a=Object.keys(s);a.sort((u,M)=>u.localeCompare(M)),a.forEach(u=>o[u]=s[u]);let h="";for(const u in o){const M=o[u];h+=`;${u}=${M}`}const c=`${e}/${i}${h}`,g=o.encoding;this.string=c,this.type=e,this.subtype=i,this.parameters=o,this.encoding=g,this.name=t.name,this.fileExtension=t.fileExtension}static parse(t){return new d(t)}get structuredSyntaxSuffix(){const t=this.subtype.split("+");return t.length>1?`+${t[t.length-1]}`:void 0}get charset(){return this.parameters.charset}contains(t){const e=typeof t=="string"?d.parse({mediaType:t}):t;if(!((this.type==="*"||this.type===e.type)&&(this.subtype==="*"||this.subtype===e.subtype)))return!1;const i=new Set(Object.entries(this.parameters).map(([n,s])=>`${n}=${s}`)),A=new Set(Object.entries(e.parameters).map(([n,s])=>`${n}=${s}`));for(const n of Array.from(i.values()))if(!A.has(n))return!1;return!0}matches(t){const e=typeof t=="string"?d.parse({mediaType:t}):t;return this.contains(e)||e.contains(this)}matchesAny(...t){for(const e of t)if(this.matches(e))return!0;return!1}equals(t){return this.string===t.string}get isZIP(){return this.matchesAny(d.ZIP,d.LCP_PROTECTED_AUDIOBOOK,d.LCP_PROTECTED_PDF)||this.structuredSyntaxSuffix==="+zip"}get isJSON(){return this.matchesAny(d.JSON)||this.structuredSyntaxSuffix==="+json"}get isOPDS(){return this.matchesAny(d.OPDS1,d.OPDS1_ENTRY,d.OPDS2,d.OPDS2_PUBLICATION,d.OPDS_AUTHENTICATION)||this.structuredSyntaxSuffix==="+json"}get isHTML(){return this.matchesAny(d.HTML,d.XHTML)}get isBitmap(){return this.matchesAny(d.BMP,d.GIF,d.JPEG,d.PNG,d.TIFF,d.WEBP)}get isAudio(){return this.type==="audio"}get isVideo(){return this.type==="video"}get isRWPM(){return this.matchesAny(d.READIUM_AUDIOBOOK_MANIFEST,d.DIVINA_MANIFEST,d.READIUM_WEBPUB_MANIFEST)}get isPublication(){return this.matchesAny(d.READIUM_AUDIOBOOK,d.READIUM_AUDIOBOOK_MANIFEST,d.CBZ,d.DIVINA,d.DIVINA_MANIFEST,d.EPUB,d.LCP_PROTECTED_AUDIOBOOK,d.LCP_PROTECTED_PDF,d.LPF,d.PDF,d.W3C_WPUB_MANIFEST,d.READIUM_WEBPUB,d.READIUM_WEBPUB_MANIFEST,d.ZAB)}static get AAC(){return d.parse({mediaType:"audio/aac",fileExtension:"aac"})}static get ACSM(){return d.parse({mediaType:"application/vnd.adobe.adept+xml",name:"Adobe Content Server Message",fileExtension:"acsm"})}static get AIFF(){return d.parse({mediaType:"audio/aiff",fileExtension:"aiff"})}static get AVI(){return d.parse({mediaType:"video/x-msvideo",fileExtension:"avi"})}static get BINARY(){return d.parse({mediaType:"application/octet-stream"})}static get BMP(){return d.parse({mediaType:"image/bmp",fileExtension:"bmp"})}static get CBZ(){return d.parse({mediaType:"application/vnd.comicbook+zip",name:"Comic Book Archive",fileExtension:"cbz"})}static get CSS(){return d.parse({mediaType:"text/css",fileExtension:"css"})}static get DIVINA(){return d.parse({mediaType:"application/divina+zip",name:"Digital Visual Narratives",fileExtension:"divina"})}static get DIVINA_MANIFEST(){return d.parse({mediaType:"application/divina+json",name:"Digital Visual Narratives",fileExtension:"json"})}static get EPUB(){return d.parse({mediaType:"application/epub+zip",name:"EPUB",fileExtension:"epub"})}static get GIF(){return d.parse({mediaType:"image/gif",fileExtension:"gif"})}static get GZ(){return d.parse({mediaType:"application/gzip",fileExtension:"gz"})}static get HTML(){return d.parse({mediaType:"text/html",fileExtension:"html"})}static get JAVASCRIPT(){return d.parse({mediaType:"text/javascript",fileExtension:"js"})}static get JPEG(){return d.parse({mediaType:"image/jpeg",fileExtension:"jpeg"})}static get JSON(){return d.parse({mediaType:"application/json"})}static get LCP_LICENSE_DOCUMENT(){return d.parse({mediaType:"application/vnd.readium.lcp.license.v1.0+json",name:"LCP License",fileExtension:"lcpl"})}static get LCP_PROTECTED_AUDIOBOOK(){return d.parse({mediaType:"application/audiobook+lcp",name:"LCP Protected Audiobook",fileExtension:"lcpa"})}static get LCP_PROTECTED_PDF(){return d.parse({mediaType:"application/pdf+lcp",name:"LCP Protected PDF",fileExtension:"lcpdf"})}static get LCP_STATUS_DOCUMENT(){return d.parse({mediaType:"application/vnd.readium.license.status.v1.0+json"})}static get LPF(){return d.parse({mediaType:"application/lpf+zip",fileExtension:"lpf"})}static get MP3(){return d.parse({mediaType:"audio/mpeg",fileExtension:"mp3"})}static get MPEG(){return d.parse({mediaType:"video/mpeg",fileExtension:"mpeg"})}static get NCX(){return d.parse({mediaType:"application/x-dtbncx+xml",fileExtension:"ncx"})}static get OGG(){return d.parse({mediaType:"audio/ogg",fileExtension:"oga"})}static get OGV(){return d.parse({mediaType:"video/ogg",fileExtension:"ogv"})}static get OPDS1(){return d.parse({mediaType:"application/atom+xml;profile=opds-catalog"})}static get OPDS1_ENTRY(){return d.parse({mediaType:"application/atom+xml;type=entry;profile=opds-catalog"})}static get OPDS2(){return d.parse({mediaType:"application/opds+json"})}static get OPDS2_PUBLICATION(){return d.parse({mediaType:"application/opds-publication+json"})}static get OPDS_AUTHENTICATION(){return d.parse({mediaType:"application/opds-authentication+json"})}static get OPUS(){return d.parse({mediaType:"audio/opus",fileExtension:"opus"})}static get OTF(){return d.parse({mediaType:"font/otf",fileExtension:"otf"})}static get PDF(){return d.parse({mediaType:"application/pdf",name:"PDF",fileExtension:"pdf"})}static get PNG(){return d.parse({mediaType:"image/png",fileExtension:"png"})}static get READIUM_AUDIOBOOK(){return d.parse({mediaType:"application/audiobook+zip",name:"Readium Audiobook",fileExtension:"audiobook"})}static get READIUM_AUDIOBOOK_MANIFEST(){return d.parse({mediaType:"application/audiobook+json",name:"Readium Audiobook",fileExtension:"json"})}static get READIUM_CONTENT_DOCUMENT(){return d.parse({mediaType:"application/vnd.readium.content+json",name:"Readium Content Document",fileExtension:"json"})}static get READIUM_GUIDED_NAVIGATION_DOCUMENT(){return d.parse({mediaType:"application/guided-navigation+json",name:"Readium Guided Navigation Document",fileExtension:"json"})}static get READIUM_POSITION_LIST(){return d.parse({mediaType:"application/vnd.readium.position-list+json",name:"Readium Position List",fileExtension:"json"})}static get READIUM_WEBPUB(){return d.parse({mediaType:"application/webpub+zip",name:"Readium Web Publication",fileExtension:"webpub"})}static get READIUM_WEBPUB_MANIFEST(){return d.parse({mediaType:"application/webpub+json",name:"Readium Web Publication",fileExtension:"json"})}static get SMIL(){return d.parse({mediaType:"application/smil+xml",fileExtension:"smil"})}static get SVG(){return d.parse({mediaType:"image/svg+xml",fileExtension:"svg"})}static get TEXT(){return d.parse({mediaType:"text/plain",fileExtension:"txt"})}static get TIFF(){return d.parse({mediaType:"image/tiff",fileExtension:"tiff"})}static get TTF(){return d.parse({mediaType:"font/ttf",fileExtension:"ttf"})}static get W3C_WPUB_MANIFEST(){return d.parse({mediaType:"application/x.readium.w3c.wpub+json",name:"Web Publication",fileExtension:"json"})}static get WAV(){return d.parse({mediaType:"audio/wav",fileExtension:"wav"})}static get WEBM_AUDIO(){return d.parse({mediaType:"audio/webm",fileExtension:"webm"})}static get WEBM_VIDEO(){return d.parse({mediaType:"video/webm",fileExtension:"webm"})}static get WEBP(){return d.parse({mediaType:"image/webp",fileExtension:"webp"})}static get WOFF(){return d.parse({mediaType:"font/woff",fileExtension:"woff"})}static get WOFF2(){return d.parse({mediaType:"font/woff2",fileExtension:"woff2"})}static get XHTML(){return d.parse({mediaType:"application/xhtml+xml",fileExtension:"xhtml"})}static get XML(){return d.parse({mediaType:"application/xml",fileExtension:"xml"})}static get ZAB(){return d.parse({mediaType:"application/x.readium.zab+zip",name:"Zipped Audio Book",fileExtension:"zab"})}static get ZIP(){return d.parse({mediaType:"application/zip",fileExtension:"zip"})}}let Ge=class{constructor(t){this.uri=t,this.parameters=this.getParameters(t)}getParameters(t){const e=/\{\??([^}]+)\}/g,i=t.match(e);return i?new Set(i.join(",").replace(e,"$1").split(",").map(A=>A.trim())):new Set}expand(t){const e=A=>A.split(",").map(n=>{const s=t[n];return s?encodeURIComponent(s):""}).join(","),i=A=>"?"+A.split(",").map(n=>{const s=n.split("=")[0],o=t[s];return o?`${s}=${encodeURIComponent(o)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...A)=>A[1]?i(A[2]):e(A[2]))}},V=class wA{constructor(t){this.fragments=t.fragments?t.fragments:new Array,this.progression=t.progression,this.totalProgression=t.totalProgression,this.position=t.position,this.otherLocations=t.otherLocations}static deserialize(t){if(!t)return;const e=xt(t.progression),i=xt(t.totalProgression),A=xt(t.position),n=new Map,s=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(t).forEach(([o,a])=>{s.has(o)||n.set(o,a)}),new wA({fragments:De(t.fragments||t.fragment),progression:e!==void 0&&e>=0&&e<=1?e:void 0,totalProgression:i!==void 0&&i>=0&&i<=1?i:void 0,position:A!==void 0&&A>0?A:void 0,otherLocations:n.size===0?void 0:n})}serialize(){const t={};return this.fragments&&(t.fragments=this.fragments),this.progression!==void 0&&(t.progression=this.progression),this.totalProgression!==void 0&&(t.totalProgression=this.totalProgression),this.position!==void 0&&(t.position=this.position),this.otherLocations&&this.otherLocations.forEach((e,i)=>t[i]=e),t}},RA=class EA{constructor(t){this.after=t.after,this.before=t.before,this.highlight=t.highlight}static deserialize(t){if(t)return new EA({after:t.after,before:t.before,highlight:t.highlight})}serialize(){const t={};return this.after!==void 0&&(t.after=this.after),this.before!==void 0&&(t.before=this.before),this.highlight!==void 0&&(t.highlight=this.highlight),t}},lt=class je{constructor(t){this.href=t.href,this.type=t.type,this.title=t.title,this.locations=t.locations?t.locations:new V({}),this.text=t.text}static deserialize(t){if(t&&t.href&&t.type)return new je({href:t.href,type:t.type,title:t.title,locations:V.deserialize(t.locations),text:RA.deserialize(t.text)})}serialize(){const t={href:this.href,type:this.type};return this.title!==void 0&&(t.title=this.title),this.locations&&(t.locations=this.locations.serialize()),this.text&&(t.text=this.text.serialize()),t}copyWithLocations(t){return new je({href:this.href,type:this.type,title:this.title,text:this.text,locations:new V({...this.locations,...t})})}},_=class qt{constructor(t){this.href=t.href,this.templated=t.templated,this.type=t.type,this.title=t.title,this.rels=t.rels,this.properties=t.properties,this.height=t.height,this.width=t.width,this.size=t.size,this.duration=t.duration,this.bitrate=t.bitrate,this.languages=t.languages,this.alternates=t.alternates,this.children=t.children}static deserialize(t){if(!(!t||typeof t.href!="string"))return new qt({href:t.href,templated:t.templated,type:t.type,title:t.title,rels:t.rel?Array.isArray(t.rel)?new Set(t.rel):new Set([t.rel]):void 0,properties:J.deserialize(t.properties),height:T(t.height),width:T(t.width),size:T(t.size),duration:T(t.duration),bitrate:T(t.bitrate),languages:De(t.language),alternates:ke.deserialize(t.alternate),children:ke.deserialize(t.children)})}serialize(){const t={href:this.href};return this.templated!==void 0&&(t.templated=this.templated),this.type!==void 0&&(t.type=this.type),this.title!==void 0&&(t.title=this.title),this.rels&&(t.rel=yA(this.rels)),this.properties&&(t.properties=this.properties.serialize()),this.height!==void 0&&(t.height=this.height),this.width!==void 0&&(t.width=this.width),this.size!==void 0&&(t.size=this.size),this.duration!==void 0&&(t.duration=this.duration),this.bitrate!==void 0&&(t.bitrate=this.bitrate),this.languages&&(t.language=this.languages),this.alternates&&(t.alternate=this.alternates.serialize()),this.children&&(t.children=this.children.serialize()),t}get mediaType(){return this.type!==void 0?d.parse({mediaType:this.type}):d.BINARY}toURL(t){const e=this.href.replace(/^(\/)/,"");if(e.length===0)return;let i=t||"/";return i.startsWith("/")&&(i="file://"+i),new URL(e,i).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new Ge(this.href).parameters:new Set}expandTemplate(t){return new qt({href:new Ge(this.href).expand(t),templated:!1})}addProperties(t){const e=qt.deserialize(this.serialize());return e.properties=e.properties?e.properties?.add(t):new J(t),e}get locator(){let t=this.href.split("#");return new lt({href:t.length>0&&t[0]!==void 0?t[0]:this.href,type:this.type??"",title:this.title,locations:new V({fragments:t.length>1&&t[1]!==void 0?[t[1]]:[]})})}},ke=class IA{constructor(t){this.items=t}static deserialize(t){if(t&&Array.isArray(t))return new IA(t.map(e=>_.deserialize(e)).filter(e=>e!==void 0))}serialize(){return this.items.map(t=>t.serialize())}findWithRel(t){const e=i=>i.rels&&i.rels.has(t);return this.items.find(e)}filterByRel(t){const e=i=>i.rels&&i.rels.has(t);return this.items.filter(e)}findWithHref(t){const e=i=>i.href===t;return this.items.find(e)}findIndexWithHref(t){const e=i=>i.href===t;return this.items.findIndex(e)}findWithMediaType(t){const e=i=>i.mediaType.matches(t);return this.items.find(e)}filterByMediaType(t){const e=i=>i.mediaType.matches(t);return this.items.filter(e)}filterByMediaTypes(t){const e=i=>{for(const A of t)if(i.mediaType.matches(A))return!0;return!1};return this.items.filter(e)}everyIsAudio(){const t=e=>e.mediaType.isAudio;return this.items.length>0&&this.items.every(t)}everyIsBitmap(){const t=e=>e.mediaType.isBitmap;return this.items.length>0&&this.items.every(t)}everyIsHTML(){const t=e=>e.mediaType.isHTML;return this.items.length>0&&this.items.every(t)}everyIsVideo(){const t=e=>e.mediaType.isVideo;return this.items.length>0&&this.items.every(t)}everyMatchesMediaType(t){return Array.isArray(t)?this.items.length>0&&this.items.every(e=>{for(const i of t)return e.mediaType.matches(i);return!1}):this.items.length>0&&this.items.every(e=>e.mediaType.matches(t))}filterLinksHasType(){return this.items.filter(t=>t.type)}};var Je=(r=>(r.EPUB="https://readium.org/webpub-manifest/profiles/epub",r.AUDIOBOOK="https://readium.org/webpub-manifest/profiles/audiobook",r.DIVINA="https://readium.org/webpub-manifest/profiles/divina",r.PDF="https://readium.org/webpub-manifest/profiles/pdf",r))(Je||{}),Y=(r=>(r.ltr="ltr",r.rtl="rtl",r))(Y||{});J.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])};let We=class FA{constructor(t){this.cssSelector=t.cssSelector,this.textNodeIndex=t.textNodeIndex,this.charOffset=t.charOffset}static deserialize(t){if(!(t&&t.cssSelector))return;let e=T(t.textNodeIndex);if(e===void 0)return;let i=T(t.charOffset);return i===void 0&&(i=T(t.offset)),new FA({cssSelector:t.cssSelector,textNodeIndex:e,charOffset:i})}serialize(){const t={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(t.charOffset=this.charOffset),t}};class te{constructor(t){this.start=t.start,this.end=t.end}static deserialize(t){if(!t)return;let e=We.deserialize(t.start);if(e)return new te({start:e,end:We.deserialize(t.end)})}serialize(){const t={start:this.start.serialize()};return this.end&&(t.end=this.end.serialize()),t}}V.prototype.getCssSelector=function(){return this.otherLocations?.get("cssSelector")},V.prototype.getPartialCfi=function(){return this.otherLocations?.get("partialCfi")},V.prototype.getDomRange=function(){return te.deserialize(this.otherLocations?.get("domRange"))},V.prototype.fragmentParameters=function(){return new Map(this.fragments.map(r=>r.startsWith("#")?r.slice(1):r).join("&").split("&").filter(r=>!r.startsWith("#")).map(r=>r.split("=")).filter(r=>r.length===2).map(r=>[r[0].trim().toLowerCase(),r[1].trim()]))},V.prototype.htmlId=function(){if(!this.fragments.length)return;let r=this.fragments.find(t=>t.length&&!t.includes("="));if(!r){const t=this.fragmentParameters();t.has("id")?r=t.get("id"):t.has("name")&&(r=t.get("name"))}return r?.startsWith("#")?r.slice(1):r},V.prototype.page=function(){const r=parseInt(this.fragmentParameters().get("page"));if(!isNaN(r)&&r>=0)return r},V.prototype.time=function(){const r=parseInt(this.fragmentParameters().get("t"));if(!isNaN(r))return r},V.prototype.space=function(){const r=this.fragmentParameters();if(!r.has("xywh"))return;const t=r.get("xywh").split(",").map(e=>parseInt(e));if(t.length===4&&!t.some(isNaN))return t};class ee{constructor(t){this.currency=t.currency,this.value=t.value}static deserialize(t){if(!t)return;let e=t.currency;if(!(e&&typeof e=="string"&&e.length>0))return;let i=T(t.value);if(i!==void 0)return new ee({currency:e,value:i})}serialize(){return{currency:this.currency,value:this.value}}}let CA=class _t{constructor(t){this.type=t.type,this.children=t.children}static deserialize(t){if(t&&t.type)return new _t({type:t.type,children:_t.deserializeArray(t.children)})}static deserializeArray(t){if(Array.isArray(t))return t.map(e=>_t.deserialize(e)).filter(e=>e!==void 0)}serialize(){const t={type:this.type};return this.children&&(t.children=this.children.map(e=>e.serialize())),t}};class ie{constructor(t){this.total=t.total,this.position=t.position}static deserialize(t){if(t)return new ie({total:T(t.total),position:T(t.position)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.position!==void 0&&(t.position=this.position),t}}class Ae{constructor(t){this.total=t.total,this.available=t.available}static deserialize(t){if(t)return new Ae({total:T(t.total),available:T(t.available)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.available!==void 0&&(t.available=this.available),t}}class ne{constructor(t){this.state=t.state,this.since=t.since,this.until=t.until}static deserialize(t){if(t&&t.state)return new ne({state:t.state,since:He(t.since),until:He(t.until)})}serialize(){const t={state:this.state};return this.since!==void 0&&(t.since=this.since.toISOString()),this.until!==void 0&&(t.until=this.until.toISOString()),t}}J.prototype.getNumberOfItems=function(){return T(this.otherProperties.numberOfItems)},J.prototype.getPrice=function(){return ee.deserialize(this.otherProperties.price)},J.prototype.getIndirectAcquisitions=function(){const r=this.otherProperties.indirectAcquisition;if(r&&Array.isArray(r))return r.map(t=>CA.deserialize(t)).filter(t=>t!==void 0)},J.prototype.getHolds=function(){return ie.deserialize(this.otherProperties.holds)},J.prototype.getCopies=function(){return Ae.deserialize(this.otherProperties.copies)},J.prototype.getAvailability=function(){return ne.deserialize(this.otherProperties.availability)},J.prototype.getAuthenticate=function(){return _.deserialize(this.otherProperties.authenticate)};const SA="CssSelectorGenerator";function Le(r="unknown problem",...t){console.warn(`${SA}: ${r}`,...t)}function QA(r){return r instanceof RegExp}function zA(r){return r.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function YA(r){const t=r.map(e=>{if(QA(e))return i=>e.test(i);if(typeof e=="function")return i=>{const A=e(i);return typeof A!="boolean"?(Le("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",e),!1):A};if(typeof e=="string"){const i=new RegExp("^"+zA(e)+"$");return A=>i.test(A)}return Le("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",e),()=>!1});return e=>t.some(i=>i(e))}YA(["class","id","ng-*"]);class Oe{}class re extends Oe{goLeft(t=!1,e){this.readingProgression===Y.ltr?this.goBackward(t,e):this.readingProgression===Y.rtl&&this.goForward(t,e)}goRight(t=!1,e){this.readingProgression===Y.ltr?this.goForward(t,e):this.readingProgression===Y.rtl&&this.goBackward(t,e)}}const Xe=`
|
|
1
|
+
(function(B,j){typeof exports=="object"&&typeof module<"u"?j(exports):typeof define=="function"&&define.amd?define(["exports"],j):(B=typeof globalThis<"u"?globalThis:B||self,j(B.navigator={}))})(this,(function(B){"use strict";const j=class Bt{constructor(t){if(typeof t=="string"){if(!Bt.VALID_MODES.has(t.toLowerCase()))return;this.value=t.toLowerCase()}else{const e=t.filter(i=>Bt.VALID_MODES.has(i.toLowerCase()));if(e.length===0)return;this.value=Array.from(new Set(e))}}static deserialize(t){if(!t)return;if(typeof t=="string")return new Bt(t);if(!Array.isArray(t))return;const e=t.filter(i=>i?Bt.VALID_MODES.has(i.toLowerCase()):!1);if(e.length!==0)return new Bt(e)}serialize(){return this.value}};j.VALID_MODES=new Set(["auditory","tactile","textual","visual"]),j.AUDITORY=new j("auditory"),j.TACTILE=new j("tactile"),j.TEXTUAL=new j("textual"),j.VISUAL=new j("visual");const p=class BA{constructor(t){this.value=t}static deserialize(t){if(!(!t||typeof t!="string"))return new BA(t)}serialize(){return this.value}};p.NONE=new p("none"),p.ANNOTATIONS=new p("annotations"),p.ARIA=new p("ARIA"),p.INDEX=new p("index"),p.PAGE_BREAK_MARKERS=new p("pageBreakMarkers"),p.PAGE_NAVIGATION=new p("pageNavigation"),p.PRINT_PAGE_NUMBERS=new p("printPageNumbers"),p.READING_ORDER=new p("readingOrder"),p.STRUCTURAL_NAVIGATION=new p("structuralNavigation"),p.TABLE_OF_CONTENTS=new p("tableOfContents"),p.TAGGED_PDF=new p("taggedPDF"),p.ALTERNATIVE_TEXT=new p("alternativeText"),p.AUDIO_DESCRIPTION=new p("audioDescription"),p.CAPTIONS=new p("captions"),p.CLOSED_CAPTIONS=new p("closedCaptions"),p.DESCRIBED_MATH=new p("describedMath"),p.LONG_DESCRIPTION=new p("longDescription"),p.OPEN_CAPTIONS=new p("openCaptions"),p.SIGN_LANGUAGE=new p("signLanguage"),p.TRANSCRIPT=new p("transcript"),p.DISPLAY_TRANSFORMABILITY=new p("displayTransformability"),p.SYNCHRONIZED_AUDIO_TEXT=new p("synchronizedAudioText"),p.TIMING_CONTROL=new p("timingControl"),p.UNLOCKED=new p("unlocked"),p.CHEM_ML=new p("ChemML"),p.LATEX=new p("latex"),p.LATEX_CHEMISTRY=new p("latex-chemistry"),p.MATH_ML=new p("MathML"),p.MATH_ML_CHEMISTRY=new p("MathML-chemistry"),p.TTS_MARKUP=new p("ttsMarkup"),p.HIGH_CONTRAST_AUDIO=new p("highContrastAudio"),p.HIGH_CONTRAST_DISPLAY=new p("highContrastDisplay"),p.LARGE_PRINT=new p("largePrint"),p.BRAILLE=new p("braille"),p.TACTILE_GRAPHIC=new p("tactileGraphic"),p.TACTILE_OBJECT=new p("tactileObject"),p.FULL_RUBY_ANNOTATIONS=new p("fullRubyAnnotations"),p.HORIZONTAL_WRITING=new p("horizontalWriting"),p.RUBY_ANNOTATIONS=new p("rubyAnnotations"),p.VERTICAL_WRITING=new p("verticalWriting"),p.WITH_ADDITIONAL_WORD_SEGMENTATION=new p("withAdditionalWordSegmentation"),p.WITHOUT_ADDITIONAL_WORD_SEGMENTATION=new p("withoutAdditionalWordSegmentation");let ve=p;var w=(r=>(r.reflowable="reflowable",r.fixed="fixed",r.scrolled="scrolled",r))(w||{});class _t{constructor(t){this.algorithm=t.algorithm,this.compression=t.compression,this.originalLength=t.originalLength,this.profile=t.profile,this.scheme=t.scheme}static deserialize(t){if(t&&t.algorithm)return new _t({algorithm:t.algorithm,compression:t.compression,originalLength:t.originalLength,profile:t.profile,scheme:t.scheme})}serialize(){const t={algorithm:this.algorithm};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}}var G=(r=>(r.left="left",r.right="right",r.center="center",r))(G||{});let k=class Te{constructor(t){this.otherProperties=t}get page(){return this.otherProperties.page}static deserialize(t){if(t)return new Te(t)}serialize(){return this.otherProperties}add(t){const e=Object.assign({},this.otherProperties);for(const i in t)e[i]=t[i];return new Te(e)}};Object.defineProperty(k.prototype,"encryption",{get:function(){return _t.deserialize(this.otherProperties.encrypted)}});function yA(r){return r&&Array.isArray(r)?r:void 0}function De(r){return r&&typeof r=="string"?[r]:yA(r)}function He(r){return typeof r=="string"?new Date(r):void 0}function xt(r){return isNaN(r)?void 0:r}function x(r){return xt(r)!==void 0&&Math.sign(r)>=0?r:void 0}function UA(r){const t=new Array;return r.forEach(e=>t.push(e)),t}class d{constructor(t){let e,i,A=t.mediaType.replace(/\s/g,"").split(";");const n=A[0].split("/");if(n.length===2){if(e=n[0].toLowerCase().trim(),i=n[1].toLowerCase().trim(),e.length===0||i.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const s={};for(let u=1;u<A.length;u++){const M=A[u].split("=");if(M.length===2){const l=M[0].toLocaleLowerCase(),f=l==="charset"?M[1].toUpperCase():M[1];s[l]=f}}const o={},a=Object.keys(s);a.sort((u,M)=>u.localeCompare(M)),a.forEach(u=>o[u]=s[u]);let h="";for(const u in o){const M=o[u];h+=`;${u}=${M}`}const c=`${e}/${i}${h}`,g=o.encoding;this.string=c,this.type=e,this.subtype=i,this.parameters=o,this.encoding=g,this.name=t.name,this.fileExtension=t.fileExtension}static parse(t){return new d(t)}get structuredSyntaxSuffix(){const t=this.subtype.split("+");return t.length>1?`+${t[t.length-1]}`:void 0}get charset(){return this.parameters.charset}contains(t){const e=typeof t=="string"?d.parse({mediaType:t}):t;if(!((this.type==="*"||this.type===e.type)&&(this.subtype==="*"||this.subtype===e.subtype)))return!1;const i=new Set(Object.entries(this.parameters).map(([n,s])=>`${n}=${s}`)),A=new Set(Object.entries(e.parameters).map(([n,s])=>`${n}=${s}`));for(const n of Array.from(i.values()))if(!A.has(n))return!1;return!0}matches(t){const e=typeof t=="string"?d.parse({mediaType:t}):t;return this.contains(e)||e.contains(this)}matchesAny(...t){for(const e of t)if(this.matches(e))return!0;return!1}equals(t){return this.string===t.string}get isZIP(){return this.matchesAny(d.ZIP,d.LCP_PROTECTED_AUDIOBOOK,d.LCP_PROTECTED_PDF)||this.structuredSyntaxSuffix==="+zip"}get isJSON(){return this.matchesAny(d.JSON)||this.structuredSyntaxSuffix==="+json"}get isOPDS(){return this.matchesAny(d.OPDS1,d.OPDS1_ENTRY,d.OPDS2,d.OPDS2_PUBLICATION,d.OPDS_AUTHENTICATION)||this.structuredSyntaxSuffix==="+json"}get isHTML(){return this.matchesAny(d.HTML,d.XHTML)}get isBitmap(){return this.matchesAny(d.BMP,d.GIF,d.JPEG,d.PNG,d.TIFF,d.WEBP)}get isAudio(){return this.type==="audio"}get isVideo(){return this.type==="video"}get isRWPM(){return this.matchesAny(d.READIUM_AUDIOBOOK_MANIFEST,d.DIVINA_MANIFEST,d.READIUM_WEBPUB_MANIFEST)}get isPublication(){return this.matchesAny(d.READIUM_AUDIOBOOK,d.READIUM_AUDIOBOOK_MANIFEST,d.CBZ,d.DIVINA,d.DIVINA_MANIFEST,d.EPUB,d.LCP_PROTECTED_AUDIOBOOK,d.LCP_PROTECTED_PDF,d.LPF,d.PDF,d.W3C_WPUB_MANIFEST,d.READIUM_WEBPUB,d.READIUM_WEBPUB_MANIFEST,d.ZAB)}static get AAC(){return d.parse({mediaType:"audio/aac",fileExtension:"aac"})}static get ACSM(){return d.parse({mediaType:"application/vnd.adobe.adept+xml",name:"Adobe Content Server Message",fileExtension:"acsm"})}static get AIFF(){return d.parse({mediaType:"audio/aiff",fileExtension:"aiff"})}static get AVI(){return d.parse({mediaType:"video/x-msvideo",fileExtension:"avi"})}static get BINARY(){return d.parse({mediaType:"application/octet-stream"})}static get BMP(){return d.parse({mediaType:"image/bmp",fileExtension:"bmp"})}static get CBZ(){return d.parse({mediaType:"application/vnd.comicbook+zip",name:"Comic Book Archive",fileExtension:"cbz"})}static get CSS(){return d.parse({mediaType:"text/css",fileExtension:"css"})}static get DIVINA(){return d.parse({mediaType:"application/divina+zip",name:"Digital Visual Narratives",fileExtension:"divina"})}static get DIVINA_MANIFEST(){return d.parse({mediaType:"application/divina+json",name:"Digital Visual Narratives",fileExtension:"json"})}static get EPUB(){return d.parse({mediaType:"application/epub+zip",name:"EPUB",fileExtension:"epub"})}static get GIF(){return d.parse({mediaType:"image/gif",fileExtension:"gif"})}static get GZ(){return d.parse({mediaType:"application/gzip",fileExtension:"gz"})}static get HTML(){return d.parse({mediaType:"text/html",fileExtension:"html"})}static get JAVASCRIPT(){return d.parse({mediaType:"text/javascript",fileExtension:"js"})}static get JPEG(){return d.parse({mediaType:"image/jpeg",fileExtension:"jpeg"})}static get JSON(){return d.parse({mediaType:"application/json"})}static get LCP_LICENSE_DOCUMENT(){return d.parse({mediaType:"application/vnd.readium.lcp.license.v1.0+json",name:"LCP License",fileExtension:"lcpl"})}static get LCP_PROTECTED_AUDIOBOOK(){return d.parse({mediaType:"application/audiobook+lcp",name:"LCP Protected Audiobook",fileExtension:"lcpa"})}static get LCP_PROTECTED_PDF(){return d.parse({mediaType:"application/pdf+lcp",name:"LCP Protected PDF",fileExtension:"lcpdf"})}static get LCP_STATUS_DOCUMENT(){return d.parse({mediaType:"application/vnd.readium.license.status.v1.0+json"})}static get LPF(){return d.parse({mediaType:"application/lpf+zip",fileExtension:"lpf"})}static get MP3(){return d.parse({mediaType:"audio/mpeg",fileExtension:"mp3"})}static get MPEG(){return d.parse({mediaType:"video/mpeg",fileExtension:"mpeg"})}static get NCX(){return d.parse({mediaType:"application/x-dtbncx+xml",fileExtension:"ncx"})}static get OGG(){return d.parse({mediaType:"audio/ogg",fileExtension:"oga"})}static get OGV(){return d.parse({mediaType:"video/ogg",fileExtension:"ogv"})}static get OPDS1(){return d.parse({mediaType:"application/atom+xml;profile=opds-catalog"})}static get OPDS1_ENTRY(){return d.parse({mediaType:"application/atom+xml;type=entry;profile=opds-catalog"})}static get OPDS2(){return d.parse({mediaType:"application/opds+json"})}static get OPDS2_PUBLICATION(){return d.parse({mediaType:"application/opds-publication+json"})}static get OPDS_AUTHENTICATION(){return d.parse({mediaType:"application/opds-authentication+json"})}static get OPUS(){return d.parse({mediaType:"audio/opus",fileExtension:"opus"})}static get OTF(){return d.parse({mediaType:"font/otf",fileExtension:"otf"})}static get PDF(){return d.parse({mediaType:"application/pdf",name:"PDF",fileExtension:"pdf"})}static get PNG(){return d.parse({mediaType:"image/png",fileExtension:"png"})}static get READIUM_AUDIOBOOK(){return d.parse({mediaType:"application/audiobook+zip",name:"Readium Audiobook",fileExtension:"audiobook"})}static get READIUM_AUDIOBOOK_MANIFEST(){return d.parse({mediaType:"application/audiobook+json",name:"Readium Audiobook",fileExtension:"json"})}static get READIUM_CONTENT_DOCUMENT(){return d.parse({mediaType:"application/vnd.readium.content+json",name:"Readium Content Document",fileExtension:"json"})}static get READIUM_GUIDED_NAVIGATION_DOCUMENT(){return d.parse({mediaType:"application/guided-navigation+json",name:"Readium Guided Navigation Document",fileExtension:"json"})}static get READIUM_POSITION_LIST(){return d.parse({mediaType:"application/vnd.readium.position-list+json",name:"Readium Position List",fileExtension:"json"})}static get READIUM_WEBPUB(){return d.parse({mediaType:"application/webpub+zip",name:"Readium Web Publication",fileExtension:"webpub"})}static get READIUM_WEBPUB_MANIFEST(){return d.parse({mediaType:"application/webpub+json",name:"Readium Web Publication",fileExtension:"json"})}static get SMIL(){return d.parse({mediaType:"application/smil+xml",fileExtension:"smil"})}static get SVG(){return d.parse({mediaType:"image/svg+xml",fileExtension:"svg"})}static get TEXT(){return d.parse({mediaType:"text/plain",fileExtension:"txt"})}static get TIFF(){return d.parse({mediaType:"image/tiff",fileExtension:"tiff"})}static get TTF(){return d.parse({mediaType:"font/ttf",fileExtension:"ttf"})}static get W3C_WPUB_MANIFEST(){return d.parse({mediaType:"application/x.readium.w3c.wpub+json",name:"Web Publication",fileExtension:"json"})}static get WAV(){return d.parse({mediaType:"audio/wav",fileExtension:"wav"})}static get WEBM_AUDIO(){return d.parse({mediaType:"audio/webm",fileExtension:"webm"})}static get WEBM_VIDEO(){return d.parse({mediaType:"video/webm",fileExtension:"webm"})}static get WEBP(){return d.parse({mediaType:"image/webp",fileExtension:"webp"})}static get WOFF(){return d.parse({mediaType:"font/woff",fileExtension:"woff"})}static get WOFF2(){return d.parse({mediaType:"font/woff2",fileExtension:"woff2"})}static get XHTML(){return d.parse({mediaType:"application/xhtml+xml",fileExtension:"xhtml"})}static get XML(){return d.parse({mediaType:"application/xml",fileExtension:"xml"})}static get ZAB(){return d.parse({mediaType:"application/x.readium.zab+zip",name:"Zipped Audio Book",fileExtension:"zab"})}static get ZIP(){return d.parse({mediaType:"application/zip",fileExtension:"zip"})}}let Ge=class{constructor(t){this.uri=t,this.parameters=this.getParameters(t)}getParameters(t){const e=/\{\??([^}]+)\}/g,i=t.match(e);return i?new Set(i.join(",").replace(e,"$1").split(",").map(A=>A.trim())):new Set}expand(t){const e=A=>A.split(",").map(n=>{const s=t[n];return s?encodeURIComponent(s):""}).join(","),i=A=>"?"+A.split(",").map(n=>{const s=n.split("=")[0],o=t[s];return o?`${s}=${encodeURIComponent(o)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...A)=>A[1]?i(A[2]):e(A[2]))}},V=class wA{constructor(t){this.fragments=t.fragments?t.fragments:new Array,this.progression=t.progression,this.totalProgression=t.totalProgression,this.position=t.position,this.otherLocations=t.otherLocations}static deserialize(t){if(!t)return;const e=xt(t.progression),i=xt(t.totalProgression),A=xt(t.position),n=new Map,s=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(t).forEach(([o,a])=>{s.has(o)||n.set(o,a)}),new wA({fragments:De(t.fragments||t.fragment),progression:e!==void 0&&e>=0&&e<=1?e:void 0,totalProgression:i!==void 0&&i>=0&&i<=1?i:void 0,position:A!==void 0&&A>0?A:void 0,otherLocations:n.size===0?void 0:n})}serialize(){const t={};return this.fragments&&(t.fragments=this.fragments),this.progression!==void 0&&(t.progression=this.progression),this.totalProgression!==void 0&&(t.totalProgression=this.totalProgression),this.position!==void 0&&(t.position=this.position),this.otherLocations&&this.otherLocations.forEach((e,i)=>t[i]=e),t}},RA=class EA{constructor(t){this.after=t.after,this.before=t.before,this.highlight=t.highlight}static deserialize(t){if(t)return new EA({after:t.after,before:t.before,highlight:t.highlight})}serialize(){const t={};return this.after!==void 0&&(t.after=this.after),this.before!==void 0&&(t.before=this.before),this.highlight!==void 0&&(t.highlight=this.highlight),t}},at=class be{constructor(t){this.href=t.href,this.type=t.type,this.title=t.title,this.locations=t.locations?t.locations:new V({}),this.text=t.text}static deserialize(t){if(t&&t.href&&t.type)return new be({href:t.href,type:t.type,title:t.title,locations:V.deserialize(t.locations),text:RA.deserialize(t.text)})}serialize(){const t={href:this.href,type:this.type};return this.title!==void 0&&(t.title=this.title),this.locations&&(t.locations=this.locations.serialize()),this.text&&(t.text=this.text.serialize()),t}copyWithLocations(t){return new be({href:this.href,type:this.type,title:this.title,text:this.text,locations:new V({...this.locations,...t})})}},q=class Kt{constructor(t){this.href=t.href,this.templated=t.templated,this.type=t.type,this.title=t.title,this.rels=t.rels,this.properties=t.properties,this.height=t.height,this.width=t.width,this.size=t.size,this.duration=t.duration,this.bitrate=t.bitrate,this.languages=t.languages,this.alternates=t.alternates,this.children=t.children}static deserialize(t){if(!(!t||typeof t.href!="string"))return new Kt({href:t.href,templated:t.templated,type:t.type,title:t.title,rels:t.rel?Array.isArray(t.rel)?new Set(t.rel):new Set([t.rel]):void 0,properties:k.deserialize(t.properties),height:x(t.height),width:x(t.width),size:x(t.size),duration:x(t.duration),bitrate:x(t.bitrate),languages:De(t.language),alternates:ke.deserialize(t.alternate),children:ke.deserialize(t.children)})}serialize(){const t={href:this.href};return this.templated!==void 0&&(t.templated=this.templated),this.type!==void 0&&(t.type=this.type),this.title!==void 0&&(t.title=this.title),this.rels&&(t.rel=UA(this.rels)),this.properties&&(t.properties=this.properties.serialize()),this.height!==void 0&&(t.height=this.height),this.width!==void 0&&(t.width=this.width),this.size!==void 0&&(t.size=this.size),this.duration!==void 0&&(t.duration=this.duration),this.bitrate!==void 0&&(t.bitrate=this.bitrate),this.languages&&(t.language=this.languages),this.alternates&&(t.alternate=this.alternates.serialize()),this.children&&(t.children=this.children.serialize()),t}get mediaType(){return this.type!==void 0?d.parse({mediaType:this.type}):d.BINARY}toURL(t){const e=this.href.replace(/^(\/)/,"");if(e.length===0)return;let i=t||"/";return i.startsWith("/")&&(i="file://"+i),new URL(e,i).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new Ge(this.href).parameters:new Set}expandTemplate(t){return new Kt({href:new Ge(this.href).expand(t),templated:!1})}addProperties(t){const e=Kt.deserialize(this.serialize());return e.properties=e.properties?e.properties?.add(t):new k(t),e}get locator(){let t=this.href.split("#");return new at({href:t.length>0&&t[0]!==void 0?t[0]:this.href,type:this.type??"",title:this.title,locations:new V({fragments:t.length>1&&t[1]!==void 0?[t[1]]:[]})})}},ke=class IA{constructor(t){this.items=t}static deserialize(t){if(t&&Array.isArray(t))return new IA(t.map(e=>q.deserialize(e)).filter(e=>e!==void 0))}serialize(){return this.items.map(t=>t.serialize())}findWithRel(t){const e=i=>i.rels&&i.rels.has(t);return this.items.find(e)}filterByRel(t){const e=i=>i.rels&&i.rels.has(t);return this.items.filter(e)}findWithHref(t){const e=i=>i.href===t;return this.items.find(e)}findIndexWithHref(t){const e=i=>i.href===t;return this.items.findIndex(e)}findWithMediaType(t){const e=i=>i.mediaType.matches(t);return this.items.find(e)}filterByMediaType(t){const e=i=>i.mediaType.matches(t);return this.items.filter(e)}filterByMediaTypes(t){const e=i=>{for(const A of t)if(i.mediaType.matches(A))return!0;return!1};return this.items.filter(e)}everyIsAudio(){const t=e=>e.mediaType.isAudio;return this.items.length>0&&this.items.every(t)}everyIsBitmap(){const t=e=>e.mediaType.isBitmap;return this.items.length>0&&this.items.every(t)}everyIsHTML(){const t=e=>e.mediaType.isHTML;return this.items.length>0&&this.items.every(t)}everyIsVideo(){const t=e=>e.mediaType.isVideo;return this.items.length>0&&this.items.every(t)}everyMatchesMediaType(t){return Array.isArray(t)?this.items.length>0&&this.items.every(e=>{for(const i of t)return e.mediaType.matches(i);return!1}):this.items.length>0&&this.items.every(e=>e.mediaType.matches(t))}filterLinksHasType(){return this.items.filter(t=>t.type)}};var Je=(r=>(r.EPUB="https://readium.org/webpub-manifest/profiles/epub",r.AUDIOBOOK="https://readium.org/webpub-manifest/profiles/audiobook",r.DIVINA="https://readium.org/webpub-manifest/profiles/divina",r.PDF="https://readium.org/webpub-manifest/profiles/pdf",r))(Je||{}),Y=(r=>(r.ltr="ltr",r.rtl="rtl",r))(Y||{});k.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])};let We=class FA{constructor(t){this.cssSelector=t.cssSelector,this.textNodeIndex=t.textNodeIndex,this.charOffset=t.charOffset}static deserialize(t){if(!(t&&t.cssSelector))return;let e=x(t.textNodeIndex);if(e===void 0)return;let i=x(t.charOffset);return i===void 0&&(i=x(t.offset)),new FA({cssSelector:t.cssSelector,textNodeIndex:e,charOffset:i})}serialize(){const t={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(t.charOffset=this.charOffset),t}};class $t{constructor(t){this.start=t.start,this.end=t.end}static deserialize(t){if(!t)return;let e=We.deserialize(t.start);if(e)return new $t({start:e,end:We.deserialize(t.end)})}serialize(){const t={start:this.start.serialize()};return this.end&&(t.end=this.end.serialize()),t}}V.prototype.getCssSelector=function(){return this.otherLocations?.get("cssSelector")},V.prototype.getPartialCfi=function(){return this.otherLocations?.get("partialCfi")},V.prototype.getDomRange=function(){return $t.deserialize(this.otherLocations?.get("domRange"))},V.prototype.fragmentParameters=function(){return new Map(this.fragments.map(r=>r.startsWith("#")?r.slice(1):r).join("&").split("&").filter(r=>!r.startsWith("#")).map(r=>r.split("=")).filter(r=>r.length===2).map(r=>[r[0].trim().toLowerCase(),r[1].trim()]))},V.prototype.htmlId=function(){if(!this.fragments.length)return;let r=this.fragments.find(t=>t.length&&!t.includes("="));if(!r){const t=this.fragmentParameters();t.has("id")?r=t.get("id"):t.has("name")&&(r=t.get("name"))}return r?.startsWith("#")?r.slice(1):r},V.prototype.page=function(){const r=parseInt(this.fragmentParameters().get("page"));if(!isNaN(r)&&r>=0)return r},V.prototype.time=function(){const r=parseInt(this.fragmentParameters().get("t"));if(!isNaN(r))return r},V.prototype.space=function(){const r=this.fragmentParameters();if(!r.has("xywh"))return;const t=r.get("xywh").split(",").map(e=>parseInt(e));if(t.length===4&&!t.some(isNaN))return t};class te{constructor(t){this.currency=t.currency,this.value=t.value}static deserialize(t){if(!t)return;let e=t.currency;if(!(e&&typeof e=="string"&&e.length>0))return;let i=x(t.value);if(i!==void 0)return new te({currency:e,value:i})}serialize(){return{currency:this.currency,value:this.value}}}let CA=class qt{constructor(t){this.type=t.type,this.children=t.children}static deserialize(t){if(t&&t.type)return new qt({type:t.type,children:qt.deserializeArray(t.children)})}static deserializeArray(t){if(Array.isArray(t))return t.map(e=>qt.deserialize(e)).filter(e=>e!==void 0)}serialize(){const t={type:this.type};return this.children&&(t.children=this.children.map(e=>e.serialize())),t}};class ee{constructor(t){this.total=t.total,this.position=t.position}static deserialize(t){if(t)return new ee({total:x(t.total),position:x(t.position)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.position!==void 0&&(t.position=this.position),t}}class ie{constructor(t){this.total=t.total,this.available=t.available}static deserialize(t){if(t)return new ie({total:x(t.total),available:x(t.available)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.available!==void 0&&(t.available=this.available),t}}class Ae{constructor(t){this.state=t.state,this.since=t.since,this.until=t.until}static deserialize(t){if(t&&t.state)return new Ae({state:t.state,since:He(t.since),until:He(t.until)})}serialize(){const t={state:this.state};return this.since!==void 0&&(t.since=this.since.toISOString()),this.until!==void 0&&(t.until=this.until.toISOString()),t}}k.prototype.getNumberOfItems=function(){return x(this.otherProperties.numberOfItems)},k.prototype.getPrice=function(){return te.deserialize(this.otherProperties.price)},k.prototype.getIndirectAcquisitions=function(){const r=this.otherProperties.indirectAcquisition;if(r&&Array.isArray(r))return r.map(t=>CA.deserialize(t)).filter(t=>t!==void 0)},k.prototype.getHolds=function(){return ee.deserialize(this.otherProperties.holds)},k.prototype.getCopies=function(){return ie.deserialize(this.otherProperties.copies)},k.prototype.getAvailability=function(){return Ae.deserialize(this.otherProperties.availability)},k.prototype.getAuthenticate=function(){return q.deserialize(this.otherProperties.authenticate)};const SA="CssSelectorGenerator";function Le(r="unknown problem",...t){console.warn(`${SA}: ${r}`,...t)}function QA(r){return r instanceof RegExp}function zA(r){return r.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function YA(r){const t=r.map(e=>{if(QA(e))return i=>e.test(i);if(typeof e=="function")return i=>{const A=e(i);return typeof A!="boolean"?(Le("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",e),!1):A};if(typeof e=="string"){const i=new RegExp("^"+zA(e)+"$");return A=>i.test(A)}return Le("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",e),()=>!1});return e=>t.some(i=>i(e))}YA(["class","id","ng-*"]);class Oe{}class ne extends Oe{goLeft(t=!1,e){this.readingProgression===Y.ltr?this.goBackward(t,e):this.readingProgression===Y.rtl&&this.goForward(t,e)}goRight(t=!1,e){this.readingProgression===Y.ltr?this.goForward(t,e):this.readingProgression===Y.rtl&&this.goBackward(t,e)}}const Xe=`
|
|
2
2
|
/* FontFamily */
|
|
3
3
|
|
|
4
4
|
:root[style*="--USER__fontFamily"] {
|
|
@@ -199,11 +199,11 @@
|
|
|
199
199
|
zoom: var(--USER__zoom) !important;
|
|
200
200
|
}
|
|
201
201
|
}
|
|
202
|
-
`,
|
|
202
|
+
`,Tt=(r,t)=>URL.createObjectURL(new Blob([r],{type:t})),Ze=r=>r.replace(/\/\/.*/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\n/g,"").replace(/\s+/g," "),re=(r,t)=>{const e=r.createElement("script");return e.dataset.readium="true",e.src=t.startsWith("blob:")?t:Tt(t,"text/javascript"),e},NA=(r,t)=>{const e=r.createElement("style");return e.dataset.readium="true",e.textContent=t,e},se=new Map,oe=(r,t)=>{if(se.has(r))return se.get(r);const e=t();return se.set(r,e),e},xA=r=>re(r,oe("css-selector-generator",()=>Tt('!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports._readium_cssSelectorGenerator=e():t._readium_cssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t,e,n={d:(t,e)=>{for(var o in e)n.o(e,o)&&!n.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:e[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},o={};function r(t){return t&&t instanceof Element}function i(t="unknown problem",...e){console.warn(`CssSelectorGenerator: ${t}`,...e)}n.r(o),n.d(o,{default:()=>z,getCssSelector:()=>U}),function(t){t.NONE="none",t.DESCENDANT="descendant",t.CHILD="child"}(t||(t={})),function(t){t.id="id",t.class="class",t.tag="tag",t.attribute="attribute",t.nthchild="nthchild",t.nthoftype="nthoftype"}(e||(e={}));const c={selectors:[e.id,e.class,e.tag,e.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY};function u(t){return t instanceof RegExp}function s(t){return["string","function"].includes(typeof t)||u(t)}function l(t){return Array.isArray(t)?t.filter(s):[]}function a(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function f(t,e){if(a(t))return t.contains(e)||i("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element\'s real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will nto work as intended."),t;const n=e.getRootNode({composed:!1});return a(n)?(n!==document&&i("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):e.ownerDocument.querySelector(":root")}function d(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function m(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function p(t){return[].concat(...t)}function h(t){const e=t.map((t=>{if(u(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(i("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return i("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1}));return t=>e.some((e=>e(t)))}function g(t,e,n){const o=Array.from(f(n,t[0]).querySelectorAll(e));return o.length===t.length&&t.every((t=>o.includes(t)))}function y(t,e){e=null!=e?e:function(t){return t.ownerDocument.querySelector(":root")}(t);const n=[];let o=t;for(;r(o)&&o!==e;)n.push(o),o=o.parentElement;return n}function b(t,e){return m(t.map((t=>y(t,e))))}const N={[t.NONE]:{type:t.NONE,value:""},[t.DESCENDANT]:{type:t.DESCENDANT,value:" > "},[t.CHILD]:{type:t.CHILD,value:" "}},S=new RegExp(["^$","\\\\s"].join("|")),E=new RegExp(["^$"].join("|")),w=[e.nthoftype,e.tag,e.id,e.class,e.attribute,e.nthchild],v=h(["class","id","ng-*"]);function C({nodeName:t}){return`[${t}]`}function O({nodeName:t,nodeValue:e}){return`[${t}=\'${L(e)}\']`}function T(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t},e){const n=e.tagName.toLowerCase();return!(["input","option"].includes(n)&&"value"===t||v(t))}(e,t)));return[...e.map(C),...e.map(O)]}function I(t){return(t.getAttribute("class")||"").trim().split(/\\s+/).filter((t=>!E.test(t))).map((t=>`.${L(t)}`))}function x(t){const e=t.getAttribute("id")||"",n=`#${L(e)}`,o=t.getRootNode({composed:!1});return!S.test(e)&&g([t],n,o)?[n]:[]}function j(t){const e=t.parentNode;if(e){const n=Array.from(e.childNodes).filter(r).indexOf(t);if(n>-1)return[`:nth-child(${n+1})`]}return[]}function A(t){return[L(t.tagName.toLowerCase())]}function D(t){const e=[...new Set(p(t.map(A)))];return 0===e.length||e.length>1?[]:[e[0]]}function $(t){const e=D([t])[0],n=t.parentElement;if(n){const o=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),r=o.indexOf(t);if(r>-1)return[`${e}:nth-of-type(${r+1})`]}return[]}function R(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){const n=[];let o=0,r=k(1);for(;r.length<=t.length&&o<e;)o+=1,n.push(r.map((e=>t[e]))),r=P(r,t.length-1);return n}function P(t=[],e=0){const n=t.length;if(0===n)return[];const o=[...t];o[n-1]+=1;for(let t=n-1;t>=0;t--)if(o[t]>e){if(0===t)return k(n+1);o[t-1]++,o[t]=o[t-1]+1}return o[n-1]>e?k(n+1):o}function k(t=1){return Array.from(Array(t).keys())}const _=":".charCodeAt(0).toString(16).toUpperCase(),M=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function L(t=""){var e,n;return null!==(n=null===(e=null===CSS||void 0===CSS?void 0:CSS.escape)||void 0===e?void 0:e.call(CSS,t))&&void 0!==n?n:function(t=""){return t.split("").map((t=>":"===t?`\\\\${_} `:M.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const q={tag:D,id:function(t){return 0===t.length||t.length>1?[]:x(t[0])},class:function(t){return m(t.map(I))},attribute:function(t){return m(t.map(T))},nthchild:function(t){return m(t.map(j))},nthoftype:function(t){return m(t.map($))}},F={tag:A,id:x,class:I,attribute:T,nthchild:j,nthoftype:$};function V(t){return t.includes(e.tag)||t.includes(e.nthoftype)?[...t]:[...t,e.tag]}function Y(t={}){const n=[...w];return t[e.tag]&&t[e.nthoftype]&&n.splice(n.indexOf(e.tag),1),n.map((e=>{return(o=t)[n=e]?o[n].join(""):"";var n,o})).join("")}function B(t,e,n="",o){const r=function(t,e){return""===e?t:function(t,e){return[...t.map((t=>e+" "+t)),...t.map((t=>e+" > "+t))]}(t,e)}(function(t,e,n){const o=function(t,e){const{blacklist:n,whitelist:o,combineWithinSelector:r,maxCombinations:i}=e,c=h(n),u=h(o);return function(t){const{selectors:e,includeTag:n}=t,o=[].concat(e);return n&&!o.includes("tag")&&o.push("tag"),o}(e).reduce(((e,n)=>{const o=function(t,e){var n;return(null!==(n=q[e])&&void 0!==n?n:()=>[])(t)}(t,n),s=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(o,c,u),l=function(t=[],e){return t.sort(((t,n)=>{const o=e(t),r=e(n);return o&&!r?-1:!o&&r?1:0}))}(s,u);return e[n]=r?R(l,{maxResults:i}):l.map((t=>[t])),e}),{})}(t,n),r=function(t,e){return function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:o,maxCandidates:r}=t,i=n?R(e,{maxResults:r}):e.map((t=>[t]));return o?i.map(V):i}(e).map((e=>function(t,e){const n={};return t.forEach((t=>{const o=e[t];o.length>0&&(n[t]=o)})),function(t={}){let e=[];return Object.entries(t).forEach((([t,n])=>{e=n.flatMap((n=>0===e.length?[{[t]:n}]:e.map((e=>Object.assign(Object.assign({},e),{[t]:n})))))})),e}(n).map(Y)}(e,t))).filter((t=>t.length>0))}(o,n),i=p(r);return[...new Set(i)]}(t,o.root,o),n);for(const e of r)if(g(t,e,o.root))return e;return null}function G(t){return{value:t,include:!1}}function W({selectors:t,operator:n}){let o=[...w];t[e.tag]&&t[e.nthoftype]&&(o=o.filter((t=>t!==e.tag)));let r="";return o.forEach((e=>{(t[e]||[]).forEach((({value:t,include:e})=>{e&&(r+=t)}))})),n.value+r}function H(n){return[":root",...y(n).reverse().map((n=>{const o=function(e,n,o=t.NONE){const r={};return n.forEach((t=>{Reflect.set(r,t,function(t,e){return F[e](t)}(e,t).map(G))})),{element:e,operator:N[o],selectors:r}}(n,[e.nthchild],t.DESCENDANT);return o.selectors.nthchild.forEach((t=>{t.include=!0})),o})).map(W)].join("")}function U(t,n={}){const o=function(t){const e=(Array.isArray(t)?t:[t]).filter(r);return[...new Set(e)]}(t),i=function(t,n={}){const o=Object.assign(Object.assign({},c),n);return{selectors:(r=o.selectors,Array.isArray(r)?r.filter((t=>{return n=e,o=t,Object.values(n).includes(o);var n,o})):[]),whitelist:l(o.whitelist),blacklist:l(o.blacklist),root:f(o.root,t),combineWithinSelector:!!o.combineWithinSelector,combineBetweenSelectors:!!o.combineBetweenSelectors,includeTag:!!o.includeTag,maxCombinations:d(o.maxCombinations),maxCandidates:d(o.maxCandidates)};var r}(o[0],n);let u="",s=i.root;function a(){return function(t,e,n="",o){if(0===t.length)return null;const r=[t.length>1?t:[],...b(t,e).map((t=>[t]))];for(const t of r){const e=B(t,0,n,o);if(e)return{foundElements:t,selector:e}}return null}(o,s,u,i)}let m=a();for(;m;){const{foundElements:t,selector:e}=m;if(g(o,e,i.root))return e;s=t[0],u=e,m=a()}return o.length>1?o.map((t=>U(t,i))).join(", "):function(t){return t.map(H).join(", ")}(o)}const z=U;return o})()));',"text/javascript"))),TA=`
|
|
203
203
|
window._readium_blockedEvents = [];
|
|
204
204
|
window._readium_blockEvents = false; // WebPub doesn't need event blocking
|
|
205
205
|
window._readium_eventBlocker = null;
|
|
206
|
-
`,bA=r=>
|
|
206
|
+
`,bA=r=>re(r,oe("webpub-js-before",()=>Tt(Ze(TA),"text/javascript"))),jA=r=>re(r,oe("webpub-js-after",()=>Tt(Ze(`
|
|
207
207
|
if(window.onload) window.onload = new Proxy(window.onload, {
|
|
208
208
|
apply: function(target, receiver, args) {
|
|
209
209
|
if(!window._readium_blockEvents) {
|
|
@@ -212,8 +212,8 @@ if(window.onload) window.onload = new Proxy(window.onload, {
|
|
|
212
212
|
}
|
|
213
213
|
_readium_blockedEvents.push([0, target, receiver, args]);
|
|
214
214
|
}
|
|
215
|
-
});`),"text/javascript")));class Ke{constructor(t,e,i,A){this.pub=t,this.item=i,this.burl=i.toURL(e)||"",this.cssProperties=A}async build(){if(!this.item.mediaType.isHTML)throw new Error(`Unsupported media type for WebPub: ${this.item.mediaType.string}`);return await this.buildHtmlFrame()}async buildHtmlFrame(){const t=await this.pub.get(this.item).readAsString();if(!t)throw new Error(`Failed reading item ${this.item.href}`);const e=new DOMParser().parseFromString(t,this.item.mediaType.string),i=e.querySelector("parsererror");if(i){const A=i.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${A?.textContent||i.textContent}`)}return this.finalizeDOM(e,this.burl,this.item.mediaType,t,this.cssProperties)}hasExecutable(t){return!!t.querySelector("script")||!!t.querySelector("body[onload]:not(body[onload=''])")}setProperties(t,e){for(const i in t){const A=t[i];A&&e.documentElement.style.setProperty(i,A)}}finalizeDOM(t,e,i,A,n){if(!t)return"";const s=NA(t,Xe);if(t.head.appendChild(s),n&&this.setProperties(n,t),t.body.querySelectorAll("img").forEach(h=>{h.setAttribute("fetchpriority","high")}),e!==void 0){const h=t.createElement("base");h.href=e,h.dataset.readium="true",t.head.firstChild.before(h)}const o=this.hasExecutable(t);o&&t.head.firstChild.before(bA(t)),t.head.firstChild.before(
|
|
216
|
-
`:"";let s=t.documentElement.outerHTML;return A+s}}const VA=Math.pow(2,32),qe=()=>Math.round(Math.random()*VA).toString(36),le=()=>`${Math.round(performance.now())}-${qe()}-${qe()}`,ht=1;class PA{constructor(t){this.destination=null,this.registrar=new Map,this.origin="",this.channelId="",this.receiver=this.receive.bind(this),this.preLog=[],this.wnd=t,t.addEventListener("message",this.receiver)}receive(t){if(t.source===null)throw Error("Event source is null");if(typeof t.data!="object")return;const e=t.data;if(!(!("_readium"in e)||!e._readium||e._readium<=0)){if(e.key==="_ping"){if(!this.destination){if(this.destination=t.source,this.origin=t.origin,this.channelId=e._channel,e._readium!==ht){e._readium>ht?this.send("error",`received comms version ${e._readium} higher than ${ht}`):this.send("error",`received comms version ${e._readium} lower than ${ht}`),this.destination=null,this.origin="",this.channelId="";return}this.send("_pong",void 0),this.preLog.forEach(i=>this.send("log",i)),this.preLog=[]}return}else if(this.channelId){if(e._channel!==this.channelId||t.origin!==this.origin)return}else return;this.handle(e)}}handle(t){const e=this.registrar.get(t.key);if(!e||e.length===0){t.strict&&this.send("_unhandled",t);return}e.forEach(i=>i.cb(t.data,A=>{this.send("_ack",A,t.id)}))}register(t,e,i){Array.isArray(t)||(t=[t]),t.forEach(A=>{const n=this.registrar.get(A);if(n&&n.length>=0){if(n.find(s=>s.module===e))throw new Error(`Trying to register another callback for combination of event ${A} and module ${e}`);n.push({cb:i,module:e}),this.registrar.set(A,n)}else this.registrar.set(A,[{cb:i,module:e}])})}unregister(t,e){Array.isArray(t)||(t=[t]),t.forEach(i=>{const A=this.registrar.get(i);!A||A.length===0||A.splice(A.findIndex(n=>n.module===e),1)})}unregisterAll(t){this.registrar.forEach((e,i)=>this.registrar.set(i,e.filter(A=>A.module!==t)))}log(...t){this.destination?this.send("log",t):this.preLog.push(t)}get ready(){return!!this.destination}destroy(){this.destination=null,this.channelId="",this.preLog=[],this.registrar.clear(),this.wnd.removeEventListener("message",this.receiver)}send(t,e,i=void 0,A=[]){if(!this.destination)throw Error("Attempted to send comms message before destination has been initialized");const n={_readium:ht,_channel:this.channelId,id:i??le(),key:t,data:e};try{this.destination.postMessage(n,{targetOrigin:this.origin,transfer:A})}catch(s){if(A.length>0)throw s;this.destination.postMessage(n,this.origin,A)}}}const Z=class Et{constructor(t){if(typeof t=="string"){if(!Et.VALID_MODES.has(t.toLowerCase()))return;this.value=t.toLowerCase()}else{const e=t.filter(i=>Et.VALID_MODES.has(i.toLowerCase()));if(e.length===0)return;this.value=Array.from(new Set(e))}}static deserialize(t){if(!t)return;if(typeof t=="string")return new Et(t);if(!Array.isArray(t))return;const e=t.filter(i=>i?Et.VALID_MODES.has(i.toLowerCase()):!1);if(e.length!==0)return new Et(e)}serialize(){return this.value}};Z.VALID_MODES=new Set(["auditory","tactile","textual","visual"]),Z.AUDITORY=new Z("auditory"),Z.TACTILE=new Z("tactile"),Z.TEXTUAL=new Z("textual"),Z.VISUAL=new Z("visual");class he{constructor(t){this.algorithm=t.algorithm,this.compression=t.compression,this.originalLength=t.originalLength,this.profile=t.profile,this.scheme=t.scheme}static deserialize(t){if(t&&t.algorithm)return new he({algorithm:t.algorithm,compression:t.compression,originalLength:t.originalLength,profile:t.profile,scheme:t.scheme})}serialize(){const t={algorithm:this.algorithm};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}}class x{constructor(t){this.otherProperties=t}get page(){return this.otherProperties.page}static deserialize(t){if(t)return new x(t)}serialize(){return this.otherProperties}add(t){const e=Object.assign({},this.otherProperties);for(const i in t)e[i]=t[i];return new x(e)}}Object.defineProperty(x.prototype,"encryption",{get:function(){return he.deserialize(this.otherProperties.encrypted)}});function vA(r){return r&&Array.isArray(r)?r:void 0}function _e(r){return r&&typeof r=="string"?[r]:vA(r)}function $e(r){return typeof r=="string"?new Date(r):void 0}function jt(r){return isNaN(r)?void 0:r}function b(r){return jt(r)!==void 0&&Math.sign(r)>=0?r:void 0}function DA(r){const t=new Array;return r.forEach(e=>t.push(e)),t}class m{constructor(t){let e,i,A=t.mediaType.replace(/\s/g,"").split(";");const n=A[0].split("/");if(n.length===2){if(e=n[0].toLowerCase().trim(),i=n[1].toLowerCase().trim(),e.length===0||i.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const s={};for(let u=1;u<A.length;u++){const M=A[u].split("=");if(M.length===2){const l=M[0].toLocaleLowerCase(),f=l==="charset"?M[1].toUpperCase():M[1];s[l]=f}}const o={},a=Object.keys(s);a.sort((u,M)=>u.localeCompare(M)),a.forEach(u=>o[u]=s[u]);let h="";for(const u in o){const M=o[u];h+=`;${u}=${M}`}const c=`${e}/${i}${h}`,g=o.encoding;this.string=c,this.type=e,this.subtype=i,this.parameters=o,this.encoding=g,this.name=t.name,this.fileExtension=t.fileExtension}static parse(t){return new m(t)}get structuredSyntaxSuffix(){const t=this.subtype.split("+");return t.length>1?`+${t[t.length-1]}`:void 0}get charset(){return this.parameters.charset}contains(t){const e=typeof t=="string"?m.parse({mediaType:t}):t;if(!((this.type==="*"||this.type===e.type)&&(this.subtype==="*"||this.subtype===e.subtype)))return!1;const i=new Set(Object.entries(this.parameters).map(([n,s])=>`${n}=${s}`)),A=new Set(Object.entries(e.parameters).map(([n,s])=>`${n}=${s}`));for(const n of Array.from(i.values()))if(!A.has(n))return!1;return!0}matches(t){const e=typeof t=="string"?m.parse({mediaType:t}):t;return this.contains(e)||e.contains(this)}matchesAny(...t){for(const e of t)if(this.matches(e))return!0;return!1}equals(t){return this.string===t.string}get isZIP(){return this.matchesAny(m.ZIP,m.LCP_PROTECTED_AUDIOBOOK,m.LCP_PROTECTED_PDF)||this.structuredSyntaxSuffix==="+zip"}get isJSON(){return this.matchesAny(m.JSON)||this.structuredSyntaxSuffix==="+json"}get isOPDS(){return this.matchesAny(m.OPDS1,m.OPDS1_ENTRY,m.OPDS2,m.OPDS2_PUBLICATION,m.OPDS_AUTHENTICATION)||this.structuredSyntaxSuffix==="+json"}get isHTML(){return this.matchesAny(m.HTML,m.XHTML)}get isBitmap(){return this.matchesAny(m.BMP,m.GIF,m.JPEG,m.PNG,m.TIFF,m.WEBP)}get isAudio(){return this.type==="audio"}get isVideo(){return this.type==="video"}get isRWPM(){return this.matchesAny(m.READIUM_AUDIOBOOK_MANIFEST,m.DIVINA_MANIFEST,m.READIUM_WEBPUB_MANIFEST)}get isPublication(){return this.matchesAny(m.READIUM_AUDIOBOOK,m.READIUM_AUDIOBOOK_MANIFEST,m.CBZ,m.DIVINA,m.DIVINA_MANIFEST,m.EPUB,m.LCP_PROTECTED_AUDIOBOOK,m.LCP_PROTECTED_PDF,m.LPF,m.PDF,m.W3C_WPUB_MANIFEST,m.READIUM_WEBPUB,m.READIUM_WEBPUB_MANIFEST,m.ZAB)}static get AAC(){return m.parse({mediaType:"audio/aac",fileExtension:"aac"})}static get ACSM(){return m.parse({mediaType:"application/vnd.adobe.adept+xml",name:"Adobe Content Server Message",fileExtension:"acsm"})}static get AIFF(){return m.parse({mediaType:"audio/aiff",fileExtension:"aiff"})}static get AVI(){return m.parse({mediaType:"video/x-msvideo",fileExtension:"avi"})}static get BINARY(){return m.parse({mediaType:"application/octet-stream"})}static get BMP(){return m.parse({mediaType:"image/bmp",fileExtension:"bmp"})}static get CBZ(){return m.parse({mediaType:"application/vnd.comicbook+zip",name:"Comic Book Archive",fileExtension:"cbz"})}static get CSS(){return m.parse({mediaType:"text/css",fileExtension:"css"})}static get DIVINA(){return m.parse({mediaType:"application/divina+zip",name:"Digital Visual Narratives",fileExtension:"divina"})}static get DIVINA_MANIFEST(){return m.parse({mediaType:"application/divina+json",name:"Digital Visual Narratives",fileExtension:"json"})}static get EPUB(){return m.parse({mediaType:"application/epub+zip",name:"EPUB",fileExtension:"epub"})}static get GIF(){return m.parse({mediaType:"image/gif",fileExtension:"gif"})}static get GZ(){return m.parse({mediaType:"application/gzip",fileExtension:"gz"})}static get HTML(){return m.parse({mediaType:"text/html",fileExtension:"html"})}static get JAVASCRIPT(){return m.parse({mediaType:"text/javascript",fileExtension:"js"})}static get JPEG(){return m.parse({mediaType:"image/jpeg",fileExtension:"jpeg"})}static get JSON(){return m.parse({mediaType:"application/json"})}static get LCP_LICENSE_DOCUMENT(){return m.parse({mediaType:"application/vnd.readium.lcp.license.v1.0+json",name:"LCP License",fileExtension:"lcpl"})}static get LCP_PROTECTED_AUDIOBOOK(){return m.parse({mediaType:"application/audiobook+lcp",name:"LCP Protected Audiobook",fileExtension:"lcpa"})}static get LCP_PROTECTED_PDF(){return m.parse({mediaType:"application/pdf+lcp",name:"LCP Protected PDF",fileExtension:"lcpdf"})}static get LCP_STATUS_DOCUMENT(){return m.parse({mediaType:"application/vnd.readium.license.status.v1.0+json"})}static get LPF(){return m.parse({mediaType:"application/lpf+zip",fileExtension:"lpf"})}static get MP3(){return m.parse({mediaType:"audio/mpeg",fileExtension:"mp3"})}static get MPEG(){return m.parse({mediaType:"video/mpeg",fileExtension:"mpeg"})}static get NCX(){return m.parse({mediaType:"application/x-dtbncx+xml",fileExtension:"ncx"})}static get OGG(){return m.parse({mediaType:"audio/ogg",fileExtension:"oga"})}static get OGV(){return m.parse({mediaType:"video/ogg",fileExtension:"ogv"})}static get OPDS1(){return m.parse({mediaType:"application/atom+xml;profile=opds-catalog"})}static get OPDS1_ENTRY(){return m.parse({mediaType:"application/atom+xml;type=entry;profile=opds-catalog"})}static get OPDS2(){return m.parse({mediaType:"application/opds+json"})}static get OPDS2_PUBLICATION(){return m.parse({mediaType:"application/opds-publication+json"})}static get OPDS_AUTHENTICATION(){return m.parse({mediaType:"application/opds-authentication+json"})}static get OPUS(){return m.parse({mediaType:"audio/opus",fileExtension:"opus"})}static get OTF(){return m.parse({mediaType:"font/otf",fileExtension:"otf"})}static get PDF(){return m.parse({mediaType:"application/pdf",name:"PDF",fileExtension:"pdf"})}static get PNG(){return m.parse({mediaType:"image/png",fileExtension:"png"})}static get READIUM_AUDIOBOOK(){return m.parse({mediaType:"application/audiobook+zip",name:"Readium Audiobook",fileExtension:"audiobook"})}static get READIUM_AUDIOBOOK_MANIFEST(){return m.parse({mediaType:"application/audiobook+json",name:"Readium Audiobook",fileExtension:"json"})}static get READIUM_CONTENT_DOCUMENT(){return m.parse({mediaType:"application/vnd.readium.content+json",name:"Readium Content Document",fileExtension:"json"})}static get READIUM_GUIDED_NAVIGATION_DOCUMENT(){return m.parse({mediaType:"application/guided-navigation+json",name:"Readium Guided Navigation Document",fileExtension:"json"})}static get READIUM_POSITION_LIST(){return m.parse({mediaType:"application/vnd.readium.position-list+json",name:"Readium Position List",fileExtension:"json"})}static get READIUM_WEBPUB(){return m.parse({mediaType:"application/webpub+zip",name:"Readium Web Publication",fileExtension:"webpub"})}static get READIUM_WEBPUB_MANIFEST(){return m.parse({mediaType:"application/webpub+json",name:"Readium Web Publication",fileExtension:"json"})}static get SMIL(){return m.parse({mediaType:"application/smil+xml",fileExtension:"smil"})}static get SVG(){return m.parse({mediaType:"image/svg+xml",fileExtension:"svg"})}static get TEXT(){return m.parse({mediaType:"text/plain",fileExtension:"txt"})}static get TIFF(){return m.parse({mediaType:"image/tiff",fileExtension:"tiff"})}static get TTF(){return m.parse({mediaType:"font/ttf",fileExtension:"ttf"})}static get W3C_WPUB_MANIFEST(){return m.parse({mediaType:"application/x.readium.w3c.wpub+json",name:"Web Publication",fileExtension:"json"})}static get WAV(){return m.parse({mediaType:"audio/wav",fileExtension:"wav"})}static get WEBM_AUDIO(){return m.parse({mediaType:"audio/webm",fileExtension:"webm"})}static get WEBM_VIDEO(){return m.parse({mediaType:"video/webm",fileExtension:"webm"})}static get WEBP(){return m.parse({mediaType:"image/webp",fileExtension:"webp"})}static get WOFF(){return m.parse({mediaType:"font/woff",fileExtension:"woff"})}static get WOFF2(){return m.parse({mediaType:"font/woff2",fileExtension:"woff2"})}static get XHTML(){return m.parse({mediaType:"application/xhtml+xml",fileExtension:"xhtml"})}static get XML(){return m.parse({mediaType:"application/xml",fileExtension:"xml"})}static get ZAB(){return m.parse({mediaType:"application/x.readium.zab+zip",name:"Zipped Audio Book",fileExtension:"zab"})}static get ZIP(){return m.parse({mediaType:"application/zip",fileExtension:"zip"})}}class ti{constructor(t){this.uri=t,this.parameters=this.getParameters(t)}getParameters(t){const e=/\{\??([^}]+)\}/g,i=t.match(e);return i?new Set(i.join(",").replace(e,"$1").split(",").map(A=>A.trim())):new Set}expand(t){const e=A=>A.split(",").map(n=>{const s=t[n];return s?encodeURIComponent(s):""}).join(","),i=A=>"?"+A.split(",").map(n=>{const s=n.split("=")[0],o=t[s];return o?`${s}=${encodeURIComponent(o)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...A)=>A[1]?i(A[2]):e(A[2]))}}class R{constructor(t){this.fragments=t.fragments?t.fragments:new Array,this.progression=t.progression,this.totalProgression=t.totalProgression,this.position=t.position,this.otherLocations=t.otherLocations}static deserialize(t){if(!t)return;const e=jt(t.progression),i=jt(t.totalProgression),A=jt(t.position),n=new Map,s=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(t).forEach(([o,a])=>{s.has(o)||n.set(o,a)}),new R({fragments:_e(t.fragments||t.fragment),progression:e!==void 0&&e>=0&&e<=1?e:void 0,totalProgression:i!==void 0&&i>=0&&i<=1?i:void 0,position:A!==void 0&&A>0?A:void 0,otherLocations:n.size===0?void 0:n})}serialize(){const t={};return this.fragments&&(t.fragments=this.fragments),this.progression!==void 0&&(t.progression=this.progression),this.totalProgression!==void 0&&(t.totalProgression=this.totalProgression),this.position!==void 0&&(t.position=this.position),this.otherLocations&&this.otherLocations.forEach((e,i)=>t[i]=e),t}}class it{constructor(t){this.after=t.after,this.before=t.before,this.highlight=t.highlight}static deserialize(t){if(t)return new it({after:t.after,before:t.before,highlight:t.highlight})}serialize(){const t={};return this.after!==void 0&&(t.after=this.after),this.before!==void 0&&(t.before=this.before),this.highlight!==void 0&&(t.highlight=this.highlight),t}}class K{constructor(t){this.href=t.href,this.type=t.type,this.title=t.title,this.locations=t.locations?t.locations:new R({}),this.text=t.text}static deserialize(t){if(t&&t.href&&t.type)return new K({href:t.href,type:t.type,title:t.title,locations:R.deserialize(t.locations),text:it.deserialize(t.text)})}serialize(){const t={href:this.href,type:this.type};return this.title!==void 0&&(t.title=this.title),this.locations&&(t.locations=this.locations.serialize()),this.text&&(t.text=this.text.serialize()),t}copyWithLocations(t){return new K({href:this.href,type:this.type,title:this.title,text:this.text,locations:new R({...this.locations,...t})})}}class ct{constructor(t){this.href=t.href,this.templated=t.templated,this.type=t.type,this.title=t.title,this.rels=t.rels,this.properties=t.properties,this.height=t.height,this.width=t.width,this.size=t.size,this.duration=t.duration,this.bitrate=t.bitrate,this.languages=t.languages,this.alternates=t.alternates,this.children=t.children}static deserialize(t){if(!(!t||typeof t.href!="string"))return new ct({href:t.href,templated:t.templated,type:t.type,title:t.title,rels:t.rel?Array.isArray(t.rel)?new Set(t.rel):new Set([t.rel]):void 0,properties:x.deserialize(t.properties),height:b(t.height),width:b(t.width),size:b(t.size),duration:b(t.duration),bitrate:b(t.bitrate),languages:_e(t.language),alternates:Vt.deserialize(t.alternate),children:Vt.deserialize(t.children)})}serialize(){const t={href:this.href};return this.templated!==void 0&&(t.templated=this.templated),this.type!==void 0&&(t.type=this.type),this.title!==void 0&&(t.title=this.title),this.rels&&(t.rel=DA(this.rels)),this.properties&&(t.properties=this.properties.serialize()),this.height!==void 0&&(t.height=this.height),this.width!==void 0&&(t.width=this.width),this.size!==void 0&&(t.size=this.size),this.duration!==void 0&&(t.duration=this.duration),this.bitrate!==void 0&&(t.bitrate=this.bitrate),this.languages&&(t.language=this.languages),this.alternates&&(t.alternate=this.alternates.serialize()),this.children&&(t.children=this.children.serialize()),t}get mediaType(){return this.type!==void 0?m.parse({mediaType:this.type}):m.BINARY}toURL(t){const e=this.href.replace(/^(\/)/,"");if(e.length===0)return;let i=t||"/";return i.startsWith("/")&&(i="file://"+i),new URL(e,i).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new ti(this.href).parameters:new Set}expandTemplate(t){return new ct({href:new ti(this.href).expand(t),templated:!1})}addProperties(t){const e=ct.deserialize(this.serialize());return e.properties=e.properties?e.properties?.add(t):new x(t),e}get locator(){let t=this.href.split("#");return new K({href:t.length>0&&t[0]!==void 0?t[0]:this.href,type:this.type??"",title:this.title,locations:new R({fragments:t.length>1&&t[1]!==void 0?[t[1]]:[]})})}}class Vt{constructor(t){this.items=t}static deserialize(t){if(t&&Array.isArray(t))return new Vt(t.map(e=>ct.deserialize(e)).filter(e=>e!==void 0))}serialize(){return this.items.map(t=>t.serialize())}findWithRel(t){const e=i=>i.rels&&i.rels.has(t);return this.items.find(e)}filterByRel(t){const e=i=>i.rels&&i.rels.has(t);return this.items.filter(e)}findWithHref(t){const e=i=>i.href===t;return this.items.find(e)}findIndexWithHref(t){const e=i=>i.href===t;return this.items.findIndex(e)}findWithMediaType(t){const e=i=>i.mediaType.matches(t);return this.items.find(e)}filterByMediaType(t){const e=i=>i.mediaType.matches(t);return this.items.filter(e)}filterByMediaTypes(t){const e=i=>{for(const A of t)if(i.mediaType.matches(A))return!0;return!1};return this.items.filter(e)}everyIsAudio(){const t=e=>e.mediaType.isAudio;return this.items.length>0&&this.items.every(t)}everyIsBitmap(){const t=e=>e.mediaType.isBitmap;return this.items.length>0&&this.items.every(t)}everyIsHTML(){const t=e=>e.mediaType.isHTML;return this.items.length>0&&this.items.every(t)}everyIsVideo(){const t=e=>e.mediaType.isVideo;return this.items.length>0&&this.items.every(t)}everyMatchesMediaType(t){return Array.isArray(t)?this.items.length>0&&this.items.every(e=>{for(const i of t)return e.mediaType.matches(i);return!1}):this.items.length>0&&this.items.every(e=>e.mediaType.matches(t))}filterLinksHasType(){return this.items.filter(t=>t.type)}}x.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])};class Pt{constructor(t){this.cssSelector=t.cssSelector,this.textNodeIndex=t.textNodeIndex,this.charOffset=t.charOffset}static deserialize(t){if(!(t&&t.cssSelector))return;let e=b(t.textNodeIndex);if(e===void 0)return;let i=b(t.charOffset);return i===void 0&&(i=b(t.offset)),new Pt({cssSelector:t.cssSelector,textNodeIndex:e,charOffset:i})}serialize(){const t={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(t.charOffset=this.charOffset),t}}class ce{constructor(t){this.start=t.start,this.end=t.end}static deserialize(t){if(!t)return;let e=Pt.deserialize(t.start);if(e)return new ce({start:e,end:Pt.deserialize(t.end)})}serialize(){const t={start:this.start.serialize()};return this.end&&(t.end=this.end.serialize()),t}}R.prototype.getCssSelector=function(){return this.otherLocations?.get("cssSelector")},R.prototype.getPartialCfi=function(){return this.otherLocations?.get("partialCfi")},R.prototype.getDomRange=function(){return ce.deserialize(this.otherLocations?.get("domRange"))},R.prototype.fragmentParameters=function(){return new Map(this.fragments.map(r=>r.startsWith("#")?r.slice(1):r).join("&").split("&").filter(r=>!r.startsWith("#")).map(r=>r.split("=")).filter(r=>r.length===2).map(r=>[r[0].trim().toLowerCase(),r[1].trim()]))},R.prototype.htmlId=function(){if(!this.fragments.length)return;let r=this.fragments.find(t=>t.length&&!t.includes("="));if(!r){const t=this.fragmentParameters();t.has("id")?r=t.get("id"):t.has("name")&&(r=t.get("name"))}return r?.startsWith("#")?r.slice(1):r},R.prototype.page=function(){const r=parseInt(this.fragmentParameters().get("page"));if(!isNaN(r)&&r>=0)return r},R.prototype.time=function(){const r=parseInt(this.fragmentParameters().get("t"));if(!isNaN(r))return r},R.prototype.space=function(){const r=this.fragmentParameters();if(!r.has("xywh"))return;const t=r.get("xywh").split(",").map(e=>parseInt(e));if(t.length===4&&!t.some(isNaN))return t};class ge{constructor(t){this.currency=t.currency,this.value=t.value}static deserialize(t){if(!t)return;let e=t.currency;if(!(e&&typeof e=="string"&&e.length>0))return;let i=b(t.value);if(i!==void 0)return new ge({currency:e,value:i})}serialize(){return{currency:this.currency,value:this.value}}}class It{constructor(t){this.type=t.type,this.children=t.children}static deserialize(t){if(t&&t.type)return new It({type:t.type,children:It.deserializeArray(t.children)})}static deserializeArray(t){if(Array.isArray(t))return t.map(e=>It.deserialize(e)).filter(e=>e!==void 0)}serialize(){const t={type:this.type};return this.children&&(t.children=this.children.map(e=>e.serialize())),t}}class de{constructor(t){this.total=t.total,this.position=t.position}static deserialize(t){if(t)return new de({total:b(t.total),position:b(t.position)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.position!==void 0&&(t.position=this.position),t}}class ue{constructor(t){this.total=t.total,this.available=t.available}static deserialize(t){if(t)return new ue({total:b(t.total),available:b(t.available)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.available!==void 0&&(t.available=this.available),t}}class me{constructor(t){this.state=t.state,this.since=t.since,this.until=t.until}static deserialize(t){if(t&&t.state)return new me({state:t.state,since:$e(t.since),until:$e(t.until)})}serialize(){const t={state:this.state};return this.since!==void 0&&(t.since=this.since.toISOString()),this.until!==void 0&&(t.until=this.until.toISOString()),t}}x.prototype.getNumberOfItems=function(){return b(this.otherProperties.numberOfItems)},x.prototype.getPrice=function(){return ge.deserialize(this.otherProperties.price)},x.prototype.getIndirectAcquisitions=function(){const r=this.otherProperties.indirectAcquisition;if(r&&Array.isArray(r))return r.map(t=>It.deserialize(t)).filter(t=>t!==void 0)},x.prototype.getHolds=function(){return de.deserialize(this.otherProperties.holds)},x.prototype.getCopies=function(){return ue.deserialize(this.otherProperties.copies)},x.prototype.getAvailability=function(){return me.deserialize(this.otherProperties.availability)},x.prototype.getAuthenticate=function(){return ct.deserialize(this.otherProperties.authenticate)};const HA="CssSelectorGenerator";function ei(r="unknown problem",...t){console.warn(`${HA}: ${r}`,...t)}function GA(r){return r instanceof RegExp}function kA(r){return r.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function JA(r){const t=r.map(e=>{if(GA(e))return i=>e.test(i);if(typeof e=="function")return i=>{const A=e(i);return typeof A!="boolean"?(ei("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",e),!1):A};if(typeof e=="string"){const i=new RegExp("^"+kA(e)+"$");return A=>i.test(A)}return ei("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",e),()=>!1});return e=>t.some(i=>i(e))}JA(["class","id","ng-*"]);class Ft{}function ii(r){return r.split("").reverse().join("")}function WA(r,t,e){const i=ii(t);return e.map(A=>{const n=Math.max(0,A.end-t.length-A.errors),s=ii(r.slice(n,A.end));return{start:ni(s,i,A.errors).reduce((o,a)=>A.end-a.end<o?A.end-a.end:o,A.end),end:A.end,errors:A.errors}})}function fe(r){return(r|-r)>>31&1}function Ai(r,t,e,i){let A=r.P[e],n=r.M[e];const s=i>>>31,o=t[e]|s,a=o|n,h=(o&A)+A^A|o;let c=n|~(h|A),g=A&h;const u=fe(c&r.lastRowMask[e])-fe(g&r.lastRowMask[e]);return c<<=1,g<<=1,g|=s,c|=fe(i)-s,A=g|~(a|c),n=c&a,r.P[e]=A,r.M[e]=n,u}function ni(r,t,e){if(t.length===0)return[];e=Math.min(e,t.length);const i=[],A=32,n=Math.ceil(t.length/A)-1,s={P:new Uint32Array(n+1),M:new Uint32Array(n+1),lastRowMask:new Uint32Array(n+1)};s.lastRowMask.fill(1<<31),s.lastRowMask[n]=1<<(t.length-1)%A;const o=new Uint32Array(n+1),a=new Map,h=[];for(let u=0;u<256;u++)h.push(o);for(let u=0;u<t.length;u+=1){const M=t.charCodeAt(u);if(a.has(M))continue;const l=new Uint32Array(n+1);a.set(M,l),M<h.length&&(h[M]=l);for(let f=0;f<=n;f+=1){l[f]=0;for(let E=0;E<A;E+=1){const F=f*A+E;F>=t.length||t.charCodeAt(F)===M&&(l[f]|=1<<E)}}}let c=Math.max(0,Math.ceil(e/A)-1);const g=new Uint32Array(n+1);for(let u=0;u<=c;u+=1)g[u]=(u+1)*A;g[n]=t.length;for(let u=0;u<=c;u+=1)s.P[u]=-1,s.M[u]=0;for(let u=0;u<r.length;u+=1){const M=r.charCodeAt(u);let l;M<h.length?l=h[M]:(l=a.get(M),typeof l>"u"&&(l=o));let f=0;for(let E=0;E<=c;E+=1)f=Ai(s,l,E,f),g[E]+=f;if(g[c]-f<=e&&c<n&&(l[c+1]&1||f<0)){c+=1,s.P[c]=-1,s.M[c]=0;let E;if(c===n){const F=t.length%A;E=F===0?A:F}else E=A;g[c]=g[c-1]+E-f+Ai(s,l,c,f)}else for(;c>0&&g[c]>=e+A;)c-=1;c===n&&g[c]<=e&&(g[c]<e&&i.splice(0,i.length),i.push({start:-1,end:u+1,errors:g[c]}),e=g[c])}return i}function LA(r,t,e){const i=ni(r,t,e);return WA(r,t,i)}function ri(r,t,e){let i=0;const A=[];for(;i!==-1;)i=r.indexOf(t,i),i!==-1&&(A.push({start:i,end:i+t.length,errors:0}),i+=1);return A.length>0?A:LA(r,t,e)}function si(r,t){return t.length===0||r.length===0?0:1-ri(r,t,t.length)[0].errors/t.length}function OA(r,t,e={}){if(t.length===0)return null;const i=Math.min(256,t.length/2),A=ri(r,t,i);if(A.length===0)return null;const n=o=>{const a=1-o.errors/t.length,h=e.prefix?si(r.slice(Math.max(0,o.start-e.prefix.length),o.start),e.prefix):1,c=e.suffix?si(r.slice(o.end,o.end+e.suffix.length),e.suffix):1;let g=1;return typeof e.hint=="number"&&(g=1-Math.abs(o.start-e.hint)/r.length),(50*a+20*h+20*c+2*g)/92},s=A.map(o=>({start:o.start,end:o.end,score:n(o)}));return s.sort((o,a)=>a.score-o.score),s[0]}function pe(r,t,e){const i=e===1?t:t-1;if(r.charAt(i).trim()!=="")return t;let A,n;if(e===2?(A=r.substring(0,t),n=A.trimEnd()):(A=r.substring(t),n=A.trimStart()),!n.length)return-1;const s=A.length-n.length;return e===2?t-s:t+s}function oi(r,t){const e=r.commonAncestorContainer.ownerDocument.createNodeIterator(r.commonAncestorContainer,NodeFilter.SHOW_TEXT),i=t===1?r.startContainer:r.endContainer,A=t===1?r.endContainer:r.startContainer;let n=e.nextNode();for(;n&&n!==i;)n=e.nextNode();t===2&&(n=e.previousNode());let s=-1;const o=()=>{if(n=t===1?e.nextNode():e.previousNode(),n){const a=n.textContent,h=t===1?0:a.length;s=pe(a,h,t)}};for(;n&&s===-1&&n!==A;)o();if(n&&s>=0)return{node:n,offset:s};throw new RangeError("No text nodes with non-whitespace text found in range")}function XA(r){if(!r.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(r.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(r.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const t=r.cloneRange();let e=!1,i=!1;const A={start:pe(r.startContainer.textContent,r.startOffset,1),end:pe(r.endContainer.textContent,r.endOffset,2)};if(A.start>=0&&(t.setStart(r.startContainer,A.start),e=!0),A.end>0&&(t.setEnd(r.endContainer,A.end),i=!0),e&&i)return t;if(!e){const{node:n,offset:s}=oi(t,1);n&&s>=0&&t.setStart(n,s)}if(!i){const{node:n,offset:s}=oi(t,2);n&&s>0&&t.setEnd(n,s)}return t}function ai(r){switch(r.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return r.textContent?.length??0;default:return 0}}function li(r){let t=r.previousSibling,e=0;for(;t;)e+=ai(t),t=t.previousSibling;return e}function hi(r,...t){let e=t.shift();const i=r.ownerDocument.createNodeIterator(r,NodeFilter.SHOW_TEXT),A=[];let n=i.nextNode(),s,o=0;for(;e!==void 0&&n;)s=n,o+s.data.length>e?(A.push({node:s,offset:e-o}),e=t.shift()):(n=i.nextNode(),o+=s.data.length);for(;e!==void 0&&s&&o===e;)A.push({node:s,offset:s.data.length}),e=t.shift();if(e!==void 0)throw new RangeError("Offset exceeds text length");return A}class O{constructor(t,e){if(e<0)throw new Error("Offset is invalid");this.element=t,this.offset=e}relativeTo(t){if(!t.contains(this.element))throw new Error("Parent is not an ancestor of current element");let e=this.element,i=this.offset;for(;e!==t;)i+=li(e),e=e.parentElement;return new O(e,i)}resolve(t={}){try{return hi(this.element,this.offset)[0]}catch(e){if(this.offset===0&&t.direction!==void 0){const i=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);i.currentNode=this.element;const A=t.direction===1,n=A?i.nextNode():i.previousNode();if(!n)throw e;return{node:n,offset:A?0:n.data.length}}else throw e}}static fromCharOffset(t,e){switch(t.nodeType){case Node.TEXT_NODE:return O.fromPoint(t,e);case Node.ELEMENT_NODE:return new O(t,e);default:throw new Error("Node is not an element or text node")}}static fromPoint(t,e){switch(t.nodeType){case Node.TEXT_NODE:{if(e<0||e>t.data.length)throw new Error("Text node offset is out of range");if(!t.parentElement)throw new Error("Text node has no parent");const i=li(t)+e;return new O(t.parentElement,i)}case Node.ELEMENT_NODE:{if(e<0||e>t.childNodes.length)throw new Error("Child node offset is out of range");let i=0;for(let A=0;A<e;A++)i+=ai(t.childNodes[A]);return new O(t,i)}default:throw new Error("Point is not in an element or text node")}}}class ${constructor(t,e){this.start=t,this.end=e}relativeTo(t){return new $(this.start.relativeTo(t),this.end.relativeTo(t))}toRange(){let t,e;this.start.element===this.end.element&&this.start.offset<=this.end.offset?[t,e]=hi(this.start.element,this.start.offset,this.end.offset):(t=this.start.resolve({direction:1}),e=this.end.resolve({direction:2}));const i=new Range;return i.setStart(t.node,t.offset),i.setEnd(e.node,e.offset),i}static fromRange(t){const e=O.fromPoint(t.startContainer,t.startOffset),i=O.fromPoint(t.endContainer,t.endOffset);return new $(e,i)}static fromOffsets(t,e,i){return new $(new O(t,e),new O(t,i))}static trimmedRange(t){return XA($.fromRange(t).toRange())}}class vt{constructor(t,e,i){this.root=t,this.start=e,this.end=i}static fromRange(t,e){const i=$.fromRange(e).relativeTo(t);return new vt(t,i.start.offset,i.end.offset)}static fromSelector(t,e){return new vt(t,e.start,e.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return $.fromOffsets(this.root,this.start,this.end).toRange()}}class Dt{constructor(t,e,i={}){this.root=t,this.exact=e,this.context=i}static fromRange(t,e){const i=t.textContent,A=$.fromRange(e).relativeTo(t),n=A.start.offset,s=A.end.offset,o=32;return new Dt(t,i.slice(n,s),{prefix:i.slice(Math.max(0,n-o),n),suffix:i.slice(s,Math.min(i.length,s+o))})}static fromSelector(t,e){const{prefix:i,suffix:A}=e;return new Dt(t,e.exact,{prefix:i,suffix:A})}toSelector(){return{type:"TextQuoteSelector",exact:this.exact,prefix:this.context.prefix,suffix:this.context.suffix}}toRange(t={}){return this.toPositionAnchor(t).toRange()}toPositionAnchor(t={}){const e=this.root.textContent,i=OA(e,this.exact,{...this.context,hint:t.hint});if(!i)throw new Error("Quote not found");return new vt(this.root,i.start,i.end)}}function ZA(r){const t=r.tagName.toUpperCase();return t==="IMG"||t==="VIDEO"||t==="AUDIO"||t==="IFRAME"||t==="OBJECT"||t==="EMBED"||t==="CANVAS"}function Ht(r,t){try{const e=t.locations,i=t.text;if(i&&i.highlight){let A;e&&e.getCssSelector()&&(A=r.querySelector(e.getCssSelector())),A||(A=r.body);const n=new Dt(A,i.highlight,{prefix:i.before,suffix:i.after});try{return n.toRange()}catch{return console.warn("Quote not found:",n),null}}if(e){let A=null;if(!A&&e.getCssSelector()&&(A=r.querySelector(e.getCssSelector())),!A&&e.fragments){for(const n of e.fragments)if(A=r.getElementById(n),A)break}if(A){const n=r.createRange();return A.childNodes.length===0||ZA(A)?(n.selectNode(A),n):(n.setStartBefore(A),n.setEndAfter(A),n)}}}catch(e){console.error(e)}return null}function KA(r,t){let e=r.getClientRects();e.length||r.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(e=r.commonAncestorContainer.getClientRects());const i=1,A=[];for(const h of e)A.push({bottom:h.bottom,height:h.height,left:h.left,right:h.right,top:h.top,width:h.width});const n=ci(A,i),s=_A(n,i),o=gi(s),a=4;for(let h=o.length-1;h>=0;h--){const c=o[h];if(!(c.width*c.height>a))if(o.length>1)o.splice(h,1);else break}return o}function ci(r,t,e){for(let i=0;i<r.length;i++)for(let A=i+1;A<r.length;A++){const n=r[i],s=r[A];if(n===s)continue;const o=D(n.top,s.top,t)&&D(n.bottom,s.bottom,t),a=D(n.left,s.left,t)&&D(n.right,s.right,t);if(o&&!a&&ui(n,s,t)){const h=r.filter(g=>g!==n&&g!==s),c=qA(n,s);return h.push(c),ci(h,t)}}return r}function qA(r,t){const e=Math.min(r.left,t.left),i=Math.max(r.right,t.right),A=Math.min(r.top,t.top),n=Math.max(r.bottom,t.bottom);return{bottom:n,height:n-A,left:e,right:i,top:A,width:i-e}}function _A(r,t){const e=new Set(r);for(const i of r){if(!(i.width>1&&i.height>1)){e.delete(i);continue}for(const A of r)if(i!==A&&e.has(A)&&$A(A,i,t)){e.delete(i);break}}return Array.from(e)}function $A(r,t,e){return Gt(r,t.left,t.top,e)&&Gt(r,t.right,t.top,e)&&Gt(r,t.left,t.bottom,e)&&Gt(r,t.right,t.bottom,e)}function Gt(r,t,e,i){return(r.left<t||D(r.left,t,i))&&(r.right>t||D(r.right,t,i))&&(r.top<e||D(r.top,e,i))&&(r.bottom>e||D(r.bottom,e,i))}function gi(r){for(let t=0;t<r.length;t++)for(let e=t+1;e<r.length;e++){const i=r[t],A=r[e];if(i!==A&&ui(i,A,-1)){let n=[],s;const o=di(i,A);if(o.length===1)n=o,s=i;else{const h=di(A,i);o.length<h.length?(n=o,s=i):(n=h,s=A)}const a=r.filter(h=>h!==s);return Array.prototype.push.apply(a,n),gi(a)}}return r}function di(r,t){const e=tn(t,r);if(e.height===0||e.width===0)return[r];const i=[];{const A={bottom:r.bottom,height:0,left:r.left,right:e.left,top:r.top,width:0};A.width=A.right-A.left,A.height=A.bottom-A.top,A.height!==0&&A.width!==0&&i.push(A)}{const A={bottom:e.top,height:0,left:e.left,right:e.right,top:r.top,width:0};A.width=A.right-A.left,A.height=A.bottom-A.top,A.height!==0&&A.width!==0&&i.push(A)}{const A={bottom:r.bottom,height:0,left:e.left,right:e.right,top:e.bottom,width:0};A.width=A.right-A.left,A.height=A.bottom-A.top,A.height!==0&&A.width!==0&&i.push(A)}{const A={bottom:r.bottom,height:0,left:e.right,right:r.right,top:r.top,width:0};A.width=A.right-A.left,A.height=A.bottom-A.top,A.height!==0&&A.width!==0&&i.push(A)}return i}function tn(r,t){const e=Math.max(r.left,t.left),i=Math.min(r.right,t.right),A=Math.max(r.top,t.top),n=Math.min(r.bottom,t.bottom);return{bottom:n,height:Math.max(0,n-A),left:e,right:i,top:A,width:Math.max(0,i-e)}}function ui(r,t,e){return(r.left<t.right||e>=0&&D(r.left,t.right,e))&&(t.left<r.right||e>=0&&D(t.left,r.right,e))&&(r.top<t.bottom||e>=0&&D(r.top,t.bottom,e))&&(t.top<r.bottom||e>=0&&D(t.top,r.bottom,e))}function D(r,t,e){return Math.abs(r-t)<=e}function Me(r){const t={},e=r.document.documentElement.style;for(const i in r.document.documentElement.style)Object.hasOwn(e,i)&&!Number.isNaN(Number.parseInt(i))&&(t[e[i]]=e.getPropertyValue(e[i]));return t}function mi(r,t){const e=Me(r);Object.keys(e).forEach(i=>{t.hasOwnProperty(i)||kt(r,i)}),Object.entries(t).forEach(([i,A])=>{e[i]!==A&&Ut(r,i,A)})}function fi(r,t){return r.document.documentElement.style.getPropertyValue(t)}function Ut(r,t,e){r.document.documentElement.style.setProperty(t,e)}function kt(r,t){r.document.documentElement.style.removeProperty(t)}const en=r=>{if(r.startsWith("rgb")){const t=r.match(/rgb\((\d+),\s(\d+),\s(\d+)(?:,\s(\d+))?\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?parseInt(t[4],10)/255:1}}else if(r.startsWith("#")){const t=r.slice(1);if(t.length===3||t.length===4)return{r:parseInt(t[0]+t[0],16)/255,g:parseInt(t[1]+t[1],16)/255,b:parseInt(t[2]+t[2],16)/255,a:t.length===4?parseInt(t[3]+t[3],16)/255:1};if(t.length===6||t.length===8)return{r:parseInt(t[0]+t[1],16)/255,g:parseInt(t[2]+t[3],16)/255,b:parseInt(t[4]+t[5],16)/255,a:t.length===8?parseInt(t[6]+t[7],16)/255:1}}return{r:0,g:0,b:0,a:1}},An=r=>.2126*r.r*r.a+.7152*r.g*r.a+.0722*r.b*r.a,nn=r=>{const t=en(r);return An(t)<128},rn=()=>"Highlight"in window,pi=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class sn{constructor(t,e,i,A){this.wnd=t,this.comms=e,this.id=i,this.name=A,this.items=[],this.lastItemId=0,this.container=void 0,this.activateable=!1,this.experimentalHighlights=!1,this.currentRender=0,rn()&&(this.experimentalHighlights=!0,this.notTextFlag=new Map)}get activeable(){return this.activateable}set activeable(t){this.activateable=t}add(t){const e=`${this.id}-${this.lastItemId++}`,i=Ht(this.wnd.document,t.locator);if(!i){this.comms.log("Can't locate DOM range for decoration",t);return}const A=i.commonAncestorContainer;A.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&(pi.includes(A.nodeName.toUpperCase())&&this.notTextFlag?.set(e,!0),A.querySelector(pi.join(", ").toLowerCase())&&this.notTextFlag?.set(e,!0),(A.textContent?.trim()||"").length===0&&this.notTextFlag?.set(e,!0));const n={decoration:t,id:e,range:i};this.items.push(n),this.layout(n),this.renderLayout([n])}remove(t){const e=this.items.findIndex(A=>A.decoration.id===t);if(e<0)return;const i=this.items[e];this.items.splice(e,1),i.clickableElements=void 0,i.container&&(i.container.remove(),i.container=void 0),this.experimentalHighlights&&!this.notTextFlag?.has(i.id)&&this.wnd.CSS.highlights.get(this.id)?.delete(i.range),this.notTextFlag?.delete(i.id)}update(t){this.remove(t.id),this.add(t)}clear(){this.clearContainer(),this.items.length=0,this.notTextFlag?.clear()}requestLayout(){this.wnd.cancelAnimationFrame(this.currentRender),this.clearContainer(),this.items.forEach(t=>this.layout(t)),this.renderLayout(this.items)}experimentalLayout(t){const[e,i]=this.requireContainer(!0);i.add(t.range),e.innerHTML=`
|
|
215
|
+
});`),"text/javascript")));class Ke{constructor(t,e,i,A){this.pub=t,this.item=i,this.burl=i.toURL(e)||"",this.cssProperties=A}async build(){if(!this.item.mediaType.isHTML)throw new Error(`Unsupported media type for WebPub: ${this.item.mediaType.string}`);return await this.buildHtmlFrame()}async buildHtmlFrame(){const t=await this.pub.get(this.item).readAsString();if(!t)throw new Error(`Failed reading item ${this.item.href}`);const e=new DOMParser().parseFromString(t,this.item.mediaType.string),i=e.querySelector("parsererror");if(i){const A=i.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${A?.textContent||i.textContent}`)}return this.finalizeDOM(e,this.burl,this.item.mediaType,t,this.cssProperties)}hasExecutable(t){return!!t.querySelector("script")||!!t.querySelector("body[onload]:not(body[onload=''])")}setProperties(t,e){for(const i in t){const A=t[i];A&&e.documentElement.style.setProperty(i,A)}}finalizeDOM(t,e,i,A,n){if(!t)return"";const s=NA(t,Xe);if(t.head.appendChild(s),n&&this.setProperties(n,t),t.body.querySelectorAll("img").forEach(h=>{h.setAttribute("fetchpriority","high")}),e!==void 0){const h=t.createElement("base");h.href=e,h.dataset.readium="true",t.head.firstChild.before(h)}const o=this.hasExecutable(t);o&&t.head.firstChild.before(bA(t)),t.head.firstChild.before(xA(t)),o&&t.head.appendChild(jA(t));let a;return i.string==="application/xhtml+xml"?a=new XMLSerializer().serializeToString(t):a=this.serializeAsHTML(t,A||""),URL.createObjectURL(new Blob([a],{type:i.isHTML?i.string:"application/xhtml+xml"}))}serializeAsHTML(t,e){const i=e.match(/<!DOCTYPE[^>]*>/i),A=i?i[0]+`
|
|
216
|
+
`:"";let s=t.documentElement.outerHTML;return A+s}}const VA=Math.pow(2,32),qe=()=>Math.round(Math.random()*VA).toString(36),ae=()=>`${Math.round(performance.now())}-${qe()}-${qe()}`,lt=1;class PA{constructor(t){this.destination=null,this.registrar=new Map,this.origin="",this.channelId="",this.receiver=this.receive.bind(this),this.preLog=[],this.wnd=t,t.addEventListener("message",this.receiver)}receive(t){if(t.source===null)throw Error("Event source is null");if(typeof t.data!="object")return;const e=t.data;if(!(!("_readium"in e)||!e._readium||e._readium<=0)){if(e.key==="_ping"){if(!this.destination){if(this.destination=t.source,this.origin=t.origin,this.channelId=e._channel,e._readium!==lt){e._readium>lt?this.send("error",`received comms version ${e._readium} higher than ${lt}`):this.send("error",`received comms version ${e._readium} lower than ${lt}`),this.destination=null,this.origin="",this.channelId="";return}this.send("_pong",void 0),this.preLog.forEach(i=>this.send("log",i)),this.preLog=[]}return}else if(this.channelId){if(e._channel!==this.channelId||t.origin!==this.origin)return}else return;this.handle(e)}}handle(t){const e=this.registrar.get(t.key);if(!e||e.length===0){t.strict&&this.send("_unhandled",t);return}e.forEach(i=>i.cb(t.data,A=>{this.send("_ack",A,t.id)}))}register(t,e,i){Array.isArray(t)||(t=[t]),t.forEach(A=>{const n=this.registrar.get(A);if(n&&n.length>=0){if(n.find(s=>s.module===e))throw new Error(`Trying to register another callback for combination of event ${A} and module ${e}`);n.push({cb:i,module:e}),this.registrar.set(A,n)}else this.registrar.set(A,[{cb:i,module:e}])})}unregister(t,e){Array.isArray(t)||(t=[t]),t.forEach(i=>{const A=this.registrar.get(i);!A||A.length===0||A.splice(A.findIndex(n=>n.module===e),1)})}unregisterAll(t){this.registrar.forEach((e,i)=>this.registrar.set(i,e.filter(A=>A.module!==t)))}log(...t){this.destination?this.send("log",t):this.preLog.push(t)}get ready(){return!!this.destination}destroy(){this.destination=null,this.channelId="",this.preLog=[],this.registrar.clear(),this.wnd.removeEventListener("message",this.receiver)}send(t,e,i=void 0,A=[]){if(!this.destination)throw Error("Attempted to send comms message before destination has been initialized");const n={_readium:lt,_channel:this.channelId,id:i??ae(),key:t,data:e};try{this.destination.postMessage(n,{targetOrigin:this.origin,transfer:A})}catch(s){if(A.length>0)throw s;this.destination.postMessage(n,this.origin,A)}}}const X=class wt{constructor(t){if(typeof t=="string"){if(!wt.VALID_MODES.has(t.toLowerCase()))return;this.value=t.toLowerCase()}else{const e=t.filter(i=>wt.VALID_MODES.has(i.toLowerCase()));if(e.length===0)return;this.value=Array.from(new Set(e))}}static deserialize(t){if(!t)return;if(typeof t=="string")return new wt(t);if(!Array.isArray(t))return;const e=t.filter(i=>i?wt.VALID_MODES.has(i.toLowerCase()):!1);if(e.length!==0)return new wt(e)}serialize(){return this.value}};X.VALID_MODES=new Set(["auditory","tactile","textual","visual"]),X.AUDITORY=new X("auditory"),X.TACTILE=new X("tactile"),X.TEXTUAL=new X("textual"),X.VISUAL=new X("visual");class le{constructor(t){this.algorithm=t.algorithm,this.compression=t.compression,this.originalLength=t.originalLength,this.profile=t.profile,this.scheme=t.scheme}static deserialize(t){if(t&&t.algorithm)return new le({algorithm:t.algorithm,compression:t.compression,originalLength:t.originalLength,profile:t.profile,scheme:t.scheme})}serialize(){const t={algorithm:this.algorithm};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}}class T{constructor(t){this.otherProperties=t}get page(){return this.otherProperties.page}static deserialize(t){if(t)return new T(t)}serialize(){return this.otherProperties}add(t){const e=Object.assign({},this.otherProperties);for(const i in t)e[i]=t[i];return new T(e)}}Object.defineProperty(T.prototype,"encryption",{get:function(){return le.deserialize(this.otherProperties.encrypted)}});function vA(r){return r&&Array.isArray(r)?r:void 0}function _e(r){return r&&typeof r=="string"?[r]:vA(r)}function $e(r){return typeof r=="string"?new Date(r):void 0}function bt(r){return isNaN(r)?void 0:r}function b(r){return bt(r)!==void 0&&Math.sign(r)>=0?r:void 0}function DA(r){const t=new Array;return r.forEach(e=>t.push(e)),t}class m{constructor(t){let e,i,A=t.mediaType.replace(/\s/g,"").split(";");const n=A[0].split("/");if(n.length===2){if(e=n[0].toLowerCase().trim(),i=n[1].toLowerCase().trim(),e.length===0||i.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const s={};for(let u=1;u<A.length;u++){const M=A[u].split("=");if(M.length===2){const l=M[0].toLocaleLowerCase(),f=l==="charset"?M[1].toUpperCase():M[1];s[l]=f}}const o={},a=Object.keys(s);a.sort((u,M)=>u.localeCompare(M)),a.forEach(u=>o[u]=s[u]);let h="";for(const u in o){const M=o[u];h+=`;${u}=${M}`}const c=`${e}/${i}${h}`,g=o.encoding;this.string=c,this.type=e,this.subtype=i,this.parameters=o,this.encoding=g,this.name=t.name,this.fileExtension=t.fileExtension}static parse(t){return new m(t)}get structuredSyntaxSuffix(){const t=this.subtype.split("+");return t.length>1?`+${t[t.length-1]}`:void 0}get charset(){return this.parameters.charset}contains(t){const e=typeof t=="string"?m.parse({mediaType:t}):t;if(!((this.type==="*"||this.type===e.type)&&(this.subtype==="*"||this.subtype===e.subtype)))return!1;const i=new Set(Object.entries(this.parameters).map(([n,s])=>`${n}=${s}`)),A=new Set(Object.entries(e.parameters).map(([n,s])=>`${n}=${s}`));for(const n of Array.from(i.values()))if(!A.has(n))return!1;return!0}matches(t){const e=typeof t=="string"?m.parse({mediaType:t}):t;return this.contains(e)||e.contains(this)}matchesAny(...t){for(const e of t)if(this.matches(e))return!0;return!1}equals(t){return this.string===t.string}get isZIP(){return this.matchesAny(m.ZIP,m.LCP_PROTECTED_AUDIOBOOK,m.LCP_PROTECTED_PDF)||this.structuredSyntaxSuffix==="+zip"}get isJSON(){return this.matchesAny(m.JSON)||this.structuredSyntaxSuffix==="+json"}get isOPDS(){return this.matchesAny(m.OPDS1,m.OPDS1_ENTRY,m.OPDS2,m.OPDS2_PUBLICATION,m.OPDS_AUTHENTICATION)||this.structuredSyntaxSuffix==="+json"}get isHTML(){return this.matchesAny(m.HTML,m.XHTML)}get isBitmap(){return this.matchesAny(m.BMP,m.GIF,m.JPEG,m.PNG,m.TIFF,m.WEBP)}get isAudio(){return this.type==="audio"}get isVideo(){return this.type==="video"}get isRWPM(){return this.matchesAny(m.READIUM_AUDIOBOOK_MANIFEST,m.DIVINA_MANIFEST,m.READIUM_WEBPUB_MANIFEST)}get isPublication(){return this.matchesAny(m.READIUM_AUDIOBOOK,m.READIUM_AUDIOBOOK_MANIFEST,m.CBZ,m.DIVINA,m.DIVINA_MANIFEST,m.EPUB,m.LCP_PROTECTED_AUDIOBOOK,m.LCP_PROTECTED_PDF,m.LPF,m.PDF,m.W3C_WPUB_MANIFEST,m.READIUM_WEBPUB,m.READIUM_WEBPUB_MANIFEST,m.ZAB)}static get AAC(){return m.parse({mediaType:"audio/aac",fileExtension:"aac"})}static get ACSM(){return m.parse({mediaType:"application/vnd.adobe.adept+xml",name:"Adobe Content Server Message",fileExtension:"acsm"})}static get AIFF(){return m.parse({mediaType:"audio/aiff",fileExtension:"aiff"})}static get AVI(){return m.parse({mediaType:"video/x-msvideo",fileExtension:"avi"})}static get BINARY(){return m.parse({mediaType:"application/octet-stream"})}static get BMP(){return m.parse({mediaType:"image/bmp",fileExtension:"bmp"})}static get CBZ(){return m.parse({mediaType:"application/vnd.comicbook+zip",name:"Comic Book Archive",fileExtension:"cbz"})}static get CSS(){return m.parse({mediaType:"text/css",fileExtension:"css"})}static get DIVINA(){return m.parse({mediaType:"application/divina+zip",name:"Digital Visual Narratives",fileExtension:"divina"})}static get DIVINA_MANIFEST(){return m.parse({mediaType:"application/divina+json",name:"Digital Visual Narratives",fileExtension:"json"})}static get EPUB(){return m.parse({mediaType:"application/epub+zip",name:"EPUB",fileExtension:"epub"})}static get GIF(){return m.parse({mediaType:"image/gif",fileExtension:"gif"})}static get GZ(){return m.parse({mediaType:"application/gzip",fileExtension:"gz"})}static get HTML(){return m.parse({mediaType:"text/html",fileExtension:"html"})}static get JAVASCRIPT(){return m.parse({mediaType:"text/javascript",fileExtension:"js"})}static get JPEG(){return m.parse({mediaType:"image/jpeg",fileExtension:"jpeg"})}static get JSON(){return m.parse({mediaType:"application/json"})}static get LCP_LICENSE_DOCUMENT(){return m.parse({mediaType:"application/vnd.readium.lcp.license.v1.0+json",name:"LCP License",fileExtension:"lcpl"})}static get LCP_PROTECTED_AUDIOBOOK(){return m.parse({mediaType:"application/audiobook+lcp",name:"LCP Protected Audiobook",fileExtension:"lcpa"})}static get LCP_PROTECTED_PDF(){return m.parse({mediaType:"application/pdf+lcp",name:"LCP Protected PDF",fileExtension:"lcpdf"})}static get LCP_STATUS_DOCUMENT(){return m.parse({mediaType:"application/vnd.readium.license.status.v1.0+json"})}static get LPF(){return m.parse({mediaType:"application/lpf+zip",fileExtension:"lpf"})}static get MP3(){return m.parse({mediaType:"audio/mpeg",fileExtension:"mp3"})}static get MPEG(){return m.parse({mediaType:"video/mpeg",fileExtension:"mpeg"})}static get NCX(){return m.parse({mediaType:"application/x-dtbncx+xml",fileExtension:"ncx"})}static get OGG(){return m.parse({mediaType:"audio/ogg",fileExtension:"oga"})}static get OGV(){return m.parse({mediaType:"video/ogg",fileExtension:"ogv"})}static get OPDS1(){return m.parse({mediaType:"application/atom+xml;profile=opds-catalog"})}static get OPDS1_ENTRY(){return m.parse({mediaType:"application/atom+xml;type=entry;profile=opds-catalog"})}static get OPDS2(){return m.parse({mediaType:"application/opds+json"})}static get OPDS2_PUBLICATION(){return m.parse({mediaType:"application/opds-publication+json"})}static get OPDS_AUTHENTICATION(){return m.parse({mediaType:"application/opds-authentication+json"})}static get OPUS(){return m.parse({mediaType:"audio/opus",fileExtension:"opus"})}static get OTF(){return m.parse({mediaType:"font/otf",fileExtension:"otf"})}static get PDF(){return m.parse({mediaType:"application/pdf",name:"PDF",fileExtension:"pdf"})}static get PNG(){return m.parse({mediaType:"image/png",fileExtension:"png"})}static get READIUM_AUDIOBOOK(){return m.parse({mediaType:"application/audiobook+zip",name:"Readium Audiobook",fileExtension:"audiobook"})}static get READIUM_AUDIOBOOK_MANIFEST(){return m.parse({mediaType:"application/audiobook+json",name:"Readium Audiobook",fileExtension:"json"})}static get READIUM_CONTENT_DOCUMENT(){return m.parse({mediaType:"application/vnd.readium.content+json",name:"Readium Content Document",fileExtension:"json"})}static get READIUM_GUIDED_NAVIGATION_DOCUMENT(){return m.parse({mediaType:"application/guided-navigation+json",name:"Readium Guided Navigation Document",fileExtension:"json"})}static get READIUM_POSITION_LIST(){return m.parse({mediaType:"application/vnd.readium.position-list+json",name:"Readium Position List",fileExtension:"json"})}static get READIUM_WEBPUB(){return m.parse({mediaType:"application/webpub+zip",name:"Readium Web Publication",fileExtension:"webpub"})}static get READIUM_WEBPUB_MANIFEST(){return m.parse({mediaType:"application/webpub+json",name:"Readium Web Publication",fileExtension:"json"})}static get SMIL(){return m.parse({mediaType:"application/smil+xml",fileExtension:"smil"})}static get SVG(){return m.parse({mediaType:"image/svg+xml",fileExtension:"svg"})}static get TEXT(){return m.parse({mediaType:"text/plain",fileExtension:"txt"})}static get TIFF(){return m.parse({mediaType:"image/tiff",fileExtension:"tiff"})}static get TTF(){return m.parse({mediaType:"font/ttf",fileExtension:"ttf"})}static get W3C_WPUB_MANIFEST(){return m.parse({mediaType:"application/x.readium.w3c.wpub+json",name:"Web Publication",fileExtension:"json"})}static get WAV(){return m.parse({mediaType:"audio/wav",fileExtension:"wav"})}static get WEBM_AUDIO(){return m.parse({mediaType:"audio/webm",fileExtension:"webm"})}static get WEBM_VIDEO(){return m.parse({mediaType:"video/webm",fileExtension:"webm"})}static get WEBP(){return m.parse({mediaType:"image/webp",fileExtension:"webp"})}static get WOFF(){return m.parse({mediaType:"font/woff",fileExtension:"woff"})}static get WOFF2(){return m.parse({mediaType:"font/woff2",fileExtension:"woff2"})}static get XHTML(){return m.parse({mediaType:"application/xhtml+xml",fileExtension:"xhtml"})}static get XML(){return m.parse({mediaType:"application/xml",fileExtension:"xml"})}static get ZAB(){return m.parse({mediaType:"application/x.readium.zab+zip",name:"Zipped Audio Book",fileExtension:"zab"})}static get ZIP(){return m.parse({mediaType:"application/zip",fileExtension:"zip"})}}class ti{constructor(t){this.uri=t,this.parameters=this.getParameters(t)}getParameters(t){const e=/\{\??([^}]+)\}/g,i=t.match(e);return i?new Set(i.join(",").replace(e,"$1").split(",").map(A=>A.trim())):new Set}expand(t){const e=A=>A.split(",").map(n=>{const s=t[n];return s?encodeURIComponent(s):""}).join(","),i=A=>"?"+A.split(",").map(n=>{const s=n.split("=")[0],o=t[s];return o?`${s}=${encodeURIComponent(o)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...A)=>A[1]?i(A[2]):e(A[2]))}}class R{constructor(t){this.fragments=t.fragments?t.fragments:new Array,this.progression=t.progression,this.totalProgression=t.totalProgression,this.position=t.position,this.otherLocations=t.otherLocations}static deserialize(t){if(!t)return;const e=bt(t.progression),i=bt(t.totalProgression),A=bt(t.position),n=new Map,s=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(t).forEach(([o,a])=>{s.has(o)||n.set(o,a)}),new R({fragments:_e(t.fragments||t.fragment),progression:e!==void 0&&e>=0&&e<=1?e:void 0,totalProgression:i!==void 0&&i>=0&&i<=1?i:void 0,position:A!==void 0&&A>0?A:void 0,otherLocations:n.size===0?void 0:n})}serialize(){const t={};return this.fragments&&(t.fragments=this.fragments),this.progression!==void 0&&(t.progression=this.progression),this.totalProgression!==void 0&&(t.totalProgression=this.totalProgression),this.position!==void 0&&(t.position=this.position),this.otherLocations&&this.otherLocations.forEach((e,i)=>t[i]=e),t}}class et{constructor(t){this.after=t.after,this.before=t.before,this.highlight=t.highlight}static deserialize(t){if(t)return new et({after:t.after,before:t.before,highlight:t.highlight})}serialize(){const t={};return this.after!==void 0&&(t.after=this.after),this.before!==void 0&&(t.before=this.before),this.highlight!==void 0&&(t.highlight=this.highlight),t}}class Z{constructor(t){this.href=t.href,this.type=t.type,this.title=t.title,this.locations=t.locations?t.locations:new R({}),this.text=t.text}static deserialize(t){if(t&&t.href&&t.type)return new Z({href:t.href,type:t.type,title:t.title,locations:R.deserialize(t.locations),text:et.deserialize(t.text)})}serialize(){const t={href:this.href,type:this.type};return this.title!==void 0&&(t.title=this.title),this.locations&&(t.locations=this.locations.serialize()),this.text&&(t.text=this.text.serialize()),t}copyWithLocations(t){return new Z({href:this.href,type:this.type,title:this.title,text:this.text,locations:new R({...this.locations,...t})})}}class ht{constructor(t){this.href=t.href,this.templated=t.templated,this.type=t.type,this.title=t.title,this.rels=t.rels,this.properties=t.properties,this.height=t.height,this.width=t.width,this.size=t.size,this.duration=t.duration,this.bitrate=t.bitrate,this.languages=t.languages,this.alternates=t.alternates,this.children=t.children}static deserialize(t){if(!(!t||typeof t.href!="string"))return new ht({href:t.href,templated:t.templated,type:t.type,title:t.title,rels:t.rel?Array.isArray(t.rel)?new Set(t.rel):new Set([t.rel]):void 0,properties:T.deserialize(t.properties),height:b(t.height),width:b(t.width),size:b(t.size),duration:b(t.duration),bitrate:b(t.bitrate),languages:_e(t.language),alternates:jt.deserialize(t.alternate),children:jt.deserialize(t.children)})}serialize(){const t={href:this.href};return this.templated!==void 0&&(t.templated=this.templated),this.type!==void 0&&(t.type=this.type),this.title!==void 0&&(t.title=this.title),this.rels&&(t.rel=DA(this.rels)),this.properties&&(t.properties=this.properties.serialize()),this.height!==void 0&&(t.height=this.height),this.width!==void 0&&(t.width=this.width),this.size!==void 0&&(t.size=this.size),this.duration!==void 0&&(t.duration=this.duration),this.bitrate!==void 0&&(t.bitrate=this.bitrate),this.languages&&(t.language=this.languages),this.alternates&&(t.alternate=this.alternates.serialize()),this.children&&(t.children=this.children.serialize()),t}get mediaType(){return this.type!==void 0?m.parse({mediaType:this.type}):m.BINARY}toURL(t){const e=this.href.replace(/^(\/)/,"");if(e.length===0)return;let i=t||"/";return i.startsWith("/")&&(i="file://"+i),new URL(e,i).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new ti(this.href).parameters:new Set}expandTemplate(t){return new ht({href:new ti(this.href).expand(t),templated:!1})}addProperties(t){const e=ht.deserialize(this.serialize());return e.properties=e.properties?e.properties?.add(t):new T(t),e}get locator(){let t=this.href.split("#");return new Z({href:t.length>0&&t[0]!==void 0?t[0]:this.href,type:this.type??"",title:this.title,locations:new R({fragments:t.length>1&&t[1]!==void 0?[t[1]]:[]})})}}class jt{constructor(t){this.items=t}static deserialize(t){if(t&&Array.isArray(t))return new jt(t.map(e=>ht.deserialize(e)).filter(e=>e!==void 0))}serialize(){return this.items.map(t=>t.serialize())}findWithRel(t){const e=i=>i.rels&&i.rels.has(t);return this.items.find(e)}filterByRel(t){const e=i=>i.rels&&i.rels.has(t);return this.items.filter(e)}findWithHref(t){const e=i=>i.href===t;return this.items.find(e)}findIndexWithHref(t){const e=i=>i.href===t;return this.items.findIndex(e)}findWithMediaType(t){const e=i=>i.mediaType.matches(t);return this.items.find(e)}filterByMediaType(t){const e=i=>i.mediaType.matches(t);return this.items.filter(e)}filterByMediaTypes(t){const e=i=>{for(const A of t)if(i.mediaType.matches(A))return!0;return!1};return this.items.filter(e)}everyIsAudio(){const t=e=>e.mediaType.isAudio;return this.items.length>0&&this.items.every(t)}everyIsBitmap(){const t=e=>e.mediaType.isBitmap;return this.items.length>0&&this.items.every(t)}everyIsHTML(){const t=e=>e.mediaType.isHTML;return this.items.length>0&&this.items.every(t)}everyIsVideo(){const t=e=>e.mediaType.isVideo;return this.items.length>0&&this.items.every(t)}everyMatchesMediaType(t){return Array.isArray(t)?this.items.length>0&&this.items.every(e=>{for(const i of t)return e.mediaType.matches(i);return!1}):this.items.length>0&&this.items.every(e=>e.mediaType.matches(t))}filterLinksHasType(){return this.items.filter(t=>t.type)}}T.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])};class Vt{constructor(t){this.cssSelector=t.cssSelector,this.textNodeIndex=t.textNodeIndex,this.charOffset=t.charOffset}static deserialize(t){if(!(t&&t.cssSelector))return;let e=b(t.textNodeIndex);if(e===void 0)return;let i=b(t.charOffset);return i===void 0&&(i=b(t.offset)),new Vt({cssSelector:t.cssSelector,textNodeIndex:e,charOffset:i})}serialize(){const t={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(t.charOffset=this.charOffset),t}}class he{constructor(t){this.start=t.start,this.end=t.end}static deserialize(t){if(!t)return;let e=Vt.deserialize(t.start);if(e)return new he({start:e,end:Vt.deserialize(t.end)})}serialize(){const t={start:this.start.serialize()};return this.end&&(t.end=this.end.serialize()),t}}R.prototype.getCssSelector=function(){return this.otherLocations?.get("cssSelector")},R.prototype.getPartialCfi=function(){return this.otherLocations?.get("partialCfi")},R.prototype.getDomRange=function(){return he.deserialize(this.otherLocations?.get("domRange"))},R.prototype.fragmentParameters=function(){return new Map(this.fragments.map(r=>r.startsWith("#")?r.slice(1):r).join("&").split("&").filter(r=>!r.startsWith("#")).map(r=>r.split("=")).filter(r=>r.length===2).map(r=>[r[0].trim().toLowerCase(),r[1].trim()]))},R.prototype.htmlId=function(){if(!this.fragments.length)return;let r=this.fragments.find(t=>t.length&&!t.includes("="));if(!r){const t=this.fragmentParameters();t.has("id")?r=t.get("id"):t.has("name")&&(r=t.get("name"))}return r?.startsWith("#")?r.slice(1):r},R.prototype.page=function(){const r=parseInt(this.fragmentParameters().get("page"));if(!isNaN(r)&&r>=0)return r},R.prototype.time=function(){const r=parseInt(this.fragmentParameters().get("t"));if(!isNaN(r))return r},R.prototype.space=function(){const r=this.fragmentParameters();if(!r.has("xywh"))return;const t=r.get("xywh").split(",").map(e=>parseInt(e));if(t.length===4&&!t.some(isNaN))return t};class ce{constructor(t){this.currency=t.currency,this.value=t.value}static deserialize(t){if(!t)return;let e=t.currency;if(!(e&&typeof e=="string"&&e.length>0))return;let i=b(t.value);if(i!==void 0)return new ce({currency:e,value:i})}serialize(){return{currency:this.currency,value:this.value}}}class Et{constructor(t){this.type=t.type,this.children=t.children}static deserialize(t){if(t&&t.type)return new Et({type:t.type,children:Et.deserializeArray(t.children)})}static deserializeArray(t){if(Array.isArray(t))return t.map(e=>Et.deserialize(e)).filter(e=>e!==void 0)}serialize(){const t={type:this.type};return this.children&&(t.children=this.children.map(e=>e.serialize())),t}}class ge{constructor(t){this.total=t.total,this.position=t.position}static deserialize(t){if(t)return new ge({total:b(t.total),position:b(t.position)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.position!==void 0&&(t.position=this.position),t}}class de{constructor(t){this.total=t.total,this.available=t.available}static deserialize(t){if(t)return new de({total:b(t.total),available:b(t.available)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.available!==void 0&&(t.available=this.available),t}}class ue{constructor(t){this.state=t.state,this.since=t.since,this.until=t.until}static deserialize(t){if(t&&t.state)return new ue({state:t.state,since:$e(t.since),until:$e(t.until)})}serialize(){const t={state:this.state};return this.since!==void 0&&(t.since=this.since.toISOString()),this.until!==void 0&&(t.until=this.until.toISOString()),t}}T.prototype.getNumberOfItems=function(){return b(this.otherProperties.numberOfItems)},T.prototype.getPrice=function(){return ce.deserialize(this.otherProperties.price)},T.prototype.getIndirectAcquisitions=function(){const r=this.otherProperties.indirectAcquisition;if(r&&Array.isArray(r))return r.map(t=>Et.deserialize(t)).filter(t=>t!==void 0)},T.prototype.getHolds=function(){return ge.deserialize(this.otherProperties.holds)},T.prototype.getCopies=function(){return de.deserialize(this.otherProperties.copies)},T.prototype.getAvailability=function(){return ue.deserialize(this.otherProperties.availability)},T.prototype.getAuthenticate=function(){return ht.deserialize(this.otherProperties.authenticate)};const HA="CssSelectorGenerator";function ei(r="unknown problem",...t){console.warn(`${HA}: ${r}`,...t)}function GA(r){return r instanceof RegExp}function kA(r){return r.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function JA(r){const t=r.map(e=>{if(GA(e))return i=>e.test(i);if(typeof e=="function")return i=>{const A=e(i);return typeof A!="boolean"?(ei("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",e),!1):A};if(typeof e=="string"){const i=new RegExp("^"+kA(e)+"$");return A=>i.test(A)}return ei("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",e),()=>!1});return e=>t.some(i=>i(e))}JA(["class","id","ng-*"]);class It{}function ii(r){return r.split("").reverse().join("")}function WA(r,t,e){const i=ii(t);return e.map(A=>{const n=Math.max(0,A.end-t.length-A.errors),s=ii(r.slice(n,A.end));return{start:ni(s,i,A.errors).reduce((o,a)=>A.end-a.end<o?A.end-a.end:o,A.end),end:A.end,errors:A.errors}})}function me(r){return(r|-r)>>31&1}function Ai(r,t,e,i){let A=r.P[e],n=r.M[e];const s=i>>>31,o=t[e]|s,a=o|n,h=(o&A)+A^A|o;let c=n|~(h|A),g=A&h;const u=me(c&r.lastRowMask[e])-me(g&r.lastRowMask[e]);return c<<=1,g<<=1,g|=s,c|=me(i)-s,A=g|~(a|c),n=c&a,r.P[e]=A,r.M[e]=n,u}function ni(r,t,e){if(t.length===0)return[];e=Math.min(e,t.length);const i=[],A=32,n=Math.ceil(t.length/A)-1,s={P:new Uint32Array(n+1),M:new Uint32Array(n+1),lastRowMask:new Uint32Array(n+1)};s.lastRowMask.fill(1<<31),s.lastRowMask[n]=1<<(t.length-1)%A;const o=new Uint32Array(n+1),a=new Map,h=[];for(let u=0;u<256;u++)h.push(o);for(let u=0;u<t.length;u+=1){const M=t.charCodeAt(u);if(a.has(M))continue;const l=new Uint32Array(n+1);a.set(M,l),M<h.length&&(h[M]=l);for(let f=0;f<=n;f+=1){l[f]=0;for(let E=0;E<A;E+=1){const F=f*A+E;F>=t.length||t.charCodeAt(F)===M&&(l[f]|=1<<E)}}}let c=Math.max(0,Math.ceil(e/A)-1);const g=new Uint32Array(n+1);for(let u=0;u<=c;u+=1)g[u]=(u+1)*A;g[n]=t.length;for(let u=0;u<=c;u+=1)s.P[u]=-1,s.M[u]=0;for(let u=0;u<r.length;u+=1){const M=r.charCodeAt(u);let l;M<h.length?l=h[M]:(l=a.get(M),typeof l>"u"&&(l=o));let f=0;for(let E=0;E<=c;E+=1)f=Ai(s,l,E,f),g[E]+=f;if(g[c]-f<=e&&c<n&&(l[c+1]&1||f<0)){c+=1,s.P[c]=-1,s.M[c]=0;let E;if(c===n){const F=t.length%A;E=F===0?A:F}else E=A;g[c]=g[c-1]+E-f+Ai(s,l,c,f)}else for(;c>0&&g[c]>=e+A;)c-=1;c===n&&g[c]<=e&&(g[c]<e&&i.splice(0,i.length),i.push({start:-1,end:u+1,errors:g[c]}),e=g[c])}return i}function LA(r,t,e){const i=ni(r,t,e);return WA(r,t,i)}function ri(r,t,e){let i=0;const A=[];for(;i!==-1;)i=r.indexOf(t,i),i!==-1&&(A.push({start:i,end:i+t.length,errors:0}),i+=1);return A.length>0?A:LA(r,t,e)}function si(r,t){return t.length===0||r.length===0?0:1-ri(r,t,t.length)[0].errors/t.length}function OA(r,t,e={}){if(t.length===0)return null;const i=Math.min(256,t.length/2),A=ri(r,t,i);if(A.length===0)return null;const n=o=>{const a=1-o.errors/t.length,h=e.prefix?si(r.slice(Math.max(0,o.start-e.prefix.length),o.start),e.prefix):1,c=e.suffix?si(r.slice(o.end,o.end+e.suffix.length),e.suffix):1;let g=1;return typeof e.hint=="number"&&(g=1-Math.abs(o.start-e.hint)/r.length),(50*a+20*h+20*c+2*g)/92},s=A.map(o=>({start:o.start,end:o.end,score:n(o)}));return s.sort((o,a)=>a.score-o.score),s[0]}function fe(r,t,e){const i=e===1?t:t-1;if(r.charAt(i).trim()!=="")return t;let A,n;if(e===2?(A=r.substring(0,t),n=A.trimEnd()):(A=r.substring(t),n=A.trimStart()),!n.length)return-1;const s=A.length-n.length;return e===2?t-s:t+s}function oi(r,t){const e=r.commonAncestorContainer.ownerDocument.createNodeIterator(r.commonAncestorContainer,NodeFilter.SHOW_TEXT),i=t===1?r.startContainer:r.endContainer,A=t===1?r.endContainer:r.startContainer;let n=e.nextNode();for(;n&&n!==i;)n=e.nextNode();t===2&&(n=e.previousNode());let s=-1;const o=()=>{if(n=t===1?e.nextNode():e.previousNode(),n){const a=n.textContent,h=t===1?0:a.length;s=fe(a,h,t)}};for(;n&&s===-1&&n!==A;)o();if(n&&s>=0)return{node:n,offset:s};throw new RangeError("No text nodes with non-whitespace text found in range")}function XA(r){if(!r.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(r.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(r.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const t=r.cloneRange();let e=!1,i=!1;const A={start:fe(r.startContainer.textContent,r.startOffset,1),end:fe(r.endContainer.textContent,r.endOffset,2)};if(A.start>=0&&(t.setStart(r.startContainer,A.start),e=!0),A.end>0&&(t.setEnd(r.endContainer,A.end),i=!0),e&&i)return t;if(!e){const{node:n,offset:s}=oi(t,1);n&&s>=0&&t.setStart(n,s)}if(!i){const{node:n,offset:s}=oi(t,2);n&&s>0&&t.setEnd(n,s)}return t}function ai(r){switch(r.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return r.textContent?.length??0;default:return 0}}function li(r){let t=r.previousSibling,e=0;for(;t;)e+=ai(t),t=t.previousSibling;return e}function hi(r,...t){let e=t.shift();const i=r.ownerDocument.createNodeIterator(r,NodeFilter.SHOW_TEXT),A=[];let n=i.nextNode(),s,o=0;for(;e!==void 0&&n;)s=n,o+s.data.length>e?(A.push({node:s,offset:e-o}),e=t.shift()):(n=i.nextNode(),o+=s.data.length);for(;e!==void 0&&s&&o===e;)A.push({node:s,offset:s.data.length}),e=t.shift();if(e!==void 0)throw new RangeError("Offset exceeds text length");return A}class L{constructor(t,e){if(e<0)throw new Error("Offset is invalid");this.element=t,this.offset=e}relativeTo(t){if(!t.contains(this.element))throw new Error("Parent is not an ancestor of current element");let e=this.element,i=this.offset;for(;e!==t;)i+=li(e),e=e.parentElement;return new L(e,i)}resolve(t={}){try{return hi(this.element,this.offset)[0]}catch(e){if(this.offset===0&&t.direction!==void 0){const i=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);i.currentNode=this.element;const A=t.direction===1,n=A?i.nextNode():i.previousNode();if(!n)throw e;return{node:n,offset:A?0:n.data.length}}else throw e}}static fromCharOffset(t,e){switch(t.nodeType){case Node.TEXT_NODE:return L.fromPoint(t,e);case Node.ELEMENT_NODE:return new L(t,e);default:throw new Error("Node is not an element or text node")}}static fromPoint(t,e){switch(t.nodeType){case Node.TEXT_NODE:{if(e<0||e>t.data.length)throw new Error("Text node offset is out of range");if(!t.parentElement)throw new Error("Text node has no parent");const i=li(t)+e;return new L(t.parentElement,i)}case Node.ELEMENT_NODE:{if(e<0||e>t.childNodes.length)throw new Error("Child node offset is out of range");let i=0;for(let A=0;A<e;A++)i+=ai(t.childNodes[A]);return new L(t,i)}default:throw new Error("Point is not in an element or text node")}}}class _{constructor(t,e){this.start=t,this.end=e}relativeTo(t){return new _(this.start.relativeTo(t),this.end.relativeTo(t))}toRange(){let t,e;this.start.element===this.end.element&&this.start.offset<=this.end.offset?[t,e]=hi(this.start.element,this.start.offset,this.end.offset):(t=this.start.resolve({direction:1}),e=this.end.resolve({direction:2}));const i=new Range;return i.setStart(t.node,t.offset),i.setEnd(e.node,e.offset),i}static fromRange(t){const e=L.fromPoint(t.startContainer,t.startOffset),i=L.fromPoint(t.endContainer,t.endOffset);return new _(e,i)}static fromOffsets(t,e,i){return new _(new L(t,e),new L(t,i))}static trimmedRange(t){return XA(_.fromRange(t).toRange())}}class Pt{constructor(t,e,i){this.root=t,this.start=e,this.end=i}static fromRange(t,e){const i=_.fromRange(e).relativeTo(t);return new Pt(t,i.start.offset,i.end.offset)}static fromSelector(t,e){return new Pt(t,e.start,e.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return _.fromOffsets(this.root,this.start,this.end).toRange()}}class vt{constructor(t,e,i={}){this.root=t,this.exact=e,this.context=i}static fromRange(t,e){const i=t.textContent,A=_.fromRange(e).relativeTo(t),n=A.start.offset,s=A.end.offset,o=32;return new vt(t,i.slice(n,s),{prefix:i.slice(Math.max(0,n-o),n),suffix:i.slice(s,Math.min(i.length,s+o))})}static fromSelector(t,e){const{prefix:i,suffix:A}=e;return new vt(t,e.exact,{prefix:i,suffix:A})}toSelector(){return{type:"TextQuoteSelector",exact:this.exact,prefix:this.context.prefix,suffix:this.context.suffix}}toRange(t={}){return this.toPositionAnchor(t).toRange()}toPositionAnchor(t={}){const e=this.root.textContent,i=OA(e,this.exact,{...this.context,hint:t.hint});if(!i)throw new Error("Quote not found");return new Pt(this.root,i.start,i.end)}}function ZA(r){const t=r.tagName.toUpperCase();return t==="IMG"||t==="VIDEO"||t==="AUDIO"||t==="IFRAME"||t==="OBJECT"||t==="EMBED"||t==="CANVAS"}function Dt(r,t){try{const e=t.locations,i=t.text;if(i&&i.highlight){let A;e&&e.getCssSelector()&&(A=r.querySelector(e.getCssSelector())),A||(A=r.body);const n=new vt(A,i.highlight,{prefix:i.before,suffix:i.after});try{return n.toRange()}catch{return console.warn("Quote not found:",n),null}}if(e){let A=null;if(!A&&e.getCssSelector()&&(A=r.querySelector(e.getCssSelector())),!A&&e.fragments){for(const n of e.fragments)if(A=r.getElementById(n),A)break}if(A){const n=r.createRange();return A.childNodes.length===0||ZA(A)?(n.selectNode(A),n):(n.setStartBefore(A),n.setEndAfter(A),n)}}}catch(e){console.error(e)}return null}function KA(r,t){let e=r.getClientRects();e.length||r.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(e=r.commonAncestorContainer.getClientRects());const i=1,A=[];for(const h of e)A.push({bottom:h.bottom,height:h.height,left:h.left,right:h.right,top:h.top,width:h.width});const n=ci(A,i),s=_A(n,i),o=gi(s),a=4;for(let h=o.length-1;h>=0;h--){const c=o[h];if(!(c.width*c.height>a))if(o.length>1)o.splice(h,1);else break}return o}function ci(r,t,e){for(let i=0;i<r.length;i++)for(let A=i+1;A<r.length;A++){const n=r[i],s=r[A];if(n===s)continue;const o=v(n.top,s.top,t)&&v(n.bottom,s.bottom,t),a=v(n.left,s.left,t)&&v(n.right,s.right,t);if(o&&!a&&ui(n,s,t)){const h=r.filter(g=>g!==n&&g!==s),c=qA(n,s);return h.push(c),ci(h,t)}}return r}function qA(r,t){const e=Math.min(r.left,t.left),i=Math.max(r.right,t.right),A=Math.min(r.top,t.top),n=Math.max(r.bottom,t.bottom);return{bottom:n,height:n-A,left:e,right:i,top:A,width:i-e}}function _A(r,t){const e=new Set(r);for(const i of r){if(!(i.width>1&&i.height>1)){e.delete(i);continue}for(const A of r)if(i!==A&&e.has(A)&&$A(A,i,t)){e.delete(i);break}}return Array.from(e)}function $A(r,t,e){return Ht(r,t.left,t.top,e)&&Ht(r,t.right,t.top,e)&&Ht(r,t.left,t.bottom,e)&&Ht(r,t.right,t.bottom,e)}function Ht(r,t,e,i){return(r.left<t||v(r.left,t,i))&&(r.right>t||v(r.right,t,i))&&(r.top<e||v(r.top,e,i))&&(r.bottom>e||v(r.bottom,e,i))}function gi(r){for(let t=0;t<r.length;t++)for(let e=t+1;e<r.length;e++){const i=r[t],A=r[e];if(i!==A&&ui(i,A,-1)){let n=[],s;const o=di(i,A);if(o.length===1)n=o,s=i;else{const h=di(A,i);o.length<h.length?(n=o,s=i):(n=h,s=A)}const a=r.filter(h=>h!==s);return Array.prototype.push.apply(a,n),gi(a)}}return r}function di(r,t){const e=tn(t,r);if(e.height===0||e.width===0)return[r];const i=[];{const A={bottom:r.bottom,height:0,left:r.left,right:e.left,top:r.top,width:0};A.width=A.right-A.left,A.height=A.bottom-A.top,A.height!==0&&A.width!==0&&i.push(A)}{const A={bottom:e.top,height:0,left:e.left,right:e.right,top:r.top,width:0};A.width=A.right-A.left,A.height=A.bottom-A.top,A.height!==0&&A.width!==0&&i.push(A)}{const A={bottom:r.bottom,height:0,left:e.left,right:e.right,top:e.bottom,width:0};A.width=A.right-A.left,A.height=A.bottom-A.top,A.height!==0&&A.width!==0&&i.push(A)}{const A={bottom:r.bottom,height:0,left:e.right,right:r.right,top:r.top,width:0};A.width=A.right-A.left,A.height=A.bottom-A.top,A.height!==0&&A.width!==0&&i.push(A)}return i}function tn(r,t){const e=Math.max(r.left,t.left),i=Math.min(r.right,t.right),A=Math.max(r.top,t.top),n=Math.min(r.bottom,t.bottom);return{bottom:n,height:Math.max(0,n-A),left:e,right:i,top:A,width:Math.max(0,i-e)}}function ui(r,t,e){return(r.left<t.right||e>=0&&v(r.left,t.right,e))&&(t.left<r.right||e>=0&&v(t.left,r.right,e))&&(r.top<t.bottom||e>=0&&v(r.top,t.bottom,e))&&(t.top<r.bottom||e>=0&&v(t.top,r.bottom,e))}function v(r,t,e){return Math.abs(r-t)<=e}function pe(r){const t={},e=r.document.documentElement.style;for(const i in r.document.documentElement.style)Object.hasOwn(e,i)&&!Number.isNaN(Number.parseInt(i))&&(t[e[i]]=e.getPropertyValue(e[i]));return t}function mi(r,t){const e=pe(r);Object.keys(e).forEach(i=>{t.hasOwnProperty(i)||Gt(r,i)}),Object.entries(t).forEach(([i,A])=>{e[i]!==A&&Ft(r,i,A)})}function fi(r,t){return r.document.documentElement.style.getPropertyValue(t)}function Ft(r,t,e){r.document.documentElement.style.setProperty(t,e)}function Gt(r,t){r.document.documentElement.style.removeProperty(t)}const en=r=>{if(r.startsWith("rgb")){const t=r.match(/rgb\((\d+),\s(\d+),\s(\d+)(?:,\s(\d+))?\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?parseInt(t[4],10)/255:1}}else if(r.startsWith("#")){const t=r.slice(1);if(t.length===3||t.length===4)return{r:parseInt(t[0]+t[0],16)/255,g:parseInt(t[1]+t[1],16)/255,b:parseInt(t[2]+t[2],16)/255,a:t.length===4?parseInt(t[3]+t[3],16)/255:1};if(t.length===6||t.length===8)return{r:parseInt(t[0]+t[1],16)/255,g:parseInt(t[2]+t[3],16)/255,b:parseInt(t[4]+t[5],16)/255,a:t.length===8?parseInt(t[6]+t[7],16)/255:1}}return{r:0,g:0,b:0,a:1}},An=r=>.2126*r.r*r.a+.7152*r.g*r.a+.0722*r.b*r.a,nn=r=>{const t=en(r);return An(t)<128},rn=()=>"Highlight"in window,pi=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class sn{constructor(t,e,i,A){this.wnd=t,this.comms=e,this.id=i,this.name=A,this.items=[],this.lastItemId=0,this.container=void 0,this.activateable=!1,this.experimentalHighlights=!1,this.currentRender=0,rn()&&(this.experimentalHighlights=!0,this.notTextFlag=new Map)}get activeable(){return this.activateable}set activeable(t){this.activateable=t}add(t){const e=`${this.id}-${this.lastItemId++}`,i=Dt(this.wnd.document,t.locator);if(!i){this.comms.log("Can't locate DOM range for decoration",t);return}const A=i.commonAncestorContainer;A.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&(pi.includes(A.nodeName.toUpperCase())&&this.notTextFlag?.set(e,!0),A.querySelector(pi.join(", ").toLowerCase())&&this.notTextFlag?.set(e,!0),(A.textContent?.trim()||"").length===0&&this.notTextFlag?.set(e,!0));const n={decoration:t,id:e,range:i};this.items.push(n),this.layout(n),this.renderLayout([n])}remove(t){const e=this.items.findIndex(A=>A.decoration.id===t);if(e<0)return;const i=this.items[e];this.items.splice(e,1),i.clickableElements=void 0,i.container&&(i.container.remove(),i.container=void 0),this.experimentalHighlights&&!this.notTextFlag?.has(i.id)&&this.wnd.CSS.highlights.get(this.id)?.delete(i.range),this.notTextFlag?.delete(i.id)}update(t){this.remove(t.id),this.add(t)}clear(){this.clearContainer(),this.items.length=0,this.notTextFlag?.clear()}requestLayout(){this.wnd.cancelAnimationFrame(this.currentRender),this.clearContainer(),this.items.forEach(t=>this.layout(t)),this.renderLayout(this.items)}experimentalLayout(t){const[e,i]=this.requireContainer(!0);i.add(t.range),e.innerHTML=`
|
|
217
217
|
::highlight(${this.id}) {
|
|
218
218
|
color: black;
|
|
219
219
|
background-color: ${t.decoration?.style?.tint??"yellow"};
|
|
@@ -223,11 +223,11 @@ if(window.onload) window.onload = new Proxy(window.onload, {
|
|
|
223
223
|
style="${[`background-color: ${t.decoration?.style?.tint??"yellow"} !important`,`mix-blend-mode: ${u?"exclusion":"multiply"} !important`,"opacity: 1 !important","box-sizing: border-box !important"].join("; ")}"
|
|
224
224
|
>
|
|
225
225
|
</div>
|
|
226
|
-
`.trim();const M=g.content.firstElementChild;if(t.decoration?.style?.layout==="bounds"){const l=M.cloneNode(!0);l.style.setProperty("pointer-events","none"),h(l,c,c),e.append(l)}else{let l=KA(t.range);l=l.sort((f,E)=>f.top<E.top?-1:f.top>E.top?1:0);for(let f of l){const E=M.cloneNode(!0);E.style.setProperty("pointer-events","none"),h(E,f,c),e.append(E)}}t.container=e,t.clickableElements=Array.from(e.querySelectorAll("[data-activable='1']")),t.clickableElements.length||(t.clickableElements=Array.from(e.children))}renderLayout(t){this.wnd.cancelAnimationFrame(this.currentRender),this.currentRender=this.wnd.requestAnimationFrame(()=>{t=t.filter(e=>!this.experimentalHighlights||!!this.notTextFlag?.has(e.id)),!(!t||t.length===0)&&this.requireContainer().append(...t.map(e=>e.container).filter(e=>!!e))})}requireContainer(t=!1){if(t){let e;this.wnd.document.getElementById(`${this.id}-style`)?e=this.wnd.document.getElementById(`${this.id}-style`):(e=this.wnd.document.createElement("style"),e.dataset.readium="true",e.id=`${this.id}-style`,this.wnd.document.head.appendChild(e));let i;return this.wnd.CSS.highlights.has(this.id)?i=this.wnd.CSS.highlights.get(this.id):(i=new this.wnd.Highlight,this.wnd.CSS.highlights.set(this.id,i)),[e,i]}return this.container||(this.container=this.wnd.document.createElement("div"),this.container.setAttribute("id",this.id),this.container.dataset.group=this.name,this.container.dataset.readium="true",this.container.style.setProperty("pointer-events","none"),this.container.style.display="contents",this.wnd.document.body.append(this.container)),this.container}clearContainer(){this.experimentalHighlights&&this.wnd.CSS.highlights.delete(this.id),this.container&&(this.container.remove(),this.container=void 0)}}const Mi=class
|
|
226
|
+
`.trim();const M=g.content.firstElementChild;if(t.decoration?.style?.layout==="bounds"){const l=M.cloneNode(!0);l.style.setProperty("pointer-events","none"),h(l,c,c),e.append(l)}else{let l=KA(t.range);l=l.sort((f,E)=>f.top<E.top?-1:f.top>E.top?1:0);for(let f of l){const E=M.cloneNode(!0);E.style.setProperty("pointer-events","none"),h(E,f,c),e.append(E)}}t.container=e,t.clickableElements=Array.from(e.querySelectorAll("[data-activable='1']")),t.clickableElements.length||(t.clickableElements=Array.from(e.children))}renderLayout(t){this.wnd.cancelAnimationFrame(this.currentRender),this.currentRender=this.wnd.requestAnimationFrame(()=>{t=t.filter(e=>!this.experimentalHighlights||!!this.notTextFlag?.has(e.id)),!(!t||t.length===0)&&this.requireContainer().append(...t.map(e=>e.container).filter(e=>!!e))})}requireContainer(t=!1){if(t){let e;this.wnd.document.getElementById(`${this.id}-style`)?e=this.wnd.document.getElementById(`${this.id}-style`):(e=this.wnd.document.createElement("style"),e.dataset.readium="true",e.id=`${this.id}-style`,this.wnd.document.head.appendChild(e));let i;return this.wnd.CSS.highlights.has(this.id)?i=this.wnd.CSS.highlights.get(this.id):(i=new this.wnd.Highlight,this.wnd.CSS.highlights.set(this.id,i)),[e,i]}return this.container||(this.container=this.wnd.document.createElement("div"),this.container.setAttribute("id",this.id),this.container.dataset.group=this.name,this.container.dataset.readium="true",this.container.style.setProperty("pointer-events","none"),this.container.style.display="contents",this.wnd.document.body.append(this.container)),this.container}clearContainer(){this.experimentalHighlights&&this.wnd.CSS.highlights.delete(this.id),this.container&&(this.container.remove(),this.container=void 0)}}const Mi=class je extends It{constructor(){super(...arguments),this.resizeFrame=0,this.lastGroupId=0,this.groups=new Map,this.handleResizer=this.handleResize.bind(this)}cleanup(){this.groups.forEach(t=>t.clear()),this.groups.clear()}handleResize(){this.wnd.clearTimeout(this.resizeFrame),this.resizeFrame=this.wnd.setTimeout(()=>{this.groups.forEach(t=>{t.experimentalHighlights||t.requestLayout()})},50)}mount(t,e){return this.wnd=t,e.register("decorate",je.moduleName,(i,A)=>{const n=i;n.decoration&&n.decoration.locator&&(n.decoration.locator=Z.deserialize(n.decoration.locator)),this.groups.has(n.group)||this.groups.set(n.group,new sn(t,e,`readium-decoration-${this.lastGroupId++}`,n.group));const s=this.groups.get(n.group);switch(n.action){case"add":s?.add(n.decoration);break;case"remove":s?.remove(n.decoration.id);break;case"clear":s?.clear();break;case"update":s?.update(n.decoration);break}A(!0)}),this.resizeObserver=new ResizeObserver(()=>t.requestAnimationFrame(()=>this.handleResize())),this.resizeObserver.observe(t.document.body),t.addEventListener("orientationchange",this.handleResizer),t.addEventListener("resize",this.handleResizer),e.log("Decorator Mounted"),!0}unmount(t,e){return t.removeEventListener("orientationchange",this.handleResizer),t.removeEventListener("resize",this.handleResizer),e.unregisterAll(je.moduleName),this.resizeObserver.disconnect(),this.cleanup(),e.log("Decorator Unmounted"),!0}};Mi.moduleName="decorator";let on=Mi;const Bi="readium-snapper-style",wi=class Ve extends It{constructor(){super(...arguments),this.protected=!1}buildStyles(){return`
|
|
227
227
|
html, body {
|
|
228
228
|
touch-action: manipulation;
|
|
229
229
|
user-select: ${this.protected?"none":"auto"};
|
|
230
|
-
}`}mount(t,e){const i=t.document.createElement("style");return i.dataset.readium="true",i.id=Bi,i.textContent=this.buildStyles(),t.document.head.appendChild(i),e.register("protect",
|
|
230
|
+
}`}mount(t,e){const i=t.document.createElement("style");return i.dataset.readium="true",i.id=Bi,i.textContent=this.buildStyles(),t.document.head.appendChild(i),e.register("protect",Ve.moduleName,(A,n)=>{this.protected=!0,i.textContent=this.buildStyles(),n(!0)}),e.register("unprotect",Ve.moduleName,(A,n)=>{this.protected=!1,i.textContent=this.buildStyles(),n(!0)}),e.log("Snapper Mounted"),!0}unmount(t,e){return t.document.getElementById(Bi)?.remove(),e.log("Snapper Unmounted"),!0}};wi.moduleName="snapper";let Me=wi;function it(r){return r.document.body.dir.toLowerCase()==="rtl"}function Ei(r){return parseInt(r.getComputedStyle(r.document.documentElement).getPropertyValue("column-count"))}function an(r){const t=getComputedStyle(r),e=parseFloat(t.paddingTop||"0"),i=parseFloat(t.paddingBottom||"0");return r.clientHeight-e-i}function Ii(r){const t=Ei(r);if(!t)return!1;const e=r.document.querySelectorAll("div[id^='readium-virtual-page']");for(const a of e)a.remove();const i=e.length,A=r.document.scrollingElement.scrollWidth,n=r.visualViewport.width,s=Math.round(A/n*t)%t,o=t===1||s===0?0:t-s;if(o>0)for(let a=0;a<o;a++){const h=r.document.createElement("div");h.setAttribute("id",`readium-virtual-page-${a}`),h.dataset.readium="true",CSS.supports("break-before","column")?h.style.breakBefore="column":(CSS.supports("break-inside","avoid-column")&&(h.style.breakInside="avoid-column"),h.style.height=an(r.document.documentElement)+"px"),h.innerHTML="​",r.document.body.appendChild(h)}return i!==o}function Fi(r){const t=r.document.createElement("style");t.appendChild(r.document.createTextNode("*{}")),r.document.body.appendChild(t),r.document.body.removeChild(t)}function ln(r){return r<.5?2*r*r:-1+(4-2*r)*r}function C(r){const t=r.getSelection();t&&t.removeAllRanges()}const hn=["a","audio","button","canvas","details","input","label","option","select","submit","textarea","video"];function yi(r){return hn.indexOf(r.nodeName.toLowerCase())!==-1||r.hasAttribute("contenteditable")&&r.getAttribute("contenteditable")?.toLowerCase()!=="false"?r:r.parentElement?yi(r.parentElement):null}function Be(r,t){const e=Ui(r,r.document.body,t),i=r._readium_cssSelectorGenerator.getCssSelector(e,{selectors:["tag","id","class","nthchild","nthoftype","attribute"]});return new Z({href:"#",type:"application/xhtml+xml",locations:new R({otherLocations:new Map([["cssSelector",i]])}),text:new et({highlight:e.textContent||void 0})})}function Ui(r,t,e){for(var i=0;i<t.children.length;i++){const A=t.children[i];if(!dn(A)&&cn(r,A,e))return gn(r,A)?A:Ui(r,A,e)}return t}function cn(r,t,e){if(t===document.body||t===document.documentElement)return!0;if(!document||!document.documentElement||!document.body)return!1;const i=t.getBoundingClientRect();return e?i.bottom>0&&i.top<r.innerHeight:i.right>0&&i.left<r.innerWidth}function gn(r,t){const e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=r.innerHeight&&e.right<=r.innerWidth}function dn(r){const t=getComputedStyle(r);if(t){const e=t.getPropertyValue("display");if(e!="block"&&e!="list-item"||t.getPropertyValue("opacity")==="0")return!0}return!1}const Ri="readium-column-snapper-style",un=200,Ci=class P extends Me{constructor(){super(...arguments),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)}doc(){return this.wnd.document.scrollingElement}scrollOffset(){return this.doc().scrollLeft>0?this.doc().scrollLeft:this.alreadyScrollLeft}snapOffset(t){const e=t+(it(this.wnd)?-1:1);return e-e%this.wnd.innerWidth}reportProgress(){const t=this.wnd.scrollX,e=this.cachedScrollWidth,i=Math.max(0,Math.min(1,t/e)),A=Math.max(0,Math.min(1,(t+this.wnd.innerWidth)/e));this.comms.send("progress",{start:i,end:A})}shake(){if(this.overscroll!==0||this.shakeTimeout!==0)return;const t=this.doc();t.classList.add(it(this.wnd)?"readium-bounce-l":"readium-bounce-r");const e=this.scrollOffset();this.shakeTimeout=this.wnd.setTimeout(()=>{t.classList.remove("readium-bounce-l"),t.classList.remove("readium-bounce-r"),this.shakeTimeout=0,this.doc().scrollLeft=e},150)}takeOverSnap(){this.snappingCancelled=!0,this.clearTouches();const t=this.doc();this.overscroll=t.style.transform?.length>12?parseFloat(t.style.transform.slice(12).split("px")[0]):0}snapCurrentOffset(t=!1,e=!1){const i=this.wnd.scrollX>0?this.wnd.scrollX:this.alreadyScrollLeft,A=this.doc(),n=this.dragOffset(),s=Ei(this.wnd),o=Math.min(Math.max(0,i),this.cachedScrollWidth),a=it(this.wnd)?-1:1,h=a*(this.wnd.innerWidth/3)*(a*n>0?2:1),c=this.snapOffset(o+h);if(t&&c!==this.scrollOffset()){this.snappingCancelled=!1;const g=(f,E,F,S)=>F>S?E:f+(E-f)*ln(F/S),u=un*s;let M;const l=f=>{if(this.snappingCancelled)return;M||(M=f);const E=f-M,F=g(this.overscroll,0,E,u),S=g(i,c,E,u);A.scrollLeft=S,this.overscroll!==0&&(A.style.transform=`translate3d(${-F}px, 0px, 0px)`),E<u?this.wnd.requestAnimationFrame(l):(this.clearTouches(),A.style.removeProperty("transform"),A.scrollLeft=c,e||this.reportProgress())};this.wnd.requestAnimationFrame(l)}else A.style.removeProperty("transform"),this.wnd.requestAnimationFrame(()=>{A.scrollLeft=c,this.clearTouches(),e||this.reportProgress()})}dragOffset(){return(this.startingX??0)-(this.endingX??0)}clearTouches(){this.startingX=void 0,this.endingX=void 0,this.overscroll=0}onTouchStart(t){switch(t.stopPropagation(),this.takeOverSnap(),t.touches.length){case 1:break;case 2:this.onTouchEnd(t);return;default:{this.onTouchEnd(t),this.comms.send("tap_more",t.touches.length);return}}this.startingX=t.touches[0].clientX,this.alreadyScrollLeft=this.doc().scrollLeft,this.touchState=1}onTouchEnd(t){if(this.touchState===2){const e=this.dragOffset(),i=this.scrollOffset();this.cachedScrollWidth<=this.wnd.innerWidth?(this.reportProgress(),e>5&&this.comms.send("no_more",void 0),e<-5&&this.comms.send("no_less",void 0)):i<5&&e<5?(this.alreadyScrollLeft=0,this.comms.send("no_less",void 0)):this.cachedScrollWidth-i-this.wnd.innerWidth<5&&e>5&&(this.alreadyScrollLeft=this.cachedScrollWidth,this.comms.send("no_more",void 0)),this.snapCurrentOffset(!0),this.comms.send("swipe",e)}this.touchState=0}onWidthChange(){this.cachedScrollWidth=this.doc().scrollWidth,this.comms.ready&&this.snapCurrentOffset()}onTouchMove(t){if(this.touchState===0)return;this.touchState===1&&(this.touchState=2,C(this.wnd)),this.endingX=t.touches[0].clientX;const e=this.dragOffset(),i=this.alreadyScrollLeft+e;i<0?(this.overscroll=i,this.doc().style.transform=`translate3d(${-this.overscroll}px, 0px, 0px)`):i+this.wnd.innerWidth>this.cachedScrollWidth?(this.overscroll=i,this.doc().style.transform=`translate3d(${-i}px, 0px, 0px)`):(this.overscroll=0,this.doc().style.removeProperty("transform"),this.doc().scrollLeft=this.alreadyScrollLeft+e)}mount(t,e){if(this.wnd=t,this.comms=e,!super.mount(t,e))return!1;t.navigator.epubReadingSystem&&(t.navigator.epubReadingSystem.layoutStyle="paginated");const i=t.document.createElement("style");i.dataset.readium="true",i.id=Ri,i.textContent=`
|
|
231
231
|
@keyframes readium-bounce-l-animation {
|
|
232
232
|
0%, 100% {transform: translate3d(0, 0, 0);}
|
|
233
233
|
50% {transform: translate3d(-50px, 0, 0);}
|
|
@@ -261,7 +261,7 @@ if(window.onload) window.onload = new Proxy(window.onload, {
|
|
|
261
261
|
body::-webkit-scrollbar {
|
|
262
262
|
display: none; /* for Chrome, Safari, and Opera */
|
|
263
263
|
}
|
|
264
|
-
`,t.document.head.appendChild(i),this.resizeObserver=new ResizeObserver(()=>{t.requestAnimationFrame(()=>{t&&Ii(t)}),this.onWidthChange()}),this.resizeObserver.observe(t.document.body),this.mutationObserver=new MutationObserver(n=>{for(const s of n)if(s.target===this.wnd.document.documentElement){const o=s.oldValue,a=s.target.getAttribute("style"),h=/transform\s*:\s*([^;]+)/,c=o?.match(h),g=a?.match(h);(!c&&!g||c&&!g||c&&g&&c[1]!==g[1])&&(t.requestAnimationFrame(()=>{t&&Ii(t)}),this.onWidthChange())}else t.requestAnimationFrame(()=>this.cachedScrollWidth=this.doc().scrollWidth)}),t.frameElement&&this.mutationObserver.observe(t.frameElement,{attributes:!0,attributeFilter:["style"]}),this.mutationObserver.observe(t.document,{attributes:!0,attributeFilter:["style"]}),this.mutationObserver.observe(t.document.documentElement,{attributes:!0,attributeFilter:["style"]});const A=n=>{const s=this.doc().scrollLeft;return this.doc().scrollLeft=this.snapOffset(n),s!==this.doc().scrollLeft};return t.addEventListener("orientationchange",this.onWidthChanger),t.addEventListener("resize",this.onWidthChanger),t.requestAnimationFrame(()=>this.cachedScrollWidth=this.doc().scrollWidth),e.register("go_progression",P.moduleName,(n,s)=>{const o=n;if(o<0||o>1){e.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),s(!1);return}this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const a=this.cachedScrollWidth,h=
|
|
264
|
+
`,t.document.head.appendChild(i),this.resizeObserver=new ResizeObserver(()=>{t.requestAnimationFrame(()=>{t&&Ii(t)}),this.onWidthChange()}),this.resizeObserver.observe(t.document.body),this.mutationObserver=new MutationObserver(n=>{for(const s of n)if(s.target===this.wnd.document.documentElement){const o=s.oldValue,a=s.target.getAttribute("style"),h=/transform\s*:\s*([^;]+)/,c=o?.match(h),g=a?.match(h);(!c&&!g||c&&!g||c&&g&&c[1]!==g[1])&&(t.requestAnimationFrame(()=>{t&&Ii(t)}),this.onWidthChange())}else t.requestAnimationFrame(()=>this.cachedScrollWidth=this.doc().scrollWidth)}),t.frameElement&&this.mutationObserver.observe(t.frameElement,{attributes:!0,attributeFilter:["style"]}),this.mutationObserver.observe(t.document,{attributes:!0,attributeFilter:["style"]}),this.mutationObserver.observe(t.document.documentElement,{attributes:!0,attributeFilter:["style"]});const A=n=>{const s=this.doc().scrollLeft;return this.doc().scrollLeft=this.snapOffset(n),s!==this.doc().scrollLeft};return t.addEventListener("orientationchange",this.onWidthChanger),t.addEventListener("resize",this.onWidthChanger),t.requestAnimationFrame(()=>this.cachedScrollWidth=this.doc().scrollWidth),e.register("go_progression",P.moduleName,(n,s)=>{const o=n;if(o<0||o>1){e.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),s(!1);return}this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const a=this.cachedScrollWidth,h=it(t)?-1:1,c=a*o*h;this.doc().scrollLeft=this.snapOffset(c),this.reportProgress(),C(this.wnd),s(!0)})}),e.register("go_id",P.moduleName,(n,s)=>{const o=t.document.getElementById(n);if(!o){s(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollLeft=this.snapOffset(o.getBoundingClientRect().left+t.scrollX),this.reportProgress(),C(this.wnd),s(!0)})}),e.register("go_text",P.moduleName,(n,s)=>{let o;Array.isArray(n)&&(n.length>1&&(o=n[1]),n=n[0]);const a=et.deserialize(n),h=Dt(this.wnd.document,new Z({href:t.location.href,type:"text/html",text:a,locations:o?new R({otherLocations:new Map([["cssSelector",o]])}):void 0}));if(!h){s(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollLeft=this.snapOffset(h.getBoundingClientRect().left+t.scrollX),this.reportProgress(),C(this.wnd),s(!0)})}),e.register("go_end",P.moduleName,(n,s)=>{const o=it(t)?-1:1;this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const a=this.cachedScrollWidth*o;if(this.doc().scrollLeft===a)return s(!1);this.doc().scrollLeft=this.snapOffset(a),this.reportProgress(),C(this.wnd),s(!0)})}),e.register("go_start",P.moduleName,(n,s)=>{this.wnd.requestAnimationFrame(()=>{if(this.doc().scrollLeft===0)return s(!1);this.doc().scrollLeft=0,this.reportProgress(),C(this.wnd),s(!0)})}),e.register("go_prev",P.moduleName,(n,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const o=t.scrollX-t.innerWidth,a=it(t)?-(this.cachedScrollWidth-t.innerWidth):0,h=A(Math.max(o,a));h&&(this.reportProgress(),C(this.wnd)),s(h)})}),e.register("go_next",P.moduleName,(n,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const o=t.scrollX+t.innerWidth,a=it(t)?0:this.cachedScrollWidth-t.innerWidth,h=A(Math.min(o,a));h&&(this.reportProgress(),C(this.wnd)),s(h)})}),e.register("unfocus",P.moduleName,(n,s)=>{this.snappingCancelled=!0,C(this.wnd),s(!0)}),e.register("shake",P.moduleName,(n,s)=>{this.shake(),s(!0)}),e.register("focus",P.moduleName,(n,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth,this.snapCurrentOffset(!1,!0),this.reportProgress(),s(!0)})}),e.register("first_visible_locator",P.moduleName,(n,s)=>{const o=Be(t,!1);this.comms.send("first_visible_locator",o.serialize()),s(!0)}),t.addEventListener("touchstart",this.onTouchStarter,{passive:!0}),t.addEventListener("touchend",this.onTouchEnder,{passive:!0}),t.addEventListener("touchmove",this.onTouchMover,{passive:!0}),t.document.addEventListener("touchstart",()=>{}),e.log("ColumnSnapper Mounted"),!0}unmount(t,e){return this.snappingCancelled=!0,e.unregisterAll(P.moduleName),this.resizeObserver.disconnect(),this.mutationObserver.disconnect(),t.removeEventListener("touchstart",this.onTouchStarter),t.removeEventListener("touchend",this.onTouchEnder),t.removeEventListener("touchmove",this.onTouchMover),t.removeEventListener("orientationchange",this.onWidthChanger),t.removeEventListener("resize",this.onWidthChanger),t.document.getElementById(Ri)?.remove(),e.log("ColumnSnapper Unmounted"),super.unmount(t,e)}};Ci.moduleName="column_snapper";let mn=Ci;const Si="readium-scroll-snapper-style",Qi=class D extends Me{constructor(){super(...arguments),this.initialScrollHandled=!1,this.isScrolling=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce=null,this.handleScroll=()=>{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,e=t-this.lastScrollTop;this.lastScrollTop=t,this.comms.send("scroll",e),this.isScrolling=!1}))}}}doc(){return this.wnd.document.scrollingElement}reportProgress(){if(!this.comms.ready)return;const t=Math.ceil(this.doc().scrollTop),e=this.doc().scrollHeight,i=this.wnd.innerHeight,A=Math.max(0,Math.min(1,t/e)),n=Math.max(0,Math.min(1,(t+i)/e));this.comms.send("progress",{start:A,end:n})}mount(t,e){this.wnd=t,this.comms=e,this.initialScrollHandled=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce&&(this.wnd.clearTimeout(this.resizeDebounce),this.resizeDebounce=null),t.navigator.epubReadingSystem&&(t.navigator.epubReadingSystem.layoutStyle="scrolling");const i=t.document.createElement("style");return i.dataset.readium="true",i.id=Si,i.textContent=`
|
|
265
265
|
* {
|
|
266
266
|
scrollbar-width: none; /* for Firefox */
|
|
267
267
|
}
|
|
@@ -269,7 +269,7 @@ if(window.onload) window.onload = new Proxy(window.onload, {
|
|
|
269
269
|
body::-webkit-scrollbar {
|
|
270
270
|
display: none; /* for Chrome, Safari, and Opera */
|
|
271
271
|
}
|
|
272
|
-
`,t.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(t.document.body),t.addEventListener("scroll",this.handleScroll,{passive:!0}),e.register("force_webkit_recalc",H.moduleName,()=>{Fi(this.wnd);const A=this.doc().scrollTop;A>1?this.doc().scrollTop=A-1:this.doc().scrollTop=A+1,this.doc().scrollTop=A}),e.register("go_progression",H.moduleName,(A,n)=>{const s=A;if(s<0||s>1){e.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*s,this.reportProgress(),C(this.wnd),n(!0)})}),e.register("go_id",H.moduleName,(A,n)=>{const s=t.document.getElementById(A);if(!s){n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=s.getBoundingClientRect().top+t.scrollY-t.innerHeight/2,this.reportProgress(),C(this.wnd),n(!0)})}),e.register("go_text",H.moduleName,(A,n)=>{let s;Array.isArray(A)&&(A.length>1&&(s=A[1]),A=A[0]);const o=it.deserialize(A),a=Ht(this.wnd.document,new K({href:t.location.href,type:"text/html",text:o,locations:s?new R({otherLocations:new Map([["cssSelector",s]])}):void 0}));if(!a){n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=a.getBoundingClientRect().top+t.scrollY-t.innerHeight/2,this.reportProgress(),C(this.wnd),n(!0)})}),e.register("go_start",H.moduleName,(A,n)=>{if(this.doc().scrollTop===0)return n(!1);this.doc().scrollTop=0,this.reportProgress(),n(!0)}),e.register("go_end",H.moduleName,(A,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)}),e.register("unfocus",H.moduleName,(A,n)=>{C(this.wnd),n(!0)}),e.register(["go_next","go_prev"],H.moduleName,(A,n)=>n(!1)),e.register("focus",H.moduleName,(A,n)=>{this.reportProgress(),n(!0)}),e.register("first_visible_locator",H.moduleName,(A,n)=>{const s=we(t,!0);this.comms.send("first_visible_locator",s.serialize()),n(!0)}),e.log("ScrollSnapper Mounted"),!0}unmount(t,e){return e.unregisterAll(H.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&t.removeEventListener("scroll",this.handleScroll),t.document.getElementById(Si)?.remove(),e.log("ScrollSnapper Unmounted"),!0}};Qi.moduleName="scroll_snapper";let fn=Qi;const zi=class G extends Be{constructor(){super(...arguments),this.initialScrollHandled=!1,this.isScrolling=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce=null,this.handleScroll=()=>{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,e=t-this.lastScrollTop;this.lastScrollTop=t,this.comms.send("scroll",e),this.isScrolling=!1}))}}}doc(){return this.wnd.document.scrollingElement}reportProgress(){if(!this.comms.ready)return;const t=Math.ceil(this.doc().scrollTop),e=this.doc().scrollHeight,i=this.wnd.innerHeight,A=Math.max(0,Math.min(1,t/e)),n=Math.max(0,Math.min(1,(t+i)/e));this.comms.send("progress",{start:A,end:n})}mount(t,e){return this.wnd=t,this.comms=e,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(t.document.body),t.addEventListener("scroll",this.handleScroll,{passive:!0}),e.register("force_webkit_recalc",G.moduleName,()=>{Fi(this.wnd);const i=this.doc().scrollTop;i>1?this.doc().scrollTop=i-1:this.doc().scrollTop=i+1,this.doc().scrollTop=i}),e.register("go_progression",G.moduleName,(i,A)=>{const n=i;if(n<0||n>1){e.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),A(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*n,this.reportProgress(),C(this.wnd),A(!0)})}),this.comms.register("go_id",G.moduleName,(i,A)=>{const n=t.document.getElementById(i);if(!n){A(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=n.getBoundingClientRect().top+t.scrollY-t.innerHeight/2,this.reportProgress(),C(this.wnd),A(!0)})}),e.register("go_text",G.moduleName,(i,A)=>{let n;Array.isArray(i)&&(i.length>1&&(n=i[1]),i=i[0]);const s=it.deserialize(i),o=Ht(this.wnd.document,new K({href:t.location.href,type:"text/html",text:s,locations:n?new R({otherLocations:new Map([["cssSelector",n]])}):void 0}));if(!o){A(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=o.getBoundingClientRect().top+t.scrollY-t.innerHeight/2,this.reportProgress(),C(this.wnd),A(!0)})}),e.register("go_start",G.moduleName,(i,A)=>{if(this.doc().scrollTop===0)return A(!1);this.doc().scrollTop=0,this.reportProgress(),A(!0)}),e.register("go_end",G.moduleName,(i,A)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return A(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),A(!0)}),e.register("unfocus",G.moduleName,(i,A)=>{C(this.wnd),A(!0)}),e.register(["go_next","go_prev"],G.moduleName,(i,A)=>A(!1)),e.register("focus",G.moduleName,(i,A)=>{this.reportProgress(),A(!0)}),e.register("first_visible_locator",G.moduleName,(i,A)=>{const n=we(t,!0);e.send("first_visible_locator",n.serialize()),A(!0)}),e.log("WebPubSnapper Mounted"),!0}unmount(t,e){return e.unregisterAll(G.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&t.removeEventListener("scroll",this.handleScroll),e.log("WebPubSnapper Unmounted"),!0}};zi.moduleName="webpub_snapper";let pn=zi;const Yi=class extends Ft{constructor(){super(...arguments),this.pointerMoved=!1,this.onPointerUp=this.onPointUp.bind(this),this.onPointerMove=this.onPointMove.bind(this),this.onPointerDown=this.onPointDown.bind(this),this.onContextMenu=this.onContext.bind(this),this.onClicker=this.onClick.bind(this)}onPointUp(t){const e=this.wnd.getSelection();if(e&&e.toString()?.length>0){const A=e.getRangeAt(0)?.getClientRects();if(!A||A.length===0)return;const n=A[0],s={text:e.toString(),x:n.x,y:n.y,width:n.width,height:n.height,targetFrameSrc:this.wnd?.location?.href};this.comms.send("text_selected",s)}if(this.pointerMoved){this.pointerMoved=!1;return}if(!e?.isCollapsed||!t.isPrimary)return;const i=this.wnd.devicePixelRatio;t.preventDefault(),this.comms.send(t.pointerType==="touch"?"tap":"click",{defaultPrevented:t.defaultPrevented,x:t.clientX*i,y:t.clientY*i,targetFrameSrc:this.wnd.location.href,targetElement:t.target.outerHTML,interactiveElement:Ui(t.target)?.outerHTML,cssSelector:this.wnd._readium_cssSelectorGenerator.getCssSelector(t.target)}),this.pointerMoved=!1}onPointMove(t){if(t.movementY!==void 0&&t.movementX!==void 0){(Math.abs(t.movementX)>1||Math.abs(t.movementY)>1)&&(this.pointerMoved=!0);return}this.pointerMoved=!0}onPointDown(){this.pointerMoved=!1}onContext(t){this.onPointUp(t),this.pointerMoved=!1}onClick(t){if(t.preventDefault(),!t.isTrusted){const e=new PointerEvent("pointerup",{isPrimary:!0,pointerType:"mouse",clientX:t.clientX,clientY:t.clientY});Object.defineProperty(e,"target",{writable:!1,value:t.target}),Object.defineProperty(e,"defaultPrevented",{writable:!1,value:t.defaultPrevented}),this.onPointUp(e)}}mount(t,e){return this.wnd=t,this.comms=e,t.document.addEventListener("pointerdown",this.onPointerDown),t.document.addEventListener("pointerup",this.onPointerUp),t.document.addEventListener("contextmenu",this.onContextMenu),t.document.addEventListener("pointermove",this.onPointerMove),t.document.addEventListener("click",this.onClicker),e.log("Peripherals Mounted"),!0}unmount(t,e){return t.document.removeEventListener("pointerdown",this.onPointerDown),t.document.removeEventListener("pointerup",this.onPointerUp),t.document.removeEventListener("contextmenu",this.onContextMenu),t.document.removeEventListener("pointermove",this.onPointerMove),t.document.removeEventListener("click",this.onClicker),e.log("Peripherals Unmounted"),!0}};Yi.moduleName="peripherals";let Mn=Yi;const Ni=class ve extends Ft{constructor(){super(...arguments),this.mediaPlayingCount=0,this.allAnimations=new Set}wndOnErr(t){this.comms?.send("error",{message:t.message,filename:t.filename,lineno:t.lineno,colno:t.colno})}unblock(t){for(t._readium_blockEvents=!1;t._readium_blockedEvents?.length>0;){const e=t._readium_blockedEvents.shift();switch(e[0]){case 0:Reflect.apply(e[1],e[2],e[3]);break;case 1:const i=e[1],A=e[2];t.removeEventListener(i.type,t._readium_eventBlocker,!0);const n=new Event(i.type,{bubbles:i.bubbles,cancelable:i.cancelable});A?A.dispatchEvent(n):t.dispatchEvent(n);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(t){const e=t.document.querySelectorAll("audio,video");for(let i=0;i<e.length;i++)e[i].pause()}mount(t,e){this.comms=e,t.addEventListener("error",this.wndOnErr,!1),Reflect.defineProperty(t.navigator,"epubReadingSystem",{value:{name:"readium-ts-toolkit",version:"2.2.1",hasFeature:(A,n="")=>{switch(A){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 t.document&&t.document.getAnimations().forEach(A=>{A.cancel(),this.allAnimations.add(A)}),e.register("activate",ve.moduleName,(A,n)=>{this.allAnimations.forEach(s=>{s.cancel(),s.play()}),n(!0)}),e.register("unfocus",ve.moduleName,(A,n)=>{this.pauseAllMedia(t),this.allAnimations.forEach(s=>s.pause()),n(!0)});const i=t.document.querySelectorAll("audio,video");for(let A=0;A<i.length;A++){const n=i[A];n.addEventListener("play",this.onMediaPlayEvent,{passive:!0}),n.addEventListener("pause",this.onMediaPauseEvent,{passive:!0})}return e.log("Setup Mounted"),!0}unmount(t,e){return t.removeEventListener("error",this.wndOnErr),t.removeEventListener("play",this.onMediaPlayEvent),t.removeEventListener("pause",this.onMediaPauseEvent),this.allAnimations.forEach(i=>i.cancel()),this.allAnimations.clear(),e.log("Setup Unmounted"),!0}};Ni.moduleName="setup";let Ti=Ni;const xi="readium-viewport",bi=class ot extends Ti{onViewportWidthChanged(t){const e=t.target;Ut(e,"--RS__viewportWidth",`${e.innerWidth}px`)}mount(t,e){if(!super.mount(t,e))return!1;const i=t.document.createElement("meta");return i.dataset.readium="true",i.setAttribute("name","viewport"),i.setAttribute("id",xi),i.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"),t.document.head.appendChild(i),t.addEventListener("orientationchange",this.onViewportWidthChanged),t.addEventListener("resize",this.onViewportWidthChanged),this.onViewportWidthChanged({target:t}),e.register("get_properties",ot.moduleName,(A,n)=>{Me(t),n(!0)}),e.register("update_properties",ot.moduleName,(A,n)=>{A["--RS__viewportWidth"]=`${t.innerWidth}px`,mi(t,A),n(!0)}),e.register("set_property",ot.moduleName,(A,n)=>{const s=A;Ut(t,s[0],s[1]),n(!0)}),e.register("remove_property",ot.moduleName,(A,n)=>{kt(t,A),n(!0)}),e.register("activate",ot.moduleName,(A,n)=>{this.unblock(t),n(!0)}),e.log("ReflowableSetup Mounted"),!0}unmount(t,e){return e.unregisterAll(ot.moduleName),t.document.head.querySelector(`#${xi}`)?.remove(),t.removeEventListener("orientationchange",this.onViewportWidthChanged),e.log("ReflowableSetup Unmounted"),super.unmount(t,e)}};bi.moduleName="reflowable_setup";let Bn=bi;const ji="readium-fixed-style",Vi=class et extends Ti{mount(t,e){if(!super.mount(t,e))return!1;t.navigator.epubReadingSystem&&(t.navigator.epubReadingSystem.layoutStyle="paginated");const i=t.document.createElement("style");return i.id=ji,i.dataset.readium="true",i.textContent=`
|
|
272
|
+
`,t.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(t.document.body),t.addEventListener("scroll",this.handleScroll,{passive:!0}),e.register("force_webkit_recalc",D.moduleName,()=>{Fi(this.wnd);const A=this.doc().scrollTop;A>1?this.doc().scrollTop=A-1:this.doc().scrollTop=A+1,this.doc().scrollTop=A}),e.register("go_progression",D.moduleName,(A,n)=>{const s=A;if(s<0||s>1){e.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*s,this.reportProgress(),C(this.wnd),n(!0)})}),e.register("go_id",D.moduleName,(A,n)=>{const s=t.document.getElementById(A);if(!s){n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=s.getBoundingClientRect().top+t.scrollY-t.innerHeight/2,this.reportProgress(),C(this.wnd),n(!0)})}),e.register("go_text",D.moduleName,(A,n)=>{let s;Array.isArray(A)&&(A.length>1&&(s=A[1]),A=A[0]);const o=et.deserialize(A),a=Dt(this.wnd.document,new Z({href:t.location.href,type:"text/html",text:o,locations:s?new R({otherLocations:new Map([["cssSelector",s]])}):void 0}));if(!a){n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=a.getBoundingClientRect().top+t.scrollY-t.innerHeight/2,this.reportProgress(),C(this.wnd),n(!0)})}),e.register("go_start",D.moduleName,(A,n)=>{if(this.doc().scrollTop===0)return n(!1);this.doc().scrollTop=0,this.reportProgress(),n(!0)}),e.register("go_end",D.moduleName,(A,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)}),e.register("unfocus",D.moduleName,(A,n)=>{C(this.wnd),n(!0)}),e.register(["go_next","go_prev"],D.moduleName,(A,n)=>n(!1)),e.register("focus",D.moduleName,(A,n)=>{this.reportProgress(),n(!0)}),e.register("first_visible_locator",D.moduleName,(A,n)=>{const s=Be(t,!0);this.comms.send("first_visible_locator",s.serialize()),n(!0)}),e.log("ScrollSnapper Mounted"),!0}unmount(t,e){return e.unregisterAll(D.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&t.removeEventListener("scroll",this.handleScroll),t.document.getElementById(Si)?.remove(),e.log("ScrollSnapper Unmounted"),!0}};Qi.moduleName="scroll_snapper";let fn=Qi;const zi=class H extends Me{constructor(){super(...arguments),this.initialScrollHandled=!1,this.isScrolling=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce=null,this.handleScroll=()=>{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,e=t-this.lastScrollTop;this.lastScrollTop=t,this.comms.send("scroll",e),this.isScrolling=!1}))}}}doc(){return this.wnd.document.scrollingElement}reportProgress(){if(!this.comms.ready)return;const t=Math.ceil(this.doc().scrollTop),e=this.doc().scrollHeight,i=this.wnd.innerHeight,A=Math.max(0,Math.min(1,t/e)),n=Math.max(0,Math.min(1,(t+i)/e));this.comms.send("progress",{start:A,end:n})}mount(t,e){return this.wnd=t,this.comms=e,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(t.document.body),t.addEventListener("scroll",this.handleScroll,{passive:!0}),e.register("force_webkit_recalc",H.moduleName,()=>{Fi(this.wnd);const i=this.doc().scrollTop;i>1?this.doc().scrollTop=i-1:this.doc().scrollTop=i+1,this.doc().scrollTop=i}),e.register("go_progression",H.moduleName,(i,A)=>{const n=i;if(n<0||n>1){e.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),A(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*n,this.reportProgress(),C(this.wnd),A(!0)})}),this.comms.register("go_id",H.moduleName,(i,A)=>{const n=t.document.getElementById(i);if(!n){A(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=n.getBoundingClientRect().top+t.scrollY-t.innerHeight/2,this.reportProgress(),C(this.wnd),A(!0)})}),e.register("go_text",H.moduleName,(i,A)=>{let n;Array.isArray(i)&&(i.length>1&&(n=i[1]),i=i[0]);const s=et.deserialize(i),o=Dt(this.wnd.document,new Z({href:t.location.href,type:"text/html",text:s,locations:n?new R({otherLocations:new Map([["cssSelector",n]])}):void 0}));if(!o){A(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=o.getBoundingClientRect().top+t.scrollY-t.innerHeight/2,this.reportProgress(),C(this.wnd),A(!0)})}),e.register("go_start",H.moduleName,(i,A)=>{if(this.doc().scrollTop===0)return A(!1);this.doc().scrollTop=0,this.reportProgress(),A(!0)}),e.register("go_end",H.moduleName,(i,A)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return A(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),A(!0)}),e.register("unfocus",H.moduleName,(i,A)=>{C(this.wnd),A(!0)}),e.register(["go_next","go_prev"],H.moduleName,(i,A)=>A(!1)),e.register("focus",H.moduleName,(i,A)=>{this.reportProgress(),A(!0)}),e.register("first_visible_locator",H.moduleName,(i,A)=>{const n=Be(t,!0);e.send("first_visible_locator",n.serialize()),A(!0)}),e.log("WebPubSnapper Mounted"),!0}unmount(t,e){return e.unregisterAll(H.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&t.removeEventListener("scroll",this.handleScroll),e.log("WebPubSnapper Unmounted"),!0}};zi.moduleName="webpub_snapper";let pn=zi;const Yi=class extends It{constructor(){super(...arguments),this.pointerMoved=!1,this.onPointerUp=this.onPointUp.bind(this),this.onPointerMove=this.onPointMove.bind(this),this.onPointerDown=this.onPointDown.bind(this),this.onContextMenu=this.onContext.bind(this),this.onClicker=this.onClick.bind(this)}onPointUp(t){const e=this.wnd.getSelection();if(e&&e.toString()?.length>0){const A=e.getRangeAt(0)?.getClientRects();if(!A||A.length===0)return;const n=A[0],s={text:e.toString(),x:n.x,y:n.y,width:n.width,height:n.height,targetFrameSrc:this.wnd?.location?.href};this.comms.send("text_selected",s)}if(this.pointerMoved){this.pointerMoved=!1;return}if(!e?.isCollapsed||!t.isPrimary)return;const i=this.wnd.devicePixelRatio;t.preventDefault(),this.comms.send(t.pointerType==="touch"?"tap":"click",{defaultPrevented:t.defaultPrevented,x:t.clientX*i,y:t.clientY*i,targetFrameSrc:this.wnd.location.href,targetElement:t.target.outerHTML,interactiveElement:yi(t.target)?.outerHTML,cssSelector:this.wnd._readium_cssSelectorGenerator.getCssSelector(t.target)}),this.pointerMoved=!1}onPointMove(t){if(t.movementY!==void 0&&t.movementX!==void 0){(Math.abs(t.movementX)>1||Math.abs(t.movementY)>1)&&(this.pointerMoved=!0);return}this.pointerMoved=!0}onPointDown(){this.pointerMoved=!1}onContext(t){this.onPointUp(t),this.pointerMoved=!1}onClick(t){if(t.preventDefault(),!t.isTrusted){const e=new PointerEvent("pointerup",{isPrimary:!0,pointerType:"mouse",clientX:t.clientX,clientY:t.clientY});Object.defineProperty(e,"target",{writable:!1,value:t.target}),Object.defineProperty(e,"defaultPrevented",{writable:!1,value:t.defaultPrevented}),this.onPointUp(e)}}mount(t,e){return this.wnd=t,this.comms=e,t.document.addEventListener("pointerdown",this.onPointerDown),t.document.addEventListener("pointerup",this.onPointerUp),t.document.addEventListener("contextmenu",this.onContextMenu),t.document.addEventListener("pointermove",this.onPointerMove),t.document.addEventListener("click",this.onClicker),e.log("Peripherals Mounted"),!0}unmount(t,e){return t.document.removeEventListener("pointerdown",this.onPointerDown),t.document.removeEventListener("pointerup",this.onPointerUp),t.document.removeEventListener("contextmenu",this.onContextMenu),t.document.removeEventListener("pointermove",this.onPointerMove),t.document.removeEventListener("click",this.onClicker),e.log("Peripherals Unmounted"),!0}};Yi.moduleName="peripherals";let Mn=Yi;const Ni=class Pe extends It{constructor(){super(...arguments),this.mediaPlayingCount=0,this.allAnimations=new Set}wndOnErr(t){this.comms?.send("error",{message:t.message,filename:t.filename,lineno:t.lineno,colno:t.colno})}unblock(t){for(t._readium_blockEvents=!1;t._readium_blockedEvents?.length>0;){const e=t._readium_blockedEvents.shift();switch(e[0]){case 0:Reflect.apply(e[1],e[2],e[3]);break;case 1:const i=e[1],A=e[2];t.removeEventListener(i.type,t._readium_eventBlocker,!0);const n=new Event(i.type,{bubbles:i.bubbles,cancelable:i.cancelable});A?A.dispatchEvent(n):t.dispatchEvent(n);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(t){const e=t.document.querySelectorAll("audio,video");for(let i=0;i<e.length;i++)e[i].pause()}mount(t,e){this.comms=e,t.addEventListener("error",this.wndOnErr,!1),Reflect.defineProperty(t.navigator,"epubReadingSystem",{value:{name:"readium-ts-toolkit",version:"2.2.1",hasFeature:(A,n="")=>{switch(A){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 t.document&&t.document.getAnimations().forEach(A=>{A.cancel(),this.allAnimations.add(A)}),e.register("activate",Pe.moduleName,(A,n)=>{this.allAnimations.forEach(s=>{s.cancel(),s.play()}),n(!0)}),e.register("unfocus",Pe.moduleName,(A,n)=>{this.pauseAllMedia(t),this.allAnimations.forEach(s=>s.pause()),n(!0)});const i=t.document.querySelectorAll("audio,video");for(let A=0;A<i.length;A++){const n=i[A];n.addEventListener("play",this.onMediaPlayEvent,{passive:!0}),n.addEventListener("pause",this.onMediaPauseEvent,{passive:!0})}return e.log("Setup Mounted"),!0}unmount(t,e){return t.removeEventListener("error",this.wndOnErr),t.removeEventListener("play",this.onMediaPlayEvent),t.removeEventListener("pause",this.onMediaPauseEvent),this.allAnimations.forEach(i=>i.cancel()),this.allAnimations.clear(),e.log("Setup Unmounted"),!0}};Ni.moduleName="setup";let xi=Ni;const Ti="readium-viewport",bi=class st extends xi{onViewportWidthChanged(t){const e=t.target;Ft(e,"--RS__viewportWidth",`${e.innerWidth}px`)}mount(t,e){if(!super.mount(t,e))return!1;const i=t.document.createElement("meta");return i.dataset.readium="true",i.setAttribute("name","viewport"),i.setAttribute("id",Ti),i.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"),t.document.head.appendChild(i),t.addEventListener("orientationchange",this.onViewportWidthChanged),t.addEventListener("resize",this.onViewportWidthChanged),this.onViewportWidthChanged({target:t}),e.register("get_properties",st.moduleName,(A,n)=>{pe(t),n(!0)}),e.register("update_properties",st.moduleName,(A,n)=>{A["--RS__viewportWidth"]=`${t.innerWidth}px`,mi(t,A),n(!0)}),e.register("set_property",st.moduleName,(A,n)=>{const s=A;Ft(t,s[0],s[1]),n(!0)}),e.register("remove_property",st.moduleName,(A,n)=>{Gt(t,A),n(!0)}),e.register("activate",st.moduleName,(A,n)=>{this.unblock(t),n(!0)}),e.log("ReflowableSetup Mounted"),!0}unmount(t,e){return e.unregisterAll(st.moduleName),t.document.head.querySelector(`#${Ti}`)?.remove(),t.removeEventListener("orientationchange",this.onViewportWidthChanged),e.log("ReflowableSetup Unmounted"),super.unmount(t,e)}};bi.moduleName="reflowable_setup";let Bn=bi;const ji="readium-fixed-style",Vi=class tt extends xi{mount(t,e){if(!super.mount(t,e))return!1;t.navigator.epubReadingSystem&&(t.navigator.epubReadingSystem.layoutStyle="paginated");const i=t.document.createElement("style");return i.id=ji,i.dataset.readium="true",i.textContent=`
|
|
273
273
|
html, body {
|
|
274
274
|
text-size-adjust: none;
|
|
275
275
|
-ms-text-size-adjust: none;
|
|
@@ -281,7 +281,7 @@ if(window.onload) window.onload = new Proxy(window.onload, {
|
|
|
281
281
|
min-height: 100%;
|
|
282
282
|
|
|
283
283
|
/*cursor: var() TODO*/
|
|
284
|
-
}`,t.document.head.appendChild(i),e.register("set_property",
|
|
284
|
+
}`,t.document.head.appendChild(i),e.register("set_property",tt.moduleName,(A,n)=>{const s=A;Ft(t,s[0],s[1]),n(!0)}),e.register("remove_property",tt.moduleName,(A,n)=>{Gt(t,A),n(!0)}),e.register("first_visible_locator",tt.moduleName,(A,n)=>n(!1)),e.register("unfocus",tt.moduleName,(A,n)=>{C(t),n(!0)}),e.register(["focus","go_next","go_prev","go_id","go_end","go_start","go_text","go_progression"],tt.moduleName,(A,n)=>n(!0)),e.register("activate",tt.moduleName,(A,n)=>{this.unblock(t),n(!0)}),e.log("FixedSetup Mounted"),!0}unmount(t,e){return e.unregisterAll(tt.moduleName),t.document.getElementById(ji)?.remove(),e.log("FixedSetup Unmounted"),super.unmount(t,e)}};Vi.moduleName="fixed_setup";let wn=Vi;const Pi=class ot extends It{wndOnErr(t){this.comms?.send("error",{message:t.message,filename:t.filename,lineno:t.lineno,colno:t.colno})}mount(t,e){return this.comms=e,t.addEventListener("error",this.wndOnErr,!1),e.register("get_properties",ot.moduleName,(i,A)=>{pe(t),A(!0)}),e.register("update_properties",ot.moduleName,(i,A)=>{mi(t,i),A(!0)}),e.register("set_property",ot.moduleName,(i,A)=>{const n=i;Ft(t,n[0],n[1]),A(!0)}),e.register("remove_property",ot.moduleName,(i,A)=>{Gt(t,i),A(!0)}),e.register("activate",ot.moduleName,(i,A)=>{A(!0)}),e.log("WebPubSetup Mounted"),!0}unmount(t,e){return e.unregisterAll(ot.moduleName),t.removeEventListener("error",this.wndOnErr),e.log("WebPubSetup Unmounted"),!0}};Pi.moduleName="webpub_setup";let En=Pi;const In=["fixed_setup","decorator","peripherals"],Fn=["reflowable_setup","decorator","peripherals","column_snapper","scroll_snapper"],yn=["webpub_setup","webpub_snapper","decorator","peripherals"],kt=new Map([wn,Bn,En,pn,Mn,on,mn,fn].map(r=>[r.moduleName,r]));class ct{constructor(t=window,e=[]){this.loadedModules=[],this.wnd=t,this.comms=new PA(t);const i=[...new Set(e)];if(i.length){if(typeof t>"u")throw Error("Loader is not in a web browser");t.parent!==t&&this.comms.log("Loader is probably in a frame"),this.loadedModules=i.map(A=>{const n=this.loadModule(A);if(n)return n.mount(this.wnd,this.comms),n}).filter(A=>A!==void 0)}}loadModule(t){const e=kt.get(t);return e===void 0?(this.comms.log(`Module "${name}" does not exist in the library`),e):new e}addModule(t){const e=this.loadModule(t);return!e||!e.mount(this.wnd,this.comms)?!1:(this.loadedModules.push(e),!0)}removeModule(t){const e=kt.get(t);if(e===void 0)return this.comms.log(`Module "${t}" does not exist in the library`),!1;const i=this.loadedModules.findIndex(A=>A instanceof e);return i<0?!1:(this.loadedModules[i].unmount(this.wnd,this.comms),this.loadedModules.splice(i,1),!0)}destroy(){this.comms.destroy(),this.loadedModules.forEach(t=>t.unmount(this.wnd,this.comms)),this.loadedModules=[]}}const Un=1e4;class gt{constructor(t,e){this.registry=new Map,this._ready=!1,this.listenerBuffer=[],this.handler=this.handle.bind(this),this.wnd=t,this.origin=e;try{this.channelId=window.crypto.randomUUID()}catch{this.channelId=ae()}this.gc=setInterval(()=>{this.registry.forEach((i,A)=>{performance.now()-i.time>Un&&(console.warn(A,"event for",i.key,"was never handled!"),this.registry.delete(A))})},5e3),window.addEventListener("message",this.handler),this.send("_ping",void 0)}set listener(t){this.listenerBuffer.length>0&&this.listenerBuffer.forEach(e=>t(e[0],e[1])),this.listenerBuffer=[],this._listener=t}clearListener(){typeof this._listener=="function"&&(this._listener=void 0)}halt(){this._ready=!1,window.removeEventListener("message",this.handler),clearInterval(this.gc),this._listener=void 0,this.registry.clear()}resume(){window.addEventListener("message",this.handler),this._ready=!0}handle(t){const e=t.data;if(!e._readium){console.warn("Ignoring",e);return}if(e._channel===this.channelId)switch(e.key){case"_ack":{if(!e.id)return;const i=this.registry.get(e.id);if(!i)return;this.registry.delete(e.id),i.cb(!!e.data);return}case"_pong":this._ready=!0;default:{if(!this.ready)return;typeof this._listener=="function"?this._listener(e.key,e.data):this.listenerBuffer.push([e.key,e.data])}}}get ready(){return this._ready}send(t,e,i,A=!1,n=[]){const s=ae();return i&&this.registry.set(s,{cb:i,time:performance.now(),key:t}),this.wnd.postMessage({_readium:lt,_channel:this.channelId,id:s,data:e,key:t,strict:A},"/",n),s}}const Rn={RS__oldStyleTf:"'Iowan Old Style', Sitka, 'Sitka Text', Palatino, 'Book Antiqua', 'URW Palladio L', P052, serif"},Cn=16,vi=Rn.RS__oldStyleTf;class dt{constructor(t){this._optimalLineLength=null,this._canvas=document.createElement("canvas"),this._optimalChars=t.optimalChars,this._minChars=t.minChars,this._maxChars=t.maxChars,this._baseFontSize=t.baseFontSize||Cn,this._fontFace=t.fontFace||vi,this._sample=t.sample||null,this._pageGutter=t.pageGutter||0,this._letterSpacing=t.letterSpacing?Math.round(t.letterSpacing*this._baseFontSize):0,this._wordSpacing=t.wordSpacing?Math.round(t.wordSpacing*this._baseFontSize):0,this._isCJK=t.isCJK||!1,this._getRelative=t.getRelative||!1,this._padding=this._pageGutter*2,this._minDivider=this._minChars&&this._minChars<this._optimalChars?this._optimalChars/this._minChars:this._minChars===null?null:1,this._maxMultiplier=this._maxChars&&this._maxChars>this._optimalChars?this._maxChars/this._optimalChars:this._maxChars===null?null:1,this._approximatedWordSpaces=dt.approximateWordSpaces(this._optimalChars,this._sample)}updateMultipliers(){this._minDivider=this._minChars&&this._minChars<this._optimalChars?this._optimalChars/this._minChars:this._minChars===null?null:1,this._maxMultiplier=this._maxChars&&this._maxChars>this._optimalChars?this._maxChars/this._optimalChars:this._maxChars===null?null:1}update(t){t.optimalChars&&(this._optimalChars=t.optimalChars),t.minChars!==void 0&&(this._minChars=t.minChars),t.maxChars!==void 0&&(this._maxChars=t.maxChars),t.baseFontSize&&(this._baseFontSize=t.baseFontSize),t.fontFace!==void 0&&(this._fontFace=t.fontFace||vi),t.letterSpacing&&(this._letterSpacing=t.letterSpacing),t.wordSpacing&&(this._wordSpacing=t.wordSpacing),t.isCJK!=null&&(this._isCJK=t.isCJK),t.pageGutter&&(this._pageGutter=t.pageGutter),t.getRelative&&(this._getRelative=t.getRelative),t.sample&&(this._sample=t.sample,this._approximatedWordSpaces=dt.approximateWordSpaces(this._optimalChars,this._sample)),this.updateMultipliers(),this._optimalLineLength=this.getOptimalLineLength()}get baseFontSize(){return this._baseFontSize}get minimalLineLength(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),this._minDivider!==null?Math.round(this._optimalLineLength/this._minDivider+this._padding)/(this._getRelative?this._baseFontSize:1):null}get maximalLineLength(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),this._maxMultiplier!==null?Math.round(this._optimalLineLength*this._maxMultiplier+this._padding)/(this._getRelative?this._baseFontSize:1):null}get optimalLineLength(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),Math.round(this._optimalLineLength+this._padding)/(this._getRelative?this._baseFontSize:1)}get all(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),{min:this.minimalLineLength,max:this.maximalLineLength,optimal:this.optimalLineLength,baseFontSize:this._baseFontSize}}static approximateWordSpaces(t,e){let i=0;if(e&&e.length>=t){const A=e.match(/([\s]+)/gi);i=(A?A.length:0)*(t/e.length)}return i}getLineLengthFallback(){const t=this._letterSpacing*(this._optimalChars-1),e=this._wordSpacing*this._approximatedWordSpaces;return this._optimalChars*(this._baseFontSize*.5)+t+e}getOptimalLineLength(){if(this._fontFace){if(typeof this._fontFace=="string")return this.measureText(this._fontFace);{const t=new FontFace(this._fontFace.name,`url(${this._fontFace.url})`);t.load().then(()=>(document.fonts.add(t),this.measureText(t.family)),e=>{})}}return this.getLineLengthFallback()}measureText(t){const e=this._canvas.getContext("2d");if(e&&t){let i=this._isCJK?"水".repeat(this._optimalChars):"0".repeat(this._optimalChars);if(e.font=`${this._baseFontSize}px ${t}`,this._sample&&this._sample.length>=this._optimalChars&&(i=this._sample.slice(0,this._optimalChars)),Object.hasOwn(e,"letterSpacing")&&Object.hasOwn(e,"wordSpacing"))return e.letterSpacing=this._letterSpacing.toString()+"px",e.wordSpacing=this._wordSpacing.toString()+"px",e.measureText(i).width;{const A=this._letterSpacing*(this._optimalChars-1),n=this._wordSpacing*dt.approximateWordSpaces(this._optimalChars,this._sample);return e.measureText(i).width+A+n}}else return this.getLineLengthFallback()}}/*!
|
|
285
285
|
* (℠)
|
|
286
286
|
* # sML.js | I'm a Simple and Middling Library.
|
|
287
287
|
*
|
|
@@ -290,7 +290,7 @@ if(window.onload) window.onload = new Proxy(window.onload, {
|
|
|
290
290
|
*
|
|
291
291
|
* Portions of this code come from the sML library
|
|
292
292
|
* Current version: 1.0.36
|
|
293
|
-
*/const Di=()=>typeof navigator>"u"?"":navigator.userAgent||"",Hi=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;class Gi{constructor(){const t=Hi(),e=Di(),i=n=>(typeof n=="string"||typeof n=="number")&&n?String(n).replace(/_/g,".").split(".").map(s=>parseInt(s)||0):[],A=(n="")=>{if(!n)return[];const s=new RegExp("^.*"+n+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return s.test(e)?i(e.replace(s,"$1")):[]};this.OS=(n=>(/(macOS|Mac OS X)/.test(e)?(/\(iP(hone|od touch);/.test(e)&&(n.iOS=A("CPU (?:iPhone )?OS ")),/\(iPad;/.test(e)?n.iOS=n.iPadOS=A("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(e)&&(document.ontouchend!==void 0?n.iOS=n.iPadOS=A():n.macOS=A("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(e)?n.Windows=(s=>s[0]!==6||!s[1]?s:s[1]===1?[7]:s[1]===2?[8]:[8,1])(A("Windows(?: NT)?")):/Android \d/.test(e)?n.Android=A("Android"):/CrOS/.test(e)?n.ChromeOS=A():/X11;/.test(e)&&(n.Linux=A()),n))({}),t&&t.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(n=>(s=>{const o=n.platform,a=n.platformVersion;if(!(!o||!a)){if(/^i(OS|P(hone|od touch))$/.test(o))s.iOS=i(a);else if(/^iPad(OS)?$/.test(o))s.iOS=s.iPadOS=i(a);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(o))document.ontouchend!==void 0?s.iOS=s.iPadOS=i():s.macOS=i(a);else if(/^(Microsoft )?Windows$/.test(o))s.Windows=i(a);else if(/^(Google )?Android$/.test(o))s.Android=i(a);else if(/^((Google )?Chrome OS|CrOS)$/.test(o))s.ChromeOS=i(a);else if(/^(Linux|Ubuntu|X11)$/.test(o))s.Linux=i(a);else return;Object.keys(this.OS).forEach(h=>delete this.OS[h]),Object.assign(this.OS,s)}})({})),this.UA=(n=>{let s=!1;if(t&&Array.isArray(t.brands)){const o=t.brands.reduce((a,h)=>(a[h.brand]=[h.version*1],a),{});o["Google Chrome"]?(s=!0,n.Blink=n.Chromium=o.Chromium||[],n.Chrome=o["Google Chrome"]):o["Microsoft Edge"]?(s=!0,n.Blink=n.Chromium=o.Chromium||[],n.Edge=o["Microsoft Edge"]):o.Opera&&(s=!0,n.Blink=n.Chromium=o.Chromium||[],n.Opera=o.Opera)}return s||(/ Gecko\/\d/.test(e)?(n.Gecko=A("rv"),/ Waterfox\/\d/.test(e)?n.Waterfox=A("Waterfox"):/ Firefox\/\d/.test(e)&&(n.Firefox=A("Firefox"))):/ Edge\/\d/.test(e)?(n.EdgeHTML=A("Edge"),n.Edge=n.EdgeHTML):/ Chrom(ium|e)\/\d/.test(e)?(n.Blink=n.Chromium=(o=>o[0]?o:A("Chrome"))(A("Chromium")),/ EdgA?\/\d/.test(e)?n.Edge=(o=>o[0]?o:A("Edg"))(A("EdgA")):/ OPR\/\d/.test(e)?n.Opera=A("OPR"):/ Vivaldi\/\d/.test(e)?n.Vivaldi=A("Vivaldi"):/ Silk\/\d/.test(e)?n.Silk=A("Silk"):/ UCBrowser\/\d/.test(e)?n.UCBrowser=A("UCBrowser"):/ Phoebe\/\d/.test(e)?n.Phoebe=A("Phoebe"):n.Chrome=(o=>o[0]?o:n.Chromium)(A("Chrome"))):/ AppleWebKit\/\d/.test(e)?(n.WebKit=A("AppleWebKit"),/ CriOS \d/.test(e)?n.Chrome=A("CriOS"):/ FxiOS \d/.test(e)?n.Firefox=A("FxiOS"):/ EdgiOS\/\d/.test(e)?n.Edge=A("EdgiOS"):/ Version\/\d/.test(e)&&(n.Safari=A("Version"))):/ Trident\/\d/.test(e)&&(n.Trident=A("Trident"),n.InternetExplorer=(o=>o[0]?o:A("MSIE"))(A("rv")))),/[\[; ]FB(AN|_IAB)\//.test(e)&&(n.Facebook=A("FBAV")),/ Line\/\d/.test(e)&&(n.LINE=A("Line")),n})({}),this.Env={get:()=>[this.OS,this.UA].reduce((n,s)=>{for(const o in s)s[o]&&n.push(o);return n},[])}}}class Sn extends Gi{get iOSRequest(){const t=Hi(),e=Di();if(this.OS.iOS&&!this.OS.iPadOS)return"mobile";if(this.OS.iPadOS)return/\(iPad;/.test(e)||t&&/^iPad(OS)?$/.test(t.platform)?"mobile":"desktop"}}const mt=new Gi,W=new Sn;class ki{constructor(t){this.hidden=!0,this.destroyed=!1,this.currModules=[],this.frame=document.createElement("iframe"),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.frame.style.backgroundColor="#FFFFFF",this.source=t}async load(t=[]){return new Promise((e,i)=>{if(this.loader){const A=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...t].sort().join("|")){try{e(A)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new gt(A,t),this.currModules=t,this.comms=void 0;try{e(A)}catch{}return}this.frame.onload=()=>{const A=this.frame.contentWindow;this.loader=new gt(A,t),this.currModules=t;try{e(A)}catch{}},this.frame.onerror=A=>{try{i(A)}catch{}},this.frame.contentWindow.location.replace(this.source)})}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((t,e)=>{this.comms?.send("unfocus",void 0,i=>{this.comms?.halt(),t()})});this.comms?.halt()}}async show(t){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 dt(this.frame.contentWindow,this.source),new Promise((e,i)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{const A=()=>{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,mt.UA.WebKit&&this.comms?.send("force_webkit_recalc",void 0),e()};t!==void 0?this.comms?.send("go_progression",t,A):A()})})})}setCSSProperties(t){this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?this.comms?.resume():this.comms=new dt(this.frame.contentWindow,this.source)),this.comms?.send("update_properties",t),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 msg(){return this.comms}get ldr(){return this.loader}}class Ji{constructor(t,e){this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.pendingUpdates=new Map,this.container=t,this.currentCssProperties=e}async destroy(){let t=this.inprogress.values(),e=t.next();const i=[];for(;e.value;)i.push(e.value),e=t.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let A=this.pool.values(),n=A.next();for(;n.value;)await n.value.destroy(),n=A.next();this.pool.clear(),this.blobs.forEach(s=>URL.revokeObjectURL(s)),this.blobs.clear(),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}async update(t,e,i){const A=t.readingOrder.items;let n=A.findIndex(a=>a.href===e.href);if(n<0)throw Error(`Locator not found in reading order: ${e.href}`);const s=A[n].href;this.inprogress.has(s)&&await this.inprogress.get(s);const o=new Promise(async(a,h)=>{const c=[],g=[];t.readingOrder.items.forEach((l,f)=>{f!==n&&f!==n-1&&f!==n+1&&(c.includes(l.href)||c.push(l.href)),f===n&&(g.includes(l.href)||g.push(l.href))}),c.forEach(async l=>{g.includes(l)||this.pool.has(l)&&(await this.pool.get(l)?.destroy(),this.pool.delete(l))}),this.currentBaseURL!==void 0&&t.baseURL!==this.currentBaseURL&&(this.blobs.forEach(l=>URL.revokeObjectURL(l)),this.blobs.clear()),this.currentBaseURL=t.baseURL;const u=async l=>{if(this.pendingUpdates.has(l)&&this.pendingUpdates.get(l)?.inPool===!1){const F=this.blobs.get(l);F&&(URL.revokeObjectURL(F),this.blobs.delete(l),this.pendingUpdates.delete(l))}if(this.pool.has(l)){const F=this.pool.get(l);if(!this.blobs.has(l))await F.destroy(),this.pool.delete(l),this.pendingUpdates.delete(l);else{await F.load(i);return}}const f=t.readingOrder.findWithHref(l);if(!f)return;if(!this.blobs.has(l)){const S=await new Ke(t,this.currentBaseURL||"",f,this.currentCssProperties).build();this.blobs.set(l,S)}const E=new ki(this.blobs.get(l));l!==s&&await E.hide(),this.container.appendChild(E.iframe),await E.load(i),this.pool.set(l,E)};try{await Promise.all(g.map(l=>u(l)))}catch(l){h(l)}const M=this.pool.get(s);M?.source!==this._currentFrame?.source&&(await this._currentFrame?.hide(),M&&await M.load(i),M&&await M.show(e.locations.progression),this._currentFrame=M),a()});this.inprogress.set(s,o),await o,this.inprogress.delete(s)}setCSSProperties(t){if(!((i,A)=>{const n=Object.keys(i),s=Object.keys(A);if(n.length!==s.length)return!1;for(const o of n)if(i[o]!==A[o])return!1;return!0})(this.currentCssProperties||{},t)){this.currentCssProperties=t,this.pool.forEach(i=>{i.setCSSProperties(t)});for(const i of this.blobs.keys())this.pendingUpdates.set(i,{inPool:this.pool.has(i)})}}get currentFrames(){return[this._currentFrame]}get currentBounds(){const t={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(e=>{if(!e)return;const i=e.realSize;t.x=Math.min(t.x,i.x),t.y=Math.min(t.y,i.y),t.width+=i.width,t.height=Math.max(t.height,i.height),t.top=Math.min(t.top,i.top),t.right=Math.min(t.right,i.right),t.bottom=Math.min(t.bottom,i.bottom),t.left=Math.min(t.left,i.left)}),t}}var Ee,Wi;function Qn(){if(Wi)return Ee;Wi=1;function r(A){if(typeof A!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(A))}function t(A,n){for(var s="",o=0,a=-1,h=0,c,g=0;g<=A.length;++g){if(g<A.length)c=A.charCodeAt(g);else{if(c===47)break;c=47}if(c===47){if(!(a===g-1||h===1))if(a!==g-1&&h===2){if(s.length<2||o!==2||s.charCodeAt(s.length-1)!==46||s.charCodeAt(s.length-2)!==46){if(s.length>2){var u=s.lastIndexOf("/");if(u!==s.length-1){u===-1?(s="",o=0):(s=s.slice(0,u),o=s.length-1-s.lastIndexOf("/")),a=g,h=0;continue}}else if(s.length===2||s.length===1){s="",o=0,a=g,h=0;continue}}n&&(s.length>0?s+="/..":s="..",o=2)}else s.length>0?s+="/"+A.slice(a+1,g):s=A.slice(a+1,g),o=g-a-1;a=g,h=0}else c===46&&h!==-1?++h:h=-1}return s}function e(A,n){var s=n.dir||n.root,o=n.base||(n.name||"")+(n.ext||"");return s?s===n.root?s+o:s+A+o:o}var i={resolve:function(){for(var n="",s=!1,o,a=arguments.length-1;a>=-1&&!s;a--){var h;a>=0?h=arguments[a]:(o===void 0&&(o=process.cwd()),h=o),r(h),h.length!==0&&(n=h+"/"+n,s=h.charCodeAt(0)===47)}return n=t(n,!s),s?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(r(n),n.length===0)return".";var s=n.charCodeAt(0)===47,o=n.charCodeAt(n.length-1)===47;return n=t(n,!s),n.length===0&&!s&&(n="."),n.length>0&&o&&(n+="/"),s?"/"+n:n},isAbsolute:function(n){return r(n),n.length>0&&n.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var n,s=0;s<arguments.length;++s){var o=arguments[s];r(o),o.length>0&&(n===void 0?n=o:n+="/"+o)}return n===void 0?".":i.normalize(n)},relative:function(n,s){if(r(n),r(s),n===s||(n=i.resolve(n),s=i.resolve(s),n===s))return"";for(var o=1;o<n.length&&n.charCodeAt(o)===47;++o);for(var a=n.length,h=a-o,c=1;c<s.length&&s.charCodeAt(c)===47;++c);for(var g=s.length,u=g-c,M=h<u?h:u,l=-1,f=0;f<=M;++f){if(f===M){if(u>M){if(s.charCodeAt(c+f)===47)return s.slice(c+f+1);if(f===0)return s.slice(c+f)}else h>M&&(n.charCodeAt(o+f)===47?l=f:f===0&&(l=0));break}var E=n.charCodeAt(o+f),F=s.charCodeAt(c+f);if(E!==F)break;E===47&&(l=f)}var S="";for(f=o+l+1;f<=a;++f)(f===a||n.charCodeAt(f)===47)&&(S.length===0?S+="..":S+="/..");return S.length>0?S+s.slice(c+l):(c+=l,s.charCodeAt(c)===47&&++c,s.slice(c))},_makeLong:function(n){return n},dirname:function(n){if(r(n),n.length===0)return".";for(var s=n.charCodeAt(0),o=s===47,a=-1,h=!0,c=n.length-1;c>=1;--c)if(s=n.charCodeAt(c),s===47){if(!h){a=c;break}}else h=!1;return a===-1?o?"/":".":o&&a===1?"//":n.slice(0,a)},basename:function(n,s){if(s!==void 0&&typeof s!="string")throw new TypeError('"ext" argument must be a string');r(n);var o=0,a=-1,h=!0,c;if(s!==void 0&&s.length>0&&s.length<=n.length){if(s.length===n.length&&s===n)return"";var g=s.length-1,u=-1;for(c=n.length-1;c>=0;--c){var M=n.charCodeAt(c);if(M===47){if(!h){o=c+1;break}}else u===-1&&(h=!1,u=c+1),g>=0&&(M===s.charCodeAt(g)?--g===-1&&(a=c):(g=-1,a=u))}return o===a?a=u:a===-1&&(a=n.length),n.slice(o,a)}else{for(c=n.length-1;c>=0;--c)if(n.charCodeAt(c)===47){if(!h){o=c+1;break}}else a===-1&&(h=!1,a=c+1);return a===-1?"":n.slice(o,a)}},extname:function(n){r(n);for(var s=-1,o=0,a=-1,h=!0,c=0,g=n.length-1;g>=0;--g){var u=n.charCodeAt(g);if(u===47){if(!h){o=g+1;break}continue}a===-1&&(h=!1,a=g+1),u===46?s===-1?s=g:c!==1&&(c=1):s!==-1&&(c=-1)}return s===-1||a===-1||c===0||c===1&&s===a-1&&s===o+1?"":n.slice(s,a)},format:function(n){if(n===null||typeof n!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof n);return e("/",n)},parse:function(n){r(n);var s={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return s;var o=n.charCodeAt(0),a=o===47,h;a?(s.root="/",h=1):h=0;for(var c=-1,g=0,u=-1,M=!0,l=n.length-1,f=0;l>=h;--l){if(o=n.charCodeAt(l),o===47){if(!M){g=l+1;break}continue}u===-1&&(M=!1,u=l+1),o===46?c===-1?c=l:f!==1&&(f=1):c!==-1&&(f=-1)}return c===-1||u===-1||f===0||f===1&&c===u-1&&c===g+1?u!==-1&&(g===0&&a?s.base=s.name=n.slice(1,u):s.base=s.name=n.slice(g,u)):(g===0&&a?(s.name=n.slice(1,c),s.base=n.slice(1,u)):(s.name=n.slice(g,c),s.base=n.slice(g,u)),s.ext=n.slice(c,u)),g>0?s.dir=n.slice(0,g-1):a&&(s.dir="/"),s},sep:"/",delimiter:":",win32:null,posix:null};return i.posix=i,Ee=i,Ee}var Wt=Qn();class Lt{constructor(){}toFlag(t){return`readium-${t}-on`}toUnitless(t){return t.toString()}toPercentage(t,e=!1){return e||t>0&&t<=1?`${Math.round(t*100)}%`:`${t}%`}toVw(t){const e=Math.round(t*100);return`${Math.min(e,100)}vw`}toVh(t){const e=Math.round(t*100);return`${Math.min(e,100)}vh`}toPx(t){return`${t}px`}toRem(t){return`${t}rem`}}class Ie extends Lt{constructor(t){super(),this.a11yNormalize=t.a11yNormalize??null,this.bodyHyphens=t.bodyHyphens??null,this.fontFamily=t.fontFamily??null,this.fontWeight=t.fontWeight??null,this.letterSpacing=t.letterSpacing??null,this.ligatures=t.ligatures??null,this.lineHeight=t.lineHeight??null,this.noRuby=t.noRuby??null,this.paraIndent=t.paraIndent??null,this.paraSpacing=t.paraSpacing??null,this.textAlign=t.textAlign??null,this.wordSpacing=t.wordSpacing??null,this.zoom=t.zoom??null}toCSSProperties(){const t={};return this.a11yNormalize&&(t["--USER__a11yNormalize"]=this.toFlag("a11y")),this.bodyHyphens&&(t["--USER__bodyHyphens"]=this.bodyHyphens),this.fontFamily&&(t["--USER__fontFamily"]=this.fontFamily),this.fontWeight!=null&&(t["--USER__fontWeight"]=this.toUnitless(this.fontWeight)),this.letterSpacing!=null&&(t["--USER__letterSpacing"]=this.toRem(this.letterSpacing)),this.ligatures&&(t["--USER__ligatures"]=this.ligatures),this.lineHeight!=null&&(t["--USER__lineHeight"]=this.toUnitless(this.lineHeight)),this.noRuby&&(t["--USER__noRuby"]=this.toFlag("noRuby")),this.paraIndent!=null&&(t["--USER__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(t["--USER__paraSpacing"]=this.toRem(this.paraSpacing)),this.textAlign&&(t["--USER__textAlign"]=this.textAlign),this.wordSpacing!=null&&(t["--USER__wordSpacing"]=this.toRem(this.wordSpacing)),this.zoom!==null&&(t["--USER__zoom"]=this.toPercentage(this.zoom,!0)),t}}class Li{constructor(t){this.userProperties=t.userProperties}update(t){const e={a11yNormalize:t.textNormalization,bodyHyphens:typeof t.hyphens!="boolean"?null:t.hyphens?"auto":"none",fontFamily:t.fontFamily,fontWeight:t.fontWeight,letterSpacing:t.letterSpacing,ligatures:typeof t.ligatures!="boolean"?null:t.ligatures?"common-ligatures":"none",lineHeight:t.lineHeight,noRuby:t.noRuby,paraIndent:t.paragraphIndent,paraSpacing:t.paragraphSpacing,textAlign:t.textAlign,wordSpacing:t.wordSpacing,zoom:t.zoom};this.userProperties=new Ie(e)}}var X=(r=>(r.start="start",r.left="left",r.right="right",r.justify="justify",r))(X||{});const nt={range:[0,100],step:1},yt={range:[.7,4],step:.05},q={range:[100,1e3],step:100},Rt={range:[50,250],step:10},Ct={range:[0,1],step:.125},St={range:[1,2],step:.1},rt={range:[20,100],step:1},Qt={range:[0,3],step:.25},zt={range:[0,3],step:.25},Yt={range:[0,2],step:.125},Nt={range:[.7,4],step:.05};function Oi(r,t){return r==null||t==null||r<=t?r:void 0}function Xi(r,t){return r==null||t==null||r>=t?r:void 0}function Q(r){return typeof r=="string"?r:r===null?null:void 0}function U(r){return typeof r=="boolean"||r==null?r:void 0}function Tt(r,t){if(r!==void 0)return r===null?null:t[r]!==void 0?r:void 0}function st(r){return typeof r=="boolean"||typeof r=="number"&&r>=0?r:r===null?null:void 0}function I(r){if(r!==void 0)return r===null?null:r<0?void 0:r}function L(r,t){if(r===void 0)return;if(r===null)return null;const e=Math.min(...t),i=Math.max(...t);return r>=e&&r<=i?r:void 0}function Ot(r,t){return r===void 0?t:r}class ft{constructor(t={}){this.fontFamily=Q(t.fontFamily),this.fontWeight=L(t.fontWeight,q.range),this.hyphens=U(t.hyphens),this.letterSpacing=I(t.letterSpacing),this.ligatures=U(t.ligatures),this.lineHeight=I(t.lineHeight),this.noRuby=U(t.noRuby),this.paragraphIndent=I(t.paragraphIndent),this.paragraphSpacing=I(t.paragraphSpacing),this.textAlign=Tt(t.textAlign,X),this.textNormalization=U(t.textNormalization),this.wordSpacing=I(t.wordSpacing),this.zoom=L(t.zoom,Nt.range)}static serialize(t){const{...e}=t;return JSON.stringify(e)}static deserialize(t){try{const e=JSON.parse(t);return new ft(e)}catch(e){return console.error("Failed to deserialize preferences:",e),null}}merging(t){const e={...this};for(const i of Object.keys(t))t[i]!==void 0&&(e[i]=t[i]);return new ft(e)}}class Zi{constructor(t){this.fontFamily=Q(t.fontFamily)||null,this.fontWeight=L(t.fontWeight,q.range)||null,this.hyphens=U(t.hyphens)??null,this.letterSpacing=I(t.letterSpacing)||null,this.ligatures=U(t.ligatures)??null,this.lineHeight=I(t.lineHeight)||null,this.noRuby=U(t.noRuby)??!1,this.paragraphIndent=I(t.paragraphIndent)??null,this.paragraphSpacing=I(t.paragraphSpacing)??null,this.textAlign=Tt(t.textAlign,X)||null,this.textNormalization=U(t.textNormalization)??!1,this.wordSpacing=I(t.wordSpacing)||null,this.zoom=L(t.zoom,Nt.range)||1}}class Fe{constructor(t,e){this.fontFamily=t.fontFamily||e.fontFamily||null,this.fontWeight=t.fontWeight!==void 0?t.fontWeight:e.fontWeight!==void 0?e.fontWeight:null,this.hyphens=typeof t.hyphens=="boolean"?t.hyphens:e.hyphens??null,this.letterSpacing=t.letterSpacing!==void 0?t.letterSpacing:e.letterSpacing!==void 0?e.letterSpacing:null,this.ligatures=typeof t.ligatures=="boolean"?t.ligatures:e.ligatures??null,this.lineHeight=t.lineHeight!==void 0?t.lineHeight:e.lineHeight!==void 0?e.lineHeight:null,this.noRuby=typeof t.noRuby=="boolean"?t.noRuby:e.noRuby??null,this.paragraphIndent=t.paragraphIndent!==void 0?t.paragraphIndent:e.paragraphIndent!==void 0?e.paragraphIndent:null,this.paragraphSpacing=t.paragraphSpacing!==void 0?t.paragraphSpacing:e.paragraphSpacing!==void 0?e.paragraphSpacing:null,this.textAlign=t.textAlign||e.textAlign||null,this.textNormalization=typeof t.textNormalization=="boolean"?t.textNormalization:e.textNormalization??null,this.wordSpacing=t.wordSpacing!==void 0?t.wordSpacing:e.wordSpacing!==void 0?e.wordSpacing:null,this.zoom=t.zoom!==void 0?t.zoom:e.zoom!==void 0?e.zoom:null}}class z{constructor({initialValue:t=null,effectiveValue:e,isEffective:i,onChange:A}){this._value=t,this._effectiveValue=e,this._isEffective=i,this._onChange=A}set value(t){this._value=t,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}clear(){this._value=null}}class N extends z{set value(t){this._value=t,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}clear(){this._value=null}toggle(){this._value=!this._value,this._onChange(this._value)}}class Ue extends z{constructor({initialValue:t=null,effectiveValue:e,isEffective:i,onChange:A,supportedValues:n}){super({initialValue:t,effectiveValue:e,isEffective:i,onChange:A}),this._supportedValues=n}set value(t){if(t&&!this._supportedValues.includes(t))throw new Error(`Value '${String(t)}' is not in the supported values for this preference.`);this._value=t,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}get supportedValues(){return this._supportedValues}clear(){this._value=null}}class y extends z{constructor({initialValue:t=null,effectiveValue:e,isEffective:i,onChange:A,supportedRange:n,step:s}){super({initialValue:t,effectiveValue:e,isEffective:i,onChange:A}),this._supportedRange=n,this._step=s,this._decimals=this._step.toString().includes(".")?this._step.toString().split(".")[1].length:0}set value(t){if(t&&(t<this._supportedRange[0]||t>this._supportedRange[1]))throw new Error(`Value '${String(t)}' is out of the supported range for this preference.`);this._value=t,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}get supportedRange(){return this._supportedRange}get step(){return this._step}increment(){this._value&&this._value<this._supportedRange[1]&&(this._value=Math.min(Math.round((this._value+this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[1]),this._onChange(this._value))}decrement(){this._value&&this._value>this._supportedRange[0]&&(this._value=Math.max(Math.round((this._value-this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[0]),this._onChange(this._value))}format(t){return t.toString()}clear(){this._value=null}}class ye{constructor(t,e,i){this.preferences=t,this.settings=e,this.metadata=i}clear(){this.preferences=new ft({})}updatePreference(t,e){this.preferences[t]=e}get fontFamily(){return new z({initialValue:this.preferences.fontFamily,effectiveValue:this.settings.fontFamily||null,isEffective:this.metadata?.accessibility?.feature?.includes(v.DISPLAY_TRANSFORMABILITY)??!1,onChange:t=>{this.updatePreference("fontFamily",t||null)}})}get fontWeight(){return new y({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.metadata?.accessibility?.feature?.includes(v.DISPLAY_TRANSFORMABILITY)??!1,onChange:t=>{this.updatePreference("fontWeight",t||null)},supportedRange:q.range,step:q.step})}get hyphens(){return new N({initialValue:this.preferences.hyphens,effectiveValue:this.settings.hyphens||!1,isEffective:this.metadata?.accessibility?.feature?.includes(v.DISPLAY_TRANSFORMABILITY)??!1,onChange:t=>{this.updatePreference("hyphens",t||null)}})}get letterSpacing(){return new y({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.metadata?.accessibility?.feature?.includes(v.DISPLAY_TRANSFORMABILITY)??!1,onChange:t=>{this.updatePreference("letterSpacing",t||null)},supportedRange:Ct.range,step:Ct.step})}get ligatures(){return new N({initialValue:this.preferences.ligatures,effectiveValue:this.settings.ligatures||!0,isEffective:this.metadata?.accessibility?.feature?.includes(v.DISPLAY_TRANSFORMABILITY)??!1,onChange:t=>{this.updatePreference("ligatures",t||null)}})}get lineHeight(){return new y({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.metadata?.accessibility?.feature?.includes(v.DISPLAY_TRANSFORMABILITY)??!1,onChange:t=>{this.updatePreference("lineHeight",t||null)},supportedRange:St.range,step:St.step})}get noRuby(){return new N({initialValue:this.preferences.noRuby,effectiveValue:this.settings.noRuby||!1,isEffective:this.metadata?.accessibility?.feature?.includes(v.DISPLAY_TRANSFORMABILITY)??!1,onChange:t=>{this.updatePreference("noRuby",t||null)}})}get paragraphIndent(){return new y({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.metadata?.accessibility?.feature?.includes(v.DISPLAY_TRANSFORMABILITY)??!1,onChange:t=>{this.updatePreference("paragraphIndent",t||null)},supportedRange:Qt.range,step:Qt.step})}get paragraphSpacing(){return new y({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.metadata?.accessibility?.feature?.includes(v.DISPLAY_TRANSFORMABILITY)??!1,onChange:t=>{this.updatePreference("paragraphSpacing",t||null)},supportedRange:zt.range,step:zt.step})}get textAlign(){return new Ue({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||X.start,isEffective:this.metadata?.accessibility?.feature?.includes(v.DISPLAY_TRANSFORMABILITY)??!1,onChange:t=>{this.updatePreference("textAlign",t||null)},supportedValues:Object.values(X)})}get textNormalization(){return new N({initialValue:this.preferences.textNormalization,effectiveValue:this.settings.textNormalization||!1,isEffective:this.metadata?.accessibility?.feature?.includes(v.DISPLAY_TRANSFORMABILITY)??!1,onChange:t=>{this.updatePreference("textNormalization",t||null)}})}get wordSpacing(){return new y({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.metadata?.accessibility?.feature?.includes(v.DISPLAY_TRANSFORMABILITY)??!1,onChange:t=>{this.updatePreference("wordSpacing",t||null)},supportedRange:Yt.range,step:Yt.step})}get zoom(){return new y({initialValue:this.preferences.zoom,effectiveValue:this.settings.zoom||1,isEffective:CSS.supports("zoom","1")??!1,onChange:t=>{this.updatePreference("zoom",t||null)},supportedRange:Nt.range,step:Nt.step})}}const zn=r=>({frameLoaded:r.frameLoaded||(()=>{}),positionChanged:r.positionChanged||(()=>{}),tap:r.tap||(()=>!1),click:r.click||(()=>!1),zoom:r.zoom||(()=>{}),scroll:r.scroll||(()=>{}),customEvent:r.customEvent||(()=>{}),handleLocator:r.handleLocator||(()=>!1),textSelected:r.textSelected||(()=>{})});class Ki extends re{constructor(t,e,i,A=void 0,n={preferences:{},defaults:{}}){if(super(),this.currentIndex=0,this._preferencesEditor=null,this.webViewport={readingOrder:[],progressions:new Map,positions:null},this.pub=e,this.container=t,this.listeners=zn(i),this._preferences=new ft(n.preferences),this._defaults=new Zi(n.defaults),this._settings=new Fe(this._preferences,this._defaults),this._css=new Li({userProperties:new Ie({zoom:this._settings.zoom})}),A&&typeof A.copyWithLocations=="function"){this.currentLocation=A;const s=this.pub.readingOrder.findIndexWithHref(A.href);s>=0&&(this.currentIndex=s)}else this.currentLocation=this.createCurrentLocator()}async load(){await this.updateCSS(!1);const t=this.compileCSSProperties(this._css);this.framePool=new Ji(this.container,t),await this.apply()}get settings(){return Object.freeze({...this._settings})}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new ye(this._preferences,this.settings,this.pub.metadata)),this._preferencesEditor}async submitPreferences(t){this._preferences=this._preferences.merging(t),await this.applyPreferences()}async applyPreferences(){this._settings=new Fe(this._preferences,this._defaults),this._preferencesEditor!==null&&(this._preferencesEditor=new ye(this._preferences,this.settings,this.pub.metadata)),await this.updateCSS(!0)}async updateCSS(t){this._css.update(this._settings),t&&await this.commitCSS(this._css)}compileCSSProperties(t){const e={};for(const[i,A]of Object.entries(t.userProperties.toCSSProperties()))e[i]=A;return e}async commitCSS(t){const e=this.compileCSSProperties(t);this.framePool.setCSSProperties(e)}eventListener(t,e){switch(t){case"_pong":this.listeners.frameLoaded(this.framePool.currentFrames[0].iframe.contentWindow),this.listeners.positionChanged(this.currentLocation);break;case"first_visible_locator":const i=lt.deserialize(e);if(!i)break;this.currentLocation=new lt({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(e);break;case"click":case"tap":const A=e;if(A.interactiveElement){const n=new DOMParser().parseFromString(A.interactiveElement,"text/html").body.children[0];if(n.nodeType===n.ELEMENT_NODE&&n.nodeName==="A"&&n.hasAttribute("href")){const s=n.attributes.getNamedItem("href")?.value;if(s.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[s.substring(1)]}),!1,()=>{});else if(s.startsWith("mailto:")||s.startsWith("tel:"))this.listeners.handleLocator(new _({href:s}).locator);else try{let o;if(s.startsWith("http://")||s.startsWith("https://"))o=s;else if(this.currentLocation.href.startsWith("http://")||this.currentLocation.href.startsWith("https://")){const h=new URL(this.currentLocation.href);o=new URL(s,h).href}else o=Wt.join(Wt.dirname(this.currentLocation.href),s);const a=this.pub.readingOrder.findWithHref(o);a?this.goLink(a,!1,()=>{}):(console.warn(`Internal link not found in readingOrder: ${o}`),this.listeners.handleLocator(new _({href:s}).locator))}catch(o){console.warn(`Couldn't resolve internal link for ${s}: ${o}`),this.listeners.handleLocator(new _({href:s}).locator)}}else console.log("Clicked on",n)}else if(t==="click"?this.listeners.click(A):this.listeners.tap(A))break;break;case"scroll":this.listeners.scroll(e);break;case"zoom":this.listeners.zoom(e);break;case"progress":this.syncLocation(e);break;case"log":console.log(this.framePool.currentFrames[0]?.source?.split("/")[3],...e);break;default:this.listeners.customEvent(t,e);break}}determineModules(){return Array.from(Jt.keys()).filter(e=>Un.includes(e))}attachListener(){this.framePool.currentFrames[0]?.msg&&(this.framePool.currentFrames[0].msg.listener=(t,e)=>{this.eventListener(t,e)})}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(){await this.framePool?.destroy()}async changeResource(t){if(t===0)return!1;const e=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),i=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,e+t));return i===e?!1:(this.currentIndex=i,this.currentLocation=this.createCurrentLocator(),await this.apply(),!0)}updateViewport(t){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,t),this.currentLocation.locations?.position!==void 0&&(this.webViewport.positions=[this.currentLocation.locations.position]))}async syncLocation(t){const e=t;this.currentLocation&&(this.currentLocation=this.currentLocation.copyWithLocations({progression:e.start})),this.updateViewport(e),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(t,e){this.changeResource(-1).then(i=>{e(i)})}goForward(t,e){this.changeResource(1).then(i=>{e(i)})}get currentLocator(){return this.currentLocation}get viewport(){return this.webViewport}get isScrollStart(){const t=this.viewport.readingOrder[0];return this.viewport.progressions.get(t)?.start===0}get isScrollEnd(){const t=this.viewport.readingOrder[this.viewport.readingOrder.length-1];return this.viewport.progressions.get(t)?.end===1}get canGoBackward(){const t=this.pub.readingOrder.items[0]?.href;return!(this.viewport.progressions.has(t)&&this.viewport.progressions.get(t)?.start===0)}get canGoForward(){const t=this.pub.readingOrder.items[this.pub.readingOrder.items.length-1]?.href;return!(this.viewport.progressions.has(t)&&this.viewport.progressions.get(t)?.end===1)}get readingProgression(){return this.pub.metadata.effectiveReadingProgression}get publication(){return this.pub}async loadLocator(t,e){let i=!1,A=typeof t.locations.getCssSelector=="function"&&t.locations.getCssSelector();if(t.text?.highlight?i=await new Promise((a,h)=>{this.framePool.currentFrames[0].msg.send("go_text",A?[t.text?.serialize(),A]:t.text?.serialize(),c=>a(c))}):A&&(i=await new Promise((a,h)=>{this.framePool.currentFrames[0].msg.send("go_text",["",A],c=>a(c))})),i){e(i);return}const n=typeof t.locations.htmlId=="function"&&t.locations.htmlId();if(n&&(i=await new Promise((a,h)=>{this.framePool.currentFrames[0].msg.send("go_id",n,c=>a(c))})),i){e(i);return}const s=t?.locations?.progression;s&&s>0?i=await new Promise((a,h)=>{this.framePool.currentFrames[0].msg.send("go_progression",s,c=>a(c))}):i=!0,e(i)}go(t,e,i){const A=t.href.split("#")[0];if(!this.pub.readingOrder.findWithHref(A))return i(this.listeners.handleLocator(t));const s=this.pub.readingOrder.findIndexWithHref(A);s>=0&&(this.currentIndex=s),this.currentLocation=this.createCurrentLocator(),this.apply().then(()=>this.loadLocator(t,o=>i(o))).then(()=>{this.attachListener()})}goLink(t,e,i){return this.go(t.locator,e,i)}createCurrentLocator(){const e=this.pub.readingOrder.items[this.currentIndex];if(!e)throw new Error("No current resource available");const A=this.currentLocation&&this.currentLocation.href===e.href&&this.currentLocation.locations.progression?this.currentLocation.locations.progression:0;return this.pub.manifest.locatorFromLink(e)||new lt({href:e.href,type:e.type||"text/html",locations:new V({fragments:[],progression:A,position:this.currentIndex+1})})}}const Yn=Ki,Nn=`/*!
|
|
293
|
+
*/const Di=()=>typeof navigator>"u"?"":navigator.userAgent||"",Hi=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;class Gi{constructor(){const t=Hi(),e=Di(),i=n=>(typeof n=="string"||typeof n=="number")&&n?String(n).replace(/_/g,".").split(".").map(s=>parseInt(s)||0):[],A=(n="")=>{if(!n)return[];const s=new RegExp("^.*"+n+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return s.test(e)?i(e.replace(s,"$1")):[]};this.OS=(n=>(/(macOS|Mac OS X)/.test(e)?(/\(iP(hone|od touch);/.test(e)&&(n.iOS=A("CPU (?:iPhone )?OS ")),/\(iPad;/.test(e)?n.iOS=n.iPadOS=A("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(e)&&(document.ontouchend!==void 0?n.iOS=n.iPadOS=A():n.macOS=A("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(e)?n.Windows=(s=>s[0]!==6||!s[1]?s:s[1]===1?[7]:s[1]===2?[8]:[8,1])(A("Windows(?: NT)?")):/Android \d/.test(e)?n.Android=A("Android"):/CrOS/.test(e)?n.ChromeOS=A():/X11;/.test(e)&&(n.Linux=A()),n))({}),t&&t.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(n=>(s=>{const o=n.platform,a=n.platformVersion;if(!(!o||!a)){if(/^i(OS|P(hone|od touch))$/.test(o))s.iOS=i(a);else if(/^iPad(OS)?$/.test(o))s.iOS=s.iPadOS=i(a);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(o))document.ontouchend!==void 0?s.iOS=s.iPadOS=i():s.macOS=i(a);else if(/^(Microsoft )?Windows$/.test(o))s.Windows=i(a);else if(/^(Google )?Android$/.test(o))s.Android=i(a);else if(/^((Google )?Chrome OS|CrOS)$/.test(o))s.ChromeOS=i(a);else if(/^(Linux|Ubuntu|X11)$/.test(o))s.Linux=i(a);else return;Object.keys(this.OS).forEach(h=>delete this.OS[h]),Object.assign(this.OS,s)}})({})),this.UA=(n=>{let s=!1;if(t&&Array.isArray(t.brands)){const o=t.brands.reduce((a,h)=>(a[h.brand]=[h.version*1],a),{});o["Google Chrome"]?(s=!0,n.Blink=n.Chromium=o.Chromium||[],n.Chrome=o["Google Chrome"]):o["Microsoft Edge"]?(s=!0,n.Blink=n.Chromium=o.Chromium||[],n.Edge=o["Microsoft Edge"]):o.Opera&&(s=!0,n.Blink=n.Chromium=o.Chromium||[],n.Opera=o.Opera)}return s||(/ Gecko\/\d/.test(e)?(n.Gecko=A("rv"),/ Waterfox\/\d/.test(e)?n.Waterfox=A("Waterfox"):/ Firefox\/\d/.test(e)&&(n.Firefox=A("Firefox"))):/ Edge\/\d/.test(e)?(n.EdgeHTML=A("Edge"),n.Edge=n.EdgeHTML):/ Chrom(ium|e)\/\d/.test(e)?(n.Blink=n.Chromium=(o=>o[0]?o:A("Chrome"))(A("Chromium")),/ EdgA?\/\d/.test(e)?n.Edge=(o=>o[0]?o:A("Edg"))(A("EdgA")):/ OPR\/\d/.test(e)?n.Opera=A("OPR"):/ Vivaldi\/\d/.test(e)?n.Vivaldi=A("Vivaldi"):/ Silk\/\d/.test(e)?n.Silk=A("Silk"):/ UCBrowser\/\d/.test(e)?n.UCBrowser=A("UCBrowser"):/ Phoebe\/\d/.test(e)?n.Phoebe=A("Phoebe"):n.Chrome=(o=>o[0]?o:n.Chromium)(A("Chrome"))):/ AppleWebKit\/\d/.test(e)?(n.WebKit=A("AppleWebKit"),/ CriOS \d/.test(e)?n.Chrome=A("CriOS"):/ FxiOS \d/.test(e)?n.Firefox=A("FxiOS"):/ EdgiOS\/\d/.test(e)?n.Edge=A("EdgiOS"):/ Version\/\d/.test(e)&&(n.Safari=A("Version"))):/ Trident\/\d/.test(e)&&(n.Trident=A("Trident"),n.InternetExplorer=(o=>o[0]?o:A("MSIE"))(A("rv")))),/[\[; ]FB(AN|_IAB)\//.test(e)&&(n.Facebook=A("FBAV")),/ Line\/\d/.test(e)&&(n.LINE=A("Line")),n})({}),this.Env={get:()=>[this.OS,this.UA].reduce((n,s)=>{for(const o in s)s[o]&&n.push(o);return n},[])}}}class Sn extends Gi{get iOSRequest(){const t=Hi(),e=Di();if(this.OS.iOS&&!this.OS.iPadOS)return"mobile";if(this.OS.iPadOS)return/\(iPad;/.test(e)||t&&/^iPad(OS)?$/.test(t.platform)?"mobile":"desktop"}}const ut=new Gi,J=new Sn;class ki{constructor(t){this.hidden=!0,this.destroyed=!1,this.currModules=[],this.frame=document.createElement("iframe"),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.frame.style.backgroundColor="#FFFFFF",this.source=t}async load(t=[]){return new Promise((e,i)=>{if(this.loader){const A=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...t].sort().join("|")){try{e(A)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new ct(A,t),this.currModules=t,this.comms=void 0;try{e(A)}catch{}return}this.frame.onload=()=>{const A=this.frame.contentWindow;this.loader=new ct(A,t),this.currModules=t;try{e(A)}catch{}},this.frame.onerror=A=>{try{i(A)}catch{}},this.frame.contentWindow.location.replace(this.source)})}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((t,e)=>{this.comms?.send("unfocus",void 0,i=>{this.comms?.halt(),t()})});this.comms?.halt()}}async show(t){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 gt(this.frame.contentWindow,this.source),new Promise((e,i)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{const A=()=>{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,ut.UA.WebKit&&this.comms?.send("force_webkit_recalc",void 0),e()};t!==void 0?this.comms?.send("go_progression",t,A):A()})})})}setCSSProperties(t){this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?this.comms?.resume():this.comms=new gt(this.frame.contentWindow,this.source)),this.comms?.send("update_properties",t),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 msg(){return this.comms}get ldr(){return this.loader}}class Ji{constructor(t,e){this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.pendingUpdates=new Map,this.container=t,this.currentCssProperties=e}async destroy(){let t=this.inprogress.values(),e=t.next();const i=[];for(;e.value;)i.push(e.value),e=t.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let A=this.pool.values(),n=A.next();for(;n.value;)await n.value.destroy(),n=A.next();this.pool.clear(),this.blobs.forEach(s=>URL.revokeObjectURL(s)),this.blobs.clear(),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}async update(t,e,i){const A=t.readingOrder.items;let n=A.findIndex(a=>a.href===e.href);if(n<0)throw Error(`Locator not found in reading order: ${e.href}`);const s=A[n].href;this.inprogress.has(s)&&await this.inprogress.get(s);const o=new Promise(async(a,h)=>{const c=[],g=[];t.readingOrder.items.forEach((l,f)=>{f!==n&&f!==n-1&&f!==n+1&&(c.includes(l.href)||c.push(l.href)),f===n&&(g.includes(l.href)||g.push(l.href))}),c.forEach(async l=>{g.includes(l)||this.pool.has(l)&&(await this.pool.get(l)?.destroy(),this.pool.delete(l))}),this.currentBaseURL!==void 0&&t.baseURL!==this.currentBaseURL&&(this.blobs.forEach(l=>URL.revokeObjectURL(l)),this.blobs.clear()),this.currentBaseURL=t.baseURL;const u=async l=>{if(this.pendingUpdates.has(l)&&this.pendingUpdates.get(l)?.inPool===!1){const F=this.blobs.get(l);F&&(URL.revokeObjectURL(F),this.blobs.delete(l),this.pendingUpdates.delete(l))}if(this.pool.has(l)){const F=this.pool.get(l);if(!this.blobs.has(l))await F.destroy(),this.pool.delete(l),this.pendingUpdates.delete(l);else{await F.load(i);return}}const f=t.readingOrder.findWithHref(l);if(!f)return;if(!this.blobs.has(l)){const S=await new Ke(t,this.currentBaseURL||"",f,this.currentCssProperties).build();this.blobs.set(l,S)}const E=new ki(this.blobs.get(l));l!==s&&await E.hide(),this.container.appendChild(E.iframe),await E.load(i),this.pool.set(l,E)};try{await Promise.all(g.map(l=>u(l)))}catch(l){h(l)}const M=this.pool.get(s);M?.source!==this._currentFrame?.source&&(await this._currentFrame?.hide(),M&&await M.load(i),M&&await M.show(e.locations.progression),this._currentFrame=M),a()});this.inprogress.set(s,o),await o,this.inprogress.delete(s)}setCSSProperties(t){if(!((i,A)=>{const n=Object.keys(i),s=Object.keys(A);if(n.length!==s.length)return!1;for(const o of n)if(i[o]!==A[o])return!1;return!0})(this.currentCssProperties||{},t)){this.currentCssProperties=t,this.pool.forEach(i=>{i.setCSSProperties(t)});for(const i of this.blobs.keys())this.pendingUpdates.set(i,{inPool:this.pool.has(i)})}}get currentFrames(){return[this._currentFrame]}get currentBounds(){const t={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(e=>{if(!e)return;const i=e.realSize;t.x=Math.min(t.x,i.x),t.y=Math.min(t.y,i.y),t.width+=i.width,t.height=Math.max(t.height,i.height),t.top=Math.min(t.top,i.top),t.right=Math.min(t.right,i.right),t.bottom=Math.min(t.bottom,i.bottom),t.left=Math.min(t.left,i.left)}),t}}var we,Wi;function Qn(){if(Wi)return we;Wi=1;function r(A){if(typeof A!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(A))}function t(A,n){for(var s="",o=0,a=-1,h=0,c,g=0;g<=A.length;++g){if(g<A.length)c=A.charCodeAt(g);else{if(c===47)break;c=47}if(c===47){if(!(a===g-1||h===1))if(a!==g-1&&h===2){if(s.length<2||o!==2||s.charCodeAt(s.length-1)!==46||s.charCodeAt(s.length-2)!==46){if(s.length>2){var u=s.lastIndexOf("/");if(u!==s.length-1){u===-1?(s="",o=0):(s=s.slice(0,u),o=s.length-1-s.lastIndexOf("/")),a=g,h=0;continue}}else if(s.length===2||s.length===1){s="",o=0,a=g,h=0;continue}}n&&(s.length>0?s+="/..":s="..",o=2)}else s.length>0?s+="/"+A.slice(a+1,g):s=A.slice(a+1,g),o=g-a-1;a=g,h=0}else c===46&&h!==-1?++h:h=-1}return s}function e(A,n){var s=n.dir||n.root,o=n.base||(n.name||"")+(n.ext||"");return s?s===n.root?s+o:s+A+o:o}var i={resolve:function(){for(var n="",s=!1,o,a=arguments.length-1;a>=-1&&!s;a--){var h;a>=0?h=arguments[a]:(o===void 0&&(o=process.cwd()),h=o),r(h),h.length!==0&&(n=h+"/"+n,s=h.charCodeAt(0)===47)}return n=t(n,!s),s?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(r(n),n.length===0)return".";var s=n.charCodeAt(0)===47,o=n.charCodeAt(n.length-1)===47;return n=t(n,!s),n.length===0&&!s&&(n="."),n.length>0&&o&&(n+="/"),s?"/"+n:n},isAbsolute:function(n){return r(n),n.length>0&&n.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var n,s=0;s<arguments.length;++s){var o=arguments[s];r(o),o.length>0&&(n===void 0?n=o:n+="/"+o)}return n===void 0?".":i.normalize(n)},relative:function(n,s){if(r(n),r(s),n===s||(n=i.resolve(n),s=i.resolve(s),n===s))return"";for(var o=1;o<n.length&&n.charCodeAt(o)===47;++o);for(var a=n.length,h=a-o,c=1;c<s.length&&s.charCodeAt(c)===47;++c);for(var g=s.length,u=g-c,M=h<u?h:u,l=-1,f=0;f<=M;++f){if(f===M){if(u>M){if(s.charCodeAt(c+f)===47)return s.slice(c+f+1);if(f===0)return s.slice(c+f)}else h>M&&(n.charCodeAt(o+f)===47?l=f:f===0&&(l=0));break}var E=n.charCodeAt(o+f),F=s.charCodeAt(c+f);if(E!==F)break;E===47&&(l=f)}var S="";for(f=o+l+1;f<=a;++f)(f===a||n.charCodeAt(f)===47)&&(S.length===0?S+="..":S+="/..");return S.length>0?S+s.slice(c+l):(c+=l,s.charCodeAt(c)===47&&++c,s.slice(c))},_makeLong:function(n){return n},dirname:function(n){if(r(n),n.length===0)return".";for(var s=n.charCodeAt(0),o=s===47,a=-1,h=!0,c=n.length-1;c>=1;--c)if(s=n.charCodeAt(c),s===47){if(!h){a=c;break}}else h=!1;return a===-1?o?"/":".":o&&a===1?"//":n.slice(0,a)},basename:function(n,s){if(s!==void 0&&typeof s!="string")throw new TypeError('"ext" argument must be a string');r(n);var o=0,a=-1,h=!0,c;if(s!==void 0&&s.length>0&&s.length<=n.length){if(s.length===n.length&&s===n)return"";var g=s.length-1,u=-1;for(c=n.length-1;c>=0;--c){var M=n.charCodeAt(c);if(M===47){if(!h){o=c+1;break}}else u===-1&&(h=!1,u=c+1),g>=0&&(M===s.charCodeAt(g)?--g===-1&&(a=c):(g=-1,a=u))}return o===a?a=u:a===-1&&(a=n.length),n.slice(o,a)}else{for(c=n.length-1;c>=0;--c)if(n.charCodeAt(c)===47){if(!h){o=c+1;break}}else a===-1&&(h=!1,a=c+1);return a===-1?"":n.slice(o,a)}},extname:function(n){r(n);for(var s=-1,o=0,a=-1,h=!0,c=0,g=n.length-1;g>=0;--g){var u=n.charCodeAt(g);if(u===47){if(!h){o=g+1;break}continue}a===-1&&(h=!1,a=g+1),u===46?s===-1?s=g:c!==1&&(c=1):s!==-1&&(c=-1)}return s===-1||a===-1||c===0||c===1&&s===a-1&&s===o+1?"":n.slice(s,a)},format:function(n){if(n===null||typeof n!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof n);return e("/",n)},parse:function(n){r(n);var s={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return s;var o=n.charCodeAt(0),a=o===47,h;a?(s.root="/",h=1):h=0;for(var c=-1,g=0,u=-1,M=!0,l=n.length-1,f=0;l>=h;--l){if(o=n.charCodeAt(l),o===47){if(!M){g=l+1;break}continue}u===-1&&(M=!1,u=l+1),o===46?c===-1?c=l:f!==1&&(f=1):c!==-1&&(f=-1)}return c===-1||u===-1||f===0||f===1&&c===u-1&&c===g+1?u!==-1&&(g===0&&a?s.base=s.name=n.slice(1,u):s.base=s.name=n.slice(g,u)):(g===0&&a?(s.name=n.slice(1,c),s.base=n.slice(1,u)):(s.name=n.slice(g,c),s.base=n.slice(g,u)),s.ext=n.slice(c,u)),g>0?s.dir=n.slice(0,g-1):a&&(s.dir="/"),s},sep:"/",delimiter:":",win32:null,posix:null};return i.posix=i,we=i,we}var Jt=Qn();class Wt{constructor(){}toFlag(t){return`readium-${t}-on`}toUnitless(t){return t.toString()}toPercentage(t,e=!1){return e||t>0&&t<=1?`${Math.round(t*100)}%`:`${t}%`}toVw(t){const e=Math.round(t*100);return`${Math.min(e,100)}vw`}toVh(t){const e=Math.round(t*100);return`${Math.min(e,100)}vh`}toPx(t){return`${t}px`}toRem(t){return`${t}rem`}}class Ee extends Wt{constructor(t){super(),this.a11yNormalize=t.a11yNormalize??null,this.bodyHyphens=t.bodyHyphens??null,this.fontFamily=t.fontFamily??null,this.fontWeight=t.fontWeight??null,this.letterSpacing=t.letterSpacing??null,this.ligatures=t.ligatures??null,this.lineHeight=t.lineHeight??null,this.noRuby=t.noRuby??null,this.paraIndent=t.paraIndent??null,this.paraSpacing=t.paraSpacing??null,this.textAlign=t.textAlign??null,this.wordSpacing=t.wordSpacing??null,this.zoom=t.zoom??null}toCSSProperties(){const t={};return this.a11yNormalize&&(t["--USER__a11yNormalize"]=this.toFlag("a11y")),this.bodyHyphens&&(t["--USER__bodyHyphens"]=this.bodyHyphens),this.fontFamily&&(t["--USER__fontFamily"]=this.fontFamily),this.fontWeight!=null&&(t["--USER__fontWeight"]=this.toUnitless(this.fontWeight)),this.letterSpacing!=null&&(t["--USER__letterSpacing"]=this.toRem(this.letterSpacing)),this.ligatures&&(t["--USER__ligatures"]=this.ligatures),this.lineHeight!=null&&(t["--USER__lineHeight"]=this.toUnitless(this.lineHeight)),this.noRuby&&(t["--USER__noRuby"]=this.toFlag("noRuby")),this.paraIndent!=null&&(t["--USER__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(t["--USER__paraSpacing"]=this.toRem(this.paraSpacing)),this.textAlign&&(t["--USER__textAlign"]=this.textAlign),this.wordSpacing!=null&&(t["--USER__wordSpacing"]=this.toRem(this.wordSpacing)),this.zoom!==null&&(t["--USER__zoom"]=this.toPercentage(this.zoom,!0)),t}}class Li{constructor(t){this.userProperties=t.userProperties}update(t){const e={a11yNormalize:t.textNormalization,bodyHyphens:typeof t.hyphens!="boolean"?null:t.hyphens?"auto":"none",fontFamily:t.fontFamily,fontWeight:t.fontWeight,letterSpacing:t.letterSpacing,ligatures:typeof t.ligatures!="boolean"?null:t.ligatures?"common-ligatures":"none",lineHeight:t.lineHeight,noRuby:t.noRuby,paraIndent:t.paragraphIndent,paraSpacing:t.paragraphSpacing,textAlign:t.textAlign,wordSpacing:t.wordSpacing,zoom:t.zoom};this.userProperties=new Ee(e)}}var O=(r=>(r.start="start",r.left="left",r.right="right",r.justify="justify",r))(O||{});const At={range:[0,100],step:1},yt={range:[.7,4],step:.05},K={range:[100,1e3],step:100},Ut={range:[50,250],step:10},Rt={range:[0,1],step:.125},Ct={range:[1,2],step:.1},nt={range:[20,100],step:1},St={range:[0,3],step:.25},Qt={range:[0,3],step:.25},zt={range:[0,2],step:.125},Yt={range:[.7,4],step:.05};function Oi(r,t){return r==null||t==null||r<=t?r:void 0}function Xi(r,t){return r==null||t==null||r>=t?r:void 0}function Q(r){return typeof r=="string"?r:r===null?null:void 0}function y(r){return typeof r=="boolean"||r==null?r:void 0}function Nt(r,t){if(r!==void 0)return r===null?null:t[r]!==void 0?r:void 0}function rt(r){return typeof r=="boolean"||typeof r=="number"&&r>=0?r:r===null?null:void 0}function I(r){if(r!==void 0)return r===null?null:r<0?void 0:r}function W(r,t){if(r===void 0)return;if(r===null)return null;const e=Math.min(...t),i=Math.max(...t);return r>=e&&r<=i?r:void 0}function Lt(r,t){return r===void 0?t:r}class mt{constructor(t={}){this.fontFamily=Q(t.fontFamily),this.fontWeight=W(t.fontWeight,K.range),this.hyphens=y(t.hyphens),this.letterSpacing=I(t.letterSpacing),this.ligatures=y(t.ligatures),this.lineHeight=I(t.lineHeight),this.noRuby=y(t.noRuby),this.paragraphIndent=I(t.paragraphIndent),this.paragraphSpacing=I(t.paragraphSpacing),this.textAlign=Nt(t.textAlign,O),this.textNormalization=y(t.textNormalization),this.wordSpacing=I(t.wordSpacing),this.zoom=W(t.zoom,Yt.range)}static serialize(t){const{...e}=t;return JSON.stringify(e)}static deserialize(t){try{const e=JSON.parse(t);return new mt(e)}catch(e){return console.error("Failed to deserialize preferences:",e),null}}merging(t){const e={...this};for(const i of Object.keys(t))t[i]!==void 0&&(e[i]=t[i]);return new mt(e)}}class Zi{constructor(t){this.fontFamily=Q(t.fontFamily)||null,this.fontWeight=W(t.fontWeight,K.range)||null,this.hyphens=y(t.hyphens)??null,this.letterSpacing=I(t.letterSpacing)||null,this.ligatures=y(t.ligatures)??null,this.lineHeight=I(t.lineHeight)||null,this.noRuby=y(t.noRuby)??!1,this.paragraphIndent=I(t.paragraphIndent)??null,this.paragraphSpacing=I(t.paragraphSpacing)??null,this.textAlign=Nt(t.textAlign,O)||null,this.textNormalization=y(t.textNormalization)??!1,this.wordSpacing=I(t.wordSpacing)||null,this.zoom=W(t.zoom,Yt.range)||1}}class Ie{constructor(t,e,i){this.fontFamily=null,this.fontWeight=null,this.hyphens=null,this.letterSpacing=null,this.ligatures=null,this.lineHeight=null,this.noRuby=null,this.paragraphIndent=null,this.paragraphSpacing=null,this.textAlign=null,this.textNormalization=null,this.wordSpacing=null,i&&(this.fontFamily=t.fontFamily||e.fontFamily||null,this.fontWeight=t.fontWeight!==void 0?t.fontWeight:e.fontWeight!==void 0?e.fontWeight:null,this.hyphens=typeof t.hyphens=="boolean"?t.hyphens:e.hyphens??null,this.letterSpacing=t.letterSpacing!==void 0?t.letterSpacing:e.letterSpacing!==void 0?e.letterSpacing:null,this.ligatures=typeof t.ligatures=="boolean"?t.ligatures:e.ligatures??null,this.lineHeight=t.lineHeight!==void 0?t.lineHeight:e.lineHeight!==void 0?e.lineHeight:null,this.noRuby=typeof t.noRuby=="boolean"?t.noRuby:e.noRuby??null,this.paragraphIndent=t.paragraphIndent!==void 0?t.paragraphIndent:e.paragraphIndent!==void 0?e.paragraphIndent:null,this.paragraphSpacing=t.paragraphSpacing!==void 0?t.paragraphSpacing:e.paragraphSpacing!==void 0?e.paragraphSpacing:null,this.textAlign=t.textAlign||e.textAlign||null,this.textNormalization=typeof t.textNormalization=="boolean"?t.textNormalization:e.textNormalization??null,this.wordSpacing=t.wordSpacing!==void 0?t.wordSpacing:e.wordSpacing!==void 0?e.wordSpacing:null),this.zoom=t.zoom!==void 0?t.zoom:e.zoom!==void 0?e.zoom:null}}class z{constructor({initialValue:t=null,effectiveValue:e,isEffective:i,onChange:A}){this._value=t,this._effectiveValue=e,this._isEffective=i,this._onChange=A}set value(t){this._value=t,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}clear(){this._value=null}}class N extends z{set value(t){this._value=t,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}clear(){this._value=null}toggle(){this._value=!this._value,this._onChange(this._value)}}class Fe extends z{constructor({initialValue:t=null,effectiveValue:e,isEffective:i,onChange:A,supportedValues:n}){super({initialValue:t,effectiveValue:e,isEffective:i,onChange:A}),this._supportedValues=n}set value(t){if(t&&!this._supportedValues.includes(t))throw new Error(`Value '${String(t)}' is not in the supported values for this preference.`);this._value=t,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}get supportedValues(){return this._supportedValues}clear(){this._value=null}}class U extends z{constructor({initialValue:t=null,effectiveValue:e,isEffective:i,onChange:A,supportedRange:n,step:s}){super({initialValue:t,effectiveValue:e,isEffective:i,onChange:A}),this._supportedRange=n,this._step=s,this._decimals=this._step.toString().includes(".")?this._step.toString().split(".")[1].length:0}set value(t){if(t&&(t<this._supportedRange[0]||t>this._supportedRange[1]))throw new Error(`Value '${String(t)}' is out of the supported range for this preference.`);this._value=t,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}get supportedRange(){return this._supportedRange}get step(){return this._step}increment(){this._value&&this._value<this._supportedRange[1]&&(this._value=Math.min(Math.round((this._value+this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[1]),this._onChange(this._value))}decrement(){this._value&&this._value>this._supportedRange[0]&&(this._value=Math.max(Math.round((this._value-this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[0]),this._onChange(this._value))}format(t){return t.toString()}clear(){this._value=null}}class ye{constructor(t,e,i){this.preferences=t,this.settings=e,this.metadata=i}clear(){this.preferences=new mt({})}updatePreference(t,e){this.preferences[t]=e}get isDisplayTransformable(){return this.metadata?.accessibility?.feature?.some(t=>t.value===ve.DISPLAY_TRANSFORMABILITY.value)??!1}get fontFamily(){return new z({initialValue:this.preferences.fontFamily,effectiveValue:this.settings.fontFamily||null,isEffective:this.isDisplayTransformable,onChange:t=>{this.updatePreference("fontFamily",t||null)}})}get fontWeight(){return new U({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.isDisplayTransformable,onChange:t=>{this.updatePreference("fontWeight",t||null)},supportedRange:K.range,step:K.step})}get hyphens(){return new N({initialValue:this.preferences.hyphens,effectiveValue:this.settings.hyphens||!1,isEffective:this.isDisplayTransformable,onChange:t=>{this.updatePreference("hyphens",t||null)}})}get letterSpacing(){return new U({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.isDisplayTransformable,onChange:t=>{this.updatePreference("letterSpacing",t||null)},supportedRange:Rt.range,step:Rt.step})}get ligatures(){return new N({initialValue:this.preferences.ligatures,effectiveValue:this.settings.ligatures||!0,isEffective:this.isDisplayTransformable,onChange:t=>{this.updatePreference("ligatures",t||null)}})}get lineHeight(){return new U({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.isDisplayTransformable,onChange:t=>{this.updatePreference("lineHeight",t||null)},supportedRange:Ct.range,step:Ct.step})}get noRuby(){return new N({initialValue:this.preferences.noRuby,effectiveValue:this.settings.noRuby||!1,isEffective:this.isDisplayTransformable,onChange:t=>{this.updatePreference("noRuby",t||null)}})}get paragraphIndent(){return new U({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.isDisplayTransformable,onChange:t=>{this.updatePreference("paragraphIndent",t||null)},supportedRange:St.range,step:St.step})}get paragraphSpacing(){return new U({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.isDisplayTransformable,onChange:t=>{this.updatePreference("paragraphSpacing",t||null)},supportedRange:Qt.range,step:Qt.step})}get textAlign(){return new Fe({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||O.start,isEffective:this.isDisplayTransformable,onChange:t=>{this.updatePreference("textAlign",t||null)},supportedValues:Object.values(O)})}get textNormalization(){return new N({initialValue:this.preferences.textNormalization,effectiveValue:this.settings.textNormalization||!1,isEffective:this.isDisplayTransformable,onChange:t=>{this.updatePreference("textNormalization",t||null)}})}get wordSpacing(){return new U({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.isDisplayTransformable,onChange:t=>{this.updatePreference("wordSpacing",t||null)},supportedRange:zt.range,step:zt.step})}get zoom(){return new U({initialValue:this.preferences.zoom,effectiveValue:this.settings.zoom||1,isEffective:CSS.supports("zoom","1")??!1,onChange:t=>{this.updatePreference("zoom",t||null)},supportedRange:Yt.range,step:Yt.step})}}const zn=r=>({frameLoaded:r.frameLoaded||(()=>{}),positionChanged:r.positionChanged||(()=>{}),tap:r.tap||(()=>!1),click:r.click||(()=>!1),zoom:r.zoom||(()=>{}),scroll:r.scroll||(()=>{}),customEvent:r.customEvent||(()=>{}),handleLocator:r.handleLocator||(()=>!1),textSelected:r.textSelected||(()=>{})});class Ki extends ne{constructor(t,e,i,A=void 0,n={preferences:{},defaults:{}}){if(super(),this.currentIndex=0,this._preferencesEditor=null,this.webViewport={readingOrder:[],progressions:new Map,positions:null},this.pub=e,this.container=t,this.listeners=zn(i),this._preferences=new mt(n.preferences),this._defaults=new Zi(n.defaults),this._settings=new Ie(this._preferences,this._defaults,this.hasDisplayTransformability),this._css=new Li({userProperties:new Ee({zoom:this._settings.zoom})}),A&&typeof A.copyWithLocations=="function"){this.currentLocation=A;const s=this.pub.readingOrder.findIndexWithHref(A.href);s>=0&&(this.currentIndex=s)}else this.currentLocation=this.createCurrentLocator()}async load(){await this.updateCSS(!1);const t=this.compileCSSProperties(this._css);this.framePool=new Ji(this.container,t),await this.apply()}get settings(){return Object.freeze({...this._settings})}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new ye(this._preferences,this.settings,this.pub.metadata)),this._preferencesEditor}async submitPreferences(t){this._preferences=this._preferences.merging(t),await this.applyPreferences()}async applyPreferences(){this._settings=new Ie(this._preferences,this._defaults,this.hasDisplayTransformability),this._preferencesEditor!==null&&(this._preferencesEditor=new ye(this._preferences,this.settings,this.pub.metadata)),await this.updateCSS(!0)}async updateCSS(t){this._css.update(this._settings),t&&await this.commitCSS(this._css)}compileCSSProperties(t){const e={};for(const[i,A]of Object.entries(t.userProperties.toCSSProperties()))e[i]=A;return e}async commitCSS(t){const e=this.compileCSSProperties(t);this.framePool.setCSSProperties(e)}get _cframes(){return this.framePool.currentFrames}get hasDisplayTransformability(){return this.pub.metadata?.accessibility?.feature?.some(t=>t.value===ve.DISPLAY_TRANSFORMABILITY.value)??!1}eventListener(t,e){switch(t){case"_pong":this.listeners.frameLoaded(this.framePool.currentFrames[0].iframe.contentWindow),this.listeners.positionChanged(this.currentLocation);break;case"first_visible_locator":const i=at.deserialize(e);if(!i)break;this.currentLocation=new at({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(e);break;case"click":case"tap":const A=e;if(A.interactiveElement){const n=new DOMParser().parseFromString(A.interactiveElement,"text/html").body.children[0];if(n.nodeType===n.ELEMENT_NODE&&n.nodeName==="A"&&n.hasAttribute("href")){const s=n.attributes.getNamedItem("href")?.value;if(s.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[s.substring(1)]}),!1,()=>{});else if(s.startsWith("mailto:")||s.startsWith("tel:"))this.listeners.handleLocator(new q({href:s}).locator);else try{let o;if(s.startsWith("http://")||s.startsWith("https://"))o=s;else if(this.currentLocation.href.startsWith("http://")||this.currentLocation.href.startsWith("https://")){const h=new URL(this.currentLocation.href);o=new URL(s,h).href}else o=Jt.join(Jt.dirname(this.currentLocation.href),s);const a=this.pub.readingOrder.findWithHref(o);a?this.goLink(a,!1,()=>{}):(console.warn(`Internal link not found in readingOrder: ${o}`),this.listeners.handleLocator(new q({href:s}).locator))}catch(o){console.warn(`Couldn't resolve internal link for ${s}: ${o}`),this.listeners.handleLocator(new q({href:s}).locator)}}else console.log("Clicked on",n)}else if(t==="click"?this.listeners.click(A):this.listeners.tap(A))break;break;case"scroll":this.listeners.scroll(e);break;case"zoom":this.listeners.zoom(e);break;case"progress":this.syncLocation(e);break;case"log":console.log(this.framePool.currentFrames[0]?.source?.split("/")[3],...e);break;default:this.listeners.customEvent(t,e);break}}determineModules(){return Array.from(kt.keys()).filter(e=>yn.includes(e))}attachListener(){this.framePool.currentFrames[0]?.msg&&(this.framePool.currentFrames[0].msg.listener=(t,e)=>{this.eventListener(t,e)})}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(){await this.framePool?.destroy()}async changeResource(t){if(t===0)return!1;const e=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),i=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,e+t));return i===e?!1:(this.currentIndex=i,this.currentLocation=this.createCurrentLocator(),await this.apply(),!0)}updateViewport(t){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,t),this.currentLocation.locations?.position!==void 0&&(this.webViewport.positions=[this.currentLocation.locations.position]))}async syncLocation(t){const e=t;this.currentLocation&&(this.currentLocation=this.currentLocation.copyWithLocations({progression:e.start})),this.updateViewport(e),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(t,e){this.changeResource(-1).then(i=>{e(i)})}goForward(t,e){this.changeResource(1).then(i=>{e(i)})}get currentLocator(){return this.currentLocation}get viewport(){return this.webViewport}get isScrollStart(){const t=this.viewport.readingOrder[0];return this.viewport.progressions.get(t)?.start===0}get isScrollEnd(){const t=this.viewport.readingOrder[this.viewport.readingOrder.length-1];return this.viewport.progressions.get(t)?.end===1}get canGoBackward(){const t=this.pub.readingOrder.items[0]?.href;return!(this.viewport.progressions.has(t)&&this.viewport.progressions.get(t)?.start===0)}get canGoForward(){const t=this.pub.readingOrder.items[this.pub.readingOrder.items.length-1]?.href;return!(this.viewport.progressions.has(t)&&this.viewport.progressions.get(t)?.end===1)}get readingProgression(){return this.pub.metadata.effectiveReadingProgression}get publication(){return this.pub}async loadLocator(t,e){let i=!1,A=typeof t.locations.getCssSelector=="function"&&t.locations.getCssSelector();if(t.text?.highlight?i=await new Promise((a,h)=>{this.framePool.currentFrames[0].msg.send("go_text",A?[t.text?.serialize(),A]:t.text?.serialize(),c=>a(c))}):A&&(i=await new Promise((a,h)=>{this.framePool.currentFrames[0].msg.send("go_text",["",A],c=>a(c))})),i){e(i);return}const n=typeof t.locations.htmlId=="function"&&t.locations.htmlId();if(n&&(i=await new Promise((a,h)=>{this.framePool.currentFrames[0].msg.send("go_id",n,c=>a(c))})),i){e(i);return}const s=t?.locations?.progression;s&&s>0?i=await new Promise((a,h)=>{this.framePool.currentFrames[0].msg.send("go_progression",s,c=>a(c))}):i=!0,e(i)}go(t,e,i){const A=t.href.split("#")[0];if(!this.pub.readingOrder.findWithHref(A))return i(this.listeners.handleLocator(t));const s=this.pub.readingOrder.findIndexWithHref(A);s>=0&&(this.currentIndex=s),this.currentLocation=this.createCurrentLocator(),this.apply().then(()=>this.loadLocator(t,o=>i(o))).then(()=>{this.attachListener()})}goLink(t,e,i){return this.go(t.locator,e,i)}createCurrentLocator(){const e=this.pub.readingOrder.items[this.currentIndex];if(!e)throw new Error("No current resource available");const A=this.currentLocation&&this.currentLocation.href===e.href&&this.currentLocation.locations.progression?this.currentLocation.locations.progression:0;return this.pub.manifest.locatorFromLink(e)||new at({href:e.href,type:e.type||"text/html",locations:new V({fragments:[],progression:A,position:this.currentIndex+1})})}}const Yn=Ki,Nn=`/*!
|
|
294
294
|
* Readium CSS v.2.0.0-beta.19
|
|
295
295
|
* Copyright (c) 2017–2025. Readium Foundation. All rights reserved.
|
|
296
296
|
* Use of this source code is governed by a BSD-style license which is detailed in the
|
|
@@ -303,7 +303,7 @@ if(window.onload) window.onload = new Proxy(window.onload, {
|
|
|
303
303
|
* L. Le Meur
|
|
304
304
|
* Mickaël Menu
|
|
305
305
|
* k_taka
|
|
306
|
-
*/@namespace url(http://www.w3.org/1999/xhtml);@namespace epub url(http://www.idpf.org/2007/ops);@namespace m url(http://www.w3.org/1998/Math/MathML);@namespace svg url(http://www.w3.org/2000/svg);:root{--RS__viewportWidth:100%;--RS__pageGutter:0;--RS__defaultLineLength:40rem;--RS__colGap:0;--RS__colCount:1;--RS__colWidth:100vw}@page{margin:0!important}:root{position:relative;-webkit-column-width:var(--RS__colWidth);-moz-column-width:var(--RS__colWidth);column-width:var(--RS__colWidth);-webkit-column-count:var(--RS__colCount);-moz-column-count:var(--RS__colCount);column-count:var(--RS__colCount);-webkit-column-gap:var(--RS__colGap);-moz-column-gap:var(--RS__colGap);column-gap:var(--RS__colGap);-moz-column-fill:auto;column-fill:auto;width:var(--RS__viewportWidth);height:100vh;max-width:var(--RS__viewportWidth);max-height:100vh;min-width:var(--RS__viewportWidth);min-height:100vh;padding:0!important;margin:0!important;font-size:1rem!important;box-sizing:border-box;-webkit-touch-callout:none}body{width:100%;max-width:var(--RS__defaultLineLength)!important;padding:0 var(--RS__pageGutter)!important;margin:0 auto!important;box-sizing:border-box}:root:not([style*=readium-noOverflow-on]) body{overflow:hidden}@supports (overflow: clip){:root:not([style*=readium-noOverflow-on]){overflow:clip}:root:not([style*=readium-noOverflow-on]) body{overflow:clip;overflow-clip-margin:content-box}}:root[style*=readium-scroll-on]{-webkit-columns:auto auto!important;-moz-columns:auto auto!important;columns:auto auto!important;width:auto!important;height:auto!important;max-width:none!important;max-height:none!important;min-width:0!important;min-height:0!important}:root[style*=readium-scroll-on] body{max-width:var(--RS__defaultLineLength)!important;box-sizing:border-box!important}:root[style*=readium-scroll-on]:not([style*=readium-noOverflow-on]) body{overflow:auto}@supports (overflow: clip){:root[style*=readium-scroll-on]:not([style*=readium-noOverflow-on]){overflow:auto}:root[style*=readium-scroll-on]:not([style*=readium-noOverflow-on]) body{overflow:clip}}:root[style*=readium-scroll-on][style*=--RS__scrollPaddingTop] body{padding-top:var(--RS__scrollPaddingTop)!important}:root[style*=readium-scroll-on][style*=--RS__scrollPaddingBottom] body{padding-bottom:var(--RS__scrollPaddingBottom)!important}:root[style*=readium-scroll-on][style*=--RS__scrollPaddingLeft] body{padding-left:var(--RS__scrollPaddingLeft)!important}:root[style*=readium-scroll-on][style*=--RS__scrollPaddingRight] body{padding-right:var(--RS__scrollPaddingRight)!important}:root[style*=--USER__backgroundColor]{background-color:var(--USER__backgroundColor)!important}:root[style*=--USER__backgroundColor] *{background-color:transparent!important}:root[style*=--USER__textColor]{color:var(--USER__textColor)!important}:root[style*=--USER__textColor] *:not(a){color:inherit!important;background-color:transparent!important;border-color:currentcolor!important}:root[style*=--USER__textColor] svg text{fill:currentcolor!important;stroke:none!important}:root[style*=--USER__linkColor] a:link,:root[style*=--USER__linkColor] a:link *{color:var(--USER__linkColor)!important}:root[style*=--USER__visitedColor] a:visited,:root[style*=--USER__visitedColor] a:visited *{color:var(--USER__visitedColor)!important}:root[style*=--USER__selectionBackgroundColor][style*=--USER__selectionTextColor] ::-moz-selection{color:var(--USER__selectionTextColor)!important;background-color:var(--USER__selectionBackgroundColor)!important}:root[style*=--USER__selectionBackgroundColor][style*=--USER__selectionTextColor] ::selection{color:var(--USER__selectionTextColor)!important;background-color:var(--USER__selectionBackgroundColor)!important}:root[style*=--USER__colCount]{-webkit-column-count:var(--USER__colCount);-moz-column-count:var(--USER__colCount);column-count:var(--USER__colCount);--RS__colWidth:auto}:root[style*="--USER__colCount: 0"],:root[style*="--USER__colCount:0"]{-webkit-column-count:1;-moz-column-count:1;column-count:1}:root[style*="--USER__colCount: 0"],:root[style*="--USER__colCount:0"],:root[style*="--USER__colCount: 1"],:root[style*="--USER__colCount:1"]{--RS__colWidth:100vw}:root[style*=--USER__lineLength] body{max-width:var(--USER__lineLength)!important}:root[style*=--USER__textAlign]{text-align:var(--USER__textAlign)}:root[style*=--USER__textAlign] body,:root[style*=--USER__textAlign] p:not(blockquote p):not(figcaption p):not(hgroup p),:root[style*=--USER__textAlign] li,:root[style*=--USER__textAlign] dd{text-align:var(--USER__textAlign)!important;-moz-text-align-last:auto!important;-epub-text-align-last:auto!important;text-align-last:auto!important}:root[style*=--USER__bodyHyphens]{-webkit-hyphens:var(--USER__bodyHyphens)!important;-moz-hyphens:var(--USER__bodyHyphens)!important;-ms-hyphens:var(--USER__bodyHyphens)!important;-epub-hyphens:var(--USER__bodyHyphens)!important;hyphens:var(--USER__bodyHyphens)!important}:root[style*=--USER__bodyHyphens] body,:root[style*=--USER__bodyHyphens] p,:root[style*=--USER__bodyHyphens] li,:root[style*=--USER__bodyHyphens] div,:root[style*=--USER__bodyHyphens] dd{-webkit-hyphens:inherit;-moz-hyphens:inherit;-ms-hyphens:inherit;-epub-hyphens:inherit;hyphens:inherit}:root[style*=--USER__fontFamily]{font-family:var(--USER__fontFamily)!important}:root[style*=--USER__fontFamily] *{font-family:revert!important}:root[style*=AccessibleDfA]{font-family:AccessibleDfA,Verdana,Tahoma,Trebuchet MS,sans-serif!important}:root[style*="IA Writer Duospace"]{font-family:IA Writer Duospace,Menlo,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier,monospace!important}:root[style*=AccessibleDfA],:root[style*="IA Writer Duospace"],:root[style*=readium-a11y-on]{font-style:normal!important;font-weight:400!important}:root[style*=AccessibleDfA] *:not(code):not(var):not(kbd):not(samp),:root[style*="IA Writer Duospace"] *:not(code):not(var):not(kbd):not(samp),:root[style*=readium-a11y-on] *:not(code):not(var):not(kbd):not(samp){font-family:inherit!important;font-style:inherit!important;font-weight:inherit!important}:root[style*=AccessibleDfA] *,:root[style*="IA Writer Duospace"] *,:root[style*=readium-a11y-on] *{text-decoration:none!important;font-variant-caps:normal!important;font-variant-numeric:normal!important;font-variant-position:normal!important}:root[style*=AccessibleDfA] sup,:root[style*="IA Writer Duospace"] sup,:root[style*=readium-a11y-on] sup,:root[style*=AccessibleDfA] sub,:root[style*="IA Writer Duospace"] sub,:root[style*=readium-a11y-on] sub{font-size:1rem!important;vertical-align:baseline!important}:root:not([style*=readium-deprecatedFontSize-on]):not([style*=readium-iOSPatch-on])[style*=--USER__fontSize] body{zoom:var(--USER__fontSize)!important}:root[style*=readium-iOSPatch-on][style*=--USER__fontSize] body{-webkit-text-size-adjust:var(--USER__fontSize)!important}@supports not (zoom: 1){:root[style*=--USER__fontSize]{font-size:var(--USER__fontSize)!important}}:root[style*=readium-deprecatedFontSize-on][style*=--USER__fontSize]{font-size:var(--USER__fontSize)!important}:root[style*=--USER__lineHeight]{line-height:var(--USER__lineHeight)!important}:root[style*=--USER__lineHeight] body,:root[style*=--USER__lineHeight] p,:root[style*=--USER__lineHeight] li,:root[style*=--USER__lineHeight] div{line-height:inherit}:root[style*=--USER__paraSpacing] p{margin-top:var(--USER__paraSpacing)!important;margin-bottom:var(--USER__paraSpacing)!important}:root[style*=--USER__paraIndent] p{text-indent:var(--USER__paraIndent)!important}:root[style*=--USER__paraIndent] p *,:root[style*=--USER__paraIndent] p:first-letter{text-indent:0!important}:root[style*=--USER__wordSpacing] h1,:root[style*=--USER__wordSpacing] h2,:root[style*=--USER__wordSpacing] h3,:root[style*=--USER__wordSpacing] h4,:root[style*=--USER__wordSpacing] h5,:root[style*=--USER__wordSpacing] h6,:root[style*=--USER__wordSpacing] p,:root[style*=--USER__wordSpacing] li,:root[style*=--USER__wordSpacing] div,:root[style*=--USER__wordSpacing] dt,:root[style*=--USER__wordSpacing] dd{word-spacing:var(--USER__wordSpacing)}:root[style*=--USER__letterSpacing] h1,:root[style*=--USER__letterSpacing] h2,:root[style*=--USER__letterSpacing] h3,:root[style*=--USER__letterSpacing] h4,:root[style*=--USER__letterSpacing] h5,:root[style*=--USER__letterSpacing] h6,:root[style*=--USER__letterSpacing] p,:root[style*=--USER__letterSpacing] li,:root[style*=--USER__letterSpacing] div,:root[style*=--USER__letterSpacing] dt,:root[style*=--USER__letterSpacing] dd{letter-spacing:var(--USER__letterSpacing);font-variant:none}:root[style*=--USER__fontWeight] body{font-weight:var(--USER__fontWeight)!important}:root[style*=--USER__fontWeight] b,:root[style*=--USER__fontWeight] strong{font-weight:bolder}:root[style*=--USER__fontWidth] body{font-stretch:var(--USER__fontWidth)!important}:root[style*=--USER__fontOpticalSizing] body{font-optical-sizing:var(--USER__fontOpticalSizing)!important}:root[style*=readium-blend-on] svg,:root[style*=readium-blend-on] img{background-color:transparent!important;mix-blend-mode:multiply!important}:root[style*=--USER__darkenImages] img{-webkit-filter:brightness(var(--USER__darkenImages))!important;filter:brightness(var(--USER__darkenImages))!important}:root[style*=readium-darken-on] img{-webkit-filter:brightness(80%)!important;filter:brightness(80%)!important}:root[style*=--USER__invertImages] img{-webkit-filter:invert(var(--USER__invertImages))!important;filter:invert(var(--USER__invertImages))!important}:root[style*=readium-invert-on] img{-webkit-filter:invert(100%)!important;filter:invert(100%)!important}:root[style*=--USER__darkenImages][style*=--USER__invertImages] img{-webkit-filter:brightness(var(--USER__darkenImages)) invert(var(--USER__invertImages))!important;filter:brightness(var(--USER__darkenImages)) invert(var(--USER__invertImages))!important}:root[style*=readium-darken-on][style*=--USER__invertImages] img{-webkit-filter:brightness(80%) invert(var(--USER__invertImages))!important;filter:brightness(80%) invert(var(--USER__invertImages))!important}:root[style*=--USER__darkenImages][style*=readium-invert-on] img{-webkit-filter:brightness(var(--USER__darkenImages)) invert(100%)!important;filter:brightness(var(--USER__darkenImages)) invert(100%)!important}:root[style*=readium-darken-on][style*=readium-invert-on] img{-webkit-filter:brightness(80%) invert(100%)!important;filter:brightness(80%) invert(100%)!important}:root[style*=--USER__invertGaiji] img[class*=gaiji]{-webkit-filter:invert(var(--USER__invertGaiji))!important;filter:invert(var(--USER__invertGaiji))!important}:root[style*=readium-invertGaiji-on] img[class*=gaiji]{-webkit-filter:invert(100%)!important;filter:invert(100%)!important}:root[style*=readium-normalize-on]{--USER__typeScale:1.2}:root[style*=readium-normalize-on] p,:root[style*=readium-normalize-on] li,:root[style*=readium-normalize-on] div,:root[style*=readium-normalize-on] pre,:root[style*=readium-normalize-on] dd{font-size:1rem!important}:root[style*=readium-normalize-on] h1{font-size:1.75rem!important;font-size:calc(((1rem * var(--USER__typeScale)) * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-normalize-on] h2{font-size:1.5rem!important;font-size:calc((1rem * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-normalize-on] h3{font-size:1.25rem!important;font-size:calc(1rem * var(--USER__typeScale))!important}:root[style*=readium-normalize-on] h4,:root[style*=readium-normalize-on] h5,:root[style*=readium-normalize-on] h6{font-size:1rem!important}:root[style*=readium-normalize-on] small{font-size:smaller!important}:root[style*=readium-normalize-on] sub,:root[style*=readium-normalize-on] sup{font-size:67.5%!important}:root[style*=readium-normalize-on][style*=--USER__typeScale] h1{font-size:calc(((1rem * var(--USER__typeScale)) * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-normalize-on][style*=--USER__typeScale] h2{font-size:calc((1rem * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-normalize-on][style*=--USER__typeScale] h3{font-size:calc(1rem * var(--USER__typeScale))!important}:root[style*=readium-iPadOSPatch-on] body{-webkit-text-size-adjust:none}:root[style*=readium-iPadOSPatch-on] p,:root[style*=readium-iPadOSPatch-on] h1,:root[style*=readium-iPadOSPatch-on] h2,:root[style*=readium-iPadOSPatch-on] h3,:root[style*=readium-iPadOSPatch-on] h4,:root[style*=readium-iPadOSPatch-on] h5,:root[style*=readium-iPadOSPatch-on] h6,:root[style*=readium-iPadOSPatch-on] li,:root[style*=readium-iPadOSPatch-on] th,:root[style*=readium-iPadOSPatch-on] td,:root[style*=readium-iPadOSPatch-on] dt,:root[style*=readium-iPadOSPatch-on] dd,:root[style*=readium-iPadOSPatch-on] pre,:root[style*=readium-iPadOSPatch-on] address,:root[style*=readium-iPadOSPatch-on] details,:root[style*=readium-iPadOSPatch-on] summary,:root[style*=readium-iPadOSPatch-on] figcaption,:root[style*=readium-iPadOSPatch-on] div:not(:has(p,h1,h2,h3,h4,h5,h6,li,th,td,dt,dd,pre,address,aside,details,figcaption,summary)),:root[style*=readium-iPadOSPatch-on] aside:not(:has(p,h1,h2,h3,h4,h5,h6,li,th,td,dt,dd,pre,address,aside,details,figcaption,summary)){-webkit-text-zoom:reset}:root[style*=readium-iPadOSPatch-on] abbr,:root[style*=readium-iPadOSPatch-on] b,:root[style*=readium-iPadOSPatch-on] bdi,:root[style*=readium-iPadOSPatch-on] bdo,:root[style*=readium-iPadOSPatch-on] cite,:root[style*=readium-iPadOSPatch-on] code,:root[style*=readium-iPadOSPatch-on] dfn,:root[style*=readium-iPadOSPatch-on] em,:root[style*=readium-iPadOSPatch-on] i,:root[style*=readium-iPadOSPatch-on] kbd,:root[style*=readium-iPadOSPatch-on] mark,:root[style*=readium-iPadOSPatch-on] q,:root[style*=readium-iPadOSPatch-on] rp,:root[style*=readium-iPadOSPatch-on] rt,:root[style*=readium-iPadOSPatch-on] ruby,:root[style*=readium-iPadOSPatch-on] s,:root[style*=readium-iPadOSPatch-on] samp,:root[style*=readium-iPadOSPatch-on] small,:root[style*=readium-iPadOSPatch-on] span,:root[style*=readium-iPadOSPatch-on] strong,:root[style*=readium-iPadOSPatch-on] sub,:root[style*=readium-iPadOSPatch-on] sup,:root[style*=readium-iPadOSPatch-on] time,:root[style*=readium-iPadOSPatch-on] u,:root[style*=readium-iPadOSPatch-on] var{-webkit-text-zoom:normal}:root[style*=readium-iPadOSPatch-on] p:not(:has(b,cite,em,i,q,s,small,span,strong)):first-line{-webkit-text-zoom:normal}`,Tn=`/*!
|
|
306
|
+
*/@namespace url(http://www.w3.org/1999/xhtml);@namespace epub url(http://www.idpf.org/2007/ops);@namespace m url(http://www.w3.org/1998/Math/MathML);@namespace svg url(http://www.w3.org/2000/svg);:root{--RS__viewportWidth:100%;--RS__pageGutter:0;--RS__defaultLineLength:40rem;--RS__colGap:0;--RS__colCount:1;--RS__colWidth:100vw}@page{margin:0!important}:root{position:relative;-webkit-column-width:var(--RS__colWidth);-moz-column-width:var(--RS__colWidth);column-width:var(--RS__colWidth);-webkit-column-count:var(--RS__colCount);-moz-column-count:var(--RS__colCount);column-count:var(--RS__colCount);-webkit-column-gap:var(--RS__colGap);-moz-column-gap:var(--RS__colGap);column-gap:var(--RS__colGap);-moz-column-fill:auto;column-fill:auto;width:var(--RS__viewportWidth);height:100vh;max-width:var(--RS__viewportWidth);max-height:100vh;min-width:var(--RS__viewportWidth);min-height:100vh;padding:0!important;margin:0!important;font-size:1rem!important;box-sizing:border-box;-webkit-touch-callout:none}body{width:100%;max-width:var(--RS__defaultLineLength)!important;padding:0 var(--RS__pageGutter)!important;margin:0 auto!important;box-sizing:border-box}:root:not([style*=readium-noOverflow-on]) body{overflow:hidden}@supports (overflow: clip){:root:not([style*=readium-noOverflow-on]){overflow:clip}:root:not([style*=readium-noOverflow-on]) body{overflow:clip;overflow-clip-margin:content-box}}:root[style*=readium-scroll-on]{-webkit-columns:auto auto!important;-moz-columns:auto auto!important;columns:auto auto!important;width:auto!important;height:auto!important;max-width:none!important;max-height:none!important;min-width:0!important;min-height:0!important}:root[style*=readium-scroll-on] body{max-width:var(--RS__defaultLineLength)!important;box-sizing:border-box!important}:root[style*=readium-scroll-on]:not([style*=readium-noOverflow-on]) body{overflow:auto}@supports (overflow: clip){:root[style*=readium-scroll-on]:not([style*=readium-noOverflow-on]){overflow:auto}:root[style*=readium-scroll-on]:not([style*=readium-noOverflow-on]) body{overflow:clip}}:root[style*=readium-scroll-on][style*=--RS__scrollPaddingTop] body{padding-top:var(--RS__scrollPaddingTop)!important}:root[style*=readium-scroll-on][style*=--RS__scrollPaddingBottom] body{padding-bottom:var(--RS__scrollPaddingBottom)!important}:root[style*=readium-scroll-on][style*=--RS__scrollPaddingLeft] body{padding-left:var(--RS__scrollPaddingLeft)!important}:root[style*=readium-scroll-on][style*=--RS__scrollPaddingRight] body{padding-right:var(--RS__scrollPaddingRight)!important}:root[style*=--USER__backgroundColor]{background-color:var(--USER__backgroundColor)!important}:root[style*=--USER__backgroundColor] *{background-color:transparent!important}:root[style*=--USER__textColor]{color:var(--USER__textColor)!important}:root[style*=--USER__textColor] *:not(a){color:inherit!important;background-color:transparent!important;border-color:currentcolor!important}:root[style*=--USER__textColor] svg text{fill:currentcolor!important;stroke:none!important}:root[style*=--USER__linkColor] a:link,:root[style*=--USER__linkColor] a:link *{color:var(--USER__linkColor)!important}:root[style*=--USER__visitedColor] a:visited,:root[style*=--USER__visitedColor] a:visited *{color:var(--USER__visitedColor)!important}:root[style*=--USER__selectionBackgroundColor][style*=--USER__selectionTextColor] ::-moz-selection{color:var(--USER__selectionTextColor)!important;background-color:var(--USER__selectionBackgroundColor)!important}:root[style*=--USER__selectionBackgroundColor][style*=--USER__selectionTextColor] ::selection{color:var(--USER__selectionTextColor)!important;background-color:var(--USER__selectionBackgroundColor)!important}:root[style*=--USER__colCount]{-webkit-column-count:var(--USER__colCount);-moz-column-count:var(--USER__colCount);column-count:var(--USER__colCount);--RS__colWidth:auto}:root[style*="--USER__colCount: 0"],:root[style*="--USER__colCount:0"]{-webkit-column-count:1;-moz-column-count:1;column-count:1}:root[style*="--USER__colCount: 0"],:root[style*="--USER__colCount:0"],:root[style*="--USER__colCount: 1"],:root[style*="--USER__colCount:1"]{--RS__colWidth:100vw}:root[style*=--USER__lineLength] body{max-width:var(--USER__lineLength)!important}:root[style*=--USER__textAlign]{text-align:var(--USER__textAlign)}:root[style*=--USER__textAlign] body,:root[style*=--USER__textAlign] p:not(blockquote p):not(figcaption p):not(hgroup p),:root[style*=--USER__textAlign] li,:root[style*=--USER__textAlign] dd{text-align:var(--USER__textAlign)!important;-moz-text-align-last:auto!important;-epub-text-align-last:auto!important;text-align-last:auto!important}:root[style*=--USER__bodyHyphens]{-webkit-hyphens:var(--USER__bodyHyphens)!important;-moz-hyphens:var(--USER__bodyHyphens)!important;-ms-hyphens:var(--USER__bodyHyphens)!important;-epub-hyphens:var(--USER__bodyHyphens)!important;hyphens:var(--USER__bodyHyphens)!important}:root[style*=--USER__bodyHyphens] body,:root[style*=--USER__bodyHyphens] p,:root[style*=--USER__bodyHyphens] li,:root[style*=--USER__bodyHyphens] div,:root[style*=--USER__bodyHyphens] dd{-webkit-hyphens:inherit;-moz-hyphens:inherit;-ms-hyphens:inherit;-epub-hyphens:inherit;hyphens:inherit}:root[style*=--USER__fontFamily]{font-family:var(--USER__fontFamily)!important}:root[style*=--USER__fontFamily] *{font-family:revert!important}:root[style*=AccessibleDfA]{font-family:AccessibleDfA,Verdana,Tahoma,Trebuchet MS,sans-serif!important}:root[style*="IA Writer Duospace"]{font-family:IA Writer Duospace,Menlo,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier,monospace!important}:root[style*=AccessibleDfA],:root[style*="IA Writer Duospace"],:root[style*=readium-a11y-on]{font-style:normal!important;font-weight:400!important}:root[style*=AccessibleDfA] *:not(code):not(var):not(kbd):not(samp),:root[style*="IA Writer Duospace"] *:not(code):not(var):not(kbd):not(samp),:root[style*=readium-a11y-on] *:not(code):not(var):not(kbd):not(samp){font-family:inherit!important;font-style:inherit!important;font-weight:inherit!important}:root[style*=AccessibleDfA] *,:root[style*="IA Writer Duospace"] *,:root[style*=readium-a11y-on] *{text-decoration:none!important;font-variant-caps:normal!important;font-variant-numeric:normal!important;font-variant-position:normal!important}:root[style*=AccessibleDfA] sup,:root[style*="IA Writer Duospace"] sup,:root[style*=readium-a11y-on] sup,:root[style*=AccessibleDfA] sub,:root[style*="IA Writer Duospace"] sub,:root[style*=readium-a11y-on] sub{font-size:1rem!important;vertical-align:baseline!important}:root:not([style*=readium-deprecatedFontSize-on]):not([style*=readium-iOSPatch-on])[style*=--USER__fontSize] body{zoom:var(--USER__fontSize)!important}:root[style*=readium-iOSPatch-on][style*=--USER__fontSize] body{-webkit-text-size-adjust:var(--USER__fontSize)!important}@supports not (zoom: 1){:root[style*=--USER__fontSize]{font-size:var(--USER__fontSize)!important}}:root[style*=readium-deprecatedFontSize-on][style*=--USER__fontSize]{font-size:var(--USER__fontSize)!important}:root[style*=--USER__lineHeight]{line-height:var(--USER__lineHeight)!important}:root[style*=--USER__lineHeight] body,:root[style*=--USER__lineHeight] p,:root[style*=--USER__lineHeight] li,:root[style*=--USER__lineHeight] div{line-height:inherit}:root[style*=--USER__paraSpacing] p{margin-top:var(--USER__paraSpacing)!important;margin-bottom:var(--USER__paraSpacing)!important}:root[style*=--USER__paraIndent] p{text-indent:var(--USER__paraIndent)!important}:root[style*=--USER__paraIndent] p *,:root[style*=--USER__paraIndent] p:first-letter{text-indent:0!important}:root[style*=--USER__wordSpacing] h1,:root[style*=--USER__wordSpacing] h2,:root[style*=--USER__wordSpacing] h3,:root[style*=--USER__wordSpacing] h4,:root[style*=--USER__wordSpacing] h5,:root[style*=--USER__wordSpacing] h6,:root[style*=--USER__wordSpacing] p,:root[style*=--USER__wordSpacing] li,:root[style*=--USER__wordSpacing] div,:root[style*=--USER__wordSpacing] dt,:root[style*=--USER__wordSpacing] dd{word-spacing:var(--USER__wordSpacing)}:root[style*=--USER__letterSpacing] h1,:root[style*=--USER__letterSpacing] h2,:root[style*=--USER__letterSpacing] h3,:root[style*=--USER__letterSpacing] h4,:root[style*=--USER__letterSpacing] h5,:root[style*=--USER__letterSpacing] h6,:root[style*=--USER__letterSpacing] p,:root[style*=--USER__letterSpacing] li,:root[style*=--USER__letterSpacing] div,:root[style*=--USER__letterSpacing] dt,:root[style*=--USER__letterSpacing] dd{letter-spacing:var(--USER__letterSpacing);font-variant:none}:root[style*=--USER__fontWeight] body{font-weight:var(--USER__fontWeight)!important}:root[style*=--USER__fontWeight] b,:root[style*=--USER__fontWeight] strong{font-weight:bolder}:root[style*=--USER__fontWidth] body{font-stretch:var(--USER__fontWidth)!important}:root[style*=--USER__fontOpticalSizing] body{font-optical-sizing:var(--USER__fontOpticalSizing)!important}:root[style*=readium-blend-on] svg,:root[style*=readium-blend-on] img{background-color:transparent!important;mix-blend-mode:multiply!important}:root[style*=--USER__darkenImages] img{-webkit-filter:brightness(var(--USER__darkenImages))!important;filter:brightness(var(--USER__darkenImages))!important}:root[style*=readium-darken-on] img{-webkit-filter:brightness(80%)!important;filter:brightness(80%)!important}:root[style*=--USER__invertImages] img{-webkit-filter:invert(var(--USER__invertImages))!important;filter:invert(var(--USER__invertImages))!important}:root[style*=readium-invert-on] img{-webkit-filter:invert(100%)!important;filter:invert(100%)!important}:root[style*=--USER__darkenImages][style*=--USER__invertImages] img{-webkit-filter:brightness(var(--USER__darkenImages)) invert(var(--USER__invertImages))!important;filter:brightness(var(--USER__darkenImages)) invert(var(--USER__invertImages))!important}:root[style*=readium-darken-on][style*=--USER__invertImages] img{-webkit-filter:brightness(80%) invert(var(--USER__invertImages))!important;filter:brightness(80%) invert(var(--USER__invertImages))!important}:root[style*=--USER__darkenImages][style*=readium-invert-on] img{-webkit-filter:brightness(var(--USER__darkenImages)) invert(100%)!important;filter:brightness(var(--USER__darkenImages)) invert(100%)!important}:root[style*=readium-darken-on][style*=readium-invert-on] img{-webkit-filter:brightness(80%) invert(100%)!important;filter:brightness(80%) invert(100%)!important}:root[style*=--USER__invertGaiji] img[class*=gaiji]{-webkit-filter:invert(var(--USER__invertGaiji))!important;filter:invert(var(--USER__invertGaiji))!important}:root[style*=readium-invertGaiji-on] img[class*=gaiji]{-webkit-filter:invert(100%)!important;filter:invert(100%)!important}:root[style*=readium-normalize-on]{--USER__typeScale:1.2}:root[style*=readium-normalize-on] p,:root[style*=readium-normalize-on] li,:root[style*=readium-normalize-on] div,:root[style*=readium-normalize-on] pre,:root[style*=readium-normalize-on] dd{font-size:1rem!important}:root[style*=readium-normalize-on] h1{font-size:1.75rem!important;font-size:calc(((1rem * var(--USER__typeScale)) * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-normalize-on] h2{font-size:1.5rem!important;font-size:calc((1rem * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-normalize-on] h3{font-size:1.25rem!important;font-size:calc(1rem * var(--USER__typeScale))!important}:root[style*=readium-normalize-on] h4,:root[style*=readium-normalize-on] h5,:root[style*=readium-normalize-on] h6{font-size:1rem!important}:root[style*=readium-normalize-on] small{font-size:smaller!important}:root[style*=readium-normalize-on] sub,:root[style*=readium-normalize-on] sup{font-size:67.5%!important}:root[style*=readium-normalize-on][style*=--USER__typeScale] h1{font-size:calc(((1rem * var(--USER__typeScale)) * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-normalize-on][style*=--USER__typeScale] h2{font-size:calc((1rem * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-normalize-on][style*=--USER__typeScale] h3{font-size:calc(1rem * var(--USER__typeScale))!important}:root[style*=readium-iPadOSPatch-on] body{-webkit-text-size-adjust:none}:root[style*=readium-iPadOSPatch-on] p,:root[style*=readium-iPadOSPatch-on] h1,:root[style*=readium-iPadOSPatch-on] h2,:root[style*=readium-iPadOSPatch-on] h3,:root[style*=readium-iPadOSPatch-on] h4,:root[style*=readium-iPadOSPatch-on] h5,:root[style*=readium-iPadOSPatch-on] h6,:root[style*=readium-iPadOSPatch-on] li,:root[style*=readium-iPadOSPatch-on] th,:root[style*=readium-iPadOSPatch-on] td,:root[style*=readium-iPadOSPatch-on] dt,:root[style*=readium-iPadOSPatch-on] dd,:root[style*=readium-iPadOSPatch-on] pre,:root[style*=readium-iPadOSPatch-on] address,:root[style*=readium-iPadOSPatch-on] details,:root[style*=readium-iPadOSPatch-on] summary,:root[style*=readium-iPadOSPatch-on] figcaption,:root[style*=readium-iPadOSPatch-on] div:not(:has(p,h1,h2,h3,h4,h5,h6,li,th,td,dt,dd,pre,address,aside,details,figcaption,summary)),:root[style*=readium-iPadOSPatch-on] aside:not(:has(p,h1,h2,h3,h4,h5,h6,li,th,td,dt,dd,pre,address,aside,details,figcaption,summary)){-webkit-text-zoom:reset}:root[style*=readium-iPadOSPatch-on] abbr,:root[style*=readium-iPadOSPatch-on] b,:root[style*=readium-iPadOSPatch-on] bdi,:root[style*=readium-iPadOSPatch-on] bdo,:root[style*=readium-iPadOSPatch-on] cite,:root[style*=readium-iPadOSPatch-on] code,:root[style*=readium-iPadOSPatch-on] dfn,:root[style*=readium-iPadOSPatch-on] em,:root[style*=readium-iPadOSPatch-on] i,:root[style*=readium-iPadOSPatch-on] kbd,:root[style*=readium-iPadOSPatch-on] mark,:root[style*=readium-iPadOSPatch-on] q,:root[style*=readium-iPadOSPatch-on] rp,:root[style*=readium-iPadOSPatch-on] rt,:root[style*=readium-iPadOSPatch-on] ruby,:root[style*=readium-iPadOSPatch-on] s,:root[style*=readium-iPadOSPatch-on] samp,:root[style*=readium-iPadOSPatch-on] small,:root[style*=readium-iPadOSPatch-on] span,:root[style*=readium-iPadOSPatch-on] strong,:root[style*=readium-iPadOSPatch-on] sub,:root[style*=readium-iPadOSPatch-on] sup,:root[style*=readium-iPadOSPatch-on] time,:root[style*=readium-iPadOSPatch-on] u,:root[style*=readium-iPadOSPatch-on] var{-webkit-text-zoom:normal}:root[style*=readium-iPadOSPatch-on] p:not(:has(b,cite,em,i,q,s,small,span,strong)):first-line{-webkit-text-zoom:normal}`,xn=`/*!
|
|
307
307
|
* Readium CSS v.2.0.0-beta.19
|
|
308
308
|
* Copyright (c) 2017–2025. Readium Foundation. All rights reserved.
|
|
309
309
|
* Use of this source code is governed by a BSD-style license which is detailed in the
|
|
@@ -316,7 +316,7 @@ if(window.onload) window.onload = new Proxy(window.onload, {
|
|
|
316
316
|
* L. Le Meur
|
|
317
317
|
* Mickaël Menu
|
|
318
318
|
* k_taka
|
|
319
|
-
*/@namespace url(http://www.w3.org/1999/xhtml);@namespace epub url(http://www.idpf.org/2007/ops);@namespace m url(http://www.w3.org/1998/Math/MathML);@namespace svg url(http://www.w3.org/2000/svg);@-ms-viewport{width:device-width}@viewport{width:device-width;zoom:1}:root{--RS__monospaceTf:ui-monospace, "Andale Mono", "Cascadia Code", "Source Code Pro", Menlo, Consolas, "DejaVu Sans Mono", monospace;--RS__humanistTf:Seravek, Calibri, "Gill Sans Nova", Roboto, Ubuntu, "DejaVu Sans", source-sans-pro, sans-serif;--RS__sansTf:-ui-sans-serif, -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI Variable", "Segoe UI", Inter, Roboto, "Helvetica Neue", "Arial Nova", "Liberation Sans", Arial, sans-serif;--RS__modernTf:Athelas, Constantia, Charter, "Bitstream Charter", Cambria, "Georgia Pro", Georgia, serif;--RS__oldStyleTf:"Iowan Old Style", Sitka, "Sitka Text", Palatino, "Book Antiqua", "URW Palladio L", P052, serif;--RS__baseFontFamily:var(--RS__oldStyleTf);--RS__lineHeightCompensation:1;--RS__baseLineHeight:calc(1.5 * var(--RS__lineHeightCompensation));--RS__selectionTextColor:inherit;--RS__selectionBackgroundColor:#b4d8fe;--RS__visitedColor:#551A8B;--RS__linkColor:#0000EE;--RS__textColor:#121212;--RS__backgroundColor:#FFFFFF;color:var(--RS__textColor)!important;background-color:var(--RS__backgroundColor)!important}::-moz-selection{color:var(--RS__selectionTextColor);background-color:var(--RS__selectionBackgroundColor)}::selection{color:var(--RS__selectionTextColor);background-color:var(--RS__selectionBackgroundColor)}html{font-family:var(--RS__baseFontFamily);line-height:1.6;line-height:var(--RS__baseLineHeight);text-rendering:optimizelegibility}h1,h2,h3{line-height:normal}:lang(ja),:lang(zh),:lang(ko){word-wrap:break-word;-webkit-line-break:strict;-epub-line-break:strict;line-break:strict}math{font-family:"Latin Modern Math","STIX Two Math","XITS Math","STIX Math","Libertinus Math","TeX Gyre Termes Math","TeX Gyre Bonum Math",TeX Gyre Schola,"DejaVu Math TeX Gyre","TeX Gyre Pagella Math","Asana Math","Cambria Math","Lucida Bright Math","Minion Math",STIXGeneral,STIXSizeOneSym,Symbol,Times New Roman,serif}:lang(am){--RS__baseFontFamily:kefa, nyala, roboto, noto, "Noto Sans Ethiopic", serif;--RS__lineHeightCompensation:1.167}:lang(ar){--RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif}:lang(bn){--RS__baseFontFamily:"Kohinoor Bangla", "Bangla Sangam MN", vrinda, roboto, noto, "Noto Sans Bengali", sans-serif;--RS__lineHeightCompensation:1.067}:lang(bo){--RS__baseFontFamily:kailasa, "Microsoft Himalaya", roboto, noto, "Noto Sans Tibetan", sans-serif}:lang(chr){--RS__baseFontFamily:"Plantagenet Cherokee", roboto, noto, "Noto Sans Cherokee";--RS__lineHeightCompensation:1.167}:lang(fa){--RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif}:lang(gu){--RS__baseFontFamily:"Gujarati Sangam MN", "Nirmala UI", shruti, roboto, noto, "Noto Sans Gujarati", sans-serif;--RS__lineHeightCompensation:1.167}:lang(he){--RS__baseFontFamily:"New Peninim MT", "Arial Hebrew", gisha, "Times New Roman", roboto, noto, "Noto Sans Hebrew" sans-serif;--RS__lineHeightCompensation:1.1}:lang(hi){--RS__baseFontFamily:"Kohinoor Devanagari", "Devanagari Sangam MN", kokila, "Nirmala UI", roboto, noto, "Noto Sans Devanagari", sans-serif;--RS__lineHeightCompensation:1.1}:lang(hy){--RS__baseFontFamily:mshtakan, sylfaen, roboto, noto, "Noto Serif Armenian", serif}:lang(iu){--RS__baseFontFamily:"Euphemia UCAS", euphemia, roboto, noto, "Noto Sans Canadian Aboriginal", sans-serif}:lang(ja){--RS__baseFontFamily:yugothic, "Hiragino Maru Gothic ProN", "Hiragino Sans", "Yu Gothic UI", "Meiryo UI", "MS Gothic", roboto, noto, "Noto Sans CJK JP", sans-serif;--RS__lineHeightCompensation:1.167;--RS__serif-ja:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDPMincho", "Yu Mincho", "MS P明朝", "MS PMincho", serif;--RS__sans-serif-ja:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDPGothic", "Yu Gothic", "MS Pゴシック", "MS PGothic", sans-serif;--RS__serif-ja-v:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDMincho", "Yu Mincho", "MS明朝", "MS Mincho", serif;--RS__sans-serif-ja-v:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDGothic", "Yu Gothic", "MSゴシック", "MS Gothic", sans-serif}:lang(km){--RS__baseFontFamily:"Khmer Sangam MN", "Leelawadee UI", "Khmer UI", roboto, noto, "Noto Sans Khmer", sans-serif;--RS__lineHeightCompensation:1.067}:lang(kn){--RS__baseFontFamily:"Kannada Sangam MN", "Nirmala UI", tunga, roboto, noto, "Noto Sans Kannada", sans-serif;--RS__lineHeightCompensation:1.1}:lang(ko){--RS__baseFontFamily:"Nanum Gothic", "Apple SD Gothic Neo", "Malgun Gothic", roboto, noto, "Noto Sans CJK KR", sans-serif;--RS__lineHeightCompensation:1.167}:lang(lo){--RS__baseFontFamily:"Lao Sangam MN", "Leelawadee UI", "Lao UI", roboto, noto, "Noto Sans Lao", sans-serif}:lang(ml){--RS__baseFontFamily:"Malayalam Sangam MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Malayalam", sans-serif;--RS__lineHeightCompensation:1.067}:lang(or){--RS__baseFontFamily:"Oriya Sangam MN", "Nirmala UI", kalinga, roboto, noto, "Noto Sans Oriya", sans-serif;--RS__lineHeightCompensation:1.167}:lang(pa){--RS__baseFontFamily:"Gurmukhi MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Gurmukhi", sans-serif;--RS__lineHeightCompensation:1.1}:lang(si){--RS__baseFontFamily:"Sinhala Sangam MN", "Nirmala UI", "Iskoola Pota", roboto, noto, "Noto Sans Sinhala", sans-serif;--RS__lineHeightCompensation:1.167}:lang(ta){--RS__baseFontFamily:"Tamil Sangam MN", "Nirmala UI", latha, roboto, noto, "Noto Sans Tamil", sans-serif;--RS__lineHeightCompensation:1.067}:lang(te){--RS__baseFontFamily:"Kohinoor Telugu", "Telugu Sangam MN", "Nirmala UI", gautami, roboto, noto, "Noto Sans Telugu", sans-serif}:lang(th){--RS__baseFontFamily:"Thonburi", "Leelawadee UI", "Cordia New", roboto, noto, "Noto Sans Thai", sans-serif;--RS__lineHeightCompensation:1.067}:lang(zh){--RS__baseFontFamily:"方体", "PingFang SC", "黑体", "Heiti SC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK SC", sans-serif;--RS__lineHeightCompensation:1.167}:lang(zh-Hant),:lang(zh-TW){--RS__baseFontFamily:"方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;--RS__lineHeightCompensation:1.167}:lang(zh-HK){--RS__baseFontFamily:"方體", "PingFang HK", "方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;--RS__lineHeightCompensation:1.167}@font-face{font-family:AccessibleDfA;font-style:normal;font-weight:400;src:local("AccessibleDfA"),url(./assets/AccessibleDfA-Regular.woff2) format("woff2"),url(./assets/AccessibleDfA-Regular.woff) format("woff")}@font-face{font-family:AccessibleDfA;font-style:normal;font-weight:700;src:local("AccessibleDfA"),url(./assets/AccessibleDfA-Bold.woff2) format("woff2")}@font-face{font-family:AccessibleDfA;font-style:italic;font-weight:400;src:local("AccessibleDfA"),url(./assets/AccessibleDfA-Italic.woff2) format("woff2")}@font-face{font-family:IA Writer Duospace;font-style:normal;font-weight:400;src:local("iAWriterDuospace-Regular"),url(./assets/iAWriterDuospace-Regular.ttf) format("truetype")}body{widows:2;orphans:2}figcaption,th,td{widows:1;orphans:1}h2,h3,h4,h5,h6,dt,hr,caption{-webkit-column-break-after:avoid;page-break-after:avoid;break-after:avoid}h1,h2,h3,h4,h5,h6,dt,figure,tr{-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}body{-webkit-hyphenate-character:"-";-moz-hyphenate-character:"-";-ms-hyphenate-character:"-";hyphenate-character:"-";-webkit-hyphenate-limit-lines:3;-ms-hyphenate-limit-lines:3;hyphenate-limit-lines:3}h1,h2,h3,h4,h5,h6,dt,figcaption,pre,caption,address,center,code,var{-ms-hyphens:none;-moz-hyphens:none;-webkit-hyphens:none;-epub-hyphens:none;hyphens:none}body{font-variant-numeric:oldstyle-nums proportional-nums}:lang(ja) body,:lang(zh) body,:lang(ko) body{font-variant-numeric:lining-nums proportional-nums}h1,h2,h3,h4,h5,h6,dt{font-variant-numeric:lining-nums proportional-nums}table{font-variant-numeric:lining-nums tabular-nums}code,var{font-variant-ligatures:none;font-variant-numeric:lining-nums tabular-nums slashed-zero}rt{font-variant-east-asian:ruby}:lang(ar){font-variant-ligatures:common-ligatures}:lang(ko){font-kerning:normal}hr{color:inherit;border-color:currentcolor}table,th,td{border-color:currentcolor}figure,blockquote{margin:1em 5%}ul,ol{padding-left:5%}dd{margin-left:5%}pre{white-space:pre-wrap;-ms-tab-size:2;-moz-tab-size:2;-webkit-tab-size:2;tab-size:2}abbr[title],acronym[title]{text-decoration:dotted underline}nobr wbr{white-space:normal}ruby>rt,ruby>rp{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}*:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)),*:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)),*:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)),:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) cite,:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) dfn,:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) em,:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) i,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) cite,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) dfn,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) em,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) i,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) cite,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) dfn,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) em,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) i{font-style:normal}:lang(ja) a,:lang(zh) a,:lang(ko) a{text-decoration:none}:root{--RS__maxMediaWidth:100%;--RS__maxMediaHeight:95vh;--RS__boxSizingMedia:border-box;--RS__boxSizingTable:border-box}a,a span,span a,h1,h2,h3,h4,h5,h6{word-wrap:break-word}div{max-width:var(--RS__maxMediaWidth)}img,svg|svg,video{object-fit:contain;width:auto;height:auto;max-width:var(--RS__maxMediaWidth);max-height:var(--RS__maxMediaHeight)!important;box-sizing:var(--RS__boxSizingMedia);-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}audio{max-width:100%;-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}table{max-width:var(--RS__maxMediaWidth);box-sizing:var(--RS__boxSizingTable)}`,xn=`/*!
|
|
319
|
+
*/@namespace url(http://www.w3.org/1999/xhtml);@namespace epub url(http://www.idpf.org/2007/ops);@namespace m url(http://www.w3.org/1998/Math/MathML);@namespace svg url(http://www.w3.org/2000/svg);@-ms-viewport{width:device-width}@viewport{width:device-width;zoom:1}:root{--RS__monospaceTf:ui-monospace, "Andale Mono", "Cascadia Code", "Source Code Pro", Menlo, Consolas, "DejaVu Sans Mono", monospace;--RS__humanistTf:Seravek, Calibri, "Gill Sans Nova", Roboto, Ubuntu, "DejaVu Sans", source-sans-pro, sans-serif;--RS__sansTf:-ui-sans-serif, -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI Variable", "Segoe UI", Inter, Roboto, "Helvetica Neue", "Arial Nova", "Liberation Sans", Arial, sans-serif;--RS__modernTf:Athelas, Constantia, Charter, "Bitstream Charter", Cambria, "Georgia Pro", Georgia, serif;--RS__oldStyleTf:"Iowan Old Style", Sitka, "Sitka Text", Palatino, "Book Antiqua", "URW Palladio L", P052, serif;--RS__baseFontFamily:var(--RS__oldStyleTf);--RS__lineHeightCompensation:1;--RS__baseLineHeight:calc(1.5 * var(--RS__lineHeightCompensation));--RS__selectionTextColor:inherit;--RS__selectionBackgroundColor:#b4d8fe;--RS__visitedColor:#551A8B;--RS__linkColor:#0000EE;--RS__textColor:#121212;--RS__backgroundColor:#FFFFFF;color:var(--RS__textColor)!important;background-color:var(--RS__backgroundColor)!important}::-moz-selection{color:var(--RS__selectionTextColor);background-color:var(--RS__selectionBackgroundColor)}::selection{color:var(--RS__selectionTextColor);background-color:var(--RS__selectionBackgroundColor)}html{font-family:var(--RS__baseFontFamily);line-height:1.6;line-height:var(--RS__baseLineHeight);text-rendering:optimizelegibility}h1,h2,h3{line-height:normal}:lang(ja),:lang(zh),:lang(ko){word-wrap:break-word;-webkit-line-break:strict;-epub-line-break:strict;line-break:strict}math{font-family:"Latin Modern Math","STIX Two Math","XITS Math","STIX Math","Libertinus Math","TeX Gyre Termes Math","TeX Gyre Bonum Math",TeX Gyre Schola,"DejaVu Math TeX Gyre","TeX Gyre Pagella Math","Asana Math","Cambria Math","Lucida Bright Math","Minion Math",STIXGeneral,STIXSizeOneSym,Symbol,Times New Roman,serif}:lang(am){--RS__baseFontFamily:kefa, nyala, roboto, noto, "Noto Sans Ethiopic", serif;--RS__lineHeightCompensation:1.167}:lang(ar){--RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif}:lang(bn){--RS__baseFontFamily:"Kohinoor Bangla", "Bangla Sangam MN", vrinda, roboto, noto, "Noto Sans Bengali", sans-serif;--RS__lineHeightCompensation:1.067}:lang(bo){--RS__baseFontFamily:kailasa, "Microsoft Himalaya", roboto, noto, "Noto Sans Tibetan", sans-serif}:lang(chr){--RS__baseFontFamily:"Plantagenet Cherokee", roboto, noto, "Noto Sans Cherokee";--RS__lineHeightCompensation:1.167}:lang(fa){--RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif}:lang(gu){--RS__baseFontFamily:"Gujarati Sangam MN", "Nirmala UI", shruti, roboto, noto, "Noto Sans Gujarati", sans-serif;--RS__lineHeightCompensation:1.167}:lang(he){--RS__baseFontFamily:"New Peninim MT", "Arial Hebrew", gisha, "Times New Roman", roboto, noto, "Noto Sans Hebrew" sans-serif;--RS__lineHeightCompensation:1.1}:lang(hi){--RS__baseFontFamily:"Kohinoor Devanagari", "Devanagari Sangam MN", kokila, "Nirmala UI", roboto, noto, "Noto Sans Devanagari", sans-serif;--RS__lineHeightCompensation:1.1}:lang(hy){--RS__baseFontFamily:mshtakan, sylfaen, roboto, noto, "Noto Serif Armenian", serif}:lang(iu){--RS__baseFontFamily:"Euphemia UCAS", euphemia, roboto, noto, "Noto Sans Canadian Aboriginal", sans-serif}:lang(ja){--RS__baseFontFamily:yugothic, "Hiragino Maru Gothic ProN", "Hiragino Sans", "Yu Gothic UI", "Meiryo UI", "MS Gothic", roboto, noto, "Noto Sans CJK JP", sans-serif;--RS__lineHeightCompensation:1.167;--RS__serif-ja:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDPMincho", "Yu Mincho", "MS P明朝", "MS PMincho", serif;--RS__sans-serif-ja:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDPGothic", "Yu Gothic", "MS Pゴシック", "MS PGothic", sans-serif;--RS__serif-ja-v:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDMincho", "Yu Mincho", "MS明朝", "MS Mincho", serif;--RS__sans-serif-ja-v:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDGothic", "Yu Gothic", "MSゴシック", "MS Gothic", sans-serif}:lang(km){--RS__baseFontFamily:"Khmer Sangam MN", "Leelawadee UI", "Khmer UI", roboto, noto, "Noto Sans Khmer", sans-serif;--RS__lineHeightCompensation:1.067}:lang(kn){--RS__baseFontFamily:"Kannada Sangam MN", "Nirmala UI", tunga, roboto, noto, "Noto Sans Kannada", sans-serif;--RS__lineHeightCompensation:1.1}:lang(ko){--RS__baseFontFamily:"Nanum Gothic", "Apple SD Gothic Neo", "Malgun Gothic", roboto, noto, "Noto Sans CJK KR", sans-serif;--RS__lineHeightCompensation:1.167}:lang(lo){--RS__baseFontFamily:"Lao Sangam MN", "Leelawadee UI", "Lao UI", roboto, noto, "Noto Sans Lao", sans-serif}:lang(ml){--RS__baseFontFamily:"Malayalam Sangam MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Malayalam", sans-serif;--RS__lineHeightCompensation:1.067}:lang(or){--RS__baseFontFamily:"Oriya Sangam MN", "Nirmala UI", kalinga, roboto, noto, "Noto Sans Oriya", sans-serif;--RS__lineHeightCompensation:1.167}:lang(pa){--RS__baseFontFamily:"Gurmukhi MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Gurmukhi", sans-serif;--RS__lineHeightCompensation:1.1}:lang(si){--RS__baseFontFamily:"Sinhala Sangam MN", "Nirmala UI", "Iskoola Pota", roboto, noto, "Noto Sans Sinhala", sans-serif;--RS__lineHeightCompensation:1.167}:lang(ta){--RS__baseFontFamily:"Tamil Sangam MN", "Nirmala UI", latha, roboto, noto, "Noto Sans Tamil", sans-serif;--RS__lineHeightCompensation:1.067}:lang(te){--RS__baseFontFamily:"Kohinoor Telugu", "Telugu Sangam MN", "Nirmala UI", gautami, roboto, noto, "Noto Sans Telugu", sans-serif}:lang(th){--RS__baseFontFamily:"Thonburi", "Leelawadee UI", "Cordia New", roboto, noto, "Noto Sans Thai", sans-serif;--RS__lineHeightCompensation:1.067}:lang(zh){--RS__baseFontFamily:"方体", "PingFang SC", "黑体", "Heiti SC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK SC", sans-serif;--RS__lineHeightCompensation:1.167}:lang(zh-Hant),:lang(zh-TW){--RS__baseFontFamily:"方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;--RS__lineHeightCompensation:1.167}:lang(zh-HK){--RS__baseFontFamily:"方體", "PingFang HK", "方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;--RS__lineHeightCompensation:1.167}@font-face{font-family:AccessibleDfA;font-style:normal;font-weight:400;src:local("AccessibleDfA"),url(./assets/AccessibleDfA-Regular.woff2) format("woff2"),url(./assets/AccessibleDfA-Regular.woff) format("woff")}@font-face{font-family:AccessibleDfA;font-style:normal;font-weight:700;src:local("AccessibleDfA"),url(./assets/AccessibleDfA-Bold.woff2) format("woff2")}@font-face{font-family:AccessibleDfA;font-style:italic;font-weight:400;src:local("AccessibleDfA"),url(./assets/AccessibleDfA-Italic.woff2) format("woff2")}@font-face{font-family:IA Writer Duospace;font-style:normal;font-weight:400;src:local("iAWriterDuospace-Regular"),url(./assets/iAWriterDuospace-Regular.ttf) format("truetype")}body{widows:2;orphans:2}figcaption,th,td{widows:1;orphans:1}h2,h3,h4,h5,h6,dt,hr,caption{-webkit-column-break-after:avoid;page-break-after:avoid;break-after:avoid}h1,h2,h3,h4,h5,h6,dt,figure,tr{-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}body{-webkit-hyphenate-character:"-";-moz-hyphenate-character:"-";-ms-hyphenate-character:"-";hyphenate-character:"-";-webkit-hyphenate-limit-lines:3;-ms-hyphenate-limit-lines:3;hyphenate-limit-lines:3}h1,h2,h3,h4,h5,h6,dt,figcaption,pre,caption,address,center,code,var{-ms-hyphens:none;-moz-hyphens:none;-webkit-hyphens:none;-epub-hyphens:none;hyphens:none}body{font-variant-numeric:oldstyle-nums proportional-nums}:lang(ja) body,:lang(zh) body,:lang(ko) body{font-variant-numeric:lining-nums proportional-nums}h1,h2,h3,h4,h5,h6,dt{font-variant-numeric:lining-nums proportional-nums}table{font-variant-numeric:lining-nums tabular-nums}code,var{font-variant-ligatures:none;font-variant-numeric:lining-nums tabular-nums slashed-zero}rt{font-variant-east-asian:ruby}:lang(ar){font-variant-ligatures:common-ligatures}:lang(ko){font-kerning:normal}hr{color:inherit;border-color:currentcolor}table,th,td{border-color:currentcolor}figure,blockquote{margin:1em 5%}ul,ol{padding-left:5%}dd{margin-left:5%}pre{white-space:pre-wrap;-ms-tab-size:2;-moz-tab-size:2;-webkit-tab-size:2;tab-size:2}abbr[title],acronym[title]{text-decoration:dotted underline}nobr wbr{white-space:normal}ruby>rt,ruby>rp{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}*:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)),*:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)),*:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)),:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) cite,:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) dfn,:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) em,:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) i,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) cite,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) dfn,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) em,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) i,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) cite,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) dfn,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) em,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) i{font-style:normal}:lang(ja) a,:lang(zh) a,:lang(ko) a{text-decoration:none}:root{--RS__maxMediaWidth:100%;--RS__maxMediaHeight:95vh;--RS__boxSizingMedia:border-box;--RS__boxSizingTable:border-box}a,a span,span a,h1,h2,h3,h4,h5,h6{word-wrap:break-word}div{max-width:var(--RS__maxMediaWidth)}img,svg|svg,video{object-fit:contain;width:auto;height:auto;max-width:var(--RS__maxMediaWidth);max-height:var(--RS__maxMediaHeight)!important;box-sizing:var(--RS__boxSizingMedia);-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}audio{max-width:100%;-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}table{max-width:var(--RS__maxMediaWidth);box-sizing:var(--RS__boxSizingTable)}`,Tn=`/*!
|
|
320
320
|
* Readium CSS v.2.0.0-beta.19
|
|
321
321
|
* Copyright (c) 2017–2025. Readium Foundation. All rights reserved.
|
|
322
322
|
* Use of this source code is governed by a BSD-style license which is detailed in the
|
|
@@ -329,7 +329,7 @@ if(window.onload) window.onload = new Proxy(window.onload, {
|
|
|
329
329
|
* L. Le Meur
|
|
330
330
|
* Mickaël Menu
|
|
331
331
|
* k_taka
|
|
332
|
-
*/@namespace url(http://www.w3.org/1999/xhtml);@namespace epub url(http://www.idpf.org/2007/ops);@namespace m url(http://www.w3.org/1998/Math/MathML);@namespace svg url(http://www.w3.org/2000/svg);:root{--RS__compFontFamily:var(--RS__baseFontFamily);--RS__codeFontFamily:var(--RS__monospaceTf);--RS__typeScale:1.125;--RS__baseFontSize:100%;--RS__flowSpacing:1.5rem;--RS__paraSpacing:0;--RS__paraIndent:1em;--RS__linkColor:#0000EE;--RS__visitedColor:#551A8B;--RS__primaryColor:;--RS__secondaryColor:}body{font-size:var(--RS__baseFontSize)}h1,h2,h3,h4,h5,h6{font-family:var(--RS__compFontFamily)}blockquote,figure,p,pre,aside,footer,form,hr{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing)}p{margin-top:var(--RS__paraSpacing);margin-bottom:var(--RS__paraSpacing);text-indent:var(--RS__paraIndent)}h1+p,h2+p,h3+p,h4+p,h5+p,h6+p,hr+p{text-indent:0}pre{font-family:var(--RS__codeFontFamily)}code,kbd,samp,tt{font-family:var(--RS__codeFontFamily)}sub,sup{position:relative;font-size:67.5%;line-height:1}sub{bottom:-.2ex}sup{bottom:0}:link{color:var(--RS__linkColor)}:visited{color:var(--RS__visitedColor)}h1{margin-top:calc(var(--RS__flowSpacing) * 2);margin-bottom:calc(var(--RS__flowSpacing) * 2);font-size:calc(((1em * var(--RS__typeScale)) * var(--RS__typeScale)) * var(--RS__typeScale))}h2{margin-top:calc(var(--RS__flowSpacing) * 2);margin-bottom:var(--RS__flowSpacing);font-size:calc((1em * var(--RS__typeScale)) * var(--RS__typeScale))}h3{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing);font-size:calc(1em * var(--RS__typeScale))}h4{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing);font-size:1em}h5{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing);font-size:1em;font-variant:small-caps}h6{margin-top:var(--RS__flowSpacing);margin-bottom:0;font-size:1em;text-transform:lowercase;font-variant:small-caps}dl,ol,ul{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing)}table{margin:var(--RS__flowSpacing) 0;border:1px solid currentcolor;border-collapse:collapse;empty-cells:show}thead,tbody,tfoot,table>tr{vertical-align:top}th{text-align:left}th,td{padding:4px;border:1px solid currentcolor}`,tt=(r,t)=>URL.createObjectURL(new Blob([r],{type:t})),qi=r=>r.replace(/\/\/.*/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\n/g,"").replace(/\s+/g," "),Re=r=>r.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g,"").replace(/ {2,}/g," ").replace(/url\((?!(https?:)?\/\/)("?)\/([^\)]+)/g,`url($2${window.location.origin}/$3`),Ce=(r,t)=>{const e=r.createElement("script");return e.dataset.readium="true",e.src=t.startsWith("blob:")?t:tt(t,"text/javascript"),e},Se=(r,t)=>{const e=r.createElement("link");return e.dataset.readium="true",e.rel="stylesheet",e.type="text/css",e.href=t.startsWith("blob:")?t:tt(t,"text/css"),e},Qe=new Map,pt=(r,t)=>{if(Qe.has(r))return Qe.get(r);const e=t();return Qe.set(r,e),e},bn=r=>Ce(r,pt("css-selector-generator",()=>tt('!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports._readium_cssSelectorGenerator=e():t._readium_cssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t,e,n={d:(t,e)=>{for(var o in e)n.o(e,o)&&!n.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:e[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},o={};function r(t){return t&&t instanceof Element}function i(t="unknown problem",...e){console.warn(`CssSelectorGenerator: ${t}`,...e)}n.r(o),n.d(o,{default:()=>z,getCssSelector:()=>U}),function(t){t.NONE="none",t.DESCENDANT="descendant",t.CHILD="child"}(t||(t={})),function(t){t.id="id",t.class="class",t.tag="tag",t.attribute="attribute",t.nthchild="nthchild",t.nthoftype="nthoftype"}(e||(e={}));const c={selectors:[e.id,e.class,e.tag,e.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY};function u(t){return t instanceof RegExp}function s(t){return["string","function"].includes(typeof t)||u(t)}function l(t){return Array.isArray(t)?t.filter(s):[]}function a(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function f(t,e){if(a(t))return t.contains(e)||i("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element\'s real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will nto work as intended."),t;const n=e.getRootNode({composed:!1});return a(n)?(n!==document&&i("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):e.ownerDocument.querySelector(":root")}function d(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function m(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function p(t){return[].concat(...t)}function h(t){const e=t.map((t=>{if(u(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(i("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return i("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1}));return t=>e.some((e=>e(t)))}function g(t,e,n){const o=Array.from(f(n,t[0]).querySelectorAll(e));return o.length===t.length&&t.every((t=>o.includes(t)))}function y(t,e){e=null!=e?e:function(t){return t.ownerDocument.querySelector(":root")}(t);const n=[];let o=t;for(;r(o)&&o!==e;)n.push(o),o=o.parentElement;return n}function b(t,e){return m(t.map((t=>y(t,e))))}const N={[t.NONE]:{type:t.NONE,value:""},[t.DESCENDANT]:{type:t.DESCENDANT,value:" > "},[t.CHILD]:{type:t.CHILD,value:" "}},S=new RegExp(["^$","\\\\s"].join("|")),E=new RegExp(["^$"].join("|")),w=[e.nthoftype,e.tag,e.id,e.class,e.attribute,e.nthchild],v=h(["class","id","ng-*"]);function C({nodeName:t}){return`[${t}]`}function O({nodeName:t,nodeValue:e}){return`[${t}=\'${L(e)}\']`}function T(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t},e){const n=e.tagName.toLowerCase();return!(["input","option"].includes(n)&&"value"===t||v(t))}(e,t)));return[...e.map(C),...e.map(O)]}function I(t){return(t.getAttribute("class")||"").trim().split(/\\s+/).filter((t=>!E.test(t))).map((t=>`.${L(t)}`))}function x(t){const e=t.getAttribute("id")||"",n=`#${L(e)}`,o=t.getRootNode({composed:!1});return!S.test(e)&&g([t],n,o)?[n]:[]}function j(t){const e=t.parentNode;if(e){const n=Array.from(e.childNodes).filter(r).indexOf(t);if(n>-1)return[`:nth-child(${n+1})`]}return[]}function A(t){return[L(t.tagName.toLowerCase())]}function D(t){const e=[...new Set(p(t.map(A)))];return 0===e.length||e.length>1?[]:[e[0]]}function $(t){const e=D([t])[0],n=t.parentElement;if(n){const o=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),r=o.indexOf(t);if(r>-1)return[`${e}:nth-of-type(${r+1})`]}return[]}function R(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){const n=[];let o=0,r=k(1);for(;r.length<=t.length&&o<e;)o+=1,n.push(r.map((e=>t[e]))),r=P(r,t.length-1);return n}function P(t=[],e=0){const n=t.length;if(0===n)return[];const o=[...t];o[n-1]+=1;for(let t=n-1;t>=0;t--)if(o[t]>e){if(0===t)return k(n+1);o[t-1]++,o[t]=o[t-1]+1}return o[n-1]>e?k(n+1):o}function k(t=1){return Array.from(Array(t).keys())}const _=":".charCodeAt(0).toString(16).toUpperCase(),M=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function L(t=""){var e,n;return null!==(n=null===(e=null===CSS||void 0===CSS?void 0:CSS.escape)||void 0===e?void 0:e.call(CSS,t))&&void 0!==n?n:function(t=""){return t.split("").map((t=>":"===t?`\\\\${_} `:M.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const q={tag:D,id:function(t){return 0===t.length||t.length>1?[]:x(t[0])},class:function(t){return m(t.map(I))},attribute:function(t){return m(t.map(T))},nthchild:function(t){return m(t.map(j))},nthoftype:function(t){return m(t.map($))}},F={tag:A,id:x,class:I,attribute:T,nthchild:j,nthoftype:$};function V(t){return t.includes(e.tag)||t.includes(e.nthoftype)?[...t]:[...t,e.tag]}function Y(t={}){const n=[...w];return t[e.tag]&&t[e.nthoftype]&&n.splice(n.indexOf(e.tag),1),n.map((e=>{return(o=t)[n=e]?o[n].join(""):"";var n,o})).join("")}function B(t,e,n="",o){const r=function(t,e){return""===e?t:function(t,e){return[...t.map((t=>e+" "+t)),...t.map((t=>e+" > "+t))]}(t,e)}(function(t,e,n){const o=function(t,e){const{blacklist:n,whitelist:o,combineWithinSelector:r,maxCombinations:i}=e,c=h(n),u=h(o);return function(t){const{selectors:e,includeTag:n}=t,o=[].concat(e);return n&&!o.includes("tag")&&o.push("tag"),o}(e).reduce(((e,n)=>{const o=function(t,e){var n;return(null!==(n=q[e])&&void 0!==n?n:()=>[])(t)}(t,n),s=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(o,c,u),l=function(t=[],e){return t.sort(((t,n)=>{const o=e(t),r=e(n);return o&&!r?-1:!o&&r?1:0}))}(s,u);return e[n]=r?R(l,{maxResults:i}):l.map((t=>[t])),e}),{})}(t,n),r=function(t,e){return function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:o,maxCandidates:r}=t,i=n?R(e,{maxResults:r}):e.map((t=>[t]));return o?i.map(V):i}(e).map((e=>function(t,e){const n={};return t.forEach((t=>{const o=e[t];o.length>0&&(n[t]=o)})),function(t={}){let e=[];return Object.entries(t).forEach((([t,n])=>{e=n.flatMap((n=>0===e.length?[{[t]:n}]:e.map((e=>Object.assign(Object.assign({},e),{[t]:n})))))})),e}(n).map(Y)}(e,t))).filter((t=>t.length>0))}(o,n),i=p(r);return[...new Set(i)]}(t,o.root,o),n);for(const e of r)if(g(t,e,o.root))return e;return null}function G(t){return{value:t,include:!1}}function W({selectors:t,operator:n}){let o=[...w];t[e.tag]&&t[e.nthoftype]&&(o=o.filter((t=>t!==e.tag)));let r="";return o.forEach((e=>{(t[e]||[]).forEach((({value:t,include:e})=>{e&&(r+=t)}))})),n.value+r}function H(n){return[":root",...y(n).reverse().map((n=>{const o=function(e,n,o=t.NONE){const r={};return n.forEach((t=>{Reflect.set(r,t,function(t,e){return F[e](t)}(e,t).map(G))})),{element:e,operator:N[o],selectors:r}}(n,[e.nthchild],t.DESCENDANT);return o.selectors.nthchild.forEach((t=>{t.include=!0})),o})).map(W)].join("")}function U(t,n={}){const o=function(t){const e=(Array.isArray(t)?t:[t]).filter(r);return[...new Set(e)]}(t),i=function(t,n={}){const o=Object.assign(Object.assign({},c),n);return{selectors:(r=o.selectors,Array.isArray(r)?r.filter((t=>{return n=e,o=t,Object.values(n).includes(o);var n,o})):[]),whitelist:l(o.whitelist),blacklist:l(o.blacklist),root:f(o.root,t),combineWithinSelector:!!o.combineWithinSelector,combineBetweenSelectors:!!o.combineBetweenSelectors,includeTag:!!o.includeTag,maxCombinations:d(o.maxCombinations),maxCandidates:d(o.maxCandidates)};var r}(o[0],n);let u="",s=i.root;function a(){return function(t,e,n="",o){if(0===t.length)return null;const r=[t.length>1?t:[],...b(t,e).map((t=>[t]))];for(const t of r){const e=B(t,0,n,o);if(e)return{foundElements:t,selector:e}}return null}(o,s,u,i)}let m=a();for(;m;){const{foundElements:t,selector:e}=m;if(g(o,e,i.root))return e;s=t[0],u=e,m=a()}return o.length>1?o.map((t=>U(t,i))).join(", "):function(t){return t.map(H).join(", ")}(o)}const z=U;return o})()));',"text/javascript"))),jn=r=>Ce(r,pt("JS-Before",()=>tt(qi(`
|
|
332
|
+
*/@namespace url(http://www.w3.org/1999/xhtml);@namespace epub url(http://www.idpf.org/2007/ops);@namespace m url(http://www.w3.org/1998/Math/MathML);@namespace svg url(http://www.w3.org/2000/svg);:root{--RS__compFontFamily:var(--RS__baseFontFamily);--RS__codeFontFamily:var(--RS__monospaceTf);--RS__typeScale:1.125;--RS__baseFontSize:100%;--RS__flowSpacing:1.5rem;--RS__paraSpacing:0;--RS__paraIndent:1em;--RS__linkColor:#0000EE;--RS__visitedColor:#551A8B;--RS__primaryColor:;--RS__secondaryColor:}body{font-size:var(--RS__baseFontSize)}h1,h2,h3,h4,h5,h6{font-family:var(--RS__compFontFamily)}blockquote,figure,p,pre,aside,footer,form,hr{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing)}p{margin-top:var(--RS__paraSpacing);margin-bottom:var(--RS__paraSpacing);text-indent:var(--RS__paraIndent)}h1+p,h2+p,h3+p,h4+p,h5+p,h6+p,hr+p{text-indent:0}pre{font-family:var(--RS__codeFontFamily)}code,kbd,samp,tt{font-family:var(--RS__codeFontFamily)}sub,sup{position:relative;font-size:67.5%;line-height:1}sub{bottom:-.2ex}sup{bottom:0}:link{color:var(--RS__linkColor)}:visited{color:var(--RS__visitedColor)}h1{margin-top:calc(var(--RS__flowSpacing) * 2);margin-bottom:calc(var(--RS__flowSpacing) * 2);font-size:calc(((1em * var(--RS__typeScale)) * var(--RS__typeScale)) * var(--RS__typeScale))}h2{margin-top:calc(var(--RS__flowSpacing) * 2);margin-bottom:var(--RS__flowSpacing);font-size:calc((1em * var(--RS__typeScale)) * var(--RS__typeScale))}h3{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing);font-size:calc(1em * var(--RS__typeScale))}h4{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing);font-size:1em}h5{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing);font-size:1em;font-variant:small-caps}h6{margin-top:var(--RS__flowSpacing);margin-bottom:0;font-size:1em;text-transform:lowercase;font-variant:small-caps}dl,ol,ul{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing)}table{margin:var(--RS__flowSpacing) 0;border:1px solid currentcolor;border-collapse:collapse;empty-cells:show}thead,tbody,tfoot,table>tr{vertical-align:top}th{text-align:left}th,td{padding:4px;border:1px solid currentcolor}`,$=(r,t)=>URL.createObjectURL(new Blob([r],{type:t})),qi=r=>r.replace(/\/\/.*/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\n/g,"").replace(/\s+/g," "),Ue=r=>r.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g,"").replace(/ {2,}/g," ").replace(/url\((?!(https?:)?\/\/)("?)\/([^\)]+)/g,`url($2${window.location.origin}/$3`),Re=(r,t)=>{const e=r.createElement("script");return e.dataset.readium="true",e.src=t.startsWith("blob:")?t:$(t,"text/javascript"),e},Ce=(r,t)=>{const e=r.createElement("link");return e.dataset.readium="true",e.rel="stylesheet",e.type="text/css",e.href=t.startsWith("blob:")?t:$(t,"text/css"),e},Se=new Map,ft=(r,t)=>{if(Se.has(r))return Se.get(r);const e=t();return Se.set(r,e),e},bn=r=>Re(r,ft("css-selector-generator",()=>$('!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports._readium_cssSelectorGenerator=e():t._readium_cssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t,e,n={d:(t,e)=>{for(var o in e)n.o(e,o)&&!n.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:e[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},o={};function r(t){return t&&t instanceof Element}function i(t="unknown problem",...e){console.warn(`CssSelectorGenerator: ${t}`,...e)}n.r(o),n.d(o,{default:()=>z,getCssSelector:()=>U}),function(t){t.NONE="none",t.DESCENDANT="descendant",t.CHILD="child"}(t||(t={})),function(t){t.id="id",t.class="class",t.tag="tag",t.attribute="attribute",t.nthchild="nthchild",t.nthoftype="nthoftype"}(e||(e={}));const c={selectors:[e.id,e.class,e.tag,e.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY};function u(t){return t instanceof RegExp}function s(t){return["string","function"].includes(typeof t)||u(t)}function l(t){return Array.isArray(t)?t.filter(s):[]}function a(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function f(t,e){if(a(t))return t.contains(e)||i("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element\'s real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will nto work as intended."),t;const n=e.getRootNode({composed:!1});return a(n)?(n!==document&&i("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):e.ownerDocument.querySelector(":root")}function d(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function m(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function p(t){return[].concat(...t)}function h(t){const e=t.map((t=>{if(u(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(i("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return i("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1}));return t=>e.some((e=>e(t)))}function g(t,e,n){const o=Array.from(f(n,t[0]).querySelectorAll(e));return o.length===t.length&&t.every((t=>o.includes(t)))}function y(t,e){e=null!=e?e:function(t){return t.ownerDocument.querySelector(":root")}(t);const n=[];let o=t;for(;r(o)&&o!==e;)n.push(o),o=o.parentElement;return n}function b(t,e){return m(t.map((t=>y(t,e))))}const N={[t.NONE]:{type:t.NONE,value:""},[t.DESCENDANT]:{type:t.DESCENDANT,value:" > "},[t.CHILD]:{type:t.CHILD,value:" "}},S=new RegExp(["^$","\\\\s"].join("|")),E=new RegExp(["^$"].join("|")),w=[e.nthoftype,e.tag,e.id,e.class,e.attribute,e.nthchild],v=h(["class","id","ng-*"]);function C({nodeName:t}){return`[${t}]`}function O({nodeName:t,nodeValue:e}){return`[${t}=\'${L(e)}\']`}function T(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t},e){const n=e.tagName.toLowerCase();return!(["input","option"].includes(n)&&"value"===t||v(t))}(e,t)));return[...e.map(C),...e.map(O)]}function I(t){return(t.getAttribute("class")||"").trim().split(/\\s+/).filter((t=>!E.test(t))).map((t=>`.${L(t)}`))}function x(t){const e=t.getAttribute("id")||"",n=`#${L(e)}`,o=t.getRootNode({composed:!1});return!S.test(e)&&g([t],n,o)?[n]:[]}function j(t){const e=t.parentNode;if(e){const n=Array.from(e.childNodes).filter(r).indexOf(t);if(n>-1)return[`:nth-child(${n+1})`]}return[]}function A(t){return[L(t.tagName.toLowerCase())]}function D(t){const e=[...new Set(p(t.map(A)))];return 0===e.length||e.length>1?[]:[e[0]]}function $(t){const e=D([t])[0],n=t.parentElement;if(n){const o=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),r=o.indexOf(t);if(r>-1)return[`${e}:nth-of-type(${r+1})`]}return[]}function R(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){const n=[];let o=0,r=k(1);for(;r.length<=t.length&&o<e;)o+=1,n.push(r.map((e=>t[e]))),r=P(r,t.length-1);return n}function P(t=[],e=0){const n=t.length;if(0===n)return[];const o=[...t];o[n-1]+=1;for(let t=n-1;t>=0;t--)if(o[t]>e){if(0===t)return k(n+1);o[t-1]++,o[t]=o[t-1]+1}return o[n-1]>e?k(n+1):o}function k(t=1){return Array.from(Array(t).keys())}const _=":".charCodeAt(0).toString(16).toUpperCase(),M=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function L(t=""){var e,n;return null!==(n=null===(e=null===CSS||void 0===CSS?void 0:CSS.escape)||void 0===e?void 0:e.call(CSS,t))&&void 0!==n?n:function(t=""){return t.split("").map((t=>":"===t?`\\\\${_} `:M.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const q={tag:D,id:function(t){return 0===t.length||t.length>1?[]:x(t[0])},class:function(t){return m(t.map(I))},attribute:function(t){return m(t.map(T))},nthchild:function(t){return m(t.map(j))},nthoftype:function(t){return m(t.map($))}},F={tag:A,id:x,class:I,attribute:T,nthchild:j,nthoftype:$};function V(t){return t.includes(e.tag)||t.includes(e.nthoftype)?[...t]:[...t,e.tag]}function Y(t={}){const n=[...w];return t[e.tag]&&t[e.nthoftype]&&n.splice(n.indexOf(e.tag),1),n.map((e=>{return(o=t)[n=e]?o[n].join(""):"";var n,o})).join("")}function B(t,e,n="",o){const r=function(t,e){return""===e?t:function(t,e){return[...t.map((t=>e+" "+t)),...t.map((t=>e+" > "+t))]}(t,e)}(function(t,e,n){const o=function(t,e){const{blacklist:n,whitelist:o,combineWithinSelector:r,maxCombinations:i}=e,c=h(n),u=h(o);return function(t){const{selectors:e,includeTag:n}=t,o=[].concat(e);return n&&!o.includes("tag")&&o.push("tag"),o}(e).reduce(((e,n)=>{const o=function(t,e){var n;return(null!==(n=q[e])&&void 0!==n?n:()=>[])(t)}(t,n),s=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(o,c,u),l=function(t=[],e){return t.sort(((t,n)=>{const o=e(t),r=e(n);return o&&!r?-1:!o&&r?1:0}))}(s,u);return e[n]=r?R(l,{maxResults:i}):l.map((t=>[t])),e}),{})}(t,n),r=function(t,e){return function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:o,maxCandidates:r}=t,i=n?R(e,{maxResults:r}):e.map((t=>[t]));return o?i.map(V):i}(e).map((e=>function(t,e){const n={};return t.forEach((t=>{const o=e[t];o.length>0&&(n[t]=o)})),function(t={}){let e=[];return Object.entries(t).forEach((([t,n])=>{e=n.flatMap((n=>0===e.length?[{[t]:n}]:e.map((e=>Object.assign(Object.assign({},e),{[t]:n})))))})),e}(n).map(Y)}(e,t))).filter((t=>t.length>0))}(o,n),i=p(r);return[...new Set(i)]}(t,o.root,o),n);for(const e of r)if(g(t,e,o.root))return e;return null}function G(t){return{value:t,include:!1}}function W({selectors:t,operator:n}){let o=[...w];t[e.tag]&&t[e.nthoftype]&&(o=o.filter((t=>t!==e.tag)));let r="";return o.forEach((e=>{(t[e]||[]).forEach((({value:t,include:e})=>{e&&(r+=t)}))})),n.value+r}function H(n){return[":root",...y(n).reverse().map((n=>{const o=function(e,n,o=t.NONE){const r={};return n.forEach((t=>{Reflect.set(r,t,function(t,e){return F[e](t)}(e,t).map(G))})),{element:e,operator:N[o],selectors:r}}(n,[e.nthchild],t.DESCENDANT);return o.selectors.nthchild.forEach((t=>{t.include=!0})),o})).map(W)].join("")}function U(t,n={}){const o=function(t){const e=(Array.isArray(t)?t:[t]).filter(r);return[...new Set(e)]}(t),i=function(t,n={}){const o=Object.assign(Object.assign({},c),n);return{selectors:(r=o.selectors,Array.isArray(r)?r.filter((t=>{return n=e,o=t,Object.values(n).includes(o);var n,o})):[]),whitelist:l(o.whitelist),blacklist:l(o.blacklist),root:f(o.root,t),combineWithinSelector:!!o.combineWithinSelector,combineBetweenSelectors:!!o.combineBetweenSelectors,includeTag:!!o.includeTag,maxCombinations:d(o.maxCombinations),maxCandidates:d(o.maxCandidates)};var r}(o[0],n);let u="",s=i.root;function a(){return function(t,e,n="",o){if(0===t.length)return null;const r=[t.length>1?t:[],...b(t,e).map((t=>[t]))];for(const t of r){const e=B(t,0,n,o);if(e)return{foundElements:t,selector:e}}return null}(o,s,u,i)}let m=a();for(;m;){const{foundElements:t,selector:e}=m;if(g(o,e,i.root))return e;s=t[0],u=e,m=a()}return o.length>1?o.map((t=>U(t,i))).join(", "):function(t){return t.map(H).join(", ")}(o)}const z=U;return o})()));',"text/javascript"))),jn=r=>Re(r,ft("JS-Before",()=>$(qi(`
|
|
333
333
|
window._readium_blockedEvents = [];
|
|
334
334
|
window._readium_blockEvents = true;
|
|
335
335
|
window._readium_eventBlocker = (e) => {
|
|
@@ -341,7 +341,7 @@ if(window.onload) window.onload = new Proxy(window.onload, {
|
|
|
341
341
|
]);
|
|
342
342
|
};
|
|
343
343
|
window.addEventListener("DOMContentLoaded", window._readium_eventBlocker, true);
|
|
344
|
-
window.addEventListener("load", window._readium_eventBlocker, true);`),"text/javascript"))),Vn=r=>
|
|
344
|
+
window.addEventListener("load", window._readium_eventBlocker, true);`),"text/javascript"))),Vn=r=>Re(r,ft("JS-After",()=>$(qi(`
|
|
345
345
|
if(window.onload) window.onload = new Proxy(window.onload, {
|
|
346
346
|
apply: function(target, receiver, args) {
|
|
347
347
|
if(!window._readium_blockEvents) {
|
|
@@ -352,7 +352,7 @@ if(window.onload) window.onload = new Proxy(window.onload, {
|
|
|
352
352
|
0, target, receiver, args
|
|
353
353
|
]);
|
|
354
354
|
}
|
|
355
|
-
});`),"text/javascript")));class _i{constructor(t,e,i,A){this.pub=t,this.item=i,this.burl=i.toURL(e)||"",this.cssProperties=A}async build(t=!1){if(this.item.mediaType.isHTML)return await this.buildHtmlFrame(t);if(this.item.mediaType.isBitmap)return this.buildImageFrame();throw Error("Unsupported frame mediatype "+this.item.mediaType.string)}async buildHtmlFrame(t=!1){const e=await this.pub.get(this.item).readAsString();if(!e)throw new Error(`Failed reading item ${this.item.href}`);const i=new DOMParser().parseFromString(e,this.item.mediaType.string),A=i.querySelector("parsererror");if(A){const n=A.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${n?.textContent||A.textContent}`)}return this.finalizeDOM(i,this.burl,this.item.mediaType,t,this.cssProperties)}buildImageFrame(){const t=document.implementation.createHTMLDocument(this.item.title||this.item.href),e=document.createElement("img");return e.src=this.burl||"",e.alt=this.item.title||"",e.decoding="async",t.body.appendChild(e),this.finalizeDOM(t,this.burl,this.item.mediaType,!0)}hasExecutable(t){return!!t.querySelector("script")||!!t.querySelector("body[onload]:not(body[onload=''])")}hasStyle(t){return!!(t.querySelector("link[rel='stylesheet']")||t.querySelector("style")||t.querySelector("[style]:not([style=''])"))}setProperties(t,e){for(const i in t){const A=t[i];A&&e.documentElement.style.setProperty(i,A)}}finalizeDOM(t,e,i,A=!1,n){if(!t)return"";if(!A){const o=Se(t,pt("ReadiumCSS-before",()=>tt(Re(Tn),"text/css")));t.head.firstChild?t.head.firstChild.before(o):t.head.appendChild(o),this.hasStyle(t)||o.after(Se(t,pt("ReadiumCSS-default",()=>tt(Re(xn),"text/css")))),t.head.appendChild(Se(t,pt("ReadiumCSS-after",()=>tt(Re(Nn),"text/css")))),n&&this.setProperties(n,t)}if(t.body.querySelectorAll("img").forEach(o=>{o.setAttribute("fetchpriority","high")}),i.isHTML&&this.pub.metadata.languages?.[0]){const o=this.pub.metadata.languages[0];if(i===d.XHTML){const a=document.documentElement.lang||document.documentElement.getAttribute("xml:lang"),h=document.body.lang||document.body.getAttribute("xml:lang");h&&!a?(document.documentElement.lang=h,document.documentElement.setAttribute("xml:lang",h),document.body.removeAttribute("xml:lang"),document.body.removeAttribute("lang")):a||(document.documentElement.lang=o,document.documentElement.setAttribute("xml:lang",o))}else i===d.HTML&&!document.documentElement.lang&&(document.documentElement.lang=o)}if(e!==void 0){const o=t.createElement("base");o.href=e,o.dataset.readium="true",t.head.firstChild.before(o)}const s=this.hasExecutable(t);return s&&t.head.firstChild.before(jn(t)),t.head.firstChild.before(bn(t)),s&&t.head.appendChild(Vn(t)),URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(t)],{type:i.isHTML?i.string:"application/xhtml+xml"}))}}class $i{constructor(t){this.hidden=!0,this.destroyed=!1,this.currModules=[],this.frame=document.createElement("iframe"),this.frame.classList.add("readium-navigator-iframe"),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transition="visibility 0s, opacity 0.1s linear",this.source=t}async load(t){return new Promise((e,i)=>{if(this.loader){const A=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...t].sort().join("|")){try{e(A)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new gt(A,t),this.currModules=t,this.comms=void 0;try{e(A)}catch{}return}this.frame.onload=()=>{const A=this.frame.contentWindow;this.loader=new gt(A,t),this.currModules=t;try{e(A)}catch{}},this.frame.onerror=A=>{try{i(A)}catch{}},this.frame.contentWindow.location.replace(this.source)})}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((t,e)=>{this.comms?.send("unfocus",void 0,i=>{this.comms?.halt(),t()})});this.comms?.halt()}}async show(t){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 dt(this.frame.contentWindow,this.source),new Promise((e,i)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{const A=()=>{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,mt.UA.WebKit&&this.comms?.send("force_webkit_recalc",void 0),e()};t!==void 0?this.comms?.send("go_progression",t,A):A()})})})}setCSSProperties(t){this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?this.comms?.resume():this.comms=new dt(this.frame.contentWindow,this.source)),this.comms?.send("update_properties",t),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 tA=5,eA=3;class iA{constructor(t,e,i){this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.pendingUpdates=new Map,this.container=t,this.positions=e,this.currentCssProperties=i}async destroy(){let t=this.inprogress.values(),e=t.next();const i=[];for(;e.value;)i.push(e.value),e=t.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let A=this.pool.values(),n=A.next();for(;n.value;)await n.value.destroy(),n=A.next();this.pool.clear(),this.blobs.forEach(s=>URL.revokeObjectURL(s)),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}async update(t,e,i,A=!1){let n=this.positions.findIndex(a=>a.locations.position===e.locations.position);if(n<0)throw Error(`Locator not found in position list: ${e.locations.position} > ${this.positions.reduce((a,h)=>h.locations.position||0>a?h.locations.position||0:a,0)}`);const s=this.positions[n].href;this.inprogress.has(s)&&await this.inprogress.get(s);const o=new Promise(async(a,h)=>{const c=[],g=[];this.positions.forEach((l,f)=>{(f>n+tA||f<n-tA)&&(c.includes(l.href)||c.push(l.href)),f<n+eA&&f>n-eA&&(g.includes(l.href)||g.push(l.href))}),c.forEach(async l=>{g.includes(l)||this.pool.has(l)&&(await this.pool.get(l)?.destroy(),this.pool.delete(l),this.pendingUpdates.has(l)&&this.pendingUpdates.set(l,{inPool:!1}))}),this.currentBaseURL!==void 0&&t.baseURL!==this.currentBaseURL&&(this.blobs.forEach(l=>URL.revokeObjectURL(l)),this.blobs.clear()),this.currentBaseURL=t.baseURL;const u=async l=>{if(A&&(this.blobs.forEach(F=>URL.revokeObjectURL(F)),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(l)&&this.pendingUpdates.get(l)?.inPool===!1){const F=this.blobs.get(l);F&&(URL.revokeObjectURL(F),this.blobs.delete(l),this.pendingUpdates.delete(l))}if(this.pool.has(l)){const F=this.pool.get(l);if(!this.blobs.has(l))await F.destroy(),this.pool.delete(l),this.pendingUpdates.delete(l);else{await F.load(i);return}}const f=t.readingOrder.findWithHref(l);if(!f)return;if(!this.blobs.has(l)){const S=await new _i(t,this.currentBaseURL||"",f,this.currentCssProperties).build();this.blobs.set(l,S)}const E=new $i(this.blobs.get(l));l!==s&&await E.hide(),this.container.appendChild(E.iframe),await E.load(i),this.pool.set(l,E)};try{await Promise.all(g.map(l=>u(l)))}catch(l){h(l)}const M=this.pool.get(s);(M?.source!==this._currentFrame?.source||A)&&(await this._currentFrame?.hide(),M&&await M.load(i),M&&await M.show(e.locations.progression),this._currentFrame=M),a()});this.inprogress.set(s,o),await o,this.inprogress.delete(s)}setCSSProperties(t){if(!((i,A)=>{const n=Object.keys(i),s=Object.keys(A);if(n.length!==s.length)return!1;for(const o of n)if(i[o]!==A[o])return!1;return!0})(this.currentCssProperties||{},t)){this.currentCssProperties=t,this.pool.forEach(i=>{i.setCSSProperties(t)});for(const i of this.blobs.keys())this.pendingUpdates.set(i,{inPool:this.pool.has(i)})}}get currentFrames(){return[this._currentFrame]}get currentBounds(){const t={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(e=>{if(!e)return;const i=e.realSize;t.x=Math.min(t.x,i.x),t.y=Math.min(t.y,i.y),t.width+=i.width,t.height=Math.max(t.height,i.height),t.top=Math.min(t.top,i.top),t.right=Math.min(t.right,i.right),t.bottom=Math.min(t.bottom,i.bottom),t.left=Math.min(t.left,i.left)}),t}}class AA{constructor(t,e,i){this.currModules=[],this.cachedPage=void 0,this.peripherals=t,this.debugHref=i,this.frame=document.createElement("iframe"),this.frame.classList.add("readium-navigator-iframe"),this.frame.classList.add("blank"),this.frame.scrolling="no",this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.display="none",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transformOrigin="0 0",this.frame.style.transform="scale(1)",this.frame.style.background="#fff",this.frame.style.touchAction="none",this.frame.dataset.originalHref=i,this.source="about:blank",this.wrapper=document.createElement("div"),this.wrapper.style.position="relative",this.wrapper.style.float=this.wrapper.style.cssFloat=e===Y.rtl?"right":"left",this.wrapper.appendChild(this.frame)}async load(t,e){return this.source===e&&this.loadPromise&&[...this.currModules].sort().join("|")===[...t].sort().join("|")?this.loadPromise:(this.loaded&&this.source!==e&&this.window.stop(),this.source=e,this.loadPromise=new Promise((i,A)=>{if(this.loader&&this.loaded){const n=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...t].sort().join("|")){try{i(n),this.loadPromise=void 0}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new gt(n,t),this.currModules=t,this.comms=void 0;try{i(n),this.loadPromise=void 0}catch{}return}this.frame.addEventListener("load",()=>{const n=this.frame.contentWindow;this.loader=new gt(n,t),this.currModules=t,this.peripherals.observe(this.wrapper),this.peripherals.observe(n);try{i(n)}catch{}},{once:!0}),this.frame.addEventListener("error",n=>{try{A(n.error),this.loadPromise=void 0}catch{}},{once:!0}),this.frame.style.removeProperty("display"),this.frame.contentWindow.location.replace(this.source)}),this.loadPromise)}loadPageSize(){const t=this.frame.contentWindow,e=t.document.head.querySelector("meta[name=viewport]");if(e){const i=/(\w+) *= *([^\s,]+)/g;let A,n=0,s=0;for(;A=i.exec(e.content);)A[1]==="width"?n=Number.parseFloat(A[2]):A[1]==="height"&&(s=Number.parseFloat(A[2]));if(n>0&&s>0)return{width:n,height:s}}return{width:t.document.body.scrollWidth,height:t.document.body.scrollHeight}}update(t){if(!this.loaded)return;const e=this.loadPageSize();this.frame.style.height=`${e.height}px`,this.frame.style.width=`${e.width}px`;const i=Math.min(this.wrapper.clientWidth/e.width,this.wrapper.clientHeight/e.height);this.frame.style.transform=`scale(${i})`;const A=this.frame.getBoundingClientRect(),n=this.wrapper.clientHeight-A.height;if(this.frame.style.top=`${n/2}px`,t===k.left){const s=this.wrapper.clientWidth-A.width;this.frame.style.left=`${s}px`}else if(t===k.center){const s=this.wrapper.clientWidth-A.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((t,e)=>{this.frame.addEventListener("load",()=>{try{this.showPromise=void 0,t()}catch{}},{once:!0}),this.frame.addEventListener("error",i=>{try{this.showPromise=void 0,e(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((t,e)=>{this.comms?.send("unfocus",void 0,i=>{this.comms?.halt(),this.showPromise=void 0,t()})});this.comms?.halt()}async show(t){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!==t&&(this.update(t),this.cachedPage=t),this.showPromise):(this.cachedPage=t,this.comms?this.comms.resume():this.comms=new dt(this.frame.contentWindow,this.source),this.showPromise=new Promise((e,i)=>{this.comms.send("focus",void 0,A=>{this.update(this.cachedPage),e()})}),this.showPromise)}async activate(){return new Promise((t,e)=>{if(!this.comms)return t();this.comms?.send("activate",void 0,()=>{t()})})}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(t){const e=`${t}%`;this.wrapper.style.width!==e&&(this.wrapper.style.width=e)}set height(t){const e=`${t}px`;this.wrapper.style.height!==e&&(this.wrapper.style.height=e)}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 nA=(r=>(r[r.Left=0]="Left",r[r.Center=1]="Center",r[r.Right=2]="Right",r))(nA||{}),rA=(r=>(r[r.Top=0]="Top",r[r.Middle=1]="Middle",r[r.Bottom=2]="Bottom",r))(rA||{});class sA{constructor(){this.outerWidth=0,this.outerHeight=0,this.HTML=document.documentElement,this.Head=document.head,this.Body=document.body}refreshOuterPixels(t){mt.OS.iOS||(this.outerHeight=window.outerHeight-window.innerHeight,mt.OS.Android&&mt.UA.Chrome&&window.screen.height>window.innerHeight&&(this.outerHeight=(window.screen.height-window.innerHeight)/1.5),this.outerWidth=window.outerWidth-window.innerWidth)}getBibiEventCoord(t,e=0){const i={X:0,Y:0};return/^touch/.test(t.type)?(i.X=t.touches[e].screenX,i.Y=t.touches[e].screenY):(i.X=t.screenX,i.Y=t.screenY),(t.target.ownerDocument?.documentElement||t.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(t){if(t.touches.length!==2)return 0;const e=t.touches[0].screenX-this.outerWidth,i=t.touches[0].screenY-this.outerHeight,A=t.touches[1].screenX-this.outerWidth,n=t.touches[1].screenY-this.outerHeight;return Math.sqrt(Math.pow(A-e,2)+Math.pow(n-i,2))}getTouchCenter(t){if(t.touches.length!==2)return null;const e=this.HTML.scrollLeft+this.Body.scrollLeft,i=this.HTML.scrollTop+this.Body.scrollTop,A=t.touches[0].screenX-this.outerWidth-e,n=t.touches[0].screenY-this.outerHeight-i,s=t.touches[1].screenX-this.outerWidth-e,o=t.touches[1].screenY-this.outerHeight-i;return{X:(A+s)/2,Y:(n+o)/2}}getBibiEvent(t){if(!t)return{Coord:null,Division:null,Ratio:null,Target:null};const e=this.getBibiEventCoord(t);let i=.3;const A={X:e.X/window.innerWidth,Y:e.Y/window.innerHeight};let n,s,o,a;o=n=i,a=s=1-i;const h={X:null,Y:null};return A.X<o?h.X=0:a<A.X?h.X=2:h.X=1,A.Y<n?h.Y=0:s<A.Y?h.Y=2:h.Y=1,{Target:t.target,Coord:e,Ratio:A,Division:h}}}class Pn{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 oA=6,ze=1.02,aA=50;class lA{constructor(t,e=!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=t,this.coordinator=new sA,this.attachEvents(),e&&(this.debugger=new Pn)}get scale(){return this._scale}set scale(t){isNaN(t)&&(t=1),window.clearTimeout(this.scaleDebouncer),this.scaleDebouncer=window.setTimeout(()=>{this.dragState===0&&this.scale<ze&&(this.pan.translateX=0,this.pan.translateY=0,this.clearPan(),this.manager.updateBookStyle()),this.manager.listener("zoom",t)},100),this._scale=t}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(t){t.addEventListener("touchstart",this.btouchstartHandler),t.addEventListener("touchend",this.btouchendHandler),t.addEventListener("touchmove",this.btouchmoveHandler,{passive:!0}),t.addEventListener("dblclick",this.bdblclickHandler,{passive:!0}),t.addEventListener("mousedown",this.bmousedownHandler),t.addEventListener("mouseup",this.bmouseupHandler),t.addEventListener("mousemove",this.bmousemoveHandler)}clickHandler(t){}touchstartHandler(t){if(["TEXTAREA","OPTION","INPUT","SELECT"].indexOf(t.target.nodeName)!==-1)return;switch(t.stopPropagation(),this.frameBounds=this.manager.currentBounds,this.coordinator.refreshOuterPixels(this.frameBounds),t.touches.length){case 3:return;case 2:{t.preventDefault(),this.pinch.startDistance=this.coordinator.getTouchDistance(t);const A=this.startTouch(t);this.pan.startX=A.X,this.pan.startY=A.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=t.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(t);this.pan.startX=i.X,this.pan.startY=i.Y}startTouch(t){const e=this.coordinator.getTouchCenter(t)||this.coordinator.getBibiEventCoord(t);return{X:e.X-this.manager.width/2-this.pan.translateX*this.scale+this.manager.width/2,Y:e.Y-this.manager.height/2-this.pan.translateY*this.scale+this.manager.height/2}}touchendHandler(t){if(t.stopPropagation(),!t.touches||t.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)>aA&&Math.abs(this.pan.overscrollY)<aA/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(t.touches.length===1){this.dragState=1,t.touches[0].identifier!==this.pan.touchID&&(this.pan.touchID=t.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 e=this.startTouch(t);this.pan.startX=e.X,this.pan.startY=e.Y}window.setTimeout(()=>{this.manager.updateBookStyle(!0),this.dragState===0&&(this.scale<ze&&(this.pan.translateX=0,this.pan.translateY=0),this.clearPan()),this.manager.updateBookStyle(!0)},50)}touchmoveHandler(t){t.stopPropagation();const e=this.coordinator.getBibiEventCoord(t);Math.abs(this.pan.startY-e.Y)+Math.abs(this.pan.startX-e.X)>5&&(this.minimumMoved||(this.manager.deselect(),this.minimumMoved=!0),this.dragState<1&&(this.dragState=1));const i=this.coordinator?.getTouchDistance(t);let A=!1;const n=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>=oA&&(s=oA),s<=ze&&(s=1),this.scale=s,this.pinch.startDistance=i,A=!0}if(this.pan.letItGo===!1&&(this.pan.letItGo=Math.abs(this.pan.startY-e.Y)<Math.abs(this.pan.startX-e.X)),this.debugger?.show&&(this.debugger.DOM.touch1.style.top=`${e.Y-10}px`,this.debugger.DOM.touch1.style.left=`${e.X-10}px`,this.debugger.DOM.touch1.innerText=`${e.X.toFixed(2)},${e.Y.toFixed(2)}`),this.dragState>0&&this.isScaled||this.dragState>1){if(this.dragState===1){const a={X:e.X-this.manager.width/2,Y:e.Y-this.manager.height/2};this.pan.translateX=(a.X-(this.pan.startX-this.manager.width/2))*1/this.scale,this.pan.translateY=(a.Y-(this.pan.startY-this.manager.height/2))*1/this.scale}else if(this.dragState===2){const a=this.coordinator.getTouchCenter(t);if(this.debugger?.show){this.debugger.DOM.center.style.top=`${a.Y-5}px`,this.debugger.DOM.center.style.left=`${a.X-5}px`,this.debugger.DOM.center.innerText=`${a.X.toFixed(2)},${a.Y.toFixed(2)}`;const M=this.coordinator.getBibiEventCoord(t,1);this.debugger.DOM.touch2.style.top=`${M.Y-10}px`,this.debugger.DOM.touch2.style.left=`${M.X-10}px`,this.debugger.DOM.touch2.innerText=`${M.X.toFixed(2)},${M.Y.toFixed(2)}`}a.X-=this.manager.width/2,a.Y-=this.manager.height/2;let h=-a.X/n;h+=a.X/this.scale,this.pinch.target.X+=h,a.X+=this.pinch.target.X*this.scale/this.pinch.startScale;let c=-a.Y/n;c+=a.Y/this.scale,this.pinch.target.Y+=c,a.Y+=this.pinch.target.Y*this.scale/this.pinch.startScale;let g=(a.X-(this.pan.startX-this.manager.width/2))*1/this.scale,u=(a.Y-(this.pan.startY-this.manager.height/2))*1/this.scale;this.pan.translateX=g,this.pan.translateY=u,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,o=this.frameBounds.height/6;this.pan.translateX<-s&&(this.pan.overscrollX=-(s+this.pan.translateX),this.pan.translateX=-s),this.pan.translateY<-o&&(this.pan.overscrollY=-(o+this.pan.translateY),this.pan.translateY=-o),this.pan.translateX>s&&(this.pan.overscrollX=s-this.pan.translateX,this.pan.translateX=s),this.pan.translateY>o&&(this.pan.overscrollY=o-this.pan.translateY,this.pan.translateY=o),A=!0,this.debugger?.show&&(this.debugger.DOM.stats.innerText=`TX: ${this.pan.translateX.toFixed(2)}
|
|
355
|
+
});`),"text/javascript")));class _i{constructor(t,e,i,A){this.pub=t,this.item=i,this.burl=i.toURL(e)||"",this.cssProperties=A}async build(t=!1){if(this.item.mediaType.isHTML)return await this.buildHtmlFrame(t);if(this.item.mediaType.isBitmap)return this.buildImageFrame();throw Error("Unsupported frame mediatype "+this.item.mediaType.string)}async buildHtmlFrame(t=!1){const e=await this.pub.get(this.item).readAsString();if(!e)throw new Error(`Failed reading item ${this.item.href}`);const i=new DOMParser().parseFromString(e,this.item.mediaType.string),A=i.querySelector("parsererror");if(A){const n=A.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${n?.textContent||A.textContent}`)}return this.finalizeDOM(i,this.burl,this.item.mediaType,t,this.cssProperties)}buildImageFrame(){const t=document.implementation.createHTMLDocument(this.item.title||this.item.href),e=document.createElement("img");return e.src=this.burl||"",e.alt=this.item.title||"",e.decoding="async",t.body.appendChild(e),this.finalizeDOM(t,this.burl,this.item.mediaType,!0)}hasExecutable(t){return!!t.querySelector("script")||!!t.querySelector("body[onload]:not(body[onload=''])")}hasStyle(t){return!!(t.querySelector("link[rel='stylesheet']")||t.querySelector("style")||t.querySelector("[style]:not([style=''])"))}setProperties(t,e){for(const i in t){const A=t[i];A&&e.documentElement.style.setProperty(i,A)}}finalizeDOM(t,e,i,A=!1,n){if(!t)return"";if(!A){const o=Ce(t,ft("ReadiumCSS-before",()=>$(Ue(xn),"text/css")));t.head.firstChild?t.head.firstChild.before(o):t.head.appendChild(o),this.hasStyle(t)||o.after(Ce(t,ft("ReadiumCSS-default",()=>$(Ue(Tn),"text/css")))),t.head.appendChild(Ce(t,ft("ReadiumCSS-after",()=>$(Ue(Nn),"text/css")))),n&&this.setProperties(n,t)}if(t.body.querySelectorAll("img").forEach(o=>{o.setAttribute("fetchpriority","high")}),i.isHTML&&this.pub.metadata.languages?.[0]){const o=this.pub.metadata.languages[0];if(i===d.XHTML){const a=document.documentElement.lang||document.documentElement.getAttribute("xml:lang"),h=document.body.lang||document.body.getAttribute("xml:lang");h&&!a?(document.documentElement.lang=h,document.documentElement.setAttribute("xml:lang",h),document.body.removeAttribute("xml:lang"),document.body.removeAttribute("lang")):a||(document.documentElement.lang=o,document.documentElement.setAttribute("xml:lang",o))}else i===d.HTML&&!document.documentElement.lang&&(document.documentElement.lang=o)}if(e!==void 0){const o=t.createElement("base");o.href=e,o.dataset.readium="true",t.head.firstChild.before(o)}const s=this.hasExecutable(t);return s&&t.head.firstChild.before(jn(t)),t.head.firstChild.before(bn(t)),s&&t.head.appendChild(Vn(t)),URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(t)],{type:i.isHTML?i.string:"application/xhtml+xml"}))}}class $i{constructor(t){this.hidden=!0,this.destroyed=!1,this.currModules=[],this.frame=document.createElement("iframe"),this.frame.classList.add("readium-navigator-iframe"),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transition="visibility 0s, opacity 0.1s linear",this.source=t}async load(t){return new Promise((e,i)=>{if(this.loader){const A=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...t].sort().join("|")){try{e(A)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new ct(A,t),this.currModules=t,this.comms=void 0;try{e(A)}catch{}return}this.frame.onload=()=>{const A=this.frame.contentWindow;this.loader=new ct(A,t),this.currModules=t;try{e(A)}catch{}},this.frame.onerror=A=>{try{i(A)}catch{}},this.frame.contentWindow.location.replace(this.source)})}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((t,e)=>{this.comms?.send("unfocus",void 0,i=>{this.comms?.halt(),t()})});this.comms?.halt()}}async show(t){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 gt(this.frame.contentWindow,this.source),new Promise((e,i)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{const A=()=>{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,ut.UA.WebKit&&this.comms?.send("force_webkit_recalc",void 0),e()};t!==void 0?this.comms?.send("go_progression",t,A):A()})})})}setCSSProperties(t){this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?this.comms?.resume():this.comms=new gt(this.frame.contentWindow,this.source)),this.comms?.send("update_properties",t),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 tA=5,eA=3;class iA{constructor(t,e,i){this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.pendingUpdates=new Map,this.container=t,this.positions=e,this.currentCssProperties=i}async destroy(){let t=this.inprogress.values(),e=t.next();const i=[];for(;e.value;)i.push(e.value),e=t.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let A=this.pool.values(),n=A.next();for(;n.value;)await n.value.destroy(),n=A.next();this.pool.clear(),this.blobs.forEach(s=>URL.revokeObjectURL(s)),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}async update(t,e,i,A=!1){let n=this.positions.findIndex(a=>a.locations.position===e.locations.position);if(n<0)throw Error(`Locator not found in position list: ${e.locations.position} > ${this.positions.reduce((a,h)=>h.locations.position||0>a?h.locations.position||0:a,0)}`);const s=this.positions[n].href;this.inprogress.has(s)&&await this.inprogress.get(s);const o=new Promise(async(a,h)=>{const c=[],g=[];this.positions.forEach((l,f)=>{(f>n+tA||f<n-tA)&&(c.includes(l.href)||c.push(l.href)),f<n+eA&&f>n-eA&&(g.includes(l.href)||g.push(l.href))}),c.forEach(async l=>{g.includes(l)||this.pool.has(l)&&(await this.pool.get(l)?.destroy(),this.pool.delete(l),this.pendingUpdates.has(l)&&this.pendingUpdates.set(l,{inPool:!1}))}),this.currentBaseURL!==void 0&&t.baseURL!==this.currentBaseURL&&(this.blobs.forEach(l=>URL.revokeObjectURL(l)),this.blobs.clear()),this.currentBaseURL=t.baseURL;const u=async l=>{if(A&&(this.blobs.forEach(F=>URL.revokeObjectURL(F)),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(l)&&this.pendingUpdates.get(l)?.inPool===!1){const F=this.blobs.get(l);F&&(URL.revokeObjectURL(F),this.blobs.delete(l),this.pendingUpdates.delete(l))}if(this.pool.has(l)){const F=this.pool.get(l);if(!this.blobs.has(l))await F.destroy(),this.pool.delete(l),this.pendingUpdates.delete(l);else{await F.load(i);return}}const f=t.readingOrder.findWithHref(l);if(!f)return;if(!this.blobs.has(l)){const S=await new _i(t,this.currentBaseURL||"",f,this.currentCssProperties).build();this.blobs.set(l,S)}const E=new $i(this.blobs.get(l));l!==s&&await E.hide(),this.container.appendChild(E.iframe),await E.load(i),this.pool.set(l,E)};try{await Promise.all(g.map(l=>u(l)))}catch(l){h(l)}const M=this.pool.get(s);(M?.source!==this._currentFrame?.source||A)&&(await this._currentFrame?.hide(),M&&await M.load(i),M&&await M.show(e.locations.progression),this._currentFrame=M),a()});this.inprogress.set(s,o),await o,this.inprogress.delete(s)}setCSSProperties(t){if(!((i,A)=>{const n=Object.keys(i),s=Object.keys(A);if(n.length!==s.length)return!1;for(const o of n)if(i[o]!==A[o])return!1;return!0})(this.currentCssProperties||{},t)){this.currentCssProperties=t,this.pool.forEach(i=>{i.setCSSProperties(t)});for(const i of this.blobs.keys())this.pendingUpdates.set(i,{inPool:this.pool.has(i)})}}get currentFrames(){return[this._currentFrame]}get currentBounds(){const t={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(e=>{if(!e)return;const i=e.realSize;t.x=Math.min(t.x,i.x),t.y=Math.min(t.y,i.y),t.width+=i.width,t.height=Math.max(t.height,i.height),t.top=Math.min(t.top,i.top),t.right=Math.min(t.right,i.right),t.bottom=Math.min(t.bottom,i.bottom),t.left=Math.min(t.left,i.left)}),t}}class AA{constructor(t,e,i){this.currModules=[],this.cachedPage=void 0,this.peripherals=t,this.debugHref=i,this.frame=document.createElement("iframe"),this.frame.classList.add("readium-navigator-iframe"),this.frame.classList.add("blank"),this.frame.scrolling="no",this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.display="none",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transformOrigin="0 0",this.frame.style.transform="scale(1)",this.frame.style.background="#fff",this.frame.style.touchAction="none",this.frame.dataset.originalHref=i,this.source="about:blank",this.wrapper=document.createElement("div"),this.wrapper.style.position="relative",this.wrapper.style.float=this.wrapper.style.cssFloat=e===Y.rtl?"right":"left",this.wrapper.appendChild(this.frame)}async load(t,e){return this.source===e&&this.loadPromise&&[...this.currModules].sort().join("|")===[...t].sort().join("|")?this.loadPromise:(this.loaded&&this.source!==e&&this.window.stop(),this.source=e,this.loadPromise=new Promise((i,A)=>{if(this.loader&&this.loaded){const n=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...t].sort().join("|")){try{i(n),this.loadPromise=void 0}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new ct(n,t),this.currModules=t,this.comms=void 0;try{i(n),this.loadPromise=void 0}catch{}return}this.frame.addEventListener("load",()=>{const n=this.frame.contentWindow;this.loader=new ct(n,t),this.currModules=t,this.peripherals.observe(this.wrapper),this.peripherals.observe(n);try{i(n)}catch{}},{once:!0}),this.frame.addEventListener("error",n=>{try{A(n.error),this.loadPromise=void 0}catch{}},{once:!0}),this.frame.style.removeProperty("display"),this.frame.contentWindow.location.replace(this.source)}),this.loadPromise)}loadPageSize(){const t=this.frame.contentWindow,e=t.document.head.querySelector("meta[name=viewport]");if(e){const i=/(\w+) *= *([^\s,]+)/g;let A,n=0,s=0;for(;A=i.exec(e.content);)A[1]==="width"?n=Number.parseFloat(A[2]):A[1]==="height"&&(s=Number.parseFloat(A[2]));if(n>0&&s>0)return{width:n,height:s}}return{width:t.document.body.scrollWidth,height:t.document.body.scrollHeight}}update(t){if(!this.loaded)return;const e=this.loadPageSize();this.frame.style.height=`${e.height}px`,this.frame.style.width=`${e.width}px`;const i=Math.min(this.wrapper.clientWidth/e.width,this.wrapper.clientHeight/e.height);this.frame.style.transform=`scale(${i})`;const A=this.frame.getBoundingClientRect(),n=this.wrapper.clientHeight-A.height;if(this.frame.style.top=`${n/2}px`,t===G.left){const s=this.wrapper.clientWidth-A.width;this.frame.style.left=`${s}px`}else if(t===G.center){const s=this.wrapper.clientWidth-A.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((t,e)=>{this.frame.addEventListener("load",()=>{try{this.showPromise=void 0,t()}catch{}},{once:!0}),this.frame.addEventListener("error",i=>{try{this.showPromise=void 0,e(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((t,e)=>{this.comms?.send("unfocus",void 0,i=>{this.comms?.halt(),this.showPromise=void 0,t()})});this.comms?.halt()}async show(t){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!==t&&(this.update(t),this.cachedPage=t),this.showPromise):(this.cachedPage=t,this.comms?this.comms.resume():this.comms=new gt(this.frame.contentWindow,this.source),this.showPromise=new Promise((e,i)=>{this.comms.send("focus",void 0,A=>{this.update(this.cachedPage),e()})}),this.showPromise)}async activate(){return new Promise((t,e)=>{if(!this.comms)return t();this.comms?.send("activate",void 0,()=>{t()})})}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(t){const e=`${t}%`;this.wrapper.style.width!==e&&(this.wrapper.style.width=e)}set height(t){const e=`${t}px`;this.wrapper.style.height!==e&&(this.wrapper.style.height=e)}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 nA=(r=>(r[r.Left=0]="Left",r[r.Center=1]="Center",r[r.Right=2]="Right",r))(nA||{}),rA=(r=>(r[r.Top=0]="Top",r[r.Middle=1]="Middle",r[r.Bottom=2]="Bottom",r))(rA||{});class sA{constructor(){this.outerWidth=0,this.outerHeight=0,this.HTML=document.documentElement,this.Head=document.head,this.Body=document.body}refreshOuterPixels(t){ut.OS.iOS||(this.outerHeight=window.outerHeight-window.innerHeight,ut.OS.Android&&ut.UA.Chrome&&window.screen.height>window.innerHeight&&(this.outerHeight=(window.screen.height-window.innerHeight)/1.5),this.outerWidth=window.outerWidth-window.innerWidth)}getBibiEventCoord(t,e=0){const i={X:0,Y:0};return/^touch/.test(t.type)?(i.X=t.touches[e].screenX,i.Y=t.touches[e].screenY):(i.X=t.screenX,i.Y=t.screenY),(t.target.ownerDocument?.documentElement||t.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(t){if(t.touches.length!==2)return 0;const e=t.touches[0].screenX-this.outerWidth,i=t.touches[0].screenY-this.outerHeight,A=t.touches[1].screenX-this.outerWidth,n=t.touches[1].screenY-this.outerHeight;return Math.sqrt(Math.pow(A-e,2)+Math.pow(n-i,2))}getTouchCenter(t){if(t.touches.length!==2)return null;const e=this.HTML.scrollLeft+this.Body.scrollLeft,i=this.HTML.scrollTop+this.Body.scrollTop,A=t.touches[0].screenX-this.outerWidth-e,n=t.touches[0].screenY-this.outerHeight-i,s=t.touches[1].screenX-this.outerWidth-e,o=t.touches[1].screenY-this.outerHeight-i;return{X:(A+s)/2,Y:(n+o)/2}}getBibiEvent(t){if(!t)return{Coord:null,Division:null,Ratio:null,Target:null};const e=this.getBibiEventCoord(t);let i=.3;const A={X:e.X/window.innerWidth,Y:e.Y/window.innerHeight};let n,s,o,a;o=n=i,a=s=1-i;const h={X:null,Y:null};return A.X<o?h.X=0:a<A.X?h.X=2:h.X=1,A.Y<n?h.Y=0:s<A.Y?h.Y=2:h.Y=1,{Target:t.target,Coord:e,Ratio:A,Division:h}}}class Pn{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 oA=6,Qe=1.02,aA=50;class lA{constructor(t,e=!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=t,this.coordinator=new sA,this.attachEvents(),e&&(this.debugger=new Pn)}get scale(){return this._scale}set scale(t){isNaN(t)&&(t=1),window.clearTimeout(this.scaleDebouncer),this.scaleDebouncer=window.setTimeout(()=>{this.dragState===0&&this.scale<Qe&&(this.pan.translateX=0,this.pan.translateY=0,this.clearPan(),this.manager.updateBookStyle()),this.manager.listener("zoom",t)},100),this._scale=t}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(t){t.addEventListener("touchstart",this.btouchstartHandler),t.addEventListener("touchend",this.btouchendHandler),t.addEventListener("touchmove",this.btouchmoveHandler,{passive:!0}),t.addEventListener("dblclick",this.bdblclickHandler,{passive:!0}),t.addEventListener("mousedown",this.bmousedownHandler),t.addEventListener("mouseup",this.bmouseupHandler),t.addEventListener("mousemove",this.bmousemoveHandler)}clickHandler(t){}touchstartHandler(t){if(["TEXTAREA","OPTION","INPUT","SELECT"].indexOf(t.target.nodeName)!==-1)return;switch(t.stopPropagation(),this.frameBounds=this.manager.currentBounds,this.coordinator.refreshOuterPixels(this.frameBounds),t.touches.length){case 3:return;case 2:{t.preventDefault(),this.pinch.startDistance=this.coordinator.getTouchDistance(t);const A=this.startTouch(t);this.pan.startX=A.X,this.pan.startY=A.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=t.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(t);this.pan.startX=i.X,this.pan.startY=i.Y}startTouch(t){const e=this.coordinator.getTouchCenter(t)||this.coordinator.getBibiEventCoord(t);return{X:e.X-this.manager.width/2-this.pan.translateX*this.scale+this.manager.width/2,Y:e.Y-this.manager.height/2-this.pan.translateY*this.scale+this.manager.height/2}}touchendHandler(t){if(t.stopPropagation(),!t.touches||t.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)>aA&&Math.abs(this.pan.overscrollY)<aA/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(t.touches.length===1){this.dragState=1,t.touches[0].identifier!==this.pan.touchID&&(this.pan.touchID=t.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 e=this.startTouch(t);this.pan.startX=e.X,this.pan.startY=e.Y}window.setTimeout(()=>{this.manager.updateBookStyle(!0),this.dragState===0&&(this.scale<Qe&&(this.pan.translateX=0,this.pan.translateY=0),this.clearPan()),this.manager.updateBookStyle(!0)},50)}touchmoveHandler(t){t.stopPropagation();const e=this.coordinator.getBibiEventCoord(t);Math.abs(this.pan.startY-e.Y)+Math.abs(this.pan.startX-e.X)>5&&(this.minimumMoved||(this.manager.deselect(),this.minimumMoved=!0),this.dragState<1&&(this.dragState=1));const i=this.coordinator?.getTouchDistance(t);let A=!1;const n=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>=oA&&(s=oA),s<=Qe&&(s=1),this.scale=s,this.pinch.startDistance=i,A=!0}if(this.pan.letItGo===!1&&(this.pan.letItGo=Math.abs(this.pan.startY-e.Y)<Math.abs(this.pan.startX-e.X)),this.debugger?.show&&(this.debugger.DOM.touch1.style.top=`${e.Y-10}px`,this.debugger.DOM.touch1.style.left=`${e.X-10}px`,this.debugger.DOM.touch1.innerText=`${e.X.toFixed(2)},${e.Y.toFixed(2)}`),this.dragState>0&&this.isScaled||this.dragState>1){if(this.dragState===1){const a={X:e.X-this.manager.width/2,Y:e.Y-this.manager.height/2};this.pan.translateX=(a.X-(this.pan.startX-this.manager.width/2))*1/this.scale,this.pan.translateY=(a.Y-(this.pan.startY-this.manager.height/2))*1/this.scale}else if(this.dragState===2){const a=this.coordinator.getTouchCenter(t);if(this.debugger?.show){this.debugger.DOM.center.style.top=`${a.Y-5}px`,this.debugger.DOM.center.style.left=`${a.X-5}px`,this.debugger.DOM.center.innerText=`${a.X.toFixed(2)},${a.Y.toFixed(2)}`;const M=this.coordinator.getBibiEventCoord(t,1);this.debugger.DOM.touch2.style.top=`${M.Y-10}px`,this.debugger.DOM.touch2.style.left=`${M.X-10}px`,this.debugger.DOM.touch2.innerText=`${M.X.toFixed(2)},${M.Y.toFixed(2)}`}a.X-=this.manager.width/2,a.Y-=this.manager.height/2;let h=-a.X/n;h+=a.X/this.scale,this.pinch.target.X+=h,a.X+=this.pinch.target.X*this.scale/this.pinch.startScale;let c=-a.Y/n;c+=a.Y/this.scale,this.pinch.target.Y+=c,a.Y+=this.pinch.target.Y*this.scale/this.pinch.startScale;let g=(a.X-(this.pan.startX-this.manager.width/2))*1/this.scale,u=(a.Y-(this.pan.startY-this.manager.height/2))*1/this.scale;this.pan.translateX=g,this.pan.translateY=u,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,o=this.frameBounds.height/6;this.pan.translateX<-s&&(this.pan.overscrollX=-(s+this.pan.translateX),this.pan.translateX=-s),this.pan.translateY<-o&&(this.pan.overscrollY=-(o+this.pan.translateY),this.pan.translateY=-o),this.pan.translateX>s&&(this.pan.overscrollX=s-this.pan.translateX,this.pan.translateX=s),this.pan.translateY>o&&(this.pan.overscrollY=o-this.pan.translateY,this.pan.translateY=o),A=!0,this.debugger?.show&&(this.debugger.DOM.stats.innerText=`TX: ${this.pan.translateX.toFixed(2)}
|
|
356
356
|
TY: ${this.pan.translateY.toFixed(2)}
|
|
357
357
|
Zoom: ${this.scale.toFixed(2)}
|
|
358
|
-
Overscroll: ${this.pan.overscrollX.toFixed(2)},${this.pan.overscrollY.toFixed(2)}`)}if(A){this.manager.updateBookStyle();return}if(this.dragState>0&&this.pan.letItGo){this.pan.endX=e.X;const o=this.manager.currentSlide*(this.manager.width/this.manager.perPage),a=this.pan.endX-this.pan.startX,h=this.manager.rtl?o+a:o-a;cancelAnimationFrame(this.moveFrame),this.moveFrame=requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.manager.spineElement.style.transform=`translate3d(${(this.manager.rtl?1:-1)*h}px, 0, 0)`})})}}dblclickHandler(t){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(t){t.touches=[{pageX:t.pageX,pageY:t.pageY}]}mousedownHandler(t){this.isScaled&&(this.addTouch(t),this.touchstartHandler(t))}mouseupHandler(t){this.isScaled&&this.touchendHandler(t)}mousemoveHandler(t){this.isScaled&&t.buttons>0&&(t.preventDefault(),this.addTouch(t),this.touchmoveHandler(t))}updateAfterDrag(){const t=(this.manager.rtl?-1:1)*(this.pan.endX-this.pan.startX),e=Math.abs(t);t>0&&e>this.manager.threshold&&this.manager.slength>this.manager.perPage?this.manager.listener("no_less",void 0):t<0&&e>this.manager.threshold&&this.manager.slength>this.manager.perPage&&this.manager.listener("no_more",void 0),this.manager.slideToCurrent(!0,!0)}}var Xt=(r=>(r.auto="auto",r.landscape="landscape",r.portrait="portrait",r))(Xt||{}),Zt=(r=>(r.auto="auto",r.both="both",r.none="none",r.landscape="landscape",r))(Zt||{});class hA{constructor(t){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`)}index(t,e=!1){this.nLandscape=0,t.readingOrder.items.forEach((i,A)=>{e||(t.readingOrder.items[A]=i.addProperties({number:A+1,isImage:i.type?.indexOf("image/")===0}));const n=i.properties?.otherProperties.orientation==="landscape";(!i.properties?.page||e)&&(i.properties=i.properties?.add({page:n?"center":((this.shift?0:1)+A-this.nLandscape)%2?t.metadata.readingProgression===Y.rtl?"right":"left":t.metadata.readingProgression===Y.rtl?"left":"right"})),(n||i.properties?.otherProperties.addBlank)&&this.nLandscape++}),e&&(this.spreads=[]),this.buildSpreads(t.readingOrder)}testShift(t){let e=!1;this.spreads.forEach((i,A)=>{if(i.length>1)return;const n=i[0],s=n.properties?.otherProperties.orientation;A===0&&(s==="landscape"||s!=="portrait"&&((n.width||0)>(n.height||0)||n.properties?.otherProperties.spread==="both"))&&(this.shift=!1),e&&n.properties?.page===k.center&&this.spreads[A-1][0].addProperties({addBlank:!0}),s==="portrait"&&n.properties?.page!=="center"&&n.properties?.otherProperties.number>1?e=!0:e=!1}),this.shift||this.index(t,!0)}buildSpreads(t){let e=[];t.items.forEach((i,A)=>{!A&&this.shift?this.spreads.push([i]):i.properties?.page===k.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)}),e.length>0&&this.spreads.push(e)}currentSpread(t,e){return this.spreads[Math.min(Math.floor(t/e),this.spreads.length-1)]}findByLink(t){return this.spreads.find(e=>e.includes(t))||void 0}}const cA=8,gA=5,vn=300,Dn=15e3,Hn=250,Gn=150,kn=500;class dA{constructor(t,e,i){if(this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.delayedShow=new Map,this.delayedTimeout=new Map,this.previousFrames=[],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.spreadPresentation=i.metadata.otherMetadata?.spread||Zt.auto,this.pub.metadata.effectiveReadingProgression!==Y.rtl&&this.pub.metadata.effectiveReadingProgression!==Y.ltr)throw Error("Unsupported reading progression for EPUB");this.spreader=new hA(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 lA(this),this.pub.readingOrder.items.forEach(A=>{const n=new AA(this.peripherals,this.pub.metadata.effectiveReadingProgression,A.href);this.spineElement.appendChild(n.element),this.pool.set(A.href,n),n.width=100/this.length*(A.properties?.otherProperties.orientation===Xt.landscape||A.properties?.otherProperties.addBlank?this.perPage:1),n.height=this.height})}set listener(t){this._listener=t}get listener(){return this._listener}get doNotDisturb(){return this.peripherals.pan.touchID>0}resizeHandler(t=!0,e=!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),t&&(this.currentSlide=this.reAlign(),this.slideToCurrent(!e,e)),clearTimeout(this.resizeTimeout),this.resizeTimeout=window.setTimeout(()=>{this.pool.forEach((i,A)=>{let n=this.pub.readingOrder.items.findIndex(a=>a.href===A);const s=this.pub.readingOrder.items[n];if(i.width=100/this.length*(s.properties?.otherProperties.orientation===Xt.landscape||s.properties?.otherProperties.addBlank?this.perPage:1),i.height=this.height,!i.loaded)return;const o=this.spreader.findByLink(s);i.update(this.spreadPosition(o,s))})},Hn)}updateDimensions(){this.width=this.bookElement.clientWidth,this.height=this.bookElement.clientHeight}get rtl(){return this.pub.metadata.effectiveReadingProgression===Y.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===Zt.none?!0:(this.orientationInternal===-1&&(this.orientationInternal=this.containerHeightCached>this.container.clientWidth?1:0),this.orientationInternal===1)}updateSpineStyle(t,e=!0){let i="0";this.updateDimensions(),this.perPage>1&&(i=`${this.width/2}px`);const A={transition:t?`all ${e?Gn:kn}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,A)}updateBookStyle(t=!1){if(t){const e={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,e)}this.bookElement.style.transform=`scale(${this.peripherals?.scale||1})`+(this.peripherals?` translate3d(${this.peripherals.pan.translateX}px, ${this.peripherals.pan.translateY}px, 0px)`:"")}goTo(t){if(this.slength<=this.perPage)return;t=this.reAlign(t);const e=this.currentSlide;this.currentSlide=Math.min(Math.max(t,0),this.length-1),e!==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 t=this.slength+this.nLandscape;return this.shift&&t%2===0?t+1:t}get slength(){return this.pub.readingOrder.items.length||0}get shift(){return this.spreader.shift}get nLandscape(){return this.spreader.nLandscape}setPerPage(t){t===null?this.spread=!0:t===1?this.spread=!1:this.spread=!0,requestAnimationFrame(()=>this.resizeHandler(!0))}slideToCurrent(t,e=!0){if(this.updateDimensions(),t)requestAnimationFrame(()=>{requestAnimationFrame(()=>{const i=`translate3d(${this.offset}px, 0, 0)`;this.spineElement.style.transform!==i&&(this.transform=i,this.updateSpineStyle(!0,e),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(t=!1){requestAnimationFrame(()=>{this.transform=`translate3d(${this.offset+50*(t?1:-1)}px, 0, 0)`,this.updateSpineStyle(!0,!0),setTimeout(()=>{this.transform=`translate3d(${this.offset}px, 0, 0)`,this.updateSpineStyle(!0,!0)},100)})}next(t=1){if(this.slength<=this.perPage)return!1;const e=this.currentSlide;return this.currentSlide=Math.min(this.currentSlide+t,this.length-1),this.perPage>1&&this.currentSlide%2&&this.currentSlide--,this.currentSlide===e&&(this.currentSlide+1,this.length),e!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(this.rtl),!1)}prev(t=1){if(this.slength<=this.perPage)return!1;const e=this.currentSlide;return this.currentSlide=Math.max(this.currentSlide-t,0),this.perPage>1&&this.currentSlide%2&&this.currentSlide++,e!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(!this.rtl),!1)}get ownerWindow(){return this.container.ownerDocument.defaultView||window}async destroy(){let t=this.inprogress.values(),e=t.next();const i=[];for(;e.value;)i.push(e.value),e=t.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let A=this.pool.values(),n=A.next();for(;n.value;)await n.value.destroy(),n=A.next();this.pool.clear(),this.blobs.forEach(s=>URL.revokeObjectURL(s)),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}makeSpread(t){return this.perPage<2?[this.pub.readingOrder.items[t]]:this.spreader.currentSpread(t,this.perPage)}reAlign(t=this.currentSlide){return t%2&&!this.single&&t++,t}spreadPosition(t,e){return this.perPage<2||t.length<2?k.center:e.href===t[0].href?this.rtl?k.right:k.left:this.rtl?k.left:k.right}async waitForItem(t){if(this.inprogress.has(t)&&await this.inprogress.get(t),this.delayedShow.has(t)){const e=this.delayedTimeout.get(t);e>0?clearTimeout(e):await this.delayedShow.get(t),this.delayedTimeout.set(t,0),this.delayedShow.delete(t)}}async cancelShowing(t){if(this.delayedShow.has(t)){const e=this.delayedTimeout.get(t);e>0&&clearTimeout(e),this.delayedShow.delete(t)}}async update(t,e,i,A=!1){let n=this.pub.readingOrder.items.findIndex(a=>a.href===e.href);if(n<0)throw Error("Href not found in reading order");this.currentSlide!==n&&(this.currentSlide=this.reAlign(n),this.slideToCurrent(!0));const s=this.makeSpread(this.currentSlide);this.perPage>1&&n++;for(const a of s)await this.waitForItem(a.href);const o=new Promise(async(a,h)=>{const c=[],g=[];this.positions.forEach((l,f)=>{(f>n+cA||f<n-cA)&&(c.includes(l.href)||c.push(l.href)),f<n+gA&&f>n-gA&&(g.includes(l.href)||g.push(l.href))}),c.forEach(async l=>{g.includes(l)||this.pool.has(l)&&(this.cancelShowing(l),await this.pool.get(l)?.unload())}),this.currentBaseURL!==void 0&&t.baseURL!==this.currentBaseURL&&(this.blobs.forEach(l=>URL.revokeObjectURL(l)),this.blobs.clear()),this.currentBaseURL=t.baseURL;const u=async l=>{const f=t.readingOrder.findIndexWithHref(l),E=t.readingOrder.items[f];if(E){if(!this.blobs.has(l)){const S=await new _i(t,this.currentBaseURL||"",E).build(!0);this.blobs.set(l,S)}this.delayedShow.has(l)||this.delayedShow.set(l,new Promise((F,S)=>{let pA=!1;const Ln=window.setTimeout(async()=>{this.delayedTimeout.set(l,0);const On=this.makeSpread(this.reAlign(f)),Xn=this.spreadPosition(On,E),MA=this.pool.get(l);await MA.load(i,this.blobs.get(l)),this.peripherals.isScaled||await MA.show(Xn),this.delayedShow.delete(l),pA=!0,F()},vn);setTimeout(()=>{!pA&&this.delayedShow.has(l)&&S(`Offscreen load timeout: ${l}`)},Dn),this.delayedTimeout.set(l,Ln)}))}};try{await Promise.all(g.map(l=>u(l)))}catch(l){h(l)}const M=[];for(const l of s){const f=this.pool.get(l.href),E=this.blobs.get(l.href);E&&(this.cancelShowing(l.href),await f.load(i,E),await f.show(this.spreadPosition(s,l)),this.previousFrames.push(f),await f.activate(),M.push(f))}for(;this.previousFrames.length>0;){const l=this.previousFrames.shift();l&&!M.includes(l)&&await l.unfocus()}this.previousFrames=M,a()});for(const a of s)this.inprogress.set(a.href,o);await o;for(const a of s)this.inprogress.delete(a.href)}get currentFrames(){if(this.perPage<2){const e=this.pub.readingOrder.items[this.currentSlide];return[this.pool.get(e.href)]}return this.spreader.currentSpread(this.currentSlide,this.perPage).map(e=>this.pool.get(e.href))}get currentBounds(){const t={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(e=>{if(!e)return;const i=e.realSize;t.x=Math.min(t.x,i.x),t.y=Math.min(t.y,i.y),t.width+=i.width,t.height=Math.max(t.height,i.height),t.top=Math.min(t.top,i.top),t.right=Math.min(t.right,i.right),t.bottom=Math.min(t.bottom,i.bottom),t.left=Math.min(t.left,i.left)}),t}get viewport(){const t={readingOrder:[],progressions:new Map,positions:null};return this.spreader.currentSpread(this.currentSlide,this.perPage).forEach(i=>{t.readingOrder.push(i.href),t.progressions.set(i.href,{start:0,end:1})}),t.positions=this.getCurrentNumbers(),t}getCurrentNumbers(){if(this.perPage<2)return[this.pub.readingOrder.items[this.currentSlide].properties?.otherProperties.number];const t=this.spreader.currentSpread(this.currentSlide,this.perPage);return t.length>1?[t[0].properties?.otherProperties.number,t[t.length-1].properties?.otherProperties.number]:[t[0].properties?.otherProperties.number]}deselect(){this.currentFrames?.forEach(t=>t?.deselect())}}class Mt{constructor(t={}){this.backgroundColor=Q(t.backgroundColor),this.blendFilter=U(t.blendFilter),this.constraint=I(t.constraint),this.columnCount=I(t.columnCount),this.darkenFilter=st(t.darkenFilter),this.deprecatedFontSize=U(t.deprecatedFontSize),this.fontFamily=Q(t.fontFamily),this.fontSize=L(t.fontSize,yt.range),this.fontSizeNormalize=U(t.fontSizeNormalize),this.fontOpticalSizing=U(t.fontOpticalSizing),this.fontWeight=L(t.fontWeight,q.range),this.fontWidth=L(t.fontWidth,Rt.range),this.hyphens=U(t.hyphens),this.invertFilter=st(t.invertFilter),this.invertGaijiFilter=st(t.invertGaijiFilter),this.iOSPatch=U(t.iOSPatch),this.iPadOSPatch=U(t.iPadOSPatch),this.letterSpacing=I(t.letterSpacing),this.ligatures=U(t.ligatures),this.lineHeight=I(t.lineHeight),this.linkColor=Q(t.linkColor),this.noRuby=U(t.noRuby),this.pageGutter=I(t.pageGutter),this.paragraphIndent=I(t.paragraphIndent),this.paragraphSpacing=I(t.paragraphSpacing),this.scroll=U(t.scroll),this.scrollPaddingTop=I(t.scrollPaddingTop),this.scrollPaddingBottom=I(t.scrollPaddingBottom),this.selectionBackgroundColor=Q(t.selectionBackgroundColor),this.selectionTextColor=Q(t.selectionTextColor),this.textAlign=Tt(t.textAlign,X),this.textColor=Q(t.textColor),this.textNormalization=U(t.textNormalization),this.visitedColor=Q(t.visitedColor),this.wordSpacing=I(t.wordSpacing),this.optimalLineLength=I(t.optimalLineLength),this.maximalLineLength=I(t.maximalLineLength),this.minimalLineLength=I(t.minimalLineLength)}static serialize(t){const{...e}=t;return JSON.stringify(e)}static deserialize(t){try{const e=JSON.parse(t);return new Mt(e)}catch(e){return console.error("Failed to deserialize preferences:",e),null}}merging(t){const e={...this};for(const i of Object.keys(t))t[i]!==void 0&&(i!=="maximalLineLength"||t[i]===null||t[i]>=(t.optimalLineLength??e.optimalLineLength??65))&&(i!=="minimalLineLength"||t[i]===null||t[i]<=(t.optimalLineLength??e.optimalLineLength??65))&&(e[i]=t[i]);return new Mt(e)}}class uA{constructor(t){this.backgroundColor=Q(t.backgroundColor)||null,this.blendFilter=U(t.blendFilter)??!1,this.constraint=I(t.constraint)||0,this.columnCount=I(t.columnCount)||null,this.darkenFilter=st(t.darkenFilter)??!1,this.deprecatedFontSize=U(t.deprecatedFontSize),(this.deprecatedFontSize===!1||this.deprecatedFontSize===null)&&(this.deprecatedFontSize=!CSS.supports("zoom","1")),this.fontFamily=Q(t.fontFamily)||null,this.fontSize=L(t.fontSize,yt.range)||1,this.fontSizeNormalize=U(t.fontSizeNormalize)??!1,this.fontOpticalSizing=U(t.fontOpticalSizing)??null,this.fontWeight=L(t.fontWeight,q.range)||null,this.fontWidth=L(t.fontWidth,Rt.range)||null,this.hyphens=U(t.hyphens)??null,this.invertFilter=st(t.invertFilter)??!1,this.invertGaijiFilter=st(t.invertGaijiFilter)??!1,this.iOSPatch=t.iOSPatch===!1?!1:(W.OS.iOS||W.OS.iPadOS)&&W.iOSRequest==="mobile",this.iPadOSPatch=t.iPadOSPatch===!1?!1:W.OS.iPadOS&&W.iOSRequest==="desktop",this.letterSpacing=I(t.letterSpacing)||null,this.ligatures=U(t.ligatures)??null,this.lineHeight=I(t.lineHeight)||null,this.linkColor=Q(t.linkColor)||null,this.noRuby=U(t.noRuby)??!1,this.pageGutter=Ot(I(t.pageGutter),20),this.paragraphIndent=I(t.paragraphIndent)??null,this.paragraphSpacing=I(t.paragraphSpacing)??null,this.scroll=U(t.scroll)??!1,this.scrollPaddingTop=I(t.scrollPaddingTop)??null,this.scrollPaddingBottom=I(t.scrollPaddingBottom)??null,this.selectionBackgroundColor=Q(t.selectionBackgroundColor)||null,this.selectionTextColor=Q(t.selectionTextColor)||null,this.textAlign=Tt(t.textAlign,X)||null,this.textColor=Q(t.textColor)||null,this.textNormalization=U(t.textNormalization)??!1,this.visitedColor=Q(t.visitedColor)||null,this.wordSpacing=I(t.wordSpacing)||null,this.optimalLineLength=I(t.optimalLineLength)||65,this.maximalLineLength=Ot(Xi(t.maximalLineLength,this.optimalLineLength),80),this.minimalLineLength=Ot(Oi(t.minimalLineLength,this.optimalLineLength),40)}}const Bt={RS__backgroundColor:"#FFFFFF",RS__textColor:"#121212",RS__linkColor:"#0000EE",RS__visitedColor:"#551A8B",RS__selectionBackgroundColor:"#b4d8fe",RS__selectionTextColor:"inherit"};class Ye{constructor(t,e,i){this.preferences=t,this.settings=e,this.metadata=i,this.layout=this.metadata?.effectiveLayout||w.reflowable}clear(){this.preferences=new Mt({optimalLineLength:65})}updatePreference(t,e){this.preferences[t]=e}get backgroundColor(){return new z({initialValue:this.preferences.backgroundColor,effectiveValue:this.settings.backgroundColor||Bt.RS__backgroundColor,isEffective:this.preferences.backgroundColor!==null,onChange:t=>{this.updatePreference("backgroundColor",t||null)}})}get blendFilter(){return new N({initialValue:this.preferences.blendFilter,effectiveValue:this.settings.blendFilter||!1,isEffective:this.preferences.blendFilter!==null,onChange:t=>{this.updatePreference("blendFilter",t||null)}})}get columnCount(){return new z({initialValue:this.preferences.columnCount,effectiveValue:this.settings.columnCount||null,isEffective:this.layout!==w.fixed&&!this.settings.scroll,onChange:t=>{this.updatePreference("columnCount",t||null)}})}get constraint(){return new z({initialValue:this.preferences.constraint,effectiveValue:this.preferences.constraint||0,isEffective:!0,onChange:t=>{this.updatePreference("constraint",t||null)}})}get darkenFilter(){return new y({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:t=>{this.updatePreference("darkenFilter",t||null)},supportedRange:nt.range,step:nt.step})}get deprecatedFontSize(){return new N({initialValue:this.preferences.deprecatedFontSize,effectiveValue:CSS.supports("zoom","1")?this.settings.deprecatedFontSize||!1:!0,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("deprecatedFontSize",t||null)}})}get fontFamily(){return new z({initialValue:this.preferences.fontFamily,effectiveValue:this.settings.fontFamily||null,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("fontFamily",t||null)}})}get fontSize(){return new y({initialValue:this.preferences.fontSize,effectiveValue:this.settings.fontSize||1,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("fontSize",t||null)},supportedRange:yt.range,step:yt.step})}get fontSizeNormalize(){return new N({initialValue:this.preferences.fontSizeNormalize,effectiveValue:this.settings.fontSizeNormalize||!1,isEffective:this.layout!==w.fixed&&this.preferences.fontSizeNormalize!==null,onChange:t=>{this.updatePreference("fontSizeNormalize",t||null)}})}get fontOpticalSizing(){return new N({initialValue:this.preferences.fontOpticalSizing,effectiveValue:this.settings.fontOpticalSizing||!0,isEffective:this.layout!==w.fixed&&this.preferences.fontOpticalSizing!==null,onChange:t=>{this.updatePreference("fontOpticalSizing",t||null)}})}get fontWeight(){return new y({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.layout!==w.fixed&&this.preferences.fontWeight!==null,onChange:t=>{this.updatePreference("fontWeight",t||null)},supportedRange:q.range,step:q.step})}get fontWidth(){return new y({initialValue:this.preferences.fontWidth,effectiveValue:this.settings.fontWidth||100,isEffective:this.layout!==w.fixed&&this.preferences.fontWidth!==null,onChange:t=>{this.updatePreference("fontWidth",t||null)},supportedRange:Rt.range,step:Rt.step})}get hyphens(){return new N({initialValue:this.preferences.hyphens,effectiveValue:this.settings.hyphens||!1,isEffective:this.layout!==w.fixed&&this.metadata?.effectiveReadingProgression===Y.ltr&&this.preferences.hyphens!==null,onChange:t=>{this.updatePreference("hyphens",t||null)}})}get invertFilter(){return new y({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:t=>{this.updatePreference("invertFilter",t||null)},supportedRange:nt.range,step:nt.step})}get invertGaijiFilter(){return new y({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:t=>{this.updatePreference("invertGaijiFilter",t||null)},supportedRange:nt.range,step:nt.step})}get iOSPatch(){return new N({initialValue:this.preferences.iOSPatch,effectiveValue:this.settings.iOSPatch||!1,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("iOSPatch",t||null)}})}get iPadOSPatch(){return new N({initialValue:this.preferences.iPadOSPatch,effectiveValue:this.settings.iPadOSPatch||!1,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("iPadOSPatch",t||null)}})}get letterSpacing(){return new y({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.layout!==w.fixed&&this.preferences.letterSpacing!==null,onChange:t=>{this.updatePreference("letterSpacing",t||null)},supportedRange:Ct.range,step:Ct.step})}get ligatures(){return new N({initialValue:this.preferences.ligatures,effectiveValue:this.settings.ligatures||!0,isEffective:this.layout!==w.fixed&&this.metadata?.languages?.some(t=>t==="ar"||t==="fa")&&this.preferences.ligatures!==null||!1,onChange:t=>{this.updatePreference("ligatures",t||null)}})}get lineHeight(){return new y({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.layout!==w.fixed&&this.preferences.lineHeight!==null,onChange:t=>{this.updatePreference("lineHeight",t||null)},supportedRange:St.range,step:St.step})}get linkColor(){return new z({initialValue:this.preferences.linkColor,effectiveValue:this.settings.linkColor||Bt.RS__linkColor,isEffective:this.layout!==w.fixed&&this.preferences.linkColor!==null,onChange:t=>{this.updatePreference("linkColor",t||null)}})}get maximalLineLength(){return new y({initialValue:this.preferences.maximalLineLength,effectiveValue:this.settings.maximalLineLength,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("maximalLineLength",t)},supportedRange:rt.range,step:rt.step})}get minimalLineLength(){return new y({initialValue:this.preferences.minimalLineLength,effectiveValue:this.settings.minimalLineLength,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("minimalLineLength",t)},supportedRange:rt.range,step:rt.step})}get noRuby(){return new N({initialValue:this.preferences.noRuby,effectiveValue:this.settings.noRuby||!1,isEffective:this.layout!==w.fixed&&this.metadata?.languages?.includes("ja")||!1,onChange:t=>{this.updatePreference("noRuby",t||null)}})}get optimalLineLength(){return new y({initialValue:this.preferences.optimalLineLength,effectiveValue:this.settings.optimalLineLength,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("optimalLineLength",t)},supportedRange:rt.range,step:rt.step})}get pageGutter(){return new z({initialValue:this.preferences.pageGutter,effectiveValue:this.settings.pageGutter,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("pageGutter",t||null)}})}get paragraphIndent(){return new y({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.layout!==w.fixed&&this.preferences.paragraphIndent!==null,onChange:t=>{this.updatePreference("paragraphIndent",t||null)},supportedRange:Qt.range,step:Qt.step})}get paragraphSpacing(){return new y({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.layout!==w.fixed&&this.preferences.paragraphSpacing!==null,onChange:t=>{this.updatePreference("paragraphSpacing",t||null)},supportedRange:zt.range,step:zt.step})}get scroll(){return new N({initialValue:this.preferences.scroll,effectiveValue:this.settings.scroll||!1,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("scroll",t||null)}})}get scrollPaddingTop(){return new z({initialValue:this.preferences.scrollPaddingTop,effectiveValue:this.settings.scrollPaddingTop||0,isEffective:this.layout!==w.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingTop!==null,onChange:t=>{this.updatePreference("scrollPaddingTop",t||null)}})}get scrollPaddingBottom(){return new z({initialValue:this.preferences.scrollPaddingBottom,effectiveValue:this.settings.scrollPaddingBottom||0,isEffective:this.layout!==w.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingBottom!==null,onChange:t=>{this.updatePreference("scrollPaddingBottom",t||null)}})}get selectionBackgroundColor(){return new z({initialValue:this.preferences.selectionBackgroundColor,effectiveValue:this.settings.selectionBackgroundColor||Bt.RS__selectionBackgroundColor,isEffective:this.layout!==w.fixed&&this.preferences.selectionBackgroundColor!==null,onChange:t=>{this.updatePreference("selectionBackgroundColor",t||null)}})}get selectionTextColor(){return new z({initialValue:this.preferences.selectionTextColor,effectiveValue:this.settings.selectionTextColor||Bt.RS__selectionTextColor,isEffective:this.layout!==w.fixed&&this.preferences.selectionTextColor!==null,onChange:t=>{this.updatePreference("selectionTextColor",t||null)}})}get textAlign(){return new Ue({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||X.start,isEffective:this.layout!==w.fixed&&this.preferences.textAlign!==null,onChange:t=>{this.updatePreference("textAlign",t||null)},supportedValues:Object.values(X)})}get textColor(){return new z({initialValue:this.preferences.textColor,effectiveValue:this.settings.textColor||Bt.RS__textColor,isEffective:this.layout!==w.fixed&&this.preferences.textColor!==null,onChange:t=>{this.updatePreference("textColor",t||null)}})}get textNormalization(){return new N({initialValue:this.preferences.textNormalization,effectiveValue:this.settings.textNormalization||!1,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("textNormalization",t||null)}})}get visitedColor(){return new z({initialValue:this.preferences.visitedColor,effectiveValue:this.settings.visitedColor||Bt.RS__visitedColor,isEffective:this.layout!==w.fixed&&this.preferences.visitedColor!==null,onChange:t=>{this.updatePreference("visitedColor",t||null)}})}get wordSpacing(){return new y({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.layout!==w.fixed&&this.preferences.wordSpacing!==null,onChange:t=>{this.updatePreference("wordSpacing",t||null)},supportedRange:Yt.range,step:Yt.step})}}class Ne{constructor(t,e){this.backgroundColor=t.backgroundColor||e.backgroundColor||null,this.blendFilter=typeof t.blendFilter=="boolean"?t.blendFilter:e.blendFilter??null,this.columnCount=t.columnCount!==void 0?t.columnCount:e.columnCount!==void 0?e.columnCount:null,this.constraint=t.constraint||e.constraint,this.darkenFilter=typeof t.darkenFilter=="boolean"?t.darkenFilter:e.darkenFilter??null,this.deprecatedFontSize=typeof t.deprecatedFontSize=="boolean"?t.deprecatedFontSize:e.deprecatedFontSize??null,this.fontFamily=t.fontFamily||e.fontFamily||null,this.fontSize=t.fontSize!==void 0?t.fontSize:e.fontSize!==void 0?e.fontSize:null,this.fontSizeNormalize=typeof t.fontSizeNormalize=="boolean"?t.fontSizeNormalize:e.fontSizeNormalize??null,this.fontOpticalSizing=typeof t.fontOpticalSizing=="boolean"?t.fontOpticalSizing:e.fontOpticalSizing??null,this.fontWeight=t.fontWeight!==void 0?t.fontWeight:e.fontWeight!==void 0?e.fontWeight:null,this.fontWidth=t.fontWidth!==void 0?t.fontWidth:e.fontWidth!==void 0?e.fontWidth:null,this.hyphens=typeof t.hyphens=="boolean"?t.hyphens:e.hyphens??null,this.invertFilter=typeof t.invertFilter=="boolean"?t.invertFilter:e.invertFilter??null,this.invertGaijiFilter=typeof t.invertGaijiFilter=="boolean"?t.invertGaijiFilter:e.invertGaijiFilter??null,this.iOSPatch=this.deprecatedFontSize||t.iOSPatch===!1?!1:t.iOSPatch===!0?(W.OS.iOS||W.OS.iPadOS)&&W.iOSRequest==="mobile":e.iOSPatch,this.iPadOSPatch=this.deprecatedFontSize||t.iPadOSPatch===!1?!1:t.iPadOSPatch===!0?W.OS.iPadOS&&W.iOSRequest==="desktop":e.iPadOSPatch,this.letterSpacing=t.letterSpacing!==void 0?t.letterSpacing:e.letterSpacing!==void 0?e.letterSpacing:null,this.ligatures=typeof t.ligatures=="boolean"?t.ligatures:e.ligatures??null,this.lineHeight=t.lineHeight!==void 0?t.lineHeight:e.lineHeight!==void 0?e.lineHeight:null,this.linkColor=t.linkColor||e.linkColor||null,this.maximalLineLength=t.maximalLineLength===null?null:t.maximalLineLength||e.maximalLineLength||null,this.minimalLineLength=t.minimalLineLength===null?null:t.minimalLineLength||e.minimalLineLength||null,this.noRuby=typeof t.noRuby=="boolean"?t.noRuby:e.noRuby??null,this.optimalLineLength=t.optimalLineLength||e.optimalLineLength,this.pageGutter=t.pageGutter!==void 0?t.pageGutter:e.pageGutter!==void 0?e.pageGutter:null,this.paragraphIndent=t.paragraphIndent!==void 0?t.paragraphIndent:e.paragraphIndent!==void 0?e.paragraphIndent:null,this.paragraphSpacing=t.paragraphSpacing!==void 0?t.paragraphSpacing:e.paragraphSpacing!==void 0?e.paragraphSpacing:null,this.scroll=typeof t.scroll=="boolean"?t.scroll:e.scroll??null,this.scrollPaddingTop=t.scrollPaddingTop!==void 0?t.scrollPaddingTop:e.scrollPaddingTop!==void 0?e.scrollPaddingTop:null,this.scrollPaddingBottom=t.scrollPaddingBottom!==void 0?t.scrollPaddingBottom:e.scrollPaddingBottom!==void 0?e.scrollPaddingBottom:null,this.selectionBackgroundColor=t.selectionBackgroundColor||e.selectionBackgroundColor||null,this.selectionTextColor=t.selectionTextColor||e.selectionTextColor||null,this.textAlign=t.textAlign||e.textAlign||null,this.textColor=t.textColor||e.textColor||null,this.textNormalization=typeof t.textNormalization=="boolean"?t.textNormalization:e.textNormalization??null,this.visitedColor=t.visitedColor||e.visitedColor||null,this.wordSpacing=t.wordSpacing!==void 0?t.wordSpacing:e.wordSpacing!==void 0?e.wordSpacing:null}}function Kt(r){const t=getComputedStyle(r),e=parseFloat(t.paddingLeft||"0"),i=parseFloat(t.paddingRight||"0");return r.clientWidth-e-i}class Te extends Lt{constructor(t){super(),this.a11yNormalize=t.a11yNormalize??null,this.backgroundColor=t.backgroundColor??null,this.blendFilter=t.blendFilter??null,this.bodyHyphens=t.bodyHyphens??null,this.colCount=t.colCount??null,this.darkenFilter=t.darkenFilter??null,this.deprecatedFontSize=t.deprecatedFontSize??null,this.fontFamily=t.fontFamily??null,this.fontOpticalSizing=t.fontOpticalSizing??null,this.fontSize=t.fontSize??null,this.fontSizeNormalize=t.fontSizeNormalize??null,this.fontWeight=t.fontWeight??null,this.fontWidth=t.fontWidth??null,this.invertFilter=t.invertFilter??null,this.invertGaijiFilter=t.invertGaijiFilter??null,this.iOSPatch=t.iOSPatch??null,this.iPadOSPatch=t.iPadOSPatch??null,this.letterSpacing=t.letterSpacing??null,this.ligatures=t.ligatures??null,this.lineHeight=t.lineHeight??null,this.lineLength=t.lineLength??null,this.linkColor=t.linkColor??null,this.noRuby=t.noRuby??null,this.paraIndent=t.paraIndent??null,this.paraSpacing=t.paraSpacing??null,this.selectionBackgroundColor=t.selectionBackgroundColor??null,this.selectionTextColor=t.selectionTextColor??null,this.textAlign=t.textAlign??null,this.textColor=t.textColor??null,this.view=t.view??null,this.visitedColor=t.visitedColor??null,this.wordSpacing=t.wordSpacing??null}toCSSProperties(){const t={};return this.a11yNormalize&&(t["--USER__a11yNormalize"]=this.toFlag("a11y")),this.backgroundColor&&(t["--USER__backgroundColor"]=this.backgroundColor),this.blendFilter&&(t["--USER__blendFilter"]=this.toFlag("blend")),this.bodyHyphens&&(t["--USER__bodyHyphens"]=this.bodyHyphens),this.colCount&&(t["--USER__colCount"]=this.toUnitless(this.colCount)),this.darkenFilter===!0?t["--USER__darkenFilter"]=this.toFlag("darken"):typeof this.darkenFilter=="number"&&(t["--USER__darkenFilter"]=this.toPercentage(this.darkenFilter)),this.deprecatedFontSize&&(t["--USER__fontSizeImplementation"]=this.toFlag("deprecatedFontSize")),this.fontFamily&&(t["--USER__fontFamily"]=this.fontFamily),this.fontOpticalSizing!=null&&(t["--USER__fontOpticalSizing"]=this.fontOpticalSizing),this.fontSize!=null&&(t["--USER__fontSize"]=this.toPercentage(this.fontSize,!0)),this.fontSizeNormalize&&(t["--USER__fontSizeNormalize"]=this.toFlag("normalize")),this.fontWeight!=null&&(t["--USER__fontWeight"]=this.toUnitless(this.fontWeight)),this.fontWidth!=null&&(t["--USER__fontWidth"]=typeof this.fontWidth=="string"?this.fontWidth:this.toUnitless(this.fontWidth)),this.invertFilter===!0?t["--USER__invertFilter"]=this.toFlag("invert"):typeof this.invertFilter=="number"&&(t["--USER__invertFilter"]=this.toPercentage(this.invertFilter)),this.invertGaijiFilter===!0?t["--USER__invertGaiji"]=this.toFlag("invertGaiji"):typeof this.invertGaijiFilter=="number"&&(t["--USER__invertGaiji"]=this.toPercentage(this.invertGaijiFilter)),this.iOSPatch&&(t["--USER__iOSPatch"]=this.toFlag("iOSPatch")),this.iPadOSPatch&&(t["--USER__iPadOSPatch"]=this.toFlag("iPadOSPatch")),this.letterSpacing!=null&&(t["--USER__letterSpacing"]=this.toRem(this.letterSpacing)),this.ligatures&&(t["--USER__ligatures"]=this.ligatures),this.lineHeight!=null&&(t["--USER__lineHeight"]=this.toUnitless(this.lineHeight)),this.lineLength!=null&&(t["--USER__lineLength"]=this.toPx(this.lineLength)),this.linkColor&&(t["--USER__linkColor"]=this.linkColor),this.noRuby&&(t["--USER__noRuby"]=this.toFlag("noRuby")),this.paraIndent!=null&&(t["--USER__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(t["--USER__paraSpacing"]=this.toRem(this.paraSpacing)),this.selectionBackgroundColor&&(t["--USER__selectionBackgroundColor"]=this.selectionBackgroundColor),this.selectionTextColor&&(t["--USER__selectionTextColor"]=this.selectionTextColor),this.textAlign&&(t["--USER__textAlign"]=this.textAlign),this.textColor&&(t["--USER__textColor"]=this.textColor),this.view&&(t["--USER__view"]=this.toFlag(this.view)),this.visitedColor&&(t["--USER__visitedColor"]=this.visitedColor),this.wordSpacing!=null&&(t["--USER__wordSpacing"]=this.toRem(this.wordSpacing)),t}}class mA extends Lt{constructor(t){super(),this.backgroundColor=t.backgroundColor??null,this.baseFontFamily=t.baseFontFamily??null,this.baseFontSize=t.baseFontSize??null,this.baseLineHeight=t.baseLineHeight??null,this.boxSizingMedia=t.boxSizingMedia??null,this.boxSizingTable=t.boxSizingTable??null,this.colWidth=t.colWidth??null,this.colCount=t.colCount??null,this.colGap=t.colGap??null,this.codeFontFamily=t.codeFontFamily??null,this.compFontFamily=t.compFontFamily??null,this.defaultLineLength=t.defaultLineLength??null,this.flowSpacing=t.flowSpacing??null,this.humanistTf=t.humanistTf??null,this.linkColor=t.linkColor??null,this.maxMediaWidth=t.maxMediaWidth??null,this.maxMediaHeight=t.maxMediaHeight??null,this.modernTf=t.modernTf??null,this.monospaceTf=t.monospaceTf??null,this.noOverflow=t.noOverflow??null,this.noVerticalPagination=t.noVerticalPagination??null,this.oldStyleTf=t.oldStyleTf??null,this.pageGutter=t.pageGutter??null,this.paraIndent=t.paraIndent??null,this.paraSpacing=t.paraSpacing??null,this.primaryColor=t.primaryColor??null,this.scrollPaddingBottom=t.scrollPaddingBottom??null,this.scrollPaddingTop=t.scrollPaddingTop??null,this.sansSerifJa=t.sansSerifJa??null,this.sansSerifJaV=t.sansSerifJaV??null,this.sansTf=t.sansTf??null,this.secondaryColor=t.secondaryColor??null,this.selectionBackgroundColor=t.selectionBackgroundColor??null,this.selectionTextColor=t.selectionTextColor??null,this.serifJa=t.serifJa??null,this.serifJaV=t.serifJaV??null,this.textColor=t.textColor??null,this.typeScale=t.typeScale??null,this.visitedColor=t.visitedColor??null}toCSSProperties(){const t={};return this.backgroundColor&&(t["--RS__backgroundColor"]=this.backgroundColor),this.baseFontFamily&&(t["--RS__baseFontFamily"]=this.baseFontFamily),this.baseFontSize!=null&&(t["--RS__baseFontSize"]=this.toRem(this.baseFontSize)),this.baseLineHeight!=null&&(t["--RS__baseLineHeight"]=this.toUnitless(this.baseLineHeight)),this.boxSizingMedia&&(t["--RS__boxSizingMedia"]=this.boxSizingMedia),this.boxSizingTable&&(t["--RS__boxSizingTable"]=this.boxSizingTable),this.colWidth!=null&&(t["--RS__colWidth"]=this.colWidth),this.colCount!=null&&(t["--RS__colCount"]=this.toUnitless(this.colCount)),this.colGap!=null&&(t["--RS__colGap"]=this.toPx(this.colGap)),this.codeFontFamily&&(t["--RS__codeFontFamily"]=this.codeFontFamily),this.compFontFamily&&(t["--RS__compFontFamily"]=this.compFontFamily),this.defaultLineLength!=null&&(t["--RS__defaultLineLength"]=this.toPx(this.defaultLineLength)),this.flowSpacing!=null&&(t["--RS__flowSpacing"]=this.toRem(this.flowSpacing)),this.humanistTf&&(t["--RS__humanistTf"]=this.humanistTf),this.linkColor&&(t["--RS__linkColor"]=this.linkColor),this.maxMediaWidth&&(t["--RS__maxMediaWidth"]=this.toVw(this.maxMediaWidth)),this.maxMediaHeight&&(t["--RS__maxMediaHeight"]=this.toVh(this.maxMediaHeight)),this.modernTf&&(t["--RS__modernTf"]=this.modernTf),this.monospaceTf&&(t["--RS__monospaceTf"]=this.monospaceTf),this.noOverflow&&(t["--RS__disableOverflow"]=this.toFlag("noOverflow")),this.noVerticalPagination&&(t["--RS__disablePagination"]=this.toFlag("noVerticalPagination")),this.oldStyleTf&&(t["--RS__oldStyleTf"]=this.oldStyleTf),this.pageGutter!=null&&(t["--RS__pageGutter"]=this.toPx(this.pageGutter)),this.paraIndent!=null&&(t["--RS__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(t["--RS__paraSpacing"]=this.toRem(this.paraSpacing)),this.primaryColor&&(t["--RS__primaryColor"]=this.primaryColor),this.sansSerifJa&&(t["--RS__sans-serif-ja"]=this.sansSerifJa),this.sansSerifJaV&&(t["--RS__sans-serif-ja-v"]=this.sansSerifJaV),this.sansTf&&(t["--RS__sansTf"]=this.sansTf),this.scrollPaddingBottom!=null&&(t["--RS__scrollPaddingBottom"]=this.toPx(this.scrollPaddingBottom)),this.scrollPaddingTop!=null&&(t["--RS__scrollPaddingTop"]=this.toPx(this.scrollPaddingTop)),this.secondaryColor&&(t["--RS__secondaryColor"]=this.secondaryColor),this.selectionBackgroundColor&&(t["--RS__selectionBackgroundColor"]=this.selectionBackgroundColor),this.selectionTextColor&&(t["--RS__selectionTextColor"]=this.selectionTextColor),this.serifJa&&(t["--RS__serif-ja"]=this.serifJa),this.serifJaV&&(t["--RS__serif-ja-v"]=this.serifJaV),this.textColor&&(t["--RS__textColor"]=this.textColor),this.typeScale&&(t["--RS__typeScale"]=this.toUnitless(this.typeScale)),this.visitedColor&&(t["--RS__visitedColor"]=this.visitedColor),t}}class fA{constructor(t){this.rsProperties=t.rsProperties,this.userProperties=t.userProperties,this.lineLengths=t.lineLengths,this.container=t.container,this.containerParent=t.container.parentElement||document.documentElement,this.constraint=t.constraint,this.cachedColCount=t.userProperties.colCount,this.effectiveContainerWidth=Kt(this.containerParent)}update(t){this.cachedColCount=t.columnCount,t.constraint!==this.constraint&&(this.constraint=t.constraint),t.pageGutter!==this.rsProperties.pageGutter&&(this.rsProperties.pageGutter=t.pageGutter),t.scrollPaddingBottom!==this.rsProperties.scrollPaddingBottom&&(this.rsProperties.scrollPaddingBottom=t.scrollPaddingBottom),t.scrollPaddingTop!==this.rsProperties.scrollPaddingTop&&(this.rsProperties.scrollPaddingTop=t.scrollPaddingTop),this.lineLengths.update({fontFace:t.fontFamily,letterSpacing:t.letterSpacing,pageGutter:t.pageGutter,wordSpacing:t.wordSpacing,optimalChars:t.optimalLineLength,minChars:t.minimalLineLength,maxChars:t.maximalLineLength});const e=this.updateLayout(t.fontSize,t.deprecatedFontSize||t.iOSPatch,t.scroll,t.columnCount);e?.effectiveContainerWidth&&(this.effectiveContainerWidth=e?.effectiveContainerWidth);const i={a11yNormalize:t.textNormalization,backgroundColor:t.backgroundColor,blendFilter:t.blendFilter,bodyHyphens:typeof t.hyphens!="boolean"?null:t.hyphens?"auto":"none",colCount:e?.colCount,darkenFilter:t.darkenFilter,deprecatedFontSize:t.deprecatedFontSize,fontFamily:t.fontFamily,fontOpticalSizing:typeof t.fontOpticalSizing!="boolean"?null:t.fontOpticalSizing?"auto":"none",fontSize:t.fontSize,fontSizeNormalize:t.fontSizeNormalize,fontWeight:t.fontWeight,fontWidth:t.fontWidth,invertFilter:t.invertFilter,invertGaijiFilter:t.invertGaijiFilter,iOSPatch:t.iOSPatch,iPadOSPatch:t.iPadOSPatch,letterSpacing:t.letterSpacing,ligatures:typeof t.ligatures!="boolean"?null:t.ligatures?"common-ligatures":"none",lineHeight:t.lineHeight,lineLength:e?.effectiveLineLength,linkColor:t.linkColor,noRuby:t.noRuby,paraIndent:t.paragraphIndent,paraSpacing:t.paragraphSpacing,selectionBackgroundColor:t.selectionBackgroundColor,selectionTextColor:t.selectionTextColor,textAlign:t.textAlign,textColor:t.textColor,view:typeof t.scroll!="boolean"?null:t.scroll?"scroll":"paged",visitedColor:t.visitedColor,wordSpacing:t.wordSpacing};this.userProperties=new Te(i)}updateLayout(t,e,i,A){return i??this.userProperties.view==="scroll"?this.computeScrollLength(t,e):this.paginate(t,e,A)}getCompensatedMetrics(t,e){const i=t||this.userProperties.fontSize||1,A=i<1?1/i:e?i:1;return{zoomFactor:i,zoomCompensation:A,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(t,e,i){const A=Math.round(Kt(this.containerParent)-this.constraint),n=this.getCompensatedMetrics(t,e),{zoomCompensation:s,optimal:o,minimal:a,maximal:h}=n,c=()=>A>=o&&h!==null?Math.min(Math.round(h*s),A):A;let g=1,u=A;if(i===void 0)return{colCount:void 0,effectiveContainerWidth:u,effectiveLineLength:Math.round(u/g*s)};if(i===null)if(A>=o&&h!==null){g=Math.floor(A/o);const M=Math.round(g*(h*s));u=Math.min(M,A)}else u=c();else if(i>1){const M=Math.round(i*(a!==null?a:o));if(A>=M)if(g=i,h===null)u=A;else{const l=Math.round(g*(h*s));u=Math.min(l,A)}else if(a!==null&&A<Math.round(i*a))if(g=Math.floor(A/a),g<=1)g=1,u=c();else{const l=Math.round(g*(o*s));u=Math.min(l,A)}else{g=i;const l=Math.round(g*(o*s));u=Math.min(l,A)}}else g=1,u=c();return{colCount:g,effectiveContainerWidth:u,effectiveLineLength:Math.round(u/g/(t&&t>=1?t:1)*s)}}computeScrollLength(t,e){const i=Math.round(Kt(this.containerParent)-this.constraint),A=this.getCompensatedMetrics(t&&(t<1||e)?t:1,e),n=A.zoomCompensation,s=A.optimal,o=A.maximal;let a,h=i,c=Math.round(s*n);if(o===null)c=i;else{const g=Math.min(Math.round(o*n),i);c=e?g:Math.round(g*n)}return{colCount:a,effectiveContainerWidth:h,effectiveLineLength:c}}setContainerWidth(){this.container.style.width=`${this.effectiveContainerWidth}px`}resizeHandler(){const t=this.updateLayout(this.userProperties.fontSize,this.userProperties.deprecatedFontSize||this.userProperties.iOSPatch,this.userProperties.view==="scroll",this.cachedColCount);this.userProperties.colCount=t.colCount,this.userProperties.lineLength=t.effectiveLineLength,this.effectiveContainerWidth=t.effectiveContainerWidth,this.container.style.width=`${this.effectiveContainerWidth}px`}}const Jn=r=>({frameLoaded:r.frameLoaded||(()=>{}),positionChanged:r.positionChanged||(()=>{}),tap:r.tap||(()=>!1),click:r.click||(()=>!1),zoom:r.zoom||(()=>{}),miscPointer:r.miscPointer||(()=>{}),scroll:r.scroll||(()=>{}),customEvent:r.customEvent||(()=>{}),handleLocator:r.handleLocator||(()=>!1),textSelected:r.textSelected||(()=>{})});class xe extends re{constructor(t,e,i,A=[],n=void 0,s={preferences:{},defaults:{}}){super(),this._preferencesEditor=null,this.reflowViewport={readingOrder:[],progressions:new Map,positions:null},this.pub=e,this.container=t,this.listeners=Jn(i),this.currentLocation=n,A.length&&(this.positions=A),this._preferences=new Mt(s.preferences),this._defaults=new uA(s.defaults),this._settings=new Ne(this._preferences,this._defaults),this._css=new fA({rsProperties:new mA({}),userProperties:new Te({}),lineLengths:new ut({optimalChars:this._settings.optimalLineLength,minChars:this._settings.minimalLineLength,maxChars:this._settings.maximalLineLength,pageGutter:this._settings.pageGutter,fontFace:this._settings.fontFamily,letterSpacing:this._settings.letterSpacing,wordSpacing:this._settings.wordSpacing}),container:t,constraint:this._settings.constraint}),this._layout=xe.determineLayout(e,!!this._settings.scroll),this.currentProgression=e.metadata.effectiveReadingProgression,this.resizeObserver=new ResizeObserver(()=>this.ownerWindow.requestAnimationFrame(async()=>await this.resizeHandler())),this.resizeObserver.observe(this.container.parentElement||document.documentElement)}static determineLayout(t,e){const i=t.metadata.effectiveLayout;return i===w.fixed||t.metadata.otherMetadata&&"http://openmangaformat.org/schema/1.0#version"in t.metadata.otherMetadata||t.metadata?.conformsTo?.includes(Je.DIVINA)?w.fixed:i===w.scrolled||i===w.reflowable&&e?w.scrolled:w.reflowable}async load(){if(this.positions?.length||(this.positions=await this.pub.positionsFromManifest()),this._layout===w.fixed)this.framePool=new dA(this.container,this.positions,this.pub),this.framePool.listener=(t,e)=>{this.eventListener(t,e)};else{await this.updateCSS(!1);const t=this.compileCSSProperties(this._css);this.framePool=new iA(this.container,this.positions,t)}this.currentLocation===void 0&&(this.currentLocation=this.positions[0]),await this.resizeHandler(),await this.apply()}get settings(){if(this._layout===w.fixed)return Object.freeze({...this._settings});{const t=this._css.userProperties.colCount||this._css.rsProperties.colCount||this._settings.columnCount;return Object.freeze({...this._settings,columnCount:t})}}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new Ye(this._preferences,this.settings,this.pub.metadata)),this._preferencesEditor}async submitPreferences(t){this._preferences=this._preferences.merging(t),await this.applyPreferences()}async applyPreferences(){const t=this._settings;this._settings=new Ne(this._preferences,this._defaults),this._preferencesEditor!==null&&(this._preferencesEditor=new Ye(this._preferences,this.settings,this.pub.metadata)),this._layout===w.fixed?this.handleFXLPrefs(t,this._settings):await this.updateCSS(!0)}handleFXLPrefs(t,e){t.columnCount!==e.columnCount&&this.framePool.setPerPage(e.columnCount)}async updateCSS(t){this._css.update(this._settings),t&&await this.commitCSS(this._css)}compileCSSProperties(t){const e={};for(const[i,A]of Object.entries(t.rsProperties.toCSSProperties()))e[i]=A;for(const[i,A]of Object.entries(t.userProperties.toCSSProperties()))e[i]=A;return e}async commitCSS(t){const e=this.compileCSSProperties(t);this.framePool.setCSSProperties(e),this._css.userProperties.view==="paged"&&this._layout===w.scrolled?await this.setLayout(w.reflowable):this._css.userProperties.view==="scroll"&&this._layout===w.reflowable&&await this.setLayout(w.scrolled),this._css.setContainerWidth()}async resizeHandler(){const t=this.container.parentElement||document.documentElement;if(this._layout===w.fixed)this.container.style.width=`${Kt(t)-this._settings.constraint}px`,this.framePool.resizeHandler();else{const e=this._css.userProperties.colCount,i=this._css.userProperties.lineLength;this._css.resizeHandler(),(this._css.userProperties.view!=="scroll"&&e!==this._css.userProperties.colCount||i!==this._css.userProperties.lineLength)&&await this.commitCSS(this._css)}}get layout(){return this._layout}get ownerWindow(){return this.container.ownerDocument.defaultView||window}get _cframes(){return this.framePool.currentFrames}get pool(){return this.framePool}eventListener(t,e){switch(t){case"_pong":this.listeners.frameLoaded(this._cframes[0].iframe.contentWindow),this.listeners.positionChanged(this.currentLocation);break;case"first_visible_locator":const i=lt.deserialize(e);if(!i)break;this.currentLocation=new lt({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(e);break;case"click":case"tap":const A=e;if(A.interactiveElement){const n=new DOMParser().parseFromString(A.interactiveElement,"text/html").body.children[0];if(n.nodeType===n.ELEMENT_NODE&&n.nodeName==="A"&&n.hasAttribute("href")){const s=n.attributes.getNamedItem("href")?.value;if(s.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[s.substring(1)]}),!1,()=>{});else if(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("mailto:")||s.startsWith("tel:"))this.listeners.handleLocator(new _({href:s}).locator);else try{this.goLink(new _({href:Wt.join(Wt.dirname(this.currentLocation.href),s)}),!1,()=>{})}catch(o){console.warn(`Couldn't go to link for ${s}: ${o}`),this.listeners.handleLocator(new _({href:s}).locator)}}else console.log("Clicked on",n)}else{if(this._layout===w.fixed&&this.framePool.doNotDisturb&&(A.doNotDisturb=!0),this._layout===w.fixed&&(this.currentProgression===Y.rtl||this.currentProgression===Y.ltr)&&this.framePool.currentFrames.length>1){const o=this.framePool.currentFrames;A.targetFrameSrc===o[this.currentProgression===Y.rtl?0:1]?.source&&(A.x+=(o[this.currentProgression===Y.rtl?1:0]?.iframe.contentWindow?.innerWidth??0)*window.devicePixelRatio)}if(t==="click"?this.listeners.click(A):this.listeners.tap(A))break;const s=(this._cframes.length===2?this._cframes[0].window.innerWidth+this._cframes[1].window.innerWidth:this._cframes[0].window.innerWidth)*window.devicePixelRatio/4;A.x>=s&&A.x<=s*3&&this.listeners.miscPointer(1),A.x<s?this.goLeft(!1,()=>{}):A.x>s*3&&this.goRight(!1,()=>{})}break;case"tap_more":this.listeners.miscPointer(e);break;case"no_more":this.changeResource(1);break;case"no_less":this.changeResource(-1);break;case"swipe":break;case"scroll":this.listeners.scroll(e);break;case"zoom":this.listeners.zoom(e);break;case"progress":this.syncLocation(e);break;case"log":console.log(this._cframes[0]?.source?.split("/")[3],...e);break;default:this.listeners.customEvent(t,e);break}}determineModules(){let t=Array.from(Jt.keys());return this._layout===w.fixed?t.filter(e=>In.includes(e)):(t=t.filter(e=>Fn.includes(e)),this._layout===w.scrolled?t=t.filter(e=>e!=="column_snapper"):t=t.filter(e=>e!=="scroll_snapper"),t)}attachListener(){const t=this._cframes.filter(e=>!!e);if(t.length===0)throw Error("no cframe to attach listener to");t.forEach(e=>{e.msg&&(e.msg.listener=(i,A)=>{this.eventListener(i,A)})})}async apply(){if(await this.framePool.update(this.pub,this.currentLocator,this.determineModules()),this.attachListener(),this.pub.readingOrder.findIndexWithHref(this.currentLocation.href)<0)throw Error("Link for "+this.currentLocation.href+" not found!")}async destroy(){await this.framePool?.destroy()}async changeResource(t){if(t===0)return!1;if(this._layout===w.fixed){const A=this.framePool,n=A.viewport.positions[0];if(t===1){if(!A.next(A.perPage))return!1}else if(t===-1){if(!A.prev(A.perPage))return!1}else throw Error("Invalid relative value for FXL");const s=A.viewport.positions[0];if(n>s){for(let o=this.positions.length-1;o>=0;o--)if(this.positions[o].href===this.pub.readingOrder.items[s-1].href){this.currentLocation=this.positions[o].copyWithLocations({progression:.999999999999});break}}else if(n<s){for(let o=0;o<this.positions.length;o++)if(this.positions[o].href===this.pub.readingOrder.items[s-1].href){this.currentLocation=this.positions[o];break}}return await this.apply(),!0}const e=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),i=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,e+t));if(i===e)return this._cframes[0]?.msg?.send("shake",void 0,async A=>{}),!1;if(e>i){for(let A=this.positions.length-1;A>=0;A--)if(this.positions[A].href===this.pub.readingOrder.items[i].href){this.currentLocation=this.positions[A].copyWithLocations({progression:.999999999999});break}}else for(let A=0;A<this.positions.length;A++)if(this.positions[A].href===this.pub.readingOrder.items[i].href){this.currentLocation=this.positions[A];break}return await this.apply(),!0}findLastPositionInProgressionRange(t,e){const i=t.findLastIndex(A=>{const n=A.locations.progression;return!!(n&&n>e.start&&n<=e.end)});return i!==-1?t[i]:void 0}findNearestPositions(t){const e=this.positions.filter(n=>n.href===this.currentLocation.href);let i=this.currentLocation,A;return e.some((n,s)=>{const o=n.locations.progression??0;if(t.start<=o){i=n;const a=e.splice(s+1,e.length);return A=this.findLastPositionInProgressionRange(a,t),!0}else return!1}),{first:i,last:A}}updateViewport(t){this.reflowViewport.readingOrder=[],this.reflowViewport.progressions.clear(),this.reflowViewport.positions=null,this.currentLocation&&(this.reflowViewport.readingOrder.push(this.currentLocation.href),this.reflowViewport.progressions.set(this.currentLocation.href,t),this.currentLocation.locations?.position!==void 0&&(this.reflowViewport.positions=[this.currentLocation.locations.position],this.lastLocationInView?.locations?.position!==void 0&&this.reflowViewport.positions.push(this.lastLocationInView.locations.position)))}async syncLocation(t){const e=t,i=this.findNearestPositions(e);this.currentLocation=i.first.copyWithLocations({progression:e.start}),this.lastLocationInView=i.last,this.updateViewport(e),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(t,e){this._layout===w.fixed?(this.changeResource(-1),e(!0)):this._cframes[0]?.msg?.send("go_prev",void 0,async i=>{e(i?!0:await this.changeResource(-1))})}goForward(t,e){this._layout===w.fixed?(this.changeResource(1),e(!0)):this._cframes[0]?.msg?.send("go_next",void 0,async i=>{e(i?!0:await this.changeResource(1))})}get currentLocator(){return this.currentLocation}get viewport(){return this._layout===w.fixed?this.framePool.viewport:this.reflowViewport}get isScrollStart(){const t=this.viewport.readingOrder[0];return this.viewport.progressions.get(t)?.start===0}get isScrollEnd(){const t=this.viewport.readingOrder[this.viewport.readingOrder.length-1];return this.viewport.progressions.get(t)?.end===1}get canGoBackward(){const t=this.pub.readingOrder.items[0]?.href;return!(this.viewport.progressions.has(t)&&this.viewport.progressions.get(t)?.start===0)}get canGoForward(){const t=this.pub.readingOrder.items[this.pub.readingOrder.items.length-1]?.href;return!(this.viewport.progressions.has(t)&&this.viewport.progressions.get(t)?.end===1)}get readingProgression(){return this.currentProgression}async setLayout(t){this._layout!==t&&(this._layout=t,await this.framePool.update(this.pub,this.currentLocator,this.determineModules(),!0),this.attachListener())}get publication(){return this.pub}async loadLocator(t,e){let i=!1,A=typeof t.locations.getCssSelector=="function"&&t.locations.getCssSelector();if(t.text?.highlight?i=await new Promise((a,h)=>{this._cframes[0].msg.send("go_text",A?[t.text?.serialize(),A]:t.text?.serialize(),c=>a(c))}):A&&(i=await new Promise((a,h)=>{this._cframes[0].msg.send("go_text",["",A],c=>a(c))})),i){e(i);return}const n=typeof t.locations.htmlId=="function"&&t.locations.htmlId();if(n&&(i=await new Promise((a,h)=>{this._cframes[0].msg.send("go_id",n,c=>a(c))})),i){e(i);return}const s=t?.locations?.progression;s&&s>0?i=await new Promise((a,h)=>{this._cframes[0].msg.send("go_progression",s,c=>a(c))}):i=!0,e(i)}go(t,e,i){const A=t.href.split("#")[0];let n=this.pub.readingOrder.findWithHref(A);if(!n)return i(this.listeners.handleLocator(t));this.currentLocation=this.positions.find(s=>s.href===n.href),this.apply().then(()=>this.loadLocator(t,s=>i(s))).then(()=>{this.attachListener()})}goLink(t,e,i){return this.go(t.locator,e,i)}}class Wn{constructor(t){this.sourceNode=null,this.listeners={},this.isMutedValue=!1,this.isPlayingValue=!1,this.isPausedValue=!1,this.isLoadingValue=!1,this.isLoadedValue=!1,this.isEndedValue=!1,this.playback=t.playback,this.audioContext=t.audioContext,this.gainNode=this.audioContext?.createGain(),this.setVolume(this.playback.state.volume),this.mediaElement=document.createElement("audio"),this.mediaElement.crossOrigin="use-credentials",this.mediaElement.addEventListener("canplaythrough",this.onCanPlayThrough.bind(this)),this.mediaElement.addEventListener("timeupdate",this.onTimeUpdate.bind(this)),this.mediaElement.addEventListener("error",this.onError.bind(this)),this.mediaElement.addEventListener("ended",this.onEnded.bind(this)),this.mediaElement.currentTime=this.playback.state.currentTime}on(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)}off(t,e){this.listeners[t]&&(this.listeners[t]=this.listeners[t].filter(i=>i!==e))}loadAudio(t){this.isLoadingValue=!0,this.mediaElement.src=t,this.mediaElement.load(),this.sourceNode||(this.sourceNode=new MediaElementAudioSourceNode(this.audioContext,{mediaElement:this.mediaElement}),this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination))}async ensureAudioContextRunning(){this.audioContext.state==="suspended"&&await this.audioContext.resume()}onTimeUpdate(){this.emit("timeupdate",this.mediaElement.currentTime)}onCanPlayThrough(){this.isLoadingValue=!1,this.isLoadedValue=!0,this.emit("canplaythrough",null)}onError(){console.error("Error loading media element"),this.emit("error",this.mediaElement.error)}onEnded(){this.isPlayingValue=!1,this.isPausedValue=!1,this.isEndedValue=!0,this.emit("ended",null)}emit(t,e){this.listeners[t]&&this.listeners[t].forEach(i=>i(e))}async playLocator(t,e){}async play(){if(await this.ensureAudioContextRunning(),this.isPlayingValue){this.stop(),console.error("Audio is already playing");return}try{await this.mediaElement.play(),this.isPlayingValue=!0,this.isPausedValue=!1}catch(t){console.error("error trying to play media element",t)}}pause(){this.mediaElement.pause(),this.isPlayingValue=!1,this.isPausedValue=!0}stop(){this.mediaElement.pause(),this.mediaElement.currentTime=0,this.isPlayingValue=!1,this.isPausedValue=!1}setVolume(t){if(t<0){this.gainNode.gain.value=0,this.isMutedValue=!0;return}if(t>1){this.setVolume(t/100);return}this.gainNode.gain.value=t}skip(t){if(!this.mediaElement){console.error("Audio not loaded");return}const e=this.mediaElement.currentTime+t;e<0?this.mediaElement.currentTime=0:e>this.mediaElement.duration?this.mediaElement.currentTime=this.mediaElement.duration:this.mediaElement.currentTime=e}currentTime(){return this.mediaElement.currentTime}duration(){return this.mediaElement.duration}isPlaying(){return this.isPlayingValue}isPaused(){return this.isPausedValue}isStopped(){return!1}isLoading(){return this.isLoadingValue}isLoaded(){return this.isLoadedValue}isEnded(){return this.isEndedValue}isMuted(){return this.isMutedValue}}B.BooleanPreference=N,B.EnumPreference=Ue,B.EpubDefaults=uA,B.EpubNavigator=xe,B.EpubPreferences=Mt,B.EpubPreferencesEditor=Ye,B.EpubSettings=Ne,B.ExperimentalWebPubNavigator=Yn,B.FXLCoordinator=sA,B.FXLFrameManager=AA,B.FXLFramePoolManager=dA,B.FXLPeripherals=lA,B.FXLSpreader=hA,B.FrameComms=dt,B.FrameManager=$i,B.FramePoolManager=iA,B.HorizontalThird=nA,B.LineLengths=ut,B.Navigator=Oe,B.Orientation=Xt,B.Preference=z,B.Properties=Lt,B.RSProperties=mA,B.RangePreference=y,B.ReadiumCSS=fA,B.Spread=Zt,B.TextAlignment=X,B.UserProperties=Te,B.VerticalThird=rA,B.VisualNavigator=re,B.WebAudioEngine=Wn,B.WebPubBlobBuilder=Ke,B.WebPubCSS=Li,B.WebPubDefaults=Zi,B.WebPubFrameManager=ki,B.WebPubFramePoolManager=Ji,B.WebPubNavigator=Ki,B.WebPubPreferences=ft,B.WebPubPreferencesEditor=ye,B.WebPubSettings=Fe,B.WebUserProperties=Ie,B.ensureBoolean=U,B.ensureEnumValue=Tt,B.ensureFilter=st,B.ensureLessThanOrEqual=Oi,B.ensureMoreThanOrEqual=Xi,B.ensureNonNegative=I,B.ensureString=Q,B.ensureValueInRange=L,B.filterRangeConfig=nt,B.fontSizeRangeConfig=yt,B.fontWeightRangeConfig=q,B.fontWidthRangeConfig=Rt,B.letterSpacingRangeConfig=Ct,B.lineHeightRangeConfig=St,B.lineLengthRangeConfig=rt,B.paragraphIndentRangeConfig=Qt,B.paragraphSpacingRangeConfig=zt,B.sML=mt,B.sMLWithRequest=W,B.webPubStylesheet=Xe,B.withFallback=Ot,B.wordSpacingRangeConfig=Yt,B.zoomRangeConfig=Nt,Object.defineProperty(B,Symbol.toStringTag,{value:"Module"})}));
|
|
358
|
+
Overscroll: ${this.pan.overscrollX.toFixed(2)},${this.pan.overscrollY.toFixed(2)}`)}if(A){this.manager.updateBookStyle();return}if(this.dragState>0&&this.pan.letItGo){this.pan.endX=e.X;const o=this.manager.currentSlide*(this.manager.width/this.manager.perPage),a=this.pan.endX-this.pan.startX,h=this.manager.rtl?o+a:o-a;cancelAnimationFrame(this.moveFrame),this.moveFrame=requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.manager.spineElement.style.transform=`translate3d(${(this.manager.rtl?1:-1)*h}px, 0, 0)`})})}}dblclickHandler(t){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(t){t.touches=[{pageX:t.pageX,pageY:t.pageY}]}mousedownHandler(t){this.isScaled&&(this.addTouch(t),this.touchstartHandler(t))}mouseupHandler(t){this.isScaled&&this.touchendHandler(t)}mousemoveHandler(t){this.isScaled&&t.buttons>0&&(t.preventDefault(),this.addTouch(t),this.touchmoveHandler(t))}updateAfterDrag(){const t=(this.manager.rtl?-1:1)*(this.pan.endX-this.pan.startX),e=Math.abs(t);t>0&&e>this.manager.threshold&&this.manager.slength>this.manager.perPage?this.manager.listener("no_less",void 0):t<0&&e>this.manager.threshold&&this.manager.slength>this.manager.perPage&&this.manager.listener("no_more",void 0),this.manager.slideToCurrent(!0,!0)}}var Ot=(r=>(r.auto="auto",r.landscape="landscape",r.portrait="portrait",r))(Ot||{}),Xt=(r=>(r.auto="auto",r.both="both",r.none="none",r.landscape="landscape",r))(Xt||{});class hA{constructor(t){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`)}index(t,e=!1){this.nLandscape=0,t.readingOrder.items.forEach((i,A)=>{e||(t.readingOrder.items[A]=i.addProperties({number:A+1,isImage:i.type?.indexOf("image/")===0}));const n=i.properties?.otherProperties.orientation==="landscape";(!i.properties?.page||e)&&(i.properties=i.properties?.add({page:n?"center":((this.shift?0:1)+A-this.nLandscape)%2?t.metadata.readingProgression===Y.rtl?"right":"left":t.metadata.readingProgression===Y.rtl?"left":"right"})),(n||i.properties?.otherProperties.addBlank)&&this.nLandscape++}),e&&(this.spreads=[]),this.buildSpreads(t.readingOrder)}testShift(t){let e=!1;this.spreads.forEach((i,A)=>{if(i.length>1)return;const n=i[0],s=n.properties?.otherProperties.orientation;A===0&&(s==="landscape"||s!=="portrait"&&((n.width||0)>(n.height||0)||n.properties?.otherProperties.spread==="both"))&&(this.shift=!1),e&&n.properties?.page===G.center&&this.spreads[A-1][0].addProperties({addBlank:!0}),s==="portrait"&&n.properties?.page!=="center"&&n.properties?.otherProperties.number>1?e=!0:e=!1}),this.shift||this.index(t,!0)}buildSpreads(t){let e=[];t.items.forEach((i,A)=>{!A&&this.shift?this.spreads.push([i]):i.properties?.page===G.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)}),e.length>0&&this.spreads.push(e)}currentSpread(t,e){return this.spreads[Math.min(Math.floor(t/e),this.spreads.length-1)]}findByLink(t){return this.spreads.find(e=>e.includes(t))||void 0}}const cA=8,gA=5,vn=300,Dn=15e3,Hn=250,Gn=150,kn=500;class dA{constructor(t,e,i){if(this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.delayedShow=new Map,this.delayedTimeout=new Map,this.previousFrames=[],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.spreadPresentation=i.metadata.otherMetadata?.spread||Xt.auto,this.pub.metadata.effectiveReadingProgression!==Y.rtl&&this.pub.metadata.effectiveReadingProgression!==Y.ltr)throw Error("Unsupported reading progression for EPUB");this.spreader=new hA(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 lA(this),this.pub.readingOrder.items.forEach(A=>{const n=new AA(this.peripherals,this.pub.metadata.effectiveReadingProgression,A.href);this.spineElement.appendChild(n.element),this.pool.set(A.href,n),n.width=100/this.length*(A.properties?.otherProperties.orientation===Ot.landscape||A.properties?.otherProperties.addBlank?this.perPage:1),n.height=this.height})}set listener(t){this._listener=t}get listener(){return this._listener}get doNotDisturb(){return this.peripherals.pan.touchID>0}resizeHandler(t=!0,e=!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),t&&(this.currentSlide=this.reAlign(),this.slideToCurrent(!e,e)),clearTimeout(this.resizeTimeout),this.resizeTimeout=window.setTimeout(()=>{this.pool.forEach((i,A)=>{let n=this.pub.readingOrder.items.findIndex(a=>a.href===A);const s=this.pub.readingOrder.items[n];if(i.width=100/this.length*(s.properties?.otherProperties.orientation===Ot.landscape||s.properties?.otherProperties.addBlank?this.perPage:1),i.height=this.height,!i.loaded)return;const o=this.spreader.findByLink(s);i.update(this.spreadPosition(o,s))})},Hn)}updateDimensions(){this.width=this.bookElement.clientWidth,this.height=this.bookElement.clientHeight}get rtl(){return this.pub.metadata.effectiveReadingProgression===Y.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===Xt.none?!0:(this.orientationInternal===-1&&(this.orientationInternal=this.containerHeightCached>this.container.clientWidth?1:0),this.orientationInternal===1)}updateSpineStyle(t,e=!0){let i="0";this.updateDimensions(),this.perPage>1&&(i=`${this.width/2}px`);const A={transition:t?`all ${e?Gn:kn}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,A)}updateBookStyle(t=!1){if(t){const e={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,e)}this.bookElement.style.transform=`scale(${this.peripherals?.scale||1})`+(this.peripherals?` translate3d(${this.peripherals.pan.translateX}px, ${this.peripherals.pan.translateY}px, 0px)`:"")}goTo(t){if(this.slength<=this.perPage)return;t=this.reAlign(t);const e=this.currentSlide;this.currentSlide=Math.min(Math.max(t,0),this.length-1),e!==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 t=this.slength+this.nLandscape;return this.shift&&t%2===0?t+1:t}get slength(){return this.pub.readingOrder.items.length||0}get shift(){return this.spreader.shift}get nLandscape(){return this.spreader.nLandscape}setPerPage(t){t===null?this.spread=!0:t===1?this.spread=!1:this.spread=!0,requestAnimationFrame(()=>this.resizeHandler(!0))}slideToCurrent(t,e=!0){if(this.updateDimensions(),t)requestAnimationFrame(()=>{requestAnimationFrame(()=>{const i=`translate3d(${this.offset}px, 0, 0)`;this.spineElement.style.transform!==i&&(this.transform=i,this.updateSpineStyle(!0,e),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(t=!1){requestAnimationFrame(()=>{this.transform=`translate3d(${this.offset+50*(t?1:-1)}px, 0, 0)`,this.updateSpineStyle(!0,!0),setTimeout(()=>{this.transform=`translate3d(${this.offset}px, 0, 0)`,this.updateSpineStyle(!0,!0)},100)})}next(t=1){if(this.slength<=this.perPage)return!1;const e=this.currentSlide;return this.currentSlide=Math.min(this.currentSlide+t,this.length-1),this.perPage>1&&this.currentSlide%2&&this.currentSlide--,this.currentSlide===e&&(this.currentSlide+1,this.length),e!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(this.rtl),!1)}prev(t=1){if(this.slength<=this.perPage)return!1;const e=this.currentSlide;return this.currentSlide=Math.max(this.currentSlide-t,0),this.perPage>1&&this.currentSlide%2&&this.currentSlide++,e!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(!this.rtl),!1)}get ownerWindow(){return this.container.ownerDocument.defaultView||window}async destroy(){let t=this.inprogress.values(),e=t.next();const i=[];for(;e.value;)i.push(e.value),e=t.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let A=this.pool.values(),n=A.next();for(;n.value;)await n.value.destroy(),n=A.next();this.pool.clear(),this.blobs.forEach(s=>URL.revokeObjectURL(s)),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}makeSpread(t){return this.perPage<2?[this.pub.readingOrder.items[t]]:this.spreader.currentSpread(t,this.perPage)}reAlign(t=this.currentSlide){return t%2&&!this.single&&t++,t}spreadPosition(t,e){return this.perPage<2||t.length<2?G.center:e.href===t[0].href?this.rtl?G.right:G.left:this.rtl?G.left:G.right}async waitForItem(t){if(this.inprogress.has(t)&&await this.inprogress.get(t),this.delayedShow.has(t)){const e=this.delayedTimeout.get(t);e>0?clearTimeout(e):await this.delayedShow.get(t),this.delayedTimeout.set(t,0),this.delayedShow.delete(t)}}async cancelShowing(t){if(this.delayedShow.has(t)){const e=this.delayedTimeout.get(t);e>0&&clearTimeout(e),this.delayedShow.delete(t)}}async update(t,e,i,A=!1){let n=this.pub.readingOrder.items.findIndex(a=>a.href===e.href);if(n<0)throw Error("Href not found in reading order");this.currentSlide!==n&&(this.currentSlide=this.reAlign(n),this.slideToCurrent(!0));const s=this.makeSpread(this.currentSlide);this.perPage>1&&n++;for(const a of s)await this.waitForItem(a.href);const o=new Promise(async(a,h)=>{const c=[],g=[];this.positions.forEach((l,f)=>{(f>n+cA||f<n-cA)&&(c.includes(l.href)||c.push(l.href)),f<n+gA&&f>n-gA&&(g.includes(l.href)||g.push(l.href))}),c.forEach(async l=>{g.includes(l)||this.pool.has(l)&&(this.cancelShowing(l),await this.pool.get(l)?.unload())}),this.currentBaseURL!==void 0&&t.baseURL!==this.currentBaseURL&&(this.blobs.forEach(l=>URL.revokeObjectURL(l)),this.blobs.clear()),this.currentBaseURL=t.baseURL;const u=async l=>{const f=t.readingOrder.findIndexWithHref(l),E=t.readingOrder.items[f];if(E){if(!this.blobs.has(l)){const S=await new _i(t,this.currentBaseURL||"",E).build(!0);this.blobs.set(l,S)}this.delayedShow.has(l)||this.delayedShow.set(l,new Promise((F,S)=>{let pA=!1;const Ln=window.setTimeout(async()=>{this.delayedTimeout.set(l,0);const On=this.makeSpread(this.reAlign(f)),Xn=this.spreadPosition(On,E),MA=this.pool.get(l);await MA.load(i,this.blobs.get(l)),this.peripherals.isScaled||await MA.show(Xn),this.delayedShow.delete(l),pA=!0,F()},vn);setTimeout(()=>{!pA&&this.delayedShow.has(l)&&S(`Offscreen load timeout: ${l}`)},Dn),this.delayedTimeout.set(l,Ln)}))}};try{await Promise.all(g.map(l=>u(l)))}catch(l){h(l)}const M=[];for(const l of s){const f=this.pool.get(l.href),E=this.blobs.get(l.href);E&&(this.cancelShowing(l.href),await f.load(i,E),await f.show(this.spreadPosition(s,l)),this.previousFrames.push(f),await f.activate(),M.push(f))}for(;this.previousFrames.length>0;){const l=this.previousFrames.shift();l&&!M.includes(l)&&await l.unfocus()}this.previousFrames=M,a()});for(const a of s)this.inprogress.set(a.href,o);await o;for(const a of s)this.inprogress.delete(a.href)}get currentFrames(){if(this.perPage<2){const e=this.pub.readingOrder.items[this.currentSlide];return[this.pool.get(e.href)]}return this.spreader.currentSpread(this.currentSlide,this.perPage).map(e=>this.pool.get(e.href))}get currentBounds(){const t={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(e=>{if(!e)return;const i=e.realSize;t.x=Math.min(t.x,i.x),t.y=Math.min(t.y,i.y),t.width+=i.width,t.height=Math.max(t.height,i.height),t.top=Math.min(t.top,i.top),t.right=Math.min(t.right,i.right),t.bottom=Math.min(t.bottom,i.bottom),t.left=Math.min(t.left,i.left)}),t}get viewport(){const t={readingOrder:[],progressions:new Map,positions:null};return this.spreader.currentSpread(this.currentSlide,this.perPage).forEach(i=>{t.readingOrder.push(i.href),t.progressions.set(i.href,{start:0,end:1})}),t.positions=this.getCurrentNumbers(),t}getCurrentNumbers(){if(this.perPage<2)return[this.pub.readingOrder.items[this.currentSlide].properties?.otherProperties.number];const t=this.spreader.currentSpread(this.currentSlide,this.perPage);return t.length>1?[t[0].properties?.otherProperties.number,t[t.length-1].properties?.otherProperties.number]:[t[0].properties?.otherProperties.number]}deselect(){this.currentFrames?.forEach(t=>t?.deselect())}}class pt{constructor(t={}){this.backgroundColor=Q(t.backgroundColor),this.blendFilter=y(t.blendFilter),this.constraint=I(t.constraint),this.columnCount=I(t.columnCount),this.darkenFilter=rt(t.darkenFilter),this.deprecatedFontSize=y(t.deprecatedFontSize),this.fontFamily=Q(t.fontFamily),this.fontSize=W(t.fontSize,yt.range),this.fontSizeNormalize=y(t.fontSizeNormalize),this.fontOpticalSizing=y(t.fontOpticalSizing),this.fontWeight=W(t.fontWeight,K.range),this.fontWidth=W(t.fontWidth,Ut.range),this.hyphens=y(t.hyphens),this.invertFilter=rt(t.invertFilter),this.invertGaijiFilter=rt(t.invertGaijiFilter),this.iOSPatch=y(t.iOSPatch),this.iPadOSPatch=y(t.iPadOSPatch),this.letterSpacing=I(t.letterSpacing),this.ligatures=y(t.ligatures),this.lineHeight=I(t.lineHeight),this.linkColor=Q(t.linkColor),this.noRuby=y(t.noRuby),this.pageGutter=I(t.pageGutter),this.paragraphIndent=I(t.paragraphIndent),this.paragraphSpacing=I(t.paragraphSpacing),this.scroll=y(t.scroll),this.scrollPaddingTop=I(t.scrollPaddingTop),this.scrollPaddingBottom=I(t.scrollPaddingBottom),this.selectionBackgroundColor=Q(t.selectionBackgroundColor),this.selectionTextColor=Q(t.selectionTextColor),this.textAlign=Nt(t.textAlign,O),this.textColor=Q(t.textColor),this.textNormalization=y(t.textNormalization),this.visitedColor=Q(t.visitedColor),this.wordSpacing=I(t.wordSpacing),this.optimalLineLength=I(t.optimalLineLength),this.maximalLineLength=I(t.maximalLineLength),this.minimalLineLength=I(t.minimalLineLength)}static serialize(t){const{...e}=t;return JSON.stringify(e)}static deserialize(t){try{const e=JSON.parse(t);return new pt(e)}catch(e){return console.error("Failed to deserialize preferences:",e),null}}merging(t){const e={...this};for(const i of Object.keys(t))t[i]!==void 0&&(i!=="maximalLineLength"||t[i]===null||t[i]>=(t.optimalLineLength??e.optimalLineLength??65))&&(i!=="minimalLineLength"||t[i]===null||t[i]<=(t.optimalLineLength??e.optimalLineLength??65))&&(e[i]=t[i]);return new pt(e)}}class uA{constructor(t){this.backgroundColor=Q(t.backgroundColor)||null,this.blendFilter=y(t.blendFilter)??!1,this.constraint=I(t.constraint)||0,this.columnCount=I(t.columnCount)||null,this.darkenFilter=rt(t.darkenFilter)??!1,this.deprecatedFontSize=y(t.deprecatedFontSize),(this.deprecatedFontSize===!1||this.deprecatedFontSize===null)&&(this.deprecatedFontSize=!CSS.supports("zoom","1")),this.fontFamily=Q(t.fontFamily)||null,this.fontSize=W(t.fontSize,yt.range)||1,this.fontSizeNormalize=y(t.fontSizeNormalize)??!1,this.fontOpticalSizing=y(t.fontOpticalSizing)??null,this.fontWeight=W(t.fontWeight,K.range)||null,this.fontWidth=W(t.fontWidth,Ut.range)||null,this.hyphens=y(t.hyphens)??null,this.invertFilter=rt(t.invertFilter)??!1,this.invertGaijiFilter=rt(t.invertGaijiFilter)??!1,this.iOSPatch=t.iOSPatch===!1?!1:(J.OS.iOS||J.OS.iPadOS)&&J.iOSRequest==="mobile",this.iPadOSPatch=t.iPadOSPatch===!1?!1:J.OS.iPadOS&&J.iOSRequest==="desktop",this.letterSpacing=I(t.letterSpacing)||null,this.ligatures=y(t.ligatures)??null,this.lineHeight=I(t.lineHeight)||null,this.linkColor=Q(t.linkColor)||null,this.noRuby=y(t.noRuby)??!1,this.pageGutter=Lt(I(t.pageGutter),20),this.paragraphIndent=I(t.paragraphIndent)??null,this.paragraphSpacing=I(t.paragraphSpacing)??null,this.scroll=y(t.scroll)??!1,this.scrollPaddingTop=I(t.scrollPaddingTop)??null,this.scrollPaddingBottom=I(t.scrollPaddingBottom)??null,this.selectionBackgroundColor=Q(t.selectionBackgroundColor)||null,this.selectionTextColor=Q(t.selectionTextColor)||null,this.textAlign=Nt(t.textAlign,O)||null,this.textColor=Q(t.textColor)||null,this.textNormalization=y(t.textNormalization)??!1,this.visitedColor=Q(t.visitedColor)||null,this.wordSpacing=I(t.wordSpacing)||null,this.optimalLineLength=I(t.optimalLineLength)||65,this.maximalLineLength=Lt(Xi(t.maximalLineLength,this.optimalLineLength),80),this.minimalLineLength=Lt(Oi(t.minimalLineLength,this.optimalLineLength),40)}}const Mt={RS__backgroundColor:"#FFFFFF",RS__textColor:"#121212",RS__linkColor:"#0000EE",RS__visitedColor:"#551A8B",RS__selectionBackgroundColor:"#b4d8fe",RS__selectionTextColor:"inherit"};class ze{constructor(t,e,i){this.preferences=t,this.settings=e,this.metadata=i,this.layout=this.metadata?.effectiveLayout||w.reflowable}clear(){this.preferences=new pt({optimalLineLength:65})}updatePreference(t,e){this.preferences[t]=e}get backgroundColor(){return new z({initialValue:this.preferences.backgroundColor,effectiveValue:this.settings.backgroundColor||Mt.RS__backgroundColor,isEffective:this.preferences.backgroundColor!==null,onChange:t=>{this.updatePreference("backgroundColor",t||null)}})}get blendFilter(){return new N({initialValue:this.preferences.blendFilter,effectiveValue:this.settings.blendFilter||!1,isEffective:this.preferences.blendFilter!==null,onChange:t=>{this.updatePreference("blendFilter",t||null)}})}get columnCount(){return new z({initialValue:this.preferences.columnCount,effectiveValue:this.settings.columnCount||null,isEffective:this.layout!==w.fixed&&!this.settings.scroll,onChange:t=>{this.updatePreference("columnCount",t||null)}})}get constraint(){return new z({initialValue:this.preferences.constraint,effectiveValue:this.preferences.constraint||0,isEffective:!0,onChange:t=>{this.updatePreference("constraint",t||null)}})}get darkenFilter(){return new U({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:t=>{this.updatePreference("darkenFilter",t||null)},supportedRange:At.range,step:At.step})}get deprecatedFontSize(){return new N({initialValue:this.preferences.deprecatedFontSize,effectiveValue:CSS.supports("zoom","1")?this.settings.deprecatedFontSize||!1:!0,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("deprecatedFontSize",t||null)}})}get fontFamily(){return new z({initialValue:this.preferences.fontFamily,effectiveValue:this.settings.fontFamily||null,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("fontFamily",t||null)}})}get fontSize(){return new U({initialValue:this.preferences.fontSize,effectiveValue:this.settings.fontSize||1,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("fontSize",t||null)},supportedRange:yt.range,step:yt.step})}get fontSizeNormalize(){return new N({initialValue:this.preferences.fontSizeNormalize,effectiveValue:this.settings.fontSizeNormalize||!1,isEffective:this.layout!==w.fixed&&this.preferences.fontSizeNormalize!==null,onChange:t=>{this.updatePreference("fontSizeNormalize",t||null)}})}get fontOpticalSizing(){return new N({initialValue:this.preferences.fontOpticalSizing,effectiveValue:this.settings.fontOpticalSizing||!0,isEffective:this.layout!==w.fixed&&this.preferences.fontOpticalSizing!==null,onChange:t=>{this.updatePreference("fontOpticalSizing",t||null)}})}get fontWeight(){return new U({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.layout!==w.fixed&&this.preferences.fontWeight!==null,onChange:t=>{this.updatePreference("fontWeight",t||null)},supportedRange:K.range,step:K.step})}get fontWidth(){return new U({initialValue:this.preferences.fontWidth,effectiveValue:this.settings.fontWidth||100,isEffective:this.layout!==w.fixed&&this.preferences.fontWidth!==null,onChange:t=>{this.updatePreference("fontWidth",t||null)},supportedRange:Ut.range,step:Ut.step})}get hyphens(){return new N({initialValue:this.preferences.hyphens,effectiveValue:this.settings.hyphens||!1,isEffective:this.layout!==w.fixed&&this.metadata?.effectiveReadingProgression===Y.ltr&&this.preferences.hyphens!==null,onChange:t=>{this.updatePreference("hyphens",t||null)}})}get invertFilter(){return new U({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:t=>{this.updatePreference("invertFilter",t||null)},supportedRange:At.range,step:At.step})}get invertGaijiFilter(){return new U({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:t=>{this.updatePreference("invertGaijiFilter",t||null)},supportedRange:At.range,step:At.step})}get iOSPatch(){return new N({initialValue:this.preferences.iOSPatch,effectiveValue:this.settings.iOSPatch||!1,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("iOSPatch",t||null)}})}get iPadOSPatch(){return new N({initialValue:this.preferences.iPadOSPatch,effectiveValue:this.settings.iPadOSPatch||!1,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("iPadOSPatch",t||null)}})}get letterSpacing(){return new U({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.layout!==w.fixed&&this.preferences.letterSpacing!==null,onChange:t=>{this.updatePreference("letterSpacing",t||null)},supportedRange:Rt.range,step:Rt.step})}get ligatures(){return new N({initialValue:this.preferences.ligatures,effectiveValue:this.settings.ligatures||!0,isEffective:this.layout!==w.fixed&&this.metadata?.languages?.some(t=>t==="ar"||t==="fa")&&this.preferences.ligatures!==null||!1,onChange:t=>{this.updatePreference("ligatures",t||null)}})}get lineHeight(){return new U({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.layout!==w.fixed&&this.preferences.lineHeight!==null,onChange:t=>{this.updatePreference("lineHeight",t||null)},supportedRange:Ct.range,step:Ct.step})}get linkColor(){return new z({initialValue:this.preferences.linkColor,effectiveValue:this.settings.linkColor||Mt.RS__linkColor,isEffective:this.layout!==w.fixed&&this.preferences.linkColor!==null,onChange:t=>{this.updatePreference("linkColor",t||null)}})}get maximalLineLength(){return new U({initialValue:this.preferences.maximalLineLength,effectiveValue:this.settings.maximalLineLength,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("maximalLineLength",t)},supportedRange:nt.range,step:nt.step})}get minimalLineLength(){return new U({initialValue:this.preferences.minimalLineLength,effectiveValue:this.settings.minimalLineLength,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("minimalLineLength",t)},supportedRange:nt.range,step:nt.step})}get noRuby(){return new N({initialValue:this.preferences.noRuby,effectiveValue:this.settings.noRuby||!1,isEffective:this.layout!==w.fixed&&this.metadata?.languages?.includes("ja")||!1,onChange:t=>{this.updatePreference("noRuby",t||null)}})}get optimalLineLength(){return new U({initialValue:this.preferences.optimalLineLength,effectiveValue:this.settings.optimalLineLength,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("optimalLineLength",t)},supportedRange:nt.range,step:nt.step})}get pageGutter(){return new z({initialValue:this.preferences.pageGutter,effectiveValue:this.settings.pageGutter,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("pageGutter",t||null)}})}get paragraphIndent(){return new U({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.layout!==w.fixed&&this.preferences.paragraphIndent!==null,onChange:t=>{this.updatePreference("paragraphIndent",t||null)},supportedRange:St.range,step:St.step})}get paragraphSpacing(){return new U({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.layout!==w.fixed&&this.preferences.paragraphSpacing!==null,onChange:t=>{this.updatePreference("paragraphSpacing",t||null)},supportedRange:Qt.range,step:Qt.step})}get scroll(){return new N({initialValue:this.preferences.scroll,effectiveValue:this.settings.scroll||!1,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("scroll",t||null)}})}get scrollPaddingTop(){return new z({initialValue:this.preferences.scrollPaddingTop,effectiveValue:this.settings.scrollPaddingTop||0,isEffective:this.layout!==w.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingTop!==null,onChange:t=>{this.updatePreference("scrollPaddingTop",t||null)}})}get scrollPaddingBottom(){return new z({initialValue:this.preferences.scrollPaddingBottom,effectiveValue:this.settings.scrollPaddingBottom||0,isEffective:this.layout!==w.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingBottom!==null,onChange:t=>{this.updatePreference("scrollPaddingBottom",t||null)}})}get selectionBackgroundColor(){return new z({initialValue:this.preferences.selectionBackgroundColor,effectiveValue:this.settings.selectionBackgroundColor||Mt.RS__selectionBackgroundColor,isEffective:this.layout!==w.fixed&&this.preferences.selectionBackgroundColor!==null,onChange:t=>{this.updatePreference("selectionBackgroundColor",t||null)}})}get selectionTextColor(){return new z({initialValue:this.preferences.selectionTextColor,effectiveValue:this.settings.selectionTextColor||Mt.RS__selectionTextColor,isEffective:this.layout!==w.fixed&&this.preferences.selectionTextColor!==null,onChange:t=>{this.updatePreference("selectionTextColor",t||null)}})}get textAlign(){return new Fe({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||O.start,isEffective:this.layout!==w.fixed&&this.preferences.textAlign!==null,onChange:t=>{this.updatePreference("textAlign",t||null)},supportedValues:Object.values(O)})}get textColor(){return new z({initialValue:this.preferences.textColor,effectiveValue:this.settings.textColor||Mt.RS__textColor,isEffective:this.layout!==w.fixed&&this.preferences.textColor!==null,onChange:t=>{this.updatePreference("textColor",t||null)}})}get textNormalization(){return new N({initialValue:this.preferences.textNormalization,effectiveValue:this.settings.textNormalization||!1,isEffective:this.layout!==w.fixed,onChange:t=>{this.updatePreference("textNormalization",t||null)}})}get visitedColor(){return new z({initialValue:this.preferences.visitedColor,effectiveValue:this.settings.visitedColor||Mt.RS__visitedColor,isEffective:this.layout!==w.fixed&&this.preferences.visitedColor!==null,onChange:t=>{this.updatePreference("visitedColor",t||null)}})}get wordSpacing(){return new U({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.layout!==w.fixed&&this.preferences.wordSpacing!==null,onChange:t=>{this.updatePreference("wordSpacing",t||null)},supportedRange:zt.range,step:zt.step})}}class Ye{constructor(t,e){this.backgroundColor=t.backgroundColor||e.backgroundColor||null,this.blendFilter=typeof t.blendFilter=="boolean"?t.blendFilter:e.blendFilter??null,this.columnCount=t.columnCount!==void 0?t.columnCount:e.columnCount!==void 0?e.columnCount:null,this.constraint=t.constraint||e.constraint,this.darkenFilter=typeof t.darkenFilter=="boolean"?t.darkenFilter:e.darkenFilter??null,this.deprecatedFontSize=typeof t.deprecatedFontSize=="boolean"?t.deprecatedFontSize:e.deprecatedFontSize??null,this.fontFamily=t.fontFamily||e.fontFamily||null,this.fontSize=t.fontSize!==void 0?t.fontSize:e.fontSize!==void 0?e.fontSize:null,this.fontSizeNormalize=typeof t.fontSizeNormalize=="boolean"?t.fontSizeNormalize:e.fontSizeNormalize??null,this.fontOpticalSizing=typeof t.fontOpticalSizing=="boolean"?t.fontOpticalSizing:e.fontOpticalSizing??null,this.fontWeight=t.fontWeight!==void 0?t.fontWeight:e.fontWeight!==void 0?e.fontWeight:null,this.fontWidth=t.fontWidth!==void 0?t.fontWidth:e.fontWidth!==void 0?e.fontWidth:null,this.hyphens=typeof t.hyphens=="boolean"?t.hyphens:e.hyphens??null,this.invertFilter=typeof t.invertFilter=="boolean"?t.invertFilter:e.invertFilter??null,this.invertGaijiFilter=typeof t.invertGaijiFilter=="boolean"?t.invertGaijiFilter:e.invertGaijiFilter??null,this.iOSPatch=this.deprecatedFontSize||t.iOSPatch===!1?!1:t.iOSPatch===!0?(J.OS.iOS||J.OS.iPadOS)&&J.iOSRequest==="mobile":e.iOSPatch,this.iPadOSPatch=this.deprecatedFontSize||t.iPadOSPatch===!1?!1:t.iPadOSPatch===!0?J.OS.iPadOS&&J.iOSRequest==="desktop":e.iPadOSPatch,this.letterSpacing=t.letterSpacing!==void 0?t.letterSpacing:e.letterSpacing!==void 0?e.letterSpacing:null,this.ligatures=typeof t.ligatures=="boolean"?t.ligatures:e.ligatures??null,this.lineHeight=t.lineHeight!==void 0?t.lineHeight:e.lineHeight!==void 0?e.lineHeight:null,this.linkColor=t.linkColor||e.linkColor||null,this.maximalLineLength=t.maximalLineLength===null?null:t.maximalLineLength||e.maximalLineLength||null,this.minimalLineLength=t.minimalLineLength===null?null:t.minimalLineLength||e.minimalLineLength||null,this.noRuby=typeof t.noRuby=="boolean"?t.noRuby:e.noRuby??null,this.optimalLineLength=t.optimalLineLength||e.optimalLineLength,this.pageGutter=t.pageGutter!==void 0?t.pageGutter:e.pageGutter!==void 0?e.pageGutter:null,this.paragraphIndent=t.paragraphIndent!==void 0?t.paragraphIndent:e.paragraphIndent!==void 0?e.paragraphIndent:null,this.paragraphSpacing=t.paragraphSpacing!==void 0?t.paragraphSpacing:e.paragraphSpacing!==void 0?e.paragraphSpacing:null,this.scroll=typeof t.scroll=="boolean"?t.scroll:e.scroll??null,this.scrollPaddingTop=t.scrollPaddingTop!==void 0?t.scrollPaddingTop:e.scrollPaddingTop!==void 0?e.scrollPaddingTop:null,this.scrollPaddingBottom=t.scrollPaddingBottom!==void 0?t.scrollPaddingBottom:e.scrollPaddingBottom!==void 0?e.scrollPaddingBottom:null,this.selectionBackgroundColor=t.selectionBackgroundColor||e.selectionBackgroundColor||null,this.selectionTextColor=t.selectionTextColor||e.selectionTextColor||null,this.textAlign=t.textAlign||e.textAlign||null,this.textColor=t.textColor||e.textColor||null,this.textNormalization=typeof t.textNormalization=="boolean"?t.textNormalization:e.textNormalization??null,this.visitedColor=t.visitedColor||e.visitedColor||null,this.wordSpacing=t.wordSpacing!==void 0?t.wordSpacing:e.wordSpacing!==void 0?e.wordSpacing:null}}function Zt(r){const t=getComputedStyle(r),e=parseFloat(t.paddingLeft||"0"),i=parseFloat(t.paddingRight||"0");return r.clientWidth-e-i}class Ne extends Wt{constructor(t){super(),this.a11yNormalize=t.a11yNormalize??null,this.backgroundColor=t.backgroundColor??null,this.blendFilter=t.blendFilter??null,this.bodyHyphens=t.bodyHyphens??null,this.colCount=t.colCount??null,this.darkenFilter=t.darkenFilter??null,this.deprecatedFontSize=t.deprecatedFontSize??null,this.fontFamily=t.fontFamily??null,this.fontOpticalSizing=t.fontOpticalSizing??null,this.fontSize=t.fontSize??null,this.fontSizeNormalize=t.fontSizeNormalize??null,this.fontWeight=t.fontWeight??null,this.fontWidth=t.fontWidth??null,this.invertFilter=t.invertFilter??null,this.invertGaijiFilter=t.invertGaijiFilter??null,this.iOSPatch=t.iOSPatch??null,this.iPadOSPatch=t.iPadOSPatch??null,this.letterSpacing=t.letterSpacing??null,this.ligatures=t.ligatures??null,this.lineHeight=t.lineHeight??null,this.lineLength=t.lineLength??null,this.linkColor=t.linkColor??null,this.noRuby=t.noRuby??null,this.paraIndent=t.paraIndent??null,this.paraSpacing=t.paraSpacing??null,this.selectionBackgroundColor=t.selectionBackgroundColor??null,this.selectionTextColor=t.selectionTextColor??null,this.textAlign=t.textAlign??null,this.textColor=t.textColor??null,this.view=t.view??null,this.visitedColor=t.visitedColor??null,this.wordSpacing=t.wordSpacing??null}toCSSProperties(){const t={};return this.a11yNormalize&&(t["--USER__a11yNormalize"]=this.toFlag("a11y")),this.backgroundColor&&(t["--USER__backgroundColor"]=this.backgroundColor),this.blendFilter&&(t["--USER__blendFilter"]=this.toFlag("blend")),this.bodyHyphens&&(t["--USER__bodyHyphens"]=this.bodyHyphens),this.colCount&&(t["--USER__colCount"]=this.toUnitless(this.colCount)),this.darkenFilter===!0?t["--USER__darkenFilter"]=this.toFlag("darken"):typeof this.darkenFilter=="number"&&(t["--USER__darkenFilter"]=this.toPercentage(this.darkenFilter)),this.deprecatedFontSize&&(t["--USER__fontSizeImplementation"]=this.toFlag("deprecatedFontSize")),this.fontFamily&&(t["--USER__fontFamily"]=this.fontFamily),this.fontOpticalSizing!=null&&(t["--USER__fontOpticalSizing"]=this.fontOpticalSizing),this.fontSize!=null&&(t["--USER__fontSize"]=this.toPercentage(this.fontSize,!0)),this.fontSizeNormalize&&(t["--USER__fontSizeNormalize"]=this.toFlag("normalize")),this.fontWeight!=null&&(t["--USER__fontWeight"]=this.toUnitless(this.fontWeight)),this.fontWidth!=null&&(t["--USER__fontWidth"]=typeof this.fontWidth=="string"?this.fontWidth:this.toUnitless(this.fontWidth)),this.invertFilter===!0?t["--USER__invertFilter"]=this.toFlag("invert"):typeof this.invertFilter=="number"&&(t["--USER__invertFilter"]=this.toPercentage(this.invertFilter)),this.invertGaijiFilter===!0?t["--USER__invertGaiji"]=this.toFlag("invertGaiji"):typeof this.invertGaijiFilter=="number"&&(t["--USER__invertGaiji"]=this.toPercentage(this.invertGaijiFilter)),this.iOSPatch&&(t["--USER__iOSPatch"]=this.toFlag("iOSPatch")),this.iPadOSPatch&&(t["--USER__iPadOSPatch"]=this.toFlag("iPadOSPatch")),this.letterSpacing!=null&&(t["--USER__letterSpacing"]=this.toRem(this.letterSpacing)),this.ligatures&&(t["--USER__ligatures"]=this.ligatures),this.lineHeight!=null&&(t["--USER__lineHeight"]=this.toUnitless(this.lineHeight)),this.lineLength!=null&&(t["--USER__lineLength"]=this.toPx(this.lineLength)),this.linkColor&&(t["--USER__linkColor"]=this.linkColor),this.noRuby&&(t["--USER__noRuby"]=this.toFlag("noRuby")),this.paraIndent!=null&&(t["--USER__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(t["--USER__paraSpacing"]=this.toRem(this.paraSpacing)),this.selectionBackgroundColor&&(t["--USER__selectionBackgroundColor"]=this.selectionBackgroundColor),this.selectionTextColor&&(t["--USER__selectionTextColor"]=this.selectionTextColor),this.textAlign&&(t["--USER__textAlign"]=this.textAlign),this.textColor&&(t["--USER__textColor"]=this.textColor),this.view&&(t["--USER__view"]=this.toFlag(this.view)),this.visitedColor&&(t["--USER__visitedColor"]=this.visitedColor),this.wordSpacing!=null&&(t["--USER__wordSpacing"]=this.toRem(this.wordSpacing)),t}}class mA extends Wt{constructor(t){super(),this.backgroundColor=t.backgroundColor??null,this.baseFontFamily=t.baseFontFamily??null,this.baseFontSize=t.baseFontSize??null,this.baseLineHeight=t.baseLineHeight??null,this.boxSizingMedia=t.boxSizingMedia??null,this.boxSizingTable=t.boxSizingTable??null,this.colWidth=t.colWidth??null,this.colCount=t.colCount??null,this.colGap=t.colGap??null,this.codeFontFamily=t.codeFontFamily??null,this.compFontFamily=t.compFontFamily??null,this.defaultLineLength=t.defaultLineLength??null,this.flowSpacing=t.flowSpacing??null,this.humanistTf=t.humanistTf??null,this.linkColor=t.linkColor??null,this.maxMediaWidth=t.maxMediaWidth??null,this.maxMediaHeight=t.maxMediaHeight??null,this.modernTf=t.modernTf??null,this.monospaceTf=t.monospaceTf??null,this.noOverflow=t.noOverflow??null,this.noVerticalPagination=t.noVerticalPagination??null,this.oldStyleTf=t.oldStyleTf??null,this.pageGutter=t.pageGutter??null,this.paraIndent=t.paraIndent??null,this.paraSpacing=t.paraSpacing??null,this.primaryColor=t.primaryColor??null,this.scrollPaddingBottom=t.scrollPaddingBottom??null,this.scrollPaddingTop=t.scrollPaddingTop??null,this.sansSerifJa=t.sansSerifJa??null,this.sansSerifJaV=t.sansSerifJaV??null,this.sansTf=t.sansTf??null,this.secondaryColor=t.secondaryColor??null,this.selectionBackgroundColor=t.selectionBackgroundColor??null,this.selectionTextColor=t.selectionTextColor??null,this.serifJa=t.serifJa??null,this.serifJaV=t.serifJaV??null,this.textColor=t.textColor??null,this.typeScale=t.typeScale??null,this.visitedColor=t.visitedColor??null}toCSSProperties(){const t={};return this.backgroundColor&&(t["--RS__backgroundColor"]=this.backgroundColor),this.baseFontFamily&&(t["--RS__baseFontFamily"]=this.baseFontFamily),this.baseFontSize!=null&&(t["--RS__baseFontSize"]=this.toRem(this.baseFontSize)),this.baseLineHeight!=null&&(t["--RS__baseLineHeight"]=this.toUnitless(this.baseLineHeight)),this.boxSizingMedia&&(t["--RS__boxSizingMedia"]=this.boxSizingMedia),this.boxSizingTable&&(t["--RS__boxSizingTable"]=this.boxSizingTable),this.colWidth!=null&&(t["--RS__colWidth"]=this.colWidth),this.colCount!=null&&(t["--RS__colCount"]=this.toUnitless(this.colCount)),this.colGap!=null&&(t["--RS__colGap"]=this.toPx(this.colGap)),this.codeFontFamily&&(t["--RS__codeFontFamily"]=this.codeFontFamily),this.compFontFamily&&(t["--RS__compFontFamily"]=this.compFontFamily),this.defaultLineLength!=null&&(t["--RS__defaultLineLength"]=this.toPx(this.defaultLineLength)),this.flowSpacing!=null&&(t["--RS__flowSpacing"]=this.toRem(this.flowSpacing)),this.humanistTf&&(t["--RS__humanistTf"]=this.humanistTf),this.linkColor&&(t["--RS__linkColor"]=this.linkColor),this.maxMediaWidth&&(t["--RS__maxMediaWidth"]=this.toVw(this.maxMediaWidth)),this.maxMediaHeight&&(t["--RS__maxMediaHeight"]=this.toVh(this.maxMediaHeight)),this.modernTf&&(t["--RS__modernTf"]=this.modernTf),this.monospaceTf&&(t["--RS__monospaceTf"]=this.monospaceTf),this.noOverflow&&(t["--RS__disableOverflow"]=this.toFlag("noOverflow")),this.noVerticalPagination&&(t["--RS__disablePagination"]=this.toFlag("noVerticalPagination")),this.oldStyleTf&&(t["--RS__oldStyleTf"]=this.oldStyleTf),this.pageGutter!=null&&(t["--RS__pageGutter"]=this.toPx(this.pageGutter)),this.paraIndent!=null&&(t["--RS__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(t["--RS__paraSpacing"]=this.toRem(this.paraSpacing)),this.primaryColor&&(t["--RS__primaryColor"]=this.primaryColor),this.sansSerifJa&&(t["--RS__sans-serif-ja"]=this.sansSerifJa),this.sansSerifJaV&&(t["--RS__sans-serif-ja-v"]=this.sansSerifJaV),this.sansTf&&(t["--RS__sansTf"]=this.sansTf),this.scrollPaddingBottom!=null&&(t["--RS__scrollPaddingBottom"]=this.toPx(this.scrollPaddingBottom)),this.scrollPaddingTop!=null&&(t["--RS__scrollPaddingTop"]=this.toPx(this.scrollPaddingTop)),this.secondaryColor&&(t["--RS__secondaryColor"]=this.secondaryColor),this.selectionBackgroundColor&&(t["--RS__selectionBackgroundColor"]=this.selectionBackgroundColor),this.selectionTextColor&&(t["--RS__selectionTextColor"]=this.selectionTextColor),this.serifJa&&(t["--RS__serif-ja"]=this.serifJa),this.serifJaV&&(t["--RS__serif-ja-v"]=this.serifJaV),this.textColor&&(t["--RS__textColor"]=this.textColor),this.typeScale&&(t["--RS__typeScale"]=this.toUnitless(this.typeScale)),this.visitedColor&&(t["--RS__visitedColor"]=this.visitedColor),t}}class fA{constructor(t){this.rsProperties=t.rsProperties,this.userProperties=t.userProperties,this.lineLengths=t.lineLengths,this.container=t.container,this.containerParent=t.container.parentElement||document.documentElement,this.constraint=t.constraint,this.cachedColCount=t.userProperties.colCount,this.effectiveContainerWidth=Zt(this.containerParent)}update(t){this.cachedColCount=t.columnCount,t.constraint!==this.constraint&&(this.constraint=t.constraint),t.pageGutter!==this.rsProperties.pageGutter&&(this.rsProperties.pageGutter=t.pageGutter),t.scrollPaddingBottom!==this.rsProperties.scrollPaddingBottom&&(this.rsProperties.scrollPaddingBottom=t.scrollPaddingBottom),t.scrollPaddingTop!==this.rsProperties.scrollPaddingTop&&(this.rsProperties.scrollPaddingTop=t.scrollPaddingTop),this.lineLengths.update({fontFace:t.fontFamily,letterSpacing:t.letterSpacing,pageGutter:t.pageGutter,wordSpacing:t.wordSpacing,optimalChars:t.optimalLineLength,minChars:t.minimalLineLength,maxChars:t.maximalLineLength});const e=this.updateLayout(t.fontSize,t.deprecatedFontSize||t.iOSPatch,t.scroll,t.columnCount);e?.effectiveContainerWidth&&(this.effectiveContainerWidth=e?.effectiveContainerWidth);const i={a11yNormalize:t.textNormalization,backgroundColor:t.backgroundColor,blendFilter:t.blendFilter,bodyHyphens:typeof t.hyphens!="boolean"?null:t.hyphens?"auto":"none",colCount:e?.colCount,darkenFilter:t.darkenFilter,deprecatedFontSize:t.deprecatedFontSize,fontFamily:t.fontFamily,fontOpticalSizing:typeof t.fontOpticalSizing!="boolean"?null:t.fontOpticalSizing?"auto":"none",fontSize:t.fontSize,fontSizeNormalize:t.fontSizeNormalize,fontWeight:t.fontWeight,fontWidth:t.fontWidth,invertFilter:t.invertFilter,invertGaijiFilter:t.invertGaijiFilter,iOSPatch:t.iOSPatch,iPadOSPatch:t.iPadOSPatch,letterSpacing:t.letterSpacing,ligatures:typeof t.ligatures!="boolean"?null:t.ligatures?"common-ligatures":"none",lineHeight:t.lineHeight,lineLength:e?.effectiveLineLength,linkColor:t.linkColor,noRuby:t.noRuby,paraIndent:t.paragraphIndent,paraSpacing:t.paragraphSpacing,selectionBackgroundColor:t.selectionBackgroundColor,selectionTextColor:t.selectionTextColor,textAlign:t.textAlign,textColor:t.textColor,view:typeof t.scroll!="boolean"?null:t.scroll?"scroll":"paged",visitedColor:t.visitedColor,wordSpacing:t.wordSpacing};this.userProperties=new Ne(i)}updateLayout(t,e,i,A){return i??this.userProperties.view==="scroll"?this.computeScrollLength(t,e):this.paginate(t,e,A)}getCompensatedMetrics(t,e){const i=t||this.userProperties.fontSize||1,A=i<1?1/i:e?i:1;return{zoomFactor:i,zoomCompensation:A,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(t,e,i){const A=Math.round(Zt(this.containerParent)-this.constraint),n=this.getCompensatedMetrics(t,e),{zoomCompensation:s,optimal:o,minimal:a,maximal:h}=n,c=()=>A>=o&&h!==null?Math.min(Math.round(h*s),A):A;let g=1,u=A;if(i===void 0)return{colCount:void 0,effectiveContainerWidth:u,effectiveLineLength:Math.round(u/g*s)};if(i===null)if(A>=o&&h!==null){g=Math.floor(A/o);const M=Math.round(g*(h*s));u=Math.min(M,A)}else u=c();else if(i>1){const M=Math.round(i*(a!==null?a:o));if(A>=M)if(g=i,h===null)u=A;else{const l=Math.round(g*(h*s));u=Math.min(l,A)}else if(a!==null&&A<Math.round(i*a))if(g=Math.floor(A/a),g<=1)g=1,u=c();else{const l=Math.round(g*(o*s));u=Math.min(l,A)}else{g=i;const l=Math.round(g*(o*s));u=Math.min(l,A)}}else g=1,u=c();return{colCount:g,effectiveContainerWidth:u,effectiveLineLength:Math.round(u/g/(t&&t>=1?t:1)*s)}}computeScrollLength(t,e){const i=Math.round(Zt(this.containerParent)-this.constraint),A=this.getCompensatedMetrics(t&&(t<1||e)?t:1,e),n=A.zoomCompensation,s=A.optimal,o=A.maximal;let a,h=i,c=Math.round(s*n);if(o===null)c=i;else{const g=Math.min(Math.round(o*n),i);c=e?g:Math.round(g*n)}return{colCount:a,effectiveContainerWidth:h,effectiveLineLength:c}}setContainerWidth(){this.container.style.width=`${this.effectiveContainerWidth}px`}resizeHandler(){const t=this.updateLayout(this.userProperties.fontSize,this.userProperties.deprecatedFontSize||this.userProperties.iOSPatch,this.userProperties.view==="scroll",this.cachedColCount);this.userProperties.colCount=t.colCount,this.userProperties.lineLength=t.effectiveLineLength,this.effectiveContainerWidth=t.effectiveContainerWidth,this.container.style.width=`${this.effectiveContainerWidth}px`}}const Jn=r=>({frameLoaded:r.frameLoaded||(()=>{}),positionChanged:r.positionChanged||(()=>{}),tap:r.tap||(()=>!1),click:r.click||(()=>!1),zoom:r.zoom||(()=>{}),miscPointer:r.miscPointer||(()=>{}),scroll:r.scroll||(()=>{}),customEvent:r.customEvent||(()=>{}),handleLocator:r.handleLocator||(()=>!1),textSelected:r.textSelected||(()=>{})});class xe extends ne{constructor(t,e,i,A=[],n=void 0,s={preferences:{},defaults:{}}){super(),this._preferencesEditor=null,this.reflowViewport={readingOrder:[],progressions:new Map,positions:null},this.pub=e,this.container=t,this.listeners=Jn(i),this.currentLocation=n,A.length&&(this.positions=A),this._preferences=new pt(s.preferences),this._defaults=new uA(s.defaults),this._settings=new Ye(this._preferences,this._defaults),this._css=new fA({rsProperties:new mA({}),userProperties:new Ne({}),lineLengths:new dt({optimalChars:this._settings.optimalLineLength,minChars:this._settings.minimalLineLength,maxChars:this._settings.maximalLineLength,pageGutter:this._settings.pageGutter,fontFace:this._settings.fontFamily,letterSpacing:this._settings.letterSpacing,wordSpacing:this._settings.wordSpacing}),container:t,constraint:this._settings.constraint}),this._layout=xe.determineLayout(e,!!this._settings.scroll),this.currentProgression=e.metadata.effectiveReadingProgression,this.resizeObserver=new ResizeObserver(()=>this.ownerWindow.requestAnimationFrame(async()=>await this.resizeHandler())),this.resizeObserver.observe(this.container.parentElement||document.documentElement)}static determineLayout(t,e){const i=t.metadata.effectiveLayout;return i===w.fixed||t.metadata.otherMetadata&&"http://openmangaformat.org/schema/1.0#version"in t.metadata.otherMetadata||t.metadata?.conformsTo?.includes(Je.DIVINA)?w.fixed:i===w.scrolled||i===w.reflowable&&e?w.scrolled:w.reflowable}async load(){if(this.positions?.length||(this.positions=await this.pub.positionsFromManifest()),this._layout===w.fixed)this.framePool=new dA(this.container,this.positions,this.pub),this.framePool.listener=(t,e)=>{this.eventListener(t,e)};else{await this.updateCSS(!1);const t=this.compileCSSProperties(this._css);this.framePool=new iA(this.container,this.positions,t)}this.currentLocation===void 0&&(this.currentLocation=this.positions[0]),await this.resizeHandler(),await this.apply()}get settings(){if(this._layout===w.fixed)return Object.freeze({...this._settings});{const t=this._css.userProperties.colCount||this._css.rsProperties.colCount||this._settings.columnCount;return Object.freeze({...this._settings,columnCount:t})}}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new ze(this._preferences,this.settings,this.pub.metadata)),this._preferencesEditor}async submitPreferences(t){this._preferences=this._preferences.merging(t),await this.applyPreferences()}async applyPreferences(){const t=this._settings;this._settings=new Ye(this._preferences,this._defaults),this._preferencesEditor!==null&&(this._preferencesEditor=new ze(this._preferences,this.settings,this.pub.metadata)),this._layout===w.fixed?this.handleFXLPrefs(t,this._settings):await this.updateCSS(!0)}handleFXLPrefs(t,e){t.columnCount!==e.columnCount&&this.framePool.setPerPage(e.columnCount)}async updateCSS(t){this._css.update(this._settings),t&&await this.commitCSS(this._css)}compileCSSProperties(t){const e={};for(const[i,A]of Object.entries(t.rsProperties.toCSSProperties()))e[i]=A;for(const[i,A]of Object.entries(t.userProperties.toCSSProperties()))e[i]=A;return e}async commitCSS(t){const e=this.compileCSSProperties(t);this.framePool.setCSSProperties(e),this._css.userProperties.view==="paged"&&this._layout===w.scrolled?await this.setLayout(w.reflowable):this._css.userProperties.view==="scroll"&&this._layout===w.reflowable&&await this.setLayout(w.scrolled),this._css.setContainerWidth()}async resizeHandler(){const t=this.container.parentElement||document.documentElement;if(this._layout===w.fixed)this.container.style.width=`${Zt(t)-this._settings.constraint}px`,this.framePool.resizeHandler();else{const e=this._css.userProperties.colCount,i=this._css.userProperties.lineLength;this._css.resizeHandler(),(this._css.userProperties.view!=="scroll"&&e!==this._css.userProperties.colCount||i!==this._css.userProperties.lineLength)&&await this.commitCSS(this._css)}}get layout(){return this._layout}get ownerWindow(){return this.container.ownerDocument.defaultView||window}get _cframes(){return this.framePool.currentFrames}get pool(){return this.framePool}eventListener(t,e){switch(t){case"_pong":this.listeners.frameLoaded(this._cframes[0].iframe.contentWindow),this.listeners.positionChanged(this.currentLocation);break;case"first_visible_locator":const i=at.deserialize(e);if(!i)break;this.currentLocation=new at({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(e);break;case"click":case"tap":const A=e;if(A.interactiveElement){const n=new DOMParser().parseFromString(A.interactiveElement,"text/html").body.children[0];if(n.nodeType===n.ELEMENT_NODE&&n.nodeName==="A"&&n.hasAttribute("href")){const s=n.attributes.getNamedItem("href")?.value;if(s.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[s.substring(1)]}),!1,()=>{});else if(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("mailto:")||s.startsWith("tel:"))this.listeners.handleLocator(new q({href:s}).locator);else try{this.goLink(new q({href:Jt.join(Jt.dirname(this.currentLocation.href),s)}),!1,()=>{})}catch(o){console.warn(`Couldn't go to link for ${s}: ${o}`),this.listeners.handleLocator(new q({href:s}).locator)}}else console.log("Clicked on",n)}else{if(this._layout===w.fixed&&this.framePool.doNotDisturb&&(A.doNotDisturb=!0),this._layout===w.fixed&&(this.currentProgression===Y.rtl||this.currentProgression===Y.ltr)&&this.framePool.currentFrames.length>1){const o=this.framePool.currentFrames;A.targetFrameSrc===o[this.currentProgression===Y.rtl?0:1]?.source&&(A.x+=(o[this.currentProgression===Y.rtl?1:0]?.iframe.contentWindow?.innerWidth??0)*window.devicePixelRatio)}if(t==="click"?this.listeners.click(A):this.listeners.tap(A))break;const s=(this._cframes.length===2?this._cframes[0].window.innerWidth+this._cframes[1].window.innerWidth:this._cframes[0].window.innerWidth)*window.devicePixelRatio/4;A.x>=s&&A.x<=s*3&&this.listeners.miscPointer(1),A.x<s?this.goLeft(!1,()=>{}):A.x>s*3&&this.goRight(!1,()=>{})}break;case"tap_more":this.listeners.miscPointer(e);break;case"no_more":this.changeResource(1);break;case"no_less":this.changeResource(-1);break;case"swipe":break;case"scroll":this.listeners.scroll(e);break;case"zoom":this.listeners.zoom(e);break;case"progress":this.syncLocation(e);break;case"log":console.log(this._cframes[0]?.source?.split("/")[3],...e);break;default:this.listeners.customEvent(t,e);break}}determineModules(){let t=Array.from(kt.keys());return this._layout===w.fixed?t.filter(e=>In.includes(e)):(t=t.filter(e=>Fn.includes(e)),this._layout===w.scrolled?t=t.filter(e=>e!=="column_snapper"):t=t.filter(e=>e!=="scroll_snapper"),t)}attachListener(){const t=this._cframes.filter(e=>!!e);if(t.length===0)throw Error("no cframe to attach listener to");t.forEach(e=>{e.msg&&(e.msg.listener=(i,A)=>{this.eventListener(i,A)})})}async apply(){if(await this.framePool.update(this.pub,this.currentLocator,this.determineModules()),this.attachListener(),this.pub.readingOrder.findIndexWithHref(this.currentLocation.href)<0)throw Error("Link for "+this.currentLocation.href+" not found!")}async destroy(){await this.framePool?.destroy()}async changeResource(t){if(t===0)return!1;if(this._layout===w.fixed){const A=this.framePool,n=A.viewport.positions[0];if(t===1){if(!A.next(A.perPage))return!1}else if(t===-1){if(!A.prev(A.perPage))return!1}else throw Error("Invalid relative value for FXL");const s=A.viewport.positions[0];if(n>s){for(let o=this.positions.length-1;o>=0;o--)if(this.positions[o].href===this.pub.readingOrder.items[s-1].href){this.currentLocation=this.positions[o].copyWithLocations({progression:.999999999999});break}}else if(n<s){for(let o=0;o<this.positions.length;o++)if(this.positions[o].href===this.pub.readingOrder.items[s-1].href){this.currentLocation=this.positions[o];break}}return await this.apply(),!0}const e=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),i=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,e+t));if(i===e)return this._cframes[0]?.msg?.send("shake",void 0,async A=>{}),!1;if(e>i){for(let A=this.positions.length-1;A>=0;A--)if(this.positions[A].href===this.pub.readingOrder.items[i].href){this.currentLocation=this.positions[A].copyWithLocations({progression:.999999999999});break}}else for(let A=0;A<this.positions.length;A++)if(this.positions[A].href===this.pub.readingOrder.items[i].href){this.currentLocation=this.positions[A];break}return await this.apply(),!0}findLastPositionInProgressionRange(t,e){const i=t.findLastIndex(A=>{const n=A.locations.progression;return!!(n&&n>e.start&&n<=e.end)});return i!==-1?t[i]:void 0}findNearestPositions(t){const e=this.positions.filter(n=>n.href===this.currentLocation.href);let i=this.currentLocation,A;return e.some((n,s)=>{const o=n.locations.progression??0;if(t.start<=o){i=n;const a=e.splice(s+1,e.length);return A=this.findLastPositionInProgressionRange(a,t),!0}else return!1}),{first:i,last:A}}updateViewport(t){this.reflowViewport.readingOrder=[],this.reflowViewport.progressions.clear(),this.reflowViewport.positions=null,this.currentLocation&&(this.reflowViewport.readingOrder.push(this.currentLocation.href),this.reflowViewport.progressions.set(this.currentLocation.href,t),this.currentLocation.locations?.position!==void 0&&(this.reflowViewport.positions=[this.currentLocation.locations.position],this.lastLocationInView?.locations?.position!==void 0&&this.reflowViewport.positions.push(this.lastLocationInView.locations.position)))}async syncLocation(t){const e=t,i=this.findNearestPositions(e);this.currentLocation=i.first.copyWithLocations({progression:e.start}),this.lastLocationInView=i.last,this.updateViewport(e),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(t,e){this._layout===w.fixed?(this.changeResource(-1),e(!0)):this._cframes[0]?.msg?.send("go_prev",void 0,async i=>{e(i?!0:await this.changeResource(-1))})}goForward(t,e){this._layout===w.fixed?(this.changeResource(1),e(!0)):this._cframes[0]?.msg?.send("go_next",void 0,async i=>{e(i?!0:await this.changeResource(1))})}get currentLocator(){return this.currentLocation}get viewport(){return this._layout===w.fixed?this.framePool.viewport:this.reflowViewport}get isScrollStart(){const t=this.viewport.readingOrder[0];return this.viewport.progressions.get(t)?.start===0}get isScrollEnd(){const t=this.viewport.readingOrder[this.viewport.readingOrder.length-1];return this.viewport.progressions.get(t)?.end===1}get canGoBackward(){const t=this.pub.readingOrder.items[0]?.href;return!(this.viewport.progressions.has(t)&&this.viewport.progressions.get(t)?.start===0)}get canGoForward(){const t=this.pub.readingOrder.items[this.pub.readingOrder.items.length-1]?.href;return!(this.viewport.progressions.has(t)&&this.viewport.progressions.get(t)?.end===1)}get readingProgression(){return this.currentProgression}async setLayout(t){this._layout!==t&&(this._layout=t,await this.framePool.update(this.pub,this.currentLocator,this.determineModules(),!0),this.attachListener())}get publication(){return this.pub}async loadLocator(t,e){let i=!1,A=typeof t.locations.getCssSelector=="function"&&t.locations.getCssSelector();if(t.text?.highlight?i=await new Promise((a,h)=>{this._cframes[0].msg.send("go_text",A?[t.text?.serialize(),A]:t.text?.serialize(),c=>a(c))}):A&&(i=await new Promise((a,h)=>{this._cframes[0].msg.send("go_text",["",A],c=>a(c))})),i){e(i);return}const n=typeof t.locations.htmlId=="function"&&t.locations.htmlId();if(n&&(i=await new Promise((a,h)=>{this._cframes[0].msg.send("go_id",n,c=>a(c))})),i){e(i);return}const s=t?.locations?.progression;s&&s>0?i=await new Promise((a,h)=>{this._cframes[0].msg.send("go_progression",s,c=>a(c))}):i=!0,e(i)}go(t,e,i){const A=t.href.split("#")[0];let n=this.pub.readingOrder.findWithHref(A);if(!n)return i(this.listeners.handleLocator(t));this.currentLocation=this.positions.find(s=>s.href===n.href),this.apply().then(()=>this.loadLocator(t,s=>i(s))).then(()=>{this.attachListener()})}goLink(t,e,i){return this.go(t.locator,e,i)}}class Wn{constructor(t){this.sourceNode=null,this.listeners={},this.isMutedValue=!1,this.isPlayingValue=!1,this.isPausedValue=!1,this.isLoadingValue=!1,this.isLoadedValue=!1,this.isEndedValue=!1,this.playback=t.playback,this.audioContext=t.audioContext,this.gainNode=this.audioContext?.createGain(),this.setVolume(this.playback.state.volume),this.mediaElement=document.createElement("audio"),this.mediaElement.crossOrigin="use-credentials",this.mediaElement.addEventListener("canplaythrough",this.onCanPlayThrough.bind(this)),this.mediaElement.addEventListener("timeupdate",this.onTimeUpdate.bind(this)),this.mediaElement.addEventListener("error",this.onError.bind(this)),this.mediaElement.addEventListener("ended",this.onEnded.bind(this)),this.mediaElement.currentTime=this.playback.state.currentTime}on(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)}off(t,e){this.listeners[t]&&(this.listeners[t]=this.listeners[t].filter(i=>i!==e))}loadAudio(t){this.isLoadingValue=!0,this.mediaElement.src=t,this.mediaElement.load(),this.sourceNode||(this.sourceNode=new MediaElementAudioSourceNode(this.audioContext,{mediaElement:this.mediaElement}),this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination))}async ensureAudioContextRunning(){this.audioContext.state==="suspended"&&await this.audioContext.resume()}onTimeUpdate(){this.emit("timeupdate",this.mediaElement.currentTime)}onCanPlayThrough(){this.isLoadingValue=!1,this.isLoadedValue=!0,this.emit("canplaythrough",null)}onError(){console.error("Error loading media element"),this.emit("error",this.mediaElement.error)}onEnded(){this.isPlayingValue=!1,this.isPausedValue=!1,this.isEndedValue=!0,this.emit("ended",null)}emit(t,e){this.listeners[t]&&this.listeners[t].forEach(i=>i(e))}async playLocator(t,e){}async play(){if(await this.ensureAudioContextRunning(),this.isPlayingValue){this.stop(),console.error("Audio is already playing");return}try{await this.mediaElement.play(),this.isPlayingValue=!0,this.isPausedValue=!1}catch(t){console.error("error trying to play media element",t)}}pause(){this.mediaElement.pause(),this.isPlayingValue=!1,this.isPausedValue=!0}stop(){this.mediaElement.pause(),this.mediaElement.currentTime=0,this.isPlayingValue=!1,this.isPausedValue=!1}setVolume(t){if(t<0){this.gainNode.gain.value=0,this.isMutedValue=!0;return}if(t>1){this.setVolume(t/100);return}this.gainNode.gain.value=t}skip(t){if(!this.mediaElement){console.error("Audio not loaded");return}const e=this.mediaElement.currentTime+t;e<0?this.mediaElement.currentTime=0:e>this.mediaElement.duration?this.mediaElement.currentTime=this.mediaElement.duration:this.mediaElement.currentTime=e}currentTime(){return this.mediaElement.currentTime}duration(){return this.mediaElement.duration}isPlaying(){return this.isPlayingValue}isPaused(){return this.isPausedValue}isStopped(){return!1}isLoading(){return this.isLoadingValue}isLoaded(){return this.isLoadedValue}isEnded(){return this.isEndedValue}isMuted(){return this.isMutedValue}}B.BooleanPreference=N,B.EnumPreference=Fe,B.EpubDefaults=uA,B.EpubNavigator=xe,B.EpubPreferences=pt,B.EpubPreferencesEditor=ze,B.EpubSettings=Ye,B.ExperimentalWebPubNavigator=Yn,B.FXLCoordinator=sA,B.FXLFrameManager=AA,B.FXLFramePoolManager=dA,B.FXLPeripherals=lA,B.FXLSpreader=hA,B.FrameComms=gt,B.FrameManager=$i,B.FramePoolManager=iA,B.HorizontalThird=nA,B.LineLengths=dt,B.Navigator=Oe,B.Orientation=Ot,B.Preference=z,B.Properties=Wt,B.RSProperties=mA,B.RangePreference=U,B.ReadiumCSS=fA,B.Spread=Xt,B.TextAlignment=O,B.UserProperties=Ne,B.VerticalThird=rA,B.VisualNavigator=ne,B.WebAudioEngine=Wn,B.WebPubBlobBuilder=Ke,B.WebPubCSS=Li,B.WebPubDefaults=Zi,B.WebPubFrameManager=ki,B.WebPubFramePoolManager=Ji,B.WebPubNavigator=Ki,B.WebPubPreferences=mt,B.WebPubPreferencesEditor=ye,B.WebPubSettings=Ie,B.WebUserProperties=Ee,B.ensureBoolean=y,B.ensureEnumValue=Nt,B.ensureFilter=rt,B.ensureLessThanOrEqual=Oi,B.ensureMoreThanOrEqual=Xi,B.ensureNonNegative=I,B.ensureString=Q,B.ensureValueInRange=W,B.filterRangeConfig=At,B.fontSizeRangeConfig=yt,B.fontWeightRangeConfig=K,B.fontWidthRangeConfig=Ut,B.letterSpacingRangeConfig=Rt,B.lineHeightRangeConfig=Ct,B.lineLengthRangeConfig=nt,B.paragraphIndentRangeConfig=St,B.paragraphSpacingRangeConfig=Qt,B.sML=ut,B.sMLWithRequest=J,B.webPubStylesheet=Xe,B.withFallback=Lt,B.wordSpacingRangeConfig=zt,B.zoomRangeConfig=Yt,Object.defineProperty(B,Symbol.toStringTag,{value:"Module"})}));
|