vue-book-reader 1.0.9 → 1.1.0

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/README.md CHANGED
@@ -3,6 +3,10 @@
3
3
  vue-book-reader is a vue wrapper for [foliate-js](https://github.com/johnfactotum/foliate-js) - library for rendering e-books in the browser.
4
4
  Supports EPUB, MOBI, KF8 (AZW3), FB2, CBZ, PDF (experimental; requires PDF.js), or add support for other formats yourself by implementing the book interface
5
5
 
6
+ ## Document
7
+
8
+ [document](https://jinhuan138.github.io/vue-book-reader/)
9
+
6
10
  ## Basic usage
7
11
 
8
12
  ```bash
@@ -70,7 +74,7 @@ const getRendition = async (rendition) => {
70
74
  ```vue
71
75
  <template>
72
76
  <div style="height: 100vh">
73
- <VueReader url="/files/啼笑因缘.mobi":getRendition="getRendition"/>
77
+ <VueReader url="/files/啼笑因缘.mobi" :getRendition="getRendition"/>
74
78
  </div>
75
79
  </template>
76
80
 
@@ -118,8 +122,7 @@ const onchange = (e) => {
118
122
  url="/files/啼笑因缘.azw3"
119
123
  :getRendition="getRendition"
120
124
  @update:location="locationChange"
121
- >
122
- </vue-reader>
125
+ />
123
126
  <div class="progress">
124
127
  <input
125
128
  type="number"
@@ -192,8 +195,7 @@ const locationChange = (detail) => {
192
195
  url="/files/啼笑因缘.azw3"
193
196
  :getRendition="getRendition"
194
197
  v-show="false"
195
- >
196
- </vue-reader>
198
+ />
197
199
  <div v-if="information" style="color: #000">
198
200
  <img
199
201
  :src="information.cover"
@@ -0,0 +1 @@
1
+ const e={};export{e as default};
@@ -0,0 +1 @@
1
+ const h=({entries:l,loadBlob:i,getSize:c},d)=>{const r=new Map,a=new Map,m=async e=>{if(r.has(e))return r.get(e);const t=URL.createObjectURL(await i(e)),n=URL.createObjectURL(new Blob([`<!DOCTYPE html><html><head><meta charset="utf-8"></head><body style="margin: 0"><img src="${t}"></body></html>`],{type:"text/html"}));return a.set(e,[t,n]),r.set(e,n),n},f=e=>{var t,n;(n=(t=a.get(e))==null?void 0:t.forEach)==null||n.call(t,g=>URL.revokeObjectURL(g)),a.delete(e),r.delete(e)},p=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".svg",".jxl",".avif"],s=l.map(e=>e.filename).filter(e=>p.some(t=>e.endsWith(t))).sort();if(!s.length)throw new Error("No supported image files in archive");const o={};return o.getCover=()=>i(s[0]),o.metadata={title:d.name},o.sections=s.map(e=>({id:e,load:()=>m(e),unload:()=>f(e),size:c(e)})),o.toc=s.map(e=>({label:e,href:e})),o.rendition={layout:"pre-paginated"},o.resolveHref=e=>({index:o.sections.findIndex(t=>t.id===e)}),o.splitTOCHref=e=>[e,null],o.getTOCFragment=e=>e.documentElement,o.destroy=()=>{for(const e of a.values())for(const t of e)URL.revokeObjectURL(t)},o};export{h as makeComicBook};
@@ -0,0 +1,2 @@
1
+ import{f as gt,p as yt,t as pt,a as wt}from"./index-vPPvgtWJ.js";const S={CONTAINER:"urn:oasis:names:tc:opendocument:xmlns:container",XHTML:"http://www.w3.org/1999/xhtml",OPF:"http://www.idpf.org/2007/opf",EPUB:"http://www.idpf.org/2007/ops",DC:"http://purl.org/dc/elements/1.1/",DCTERMS:"http://purl.org/dc/terms/",ENC:"http://www.w3.org/2001/04/xmlenc#",NCX:"http://www.daisy.org/z3986/2005/ncx/",XLINK:"http://www.w3.org/1999/xlink",SMIL:"http://www.w3.org/ns/SMIL"},T={XML:"application/xml",NCX:"application/x-dtbncx+xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml",JS:/\/(x-)?(javascript|ecmascript)/},B={a11y:"http://www.idpf.org/epub/vocab/package/a11y/#",dcterms:"http://purl.org/dc/terms/",marc:"http://id.loc.gov/vocabulary/",media:"http://www.idpf.org/epub/vocab/overlays/#",onix:"http://www.editeur.org/ONIX/book/codelists/current.html#",rendition:"http://www.idpf.org/vocab/rendition/#",schema:"http://schema.org/",xsd:"http://www.w3.org/2001/XMLSchema#",msv:"http://www.idpf.org/epub/vocab/structure/magazine/#",prism:"http://www.prismstandard.org/specifications/3.0/PRISM_CV_Spec_3.0.htm#"},bt={art:"artist",aut:"author",clr:"colorist",edt:"editor",ill:"illustrator",nrt:"narrator",trl:"translator",pbl:"publisher"},vt={"02":"isbn","06":"doi",15:"isbn",26:"doi",34:"issn"},j=i=>i.toLowerCase().replace(/[-:](.)/g,(t,e)=>e.toUpperCase()),St=i=>i?i.replace(/[\t\n\f\r ]+/g," ").replace(/^[\t\n\f\r ]+/,"").replace(/[\t\n\f\r ]+$/,""):"",At=(i,t,e)=>e?r=>{var s,n;return(n=(s=r.getAttribute(i))==null?void 0:s.split(/\s/))==null?void 0:n.includes(t)}:typeof t=="function"?r=>t(r.getAttribute(i)):r=>r.getAttribute(i)===t,O=(...i)=>t=>t?Object.fromEntries(i.map(e=>[j(e),t.getAttribute(e)])):null,L=i=>St(i==null?void 0:i.textContent),U=(i,t)=>{const e=i.lookupNamespaceURI(null)===t||i.lookupPrefix(t),r=e?(s,n)=>o=>o.namespaceURI===t&&o.localName===n:(s,n)=>o=>o.localName===n;return{$:(s,n)=>[...s.children].find(r(s,n)),$$:(s,n)=>[...s.children].filter(r(s,n)),$$$:e?(s,n)=>[...s.getElementsByTagNameNS(t,n)]:(s,n)=>[...s.getElementsByTagName(n)]}},$=(i,t)=>{try{if(t.includes(":"))return new URL(i,t);const e="https://invalid.invalid/",r=new URL(i,e+t);return r.search="",decodeURI(r.href.replace(e,""))}catch(e){return console.warn(e),i}},ut=i=>/^(?!blob)\w+:/i.test(i),Et=(i,t)=>{if(!i)return t;const e=i.replace(/\/$/,"").split("/"),r=t.replace(/\/$/,"").split("/"),s=(e.length>r.length?e:r).findIndex((n,o)=>e[o]!==r[o]);return s<0?"":Array(e.length-s).fill("..").concat(r.slice(s)).join("/")},Tt=i=>i.slice(0,i.lastIndexOf("/")+1),k=async(i,t,e)=>{const r=[];i.replace(t,(...n)=>(r.push(n),null));const s=[];for(const n of r)s.push(await e(...n));return i.replace(t,()=>s.shift())},xt=i=>i.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),H=i=>{for(const[e,r]of Object.entries(i))r==null?delete i[e]:Array.isArray(r)?(i[e]=r.filter(s=>s).map(s=>typeof s=="object"&&!Array.isArray(s)?H(s):s),i[e].length?i[e].length===1&&(i[e]=i[e][0]):delete i[e]):typeof r=="object"&&(i[e]=H(r),Object.keys(r).length||delete i[e]);const t=Object.keys(i);return t.length===1&&t[0]==="name"?i[t[0]]:i},It=i=>{const t=new Map(Object.entries(B)),e=i.documentElement.getAttributeNS(S.EPUB,"prefix")||i.documentElement.getAttribute("prefix");if(e)for(const[,r,s]of e.matchAll(/(.+): +(.+)[ \t\r\n]*/g))t.set(r,s);return t},dt=(i,t)=>{if(!i)return null;const[e,r]=i.split(":"),s=r?e:null,n=r||e,o=t.get(s);return o?o+n:null},Lt=i=>{var D,q,z,V,_,G,W,J,K,Q,Y,Z,tt,et,rt,st,it,nt,at,ot,lt,ct,ht;const{$:t}=U(i,S.OPF),e=t(i.documentElement,"metadata"),r=Object.groupBy(e.children,a=>a.namespaceURI===S.DC?"dc":a.namespaceURI===S.OPF&&a.localName==="meta"?a.hasAttribute("name")?"legacyMeta":"meta":""),s=e.getAttribute("xml:lang")??i.documentElement.getAttribute("xml:lang")??"und",n=It(i),o=a=>{const m=a.getAttribute("property"),v=a.getAttribute("scheme");return{property:dt(m,n)??m,scheme:dt(v,n)??v,lang:a.getAttribute("xml:lang"),value:L(a),props:h(a),attrs:Object.fromEntries(Array.from(a.attributes).filter(A=>A.namespaceURI===S.OPF).map(A=>[A.localName,A.value]))}},c=Map.groupBy(r.meta??[],a=>a.getAttribute("refines")),h=a=>{const m=c.get(a?"#"+a.getAttribute("id"):null);return m?Object.groupBy(m.map(o),v=>v.property):null},p=Object.fromEntries(Object.entries(Object.groupBy(r.dc,a=>a.localName)).map(([a,m])=>[a,m.map(o)])),u=h()??{},g=Object.fromEntries(((D=r.legacyMeta)==null?void 0:D.map(a=>[a.getAttribute("name"),a.getAttribute("content")]))??[]),d=a=>{var m;return(m=a==null?void 0:a[0])==null?void 0:m.value},l=(a,m)=>{var v;return d((v=a==null?void 0:a.props)==null?void 0:v[m])},b=a=>{var E;if(!a)return null;const m=((E=a.props)==null?void 0:E["alternate-script"])??[],v=a.attrs["alt-rep"];if(!m.length&&(!a.lang||a.lang===s)&&!v)return a.value;const A={[a.lang??s]:a.value};v&&(A[a.attrs["alt-rep-lang"]]=v);for(const R of m)A[R.lang]??=R.value;return A},f=a=>{var m,v,A,E,R;return a?{name:b(a),sortAs:b((v=(m=a.props)==null?void 0:m["file-as"])==null?void 0:v[0])??a.attrs["file-as"],role:((R=(E=(A=a.props)==null?void 0:A.role)==null?void 0:E.filter(P=>P.scheme===B.marc+"relators"))==null?void 0:R.map(P=>P.value))??[a.attrs.role],code:l(a,"term")??a.attrs.term,scheme:l(a,"authority")??a.attrs.authority}:null},y=a=>{var m;return{name:b(a),position:d((m=a.props)==null?void 0:m["group-position"])}},w=a=>{var A;const{value:m}=a;if(/^urn:/i.test(m))return m;if(/^doi:/i.test(m))return`urn:${m}`;const v=(A=a.props)==null?void 0:A["identifier-type"];if(!v){const E=a.attrs.scheme;return E?/^(doi|isbn|uuid)$/i.test(E)?`urn:${E}:${m}`:{scheme:E,value:m}:m}if(v.scheme===B.onix+"codelist5"){const E=vt[v.value];if(E)return`urn:${E}:${m}`}return m},N=Object.groupBy(u["belongs-to-collection"]??[],a=>l(a,"collection-type")==="series"?"series":"collection"),x=((q=p.title)==null?void 0:q.find(a=>l(a,"title-type")==="main"))??((z=p.title)==null?void 0:z[0]),I={identifier:ft(i),title:b(x),sortAs:b((_=(V=x==null?void 0:x.props)==null?void 0:V["file-as"])==null?void 0:_[0])??((G=x==null?void 0:x.attrs)==null?void 0:G["file-as"])??(g==null?void 0:g["calibre:title_sort"]),subtitle:(J=(W=p.title)==null?void 0:W.find(a=>l(a,"title-type")==="subtitle"))==null?void 0:J.value,language:(K=p.language)==null?void 0:K.map(a=>a.value),description:d(p.description),publisher:f((Q=p.publisher)==null?void 0:Q[0]),published:((Z=(Y=p.date)==null?void 0:Y.find(a=>a.attrs.event==="publication"))==null?void 0:Z.value)??d(p.date),modified:d(u[B.dcterms+"modified"])??((et=(tt=p.date)==null?void 0:tt.find(a=>a.attrs.event==="modification"))==null?void 0:et.value),subject:(rt=p.subject)==null?void 0:rt.map(f),belongsTo:{collection:(st=N.collection)==null?void 0:st.map(y),series:((it=N.series)==null?void 0:it.map(y))??(g==null?void 0:g["calibre:series"])?{name:g==null?void 0:g["calibre:series"],position:parseFloat(g==null?void 0:g["calibre:series_index"])}:null},altIdentifier:(nt=p.identifier)==null?void 0:nt.map(w),source:(at=p.source)==null?void 0:at.map(w),rights:d(p.rights)},M=a=>m=>{var A;const v=new Set((A=m.role)==null?void 0:A.map(E=>bt[E]??a));return[v.size?v:[a],m]};for(const[a,m]of[].concat(((lt=(ot=p.creator)==null?void 0:ot.map(f))==null?void 0:lt.map(M("author")))??[],((ht=(ct=p.contributor)==null?void 0:ct.map(f))==null?void 0:ht.map(M("contributor")))??[]))for(const v of a)I[v]?I[v].push(m):I[v]=[m];H(I),I.altIdentifier===I.identifier&&delete I.altIdentifier;const X={},C={};for(const[a,m]of Object.entries(u))a.startsWith(B.rendition)?X[j(a.replace(B.rendition,""))]=d(m):a.startsWith(B.media)&&(C[j(a.replace(B.media,""))]=d(m));return C.duration&&(C.duration=F(C.duration)),{metadata:I,rendition:X,media:C}},Nt=(i,t=e=>e)=>{var b;const{$:e,$$:r,$$$:s}=U(i,S.XHTML),n=f=>f?decodeURI(t(f)):null,o=f=>y=>{var M;const w=e(y,"a")??e(y,"span"),N=e(y,"ol"),x=n(w==null?void 0:w.getAttribute("href")),I={label:L(w)||(w==null?void 0:w.getAttribute("title")),href:x,subitems:c(N)};return f&&(I.type=(M=w==null?void 0:w.getAttributeNS(S.EPUB,"type"))==null?void 0:M.split(/\s/)),I},c=(f,y)=>f?r(f,"li").map(o(y)):null,h=(f,y)=>c(e(f,"ol"),y),p=s(i,"nav");let u=null,g=null,d=null,l=[];for(const f of p){const y=((b=f.getAttributeNS(S.EPUB,"type"))==null?void 0:b.split(/\s/))??[];y.includes("toc")?u??=h(f):y.includes("page-list")?g??=h(f):y.includes("landmarks")?d??=h(f,!0):l.push({label:L(f.firstElementChild),type:y,list:h(f)})}return{toc:u,pageList:g,landmarks:d,others:l}},Bt=(i,t=e=>e)=>{const{$:e,$$:r}=U(i,S.NCX),s=h=>h?decodeURI(t(h)):null,n=h=>{const p=e(h,"navLabel"),u=e(h,"content"),g=L(p),d=s(u.getAttribute("src"));if(h.localName==="navPoint"){const l=r(h,"navPoint");return{label:g,href:d,subitems:l.length?l.map(n):null}}return{label:g,href:d}},o=(h,p)=>r(h,p).map(n),c=(h,p)=>{const u=e(i.documentElement,h);return u?o(u,p):null};return{toc:c("navMap","navPoint"),pageList:c("pageList","pageTarget"),others:r(i.documentElement,"navList").map(h=>({label:L(e(h,"navLabel")),list:o(h,"navTarget")}))}},F=i=>{if(!i)return;const t=i.split(":").map(o=>parseFloat(o));if(t.length===3){const[o,c,h]=t;return o*60*60+c*60+h}if(t.length===2){const[o,c]=t;return o*60+c}const[e,r]=i.split(/(?=[^\d.])/),s=parseFloat(e),n=r==="h"?60*60:r==="min"?60:r==="ms"?.001:1;return s*n};class $t extends EventTarget{#e;#r;#t;#n;#i;#s;#d=1;#f=1;#c;constructor(t,e){super(),this.book=t,this.loadXML=e}async#g(t){if(this.#r===t)return;const e=await this.loadXML(t.href),r=o=>o?$(o,t.href):null,{$:s,$$$:n}=U(e,S.SMIL);this.#n=-1,this.#i=-1,this.#e=n(e,"par").reduce((o,c)=>{var b;const h=r((b=s(c,"text"))==null?void 0:b.getAttribute("src")),p=s(c,"audio");if(!h||!p)return o;const u=r(p.getAttribute("src")),g=F(p.getAttribute("clipBegin")),d=F(p.getAttribute("clipEnd")),l=o.at(-1);return(l==null?void 0:l.src)===u?l.items.push({text:h,begin:g,end:d}):o.push({src:u,items:[{text:h,begin:g,end:d}]}),o},[]),this.#r=t}get#h(){return this.#e[this.#n]}get#a(){var t,e;return(e=(t=this.#h)==null?void 0:t.items)==null?void 0:e[this.#i]}#o(t){console.error(t),this.dispatchEvent(new CustomEvent("error",{detail:t}))}#p(){this.dispatchEvent(new CustomEvent("highlight",{detail:this.#a}))}#u(){this.dispatchEvent(new CustomEvent("unhighlight",{detail:this.#a}))}async#l(t,e){var o;this.#m(),this.#n=t,this.#i=e;const r=(o=this.#h)==null?void 0:o.src;if(!r||!this.#a)return this.start(this.#t+1);const s=URL.createObjectURL(await this.book.loadBlob(r)),n=new Audio(s);this.#s=n,n.volume=this.#d,n.playbackRate=this.#f,n.addEventListener("timeupdate",()=>{var u,g;if(n.paused)return;const c=n.currentTime,{items:h}=this.#h;if(c>((u=this.#a)==null?void 0:u.end)&&(this.#u(),this.#i===h.length-1)){this.#l(this.#n+1,0).catch(d=>this.#o(d));return}const p=this.#i;for(;((g=h[this.#i+1])==null?void 0:g.begin)<=c;)this.#i++;this.#i!==p&&this.#p()}),n.addEventListener("error",()=>this.#o(new Error(`Failed to load ${r}`))),n.addEventListener("playing",()=>this.#p()),n.addEventListener("ended",()=>{this.#u(),URL.revokeObjectURL(s),this.#s=null,this.#l(t+1,0).catch(c=>this.#o(c))}),this.#c==="paused"?(this.#p(),n.currentTime=this.#a.begin??0):n.addEventListener("canplaythrough",()=>{n.currentTime=this.#a.begin??0,this.#c="playing",n.play().catch(c=>this.#o(c))},{once:!0})}async start(t,e=()=>!0){var o;(o=this.#s)==null||o.pause();const r=this.book.sections[t],s=r==null?void 0:r.id;if(!s)return;const{mediaOverlay:n}=r;if(!n)return this.start(t+1);this.#t=t,await this.#g(n);for(let c=0;c<this.#e.length;c++){const{items:h}=this.#e[c];for(let p=0;p<h.length;p++)if(h[p].text.split("#")[0]===s&&e(h[p],p,h))return this.#l(c,p).catch(u=>this.#o(u))}}pause(){var t;this.#c="paused",(t=this.#s)==null||t.pause()}resume(){var t;this.#c="playing",(t=this.#s)==null||t.play().catch(e=>this.#o(e))}#m(){this.#s&&(this.#s.pause(),URL.revokeObjectURL(this.#s.src),this.#s=null,this.#u())}stop(){this.#c="stopped",this.#m()}prev(){this.#i>0?this.#l(this.#n,this.#i-1):this.#n>0?this.#l(this.#n-1,this.#e[this.#n-1].items.length-1):this.#t>0&&this.start(this.#t-1,(t,e,r)=>e===r.length-1)}next(){this.#l(this.#n,this.#i+1)}setVolume(t){this.#d=t,this.#s&&(this.#s.volume=t)}setRate(t){this.#f=t,this.#s&&(this.#s.playbackRate=t)}}const Mt=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,Ct=i=>{for(const t of i.getElementsByTagNameNS(S.DC,"identifier")){const[e]=L(t).split(":").slice(-1);if(Mt.test(e))return e}return""},ft=i=>L(i.getElementById(i.documentElement.getAttribute("unique-identifier"))??i.getElementsByTagNameNS(S.DC,"identifier")[0]),mt=async(i,t,e)=>{const r=new Uint8Array(await e.slice(0,t).arrayBuffer());t=Math.min(t,r.length);for(var s=0;s<t;s++)r[s]=r[s]^i[s%i.length];return new Blob([r,e.slice(t)],{type:e.type})},Rt=async i=>{const t=new TextEncoder().encode(i),e=await globalThis.crypto.subtle.digest("SHA-1",t);return new Uint8Array(e)},Ut=(i=Rt)=>({"http://www.idpf.org/2008/embedding":{key:t=>i(ft(t).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(t,e)=>mt(t,1040,e)},"http://ns.adobe.com/pdf/enc#RC":{key:t=>{const e=Ct(t).replaceAll("-","");return Uint8Array.from({length:16},(r,s)=>parseInt(e.slice(s*2,s*2+2),16))},decode:(t,e)=>mt(t,1024,e)}});class Ot{#e=new Map;#r=new Map;#t;constructor(t){this.#t=t}async init(t,e){if(!t)return;const r=Array.from(t.getElementsByTagNameNS(S.ENC,"EncryptedData"),s=>{var n,o;return{algorithm:(n=s.getElementsByTagNameNS(S.ENC,"EncryptionMethod")[0])==null?void 0:n.getAttribute("Algorithm"),uri:(o=s.getElementsByTagNameNS(S.ENC,"CipherReference")[0])==null?void 0:o.getAttribute("URI")}});for(const{algorithm:s,uri:n}of r){if(!this.#r.has(s)){const o=this.#t[s];if(!o){console.warn("Unknown encryption algorithm");continue}const c=await o.key(e);this.#r.set(s,h=>o.decode(c,h))}this.#e.set(n,s)}}getDecoder(t){return this.#r.get(this.#e.get(t))??(e=>e)}}class kt{constructor({opf:t,resolveHref:e}){var u,g,d,l,b;this.opf=t;const{$:r,$$:s,$$$:n}=U(t,S.OPF),o=r(t.documentElement,"manifest"),c=r(t.documentElement,"spine"),h=s(c,"itemref");this.manifest=s(o,"item").map(O("href","id","media-type","properties","media-overlay")).map(f=>{var y;return f.href=e(f.href),f.properties=(y=f.properties)==null?void 0:y.split(/\s/),f}),this.manifestById=new Map(this.manifest.map(f=>[f.id,f])),this.spine=h.map(O("idref","id","linear","properties")).map(f=>{var y;return f.properties=(y=f.properties)==null?void 0:y.split(/\s/),f}),this.pageProgressionDirection=c.getAttribute("page-progression-direction"),this.navPath=(u=this.getItemByProperty("nav"))==null?void 0:u.href,this.ncxPath=(g=this.getItemByID(c.getAttribute("toc"))??this.manifest.find(f=>f.mediaType===T.NCX))==null?void 0:g.href;const p=r(t.documentElement,"guide");p&&(this.guide=s(p,"reference").map(O("type","title","href")).map(({type:f,title:y,href:w})=>({label:y,type:f.split(/\s/),href:e(w)}))),this.cover=this.getItemByProperty("cover-image")??this.getItemByID((d=n(t,"meta").find(At("name","cover")))==null?void 0:d.getAttribute("content"))??this.getItemByHref((b=(l=this.guide)==null?void 0:l.find(f=>f.type.includes("cover")))==null?void 0:b.href),this.cfis=gt(h)}getItemByID(t){return this.manifestById.get(t)}getItemByHref(t){return this.manifest.find(e=>e.href===t)}getItemByProperty(t){return this.manifest.find(e=>{var r;return(r=e.properties)==null?void 0:r.includes(t)})}resolveCFI(t){const e=yt(t),r=(e.parent??e).shift();let s=pt(this.opf,r);s&&s.nodeName!=="idref"&&(r.at(-1).id=null,s=pt(this.opf,r));const n=s==null?void 0:s.getAttribute("idref");return{index:this.spine.findIndex(o=>o.idref===n),anchor:o=>wt(o,e)}}}class Pt{#e=new Map;#r=new Map;#t=new Map;eventTarget=new EventTarget;constructor({loadText:t,loadBlob:e,resources:r}){this.loadText=t,this.loadBlob=e,this.manifest=r.manifest,this.assets=r.manifest}async createURL(t,e,r,s){if(!e)return"";const n={data:e,type:r};Object.defineProperty(n,"name",{value:t});const o=new CustomEvent("data",{detail:n});this.eventTarget.dispatchEvent(o);const c=await o.detail.data,h=await o.detail.type,p=URL.createObjectURL(new Blob([c],{type:h}));if(this.#e.set(t,p),this.#t.set(t,1),s){const u=this.#r.get(s);u?u.push(t):this.#r.set(s,[t])}return p}ref(t,e){const r=this.#r.get(e);return r!=null&&r.includes(t)||(this.#t.set(t,this.#t.get(t)+1),r?r.push(t):this.#r.set(e,[t])),this.#e.get(t)}unref(t){if(!this.#t.has(t))return;const e=this.#t.get(t)-1;if(e<1){URL.revokeObjectURL(this.#e.get(t)),this.#e.delete(t),this.#t.delete(t);const r=this.#r.get(t);if(r)for(;r.length;)this.unref(r.pop());this.#r.delete(t)}else this.#t.set(t,e)}async loadItem(t,e=[]){if(!t)return null;const{href:r,mediaType:s}=t,n=T.JS.test(t.mediaType),o={type:s,isScript:n,allow:!0},c=new CustomEvent("load",{detail:o});if(this.eventTarget.dispatchEvent(c),!await c.detail.allow)return null;const h=e.at(-1);if(this.#e.has(r))return this.ref(r,h);if((n||[T.XHTML,T.HTML,T.CSS,T.SVG].includes(s))&&e.every(u=>u!==r))return this.loadReplaced(t,e);const p=Promise.resolve().then(()=>this.loadBlob(r));return this.createURL(r,p,s,h)}async loadHref(t,e,r=[]){if(ut(t))return t;const s=$(t,e),n=this.manifest.find(o=>o.href===s);return n?this.loadItem(n,r.concat(e)):t}async loadReplaced(t,e=[]){var h,p;const{href:r,mediaType:s}=t,n=e.at(-1);let o="";try{o=await this.loadText(r)}catch(u){return this.createURL(r,Promise.reject(u),s,n)}if(!o)return null;if([T.XHTML,T.HTML,T.SVG].includes(s)){let u=new DOMParser().parseFromString(o,s);if(s===T.XHTML&&(u.querySelector("parsererror")||!((h=u.documentElement)!=null&&h.namespaceURI))&&(console.warn(((p=u.querySelector("parsererror"))==null?void 0:p.innerText)??"Invalid XHTML"),t.mediaType=T.HTML,u=new DOMParser().parseFromString(o,t.mediaType)),[T.XHTML,T.SVG].includes(t.mediaType)){let l=u.firstChild;for(;l instanceof ProcessingInstruction;){if(l.data){const b=await k(l.data,/(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,(f,y,w,N)=>this.loadHref(w,r,e).then(x=>`${y}${x}${N}`));l.replaceWith(u.createProcessingInstruction(l.target,b))}l=l.nextSibling}}const g=async(l,b)=>l.setAttribute(b,await this.loadHref(l.getAttribute(b),r,e));for(const l of u.querySelectorAll("link[href]"))await g(l,"href");for(const l of u.querySelectorAll("[src]"))await g(l,"src");for(const l of u.querySelectorAll("[poster]"))await g(l,"poster");for(const l of u.querySelectorAll("object[data]"))await g(l,"data");for(const l of u.querySelectorAll("[*|href]:not([href])"))l.setAttributeNS(S.XLINK,"href",await this.loadHref(l.getAttributeNS(S.XLINK,"href"),r,e));for(const l of u.querySelectorAll("style"))l.textContent&&(l.textContent=await this.replaceCSS(l.textContent,r,e));for(const l of u.querySelectorAll("[style]"))l.setAttribute("style",await this.replaceCSS(l.getAttribute("style"),r,e));const d=new XMLSerializer().serializeToString(u);return this.createURL(r,d,t.mediaType,n)}const c=s===T.CSS?await this.replaceCSS(o,r,e):await this.replaceString(o,r,e);return this.createURL(r,c,s,n)}async replaceCSS(t,e,r=[]){const s=await k(t,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,(n,o)=>this.loadHref(o,e,r).then(c=>`url("${c}")`));return k(s,/@import\s*["']([^"'\n]*?)["']/gi,(n,o)=>this.loadHref(o,e,r).then(c=>`@import "${c}"`))}replaceString(t,e,r=[]){const s=new Map,n=this.assets.map(c=>{if(c.href===e)return;const h=Et(Tt(e),c.href),p=encodeURI(h),u="/"+c.href,g=encodeURI(u),d=new Set([h,p,u,g]);for(const l of d)s.set(l,c);return Array.from(d)}).flat().filter(c=>c);if(!n.length)return t;const o=new RegExp(n.map(xt).join("|"),"g");return k(t,o,async c=>this.loadItem(s.get(c.replace(/^\//,"")),r.concat(e)))}unloadItem(t){this.unref(t==null?void 0:t.href)}destroy(){for(const t of this.#e.values())URL.revokeObjectURL(t)}}const jt=(i,t)=>i.getElementById(t)??i.querySelector(`[name="${CSS.escape(t)}"]`),Ht=i=>{for(const t of i){if(t==="page-spread-left"||t==="rendition:page-spread-left")return"left";if(t==="page-spread-right"||t==="rendition:page-spread-right")return"right";if(t==="rendition:page-spread-center")return"center"}},Ft=i=>i?{fixedLayout:L(i.querySelector('option[name="fixed-layout"]')),openToSpread:L(i.querySelector('option[name="open-to-spread"]'))}:null;class Xt{parser=new DOMParser;#e;#r;constructor({loadText:t,loadBlob:e,getSize:r,sha1:s}){this.loadText=t,this.loadBlob=e,this.getSize=r,this.#r=new Ot(Ut(s))}async#t(t){const e=await this.loadText(t);if(!e)return null;const r=this.parser.parseFromString(e,T.XML);if(r.querySelector("parsererror"))throw new Error(`XML parsing error: ${t}
2
+ ${r.querySelector("parsererror").innerText}`);return r}async init(){const t=await this.#t("META-INF/container.xml");if(!t)throw new Error("Failed to load container file");const e=Array.from(t.getElementsByTagNameNS(S.CONTAINER,"rootfile"),O("full-path","media-type")).filter(d=>d.mediaType==="application/oebps-package+xml");if(!e.length)throw new Error("No package document defined in container");const r=e[0].fullPath,s=await this.#t(r);if(!s)throw new Error("Failed to load package document");const n=await this.#t("META-INF/encryption.xml");await this.#r.init(n,s),this.resources=new kt({opf:s,resolveHref:d=>$(d,r)}),this.#e=new Pt({loadText:this.loadText,loadBlob:d=>Promise.resolve(this.loadBlob(d)).then(this.#r.getDecoder(d)),resources:this.resources}),this.transformTarget=this.#e.eventTarget,this.sections=this.resources.spine.map((d,l)=>{const{idref:b,linear:f,properties:y=[]}=d,w=this.resources.getItemByID(b);return w?{id:w.href,load:()=>this.#e.loadItem(w),unload:()=>this.#e.unloadItem(w),createDocument:()=>this.loadDocument(w),size:this.getSize(w.href),cfi:this.resources.cfis[l],linear:f,pageSpread:Ht(y),resolveHref:N=>$(N,w.href),mediaOverlay:w.mediaOverlay?this.resources.getItemByID(w.mediaOverlay):null}:(console.warn(`Could not find item with ID "${b}" in manifest`),null)}).filter(d=>d);const{navPath:o,ncxPath:c}=this.resources;if(o)try{const d=b=>$(b,o),l=Nt(await this.#t(o),d);this.toc=l.toc,this.pageList=l.pageList,this.landmarks=l.landmarks}catch(d){console.warn(d)}if(!this.toc&&c)try{const d=b=>$(b,c),l=Bt(await this.#t(c),d);this.toc=l.toc,this.pageList=l.pageList}catch(d){console.warn(d)}this.landmarks??=this.resources.guide;const{metadata:h,rendition:p,media:u}=Lt(s);this.metadata=h,this.rendition=p,this.media=u,this.dir=this.resources.pageProgressionDirection;const g=Ft(await this.#t("META-INF/com.apple.ibooks.display-options.xml")??await this.#t("META-INF/com.kobobooks.display-options.xml"));return g&&(g.fixedLayout==="true"&&(this.rendition.layout??="pre-paginated"),g.openToSpread==="false"&&(this.sections.find(d=>d.linear!=="no").pageSpread??=this.dir==="rtl"?"left":"right")),this}async loadDocument(t){const e=await this.loadText(t.href);return this.parser.parseFromString(e,t.mediaType)}getMediaOverlay(){return new $t(this,this.#t.bind(this))}resolveCFI(t){return this.resources.resolveCFI(t)}resolveHref(t){const[e,r]=t.split("#"),s=this.resources.getItemByHref(decodeURI(e));return s?{index:this.resources.spine.findIndex(({idref:n})=>n===s.id),anchor:r?n=>jt(n,r):()=>0}:null}splitTOCHref(t){return(t==null?void 0:t.split("#"))??[]}getTOCFragment(t,e){return t.getElementById(e)??t.querySelector(`[name="${CSS.escape(e)}"]`)}isExternal(t){return ut(t)}async getCover(){var e;const t=(e=this.resources)==null?void 0:e.cover;return t!=null&&t.href?new Blob([await this.loadBlob(t.href)],{type:t.mediaType}):null}async getCalibreBookmarks(){const t=await this.loadText("META-INF/calibre_bookmarks.txt"),e="encoding=json+base64:";if(t!=null&&t.startsWith(e)){const r=atob(t.slice(e.length));return JSON.parse(r)}}destroy(){var t;(t=this.#e)==null||t.destroy()}}export{Xt as EPUB};
@@ -0,0 +1,53 @@
1
+ const M=c=>c?c.replace(/[\t\n\f\r ]+/g," ").replace(/^[\t\n\f\r ]+/,"").replace(/[\t\n\f\r ]+$/,""):"",u=c=>M(c==null?void 0:c.textContent),T={XLINK:"http://www.w3.org/1999/xlink",EPUB:"http://www.idpf.org/2007/ops"},L={XML:"application/xml",XHTML:"application/xhtml+xml"},p={strong:["strong","self"],emphasis:["em","self"],style:["span","self"],a:"anchor",strikethrough:["s","self"],sub:["sub","self"],sup:["sup","self"],code:["code","self"],image:"image"},$={tr:["tr",{th:["th",p,["colspan","rowspan","align","valign"]],td:["td",p,["colspan","rowspan","align","valign"]]},["align"]]},N={epigraph:["blockquote"],subtitle:["h2",p],"text-author":["p",p],date:["p",p],stanza:"stanza"},v={title:["header",{p:["h1",p],"empty-line":["br"]}],epigraph:["blockquote","self"],image:"image",annotation:["aside"],section:["section","self"],p:["p",p],poem:["blockquote",N],subtitle:["h2",p],cite:["blockquote","self"],"empty-line":["br"],table:["table",$],"text-author":["p",p]};N.epigraph.push(v);const z={image:"image",title:["section",{p:["h1",p],"empty-line":["br"]}],epigraph:["section",v],section:["section",v]};class X{constructor(t){this.fb2=t,this.doc=document.implementation.createDocument(T.XHTML,"html"),this.bins=new Map(Array.from(this.fb2.getElementsByTagName("binary"),n=>[n.id,n]))}getImageSrc(t){const n=t.getAttributeNS(T.XLINK,"href");if(!n)return"data:,";const[,a]=n.split("#");if(!a)return n;const s=this.bins.get(a);return s?`data:${s.getAttribute("content-type")};base64,${s.textContent}`:n}image(t){const n=this.doc.createElement("img");return n.alt=t.getAttribute("alt"),n.title=t.getAttribute("title"),n.setAttribute("src",this.getImageSrc(t)),n}anchor(t){const n=this.convert(t,{a:["a",p]});return n.setAttribute("href",t.getAttributeNS(T.XLINK,"href")),t.getAttribute("type")==="note"&&n.setAttributeNS(T.EPUB,"epub:type","noteref"),n}stanza(t){const n=this.convert(t,{stanza:["p",{title:["header",{p:["strong",p],"empty-line":["br"]}],subtitle:["p",p]}]});for(const a of t.children)a.nodeName==="v"&&(n.append(this.doc.createTextNode(a.textContent)),n.append(this.doc.createElement("br")));return n}convert(t,n){if(t.nodeType===3)return this.doc.createTextNode(t.textContent);if(t.nodeType===4)return this.doc.createCDATASection(t.textContent);if(t.nodeType===8)return this.doc.createComment(t.textContent);const a=n==null?void 0:n[t.nodeName];if(!a)return null;if(typeof a=="string")return this[a](t);const[s,d,g]=a,m=this.doc.createElement(s);if(t.id&&(m.id=t.id),m.classList.add(t.nodeName),Array.isArray(g))for(const f of g){const A=t.getAttribute(f);A&&m.setAttribute(f,A)}const w=d==="self"?n:d;let y=t.firstChild;for(;y;){const f=this.convert(y,w);f&&m.append(f),y=y.nextSibling}return m}}const D=async c=>{var g;const t=await c.arrayBuffer(),n=new TextDecoder("utf-8").decode(t),a=new DOMParser,s=a.parseFromString(n,L.XML),d=s.xmlEncoding||((g=n.match(/^<\?xml\s+version\s*=\s*["']1.\d+"\s+encoding\s*=\s*["']([A-Za-z0-9._-]*)["']/))==null?void 0:g[1]);if(d&&d.toLowerCase()!=="utf-8"){const m=new TextDecoder(d).decode(t);return a.parseFromString(m,L.XML)}return s},E=URL.createObjectURL(new Blob([`
2
+ @namespace epub "http://www.idpf.org/2007/ops";
3
+ body > img, section > img {
4
+ display: block;
5
+ margin: auto;
6
+ }
7
+ .title h1 {
8
+ text-align: center;
9
+ }
10
+ body > section > .title, body.notesBodyType > .title {
11
+ margin: 3em 0;
12
+ }
13
+ body.notesBodyType > section .title h1 {
14
+ text-align: start;
15
+ }
16
+ body.notesBodyType > section .title {
17
+ margin: 1em 0;
18
+ }
19
+ p {
20
+ text-indent: 1em;
21
+ margin: 0;
22
+ }
23
+ :not(p) + p, p:first-child {
24
+ text-indent: 0;
25
+ }
26
+ .poem p {
27
+ text-indent: 0;
28
+ margin: 1em 0;
29
+ }
30
+ .text-author, .date {
31
+ text-align: end;
32
+ }
33
+ .text-author:before {
34
+ content: "\u2014";
35
+ }
36
+ table {
37
+ border-collapse: collapse;
38
+ }
39
+ td, th {
40
+ padding: .25em;
41
+ }
42
+ a[epub|type~="noteref"] {
43
+ font-size: .75em;
44
+ vertical-align: super;
45
+ }
46
+ body:not(.notesBodyType) > .title, body:not(.notesBodyType) > .epigraph {
47
+ margin: 3em 0;
48
+ }
49
+ `],{type:"text/css"})),O=c=>`<?xml version="1.0" encoding="utf-8"?>
50
+ <html xmlns="http://www.w3.org/1999/xhtml">
51
+ <head><link href="${E}" rel="stylesheet" type="text/css"/></head>
52
+ <body>${c}</body>
53
+ </html>`,C="data-foliate-id",j=async c=>{const t={},n=await D(c),a=new X(n),s=e=>n.querySelector(e),d=e=>[...n.querySelectorAll(e)],g=e=>{const r=u(e.querySelector("nickname"));if(r)return r;const o=u(e.querySelector("first-name")),i=u(e.querySelector("middle-name")),l=u(e.querySelector("last-name")),h=[o,i,l].filter(b=>b).join(" "),x=l?[l,[o,i].filter(b=>b).join(" ")].join(", "):null;return{name:h,sortAs:x}},m=e=>(e==null?void 0:e.getAttribute("value"))??u(e),w=s("title-info annotation");if(t.metadata={title:u(s("title-info book-title")),identifier:u(s("document-info id")),language:u(s("title-info lang")),author:d("title-info author").map(g),translator:d("title-info translator").map(g),contributor:d("document-info author").map(g).concat(d("document-info program-used").map(u)).map(e=>Object.assign(typeof e=="string"?{name:e}:e,{role:"bkp"})),publisher:u(s("publish-info publisher")),published:m(s("title-info date")),modified:m(s("document-info date")),description:w?a.convert(w,{annotation:["div",v]}).innerHTML:null,subject:d("title-info genre").map(u)},s("coverpage image")){const e=a.getImageSrc(s("coverpage image"));t.getCover=()=>fetch(e).then(r=>r.blob())}else t.getCover=()=>null;const y=Array.from(n.querySelectorAll("body"),e=>{const r=a.convert(e,{body:["body",z]});return[Array.from(r.children,o=>{const i=[o,...o.querySelectorAll("[id]")].map(l=>l.id);return{el:o,ids:i}}),r]}),f=[],A=y[0][0].map(({el:e,ids:r})=>{const o=Array.from(e.querySelectorAll(":scope > section > .title"),(i,l)=>(i.setAttribute(C,l),{title:u(i),index:l}));return{ids:r,titles:o,el:e}}).concat(y.slice(1).map(([e,r])=>{const o=e.map(i=>i.ids).flat();return r.classList.add("notesBodyType"),{ids:o,el:r,linear:"no"}})).map(({ids:e,titles:r,el:o,linear:i})=>{var k;const l=O(o.outerHTML),h=new Blob([l],{type:L.XHTML}),x=URL.createObjectURL(h);f.push(x);const b=M(((k=o.querySelector(".title, .subtitle, p"))==null?void 0:k.textContent)??(o.classList.contains("title")?o.textContent:""));return{ids:e,title:b,titles:r,load:()=>x,createDocument:()=>new DOMParser().parseFromString(l,L.XHTML),size:h.size-Array.from(o.querySelectorAll("[src]"),q=>{var S;return((S=q.getAttribute("src"))==null?void 0:S.length)??0}).reduce((q,S)=>q+S,0),linear:i}}),B=new Map;return t.sections=A.map((e,r)=>{const{ids:o,load:i,createDocument:l,size:h,linear:x}=e;for(const b of o)b&&B.set(b,r);return{id:r,load:i,createDocument:l,size:h,linear:x}}),t.toc=A.map(({title:e,titles:r},o)=>{const i=o.toString();return{label:e,href:i,subitems:r!=null&&r.length?r.map(({title:l,index:h})=>({label:l,href:`${i}#${h}`})):null}}).filter(e=>e),t.resolveHref=e=>{const[r,o]=e.split("#");return r?{index:Number(r),anchor:i=>i.querySelector(`[${C}="${o}"]`)}:{index:B.get(o),anchor:i=>i.getElementById(o)}},t.splitTOCHref=e=>{var r;return((r=e==null?void 0:e.split("#"))==null?void 0:r.map(o=>Number(o)))??[]},t.getTOCFragment=(e,r)=>e.querySelector(`[${C}="${r}"]`),t.destroy=()=>{for(const e of f)URL.revokeObjectURL(e)},t};export{j as makeFB2};
@@ -0,0 +1 @@
1
+ var l=Uint8Array,m=Uint16Array,s1=Int32Array,e1=new l([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),n1=new l([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),w1=new l([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),t1=function(a,r){for(var e=new m(31),i=0;i<31;++i)e[i]=r+=1<<a[i-1];var t=new s1(e[30]);for(i=1;i<30;++i)for(var d=e[i];d<e[i+1];++d)t[d]=d-e[i]<<5|i;return{b:e,r:t}},i1=t1(e1,2),v1=i1.b,b1=i1.r;v1[28]=258,b1[258]=28;for(var y1=t1(n1,0).b,D=new m(32768),v=0;v<32768;++v){var g=(43690&v)>>1|(21845&v)<<1;g=(61680&(g=(52428&g)>>2|(13107&g)<<2))>>4|(3855&g)<<4,D[v]=((65280&g)>>8|(255&g)<<8)>>1}var K=function(a,r,e){for(var i=a.length,t=0,d=new m(r);t<i;++t)a[t]&&++d[a[t]-1];var s,b=new m(r);for(t=1;t<r;++t)b[t]=b[t-1]+d[t-1]<<1;if(e){s=new m(1<<r);var k=15-r;for(t=0;t<i;++t)if(a[t])for(var A=t<<4|a[t],y=r-a[t],n=b[a[t]-1]++<<y,o=n|(1<<y)-1;n<=o;++n)s[D[n]>>k]=A}else for(s=new m(i),t=0;t<i;++t)a[t]&&(s[t]=D[b[a[t]-1]++]>>15-a[t]);return s},L=new l(288);for(v=0;v<144;++v)L[v]=8;for(v=144;v<256;++v)L[v]=9;for(v=256;v<280;++v)L[v]=7;for(v=280;v<288;++v)L[v]=8;var o1=new l(32);for(v=0;v<32;++v)o1[v]=5;var p1=K(L,9,1),h1=K(o1,5,1),F=function(a){for(var r=a[0],e=1;e<a.length;++e)a[e]>r&&(r=a[e]);return r},f=function(a,r,e){var i=r/8|0;return(a[i]|a[i+1]<<8)>>(7&r)&e},J=function(a,r){var e=r/8|0;return(a[e]|a[e+1]<<8|a[e+2]<<16)>>(7&r)},x1=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],c=function(a,r,e){var i=new Error(r||x1[a]);if(i.code=a,Error.captureStackTrace&&Error.captureStackTrace(i,c),!e)throw i;return i},g1=function(a,r,e,i){var t=a.length,d=i?i.length:0;if(!t||r.f&&!r.l)return e||new l(0);var s=!e,b=s||r.i!=2,k=r.i;s&&(e=new l(3*t));var A=function(E){var C=e.length;if(E>C){var x=new l(Math.max(2*C,E));x.set(e),e=x}},y=r.f||0,n=r.p||0,o=r.b||0,h=r.l,Y=r.d,S=r.m,U=r.n,H=8*t;do{if(!h){y=f(a,n,1);var I=f(a,n+1,3);if(n+=3,!I){var N=a[(w=4+((n+7)/8|0))-4]|a[w-3]<<8,O=w+N;if(O>t){k&&c(0);break}b&&A(o+N),e.set(a.subarray(w,O),o),r.b=o+=N,r.p=n=8*O,r.f=y;continue}if(I==1)h=p1,Y=h1,S=9,U=5;else if(I==2){var Q=f(a,n,31)+257,M=f(a,n+10,15)+4,P=Q+f(a,n+5,31)+1;n+=14;for(var z=new l(P),W=new l(19),u=0;u<M;++u)W[w1[u]]=f(a,n+3*u,7);n+=3*M;var R=F(W),l1=(1<<R)-1,u1=K(W,R,1);for(u=0;u<P;){var w,V=u1[f(a,n,l1)];if(n+=15&V,(w=V>>4)<16)z[u++]=w;else{var q=0,Z=0;for(w==16?(Z=3+f(a,n,3),n+=2,q=z[u-1]):w==17?(Z=3+f(a,n,7),n+=3):w==18&&(Z=11+f(a,n,127),n+=7);Z--;)z[u++]=q}}var _=z.subarray(0,Q),p=z.subarray(Q);S=F(_),U=F(p),h=K(_,S,1),Y=K(p,U,1)}else c(1);if(n>H){k&&c(0);break}}b&&A(o+131072);for(var f1=(1<<S)-1,c1=(1<<U)-1,$=n;;$=n){var T=(q=h[J(a,n)&f1])>>4;if((n+=15&q)>H){k&&c(0);break}if(q||c(2),T<256)e[o++]=T;else{if(T==256){$=n,h=null;break}var X=T-254;if(T>264){var G=e1[u=T-257];X=f(a,n,(1<<G)-1)+v1[u],n+=G}var j=Y[J(a,n)&c1],B=j>>4;if(j||c(3),n+=15&j,p=y1[B],B>3&&(G=n1[B],p+=J(a,n)&(1<<G)-1,n+=G),n>H){k&&c(0);break}b&&A(o+131072);var a1=o+X;if(o<p){var r1=d-p,d1=Math.min(p,a1);for(r1+o<0&&c(3);o<d1;++o)e[o]=i[r1+o]}for(;o<a1;++o)e[o]=e[o-p]}}r.l=h,r.p=$,r.b=o,r.f=y,h&&(y=1,r.m=S,r.d=Y,r.n=U)}while(!y);return o!=e.length&&s?function(E,C,x){return(x==null||x>E.length)&&(x=E.length),new l(E.subarray(C,x))}(e,0,o):e.subarray(0,o)},k1=new l(0);function T1(a,r){return g1(a.subarray((e=a,i=r&&r.dictionary,((15&e[0])!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&c(6,"invalid zlib data"),(e[1]>>5&1)==+!i&&c(6,"invalid zlib data: "+(32&e[1]?"need":"unexpected")+" dictionary"),2+(e[1]>>3&4)),-4),{i:2},r&&r.out,r&&r.dictionary);var e,i}var E1=typeof TextDecoder<"u"&&new TextDecoder;try{E1.decode(k1,{stream:!0})}catch{}export{T1 as unzlibSync};
@@ -0,0 +1,8 @@
1
+ const y=d=>{var t,e;return(e=(t=d==null?void 0:d.split(/[,;\s]/))==null?void 0:t.filter(i=>i))==null?void 0:e.map(i=>i.split("=").map(s=>s.trim()))},k=(d,t)=>{var s,o;if(d.documentElement.localName==="svg"){const[,,h,r]=((s=d.documentElement.getAttribute("viewBox"))==null?void 0:s.split(/\s/))??[];return{width:h,height:r}}const e=y((o=d.querySelector('meta[name="viewport"]'))==null?void 0:o.getAttribute("content"));if(e)return Object.fromEntries(e);if(typeof t=="string")return y(t);if(t!=null&&t.width&&t.height)return t;const i=d.querySelector("img");return i?{width:i.naturalWidth,height:i.naturalHeight}:(console.warn(new Error("Missing viewport properties")),{width:1e3,height:2e3})};class x extends HTMLElement{static observedAttributes=["zoom"];#a=this.attachShadow({mode:"closed"});#f=new ResizeObserver(()=>this.#e());#i;#r=-1;defaultViewport;spread;#l=!1;#s;#n;#t;#h;#o;constructor(){super();const t=new CSSStyleSheet;this.#a.adoptedStyleSheets=[t],t.replaceSync(`:host {
2
+ width: 100%;
3
+ height: 100%;
4
+ display: flex;
5
+ justify-content: center;
6
+ align-items: center;
7
+ overflow: auto;
8
+ }`),this.#f.observe(this)}attributeChangedCallback(t,e,i){switch(t){case"zoom":this.#o=i!=="fit-width"&&i!=="fit-page"?parseFloat(i):i,this.#e();break}}async#c({index:t,src:e}){const i=typeof e=="string",s=i?e:e==null?void 0:e.src,o=i?null:e==null?void 0:e.onZoom,h=document.createElement("div");h.setAttribute("dir","ltr");const r=document.createElement("iframe");return h.append(r),Object.assign(r.style,{border:"0",display:"none",overflow:"hidden"}),r.setAttribute("sandbox","allow-same-origin allow-scripts"),r.setAttribute("scrolling","no"),r.setAttribute("part","filter"),this.#a.append(h),s?new Promise(n=>{r.addEventListener("load",()=>{const l=r.contentDocument;this.dispatchEvent(new CustomEvent("load",{detail:{doc:l,index:t}}));const{width:c,height:a}=k(l,this.defaultViewport);n({element:h,iframe:r,width:parseFloat(c),height:parseFloat(a),onZoom:o})},{once:!0}),r.src=s}):{blank:!0,element:h,iframe:r}}#e(t=this.#h){if(!t)return;const e=this.#s??{},i=this.#t??this.#n??{},s=t==="left"?e:i,{width:o,height:h}=this.getBoundingClientRect(),r=this.spread!=="both"&&this.spread!=="portrait"&&h>o;this.#l=r;const n=e.width??i.width??0,l=e.height??i.height??0,c=typeof this.#o=="number"&&!isNaN(this.#o)?this.#o:(this.#o==="fit-width"?r||this.#t?o/(s.width??n):o/((e.width??n)+(i.width??n)):r||this.#t?Math.min(o/(s.width??n),h/(s.height??l)):Math.min(o/((e.width??n)+(i.width??n)),h/Math.max(e.height??l,i.height??l)))||1,a=f=>{let{element:g,iframe:p,width:u,height:m,blank:S,onZoom:w}=f;if(!p)return;w&&w({doc:f.iframe.contentDocument,scale:c});const b=w?c:1;Object.assign(p.style,{width:`${u*b}px`,height:`${m*b}px`,transform:w?"none":`scale(${c})`,transformOrigin:"top left",display:S?"none":"block"}),Object.assign(g.style,{width:`${(u??n)*c}px`,height:`${(m??l)*c}px`,overflow:"hidden",display:"block",flexShrink:"0",marginBlock:"auto"}),r&&f!==s&&(g.style.display="none")};this.#t?a(this.#t):(a(e),a(i))}async#g({left:t,right:e,center:i,side:s}){this.#a.replaceChildren(),this.#s=null,this.#n=null,this.#t=null,i?(this.#t=await this.#c(i),this.#h="center",this.#e()):(this.#s=await this.#c(t),this.#n=await this.#c(e),this.#h=this.#s.blank?"right":this.#n.blank?"left":s,this.#e())}#p(){var t,e,i,s;if(!(this.#t||(t=this.#s)!=null&&t.blank)&&this.#l&&((s=(i=(e=this.#s)==null?void 0:e.element)==null?void 0:i.style)==null?void 0:s.display)==="none")return this.#h="left",this.#e(),this.#d("page"),!0}#u(){var t,e,i,s;if(!(this.#t||(t=this.#n)!=null&&t.blank)&&this.#l&&((s=(i=(e=this.#n)==null?void 0:e.element)==null?void 0:i.style)==null?void 0:s.display)==="none")return this.#h="right",this.#e(),this.#d("page"),!0}open(t){this.book=t;const{rendition:e}=t;this.spread=e==null?void 0:e.spread,this.defaultViewport=e==null?void 0:e.viewport;const i=t.dir==="rtl",s=!i;this.rtl=i,(e==null?void 0:e.spread)==="none"?this.#i=t.sections.map(o=>({center:o})):this.#i=t.sections.reduce((o,h,r)=>{const n=o[o.length-1],{pageSpread:l}=h,c=()=>{const a={};return o.push(a),a};if(l==="center"){const a=n.left||n.right?c():n;a.center=h}else if(l==="left"){const a=n.center||n.left||s&&r?c():n;a.left=h}else if(l==="right"){const a=n.center||n.right||i&&r?c():n;a.right=h}else s?n.center||n.right?c().left=h:n.left||!r?n.right=h:n.left=h:n.center||n.left?c().right=h:n.right||!r?n.left=h:n.right=h;return o},[{}])}get index(){const t=this.#i[this.#r],e=(t==null?void 0:t.center)??(this.#h==="left"?t.left??t.right:t.right??t.left);return this.book.sections.indexOf(e)}#d(t){this.dispatchEvent(new CustomEvent("relocate",{detail:{reason:t,range:null,index:this.index,fraction:0,size:1}}))}getSpreadOf(t){const e=this.#i;for(let i=0;i<e.length;i++){const{left:s,right:o,center:h}=e[i];if(s===t)return{index:i,side:"left"};if(o===t)return{index:i,side:"right"};if(h===t)return{index:i,side:"center"}}}async goToSpread(t,e,i){var o,h,r,n,l,c;if(t<0||t>this.#i.length-1)return;if(t===this.#r){this.#e(e);return}this.#r=t;const s=this.#i[t];if(s.center){const a=this.book.sections.indexOf(s.center),f=await((h=(o=s.center)==null?void 0:o.load)==null?void 0:h.call(o));await this.#g({center:{index:a,src:f}})}else{const a=this.book.sections.indexOf(s.left),f=this.book.sections.indexOf(s.right),g=await((n=(r=s.left)==null?void 0:r.load)==null?void 0:n.call(r)),p=await((c=(l=s.right)==null?void 0:l.load)==null?void 0:c.call(l)),u={index:a,src:g},m={index:f,src:p};await this.#g({left:u,right:m,side:e})}this.#d(i)}async select(t){await this.goTo(t)}async goTo(t){const{book:e}=this,i=await t,s=e.sections[i.index];if(!s)return;const{index:o,side:h}=this.getSpreadOf(s);await this.goToSpread(o,h)}async next(){if(!(this.rtl?this.#p():this.#u()))return this.goToSpread(this.#r+1,this.rtl?"right":"left","page")}async prev(){if(!(this.rtl?this.#u():this.#p()))return this.goToSpread(this.#r-1,this.rtl?"left":"right","page")}getContents(){return Array.from(this.#a.querySelectorAll("iframe"),t=>({doc:t.contentDocument}))}destroy(){this.#f.unobserve(this)}}customElements.define("foliate-fxl",x);export{x as FixedLayout};
@@ -0,0 +1,38 @@
1
+ import{toRefs as de,ref as Q,watch as bc,onMounted as vc,openBlock as z,createElementBlock as B,createElementVNode as O,withDirectives as wc,vShow as xc,renderSlot as pe,createCommentVNode as xt,defineComponent as Ec,getCurrentInstance as Tc,h as Sc,Transition as Ac,reactive as kc,normalizeClass as er,unref as tt,normalizeStyle as Cc,toDisplayString as Oc,createVNode as nr,mergeProps as Pc,withCtx as Lc}from"vue";let ge,rr,me,or,$,ir,Fc=(async()=>{let ye,Et,be,et,_,Tt,St,ve,we,xe,Ee,At,Te,kt,Se,Ct,D,L,Ae,nt,W,Ot,rt,ot,V,ke,Pt,Ce,Lt;ye=(e,t)=>e.map((n,r,o)=>t(n,r,o)?r:null).filter(n=>n!=null),Et=(e,t)=>[-1,...t,e.length].reduce(({xs:n,a:r},o)=>({xs:(n==null?void 0:n.concat([e.slice(r+1,o)]))??[],a:o}),{}).xs,be=(e,t)=>e.slice(0,-1).concat([e[e.length-1].concat(t[0])]).concat(t.slice(1)),et=/\d/,_=/^epubcfi\((.*)\)$/,Tt=e=>e.replace(/[\^[\](),;=]/g,"^$&"),St=e=>_.test(e)?e:`epubcfi(${e})`,ve=e=>{var t;return((t=e.match(_))==null?void 0:t[1])??e},we=e=>(...t)=>`epubcfi(${e(...t.map(n=>{var r;return((r=n.match(_))==null?void 0:r[1])??n}))})`,xe=we((...e)=>e.join("!")),Ee=e=>{const t=[];let n,r,o="";const i=s=>(t.push(s),n=null,o=""),a=s=>(o+=s,r=!1);for(const s of Array.from(e.trim()).concat("")){if(s==="^"&&!r){r=!0;continue}if(n==="!")i(["!"]);else if(n===",")i([","]);else if(n==="/"||n===":")if(et.test(s)){a(s);continue}else i([n,parseInt(o)]);else if(n==="~")if(et.test(s)||s==="."){a(s);continue}else i(["~",parseFloat(o)]);else if(n==="@"){if(s===":"){i(["@",parseFloat(o)]),n="@";continue}if(et.test(s)||s==="."){a(s);continue}else i(["@",parseFloat(o)])}else if(n==="["){s===";"&&!r?(i(["[",o]),n=";"):s===","&&!r?(i(["[",o]),n="["):s==="]"&&!r?i(["[",o]):a(s);continue}else if(n!=null&&n.startsWith(";")){s==="="&&!r?(n=`;${o}`,o=""):s===";"&&!r?(i([n,o]),n=";"):s==="]"&&!r?i([n,o]):a(s);continue}(s==="/"||s===":"||s==="~"||s==="@"||s==="["||s==="!"||s===",")&&(n=s)}return t},At=(e,t)=>ye(e,([n])=>n===t),Te=e=>{const t=[];let n;for(const[r,o]of e){if(r==="/")t.push({index:o});else{const i=t[t.length-1];if(r===":")i.offset=o;else if(r==="~")i.temporal=o;else if(r==="@")i.spatial=(i.spatial??[]).concat(o);else if(r===";s")i.side=o;else if(r==="[")if(n==="/"&&o)i.id=o;else{i.text=(i.text??[]).concat(o);continue}}n=r}return t},kt=e=>Et(e,At(e,"!")).map(Te),$=e=>{const t=Ee(ve(e)),n=At(t,",");if(!n.length)return kt(t);const[r,o,i]=Et(t,n).map(kt);return{parent:r,start:o,end:i}},Se=({index:e,id:t,offset:n,temporal:r,spatial:o,text:i,side:a})=>{var l;const s=a?`;s=${a}`:"";return`/${e}`+(t?`[${Tt(t)}${s}]`:"")+(n!=null&&e%2?`:${n}`:"")+(r?`~${r}`:"")+(o?`@${o.join(":")}`:"")+(i||!t&&a?"["+(((l=i==null?void 0:i.map(Tt))==null?void 0:l.join(","))??"")+s+"]":"")},Ct=e=>e.parent?[e.parent,e.start,e.end].map(Ct).join(","):e.map(t=>t.map(Se).join("")).join("!"),D=e=>St(Ct(e)),L=(e,t)=>typeof e=="string"?D(L($(e),t)):e.parent?be(e.parent,e[t?"end":"start"]):e,Ae=(e,t)=>{typeof e=="string"&&(e=$(e)),typeof t=="string"&&(t=$(t)),e=L(e),t=L(t,!0);const n=e[e.length-1],r=t[t.length-1],o=[],i=[],a=[];let s=!0;const l=Math.max(n.length,r.length);for(let u=0;u<l;u++){const h=n[u],f=r[u];s&&=(h==null?void 0:h.index)===(f==null?void 0:f.index)&&!(h!=null&&h.offset)&&!(f!=null&&f.offset),s?o.push(h):(h&&i.push(h),f&&a.push(f))}const c=e.slice(0,-1).concat([o]);return D({parent:c,start:[i],end:[a]})},nt=({nodeType:e})=>e===3||e===4,W=({nodeType:e})=>e===1,Ot=(e,t)=>{const n=Array.from(e.childNodes).filter(r=>nt(r)||W(r));return t?n.map(r=>{const o=t(r);return o===NodeFilter.FILTER_REJECT?null:o===NodeFilter.FILTER_SKIP?Ot(r,t):r}).flat().filter(r=>r):n},rt=(e,t)=>{const n=Ot(e,t).reduce((r,o)=>{let i=r[r.length-1];return i?nt(o)?Array.isArray(i)?i.push(o):nt(i)?r[r.length-1]=[i,o]:r.push(o):W(i)?r.push(null,o):r.push(o):r.push(o),r},[]);return W(n[0])&&n.unshift("first"),W(n[n.length-1])&&n.push("last"),n.unshift("before"),n.push("after"),n},ot=(e,t,n)=>{const{id:r}=t[t.length-1];if(r){const a=e.ownerDocument.getElementById(r);if(a)return{node:a,offset:0}}for(const{index:a}of t){const s=e?rt(e,n)[a]:null;if(s==="first")return{node:e.firstChild??e};if(s==="last")return{node:e.lastChild??e};if(s==="before")return{node:e,before:!0};if(s==="after")return{node:e,after:!0};e=s}const{offset:o}=t[t.length-1];if(!Array.isArray(e))return{node:e,offset:o};let i=0;for(const a of e){const{length:s}=a.nodeValue;if(i+s>=o)return{node:a,offset:o-i};i+=s}},V=(e,t,n)=>{const{parentNode:r,id:o}=e,i=rt(r,n),a=i.findIndex(c=>Array.isArray(c)?c.some(u=>u===e):c===e),s=i[a];if(Array.isArray(s)){let c=0;for(const u of s)if(u===e){c+=t;break}else c+=u.nodeValue.length;t=c}const l={id:o,index:a,offset:t};return(r!==e.ownerDocument.documentElement?V(r,null,n).concat(l):[l]).filter(c=>c.index!==-1)},ke=(e,t)=>{const{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=e,a=V(n,r,t);if(e.collapsed)return D([a]);const s=V(o,i,t);return Ae([a],[s])},me=(e,t,n)=>{const r=L(t),o=L(t,!0),i=e.documentElement,a=ot(i,r[0],n),s=ot(i,o[0],n),l=e.createRange();return a.before?l.setStartBefore(a.node):a.after?l.setStartAfter(a.node):l.setStart(a.node,a.offset),s.before?l.setEndBefore(s.node):s.after?l.setEndAfter(s.node):l.setEnd(s.node,s.offset),l},or=e=>{const t=[],{parentNode:n}=e[0],r=V(n);for(const[o,i]of rt(n).entries()){const a=e[t.length];i===a&&t.push(D([r.concat({id:a.id,index:o})]))}return t},ir=(e,t)=>ot(e.documentElement,L(t)).node,Pt={fromIndex:e=>St(`/6/${(e+1)*2}`),toIndex:e=>(e==null?void 0:e.at(-1).index)/2-1},Ce=e=>{let t=0;const n=r=>{if(r.id=t++,r.subitems)for(const o of r.subitems)n(o)};for(const r of e)n(r);return e},Lt=e=>e.map(t=>{var n;return(n=t.subitems)!=null&&n.length?[t,Lt(t.subitems)].flat():t}).flat();class Oe{async init({toc:t,ids:n,splitHref:r,getFragment:o}){Ce(t);const i=Lt(t),a=new Map;for(const[l,c]of i.entries()){const[u,h]=await r(c==null?void 0:c.href)??[],f={fragment:h,item:c};a.has(u)?a.get(u).items.push(f):a.set(u,{prev:i[l-1],items:[f]})}const s=new Map;for(const[l,c]of n.entries())a.has(c)?s.set(c,a.get(c)):s.set(c,s.get(n[l-1]));this.ids=n,this.map=s,this.getFragment=o}getProgress(t,n){var l;if(!this.ids)return;const r=this.ids[t],o=this.map.get(r);if(!o)return null;const{prev:i,items:a}=o;if(!a)return i;if(!n||a.length===1&&!a[0].fragment)return a[0].item;const s=n.startContainer.getRootNode();for(const[c,{fragment:u}]of a.entries()){const h=this.getFragment(s,u);if(h&&n.comparePoint(h,0)>0)return((l=a[c-1])==null?void 0:l.item)??i}return a[a.length-1].item}}class sr{constructor(t,n,r){this.sizes=t.map(o=>o.linear!="no"&&o.size>0?o.size:0),this.sizePerLoc=n,this.sizePerTimeUnit=r,this.sizeTotal=this.sizes.reduce((o,i)=>o+i,0),this.sectionFractions=this.#e()}#e(){const{sizeTotal:t}=this,n=[0];let r=0;for(const o of this.sizes)n.push((r+=o)/t);return n}getProgress(t,n,r=0){const{sizes:o,sizePerLoc:i,sizePerTimeUnit:a,sizeTotal:s}=this,l=o[t]??0,c=o.slice(0,t).reduce((p,b)=>p+b,0)+n*l,u=c+r*l,h=s-c,f=(1-n)*l;return{fraction:u/s,section:{current:t,total:o.length},location:{current:Math.floor(c/i),next:Math.floor(u/i),total:Math.ceil(s/i)},time:{section:f/a,total:h/a}}}getSection(t){if(t<=0)return[0,0];if(t>=1)return[this.sizes.length-1,1];t=t+Number.EPSILON;const{sizeTotal:n}=this;let r=this.sectionFractions.findIndex(i=>i>t)-1;if(r<0)return[0,0];for(;!this.sizes[r];)r++;const o=(t-this.sectionFractions[r])/(this.sizes[r]/n);return[r,o]}}const v=e=>document.createElementNS("http://www.w3.org/2000/svg",e);class Pe{#e=v("svg");#t=new Map;constructor(){Object.assign(this.#e.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",pointerEvents:"none"})}get element(){return this.#e}add(t,n,r,o){this.#t.has(t)&&this.remove(t),typeof n=="function"&&(n=n(this.#e.getRootNode()));const i=n.getClientRects(),a=r(i,o);this.#e.append(a),this.#t.set(t,{range:n,draw:r,options:o,element:a,rects:i})}remove(t){this.#t.has(t)&&(this.#e.removeChild(this.#t.get(t).element),this.#t.delete(t))}redraw(){for(const t of this.#t.values()){const{range:n,draw:r,options:o,element:i}=t;this.#e.removeChild(i);const a=n.getClientRects(),s=r(a,o);this.#e.append(s),t.element=s,t.rects=a}}hitTest({x:t,y:n}){const r=Array.from(this.#t.entries());for(let o=r.length-1;o>=0;o--){const[i,a]=r[o];for(const{left:s,top:l,right:c,bottom:u}of a.rects)if(l<=n&&s<=t&&u>n&&c>t)return[i,a.range]}return[]}static underline(t,n={}){const{color:r="red",width:o=2,writingMode:i}=n,a=v("g");if(a.setAttribute("fill",r),i==="vertical-rl"||i==="vertical-lr")for(const{right:s,top:l,height:c}of t){const u=v("rect");u.setAttribute("x",s-o),u.setAttribute("y",l),u.setAttribute("height",c),u.setAttribute("width",o),a.append(u)}else for(const{left:s,bottom:l,width:c}of t){const u=v("rect");u.setAttribute("x",s),u.setAttribute("y",l-o),u.setAttribute("height",o),u.setAttribute("width",c),a.append(u)}return a}static strikethrough(t,n={}){const{color:r="red",width:o=2,writingMode:i}=n,a=v("g");if(a.setAttribute("fill",r),i==="vertical-rl"||i==="vertical-lr")for(const{right:s,left:l,top:c,height:u}of t){const h=v("rect");h.setAttribute("x",(s+l)/2),h.setAttribute("y",c),h.setAttribute("height",u),h.setAttribute("width",o),a.append(h)}else for(const{left:s,top:l,bottom:c,width:u}of t){const h=v("rect");h.setAttribute("x",s),h.setAttribute("y",(l+c)/2),h.setAttribute("height",o),h.setAttribute("width",u),a.append(h)}return a}static squiggly(t,n={}){const{color:r="red",width:o=2,writingMode:i}=n,a=v("g");a.setAttribute("fill","none"),a.setAttribute("stroke",r),a.setAttribute("stroke-width",o);const s=o*1.5;if(i==="vertical-rl"||i==="vertical-lr")for(const{right:l,top:c,height:u}of t){const h=v("path"),f=Math.round(u/s/1.5),p=u/f,b=Array.from({length:f},(x,d)=>`l${d%2?-s:s} ${p}`).join("");h.setAttribute("d",`M${l} ${c}${b}`),a.append(h)}else for(const{left:l,bottom:c,width:u}of t){const h=v("path"),f=Math.round(u/s/1.5),p=u/f,b=Array.from({length:f},(x,d)=>`l${p} ${d%2?s:-s}`).join("");h.setAttribute("d",`M${l} ${c}${b}`),a.append(h)}return a}static highlight(t,n={}){const{color:r="red"}=n,o=v("g");o.setAttribute("fill",r),o.style.opacity="var(--overlayer-highlight-opacity, .3)",o.style.mixBlendMode="var(--overlayer-highlight-blend-mode, normal)";for(const{left:i,top:a,height:s,width:l}of t){const c=v("rect");c.setAttribute("x",i),c.setAttribute("y",a),c.setAttribute("height",s),c.setAttribute("width",l),o.append(c)}return o}static outline(t,n={}){const{color:r="red",width:o=3,radius:i=3}=n,a=v("g");a.setAttribute("fill","none"),a.setAttribute("stroke",r),a.setAttribute("stroke-width",o);for(const{left:s,top:l,height:c,width:u}of t){const h=v("rect");h.setAttribute("x",s),h.setAttribute("y",l),h.setAttribute("height",c),h.setAttribute("width",u),h.setAttribute("rx",i),a.append(h)}return a}static copyImage([t],n={}){const{src:r}=n,o=v("image"),{left:i,top:a,height:s,width:l}=t;return o.setAttribute("href",r),o.setAttribute("x",i),o.setAttribute("y",a),o.setAttribute("height",s),o.setAttribute("width",l),o}}const ar=(e,t)=>{const n=[];for(let r=t.currentNode;r;r=t.nextNode()){const o=e.comparePoint(r,0);if(o===0)n.push(r);else if(o>0)break}return n},cr=(e,t)=>{const n=[];for(let r=t.nextNode();r;r=t.nextNode())n.push(r);return n},lr=NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT|NodeFilter.SHOW_CDATA_SECTION,ur=e=>{if(e.nodeType===1){const t=e.tagName.toLowerCase();return t==="script"||t==="style"?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_SKIP}return NodeFilter.FILTER_ACCEPT},Le=function*(e,t,n){const r=e.commonAncestorContainer??e.body??e,o=document.createTreeWalker(r,lr,{acceptNode:n||ur}),i=(e.commonAncestorContainer?ar:cr)(e,o),a=i.map(l=>l.nodeValue),s=(l,c,u,h)=>{const f=document.createRange();return f.setStart(i[l],c),f.setEnd(i[u],h),f};for(const l of t(a,s))yield l},H="foliate-search:",hr=async e=>{const t=new Uint8Array(await e.slice(0,4).arrayBuffer());return t[0]===80&&t[1]===75&&t[2]===3&&t[3]===4},fr=async e=>{const t=new Uint8Array(await e.slice(0,5).arrayBuffer());return t[0]===37&&t[1]===80&&t[2]===68&&t[3]===70&&t[4]===45},dr=({name:e,type:t})=>t==="application/vnd.comicbook+zip"||e.endsWith(".cbz"),pr=({name:e,type:t})=>t==="application/x-fictionbook+xml"||e.endsWith(".fb2"),gr=({name:e,type:t})=>t==="application/x-zip-compressed-fb2"||e.endsWith(".fb2.zip")||e.endsWith(".fbz"),mr=async e=>{const{configure:t,ZipReader:n,BlobReader:r,TextWriter:o,BlobWriter:i}=await import("./zip-eoP6P7MM.js");t({useWebWorkers:!1});const a=await new n(new r(e)).getEntries(),s=new Map(a.map(h=>[h.filename,h])),l=h=>(f,...p)=>s.has(f)?h(s.get(f),...p):null,c=l(h=>h.getData(new o)),u=l((h,f)=>h.getData(new i(f)));return{entries:a,loadText:c,loadBlob:u,getSize:h=>{var f;return((f=s.get(h))==null?void 0:f.uncompressedSize)??0}}},Fe=async e=>e.isFile?e:(await Promise.all(Array.from(await new Promise((t,n)=>e.createReader().readEntries(r=>t(r),r=>n(r))),Fe))).flat(),yr=async e=>{const t=await Fe(e),n=await Promise.all(t.map(s=>new Promise((l,c)=>s.file(u=>l([u,s.fullPath]),u=>c(u))))),r=new Map(n.map(([s,l])=>[l.replace(e.fullPath+"/",""),s])),o=new TextDecoder,i=s=>s?o.decode(s):null,a=s=>{var l;return((l=r.get(s))==null?void 0:l.arrayBuffer())??null};return{loadText:async s=>i(await a(s)),loadBlob:s=>r.get(s),getSize:s=>{var l;return((l=r.get(s))==null?void 0:l.size)??0}}};class br extends Error{}class vr extends Error{}class wr extends Error{}const xr=async e=>{const t=await fetch(e);if(!t.ok)throw new br(`${t.status} ${t.statusText}`,{cause:t});return new File([await t.blob()],new URL(t.url).pathname)},Er=async e=>{typeof e=="string"&&(e=await xr(e));let t;if(e.isDirectory){const n=await yr(e),{EPUB:r}=await import("./epub-CsHwZdaW.js");t=await new r(n).init()}else if(e.size)if(await hr(e)){const n=await mr(e);if(dr(e)){const{makeComicBook:r}=await import("./comic-book-COtMh0BD.js");t=r(n,e)}else if(gr(e)){const{makeFB2:r}=await import("./fb2-BRzs6sg2.js"),{entries:o}=n,i=o.find(s=>s.filename.endsWith(".fb2")),a=await n.loadBlob((i??o[0]).filename);t=await r(a)}else{const{EPUB:r}=await import("./epub-CsHwZdaW.js");t=await new r(n).init()}}else if(await fr(e)){const{makePDF:n}=await import("./pdf-B2ALGNHl.js").then(async r=>(await r.__tla,r));t=await n(e)}else{const{isMOBI:n,MOBI:r}=await import("./mobi-c0I-fyTR.js");if(await n(e)){const o=await import("./fflate-x0QqQh-3.js");t=await new r({unzlib:o.unzlibSync}).open(e)}else if(pr(e)){const{makeFB2:o}=await import("./fb2-BRzs6sg2.js");t=await o(e)}}else throw new vr("File not found");if(!t)throw new wr("File type not supported");return t};class Ft{#e;#t;#r;#n;constructor(t,n,r={}){this.#t=t,this.#r=n,this.#n=r,this.#n.hidden&&this.hide(),this.#t.addEventListener("mousemove",({screenX:o,screenY:i})=>{o===this.#n.x&&i===this.#n.y||(this.#n.x=o,this.#n.y=i,this.show(),this.#e&&clearTimeout(this.#e),n()&&(this.#e=setTimeout(this.hide.bind(this),1e3)))},!1)}cloneFor(t){return new Ft(t,this.#r,this.#n)}hide(){this.#t.style.cursor="none",this.#n.hidden=!0}show(){this.#t.style.removeProperty("cursor"),this.#n.hidden=!1}}class Tr extends EventTarget{#e=[];#t=-1;pushState(t){const n=this.#e[this.#t];n===t||n!=null&&n.fraction&&n.fraction===t.fraction||(this.#e[++this.#t]=t,this.#e.length=this.#t+1,this.dispatchEvent(new Event("index-change")))}replaceState(t){const n=this.#t;this.#e[n]=t}back(){const t=this.#t;if(t<=0)return;const n={state:this.#e[t-1]};this.#t=t-1,this.dispatchEvent(new CustomEvent("popstate",{detail:n})),this.dispatchEvent(new Event("index-change"))}forward(){const t=this.#t;if(t>=this.#e.length-1)return;const n={state:this.#e[t+1]};this.#t=t+1,this.dispatchEvent(new CustomEvent("popstate",{detail:n})),this.dispatchEvent(new Event("index-change"))}get canGoBack(){return this.#t>0}get canGoForward(){return this.#t<this.#e.length-1}clear(){this.#e=[],this.#t=-1}}const Sr=e=>{var t,n;if(!e)return{};try{const r=Intl.getCanonicalLocales(e)[0],o=new Intl.Locale(r),i=["zh","ja","kr"].includes(o.language),a=(n=((t=o.getTextInfo)==null?void 0:t.call(o))??o.textInfo)==null?void 0:n.direction;return{canonical:r,locale:o,isCJK:i,direction:a}}catch(r){return console.warn(r),{}}};class Ar extends HTMLElement{#e=this.attachShadow({mode:"closed"});#t;#r;#n;#i=new Map;#a=new Ft(this,()=>this.hasAttribute("autohide-cursor"));isFixedLayout=!1;lastLocation;history=new Tr;constructor(){super(),this.history.addEventListener("popstate",({detail:t})=>{const n=this.resolveNavigation(t.state);this.renderer.goTo(n)})}async open(t){var n,r;if((typeof t=="string"||typeof t.arrayBuffer=="function"||t.isDirectory)&&(t=await Er(t)),this.book=t,this.language=Sr((n=t.metadata)==null?void 0:n.language),t.splitTOCHref&&t.getTOCFragment){const o=t.sections.map(s=>s.id);this.#t=new sr(t.sections,1500,1600);const i=t.splitTOCHref.bind(t),a=t.getTOCFragment.bind(t);this.#r=new Oe,await this.#r.init({toc:t.toc??[],ids:o,splitHref:i,getFragment:a}),this.#n=new Oe,await this.#n.init({toc:t.pageList??[],ids:o,splitHref:i,getFragment:a})}if(this.isFixedLayout=((r=this.book.rendition)==null?void 0:r.layout)==="pre-paginated",this.isFixedLayout?(await import("./fixed-layout-C5HoOcVm.js"),this.renderer=document.createElement("foliate-fxl")):(await import("./paginator-DA7VmVNy.js"),this.renderer=document.createElement("foliate-paginator")),this.renderer.setAttribute("exportparts","head,foot,filter"),this.renderer.addEventListener("load",o=>this.#l(o.detail)),this.renderer.addEventListener("relocate",o=>this.#c(o.detail)),this.renderer.addEventListener("create-overlayer",o=>o.detail.attach(this.#h(o.detail))),this.renderer.open(t),this.#e.append(this.renderer),t.sections.some(o=>o.mediaOverlay)){const o=t.media.activeClass,i=t.media.playbackActiveClass;this.mediaOverlay=t.getMediaOverlay();let a;this.mediaOverlay.addEventListener("highlight",s=>{const l=this.resolveNavigation(s.detail.text);this.renderer.goTo(l).then(()=>{const{doc:c}=this.renderer.getContents().find(h=>h.index=l.index),u=l.anchor(c);u.classList.add(o),i&&u.ownerDocument.documentElement.classList.add(i),a=new WeakRef(u)})}),this.mediaOverlay.addEventListener("unhighlight",()=>{const s=a==null?void 0:a.deref();s&&(s.classList.remove(o),i&&s.ownerDocument.documentElement.classList.remove(i))})}}close(){var t,n;(t=this.renderer)==null||t.destroy(),(n=this.renderer)==null||n.remove(),this.#t=null,this.#r=null,this.#n=null,this.#i=new Map,this.lastLocation=null,this.history.clear(),this.tts=null,this.mediaOverlay=null}goToTextStart(){var t,n;return this.goTo(((n=(t=this.book.landmarks)==null?void 0:t.find(r=>r.type.includes("bodymatter")||r.type.includes("text")))==null?void 0:n.href)??this.book.sections.findIndex(r=>r.linear!=="no"))}async init({lastLocation:t,showTextStart:n}){const r=t?this.resolveNavigation(t):null;r?(await this.renderer.goTo(r),this.history.pushState(t)):n?await this.goToTextStart():(this.history.pushState(0),await this.next())}#o(t,n,r){return this.dispatchEvent(new CustomEvent(t,{detail:n,cancelable:r}))}#c({reason:t,range:n,index:r,fraction:o,size:i}){var u,h,f;const a=((u=this.#t)==null?void 0:u.getProgress(r,o,i))??{},s=(h=this.#r)==null?void 0:h.getProgress(r,n),l=(f=this.#n)==null?void 0:f.getProgress(r,n),c=this.getCFI(r,n);this.lastLocation={...a,tocItem:s,pageItem:l,cfi:c,range:n},(t==="snap"||t==="page"||t==="scroll")&&this.history.replaceState(c),this.#o("relocate",this.lastLocation)}#l({doc:t,index:n}){t.documentElement.lang||=this.language.canonical??"",this.language.isCJK||(t.documentElement.dir||=this.language.direction??""),this.#u(t,n),this.#a.cloneFor(t.documentElement),this.#o("load",{doc:t,index:n})}#u(t,n){const{book:r}=this,o=r.sections[n];t.addEventListener("click",i=>{var c,u;const a=i.target.closest("a[href]");if(!a)return;i.preventDefault();const s=a.getAttribute("href"),l=((c=o==null?void 0:o.resolveHref)==null?void 0:c.call(o,s))??s;(u=r==null?void 0:r.isExternal)!=null&&u.call(r,l)?Promise.resolve(this.#o("external-link",{a,href:l},!0)).then(h=>h?globalThis.open(l,"_blank"):null).catch(h=>console.error(h)):Promise.resolve(this.#o("link",{a,href:l},!0)).then(h=>h?this.goTo(l):null).catch(h=>console.error(h))})}async addAnnotation(t,n){var l;const{value:r}=t;if(r.startsWith(H)){const c=r.replace(H,""),{index:u,anchor:h}=await this.resolveNavigation(c),f=this.#s(u);if(f){const{overlayer:p,doc:b}=f;if(n){p.remove(r);return}const x=b?h(b):h;p.add(r,x,Pe.outline)}return}const{index:o,anchor:i}=await this.resolveNavigation(r),a=this.#s(o);if(a){const{overlayer:c,doc:u}=a;if(c.remove(r),!n){const h=u?i(u):i,f=(p,b)=>c.add(r,h,p,b);this.#o("draw-annotation",{draw:f,annotation:t,doc:u,range:h})}}const s=((l=this.#r.getProgress(o))==null?void 0:l.label)??"";return{index:o,label:s}}deleteAnnotation(t){return this.addAnnotation(t,!0)}#s(t){return this.renderer.getContents().find(n=>n.index===t&&n.overlayer)}#h({doc:t,index:n}){const r=new Pe;t.addEventListener("click",i=>{const[a,s]=r.hitTest(i);a&&!a.startsWith(H)&&this.#o("show-annotation",{value:a,index:n,range:s})},!1);const o=this.#i.get(n);if(o)for(const i of o)this.addAnnotation(i);return this.#o("create-overlay",{index:n}),r}async showAnnotation(t){const{value:n}=t,r=await this.goTo(n);if(r){const{index:o,anchor:i}=r,{doc:a}=this.#s(o),s=i(a);this.#o("show-annotation",{value:n,index:o,range:s})}}getCFI(t,n){const r=this.book.sections[t].cfi??Pt.fromIndex(t);return n?xe(r,ke(n)):r}resolveCFI(t){if(this.book.resolveCFI)return this.book.resolveCFI(t);{const n=$(t);return{index:Pt.toIndex((n.parent??n).shift()),anchor:r=>me(r,n)}}}resolveNavigation(t){try{if(typeof t=="number")return{index:t};if(typeof t.fraction=="number"){const[n,r]=this.#t.getSection(t.fraction);return{index:n,anchor:r}}return _.test(t)?this.resolveCFI(t):this.book.resolveHref(t)}catch(n){console.error(n),console.error(`Could not resolve target ${t}`)}}async goTo(t){const n=this.resolveNavigation(t);try{return await this.renderer.goTo(n),this.history.pushState(t),n}catch(r){console.error(r),console.error(`Could not go to ${t}`)}}async goToFraction(t){const[n,r]=this.#t.getSection(t);await this.renderer.goTo({index:n,anchor:r}),this.history.pushState({fraction:t})}async select(t){try{const n=await this.resolveNavigation(t);await this.renderer.goTo({...n,select:!0}),this.history.pushState(t)}catch(n){console.error(n),console.error(`Could not go to ${t}`)}}deselect(){for(const{doc:t}of this.renderer.getContents())t.defaultView.getSelection().removeAllRanges()}getSectionFractions(){var t;return(((t=this.#t)==null?void 0:t.sectionFractions)??[]).map(n=>n+Number.EPSILON)}getProgressOf(t,n){var i,a;const r=(i=this.#r)==null?void 0:i.getProgress(t,n),o=(a=this.#n)==null?void 0:a.getProgress(t,n);return{tocItem:r,pageItem:o}}async getTOCItemOf(t){try{const{index:n,anchor:r}=await this.resolveNavigation(t),o=await this.book.sections[n].createDocument(),i=r(o),a=i instanceof Range,s=a?i:o.createRange();return a||s.selectNodeContents(i),this.#r.getProgress(n,s)}catch(n){console.error(n),console.error(`Could not get ${t}`)}}async prev(t){await this.renderer.prev(t)}async next(t){await this.renderer.next(t)}goLeft(){return this.book.dir==="rtl"?this.next():this.prev()}goRight(){return this.book.dir==="rtl"?this.prev():this.next()}async*#f(t,n,r){const o=await this.book.sections[r].createDocument();for(const{range:i,excerpt:a}of t(o,n))yield{cfi:this.getCFI(r,i),excerpt:a}}async*#d(t,n){const{sections:r}=this.book;for(const[o,{createDocument:i}]of r.entries()){if(!i)continue;const a=await i(),s=Array.from(t(a,n),({range:l,excerpt:c})=>({cfi:this.getCFI(o,l),excerpt:c}));yield{progress:(o+1)/r.length},s.length&&(yield{index:o,subitems:s})}}async*search(t){var l;this.clearSearch();const{searchMatcher:n}=await import("./search-DvSJ-YTA.js"),{query:r,index:o}=t,i=n(Le,{defaultLocale:this.language,...t}),a=o!=null?this.#f(i,r,o):this.#d(i,r),s=[];this.#i.set(o,s);for await(const c of a)if(c.subitems){const u=c.subitems.map(({cfi:h})=>({value:H+h}));this.#i.set(c.index,u);for(const h of u)this.addAnnotation(h);yield{label:((l=this.#r.getProgress(c.index))==null?void 0:l.label)??"",subitems:c.subitems}}else{if(c.cfi){const u={value:H+c.cfi};s.push(u),this.addAnnotation(u)}yield c}yield"done"}clearSearch(){for(const t of this.#i.values())for(const n of t)this.deleteAnnotation(n);this.#i.clear()}async initTTS(t="word",n){const r=this.renderer.getContents()[0].doc;if(this.tts&&this.tts.doc===r)return;const{TTS:o}=await import("./tts-58gjxLCO.js");this.tts=new o(r,Le,n||(i=>this.renderer.scrollToAnchor(i,!0)),t)}startMediaOverlay(){const{index:t}=this.renderer.getContents()[0];return this.mediaOverlay.start(t)}}customElements.define("foliate-view",Ar);var it=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},U=function(e){return e&&e.Math===Math&&e},E=U(typeof globalThis=="object"&&globalThis)||U(typeof window=="object"&&window)||U(typeof self=="object"&&self)||U(typeof it=="object"&&it)||U(typeof it=="object"&&it)||function(){return this}()||Function("return this")(),jt={},k=function(e){try{return!!e()}catch{return!0}},kr=k,F=!kr(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),Cr=k,Nt=!Cr(function(){var e=(function(){}).bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),Or=Nt,st=Function.prototype.call,M=Or?st.bind(st):function(){return st.apply(st,arguments)},je={},Ne={}.propertyIsEnumerable,Me=Object.getOwnPropertyDescriptor,Pr=Me&&!Ne.call({1:2},1);je.f=Pr?function(e){var t=Me(this,e);return!!t&&t.enumerable}:Ne;var Ie=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}},Re=Nt,ze=Function.prototype,Mt=ze.call,Lr=Re&&ze.bind.bind(Mt,Mt),w=Re?Lr:function(e){return function(){return Mt.apply(e,arguments)}},Be=w,Fr=Be({}.toString),jr=Be("".slice),It=function(e){return jr(Fr(e),8,-1)},Nr=w,Mr=k,Ir=It,Rt=Object,Rr=Nr("".split),zr=Mr(function(){return!Rt("z").propertyIsEnumerable(0)})?function(e){return Ir(e)==="String"?Rr(e,""):Rt(e)}:Rt,zt=function(e){return e==null},Br=zt,$r=TypeError,at=function(e){if(Br(e))throw new $r("Can't call method on "+e);return e},_r=zr,Dr=at,Bt=function(e){return _r(Dr(e))},$t=typeof document=="object"&&document.all,T=typeof $t>"u"&&$t!==void 0?function(e){return typeof e=="function"||e===$t}:function(e){return typeof e=="function"},Wr=T,q=function(e){return typeof e=="object"?e!==null:Wr(e)},_t=E,Vr=T,Hr=function(e){return Vr(e)?e:void 0},Dt=function(e,t){return arguments.length<2?Hr(_t[e]):_t[e]&&_t[e][t]},Ur=w,$e=Ur({}.isPrototypeOf),qr=E,_e=qr.navigator,De=_e&&_e.userAgent,Yr=De?String(De):"",We=E,Wt=Yr,Ve=We.process,He=We.Deno,Ue=Ve&&Ve.versions||He&&He.version,qe=Ue&&Ue.v8,S,ct;qe&&(S=qe.split("."),ct=S[0]>0&&S[0]<4?1:+(S[0]+S[1])),!ct&&Wt&&(S=Wt.match(/Edge\/(\d+)/),(!S||S[1]>=74)&&(S=Wt.match(/Chrome\/(\d+)/),S&&(ct=+S[1])));var Gr=ct,Ye=Gr,Kr=k,Jr=E,Xr=Jr.String,Ge=!!Object.getOwnPropertySymbols&&!Kr(function(){var e=Symbol("symbol detection");return!Xr(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Ye&&Ye<41}),Zr=Ge,Ke=Zr&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Qr=Dt,to=T,eo=$e,no=Ke,ro=Object,Je=no?function(e){return typeof e=="symbol"}:function(e){var t=Qr("Symbol");return to(t)&&eo(t.prototype,ro(e))},oo=String,Vt=function(e){try{return oo(e)}catch{return"Object"}},io=T,so=Vt,ao=TypeError,Y=function(e){if(io(e))return e;throw new ao(so(e)+" is not a function")},co=Y,lo=zt,Ht=function(e,t){var n=e[t];return lo(n)?void 0:co(n)},Ut=M,qt=T,Yt=q,uo=TypeError,ho=function(e,t){var n,r;if(t==="string"&&qt(n=e.toString)&&!Yt(r=Ut(n,e))||qt(n=e.valueOf)&&!Yt(r=Ut(n,e))||t!=="string"&&qt(n=e.toString)&&!Yt(r=Ut(n,e)))return r;throw new uo("Can't convert object to primitive value")},Xe={exports:{}},Ze=E,fo=Object.defineProperty,Gt=function(e,t){try{fo(Ze,e,{value:t,configurable:!0,writable:!0})}catch{Ze[e]=t}return t},po=E,go=Gt,Qe="__core-js_shared__",tn=Xe.exports=po[Qe]||go(Qe,{});(tn.versions||(tn.versions=[])).push({version:"3.45.1",mode:"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.45.1/LICENSE",source:"https://github.com/zloirock/core-js"});var Kt=Xe.exports,en=Kt,nn=function(e,t){return en[e]||(en[e]=t||{})},mo=at,yo=Object,bo=function(e){return yo(mo(e))},vo=w,wo=bo,xo=vo({}.hasOwnProperty),j=Object.hasOwn||function(e,t){return xo(wo(e),t)},Eo=w,To=0,So=Math.random(),Ao=Eo(1.1.toString),rn=function(e){return"Symbol("+(e===void 0?"":e)+")_"+Ao(++To+So,36)},ko=E,Co=nn,on=j,Oo=rn,Po=Ge,Lo=Ke,I=ko.Symbol,Jt=Co("wks"),Fo=Lo?I.for||I:I&&I.withoutSetter||Oo,G=function(e){return on(Jt,e)||(Jt[e]=Po&&on(I,e)?I[e]:Fo("Symbol."+e)),Jt[e]},jo=M,sn=q,an=Je,No=Ht,Mo=ho,Io=G,Ro=TypeError,zo=Io("toPrimitive"),Bo=function(e,t){if(!sn(e)||an(e))return e;var n=No(e,zo),r;if(n){if(t===void 0&&(t="default"),r=jo(n,e,t),!sn(r)||an(r))return r;throw new Ro("Can't convert object to primitive value")}return t===void 0&&(t="number"),Mo(e,t)},$o=Bo,_o=Je,Xt=function(e){var t=$o(e,"string");return _o(t)?t:t+""},Do=E,cn=q,Zt=Do.document,Wo=cn(Zt)&&cn(Zt.createElement),Vo=function(e){return Wo?Zt.createElement(e):{}},Ho=F,Uo=k,qo=Vo,ln=!Ho&&!Uo(function(){return Object.defineProperty(qo("div"),"a",{get:function(){return 7}}).a!==7}),Yo=F,Go=M,Ko=je,Jo=Ie,Xo=Bt,Zo=Xt,Qo=j,ti=ln,un=Object.getOwnPropertyDescriptor;jt.f=Yo?un:function(e,t){if(e=Xo(e),t=Zo(t),ti)try{return un(e,t)}catch{}if(Qo(e,t))return Jo(!Go(Ko.f,e,t),e[t])};var lt={},ei=F,ni=k,ri=ei&&ni(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),oi=q,ii=String,si=TypeError,K=function(e){if(oi(e))return e;throw new si(ii(e)+" is not an object")},ai=F,ci=ln,li=ri,ut=K,hn=Xt,ui=TypeError,Qt=Object.defineProperty,hi=Object.getOwnPropertyDescriptor,te="enumerable",ee="configurable",ne="writable";lt.f=ai?li?function(e,t,n){if(ut(e),t=hn(t),ut(n),typeof e=="function"&&t==="prototype"&&"value"in n&&ne in n&&!n[ne]){var r=hi(e,t);r&&r[ne]&&(e[t]=n.value,n={configurable:ee in n?n[ee]:r[ee],enumerable:te in n?n[te]:r[te],writable:!1})}return Qt(e,t,n)}:Qt:function(e,t,n){if(ut(e),t=hn(t),ut(n),ci)try{return Qt(e,t,n)}catch{}if("get"in n||"set"in n)throw new ui("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var fi=F,di=lt,pi=Ie,fn=fi?function(e,t,n){return di.f(e,t,pi(1,n))}:function(e,t,n){return e[t]=n,e},dn={exports:{}},re=F,gi=j,pn=Function.prototype,mi=re&&Object.getOwnPropertyDescriptor,oe=gi(pn,"name"),yi=oe&&(function(){}).name==="something",bi=oe&&(!re||re&&mi(pn,"name").configurable),vi={EXISTS:oe,PROPER:yi,CONFIGURABLE:bi},wi=w,xi=T,ie=Kt,Ei=wi(Function.toString);xi(ie.inspectSource)||(ie.inspectSource=function(e){return Ei(e)});var Ti=ie.inspectSource,Si=E,Ai=T,gn=Si.WeakMap,ki=Ai(gn)&&/native code/.test(String(gn)),Ci=nn,Oi=rn,mn=Ci("keys"),Pi=function(e){return mn[e]||(mn[e]=Oi(e))},yn={},Li=ki,bn=E,Fi=q,ji=fn,se=j,ae=Kt,Ni=Pi,Mi=yn,vn="Object already initialized",ce=bn.TypeError,Ii=bn.WeakMap,ht,J,ft,Ri=function(e){return ft(e)?J(e):ht(e,{})},zi=function(e){return function(t){var n;if(!Fi(t)||(n=J(t)).type!==e)throw new ce("Incompatible receiver, "+e+" required");return n}};if(Li||ae.state){var C=ae.state||(ae.state=new Ii);C.get=C.get,C.has=C.has,C.set=C.set,ht=function(e,t){if(C.has(e))throw new ce(vn);return t.facade=e,C.set(e,t),t},J=function(e){return C.get(e)||{}},ft=function(e){return C.has(e)}}else{var R=Ni("state");Mi[R]=!0,ht=function(e,t){if(se(e,R))throw new ce(vn);return t.facade=e,ji(e,R,t),t},J=function(e){return se(e,R)?e[R]:{}},ft=function(e){return se(e,R)}}var Bi={set:ht,get:J,has:ft,enforce:Ri,getterFor:zi},le=w,$i=k,_i=T,dt=j,ue=F,Di=vi.CONFIGURABLE,Wi=Ti,wn=Bi,Vi=wn.enforce,Hi=wn.get,xn=String,pt=Object.defineProperty,Ui=le("".slice),qi=le("".replace),Yi=le([].join),Gi=ue&&!$i(function(){return pt(function(){},"length",{value:8}).length!==8}),Ki=String(String).split("String"),Ji=dn.exports=function(e,t,n){Ui(xn(t),0,7)==="Symbol("&&(t="["+qi(xn(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),n&&n.getter&&(t="get "+t),n&&n.setter&&(t="set "+t),(!dt(e,"name")||Di&&e.name!==t)&&(ue?pt(e,"name",{value:t,configurable:!0}):e.name=t),Gi&&n&&dt(n,"arity")&&e.length!==n.arity&&pt(e,"length",{value:n.arity});try{n&&dt(n,"constructor")&&n.constructor?ue&&pt(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch{}var r=Vi(e);return dt(r,"source")||(r.source=Yi(Ki,typeof t=="string"?t:"")),e};Function.prototype.toString=Ji(function(){return _i(this)&&Hi(this).source||Wi(this)},"toString");var Xi=dn.exports,Zi=T,Qi=lt,ts=Xi,es=Gt,ns=function(e,t,n,r){r||(r={});var o=r.enumerable,i=r.name!==void 0?r.name:t;if(Zi(n)&&ts(n,i,r),r.global)o?e[t]=n:es(t,n);else{try{r.unsafe?e[t]&&(o=!0):delete e[t]}catch{}o?e[t]=n:Qi.f(e,t,{value:n,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},En={},rs=Math.ceil,os=Math.floor,is=Math.trunc||function(e){var t=+e;return(t>0?os:rs)(t)},ss=is,Tn=function(e){var t=+e;return t!==t||t===0?0:ss(t)},as=Tn,cs=Math.max,ls=Math.min,us=function(e,t){var n=as(e);return n<0?cs(n+t,0):ls(n,t)},hs=Tn,fs=Math.min,ds=function(e){var t=hs(e);return t>0?fs(t,9007199254740991):0},ps=ds,Sn=function(e){return ps(e.length)},gs=Bt,ms=us,ys=Sn,An=function(e){return function(t,n,r){var o=gs(t),i=ys(o);if(i===0)return!e&&-1;var a=ms(r,i),s;if(e&&n!==n){for(;i>a;)if(s=o[a++],s!==s)return!0}else for(;i>a;a++)if((e||a in o)&&o[a]===n)return e||a||0;return!e&&-1}},bs={includes:An(!0),indexOf:An(!1)},vs=w,he=j,ws=Bt,xs=bs.indexOf,Es=yn,kn=vs([].push),Ts=function(e,t){var n=ws(e),r=0,o=[],i;for(i in n)!he(Es,i)&&he(n,i)&&kn(o,i);for(;t.length>r;)he(n,i=t[r++])&&(~xs(o,i)||kn(o,i));return o},Ss=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],As=Ts,ks=Ss,Cs=ks.concat("length","prototype");En.f=Object.getOwnPropertyNames||function(e){return As(e,Cs)};var Cn={};Cn.f=Object.getOwnPropertySymbols;var Os=Dt,Ps=w,Ls=En,Fs=Cn,js=K,Ns=Ps([].concat),Ms=Os("Reflect","ownKeys")||function(e){var t=Ls.f(js(e)),n=Fs.f;return n?Ns(t,n(e)):t},On=j,Is=Ms,Rs=jt,zs=lt,Bs=function(e,t,n){for(var r=Is(t),o=zs.f,i=Rs.f,a=0;a<r.length;a++){var s=r[a];!On(e,s)&&!(n&&On(n,s))&&o(e,s,i(t,s))}},$s=k,_s=T,Ds=/#|\.prototype\./,X=function(e,t){var n=Vs[Ws(e)];return n===Us?!0:n===Hs?!1:_s(t)?$s(t):!!t},Ws=X.normalize=function(e){return String(e).replace(Ds,".").toLowerCase()},Vs=X.data={},Hs=X.NATIVE="N",Us=X.POLYFILL="P",qs=X,gt=E,Ys=jt.f,Gs=fn,Ks=ns,Js=Gt,Xs=Bs,Zs=qs,Pn=function(e,t){var n=e.target,r=e.global,o=e.stat,i,a,s,l,c,u;if(r?a=gt:o?a=gt[n]||Js(n,{}):a=gt[n]&&gt[n].prototype,a)for(s in t){if(c=t[s],e.dontCallGetSet?(u=Ys(a,s),l=u&&u.value):l=a[s],i=Zs(r?s:n+(o?".":"#")+s,e.forced),!i&&l!==void 0){if(typeof c==typeof l)continue;Xs(c,l)}(e.sham||l&&l.sham)&&Gs(c,"sham",!0),Ks(a,s,c,e)}},Qs=It,ta=w,ea=function(e){if(Qs(e)==="Function")return ta(e)},Ln=ea,na=Y,ra=Nt,oa=Ln(Ln.bind),ia=function(e,t){return na(e),t===void 0?e:ra?oa(e,t):function(){return e.apply(t,arguments)}},Fn={},sa=G,aa=Fn,ca=sa("iterator"),la=Array.prototype,ua=function(e){return e!==void 0&&(aa.Array===e||la[ca]===e)},ha=G,fa=ha("toStringTag"),jn={};jn[fa]="z";var da=String(jn)==="[object z]",pa=da,ga=T,mt=It,ma=G,ya=ma("toStringTag"),ba=Object,va=mt(function(){return arguments}())==="Arguments",wa=function(e,t){try{return e[t]}catch{}},xa=pa?mt:function(e){var t,n,r;return e===void 0?"Undefined":e===null?"Null":typeof(n=wa(t=ba(e),ya))=="string"?n:va?mt(t):(r=mt(t))==="Object"&&ga(t.callee)?"Arguments":r},Ea=xa,Nn=Ht,Ta=zt,Sa=Fn,Aa=G,ka=Aa("iterator"),Mn=function(e){if(!Ta(e))return Nn(e,ka)||Nn(e,"@@iterator")||Sa[Ea(e)]},Ca=M,Oa=Y,Pa=K,La=Vt,Fa=Mn,ja=TypeError,Na=function(e,t){var n=arguments.length<2?Fa(e):t;if(Oa(n))return Pa(Ca(n,e));throw new ja(La(e)+" is not iterable")},Ma=M,In=K,Ia=Ht,Ra=function(e,t,n){var r,o;In(e);try{if(r=Ia(e,"return"),!r){if(t==="throw")throw n;return n}r=Ma(r,e)}catch(i){o=!0,r=i}if(t==="throw")throw n;if(o)throw r;return In(r),n},za=ia,Ba=M,$a=K,_a=Vt,Da=ua,Wa=Sn,Rn=$e,Va=Na,Ha=Mn,zn=Ra,Ua=TypeError,yt=function(e,t){this.stopped=e,this.result=t},Bn=yt.prototype,$n=function(e,t,n){var r=n&&n.that,o=!!(n&&n.AS_ENTRIES),i=!!(n&&n.IS_RECORD),a=!!(n&&n.IS_ITERATOR),s=!!(n&&n.INTERRUPTED),l=za(t,r),c,u,h,f,p,b,x,d=function(g){return c&&zn(c,"normal"),new yt(!0,g)},A=function(g){return o?($a(g),s?l(g[0],g[1],d):l(g[0],g[1])):s?l(g,d):l(g)};if(i)c=e.iterator;else if(a)c=e;else{if(u=Ha(e),!u)throw new Ua(_a(e)+" is not iterable");if(Da(u)){for(h=0,f=Wa(e);f>h;h++)if(p=A(e[h]),p&&Rn(Bn,p))return p;return new yt(!1)}c=Va(e,u)}for(b=i?e.next:c.next;!(x=Ba(b,c)).done;){try{p=A(x.value)}catch(g){zn(c,"throw",g)}if(typeof p=="object"&&p&&Rn(Bn,p))return p}return new yt(!1)},bt=w,Z=Map.prototype,qa={Map,set:bt(Z.set),get:bt(Z.get),has:bt(Z.has),remove:bt(Z.delete),proto:Z},Ya=Pn,Ga=w,Ka=Y,Ja=at,Xa=$n,vt=qa,Za=k,_n=vt.Map,Qa=vt.has,tc=vt.get,ec=vt.set,nc=Ga([].push),rc=Za(function(){return _n.groupBy("ab",function(e){return e}).get("a").length!==1});Ya({target:"Map",stat:!0,forced:rc},{groupBy:function(e,t){Ja(e),Ka(t);var n=new _n,r=0;return Xa(e,function(o){var i=t(o,r++);Qa(n,i)?nc(tc(n,i),o):ec(n,i,[o])}),n}});var oc=Pn,ic=Dt,sc=w,ac=Y,cc=at,lc=Xt,uc=$n,hc=k,Dn=Object.groupBy,fc=ic("Object","create"),dc=sc([].push),pc=!Dn||hc(function(){return Dn("ab",function(e){return e}).a.length!==1});oc({target:"Object",stat:!0,forced:pc},{groupBy:function(e,t){cc(e),ac(t);var n=fc(null),r=0;return uc(e,function(o){var i=lc(t(o,r++));i in n?dc(n[i],o):n[i]=[o]}),n}});function gc(e,t){e.addEventListener("keyup",n=>{n.key==="ArrowUp"||n.key==="ArrowRight"?t("next"):(n.key==="ArrowDown"||n.key==="ArrowLeft")&&t("prev")},!1)}function mc(e,t){let n=0,r;e.addEventListener("wheel",o=>{o.ignore||(o.ignore=!0,clearTimeout(r),n+=o.deltaY,r=setTimeout(()=>{if(Math.abs(n)>=750){let i=Math.sign(n)>0?"next":"prev";t(i),n=0}n=0},50))})}function yc(e,t){let n,r,o;e.addEventListener("touchstart",i=>{i.ignore||(i.ignore=!0,n=i.changedTouches[0].pageX,r=i.changedTouches[0].pageY,o=Date.now())},!1),e.addEventListener("touchend",i=>{var l,c;if(i.ignore)return;i.ignore=!0;const a=i.changedTouches[0].pageX-n,s=i.changedTouches[0].pageY-r;Date.now()-o<=500&&(Math.abs(a)>=50&&Math.abs(s)<=200?t(a<0?"next":"prev"):Math.abs(s)>=50&&Math.abs(a)<=200?t(s<0?"up":"down"):((c=(l=e==null?void 0:e.defaultView)==null?void 0:l.getSelection())==null||c.removeAllRanges(),e.dispatchEvent(new MouseEvent("click",{clientX:n,clientY:r})),i.preventDefault()))},!1)}let Wn,Vn,Hn,Un,qn,Yn,Gn,Kn,Jn,Xn,Zn,Qn,tr;Wn=(e,t)=>{const n=e.__vccOpts||e;for(const[r,o]of t)n[r]=o;return n},Vn={class:"reader"},Hn={class:"viewHolder"},Un={key:0},qn={__name:"BookView",props:{url:{type:[String,File]},location:{type:[String,Number]},tocChanged:Function,getRendition:Function},emits:["update:location"],setup(e,{expose:t,emit:n}){const r=e,{tocChanged:o,getRendition:i}=r,{url:a,location:s}=de(r),l=n;let c=null;const u=Q(null),h=Q(!1),f=({spacing:y,justify:m,hyphenate:N})=>`
2
+ @namespace epub "http://www.idpf.org/2007/ops";
3
+ html {
4
+ color-scheme: light dark;
5
+ }
6
+ /* https://github.com/whatwg/html/issues/5426 */
7
+ @media (prefers-color-scheme: dark) {
8
+ a:link {
9
+ color: lightblue;
10
+ }
11
+ }
12
+ p, li, blockquote, dd {
13
+ line-height: ${y};
14
+ text-align: ${m?"justify":"start"};
15
+ -webkit-hyphens: ${N?"auto":"manual"};
16
+ hyphens: ${N?"auto":"manual"};
17
+ -webkit-hyphenate-limit-before: 3;
18
+ -webkit-hyphenate-limit-after: 2;
19
+ -webkit-hyphenate-limit-lines: 2;
20
+ hanging-punctuation: allow-end last;
21
+ widows: 2;
22
+ }
23
+ /* prevent the above from overriding the align attribute */
24
+ [align="left"] { text-align: left; }
25
+ [align="right"] { text-align: right; }
26
+ [align="center"] { text-align: center; }
27
+ [align="justify"] { text-align: justify; }
28
+
29
+ pre {
30
+ white-space: pre-wrap !important;
31
+ }
32
+ aside[epub|type~="endnote"],
33
+ aside[epub|type~="footnote"],
34
+ aside[epub|type~="note"],
35
+ aside[epub|type~="rearnote"] {
36
+ display: none;
37
+ }
38
+ `,p=async()=>{c=document.createElement("foliate-view"),u.value.append(c),a.value&&(c&&c.close(),typeof a.value=="string"?(await c.open(a.value),b()):(c=await getView(a.value,u.value),b()))},b=()=>{var m,N;h.value=!0;const{book:y}=c;(N=(m=c.renderer).setStyles)==null||N.call(m,f({spacing:1.4,justify:!0,hyphenate:!0})),d(),i(c),o&&o(y.toc),s.value?c==null||c.goTo(s.value):c.renderer.next()},x=y=>{y==="next"?P():y==="prev"&&wt()},d=()=>{c.addEventListener("load",A),c.addEventListener("relocate",g)},A=({detail:{doc:y}})=>{mc(y,x),yc(y,x),gc(y,x)},g=({detail:y})=>{l("update:location",y)},P=()=>c==null?void 0:c.next(),wt=()=>c==null?void 0:c.prev(),fe=y=>c==null?void 0:c.goTo(y);return bc(a,()=>{p()}),vc(()=>{p()}),t({nextPage:P,prevPage:wt,setLocation:fe}),(y,m)=>(z(),B("div",Vn,[O("div",Hn,[wc(O("div",{ref_key:"viewer",ref:u,id:"viewer"},null,512),[[xc,h.value]]),h.value?xt("",!0):(z(),B("div",Un,[pe(y.$slots,"loadingView",{},void 0,!0)]))])]))}},ge=Wn(qn,[["__scopeId","data-v-847bd338"]]),Yn={class:"container"},Gn=O("span",{class:"tocButtonBar",style:{top:"35%"}},null,-1),Kn=O("span",{class:"tocButtonBar",style:{top:"66%"}},null,-1),Jn=[Gn,Kn],Xn=["title"],Zn=O("div",{class:"loadingView"},"Loading\u2026",-1),Qn={key:0},tr={class:"tocArea"},rr={__name:"VueReader",props:{title:{type:String},showToc:{type:Boolean,default:!0},title:{type:String,default:""},getRendition:{type:Function},backgroundColor:{type:String,default:"#fff"}},setup(e){const t=Ec({name:"TocComponent",props:{toc:{type:Array,default:()=>[]},current:{type:[String,Number],default:""},setLocation:{type:Function,required:!0},isSubmenu:{type:Boolean,default:!1,required:!1}},setup(d){const A=Tc(),g=Sc.bind(A),{setLocation:P,isSubmenu:wt}=d,{toc:fe,current:y}=de(d);return()=>fe.value.map((m,N)=>g("div",{key:N},[g("button",{class:["tocAreaButton",m.href===y.value?"active":""],onClick:()=>{m.subitems&&m.subitems.length>0?(m.expansion=!m.expansion,P(m.href,!1)):P(m.href)}},[wt?" ".repeat(4)+m.label:m.label,m.subitems&&m.subitems.length>0&&g("div",{class:`${m.expansion?"open":""} expansion`})]),m.subitems&&m.subitems.length>0&&g(Ac,{name:"collapse-transition"},{default:()=>g("div",{style:{display:m.expansion?void 0:"none"}},[g(t,{toc:m.subitems,current:y.value,setLocation:P,isSubmenu:!0})])})]))}}),n=e,r=kc({toc:[],expandedToc:!1}),{getRendition:o}=n,{toc:i,expandedToc:a}=de(r),s=Q(null),l=Q(null),c=Q(""),u=d=>{var P;o&&o(d);const{book:A}=d,g=(P=A.metadata)==null?void 0:P.title;c.value=g||""},h=d=>{i.value=d},f=()=>{a.value=!a.value},p=()=>{var d;(d=s.value)==null||d.nextPage()},b=()=>{var d;(d=s.value)==null||d.prevPage()},x=(d,A=!0)=>{s.value.setLocation(d),a.value=!1,a.value=!A};return(d,A)=>(z(),B("div",Yn,[O("div",{class:er(["readerArea",{containerExpanded:tt(a)}]),style:Cc({backgroundColor:e.backgroundColor})},[e.showToc?(z(),B("button",{key:0,class:er(["tocButton",{tocButtonExpanded:tt(a)}]),type:"button",onClick:f},Jn,2)):xt("",!0),pe(d.$slots,"title",{},()=>[O("div",{class:"titleArea",title:e.title||c.value},Oc(e.title||c.value),9,Xn)]),nr(ge,Pc({ref_key:"bookRef",ref:s},d.$attrs,{tocChanged:h,getRendition:u}),{loadingView:Lc(()=>[pe(d.$slots,"loadingView",{},()=>[Zn])]),_:3},16),O("button",{class:"arrow pre",onClick:b},"\u2039"),O("button",{class:"arrow next",onClick:p},"\u203A")],6),e.showToc?(z(),B("div",Qn,[O("div",tr,[nr(tt(t),{toc:tt(i),current:l.value,setLocation:x},null,8,["toc","current"])]),tt(a)?(z(),B("div",{key:0,class:"tocBackground",onClick:f})):xt("",!0)])):xt("",!0)]))}}})();export{ge as B,rr as _,Fc as __tla,me as a,or as f,$ as p,ir as t};
@@ -0,0 +1,6 @@
1
+ const M=i=>{if(!i)return"";const e=document.createElement("textarea");return e.innerHTML=i,e.value},A={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},Q={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},_={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},ee={magic:[16,4,"string"],length:[20,4,"uint"],type:[24,4,"uint"],encoding:[28,4,"uint"],uid:[32,4,"uint"],version:[36,4,"uint"],titleOffset:[84,4,"uint"],titleLength:[88,4,"uint"],localeRegion:[94,1,"uint"],localeLanguage:[95,1,"uint"],resourceStart:[108,4,"uint"],huffcdic:[112,4,"uint"],numHuffcdic:[116,4,"uint"],exthFlag:[128,4,"uint"],trailingFlags:[240,4,"uint"],indx:[244,4,"uint"]},te={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},se={magic:[0,4,"string"],length:[4,4,"uint"],count:[8,4,"uint"]},$={magic:[0,4,"string"],length:[4,4,"uint"],type:[8,4,"uint"],idxt:[20,4,"uint"],numRecords:[24,4,"uint"],encoding:[28,4,"uint"],language:[32,4,"uint"],total:[36,4,"uint"],ordt:[40,4,"uint"],ligt:[44,4,"uint"],numLigt:[48,4,"uint"],numCncx:[52,4,"uint"]},ne={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},re={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},ie={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},oe={magic:[0,4,"string"],numEntries:[8,4,"uint"]},ae={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},ce={1252:"windows-1252",65001:"utf-8"},q={100:["creator","string",!0],101:["publisher"],103:["description"],104:["isbn"],105:["subject","string",!0],106:["date"],108:["contributor","string",!0],109:["rights"],110:["subjectCode","string",!0],112:["source","string",!0],113:["asin"],121:["boundary","uint"],122:["fixedLayout"],125:["numResources","uint"],126:["originalResolution"],127:["zeroGutter"],128:["zeroMargin"],129:["coverURI"],132:["regionMagnification"],201:["coverOffset","uint"],202:["thumbnailOffset","uint"],503:["title"],524:["language","string",!0],527:["pageProgressionDirection"]},le={1:["ar","ar-SA","ar-IQ","ar-EG","ar-LY","ar-DZ","ar-MA","ar-TN","ar-OM","ar-YE","ar-SY","ar-JO","ar-LB","ar-KW","ar-AE","ar-BH","ar-QA"],2:["bg"],3:["ca"],4:["zh","zh-TW","zh-CN","zh-HK","zh-SG"],5:["cs"],6:["da"],7:["de","de-DE","de-CH","de-AT","de-LU","de-LI"],8:["el"],9:["en","en-US","en-GB","en-AU","en-CA","en-NZ","en-IE","en-ZA","en-JM",null,"en-BZ","en-TT","en-ZW","en-PH"],10:["es","es-ES","es-MX",null,"es-GT","es-CR","es-PA","es-DO","es-VE","es-CO","es-PE","es-AR","es-EC","es-CL","es-UY","es-PY","es-BO","es-SV","es-HN","es-NI","es-PR"],11:["fi"],12:["fr","fr-FR","fr-BE","fr-CA","fr-CH","fr-LU","fr-MC"],13:["he"],14:["hu"],15:["is"],16:["it","it-IT","it-CH"],17:["ja"],18:["ko"],19:["nl","nl-NL","nl-BE"],20:["no","nb","nn"],21:["pl"],22:["pt","pt-BR","pt-PT"],23:["rm"],24:["ro"],25:["ru"],26:["hr",null,"sr"],27:["sk"],28:["sq"],29:["sv","sv-SE","sv-FI"],30:["th"],31:["tr"],32:["ur"],33:["id"],34:["uk"],35:["be"],36:["sl"],37:["et"],38:["lv"],39:["lt"],41:["fa"],42:["vi"],43:["hy"],44:["az"],45:["eu"],46:["hsb"],47:["mk"],48:["st"],49:["ts"],50:["tn"],52:["xh"],53:["zu"],54:["af"],55:["ka"],56:["fo"],57:["hi"],58:["mt"],59:["se"],62:["ms"],63:["kk"],65:["sw"],67:["uz",null,"uz-UZ"],68:["tt"],69:["bn"],70:["pa"],71:["gu"],72:["or"],73:["ta"],74:["te"],75:["kn"],76:["ml"],77:["as"],78:["mr"],79:["sa"],82:["cy","cy-GB"],83:["gl","gl-ES"],87:["kok"],97:["ne"],98:["fy"]},N=(i,e)=>{const t=new i.constructor(i.length+e.length);return t.set(i),t.set(e,i.length),t},P=(i,e,t)=>{const s=new i.constructor(i.length+e.length+t.length);return s.set(i),s.set(e,i.length),s.set(t,i.length+e.length),s},he=new TextDecoder,O=i=>he.decode(i),x=i=>{if(!i)return;const e=i.byteLength,t=e===4?"getUint32":e===2?"getUint16":"getUint8";return new DataView(i)[t](0)},S=(i,e)=>Object.fromEntries(Array.from(Object.entries(i)).map(([t,[s,r,a]])=>[t,(a==="string"?O:x)(e.slice(s,s+r))])),X=i=>new TextDecoder(ce[i]),D=(i,e=0)=>{let t=0,s=0;for(const r of i.subarray(e,e+4))if(t=t<<7|(r&127)>>>0,s++,r&128)break;return{value:t,length:s}},ue=i=>{let e=0;for(const t of i.subarray(-4))t&128&&(e=0),e=e<<7|t&127;return e},V=i=>{let e=0;for(;i>0;i=i>>1)(i&1)===1&&e++;return e},de=i=>{let e=0;for(;!(i&1);)i=i>>1,e++;return e},fe=i=>{let e=[];for(let t=0;t<i.length;t++){const s=i[t];if(s===0)e.push(0);else if(s<=8)for(const r of i.subarray(t+1,(t+=s)+1))e.push(r);else if(s<=127)e.push(s);else if(s<=191){const r=s<<8|i[t+++1],a=(r&16383)>>>3,n=(r&7)+3;for(let o=0;o<n;o++)e.push(e[e.length-a])}else e.push(32,s^128)}return Uint8Array.from(e)},ge=(i,e)=>{const t=e>>3,s=e+32,r=s>>3;let a=0n;for(let n=t;n<=r;n++)a=a<<8n|BigInt(i[n]??0);return a>>8n-BigInt(s&7)&0xffffffffn},me=async(i,e)=>{const t=await e(i.huffcdic),{magic:s,offset1:r,offset2:a}=S(re,t);if(s!=="HUFF")throw new Error("Invalid HUFF record");const n=Array.from({length:256},(u,m)=>r+m*4).map(u=>x(t.slice(u,u+4))).map(u=>[u&128,u&31,u>>>8]),o=[null].concat(Array.from({length:32},(u,m)=>a+m*8).map(u=>[x(t.slice(u,u+4)),x(t.slice(u+4,u+8))])),l=[];for(let u=1;u<i.numHuffcdic;u++){const m=await e(i.huffcdic+u),p=S(ie,m);if(p.magic!=="CDIC")throw new Error("Invalid CDIC record");const c=Math.min(1<<p.codeLength,p.numEntries-l.length),h=m.slice(p.length);for(let f=0;f<c;f++){const g=x(h.slice(f*2,f*2+2)),b=x(h.slice(g,g+2)),w=b&32767,y=b&32768,R=new Uint8Array(h.slice(g+2,g+2+w));l.push([R,y])}}const d=u=>{let m=new Uint8Array;const p=u.byteLength*8;for(let c=0;c<p;){const h=Number(ge(u,c));let[f,g,b]=n[h>>>24];if(!f){for(;h>>>32-g<o[g][0];)g+=1;b=o[g][1]}if((c+=g)>p)break;const w=b-(h>>>32-g);let[y,R]=l[w];R||(y=d(y),l[w]=[y,!0]),m=N(m,y)}return m};return d},z=async(i,e)=>{const t=await e(i),s=S($,t);if(s.magic!=="INDX")throw new Error("Invalid INDX record");const r=X(s.encoding),a=t.slice(s.length),n=S(ne,a);if(n.magic!=="TAGX")throw new Error("Invalid TAGX section");const o=(n.length-12)/4,l=Array.from({length:o},(p,c)=>new Uint8Array(a.slice(12+c*4,12+c*4+4))),d={};let u=0;for(let p=0;p<s.numCncx;p++){const c=await e(i+s.numRecords+p+1),h=new Uint8Array(c);for(let f=0;f<h.byteLength;){const g=f,{value:b,length:w}=D(h,f);f+=w;const y=c.slice(f,f+b);f+=b,d[u+g]=r.decode(y)}u+=65536}const m=[];for(let p=0;p<s.numRecords;p++){const c=await e(i+1+p),h=new Uint8Array(c),f=S($,c);if(f.magic!=="INDX")throw new Error("Invalid INDX record");for(let g=0;g<f.numRecords;g++){const b=f.idxt+4+2*g,w=x(c.slice(b,b+2)),y=x(c.slice(w,w+1)),R=O(c.slice(w+1,w+1+y)),T=[],F=w+1+y;let G=0,E=F+n.numControlBytes;for(const[B,k,v,H]of l){if(H&1){G++;continue}const C=F+G,L=x(c.slice(C,C+1))&v;if(L===v)if(V(v)>1){const{value:U,length:I}=D(h,E);T.push([B,null,U,k]),E+=I}else T.push([B,1,null,k]);else T.push([B,L>>de(v),null,k])}const j={};for(const[B,k,v,H]of T){const C=[];if(k!=null)for(let L=0;L<k*H;L++){const{value:U,length:I}=D(h,E);C.push(U),E+=I}else{let L=0;for(;L<v;){const{value:U,length:I}=D(h,E);C.push(U),E+=I,L+=I}}j[B]=C}m.push({name:R,tagMap:j})}}return{table:m,cncx:d}},pe=async(i,e)=>{const{table:t,cncx:s}=await z(i,e),r=t.map(({tagMap:n},o)=>{var l,d,u,m,p,c;return{index:o,offset:(l=n[1])==null?void 0:l[0],size:(d=n[2])==null?void 0:d[0],label:s[n[3]]??"",headingLevel:(u=n[4])==null?void 0:u[0],pos:n[6],parent:(m=n[21])==null?void 0:m[0],firstChild:(p=n[22])==null?void 0:p[0],lastChild:(c=n[23])==null?void 0:c[0]}}),a=n=>(n.firstChild==null||(n.children=r.filter(o=>o.parent===n.index).map(a)),n);return r.filter(n=>n.headingLevel===0).map(a)},be=(i,e)=>{const{magic:t,count:s}=S(se,i);if(t!=="EXTH")throw new Error("Invalid EXTH header");const r=X(e),a={};let n=12;for(let o=0;o<s;o++){const l=x(i.slice(n,n+4)),d=x(i.slice(n+4,n+8));if(l in q){const[u,m,p]=q[l],c=i.slice(n+8,n+d),h=m==="uint"?x(c):r.decode(c);p?(a[u]??=[],a[u].push(h)):a[u]=h}n+=d}return a},we=async(i,e)=>{const{flags:t,dataStart:s,keyLength:r,keyStart:a}=S(ae,i),n=new Uint8Array(i.slice(s));if(t&2){const l=r===16?1024:1040,d=new Uint8Array(i.slice(a,a+r)),u=Math.min(l,n.length);for(var o=0;o<u;o++)n[o]=n[o]^d[o%d.length]}if(t&1)try{return await e(n)}catch(l){console.warn(l),console.warn("Failed to decompress font")}return n},ye=async i=>O(await i.slice(60,68).arrayBuffer())==="BOOKMOBI";class xe{#e;#t;pdb;async open(e){this.#e=e;const t=S(Q,await e.slice(0,78).arrayBuffer());this.pdb=t;const s=await e.slice(78,78+t.numRecords*8).arrayBuffer();this.#t=Array.from({length:t.numRecords},(r,a)=>x(s.slice(a*8,a*8+4))).map((r,a,n)=>[r,n[a+1]])}loadRecord(e){const t=this.#t[e];if(!t)throw new RangeError("Record index out of bounds");return this.#e.slice(...t).arrayBuffer()}async loadMagic(e){const t=this.#t[e][0];return O(await this.#e.slice(t,t+4).arrayBuffer())}}class Re extends xe{#e=0;#t;#n;#s;#r;#i;constructor({unzlib:e}){super(),this.unzlib=e}async open(e){var s;await super.open(e),this.headers=this.#o(await super.loadRecord(0)),this.#t=this.headers.mobi.resourceStart;let t=this.headers.mobi.version>=8;if(!t){const r=(s=this.headers.exth)==null?void 0:s.boundary;if(r<4294967295)try{this.headers=this.#o(await super.loadRecord(r)),this.#e=r,t=!0}catch(a){console.warn(a),console.warn("Failed to open KF8; falling back to MOBI")}}return await this.#a(),t?new Ce(this).init():new Le(this).init()}#o(e){const t=S(_,e),s=S(ee,e);if(s.magic!=="MOBI")throw new Error("Missing MOBI header");const{titleOffset:r,titleLength:a,localeLanguage:n,localeRegion:o}=s;s.title=e.slice(r,r+a);const l=le[n];s.language=(l==null?void 0:l[o>>2])??(l==null?void 0:l[0]);const d=s.exthFlag&64?be(e.slice(s.length+16),s.encoding):null,u=s.version>=8?S(te,e):null;return{palmdoc:t,mobi:s,exth:d,kf8:u}}async#a(){const{palmdoc:e,mobi:t}=this.headers;this.#n=X(t.encoding),this.#s=new TextEncoder;const{compression:s}=e;if(this.#r=s===1?o=>o:s===2?fe:s===17480?await me(t,this.loadRecord.bind(this)):null,!this.#r)throw new Error("Unknown compression type");const{trailingFlags:r}=t,a=r&1,n=V(r>>>1);this.#i=o=>{for(let l=0;l<n;l++){const d=ue(o);o=o.subarray(0,-d)}if(a){const l=(o[o.length-1]&3)+1;o=o.subarray(0,-l)}return o}}decode(...e){return this.#n.decode(...e)}encode(...e){return this.#s.encode(...e)}loadRecord(e){return super.loadRecord(this.#e+e)}loadMagic(e){return super.loadMagic(this.#e+e)}loadText(e){return this.loadRecord(e+1).then(t=>new Uint8Array(t)).then(this.#i).then(this.#r)}async loadResource(e){const t=await super.loadRecord(this.#t+e),s=O(t.slice(0,4));return s==="FONT"?we(t,this.unzlib):s==="VIDE"||s==="AUDI"?t.slice(12):t}getNCX(){const e=this.headers.mobi.indx;if(e<4294967295)return pe(e,this.loadRecord.bind(this))}getMetadata(){var s,r;const{mobi:e,exth:t}=this.headers;return{identifier:e.uid.toString(),title:M((t==null?void 0:t.title)||this.decode(e.title)),author:(s=t==null?void 0:t.creator)==null?void 0:s.map(M),publisher:M(t==null?void 0:t.publisher),language:(t==null?void 0:t.language)??e.language,published:t==null?void 0:t.date,description:M(t==null?void 0:t.description),subject:(r=t==null?void 0:t.subject)==null?void 0:r.map(M),rights:M(t==null?void 0:t.rights),contributor:t==null?void 0:t.contributor}}async getCover(){const{exth:e}=this.headers,t=(e==null?void 0:e.coverOffset)<4294967295?e==null?void 0:e.coverOffset:(e==null?void 0:e.thumbnailOffset)<4294967295?e==null?void 0:e.thumbnailOffset:null;if(t!=null){const s=await this.loadResource(t);return new Blob([s])}}}const Z=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,Se=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi,Te=i=>{let e=0;for(;i;){const t=i.parentElement;if(t){const s=t.tagName.toLowerCase();s==="p"?e+=1.5:s==="blockquote"&&(e+=2)}i=t}return e};function Ae(i){let e="";for(let t=0;t<i.length;t+=32768)e+=String.fromCharCode.apply(null,i.subarray(t,t+32768));return e}class Le{parser=new DOMParser;serializer=new XMLSerializer;#e=new Map;#t=new Map;#n=new Map;#s;#r=[];#i=A.HTML;constructor(e){this.mobi=e}async init(){var a;const e=[];for(let n=0;n<this.mobi.headers.palmdoc.numTextRecords;n++){const o=await this.mobi.loadText(n);e.push(o)}const t=e.reduce((n,o)=>n+o.byteLength,0),s=new Uint8Array(t);e.reduce((n,o)=>(s.set(new Uint8Array(o),n),n+o.byteLength),0);const r=Ae(s);this.#s=[0].concat(Array.from(r.matchAll(Z),n=>n.index)).map((n,o,l)=>{const d=l[o+1]??s.length;return{book:this,raw:s.subarray(n,d)}}).map((n,o,l)=>{var d;return n.start=((d=l[o-1])==null?void 0:d.end)??0,n.end=n.start+n.raw.byteLength,n}),this.sections=this.#s.map((n,o)=>({id:o,load:()=>this.loadSection(n),createDocument:()=>this.createDocument(n),size:n.end-n.start}));try{this.landmarks=await this.getGuide();const n=(a=this.landmarks.find(({type:o})=>o==null?void 0:o.includes("toc")))==null?void 0:a.href;if(n){const{index:o}=this.resolveHref(n),l=await this.sections[o].createDocument();let d,u=0,m=0;const p=new Map,c=new Map;this.toc=Array.from(l.querySelectorAll("a[filepos]")).reduce((h,f)=>{var y;const g=Te(f),b={label:((y=f.innerText)==null?void 0:y.trim())??"",href:`filepos:${f.getAttribute("filepos")}`},w=g>m?u+1:g===m?u:p.get(g)??Math.max(0,u-1);if(w>u)d?(d.subitems??=[],d.subitems.push(b),c.set(w,d)):h.push(b);else{const R=c.get(w);R?R.subitems.push(b):h.push(b)}return d=b,u=w,m=g,p.set(g,w),h},[])}}catch(n){console.warn(n)}return this.#r=[...new Set(Array.from(r.matchAll(Se),n=>n[1]))].map(n=>({filepos:n,number:Number(n)})).sort((n,o)=>n.number-o.number),this.metadata=this.mobi.getMetadata(),this.getCover=this.mobi.getCover.bind(this.mobi),this}async getGuide(){const e=await this.createDocument(this.#s[0]);return Array.from(e.getElementsByTagName("reference"),t=>{var s;return{label:t.getAttribute("title"),type:(s=t.getAttribute("type"))==null?void 0:s.split(/\s/),href:`filepos:${t.getAttribute("filepos")}`}})}async loadResource(e){if(this.#e.has(e))return this.#e.get(e);const t=await this.mobi.loadResource(e),s=URL.createObjectURL(new Blob([t]));return this.#e.set(e,s),s}async loadRecindex(e){return this.loadResource(Number(e)-1)}async replaceResources(e){for(const t of e.querySelectorAll("img[recindex]")){const s=t.getAttribute("recindex");try{t.src=await this.loadRecindex(s)}catch{console.warn(`Failed to load image ${s}`)}}for(const t of e.querySelectorAll("[mediarecindex]")){const s=t.getAttribute("mediarecindex"),r=t.getAttribute("recindex");try{t.src=await this.loadRecindex(s),r&&(t.poster=await this.loadRecindex(r))}catch{console.warn(`Failed to load media ${s}`)}}for(const t of e.querySelectorAll("[filepos]")){const s=t.getAttribute("filepos");t.href=`filepos:${s}`}}async loadText(e){if(this.#t.has(e))return this.#t.get(e);const{raw:t}=e,s=this.#r.filter(({number:n})=>n>=e.start&&n<e.end).map(n=>({...n,offset:n.number-e.start}));let r=t;s.length&&(r=t.subarray(0,s[0].offset),s.forEach(({filepos:n,offset:o},l)=>{const d=s[l+1],u=this.mobi.encode(`<a id="filepos${n}"></a>`);r=P(r,u,t.subarray(o,d==null?void 0:d.offset))}));const a=this.mobi.decode(r).replaceAll(Z,"");return this.#t.set(e,a),a}async createDocument(e){const t=await this.loadText(e);return this.parser.parseFromString(t,this.#i)}async loadSection(e){if(this.#n.has(e))return this.#n.get(e);const t=await this.createDocument(e),s=t.createElement("style");t.head.append(s),s.append(t.createTextNode(`blockquote {
2
+ margin-block-start: 0;
3
+ margin-block-end: 0;
4
+ margin-inline-start: 1em;
5
+ margin-inline-end: 0;
6
+ }`)),await this.replaceResources(t);const r=this.serializer.serializeToString(t),a=URL.createObjectURL(new Blob([r],{type:this.#i}));return this.#n.set(e,a),a}resolveHref(e){const t=e.match(/filepos:(.*)/)[1],s=Number(t);return{index:this.#s.findIndex(r=>r.end>s),anchor:r=>r.getElementById(`filepos${t}`)}}splitTOCHref(e){const t=e.match(/filepos:(.*)/)[1],s=Number(t);return[this.#s.findIndex(r=>r.end>s),`filepos${t}`]}getTOCFragment(e,t){return e.getElementById(t)}isExternal(e){return/^(?!blob|filepos)\w+:/i.test(e)}destroy(){for(const e of this.#e.values())URL.revokeObjectURL(e);for(const e of this.#n.values())URL.revokeObjectURL(e)}}const Y=/kindle:(flow|embed):(\w+)(?:\?mime=(\w+\/[-+.\w]+))?/,Me=/kindle:pos:fid:(\w+):off:(\w+)/,Ee=i=>{const[e,t,s]=i.match(Y).slice(1);return{resourceType:e,id:parseInt(t,32),type:s}},K=i=>{const[e,t]=i.match(Me).slice(1);return{fid:parseInt(e,32),off:parseInt(t,32)}},W=(i=0,e=0)=>`kindle:pos:fid:${i.toString(32).toUpperCase().padStart(4,"0")}:off:${e.toString(32).toUpperCase().padStart(10,"0")}`,J=i=>{const e=i.match(/\s(id|name|aid)\s*=\s*['"]([^'"]*)['"]/i);if(!e)return;const[,t,s]=e;return`[${t}="${CSS.escape(s)}"]`},ke=async(i,e,t)=>{const s=[];i.replace(e,(...a)=>(s.push(a),null));const r=[];for(const a of s)r.push(await t(...a));return i.replace(e,()=>r.shift())},ve=i=>{for(const e of i){if(e==="page-spread-left"||e==="rendition:page-spread-left")return"left";if(e==="page-spread-right"||e==="rendition:page-spread-right")return"right";if(e==="rendition:page-spread-center")return"center"}};class Ce{parser=new DOMParser;serializer=new XMLSerializer;transformTarget=new EventTarget;#e=new Map;#t=new Map;#n=new Map;#s={};#r;#i;#o=new Uint8Array;#a=new Uint8Array;#u=-1;#d=-1;#c=A.XHTML;#l=new Map;constructor(e){this.mobi=e}async init(){var d,u,m,p;const e=this.mobi.loadRecord.bind(this.mobi),{kf8:t}=this.mobi.headers;try{const c=await e(t.fdst),h=S(oe,c);if(h.magic!=="FDST")throw new Error("Missing FDST record");const f=Array.from({length:h.numEntries},(g,b)=>12+b*8).map(g=>[x(c.slice(g,g+4)),x(c.slice(g+4,g+8))]);this.#s.fdstTable=f,this.#i=f[f.length-1][1]}catch{}const s=(await z(t.skel,e)).table.map(({name:c,tagMap:h},f)=>({index:f,name:c,numFrag:h[1][0],offset:h[6][0],length:h[6][1]})),r=await z(t.frag,e),a=r.table.map(({name:c,tagMap:h})=>({insertOffset:parseInt(c),selector:r.cncx[h[2][0]],index:h[4][0],offset:h[6][0],length:h[6][1]}));this.#s.skelTable=s,this.#s.fragTable=a,this.#r=s.reduce((c,h)=>{const f=c[c.length-1],g=(f==null?void 0:f.fragEnd)??0,b=g+h.numFrag,w=a.slice(g,b),y=h.length+w.map(T=>T.length).reduce((T,F)=>T+F),R=((f==null?void 0:f.totalLength)??0)+y;return c.concat({skel:h,frags:w,fragEnd:b,length:y,totalLength:R})},[]);const n=await this.getResourcesByMagic(["RESC","PAGE"]),o=new Map;if(n.RESC){const c=await this.mobi.loadRecord(n.RESC),h=this.mobi.decode(c.slice(16)).replace(/\0/g,""),f=h.search(/\?>/),g=`<package>${h.slice(f)}</package>`,b=this.parser.parseFromString(g,A.XML);for(const w of b.querySelectorAll("spine > itemref")){const y=parseInt(w.getAttribute("skelid"));o.set(y,ve(((d=w.getAttribute("properties"))==null?void 0:d.split(" "))??[]))}}this.sections=this.#r.map((c,h)=>c.frags.length?{id:h,load:()=>this.loadSection(c),createDocument:()=>this.createDocument(c),size:c.length,pageSpread:o.get(h)}:{linear:"no"});try{const c=await this.mobi.getNCX(),h=({label:f,pos:g,children:b})=>{const[w,y]=g,R=W(w,y),T=this.#t.get(w);return T?T.push(y):this.#t.set(w,[y]),{label:M(f),href:R,subitems:b==null?void 0:b.map(h)}};this.toc=c==null?void 0:c.map(h),this.landmarks=await this.getGuide()}catch(c){console.warn(c)}const{exth:l}=this.mobi.headers;return this.dir=l.pageProgressionDirection,this.rendition={layout:l.fixedLayout==="true"?"pre-paginated":"reflowable",viewport:Object.fromEntries(((p=(m=(u=l.originalResolution)==null?void 0:u.split("x"))==null?void 0:m.slice(0,2))==null?void 0:p.map((c,h)=>[h?"height":"width",c]))??[])},this.metadata=this.mobi.getMetadata(),this.getCover=this.mobi.getCover.bind(this.mobi),this}async getResourcesByMagic(e){const t={},s=this.mobi.headers.kf8.resourceStart,r=this.mobi.pdb.numRecords;for(let a=s;a<r;a++)try{const n=await this.mobi.loadMagic(a),o=e.find(l=>l===n);o&&(t[o]=a)}catch{}return t}async getGuide(){const e=this.mobi.headers.kf8.guide;if(e<4294967295){const t=this.mobi.loadRecord.bind(this.mobi),{table:s,cncx:r}=await z(e,t);return s.map(({name:a,tagMap:n})=>{var o,l;return{label:r[n[1][0]]??"",type:a==null?void 0:a.split(/\s/),href:W(((o=n[6])==null?void 0:o[0])??((l=n[3])==null?void 0:l[0]))}})}}async loadResourceBlob(e){var m;const{resourceType:t,id:s,type:r}=Ee(e),a=t==="flow"?await this.loadFlow(s):await this.mobi.loadResource(s-1),n={data:[A.XHTML,A.HTML,A.CSS,A.SVG].includes(r)?await this.replaceResources(this.mobi.decode(a)):a,type:r},o=new CustomEvent("data",{detail:n});this.transformTarget.dispatchEvent(o);const l=await o.detail.data,d=await o.detail.type,u=d===A.SVG?this.parser.parseFromString(l,d):null;return[new Blob([l],{newType:d}),(m=u==null?void 0:u.getElementsByTagNameNS("http://www.w3.org/2000/svg","image"))!=null&&m.length?u.documentElement:null]}async loadResource(e){if(this.#e.has(e))return this.#e.get(e);const[t,s]=await this.loadResourceBlob(e),r=s?e:URL.createObjectURL(t);return s&&this.#l.set(r,s),this.#e.set(e,r),r}replaceResources(e){const t=new RegExp(Y,"g");return ke(e,t,this.loadResource.bind(this))}async loadRaw(e,t){const s=t-this.#o.length,r=this.#i==null?1/0:this.#i-this.#a.length-e;if(s<0||s<r){for(;this.#o.length<t;){const n=++this.#u,o=await this.mobi.loadText(n);this.#o=N(this.#o,o)}return this.#o.slice(e,t)}for(;this.#i-this.#a.length>e;){const n=this.mobi.headers.palmdoc.numTextRecords-1-++this.#d,o=await this.mobi.loadText(n);this.#a=N(o,this.#a)}const a=this.#i-this.#a.length;return this.#a.slice(e-a,t-a)}loadFlow(e){if(e<4294967295)return this.loadRaw(...this.#s.fdstTable[e])}async loadText(e){const{skel:t,frags:s,length:r}=e,a=await this.loadRaw(t.offset,t.offset+r);let n=a.slice(0,t.length);for(const o of s){const l=o.insertOffset-t.offset,d=t.length+o.offset,u=a.slice(d,d+o.length);n=P(n.slice(0,l),u,n.slice(l));const m=this.#t.get(o.index);if(m)for(const p of m){const c=this.mobi.decode(u.slice(p)),h=J(c);this.#h(o.index,p,h)}}return this.mobi.decode(n)}async createDocument(e){const t=await this.loadText(e);return this.parser.parseFromString(t,this.#c)}async loadSection(e){var n;if(this.#e.has(e))return this.#e.get(e);const t=await this.loadText(e),s=await this.replaceResources(t);let r=this.parser.parseFromString(s,this.#c);(r.querySelector("parsererror")||!((n=r.documentElement)!=null&&n.namespaceURI))&&(this.#c=A.HTML,r=this.parser.parseFromString(s,this.#c));for(const[o,l]of this.#l)for(const d of r.querySelectorAll(`img[src="${o}"]`))d.replaceWith(l);const a=URL.createObjectURL(new Blob([this.serializer.serializeToString(r)],{type:this.#c}));return this.#e.set(e,a),a}getIndexByFID(e){return this.#r.findIndex(t=>t.frags.some(s=>s.index===e))}#h(e,t,s){const r=this.#n.get(e);if(r)r.set(t,s);else{const a=new Map;this.#n.set(e,a),a.set(t,s)}}async resolveHref(e){var c;const{fid:t,off:s}=K(e),r=this.getIndexByFID(t);if(r<0)return;const a=(c=this.#n.get(t))==null?void 0:c.get(s);if(a)return{index:r,anchor:h=>h.querySelector(a)};const{skel:n,frags:o}=this.#r[r],l=o.find(h=>h.index===t),d=n.offset+n.length+l.offset,u=await this.loadRaw(d,d+l.length),m=this.mobi.decode(u).slice(s),p=J(m);return this.#h(t,s,p),{index:r,anchor:h=>h.querySelector(p)}}splitTOCHref(e){const t=K(e);return[this.getIndexByFID(t.fid),t]}getTOCFragment(e,{fid:t,off:s}){var a;const r=(a=this.#n.get(t))==null?void 0:a.get(s);return e.querySelector(r)}isExternal(e){return/^(?!blob|kindle)\w+:/i.test(e)}destroy(){for(const e of this.#e.values())URL.revokeObjectURL(e)}}export{Re as MOBI,ye as isMOBI};
@@ -0,0 +1,97 @@
1
+ const N=a=>new Promise(t=>setTimeout(t,a)),k=(a,t,e)=>{let i;return(...s)=>{const n=()=>{i=null,e||a(...s)},r=e&&!i;i&&clearTimeout(i),i=setTimeout(n,t),r&&a(...s)}},C=(a,t,e)=>e*(t-a)+a,B=a=>1-(1-a)*(1-a),O=(a,t,e,i,s)=>new Promise(n=>{let r;const o=h=>{if(document.hidden)return s(C(a,t,1)),n();r??=h;const l=Math.min(1,(h-r)/e);s(C(a,t,i(l))),l<1?requestAnimationFrame(o):n()};if(document.hidden)return s(C(a,t,1)),n();requestAnimationFrame(o)}),F=a=>{if(!(a!=null&&a.collapsed))return a;const{endOffset:t,endContainer:e}=a;if(e.nodeType===1){const i=e.childNodes[t];return(i==null?void 0:i.nodeType)===1?i:e}if(t+1<e.length)a.setEnd(e,t+1);else if(t>1)a.setStart(e,t-1);else return e.parentNode;return a},b=(a,t,e,i=e)=>{const s=a.createRange();return s.setStart(t,e),s.setEnd(t,i),s},E=(a,t,e,i=0,s=t.nodeValue.length)=>{if(s-i===1)return e(b(a,t,i),b(a,t,s))<0?i:s;const n=Math.floor(i+(s-i)/2),r=e(b(a,t,i,n),b(a,t,n,s));return r<0?E(a,t,e,i,n):r>0?E(a,t,e,n,s):n},{SHOW_ELEMENT:V,SHOW_TEXT:D,SHOW_CDATA_SECTION:W,FILTER_ACCEPT:L,FILTER_REJECT:R,FILTER_SKIP:M}=NodeFilter,j=V|D|W,_=a=>{let t=1/0,e=-1/0,i=1/0,s=-1/0;for(const n of a.getClientRects())i=Math.min(i,n.left),t=Math.min(t,n.top),e=Math.max(e,n.right),s=Math.max(s,n.bottom);return new DOMRect(i,t,e-i,s-t)},A=(a,t,e,i)=>{const s=c=>{var m,g;const d=(m=c.localName)==null?void 0:m.toLowerCase();if(d==="script"||d==="style")return R;if(c.nodeType===1){const{left:f,right:x}=i(c.getBoundingClientRect());if(x<t||f>e)return R;if(f>=t&&x<=e)return L}else{if(!((g=c.nodeValue)!=null&&g.trim()))return M;const f=a.createRange();f.selectNodeContents(c);const{left:x,right:w}=i(f.getBoundingClientRect());if(w>=t&&x<=e)return L}return M},n=a.createTreeWalker(a.body,j,{acceptNode:s}),r=[];for(let c=n.nextNode();c;c=n.nextNode())r.push(c);const o=r[0]??a.body,h=r[r.length-1]??o,l=o.nodeType===1?0:E(a,o,(c,d)=>{const m=i(_(c)),g=i(_(d));return m.right<t&&g.left>t?0:g.left>t?-1:1}),u=h.nodeType===1?0:E(a,h,(c,d)=>{const m=i(_(c)),g=i(_(d));return m.right<e&&g.left>e?0:g.left>e?-1:1}),p=a.createRange();return p.setStart(o,l),p.setEnd(h,u),p},$=a=>{const t=document.createRange();return t.setStart(a.anchorNode,a.anchorOffset),t.setEnd(a.focusNode,a.focusOffset),t.collapsed},z=(a,t)=>{let e;if(a.startContainer?e=a.cloneRange():a.nodeType&&(e=document.createRange(),e.selectNode(a)),e){const i=e.startContainer.ownerDocument.defaultView.getSelection();i&&(i.removeAllRanges(),t===-1?e.collapse(!0):t===1&&e.collapse(),i.addRange(e))}},H=a=>{const{defaultView:t}=a,{writingMode:e,direction:i}=t.getComputedStyle(a.body),s=e==="vertical-rl"||e==="vertical-lr",n=a.body.dir==="rtl"||i==="rtl"||a.documentElement.dir==="rtl";return{vertical:s,rtl:n}},S=a=>{const t=a.defaultView.getComputedStyle(a.body);return t.backgroundColor==="rgba(0, 0, 0, 0)"&&t.backgroundImage==="none"?a.defaultView.getComputedStyle(a.documentElement).background:t.background},P=(a,t)=>Array.from({length:a},()=>{const e=document.createElement("div"),i=document.createElement("div");return e.append(i),i.setAttribute("part",t),e}),y=(a,t)=>{const{style:e}=a;for(const[i,s]of Object.entries(t))e.setProperty(i,s,"important")};class q{#o=new ResizeObserver(()=>this.expand());#r=document.createElement("div");#i=document.createElement("iframe");#l=document.createRange();#e;#s=!1;#c=!1;#t=!0;#n;#a={};constructor({container:t,onExpand:e}){this.container=t,this.onExpand=e,this.#i.setAttribute("part","filter"),this.#r.append(this.#i),Object.assign(this.#r.style,{boxSizing:"content-box",position:"relative",overflow:"hidden",flex:"0 0 auto",width:"100%",height:"100%",display:"flex",justifyContent:"center",alignItems:"center"}),Object.assign(this.#i.style,{overflow:"hidden",border:"0",display:"none",width:"100%",height:"100%"}),this.#i.setAttribute("sandbox","allow-same-origin allow-scripts"),this.#i.setAttribute("scrolling","no")}get element(){return this.#r}get document(){return this.#i.contentDocument}async load(t,e,i){if(typeof t!="string")throw new Error(`${t} is not string`);return new Promise(s=>{this.#i.addEventListener("load",()=>{const n=this.document;e==null||e(n),this.#i.style.display="block";const{vertical:r,rtl:o}=H(n),h=S(n);this.#i.style.display="none",this.#s=r,this.#c=o,this.#l.selectNodeContents(n.body);const l=i==null?void 0:i({vertical:r,rtl:o,background:h});this.#i.style.display="block",this.render(l),this.#o.observe(n.body),n.fonts.ready.then(()=>this.expand()),s()},{once:!0}),this.#i.src=t})}render(t){t&&(this.#t=t.flow!=="scrolled",this.#a=t,this.#t?this.columnize(t):this.scrolled(t))}scrolled({gap:t,columnWidth:e}){const i=this.#s,s=this.document;y(s.documentElement,{"box-sizing":"border-box",padding:i?`${t}px 0`:`0 ${t}px`,"column-width":"auto",height:"auto",width:"auto"}),y(s.body,{[i?"max-height":"max-width"]:`${e}px`,margin:"auto"}),this.setImageSize(),this.expand()}columnize({width:t,height:e,gap:i,columnWidth:s}){const n=this.#s;this.#n=n?e:t;const r=this.document;y(r.documentElement,{"box-sizing":"border-box","column-width":`${Math.trunc(s)}px`,"column-gap":`${i}px`,"column-fill":"auto",...n?{width:`${t}px`}:{height:`${e}px`},padding:n?`${i/2}px 0`:`0 ${i/2}px`,overflow:"hidden","overflow-wrap":"break-word",position:"static",border:"0",margin:"0","max-height":"none","max-width":"none","min-height":"none","min-width":"none","-webkit-line-box-contain":"block glyphs replaced"}),y(r.body,{"max-height":"none","max-width":"none",margin:"0"}),this.setImageSize(),this.expand()}setImageSize(){const{width:t,height:e,margin:i}=this.#a,s=this.#s,n=this.document;for(const r of n.body.querySelectorAll("img, svg, video")){const{maxHeight:o,maxWidth:h}=n.defaultView.getComputedStyle(r);y(r,{"max-height":s?o!=="none"&&o!=="0px"?o:"100%":`${e-i*2}px`,"max-width":s?`${t-i*2}px`:h!=="none"&&h!=="0px"?h:"100%","object-fit":"contain","page-break-inside":"avoid","break-inside":"avoid","box-sizing":"border-box"})}}expand(){const{documentElement:t}=this.document;if(this.#t){const e=this.#s?"height":"width",i=this.#s?"width":"height",s=this.#l.getBoundingClientRect(),n=t.getBoundingClientRect(),r=(this.#s?0:this.#c?n.right-s.right:s.left-n.left)+s[e],o=Math.ceil(r/this.#n)*this.#n;this.#r.style.padding="0",this.#i.style[e]=`${o}px`,this.#r.style[e]=`${o+this.#n*2}px`,this.#i.style[i]="100%",this.#r.style[i]="100%",t.style[e]=`${this.#n}px`,this.#e&&(this.#e.element.style.margin="0",this.#e.element.style.left=this.#s?"0":`${this.#n}px`,this.#e.element.style.top=this.#s?`${this.#n}px`:"0",this.#e.element.style[e]=`${o}px`,this.#e.redraw())}else{const e=this.#s?"width":"height",i=this.#s?"height":"width",s=t.getBoundingClientRect()[e],{margin:n}=this.#a,r=this.#s?`0 ${n}px`:`${n}px 0`;this.#r.style.padding=r,this.#i.style[e]=`${s}px`,this.#r.style[e]=`${s}px`,this.#i.style[i]="100%",this.#r.style[i]="100%",this.#e&&(this.#e.element.style.margin=r,this.#e.element.style.left="0",this.#e.element.style.top="0",this.#e.element.style[e]=`${s}px`,this.#e.redraw())}this.onExpand()}set overlayer(t){this.#e=t,this.#r.append(t.element)}get overlayer(){return this.#e}destroy(){this.document&&this.#o.unobserve(this.document.body)}}class I extends HTMLElement{static observedAttributes=["flow","gap","margin","max-inline-size","max-block-size","max-column-count"];#o=this.attachShadow({mode:"closed"});#r=new ResizeObserver(()=>this.render());#i;#l;#e;#s;#c;#t;#n=!1;#a=!1;#g=0;#d=-1;#h=0;#E=!1;#v=!1;#S;#T=new WeakMap;#k=matchMedia("(prefers-color-scheme: dark)");#_;#m;#y;#z;#L;constructor(){super(),this.#o.innerHTML=`<style>
2
+ :host {
3
+ display: block;
4
+ container-type: size;
5
+ }
6
+ :host, #top {
7
+ box-sizing: border-box;
8
+ position: relative;
9
+ overflow: hidden;
10
+ width: 100%;
11
+ height: 100%;
12
+ }
13
+ #top {
14
+ --_gap: 7%;
15
+ --_margin: 48px;
16
+ --_max-inline-size: 720px;
17
+ --_max-block-size: 1440px;
18
+ --_max-column-count: 2;
19
+ --_max-column-count-portrait: 1;
20
+ --_max-column-count-spread: var(--_max-column-count);
21
+ --_half-gap: calc(var(--_gap) / 2);
22
+ --_max-width: calc(var(--_max-inline-size) * var(--_max-column-count-spread));
23
+ --_max-height: var(--_max-block-size);
24
+ display: grid;
25
+ grid-template-columns:
26
+ minmax(var(--_half-gap), 1fr)
27
+ var(--_half-gap)
28
+ minmax(0, calc(var(--_max-width) - var(--_gap)))
29
+ var(--_half-gap)
30
+ minmax(var(--_half-gap), 1fr);
31
+ grid-template-rows:
32
+ minmax(var(--_margin), 1fr)
33
+ minmax(0, var(--_max-height))
34
+ minmax(var(--_margin), 1fr);
35
+ &.vertical {
36
+ --_max-column-count-spread: var(--_max-column-count-portrait);
37
+ --_max-width: var(--_max-block-size);
38
+ --_max-height: calc(var(--_max-inline-size) * var(--_max-column-count-spread));
39
+ }
40
+ @container (orientation: portrait) {
41
+ & {
42
+ --_max-column-count-spread: var(--_max-column-count-portrait);
43
+ }
44
+ &.vertical {
45
+ --_max-column-count-spread: var(--_max-column-count);
46
+ }
47
+ }
48
+ }
49
+ #background {
50
+ grid-column: 1 / -1;
51
+ grid-row: 1 / -1;
52
+ }
53
+ #container {
54
+ grid-column: 2 / 5;
55
+ grid-row: 2;
56
+ overflow: hidden;
57
+ }
58
+ :host([flow="scrolled"]) #container {
59
+ grid-column: 1 / -1;
60
+ grid-row: 1 / -1;
61
+ overflow: auto;
62
+ }
63
+ #header {
64
+ grid-column: 3 / 4;
65
+ grid-row: 1;
66
+ }
67
+ #footer {
68
+ grid-column: 3 / 4;
69
+ grid-row: 3;
70
+ align-self: end;
71
+ }
72
+ #header, #footer {
73
+ display: grid;
74
+ height: var(--_margin);
75
+ }
76
+ :is(#header, #footer) > * {
77
+ display: flex;
78
+ align-items: center;
79
+ min-width: 0;
80
+ }
81
+ :is(#header, #footer) > * > * {
82
+ width: 100%;
83
+ overflow: hidden;
84
+ white-space: nowrap;
85
+ text-overflow: ellipsis;
86
+ text-align: center;
87
+ font-size: .75em;
88
+ opacity: .6;
89
+ }
90
+ </style>
91
+ <div id="top">
92
+ <div id="background" part="filter"></div>
93
+ <div id="header"></div>
94
+ <div id="container"></div>
95
+ <div id="footer"></div>
96
+ </div>
97
+ `,this.#i=this.#o.getElementById("top"),this.#l=this.#o.getElementById("background"),this.#e=this.#o.getElementById("container"),this.#s=this.#o.getElementById("header"),this.#c=this.#o.getElementById("footer"),this.#r.observe(this.#e),this.#e.addEventListener("scroll",()=>this.dispatchEvent(new Event("scroll"))),this.#e.addEventListener("scroll",k(()=>{this.scrolled&&(this.#E?this.#E=!1:this.#b("scroll"))},250));const t={passive:!1};this.addEventListener("touchstart",this.#M.bind(this),t),this.addEventListener("touchmove",this.#A.bind(this),t),this.addEventListener("touchend",this.#$.bind(this)),this.addEventListener("load",({detail:{doc:i}})=>{i.addEventListener("touchstart",this.#M.bind(this),t),i.addEventListener("touchmove",this.#A.bind(this),t),i.addEventListener("touchend",this.#$.bind(this))}),this.addEventListener("relocate",({detail:i})=>{i.reason==="selection"?z(this.#h,0):i.reason==="navigation"&&(this.#h===1?z(i.range,1):typeof this.#h=="number"?z(i.range,-1):z(this.#h,-1))});const e=k((i,s)=>{if(!s.rangeCount)return;const n=s.getRangeAt(0),r=$(s);r&&n.compareBoundaryPoints(Range.START_TO_START,i)<0?this.prev():!r&&n.compareBoundaryPoints(Range.END_TO_END,i)>0&&this.next()},700);this.addEventListener("load",({detail:{doc:i}})=>{let s=!1;i.addEventListener("pointerdown",()=>s=!0),i.addEventListener("pointerup",()=>s=!1);let n=!1;i.addEventListener("keydown",()=>n=!0),i.addEventListener("keyup",()=>n=!1),i.addEventListener("selectionchange",()=>{if(this.scrolled)return;const r=this.#L;if(!r)return;const o=i.getSelection();if(o.rangeCount){if(s&&o.type==="Range")e(r,o);else if(n){const h=o.getRangeAt(0).cloneRange();$(o)||h.collapse(),this.#x(h)}}}),i.addEventListener("focusin",r=>this.scrolled?null:requestAnimationFrame(()=>this.#x(r.target)))}),this.#_=()=>{this.#t&&(this.#l.style.background=S(this.#t.document))},this.#k.addEventListener("change",this.#_)}attributeChangedCallback(t,e,i){switch(t){case"flow":this.render();break;case"gap":case"margin":case"max-block-size":case"max-column-count":this.#i.style.setProperty("--_"+t,i);break;case"max-inline-size":this.#i.style.setProperty("--_"+t,i),this.render();break}}open(t){var e;this.bookDir=t.dir,this.sections=t.sections,(e=t.transformTarget)==null||e.addEventListener("data",({detail:i})=>{if(i.type!=="text/css")return;const s=innerWidth,n=innerHeight;i.data=Promise.resolve(i.data).then(r=>r.replace(new RegExp("(?<=[{\\s;])-epub-","gi"),"").replace(/(\d*\.?\d+)vw/gi,(o,h)=>parseFloat(h)*s/100+"px").replace(/(\d*\.?\d+)vh/gi,(o,h)=>parseFloat(h)*n/100+"px").replace(/page-break-(after|before|inside)\s*:/gi,(o,h)=>`-webkit-column-break-${h}:`).replace(/break-(after|before|inside)\s*:\s*(avoid-)?page/gi,(o,h,l)=>`break-${h}: ${l??""}column`))})}#B(){return this.#t&&(this.#t.destroy(),this.#e.removeChild(this.#t.element)),this.#t=new q({container:this,onExpand:()=>this.#x(this.#h)}),this.#e.append(this.#t.element),this.#t}#R({vertical:t,rtl:e,background:i}){this.#n=t,this.#a=e,this.#i.classList.toggle("vertical",t),this.#l.style.background=i;const{width:s,height:n}=this.#e.getBoundingClientRect(),r=t?n:s,o=getComputedStyle(this.#i),h=parseFloat(o.getPropertyValue("--_max-inline-size")),l=parseInt(o.getPropertyValue("--_max-column-count-spread")),u=parseFloat(o.getPropertyValue("--_margin"));this.#g=u;const p=parseFloat(o.getPropertyValue("--_gap"))/100,c=-p/(p-1)*r,d=this.getAttribute("flow");if(d==="scrolled"){this.setAttribute("dir",t?"rtl":"ltr"),this.#i.style.padding="0";const v=h;return this.heads=null,this.feet=null,this.#s.replaceChildren(),this.#c.replaceChildren(),{flow:d,margin:u,gap:c,columnWidth:v}}const m=Math.min(l,Math.ceil(r/h)),g=r/m-c;this.setAttribute("dir",e?"rtl":"ltr");const f=t?Math.min(2,Math.ceil(s/h)):m,x={gridTemplateColumns:`repeat(${f}, 1fr)`,gap:`${c}px`,direction:this.bookDir==="rtl"?"rtl":"ltr"};Object.assign(this.#s.style,x),Object.assign(this.#c.style,x);const w=P(f,"head"),T=P(f,"foot");return this.heads=w.map(v=>v.children[0]),this.feet=T.map(v=>v.children[0]),this.#s.replaceChildren(...w),this.#c.replaceChildren(...T),{height:n,width:s,margin:u,gap:c,columnWidth:g}}render(){this.#t&&(this.#t.render(this.#R({vertical:this.#n,rtl:this.#a})),this.#x(this.#h))}get scrolled(){return this.getAttribute("flow")==="scrolled"}get scrollProp(){const{scrolled:t}=this;return this.#n?t?"scrollLeft":"scrollTop":t?"scrollTop":"scrollLeft"}get sideProp(){const{scrolled:t}=this;return this.#n?t?"width":"height":t?"height":"width"}get size(){return this.#e.getBoundingClientRect()[this.sideProp]}get viewSize(){return this.#t.element.getBoundingClientRect()[this.sideProp]}get start(){return Math.abs(this.#e[this.scrollProp])}get end(){return this.start+this.size}get page(){return Math.floor((this.start+this.end)/2/this.size)}get pages(){return Math.round(this.viewSize/this.size)}scrollBy(t,e){const i=this.#n?e:t,s=this.#e,{scrollProp:n}=this,[r,o,h]=this.#m,l=this.#a,u=l?r-h:r-o,p=l?r+o:r+h;s[n]=Math.max(u,Math.min(p,s[n]+i))}snap(t,e){const i=this.#n?e:t,[s,n,r]=this.#m,{start:o,end:h,pages:l,size:u}=this,p=Math.abs(s)-n,c=Math.abs(s)+r,d=i*(this.#a?-u:u),m=Math.floor(Math.max(p,Math.min(c,(o+h)/2+(isNaN(d)?0:d)))/u);this.#f(m,"snap").then(()=>{const g=m<=0?-1:m>=l-1?1:null;if(g)return this.#C({index:this.#u(g),anchor:g<0?()=>1:()=>0})})}#M(t){const e=t.changedTouches[0];this.#y={x:e==null?void 0:e.screenX,y:e==null?void 0:e.screenY,t:t.timeStamp,vx:0,xy:0}}#A(t){const e=this.#y;if(e.pinched||(e.pinched=globalThis.visualViewport.scale>1,this.scrolled||e.pinched))return;if(t.touches.length>1){this.#z&&t.preventDefault();return}t.preventDefault();const i=t.changedTouches[0],s=i.screenX,n=i.screenY,r=e.x-s,o=e.y-n,h=t.timeStamp-e.t;e.x=s,e.y=n,e.t=t.timeStamp,e.vx=r/h,e.vy=o/h,this.#z=!0,this.scrollBy(r,o)}#$(){this.#z=!1,!this.scrolled&&requestAnimationFrame(()=>{globalThis.visualViewport.scale===1&&this.snap(this.#y.vx,this.#y.vy)})}#w(){if(this.scrolled){const e=this.viewSize,i=this.#g;return this.#n?({left:s,right:n})=>({left:e-n-i,right:e-s-i}):({top:s,bottom:n})=>({left:s+i,right:n+i})}const t=this.pages*this.size;return this.#a?({left:e,right:i})=>({left:t-i,right:t-e}):this.#n?({top:e,bottom:i})=>({left:e,right:i}):e=>e}async#O(t,e){if(this.scrolled){const s=this.#w()(t).left-this.#g;return this.#p(s,e)}const i=this.#w()(t).left;return this.#f(Math.floor(i/this.size)+(this.#a?-1:1),e)}async#p(t,e,i){const s=this.#e,{scrollProp:n,size:r}=this;if(s[n]===t){this.#m=[t,this.atStart?0:r,this.atEnd?0:r],this.#b(e);return}if(this.scrolled&&this.#n&&(t=-t),(e==="snap"||i)&&this.hasAttribute("animated"))return O(s[n],t,300,B,o=>s[n]=o).then(()=>{this.#m=[t,this.atStart?0:r,this.atEnd?0:r],this.#b(e)});s[n]=t,this.#m=[t,this.atStart?0:r,this.atEnd?0:r],this.#b(e)}async#f(t,e,i){const s=this.size*(this.#a?-t:t);return this.#p(s,e,i)}async scrollToAnchor(t,e){return this.#x(t,e?"selection":"navigation")}async#x(t,e="anchor"){var o,h;this.#h=t;const i=(h=(o=F(t))==null?void 0:o.getClientRects)==null?void 0:h.call(o);if(i){const l=Array.from(i).find(u=>u.width>0&&u.height>0)||i[0];if(!l)return;await this.#O(l,e);return}if(this.scrolled){await this.#p(t*this.viewSize,e);return}const{pages:s}=this;if(!s)return;const n=s-2,r=Math.round(t*(n-1));await this.#f(r+1,e)}#F(){if(this.scrolled)return A(this.#t.document,this.start+this.#g,this.end-this.#g,this.#w());const t=this.#a?-this.size:this.size;return A(this.#t.document,this.start-t,this.end-t,this.#w())}#b(t){const e=this.#F();this.#L=e,t!=="selection"&&t!=="navigation"&&t!=="anchor"?this.#h=e:this.#E=!0;const i=this.#d,s={reason:t,range:e,index:i};if(this.scrolled)s.fraction=this.start/this.viewSize;else if(this.pages>0){const{page:n,pages:r}=this;this.#s.style.visibility=n>1?"visible":"hidden",s.fraction=(n-1)/(r-2),s.size=1/(r-2)}this.dispatchEvent(new CustomEvent("relocate",{detail:s}))}async#P(t){var h,l;const{index:e,src:i,anchor:s,onLoad:n,select:r}=await t;this.#d=e;const o=(l=(h=this.#t)==null?void 0:h.document)==null?void 0:l.hasFocus();if(i){const u=this.#B(),p=d=>{if(d.head){const m=d.createElement("style");d.head.prepend(m);const g=d.createElement("style");d.head.append(g),this.#T.set(d,[m,g])}n==null||n({doc:d,index:e})},c=this.#R.bind(this);await u.load(i,p,c),this.dispatchEvent(new CustomEvent("create-overlayer",{detail:{doc:u.document,index:e,attach:d=>u.overlayer=d}})),this.#t=u}await this.scrollToAnchor((typeof s=="function"?s(this.#t.document):s)??0,r),o&&this.focusView()}#I(t){return t>=0&&t<=this.sections.length-1}async#C({index:t,anchor:e,select:i}){if(t===this.#d)await this.#P({index:t,anchor:e,select:i});else{const s=this.#d,n=r=>{var o,h;(h=(o=this.sections[s])==null?void 0:o.unload)==null||h.call(o),this.setStyles(this.#S),this.dispatchEvent(new CustomEvent("load",{detail:r}))};await this.#P(Promise.resolve(this.sections[t].load()).then(r=>({index:t,src:r,anchor:e,onLoad:n,select:i})).catch(r=>(console.warn(r),console.warn(new Error(`Failed to load section ${t}`)),{})))}}async goTo(t){if(this.#v)return;const e=await t;if(this.#I(e.index))return this.#C(e)}#V(t){if(!this.#t)return!0;if(this.scrolled)return this.start>0?this.#p(Math.max(0,this.start-(t??this.size)),null,!0):!0;if(this.atStart)return;const e=this.page-1;return this.#f(e,"page",!0).then(()=>e<=0)}#D(t){if(!this.#t)return!0;if(this.scrolled)return this.viewSize-this.end>2?this.#p(Math.min(this.viewSize,t?this.start+t:this.end),null,!0):!0;if(this.atEnd)return;const e=this.page+1,i=this.pages;return this.#f(e,"page",!0).then(()=>e>=i-1)}get atStart(){return this.#u(-1)==null&&this.page<=1}get atEnd(){return this.#u(1)==null&&this.page>=this.pages-2}#u(t){var e;for(let i=this.#d+t;this.#I(i);i+=t)if(((e=this.sections[i])==null?void 0:e.linear)!=="no")return i}async#N(t,e){if(this.#v)return;this.#v=!0;const i=t===-1,s=await(i?this.#V(e):this.#D(e));s&&await this.#C({index:this.#u(t),anchor:i?()=>1:()=>0}),(s||!this.hasAttribute("animated"))&&await N(100),this.#v=!1}prev(t){return this.#N(-1,t)}next(t){return this.#N(1,t)}prevSection(){return this.goTo({index:this.#u(-1)})}nextSection(){return this.goTo({index:this.#u(1)})}firstSection(){const t=this.sections.findIndex(e=>e.linear!=="no");return this.goTo({index:t})}lastSection(){const t=this.sections.findLastIndex(e=>e.linear!=="no");return this.goTo({index:t})}getContents(){return this.#t?[{index:this.#d,overlayer:this.#t.overlayer,doc:this.#t.document}]:[]}setStyles(t){var n,r,o,h,l;this.#S=t;const e=this.#T.get((n=this.#t)==null?void 0:n.document);if(!e)return;const[i,s]=e;if(Array.isArray(t)){const[u,p]=t;i.textContent=u,s.textContent=p}else s.textContent=t;requestAnimationFrame(()=>this.#l.style.background=S(this.#t.document)),(l=(h=(o=(r=this.#t)==null?void 0:r.document)==null?void 0:o.fonts)==null?void 0:h.ready)==null||l.then(()=>this.#t.expand())}focusView(){this.#t.document.defaultView.focus()}destroy(){var t,e;this.#r.unobserve(this),this.#t.destroy(),this.#t=null,(e=(t=this.sections[this.#d])==null?void 0:t.unload)==null||e.call(t),this.#k.removeEventListener("change",this.#_)}}customElements.define("foliate-paginator",I);export{I as Paginator};