@d-i-t-a/reader 3.0.0-alpha.18 → 3.0.0-alpha.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/reader.js CHANGED
@@ -662,7 +662,7 @@ pdfjs-views-manager-paste-button-label = Paste`)}},Wte=1e3,Fw=50,NL=1e3;Lh=class
662
662
  display: none !important;
663
663
  }
664
664
  `,e.head.appendChild(i)}interceptSourceAccess(){let n=this,e=Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype,"src"),t=Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype,"currentSrc");if(this.originalGetters.set("src",e),this.originalGetters.set("currentSrc",t),e?.get){let i=e.get;Object.defineProperty(HTMLMediaElement.prototype,"src",{get(){return n.originalSrcs.has(this)?i.call(this):i.call(this)},set:e.set,configurable:!0,enumerable:!0})}if(t?.get){let i=t.get;Object.defineProperty(HTMLMediaElement.prototype,"currentSrc",{get(){let r=i.call(this);return r.startsWith("blob:")?r:n.originalSrcs.has(this)?"":r},configurable:!0,enumerable:!0})}}restoreSourceAccess(){let n=this.originalGetters.get("src"),e=this.originalGetters.get("currentSrc");n&&Object.defineProperty(HTMLMediaElement.prototype,"src",n),e&&Object.defineProperty(HTMLMediaElement.prototype,"currentSrc",e),this.originalGetters.clear()}startRecordingDetection(){if(!navigator.mediaDevices?.enumerateDevices)return;(async()=>{try{let t=(await navigator.mediaDevices.enumerateDevices()).filter(i=>i.kind==="audiooutput"&&(i.label.toLowerCase().includes("virtual")||i.label.toLowerCase().includes("cable")||i.label.toLowerCase().includes("stereo mix")));t.length>0&&this.config.onEvent?.({type:"media_protected",timestamp:Date.now(),detail:`recording_suspected: ${t.map(i=>i.label).join(", ")}`})}catch{}})()}},KM=class{constructor(n){this.originalMediaRecorder=null,this.originalCreateMediaStreamSource=null,this.originalCreateMediaElementSource=null,this.originalCaptureStream=null,this.originalCanvasCaptureStream=null,this.originalGetDisplayMedia=null,this.config={chunkSize:512*1024,audioMimeType:"audio/mpeg",videoMimeType:'video/mp4; codecs="avc1.42E01E,mp4a.40.2"',blockMediaRecorder:!0,blockAudioCapture:!0,blockCaptureStream:!0,blockDisplayCapture:!0,...n}}activate(){this.config.blockMediaRecorder&&this.interceptMediaRecorder(),this.config.blockAudioCapture&&this.interceptAudioCapture(),this.config.blockCaptureStream&&this.interceptCaptureStream(),this.config.blockDisplayCapture&&this.interceptGetDisplayMedia()}deactivate(){this.originalMediaRecorder&&(window.MediaRecorder=this.originalMediaRecorder,this.originalMediaRecorder=null),this.originalCreateMediaStreamSource&&(AudioContext.prototype.createMediaStreamSource=this.originalCreateMediaStreamSource,this.originalCreateMediaStreamSource=null),this.originalCreateMediaElementSource&&(AudioContext.prototype.createMediaElementSource=this.originalCreateMediaElementSource,this.originalCreateMediaElementSource=null),this.originalCaptureStream&&(HTMLMediaElement.prototype.captureStream=this.originalCaptureStream,this.originalCaptureStream=null),this.originalCanvasCaptureStream&&(HTMLCanvasElement.prototype.captureStream=this.originalCanvasCaptureStream,this.originalCanvasCaptureStream=null),this.originalGetDisplayMedia&&navigator.mediaDevices&&(navigator.mediaDevices.getDisplayMedia=this.originalGetDisplayMedia,this.originalGetDisplayMedia=null)}interceptMediaRecorder(){if(typeof MediaRecorder>"u")return;this.originalMediaRecorder=MediaRecorder;let n=this;window.MediaRecorder=class{constructor(t,i){throw n.config.onEvent?.({type:"media_stream_blocked",timestamp:Date.now(),detail:`MediaRecorder blocked \u2014 ${t.getTracks().length} tracks`}),new DOMException("Failed to construct 'MediaRecorder': The MediaRecorder failed to start because the stream is protected.","NotSupportedError")}static isTypeSupported(t){return n.originalMediaRecorder.isTypeSupported(t)}}}interceptAudioCapture(){if(typeof AudioContext>"u")return;let n=this;this.originalCreateMediaElementSource=AudioContext.prototype.createMediaElementSource;let e=this.originalCreateMediaElementSource;AudioContext.prototype.createMediaElementSource=function(i){if(n.isProtectedElement(i))throw n.config.onEvent?.({type:"media_stream_blocked",timestamp:Date.now(),detail:`createMediaElementSource blocked on ${i.tagName.toLowerCase()}`}),new DOMException("Failed to execute 'createMediaElementSource': The media element is protected.","InvalidStateError");return e.call(this,i)},this.originalCreateMediaStreamSource=AudioContext.prototype.createMediaStreamSource;let t=this.originalCreateMediaStreamSource;AudioContext.prototype.createMediaStreamSource=function(i){return n.config.onEvent?.({type:"media_stream_blocked",timestamp:Date.now(),detail:"createMediaStreamSource intercepted"}),t.call(this,i)}}interceptCaptureStream(){let n=this;if(HTMLMediaElement.prototype.captureStream){this.originalCaptureStream=HTMLMediaElement.prototype.captureStream;let e=this.originalCaptureStream;HTMLMediaElement.prototype.captureStream=function(){if(n.isProtectedElement(this))throw n.config.onEvent?.({type:"media_stream_blocked",timestamp:Date.now(),detail:`captureStream blocked on ${this.tagName.toLowerCase()}`}),new DOMException("Failed to execute 'captureStream': The element is protected.","NotSupportedError");return e.call(this)}}if(HTMLCanvasElement.prototype.captureStream){this.originalCanvasCaptureStream=HTMLCanvasElement.prototype.captureStream;let e=this.originalCanvasCaptureStream;HTMLCanvasElement.prototype.captureStream=function(t){if(n.isProtectedElement(this))throw n.config.onEvent?.({type:"media_stream_blocked",timestamp:Date.now(),detail:"canvas captureStream blocked"}),new DOMException("Failed to execute 'captureStream': The canvas is protected.","NotSupportedError");return e.call(this,t)}}}interceptGetDisplayMedia(){if(!navigator.mediaDevices?.getDisplayMedia)return;this.originalGetDisplayMedia=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);let n=this;navigator.mediaDevices.getDisplayMedia=function(e){return n.config.onEvent?.({type:"media_stream_blocked",timestamp:Date.now(),detail:"getDisplayMedia blocked \u2014 screen capture attempt"}),Promise.reject(new DOMException("Failed to execute 'getDisplayMedia': Screen capture is not permitted on this page.","NotAllowedError"))}}isProtectedElement(n){if(this.config.contentRoot.contains(n))return!0;if(this.config.contentIframes)for(let e of this.config.contentIframes)try{if(e.contentDocument?.body?.contains(n))return!0}catch{}return!1}},YM=class{constructor(n){this.sentinels=[],this.isHacked=!1,this.savedVisibility=new Map,this.restoreTimer=null,this.checkInterval=null,this.observers=[],this.config={sentinelCount:3,autoRestore:!1,restoreDelay:1e3,watchProperties:["animation","transition","position","transform","opacity","visibility","display","filter","clip","clip-path"],...n}}get tampered(){return this.isHacked}activate(){this.isHacked=!1,this.placeSentinels(),this.startObserver(),this.checkInterval=setInterval(()=>this.checkSentinels(),2e3)}deactivate(){for(let n of this.sentinels)n.remove();this.sentinels=[];for(let n of this.observers)n.disconnect();this.observers=[],this.restoreTimer!==null&&(clearTimeout(this.restoreTimer),this.restoreTimer=null),this.checkInterval!==null&&(clearInterval(this.checkInterval),this.checkInterval=null),this.restoreContent(),this.isHacked=!1}placeSentinels(){let n=this.config.sentinelCount??3,e=this.config.contentRoot,t=Array.from(e.children);for(let i=0;i<n;i++){let r=document.createElement("div");if(r.style.cssText="width:0;height:0;overflow:hidden;position:absolute;pointer-events:none;",r.dataset.contentProtection="sentinel",r.setAttribute("aria-hidden","true"),t.length>0){let s=Math.floor(i/n*t.length),o=t[Math.min(s,t.length-1)];e.insertBefore(r,o)}else e.appendChild(r);this.sentinels.push(r)}}startObserver(){for(let e of this.sentinels){let t=new MutationObserver(i=>{for(let r of i)if(r.type==="attributes"&&(r.attributeName==="style"||r.attributeName==="class")){this.onTamperDetected("sentinel_style_injected");return}});t.observe(e,{attributes:!0,attributeFilter:["style","class"]}),this.observers.push(t)}let n=new MutationObserver(e=>{for(let t of e)if(t.type==="childList"){for(let i of t.removedNodes)if(this.sentinels.includes(i)){this.onTamperDetected("sentinel_removed");return}}});n.observe(this.config.contentRoot,{childList:!0,subtree:!1}),this.observers.push(n)}checkSentinels(){for(let n of this.sentinels){if(!n.isConnected){this.onTamperDetected("sentinel_removed");return}if(this.hasSuspiciousStyles(n)){this.onTamperDetected("sentinel_style_injected");return}if(this.hasSuspiciousComputedStyles(n)){this.onTamperDetected("computed_style_anomaly");return}}this.isHacked&&this.config.autoRestore&&this.scheduleRestore()}hasSuspiciousStyles(n){return!!(n.style.animation||n.style.transition||n.style.transform||n.style.filter||n.style.clip||n.style.clipPath)}hasSuspiciousComputedStyles(n){try{let e=getComputedStyle(n);if(e.animationName&&e.animationName!=="none"||e.transform&&e.transform!=="none"||e.filter&&e.filter!=="none")return!0}catch{}return!1}onTamperDetected(n){if(!this.isHacked)switch(this.isHacked=!0,this.config.onEvent?.({type:"tamper_detected",timestamp:Date.now(),detail:n}),this.config.action){case"blank":this.blankContent();break;case"scramble":this.blankContent();break;case"callback":break}}blankContent(){for(let n of this.config.protectedElements)this.savedVisibility.has(n)||this.savedVisibility.set(n,n.style.visibility),n.style.setProperty("visibility","hidden","important")}restoreContent(){for(let[n,e]of this.savedVisibility)n.style.visibility=e;this.savedVisibility.clear()}scheduleRestore(){this.restoreTimer===null&&(this.restoreTimer=setTimeout(()=>{this.restoreTimer=null,this.sentinels.some(e=>!e.isConnected||this.hasSuspiciousStyles(e)||this.hasSuspiciousComputedStyles(e))||(this.isHacked=!1,this.restoreContent(),this.config.onEvent?.({type:"tamper_detected",timestamp:Date.now(),detail:"restored"}))},this.config.restoreDelay??1e3))}},bie=class{constructor(n){this.modules=new Map,this.eventLog=[],this.config=n,this.initModules()}initModules(){let n=e=>{this.eventLog.push(e),this.config.onEvent?.(e)};this.config.dragPrevention&&this.modules.set("drag",new PM({...this.config.dragPrevention,onEvent:n})),this.config.printProtection&&this.modules.set("print",new kM({...this.config.printProtection,onEvent:n})),this.config.copyProtection&&this.modules.set("copy",new RM({...this.config.copyProtection,onEvent:n})),this.config.contextMenuProtection&&this.modules.set("contextMenu",new LM({...this.config.contextMenuProtection,onEvent:n})),this.config.keyboardProtection&&this.modules.set("keyboard",new MM({...this.config.keyboardProtection,onEvent:n})),this.config.devToolsDetection&&this.modules.set("devtools",new OM({...this.config.devToolsDetection,onEvent:n})),this.config.textObfuscation&&this.modules.set("obfuscation",new NM({...this.config.textObfuscation,onEvent:n})),this.config.linkUrlHiding&&this.modules.set("linkHiding",new BM(this.config.linkUrlHiding)),this.config.browserEnforcement&&this.modules.set("browser",new DM({...this.config.browserEnforcement,onEvent:n})),this.config.screenshotDetection&&this.modules.set("screenshot",new FM({...this.config.screenshotDetection,onEvent:n})),this.config.watermarking&&this.modules.set("watermark",new HM(this.config.watermarking)),this.config.selectionLimiting&&this.modules.set("selection",new UM({...this.config.selectionLimiting,onEvent:n})),this.config.imageProtection&&this.modules.set("image",new jM({...this.config.imageProtection,onEvent:n})),this.config.antiAutomation&&this.modules.set("automation",new GM({...this.config.antiAutomation,onEvent:n})),this.config.speechSynthesisBlocking&&this.modules.set("speech",new WM({...this.config.speechSynthesisBlocking,onEvent:n})),this.config.contentExpiration&&this.modules.set("expiration",new zM({...this.config.contentExpiration,onEvent:n})),this.config.mediaProtection&&this.modules.set("media",new VM({...this.config.mediaProtection,onEvent:n})),this.config.mediaStreamProtection&&this.modules.set("mediaStream",new KM({...this.config.mediaStreamProtection,onEvent:n})),this.config.tamperDetection&&this.modules.set("tamper",new YM({...this.config.tamperDetection,onEvent:n}))}async activate(){let n=this.modules.get("browser");n&&await n.activate();let e=this.modules.get("devtools");e&&await e.activate();for(let[t,i]of this.modules)t==="browser"||t==="devtools"||await i.activate()}deactivate(){for(let n of this.modules.values())n.deactivate()}getModule(n){return this.modules.get(n)}get copyProtection(){return this.modules.get("copy")}get textObfuscation(){return this.modules.get("obfuscation")}get watermarking(){return this.modules.get("watermark")}get contentExpiration(){return this.modules.get("expiration")}get antiAutomation(){return this.modules.get("automation")}getEventLog(){return this.eventLog}clearEventLog(){this.eventLog=[]}}});var Cie={};li(Cie,{AnnotationMarker:()=>wr,BlobUrlManager:()=>Dh,CacheFetcher:()=>za,ContentFetcher:()=>Il,EpubNavigator:()=>Va,EpubParser:()=>Bh,HostType:()=>nt,HttpFetcher:()=>no,IFrameNavigator:()=>fR,Link:()=>js,ModuleAccessors:()=>Go,ModuleRegistry:()=>dl,NavigatorFeature:()=>we,ReadError:()=>vs,ReaderEvent:()=>xe,RightsKey:()=>vt,TransformingFetcher:()=>Fh,ZipContainer:()=>Xl,ZipFetcher:()=>Nh,createDeobfuscationTransform:()=>B4,default:()=>wie,deobfuscateAdobe:()=>Em,deobfuscateIdpf:()=>wm,getPageFromLocations:()=>gs,guessMediaType:()=>ro,load:()=>Eie,parseEncryptionXml:()=>N4});I();I();I();J0();Uc();I();I();var Ca=class{json(){return JSON.stringify(this)}},Yb=class extends Ca{constructor(e,t,i){super(),this.value=e,this.ref=t,this.name=i}toString(){return this.value}},qb=class extends Ca{constructor(e,t,i){super(),this.value=e,this.ref=t,this.name=i}toString(){return this.value}toJson(){return JSON.parse(this.value)}},$b=class extends Ca{constructor(e,t,i,r){super(),this.value=e,this.values=t,this.ref=i,this.name=r}toString(){return this.values[this.value]}},Qb=class extends Ca{constructor(t,i,r,s,o,a,u){super();this.countDecimals=function(t){return t%1!==0?t.toString().split(".")[1].length:1};this.value=t,this.min=i,this.max=r,this.step=s,this.suffix=o,this.ref=a,this.name=u}toString(){return this.value.toString()+this.suffix}increment(){let t=this.countDecimals(this.max);parseFloat(this.value.toFixed(t))<this.max&&(this.value=parseFloat(this.value.toFixed(t))+this.step)}decrement(){let t=this.countDecimals(this.min);parseFloat(this.value.toFixed(t))>this.min&&(this.value=parseFloat(this.value.toFixed(t))-this.step)}},Ku=class extends Ca{constructor(e,t,i,r,s){super(),this.value=i,this.onValue=e,this.offValue=t,this.ref=r,this.name=s}toString(){return this.value?this.onValue:this.offValue}switch(){this.value=!this.value}},os=class{constructor(){this.properties=[]}addIncremental(e,t,i,r,s,o,a){this.properties.push(new Qb(e,t,i,r,s,o,a))}addStringable(e,t,i){this.properties.push(new Yb(e,t,i))}addJSONable(e,t,i){this.properties.push(new qb(e,t,i))}addSwitchable(e,t,i,r,s){this.properties.push(new Ku(e,t,i,r,s))}addEnumerable(e,t,i,r){this.properties.push(new $b(e,t,i,r))}getByRef(e){let t=this.properties.filter(i=>i.ref===e);return t.length>0?t[0]:null}getByKey(e){let t=this.properties.filter(i=>i.key===e);return t.length>0?t[0]:null}};I();var me=class me{};me.FONT_SIZE_REF="fontSize",me.FONT_FAMILY_REF="fontFamily",me.FONT_OVERRIDE_REF="fontOverride",me.APPEARANCE_REF="appearance",me.SCROLL_REF="scroll",me.ADVANCED_SETTINGS_REF="advancedSettings",me.TEXT_ALIGNMENT_REF="textAlign",me.COLUMN_COUNT_REF="colCount",me.DIRECTION_REF="direction",me.WORD_SPACING_REF="wordSpacing",me.LETTER_SPACING_REF="letterSpacing",me.PAGE_MARGINS_REF="pageMargins",me.LINE_HEIGHT_REF="lineHeight",me.BODY_HYPHENS_REF="bodyHyphens",me.PARA_SPACING_REF="paraSpacing",me.PARA_INDENT_REF="paraIndent",me.TYPE_SCALE_REF="typeScale",me.BACKGROUND_COLOR_REF="backgroundColor",me.TEXT_COLOR_REF="textColor",me.FONT_SIZE_KEY="--USER__"+me.FONT_SIZE_REF,me.FONT_FAMILY_KEY="--USER__"+me.FONT_FAMILY_REF,me.FONT_OVERRIDE_KEY="--USER__"+me.FONT_OVERRIDE_REF,me.APPEARANCE_KEY="--USER__"+me.APPEARANCE_REF,me.SCROLL_KEY="--USER__"+me.SCROLL_REF,me.ADVANCED_SETTINGS_KEY="--USER__"+me.ADVANCED_SETTINGS_REF,me.TEXT_ALIGNMENT_KEY="--USER__"+me.TEXT_ALIGNMENT_REF,me.COLUMN_COUNT_KEY="--USER__"+me.COLUMN_COUNT_REF,me.DIRECTION_KEY="--USER__"+me.DIRECTION_REF,me.WORD_SPACING_KEY="--USER__"+me.WORD_SPACING_REF,me.LETTER_SPACING_KEY="--USER__"+me.LETTER_SPACING_REF,me.PAGE_MARGINS_KEY="--USER__"+me.PAGE_MARGINS_REF,me.LINE_HEIGHT_KEY="--USER__"+me.LINE_HEIGHT_REF,me.BODY_HYPHENS_KEY="--USER__"+me.BODY_HYPHENS_REF,me.PARA_SPACING_KEY="--USER__"+me.PARA_SPACING_REF,me.PARA_INDENT_KEY="--USER__"+me.PARA_INDENT_REF,me.TYPE_SCALE_KEY="--USER__"+me.TYPE_SCALE_REF,me.BACKGROUND_COLOR_KEY="--USER__"+me.BACKGROUND_COLOR_REF,me.TEXT_COLOR_KEY="--USER__"+me.TEXT_COLOR_REF,me.LINE_LENGTH_REF="lineLength",me.LINE_LENGTH_KEY="--USER__"+me.LINE_LENGTH_REF,me.FONT_WEIGHT_REF="fontWeight",me.FONT_WEIGHT_KEY="--USER__"+me.FONT_WEIGHT_REF,me.FONT_WIDTH_REF="fontWidth",me.FONT_WIDTH_KEY="--USER__"+me.FONT_WIDTH_REF,me.FONT_OPTICAL_SIZING_REF="fontOpticalSizing",me.FONT_OPTICAL_SIZING_KEY="--USER__"+me.FONT_OPTICAL_SIZING_REF,me.LIGATURES_REF="ligatures",me.LIGATURES_KEY="--USER__"+me.LIGATURES_REF,me.BLEND_IMAGES_REF="blendImages",me.BLEND_IMAGES_KEY="--USER__"+me.BLEND_IMAGES_REF,me.DARKEN_IMAGES_REF="darkenImages",me.DARKEN_IMAGES_KEY="--USER__"+me.DARKEN_IMAGES_REF,me.INVERT_IMAGES_REF="invertImages",me.INVERT_IMAGES_KEY="--USER__"+me.INVERT_IMAGES_REF,me.INVERT_GAIJI_REF="invertGaiji",me.INVERT_GAIJI_KEY="--USER__"+me.INVERT_GAIJI_REF,me.LINK_COLOR_REF="linkColor",me.LINK_COLOR_KEY="--USER__"+me.LINK_COLOR_REF,me.VISITED_COLOR_REF="visitedColor",me.VISITED_COLOR_KEY="--USER__"+me.VISITED_COLOR_REF,me.SELECTION_BACKGROUND_COLOR_REF="selectionBackgroundColor",me.SELECTION_BACKGROUND_COLOR_KEY="--USER__"+me.SELECTION_BACKGROUND_COLOR_REF,me.SELECTION_TEXT_COLOR_REF="selectionTextColor",me.SELECTION_TEXT_COLOR_KEY="--USER__"+me.SELECTION_TEXT_COLOR_REF,me.SCROLL_PADDING_TOP_KEY="--RS__scrollPaddingTop",me.SCROLL_PADDING_BOTTOM_KEY="--RS__scrollPaddingBottom",me.SCROLL_PADDING_LEFT_KEY="--RS__scrollPaddingLeft",me.SCROLL_PADDING_RIGHT_KEY="--RS__scrollPaddingRight",me.FONT_SIZE_NORMALIZE_KEY="--USER__fontSizeNormalize";var H=me;function bS(n){return n>=1800?"4":n>=1200?"3":n>=600?"2":"1"}function yS(n){let e=Math.max(.5,Math.min(4,n));return Math.max(0,Math.min(100,100-(e-.5)*20))+"%"}var vS={"readium-default-on":{background:"#ffffff",text:"#121212",link:"#0000ee",visited:"#551a8b",selectionBackground:"#b4d8fe",selectionText:"inherit"},"readium-sepia-on":{background:"#faf4e8",text:"#121212",link:"#0000ee",visited:"#551a8b",selectionBackground:"#b4d8fe",selectionText:"inherit"},"readium-night-on":{background:"#000000",text:"#fefefe",link:"#63caff",visited:"#0099e5",selectionBackground:"#b4d8fe",selectionText:"inherit"}},AS={"readium-default-on":{blendImages:!1,invertImages:!1,darkenImages:!1},"readium-sepia-on":{blendImages:!0,invertImages:!1,darkenImages:!1},"readium-night-on":{blendImages:!1,invertImages:!1,darkenImages:!1}};ci();I();ci();function Z0(){return dt(document,"#iframe-wrapper").clientWidth}function Yu(){return dt(document,"#iframe-wrapper").clientHeight}function qu(n,e){let t=n?.parentElement?.clientHeight??Yu(),i=e?.safeArea?.bottom?.()?.getBoundingClientRect().height??0,r=n?window.getComputedStyle(n):null,s=(parseFloat(r?.paddingTop??"0")||0)+(parseFloat(r?.paddingBottom??"0")||0),o=e?.margin??0;return t-i-s-o}function wS(){let n=navigator.userAgent;return!!(/iPad/.test(n)||/Macintosh/.test(n)&&typeof navigator.maxTouchPoints=="number"&&navigator.maxTouchPoints>1)}mn();I();ci();var x_=$e($s()),md=class{constructor(e){this.layout="reflowable";this.USERSETTINGS="userSetting";this.sideMargin=20;this.height=0;this.attributes={};this.hasFixedScrollWidth=!1;this.store=e,this.scrollMode?(this.name="readium-scroll-on",this.label="Scrolling"):(this.name="readium-scroll-off",this.label="Paginated")}setMode(e){if(this.scrollMode=e,e){this.name="readium-scroll-on",this.label="Scrolling";let t=this.iframe.contentDocument;if(t){let i=Ni(t,"head");if(i){let o=fe(i,"meta[name=viewport]");o&&o.remove()}let r=Ni(t,"html");r&&r.style.setProperty("--USER__scroll","readium-scroll-on");let s=t.getElementById("r2d2bc-column-spacer");s&&s.remove()}this.setSize(),this.setIframeHeight(this.iframe)}else{this.height=qu(this.iframe,this.attributes),this.name="readium-scroll-off",this.label="Paginated",this.checkForFixedScrollWidth();let t=this.iframe.contentDocument;if(t){let i=Ni(t,"html");i&&i.style.setProperty("--USER__scroll","readium-scroll-off")}this.setSize(),this.padOddColumns()}this.host.isContentProtectionEnabled()&&this.host.recalculateContentProtection()}start(){if(this.scrollMode){let e=this.iframe.contentDocument;if(e){let t=Ni(e,"head");if(t){let i=fe(t,"meta[name=viewport]");i&&i.remove()}}this.setSize(),this.setIframeHeight(this.iframe)}else{this.iframe.height="0",this.iframe.width="0",this.setSize();let e=document.createElement("meta");e.name="viewport",e.content="width=device-width, initial-scale=1, maximum-scale=1",this.checkForFixedScrollWidth()}}stop(){if(this.iframe.height="0",this.iframe.width="0",this.iframe.contentDocument){let t=Ni(this.iframe.contentDocument,"body"),i=Array.prototype.slice.call(t.querySelectorAll("img"));for(let r of i)r.style.maxWidth=""}}getCurrentPosition(){let e=dt(document,"#iframe-wrapper");if(this.scrollMode)return e.scrollTop/this.scrollingElement.scrollHeight;{let t=this.getColumnWidth(),i=this.getLeftColumnsWidth(),r=this.getRightColumnsWidth(),s=i+t+r;return i/s}}goToProgression(e){let t=dt(document,"#iframe-wrapper");if(this.scrollMode)t.scrollTop=this.scrollingElement.scrollHeight*e;else{let i=this.getColumnWidth(),r=this.getLeftColumnsWidth(),s=this.getRightColumnsWidth(),o=r+i+s,a=e*o,u=Math.round(a/i)*i;u>=o&&(u=u-i),this.setLeftColumnsWidth(u)}}goToCssSelector(e,t){let i=this.iframe.contentDocument;if(i){let r=i.querySelector(e);this.goToElement(r,t)}}goToFragment(e,t){let i=this.iframe.contentDocument;if(i){let r=i.getElementById(e);this.goToElement(r,t)}}snap(e,t){if(e&&!this.scrollMode){let i=e.style.height;e.style.height="0";let r=this.getColumnWidth(),s=this.getLeftColumnsWidth()+e.getBoundingClientRect().left,o=Math.floor(s/r)*r;e.style.height=i,this.setLeftColumnsWidth(o),this.host.isContentProtectionEnabled()&&this.host.recalculateContentProtection(0)}}goToElement(e,t){if(this.scrollMode)e&&e.scrollIntoView({block:"center"});else if(e){let i=e.style.height;e.style.height="0";let r=e.getBoundingClientRect().left,s=this.getColumnWidth(),o=this.scrollingElement.scrollLeft-s,a=Math.ceil(r/s)*s+o;if(t){let u=this.getLeftColumnsWidth();a=Math.ceil(r/s)*s+u}e.style.height=i,this.setLeftColumnsWidth(a),this.host.isContentProtectionEnabled()&&this.host.recalculateContentProtection(200)}}atStart(){return this.scrollMode?dt(document,"#iframe-wrapper").scrollTop===0:this.getLeftColumnsWidth()<=0}atEnd(){if(this.scrollMode){let e=dt(document,"#iframe-wrapper");return Math.ceil(this.scrollingElement.scrollHeight-e.scrollTop)-1<=Yu()}else{let e=Math.floor(this.getRightColumnsWidth());return e<=0?!0:this.iframe.contentDocument?.getElementById("r2d2bc-column-spacer")?e<=5:Math.round(this.getCurrentPage())>=this.getPageCount()}}goToPreviousPage(){let e=dt(document,"#iframe-wrapper");if(this.scrollMode){let t=e.scrollTop,i=this.getScreenHeight()-40,r=t-i;r>=0?e.scrollTop=r:e.scrollTop=0}else{let t=this.getLeftColumnsWidth(),i=this.getColumnWidth(),r=t-i;r>=0?this.setLeftColumnsWidth(r):this.setLeftColumnsWidth(0),this.host.checkResourcePosition()}this.host.isContentProtectionEnabled()&&this.host.recalculateContentProtection()}goToNextPage(){let e=dt(document,"#iframe-wrapper");if(this.scrollMode){let t=e.scrollTop,i=this.getScreenHeight()-40,r=this.scrollingElement.scrollHeight,s=t+i;s<r?e.scrollTop=s:e.scrollTop=r}else{let t=this.getLeftColumnsWidth(),i=this.getColumnWidth(),r=this.scrollWidth,s=t+i;s<r?this.setLeftColumnsWidth(s):this.setLeftColumnsWidth(r),this.host.checkResourcePosition()}this.host.isContentProtectionEnabled()&&this.host.recalculateContentProtection()}getCurrentPage(){return this.scrollMode?0:this.getCurrentPosition()*this.getPageCount()+1}getPageCount(){if(this.scrollMode)return 0;{let e=this.getColumnWidth();return this.scrollWidth/e}}isPaginated(){if(this.iframe){let e=this.iframe.contentDocument;if(e){let t=Ni(e,"html");if(t)return!(t.style.getPropertyValue("--USER__scroll")==="readium-scroll-on")}}return!this.scrollMode}isScrollMode(){if(this.iframe){let e=this.iframe.contentDocument;if(e){let t=Ni(e,"html");if(t)return t.style.getPropertyValue("--USER__scroll")==="readium-scroll-on"}}return this.scrollMode}async getProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let i=JSON.parse(t);return i=i.filter(r=>r.name===e),i.length===0?null:i[0]}return null}getScreenHeight(){return dt(document,"#iframe-wrapper").clientHeight}setIframeHeight(e){(0,x_.default)(i=>{if(i){let r=i.contentWindow.document.body,s=i.contentWindow.document.documentElement,o=Math.max(r?.scrollHeight,r?.offsetHeight,s?.clientHeight,s?.scrollHeight,s?.offsetHeight);if(o){let a=qu(i,this.attributes);i.height=Math.max(a,o)+"px"}}},200)(e)}checkForFixedScrollWidth(){let e=this.iframe.contentDocument;if(e){let t=Ni(e,"body"),i=t?.scrollWidth;this.hasFixedScrollWidth=t?.scrollWidth===i}}setSize(){if(this.iframe.width=Z0()+"px",this.scrollMode){let e=this.iframe.contentWindow?.document?.documentElement;this.iframe.height=e?.offsetHeight+"px"}else{let e=this.iframe.contentDocument;e&&e.documentElement&&(e.documentElement.style.height=this.height+"px"),this.iframe.height=this.height+"px"}}getLeftColumnsWidth(){return Math.round(this.scrollingElement.scrollLeft)}getRightColumnsWidth(){let e=this.getColumnWidth(),t=this.scrollWidth-e;if(this.hasFixedScrollWidth){let i=this.getLeftColumnsWidth();t=Math.max(0,t-i)}return t}getColumnWidth(){return this.scrollingElement.clientWidth}setLeftColumnsWidth(e){this.scrollingElement.scrollLeft=e}get scrollingElement(){return this.iframe.contentDocument?.scrollingElement?this.iframe.contentDocument?.scrollingElement:this.iframe.contentDocument?.body?this.iframe.contentDocument?.body:document.createElement("body")}get scrollWidth(){let e=this.scrollingElement?.scrollWidth,t=this.getColumnWidth(),i=Math.ceil((e-1)/t);return Math.max(1,i)*t}padOddColumns(){if(this.scrollMode)return!1;let e=this.iframe.contentDocument;if(!e||e.getElementById("r2d2bc-column-spacer"))return!1;let i=e.body;if(!i)return!1;let r=i.scrollWidth,s=this.getColumnWidth(),o=r%s,a=i.getBoundingClientRect().left,u=i.lastElementChild;if(u){let l=u.getBoundingClientRect().right-a;if(r-l>s*.5)return!1}if(o>s*.25){let l=e.createElement("div");return l.id="r2d2bc-column-spacer",l.style.breakBefore="column",l.style.height="100%",l.style.visibility="hidden",i.appendChild(l),i.scrollWidth,!0}return!1}};I();ci();var bd=class{constructor(){this.layout="fixed";this.sideMargin=20;this.height=0;this.attributes={}}start(){}stop(){}getCurrentPosition(){return 0}getScreenHeight(){return dt(document,"#iframe-wrapper").clientHeight}goToProgression(e){}goToCssSelector(e,t){}goToFragment(e,t){}snap(e,t){}getCurrentPage(){return 0}getPageCount(){return 1}setSize(){}isPaginated(){return!0}isScrollMode(){return!1}atEnd(){return!0}atStart(){return!0}};var Nn=$e(jt()),it=class it{constructor(e,t,i,r,s){this.USERSETTINGS="userSetting";this.fontSize=100;this.fontOverride=!1;this.fontFamily=0;this.appearance=0;this.verticalScroll=!0;this.textAlignment=0;this.columnCount=0;this.direction=0;this.wordSpacing=0;this.letterSpacing=0;this.pageMargins=2;this.lineHeight=1;this.bodyHyphens=!1;this.paraSpacing=0;this.paraIndent=1;this.typeScale=1.2;this.backgroundColor="";this.textColor="";this.lineLength="";this.fontWeight=400;this.fontWidth=100;this.fontOpticalSizing=!0;this.ligatures="common-ligatures";this.blendImages=!1;this.darkenImages=!1;this.invertImages=!1;this.invertGaiji=!1;this.linkColor="";this.visitedColor="";this.selectionBackgroundColor="";this.selectionTextColor="";this.scrollPaddingTop="";this.scrollPaddingBottom="";this.scrollPaddingLeft="";this.scrollPaddingRight="";this.settingsChangeCallback=()=>{};this.settingsColumnsChangeCallback=()=>{};this.viewChangeCallback=()=>{};this.resizeTimer=null;this.onWindowResize=()=>{this.userProperties?.getByRef(H.COLUMN_COUNT_REF)?.toString()==="auto"&&(this.resizeTimer!==null&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout(()=>{this.resizeTimer=null,this.applyProperties()},150))};this.store=e,this.view=s==="fixed"?new bd:new md(this.store),this.headerMenu=t,this.api=i,this.injectables=r,this.injectables?.forEach(o=>{o.type==="style"&&(o.fontFamily&&this.addFont(o.fontFamily),o.appearance&&this.addAppearance(o.appearance))})}async isPaginated(){return!await this.getPropertyAndFallback("verticalScroll",H.SCROLL_KEY)}async isScrollMode(){return!await this.isPaginated()}static async create(e){let t=new this(e.store,e.headerMenu,e.api,e.injectables,e.layout);if(await t.initialise(),e.initialUserSettings){t.userProperties||(t.userProperties=t.getUserSettings());let i=e.initialUserSettings;if(i.verticalScroll!==void 0){t.verticalScroll=this.parseScrollSetting(i.verticalScroll);let r=t.userProperties.getByRef(H.SCROLL_REF);r&&(r.value=t.verticalScroll,await t.saveProperty(r)),Nn.default.log(t.verticalScroll)}if(i.appearance){t.appearance=it.parseAppearanceSetting(i.appearance);let r=t.userProperties.getByRef(H.APPEARANCE_REF);r&&(r.value=t.appearance,await t.saveProperty(r)),Nn.default.log(t.appearance)}if(i.fontSize){t.fontSize=i.fontSize;let r=t.userProperties.getByRef(H.FONT_SIZE_REF);r&&(r.value=t.fontSize,await t.saveProperty(r)),Nn.default.log(t.fontSize)}if(i.fontFamily){t.fontFamily=it.fontFamilyValues.findIndex(s=>s===i.fontFamily);let r=t.userProperties.getByRef(H.FONT_FAMILY_REF);r&&(r.value=t.fontFamily,await t.saveProperty(r)),Nn.default.log(t.fontFamily),t.fontFamily!==0&&(t.fontOverride=!0)}if(i.textAlignment){t.textAlignment=it.textAlignmentValues.findIndex(s=>s===i.textAlignment);let r=t.userProperties.getByRef(H.TEXT_ALIGNMENT_REF);r&&(r.value=t.textAlignment,await t.saveProperty(r)),Nn.default.log(t.textAlignment)}if(i.columnCount){t.columnCount=it.columnCountValues.findIndex(s=>s===i.columnCount);let r=t.userProperties.getByRef(H.COLUMN_COUNT_REF);r&&(r.value=t.columnCount,await t.saveProperty(r)),Nn.default.log(t.columnCount)}if(i.direction){t.direction=it.directionValues.findIndex(s=>s===i.direction);let r=t.userProperties.getByRef(H.DIRECTION_REF);r&&(r.value=t.direction,await t.saveProperty(r)),Nn.default.log(t.direction)}if(i.wordSpacing){t.wordSpacing=i.wordSpacing;let r=t.userProperties.getByRef(H.WORD_SPACING_REF);r&&(r.value=t.wordSpacing,await t.saveProperty(r)),Nn.default.log(t.wordSpacing)}if(i.letterSpacing){t.letterSpacing=i.letterSpacing;let r=t.userProperties.getByRef(H.LETTER_SPACING_REF);r&&(r.value=t.letterSpacing,await t.saveProperty(r)),Nn.default.log(t.letterSpacing)}if(i.pageMargins){t.pageMargins=i.pageMargins;let r=t.userProperties.getByRef(H.PAGE_MARGINS_REF);r&&(r.value=t.pageMargins,await t.saveProperty(r)),Nn.default.log(t.pageMargins)}if(i.lineHeight){t.lineHeight=i.lineHeight;let r=t.userProperties.getByRef(H.LINE_HEIGHT_REF);r&&(r.value=t.lineHeight,await t.saveProperty(r)),Nn.default.log(t.lineHeight)}if(i.bodyHyphens!==void 0){t.bodyHyphens=i.bodyHyphens;let r=t.userProperties.getByRef(H.BODY_HYPHENS_REF);r&&(r.value=t.bodyHyphens,await t.saveProperty(r))}if(i.paraSpacing!==void 0){t.paraSpacing=i.paraSpacing;let r=t.userProperties.getByRef(H.PARA_SPACING_REF);r&&(r.value=t.paraSpacing,await t.saveProperty(r))}if(i.paraIndent!==void 0){t.paraIndent=i.paraIndent;let r=t.userProperties.getByRef(H.PARA_INDENT_REF);r&&(r.value=t.paraIndent,await t.saveProperty(r))}if(i.typeScale!==void 0){t.typeScale=i.typeScale;let r=t.userProperties.getByRef(H.TYPE_SCALE_REF);r&&(r.value=t.typeScale,await t.saveProperty(r))}if(i.backgroundColor!==void 0){t.backgroundColor=i.backgroundColor;let r=t.userProperties.getByRef(H.BACKGROUND_COLOR_REF);r&&(r.value=t.backgroundColor,await t.saveProperty(r))}if(i.textColor!==void 0){t.textColor=i.textColor;let r=t.userProperties.getByRef(H.TEXT_COLOR_REF);r&&(r.value=t.textColor,await t.saveProperty(r))}if(i.lineLength!==void 0&&(t.lineLength=i.lineLength),i.fontWeight!==void 0){t.fontWeight=i.fontWeight;let r=t.userProperties.getByRef(H.FONT_WEIGHT_REF);r&&(r.value=t.fontWeight,await t.saveProperty(r))}if(i.fontWidth!==void 0){t.fontWidth=i.fontWidth;let r=t.userProperties.getByRef(H.FONT_WIDTH_REF);r&&(r.value=t.fontWidth,await t.saveProperty(r))}i.fontOpticalSizing!==void 0&&(t.fontOpticalSizing=i.fontOpticalSizing),i.ligatures!==void 0&&(t.ligatures=i.ligatures),i.blendImages!==void 0&&(t.blendImages=i.blendImages),i.darkenImages!==void 0&&(t.darkenImages=i.darkenImages),i.invertImages!==void 0&&(t.invertImages=i.invertImages),i.invertGaiji!==void 0&&(t.invertGaiji=i.invertGaiji),i.linkColor!==void 0&&(t.linkColor=i.linkColor),i.visitedColor!==void 0&&(t.visitedColor=i.visitedColor),i.selectionBackgroundColor!==void 0&&(t.selectionBackgroundColor=i.selectionBackgroundColor),i.selectionTextColor!==void 0&&(t.selectionTextColor=i.selectionTextColor),i.scrollPaddingTop!==void 0&&(t.scrollPaddingTop=i.scrollPaddingTop),i.scrollPaddingBottom!==void 0&&(t.scrollPaddingBottom=i.scrollPaddingBottom),i.scrollPaddingLeft!==void 0&&(t.scrollPaddingLeft=i.scrollPaddingLeft),i.scrollPaddingRight!==void 0&&(t.scrollPaddingRight=i.scrollPaddingRight),t.userProperties=t.getUserSettings(),await t.initialise()}return await t.initializeSelections(),new Promise(i=>i(t))}stop(){Nn.default.log("book settings stop"),window.removeEventListener("resize",this.onWindowResize),this.resizeTimer!==null&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null)}async initialise(){this.appearance=await this.getPropertyAndFallback("appearance",H.APPEARANCE_KEY),this.verticalScroll=await this.getPropertyAndFallback("verticalScroll",H.SCROLL_KEY),this.fontFamily=await this.getPropertyAndFallback("fontFamily",H.FONT_FAMILY_KEY),this.fontFamily!==0&&(this.fontOverride=!0),this.textAlignment=await this.getPropertyAndFallback("textAlignment",H.TEXT_ALIGNMENT_KEY),this.columnCount=await this.getPropertyAndFallback("columnCount",H.COLUMN_COUNT_KEY),this.direction=await this.getPropertyAndFallback("direction",H.DIRECTION_KEY),this.fontSize=await this.getPropertyAndFallback("fontSize",H.FONT_SIZE_KEY),this.wordSpacing=await this.getPropertyAndFallback("wordSpacing",H.WORD_SPACING_KEY),this.letterSpacing=await this.getPropertyAndFallback("letterSpacing",H.LETTER_SPACING_KEY),this.pageMargins=await this.getPropertyAndFallback("pageMargins",H.PAGE_MARGINS_KEY),this.lineHeight=await this.getPropertyAndFallback("lineHeight",H.LINE_HEIGHT_KEY),this.bodyHyphens=await this.getPropertyAndFallback("bodyHyphens",H.BODY_HYPHENS_KEY),this.paraSpacing=await this.getPropertyAndFallback("paraSpacing",H.PARA_SPACING_KEY),this.paraIndent=await this.getPropertyAndFallback("paraIndent",H.PARA_INDENT_KEY),this.typeScale=await this.getPropertyAndFallback("typeScale",H.TYPE_SCALE_KEY),this.backgroundColor=await this.getPropertyAndFallback("backgroundColor",H.BACKGROUND_COLOR_KEY),this.textColor=await this.getPropertyAndFallback("textColor",H.TEXT_COLOR_KEY),window.addEventListener("resize",this.onWindowResize),this.userProperties=this.getUserSettings()}async reset(){this.appearance=0,this.verticalScroll=!0,this.fontSize=100,this.fontOverride=!1,this.fontFamily=0,this.textAlignment=0,this.columnCount=0,this.direction=0,this.wordSpacing=0,this.letterSpacing=0,this.pageMargins=2,this.lineHeight=1,this.bodyHyphens=!1,this.paraSpacing=0,this.paraIndent=1,this.typeScale=1.2,this.backgroundColor="",this.textColor="",this.userProperties=this.getUserSettings();let e=this.iframe.contentDocument;if(e){let t=Ni(e,"html");if(t){let i=fe(document,"#root")||document.documentElement,r=fe(t,"body");t.style.removeProperty(H.FONT_SIZE_KEY),t.style.removeProperty(H.WORD_SPACING_KEY),t.style.removeProperty(H.LETTER_SPACING_KEY),t.style.removeProperty(H.COLUMN_COUNT_KEY),t.style.removeProperty(H.DIRECTION_KEY),t.style.removeProperty(H.TEXT_ALIGNMENT_KEY),t.style.removeProperty(H.LINE_HEIGHT_KEY),t.style.removeProperty(H.PAGE_MARGINS_KEY),t.style.removeProperty(H.BODY_HYPHENS_KEY),t.style.removeProperty(H.PARA_SPACING_KEY),t.style.removeProperty(H.PARA_INDENT_KEY),t.style.removeProperty(H.TYPE_SCALE_KEY),t.style.removeProperty(H.BACKGROUND_COLOR_KEY),t.style.removeProperty(H.TEXT_COLOR_KEY),t.style.removeProperty(H.APPEARANCE_KEY),i&&Br(i,"data-viewer-theme","day"),r&&Br(r,"data-viewer-theme","day"),t.style.removeProperty(H.FONT_FAMILY_KEY),Br(t,"data-viewer-font","publisher"),t.style.setProperty(H.FONT_OVERRIDE_KEY,"readium-font-off")}}}async initializeSelections(){this.headerMenu&&(this.settingsView=fe(this.headerMenu,"#container-view-settings"))}async applyProperties(){this.userProperties=this.getUserSettings();let e=this.iframe.contentDocument;if(e){let t=Ni(e,"html");if(t){wS()?t.style.setProperty("--readium-iPadOSPatch-on","1"):t.style.removeProperty("--readium-iPadOSPatch-on");let i=fe(document,"#root")||document.documentElement,r=fe(t,"body");this.view?.host?.isReflowable()&&(await this.getProperty(H.FONT_SIZE_KEY)&&t.style.setProperty(H.FONT_SIZE_KEY,this.userProperties.getByRef(H.FONT_SIZE_REF)?.toString()??null),await this.getProperty(H.WORD_SPACING_KEY)&&t.style.setProperty(H.WORD_SPACING_KEY,this.userProperties.getByRef(H.WORD_SPACING_REF)?.toString()??null),await this.getProperty(H.LETTER_SPACING_KEY)&&t.style.setProperty(H.LETTER_SPACING_KEY,this.userProperties.getByRef(H.LETTER_SPACING_REF)?.toString()??null));{let s=this.userProperties.getByRef(H.COLUMN_COUNT_REF)?.toString()??"auto",o=s==="auto"?bS(Z0()):s;t.style.setProperty(H.COLUMN_COUNT_KEY,o)}if(this.view?.host?.isReflowable()){await this.getProperty(H.TEXT_ALIGNMENT_KEY)&&(this.userProperties.getByRef(H.TEXT_ALIGNMENT_REF)?.toString()==="auto"?t.style.removeProperty(H.TEXT_ALIGNMENT_KEY):t.style.setProperty(H.TEXT_ALIGNMENT_KEY,this.userProperties.getByRef(H.TEXT_ALIGNMENT_REF)?.toString()??null)),await this.getProperty(H.LINE_HEIGHT_KEY)&&t.style.setProperty(H.LINE_HEIGHT_KEY,this.userProperties.getByRef(H.LINE_HEIGHT_REF)?.toString()??null);{let s=this.userProperties.getByRef(H.PAGE_MARGINS_REF)?.toString()??null;if(t.style.setProperty(H.PAGE_MARGINS_KEY,s),this.lineLength)t.style.setProperty(H.LINE_LENGTH_KEY,this.lineLength);else{let o=this.userProperties.getByRef(H.PAGE_MARGINS_REF),a=typeof o?.value=="number"?o.value:this.pageMargins;t.style.setProperty(H.LINE_LENGTH_KEY,yS(a))}}await this.getProperty(H.BODY_HYPHENS_KEY)&&t.style.setProperty(H.BODY_HYPHENS_KEY,this.userProperties.getByRef(H.BODY_HYPHENS_REF)?.toString()??null),await this.getProperty(H.PARA_SPACING_KEY)&&t.style.setProperty(H.PARA_SPACING_KEY,this.userProperties.getByRef(H.PARA_SPACING_REF)?.toString()??null),await this.getProperty(H.PARA_INDENT_KEY)&&t.style.setProperty(H.PARA_INDENT_KEY,this.userProperties.getByRef(H.PARA_INDENT_REF)?.toString()??null),await this.getProperty(H.TYPE_SCALE_KEY)&&t.style.setProperty(H.TYPE_SCALE_KEY,this.userProperties.getByRef(H.TYPE_SCALE_REF)?.toString()??null),await this.getProperty(H.BACKGROUND_COLOR_KEY)&&t.style.setProperty(H.BACKGROUND_COLOR_KEY,this.userProperties.getByRef(H.BACKGROUND_COLOR_REF)?.toString()??null),await this.getProperty(H.TEXT_COLOR_KEY)&&t.style.setProperty(H.TEXT_COLOR_KEY,this.userProperties.getByRef(H.TEXT_COLOR_REF)?.toString()??null)}{let s=this.userProperties.getByRef(H.APPEARANCE_REF)?.toString()??"readium-default-on";t.style.setProperty(H.APPEARANCE_KEY,s);let o=vS[s],a=AS[s],u=s==="readium-default-on";o&&!u?(this.backgroundColor||t.style.setProperty(H.BACKGROUND_COLOR_KEY,o.background),this.textColor||t.style.setProperty(H.TEXT_COLOR_KEY,o.text),this.linkColor||t.style.setProperty(H.LINK_COLOR_KEY,o.link),this.visitedColor||t.style.setProperty(H.VISITED_COLOR_KEY,o.visited),this.selectionBackgroundColor||t.style.setProperty(H.SELECTION_BACKGROUND_COLOR_KEY,o.selectionBackground),this.selectionTextColor||t.style.setProperty(H.SELECTION_TEXT_COLOR_KEY,o.selectionText)):u&&(this.backgroundColor||t.style.removeProperty(H.BACKGROUND_COLOR_KEY),this.textColor||t.style.removeProperty(H.TEXT_COLOR_KEY),this.linkColor||t.style.removeProperty(H.LINK_COLOR_KEY),this.visitedColor||t.style.removeProperty(H.VISITED_COLOR_KEY),this.selectionBackgroundColor||t.style.removeProperty(H.SELECTION_BACKGROUND_COLOR_KEY),this.selectionTextColor||t.style.removeProperty(H.SELECTION_TEXT_COLOR_KEY)),a&&(this.blendImages=a.blendImages,this.invertImages=a.invertImages,this.darkenImages=a.darkenImages);let l=this.userProperties.getByRef(H.APPEARANCE_REF)?.value??0,c=l===1?"sepia":l===2?"night":"day";i&&Br(i,"data-viewer-theme",c),r&&Br(r,"data-viewer-theme",c)}if(this.view?.host?.isFixedLayout()&&await this.getProperty(H.DIRECTION_KEY)){let s=this.userProperties.getByRef(H.DIRECTION_REF)?.toString()??null;t.style.setProperty(H.DIRECTION_KEY,s),this.view.host?.setDirection(s)}if(this.view?.host?.isReflowable()){if(await this.getProperty(H.FONT_FAMILY_KEY))if(this.userProperties.getByRef(H.FONT_FAMILY_REF)?.value===0?t.style.removeProperty(H.FONT_FAMILY_KEY):t.style.setProperty(H.FONT_FAMILY_KEY,this.userProperties.getByRef(H.FONT_FAMILY_REF)?.toString()??null),this.userProperties.getByRef(H.FONT_FAMILY_REF)?.value===0)Br(t,"data-viewer-font","publisher"),t.style.setProperty(H.FONT_OVERRIDE_KEY,"readium-font-off");else if(this.userProperties.getByRef(H.FONT_FAMILY_REF)?.value===1)Br(t,"data-viewer-font","serif"),t.style.setProperty(H.FONT_OVERRIDE_KEY,"readium-font-on");else if(this.userProperties.getByRef(H.FONT_FAMILY_REF)?.value===2)Br(t,"data-viewer-font","sans"),t.style.setProperty(H.FONT_OVERRIDE_KEY,"readium-font-on");else{let o=this.userProperties.getByRef(H.FONT_FAMILY_REF);o&&Br(t,"data-viewer-font",o.toString()),t.style.setProperty(H.FONT_OVERRIDE_KEY,"readium-font-on")}else t.style.removeProperty(H.FONT_FAMILY_KEY),Br(t,"data-viewer-font","publisher"),t.style.setProperty(H.FONT_OVERRIDE_KEY,"readium-font-off");this.lineLength&&t.style.setProperty(H.LINE_LENGTH_KEY,this.lineLength),this.fontWeight&&this.fontWeight!==400&&t.style.setProperty(H.FONT_WEIGHT_KEY,String(this.fontWeight)),this.fontWidth&&this.fontWidth!==100&&t.style.setProperty(H.FONT_WIDTH_KEY,String(this.fontWidth)),t.style.setProperty(H.FONT_OPTICAL_SIZING_KEY,this.fontOpticalSizing?"auto":"none"),t.style.setProperty(H.LIGATURES_KEY,this.ligatures),this.blendImages?t.style.setProperty(H.BLEND_IMAGES_KEY,"readium-blend-on"):t.style.removeProperty(H.BLEND_IMAGES_KEY),fv(t,H.DARKEN_IMAGES_KEY,this.darkenImages,"readium-darken-on"),fv(t,H.INVERT_IMAGES_KEY,this.invertImages,"readium-invert-on"),fv(t,H.INVERT_GAIJI_KEY,this.invertGaiji,"readium-invertGaiji-on"),this.linkColor&&t.style.setProperty(H.LINK_COLOR_KEY,this.linkColor),this.visitedColor&&t.style.setProperty(H.VISITED_COLOR_KEY,this.visitedColor),this.selectionBackgroundColor&&t.style.setProperty(H.SELECTION_BACKGROUND_COLOR_KEY,this.selectionBackgroundColor),this.selectionTextColor&&t.style.setProperty(H.SELECTION_TEXT_COLOR_KEY,this.selectionTextColor),this.scrollPaddingTop&&t.style.setProperty(H.SCROLL_PADDING_TOP_KEY,this.scrollPaddingTop),this.scrollPaddingBottom&&t.style.setProperty(H.SCROLL_PADDING_BOTTOM_KEY,this.scrollPaddingBottom),this.scrollPaddingLeft&&t.style.setProperty(H.SCROLL_PADDING_LEFT_KEY,this.scrollPaddingLeft),this.scrollPaddingRight&&t.style.setProperty(H.SCROLL_PADDING_RIGHT_KEY,this.scrollPaddingRight),await this.getProperty(H.SCROLL_KEY)?this.userProperties.getByRef(H.SCROLL_REF)?.value===!0?t.style.setProperty("--USER__scroll","readium-scroll-on"):t.style.setProperty("--USER__scroll","readium-scroll-off"):t.style.setProperty("--USER__scroll","readium-scroll-on"),t.style.setProperty("--USER__advancedSettings","readium-advanced-on"),this.isScrollMode().then(s=>{this.view?.setMode?.(s)})}}}}setIframe(e){this.iframe=e,this.view&&(this.view.iframe=e),this.settingsView&&it.renderControls(this.settingsView)}static renderControls(e){ee(fe(e,"ul"),"click",t=>{t.stopPropagation()})}onSettingsChange(e){this.settingsChangeCallback=e}onColumnSettingsChange(e){this.settingsColumnsChangeCallback=e}onViewChange(e){this.viewChangeCallback=e}async storeProperty(e){await this.updateUserSettings(),await this.saveProperty(e)}addAppearance(e){it.appearanceValues.includes(e)||it.appearanceValues.push(e)}initAddedAppearance(){this.applyProperties()}addFont(e){it.fontFamilyValues.includes(e)||it.fontFamilyValues.push(e)}initAddedFont(){this.applyProperties()}async updateUserSettings(){let e={fontFamily:it.fontFamilyValues[await this.userProperties?.getByRef(H.FONT_FAMILY_REF)?.value],fontSize:this.userProperties?.getByRef(H.FONT_SIZE_REF)?.value,appearance:it.appearanceValues[await this.userProperties?.getByRef(H.APPEARANCE_REF)?.value],textAlignment:it.textAlignmentValues[await this.userProperties?.getByRef(H.TEXT_ALIGNMENT_REF)?.value],columnCount:it.columnCountValues[await this.userProperties?.getByRef(H.COLUMN_COUNT_REF)?.value],direction:it.directionValues[await this.userProperties?.getByRef(H.DIRECTION_REF)?.value],wordSpacing:this.userProperties?.getByRef(H.WORD_SPACING_REF)?.value,letterSpacing:this.userProperties?.getByRef(H.LETTER_SPACING_REF)?.value,verticalScroll:this.userProperties?.getByRef(H.SCROLL_REF)?.value,bodyHyphens:this.userProperties?.getByRef(H.BODY_HYPHENS_REF)?.value,paraSpacing:this.userProperties?.getByRef(H.PARA_SPACING_REF)?.value,paraIndent:this.userProperties?.getByRef(H.PARA_INDENT_REF)?.value,typeScale:this.userProperties?.getByRef(H.TYPE_SCALE_REF)?.value,backgroundColor:this.userProperties?.getByRef(H.BACKGROUND_COLOR_REF)?.value,textColor:this.userProperties?.getByRef(H.TEXT_COLOR_REF)?.value};this.api?.updateSettings&&this.api?.updateSettings(e).then(t=>{Nn.default.log("api updated user settings",JSON.stringify(e))})}getUserSettings(){let e=new os;return e.addSwitchable("readium-font-on","readium-font-off",this.fontOverride,H.FONT_OVERRIDE_REF,H.FONT_OVERRIDE_KEY),e.addEnumerable(this.columnCount,it.columnCountValues,H.COLUMN_COUNT_REF,H.COLUMN_COUNT_KEY),e.addEnumerable(this.direction,it.directionValues,H.DIRECTION_REF,H.DIRECTION_KEY),e.addEnumerable(this.appearance,it.appearanceValues,H.APPEARANCE_REF,H.APPEARANCE_KEY),e.addIncremental(this.pageMargins,.5,4,.25,"",H.PAGE_MARGINS_REF,H.PAGE_MARGINS_KEY),e.addEnumerable(this.textAlignment,it.textAlignmentValues,H.TEXT_ALIGNMENT_REF,H.TEXT_ALIGNMENT_KEY),e.addEnumerable(this.fontFamily,it.fontFamilyValues,H.FONT_FAMILY_REF,H.FONT_FAMILY_KEY),e.addIncremental(this.fontSize,100,300,25,"%",H.FONT_SIZE_REF,H.FONT_SIZE_KEY),e.addIncremental(this.lineHeight,1,2,.25,"em",H.LINE_HEIGHT_REF,H.LINE_HEIGHT_KEY),e.addIncremental(this.wordSpacing,0,1,.25,"rem",H.WORD_SPACING_REF,H.WORD_SPACING_KEY),e.addIncremental(this.letterSpacing,0,.5,.0625,"em",H.LETTER_SPACING_REF,H.LETTER_SPACING_KEY),e.addSwitchable("readium-scroll-on","readium-scroll-off",this.verticalScroll,H.SCROLL_REF,H.SCROLL_KEY),e.addSwitchable("auto","none",this.bodyHyphens,H.BODY_HYPHENS_REF,H.BODY_HYPHENS_KEY),e.addIncremental(this.paraSpacing,0,3,.5,"rem",H.PARA_SPACING_REF,H.PARA_SPACING_KEY),e.addIncremental(this.paraIndent,0,3,.5,"em",H.PARA_INDENT_REF,H.PARA_INDENT_KEY),e.addIncremental(this.typeScale,1,1.5,.1,"",H.TYPE_SCALE_REF,H.TYPE_SCALE_KEY),e.addStringable(this.backgroundColor,H.BACKGROUND_COLOR_REF,H.BACKGROUND_COLOR_KEY),e.addStringable(this.textColor,H.TEXT_COLOR_REF,H.TEXT_COLOR_KEY),e.addIncremental(this.fontWeight,100,900,50,"",H.FONT_WEIGHT_REF,H.FONT_WEIGHT_KEY),e.addIncremental(this.fontWidth,50,200,10,"",H.FONT_WIDTH_REF,H.FONT_WIDTH_KEY),e}async saveProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.name!==e.name),e.value!==void 0&&i.push(e),await this.store.set(this.USERSETTINGS,JSON.stringify(i))}else{let i=[];i.push(e),await this.store.set(this.USERSETTINGS,JSON.stringify(i))}return new Promise(i=>i(e))}async getProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let i=JSON.parse(t);return i=i.filter(r=>r.name===e),i.length===0?null:i[0]}return null}async getPropertyAndFallback(e,t){return(await this.getProperty(t))?.value??this[e]}async resetUserSettings(){this.store.remove(this.USERSETTINGS),await this.reset(),this.viewChangeCallback(),this.settingsChangeCallback()}get currentSettings(){return{appearance:it.appearanceValues[this.userProperties?.getByRef(H.APPEARANCE_REF)?.value],fontFamily:it.fontFamilyValues[this.userProperties?.getByRef(H.FONT_FAMILY_REF)?.value],textAlignment:it.textAlignmentValues[this.userProperties?.getByRef(H.TEXT_ALIGNMENT_REF)?.value],columnCount:it.columnCountValues[this.userProperties?.getByRef(H.COLUMN_COUNT_REF)?.value],direction:it.directionValues[this.userProperties?.getByRef(H.DIRECTION_REF)?.value],verticalScroll:this.verticalScroll,fontSize:this.fontSize,wordSpacing:this.wordSpacing,letterSpacing:this.letterSpacing,pageMargins:this.pageMargins,lineHeight:this.lineHeight,bodyHyphens:this.bodyHyphens,paraSpacing:this.paraSpacing,paraIndent:this.paraIndent,typeScale:this.typeScale,backgroundColor:this.backgroundColor,textColor:this.textColor}}async applyUserSettings(e){if(e.appearance){this.appearance=it.parseAppearanceSetting(e.appearance);let t=this.userProperties?.getByRef(H.APPEARANCE_REF);t&&(t.value=this.appearance,await this.storeProperty(t))}if(e.fontSize){this.fontSize=e.fontSize;let t=this.userProperties?.getByRef(H.FONT_SIZE_REF);t&&(t.value=this.fontSize,await this.storeProperty(t))}if(e.fontFamily){this.fontFamily=it.fontFamilyValues.findIndex(i=>i===e.fontFamily);let t=this.userProperties?.getByRef(H.FONT_FAMILY_REF);t&&(t.value=this.fontFamily,await this.storeProperty(t))}if(e.letterSpacing){this.letterSpacing=e.letterSpacing;let t=this.userProperties?.getByRef(H.LETTER_SPACING_REF);t&&(t.value=this.letterSpacing,await this.storeProperty(t))}if(e.wordSpacing){this.wordSpacing=e.wordSpacing;let t=this.userProperties?.getByRef(H.WORD_SPACING_REF);t&&(t.value=this.wordSpacing,await this.storeProperty(t))}if(e.columnCount){this.columnCount=it.columnCountValues.findIndex(i=>i===e.columnCount);let t=this.userProperties?.getByRef(H.COLUMN_COUNT_REF);t&&(t.value=this.columnCount,await this.storeProperty(t)),this.settingsColumnsChangeCallback()}if(e.direction){this.direction=it.directionValues.findIndex(i=>i===e.direction);let t=this.userProperties?.getByRef(H.DIRECTION_REF);t&&(t.value=this.direction,await this.storeProperty(t))}if(e.textAlignment){this.textAlignment=it.textAlignmentValues.findIndex(i=>i===e.textAlignment);let t=this.userProperties?.getByRef(H.TEXT_ALIGNMENT_REF);t&&(t.value=this.textAlignment,await this.storeProperty(t))}if(e.lineHeight){this.lineHeight=e.lineHeight;let t=this.userProperties?.getByRef(H.LINE_HEIGHT_REF);t&&(t.value=this.lineHeight,await this.storeProperty(t))}if(e.pageMargins){this.pageMargins=e.pageMargins;let t=this.userProperties?.getByRef(H.PAGE_MARGINS_REF);t&&(t.value=this.pageMargins,await this.storeProperty(t))}if(e.verticalScroll!==void 0){let t=this.view?.getCurrentPosition();this.verticalScroll=it.parseScrollSetting(e.verticalScroll);let i=this.userProperties?.getByRef(H.SCROLL_REF);i&&(i.value=this.verticalScroll,await this.saveProperty(i)),this.view?.setMode?.(this.verticalScroll),t&&this.view?.goToProgression(t),this.viewChangeCallback()}if(e.bodyHyphens!==void 0){this.bodyHyphens=e.bodyHyphens;let t=this.userProperties?.getByRef(H.BODY_HYPHENS_REF);t&&(t.value=this.bodyHyphens,await this.storeProperty(t))}if(e.paraSpacing!==void 0){this.paraSpacing=e.paraSpacing;let t=this.userProperties?.getByRef(H.PARA_SPACING_REF);t&&(t.value=this.paraSpacing,await this.storeProperty(t))}if(e.paraIndent!==void 0){this.paraIndent=e.paraIndent;let t=this.userProperties?.getByRef(H.PARA_INDENT_REF);t&&(t.value=this.paraIndent,await this.storeProperty(t))}if(e.typeScale!==void 0){this.typeScale=e.typeScale;let t=this.userProperties?.getByRef(H.TYPE_SCALE_REF);t&&(t.value=this.typeScale,await this.storeProperty(t))}if(e.backgroundColor!==void 0){this.backgroundColor=e.backgroundColor;let t=this.userProperties?.getByRef(H.BACKGROUND_COLOR_REF);t&&(t.value=this.backgroundColor,await this.storeProperty(t))}if(e.textColor!==void 0){this.textColor=e.textColor;let t=this.userProperties?.getByRef(H.TEXT_COLOR_REF);t&&(t.value=this.textColor,await this.storeProperty(t))}if(e.lineLength!==void 0&&(this.lineLength=e.lineLength),e.fontWeight!==void 0){this.fontWeight=e.fontWeight;let t=this.userProperties?.getByRef(H.FONT_WEIGHT_REF);t&&(t.value=this.fontWeight,await this.storeProperty(t))}if(e.fontWidth!==void 0){this.fontWidth=e.fontWidth;let t=this.userProperties?.getByRef(H.FONT_WIDTH_REF);t&&(t.value=this.fontWidth,await this.storeProperty(t))}e.fontOpticalSizing!==void 0&&(this.fontOpticalSizing=e.fontOpticalSizing),e.ligatures!==void 0&&(this.ligatures=e.ligatures),e.blendImages!==void 0&&(this.blendImages=e.blendImages),e.darkenImages!==void 0&&(this.darkenImages=e.darkenImages),e.invertImages!==void 0&&(this.invertImages=e.invertImages),e.invertGaiji!==void 0&&(this.invertGaiji=e.invertGaiji),e.linkColor!==void 0&&(this.linkColor=e.linkColor),e.visitedColor!==void 0&&(this.visitedColor=e.visitedColor),e.selectionBackgroundColor!==void 0&&(this.selectionBackgroundColor=e.selectionBackgroundColor),e.selectionTextColor!==void 0&&(this.selectionTextColor=e.selectionTextColor),e.scrollPaddingTop!==void 0&&(this.scrollPaddingTop=e.scrollPaddingTop),e.scrollPaddingBottom!==void 0&&(this.scrollPaddingBottom=e.scrollPaddingBottom),e.scrollPaddingLeft!==void 0&&(this.scrollPaddingLeft=e.scrollPaddingLeft),e.scrollPaddingRight!==void 0&&(this.scrollPaddingRight=e.scrollPaddingRight),await this.applyProperties(),this.settingsChangeCallback()}static parseScrollSetting(e){switch(e){case!0:case"scroll":case"readium-scroll-on":return!0;case!1:case"paginated":case"readium-scroll-off":return!1;default:return!1}}static parseAppearanceSetting(e){let t;return e==="day"||e==="readium-default-on"?t=it.appearanceValues[0]:e==="sepia"||e==="readium-sepia-on"?t=it.appearanceValues[1]:e==="night"||e==="readium-night-on"?t=it.appearanceValues[2]:t=e,it.appearanceValues.findIndex(i=>i===t)}async scroll(e){let t=this.view?.getCurrentPosition();this.verticalScroll=e;let i=this.userProperties?.getByRef(H.SCROLL_REF);i&&(i.value=this.verticalScroll,await this.saveProperty(i)),await this.applyProperties(),this.view?.setMode?.(this.verticalScroll),t&&this.view?.goToProgression(t),this.viewChangeCallback()}async increase(e){if(e==="fontSize"){(this.userProperties?.getByRef(H.FONT_SIZE_REF)).increment(),this.fontSize=this.userProperties?.getByRef(H.FONT_SIZE_REF)?.value;let t=this.userProperties?.getByRef(H.FONT_SIZE_REF);t&&await this.storeProperty(t)}else if(e==="letterSpacing"){(this.userProperties?.getByRef(H.LETTER_SPACING_REF)).increment(),this.letterSpacing=this.userProperties?.getByRef(H.LETTER_SPACING_REF)?.value;let t=this.userProperties?.getByRef(H.LETTER_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="wordSpacing"){(this.userProperties?.getByRef(H.WORD_SPACING_REF)).increment(),this.wordSpacing=this.userProperties?.getByRef(H.WORD_SPACING_REF)?.value;let t=this.userProperties?.getByRef(H.WORD_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="lineHeight"){(this.userProperties?.getByRef(H.LINE_HEIGHT_REF)).increment(),this.lineHeight=this.userProperties?.getByRef(H.LINE_HEIGHT_REF)?.value;let t=this.userProperties?.getByRef(H.LINE_HEIGHT_REF);t&&await this.storeProperty(t)}else if(e==="paraSpacing"){(this.userProperties?.getByRef(H.PARA_SPACING_REF)).increment(),this.paraSpacing=this.userProperties?.getByRef(H.PARA_SPACING_REF)?.value;let t=this.userProperties?.getByRef(H.PARA_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="paraIndent"){(this.userProperties?.getByRef(H.PARA_INDENT_REF)).increment(),this.paraIndent=this.userProperties?.getByRef(H.PARA_INDENT_REF)?.value;let t=this.userProperties?.getByRef(H.PARA_INDENT_REF);t&&await this.storeProperty(t)}else if(e==="typeScale"){(this.userProperties?.getByRef(H.TYPE_SCALE_REF)).increment(),this.typeScale=this.userProperties?.getByRef(H.TYPE_SCALE_REF)?.value;let t=this.userProperties?.getByRef(H.TYPE_SCALE_REF);t&&await this.storeProperty(t)}else if(e==="pageMargins"){(this.userProperties?.getByRef(H.PAGE_MARGINS_REF)).increment(),this.pageMargins=this.userProperties?.getByRef(H.PAGE_MARGINS_REF)?.value;let t=this.userProperties?.getByRef(H.PAGE_MARGINS_REF);t&&await this.storeProperty(t)}else if(e==="fontWeight"){(this.userProperties?.getByRef(H.FONT_WEIGHT_REF)).increment(),this.fontWeight=this.userProperties?.getByRef(H.FONT_WEIGHT_REF)?.value;let t=this.userProperties?.getByRef(H.FONT_WEIGHT_REF);t&&await this.storeProperty(t)}else if(e==="fontWidth"){(this.userProperties?.getByRef(H.FONT_WIDTH_REF)).increment(),this.fontWidth=this.userProperties?.getByRef(H.FONT_WIDTH_REF)?.value;let t=this.userProperties?.getByRef(H.FONT_WIDTH_REF);t&&await this.storeProperty(t)}await this.applyProperties(),this.settingsChangeCallback()}async decrease(e){if(e==="fontSize"){(this.userProperties?.getByRef(H.FONT_SIZE_REF)).decrement(),this.fontSize=this.userProperties?.getByRef(H.FONT_SIZE_REF)?.value;let t=this.userProperties?.getByRef(H.FONT_SIZE_REF);t&&await this.storeProperty(t)}else if(e==="letterSpacing"){(this.userProperties?.getByRef(H.LETTER_SPACING_REF)).decrement(),this.letterSpacing=this.userProperties?.getByRef(H.LETTER_SPACING_REF)?.value;let t=this.userProperties?.getByRef(H.LETTER_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="wordSpacing"){(this.userProperties?.getByRef(H.WORD_SPACING_REF)).decrement(),this.wordSpacing=this.userProperties?.getByRef(H.WORD_SPACING_REF)?.value;let t=this.userProperties?.getByRef(H.WORD_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="lineHeight"){(this.userProperties?.getByRef(H.LINE_HEIGHT_REF)).decrement(),this.lineHeight=this.userProperties?.getByRef(H.LINE_HEIGHT_REF)?.value;let t=this.userProperties?.getByRef(H.LINE_HEIGHT_REF);t&&await this.storeProperty(t)}else if(e==="paraSpacing"){(this.userProperties?.getByRef(H.PARA_SPACING_REF)).decrement(),this.paraSpacing=this.userProperties?.getByRef(H.PARA_SPACING_REF)?.value;let t=this.userProperties?.getByRef(H.PARA_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="paraIndent"){(this.userProperties?.getByRef(H.PARA_INDENT_REF)).decrement(),this.paraIndent=this.userProperties?.getByRef(H.PARA_INDENT_REF)?.value;let t=this.userProperties?.getByRef(H.PARA_INDENT_REF);t&&await this.storeProperty(t)}else if(e==="typeScale"){(this.userProperties?.getByRef(H.TYPE_SCALE_REF)).decrement(),this.typeScale=this.userProperties?.getByRef(H.TYPE_SCALE_REF)?.value;let t=this.userProperties?.getByRef(H.TYPE_SCALE_REF);t&&await this.storeProperty(t)}else if(e==="pageMargins"){(this.userProperties?.getByRef(H.PAGE_MARGINS_REF)).decrement(),this.pageMargins=this.userProperties?.getByRef(H.PAGE_MARGINS_REF)?.value;let t=this.userProperties?.getByRef(H.PAGE_MARGINS_REF);t&&await this.storeProperty(t)}else if(e==="fontWeight"){(this.userProperties?.getByRef(H.FONT_WEIGHT_REF)).decrement(),this.fontWeight=this.userProperties?.getByRef(H.FONT_WEIGHT_REF)?.value;let t=this.userProperties?.getByRef(H.FONT_WEIGHT_REF);t&&await this.storeProperty(t)}else if(e==="fontWidth"){(this.userProperties?.getByRef(H.FONT_WIDTH_REF)).decrement(),this.fontWidth=this.userProperties?.getByRef(H.FONT_WIDTH_REF)?.value;let t=this.userProperties?.getByRef(H.FONT_WIDTH_REF);t&&await this.storeProperty(t)}await this.applyProperties(),this.settingsChangeCallback()}};it.appearanceValues=["readium-default-on","readium-sepia-on","readium-night-on"],it.fontFamilyValues=["Original","serif","sans-serif"],it.textAlignmentValues=["auto","justify","start"],it.columnCountValues=["auto","1","2","3","4"],it.directionValues=["auto","ltr","rtl"];var yd=it;function fv(n,e,t,i){typeof t=="number"?n.style.setProperty(e,String(t)):t===!0?n.style.setProperty(e,i):n.style.removeProperty(e)}I();ci();Xt();I();I();I();I();I();I();I();var k_={stringify(n){let e=n.nSigBytes,t=n.words,i=[];for(let r=0;r<e;r++){let s=t[r>>>2]>>>24-r%4*8&255;i.push((s>>>4).toString(16)),i.push((s&15).toString(16))}return i.join("")},parse(n){let e=n.length;if(e%2!==0)throw new Error("Hex string count must be even");if(!/^[a-fA-F0-9]+$/.test(n))throw new Error(`Invalid Hex string: ${n}`);let t=[];for(let i=0;i<e;i+=2)t[i>>>3]|=parseInt(n.substr(i,2),16)<<24-i%8*4;return new er(t,e/2)}};I();I();var R_=typeof navigator<"u"&&navigator.userAgent?navigator.userAgent.toLowerCase():"",Ma=(()=>{let n=parseInt((/msie (\d+)/.exec(R_)||[])[1],10);return isNaN(n)?(n=parseInt((/trident\/.*; rv:(\d+)/.exec(R_)||[])[1],10),isNaN(n)?!1:n):n})();function L_(n,e){return Ma===!1?!1:e?n==="<"?Ma<e:n==="<="?Ma<=e:n===">"?Ma>e:n===">="?Ma>=e:Ma===e:!0}function C$(){if(typeof window<"u"){let n=window.crypto||window.msCrypto;if(!n){if(L_("<",11))return console.warn("IE <= 10 uses insecure random generator. Please consider to use IE11 or another modern browser"),function(){return Math.floor(Math.random()*512)%256};throw new Error("Crypto module not found")}return function(){return n.getRandomValues(new Uint32Array(1))[0]}}else{if(typeof globalThis<"u"&&globalThis.crypto)return function(){return globalThis.crypto.randomBytes(4).readInt32LE()};if(typeof v6=="function")return function(){return __non_webpack_require__("crypto").randomBytes(4).readInt32LE()}}throw new Error("Unable to find crypto module")}var M_=C$();var er=class n{constructor(e,t){if(Array.isArray(e)||!e){this._words=Array.isArray(e)?e:[],this._nSignificantBytes=typeof t=="number"?t:this._words.length*4;return}else if(e instanceof n){this._words=e.words.slice(),this._nSignificantBytes=e.nSigBytes;return}let i;try{e instanceof ArrayBuffer?i=new Uint8Array(e):(e instanceof Uint8Array||e instanceof Int8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array)&&(i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}catch{throw new Error("Invalid argument")}if(!i)throw new Error("Invalid argument");let r=i.byteLength,s=[];for(let o=0;o<r;o++)s[o>>>2]|=i[o]<<24-o%4*8;this._words=s,this._nSignificantBytes=r}get nSigBytes(){return this._nSignificantBytes}set nSigBytes(e){this._nSignificantBytes=e}get words(){return this._words}toString(e){return e?e.stringify(this):k_.stringify(this)}toUint8Array(){let e=this._words,t=this._nSignificantBytes,i=new Uint8Array(t);for(let r=0;r<t;r++)i[r]=e[r>>>2]>>>24-r%4*8&255;return i}concat(e){let t=e.words.slice(),i=e.nSigBytes;if(this.clamp(),this._nSignificantBytes%4)for(let r=0;r<i;r++){let s=t[r>>>2]>>>24-r%4*8&255;this._words[this._nSignificantBytes+r>>>2]|=s<<24-(this._nSignificantBytes+r)%4*8}else for(let r=0;r<i;r+=4)this._words[this._nSignificantBytes+r>>>2]=t[r>>>2];return this._nSignificantBytes+=i,this}clamp(){let e=this._nSignificantBytes;this._words[e>>>2]&=4294967295<<32-e%4*8,this._words.length=Math.ceil(e/4)}clone(){return new n(this._words.slice(),this._nSignificantBytes)}static random(e){let t=[];for(let i=0;i<e;i+=4)t.push(M_());return new n(t,e)}};I();I();var bv={stringify(n){let e=n.nSigBytes,t=n.words,i=[];for(let r=0;r<e;r++){let s=t[r>>>2]>>>24-r%4*8&255;i.push(String.fromCharCode(s))}return i.join("")},parse(n){let e=n.length,t=[];for(let i=0;i<e;i++)t[i>>>2]|=(n.charCodeAt(i)&255)<<24-i%4*8;return new er(t,e)}};var O_={stringify(n){try{return decodeURIComponent(escape(bv.stringify(n)))}catch{throw new Error("Malformed UTF-8 data")}},parse(n){return bv.parse(unescape(encodeURIComponent(n)))}};var Fp=class{constructor(e){this._minBufferSize=0,this._blockSize=0,this._props=e,this._data=e&&typeof e.data<"u"?e.data.clone():new er,this._nBytes=e&&typeof e.nBytes=="number"?e.nBytes:0}get blockSize(){return this._blockSize}reset(e,t){this._data=typeof e<"u"?e.clone():new er,this._nBytes=typeof t=="number"?t:0}_append(e){let t=typeof e=="string"?O_.parse(e):e;this._data.concat(t),this._nBytes+=t.nSigBytes}_process(e){let t,i=this._data.words,r=this._data.nSigBytes,s=this._blockSize,o=this._blockSize*4,a=r/o;e?a=Math.ceil(a):a=Math.max((a|0)-this._minBufferSize,0);let u=a*s,l=Math.min(u*4,r);if(u){for(let c=0;c<u;c+=s)this._doProcessBlock(i,c);t=i.splice(0,u),this._data.nSigBytes-=l}return new er(t,l)}_doProcessBlock(e,t){throw new Error("Not implemented")}};var Hp=class extends Fp{constructor(e){super(e),this._blockSize=512/32,this._props=e,e&&typeof e.blockSize=="number"&&(this._blockSize=e.blockSize),this.reset(e?e.data:void 0,e?e.nBytes:void 0)}get blockSize(){return this._blockSize}reset(e,t){super.reset.call(this,e,t),this._doReset()}update(e){return this._append(e),this._process(),this}finalize(e){return e&&this._append(e),this._doFinalize()}_doReset(){throw new Error("Not implemented")}_doFinalize(){throw new Error("Not implemented")}};var yv=[],B_=[];function x$(n){let e=Math.sqrt(n);for(let t=2;t<=e;t++)if(!(n%t))return!1;return!0}function N_(n){return(n-(n|0))*4294967296|0}(function(){let e=2,t=0;for(;t<64;)x$(e)&&(t<8&&(yv[t]=N_(Math.pow(e,1/2))),B_[t]=N_(Math.pow(e,1/3)),t++),e++})();var Oa=[],fs=class n extends Hp{constructor(e){super(e),this._hash=new er(yv.slice(0)),this._props=e,e&&typeof e.hash<"u"&&(this._hash=e.hash.clone())}_doReset(){this._hash=new er(yv.slice(0))}_doProcessBlock(e,t){let i=this._hash.words,r=i[0],s=i[1],o=i[2],a=i[3],u=i[4],l=i[5],c=i[6],d=i[7];for(let f=0;f<64;f++){if(f<16)Oa[f]=e[t+f]|0;else{let w=Oa[f-15],x=(w<<25|w>>>7)^(w<<14|w>>>18)^w>>>3,C=Oa[f-2],T=(C<<15|C>>>17)^(C<<13|C>>>19)^C>>>10;Oa[f]=x+Oa[f-7]+T+Oa[f-16]}let m=u&l^~u&c,y=r&s^r&o^s&o,g=(r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22),b=(u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25),v=d+b+m+B_[f]+Oa[f],A=g+y;d=c,c=l,l=u,u=a+v|0,a=o,o=s,s=r,r=v+A|0}i[0]=i[0]+r|0,i[1]=i[1]+s|0,i[2]=i[2]+o|0,i[3]=i[3]+a|0,i[4]=i[4]+u|0,i[5]=i[5]+l|0,i[6]=i[6]+c|0,i[7]=i[7]+d|0}_doFinalize(){let e=this._data.words,t=this._nBytes*8,i=this._data.nSigBytes*8;return e[i>>>5]|=128<<24-i%32,e[(i+64>>>9<<4)+14]=Math.floor(t/4294967296),e[(i+64>>>9<<4)+15]=t,this._data.nSigBytes=e.length*4,this._process(),this._hash}clone(){let e={hash:this._hash,blockSize:this._blockSize,data:this._data,nBytes:this._nBytes};return new n(e)}static hash(e,t){return new n(t).finalize(e)}};var Cd=$e($s());I();tr();I();var ln=$e(jt());function jp(n,e){let t=n.getClientRects();return vv(t,e)}function vv(n,e){let i=[];for(let u of n)i.push({bottom:u.bottom,height:u.height,left:u.left,right:u.right,top:u.top,width:u.width});let r=F_(i,1,e),s=k$(r,1),o=H_(s),a=4;for(let u=o.length-1;u>=0;u--){let l=o[u];if(!(l.width*l.height>a))if(o.length>1)ln.default.log("CLIENT RECT: remove small"),o.splice(u,1);else{ln.default.log("CLIENT RECT: remove small, but keep otherwise empty!");break}}return U_(o),ln.default.log(`CLIENT RECT: reduced ${i.length} --> ${o.length}`),o}function Ar(n,e,t){return Math.abs(n-e)<=t}function S$(n,e){let t=Math.max(n.left,e.left),i=Math.min(n.right,e.right),r=Math.max(n.top,e.top),s=Math.min(n.bottom,e.bottom);return{bottom:s,height:Math.max(0,s-r),left:t,right:i,top:r,width:Math.max(0,i-t)}}function D_(n,e){let t=S$(e,n);if(t.height===0||t.width===0)return[n];let i=[];{let r={bottom:n.bottom,height:0,left:n.left,right:t.left,top:n.top,width:0};r.width=r.right-r.left,r.height=r.bottom-r.top,r.height!==0&&r.width!==0&&i.push(r)}{let r={bottom:t.top,height:0,left:t.left,right:t.right,top:n.top,width:0};r.width=r.right-r.left,r.height=r.bottom-r.top,r.height!==0&&r.width!==0&&i.push(r)}{let r={bottom:n.bottom,height:0,left:t.left,right:t.right,top:t.bottom,width:0};r.width=r.right-r.left,r.height=r.bottom-r.top,r.height!==0&&r.width!==0&&i.push(r)}{let r={bottom:n.bottom,height:0,left:t.right,right:n.right,top:n.top,width:0};r.width=r.right-r.left,r.height=r.bottom-r.top,r.height!==0&&r.width!==0&&i.push(r)}return i}function Up(n,e,t,i){return(n.left<e||Ar(n.left,e,i))&&(n.right>e||Ar(n.right,e,i))&&(n.top<t||Ar(n.top,t,i))&&(n.bottom>t||Ar(n.bottom,t,i))}function T$(n,e,t){return Up(n,e.left,e.top,t)&&Up(n,e.right,e.top,t)&&Up(n,e.left,e.bottom,t)&&Up(n,e.right,e.bottom,t)}function I$(n,e){let t=Math.min(n.left,e.left),i=Math.max(n.right,e.right),r=Math.min(n.top,e.top),s=Math.max(n.bottom,e.bottom);return{bottom:s,height:s-r,left:t,right:i,top:r,width:i-t}}function Av(n,e,t){return(n.left<e.right||t>=0&&Ar(n.left,e.right,t))&&(e.left<n.right||t>=0&&Ar(e.left,n.right,t))&&(n.top<e.bottom||t>=0&&Ar(n.top,e.bottom,t))&&(e.top<n.bottom||t>=0&&Ar(e.top,n.bottom,t))}function F_(n,e,t){for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let s=n[i],o=n[r];if(s===o){ln.default.log("mergeTouchingRects rect1 === rect2 ??!");continue}let a=Ar(s.top,o.top,e)&&Ar(s.bottom,o.bottom,e),u=Ar(s.left,o.left,e)&&Ar(s.right,o.right,e);if((u&&!t||a&&!u)&&Av(s,o,e)){ln.default.log(`CLIENT RECT: merging two into one, VERTICAL: ${a} HORIZONTAL: ${u} (${t})`);let f=n.filter(y=>y!==s&&y!==o),m=I$(s,o);return f.push(m),F_(f,e,t)}}return n}function H_(n){for(let e=0;e<n.length;e++)for(let t=e+1;t<n.length;t++){let i=n[e],r=n[t];if(i===r){ln.default.log("replaceOverlappingRects rect1 === rect2 ??!");continue}if(Av(i,r,-1)){let s=[],o,a,u=D_(i,r);if(u.length===1)s=u,o=i,a=r;else{let d=D_(r,i);u.length<d.length?(s=u,o=i,a=r):(s=d,o=r,a=i)}let l=[];l.push(a),Array.prototype.push.apply(l,s),U_(l),ln.default.log(`CLIENT RECT: overlap, cut one rect into ${s.length}`);let c=n.filter(d=>d!==o);return Array.prototype.push.apply(c,s),H_(c)}}return n}function _$(n,e){return Math.max(0,Math.min(n.right,e.right)-Math.max(n.left,e.left))}function P$(n,e){return Math.max(0,Math.min(n.bottom,e.bottom)-Math.max(n.top,e.top))}function k$(n,e){let t=new Set(n);for(let i of n){if(!(i.width>1&&i.height>1)){ln.default.log("CLIENT RECT: remove tiny"),t.delete(i);continue}for(let s of n)if(i!==s&&t.has(s)&&T$(s,i,e)){ln.default.log("CLIENT RECT: remove contained"),t.delete(i);break}}return Array.from(t)}function U_(n){let e=[];for(let t of n)for(let i of n){if(t===i)continue;let r=e.indexOf(t)>=0,s=e.indexOf(i)>=0;if((!r||!s)&&Av(t,i,-1)){r||e.push(t),s||e.push(i),ln.default.log("CLIENT RECT: overlap ---"),ln.default.log(`#1 TOP:${t.top} BOTTOM:${t.bottom} LEFT:${t.left} RIGHT:${t.right} WIDTH:${t.width} HEIGHT:${t.height}`),ln.default.log(`#2 TOP:${i.top} BOTTOM:${i.bottom} LEFT:${i.left} RIGHT:${i.right} WIDTH:${i.width} HEIGHT:${i.height}`);let o=_$(t,i);ln.default.log(`xOverlap: ${o}`);let a=P$(t,i);ln.default.log(`yOverlap: ${a}`)}}e.length&&ln.default.log(`CLIENT RECT: overlaps ${e.length}`)}I();var Nt=$e(jt());function ps(n,e){let t=n?n.getSelection():null;if(!t)return;if(t.isCollapsed){Nt.default.log("^^^ SELECTION COLLAPSED.");return}let i=t.toString(),r=i.trim().replace(/\n/g," ").replace(/\s\s+/g," ");if(r.length===0){Nt.default.log("^^^ SELECTION TEXT EMPTY.");return}if(!t.anchorNode||!t.focusNode)return;let s=t.rangeCount===1?t.getRangeAt(0):W_(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset);if(!s||s.collapsed){Nt.default.log("$$$$$$$$$$$$$$$$$ CANNOT GET NON-COLLAPSED SELECTION RANGE?!");return}let o=L$(s);o.startContainer!==s.startContainer&&(Nt.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startContainer"),Nt.default.log(o.startContainer),Nt.default.log(s.startContainer)),o.startOffset!==s.startOffset&&(Nt.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startOffset"),Nt.default.log(`${o.startOffset} !== ${s.startOffset}`)),o.endContainer!==s.endContainer&&(Nt.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endContainer"),Nt.default.log(o.endContainer),Nt.default.log(s.endContainer)),o.endOffset!==s.endOffset&&(Nt.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endOffset"),Nt.default.log(`${o.endOffset} !== ${s.endOffset}`));let a=Qs(o,e);if(!a){Nt.default.log("^^^ SELECTION RANGE INFO FAIL?!");return}return{rangeInfo:a,cleanText:r,rawText:i,range:o}}function W_(n,e,t,i){try{let r=new Range;if(r.setStart(n,e),r.setEnd(t,i),!r.collapsed)return Nt.default.log(">>> createOrderedRange RANGE OK"),r;Nt.default.log(">>> createOrderedRange COLLAPSED ... RANGE REVERSE?");let s=new Range;if(s.setStart(t,i),s.setEnd(n,e),!s.collapsed)return Nt.default.log(">>> createOrderedRange RANGE REVERSE OK."),r;Nt.default.log(">>> createOrderedRange RANGE REVERSE ALSO COLLAPSED?!");return}catch(r){console.warn(r.message);return}}function Qs(n,e){let t=n.startContainer.nodeType===Node.ELEMENT_NODE,i=t?n.startContainer:n.startContainer.parentNode&&n.startContainer.parentNode.nodeType===Node.ELEMENT_NODE?n.startContainer.parentNode:void 0;if(!i)return;let r=t?-1:Array.from(i.childNodes).indexOf(n.startContainer);if(r<-1)return;let s=e(i),o=n.endContainer.nodeType===Node.ELEMENT_NODE,a=o?n.endContainer:n.endContainer.parentNode&&n.endContainer.parentNode.nodeType===Node.ELEMENT_NODE?n.endContainer.parentNode:void 0;if(!a)return;let u=o?-1:Array.from(a.childNodes).indexOf(n.endContainer);if(u<-1)return;let l=e(a),c=R$(n.startContainer,n.endContainer);if(!c){Nt.default.log("^^^ NO RANGE COMMON ANCESTOR?!");return}if(n.commonAncestorContainer){let d=n.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?n.commonAncestorContainer:n.commonAncestorContainer.parentNode;d&&d.nodeType===Node.ELEMENT_NODE&&c!==d&&(Nt.default.log(">>>>>> COMMON ANCESTOR CONTAINER DIFF??!"),Nt.default.log(e(c)),Nt.default.log(e(d)))}if(l&&s)return{endContainerChildTextNodeIndex:u,endContainerElementCssSelector:l,endOffset:n.endOffset,startContainerChildTextNodeIndex:r,startContainerElementCssSelector:s,startOffset:n.startOffset}}function Gp(n,e){let t=n.querySelector(e.startContainerElementCssSelector);if(!t){Nt.default.log("^^^ convertRangeInfo NO START ELEMENT CSS SELECTOR?!");return}let i=t;if(e.startContainerChildTextNodeIndex>=0){if(e.startContainerChildTextNodeIndex>=t.childNodes.length){Nt.default.log("^^^ convertRangeInfo rangeInfo.startContainerChildTextNodeIndex >= startElement.childNodes.length?!");return}if(i=t.childNodes[e.startContainerChildTextNodeIndex],i.nodeType!==Node.TEXT_NODE){Nt.default.log("^^^ convertRangeInfo startContainer.nodeType !== Node.TEXT_NODE?!");return}}let r=n.querySelector(e.endContainerElementCssSelector);if(!r){Nt.default.log("^^^ convertRangeInfo NO END ELEMENT CSS SELECTOR?!");return}let s=r;if(e.endContainerChildTextNodeIndex>=0){if(e.endContainerChildTextNodeIndex>=r.childNodes.length){Nt.default.log("^^^ convertRangeInfo rangeInfo.endContainerChildTextNodeIndex >= endElement.childNodes.length?!");return}if(s=r.childNodes[e.endContainerChildTextNodeIndex],s.nodeType!==Node.TEXT_NODE){Nt.default.log("^^^ convertRangeInfo endContainer.nodeType !== Node.TEXT_NODE?!");return}}return W_(i,e.startOffset,s,e.endOffset)}function R$(n,e){if(n.nodeType===Node.ELEMENT_NODE&&n===e||n.nodeType===Node.ELEMENT_NODE&&n.contains(e))return n;if(e.nodeType===Node.ELEMENT_NODE&&e.contains(n))return e;let t=[],i=n.parentNode;for(;i&&i.nodeType===Node.ELEMENT_NODE;)t.push(i),i=i.parentNode;let r=[];for(i=e.parentNode;i&&i.nodeType===Node.ELEMENT_NODE;)r.push(i),i=i.parentNode;let s=t.find(o=>r.indexOf(o)>=0);return s||(s=r.find(o=>t.indexOf(o)>=0)),s}function L$(n){let e=n.cloneRange(),t=e.startContainer,i=e.startOffset,r=e.endContainer,s=e.endOffset;t.childNodes.length&&i>0&&(t=G_(t.childNodes[i-1]),i=t.length||0),s<r.childNodes.length&&(r=j_(r.childNodes[s]),s=0);let o=j_(t),a=G_(r);function u(l){if(l.childNodes.length)return!1;let c=l.length||0;return l===t&&i===c?!1:!(l===r&&s===0)}for(;o&&!u(o)&&o!==a;)o=M$(o);for(o===t?e.setStart(t,i):o!==null&&(o.nodeType===3?e.setStart(o,0):e.setStartBefore(o));a&&!u(a)&&a!==o;)a=O$(a);return a===r?e.setEnd(r,s):a!==null&&(a.nodeType===3?e.setEnd(a,a.length):e.setEndAfter(a)),e}function M$(n){if(n.firstChild)return n.firstChild;let e=n;for(;!e.nextSibling;)if(e=e.parentNode,!e)return null;return e.nextSibling}function O$(n){if(n.lastChild)return n.lastChild;let e=n;for(;!e.previousSibling;)if(e=e.parentNode,!e)return null;return e.previousSibling}function j_(n){for(;n.firstChild;)n=n.firstChild;return n}function G_(n){for(;n.lastChild;)n=n.lastChild;return n}I();var Tv=$e(V_());var Xs,Iv;function Vi(n,e,t){if(n.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if(n.tagName.toLowerCase()==="html")return n.tagName.toLowerCase();let i={className:s=>!0,idName:s=>!0,optimizedMinLength:2,root:e.body,seedMinLength:1,tagName:s=>!0,threshold:1e3};Xs={...i,...t},Iv=j$(Xs.root,i);let r=Ev(n,0,()=>Ev(n,1,()=>Ev(n,2)));if(r){let s=Q_(X_(r,n));return s.length>0&&(r=s[0]),Wp(r)}else throw new Error("Selector was not found.")}function j$(n,e){return n.nodeType===Node.DOCUMENT_NODE?n:n===e.root?n.ownerDocument:n}function Ev(n,e,t){let i=null,r=[],s=n,o=0;for(;s&&s!==Xs.root.parentElement;){let a=Sv(G$(s))||Sv(...W$(s))||Sv(z$(s))||[V$()],u=K$(s);if(e===0)u&&(a=a.concat(a.filter(xv).map(l=>Cv(l,u))));else if(e===1)a=a.slice(0,1),u&&(a=a.concat(a.filter(xv).map(l=>Cv(l,u))));else if(e===2){let[l]=a=a.slice(0,1);u&&xv(l)&&(a=[Cv(l,u)])}for(let l of a)l.level=o;if(r.push(a),r.length>=Xs.seedMinLength&&(i=K_(r,t),i))break;s=s.parentElement,o++}return i||(i=K_(r,t)),i}function K_(n,e){let t=Q_($_(n));if(t.length>Xs.threshold)return e?e():null;for(let i of t)if(q_(i))return i;return null}function Wp(n){let e=n[0],t=e.name;for(let i=1;i<n.length;i++){let r=n[i].level||0;e.level===r-1?t=`${n[i].name} > ${t}`:t=`${n[i].name} ${t}`,e=n[i]}return t}function Y_(n){return n.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function q_(n){switch(Iv.querySelectorAll(Wp(n)).length){case 0:throw new Error(`Can't select any node with this selector: ${Wp(n)}`);case 1:return!0;default:return!1}}function G$(n){let e=n.getAttribute("id");return e&&Xs.idName(e)?{name:"#"+(0,Tv.default)(e,{isIdentifier:!0}),penalty:0}:null}function W$(n){return Array.from(n.classList).filter(Xs.className).map(t=>({name:"."+(0,Tv.default)(t,{isIdentifier:!0}),penalty:1}))}function z$(n){let e=n.tagName.toLowerCase();return Xs.tagName(e)?{name:e,penalty:2}:null}function V$(){return{name:"*",penalty:3}}function K$(n){let e=n.parentNode;if(!e)return null;let t=e.firstChild;if(!t)return null;let i=0;for(;t&&(t.nodeType===Node.ELEMENT_NODE&&i++,t!==n);)t=t.nextSibling;return i}function Cv(n,e){return{name:n.name+`:nth-child(${e})`,penalty:n.penalty+1}}function xv(n){return n.name!=="html"&&!n.name.startsWith("#")}function Sv(...n){let e=n.filter(Y$);return e.length>0?e:null}function Y$(n){return n!=null}function*$_(n,e=[]){if(n.length>0)for(let t of n[0])yield*$_(n.slice(1,n.length),e.concat(t));else yield e}function Q_(n){return Array.from(n).sort((e,t)=>Y_(e)-Y_(t))}function*X_(n,e){if(n.length>2&&n.length>Xs.optimizedMinLength)for(let t=1;t<n.length-1;t++){let i=[...n];i.splice(t,1),q_(i)&&q$(i,e)&&(yield i,yield*X_(i,e))}}function q$(n,e){return Iv.querySelector(Wp(n))===e}I();_v();Ad();ci();var Rv=$e(zp());dv();var yn=$e(jt()),Na=(u=>(u.R2_ID_HIGHLIGHTS_CONTAINER="R2_ID_HIGHLIGHTS_CONTAINER",u.R2_ID_BOOKMAKRS_CONTAINER="R2_ID_BOOKMAKRS_CONTAINER",u.R2_ID_READALOUD_CONTAINER="R2_ID_READALOUD_CONTAINER",u.R2_ID_PAGEBREAK_CONTAINER="R2_ID_PAGEBREAK_CONTAINER",u.R2_ID_SEARCH_CONTAINER="R2_ID_SEARCH_CONTAINER",u.R2_ID_DEFINITIONS_CONTAINER="R2_ID_DEFINITIONS_CONTAINER",u.R2_ID_LINEFOCUS_CONTAINER="R2_ID_LINEFOCUS_CONTAINER",u.R2_ID_GUTTER_RIGHT_CONTAINER="R2_ID_GUTTER_RIGHT_CONTAINER",u))(Na||{}),e7="R2_CLASS_HIGHLIGHT_CONTAINER",xd="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",cn="R2_CLASS_HIGHLIGHT_AREA",Ed="R2_CLASS_HIGHLIGHT_ICON",ms=.5,Z_=.75,Ba={blue:100,green:50,red:230},di=[],X$="data-highlighted",J$="data-timestamp",gl={ELEMENT_NODE:1,TEXT_NODE:3};var ir=["R2_ID_HIGHLIGHTS_CONTAINER","R2_ID_PAGEBREAK_CONTAINER","R2_ID_SEARCH_CONTAINER","R2_ID_READALOUD_CONTAINER","R2_ID_BOOKMAKRS_CONTAINER","R2_ID_DEFINITIONS_CONTAINER","R2_ID_LINEFOCUS_CONTAINER","R2_ID_GUTTER_RIGHT_CONTAINER",e7,cn,xd],Pv=-1,kv=-1,$t=class n{constructor(e,t,i,r,s,o){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.colors=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"];this.showTool=(0,Cd.default)(e=>{this.isAndroid()||this.snapSelectionToWord(e),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,Cd.default)(()=>{if(!this.isSelectionMenuOpen){this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen();let e=this.navigator.iframes[0].contentDocument,t=e?this.dom(e.body)?.getSelection():null,i=t&&!t.isCollapsed?t.toString():void 0;this.navigator.emit(xe.ToolboxOpened,"opened",{text:i}),i&&t&&(this.api?.selection&&this.api.selection(i,t),this.navigator.emit(xe.TextSelected,{text:i,selection:t}))}},100);this.selectionMenuClosed=(0,Cd.default)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.navigator.emit(xe.ToolboxClosed,"closed"))},100);this.selection=(0,Cd.default)((e,t)=>{},100);this.getScrollingElement=e=>e?.scrollingElement?e?.scrollingElement:e?.body?e?.body:document.createElement("body");this.layerSettings=e,this.properties=t,this.properties.menuPosition===void 0&&(this.properties.menuPosition="inline"),this.api=s,this.hasEventListener=i,o&&o.length>0&&(this.colors=o),this.options=this.defaults(r,{color:this.colors[0],highlightedClass:"highlighted",contextClass:"highlighter-context",onBeforeHighlight:function(){return!0},onAfterHighlight:function(){}})}static async create(e){let t=new this(e.layerSettings,e,!1,{},e.api,e.colors);return new Promise(i=>i(t))}async initialize(e){let t=e.contentDocument;t&&this.dom(t.body).addClass(this.options.contextClass),this.bindEvents(e.contentDocument?.body,this,this.hasEventListener),this.initializeToolbox(),Pv=-1,kv=-1;let i=this;async function r(){i.lastSelectedHighlight===void 0||(i.lastSelectedHighlight=void 0)}setTimeout(async()=>{let s=e.contentDocument;s&&await s.body?.addEventListener("click",r)},100)}haveSameColor(e,t){return this.dom(e).color()===this.dom(t).color()}defaults(e,t){e=e||{};for(let i in t)t.hasOwnProperty(i)&&e[i]===void 0&&(e[i]=t[i]);return e}unique(e){return e.filter(function(t,i,r){return r.indexOf(t)===i})}refineRangeBoundaries(e){let t=e.startContainer,i=e.endContainer,r=e.commonAncestorContainer,s=!0;if(e.endOffset===0){for(;!i.previousSibling&&i.parentNode!==r;)i=i.parentNode;i=i.previousSibling}else i.nodeType===gl.TEXT_NODE?e.endOffset<i.nodeValue.length&&i.splitText(e.endOffset):e.endOffset>0&&(i=i.childNodes.item(e.endOffset-1));return t.nodeType===gl.TEXT_NODE?e.startOffset===t.nodeValue.length?s=!1:e.startOffset>0&&(t=t.splitText(e.startOffset),i===t.previousSibling&&(i=t)):e.startOffset<t.childNodes.length?t=t.childNodes.item(e.startOffset):t=t.nextSibling,{startContainer:t,endContainer:i,goDeeper:s}}sortByDepth(e,t){let i=this;e.sort(function(r,s){return i.dom(t?s:r).parents().length-i.dom(t?r:s).parents().length})}groupHighlights(e){let t=[],i={},r=[];return e.forEach(function(s){let o=s.getAttribute(J$);typeof i[o]>"u"&&(i[o]=[],t.push(o)),i[o].push(s)}),t.forEach(function(s){let o=i[s];r.push({chunks:o,timestamp:s,toString:function(){return o.map(function(a){return a.textContent}).join("")}})}),r}dom(e){let t=this;return{addClass:function(i){e.classList?e.classList.add(i):e.className+=" "+i},removeClass:function(i){e.classList?e.classList.remove(i):e.className=e.className.replace(new RegExp("(^|\\b)"+i+"(\\b|$)","gi")," ")},prepend:function(i){let r=Array.prototype.slice.call(i),s=r.length;for(;s--;)e.insertBefore(r[s],e.firstChild)},append:function(i){let r=Array.prototype.slice.call(i);for(let s=0,o=r.length;s<o;++s)e.appendChild(r[s])},insertAfter:function(i){return i.parentNode?.insertBefore(e,i.nextSibling)},insertBefore:function(i){return i.parentNode?.insertBefore(e,i)},remove:function(){e.parentNode.removeChild(e),e=null},contains:function(i){return e!==i&&e.contains(i)},wrap:function(i){return e.parentNode&&e.parentNode.insertBefore(i,e),i.appendChild(e),i},unwrap:function(){let i=Array.prototype.slice.call(e.childNodes),r;return i.forEach(function(s){r=s.parentNode,t.dom(s).insertBefore(s.parentNode),t.dom(r).remove()}),i},parents:function(){let i,r=[];for(;i=e.parentNode;)r.push(i),e=i;return r},normalizeTextNodes:function(){if(e){if(e.nodeType===gl.TEXT_NODE)for(;e.nextSibling&&e.nextSibling.nodeType===gl.TEXT_NODE;)e.nodeValue+=e.nextSibling.nodeValue,e.parentNode.removeChild(e.nextSibling);else t.dom(e.firstChild).normalizeTextNodes();t.dom(e.nextSibling).normalizeTextNodes()}},color:function(){return e.style.backgroundColor},fromHTML:function(i){let r=document.createElement("div");return r.innerHTML=i,r.childNodes},getRange:function(){let i=t.dom(e)?.getSelection(),r;return i?.rangeCount>0&&(r=i?.getRangeAt(0)),r},removeAllRanges:function(){t.dom(e)?.getSelection()?.removeAllRanges(),t.toolboxHide()},getSelection:function(){return t.dom(e).getWindow()?.getSelection()},getWindow:function(){return t.dom(e).getDocument()?.defaultView},getDocument:function(){return e?.ownerDocument||e}}}disableContext(e){return e.preventDefault(),e.stopPropagation(),!1}bindEvents(e,t,i){let r=e.ownerDocument;e.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),e.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),r.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),r.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),i||window.addEventListener("resize",this.toolboxPlacement.bind(this)),r.addEventListener("selectionchange",this.toolboxPlacement.bind(this)),this.isIOS()||r.addEventListener("selectionchange",this.toolboxShowDelayed.bind(this)),e.addEventListener("mousedown",this.toolboxHide.bind(this)),e.addEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&e.addEventListener("contextmenu",this.disableContext),e.addEventListener("mousedown",this.mousedown.bind(this)),e.addEventListener("mouseup",this.mouseup.bind(this)),e.addEventListener("touchstart",this.mousedown.bind(this)),e.addEventListener("touchend",this.mouseup.bind(this)),this.hasEventListener=!0}async mousedown(e){if(Pv=e.clientX,kv=e.clientY,this.properties?.preventScrollOnSelection){let t=dt(document,"#iframe-wrapper");t.style.overflow="hidden"}}async mouseup(e){Math.abs(Pv-e.clientX)<3&&Math.abs(kv-e.clientY)<3&&await this.processMouseEvent(e)}async mousemove(e){await this.processMouseEvent(e)}unbindEvents(e,t){let i=e.ownerDocument;e.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),e.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),i.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),i.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),i.removeEventListener("selectionchange",this.toolboxPlacement.bind(this)),e.removeEventListener("mousedown",this.toolboxHide.bind(this)),e.removeEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&e.removeEventListener("contextmenu",this.disableContext),e.removeEventListener("mousedown",this.mousedown.bind(this)),e.removeEventListener("mouseup",this.mouseup.bind(this)),e.removeEventListener("mousemove",this.mousemove.bind(this)),e.removeEventListener("touchstart",this.mousedown.bind(this)),e.removeEventListener("touchend",this.mouseup.bind(this)),e.removeEventListener("touchmove",this.mousemove.bind(this)),this.hasEventListener=!1}destroy(){this.toolboxHide();let e=this.navigator.iframes[0].contentDocument;e&&(this.unbindEvents(e.body,this),this.dom(e.body).removeClass(this.options.contextClass))}initializeToolbox(){let e=document.getElementById("highlight-toolbox-mode-colors"),t=document.getElementById("highlight-toolbox-mode-add"),i=document.getElementById("colorIcon"),r=document.getElementById("actionIcon"),s=document.getElementById("dismissIcon"),o=document.getElementById("collapseIcon"),a=document.getElementById("highlightIcon"),u=this;if(s&&(s.innerHTML=jr.close,s.addEventListener("click",function(){u.toolboxMode("add")})),o&&(o.innerHTML=jr.close,o.addEventListener("click",function(){u.toolboxMode("add")})),i){i.style.position="relative",i.style.zIndex="20",this.colors.forEach(d=>{let f=document.getElementById(d),m=document.getElementById(`c${d}`);f&&e?.contains(f)&&e.removeChild(f),t&&m&&t.contains(m)&&t.removeChild(m)});let l=[],c=[];if(i.addEventListener("click",function(){u.toolboxMode("colors")}),this.navigator.rights.enableAnnotations){let d=10;this.colors.forEach(f=>{d--;let m=i?.cloneNode(!0),y=m.lastChild,g=n.hexToRgbChannels(f);y.style.backgroundColor="rgba("+[g.red,g.green,g.blue].join(",")+",.5)",m.id=`c${f}`,m.style.display="unset",m.style.position="relative",m.style.zIndex=`${d}`,m.style.marginLeft="-30px",c.push(m),t?.insertBefore(m,a)})}this.colors.forEach(d=>{let f=i?.cloneNode(!0),m=f.lastChild;m.style.backgroundColor=d,f.id=d,f.style.position="relative",f.style.display="unset",l.push(f),i&&f.addEventListener("click",function(){u.setColor(d);let y=i?.lastChild;y&&(y.style.backgroundColor=d);let g=document.getElementById("highlightIcon"),b=document.getElementById("underlineIcon"),v=document.getElementById("noteIcon");(g?.getElementsByTagName?.("span").length??0)>0&&((g?.getElementsByTagName("span")[0]).style.background=u.getColor()),(b?.getElementsByTagName?.("span").length??0)>0&&((b?.getElementsByTagName("span")[0]).style.borderBottomColor=u.getColor()),(v?.getElementsByTagName?.("span").length??0)>0&&((v?.getElementsByTagName("span")[0]).style.borderBottomColor=u.getColor()),u.toolboxMode("add")}),e?.insertBefore(f,s)})}r&&r.addEventListener("click",function(){u.toolboxMode("action")}),u.toolboxMode("add")}toolboxMode(e){let t=document.getElementById("highlight-toolbox-mode-colors"),i=document.getElementById("highlight-toolbox-mode-add"),r=document.getElementById("highlight-toolbox-mode-edit"),s=document.getElementById("highlight-toolbox-mode-action");switch(e){case"colors":this.selectionMenuOpened(),t&&(t.style.display="unset"),i&&(i.style.display="none"),r&&(r.style.display="none"),s&&(s.style.display="none");break;case"edit":this.selectionMenuOpened(),t&&(t.style.display="none"),i&&(i.style.display="none"),r&&(r.style.display="unset"),s&&(s.style.display="none");break;case"action":this.selectionMenuOpened(),t&&(t.style.display="none"),i&&(i.style.display="none"),r&&(r.style.display="none"),s&&(s.style.display="unset");break;default:this.selectionMenuOpened(),t&&(t.style.display="none"),i&&(i.style.display="unset"),r&&(r.style.display="none"),s&&(s.style.display="none");break}}toolboxHide(){let e=document.getElementById("highlight-toolbox");if(e&&(e.style.display="none"),this.selectionMenuClosed(),this.properties?.preventScrollOnSelection){let t=dt(document,"#iframe-wrapper");t.style.overflow="auto"}}toolboxShowDelayed(e){this.showTool(e.detail===1)}snapSelectionToWord(e=!1){let t=this,i=this.navigator.iframes[0].contentDocument;if(i){let s=t.dom(i.body)?.getSelection();if(t.dom(i.body)&&s&&!s?.isCollapsed){let l=function(b){let v=b.match(new RegExp("[^a-zA-Z0-9]+$"));return!v||!v.index?b:b.slice(0,v.index)},o=s.toString(),a=o.length-o.trimStart().length,u=o.length-o.trimEnd().length,c=o.length;var r=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;o=o.replace(r,""),a=c-o.trimStart().length,o=l(o),u=c-o.trimEnd().length;let d=document.createRange();e?(d.setStart(s.anchorNode,s.anchorOffset+a),d.setEnd(s.focusNode,s.focusOffset-u)):(d.setStart(s.anchorNode,s.anchorOffset),d.setEnd(s.focusNode,s.focusOffset));let f=d.collapsed;d.detach();let m=s.focusNode,y;e?(y=s.focusOffset-u,s.collapse(s.anchorNode,s.anchorOffset+a)):(y=s.focusOffset,s.collapse(s.anchorNode,s.anchorOffset));let g=["forward","backward"];f&&(g=["backward","forward"]),e?(s.modify("move",g[0],"character"),s.modify("move",g[1],"word"),s.extend(m,y),s.modify("extend",g[1],"character"),s.modify("extend",g[0],"word")):s.extend(m,y),this.selection(s.toString(),s)}return s}}toolboxShow(){if(this.activeAnnotationMarkerId===void 0){let e=this,t=document.getElementById("highlight-toolbox-mode-add"),i=this.dom(this.navigator.iframes[0].contentDocument?.body).getRange();if((!i||i.collapsed)&&t){getComputedStyle(t).display!=="none"&&e.toolboxHide();return}this.isIOS()&&setTimeout(function(){let r=e.navigator.iframes[0].contentDocument;if(r){let s=e.dom(r.body).getSelection();s.removeAllRanges(),setTimeout(function(){s.addRange(i);function o(l){let c={className:f=>ir.indexOf(f)<0,idName:f=>ir.indexOf(f)<0},d=e.navigator.iframes[0].contentDocument;if(d)return Vi(l,d,c)}let a=e.navigator.iframes[0].contentWindow,u=ps(a,o);u&&e.navigator.modules.annotations?.annotator?.saveTemporarySelectionInfo(u)},5)}},100),this.toolboxPlacement(),this.toolboxHandler()}}toolboxPlacement(){let e=this.dom(this.navigator.iframes[0].contentDocument?.body).getRange();if(!e||e.collapsed)return;let t=e.getBoundingClientRect(),i=document.getElementById("highlight-toolbox");if(i)if(this.properties?.menuPosition==="top")i.style.left="0px",i.style.transform="revert",i.style.width="100%",i.style.textAlign="center",i.style.position="absolute",i.style.setProperty("--content","revert");else if(this.properties?.menuPosition==="bottom")i.style.bottom="0px",i.style.left="0px",i.style.transform="revert",i.style.width="100%",i.style.textAlign="center",i.style.position="absolute",i.style.setProperty("--content","revert");else{let r=this.navigator.iframes[0],s=r?.getBoundingClientRect(),o=r?getComputedStyle(r):null,a=o&&parseFloat(o.paddingTop)||0,u=o&&parseFloat(o.paddingLeft)||0,l=(s?.top??0)+(r?.clientTop??0)+a,c=(s?.left??0)+(r?.clientLeft??0)+u,d=r?.contentWindow?.getSelection(),f=null,m=!0;if(d&&d.focusNode&&d.anchorNode){let W=d.anchorNode.compareDocumentPosition(d.focusNode);W&Node.DOCUMENT_POSITION_PRECEDING?m=!1:W===0&&(m=d.anchorOffset<=d.focusOffset);try{let $=r.contentDocument.createRange();$.setStart(d.focusNode,d.focusOffset),$.collapse(!0);let te=$.getClientRects();te.length>0&&(f=te[0])}catch{f=null}}i.style.position="fixed";let y=i.offsetHeight||0,g=window.innerHeight,b=(f?.top??t.top)+l,v=(f?.bottom??t.bottom)+l,A=this.navigator.attributes?.safeArea,w=W=>{try{return W?.()?.getBoundingClientRect().height??0}catch{return 0}},x=w(A?.top),C=w(A?.bottom),_=e.getClientRects().length>1&&m,R=b-y<x,L=v+y>g-C;_&&L&&!R?_=!1:!_&&R&&!L&&(_=!0),_?(i.classList.add("below"),i.style.top=v+"px"):(i.classList.remove("below"),i.style.top=b+"px");let M=f!=null?f.left:m?t.right:t.left,O=c+M,U=i.offsetWidth||0,G=window.innerWidth,j;if(U>=G)j=G/2;else{let W=U/2,z=G-U/2;j=Math.max(W,Math.min(z,O))}i.style.left=j+"px"}}toolboxHandler(){let e=document.getElementById("highlight-toolbox");if(e&&getComputedStyle(e).display==="none"){e.style.display="block",this.navigator.view?.isPaginated()?e.style.position="absolute":e.style.position="relative",this.selectionMenuOpened();let i=this;i.toolboxMode("add");let r=document.getElementById("highlightIcon"),s=document.getElementById("collapseIcon"),o=document.getElementById("underlineIcon"),a=document.getElementById("noteIcon"),u=document.getElementById("colorIcon"),l=document.getElementById("speakIcon");if(this.navigator.rights.enableAnnotations){if(r&&(r.style.display="unset",u&&r.getElementsByTagName("span").length>0&&(r.getElementsByTagName("span")[0].style.background=this.getColor())),o&&(o.style.display="unset",u&&o.getElementsByTagName("span").length>0&&(o.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),a&&(a.style.display="unset",u&&a.getElementsByTagName("span").length>0&&(a.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),u){u.style.display="unset";let c=u.lastChild;c.style.backgroundColor=this.getColor()}if(r){let c=function(){i.doHighlight(!1,0),i.toolboxHide(),r?.removeEventListener("click",c)},d=r.cloneNode(!0);r?.parentNode?.replaceChild(d,r),r=document.getElementById("highlightIcon"),r?.addEventListener("click",c)}if(o){let c=function(){i.doHighlight(!1,1),i.toolboxHide(),o?.removeEventListener("click",c)},d=o.cloneNode(!0);o?.parentNode?.replaceChild(d,o),o=document.getElementById("underlineIcon"),o?.addEventListener("click",c)}if(a){let c=function(){i.doHighlight(!1,4),i.toolboxHide(),a?.removeEventListener("click",c)},d=a.cloneNode(!0);a?.parentNode?.replaceChild(d,a),a=document.getElementById("noteIcon"),a?.addEventListener("click",c)}}else r&&r.style.setProperty("display","none"),o&&o.style.setProperty("display","none"),a&&a.style.setProperty("display","none"),u&&u.style.setProperty("display","none"),s&&s.style.setProperty("display","none");if(this.navigator.rights.enableTTS){if(l){let c=function(){l?.removeEventListener("click",c),i.speak()},d=l.cloneNode(!0);l?.parentNode?.replaceChild(d,l),l=document.getElementById("speakIcon"),l?.addEventListener("click",c)}}else l&&l.style.setProperty("display","none");(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).forEach(c=>{c.icon&&(c.icon.id=c.id);let d=document.getElementById(c.id),f=this;function m(){d?.removeEventListener("click",m);function y(b){let v={className:w=>ir.indexOf(w)<0,idName:w=>ir.indexOf(w)<0},A=f.navigator.iframes[0].contentDocument;if(A)return Vi(b,A,v)}let g=f.navigator.iframes[0].contentWindow;if(g){let b=ps(g,y);if(b===void 0){let v=f.navigator.iframes[0].contentDocument;b=f.navigator.modules.annotations?.annotator?.getTemporarySelectionInfo(v)??void 0}if(b!==void 0)if(c.callback)c.callback(b.cleanText,b.range?.startContainer.parentElement);else{let v=c.highlight?.style,A=c.marker?c.marker:3;if(A===3&&f.navigator.rights.enableAnnotations||A===2&&f.navigator.rights.enableBookmarks){let w=f.navigator.iframes[0].contentDocument;if(w){let x=f.createHighlight(f.dom(w.body).getWindow(),b,c.highlight?.color,!0,A,c.icon,c.popup,v);f.options.onAfterHighlight(x,A),f.navigator.rights.enableAnnotations?f.navigator.modules.annotations?.saveAnnotation(x[0]).then(C=>{c?.note&&C.highlight&&f.navigator.modules.annotations?.api?.addCommentToAnnotation(C).then(T=>{f.navigator.emit(xe.AnnotationCommentAdded,T),f.navigator.modules.annotations?.updateAnnotation(T).then(async()=>{yn.default.log("update highlight "+T.id)})})}):f.navigator.rights.enableBookmarks&&f.navigator.modules.bookmarks?.saveAnnotation(x[0])}}}}f.callbackComplete()}if(d){let y=d.cloneNode(!0);d?.parentNode?.replaceChild(y,d),d=document.getElementById(c.id),d?.addEventListener("click",m)}})}}doHighlight(e,t){let i=this;function r(o){let a={className:l=>ir.indexOf(l)<0,idName:l=>ir.indexOf(l)<0},u=i.navigator.iframes[0].contentDocument;if(u)return Vi(o,u,a)}let s=i.navigator.iframes[0].contentWindow;if(s){let o=ps(s,r);if(o===void 0){let a=i.navigator.iframes[0].contentDocument;o=this.navigator.modules.annotations?.annotator?.getTemporarySelectionInfo(a)??void 0}if(o){if(this.options.onBeforeHighlight(o)===!0){let a;a=this.getColor(),n.isHexColor(a)&&(a=n.hexToRgbChannels(a));let u=i.navigator.iframes[0].contentDocument;if(u){let l=this.createHighlight(i.dom(u.body).getWindow(),o,a,!0,t??0);this.options.onAfterHighlight(l,t),this.navigator.rights.enableAnnotations&&t!==2?this.navigator.modules.annotations?.saveAnnotation(l[0]):this.navigator.rights.enableBookmarks&&t===2&&this.navigator.modules.bookmarks?.saveAnnotation(l[0])}}e||this.dom(this.navigator.iframes[0].contentDocument?.body).removeAllRanges()}else e||this.dom(this.navigator.iframes[0].contentDocument?.body).removeAllRanges()}}speak(){if(this.navigator.rights.enableTTS){let t=function(o){let a={className:l=>ir.indexOf(l)<0,idName:l=>ir.indexOf(l)<0},u=e.navigator.iframes[0].contentDocument;if(u)return Vi(o,u,a)},e=this,i=e.navigator.iframes[0].contentWindow;if(i){let o=ps(i,t);if(o===void 0){let a=e.navigator.iframes[0].contentDocument;o=e.navigator.modules.annotations?.annotator?.getTemporarySelectionInfo(a)??void 0}o!==void 0&&this.navigator.modules.tts?.speak(o,!0,()=>{})}let r=e.navigator.iframes[0].contentDocument;r&&e.dom(r.body).getSelection().removeAllRanges();let s=document.getElementById("highlight-toolbox");s&&(s.style.display="none"),this.selectionMenuClosed()}}stopReadAloud(){this.navigator.rights.enableTTS&&this.doneSpeaking()}callbackComplete(){this.toolboxHide();let e=this.navigator.iframes[0].contentDocument;e&&this.dom(e.body).removeAllRanges()}isOutsideViewport(e){let t=dt(document,"#iframe-wrapper"),i=t.scrollLeft,r=i+t.clientWidth,s=e.left+e.width,o=e.top+e.height,a=t.scrollTop,u=a+t.clientHeight,l=o<a,c=e.top>u,d=s<i,f=e.left>r;return l||c||d||f}isInsideViewport(e){let t=dt(document,"#iframe-wrapper"),i=t.scrollTop,r=i+t.clientHeight,s=e.top+20>=i,o=e.top<=r,a=t.scrollLeft,u=a+t.clientWidth,l=e.left+e.width,c=e.left>a,d=l<u;return s&&o&&c&&d}get visibleTextRects(){let e=this.navigator.iframes[0].contentDocument;if(e){let i=function(a,u=[]){let l=a.firstChild;for(;l;)l.nodeType===1&&i(l,u),l.nodeType===3&&l.textContent?.trim()&&u.push(l),l=l.nextSibling;return u},r=function(a){return i(a).map(l=>{let{top:c,height:d,left:f,width:m}=s(l);return{top:c,height:d,width:m,left:f,node:l,textContent:l.textContent??""}})},s=function(a){try{let u=document.createRange();u.selectNode(a);let l=u.getBoundingClientRect();return u.detach(),l}catch(u){yn.default.log("measureTextNode "+u),yn.default.log("measureTextNode "+a),yn.default.log(`${a.textContent}`)}},t=Gs(e,"body");return r(t).filter(a=>this.isInsideViewport(a))}return[]}doneSpeaking(e=!1){if(this.navigator.rights.enableTTS){this.toolboxHide();let t=this.navigator.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges(),this.navigator.modules.tts?.cancel(),e&&this.navigator.reload()}}normalizeHighlights(e){var t;return t=e.filter(function(i){return i.parentElement?i:null}),t=this.unique(t),t.sort(function(i,r){return i.offsetTop-r.offsetTop||i.offsetLeft-r.offsetLeft}),t}flattenNestedHighlights(e){let t,i=this;i.sortByDepth(e,!0);function r(){let s=!1;return e.forEach(function(o,a){let u=o.parentElement,l=u.previousSibling,c=u.nextSibling;i.isHighlight(u)&&(i.haveSameColor(u,o)?(u.replaceChild(o.firstChild,o),e[a]=u,s=!0):(o.nextSibling||(i.dom(o).insertBefore(c||u),s=!0),o.previousSibling||(i.dom(o).insertAfter(l||u),s=!0),u.hasChildNodes()||i.dom(u).remove()))}),s}do t=r();while(t)}mergeSiblingHighlights(e){let t=this;function i(r,s){return s&&s.nodeType===gl.ELEMENT_NODE&&t.haveSameColor(r,s)&&t.isHighlight(s)}e.forEach(function(r){let s=r.previousSibling,o=r.nextSibling;i(r,s)&&(t.dom(r).prepend(s.childNodes),t.dom(s).remove()),i(r,o)&&(t.dom(r).append(o.childNodes),t.dom(o).remove()),t.dom(r).normalizeTextNodes()})}setColor(e){this.options.color=e}getColor(){return this.options.color}isHighlight(e){return e&&e.nodeType===gl.ELEMENT_NODE&&e.hasAttribute(X$)}createWrapper(){let e=document.createElement("mark");return e.style.background="linear-gradient("+n.hexToRgbA(this.options.color)+", "+n.hexToRgbA(this.options.color)+")",e.className=this.options.highlightedClass,e}static isHexColor(e){return/^#([A-Fa-f0-9]{3}){1,2}$/.test(e)}static hexToRgbString(e){let t;return t=e.substring(1).split(""),t.length===3&&(t=[t[0],t[0],t[1],t[1],t[2],t[2]]),t="0x"+t.join(""),t}static hexToRgbChannels(e){let t;if(this.isHexColor(e))return t=this.hexToRgbString(e),{red:t>>16&255,green:t>>8&255,blue:t&255};throw new Error("Bad Hex")}static hexToRgbA(e){let t;if(this.isHexColor(e))return t=this.hexToRgbChannels(e),"rgba("+[t.red,t.green,t.blue].join(",")+",.5)";if(typeof e=="object"){let i=e;return"rgba("+[i.red,i.green,i.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(e,t){let i;if(this.isHexColor(e))return i=this.hexToRgbChannels(e),"rgba("+[i.red,i.green,i.blue].join(",")+","+t+")";if(typeof e=="object"){let r=e;return"rgba("+[r.red,r.green,r.blue].join(",")+","+t+")"}throw new Error("Bad Hex")}resetHighlightBoundingStyle(e){e.style.outline="none",e.style.setProperty("background-color","transparent","important")}resetHighlightAreaStyle(e,t){let i=this.navigator.iframes[0].contentWindow?.document,r=e.parentNode&&e.parentNode.nodeType===Node.ELEMENT_NODE&&e.parentNode.getAttribute?e.parentNode.getAttribute("id"):void 0;if(r){let s=di.find(o=>o.id===r);if(s){if(s.marker===3||s.marker===2)if(s.style?.hover){if(s.style?.hover)for(let u=0;u<s.style?.hover?.length;u++){let l=s.style?.hover[u];e.style.removeProperty(l.property)}let a="";if(s.style?.default)for(let u=0;u<s.style?.default?.length;u++){let l=s.style?.default[u];e.style.removeProperty(l.property),a+=`${l.property}: ${l.value} !${l.priority};`}e.setAttribute("style",`${e.getAttribute("style")}; ${a}`)}else if(s.style?.hoverClass){s.style?.hoverClass&&e.classList.remove(s.style?.hoverClass);let a="";s.style?.defaultClass&&e.classList.add(s.style?.defaultClass),e.setAttribute("style",`${e.getAttribute("style")}; ${a}`)}else if(n.isHexColor(s.color)){let a=n.hexToRgbChannels(s.color);e.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, 0)`,"important")}else e.classList.remove("hover");else if(s.marker===1||s.marker===4)if(typeof s.color=="object"){let a=s.color;e.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, 0)`,"important"),e.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, 1)`,"important")}else if(n.isHexColor(s.color)){let a=n.hexToRgbChannels(s.color);e.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, 0)`,"important"),e.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, 1)`,"important")}else e.classList.remove("hover");else if(typeof s.color=="object"){let a=s.color;e.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${ms})`,"important")}else if(n.isHexColor(s.color)){let a=n.hexToRgbChannels(s.color);e.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${ms})`,"important")}else e.classList.remove("hover");let o;if(i){let a=i.getElementById(t);a&&(o=a.querySelector(`#${s.id}`))}if(o){let a=o.getElementsByClassName(Ed);if(a.length>0){let u=a.item(0).getElementsByClassName("icon-tooltip");u.length>0&&u.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(e,t,i){for(let r of t){if(i.marker===3||i.marker===2)if(i.style?.hover){if(i.style?.default)for(let o=0;o<i.style?.default?.length;o++){let a=i.style?.default[o];r.style.removeProperty(a.property)}let s="";for(let o=0;o<i.style?.hover?.length;o++){let a=i.style?.hover[o];r.style.removeProperty(a.property),s+=`${a.property}: ${a.value} !${a.priority};`}r.setAttribute("style",`${r.getAttribute("style")}; ${s}`)}else if(i.style?.hoverClass){i.style?.defaultClass&&r.classList.remove(i.style?.defaultClass);let s="";r.classList.add(i.style?.hoverClass),r.setAttribute("style",`${r.getAttribute("style")}; ${s}`)}else if(n.isHexColor(i.color)){let s=n.hexToRgbChannels(i.color);r.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${.1})`,"important")}else r.classList.add("hover");else if(i.marker===1||i.marker===4)if(typeof i.color=="object"){let s=i.color;r.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${.1})`,"important"),r.style.setProperty("border-bottom",`2px solid rgba(${s.red}, ${s.green}, ${s.blue}, 1)`,"important")}else if(n.isHexColor(i.color)){let s=n.hexToRgbChannels(i.color);r.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${.1})`,"important"),r.style.setProperty("border-bottom",`2px solid rgba(${s.red}, ${s.green}, ${s.blue}, 1)`,"important")}else r.classList.add("hover");else if(typeof i.color=="object"){let s=i.color;r.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${Z_})`,"important")}else if(n.isHexColor(i.color)){let s=n.hexToRgbChannels(i.color);r.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${Z_})`,"important")}else r.classList.add("hover");if(i.type!==4){let o=e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER").querySelector(`#${i.id}`).getElementsByClassName(Ed);if(o.length>0){let a=o.item(0).getElementsByClassName("icon-tooltip");a.length>0&&a.item(0).style.setProperty("display","block")}}}}setAndResetSearchHighlight(e,t){let i=this.navigator.iframes[0].contentWindow?.document,r=Array.from(i.getElementById("R2_ID_SEARCH_CONTAINER").querySelectorAll(`.${cn}`));for(let s of r){let o=s,a=o.parentNode&&o.parentNode.nodeType===Node.ELEMENT_NODE&&o.parentNode.getAttribute?o.parentNode.getAttribute("id"):void 0;if(t.forEach(u=>{if(a===u.id&&u){if(typeof u.color=="object"){let d=u.color;o.style.setProperty("background-color",`rgba(${d.red}, ${d.green}, ${d.blue}, ${ms})`,"important")}else if(n.isHexColor(u.color)){let d=n.hexToRgbChannels(u.color);o.style.setProperty("background-color",`rgba(${d.red}, ${d.green}, ${d.blue}, ${ms})`,"important")}else o.classList.remove("hover");let c=i.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${u.id}`).getElementsByClassName(Ed);if(c.length>0){let d=c.item(0).getElementsByClassName("icon-tooltip");d.length>0&&d.item(0).style.removeProperty("display")}}}),a===e.id&&e){if(typeof e.color=="object"){let c=e.color;o.style.setProperty("background-color",`rgba(${c.red}, ${c.green}, ${c.blue}, ${ms})`,"important")}else if(n.isHexColor(e.color)){let c=n.hexToRgbChannels(e.color);o.style.setProperty("background-color",`rgba(${c.red}, ${c.green}, ${c.blue}, ${ms})`,"important")}else o.classList.remove("hover");let l=i.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${e.id}`).getElementsByClassName(Ed);if(l.length>0){let c=l.item(0).getElementsByClassName("icon-tooltip");c.length>0&&c.item(0).style.removeProperty("display")}}}}isIOS(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}isAndroid(){return navigator.userAgent.match(/Android/i)!=null}async processMouseEvent(e){let t=this.navigator.iframes[0].contentWindow?.document;if(!t||!(e.type==="mouseup"||e.type==="click"||e.type==="touchup")||!t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER")&&!t.getElementById("R2_ID_SEARCH_CONTAINER")&&!t.getElementById("R2_ID_PAGEBREAK_CONTAINER")&&!t.getElementById("R2_ID_READALOUD_CONTAINER")&&!t.getElementById("R2_ID_DEFINITIONS_CONTAINER"))return;let i=e.target,r=di.find(s=>s.id===e.target.parentElement?.id);if(!r||!i){for(let s in Na){let o=t.getElementById(s);if(o){let a=o.querySelectorAll(`.${xd}`);for(let l of a)this.resetHighlightBoundingStyle(l);let u=Array.from(o.querySelectorAll(`.${cn}`));for(let l of u)this.resetHighlightAreaStyle(l,s)}}return}if(i.getAttribute("data-click")&&(e.type==="mouseup"||e.type==="click"||e.type==="touchup")&&i.parentElement?.style.display!=="none"){let s={highlight:r};yn.default.log(JSON.stringify(s));let o=this,a;if(o.navigator.rights.enableAnnotations?a=await this.navigator.modules.annotations?.getAnnotation(s.highlight):o.navigator.rights.enableBookmarks&&(a=await this.navigator.modules.bookmarks?.getAnnotation(s.highlight)),s.highlight.type===0&&(this.navigator.modules.annotations?.api?.selectedAnnotation(a).then(async()=>{}),this.navigator.emit(xe.AnnotationSelected,a)),a?.id){yn.default.log("selected highlight "+a.id),o.lastSelectedHighlight=a.id;let u=document.getElementById("highlight-toolbox");if(u){let l=this.navigator.iframes[0]?.getBoundingClientRect().top??0;if(u.style.top=e.clientY+l+"px",u.style.left=e.clientX+"px",getComputedStyle(u).display==="none"){let f=function(){o.navigator.modules.annotations?.api?.addCommentToAnnotation(a).then(A=>{o.navigator.emit(xe.AnnotationCommentAdded,A),o.navigator.modules.annotations?.updateAnnotation(A).then(async()=>{yn.default.log("update highlight "+A.id),u&&(u.style.display="none"),o.selectionMenuClosed()}),u&&(u.style.display="none"),o.selectionMenuClosed(),m?.removeEventListener("click",f,!1)})},g=function(){o.navigator.rights.enableAnnotations?o.navigator.modules.annotations?.deleteSelectedHighlight(a).then(async()=>{yn.default.log("delete highlight "+a.id),u&&(u.style.display="none"),o.selectionMenuClosed()}):o.navigator.rights.enableBookmarks&&o.navigator.modules.bookmarks?.deleteSelectedHighlight(a).then(async()=>{yn.default.log("delete highlight "+a.id),u&&(u.style.display="none"),o.selectionMenuClosed()})};u.style.display="block",this.toolboxMode("edit");let c=document.getElementById("colorIcon"),d=document.getElementById("highlightIcon");c&&(c.style.display="none"),d&&(d.style.display="none");let m=document.getElementById("commentIcon"),y=document.getElementById("cloneCommentIcon");if(y){let A=y.parentElement;A&&A.removeChild(y)}if(m){m.style.display="none";let A=m.cloneNode(!0),w=m.parentElement;A.style.display="unset",A.id="cloneCommentIcon",A.addEventListener("click",f,!1),w&&w.append(A)}let b=document.getElementById("deleteIcon"),v=document.getElementById("cloneDeleteIcon");if(v){let A=v.parentElement;A&&A.removeChild(v)}if(b){b.style.display="none";let A=b.cloneNode(!0),w=b.parentElement;A.style.display="unset",A.id="cloneDeleteIcon",A.addEventListener("click",g,!1),w&&w.append(A)}}else u.style.display="none",this.selectionMenuClosed(),u.offsetWidth,u.style.display="block"}}else{let u=i.parentElement??i;u.dataset.definition&&new ll(this.navigator).showPopup(u.dataset.definition,e);let l=this.navigator.modules.definitions?.properties?.definitions?.filter(c=>c.order===Number(u?.dataset.order))[0];yn.default.log(l),this.navigator.modules.definitions?.api?.click&&(this.navigator.modules.definitions.api?.click(Rv.omit(l,"callbacks"),Rv.omit(r,"definition")),this.navigator.emit(xe.DefinitionClick,l,r))}}}async prepareContainers(e){for(let t in Na)await this.ensureHighlightsContainer(e,t)}async ensureHighlightsContainer(e,t){let i=e.document;if(!i.getElementById(t)){let r=i.createElement("div");r.setAttribute("id",t),t!=="R2_ID_GUTTER_RIGHT_CONTAINER"&&r.style.setProperty("pointer-events","none"),this.navigator.view?.layout==="fixed"&&(r.style.setProperty("position","absolute"),r.style.setProperty("top","0"),r.style.setProperty("left","0")),i.body&&i.body.append(r),(await this.layerSettings.getProperty(t))?.value===!1&&(r.style.display="none")}return i.getElementById(t)}hideAllhighlights(e){this.removeAllChildNodes(e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER")),this.removeAllChildNodes(e.getElementById("R2_ID_SEARCH_CONTAINER")),this.removeAllChildNodes(e.getElementById("R2_ID_READALOUD_CONTAINER")),this.removeAllChildNodes(e.getElementById("R2_ID_PAGEBREAK_CONTAINER")),this.removeAllChildNodes(e.getElementById("R2_ID_DEFINITIONS_CONTAINER"))}destroyAllhighlights(e){this.hideAllhighlights(e),di.splice(0,di.length)}removeAllChildNodes(e){for(;e.firstChild;)e.removeChild(e.firstChild)}destroyHighlights(e){let t=this.navigator.iframes[0].contentWindow?.document;if(t){let i;switch(e){case 2:i=t.getElementById("R2_ID_READALOUD_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 1:i=t.getElementById("R2_ID_SEARCH_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 3:i=t.getElementById("R2_ID_PAGEBREAK_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 4:i=t.getElementById("R2_ID_DEFINITIONS_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 5:i=t.getElementById("R2_ID_LINEFOCUS_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 6:i=t.getElementById("R2_ID_GUTTER_RIGHT_CONTAINER"),i&&this.removeAllChildNodes(i);break;default:i=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),i&&this.removeAllChildNodes(i),di.splice(0,di.length);break}}}destroyHighlight(e,t){if(!e)return;let i=-1;di.find((o,a)=>(i=a,o.id===t))&&i>=0&&i<di.length&&di.splice(i,1);let s=e.getElementById(t);s&&this.removeAllChildNodes(s)}createHighlight(e,t,i,r,s,o,a,u,l,c){try{let d=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,f=fs.hash(d),m=(c||"R2_HIGHLIGHT_")+f;this.destroyHighlight(e.document,m);let y=`rgb(${Ba.red}, ${Ba.green}, ${Ba.blue})`,g={color:i||y,id:m,pointerInteraction:r,selectionInfo:t,marker:s,icon:o,popup:a,style:u,type:l||0};(l===0||l===4||l===void 0)&&di.push(g);let b=this.createHighlightDom(e,g);return g.position=parseInt((b?.hasChildNodes()?b.childNodes[0]:b).style.top.replace("px","")),[g,b]}catch(d){throw"Can't create highlight: "+d}}createHighlightDom(e,t){let i=e.document,r=Gp(i,t.selectionInfo.rangeInfo);if(!r)return;for(let O in Na)this.ensureHighlightsContainer(e,O);let s=i.createElement("div");s.setAttribute("id",t.id),s.setAttribute("class",e7),s.style.setProperty("pointer-events","none"),t.pointerInteraction&&(s.setAttribute("data-click","1"),s.addEventListener("mouseover",O=>{if(O.target.classList.contains("R2_CLASS_HIGHLIGHT_AREA")){let U=O.currentTarget,G=di.find(j=>j.id===O.currentTarget.id);if(O.type==="mouseover"&&U.parentElement?.style.display!=="none"&&G){let j=Array.from(U.querySelectorAll(`.${cn}`));this.setHighlightAreaStyle(i,j,G)}}}),s.addEventListener("mouseleave",O=>{let U=O.currentTarget,G=Array.from(U.querySelectorAll(`.${cn}`));for(let z of G)this.resetHighlightAreaStyle(z,U.id);let j=U.querySelector(`.${xd}`),W=U.querySelectorAll(`.${xd}`);for(let z of W)(!j||z!==j)&&this.resetHighlightBoundingStyle(z)}));let o=this.navigator.view?.isPaginated();o?i.body.style.position="revert":i.body.style.position="relative";let a=i.body.getBoundingClientRect(),u=this.getScrollingElement(i),l=o?-u.scrollLeft:a.left,c=o?-u.scrollTop:a.top,d=1,f=!1,m=!1,g=f||m||!1;yn.default.debug(g),g=!0;let b=jp(r,g),v=3,A=2,w=3,x=0,C=24,T,k;for(let O of b){let U=i.createElement("div");U.setAttribute("class",cn),U.dataset.marker=""+t.marker;let G="";if(f&&t.marker!==3&&t.marker!==2&&t.marker!==4){let Y=t.color;n.isHexColor(Y)&&(Y=n.hexToRgbChannels(Y)),G+=`border-bottom: ${A*d}px solid rgba(${Y.red}, ${Y.green}, ${Y.blue}, ${ms}) !important`}if(t.marker===3||t.marker===2)if(t.style?.default){for(let Y=0;Y<t.style?.default?.length;Y++){let J=t.style?.default[Y];G+=`${J.property}: ${J.value} !${J.priority};`}U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; ${G}`)}else t.style?.defaultClass&&(U.classList.add(t.style?.defaultClass),U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; ${G}`));else if(t.marker===1||t.marker===4)if(typeof t.color=="object"){let Y=t.color;U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${Y.red}, ${Y.green}, ${Y.blue}, 0) !important; ${G}`),U.style.setProperty("border-bottom",`2px solid rgba(${Y.red}, ${Y.green}, ${Y.blue}, 1)`,"important")}else if(n.isHexColor(t.color)){let Y=n.hexToRgbChannels(t.color);U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${Y.red}, ${Y.green}, ${Y.blue}, 0) !important; ${G}`),U.style.setProperty("border-bottom",`2px solid rgba(${Y.red}, ${Y.green}, ${Y.blue}, 1)`,"important")}else U.setAttribute("style",`border-radius: ${v}px !important; ${G}`);else if(typeof t.color=="object"){let Y=t.color;U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${Y.red}, ${Y.green}, ${Y.blue}, ${ms}) !important; ${G}`)}else if(n.isHexColor(t.color)){let Y=n.hexToRgbChannels(t.color);U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${Y.red}, ${Y.green}, ${Y.blue}, ${ms}) !important; ${G}`)}else U.setAttribute("style",`border-radius: ${v}px !important; ${G}`);t.type===1||t.type===2||t.type===5||t.type===3?U.style.setProperty("pointer-events","none"):(U.style.setProperty("pointer-events","all"),U.style.setProperty("cursor","hand")),U.style.position="absolute",U.scale=d,U.rect={height:O.height,left:O.left-l,top:O.top-c,width:O.width},t.pointerInteraction&&(U.setAttribute("data-click","1"),U.tabIndex=0),U.style.width=`${U.rect.width*d}px`,U.style.height=`${U.rect.height*d}px`,U.style.left=`${U.rect.left*d}px`,U.style.top=`${U.rect.top*d}px`,s.append(U);let j=parseInt(U.style.top.replace("px",""));if((j<x||x===0)&&(x=j),C=parseInt(U.style.height.replace("px","")),m){let Y=i.createElement("div");Y.setAttribute("class",cn);let J=t.color;n.isHexColor(J)&&(J=n.hexToRgbChannels(J)),Y.setAttribute("style",`background-color: rgba(${J.red}, ${J.green}, ${J.blue}, ${ms}) !important;`),t.type===1||t.type===2||t.type===5||t.type===3?Y.style.setProperty("pointer-events","none"):(Y.style.setProperty("pointer-events","all"),Y.style.setProperty("cursor","hand")),Y.style.position="absolute",Y.scale=d,Y.rect={height:O.height,left:O.left-l,top:O.top-c,width:O.width},Y.style.width=`${Y.rect.width*d}px`,Y.style.height=`${w*d}px`,Y.style.left=`${Y.rect.left*d}px`,Y.style.top=`${(Y.rect.top+Y.rect.height/2-w/2)*d}px`,s.append(Y)}let W=this.navigator.iframes[0].contentWindow?.innerWidth,z=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-count")),$=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-width")),te=parseInt(getComputedStyle(i.body).getPropertyValue("padding-left")),le=W/(z||1);le<$&&(le=W),o||(le=parseInt(getComputedStyle(i.body).width.replace("px","")));let ce=this.navigator.settings.fontSize/100,pe=20*ce;ce<=1&&(pe=-60);let se=0*ce;ce<=1&&(se=-60),T=Math.floor(O.left/le)*le+le-(C<40?40:C)+se,k=Math.floor(O.left/le)*le+(C<40?40:C)-pe;let de=parseInt(this.navigator.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));de>=2&&(k=k+te/z,T=T-te/z),o||(T=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px","")),k=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px",""))-le,de>=2&&(k=k+te/2,T=T-te/2))}let _=r.getBoundingClientRect(),R=i.createElement("div");R.setAttribute("class",xd),R.style.setProperty("pointer-events","none"),R.style.position="absolute",R.scale=d,R.rect={height:_.height,left:_.left-l,top:_.top-c,width:_.width},R.style.width=`${R.rect.width*d}px`,R.style.height=`${R.rect.height*d}px`,R.style.left=`${R.rect.left*d}px`,R.style.top=`${R.rect.top*d}px`,s.append(R);let L=i.createElement("div");if(L.setAttribute("class",Ed),t.icon?.position==="left")L.setAttribute("style",`position: absolute;top:${x}px;left:${k+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${C}px; width:${C}px;`);else if(t.icon?.position==="inline")L.setAttribute("style",`position: absolute;top:${x-C/2}px;left:${parseInt(R.style.left.replace("px",""))+parseInt(R.style.width.replace("px",""))-C/2}px;height:${C}px; width:${C}px;`);else if(t.icon?.position==="center"){let U=C/3*2;L.setAttribute("style",`position: absolute;top:${x}px;left:${parseInt(R.style.left.replace("px",""))+parseInt(R.style.width.replace("px",""))-U}px;height:${C}px; width:${C}px;`)}else t.note&&t.marker!==3&&t.marker!==2&&t.marker!==4&&t.marker!==0&&t.marker!==1?L.setAttribute("style",`position: absolute;top:${x-C/2}px;left:${parseInt(R.style.left.replace("px",""))+parseInt(R.style.width.replace("px",""))-C/2}px;height:${C}px; width:${C}px;`):t.note&&t.marker===4||t.marker===0||t.marker===1?L.setAttribute("style",`position: absolute;top:${x}px;left:${T+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${C}px; width:${C}px;`):L.setAttribute("style",`position: absolute;top:${x}px;left:${T+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${C}px; width:${C}px;`);if(t.marker===3||t.marker===2)t.icon?.class?(L.classList.add(t.icon?.class),L.id=t.icon?.id):t.icon?.svgPath?L.innerHTML=fl(`${t.icon?.id}`,`${t.icon?.title}`,`${t.icon?.svgPath}`,"icon open",C,`${t.icon?.color} !important`):t.icon?.title&&(L.innerHTML=t.icon?.title);else if(t.note){let O=t.color;n.isHexColor(O)&&(O=n.hexToRgbChannels(O)),t.marker===4||t.marker===0||t.marker===1?L.innerHTML=fl("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",C/2,`rgba(${O.red}, ${O.green}, ${O.blue}, 1) !important`):L.innerHTML=fl("note-icon","Note",'<rect fill="none" height="24" width="24"/><path d="M19,5v9l-5,0l0,5H5V5H19 M19,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h10l6-6V5C21,3.9,20.1,3,19,3z M12,14H7v-2h5V14z M17,10H7V8h10V10z"/>',"icon open",C,`rgba(${O.red}, ${O.green}, ${O.blue}, 1) !important`)}t.type===1||t.type===2||t.type===5||t.type===3?L.style.setProperty("pointer-events","none"):(L.style.setProperty("pointer-events","all"),L.style.setProperty("cursor","hand"));let M=this;if(t.type!==3&&t.type!==4&&L.addEventListener("click",async function(O){let U;M.navigator.rights.enableAnnotations?(U=await M.navigator.modules.annotations?.getAnnotationByID(t.id),M.navigator.modules.annotations?.api?.selectedAnnotation(U).then(async()=>{}),M.navigator.emit(xe.AnnotationSelected,U)):M.navigator.rights.enableBookmarks&&(U=await M.navigator.modules.bookmarks?.getAnnotationByID(t.id)),yn.default.log("selected highlight "+U.id),M.lastSelectedHighlight=U.id;let G=document.getElementById("highlight-toolbox");if(G){let W=M.navigator.iframes[0]?.getBoundingClientRect().top??0;if(G.style.top=O.clientY+W+"px",G.style.left=O.clientX+"px",getComputedStyle(G).display==="none"){let ce=function(){M.navigator.rights.enableAnnotations?M.navigator.modules.annotations?.deleteSelectedHighlight(U).then(async()=>{yn.default.log("delete highlight "+U.id),G.style.display="none",M.selectionMenuClosed()}):M.navigator.rights.enableBookmarks&&M.navigator.modules.bookmarks?.deleteSelectedHighlight(U).then(async()=>{yn.default.log("delete highlight "+U.id),G.style.display="none",M.selectionMenuClosed()})};G.style.display="block",M.toolboxMode("edit");let z=document.getElementById("colorIcon"),$=document.getElementById("highlightIcon");z&&(z.style.display="none"),$&&($.style.display="none");let te=document.getElementById("commentIcon"),le=document.getElementById("cloneCommentIcon");if(le){let de=le.parentElement;de&&de.removeChild(le)}te&&(te.style.display="none");let pe=document.getElementById("deleteIcon"),se=document.getElementById("cloneDeleteIcon");if(se){let de=se.parentElement;de&&de.removeChild(se)}if(pe){pe.style.display="none";let de=pe.cloneNode(!0),Y=pe.parentElement;de.style.display="unset",de.id="cloneDeleteIcon",de.addEventListener("click",ce,!1),Y&&Y.append(de)}}else G.style.display="none",M.selectionMenuClosed(),G.offsetWidth,G.style.display="block"}let j=Array.from(s.querySelectorAll(`.${cn}`));M.setHighlightAreaStyle(i,j,t)}),t.note){let O=document.createElement("span");O.innerHTML=t.note,O.className="icon-tooltip",t.marker===3||t.marker===2?(t.popup?.background&&O.style.setProperty("background",t.popup.background),t.popup?.textColor&&O.style.setProperty("color",t.popup.textColor),t.popup?.class&&O.classList.add(t.popup.class)):(O.style.setProperty("background","lightyellow"),O.style.setProperty("color","black"))}switch((t.note||t.marker===3||t.marker===2)&&s.append(L),t.type){case 1:i.getElementById("R2_ID_SEARCH_CONTAINER").append(s);break;case 2:i.getElementById("R2_ID_READALOUD_CONTAINER").append(s);break;case 3:i.getElementById("R2_ID_PAGEBREAK_CONTAINER").append(s);break;case 4:i.getElementById("R2_ID_DEFINITIONS_CONTAINER").append(s);break;default:i.getElementById("R2_ID_HIGHLIGHTS_CONTAINER").append(s);break}return s}addSelectionMenuItem(e){(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).push(e)}};hi();mn();Er();Ad();I();I();var en=[];for(let n=0;n<256;++n)en.push((n+256).toString(16).slice(1));function i7(n,e=0){return(en[n[e+0]]+en[n[e+1]]+en[n[e+2]]+en[n[e+3]]+"-"+en[n[e+4]]+en[n[e+5]]+"-"+en[n[e+6]]+en[n[e+7]]+"-"+en[n[e+8]]+en[n[e+9]]+"-"+en[n[e+10]]+en[n[e+11]]+en[n[e+12]]+en[n[e+13]]+en[n[e+14]]+en[n[e+15]]).toLowerCase()}I();var Lv,Z$=new Uint8Array(16);function Mv(){if(!Lv){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Lv=crypto.getRandomValues.bind(crypto)}return Lv(Z$)}I();I();var eQ=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ov={randomUUID:eQ};function tQ(n,e,t){if(Ov.randomUUID&&!e&&!n)return Ov.randomUUID();n=n||{};let i=n.random??n.rng?.()??Mv();if(i.length<16)throw new Error("Random bytes length must be >= 16");if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){if(t=t||0,t<0||t+16>e.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let r=0;r<16;++r)e[t+r]=i[r];return e}return i7(i)}var bl=tQ;I();var iQ=$e(jt());var zo={className:n=>!0,idName:n=>!0,tagName:n=>!0};var s7=$e(zp()),Cr=$e(jt());I();hi();Xt();tr();var n7=$e(jt());var Vp=class{constructor(e,t,i){this.name=we.Consumption;this.hostType=nt.Epub;this.rightsKey=vt.Consumption;this.currSeconds=0;this.publication=e,this.properties=t,this.api=i}attach(e){this.host=e}static async create(e){let t=new this(e.publication,e,e.api);return await t.start(),t}async start(){this.startResearchSession()}async stop(){n7.default.log("Consumption module stop"),this.endResearchSession()}initialize(e){let t=e.contentWindow;if(t){let i=this;t.onload=function(){i.resetTimer()},t.onmousemove=function(){i.resetTimer()},t.onmousedown=function(){i.resetTimer()},t.ontouchstart=function(){i.resetTimer()},t.onclick=function(){i.resetTimer()},t.onkeypress=function(){i.resetTimer()}}}trackAction(e,t){this.api?.actionTracked(e,t),this.host.emit(xe.ActionTracked,{locator:e,action:t})}startReadingSession(e){if(this.firstReadingLocator&&this.lastReadingLocator){let t=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,i=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:i,progress:Math.round(t*100)})}this.firstReadingLocator=e,this.startReadingTimer=new Date}continueReadingSession(e){this.properties.enableTrackingSession&&(this.startResearchTimer===void 0&&this.startResearchSession(),(this.lastReadingLocator===void 0||this.lastReadingLocator.locations.totalProgression<e.locations.totalProgression)&&(this.lastReadingLocator=e),this.firstReadingLocator===void 0&&(this.firstReadingLocator=e),this.startReadingTimer===void 0&&(this.startReadingTimer=new Date))}startResearchSession(){if(this.properties.enableTrackingSession){this.startResearchTimer=new Date,this.readingSessions=[],clearInterval(this.readingSessionsInterval);let e=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.researchSessionId=this.api?.startResearchSession(this.readingSessions,Math.round(e));let t=this;this.readingSessionsInterval=setInterval(function(){t.updateResearchSession()},this.properties.updateSessionInterval*1e3)}}updateResearchSession(){if(this.properties.enableTrackingSession){let e=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.api?.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(e))}}endResearchSession(){if(this.properties.enableTrackingSession){if(this.firstReadingLocator&&this.lastReadingLocator){let t=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,i=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:i,progress:Math.round(t*100)})}let e=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.api?.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(e)),this.api?.endResearchSession(this.researchSessionId,this.readingSessions,Math.round(e)),this.researchSessionId=void 0,this.readingSessions=[],this.startResearchTimer=void 0,clearInterval(this.readingSessionsInterval),clearInterval(this.timer)}}startIdleTimer(){this.currSeconds++,this.currSeconds===this.properties.idleTimeout&&(this.api?.idleSince(this.currSeconds),this.host.emit(xe.IdleSince,this.currSeconds),this.startResearchTimer!==void 0?this.updateResearchSession():this.startResearchSession()),this.currSeconds===this.properties.idleTimeout+this.properties.responseTimeout&&this.endResearchSession()}resetTimer(){clearInterval(this.timer),this.currSeconds=0;let e=this;this.timer=setInterval(function(){e.startIdleTimer()},1e3)}};tr();var Kp=class n{constructor(e,t,i,r,s,o,a){this.name=we.Annotations;this.hostType=nt.Epub;this.rightsKey=vt.Annotations;this.hide=fe(document,"#menu-button-hide");this.show=fe(document,"#menu-button-show");this.annotator=e,this.publication=t,this.headerMenu=a,this.initialAnnotations=i,this.highlighter=s,this.properties=r,this.api=o}attach(e){this.host=e}static async create(e){let t=new this(e.annotator,e.publication,e.initialAnnotations||null,e,e.highlighter,e.api,e.headerMenu);return await t.start(),t}async stop(){Cr.default.log("Annotation module stop")}async start(){if(this.headerMenu&&(this.highlightsView=fe(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var e=this.initialAnnotations.highlights||null;e&&this.annotator?.initAnnotations(e)}setTimeout(()=>{this.properties?.hideLayer?this.host.hideLayer("highlights"):this.host.showLayer("highlights")},10)}hideAnnotationLayer(){let e=this.host.iframes[0].contentDocument;if(e){let t=fe(e,"#R2_ID_HIGHLIGHTS_CONTAINER");t&&(t.style.display="none")}this.show&&this.hide&&(this.show.style.display="block",this.hide.style.display="none")}showAnnotationLayer(){let e=this.host.iframes[0].contentDocument;if(e){let t=fe(e,"#R2_ID_HIGHLIGHTS_CONTAINER");t&&(t.style.display="block")}this.show&&this.hide&&(this.show.style.display="none",this.hide.style.display="block")}async handleResize(){setTimeout(async()=>{await this.drawHighlights(),await this.showHighlights()},200)}initialize(e){return new Promise(async t=>{await document.fonts.ready,this.host.rights.enableAnnotations&&setTimeout(()=>{this.drawHighlights(),this.showHighlights(),ee(e.contentDocument?.body,"click",this.click.bind(this))},300),t(null)})}click(e){if(this.activeAnnotationMarkerId){let t=this.highlighter?.properties?.selectionMenuItems?.filter(i=>i.id===this.activeAnnotationMarkerId);if(t&&t?.length>0){let i=s7.cloneDeep(t[0]);i.marker=3,this.activeAnnotationMarkerPosition&&i.icon&&(i.icon.position=this.activeAnnotationMarkerPosition),i.highlight?.style&&(i.highlight.style.default=void 0,i.highlight.style.hover=void 0);let r=this.host.iframes[0].contentDocument;if(r){let l=function(d){try{let f=u.host.iframes[0].contentDocument;return f?Vi(d,f,zo):""}catch(f){return Cr.default.log("uniqueCssSelector:"),Cr.default.error(f),""}},s=this.highlighter?.dom(r.body).getSelection(),o=s.getRangeAt(0),a=s.anchorNode;o.setStart(a,o.startOffset),o.setEnd(a,o.endOffset+1),s.removeAllRanges(),s.addRange(o);let u=this,c=Qs(o,l);if(s.removeAllRanges(),c){let d={rangeInfo:c},f=this.host.highlighter?.createHighlight(this.host.highlighter?.dom(r.body).getWindow(),d,i.highlight?.color,!0,2,i.icon,i.popup,i.highlight?.style);f&&this.saveAnnotation(f[0]).then(m=>{Cr.default.log("saved bookmark "+m.id)})}r.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(e){Cr.default.log("still need to scroll to "+e);var t=await this.annotator?.getAnnotationElement(e,this.host.iframes[0].contentWindow);t?.scrollIntoView({block:"center",behavior:"smooth"})}async updateLocalHighlight(e){if(this.annotator){let t=await this.annotator.deleteAnnotation(e.id),i=await this.addAnnotation(e);return Cr.default.log("Highlight deleted "+JSON.stringify(t)),Cr.default.log("Highlight added "+JSON.stringify(i)),await this.showHighlights(),await this.drawHighlights(),i}else return new Promise(t=>t(null))}async deleteLocalHighlight(e){if(this.annotator){var t=await this.annotator.deleteAnnotation(e);return Cr.default.log("Highlight deleted "+JSON.stringify(t)),await this.showHighlights(),await this.drawHighlights(),t}else return new Promise(i=>i(null))}async deleteAnnotation(e){await this.deleteLocalHighlight(e.id),this.host.emit(xe.AnnotationDeleted,e)}async addAnnotation(e){await this.annotator?.saveAnnotation(e),this.host.emit(xe.AnnotationCreated,e),await this.showHighlights(),await this.drawHighlights()}async deleteHighlight(e){this.api?.deleteAnnotation?this.api?.deleteAnnotation(e).then(async()=>{this.deleteLocalHighlight(e.id),this.host.emit(xe.AnnotationDeleted,e)}):(this.deleteLocalHighlight(e.id),this.host.emit(xe.AnnotationDeleted,e))}async deleteSelectedHighlight(e){this.api?.deleteAnnotation?this.api.deleteAnnotation(e).then(async()=>{this.deleteLocalHighlight(e.id),this.host.emit(xe.AnnotationDeleted,e)}):(this.deleteLocalHighlight(e.id),this.host.emit(xe.AnnotationDeleted,e))}async updateAnnotation(e){this.api?.updateAnnotation?this.api.updateAnnotation(e).then(async()=>{this.updateLocalHighlight(e),this.host.emit(xe.AnnotationUpdated,e)}):(this.updateLocalHighlight(e),this.host.emit(xe.AnnotationUpdated,e))}async saveAnnotation(e){if(this.annotator){var t=this.publication.getTOCItem(this.host.currentChapterLink.href);this.host.currentTocUrl&&(t=this.publication.getTOCItem(this.host.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.host.currentChapterLink.href));let i=this.host.view?.getCurrentPosition(),r=this.host.iframes[0].contentDocument;if(r){let s=Gs(r,"body"),o=e.position?e.position/s.scrollHeight:i,a=bl(),u;if(t){let l=t.href;if(l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),this.host.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let c=this.publication.positionsByHref(this.publication.getRelativeHref(this.host.currentChapterLink.href)),d=Math.ceil((o??0)*(c.length-1));u={...c[d],id:a,href:l,created:new Date,title:this.host.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}else u={id:a,href:l,locations:{progression:o},created:new Date,type:this.host.currentChapterLink.type,title:this.host.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}if(u)if(this.host.getModule(we.Consumption)?.trackAction(u,"HighlightCreated"),this.api?.addAnnotation)try{let l=await this.api.addAnnotation(u),c=await this.annotator.saveAnnotation(l);return this.host.emit(xe.AnnotationCreated,c),await this.showHighlights(),await this.drawHighlights(),new Promise(d=>d(c))}catch{await this.showHighlights(),await this.drawHighlights()}else{let l=await this.annotator.saveAnnotation(u);return this.host.emit(xe.AnnotationCreated,l),await this.showHighlights(),await this.drawHighlights(),new Promise(c=>c(l))}}}return new Promise(i=>i(null))}getAnnotations(){let e=[];return this.annotator&&(e=this.annotator.getAnnotations()),e}showHighlights(){let e=[];this.annotator&&(e=this.annotator.getAnnotations(),e&&(e=e.filter(t=>t.highlight.marker!==2),e.forEach(t=>{di.push(t.highlight)}))),this.highlightsView&&this.createTree(1,e,this.highlightsView)}async drawHighlights(){if(this.host.rights.enableAnnotations&&this.highlighter){if(this.api){let t=[],i=this.host.currentLocator();if(this.annotator&&i?.href&&(t=this.annotator.getAnnotationsByChapter(i.href)),this.highlighter&&t&&this.host.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(0);for(let r of t){di.push(r.highlight);let s=r,o=this.host.currentChapterLink.href;var e=this.publication.getTOCItem(o);if(this.host.currentTocUrl!==void 0&&(e=this.publication.getTOCItem(this.host.currentTocUrl)),e===null&&(e=this.publication.getTOCItemAbsolute(this.host.currentChapterLink.href)),e){let a=e.href;a.indexOf("#")>0&&(a=a.slice(0,a.indexOf("#"))),s.href===a&&(await this.highlighter.createHighlightDom(this.host.iframes[0].contentWindow,r.highlight),setTimeout(async()=>{if(s.highlight?.marker===1){let l='<div class="comment" style="top: '+await this.annotator?.getAnnotationPosition(r.id,this.host.iframes[0].contentWindow)+'px;width:20px"></div>',c=document.createElement("div");c.innerHTML=l;let d=c.childNodes[0],f=document.createElement("i");f.innerHTML="sticky_note_2",f.className="material-icons",f.style.color=s.highlight.color,d.appendChild(f),ee(c,"click",m=>{m.preventDefault(),m.stopPropagation(),this.scrollToHighlight(s.id)})}},100))}}}}else{let t=[],i=this.host.currentLocator();if(this.annotator&&i?.href&&(t=this.annotator.getAnnotationsByChapter(i.href)),this.highlighter&&t&&this.host.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(0);for(let r of t){di.push(r.highlight);let s=r,o=this.host.currentChapterLink.href,a=this.publication.getTOCItem(o);if(this.host.currentTocUrl&&(a=this.publication.getTOCItem(this.host.currentTocUrl)),a===null&&(a=this.publication.getTOCItemAbsolute(this.host.currentChapterLink.href)),a){let u=a.href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),s.href===u&&(await this.highlighter.createHighlightDom(this.host.iframes[0].contentWindow,r.highlight),setTimeout(async()=>{if(s.highlight?.marker===1){let c='<div class="comment" style="top: '+await this.annotator?.getAnnotationPosition(r.id,this.host.iframes[0].contentWindow)+"px;background: "+s.highlight?.color+';width:20px"></div>',d=document.createElement("div");d.innerHTML=c,d.childNodes[0].innerHTML=jr.note,ee(d,"click",f=>{f.preventDefault(),f.stopPropagation(),this.scrollToHighlight(s.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){let e=this.host.iframes[0].contentDocument;if(e&&(this.commentGutter=e.getElementById("R2_ID_GUTTER_RIGHT_CONTAINER"),this.host.view?.isScrollMode()&&this.properties?.enableComments?this.commentGutter?.style.removeProperty("display"):this.commentGutter?.style.setProperty("display","none"),this.commentGutter&&this.host.view?.isScrollMode()&&this.properties?.enableComments)){this.commentGutter.innerHTML="";let t=[];this.annotator&&(t=this.annotator.getAnnotationsByChapter(this.host.currentLocator().href),t&&(t=t.filter(i=>i.highlight?.note?.length>0),t=this.syncPosition(t),t=this.reposition(t),t.forEach(i=>{let r=document.createElement("i");r.innerHTML="sticky_note_2",r.className="material-icons",r.style.color=i.highlight.color;let s=e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),o,a;s&&(o=s.querySelector(`#${i.highlight.id}`)),a=o.getElementsByClassName(cn)[0];let l=parseInt(a.style.height.replace("px","")),c=i.highlight.position,d=e.createElement("div");d.setAttribute("style",`position: absolute;top:${c}px;display: flex;max-width: 250px !important;height:${l}px;width: 200px;align-items: center;`);let f=e.createElement("div");d.appendChild(f);let m=i.highlight.color;$t.isHexColor(m)&&(m=$t.hexToRgbChannels(m)),d.innerHTML=fl("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="8"/>',"icon open",10,`rgba(${m.red}, ${m.green}, ${m.blue}, 1) !important`);let y=e.createElement("div");y.innerHTML=i.highlight?.note,y.setAttribute("style",`height:${l}px;overflow: hidden;padding-left: 5px;`),d.appendChild(y),ee(d,"click",g=>{g.preventDefault(),g.stopPropagation(),this.scrollToHighlight(i.highlight.id)}),this.commentGutter?.appendChild(d)})))}}createTree(e,t,i){if(t){let r=this,s=this.publication.readingOrder;if(s.length){let o=(a,u)=>{let l=document.createElement("ul");l.className="sidenav-annotations";for(let c of u){let d=document.createElement("li"),f=document.createElement("a"),m=document.createElement("span");if(f.tabIndex=-1,f.className="chapter-link",c.href){let g=this.publication.getAbsoluteHref(c.href),b=this.publication.getTOCItemAbsolute(g);f.href=g,f.innerHTML=b?.title||"",d.appendChild(f)}else m.innerHTML=c.title||"",m.className="chapter-title",d.appendChild(m);ee(f,"click",g=>{g.preventDefault(),g.stopPropagation();let b={href:f.href,locations:{progression:0},type:c.type,title:f.title};this.host.stopReadAloud(),this.host.navigate(b)});let y=document.createElement("ol");t.forEach(function(g){let b=c.href.indexOf("#")!==-1?c.href.slice(0,c.href.indexOf("#")):c.href;if(c.href&&g.href.endsWith(b)){let v=document.createElement("li");v.className="annotation-item";let A=document.createElement("a");if(A.setAttribute("href",g.href),e===1){A.className="highlight-link";let x=document.createElement("span"),C=document.createElement("span");if(x.className="title",C.innerHTML=g.highlight.selectionInfo.cleanText,g.highlight?.marker===1)if(typeof g.highlight?.color=="object"){let _=g.highlight?.color;_&&C.style.setProperty("border-bottom",`2px solid ${$t.hexToRgbA(_)}`,"important")}else C.style.setProperty("border-bottom",`2px solid ${g.highlight?.color}`,"important");else if(typeof g.highlight?.color=="object"){let _=g.highlight?.color;_&&(C.style.backgroundColor=$t.hexToRgbA(_))}else{let _=g.highlight?.color;_&&(C.style.backgroundColor=_)}x.appendChild(C),A.appendChild(x);let T=document.createElement("span"),k=Math.round((g.locations.progression??0)*100)+"% through resource";T.className="subtitle",T.innerHTML=k,A.appendChild(T)}let w=document.createElement("span");if(w.className="timestamp",w.innerHTML=n.readableTimestamp(g.created),A.appendChild(w),ee(A,"click",x=>{x.preventDefault(),x.stopPropagation(),r.handleAnnotationLinkClick(x,g)}),v.appendChild(A),r.host.sideNavExpanded){let x=document.createElement("button");x.className="delete",x.innerHTML=jr.delete,ee(x,"click",C=>{C.preventDefault(),C.stopPropagation(),r.handleAnnotationLinkDeleteClick(e,C,g)}),v.appendChild(x)}y.appendChild(v)}}),y.children.length>0&&(l.appendChild(d),l.appendChild(y)),l.children.length>0&&a.appendChild(l),c.children?.items&&c.children.items.length>0&&o(a,c.children.items)}};i.innerHTML="",o(i,s)}}}handleAnnotationLinkClick(e,t){t?(t.href=this.publication.getAbsoluteHref(t.href),this.host.stopReadAloud(),this.host.navigate(t)):Cr.default.log("annotation data missing: ",e)}handleAnnotationLinkDeleteClick(e,t,i){Cr.default.log("annotation data locator: ",i),i?e===1&&this.deleteHighlight(i):Cr.default.log("annotation data missing: ",t)}static readableTimestamp(e){let t=new Date(e);return t.toDateString()+" "+t.toLocaleTimeString()}async getAnnotation(e){return this.annotator?.getAnnotation(e)}async getAnnotationByID(e){return this.annotator?.getAnnotationByID(e)}syncPosition(e){let t=this.host.iframes[0].contentDocument,i=(r,s)=>{let o=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),a,u;o&&(a=o.querySelector(`#${s.highlight.id}`)),u=a.getElementsByClassName(cn)[0];let c=parseInt(u.style.top.replace("px","")),d={...s,highlight:{...s.highlight,position:c}};return[...r,d]};return e.reduce(i,[])}reposition(e){let t=this.host.iframes[0].contentDocument,i=(r,s,o)=>{let a=e[0],u=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),l,c;u&&(l=u.querySelector(`#${a.highlight.id}`)),c=l.getElementsByClassName(cn)[0];let f=parseInt(c.style.height.replace("px","")),m=s.highlight.position,y=r[o-1]&&r[o-1].highlight.position,b=o===0?0:y+f+0,v=b>m?b:m,A={...s,highlight:{...s.highlight,position:v}};return[...r,A]};return e.sort(function(r,s){return r.highlight.position-s.highlight.position}).reduce(i,[])}getAll(){return this.getAnnotations()}clear(){if(!this.annotator)return;let e=this.annotator.getAnnotations();if(e)for(let t of e)this.deleteAnnotation(t)}};I();ci();Xt();hi();mn();Ad();Er();var xr=$e(jt());tr();var Yp=class n{constructor(e,t,i,r,s,o){this.name=we.Bookmarks;this.hostType=nt.Epub;this.rightsKey=vt.Bookmarks;this.annotator=e,this.publication=t,this.headerMenu=o,this.initialAnnotations=r,this.properties=i,this.api=s}attach(e){this.host=e}static async create(e){let t=new this(e.annotator,e.publication,e,e.initialAnnotations,e.api,e.headerMenu);return await t.start(),new Promise(i=>i(t))}stop(){xr.default.log("Bookmark module stop")}async start(){if(this.headerMenu&&(this.bookmarksView=fe(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=fe(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let e=fe(this.headerMenu,"#menu-button-bookmark");e&&e.parentElement?.style.removeProperty("display"),e&&ee(e,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let e=this.initialAnnotations.bookmarks||null;e&&this.annotator?.initBookmarks(e)}}async handleResize(){setTimeout(async()=>{await this.drawBookmarks(),await this.showBookmarks(),setTimeout(()=>{this.properties.hideLayer?this.host.hideLayer("highlights"):this.host.showLayer("highlights")},10)},100)}initialize(){return new Promise(async e=>{await document.fonts.ready,this.host.rights.enableBookmarks&&setTimeout(()=>{this.drawBookmarks(),this.showBookmarks()},300),e(null)})}async deleteBookmark(e){if(this.annotator)if(this.api?.deleteBookmark){await this.api?.deleteBookmark(e);let t=await this.annotator.deleteBookmark(e);return xr.default.log("Bookmark deleted "+JSON.stringify(t)),this.host.emit(xe.BookmarkDeleted,e),await this.showBookmarks(),await this.drawBookmarks(),t}else{let t=await this.annotator.deleteBookmark(e);return xr.default.log("Bookmark deleted "+JSON.stringify(t)),this.host.emit(xe.BookmarkDeleted,e),await this.showBookmarks(),await this.drawBookmarks(),t}else return new Promise(t=>t(null))}async saveBookmarkPlus(){await this.addBookmarkPlus()}async saveBookmark(){if(this.annotator){var e=this.publication.getTOCItem(this.host.currentChapterLink.href);if(this.host.currentTocUrl&&(e=this.publication.getTOCItem(this.host.currentTocUrl)),e===void 0&&(e=this.publication.getTOCItemAbsolute(this.host.currentChapterLink.href)),e){let t=e.href;t.indexOf("#")>0&&(t=t.slice(0,t.indexOf("#")));let i=this.host.view?.getCurrentPosition(),r=bl(),s;if(this.host.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let o=this.publication.positionsByHref(this.publication.getRelativeHref(this.host.currentChapterLink.href)),a=Math.ceil((i??0)*(o.length-1));s={...o[a],id:r,href:t,created:new Date,title:this.host.currentChapterLink.title}}else s={id:r,href:t,locations:{progression:i},created:new Date,type:this.host.currentChapterLink.type,title:this.host.currentChapterLink.title};if(!this.annotator.locatorExists(s,0))if(this.host.getModule(we.Consumption)?.trackAction(s,"BookmarkCreated"),this.api?.addBookmark){let o=await this.api.addBookmark(s);o&&(s=o),xr.default.log(s);let a=this.annotator.saveBookmark(s);return xr.default.log("Bookmark added "+JSON.stringify(a)),this.host.emit(xe.BookmarkCreated,s),this.showBookmarks(),await this.drawBookmarks(),a}else{let o=this.annotator.saveBookmark(s);return xr.default.log("Bookmark added "+JSON.stringify(o)),this.host.emit(xe.BookmarkCreated,s),this.showBookmarks(),await this.drawBookmarks(),o}}}}async addBookmarkPlus(){let e=this,t=this.host.highlighter?.visibleTextRects[0],i=this.host.iframes[0].contentDocument;if(i){let a=this.host.highlighter?.dom(i.body).getWindow().document.createRange(),u=this.host.highlighter?.dom(this.host.iframes[0].contentDocument?.body).getSelection();u.removeAllRanges(),t&&a.selectNodeContents(t.node),u.addRange(a);let l=jp(a,!1),c=0;for(let d of l){if(!this.host.highlighter?.isOutsideViewport(d)){let f=u.focusNode,m=u.focusOffset;u.collapse(u.anchorNode,u.anchorOffset);for(let v=0;v<c;v++)u.modify("move","forward","line");u.extend(f,m);let y=u.focusNode,g=u.focusNode.length;u.collapse(u.anchorNode,u.anchorOffset);let b=g;u.anchorOffset>g?b=g:b=u.anchorOffset+1,u.modify("move","forward","character"),u.modify("move","backward","word"),u.extend(y,b),u.modify("extend","backward","character"),u.modify("extend","forward","word");break}c++}}function r(a){let u={},l=e.host.iframes[0].contentDocument;if(l)return Vi(a,e.host.highlighter?.dom(l.body).getDocument(),u)}let s=this.host.iframes[0].contentWindow,o={id:"bookmarkIcon",marker:2,icon:{id:"bookmarkIcon",title:"Bookmark",svgPath:'<path d="M0 0h24v24H0V0z" fill="none"/><path d="M17 3H7c-1.1 0-2 .9-2 2v16l7-3 7 3V5c0-1.1-.9-2-2-2z"/>',color:"#000000",position:"left"},popup:{background:"#000000",textColor:"#ffffff"},highlight:{color:"#000000",style:{default:[{property:"border-bottom",value:"0px dashed #000000",priority:"important"}]}}};if(s!==null){let a=ps(s,r);if(a===void 0){let l=e.host.iframes[0].contentDocument;a=this.host.getModule(we.Annotations)?.annotator?.getTemporarySelectionInfo(l)??void 0}let u=e.host.iframes[0].contentDocument;if(a&&u){let l=this.host.highlighter?.createHighlight(this.host.highlighter?.dom(u.body).getWindow(),a,o.highlight?.color,!0,2,o.icon,o.popup,o.highlight?.style);if(this.host.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),l)return this.saveAnnotation(l[0]).then(c=>{xr.default.log("saved bookmark "+c?.id)})}}}async saveAnnotation(e){if(this.annotator){var t=this.publication.getTOCItem(this.host.currentChapterLink.href);this.host.currentTocUrl&&(t=this.publication.getTOCItem(this.host.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.host.currentChapterLink.href));let i=this.host.view?.getCurrentPosition(),r=this.host.iframes[0].contentDocument;if(r){let s=Gs(r,"body"),o=e.position?e.position/s.scrollHeight:i,a=bl(),u;if(t){let l=t.href;if(l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),this.host.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let c=this.publication.positionsByHref(this.publication.getRelativeHref(this.host.currentChapterLink.href)),d=Math.ceil((o??0)*(c.length-1));u={...c[d],id:a,href:l,created:new Date,title:this.host.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}else u={id:a,href:l,locations:{progression:o},created:new Date,type:this.host.currentChapterLink.type,title:this.host.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}if(u)if(this.host.getModule(we.Consumption)?.trackAction(u,"BookmarkCreated"),this.api?.addBookmark){let l=await this.api.addBookmark(u),c=await this.annotator.saveAnnotation(l);return this.host.emit(xe.BookmarkCreated,u),await this.showBookmarks(),await this.drawBookmarks(),new Promise(d=>d(c))}else{let l=await this.annotator.saveAnnotation(u);return this.host.emit(xe.BookmarkCreated,u),await this.showBookmarks(),await this.drawBookmarks(),new Promise(c=>c(l))}}}return new Promise(i=>i(void 0))}getBookmarks(){let e=[];return this.annotator&&(e=this.annotator.getBookmarks()),e}showBookmarks(){let e=[];this.annotator&&(e=this.annotator.getBookmarks());let t=[];this.annotator&&(t=this.annotator.getAnnotations(),t&&(t=t.filter(i=>i.highlight.marker===2),e?e.push.apply(e,t):e=t)),this.bookmarksView&&this.createTree(0,e,this.bookmarksView)}async drawBookmarks(){if(this.host.rights.enableBookmarks&&this.host.highlighter)if(this.api){let t=[];if(this.annotator&&(t=await this.annotator.getAnnotations()),this.host.highlighter&&t&&this.host.iframes[0].contentDocument?.readyState==="complete"){await this.host.highlighter.destroyHighlights(0);for(let i of t){di.push(i.highlight);let r=i,s=this.host.currentChapterLink.href;var e=this.publication.getTOCItem(s);if(this.host.currentTocUrl&&(e=this.publication.getTOCItem(this.host.currentTocUrl)),e===void 0&&(e=this.publication.getTOCItemAbsolute(this.host.currentChapterLink.href)),e){let o=e.href;o.indexOf("#")>0&&(o=o.slice(0,o.indexOf("#"))),r.href===o&&await this.host.highlighter.createHighlightDom(this.host.iframes[0].contentWindow,i.highlight)}}}}else{let t=[];if(this.annotator&&(t=await this.annotator.getAnnotations()),this.host.highlighter&&t&&this.host.iframes[0].contentDocument?.readyState==="complete"){await this.host.highlighter.destroyHighlights(0);for(let i of t){di.push(i.highlight);let r=i,s=this.host.currentChapterLink.href,o=this.publication.getTOCItem(s);if(this.host.currentTocUrl&&(o=this.publication.getTOCItem(this.host.currentTocUrl)),o===void 0&&(o=this.publication.getTOCItemAbsolute(this.host.currentChapterLink.href)),o){let a=o.href;a.indexOf("#")>0&&(a=a.slice(0,a.indexOf("#"))),r.href===a&&await this.host.highlighter.createHighlightDom(this.host.iframes[0].contentWindow,i.highlight)}}}}}async deleteSelectedHighlight(e){this.api?.deleteBookmark?this.api.deleteBookmark(e).then(async()=>{this.deleteLocalHighlight(e.id)}):this.deleteLocalHighlight(e.id)}async deleteLocalHighlight(e){if(this.annotator){var t=await this.annotator.deleteAnnotation(e);return xr.default.log("Highlight deleted "+JSON.stringify(t)),await this.showBookmarks(),await this.drawBookmarks(),t}else return new Promise(i=>i(null))}createTree(e,t,i){if(t){let r=this,s=this.publication.readingOrder;if(s.length){let o=(a,u)=>{let l=document.createElement("ul");l.className="sidenav-annotations";for(let c of u){let d=document.createElement("li"),f=document.createElement("a"),m=document.createElement("span");if(f.tabIndex=-1,f.className="chapter-link",c.href){let g=this.publication.getAbsoluteHref(c.href),b=this.publication.getTOCItemAbsolute(g);f.href=g,f.innerHTML=b?.title||"",d.appendChild(f)}else m.innerHTML=c.title||"",m.className="chapter-title",d.appendChild(m);ee(f,"click",g=>{g.preventDefault(),g.stopPropagation();let b={href:f.href,locations:{progression:0},type:c.type,title:f.title};this.host.stopReadAloud(),this.host.navigate(b)});let y=document.createElement("ol");t.forEach(function(g){let b=c.href.indexOf("#")!==-1?c.href.slice(0,c.href.indexOf("#")):c.href;if(c.href&&g.href.endsWith(b)){let v=document.createElement("li");v.className="annotation-item";let A=document.createElement("a");if(A.setAttribute("href",g.href),e===0){A.className="bookmark-link";let x=document.createElement("span"),C=Math.round((g.locations.progression??0)*100)+"% through resource";x.className="title",x.innerHTML=C,A.appendChild(x)}let w=document.createElement("span");if(w.className="timestamp",w.innerHTML=n.readableTimestamp(g.created),A.appendChild(w),ee(A,"click",x=>{x.preventDefault(),x.stopPropagation(),r.handleAnnotationLinkClick(x,g)}),v.appendChild(A),r.host.sideNavExpanded){let x=document.createElement("button");x.className="delete",x.innerHTML=jr.delete,ee(x,"click",C=>{C.preventDefault(),C.stopPropagation(),r.handleAnnotationLinkDeleteClick(e,C,g)}),v.appendChild(x)}y.appendChild(v)}}),y.children.length>0&&(l.appendChild(d),l.appendChild(y)),l.children.length>0&&a.appendChild(l),c.children?.items&&c.children.items.length>0&&o(a,c.children.items)}};i.innerHTML="",o(i,s)}}}handleAnnotationLinkClick(e,t){t?(t.href=this.publication.getAbsoluteHref(t.href),this.host.stopReadAloud(),this.host.navigate(t)):xr.default.log("bookmark data missing: ",e)}handleAnnotationLinkDeleteClick(e,t,i){xr.default.log("bookmark data locator: ",i),i?e===0&&this.deleteBookmark(i):xr.default.log("bookmark data missing: ",t)}static readableTimestamp(e){let t=new Date(e);return t.toDateString()+" "+t.toLocaleTimeString()}async getAnnotation(e){return this.annotator?.getAnnotation(e)}async getAnnotationByID(e){return this.annotator?.getAnnotationByID(e)}save(){return this.saveBookmark().then(e=>e??null)}delete(e){return this.deleteBookmark(e).then(()=>{})}list(){return this.getBookmarks()}isCurrentBookmarked(){if(!this.annotator)return!1;let e=this.host.view?.getCurrentPosition();return e===void 0?!1:!!this.annotator.locatorExists({href:this.host.currentChapterLink.href,locations:{progression:e}},0)}};I();Xt();hi();tr();Er();I();ci();mn();var Dn=$e(jt()),$p="r2-mo-active",tn=class tn{};tn.COLOR_REF="color",tn.AUTO_SCROLL_REF="autoscroll",tn.AUTO_TURN_REF="autoturn",tn.VOLUME_REF="volume",tn.RATE_REF="rate",tn.COLOR_KEY="mediaoverlay-"+tn.COLOR_REF,tn.AUTO_SCROLL_KEY="mediaoverlay-"+tn.AUTO_SCROLL_REF,tn.AUTO_TURN_KEY="mediaoverlay-"+tn.AUTO_TURN_REF,tn.VOLUME_KEY="mediaoverlay-"+tn.VOLUME_REF,tn.RATE_KEY="mediaoverlay-"+tn.RATE_REF;var ze=tn,qp=class{constructor(e,t,i){this.MEDIAOVERLAYSETTINGS="mediaOverlaySetting";this.color="r2-mo-active";this.autoScroll=!0;this.autoTurn=!0;this.volume=1;this.rate=1;this.playing=!1;this.resourceReady=!1;this.wait=1;this.settingsChangeCallback=()=>{};this.store=e,this.api=t,this.headerMenu=i,this.initialise(),Dn.default.log(this.api)}static create(e){let t=new this(e.store,e.api,e.headerMenu);if(e.initialMediaOverlaySettings){let i=e.initialMediaOverlaySettings;i?.color&&(t.color=i.color,Dn.default.log(t.color)),i?.autoScroll&&(t.autoScroll=i.autoScroll,Dn.default.log(t.autoScroll)),i?.autoTurn&&(t.autoTurn=i.autoTurn,Dn.default.log(t.autoScroll)),i?.volume&&(t.volume=i.volume,Dn.default.log(t.volume)),i?.rate&&(t.rate=i.rate,Dn.default.log(t.rate)),i?.wait&&(t.wait=i.wait,Dn.default.log(t.wait))}return t.initializeSelections(),t}stop(){Dn.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(ze.AUTO_SCROLL_KEY)!=null?this.getProperty(ze.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(ze.AUTO_TURN_KEY)!=null?this.getProperty(ze.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(ze.COLOR_KEY)!=null?this.getProperty(ze.COLOR_KEY).value:this.color,this.volume=this.getProperty(ze.VOLUME_KEY)!=null?this.getProperty(ze.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(ze.RATE_KEY)!=null?this.getProperty(ze.RATE_KEY).value:this.rate,this.userProperties=this.getMediaOverlaySettings()}reset(){this.color="redtext",this.autoScroll=!0,this.autoTurn=!0,this.volume=1,this.rate=1,this.wait=1,this.userProperties=this.getMediaOverlaySettings()}initializeSelections(){this.headerMenu&&(this.settingsView=fe(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechAutoTurn=fe(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=fe(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=fe(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=fe(this.headerMenu,"#mediaOverlayRate")),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),this.speechAutoTurn&&(this.speechAutoTurn.checked=this.autoTurn),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechRate&&(this.speechRate.value=this.volume.toString()),ee(fe(e,"ul"),"click",t=>{t.stopPropagation()})}onSettingsChange(e){this.settingsChangeCallback=e}storeProperty(e){this.updateUserSettings(),this.saveProperty(e)}updateUserSettings(){let e={color:this.userProperties.getByRef(ze.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(ze.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(ze.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(ze.VOLUME_REF)?.value,rate:this.userProperties.getByRef(ze.RATE_REF)?.value};this.applyMediaOverlaySettings(e),this.api?.updateSettings&&this.api?.updateSettings(e).then(async t=>{Dn.default.log("api updated sync settings",t)})}getMediaOverlaySettings(){let e=new os;return e.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,ze.AUTO_SCROLL_REF,ze.AUTO_SCROLL_KEY),e.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,ze.AUTO_TURN_REF,ze.AUTO_TURN_KEY),e.addStringable(this.color,ze.COLOR_REF,ze.COLOR_KEY),e.addIncremental(this.volume,.1,1,.1,"",ze.VOLUME_REF,ze.VOLUME_KEY),e.addIncremental(this.rate,.1,3,.1,"",ze.RATE_REF,ze.RATE_KEY),e}saveProperty(e){let t=this.store.get(this.MEDIAOVERLAYSETTINGS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.name!==e.name),i.push(e),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}else{let i=[];i.push(e),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}return e}getProperty(e){let t=this.store.get(this.MEDIAOVERLAYSETTINGS);if(t){let i=JSON.parse(t);return i=i.filter(r=>r.name===e),i.length===0?null:i[0]}return null}resetMediaOverlaySettings(){this.store.remove(this.MEDIAOVERLAYSETTINGS),this.reset(),this.settingsChangeCallback()}applyMediaOverlaySettings(e){if(e.color){this.color=e.color;let t=this.userProperties.getByRef(ze.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){Dn.default.log("autoScroll "+this.autoScroll),this.autoScroll=e.autoScroll;let t=this.userProperties.getByRef(ze.AUTO_SCROLL_REF);t&&(t.value=this.autoScroll,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoTurn!==void 0){Dn.default.log("autoTurn "+this.autoTurn),this.autoTurn=e.autoTurn;let t=this.userProperties.getByRef(ze.AUTO_TURN_REF);t&&(t.value=this.autoTurn,this.saveProperty(t)),this.settingsChangeCallback()}if(e.volume){Dn.default.log("volume "+this.volume),this.volume=e.volume;let t=this.userProperties.getByRef(ze.VOLUME_REF);t&&(t.value=this.volume,this.saveProperty(t)),this.settingsChangeCallback()}if(e.rate){Dn.default.log("rate "+this.rate),this.rate=e.rate;let t=this.userProperties.getByRef(ze.RATE_REF);t&&(t.value=this.rate,this.saveProperty(t)),this.settingsChangeCallback()}}applyMediaOverlaySetting(e,t){if(e===ze.COLOR_REF){this.color=t;let i=this.userProperties.getByRef(ze.COLOR_REF);i&&(i.value=this.color,this.saveProperty(i)),this.settingsChangeCallback()}else if(e===ze.AUTO_SCROLL_REF){this.autoScroll=t;let i=this.userProperties.getByRef(ze.AUTO_SCROLL_REF);i&&(i.value=this.autoScroll,this.saveProperty(i)),this.settingsChangeCallback()}else if(e===ze.AUTO_TURN_REF){this.autoTurn=t;let i=this.userProperties.getByRef(ze.AUTO_TURN_REF);i&&(i.value=this.autoTurn,this.saveProperty(i)),this.settingsChangeCallback()}}increase(e){if(e==="mo_volume"){this.userProperties.getByRef(ze.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(ze.VOLUME_REF)?.value;let t=this.userProperties.getByRef(ze.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(ze.RATE_REF).increment(),this.rate=this.userProperties.getByRef(ze.RATE_REF)?.value;let t=this.userProperties.getByRef(ze.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback()}}decrease(e){if(e==="mo_volume"){this.userProperties.getByRef(ze.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(ze.VOLUME_REF)?.value;let t=this.userProperties.getByRef(ze.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(ze.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(ze.RATE_REF)?.value;let t=this.userProperties.getByRef(ze.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback()}}};ci();var Be=$e(jt()),Qp=class{constructor(e,t,i){this.name=we.MediaOverlays;this.hostType=nt.Epub;this.rightsKey=vt.MediaOverlays;this.play=fe(document,"#menu-button-play");this.pause=fe(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async e=>{Be.default.log("ontimeupdate"),this.trackCurrentTime()};this.ensureOnTimeUpdate=(e,t)=>{e?this.__ontimeupdate&&(this.__ontimeupdate=!1,this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),cancelAnimationFrame(this.myReq)):(!this.__ontimeupdate||t)&&(this.__ontimeupdate=!0,t&&(this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),this.audioElement.addEventListener("timeupdate",this.ontimeupdate)))};this.publication=e,this.settings=t,this.properties=i}attach(e){this.host=e}static create(e){let t=new this(e.publication,e.settings,e);return t.api=e.api,t.start(),t}stop(){Be.default.log("MediaOverlay module stop")}start(){Be.default.log("MediaOverlay module start")}async initialize(){return new Promise(async e=>{await document.fonts.ready,this.settings.setControls(),this.settings.onSettingsChange(()=>{this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}),e()})}async initializeResource(e){this.currentLinks=e,this.currentLinkIndex=0,await this.playLink()}async playLink(){let e=this.currentLinks[this.currentLinkIndex];if(e?.mediaOverlay){this.ensureOnTimeUpdate(!1,!1);let t=e.mediaOverlay,r=new URL(t,this.publication.manifestUrl).toString(),s;try{let u=await this.host.fetcher.getByHref(r);s=JSON.parse(u.text)}catch(u){console.error(u,r)}if(!s){Be.default.log("## moJson"+s);return}e.mediaOverlayNode=ml.deserialize(s),e.mediaOverlayNode.initialized=!0;let o=e.hrefDecoded||e.href,a=new URL("https://dita.digital/"+o);await this.playMediaOverlays(a.pathname.substr(1),e.mediaOverlayNode,void 0)}else if(this.audioElement&&await this.audioElement.pause(),this.currentLinks.length>1&&this.currentLinkIndex===0)this.currentLinkIndex++,await this.playLink();else if(this.settings.autoTurn&&this.settings.playing){let t=this.currentLinks[this.currentLinkIndex];(t?this.publication.getNextSpineItem(this.publication.getAbsoluteHref(t.href)):void 0)?(this.audioElement&&await this.audioElement.pause(),this.host.nextResource()):(await this.stopReadAloud(),this.api?.finished&&this.api.finished(),this.host.emit(xe.ReadAlongFinished,"finished",{href:this.currentLinks[this.currentLinkIndex]?.href}))}else this.settings.playing?(await this.stopReadAloud(),this.api?.stopped&&this.api.stopped(),this.host.emit(xe.ReadAlongStopped,"stopped",{href:this.currentLinks[this.currentLinkIndex]?.href})):await this.stopReadAloud()}bindClickHandler(){this.unbindClickHandler();let e=this.handleContentClick.bind(this);this.clickHandler=e;for(let t of this.host.iframes)t.contentDocument?.body?.addEventListener("click",e)}unbindClickHandler(){let e=this.clickHandler;if(e){for(let t of this.host.iframes)t.contentDocument?.body?.removeEventListener("click",e);this.clickHandler=void 0}}async handleContentClick(e){if(!this.settings.playing)return;let t=e.target,i=[];for(;t;)t.id&&i.push(t.id),t=t.parentElement;if(i.length===0)return;let r=e.target?.ownerDocument,s=this.currentLinkIndex;for(let d=0;d<this.host.iframes.length;d++)if(this.host.iframes[d].contentDocument===r){s=d;break}let o=this.currentLinks[s];if(!o)return;if(s!==this.currentLinkIndex||!this.mediaOverlayRoot){if(!o.mediaOverlayNode?.initialized)if(o.mediaOverlay){let d=o.mediaOverlay,f=new URL(d,this.publication.manifestUrl);try{let m=await this.host.fetcher.getByHref(f.toString()),y=JSON.parse(m.text);y&&(o.mediaOverlayNode=ml.deserialize(y),o.mediaOverlayNode.initialized=!0)}catch{Be.default.log("handleContentClick() - failed to load MO for clicked page");return}}else return;this.currentLinkIndex=s,this.mediaOverlayRoot=o.mediaOverlayNode}let a=o.hrefDecoded||o.href,l=new URL("https://dita.digital/"+a).pathname.substr(1),c=this.findDepthFirstTextAudioPair(l,this.mediaOverlayRoot,i);c&&c.Audio&&(this.mediaOverlayHighlight(void 0),await this.playMediaOverlaysAudio(c,void 0,void 0))}async startReadAloud(){if(this.host.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement&&this.currentLinks[this.currentLinkIndex]?.mediaOverlay){let e=this.currentAudioBegin?this.currentAudioBegin:0;this.audioElement.currentTime=e,await this.audioElement.play(),this.ensureOnTimeUpdate(!1,!0),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}else this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?this.host.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"),this.bindClickHandler(),this.api?.started&&this.api.started(),this.host.emit(xe.ReadAlongStarted,"started",{href:this.currentLinks[this.currentLinkIndex]?.href})}}async stopReadAloud(){this.host.rights.enableMediaOverlays&&(this.settings.playing=!1,this.unbindClickHandler(),this.audioElement&&this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.host.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"),this.api?.paused&&this.api.paused(),this.host.emit(xe.ReadAlongPaused,"paused",{href:this.currentLinks[this.currentLinkIndex]?.href}))}async resumeReadAloud(){this.host.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"),this.api?.resumed&&this.api.resumed(),this.host.emit(xe.ReadAlongResumed,"resumed",{href:this.currentLinks[this.currentLinkIndex]?.href}))}findDepthFirstTextAudioPair(e,t,i){Be.default.log("findDepthFirstTextAudioPair()");let r,s;if(t.Text){let u=new URL("https://dita.digital/"+t.Text);if(u.pathname.substr(1)===e){if(r=!0,u.hash&&i){s=!1;let l=u.hash.substr(1);for(let c of i)if(c===l){s=!0;break}}}else r=!1}if(Be.default.log("isFragmentIDMatch: "+s),Be.default.log("isTextUrlMatch: "+r),!t.Children||!t.Children.length){if(Be.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!r){Be.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return s||r&&!i?(Be.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),t):void 0}let o=i,a=i;for(let u of t.Children){Be.default.log("findDepthFirstTextAudioPair() - child"),Be.default.log(JSON.stringify(u));let l=this.findDepthFirstTextAudioPair(e,u,a);if(l===null&&(Be.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),a=void 0),l)return Be.default.log("findDepthFirstTextAudioPair() - child - match"),Be.default.log(JSON.stringify(l)),l}if(s){Be.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let u=this.findDepthFirstTextAudioPair(e,t,void 0);return u&&(Be.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),Be.default.log(JSON.stringify(u)),u)}if(o&&!a)return null}trackCurrentTime(){if(cancelAnimationFrame(this.myReq),this.mediaOverlayTextAudioPair)try{this.currentAudioEnd&&this.audioElement.currentTime>=this.currentAudioEnd-.05&&(Be.default.log("ontimeupdate - mediaOverlaysNext()"),this.mediaOverlaysNext());let e=this.mediaOverlayTextAudioPair.Text.lastIndexOf("#"),t=this.mediaOverlayTextAudioPair.Text.substr(e+1);this.mediaOverlayHighlight(t),this.myReq=requestAnimationFrame(this.trackCurrentTime.bind(this))}catch{}}mediaOverlaysNext(e){if(Be.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let t=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!e);if(t){let i=!1;if(this.mediaOverlayTextAudioPair.Text&&t.Text){let r=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),s=new URL("https://dita.digital/"+t.Text);r.pathname!==s.pathname&&(Be.default.log("mediaOverlaysNext() SWITCH! "+r.pathname+" != "+s.pathname),i=!0)}i?this.mediaOverlaysStop():(Be.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(t,void 0,void 0)},0))}else if(Be.default.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0)this.currentLinkIndex++,this.playLink();else if(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing){let i=this.currentLinks[this.currentLinkIndex];(i?this.publication.getNextSpineItem(this.publication.getAbsoluteHref(i.href)):void 0)?this.host.nextResource():(this.stopReadAloud(),this.api?.finished&&this.api.finished(),this.host.emit(xe.ReadAlongFinished,"finished",{href:this.currentLinks[this.currentLinkIndex]?.href}))}else this.settings.playing?(this.stopReadAloud(),this.api?.stopped&&this.api.stopped(),this.host.emit(xe.ReadAlongStopped,"stopped",{href:this.currentLinks[this.currentLinkIndex]?.href})):this.stopReadAloud()}else Be.default.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.host.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){Be.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){Be.default.log("mediaOverlaysPause()"),this.mediaOverlayHighlight(void 0),this.audioElement&&this.audioElement.pause()}findNextTextAudioPair(e,t,i,r){if(!e.Children||!e.Children.length){if(i?.prev===t)return Be.default.log("findNextTextAudioPair() - prevMo === moToMatch"),e;Be.default.log("findNextTextAudioPair() - set previous"),Be.default.log(JSON.stringify(e)),i.prev=e;return}for(let s of e.Children){Be.default.log("findNextTextAudioPair() - child"),Be.default.log(JSON.stringify(s));let o=this.findNextTextAudioPair(s,t,i,r);if(o)return Be.default.log("findNextTextAudioPair() - match"),Be.default.log(JSON.stringify(o)),o}}async playMediaOverlaysAudio(e,t,i){if(Be.default.log("playMediaOverlaysAudio()"),this.mediaOverlayTextAudioPair=e,!e.Audio)return;let r=new URL(e.Audio,this.publication.manifestUrl),s=r.toString(),o=new URL(s);o.hash="",o.search="";let a=o.toString(),u=typeof t<"u",l=typeof i<"u";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!u&&!l){if(r.hash){let d=r.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(d&&d.length>=1){let f=d[1];try{this.currentAudioBegin=parseFloat(f)}catch(m){Be.default.error(m)}if(d.length>=3){let m=d[3];try{this.currentAudioEnd=parseFloat(m)}catch(y){Be.default.error(y)}}}}}else this.currentAudioBegin=t,this.currentAudioEnd=i;Be.default.log(`${s} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let c=async d=>{if(!this.audioElement)return;let f=this.currentAudioBegin?this.currentAudioBegin:0;if(d||this.audioElement.paused)if(d&&!f||this.audioElement.currentTime===f){if(Be.default.log("playMediaOverlaysAudio() - playClip() - _currentAudioElement.play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing){let y=function(){m.settings.resourceReady?setTimeout(async()=>{await m.audioElement.play(),m.ensureOnTimeUpdate(!1,!0)},m.settings.wait*1e3):setTimeout(y,200)},m=this;y()}}else{Be.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let m=async y=>{if(this.audioElement.removeEventListener("timeupdate",m),Be.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked - .play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement&&(this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing)){let b=function(){g.settings.resourceReady?setTimeout(async()=>{await g.audioElement.play(),g.ensureOnTimeUpdate(!1,!0)},g.settings.wait*1e3):setTimeout(b,200)},g=this;b()}};this.audioElement.addEventListener("timeupdate",m),this.audioElement.currentTime=f}else{let m=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd<"u"&&this.previousAudioEnd>f-.02&&this.previousAudioEnd<=f&&this.audioElement.currentTime>=f-.1;this.ensureOnTimeUpdate(!1,!1),m?Be.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(Be.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=f)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||a!==this.currentAudioUrl){this.currentAudioUrl=a,Be.default.log("playMediaOverlaysAudio() - RESET: "+this.previousAudioUrl+" => "+this.currentAudioUrl),this.audioElement=document.getElementById("AUDIO_MO_ID"),this.audioElement&&(this.audioElement.pause(),this.audioElement.setAttribute("src",""),this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement)),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("style","display: none"),this.audioElement.setAttribute("id","AUDIO_MO_ID"),this.audioElement.setAttribute("role","media-overlays"),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate,document.body.appendChild(this.audioElement),this.audioElement.addEventListener("error",m=>{Be.default.log("-1) error: "+(this.currentAudioUrl!==m.currentTarget.src?this.currentAudioUrl+" -- ":"")+m.currentTarget.src.substr(m.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(Be.default.log(this.audioElement.error.code),Be.default.log(this.audioElement.error.message))});let d=async m=>{m.currentTarget.removeEventListener("canplaythrough",d),Be.default.log("oncanplaythrough"),await c(!0)};this.audioElement.addEventListener("canplaythrough",d);let f=async m=>{Be.default.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.host.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",f),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else Be.default.log("playMediaOverlaysAudio() - playClip()"),await c(!1)}async playMediaOverlays(e,t,i){Be.default.log("playMediaOverlays()");let r=i?i.filter(o=>o):void 0;r&&r.length===0&&(r=void 0);let s=this.findDepthFirstTextAudioPair(e,t,r);!s&&r&&(Be.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),Be.default.log(JSON.stringify(r,null,4)),Be.default.log(JSON.stringify(t,null,4)),s=this.findDepthFirstTextAudioPair(e,t,void 0)),s?s.Audio&&(Be.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=t,await this.playMediaOverlaysAudio(s,void 0,void 0)):Be.default.log("playMediaOverlays() - !moTextAudioPair "+e)}mediaOverlayHighlight(e){Be.default.log("moHighlight: ## "+e);let t=this.publication.metadata?.getMediaOverlay?.()?.activeClass??this.publication.metadata?.otherMetadata?.["media-overlay"]?.["active-class"]??this.settings.color,i=this.host.iframes[0].contentDocument?.documentElement.getAttribute("style"),r=i?i.indexOf("readium-night-on")>0:!1,s=i?i.indexOf("readium-sepia-on")>0:!1;if(this.publication.isFixedLayout||(t=r||s?$p:t||$p),t||(t=$p),this.pid)for(let a of this.host.iframes){let u=a.contentDocument?.getElementById(this.pid);u&&u.classList.remove(t)}let o;e&&(this.currentLinkIndex===0?o=this.host.iframes[0].contentDocument?.getElementById(e):o=this.host.iframes[1].contentDocument?.getElementById(e),o&&o.classList.add(t),this.pid=e),o&&!this.publication.isFixedLayout&&o.scrollIntoView({block:"center",behavior:"smooth"})}};I();Xt();hi();ci();mn();var Nv=$e(jt()),Xp=class{constructor(e){this.name=we.Timeline;this.hostType=nt.Epub;this.rightsKey=vt.Timeline;this.publication=e}attach(e){this.host=e}static async create(e){let t=new this(e.publication);return await t.start(),t}async stop(){Nv.default.log("Timeline module stop")}async start(){this.timelineContainer=fe(document,"#container-view-timeline"),this.positionSlider=fe(document,"#positionSlider"),this.publication.positions?this.positionSlider&&(this.positionSlider.style.display="block"):this.positionSlider&&(this.positionSlider.style.display="none")}async initialize(){return new Promise(async e=>{await document.fonts.ready;let t=this.host.currentLocator();(this.host.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions)&&(this.positionSlider&&(this.positionSlider.value=(t.locations.position??0).toString()),this.positionSlider&&(this.positionSlider.max=((t.locations.totalRemainingPositions??0)+(t.locations.position??0)).toString())),this.timelineContainer&&(this.timelineContainer.innerHTML=""),this.publication.readingOrder?.forEach(i=>{let r=this.publication.getAbsoluteHref(i.href),s=this.publication.getTOCItemAbsolute(r),o=s?.href.indexOf("#")!==-1?s?.href.slice(0,s?.href.indexOf("#")):s.href,a=this.publication.getAbsoluteHref(o??"");var u;this.publication.positions&&this.host.view?.layout!=="fixed"?i.contentWeight?u=i.contentWeight:u=1:u=100/(this.publication.readingOrder?.length??0);var l=document.createElement("div");if(l.style.height=u+"%",l.style.width="100%",l.className="chapter",s?.title!==void 0){var c=document.createElement("span");c.innerHTML=s.title,c.className="chapter-tooltip",l.appendChild(c)}ee(l,"click",d=>{d.preventDefault(),d.stopPropagation();var f;this.publication.positions||this.host.rights.autoGeneratePositions&&this.publication.positions?(f={...this.publication.positions.filter(m=>m.href===i.href)[0]},f.href=this.publication.getAbsoluteHref(f.href)):f={href:a,locations:{progression:0},type:i.type,title:i.title},Nv.default.log(f),this.host.navigate(f)}),a===this.host.currentChapterLink.href?l.className+=" dita-active":l.className=l.className.replace(" dita-active",""),this.timelineContainer&&this.timelineContainer.appendChild(l)}),e()})}};I();hi();Xt();ci();mn();var NA=$e($s());I();var o7=$e(jt());function a7(n,e){return new Promise(function(t){setTimeout(t.bind(null,e),n)})}var rQ=!1;o7.default.setLevel(rQ?"trace":"warn",!0);var M1=$e(Dv()),nn=$e(jt());OA();var Dd=class{constructor(e){this.name=we.ContentProtection;this.hostType=nt.Epub;this.rightsKey=vt.ContentProtection;this.hasEventListener=!1;this.isHacked=!1;this.properties=e}attach(e){this.host=e}static async setupPreloadProtection(e){if(this.isCurrentBrowserSupported(e))e.detectInspect&&await this.startInspectorProtection(e);else throw new Error("Browser not supported")}static async create(e){let t=new this(e);return await t.start(),t}static async startInspectorProtection(e){(0,M1.addListener)(i=>{i&&(e.clearOnInspect&&(console.clear(),window.localStorage.clear(),window.sessionStorage.clear(),window.location.replace(window.location.origin)),e.detectInspect&&typeof e.api?.inspectDetected=="function"&&e.api.inspectDetected())}),(0,M1.launch)(),await a7(e.detectInspectInitDelay??100)}static isCurrentBrowserSupported(e){if(!e.enforceSupportedBrowsers)return!0;let t=[];return(e.supportedBrowsers??[]).forEach(r=>{t.push("last 1 "+r+" version")}),MA({browsers:t,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.properties?.enableObfuscation){this.wrapper=dt(document,"#iframe-wrapper"),this.securityContainer=fe(document,"#container-view-security");var e=this;this.mutationObserver=new MutationObserver(function(t){t.forEach(function(i){nn.default.log(i.type),e.isHacked=!0})})}}async stop(){if(nn.default.log("Protection module stop"),this.properties?.enableObfuscation&&this.mutationObserver.disconnect(),this.properties?.disableKeys){Ae(this.host.mainElement,"keydown",this.disableSave),Ae(this.host.headerMenu,"keydown",this.disableSave);for(let e of this.host.iframes)Ae(e.contentDocument,"keydown",this.disableSave),Ae(e.contentWindow,"keydown",this.disableSave);Ae(window,"keydown",this.disableSave),Ae(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){Ae(this.host.mainElement,"copy",this.preventCopy),Ae(this.host.headerMenu,"copy",this.preventCopy);for(let e of this.host.iframes)Ae(e.contentDocument,"copy",this.preventCopy),Ae(e.contentWindow,"copy",this.preventCopy);Ae(window,"copy",this.preventCopy),Ae(document,"copy",this.preventCopy),Ae(this.host.mainElement,"cut",this.preventCopy),Ae(this.host.headerMenu,"cut",this.preventCopy);for(let e of this.host.iframes)Ae(e.contentDocument,"cut",this.preventCopy),Ae(e.contentWindow,"cut",this.preventCopy);Ae(window,"cut",this.preventCopy),Ae(document,"cut",this.preventCopy),Ae(this.host.mainElement,"keydown",this.preventCopyKey),Ae(this.host.headerMenu,"keydown",this.preventCopyKey);for(let e of this.host.iframes)Ae(e.contentDocument,"keydown",this.preventCopyKey),Ae(e.contentWindow,"keydown",this.preventCopyKey);Ae(window,"keydown",this.preventCopyKey),Ae(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){Ae(this.host.mainElement,"copy",this.restrictCopy),Ae(this.host.headerMenu,"copy",this.restrictCopy);for(let e of this.host.iframes)Ae(e.contentDocument,"copy",this.restrictCopy),Ae(e.contentWindow,"copy",this.restrictCopy);Ae(window,"copy",this.restrictCopy),Ae(document,"copy",this.restrictCopy),Ae(this.host.mainElement,"cut",this.restrictCopy),Ae(this.host.headerMenu,"cut",this.restrictCopy);for(let e of this.host.iframes)Ae(e.contentDocument,"cut",this.restrictCopy),Ae(e.contentWindow,"cut",this.restrictCopy);Ae(window,"cut",this.restrictCopy),Ae(document,"cut",this.restrictCopy),Ae(this.host.mainElement,"keydown",this.restrictCopyKey),Ae(this.host.headerMenu,"keydown",this.restrictCopyKey);for(let e of this.host.iframes)Ae(e.contentDocument,"keydown",this.restrictCopyKey),Ae(e.contentWindow,"keydown",this.restrictCopyKey);Ae(window,"keydown",this.restrictCopyKey),Ae(document,"keydown",this.restrictCopyKey)}if(this.properties?.disablePrint){Ae(this.host.mainElement,"beforeprint",this.beforePrint.bind(this)),Ae(this.host.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let e of this.host.iframes)Ae(e.contentDocument,"beforeprint",this.beforePrint),Ae(e.contentWindow,"beforeprint",this.beforePrint);Ae(window,"beforeprint",this.beforePrint),Ae(document,"beforeprint",this.beforePrint),Ae(this.host.mainElement,"afterprint",this.afterPrint.bind(this)),Ae(this.host.headerMenu,"afterprint",this.afterPrint.bind(this));for(let e of this.host.iframes)Ae(e.contentDocument,"afterprint",this.afterPrint.bind(this)),Ae(e.contentWindow,"afterprint",this.afterPrint.bind(this));Ae(window,"afterprint",this.afterPrint.bind(this)),Ae(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){Ae(this.host.mainElement,"contextmenu",this.disableContext),Ae(this.host.headerMenu,"contextmenu",this.disableContext);for(let e of this.host.iframes)Ae(e.contentDocument,"contextmenu",this.disableContext),Ae(e.contentWindow,"contextmenu",this.disableContext);Ae(window,"contextmenu",this.disableContext),Ae(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),Ae(this.wrapper,"scroll",this.handleScroll.bind(this))}observe(){if(this.properties?.enableObfuscation){this.securityContainer.hasAttribute("style")&&(this.isHacked=!0),this.mutationObserver.disconnect();var e={attributes:!0,childList:!0,characterData:!0};this.mutationObserver.observe(this.securityContainer,e)}}async deactivate(){this.properties?.enableObfuscation&&(this.observe(),this.rects.forEach(e=>this.deactivateRect(e,this.securityContainer,this.isHacked)))}async activate(){if(this.properties?.enableObfuscation){this.observe();for(let e of this.host.iframes)if(e.contentDocument){let t=Gs(e.contentDocument,"body");this.rects=this.findRects(t),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){ee(this.host.mainElement,"keydown",this.disableSave),ee(this.host.headerMenu,"keydown",this.disableSave);for(let e of this.host.iframes)ee(e,"keydown",this.disableSave),ee(e.ownerDocument,"keydown",this.disableSave),ee(e.contentDocument,"keydown",this.disableSave),ee(e.contentWindow,"keydown",this.disableSave),ee(e.contentWindow?.document,"keydown",this.disableSave);ee(window,"keydown",this.disableSave),ee(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){ee(this.host.mainElement,"copy",this.preventCopy),ee(this.host.headerMenu,"copy",this.preventCopy);for(let e of this.host.iframes)ee(e,"copy",this.preventCopy),ee(e.ownerDocument,"copy",this.preventCopy),ee(e.contentDocument,"copy",this.preventCopy),ee(e.contentWindow,"copy",this.preventCopy),ee(e.contentWindow?.document,"copy",this.preventCopy);ee(window,"copy",this.preventCopy),ee(document,"copy",this.preventCopy),ee(this.host.mainElement,"cut",this.preventCopy),ee(this.host.headerMenu,"cut",this.preventCopy);for(let e of this.host.iframes)ee(e,"cut",this.preventCopy),ee(e.ownerDocument,"cut",this.preventCopy),ee(e.contentDocument,"cut",this.preventCopy),ee(e.contentWindow,"cut",this.preventCopy),ee(e.contentWindow?.document,"cut",this.preventCopy);ee(window,"cut",this.preventCopy),ee(document,"cut",this.preventCopy),ee(this.host.mainElement,"keydown",this.preventCopyKey),ee(this.host.headerMenu,"keydown",this.preventCopyKey);for(let e of this.host.iframes)ee(e,"keydown",this.preventCopyKey),ee(e.ownerDocument,"keydown",this.preventCopyKey),ee(e.contentDocument,"keydown",this.preventCopyKey),ee(e.contentWindow,"keydown",this.preventCopyKey),ee(e.contentWindow?.document,"keydown",this.preventCopyKey);ee(window,"keydown",this.preventCopyKey),ee(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){ee(this.host.mainElement,"copy",this.restrictCopy.bind(this)),ee(this.host.headerMenu,"copy",this.restrictCopy.bind(this));for(let e of this.host.iframes)ee(e,"copy",this.restrictCopy),ee(e.ownerDocument,"copy",this.restrictCopy.bind(this)),ee(e.contentDocument,"copy",this.restrictCopy.bind(this)),ee(e.contentWindow,"copy",this.restrictCopy.bind(this)),ee(e.contentWindow?.document,"copy",this.restrictCopy.bind(this));ee(window,"copy",this.restrictCopy.bind(this)),ee(document,"copy",this.restrictCopy.bind(this)),ee(this.host.mainElement,"cut",this.restrictCopy.bind(this)),ee(this.host.headerMenu,"cut",this.restrictCopy.bind(this));for(let e of this.host.iframes)ee(e,"cut",this.restrictCopy.bind(this)),ee(e.ownerDocument,"cut",this.restrictCopy.bind(this)),ee(e.contentDocument,"cut",this.restrictCopy.bind(this)),ee(e.contentWindow,"cut",this.restrictCopy.bind(this)),ee(e.contentWindow?.document,"cut",this.restrictCopy.bind(this));ee(window,"cut",this.restrictCopy.bind(this)),ee(document,"cut",this.restrictCopy.bind(this)),ee(this.host.mainElement,"keydown",this.restrictCopyKey.bind(this)),ee(this.host.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let e of this.host.iframes)ee(e,"keydown",this.restrictCopyKey.bind(this)),ee(e.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),ee(e.contentDocument,"keydown",this.restrictCopyKey.bind(this)),ee(e.contentWindow,"keydown",this.restrictCopyKey.bind(this)),ee(e.contentWindow?.document,"keydown",this.restrictCopyKey.bind(this));ee(window,"keydown",this.restrictCopyKey.bind(this)),ee(document,"keydown",this.restrictCopyKey.bind(this))}if(this.properties?.disablePrint){ee(this.host.mainElement,"beforeprint",this.beforePrint),ee(this.host.headerMenu,"beforeprint",this.beforePrint);for(let e of this.host.iframes)ee(e,"beforeprint",this.beforePrint.bind(this)),ee(e.ownerDocument,"beforeprint",this.beforePrint.bind(this)),ee(e.contentDocument,"beforeprint",this.beforePrint.bind(this)),ee(e.contentWindow,"beforeprint",this.beforePrint.bind(this)),ee(e.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));ee(window,"beforeprint",this.beforePrint.bind(this)),ee(document,"beforeprint",this.beforePrint.bind(this)),ee(this.host.mainElement,"afterprint",this.afterPrint),ee(this.host.headerMenu,"afterprint",this.afterPrint);for(let e of this.host.iframes)ee(e,"afterprint",this.afterPrint.bind(this)),ee(e.ownerDocument,"afterprint",this.afterPrint.bind(this)),ee(e.contentDocument,"afterprint",this.afterPrint.bind(this)),ee(e.contentWindow,"afterprint",this.afterPrint.bind(this)),ee(e.contentWindow?.document,"afterprint",this.afterPrint.bind(this));ee(window,"afterprint",this.afterPrint.bind(this)),ee(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){ee(this.host.mainElement,"contextmenu",this.disableContext),ee(this.host.headerMenu,"contextmenu",this.disableContext);for(let e of this.host.iframes)ee(e,"contextmenu",this.disableContext),ee(e.ownerDocument,"contextmenu",this.disableContext),ee(e.contentDocument,"contextmenu",this.disableContext),ee(e.contentWindow,"contextmenu",this.disableContext),ee(e.contentWindow?.document,"contextmenu",this.disableContext);ee(window,"contextmenu",this.disableContext),ee(document,"contextmenu",this.disableContext)}}initializeResource(){this.properties?.hideTargetUrl&&this.hideTargetUrls(!0),this.properties?.disableDrag&&this.preventDrag(!0)}async initialize(e){if(this.properties?.enableObfuscation)return new Promise(async t=>{if(await document.fonts.ready,e.contentDocument){let i=Gs(e.contentDocument,"body");this.observe(),setTimeout(()=>{this.rects=this.findRects(i),this.rects.forEach(r=>this.toggleRect(r,this.securityContainer,this.isHacked)),this.setupEvents(),this.hasEventListener||(this.hasEventListener=!0,ee(this.wrapper,"scroll",this.handleScroll.bind(this))),t()},10)}})}handleScroll(){this.rects.forEach(e=>this.toggleRect(e,this.securityContainer,this.isHacked))}async handleResize(){if(this.properties?.enableObfuscation){let e=(0,NA.default)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(t=>this.toggleRect(t,this.securityContainer,this.isHacked))},50);this.rects&&(this.observe(),e())}}disableContext(e){return e.preventDefault(),e.stopPropagation(),!1}disableSave(e){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?e.metaKey:e.ctrlKey&&(e.key==="s"||e.keyCode===83))?(e.preventDefault(),e.stopPropagation(),!1):!0}preventCopy(e){return nn.default.log("copy action initiated"),e.clipboardData.setData("text/plain","copy not allowed"),e.stopPropagation(),e.preventDefault(),!1}preventCopyKey(e){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?e.metaKey:e.ctrlKey&&(e.key==="c"||e.keyCode===67))?(e.preventDefault(),e.stopPropagation(),!1):!0}restrictCopy(e){if(this.citation)return;nn.default.log("copy action initiated");let t=this.host.iframes[0].contentWindow;if(t){let r=function(o){let a={className:l=>ir.indexOf(l)<0,idName:l=>ir.indexOf(l)<0},u=i.host.iframes[0].contentDocument;if(u)return Vi(o,u,a)},i=this,s=ps(t,r);if(s===void 0){let o=this.host.iframes[0].contentDocument;s=this.host.getModule(we.Annotations)?.annotator?.getTemporarySelectionInfo(o)??void 0}e.clipboardData.setData("text/plain",s?.cleanText?.substring(0,this.properties?.charactersToCopy??0))}else e.clipboardData.setData("text/plain","");return e.stopPropagation(),e.preventDefault(),!1}restrictCopyKey(e){if(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?e.metaKey:e.ctrlKey&&(e.key==="c"||e.keyCode===67)){let t=this.host.iframes[0].contentWindow;if(t){let r=function(o){let a={className:l=>ir.indexOf(l)<0,idName:l=>ir.indexOf(l)<0},u=i.host.iframes[0].contentDocument;if(u)return Vi(o,u,a)},i=this,s=ps(t,r);if(s===void 0){let o=this.host.iframes[0].contentDocument;s=this.host.getModule(we.Annotations)?.annotator?.getTemporarySelectionInfo(o)??void 0}this.copyToClipboard(s?.cleanText?.substring(0,this.properties?.charactersToCopy??0))}else this.copyToClipboard("");return e.stopPropagation(),e.preventDefault(),!1}return!0}copyToClipboard(e){e=e?.substring(0,this.properties?.charactersToCopy??0),e&&(navigator.clipboard?.writeText?navigator.clipboard.writeText(e).catch(()=>{this.execCommandCopy(e)}):this.execCommandCopy(e))}execCommandCopy(e){let t=document.createElement("div");t.style.position="absolute",t.style.left="-10000px",t.style.top="-10000px",t.textContent=e,t.contentEditable="true",document.body.appendChild(t);let i=document.createRange();i.selectNodeContents(t);let r=window.getSelection();r?.removeAllRanges(),r?.addRange(i);try{document.execCommand("copy",!1)}catch{}document.body.removeChild(t)}beforePrint(e){return nn.default.log("before print"),this.host&&this.host.headerMenu&&(this.host.headerMenu.style.display="none",this.host.mainElement.style.display="none"),e.stopPropagation(),e.preventDefault(),!1}afterPrint(e){return nn.default.log("after print"),this.host&&this.host.headerMenu&&(this.host.headerMenu.style.removeProperty("display"),this.host.mainElement.style.removeProperty("display")),e.stopPropagation(),e.preventDefault(),!1}hideTargetUrls(e){function t(i){i.preventDefault();let r=i.currentTarget.getAttribute("data-href-resolved"),s=document.createElement("a");s.setAttribute("href",r),s.click()}for(let i of this.host.iframes){let r=i.contentDocument?.querySelectorAll("a");r?.forEach(s=>{let o=s.getAttribute("data-href"),a=s.getAttribute("href");!o&&a&&(s.setAttribute("data-href",a),s.setAttribute("data-href-resolved",s.href))}),e?r?.forEach(s=>{s.setAttribute("href",""),s.addEventListener("click",t)}):r?.forEach(s=>{let o=s.getAttribute("data-href");o&&s.setAttribute("href",o),s.removeEventListener("click",t)})}}preventDrag(e){let t="-webkit-user-drag: none; -khtml-user-drag: none; -moz-user-drag: none; -ms-user-drag: none; user-drag: none; -webkit-pointer-events: none; -khtml-pointer-events: none; -moz-pointer-events: none; -ms-pointer-events: none; pointer-events: none;",i=r=>{r.preventDefault()};for(let r of this.host.iframes){let s=r.contentDocument?.body.getAttribute("style")||"";e?(r.contentDocument?.body.addEventListener("dragstart",i),r.contentDocument?.body.setAttribute("style",s+t)):(r.contentDocument?.body.removeEventListener("dragstart",i),r.contentDocument?.body.setAttribute("style",s.replace(t,"")))}}recalculate(e=0){return new Promise(t=>{if(this.properties?.enableObfuscation){let i=(0,NA.default)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(r=>this.toggleRect(r,this.securityContainer,this.isHacked)),t(!0)},e);this.rects?(this.observe(),i()):t(!1)}else t(!1)})}calcRects(e){e!==void 0&&e.forEach(t=>{try{let{top:i,height:r,left:s,width:o}=this.measureTextNode(t.node);t.top=i,t.height=r,t.width=o,t.left=s}catch(i){nn.default.log("error "+i),nn.default.log(t),nn.default.log(t.node),nn.default.log("scrambledTextContent "+t.scrambledTextContent),nn.default.log("textContent "+t.textContent),nn.default.log("isObfuscated "+t.isObfuscated)}})}deactivateRect(e,t,i){this.isBeingHacked(t)||i?(e.node.textContent=e.scrambledTextContent,e.isObfuscated=!0):(e.node.textContent=e.textContent,e.isObfuscated=!1)}toggleRect(e,t,i){let r=this.isOutsideViewport(e),s=this.isBeingHacked(t);e.isObfuscated&&!r&&!s&&!i&&(e.node.textContent=e.textContent,e.isObfuscated=!1),!e.isObfuscated&&(r||s||i)&&(e.node.textContent=e.scrambledTextContent,e.isObfuscated=!0)}findRects(e){return this.findTextNodes(e).map(i=>{let{top:r,height:s,left:o,width:a}=this.measureTextNode(i),u=i.parentElement&&(this.properties?.excludeNodes&&this.properties?.excludeNodes.indexOf(i.parentElement.nodeName.toLowerCase())>-1||i.parentElement?.nodeName.toLowerCase()==="option"||i.parentElement?.nodeName.toLowerCase()==="script")?i.textContent:this.obfuscateText(i.textContent??"");return{top:r,height:s,width:a,left:o,node:i,textContent:i.textContent??"",scrambledTextContent:u??"",isObfuscated:!1}})}obfuscateText(e){return this.scramble(e,!0)}measureTextNode(e){try{let t=document.createRange();t.selectNode(e);let i=t.getBoundingClientRect();return t.detach(),i}catch(t){nn.default.log("measureTextNode "+t),nn.default.log("measureTextNode "+e),nn.default.log(e.textContent)}}isBeingHacked(e){return e.style.animation||e.style.transition||e.style.position||e.hasAttribute("style")?(nn.default.log("content being hacked"),!0):!1}isOutsideViewport(e){let t=this.wrapper.scrollLeft,i=t+this.wrapper.clientWidth,r=e.left+e.width,s=e.top+e.height,o=this.wrapper.scrollTop-(e.node.parentElement?parseInt(getComputedStyle(e.node.parentElement).lineHeight.replace("px","")):10),a=o+this.wrapper.clientHeight+(e.node.parentElement?parseInt(getComputedStyle(e.node.parentElement).lineHeight.replace("px","")):10),u=s<o,l=e.top>a,c=r<t-window.innerWidth,d=e.left>i+window.innerWidth;return u||l||c||d}findTextNodes(e,t=[]){let i=e.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,t),i.nodeType===3&&i.textContent?.trim()&&t.push(i),i=i.nextSibling;return t}scramble(e,t=!1,i=!1){var r=e.split(" ");function s(o){for(var a=o.length,u,l;a>0;)l=Math.floor(Math.random()*a),a--,u=o[a],o[a]=o[l],o[l]=u;return o}return t&&(r=r.map(function(o){return o.includes("-")?o:s(o.split("")).join("")})),i?s(r).join(" "):r.join(" ")}};I();ci();Xt();hi();mn();Er();var uR=$e(rR());I();var O1=n=>n.replace(/\n/g," ").replace(/\s\s+/g," "),uZ=n=>O1(n).trim(),oR=/[\\^$.*+?()[\]{}|]/g,lZ=RegExp(oR.source);function sR(n){return n&&lZ.test(n)?n.replace(oR,"\\$&"):n||""}var N1=0,cZ=()=>()=>Number.isSafeInteger(++N1)?N1:N1=1,aR=()=>{N1=0},dZ=cZ(),hZ=n=>e=>{try{return Vi(e,n,zo)}catch(t){return console.error("uniqueCssSelector:",t),""}};async function Sl(n,e,t,i,r=!1){if(!e)return[];let s=e.body?.textContent;if(!s)return[];if(n=uZ(n),!n.length)return[];let o=e.createNodeIterator(e.body,NodeFilter.SHOW_TEXT,{acceptNode:m=>NodeFilter.FILTER_ACCEPT}),a=new RegExp(sR(n).replace(/ /g,"\\s+"),"gim");r&&(a=new RegExp("\\b"+sR(n).replace(/ /g,"\\s+")+"\\b","gim"));let u=[],l=100,c=30,d=0,f;for(;f=a.exec(s);){let m=Math.max(0,f.index-l),y=Math.min(l,f.index),g=O1(s.substr(m,y));g=g.substr(g.length-c),m=a.lastIndex,y=Math.min(l,s.length-m);let b=O1(s.substr(m,y)).substr(0,c),v=new Range,A=f.index;for(;d<=A;){let C=o.nextNode();C&&C.nodeValue&&(d+=C.nodeValue.length)}let w=o.referenceNode.nodeValue?o.referenceNode.nodeValue?.length-(d-A):0;for(v.setStart(o.referenceNode,w),A=f.index+f[0].length;d<=A;){let T=o.nextNode()?.nodeValue;T&&(d+=T.length)}w=o.referenceNode.nodeValue?o.referenceNode.nodeValue?.length-(d-A):0,v.setEnd(o.referenceNode,w),e.getCssSelector||(e.getCssSelector=hZ(e));let x=Qs(v,e.getCssSelector);x&&u.push({textMatch:O1(f[0]),textBefore:g,textAfter:b,rangeInfo:x,href:t,title:i,uuid:dZ().toString()})}return u}var lR=$e(jt()),fZ="#fff059",pZ="#ff6600",B1=class{constructor(e,t,i,r,s){this.name=we.Search;this.hostType=nt.Epub;this.rightsKey=vt.Search;this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.headerMenu=s,this.publication=e,this.properties={...t,color:t.color??fZ,current:t.current??pZ},this.api=r,this.highlighter=i}attach(e){this.host=e}static async create(e){let t=new this(e.publication,e,e.highlighter,e.api,e.headerMenu);return await t.start(),t}async stop(){lR.default.log("Search module stop"),Ae(this.searchInput,"keypress",this.handleSearch.bind(this)),Ae(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.headerMenu){this.searchInput=fe(this.headerMenu,"#searchInput"),ee(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=fe(this.headerMenu,"#searchGo"),ee(this.searchGo,"click",this.handleSearch.bind(this));var e=fe(this.headerMenu,"#menu-button-search");e&&e.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties.hideLayer?this.host.hideLayer("search"):this.host.showLayer("search")},10)}async handleSearch(e){(e.key==="Enter"||e.type==="click")&&(await this.handleSearchChapter(),await this.handleSearchBook())}async handleSearchChapter(e){var t=this,i=this.searchInput.value;let r=this.host.currentChapterLink.href,s=this.publication.getSpineItem(r);if(this.headerMenu)var o=fe(document,"#searchResultChapter");t.currentChapterSearchResult=[],t.currentSearchHighlights=[];var a=[];await this.searchAndPaintChapter(i,e,async l=>{a=l,u(1),this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.recalculate(200)});async function u(l){o.innerHTML="";var c;if(c=t.paginate(a,l,10),c.total===0){let d=document.createElement("a");d.className="collection-item",d.innerHTML="nothing found",o.appendChild(d)}else{for(let g=0;g<c.data.length;g++){let b=document.createElement("a"),v=c.data[g];b.className="collection-item",b.href=s?.href??"",b.innerHTML="..."+v.textBefore+"<mark>"+v.textMatch+"</mark>"+v.textAfter+"...",ee(b,"click",A=>{A.preventDefault(),A.stopPropagation(),t.jumpToMark(g+l*10-10)}),o.appendChild(b)}let d=document.createElement("div");d.style.textAlign="center",d.style.marginTop="10px";let f=document.createElement("ul");f.className="dita-pagination";let m=document.createElement("li");if(m.className="disabled",m.innerHTML='<a href="#!"> < </a>',c.pre_page!==void 0){let g=c.pre_page;m.className="waves-effect",ee(m,"click",b=>{b.preventDefault(),b.stopPropagation(),u(g)})}f.appendChild(m);for(let g=1;g<=c.total_pages;g++){let b,v=document.createElement("li");v.className="waves-effect",g===c.page&&(v.className="dita-active",b=v),v.innerHTML='<a href="#!">'+g+"</a>",ee(v,"click",A=>{A.preventDefault(),A.stopPropagation(),b&&(b.className="waves-effect"),v.className="dita-active",b=v,u(g)}),f.appendChild(v)}let y=document.createElement("li");if(y.className="disabled",y.innerHTML='<a href="#!"> > </a>',c.next_page!==void 0){let g=c.next_page;y.className="waves-effect",ee(y,"click",b=>{b.preventDefault(),b.stopPropagation(),u(g)})}f.appendChild(y),d.appendChild(f),o.appendChild(d)}}}async searchAndPaintChapter(e,t=0,i){this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.deactivate();let r=this.publication.getAbsoluteHref(this.publication.readingOrder[this.host.currentResource()??0].href),s=this.publication.getTOCItem(r);s===null&&(s=this.publication.readingOrder[this.host.currentResource()??0]);let o=[];this.highlighter?.destroyHighlights(1),this.host.rights.enableSearch&&this.drawSearch();let a=0;if(s){let u=this.host.iframes[0].contentDocument;u&&s&&Sl(e,u,s.href,s.title).then(l=>{l.forEach(c=>{let d={rangeInfo:c.rangeInfo};setTimeout(()=>{let f;a===t?(f=this.createSearchHighlight(d,this.properties?.current),this.jumpToMark(t)):f=this.createSearchHighlight(d,this.properties?.color),c.highlight=f,o.push(c),this.currentChapterSearchResult.push(c),this.currentSearchHighlights.push(f),a++},500)}),setTimeout(()=>{i(o)},500)})}}createSearchHighlight(e,t){try{var i=t;$t.isHexColor(i)&&(i=$t.hexToRgbChannels(i));let s=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,a="R2_SEARCH_"+uR.SHA256.hash(s);var r=!1;let u={color:i||Ba,id:a,pointerInteraction:r,selectionInfo:e,marker:0,type:1},l=this.highlighter?.createHighlightDom(this.host.iframes[0].contentWindow,u);return u.position=parseInt((l?.hasChildNodes()?l.childNodes[0]:l).style.top.replace("px","")),u}catch(s){throw"Can't create highlight: "+s}}clearSearch(){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.highlighter?.destroyHighlights(1)}clear(){this.clearSearch()}async search(e,t){return this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],aR(),await this.searchAndPaintChapter(e,0,async()=>{this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.recalculate(200)}),t?(await this.searchBook(e),await this.searchChapter(e)):(await this.searchChapter(e),await this.searchBook(e))}async goToSearchID(e,t,i){var r=t,s;let o=this.host.currentChapterLink.href;var a=this.publication.getAbsoluteHref(e);let u=this.bookSearchResult.filter(l=>l.href===e);if(i?(s=this.currentChapterSearchResult.filter(l=>l.uuid===t)[0],r=this.currentChapterSearchResult.findIndex(l=>l.uuid===t)):(s=u.filter(l=>l.uuid===t)[0],r=u.findIndex(l=>l.uuid===t)),s!==void 0)if(o===a)this.jumpToMark(r);else{let c={href:a,locations:{progression:0},title:"title"},d=this.publication.positionsByHref(c.href);d?.length>0&&(c.locations.totalProgression=d[0].locations.totalProgression,c.locations.position=d[0].locations.position),this.host.navigate(c),setTimeout(()=>{this.searchAndPaintChapter(s.textMatch,r,async()=>{this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.recalculate(200)})},300)}}async goToSearchIndex(e,t,i){var r=t,s;let o=this.host.currentChapterLink.href;var a=this.publication.getAbsoluteHref(e);let u=this.bookSearchResult.filter(l=>l.href===e);if(i?s=this.currentChapterSearchResult[r]:s=u[r],s!==void 0)if(o===a)this.jumpToMark(r);else{let c={href:a,locations:{progression:0},title:"title"},d=this.publication.positionsByHref(c.href);d?.length>0&&(c.locations.totalProgression=d[0].locations.totalProgression,c.locations.position=d[0].locations.position),this.host.navigate(c),setTimeout(()=>{this.searchAndPaintChapter(s.textMatch,r,async()=>{this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.recalculate(200)})},300)}}async handleSearchBook(){var e=this,t=this.searchInput.value;if(e.headerMenu)var i=fe(document,"#searchResultBook");r(1);async function r(o){i.innerHTML="";var a,u=await e.searchBook(t);if(a=e.paginate(u,o,10),a.total===0){let l=document.createElement("a");l.className="collection-item",l.innerHTML="nothing found",i.appendChild(l)}else{s(a.data,y=>y.href).forEach(y=>{let g=document.createElement("div");if(g.style.marginBottom="10px",y[0].title){let b=document.createElement("span");b.className="collection-item",b.style.display="block",b.innerHTML=y[0].title,g.appendChild(b)}i.appendChild(g),y.forEach(b=>{let v=document.createElement("a");v.className="collection-item";var A=e.publication.getAbsoluteHref(b.href);v.innerHTML="..."+b.textBefore+"<mark>"+b.textMatch+"</mark>"+b.textAfter+"...",ee(v,"click",w=>{w.preventDefault(),w.stopPropagation();let C=u.filter(k=>k.href===b.href).findIndex(k=>k===b);if(e.host.currentChapterLink.href===A)e.jumpToMark(C);else{let _={href:A,locations:{progression:0},title:"title"},R=e.publication.positionsByHref(_.href);R?.length>0&&(_.locations.totalProgression=R[0].locations.totalProgression,_.locations.position=R[0].locations.position),e.host.navigate(_),setTimeout(()=>{e.handleSearchChapter(C)},300)}}),g.appendChild(v)})});let c=document.createElement("div");c.style.textAlign="center",c.style.marginTop="10px";let d=document.createElement("ul");d.className="dita-pagination";let f=document.createElement("li");if(f.className="disabled",f.innerHTML='<a href="#!"> < </a>',a.pre_page!=null){let y=a.pre_page;f.className="waves-effect",ee(f,"click",g=>{g.preventDefault(),g.stopPropagation(),r(y)})}d.appendChild(f);for(let y=1;y<=a.total_pages;y++){let g,b=document.createElement("li");b.className="waves-effect",y===a.page&&(b.className="dita-active",g=b),b.innerHTML='<a href="#!">'+y+"</a>",ee(b,"click",v=>{v.preventDefault(),v.stopPropagation(),g&&(g.className="waves-effect"),b.className="dita-active",g=b,r(y)}),d.appendChild(b)}let m=document.createElement("li");if(m.className="disabled",m.innerHTML='<a href="#!"> > </a>',a.next_page!=null){let y=a.next_page;m.className="waves-effect",ee(m,"click",g=>{g.preventDefault(),g.stopPropagation(),r(y)})}d.appendChild(m),c.appendChild(d),i.appendChild(c)}}function s(o,a){let u=new Map;return o.forEach(l=>{let c=a(l),d=u.get(c);d?d.push(l):u.set(c,[l])}),Array.from(u.values())}}async searchBook(e){this.bookSearchResult=[];let t=[];for(let i=0;i<this.publication.readingOrder.length;i++){let r=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[i].href:""),s=this.publication.getTOCItem(r);if(s===void 0&&this.publication.readingOrder&&(s=this.publication.readingOrder[i]),s){let o=this.publication.getAbsoluteHref(s.href),a=await this.host.fetcher.getByHref(o),l=new DOMParser().parseFromString(a.text,"application/xhtml+xml");s&&(await Sl(e,l,s.href,s.title)).forEach(d=>{t.push(d),this.bookSearchResult.push(d)})}if(i===this.publication.readingOrder.length-1)return t}}async searchChapter(e){let t=[],i=this.publication.getAbsoluteHref(this.publication.readingOrder[this.host.currentResource()??0].href),r=this.publication.getTOCItem(i);if(r===null&&(r=this.publication.readingOrder[this.host.currentResource()??0]),r){let s=this.publication.getAbsoluteHref(r.href),o=await this.host.fetcher.getByHref(s),u=new DOMParser().parseFromString(o.text,"application/xhtml+xml");r&&(await Sl(e,u,r.href,r.title)).forEach(c=>{t.push(c)})}return t}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(e=>{let t={rangeInfo:e.rangeInfo};if(this.properties?.color){let i=this.createSearchHighlight(t,this.properties?.color);e.highlight=i,this.currentSearchHighlights.push(i)}})},100)}async handleResize(){await this.highlighter?.destroyHighlights(1),this.drawSearch()}jumpToMark(e){setTimeout(()=>{if(this.currentChapterSearchResult.length){var t=this.currentChapterSearchResult[e];this.currentSearchHighlights.forEach(r=>{var s=this.properties?.color;$t.isHexColor(s)&&(s=$t.hexToRgbChannels(s)),r.color=s});var i=this.properties?.current;$t.isHexColor(i)&&(i=$t.hexToRgbChannels(i)),t.highlight.color=i,this.highlighter?.setAndResetSearchHighlight(t.highlight,this.currentSearchHighlights),this.host.view?.goToCssSelector(t.rangeInfo.startContainerElementCssSelector),this.host.updatePositionInfo()}},200)}paginate(e,t,i){let r=t||1,s=i||10,o=(r-1)*s,a=e.slice(o).slice(0,s),u=Math.ceil(e.length/s);return{page:r,per_page:s,pre_page:r-1?r-1:void 0,next_page:u>r?r+1:void 0,total:e.length,total_pages:u,data:a}}};I();ci();mn();var Hn=$e(jt()),Pi=class Pi{};Pi.COLOR_REF="color",Pi.AUTO_SCROLL_REF="autoscroll",Pi.RATE_REF="rate",Pi.PITCH_REF="pitch",Pi.VOLUME_REF="volume",Pi.VOICE_REF="voice",Pi.COLOR_KEY="tts-"+Pi.COLOR_REF,Pi.AUTO_SCROLL_KEY="tts-"+Pi.AUTO_SCROLL_REF,Pi.RATE_KEY="tts-"+Pi.RATE_REF,Pi.PITCH_KEY="tts-"+Pi.PITCH_REF,Pi.VOLUME_KEY="tts-"+Pi.VOLUME_REF,Pi.VOICE_KEY="tts-"+Pi.VOICE_REF;var Ve=Pi,D1=class{constructor(e,t,i){this.TTSSETTINGS="ttsSetting";this.color="orange";this.autoScroll=!0;this.rate=1;this.pitch=1;this.volume=1;this.voice={usePublication:!0};this.settingsChangeCallback=()=>{};this.restartCallback=()=>{};this.store=e,this.api=t,this.headerMenu=i,this.initialise()}static create(e){let t=new this(e.store,e.api,e.headerMenu);if(e.initialTTSSettings){let i=e.initialTTSSettings;i?.rate&&(t.rate=i.rate,Hn.default.log(t.rate)),i?.pitch&&(t.pitch=i.pitch,Hn.default.log(t.pitch)),i?.volume&&(t.volume=i.volume,Hn.default.log(t.volume)),i?.color&&(t.color=i.color,Hn.default.log(t.color)),i?.autoScroll&&(t.autoScroll=i.autoScroll,Hn.default.log(t.autoScroll)),i?.voice&&(t.voice=i.voice,Hn.default.log(t.voice))}return t.initializeSelections(),t}stop(){Hn.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(Ve.AUTO_SCROLL_KEY)!=null?this.getProperty(Ve.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(Ve.RATE_KEY)!=null?this.getProperty(Ve.RATE_KEY).value:this.rate,this.pitch=this.getProperty(Ve.PITCH_KEY)!=null?this.getProperty(Ve.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(Ve.VOLUME_KEY)!=null?this.getProperty(Ve.VOLUME_KEY).value:this.volume,this.color=this.getProperty(Ve.COLOR_KEY)!=null?this.getProperty(Ve.COLOR_KEY).value:this.color,this.voice=this.getProperty(Ve.VOICE_REF)!=null?this.getProperty(Ve.VOICE_REF).value:this.voice,this.userProperties=this.getTTSSettings()}reset(){this.color="orange",this.autoScroll=!0,this.rate=1,this.pitch=1,this.volume=1,this.voice={usePublication:!0},this.userProperties=this.getTTSSettings()}initializeSelections(){this.headerMenu&&(this.settingsView=fe(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechRate=fe(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=fe(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=fe(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=fe(this.headerMenu,"#autoScroll")),this.speechRate&&(this.speechRate.value=this.rate.toString()),this.speechPitch&&(this.speechPitch.value=this.pitch.toString()),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),ee(fe(e,"ul"),"click",t=>{t.stopPropagation()})}onSettingsChange(e){this.settingsChangeCallback=e}onRestart(e){this.restartCallback=e}storeProperty(e){this.updateUserSettings(),this.saveProperty(e)}updateUserSettings(){var e={rate:this.userProperties.getByRef(Ve.RATE_REF)?.value,pitch:this.userProperties.getByRef(Ve.PITCH_REF)?.value,volume:this.userProperties.getByRef(Ve.VOLUME_REF)?.value,voice:this.userProperties.getByRef(Ve.VOLUME_REF)?.value,color:this.userProperties.getByRef(Ve.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Ve.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(e),this.api?.updateSettings&&this.api?.updateSettings(e).then(async t=>{Hn.default.log("api updated tts settings",t)})}getTTSSettings(){var e=new os;return e.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,Ve.AUTO_SCROLL_REF,Ve.AUTO_SCROLL_KEY),e.addIncremental(this.rate,.1,10,.1,"",Ve.RATE_REF,Ve.RATE_KEY),e.addIncremental(this.pitch,.1,2,.1,"",Ve.PITCH_REF,Ve.PITCH_KEY),e.addIncremental(this.volume,.1,1,.1,"",Ve.VOLUME_REF,Ve.VOLUME_KEY),e.addStringable(this.color,Ve.COLOR_REF,Ve.COLOR_KEY),e.addJSONable(JSON.stringify(this.voice),Ve.VOICE_REF,Ve.VOICE_KEY),e}saveProperty(e){let t=this.store.get(this.TTSSETTINGS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.name!==e.name),i.push(e),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}else{let i=[];i.push(e),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}return e}getProperty(e){let t=this.store.get(this.TTSSETTINGS);if(t){let i=JSON.parse(t);return i=i.filter(r=>r.name===e),i.length===0?void 0:i[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(e){if(e.rate){Hn.default.log("rate "+this.rate),this.rate=e.rate;let t=this.userProperties.getByRef(Ve.RATE_REF);t&&(t.value=this.rate,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.pitch){Hn.default.log("pitch "+this.pitch),this.pitch=e.pitch;let t=this.userProperties.getByRef(Ve.PITCH_REF);t&&(t.value=this.pitch,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.volume){Hn.default.log("volume "+this.volume),this.volume=e.volume;let t=this.userProperties.getByRef(Ve.VOLUME_REF);t&&(t.value=this.volume,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.color){this.color=e.color;let t=this.userProperties.getByRef(Ve.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){Hn.default.log("autoScroll "+this.autoScroll),this.autoScroll=e.autoScroll;let t=this.userProperties.getByRef(Ve.AUTO_SCROLL_REF);t&&(t.value=this.autoScroll,this.saveProperty(t)),this.settingsChangeCallback()}if(e.voice){Hn.default.log("voice "+this.voice),this.voice=e.voice;let t=this.userProperties.getByRef(Ve.VOICE_REF);t&&(t.value=this.voice,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}}applyPreferredVoice(e){var t=e.indexOf(":")!==-1?e.slice(0,e.indexOf(":")):void 0,i=e.indexOf(":")!==-1?e.slice(e.indexOf(":")+1):e;t!==void 0&&i!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:t,lang:i}}):i!==void 0&&t===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:i}})}increase(e){if(e==="rate"){this.userProperties.getByRef(Ve.RATE_REF).increment();let t=this.userProperties.getByRef(Ve.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef(Ve.PITCH_REF).increment();let t=this.userProperties.getByRef(Ve.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef(Ve.VOLUME_REF).increment();let t=this.userProperties.getByRef(Ve.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}decrease(e){if(e==="rate"){this.userProperties.getByRef(Ve.RATE_REF).decrement();let t=this.userProperties.getByRef(Ve.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef(Ve.PITCH_REF).decrement();let t=this.userProperties.getByRef(Ve.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef(Ve.VOLUME_REF).decrement();let t=this.userProperties.getByRef(Ve.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}};I();Xt();tr();mn();ci();DA();Dp();var W1=$e($s());I();var io=class io{constructor(e){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=e=>{let t=null,i=null,r=this;e&&(e.addEventListener("touchstart",function(s){s.changedTouches.length===1&&(t=s)},!1),e.addEventListener("touchend",function(s){if(s.changedTouches.length!==1||!t)return;let o=t.changedTouches[0],a=s.changedTouches[0];if(!o)return;let u=window.devicePixelRatio,l=(o.clientX-a.clientX)/u,c=(o.clientY-a.clientY)/u;if(Math.abs(l)<io.TAP_TOLERANCE&&Math.abs(c)<io.TAP_TOLERANCE){if(i){t=null,i=null;return}if(s.timeStamp-t.timeStamp>io.LONG_PRESS_MS){t=null,i=null;return}t=null,i=s;return}if(i=null,s.timeStamp-t.timeStamp>io.SLOW_SWIPE_MS){t=null;return}let d=(o.clientY-a.clientY)/(o.clientX-a.clientX);if(Math.abs(d)>.5){t=null;return}l<0?r.onBackwardSwipe(s):r.onForwardSwipe(s),t=null},!1))};this.navigator=e}};io.TAP_TOLERANCE=10,io.LONG_PRESS_MS=500,io.SLOW_SWIPE_MS=500;var Hd=io;I();var Ud=class{constructor(e){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.onKeydown=()=>{};this.setupEvents=e=>{e&&(this.focusin(e),this.keydown(e))};this.removeEvents=e=>{if(e){let t=this;e.removeEventListener("focusin",this.onFocusIn(t),!0),e.removeEventListener("keydown",this.onKeyDown(t),!1)}};this.focusin=e=>{let t=this;e.addEventListener("focusin",this.onFocusIn(t),!0)};this.keydown=e=>{let t=this;this.navigator.rights.customKeyboardEvents||e.addEventListener("keydown",this.onKeyDown(t),!1)};this.handlers={};this.navigator=e,this.rtl=!1}onFocusIn(e){return this.handlers.onFocusIn||(this.handlers.onFocusIn=function(t){e.navigator.view?.snap(t.target)})}onKeyDown(e){return this.handlers.onKeyDown||(this.handlers.onKeyDown=function(t){let i=t.target;if(/input|select|option|textarea/i.test(i.tagName)||!(i.ownerDocument||i).defaultView.getSelection().isCollapsed)return;switch(t.key){case"ArrowRight":e.rtl?e.onBackwardSwipe(t):e.onForwardSwipe(t);return;case"ArrowLeft":e.rtl?e.onForwardSwipe(t):e.onBackwardSwipe(t);return}switch(t.code){case"Space":if(t.ctrlKey){e.onBackwardSwipe(t);return}else{e.onForwardSwipe(t);return}}e.onKeydown(t)})}};I();var dR=$e($s()),jd=class{constructor(e){this.enforceSampleRead=(0,dR.default)(e=>{let t=Math.round(e.locations.totalProgression*100),i=!1;this.navigator.sample?.limit&&(i=t<=this.navigator.sample?.limit,this.navigator.view?.layout==="fixed"&&!i&&this.navigator.sample?.minimum&&e.locations.position<=this.navigator.sample?.minimum&&(i=!0));let r={37:1,38:0,39:1,40:1,32:1,33:1,34:1,35:1,36:1};function s(y){y.preventDefault()}function o(y){r[y.keyCode]&&!i&&s(y)}let a=!1,u=Object.defineProperty&&Object.defineProperty({},"passive",{get:function(){a=!0}});window.addEventListener("test",function(){},u);let l=a?{passive:!1}:!1;function c(y){y=y||window.event;let g=Math.max(-1,Math.min(1,y.wheelDelta||-y.detail));return g===-1&&!i&&y.preventDefault(),!1}let d;function f(y){y=y||window.event;let g=y.target||y.srcElement,b=y.touches[0].clientY;if(!(b>d)){if(b<d&&!i)return g.className.match(/\baltNav\b/)||(y.returnValue=!1,y.cancelable&&(y.cancelBubble=!0),y.preventDefault&&y.cancelable&&(y.preventDefault(),y.stopPropagation())),!1}return d=b,!1}function m(y){return y=y||window.event,d=y.touches[0].clientY,!1}window.addEventListener("mousewheel",c,l),window.addEventListener("DOMMouseScroll",c,l),window.addEventListener("keydown",o,l),window.addEventListener("touchmove",f,l),window.addEventListener("touchstart",m,l),i?(this.navigator.iframes[0].focus(),this.navigator.errorMessage&&(this.navigator.errorMessage.style.display="none",this.navigator.errorMessage.style.removeProperty("background-color"))):(this.navigator.iframes[0].blur(),this.navigator.errorMessage&&(this.navigator.errorMessage.style.display="block",this.navigator.errorMessage.style.backgroundColor="rgb(255, 255, 255)",this.navigator.errorMessage.innerHTML=`<span>${this.navigator.sample?.popup}</span>`))},300);this.navigator=e}};hi();Tl();I();var U1=class{constructor(e){this.inner=e}async get(e){return this.maybeDecode(await this.inner.get(e))}async getByHref(e){return this.maybeDecode(await this.inner.getByHref(e))}cancel(e){this.inner.cancel?.(e)}destroy(){this.inner.destroy?.()}maybeDecode(e){if(!gZ(e.mediaType)||!mZ(e.text))return e;try{return{...e,text:bZ(e.text)}}catch{return e}}};function gZ(n){if(!n)return!1;let e=n.toLowerCase();return e==="application/xhtml+xml"||e==="text/html"||e==="application/xml"}function mZ(n){if(!n)return!1;let e=0;for(;e<n.length;){let t=n[e],i=n.charCodeAt(e);if(t===" "||t===`
665
- `||t==="\r"||t===" "||i===65279){e++;continue}return t!=="<"}return!1}function bZ(n){let e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return new TextDecoder().decode(t)}I();var G1=class{constructor(e,t){this.publication=e;this.settings=t;this.objectUrlRegistry=new Map}injectStaticIntoDoc(e,t,i,r){let s=e.head;if(!s)return;let o={publication:this.publication,resourceHref:r,doc:e},a=c=>{let d=this.objectUrlRegistry.get(t);d||(d=[],this.objectUrlRegistry.set(t,d)),d.push(c)},u=c=>{if(c.url)return c.url;if(c.blob){let d=URL.createObjectURL(c.blob);return a(d),d}return null},l=(c,d)=>{d.r2before?s.insertBefore(c,s.firstChild):d.r2default?s.insertBefore(c,s.childNodes[1]):s.appendChild(c)};for(let c of i??[])if(!(c.when&&!c.when(o))){if(c.type==="style"){if(c.fontFamily&&this.settings.initAddedFont(),c.r2after&&c.appearance&&this.settings.initAddedAppearance(),c.systemFont&&!c.url&&!c.blob)continue;let d=u(c);if(!d)continue;let f=yZ(d);j1(f,c.attributes),l(f,{r2before:c.r2before,r2default:c.r2default,r2after:c.r2after})}else if(c.type==="script"){let d=u(c);if(!d)continue;let f=vZ(d,c.async??!1,c.module??!1);j1(f,c.attributes),s.appendChild(f)}else if(c.type==="style-inline"){let d=AZ(c.source);j1(d,c.attributes),l(d,{r2before:c.r2before,r2default:c.r2default,r2after:c.r2after})}else if(c.type==="script-inline"){let d=wZ(c.source,c.async??!1,c.module??!1);j1(d,c.attributes),s.appendChild(d)}}}cleanupForIframe(e){let t=this.objectUrlRegistry.get(e);if(t){for(let i of t)URL.revokeObjectURL(i);this.objectUrlRegistry.delete(e)}}};function yZ(n){let e=document.createElement("link");return e.rel="stylesheet",e.type="text/css",e.href=n,e}function vZ(n,e,t){let i=document.createElement("script");return i.type=t?"module":"text/javascript",i.src=n,i.async=e,i.appendChild(document.createTextNode("")),i}function AZ(n){let e=document.createElement("style");return e.type="text/css",e.textContent=n,e}function wZ(n,e,t){let i=document.createElement("script");return i.type=t?"module":"text/javascript",i.async=e,i.textContent=n,i}function j1(n,e){if(e)for(let[t,i]of Object.entries(e))n.setAttribute(t,i)}I();Gd();var Il=class{constructor(e,t,i){this.inner=e;this.getContent=t;let r=[...i.readingOrder??[],...i.resources??[]];this.publicationResourceHrefs=new Set(r.map(s=>i.getAbsoluteHref(s.href)))}async get(e){if(!this.isPublicationResource(e.href))return this.inner.get(e);let t=await this.getContent(e.href);return t!==void 0?{text:t,headers:{},mediaType:e.type??"application/xhtml+xml",href:e.href}:this.inner.get(e)}async getByHref(e){if(!this.isPublicationResource(e))return this.inner.getByHref(e);let t=await this.getContent(e);return t!==void 0?{text:t,headers:{},mediaType:ro(e),href:e}:this.inner.getByHref(e)}cancel(e){this.inner.cancel?.(e)}destroy(){this.inner.destroy?.()}isPublicationResource(e){return this.publicationResourceHrefs.has(e)}};I();var za=class{constructor(e){this.inner=e;this.cache=new Map;this.pending=new Map}async get(e){let t=this.cache.get(e.href);if(t)return t;let i=this.pending.get(e.href);if(i)return i;let r=this.inner.get(e).then(s=>(this.cache.set(e.href,s),this.pending.delete(e.href),s)).catch(s=>{throw this.pending.delete(e.href),s});return this.pending.set(e.href,r),r}async getByHref(e){let t=this.cache.get(e);if(t)return t;let i=this.pending.get(e);if(i)return i;let r=this.inner.getByHref(e).then(s=>(this.cache.set(e,s),this.pending.delete(e),s)).catch(s=>{throw this.pending.delete(e),s});return this.pending.set(e,r),r}async prefetch(e){if(!(this.cache.has(e.href)||this.pending.has(e.href)))try{await this.get(e)}catch{}}async has(e){return this.cache.has(e.href)}evict(e){this.cache.delete(e)}clear(){this.cache.clear()}cancel(e){this.inner.cancel?.(e)}destroy(){this.cache.clear(),this.pending.clear(),this.inner.destroy?.()}};var wn=$e(jt());HA();var Va=class n extends hl{constructor(t,i=void 0,r=void 0,s,o,a,u,l,c,d,f,m,y,g,b,v){super();this.iframes=[];this.modules=new Go(this.registry);this.fxlZoomKeyHandler=t=>{if(/input|select|option|textarea/i.test(t.target.tagName))return;let i=t.key;if(i==="="||i==="+")this.zoomIn();else if(i==="-")this.zoomOut();else if(i==="0")this.fitToPage();else return;t.preventDefault()};this.sideNavExpanded=!1;this.currentChapterLink={href:""};this.currentSpreadLinks={};this.rights={autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};this.didInitKeyboardEventHandler=!1;this.fxlContentWidth=0;this.fxlContentHeight=0;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.reload=async()=>{let t;if(this.annotator&&(t=await this.annotator.getLastReadingPosition()),t){let i=this.publication.getAbsoluteHref(t.href);wn.default.log(t.href),wn.default.log(i),t.href=i,await this.navigate(t)}};this.savePosition=(0,W1.default)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,W1.default)(()=>{this.view?.atStart()&&this.view?.atEnd()?(this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit(xe.ResourceFits,{href:this.currentChapterLink.href})):this.view?.atEnd()?(this.api?.resourceAtEnd&&this.api?.resourceAtEnd(),this.emit(xe.ResourceEnd,{href:this.currentChapterLink.href})):this.view?.atStart()&&(this.api?.resourceAtStart&&this.api?.resourceAtStart(),this.emit(xe.ResourceStart,{href:this.currentChapterLink.href}))},200);this._blobUrlManager=v,this.highlighter=y,this.highlighter&&(this.highlighter.navigator=this);for(let A of g??[])if(A){if(A.hostType!==nt.Epub){wn.default.warn(`Module "${A.name}" requires host type "${A.hostType}" but navigator is EPUB \u2014 skipping`);continue}this.registry.register(A,this)}if(b)this._fetcher=new za(b);else{let A=new no(m);o?.getContent&&(A=new Il(A,o.getContent,s)),m?.encoded&&(A=new U1(A)),this._fetcher=new za(A)}this.settings=t,this.annotator=i,this.attributes=c??{},this.view=t.view,this.view.attributes=this.attributes,this.view.host={checkResourcePosition:()=>this.checkResourcePosition(),recalculateContentProtection:A=>this.modules.contentProtection?.recalculate(A),isContentProtectionEnabled:()=>!!this.rights.enableContentProtection,isFixedLayout:()=>this.publication.isFixedLayout,isReflowable:()=>this.publication.isReflowable,setDirection:A=>this.setDirection(A)},this.eventHandler=new gd(this),this.touchEventHandler=new Hd(this),this.keyboardEventHandler=new Ud(this),this.initialLastReadingPosition=r,this.publication=s,this.api=o,this.rights=a??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1},this.tts=u,this.injectables=l,this.services=d,this.sample=f,this.requestConfig=m,this.sampleReadEventHandler=new jd(this),this.injectableManager=new G1(s,t)}get fetcher(){return this._fetcher}supports(t){return t===we.Zoom?this.publication.isFixedLayout:t===we.MediaOverlays?this.registry.has(t)&&this.hasMediaOverlays:this.registry.has(t)}getFxlCurrentScale(){let t=this.spreads?.style.transform?.match(/scale\(([^)]+)\)/);return t?parseFloat(t[1]):1}fitToPage(){this.publication.isFixedLayout&&this.handleResize()}zoomIn(){this.publication.isFixedLayout&&this.setFxlScale(this.getFxlCurrentScale()*1.15)}zoomOut(){this.publication.isFixedLayout&&this.setFxlScale(this.getFxlCurrentScale()/1.15)}setFxlScale(t){!this.spreads||!this.fxlZoomContainer||(this.spreads.style.transform="scale("+t+")",this.updateFxlZoomContainer(t))}updateFxlZoomContainer(t){!this.fxlZoomContainer||!this.fxlContentWidth||!this.fxlContentHeight||(this.fxlZoomContainer.style.width=this.fxlContentWidth*t+"px",this.fxlZoomContainer.style.height=this.fxlContentHeight*t+"px",this.spreads.style.width=this.fxlContentWidth+"px",this.spreads.style.height=this.fxlContentHeight+"px",this.fxlHandTool&&requestAnimationFrame(()=>{if(!this.fxlScrollContainer)return;this.fxlScrollContainer.scrollWidth>this.fxlScrollContainer.clientWidth||this.fxlScrollContainer.scrollHeight>this.fxlScrollContainer.clientHeight?this.activateHand():this.deactivateHand()}))}setupFxlPan(){let t=this.fxlScrollContainer;t&&(this.fxlPanOverlay=document.createElement("div"),this.fxlPanOverlay.style.position="absolute",this.fxlPanOverlay.style.top="0",this.fxlPanOverlay.style.left="0",this.fxlPanOverlay.style.width="100%",this.fxlPanOverlay.style.height="100%",this.fxlPanOverlay.style.pointerEvents="none",this.fxlPanOverlay.style.zIndex="1",this.fxlZoomContainer.style.position="relative",this.fxlZoomContainer.appendChild(this.fxlPanOverlay),this.fxlHandTool=new _l({element:t}))}activateHand(){if(!this.publication.isFixedLayout)return;this.fxlPanOverlay&&(this.fxlPanOverlay.style.pointerEvents="auto"),this.fxlHandTool?.activate();let t=document.querySelector("#fxl-pan a");t&&(t.classList.add("dita-active"),t.style.color="#039be5")}deactivateHand(){if(!this.publication.isFixedLayout)return;this.fxlPanOverlay&&(this.fxlPanOverlay.style.pointerEvents="none"),this.fxlHandTool?.deactivate();let t=document.querySelector("#fxl-pan a");t&&(t.classList.remove("dita-active"),t.style.color="")}static async create(t){let i=new this(t.settings,t.annotator||void 0,t.initialLastReadingPosition||void 0,t.publication,t.api,t.rights,t.tts,t.injectables,t.attributes,t.services,t.sample,t.requestConfig,t.highlighter,t.modules,t.fetcher,t.blobUrlManager);return await i.start(t.mainElement,t.headerMenu,t.footerMenu),await i.registry.setupAll(),new Promise(r=>r(i))}stop(){wn.default.log("Iframe navigator stop"),Ae(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),Ae(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),Ae(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ae(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),Ae(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ae(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),Ae(this.tryAgainButton,"click",this.tryAgain.bind(this)),Ae(this.goBackButton,"click",n.goBack.bind(this)),Ae(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),Ae(window,"resize",this.onResize),this.iframes.forEach(t=>{this.injectableManager.cleanupForIframe(t),Ae(t,"resize",this.onResize),t.remove()}),this.didInitKeyboardEventHandler&&this.keyboardEventHandler.removeEvents(document),this.registry.stopAll(),this._fetcher?.destroy?.(),this._blobUrlManager?.destroy()}setDirection(t){let i="";t==="rtl"||t==="ltr"?i=t:t==="auto"&&(i=this.publication.metadata?.readingProgression||this.publication.metadata?.otherMetadata?.["rendition:spread-direction"]||"ltr"),(i==="rtl"||i==="ltr")&&(this.publication.isFixedLayout&&(this.spreads.style.flexDirection=i==="rtl"?"row-reverse":"row"),this.keyboardEventHandler.rtl=i==="rtl",this.api?.direction&&this.api?.direction(i),this.emit(xe.Direction,i))}async start(t,i,r){this.headerMenu=i,this.mainElement=t;try{let m=dt(t,"main#iframe-wrapper");m.style.overflow="auto";let y=fe(t,"main#iframe-wrapper iframe"),g=fe(t,"#second");if(y&&(y.style.verticalAlign="top",this.iframes.push(y)),g&&(g.style.verticalAlign="top",this.iframes.push(g)),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.publication.isFixedLayout&&(this.publication.metadata?.otherMetadata?.["rendition:spread"]??this.publication.metadata?.otherMetadata?.rendition?.spread)==="none"&&(this.settings.columnCount=1),this.iframes.length===0){m.style.overflow="auto";let b=document.createElement("iframe");if(b.setAttribute("SCROLLING","no"),b.setAttribute("allowtransparency","true"),b.style.verticalAlign="top",this.iframes.push(b),this.publication.isFixedLayout){this.spreads=document.createElement("div"),this.firstSpread=document.createElement("div"),this.spreads.style.display="flex",this.spreads.style.transformOrigin="0 0",this.spreads.appendChild(this.firstSpread),this.firstSpread.appendChild(this.iframes[0]),this.fxlScrollContainer=document.createElement("div"),this.fxlScrollContainer.style.position="absolute",this.fxlScrollContainer.style.top="0",this.fxlScrollContainer.style.right="0";let v=document.getElementById("container-view-timeline");this.fxlScrollContainer.style.left=v&&this.rights.enableTimeline?"70px":"0";let A=document.getElementById("reader-info-bottom");this.fxlScrollContainer.style.bottom=A?A.offsetHeight+"px":"0",this.fxlScrollContainer.style.overflow="auto",this.fxlScrollContainer.style.display="flex",this.fxlZoomContainer=document.createElement("div"),this.fxlZoomContainer.style.margin="auto",this.fxlZoomContainer.style.flexShrink="0",this.fxlZoomContainer.style.overflow="hidden",this.attributes?.fixedLayoutShadow!==!1&&(this.fxlZoomContainer.style.padding="12px",this.fxlZoomContainer.style.boxSizing="content-box"),this.fxlZoomContainer.appendChild(this.spreads),this.fxlScrollContainer.appendChild(this.fxlZoomContainer),m.style.position="relative",m.appendChild(this.fxlScrollContainer),document.addEventListener("keydown",this.fxlZoomKeyHandler),this.setupFxlPan();let w="";switch(this.settings.direction){case 0:w="auto";break;case 1:w="ltr";break;case 2:w="rtl";break}this.setDirection(w)}else b.setAttribute("height","100%"),b.setAttribute("width","100%"),m.appendChild(this.iframes[0]);if(this.publication.isFixedLayout)if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){let v=document.createElement("div");this.spreads.appendChild(v);let A=document.createElement("iframe");A.setAttribute("SCROLLING","no"),A.setAttribute("allowtransparency","true"),A.style.opacity="1",A.style.border="none",A.style.overflow="hidden",A.style.verticalAlign="top",this.iframes.push(A),v.appendChild(this.iframes[1]),this.attributes?.fixedLayoutShadow!==!1&&(this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",v.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",v.style.boxShadow="0 0 8px 2px #ccc")}else this.attributes?.fixedLayoutShadow!==!1&&(this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc");else{let v=this.iframes[0],A=this.attributes?.iframe?.padding;A!==void 0?typeof A=="number"?v.style.padding=A+"px":(A.top!==void 0&&(v.style.paddingTop=A.top+"px"),A.bottom!==void 0&&(v.style.paddingBottom=A.bottom+"px"),A.left!==void 0&&(v.style.paddingLeft=A.left+"px"),A.right!==void 0&&(v.style.paddingRight=A.right+"px")):this.attributes?.iframePaddingTop!==void 0&&(v.style.paddingTop=this.attributes.iframePaddingTop+"px")}}if(!this.publication.isFixedLayout){this.iframes.length===2&&this.iframes.pop();let b="";switch(this.settings.direction){case 0:b="auto";break;case 1:b="ltr";break;case 2:b="rtl";break}this.setDirection(b)}if(this.loadingMessage=fe(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=F1,this.loadingMessage.style.display="none"),this.errorMessage=fe(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=cR,this.errorMessage.style.display="none"),this.tryAgainButton=fe(t,"button[class=try-again]"),this.goBackButton=fe(t,"button[class=go-back]"),this.infoTop=fe(t,"div[class='dita-info top']"),this.infoBottom=fe(t,"div[class='dita-info bottom']"),this.headerMenu&&(this.bookTitle=fe(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=fe(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=fe(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=fe(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=fe(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=fe(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=fe(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=fe(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=fe(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=fe(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=fe(this.headerMenu,"#container-view-pagelist")),r&&(this.linksBottom=fe(r,"ul.links.bottom")),r&&(this.linksMiddle=fe(r,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=fe(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=fe(t,"#next-chapter")),r&&(this.nextPageAnchorElement=fe(r,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=fe(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=fe(t,"#previous-chapter")),r&&(this.previousPageAnchorElement=fe(r,"a[rel=prev]")),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.newPosition=void 0,this.newElementId=void 0,this.isBeingStyled=!0,this.isLoading=!0,this.settings.setIframe(this.iframes[0]),this.settings.onSettingsChange(this.handleResize.bind(this)),this.settings.onColumnSettingsChange(this.handleNumberOfIframes.bind(this)),this.settings.onViewChange(this.updateBookView.bind(this)),this.initialLastReadingPosition&&this.annotator?.initLastReadingPosition(this.initialLastReadingPosition),this.headerMenu){var s=fe(this.headerMenu,"#menu-button-search"),o=fe(this.headerMenu,"#menu-button-tts"),a=fe(this.headerMenu,"#menu-button-bookmark"),u=fe(this.headerMenu,"#menu-button-play"),l=fe(this.headerMenu,"#menu-button-pause"),c=fe(this.headerMenu,"#menu-button-mediaoverlay");if(!this.rights.enableBookmarks){a&&a.parentElement?.style.setProperty("display","none");var d=fe(this.headerMenu,"#sidenav-section-bookmarks");d&&d.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var f=fe(this.headerMenu,"#sidenav-section-highlights");f&&f.style.setProperty("display","none")}this.rights.enableTTS||o&&o.parentElement?.style.setProperty("display","none"),this.rights.enableSearch||s&&s.parentElement?.style.setProperty("display","none"),s&&this.publication.isFixedLayout&&s.parentElement?.style.setProperty("display","none"),this.hasMediaOverlays?(u&&u.parentElement?.style.removeProperty("display"),l&&l.parentElement?.style.removeProperty("display"),c&&c.parentElement?.style.removeProperty("display")):(u&&u.parentElement?.style.setProperty("display","none"),l&&l.parentElement?.style.setProperty("display","none"),c&&c.parentElement?.style.setProperty("display","none"))}else s&&s.parentElement?.style.setProperty("display","none"),o&&o.parentElement?.style.setProperty("display","none"),a&&a.parentElement?.style.setProperty("display","none");return this.setupEvents(),await this.loadManifest()}catch(m){return wn.default.error(m),this.abortOnError(m),Promise.reject(m)}}setupEvents(){for(let t of this.iframes)ee(t,"load",this.handleIFrameLoad.bind(this,t));ee(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),ee(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),ee(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ee(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),ee(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ee(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),ee(this.tryAgainButton,"click",this.tryAgain.bind(this)),ee(this.goBackButton,"click",n.goBack.bind(this)),ee(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),ee(window,"resize",this.onResize);for(let t of this.iframes)ee(t,"resize",this.onResize)}updateBookView(t){this.view?.layout==="fixed"?(this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.eventHandler&&(this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousChapterClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextChapterClick.bind(this),this.keyboardEventHandler.onKeydown=this.handleKeydownFallthrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this))):(this.settings.isPaginated().then(i=>{if(i)this.view.height=qu(this.iframes[0],this.attributes),this.infoBottom&&this.infoBottom.style.removeProperty("display"),document.body.onscroll=()=>{},this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="unset"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="unset"),this.chapterTitle&&(this.chapterTitle.style.display="inline"),this.chapterPosition&&(this.chapterPosition.style.display="inline"),this.remainingPositions&&(this.remainingPositions.style.display="inline"),this.eventHandler&&(this.eventHandler.onInternalLink=this.handleInternalLink.bind(this),this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this),this.keyboardEventHandler.onKeydown=this.handleKeydownFallthrough.bind(this));else{this.infoBottom&&(this.infoBottom.style.display="none"),this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),this.view?.layout==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")):this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"));let r=(0,W1.default)(()=>{this.isScrolling=!1},200),s=dt(document,"#iframe-wrapper");s.onscroll=async()=>{this.isScrolling=!0,await this.savePosition(),this.view?.atEnd(),this.view?.layout==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")):(this.settings.isPaginated().then(o=>{o||(this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))}),this.checkResourcePosition()),r()},this.chapterTitle&&(this.chapterTitle.style.display="none"),this.chapterPosition&&(this.chapterPosition.style.display="none"),this.remainingPositions&&(this.remainingPositions.style.display="none"),this.eventHandler&&(this.eventHandler.onInternalLink=this.handleInternalLink.bind(this),this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this),this.keyboardEventHandler.onKeydown=this.handleKeydownFallthrough.bind(this))}}),t?.skipDrawingAnnotations||setTimeout(async()=>{await this.highlighter?.prepareContainers(this.iframes[0].contentWindow),this.highlighter&&(this.rights.enableAnnotations&&this.modules.annotations&&await this.modules.annotations.drawHighlights(),this.rights.enableBookmarks&&this.modules.bookmarks&&await this.modules.bookmarks.drawBookmarks(),this.rights.enableSearch&&this.modules.search&&(await this.highlighter.destroyHighlights(1),this.modules.search.drawSearch()),this.rights.enablePageBreaks&&this.modules.pageBreaks&&(await this.highlighter.destroyHighlights(3),await this.modules.pageBreaks.drawPageBreaks()),this.rights.enableDefinitions&&this.modules.definitions&&await this.modules.definitions.drawDefinitions())},200))}async loadManifest(){try{let t=(l,c,d=!1)=>{var f=document.createElement("ul");d&&(f=document.createElement("ol")),f.className="sidenav-toc";for(let m of c){let y=document.createElement("li"),g=document.createElement("a"),b=document.createElement("span");g.className="chapter-link",g.tabIndex=-1;let v="";m.href?(v=this.publication.getAbsoluteHref(m.href),g.href=v,g.innerHTML=m.title||"",y.appendChild(g)):(b.innerHTML=m.title||"",b.className="chapter-title",y.appendChild(b)),m.children?.items&&m.children.items.length>0&&t(y,m.children.items,!0),f.appendChild(y)}ee(f,"click",m=>{if(m.preventDefault(),m.stopPropagation(),m.target&&m.target.tagName.toLowerCase()==="a"){let y=m.target;if(y.className.indexOf("active")!==-1)this.hideView();else{let g={progression:0};if(y.href.indexOf("#")!==-1){let v=y.href.slice(y.href.indexOf("#")+1);v!==void 0&&(g={fragment:v})}let b={href:y.href,locations:g,type:y.type,title:y.title};this.hideView(),this.navigate(b)}}}),l.appendChild(f)},i=this.publication.tableOfContents,r=this.publication.landmarks,s=this.publication.pageList;this.tocView&&(i.length?t(this.tocView,i):this.tocView.parentElement?.parentElement?.removeChild(this.tocView.parentElement)),this.pageListView&&(s?.length?t(this.pageListView,s):this.pageListView.parentElement?.parentElement?.removeChild(this.pageListView.parentElement)),this.landmarksView&&(r?.length?t(this.landmarksView,r):this.landmarksSection.parentElement?.removeChild(this.landmarksSection));let o;this.annotator&&(o=await this.annotator.getLastReadingPosition());let a=this.publication.getStartLink(),u;if(a&&a.href&&(u=this.publication.getAbsoluteHref(a.href)),o){let l=this.publication.getAbsoluteHref(o.href);wn.default.log(o.href),wn.default.log(l),o.href=l,await this.navigate(o)}else if(u){let l={href:u,locations:{progression:0},created:new Date,title:a?.title};await this.navigate(l)}return new Promise(l=>l())}catch(t){return wn.default.error(t),this.abortOnError(t),new Promise((i,r)=>r(t)).catch(()=>{})}}async handleIFrameLoad(t){this.errorMessage&&(this.errorMessage.style.display="none"),this.showLoadingMessageAfterDelay();try{let i=0;this.newPosition&&(i=this.newPosition.locations.progression),await this.handleResize(),this.updateBookView({skipDrawingAnnotations:!0}),await this.settings.applyProperties();let r=this.currentChapterLink.href;if(r){let c=this.publication.getPreviousSpineItem(r);c&&c.href&&(this.previousChapterLink={href:c.href,title:c.title,type:c.type})}this.previousChapterAnchorElement&&(this.previousChapterLink&&this.previousChapterLink.href?(this.previousChapterAnchorElement.href=this.publication.getAbsoluteHref(this.previousChapterLink.href),this.previousChapterAnchorElement.className=this.previousChapterAnchorElement.className.replace(" disabled","")):(this.previousChapterAnchorElement.removeAttribute("href"),this.previousChapterAnchorElement.className+=" disabled"));let s=this.publication.getNextSpineItem(r);s?this.nextChapterLink={href:s.href,title:s.title,type:s.type}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink&&this.nextChapterLink.href?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.modules.history&&this.modules.history.setup(),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(r),this.publication.metadata?.title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.metadata?.title.toString());let o=this.publication.getSpineItem(r);o!==void 0&&(this.currentChapterLink.title=o.title,this.currentChapterLink.type=o.type);let a=this.publication.getTOCItem(r);this.currentTocUrl!==void 0&&(a=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&a!==void 0&&a.title&&(this.currentChapterLink.title=a.title),!this.currentChapterLink.type&&a!==void 0&&a.type&&(this.currentChapterLink.title=a.title),this.currentChapterLink.title?(this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"),this.api?.chapterInfo&&this.api.chapterInfo(this.currentChapterLink.title),this.emit(xe.ChapterInfo,this.currentChapterLink.title)):(this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),this.api?.chapterInfo&&this.api.chapterInfo(void 0),this.emit(xe.ChapterInfo,void 0)),this.view?.layout!=="fixed"&&this.highlighter!==void 0&&await this.highlighter.initialize(t);let l=t.contentDocument?.body?.querySelector("details");if(l){let c=this;l.addEventListener("toggle",async d=>{await c.view?.setIframeHeight?.(t)})}if(this.eventHandler&&(this.eventHandler.setupEvents(t.contentDocument),this.touchEventHandler.setupEvents(t.contentDocument),this.keyboardEventHandler.setupEvents(t.contentDocument),this.touchEventHandler.setupEvents(this.errorMessage),this.didInitKeyboardEventHandler||(this.keyboardEventHandler.keydown(document),this.didInitKeyboardEventHandler=!0)),this.publication.isFixedLayout&&t.contentDocument&&t.contentDocument.addEventListener("keydown",this.fxlZoomKeyHandler),this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(t.height="0",this.view?.setIframeHeight?.(t)),this.rights.enableContentProtection&&this.modules.contentProtection&&await this.modules.contentProtection.initialize(t),this.rights.enableConsumption&&this.modules.consumption&&await this.modules.consumption.initialize(t),this.rights.enableAnnotations&&this.modules.annotations&&await this.modules.annotations.initialize(t),this.rights.enableBookmarks&&this.modules.bookmarks&&await this.modules.bookmarks.initialize(),this.rights.enableLineFocus&&this.modules.lineFocus&&await this.modules.lineFocus.initialize(t),this.rights.enableTTS&&this.modules.tts){let c=t.contentDocument?.body;await this.modules.tts.initialize(c)}return this.rights.enableTimeline&&this.modules.timeline&&await this.modules.timeline.initialize(),this.rights.enableMediaOverlays&&this.modules.mediaOverlays&&this.hasMediaOverlays&&await this.modules.mediaOverlays.initialize(),setTimeout(async()=>{if(this.newElementId){let c=t.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(c),this.newElementId=void 0}else if(this.newPosition&&this.newPosition.highlight){let c=this.newPosition.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;c&&this.view?.goToCssSelector(c)}else i&&i>=0&&(this.view?.layout!=="fixed"&&this.view?.padOddColumns?.(),this.view?.goToProgression(i));if(this.newPosition=void 0,this.rights?.enableContentProtection&&this.modules.contentProtection!==void 0&&await this.modules.contentProtection.recalculate(10),this.hideLoadingMessage(),this.showIframeContents(t),this.rights.enableMediaOverlays&&this.modules.mediaOverlays&&this.hasMediaOverlays){let c=this.currentLink();await this.modules.mediaOverlays?.initializeResource(c)}await this.updatePositionInfo(),await this.view?.setSize(),setTimeout(()=>{this.modules.mediaOverlays&&(this.modules.mediaOverlays.settings.resourceReady=!0,this.modules.mediaOverlays.settings.playing&&this.modules.mediaOverlays.bindClickHandler())},300)},200),new Promise(c=>c())}catch(i){return wn.default.error(i),this.abortOnError(i),Promise.reject(i)}}abortOnError(t){if(this.api?.onError){let i=t instanceof Error?t:typeof t=="string"?new Error(t):new Error("An unknown error occurred in the EpubNavigator.");this.api.onError(i),this.emit(xe.Error,i)}else this.errorMessage&&(this.errorMessage.style.display="block"),this.isLoading&&this.hideLoadingMessage()}tryAgain(){this.precessContentForIframe()}precessContentForIframe(){let t=this;var i=this.publication.getSpineIndex(this.currentChapterLink.href);let s=(i!==void 0?this.publication.readingOrder?.[i]:void 0)?.properties?.page;var o;s==="left"?o=!0:s==="right"?o=!1:s==="center"?o=!0:o=(i??0)%2===1,this.showLoadingMessageAfterDelay(),this.currentSpreadLinks={};let a=async f=>(await t._fetcher.getByHref(f)).text;function u(f,m,y){let b=new DOMParser().parseFromString(f,"application/xhtml+xml");if(b.head&&b.getElementsByTagName("base").length===0&&b.head.insertBefore(n.createBase(m),b.head.firstChild),t.injectableManager.injectStaticIntoDoc(b,y,t.injectables,m),t._blobUrlManager){let A=t.publication.getRelativeHref(m);t._blobUrlManager.rewriteDom(b,A)}return b.documentElement.outerHTML}function l(f,m){t.injectableManager.cleanupForIframe(t.iframes[0]);let y=u(f,m,t.iframes[0]),g=t.iframes[0].contentDocument;g&&(g.open(),g.write(y),g.close())}function c(f,m){t.injectableManager.cleanupForIframe(t.iframes[1]);let y=u(f,m,t.iframes[1]),g=t.iframes[1].contentDocument;g&&(g.open(),g.write(y),g.close())}let d=async(f,m)=>{let y=await a(f);m===0?l.call(t,y,f):c.call(t,y,f)};if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(o){if(this.currentSpreadLinks.left={href:this.currentChapterLink.href},d(this.currentChapterLink.href,0),this.iframes.length===2)if(s!=="center"&&(i??0)<this.publication.readingOrder.length-1){let f=this.publication.getNextSpineItem(this.currentChapterLink.href);if(f){let m=this.publication.getAbsoluteHref(f.href);this.currentSpreadLinks.right={href:m},d(m,1)}}else this.injectableManager.cleanupForIframe(this.iframes[1]),this.iframes[1].src="about:blank",this.currentSpreadLinks.right=void 0}else{if((i??0)>0){let f=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(f){let m=this.publication.getAbsoluteHref(f.href);this.currentSpreadLinks.left={href:m},d(m,0)}}else this.injectableManager.cleanupForIframe(this.iframes[0]),this.iframes[0].src="about:blank",this.currentSpreadLinks.left=void 0;this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},d(this.currentChapterLink.href,1))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},d(this.currentChapterLink.href,0);else this.currentSpreadLinks.left={href:this.currentChapterLink.href},d(this.currentChapterLink.href,0);this.publication.isFixedLayout&&setTimeout(()=>{let f,m,y;if(i===0&&this.iframes?.length===2?y=this.iframes[1].contentDocument:y=this.iframes[0].contentDocument,y&&y.body&&(f=getComputedStyle(y.body).height,m=getComputedStyle(y.body).width,parseInt(f.toString().replace("px",""))===0||parseInt(m.toString().replace("px",""))===0)){let x=Ni(y,"head");if(x){let C=fe(x,"meta[name=viewport]");if(C){var g=C.content,b=g.split(",").reduce((T,k)=>{var[_,R]=k.match(/[^\s;=]+/g);return T[_]=isNaN(Number(R))?R:+R,T},{});f=b.height+"px",m=b.width+"px"}}}if(m){if(!this.fxlScrollContainer)return;let x=this.attributes?.fixedLayoutMargin??100,C=parseInt(m.toString().replace("px","")),T=parseInt(f.toString().replace("px",""));var v=(this.fxlScrollContainer.clientWidth-x)/(this.iframes.length===2?C*2+x*2:C),A=(this.fxlScrollContainer.clientHeight-x)/T,w=Math.min(v,A);this.spreads.style.transform="scale("+w+")";for(let k of this.iframes)k.style.height=f,k.style.width=m,k.parentElement&&(k.parentElement.style.height=f);this.fxlContentWidth=this.iframes.length===2?C*2:C,this.fxlContentHeight=T,this.updateFxlZoomContainer(w)}},400)}static goBack(){window.history.back()}handleEditClick(t){var i=t.target;if(this.headerMenu){var r=fe(document,".sidenav");i.className.indexOf(" dita-active")===-1?(i.className+=" dita-active",r.className+=" expanded",i.innerText="unfold_less",this.sideNavExpanded=!0,this.modules.bookmarks?.showBookmarks(),this.modules.annotations?.showHighlights()):(i.className=i.className.replace(" dita-active",""),r.className=r.className.replace(" expanded",""),i.innerText="unfold_more",this.sideNavExpanded=!1,this.modules.bookmarks?.showBookmarks(),this.modules.annotations?.showHighlights())}t.preventDefault(),t.stopPropagation()}get hasMediaOverlays(){return this.publication.hasMediaOverlays}startReadAloud(){this.rights.enableTTS&&this.modules.tts?.speakPlay()}startReadAlong(){this.rights.enableMediaOverlays&&this.modules.mediaOverlays!==void 0&&this.hasMediaOverlays&&this.modules.mediaOverlays?.startReadAloud()}stopReadAloud(){this.rights.enableTTS&&this.highlighter?.stopReadAloud()}stopReadAlong(){if(this.rights.enableMediaOverlays&&this.modules.mediaOverlays!==void 0&&this.hasMediaOverlays){let t=this.modules.mediaOverlays.settings.playing;this.modules.mediaOverlays?.stopReadAloud(),t&&this.emit(xe.ReadAlongStopped,"stopped")}}pauseReadAloud(){this.rights.enableTTS&&(this.modules.tts?.speakPause(),this.modules.annotations!==void 0&&this.modules.annotations.drawHighlights())}pauseReadAlong(){this.rights.enableMediaOverlays&&this.modules.mediaOverlays!==void 0&&this.hasMediaOverlays&&this.modules.mediaOverlays?.pauseReadAloud()}resumeReadAloud(){this.rights.enableTTS&&this.modules.tts?.speakResume()}resumeReadAlong(){this.rights.enableMediaOverlays&&this.modules.mediaOverlays!==void 0&&this.hasMediaOverlays&&this.modules.mediaOverlays?.resumeReadAloud()}totalResources(){return this.publication.readingOrder.length}mostRecentNavigatedTocItem(){return this.publication.getRelativeHref(this.currentTOCRawLink)}currentResource(){let t=this.currentChapterLink.href;return this.publication.getSpineIndex(t)}currentLink(){if(this.settings.columnCount!==1&&this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0){let i=this.publication.getSpineItem(this.currentSpreadLinks.left.href),r=this.publication.getSpineItem(this.currentSpreadLinks.right.href);return[i,r]}let t=this.currentChapterLink.href;return[this.publication.getSpineItem(t)]}tableOfContents(){return this.publication.tableOfContents}landmarks(){return this.publication.landmarks}pageList(){return this.publication.pageList}readingOrder(){return this.publication.readingOrder}atStart(){return this.view?.atStart()??!1}atEnd(){return this.view?.atEnd()??!1}previousPage(){this.handlePreviousPageClick(void 0)}nextPage(){this.handleNextPageClick(void 0)}previousResource(){this.handlePreviousChapterClick(void 0)}nextResource(){this.handleNextChapterClick(void 0)}goTo(t){let i=t.locations??{progression:0};if(t.href.indexOf("#")!==-1){let o=t.href.slice(t.href.indexOf("#")+1);o!==void 0&&(i={...i,fragment:o})}let r={...t};r.locations=i;let s=this.publication.getAbsoluteHref(t.href);wn.default.log(t.href),wn.default.log(s),r.href=s,this.stopReadAloud(),this.navigate(r)}currentLocator(){let t;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let i=this.publication.positionsByHref(this.publication.getRelativeHref(this.currentChapterLink.href)),r=Math.ceil((this.view?.getCurrentPosition()??0)*(i.length-1));t=i[r]}else{let i=this.publication.getTOCItem(this.currentChapterLink.href);i&&(this.currentTocUrl!==void 0&&(i=this.publication.getTOCItem(this.currentTocUrl)),i===void 0&&(i=this.publication.getTOCItemAbsolute(this.currentChapterLink.href)),i&&(t={href:i.href,type:this.currentChapterLink.type,title:this.currentChapterLink.title,locations:{}}))}return t&&(!t.title&&this.currentChapterLink.title&&(t.title=this.currentChapterLink.title),t.locations.progression=this.view?.getCurrentPosition(),t.displayInfo={resourceScreenIndex:Math.round(this.view?.getCurrentPage()??0),resourceScreenCount:Math.round(this.view?.getPageCount()??0)}),t}positions(){return this.publication.positions??[]}goToPosition(t){if(this.publication.positions){let i=this.publication.positions.filter(r=>r.locations.position===parseInt(String(t)))[0];this.goTo(i)}}async goToPage(t){this.modules.pageBreaks!==void 0&&await this.modules.pageBreaks.goToPageNumber(t)}snapToSelector(t){let i=this.iframes[0].contentDocument;if(i){wn.default.log(t);let r=i.querySelectorAll(t);r.length>0&&this.view?.snap(r[0])}}applyAttributes(t){this.attributes=t??{},this.view.attributes=this.attributes,this.handleResize()}handlePreviousPageClick(t){this.stopReadAloud(),this.view?.layout==="fixed"?this.handlePreviousChapterClick(t):(this.view?.atStart()?this.handlePreviousChapterClick(t):(this.view?.goToPreviousPage?.(),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))}handleNextPageClick(t){let i=!0;if(this.sample?.isSampleRead&&this.publication.positions){let r=this.currentLocator(),s=Math.round((r.locations.totalProgression??0)*100);this.sample?.limit&&(i=s<=this.sample?.limit,this.view?.layout==="fixed"&&((!i&&this.sample?.minimum&&r.locations.position)??0<=(this.sample?.minimum??0))&&(i=!0))}(i&&this.sample?.isSampleRead&&this.publication.positions||!this.sample?.isSampleRead||!this.publication.positions)&&(this.stopReadAloud(),this.view?.layout==="fixed"?this.handleNextChapterClick(t):(this.view?.atEnd()?this.handleNextChapterClick(t):(this.view?.goToNextPage?.(),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))),!i&&this.sample?.isSampleRead&&this.publication.positions&&t&&(t.preventDefault(),t.stopPropagation())}handleClickThrough(t){this.api?.clickThrough&&this.api?.clickThrough(t),this.emit(xe.Click,t)}handleInternalLink(t){let i=t.target,r={progression:0},s=i;if(s.href.indexOf("#")!==-1){let a=s.href.slice(s.href.indexOf("#")+1);a!==void 0&&(r={fragment:a})}let o={href:s.href,locations:r,type:s.type,title:s.title};t.preventDefault(),t.stopPropagation(),this.stopReadAloud(),this.navigate(o)}handleNumberOfIframes(){if(this.publication.isFixedLayout){if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){if(this.iframes.length===1){var t=document.createElement("iframe");t.setAttribute("SCROLLING","no"),t.setAttribute("allowtransparency","true"),t.style.opacity="1",t.style.border="none",t.style.overflow="hidden",this.iframes.push(t)}let i=document.createElement("div");this.spreads.appendChild(i),i.appendChild(this.iframes[1]),this.attributes?.fixedLayoutShadow!==!1&&(this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",i.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",i.style.boxShadow="0 0 8px 2px #ccc")}else this.iframes.length===2&&(this.iframes.pop(),this.spreads.lastChild&&this.spreads.removeChild(this.spreads.lastChild)),this.attributes?.fixedLayoutShadow!==!1&&(this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc");this.precessContentForIframe()}}async handleResize(){if(this.isScrolling)return;if(this.publication.isFixedLayout){var t=this.publication.getSpineIndex(this.currentChapterLink.href);if(this.fxlScrollContainer){let l,c,d;if(t===0&&this.iframes?.length===2?d=this.iframes[1].contentDocument:d=this.iframes[0].contentDocument,!d)return;d.body&&(l=getComputedStyle(d.body).height,c=getComputedStyle(d.body).width);let f=Ni(d,"head");if(f){let b=fe(f,"meta[name=viewport]");if(b){var i=b.content,r={};i.split(",").forEach(v=>{let A=v.match(/[^\s;=]+/g);if(A&&A.length>=2){let[w,x]=A;r[w]=isNaN(Number(x))?x:+x}}),(parseInt(String(r.height))!==0||parseInt(String(r.width))!==0)&&(l=r.height.toString().endsWith("px")?r.height:r.height+"px",c=r.width.toString().endsWith("px")?r.width:r.width+"px")}}let m=this.attributes?.fixedLayoutMargin??100,y=parseInt(c.toString().endsWith("px")?c?.replace("px",""):c),g=parseInt(l.toString().replace("px",""));var s=(this.fxlScrollContainer.clientWidth-m)/(this.iframes.length===2?y*2+m*2:y),o=(this.fxlScrollContainer.clientHeight-m)/g,a=Math.min(s,o);this.spreads.style.transform="scale("+a+")";for(let b of this.iframes)b.style.height=l,b.style.width=c,b.parentElement&&(b.parentElement.style.height=l);this.fxlContentWidth=this.iframes.length===2?y*2:y,this.fxlContentHeight=g,this.updateFxlZoomContainer(a)}}let u=this.view?.getCurrentPosition();await this.settings.applyProperties(),this.infoTop&&(this.infoTop.style.height="0px"),this.infoTop&&(this.infoTop.style.minHeight="0px"),this.view?.layout!=="fixed"&&this.settings.isPaginated().then(l=>{l?(this.view.height=qu(this.iframes[0],this.attributes),this.infoBottom&&this.infoBottom.style.removeProperty("display")):this.infoBottom&&(this.infoBottom.style.display="none")}),setTimeout(()=>{this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&this.view?.setIframeHeight?.(this.iframes[0])},100),setTimeout(async()=>{u&&this.view?.goToProgression(u),this.updatePositionInfo(!1),this.modules.contentProtection!==void 0&&await this.modules.contentProtection.handleResize(),this.modules.annotations!==void 0&&await this.modules.annotations.handleResize(),this.modules.bookmarks!==void 0&&await this.modules.bookmarks.handleResize(),this.modules.search!==void 0&&await this.modules.search.handleResize(),this.modules.definitions!==void 0&&await this.modules.definitions.handleResize(),this.modules.pageBreaks!==void 0&&await this.modules.pageBreaks.handleResize(),this.modules.lineFocus!==void 0&&this.modules.lineFocus.handleResize(),this.modules.history!==void 0&&await this.modules.history.handleResize()},150)}updatePositionInfo(t=!0){if(this.view?.layout==="fixed")this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");else if(this.view?.isPaginated()){let i=this.currentLocator();if(i){let r=i.displayInfo.resourceScreenIndex,s=i.displayInfo.resourceScreenCount;this.chapterPosition&&(this.chapterPosition.innerHTML="Page "+r+" of "+s),this.api?.positionInfo&&this.api.positionInfo(i),this.emit(xe.PositionInfo,i)}}else this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");t&&this.savePosition()}handlePreviousChapterClick(t){if(this.view?.layout==="fixed"&&this.settings.columnCount!==1){let i=this.publication.getSpineIndex(this.currentChapterLink.href)??0;i=i-2,i<0&&(i=0);let r=this.publication.readingOrder[i],s={href:this.publication.getAbsoluteHref(r.href),locations:{progression:0},type:r.type,title:r.title};this.stopReadAloud(),this.navigate(s,!1)}else if(this.previousChapterLink){let i={href:this.publication.getAbsoluteHref(this.previousChapterLink.href),locations:{progression:1},type:this.previousChapterLink.type,title:this.previousChapterLink.title};this.stopReadAloud(),this.navigate(i,!1)}t&&(t.preventDefault(),t.stopPropagation())}handleNextChapterClick(t){if(this.view?.layout==="fixed"&&this.settings.columnCount!==1){let i=this.publication.getSpineIndex(this.currentChapterLink.href)??0;i=i+2,i>=this.publication.readingOrder.length-1&&(i=this.publication.readingOrder.length-1);let r=this.publication.readingOrder[i],s={href:this.publication.getAbsoluteHref(r.href),locations:{progression:0},type:r.type,title:r.title};this.stopReadAloud(),this.navigate(s,!1)}else if(this.nextChapterLink){let i={href:this.publication.getAbsoluteHref(this.nextChapterLink.href),locations:{progression:0},type:this.nextChapterLink.type,title:this.nextChapterLink.title};this.stopReadAloud(),this.navigate(i,!1)}t&&(t.preventDefault(),t.stopPropagation())}handleKeydownFallthrough(t){this.api?.keydownFallthrough&&this.api?.keydownFallthrough(t),this.emit(xe.KeyDown,t)}hideView(){this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(document.body.style.overflow="auto")}setActiveTOCItem(t){if(this.tocView){let i=Array.prototype.slice.call(this.tocView.querySelectorAll("li > a"));for(let s of i)s.className=s.className.replace(" dita-active","");let r=this.tocView.querySelector('li > a[href^="'+t+'"]');r&&(r.className+=" dita-active")}}async navigate(t,i=!0){if(this.rights.enableConsumption&&this.modules.consumption&&i&&this.modules.consumption.startReadingSession(t),this.modules.history&&await this.modules.history.push(t,i),this.publication.getTOCItem(t.href)){var s=!1;if(t.href.indexOf("#")!==-1){let o=t.href.slice(0,t.href.indexOf("#"));o===this.currentChapterLink.href&&(s=!0),this.currentChapterLink.href=o,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title}else t.href===this.currentChapterLink.href&&(s=!0),this.currentChapterLink.href=t.href,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title;if(this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0&&(t.href===this.currentSpreadLinks.left.href||t.href===this.currentSpreadLinks.right.href))return;if(s){if(t.href.indexOf("#")!==-1){let d=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:d}}if(this.newPosition=t,this.currentTOCRawLink=t.href,t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.view?.layout!=="fixed"&&this.view?.padOddColumns?.(),this.newElementId){for(let d of this.iframes){let f=d.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(f)}this.newElementId=void 0}else if(t.highlight){let d=t.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;d&&this.view?.goToCssSelector(d)}else this.view?.goToProgression(t.locations.progression??0);let o=this.currentChapterLink.href,a=this.publication.getPreviousSpineItem(o);a&&a.href&&(this.previousChapterLink={href:a.href,type:a.type,title:a.title}),this.previousChapterAnchorElement&&(this.previousChapterLink?(this.previousChapterAnchorElement.href=this.publication.getAbsoluteHref(this.previousChapterLink.href),this.previousChapterAnchorElement.className=this.previousChapterAnchorElement.className.replace(" disabled","")):(this.previousChapterAnchorElement.removeAttribute("href"),this.previousChapterAnchorElement.className+=" disabled"));let u=this.publication.getNextSpineItem(o);u?this.nextChapterLink={href:u.href,type:u.type,title:u.title}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(o),this.publication.metadata?.title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.metadata?.title.toString());let l=this.publication.getSpineItem(o);l!==void 0&&(this.currentChapterLink.title=l.title,this.currentChapterLink.type=l.type);let c=this.publication.getTOCItem(o);this.currentTocUrl!==void 0&&(c=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&c!==void 0&&c.title&&(this.currentChapterLink.title=c.title),!this.currentChapterLink.type&&c!==void 0&&c.type&&(this.currentChapterLink.title=c.title),this.currentChapterLink.title?(this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"),this.api?.chapterInfo&&this.api.chapterInfo(this.currentChapterLink.title),this.emit(xe.ChapterInfo,this.currentChapterLink.title)):(this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),this.api?.chapterInfo&&this.api.chapterInfo(void 0),this.emit(xe.ChapterInfo,void 0)),await this.updatePositionInfo()}else this.modules.lineFocus!==void 0&&this.modules.lineFocus.disableLineFocus(!1),this.modules.search!==void 0&&this.modules.search.clearSearch(),t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.hideIframeContents(),this.showLoadingMessageAfterDelay(),t.locations===void 0&&(t.locations={progression:0}),this.newPosition=t,this.currentTOCRawLink=t.href,this.precessContentForIframe(),this.rights.enableContentProtection&&this.modules.contentProtection!==void 0&&await this.modules.contentProtection.initializeResource(),this.rights.enableMediaOverlays&&this.modules.mediaOverlays!==void 0&&this.hasMediaOverlays&&await this.modules.mediaOverlays.initializeResource(this.currentLink()),this.rights.enableContentProtection&&this.modules.contentProtection!==void 0&&await this.modules.contentProtection.recalculate(300),this.modules.bookmarks&&(await this.modules.bookmarks.drawBookmarks(),await this.modules.bookmarks.showBookmarks()),this.modules.pageBreaks&&(await this.highlighter?.destroyHighlights(3),await this.modules.pageBreaks.drawPageBreaks()),this.rights.enableSearch&&this.modules.search!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(1),this.modules.search.drawSearch()),this.rights.enableDefinitions&&this.modules.definitions&&this.highlighter&&await this.modules.definitions.drawDefinitions(),this.rights.enableConsumption&&this.modules.consumption&&this.modules.consumption.continueReadingSession(t),this.view?.layout==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit(xe.ResourceFits,{href:this.currentChapterLink.href})):this.settings.isPaginated().then(o=>{o||(this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))})}else{let o=this.publication.getStartLink(),a;if(o&&o.href&&(a=this.publication.getAbsoluteHref(o.href),a)){let u={href:a,locations:{progression:0},created:new Date,title:o.title};await this.navigate(u)}}}showIframeContents(t){this.isBeingStyled=!1,setTimeout(()=>{this.isBeingStyled||(t.style.opacity="1",t.style.border="none",t.style.overflow="hidden")},150)}showLoadingMessageAfterDelay(){this.isLoading=!0,this.isLoading&&this.loadingMessage&&(this.loadingMessage.style.display="block",this.loadingMessage.classList.add("is-loading")),this.modules.mediaOverlays!==void 0&&(this.modules.mediaOverlays.settings.resourceReady=!1)}hideIframeContents(){this.isBeingStyled=!0,this.iframes.forEach(t=>{t.style.opacity="0",t.style.border="none",t.style.overflow="hidden"})}hideLoadingMessage(){setTimeout(()=>{if(this.isLoading=!1,this.loadingMessage&&(this.loadingMessage.style.display="none",this.loadingMessage.classList.remove("is-loading")),this.view?.layout!=="fixed"&&(this.view?.padOddColumns?.(),this.view?.atStart()&&this.view?.atEnd()?(this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit(xe.ResourceFits,{href:this.currentChapterLink.href})):this.view?.atEnd()?(this.api?.resourceAtEnd&&this.api?.resourceAtEnd(),this.emit(xe.ResourceEnd,{href:this.currentChapterLink.href})):this.view?.atStart()&&(this.api?.resourceAtStart&&this.api?.resourceAtStart(),this.emit(xe.ResourceStart,{href:this.currentChapterLink.href}))),this.api?.resourceReady&&this.api?.resourceReady(),this.emit(xe.ResourceReady,{href:this.currentChapterLink.href}),this.registry.notifyResourceReady(),this._fetcher.prefetch){let t=this.publication.readingOrder.findIndex(i=>i.href&&this.publication.getAbsoluteHref(i.href)===this.currentChapterLink.href);if(t>=0){let i=this.publication.readingOrder[t+1],r=this.publication.readingOrder[t-1];i&&this._fetcher.prefetch({...i,href:this.publication.getAbsoluteHref(i.href)}),r&&this._fetcher.prefetch({...r,href:this.publication.getAbsoluteHref(r.href)})}}},150)}saveCurrentReadingPosition(){if(this.annotator){var t=this.publication.getTOCItem(this.currentChapterLink.href);this.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.currentChapterLink.href));let i={progression:this.view?.getCurrentPosition()};if(t){if(t.href.indexOf("#")!==-1){let s=t.href.slice(t.href.indexOf("#")+1);s!==void 0&&(i={progression:this.view?.getCurrentPosition(),fragment:s})}let r;if(this.publication.positions&&this.publication.positions.length>0){let s=this.publication.positionsByHref(this.publication.getRelativeHref(t.href));if(s.length>0){let o=Math.ceil((i.progression??0)*(s.length-1)),a=s[o];a&&(a.locations.fragment=i.fragment,r={...a,href:t.href,created:new Date,title:this.currentChapterLink.title})}}else r={href:t.href,locations:i,created:new Date,type:this.currentChapterLink.type,title:this.currentChapterLink.title};r&&(this.sample?.isSampleRead&&this.publication.positions&&this.sampleReadEventHandler?.enforceSampleRead(r),this.api?.updateCurrentLocation?this.api?.updateCurrentLocation(r).then(async s=>(wn.default.log("api updated current location",r),this.annotator?.saveLastReadingPosition(r))):(wn.default.log("save last reading position",r),this.annotator.saveLastReadingPosition(r)),this.emit(xe.LocationChanged,r),this.modules.consumption&&this.modules.consumption.continueReadingSession(r))}}}static createBase(t){let i=document.createElement("base");return i.target="_self",i.href=t,i}activateMarker(t,i){let r=this.modules.annotations;r!==void 0&&(r.activeAnnotationMarkerId===void 0||r.activeAnnotationMarkerId!==t?(r.activeAnnotationMarkerId=t,r.activeAnnotationMarkerPosition=i,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=t)):this.deactivateMarker())}deactivateMarker(){let t=this.modules.annotations;t!==void 0&&(t.activeAnnotationMarkerId=void 0,t.activeAnnotationMarkerPosition=void 0,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=void 0))}showLayer(t){let i="#",r=new Ku("layer-on","layer-off",!0,t,"layer-"+t);switch(t){case"annotations":case"highlights":i+="R2_ID_HIGHLIGHTS_CONTAINER",r.name="R2_ID_HIGHLIGHTS_CONTAINER";break;case"readaloud":i+="R2_ID_READALOUD_CONTAINER",r.name="R2_ID_READALOUD_CONTAINER";break;case"pagebreak":i+="R2_ID_PAGEBREAK_CONTAINER",r.name="R2_ID_PAGEBREAK_CONTAINER";break;case"search":i+="R2_ID_SEARCH_CONTAINER",r.name="R2_ID_SEARCH_CONTAINER";break;case"definitions":i+="R2_ID_DEFINITIONS_CONTAINER",r.name="R2_ID_DEFINITIONS_CONTAINER";break}this.highlighter?.layerSettings.saveProperty(r);let s=this.iframes[0].contentDocument;if(s){let o=fe(s,i);o&&(o.style.display="block")}}hideLayer(t){let i="#",r=new Ku("layer-on","layer-off",!1,t,"layer-"+t);switch(t){case"annotations":case"highlights":i+="R2_ID_HIGHLIGHTS_CONTAINER",r.name="R2_ID_HIGHLIGHTS_CONTAINER";break;case"readaloud":i+="R2_ID_READALOUD_CONTAINER",r.name="R2_ID_READALOUD_CONTAINER";break;case"pagebreak":i+="R2_ID_PAGEBREAK_CONTAINER",r.name="R2_ID_PAGEBREAK_CONTAINER";break;case"search":i+="R2_ID_SEARCH_CONTAINER",r.name="R2_ID_SEARCH_CONTAINER";break;case"definitions":i+="R2_ID_DEFINITIONS_CONTAINER",r.name="R2_ID_DEFINITIONS_CONTAINER";break}this.highlighter?.layerSettings.saveProperty(r);let s=this.iframes[0].contentDocument;if(s){let o=fe(s,i);o&&(o.style.display="none")}}},fR=Va;I();var bt=class bt{constructor(e){this.store=e.store}getLastReadingPosition(){let e=this.store.get(bt.LAST_READING_POSITION);return e?JSON.parse(e):null}initLastReadingPosition(e){if(typeof e=="string")this.store.set(bt.LAST_READING_POSITION,e);else{let t=JSON.stringify(e);this.store.set(bt.LAST_READING_POSITION,t)}}saveLastReadingPosition(e){if(typeof e=="string")this.store.set(bt.LAST_READING_POSITION,e);else{let t=JSON.stringify(e);this.store.set(bt.LAST_READING_POSITION,t)}}initBookmarks(e){if(typeof e=="string"){let t=JSON.parse(e);this.store.set(bt.BOOKMARKS,JSON.stringify(t))}else this.store.set(bt.BOOKMARKS,JSON.stringify(e));return e}saveBookmark(e){let t=this.store.get(bt.BOOKMARKS);if(t){let i=JSON.parse(t);i.push(e),this.store.set(bt.BOOKMARKS,JSON.stringify(i))}else{let i=[];i.push(e),this.store.set(bt.BOOKMARKS,JSON.stringify(i))}return e}locatorExists(e,t){let i;t===0&&(i=bt.BOOKMARKS);let r=this.store.get(i);return r&&JSON.parse(r).filter(a=>a.href===e.href&&a.locations.progression===e.locations.progression).length>0?e:null}deleteBookmark(e){let t=this.store.get(bt.BOOKMARKS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.id!==e.id),this.store.set(bt.BOOKMARKS,JSON.stringify(i))}return e}getBookmarks(e){let t=this.store.get(bt.BOOKMARKS);if(t){let i=JSON.parse(t);if(e){let r=i.filter(s=>s.href===e);return r=r.sort((s,o)=>s.locations.progression&&o.locations.progression?s.locations.progression-o.locations.progression:0),r}return i=i.sort((r,s)=>{if(r.locations.progression&&s.locations.progression)return r.locations.progression-s.locations.progression}),i}return[]}initAnnotations(e){let t;typeof e=="string"?t=JSON.parse(e):t=e;let i=[];return t.forEach(r=>{let s=`${r.highlight.selectionInfo.rangeInfo.startContainerElementCssSelector}${r.highlight.selectionInfo.rangeInfo.startContainerChildTextNodeIndex}${r.highlight.selectionInfo.rangeInfo.startOffset}${r.highlight.selectionInfo.rangeInfo.endContainerElementCssSelector}${r.highlight.selectionInfo.rangeInfo.endContainerChildTextNodeIndex}${r.highlight.selectionInfo.rangeInfo.endOffset}`,o=fs.hash(s);r.highlight.id="R2_HIGHLIGHT_"+o;let a;r.highlight.color?a=r.highlight.color:r.color&&(a=r.color),$t.isHexColor(a)&&(a=$t.hexToRgbString(a)),r.highlight.color=a,r.highlight.pointerInteraction=!0,r.highlight.selectionInfo.cleanText=r.highlight.selectionInfo.rawText.trim().replace(/\n/g," ").replace(/\s\s+/g," "),i.push(r)}),this.store.set(bt.ANNOTATIONS,JSON.stringify(i)),i}saveTemporarySelectionInfo(e){this.store.set(bt.SELECTIONINFO,JSON.stringify(e))}getTemporarySelectionInfo(e){if(!e)return null;let t=this.store.get(bt.SELECTIONINFO);if(t){let i=JSON.parse(t);return i.range=Gp(e,i.rangeInfo),i}return null}deleteTemporarySelectionInfo(){this.store.remove(bt.SELECTIONINFO)}saveAnnotation(e){let t=this.store.get(bt.ANNOTATIONS);if(t){let i=JSON.parse(t);i.push(e),this.store.set(bt.ANNOTATIONS,JSON.stringify(i))}else{let i=[];i.push(e),this.store.set(bt.ANNOTATIONS,JSON.stringify(i))}return e}deleteAnnotation(e){let t=this.store.get(bt.ANNOTATIONS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.id!==e),this.store.set(bt.ANNOTATIONS,JSON.stringify(i))}return e}deleteSelectedAnnotation(e){let t=this.store.get(bt.ANNOTATIONS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.highlight?.id!==e.highlight.id),this.store.set(bt.ANNOTATIONS,JSON.stringify(i))}return e}getAnnotations(){let e=this.store.get(bt.ANNOTATIONS);if(e){let t=JSON.parse(e);return t=t.sort((i,r)=>{if(i.locations.progression&&r.locations.progression)return i.locations.progression-r.locations.progression}),t}return[]}getAnnotationsByChapter(e){let t=this.store.get(bt.ANNOTATIONS);if(t){let i=JSON.parse(t);return i=i.filter(r=>r.href===e),i=i.sort((r,s)=>{if(r.locations.progression&&s.locations.progression)return r.locations.progression-s.locations.progression}),i}return[]}getAnnotationPosition(e,t){let i=this.store.get(bt.ANNOTATIONS);if(i){let s=JSON.parse(i).filter(o=>o.highlight?.id===e||o.id===e);if(s.length>0){let o=t.document.getElementById(`${s[0].highlight.id}`);if(o){let a=0;if(o.hasChildNodes())for(let u=0;u<o.childNodes.length;u++){let l=o.childNodes[u],c=parseInt(l.style.top.replace("px",""));(c<a||a===0)&&(a=c)}else a=parseInt(o.style.top.replace("px",""));return a}}}return null}getAnnotationElement(e,t){let i=this.store.get(bt.ANNOTATIONS);if(i){let s=JSON.parse(i).filter(o=>o.highlight?.id===e);if(s.length>0){let o=t.document.getElementById(`${s[0].highlight.id}`);if(o){let a=0;if(o.hasChildNodes())for(let u=0;u<o.childNodes.length;u++){let l=o.childNodes[u],c=parseInt(l.style.top.replace("px",""));if(c<a||a===0)return a=c,l}else a=parseInt(o.style.top.replace("px",""));return o}}}return null}getAnnotation(e){let t=this.store.get(bt.ANNOTATIONS);if(t){let r=JSON.parse(t).filter(s=>s.highlight?.id===e.id);if(r.length>0)return r[0]}return null}getAnnotationByID(e){let t=this.store.get(bt.ANNOTATIONS);if(t){let r=JSON.parse(t).filter(s=>s.highlight?.id===e);if(r.length>0)return r[0]}return null}};bt.LAST_READING_POSITION="last-reading-position",bt.BOOKMARKS="bookmarks",bt.ANNOTATIONS="annotations",bt.SELECTIONINFO="selectionInfo";var Wd=bt;I();I();var Pl=class{constructor(){this.store={}}get(e){return this.store[e]||null}set(e,t){this.store[e]=t}remove(e){this.store[e]=null}};var Ka=class{constructor(e){this.prefix=e.prefix.toString(),this.useLocalStorage=e.useLocalStorage,this.useStorageType=e.useStorageType;try{let t=e.prefix+"-"+String(Math.random());this.useStorageType==="memory"?this.fallbackStore=new Pl:this.useStorageType==="local"||this.useLocalStorage?(window.localStorage.setItem(t,"test"),window.localStorage.removeItem(t),this.fallbackStore=null):(this.useStorageType==="session"||!this.useLocalStorage)&&(window.sessionStorage.setItem(t,"test"),window.sessionStorage.removeItem(t),this.fallbackStore=null)}catch{this.fallbackStore=new Pl}}getLocalStorageKey(e){return this.prefix+"-"+e}get(e){let t;return this.fallbackStore?t=this.fallbackStore.get(e):this.useStorageType==="local"||this.useLocalStorage?t=window.localStorage.getItem(this.getLocalStorageKey(e)):t=window.sessionStorage.getItem(this.getLocalStorageKey(e)),t}set(e,t){this.fallbackStore?this.fallbackStore.set(e,t):this.useStorageType==="local"||this.useLocalStorage?window.localStorage.setItem(this.getLocalStorageKey(e),t):window.sessionStorage.setItem(this.getLocalStorageKey(e),t)}remove(e){this.fallbackStore?this.fallbackStore.remove(e):this.useStorageType==="local"||this.useLocalStorage?window.localStorage.removeItem(this.getLocalStorageKey(e)):window.sessionStorage.removeItem(this.getLocalStorageKey(e))}};ci();I();X0();function $o(n){if(n==null)return n;if(n instanceof Set)return Array.from(n);if(n.items&&Array.isArray(n.items))return n.items.map($o);if(Array.isArray(n))return n.map($o);if(typeof n!="object")return n;let e={};for(let t in n)n.hasOwnProperty(t)&&(e[t]=$o(n[t]));return e}I();var pR=$e(jt()),z1=class{constructor(e){this.LAYERSETTINGS="layerSetting";this.store=e,this.initialize()}static async create(e){let t=new this(e.store);return new Promise(i=>i(t))}async stop(){pR.default.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let e=new os,t=await this.store.get(this.LAYERSETTINGS);if(t){let i=JSON.parse(t);e.properties=i}return e}async saveProperty(e){let t=await this.store.get(this.LAYERSETTINGS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.name!==e.name),i.push(e),await this.store.set(this.LAYERSETTINGS,JSON.stringify(i))}else{let i=[];i.push(e),await this.store.set(this.LAYERSETTINGS,JSON.stringify(i))}return new Promise(i=>i(e))}async getProperty(e){let t=await this.store.get(this.LAYERSETTINGS);if(t){let i=JSON.parse(t);return i=i.filter(r=>r.name===e),i.length===0?null:i[0]}return null}};I();Xt();hi();ci();mn();Er();var zd=$e(jt()),V1=class{constructor(e,t,i){this.name=we.PageBreaks;this.hostType=nt.Epub;this.rightsKey=vt.PageBreaks;this.headerMenu=i,this.publication=e,this.properties=t}attach(e){this.host=e}static async create(e){let t=new this(e.publication,e,e.headerMenu);return await t.start(),t}async stop(){zd.default.log("Page Break module stop")}async start(){this.headerMenu&&(this.goToPageView=fe(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=fe(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=fe(this.headerMenu,"#goToPageNumberButton")),ee(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),ee(this.goToPageNumberButton,"click",this.goToPageNumber.bind(this)),this.goToPageView&&(this.publication.pageList?.length||this.goToPageView.parentElement?.removeChild(this.goToPageView)),setTimeout(()=>{this.properties.hideLayer?this.host.hideLayer("pagebreak"):this.host.showLayer("pagebreak")},10)}async goToPageNumber(e){if(this.goToPageNumberInput.value&&(e.key==="Enter"||e.type==="click")){var t=this.publication.pageList?.filter(r=>r.href.slice(r.href.indexOf("#")+1).replace(/[^0-9]/g,"")===this.goToPageNumberInput.value);if(t&&t.length>0){var i=t[0];let r={progression:0};if(i.href.indexOf("#")!==-1){let o=i.href.slice(i.href.indexOf("#")+1);o!==null&&(r={fragment:o})}let s={href:this.publication.getAbsoluteHref(i.href),locations:r,type:i.type,title:i.title};this.host.goTo(s)}}}async handleResize(){await this.host.highlighter?.destroyHighlights(3),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{let e=this.host.iframes[0].contentDocument?.body,t=e?.querySelectorAll('[*|type="pagebreak"]');t?.length===0&&(t=e?.querySelectorAll("[epub\\:type='pagebreak']")),t?.length===0&&(t=e?.querySelectorAll("[role='doc-pagebreak']"));let i=this;function r(s){try{let o=i.host.iframes[0].contentDocument;return o?Vi(s,o,zo):""}catch(o){return zd.default.log("uniqueCssSelector:"),zd.default.error(o),""}}if(t)for(let s=0;s<t.length;s++){let o=t[s];zd.default.log(o);let a=o.innerHTML,u=!1;o.innerHTML.length===0&&(a=o.getAttribute("title")??"",o.textContent=a,u=!0),o.innerHTML.length===0&&(a=(o.getAttribute("id")??"").replace(/[^0-9]/g,""),o.innerHTML=a,u=!0);let l=this.host.iframes[0].contentDocument;if(l){let c=this.host.highlighter?.dom(l.body).getWindow().document.createRange(),d=this.host.highlighter?.dom(l.body).getSelection();if(d.removeAllRanges(),c.selectNodeContents(o),d.addRange(c),!d.isCollapsed){let f=Qs(c,r);d.removeAllRanges(),f&&this.createPageBreakHighlight({rangeInfo:f,cleanText:"",rawText:""},a)}}u&&(o.innerHTML="")}},200)}createPageBreakHighlight(e,t){try{let r=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,o="R2_PAGEBREAK_"+fs.hash(r);var i=!1;let a={color:"#000000",id:o,pointerInteraction:i,selectionInfo:e,marker:3,icon:{id:"pageBreak",title:t,color:"#000000",position:"left"},type:3};di.push(a);let u=this.host.highlighter?.createHighlightDom(this.host.iframes[0].contentWindow,a);return a.position=parseInt((u?.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px","")),a}catch(r){throw"Can't create highlight: "+r}}};I();hi();Xt();tr();Er();ci();mn();var mR=$e(cv());var bR=$e($s());var Ct=$e(jt()),K1=class{constructor(e,t,i,r,s){this.name=we.TTS;this.hostType=nt.Epub;this.rightsKey=vt.TTS;this.voices=[];this.hasEventListener=!1;this.startX=0;this.startY=0;this.index=0;this.userScrolled=!1;this.scrollPartial=!1;this.speaking=!1;this.restartIndex=-1;this.ttsQueueIndex=-1;this.ttsQueue=void 0;this.ttsPlayQueueIndexDebounced=(0,bR.default)((e,t)=>{this.restartIndex>=0?(this.ttsQueueIndex=this.restartIndex,this.restartIndex=-1):this.ttsQueueIndex=e,this.ttsQueue=t,this.ttsPlayQueueIndex(this.ttsQueueIndex,t)},150);this.tts=e,this.headerMenu=s,this.highlighter=t,this.properties=i,this.api=r}attach(e){this.host=e}initialize(e){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=e,this.clean=(0,mR.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),this.wrapper=dt(document,"#iframe-wrapper"),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,ee(document,"wheel",this.wheel.bind(this)),ee(this.body,"wheel",this.wheel.bind(this)),ee(document,"keydown",this.wheel.bind(this)),ee(this.host.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),ee(this.body,"mousedown",this.clickStart.bind(this)),ee(this.body,"mouseup",this.click.bind(this)))}clickStart(e){"clientX"in e&&(this.startX=e.clientX),"clientY"in e&&(this.startY=e.clientY)}click(e){let t=0,i=0;if("clientX"in e&&(t=e.clientX),"clientY"in e&&(i=e.clientY),window.speechSynthesis.speaking&&this.speaking&&t===this.startX&&i===this.startY){let r=this.host.iframes[0].contentDocument;if(r){let s=this.highlighter.dom(r.body).getSelection(),o=s.getRangeAt(0),a=s.anchorNode;for(;o.toString().indexOf(" ")!==0;)try{o.setStart(a,o.startOffset-1)}catch{break}o.setStart(a,o.startOffset+1);do o.setEnd(a,a.length<o.endOffset?o.endOffset+1:a.length);while(o.toString().indexOf(" ")===-1&&o.toString().trim()!=="");let l=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(this.ttsQueue&&l){let c=this.findTtsQueueItemIndex(this.ttsQueue,s.anchorNode,s.anchorNode,s.anchorOffset,l);s.removeAllRanges(),c>=0&&(window.speechSynthesis.cancel(),this.restartIndex=c,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}}}}initVoices(e){function t(){return new Promise(function(r,s){let o=window.speechSynthesis,a;a=setInterval(()=>{o.getVoices().length!==0&&(r(o.getVoices()),clearInterval(a))},10)})}t().then(async r=>{if(Ct.default.log(r),this.voices=[],r.forEach(o=>{o.localService===!0&&this.voices.push(o)}),Ct.default.log(this.voices),e&&this.headerMenu){var s=fe(this.headerMenu,"#preferred-languages");s&&this.voices.forEach(o=>{var a=document.createElement("option");a.value=o.name+":"+o.lang,a.innerHTML=o.name+" ("+o.lang+")",s.add(a)})}})}cancel(e=!0){e&&this.speaking&&(this.api?.stopped&&this.api?.stopped(),this.host.emit(xe.ReadAloudStopped,"stopped",{locator:this.host.currentLocator()})),this.userScrolled=!1,this.speaking=!1,setTimeout(()=>{window.speechSynthesis.cancel()},0),this._ttsQueueItemHighlightsWord&&(this.host.highlighter?.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0)}async speak(e,t,i){t||this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.deactivate(),this.api?.started&&this.api?.started(),this.host.emit(xe.ReadAloudStarted,"started",{locator:this.host.currentLocator()});let r=this;this.userScrolled=!1,this.cancel(!1);let s;if(t){let f=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body,m=this.host.iframes[0].contentDocument;if(m){let y=this.highlighter.dom(m.body).getSelection();if(y.isCollapsed){let g=r.host.iframes[0].contentDocument,v=r.host.getModule(we.Annotations)?.annotator?.getTemporarySelectionInfo(g);v?.range&&y.addRange(v.range)}if(f){var o=this.generateTtsQueue(f);if(!o.length)return;var a=this.findTtsQueueItemIndex(o,y.anchorNode,y.anchorNode,y.anchorOffset,f),u=this.findTtsQueueItemIndex(o,y.focusNode,y.focusNode,y.focusOffset,f);let g=Ya(o,a),b=Ya(o,u);var l;if(g&&e&&e.cleanText){let v=qa(g),A=e.rangeInfo.startOffset,w=e.cleanText;if(b&&a+1===u){let C=qa(b);A=(v+" "+C).indexOf(e.cleanText),w=v.slice(A,v.length),l=e.cleanText.replace(w,"").trim()}else if(u>a){let C="";for(let T=a+1;T<u;T++){let k=Ya(o,T);if(k){let _=qa(k);C+=_,l=e.cleanText.replace(_,"")}}if(b){let T=qa(b);C+=" "+T}A=(v+" "+C).indexOf(e.cleanText),w=v.slice(A,v.length),l=l.replace(w,"").trim()}s=new SpeechSynthesisUtterance(w),s.rate=this.tts.rate,s.pitch=this.tts.pitch,s.volume=this.tts.volume,this.setVoice(this,s),Ct.default.log(e),Ct.default.log(w,e.range?.commonAncestorContainer.textContent),Ct.default.log(g),Ct.default.log(g.item.textNodes),Ct.default.log(A),Ct.default.log(g.item.combinedText);let x=g.item.textNodes.filter(C=>C===e.range?.commonAncestorContainer)[0];Ct.default.log(x),s.onboundary=C=>{this.updateTTSInfo(g,C.charIndex,C.charLength,A,s.text)}}}}}else s=new SpeechSynthesisUtterance(this.clean);s.rate=this.tts.rate,s.pitch=this.tts.pitch,s.volume=this.tts.volume,this.setVoice(r,s),this.index=0;function c(){s.onend=function(){if(u>a)if(a=a+1,a!==u){let d=Ya(o,a);if(d){let f=qa(d);s=new SpeechSynthesisUtterance(f),s.rate=r.tts.rate,s.pitch=r.tts.pitch,s.volume=r.tts.volume,r.setVoice(r,s),s.onboundary=m=>{r.updateTTSInfo(d,m.charIndex,m.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s)},0),c()}}else{let d=Ya(o,a);d&&(s=new SpeechSynthesisUtterance(l),s.rate=r.tts.rate,s.pitch=r.tts.pitch,s.volume=r.tts.volume,r.setVoice(r,s),s.onboundary=f=>{r.updateTTSInfo(d,f.charIndex,f.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s)},0),c()),a>u&&(Ct.default.log("utterance ended"),r.highlighter.doneSpeaking(),r.api?.finished(),r.host.emit(xe.ReadAloudFinished,"finished",{locator:r.host.currentLocator()}))}else Ct.default.log("utterance ended"),r.highlighter.doneSpeaking(),r.api?.finished(),r.host.emit(xe.ReadAloudFinished,"finished",{locator:r.host.currentLocator()})}}setTimeout(()=>{window.speechSynthesis.speak(s),t||this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.recalculate(200)},0),c(),i()}setVoice(e,t){Ct.default.log("this.tts.voice.lang",this.tts.voice.lang);let i=!0;this.tts.voice&&this.tts.voice.lang&&(i=this.tts.voice.lang.indexOf("-")!==-1,i||(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),i=!0)),Ct.default.log("initialVoiceHasHyphen",i),Ct.default.log("voices",this.voices);let r;i?(r=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(c=>{var d=c.lang.replace("_","-");return d===this.tts.voice.lang&&c.name===this.tts.voice.name})[0]:void 0,r===void 0&&(r=this.tts.voice&&this.tts.voice.lang?this.voices.filter(c=>c.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(r=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(c=>c.lang===this.tts.voice.lang&&c.name===this.tts.voice.name)[0]:void 0,r===void 0&&(r=this.tts.voice&&this.tts.voice.lang?this.voices.filter(c=>c.lang===this.tts.voice.lang)[0]:void 0)),Ct.default.log("initialVoice",r);let s=e.host.publication.metadata?.languages?.[0],o=s?s.indexOf("-")!==-1:!1;Ct.default.log("publicationVoiceHasHyphen",o);let a;o?a=this.tts.voice&&this.tts.voice.usePublication&&s?this.voices.filter(c=>{var d=c.lang.replace("_","-");return d.startsWith(s)||d.endsWith(s.toUpperCase())})[0]:void 0:a=this.tts.voice&&this.tts.voice.usePublication&&s?this.voices.filter(c=>c.lang.startsWith(s)||c.lang.endsWith(s.toUpperCase()))[0]:void 0,Ct.default.log("publicationVoice",a);let u=navigator.language.indexOf("-")!==-1;Ct.default.log("defaultVoiceHasHyphen",u);let l;u?l=this.voices.filter(c=>c.lang.replace("_","-")===navigator.language&&c.localService)[0]:l=this.voices.filter(c=>c.lang===navigator.language&&c.localService)[0],l===void 0&&(l=this.voices.filter(c=>c.lang.includes(navigator.language)&&c.localService)[0]),Ct.default.log("defaultVoice",l),r?(Ct.default.log("initialVoice"),t.voice=r):a?(Ct.default.log("publicationVoice"),t.voice=a):l&&(Ct.default.log("defaultVoice"),t.voice=l),t.voice!==void 0&&t.voice!==null&&(t.lang=t.voice.lang,Ct.default.log("utterance.voice.lang",t.voice.lang),Ct.default.log("utterance.lang",t.lang)),Ct.default.log("navigator.language",navigator.language)}speakPlay(){this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.deactivate(),this.scrollPartial=!0,this.cancel(!1),this.api?.started&&this.api?.started(),this.host.emit(xe.ReadAloudStarted,"started",{locator:this.host.currentLocator()});let e=this,i=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(i){let o=function(){let a=e.highlighter.visibleTextRects[0],u=e.host.iframes[0].contentDocument;if(u){let l=e.highlighter.dom(u.body).getWindow().document.createRange(),c=e.highlighter.dom(e.host.iframes[0].contentDocument?.body).getSelection();c.removeAllRanges(),l.selectNodeContents(a.node),c.addRange(l);let d=0,f=c.focusNode,m=c.focusOffset;c.collapse(c.anchorNode,c.anchorOffset);for(let y=0;y<d;y++)c.modify("move","forward","line");if(c.extend(f,m),c.collapse(c.anchorNode,c.anchorOffset),i){let y=e.findTtsQueueItemIndex(r,c.anchorNode,c.anchorNode,c.anchorOffset,i);y>=0&&(s=y)}c.removeAllRanges()}},r=this.generateTtsQueue(i);if(!r.length)return;let s=0;o(),s<0&&(s=0),setTimeout(()=>{this.startTTSSession(r,s)},200)}this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.recalculate(200)}speakPause(){window.speechSynthesis.speaking&&(this.api?.paused&&this.api?.paused(),this.host.emit(xe.ReadAloudPaused,"paused",{locator:this.host.currentLocator()}),this.userScrolled=!1,window.speechSynthesis.pause(),this.speaking=!1,this._ttsQueueItemHighlightsWord&&(this.host.highlighter?.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0))}speakResume(){window.speechSynthesis.speaking&&(this.api?.resumed&&this.api?.resumed(),this.host.emit(xe.ReadAloudResumed,"resumed",{locator:this.host.currentLocator()}),this.userScrolled=!1,window.speechSynthesis.resume(),this.speaking=!0)}static async create(e){let t=new this(e.tts,e.highlighter,e,e.api,e.headerMenu);return await t.start(),t}async start(){if(this.headerMenu){var e=fe(this.headerMenu,"#menu-button-tts");e&&e.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties?.hideLayer?this.host.hideLayer("readaloud"):this.host.showLayer("readaloud")},10)}wheel(e){if(e instanceof KeyboardEvent)switch(e.key){case"ArrowUp":this.userScrolled=!0;break;case"ArrowDown":this.userScrolled=!0;break}else this.userScrolled=!0}stop(){Ct.default.log("TTS module stop"),Ae(document,"wheel",this.wheel.bind(this)),Ae(this.body,"wheel",this.wheel.bind(this)),Ae(document,"keydown",this.wheel.bind(this)),Ae(this.host.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),Ae(this.body,"click",this.click.bind(this))}generateTtsQueue(e){let t=[],i=[];function r(u){if(u.nodeType!==Node.TEXT_NODE||!u.nodeValue||!u.nodeValue.trim().length)return;let l=i[i.length-1];if(!l)return;let c=u.parentElement?gR(u.parentElement):void 0,d=u.parentElement?EZ(u.parentElement):void 0,f=t[t.length-1];(!f||f.parentElement!==l||f.lang!==c||f.dir!==d)&&(f={combinedText:"",dir:d,lang:c,parentElement:l,textNodes:[]},t.push(f)),f.textNodes.push(u)}let s=!0;function o(u){if(u.nodeType!==Node.ELEMENT_NODE)return;let l=s||u.matches("h1, h2, h3, h4, h5, h6, p, th, td, caption, li, blockquote, q, dt, dd, figcaption, div, pre");s=!1,l&&i.push(u);for(let c of u.childNodes)switch(c.nodeType){case Node.ELEMENT_NODE:let d=c;if(!d.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))o(d);else if(d.tagName&&d.tagName.toLowerCase()==="img"&&d.src){let m=d.getAttribute("alt");if(m){let y=m.trim();if(y){let g=gR(d);t.push({combinedText:y,dir:void 0,lang:g,parentElement:d,textNodes:[]})}}}break;case Node.TEXT_NODE:i.length!==0&&r(c);break;default:break}l&&i.pop()}o(e);function a(u){if(!u.textNodes||!u.textNodes.length){(!u.combinedText||!u.combinedText.length)&&(u.combinedText="");return}u.combinedText=CZ(u.textNodes,!0).replace(/[\r\n]/g," ");let l=u.parentElement;for(;l;){if(l.tagName){let c=l.tagName.toLowerCase();if(c==="pre"||c==="code"||c==="video"||c==="audio")break}l=l.parentElement}}for(let u of t)a(u);return t}findTtsQueueItemIndex(e,t,i,r,s){let o=0;for(let a of e){if(i&&a.textNodes){if(a.textNodes.includes(i))return o}else if(t===a.parentElement||a.parentElement!==t.ownerDocument.body&&a.parentElement!==s&&a.parentElement.contains(t)||t.contains(a.parentElement))return o;o++}return-1}restart(){window.speechSynthesis.speaking&&(window.speechSynthesis.cancel(),this.restartIndex=this.ttsQueueIndex,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}startTTSSession(e,t){if(!Ya(e,t)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(t,e)}ttsPlayQueueIndex(e,t){if(e<0){this.cancel();return}let i=Ya(t,e);if(!i){this.cancel();return}let r=qa(i);if(!r){this.cancel();return}let s=new SpeechSynthesisUtterance(r);s.rate=this.tts.rate,s.pitch=this.tts.pitch,s.volume=this.tts.volume;let o=this;this.setVoice(o,s),s.onboundary=a=>{Ct.default.log(a.name),this.updateTTSInfo(i,a.charIndex,a.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s),o.speaking||window.speechSynthesis.pause()},0),s.onend=function(){o.speaking&&o.ttsPlayQueueIndexDebounced(e+1,t)}}updateTTSInfo(e,t,i,r,s){if(!e)return;Ct.default.log(e,t,i,s);let o=s||qa(e);if(t>=0&&s){let a=s.slice(0,t+1).search(/\S+$/),u=s.slice(t).search(/\s/),l=u<0?s.slice(a):s.slice(a,u+t),c=a+l.length;if(i===void 0){let d=s.substring(t).match(/^[a-z\d']*/i);d&&(i=d[0].length)}i===void 0&&(i=l.length),this.wrapHighlightWord(e,s,t+r,i,l,a,c)}return o}wrapHighlightWord(e,t,i,r,s,o,a){Ct.default.log(e),Ct.default.log(t),Ct.default.log(i,r,s,o,a),this._ttsQueueItemHighlightsWord&&(this.host.highlighter?.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0);let u=e.item,l=i,c=0,d,f=-1,m,y=-1,g=l+r;for(let b of u.textNodes){if(!b.nodeValue&&b.nodeValue!=="")continue;let v=b.nodeValue.length;if(c+=v,d||l<c&&(d=b,f=v-(c-l)),d&&g<=c&&(m=b,y=v-(c-g)),m)break}if(d&&m){let A=function(C){try{let T=v.host.iframes[0].contentDocument;return T?Vi(C,T,zo):""}catch(T){return Ct.default.log("uniqueCssSelector:"),Ct.default.error(T),""}},b=new Range;b.setStart(d,f),b.setEnd(m,y);let v=this,w=Qs(b,A);if(!w)return;let x=this.host.highlighter?.createHighlight(this.host.iframes[0].contentWindow,{rangeInfo:w,cleanText:"",rawText:"",range:void 0},this.tts.color,!1,3,{id:"tts",title:"",position:"right"},void 0,{defaultClass:this.tts.color},2,"R2_READALOUD_");if(x){this._ttsQueueItemHighlightsWord=x[0];let k=(x[1]?.firstChild?.getBoundingClientRect()).top-this.wrapper.scrollTop>window.innerHeight/2-65;this.host.view?.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&this.scrollPartial&&k?x[1]?.firstChild?.scrollIntoView({block:"center",behavior:"smooth"}):this.host.view?.isPaginated()&&v.host.view?.snap(x[1]?.firstChild)}}}};function gR(n){let e=n;for(;e&&e.nodeType===Node.ELEMENT_NODE;){let t=e.getAttribute("xml:lang");if(t||(t=e.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang")),t||(t=e.getAttribute("lang")),t)return t;e=e.parentNode}}function EZ(n){let e=n;for(;e&&e.nodeType===Node.ELEMENT_NODE;){let t=e.getAttribute("dir");if(t)return t;e=e.parentNode}}function CZ(n,e){if(n&&n.length){let t="";for(let i of n)i.nodeValue&&(t+=e?i.nodeValue:SZ(i.nodeValue));return t}return""}function xZ(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function SZ(n){return xZ(n).replace(/\n/g," ").replace(/\s\s+/g," ")}function Ya(n,e){let t=-1,i=-1;for(let r of n)if(i++,t++,e===t)return{item:r,iArray:i,iGlobal:t,iSentence:-1}}function qa(n){return n.item.combinedText}I();Xt();hi();var Vd=$e(zp());tr();var yR=$e($s());Er();var vR=$e(jt()),Y1=class{constructor(e,t,i,r){this.name=we.Definitions;this.hostType=nt.Epub;this.rightsKey=vt.Definitions;this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,yR.default)(async()=>{if(await this.highlighter.destroyHighlights(4),this.properties.definitions)for(let e of this.properties.definitions)await this.define(e)},200);this.publication=e,this.properties=t,this.api=r,this.highlighter=i}attach(e){this.host=e}static async create(e){let t=new this(e.publication,e,e.highlighter,e.api);return await t.start(),t}async stop(){vR.default.log("Definitions module stop")}async start(){setTimeout(()=>{this.properties.hideLayer?this.host.hideLayer("definitions"):this.host.showLayer("definitions")},10)}async searchAndPaint(e,t){let i=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[this.host.currentResource()??0].href:""),r=this.publication.getTOCItem(i);r===void 0&&this.publication.readingOrder&&(r=this.publication.readingOrder[this.host.currentResource()??0]);let s=[];if(r)for(let o of e.terms){let a=e.terms.indexOf(o);r&&await Sl(o,this.host.iframes[0].contentDocument,r.href,r.title,this.host.getModule(we.Definitions)?.properties.fullWordSearch).then(u=>{let l;e.result===1?l=0:e.result===2&&(l=Math.floor(Math.random()*u.length-1)+1),u.forEach((c,d)=>{if(l===void 0||l===d){let f={rangeInfo:c.rangeInfo},m=this.createDefinitionHighlight(f,e);c.highlight=m,s.push(Vd.omit(m,"definition")),this.currentChapterPopupResult.push(c),this.currentPopupHighlights.push(m)}}),a===e.terms.length-1&&t(s)})}}async define(e){await this.searchAndPaint(e,async t=>{this.api?.success&&(this.api?.success(Vd.omit(e,"callbacks"),t),t&&t.length>0&&this.host.emit(xe.DefinitionSuccess,t),this.api?.visible&&t.forEach(i=>{let s=this.host.iframes[0].contentDocument?.querySelector(`#${i.id}`)?.querySelectorAll(`.${cn}`),o=new IntersectionObserver((a,u)=>{a.forEach(l=>{l.intersectionRatio===1&&(this.api?.visible(Vd.omit(e,"callbacks"),Vd.omit(i,"definition")),this.host.emit(xe.DefinitionVisible,e,i))})},{threshold:1});s&&s.length>0&&o.observe(s[0])}))})}async drawDefinitions(){setTimeout(async()=>{await this.definitions()},100)}async handleResize(){await this.drawDefinitions()}createDefinitionHighlight(e,t){try{let i=this.host.getModule(we.Definitions)?.properties.color;$t.isHexColor(i)&&(i=$t.hexToRgbChannels(i));let r=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,o="R2_DEFINITION_"+fs.hash(r);this.highlighter.destroyHighlight(this.host.iframes[0].contentDocument,o);let a={color:i||Ba,id:o,pointerInteraction:!0,selectionInfo:e,marker:1,type:4};di.push(a);let u=this.highlighter.createHighlightDom(this.host.iframes[0].contentWindow,a);return u&&(t.definition&&(u.dataset.definition=t.definition),u.dataset.order=String(t.order),a.definition=t,a.position=parseInt((u?.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px",""))),a}catch(i){throw"Can't create definitions highlight: "+i}}async addDefinition(e){await this.define(e)}async clearDefinitions(){await this.highlighter.destroyHighlights(4)}};I();Xt();hi();ci();mn();var Qo=$e(jt()),AR=.5,Kd=class{constructor(e,t,i){this.name=we.LineFocus;this.hostType=nt.Epub;this.rightsKey=vt.LineFocus;this.hasEventListener=!1;this.lines=[];this.index=0;this.isActive=!1;this.isDebug=!1;this.lineFocusContainer=document.getElementById("lineFocusContainer");this.readerContainer=document.getElementById("D2Reader-Container");this.lineFocusTopBlinder=document.getElementById("lineFocusTopBlinder");this.lineFocusBottomBlinder=document.getElementById("lineFocusBottomBlinder");this.wrapperHeight=void 0;this.properties=e,this.api=i,this.highlighter=t}attach(e){this.host=e}static async create(e){let t=new this(e,e.highlighter,e.api);return await t.start(),t}async stop(){Qo.default.log("Definitions module stop"),this.hasEventListener=!1,Ae(document,"keydown",this.keydown.bind(this)),Ae(document,"keyup",this.keyup.bind(this)),Ae(this.host.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),Ae(this.host.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){let e=dt(document,"#iframe-wrapper");e.style.height.length>0&&(this.wrapperHeight=e.style.height,this.lineFocusContainer&&this.lineFocusContainer.style.height.length===0&&(this.lineFocusContainer.style.height=this.wrapperHeight),this.readerContainer&&this.readerContainer.style.height.length===0&&(this.readerContainer.style.height=this.wrapperHeight),this.readerContainer&&(this.readerContainer.style.overflow="hidden"))}initialize(e){return new Promise(async t=>{await document.fonts.ready,this.hasEventListener||(this.hasEventListener=!0,ee(document,"keydown",this.keydown.bind(this)),ee(document,"keyup",this.keyup.bind(this)),ee(e.contentDocument,"keydown",this.keydown.bind(this)),ee(e.contentDocument,"keyup",this.keyup.bind(this))),t(null)})}keydown(e){if(e instanceof KeyboardEvent&&this.isActive)switch(e.key){case"ArrowUp":e.stopPropagation();break;case"ArrowDown":e.stopPropagation();break}}keyup(e){if(e instanceof KeyboardEvent&&this.isActive)switch(e.key){case"ArrowUp":this.lineUp();break;case"ArrowDown":this.lineDown();break}}handleResize(){this.isActive&&this.lineFocus()}async enableLineFocus(){this.isActive=!0,await this.host.settings.scroll(!0),this.lineFocus()}disableLineFocus(e=!0){this.isActive=!1;let t=dt(document,"#iframe-wrapper");this.wrapperHeight&&(t.style.height=this.wrapperHeight),e||(this.index=0);let i=this.host.iframes[0].contentDocument;Ni(i,"html").style.removeProperty("--USER__maxMediaHeight"),this.wrapperHeight=void 0,this.lineFocusContainer&&(this.lineFocusContainer.style.display="none");let s=document.getElementById("container-view-timeline");s&&s.style.removeProperty("display");let o=document.getElementById("divBefore");o&&o.remove();let a=document.getElementById("divAfter");a&&a.remove(),this.highlighter.destroyHighlights(5)}lineFocus(){let e=dt(document,"#iframe-wrapper"),t=this.host.iframes[0].contentDocument,i=Ni(t,"html"),r=this.properties.maxHeight?Yu()*this.properties.maxHeight/100:Yu()/2;i.style.setProperty("--USER__maxMediaHeight",r+"px");function s(c,d){c.parentNode.insertBefore(d,c.nextSibling)}function o(c,d){c.parentNode.insertBefore(d,c)}let a=document.getElementById("container-view-timeline");a&&(a.style.display="none"),this.lineFocusContainer&&this.lineFocusContainer.style.removeProperty("display");let u=document.getElementById("divBefore");if(u)u.style.height=e.clientHeight/2+"px";else{let c=document.createElement("div");c.style.height=e.clientHeight/2+"px",c.id="divBefore",o(e,c)}let l=document.getElementById("divAfter");if(l)l.style.height=e.clientHeight/2+"px";else{let c=document.createElement("div");c.style.height=e.clientHeight/2+"px",c.id="divAfter",s(e,c)}if(this.lines=[],t){let f=function(){let A=Math.round,w=Math.random,x=255;return{blue:A(w()*x),green:A(w()*x),red:A(w()*x)}},m=function(A,w){let x=[];for(let C=0,T=0;C<A.length;C++)C>=w&&C%w===0&&T++,x[T]=x[T]||[],x[T].push(A[C]);return x},y=function(A,w){let x=Math.min(A.left,w.left),C=Math.max(A.right,w.right),T=Math.min(A.top,w.top),k=Math.max(A.bottom,w.bottom);return{bottom:k,height:k-T,left:x,right:C,top:T,width:C-x}},g=function(A){if(A.length>1){let w=y(A[0],A[1]);if(A.length>2){let x=y(w,A[2]);if(A.length>3){let C=y(x,A[3]);return A.length>4?y(C,A[4]):C}return x}return w}return A[0]},c=this.findRects(t.body);c=vv(c,!0),c=c.sort(function(A,w){return A.top-w.top});let d=[];c=c.filter(function(A){let w=A.top;return d.indexOf(w)===-1&&d.indexOf(w+1)===-1&&d.indexOf(w+2)===-1&&d.indexOf(w+3)===-1&&d.indexOf(w+4)===-1&&d.indexOf(w-1)===-1&&d.indexOf(w-2)===-1&&d.indexOf(w-3)===-1&&d.indexOf(w-4)===-1?(d.push(w),!0):!1}),this.highlighter.destroyHighlights(5);let b=[];this.properties.lines&&this.properties.lines>1?m(c,this.properties.lines).forEach(w=>{b.push(g(w))}):b=c;let v=fe(t,"#R2_ID_LINEFOCUS_CONTAINER");if(v)for(let A of b){let w=document.createElement("div");w.setAttribute("class",cn);let x=f();if($t.isHexColor(x)&&(x=$t.hexToRgbChannels(x)),this.isDebug){let te=`border-bottom: 1px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${AR}) !important`;w.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${AR}) !important; ${te}`)}w.style.outline="none",w.tabIndex=0;let C=this.host.iframes[0].contentWindow.document,T=this.host.view.isPaginated();T?C.body.style.position="revert":C.body.style.position="relative";let k=C.body.getBoundingClientRect(),_=this.highlighter.getScrollingElement(C),R=T?-_.scrollLeft:k.left,L=T?-_.scrollTop:k.top,M=1,O=24,U,G,j=this.host.iframes[0].contentWindow?.innerWidth,W=parseInt(getComputedStyle(t.documentElement).getPropertyValue("column-count")),z=parseInt(getComputedStyle(t.documentElement).getPropertyValue("column-width")),$=parseInt(getComputedStyle(t.body).getPropertyValue("padding-left"));if(j){let te=j/(W||1);te<z&&(te=j),T||(te=parseInt(getComputedStyle(t.body).width.replace("px","")));let le=this.host.settings.fontSize/100,ce=20*le;le<=1&&(ce=-60);let pe=0;le<=1&&(pe=-60),U=Math.floor(A.left/te)*te+te-(O<40?40:O)+pe,G=Math.floor(A.left/te)*te+(O<40?40:O)-ce;let se=parseInt(t.documentElement.style.getPropertyValue("--USER__pageMargins"));se>=2&&(G=G+$/W,U=U-$/W),T||(U=parseInt(getComputedStyle(t.body).width.replace("px","")),G=parseInt(getComputedStyle(t.body).width.replace("px",""))-te,se>=2&&(G=G+$/2,U=U-$/2))}w.style.setProperty("pointer-events","none"),w.style.position="absolute",w.scale=M,w.rect={height:A.height,left:A.left-R,top:A.top-L,width:A.width},w.style.width=`${w.rect.width*M}px`,w.style.height=`${w.rect.height*M}px`,w.style.left=`${w.rect.left*M}px`,w.style.top=`${w.rect.top*M}px`,this.lines.push(w),v.append(w)}setTimeout(()=>{this.currentLine()},100)}}currentLine(){let e=this.lines[this.index],t=e.style.top,r=parseInt(e.style.top.replace("px",""))+parseInt(e.style.height.replace("px",""))-parseInt(t.replace("px",""));if(this.lineFocusContainer){let o=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-r)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=o+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=o+"px")}e.scrollIntoView({block:"center",behavior:"smooth"})}lineDown(){if(this.index<this.lines.length-1){this.index+=1,this.index>this.lines.length-1&&(this.index=this.lines.length-1);let e=this.lines[this.index],t=e.style.top,r=parseInt(e.style.top.replace("px",""))+parseInt(e.style.height.replace("px",""))-parseInt(t.replace("px",""));if(this.lineFocusContainer){let o=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-r)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=o+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=o+"px")}e.scrollIntoView({block:"center",behavior:"smooth"})}}lineUp(){if(this.index>0){this.index-=1,this.index<0&&(this.index=0);let e=this.lines[this.index],t=e.style.top,r=parseInt(e.style.top.replace("px",""))+parseInt(e.style.height.replace("px",""))-parseInt(t.replace("px",""));if(this.lineFocusContainer){let o=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-r)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=o+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=o+"px")}e.scrollIntoView({block:"center",behavior:"smooth"})}}almostEqual(e,t,i){return Math.abs(e-t)<=i}findRects(e){let t=this.findTextNodes(e),i=Array.from(e.getElementsByTagName("img")),r=[];return t.forEach(s=>{r.push(...this.measureTextNodes(s))}),i.forEach(s=>{r.push(...this.measureImageNodes(s))}),r}findTextNodes(e,t=[]){let i=e.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,t),i.nodeType===3&&i.textContent?.trim()&&(i.textContent.trim().length>1||i.parentElement?.tagName.toLowerCase()==="h1"||i.parentElement?.tagName.toLowerCase()==="h2"||i.parentElement?.tagName.toLowerCase()==="h3"||i.parentElement?.tagName.toLowerCase()==="h4"||i.parentElement?.tagName.toLowerCase()==="h5"||i.parentElement?.tagName.toLowerCase()==="h6")&&i.parentElement&&getComputedStyle(i.parentElement).verticalAlign==="baseline"&&t.push(i),i=i.nextSibling;return t}measureTextNodes(e){try{let t=document.createRange();t.selectNodeContents(e);let i=Array.from(t.getClientRects());return t.detach(),i}catch(t){Qo.default.log("measureTextNode "+t),Qo.default.log("measureTextNode "+e),Qo.default.log(`${e.textContent}`)}}measureImageNodes(e){try{let t=document.createRange();t.selectNode(e);let i=Array.from(t.getClientRects());return t.detach(),i}catch(t){Qo.default.log("measureTextNode "+t),Qo.default.log("measureTextNode "+e),Qo.default.log(`${e.textContent}`)}}};I();Xt();hi();ci();mn();var wR=$e(jt()),q1=class{constructor(e,t,i,r){this.name=we.History;this.hostType=nt.Epub;this.rightsKey=vt.History;this.history=[];this.headerMenu=r,this.publication=t,this.properties=i,this.annotator=e}attach(e){this.host=e}static async create(e){let t=new this(e.annotator,e.publication,e,e.headerMenu);return await t.start(),t}async stop(){wR.default.log("Page Break module stop"),Ae(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),Ae(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleResize(){await this.setup()}setup(){this.history.length>0&&(this.historyForwardAnchorElement&&this.historyCurrentIndex+1<this.history.length?this.historyForwardAnchorElement.className=this.historyForwardAnchorElement.className.replace(" disabled",""):this.historyForwardAnchorElement&&(this.historyForwardAnchorElement.removeAttribute("href"),this.historyForwardAnchorElement.className+=" disabled"),this.historyBackAnchorElement&&this.historyCurrentIndex>0?this.historyBackAnchorElement.className=this.historyBackAnchorElement.className.replace(" disabled",""):this.historyBackAnchorElement&&(this.historyBackAnchorElement.removeAttribute("href"),this.historyBackAnchorElement.className+=" disabled"))}async push(e,t){if(t&&this.annotator){let i=await this.annotator.getLastReadingPosition();if(i){let s=this.publication.getAbsoluteHref(i.href);if(i.href=s,this.historyCurrentIndex<this.history.length-1)this.history=this.history.slice(0,this.historyCurrentIndex),this.history.push(i),this.historyCurrentIndex=this.history.length-1;else if(i?.locations.progression&&i?.locations.progression>0)this.history.push(i),this.historyCurrentIndex=this.history.length-1;else{let o=this.history[this.history.length-1];(o&&o.href!==e.href&&o.locations!==e.locations||o===void 0)&&(this.history.push(i),this.historyCurrentIndex=this.history.length-1)}}this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex));let r=this.history[this.history.length-1];(r&&r.href!==e.href||r===void 0)&&(this.history.push(e),this.historyCurrentIndex=this.history.length-1)}}async start(){this.headerMenu&&(this.historyForwardAnchorElement=fe(this.headerMenu,"#history-forward")),this.headerMenu&&(this.historyBackAnchorElement=fe(this.headerMenu,"#history-back")),this.historyCurrentIndex=this.history.length-1,ee(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),ee(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleHistoryForwardClick(e){await this.historyForward(),e.preventDefault(),e.stopPropagation()}async historyForward(){this.history.length>0&&this.historyCurrentIndex+1<this.history.length&&(this.historyCurrentIndex=this.historyCurrentIndex+1,await this.host.navigate(this.history[this.historyCurrentIndex],!1))}async handleHistoryBackClick(e){await this.historyBack(),e.preventDefault(),e.stopPropagation()}async historyBack(){this.history.length>0&&this.historyCurrentIndex>0&&(this.historyCurrentIndex=this.historyCurrentIndex-1,await this.host.navigate(this.history[this.historyCurrentIndex],!1))}back(){return this.historyBack()}forward(){return this.historyForward()}canGoBack(){return this.historyCurrentIndex>0}canGoForward(){return this.historyCurrentIndex<this.history.length-1}};I();Xt();hi();var ER=$e(jt());tr();var $1=(i=>(i[i.Chicago=0]="Chicago",i[i.MLA=1]="MLA",i[i.APA=2]="APA",i))($1||{});function Xo(n){let e=n.name??n.Name;if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=Object.values(e);return t.length>0?String(t[0]):""}return""}var Sr=["","",""],Yd=class{constructor(e,t,i,r){this.name=we.Citations;this.hostType=nt.Epub;this.rightsKey=vt.Citations;this.highlighter=t,this.properties=i,this.publication=e,this.api=r}attach(e){this.host=e}static async create(e){let t=new this(e.publication,e.highlighter,e,e.api);return await t.start(),t}async stop(){ER.default.log("Citation module stop")}copyToClipboard(e){let t=this.host?.getModule(we.ContentProtection);if(t&&(t.citation=!0),navigator.clipboard){let i=document.createElement("div");i.innerHTML=e;let r=i.textContent??i.innerText??e;navigator.clipboard.writeText(r).then(()=>{this.api?.citationCreated("The text was copied to the clipboard!"),this.host.emit(xe.CitationCreated,"The text was copied to the clipboard!")},()=>this.legacyCopyToClipboard(e))}else this.legacyCopyToClipboard(e)}legacyCopyToClipboard(e){let t=document.createElement("div");t.style.position="absolute",t.style.left="-10000px",t.style.top="-10000px",t.innerHTML=e,t.contentEditable="true",document.body.appendChild(t),this.selectContent(t);let i;try{i=document.execCommand("copy")}catch{i=!1}document.body.removeChild(t),i?(this.api?.citationCreated("The text was copied to the clipboard!"),this.host.emit(xe.CitationCreated,"The text was copied to the clipboard!")):(this.api?.citationFailed("Your browser doesn't allow clipboard access!"),this.host.emit(xe.CitationFailed,"Your browser doesn't allow clipboard access!"))}selectContent(e){let t=document.createRange();t.selectNodeContents(e);let i=window.getSelection();i?.removeAllRanges(),i?.addRange(t)}authorsFormatted(){let e="",t="",i="";if(this.properties.author)e=this.properties.author,t=this.properties.author,i=this.properties.author;else if((this.publication.metadata?.authors?.items?.length??0)>0){let s=this.publication.metadata.authors.items.map(o=>Xo(o)).filter(o=>o.length>0);s.length===1?(e=s[0],t=s[0],i=s[0]):s.length===2?(e=s[0]+" and "+s[1],t=s[0]+", and "+s[1],i=s[0]+" & "+s[1]):s.length>2&&(s.length<=6?e=s.slice(0,-1).join(", ")+", and "+s[s.length-1]:e=s.slice(0,3).join(", ")+", et al.",t=s[0]+", et al.",s.length<=20?i=s.slice(0,-1).join(", ")+", & "+s[s.length-1]:i=s.slice(0,19).join(", ")+", ... "+s[s.length-1])}return e?[e+". ",t+". ",i+". "]:Sr}yearPublishedFormatted(){let e="",t="",i="";if(this.properties.publisher)t+=this.properties.publisher,e+=this.properties.publisher;else if((this.publication.metadata?.publishers?.items?.length??0)>0&&Xo(this.publication.metadata?.publishers?.items[0])){let s=Xo(this.publication.metadata?.publishers?.items[0]);t+=s,e+=s}let r="";if(this.properties.published)r=this.properties.published;else if(this.publication.metadata?.published){let s=this.publication.metadata?.published.getFullYear();s>0&&(r=String(s))}return r&&(i+="("+r+")",t+=(t?", ":"")+r,e+=(e?", ":"")+r),i||t||e?[e?e+". ":"",t?t+". ":"",i?i+". ":""]:Sr}bookTitleFormatted(){let e=this.properties.title||this.publication.metadata?.title||"";if(e){let t="<em>"+e+"</em>. ";return[t,t,t]}return Sr}editionFormatted(){return Sr}publisherFormatted(){let e="";return this.properties.publisher?e=this.properties.publisher:(this.publication.metadata?.publishers?.items?.length??0)>0&&Xo(this.publication.metadata?.publishers?.items[0])&&(e=Xo(this.publication.metadata?.publishers?.items[0])),e?["","",e+". "]:Sr}contributorsFormatted(){let e=[],t=this.publication.metadata?.editors?.items;if((t?.length??0)>0){let r=t.map(s=>Xo(s)).filter(s=>s.length>0);r.length>0&&e.push("Edited by "+(r.length<=2?r.join(" and "):r.slice(0,-1).join(", ")+", and "+r[r.length-1]))}let i=this.publication.metadata?.translators?.items;if((i?.length??0)>0){let r=i.map(s=>Xo(s)).filter(s=>s.length>0);r.length>0&&e.push("Translated by "+(r.length<=2?r.join(" and "):r.slice(0,-1).join(", ")+", and "+r[r.length-1]))}if(e.length>0){let r=e.join(". ")+". ";return[r,r,r]}return Sr}eBookVersionFormatted(){if(this.publication.metadata?.modified){let e=this.publication.metadata?.modified,t=e.getFullYear()+"-"+String(e.getMonth()+1).padStart(2,"0")+"-"+String(e.getDate()).padStart(2,"0");return["["+t+"]. ",t+". ",t+". "]}return Sr}locationFormatted(){return Sr}libraryFormatted(){if(this.properties.library){let e="Retrieved from "+this.properties.library+". ";return[e,e,e]}return Sr}appNameFormatted(){if(this.properties.appName){let e=this.properties.appName+". ";return[e,e,e]}return Sr}appLinkFormatted(){if(this.properties.appLink){let e=this.properties.appLink+". ";return[e,e,e]}return Sr}seriesFormatted(){let e=this.publication.metadata?.belongsToSeries?.items;if(e&&e.length>0){let t=Xo(e[0]);if(t)return[t+". ",t+". ",t+". "]}return Sr}selectedText(e,t){return e.length>t?e.substring(0,t)+"...":e}buildCitation(e){let t=this.authorsFormatted(),i=this.yearPublishedFormatted(),r=this.bookTitleFormatted(),s=this.editionFormatted(),o=this.publisherFormatted(),a=this.contributorsFormatted(),u=this.eBookVersionFormatted(),l=this.locationFormatted(),c=this.libraryFormatted(),d=this.appNameFormatted(),f=this.appLinkFormatted(),m=this.seriesFormatted(),y=0,g=1,b=2,v=t[y]+r[y]+a[y]+s[y]+l[y]+i[y]+u[y]+c[y]+d[y]+f[y],A=t[b]+i[b]+r[b]+s[b]+o[b]+a[b]+u[b]+l[b]+c[b]+d[b]+f[b],w=t[g]+r[g]+a[g]+s[g]+l[g]+i[g]+m[g]+c[g]+d[g]+f[g],x=this.properties.characters??200,C="\u201C"+this.selectedText(e,x)+"\u201D",T="";return this.properties.styles?.includes($1[0])&&(this.properties.styles.length>1&&(T+="Chicago: <br>"),T+=C+"<br><br>"+v+"<br><br>"),this.properties.styles?.includes($1[2])&&(this.properties.styles.length>1&&(T+="APA: <br>"),T+=C+"<br><br>"+A+"<br><br>"),this.properties.styles?.includes($1[1])&&(this.properties.styles.length>1&&(T+="MLA: <br>"),T+=C+"<br><br>"+w+"<br><br>"),T}async start(){let e=this,t={id:"citationIcon",callback:function(i){let r=e.buildCitation(i);e.copyToClipboard(r)}};this.highlighter?.addSelectionMenuItem(t)}};Xt();var V4;async function yie(){return V4||(V4=(await Promise.resolve().then(()=>(rM(),nM))).PDFNavigator),V4}function vie(n){return n?.isPDF===!0}var Jl=class n{constructor(e,t,i,r,s){this.settings=e;this.navigator=t;this.highlighter=i;this.ttsSettings=r;this.mediaOverlaySettings=s;this.startReadAloud=()=>{this.navigator.startReadAloud()};this.stopReadAloud=()=>{this.navigator.stopReadAloud()};this.pauseReadAloud=()=>{this.navigator.pauseReadAloud()};this.resumeReadAloud=()=>{this.navigator.resumeReadAloud()};this.startReadAlong=()=>{this.navigator.startReadAlong()};this.stopReadAlong=()=>{this.navigator.stopReadAlong()};this.pauseReadAlong=()=>{this.navigator.pauseReadAlong()};this.resumeReadAlong=()=>{this.navigator.resumeReadAlong()};this.saveBookmark=async()=>await this.navigator.modules.bookmarks?.save()??!1;this.saveBookmarkPlus=async()=>this.epubBookmarkModule?.saveBookmarkPlus();this.deleteBookmark=async e=>await this.navigator.modules.bookmarks?.delete(e)??!1;this.deleteAnnotation=async e=>await this.epubAnnotationModule?.deleteAnnotation(e)??!1;this.addAnnotation=async e=>await this.epubAnnotationModule?.addAnnotation(e)??!1;this.updateAnnotation=async e=>await this.epubAnnotationModule?.updateAnnotation(e)??!1;this.changeHighlighterColor=e=>{this.highlighter?.setColor(e)};this.hideAnnotationLayer=()=>this.epubAnnotationModule?.hideAnnotationLayer();this.showAnnotationLayer=()=>this.epubAnnotationModule?.showAnnotationLayer();this.hideLayer=e=>{this.navigator.hideLayer(e)};this.showLayer=e=>{this.navigator.showLayer(e)};this.activateMarker=(e,t)=>{this.navigator.activateMarker(e,t)};this.deactivateMarker=()=>{this.navigator.deactivateMarker()};this.clearDefinitions=async()=>{await this.navigator.modules.definitions?.clearDefinitions()};this.addDefinition=async e=>{await this.navigator.modules.definitions?.addDefinition(e)};this.historyBack=async()=>this.navigator.modules.history?.back();this.historyForward=async()=>this.navigator.modules.history?.forward();this.search=async(e,t)=>await this.epubSearchModule?.search(e,t)??[];this.goToSearchIndex=async(e,t,i)=>{this.navigator.supports(we.Search)&&await this.epubSearchModule?.goToSearchIndex(e,t,i)};this.goToSearchID=async(e,t,i)=>{this.navigator.supports(we.Search)&&await this.epubSearchModule?.goToSearchID(e,t,i)};this.clearSearch=async()=>{this.navigator.supports(we.Search)&&await this.epubSearchModule?.clearSearch()};this.resetUserSettings=async()=>await this.settings.resetUserSettings();this.applyUserSettings=async e=>await this.settings.applyUserSettings(e);this.scroll=async(e,t)=>vie(this.navigator)?this.navigator.scroll(e,t):await this.settings.scroll(e);this.increase=async e=>{this.isTTSIncrementable(e)?this.navigator.supports(we.TTS)&&await this.ttsSettings?.increase(e):this.isMOIncrementable(e)?this.navigator.supports(we.MediaOverlays)&&await this.mediaOverlaySettings?.increase(e):await this.settings.increase(e)};this.decrease=async e=>{this.isTTSIncrementable(e)?this.navigator.supports(we.TTS)&&await this.ttsSettings?.decrease(e):this.isMOIncrementable(e)?this.navigator.supports(we.MediaOverlays)&&await this.mediaOverlaySettings?.decrease(e):await this.settings.decrease(e)};this.resetTTSSettings=()=>{this.navigator.supports(we.TTS)&&this.ttsSettings?.resetTTSSettings()};this.applyTTSSettings=async e=>{this.navigator.supports(we.TTS)&&await this.ttsSettings?.applyTTSSettings(e)};this.applyPreferredVoice=async e=>{this.navigator.supports(we.TTS)&&await this.ttsSettings?.applyPreferredVoice(e)};this.resetMediaOverlaySettings=async()=>{this.navigator.supports(we.MediaOverlays)&&await this.mediaOverlaySettings?.resetMediaOverlaySettings()};this.applyMediaOverlaySettings=async e=>{this.navigator.supports(we.MediaOverlays)&&await this.mediaOverlaySettings?.applyMediaOverlaySettings(e)};this.goTo=async e=>{this.navigator.goTo(e)};this.goToPosition=async e=>this.navigator.goToPosition(e);this.goToPage=async e=>{await this.navigator.goToPage(e)};this.fitToPage=()=>{this.navigator.fitToPage()};this.fitToWidth=()=>{this.navigator.fitToWidth()};this.zoomIn=()=>{this.navigator.zoomIn()};this.zoomOut=()=>{this.navigator.zoomOut()};this.activateHand=()=>{this.navigator.activateHand()};this.deactivateHand=()=>{this.navigator.deactivateHand()};this.copyToClipboard=e=>{this.navigator.modules.contentProtection?.copyToClipboard(e)};this.nextResource=()=>{this.navigator.nextResource()};this.previousResource=()=>{this.navigator.previousResource()};this.nextPage=async()=>{this.navigator.nextPage()};this.previousPage=async()=>{this.navigator.previousPage()};this.snapToSelector=async e=>{this.navigator.snapToSelector?.(e)};this.applyAttributes=e=>{this.navigator.applyAttributes?.(e)};this.stop=()=>{document.body.onscroll=()=>{},this.navigator.stop(),this.settings.stop(),this.ttsSettings?.stop(),this.mediaOverlaySettings?.stop()}}get epubBookmarkModule(){return this.navigator.modules.bookmarks}get epubAnnotationModule(){return this.navigator.modules.annotations}get epubSearchModule(){return this.navigator.modules.search}addEventListener(e,t){this.navigator.addListener(e,t)}static async load(e){let t=e.rights??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};t.enableContentProtection&&e.protection&&await Dd.setupPreloadProtection(e.protection);let i=dt(document,"#D2Reader-Container"),r=fe(document,"#headerMenu"),s=fe(document,"#footerMenu"),o=e.url,a=null,u,l;if(e.epub){let{ZipFetcher:y}=await Promise.resolve().then(()=>(k4(),fM)),{EpubParser:g}=await Promise.resolve().then(()=>(R4(),pM)),{BlobUrlManager:b}=await Promise.resolve().then(()=>(L4(),gM)),{parseEncryptionXml:v,createDeobfuscationTransform:A}=await Promise.resolve().then(()=>(D4(),mM)),w,x=e.epub;if(typeof x=="string"||x instanceof URL){let O=await fetch(x.toString(),e.requestConfig);if(!O.ok)throw new Error(`Failed to fetch EPUB: ${O.status} ${O.statusText}`);w=await O.arrayBuffer()}else x instanceof ArrayBuffer?w=x:w=await x.arrayBuffer();let C=new y(w),T=await g.extractIdentifier(C),k=`${window.location.origin}/epub-local/${encodeURIComponent(T)}/`;C.setBasePath(k),u=C;let _;try{let O=await C.getByHref("META-INF/encryption.xml");O.text&&(_=v(O.text),_.size>0&&C.setEncryptionMap(_))}catch{}l=new b(C.container),_&&_.size>0&&l.setEncryptionMap(_);let R=A(T);if(l.addTransform(R),await l.initialize(),_&&_.size>0){let{TransformingFetcher:O}=await Promise.resolve().then(()=>(F4(),bM));u=new O(C,R)}let L=new URL(k+"manifest.json");if(a=await g.parse(C,L),o=L,_&&_.size>0){let{Properties:O}=await Promise.resolve().then(()=>(Uc(),mS)),U=G=>{for(let j of G){let W=_.get(j.href.replace(k,""));W&&(j.properties=j.properties?j.properties.add({encrypted:W}):new O({encrypted:W}))}};a.readingOrder&&U(a.readingOrder),a.resources&&U(a.resources)}let M=C;await a.autoGeneratePositions(void 0,async O=>(await M.getByHref(O)).bytes?.byteLength??0)}else if(e.publication){let y=e.publication;y instanceof ss?a=y:a=ss.fromJSON(y,o)}if(!a){let{HttpFetcher:y}=await Promise.resolve().then(()=>(Tl(),FA));a=await ss.fromUrl(o,e.requestConfig,new y(e.requestConfig))}let c=new Ka({prefix:a.manifestUrl,useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),d=new Ka({prefix:"r2d2bc-reader",useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),f=new Ka({prefix:"r2d2bc-layers",useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),m=new Wd({store:c});if(a.sample=e.sample,t=Aie(t,a),a.metadata?.conformsTo&&a.metadata?.conformsTo.includes(Io.PDF)){let y=await yd.create({store:d,initialUserSettings:e.userSettings,layout:""}),g=await yie(),{PdfBookmarkModule:b}=await Promise.resolve().then(()=>(vM(),yM)),{PdfSearchModule:v}=await Promise.resolve().then(()=>(wM(),AM)),{PdfAnnotationModule:A}=await Promise.resolve().then(()=>(xM(),CM)),{PdfHistoryModule:w}=await Promise.resolve().then(()=>(TM(),SM)),{PdfViewSettingsModule:x}=await Promise.resolve().then(()=>(_M(),IM)),C=[new b,new v,new A,new w,new x],T=await g.create({mainElement:i,publication:a,settings:y,api:e.api,rights:t,workerSrc:e.workerSrc,annotator:m,initialLastReadingPosition:e.lastReadingPosition,store:c,modules:[...C,...e.modules??[]]});if(t.enableContentProtection&&e.webProtection){let{ContentProtection:k}=await Promise.resolve().then(()=>($M(),qM));await new k(e.webProtection).activate()}return new n(y,T)}else{if(!u){let{HttpFetcher:le}=await Promise.resolve().then(()=>(Tl(),FA)),ce=new le(e.requestConfig);t.autoGeneratePositions?await a.autoGeneratePositions(e.requestConfig,async pe=>{let se=await ce.getByHref(pe);return new TextEncoder().encode(se.text).length}):(e.services?.positions&&await a.fetchPositionsFromService(e.services?.positions.href,ce),e.services?.weight&&await a.fetchWeightsFromService(e.services?.weight.href,ce))}let y=await z1.create({store:f}),g=await yd.create({store:d,initialUserSettings:e.userSettings,headerMenu:r,api:e.api,injectables:a.isFixedLayout?e.injectablesFixed:e.injectables,layout:a.isFixedLayout?"fixed":"reflowable"}),b=await $t.create({layerSettings:y,...e.highlighter}),v=t.enableBookmarks?await Yp.create({annotator:m,headerMenu:r,publication:a,initialAnnotations:e.initialAnnotations,...e.bookmarks}):void 0,A=t.enableAnnotations?await Kp.create({annotator:m,publication:a,initialAnnotations:e.initialAnnotations,highlighter:b,headerMenu:r,...e.annotations}):void 0,w=t.enableTTS,x=w?await D1.create({store:d,initialTTSSettings:e.tts,headerMenu:r}):void 0,C;w&&x&&(C=await K1.create({tts:x,headerMenu:r,highlighter:b,...e.tts}));let T=t.enableSearch?await B1.create({headerMenu:r,publication:a,highlighter:b,...e.search}):void 0,k=t.enableDefinitions?await Y1.create({publication:a,highlighter:b,...e.define}):void 0,_=t.enableTimeline?await Xp.create({publication:a}):void 0,R=t.enableContentProtection?await Dd.create({...e.protection}):void 0,L=t.enableCitations?await Yd.create({publication:a,highlighter:b,...e.citations}):void 0,M=t.enableMediaOverlays,O=M?await qp.create({store:d,initialMediaOverlaySettings:e.mediaOverlays,headerMenu:r,...e.mediaOverlays}):void 0,U=M?await Qp.create({publication:a,settings:O,...e.mediaOverlays}):void 0,j=t.enablePageBreaks&&a.isReflowable?await V1.create({publication:a,headerMenu:r,...e.pagebreak}):void 0,W=t.enableLineFocus?await Kd.create({publication:a,highlighter:b,...e.lineFocus}):void 0,z=t.enableHistory?await q1.create({annotator:m,publication:a,headerMenu:r}):void 0,$=t.enableConsumption?await Vp.create({publication:a,...e.consumption}):void 0,te=await Va.create({mainElement:i,headerMenu:r,footerMenu:s,publication:a,settings:g,annotator:m,initialLastReadingPosition:e.lastReadingPosition,api:e.api,rights:t,tts:e.tts,sample:e.sample,requestConfig:e.requestConfig,fetcher:u,blobUrlManager:l,injectables:a.isFixedLayout?e.injectablesFixed??[]:e.injectables,attributes:e.attributes,services:e.services,highlighter:b,modules:[v,A,C,T,k,_,R,L,U,j,W,z,$,...e.modules??[]]});return new n(g,te,b,x,O)}}get hasMediaOverlays(){return this.navigator.publication.hasMediaOverlays??!1}get tableOfContents(){return $o(this.navigator.tableOfContents())??[]}get landmarks(){return $o(this.navigator.landmarks())??[]}get pageList(){return $o(this.navigator.pageList())??[]}get readingOrder(){return $o(this.navigator.readingOrder())??[]}get bookmarks(){return this.navigator.modules.bookmarks?.list()??[]}get annotations(){return this.navigator.modules.annotations?.getAll()??[]}get publicationLayout(){return this.navigator.publication.layout}get canGoBack(){return this.navigator.modules.history?.canGoBack()??!1}get canGoForward(){return this.navigator.modules.history?.canGoForward()??!1}get currentResource(){return this.navigator.currentResource()}get mostRecentNavigatedTocItem(){return this.navigator.mostRecentNavigatedTocItem?.()??void 0}get totalResources(){return this.navigator.totalResources()}get publicationLanguage(){return this.navigator.publication.metadata?.languages}get currentSettings(){return this.settings.currentSettings}isTTSIncrementable(e){return e==="pitch"||e==="rate"||e==="volume"}isMOIncrementable(e){return e==="mo_rate"||e==="mo_volume"}get currentLocator(){return this.navigator.currentLocator()}get positions(){return this.navigator.positions()}get atStart(){return this.navigator.atStart()}get atEnd(){return this.navigator.atEnd()}async applyLineFocusSettings(e){if(e.lines&&this.navigator.modules.lineFocus){let t=this.navigator.modules.lineFocus.properties.lines??1;this.navigator.modules.lineFocus.index=this.navigator.modules.lineFocus.index*t/parseInt(e.lines),this.navigator.modules.lineFocus.index=Math.abs(parseInt(this.navigator.modules.lineFocus.index.toFixed())),this.navigator.modules.lineFocus.properties.lines=parseInt(e.lines),this.navigator.modules.lineFocus.isActive&&await this.navigator.modules.lineFocus.enableLineFocus()}e.debug!==void 0&&this.navigator.modules.lineFocus&&(this.navigator.modules.lineFocus.isDebug=e.debug,this.navigator.modules.lineFocus.isActive&&await this.navigator.modules.lineFocus.enableLineFocus())}lineUp(){this.navigator.modules.lineFocus?.lineUp()}lineDown(){this.navigator.modules.lineFocus?.lineDown()}async enableLineFocus(){await this.navigator.modules.lineFocus?.enableLineFocus()}async lineFocus(e){e?await this.navigator.modules.lineFocus?.enableLineFocus():this.navigator.modules.lineFocus?.disableLineFocus()}disableLineFocus(){this.navigator.modules.lineFocus?.disableLineFocus()}};function Aie(n,e){return e.isFixedLayout&&(n.enableAnnotations=!1,n.enableSearch=!1,n.enableTTS=!1,n.enableDefinitions=!1,n.enablePageBreaks=!1,n.enableLineFocus=!1),e.sample?.isSampleRead&&(n.enableAnnotations=!1,n.enableSearch=!1,n.enableTTS=!1,n.enableDefinitions=!1,n.enableTimeline=!1,n.enableMediaOverlays=!1,n.enablePageBreaks=!1,n.enableLineFocus=!1),n}tr();Xt();hi();mv();Dp();Er();P4();H1();Tl();k4();R4();L4();Gd();F4();D4();var wie=Jl,Eie=Jl.load;return vj(Cie);})();
665
+ `||t==="\r"||t===" "||i===65279){e++;continue}return t!=="<"}return!1}function bZ(n){let e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return new TextDecoder().decode(t)}I();var G1=class{constructor(e,t){this.publication=e;this.settings=t;this.objectUrlRegistry=new Map}injectStaticIntoDoc(e,t,i,r){let s=e.head;if(!s)return;let o={publication:this.publication,resourceHref:r,doc:e},a=c=>{let d=this.objectUrlRegistry.get(t);d||(d=[],this.objectUrlRegistry.set(t,d)),d.push(c)},u=c=>{if(c.url)return c.url;if(c.blob){let d=URL.createObjectURL(c.blob);return a(d),d}return null},l=(c,d)=>{d.r2before?s.insertBefore(c,s.firstChild):d.r2default?s.insertBefore(c,s.childNodes[1]):s.appendChild(c)};for(let c of i??[])if(!(c.when&&!c.when(o))){if(c.type==="style"){if(c.fontFamily&&this.settings.initAddedFont(),c.r2after&&c.appearance&&this.settings.initAddedAppearance(),c.systemFont&&!c.url&&!c.blob)continue;let d=u(c);if(!d)continue;let f=yZ(d);j1(f,c.attributes),l(f,{r2before:c.r2before,r2default:c.r2default,r2after:c.r2after})}else if(c.type==="script"){let d=u(c);if(!d)continue;let f=vZ(d,c.async??!1,c.module??!1);j1(f,c.attributes),s.appendChild(f)}else if(c.type==="style-inline"){let d=AZ(c.source);j1(d,c.attributes),l(d,{r2before:c.r2before,r2default:c.r2default,r2after:c.r2after})}else if(c.type==="script-inline"){let d=wZ(c.source,c.async??!1,c.module??!1);j1(d,c.attributes),s.appendChild(d)}}}cleanupForIframe(e){let t=this.objectUrlRegistry.get(e);if(t){for(let i of t)URL.revokeObjectURL(i);this.objectUrlRegistry.delete(e)}}};function yZ(n){let e=document.createElement("link");return e.rel="stylesheet",e.type="text/css",e.href=n,e}function vZ(n,e,t){let i=document.createElement("script");return i.type=t?"module":"text/javascript",i.src=n,i.async=e,i.appendChild(document.createTextNode("")),i}function AZ(n){let e=document.createElement("style");return e.type="text/css",e.textContent=n,e}function wZ(n,e,t){let i=document.createElement("script");return i.type=t?"module":"text/javascript",i.async=e,i.textContent=n,i}function j1(n,e){if(e)for(let[t,i]of Object.entries(e))n.setAttribute(t,i)}I();Gd();var Il=class{constructor(e,t,i){this.inner=e;this.getContent=t;let r=[...i.readingOrder??[],...i.resources??[]];this.publicationResourceHrefs=new Set(r.map(s=>i.getAbsoluteHref(s.href)))}async get(e){if(!this.isPublicationResource(e.href))return this.inner.get(e);let t=await this.getContent(e.href);return t!==void 0?{text:t,headers:{},mediaType:e.type??"application/xhtml+xml",href:e.href}:this.inner.get(e)}async getByHref(e){if(!this.isPublicationResource(e))return this.inner.getByHref(e);let t=await this.getContent(e);return t!==void 0?{text:t,headers:{},mediaType:ro(e),href:e}:this.inner.getByHref(e)}cancel(e){this.inner.cancel?.(e)}destroy(){this.inner.destroy?.()}isPublicationResource(e){return this.publicationResourceHrefs.has(e)}};I();var za=class{constructor(e){this.inner=e;this.cache=new Map;this.pending=new Map}async get(e){let t=this.cache.get(e.href);if(t)return t;let i=this.pending.get(e.href);if(i)return i;let r=this.inner.get(e).then(s=>(this.cache.set(e.href,s),this.pending.delete(e.href),s)).catch(s=>{throw this.pending.delete(e.href),s});return this.pending.set(e.href,r),r}async getByHref(e){let t=this.cache.get(e);if(t)return t;let i=this.pending.get(e);if(i)return i;let r=this.inner.getByHref(e).then(s=>(this.cache.set(e,s),this.pending.delete(e),s)).catch(s=>{throw this.pending.delete(e),s});return this.pending.set(e,r),r}async prefetch(e){if(!(this.cache.has(e.href)||this.pending.has(e.href)))try{await this.get(e)}catch{}}async has(e){return this.cache.has(e.href)}evict(e){this.cache.delete(e)}clear(){this.cache.clear()}cancel(e){this.inner.cancel?.(e)}destroy(){this.cache.clear(),this.pending.clear(),this.inner.destroy?.()}};var wn=$e(jt());HA();var Va=class n extends hl{constructor(t,i=void 0,r=void 0,s,o,a,u,l,c,d,f,m,y,g,b,v){super();this.iframes=[];this.modules=new Go(this.registry);this.fxlZoomKeyHandler=t=>{if(/input|select|option|textarea/i.test(t.target.tagName))return;let i=t.key;if(i==="="||i==="+")this.zoomIn();else if(i==="-")this.zoomOut();else if(i==="0")this.fitToPage();else return;t.preventDefault()};this.sideNavExpanded=!1;this.currentChapterLink={href:""};this.currentSpreadLinks={};this.rights={autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};this.didInitKeyboardEventHandler=!1;this.fxlContentWidth=0;this.fxlContentHeight=0;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.reload=async()=>{let t;if(this.annotator&&(t=await this.annotator.getLastReadingPosition()),t){let i=this.publication.getAbsoluteHref(t.href);wn.default.log(t.href),wn.default.log(i),t.href=i,await this.navigate(t)}};this.savePosition=(0,W1.default)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,W1.default)(()=>{this.view?.atStart()&&this.view?.atEnd()?(this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit(xe.ResourceFits,{href:this.currentChapterLink.href})):this.view?.atEnd()?(this.api?.resourceAtEnd&&this.api?.resourceAtEnd(),this.emit(xe.ResourceEnd,{href:this.currentChapterLink.href})):this.view?.atStart()&&(this.api?.resourceAtStart&&this.api?.resourceAtStart(),this.emit(xe.ResourceStart,{href:this.currentChapterLink.href}))},200);this._blobUrlManager=v,this.highlighter=y,this.highlighter&&(this.highlighter.navigator=this);for(let A of g??[])if(A){if(A.hostType!==nt.Epub){wn.default.warn(`Module "${A.name}" requires host type "${A.hostType}" but navigator is EPUB \u2014 skipping`);continue}this.registry.register(A,this)}if(b)this._fetcher=new za(b);else{let A=new no(m);o?.getContent&&(A=new Il(A,o.getContent,s)),m?.encoded&&(A=new U1(A)),this._fetcher=new za(A)}this.settings=t,this.annotator=i,this.attributes=c??{},this.view=t.view,this.view.attributes=this.attributes,this.view.host={checkResourcePosition:()=>this.checkResourcePosition(),recalculateContentProtection:A=>this.modules.contentProtection?.recalculate(A),isContentProtectionEnabled:()=>!!this.rights.enableContentProtection,isFixedLayout:()=>this.publication.isFixedLayout,isReflowable:()=>this.publication.isReflowable,setDirection:A=>this.setDirection(A)},this.eventHandler=new gd(this),this.touchEventHandler=new Hd(this),this.keyboardEventHandler=new Ud(this),this.initialLastReadingPosition=r,this.publication=s,this.api=o,this.rights=a??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1},this.tts=u,this.injectables=l,this.services=d,this.sample=f,this.requestConfig=m,this.sampleReadEventHandler=new jd(this),this.injectableManager=new G1(s,t)}get fetcher(){return this._fetcher}supports(t){return t===we.Zoom?this.publication.isFixedLayout:t===we.MediaOverlays?this.registry.has(t)&&this.hasMediaOverlays:this.registry.has(t)}getFxlCurrentScale(){let t=this.spreads?.style.transform?.match(/scale\(([^)]+)\)/);return t?parseFloat(t[1]):1}fitToPage(){this.publication.isFixedLayout&&this.handleResize()}zoomIn(){this.publication.isFixedLayout&&this.setFxlScale(this.getFxlCurrentScale()*1.15)}zoomOut(){this.publication.isFixedLayout&&this.setFxlScale(this.getFxlCurrentScale()/1.15)}setFxlScale(t){!this.spreads||!this.fxlZoomContainer||(this.spreads.style.transform="scale("+t+")",this.updateFxlZoomContainer(t))}updateFxlZoomContainer(t){!this.fxlZoomContainer||!this.fxlContentWidth||!this.fxlContentHeight||(this.fxlZoomContainer.style.width=this.fxlContentWidth*t+"px",this.fxlZoomContainer.style.height=this.fxlContentHeight*t+"px",this.spreads.style.width=this.fxlContentWidth+"px",this.spreads.style.height=this.fxlContentHeight+"px",this.fxlHandTool&&requestAnimationFrame(()=>{if(!this.fxlScrollContainer)return;this.fxlScrollContainer.scrollWidth>this.fxlScrollContainer.clientWidth||this.fxlScrollContainer.scrollHeight>this.fxlScrollContainer.clientHeight?this.activateHand():this.deactivateHand()}))}setupFxlPan(){let t=this.fxlScrollContainer;t&&(this.fxlPanOverlay=document.createElement("div"),this.fxlPanOverlay.style.position="absolute",this.fxlPanOverlay.style.top="0",this.fxlPanOverlay.style.left="0",this.fxlPanOverlay.style.width="100%",this.fxlPanOverlay.style.height="100%",this.fxlPanOverlay.style.pointerEvents="none",this.fxlPanOverlay.style.zIndex="1",this.fxlZoomContainer.style.position="relative",this.fxlZoomContainer.appendChild(this.fxlPanOverlay),this.fxlHandTool=new _l({element:t}))}activateHand(){if(!this.publication.isFixedLayout)return;this.fxlPanOverlay&&(this.fxlPanOverlay.style.pointerEvents="auto"),this.fxlHandTool?.activate();let t=document.querySelector("#fxl-pan a");t&&(t.classList.add("dita-active"),t.style.color="#039be5")}deactivateHand(){if(!this.publication.isFixedLayout)return;this.fxlPanOverlay&&(this.fxlPanOverlay.style.pointerEvents="none"),this.fxlHandTool?.deactivate();let t=document.querySelector("#fxl-pan a");t&&(t.classList.remove("dita-active"),t.style.color="")}static async create(t){let i=new this(t.settings,t.annotator||void 0,t.initialLastReadingPosition||void 0,t.publication,t.api,t.rights,t.tts,t.injectables,t.attributes,t.services,t.sample,t.requestConfig,t.highlighter,t.modules,t.fetcher,t.blobUrlManager);return await i.start(t.mainElement,t.headerMenu,t.footerMenu),await i.registry.setupAll(),new Promise(r=>r(i))}stop(){wn.default.log("Iframe navigator stop"),Ae(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),Ae(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),Ae(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ae(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),Ae(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ae(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),Ae(this.tryAgainButton,"click",this.tryAgain.bind(this)),Ae(this.goBackButton,"click",n.goBack.bind(this)),Ae(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),Ae(window,"resize",this.onResize),this.iframes.forEach(t=>{this.injectableManager.cleanupForIframe(t),Ae(t,"resize",this.onResize),t.remove()}),this.didInitKeyboardEventHandler&&this.keyboardEventHandler.removeEvents(document),this.registry.stopAll(),this._fetcher?.destroy?.(),this._blobUrlManager?.destroy()}setDirection(t){let i="";t==="rtl"||t==="ltr"?i=t:t==="auto"&&(i=this.publication.metadata?.readingProgression||this.publication.metadata?.otherMetadata?.["rendition:spread-direction"]||"ltr"),(i==="rtl"||i==="ltr")&&(this.publication.isFixedLayout&&(this.spreads.style.flexDirection=i==="rtl"?"row-reverse":"row"),this.keyboardEventHandler.rtl=i==="rtl",this.api?.direction&&this.api?.direction(i),this.emit(xe.Direction,i))}async start(t,i,r){this.headerMenu=i,this.mainElement=t;try{let m=dt(t,"main#iframe-wrapper");m.style.overflow="auto";let y=fe(t,"main#iframe-wrapper iframe"),g=fe(t,"#second");if(y&&(y.style.verticalAlign="top",this.iframes.push(y)),g&&(g.style.verticalAlign="top",this.iframes.push(g)),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.publication.isFixedLayout&&(this.publication.metadata?.otherMetadata?.["rendition:spread"]??this.publication.metadata?.otherMetadata?.rendition?.spread)==="none"&&(this.settings.columnCount=1),this.iframes.length===0){m.style.overflow="auto";let b=document.createElement("iframe");if(b.setAttribute("SCROLLING","no"),b.setAttribute("allowtransparency","true"),b.style.verticalAlign="top",this.iframes.push(b),this.publication.isFixedLayout){this.spreads=document.createElement("div"),this.firstSpread=document.createElement("div"),this.spreads.style.display="flex",this.spreads.style.transformOrigin="0 0",this.spreads.appendChild(this.firstSpread),this.firstSpread.appendChild(this.iframes[0]),this.fxlScrollContainer=document.createElement("div"),this.fxlScrollContainer.style.position="absolute",this.fxlScrollContainer.style.top="0",this.fxlScrollContainer.style.right="0";let v=document.getElementById("container-view-timeline");this.fxlScrollContainer.style.left=v&&this.rights.enableTimeline?"70px":"0";let A=document.getElementById("reader-info-bottom");this.fxlScrollContainer.style.bottom=A?A.offsetHeight+"px":"0",this.fxlScrollContainer.style.overflow="auto",this.fxlScrollContainer.style.display="flex",this.fxlZoomContainer=document.createElement("div"),this.fxlZoomContainer.style.margin="auto",this.fxlZoomContainer.style.flexShrink="0",this.fxlZoomContainer.style.overflow="hidden",this.attributes?.fixedLayoutShadow!==!1&&(this.fxlZoomContainer.style.padding="12px",this.fxlZoomContainer.style.boxSizing="content-box"),this.fxlZoomContainer.appendChild(this.spreads),this.fxlScrollContainer.appendChild(this.fxlZoomContainer),m.style.position="relative",m.appendChild(this.fxlScrollContainer),document.addEventListener("keydown",this.fxlZoomKeyHandler),this.setupFxlPan();let w="";switch(this.settings.direction){case 0:w="auto";break;case 1:w="ltr";break;case 2:w="rtl";break}this.setDirection(w)}else b.setAttribute("height","100%"),b.setAttribute("width","100%"),m.appendChild(this.iframes[0]);if(this.publication.isFixedLayout)if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){let v=document.createElement("div");this.spreads.appendChild(v);let A=document.createElement("iframe");A.setAttribute("SCROLLING","no"),A.setAttribute("allowtransparency","true"),A.style.opacity="1",A.style.border="none",A.style.overflow="hidden",A.style.verticalAlign="top",this.iframes.push(A),v.appendChild(this.iframes[1]),this.attributes?.fixedLayoutShadow!==!1&&(this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",v.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",v.style.boxShadow="0 0 8px 2px #ccc")}else this.attributes?.fixedLayoutShadow!==!1&&(this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc");else{let v=this.iframes[0],A=this.attributes?.iframe?.padding;A!==void 0?typeof A=="number"?v.style.padding=A+"px":(A.top!==void 0&&(v.style.paddingTop=A.top+"px"),A.bottom!==void 0&&(v.style.paddingBottom=A.bottom+"px"),A.left!==void 0&&(v.style.paddingLeft=A.left+"px"),A.right!==void 0&&(v.style.paddingRight=A.right+"px")):this.attributes?.iframePaddingTop!==void 0&&(v.style.paddingTop=this.attributes.iframePaddingTop+"px")}}if(!this.publication.isFixedLayout){this.iframes.length===2&&this.iframes.pop();let b="";switch(this.settings.direction){case 0:b="auto";break;case 1:b="ltr";break;case 2:b="rtl";break}this.setDirection(b)}if(this.loadingMessage=fe(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=F1,this.loadingMessage.style.display="none"),this.errorMessage=fe(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=cR,this.errorMessage.style.display="none"),this.tryAgainButton=fe(t,"button[class=try-again]"),this.goBackButton=fe(t,"button[class=go-back]"),this.infoTop=fe(t,"div[class='dita-info top']"),this.infoBottom=fe(t,"div[class='dita-info bottom']"),this.headerMenu&&(this.bookTitle=fe(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=fe(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=fe(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=fe(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=fe(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=fe(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=fe(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=fe(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=fe(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=fe(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=fe(this.headerMenu,"#container-view-pagelist")),r&&(this.linksBottom=fe(r,"ul.links.bottom")),r&&(this.linksMiddle=fe(r,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=fe(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=fe(t,"#next-chapter")),r&&(this.nextPageAnchorElement=fe(r,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=fe(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=fe(t,"#previous-chapter")),r&&(this.previousPageAnchorElement=fe(r,"a[rel=prev]")),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.newPosition=void 0,this.newElementId=void 0,this.isBeingStyled=!0,this.isLoading=!0,this.settings.setIframe(this.iframes[0]),this.settings.onSettingsChange(this.handleResize.bind(this)),this.settings.onColumnSettingsChange(this.handleNumberOfIframes.bind(this)),this.settings.onViewChange(this.updateBookView.bind(this)),this.initialLastReadingPosition&&this.annotator?.initLastReadingPosition(this.initialLastReadingPosition),this.headerMenu){var s=fe(this.headerMenu,"#menu-button-search"),o=fe(this.headerMenu,"#menu-button-tts"),a=fe(this.headerMenu,"#menu-button-bookmark"),u=fe(this.headerMenu,"#menu-button-play"),l=fe(this.headerMenu,"#menu-button-pause"),c=fe(this.headerMenu,"#menu-button-mediaoverlay");if(!this.rights.enableBookmarks){a&&a.parentElement?.style.setProperty("display","none");var d=fe(this.headerMenu,"#sidenav-section-bookmarks");d&&d.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var f=fe(this.headerMenu,"#sidenav-section-highlights");f&&f.style.setProperty("display","none")}this.rights.enableTTS||o&&o.parentElement?.style.setProperty("display","none"),this.rights.enableSearch||s&&s.parentElement?.style.setProperty("display","none"),s&&this.publication.isFixedLayout&&s.parentElement?.style.setProperty("display","none"),this.hasMediaOverlays?(u&&u.parentElement?.style.removeProperty("display"),l&&l.parentElement?.style.removeProperty("display"),c&&c.parentElement?.style.removeProperty("display")):(u&&u.parentElement?.style.setProperty("display","none"),l&&l.parentElement?.style.setProperty("display","none"),c&&c.parentElement?.style.setProperty("display","none"))}else s&&s.parentElement?.style.setProperty("display","none"),o&&o.parentElement?.style.setProperty("display","none"),a&&a.parentElement?.style.setProperty("display","none");return this.setupEvents(),await this.loadManifest()}catch(m){return wn.default.error(m),this.abortOnError(m),Promise.reject(m)}}setupEvents(){for(let t of this.iframes)ee(t,"load",this.handleIFrameLoad.bind(this,t));ee(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),ee(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),ee(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ee(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),ee(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ee(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),ee(this.tryAgainButton,"click",this.tryAgain.bind(this)),ee(this.goBackButton,"click",n.goBack.bind(this)),ee(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),ee(window,"resize",this.onResize);for(let t of this.iframes)ee(t,"resize",this.onResize)}updateBookView(t){this.view?.layout==="fixed"?(this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.eventHandler&&(this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousChapterClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextChapterClick.bind(this),this.keyboardEventHandler.onKeydown=this.handleKeydownFallthrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this))):(this.settings.isPaginated().then(i=>{if(i)this.view.height=qu(this.iframes[0],this.attributes),this.infoBottom&&this.infoBottom.style.removeProperty("display"),document.body.onscroll=()=>{},this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="unset"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="unset"),this.chapterTitle&&(this.chapterTitle.style.display="inline"),this.chapterPosition&&(this.chapterPosition.style.display="inline"),this.remainingPositions&&(this.remainingPositions.style.display="inline"),this.eventHandler&&(this.eventHandler.onInternalLink=this.handleInternalLink.bind(this),this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this),this.keyboardEventHandler.onKeydown=this.handleKeydownFallthrough.bind(this));else{this.infoBottom&&(this.infoBottom.style.display="none"),this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),this.view?.layout==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")):this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"));let r=(0,W1.default)(()=>{this.isScrolling=!1},200),s=dt(document,"#iframe-wrapper");s.onscroll=async()=>{this.isScrolling=!0,await this.savePosition(),this.view?.atEnd(),this.view?.layout==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")):(this.settings.isPaginated().then(o=>{o||(this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))}),this.checkResourcePosition()),r()},this.chapterTitle&&(this.chapterTitle.style.display="none"),this.chapterPosition&&(this.chapterPosition.style.display="none"),this.remainingPositions&&(this.remainingPositions.style.display="none"),this.eventHandler&&(this.eventHandler.onInternalLink=this.handleInternalLink.bind(this),this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this),this.keyboardEventHandler.onKeydown=this.handleKeydownFallthrough.bind(this))}}),t?.skipDrawingAnnotations||setTimeout(async()=>{await this.highlighter?.prepareContainers(this.iframes[0].contentWindow),this.highlighter&&(this.rights.enableAnnotations&&this.modules.annotations&&await this.modules.annotations.drawHighlights(),this.rights.enableBookmarks&&this.modules.bookmarks&&await this.modules.bookmarks.drawBookmarks(),this.rights.enableSearch&&this.modules.search&&(await this.highlighter.destroyHighlights(1),this.modules.search.drawSearch()),this.rights.enablePageBreaks&&this.modules.pageBreaks&&(await this.highlighter.destroyHighlights(3),await this.modules.pageBreaks.drawPageBreaks()),this.rights.enableDefinitions&&this.modules.definitions&&await this.modules.definitions.drawDefinitions())},200))}async loadManifest(){try{let t=(l,c,d=!1)=>{var f=document.createElement("ul");d&&(f=document.createElement("ol")),f.className="sidenav-toc";for(let m of c){let y=document.createElement("li"),g=document.createElement("a"),b=document.createElement("span");g.className="chapter-link",g.tabIndex=-1;let v="";m.href?(v=this.publication.getAbsoluteHref(m.href),g.href=v,g.innerHTML=m.title||"",y.appendChild(g)):(b.innerHTML=m.title||"",b.className="chapter-title",y.appendChild(b)),m.children?.items&&m.children.items.length>0&&t(y,m.children.items,!0),f.appendChild(y)}ee(f,"click",m=>{if(m.preventDefault(),m.stopPropagation(),m.target&&m.target.tagName.toLowerCase()==="a"){let y=m.target;if(y.className.indexOf("active")!==-1)this.hideView();else{let g={progression:0};if(y.href.indexOf("#")!==-1){let v=y.href.slice(y.href.indexOf("#")+1);v!==void 0&&(g={fragment:v})}let b={href:y.href,locations:g,type:y.type,title:y.title};this.hideView(),this.navigate(b)}}}),l.appendChild(f)},i=this.publication.tableOfContents,r=this.publication.landmarks,s=this.publication.pageList;this.tocView&&(i.length?t(this.tocView,i):this.tocView.parentElement?.parentElement?.removeChild(this.tocView.parentElement)),this.pageListView&&(s?.length?t(this.pageListView,s):this.pageListView.parentElement?.parentElement?.removeChild(this.pageListView.parentElement)),this.landmarksView&&(r?.length?t(this.landmarksView,r):this.landmarksSection.parentElement?.removeChild(this.landmarksSection));let o;this.annotator&&(o=await this.annotator.getLastReadingPosition());let a=this.publication.getStartLink(),u;if(a&&a.href&&(u=this.publication.getAbsoluteHref(a.href)),o){let l=this.publication.getAbsoluteHref(o.href);wn.default.log(o.href),wn.default.log(l),o.href=l,await this.navigate(o)}else if(u){let l={href:u,locations:{progression:0},created:new Date,title:a?.title};await this.navigate(l)}return new Promise(l=>l())}catch(t){return wn.default.error(t),this.abortOnError(t),new Promise((i,r)=>r(t)).catch(()=>{})}}async handleIFrameLoad(t){this.errorMessage&&(this.errorMessage.style.display="none"),this.showLoadingMessageAfterDelay();try{let i=0;this.newPosition&&(i=this.newPosition.locations.progression),await this.handleResize(),this.updateBookView({skipDrawingAnnotations:!0}),await this.settings.applyProperties();let r=this.currentChapterLink.href;if(r){let c=this.publication.getPreviousSpineItem(r);c&&c.href&&(this.previousChapterLink={href:c.href,title:c.title,type:c.type})}this.previousChapterAnchorElement&&(this.previousChapterLink&&this.previousChapterLink.href?(this.previousChapterAnchorElement.href=this.publication.getAbsoluteHref(this.previousChapterLink.href),this.previousChapterAnchorElement.className=this.previousChapterAnchorElement.className.replace(" disabled","")):(this.previousChapterAnchorElement.removeAttribute("href"),this.previousChapterAnchorElement.className+=" disabled"));let s=this.publication.getNextSpineItem(r);s?this.nextChapterLink={href:s.href,title:s.title,type:s.type}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink&&this.nextChapterLink.href?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.modules.history&&this.modules.history.setup(),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(r),this.publication.metadata?.title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.metadata?.title.toString());let o=this.publication.getSpineItem(r);o!==void 0&&(this.currentChapterLink.title=o.title,this.currentChapterLink.type=o.type);let a=this.publication.getTOCItem(r);this.currentTocUrl!==void 0&&(a=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&a!==void 0&&a.title&&(this.currentChapterLink.title=a.title),!this.currentChapterLink.type&&a!==void 0&&a.type&&(this.currentChapterLink.title=a.title),this.currentChapterLink.title?(this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"),this.api?.chapterInfo&&this.api.chapterInfo(this.currentChapterLink.title),this.emit(xe.ChapterInfo,this.currentChapterLink.title)):(this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),this.api?.chapterInfo&&this.api.chapterInfo(void 0),this.emit(xe.ChapterInfo,void 0)),this.view?.layout!=="fixed"&&this.highlighter!==void 0&&await this.highlighter.initialize(t);let l=t.contentDocument?.body?.querySelector("details");if(l){let c=this;l.addEventListener("toggle",async d=>{await c.view?.setIframeHeight?.(t)})}if(this.eventHandler&&(this.eventHandler.setupEvents(t.contentDocument),this.touchEventHandler.setupEvents(t.contentDocument),this.keyboardEventHandler.setupEvents(t.contentDocument),this.touchEventHandler.setupEvents(this.errorMessage),this.didInitKeyboardEventHandler||(this.keyboardEventHandler.keydown(document),this.didInitKeyboardEventHandler=!0)),this.publication.isFixedLayout&&t.contentDocument&&t.contentDocument.addEventListener("keydown",this.fxlZoomKeyHandler),this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(t.height="0",this.view?.setIframeHeight?.(t)),this.rights.enableContentProtection&&this.modules.contentProtection&&await this.modules.contentProtection.initialize(t),this.rights.enableConsumption&&this.modules.consumption&&await this.modules.consumption.initialize(t),this.rights.enableAnnotations&&this.modules.annotations&&await this.modules.annotations.initialize(t),this.rights.enableBookmarks&&this.modules.bookmarks&&await this.modules.bookmarks.initialize(),this.rights.enableLineFocus&&this.modules.lineFocus&&await this.modules.lineFocus.initialize(t),this.rights.enableTTS&&this.modules.tts){let c=t.contentDocument?.body;await this.modules.tts.initialize(c)}return this.rights.enableTimeline&&this.modules.timeline&&await this.modules.timeline.initialize(),this.rights.enableMediaOverlays&&this.modules.mediaOverlays&&this.hasMediaOverlays&&await this.modules.mediaOverlays.initialize(),setTimeout(async()=>{if(this.newElementId){let c=t.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(c),this.newElementId=void 0}else if(this.newPosition&&this.newPosition.highlight){let c=this.newPosition.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;c&&this.view?.goToCssSelector(c)}else i!==void 0&&i>=0&&(this.view?.layout!=="fixed"&&this.view?.padOddColumns?.(),this.view?.goToProgression(i));if(this.newPosition=void 0,this.rights?.enableContentProtection&&this.modules.contentProtection!==void 0&&await this.modules.contentProtection.recalculate(10),this.hideLoadingMessage(),this.showIframeContents(t),this.rights.enableMediaOverlays&&this.modules.mediaOverlays&&this.hasMediaOverlays){let c=this.currentLink();await this.modules.mediaOverlays?.initializeResource(c)}await this.updatePositionInfo(),await this.view?.setSize(),setTimeout(()=>{this.modules.mediaOverlays&&(this.modules.mediaOverlays.settings.resourceReady=!0,this.modules.mediaOverlays.settings.playing&&this.modules.mediaOverlays.bindClickHandler())},300)},200),new Promise(c=>c())}catch(i){return wn.default.error(i),this.abortOnError(i),Promise.reject(i)}}abortOnError(t){if(this.api?.onError){let i=t instanceof Error?t:typeof t=="string"?new Error(t):new Error("An unknown error occurred in the EpubNavigator.");this.api.onError(i),this.emit(xe.Error,i)}else this.errorMessage&&(this.errorMessage.style.display="block"),this.isLoading&&this.hideLoadingMessage()}tryAgain(){this.precessContentForIframe()}precessContentForIframe(){let t=this;var i=this.publication.getSpineIndex(this.currentChapterLink.href);let s=(i!==void 0?this.publication.readingOrder?.[i]:void 0)?.properties?.page;var o;s==="left"?o=!0:s==="right"?o=!1:s==="center"?o=!0:o=(i??0)%2===1,this.showLoadingMessageAfterDelay(),this.currentSpreadLinks={};let a=async f=>(await t._fetcher.getByHref(f)).text;function u(f,m,y){let b=new DOMParser().parseFromString(f,"application/xhtml+xml");if(b.head&&b.getElementsByTagName("base").length===0&&b.head.insertBefore(n.createBase(m),b.head.firstChild),t.injectableManager.injectStaticIntoDoc(b,y,t.injectables,m),t._blobUrlManager){let A=t.publication.getRelativeHref(m);t._blobUrlManager.rewriteDom(b,A)}return b.documentElement.outerHTML}function l(f,m){t.injectableManager.cleanupForIframe(t.iframes[0]);let y=u(f,m,t.iframes[0]),g=t.iframes[0].contentDocument;g&&(g.open(),g.write(y),g.close())}function c(f,m){t.injectableManager.cleanupForIframe(t.iframes[1]);let y=u(f,m,t.iframes[1]),g=t.iframes[1].contentDocument;g&&(g.open(),g.write(y),g.close())}let d=async(f,m)=>{let y=await a(f);m===0?l.call(t,y,f):c.call(t,y,f)};if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(o){if(this.currentSpreadLinks.left={href:this.currentChapterLink.href},d(this.currentChapterLink.href,0),this.iframes.length===2)if(s!=="center"&&(i??0)<this.publication.readingOrder.length-1){let f=this.publication.getNextSpineItem(this.currentChapterLink.href);if(f){let m=this.publication.getAbsoluteHref(f.href);this.currentSpreadLinks.right={href:m},d(m,1)}}else this.injectableManager.cleanupForIframe(this.iframes[1]),this.iframes[1].src="about:blank",this.currentSpreadLinks.right=void 0}else{if((i??0)>0){let f=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(f){let m=this.publication.getAbsoluteHref(f.href);this.currentSpreadLinks.left={href:m},d(m,0)}}else this.injectableManager.cleanupForIframe(this.iframes[0]),this.iframes[0].src="about:blank",this.currentSpreadLinks.left=void 0;this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},d(this.currentChapterLink.href,1))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},d(this.currentChapterLink.href,0);else this.currentSpreadLinks.left={href:this.currentChapterLink.href},d(this.currentChapterLink.href,0);this.publication.isFixedLayout&&setTimeout(()=>{let f,m,y;if(i===0&&this.iframes?.length===2?y=this.iframes[1].contentDocument:y=this.iframes[0].contentDocument,y&&y.body&&(f=getComputedStyle(y.body).height,m=getComputedStyle(y.body).width,parseInt(f.toString().replace("px",""))===0||parseInt(m.toString().replace("px",""))===0)){let x=Ni(y,"head");if(x){let C=fe(x,"meta[name=viewport]");if(C){var g=C.content,b=g.split(",").reduce((T,k)=>{var[_,R]=k.match(/[^\s;=]+/g);return T[_]=isNaN(Number(R))?R:+R,T},{});f=b.height+"px",m=b.width+"px"}}}if(m){if(!this.fxlScrollContainer)return;let x=this.attributes?.fixedLayoutMargin??100,C=parseInt(m.toString().replace("px","")),T=parseInt(f.toString().replace("px",""));var v=(this.fxlScrollContainer.clientWidth-x)/(this.iframes.length===2?C*2+x*2:C),A=(this.fxlScrollContainer.clientHeight-x)/T,w=Math.min(v,A);this.spreads.style.transform="scale("+w+")";for(let k of this.iframes)k.style.height=f,k.style.width=m,k.parentElement&&(k.parentElement.style.height=f);this.fxlContentWidth=this.iframes.length===2?C*2:C,this.fxlContentHeight=T,this.updateFxlZoomContainer(w)}},400)}static goBack(){window.history.back()}handleEditClick(t){var i=t.target;if(this.headerMenu){var r=fe(document,".sidenav");i.className.indexOf(" dita-active")===-1?(i.className+=" dita-active",r.className+=" expanded",i.innerText="unfold_less",this.sideNavExpanded=!0,this.modules.bookmarks?.showBookmarks(),this.modules.annotations?.showHighlights()):(i.className=i.className.replace(" dita-active",""),r.className=r.className.replace(" expanded",""),i.innerText="unfold_more",this.sideNavExpanded=!1,this.modules.bookmarks?.showBookmarks(),this.modules.annotations?.showHighlights())}t.preventDefault(),t.stopPropagation()}get hasMediaOverlays(){return this.publication.hasMediaOverlays}startReadAloud(){this.rights.enableTTS&&this.modules.tts?.speakPlay()}startReadAlong(){this.rights.enableMediaOverlays&&this.modules.mediaOverlays!==void 0&&this.hasMediaOverlays&&this.modules.mediaOverlays?.startReadAloud()}stopReadAloud(){this.rights.enableTTS&&this.highlighter?.stopReadAloud()}stopReadAlong(){if(this.rights.enableMediaOverlays&&this.modules.mediaOverlays!==void 0&&this.hasMediaOverlays){let t=this.modules.mediaOverlays.settings.playing;this.modules.mediaOverlays?.stopReadAloud(),t&&this.emit(xe.ReadAlongStopped,"stopped")}}pauseReadAloud(){this.rights.enableTTS&&(this.modules.tts?.speakPause(),this.modules.annotations!==void 0&&this.modules.annotations.drawHighlights())}pauseReadAlong(){this.rights.enableMediaOverlays&&this.modules.mediaOverlays!==void 0&&this.hasMediaOverlays&&this.modules.mediaOverlays?.pauseReadAloud()}resumeReadAloud(){this.rights.enableTTS&&this.modules.tts?.speakResume()}resumeReadAlong(){this.rights.enableMediaOverlays&&this.modules.mediaOverlays!==void 0&&this.hasMediaOverlays&&this.modules.mediaOverlays?.resumeReadAloud()}totalResources(){return this.publication.readingOrder.length}mostRecentNavigatedTocItem(){return this.publication.getRelativeHref(this.currentTOCRawLink)}currentResource(){let t=this.currentChapterLink.href;return this.publication.getSpineIndex(t)}currentLink(){if(this.settings.columnCount!==1&&this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0){let i=this.publication.getSpineItem(this.currentSpreadLinks.left.href),r=this.publication.getSpineItem(this.currentSpreadLinks.right.href);return[i,r]}let t=this.currentChapterLink.href;return[this.publication.getSpineItem(t)]}tableOfContents(){return this.publication.tableOfContents}landmarks(){return this.publication.landmarks}pageList(){return this.publication.pageList}readingOrder(){return this.publication.readingOrder}atStart(){return this.view?.atStart()??!1}atEnd(){return this.view?.atEnd()??!1}previousPage(){this.handlePreviousPageClick(void 0)}nextPage(){this.handleNextPageClick(void 0)}previousResource(){this.handlePreviousChapterClick(void 0)}nextResource(){this.handleNextChapterClick(void 0)}goTo(t){let i=t.locations??{progression:0};if(t.href.indexOf("#")!==-1){let o=t.href.slice(t.href.indexOf("#")+1);o!==void 0&&(i={...i,fragment:o})}let r={...t};r.locations=i;let s=this.publication.getAbsoluteHref(t.href);wn.default.log(t.href),wn.default.log(s),r.href=s,this.stopReadAloud(),this.navigate(r)}currentLocator(){let t;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let i=this.publication.positionsByHref(this.publication.getRelativeHref(this.currentChapterLink.href)),r=Math.ceil((this.view?.getCurrentPosition()??0)*(i.length-1));t=i[r]}else{let i=this.publication.getTOCItem(this.currentChapterLink.href);i&&(this.currentTocUrl!==void 0&&(i=this.publication.getTOCItem(this.currentTocUrl)),i===void 0&&(i=this.publication.getTOCItemAbsolute(this.currentChapterLink.href)),i&&(t={href:i.href,type:this.currentChapterLink.type,title:this.currentChapterLink.title,locations:{}}))}return t&&(!t.title&&this.currentChapterLink.title&&(t.title=this.currentChapterLink.title),t.locations.progression=this.view?.getCurrentPosition(),t.displayInfo={resourceScreenIndex:Math.round(this.view?.getCurrentPage()??0),resourceScreenCount:Math.round(this.view?.getPageCount()??0)}),t}positions(){return this.publication.positions??[]}goToPosition(t){if(this.publication.positions){let i=this.publication.positions.filter(r=>r.locations.position===parseInt(String(t)))[0];this.goTo(i)}}async goToPage(t){this.modules.pageBreaks!==void 0&&await this.modules.pageBreaks.goToPageNumber(t)}snapToSelector(t){let i=this.iframes[0].contentDocument;if(i){wn.default.log(t);let r=i.querySelectorAll(t);r.length>0&&this.view?.snap(r[0])}}applyAttributes(t){this.attributes=t??{},this.view.attributes=this.attributes,this.handleResize()}handlePreviousPageClick(t){this.stopReadAloud(),this.view?.layout==="fixed"?this.handlePreviousChapterClick(t):(this.view?.atStart()?this.handlePreviousChapterClick(t):(this.view?.goToPreviousPage?.(),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))}handleNextPageClick(t){let i=!0;if(this.sample?.isSampleRead&&this.publication.positions){let r=this.currentLocator(),s=Math.round((r.locations.totalProgression??0)*100);this.sample?.limit&&(i=s<=this.sample?.limit,this.view?.layout==="fixed"&&((!i&&this.sample?.minimum&&r.locations.position)??0<=(this.sample?.minimum??0))&&(i=!0))}(i&&this.sample?.isSampleRead&&this.publication.positions||!this.sample?.isSampleRead||!this.publication.positions)&&(this.stopReadAloud(),this.view?.layout==="fixed"?this.handleNextChapterClick(t):(this.view?.atEnd()?this.handleNextChapterClick(t):(this.view?.goToNextPage?.(),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))),!i&&this.sample?.isSampleRead&&this.publication.positions&&t&&(t.preventDefault(),t.stopPropagation())}handleClickThrough(t){this.api?.clickThrough&&this.api?.clickThrough(t),this.emit(xe.Click,t)}handleInternalLink(t){let i=t.target,r={progression:0},s=i;if(s.href.indexOf("#")!==-1){let a=s.href.slice(s.href.indexOf("#")+1);a!==void 0&&(r={fragment:a})}let o={href:s.href,locations:r,type:s.type,title:s.title};t.preventDefault(),t.stopPropagation(),this.stopReadAloud(),this.navigate(o)}handleNumberOfIframes(){if(this.publication.isFixedLayout){if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){if(this.iframes.length===1){var t=document.createElement("iframe");t.setAttribute("SCROLLING","no"),t.setAttribute("allowtransparency","true"),t.style.opacity="1",t.style.border="none",t.style.overflow="hidden",this.iframes.push(t)}let i=document.createElement("div");this.spreads.appendChild(i),i.appendChild(this.iframes[1]),this.attributes?.fixedLayoutShadow!==!1&&(this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",i.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",i.style.boxShadow="0 0 8px 2px #ccc")}else this.iframes.length===2&&(this.iframes.pop(),this.spreads.lastChild&&this.spreads.removeChild(this.spreads.lastChild)),this.attributes?.fixedLayoutShadow!==!1&&(this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc");this.precessContentForIframe()}}async handleResize(){if(this.isScrolling)return;if(this.publication.isFixedLayout){var t=this.publication.getSpineIndex(this.currentChapterLink.href);if(this.fxlScrollContainer){let l,c,d;if(t===0&&this.iframes?.length===2?d=this.iframes[1].contentDocument:d=this.iframes[0].contentDocument,!d)return;d.body&&(l=getComputedStyle(d.body).height,c=getComputedStyle(d.body).width);let f=Ni(d,"head");if(f){let b=fe(f,"meta[name=viewport]");if(b){var i=b.content,r={};i.split(",").forEach(v=>{let A=v.match(/[^\s;=]+/g);if(A&&A.length>=2){let[w,x]=A;r[w]=isNaN(Number(x))?x:+x}}),(parseInt(String(r.height))!==0||parseInt(String(r.width))!==0)&&(l=r.height.toString().endsWith("px")?r.height:r.height+"px",c=r.width.toString().endsWith("px")?r.width:r.width+"px")}}let m=this.attributes?.fixedLayoutMargin??100,y=parseInt(c.toString().endsWith("px")?c?.replace("px",""):c),g=parseInt(l.toString().replace("px",""));var s=(this.fxlScrollContainer.clientWidth-m)/(this.iframes.length===2?y*2+m*2:y),o=(this.fxlScrollContainer.clientHeight-m)/g,a=Math.min(s,o);this.spreads.style.transform="scale("+a+")";for(let b of this.iframes)b.style.height=l,b.style.width=c,b.parentElement&&(b.parentElement.style.height=l);this.fxlContentWidth=this.iframes.length===2?y*2:y,this.fxlContentHeight=g,this.updateFxlZoomContainer(a)}}let u=this.view?.getCurrentPosition();await this.settings.applyProperties(),this.infoTop&&(this.infoTop.style.height="0px"),this.infoTop&&(this.infoTop.style.minHeight="0px"),this.view?.layout!=="fixed"&&this.settings.isPaginated().then(l=>{l?(this.view.height=qu(this.iframes[0],this.attributes),this.infoBottom&&this.infoBottom.style.removeProperty("display")):this.infoBottom&&(this.infoBottom.style.display="none")}),setTimeout(()=>{this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&this.view?.setIframeHeight?.(this.iframes[0])},100),setTimeout(async()=>{u&&this.view?.goToProgression(u),this.updatePositionInfo(!1),this.modules.contentProtection!==void 0&&await this.modules.contentProtection.handleResize(),this.modules.annotations!==void 0&&await this.modules.annotations.handleResize(),this.modules.bookmarks!==void 0&&await this.modules.bookmarks.handleResize(),this.modules.search!==void 0&&await this.modules.search.handleResize(),this.modules.definitions!==void 0&&await this.modules.definitions.handleResize(),this.modules.pageBreaks!==void 0&&await this.modules.pageBreaks.handleResize(),this.modules.lineFocus!==void 0&&this.modules.lineFocus.handleResize(),this.modules.history!==void 0&&await this.modules.history.handleResize()},150)}updatePositionInfo(t=!0){if(this.view?.layout==="fixed")this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");else if(this.view?.isPaginated()){let i=this.currentLocator();if(i){let r=i.displayInfo.resourceScreenIndex,s=i.displayInfo.resourceScreenCount;this.chapterPosition&&(this.chapterPosition.innerHTML="Page "+r+" of "+s),this.api?.positionInfo&&this.api.positionInfo(i),this.emit(xe.PositionInfo,i)}}else this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");t&&this.savePosition()}handlePreviousChapterClick(t){if(this.view?.layout==="fixed"&&this.settings.columnCount!==1){let i=this.publication.getSpineIndex(this.currentChapterLink.href)??0;i=i-2,i<0&&(i=0);let r=this.publication.readingOrder[i],s={href:this.publication.getAbsoluteHref(r.href),locations:{progression:0},type:r.type,title:r.title};this.stopReadAloud(),this.navigate(s,!1)}else if(this.previousChapterLink){let i={href:this.publication.getAbsoluteHref(this.previousChapterLink.href),locations:{progression:1},type:this.previousChapterLink.type,title:this.previousChapterLink.title};this.stopReadAloud(),this.navigate(i,!1)}t&&(t.preventDefault(),t.stopPropagation())}handleNextChapterClick(t){if(this.view?.layout==="fixed"&&this.settings.columnCount!==1){let i=this.publication.getSpineIndex(this.currentChapterLink.href)??0;i=i+2,i>=this.publication.readingOrder.length-1&&(i=this.publication.readingOrder.length-1);let r=this.publication.readingOrder[i],s={href:this.publication.getAbsoluteHref(r.href),locations:{progression:0},type:r.type,title:r.title};this.stopReadAloud(),this.navigate(s,!1)}else if(this.nextChapterLink){let i={href:this.publication.getAbsoluteHref(this.nextChapterLink.href),locations:{progression:0},type:this.nextChapterLink.type,title:this.nextChapterLink.title};this.stopReadAloud(),this.navigate(i,!1)}t&&(t.preventDefault(),t.stopPropagation())}handleKeydownFallthrough(t){this.api?.keydownFallthrough&&this.api?.keydownFallthrough(t),this.emit(xe.KeyDown,t)}hideView(){this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(document.body.style.overflow="auto")}setActiveTOCItem(t){if(this.tocView){let i=Array.prototype.slice.call(this.tocView.querySelectorAll("li > a"));for(let s of i)s.className=s.className.replace(" dita-active","");let r=this.tocView.querySelector('li > a[href^="'+t+'"]');r&&(r.className+=" dita-active")}}async navigate(t,i=!0){if(this.rights.enableConsumption&&this.modules.consumption&&i&&this.modules.consumption.startReadingSession(t),this.modules.history&&await this.modules.history.push(t,i),this.publication.getTOCItem(t.href)){var s=!1;if(t.href.indexOf("#")!==-1){let o=t.href.slice(0,t.href.indexOf("#"));o===this.currentChapterLink.href&&(s=!0),this.currentChapterLink.href=o,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title}else t.href===this.currentChapterLink.href&&(s=!0),this.currentChapterLink.href=t.href,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title;if(this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0&&(t.href===this.currentSpreadLinks.left.href||t.href===this.currentSpreadLinks.right.href))return;if(s){if(t.href.indexOf("#")!==-1){let d=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:d}}if(this.newPosition=t,this.currentTOCRawLink=t.href,t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.view?.layout!=="fixed"&&this.view?.padOddColumns?.(),this.newElementId){for(let d of this.iframes){let f=d.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(f)}this.newElementId=void 0}else if(t.highlight){let d=t.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;d&&this.view?.goToCssSelector(d)}else this.view?.goToProgression(t.locations.progression??0);let o=this.currentChapterLink.href,a=this.publication.getPreviousSpineItem(o);a&&a.href&&(this.previousChapterLink={href:a.href,type:a.type,title:a.title}),this.previousChapterAnchorElement&&(this.previousChapterLink?(this.previousChapterAnchorElement.href=this.publication.getAbsoluteHref(this.previousChapterLink.href),this.previousChapterAnchorElement.className=this.previousChapterAnchorElement.className.replace(" disabled","")):(this.previousChapterAnchorElement.removeAttribute("href"),this.previousChapterAnchorElement.className+=" disabled"));let u=this.publication.getNextSpineItem(o);u?this.nextChapterLink={href:u.href,type:u.type,title:u.title}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(o),this.publication.metadata?.title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.metadata?.title.toString());let l=this.publication.getSpineItem(o);l!==void 0&&(this.currentChapterLink.title=l.title,this.currentChapterLink.type=l.type);let c=this.publication.getTOCItem(o);this.currentTocUrl!==void 0&&(c=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&c!==void 0&&c.title&&(this.currentChapterLink.title=c.title),!this.currentChapterLink.type&&c!==void 0&&c.type&&(this.currentChapterLink.title=c.title),this.currentChapterLink.title?(this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"),this.api?.chapterInfo&&this.api.chapterInfo(this.currentChapterLink.title),this.emit(xe.ChapterInfo,this.currentChapterLink.title)):(this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),this.api?.chapterInfo&&this.api.chapterInfo(void 0),this.emit(xe.ChapterInfo,void 0)),await this.updatePositionInfo()}else this.modules.lineFocus!==void 0&&this.modules.lineFocus.disableLineFocus(!1),this.modules.search!==void 0&&this.modules.search.clearSearch(),t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.hideIframeContents(),this.showLoadingMessageAfterDelay(),t.locations===void 0&&(t.locations={progression:0}),this.newPosition=t,this.currentTOCRawLink=t.href,this.precessContentForIframe(),this.rights.enableContentProtection&&this.modules.contentProtection!==void 0&&await this.modules.contentProtection.initializeResource(),this.rights.enableMediaOverlays&&this.modules.mediaOverlays!==void 0&&this.hasMediaOverlays&&await this.modules.mediaOverlays.initializeResource(this.currentLink()),this.rights.enableContentProtection&&this.modules.contentProtection!==void 0&&await this.modules.contentProtection.recalculate(300),this.modules.bookmarks&&(await this.modules.bookmarks.drawBookmarks(),await this.modules.bookmarks.showBookmarks()),this.modules.pageBreaks&&(await this.highlighter?.destroyHighlights(3),await this.modules.pageBreaks.drawPageBreaks()),this.rights.enableSearch&&this.modules.search!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(1),this.modules.search.drawSearch()),this.rights.enableDefinitions&&this.modules.definitions&&this.highlighter&&await this.modules.definitions.drawDefinitions(),this.rights.enableConsumption&&this.modules.consumption&&this.modules.consumption.continueReadingSession(t),this.view?.layout==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit(xe.ResourceFits,{href:this.currentChapterLink.href})):this.settings.isPaginated().then(o=>{o||(this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))})}else{let o=this.publication.getStartLink(),a;if(o&&o.href&&(a=this.publication.getAbsoluteHref(o.href),a)){let u={href:a,locations:{progression:0},created:new Date,title:o.title};await this.navigate(u)}}}showIframeContents(t){this.isBeingStyled=!1,setTimeout(()=>{this.isBeingStyled||(t.style.opacity="1",t.style.border="none",t.style.overflow="hidden")},150)}showLoadingMessageAfterDelay(){this.isLoading=!0,this.isLoading&&this.loadingMessage&&(this.loadingMessage.style.display="block",this.loadingMessage.classList.add("is-loading")),this.modules.mediaOverlays!==void 0&&(this.modules.mediaOverlays.settings.resourceReady=!1)}hideIframeContents(){this.isBeingStyled=!0,this.iframes.forEach(t=>{t.style.opacity="0",t.style.border="none",t.style.overflow="hidden"})}hideLoadingMessage(){setTimeout(()=>{if(this.isLoading=!1,this.loadingMessage&&(this.loadingMessage.style.display="none",this.loadingMessage.classList.remove("is-loading")),this.view?.layout!=="fixed"&&(this.view?.padOddColumns?.(),this.view?.atStart()&&this.view?.atEnd()?(this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit(xe.ResourceFits,{href:this.currentChapterLink.href})):this.view?.atEnd()?(this.api?.resourceAtEnd&&this.api?.resourceAtEnd(),this.emit(xe.ResourceEnd,{href:this.currentChapterLink.href})):this.view?.atStart()&&(this.api?.resourceAtStart&&this.api?.resourceAtStart(),this.emit(xe.ResourceStart,{href:this.currentChapterLink.href}))),this.api?.resourceReady&&this.api?.resourceReady(),this.emit(xe.ResourceReady,{href:this.currentChapterLink.href}),this.registry.notifyResourceReady(),this._fetcher.prefetch){let t=this.publication.readingOrder.findIndex(i=>i.href&&this.publication.getAbsoluteHref(i.href)===this.currentChapterLink.href);if(t>=0){let i=this.publication.readingOrder[t+1],r=this.publication.readingOrder[t-1];i&&this._fetcher.prefetch({...i,href:this.publication.getAbsoluteHref(i.href)}),r&&this._fetcher.prefetch({...r,href:this.publication.getAbsoluteHref(r.href)})}}},150)}saveCurrentReadingPosition(){if(this.annotator){var t=this.publication.getTOCItem(this.currentChapterLink.href);this.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.currentChapterLink.href));let i={progression:this.view?.getCurrentPosition()};if(t){if(t.href.indexOf("#")!==-1){let s=t.href.slice(t.href.indexOf("#")+1);s!==void 0&&(i={progression:this.view?.getCurrentPosition(),fragment:s})}let r;if(this.publication.positions&&this.publication.positions.length>0){let s=this.publication.positionsByHref(this.publication.getRelativeHref(t.href));if(s.length>0){let o=Math.ceil((i.progression??0)*(s.length-1)),a=s[o];a&&(a.locations.fragment=i.fragment,r={...a,href:t.href,created:new Date,title:this.currentChapterLink.title})}}else r={href:t.href,locations:i,created:new Date,type:this.currentChapterLink.type,title:this.currentChapterLink.title};r&&(this.sample?.isSampleRead&&this.publication.positions&&this.sampleReadEventHandler?.enforceSampleRead(r),this.api?.updateCurrentLocation?this.api?.updateCurrentLocation(r).then(async s=>(wn.default.log("api updated current location",r),this.annotator?.saveLastReadingPosition(r))):(wn.default.log("save last reading position",r),this.annotator.saveLastReadingPosition(r)),this.emit(xe.LocationChanged,r),this.modules.consumption&&this.modules.consumption.continueReadingSession(r))}}}static createBase(t){let i=document.createElement("base");return i.target="_self",i.href=t,i}activateMarker(t,i){let r=this.modules.annotations;r!==void 0&&(r.activeAnnotationMarkerId===void 0||r.activeAnnotationMarkerId!==t?(r.activeAnnotationMarkerId=t,r.activeAnnotationMarkerPosition=i,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=t)):this.deactivateMarker())}deactivateMarker(){let t=this.modules.annotations;t!==void 0&&(t.activeAnnotationMarkerId=void 0,t.activeAnnotationMarkerPosition=void 0,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=void 0))}showLayer(t){let i="#",r=new Ku("layer-on","layer-off",!0,t,"layer-"+t);switch(t){case"annotations":case"highlights":i+="R2_ID_HIGHLIGHTS_CONTAINER",r.name="R2_ID_HIGHLIGHTS_CONTAINER";break;case"readaloud":i+="R2_ID_READALOUD_CONTAINER",r.name="R2_ID_READALOUD_CONTAINER";break;case"pagebreak":i+="R2_ID_PAGEBREAK_CONTAINER",r.name="R2_ID_PAGEBREAK_CONTAINER";break;case"search":i+="R2_ID_SEARCH_CONTAINER",r.name="R2_ID_SEARCH_CONTAINER";break;case"definitions":i+="R2_ID_DEFINITIONS_CONTAINER",r.name="R2_ID_DEFINITIONS_CONTAINER";break}this.highlighter?.layerSettings.saveProperty(r);let s=this.iframes[0].contentDocument;if(s){let o=fe(s,i);o&&(o.style.display="block")}}hideLayer(t){let i="#",r=new Ku("layer-on","layer-off",!1,t,"layer-"+t);switch(t){case"annotations":case"highlights":i+="R2_ID_HIGHLIGHTS_CONTAINER",r.name="R2_ID_HIGHLIGHTS_CONTAINER";break;case"readaloud":i+="R2_ID_READALOUD_CONTAINER",r.name="R2_ID_READALOUD_CONTAINER";break;case"pagebreak":i+="R2_ID_PAGEBREAK_CONTAINER",r.name="R2_ID_PAGEBREAK_CONTAINER";break;case"search":i+="R2_ID_SEARCH_CONTAINER",r.name="R2_ID_SEARCH_CONTAINER";break;case"definitions":i+="R2_ID_DEFINITIONS_CONTAINER",r.name="R2_ID_DEFINITIONS_CONTAINER";break}this.highlighter?.layerSettings.saveProperty(r);let s=this.iframes[0].contentDocument;if(s){let o=fe(s,i);o&&(o.style.display="none")}}},fR=Va;I();var bt=class bt{constructor(e){this.store=e.store}getLastReadingPosition(){let e=this.store.get(bt.LAST_READING_POSITION);return e?JSON.parse(e):null}initLastReadingPosition(e){if(typeof e=="string")this.store.set(bt.LAST_READING_POSITION,e);else{let t=JSON.stringify(e);this.store.set(bt.LAST_READING_POSITION,t)}}saveLastReadingPosition(e){if(typeof e=="string")this.store.set(bt.LAST_READING_POSITION,e);else{let t=JSON.stringify(e);this.store.set(bt.LAST_READING_POSITION,t)}}initBookmarks(e){if(typeof e=="string"){let t=JSON.parse(e);this.store.set(bt.BOOKMARKS,JSON.stringify(t))}else this.store.set(bt.BOOKMARKS,JSON.stringify(e));return e}saveBookmark(e){let t=this.store.get(bt.BOOKMARKS);if(t){let i=JSON.parse(t);i.push(e),this.store.set(bt.BOOKMARKS,JSON.stringify(i))}else{let i=[];i.push(e),this.store.set(bt.BOOKMARKS,JSON.stringify(i))}return e}locatorExists(e,t){let i;t===0&&(i=bt.BOOKMARKS);let r=this.store.get(i);return r&&JSON.parse(r).filter(a=>a.href===e.href&&a.locations.progression===e.locations.progression).length>0?e:null}deleteBookmark(e){let t=this.store.get(bt.BOOKMARKS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.id!==e.id),this.store.set(bt.BOOKMARKS,JSON.stringify(i))}return e}getBookmarks(e){let t=this.store.get(bt.BOOKMARKS);if(t){let i=JSON.parse(t);if(e){let r=i.filter(s=>s.href===e);return r=r.sort((s,o)=>s.locations.progression&&o.locations.progression?s.locations.progression-o.locations.progression:0),r}return i=i.sort((r,s)=>{if(r.locations.progression&&s.locations.progression)return r.locations.progression-s.locations.progression}),i}return[]}initAnnotations(e){let t;typeof e=="string"?t=JSON.parse(e):t=e;let i=[];return t.forEach(r=>{let s=`${r.highlight.selectionInfo.rangeInfo.startContainerElementCssSelector}${r.highlight.selectionInfo.rangeInfo.startContainerChildTextNodeIndex}${r.highlight.selectionInfo.rangeInfo.startOffset}${r.highlight.selectionInfo.rangeInfo.endContainerElementCssSelector}${r.highlight.selectionInfo.rangeInfo.endContainerChildTextNodeIndex}${r.highlight.selectionInfo.rangeInfo.endOffset}`,o=fs.hash(s);r.highlight.id="R2_HIGHLIGHT_"+o;let a;r.highlight.color?a=r.highlight.color:r.color&&(a=r.color),$t.isHexColor(a)&&(a=$t.hexToRgbString(a)),r.highlight.color=a,r.highlight.pointerInteraction=!0,r.highlight.selectionInfo.cleanText=r.highlight.selectionInfo.rawText.trim().replace(/\n/g," ").replace(/\s\s+/g," "),i.push(r)}),this.store.set(bt.ANNOTATIONS,JSON.stringify(i)),i}saveTemporarySelectionInfo(e){this.store.set(bt.SELECTIONINFO,JSON.stringify(e))}getTemporarySelectionInfo(e){if(!e)return null;let t=this.store.get(bt.SELECTIONINFO);if(t){let i=JSON.parse(t);return i.range=Gp(e,i.rangeInfo),i}return null}deleteTemporarySelectionInfo(){this.store.remove(bt.SELECTIONINFO)}saveAnnotation(e){let t=this.store.get(bt.ANNOTATIONS);if(t){let i=JSON.parse(t);i.push(e),this.store.set(bt.ANNOTATIONS,JSON.stringify(i))}else{let i=[];i.push(e),this.store.set(bt.ANNOTATIONS,JSON.stringify(i))}return e}deleteAnnotation(e){let t=this.store.get(bt.ANNOTATIONS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.id!==e),this.store.set(bt.ANNOTATIONS,JSON.stringify(i))}return e}deleteSelectedAnnotation(e){let t=this.store.get(bt.ANNOTATIONS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.highlight?.id!==e.highlight.id),this.store.set(bt.ANNOTATIONS,JSON.stringify(i))}return e}getAnnotations(){let e=this.store.get(bt.ANNOTATIONS);if(e){let t=JSON.parse(e);return t=t.sort((i,r)=>{if(i.locations.progression&&r.locations.progression)return i.locations.progression-r.locations.progression}),t}return[]}getAnnotationsByChapter(e){let t=this.store.get(bt.ANNOTATIONS);if(t){let i=JSON.parse(t);return i=i.filter(r=>r.href===e),i=i.sort((r,s)=>{if(r.locations.progression&&s.locations.progression)return r.locations.progression-s.locations.progression}),i}return[]}getAnnotationPosition(e,t){let i=this.store.get(bt.ANNOTATIONS);if(i){let s=JSON.parse(i).filter(o=>o.highlight?.id===e||o.id===e);if(s.length>0){let o=t.document.getElementById(`${s[0].highlight.id}`);if(o){let a=0;if(o.hasChildNodes())for(let u=0;u<o.childNodes.length;u++){let l=o.childNodes[u],c=parseInt(l.style.top.replace("px",""));(c<a||a===0)&&(a=c)}else a=parseInt(o.style.top.replace("px",""));return a}}}return null}getAnnotationElement(e,t){let i=this.store.get(bt.ANNOTATIONS);if(i){let s=JSON.parse(i).filter(o=>o.highlight?.id===e);if(s.length>0){let o=t.document.getElementById(`${s[0].highlight.id}`);if(o){let a=0;if(o.hasChildNodes())for(let u=0;u<o.childNodes.length;u++){let l=o.childNodes[u],c=parseInt(l.style.top.replace("px",""));if(c<a||a===0)return a=c,l}else a=parseInt(o.style.top.replace("px",""));return o}}}return null}getAnnotation(e){let t=this.store.get(bt.ANNOTATIONS);if(t){let r=JSON.parse(t).filter(s=>s.highlight?.id===e.id);if(r.length>0)return r[0]}return null}getAnnotationByID(e){let t=this.store.get(bt.ANNOTATIONS);if(t){let r=JSON.parse(t).filter(s=>s.highlight?.id===e);if(r.length>0)return r[0]}return null}};bt.LAST_READING_POSITION="last-reading-position",bt.BOOKMARKS="bookmarks",bt.ANNOTATIONS="annotations",bt.SELECTIONINFO="selectionInfo";var Wd=bt;I();I();var Pl=class{constructor(){this.store={}}get(e){return this.store[e]||null}set(e,t){this.store[e]=t}remove(e){this.store[e]=null}};var Ka=class{constructor(e){this.prefix=e.prefix.toString(),this.useLocalStorage=e.useLocalStorage,this.useStorageType=e.useStorageType;try{let t=e.prefix+"-"+String(Math.random());this.useStorageType==="memory"?this.fallbackStore=new Pl:this.useStorageType==="local"||this.useLocalStorage?(window.localStorage.setItem(t,"test"),window.localStorage.removeItem(t),this.fallbackStore=null):(this.useStorageType==="session"||!this.useLocalStorage)&&(window.sessionStorage.setItem(t,"test"),window.sessionStorage.removeItem(t),this.fallbackStore=null)}catch{this.fallbackStore=new Pl}}getLocalStorageKey(e){return this.prefix+"-"+e}get(e){let t;return this.fallbackStore?t=this.fallbackStore.get(e):this.useStorageType==="local"||this.useLocalStorage?t=window.localStorage.getItem(this.getLocalStorageKey(e)):t=window.sessionStorage.getItem(this.getLocalStorageKey(e)),t}set(e,t){this.fallbackStore?this.fallbackStore.set(e,t):this.useStorageType==="local"||this.useLocalStorage?window.localStorage.setItem(this.getLocalStorageKey(e),t):window.sessionStorage.setItem(this.getLocalStorageKey(e),t)}remove(e){this.fallbackStore?this.fallbackStore.remove(e):this.useStorageType==="local"||this.useLocalStorage?window.localStorage.removeItem(this.getLocalStorageKey(e)):window.sessionStorage.removeItem(this.getLocalStorageKey(e))}};ci();I();X0();function $o(n){if(n==null)return n;if(n instanceof Set)return Array.from(n);if(n.items&&Array.isArray(n.items))return n.items.map($o);if(Array.isArray(n))return n.map($o);if(typeof n!="object")return n;let e={};for(let t in n)n.hasOwnProperty(t)&&(e[t]=$o(n[t]));return e}I();var pR=$e(jt()),z1=class{constructor(e){this.LAYERSETTINGS="layerSetting";this.store=e,this.initialize()}static async create(e){let t=new this(e.store);return new Promise(i=>i(t))}async stop(){pR.default.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let e=new os,t=await this.store.get(this.LAYERSETTINGS);if(t){let i=JSON.parse(t);e.properties=i}return e}async saveProperty(e){let t=await this.store.get(this.LAYERSETTINGS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.name!==e.name),i.push(e),await this.store.set(this.LAYERSETTINGS,JSON.stringify(i))}else{let i=[];i.push(e),await this.store.set(this.LAYERSETTINGS,JSON.stringify(i))}return new Promise(i=>i(e))}async getProperty(e){let t=await this.store.get(this.LAYERSETTINGS);if(t){let i=JSON.parse(t);return i=i.filter(r=>r.name===e),i.length===0?null:i[0]}return null}};I();Xt();hi();ci();mn();Er();var zd=$e(jt()),V1=class{constructor(e,t,i){this.name=we.PageBreaks;this.hostType=nt.Epub;this.rightsKey=vt.PageBreaks;this.headerMenu=i,this.publication=e,this.properties=t}attach(e){this.host=e}static async create(e){let t=new this(e.publication,e,e.headerMenu);return await t.start(),t}async stop(){zd.default.log("Page Break module stop")}async start(){this.headerMenu&&(this.goToPageView=fe(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=fe(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=fe(this.headerMenu,"#goToPageNumberButton")),ee(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),ee(this.goToPageNumberButton,"click",this.goToPageNumber.bind(this)),this.goToPageView&&(this.publication.pageList?.length||this.goToPageView.parentElement?.removeChild(this.goToPageView)),setTimeout(()=>{this.properties.hideLayer?this.host.hideLayer("pagebreak"):this.host.showLayer("pagebreak")},10)}async goToPageNumber(e){if(this.goToPageNumberInput.value&&(e.key==="Enter"||e.type==="click")){var t=this.publication.pageList?.filter(r=>r.href.slice(r.href.indexOf("#")+1).replace(/[^0-9]/g,"")===this.goToPageNumberInput.value);if(t&&t.length>0){var i=t[0];let r={progression:0};if(i.href.indexOf("#")!==-1){let o=i.href.slice(i.href.indexOf("#")+1);o!==null&&(r={fragment:o})}let s={href:this.publication.getAbsoluteHref(i.href),locations:r,type:i.type,title:i.title};this.host.goTo(s)}}}async handleResize(){await this.host.highlighter?.destroyHighlights(3),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{let e=this.host.iframes[0].contentDocument?.body,t=e?.querySelectorAll('[*|type="pagebreak"]');t?.length===0&&(t=e?.querySelectorAll("[epub\\:type='pagebreak']")),t?.length===0&&(t=e?.querySelectorAll("[role='doc-pagebreak']"));let i=this;function r(s){try{let o=i.host.iframes[0].contentDocument;return o?Vi(s,o,zo):""}catch(o){return zd.default.log("uniqueCssSelector:"),zd.default.error(o),""}}if(t)for(let s=0;s<t.length;s++){let o=t[s];zd.default.log(o);let a=o.innerHTML,u=!1;o.innerHTML.length===0&&(a=o.getAttribute("title")??"",o.textContent=a,u=!0),o.innerHTML.length===0&&(a=(o.getAttribute("id")??"").replace(/[^0-9]/g,""),o.innerHTML=a,u=!0);let l=this.host.iframes[0].contentDocument;if(l){let c=this.host.highlighter?.dom(l.body).getWindow().document.createRange(),d=this.host.highlighter?.dom(l.body).getSelection();if(d.removeAllRanges(),c.selectNodeContents(o),d.addRange(c),!d.isCollapsed){let f=Qs(c,r);d.removeAllRanges(),f&&this.createPageBreakHighlight({rangeInfo:f,cleanText:"",rawText:""},a)}}u&&(o.innerHTML="")}},200)}createPageBreakHighlight(e,t){try{let r=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,o="R2_PAGEBREAK_"+fs.hash(r);var i=!1;let a={color:"#000000",id:o,pointerInteraction:i,selectionInfo:e,marker:3,icon:{id:"pageBreak",title:t,color:"#000000",position:"left"},type:3};di.push(a);let u=this.host.highlighter?.createHighlightDom(this.host.iframes[0].contentWindow,a);return a.position=parseInt((u?.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px","")),a}catch(r){throw"Can't create highlight: "+r}}};I();hi();Xt();tr();Er();ci();mn();var mR=$e(cv());var bR=$e($s());var Ct=$e(jt()),K1=class{constructor(e,t,i,r,s){this.name=we.TTS;this.hostType=nt.Epub;this.rightsKey=vt.TTS;this.voices=[];this.hasEventListener=!1;this.startX=0;this.startY=0;this.index=0;this.userScrolled=!1;this.scrollPartial=!1;this.speaking=!1;this.restartIndex=-1;this.ttsQueueIndex=-1;this.ttsQueue=void 0;this.ttsPlayQueueIndexDebounced=(0,bR.default)((e,t)=>{this.restartIndex>=0?(this.ttsQueueIndex=this.restartIndex,this.restartIndex=-1):this.ttsQueueIndex=e,this.ttsQueue=t,this.ttsPlayQueueIndex(this.ttsQueueIndex,t)},150);this.tts=e,this.headerMenu=s,this.highlighter=t,this.properties=i,this.api=r}attach(e){this.host=e}initialize(e){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=e,this.clean=(0,mR.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),this.wrapper=dt(document,"#iframe-wrapper"),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,ee(document,"wheel",this.wheel.bind(this)),ee(this.body,"wheel",this.wheel.bind(this)),ee(document,"keydown",this.wheel.bind(this)),ee(this.host.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),ee(this.body,"mousedown",this.clickStart.bind(this)),ee(this.body,"mouseup",this.click.bind(this)))}clickStart(e){"clientX"in e&&(this.startX=e.clientX),"clientY"in e&&(this.startY=e.clientY)}click(e){let t=0,i=0;if("clientX"in e&&(t=e.clientX),"clientY"in e&&(i=e.clientY),window.speechSynthesis.speaking&&this.speaking&&t===this.startX&&i===this.startY){let r=this.host.iframes[0].contentDocument;if(r){let s=this.highlighter.dom(r.body).getSelection(),o=s.getRangeAt(0),a=s.anchorNode;for(;o.toString().indexOf(" ")!==0;)try{o.setStart(a,o.startOffset-1)}catch{break}o.setStart(a,o.startOffset+1);do o.setEnd(a,a.length<o.endOffset?o.endOffset+1:a.length);while(o.toString().indexOf(" ")===-1&&o.toString().trim()!=="");let l=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(this.ttsQueue&&l){let c=this.findTtsQueueItemIndex(this.ttsQueue,s.anchorNode,s.anchorNode,s.anchorOffset,l);s.removeAllRanges(),c>=0&&(window.speechSynthesis.cancel(),this.restartIndex=c,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}}}}initVoices(e){function t(){return new Promise(function(r,s){let o=window.speechSynthesis,a;a=setInterval(()=>{o.getVoices().length!==0&&(r(o.getVoices()),clearInterval(a))},10)})}t().then(async r=>{if(Ct.default.log(r),this.voices=[],r.forEach(o=>{o.localService===!0&&this.voices.push(o)}),Ct.default.log(this.voices),e&&this.headerMenu){var s=fe(this.headerMenu,"#preferred-languages");s&&this.voices.forEach(o=>{var a=document.createElement("option");a.value=o.name+":"+o.lang,a.innerHTML=o.name+" ("+o.lang+")",s.add(a)})}})}cancel(e=!0){e&&this.speaking&&(this.api?.stopped&&this.api?.stopped(),this.host.emit(xe.ReadAloudStopped,"stopped",{locator:this.host.currentLocator()})),this.userScrolled=!1,this.speaking=!1,setTimeout(()=>{window.speechSynthesis.cancel()},0),this._ttsQueueItemHighlightsWord&&(this.host.highlighter?.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0)}async speak(e,t,i){t||this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.deactivate(),this.api?.started&&this.api?.started(),this.host.emit(xe.ReadAloudStarted,"started",{locator:this.host.currentLocator()});let r=this;this.userScrolled=!1,this.cancel(!1);let s;if(t){let f=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body,m=this.host.iframes[0].contentDocument;if(m){let y=this.highlighter.dom(m.body).getSelection();if(y.isCollapsed){let g=r.host.iframes[0].contentDocument,v=r.host.getModule(we.Annotations)?.annotator?.getTemporarySelectionInfo(g);v?.range&&y.addRange(v.range)}if(f){var o=this.generateTtsQueue(f);if(!o.length)return;var a=this.findTtsQueueItemIndex(o,y.anchorNode,y.anchorNode,y.anchorOffset,f),u=this.findTtsQueueItemIndex(o,y.focusNode,y.focusNode,y.focusOffset,f);let g=Ya(o,a),b=Ya(o,u);var l;if(g&&e&&e.cleanText){let v=qa(g),A=e.rangeInfo.startOffset,w=e.cleanText;if(b&&a+1===u){let C=qa(b);A=(v+" "+C).indexOf(e.cleanText),w=v.slice(A,v.length),l=e.cleanText.replace(w,"").trim()}else if(u>a){let C="";for(let T=a+1;T<u;T++){let k=Ya(o,T);if(k){let _=qa(k);C+=_,l=e.cleanText.replace(_,"")}}if(b){let T=qa(b);C+=" "+T}A=(v+" "+C).indexOf(e.cleanText),w=v.slice(A,v.length),l=l.replace(w,"").trim()}s=new SpeechSynthesisUtterance(w),s.rate=this.tts.rate,s.pitch=this.tts.pitch,s.volume=this.tts.volume,this.setVoice(this,s),Ct.default.log(e),Ct.default.log(w,e.range?.commonAncestorContainer.textContent),Ct.default.log(g),Ct.default.log(g.item.textNodes),Ct.default.log(A),Ct.default.log(g.item.combinedText);let x=g.item.textNodes.filter(C=>C===e.range?.commonAncestorContainer)[0];Ct.default.log(x),s.onboundary=C=>{this.updateTTSInfo(g,C.charIndex,C.charLength,A,s.text)}}}}}else s=new SpeechSynthesisUtterance(this.clean);s.rate=this.tts.rate,s.pitch=this.tts.pitch,s.volume=this.tts.volume,this.setVoice(r,s),this.index=0;function c(){s.onend=function(){if(u>a)if(a=a+1,a!==u){let d=Ya(o,a);if(d){let f=qa(d);s=new SpeechSynthesisUtterance(f),s.rate=r.tts.rate,s.pitch=r.tts.pitch,s.volume=r.tts.volume,r.setVoice(r,s),s.onboundary=m=>{r.updateTTSInfo(d,m.charIndex,m.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s)},0),c()}}else{let d=Ya(o,a);d&&(s=new SpeechSynthesisUtterance(l),s.rate=r.tts.rate,s.pitch=r.tts.pitch,s.volume=r.tts.volume,r.setVoice(r,s),s.onboundary=f=>{r.updateTTSInfo(d,f.charIndex,f.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s)},0),c()),a>u&&(Ct.default.log("utterance ended"),r.highlighter.doneSpeaking(),r.api?.finished(),r.host.emit(xe.ReadAloudFinished,"finished",{locator:r.host.currentLocator()}))}else Ct.default.log("utterance ended"),r.highlighter.doneSpeaking(),r.api?.finished(),r.host.emit(xe.ReadAloudFinished,"finished",{locator:r.host.currentLocator()})}}setTimeout(()=>{window.speechSynthesis.speak(s),t||this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.recalculate(200)},0),c(),i()}setVoice(e,t){Ct.default.log("this.tts.voice.lang",this.tts.voice.lang);let i=!0;this.tts.voice&&this.tts.voice.lang&&(i=this.tts.voice.lang.indexOf("-")!==-1,i||(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),i=!0)),Ct.default.log("initialVoiceHasHyphen",i),Ct.default.log("voices",this.voices);let r;i?(r=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(c=>{var d=c.lang.replace("_","-");return d===this.tts.voice.lang&&c.name===this.tts.voice.name})[0]:void 0,r===void 0&&(r=this.tts.voice&&this.tts.voice.lang?this.voices.filter(c=>c.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(r=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(c=>c.lang===this.tts.voice.lang&&c.name===this.tts.voice.name)[0]:void 0,r===void 0&&(r=this.tts.voice&&this.tts.voice.lang?this.voices.filter(c=>c.lang===this.tts.voice.lang)[0]:void 0)),Ct.default.log("initialVoice",r);let s=e.host.publication.metadata?.languages?.[0],o=s?s.indexOf("-")!==-1:!1;Ct.default.log("publicationVoiceHasHyphen",o);let a;o?a=this.tts.voice&&this.tts.voice.usePublication&&s?this.voices.filter(c=>{var d=c.lang.replace("_","-");return d.startsWith(s)||d.endsWith(s.toUpperCase())})[0]:void 0:a=this.tts.voice&&this.tts.voice.usePublication&&s?this.voices.filter(c=>c.lang.startsWith(s)||c.lang.endsWith(s.toUpperCase()))[0]:void 0,Ct.default.log("publicationVoice",a);let u=navigator.language.indexOf("-")!==-1;Ct.default.log("defaultVoiceHasHyphen",u);let l;u?l=this.voices.filter(c=>c.lang.replace("_","-")===navigator.language&&c.localService)[0]:l=this.voices.filter(c=>c.lang===navigator.language&&c.localService)[0],l===void 0&&(l=this.voices.filter(c=>c.lang.includes(navigator.language)&&c.localService)[0]),Ct.default.log("defaultVoice",l),r?(Ct.default.log("initialVoice"),t.voice=r):a?(Ct.default.log("publicationVoice"),t.voice=a):l&&(Ct.default.log("defaultVoice"),t.voice=l),t.voice!==void 0&&t.voice!==null&&(t.lang=t.voice.lang,Ct.default.log("utterance.voice.lang",t.voice.lang),Ct.default.log("utterance.lang",t.lang)),Ct.default.log("navigator.language",navigator.language)}speakPlay(){this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.deactivate(),this.scrollPartial=!0,this.cancel(!1),this.api?.started&&this.api?.started(),this.host.emit(xe.ReadAloudStarted,"started",{locator:this.host.currentLocator()});let e=this,i=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(i){let o=function(){let a=e.highlighter.visibleTextRects[0],u=e.host.iframes[0].contentDocument;if(u){let l=e.highlighter.dom(u.body).getWindow().document.createRange(),c=e.highlighter.dom(e.host.iframes[0].contentDocument?.body).getSelection();c.removeAllRanges(),l.selectNodeContents(a.node),c.addRange(l);let d=0,f=c.focusNode,m=c.focusOffset;c.collapse(c.anchorNode,c.anchorOffset);for(let y=0;y<d;y++)c.modify("move","forward","line");if(c.extend(f,m),c.collapse(c.anchorNode,c.anchorOffset),i){let y=e.findTtsQueueItemIndex(r,c.anchorNode,c.anchorNode,c.anchorOffset,i);y>=0&&(s=y)}c.removeAllRanges()}},r=this.generateTtsQueue(i);if(!r.length)return;let s=0;o(),s<0&&(s=0),setTimeout(()=>{this.startTTSSession(r,s)},200)}this.host.rights.enableContentProtection&&this.host.getModule(we.ContentProtection)?.recalculate(200)}speakPause(){window.speechSynthesis.speaking&&(this.api?.paused&&this.api?.paused(),this.host.emit(xe.ReadAloudPaused,"paused",{locator:this.host.currentLocator()}),this.userScrolled=!1,window.speechSynthesis.pause(),this.speaking=!1,this._ttsQueueItemHighlightsWord&&(this.host.highlighter?.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0))}speakResume(){window.speechSynthesis.speaking&&(this.api?.resumed&&this.api?.resumed(),this.host.emit(xe.ReadAloudResumed,"resumed",{locator:this.host.currentLocator()}),this.userScrolled=!1,window.speechSynthesis.resume(),this.speaking=!0)}static async create(e){let t=new this(e.tts,e.highlighter,e,e.api,e.headerMenu);return await t.start(),t}async start(){if(this.headerMenu){var e=fe(this.headerMenu,"#menu-button-tts");e&&e.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties?.hideLayer?this.host.hideLayer("readaloud"):this.host.showLayer("readaloud")},10)}wheel(e){if(e instanceof KeyboardEvent)switch(e.key){case"ArrowUp":this.userScrolled=!0;break;case"ArrowDown":this.userScrolled=!0;break}else this.userScrolled=!0}stop(){Ct.default.log("TTS module stop"),Ae(document,"wheel",this.wheel.bind(this)),Ae(this.body,"wheel",this.wheel.bind(this)),Ae(document,"keydown",this.wheel.bind(this)),Ae(this.host.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),Ae(this.body,"click",this.click.bind(this))}generateTtsQueue(e){let t=[],i=[];function r(u){if(u.nodeType!==Node.TEXT_NODE||!u.nodeValue||!u.nodeValue.trim().length)return;let l=i[i.length-1];if(!l)return;let c=u.parentElement?gR(u.parentElement):void 0,d=u.parentElement?EZ(u.parentElement):void 0,f=t[t.length-1];(!f||f.parentElement!==l||f.lang!==c||f.dir!==d)&&(f={combinedText:"",dir:d,lang:c,parentElement:l,textNodes:[]},t.push(f)),f.textNodes.push(u)}let s=!0;function o(u){if(u.nodeType!==Node.ELEMENT_NODE)return;let l=s||u.matches("h1, h2, h3, h4, h5, h6, p, th, td, caption, li, blockquote, q, dt, dd, figcaption, div, pre");s=!1,l&&i.push(u);for(let c of u.childNodes)switch(c.nodeType){case Node.ELEMENT_NODE:let d=c;if(!d.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))o(d);else if(d.tagName&&d.tagName.toLowerCase()==="img"&&d.src){let m=d.getAttribute("alt");if(m){let y=m.trim();if(y){let g=gR(d);t.push({combinedText:y,dir:void 0,lang:g,parentElement:d,textNodes:[]})}}}break;case Node.TEXT_NODE:i.length!==0&&r(c);break;default:break}l&&i.pop()}o(e);function a(u){if(!u.textNodes||!u.textNodes.length){(!u.combinedText||!u.combinedText.length)&&(u.combinedText="");return}u.combinedText=CZ(u.textNodes,!0).replace(/[\r\n]/g," ");let l=u.parentElement;for(;l;){if(l.tagName){let c=l.tagName.toLowerCase();if(c==="pre"||c==="code"||c==="video"||c==="audio")break}l=l.parentElement}}for(let u of t)a(u);return t}findTtsQueueItemIndex(e,t,i,r,s){let o=0;for(let a of e){if(i&&a.textNodes){if(a.textNodes.includes(i))return o}else if(t===a.parentElement||a.parentElement!==t.ownerDocument.body&&a.parentElement!==s&&a.parentElement.contains(t)||t.contains(a.parentElement))return o;o++}return-1}restart(){window.speechSynthesis.speaking&&(window.speechSynthesis.cancel(),this.restartIndex=this.ttsQueueIndex,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}startTTSSession(e,t){if(!Ya(e,t)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(t,e)}ttsPlayQueueIndex(e,t){if(e<0){this.cancel();return}let i=Ya(t,e);if(!i){this.cancel();return}let r=qa(i);if(!r){this.cancel();return}let s=new SpeechSynthesisUtterance(r);s.rate=this.tts.rate,s.pitch=this.tts.pitch,s.volume=this.tts.volume;let o=this;this.setVoice(o,s),s.onboundary=a=>{Ct.default.log(a.name),this.updateTTSInfo(i,a.charIndex,a.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s),o.speaking||window.speechSynthesis.pause()},0),s.onend=function(){o.speaking&&o.ttsPlayQueueIndexDebounced(e+1,t)}}updateTTSInfo(e,t,i,r,s){if(!e)return;Ct.default.log(e,t,i,s);let o=s||qa(e);if(t>=0&&s){let a=s.slice(0,t+1).search(/\S+$/),u=s.slice(t).search(/\s/),l=u<0?s.slice(a):s.slice(a,u+t),c=a+l.length;if(i===void 0){let d=s.substring(t).match(/^[a-z\d']*/i);d&&(i=d[0].length)}i===void 0&&(i=l.length),this.wrapHighlightWord(e,s,t+r,i,l,a,c)}return o}wrapHighlightWord(e,t,i,r,s,o,a){Ct.default.log(e),Ct.default.log(t),Ct.default.log(i,r,s,o,a),this._ttsQueueItemHighlightsWord&&(this.host.highlighter?.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0);let u=e.item,l=i,c=0,d,f=-1,m,y=-1,g=l+r;for(let b of u.textNodes){if(!b.nodeValue&&b.nodeValue!=="")continue;let v=b.nodeValue.length;if(c+=v,d||l<c&&(d=b,f=v-(c-l)),d&&g<=c&&(m=b,y=v-(c-g)),m)break}if(d&&m){let A=function(C){try{let T=v.host.iframes[0].contentDocument;return T?Vi(C,T,zo):""}catch(T){return Ct.default.log("uniqueCssSelector:"),Ct.default.error(T),""}},b=new Range;b.setStart(d,f),b.setEnd(m,y);let v=this,w=Qs(b,A);if(!w)return;let x=this.host.highlighter?.createHighlight(this.host.iframes[0].contentWindow,{rangeInfo:w,cleanText:"",rawText:"",range:void 0},this.tts.color,!1,3,{id:"tts",title:"",position:"right"},void 0,{defaultClass:this.tts.color},2,"R2_READALOUD_");if(x){this._ttsQueueItemHighlightsWord=x[0];let k=(x[1]?.firstChild?.getBoundingClientRect()).top-this.wrapper.scrollTop>window.innerHeight/2-65;this.host.view?.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&this.scrollPartial&&k?x[1]?.firstChild?.scrollIntoView({block:"center",behavior:"smooth"}):this.host.view?.isPaginated()&&v.host.view?.snap(x[1]?.firstChild)}}}};function gR(n){let e=n;for(;e&&e.nodeType===Node.ELEMENT_NODE;){let t=e.getAttribute("xml:lang");if(t||(t=e.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang")),t||(t=e.getAttribute("lang")),t)return t;e=e.parentNode}}function EZ(n){let e=n;for(;e&&e.nodeType===Node.ELEMENT_NODE;){let t=e.getAttribute("dir");if(t)return t;e=e.parentNode}}function CZ(n,e){if(n&&n.length){let t="";for(let i of n)i.nodeValue&&(t+=e?i.nodeValue:SZ(i.nodeValue));return t}return""}function xZ(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function SZ(n){return xZ(n).replace(/\n/g," ").replace(/\s\s+/g," ")}function Ya(n,e){let t=-1,i=-1;for(let r of n)if(i++,t++,e===t)return{item:r,iArray:i,iGlobal:t,iSentence:-1}}function qa(n){return n.item.combinedText}I();Xt();hi();var Vd=$e(zp());tr();var yR=$e($s());Er();var vR=$e(jt()),Y1=class{constructor(e,t,i,r){this.name=we.Definitions;this.hostType=nt.Epub;this.rightsKey=vt.Definitions;this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,yR.default)(async()=>{if(await this.highlighter.destroyHighlights(4),this.properties.definitions)for(let e of this.properties.definitions)await this.define(e)},200);this.publication=e,this.properties=t,this.api=r,this.highlighter=i}attach(e){this.host=e}static async create(e){let t=new this(e.publication,e,e.highlighter,e.api);return await t.start(),t}async stop(){vR.default.log("Definitions module stop")}async start(){setTimeout(()=>{this.properties.hideLayer?this.host.hideLayer("definitions"):this.host.showLayer("definitions")},10)}async searchAndPaint(e,t){let i=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[this.host.currentResource()??0].href:""),r=this.publication.getTOCItem(i);r===void 0&&this.publication.readingOrder&&(r=this.publication.readingOrder[this.host.currentResource()??0]);let s=[];if(r)for(let o of e.terms){let a=e.terms.indexOf(o);r&&await Sl(o,this.host.iframes[0].contentDocument,r.href,r.title,this.host.getModule(we.Definitions)?.properties.fullWordSearch).then(u=>{let l;e.result===1?l=0:e.result===2&&(l=Math.floor(Math.random()*u.length-1)+1),u.forEach((c,d)=>{if(l===void 0||l===d){let f={rangeInfo:c.rangeInfo},m=this.createDefinitionHighlight(f,e);c.highlight=m,s.push(Vd.omit(m,"definition")),this.currentChapterPopupResult.push(c),this.currentPopupHighlights.push(m)}}),a===e.terms.length-1&&t(s)})}}async define(e){await this.searchAndPaint(e,async t=>{this.api?.success&&(this.api?.success(Vd.omit(e,"callbacks"),t),t&&t.length>0&&this.host.emit(xe.DefinitionSuccess,t),this.api?.visible&&t.forEach(i=>{let s=this.host.iframes[0].contentDocument?.querySelector(`#${i.id}`)?.querySelectorAll(`.${cn}`),o=new IntersectionObserver((a,u)=>{a.forEach(l=>{l.intersectionRatio===1&&(this.api?.visible(Vd.omit(e,"callbacks"),Vd.omit(i,"definition")),this.host.emit(xe.DefinitionVisible,e,i))})},{threshold:1});s&&s.length>0&&o.observe(s[0])}))})}async drawDefinitions(){setTimeout(async()=>{await this.definitions()},100)}async handleResize(){await this.drawDefinitions()}createDefinitionHighlight(e,t){try{let i=this.host.getModule(we.Definitions)?.properties.color;$t.isHexColor(i)&&(i=$t.hexToRgbChannels(i));let r=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,o="R2_DEFINITION_"+fs.hash(r);this.highlighter.destroyHighlight(this.host.iframes[0].contentDocument,o);let a={color:i||Ba,id:o,pointerInteraction:!0,selectionInfo:e,marker:1,type:4};di.push(a);let u=this.highlighter.createHighlightDom(this.host.iframes[0].contentWindow,a);return u&&(t.definition&&(u.dataset.definition=t.definition),u.dataset.order=String(t.order),a.definition=t,a.position=parseInt((u?.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px",""))),a}catch(i){throw"Can't create definitions highlight: "+i}}async addDefinition(e){await this.define(e)}async clearDefinitions(){await this.highlighter.destroyHighlights(4)}};I();Xt();hi();ci();mn();var Qo=$e(jt()),AR=.5,Kd=class{constructor(e,t,i){this.name=we.LineFocus;this.hostType=nt.Epub;this.rightsKey=vt.LineFocus;this.hasEventListener=!1;this.lines=[];this.index=0;this.isActive=!1;this.isDebug=!1;this.lineFocusContainer=document.getElementById("lineFocusContainer");this.readerContainer=document.getElementById("D2Reader-Container");this.lineFocusTopBlinder=document.getElementById("lineFocusTopBlinder");this.lineFocusBottomBlinder=document.getElementById("lineFocusBottomBlinder");this.wrapperHeight=void 0;this.properties=e,this.api=i,this.highlighter=t}attach(e){this.host=e}static async create(e){let t=new this(e,e.highlighter,e.api);return await t.start(),t}async stop(){Qo.default.log("Definitions module stop"),this.hasEventListener=!1,Ae(document,"keydown",this.keydown.bind(this)),Ae(document,"keyup",this.keyup.bind(this)),Ae(this.host.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),Ae(this.host.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){let e=dt(document,"#iframe-wrapper");e.style.height.length>0&&(this.wrapperHeight=e.style.height,this.lineFocusContainer&&this.lineFocusContainer.style.height.length===0&&(this.lineFocusContainer.style.height=this.wrapperHeight),this.readerContainer&&this.readerContainer.style.height.length===0&&(this.readerContainer.style.height=this.wrapperHeight),this.readerContainer&&(this.readerContainer.style.overflow="hidden"))}initialize(e){return new Promise(async t=>{await document.fonts.ready,this.hasEventListener||(this.hasEventListener=!0,ee(document,"keydown",this.keydown.bind(this)),ee(document,"keyup",this.keyup.bind(this)),ee(e.contentDocument,"keydown",this.keydown.bind(this)),ee(e.contentDocument,"keyup",this.keyup.bind(this))),t(null)})}keydown(e){if(e instanceof KeyboardEvent&&this.isActive)switch(e.key){case"ArrowUp":e.stopPropagation();break;case"ArrowDown":e.stopPropagation();break}}keyup(e){if(e instanceof KeyboardEvent&&this.isActive)switch(e.key){case"ArrowUp":this.lineUp();break;case"ArrowDown":this.lineDown();break}}handleResize(){this.isActive&&this.lineFocus()}async enableLineFocus(){this.isActive=!0,await this.host.settings.scroll(!0),this.lineFocus()}disableLineFocus(e=!0){this.isActive=!1;let t=dt(document,"#iframe-wrapper");this.wrapperHeight&&(t.style.height=this.wrapperHeight),e||(this.index=0);let i=this.host.iframes[0].contentDocument;Ni(i,"html").style.removeProperty("--USER__maxMediaHeight"),this.wrapperHeight=void 0,this.lineFocusContainer&&(this.lineFocusContainer.style.display="none");let s=document.getElementById("container-view-timeline");s&&s.style.removeProperty("display");let o=document.getElementById("divBefore");o&&o.remove();let a=document.getElementById("divAfter");a&&a.remove(),this.highlighter.destroyHighlights(5)}lineFocus(){let e=dt(document,"#iframe-wrapper"),t=this.host.iframes[0].contentDocument,i=Ni(t,"html"),r=this.properties.maxHeight?Yu()*this.properties.maxHeight/100:Yu()/2;i.style.setProperty("--USER__maxMediaHeight",r+"px");function s(c,d){c.parentNode.insertBefore(d,c.nextSibling)}function o(c,d){c.parentNode.insertBefore(d,c)}let a=document.getElementById("container-view-timeline");a&&(a.style.display="none"),this.lineFocusContainer&&this.lineFocusContainer.style.removeProperty("display");let u=document.getElementById("divBefore");if(u)u.style.height=e.clientHeight/2+"px";else{let c=document.createElement("div");c.style.height=e.clientHeight/2+"px",c.id="divBefore",o(e,c)}let l=document.getElementById("divAfter");if(l)l.style.height=e.clientHeight/2+"px";else{let c=document.createElement("div");c.style.height=e.clientHeight/2+"px",c.id="divAfter",s(e,c)}if(this.lines=[],t){let f=function(){let A=Math.round,w=Math.random,x=255;return{blue:A(w()*x),green:A(w()*x),red:A(w()*x)}},m=function(A,w){let x=[];for(let C=0,T=0;C<A.length;C++)C>=w&&C%w===0&&T++,x[T]=x[T]||[],x[T].push(A[C]);return x},y=function(A,w){let x=Math.min(A.left,w.left),C=Math.max(A.right,w.right),T=Math.min(A.top,w.top),k=Math.max(A.bottom,w.bottom);return{bottom:k,height:k-T,left:x,right:C,top:T,width:C-x}},g=function(A){if(A.length>1){let w=y(A[0],A[1]);if(A.length>2){let x=y(w,A[2]);if(A.length>3){let C=y(x,A[3]);return A.length>4?y(C,A[4]):C}return x}return w}return A[0]},c=this.findRects(t.body);c=vv(c,!0),c=c.sort(function(A,w){return A.top-w.top});let d=[];c=c.filter(function(A){let w=A.top;return d.indexOf(w)===-1&&d.indexOf(w+1)===-1&&d.indexOf(w+2)===-1&&d.indexOf(w+3)===-1&&d.indexOf(w+4)===-1&&d.indexOf(w-1)===-1&&d.indexOf(w-2)===-1&&d.indexOf(w-3)===-1&&d.indexOf(w-4)===-1?(d.push(w),!0):!1}),this.highlighter.destroyHighlights(5);let b=[];this.properties.lines&&this.properties.lines>1?m(c,this.properties.lines).forEach(w=>{b.push(g(w))}):b=c;let v=fe(t,"#R2_ID_LINEFOCUS_CONTAINER");if(v)for(let A of b){let w=document.createElement("div");w.setAttribute("class",cn);let x=f();if($t.isHexColor(x)&&(x=$t.hexToRgbChannels(x)),this.isDebug){let te=`border-bottom: 1px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${AR}) !important`;w.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${AR}) !important; ${te}`)}w.style.outline="none",w.tabIndex=0;let C=this.host.iframes[0].contentWindow.document,T=this.host.view.isPaginated();T?C.body.style.position="revert":C.body.style.position="relative";let k=C.body.getBoundingClientRect(),_=this.highlighter.getScrollingElement(C),R=T?-_.scrollLeft:k.left,L=T?-_.scrollTop:k.top,M=1,O=24,U,G,j=this.host.iframes[0].contentWindow?.innerWidth,W=parseInt(getComputedStyle(t.documentElement).getPropertyValue("column-count")),z=parseInt(getComputedStyle(t.documentElement).getPropertyValue("column-width")),$=parseInt(getComputedStyle(t.body).getPropertyValue("padding-left"));if(j){let te=j/(W||1);te<z&&(te=j),T||(te=parseInt(getComputedStyle(t.body).width.replace("px","")));let le=this.host.settings.fontSize/100,ce=20*le;le<=1&&(ce=-60);let pe=0;le<=1&&(pe=-60),U=Math.floor(A.left/te)*te+te-(O<40?40:O)+pe,G=Math.floor(A.left/te)*te+(O<40?40:O)-ce;let se=parseInt(t.documentElement.style.getPropertyValue("--USER__pageMargins"));se>=2&&(G=G+$/W,U=U-$/W),T||(U=parseInt(getComputedStyle(t.body).width.replace("px","")),G=parseInt(getComputedStyle(t.body).width.replace("px",""))-te,se>=2&&(G=G+$/2,U=U-$/2))}w.style.setProperty("pointer-events","none"),w.style.position="absolute",w.scale=M,w.rect={height:A.height,left:A.left-R,top:A.top-L,width:A.width},w.style.width=`${w.rect.width*M}px`,w.style.height=`${w.rect.height*M}px`,w.style.left=`${w.rect.left*M}px`,w.style.top=`${w.rect.top*M}px`,this.lines.push(w),v.append(w)}setTimeout(()=>{this.currentLine()},100)}}currentLine(){let e=this.lines[this.index],t=e.style.top,r=parseInt(e.style.top.replace("px",""))+parseInt(e.style.height.replace("px",""))-parseInt(t.replace("px",""));if(this.lineFocusContainer){let o=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-r)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=o+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=o+"px")}e.scrollIntoView({block:"center",behavior:"smooth"})}lineDown(){if(this.index<this.lines.length-1){this.index+=1,this.index>this.lines.length-1&&(this.index=this.lines.length-1);let e=this.lines[this.index],t=e.style.top,r=parseInt(e.style.top.replace("px",""))+parseInt(e.style.height.replace("px",""))-parseInt(t.replace("px",""));if(this.lineFocusContainer){let o=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-r)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=o+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=o+"px")}e.scrollIntoView({block:"center",behavior:"smooth"})}}lineUp(){if(this.index>0){this.index-=1,this.index<0&&(this.index=0);let e=this.lines[this.index],t=e.style.top,r=parseInt(e.style.top.replace("px",""))+parseInt(e.style.height.replace("px",""))-parseInt(t.replace("px",""));if(this.lineFocusContainer){let o=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-r)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=o+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=o+"px")}e.scrollIntoView({block:"center",behavior:"smooth"})}}almostEqual(e,t,i){return Math.abs(e-t)<=i}findRects(e){let t=this.findTextNodes(e),i=Array.from(e.getElementsByTagName("img")),r=[];return t.forEach(s=>{r.push(...this.measureTextNodes(s))}),i.forEach(s=>{r.push(...this.measureImageNodes(s))}),r}findTextNodes(e,t=[]){let i=e.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,t),i.nodeType===3&&i.textContent?.trim()&&(i.textContent.trim().length>1||i.parentElement?.tagName.toLowerCase()==="h1"||i.parentElement?.tagName.toLowerCase()==="h2"||i.parentElement?.tagName.toLowerCase()==="h3"||i.parentElement?.tagName.toLowerCase()==="h4"||i.parentElement?.tagName.toLowerCase()==="h5"||i.parentElement?.tagName.toLowerCase()==="h6")&&i.parentElement&&getComputedStyle(i.parentElement).verticalAlign==="baseline"&&t.push(i),i=i.nextSibling;return t}measureTextNodes(e){try{let t=document.createRange();t.selectNodeContents(e);let i=Array.from(t.getClientRects());return t.detach(),i}catch(t){Qo.default.log("measureTextNode "+t),Qo.default.log("measureTextNode "+e),Qo.default.log(`${e.textContent}`)}}measureImageNodes(e){try{let t=document.createRange();t.selectNode(e);let i=Array.from(t.getClientRects());return t.detach(),i}catch(t){Qo.default.log("measureTextNode "+t),Qo.default.log("measureTextNode "+e),Qo.default.log(`${e.textContent}`)}}};I();Xt();hi();ci();mn();var wR=$e(jt()),q1=class{constructor(e,t,i,r){this.name=we.History;this.hostType=nt.Epub;this.rightsKey=vt.History;this.history=[];this.headerMenu=r,this.publication=t,this.properties=i,this.annotator=e}attach(e){this.host=e}static async create(e){let t=new this(e.annotator,e.publication,e,e.headerMenu);return await t.start(),t}async stop(){wR.default.log("Page Break module stop"),Ae(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),Ae(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleResize(){await this.setup()}setup(){this.history.length>0&&(this.historyForwardAnchorElement&&this.historyCurrentIndex+1<this.history.length?this.historyForwardAnchorElement.className=this.historyForwardAnchorElement.className.replace(" disabled",""):this.historyForwardAnchorElement&&(this.historyForwardAnchorElement.removeAttribute("href"),this.historyForwardAnchorElement.className+=" disabled"),this.historyBackAnchorElement&&this.historyCurrentIndex>0?this.historyBackAnchorElement.className=this.historyBackAnchorElement.className.replace(" disabled",""):this.historyBackAnchorElement&&(this.historyBackAnchorElement.removeAttribute("href"),this.historyBackAnchorElement.className+=" disabled"))}async push(e,t){if(t&&this.annotator){let i=await this.annotator.getLastReadingPosition();if(i){let s=this.publication.getAbsoluteHref(i.href);if(i.href=s,this.historyCurrentIndex<this.history.length-1)this.history=this.history.slice(0,this.historyCurrentIndex),this.history.push(i),this.historyCurrentIndex=this.history.length-1;else if(i?.locations.progression&&i?.locations.progression>0)this.history.push(i),this.historyCurrentIndex=this.history.length-1;else{let o=this.history[this.history.length-1];(o&&o.href!==e.href&&o.locations!==e.locations||o===void 0)&&(this.history.push(i),this.historyCurrentIndex=this.history.length-1)}}this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex));let r=this.history[this.history.length-1];(r&&r.href!==e.href||r===void 0)&&(this.history.push(e),this.historyCurrentIndex=this.history.length-1)}}async start(){this.headerMenu&&(this.historyForwardAnchorElement=fe(this.headerMenu,"#history-forward")),this.headerMenu&&(this.historyBackAnchorElement=fe(this.headerMenu,"#history-back")),this.historyCurrentIndex=this.history.length-1,ee(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),ee(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleHistoryForwardClick(e){await this.historyForward(),e.preventDefault(),e.stopPropagation()}async historyForward(){this.history.length>0&&this.historyCurrentIndex+1<this.history.length&&(this.historyCurrentIndex=this.historyCurrentIndex+1,await this.host.navigate(this.history[this.historyCurrentIndex],!1))}async handleHistoryBackClick(e){await this.historyBack(),e.preventDefault(),e.stopPropagation()}async historyBack(){this.history.length>0&&this.historyCurrentIndex>0&&(this.historyCurrentIndex=this.historyCurrentIndex-1,await this.host.navigate(this.history[this.historyCurrentIndex],!1))}back(){return this.historyBack()}forward(){return this.historyForward()}canGoBack(){return this.historyCurrentIndex>0}canGoForward(){return this.historyCurrentIndex<this.history.length-1}};I();Xt();hi();var ER=$e(jt());tr();var $1=(i=>(i[i.Chicago=0]="Chicago",i[i.MLA=1]="MLA",i[i.APA=2]="APA",i))($1||{});function Xo(n){let e=n.name??n.Name;if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=Object.values(e);return t.length>0?String(t[0]):""}return""}var Sr=["","",""],Yd=class{constructor(e,t,i,r){this.name=we.Citations;this.hostType=nt.Epub;this.rightsKey=vt.Citations;this.highlighter=t,this.properties=i,this.publication=e,this.api=r}attach(e){this.host=e}static async create(e){let t=new this(e.publication,e.highlighter,e,e.api);return await t.start(),t}async stop(){ER.default.log("Citation module stop")}copyToClipboard(e){let t=this.host?.getModule(we.ContentProtection);if(t&&(t.citation=!0),navigator.clipboard){let i=document.createElement("div");i.innerHTML=e;let r=i.textContent??i.innerText??e;navigator.clipboard.writeText(r).then(()=>{this.api?.citationCreated("The text was copied to the clipboard!"),this.host.emit(xe.CitationCreated,"The text was copied to the clipboard!")},()=>this.legacyCopyToClipboard(e))}else this.legacyCopyToClipboard(e)}legacyCopyToClipboard(e){let t=document.createElement("div");t.style.position="absolute",t.style.left="-10000px",t.style.top="-10000px",t.innerHTML=e,t.contentEditable="true",document.body.appendChild(t),this.selectContent(t);let i;try{i=document.execCommand("copy")}catch{i=!1}document.body.removeChild(t),i?(this.api?.citationCreated("The text was copied to the clipboard!"),this.host.emit(xe.CitationCreated,"The text was copied to the clipboard!")):(this.api?.citationFailed("Your browser doesn't allow clipboard access!"),this.host.emit(xe.CitationFailed,"Your browser doesn't allow clipboard access!"))}selectContent(e){let t=document.createRange();t.selectNodeContents(e);let i=window.getSelection();i?.removeAllRanges(),i?.addRange(t)}authorsFormatted(){let e="",t="",i="";if(this.properties.author)e=this.properties.author,t=this.properties.author,i=this.properties.author;else if((this.publication.metadata?.authors?.items?.length??0)>0){let s=this.publication.metadata.authors.items.map(o=>Xo(o)).filter(o=>o.length>0);s.length===1?(e=s[0],t=s[0],i=s[0]):s.length===2?(e=s[0]+" and "+s[1],t=s[0]+", and "+s[1],i=s[0]+" & "+s[1]):s.length>2&&(s.length<=6?e=s.slice(0,-1).join(", ")+", and "+s[s.length-1]:e=s.slice(0,3).join(", ")+", et al.",t=s[0]+", et al.",s.length<=20?i=s.slice(0,-1).join(", ")+", & "+s[s.length-1]:i=s.slice(0,19).join(", ")+", ... "+s[s.length-1])}return e?[e+". ",t+". ",i+". "]:Sr}yearPublishedFormatted(){let e="",t="",i="";if(this.properties.publisher)t+=this.properties.publisher,e+=this.properties.publisher;else if((this.publication.metadata?.publishers?.items?.length??0)>0&&Xo(this.publication.metadata?.publishers?.items[0])){let s=Xo(this.publication.metadata?.publishers?.items[0]);t+=s,e+=s}let r="";if(this.properties.published)r=this.properties.published;else if(this.publication.metadata?.published){let s=this.publication.metadata?.published.getFullYear();s>0&&(r=String(s))}return r&&(i+="("+r+")",t+=(t?", ":"")+r,e+=(e?", ":"")+r),i||t||e?[e?e+". ":"",t?t+". ":"",i?i+". ":""]:Sr}bookTitleFormatted(){let e=this.properties.title||this.publication.metadata?.title||"";if(e){let t="<em>"+e+"</em>. ";return[t,t,t]}return Sr}editionFormatted(){return Sr}publisherFormatted(){let e="";return this.properties.publisher?e=this.properties.publisher:(this.publication.metadata?.publishers?.items?.length??0)>0&&Xo(this.publication.metadata?.publishers?.items[0])&&(e=Xo(this.publication.metadata?.publishers?.items[0])),e?["","",e+". "]:Sr}contributorsFormatted(){let e=[],t=this.publication.metadata?.editors?.items;if((t?.length??0)>0){let r=t.map(s=>Xo(s)).filter(s=>s.length>0);r.length>0&&e.push("Edited by "+(r.length<=2?r.join(" and "):r.slice(0,-1).join(", ")+", and "+r[r.length-1]))}let i=this.publication.metadata?.translators?.items;if((i?.length??0)>0){let r=i.map(s=>Xo(s)).filter(s=>s.length>0);r.length>0&&e.push("Translated by "+(r.length<=2?r.join(" and "):r.slice(0,-1).join(", ")+", and "+r[r.length-1]))}if(e.length>0){let r=e.join(". ")+". ";return[r,r,r]}return Sr}eBookVersionFormatted(){if(this.publication.metadata?.modified){let e=this.publication.metadata?.modified,t=e.getFullYear()+"-"+String(e.getMonth()+1).padStart(2,"0")+"-"+String(e.getDate()).padStart(2,"0");return["["+t+"]. ",t+". ",t+". "]}return Sr}locationFormatted(){return Sr}libraryFormatted(){if(this.properties.library){let e="Retrieved from "+this.properties.library+". ";return[e,e,e]}return Sr}appNameFormatted(){if(this.properties.appName){let e=this.properties.appName+". ";return[e,e,e]}return Sr}appLinkFormatted(){if(this.properties.appLink){let e=this.properties.appLink+". ";return[e,e,e]}return Sr}seriesFormatted(){let e=this.publication.metadata?.belongsToSeries?.items;if(e&&e.length>0){let t=Xo(e[0]);if(t)return[t+". ",t+". ",t+". "]}return Sr}selectedText(e,t){return e.length>t?e.substring(0,t)+"...":e}buildCitation(e){let t=this.authorsFormatted(),i=this.yearPublishedFormatted(),r=this.bookTitleFormatted(),s=this.editionFormatted(),o=this.publisherFormatted(),a=this.contributorsFormatted(),u=this.eBookVersionFormatted(),l=this.locationFormatted(),c=this.libraryFormatted(),d=this.appNameFormatted(),f=this.appLinkFormatted(),m=this.seriesFormatted(),y=0,g=1,b=2,v=t[y]+r[y]+a[y]+s[y]+l[y]+i[y]+u[y]+c[y]+d[y]+f[y],A=t[b]+i[b]+r[b]+s[b]+o[b]+a[b]+u[b]+l[b]+c[b]+d[b]+f[b],w=t[g]+r[g]+a[g]+s[g]+l[g]+i[g]+m[g]+c[g]+d[g]+f[g],x=this.properties.characters??200,C="\u201C"+this.selectedText(e,x)+"\u201D",T="";return this.properties.styles?.includes($1[0])&&(this.properties.styles.length>1&&(T+="Chicago: <br>"),T+=C+"<br><br>"+v+"<br><br>"),this.properties.styles?.includes($1[2])&&(this.properties.styles.length>1&&(T+="APA: <br>"),T+=C+"<br><br>"+A+"<br><br>"),this.properties.styles?.includes($1[1])&&(this.properties.styles.length>1&&(T+="MLA: <br>"),T+=C+"<br><br>"+w+"<br><br>"),T}async start(){let e=this,t={id:"citationIcon",callback:function(i){let r=e.buildCitation(i);e.copyToClipboard(r)}};this.highlighter?.addSelectionMenuItem(t)}};Xt();var V4;async function yie(){return V4||(V4=(await Promise.resolve().then(()=>(rM(),nM))).PDFNavigator),V4}function vie(n){return n?.isPDF===!0}var Jl=class n{constructor(e,t,i,r,s){this.settings=e;this.navigator=t;this.highlighter=i;this.ttsSettings=r;this.mediaOverlaySettings=s;this.startReadAloud=()=>{this.navigator.startReadAloud()};this.stopReadAloud=()=>{this.navigator.stopReadAloud()};this.pauseReadAloud=()=>{this.navigator.pauseReadAloud()};this.resumeReadAloud=()=>{this.navigator.resumeReadAloud()};this.startReadAlong=()=>{this.navigator.startReadAlong()};this.stopReadAlong=()=>{this.navigator.stopReadAlong()};this.pauseReadAlong=()=>{this.navigator.pauseReadAlong()};this.resumeReadAlong=()=>{this.navigator.resumeReadAlong()};this.saveBookmark=async()=>await this.navigator.modules.bookmarks?.save()??!1;this.saveBookmarkPlus=async()=>this.epubBookmarkModule?.saveBookmarkPlus();this.deleteBookmark=async e=>await this.navigator.modules.bookmarks?.delete(e)??!1;this.deleteAnnotation=async e=>await this.epubAnnotationModule?.deleteAnnotation(e)??!1;this.addAnnotation=async e=>await this.epubAnnotationModule?.addAnnotation(e)??!1;this.updateAnnotation=async e=>await this.epubAnnotationModule?.updateAnnotation(e)??!1;this.changeHighlighterColor=e=>{this.highlighter?.setColor(e)};this.hideAnnotationLayer=()=>this.epubAnnotationModule?.hideAnnotationLayer();this.showAnnotationLayer=()=>this.epubAnnotationModule?.showAnnotationLayer();this.hideLayer=e=>{this.navigator.hideLayer(e)};this.showLayer=e=>{this.navigator.showLayer(e)};this.activateMarker=(e,t)=>{this.navigator.activateMarker(e,t)};this.deactivateMarker=()=>{this.navigator.deactivateMarker()};this.clearDefinitions=async()=>{await this.navigator.modules.definitions?.clearDefinitions()};this.addDefinition=async e=>{await this.navigator.modules.definitions?.addDefinition(e)};this.historyBack=async()=>this.navigator.modules.history?.back();this.historyForward=async()=>this.navigator.modules.history?.forward();this.search=async(e,t)=>await this.epubSearchModule?.search(e,t)??[];this.goToSearchIndex=async(e,t,i)=>{this.navigator.supports(we.Search)&&await this.epubSearchModule?.goToSearchIndex(e,t,i)};this.goToSearchID=async(e,t,i)=>{this.navigator.supports(we.Search)&&await this.epubSearchModule?.goToSearchID(e,t,i)};this.clearSearch=async()=>{this.navigator.supports(we.Search)&&await this.epubSearchModule?.clearSearch()};this.resetUserSettings=async()=>await this.settings.resetUserSettings();this.applyUserSettings=async e=>await this.settings.applyUserSettings(e);this.scroll=async(e,t)=>vie(this.navigator)?this.navigator.scroll(e,t):await this.settings.scroll(e);this.increase=async e=>{this.isTTSIncrementable(e)?this.navigator.supports(we.TTS)&&await this.ttsSettings?.increase(e):this.isMOIncrementable(e)?this.navigator.supports(we.MediaOverlays)&&await this.mediaOverlaySettings?.increase(e):await this.settings.increase(e)};this.decrease=async e=>{this.isTTSIncrementable(e)?this.navigator.supports(we.TTS)&&await this.ttsSettings?.decrease(e):this.isMOIncrementable(e)?this.navigator.supports(we.MediaOverlays)&&await this.mediaOverlaySettings?.decrease(e):await this.settings.decrease(e)};this.resetTTSSettings=()=>{this.navigator.supports(we.TTS)&&this.ttsSettings?.resetTTSSettings()};this.applyTTSSettings=async e=>{this.navigator.supports(we.TTS)&&await this.ttsSettings?.applyTTSSettings(e)};this.applyPreferredVoice=async e=>{this.navigator.supports(we.TTS)&&await this.ttsSettings?.applyPreferredVoice(e)};this.resetMediaOverlaySettings=async()=>{this.navigator.supports(we.MediaOverlays)&&await this.mediaOverlaySettings?.resetMediaOverlaySettings()};this.applyMediaOverlaySettings=async e=>{this.navigator.supports(we.MediaOverlays)&&await this.mediaOverlaySettings?.applyMediaOverlaySettings(e)};this.goTo=async e=>{this.navigator.goTo(e)};this.goToPosition=async e=>this.navigator.goToPosition(e);this.goToPage=async e=>{await this.navigator.goToPage(e)};this.fitToPage=()=>{this.navigator.fitToPage()};this.fitToWidth=()=>{this.navigator.fitToWidth()};this.zoomIn=()=>{this.navigator.zoomIn()};this.zoomOut=()=>{this.navigator.zoomOut()};this.activateHand=()=>{this.navigator.activateHand()};this.deactivateHand=()=>{this.navigator.deactivateHand()};this.copyToClipboard=e=>{this.navigator.modules.contentProtection?.copyToClipboard(e)};this.nextResource=()=>{this.navigator.nextResource()};this.previousResource=()=>{this.navigator.previousResource()};this.nextPage=async()=>{this.navigator.nextPage()};this.previousPage=async()=>{this.navigator.previousPage()};this.snapToSelector=async e=>{this.navigator.snapToSelector?.(e)};this.applyAttributes=e=>{this.navigator.applyAttributes?.(e)};this.stop=()=>{document.body.onscroll=()=>{},this.navigator.stop(),this.settings.stop(),this.ttsSettings?.stop(),this.mediaOverlaySettings?.stop()}}get epubBookmarkModule(){return this.navigator.modules.bookmarks}get epubAnnotationModule(){return this.navigator.modules.annotations}get epubSearchModule(){return this.navigator.modules.search}addEventListener(e,t){this.navigator.addListener(e,t)}static async load(e){let t=e.rights??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};t.enableContentProtection&&e.protection&&await Dd.setupPreloadProtection(e.protection);let i=dt(document,"#D2Reader-Container"),r=fe(document,"#headerMenu"),s=fe(document,"#footerMenu"),o=e.url,a=null,u,l;if(e.epub){let{ZipFetcher:y}=await Promise.resolve().then(()=>(k4(),fM)),{EpubParser:g}=await Promise.resolve().then(()=>(R4(),pM)),{BlobUrlManager:b}=await Promise.resolve().then(()=>(L4(),gM)),{parseEncryptionXml:v,createDeobfuscationTransform:A}=await Promise.resolve().then(()=>(D4(),mM)),w,x=e.epub;if(typeof x=="string"||x instanceof URL){let O=await fetch(x.toString(),e.requestConfig);if(!O.ok)throw new Error(`Failed to fetch EPUB: ${O.status} ${O.statusText}`);w=await O.arrayBuffer()}else x instanceof ArrayBuffer?w=x:w=await x.arrayBuffer();let C=new y(w),T=await g.extractIdentifier(C),k=`${window.location.origin}/epub-local/${encodeURIComponent(T)}/`;C.setBasePath(k),u=C;let _;try{let O=await C.getByHref("META-INF/encryption.xml");O.text&&(_=v(O.text),_.size>0&&C.setEncryptionMap(_))}catch{}l=new b(C.container),_&&_.size>0&&l.setEncryptionMap(_);let R=A(T);if(l.addTransform(R),await l.initialize(),_&&_.size>0){let{TransformingFetcher:O}=await Promise.resolve().then(()=>(F4(),bM));u=new O(C,R)}let L=new URL(k+"manifest.json");if(a=await g.parse(C,L),o=L,_&&_.size>0){let{Properties:O}=await Promise.resolve().then(()=>(Uc(),mS)),U=G=>{for(let j of G){let W=_.get(j.href.replace(k,""));W&&(j.properties=j.properties?j.properties.add({encrypted:W}):new O({encrypted:W}))}};a.readingOrder&&U(a.readingOrder),a.resources&&U(a.resources)}let M=C;await a.autoGeneratePositions(void 0,async O=>(await M.getByHref(O)).bytes?.byteLength??0)}else if(e.publication){let y=e.publication;y instanceof ss?a=y:a=ss.fromJSON(y,o)}if(!a){let{HttpFetcher:y}=await Promise.resolve().then(()=>(Tl(),FA));a=await ss.fromUrl(o,e.requestConfig,new y(e.requestConfig))}let c=new Ka({prefix:a.manifestUrl,useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),d=new Ka({prefix:"r2d2bc-reader",useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),f=new Ka({prefix:"r2d2bc-layers",useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),m=new Wd({store:c});if(a.sample=e.sample,t=Aie(t,a),a.metadata?.conformsTo&&a.metadata?.conformsTo.includes(Io.PDF)){let y=await yd.create({store:d,initialUserSettings:e.userSettings,layout:""}),g=await yie(),{PdfBookmarkModule:b}=await Promise.resolve().then(()=>(vM(),yM)),{PdfSearchModule:v}=await Promise.resolve().then(()=>(wM(),AM)),{PdfAnnotationModule:A}=await Promise.resolve().then(()=>(xM(),CM)),{PdfHistoryModule:w}=await Promise.resolve().then(()=>(TM(),SM)),{PdfViewSettingsModule:x}=await Promise.resolve().then(()=>(_M(),IM)),C=[new b,new v,new A,new w,new x],T=await g.create({mainElement:i,publication:a,settings:y,api:e.api,rights:t,workerSrc:e.workerSrc,annotator:m,initialLastReadingPosition:e.lastReadingPosition,store:c,modules:[...C,...e.modules??[]]});if(t.enableContentProtection&&e.webProtection){let{ContentProtection:k}=await Promise.resolve().then(()=>($M(),qM));await new k(e.webProtection).activate()}return new n(y,T)}else{if(!u){let{HttpFetcher:le}=await Promise.resolve().then(()=>(Tl(),FA)),ce=new le(e.requestConfig);t.autoGeneratePositions?await a.autoGeneratePositions(e.requestConfig,async pe=>{let se=await ce.getByHref(pe);return new TextEncoder().encode(se.text).length}):(e.services?.positions&&await a.fetchPositionsFromService(e.services?.positions.href,ce),e.services?.weight&&await a.fetchWeightsFromService(e.services?.weight.href,ce))}let y=await z1.create({store:f}),g=await yd.create({store:d,initialUserSettings:e.userSettings,headerMenu:r,api:e.api,injectables:a.isFixedLayout?e.injectablesFixed:e.injectables,layout:a.isFixedLayout?"fixed":"reflowable"}),b=await $t.create({layerSettings:y,...e.highlighter}),v=t.enableBookmarks?await Yp.create({annotator:m,headerMenu:r,publication:a,initialAnnotations:e.initialAnnotations,...e.bookmarks}):void 0,A=t.enableAnnotations?await Kp.create({annotator:m,publication:a,initialAnnotations:e.initialAnnotations,highlighter:b,headerMenu:r,...e.annotations}):void 0,w=t.enableTTS,x=w?await D1.create({store:d,initialTTSSettings:e.tts,headerMenu:r}):void 0,C;w&&x&&(C=await K1.create({tts:x,headerMenu:r,highlighter:b,...e.tts}));let T=t.enableSearch?await B1.create({headerMenu:r,publication:a,highlighter:b,...e.search}):void 0,k=t.enableDefinitions?await Y1.create({publication:a,highlighter:b,...e.define}):void 0,_=t.enableTimeline?await Xp.create({publication:a}):void 0,R=t.enableContentProtection?await Dd.create({...e.protection}):void 0,L=t.enableCitations?await Yd.create({publication:a,highlighter:b,...e.citations}):void 0,M=t.enableMediaOverlays,O=M?await qp.create({store:d,initialMediaOverlaySettings:e.mediaOverlays,headerMenu:r,...e.mediaOverlays}):void 0,U=M?await Qp.create({publication:a,settings:O,...e.mediaOverlays}):void 0,j=t.enablePageBreaks&&a.isReflowable?await V1.create({publication:a,headerMenu:r,...e.pagebreak}):void 0,W=t.enableLineFocus?await Kd.create({publication:a,highlighter:b,...e.lineFocus}):void 0,z=t.enableHistory?await q1.create({annotator:m,publication:a,headerMenu:r}):void 0,$=t.enableConsumption?await Vp.create({publication:a,...e.consumption}):void 0,te=await Va.create({mainElement:i,headerMenu:r,footerMenu:s,publication:a,settings:g,annotator:m,initialLastReadingPosition:e.lastReadingPosition,api:e.api,rights:t,tts:e.tts,sample:e.sample,requestConfig:e.requestConfig,fetcher:u,blobUrlManager:l,injectables:a.isFixedLayout?e.injectablesFixed??[]:e.injectables,attributes:e.attributes,services:e.services,highlighter:b,modules:[v,A,C,T,k,_,R,L,U,j,W,z,$,...e.modules??[]]});return new n(g,te,b,x,O)}}get hasMediaOverlays(){return this.navigator.publication.hasMediaOverlays??!1}get tableOfContents(){return $o(this.navigator.tableOfContents())??[]}get landmarks(){return $o(this.navigator.landmarks())??[]}get pageList(){return $o(this.navigator.pageList())??[]}get readingOrder(){return $o(this.navigator.readingOrder())??[]}get bookmarks(){return this.navigator.modules.bookmarks?.list()??[]}get annotations(){return this.navigator.modules.annotations?.getAll()??[]}get publicationLayout(){return this.navigator.publication.layout}get canGoBack(){return this.navigator.modules.history?.canGoBack()??!1}get canGoForward(){return this.navigator.modules.history?.canGoForward()??!1}get currentResource(){return this.navigator.currentResource()}get mostRecentNavigatedTocItem(){return this.navigator.mostRecentNavigatedTocItem?.()??void 0}get totalResources(){return this.navigator.totalResources()}get publicationLanguage(){return this.navigator.publication.metadata?.languages}get currentSettings(){return this.settings.currentSettings}isTTSIncrementable(e){return e==="pitch"||e==="rate"||e==="volume"}isMOIncrementable(e){return e==="mo_rate"||e==="mo_volume"}get currentLocator(){return this.navigator.currentLocator()}get positions(){return this.navigator.positions()}get atStart(){return this.navigator.atStart()}get atEnd(){return this.navigator.atEnd()}async applyLineFocusSettings(e){if(e.lines&&this.navigator.modules.lineFocus){let t=this.navigator.modules.lineFocus.properties.lines??1;this.navigator.modules.lineFocus.index=this.navigator.modules.lineFocus.index*t/parseInt(e.lines),this.navigator.modules.lineFocus.index=Math.abs(parseInt(this.navigator.modules.lineFocus.index.toFixed())),this.navigator.modules.lineFocus.properties.lines=parseInt(e.lines),this.navigator.modules.lineFocus.isActive&&await this.navigator.modules.lineFocus.enableLineFocus()}e.debug!==void 0&&this.navigator.modules.lineFocus&&(this.navigator.modules.lineFocus.isDebug=e.debug,this.navigator.modules.lineFocus.isActive&&await this.navigator.modules.lineFocus.enableLineFocus())}lineUp(){this.navigator.modules.lineFocus?.lineUp()}lineDown(){this.navigator.modules.lineFocus?.lineDown()}async enableLineFocus(){await this.navigator.modules.lineFocus?.enableLineFocus()}async lineFocus(e){e?await this.navigator.modules.lineFocus?.enableLineFocus():this.navigator.modules.lineFocus?.disableLineFocus()}disableLineFocus(){this.navigator.modules.lineFocus?.disableLineFocus()}};function Aie(n,e){return e.isFixedLayout&&(n.enableAnnotations=!1,n.enableSearch=!1,n.enableTTS=!1,n.enableDefinitions=!1,n.enablePageBreaks=!1,n.enableLineFocus=!1),e.sample?.isSampleRead&&(n.enableAnnotations=!1,n.enableSearch=!1,n.enableTTS=!1,n.enableDefinitions=!1,n.enableTimeline=!1,n.enableMediaOverlays=!1,n.enablePageBreaks=!1,n.enableLineFocus=!1),n}tr();Xt();hi();mv();Dp();Er();P4();H1();Tl();k4();R4();L4();Gd();F4();D4();var wie=Jl,Eie=Jl.load;return vj(Cie);})();
666
666
  /*! Bundled license information:
667
667
 
668
668
  is-plain-object/dist/is-plain-object.js: