From 0a453771367577cd4ece6bbe175c2edc0699ec14 Mon Sep 17 00:00:00 2001 From: troyeguo <13820674+troyeguo@users.noreply.github.com> Date: Sat, 24 Feb 2024 17:27:31 +0800 Subject: [PATCH] fix bug --- main.js | 46 ++++++++++++++- public/lib/kookit/kookit.min.js | 2 +- src/components/imageViewer/component.tsx | 2 +- src/constants/settingList.tsx | 2 +- src/containers/htmlViewer/component.tsx | 11 ++-- .../panels/operationPanel/component.tsx | 56 +++++++++++++++---- src/pages/pdfReader/component.tsx | 9 ++- src/pages/pdfReader/interface.tsx | 1 + src/utils/fileUtils/bookUtil.tsx | 45 ++++++++------- src/utils/readUtils/linkUtil.tsx | 4 -- 10 files changed, 130 insertions(+), 48 deletions(-) diff --git a/main.js b/main.js index 46f6f766..f09f98b2 100644 --- a/main.js +++ b/main.js @@ -1,6 +1,7 @@ const { app, BrowserWindow, + BrowserView, Menu, ipcMain, dialog, @@ -16,6 +17,7 @@ const configDir = app.getPath("userData"); const { ra } = require("./edge-tts"); const dirPath = path.join(configDir, "uploads"); let mainWin; +let mainView const singleInstance = app.requestSingleInstanceLock(); var filePath = null; if (process.platform != "darwin" && process.argv.length >= 2) { @@ -69,12 +71,12 @@ const createMainWin = () => { mainWin = null; }); ipcMain.handle("open-book", (event, config) => { - let { url, isMergeWord, isFullscreen, isPreventSleep } = config; + let { url, isMergeWord, isAutoFullscreen, isPreventSleep } = config; options.webPreferences.nodeIntegrationInSubFrames = true; store.set({ url, isMergeWord: isMergeWord ? isMergeWord : "no", - isFullscreen: isFullscreen ? isFullscreen : "no", + isAutoFullscreen: isAutoFullscreen ? isAutoFullscreen : "no", isPreventSleep: isPreventSleep ? isPreventSleep : "no", }); let id; @@ -83,7 +85,7 @@ const createMainWin = () => { console.log(powerSaveBlocker.isStarted(id)); } - if (isFullscreen === "yes") { + if (isAutoFullscreen === "yes") { readerWindow = new BrowserWindow(options); readerWindow.loadURL(url); readerWindow.maximize(); @@ -480,6 +482,44 @@ const createMainWin = () => { createMainWin(); } }); + ipcMain.handle("new-tab", (event, config) => { + if (mainWin) { + mainView = new BrowserView(options) + mainWin.setBrowserView(mainView) + let [width, height] = mainWin.getSize() + mainView.setBounds({ x: 0, y: 0, width: width, height: height }) + console.log(config.url); + mainView.webContents.loadURL(config.url) + } + }); + ipcMain.handle("reload-tab", (event, config) => { + if (mainWin && mainView) { + mainView.webContents.reload() + } + }); + ipcMain.handle("adjust-tab-size", (event, config) => { + if (mainWin && mainView) { + let [width, height] = mainWin.getSize() + mainView.setBounds({ x: 0, y: 0, width: width, height: height }) + } + }); + ipcMain.handle("exit-tab", (event, message) => { + if (mainWin && mainView) { + mainWin.setBrowserView(null) + } + }); + ipcMain.handle("enter-tab-fullscreen", () => { + if (mainWin && mainView) { + mainWin.setFullScreen(true); + console.log("enter full"); + } + }); + ipcMain.handle("exit-tab-fullscreen", () => { + if (mainWin && mainView) { + mainWin.setFullScreen(false); + console.log("exit full"); + } + }); ipcMain.handle("enter-fullscreen", () => { if (readerWindow) { readerWindow.setFullScreen(true); diff --git a/public/lib/kookit/kookit.min.js b/public/lib/kookit/kookit.min.js index 11272c13..1ff87fb9 100644 --- a/public/lib/kookit/kookit.min.js +++ b/public/lib/kookit/kookit.min.js @@ -1,4 +1,4 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Kookit={})}(this,function(e){"use strict";function g(e,o,a,l){return new(a=a||Promise)(function(i,t){function r(e){try{s(l.next(e))}catch(e){t(e)}}function n(e){try{s(l.throw(e))}catch(e){t(e)}}function s(e){var t;e.done?i(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(r,n)}s((l=l.apply(e,o||[])).next())})}const y=e=>e?parseFloat(e+""):0,p=i=>g(void 0,void 0,void 0,function*(){let t="";if(i.load){let e=yield fetch(yield i.load()).then(e=>e.blob());t=yield e.text()}return i.loadAsset&&(t=yield r(t,i.loadAsset)),n(t)}),u=e=>Array.from(e.querySelectorAll("img, image")),r=(n,s)=>g(void 0,void 0,void 0,function*(){let e=(new DOMParser).parseFromString(n,"text/html"),t=u(e);for(let e=0;e{var t=(new DOMParser).parseFromString(e,"text/html");let i=u(t);if(0===i.length)return e;for(let e=0;e{var i=document.createElement("iframe");i.style.width="100%",i.style.border="0",i.style.margin="0",i.style.padding="0",i.style.minHeight="calc(100% - 2px)",i.style.fontSize="100%",i.style.font="inherit",i.scrolling="no",i.tabIndex=0,i.style.verticalAlign="baseline",e.innerHTML="",e.appendChild(i)},l=i=>g(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){t=t.contentDocument;if(t)return 1===parseInt(t.body.scrollWidth/t.body.clientWidth+"")&&(yield new Promise(e=>setTimeout(e,1e3))),{totalPage:"scroll"===i?1:parseInt(t.body.scrollWidth/t.body.clientWidth+"")+1,currentPage:parseInt(y(t.body.scrollLeft)/t.body.clientWidth+"")+1}}}}),m=()=>{let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;if(e){var i=e.querySelectorAll("a, article, cite, div, li, p, span, pre, table, bold, body, html");for(let e=0;eg(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let n=t.contentDocument;if(n){var s,t=Math.floor(c.clientWidth/12),o=t%2==0?t:t-1;for(s of n.querySelectorAll("img, image")){var a,l=s.parentElement;let e=0,t=0,i=s.naturalWidth,r=s.naturalHeight;"image"===s.tagName&&(a=yield(t=>g(void 0,void 0,void 0,function*(){const e=new Image;return e.src=t,yield e.decode(),e}))(s.getAttribute("xlink:href")),i=a.naturalWidth,r=a.naturalHeight),h.startsWith("CB")&&"scroll"===d?t=l.offsetWidth:h.startsWith("CB")&&"single"===d?(e=c.clientHeight,t=c.clientWidth):i&&r?(r/i>l.clientHeight/l.clientWidth?(e=l.clientHeight,t=parseInt(e*i/r+"")):(t=l.clientWidth,e=parseInt(t*r/i+"")),e>n.body.clientHeight&&(t=parseInt(t*(n.body.clientHeight/e)+""),e=n.body.clientHeight)):e=l&&l.clientWidth&&0r||e/t>r/i?e=t*(r/i):t=e*(i/r)),(t||e)&&s.setAttribute("style",s.getAttribute("style")+";"+`max-width: ${0{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){let t=n.contentDocument;if(t){let e=t.createElement("style");e.id="default-style",e.textContent="p,empty-line{display: inherit;margin-block-start: inherit;margin-block-end: inherit;margin-inline-start: inherit;margin-inline-end: inherit;}body{margin: 0px}",t.head.appendChild(e),"scroll"!==r&&(n="double"===r?2:1,r=(r=Math.floor(i.clientWidth/12))%2==0?r:r-1,t.body.setAttribute("style",`width: auto;height: 100%;overflow-y: hidden;overflow-X: hidden;padding-left: 0px;padding-right: 0px;margin: 0px;box-sizing: border-box;max-width: inherit;column-fill: auto;column-gap: ${r}px;column-count: 12;column-width: ${(i.clientWidth-r)/n}px;`))}}}};class f{constructor(e){this.book=e,this.chapterList=[],this.flattenChapters=[],this.chapterDocList=[]}getChapter(e){return g(this,void 0,void 0,function*(){return this.chapterList=e?yield Promise.all(e.map(t=>g(this,void 0,void 0,function*(){let e=-1;try{e=t.href&&(yield this.book.resolveHref(t.href))?(yield this.book.resolveHref(t.href)).index:-1}catch(e){console.log(e)}return{label:t.label||e,href:t.href,index:e,subitems:t.subitems?yield this.getChapter(t.subitems):[]}}))):yield Promise.all(this.book.sections.map((e,t)=>g(this,void 0,void 0,function*(){return{label:e.label||t,href:e.href||"",index:t,subitems:e.subitems?yield this.getChapter(e.subitems):[]}}))),this.flattenChapters=this.flatChapter(this.chapterList),this.chapterList})}getChapterDoc(){return g(this,void 0,void 0,function*(){const i=this.flattenChapters.map(e=>e.index);return this.book.sections.map((e,t)=>-1g(this,void 0,void 0,function*(){const t=this.book.metadata;try{var i=yield this.book.getCover(),e=new FileReader;e.readAsDataURL(i),e.onloadend=()=>{r({name:t.title,author:t.author?t.author[0].name:"",description:t.description,publisher:t.publisher,cover:e.result})}}catch(e){i=t.author&&t.author[0]&&t.author[0].name?t.author[0].name:t.author&&t.author[0]?t.author[0]:t.author||"";r({name:t.title,author:i,description:t.description,publisher:t.publisher,cover:""})}}))}}const i=(e,r)=>e.map((e,t,i)=>r(e,t,i)?t:null).filter(e=>null!=e),a=(r,e)=>[-1,...e,r.length].reduce(({xs:e,a:t},i)=>({xs:e?.concat([r.slice(t+1,i)])??[],a:i}),{}).xs,c=(e,t)=>e.slice(0,-1).concat([e[e.length-1].concat(t[0])]).concat(t.slice(1)),d=/\d/,h=/^epubcfi\((.*)\)$/,v=e=>e.replace(/[\^[\](),;=]/g,"^$&"),t=e=>h.test(e)?e:`epubcfi(${e})`,w=(e,t)=>i(e,([e])=>e===t),x=e=>{const t=[];let i;for(var[r,n]of e){if("/"===r)t.push({index:n});else{const s=t[t.length-1];if(":"===r)s.offset=n;else if("~"===r)s.temporal=n;else if("@"===r)s.spatial=(s.spatial??[]).concat(n);else if(";s"===r)s.side=n;else if("["===r){if("/"!==i||!n){s.text=(s.text??[]).concat(n);continue}s.id=n}}i=r}return t},C=e=>a(e,w(e,"!")).map(x),L=e=>{var t=(e=>{const t=[];let i,r,n="";var s=e=>(t.push(e),i=null,n=""),o=e=>(n+=e,r=!1);for(const a of Array.from(e.trim()).concat(""))if("^"!==a||r){if("!"===i)s(["!"]);else if(","===i)s([","]);else if("/"===i||":"===i){if(d.test(a)){o(a);continue}s([i,parseInt(n)])}else if("~"===i){if(d.test(a)||"."===a){o(a);continue}s(["~",parseFloat(n)])}else if("@"===i){if(":"===a){s(["@",parseFloat(n)]),i="@";continue}if(d.test(a)||"."===a){o(a);continue}s(["@",parseFloat(n)])}else{if("["===i){";"!==a||r?","!==a||r?"]"!==a||r?o(a):s(["[",n]):(s(["[",n]),i="["):(s(["[",n]),i=";");continue}if(i?.startsWith(";")){"="!==a||r?";"!==a||r?"]"!==a||r?o(a):s([i,n]):(s([i,n]),i=";"):(i=`;${n}`,n="");continue}}"/"!==a&&":"!==a&&"~"!==a&&"@"!==a&&"["!==a&&"!"!==a&&","!==a||(i=a)}else r=!0;return t})((i=e).match(h)?.[1]??i),e=w(t,",");if(!e.length)return C(t);var[i,t,e]=a(t,e).map(C);return{parent:i,start:t,end:e}},k=({index:e,id:t,offset:i,temporal:r,spatial:n,text:s,side:o})=>{var a=o?`;s=${o}`:"";return`/${e}`+(t?`[${v(t)}${a}]`:"")+(null!=i&&e%2?`:${i}`:"")+(r?`~${r}`:"")+(n?`@${n.join(":")}`:"")+(s||!t&&o?"["+(s?.map(v)?.join(",")??"")+a+"]":"")},T=e=>e.parent?[e.parent,e.start,e.end].map(T).join(","):e.map(e=>e.map(k).join("")).join("!"),S=e=>t(T(e)),A=(e,t)=>"string"==typeof e?S(A(L(e),t)):e.parent?c(e.parent,e[t?"end":"start"]):e,B=({nodeType:e})=>3===e||4===e,E=({nodeType:e})=>1===e,M=e=>{const t=Array.from(e.childNodes).filter(e=>B(e)||E(e)).reduce((e,t)=>{let i=e[e.length-1];return i?B(t)?Array.isArray(i)?i.push(t):B(i)?e[e.length-1]=[i,t]:e.push(t):E(i)?e.push(null,t):e.push(t):e.push(t),e},[]);return E(t[0])&&t.unshift("first"),E(t[t.length-1])&&t.push("last"),t.unshift("before"),t.push("after"),t},I=(e,t)=>e?M(e)[t]:null,R=(e,t)=>{var i,r=t[t.length-1]["id"];if(r){r=e.ownerDocument.getElementById(r);if(r)return{node:r,offset:0}}for({index:i}of t){var n=I(e,i);if("first"===n)return{node:e.firstChild??e};if("last"===n)return{node:e.lastChild??e};if("before"===n)return{node:e,before:!0};if("after"===n)return{node:e,after:!0};e=n}var s=t[t.length-1]["offset"];if(!Array.isArray(e))return{node:e,offset:s};let o=0;for(const l of e){var a=l.nodeValue["length"];if(o+a>=s)return{node:l,offset:s-o};o+=a}},D=(t,i)=>{var{parentNode:e,id:r}=t;const n=M(e);var s=n.findIndex(e=>Array.isArray(e)?e.some(e=>e===t):e===t),o=n[s];if(Array.isArray(o)){let e=0;for(const a of o){if(a===t){e+=i;break}e+=a.nodeValue.length}i=e}s={id:r,index:s,offset:i};return e!==t.ownerDocument.documentElement?D(e).concat(s):[s]},N=(e,t)=>R(e.documentElement,A(t)).node,O={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"},H={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)/},U=e=>e.toLowerCase().replace(/[-:](.)/g,(e,t)=>t.toUpperCase()),F=e=>e?e.trim().replace(/\s{2,}/g," "):"",$=(t,i,e)=>e?e=>e.getAttribute(t)?.split(/\s/)?.includes(i):"function"==typeof i?e=>i(e.getAttribute(t)):e=>e.getAttribute(t)===i,P=(...e)=>t=>t?Object.fromEntries(e.map(e=>[U(e),t.getAttribute(e)])):null,z=e=>F(e?.textContent),j=(e,i)=>{e=e.lookupNamespaceURI(null)===i||e.lookupPrefix(i);const r=e?(e,t)=>e=>e.namespaceURI===i&&e.localName===t:(e,t)=>e=>e.localName===t;return{$:(e,t)=>[...e.children].find(r(e,t)),$$:(e,t)=>[...e.children].filter(r(e,t)),$$$:e?(e,t)=>[...e.getElementsByTagNameNS(i,t)]:(e,t)=>[...e.getElementsByTagName(i,t)]}},W=(t,e)=>{try{if(e.includes(":"))return new URL(t,e);var i="whatever://whatever/";return decodeURI(new URL(t,i+e).href.replace(i,""))}catch(e){return console.warn(e),t}},X=e=>/^(?!blob)\w+:/i.test(e),q=async(e,t,i)=>{const r=[];e.replace(t,(...e)=>(r.push(e),null));const n=[];for(const s of r)n.push(await i(...s));return e.replace(t,()=>n.shift())},K=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&");var G={attrs:["dir","xml:lang"]},J={name:"alternate-script",many:!0,...G,props:["file-as"]},Z={many:!0,...G,props:[{name:"role",many:!0,attrs:["scheme"]},"file-as",J]};const V=[{name:"title",many:!0,...G,props:["title-type","display-seq","file-as",J]},{name:"identifier",many:!0,props:[{name:"identifier-type",attrs:["scheme"]}]},{name:"language",many:!0},{name:"creator",...Z},{name:"contributor",...Z},{name:"publisher",...G,props:["file-as",J]},{name:"description",...G,props:[J]},{name:"rights",...G,props:[J]},{name:"date"},{name:"dcterms:modified",type:"meta"},{name:"subject",many:!0,...G,props:["term","authority",J]},{name:"belongs-to-collection",type:"meta",many:!0,...G,props:["collection-type","group-position","dcterms:identifier","file-as",J,{name:"belongs-to-collection",recursive:!0}]}],_=(e,s=e=>e)=>{const{$:o,$$:i,$$$:t}=j(e,O.XHTML),r=n=>e=>{const t=o(e,"a")??o(e,"span");var i=o(e,"ol"),e=(e=t?.getAttribute("href"))?decodeURI(s(e)):null;const r={label:z(t)||t?.getAttribute("title"),href:e,subitems:a(i)};return n&&(r.type=t?.getAttributeNS(O.EPUB,"type")?.split(/\s/)),r},a=(e,t)=>e?i(e,"li").map(r(t)):null;var n=(e,t)=>a(o(e,"ol"),t);let l=null,c=null,d=null,h=[];for(const u of t(e,"nav")){const f=u.getAttributeNS(O.EPUB,"type")?.split(/\s/)??[];f.includes("toc")?l??=n(u):f.includes("page-list")?c??=n(u):f.includes("landmarks")?d??=n(u,!0):h.push({label:z(u.firstElementChild),type:f,list:n(u)})}return{toc:l,pageList:c,landmarks:d,others:h}},Y=(i,s=e=>e)=>{const{$:o,$$:a}=j(i,O.NCX),l=e=>{var t=o(e,"navLabel");const i=o(e,"content");var r=z(t),t=(t=i.getAttribute("src"))?decodeURI(s(t)):null;if("navPoint"!==e.localName)return{label:r,href:t};{const n=a(e,"navPoint");return{label:r,href:t,subitems:n.length?n.map(l):null}}},r=(e,t)=>a(e,t).map(l);var e=(e,t)=>{e=o(i.documentElement,e);return e?r(e,t):null};return{toc:e("navMap","navPoint"),pageList:e("pageList","pageTarget"),others:a(i.documentElement,"navList").map(e=>({label:z(o(e,"navLabel")),list:r(e,"navTarget")}))}},Q=e=>{if(e){var t=e.split(":").map(e=>parseFloat(e));if(3===t.length){var[i,r,n]=t;return 60*i*60+60*r+n}if(2===t.length){var[t,s]=t;return 60*t+s}var[s,e]=e.split(/(?=[^\d.])/);return parseFloat(s)*("h"===e?3600:"min"===e?60:"ms"===e?.001:1)}},ee=(e,r=e=>e)=>{const{$:n,$$$:t}=j(e,O.SMIL);return t(e,"par").map(e=>{var t=n(e,"text")?.getAttribute("src")?.split("#")?.[1];const i=n(e,"audio");return i?{id:t,audio:{src:(e=i.getAttribute("src"))?decodeURI(r(e)):null,clipBegin:Q(i.getAttribute("clipBegin")),clipEnd:Q(i.getAttribute("clipEnd"))}}:{id:t}})},te=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,ie=e=>z(e.getElementById(e.documentElement.getAttribute("unique-identifier"))??e.getElementsByTagNameNS(O.DC,"identifier")[0]),re=async(e,t,i)=>{const r=new Uint8Array(await i.slice(0,t).arrayBuffer());t=Math.min(t,r.length);for(var n=0;n{e=(new TextEncoder).encode(e),e=await globalThis.crypto.subtle.digest("SHA-1",e);return new Uint8Array(e)})=>({"http://www.idpf.org/2008/embedding":{key:e=>t(ie(e).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(e,t)=>re(e,1040,t)},"http://ns.adobe.com/pdf/enc#RC":{key:e=>{const i=(e=>{for(const i of e.getElementsByTagNameNS(O.DC,"identifier")){var[t]=z(i).split(":").slice(-1);if(te.test(t))return t}return""})(e).replaceAll("-","");return Uint8Array.from({length:16},(e,t)=>parseInt(i.slice(2*t,2*t+2),16))},decode:(e,t)=>re(e,1024,t)}});class se{#uris=new Map;#decoders=new Map;#algorithms;constructor(e){this.#algorithms=e}async init(e,t){var i,r;if(e)for({algorithm:i,uri:r}of Array.from(e.getElementsByTagNameNS(O.ENC,"EncryptedData"),e=>({algorithm:e.getElementsByTagNameNS(O.ENC,"EncryptionMethod")[0]?.getAttribute("Algorithm"),uri:e.getElementsByTagNameNS(O.ENC,"CipherReference")[0]?.getAttribute("URI")}))){if(!this.#decoders.has(i)){const n=this.#algorithms[i];if(!n){console.warn("Unknown encryption algorithm");continue}const s=await n.key(t);this.#decoders.set(i,e=>n.decode(s,e))}this.#uris.set(r,i)}}getDecoder(e){return this.#decoders.get(this.#uris.get(e))??(e=>e)}}class oe{constructor({opf:e,resolveHref:r}){this.opf=e;const{$:t,$$:i,$$$:n}=j(e,O.OPF);var s=t(e.documentElement,"manifest");const o=t(e.documentElement,"spine"),a=i(o,"itemref");this.manifest=i(s,"item").map(P("href","id","media-type","properties","media-overlay")).map(e=>(e.href=r(e.href),e.properties=e.properties?.split(/\s/),e)),this.spine=a.map(P("idref","id","linear","properties")).map(e=>(e.properties=e.properties?.split(/\s/),e)),this.pageProgressionDirection=o.getAttribute("page-progression-direction"),this.navPath=this.getItemByProperty("nav")?.href,this.ncxPath=(this.getItemByID(o.getAttribute("toc"))??this.manifest.find(e=>e.mediaType===H.NCX))?.href;s=t(e.documentElement,"guide");s&&(this.guide=i(s,"reference").map(P("type","title","href")).map(({type:e,title:t,href:i})=>({label:t,type:e.split(/\s/),href:r(i)}))),this.cover=this.getItemByProperty("cover-image")??this.getItemByID(n(e,"meta").find($("name","cover"))?.getAttribute("content"))??this.getItemByHref(this.guide?.find(e=>e.type.includes("cover"))?.href),this.cfis=(e=>{const t=[];var i,r,n=e[0]["parentNode"];const s=D(n);for([i,r]of M(n).entries()){var o=e[t.length];r===o&&t.push(S([s.concat({id:o.id,index:i})]))}return t})(a)}getItemByID(t){return this.manifest.find(e=>e.id===t)}getItemByHref(t){return this.manifest.find(e=>e.href===t)}getItemByProperty(t){return this.manifest.find(e=>e.properties?.includes(t))}resolveCFI(e){const t=L(e),i=(t.parent??t).shift();let r=N(this.opf,i);r&&"idref"!==r.nodeName&&(i.at(-1).id=null,r=N(this.opf,i));const n=r?.getAttribute("idref");return{index:this.spine.findIndex(e=>e.idref===n),anchor:e=>((e,t)=>{var i=A(t),r=A(t,!0),t=e.documentElement,i=R(t,i[0]),r=R(t,r[0]);const n=e.createRange();return i.before?n.setStartBefore(i.node):i.after?n.setStartAfter(i.node):n.setStart(i.node,i.offset),r.before?n.setEndBefore(r.node):r.after?n.setEndAfter(r.node):n.setEnd(r.node,r.offset),n})(e,t)}}}class ae{#cache=new Map;#children=new Map;#refCount=new Map;allowScript=!1;constructor({loadText:e,loadBlob:t,resources:i}){this.loadText=e,this.loadBlob=t,this.manifest=i.manifest,this.assets=i.manifest}createURL(e,t,i,r){if(!t)return"";i=URL.createObjectURL(new Blob([t],{type:i}));if(this.#cache.set(e,i),this.#refCount.set(e,1),r){const n=this.#children.get(r);n?n.push(e):this.#children.set(r,[e])}return i}ref(e,t){const i=this.#children.get(t);return i?.includes(e)||(this.#refCount.set(e,this.#refCount.get(e)+1),i?i.push(e):this.#children.set(t,[e])),this.#cache.get(e)}unref(e){if(this.#refCount.has(e)){var t=this.#refCount.get(e)-1;if(t<1){URL.revokeObjectURL(this.#cache.get(e)),this.#cache.delete(e),this.#refCount.delete(e);const i=this.#children.get(e);if(i)for(;i.length;)this.unref(i.pop());this.#children.delete(e)}else this.#refCount.set(e,t)}}async loadItem(e,t=[]){if(!e)return null;const{href:i,mediaType:r}=e;var n=H.JS.test(e.mediaType);if(n&&!this.allowScript)return null;var s=t.at(-1);return this.#cache.has(i)?this.ref(i,s):(n||[H.XHTML,H.HTML,H.CSS,H.SVG].includes(r))&&t.every(e=>e!==i)?this.loadReplaced(e,t):this.createURL(i,await this.loadBlob(i),r,s)}async loadHref(e,t,i=[]){if(X(e))return e;const r=W(e,t);let n=this.manifest.find(e=>e.href===r);return n=n||{href:r,mediaType:""},this.loadItem(n,i.concat(t))}async loadReplaced(e,n=[]){const{href:s,mediaType:i}=e;var r,o=n.at(-1),a=await this.loadText(s);if(!a)return null;if([H.XHTML,H.HTML,H.SVG].includes(i)){let t=(new DOMParser).parseFromString(a,i);if(i===H.XHTML&&t.querySelector("parsererror")&&(console.warn(t.querySelector("parsererror").innerText),e.mediaType=H.HTML,t=(new DOMParser).parseFromString(a,e.mediaType)),[H.XHTML,H.SVG].includes(e.mediaType)){let e=t.firstChild;for(;e instanceof ProcessingInstruction;)e.data&&(r=await q(e.data,/(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,(e,t,i,r)=>this.loadHref(i,s,n).then(e=>`${t}${e}${r}`)),e.replaceWith(t.createProcessingInstruction(e.target,r))),e=e.nextSibling}var l=async(e,t)=>e.setAttribute(t,await this.loadHref(e.getAttribute(t),s,n));for(const d of t.querySelectorAll("link[href]"))await l(d,"href");for(const h of t.querySelectorAll("[src]"))await l(h,"src");for(const u of t.querySelectorAll("[poster]"))await l(u,"poster");for(const f of t.querySelectorAll("object[data]"))await l(f,"data");for(const p of t.querySelectorAll("[*|href]:not([href]"))p.setAttributeNS(O.XLINK,"href",await this.loadHref(p.getAttributeNS(O.XLINK,"href"),s,n));for(const m of t.querySelectorAll("style"))m.textContent&&(m.textContent=await this.replaceCSS(m.textContent,s,n));for(const g of t.querySelectorAll("[style]"))g.setAttribute("style",await this.replaceCSS(g.getAttribute("style"),s,n));const c=(new XMLSerializer).serializeToString(t);return this.createURL(s,c,e.mediaType,o)}const c=i===H.CSS?await this.replaceCSS(a,s,n):await this.replaceString(a,s,n);return this.createURL(s,c,i,o)}async replaceCSS(e,i,r=[]){e=await q(e,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,(e,t)=>this.loadHref(t,i,r).then(e=>`url("${e}")`));const t=await q(e,/@import\s*["']([^"'\n]*?)["']/gi,(e,t)=>this.loadHref(t,i,r).then(e=>`@import "${e}"`)),n=window?.innerWidth??800,s=window?.innerHeight??600;return t.replace(/-epub-/gi,"").replace(/(\d*\.?\d+)vw/gi,(e,t)=>parseFloat(t)*n/100+"px").replace(/(\d*\.?\d+)vh/gi,(e,t)=>parseFloat(t)*s/100+"px").replace(/page-break-(after|before|inside)/gi,(e,t)=>`-webkit-column-break-${t}`)}replaceString(e,o,t=[]){const a=new Map,i=this.assets.map(e=>{if(e.href!==o){var t=((e,t)=>{if(!e)return t;const i=e.replace(/\/$/,"").split("/"),r=t.replace(/\/$/,"").split("/");t=(i.length>r.length?i:r).findIndex((e,t)=>i[t]!==r[t]);return t<0?"":Array(i.length-t).fill("..").concat(r.slice(t)).join("/")})(o.slice(0,o.lastIndexOf("/")+1),e.href),i=encodeURI(t),r="/"+e.href,n=encodeURI(r),n=new Set([t,i,r,n]);for(const s of n)a.set(s,e);return Array.from(n)}}).flat().filter(e=>e);if(!i.length)return e;var r=new RegExp(i.map(K).join("|"),"g");return q(e,r,async e=>this.loadItem(a.get(e.replace(/^\//,"")),t.concat(o)))}unloadItem(e){this.unref(e?.href)}}class le{parser=new DOMParser;#encryption;constructor({loadText:e,loadBlob:t,getSize:i,sha1:r}){this.loadText=e,this.loadBlob=t,this.getSize=i,this.#encryption=new se(ne(r))}#parseXML(e){return e?this.parser.parseFromString(e,H.XML):null}async#loadXML(e){return this.#parseXML(await this.loadText(e))}async init(){const e=await this.#loadXML("META-INF/container.xml");if(!e)throw new Error("Failed to load container file");var t=Array.from(e.getElementsByTagNameNS(O.CONTAINER,"rootfile"),P("full-path","media-type")).filter(e=>"application/oebps-package+xml"===e.mediaType);if(!t.length)throw new Error("No package document defined in container");const i=t[0].fullPath;var r=await this.#loadXML(i);if(!r)throw new Error("Failed to load package document");t=await this.#loadXML("META-INF/encryption.xml");await this.#encryption.init(t,r),this.resources=new oe({opf:r,resolveHref:e=>W(e,i)});const s=new ae({loadText:this.loadText,loadBlob:e=>Promise.resolve(this.loadBlob(e)).then(this.#encryption.getDecoder(e)),resources:this.resources});this.sections=this.resources.spine.map((e,t)=>{var{idref:i,linear:r,properties:e=[]}=e;const n=this.resources.getItemByID(i);return n?{id:this.resources.getItemByID(i)?.href,load:()=>s.loadItem(n),unload:()=>s.unloadItem(n),createDocument:()=>this.loadDocument(n),size:this.getSize(n.href),cfi:this.resources.cfis[t],linear:r,pageSpread:(e=>{for(const t of e){if("page-spread-left"===t||"rendition:page-spread-left"===t)return"left";if("page-spread-right"===t||"rendition:page-spread-right"===t)return"right";if("rendition:page-spread-center"===t)return"center"}})(e),resolveHref:e=>W(e,n.href),loadMediaOverlay:()=>this.loadMediaOverlay(n)}:(console.warn(`Could not find item with ID "${i}" in manifest`),null)}).filter(e=>e);const{navPath:n,ncxPath:o}=this.resources;if(n)try{var a=_(await this.#loadXML(n),e=>W(e,n));this.toc=a.toc,this.pageList=a.pageList,this.landmarks=a.landmarks}catch(e){console.warn(e)}if(!this.toc&&o)try{var l=Y(await this.#loadXML(o),e=>W(e,o));this.toc=l.toc,this.pageList=l.pageList}catch(e){console.warn(e)}this.landmarks??=this.resources.guide;const{metadata:c,rendition:d,media:h}=(e=>{const{$:t,$$:i}=j(e,O.OPF),r=t(e.documentElement,"metadata"),s=Array.from(r.children),l=(o,t)=>{if(!t)return null;const{props:e=[],attrs:i=[]}=o,r=z(t);if(!e.length&&!i.length)return r;var n=t.getAttribute("id");const a=n?s.filter($("refines","#"+n)):[];return Object.fromEntries([["value",r]].concat(e.map(e=>{var{many:t,recursive:i}=e,r="string"==typeof e?e:e.name,n=$("property",r);const s=i?o:e;return[U(r),t?a.filter(n).map(e=>l(s,e)):l(s,a.find(n))]})).concat(i.map(e=>[U(e),t.getAttribute(e)])))},o=s.filter($("refines",null));e=t=>Object.fromEntries(i(r,"meta").filter($("property",e=>e?.startsWith(t))).map(e=>[e.getAttribute("property").replace(t,""),z(e)]));return{metadata:Object.fromEntries(V.map(t=>{const{type:e,name:i,many:r}=t;var n="meta"===e?e=>e.namespaceURI===O.OPF&&e.getAttribute("property")===i:e=>e.namespaceURI===O.DC&&e.localName===i;return[U(i),r?o.filter(n).map(e=>l(t,e)):l(t,o.find(n))]})),rendition:e("rendition:"),media:e("media:")}})(r);this.rendition=d,this.media=h,h.duration=Q(h.duration),this.dir=this.resources.pageProgressionDirection,this.rawMetadata=c;l=c?.title?.[0];this.metadata={title:l?.value,sortAs:l?.fileAs,language:c?.language,identifier:ie(r),description:c?.description?.value,publisher:c?.publisher?.value,published:c?.date,modified:c?.dctermsModified,subject:c?.subject?.filter(({value:e,code:t})=>e||t)?.map(({value:e,code:t,scheme:i})=>({name:e,code:t,scheme:i})),rights:c?.rights?.value};const u={art:"artist",aut:"author",bkp:"producer",clr:"colorist",edt:"editor",ill:"illustrator",trl:"translator",pbl:"publisher"};r=i=>e=>{var t=[...new Set(e.role?.map(({value:e,scheme:t})=>(t&&"marc:relators"!==t?null:u[e])??i))],e={name:e.value,sortAs:e.fileAs};return[t.length?t:[i],e]};return c?.creator?.map(r("author"))?.concat(c?.contributor?.map?.(r("contributor")))?.forEach(([e,t])=>e.forEach(e=>{this.metadata[e]?this.metadata[e].push(t):this.metadata[e]=[t]})),this}async loadDocument(e){var t=await this.loadText(e.href);return this.parser.parseFromString(t,e.mediaType)}async loadMediaOverlay(e){e=e.mediaOverlay;if(!e)return null;const t=this.resources.getItemByID(e);e=await this.#loadXML(t.href);return ee(e,e=>W(e,t.href))}resolveCFI(e){return this.resources.resolveCFI(e)}resolveHref(e){const[t,i]=e.split("#"),r=this.resources.getItemByHref(decodeURI(t));return r?{index:this.resources.spine.findIndex(({idref:e})=>e===r.id),anchor:i?e=>((e,t)=>e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`))(e,i):()=>0}:null}splitTOCHref(e){return e?.split("#")??[]}getTOCFragment(e,t){return e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`)}isExternal(e){return X(e)}async getCover(){var e=this.resources?.cover;return e?.href?new Blob([await this.loadBlob(e.href)],{type:e.mediaType}):null}async getCalibreBookmarks(){const e=await this.loadText("META-INF/calibre_bookmarks.txt");var t="encoding=json+base64:";if(e?.startsWith(t)){t=atob(e.slice(t.length));return JSON.parse(t)}}}class ce{static getReaderConfig(e){return(JSON.parse(localStorage.getItem("readerConfig"))||{})[e]}static setReaderConfig(e,t){let i=JSON.parse(localStorage.getItem("readerConfig"))||{};i[e]=t,localStorage.setItem("readerConfig",JSON.stringify(i))}static getKookitConfig(e){return(JSON.parse(localStorage.getItem("kookitConfig"))||{})[e]}static setKookitConfig(e,t){let i=JSON.parse(localStorage.getItem("kookitConfig"))||{};i[e]=t,localStorage.setItem("kookitConfig",JSON.stringify(i))}static removeKookitConfig(){localStorage.removeItem("kookitConfig")}}let de=!1;const he=e=>Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address")),ue=e=>e.trim().replace(/(\r\n|\n|\r|\t)/gm,"").substring(0,100),fe=(c,d,h,u,f,p,m)=>g(void 0,void 0,void 0,function*(){var t="yes"===ce.getReaderConfig("isSliding");let e=document.getElementById("page-area");if(e){var i,r,n,s,o,a,l=e.getElementsByTagName("iframe")[0];if(l){let e=l.contentDocument;e&&(l=(l=Math.floor(c.clientWidth/12))%2==0?l:l-1,0{let n=window._.findLastIndex(i,{href:t});return n=t&&-1g(void 0,void 0,void 0,function*(){var e=parseInt(ce.getKookitConfig("chapterDocIndex")||"0"),t=ce.getKookitConfig("chapterHref")||"";0===e||(t=pe(e,t,r,"prev"))&&(ce.setKookitConfig("text","prevChapter"),ce.setKookitConfig("page",""),yield ge(t.index,t.label,t.href,r,i,n,s))}),ge=(a,l,c,d,h,u,f)=>g(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){let t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;var s,i,r,n,o;e&&(e.body.innerHTML="",t.height="0px",e.body.scrollTo(0,0),(-1===(a=l&&!a||d[a]&&d[a].label&&l&&l!==d[a].label&&-1===c.indexOf("#")?window._.findLastIndex(d,{label:l}):a)||a>d.length-1)&&(a=0),e.body.innerHTML=yield p(d[a].text),s=e,yield g(void 0,void 0,void 0,function*(){var t=Array.from(s.getElementsByTagName("link"));for(let e=0;e{console.log("finished")}}let i=[];for(let e=0;e{n.addEventListener("load",e)}))}try{yield Promise.race([Promise.all(i),new Promise((e,t)=>{setTimeout(()=>{t(new Error("Timeout"))},1e3)})])}catch(e){console.log(e)}}),ce.setKookitConfig("chapterTitle",l),ce.setKookitConfig("chapterHref",c),ce.setKookitConfig("chapterDocIndex",a+""),ce.setKookitConfig("percentage",a/d.length+""),ce.setKookitConfig("text",""),i=h,r=u,n=t,o=f,yield g(void 0,void 0,void 0,function*(){let t=n.contentDocument;if(t)if(yield Promise.all(Array.from([...t.images,...t.querySelectorAll("image")]).map(t=>t.complete?Promise.resolve(0!==t.naturalHeight):new Promise(e=>{t.addEventListener("load",()=>e(!0)),t.addEventListener("error",()=>e(!1))}))).then(e=>{e.every(e=>e)?console.log("all images loaded successfully!!"):console.log("some images failed to load, all finished loading")}),yield b(i,r,o),m(),"scroll"!==r){if(n.height=i.clientHeight+"px","double"===r){var e=Math.floor(i.clientWidth/12),e=(i.clientWidth+(e%2==0?e:e-1))/2;if((t.body.scrollWidth-t.body.clientWidth)/e%2==1){let e=document.createElement("div");e.setAttribute("style","height: "+t.body.clientHeight+"px"),t.body.appendChild(e)}}}else n.height=t.body.scrollHeight+"px",n.height=t.body.scrollHeight+"px"}),ye(h,u,"","","",""))}}}),ye=(a,l,c,d,h,u)=>g(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var s=e.getElementsByTagName("iframe")[0];if(s){let n=s.contentDocument;if(n){let t=0,i=0,r=n.body;if(u&&"scroll"!==l){s=Math.floor(a.clientWidth/12),s=a.clientWidth+(s%2==0?s:s-1);i=s*(parseInt(u)-1)}else if(c){let e=he(n.body);var o=e.filter((e,t)=>ue(e.textContent).slim()&&(ue(e.textContent).slim()===ue(c).slim()||ue(e.textContent).slim()===window.ChineseS2T.t2s(ue(c).slim())||ue(e.textContent).slim()===window.ChineseS2T.s2t(ue(c)).slim())&&(Math.abs(t-parseInt(d))<2||"search"===d));if(0===o.length)return void console.log("failed");r=be(o[0],a,l),i=r?y(r.offsetLeft)-y(r.marginLeft||parseFloat(getComputedStyle(r).marginLeft)):"prevChapter"===c?n.body.scrollWidth:0,t=r?y(r.offsetTop)-y(r.marginTop||parseInt(getComputedStyle(r).marginTop)):0}else if(h&&-1{var r=Math.floor(t.clientWidth/12),r=r%2==0?r:r-1;return"scroll"!==i&&parseInt(y(e.offsetLeft)-y(e.marginLeft||parseFloat(getComputedStyle(e).marginLeft))+"")%((t.clientWidth+r)/2)!=0&&e.parentElement?be(e.parentElement,t,i):e},ve=(s,o,a)=>g(void 0,void 0,void 0,function*(){if(!de){let e=document.getElementById("page-area");if(e){var r=e.getElementsByTagName("iframe")[0];if(r){var r=r.contentDocument;if(r){let t=he(r.body);var r=t.filter(e=>Le(s,e,o)&&(e.textContent||"").trim()),n=r[0];let i=0;for(let e=0;e{let e=ce.getKookitConfig("chapterHref")||"",r=e.lastIndexOf("#"),n=e.substring(0,r),s=e.substring(r+1);for(let e=0;e-1)ce.setKookitConfig("chapterHref",e)}}})(r,a),n&&!((e,t,i)=>{let r=Math.floor(t.clientWidth/12),n=r%2===0?r:r-1;if(Math.abs(e.offsetLeft-be(e,t,i).offsetLeft)>(t.clientWidth+n)/2)return true;else return false})(n,s,o)?(ce.setKookitConfig("text",n&&n.textContent||""),ce.setKookitConfig("count",i+""),ce.setKookitConfig("page","")):ce.setKookitConfig("page",(null===(r=yield l(o))||void 0===r?void 0:r.currentPage)+""),de=!0,setTimeout(()=>{de=!1},100)}}}}}),we=(i,e,r,n,s)=>g(void 0,void 0,void 0,function*(){var e=parseInt(ce.getKookitConfig("chapterDocIndex")||"0"),t=ce.getKookitConfig("chapterHref")||"";e>=r.length-1||(t=pe(e,t,r,"next"))&&(ce.setKookitConfig("page",""),yield ge(t.index,t.label,t.href,r,i,n,s))}),xe=(i,r)=>{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let e=he(n.body).filter(e=>!Ce(e)),t=e.filter(e=>Le(i,e,r)&&(e.textContent||"").trim());return("scroll"!==r?t:e).filter(e=>"img"!==e.textContent).map(e=>e.textContent)}}}},Ce=e=>{var t=e.children;let i=!1;for(var r=/^(address|section|blockquote|body|center|dir|div|dl|fieldset|form|h[1-6]|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul|dd|dt|frameset|li|tbody|td|tfoot|th|thead|tr|html)$/i,n=0;n{var r,n=!1,s=t.getBoundingClientRect();return"scroll"!==i&&t.textContent&&t.textContent.trim()?n=-10<(r=s.left)&&r<=e.clientWidth:t.textContent&&t.textContent.trim()?n=(t=s.top)>=e.scrollTop&&t<=e.scrollTop+e.clientHeight:"scroll"!==i&&(n=0<=(s=s.left)&&s<=e.clientWidth),n};const ke={svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",html:"text/html",htm:"text/html",xml:"text/xml",xhtml:"application/xhtml+xml",css:"text/css"},Te={"image/svg+xml":"svg","image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","application/zip":"zip","application/x-rar-compressed":"rar","application/x-7z-compressed":"7z","application/x-tar":"tar","text/html":"html","text/xml":"xml","application/xhtml+xml":"xhtml","text/css":"css"};class Se extends class{constructor(){this.callbacks={},this.callbacks.base={}}on(e,t){const i=this;if(void 0===e||""===e)return console.warn("wrong names"),!1;if(void 0===t)return console.warn("wrong callback"),!1;const r=this.resolveNames(e);return r.forEach(function(e){e=i.resolveName(e);i.callbacks[e.namespace]instanceof Object||(i.callbacks[e.namespace]={}),i.callbacks[e.namespace][e.value]instanceof Array||(i.callbacks[e.namespace][e.value]=[]),i.callbacks[e.namespace][e.value].push(t)}),this}off(e){const r=this;if(void 0===e||""===e)return console.warn("wrong name"),!1;const t=this.resolveNames(e);return t.forEach(function(e){var t=r.resolveName(e);if("base"!==t.namespace&&""===t.value)delete r.callbacks[t.namespace];else if("base"===t.namespace)for(const i in r.callbacks)r.callbacks[i]instanceof Object&&r.callbacks[i][t.value]instanceof Array&&(delete r.callbacks[i][t.value],0===Object.keys(r.callbacks[i]).length&&delete r.callbacks[i]);else r.callbacks[t.namespace]instanceof Object&&r.callbacks[t.namespace][t.value]instanceof Array&&(delete r.callbacks[t.namespace][t.value],0===Object.keys(r.callbacks[t.namespace]).length&&delete r.callbacks[t.namespace])}),this}trigger(e,t=[]){if(void 0===e||""===e)return console.warn("wrong name"),!1;const i=this;const r=t instanceof Array?t:[];let n=this.resolveNames(e);n=this.resolveName(n[0]),setTimeout(()=>{if("base"===n.namespace)for(const e in i.callbacks){if(i.callbacks[e]instanceof Object&&i.callbacks[e][n.value]instanceof Array&&i.callbacks[e][n.value])i.callbacks[e][n.value].forEach(function(e){e.apply(i,r)});else if(this.callbacks[n.namespace]instanceof Object&&i.callbacks[n.namespace][n.value]){if(""===n.value)return console.warn("wrong name"),this;i.callbacks[n.namespace][n.value].forEach(function(e){e.apply(i,r)})}return null}},100)}resolveNames(e){let t=e;return t=t.replace(/[^a-zA-Z0-9 ,/.]/g,""),t=t.replace(/[,/]+/g," "),t=t.split(" "),t}resolveName(e){const t={};var i=e.split(".");return t.original=e,t.value=i[0],t.namespace="base",1g(this,void 0,void 0,function*(){let e=new f(h);this.chapterList=yield e.getChapter(h.toc),this.chapterDocList=yield e.getChapterDoc();var t=this.chapterList,i=this.chapterDocList.map(e=>({href:e.href,label:e.label})),n=yield Promise.all(this.chapterDocList.map(i=>g(this,void 0,void 0,function*(){let t="";if(i.text.load){let e=yield fetch(yield i.text.load()).then(e=>e.blob());t=yield e.text()}return t})));let s=new window.JSZip;s.file("toc.json",JSON.stringify(t)),s.file("sections.json",JSON.stringify(i));let o=[];for(let r=0;re.blob());e.file(t+"."+Te[a.type],a),i[t].src="imgs/"+r+"/"+t+"."+Te[a.type]}catch(e){console.log(e)}}var l=Array.from(e.getElementsByTagName("link"));for(let i=0;ie.blob());t.file(i+"."+Te[c.type],c),e.href="css/"+r+"/"+i+"."+Te[c.type]}catch(e){console.log(e)}}o.push(e.documentElement.innerHTML)}let r=s.folder("chapters");for(let e=0;eg(this,void 0,void 0,function*(){d(yield new Response(e).arrayBuffer())})).catch(e=>{d("err")})}))}resolveChapter(e){var t=e;let i=-1;for(let e=0;e{let e=document.getElementById("page-area");if(e){var o=e.getElementsByTagName("iframe")[0];if(o){o=o.contentDocument;if(o){let e=he(o.body).filter(e=>!Ce(e)),t=e.filter(e=>(e.textContent||"").trim()),i=("scroll"!==s?t:e).filter(e=>"img"!==e.textContent).map(e=>e.textContent),r=0;return xe(n,s)&&0{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let e=he(n.body),t=e.filter(e=>(e.getAttribute("style")===r&&e.setAttribute("style",""),(e.textContent||"").trim()&&e.textContent===i));0!Ce(e));for(let e=0;esetTimeout(e,1e3))),yield ve(this.element,this.mode,this.flatChapter(this.chapterList))})}getPosition(){return{text:ce.getKookitConfig("text"),chapterTitle:ce.getKookitConfig("chapterTitle"),chapterDocIndex:ce.getKookitConfig("chapterDocIndex"),chapterHref:ce.getKookitConfig("chapterHref"),count:ce.getKookitConfig("count"),percentage:ce.getKookitConfig("percentage"),page:ce.getKookitConfig("page")}}setStyle(t){let e=document.getElementById("page-area");if(e){var i=e.getElementsByTagName("iframe")[0];if(i){let e=i.contentDocument;e&&e.body.setAttribute("style",t+e.body.getAttribute("style"))}}}}const Ae=e=>{if(!e)return"";const t=document.createElement("textarea");return t.innerHTML=e,t.value},Be={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},Ee={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},Me={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},Ie={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"]},Re={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},De={magic:[0,4,"string"],length:[4,4,"uint"],count:[8,4,"uint"]},Ne={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"]},Oe={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},He={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},Ue={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},Fe={magic:[0,4,"string"],numEntries:[8,4,"uint"]},$e={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},Pe={1252:"windows-1252",65001:"utf-8"},ze={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"]},je={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"]},We=(e,t)=>{const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},Xe=(e,t,i)=>{const r=new e.constructor(e.length+t.length+i.length);return r.set(e),r.set(t,e.length),r.set(i,e.length+t.length),r},qe=new TextDecoder,Ke=e=>qe.decode(e),Ge=e=>{if(e){var t=e.byteLength,t=4===t?"getUint32":2===t?"getUint16":"getUint8";return new DataView(e)[t](0)}},Je=(e,n)=>Object.fromEntries(Array.from(Object.entries(e)).map(([e,[t,i,r]])=>[e,("string"===r?Ke:Ge)(n.slice(t,t+i))])),Ze=e=>new TextDecoder(Pe[e]),Ve=(e,t=0)=>{let i=0,r=0;for(const n of e.subarray(t,t+4))if(i=i<<7|(127&n)>>>0,r++,128&n)break;return{value:i,length:r}},_e=e=>{let t=0;for(;0>=1)1==(1&e)&&t++;return t},Ye=e=>{let t=0;for(;0==(1&e);)e>>=1,t++;return t},Qe=t=>{let i=[];for(let e=0;e>>3,o=3+(7&n);for(let e=0;e{const r=await i(t.huffcdic),{magic:e,offset1:n,offset2:s}=Je(He,r);if("HUFF"!==e)throw new Error("Invalid HUFF record");const h=Array.from({length:256},(e,t)=>n+4*t).map(e=>Ge(r.slice(e,e+4))).map(e=>[128&e,31&e,e>>>8]),u=[null].concat(Array.from({length:32},(e,t)=>s+8*t).map(e=>[Ge(r.slice(e,e+4)),Ge(r.slice(e+4,e+8))])),f=[];for(let e=1;e{let a=new Uint8Array;var l=8*o.byteLength;for(let s=0;s{var e=i+32,r=e>>3;let n=0n;for(let e=i>>3;e<=r;e++)n=n<<8n|BigInt(t[e]??0);return n>>8n-BigInt(7&e)&0xffffffffn})(o,s));let[e,t,i]=h[c>>>24];if(!e){for(;c>>>32-tl)break;var d=i-(c>>>32-t);let[r,n]=f[d];n||(r=p(r),f[d]=[r,!0]),a=We(a,r)}return a};return p},tt=async(t,i)=>{const e=await i(t),r=Je(Ne,e);if("INDX"!==r.magic)throw new Error("Invalid INDX record");const n=Ze(r.encoding),s=e.slice(r.length);var o=Je(Oe,s);if("TAGX"!==o.magic)throw new Error("Invalid TAGX section");var a=(o.length-12)/4,l=Array.from({length:a},(e,t)=>new Uint8Array(s.slice(12+4*t,12+4*t+4)));const c={};let d=0;for(let e=0;e>Ye(C),null,x]));const $={};for([A,B,E,M]of F){const P=[];if(null!=B)for(let e=0;eGe(i.slice(8*t,8*t+4))).map((e,t,i)=>[e,i[t+1]])}loadRecord(e){e=this.#offsets[e];if(!e)throw new RangeError("Record index out of bounds");return this.#file.slice(...e).arrayBuffer()}async loadMagic(e){e=this.#offsets[e][0];return Ke(await this.#file.slice(e,e+4).arrayBuffer())}}{#start=0;#resourceStart;#decoder;#encoder;#decompress;#removeTrailingEntries;constructor({unzlib:e}){super(),this.unzlib=e}async open(e){await super.open(e),this.headers=this.#getHeaders(await super.loadRecord(0)),this.#resourceStart=this.headers.mobi.resourceStart;let t=8<=this.headers.mobi.version;if(!t){e=this.headers.exth?.boundary;if(e<4294967295)try{this.headers=this.#getHeaders(await super.loadRecord(e)),this.#start=e,t=!0}catch(e){console.warn(e),console.warn("Failed to open KF8; falling back to MOBI")}}return await this.#setup(),new(t?ht:st)(this).init()}#getHeaders(e){var t=Je(Me,e);const i=Je(Ie,e);if("MOBI"!==i.magic)throw new Error("Missing MOBI header");var{titleOffset:r,titleLength:n,localeLanguage:s,localeRegion:o}=i;i.title=e.slice(r,r+n);s=je[s];i.language=s?.[o>>2]??s?.[0];s=64&i.exthFlag?((t,e)=>{var{magic:i,count:r}=Je(De,t);if("EXTH"!==i)throw new Error("Invalid EXTH header");const n=Ze(e),s={};let o=12;for(let e=0;ee:2===e?Qe:17480===e?await et(t,this.loadRecord.bind(this)):null,!this.#decompress)throw new Error("Unknown compression type");var t=t["trailingFlags"];const r=1&t,n=_e(t>>>1);this.#removeTrailingEntries=t=>{for(let e=0;e{let t=0;for(const i of e.subarray(-4))128&i&&(t=0),t=t<<7|127&i;return t})(t);t=t.subarray(0,-i)}var e;return r&&(e=1+(3&t[t.length-1]),t=t.subarray(0,-e)),t}}decode(...e){return this.#decoder.decode(...e)}encode(...e){return this.#encoder.encode(...e)}loadRecord(e){return super.loadRecord(this.#start+e)}loadMagic(e){return super.loadMagic(this.#start+e)}loadText(e){return this.loadRecord(e+1).then(e=>new Uint8Array(e)).then(this.#removeTrailingEntries).then(this.#decompress)}async loadResource(e){const t=await super.loadRecord(this.#resourceStart+e);e=Ke(t.slice(0,4));return"FONT"===e?(async(e,t)=>{var{flags:i,dataStart:r,keyLength:n,keyStart:s}=Je($e,e);const o=new Uint8Array(e.slice(r));if(2&i)for(var r=16===n?1024:1040,a=new Uint8Array(e.slice(s,s+n)),l=Math.min(r,o.length),c=0;c{const{table:i,cncx:r}=await tt(e,t),n=i.map(({tagMap:e},t)=>({index:t,offset:e[1]?.[0],size:e[2]?.[0],label:r[e[3]]??"",headingLevel:e[4]?.[0],pos:e[6],parent:e[21]?.[0],firstChild:e[22]?.[0],lastChild:e[23]?.[0]})),s=t=>(null==t.firstChild||(t.children=n.filter(e=>e.parent===t.index).map(s)),t);return n.filter(e=>0===e.headingLevel).map(s)})(e,this.loadRecord.bind(this))}getMetadata(){const{mobi:e,exth:t}=this.headers;return{identifier:e.uid.toString(),title:Ae(t?.title||this.decode(e.title)),author:t?.creator?.map(Ae),publisher:Ae(t?.publisher),language:t?.language??e.language,published:t?.date,description:Ae(t?.description),subject:t?.subject?.map(Ae),rights:Ae(t?.rights)}}async getCover(){var e=this.headers["exth"],e=e?.coverOffset<4294967295?e?.coverOffset:e?.thumbnailOffset<4294967295?e?.thumbnailOffset:null;if(null!=e){e=await this.loadResource(e);return new Blob([e])}}}const rt=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,nt=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi;class st{parser=new DOMParser;serializer=new XMLSerializer;#resourceCache=new Map;#textCache=new Map;#cache=new Map;#sections;#fileposList=[];#type=Be.HTML;constructor(e){this.mobi=e}async init(){let t=new Uint8Array;for(let e=0;eString.fromCharCode(e)).join("");this.#sections=[0].concat(Array.from(r.matchAll(rt),e=>e.index)).map((e,t,i)=>r.slice(e,i[t+1])).map(e=>Uint8Array.from(e,e=>e.charCodeAt(0))).map(e=>({book:this,raw:e})).reduce((e,t)=>{var i=e[e.length-1];return t.start=i?.end??0,t.end=t.start+t.raw.byteLength,e.concat(t)},[]),this.sections=this.#sections.map((e,t)=>({id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.end-e.start}));try{this.landmarks=await this.getGuide();var e=this.landmarks.find(({type:e})=>e?.includes("toc"))?.href;if(e){var i=this.resolveHref(e)["index"];const n=await this.sections[i].createDocument();let s,o=0,a=0;const l=new Map,c=new Map;this.toc=Array.from(n.querySelectorAll("a[filepos]")).reduce((e,t)=>{var i=(e=>{let t=0;for(;e;){const r=e.parentElement;var i;r&&("p"===(i=r.tagName.toLowerCase())?t+=1.5:"blockquote"===i&&(t+=2)),e=r}return t})(t),r={label:t.innerText?.trim(),href:`filepos:${t.getAttribute("filepos")}`},t=i>a?o+1:i===a?o:l.get(i)??Math.max(0,o-1);if(t>o)s?(s.subitems??=[],s.subitems.push(r),c.set(t,s)):e.push(r);else{const n=c.get(t);(n?n.subitems:e).push(r)}return s=r,o=t,a=i,l.set(i,t),e},[])}}catch(e){console.warn(e)}return this.#fileposList=[...new Set(Array.from(r.matchAll(nt),e=>e[1]))].map(e=>({filepos:e,number:Number(e)})).sort((e,t)=>e.number-t.number),this.metadata=this.mobi.getMetadata(),this.getCover=this.mobi.getCover.bind(this.mobi),this}async getGuide(){const e=await this.createDocument(this.#sections[0]);return Array.from(e.getElementsByTagName("reference"),e=>({label:e.getAttribute("title"),type:e.getAttribute("type")?.split(/\s/),href:`filepos:${e.getAttribute("filepos")}`}))}async loadResource(e){if(this.#resourceCache.has(e))return this.#resourceCache.get(e);var t=await this.mobi.loadResource(e),t=URL.createObjectURL(new Blob([t]));return this.#resourceCache.set(e,t),t}async loadRecindex(e){return this.loadResource(Number(e)-1)}async replaceResources(e){for(const s of e.querySelectorAll("img[recindex]")){var t=s.getAttribute("recindex");try{s.src=await this.loadRecindex(t)}catch(e){console.warn(`Failed to load image ${t}`)}}for(const o of e.querySelectorAll("[mediarecindex]")){var i=o.getAttribute("mediarecindex"),r=o.getAttribute("recindex");try{o.src=await this.loadRecindex(i),r&&(o.poster=await this.loadRecindex(r))}catch(e){console.warn(`Failed to load media ${i}`)}}for(const a of e.querySelectorAll("[filepos]")){var n=a.getAttribute("filepos");a.href=`filepos:${n}`}}async loadText(t){if(this.#textCache.has(t))return this.#textCache.get(t);const r=t["raw"],n=this.#fileposList.filter(({number:e})=>e>=t.start&&e({...e,offset:e.number-t.start}));let s=r;n.length&&(s=r.subarray(0,n[0].offset),n.forEach(({filepos:e,offset:t},i)=>{i=n[i+1],e=this.mobi.encode(``);s=Xe(s,e,r.subarray(t,i?.offset))}));var e=this.mobi.decode(s).replaceAll(rt,"");return this.#textCache.set(t,e),e}async createDocument(e){e=await this.loadText(e);return this.parser.parseFromString(e,this.#type)}async loadSection(e){if(this.#cache.has(e))return this.#cache.get(e);const t=await this.createDocument(e),i=t.createElement("style");t.head.append(i),i.append(t.createTextNode(`blockquote { +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Kookit={})}(this,function(e){"use strict";function g(e,o,a,l){return new(a=a||Promise)(function(i,t){function r(e){try{s(l.next(e))}catch(e){t(e)}}function n(e){try{s(l.throw(e))}catch(e){t(e)}}function s(e){var t;e.done?i(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(r,n)}s((l=l.apply(e,o||[])).next())})}const y=e=>e?parseFloat(e+""):0,p=i=>g(void 0,void 0,void 0,function*(){let t="";if(i.load){let e=yield fetch(yield i.load()).then(e=>e.blob());t=yield e.text()}return i.loadAsset&&(t=yield r(t,i.loadAsset)),n(t)}),u=e=>Array.from(e.querySelectorAll("img, image")),r=(n,s)=>g(void 0,void 0,void 0,function*(){let e=(new DOMParser).parseFromString(n,"text/html"),t=u(e);for(let e=0;e{var t=(new DOMParser).parseFromString(e,"text/html");let i=u(t);if(0===i.length)return e;for(let e=0;e{var i=document.createElement("iframe");i.style.width="100%",i.style.border="0",i.style.margin="0",i.style.padding="0",i.style.minHeight="calc(100% - 2px)",i.style.fontSize="100%",i.style.font="inherit",i.scrolling="no",i.tabIndex=0,i.style.verticalAlign="baseline",e.innerHTML="",e.appendChild(i)},l=i=>g(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){t=t.contentDocument;if(t)return 1===parseInt(t.body.scrollWidth/t.body.clientWidth+"")&&(yield new Promise(e=>setTimeout(e,1e3))),{totalPage:"scroll"===i?1:parseInt(t.body.scrollWidth/t.body.clientWidth+"")+1,currentPage:parseInt(y(t.body.scrollLeft)/t.body.clientWidth+"")+1}}}}),m=()=>{let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;if(e){var i=e.querySelectorAll("a, article, cite, div, li, p, span, pre, table, bold");for(let e=0;eg(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let n=t.contentDocument;if(n){var s,t=Math.floor(c.clientWidth/12),o=t%2==0?t:t-1;for(s of n.querySelectorAll("img, image")){var a,l=s.parentElement;let e=0,t=0,i=s.naturalWidth,r=s.naturalHeight;"image"===s.tagName&&(a=yield(t=>g(void 0,void 0,void 0,function*(){const e=new Image;return e.src=t,yield e.decode(),e}))(s.getAttribute("xlink:href")),i=a.naturalWidth,r=a.naturalHeight),h.startsWith("CB")&&"scroll"===d?t=l.offsetWidth:h.startsWith("CB")&&"single"===d?(e=c.clientHeight,t=c.clientWidth):i&&r?(r/i>l.clientHeight/l.clientWidth?(e=l.clientHeight,t=parseInt(e*i/r+"")):(t=l.clientWidth,e=parseInt(t*r/i+"")),e>n.body.clientHeight&&(t=parseInt(t*(n.body.clientHeight/e)+""),e=n.body.clientHeight)):e=l&&l.clientWidth&&0r||e/t>r/i?e=t*(r/i):t=e*(i/r)),(t||e)&&s.setAttribute("style",s.getAttribute("style")+";"+`max-width: ${0{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){let t=n.contentDocument;if(t){let e=t.createElement("style");e.id="default-style",e.textContent="p,empty-line{display: inherit;margin-block-start: inherit;margin-block-end: inherit;margin-inline-start: inherit;margin-inline-end: inherit;}body{margin: 0px}",t.head.appendChild(e),"scroll"!==r&&(n="double"===r?2:1,r=(r=Math.floor(i.clientWidth/12))%2==0?r:r-1,t.body.setAttribute("style",`width: auto;height: 100%;overflow-y: hidden;overflow-X: hidden;padding-left: 0px;padding-right: 0px;margin: 0px;box-sizing: border-box;max-width: inherit;column-fill: auto;column-gap: ${r}px;column-count: 12;column-width: ${(i.clientWidth-r)/n}px;`))}}}};class f{constructor(e){this.book=e,this.chapterList=[],this.flattenChapters=[],this.chapterDocList=[]}getChapter(e){return g(this,void 0,void 0,function*(){return this.chapterList=e?yield Promise.all(e.map(t=>g(this,void 0,void 0,function*(){let e=-1;try{e=t.href&&(yield this.book.resolveHref(t.href))?(yield this.book.resolveHref(t.href)).index:-1}catch(e){console.log(e)}return{label:t.label||e,href:t.href,index:e,subitems:t.subitems?yield this.getChapter(t.subitems):[]}}))):yield Promise.all(this.book.sections.map((e,t)=>g(this,void 0,void 0,function*(){return{label:e.label||t,href:e.href||"",index:t,subitems:e.subitems?yield this.getChapter(e.subitems):[]}}))),this.flattenChapters=this.flatChapter(this.chapterList),this.chapterList})}getChapterDoc(){return g(this,void 0,void 0,function*(){const i=this.flattenChapters.map(e=>e.index);return this.book.sections.map((e,t)=>-1g(this,void 0,void 0,function*(){const t=this.book.metadata;try{var i=yield this.book.getCover(),e=new FileReader;e.readAsDataURL(i),e.onloadend=()=>{r({name:t.title,author:t.author?t.author[0].name:"",description:t.description,publisher:t.publisher,cover:e.result})}}catch(e){i=t.author&&t.author[0]&&t.author[0].name?t.author[0].name:t.author&&t.author[0]?t.author[0]:t.author||"";r({name:t.title,author:i,description:t.description,publisher:t.publisher,cover:""})}}))}}const i=(e,r)=>e.map((e,t,i)=>r(e,t,i)?t:null).filter(e=>null!=e),a=(r,e)=>[-1,...e,r.length].reduce(({xs:e,a:t},i)=>({xs:e?.concat([r.slice(t+1,i)])??[],a:i}),{}).xs,c=(e,t)=>e.slice(0,-1).concat([e[e.length-1].concat(t[0])]).concat(t.slice(1)),d=/\d/,h=/^epubcfi\((.*)\)$/,v=e=>e.replace(/[\^[\](),;=]/g,"^$&"),t=e=>h.test(e)?e:`epubcfi(${e})`,w=(e,t)=>i(e,([e])=>e===t),x=e=>{const t=[];let i;for(var[r,n]of e){if("/"===r)t.push({index:n});else{const s=t[t.length-1];if(":"===r)s.offset=n;else if("~"===r)s.temporal=n;else if("@"===r)s.spatial=(s.spatial??[]).concat(n);else if(";s"===r)s.side=n;else if("["===r){if("/"!==i||!n){s.text=(s.text??[]).concat(n);continue}s.id=n}}i=r}return t},C=e=>a(e,w(e,"!")).map(x),L=e=>{var t=(e=>{const t=[];let i,r,n="";var s=e=>(t.push(e),i=null,n=""),o=e=>(n+=e,r=!1);for(const a of Array.from(e.trim()).concat(""))if("^"!==a||r){if("!"===i)s(["!"]);else if(","===i)s([","]);else if("/"===i||":"===i){if(d.test(a)){o(a);continue}s([i,parseInt(n)])}else if("~"===i){if(d.test(a)||"."===a){o(a);continue}s(["~",parseFloat(n)])}else if("@"===i){if(":"===a){s(["@",parseFloat(n)]),i="@";continue}if(d.test(a)||"."===a){o(a);continue}s(["@",parseFloat(n)])}else{if("["===i){";"!==a||r?","!==a||r?"]"!==a||r?o(a):s(["[",n]):(s(["[",n]),i="["):(s(["[",n]),i=";");continue}if(i?.startsWith(";")){"="!==a||r?";"!==a||r?"]"!==a||r?o(a):s([i,n]):(s([i,n]),i=";"):(i=`;${n}`,n="");continue}}"/"!==a&&":"!==a&&"~"!==a&&"@"!==a&&"["!==a&&"!"!==a&&","!==a||(i=a)}else r=!0;return t})((i=e).match(h)?.[1]??i),e=w(t,",");if(!e.length)return C(t);var[i,t,e]=a(t,e).map(C);return{parent:i,start:t,end:e}},k=({index:e,id:t,offset:i,temporal:r,spatial:n,text:s,side:o})=>{var a=o?`;s=${o}`:"";return`/${e}`+(t?`[${v(t)}${a}]`:"")+(null!=i&&e%2?`:${i}`:"")+(r?`~${r}`:"")+(n?`@${n.join(":")}`:"")+(s||!t&&o?"["+(s?.map(v)?.join(",")??"")+a+"]":"")},T=e=>e.parent?[e.parent,e.start,e.end].map(T).join(","):e.map(e=>e.map(k).join("")).join("!"),S=e=>t(T(e)),A=(e,t)=>"string"==typeof e?S(A(L(e),t)):e.parent?c(e.parent,e[t?"end":"start"]):e,B=({nodeType:e})=>3===e||4===e,E=({nodeType:e})=>1===e,M=e=>{const t=Array.from(e.childNodes).filter(e=>B(e)||E(e)).reduce((e,t)=>{let i=e[e.length-1];return i?B(t)?Array.isArray(i)?i.push(t):B(i)?e[e.length-1]=[i,t]:e.push(t):E(i)?e.push(null,t):e.push(t):e.push(t),e},[]);return E(t[0])&&t.unshift("first"),E(t[t.length-1])&&t.push("last"),t.unshift("before"),t.push("after"),t},I=(e,t)=>e?M(e)[t]:null,R=(e,t)=>{var i,r=t[t.length-1]["id"];if(r){r=e.ownerDocument.getElementById(r);if(r)return{node:r,offset:0}}for({index:i}of t){var n=I(e,i);if("first"===n)return{node:e.firstChild??e};if("last"===n)return{node:e.lastChild??e};if("before"===n)return{node:e,before:!0};if("after"===n)return{node:e,after:!0};e=n}var s=t[t.length-1]["offset"];if(!Array.isArray(e))return{node:e,offset:s};let o=0;for(const l of e){var a=l.nodeValue["length"];if(o+a>=s)return{node:l,offset:s-o};o+=a}},D=(t,i)=>{var{parentNode:e,id:r}=t;const n=M(e);var s=n.findIndex(e=>Array.isArray(e)?e.some(e=>e===t):e===t),o=n[s];if(Array.isArray(o)){let e=0;for(const a of o){if(a===t){e+=i;break}e+=a.nodeValue.length}i=e}s={id:r,index:s,offset:i};return e!==t.ownerDocument.documentElement?D(e).concat(s):[s]},N=(e,t)=>R(e.documentElement,A(t)).node,O={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"},H={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)/},U=e=>e.toLowerCase().replace(/[-:](.)/g,(e,t)=>t.toUpperCase()),F=e=>e?e.trim().replace(/\s{2,}/g," "):"",$=(t,i,e)=>e?e=>e.getAttribute(t)?.split(/\s/)?.includes(i):"function"==typeof i?e=>i(e.getAttribute(t)):e=>e.getAttribute(t)===i,P=(...e)=>t=>t?Object.fromEntries(e.map(e=>[U(e),t.getAttribute(e)])):null,z=e=>F(e?.textContent),j=(e,i)=>{e=e.lookupNamespaceURI(null)===i||e.lookupPrefix(i);const r=e?(e,t)=>e=>e.namespaceURI===i&&e.localName===t:(e,t)=>e=>e.localName===t;return{$:(e,t)=>[...e.children].find(r(e,t)),$$:(e,t)=>[...e.children].filter(r(e,t)),$$$:e?(e,t)=>[...e.getElementsByTagNameNS(i,t)]:(e,t)=>[...e.getElementsByTagName(i,t)]}},W=(t,e)=>{try{if(e.includes(":"))return new URL(t,e);var i="whatever://whatever/";return decodeURI(new URL(t,i+e).href.replace(i,""))}catch(e){return console.warn(e),t}},X=e=>/^(?!blob)\w+:/i.test(e),q=async(e,t,i)=>{const r=[];e.replace(t,(...e)=>(r.push(e),null));const n=[];for(const s of r)n.push(await i(...s));return e.replace(t,()=>n.shift())},K=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&");var G={attrs:["dir","xml:lang"]},J={name:"alternate-script",many:!0,...G,props:["file-as"]},Z={many:!0,...G,props:[{name:"role",many:!0,attrs:["scheme"]},"file-as",J]};const V=[{name:"title",many:!0,...G,props:["title-type","display-seq","file-as",J]},{name:"identifier",many:!0,props:[{name:"identifier-type",attrs:["scheme"]}]},{name:"language",many:!0},{name:"creator",...Z},{name:"contributor",...Z},{name:"publisher",...G,props:["file-as",J]},{name:"description",...G,props:[J]},{name:"rights",...G,props:[J]},{name:"date"},{name:"dcterms:modified",type:"meta"},{name:"subject",many:!0,...G,props:["term","authority",J]},{name:"belongs-to-collection",type:"meta",many:!0,...G,props:["collection-type","group-position","dcterms:identifier","file-as",J,{name:"belongs-to-collection",recursive:!0}]}],_=(e,s=e=>e)=>{const{$:o,$$:i,$$$:t}=j(e,O.XHTML),r=n=>e=>{const t=o(e,"a")??o(e,"span");var i=o(e,"ol"),e=(e=t?.getAttribute("href"))?decodeURI(s(e)):null;const r={label:z(t)||t?.getAttribute("title"),href:e,subitems:a(i)};return n&&(r.type=t?.getAttributeNS(O.EPUB,"type")?.split(/\s/)),r},a=(e,t)=>e?i(e,"li").map(r(t)):null;var n=(e,t)=>a(o(e,"ol"),t);let l=null,c=null,d=null,h=[];for(const u of t(e,"nav")){const f=u.getAttributeNS(O.EPUB,"type")?.split(/\s/)??[];f.includes("toc")?l??=n(u):f.includes("page-list")?c??=n(u):f.includes("landmarks")?d??=n(u,!0):h.push({label:z(u.firstElementChild),type:f,list:n(u)})}return{toc:l,pageList:c,landmarks:d,others:h}},Y=(i,s=e=>e)=>{const{$:o,$$:a}=j(i,O.NCX),l=e=>{var t=o(e,"navLabel");const i=o(e,"content");var r=z(t),t=(t=i.getAttribute("src"))?decodeURI(s(t)):null;if("navPoint"!==e.localName)return{label:r,href:t};{const n=a(e,"navPoint");return{label:r,href:t,subitems:n.length?n.map(l):null}}},r=(e,t)=>a(e,t).map(l);var e=(e,t)=>{e=o(i.documentElement,e);return e?r(e,t):null};return{toc:e("navMap","navPoint"),pageList:e("pageList","pageTarget"),others:a(i.documentElement,"navList").map(e=>({label:z(o(e,"navLabel")),list:r(e,"navTarget")}))}},Q=e=>{if(e){var t=e.split(":").map(e=>parseFloat(e));if(3===t.length){var[i,r,n]=t;return 60*i*60+60*r+n}if(2===t.length){var[t,s]=t;return 60*t+s}var[s,e]=e.split(/(?=[^\d.])/);return parseFloat(s)*("h"===e?3600:"min"===e?60:"ms"===e?.001:1)}},ee=(e,r=e=>e)=>{const{$:n,$$$:t}=j(e,O.SMIL);return t(e,"par").map(e=>{var t=n(e,"text")?.getAttribute("src")?.split("#")?.[1];const i=n(e,"audio");return i?{id:t,audio:{src:(e=i.getAttribute("src"))?decodeURI(r(e)):null,clipBegin:Q(i.getAttribute("clipBegin")),clipEnd:Q(i.getAttribute("clipEnd"))}}:{id:t}})},te=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,ie=e=>z(e.getElementById(e.documentElement.getAttribute("unique-identifier"))??e.getElementsByTagNameNS(O.DC,"identifier")[0]),re=async(e,t,i)=>{const r=new Uint8Array(await i.slice(0,t).arrayBuffer());t=Math.min(t,r.length);for(var n=0;n{e=(new TextEncoder).encode(e),e=await globalThis.crypto.subtle.digest("SHA-1",e);return new Uint8Array(e)})=>({"http://www.idpf.org/2008/embedding":{key:e=>t(ie(e).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(e,t)=>re(e,1040,t)},"http://ns.adobe.com/pdf/enc#RC":{key:e=>{const i=(e=>{for(const i of e.getElementsByTagNameNS(O.DC,"identifier")){var[t]=z(i).split(":").slice(-1);if(te.test(t))return t}return""})(e).replaceAll("-","");return Uint8Array.from({length:16},(e,t)=>parseInt(i.slice(2*t,2*t+2),16))},decode:(e,t)=>re(e,1024,t)}});class se{#uris=new Map;#decoders=new Map;#algorithms;constructor(e){this.#algorithms=e}async init(e,t){var i,r;if(e)for({algorithm:i,uri:r}of Array.from(e.getElementsByTagNameNS(O.ENC,"EncryptedData"),e=>({algorithm:e.getElementsByTagNameNS(O.ENC,"EncryptionMethod")[0]?.getAttribute("Algorithm"),uri:e.getElementsByTagNameNS(O.ENC,"CipherReference")[0]?.getAttribute("URI")}))){if(!this.#decoders.has(i)){const n=this.#algorithms[i];if(!n){console.warn("Unknown encryption algorithm");continue}const s=await n.key(t);this.#decoders.set(i,e=>n.decode(s,e))}this.#uris.set(r,i)}}getDecoder(e){return this.#decoders.get(this.#uris.get(e))??(e=>e)}}class oe{constructor({opf:e,resolveHref:r}){this.opf=e;const{$:t,$$:i,$$$:n}=j(e,O.OPF);var s=t(e.documentElement,"manifest");const o=t(e.documentElement,"spine"),a=i(o,"itemref");this.manifest=i(s,"item").map(P("href","id","media-type","properties","media-overlay")).map(e=>(e.href=r(e.href),e.properties=e.properties?.split(/\s/),e)),this.spine=a.map(P("idref","id","linear","properties")).map(e=>(e.properties=e.properties?.split(/\s/),e)),this.pageProgressionDirection=o.getAttribute("page-progression-direction"),this.navPath=this.getItemByProperty("nav")?.href,this.ncxPath=(this.getItemByID(o.getAttribute("toc"))??this.manifest.find(e=>e.mediaType===H.NCX))?.href;s=t(e.documentElement,"guide");s&&(this.guide=i(s,"reference").map(P("type","title","href")).map(({type:e,title:t,href:i})=>({label:t,type:e.split(/\s/),href:r(i)}))),this.cover=this.getItemByProperty("cover-image")??this.getItemByID(n(e,"meta").find($("name","cover"))?.getAttribute("content"))??this.getItemByHref(this.guide?.find(e=>e.type.includes("cover"))?.href),this.cfis=(e=>{const t=[];var i,r,n=e[0]["parentNode"];const s=D(n);for([i,r]of M(n).entries()){var o=e[t.length];r===o&&t.push(S([s.concat({id:o.id,index:i})]))}return t})(a)}getItemByID(t){return this.manifest.find(e=>e.id===t)}getItemByHref(t){return this.manifest.find(e=>e.href===t)}getItemByProperty(t){return this.manifest.find(e=>e.properties?.includes(t))}resolveCFI(e){const t=L(e),i=(t.parent??t).shift();let r=N(this.opf,i);r&&"idref"!==r.nodeName&&(i.at(-1).id=null,r=N(this.opf,i));const n=r?.getAttribute("idref");return{index:this.spine.findIndex(e=>e.idref===n),anchor:e=>((e,t)=>{var i=A(t),r=A(t,!0),t=e.documentElement,i=R(t,i[0]),r=R(t,r[0]);const n=e.createRange();return i.before?n.setStartBefore(i.node):i.after?n.setStartAfter(i.node):n.setStart(i.node,i.offset),r.before?n.setEndBefore(r.node):r.after?n.setEndAfter(r.node):n.setEnd(r.node,r.offset),n})(e,t)}}}class ae{#cache=new Map;#children=new Map;#refCount=new Map;allowScript=!1;constructor({loadText:e,loadBlob:t,resources:i}){this.loadText=e,this.loadBlob=t,this.manifest=i.manifest,this.assets=i.manifest}createURL(e,t,i,r){if(!t)return"";i=URL.createObjectURL(new Blob([t],{type:i}));if(this.#cache.set(e,i),this.#refCount.set(e,1),r){const n=this.#children.get(r);n?n.push(e):this.#children.set(r,[e])}return i}ref(e,t){const i=this.#children.get(t);return i?.includes(e)||(this.#refCount.set(e,this.#refCount.get(e)+1),i?i.push(e):this.#children.set(t,[e])),this.#cache.get(e)}unref(e){if(this.#refCount.has(e)){var t=this.#refCount.get(e)-1;if(t<1){URL.revokeObjectURL(this.#cache.get(e)),this.#cache.delete(e),this.#refCount.delete(e);const i=this.#children.get(e);if(i)for(;i.length;)this.unref(i.pop());this.#children.delete(e)}else this.#refCount.set(e,t)}}async loadItem(e,t=[]){if(!e)return null;const{href:i,mediaType:r}=e;var n=H.JS.test(e.mediaType);if(n&&!this.allowScript)return null;var s=t.at(-1);return this.#cache.has(i)?this.ref(i,s):(n||[H.XHTML,H.HTML,H.CSS,H.SVG].includes(r))&&t.every(e=>e!==i)?this.loadReplaced(e,t):this.createURL(i,await this.loadBlob(i),r,s)}async loadHref(e,t,i=[]){if(X(e))return e;const r=W(e,t);let n=this.manifest.find(e=>e.href===r);return n=n||{href:r,mediaType:""},this.loadItem(n,i.concat(t))}async loadReplaced(e,n=[]){const{href:s,mediaType:i}=e;var r,o=n.at(-1),a=await this.loadText(s);if(!a)return null;if([H.XHTML,H.HTML,H.SVG].includes(i)){let t=(new DOMParser).parseFromString(a,i);if(i===H.XHTML&&t.querySelector("parsererror")&&(console.warn(t.querySelector("parsererror").innerText),e.mediaType=H.HTML,t=(new DOMParser).parseFromString(a,e.mediaType)),[H.XHTML,H.SVG].includes(e.mediaType)){let e=t.firstChild;for(;e instanceof ProcessingInstruction;)e.data&&(r=await q(e.data,/(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,(e,t,i,r)=>this.loadHref(i,s,n).then(e=>`${t}${e}${r}`)),e.replaceWith(t.createProcessingInstruction(e.target,r))),e=e.nextSibling}var l=async(e,t)=>e.setAttribute(t,await this.loadHref(e.getAttribute(t),s,n));for(const d of t.querySelectorAll("link[href]"))await l(d,"href");for(const h of t.querySelectorAll("[src]"))await l(h,"src");for(const u of t.querySelectorAll("[poster]"))await l(u,"poster");for(const f of t.querySelectorAll("object[data]"))await l(f,"data");for(const p of t.querySelectorAll("[*|href]:not([href]"))p.setAttributeNS(O.XLINK,"href",await this.loadHref(p.getAttributeNS(O.XLINK,"href"),s,n));for(const m of t.querySelectorAll("style"))m.textContent&&(m.textContent=await this.replaceCSS(m.textContent,s,n));for(const g of t.querySelectorAll("[style]"))g.setAttribute("style",await this.replaceCSS(g.getAttribute("style"),s,n));const c=(new XMLSerializer).serializeToString(t);return this.createURL(s,c,e.mediaType,o)}const c=i===H.CSS?await this.replaceCSS(a,s,n):await this.replaceString(a,s,n);return this.createURL(s,c,i,o)}async replaceCSS(e,i,r=[]){e=await q(e,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,(e,t)=>this.loadHref(t,i,r).then(e=>`url("${e}")`));const t=await q(e,/@import\s*["']([^"'\n]*?)["']/gi,(e,t)=>this.loadHref(t,i,r).then(e=>`@import "${e}"`)),n=window?.innerWidth??800,s=window?.innerHeight??600;return t.replace(/-epub-/gi,"").replace(/(\d*\.?\d+)vw/gi,(e,t)=>parseFloat(t)*n/100+"px").replace(/(\d*\.?\d+)vh/gi,(e,t)=>parseFloat(t)*s/100+"px").replace(/page-break-(after|before|inside)/gi,(e,t)=>`-webkit-column-break-${t}`)}replaceString(e,o,t=[]){const a=new Map,i=this.assets.map(e=>{if(e.href!==o){var t=((e,t)=>{if(!e)return t;const i=e.replace(/\/$/,"").split("/"),r=t.replace(/\/$/,"").split("/");t=(i.length>r.length?i:r).findIndex((e,t)=>i[t]!==r[t]);return t<0?"":Array(i.length-t).fill("..").concat(r.slice(t)).join("/")})(o.slice(0,o.lastIndexOf("/")+1),e.href),i=encodeURI(t),r="/"+e.href,n=encodeURI(r),n=new Set([t,i,r,n]);for(const s of n)a.set(s,e);return Array.from(n)}}).flat().filter(e=>e);if(!i.length)return e;var r=new RegExp(i.map(K).join("|"),"g");return q(e,r,async e=>this.loadItem(a.get(e.replace(/^\//,"")),t.concat(o)))}unloadItem(e){this.unref(e?.href)}}class le{parser=new DOMParser;#encryption;constructor({loadText:e,loadBlob:t,getSize:i,sha1:r}){this.loadText=e,this.loadBlob=t,this.getSize=i,this.#encryption=new se(ne(r))}#parseXML(e){return e?this.parser.parseFromString(e,H.XML):null}async#loadXML(e){return this.#parseXML(await this.loadText(e))}async init(){const e=await this.#loadXML("META-INF/container.xml");if(!e)throw new Error("Failed to load container file");var t=Array.from(e.getElementsByTagNameNS(O.CONTAINER,"rootfile"),P("full-path","media-type")).filter(e=>"application/oebps-package+xml"===e.mediaType);if(!t.length)throw new Error("No package document defined in container");const i=t[0].fullPath;var r=await this.#loadXML(i);if(!r)throw new Error("Failed to load package document");t=await this.#loadXML("META-INF/encryption.xml");await this.#encryption.init(t,r),this.resources=new oe({opf:r,resolveHref:e=>W(e,i)});const s=new ae({loadText:this.loadText,loadBlob:e=>Promise.resolve(this.loadBlob(e)).then(this.#encryption.getDecoder(e)),resources:this.resources});this.sections=this.resources.spine.map((e,t)=>{var{idref:i,linear:r,properties:e=[]}=e;const n=this.resources.getItemByID(i);return n?{id:this.resources.getItemByID(i)?.href,load:()=>s.loadItem(n),unload:()=>s.unloadItem(n),createDocument:()=>this.loadDocument(n),size:this.getSize(n.href),cfi:this.resources.cfis[t],linear:r,pageSpread:(e=>{for(const t of e){if("page-spread-left"===t||"rendition:page-spread-left"===t)return"left";if("page-spread-right"===t||"rendition:page-spread-right"===t)return"right";if("rendition:page-spread-center"===t)return"center"}})(e),resolveHref:e=>W(e,n.href),loadMediaOverlay:()=>this.loadMediaOverlay(n)}:(console.warn(`Could not find item with ID "${i}" in manifest`),null)}).filter(e=>e);const{navPath:n,ncxPath:o}=this.resources;if(n)try{var a=_(await this.#loadXML(n),e=>W(e,n));this.toc=a.toc,this.pageList=a.pageList,this.landmarks=a.landmarks}catch(e){console.warn(e)}if(!this.toc&&o)try{var l=Y(await this.#loadXML(o),e=>W(e,o));this.toc=l.toc,this.pageList=l.pageList}catch(e){console.warn(e)}this.landmarks??=this.resources.guide;const{metadata:c,rendition:d,media:h}=(e=>{const{$:t,$$:i}=j(e,O.OPF),r=t(e.documentElement,"metadata"),s=Array.from(r.children),l=(o,t)=>{if(!t)return null;const{props:e=[],attrs:i=[]}=o,r=z(t);if(!e.length&&!i.length)return r;var n=t.getAttribute("id");const a=n?s.filter($("refines","#"+n)):[];return Object.fromEntries([["value",r]].concat(e.map(e=>{var{many:t,recursive:i}=e,r="string"==typeof e?e:e.name,n=$("property",r);const s=i?o:e;return[U(r),t?a.filter(n).map(e=>l(s,e)):l(s,a.find(n))]})).concat(i.map(e=>[U(e),t.getAttribute(e)])))},o=s.filter($("refines",null));e=t=>Object.fromEntries(i(r,"meta").filter($("property",e=>e?.startsWith(t))).map(e=>[e.getAttribute("property").replace(t,""),z(e)]));return{metadata:Object.fromEntries(V.map(t=>{const{type:e,name:i,many:r}=t;var n="meta"===e?e=>e.namespaceURI===O.OPF&&e.getAttribute("property")===i:e=>e.namespaceURI===O.DC&&e.localName===i;return[U(i),r?o.filter(n).map(e=>l(t,e)):l(t,o.find(n))]})),rendition:e("rendition:"),media:e("media:")}})(r);this.rendition=d,this.media=h,h.duration=Q(h.duration),this.dir=this.resources.pageProgressionDirection,this.rawMetadata=c;l=c?.title?.[0];this.metadata={title:l?.value,sortAs:l?.fileAs,language:c?.language,identifier:ie(r),description:c?.description?.value,publisher:c?.publisher?.value,published:c?.date,modified:c?.dctermsModified,subject:c?.subject?.filter(({value:e,code:t})=>e||t)?.map(({value:e,code:t,scheme:i})=>({name:e,code:t,scheme:i})),rights:c?.rights?.value};const u={art:"artist",aut:"author",bkp:"producer",clr:"colorist",edt:"editor",ill:"illustrator",trl:"translator",pbl:"publisher"};r=i=>e=>{var t=[...new Set(e.role?.map(({value:e,scheme:t})=>(t&&"marc:relators"!==t?null:u[e])??i))],e={name:e.value,sortAs:e.fileAs};return[t.length?t:[i],e]};return c?.creator?.map(r("author"))?.concat(c?.contributor?.map?.(r("contributor")))?.forEach(([e,t])=>e.forEach(e=>{this.metadata[e]?this.metadata[e].push(t):this.metadata[e]=[t]})),this}async loadDocument(e){var t=await this.loadText(e.href);return this.parser.parseFromString(t,e.mediaType)}async loadMediaOverlay(e){e=e.mediaOverlay;if(!e)return null;const t=this.resources.getItemByID(e);e=await this.#loadXML(t.href);return ee(e,e=>W(e,t.href))}resolveCFI(e){return this.resources.resolveCFI(e)}resolveHref(e){const[t,i]=e.split("#"),r=this.resources.getItemByHref(decodeURI(t));return r?{index:this.resources.spine.findIndex(({idref:e})=>e===r.id),anchor:i?e=>((e,t)=>e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`))(e,i):()=>0}:null}splitTOCHref(e){return e?.split("#")??[]}getTOCFragment(e,t){return e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`)}isExternal(e){return X(e)}async getCover(){var e=this.resources?.cover;return e?.href?new Blob([await this.loadBlob(e.href)],{type:e.mediaType}):null}async getCalibreBookmarks(){const e=await this.loadText("META-INF/calibre_bookmarks.txt");var t="encoding=json+base64:";if(e?.startsWith(t)){t=atob(e.slice(t.length));return JSON.parse(t)}}}class ce{static getReaderConfig(e){return(JSON.parse(localStorage.getItem("readerConfig"))||{})[e]}static setReaderConfig(e,t){let i=JSON.parse(localStorage.getItem("readerConfig"))||{};i[e]=t,localStorage.setItem("readerConfig",JSON.stringify(i))}static getKookitConfig(e){return(JSON.parse(localStorage.getItem("kookitConfig"))||{})[e]}static setKookitConfig(e,t){let i=JSON.parse(localStorage.getItem("kookitConfig"))||{};i[e]=t,localStorage.setItem("kookitConfig",JSON.stringify(i))}static removeKookitConfig(){localStorage.removeItem("kookitConfig")}}let de=!1;const he=e=>Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address")),ue=e=>e.trim().replace(/(\r\n|\n|\r|\t)/gm,"").substring(0,100),fe=(c,d,h,u,f,p,m)=>g(void 0,void 0,void 0,function*(){var t="yes"===ce.getReaderConfig("isSliding");let e=document.getElementById("page-area");if(e){var i,r,n,s,o,a,l=e.getElementsByTagName("iframe")[0];if(l){let e=l.contentDocument;e&&(l=(l=Math.floor(c.clientWidth/12))%2==0?l:l-1,0{let n=window._.findLastIndex(i,{href:t});return n=t&&-1g(void 0,void 0,void 0,function*(){var e=parseInt(ce.getKookitConfig("chapterDocIndex")||"0"),t=ce.getKookitConfig("chapterHref")||"";0===e||(t=pe(e,t,r,"prev"))&&(ce.setKookitConfig("text","prevChapter"),ce.setKookitConfig("page",""),yield ge(t.index,t.label,t.href,r,i,n,s))}),ge=(a,l,c,d,h,u,f)=>g(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){let t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;var s,i,r,n,o;e&&(e.body.innerHTML="",t.height="0px",e.body.scrollTo(0,0),(-1===(a=l&&!a||d[a]&&d[a].label&&l&&l!==d[a].label&&-1===c.indexOf("#")?window._.findLastIndex(d,{label:l}):a)||a>d.length-1)&&(a=0),e.body.innerHTML=yield p(d[a].text),s=e,yield g(void 0,void 0,void 0,function*(){var t=Array.from(s.getElementsByTagName("link"));for(let e=0;e{console.log("finished")}}let i=[];for(let e=0;e{n.addEventListener("load",e)}))}try{yield Promise.race([Promise.all(i),new Promise((e,t)=>{setTimeout(()=>{t(new Error("Timeout"))},1e3)})])}catch(e){console.log(e)}}),ce.setKookitConfig("chapterTitle",l),ce.setKookitConfig("chapterHref",c),ce.setKookitConfig("chapterDocIndex",a+""),ce.setKookitConfig("percentage",a/d.length+""),ce.setKookitConfig("text",""),i=h,r=u,n=t,o=f,yield g(void 0,void 0,void 0,function*(){let t=n.contentDocument;if(t)if(yield Promise.all(Array.from([...t.images,...t.querySelectorAll("image")]).map(t=>t.complete?Promise.resolve(0!==t.naturalHeight):new Promise(e=>{t.addEventListener("load",()=>e(!0)),t.addEventListener("error",()=>e(!1))}))).then(e=>{e.every(e=>e)?console.log("all images loaded successfully!!"):console.log("some images failed to load, all finished loading")}),yield b(i,r,o),m(),"scroll"!==r){if(n.height=i.clientHeight+"px","double"===r){var e=Math.floor(i.clientWidth/12),e=(i.clientWidth+(e%2==0?e:e-1))/2;if((t.body.scrollWidth-t.body.clientWidth)/e%2==1){let e=document.createElement("div");e.setAttribute("style","height: "+t.body.clientHeight+"px"),t.body.appendChild(e)}}}else n.height=t.body.scrollHeight+"px",n.height=t.body.scrollHeight+"px"}),ye(h,u,"","","",""))}}}),ye=(a,l,c,d,h,u)=>g(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var s=e.getElementsByTagName("iframe")[0];if(s){let n=s.contentDocument;if(n){let t=0,i=0,r=n.body;if(u&&"scroll"!==l){s=Math.floor(a.clientWidth/12),s=a.clientWidth+(s%2==0?s:s-1);i=s*(parseInt(u)-1)}else if(c){let e=he(n.body);var o=e.filter((e,t)=>ue(e.textContent).slim()&&(ue(e.textContent).slim()===ue(c).slim()||ue(e.textContent).slim()===window.ChineseS2T.t2s(ue(c).slim())||ue(e.textContent).slim()===window.ChineseS2T.s2t(ue(c)).slim())&&(Math.abs(t-parseInt(d))<2||"search"===d));if(0===o.length)return void console.log("failed");r=be(o[0],a,l),i=r?y(r.offsetLeft)-y(r.marginLeft||parseFloat(getComputedStyle(r).marginLeft)):"prevChapter"===c?n.body.scrollWidth:0,t=r?y(r.offsetTop)-y(r.marginTop||parseInt(getComputedStyle(r).marginTop)):0}else if(h&&-1{var r=Math.floor(t.clientWidth/12),r=r%2==0?r:r-1;return"scroll"!==i&&parseInt(y(e.offsetLeft)-y(e.marginLeft||parseFloat(getComputedStyle(e).marginLeft))+"")%((t.clientWidth+r)/2)!=0&&e.parentElement?be(e.parentElement,t,i):e},ve=(s,o,a)=>g(void 0,void 0,void 0,function*(){if(!de){let e=document.getElementById("page-area");if(e){var r=e.getElementsByTagName("iframe")[0];if(r){var r=r.contentDocument;if(r){let t=he(r.body);var r=t.filter(e=>Le(s,e,o)&&(e.textContent||"").trim()),n=r[0];let i=0;for(let e=0;e{let e=ce.getKookitConfig("chapterHref")||"",r=e.lastIndexOf("#"),n=e.substring(0,r),s=e.substring(r+1);for(let e=0;e-1)ce.setKookitConfig("chapterHref",e)}}})(r,a),n&&!((e,t,i)=>{let r=Math.floor(t.clientWidth/12),n=r%2===0?r:r-1;if(Math.abs(e.offsetLeft-be(e,t,i).offsetLeft)>(t.clientWidth+n)/2)return true;else return false})(n,s,o)?(ce.setKookitConfig("text",n&&n.textContent||""),ce.setKookitConfig("count",i+""),ce.setKookitConfig("page","")):ce.setKookitConfig("page",(null===(r=yield l(o))||void 0===r?void 0:r.currentPage)+""),de=!0,setTimeout(()=>{de=!1},100)}}}}}),we=(i,e,r,n,s)=>g(void 0,void 0,void 0,function*(){var e=parseInt(ce.getKookitConfig("chapterDocIndex")||"0"),t=ce.getKookitConfig("chapterHref")||"";e>=r.length-1||(t=pe(e,t,r,"next"))&&(ce.setKookitConfig("page",""),yield ge(t.index,t.label,t.href,r,i,n,s))}),xe=(i,r)=>{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let e=he(n.body).filter(e=>!Ce(e)),t=e.filter(e=>Le(i,e,r)&&(e.textContent||"").trim());return("scroll"!==r?t:e).filter(e=>"img"!==e.textContent).map(e=>e.textContent)}}}},Ce=e=>{var t=e.children;let i=!1;for(var r=/^(address|section|blockquote|body|center|dir|div|dl|fieldset|form|h[1-6]|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul|dd|dt|frameset|li|tbody|td|tfoot|th|thead|tr|html)$/i,n=0;n{var r,n=!1,s=t.getBoundingClientRect();return"scroll"!==i&&t.textContent&&t.textContent.trim()?n=-10<(r=s.left)&&r<=e.clientWidth:t.textContent&&t.textContent.trim()?n=(t=s.top)>=e.scrollTop&&t<=e.scrollTop+e.clientHeight:"scroll"!==i&&(n=0<=(s=s.left)&&s<=e.clientWidth),n};const ke={svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",html:"text/html",htm:"text/html",xml:"text/xml",xhtml:"application/xhtml+xml",css:"text/css"},Te={"image/svg+xml":"svg","image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","application/zip":"zip","application/x-rar-compressed":"rar","application/x-7z-compressed":"7z","application/x-tar":"tar","text/html":"html","text/xml":"xml","application/xhtml+xml":"xhtml","text/css":"css"};class Se extends class{constructor(){this.callbacks={},this.callbacks.base={}}on(e,t){const i=this;if(void 0===e||""===e)return console.warn("wrong names"),!1;if(void 0===t)return console.warn("wrong callback"),!1;const r=this.resolveNames(e);return r.forEach(function(e){e=i.resolveName(e);i.callbacks[e.namespace]instanceof Object||(i.callbacks[e.namespace]={}),i.callbacks[e.namespace][e.value]instanceof Array||(i.callbacks[e.namespace][e.value]=[]),i.callbacks[e.namespace][e.value].push(t)}),this}off(e){const r=this;if(void 0===e||""===e)return console.warn("wrong name"),!1;const t=this.resolveNames(e);return t.forEach(function(e){var t=r.resolveName(e);if("base"!==t.namespace&&""===t.value)delete r.callbacks[t.namespace];else if("base"===t.namespace)for(const i in r.callbacks)r.callbacks[i]instanceof Object&&r.callbacks[i][t.value]instanceof Array&&(delete r.callbacks[i][t.value],0===Object.keys(r.callbacks[i]).length&&delete r.callbacks[i]);else r.callbacks[t.namespace]instanceof Object&&r.callbacks[t.namespace][t.value]instanceof Array&&(delete r.callbacks[t.namespace][t.value],0===Object.keys(r.callbacks[t.namespace]).length&&delete r.callbacks[t.namespace])}),this}trigger(e,t=[]){if(void 0===e||""===e)return console.warn("wrong name"),!1;const i=this;const r=t instanceof Array?t:[];let n=this.resolveNames(e);n=this.resolveName(n[0]),setTimeout(()=>{if("base"===n.namespace)for(const e in i.callbacks){if(i.callbacks[e]instanceof Object&&i.callbacks[e][n.value]instanceof Array&&i.callbacks[e][n.value])i.callbacks[e][n.value].forEach(function(e){e.apply(i,r)});else if(this.callbacks[n.namespace]instanceof Object&&i.callbacks[n.namespace][n.value]){if(""===n.value)return console.warn("wrong name"),this;i.callbacks[n.namespace][n.value].forEach(function(e){e.apply(i,r)})}return null}},100)}resolveNames(e){let t=e;return t=t.replace(/[^a-zA-Z0-9 ,/.]/g,""),t=t.replace(/[,/]+/g," "),t=t.split(" "),t}resolveName(e){const t={};var i=e.split(".");return t.original=e,t.value=i[0],t.namespace="base",1g(this,void 0,void 0,function*(){let e=new f(h);this.chapterList=yield e.getChapter(h.toc),this.chapterDocList=yield e.getChapterDoc();var t=this.chapterList,i=this.chapterDocList.map(e=>({href:e.href,label:e.label})),n=yield Promise.all(this.chapterDocList.map(i=>g(this,void 0,void 0,function*(){let t="";if(i.text.load){let e=yield fetch(yield i.text.load()).then(e=>e.blob());t=yield e.text()}return t})));let s=new window.JSZip;s.file("toc.json",JSON.stringify(t)),s.file("sections.json",JSON.stringify(i));let o=[];for(let r=0;re.blob());e.file(t+"."+Te[a.type],a),i[t].src="imgs/"+r+"/"+t+"."+Te[a.type]}catch(e){console.log(e)}}var l=Array.from(e.getElementsByTagName("link"));for(let i=0;ie.blob());t.file(i+"."+Te[c.type],c),e.href="css/"+r+"/"+i+"."+Te[c.type]}catch(e){console.log(e)}}o.push(e.documentElement.innerHTML)}let r=s.folder("chapters");for(let e=0;eg(this,void 0,void 0,function*(){d(yield new Response(e).arrayBuffer())})).catch(e=>{d("err")})}))}resolveChapter(e){var t=e;let i=-1;for(let e=0;e{let e=document.getElementById("page-area");if(e){var o=e.getElementsByTagName("iframe")[0];if(o){o=o.contentDocument;if(o){let e=he(o.body).filter(e=>!Ce(e)),t=e.filter(e=>(e.textContent||"").trim()),i=("scroll"!==s?t:e).filter(e=>"img"!==e.textContent).map(e=>e.textContent),r=0;return xe(n,s)&&0{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let e=he(n.body),t=e.filter(e=>(e.getAttribute("style")===r&&e.setAttribute("style",""),(e.textContent||"").trim()&&e.textContent===i));0!Ce(e));for(let e=0;esetTimeout(e,1e3))),yield ve(this.element,this.mode,this.flatChapter(this.chapterList))})}getPosition(){return{text:ce.getKookitConfig("text"),chapterTitle:ce.getKookitConfig("chapterTitle"),chapterDocIndex:ce.getKookitConfig("chapterDocIndex"),chapterHref:ce.getKookitConfig("chapterHref"),count:ce.getKookitConfig("count"),percentage:ce.getKookitConfig("percentage"),page:ce.getKookitConfig("page")}}setStyle(t){let e=document.getElementById("page-area");if(e){var i=e.getElementsByTagName("iframe")[0];if(i){let e=i.contentDocument;e&&e.body.setAttribute("style",t+e.body.getAttribute("style"))}}}}const Ae=e=>{if(!e)return"";const t=document.createElement("textarea");return t.innerHTML=e,t.value},Be={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},Ee={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},Me={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},Ie={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"]},Re={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},De={magic:[0,4,"string"],length:[4,4,"uint"],count:[8,4,"uint"]},Ne={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"]},Oe={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},He={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},Ue={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},Fe={magic:[0,4,"string"],numEntries:[8,4,"uint"]},$e={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},Pe={1252:"windows-1252",65001:"utf-8"},ze={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"]},je={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"]},We=(e,t)=>{const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},Xe=(e,t,i)=>{const r=new e.constructor(e.length+t.length+i.length);return r.set(e),r.set(t,e.length),r.set(i,e.length+t.length),r},qe=new TextDecoder,Ke=e=>qe.decode(e),Ge=e=>{if(e){var t=e.byteLength,t=4===t?"getUint32":2===t?"getUint16":"getUint8";return new DataView(e)[t](0)}},Je=(e,n)=>Object.fromEntries(Array.from(Object.entries(e)).map(([e,[t,i,r]])=>[e,("string"===r?Ke:Ge)(n.slice(t,t+i))])),Ze=e=>new TextDecoder(Pe[e]),Ve=(e,t=0)=>{let i=0,r=0;for(const n of e.subarray(t,t+4))if(i=i<<7|(127&n)>>>0,r++,128&n)break;return{value:i,length:r}},_e=e=>{let t=0;for(;0>=1)1==(1&e)&&t++;return t},Ye=e=>{let t=0;for(;0==(1&e);)e>>=1,t++;return t},Qe=t=>{let i=[];for(let e=0;e>>3,o=3+(7&n);for(let e=0;e{const r=await i(t.huffcdic),{magic:e,offset1:n,offset2:s}=Je(He,r);if("HUFF"!==e)throw new Error("Invalid HUFF record");const h=Array.from({length:256},(e,t)=>n+4*t).map(e=>Ge(r.slice(e,e+4))).map(e=>[128&e,31&e,e>>>8]),u=[null].concat(Array.from({length:32},(e,t)=>s+8*t).map(e=>[Ge(r.slice(e,e+4)),Ge(r.slice(e+4,e+8))])),f=[];for(let e=1;e{let a=new Uint8Array;var l=8*o.byteLength;for(let s=0;s{var e=i+32,r=e>>3;let n=0n;for(let e=i>>3;e<=r;e++)n=n<<8n|BigInt(t[e]??0);return n>>8n-BigInt(7&e)&0xffffffffn})(o,s));let[e,t,i]=h[c>>>24];if(!e){for(;c>>>32-tl)break;var d=i-(c>>>32-t);let[r,n]=f[d];n||(r=p(r),f[d]=[r,!0]),a=We(a,r)}return a};return p},tt=async(t,i)=>{const e=await i(t),r=Je(Ne,e);if("INDX"!==r.magic)throw new Error("Invalid INDX record");const n=Ze(r.encoding),s=e.slice(r.length);var o=Je(Oe,s);if("TAGX"!==o.magic)throw new Error("Invalid TAGX section");var a=(o.length-12)/4,l=Array.from({length:a},(e,t)=>new Uint8Array(s.slice(12+4*t,12+4*t+4)));const c={};let d=0;for(let e=0;e>Ye(C),null,x]));const $={};for([A,B,E,M]of F){const P=[];if(null!=B)for(let e=0;eGe(i.slice(8*t,8*t+4))).map((e,t,i)=>[e,i[t+1]])}loadRecord(e){e=this.#offsets[e];if(!e)throw new RangeError("Record index out of bounds");return this.#file.slice(...e).arrayBuffer()}async loadMagic(e){e=this.#offsets[e][0];return Ke(await this.#file.slice(e,e+4).arrayBuffer())}}{#start=0;#resourceStart;#decoder;#encoder;#decompress;#removeTrailingEntries;constructor({unzlib:e}){super(),this.unzlib=e}async open(e){await super.open(e),this.headers=this.#getHeaders(await super.loadRecord(0)),this.#resourceStart=this.headers.mobi.resourceStart;let t=8<=this.headers.mobi.version;if(!t){e=this.headers.exth?.boundary;if(e<4294967295)try{this.headers=this.#getHeaders(await super.loadRecord(e)),this.#start=e,t=!0}catch(e){console.warn(e),console.warn("Failed to open KF8; falling back to MOBI")}}return await this.#setup(),new(t?ht:st)(this).init()}#getHeaders(e){var t=Je(Me,e);const i=Je(Ie,e);if("MOBI"!==i.magic)throw new Error("Missing MOBI header");var{titleOffset:r,titleLength:n,localeLanguage:s,localeRegion:o}=i;i.title=e.slice(r,r+n);s=je[s];i.language=s?.[o>>2]??s?.[0];s=64&i.exthFlag?((t,e)=>{var{magic:i,count:r}=Je(De,t);if("EXTH"!==i)throw new Error("Invalid EXTH header");const n=Ze(e),s={};let o=12;for(let e=0;ee:2===e?Qe:17480===e?await et(t,this.loadRecord.bind(this)):null,!this.#decompress)throw new Error("Unknown compression type");var t=t["trailingFlags"];const r=1&t,n=_e(t>>>1);this.#removeTrailingEntries=t=>{for(let e=0;e{let t=0;for(const i of e.subarray(-4))128&i&&(t=0),t=t<<7|127&i;return t})(t);t=t.subarray(0,-i)}var e;return r&&(e=1+(3&t[t.length-1]),t=t.subarray(0,-e)),t}}decode(...e){return this.#decoder.decode(...e)}encode(...e){return this.#encoder.encode(...e)}loadRecord(e){return super.loadRecord(this.#start+e)}loadMagic(e){return super.loadMagic(this.#start+e)}loadText(e){return this.loadRecord(e+1).then(e=>new Uint8Array(e)).then(this.#removeTrailingEntries).then(this.#decompress)}async loadResource(e){const t=await super.loadRecord(this.#resourceStart+e);e=Ke(t.slice(0,4));return"FONT"===e?(async(e,t)=>{var{flags:i,dataStart:r,keyLength:n,keyStart:s}=Je($e,e);const o=new Uint8Array(e.slice(r));if(2&i)for(var r=16===n?1024:1040,a=new Uint8Array(e.slice(s,s+n)),l=Math.min(r,o.length),c=0;c{const{table:i,cncx:r}=await tt(e,t),n=i.map(({tagMap:e},t)=>({index:t,offset:e[1]?.[0],size:e[2]?.[0],label:r[e[3]]??"",headingLevel:e[4]?.[0],pos:e[6],parent:e[21]?.[0],firstChild:e[22]?.[0],lastChild:e[23]?.[0]})),s=t=>(null==t.firstChild||(t.children=n.filter(e=>e.parent===t.index).map(s)),t);return n.filter(e=>0===e.headingLevel).map(s)})(e,this.loadRecord.bind(this))}getMetadata(){const{mobi:e,exth:t}=this.headers;return{identifier:e.uid.toString(),title:Ae(t?.title||this.decode(e.title)),author:t?.creator?.map(Ae),publisher:Ae(t?.publisher),language:t?.language??e.language,published:t?.date,description:Ae(t?.description),subject:t?.subject?.map(Ae),rights:Ae(t?.rights)}}async getCover(){var e=this.headers["exth"],e=e?.coverOffset<4294967295?e?.coverOffset:e?.thumbnailOffset<4294967295?e?.thumbnailOffset:null;if(null!=e){e=await this.loadResource(e);return new Blob([e])}}}const rt=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,nt=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi;class st{parser=new DOMParser;serializer=new XMLSerializer;#resourceCache=new Map;#textCache=new Map;#cache=new Map;#sections;#fileposList=[];#type=Be.HTML;constructor(e){this.mobi=e}async init(){let t=new Uint8Array;for(let e=0;eString.fromCharCode(e)).join("");this.#sections=[0].concat(Array.from(r.matchAll(rt),e=>e.index)).map((e,t,i)=>r.slice(e,i[t+1])).map(e=>Uint8Array.from(e,e=>e.charCodeAt(0))).map(e=>({book:this,raw:e})).reduce((e,t)=>{var i=e[e.length-1];return t.start=i?.end??0,t.end=t.start+t.raw.byteLength,e.concat(t)},[]),this.sections=this.#sections.map((e,t)=>({id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.end-e.start}));try{this.landmarks=await this.getGuide();var e=this.landmarks.find(({type:e})=>e?.includes("toc"))?.href;if(e){var i=this.resolveHref(e)["index"];const n=await this.sections[i].createDocument();let s,o=0,a=0;const l=new Map,c=new Map;this.toc=Array.from(n.querySelectorAll("a[filepos]")).reduce((e,t)=>{var i=(e=>{let t=0;for(;e;){const r=e.parentElement;var i;r&&("p"===(i=r.tagName.toLowerCase())?t+=1.5:"blockquote"===i&&(t+=2)),e=r}return t})(t),r={label:t.innerText?.trim(),href:`filepos:${t.getAttribute("filepos")}`},t=i>a?o+1:i===a?o:l.get(i)??Math.max(0,o-1);if(t>o)s?(s.subitems??=[],s.subitems.push(r),c.set(t,s)):e.push(r);else{const n=c.get(t);(n?n.subitems:e).push(r)}return s=r,o=t,a=i,l.set(i,t),e},[])}}catch(e){console.warn(e)}return this.#fileposList=[...new Set(Array.from(r.matchAll(nt),e=>e[1]))].map(e=>({filepos:e,number:Number(e)})).sort((e,t)=>e.number-t.number),this.metadata=this.mobi.getMetadata(),this.getCover=this.mobi.getCover.bind(this.mobi),this}async getGuide(){const e=await this.createDocument(this.#sections[0]);return Array.from(e.getElementsByTagName("reference"),e=>({label:e.getAttribute("title"),type:e.getAttribute("type")?.split(/\s/),href:`filepos:${e.getAttribute("filepos")}`}))}async loadResource(e){if(this.#resourceCache.has(e))return this.#resourceCache.get(e);var t=await this.mobi.loadResource(e),t=URL.createObjectURL(new Blob([t]));return this.#resourceCache.set(e,t),t}async loadRecindex(e){return this.loadResource(Number(e)-1)}async replaceResources(e){for(const s of e.querySelectorAll("img[recindex]")){var t=s.getAttribute("recindex");try{s.src=await this.loadRecindex(t)}catch(e){console.warn(`Failed to load image ${t}`)}}for(const o of e.querySelectorAll("[mediarecindex]")){var i=o.getAttribute("mediarecindex"),r=o.getAttribute("recindex");try{o.src=await this.loadRecindex(i),r&&(o.poster=await this.loadRecindex(r))}catch(e){console.warn(`Failed to load media ${i}`)}}for(const a of e.querySelectorAll("[filepos]")){var n=a.getAttribute("filepos");a.href=`filepos:${n}`}}async loadText(t){if(this.#textCache.has(t))return this.#textCache.get(t);const r=t["raw"],n=this.#fileposList.filter(({number:e})=>e>=t.start&&e({...e,offset:e.number-t.start}));let s=r;n.length&&(s=r.subarray(0,n[0].offset),n.forEach(({filepos:e,offset:t},i)=>{i=n[i+1],e=this.mobi.encode(``);s=Xe(s,e,r.subarray(t,i?.offset))}));var e=this.mobi.decode(s).replaceAll(rt,"");return this.#textCache.set(t,e),e}async createDocument(e){e=await this.loadText(e);return this.parser.parseFromString(e,this.#type)}async loadSection(e){if(this.#cache.has(e))return this.#cache.get(e);const t=await this.createDocument(e),i=t.createElement("style");t.head.append(i),i.append(t.createTextNode(`blockquote { margin-block-start: 0; margin-block-end: 0; margin-inline-start: 1em; diff --git a/src/components/imageViewer/component.tsx b/src/components/imageViewer/component.tsx index 44a6d924..370d83cf 100644 --- a/src/components/imageViewer/component.tsx +++ b/src/components/imageViewer/component.tsx @@ -81,9 +81,9 @@ class ImageViewer extends React.Component { this.setState({ zoomIndex: this.state.zoomIndex + 1 }, () => { if (this.state.imageRatio === "horizontal") { image.style.width = `${60 + this.state.zoomIndex * 10}vw`; + image.style.marginTop = `${10 * this.state.zoomIndex}vh`; } else { image.style.height = `${100 + 10 * this.state.zoomIndex}vh`; - image.style.marginTop = `${10 * this.state.zoomIndex}vh`; } }); }; diff --git a/src/constants/settingList.tsx b/src/constants/settingList.tsx index 07cab995..6d485fc1 100644 --- a/src/constants/settingList.tsx +++ b/src/constants/settingList.tsx @@ -84,7 +84,7 @@ export const settingList = [ propName: "isLemmatizeWord", }, { - isElectron: false, + isElectron: true, title: "Open books in the main window", desc: "Book won't be opened in a separate window but directly opened in the main window", propName: "isOpenInMain", diff --git a/src/containers/htmlViewer/component.tsx b/src/containers/htmlViewer/component.tsx index f0543aad..361c3e11 100644 --- a/src/containers/htmlViewer/component.tsx +++ b/src/containers/htmlViewer/component.tsx @@ -61,11 +61,7 @@ class Viewer extends React.Component { this.props.handleRenderBookFunc(this.handleRenderBook); window.addEventListener("resize", () => { - if (StorageUtil.getReaderConfig("isFullscreen") === "yes") { - this.handleRenderBook(); - } else { - BookUtil.reloadBooks(); - } + BookUtil.reloadBooks(); }); } handlePageWidth = () => { @@ -318,7 +314,10 @@ class Viewer extends React.Component { this.setState({ rect }); }); doc.addEventListener("contextmenu", (event) => { - event.preventDefault(); + if (document.location.href.indexOf("localhost") === -1) { + event.preventDefault(); + } + if (!this.state.isDisablePopup && !this.state.isTouch) return; if (!doc!.getSelection() || doc!.getSelection()!.rangeCount === 0) return; diff --git a/src/containers/panels/operationPanel/component.tsx b/src/containers/panels/operationPanel/component.tsx index 7959e5f9..ec52b9a5 100644 --- a/src/containers/panels/operationPanel/component.tsx +++ b/src/containers/panels/operationPanel/component.tsx @@ -12,6 +12,7 @@ import toast from "react-hot-toast"; import { HtmlMouseEvent } from "../../../utils/serviceUtils/mouseEvent"; import storageUtil from "../../../utils/serviceUtils/storageUtil"; import BingTTSUtil from "../../../utils/serviceUtils/bingTTSUtil"; +import { isElectron } from "react-device-detect"; declare var document: any; declare var window: any; class OperationPanel extends React.Component< @@ -78,9 +79,12 @@ class OperationPanel extends React.Component< this.props.handleHtmlBook(null); } setTimeout(() => { - if (StorageUtil.getReaderConfig("isOpenInMain") === "yes") { - this.props.history.push("/manager/home"); - document.title = "Koodo Reader"; + if (isElectron) { + if (StorageUtil.getReaderConfig("isOpenInMain") === "yes") { + window.require("electron").ipcRenderer.invoke("exit-tab", "ping"); + } else { + window.close(); + } } else { window.close(); } @@ -88,21 +92,53 @@ class OperationPanel extends React.Component< } //控制进入全屏 handleFullScreen() { - let de: any = document.documentElement; - if (de.requestFullscreen) { - de.requestFullscreen(); + if (isElectron) { + if (StorageUtil.getReaderConfig("isOpenInMain") === "yes") { + window + .require("electron") + .ipcRenderer.invoke("enter-tab-fullscreen", "ping"); + } else { + window + .require("electron") + .ipcRenderer.invoke("enter-fullscreen", "ping"); + } + } else { + let de: any = document.documentElement; + if (de.requestFullscreen) { + de.requestFullscreen(); + } } + StorageUtil.setReaderConfig("isFullscreen", "yes"); + if (StorageUtil.getReaderConfig("isOpenInMain") === "yes" && isElectron) { + window.require("electron").ipcRenderer.invoke("adjust-tab-size", "ping"); + } } // 退出全屏模式 handleExitFullScreen() { - //解决使用esc退出全屏,再退出阅读时发生的bug - if (!document.fullscreenElement) return; + if (isElectron) { + if (StorageUtil.getReaderConfig("isOpenInMain") === "yes") { + window + .require("electron") + .ipcRenderer.invoke("exit-tab-fullscreen", "ping"); + } else { + window + .require("electron") + .ipcRenderer.invoke("exit-fullscreen", "ping"); + } + } else { + //解决使用esc退出全屏,再退出阅读时发生的bug + if (!document.fullscreenElement) return; - if (document.exitFullscreen) { - document.exitFullscreen(); + if (document.exitFullscreen) { + document.exitFullscreen(); + } } + StorageUtil.setReaderConfig("isFullscreen", "no"); + if (StorageUtil.getReaderConfig("isOpenInMain") === "yes" && isElectron) { + window.require("electron").ipcRenderer.invoke("adjust-tab-size", "ping"); + } } handleAddBookmark = () => { let bookKey = this.props.currentBook.key; diff --git a/src/pages/pdfReader/component.tsx b/src/pages/pdfReader/component.tsx index 839400d9..98cadc0b 100644 --- a/src/pages/pdfReader/component.tsx +++ b/src/pages/pdfReader/component.tsx @@ -25,6 +25,7 @@ class Viewer extends React.Component { rect: null, loading: true, isDisablePopup: StorageUtil.getReaderConfig("isDisablePopup") === "yes", + isTouch: StorageUtil.getReaderConfig("isTouch") === "yes", }; } UNSAFE_componentWillMount() { @@ -83,10 +84,14 @@ class Viewer extends React.Component { // iWin.getSelection() && showHighlight(getHightlightCoords()); }); doc.addEventListener("contextmenu", (event) => { - if (!this.state.isDisablePopup) return; + if (document.location.href.indexOf("localhost") === -1) { + event.preventDefault(); + } + + if (!this.state.isDisablePopup && !this.state.isTouch) return; if (!doc!.getSelection() || doc!.getSelection().rangeCount === 0) return; - event.preventDefault(); + var rect = doc!.getSelection()!.getRangeAt(0).getBoundingClientRect(); this.setState({ rect, diff --git a/src/pages/pdfReader/interface.tsx b/src/pages/pdfReader/interface.tsx index 9da57a6b..b586efe0 100644 --- a/src/pages/pdfReader/interface.tsx +++ b/src/pages/pdfReader/interface.tsx @@ -23,6 +23,7 @@ export interface ViewerState { title: string; cfiRange: any; contents: any; + isTouch: boolean; rect: any; loading: boolean; isDisablePopup: boolean; diff --git a/src/utils/fileUtils/bookUtil.tsx b/src/utils/fileUtils/bookUtil.tsx index 8ce7a173..73a9a506 100644 --- a/src/utils/fileUtils/bookUtil.tsx +++ b/src/utils/fileUtils/bookUtil.tsx @@ -161,27 +161,29 @@ class BookUtil { toast.error(t("Book not exist")); return; } - if (StorageUtil.getReaderConfig("isOpenInMain") === "yes") { - history.push( - BookUtil.getBookUrl(book) + `?title=${book.name}&file=${book.key}` - ); - return; - } let ref = book.format.toLowerCase(); if (isElectron) { - const { ipcRenderer } = window.require("electron"); - ipcRenderer.invoke("open-book", { - url: `${window.location.href.split("#")[0]}#/${ref}/${book.key}?title=${ - book.name - }&file=${book.key}`, - isMergeWord: - book.format === "PDF" - ? "no" - : StorageUtil.getReaderConfig("isMergeWord"), - isFullscreen: StorageUtil.getReaderConfig("isAutoFullscreen"), - isPreventSleep: StorageUtil.getReaderConfig("isPreventSleep"), - }); + if (StorageUtil.getReaderConfig("isOpenInMain") === "yes") { + window.require("electron").ipcRenderer.invoke("new-tab", { + url: `${window.location.href.split("#")[0]}#/${ref}/${ + book.key + }?title=${book.name}&file=${book.key}`, + }); + } else { + const { ipcRenderer } = window.require("electron"); + ipcRenderer.invoke("open-book", { + url: `${window.location.href.split("#")[0]}#/${ref}/${ + book.key + }?title=${book.name}&file=${book.key}`, + isMergeWord: + book.format === "PDF" + ? "no" + : StorageUtil.getReaderConfig("isMergeWord"), + isAutoFullscreen: StorageUtil.getReaderConfig("isAutoFullscreen"), + isPreventSleep: StorageUtil.getReaderConfig("isPreventSleep"), + }); + } } else { window.open( `${window.location.href.split("#")[0]}#/${ref}/${book.key}?title=${ @@ -226,12 +228,15 @@ class BookUtil { static reloadBooks() { if (isElectron) { if (StorageUtil.getReaderConfig("isOpenInMain") === "yes") { - window.require("electron").ipcRenderer.invoke("reload-main", "ping"); + window.require("electron").ipcRenderer.invoke("reload-tab", "ping"); } else { window.require("electron").ipcRenderer.invoke("reload-reader", "ping"); } } else { - window.location.reload(); + if (StorageUtil.getReaderConfig("isFullscreen") === "yes") { + } else { + window.location.reload(); + } } } static getRendtion = ( diff --git a/src/utils/readUtils/linkUtil.tsx b/src/utils/readUtils/linkUtil.tsx index 1c5bf7f7..83a8ca2b 100644 --- a/src/utils/readUtils/linkUtil.tsx +++ b/src/utils/readUtils/linkUtil.tsx @@ -1,7 +1,6 @@ import { openExternalUrl } from "../serviceUtils/urlUtil"; export const handleLinkJump = async (event: any, rendition: any = {}) => { - console.log("gdfdgfdg"); let href; if (event.target) { href = @@ -17,7 +16,6 @@ export const handleLinkJump = async (event: any, rendition: any = {}) => { event.target.parentNode.getAttribute("src")))) || ""; } - console.log(href, "sfsdf"); if (href && href.indexOf("#") > -1) { let pageArea = document.getElementById("page-area"); if (!pageArea) return; @@ -27,7 +25,6 @@ export const handleLinkJump = async (event: any, rendition: any = {}) => { if (!doc) { return; } - console.log(href, "href"); if (href.indexOf("#") !== 0) { let chapterInfo = rendition.resolveChapter(href.split("#")[0]); await rendition.goToChapter( @@ -37,7 +34,6 @@ export const handleLinkJump = async (event: any, rendition: any = {}) => { ); } let id = href.split("#").reverse()[0]; - console.log(doc.body.querySelector("#" + id)); await rendition.goToNode(doc.body.querySelector("#" + id) || doc.body); } else if (href && rendition.resolveChapter(href)) { let chapterInfo = rendition.resolveChapter(href);