@d-i-t-a/reader 2.5.1 → 2.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +2 -2
- package/dist/reader.js +1 -1
- package/dist/reader.js.map +3 -3
- package/package.json +1 -1
package/dist/reader.js
CHANGED
|
@@ -599,7 +599,7 @@ pdfjs-views-manager-status-close-button-label = Close
|
|
|
599
599
|
pdfjs-views-manager-paste-button-label = Paste`)}},Tee=1e3,H3=50,FL=1e3;Sh=class{#e=null;constructor({linkService:e,eventBus:t}){this.linkService=e,this.eventBus=t,this._initialized=!1,this._fingerprint="",this.reset(),this.eventBus._on("pagesinit",()=>{this._isPagesLoaded=!1,this.eventBus._on("pagesloaded",i=>{this._isPagesLoaded=!!i.pagesCount},{once:!0})})}initialize({fingerprint:e,resetHistory:t=!1,updateUrl:i=!1}){if(!e||typeof e!="string"){console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.');return}this._initialized&&this.reset();let r=this._fingerprint!==""&&this._fingerprint!==e;this._fingerprint=e,this._updateUrl=i===!0,this._initialized=!0,this.#h();let s=window.history.state;if(this._popStateInProgress=!1,this._blockHashChange=0,this._currentHash=U3(),this._numPositionUpdates=0,this._uid=this._maxUid=0,this._destination=null,this._position=null,!this.#r(s,!0)||t){let{hash:a,page:u,rotation:l}=this.#s(!0);if(!a||r||t){this.#t(null,!0);return}this.#t({hash:a,page:u,rotation:l},!0);return}let o=s.destination;this.#o(o,s.uid,!0),o.rotation!==void 0&&(this._initialRotation=o.rotation),o.dest?(this._initialBookmark=JSON.stringify(o.dest),this._destination.page=null):o.hash?this._initialBookmark=o.hash:o.page&&(this._initialBookmark=`page=${o.page}`)}reset(){this._initialized&&(this.#u(),this._initialized=!1,this.#d()),this._updateViewareaTimeout&&(clearTimeout(this._updateViewareaTimeout),this._updateViewareaTimeout=null),this._initialBookmark=null,this._initialRotation=null}push({namedDest:e=null,explicitDest:t,pageNumber:i}){if(!this._initialized)return;if(e&&typeof e!="string"){console.error(`PDFHistory.push: "${e}" is not a valid namedDest parameter.`);return}else if(Array.isArray(t)){if(!this.#i(i)&&(i!==null||this._destination)){console.error(`PDFHistory.push: "${i}" is not a valid pageNumber parameter.`);return}}else{console.error(`PDFHistory.push: "${t}" is not a valid explicitDest parameter.`);return}let r=e||JSON.stringify(t);if(!r)return;let s=!1;if(this._destination&&(Iee(this._destination.hash,r)||Pee(this._destination.dest,t))){if(this._destination.page)return;s=!0}this._popStateInProgress&&!s||(this.#t({dest:t,hash:r,page:i,rotation:this.linkService.rotation},s),this._popStateInProgress||(this._popStateInProgress=!0,Promise.resolve().then(()=>{this._popStateInProgress=!1})))}pushPage(e){if(this._initialized){if(!this.#i(e)){console.error(`PDFHistory.pushPage: "${e}" is not a valid page number.`);return}this._destination?.page!==e&&(this._popStateInProgress||(this.#t({dest:null,hash:`page=${e}`,page:e,rotation:this.linkService.rotation}),this._popStateInProgress||(this._popStateInProgress=!0,Promise.resolve().then(()=>{this._popStateInProgress=!1}))))}}pushCurrentPosition(){!this._initialized||this._popStateInProgress||this.#n()}back(){if(!this._initialized||this._popStateInProgress)return;let e=window.history.state;this.#r(e)&&e.uid>0&&window.history.back()}forward(){if(!this._initialized||this._popStateInProgress)return;let e=window.history.state;this.#r(e)&&e.uid<this._maxUid&&window.history.forward()}get popStateInProgress(){return this._initialized&&(this._popStateInProgress||this._blockHashChange>0)}get initialBookmark(){return this._initialized?this._initialBookmark:null}get initialRotation(){return this._initialized?this._initialRotation:null}#t(e,t=!1){let i=t||!this._destination,r={fingerprint:this._fingerprint,uid:i?this._uid:this._uid+1,destination:e};this.#o(e,r.uid);let s;if(this._updateUrl&&e?.hash){let{href:o,protocol:a}=document.location;a!=="file:"&&(s=aZ(o,e.hash))}i?window.history.replaceState(r,"",s):window.history.pushState(r,"",s)}#n(e=!1){if(!this._position)return;let t=this._position;if(e&&(t=Object.assign(Object.create(null),this._position),t.temporary=!0),!this._destination){this.#t(t);return}if(this._destination.temporary){this.#t(t,!0);return}if(this._destination.hash===t.hash||!this._destination.page&&(H3<=0||this._numPositionUpdates<=H3))return;let i=!1;if(this._destination.page>=t.first&&this._destination.page<=t.page){if(this._destination.dest!==void 0||!this._destination.first)return;i=!0}this.#t(t,i)}#i(e){return Number.isInteger(e)&&e>0&&e<=this.linkService.pagesCount}#r(e,t=!1){if(!e)return!1;if(e.fingerprint!==this._fingerprint)if(t){if(typeof e.fingerprint!="string"||e.fingerprint.length!==this._fingerprint.length)return!1;let[i]=performance.getEntriesByType("navigation");if(i?.type!=="reload")return!1}else return!1;return!(!Number.isInteger(e.uid)||e.uid<0||e.destination===null||typeof e.destination!="object")}#o(e,t,i=!1){this._updateViewareaTimeout&&(clearTimeout(this._updateViewareaTimeout),this._updateViewareaTimeout=null),i&&e?.temporary&&delete e.temporary,this._destination=e,this._uid=t,this._maxUid=Math.max(this._maxUid,t),this._numPositionUpdates=0}#s(e=!1){let t=unescape(U3()).substring(1),i=kg(t),r=i.get("nameddest")||"",s=i.get("page")|0;return(!this.#i(s)||e&&r.length>0)&&(s=null),{hash:t,page:s,rotation:this.linkService.rotation}}#a({location:e}){this._updateViewareaTimeout&&(clearTimeout(this._updateViewareaTimeout),this._updateViewareaTimeout=null),this._position={hash:e.pdfOpenParams.substring(1),page:this.linkService.page,first:e.pageNumber,rotation:e.rotation},!this._popStateInProgress&&(H3>0&&this._isPagesLoaded&&this._destination&&!this._destination.page&&this._numPositionUpdates++,FL>0&&(this._updateViewareaTimeout=setTimeout(()=>{this._popStateInProgress||this.#n(!0),this._updateViewareaTimeout=null},FL)))}#l({state:e}){let t=U3(),i=this._currentHash!==t;if(this._currentHash=t,!e){this._uid++;let{hash:s,page:o,rotation:a}=this.#s();this.#t({hash:s,page:o,rotation:a},!0);return}if(!this.#r(e))return;this._popStateInProgress=!0,i&&(this._blockHashChange++,HZ({target:window,name:"hashchange",delay:Tee}).then(()=>{this._blockHashChange--}));let r=e.destination;this.#o(r,e.uid,!0),QL(r.rotation)&&(this.linkService.rotation=r.rotation),r.dest?this.linkService.goToDestination(r.dest):r.hash?this.linkService.setHash(r.hash):r.page&&(this.linkService.page=r.page),Promise.resolve().then(()=>{this._popStateInProgress=!1})}#u(){(!this._destination||this._destination.temporary)&&this.#n()}#h(){if(this.#e)return;this.#e=new AbortController;let{signal:e}=this.#e;this.eventBus._on("updateviewarea",this.#a.bind(this),{signal:e}),window.addEventListener("popstate",this.#l.bind(this),{signal:e}),window.addEventListener("pagehide",this.#u.bind(this),{signal:e})}#d(){this.#e?.abort(),this.#e=null}};n4=class{#e=null;#t=null;#n=null;#i=null;#r=null;#o;#s=null;constructor(e){this.pageIndex=e.pageIndex,this.accessibilityManager=e.accessibilityManager,this.l10n=e.l10n,this.l10n||=new Ql,this.annotationEditorLayer=null,this.div=null,this._cancelled=!1,this.#o=e.uiManager,this.#e=e.annotationLayer||null,this.#r=e.textLayer||null,this.#t=e.drawLayer||null,this.#n=e.onAppend||null,this.#i=e.structTreeLayer||null,this.#s=e.clonedFrom||null}updatePageIndex(e){this.pageIndex=e,this.annotationEditorLayer?.updatePageIndex(e)}async render({viewport:e,intent:t="display"}){if(t!=="display"||this._cancelled)return;let i=e.clone({dontFlip:!0});if(this.div){this.annotationEditorLayer.update({viewport:i}),this.show();return}let r=this.div=document.createElement("div");r.className="annotationEditorLayer",r.hidden=!0,r.dir=this.#o.direction,this.#n?.(r),this.annotationEditorLayer=new $X({uiManager:this.#o,div:r,structTreeLayer:this.#i,accessibilityManager:this.accessibilityManager,pageIndex:this.pageIndex,l10n:this.l10n,viewport:i,annotationLayer:this.#e,textLayer:this.#r,drawLayer:this.#t}),this.annotationEditorLayer.setClonedFrom(this.#s?.annotationEditorLayer),this.#s=null;let s={viewport:i,div:r,annotations:null,intent:t};this.annotationEditorLayer.render(s),this.show()}cancel(){this._cancelled=!0,this.div&&this.annotationEditorLayer.destroy()}hide(){this.div&&(this.annotationEditorLayer.pause(!0),this.div.hidden=!0)}show(){!this.div||this.annotationEditorLayer.isInvisible||(this.div.hidden=!1,this.annotationEditorLayer.pause(!1))}};{Cg=new Map;let{maxTouchPoints:n,platform:e,userAgent:t}=navigator,i=/Android/.test(t);(/\b(iPad|iPhone|iPod)(?=;)/.test(t)||e==="MacIntel"&&n>1||i)&&Cg.set("maxCanvasPixels",5242880),i&&Cg.set("useSystemFonts",!1)}re={BROWSER:1,VIEWER:2,API:4,WORKER:8,EVENT_DISPATCH:16,PREFERENCE:128},r4={BOOLEAN:1,NUMBER:2,OBJECT:4,STRING:8,UNDEFINED:16},yo={allowedGlobalEvents:{value:null,kind:re.BROWSER},canvasMaxAreaInBytes:{value:-1,kind:re.BROWSER+re.API},isInAutomation:{value:!1,kind:re.BROWSER},localeProperties:{value:{lang:navigator.language||"en-US"},kind:re.BROWSER},maxCanvasDim:{value:32767,kind:re.BROWSER+re.VIEWER},nimbusDataStr:{value:"",kind:re.BROWSER},supportsCaretBrowsingMode:{value:!1,kind:re.BROWSER},supportsDocumentFonts:{value:!0,kind:re.BROWSER},supportsIntegratedFind:{value:!1,kind:re.BROWSER},supportsMouseWheelZoomCtrlKey:{value:!0,kind:re.BROWSER},supportsMouseWheelZoomMetaKey:{value:!0,kind:re.BROWSER},supportsPinchToZoom:{value:!0,kind:re.BROWSER},supportsPrinting:{value:!0,kind:re.BROWSER},toolbarDensity:{value:0,kind:re.BROWSER+re.EVENT_DISPATCH},altTextLearnMoreUrl:{value:"",kind:re.VIEWER+re.PREFERENCE},annotationEditorMode:{value:0,kind:re.VIEWER+re.PREFERENCE},annotationMode:{value:2,kind:re.VIEWER+re.PREFERENCE},capCanvasAreaFactor:{value:200,kind:re.VIEWER+re.PREFERENCE},commentLearnMoreUrl:{value:"",kind:re.VIEWER+re.PREFERENCE},cursorToolOnLoad:{value:0,kind:re.VIEWER+re.PREFERENCE},debuggerSrc:{value:"./debugger.mjs",kind:re.VIEWER},defaultZoomDelay:{value:400,kind:re.VIEWER+re.PREFERENCE},defaultZoomValue:{value:"",kind:re.VIEWER+re.PREFERENCE},disableHistory:{value:!1,kind:re.VIEWER},disablePageLabels:{value:!1,kind:re.VIEWER+re.PREFERENCE},enableAltText:{value:!1,kind:re.VIEWER+re.PREFERENCE},enableAltTextModelDownload:{value:!0,kind:re.VIEWER+re.PREFERENCE+re.EVENT_DISPATCH},enableAutoLinking:{value:!0,kind:re.VIEWER+re.PREFERENCE},enableComment:{value:!1,kind:re.VIEWER+re.PREFERENCE},enableDetailCanvas:{value:!0,kind:re.VIEWER},enableGuessAltText:{value:!0,kind:re.VIEWER+re.PREFERENCE+re.EVENT_DISPATCH},enableHighlightFloatingButton:{value:!1,kind:re.VIEWER+re.PREFERENCE},enableNewAltTextWhenAddingImage:{value:!0,kind:re.VIEWER+re.PREFERENCE},enableOptimizedPartialRendering:{value:!1,kind:re.VIEWER+re.PREFERENCE},enablePermissions:{value:!1,kind:re.VIEWER+re.PREFERENCE},enablePrintAutoRotate:{value:!0,kind:re.VIEWER+re.PREFERENCE},enableScripting:{value:!0,kind:re.VIEWER+re.PREFERENCE},enableSignatureEditor:{value:!1,kind:re.VIEWER+re.PREFERENCE},enableSplitMerge:{value:!1,kind:re.VIEWER+re.PREFERENCE},enableUpdatedAddImage:{value:!1,kind:re.VIEWER+re.PREFERENCE},externalLinkRel:{value:"noopener noreferrer nofollow",kind:re.VIEWER},externalLinkTarget:{value:0,kind:re.VIEWER+re.PREFERENCE},highlightEditorColors:{value:"yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F,yellow_HCM=#FFFFCC,green_HCM=#53FFBC,blue_HCM=#80EBFF,pink_HCM=#F6B8FF,red_HCM=#C50043",kind:re.VIEWER+re.PREFERENCE},historyUpdateUrl:{value:!1,kind:re.VIEWER+re.PREFERENCE},ignoreDestinationZoom:{value:!1,kind:re.VIEWER+re.PREFERENCE},imageResourcesPath:{value:"./images/",kind:re.VIEWER},maxCanvasPixels:{value:2**25,kind:re.VIEWER},minDurationToUpdateCanvas:{value:500,kind:re.VIEWER},forcePageColors:{value:!1,kind:re.VIEWER+re.PREFERENCE},pageColorsBackground:{value:"Canvas",kind:re.VIEWER+re.PREFERENCE},pageColorsForeground:{value:"CanvasText",kind:re.VIEWER+re.PREFERENCE},pdfBugEnabled:{value:!1,kind:re.VIEWER+re.PREFERENCE},printResolution:{value:150,kind:re.VIEWER},sidebarViewOnLoad:{value:-1,kind:re.VIEWER+re.PREFERENCE},scrollModeOnLoad:{value:-1,kind:re.VIEWER+re.PREFERENCE},spreadModeOnLoad:{value:-1,kind:re.VIEWER+re.PREFERENCE},textLayerMode:{value:1,kind:re.VIEWER+re.PREFERENCE},viewerCssTheme:{value:0,kind:re.VIEWER+re.PREFERENCE},viewOnLoad:{value:0,kind:re.VIEWER+re.PREFERENCE},cMapPacked:{value:!0,kind:re.API},cMapUrl:{value:"../web/cmaps/",kind:re.API},disableAutoFetch:{value:!1,kind:re.API+re.PREFERENCE},disableFontFace:{value:!1,kind:re.API+re.PREFERENCE},disableRange:{value:!1,kind:re.API+re.PREFERENCE},disableStream:{value:!1,kind:re.API+re.PREFERENCE},docBaseUrl:{value:"",kind:re.API},enableHWA:{value:!0,kind:re.API+re.VIEWER+re.PREFERENCE},enableXfa:{value:!0,kind:re.API+re.PREFERENCE},fontExtraProperties:{value:!1,kind:re.API},iccUrl:{value:"../web/iccs/",kind:re.API},isEvalSupported:{value:!0,kind:re.API},isOffscreenCanvasSupported:{value:!0,kind:re.API},maxImageSize:{value:-1,kind:re.API},pdfBug:{value:!1,kind:re.API},standardFontDataUrl:{value:"../web/standard_fonts/",kind:re.API},useSystemFonts:{value:void 0,kind:re.API,type:r4.BOOLEAN+r4.UNDEFINED},verbosity:{value:1,kind:re.API},wasmUrl:{value:"../web/wasm/",kind:re.API},workerPort:{value:null,kind:re.WORKER},workerSrc:{value:"../build/pdf.worker.mjs",kind:re.WORKER}};yo.defaultUrl={value:"compressed.tracemonkey-pldi-09.pdf",kind:re.VIEWER},yo.sandboxBundleSrc={value:"../build/pdf.sandbox.mjs",kind:re.VIEWER},yo.enableFakeMLManager={value:!0,kind:re.VIEWER};yo.disablePreferences={value:!1,kind:re.VIEWER};Ts=class Ts{static get(e){return Ft(this,ia).get(e)}static getAll(e=null,t=!1){let i=Object.create(null);for(let r in yo){let s=yo[r];e&&!(e&s.kind)||(i[r]=t?s.value:Ft(this,ia).get(r))}return i}static set(e,t){this.setAll({[e]:t})}static setAll(e,t=!1){this._hasInvokedSet||=!0;let i;for(let r in e){let s=yo[r],o=e[r];if(!s||!(typeof o==typeof s.value||r4[(typeof o).toUpperCase()]&s.type))continue;let{kind:a}=s;t&&!(a&re.BROWSER||a&re.PREFERENCE)||(this.eventBus&&a&re.EVENT_DISPATCH&&(i||=new Map).set(r,o),Ft(this,ia).set(r,o))}if(i)for(let[r,s]of i)this.eventBus.dispatch(r.toLowerCase(),{source:this,value:s})}};ia=new WeakMap,$6(Ts,"eventBus"),wr(Ts,ia,new Map),(()=>{for(let e in yo)Ft(Ts,ia).set(e,yo[e].value);for(let[e,t]of Cg)Ft(Ts,ia).set(e,t);Ts._hasInvokedSet=!1,Ts._checkDisablePreferences=()=>Ts.get("disablePreferences")?!0:(Ts._hasInvokedSet&&console.warn('The Preferences may override manually set AppOptions; please use the "disablePreferences"-option to prevent that.'),!1)})();yh=Ts;s4=class{static#e=0;static#t;static#n;static findLinks(e){this.#t??=new RegExp("\\b(?:https?:\\/\\/|mailto:|www\\.)(?:[\\S--[\\p{P}<>]]|\\/|[\\S--[\\[\\]]]+[\\S--[\\p{P}<>]])+|(?=\\p{L})[\\S--[@\\p{Ps}\\p{Pe}<>]]+@([\\S--[[\\p{P}--\\-]<>]]+(?:\\.[\\S--[[\\p{P}--\\-]<>]]+)+)","gmv");let[t,i]=Eg(e,{ignoreDashEOL:!0}),r=t.matchAll(this.#t),s=[];for(let o of r){let[a,u]=o,l;if(a.startsWith("www.")||a.startsWith("http://")||a.startsWith("https://"))l=a;else if(u){let h=URL.parse(`http://${u}`)?.hostname;if(!h||(this.#n??=/\.\d+$/,this.#n.test(h)))continue}l??=a.startsWith("mailto:")?a:`mailto:${a}`;let c=KL(l,null,{addDefaultProtocol:!0});if(c){let[h,f]=XL(i,o.index,a.length);s.push({url:c.href,index:h,length:f})}}return s}static processLinks(e){return this.findLinks(e._textHighlighter.textContentItemsStr.join(`
|
|
600
600
|
`)).map(t=>Lee(t,e,this.#e++))}},Lt={INITIAL:0,RUNNING:1,PAUSED:2,FINISHED:3},o4=class{renderingId="";renderTask=null;resume=null;get renderingState(){throw new Error("Abstract getter `renderingState` accessed")}set renderingState(e){throw new Error("Abstract setter `renderingState` accessed")}async draw(){throw new Error("Not implemented: draw")}},xg=class extends o4{#e=null;#t=null;#n=Lt.INITIAL;#i=null;#r=0;#o=null;canvas=null;div=null;enableOptimizedPartialRendering=!1;eventBus=null;id=null;pageColors=null;recordedBBoxes=null;renderingQueue=null;constructor(e){super(),this.eventBus=e.eventBus,this.id=e.id,this.pageColors=e.pageColors||null,this.renderingQueue=e.renderingQueue,this.enableOptimizedPartialRendering=e.enableOptimizedPartialRendering??!1,this.minDurationToUpdateCanvas=e.minDurationToUpdateCanvas??500}get renderingState(){return this.#n}set renderingState(e){if(e!==this.#n)switch(this.#n=e,this.#e&&(clearTimeout(this.#e),this.#e=null),e){case Lt.PAUSED:this.div.classList.remove("loading"),this.#r=0,this.#i?.(!1);break;case Lt.RUNNING:this.div.classList.add("loadingIcon"),this.#e=setTimeout(()=>{this.div.classList.add("loading"),this.#e=null},0),this.#r=Date.now();break;case Lt.INITIAL:case Lt.FINISHED:this.div.classList.remove("loadingIcon","loading"),this.#r=0;break}}_createCanvas(e,t=!1){let{pageColors:i}=this,r=!!(i?.background&&i?.foreground),s=this.canvas,o=!s&&!r&&!t,a=this.canvas=document.createElement("canvas");return this.#i=u=>{if(o){let l=this.#o;if(!u&&this.minDurationToUpdateCanvas>0){if(Date.now()-this.#r<this.minDurationToUpdateCanvas)return;l||(l=this.#o=a,a=this.canvas=a.cloneNode(!1),e(a))}if(l){a.getContext("2d",{alpha:!1}).drawImage(l,0,0),u?this.#a():this.#r=Date.now();return}e(a),this.#i=null;return}u&&(s?(s.replaceWith(a),s.width=s.height=0):e(a))},{canvas:a,prevCanvas:s}}#s=e=>{if(this.#i?.(!1),this.renderingQueue&&!this.renderingQueue.isHighestPriority(this)){this.renderingState=Lt.PAUSED,this.resume=()=>{this.renderingState=Lt.RUNNING,e()};return}e()};_resetCanvas(){let{canvas:e}=this;e&&(e.remove(),e.width=e.height=0,this.canvas=null,this.#a())}#a(){this.#o&&(this.#o.width=this.#o.height=0,this.#o=null)}async _drawCanvas(e,t,i){let r=this.renderTask=this.pdfPage.render(e);r.onContinue=this.#s,r.onError=o=>{o instanceof j3&&(t(),this.#t=null)};let s=null;try{await r.promise,this.#i?.(!0)}catch(o){if(o instanceof j3)return;s=o,this.#i?.(!0)}finally{this.#t=s,r===this.renderTask&&(this.renderTask=null,this.enableOptimizedPartialRendering&&(this.recordedBBoxes??=r.recordedBBoxes))}if(this.renderingState=Lt.FINISHED,i(r),s)throw s}cancelRendering({cancelExtraDelay:e=0}={}){this.renderTask&&(this.renderTask.cancel(e),this.renderTask=null),this.resume=null}dispatchPageRender(){this.eventBus.dispatch("pagerender",{source:this,pageNumber:this.id})}dispatchPageRendered(e,t){this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:e,isDetailView:t,timestamp:performance.now(),error:this.#t})}},a4=class{#e=null;async render({intent:e="display"}){e!=="display"||this.#e||this._cancelled||(this.#e=new ZX)}cancel(){this._cancelled=!0,this.#e&&(this.#e.destroy(),this.#e=null)}setParent(e){this.#e?.setParent(e)}getDrawLayer(){return this.#e}},u4=class extends xg{#e=null;renderingCancelled=!1;constructor({pageView:e}){super(e),this.pageView=e,this.renderingId="detail"+this.id,this.div=e.div}setPdfPage(e){this.pageView.setPdfPage(e)}get pdfPage(){return this.pageView.pdfPage}get renderingState(){return super.renderingState}set renderingState(e){this.renderingCancelled=!1,super.renderingState=e}reset({keepCanvas:e=!1}={}){let t=this.renderingCancelled||this.renderingState===Lt.RUNNING||this.renderingState===Lt.PAUSED;this.cancelRendering(),this.renderingState=Lt.INITIAL,this.renderingCancelled=t,e||this._resetCanvas()}#t(e){if(!this.#e)return!0;let t=this.#e.minX,i=this.#e.minY,r=this.#e.width+t,s=this.#e.height+i;if(e.minX<t||e.minY<i||e.maxX>r||e.maxY>s)return!0;let{width:o,height:a,scale:u}=this.pageView.viewport;if(this.#e.scale!==u)return!0;let l=e.minX-t,c=r-e.maxX,h=e.minY-i,f=s-e.maxY,m=.5,y=(1+m)/m;return t>0&&c/l>y||r<o&&l/c>y||i>0&&f/h>y||s<a&&h/f>y}update({visibleArea:e=null,underlyingViewUpdated:t=!1}={}){if(t){this.cancelRendering(),this.renderingState=Lt.INITIAL;return}if(!this.#t(e))return;let{viewport:i,maxCanvasPixels:r,capCanvasAreaFactor:s}=this.pageView,o=e.maxX-e.minX,a=e.maxY-e.minY,u=o*a*wg.pixelRatio**2,c=(Math.sqrt(wg.capPixels(r,s)/u)-1)/2,h=Math.min(1,c);h<0&&(h=0);let f=o*h,m=a*h,y=Math.max(0,e.minX-f),g=Math.min(i.width,e.maxX+f),b=Math.max(0,e.minY-m),A=Math.min(i.height,e.maxY+m),v=g-y,E=A-b;this.#e={minX:y,minY:b,width:v,height:E,scale:i.scale},this.reset({keepCanvas:!0})}_getRenderingContext(e,t){let i=this.pageView._getRenderingContext(e,t,!1),r=this.pdfPage.recordedBBoxes;if(!r||!this.enableOptimizedPartialRendering)return i;let{viewport:{width:s,height:o}}=this.pageView,{width:a,height:u,minX:l,minY:c}=this.#e,h=l/s,f=c/o,m=(l+a)/s,y=(c+u)/o;return{...i,operationsFilter(g){return r.isEmpty(g)?!1:r.minX(g)<=m&&r.maxX(g)>=h&&r.minY(g)<=y&&r.maxY(g)>=f}}}async draw(){if(this.pageView.detailView!==this)return;let e=this.pageView.renderingState===Lt.FINISHED||this.renderingState===Lt.FINISHED;this.renderingState!==Lt.INITIAL&&(console.error("Must be in new state before drawing"),this.reset());let{div:t,pdfPage:i,viewport:r}=this.pageView;if(!i)throw this.renderingState=Lt.FINISHED,new Error("pdfPage is not loaded");this.renderingState=Lt.RUNNING;let s=this.pageView._ensureCanvasWrapper(),{canvas:o,prevCanvas:a}=this._createCanvas(g=>{s.firstElementChild?.tagName==="CANVAS"?s.firstElementChild.after(g):s.prepend(g)},e);o.ariaHidden=!0,this.enableOptimizedPartialRendering&&(o.className="detailView");let{width:u,height:l}=r,c=this.#e,{pixelRatio:h}=wg,f=[h,0,0,h,-c.minX*h,-c.minY*h];o.width=c.width*h,o.height=c.height*h;let{style:m}=o;m.width=`${c.width*100/u}%`,m.height=`${c.height*100/l}%`,m.top=`${c.minY*100/l}%`,m.left=`${c.minX*100/u}%`;let y=this._drawCanvas(this._getRenderingContext(o,f),()=>{this.canvas?.remove(),this.canvas=a},()=>{this.dispatchPageRendered(!1,!0)});return t.setAttribute("data-loaded",!0),this.dispatchPageRender(),y}},jL={Document:null,DocumentFragment:null,Part:"group",Sect:"group",Div:"group",Aside:"note",NonStruct:"none",P:null,H:"heading",Title:null,FENote:"note",Sub:"group",Lbl:null,Span:null,Em:null,Strong:null,Link:"link",Annot:"note",Form:"form",Ruby:null,RB:null,RT:null,RP:null,Warichu:null,WT:null,WP:null,L:"list",LI:"listitem",LBody:null,Table:"table",TR:"row",TH:"columnheader",TD:"cell",THead:"rowgroup",TBody:"rowgroup",TFoot:null,Caption:null,Figure:"figure",Formula:null,Artifact:null},iR=new Set(["math","merror","mfrac","mi","mmultiscripts","mn","mo","mover","mpadded","mprescripts","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msubsup","msup","mtable","mtd","mtext","mtr","munder","munderover","semantics"]),Tg="http://www.w3.org/1998/Math/MathML",Ig=class{static get sanitizer(){return Ah(this,"sanitizer",zL.isSanitizerSupported?new Sanitizer({elements:[...iR].map(e=>({name:e,namespace:Tg})),replaceWithChildrenElements:[{name:"maction",namespace:Tg}],attributes:["dir","displaystyle","mathbackground","mathcolor","mathsize","scriptlevel","encoding","display","linethickness","intent","arg","form","fence","separator","lspace","rspace","stretchy","symmetric","maxsize","minsize","largeop","movablelimits","width","height","depth","voffset","accent","accentunder","columnspan","rowspan"],comments:!1}):null)}},Ree=/^H(\d+)$/,Pg=class{#e;#t=null;#n;#i=new Map;#r;#o=null;#s=null;#a=null;constructor(e,t){this.#e=e.getStructTree(),this.#r=t}async render(){if(this.#n)return this.#n;let{promise:e,resolve:t,reject:i}=Promise.withResolvers();this.#n=e;try{this.#t=this.#h(await this.#e)}catch(r){i(r)}return this.#e=null,this.#t?.classList.add("structTree"),t(this.#t),e}async getAriaAttributes(e){try{return await this.render(),this.#i.get(e)}catch{}return null}hide(){this.#t&&!this.#t.hidden&&(this.#t.hidden=!0)}show(){this.#t?.hidden&&(this.#t.hidden=!1)}#l(e,t){let{alt:i,id:r,lang:s}=e;if(i!==void 0){let o=!1,a=bh(i);for(let u of e.children)u.type==="annotation"&&(this.#i.getOrInsertComputed(u.id,rZ).set("aria-label",a),o=!0);o||t.setAttribute("aria-label",a)}r!==void 0&&t.setAttribute("aria-owns",r),s!==void 0&&t.setAttribute("lang",bh(s,!0))}#u(e,t){let{alt:i,bbox:r,children:s}=e,o=s?.[0];if(!this.#r||!i||!r||o?.type!=="content")return!1;let{id:a}=o;if(!a)return!1;t.setAttribute("aria-owns",a);let u=document.createElement("span");(this.#o||=new Map).set(a,u),u.setAttribute("role","img"),u.setAttribute("aria-label",bh(i));let{pageHeight:l,pageX:c,pageY:h}=this.#r,f="calc(var(--total-scale-factor) *",{style:m}=u;return m.width=`${f}${r[2]-r[0]}px)`,m.height=`${f}${r[3]-r[1]}px)`,m.left=`${f}${r[0]-c}px)`,m.top=`${f}${l-r[3]+h}px)`,!0}updateTextLayer(){if(this.#o){for(let[e,t]of this.#o)document.getElementById(e)?.append(t);this.#o.clear(),this.#o=null}if(this.#s){for(let e of this.#s){let t=document.getElementById(e);t&&(t.ariaHidden=!0)}this.#s.length=0,this.#s=null}if(this.#a){for(let e=0,t=this.#a.length;e<t;e+=2){let i=this.#a[e],r=this.#a[e+1],s="";for(let o of r){let a=document.getElementById(o);a&&(s+=a.textContent.trim()||"",a.ariaHidden="true")}s&&(i.textContent=s)}this.#a.length=0,this.#a=null}}#h(e,t=[]){if(!e)return null;let i;if("role"in e){let{role:r}=e;if(iR.has(r)){i=document.createElementNS(Tg,r);let o=[];(this.#a||=[]).push(i,o);for(let{type:a,id:u}of e.children||[])a==="content"&&u&&o.push(u)}else i=document.createElement("span");let s=r.match(Ree);if(s?(i.setAttribute("role","heading"),i.setAttribute("aria-level",s[1])):jL[r]&&i.setAttribute("role",r==="TH"&&t.at(-1)?.role==="TR"&&t.at(-2)?.role==="TBody"?"rowheader":jL[r]),r==="Figure"&&this.#u(e,i))return i;if(r==="Formula"){if(e.mathML&&Ig.sanitizer){i.setHTML(e.mathML,{sanitizer:Ig.sanitizer});for(let{id:o}of e.children||[])o&&(this.#s||=[]).push(o);delete e.alt}!e.mathML&&e.children.length===1&&e.children[0].role!=="math"&&(i=document.createElementNS(Tg,"math"),delete e.alt)}}if(i||=document.createElement("span"),this.#l(e,i),e.children)if(e.children.length===1&&"id"in e.children[0])this.#l(e.children[0],i);else{t.push(e);for(let r of e.children)i.append(this.#h(r,t));t.pop()}return i}},l4=class n{#e=!1;#t=null;#n=new Map;#i=new Map;setTextMapping(e){this.#t=e}static#r(e,t){let i=e.getBoundingClientRect(),r=t.getBoundingClientRect();if(i.width===0&&i.height===0)return 1;if(r.width===0&&r.height===0)return-1;let s=i.y,o=i.y+i.height,a=i.y+i.height/2,u=r.y,l=r.y+r.height,c=r.y+r.height/2;if(a<=u&&c>=o)return-1;if(c<=s&&a>=l)return 1;let h=i.x+i.width/2,f=r.x+r.width/2;return h-f}enable(){if(this.#e)throw new Error("TextAccessibilityManager is already enabled.");if(!this.#t)throw new Error("Text divs and strings have not been set.");if(this.#e=!0,this.#t=this.#t.slice(),this.#t.sort(n.#r),this.#n.size>0){let e=this.#t;for(let[t,i]of this.#n){if(!document.getElementById(t)){this.#n.delete(t);continue}this.#o(t,e[i])}}for(let[e,t]of this.#i)this.addPointerInTextLayer(e,t);this.#i.clear()}disable(){this.#e&&(this.#i.clear(),this.#t=null,this.#e=!1)}removePointerInTextLayer(e){if(!this.#e){this.#i.delete(e);return}let t=this.#t;if(!t||t.length===0)return;let{id:i}=e,r=this.#n.get(i);if(r===void 0)return;let s=t[r];this.#n.delete(i);let o=s.getAttribute("aria-owns");o?.includes(i)&&(o=o.split(" ").filter(a=>a!==i).join(" "),o?s.setAttribute("aria-owns",o):(s.removeAttribute("aria-owns"),s.setAttribute("role","presentation")))}#o(e,t){let i=t.getAttribute("aria-owns");i?.includes(e)||t.setAttribute("aria-owns",i?`${i} ${e}`:e),t.removeAttribute("role")}addPointerInTextLayer(e,t){let{id:i}=e;if(!i)return null;if(!this.#e)return this.#i.set(e,t),null;t&&this.removePointerInTextLayer(e);let r=this.#t;if(!r||r.length===0)return null;let s=vh(r,l=>n.#r(e,l)<0),o=Math.max(0,s-1),a=r[o];this.#o(i,a),this.#n.set(i,o);let u=a.parentNode;return u?.classList.contains("markedContent")?u.id:null}moveElementInDOM(e,t,i,r){let s=this.addPointerInTextLayer(i,r);if(!e.hasChildNodes())return e.append(t),s;let o=Array.from(e.childNodes).filter(u=>u!==t);if(o.length===0)return s;let a=vh(o,u=>n.#r(t,u)<0);return a===0?o[0].before(t):o[a-1].after(t),s}},c4=class{#e=null;constructor({findController:e,eventBus:t,pageIndex:i}){this.findController=e,this.matches=[],this.eventBus=t,this.pageIdx=i,this.textDivs=null,this.textContentItemsStr=null,this.enabled=!1}setTextMapping(e,t){this.textDivs=e,this.textContentItemsStr=t}enable(){if(!this.textDivs||!this.textContentItemsStr)throw new Error("Text divs and strings have not been set.");if(this.enabled)throw new Error("TextHighlighter is already enabled.");this.enabled=!0,this.#e||(this.#e=new AbortController,this.eventBus._on("updatetextlayermatches",e=>{(e.pageIndex===this.pageIdx||e.pageIndex===-1)&&this._updateMatches()},{signal:this.#e.signal})),this._updateMatches()}disable(){this.enabled&&(this.enabled=!1,this.#e?.abort(),this.#e=null,this._updateMatches(!0))}_convertMatches(e,t){if(!e)return[];let{textContentItemsStr:i}=this,r=0,s=0,o=i.length-1,a=[];for(let u=0,l=e.length;u<l;u++){let c=e[u];for(;r!==o&&c>=s+i[r].length;)s+=i[r].length,r++;r===i.length&&console.error("Could not find a matching mapping");let h={begin:{divIdx:r,offset:c-s}};for(c+=t[u];r!==o&&c>s+i[r].length;)s+=i[r].length,r++;h.end={divIdx:r,offset:c-s},a.push(h)}return a}_renderMatches(e){if(e.length===0)return;let{findController:t,pageIdx:i}=this,{textContentItemsStr:r,textDivs:s}=this,o=i===t.selected.pageIdx,a=t.selected.matchIdx,u=t.state.highlightAll,l=null,c={divIdx:-1,offset:void 0};function h(A,v){let E=A.divIdx;return s[E].textContent="",f(E,0,A.offset,v)}function f(A,v,E,S){let C=s[A];if(C.nodeType===Node.TEXT_NODE){let I=document.createElement("span");C.before(I),I.append(C),s[A]=I,C=I}let T=r[A].substring(v,E),M=document.createTextNode(T);if(S){let I=document.createElement("span");if(I.className=`${S} appended`,I.append(M),C.append(I),S.includes("selected")){let{left:L}=I.getClientRects()[0],R=C.getBoundingClientRect().left;return L-R}return 0}return C.append(M),0}let m=a,y=m+1;if(u)m=0,y=e.length;else if(!o)return;let g=-1,b=-1;for(let A=m;A<y;A++){let v=e[A],E=v.begin;if(E.divIdx===g&&E.offset===b)continue;g=E.divIdx,b=E.offset;let S=v.end,C=o&&A===a,T=C?" selected":"",M=0;if(!l||E.divIdx!==l.divIdx?(l!==null&&f(l.divIdx,l.offset,c.offset),h(E)):f(l.divIdx,l.offset,E.offset),E.divIdx===S.divIdx)M=f(E.divIdx,E.offset,S.offset,"highlight"+T);else{M=f(E.divIdx,E.offset,c.offset,"highlight begin"+T);for(let I=E.divIdx+1,L=S.divIdx;I<L;I++)s[I].className="highlight middle"+T;h(S,"highlight end"+T)}l=S,C&&t.scrollMatchIntoView({element:s[E.divIdx],selectedLeft:M,pageIndex:i,matchIndex:a})}l&&f(l.divIdx,l.offset,c.offset)}_updateMatches(e=!1){if(!this.enabled&&!e)return;let{findController:t,matches:i,pageIdx:r}=this,{textContentItemsStr:s,textDivs:o}=this,a=-1;for(let c of i){let h=Math.max(a,c.begin.divIdx);for(let f=h,m=c.end.divIdx;f<=m;f++){let y=o[f];y.textContent=s[f],y.className=""}a=c.end.divIdx+1}if(!t?.highlightMatches||e)return;let u=t.pageMatches[r]||null,l=t.pageMatchesLength[r]||null;this.matches=this._convertMatches(u,l),this._renderMatches(this.matches)}},Mg=class n{#e=!1;#t=null;#n=!1;#i=null;static#r=new Map;static#o=null;constructor({pdfPage:e,highlighter:t=null,accessibilityManager:i=null,enablePermissions:r=!1,onAppend:s=null}){this.pdfPage=e,this.highlighter=t,this.accessibilityManager=i,this.#e=r===!0,this.#t=s,this.div=document.createElement("div"),this.div.tabIndex=0,this.div.className="textLayer"}async render({viewport:e,textContentParams:t=null}){if(this.#n&&this.#i){this.#i.update({viewport:e,onBefore:this.hide.bind(this)}),this.show();return}this.cancel(),this.#i=new oZ({textContentSource:this.pdfPage.streamTextContent(t||{includeMarkedContent:!0,disableNormalization:!0}),container:this.div,viewport:e});let{textDivs:i,textContentItemsStr:r}=this.#i;this.highlighter?.setTextMapping(i,r),this.accessibilityManager?.setTextMapping(i),await this.#i.render(),this.#n=!0;let s=document.createElement("div");s.className="endOfContent",this.div.append(s),this.#s(s),this.#t?.(this.div),this.highlighter?.enable(),this.accessibilityManager?.enable()}hide(){!this.div.hidden&&this.#n&&(this.highlighter?.disable(),this.div.hidden=!0)}show(){this.div.hidden&&this.#n&&(this.div.hidden=!1,this.highlighter?.enable())}cancel(){this.#i?.cancel(),this.#i=null,this.highlighter?.disable(),this.accessibilityManager?.disable(),n.#a(this.div)}#s(e){let{div:t}=this;t.addEventListener("mousedown",()=>{t.classList.add("selecting")}),t.addEventListener("copy",i=>{if(!this.#e){let r=document.getSelection();i.clipboardData.setData("text/plain",bh(sZ(r.toString())))}G3(i)}),n.#r.set(t,e),n.#l()}static#a(e){this.#r.delete(e),this.#r.size===0&&(this.#o?.abort(),this.#o=null)}static#l(){if(this.#o)return;this.#o=new AbortController;let{signal:e}=this.#o,t=(o,a)=>{a.append(o),o.style.width="",o.style.height="",a.classList.remove("selecting")},i=!1;document.addEventListener("pointerdown",()=>{i=!0},{signal:e}),document.addEventListener("pointerup",()=>{i=!1,this.#r.forEach(t)},{signal:e}),window.addEventListener("blur",()=>{i=!1,this.#r.forEach(t)},{signal:e}),document.addEventListener("keyup",()=>{i||this.#r.forEach(t)},{signal:e});var r,s;document.addEventListener("selectionchange",()=>{let o=document.getSelection();if(o.rangeCount===0){this.#r.forEach(t);return}let a=new Set;for(let m=0;m<o.rangeCount;m++){let y=o.getRangeAt(m);for(let g of this.#r.keys())!a.has(g)&&y.intersectsNode(g)&&a.add(g)}for(let[m,y]of this.#r)a.has(m)?m.classList.add("selecting"):t(y,m);if(r??=getComputedStyle(this.#r.values().next().value).getPropertyValue("-moz-user-select")==="none",r)return;let u=o.getRangeAt(0),l=s&&(u.compareBoundaryPoints(Range.END_TO_END,s)===0||u.compareBoundaryPoints(Range.START_TO_END,s)===0),c=l?u.startContainer:u.endContainer;if(c.nodeType===Node.TEXT_NODE&&(c=c.parentNode),c.classList?.contains("highlight")&&(c=c.parentNode),!l&&u.endOffset===0)do{for(;!c.previousSibling;)c=c.parentNode;c=c.previousSibling}while(!c.childNodes.length);let h=c.parentElement?.closest(".textLayer"),f=this.#r.get(h);f&&(f.style.width=h.style.width,f.style.height=h.style.height,f.style.userSelect="text",c.parentElement.insertBefore(f,l?c:c.nextSibling)),s=u.cloneRange()},{signal:e})}},Lg=class{constructor({pdfPage:e,annotationStorage:t=null,linkService:i,xfaHtml:r=null}){this.pdfPage=e,this.annotationStorage=t,this.linkService=i,this.xfaHtml=r,this.div=null,this._cancelled=!1}async render({viewport:e,intent:t="display"}){if(t==="print"){let s={viewport:e.clone({dontFlip:!0}),div:this.div,xfaHtml:this.xfaHtml,annotationStorage:this.annotationStorage,linkService:this.linkService,intent:t};return this.div=document.createElement("div"),s.div=this.div,k3.render(s)}let i=await this.pdfPage.getXfa();if(this._cancelled||!i)return{textDivs:[]};let r={viewport:e.clone({dontFlip:!0}),div:this.div,xfaHtml:i,annotationStorage:this.annotationStorage,linkService:this.linkService,intent:t};return this.div?k3.update(r):(this.div=document.createElement("div"),r.div=this.div,k3.render(r))}cancel(){this._cancelled=!0}hide(){this.div&&(this.div.hidden=!0)}},kee={annotationEditorUIManager:null,annotationStorage:null,downloadManager:null,enableScripting:!1,fieldObjectsPromise:null,findController:null,hasJSActionsPromise:null,get linkService(){return new Eh}},Oee=new Map([["canvasWrapper",0],["textLayer",1],["annotationLayer",2],["annotationEditorLayer",3],["xfaLayer",3]]),Rg=class n extends xg{#e=Ps.ENABLE_FORMS;#t=null;#n=null;#i=!0;#r=!1;#o=!1;#s=null;#a=!1;#l=null;#u=null;#h=1;#d=1;#f=Is.ENABLE;#m=1;#p={directDrawing:!0,initialOptionalContent:!0,regularAnnotations:!0};#c=[null,null,null,null];#g=null;constructor(e){super(e);let{container:t,defaultViewport:i}=e;this.renderingId="page"+this.id,this.#s=e.layerProperties||kee,this.pdfPage=null,this.pageLabel=null,this.rotation=0,this.scale=e.scale||JL,this.viewport=i,this.pdfPageRotate=i.rotation,this._optionalContentConfigPromise=e.optionalContentConfigPromise||null,this.#f=e.textLayerMode??Is.ENABLE,this.#e=e.annotationMode??Ps.ENABLE_FORMS,this.imageResourcesPath=e.imageResourcesPath||"",this.enableDetailCanvas=e.enableDetailCanvas??!0,this.maxCanvasPixels=e.maxCanvasPixels??yh.get("maxCanvasPixels"),this.maxCanvasDim=e.maxCanvasDim||yh.get("maxCanvasDim"),this.capCanvasAreaFactor=e.capCanvasAreaFactor??yh.get("capCanvasAreaFactor"),this.#i=e.enableAutoLinking!==!1,this.#n=e.commentManager||null,this.#g=e.clonedFrom||null,this.l10n=e.l10n,this.l10n||=new Ql,this._isStandalone=!this.renderingQueue?.hasViewer(),this._container=t,this._annotationCanvasMap=null,this.annotationLayer=null,this.annotationEditorLayer=null,this.textLayer=null,this.xfaLayer=null,this.structTreeLayer=null,this.drawLayer=null,this.detailView=null;let r=document.createElement("div");if(r.className="page",r.setAttribute("data-page-number",this.id),r.setAttribute("role","region"),r.setAttribute("data-l10n-id","pdfjs-page-landmark"),r.setAttribute("data-l10n-args",JSON.stringify({page:this.id})),this.div=r,this.#A(),t?.append(r),this._isStandalone){t?.style.setProperty("--scale-factor",this.scale*bo.PDF_TO_CSS_UNITS),this.pageColors?.background&&t?.style.setProperty("--page-bg-color",this.pageColors.background);let{optionalContentConfigPromise:s}=e;s&&s.then(o=>{s===this._optionalContentConfigPromise&&(this.#p.initialOptionalContent=o.hasInitialVisibility)}),e.l10n||this.l10n.translate(this.div)}}clone(e){let t=new n({container:null,eventBus:this.eventBus,pagesColors:this.pageColors,renderingQueue:this.renderingQueue,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering,minDurationToUpdateCanvas:this.minDurationToUpdateCanvas,defaultViewport:this.viewport,id:e,layerProperties:this.#s,scale:this.scale,optionalContentConfigPromise:this._optionalContentConfigPromise,textLayerMode:this.#f,annotationMode:this.#e,imageResourcesPath:this.imageResourcesPath,enableDetailCanvas:this.enableDetailCanvas,maxCanvasPixels:this.maxCanvasPixels,maxCanvasDim:this.maxCanvasDim,capCanvasAreaFactor:this.capCanvasAreaFactor,enableAutoLinking:this.#i,commentManager:this.#n,l10n:this.l10n,clonedFrom:this});return t.setPdfPage(this.pdfPage),t}#y(e,t){let i=Oee.get(t),r=this.#c[i];if(this.#c[i]=e,r){r.replaceWith(e);return}for(let s=i-1;s>=0;s--){let o=this.#c[s];if(o){o.after(e);return}}this.div.prepend(e)}#A(){let{div:e,viewport:t}=this;if(t.userUnit!==this.#m&&(t.userUnit!==1?e.style.setProperty("--user-unit",t.userUnit):e.style.removeProperty("--user-unit"),this.#m=t.userUnit),this.pdfPage){if(this.#u===t.rotation)return;this.#u=t.rotation}YL(e,t,!0,!1)}updatePageNumber(e){if(this.id===e)return;this.id=e,this.renderingId=`page${e}`,this.pdfPage&&(this.pdfPage.pageNumber=e),this.setPageLabel(this.pageLabel);let{div:t}=this;t.setAttribute("data-page-number",e),t.setAttribute("data-l10n-args",JSON.stringify({page:e})),this._textHighlighter.pageIdx=e-1,this.annotationEditorLayer?.updatePageIndex(e-1)}setPdfPage(e){this._isStandalone&&(this.pageColors?.foreground==="CanvasText"||this.pageColors?.background==="Canvas")&&(this._container?.style.setProperty("--hcm-highlight-filter",e.filterFactory.addHighlightHCMFilter("highlight","CanvasText","Canvas","HighlightText","Highlight")),this._container?.style.setProperty("--hcm-highlight-selected-filter",e.filterFactory.addHighlightHCMFilter("highlight_selected","CanvasText","Canvas","HighlightText","Highlight"))),this.pdfPage=e,this.pdfPageRotate=e.rotate;let t=(this.rotation+this.pdfPageRotate)%360;this.viewport=e.getViewport({scale:this.scale*bo.PDF_TO_CSS_UNITS,rotation:t}),this.#A(),this.reset()}destroy(){this.reset(),this.pdfPage?.cleanup()}deleteMe(e){if(e){this.div.remove();return}this.destroy(),this.#s.annotationEditorUIManager?.deletePage(this.id)}hasEditableAnnotations(){return!!this.annotationLayer?.hasEditableAnnotations()}get _textHighlighter(){return Ah(this,"_textHighlighter",new c4({pageIndex:this.id-1,eventBus:this.eventBus,findController:this.#s.findController}))}#b(e,t){this.eventBus.dispatch(e,{source:this,pageNumber:this.id,error:t})}async#C(){let e=null;try{await this.annotationLayer.render({viewport:this.viewport,intent:"display",structTreeLayer:this.structTreeLayer})}catch(t){console.error("#renderAnnotationLayer:",t),e=t}finally{this.#b("annotationlayerrendered",e)}}async#E(){let e=null;try{await this.annotationEditorLayer.render({viewport:this.viewport,intent:"display"})}catch(t){console.error("#renderAnnotationEditorLayer:",t),e=t}finally{this.#b("annotationeditorlayerrendered",e)}}async#v(){try{await this.drawLayer.render({intent:"display"})}catch(e){console.error("#renderDrawLayer:",e)}}async#_(){let e=null;try{let t=await this.xfaLayer.render({viewport:this.viewport,intent:"display"});t?.textDivs&&this._textHighlighter&&this.#M(t.textDivs)}catch(t){console.error("#renderXfaLayer:",t),e=t}finally{this.xfaLayer?.div&&(this.l10n.pause(),this.#y(this.xfaLayer.div,"xfaLayer"),this.l10n.resume()),this.#b("xfalayerrendered",e)}}async#w(){if(!this.textLayer)return;let e=null;try{await this.textLayer.render({viewport:this.viewport})}catch(t){if(t instanceof JX)return;console.error("#renderTextLayer:",t),e=t}this.#b("textlayerrendered",e),this.#x()}async#x(){if(!this.textLayer)return;let e=await this.structTreeLayer?.render();e&&(this.l10n.pause(),this.structTreeLayer?.updateTextLayer(),this.canvas&&e.parentNode!==this.canvas&&this.canvas.append(e),this.l10n.resume()),this.structTreeLayer?.show()}async#M(e){let t=await this.pdfPage.getTextContent(),i=[];for(let r of t.items)i.push(r.str);this._textHighlighter.setTextMapping(e,i),this._textHighlighter.enable()}async#I(e){let t=null;try{if(await e,!this.annotationLayer)return;await this.annotationLayer.injectLinkAnnotations(s4.processLinks(this))}catch(i){console.error("#injectLinkAnnotations:",i),t=i}}_resetCanvas(){super._resetCanvas(),this.#l=null}reset({keepAnnotationLayer:e=!1,keepAnnotationEditorLayer:t=!1,keepXfaLayer:i=!1,keepTextLayer:r=!1,keepCanvasWrapper:s=!1,preserveDetailViewState:o=!1}={}){let a=this.pdfPage?._pdfBug??!1;this.cancelRendering({keepAnnotationLayer:e,keepAnnotationEditorLayer:t,keepXfaLayer:i,keepTextLayer:r}),this.renderingState=Lt.INITIAL;let u=this.div,l=u.childNodes,c=e&&this.annotationLayer?.div||null,h=t&&this.annotationEditorLayer?.div||null,f=i&&this.xfaLayer?.div||null,m=r&&this.textLayer?.div||null,y=s&&this.#t||null;for(let g=l.length-1;g>=0;g--){let b=l[g];switch(b){case c:case h:case f:case m:case y:continue}if(a&&b.classList.contains("pdfBugGroupsLayer"))continue;b.remove();let A=this.#c.indexOf(b);A>=0&&(this.#c[A]=null)}u.removeAttribute("data-loaded"),c&&this.annotationLayer.hide(),h&&this.annotationEditorLayer.hide(),f&&this.xfaLayer.hide(),m&&this.textLayer.hide(),this.structTreeLayer?.hide(),!s&&this.#t&&(this.#t=null,this._resetCanvas()),o||(this.detailView?.reset({keepCanvas:s}),s||(this.detailView=null))}toggleEditingMode(e){this.#o=e,this.hasEditableAnnotations()&&this.reset({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,keepCanvasWrapper:!0})}updateVisibleArea(e){this.enableDetailCanvas&&(this.#a&&this.maxCanvasPixels>0&&e?(this.detailView??=new u4({pageView:this,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering}),this.detailView.update({visibleArea:e})):this.detailView&&(this.detailView.reset(),this.detailView=null))}update({scale:e=0,rotation:t=null,optionalContentConfigPromise:i=null,drawingDelay:r=-1}){this.scale=e||this.scale,typeof t=="number"&&(this.rotation=t),i instanceof Promise&&(this._optionalContentConfigPromise=i,i.then(o=>{i===this._optionalContentConfigPromise&&(this.#p.initialOptionalContent=o.hasInitialVisibility)})),this.#p.directDrawing=!0;let s=(this.rotation+this.pdfPageRotate)%360;if(this.viewport=this.viewport.clone({scale:this.scale*bo.PDF_TO_CSS_UNITS,rotation:s}),this.#A(),this._isStandalone&&this._container?.style.setProperty("--scale-factor",this.viewport.scale),this.#T(),this.canvas){let o=this.#r&&this.#a,a=r>=0&&r<1e3;if(a||o){a&&!o&&this.renderingState!==Lt.FINISHED&&(this.cancelRendering({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,cancelExtraDelay:r}),this.renderingState=Lt.FINISHED,this.#p.directDrawing=!1),this.cssTransform({redrawAnnotationLayer:!0,redrawAnnotationEditorLayer:!0,redrawXfaLayer:!0,redrawTextLayer:!a,hideTextLayer:a}),a||(this.detailView?.update({underlyingViewUpdated:!0}),this.dispatchPageRendered(!0,!1));return}}this.cssTransform({}),this.reset({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,keepCanvasWrapper:!0,preserveDetailViewState:!0}),this.detailView?.update({underlyingViewUpdated:!0})}#T(){let{width:e,height:t}=this.viewport,i=this.outputScale=new wg;if(this.maxCanvasPixels===0){let r=1/this.scale;i.sx*=r,i.sy*=r,this.#a=!0}else if(this.#a=i.limitCanvas(e,t,this.maxCanvasPixels,this.maxCanvasDim,this.capCanvasAreaFactor),this.#a&&this.enableDetailCanvas){let r=this.enableOptimizedPartialRendering?4:2;i.sx/=r,i.sy/=r}}cancelRendering({keepAnnotationLayer:e=!1,keepAnnotationEditorLayer:t=!1,keepXfaLayer:i=!1,keepTextLayer:r=!1,cancelExtraDelay:s=0}={}){super.cancelRendering({cancelExtraDelay:s}),this.textLayer&&(!r||!this.textLayer.div)&&(this.textLayer.cancel(),this.textLayer=null),this.annotationLayer&&(!e||!this.annotationLayer.div)&&(this.annotationLayer.cancel(),this.annotationLayer=null,this._annotationCanvasMap=null),this.structTreeLayer&&!this.textLayer&&(this.structTreeLayer=null),this.annotationEditorLayer&&(!t||!this.annotationEditorLayer.div)&&(this.drawLayer&&(this.drawLayer.cancel(),this.drawLayer=null),this.annotationEditorLayer.cancel(),this.annotationEditorLayer=null),this.xfaLayer&&(!i||!this.xfaLayer.div)&&(this.xfaLayer.cancel(),this.xfaLayer=null,this._textHighlighter?.disable())}cssTransform({redrawAnnotationLayer:e=!1,redrawAnnotationEditorLayer:t=!1,redrawXfaLayer:i=!1,redrawTextLayer:r=!1,hideTextLayer:s=!1}){let{canvas:o}=this;if(!o)return;let a=this.#l;if(this.viewport!==a){let u=(360+this.viewport.rotation-a.rotation)%360;if(u===90||u===270){let{width:l,height:c}=this.viewport,h=c/l,f=l/c;o.style.transform=`rotate(${u}deg) scale(${h},${f})`}else o.style.transform=u===0?"":`rotate(${u}deg)`}e&&this.annotationLayer&&this.#C(),t&&this.annotationEditorLayer&&(this.drawLayer&&this.#v(),this.#E()),i&&this.xfaLayer&&this.#_(),this.textLayer&&(s?(this.textLayer.hide(),this.structTreeLayer?.hide()):r&&this.#w())}get width(){return this.viewport.width}get height(){return this.viewport.height}getPagePoint(e,t){return this.viewport.convertToPdfPoint(e,t)}_ensureCanvasWrapper(){let e=this.#t;return e||(e=this.#t=document.createElement("div"),e.classList.add("canvasWrapper"),this.#y(e,"canvasWrapper")),e}_getRenderingContext(e,t,i){return{canvas:e,transform:t,viewport:this.viewport,annotationMode:this.#e,optionalContentConfigPromise:this._optionalContentConfigPromise,annotationCanvasMap:this._annotationCanvasMap,pageColors:this.pageColors,isEditing:this.#o,recordOperations:i}}async draw(){this.renderingState!==Lt.INITIAL&&(console.error("Must be in new state before drawing"),this.reset());let{div:e,l10n:t,pdfPage:i,viewport:r}=this;if(!i)throw this.renderingState=Lt.FINISHED,new Error("pdfPage is not loaded");this.renderingState=Lt.RUNNING;let s=this._ensureCanvasWrapper();if(!this.textLayer&&this.#f!==Is.DISABLE&&!i.isPureXfa&&(this._accessibilityManager||=new l4,this.textLayer=new Mg({pdfPage:i,highlighter:this._textHighlighter,accessibilityManager:this._accessibilityManager,enablePermissions:this.#f===Is.ENABLE_PERMISSIONS,onAppend:S=>{this.l10n.pause(),this.#y(S,"textLayer"),this.l10n.resume()}})),!this.annotationLayer&&this.#e!==Ps.DISABLE){let{annotationStorage:S,annotationEditorUIManager:C,downloadManager:T,enableComment:M,enableScripting:I,fieldObjectsPromise:L,hasJSActionsPromise:R,linkService:B}=this.#s;this._annotationCanvasMap||=new Map,this.annotationLayer=new Sg({pdfPage:i,annotationStorage:S,imageResourcesPath:this.imageResourcesPath,renderForms:this.#e===Ps.ENABLE_FORMS,linkService:B,downloadManager:T,enableComment:M,enableScripting:I,hasJSActionsPromise:R,fieldObjectsPromise:L,annotationCanvasMap:this._annotationCanvasMap,accessibilityManager:this._accessibilityManager,annotationEditorUIManager:C,commentManager:this.#n,onAppend:N=>{this.#y(N,"annotationLayer")}})}let{width:o,height:a}=r;this.#l=r;let{canvas:u,prevCanvas:l}=this._createCanvas(S=>{s.prepend(S)});u.setAttribute("role","presentation"),this.outputScale||this.#T();let{outputScale:c}=this;this.#r=this.#a;let h=yL(c.sx),f=yL(c.sy),m=u.width=gg(mg(o*c.sx),h[0]),y=u.height=gg(mg(a*c.sy),f[0]),g=gg(mg(o),h[1]),b=gg(mg(a),f[1]);c.sx=m/g,c.sy=y/b,this.#h!==h[1]&&(e.style.setProperty("--scale-round-x",`${h[1]}px`),this.#h=h[1]),this.#d!==f[1]&&(e.style.setProperty("--scale-round-y",`${f[1]}px`),this.#d=f[1]);let A=this.enableOptimizedPartialRendering&&this.#r&&!this.recordedBBoxes,v=c.scaled?[c.sx,0,0,c.sy,0,0]:null,E=this._drawCanvas(this._getRenderingContext(u,v,A),()=>{l?.remove(),this._resetCanvas()},S=>{this.#p.regularAnnotations=!S.separateAnnots,this.dispatchPageRendered(!1,!1)}).then(async()=>{if(this.renderingState!==Lt.FINISHED)return;this.structTreeLayer||=new Pg(i,r.rawDims);let S=this.#w();this.annotationLayer&&(await this.#C(),this.#i&&this.annotationLayer&&this.textLayer&&await this.#I(S));let{annotationEditorUIManager:C}=this.#s;C&&(this.drawLayer||=new a4,await this.#v(),this.drawLayer.setParent(s),(this.annotationLayer||this.#e===Ps.DISABLE)&&(this.annotationEditorLayer||=new n4({uiManager:C,pageIndex:this.id-1,l10n:t,structTreeLayer:this.structTreeLayer,accessibilityManager:this._accessibilityManager,annotationLayer:this.annotationLayer?.annotationLayer,textLayer:this.textLayer,drawLayer:this.drawLayer.getDrawLayer(),clonedFrom:this.#g?.annotationEditorLayer,onAppend:T=>{this.#y(T,"annotationEditorLayer")}}),this.#g=null,this.#E()))});if(i.isPureXfa){if(!this.xfaLayer){let{annotationStorage:S,linkService:C}=this.#s;this.xfaLayer=new Lg({pdfPage:i,annotationStorage:S,linkService:C})}this.#_()}return e.setAttribute("data-loaded",!0),this.dispatchPageRender(),E}setPageLabel(e){this.pageLabel=typeof e=="string"?e:null,this.div.setAttribute("data-l10n-args",JSON.stringify({page:this.pageLabel??this.id})),this.pageLabel!==null?this.div.setAttribute("data-page-label",this.pageLabel):this.div.removeAttribute("data-page-label")}get thumbnailCanvas(){let{directDrawing:e,initialOptionalContent:t,regularAnnotations:i}=this.#p;return e&&t&&i?this.canvas:null}};d4=class{constructor(e){this._ready=new Promise((t,i)=>{import(e).then(s=>{t(s.QuickJSSandbox())}).catch(i)})}async createSandbox(e){(await this._ready).create(e)}async dispatchEventInSandbox(e){let t=await this._ready;setTimeout(()=>t.dispatchEvent(e),0)}async destroySandbox(){(await this._ready).nukeSandbox()}},h4=class{#e=null;#t=null;#n=null;#i=null;#r=null;#o=null;#s=null;#a=null;#l=!1;#u=null;#h=null;constructor({eventBus:e,externalServices:t=null,docProperties:i=null}){this.#r=e,this.#o=t,this.#n=i}setViewer(e){this.#a=e}async setDocument(e){if(this.#s&&await this.#c(),this.#s=e,!e)return;let[t,i,r]=await Promise.all([e.getFieldObjects(),e.getCalculationOrderIds(),e.getJSActions()]);if(!t&&!r){await this.#c();return}if(e!==this.#s)return;try{this.#u=this.#p()}catch(a){console.error("setDocument:",a),await this.#c();return}let s=this.#r;this.#i=new AbortController;let{signal:o}=this.#i;s._on("updatefromsandbox",a=>{a?.source===window&&this.#d(a.detail)},{signal:o}),s._on("dispatcheventinsandbox",a=>{this.#u?.dispatchEventInSandbox(a.detail)},{signal:o}),s._on("pagechanging",({pageNumber:a,previous:u})=>{a!==u&&(this.#m(u),this.#f(a))},{signal:o}),s._on("pagerendered",({pageNumber:a})=>{this._pageOpenPending.has(a)&&a===this.#a.currentPageNumber&&this.#f(a)},{signal:o}),s._on("pagesdestroy",async()=>{await this.#m(this.#a.currentPageNumber),await this.#u?.dispatchEventInSandbox({id:"doc",name:"WillClose"}),this.#e?.resolve()},{signal:o});try{let a=await this.#n(e);if(e!==this.#s)return;await this.#u.createSandbox({objects:t,calculationOrder:i,appInfo:{platform:navigator.platform,language:navigator.language},docInfo:{...a,actions:r}}),s.dispatch("sandboxcreated",{source:this})}catch(a){console.error("setDocument:",a),await this.#c();return}await this.#u?.dispatchEventInSandbox({id:"doc",name:"Open"}),await this.#f(this.#a.currentPageNumber,!0),Promise.resolve().then(()=>{e===this.#s&&(this.#l=!0)})}async dispatchWillSave(){return this.#u?.dispatchEventInSandbox({id:"doc",name:"WillSave"})}async dispatchDidSave(){return this.#u?.dispatchEventInSandbox({id:"doc",name:"DidSave"})}async dispatchWillPrint(){if(this.#u){await this.#h?.promise,this.#h=Promise.withResolvers();try{await this.#u.dispatchEventInSandbox({id:"doc",name:"WillPrint"})}catch(e){throw this.#h.resolve(),this.#h=null,e}await this.#h.promise}}async dispatchDidPrint(){return this.#u?.dispatchEventInSandbox({id:"doc",name:"DidPrint"})}get destroyPromise(){return this.#t?.promise||null}get ready(){return this.#l}get _pageOpenPending(){return Ah(this,"_pageOpenPending",new Set)}get _visitedPages(){return Ah(this,"_visitedPages",new Map)}async#d(e){let t=this.#a,i=t.isInPresentationMode||t.isChangingPresentationMode,{id:r,siblings:s,command:o,value:a}=e;if(!r){switch(o){case"clear":console.clear();break;case"error":console.error(a);break;case"layout":if(!i){let l=yZ(a);t.spreadMode=l.spreadMode}break;case"page-num":t.currentPageNumber=a+1;break;case"print":await t.pagesPromise,this.#r.dispatch("print",{source:this});break;case"println":console.log(a);break;case"zoom":i||(t.currentScaleValue=a);break;case"SaveAs":this.#r.dispatch("download",{source:this});break;case"FirstPage":t.currentPageNumber=1;break;case"LastPage":t.currentPageNumber=t.pagesCount;break;case"NextPage":t.nextPage();break;case"PrevPage":t.previousPage();break;case"ZoomViewIn":i||t.increaseScale();break;case"ZoomViewOut":i||t.decreaseScale();break;case"WillPrintFinished":this.#h?.resolve(),this.#h=null;break}return}if(i&&e.focus)return;delete e.id,delete e.siblings;let u=s?[r,...s]:[r];for(let l of u){let c=document.querySelector(`[data-element-id="${l}"]`);c?c.dispatchEvent(new CustomEvent("updatefromsandbox",{detail:e})):this.#s?.annotationStorage.setValue(l,e)}}async#f(e,t=!1){let i=this.#s,r=this._visitedPages;if(t&&(this.#e=Promise.withResolvers()),!this.#e)return;let s=this.#a.getPageView(e-1);if(s?.renderingState!==Lt.FINISHED){this._pageOpenPending.add(e);return}this._pageOpenPending.delete(e);let o=(async()=>{let a=await(r.has(e)?null:s.pdfPage?.getJSActions());i===this.#s&&await this.#u?.dispatchEventInSandbox({id:"page",name:"PageOpen",pageNumber:e,actions:a})})();r.set(e,o)}async#m(e){let t=this.#s,i=this._visitedPages;if(!this.#e||this._pageOpenPending.has(e))return;let r=i.get(e);r&&(i.set(e,null),await r,t===this.#s&&await this.#u?.dispatchEventInSandbox({id:"page",name:"PageClose",pageNumber:e}))}#p(){if(this.#t=Promise.withResolvers(),this.#u)throw new Error("#initScripting: Scripting already exists.");return this.#o.createScripting()}async#c(){if(!this.#u){this.#s=null,this.#t?.resolve();return}this.#e&&(await Promise.race([this.#e.promise,new Promise(e=>{setTimeout(e,1e3)})]).catch(()=>{}),this.#e=null),this.#s=null;try{await this.#u.destroySandbox()}catch{}this.#h?.reject(new Error("Scripting destroyed.")),this.#h=null,this.#i?.abort(),this.#i=null,this._pageOpenPending.clear(),this._visitedPages.clear(),this.#u=null,this.#l=!1,this.#t?.resolve()}},f4=class extends h4{constructor(e){e.externalServices||window.addEventListener("updatefromsandbox",t=>{e.eventBus.dispatch("updatefromsandbox",{source:window,detail:t.detail})}),e.externalServices||={createScripting:()=>new d4(e.sandboxBundleSrc)},e.docProperties||=t=>Bee(t),super(e)}},Nee=3e4,p4=class{#e=null;#t=null;#n=null;#i=null;isThumbnailViewEnabled=!1;onIdle=null;printing=!1;constructor(){Object.defineProperty(this,"hasViewer",{value:()=>!!this.#i})}setViewer(e){this.#i=e}setThumbnailViewer(e){this.#n=e}isHighestPriority(e){return this.#e===e.renderingId}renderHighestPriority(e){this.#t&&(clearTimeout(this.#t),this.#t=null),!this.#i.forceRendering(e)&&(this.isThumbnailViewEnabled&&this.#n?.forceRendering()||this.printing||this.onIdle&&(this.#t=setTimeout(this.onIdle.bind(this),Nee)))}getHighestPriority(e,t,i,r=!1,s=!1){let o=e.views,a=o.length;if(a===0)return null;for(let f=0;f<a;f++){let m=o[f].view;if(!this.isViewFinished(m))return m}if(!s)for(let f=0;f<a;f++){let{detailView:m}=o[f].view;if(m&&!this.isViewFinished(m))return m}let u=e.first.id,l=e.last.id;if(l-u+1>a){let f=e.ids;for(let m=1,y=l-u;m<y;m++){let g=i?u+m:l-m;if(f.has(g))continue;let b=t[g-1];if(!this.isViewFinished(b))return b}}let c=i?l:u-2,h=t[c];return h&&!this.isViewFinished(h)||r&&(c+=i?1:-1,h=t[c],h&&!this.isViewFinished(h))?h:null}isViewFinished(e){return e.renderingState===Lt.FINISHED}renderView(e){switch(e.renderingState){case Lt.FINISHED:return!1;case Lt.PAUSED:this.#e=e.renderingId,e.resume();break;case Lt.RUNNING:this.#e=e.renderingId;break;case Lt.INITIAL:this.#e=e.renderingId,e.draw().finally(()=>{this.renderHighestPriority()}).catch(t=>{t instanceof j3||console.error("renderView:",t)});break}return!0}},GL=10,Ag={FORCE_SCROLL_MODE_PAGE:1e4,FORCE_LAZY_PAGE_INIT:5e3,PAUSE_EAGER_PAGE_INIT:250};g4=class{#e=new Set;#t=0;constructor(e){this.#t=e}push(e){let t=this.#e;t.has(e)&&t.delete(e),t.add(e),t.size>this.#t&&this.#n()}resize(e,t=null){this.#t=e;let i=this.#e;if(t){let r=i.size,s=1;for(let o of i)if(t.has(o.id)&&(i.delete(o),i.add(o)),++s>r)break}for(;i.size>this.#t;)this.#n()}has(e){return this.#e.has(e)}[Symbol.iterator](){return this.#e.keys()}#n(){let e=this.#e.keys().next().value;e?.destroy(),this.#e.delete(e)}},Xl=class{#e=null;#t=null;#n=null;#i=Gn.NONE;#r=null;#o=Ps.ENABLE_FORMS;#s=null;#a=null;#l=null;#u=!1;#h=!1;#d=!1;#f=!1;#m=!1;#p=!0;#c=null;#g=0;#y=null;#A=!0;#b=null;#C=null;#E=null;#v=!1;#_=null;#w=!1;#x=0;#M=new ResizeObserver(this.#$.bind(this));#I=null;#T=null;#B=null;#k=!0;#O=Is.ENABLE;#N=null;#R=null;constructor(e){let t="5.5.207";if(fL!==t)throw new Error(`The API version "${fL}" does not match the Viewer version "${t}".`);if(this.container=e.container,this.viewer=e.viewer||e.container.firstElementChild,this.#N=e.viewerAlert||null,this.container?.tagName!=="DIV"||this.viewer?.tagName!=="DIV")throw new Error("Invalid `container` and/or `viewer` option.");if(this.container.offsetParent&&getComputedStyle(this.container).position!=="absolute")throw new Error("The `container` must be absolutely positioned.");this.#M.observe(this.container),this.eventBus=e.eventBus,this.linkService=e.linkService||new Eh,this.downloadManager=e.downloadManager||null,this.findController=e.findController||null,this.#t=e.altTextManager||null,this.#s=e.commentManager||null,this.#B=e.signatureManager||null,this.#l=e.editorUndoBar||null,this.findController&&(this.findController.onIsPageVisible=r=>this._getVisiblePages().ids.has(r)),this._scriptingManager=e.scriptingManager||null,this.#O=e.textLayerMode??Is.ENABLE,this.#o=e.annotationMode??Ps.ENABLE_FORMS,this.#i=e.annotationEditorMode??Gn.NONE,this.#n=e.annotationEditorHighlightColors||null,this.#h=e.enableHighlightFloatingButton===!0,this.#f=e.enableUpdatedAddImage===!0,this.#m=e.enableNewAltTextWhenAddingImage===!0,this.imageResourcesPath=e.imageResourcesPath||"",this.enablePrintAutoRotate=e.enablePrintAutoRotate||!1,this.removePageBorders=e.removePageBorders||!1,this.maxCanvasPixels=e.maxCanvasPixels,this.maxCanvasDim=e.maxCanvasDim,this.capCanvasAreaFactor=e.capCanvasAreaFactor,this.enableDetailCanvas=e.enableDetailCanvas??!0,this.enableOptimizedPartialRendering=e.enableOptimizedPartialRendering??!1,this.l10n=e.l10n,this.l10n||=new Ql,this.#d=e.enablePermissions||!1,this.pageColors=e.pageColors||null,this.#y=e.mlManager||null,this.#u=e.enableHWA||!1,this.#k=e.supportsPinchToZoom!==!1,this.#p=e.enableAutoLinking!==!1,this.#g=e.minDurationToUpdateCanvas??500,this.defaultRenderingQueue=!e.renderingQueue,this.defaultRenderingQueue?(this.renderingQueue=new p4,this.renderingQueue.setViewer(this)):this.renderingQueue=e.renderingQueue;let{abortSignal:i}=e;i?.addEventListener("abort",()=>{this.#M.disconnect(),this.#M=null},{once:!0}),this.scroll=hZ(this.container,this._scrollUpdate.bind(this),i),this.presentationModeState=ql.UNKNOWN,this._resetView(),this.removePageBorders&&this.viewer.classList.add("removePageBorders"),this.#j(),this.eventBus._on("thumbnailrendered",({pageNumber:r,pdfPage:s})=>{let o=this._pages[r-1];this.#e.has(o)||s?.cleanup()}),e.l10n||this.l10n.translate(this.container)}get printingAllowed(){return this.#A}get pagesCount(){return this._pages.length}getPageView(e){return this._pages[e]}getCachedPageViews(){return new Set(this.#e)}get pageViewsReady(){return this._pages.every(e=>e?.pdfPage)}get renderForms(){return this.#o===Ps.ENABLE_FORMS}get enableScripting(){return!!this._scriptingManager}get currentPageNumber(){return this._currentPageNumber}set currentPageNumber(e){if(!Number.isInteger(e))throw new Error("Invalid page number.");this.pdfDocument&&(this._setCurrentPageNumber(e,!0)||console.error(`currentPageNumber: "${e}" is not a valid page.`))}_setCurrentPageNumber(e,t=!1){if(this._currentPageNumber===e)return t&&this.#G(),!0;if(!(0<e&&e<=this.pagesCount))return!1;let i=this._currentPageNumber;return this._currentPageNumber=e,this.eventBus.dispatch("pagechanging",{source:this,pageNumber:e,pageLabel:this._pageLabels?.[e-1]??null,previous:i}),t&&this.#G(),!0}get currentPageLabel(){return this._pageLabels?.[this._currentPageNumber-1]??null}set currentPageLabel(e){if(!this.pdfDocument)return;let t=e|0;if(this._pageLabels){let i=this._pageLabels.indexOf(e);i>=0&&(t=i+1)}this._setCurrentPageNumber(t,!0)||console.error(`currentPageLabel: "${e}" is not a valid page.`)}get currentScale(){return this._currentScale!==O3?this._currentScale:JL}set currentScale(e){if(isNaN(e))throw new Error("Invalid numeric scale.");this.pdfDocument&&this.#U(e,{noScroll:!1})}get currentScaleValue(){return this._currentScaleValue}set currentScaleValue(e){this.pdfDocument&&this.#U(e,{noScroll:!1})}get pagesRotation(){return this._pagesRotation}set pagesRotation(e){if(!QL(e))throw new Error("Invalid pages rotation angle.");if(!this.pdfDocument||(e%=360,e<0&&(e+=360),this._pagesRotation===e))return;this._pagesRotation=e;let t=this._currentPageNumber;this.refresh(!0,{rotation:e}),this._currentScaleValue&&this.#U(this._currentScaleValue,{noScroll:!0}),this.eventBus.dispatch("rotationchanging",{source:this,pagesRotation:e,pageNumber:t}),this.defaultRenderingQueue&&this.update()}get firstPagePromise(){return this.pdfDocument?this._firstPageCapability.promise:null}get onePageRendered(){return this.pdfDocument?this._onePageRenderedCapability.promise:null}get pagesPromise(){return this.pdfDocument?this._pagesCapability.promise:null}get _layerProperties(){let e=this;return Ah(this,"_layerProperties",{get annotationEditorUIManager(){return e.#r},get annotationStorage(){return e.pdfDocument?.annotationStorage},get downloadManager(){return e.downloadManager},get enableComment(){return!!e.#s},get enableScripting(){return!!e._scriptingManager},get fieldObjectsPromise(){return e.pdfDocument?.getFieldObjects()},get findController(){return e.findController},get hasJSActionsPromise(){return e.pdfDocument?.hasJSActions()},get linkService(){return e.linkService}})}#V(e){let t={annotationEditorMode:this.#i,annotationMode:this.#o,textLayerMode:this.#O};return e?(this.#A=e.includes(zl.PRINT_HIGH_QUALITY)||e.includes(zl.PRINT),this.eventBus.dispatch("printingallowed",{source:this,isAllowed:this.#A}),!e.includes(zl.COPY)&&this.#O===Is.ENABLE&&(t.textLayerMode=Is.ENABLE_PERMISSIONS),e.includes(zl.MODIFY_CONTENTS)||(t.annotationEditorMode=Gn.DISABLE),!e.includes(zl.MODIFY_ANNOTATIONS)&&!e.includes(zl.FILL_INTERACTIVE_FORMS)&&this.#o===Ps.ENABLE_FORMS&&(t.annotationMode=Ps.ENABLE),t):(this.#A=!0,this.eventBus.dispatch("printingallowed",{source:this,isAllowed:this.#A}),t)}async#P(e){if(document.visibilityState==="hidden"||!this.container.offsetParent||this._getVisiblePages().views.length===0)return;let t=Promise.withResolvers(),i=new AbortController;document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&t.resolve()},{signal:AbortSignal.any([e,i.signal])}),await Promise.race([this._onePageRenderedCapability.promise,t.promise]),i.abort()}async getAllText(){let e=[],t=[];for(let i=1,r=this.pdfDocument.numPages;i<=r;++i){if(this.#w)return null;t.length=0;let s=await this.pdfDocument.getPage(i),{items:o}=await s.getTextContent();for(let a of o)a.str&&t.push(a.str),a.hasEOL&&t.push(`
|
|
601
601
|
`);e.push(bh(t.join("")))}return e.join(`
|
|
602
|
-
`)}#S(e,t){let i=document.getSelection(),{focusNode:r,anchorNode:s}=i;if(s&&r&&i.containsNode(this.#_)){if(this.#v||e===Is.ENABLE_PERMISSIONS){G3(t);return}this.#v=!0;let{classList:o}=this.viewer;o.add("copyAll");let a=new AbortController;window.addEventListener("keydown",u=>this.#w=u.key==="Escape",{signal:a.signal}),this.getAllText().then(async u=>{u!==null&&await navigator.clipboard.writeText(u)}).catch(u=>{console.warn(`Something goes wrong when extracting the text: ${u.message}`)}).finally(()=>{this.#v=!1,this.#w=!1,a.abort(),o.remove("copyAll")}),G3(t)}}setDocument(e){if(this.pdfDocument&&(this.eventBus.dispatch("pagesdestroy",{source:this}),this._cancelRendering(),this._resetView(),this.findController?.setDocument(null),this._scriptingManager?.setDocument(null),this.#r?.destroy(),this.#r=null,this.#i=Gn.NONE,this.#A=!0),this.pdfDocument=e,!e)return;let t=e.numPages,i=e.getPage(1),r=e.getOptionalContentConfig({intent:"display"}),s=this.#d?e.getPermissions():Promise.resolve(),{eventBus:o,pageColors:a,viewer:u}=this;this.#c=new AbortController;let{signal:l}=this.#c;if(t>Ag.FORCE_SCROLL_MODE_PAGE){console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document.");let f=this._scrollMode=ct.PAGE;o.dispatch("scrollmodechanged",{source:this,mode:f})}this._pagesCapability.promise.then(()=>{o.dispatch("pagesloaded",{source:this,pagesCount:t})},()=>{});let c=f=>{let m=this._pages[f.pageNumber-1];m&&this.#e.push(m)};o._on("pagerender",c,{signal:l});let h=f=>{f.cssTransform||f.isDetailView||(this._onePageRenderedCapability.resolve({timestamp:f.timestamp}),o._off("pagerendered",h))};o._on("pagerendered",h,{signal:l}),Promise.all([i,s]).then(([f,m])=>{if(e!==this.pdfDocument)return;this._firstPageCapability.resolve(f),this._optionalContentConfigPromise=r;let{annotationEditorMode:y,annotationMode:g,textLayerMode:b}=this.#V(m);if(b!==Is.DISABLE){let S=this.#_=document.createElement("div");S.id="hiddenCopyElement",u.before(S)}if(y!==Gn.DISABLE){let S=y;e.isPureXfa?console.warn("Warning: XFA-editing is not implemented."):WL(S)?(this.#r=new QX(this.container,u,this.#N,this.#t,this.#s,this.#B,o,e,a,this.#n,this.#h,this.#f,this.#m,this.#y,this.#l,this.#k),o.dispatch("annotationeditoruimanager",{source:this,uiManager:this.#r}),S!==Gn.NONE&&(this.#ee(S),this.#r.updateMode(S))):console.error(`Invalid AnnotationEditor mode: ${S}`)}let A=this._scrollMode===ct.PAGE?null:u,v=this.currentScale,E=f.getViewport({scale:v*bo.PDF_TO_CSS_UNITS});u.style.setProperty("--scale-factor",E.scale),a?.background&&u.style.setProperty("--page-bg-color",a.background),(a?.foreground==="CanvasText"||a?.background==="Canvas")&&(u.style.setProperty("--hcm-highlight-filter",e.filterFactory.addHighlightHCMFilter("highlight","CanvasText","Canvas","HighlightText","Highlight")),u.style.setProperty("--hcm-highlight-selected-filter",e.filterFactory.addHighlightHCMFilter("highlight_selected","CanvasText","Canvas","HighlightText","ButtonText")));for(let S=1;S<=t;++S){let C=new Rg({container:A,eventBus:o,id:S,scale:v,defaultViewport:E.clone(),optionalContentConfigPromise:r,renderingQueue:this.renderingQueue,textLayerMode:b,annotationMode:g,imageResourcesPath:this.imageResourcesPath,maxCanvasPixels:this.maxCanvasPixels,maxCanvasDim:this.maxCanvasDim,capCanvasAreaFactor:this.capCanvasAreaFactor,enableDetailCanvas:this.enableDetailCanvas,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering,pageColors:a,l10n:this.l10n,layerProperties:this._layerProperties,enableHWA:this.#u,enableAutoLinking:this.#p,minDurationToUpdateCanvas:this.#g,commentManager:this.#s});this._pages.push(C)}this._pages[0]?.setPdfPage(f),this._scrollMode===ct.PAGE?this.#L():this._spreadMode!==ki.NONE&&this._updateSpreadMode(),o._on("annotationeditorlayerrendered",S=>{this.#r&&o.dispatch("annotationeditormodechanged",{source:this,mode:this.#i})},{once:!0,signal:l}),this.#P(l).then(async()=>{if(e!==this.pdfDocument)return;if(this.findController?.setDocument(e),this._scriptingManager?.setDocument(e),this.#_&&document.addEventListener("copy",this.#S.bind(this,b),{signal:l}),e.loadingParams.disableAutoFetch||t>Ag.FORCE_LAZY_PAGE_INIT){this._pagesCapability.resolve();return}let S=t-1;if(S<=0){this._pagesCapability.resolve();return}for(let C=2;C<=t;++C){let T=e.getPage(C).then(M=>{let I=this._pages[C-1];I.pdfPage||I.setPdfPage(M),--S===0&&this._pagesCapability.resolve()},M=>{console.error(`Unable to get page ${C} to initialize viewer`,M),--S===0&&this._pagesCapability.resolve()});C%Ag.PAUSE_EAGER_PAGE_INIT===0&&await T}}),o.dispatch("pagesinit",{source:this}),e.getMetadata().then(({info:S})=>{e===this.pdfDocument&&S.Language&&(u.lang=S.Language)}),this.defaultRenderingQueue&&this.update()}).catch(f=>{console.error("Unable to initialize viewer",f),this._pagesCapability.reject(f)})}onPagesEdited({pagesMapper:e,type:t,hasBeenCut:i,pageNumbers:r}){if(t==="copy"){this.#R=new Map;for(let l of r)this.#R.set(l,this._pages[l-1]);return}let s=t==="cut";if(s||t==="delete")for(let l of r)this._pages[l-1].deleteMe(s);this._currentPageNumber=0;let o=this._pages,a=this._pages=[];for(let l=1,c=e.pagesNumber;l<=c;l++){let h=e.getPrevPageNumber(l);if(h<0){let m=this.#R.get(-h);i?m.updatePageNumber(l):m=m.clone(l),a.push(m);continue}let f=o[h-1];a.push(f),f.updatePageNumber(l)}s||(this.#R=null);let u=this._scrollMode===ct.PAGE?null:this.viewer;if(u){u.replaceChildren();let l=document.createDocumentFragment();for(let c=0,h=e.pagesNumber;c<h;c++){let{div:f}=a[c];f.setAttribute("data-page-number",c+1),l.append(f)}u.append(l)}setTimeout(()=>{this.forceRendering()})}setPageLabels(e){if(this.pdfDocument){e?Array.isArray(e)&&this.pdfDocument.numPages===e.length?this._pageLabels=e:(this._pageLabels=null,console.error("setPageLabels: Invalid page labels.")):this._pageLabels=null;for(let t=0,i=this._pages.length;t<i;t++)this._pages[t].setPageLabel(this._pageLabels?.[t]??null)}}_resetView(){this._pages=[],this._currentPageNumber=1,this._currentScale=O3,this._currentScaleValue=null,this._pageLabels=null,this.#e=new g4(GL),this._location=null,this._pagesRotation=0,this._optionalContentConfigPromise=null,this._firstPageCapability=Promise.withResolvers(),this._onePageRenderedCapability=Promise.withResolvers(),this._pagesCapability=Promise.withResolvers(),this._scrollMode=ct.VERTICAL,this._previousScrollMode=ct.UNKNOWN,this._spreadMode=ki.NONE,this.#I={previousPageNumber:1,scrollDown:!0,pages:[]},this.#c?.abort(),this.#c=null,this.viewer.textContent="",this._updateScrollMode(),this.viewer.removeAttribute("lang"),this.#_?.remove(),this.#_=null,this.#Q(),this.#X()}#L(){if(this._scrollMode!==ct.PAGE)throw new Error("#ensurePageViewVisible: Invalid scrollMode value.");let e=this._currentPageNumber,t=this.#I,i=this.viewer;if(i.textContent="",t.pages.length=0,this._spreadMode===ki.NONE&&!this.isInPresentationMode){let r=this._pages[e-1];i.append(r.div),t.pages.push(r)}else{let r=new Set,s=this._spreadMode-1;s===-1?r.add(e-1):e%2!==s?(r.add(e-1),r.add(e)):(r.add(e-2),r.add(e-1));let o=document.createElement("div");if(o.className="spread",this.isInPresentationMode){let a=document.createElement("div");a.className="dummyPage",o.append(a)}for(let a of r){let u=this._pages[a];u&&(o.append(u.div),t.pages.push(u))}i.append(o)}t.scrollDown=e>=t.previousPageNumber,t.previousPageNumber=e}_scrollUpdate(){this.pagesCount!==0&&(this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.#b=null,this.update()},100),this.update())}#D(e,t=null){let{div:i,id:r}=e;if(this._currentPageNumber!==r&&this._setCurrentPageNumber(r),this._scrollMode===ct.PAGE&&(this.#L(),this.update()),!t&&!this.isInPresentationMode){let s=i.offsetLeft+i.clientLeft,o=s+i.clientWidth,{scrollLeft:a,clientWidth:u}=this.container;(this._scrollMode===ct.HORIZONTAL||s<a||o>a+u)&&(t={left:0,top:0})}$L(i,t),!this._currentScaleValue&&this._location&&(this._location=null)}#W(e){return e===this._currentScale||Math.abs(e-this._currentScale)<1e-15}#q(e,t,{noScroll:i=!1,preset:r=!1,drawingDelay:s=-1,origin:o=null}){if(this._currentScaleValue=t.toString(),this.#W(e)){r&&this.eventBus.dispatch("scalechanging",{source:this,scale:e,presetValue:t});return}this.viewer.style.setProperty("--scale-factor",e*bo.PDF_TO_CSS_UNITS);let a=s>=0&&s<1e3;this.refresh(!0,{scale:e,drawingDelay:a?s:-1}),a&&(this.#T=setTimeout(()=>{this.#T=null,this.refresh()},s));let u=this._currentScale;if(this._currentScale=e,!i){let l=this._currentPageNumber,c;if(this._location&&!(this.isInPresentationMode||this.isChangingPresentationMode)&&(l=this._location.pageNumber,c=[null,{name:"XYZ"},this._location.left,this._location.top,null]),this.scrollPageIntoView({pageNumber:l,destArray:c,allowNegativeOffset:!0}),Array.isArray(o)){let h=e/u-1,[f,m]=this.containerTopLeft;this.container.scrollLeft+=(o[0]-m)*h,this.container.scrollTop+=(o[1]-f)*h}}this.eventBus.dispatch("scalechanging",{source:this,scale:e,presetValue:r?t:void 0}),this.defaultRenderingQueue&&this.update()}get#Y(){return this._spreadMode!==ki.NONE&&this._scrollMode!==ct.HORIZONTAL?2:1}#U(e,t){let i=parseFloat(e);if(i>0)t.preset=!1,this.#q(i,e,t);else{let r=this._pages[this._currentPageNumber-1];if(!r)return;let s=gL,o=mL;this.isInPresentationMode?(s=o=4,this._spreadMode!==ki.NONE&&(s*=2)):this.removePageBorders?s=o=0:this._scrollMode===ct.HORIZONTAL&&([s,o]=[o,s]);let a=(this.container.clientWidth-s)/r.width*r.scale/this.#Y,u=(this.container.clientHeight-o)/r.height*r.scale;switch(e){case"page-actual":i=1;break;case"page-width":i=a;break;case"page-height":i=u;break;case"page-fit":i=Math.min(a,u);break;case"auto":let l=AL(r)?a:Math.min(u,a);i=Math.min(dZ,l);break;default:console.error(`#setScale: "${e}" is an unknown zoom value.`);return}t.preset=!0,this.#q(i,e,t)}}#G(){let e=this._pages[this._currentPageNumber-1];this.isInPresentationMode&&this.#U(this._currentScaleValue,{noScroll:!0}),this.#D(e)}pageLabelToPageNumber(e){if(!this._pageLabels)return null;let t=this._pageLabels.indexOf(e);return t<0?null:t+1}scrollPageIntoView({pageNumber:e,destArray:t=null,allowNegativeOffset:i=!1,ignoreDestinationZoom:r=!1,center:s=null}){if(!this.pdfDocument)return;let o=Number.isInteger(e)&&this._pages[e-1];if(!o){console.error(`scrollPageIntoView: "${e}" is not a valid pageNumber parameter.`);return}if(this.isInPresentationMode||!t){this._setCurrentPageNumber(e,!0);return}let a=0,u=0,l=0,c=0,h,f,m=o.rotation%180!==0,y=(m?o.height:o.width)/o.scale/bo.PDF_TO_CSS_UNITS,g=(m?o.width:o.height)/o.scale/bo.PDF_TO_CSS_UNITS,b=0;switch(t[1].name){case"XYZ":a=t[2],u=t[3],b=t[4],a=a!==null?a:0,u=u!==null?u:g;break;case"Fit":case"FitB":b="page-fit";break;case"FitH":case"FitBH":u=t[2],b="page-width",u===null&&this._location?(a=this._location.left,u=this._location.top):(typeof u!="number"||u<0)&&(u=g);break;case"FitV":case"FitBV":a=t[2],l=y,c=g,b="page-height";break;case"FitR":a=t[2],u=t[3],l=t[4]-a,c=t[5]-u;let S=gL,C=mL;this.removePageBorders&&(S=C=0),h=(this.container.clientWidth-S)/l/bo.PDF_TO_CSS_UNITS,f=(this.container.clientHeight-C)/c/bo.PDF_TO_CSS_UNITS,b=Math.min(Math.abs(h),Math.abs(f));break;default:console.error(`scrollPageIntoView: "${t[1].name}" is not a valid destination type.`);return}if(r||(b&&b!==this._currentScale?this.currentScaleValue=b:this._currentScale===O3&&(this.currentScaleValue=uZ)),b==="page-fit"&&!t[4]){this.#D(o);return}let A=[o.viewport.convertToViewportPoint(a,u),o.viewport.convertToViewportPoint(a+l,u+c)],v=Math.min(A[0][0],A[1][0]),E=Math.min(A[0][1],A[1][1]);s?((s==="both"||s==="vertical")&&(E-=(this.container.clientHeight-Math.abs(A[1][1]-A[0][1]))/2),(s==="both"||s==="horizontal")&&(v-=(this.container.clientWidth-Math.abs(A[1][0]-A[0][0]))/2)):i||(v=Math.max(v,0),E=Math.max(E,0)),this.#D(o,{left:v,top:E})}_updateLocation(e){let t=this._currentScale,i=this._currentScaleValue,r=parseFloat(i)===t?Math.round(t*1e4)/100:i,s=e.id,o=this._pages[s-1],a=this.container,u=o.getPagePoint(a.scrollLeft-e.x,a.scrollTop-e.y),l=Math.round(u[0]),c=Math.round(u[1]),h=`#page=${s}`;this.isInPresentationMode||(h+=`&zoom=${r},${l},${c}`),this._location={pageNumber:s,scale:r,top:c,left:l,rotation:this._pagesRotation,pdfOpenParams:h}}update(){let e=this._getVisiblePages(),t=e.views,i=t.length;if(i===0)return;let r=Math.max(GL,2*i+1);this.#e.resize(r,e.ids);for(let{view:u,visibleArea:l}of t)u.updateVisibleArea(l);for(let u of this.#e)e.ids.has(u.id)||u.updateVisibleArea(null);this.renderingQueue.renderHighestPriority(e);let s=this._spreadMode===ki.NONE&&(this._scrollMode===ct.PAGE||this._scrollMode===ct.VERTICAL),o=this._currentPageNumber,a=!1;for(let u of t){if(u.percent<100)break;if(u.id===o&&s){a=!0;break}}this._setCurrentPageNumber(a?this._currentPageNumber:t[0].id),this._updateLocation(e.first),this.eventBus.dispatch("updateviewarea",{source:this,location:this._location})}#F(){let e=this._getVisiblePages(),t=[],{ids:i,views:r}=e;for(let s of r){let{view:o}=s;if(!o.hasEditableAnnotations()){i.delete(o.id);continue}t.push(s)}return t.length===0?null:(this.renderingQueue.renderHighestPriority({first:t[0],last:t.at(-1),views:t,ids:i}),i)}containsElement(e){return this.container.contains(e)}focus(){this.container.focus()}get _isContainerRtl(){return getComputedStyle(this.container).direction==="rtl"}get isInPresentationMode(){return this.presentationModeState===ql.FULLSCREEN}get isChangingPresentationMode(){return this.presentationModeState===ql.CHANGING}get isHorizontalScrollbarEnabled(){return this.isInPresentationMode?!1:this.container.scrollWidth>this.container.clientWidth}get isVerticalScrollbarEnabled(){return this.isInPresentationMode?!1:this.container.scrollHeight>this.container.clientHeight}_getVisiblePages(){let e=this._scrollMode===ct.PAGE?this.#I.pages:this._pages,t=this._scrollMode===ct.HORIZONTAL,i=t&&this._isContainerRtl;return pZ({scrollEl:this.container,views:e,sortByVisibility:!0,horizontal:t,rtl:i})}cleanup(){for(let e of this._pages)e.renderingState!==Lt.FINISHED&&e.reset()}_cancelRendering(){for(let e of this._pages)e.cancelRendering()}async#K(e){if(e.pdfPage)return e.pdfPage;try{let t=await this.pdfDocument.getPage(e.id);return e.pdfPage||e.setPdfPage(t),t}catch(t){return console.error("Unable to get page for page view",t),null}}#Z(e){if(e.first?.id===1)return!0;if(e.last?.id===this.pagesCount)return!1;switch(this._scrollMode){case ct.PAGE:return this.#I.scrollDown;case ct.HORIZONTAL:return this.scroll.right}return this.scroll.down}forceRendering(e){let t=e||this._getVisiblePages(),i=this.#Z(t),r=this._spreadMode!==ki.NONE&&this._scrollMode!==ct.HORIZONTAL,s=this.#T!==null||this.#b!==null&&t.views.some(a=>a.detailView?.renderingCancelled),o=this.renderingQueue.getHighestPriority(t,this._pages,i,r,s);return o?(this.#K(o).then(()=>{this.renderingQueue.renderView(o)}),!0):!1}get hasEqualPageSizes(){let e=this._pages[0];for(let t=1,i=this._pages.length;t<i;++t){let r=this._pages[t];if(r.width!==e.width||r.height!==e.height)return!1}return!0}getPagesOverview(){let e;return this._pages.map(t=>{let i=t.pdfPage.getViewport({scale:1}),r=AL(i);if(e===void 0)e=r;else if(this.enablePrintAutoRotate&&r!==e)return{width:i.height,height:i.width,rotation:(i.rotation-90)%360};return{width:i.width,height:i.height,rotation:i.rotation}})}get optionalContentConfigPromise(){return this.pdfDocument?this._optionalContentConfigPromise?this._optionalContentConfigPromise:(console.error("optionalContentConfigPromise: Not initialized yet."),this.pdfDocument.getOptionalContentConfig({intent:"display"})):Promise.resolve(null)}set optionalContentConfigPromise(e){if(!(e instanceof Promise))throw new Error(`Invalid optionalContentConfigPromise: ${e}`);this.pdfDocument&&this._optionalContentConfigPromise&&(this._optionalContentConfigPromise=e,this.refresh(!1,{optionalContentConfigPromise:e}),this.eventBus.dispatch("optionalcontentconfigchanged",{source:this,promise:e}))}get scrollMode(){return this._scrollMode}set scrollMode(e){if(this._scrollMode!==e){if(!gZ(e))throw new Error(`Invalid scroll mode: ${e}`);this.pagesCount>Ag.FORCE_SCROLL_MODE_PAGE||(this._previousScrollMode=this._scrollMode,this._scrollMode=e,this.eventBus.dispatch("scrollmodechanged",{source:this,mode:e}),this._updateScrollMode(this._currentPageNumber))}}_updateScrollMode(e=null){let t=this._scrollMode,i=this.viewer;i.classList.toggle("scrollHorizontal",t===ct.HORIZONTAL),i.classList.toggle("scrollWrapped",t===ct.WRAPPED),!(!this.pdfDocument||!e)&&(t===ct.PAGE?this.#L():this._previousScrollMode===ct.PAGE&&this._updateSpreadMode(),this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#U(this._currentScaleValue,{noScroll:!0}),this._setCurrentPageNumber(e,!0),this.update())}get spreadMode(){return this._spreadMode}set spreadMode(e){if(this._spreadMode!==e){if(!mZ(e))throw new Error(`Invalid spread mode: ${e}`);this._spreadMode=e,this.eventBus.dispatch("spreadmodechanged",{source:this,mode:e}),this._updateSpreadMode(this._currentPageNumber)}}_updateSpreadMode(e=null){if(!this.pdfDocument)return;let t=this.viewer,i=this._pages;if(this._scrollMode===ct.PAGE)this.#L();else if(t.textContent="",this._spreadMode===ki.NONE)for(let r of this._pages)t.append(r.div);else{let r=this._spreadMode-1,s=null;for(let o=0,a=i.length;o<a;++o)s===null?(s=document.createElement("div"),s.className="spread",t.append(s)):o%2===r&&(s=s.cloneNode(!1),t.append(s)),s.append(i[o].div)}e&&(this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#U(this._currentScaleValue,{noScroll:!0}),this._setCurrentPageNumber(e,!0),this.update())}#J(e,t=!1){switch(this._scrollMode){case ct.WRAPPED:{let{views:i}=this._getVisiblePages(),r=new Map;for(let{id:s,y:o,percent:a,widthPercent:u}of i)a===0||u<100||r.getOrInsertComputed(o,nZ).push(s);for(let s of r.values()){let o=s.indexOf(e);if(o===-1)continue;let a=s.length;if(a===1)break;if(t)for(let u=o-1,l=0;u>=l;u--){let c=s[u],h=s[u+1]-1;if(c<h)return e-h}else for(let u=o+1,l=a;u<l;u++){let c=s[u],h=s[u-1]+1;if(c>h)return h-e}if(t){let u=s[0];if(u<e)return e-u+1}else{let u=s[a-1];if(u>e)return u-e+1}break}break}case ct.HORIZONTAL:break;case ct.PAGE:case ct.VERTICAL:{if(this._spreadMode===ki.NONE)break;let i=this._spreadMode-1;if(t&&e%2!==i)break;if(!t&&e%2===i)break;let{views:r}=this._getVisiblePages(),s=t?e-1:e+1;for(let{id:o,percent:a,widthPercent:u}of r)if(o===s){if(a>0&&u===100)return 2;break}break}}return 1}nextPage(){let e=this._currentPageNumber,t=this.pagesCount;if(e>=t)return!1;let i=this.#J(e,!1)||1;return this.currentPageNumber=Math.min(e+i,t),!0}previousPage(){let e=this._currentPageNumber;if(e<=1)return!1;let t=this.#J(e,!0)||1;return this.currentPageNumber=Math.max(e-t,1),!0}updateScale({drawingDelay:e,scaleFactor:t=null,steps:i=null,origin:r}){if(i===null&&t===null)throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided.");if(!this.pdfDocument)return;let s=this._currentScale;if(t>0&&t!==1)s=Math.round(s*t*100)/100;else if(i){let o=i>0?pL:1/pL,a=i>0?Math.ceil:Math.floor;i=Math.abs(i);do s=a((s*o).toFixed(2)*10)/10;while(--i>0)}s=qL(s,lZ,cZ),this.#U(s,{noScroll:!1,drawingDelay:e,origin:r})}increaseScale(e={}){this.updateScale({...e,steps:e.steps??1})}decreaseScale(e={}){this.updateScale({...e,steps:-(e.steps??1)})}#j(e=this.container.clientHeight){e!==this.#x&&(this.#x=e,bZ.setProperty("--viewer-container-height",`${e}px`))}#$(e){for(let t of e)if(t.target===this.container){this.#j(Math.floor(t.borderBoxSize[0].blockSize)),this.#a=null;break}}get containerTopLeft(){return this.#a||=[this.container.offsetTop,this.container.offsetLeft]}#Q(){this.#T!==null&&(clearTimeout(this.#T),this.#T=null),this.#b!==null&&(clearTimeout(this.#b),this.#b=null)}#X(){this.#C?.abort(),this.#C=null,this.#E!==null&&(clearTimeout(this.#E),this.#E=null)}#ee(e){switch(e){case Gn.STAMP:this.#y?.loadModel("altText");break;case Gn.SIGNATURE:this.#B?.loadSignatures();break}}get annotationEditorMode(){return this.#r?this.#i:Gn.DISABLE}set annotationEditorMode({mode:e,editId:t=null,isFromKeyboard:i=!1,mustEnterInEditMode:r=!1,editComment:s=!1}){if(!this.#r)throw new Error("The AnnotationEditor is not enabled.");if(this.#i===e)return;if(!WL(e))throw new Error(`Invalid AnnotationEditor mode: ${e}`);if(!this.pdfDocument)return;this.#ee(e);let{eventBus:o,pdfDocument:a}=this,u=async()=>{this.#X(),this.#i=e,await this.#r.updateMode(e,t,!0,i,r,s),!(e!==this.#i||a!==this.pdfDocument)&&o.dispatch("annotationeditormodechanged",{source:this,mode:e})};if(e===Gn.NONE||this.#i===Gn.NONE){let l=e!==Gn.NONE;l||this.pdfDocument.annotationStorage.resetModifiedIds(),this.cleanup();for(let h of this._pages)h.toggleEditingMode(l);let c=this.#F();if(l&&c){this.#X(),this.#C=new AbortController;let h=AbortSignal.any([this.#c.signal,this.#C.signal]);o._on("pagerendered",({pageNumber:f})=>{c.delete(f),c.size===0&&(this.#E=setTimeout(u,0))},{signal:h});return}}u()}refresh(e=!1,t=Object.create(null)){if(this.pdfDocument){for(let i of this._pages)i.update(t);this.#Q(),e||this.update()}}},m4=class extends Xl{_resetView(){super._resetView(),this._scrollMode=ct.PAGE,this._spreadMode=ki.NONE}set scrollMode(e){}_updateScrollMode(){}set spreadMode(e){}_updateSpreadMode(){}};globalThis.pdfjsViewer={AnnotationLayerBuilder:Sg,DownloadManager:K3,EventBus:Jl,FindState:ta,GenericL10n:Ql,LinkTarget:su,parseQueryString:kg,PDFFindController:wh,PDFHistory:Sh,PDFLinkService:Yl,PDFPageView:Rg,PDFScriptingManager:f4,PDFSinglePageViewer:m4,PDFViewer:Xl,ProgressBar:W3,RenderingStates:Lt,ScrollMode:ct,SimpleLinkService:Eh,SpreadMode:ki,StructTreeLayerBuilder:Pg,TextLayerBuilder:Mg,XfaLayerBuilder:Lg}});var rR,Og,sR=$n(()=>{_();rR="grab-to-pan-grab",Og=class{constructor(e){this.element=e.element,this.document=e.element.ownerDocument,typeof e.ignoreTarget=="function"&&(this.ignoreTarget=e.ignoreTarget),this.onActiveChanged=e.onActiveChanged,this.activate=this.activate.bind(this),this.deactivate=this.deactivate.bind(this),this.toggle=this.toggle.bind(this),this._onMouseDown=this.#e.bind(this),this._onMouseMove=this.#t.bind(this),this._endPan=this.#n.bind(this);let t=this.overlay=document.createElement("div");t.className="grab-to-pan-grabbing"}activate(){this.active||(this.active=!0,this.element.addEventListener("mousedown",this._onMouseDown,!0),this.element.classList.add(rR),this.onActiveChanged?.(!0))}deactivate(){this.active&&(this.active=!1,this.element.removeEventListener("mousedown",this._onMouseDown,!0),this._endPan(),this.element.classList.remove(rR),this.onActiveChanged?.(!1))}toggle(){this.active?this.deactivate():this.activate()}ignoreTarget(e){return e.matches("a[href], a[href] *, input, textarea, button, button *, select, option")}#e(e){if(e.button!==0||this.ignoreTarget(e.target))return;if(e.originalTarget)try{e.originalTarget.tagName}catch{return}this.scrollLeftStart=this.element.scrollLeft,this.scrollTopStart=this.element.scrollTop,this.clientXStart=e.clientX,this.clientYStart=e.clientY,this.document.addEventListener("mousemove",this._onMouseMove,!0),this.document.addEventListener("mouseup",this._endPan,!0),this.element.addEventListener("scroll",this._endPan,!0),e.preventDefault(),e.stopPropagation();let t=document.activeElement;t&&!t.contains(e.target)&&t.blur()}#t(e){if(this.element.removeEventListener("scroll",this._endPan,!0),!(e.buttons&1)){this._endPan();return}let t=e.clientX-this.clientXStart,i=e.clientY-this.clientYStart,r=this.scrollTopStart-i,s=this.scrollLeftStart-t;this.element.scrollTo?this.element.scrollTo({top:r,left:s,behavior:"instant"}):(this.element.scrollTop=r,this.element.scrollLeft=s),this.overlay.parentNode||document.body.append(this.overlay)}#n(){this.element.removeEventListener("scroll",this._endPan,!0),this.document.removeEventListener("mousemove",this._onMouseMove,!0),this.document.removeEventListener("mouseup",this._endPan,!0),this.overlay.remove()}}});var uR={};Ef(uR,{AnnotationEditorType:()=>Xe,PDFNavigator:()=>y4,ScaleType:()=>aR,ScrollMode:()=>ct,SpreadMode:()=>ki});var oR,aR,hi,y4,lR=$n(()=>{_();oR=Qe(eo());HA();dL();nR();yn();ui();sR();DA();aR=(t=>(t[t.Page=0]="Page",t[t.Width=1]="Width",t))(aR||{}),hi=class hi extends a1{constructor(t,i,r,s,o,a,u){super();this.isPDF=!0;this.pageNum=1;this.resourceIndex=0;this.pdfDoc=null;this._numPages=0;this._positionRestored=!1;this._pendingAnnotations=null;this.onResize=()=>{clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(()=>{if(this.pdfViewer){let t=this.pdfViewer.currentScaleValue;this.pdfViewer.currentScaleValue=t}},200)};this.settings=t,this.publication=i,this.api=r,this.workerSrc=s??`https://unpkg.com/pdfjs-dist@${R3}/build/pdf.worker.min.mjs`,this.annotator=o,this.initialLastReadingPosition=a,this.viewStore=u}static async create(t){let i=new this(t.settings,t.publication,t.api,t.workerSrc,t.annotator,t.initialLastReadingPosition,t.store);return await i.start(t.mainElement,t.headerMenu,t.footerMenu),i}async start(t,i,r){this.headerMenu=i,this.footerMenu=r,this.mainElement=t,this.resourceIndex=0,this.resource=this.publication.readingOrder[this.resourceIndex],po.workerSrc=this.workerSrc,this.wrapper=gt(this.mainElement,"#iframe-wrapper"),this.pdfContainer=gt(this.mainElement,"#pdf-container"),this.wrapper.style.position="absolute",this.wrapper.style.overflow="auto",this.wrapper.style.top="0",this.wrapper.style.left="0",this.wrapper.style.right="0",this.wrapper.style.bottom="0",this.pdfContainer.classList.add("pdfViewer"),this.handTool=new Og({element:this.wrapper}),this.eventBus=new Jl,this.linkService=new Yl({eventBus:this.eventBus}),this.findController=new wh({linkService:this.linkService,eventBus:this.eventBus}),this.pdfViewer=new Xl({container:this.wrapper,viewer:this.pdfContainer,eventBus:this.eventBus,linkService:this.linkService,findController:this.findController,textLayerMode:1,annotationMode:_s.ENABLE_STORAGE,annotationEditorMode:Xe.NONE,annotationEditorHighlightColors:"Yellow=#FFFF98,Green=#53FFBC,Blue=#80EBFF,Pink=#FFCBE6,Red=#FF4F5F"}),this.linkService.setViewer(this.pdfViewer),this.pdfViewer.spreadMode=ki.NONE,this.pdfHistory=new Sh({eventBus:this.eventBus,linkService:this.linkService}),this.linkService.setHistory(this.pdfHistory),this.eventBus.on("pagesinit",()=>{this.restoreViewSettings(),this.pdfViewer.currentPageNumber=this.pageNum}),this.eventBus.on("pagechanging",({pageNumber:o})=>{this.pageNum=o,this.saveLastReadingPosition(),this.atStart()?(this.api?.resourceAtStart?.(),this.emit("resource.start")):this.atEnd()&&(this.api?.resourceAtEnd?.(),this.emit("resource.end"))}),this.eventBus.on("pagesloaded",async({pagesCount:o})=>{this._numPages=o,this.hideLoading(),this.api?.resourceReady?.(),this.emit("resource.ready"),this._positionRestored||(this._positionRestored=!0,await this.restoreLastReadingPosition())}),this.eventBus.on("annotationeditorlayerrendered",async o=>{if(o.error||!this._pendingAnnotations)return;let a=o.pageNumber-1,u=this._pendingAnnotations.get(a);if(!u||u.length===0)return;this._pendingAnnotations.delete(a);let l=o.source?.annotationEditorLayer?.annotationEditorLayer;if(!l||!this.pdfDoc)return;let c=this.pdfDoc.annotationStorage,h=c.onSetModified;c.onSetModified=null;for(let f of u)try{let m=await l.deserialize(f);m&&l.addOrRebuild(m)}catch(m){console.warn("PDFNavigator: failed to restore annotation",f,m)}c.onSetModified=h,this.saveAnnotations(this.pdfDoc.fingerprints[0]??"")});let s=(0,oR.default)(()=>{this.pdfDoc&&this.saveAnnotations(this.pdfDoc.fingerprints[0]??"")},200);this.eventBus.on("annotationeditorstateschanged",s),this.showLoading(),await this.loadDocument(this.publication.getAbsoluteHref(this.resource.Href),1),te(window,"resize",this.onResize)}showLoading(){let t=document.getElementById("loadingpdf");if(t){t.style.display="flex";return}t=document.createElement("div"),t.id="loadingpdf",t.innerHTML=s1,Object.assign(t.style,{position:"absolute",inset:"0",display:"flex",zIndex:"100",alignItems:"center",justifyContent:"center",background:"white"}),t.className="loading is-loading",(this.wrapper.parentElement??document.body).appendChild(t)}hideLoading(){let t=document.getElementById("loadingpdf");t&&(t.style.display="none")}async loadDocument(t,i){this.showLoading(),this.pageNum=i,this.pdfDoc&&(this.pdfViewer.setDocument(null),this.linkService.setDocument(null),await this.pdfDoc.destroy(),this.pdfDoc=null);try{let s=await L3(t).promise;this.pdfDoc=s,this.pdfViewer.setDocument(s),this.linkService.setDocument(s),this.pdfHistory.initialize({fingerprint:s.fingerprints[0]??""}),this.restoreAnnotations(s.fingerprints[0]??""),s.annotationStorage.onSetModified=()=>{this.saveAnnotations(s.fingerprints[0]??"")}}catch(r){this.hideLoading();let s=r instanceof Error?r:new Error(String(r));console.error("PDFNavigator: failed to load document",t,s),this.api?.onError?.(s),this.emit("resource.error",s)}}readingOrder(){return this.publication.readingOrder}tableOfContents(){return this.publication.tableOfContents}landmarks(){return[]}pageList(){return[]}atStart(){return this.pageNum<=1&&this.resourceIndex===0}atEnd(){return this.resourceIndex>=this.publication.readingOrder.length-1&&this.pageNum>=(this.pdfDoc?.numPages??1)}currentResource(){return this.resourceIndex}totalResources(){return this.publication.readingOrder.length}currentLocator(){let t=this.pdfDoc?.numPages??this._numPages??1,i=t>1?(this.pageNum-1)/(t-1):0;return{href:this.resource?this.publication.getAbsoluteHref(this.resource.Href):"",title:`Page ${this.pageNum}`,locations:{position:this.pageNum,progression:i},type:"application/pdf"}}positions(){return this.publication.positions??[]}get numPages(){return this._numPages}nextPage(){if(this.pageNum>=(this.pdfDoc?.numPages??1)){this.nextResource();return}this.pdfViewer.nextPage()}previousPage(){if(this.pageNum<=1){this.previousResource();return}this.pdfViewer.previousPage()}nextResource(){this.resourceIndex>=this.publication.readingOrder.length-1||(this.resourceIndex++,this.resource=this.publication.readingOrder[this.resourceIndex],this.loadDocument(this.publication.getAbsoluteHref(this.resource.Href),1))}previousResource(){this.resourceIndex!==0&&(this.resourceIndex--,this.resource=this.publication.readingOrder[this.resourceIndex],this.loadDocument(this.publication.getAbsoluteHref(this.resource.Href),this.pdfDoc?.numPages??1))}goTo(t){if(typeof t.locations?.position=="number"){this.pdfViewer.currentPageNumber=t.locations.position;return}let i=t.href??"",r=this.pageFromHref(i)??1;if(i){let s=i.split("#")[0].split("?")[0],o=this.publication.readingOrder.findIndex(a=>{if(!a.Href)return!1;let u=this.publication.getAbsoluteHref(a.Href);return a.Href===s||u===s||u===this.toAbsoluteHref(s)});if(o>=0&&o!==this.resourceIndex){this.resourceIndex=o,this.resource=this.publication.readingOrder[this.resourceIndex],this.loadDocument(this.publication.getAbsoluteHref(this.resource.Href),r);return}}this.pdfViewer.currentPageNumber=r}pageFromHref(t){if(!t)return null;let i=t.match(/#page=(\d+)/i);if(i)return parseInt(i[1],10);try{let r=new URL(t,window.location.href);if(r.searchParams.has("start"))return parseInt(r.searchParams.get("start"),10);if(r.searchParams.has("page"))return parseInt(r.searchParams.get("page"),10)}catch{}return null}toAbsoluteHref(t){try{return new URL(t,window.location.href).href}catch{return t}}goToPosition(t){this.pdfViewer.currentPageNumber=t}async goToPage(t){this.pdfViewer.currentPageNumber=t}saveViewSetting(t,i){this.viewStore?.set(t,String(i))}restoreViewSettings(){let t=this.viewStore?.get(hi.KEY_SCROLL),i=this.viewStore?.get(hi.KEY_SPREAD),r=this.viewStore?.get(hi.KEY_SCALE),s=this.viewStore?.get(hi.KEY_ROTATE);this.pdfViewer.currentScaleValue=r??"page-fit",t!=null&&(this.pdfViewer.scrollMode=Number(t)),i!=null&&(this.pdfViewer.spreadMode=Number(i)),s!=null&&(this.pdfViewer.pagesRotation=Number(s))}annotationKey(t){return`pdf-ann-${t||this.resourceIndex}`}static toJsonSafe(t){if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))return Array.from(t);if(Array.isArray(t))return t.map(hi.toJsonSafe);if(t!==null&&typeof t=="object"){let i={};for(let[r,s]of Object.entries(t))i[r]=hi.toJsonSafe(s);return i}return t}saveAnnotations(t){if(!this.viewStore||!this.pdfDoc)return;let i=this.annotationKey(t),r={},{map:s}=this.pdfDoc.annotationStorage.serializable;if(s)for(let[o,a]of s)a.bitmap||(r[o]=hi.toJsonSafe(a));if(this._pendingAnnotations){let o=0;for(let[a,u]of this._pendingAnnotations)for(let l of u)r[`_pending_p${a}_${o++}`]=l}Object.keys(r).length===0?this.viewStore.remove(i):this.viewStore.set(i,JSON.stringify(r))}restoreAnnotations(t){if(this._pendingAnnotations=null,!this.viewStore)return;let i=this.annotationKey(t),r=this.viewStore.get(i);if(r)try{let s=JSON.parse(r),o=new Map;for(let a of Object.values(s)){let u=a,l=u.pageIndex??0;o.has(l)||o.set(l,[]),o.get(l).push(u)}this._pendingAnnotations=o}catch{}}fitToWidth(){this.pdfViewer.currentScaleValue="page-width",this.saveViewSetting(hi.KEY_SCALE,"page-width")}fitToPage(){this.pdfViewer.currentScaleValue="page-fit",this.saveViewSetting(hi.KEY_SCALE,"page-fit")}zoomIn(){this.pdfViewer.increaseScale(),this.saveViewSetting(hi.KEY_SCALE,this.pdfViewer.currentScaleValue)}zoomOut(){this.pdfViewer.decreaseScale(),this.saveViewSetting(hi.KEY_SCALE,this.pdfViewer.currentScaleValue)}rotateCw(){this.pdfViewer.pagesRotation=(this.pdfViewer.pagesRotation+90)%360,this.saveViewSetting(hi.KEY_ROTATE,this.pdfViewer.pagesRotation)}rotateCcw(){this.pdfViewer.pagesRotation=(this.pdfViewer.pagesRotation+270)%360,this.saveViewSetting(hi.KEY_ROTATE,this.pdfViewer.pagesRotation)}setSpreadMode(t){this.pdfViewer.spreadMode=t,this.saveViewSetting(hi.KEY_SPREAD,t)}setAnnotationEditorMode(t){this.pdfViewer.annotationEditorMode={mode:t}}get annotationStorage(){return this.pdfDoc?.annotationStorage}getAllAnnotations(){let t=[],{map:i}=this.pdfDoc?.annotationStorage.serializable??{};if(i)for(let r of i.values())t.push(hi.toJsonSafe(r));if(this._pendingAnnotations)for(let r of this._pendingAnnotations.values())for(let s of r)t.push(s);return t.sort((r,s)=>(r.pageIndex??0)-(s.pageIndex??0)),t}clearAnnotations(){if(!this.pdfDoc)return;let t=this.pdfDoc.annotationStorage,{map:i}=t.serializable;if(i)for(let r of i.keys())t.remove(r);this.viewStore&&this.pdfDoc.fingerprints[0]&&this.viewStore.remove(this.annotationKey(this.pdfDoc.fingerprints[0]))}makeBookmark(){return{id:crypto.randomUUID(),href:this.resource?this.publication.getAbsoluteHref(this.resource.Href):"",locations:{position:this.pageNum},type:"application/pdf",title:`Page ${this.pageNum}`,created:new Date}}saveBookmark(){return!this.annotator||this.isCurrentPageBookmarked()?null:this.annotator.saveBookmark(this.makeBookmark())}deleteBookmark(t){this.annotator?.deleteBookmark(t)}getBookmarks(){return!this.annotator||!this.resource?[]:this.annotator.getBookmarks(this.publication.getAbsoluteHref(this.resource.Href))}isCurrentPageBookmarked(){return this.getBookmarks().some(t=>t.locations?.position===this.pageNum)}activateHand(){this.handTool.activate()}deactivateHand(){this.handTool.deactivate()}async scroll(t,i){let r=t?i==="horizontal"?ct.HORIZONTAL:i==="wrapped"?ct.WRAPPED:ct.VERTICAL:ct.PAGE;this.pdfViewer.scrollMode=r,this.saveViewSetting(hi.KEY_SCROLL,r)}find(t,i){this.eventBus.dispatch("find",{query:t,caseSensitive:i?.caseSensitive??!1,highlightAll:i?.highlightAll??!0,findPrevious:i?.findPrevious??!1,type:""})}findNext(){this.eventBus.dispatch("find",{query:this.findController.state?.query??"",caseSensitive:!1,highlightAll:!0,findPrevious:!1,type:"again"})}findPrevious(){this.eventBus.dispatch("find",{query:this.findController.state?.query??"",caseSensitive:!1,highlightAll:!0,findPrevious:!0,type:"again"})}saveLastReadingPosition(){if(!this.annotator||!this.resource)return;let t={href:this.publication.getAbsoluteHref(this.resource.Href),locations:{position:this.pageNum},type:"application/pdf",created:new Date};this.api?.updateCurrentLocation?this.api.updateCurrentLocation(t).then(()=>{this.annotator.saveLastReadingPosition(t)}):this.annotator.saveLastReadingPosition(t)}async restoreLastReadingPosition(){if(this.initialLastReadingPosition&&this.annotator?.initLastReadingPosition(this.initialLastReadingPosition),!this.annotator)return;let t=this.annotator.getLastReadingPosition();if(!t)return;let i=t.locations?.position??1,r=this.publication.readingOrder.findIndex(s=>s.Href&&this.publication.getAbsoluteHref(s.Href)===t.href);r>=0&&r!==this.resourceIndex?(this.resourceIndex=r,this.resource=this.publication.readingOrder[this.resourceIndex],await this.loadDocument(this.publication.getAbsoluteHref(this.resource.Href),i)):this.pdfViewer.currentPageNumber=i}stop(){Se(window,"resize",this.onResize),this.pdfViewer?.setDocument(null),this.pdfDoc?.destroy(),this.pdfDoc=null}};hi.KEY_SCROLL="pdf-scroll-mode",hi.KEY_SPREAD="pdf-spread-mode",hi.KEY_SCALE="pdf-scale-value",hi.KEY_ROTATE="pdf-rotation";y4=hi});var jee={};Ef(jee,{AnnotationMarker:()=>vs,Link:()=>Rl,default:()=>Hee,load:()=>Uee});_();_();_();var GS=Qe(US()),WS=Qe(Ji());_();var jS=Qe(Ji());function Sa(n,e){return jS.TaJson.deserialize(n,e)}var zs=class extends GS.Publication{static async fromUrl(e,t){let r=await(await fetch(e.href,t)).json(),s=Sa(r,zs);return s.manifestUrl=e,s}get readingOrder(){return this.Spine??[]}get resources(){return this.Resources??[]}get tableOfContents(){return this.sample?.isSampleRead&&this.positions?.length>0?this.limitedTOC():this.TOC||[]}limitedTOC(){function e(i){for(let r=0;r<(i.Children?.length??0);r++){let s=i.Children[r];s.Href=void 0,s.Children&&e(s)}}return this.TOC?.map(i=>{if(i.Href){let r=this.positionsByHref(this.getRelativeHref(i.Href));if(r?.length>0){let s=r[0],o=Math.round((s.locations.totalProgression?s.locations.totalProgression:0)*100);this.sample?.limit&&(o<=this.sample?.limit||(i.Href=void 0,i.Children&&e(i)))}}return i})||[]}get landmarks(){return this.Landmarks}get pageList(){return this.PageList}get isFixedLayout(){return this.Metadata.Rendition?.Layout==="fixed"}get isReflowable(){return!this.isFixedLayout}get layout(){return this.isFixedLayout?"fixed":"reflowable"}get hasMediaOverlays(){return this.readingOrder?this.readingOrder.filter(e=>e.Properties?.MediaOverlay).length>0:!1}getStartLink(){if(this.readingOrder!==void 0&&this.readingOrder.length>0)return this.readingOrder[0]}getPreviousSpineItem(e){let t=this.getSpineIndex(e);if(t!==void 0&&this.readingOrder!==void 0&&t>0)return this.readingOrder[t-1]}getNextSpineItem(e){let t=this.getSpineIndex(e);if(t!==void 0&&this.readingOrder!==void 0&&t<this.readingOrder.length-1)return this.readingOrder[t+1]}getSpineItem(e){let t=this.getSpineIndex(e);if(t!==void 0&&this.readingOrder!==void 0)return this.readingOrder[t]}getSpineIndex(e){return this.readingOrder?.findIndex(t=>t.Href&&this.getAbsoluteHref(t.Href)===e)}getAbsoluteHref(e){return new URL(e,this.manifestUrl.href).href}getRelativeHref(e){let t=this.manifestUrl.href.replace("/manifest.json",""),i=e.replace(t,"");return i.indexOf("#")>0&&(i=i.slice(0,i.indexOf("#"))),i.charAt(0)==="/"&&(i=i.substring(1)),i}getTOCItemAbsolute(e){let t=this.getAbsoluteHref(e),i=(s,o)=>{for(let a=0;a<o.length;a++){let u=o[a];if(u.Href){let l=u.Href.indexOf("#")!==-1?u.Href.slice(0,u.Href.indexOf("#")):u.Href;if(this.getAbsoluteHref(l)===s)return u}if(u.Children){let l=i(s,u.Children);if(l!==void 0)return l}}},r=i(t,this.tableOfContents);return r===void 0&&this.readingOrder!==void 0&&(r=i(t,this.readingOrder)),r}getTOCItem(e){let t=(r,s)=>{for(let o=0;o<s.length;o++){let a=s[o];if(a.Href&&this.getAbsoluteHref(a.Href)===r)return a;if(a.Children){let u=t(r,a.Children);if(u!==void 0)return u}}},i=t(e,this.tableOfContents);if(i===void 0&&this.readingOrder!==void 0&&(i=t(e,this.readingOrder)),i===void 0&&e.indexOf("#")!==-1){let r=e.slice(0,e.indexOf("#"));i=t(r,this.tableOfContents),i===void 0&&this.readingOrder!==void 0&&(i=t(r,this.readingOrder))}return i}positionsByHref(e){let t=decodeURI(e)??"";return this.positions?.filter(i=>t.includes(i.href))}async autoGeneratePositions(e,t=VW){let i=0,r=0,s=[];if(this.readingOrder!==void 0)for(let a of this.readingOrder)if(this.isFixedLayout){let u={href:a.Href,locations:{progression:0,position:i+1},type:a.TypeLink};s.push(u),i=i+1}else{let u=this.getAbsoluteHref(a.Href),l=await t(u,e);a.contentLength=l,r+=l;let h=Math.max(1,Math.ceil(l/1024));for(let f=0;f<h;f++){let m={href:a.Href,locations:{progression:f/h,position:i+(f+1)},type:a.TypeLink};s.push(m)}i=i+h}var o=0;if(this.isReflowable&&this.readingOrder!==void 0)for(let a of this.readingOrder){if(!a.contentLength){console.error("Link is missing contentLength",a);return}a.contentWeight=100/r*a.contentLength,o=o+a.contentWeight}for(let a of s){let u=s.filter(c=>c.href===decodeURI(a.href)),l=Math.ceil((a.locations.progression?a.locations.progression:0)*(u.length-1));a.locations.position&&(a.locations.totalProgression=(a.locations.position-1)/s.length),a.locations.remainingPositions=Math.abs(l-(u.length-1)),a.locations.position&&(a.locations.totalRemainingPositions=Math.abs(a.locations.position-1-(s.length-1)))}this.positions=s}async fetchPositionsFromService(e,t){let r=await(await fetch(e,t)).json();this.positions=r.positions}async fetchWeightsFromService(e,t){if(this.isFixedLayout){console.warn("Not fetching weights from service for fixed layout publication.");return}let r=await(await fetch(e,t)).json();this.readingOrder!==void 0&&this.readingOrder.forEach(s=>{s.contentWeight=r[s.Href]})}};zs=Cf([(0,WS.JsonObject)()],zs);var VW=async(n,e)=>(await(await fetch(n,e)).blob()).size;_();_();var _a=class{json(){return JSON.stringify(this)}},ab=class extends _a{constructor(e,t,i){super(),this.value=e,this.ref=t,this.name=i}toString(){return this.value}},ub=class extends _a{constructor(e,t,i){super(),this.value=e,this.ref=t,this.name=i}toString(){return this.value}toJson(){return JSON.parse(this.value)}},lb=class extends _a{constructor(e,t,i,r){super(),this.value=e,this.values=t,this.ref=i,this.name=r}toString(){return this.values[this.value]}},cb=class extends _a{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)}},ju=class extends _a{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}},ds=class{constructor(){this.properties=[]}addIncremental(e,t,i,r,s,o,a){this.properties.push(new cb(e,t,i,r,s,o,a))}addStringable(e,t,i){this.properties.push(new ab(e,t,i))}addJSONable(e,t,i){this.properties.push(new ub(e,t,i))}addSwitchable(e,t,i,r,s){this.properties.push(new ju(e,t,i,r,s))}addEnumerable(e,t,i,r){this.properties.push(new lb(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}};_();var Fe=class Fe{};Fe.FONT_SIZE_REF="fontSize",Fe.FONT_FAMILY_REF="fontFamily",Fe.FONT_OVERRIDE_REF="fontOverride",Fe.APPEARANCE_REF="appearance",Fe.SCROLL_REF="scroll",Fe.ADVANCED_SETTINGS_REF="advancedSettings",Fe.TEXT_ALIGNMENT_REF="textAlign",Fe.COLUMN_COUNT_REF="colCount",Fe.DIRECTION_REF="direction",Fe.WORD_SPACING_REF="wordSpacing",Fe.LETTER_SPACING_REF="letterSpacing",Fe.PAGE_MARGINS_REF="pageMargins",Fe.LINE_HEIGHT_REF="lineHeight",Fe.BODY_HYPHENS_REF="bodyHyphens",Fe.PARA_SPACING_REF="paraSpacing",Fe.PARA_INDENT_REF="paraIndent",Fe.TYPE_SCALE_REF="typeScale",Fe.BACKGROUND_COLOR_REF="backgroundColor",Fe.TEXT_COLOR_REF="textColor",Fe.FONT_SIZE_KEY="--USER__"+Fe.FONT_SIZE_REF,Fe.FONT_FAMILY_KEY="--USER__"+Fe.FONT_FAMILY_REF,Fe.FONT_OVERRIDE_KEY="--USER__"+Fe.FONT_OVERRIDE_REF,Fe.APPEARANCE_KEY="--USER__"+Fe.APPEARANCE_REF,Fe.SCROLL_KEY="--USER__"+Fe.SCROLL_REF,Fe.ADVANCED_SETTINGS_KEY="--USER__"+Fe.ADVANCED_SETTINGS_REF,Fe.TEXT_ALIGNMENT_KEY="--USER__"+Fe.TEXT_ALIGNMENT_REF,Fe.COLUMN_COUNT_KEY="--USER__"+Fe.COLUMN_COUNT_REF,Fe.DIRECTION_KEY="--USER__"+Fe.DIRECTION_REF,Fe.WORD_SPACING_KEY="--USER__"+Fe.WORD_SPACING_REF,Fe.LETTER_SPACING_KEY="--USER__"+Fe.LETTER_SPACING_REF,Fe.PAGE_MARGINS_KEY="--USER__"+Fe.PAGE_MARGINS_REF,Fe.LINE_HEIGHT_KEY="--USER__"+Fe.LINE_HEIGHT_REF,Fe.BODY_HYPHENS_KEY="--USER__"+Fe.BODY_HYPHENS_REF,Fe.PARA_SPACING_KEY="--USER__"+Fe.PARA_SPACING_REF,Fe.PARA_INDENT_KEY="--USER__"+Fe.PARA_INDENT_REF,Fe.TYPE_SCALE_KEY="--USER__"+Fe.TYPE_SCALE_REF,Fe.BACKGROUND_COLOR_KEY="--USER__"+Fe.BACKGROUND_COLOR_REF,Fe.TEXT_COLOR_KEY="--USER__"+Fe.TEXT_COLOR_REF;var W=Fe;ui();yn();_();ui();_();ui();function K7(){return gt(document,"#iframe-wrapper").clientWidth}function zr(){return gt(document,"#iframe-wrapper").clientHeight}var q7=Qe(eo()),md=class{constructor(e){this.layout="reflowable";this.USERSETTINGS="userSetting";this.sideMargin=20;this.height=0;this.attributes={margin:0};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=Pi(t,"head");if(i){let s=ge(i,"meta[name=viewport]");s&&s.remove()}let r=Pi(t,"html");r&&r.style.setProperty("--USER__scroll","readium-scroll-on")}this.setSize(),this.setIframeHeight(this.iframe)}else{this.height=zr()-40-this.attributes.margin,this.name="readium-scroll-off",this.label="Paginated",this.checkForFixedScrollWidth();let t=this.iframe.contentDocument;if(t){let i=Pi(t,"html");i&&i.style.setProperty("--USER__scroll","readium-scroll-off")}this.setSize(),this.padOddColumns()}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate()}start(){if(this.scrollMode){let e=this.iframe.contentDocument;if(e){let t=Pi(e,"head");if(t){let i=ge(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=Pi(this.iframe.contentDocument,"body"),i=Array.prototype.slice.call(t.querySelectorAll("img"));for(let r of i)r.style.maxWidth=""}}getCurrentPosition(){let e=gt(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=gt(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.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(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.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)}}atStart(){return this.scrollMode?gt(document,"#iframe-wrapper").scrollTop===0:this.getLeftColumnsWidth()<=0}atEnd(){if(this.scrollMode){let e=gt(document,"#iframe-wrapper");return Math.ceil(this.scrollingElement.scrollHeight-e.scrollTop)-1<=zr()}else{let e=Math.floor(this.getRightColumnsWidth());return e<=0?!0:this.iframe.contentDocument?.getElementById("r2d2bc-column-spacer")?e<=5:Math.ceil(this.getCurrentPage())===this.getPageCount()}}goToPreviousPage(){let e=gt(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.navigator.checkResourcePosition()}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate()}goToNextPage(){let e=gt(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.navigator.checkResourcePosition()}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate()}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=Pi(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=Pi(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 gt(document,"#iframe-wrapper").clientHeight}setIframeHeight(e){(0,q7.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=zr()-this.attributes.margin;i.height=Math.max(a,o)+"px"}}},200)(e)}checkForFixedScrollWidth(){let e=this.iframe.contentDocument;if(e){let t=Pi(e,"body"),i=t?.scrollWidth;this.hasFixedScrollWidth=t?.scrollWidth===i}}setSize(){if(this.iframe.width=K7()+"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();if(r%s>s*.25){let a=e.createElement("div");return a.id="r2d2bc-column-spacer",a.style.breakBefore="column",a.style.height="100%",a.style.visibility="hidden",i.appendChild(a),i.scrollWidth,!0}return!1}};_();ui();var bd=class{constructor(){this.layout="fixed";this.sideMargin=20;this.height=0;this.attributes={margin:0}}start(){}stop(){}getCurrentPosition(){return 0}getScreenHeight(){return gt(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 On=Qe(Qt()),at=class at{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.settingsChangeCallback=()=>{};this.settingsColumnsChangeCallback=()=>{};this.viewChangeCallback=()=>{};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",W.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(W.SCROLL_REF);r&&(r.value=t.verticalScroll,await t.saveProperty(r)),On.default.log(t.verticalScroll)}if(i.appearance){t.appearance=at.parseAppearanceSetting(i.appearance);let r=t.userProperties.getByRef(W.APPEARANCE_REF);r&&(r.value=t.appearance,await t.saveProperty(r)),On.default.log(t.appearance)}if(i.fontSize){t.fontSize=i.fontSize;let r=t.userProperties.getByRef(W.FONT_SIZE_REF);r&&(r.value=t.fontSize,await t.saveProperty(r)),On.default.log(t.fontSize)}if(i.fontFamily){t.fontFamily=at.fontFamilyValues.findIndex(s=>s===i.fontFamily);let r=t.userProperties.getByRef(W.FONT_FAMILY_REF);r&&(r.value=t.fontFamily,await t.saveProperty(r)),On.default.log(t.fontFamily),t.fontFamily!==0&&(t.fontOverride=!0)}if(i.textAlignment){t.textAlignment=at.textAlignmentValues.findIndex(s=>s===i.textAlignment);let r=t.userProperties.getByRef(W.TEXT_ALIGNMENT_REF);r&&(r.value=t.textAlignment,await t.saveProperty(r)),On.default.log(t.textAlignment)}if(i.columnCount){t.columnCount=at.columnCountValues.findIndex(s=>s===i.columnCount);let r=t.userProperties.getByRef(W.COLUMN_COUNT_REF);r&&(r.value=t.columnCount,await t.saveProperty(r)),On.default.log(t.columnCount)}if(i.direction){t.direction=at.directionValues.findIndex(s=>s===i.direction);let r=t.userProperties.getByRef(W.DIRECTION_REF);r&&(r.value=t.direction,await t.saveProperty(r)),On.default.log(t.direction)}if(i.wordSpacing){t.wordSpacing=i.wordSpacing;let r=t.userProperties.getByRef(W.WORD_SPACING_REF);r&&(r.value=t.wordSpacing,await t.saveProperty(r)),On.default.log(t.wordSpacing)}if(i.letterSpacing){t.letterSpacing=i.letterSpacing;let r=t.userProperties.getByRef(W.LETTER_SPACING_REF);r&&(r.value=t.letterSpacing,await t.saveProperty(r)),On.default.log(t.letterSpacing)}if(i.pageMargins){t.pageMargins=i.pageMargins;let r=t.userProperties.getByRef(W.PAGE_MARGINS_REF);r&&(r.value=t.pageMargins,await t.saveProperty(r)),On.default.log(t.pageMargins)}if(i.lineHeight){t.lineHeight=i.lineHeight;let r=t.userProperties.getByRef(W.LINE_HEIGHT_REF);r&&(r.value=t.lineHeight,await t.saveProperty(r)),On.default.log(t.lineHeight)}if(i.bodyHyphens!==void 0){t.bodyHyphens=i.bodyHyphens;let r=t.userProperties.getByRef(W.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(W.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(W.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(W.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(W.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(W.TEXT_COLOR_REF);r&&(r.value=t.textColor,await t.saveProperty(r))}t.userProperties=t.getUserSettings(),await t.initialise()}return await t.initializeSelections(),new Promise(i=>i(t))}stop(){On.default.log("book settings stop")}async initialise(){this.appearance=await this.getPropertyAndFallback("appearance",W.APPEARANCE_KEY),this.verticalScroll=await this.getPropertyAndFallback("verticalScroll",W.SCROLL_KEY),this.fontFamily=await this.getPropertyAndFallback("fontFamily",W.FONT_FAMILY_KEY),this.fontFamily!==0&&(this.fontOverride=!0),this.textAlignment=await this.getPropertyAndFallback("textAlignment",W.TEXT_ALIGNMENT_KEY),this.columnCount=await this.getPropertyAndFallback("columnCount",W.COLUMN_COUNT_KEY),this.direction=await this.getPropertyAndFallback("direction",W.DIRECTION_KEY),this.fontSize=await this.getPropertyAndFallback("fontSize",W.FONT_SIZE_KEY),this.wordSpacing=await this.getPropertyAndFallback("wordSpacing",W.WORD_SPACING_KEY),this.letterSpacing=await this.getPropertyAndFallback("letterSpacing",W.LETTER_SPACING_KEY),this.pageMargins=await this.getPropertyAndFallback("pageMargins",W.PAGE_MARGINS_KEY),this.lineHeight=await this.getPropertyAndFallback("lineHeight",W.LINE_HEIGHT_KEY),this.bodyHyphens=await this.getPropertyAndFallback("bodyHyphens",W.BODY_HYPHENS_KEY),this.paraSpacing=await this.getPropertyAndFallback("paraSpacing",W.PARA_SPACING_KEY),this.paraIndent=await this.getPropertyAndFallback("paraIndent",W.PARA_INDENT_KEY),this.typeScale=await this.getPropertyAndFallback("typeScale",W.TYPE_SCALE_KEY),this.backgroundColor=await this.getPropertyAndFallback("backgroundColor",W.BACKGROUND_COLOR_KEY),this.textColor=await this.getPropertyAndFallback("textColor",W.TEXT_COLOR_KEY),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=Pi(e,"html");if(t){let i=ge(document,"#root")||document.documentElement,r=ge(t,"body");t.style.removeProperty(W.FONT_SIZE_KEY),t.style.removeProperty(W.WORD_SPACING_KEY),t.style.removeProperty(W.LETTER_SPACING_KEY),t.style.removeProperty(W.COLUMN_COUNT_KEY),t.style.removeProperty(W.DIRECTION_KEY),t.style.removeProperty(W.TEXT_ALIGNMENT_KEY),t.style.removeProperty(W.LINE_HEIGHT_KEY),t.style.removeProperty(W.PAGE_MARGINS_KEY),t.style.removeProperty(W.BODY_HYPHENS_KEY),t.style.removeProperty(W.PARA_SPACING_KEY),t.style.removeProperty(W.PARA_INDENT_KEY),t.style.removeProperty(W.TYPE_SCALE_KEY),t.style.removeProperty(W.BACKGROUND_COLOR_KEY),t.style.removeProperty(W.TEXT_COLOR_KEY),t.style.removeProperty(W.APPEARANCE_KEY),i&&en(i,"data-viewer-theme","day"),r&&en(r,"data-viewer-theme","day"),t.style.removeProperty(W.FONT_FAMILY_KEY),en(t,"data-viewer-font","publisher"),t.style.setProperty(W.FONT_OVERRIDE_KEY,"readium-font-off")}}}async initializeSelections(){this.headerMenu&&(this.settingsView=ge(this.headerMenu,"#container-view-settings"))}async applyProperties(){this.userProperties=this.getUserSettings();let e=this.iframe.contentDocument;if(e){let t=Pi(e,"html");if(t){let i=ge(document,"#root")||document.documentElement,r=ge(t,"body");if(this.view?.navigator.publication.isReflowable&&(await this.getProperty(W.FONT_SIZE_KEY)&&t.style.setProperty(W.FONT_SIZE_KEY,this.userProperties.getByRef(W.FONT_SIZE_REF)?.toString()??null),await this.getProperty(W.WORD_SPACING_KEY)&&t.style.setProperty(W.WORD_SPACING_KEY,this.userProperties.getByRef(W.WORD_SPACING_REF)?.toString()??null),await this.getProperty(W.LETTER_SPACING_KEY)&&t.style.setProperty(W.LETTER_SPACING_KEY,this.userProperties.getByRef(W.LETTER_SPACING_REF)?.toString()??null)),await this.getProperty(W.COLUMN_COUNT_KEY)&&t.style.setProperty(W.COLUMN_COUNT_KEY,this.userProperties.getByRef(W.COLUMN_COUNT_REF)?.toString()??null),this.view?.navigator.publication.isReflowable&&(await this.getProperty(W.TEXT_ALIGNMENT_KEY)&&(this.userProperties.getByRef(W.TEXT_ALIGNMENT_REF)?.toString()==="auto"?t.style.removeProperty(W.TEXT_ALIGNMENT_KEY):t.style.setProperty(W.TEXT_ALIGNMENT_KEY,this.userProperties.getByRef(W.TEXT_ALIGNMENT_REF)?.toString()??null)),await this.getProperty(W.LINE_HEIGHT_KEY)&&t.style.setProperty(W.LINE_HEIGHT_KEY,this.userProperties.getByRef(W.LINE_HEIGHT_REF)?.toString()??null),await this.getProperty(W.PAGE_MARGINS_KEY)&&t.style.setProperty(W.PAGE_MARGINS_KEY,this.userProperties.getByRef(W.PAGE_MARGINS_REF)?.toString()??null),await this.getProperty(W.BODY_HYPHENS_KEY)&&t.style.setProperty(W.BODY_HYPHENS_KEY,this.userProperties.getByRef(W.BODY_HYPHENS_REF)?.toString()??null),await this.getProperty(W.PARA_SPACING_KEY)&&t.style.setProperty(W.PARA_SPACING_KEY,this.userProperties.getByRef(W.PARA_SPACING_REF)?.toString()??null),await this.getProperty(W.PARA_INDENT_KEY)&&t.style.setProperty(W.PARA_INDENT_KEY,this.userProperties.getByRef(W.PARA_INDENT_REF)?.toString()??null),await this.getProperty(W.TYPE_SCALE_KEY)&&t.style.setProperty(W.TYPE_SCALE_KEY,this.userProperties.getByRef(W.TYPE_SCALE_REF)?.toString()??null),await this.getProperty(W.BACKGROUND_COLOR_KEY)&&t.style.setProperty(W.BACKGROUND_COLOR_KEY,this.userProperties.getByRef(W.BACKGROUND_COLOR_REF)?.toString()??null),await this.getProperty(W.TEXT_COLOR_KEY)&&t.style.setProperty(W.TEXT_COLOR_KEY,this.userProperties.getByRef(W.TEXT_COLOR_REF)?.toString()??null)),await this.getProperty(W.APPEARANCE_KEY)?(t.style.setProperty(W.APPEARANCE_KEY,this.userProperties.getByRef(W.APPEARANCE_REF)?.toString()??null),this.userProperties.getByRef(W.APPEARANCE_REF)?.value===0?(i&&en(i,"data-viewer-theme","day"),r&&en(r,"data-viewer-theme","day")):this.userProperties.getByRef(W.APPEARANCE_REF)?.value===1?(i&&en(i,"data-viewer-theme","sepia"),r&&en(r,"data-viewer-theme","sepia")):this.userProperties.getByRef(W.APPEARANCE_REF)?.value===2&&(i&&en(i,"data-viewer-theme","night"),r&&en(r,"data-viewer-theme","night"))):(t.style.setProperty(W.APPEARANCE_KEY,this.userProperties.getByRef(W.APPEARANCE_REF)?.toString()??null),i&&en(i,"data-viewer-theme","day"),r&&en(r,"data-viewer-theme","day")),this.view?.navigator.publication.isFixedLayout&&await this.getProperty(W.DIRECTION_KEY)){let s=this.userProperties.getByRef(W.DIRECTION_REF)?.toString()??null;t.style.setProperty(W.DIRECTION_KEY,s),this.view.navigator.setDirection(s)}if(this.view?.navigator.publication.isReflowable){if(await this.getProperty(W.FONT_FAMILY_KEY))if(t.style.setProperty(W.FONT_FAMILY_KEY,this.userProperties.getByRef(W.FONT_FAMILY_REF)?.toString()??null),this.userProperties.getByRef(W.FONT_FAMILY_REF)?.value===0)en(t,"data-viewer-font","publisher"),t.style.setProperty(W.FONT_OVERRIDE_KEY,"readium-font-off");else if(this.userProperties.getByRef(W.FONT_FAMILY_REF)?.value===1)en(t,"data-viewer-font","serif"),t.style.setProperty(W.FONT_OVERRIDE_KEY,"readium-font-on");else if(this.userProperties.getByRef(W.FONT_FAMILY_REF)?.value===2)en(t,"data-viewer-font","sans"),t.style.setProperty(W.FONT_OVERRIDE_KEY,"readium-font-on");else{let s=this.userProperties.getByRef(W.FONT_FAMILY_REF);s&&en(t,"data-viewer-font",s.toString()),t.style.setProperty(W.FONT_OVERRIDE_KEY,"readium-font-on")}else t.style.setProperty(W.FONT_FAMILY_KEY,this.userProperties.getByRef(W.FONT_FAMILY_REF)?.toString()??null),en(t,"data-viewer-font","publisher"),t.style.setProperty(W.FONT_OVERRIDE_KEY,"readium-font-off");await this.getProperty(W.SCROLL_KEY)?this.userProperties.getByRef(W.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&&at.renderControls(this.settingsView)}static renderControls(e){te(ge(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){at.appearanceValues.includes(e)||at.appearanceValues.push(e)}initAddedAppearance(){this.applyProperties()}addFont(e){at.fontFamilyValues.includes(e)||at.fontFamilyValues.push(e)}initAddedFont(){this.applyProperties()}async updateUserSettings(){let e={fontFamily:at.fontFamilyValues[await this.userProperties?.getByRef(W.FONT_FAMILY_REF)?.value],fontSize:this.userProperties?.getByRef(W.FONT_SIZE_REF)?.value,appearance:at.appearanceValues[await this.userProperties?.getByRef(W.APPEARANCE_REF)?.value],textAlignment:at.textAlignmentValues[await this.userProperties?.getByRef(W.TEXT_ALIGNMENT_REF)?.value],columnCount:at.columnCountValues[await this.userProperties?.getByRef(W.COLUMN_COUNT_REF)?.value],direction:at.directionValues[await this.userProperties?.getByRef(W.DIRECTION_REF)?.value],wordSpacing:this.userProperties?.getByRef(W.WORD_SPACING_REF)?.value,letterSpacing:this.userProperties?.getByRef(W.LETTER_SPACING_REF)?.value,verticalScroll:this.userProperties?.getByRef(W.SCROLL_REF)?.value,bodyHyphens:this.userProperties?.getByRef(W.BODY_HYPHENS_REF)?.value,paraSpacing:this.userProperties?.getByRef(W.PARA_SPACING_REF)?.value,paraIndent:this.userProperties?.getByRef(W.PARA_INDENT_REF)?.value,typeScale:this.userProperties?.getByRef(W.TYPE_SCALE_REF)?.value,backgroundColor:this.userProperties?.getByRef(W.BACKGROUND_COLOR_REF)?.value,textColor:this.userProperties?.getByRef(W.TEXT_COLOR_REF)?.value};this.api?.updateSettings&&this.api?.updateSettings(e).then(t=>{On.default.log("api updated user settings",JSON.stringify(e))})}getUserSettings(){let e=new ds;return e.addSwitchable("readium-font-on","readium-font-off",this.fontOverride,W.FONT_OVERRIDE_REF,W.FONT_OVERRIDE_KEY),e.addEnumerable(this.columnCount,at.columnCountValues,W.COLUMN_COUNT_REF,W.COLUMN_COUNT_KEY),e.addEnumerable(this.direction,at.directionValues,W.DIRECTION_REF,W.DIRECTION_KEY),e.addEnumerable(this.appearance,at.appearanceValues,W.APPEARANCE_REF,W.APPEARANCE_KEY),e.addIncremental(this.pageMargins,.5,4,.25,"",W.PAGE_MARGINS_REF,W.PAGE_MARGINS_KEY),e.addEnumerable(this.textAlignment,at.textAlignmentValues,W.TEXT_ALIGNMENT_REF,W.TEXT_ALIGNMENT_KEY),e.addEnumerable(this.fontFamily,at.fontFamilyValues,W.FONT_FAMILY_REF,W.FONT_FAMILY_KEY),e.addIncremental(this.fontSize,100,300,25,"%",W.FONT_SIZE_REF,W.FONT_SIZE_KEY),e.addIncremental(this.lineHeight,1,2,.25,"em",W.LINE_HEIGHT_REF,W.LINE_HEIGHT_KEY),e.addIncremental(this.wordSpacing,0,1,.25,"rem",W.WORD_SPACING_REF,W.WORD_SPACING_KEY),e.addIncremental(this.letterSpacing,0,.5,.0625,"em",W.LETTER_SPACING_REF,W.LETTER_SPACING_KEY),e.addSwitchable("readium-scroll-on","readium-scroll-off",this.verticalScroll,W.SCROLL_REF,W.SCROLL_KEY),e.addSwitchable("auto","none",this.bodyHyphens,W.BODY_HYPHENS_REF,W.BODY_HYPHENS_KEY),e.addIncremental(this.paraSpacing,0,3,.5,"rem",W.PARA_SPACING_REF,W.PARA_SPACING_KEY),e.addIncremental(this.paraIndent,0,3,.5,"em",W.PARA_INDENT_REF,W.PARA_INDENT_KEY),e.addIncremental(this.typeScale,1,1.5,.1,"",W.TYPE_SCALE_REF,W.TYPE_SCALE_KEY),e.addStringable(this.backgroundColor,W.BACKGROUND_COLOR_REF,W.BACKGROUND_COLOR_KEY),e.addStringable(this.textColor,W.TEXT_COLOR_REF,W.TEXT_COLOR_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:at.appearanceValues[this.userProperties?.getByRef(W.APPEARANCE_REF)?.value],fontFamily:at.fontFamilyValues[this.userProperties?.getByRef(W.FONT_FAMILY_REF)?.value],textAlignment:at.textAlignmentValues[this.userProperties?.getByRef(W.TEXT_ALIGNMENT_REF)?.value],columnCount:at.columnCountValues[this.userProperties?.getByRef(W.COLUMN_COUNT_REF)?.value],direction:at.directionValues[this.userProperties?.getByRef(W.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=at.parseAppearanceSetting(e.appearance);let t=this.userProperties?.getByRef(W.APPEARANCE_REF);t&&(t.value=this.appearance,await this.storeProperty(t))}if(e.fontSize){this.fontSize=e.fontSize;let t=this.userProperties?.getByRef(W.FONT_SIZE_REF);t&&(t.value=this.fontSize,await this.storeProperty(t))}if(e.fontFamily){this.fontFamily=at.fontFamilyValues.findIndex(i=>i===e.fontFamily);let t=this.userProperties?.getByRef(W.FONT_FAMILY_REF);t&&(t.value=this.fontFamily,await this.storeProperty(t))}if(e.letterSpacing){this.letterSpacing=e.letterSpacing;let t=this.userProperties?.getByRef(W.LETTER_SPACING_REF);t&&(t.value=this.letterSpacing,await this.storeProperty(t))}if(e.wordSpacing){this.wordSpacing=e.wordSpacing;let t=this.userProperties?.getByRef(W.WORD_SPACING_REF);t&&(t.value=this.wordSpacing,await this.storeProperty(t))}if(e.columnCount){this.columnCount=at.columnCountValues.findIndex(i=>i===e.columnCount);let t=this.userProperties?.getByRef(W.COLUMN_COUNT_REF);t&&(t.value=this.columnCount,await this.storeProperty(t)),this.settingsColumnsChangeCallback()}if(e.direction){this.direction=at.directionValues.findIndex(i=>i===e.direction);let t=this.userProperties?.getByRef(W.DIRECTION_REF);t&&(t.value=this.direction,await this.storeProperty(t))}if(e.textAlignment){this.textAlignment=at.textAlignmentValues.findIndex(i=>i===e.textAlignment);let t=this.userProperties?.getByRef(W.TEXT_ALIGNMENT_REF);t&&(t.value=this.textAlignment,await this.storeProperty(t))}if(e.lineHeight){this.lineHeight=e.lineHeight;let t=this.userProperties?.getByRef(W.LINE_HEIGHT_REF);t&&(t.value=this.lineHeight,await this.storeProperty(t))}if(e.pageMargins){this.pageMargins=e.pageMargins;let t=this.userProperties?.getByRef(W.PAGE_MARGINS_REF);t&&(t.value=this.pageMargins,await this.storeProperty(t))}if(e.verticalScroll!==void 0){let t=this.view?.getCurrentPosition();this.verticalScroll=at.parseScrollSetting(e.verticalScroll);let i=this.userProperties?.getByRef(W.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(W.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(W.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(W.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(W.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(W.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(W.TEXT_COLOR_REF);t&&(t.value=this.textColor,await this.storeProperty(t))}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=at.appearanceValues[0]:e==="sepia"||e==="readium-sepia-on"?t=at.appearanceValues[1]:e==="night"||e==="readium-night-on"?t=at.appearanceValues[2]:t=e,at.appearanceValues.findIndex(i=>i===t)}async scroll(e){let t=this.view?.getCurrentPosition();this.verticalScroll=e;let i=this.userProperties?.getByRef(W.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(W.FONT_SIZE_REF)).increment(),this.fontSize=this.userProperties?.getByRef(W.FONT_SIZE_REF)?.value;let t=this.userProperties?.getByRef(W.FONT_SIZE_REF);t&&await this.storeProperty(t)}else if(e==="letterSpacing"){(this.userProperties?.getByRef(W.LETTER_SPACING_REF)).increment(),this.letterSpacing=this.userProperties?.getByRef(W.LETTER_SPACING_REF)?.value;let t=this.userProperties?.getByRef(W.LETTER_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="wordSpacing"){(this.userProperties?.getByRef(W.WORD_SPACING_REF)).increment(),this.wordSpacing=this.userProperties?.getByRef(W.WORD_SPACING_REF)?.value;let t=this.userProperties?.getByRef(W.WORD_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="lineHeight"){(this.userProperties?.getByRef(W.LINE_HEIGHT_REF)).increment(),this.lineHeight=this.userProperties?.getByRef(W.LINE_HEIGHT_REF)?.value;let t=this.userProperties?.getByRef(W.LINE_HEIGHT_REF);t&&await this.storeProperty(t)}else if(e==="paraSpacing"){(this.userProperties?.getByRef(W.PARA_SPACING_REF)).increment(),this.paraSpacing=this.userProperties?.getByRef(W.PARA_SPACING_REF)?.value;let t=this.userProperties?.getByRef(W.PARA_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="paraIndent"){(this.userProperties?.getByRef(W.PARA_INDENT_REF)).increment(),this.paraIndent=this.userProperties?.getByRef(W.PARA_INDENT_REF)?.value;let t=this.userProperties?.getByRef(W.PARA_INDENT_REF);t&&await this.storeProperty(t)}else if(e==="typeScale"){(this.userProperties?.getByRef(W.TYPE_SCALE_REF)).increment(),this.typeScale=this.userProperties?.getByRef(W.TYPE_SCALE_REF)?.value;let t=this.userProperties?.getByRef(W.TYPE_SCALE_REF);t&&await this.storeProperty(t)}await this.applyProperties(),this.settingsChangeCallback()}async decrease(e){if(e==="fontSize"){(this.userProperties?.getByRef(W.FONT_SIZE_REF)).decrement(),this.fontSize=this.userProperties?.getByRef(W.FONT_SIZE_REF)?.value;let t=this.userProperties?.getByRef(W.FONT_SIZE_REF);t&&await this.storeProperty(t)}else if(e==="letterSpacing"){(this.userProperties?.getByRef(W.LETTER_SPACING_REF)).decrement(),this.letterSpacing=this.userProperties?.getByRef(W.LETTER_SPACING_REF)?.value;let t=this.userProperties?.getByRef(W.LETTER_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="wordSpacing"){(this.userProperties?.getByRef(W.WORD_SPACING_REF)).decrement(),this.wordSpacing=this.userProperties?.getByRef(W.WORD_SPACING_REF)?.value;let t=this.userProperties?.getByRef(W.WORD_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="lineHeight"){(this.userProperties?.getByRef(W.LINE_HEIGHT_REF)).decrement(),this.lineHeight=this.userProperties?.getByRef(W.LINE_HEIGHT_REF)?.value;let t=this.userProperties?.getByRef(W.LINE_HEIGHT_REF);t&&await this.storeProperty(t)}else if(e==="paraSpacing"){(this.userProperties?.getByRef(W.PARA_SPACING_REF)).decrement(),this.paraSpacing=this.userProperties?.getByRef(W.PARA_SPACING_REF)?.value;let t=this.userProperties?.getByRef(W.PARA_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="paraIndent"){(this.userProperties?.getByRef(W.PARA_INDENT_REF)).decrement(),this.paraIndent=this.userProperties?.getByRef(W.PARA_INDENT_REF)?.value;let t=this.userProperties?.getByRef(W.PARA_INDENT_REF);t&&await this.storeProperty(t)}else if(e==="typeScale"){(this.userProperties?.getByRef(W.TYPE_SCALE_REF)).decrement(),this.typeScale=this.userProperties?.getByRef(W.TYPE_SCALE_REF)?.value;let t=this.userProperties?.getByRef(W.TYPE_SCALE_REF);t&&await this.storeProperty(t)}await this.applyProperties(),this.settingsChangeCallback()}};at.appearanceValues=["readium-default-on","readium-sepia-on","readium-night-on"],at.fontFamilyValues=["Original","serif","sans-serif"],at.textAlignmentValues=["auto","justify","start"],at.columnCountValues=["auto","1","2"],at.directionValues=["auto","ltr","rtl"];var yd=at;_();ui();_();_();_();_();_();_();_();var Y7={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 or(t,e/2)}};_();_();var J7=typeof navigator<"u"&&navigator.userAgent?navigator.userAgent.toLowerCase():"",Ba=(()=>{let n=parseInt((/msie (\d+)/.exec(J7)||[])[1],10);return isNaN(n)?(n=parseInt((/trident\/.*; rv:(\d+)/.exec(J7)||[])[1],10),isNaN(n)?!1:n):n})();function $7(n,e){return Ba===!1?!1:e?n==="<"?Ba<e:n==="<="?Ba<=e:n===">"?Ba>e:n===">="?Ba>=e:Ba===e:!0}function Oq(){if(typeof window<"u"){let n=window.crypto||window.msCrypto;if(!n){if($7("<",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 Y6=="function")return function(){return __non_webpack_require__("crypto").randomBytes(4).readInt32LE()}}throw new Error("Unable to find crypto module")}var Q7=Oq();var or=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):Y7.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(Q7());return new n(t,e)}};_();_();var Iy={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 or(t,e)}};var X7={stringify(n){try{return decodeURIComponent(escape(Iy.stringify(n)))}catch{throw new Error("Malformed UTF-8 data")}},parse(n){return Iy.parse(unescape(encodeURIComponent(n)))}};var pp=class{constructor(e){this._minBufferSize=0,this._blockSize=0,this._props=e,this._data=e&&typeof e.data<"u"?e.data.clone():new or,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 or,this._nBytes=typeof t=="number"?t:0}_append(e){let t=typeof e=="string"?X7.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 or(t,l)}_doProcessBlock(e,t){throw new Error("Not implemented")}};var gp=class extends pp{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 Py=[],eT=[];function Bq(n){let e=Math.sqrt(n);for(let t=2;t<=e;t++)if(!(n%t))return!1;return!0}function Z7(n){return(n-(n|0))*4294967296|0}(function(){let e=2,t=0;for(;t<64;)Bq(e)&&(t<8&&(Py[t]=Z7(Math.pow(e,1/2))),eT[t]=Z7(Math.pow(e,1/3)),t++),e++})();var Na=[],ys=class n extends gp{constructor(e){super(e),this._hash=new or(Py.slice(0)),this._props=e,e&&typeof e.hash<"u"&&(this._hash=e.hash.clone())}_doReset(){this._hash=new or(Py.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],h=i[7];for(let f=0;f<64;f++){if(f<16)Na[f]=e[t+f]|0;else{let E=Na[f-15],S=(E<<25|E>>>7)^(E<<14|E>>>18)^E>>>3,C=Na[f-2],T=(C<<15|C>>>17)^(C<<13|C>>>19)^C>>>10;Na[f]=S+Na[f-7]+T+Na[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),A=h+b+m+eT[f]+Na[f],v=g+y;h=c,c=l,l=u,u=a+A|0,a=o,o=s,s=r,r=A+v|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]+h|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 Ed=Qe(eo());_();_();var un=Qe(Qt());function bp(n,e){let t=n.getClientRects();return My(t,e)}function My(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=iT(i,1,e),s=jq(r,1),o=nT(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)un.default.log("CLIENT RECT: remove small"),o.splice(u,1);else{un.default.log("CLIENT RECT: remove small, but keep otherwise empty!");break}}return rT(o),un.default.log(`CLIENT RECT: reduced ${i.length} --> ${o.length}`),o}function Tr(n,e,t){return Math.abs(n-e)<=t}function Nq(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 tT(n,e){let t=Nq(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 mp(n,e,t,i){return(n.left<e||Tr(n.left,e,i))&&(n.right>e||Tr(n.right,e,i))&&(n.top<t||Tr(n.top,t,i))&&(n.bottom>t||Tr(n.bottom,t,i))}function Dq(n,e,t){return mp(n,e.left,e.top,t)&&mp(n,e.right,e.top,t)&&mp(n,e.left,e.bottom,t)&&mp(n,e.right,e.bottom,t)}function Fq(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 Ly(n,e,t){return(n.left<e.right||t>=0&&Tr(n.left,e.right,t))&&(e.left<n.right||t>=0&&Tr(e.left,n.right,t))&&(n.top<e.bottom||t>=0&&Tr(n.top,e.bottom,t))&&(e.top<n.bottom||t>=0&&Tr(e.top,n.bottom,t))}function iT(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){un.default.log("mergeTouchingRects rect1 === rect2 ??!");continue}let a=Tr(s.top,o.top,e)&&Tr(s.bottom,o.bottom,e),u=Tr(s.left,o.left,e)&&Tr(s.right,o.right,e);if((u&&!t||a&&!u)&&Ly(s,o,e)){un.default.log(`CLIENT RECT: merging two into one, VERTICAL: ${a} HORIZONTAL: ${u} (${t})`);let f=n.filter(y=>y!==s&&y!==o),m=Fq(s,o);return f.push(m),iT(f,e,t)}}return n}function nT(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){un.default.log("replaceOverlappingRects rect1 === rect2 ??!");continue}if(Ly(i,r,-1)){let s=[],o,a,u=tT(i,r);if(u.length===1)s=u,o=i,a=r;else{let h=tT(r,i);u.length<h.length?(s=u,o=i,a=r):(s=h,o=r,a=i)}let l=[];l.push(a),Array.prototype.push.apply(l,s),rT(l),un.default.log(`CLIENT RECT: overlap, cut one rect into ${s.length}`);let c=n.filter(h=>h!==o);return Array.prototype.push.apply(c,s),nT(c)}}return n}function Hq(n,e){return Math.max(0,Math.min(n.right,e.right)-Math.max(n.left,e.left))}function Uq(n,e){return Math.max(0,Math.min(n.bottom,e.bottom)-Math.max(n.top,e.top))}function jq(n,e){let t=new Set(n);for(let i of n){if(!(i.width>1&&i.height>1)){un.default.log("CLIENT RECT: remove tiny"),t.delete(i);continue}for(let s of n)if(i!==s&&t.has(s)&&Dq(s,i,e)){un.default.log("CLIENT RECT: remove contained"),t.delete(i);break}}return Array.from(t)}function rT(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)&&Ly(t,i,-1)){r||e.push(t),s||e.push(i),un.default.log("CLIENT RECT: overlap ---"),un.default.log(`#1 TOP:${t.top} BOTTOM:${t.bottom} LEFT:${t.left} RIGHT:${t.right} WIDTH:${t.width} HEIGHT:${t.height}`),un.default.log(`#2 TOP:${i.top} BOTTOM:${i.bottom} LEFT:${i.left} RIGHT:${i.right} WIDTH:${i.width} HEIGHT:${i.height}`);let o=Hq(t,i);un.default.log(`xOverlap: ${o}`);let a=Uq(t,i);un.default.log(`yOverlap: ${a}`)}}e.length&&un.default.log(`CLIENT RECT: overlaps ${e.length}`)}_();var Gt=Qe(Qt());function As(n,e){let t=n?n.getSelection():null;if(!t)return;if(t.isCollapsed){Gt.default.log("^^^ SELECTION COLLAPSED.");return}let i=t.toString(),r=i.trim().replace(/\n/g," ").replace(/\s\s+/g," ");if(r.length===0){Gt.default.log("^^^ SELECTION TEXT EMPTY.");return}if(!t.anchorNode||!t.focusNode)return;let s=t.rangeCount===1?t.getRangeAt(0):aT(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset);if(!s||s.collapsed){Gt.default.log("$$$$$$$$$$$$$$$$$ CANNOT GET NON-COLLAPSED SELECTION RANGE?!");return}let o=Wq(s);o.startContainer!==s.startContainer&&(Gt.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startContainer"),Gt.default.log(o.startContainer),Gt.default.log(s.startContainer)),o.startOffset!==s.startOffset&&(Gt.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startOffset"),Gt.default.log(`${o.startOffset} !== ${s.startOffset}`)),o.endContainer!==s.endContainer&&(Gt.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endContainer"),Gt.default.log(o.endContainer),Gt.default.log(s.endContainer)),o.endOffset!==s.endOffset&&(Gt.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endOffset"),Gt.default.log(`${o.endOffset} !== ${s.endOffset}`));let a=to(o,e);if(!a){Gt.default.log("^^^ SELECTION RANGE INFO FAIL?!");return}return{rangeInfo:a,cleanText:r,rawText:i,range:o}}function aT(n,e,t,i){try{let r=new Range;if(r.setStart(n,e),r.setEnd(t,i),!r.collapsed)return Gt.default.log(">>> createOrderedRange RANGE OK"),r;Gt.default.log(">>> createOrderedRange COLLAPSED ... RANGE REVERSE?");let s=new Range;if(s.setStart(t,i),s.setEnd(n,e),!s.collapsed)return Gt.default.log(">>> createOrderedRange RANGE REVERSE OK."),r;Gt.default.log(">>> createOrderedRange RANGE REVERSE ALSO COLLAPSED?!");return}catch(r){console.warn(r.message);return}}function to(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=Gq(n.startContainer,n.endContainer);if(!c){Gt.default.log("^^^ NO RANGE COMMON ANCESTOR?!");return}if(n.commonAncestorContainer){let h=n.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?n.commonAncestorContainer:n.commonAncestorContainer.parentNode;h&&h.nodeType===Node.ELEMENT_NODE&&c!==h&&(Gt.default.log(">>>>>> COMMON ANCESTOR CONTAINER DIFF??!"),Gt.default.log(e(c)),Gt.default.log(e(h)))}if(l&&s)return{endContainerChildTextNodeIndex:u,endContainerElementCssSelector:l,endOffset:n.endOffset,startContainerChildTextNodeIndex:r,startContainerElementCssSelector:s,startOffset:n.startOffset}}function yp(n,e){let t=n.querySelector(e.startContainerElementCssSelector);if(!t){Gt.default.log("^^^ convertRangeInfo NO START ELEMENT CSS SELECTOR?!");return}let i=t;if(e.startContainerChildTextNodeIndex>=0){if(e.startContainerChildTextNodeIndex>=t.childNodes.length){Gt.default.log("^^^ convertRangeInfo rangeInfo.startContainerChildTextNodeIndex >= startElement.childNodes.length?!");return}if(i=t.childNodes[e.startContainerChildTextNodeIndex],i.nodeType!==Node.TEXT_NODE){Gt.default.log("^^^ convertRangeInfo startContainer.nodeType !== Node.TEXT_NODE?!");return}}let r=n.querySelector(e.endContainerElementCssSelector);if(!r){Gt.default.log("^^^ convertRangeInfo NO END ELEMENT CSS SELECTOR?!");return}let s=r;if(e.endContainerChildTextNodeIndex>=0){if(e.endContainerChildTextNodeIndex>=r.childNodes.length){Gt.default.log("^^^ convertRangeInfo rangeInfo.endContainerChildTextNodeIndex >= endElement.childNodes.length?!");return}if(s=r.childNodes[e.endContainerChildTextNodeIndex],s.nodeType!==Node.TEXT_NODE){Gt.default.log("^^^ convertRangeInfo endContainer.nodeType !== Node.TEXT_NODE?!");return}}return aT(i,e.startOffset,s,e.endOffset)}function Gq(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 Wq(n){let e=n.cloneRange(),t=e.startContainer,i=e.startOffset,r=e.endContainer,s=e.endOffset;t.childNodes.length&&i>0&&(t=oT(t.childNodes[i-1]),i=t.length||0),s<r.childNodes.length&&(r=sT(r.childNodes[s]),s=0);let o=sT(t),a=oT(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=Vq(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=Kq(a);return a===r?e.setEnd(r,s):a!==null&&(a.nodeType===3?e.setEnd(a,a.length):e.setEndAfter(a)),e}function Vq(n){if(n.firstChild)return n.firstChild;let e=n;for(;!e.nextSibling;)if(e=e.parentNode,!e)return null;return e.nextSibling}function Kq(n){if(n.lastChild)return n.lastChild;let e=n;for(;!e.previousSibling;)if(e=e.parentNode,!e)return null;return e.previousSibling}function sT(n){for(;n.firstChild;)n=n.firstChild;return n}function oT(n){for(;n.lastChild;)n=n.lastChild;return n}_();var Dy=Qe(lT());var io,Fy;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};io={...i,...t},Fy=Xq(io.root,i);let r=ky(n,0,()=>ky(n,1,()=>ky(n,2)));if(r){let s=pT(gT(r,n));return s.length>0&&(r=s[0]),Ap(r)}else throw new Error("Selector was not found.")}function Xq(n,e){return n.nodeType===Node.DOCUMENT_NODE?n:n===e.root?n.ownerDocument:n}function ky(n,e,t){let i=null,r=[],s=n,o=0;for(;s&&s!==io.root.parentElement;){let a=Ny(Zq(s))||Ny(...eY(s))||Ny(tY(s))||[iY()],u=nY(s);if(e===0)u&&(a=a.concat(a.filter(By).map(l=>Oy(l,u))));else if(e===1)a=a.slice(0,1),u&&(a=a.concat(a.filter(By).map(l=>Oy(l,u))));else if(e===2){let[l]=a=a.slice(0,1);u&&By(l)&&(a=[Oy(l,u)])}for(let l of a)l.level=o;if(r.push(a),r.length>=io.seedMinLength&&(i=cT(r,t),i))break;s=s.parentElement,o++}return i||(i=cT(r,t)),i}function cT(n,e){let t=pT(fT(n));if(t.length>io.threshold)return e?e():null;for(let i of t)if(hT(i))return i;return null}function Ap(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 dT(n){return n.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function hT(n){switch(Fy.querySelectorAll(Ap(n)).length){case 0:throw new Error(`Can't select any node with this selector: ${Ap(n)}`);case 1:return!0;default:return!1}}function Zq(n){let e=n.getAttribute("id");return e&&io.idName(e)?{name:"#"+(0,Dy.default)(e,{isIdentifier:!0}),penalty:0}:null}function eY(n){return Array.from(n.classList).filter(io.className).map(t=>({name:"."+(0,Dy.default)(t,{isIdentifier:!0}),penalty:1}))}function tY(n){let e=n.tagName.toLowerCase();return io.tagName(e)?{name:e,penalty:2}:null}function iY(){return{name:"*",penalty:3}}function nY(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 Oy(n,e){return{name:n.name+`:nth-child(${e})`,penalty:n.penalty+1}}function By(n){return n.name!=="html"&&!n.name.startsWith("#")}function Ny(...n){let e=n.filter(rY);return e.length>0?e:null}function rY(n){return n!=null}function*fT(n,e=[]){if(n.length>0)for(let t of n[0])yield*fT(n.slice(1,n.length),e.concat(t));else yield e}function pT(n){return Array.from(n).sort((e,t)=>dT(e)-dT(t))}function*gT(n,e){if(n.length>2&&n.length>io.optimizedMinLength)for(let t=1;t<n.length-1;t++){let i=[...n];i.splice(t,1),hT(i)&&sY(i,e)&&(yield i,yield*gT(i,e))}}function sY(n,e){return Fy.querySelector(Ap(n))===e}_();var vs=(s=>(s[s.Highlight=0]="Highlight",s[s.Underline=1]="Underline",s[s.Bookmark=2]="Bookmark",s[s.Custom=3]="Custom",s[s.Comment=4]="Comment",s))(vs||{});Ad();ui();var jy=Qe(vp());_y();var An=Qe(Qt()),Da=(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))(Da||{}),yT="R2_CLASS_HIGHLIGHT_CONTAINER",Cd="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",ln="R2_CLASS_HIGHLIGHT_AREA",wd="R2_CLASS_HIGHLIGHT_ICON",ws=.5,bT=.75,Fa={blue:100,green:50,red:230},li=[],uY="data-highlighted",lY="data-timestamp",ol={ELEMENT_NODE:1,TEXT_NODE:3};var ar=["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",yT,ln,Cd],Hy=-1,Uy=-1,Xt=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,Ed.default)(e=>{this.isAndroid()||this.snapSelectionToWord(e),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,Ed.default)(()=>{this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen(),this.navigator.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,Ed.default)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.navigator.emit("toolbox.closed","closed"))},100);this.selection=(0,Ed.default)((e,t)=>{this.api?.selection&&this.api?.selection(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(),Hy=-1,Uy=-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===ol.TEXT_NODE?e.endOffset<i.nodeValue.length&&i.splitText(e.endOffset):e.endOffset>0&&(i=i.childNodes.item(e.endOffset-1));return t.nodeType===ol.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(lY);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===ol.TEXT_NODE)for(;e.nextSibling&&e.nextSibling.nodeType===ol.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(Hy=e.clientX,Uy=e.clientY,this.properties?.preventScrollOnSelection){let t=gt(document,"#iframe-wrapper");t.style.overflow="hidden"}}async mouseup(e){Math.abs(Hy-e.clientX)<3&&Math.abs(Uy-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=qr.close,s.addEventListener("click",function(){u.toolboxMode("add")})),o&&(o.innerHTML=qr.close,o.addEventListener("click",function(){u.toolboxMode("add")})),i){i.style.position="relative",i.style.zIndex="20",this.colors.forEach(h=>{let f=document.getElementById(h),m=document.getElementById(`c${h}`);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 h=10;this.colors.forEach(f=>{h--;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=`${h}`,m.style.marginLeft="-30px",c.push(m),t?.insertBefore(m,a)})}this.colors.forEach(h=>{let f=i?.cloneNode(!0),m=f.lastChild;m.style.backgroundColor=h,f.id=h,f.style.position="relative",f.style.display="unset",l.push(f),i&&f.addEventListener("click",function(){u.setColor(h);let y=i?.lastChild;y&&(y.style.backgroundColor=h);let g=document.getElementById("highlightIcon"),b=document.getElementById("underlineIcon"),A=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()),(A?.getElementsByTagName?.("span").length??0)>0&&((A?.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=gt(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 A=b.match(new RegExp("[^a-zA-Z0-9]+$"));return!A||!A.index?b:b.slice(0,A.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 h=document.createRange();e?(h.setStart(s.anchorNode,s.anchorOffset+a),h.setEnd(s.focusNode,s.focusOffset-u)):(h.setStart(s.anchorNode,s.anchorOffset),h.setEnd(s.focusNode,s.focusOffset));let f=h.collapsed;h.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=>ar.indexOf(f)<0,idName:f=>ar.indexOf(f)<0},h=e.navigator.iframes[0].contentDocument;if(h)return Vi(l,h,c)}let a=e.navigator.iframes[0].contentWindow,u=As(a,o);u&&e.navigator.annotationModule?.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");i&&(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")):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")):(this.navigator.view?.isPaginated()?i.style.top=t.top+(this.navigator.attributes?.navHeight??0)+"px":i.style.top=t.top+"px",i.style.left=(t.right-t.left)/2+t.left+"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)},h=r.cloneNode(!0);r?.parentNode?.replaceChild(h,r),r=document.getElementById("highlightIcon"),r?.addEventListener("click",c)}if(o){let c=function(){i.doHighlight(!1,1),i.toolboxHide(),o?.removeEventListener("click",c)},h=o.cloneNode(!0);o?.parentNode?.replaceChild(h,o),o=document.getElementById("underlineIcon"),o?.addEventListener("click",c)}if(a){let c=function(){i.doHighlight(!1,4),i.toolboxHide(),a?.removeEventListener("click",c)},h=a.cloneNode(!0);a?.parentNode?.replaceChild(h,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()},h=l.cloneNode(!0);l?.parentNode?.replaceChild(h,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 h=document.getElementById(c.id),f=this;function m(){h?.removeEventListener("click",m);function y(b){let A={className:E=>ar.indexOf(E)<0,idName:E=>ar.indexOf(E)<0},v=f.navigator.iframes[0].contentDocument;if(v)return Vi(b,v,A)}let g=f.navigator.iframes[0].contentWindow;if(g){let b=As(g,y);if(b===void 0){let A=f.navigator.iframes[0].contentDocument;b=f.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(A)??void 0}if(b!==void 0)if(c.callback)c.callback(b.cleanText,b.range?.startContainer.parentElement);else{let A=c.highlight?.style,v=c.marker?c.marker:3;if(v===3&&f.navigator.rights.enableAnnotations||v===2&&f.navigator.rights.enableBookmarks){let E=f.navigator.iframes[0].contentDocument;if(E){let S=f.createHighlight(f.dom(E.body).getWindow(),b,c.highlight?.color,!0,v,c.icon,c.popup,A);f.options.onAfterHighlight(S,v),f.navigator.rights.enableAnnotations?f.navigator.annotationModule?.saveAnnotation(S[0]).then(C=>{c?.note&&C.highlight&&f.navigator.annotationModule?.api?.addCommentToAnnotation(C).then(T=>{f.navigator.annotationModule?.updateAnnotation(T).then(async()=>{An.default.log("update highlight "+T.id)})})}):f.navigator.rights.enableBookmarks&&f.navigator.bookmarkModule?.saveAnnotation(S[0])}}}}f.callbackComplete()}if(h){let y=h.cloneNode(!0);h?.parentNode?.replaceChild(y,h),h=document.getElementById(c.id),h?.addEventListener("click",m)}})}}doHighlight(e,t){let i=this;function r(o){let a={className:l=>ar.indexOf(l)<0,idName:l=>ar.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=As(s,r);if(o===void 0){let a=i.navigator.iframes[0].contentDocument;o=this.navigator.annotationModule?.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.annotationModule?.saveAnnotation(l[0]):this.navigator.rights.enableBookmarks&&t===2&&this.navigator.bookmarkModule?.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=>ar.indexOf(l)<0,idName:l=>ar.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=As(i,t);if(o===void 0){let a=e.navigator.iframes[0].contentDocument;o=e.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(a)??void 0}o!==void 0&&this.navigator.ttsModule.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=gt(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,h=s<i,f=e.left>r;return l||c||h||f}isInsideViewport(e){let t=gt(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,h=l<u;return s&&o&&c&&h}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:h,left:f,width:m}=s(l);return{top:c,height:h,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){An.default.log("measureTextNode "+u),An.default.log("measureTextNode "+a),An.default.log(`${a.textContent}`)}},t=qs(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.ttsModule.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===ol.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===ol.ELEMENT_NODE&&e.hasAttribute(uY)}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=li.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}, ${ws})`,"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}, ${ws})`,"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(wd);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}, ${bT})`,"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}, ${bT})`,"important")}else r.classList.add("hover");if(i.type!==4){let o=e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER").querySelector(`#${i.id}`).getElementsByClassName(wd);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(`.${ln}`));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 h=u.color;o.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${ws})`,"important")}else if(n.isHexColor(u.color)){let h=n.hexToRgbChannels(u.color);o.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${ws})`,"important")}else o.classList.remove("hover");let c=i.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${u.id}`).getElementsByClassName(wd);if(c.length>0){let h=c.item(0).getElementsByClassName("icon-tooltip");h.length>0&&h.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}, ${ws})`,"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}, ${ws})`,"important")}else o.classList.remove("hover");let l=i.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${e.id}`).getElementsByClassName(wd);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=li.find(s=>s.id===e.target.parentElement?.id);if(!r||!i){for(let s in Da){let o=t.getElementById(s);if(o){let a=o.querySelectorAll(`.${Cd}`);for(let l of a)this.resetHighlightBoundingStyle(l);let u=Array.from(o.querySelectorAll(`.${ln}`));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};An.default.log(JSON.stringify(s));let o=this,a;if(o.navigator.rights.enableAnnotations?a=await this.navigator.annotationModule?.getAnnotation(s.highlight):o.navigator.rights.enableBookmarks&&(a=await this.navigator.bookmarkModule?.getAnnotation(s.highlight)),s.highlight.type===0&&this.navigator.annotationModule?.api?.selectedAnnotation(a).then(async()=>{}),a?.id){An.default.log("selected highlight "+a.id),o.lastSelectedHighlight=a.id;let u=document.getElementById("highlight-toolbox");if(u)if(u.style.top=e.clientY+(this.navigator.attributes?.navHeight??0)+"px",u.style.left=e.clientX+"px",getComputedStyle(u).display==="none"){let h=function(){o.navigator.annotationModule?.api?.addCommentToAnnotation(a).then(A=>{o.navigator.annotationModule?.updateAnnotation(A).then(async()=>{An.default.log("update highlight "+A.id),u&&(u.style.display="none"),o.selectionMenuClosed()}),u&&(u.style.display="none"),o.selectionMenuClosed(),f?.removeEventListener("click",h,!1)})},y=function(){o.navigator.rights.enableAnnotations?o.navigator.annotationModule?.deleteSelectedHighlight(a).then(async()=>{An.default.log("delete highlight "+a.id),u&&(u.style.display="none"),o.selectionMenuClosed()}):o.navigator.rights.enableBookmarks&&o.navigator.bookmarkModule?.deleteSelectedHighlight(a).then(async()=>{An.default.log("delete highlight "+a.id),u&&(u.style.display="none"),o.selectionMenuClosed()})};u.style.display="block",this.toolboxMode("edit");let l=document.getElementById("colorIcon"),c=document.getElementById("highlightIcon");l&&(l.style.display="none"),c&&(c.style.display="none");let f=document.getElementById("commentIcon"),m=document.getElementById("cloneCommentIcon");if(m){let A=m.parentElement;A&&A.removeChild(m)}if(f){f.style.display="none";let A=f.cloneNode(!0),v=f.parentElement;A.style.display="unset",A.id="cloneCommentIcon",A.addEventListener("click",h,!1),v&&v.append(A)}let g=document.getElementById("deleteIcon"),b=document.getElementById("cloneDeleteIcon");if(b){let A=b.parentElement;A&&A.removeChild(b)}if(g){g.style.display="none";let A=g.cloneNode(!0),v=g.parentElement;A.style.display="unset",A.id="cloneDeleteIcon",A.addEventListener("click",y,!1),v&&v.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 il(this.navigator).showPopup(u.dataset.definition,e);let l=this.navigator.definitionsModule?.properties?.definitions?.filter(c=>c.order===Number(u?.dataset.order))[0];An.default.log(l),this.navigator.definitionsModule?.api?.click&&(this.navigator.definitionsModule.api?.click(jy.omit(l,"callbacks"),jy.omit(r,"definition")),this.navigator.emit("definition.click",l,r))}}}async prepareContainers(e){for(let t in Da)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),li.splice(0,li.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),li.splice(0,li.length);break}}}destroyHighlight(e,t){if(!e)return;let i=-1;li.find((o,a)=>(i=a,o.id===t))&&i>=0&&i<li.length&&li.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 h=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,f=ys.hash(h),m=(c||"R2_HIGHLIGHT_")+f;this.destroyHighlight(e.document,m);let y=`rgb(${Fa.red}, ${Fa.green}, ${Fa.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)&&li.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(h){throw"Can't create highlight: "+h}}createHighlightDom(e,t){let i=e.document,r=yp(i,t.selectionInfo.rangeInfo);if(!r)return;for(let N in Da)this.ensureHighlightsContainer(e,N);let s=i.createElement("div");s.setAttribute("id",t.id),s.setAttribute("class",yT),s.style.setProperty("pointer-events","none"),t.pointerInteraction&&(s.setAttribute("data-click","1"),s.addEventListener("mouseover",N=>{if(N.target.classList.contains("R2_CLASS_HIGHLIGHT_AREA")){let H=N.currentTarget,j=li.find(U=>U.id===N.currentTarget.id);if(N.type==="mouseover"&&H.parentElement?.style.display!=="none"&&j){let U=Array.from(H.querySelectorAll(`.${ln}`));this.setHighlightAreaStyle(i,U,j)}}}),s.addEventListener("mouseleave",N=>{let H=N.currentTarget,j=Array.from(H.querySelectorAll(`.${ln}`));for(let V of j)this.resetHighlightAreaStyle(V,H.id);let U=H.querySelector(`.${Cd}`),z=H.querySelectorAll(`.${Cd}`);for(let V of z)(!U||V!==U)&&this.resetHighlightBoundingStyle(V)}));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,h=1,f=!1,m=!1,g=f||m||!1;An.default.debug(g),g=!0;let b=bp(r,g),A=3,v=2,E=3,S=0,C=24,T,M;for(let N of b){let H=i.createElement("div");H.setAttribute("class",ln),H.dataset.marker=""+t.marker;let j="";if(f&&t.marker!==3&&t.marker!==2&&t.marker!==4){let J=t.color;n.isHexColor(J)&&(J=n.hexToRgbChannels(J)),j+=`border-bottom: ${v*h}px solid rgba(${J.red}, ${J.green}, ${J.blue}, ${ws}) !important`}if(t.marker===3||t.marker===2)if(t.style?.default){for(let J=0;J<t.style?.default?.length;J++){let Q=t.style?.default[J];j+=`${Q.property}: ${Q.value} !${Q.priority};`}H.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${A}px !important; ${j}`)}else t.style?.defaultClass&&(H.classList.add(t.style?.defaultClass),H.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${A}px !important; ${j}`));else if(t.marker===1||t.marker===4)if(typeof t.color=="object"){let J=t.color;H.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${A}px !important; background-color: rgba(${J.red}, ${J.green}, ${J.blue}, 0) !important; ${j}`),H.style.setProperty("border-bottom",`2px solid rgba(${J.red}, ${J.green}, ${J.blue}, 1)`,"important")}else if(n.isHexColor(t.color)){let J=n.hexToRgbChannels(t.color);H.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${A}px !important; background-color: rgba(${J.red}, ${J.green}, ${J.blue}, 0) !important; ${j}`),H.style.setProperty("border-bottom",`2px solid rgba(${J.red}, ${J.green}, ${J.blue}, 1)`,"important")}else H.setAttribute("style",`border-radius: ${A}px !important; ${j}`);else if(typeof t.color=="object"){let J=t.color;H.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${A}px !important; background-color: rgba(${J.red}, ${J.green}, ${J.blue}, ${ws}) !important; ${j}`)}else if(n.isHexColor(t.color)){let J=n.hexToRgbChannels(t.color);H.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${A}px !important; background-color: rgba(${J.red}, ${J.green}, ${J.blue}, ${ws}) !important; ${j}`)}else H.setAttribute("style",`border-radius: ${A}px !important; ${j}`);t.type===1||t.type===2||t.type===5||t.type===3?H.style.setProperty("pointer-events","none"):(H.style.setProperty("pointer-events","all"),H.style.setProperty("cursor","hand")),H.style.position="absolute",H.scale=h,H.rect={height:N.height,left:N.left-l,top:N.top-c,width:N.width},t.pointerInteraction&&(H.setAttribute("data-click","1"),H.tabIndex=0),H.style.width=`${H.rect.width*h}px`,H.style.height=`${H.rect.height*h}px`,H.style.left=`${H.rect.left*h}px`,H.style.top=`${H.rect.top*h}px`,s.append(H);let U=parseInt(H.style.top.replace("px",""));if((U<S||S===0)&&(S=U),C=parseInt(H.style.height.replace("px","")),m){let J=i.createElement("div");J.setAttribute("class",ln);let Q=t.color;n.isHexColor(Q)&&(Q=n.hexToRgbChannels(Q)),J.setAttribute("style",`background-color: rgba(${Q.red}, ${Q.green}, ${Q.blue}, ${ws}) !important;`),t.type===1||t.type===2||t.type===5||t.type===3?J.style.setProperty("pointer-events","none"):(J.style.setProperty("pointer-events","all"),J.style.setProperty("cursor","hand")),J.style.position="absolute",J.scale=h,J.rect={height:N.height,left:N.left-l,top:N.top-c,width:N.width},J.style.width=`${J.rect.width*h}px`,J.style.height=`${E*h}px`,J.style.left=`${J.rect.left*h}px`,J.style.top=`${(J.rect.top+J.rect.height/2-E/2)*h}px`,s.append(J)}let z=this.navigator.iframes[0].contentWindow?.innerWidth,V=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-count")),ee=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-width")),ae=parseInt(getComputedStyle(i.body).getPropertyValue("padding-left")),Ae=z/(V||1);Ae<ee&&(Ae=z),o||(Ae=parseInt(getComputedStyle(i.body).width.replace("px","")));let ce=this.navigator.settings.fontSize/100,be=20*ce;ce<=1&&(be=-60);let oe=0*ce;ce<=1&&(oe=-60),T=Math.floor(N.left/Ae)*Ae+Ae-(C<40?40:C)+oe,M=Math.floor(N.left/Ae)*Ae+(C<40?40:C)-be;let fe=parseInt(this.navigator.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));fe>=2&&(M=M+ae/V,T=T-ae/V),o||(T=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px","")),M=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px",""))-Ae,fe>=2&&(M=M+ae/2,T=T-ae/2))}let I=r.getBoundingClientRect(),L=i.createElement("div");L.setAttribute("class",Cd),L.style.setProperty("pointer-events","none"),L.style.position="absolute",L.scale=h,L.rect={height:I.height,left:I.left-l,top:I.top-c,width:I.width},L.style.width=`${L.rect.width*h}px`,L.style.height=`${L.rect.height*h}px`,L.style.left=`${L.rect.left*h}px`,L.style.top=`${L.rect.top*h}px`,s.append(L);let R=i.createElement("div");if(R.setAttribute("class",wd),t.icon?.position==="left")R.setAttribute("style",`position: absolute;top:${S}px;left:${M+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${C}px; width:${C}px;`);else if(t.icon?.position==="inline")R.setAttribute("style",`position: absolute;top:${S-C/2}px;left:${parseInt(L.style.left.replace("px",""))+parseInt(L.style.width.replace("px",""))-C/2}px;height:${C}px; width:${C}px;`);else if(t.icon?.position==="center"){let H=C/3*2;R.setAttribute("style",`position: absolute;top:${S}px;left:${parseInt(L.style.left.replace("px",""))+parseInt(L.style.width.replace("px",""))-H}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?R.setAttribute("style",`position: absolute;top:${S-C/2}px;left:${parseInt(L.style.left.replace("px",""))+parseInt(L.style.width.replace("px",""))-C/2}px;height:${C}px; width:${C}px;`):t.note&&t.marker===4||t.marker===0||t.marker===1?R.setAttribute("style",`position: absolute;top:${S}px;left:${T+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${C}px; width:${C}px;`):R.setAttribute("style",`position: absolute;top:${S}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?(R.classList.add(t.icon?.class),R.id=t.icon?.id):t.icon?.svgPath?R.innerHTML=rl(`${t.icon?.id}`,`${t.icon?.title}`,`${t.icon?.svgPath}`,"icon open",C,`${t.icon?.color} !important`):t.icon?.title&&(R.innerHTML=t.icon?.title);else if(t.note){let N=t.color;n.isHexColor(N)&&(N=n.hexToRgbChannels(N)),t.marker===4||t.marker===0||t.marker===1?R.innerHTML=rl("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",C/2,`rgba(${N.red}, ${N.green}, ${N.blue}, 1) !important`):R.innerHTML=rl("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(${N.red}, ${N.green}, ${N.blue}, 1) !important`)}t.type===1||t.type===2||t.type===5||t.type===3?R.style.setProperty("pointer-events","none"):(R.style.setProperty("pointer-events","all"),R.style.setProperty("cursor","hand"));let B=this;if(t.type!==3&&t.type!==4&&R.addEventListener("click",async function(N){let H;B.navigator.rights.enableAnnotations?(H=await B.navigator.annotationModule?.getAnnotationByID(t.id),B.navigator.annotationModule?.api?.selectedAnnotation(H).then(async()=>{})):B.navigator.rights.enableBookmarks&&(H=await B.navigator.bookmarkModule?.getAnnotationByID(t.id)),An.default.log("selected highlight "+H.id),B.lastSelectedHighlight=H.id;let j=document.getElementById("highlight-toolbox");if(j)if(j.style.top=N.clientY+(B.navigator.attributes?.navHeight??0)+"px",j.style.left=N.clientX+"px",getComputedStyle(j).display==="none"){let Ae=function(){B.navigator.rights.enableAnnotations?B.navigator.annotationModule?.deleteSelectedHighlight(H).then(async()=>{An.default.log("delete highlight "+H.id),j.style.display="none",B.selectionMenuClosed()}):B.navigator.rights.enableBookmarks&&B.navigator.bookmarkModule?.deleteSelectedHighlight(H).then(async()=>{An.default.log("delete highlight "+H.id),j.style.display="none",B.selectionMenuClosed()})};j.style.display="block",B.toolboxMode("edit");let z=document.getElementById("colorIcon"),V=document.getElementById("highlightIcon");z&&(z.style.display="none"),V&&(V.style.display="none");let ee=document.getElementById("commentIcon"),ae=document.getElementById("cloneCommentIcon");if(ae){let oe=ae.parentElement;oe&&oe.removeChild(ae)}ee&&(ee.style.display="none");let ce=document.getElementById("deleteIcon"),be=document.getElementById("cloneDeleteIcon");if(be){let oe=be.parentElement;oe&&oe.removeChild(be)}if(ce){ce.style.display="none";let oe=ce.cloneNode(!0),fe=ce.parentElement;oe.style.display="unset",oe.id="cloneDeleteIcon",oe.addEventListener("click",Ae,!1),fe&&fe.append(oe)}}else j.style.display="none",B.selectionMenuClosed(),j.offsetWidth,j.style.display="block";let U=Array.from(s.querySelectorAll(`.${ln}`));B.setHighlightAreaStyle(i,U,t)}),t.note){let N=document.createElement("span");N.innerHTML=t.note,N.className="icon-tooltip",t.marker===3||t.marker===2?(t.popup?.background&&N.style.setProperty("background",t.popup.background),t.popup?.textColor&&N.style.setProperty("color",t.popup.textColor),t.popup?.class&&N.classList.add(t.popup.class)):(N.style.setProperty("background","lightyellow"),N.style.setProperty("color","black"))}switch((t.note||t.marker===3||t.marker===2)&&s.append(R),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)}};yn();Ad();_();_();var tn=[];for(let n=0;n<256;++n)tn.push((n+256).toString(16).slice(1));function AT(n,e=0){return(tn[n[e+0]]+tn[n[e+1]]+tn[n[e+2]]+tn[n[e+3]]+"-"+tn[n[e+4]]+tn[n[e+5]]+"-"+tn[n[e+6]]+tn[n[e+7]]+"-"+tn[n[e+8]]+tn[n[e+9]]+"-"+tn[n[e+10]]+tn[n[e+11]]+tn[n[e+12]]+tn[n[e+13]]+tn[n[e+14]]+tn[n[e+15]]).toLowerCase()}_();var Gy,cY=new Uint8Array(16);function Wy(){if(!Gy){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Gy=crypto.getRandomValues.bind(crypto)}return Gy(cY)}_();_();var dY=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Vy={randomUUID:dY};function hY(n,e,t){if(Vy.randomUUID&&!e&&!n)return Vy.randomUUID();n=n||{};let i=n.random??n.rng?.()??Wy();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 AT(i)}var al=hY;_();var fY=Qe(Qt());var Vo={className:n=>!0,idName:n=>!0,tagName:n=>!0};var ET=Qe(vp()),Ir=Qe(Qt());_();var vT=Qe(Qt());var ul=class{constructor(e,t,i){this.currSeconds=0;this.publication=e,this.properties=t,this.api=i}static async create(e){let t=new this(e.publication,e,e.api);return await t.start(),t}async start(){this.startResearchSession()}async stop(){vT.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)}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.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)}};var ll=class n{constructor(e,t,i,r,s,o,a,u){this.hide=ge(document,"#menu-button-hide");this.show=ge(document,"#menu-button-show");this.annotator=e,this.rights=t,this.publication=i,this.headerMenu=u,this.initialAnnotations=r,this.highlighter=o,this.properties=s,this.api=a}static async create(e){let t=new this(e.annotator,e.rights||{enableAnnotations:!1,enableTTS:!1},e.publication,e.initialAnnotations||null,e,e.highlighter,e.api,e.headerMenu);return await t.start(),t}async stop(){Ir.default.log("Annotation module stop")}async start(){if(this.headerMenu&&(this.highlightsView=ge(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var e=this.initialAnnotations.highlights||null;e&&this.annotator?.initAnnotations(e)}setTimeout(()=>{this.properties?.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)}hideAnnotationLayer(){let e=this.navigator.iframes[0].contentDocument;if(e){let t=ge(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.navigator.iframes[0].contentDocument;if(e){let t=ge(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.rights.enableAnnotations&&setTimeout(()=>{this.drawHighlights(),this.showHighlights(),te(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=ET.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.navigator.iframes[0].contentDocument;if(r){let l=function(h){try{let f=u.navigator.iframes[0].contentDocument;return f?Vi(h,f,Vo):""}catch(f){return Ir.default.log("uniqueCssSelector:"),Ir.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=to(o,l);if(s.removeAllRanges(),c){let h={rangeInfo:c},f=this.navigator.highlighter?.createHighlight(this.navigator.highlighter?.dom(r.body).getWindow(),h,i.highlight?.color,!0,2,i.icon,i.popup,i.highlight?.style);f&&this.saveAnnotation(f[0]).then(m=>{Ir.default.log("saved bookmark "+m.id)})}r.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(e){Ir.default.log("still need to scroll to "+e);var t=await this.annotator?.getAnnotationElement(e,this.navigator.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 Ir.default.log("Highlight deleted "+JSON.stringify(t)),Ir.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 Ir.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)}async addAnnotation(e){await this.annotator?.saveAnnotation(e),await this.showHighlights(),await this.drawHighlights()}async deleteHighlight(e){this.api?.deleteAnnotation?this.api?.deleteAnnotation(e).then(async()=>{this.deleteLocalHighlight(e.id)}):this.deleteLocalHighlight(e.id)}async deleteSelectedHighlight(e){this.api?.deleteAnnotation?this.api.deleteAnnotation(e).then(async()=>{this.deleteLocalHighlight(e.id)}):this.deleteLocalHighlight(e.id)}async updateAnnotation(e){this.api?.updateAnnotation?this.api.updateAnnotation(e).then(async()=>{this.updateLocalHighlight(e)}):this.updateLocalHighlight(e)}async saveAnnotation(e){if(this.annotator){var t=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let i=this.navigator.view?.getCurrentPosition(),r=this.navigator.iframes[0].contentDocument;if(r){let s=qs(r,"body"),o=e.position?e.position/s.scrollHeight:i,a=al(),u;if(t){let l=t.Href;if(l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let c=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),h=Math.ceil((o??0)*(c.length-1));u={...c[h],id:a,href:l,created:new Date,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}else u={id:a,href:l,locations:{progression:o},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}if(u)if(this.navigator.consumptionModule?.trackAction(u,"HighlightCreated"),this.api?.addAnnotation)try{let l=await this.api.addAnnotation(u),c=await this.annotator.saveAnnotation(l);return await this.showHighlights(),await this.drawHighlights(),new Promise(h=>h(c))}catch{await this.showHighlights(),await this.drawHighlights()}else{let l=await this.annotator.saveAnnotation(u);return 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=>{li.push(t.highlight)}))),this.highlightsView&&this.createTree(1,e,this.highlightsView)}async drawHighlights(){if(this.rights.enableAnnotations&&this.highlighter){if(this.api){let t=[];if(this.annotator&&(t=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&t&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(0);for(let i of t){li.push(i.highlight);let r=i,s=this.navigator.currentChapterLink.href;var e=this.publication.getTOCItem(s);if(this.navigator.currentTocUrl!==void 0&&(e=this.publication.getTOCItem(this.navigator.currentTocUrl)),e===null&&(e=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),e){let o=e.Href;o.indexOf("#")>0&&(o=o.slice(0,o.indexOf("#"))),r.href===o&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(r.highlight?.marker===1){let u='<div class="comment" style="top: '+await this.annotator?.getAnnotationPosition(i.id,this.navigator.iframes[0].contentWindow)+'px;width:20px"></div>',l=document.createElement("div");l.innerHTML=u;let c=l.childNodes[0],h=document.createElement("i");h.innerHTML="sticky_note_2",h.className="material-icons",h.style.color=r.highlight.color,c.appendChild(h),te(l,"click",f=>{f.preventDefault(),f.stopPropagation(),this.scrollToHighlight(r.id)})}},100))}}}}else{let t=[];if(this.annotator&&(t=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&t&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(0);for(let i of t){li.push(i.highlight);let r=i,s=this.navigator.currentChapterLink.href,o=this.publication.getTOCItem(s);if(this.navigator.currentTocUrl&&(o=this.publication.getTOCItem(this.navigator.currentTocUrl)),o===null&&(o=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),o){let a=o.Href;a.indexOf("#")>0&&(a=a.slice(0,a.indexOf("#"))),r.href===a&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(r.highlight?.marker===1){let l='<div class="comment" style="top: '+await this.annotator?.getAnnotationPosition(i.id,this.navigator.iframes[0].contentWindow)+"px;background: "+r.highlight?.color+';width:20px"></div>',c=document.createElement("div");c.innerHTML=l,c.childNodes[0].innerHTML=qr.note,te(c,"click",h=>{h.preventDefault(),h.stopPropagation(),this.scrollToHighlight(r.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){let e=this.navigator.iframes[0].contentDocument;if(e&&(this.commentGutter=e.getElementById("R2_ID_GUTTER_RIGHT_CONTAINER"),this.navigator.view?.isScrollMode()&&this.properties?.enableComments?this.commentGutter?.style.removeProperty("display"):this.commentGutter?.style.setProperty("display","none"),this.commentGutter&&this.navigator.view?.isScrollMode()&&this.properties?.enableComments)){this.commentGutter.innerHTML="";let t=[];this.annotator&&(t=this.annotator.getAnnotationsByChapter(this.navigator.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(ln)[0];let l=parseInt(a.style.height.replace("px","")),c=i.highlight.position,h=e.createElement("div");h.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");h.appendChild(f);let m=i.highlight.color;Xt.isHexColor(m)&&(m=Xt.hexToRgbChannels(m)),h.innerHTML=rl("","",'<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;`),h.appendChild(y),te(h,"click",g=>{g.preventDefault(),g.stopPropagation(),this.scrollToHighlight(i.highlight.id)}),this.commentGutter?.appendChild(h)})))}}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 h=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||"",h.appendChild(f)}else m.innerHTML=c.Title||"",m.className="chapter-title",h.appendChild(m);te(f,"click",g=>{g.preventDefault(),g.stopPropagation();let b={href:f.href,locations:{progression:0},type:c.TypeLink,title:f.title};this.navigator.stopReadAloud(),this.navigator.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 A=document.createElement("li");A.className="annotation-item";let v=document.createElement("a");if(v.setAttribute("href",g.href),e===1){v.className="highlight-link";let S=document.createElement("span"),C=document.createElement("span");if(S.className="title",C.innerHTML=g.highlight.selectionInfo.cleanText,g.highlight?.marker===1)if(typeof g.highlight?.color=="object"){let I=g.highlight?.color;I&&C.style.setProperty("border-bottom",`2px solid ${Xt.hexToRgbA(I)}`,"important")}else C.style.setProperty("border-bottom",`2px solid ${g.highlight?.color}`,"important");else if(typeof g.highlight?.color=="object"){let I=g.highlight?.color;I&&(C.style.backgroundColor=Xt.hexToRgbA(I))}else{let I=g.highlight?.color;I&&(C.style.backgroundColor=I)}S.appendChild(C),v.appendChild(S);let T=document.createElement("span"),M=Math.round((g.locations.progression??0)*100)+"% through resource";T.className="subtitle",T.innerHTML=M,v.appendChild(T)}let E=document.createElement("span");if(E.className="timestamp",E.innerHTML=n.readableTimestamp(g.created),v.appendChild(E),te(v,"click",S=>{S.preventDefault(),S.stopPropagation(),r.handleAnnotationLinkClick(S,g)}),A.appendChild(v),r.navigator.sideNavExpanded){let S=document.createElement("button");S.className="delete",S.innerHTML=qr.delete,te(S,"click",C=>{C.preventDefault(),C.stopPropagation(),r.handleAnnotationLinkDeleteClick(e,C,g)}),A.appendChild(S)}y.appendChild(A)}}),y.children.length>0&&(l.appendChild(h),l.appendChild(y)),l.children.length>0&&a.appendChild(l),c.Children&&c.Children.length>0&&o(a,c.Children)}};i.innerHTML="",o(i,s)}}}handleAnnotationLinkClick(e,t){t?(t.href=this.publication.getAbsoluteHref(t.href),this.navigator.stopReadAloud(),this.navigator.navigate(t)):Ir.default.log("annotation data missing: ",e)}handleAnnotationLinkDeleteClick(e,t,i){Ir.default.log("annotation data locator: ",i),i?e===1&&this.deleteHighlight(i):Ir.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.navigator.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(ln)[0];let c=parseInt(u.style.top.replace("px","")),h={...s,highlight:{...s.highlight,position:c}};return[...r,h]};return e.reduce(i,[])}reposition(e){let t=this.navigator.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(ln)[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,A=b>m?b:m,v={...s,highlight:{...s.highlight,position:A}};return[...r,v]};return e.sort(function(r,s){return r.highlight.position-s.highlight.position}).reduce(i,[])}};_();ui();yn();Ad();var Pr=Qe(Qt());var cl=class n{static async create(e){let t=new this(e.annotator,e.rights||{enableBookmarks:!1},e.publication,e,e.initialAnnotations,e.api,e.headerMenu);return await t.start(),new Promise(i=>i(t))}constructor(e,t,i,r,s,o,a){this.annotator=e,this.rights=t,this.publication=i,this.headerMenu=a,this.initialAnnotations=s,this.properties=r,this.api=o}stop(){Pr.default.log("Bookmark module stop")}async start(){if(this.headerMenu&&(this.bookmarksView=ge(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=ge(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let e=ge(this.headerMenu,"#menu-button-bookmark");e&&e.parentElement?.style.removeProperty("display"),e&&te(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.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)},100)}initialize(){return new Promise(async e=>{await document.fonts.ready,this.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 Pr.default.log("Bookmark deleted "+JSON.stringify(t)),await this.showBookmarks(),await this.drawBookmarks(),t}else{let t=await this.annotator.deleteBookmark(e);return Pr.default.log("Bookmark deleted "+JSON.stringify(t)),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.navigator.currentChapterLink.href);if(this.navigator.currentTocUrl&&(e=this.publication.getTOCItem(this.navigator.currentTocUrl)),e===void 0&&(e=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),e){let t=e.Href;t.indexOf("#")>0&&(t=t.slice(0,t.indexOf("#")));let i=this.navigator.view?.getCurrentPosition(),r=al(),s;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let o=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),a=Math.ceil((i??0)*(o.length-1));s={...o[a],id:r,href:t,created:new Date,title:this.navigator.currentChapterLink.title}}else s={id:r,href:t,locations:{progression:i},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title};if(!this.annotator.locatorExists(s,0))if(this.navigator.consumptionModule?.trackAction(s,"BookmarkCreated"),this.api?.addBookmark){let o=await this.api.addBookmark(s);o&&(s=o),Pr.default.log(s);let a=this.annotator.saveBookmark(s);return Pr.default.log("Bookmark added "+JSON.stringify(a)),this.showBookmarks(),await this.drawBookmarks(),a}else{let o=this.annotator.saveBookmark(s);return Pr.default.log("Bookmark added "+JSON.stringify(o)),this.showBookmarks(),await this.drawBookmarks(),o}}}}async addBookmarkPlus(){let e=this,t=this.navigator.highlighter?.visibleTextRects[0],i=this.navigator.iframes[0].contentDocument;if(i){let a=this.navigator.highlighter?.dom(i.body).getWindow().document.createRange(),u=this.navigator.highlighter?.dom(this.navigator.iframes[0].contentDocument?.body).getSelection();u.removeAllRanges(),t&&a.selectNodeContents(t.node),u.addRange(a);let l=bp(a,!1),c=0;for(let h of l){if(!this.navigator.highlighter?.isOutsideViewport(h)){let f=u.focusNode,m=u.focusOffset;u.collapse(u.anchorNode,u.anchorOffset);for(let A=0;A<c;A++)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.navigator.iframes[0].contentDocument;if(l)return Vi(a,e.navigator.highlighter?.dom(l.body).getDocument(),u)}let s=this.navigator.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=As(s,r);if(a===void 0){let l=e.navigator.iframes[0].contentDocument;a=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(l)??void 0}let u=e.navigator.iframes[0].contentDocument;if(a&&u){let l=this.navigator.highlighter?.createHighlight(this.navigator.highlighter?.dom(u.body).getWindow(),a,o.highlight?.color,!0,2,o.icon,o.popup,o.highlight?.style);if(this.navigator.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),l)return this.saveAnnotation(l[0]).then(c=>{Pr.default.log("saved bookmark "+c?.id)})}}}async saveAnnotation(e){if(this.annotator){var t=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let i=this.navigator.view?.getCurrentPosition(),r=this.navigator.iframes[0].contentDocument;if(r){let s=qs(r,"body"),o=e.position?e.position/s.scrollHeight:i,a=al(),u;if(t){let l=t.Href;if(l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let c=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),h=Math.ceil((o??0)*(c.length-1));u={...c[h],id:a,href:l,created:new Date,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}else u={id:a,href:l,locations:{progression:o},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}if(u)if(this.navigator.consumptionModule?.trackAction(u,"BookmarkCreated"),this.api?.addBookmark){let l=await this.api.addBookmark(u),c=await this.annotator.saveAnnotation(l);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(h=>h(c))}else{let l=await this.annotator.saveAnnotation(u);return 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.rights.enableBookmarks&&this.navigator.highlighter)if(this.api){let t=[];if(this.annotator&&(t=await this.annotator.getAnnotations()),this.navigator.highlighter&&t&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.navigator.highlighter.destroyHighlights(0);for(let i of t){li.push(i.highlight);let r=i,s=this.navigator.currentChapterLink.href;var e=this.publication.getTOCItem(s);if(this.navigator.currentTocUrl&&(e=this.publication.getTOCItem(this.navigator.currentTocUrl)),e===void 0&&(e=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),e){let o=e.Href;o.indexOf("#")>0&&(o=o.slice(0,o.indexOf("#"))),r.href===o&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight)}}}}else{let t=[];if(this.annotator&&(t=await this.annotator.getAnnotations()),this.navigator.highlighter&&t&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.navigator.highlighter.destroyHighlights(0);for(let i of t){li.push(i.highlight);let r=i,s=this.navigator.currentChapterLink.href,o=this.publication.getTOCItem(s);if(this.navigator.currentTocUrl&&(o=this.publication.getTOCItem(this.navigator.currentTocUrl)),o===void 0&&(o=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),o){let a=o.Href;a.indexOf("#")>0&&(a=a.slice(0,a.indexOf("#"))),r.href===a&&await this.navigator.highlighter.createHighlightDom(this.navigator.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 Pr.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 h=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||"",h.appendChild(f)}else m.innerHTML=c.Title||"",m.className="chapter-title",h.appendChild(m);te(f,"click",g=>{g.preventDefault(),g.stopPropagation();let b={href:f.href,locations:{progression:0},type:c.TypeLink,title:f.title};this.navigator.stopReadAloud(),this.navigator.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 A=document.createElement("li");A.className="annotation-item";let v=document.createElement("a");if(v.setAttribute("href",g.href),e===0){v.className="bookmark-link";let S=document.createElement("span"),C=Math.round((g.locations.progression??0)*100)+"% through resource";S.className="title",S.innerHTML=C,v.appendChild(S)}let E=document.createElement("span");if(E.className="timestamp",E.innerHTML=n.readableTimestamp(g.created),v.appendChild(E),te(v,"click",S=>{S.preventDefault(),S.stopPropagation(),r.handleAnnotationLinkClick(S,g)}),A.appendChild(v),r.navigator.sideNavExpanded){let S=document.createElement("button");S.className="delete",S.innerHTML=qr.delete,te(S,"click",C=>{C.preventDefault(),C.stopPropagation(),r.handleAnnotationLinkDeleteClick(e,C,g)}),A.appendChild(S)}y.appendChild(A)}}),y.children.length>0&&(l.appendChild(h),l.appendChild(y)),l.children.length>0&&a.appendChild(l),c.Children&&c.Children.length>0&&o(a,c.Children)}};i.innerHTML="",o(i,s)}}}handleAnnotationLinkClick(e,t){t?(t.href=this.publication.getAbsoluteHref(t.href),this.navigator.stopReadAloud(),this.navigator.navigate(t)):Pr.default.log("bookmark data missing: ",e)}handleAnnotationLinkDeleteClick(e,t,i){Pr.default.log("bookmark data locator: ",i),i?e===0&&this.deleteBookmark(i):Pr.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)}};_();var zy=Qe(CT());_();ui();yn();var Nn=Qe(Qt()),Ky="r2-mo-active",nn=class nn{};nn.COLOR_REF="color",nn.AUTO_SCROLL_REF="autoscroll",nn.AUTO_TURN_REF="autoturn",nn.VOLUME_REF="volume",nn.RATE_REF="rate",nn.COLOR_KEY="mediaoverlay-"+nn.COLOR_REF,nn.AUTO_SCROLL_KEY="mediaoverlay-"+nn.AUTO_SCROLL_REF,nn.AUTO_TURN_KEY="mediaoverlay-"+nn.AUTO_TURN_REF,nn.VOLUME_KEY="mediaoverlay-"+nn.VOLUME_REF,nn.RATE_KEY="mediaoverlay-"+nn.RATE_REF;var Je=nn,wp=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(),Nn.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,Nn.default.log(t.color)),i?.autoScroll&&(t.autoScroll=i.autoScroll,Nn.default.log(t.autoScroll)),i?.autoTurn&&(t.autoTurn=i.autoTurn,Nn.default.log(t.autoScroll)),i?.volume&&(t.volume=i.volume,Nn.default.log(t.volume)),i?.rate&&(t.rate=i.rate,Nn.default.log(t.rate)),i?.wait&&(t.wait=i.wait,Nn.default.log(t.wait))}return t.initializeSelections(),t}stop(){Nn.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(Je.AUTO_SCROLL_KEY)!=null?this.getProperty(Je.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(Je.AUTO_TURN_KEY)!=null?this.getProperty(Je.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(Je.COLOR_KEY)!=null?this.getProperty(Je.COLOR_KEY).value:this.color,this.volume=this.getProperty(Je.VOLUME_KEY)!=null?this.getProperty(Je.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(Je.RATE_KEY)!=null?this.getProperty(Je.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=ge(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechAutoTurn=ge(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=ge(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=ge(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=ge(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()),te(ge(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(Je.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Je.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(Je.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(Je.VOLUME_REF)?.value,rate:this.userProperties.getByRef(Je.RATE_REF)?.value};this.applyMediaOverlaySettings(e),this.api?.updateSettings&&this.api?.updateSettings(e).then(async t=>{Nn.default.log("api updated sync settings",t)})}getMediaOverlaySettings(){let e=new ds;return e.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,Je.AUTO_SCROLL_REF,Je.AUTO_SCROLL_KEY),e.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,Je.AUTO_TURN_REF,Je.AUTO_TURN_KEY),e.addStringable(this.color,Je.COLOR_REF,Je.COLOR_KEY),e.addIncremental(this.volume,.1,1,.1,"",Je.VOLUME_REF,Je.VOLUME_KEY),e.addIncremental(this.rate,.1,3,.1,"",Je.RATE_REF,Je.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(Je.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){Nn.default.log("autoScroll "+this.autoScroll),this.autoScroll=e.autoScroll;let t=this.userProperties.getByRef(Je.AUTO_SCROLL_REF);t&&(t.value=this.autoScroll,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoTurn!==void 0){Nn.default.log("autoTurn "+this.autoTurn),this.autoTurn=e.autoTurn;let t=this.userProperties.getByRef(Je.AUTO_TURN_REF);t&&(t.value=this.autoTurn,this.saveProperty(t)),this.settingsChangeCallback()}if(e.volume){Nn.default.log("volume "+this.volume),this.volume=e.volume;let t=this.userProperties.getByRef(Je.VOLUME_REF);t&&(t.value=this.volume,this.saveProperty(t)),this.settingsChangeCallback()}if(e.rate){Nn.default.log("rate "+this.rate),this.rate=e.rate;let t=this.userProperties.getByRef(Je.RATE_REF);t&&(t.value=this.rate,this.saveProperty(t)),this.settingsChangeCallback()}}applyMediaOverlaySetting(e,t){if(e===Je.COLOR_REF){this.color=t;let i=this.userProperties.getByRef(Je.COLOR_REF);i&&(i.value=this.color,this.saveProperty(i)),this.settingsChangeCallback()}else if(e===Je.AUTO_SCROLL_REF){this.autoScroll=t;let i=this.userProperties.getByRef(Je.AUTO_SCROLL_REF);i&&(i.value=this.autoScroll,this.saveProperty(i)),this.settingsChangeCallback()}else if(e===Je.AUTO_TURN_REF){this.autoTurn=t;let i=this.userProperties.getByRef(Je.AUTO_TURN_REF);i&&(i.value=this.autoTurn,this.saveProperty(i)),this.settingsChangeCallback()}}increase(e){if(e==="mo_volume"){this.userProperties.getByRef(Je.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(Je.VOLUME_REF)?.value;let t=this.userProperties.getByRef(Je.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(Je.RATE_REF).increment(),this.rate=this.userProperties.getByRef(Je.RATE_REF)?.value;let t=this.userProperties.getByRef(Je.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback()}}decrease(e){if(e==="mo_volume"){this.userProperties.getByRef(Je.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(Je.VOLUME_REF)?.value;let t=this.userProperties.getByRef(Je.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(Je.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(Je.RATE_REF)?.value;let t=this.userProperties.getByRef(Je.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback()}}};ui();var He=Qe(Qt()),hl=class{constructor(e,t,i){this.play=ge(document,"#menu-button-play");this.pause=ge(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async e=>{He.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}static create(e){let t=new this(e.publication,e.settings,e);return t.start(),t}stop(){He.default.log("MediaOverlay module stop")}start(){He.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?.Properties?.MediaOverlay){this.ensureOnTimeUpdate(!1,!1);let t=e.Properties?.MediaOverlay,r=new URL(t,this.publication.manifestUrl).toString(),s;try{s=await fetch(r,this.navigator.requestConfig)}catch(l){console.error(l,r);return}s.ok||He.default.log("BAD RESPONSE?!");let o;try{o=await s.json()}catch(l){console.error(l)}if(!o){He.default.log("## moJson"+o);return}e.MediaOverlays=Sa(o,zy.MediaOverlayNode),e.MediaOverlays.initialized=!0;let a=e.HrefDecoded||e.Href,u=new URL("https://dita.digital/"+a);await this.playMediaOverlays(u.pathname.substr(1),e.MediaOverlays,void 0)}else this.audioElement&&await this.audioElement.pause(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement&&await this.audioElement.pause(),this.navigator.nextResource()):await this.stopReadAloud()}bindClickHandler(){this.unbindClickHandler();let e=this.handleContentClick.bind(this);this.clickHandler=e;for(let t of this.navigator.iframes)t.contentDocument?.body?.addEventListener("click",e)}unbindClickHandler(){let e=this.clickHandler;if(e){for(let t of this.navigator.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 h=0;h<this.navigator.iframes.length;h++)if(this.navigator.iframes[h].contentDocument===r){s=h;break}let o=this.currentLinks[s];if(!o)return;if(s!==this.currentLinkIndex||!this.mediaOverlayRoot){if(!o.MediaOverlays?.initialized)if(o.Properties?.MediaOverlay){let h=o.Properties.MediaOverlay,f=new URL(h,this.publication.manifestUrl);try{let m=await fetch(f.toString(),this.navigator.requestConfig);if(m.ok){let y=await m.json();y&&(o.MediaOverlays=Sa(y,zy.MediaOverlayNode),o.MediaOverlays.initialized=!0)}}catch{He.default.log("handleContentClick() - failed to load MO for clicked page");return}}else return;this.currentLinkIndex=s,this.mediaOverlayRoot=o.MediaOverlays}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.navigator.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement&&this.currentLinks[this.currentLinkIndex]?.Properties?.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.navigator.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"),this.bindClickHandler()}}async stopReadAloud(){this.navigator.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.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"))}findDepthFirstTextAudioPair(e,t,i){He.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(He.default.log("isFragmentIDMatch: "+s),He.default.log("isTextUrlMatch: "+r),!t.Children||!t.Children.length){if(He.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!r){He.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return s||r&&!i?(He.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),t):void 0}let o=i,a=i;for(let u of t.Children){He.default.log("findDepthFirstTextAudioPair() - child"),He.default.log(JSON.stringify(u));let l=this.findDepthFirstTextAudioPair(e,u,a);if(l===null&&(He.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),a=void 0),l)return He.default.log("findDepthFirstTextAudioPair() - child - match"),He.default.log(JSON.stringify(l)),l}if(s){He.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let u=this.findDepthFirstTextAudioPair(e,t,void 0);return u&&(He.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),He.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&&(He.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(He.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let t=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!e);if(!t)He.default.log("mediaOverlaysNext() - navLeftOrRight()"),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.navigator.nextResource()):this.stopReadAloud());else{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&&(He.default.log("mediaOverlaysNext() SWITCH! "+r.pathname+" != "+s.pathname),i=!0)}i?this.mediaOverlaysStop():(He.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(t,void 0,void 0)},0))}}else He.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.navigator.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){He.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){He.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 He.default.log("findNextTextAudioPair() - prevMo === moToMatch"),e;He.default.log("findNextTextAudioPair() - set previous"),He.default.log(JSON.stringify(e)),i.prev=e;return}for(let s of e.Children){He.default.log("findNextTextAudioPair() - child"),He.default.log(JSON.stringify(s));let o=this.findNextTextAudioPair(s,t,i,r);if(o)return He.default.log("findNextTextAudioPair() - match"),He.default.log(JSON.stringify(o)),o}}async playMediaOverlaysAudio(e,t,i){if(He.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 h=r.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(h&&h.length>=1){let f=h[1];try{this.currentAudioBegin=parseFloat(f)}catch(m){He.default.error(m)}if(h.length>=3){let m=h[3];try{this.currentAudioEnd=parseFloat(m)}catch(y){He.default.error(y)}}}}}else this.currentAudioBegin=t,this.currentAudioEnd=i;He.default.log(`${s} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let c=async h=>{if(!this.audioElement)return;let f=this.currentAudioBegin?this.currentAudioBegin:0;if(h||this.audioElement.paused)if(h&&!f||this.audioElement.currentTime===f){if(He.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{He.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let m=async y=>{if(this.audioElement.removeEventListener("timeupdate",m),He.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?He.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(He.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=f)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||a!==this.currentAudioUrl){this.currentAudioUrl=a,He.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=>{He.default.log("-1) error: "+(this.currentAudioUrl!==m.currentTarget.src?this.currentAudioUrl+" -- ":"")+m.currentTarget.src.substr(m.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(He.default.log(this.audioElement.error.code),He.default.log(this.audioElement.error.message))});let h=async m=>{m.currentTarget.removeEventListener("canplaythrough",h),He.default.log("oncanplaythrough"),await c(!0)};this.audioElement.addEventListener("canplaythrough",h);let f=async m=>{He.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.navigator.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",f),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else He.default.log("playMediaOverlaysAudio() - playClip()"),await c(!1)}async playMediaOverlays(e,t,i){He.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&&(He.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),He.default.log(JSON.stringify(r,null,4)),He.default.log(JSON.stringify(t,null,4)),s=this.findDepthFirstTextAudioPair(e,t,void 0)),s?s.Audio&&(He.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=t,await this.playMediaOverlaysAudio(s,void 0,void 0)):He.default.log("playMediaOverlays() - !moTextAudioPair "+e)}mediaOverlayHighlight(e){He.default.log("moHighlight: ## "+e);let t=this.publication.Metadata?.MediaOverlay?.ActiveClass;t||(t=this.settings.color);let i=this.navigator.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.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&(t=r||s?Ky:t||Ky),this.pid)for(let a of this.navigator.iframes){let u=a.contentDocument?.getElementById(this.pid);u&&u.classList.remove(t)}let o;e&&(this.currentLinkIndex===0?o=this.navigator.iframes[0].contentDocument?.getElementById(e):o=this.navigator.iframes[1].contentDocument?.getElementById(e),o&&o.classList.add(t),this.pid=e),o&&(this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&o.scrollIntoView({block:"center",behavior:"smooth"})}};_();ui();yn();var qy=Qe(Qt()),fl=class{static async create(e){let t=new this(e.publication);return await t.start(),t}constructor(e){this.publication=e}async stop(){qy.default.log("Timeline module stop")}async start(){this.timelineContainer=ge(document,"#container-view-timeline"),this.positionSlider=ge(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.navigator.currentLocator();(this.navigator.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.navigator.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)}te(l,"click",h=>{h.preventDefault(),h.stopPropagation();var f;this.publication.positions||this.navigator.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.TypeLink,title:i.Title},qy.default.log(f),this.navigator.navigate(f)}),a===this.navigator.currentChapterLink.href?l.className+=" active":l.className=l.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(l)}),e()})}};_();ui();yn();var BA=Qe(eo());_();var ST=Qe(Qt());function _T(n,e){return new Promise(function(t){setTimeout(t.bind(null,e),n)})}var bY=!1;ST.default.setLevel(bY?"trace":"warn",!0);var t1=Qe(xT()),rn=Qe(Qt());_();var QP=Qe(x9(),1),$r=Qe(GP(),1);_();var WP=[{regex:/IE (\d+)\.(\d+)/,family:"ie",maxVersion:[7,1/0,1/0]},{regex:/Trident\/4\.0/,family:"ie",version:[8,0,0]},{regex:/Trident\/5\.0/,family:"ie",version:[9,0,0]},{regex:/Trident\/6\.0/,family:"ie",version:[10,0,0]},{regex:/Trident\/[78]\.0/,family:"ie",version:[11,0,0]},{regex:/Edge?\/(\d+)\.(\d+)(\.(\d+)|)/,family:"edge"},{regex:/Firefox\/(\d+)\.(\d+)(\.(\d+)|)/,family:"firefox"},{regex:/Chrom(ium|e)\/(\d+)\.(\d+)(\.(\d+)|)/,family:"chrome"},{regex:/Chrom(ium|e)\/(\d+)\.(\d+)(\.(\d+)|)([\d.]+$|.*Safari\/(?![\d.]+ Edge\/[\d.]+$))/,family:"chrome",maxVersion:[70,1/0,1/0]},{regex:/(Maci|X11).+ Version\/(\d+)\.(\d+)([.,](\d+)|)( \(\w+\)|)( Mobile\/\w+|) Safari\//,family:"safari"},{regex:/Opera\/9\.80.+Version\/(\d+)\.(\d+)(\.(\d+)|)/,family:"opera",maxVersion:[12,15,0]},{regex:/Chrome.+OPR\/(\d+)\.(\d+)\.(\d+)/,family:"opera",minVersion:[15,0,0]},{regex:/(CPU[ +]OS|iPhone[ +]OS|CPU[ +]iPhone|CPU IPhone OS|CPU iPad OS)[ +]+(\d+)[_.](\d+)([_.](\d+)|)/,family:"ios_saf"},{regex:/[^e] (CPU[ +]OS|iPhone[ +]OS|CPU[ +]iPhone|CPU IPhone OS|CPU iPad OS)[ +]+(\d+)[_.](\d+)([_.](\d+)|)/,family:"ios_saf",version:[7,0,3]},{regex:/Opera Mini/,family:"op_mini"},{regex:/Android Donut/,family:"android",version:[1,2,0]},{regex:/Android Eclair/,family:"android",version:[2,1,0]},{regex:/Android Froyo/,family:"android",version:[2,2,0]},{regex:/Android Gingerbread/,family:"android",version:[2,3,0]},{regex:/Android Honeycomb/,family:"android",version:[3,0,0]},{regex:/Android:?[ /-](\d+)(\.(\d+)|)(\.(\d+)|)/,family:"android"},{regex:/Android:?[ /-](\d+)(\.(\d+)|)(\.(\d+)|);(?! ARM; Trident)/,family:"android",version:[4,0,0]},{regex:/PlayBook.+RIM Tablet OS (\d+)\.(\d+)\.(\d+)/,family:"bb"},{regex:/(Black[bB]erry|BB10).+Version\/(\d+)\.(\d+)\.(\d+)/,family:"bb"},{regex:/Opera\/.+Opera Mobi.+Version\/(\d+)\.(\d+)/,family:"op_mob",maxVersion:[12,16,0]},{regex:/Mobile Safari.+OPR\/(\d+)\.(\d+)\.(\d+)/,family:"op_mob",minVersion:[14,0,0]},{regex:/Android.+Firefox\/(\d+)\.(\d+)(\.(\d+)|)/,family:"and_ff"},{regex:/Android.+Chrom(ium|e)\/(\d+)\.(\d+)(\.(\d+)|)/,family:"and_chr"},{regex:/IEMobile[ /](\d+)\.(\d+)/,family:"ie_mob"},{regex:/Android.+(UC? ?Browser|UCWEB|U3)[ /]?(\d+)\.(\d+)\.(\d+)/,family:"and_uc"},{regex:/SamsungBrowser\/(\d+)\.(\d+)/,family:"samsung"},{regex:/Android.+MQQBrowser\/(\d+)(\.(\d+)|)(\.(\d+)|)/,family:"and_qq"},{regex:/baidubrowser[/\s](\d+)(\.(\d+)|)(\.(\d+)|)/,family:"baidu"},{regex:/K[Aa][Ii]OS\/(\d+)\.(\d+)(\.(\d+)|)/,family:"kaios"}];function MA(n){return typeof n=="number"?n:n.length===1?n[0]:[n[0],n[n.length-1]]}var Li;(function(n){n[n.Major=0]="Major",n[n.Minor=1]="Minor",n[n.Patch=2]="Patch"})(Li||(Li={}));function VP(n){let e=Array.isArray(n)?n:n.toString().split(".");if(e[0]==="all")return[1/0,0,0];let t=null,i=null,r=[0,0,0];for(let s=0;s<3;s++)if(t=e[s],!(typeof t>"u")){if(i=typeof t=="number"?t:parseInt(t,10),isNaN(i))return null;r[s]=i}return r}function AQ(n,e){let t=0,i=[];for(let r=2;r>=0;r--)if(n[r]!==e[r]){t=r;break}for(let r=n[t],s=e[t];r<=s;r++)i.push(n.map((o,a)=>a===t?r:o));return i}function KP(n,e,t){let[i,r,s]=n,[o,a,u]=e,{ignoreMinor:l,ignorePatch:c,allowHigherVersions:h}=t;if(o===1/0)return!0;let f=!l,m=f&&!c;return h?m&&s<u||f&&r<a?!1:i>=o:m&&s!==u||f&&r!==a?!1:i===o}function vQ(n,e){let{ignoreMinor:t,ignorePatch:i,allowZeroSubversions:r}=e,s=t?1:i?2:3;if(r)for(let o=s-1;o>0&&!(n[o]!==0||s===1);o--)s--;return s}function wQ(n){return n.reduce((e,t)=>{let[i,r,s]=t.split(/ |-/),o=VP(r);return(o?s?AQ(o,VP(s)):[o]:[]).reduce((u,l)=>(l&&u.push({family:i,version:l}),u),e)},[])}function EQ(n={}){let{browsers:e,...t}=n,i=(0,QP.default)(e,t);return wQ(i)}function CQ(n,e,t=0){let i=n.length;for(let r=t;r<i;r++)if(n[r]!==e[r])return!1;return!0}function XP(n){if(n===null||typeof n!="object")return n;let e=Array.isArray(n)?[]:{},t;for(t in n)e[t]=XP(n[t]);return e}function Zp(n){return[].concat(...n)}function SQ(n){let e=new Map;return n.forEach(({family:t,version:i})=>{let r=e.get(t);if(r){let s=i.join(".");r.every(o=>o.join(".")!==s)&&r.push(i);return}e.set(t,[i])}),e.forEach(t=>{t.sort((i,r)=>{for(let s in i)if(i[s]!==r[s])return i[s]-r[s];return 0})}),e}function _Q(n){if(n.length<2)return n;let e=n.length+1,t=[],i=null,r=n[0],s=[r[Li.Major]],o=[r[Li.Minor]],a=[r[Li.Patch]],u=null;for(let l=1;l<e;l++){i=n[l-1],r=n[l]||[];for(let c=Li.Major;c<=Li.Patch;c++){if((c===u||u===null)&&i[c]+1===r[c]&&CQ(i,r,c+1)){u=c,c===Li.Major?s.push(r[Li.Major]):s=r[Li.Major],c===Li.Minor?o.push(r[Li.Minor]):o=r[Li.Minor],c===Li.Patch?a.push(r[Li.Patch]):a=r[Li.Patch];break}if(u===c||i[c]!==r[c]){t.push([MA(s),MA(o),MA(a)]),s=[r[Li.Major]],o=[r[Li.Minor]],a=[r[Li.Patch]],u=null;break}}}return t}function xQ(n){return{type:"RegExp",body:n,flags:""}}function lo(...n){let e=Zp(n).filter(Boolean);return e.length===1?e[0]:{type:"Alternative",expressions:e}}function Mr(n){return{type:"Char",kind:"simple",value:String(n),codePoint:NaN}}function TQ(n){return{type:"Char",kind:"meta",value:n,codePoint:NaN}}function ZP(n,e){return{type:"ClassRange",from:n,to:e}}function LA(...n){return{type:"CharacterClass",expressions:Zp(n).filter(Boolean)}}function IQ(n){return{type:"Quantifier",kind:n,greedy:!0}}function PQ(n,e){return{type:"Quantifier",kind:"Range",from:n,to:e,greedy:!0}}function eM(n){return{type:"Group",capturing:!0,expression:n,number:null}}function MQ(n,e){return{type:"Repetition",expression:n,quantifier:e}}function LQ(...n){let e=Zp(n).filter(Boolean);if(e.length===1)return e[0];let t={type:"Disjunction",left:null,right:e.pop()};return e.reduceRight((i,r,s)=>s===0?(i.left=r,i):(i.left={type:"Disjunction",left:null,right:r},i.left),t),t}function e1(...n){let e=LQ(...n);return e.type==="Disjunction"?eM(e):e}function Sl(){return TQ("\\d")}function Cl(n=IQ("+")){return MQ(Sl(),n)}function zP(n){return lo(Array.from(String(n),Mr))}function Xp(n){if(n.type==="Group"&&n.expression.type==="Repetition"){let{expression:e,quantifier:t}=n.expression;return e.type==="Char"&&e.value==="\\d"&&t.kind==="+"&&t.greedy}return!1}function El(n,e){return n&&n.type==="Char"?typeof e>"u"||e instanceof RegExp&&e.test(n.value)||String(e)===n.value:!1}function qP(n){if(n.type==="CharacterClass"&&n.expressions.length===1){let[e]=n.expressions;return e.type==="ClassRange"&&El(e.from,/\d/)&&El(e.to,/\d/)}return!1}function YP(n){return n.type!=="RegExp"&&n.type!=="ClassRange"&&n.type!=="Quantifier"}function _l(n){return typeof n=="string"?$r.default.parse(n.replace(/^([^/])/,"/$1").replace(/([^/])$/,"$1/")):n instanceof RegExp?$r.default.parse(n):n}function RQ(n){return typeof n=="string"?new RegExp(n):new RegExp($r.default.generate(n.body),n.flags)}function kQ(n){return typeof n=="string"?n:n instanceof RegExp?n.toString():$r.default.generate(n)}var OQ=["RegExp","Disjunction","Alternative","Assertion","Char","CharacterClass","ClassRange","Backreference","Group","Repetition","Quantifier"];function OA(n){let{every:e}=n;return e?typeof e=="function"?{"*":e,...n}:OQ.reduce((t,i)=>{let r=n[i],s=r?"pre"in r?r.pre:r:null,o=r&&"post"in r?r.post:null;return t[i]={pre(a){return e.pre(a)!==!1&&s?s(a):!0},post(a){return e.post(a)!==!1&&o?o(a):!0}},t},{}):n}function BQ(n){let e=$r.default.optimize(_l(kQ(n))).getAST();return $r.default.traverse(e,{Group(t){let{parent:i,node:r}=t,{expression:s}=r;r.capturing=!0,(i.type==="RegExp"||s.type!=="Disjunction"&&i.type!=="Repetition"||s.type==="Disjunction"&&i.type==="Disjunction")&&t.replace(t.node.expression)}}),e}function NQ(n,e){return El(n)&&El(e)&&n.value===e.value?e:El(n,/\d/)&&qP(e)&&Number(e.expressions[0].from.value)-Number(n.value)===1?{...e,expressions:[{...e.expressions[0],from:n}]}:qP(n)&&El(e,/\d/)&&Number(e.value)-Number(n.expressions[0].to.value)===1?{...n,expressions:[{...n.expressions[0],to:e}]}:null}function DQ(n){return n.reduce((e,t)=>{let i=e[e.length-1];if(i&&t.type==="Alternative"&&i.type==="Alternative"&&t.expressions.length===i.expressions.length){let r=i.expressions.reduceRight((s,o,a)=>{if(!s)return s;let u=NQ(o,t.expressions[a]);if(u)s.unshift(u);else return null;return s},[]);r&&(t.expressions=r,e.pop())}return e.push(t),e},[])}function RA(n){return Array.from(n.toString(),Number)}function JP(n,e){let t=n+ +!e;return t===0?Sl():t===9?Mr("9"):t>9?null:LA(ZP(Mr(t),Mr("9")))}function FQ(n){if(n===0)return[Cl()];let e=RA(n),t=e.length,i=Cl(PQ(t+1)),r=t-1;if(n/Math.pow(10,r)===e[0])return[lo(JP(e[0],!0),Array.from({length:r},Sl)),i];let o=e.reduce((a,u,l)=>{let c=t-l-1,h=l===0,f=Mr(""),m=e.reduce((y,g,b)=>{if(b<c)y.push(Mr(g));else if(f)if(b>c)y.push(Sl());else if(f=JP(g,h),f)y.push(f);else return[];return y},[]);return m.length&&a.push(m),a},[]).map(a=>lo(a));return o.push(i),o}function wl(n,e,t){if(e<n)return null;let i=Mr(n),r=Mr(e),s=typeof t=="number"&&t>0?Array.from({length:t},()=>Mr(0)):[],o=s.length?a=>lo(s,a):a=>a;return n===e?o(i):n===0&&e===9?o(Sl()):e-n===1?o(LA(i,r)):o(LA(ZP(i,r)))}function HQ(n,e){let t=[],i=n,r=1;do r*=10,i<r&&(t.push([i,Math.min(r-1,e)]),i=r);while(r<=e);return t}function UQ(n,e){let t=n.length;if(t!==e.length||n[0]!==e[0])return null;let i=n[0].toString(),r=0,s=0,o="",a="";for(let u=1;u<t;u++)r=n[u],s=e[u],r===s&&o===""&&a===""?i+=r:(o+=r,a+=s);return[i,parseInt(o,10),parseInt(a,10)]}function kA(n,e,t=0){let i=RA(n),r=i.length;if(n<10&&e<10||n===e){let c=t-r;return[wl(n,e,c)]}let s=RA(e);if(r!==s.length){let c=HQ(n,e);return Zp(c.map(([f,m])=>kA(f,m,t)))}let o=UQ(i,s);if(Array.isArray(o)){let[c,h,f]=o,m=r-c.length,y=kA(h,f,m);return[lo(Array.from(c,Mr),e1(y))]}let a=Array.from({length:r-1}),u=wl(i[0]+1,s[0]-1),l=[...a.map((c,h)=>{let f=r-h-1,m=+(h>0);return lo(i.map((y,g)=>g<f?Mr(y):g>f?wl(0,9):wl(y+m,9)))}),...u?[lo(u,Array.from({length:r-1},()=>Sl()))]:[],...a.map((c,h)=>{let f=r-h-1,m=+(h>0);return lo(s.map((y,g)=>g<f?Mr(y):g>f?wl(0,9):wl(0,y-m)))})];return DQ(l)}function $P(n,e=1/0){if(n===1/0)return Cl();let t=e===1/0?FQ(n):kA(n,e);return e1(t)}function jQ(n,e,t,i){let r={...i,allowHigherVersions:!0},s=u=>KP(u,n,r),o=u=>KP(e,u,r),a=n&&e?u=>s(u)&&o(u):n?s:e?o:()=>!0;return t.filter(a)}function GQ(n,e,t=WP){let i=[],r="",s=!1;return t.forEach(o=>{let a=n.get(o.family);if(!a)return;let{version:u,minVersion:l,maxVersion:c}=o;u&&(l=u,c=u);let h=jQ(l,c,a,e);h.length&&(r===o.family&&s&&(u=void 0,l=void 0,c=void 0,h=a,i.pop()),i.push({...o,version:u,minVersion:l,maxVersion:c,requestVersions:a,matchedVersions:h})),s=!u&&!l&&!c,r=o.family}),i}function WQ(n){let e=n.map(({regexAst:i})=>eM(i.body)),t=BQ(xQ(e1(e)));return RQ(t)}function VQ(n){let e=_l(n),t=0;return $r.default.traverse(e,{Group(i){Xp(i.node)&&t++}}),t}function KQ(n,e,t){let i=_l(n),r=typeof t=="number"&&t<e.length?e.slice(0,t):e.slice();return $r.default.traverse(i,OA({every(){return!!r.length},Group(s){return Xp(s.node)&&r.length?(i===s.node?i=r.shift():s.replace(r.shift()),!1):!0}})),i}function tM(n,e){let t=_l(n),i=Math.min(VQ(t),e||1/0),r=[],s=0,o=!1;return $r.default.traverse(t,OA({every:{pre({node:a,parent:u}){return a===t?!0:YP(a)?(u===t&&(o=!1),s<i):!1},post({node:a,parent:u}){a!==t&&u===t&&YP(a)&&(o||s>0&&s<i)&&r.push(a)}},Group(a){return Xp(a.node)&&s<i?(o=!0,s++,!1):!0}})),r.length===1&&!Xp(r[0])?tM(r[0],i):r}function zQ(n,e){let{ignoreMinor:t,ignorePatch:i,allowHigherVersions:r}=e,s=n[0]===1/0?0:t?1:i?2:3;if(r){let a=[],u=!0,l=0,c=0,h=f=>(m,y)=>y>=s?Cl():(c=Array.isArray(m)?m[0]:m,y<f?zP(c):y>f?Cl():$P(c+l));for(let f=s-1;f>=0;f--)u&&!n[f]||(u=!1,a.push(n.map(h(f))),l=1);return a}return[n.map((a,u)=>u>=s?Cl():Array.isArray(a)?$P(a[0],a[1]):zP(a))]}function qQ(n,e,t){let{allowHigherVersions:i}=t,r=_l(n),s=i&&e.length?[e[0]]:e,o=s.reduce((l,c)=>Math.max(l,vQ(c,t)),1),a=tM(r,o),u=e1(...s.map(l=>zQ(l,t).map(c=>KQ(lo(XP(a)),c,o))));return $r.default.traverse(r,OA({every(l){return a.length?(l.node===a[0]&&(a.length===1?l.replace(u):l.remove(),a.shift()),!0):!1}})),r}function YQ(n,e){return n.map(({regex:t,version:i,maxVersion:r,matchedVersions:s,...o})=>{let a=_l(t);return i||(a=qQ(a,_Q(s),{...e,allowHigherVersions:!r&&e.allowHigherVersions})),{regex:null,sourceRegex:t,regexAst:a,version:i,maxVersion:r,matchedVersions:s,...o}})}var JQ={ignoreMinor:!1,ignorePatch:!0,allowZeroSubversions:!1,allowHigherVersions:!1};function $Q(n={}){let e={...JQ,...n},t=EQ(e),i=SQ(t),r=GQ(i,e);return YQ(r,e)}function iM(n={}){return WQ($Q(n))}var ja=class{constructor(e){this.hasEventListener=!1;this.isHacked=!1;this.properties=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,t1.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,t1.launch)(),await _T(e.detectInspectInitDelay??100)}static isCurrentBrowserSupported(e){if(!e.enforceSupportedBrowsers)return!0;let t=[];return(e.supportedBrowsers??[]).forEach(r=>{t.push("last 1 "+r+" version")}),iM({browsers:t,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.properties?.enableObfuscation){this.wrapper=gt(document,"#iframe-wrapper"),this.securityContainer=ge(document,"#container-view-security");var e=this;this.mutationObserver=new MutationObserver(function(t){t.forEach(function(i){rn.default.log(i.type),e.isHacked=!0})})}}async stop(){if(rn.default.log("Protection module stop"),this.properties?.enableObfuscation&&this.mutationObserver.disconnect(),this.properties?.disableKeys){Se(this.navigator.mainElement,"keydown",this.disableSave),Se(this.navigator.headerMenu,"keydown",this.disableSave);for(let e of this.navigator.iframes)Se(e.contentDocument,"keydown",this.disableSave),Se(e.contentWindow,"keydown",this.disableSave);Se(window,"keydown",this.disableSave),Se(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){Se(this.navigator.mainElement,"copy",this.preventCopy),Se(this.navigator.headerMenu,"copy",this.preventCopy);for(let e of this.navigator.iframes)Se(e.contentDocument,"copy",this.preventCopy),Se(e.contentWindow,"copy",this.preventCopy);Se(window,"copy",this.preventCopy),Se(document,"copy",this.preventCopy),Se(this.navigator.mainElement,"cut",this.preventCopy),Se(this.navigator.headerMenu,"cut",this.preventCopy);for(let e of this.navigator.iframes)Se(e.contentDocument,"cut",this.preventCopy),Se(e.contentWindow,"cut",this.preventCopy);Se(window,"cut",this.preventCopy),Se(document,"cut",this.preventCopy),Se(this.navigator.mainElement,"keydown",this.preventCopyKey),Se(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let e of this.navigator.iframes)Se(e.contentDocument,"keydown",this.preventCopyKey),Se(e.contentWindow,"keydown",this.preventCopyKey);Se(window,"keydown",this.preventCopyKey),Se(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){Se(this.navigator.mainElement,"copy",this.restrictCopy),Se(this.navigator.headerMenu,"copy",this.restrictCopy);for(let e of this.navigator.iframes)Se(e.contentDocument,"copy",this.restrictCopy),Se(e.contentWindow,"copy",this.restrictCopy);Se(window,"copy",this.restrictCopy),Se(document,"copy",this.restrictCopy),Se(this.navigator.mainElement,"cut",this.restrictCopy),Se(this.navigator.headerMenu,"cut",this.restrictCopy);for(let e of this.navigator.iframes)Se(e.contentDocument,"cut",this.restrictCopy),Se(e.contentWindow,"cut",this.restrictCopy);Se(window,"cut",this.restrictCopy),Se(document,"cut",this.restrictCopy),Se(this.navigator.mainElement,"keydown",this.restrictCopyKey),Se(this.navigator.headerMenu,"keydown",this.restrictCopyKey);for(let e of this.navigator.iframes)Se(e.contentDocument,"keydown",this.restrictCopyKey),Se(e.contentWindow,"keydown",this.restrictCopyKey);Se(window,"keydown",this.restrictCopyKey),Se(document,"keydown",this.restrictCopyKey)}if(this.properties?.disablePrint){Se(this.navigator.mainElement,"beforeprint",this.beforePrint.bind(this)),Se(this.navigator.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let e of this.navigator.iframes)Se(e.contentDocument,"beforeprint",this.beforePrint),Se(e.contentWindow,"beforeprint",this.beforePrint);Se(window,"beforeprint",this.beforePrint),Se(document,"beforeprint",this.beforePrint),Se(this.navigator.mainElement,"afterprint",this.afterPrint.bind(this)),Se(this.navigator.headerMenu,"afterprint",this.afterPrint.bind(this));for(let e of this.navigator.iframes)Se(e.contentDocument,"afterprint",this.afterPrint.bind(this)),Se(e.contentWindow,"afterprint",this.afterPrint.bind(this));Se(window,"afterprint",this.afterPrint.bind(this)),Se(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){Se(this.navigator.mainElement,"contextmenu",this.disableContext),Se(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let e of this.navigator.iframes)Se(e.contentDocument,"contextmenu",this.disableContext),Se(e.contentWindow,"contextmenu",this.disableContext);Se(window,"contextmenu",this.disableContext),Se(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),Se(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.navigator.iframes)if(e.contentDocument){let t=qs(e.contentDocument,"body");this.rects=this.findRects(t),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){te(this.navigator.mainElement,"keydown",this.disableSave),te(this.navigator.headerMenu,"keydown",this.disableSave);for(let e of this.navigator.iframes)te(e,"keydown",this.disableSave),te(e.ownerDocument,"keydown",this.disableSave),te(e.contentDocument,"keydown",this.disableSave),te(e.contentWindow,"keydown",this.disableSave),te(e.contentWindow?.document,"keydown",this.disableSave);te(window,"keydown",this.disableSave),te(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){te(this.navigator.mainElement,"copy",this.preventCopy),te(this.navigator.headerMenu,"copy",this.preventCopy);for(let e of this.navigator.iframes)te(e,"copy",this.preventCopy),te(e.ownerDocument,"copy",this.preventCopy),te(e.contentDocument,"copy",this.preventCopy),te(e.contentWindow,"copy",this.preventCopy),te(e.contentWindow?.document,"copy",this.preventCopy);te(window,"copy",this.preventCopy),te(document,"copy",this.preventCopy),te(this.navigator.mainElement,"cut",this.preventCopy),te(this.navigator.headerMenu,"cut",this.preventCopy);for(let e of this.navigator.iframes)te(e,"cut",this.preventCopy),te(e.ownerDocument,"cut",this.preventCopy),te(e.contentDocument,"cut",this.preventCopy),te(e.contentWindow,"cut",this.preventCopy),te(e.contentWindow?.document,"cut",this.preventCopy);te(window,"cut",this.preventCopy),te(document,"cut",this.preventCopy),te(this.navigator.mainElement,"keydown",this.preventCopyKey),te(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let e of this.navigator.iframes)te(e,"keydown",this.preventCopyKey),te(e.ownerDocument,"keydown",this.preventCopyKey),te(e.contentDocument,"keydown",this.preventCopyKey),te(e.contentWindow,"keydown",this.preventCopyKey),te(e.contentWindow?.document,"keydown",this.preventCopyKey);te(window,"keydown",this.preventCopyKey),te(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){te(this.navigator.mainElement,"copy",this.restrictCopy.bind(this)),te(this.navigator.headerMenu,"copy",this.restrictCopy.bind(this));for(let e of this.navigator.iframes)te(e,"copy",this.restrictCopy),te(e.ownerDocument,"copy",this.restrictCopy.bind(this)),te(e.contentDocument,"copy",this.restrictCopy.bind(this)),te(e.contentWindow,"copy",this.restrictCopy.bind(this)),te(e.contentWindow?.document,"copy",this.restrictCopy.bind(this));te(window,"copy",this.restrictCopy.bind(this)),te(document,"copy",this.restrictCopy.bind(this)),te(this.navigator.mainElement,"cut",this.restrictCopy.bind(this)),te(this.navigator.headerMenu,"cut",this.restrictCopy.bind(this));for(let e of this.navigator.iframes)te(e,"cut",this.restrictCopy.bind(this)),te(e.ownerDocument,"cut",this.restrictCopy.bind(this)),te(e.contentDocument,"cut",this.restrictCopy.bind(this)),te(e.contentWindow,"cut",this.restrictCopy.bind(this)),te(e.contentWindow?.document,"cut",this.restrictCopy.bind(this));te(window,"cut",this.restrictCopy.bind(this)),te(document,"cut",this.restrictCopy.bind(this)),te(this.navigator.mainElement,"keydown",this.restrictCopyKey.bind(this)),te(this.navigator.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let e of this.navigator.iframes)te(e,"keydown",this.restrictCopyKey.bind(this)),te(e.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),te(e.contentDocument,"keydown",this.restrictCopyKey.bind(this)),te(e.contentWindow,"keydown",this.restrictCopyKey.bind(this)),te(e.contentWindow?.document,"keydown",this.restrictCopyKey.bind(this));te(window,"keydown",this.restrictCopyKey.bind(this)),te(document,"keydown",this.restrictCopyKey.bind(this))}if(this.properties?.disablePrint){te(this.navigator.mainElement,"beforeprint",this.beforePrint),te(this.navigator.headerMenu,"beforeprint",this.beforePrint);for(let e of this.navigator.iframes)te(e,"beforeprint",this.beforePrint.bind(this)),te(e.ownerDocument,"beforeprint",this.beforePrint.bind(this)),te(e.contentDocument,"beforeprint",this.beforePrint.bind(this)),te(e.contentWindow,"beforeprint",this.beforePrint.bind(this)),te(e.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));te(window,"beforeprint",this.beforePrint.bind(this)),te(document,"beforeprint",this.beforePrint.bind(this)),te(this.navigator.mainElement,"afterprint",this.afterPrint),te(this.navigator.headerMenu,"afterprint",this.afterPrint);for(let e of this.navigator.iframes)te(e,"afterprint",this.afterPrint.bind(this)),te(e.ownerDocument,"afterprint",this.afterPrint.bind(this)),te(e.contentDocument,"afterprint",this.afterPrint.bind(this)),te(e.contentWindow,"afterprint",this.afterPrint.bind(this)),te(e.contentWindow?.document,"afterprint",this.afterPrint.bind(this));te(window,"afterprint",this.afterPrint.bind(this)),te(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){te(this.navigator.mainElement,"contextmenu",this.disableContext),te(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let e of this.navigator.iframes)te(e,"contextmenu",this.disableContext),te(e.ownerDocument,"contextmenu",this.disableContext),te(e.contentDocument,"contextmenu",this.disableContext),te(e.contentWindow,"contextmenu",this.disableContext),te(e.contentWindow?.document,"contextmenu",this.disableContext);te(window,"contextmenu",this.disableContext),te(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=qs(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,te(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,BA.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 rn.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;rn.default.log("copy action initiated");let t=this.navigator.iframes[0].contentWindow;if(t){let r=function(o){let a={className:l=>ar.indexOf(l)<0,idName:l=>ar.indexOf(l)<0},u=i.navigator.iframes[0].contentDocument;if(u)return Vi(o,u,a)},i=this,s=As(t,r);if(s===void 0){let o=this.navigator.iframes[0].contentDocument;s=this.navigator.annotationModule?.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.navigator.iframes[0].contentWindow;if(t){let r=function(o){let a={className:l=>ar.indexOf(l)<0,idName:l=>ar.indexOf(l)<0},u=i.navigator.iframes[0].contentDocument;if(u)return Vi(o,u,a)},i=this,s=As(t,r);if(s===void 0){let o=this.navigator.iframes[0].contentDocument;s=this.navigator.annotationModule?.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 rn.default.log("before print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.display="none",this.navigator.mainElement.style.display="none"),e.stopPropagation(),e.preventDefault(),!1}afterPrint(e){return rn.default.log("after print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.removeProperty("display"),this.navigator.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.navigator.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.navigator.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,BA.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){rn.default.log("error "+i),rn.default.log(t),rn.default.log(t.node),rn.default.log("scrambledTextContent "+t.scrambledTextContent),rn.default.log("textContent "+t.textContent),rn.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){rn.default.log("measureTextNode "+t),rn.default.log("measureTextNode "+e),rn.default.log(e.textContent)}}isBeingHacked(e){return e.style.animation||e.style.transition||e.style.position||e.hasAttribute("style")?(rn.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,h=e.left>i+window.innerWidth;return u||l||c||h}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(" ")}};_();ui();yn();var uM=Qe(rM());_();var i1=n=>n.replace(/\n/g," ").replace(/\s\s+/g," "),QQ=n=>i1(n).trim(),oM=/[\\^$.*+?()[\]{}|]/g,XQ=RegExp(oM.source);function sM(n){return n&&XQ.test(n)?n.replace(oM,"\\$&"):n||""}var n1=0,ZQ=()=>()=>Number.isSafeInteger(++n1)?n1:n1=1,aM=()=>{n1=0},eX=ZQ(),tX=n=>e=>{try{return Vi(e,n,Vo)}catch(t){return console.error("uniqueCssSelector:",t),""}};async function Jo(n,e,t,i,r=!1){if(!e)return[];let s=e.body?.textContent;if(!s)return[];if(n=QQ(n),!n.length)return[];let o=e.createNodeIterator(e.body,NodeFilter.SHOW_TEXT,{acceptNode:m=>NodeFilter.FILTER_ACCEPT}),a=new RegExp(sM(n).replace(/ /g,"\\s+"),"gim");r&&(a=new RegExp("\\b"+sM(n).replace(/ /g,"\\s+")+"\\b","gim"));let u=[],l=100,c=30,h=0,f;for(;f=a.exec(s);){let m=Math.max(0,f.index-l),y=Math.min(l,f.index),g=i1(s.substr(m,y));g=g.substr(g.length-c),m=a.lastIndex,y=Math.min(l,s.length-m);let b=i1(s.substr(m,y)).substr(0,c),A=new Range,v=f.index;for(;h<=v;){let C=o.nextNode();C&&C.nodeValue&&(h+=C.nodeValue.length)}let E=o.referenceNode.nodeValue?o.referenceNode.nodeValue?.length-(h-v):0;for(A.setStart(o.referenceNode,E),v=f.index+f[0].length;h<=v;){let T=o.nextNode()?.nodeValue;T&&(h+=T.length)}E=o.referenceNode.nodeValue?o.referenceNode.nodeValue?.length-(h-v):0,A.setEnd(o.referenceNode,E),e.getCssSelector||(e.getCssSelector=tX(e));let S=to(A,e.getCssSelector);S&&u.push({textMatch:i1(f[0]),textBefore:g,textAfter:b,rangeInfo:S,href:t,title:i,uuid:eX().toString()})}return u}var lM=Qe(Qt()),iX="#fff059",nX="#ff6600",xl=class{constructor(e,t,i,r,s){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.headerMenu=s,this.publication=e,this.properties={...t,color:t.color??iX,current:t.current??nX},this.api=r,this.highlighter=i}static async create(e){let t=new this(e.publication,e,e.highlighter,e.api,e.headerMenu);return await t.start(),t}async stop(){lM.default.log("Search module stop"),Se(this.searchInput,"keypress",this.handleSearch.bind(this)),Se(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.headerMenu){this.searchInput=ge(this.headerMenu,"#searchInput"),te(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=ge(this.headerMenu,"#searchGo"),te(this.searchGo,"click",this.handleSearch.bind(this));var e=ge(this.headerMenu,"#menu-button-search");e&&e.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("search"):this.navigator.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.navigator.currentChapterLink.href,s=this.publication.getSpineItem(r);if(this.headerMenu)var o=ge(document,"#searchResultChapter");t.currentChapterSearchResult=[],t.currentSearchHighlights=[];var a=[];await this.searchAndPaintChapter(i,e,async l=>{a=l,u(1),this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)});async function u(l){o.innerHTML="";var c;if(c=t.paginate(a,l,10),c.total===0){let h=document.createElement("a");h.className="collection-item",h.innerHTML="nothing found",o.appendChild(h)}else{for(let g=0;g<c.data.length;g++){let b=document.createElement("a"),A=c.data[g];b.className="collection-item",b.href=s?.Href??"",b.innerHTML="..."+A.textBefore+"<mark>"+A.textMatch+"</mark>"+A.textAfter+"...",te(b,"click",v=>{v.preventDefault(),v.stopPropagation(),t.jumpToMark(g+l*10-10)}),o.appendChild(b)}let h=document.createElement("div");h.style.textAlign="center",h.style.marginTop="10px";let f=document.createElement("ul");f.className="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",te(m,"click",b=>{b.preventDefault(),b.stopPropagation(),u(g)})}f.appendChild(m);for(let g=1;g<=c.total_pages;g++){let b,A=document.createElement("li");A.className="waves-effect",g===c.page&&(A.className="active",b=A),A.innerHTML='<a href="#!">'+g+"</a>",te(A,"click",v=>{v.preventDefault(),v.stopPropagation(),b&&(b.className="waves-effect"),A.className="active",b=A,u(g)}),f.appendChild(A)}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",te(y,"click",b=>{b.preventDefault(),b.stopPropagation(),u(g)})}f.appendChild(y),h.appendChild(f),o.appendChild(h)}}}async searchAndPaintChapter(e,t=0,i){this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate();let r=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),s=this.publication.getTOCItem(r);s===null&&(s=this.publication.readingOrder[this.navigator.currentResource()??0]);let o=[];this.highlighter?.destroyHighlights(1),this.navigator.rights.enableSearch&&this.drawSearch();let a=0;if(s){let u=this.navigator.iframes[0].contentDocument;u&&s&&Jo(e,u,s.Href,s.Title).then(l=>{l.forEach(c=>{let h={rangeInfo:c.rangeInfo};setTimeout(()=>{let f;a===t?(f=this.createSearchHighlight(h,this.properties?.current),this.jumpToMark(t)):f=this.createSearchHighlight(h,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;Xt.isHexColor(i)&&(i=Xt.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_"+uM.SHA256.hash(s);var r=!1;let u={color:i||Fa,id:a,pointerInteraction:r,selectionInfo:e,marker:0,type:1},l=this.highlighter?.createHighlightDom(this.navigator.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)}async search(e,t){return this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],aM(),await this.searchAndPaintChapter(e,0,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.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.navigator.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"},h=this.publication.positionsByHref(c.href);h?.length>0&&(c.locations.totalProgression=h[0].locations.totalProgression,c.locations.position=h[0].locations.position),this.navigator.navigate(c),setTimeout(()=>{this.searchAndPaintChapter(s.textMatch,r,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)})},300)}}async goToSearchIndex(e,t,i){var r=t,s;let o=this.navigator.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"},h=this.publication.positionsByHref(c.href);h?.length>0&&(c.locations.totalProgression=h[0].locations.totalProgression,c.locations.position=h[0].locations.position),this.navigator.navigate(c),setTimeout(()=>{this.searchAndPaintChapter(s.textMatch,r,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)})},300)}}async handleSearchBook(){var e=this,t=this.searchInput.value;if(e.headerMenu)var i=ge(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 A=document.createElement("a");A.className="collection-item";var v=e.publication.getAbsoluteHref(b.href);A.innerHTML="..."+b.textBefore+"<mark>"+b.textMatch+"</mark>"+b.textAfter+"...",te(A,"click",E=>{E.preventDefault(),E.stopPropagation();let C=u.filter(M=>M.href===b.href).findIndex(M=>M===b);if(e.navigator.currentChapterLink.href===v)e.jumpToMark(C);else{let I={href:v,locations:{progression:0},title:"title"},L=e.publication.positionsByHref(I.href);L?.length>0&&(I.locations.totalProgression=L[0].locations.totalProgression,I.locations.position=L[0].locations.position),e.navigator.navigate(I),setTimeout(()=>{e.handleSearchChapter(C)},300)}}),g.appendChild(A)})});let c=document.createElement("div");c.style.textAlign="center",c.style.marginTop="10px";let h=document.createElement("ul");h.className="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",te(f,"click",g=>{g.preventDefault(),g.stopPropagation(),r(y)})}h.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="active",g=b),b.innerHTML='<a href="#!">'+y+"</a>",te(b,"click",A=>{A.preventDefault(),A.stopPropagation(),g&&(g.className="waves-effect"),b.className="active",g=b,r(y)}),h.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",te(m,"click",g=>{g.preventDefault(),g.stopPropagation(),r(y)})}h.appendChild(m),c.appendChild(h),i.appendChild(c)}}function s(o,a){let u=new Map;return o.forEach(l=>{let c=a(l),h=u.get(c);h?h.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);this.navigator.api?.getContent?await this.navigator.api?.getContent(o).then(a=>{let l=new DOMParser().parseFromString(a,"application/xhtml+xml");s&&Jo(e,l,s.Href,s.Title).then(c=>{c.forEach(h=>{t.push(h),this.bookSearchResult.push(h)})})}):await fetch(o,this.navigator.requestConfig).then(a=>a.text()).then(async a=>{let l=new DOMParser().parseFromString(this.navigator.requestConfig?.encoded?this.decodeBase64(a):a,"application/xhtml+xml");s&&Jo(e,l,s.Href,s.Title).then(c=>{c.forEach(h=>{t.push(h),this.bookSearchResult.push(h)})})})}if(i===this.publication.readingOrder.length-1)return t}}decodeBase64(e){let t=atob(e),i=t.length,r=new Uint8Array(i);for(let o=0;o<i;o++)r[o]=t.charCodeAt(o);return new TextDecoder().decode(r)}async searchChapter(e){let t=[],i=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),r=this.publication.getTOCItem(i);if(r===null&&(r=this.publication.readingOrder[this.navigator.currentResource()??0]),r){let s=this.publication.getAbsoluteHref(r.Href);this.navigator.api?.getContent?await this.navigator.api?.getContent(s).then(o=>{let u=new DOMParser().parseFromString(o,"application/xhtml+xml");r&&Jo(e,u,r.Href,r.Title).then(l=>{l.forEach(c=>{t.push(c)})})}):await fetch(s,this.navigator.requestConfig).then(o=>o.text()).then(async o=>{let u=new DOMParser().parseFromString(this.navigator.requestConfig?.encoded?this.decodeBase64(o):o,"application/xhtml+xml");r&&Jo(e,u,r.Href,r.Title).then(l=>{l.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;Xt.isHexColor(s)&&(s=Xt.hexToRgbChannels(s)),r.color=s});var i=this.properties?.current;Xt.isHexColor(i)&&(i=Xt.hexToRgbChannels(i)),t.highlight.color=i,this.highlighter?.setAndResetSearchHighlight(t.highlight,this.currentSearchHighlights),this.navigator.view?.goToCssSelector(t.rangeInfo.startContainerElementCssSelector),this.navigator.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}}};_();ui();yn();var Fn=Qe(Qt()),Ci=class Ci{};Ci.COLOR_REF="color",Ci.AUTO_SCROLL_REF="autoscroll",Ci.RATE_REF="rate",Ci.PITCH_REF="pitch",Ci.VOLUME_REF="volume",Ci.VOICE_REF="voice",Ci.COLOR_KEY="tts-"+Ci.COLOR_REF,Ci.AUTO_SCROLL_KEY="tts-"+Ci.AUTO_SCROLL_REF,Ci.RATE_KEY="tts-"+Ci.RATE_REF,Ci.PITCH_KEY="tts-"+Ci.PITCH_REF,Ci.VOLUME_KEY="tts-"+Ci.VOLUME_REF,Ci.VOICE_KEY="tts-"+Ci.VOICE_REF;var $e=Ci,r1=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,Fn.default.log(t.rate)),i?.pitch&&(t.pitch=i.pitch,Fn.default.log(t.pitch)),i?.volume&&(t.volume=i.volume,Fn.default.log(t.volume)),i?.color&&(t.color=i.color,Fn.default.log(t.color)),i?.autoScroll&&(t.autoScroll=i.autoScroll,Fn.default.log(t.autoScroll)),i?.voice&&(t.voice=i.voice,Fn.default.log(t.voice))}return t.initializeSelections(),t}stop(){Fn.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty($e.AUTO_SCROLL_KEY)!=null?this.getProperty($e.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty($e.RATE_KEY)!=null?this.getProperty($e.RATE_KEY).value:this.rate,this.pitch=this.getProperty($e.PITCH_KEY)!=null?this.getProperty($e.PITCH_KEY).value:this.pitch,this.volume=this.getProperty($e.VOLUME_KEY)!=null?this.getProperty($e.VOLUME_KEY).value:this.volume,this.color=this.getProperty($e.COLOR_KEY)!=null?this.getProperty($e.COLOR_KEY).value:this.color,this.voice=this.getProperty($e.VOICE_REF)!=null?this.getProperty($e.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=ge(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechRate=ge(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=ge(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=ge(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=ge(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),te(ge(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($e.RATE_REF)?.value,pitch:this.userProperties.getByRef($e.PITCH_REF)?.value,volume:this.userProperties.getByRef($e.VOLUME_REF)?.value,voice:this.userProperties.getByRef($e.VOLUME_REF)?.value,color:this.userProperties.getByRef($e.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef($e.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(e),this.api?.updateSettings&&this.api?.updateSettings(e).then(async t=>{Fn.default.log("api updated tts settings",t)})}getTTSSettings(){var e=new ds;return e.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,$e.AUTO_SCROLL_REF,$e.AUTO_SCROLL_KEY),e.addIncremental(this.rate,.1,10,.1,"",$e.RATE_REF,$e.RATE_KEY),e.addIncremental(this.pitch,.1,2,.1,"",$e.PITCH_REF,$e.PITCH_KEY),e.addIncremental(this.volume,.1,1,.1,"",$e.VOLUME_REF,$e.VOLUME_KEY),e.addStringable(this.color,$e.COLOR_REF,$e.COLOR_KEY),e.addJSONable(JSON.stringify(this.voice),$e.VOICE_REF,$e.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){Fn.default.log("rate "+this.rate),this.rate=e.rate;let t=this.userProperties.getByRef($e.RATE_REF);t&&(t.value=this.rate,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.pitch){Fn.default.log("pitch "+this.pitch),this.pitch=e.pitch;let t=this.userProperties.getByRef($e.PITCH_REF);t&&(t.value=this.pitch,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.volume){Fn.default.log("volume "+this.volume),this.volume=e.volume;let t=this.userProperties.getByRef($e.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($e.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){Fn.default.log("autoScroll "+this.autoScroll),this.autoScroll=e.autoScroll;let t=this.userProperties.getByRef($e.AUTO_SCROLL_REF);t&&(t.value=this.autoScroll,this.saveProperty(t)),this.settingsChangeCallback()}if(e.voice){Fn.default.log("voice "+this.voice),this.voice=e.voice;let t=this.userProperties.getByRef($e.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($e.RATE_REF).increment();let t=this.userProperties.getByRef($e.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef($e.PITCH_REF).increment();let t=this.userProperties.getByRef($e.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef($e.VOLUME_REF).increment();let t=this.userProperties.getByRef($e.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}decrease(e){if(e==="rate"){this.userProperties.getByRef($e.RATE_REF).decrement();let t=this.userProperties.getByRef($e.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef($e.PITCH_REF).decrement();let t=this.userProperties.getByRef($e.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef($e.VOLUME_REF).decrement();let t=this.userProperties.getByRef($e.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}};_();yn();ui();DA();var l1=Qe(eo());_();var co=class co{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)<co.TAP_TOLERANCE&&Math.abs(c)<co.TAP_TOLERANCE){if(i){t=null,i=null;return}if(s.timeStamp-t.timeStamp>co.LONG_PRESS_MS){t=null,i=null;return}t=null,i=s;return}if(i=null,s.timeStamp-t.timeStamp>co.SLOW_SWIPE_MS){t=null;return}let h=(o.clientY-a.clientY)/(o.clientX-a.clientX);if(Math.abs(h)>.5){t=null;return}l<0?r.onBackwardSwipe(s):r.onForwardSwipe(s),t=null},!1))};this.navigator=e}};co.TAP_TOLERANCE=10,co.LONG_PRESS_MS=500,co.SLOW_SWIPE_MS=500;var Od=co;_();var Bd=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)})}};_();var dM=Qe(eo()),Nd=class{constructor(e){this.enforceSampleRead=(0,dM.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 h;function f(y){y=y||window.event;let g=y.target||y.srcElement,b=y.touches[0].clientY;if(!(b>h)){if(b<h&&!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 h=b,!1}function m(y){return y=y||window.event,h=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}};_();ui();yn();var Dd=Qe(Qt()),Tl=class{static async create(e){let t=new this(e.publication,e,e.headerMenu);return await t.start(),t}constructor(e,t,i){this.headerMenu=i,this.publication=e,this.properties=t}async stop(){Dd.default.log("Page Break module stop")}async start(){this.headerMenu&&(this.goToPageView=ge(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=ge(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=ge(this.headerMenu,"#goToPageNumberButton")),te(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),te(this.goToPageNumberButton,"click",this.goToPageNumber.bind(this)),this.goToPageView&&(this.publication.pageList?.length||this.goToPageView.parentElement?.removeChild(this.goToPageView)),setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("pagebreak"):this.navigator.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.TypeLink,title:i.Title};this.navigator.goTo(s)}}}async handleResize(){await this.navigator.highlighter?.destroyHighlights(3),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{let e=this.navigator.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.navigator.iframes[0].contentDocument;return o?Vi(s,o,Vo):""}catch(o){return Dd.default.log("uniqueCssSelector:"),Dd.default.error(o),""}}if(t)for(let s=0;s<t.length;s++){let o=t[s];Dd.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.navigator.iframes[0].contentDocument;if(l){let c=this.navigator.highlighter?.dom(l.body).getWindow().document.createRange(),h=this.navigator.highlighter?.dom(l.body).getSelection();if(h.removeAllRanges(),c.selectNodeContents(o),h.addRange(c),!h.isCollapsed){let f=to(c,r);h.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_"+ys.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};li.push(a);let u=this.navigator.highlighter?.createHighlightDom(this.navigator.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}}};_();ui();yn();var fM=Qe(Sy());var pM=Qe(eo());var Tt=Qe(Qt()),Il=class{constructor(e,t,i,r,s,o){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,pM.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=o,this.rights=t,this.highlighter=i,this.properties=r,this.api=s}initialize(e){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=e,this.clean=(0,fM.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),this.wrapper=gt(document,"#iframe-wrapper"),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,te(document,"wheel",this.wheel.bind(this)),te(this.body,"wheel",this.wheel.bind(this)),te(document,"keydown",this.wheel.bind(this)),te(this.navigator.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),te(this.body,"mousedown",this.clickStart.bind(this)),te(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.navigator.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(Tt.default.log(r),this.voices=[],r.forEach(o=>{o.localService===!0&&this.voices.push(o)}),Tt.default.log(this.voices),e&&this.headerMenu){var s=ge(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.api?.stopped&&this.api?.stopped(),this.navigator.emit("readaloud.stopped","stopped")),this.userScrolled=!1,this.speaking=!1,setTimeout(()=>{window.speechSynthesis.cancel()},0),this._ttsQueueItemHighlightsWord&&(this.navigator.highlighter?.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0)}async speak(e,t,i){t||this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate(),this.api?.started&&this.api?.started(),this.navigator.emit("readaloud.started","started");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.navigator.iframes[0].contentDocument;if(m){let y=this.highlighter.dom(m.body).getSelection();if(y.isCollapsed){let g=r.navigator.iframes[0].contentDocument,b=r.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(g);b?.range&&y.addRange(b.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=Ga(o,a),b=Ga(o,u);var l;if(g&&e&&e.cleanText){let A=Wa(g),v=e.rangeInfo.startOffset,E=e.cleanText;if(b&&a+1===u){let C=Wa(b);v=(A+" "+C).indexOf(e.cleanText),E=A.slice(v,A.length),l=e.cleanText.replace(E,"").trim()}else if(u>a){let C="";for(let T=a+1;T<u;T++){let M=Ga(o,T);if(M){let I=Wa(M);C+=I,l=e.cleanText.replace(I,"")}}if(b){let T=Wa(b);C+=" "+T}v=(A+" "+C).indexOf(e.cleanText),E=A.slice(v,A.length),l=l.replace(E,"").trim()}s=new SpeechSynthesisUtterance(E),s.rate=this.tts.rate,s.pitch=this.tts.pitch,s.volume=this.tts.volume,this.setVoice(this,s),Tt.default.log(e),Tt.default.log(E,e.range?.commonAncestorContainer.textContent),Tt.default.log(g),Tt.default.log(g.item.textNodes),Tt.default.log(v),Tt.default.log(g.item.combinedText);let S=g.item.textNodes.filter(C=>C===e.range?.commonAncestorContainer)[0];Tt.default.log(S),s.onboundary=C=>{this.updateTTSInfo(g,C.charIndex,C.charLength,v,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 h=Ga(o,a);if(h){let f=Wa(h);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(h,m.charIndex,m.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s)},0),c()}}else{let h=Ga(o,a);h&&(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(h,f.charIndex,f.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s)},0),c()),a>u&&(Tt.default.log("utterance ended"),r.highlighter.doneSpeaking(),r.api?.finished(),r.navigator.emit("readaloud.finished","finished"))}else Tt.default.log("utterance ended"),r.highlighter.doneSpeaking(),r.api?.finished(),r.navigator.emit("readaloud.finished","finished")}}setTimeout(()=>{window.speechSynthesis.speak(s),t||this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)},0),c(),i()}setVoice(e,t){Tt.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)),Tt.default.log("initialVoiceHasHyphen",i),Tt.default.log("voices",this.voices);let r;i?(r=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(l=>{var c=l.lang.replace("_","-");return c===this.tts.voice.lang&&l.name===this.tts.voice.name})[0]:void 0,r===void 0&&(r=this.tts.voice&&this.tts.voice.lang?this.voices.filter(l=>l.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(r=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(l=>l.lang===this.tts.voice.lang&&l.name===this.tts.voice.name)[0]:void 0,r===void 0&&(r=this.tts.voice&&this.tts.voice.lang?this.voices.filter(l=>l.lang===this.tts.voice.lang)[0]:void 0)),Tt.default.log("initialVoice",r);let s=e.navigator.publication.Metadata.Language[0].indexOf("-")!==-1;Tt.default.log("publicationVoiceHasHyphen",s);let o;s?o=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(l=>{var c=l.lang.replace("_","-");return c.startsWith(e.navigator.publication.Metadata.Language[0])||c.endsWith(e.navigator.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:o=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(l=>l.lang.startsWith(e.navigator.publication.Metadata.Language[0])||l.lang.endsWith(e.navigator.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Tt.default.log("publicationVoice",o);let a=navigator.language.indexOf("-")!==-1;Tt.default.log("defaultVoiceHasHyphen",a);let u;a?u=this.voices.filter(l=>l.lang.replace("_","-")===navigator.language&&l.localService)[0]:u=this.voices.filter(l=>l.lang===navigator.language&&l.localService)[0],u===void 0&&(u=this.voices.filter(l=>l.lang.includes(navigator.language)&&l.localService)[0]),Tt.default.log("defaultVoice",u),r?(Tt.default.log("initialVoice"),t.voice=r):o?(Tt.default.log("publicationVoice"),t.voice=o):u&&(Tt.default.log("defaultVoice"),t.voice=u),t.voice!==void 0&&t.voice!==null&&(t.lang=t.voice.lang,Tt.default.log("utterance.voice.lang",t.voice.lang),Tt.default.log("utterance.lang",t.lang)),Tt.default.log("navigator.language",navigator.language)}speakPlay(){this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate(),this.scrollPartial=!0,this.cancel(!1),this.api?.started&&this.api?.started(),this.navigator.emit("readaloud.started","started");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.navigator.iframes[0].contentDocument;if(u){let l=e.highlighter.dom(u.body).getWindow().document.createRange(),c=e.highlighter.dom(e.navigator.iframes[0].contentDocument?.body).getSelection();c.removeAllRanges(),l.selectNodeContents(a.node),c.addRange(l);let h=0,f=c.focusNode,m=c.focusOffset;c.collapse(c.anchorNode,c.anchorOffset);for(let y=0;y<h;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.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)}speakPause(){window.speechSynthesis.speaking&&(this.api?.paused&&this.api?.paused(),this.navigator.emit("readaloud.paused","paused"),this.userScrolled=!1,window.speechSynthesis.pause(),this.speaking=!1,this._ttsQueueItemHighlightsWord&&(this.navigator.highlighter?.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0))}speakResume(){window.speechSynthesis.speaking&&(this.api?.resumed&&this.api?.resumed(),this.navigator.emit("readaloud.resumed","resumed"),this.userScrolled=!1,window.speechSynthesis.resume(),this.speaking=!0)}static async create(e){let t=new this(e.tts,e.rights,e.highlighter,e,e.api,e.headerMenu);return await t.start(),t}async start(){if(this.headerMenu){var e=ge(this.headerMenu,"#menu-button-tts");e&&e.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties?.hideLayer?this.navigator.hideLayer("readaloud"):this.navigator.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(){Tt.default.log("TTS module stop"),Se(document,"wheel",this.wheel.bind(this)),Se(this.body,"wheel",this.wheel.bind(this)),Se(document,"keydown",this.wheel.bind(this)),Se(this.navigator.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),Se(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?hM(u.parentElement):void 0,h=u.parentElement?rX(u.parentElement):void 0,f=t[t.length-1];(!f||f.parentElement!==l||f.lang!==c||f.dir!==h)&&(f={combinedText:"",dir:h,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 h=c;if(!h.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))o(h);else if(h.tagName&&h.tagName.toLowerCase()==="img"&&h.src){let m=h.getAttribute("alt");if(m){let y=m.trim();if(y){let g=hM(h);t.push({combinedText:y,dir:void 0,lang:g,parentElement:h,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=sX(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(!Ga(e,t)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(t,e)}ttsPlayQueueIndex(e,t){if(e<0){this.cancel();return}let i=Ga(t,e);if(!i){this.cancel();return}let r=Wa(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=>{Tt.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;Tt.default.log(e,t,i,s);let o=s||Wa(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 h=s.substring(t).match(/^[a-z\d']*/i);h&&(i=h[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){Tt.default.log(e),Tt.default.log(t),Tt.default.log(i,r,s,o,a),this._ttsQueueItemHighlightsWord&&(this.navigator.highlighter?.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0);let u=e.item,l=i,c=0,h,f=-1,m,y=-1,g=l+r;for(let b of u.textNodes){if(!b.nodeValue&&b.nodeValue!=="")continue;let A=b.nodeValue.length;if(c+=A,h||l<c&&(h=b,f=A-(c-l)),h&&g<=c&&(m=b,y=A-(c-g)),m)break}if(h&&m){let v=function(C){try{let T=A.navigator.iframes[0].contentDocument;return T?Vi(C,T,Vo):""}catch(T){return Tt.default.log("uniqueCssSelector:"),Tt.default.error(T),""}},b=new Range;b.setStart(h,f),b.setEnd(m,y);let A=this,E=to(b,v);if(!E)return;let S=this.navigator.highlighter?.createHighlight(this.navigator.iframes[0].contentWindow,{rangeInfo:E,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(S){this._ttsQueueItemHighlightsWord=S[0];let M=(S[1]?.firstChild?.getBoundingClientRect()).top-this.wrapper.scrollTop>window.innerHeight/2-65;this.navigator.view?.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&this.scrollPartial&&M?S[1]?.firstChild?.scrollIntoView({block:"center",behavior:"smooth"}):this.navigator.view?.isPaginated()&&A.navigator.view?.snap(S[1]?.firstChild)}}}};function hM(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 rX(n){let e=n;for(;e&&e.nodeType===Node.ELEMENT_NODE;){let t=e.getAttribute("dir");if(t)return t;e=e.parentNode}}function sX(n,e){if(n&&n.length){let t="";for(let i of n)i.nodeValue&&(t+=e?i.nodeValue:aX(i.nodeValue));return t}return""}function oX(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function aX(n){return oX(n).replace(/\n/g," ").replace(/\s\s+/g," ")}function Ga(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 Wa(n){return n.item.combinedText}_();var Fd=Qe(vp());var gM=Qe(eo());var mM=Qe(Qt()),Pl=class{constructor(e,t,i,r){this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,gM.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}static async create(e){let t=new this(e.publication,e,e.highlighter,e.api);return await t.start(),t}async stop(){mM.default.log("Definitions module stop")}async start(){setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("definitions"):this.navigator.showLayer("definitions")},10)}async searchAndPaint(e,t){let i=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[this.navigator.currentResource()??0].Href:""),r=this.publication.getTOCItem(i);r===void 0&&this.publication.readingOrder&&(r=this.publication.readingOrder[this.navigator.currentResource()??0]);let s=[];if(r)for(let o of e.terms){let a=e.terms.indexOf(o);r&&await Jo(o,this.navigator.iframes[0].contentDocument,r.Href,r.Title,this.navigator.definitionsModule?.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,h)=>{if(l===void 0||l===h){let f={rangeInfo:c.rangeInfo},m=this.createDefinitionHighlight(f,e);c.highlight=m,s.push(Fd.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(Fd.omit(e,"callbacks"),t),this.navigator.emit("definition.success",t),this.api?.visible&&t.forEach(i=>{let s=this.navigator.iframes[0].contentDocument?.querySelector(`#${i.id}`)?.querySelectorAll(`.${ln}`),o=new IntersectionObserver((a,u)=>{a.forEach(l=>{l.intersectionRatio===1&&(this.api?.visible(Fd.omit(e,"callbacks"),Fd.omit(i,"definition")),this.navigator.emit("definition.visible",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.navigator.definitionsModule?.properties.color;Xt.isHexColor(i)&&(i=Xt.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_"+ys.hash(r);this.highlighter.destroyHighlight(this.navigator.iframes[0].contentDocument,o);let a={color:i||Fa,id:o,pointerInteraction:!0,selectionInfo:e,marker:1,type:4};li.push(a);let u=this.highlighter.createHighlightDom(this.navigator.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)}};HA();_();ui();yn();var $o=Qe(Qt()),vM=.5,Va=class{constructor(e,t,i){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}static async create(e){let t=new this(e,e.highlighter,e.api);return await t.start(),t}async stop(){$o.default.log("Definitions module stop"),this.hasEventListener=!1,Se(document,"keydown",this.keydown.bind(this)),Se(document,"keyup",this.keyup.bind(this)),Se(this.navigator.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),Se(this.navigator.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){let e=gt(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,te(document,"keydown",this.keydown.bind(this)),te(document,"keyup",this.keyup.bind(this)),te(e.contentDocument,"keydown",this.keydown.bind(this)),te(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.navigator.settings.scroll(!0),this.lineFocus()}disableLineFocus(e=!0){this.isActive=!1;let t=gt(document,"#iframe-wrapper");this.wrapperHeight&&(t.style.height=this.wrapperHeight),e||(this.index=0);let i=this.navigator.iframes[0].contentDocument;Pi(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=gt(document,"#iframe-wrapper"),t=this.navigator.iframes[0].contentDocument,i=Pi(t,"html"),r=this.properties.maxHeight?zr()*this.properties.maxHeight/100:zr()/2;i.style.setProperty("--USER__maxMediaHeight",r+"px");function s(c,h){c.parentNode.insertBefore(h,c.nextSibling)}function o(c,h){c.parentNode.insertBefore(h,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 v=Math.round,E=Math.random,S=255;return{blue:v(E()*S),green:v(E()*S),red:v(E()*S)}},m=function(v,E){let S=[];for(let C=0,T=0;C<v.length;C++)C>=E&&C%E===0&&T++,S[T]=S[T]||[],S[T].push(v[C]);return S},y=function(v,E){let S=Math.min(v.left,E.left),C=Math.max(v.right,E.right),T=Math.min(v.top,E.top),M=Math.max(v.bottom,E.bottom);return{bottom:M,height:M-T,left:S,right:C,top:T,width:C-S}},g=function(v){if(v.length>1){let E=y(v[0],v[1]);if(v.length>2){let S=y(E,v[2]);if(v.length>3){let C=y(S,v[3]);return v.length>4?y(C,v[4]):C}return S}return E}return v[0]},c=this.findRects(t.body);c=My(c,!0),c=c.sort(function(v,E){return v.top-E.top});let h=[];c=c.filter(function(v){let E=v.top;return h.indexOf(E)===-1&&h.indexOf(E+1)===-1&&h.indexOf(E+2)===-1&&h.indexOf(E+3)===-1&&h.indexOf(E+4)===-1&&h.indexOf(E-1)===-1&&h.indexOf(E-2)===-1&&h.indexOf(E-3)===-1&&h.indexOf(E-4)===-1?(h.push(E),!0):!1}),this.highlighter.destroyHighlights(5);let b=[];this.properties.lines&&this.properties.lines>1?m(c,this.properties.lines).forEach(E=>{b.push(g(E))}):b=c;let A=ge(t,"#R2_ID_LINEFOCUS_CONTAINER");if(A)for(let v of b){let E=document.createElement("div");E.setAttribute("class",ln);let S=f();if(Xt.isHexColor(S)&&(S=Xt.hexToRgbChannels(S)),this.isDebug){let ae=`border-bottom: 1px solid rgba(${S.red}, ${S.green}, ${S.blue}, ${vM}) !important`;E.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${S.red}, ${S.green}, ${S.blue}, ${vM}) !important; ${ae}`)}E.style.outline="none",E.tabIndex=0;let C=this.navigator.iframes[0].contentWindow.document,T=this.navigator.view.isPaginated();T?C.body.style.position="revert":C.body.style.position="relative";let M=C.body.getBoundingClientRect(),I=this.highlighter.getScrollingElement(C),L=T?-I.scrollLeft:M.left,R=T?-I.scrollTop:M.top,B=1,N=24,H,j,U=this.navigator.iframes[0].contentWindow?.innerWidth,z=parseInt(getComputedStyle(t.documentElement).getPropertyValue("column-count")),V=parseInt(getComputedStyle(t.documentElement).getPropertyValue("column-width")),ee=parseInt(getComputedStyle(t.body).getPropertyValue("padding-left"));if(U){let ae=U/(z||1);ae<V&&(ae=U),T||(ae=parseInt(getComputedStyle(t.body).width.replace("px","")));let Ae=this.navigator.settings.fontSize/100,ce=20*Ae;Ae<=1&&(ce=-60);let be=0;Ae<=1&&(be=-60),H=Math.floor(v.left/ae)*ae+ae-(N<40?40:N)+be,j=Math.floor(v.left/ae)*ae+(N<40?40:N)-ce;let oe=parseInt(t.documentElement.style.getPropertyValue("--USER__pageMargins"));oe>=2&&(j=j+ee/z,H=H-ee/z),T||(H=parseInt(getComputedStyle(t.body).width.replace("px","")),j=parseInt(getComputedStyle(t.body).width.replace("px",""))-ae,oe>=2&&(j=j+ee/2,H=H-ee/2))}E.style.setProperty("pointer-events","none"),E.style.position="absolute",E.scale=B,E.rect={height:v.height,left:v.left-L,top:v.top-R,width:v.width},E.style.width=`${E.rect.width*B}px`,E.style.height=`${E.rect.height*B}px`,E.style.left=`${E.rect.left*B}px`,E.style.top=`${E.rect.top*B}px`,this.lines.push(E),A.append(E)}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){$o.default.log("measureTextNode "+t),$o.default.log("measureTextNode "+e),$o.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){$o.default.log("measureTextNode "+t),$o.default.log("measureTextNode "+e),$o.default.log(`${e.textContent}`)}}};_();ui();yn();var wM=Qe(Qt()),Ml=class{constructor(e,t,i,r){this.history=[];this.headerMenu=r,this.publication=t,this.properties=i,this.annotator=e}static async create(e){let t=new this(e.annotator,e.publication,e,e.headerMenu);return await t.start(),t}async stop(){wM.default.log("Page Break module stop"),Se(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),Se(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=ge(this.headerMenu,"#history-forward")),this.headerMenu&&(this.historyBackAnchorElement=ge(this.headerMenu,"#history-back")),this.historyCurrentIndex=this.history.length-1,te(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),te(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.navigator.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.navigator.navigate(this.history[this.historyCurrentIndex],!1))}};_();var EM=Qe(Qt()),u1=(i=>(i[i.Chicago=0]="Chicago",i[i.MLA=1]="MLA",i[i.APA=2]="APA",i))(u1||{});function Qo(n){if(typeof n.Name=="string")return n.Name;if(n.Name&&typeof n.Name=="object"){let e=Object.values(n.Name);return e.length>0?String(e[0]):""}return""}var Lr=["","",""],Ka=class{constructor(e,t,i,r){this.highlighter=t,this.properties=i,this.publication=e,this.api=r}static async create(e){let t=new this(e.publication,e.highlighter,e,e.api);return await t.start(),t}async stop(){EM.default.log("Citation module stop")}copyToClipboard(e){if(this.navigator?.contentProtectionModule&&(this.navigator.contentProtectionModule.citation=!0),navigator.clipboard){let t=document.createElement("div");t.innerHTML=e;let i=t.textContent??t.innerText??e;navigator.clipboard.writeText(i).then(()=>this.api?.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=!1;try{i=document.execCommand("copy")}catch{i=!1}document.body.removeChild(t),i?this.api?.citationCreated("The text was copied to the clipboard!"):this.api?.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.Author?.length>0){let s=this.publication.Metadata.Author.map(o=>Qo(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+". "]:Lr}yearPublishedFormatted(){let e="",t="",i="";if(this.properties.publisher)t+=this.properties.publisher,e+=this.properties.publisher;else if(this.publication.Metadata.Publisher?.length>0&&Qo(this.publication.Metadata.Publisher[0])){let s=Qo(this.publication.Metadata.Publisher[0]);t+=s,e+=s}let r="";if(this.properties.published)r=this.properties.published;else if(this.publication.Metadata.PublicationDate){let s=this.publication.Metadata.PublicationDate.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+". ":""]:Lr}bookTitleFormatted(){let e=this.properties.title||this.publication.Metadata.Title||"";if(e){let t="<em>"+e+"</em>. ";return[t,t,t]}return Lr}editionFormatted(){return Lr}publisherFormatted(){let e="";return this.properties.publisher?e=this.properties.publisher:this.publication.Metadata.Publisher?.length>0&&Qo(this.publication.Metadata.Publisher[0])&&(e=Qo(this.publication.Metadata.Publisher[0])),e?["","",e+". "]:Lr}contributorsFormatted(){let e=[],t=this.publication.Metadata.Editor;if(t?.length>0){let r=t.map(s=>Qo(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.Translator;if(i?.length>0){let r=i.map(s=>Qo(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 Lr}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 Lr}locationFormatted(){return Lr}libraryFormatted(){if(this.properties.library){let e="Retrieved from "+this.properties.library+". ";return[e,e,e]}return Lr}appNameFormatted(){if(this.properties.appName){let e=this.properties.appName+". ";return[e,e,e]}return Lr}appLinkFormatted(){if(this.properties.appLink){let e=this.properties.appLink+". ";return[e,e,e]}return Lr}seriesFormatted(){let e=this.publication.Metadata.BelongsTo?.Series;if(e&&e.length>0){let t=Qo(e[0]);if(t)return[t+". ",t+". ",t+". "]}return Lr}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(),h=this.appNameFormatted(),f=this.appLinkFormatted(),m=this.seriesFormatted(),y=0,g=1,b=2,A=t[y]+r[y]+a[y]+s[y]+l[y]+i[y]+u[y]+c[y]+h[y]+f[y],v=t[b]+i[b]+r[b]+s[b]+o[b]+a[b]+u[b]+l[b]+c[b]+h[b]+f[b],E=t[g]+r[g]+a[g]+s[g]+l[g]+i[g]+m[g]+c[g]+h[g]+f[g],S=this.properties.characters??200,C="\u201C"+this.selectedText(e,S)+"\u201D",T="";return this.properties.styles?.includes(u1[0])&&(this.properties.styles.length>1&&(T+="Chicago: <br>"),T+=C+"<br><br>"+A+"<br><br>"),this.properties.styles?.includes(u1[2])&&(this.properties.styles.length>1&&(T+="APA: <br>"),T+=C+"<br><br>"+v+"<br><br>"),this.properties.styles?.includes(u1[1])&&(this.properties.styles.length>1&&(T+="MLA: <br>"),T+=C+"<br><br>"+E+"<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)}};var Hn=Qe(Qt());var _t=class n extends a1{constructor(t,i=void 0,r=void 0,s,o,a,u,l,c,h,f,m,y,g){super();this.iframes=[];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.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);Hn.default.log(t.href),Hn.default.log(i),t.href=i,await this.navigate(t)}};this.savePosition=(0,l1.default)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,l1.default)(()=>{this.view?.atStart()&&this.view?.atEnd()?(this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit("resource.fits")):this.view?.atEnd()?(this.api?.resourceAtEnd&&this.api?.resourceAtEnd(),this.emit("resource.end")):this.view?.atStart()&&(this.api?.resourceAtStart&&this.api?.resourceAtStart(),this.emit("resource.start"))},200);this.highlighter=y,this.highlighter&&(this.highlighter.navigator=this);for(let b of g??[])b&&(b.navigator=this,b instanceof ll?this.annotationModule=b:b instanceof cl?this.bookmarkModule=b:b instanceof Il?this.ttsModule=b:b instanceof xl?this.searchModule=b:b instanceof Pl?this.definitionsModule=b:b instanceof fl?this.timelineModule=b:b instanceof ja?this.contentProtectionModule=b:b instanceof Ka?this.citationModule=b:b instanceof hl?this.mediaOverlayModule=b:b instanceof Tl?this.pageBreakModule=b:b instanceof Va?this.lineFocusModule=b:b instanceof Ml?this.historyModule=b:b instanceof ul&&(this.consumptionModule=b));this.settings=t,this.annotator=i,this.view=t.view,this.view.attributes=c,this.view.navigator=this,this.eventHandler=new gd(this),this.touchEventHandler=new Od(this),this.keyboardEventHandler=new Bd(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.attributes=c||{margin:0},this.services=h,this.sample=f,this.requestConfig=m,this.sampleReadEventHandler=new Nd(this)}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||{margin:0},t.services,t.sample,t.requestConfig,t.highlighter,t.modules);return await i.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(r=>r(i))}stop(){Hn.default.log("Iframe navigator stop"),Se(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),Se(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),Se(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Se(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),Se(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Se(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),Se(this.tryAgainButton,"click",this.tryAgain.bind(this)),Se(this.goBackButton,"click",n.goBack.bind(this)),Se(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),Se(window,"resize",this.onResize),this.iframes.forEach(t=>{Se(t,"resize",this.onResize)}),this.didInitKeyboardEventHandler&&this.keyboardEventHandler.removeEvents(document)}setDirection(t){let i="";(t==="rtl"||t==="ltr")&&(i=t),t==="auto"&&(i=this.publication.Metadata.Direction2),i&&(i==="rtl"&&(this.spreads.style.flexDirection="row-reverse"),i==="ltr"&&(this.spreads.style.flexDirection="row"),this.keyboardEventHandler.rtl=i==="rtl",this.api?.direction&&this.api?.direction(i),this.emit("direction",i))}async start(t,i,r){this.headerMenu=i,this.mainElement=t;try{let y=gt(t,"main#iframe-wrapper");y.style.overflow="auto";let g=ge(t,"main#iframe-wrapper iframe"),b=ge(t,"#second");if(g&&this.iframes.push(g),b&&this.iframes.push(b),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.iframes.length===0){y.style.overflow="auto";let A=document.createElement("iframe");if(A.setAttribute("SCROLLING","no"),A.setAttribute("allowtransparency","true"),this.iframes.push(A),this.publication.isFixedLayout){this.spreads=document.createElement("div"),this.firstSpread=document.createElement("div"),this.spreads.style.display="flex",this.spreads.style.alignItems="center",this.spreads.style.justifyContent="center",this.spreads.appendChild(this.firstSpread),this.firstSpread.appendChild(this.iframes[0]),y.appendChild(this.spreads);let v="";switch(this.settings.direction){case 0:v="auto";break;case 1:v="ltr";break;case 2:v="rtl";break}this.setDirection(v)}else A.setAttribute("height","100%"),A.setAttribute("width","100%"),y.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 E=document.createElement("iframe");E.setAttribute("SCROLLING","no"),E.setAttribute("allowtransparency","true"),E.style.opacity="1",E.style.border="none",E.style.overflow="hidden",this.iframes.push(E),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 this.iframes[0].style.paddingTop=(this.attributes?.iframePaddingTop??0)+"px"}if(this.publication.isFixedLayout){let A=y.clientHeight;var s=this.iframes[0].parentElement?.parentElement;s.style.height=A+40+"px"}else this.iframes.length===2&&this.iframes.pop();if(this.loadingMessage=ge(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=s1,this.loadingMessage.style.display="none"),this.errorMessage=ge(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=cM,this.errorMessage.style.display="none"),this.tryAgainButton=ge(t,"button[class=try-again]"),this.goBackButton=ge(t,"button[class=go-back]"),this.infoTop=ge(t,"div[class='info top']"),this.infoBottom=ge(t,"div[class='info bottom']"),this.headerMenu&&(this.bookTitle=ge(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=ge(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=ge(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=ge(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=ge(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=ge(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=ge(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=ge(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=ge(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=ge(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=ge(this.headerMenu,"#container-view-pagelist")),r&&(this.linksBottom=ge(r,"ul.links.bottom")),r&&(this.linksMiddle=ge(r,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=ge(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=ge(t,"#next-chapter")),r&&(this.nextPageAnchorElement=ge(r,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=ge(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=ge(t,"#previous-chapter")),r&&(this.previousPageAnchorElement=ge(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 o=ge(this.headerMenu,"#menu-button-search"),a=ge(this.headerMenu,"#menu-button-tts"),u=ge(this.headerMenu,"#menu-button-bookmark"),l=ge(this.headerMenu,"#menu-button-play"),c=ge(this.headerMenu,"#menu-button-pause"),h=ge(this.headerMenu,"#menu-button-mediaoverlay");if(!this.rights.enableBookmarks){u&&u.parentElement?.style.setProperty("display","none");var f=ge(this.headerMenu,"#sidenav-section-bookmarks");f&&f.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var m=ge(this.headerMenu,"#sidenav-section-highlights");m&&m.style.setProperty("display","none")}this.rights.enableTTS||a&&a.parentElement?.style.setProperty("display","none"),this.rights.enableSearch||o&&o.parentElement?.style.setProperty("display","none"),o&&this.view?.navigator.publication.isFixedLayout&&o.parentElement?.style.setProperty("display","none"),this.hasMediaOverlays?(l&&l.parentElement?.style.removeProperty("display"),c&&c.parentElement?.style.removeProperty("display"),h&&h.parentElement?.style.removeProperty("display")):(l&&l.parentElement?.style.setProperty("display","none"),c&&c.parentElement?.style.setProperty("display","none"),h&&h.parentElement?.style.setProperty("display","none"))}else o&&o.parentElement?.style.setProperty("display","none"),a&&a.parentElement?.style.setProperty("display","none"),u&&u.parentElement?.style.setProperty("display","none");return this.setupEvents(),await this.loadManifest()}catch(y){return Hn.default.error(y),this.abortOnError(y),Promise.reject(y)}}setupEvents(){for(let t of this.iframes)te(t,"load",this.handleIFrameLoad.bind(this,t));te(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),te(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),te(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),te(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),te(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),te(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),te(this.tryAgainButton,"click",this.tryAgain.bind(this)),te(this.goBackButton,"click",n.goBack.bind(this)),te(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),te(window,"resize",this.onResize);for(let t of this.iframes)te(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=zr()-40-(this.attributes?.margin??0),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,l1.default)(()=>{this.isScrolling=!1},200),s=gt(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.annotationModule&&await this.annotationModule.drawHighlights(),this.rights.enableBookmarks&&this.bookmarkModule&&await this.bookmarkModule.drawBookmarks(),this.rights.enableSearch&&this.searchModule&&(await this.highlighter.destroyHighlights(1),this.searchModule.drawSearch()),this.rights.enablePageBreaks&&this.pageBreakModule&&(await this.highlighter.destroyHighlights(3),await this.pageBreakModule.drawPageBreaks()),this.rights.enableDefinitions&&this.definitionsModule&&await this.definitionsModule.drawDefinitions())},200))}async loadManifest(){try{let t=(l,c,h=!1)=>{var f=document.createElement("ul");h&&(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 A="";m.Href?(A=this.publication.getAbsoluteHref(m.Href),g.href=A,g.innerHTML=m.Title||"",y.appendChild(g)):(b.innerHTML=m.Title||"",b.className="chapter-title",y.appendChild(b)),m.Children&&m.Children.length>0&&t(y,m.Children,!0),f.appendChild(y)}te(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 A=y.href.slice(y.href.indexOf("#")+1);A!==void 0&&(g={fragment:A})}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);Hn.default.log(o.href),Hn.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 Hn.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.TypeLink})}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.TypeLink}: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.historyModule&&this.historyModule.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.TypeLink);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.TypeLink&&(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("chapterinfo",this.currentChapterLink.title)):(this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),this.api?.chapterInfo&&this.api.chapterInfo(void 0),this.emit("chapterinfo",void 0)),await this.injectInjectablesIntoIframeHead(t),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 h=>{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.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(t.height="0",this.view?.setIframeHeight?.(t)),this.rights.enableContentProtection&&this.contentProtectionModule&&await this.contentProtectionModule.initialize(t),this.rights.enableConsumption&&this.consumptionModule&&await this.consumptionModule.initialize(t),this.rights.enableAnnotations&&this.annotationModule&&await this.annotationModule.initialize(t),this.rights.enableBookmarks&&this.bookmarkModule&&await this.bookmarkModule.initialize(),this.rights.enableLineFocus&&this.lineFocusModule&&await this.lineFocusModule.initialize(t),this.rights.enableTTS&&this.ttsModule){let c=t.contentDocument?.body;await this.ttsModule.initialize(c)}return this.rights.enableTimeline&&this.timelineModule&&await this.timelineModule.initialize(),this.rights.enableMediaOverlays&&this.mediaOverlayModule&&this.hasMediaOverlays&&await this.mediaOverlayModule.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?.goToProgression(i);if(this.newPosition=void 0,this.rights?.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(10),this.hideLoadingMessage(),this.showIframeContents(t),this.rights.enableMediaOverlays&&this.mediaOverlayModule&&this.hasMediaOverlays){let c=this.currentLink();await this.mediaOverlayModule?.initializeResource(c)}await this.updatePositionInfo(),await this.view?.setSize(),setTimeout(()=>{this.mediaOverlayModule&&(this.mediaOverlayModule.settings.resourceReady=!0)},300)},200),new Promise(c=>c())}catch(i){return Hn.default.error(i),this.abortOnError(i),Promise.reject(i)}}async injectInjectablesIntoIframeHead(t){let i=[],r=o=>{let a=new Promise((u,l)=>{o.onload=()=>{u(!0)},o.onerror=c=>{let h=typeof c=="string"?c:`Injectable failed to load at: ${"href"in o?o.href:o.src}`;l(new Error(h))}});i.push(a)},s=t.contentDocument?.head;s&&(t.contentDocument.getElementsByTagName("base").length===0&&s.insertBefore(n.createBase(this.currentChapterLink.href),s.firstChild),this.injectables?.forEach(a=>{if(a.type==="style"){if(a.fontFamily){if(this.settings.initAddedFont(),!a.systemFont&&a.url){let u=n.createCssLink(a.url);s.appendChild(u),r(u)}}else if(a.r2before&&a.url){let u=n.createCssLink(a.url);s.insertBefore(u,s.firstChild),r(u)}else if(a.r2default&&a.url){let u=n.createCssLink(a.url);s.insertBefore(u,s.childNodes[1]),r(u)}else if(a.r2after&&a.url){a.appearance&&this.settings.initAddedAppearance();let u=n.createCssLink(a.url);s.appendChild(u),r(u)}else if(a.url){let u=n.createCssLink(a.url);s.appendChild(u),r(u)}}else if(a.type==="script"&&a.url){let u=n.createJavascriptLink(a.url,a.async??!1);s.appendChild(u),r(u)}})),i.length!==0&&await Promise.all(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 IFrameNavigator.");this.api.onError(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),r=(i??0)%2===1;this.showLoadingMessageAfterDelay(),this.currentSpreadLinks={};function s(l,c){let f=new DOMParser().parseFromString(l,"application/xhtml+xml");f.head&&f.getElementsByTagName("base").length===0&&f.head.insertBefore(n.createBase(c),f.head.firstChild);let m=f.documentElement.outerHTML,y=t.iframes[0].contentDocument;y&&(y.open(),y.write(m),y.close())}function o(l,c){let f=new DOMParser().parseFromString(l,"application/xhtml+xml");f.head&&f.getElementsByTagName("base").length===0&&f.head.insertBefore(n.createBase(c),f.head.firstChild);let m=f.documentElement.outerHTML,y=t.iframes[1].contentDocument;y&&(y.open(),y.write(m),y.close())}let a=new URL(this.currentChapterLink.href),u=window.location.protocol===a.protocol&&window.location.port===a.port&&window.location.hostname===a.hostname;if(this.api?.getContent)if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(r){if(this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(l=>{l===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{s.call(this,c,this.currentChapterLink.href)}):s.call(this,l,this.currentChapterLink.href)}),this.iframes.length===2)if((i??0)<this.publication.readingOrder.length-1){let l=this.publication.getNextSpineItem(this.currentChapterLink.href);if(l){let c=this.publication.getAbsoluteHref(l.Href);this.currentSpreadLinks.right={href:c},this.api?.getContent(c).then(h=>{h===void 0?u?this.iframes[1].src=c:fetch(c,this.requestConfig).then(f=>f.text()).then(async f=>{o.call(this,f,c),this.currentSpreadLinks.right={href:c}}):o.call(this,h,c)})}}else this.iframes[1].src="about:blank",this.currentSpreadLinks.right=void 0}else{if((i??0)>0){let l=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(l){let c=this.publication.getAbsoluteHref(l.Href);this.currentSpreadLinks.left={href:c},this.api?.getContent(c).then(h=>{h===void 0?u?this.iframes[0].src=c:fetch(c,this.requestConfig).then(f=>f.text()).then(async f=>{s.call(this,f,c)}):s.call(this,h,c)})}}else this.iframes[0].src="about:blank",this.currentSpreadLinks.left=void 0;this.iframes.length===2&&this.publication.isFixedLayout&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},this.api.getContent(this.currentChapterLink.href).then(l=>{l===void 0?u?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{o.call(this,c,this.currentChapterLink.href)}):o.call(this,l,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(l=>{l===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{s.call(this,c,this.currentChapterLink.href)}):s.call(this,l,this.currentChapterLink.href)});else this.api?.getContent(this.currentChapterLink.href).then(l=>{this.currentSpreadLinks.left={href:this.currentChapterLink.href},l===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{s.call(this,c,this.currentChapterLink.href)}):s.call(this,l,this.currentChapterLink.href)});else if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(r){if(u){if(this.iframes[0].src=this.currentChapterLink.href,this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.iframes.length===2)if((i??0)<this.publication.readingOrder.length-1){let l=this.publication.getNextSpineItem(this.currentChapterLink.href);if(l){let c=this.publication.getAbsoluteHref(l.Href);this.iframes[1].src=c,this.currentSpreadLinks.right={href:c}}}else this.iframes[1].src="about:blank",this.currentSpreadLinks.right=void 0}else if(fetch(this.currentChapterLink.href,this.requestConfig).then(l=>l.text()).then(async l=>{s.call(this,l,this.currentChapterLink.href)}),this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.iframes.length===2)if((i??0)<this.publication.readingOrder.length-1){let l=this.publication.getNextSpineItem(this.currentChapterLink.href);if(l){let c=this.publication.getAbsoluteHref(l.Href);this.currentSpreadLinks.right={href:c},fetch(c,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,c)})}}else this.iframes[1].src="about:blank",this.currentSpreadLinks.right=void 0}else if((i??0)>0){let l=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(l){let c=this.publication.getAbsoluteHref(l.Href);this.currentSpreadLinks.left={href:c},u?(this.iframes[0].src=c,this.iframes.length===2&&(this.iframes[1].src=this.currentChapterLink.href,this.currentSpreadLinks.right={href:this.currentChapterLink.href})):(fetch(c,this.requestConfig).then(h=>h.text()).then(async h=>{s.call(this,h,c)}),this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)})))}}else this.iframes[0].src="about:blank",this.currentSpreadLinks.left=void 0,this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},u?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(l=>l.text()).then(async l=>{o.call(this,l,this.currentChapterLink.href)}));else this.currentSpreadLinks.left={href:this.currentChapterLink.href},u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(l=>l.text()).then(async l=>{s.call(this,l,this.currentChapterLink.href)});else this.currentSpreadLinks.left={href:this.currentChapterLink.href},u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(l=>l.text()).then(async l=>{s.call(this,l,this.currentChapterLink.href)});this.publication.isFixedLayout&&setTimeout(()=>{let l,c,h;if(i===0&&this.iframes?.length===2?h=this.iframes[1].contentDocument:h=this.iframes[0].contentDocument,h&&h.body&&(l=getComputedStyle(h.body).height,c=getComputedStyle(h.body).width,parseInt(l.toString().replace("px",""))===0||parseInt(c.toString().replace("px",""))===0)){let v=Pi(h,"head");if(v){let E=ge(v,"meta[name=viewport]");if(E){var f=E.content,m=f.split(",").reduce((S,C)=>{var[T,M]=C.match(/[^\s;=]+/g);return S[T]=isNaN(Number(M))?M:+M,S},{});l=m.height+"px",c=m.width+"px"}}}var y=i===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(y&&c){let v=this.attributes?.fixedLayoutMargin??100;var g=(parseInt(getComputedStyle(y).width)-v)/(this.iframes.length===2?parseInt(c.toString().replace("px",""))*2+v*2:parseInt(c.toString().replace("px",""))),b=(parseInt(getComputedStyle(y).height)-v)/parseInt(l.toString().replace("px","")),A=Math.min(g,b);y.style.transform="scale("+A+")";for(let E of this.iframes)E.style.height=l,E.style.width=c,E.parentElement&&(E.parentElement.style.height=l)}},400)}static goBack(){window.history.back()}handleEditClick(t){var i=t.target;if(this.headerMenu){var r=ge(document,".sidenav");i.className.indexOf(" active")===-1?(i.className+=" active",r.className+=" expanded",i.innerText="unfold_less",this.sideNavExpanded=!0,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights()):(i.className=i.className.replace(" active",""),r.className=r.className.replace(" expanded",""),i.innerText="unfold_more",this.sideNavExpanded=!1,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights())}t.preventDefault(),t.stopPropagation()}get hasMediaOverlays(){return this.publication.hasMediaOverlays}startReadAloud(){this.rights.enableTTS&&this.ttsModule.speakPlay()}startReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.startReadAloud()}stopReadAloud(){this.rights.enableTTS&&this.highlighter?.stopReadAloud()}stopReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.stopReadAloud()}pauseReadAloud(){this.rights.enableTTS&&(this.ttsModule.speakPause(),this.annotationModule!==void 0&&this.annotationModule.drawHighlights())}pauseReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.pauseReadAloud()}resumeReadAloud(){this.rights.enableTTS&&this.ttsModule.speakResume()}resumeReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.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);Hn.default.log(t.href),Hn.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.pageBreakModule!==void 0&&await this.pageBreakModule.goToPageNumber(t)}snapToSelector(t){let i=this.iframes[0].contentDocument;if(i){Hn.default.log(t);let r=i.querySelectorAll(t);r.length>0&&this.view?.snap(r[0])}}applyAttributes(t){this.attributes=t,this.view.attributes=t,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("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);let c=zr()-40-(this.attributes?.margin??0);var i=t===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(i){i.style.height=c+40+"px";let h,f,m;t===0&&this.iframes?.length===2?m=this.iframes[1].contentDocument:m=this.iframes[0].contentDocument,m&&m.body&&(h=getComputedStyle(m.body).height,f=getComputedStyle(m.body).width);let y=Pi(m,"head");if(y){let b=ge(y,"meta[name=viewport]");if(b){var r=b.content,s={};r.split(",").forEach(A=>{let v=A.match(/[^\s;=]+/g);if(v&&v.length>=2){let[E,S]=v;s[E]=isNaN(Number(S))?S:+S}}),(parseInt(String(s.height))!==0||parseInt(String(s.width))!==0)&&(h=s.height.toString().endsWith("px")?s.height:s.height+"px",f=s.width.toString().endsWith("px")?s.width:s.width+"px")}}let g=this.attributes?.fixedLayoutMargin??100;var o=(parseInt(getComputedStyle(i).width)-g)/(this.iframes.length===2?parseInt(f.toString().endsWith("px")?f?.replace("px",""):f)*2+g*2:parseInt(f.toString().endsWith("px")?f?.replace("px",""):f)),a=(parseInt(getComputedStyle(i).height)-g)/parseInt(h.toString().replace("px","")),u=Math.min(o,a);i.style.transform="scale("+u+")";for(let b of this.iframes)b.style.height=h,b.style.width=f,b.parentElement&&(b.parentElement.style.height=h)}}let l=this.view?.getCurrentPosition();await this.settings.applyProperties(),this.infoTop&&(this.infoTop.style.height="0px"),this.infoTop&&(this.infoTop.style.minHeight="0px"),this.infoBottom&&(this.infoBottom.style.height=this.attributes?.bottomInfoHeight?this.attributes.bottomInfoHeight+"px":"40px"),this.view?.layout!=="fixed"&&this.settings.isPaginated().then(c=>{c?(this.view.height=zr()-40-(this.attributes?.margin??0),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()=>{l&&this.view?.goToProgression(l),this.updatePositionInfo(!1),this.contentProtectionModule!==void 0&&await this.contentProtectionModule.handleResize(),this.annotationModule!==void 0&&await this.annotationModule.handleResize(),this.bookmarkModule!==void 0&&await this.bookmarkModule.handleResize(),this.searchModule!==void 0&&await this.searchModule.handleResize(),this.definitionsModule!==void 0&&await this.definitionsModule.handleResize(),this.pageBreakModule!==void 0&&await this.pageBreakModule.handleResize(),this.lineFocusModule!==void 0&&this.lineFocusModule.handleResize(),this.historyModule!==void 0&&await this.historyModule.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("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.TypeLink,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.TypeLink,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("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(" active","");let r=this.tocView.querySelector('li > a[href^="'+t+'"]');r&&(r.className+=" active")}}async navigate(t,i=!0){if(this.rights.enableConsumption&&this.consumptionModule&&i&&this.consumptionModule.startReadingSession(t),this.historyModule&&await this.historyModule.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 h=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:h}}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.newElementId){for(let h of this.iframes){let f=h.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(f)}this.newElementId=void 0}else if(t.highlight){let h=t.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;h&&this.view?.goToCssSelector(h)}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.TypeLink,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.TypeLink,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.TypeLink);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.TypeLink&&(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("chapterinfo",this.currentChapterLink.title)):(this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),this.api?.chapterInfo&&this.api.chapterInfo(void 0),this.emit("chapterinfo",void 0)),await this.updatePositionInfo()}else this.lineFocusModule!==void 0&&this.lineFocusModule.disableLineFocus(!1),this.searchModule!==void 0&&this.searchModule.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.contentProtectionModule!==void 0&&await this.contentProtectionModule.initializeResource(),this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&await this.mediaOverlayModule.initializeResource(this.currentLink()),this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(300),this.bookmarkModule&&(await this.bookmarkModule.drawBookmarks(),await this.bookmarkModule.showBookmarks()),this.pageBreakModule&&(await this.highlighter?.destroyHighlights(3),await this.pageBreakModule.drawPageBreaks()),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(1),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule&&this.highlighter&&await this.definitionsModule.drawDefinitions(),this.rights.enableConsumption&&this.consumptionModule&&this.consumptionModule.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("resource.fits")):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.mediaOverlayModule!==void 0&&(this.mediaOverlayModule.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(()=>{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("resource.fits")):this.view?.atEnd()?(this.api?.resourceAtEnd&&this.api?.resourceAtEnd(),this.emit("resource.end")):this.view?.atStart()&&(this.api?.resourceAtStart&&this.api?.resourceAtStart(),this.emit("resource.start"))),this.api?.resourceReady&&this.api?.resourceReady(),this.emit("resource.ready")},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.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){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=>(Hn.default.log("api updated current location",r),this.annotator?.saveLastReadingPosition(r))):(Hn.default.log("save last reading position",r),this.annotator.saveLastReadingPosition(r)),this.consumptionModule&&this.consumptionModule.continueReadingSession(r))}}}static createBase(t){let i=document.createElement("base");return i.target="_self",i.href=t,i}static createCssLink(t){let i=document.createElement("link");return i.rel="stylesheet",i.type="text/css",i.href=t,i}static createJavascriptLink(t,i){let r=document.createElement("script");return r.type="text/javascript",r.src=t,r.async=i,r}activateMarker(t,i){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId===void 0||this.annotationModule.activeAnnotationMarkerId!==t?(this.annotationModule.activeAnnotationMarkerId=t,this.annotationModule.activeAnnotationMarkerPosition=i,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=t)):this.deactivateMarker())}deactivateMarker(){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId=void 0,this.annotationModule.activeAnnotationMarkerPosition=void 0,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=void 0))}showLayer(t){let i="#",r=new ju("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=ge(s,i);o&&(o.style.display="block")}}hideLayer(t){let i="#",r=new ju("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=ge(s,i);o&&(o.style.display="none")}}};_();var wt=class wt{constructor(e){this.store=e.store}getLastReadingPosition(){let e=this.store.get(wt.LAST_READING_POSITION);return e?JSON.parse(e):null}initLastReadingPosition(e){if(typeof e=="string")this.store.set(wt.LAST_READING_POSITION,e);else{let t=JSON.stringify(e);this.store.set(wt.LAST_READING_POSITION,t)}}saveLastReadingPosition(e){if(typeof e=="string")this.store.set(wt.LAST_READING_POSITION,e);else{let t=JSON.stringify(e);this.store.set(wt.LAST_READING_POSITION,t)}}initBookmarks(e){if(typeof e=="string"){let t=JSON.parse(e);this.store.set(wt.BOOKMARKS,JSON.stringify(t))}else this.store.set(wt.BOOKMARKS,JSON.stringify(e));return e}saveBookmark(e){let t=this.store.get(wt.BOOKMARKS);if(t){let i=JSON.parse(t);i.push(e),this.store.set(wt.BOOKMARKS,JSON.stringify(i))}else{let i=[];i.push(e),this.store.set(wt.BOOKMARKS,JSON.stringify(i))}return e}locatorExists(e,t){let i;t===0&&(i=wt.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(wt.BOOKMARKS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.id!==e.id),this.store.set(wt.BOOKMARKS,JSON.stringify(i))}return e}getBookmarks(e){let t=this.store.get(wt.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=ys.hash(s);r.highlight.id="R2_HIGHLIGHT_"+o;let a;r.highlight.color?a=r.highlight.color:r.color&&(a=r.color),Xt.isHexColor(a)&&(a=Xt.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(wt.ANNOTATIONS,JSON.stringify(i)),i}saveTemporarySelectionInfo(e){this.store.set(wt.SELECTIONINFO,JSON.stringify(e))}getTemporarySelectionInfo(e){if(!e)return null;let t=this.store.get(wt.SELECTIONINFO);if(t){let i=JSON.parse(t);return i.range=yp(e,i.rangeInfo),i}return null}deleteTemporarySelectionInfo(){this.store.remove(wt.SELECTIONINFO)}saveAnnotation(e){let t=this.store.get(wt.ANNOTATIONS);if(t){let i=JSON.parse(t);i.push(e),this.store.set(wt.ANNOTATIONS,JSON.stringify(i))}else{let i=[];i.push(e),this.store.set(wt.ANNOTATIONS,JSON.stringify(i))}return e}deleteAnnotation(e){let t=this.store.get(wt.ANNOTATIONS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.id!==e),this.store.set(wt.ANNOTATIONS,JSON.stringify(i))}return e}deleteSelectedAnnotation(e){let t=this.store.get(wt.ANNOTATIONS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.highlight?.id!==e.highlight.id),this.store.set(wt.ANNOTATIONS,JSON.stringify(i))}return e}getAnnotations(){let e=this.store.get(wt.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(wt.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(wt.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(wt.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(wt.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(wt.ANNOTATIONS);if(t){let r=JSON.parse(t).filter(s=>s.highlight?.id===e);if(r.length>0)return r[0]}return null}};wt.LAST_READING_POSITION="last-reading-position",wt.BOOKMARKS="bookmarks",wt.ANNOTATIONS="annotations",wt.SELECTIONINFO="selectionInfo";var Ud=wt;_();_();var Ll=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 za=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 Ll: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 Ll}}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))}};ui();_();var CM=Qe(Ic()),SM=Qe(Ji());var Rl=class extends CM.Link{};Rl=Cf([(0,SM.JsonObject)()],Rl);function qa(n){let e,t,i,r;if(n instanceof Array)return n.map(function(s){return typeof s=="object"&&(s=qa(s)),s});e={};for(t in n)n.hasOwnProperty(t)&&(i=(t.charAt(0).toLowerCase()+t.slice(1)||t).toString(),r=n[t],(r instanceof Array||r!=null&&r.constructor===Object)&&(r=qa(r)),i==="href1"?e.href=r:i==="typeLink"?e.type=r:e[i]=r);return e}_();var _M=Qe(Qt()),c1=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(){_M.default.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let e=new ds,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}};var A4;async function Dee(){return A4||(A4=(await Promise.resolve().then(()=>(lR(),uR))).PDFNavigator),A4}function ra(n){return n?.isPDF===!0}var Zl=class n{constructor(e,t,i,r,s,o,a,u,l,c,h,f,m,y,g,b,A,v){this.settings=e;this.navigator=t;this.highlighter=i;this.bookmarkModule=r;this.annotationModule=s;this.ttsSettings=o;this.ttsModule=a;this.searchModule=u;this.definitionsModule=l;this.contentProtectionModule=c;this.timelineModule=h;this.mediaOverlaySettings=f;this.mediaOverlayModule=m;this.pageBreakModule=y;this.lineFocusModule=g;this.historyModule=b;this.citationModule=A;this.consumptionModule=v;this.startReadAloud=()=>{this.navigator instanceof _t&&this.navigator.startReadAloud()};this.stopReadAloud=()=>{this.navigator instanceof _t&&this.navigator.stopReadAloud()};this.pauseReadAloud=()=>{this.navigator instanceof _t&&this.navigator.pauseReadAloud()};this.resumeReadAloud=()=>{this.navigator instanceof _t&&this.navigator.resumeReadAloud()};this.startReadAlong=()=>{this.navigator instanceof _t&&this.navigator.startReadAlong()};this.stopReadAlong=()=>{this.navigator instanceof _t&&this.navigator.stopReadAlong()};this.pauseReadAlong=()=>{this.navigator instanceof _t&&this.navigator.pauseReadAlong()};this.resumeReadAlong=()=>{this.navigator instanceof _t&&this.navigator.resumeReadAlong()};this.saveBookmark=async()=>await this.bookmarkModule?.saveBookmark()??!1;this.saveBookmarkPlus=async()=>this.bookmarkModule?.saveBookmarkPlus();this.deleteBookmark=async e=>await this.bookmarkModule?.deleteBookmark(e)??!1;this.deleteAnnotation=async e=>await this.annotationModule?.deleteAnnotation(e)??!1;this.addAnnotation=async e=>await this.annotationModule?.addAnnotation(e)??!1;this.updateAnnotation=async e=>await this.annotationModule?.updateAnnotation(e)??!1;this.changeHighlighterColor=e=>{this.highlighter?.setColor(e)};this.hideAnnotationLayer=()=>this.annotationModule?.hideAnnotationLayer();this.showAnnotationLayer=()=>this.annotationModule?.showAnnotationLayer();this.hideLayer=e=>this.navigator instanceof _t?this.navigator?.hideLayer(e):!1;this.showLayer=e=>this.navigator instanceof _t?this.navigator?.showLayer(e):!1;this.activateMarker=(e,t)=>this.navigator instanceof _t?this.navigator?.activateMarker(e,t):!1;this.deactivateMarker=()=>this.navigator instanceof _t?this.navigator?.deactivateMarker():!1;this.clearDefinitions=async()=>{await this.definitionsModule?.clearDefinitions()};this.addDefinition=async e=>{await this.definitionsModule?.addDefinition(e)};this.historyBack=async()=>this.historyModule?.historyBack();this.historyForward=async()=>this.historyModule?.historyForward();this.search=async(e,t)=>await this.searchModule?.search(e,t)??[];this.goToSearchIndex=async(e,t,i)=>{this.navigator instanceof _t&&this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchIndex(e,t,i)};this.goToSearchID=async(e,t,i)=>{this.navigator instanceof _t&&this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchID(e,t,i)};this.clearSearch=async()=>{this.navigator instanceof _t&&this.navigator.rights.enableSearch&&await this.searchModule?.clearSearch()};this.resetUserSettings=async()=>await this.settings.resetUserSettings();this.applyUserSettings=async e=>await this.settings.applyUserSettings(e);this.scroll=async(e,t)=>ra(this.navigator)?this.navigator.scroll(e,t):await this.settings.scroll(e);this.increase=async e=>{this.isTTSIncrementable(e)?this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.increase(e):this.isMOIncrementable(e)?this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.increase(e):await this.settings.increase(e)};this.decrease=async e=>{this.isTTSIncrementable(e)?this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.decrease(e):this.isMOIncrementable(e)?this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.decrease(e):await this.settings.decrease(e)};this.resetTTSSettings=()=>{this.navigator instanceof _t&&this.navigator.rights.enableTTS&&this.ttsSettings?.resetTTSSettings()};this.applyTTSSettings=async e=>{this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.applyTTSSettings(e)};this.applyPreferredVoice=async e=>{this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.applyPreferredVoice(e)};this.resetMediaOverlaySettings=async()=>{this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.resetMediaOverlaySettings()};this.applyMediaOverlaySettings=async e=>{this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&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=()=>{ra(this.navigator)&&this.navigator.fitToPage()};this.fitToWidth=()=>{ra(this.navigator)&&this.navigator.fitToWidth()};this.zoomIn=()=>{ra(this.navigator)&&this.navigator.zoomIn()};this.zoomOut=()=>{ra(this.navigator)&&this.navigator.zoomOut()};this.activateHand=()=>{ra(this.navigator)&&this.navigator.activateHand()};this.deactivateHand=()=>{ra(this.navigator)&&this.navigator.deactivateHand()};this.copyToClipboard=e=>{this.contentProtectionModule?.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 instanceof _t&&this.navigator.snapToSelector(e)};this.applyAttributes=e=>{this.navigator instanceof _t&&this.navigator.applyAttributes(e)};this.stop=()=>{document.body.onscroll=()=>{},this.navigator.stop(),this.settings.stop(),this.ttsSettings?.stop(),this.ttsModule?.stop(),this.bookmarkModule?.stop(),this.annotationModule?.stop(),this.searchModule?.stop(),this.definitionsModule?.stop(),this.contentProtectionModule?.stop(),this.timelineModule?.stop(),this.mediaOverlaySettings?.stop(),this.mediaOverlayModule?.stop(),this.pageBreakModule?.stop(),this.lineFocusModule?.stop(),this.citationModule?.stop(),this.consumptionModule?.stop()}}addEventListener(e,t){(this.navigator instanceof _t||ra(this.navigator))&&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 ja.setupPreloadProtection(e.protection);let i=gt(document,"#D2Reader-Container"),r=ge(document,"#headerMenu"),s=ge(document,"#footerMenu"),o=e.url,a;e.publication?(a=Sa(e.publication,zs),a.manifestUrl=new URL(o)):a=await zs.fromUrl(o,e.requestConfig);let u=new za({prefix:a.manifestUrl,useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),l=new za({prefix:"r2d2bc-reader",useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),c=new za({prefix:"r2d2bc-layers",useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),h=new Ud({store:u});if(a.sample=e.sample,t=Fee(t,a),a.Metadata.ConformsTo&&a.Metadata.ConformsTo.includes("https://readium.org/webpub-manifest/profiles/pdf")){let f=await yd.create({store:l,initialUserSettings:e.userSettings,layout:""}),y=await(await Dee()).create({mainElement:i,publication:a,settings:f,api:e.api,workerSrc:e.workerSrc,annotator:h,initialLastReadingPosition:e.lastReadingPosition,store:u});return new n(f,y)}else{t.autoGeneratePositions?await a.autoGeneratePositions(e.requestConfig):(e.services?.positions&&await a.fetchPositionsFromService(e.services?.positions.href,e.requestConfig),e.services?.weight&&await a.fetchWeightsFromService(e.services?.weight.href,e.requestConfig));let f=await c1.create({store:c}),m=await yd.create({store:l,initialUserSettings:e.userSettings,headerMenu:r,api:e.api,injectables:(a.Metadata.Rendition?.Layout??"unknown")==="fixed"?e.injectablesFixed:e.injectables,layout:(a.Metadata.Rendition?.Layout??"unknown")==="fixed"?"fixed":"reflowable"}),y=await Xt.create({layerSettings:f,...e.highlighter}),g=t.enableBookmarks?await cl.create({annotator:h,headerMenu:r,rights:t,publication:a,initialAnnotations:e.initialAnnotations,...e.bookmarks}):void 0,b=t.enableAnnotations?await ll.create({annotator:h,rights:t,publication:a,initialAnnotations:e.initialAnnotations,highlighter:y,headerMenu:r,...e.annotations}):void 0,A=t.enableTTS,v=A?await r1.create({store:l,initialTTSSettings:e.tts,headerMenu:r}):void 0,E;A&&v&&(E=await Il.create({tts:v,headerMenu:r,rights:t,highlighter:y,...e.tts}));let S=t.enableSearch?await xl.create({headerMenu:r,publication:a,highlighter:y,...e.search}):void 0,C=t.enableDefinitions?await Pl.create({publication:a,highlighter:y,...e.define}):void 0,T=t.enableTimeline?await fl.create({publication:a}):void 0,M=t.enableContentProtection?await ja.create({...e.protection}):void 0,I=t.enableCitations?await Ka.create({publication:a,highlighter:y,...e.citations}):void 0,L=t.enableMediaOverlays,R=L?await wp.create({store:l,initialMediaOverlaySettings:e.mediaOverlays,headerMenu:r,...e.mediaOverlays}):void 0,B=L?await hl.create({publication:a,settings:R,...e.mediaOverlays}):void 0,H=t.enablePageBreaks&&a.isReflowable?await Tl.create({publication:a,headerMenu:r,...e.pagebreak}):void 0,j=t.enableLineFocus?await Va.create({publication:a,highlighter:y,...e.lineFocus}):void 0,U=t.enableHistory?await Ml.create({annotator:h,publication:a,headerMenu:r}):void 0,z=t.enableConsumption?await ul.create({publication:a,...e.consumption}):void 0,V=await _t.create({mainElement:i,headerMenu:r,footerMenu:s,publication:a,settings:m,annotator:h,initialLastReadingPosition:e.lastReadingPosition,api:e.api,rights:t,tts:e.tts,sample:e.sample,requestConfig:e.requestConfig,injectables:(a.Metadata.Rendition?.Layout??"unknown")==="fixed"?e.injectablesFixed??[]:e.injectables,attributes:e.attributes,services:e.services,highlighter:y,modules:[g,b,E,S,C,T,M,I,B,H,j,U,z]});return new n(m,V,y,g,b,v,E,S,C,M,T,R,B,H,j,U,I,z)}}get hasMediaOverlays(){return this.navigator instanceof _t?this.navigator.hasMediaOverlays:!1}get tableOfContents(){return qa(this.navigator.tableOfContents())??[]}get landmarks(){return qa(this.navigator.landmarks())??[]}get pageList(){return qa(this.navigator.pageList())??[]}get readingOrder(){return qa(this.navigator.readingOrder())??[]}get bookmarks(){return this.bookmarkModule?.getBookmarks()??[]}get annotations(){return this.annotationModule?.getAnnotations()}get publicationLayout(){return this.navigator.publication.layout}get history(){return this.historyModule?.history}get historyCurrentIndex(){return this.historyModule?.historyCurrentIndex}get currentResource(){return this.navigator.currentResource()}get mostRecentNavigatedTocItem(){return this.navigator instanceof _t?this.navigator.mostRecentNavigatedTocItem():!1}get totalResources(){return this.navigator.totalResources()}get publicationLanguage(){return this.navigator.publication.Metadata.Language}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 instanceof _t?this.navigator.atStart():!1}get atEnd(){return this.navigator instanceof _t?this.navigator.atEnd():!1}async applyLineFocusSettings(e){if(e.lines&&this.lineFocusModule){let t=this.lineFocusModule.properties.lines??1;this.lineFocusModule.index=this.lineFocusModule.index*t/parseInt(e.lines),this.lineFocusModule.index=Math.abs(parseInt(this.lineFocusModule.index.toFixed())),this.lineFocusModule.properties.lines=parseInt(e.lines),this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus()}e.debug!==void 0&&this.lineFocusModule&&(this.lineFocusModule.isDebug=e.debug,this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus())}lineUp(){this.lineFocusModule?.lineUp()}lineDown(){this.lineFocusModule?.lineDown()}async enableLineFocus(){await this.lineFocusModule?.enableLineFocus()}async lineFocus(e){e?await this.lineFocusModule?.enableLineFocus():this.lineFocusModule?.disableLineFocus()}disableLineFocus(){this.lineFocusModule?.disableLineFocus()}};function Fee(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}var Hee=Zl,Uee=Zl.load;return Qn(jee);})();
|
|
602
|
+
`)}#S(e,t){let i=document.getSelection(),{focusNode:r,anchorNode:s}=i;if(s&&r&&i.containsNode(this.#_)){if(this.#v||e===Is.ENABLE_PERMISSIONS){G3(t);return}this.#v=!0;let{classList:o}=this.viewer;o.add("copyAll");let a=new AbortController;window.addEventListener("keydown",u=>this.#w=u.key==="Escape",{signal:a.signal}),this.getAllText().then(async u=>{u!==null&&await navigator.clipboard.writeText(u)}).catch(u=>{console.warn(`Something goes wrong when extracting the text: ${u.message}`)}).finally(()=>{this.#v=!1,this.#w=!1,a.abort(),o.remove("copyAll")}),G3(t)}}setDocument(e){if(this.pdfDocument&&(this.eventBus.dispatch("pagesdestroy",{source:this}),this._cancelRendering(),this._resetView(),this.findController?.setDocument(null),this._scriptingManager?.setDocument(null),this.#r?.destroy(),this.#r=null,this.#i=Gn.NONE,this.#A=!0),this.pdfDocument=e,!e)return;let t=e.numPages,i=e.getPage(1),r=e.getOptionalContentConfig({intent:"display"}),s=this.#d?e.getPermissions():Promise.resolve(),{eventBus:o,pageColors:a,viewer:u}=this;this.#c=new AbortController;let{signal:l}=this.#c;if(t>Ag.FORCE_SCROLL_MODE_PAGE){console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document.");let f=this._scrollMode=ct.PAGE;o.dispatch("scrollmodechanged",{source:this,mode:f})}this._pagesCapability.promise.then(()=>{o.dispatch("pagesloaded",{source:this,pagesCount:t})},()=>{});let c=f=>{let m=this._pages[f.pageNumber-1];m&&this.#e.push(m)};o._on("pagerender",c,{signal:l});let h=f=>{f.cssTransform||f.isDetailView||(this._onePageRenderedCapability.resolve({timestamp:f.timestamp}),o._off("pagerendered",h))};o._on("pagerendered",h,{signal:l}),Promise.all([i,s]).then(([f,m])=>{if(e!==this.pdfDocument)return;this._firstPageCapability.resolve(f),this._optionalContentConfigPromise=r;let{annotationEditorMode:y,annotationMode:g,textLayerMode:b}=this.#V(m);if(b!==Is.DISABLE){let S=this.#_=document.createElement("div");S.id="hiddenCopyElement",u.before(S)}if(y!==Gn.DISABLE){let S=y;e.isPureXfa?console.warn("Warning: XFA-editing is not implemented."):WL(S)?(this.#r=new QX(this.container,u,this.#N,this.#t,this.#s,this.#B,o,e,a,this.#n,this.#h,this.#f,this.#m,this.#y,this.#l,this.#k),o.dispatch("annotationeditoruimanager",{source:this,uiManager:this.#r}),S!==Gn.NONE&&(this.#ee(S),this.#r.updateMode(S))):console.error(`Invalid AnnotationEditor mode: ${S}`)}let A=this._scrollMode===ct.PAGE?null:u,v=this.currentScale,E=f.getViewport({scale:v*bo.PDF_TO_CSS_UNITS});u.style.setProperty("--scale-factor",E.scale),a?.background&&u.style.setProperty("--page-bg-color",a.background),(a?.foreground==="CanvasText"||a?.background==="Canvas")&&(u.style.setProperty("--hcm-highlight-filter",e.filterFactory.addHighlightHCMFilter("highlight","CanvasText","Canvas","HighlightText","Highlight")),u.style.setProperty("--hcm-highlight-selected-filter",e.filterFactory.addHighlightHCMFilter("highlight_selected","CanvasText","Canvas","HighlightText","ButtonText")));for(let S=1;S<=t;++S){let C=new Rg({container:A,eventBus:o,id:S,scale:v,defaultViewport:E.clone(),optionalContentConfigPromise:r,renderingQueue:this.renderingQueue,textLayerMode:b,annotationMode:g,imageResourcesPath:this.imageResourcesPath,maxCanvasPixels:this.maxCanvasPixels,maxCanvasDim:this.maxCanvasDim,capCanvasAreaFactor:this.capCanvasAreaFactor,enableDetailCanvas:this.enableDetailCanvas,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering,pageColors:a,l10n:this.l10n,layerProperties:this._layerProperties,enableHWA:this.#u,enableAutoLinking:this.#p,minDurationToUpdateCanvas:this.#g,commentManager:this.#s});this._pages.push(C)}this._pages[0]?.setPdfPage(f),this._scrollMode===ct.PAGE?this.#L():this._spreadMode!==ki.NONE&&this._updateSpreadMode(),o._on("annotationeditorlayerrendered",S=>{this.#r&&o.dispatch("annotationeditormodechanged",{source:this,mode:this.#i})},{once:!0,signal:l}),this.#P(l).then(async()=>{if(e!==this.pdfDocument)return;if(this.findController?.setDocument(e),this._scriptingManager?.setDocument(e),this.#_&&document.addEventListener("copy",this.#S.bind(this,b),{signal:l}),e.loadingParams.disableAutoFetch||t>Ag.FORCE_LAZY_PAGE_INIT){this._pagesCapability.resolve();return}let S=t-1;if(S<=0){this._pagesCapability.resolve();return}for(let C=2;C<=t;++C){let T=e.getPage(C).then(M=>{let I=this._pages[C-1];I.pdfPage||I.setPdfPage(M),--S===0&&this._pagesCapability.resolve()},M=>{console.error(`Unable to get page ${C} to initialize viewer`,M),--S===0&&this._pagesCapability.resolve()});C%Ag.PAUSE_EAGER_PAGE_INIT===0&&await T}}),o.dispatch("pagesinit",{source:this}),e.getMetadata().then(({info:S})=>{e===this.pdfDocument&&S.Language&&(u.lang=S.Language)}),this.defaultRenderingQueue&&this.update()}).catch(f=>{console.error("Unable to initialize viewer",f),this._pagesCapability.reject(f)})}onPagesEdited({pagesMapper:e,type:t,hasBeenCut:i,pageNumbers:r}){if(t==="copy"){this.#R=new Map;for(let l of r)this.#R.set(l,this._pages[l-1]);return}let s=t==="cut";if(s||t==="delete")for(let l of r)this._pages[l-1].deleteMe(s);this._currentPageNumber=0;let o=this._pages,a=this._pages=[];for(let l=1,c=e.pagesNumber;l<=c;l++){let h=e.getPrevPageNumber(l);if(h<0){let m=this.#R.get(-h);i?m.updatePageNumber(l):m=m.clone(l),a.push(m);continue}let f=o[h-1];a.push(f),f.updatePageNumber(l)}s||(this.#R=null);let u=this._scrollMode===ct.PAGE?null:this.viewer;if(u){u.replaceChildren();let l=document.createDocumentFragment();for(let c=0,h=e.pagesNumber;c<h;c++){let{div:f}=a[c];f.setAttribute("data-page-number",c+1),l.append(f)}u.append(l)}setTimeout(()=>{this.forceRendering()})}setPageLabels(e){if(this.pdfDocument){e?Array.isArray(e)&&this.pdfDocument.numPages===e.length?this._pageLabels=e:(this._pageLabels=null,console.error("setPageLabels: Invalid page labels.")):this._pageLabels=null;for(let t=0,i=this._pages.length;t<i;t++)this._pages[t].setPageLabel(this._pageLabels?.[t]??null)}}_resetView(){this._pages=[],this._currentPageNumber=1,this._currentScale=O3,this._currentScaleValue=null,this._pageLabels=null,this.#e=new g4(GL),this._location=null,this._pagesRotation=0,this._optionalContentConfigPromise=null,this._firstPageCapability=Promise.withResolvers(),this._onePageRenderedCapability=Promise.withResolvers(),this._pagesCapability=Promise.withResolvers(),this._scrollMode=ct.VERTICAL,this._previousScrollMode=ct.UNKNOWN,this._spreadMode=ki.NONE,this.#I={previousPageNumber:1,scrollDown:!0,pages:[]},this.#c?.abort(),this.#c=null,this.viewer.textContent="",this._updateScrollMode(),this.viewer.removeAttribute("lang"),this.#_?.remove(),this.#_=null,this.#Q(),this.#X()}#L(){if(this._scrollMode!==ct.PAGE)throw new Error("#ensurePageViewVisible: Invalid scrollMode value.");let e=this._currentPageNumber,t=this.#I,i=this.viewer;if(i.textContent="",t.pages.length=0,this._spreadMode===ki.NONE&&!this.isInPresentationMode){let r=this._pages[e-1];i.append(r.div),t.pages.push(r)}else{let r=new Set,s=this._spreadMode-1;s===-1?r.add(e-1):e%2!==s?(r.add(e-1),r.add(e)):(r.add(e-2),r.add(e-1));let o=document.createElement("div");if(o.className="spread",this.isInPresentationMode){let a=document.createElement("div");a.className="dummyPage",o.append(a)}for(let a of r){let u=this._pages[a];u&&(o.append(u.div),t.pages.push(u))}i.append(o)}t.scrollDown=e>=t.previousPageNumber,t.previousPageNumber=e}_scrollUpdate(){this.pagesCount!==0&&(this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.#b=null,this.update()},100),this.update())}#D(e,t=null){let{div:i,id:r}=e;if(this._currentPageNumber!==r&&this._setCurrentPageNumber(r),this._scrollMode===ct.PAGE&&(this.#L(),this.update()),!t&&!this.isInPresentationMode){let s=i.offsetLeft+i.clientLeft,o=s+i.clientWidth,{scrollLeft:a,clientWidth:u}=this.container;(this._scrollMode===ct.HORIZONTAL||s<a||o>a+u)&&(t={left:0,top:0})}$L(i,t),!this._currentScaleValue&&this._location&&(this._location=null)}#W(e){return e===this._currentScale||Math.abs(e-this._currentScale)<1e-15}#q(e,t,{noScroll:i=!1,preset:r=!1,drawingDelay:s=-1,origin:o=null}){if(this._currentScaleValue=t.toString(),this.#W(e)){r&&this.eventBus.dispatch("scalechanging",{source:this,scale:e,presetValue:t});return}this.viewer.style.setProperty("--scale-factor",e*bo.PDF_TO_CSS_UNITS);let a=s>=0&&s<1e3;this.refresh(!0,{scale:e,drawingDelay:a?s:-1}),a&&(this.#T=setTimeout(()=>{this.#T=null,this.refresh()},s));let u=this._currentScale;if(this._currentScale=e,!i){let l=this._currentPageNumber,c;if(this._location&&!(this.isInPresentationMode||this.isChangingPresentationMode)&&(l=this._location.pageNumber,c=[null,{name:"XYZ"},this._location.left,this._location.top,null]),this.scrollPageIntoView({pageNumber:l,destArray:c,allowNegativeOffset:!0}),Array.isArray(o)){let h=e/u-1,[f,m]=this.containerTopLeft;this.container.scrollLeft+=(o[0]-m)*h,this.container.scrollTop+=(o[1]-f)*h}}this.eventBus.dispatch("scalechanging",{source:this,scale:e,presetValue:r?t:void 0}),this.defaultRenderingQueue&&this.update()}get#Y(){return this._spreadMode!==ki.NONE&&this._scrollMode!==ct.HORIZONTAL?2:1}#U(e,t){let i=parseFloat(e);if(i>0)t.preset=!1,this.#q(i,e,t);else{let r=this._pages[this._currentPageNumber-1];if(!r)return;let s=gL,o=mL;this.isInPresentationMode?(s=o=4,this._spreadMode!==ki.NONE&&(s*=2)):this.removePageBorders?s=o=0:this._scrollMode===ct.HORIZONTAL&&([s,o]=[o,s]);let a=(this.container.clientWidth-s)/r.width*r.scale/this.#Y,u=(this.container.clientHeight-o)/r.height*r.scale;switch(e){case"page-actual":i=1;break;case"page-width":i=a;break;case"page-height":i=u;break;case"page-fit":i=Math.min(a,u);break;case"auto":let l=AL(r)?a:Math.min(u,a);i=Math.min(dZ,l);break;default:console.error(`#setScale: "${e}" is an unknown zoom value.`);return}t.preset=!0,this.#q(i,e,t)}}#G(){let e=this._pages[this._currentPageNumber-1];this.isInPresentationMode&&this.#U(this._currentScaleValue,{noScroll:!0}),this.#D(e)}pageLabelToPageNumber(e){if(!this._pageLabels)return null;let t=this._pageLabels.indexOf(e);return t<0?null:t+1}scrollPageIntoView({pageNumber:e,destArray:t=null,allowNegativeOffset:i=!1,ignoreDestinationZoom:r=!1,center:s=null}){if(!this.pdfDocument)return;let o=Number.isInteger(e)&&this._pages[e-1];if(!o){console.error(`scrollPageIntoView: "${e}" is not a valid pageNumber parameter.`);return}if(this.isInPresentationMode||!t){this._setCurrentPageNumber(e,!0);return}let a=0,u=0,l=0,c=0,h,f,m=o.rotation%180!==0,y=(m?o.height:o.width)/o.scale/bo.PDF_TO_CSS_UNITS,g=(m?o.width:o.height)/o.scale/bo.PDF_TO_CSS_UNITS,b=0;switch(t[1].name){case"XYZ":a=t[2],u=t[3],b=t[4],a=a!==null?a:0,u=u!==null?u:g;break;case"Fit":case"FitB":b="page-fit";break;case"FitH":case"FitBH":u=t[2],b="page-width",u===null&&this._location?(a=this._location.left,u=this._location.top):(typeof u!="number"||u<0)&&(u=g);break;case"FitV":case"FitBV":a=t[2],l=y,c=g,b="page-height";break;case"FitR":a=t[2],u=t[3],l=t[4]-a,c=t[5]-u;let S=gL,C=mL;this.removePageBorders&&(S=C=0),h=(this.container.clientWidth-S)/l/bo.PDF_TO_CSS_UNITS,f=(this.container.clientHeight-C)/c/bo.PDF_TO_CSS_UNITS,b=Math.min(Math.abs(h),Math.abs(f));break;default:console.error(`scrollPageIntoView: "${t[1].name}" is not a valid destination type.`);return}if(r||(b&&b!==this._currentScale?this.currentScaleValue=b:this._currentScale===O3&&(this.currentScaleValue=uZ)),b==="page-fit"&&!t[4]){this.#D(o);return}let A=[o.viewport.convertToViewportPoint(a,u),o.viewport.convertToViewportPoint(a+l,u+c)],v=Math.min(A[0][0],A[1][0]),E=Math.min(A[0][1],A[1][1]);s?((s==="both"||s==="vertical")&&(E-=(this.container.clientHeight-Math.abs(A[1][1]-A[0][1]))/2),(s==="both"||s==="horizontal")&&(v-=(this.container.clientWidth-Math.abs(A[1][0]-A[0][0]))/2)):i||(v=Math.max(v,0),E=Math.max(E,0)),this.#D(o,{left:v,top:E})}_updateLocation(e){let t=this._currentScale,i=this._currentScaleValue,r=parseFloat(i)===t?Math.round(t*1e4)/100:i,s=e.id,o=this._pages[s-1],a=this.container,u=o.getPagePoint(a.scrollLeft-e.x,a.scrollTop-e.y),l=Math.round(u[0]),c=Math.round(u[1]),h=`#page=${s}`;this.isInPresentationMode||(h+=`&zoom=${r},${l},${c}`),this._location={pageNumber:s,scale:r,top:c,left:l,rotation:this._pagesRotation,pdfOpenParams:h}}update(){let e=this._getVisiblePages(),t=e.views,i=t.length;if(i===0)return;let r=Math.max(GL,2*i+1);this.#e.resize(r,e.ids);for(let{view:u,visibleArea:l}of t)u.updateVisibleArea(l);for(let u of this.#e)e.ids.has(u.id)||u.updateVisibleArea(null);this.renderingQueue.renderHighestPriority(e);let s=this._spreadMode===ki.NONE&&(this._scrollMode===ct.PAGE||this._scrollMode===ct.VERTICAL),o=this._currentPageNumber,a=!1;for(let u of t){if(u.percent<100)break;if(u.id===o&&s){a=!0;break}}this._setCurrentPageNumber(a?this._currentPageNumber:t[0].id),this._updateLocation(e.first),this.eventBus.dispatch("updateviewarea",{source:this,location:this._location})}#F(){let e=this._getVisiblePages(),t=[],{ids:i,views:r}=e;for(let s of r){let{view:o}=s;if(!o.hasEditableAnnotations()){i.delete(o.id);continue}t.push(s)}return t.length===0?null:(this.renderingQueue.renderHighestPriority({first:t[0],last:t.at(-1),views:t,ids:i}),i)}containsElement(e){return this.container.contains(e)}focus(){this.container.focus()}get _isContainerRtl(){return getComputedStyle(this.container).direction==="rtl"}get isInPresentationMode(){return this.presentationModeState===ql.FULLSCREEN}get isChangingPresentationMode(){return this.presentationModeState===ql.CHANGING}get isHorizontalScrollbarEnabled(){return this.isInPresentationMode?!1:this.container.scrollWidth>this.container.clientWidth}get isVerticalScrollbarEnabled(){return this.isInPresentationMode?!1:this.container.scrollHeight>this.container.clientHeight}_getVisiblePages(){let e=this._scrollMode===ct.PAGE?this.#I.pages:this._pages,t=this._scrollMode===ct.HORIZONTAL,i=t&&this._isContainerRtl;return pZ({scrollEl:this.container,views:e,sortByVisibility:!0,horizontal:t,rtl:i})}cleanup(){for(let e of this._pages)e.renderingState!==Lt.FINISHED&&e.reset()}_cancelRendering(){for(let e of this._pages)e.cancelRendering()}async#K(e){if(e.pdfPage)return e.pdfPage;try{let t=await this.pdfDocument.getPage(e.id);return e.pdfPage||e.setPdfPage(t),t}catch(t){return console.error("Unable to get page for page view",t),null}}#Z(e){if(e.first?.id===1)return!0;if(e.last?.id===this.pagesCount)return!1;switch(this._scrollMode){case ct.PAGE:return this.#I.scrollDown;case ct.HORIZONTAL:return this.scroll.right}return this.scroll.down}forceRendering(e){let t=e||this._getVisiblePages(),i=this.#Z(t),r=this._spreadMode!==ki.NONE&&this._scrollMode!==ct.HORIZONTAL,s=this.#T!==null||this.#b!==null&&t.views.some(a=>a.detailView?.renderingCancelled),o=this.renderingQueue.getHighestPriority(t,this._pages,i,r,s);return o?(this.#K(o).then(()=>{this.renderingQueue.renderView(o)}),!0):!1}get hasEqualPageSizes(){let e=this._pages[0];for(let t=1,i=this._pages.length;t<i;++t){let r=this._pages[t];if(r.width!==e.width||r.height!==e.height)return!1}return!0}getPagesOverview(){let e;return this._pages.map(t=>{let i=t.pdfPage.getViewport({scale:1}),r=AL(i);if(e===void 0)e=r;else if(this.enablePrintAutoRotate&&r!==e)return{width:i.height,height:i.width,rotation:(i.rotation-90)%360};return{width:i.width,height:i.height,rotation:i.rotation}})}get optionalContentConfigPromise(){return this.pdfDocument?this._optionalContentConfigPromise?this._optionalContentConfigPromise:(console.error("optionalContentConfigPromise: Not initialized yet."),this.pdfDocument.getOptionalContentConfig({intent:"display"})):Promise.resolve(null)}set optionalContentConfigPromise(e){if(!(e instanceof Promise))throw new Error(`Invalid optionalContentConfigPromise: ${e}`);this.pdfDocument&&this._optionalContentConfigPromise&&(this._optionalContentConfigPromise=e,this.refresh(!1,{optionalContentConfigPromise:e}),this.eventBus.dispatch("optionalcontentconfigchanged",{source:this,promise:e}))}get scrollMode(){return this._scrollMode}set scrollMode(e){if(this._scrollMode!==e){if(!gZ(e))throw new Error(`Invalid scroll mode: ${e}`);this.pagesCount>Ag.FORCE_SCROLL_MODE_PAGE||(this._previousScrollMode=this._scrollMode,this._scrollMode=e,this.eventBus.dispatch("scrollmodechanged",{source:this,mode:e}),this._updateScrollMode(this._currentPageNumber))}}_updateScrollMode(e=null){let t=this._scrollMode,i=this.viewer;i.classList.toggle("scrollHorizontal",t===ct.HORIZONTAL),i.classList.toggle("scrollWrapped",t===ct.WRAPPED),!(!this.pdfDocument||!e)&&(t===ct.PAGE?this.#L():this._previousScrollMode===ct.PAGE&&this._updateSpreadMode(),this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#U(this._currentScaleValue,{noScroll:!0}),this._setCurrentPageNumber(e,!0),this.update())}get spreadMode(){return this._spreadMode}set spreadMode(e){if(this._spreadMode!==e){if(!mZ(e))throw new Error(`Invalid spread mode: ${e}`);this._spreadMode=e,this.eventBus.dispatch("spreadmodechanged",{source:this,mode:e}),this._updateSpreadMode(this._currentPageNumber)}}_updateSpreadMode(e=null){if(!this.pdfDocument)return;let t=this.viewer,i=this._pages;if(this._scrollMode===ct.PAGE)this.#L();else if(t.textContent="",this._spreadMode===ki.NONE)for(let r of this._pages)t.append(r.div);else{let r=this._spreadMode-1,s=null;for(let o=0,a=i.length;o<a;++o)s===null?(s=document.createElement("div"),s.className="spread",t.append(s)):o%2===r&&(s=s.cloneNode(!1),t.append(s)),s.append(i[o].div)}e&&(this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#U(this._currentScaleValue,{noScroll:!0}),this._setCurrentPageNumber(e,!0),this.update())}#J(e,t=!1){switch(this._scrollMode){case ct.WRAPPED:{let{views:i}=this._getVisiblePages(),r=new Map;for(let{id:s,y:o,percent:a,widthPercent:u}of i)a===0||u<100||r.getOrInsertComputed(o,nZ).push(s);for(let s of r.values()){let o=s.indexOf(e);if(o===-1)continue;let a=s.length;if(a===1)break;if(t)for(let u=o-1,l=0;u>=l;u--){let c=s[u],h=s[u+1]-1;if(c<h)return e-h}else for(let u=o+1,l=a;u<l;u++){let c=s[u],h=s[u-1]+1;if(c>h)return h-e}if(t){let u=s[0];if(u<e)return e-u+1}else{let u=s[a-1];if(u>e)return u-e+1}break}break}case ct.HORIZONTAL:break;case ct.PAGE:case ct.VERTICAL:{if(this._spreadMode===ki.NONE)break;let i=this._spreadMode-1;if(t&&e%2!==i)break;if(!t&&e%2===i)break;let{views:r}=this._getVisiblePages(),s=t?e-1:e+1;for(let{id:o,percent:a,widthPercent:u}of r)if(o===s){if(a>0&&u===100)return 2;break}break}}return 1}nextPage(){let e=this._currentPageNumber,t=this.pagesCount;if(e>=t)return!1;let i=this.#J(e,!1)||1;return this.currentPageNumber=Math.min(e+i,t),!0}previousPage(){let e=this._currentPageNumber;if(e<=1)return!1;let t=this.#J(e,!0)||1;return this.currentPageNumber=Math.max(e-t,1),!0}updateScale({drawingDelay:e,scaleFactor:t=null,steps:i=null,origin:r}){if(i===null&&t===null)throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided.");if(!this.pdfDocument)return;let s=this._currentScale;if(t>0&&t!==1)s=Math.round(s*t*100)/100;else if(i){let o=i>0?pL:1/pL,a=i>0?Math.ceil:Math.floor;i=Math.abs(i);do s=a((s*o).toFixed(2)*10)/10;while(--i>0)}s=qL(s,lZ,cZ),this.#U(s,{noScroll:!1,drawingDelay:e,origin:r})}increaseScale(e={}){this.updateScale({...e,steps:e.steps??1})}decreaseScale(e={}){this.updateScale({...e,steps:-(e.steps??1)})}#j(e=this.container.clientHeight){e!==this.#x&&(this.#x=e,bZ.setProperty("--viewer-container-height",`${e}px`))}#$(e){for(let t of e)if(t.target===this.container){this.#j(Math.floor(t.borderBoxSize[0].blockSize)),this.#a=null;break}}get containerTopLeft(){return this.#a||=[this.container.offsetTop,this.container.offsetLeft]}#Q(){this.#T!==null&&(clearTimeout(this.#T),this.#T=null),this.#b!==null&&(clearTimeout(this.#b),this.#b=null)}#X(){this.#C?.abort(),this.#C=null,this.#E!==null&&(clearTimeout(this.#E),this.#E=null)}#ee(e){switch(e){case Gn.STAMP:this.#y?.loadModel("altText");break;case Gn.SIGNATURE:this.#B?.loadSignatures();break}}get annotationEditorMode(){return this.#r?this.#i:Gn.DISABLE}set annotationEditorMode({mode:e,editId:t=null,isFromKeyboard:i=!1,mustEnterInEditMode:r=!1,editComment:s=!1}){if(!this.#r)throw new Error("The AnnotationEditor is not enabled.");if(this.#i===e)return;if(!WL(e))throw new Error(`Invalid AnnotationEditor mode: ${e}`);if(!this.pdfDocument)return;this.#ee(e);let{eventBus:o,pdfDocument:a}=this,u=async()=>{this.#X(),this.#i=e,await this.#r.updateMode(e,t,!0,i,r,s),!(e!==this.#i||a!==this.pdfDocument)&&o.dispatch("annotationeditormodechanged",{source:this,mode:e})};if(e===Gn.NONE||this.#i===Gn.NONE){let l=e!==Gn.NONE;l||this.pdfDocument.annotationStorage.resetModifiedIds(),this.cleanup();for(let h of this._pages)h.toggleEditingMode(l);let c=this.#F();if(l&&c){this.#X(),this.#C=new AbortController;let h=AbortSignal.any([this.#c.signal,this.#C.signal]);o._on("pagerendered",({pageNumber:f})=>{c.delete(f),c.size===0&&(this.#E=setTimeout(u,0))},{signal:h});return}}u()}refresh(e=!1,t=Object.create(null)){if(this.pdfDocument){for(let i of this._pages)i.update(t);this.#Q(),e||this.update()}}},m4=class extends Xl{_resetView(){super._resetView(),this._scrollMode=ct.PAGE,this._spreadMode=ki.NONE}set scrollMode(e){}_updateScrollMode(){}set spreadMode(e){}_updateSpreadMode(){}};globalThis.pdfjsViewer={AnnotationLayerBuilder:Sg,DownloadManager:K3,EventBus:Jl,FindState:ta,GenericL10n:Ql,LinkTarget:su,parseQueryString:kg,PDFFindController:wh,PDFHistory:Sh,PDFLinkService:Yl,PDFPageView:Rg,PDFScriptingManager:f4,PDFSinglePageViewer:m4,PDFViewer:Xl,ProgressBar:W3,RenderingStates:Lt,ScrollMode:ct,SimpleLinkService:Eh,SpreadMode:ki,StructTreeLayerBuilder:Pg,TextLayerBuilder:Mg,XfaLayerBuilder:Lg}});var rR,Og,sR=$n(()=>{_();rR="grab-to-pan-grab",Og=class{constructor(e){this.element=e.element,this.document=e.element.ownerDocument,typeof e.ignoreTarget=="function"&&(this.ignoreTarget=e.ignoreTarget),this.onActiveChanged=e.onActiveChanged,this.activate=this.activate.bind(this),this.deactivate=this.deactivate.bind(this),this.toggle=this.toggle.bind(this),this._onMouseDown=this.#e.bind(this),this._onMouseMove=this.#t.bind(this),this._endPan=this.#n.bind(this);let t=this.overlay=document.createElement("div");t.className="grab-to-pan-grabbing"}activate(){this.active||(this.active=!0,this.element.addEventListener("mousedown",this._onMouseDown,!0),this.element.classList.add(rR),this.onActiveChanged?.(!0))}deactivate(){this.active&&(this.active=!1,this.element.removeEventListener("mousedown",this._onMouseDown,!0),this._endPan(),this.element.classList.remove(rR),this.onActiveChanged?.(!1))}toggle(){this.active?this.deactivate():this.activate()}ignoreTarget(e){return e.matches("a[href], a[href] *, input, textarea, button, button *, select, option")}#e(e){if(e.button!==0||this.ignoreTarget(e.target))return;if(e.originalTarget)try{e.originalTarget.tagName}catch{return}this.scrollLeftStart=this.element.scrollLeft,this.scrollTopStart=this.element.scrollTop,this.clientXStart=e.clientX,this.clientYStart=e.clientY,this.document.addEventListener("mousemove",this._onMouseMove,!0),this.document.addEventListener("mouseup",this._endPan,!0),this.element.addEventListener("scroll",this._endPan,!0),e.preventDefault(),e.stopPropagation();let t=document.activeElement;t&&!t.contains(e.target)&&t.blur()}#t(e){if(this.element.removeEventListener("scroll",this._endPan,!0),!(e.buttons&1)){this._endPan();return}let t=e.clientX-this.clientXStart,i=e.clientY-this.clientYStart,r=this.scrollTopStart-i,s=this.scrollLeftStart-t;this.element.scrollTo?this.element.scrollTo({top:r,left:s,behavior:"instant"}):(this.element.scrollTop=r,this.element.scrollLeft=s),this.overlay.parentNode||document.body.append(this.overlay)}#n(){this.element.removeEventListener("scroll",this._endPan,!0),this.document.removeEventListener("mousemove",this._onMouseMove,!0),this.document.removeEventListener("mouseup",this._endPan,!0),this.overlay.remove()}}});var uR={};Ef(uR,{AnnotationEditorType:()=>Xe,PDFNavigator:()=>y4,ScaleType:()=>aR,ScrollMode:()=>ct,SpreadMode:()=>ki});var oR,aR,hi,y4,lR=$n(()=>{_();oR=Qe(eo());HA();dL();nR();yn();ui();sR();DA();aR=(t=>(t[t.Page=0]="Page",t[t.Width=1]="Width",t))(aR||{}),hi=class hi extends a1{constructor(t,i,r,s,o,a,u){super();this.isPDF=!0;this.pageNum=1;this.resourceIndex=0;this.pdfDoc=null;this._numPages=0;this._positionRestored=!1;this._pendingAnnotations=null;this.onResize=()=>{clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(()=>{if(this.pdfViewer){let t=this.pdfViewer.currentScaleValue;this.pdfViewer.currentScaleValue=t}},200)};this.settings=t,this.publication=i,this.api=r,this.workerSrc=s??`https://unpkg.com/pdfjs-dist@${R3}/build/pdf.worker.min.mjs`,this.annotator=o,this.initialLastReadingPosition=a,this.viewStore=u}static async create(t){let i=new this(t.settings,t.publication,t.api,t.workerSrc,t.annotator,t.initialLastReadingPosition,t.store);return await i.start(t.mainElement,t.headerMenu,t.footerMenu),i}async start(t,i,r){this.headerMenu=i,this.footerMenu=r,this.mainElement=t,this.resourceIndex=0,this.resource=this.publication.readingOrder[this.resourceIndex],po.workerSrc=this.workerSrc,this.wrapper=gt(this.mainElement,"#iframe-wrapper"),this.pdfContainer=gt(this.mainElement,"#pdf-container"),this.wrapper.style.position="absolute",this.wrapper.style.overflow="auto",this.wrapper.style.top="0",this.wrapper.style.left="0",this.wrapper.style.right="0",this.wrapper.style.bottom="0",this.pdfContainer.classList.add("pdfViewer"),this.handTool=new Og({element:this.wrapper}),this.eventBus=new Jl,this.linkService=new Yl({eventBus:this.eventBus}),this.findController=new wh({linkService:this.linkService,eventBus:this.eventBus}),this.pdfViewer=new Xl({container:this.wrapper,viewer:this.pdfContainer,eventBus:this.eventBus,linkService:this.linkService,findController:this.findController,textLayerMode:1,annotationMode:_s.ENABLE_STORAGE,annotationEditorMode:Xe.NONE,annotationEditorHighlightColors:"Yellow=#FFFF98,Green=#53FFBC,Blue=#80EBFF,Pink=#FFCBE6,Red=#FF4F5F"}),this.linkService.setViewer(this.pdfViewer),this.pdfViewer.spreadMode=ki.NONE,this.pdfHistory=new Sh({eventBus:this.eventBus,linkService:this.linkService}),this.linkService.setHistory(this.pdfHistory),this.eventBus.on("pagesinit",()=>{this.restoreViewSettings(),this.pdfViewer.currentPageNumber=this.pageNum}),this.eventBus.on("pagechanging",({pageNumber:o})=>{this.pageNum=o,this.saveLastReadingPosition(),this.atStart()?(this.api?.resourceAtStart?.(),this.emit("resource.start")):this.atEnd()&&(this.api?.resourceAtEnd?.(),this.emit("resource.end"))}),this.eventBus.on("pagesloaded",async({pagesCount:o})=>{this._numPages=o,this.hideLoading(),this.api?.resourceReady?.(),this.emit("resource.ready"),this._positionRestored||(this._positionRestored=!0,await this.restoreLastReadingPosition())}),this.eventBus.on("annotationeditorlayerrendered",async o=>{if(o.error||!this._pendingAnnotations)return;let a=o.pageNumber-1,u=this._pendingAnnotations.get(a);if(!u||u.length===0)return;this._pendingAnnotations.delete(a);let l=o.source?.annotationEditorLayer?.annotationEditorLayer;if(!l||!this.pdfDoc)return;let c=this.pdfDoc.annotationStorage,h=c.onSetModified;c.onSetModified=null;for(let f of u)try{let m=await l.deserialize(f);m&&l.addOrRebuild(m)}catch(m){console.warn("PDFNavigator: failed to restore annotation",f,m)}c.onSetModified=h,this.saveAnnotations(this.pdfDoc.fingerprints[0]??"")});let s=(0,oR.default)(()=>{this.pdfDoc&&this.saveAnnotations(this.pdfDoc.fingerprints[0]??"")},200);this.eventBus.on("annotationeditorstateschanged",s),this.showLoading(),await this.loadDocument(this.publication.getAbsoluteHref(this.resource.Href),1),te(window,"resize",this.onResize)}showLoading(){let t=document.getElementById("loadingpdf");if(t){t.style.display="flex";return}t=document.createElement("div"),t.id="loadingpdf",t.innerHTML=s1,Object.assign(t.style,{position:"absolute",inset:"0",display:"flex",zIndex:"100",alignItems:"center",justifyContent:"center",background:"white"}),t.className="loading is-loading",(this.wrapper.parentElement??document.body).appendChild(t)}hideLoading(){let t=document.getElementById("loadingpdf");t&&(t.style.display="none")}async loadDocument(t,i){this.showLoading(),this.pageNum=i,this.pdfDoc&&(this.pdfViewer.setDocument(null),this.linkService.setDocument(null),await this.pdfDoc.destroy(),this.pdfDoc=null);try{let s=await L3(t).promise;this.pdfDoc=s,this.pdfViewer.setDocument(s),this.linkService.setDocument(s),this.pdfHistory.initialize({fingerprint:s.fingerprints[0]??""}),this.restoreAnnotations(s.fingerprints[0]??""),s.annotationStorage.onSetModified=()=>{this.saveAnnotations(s.fingerprints[0]??"")}}catch(r){this.hideLoading();let s=r instanceof Error?r:new Error(String(r));console.error("PDFNavigator: failed to load document",t,s),this.api?.onError?.(s),this.emit("resource.error",s)}}readingOrder(){return this.publication.readingOrder}tableOfContents(){return this.publication.tableOfContents}landmarks(){return[]}pageList(){return[]}atStart(){return this.pageNum<=1&&this.resourceIndex===0}atEnd(){return this.resourceIndex>=this.publication.readingOrder.length-1&&this.pageNum>=(this.pdfDoc?.numPages??1)}currentResource(){return this.resourceIndex}totalResources(){return this.publication.readingOrder.length}currentLocator(){let t=this.pdfDoc?.numPages??this._numPages??1,i=t>1?(this.pageNum-1)/(t-1):0;return{href:this.resource?this.publication.getAbsoluteHref(this.resource.Href):"",title:`Page ${this.pageNum}`,locations:{position:this.pageNum,progression:i},type:"application/pdf"}}positions(){return this.publication.positions??[]}get numPages(){return this._numPages}nextPage(){if(this.pageNum>=(this.pdfDoc?.numPages??1)){this.nextResource();return}this.pdfViewer.nextPage()}previousPage(){if(this.pageNum<=1){this.previousResource();return}this.pdfViewer.previousPage()}nextResource(){this.resourceIndex>=this.publication.readingOrder.length-1||(this.resourceIndex++,this.resource=this.publication.readingOrder[this.resourceIndex],this.loadDocument(this.publication.getAbsoluteHref(this.resource.Href),1))}previousResource(){this.resourceIndex!==0&&(this.resourceIndex--,this.resource=this.publication.readingOrder[this.resourceIndex],this.loadDocument(this.publication.getAbsoluteHref(this.resource.Href),this.pdfDoc?.numPages??1))}goTo(t){if(typeof t.locations?.position=="number"){this.pdfViewer.currentPageNumber=t.locations.position;return}let i=t.href??"",r=this.pageFromHref(i)??1;if(i){let s=i.split("#")[0].split("?")[0],o=this.publication.readingOrder.findIndex(a=>{if(!a.Href)return!1;let u=this.publication.getAbsoluteHref(a.Href);return a.Href===s||u===s||u===this.toAbsoluteHref(s)});if(o>=0&&o!==this.resourceIndex){this.resourceIndex=o,this.resource=this.publication.readingOrder[this.resourceIndex],this.loadDocument(this.publication.getAbsoluteHref(this.resource.Href),r);return}}this.pdfViewer.currentPageNumber=r}pageFromHref(t){if(!t)return null;let i=t.match(/#page=(\d+)/i);if(i)return parseInt(i[1],10);try{let r=new URL(t,window.location.href);if(r.searchParams.has("start"))return parseInt(r.searchParams.get("start"),10);if(r.searchParams.has("page"))return parseInt(r.searchParams.get("page"),10)}catch{}return null}toAbsoluteHref(t){try{return new URL(t,window.location.href).href}catch{return t}}goToPosition(t){this.pdfViewer.currentPageNumber=t}async goToPage(t){this.pdfViewer.currentPageNumber=t}saveViewSetting(t,i){this.viewStore?.set(t,String(i))}restoreViewSettings(){let t=this.viewStore?.get(hi.KEY_SCROLL),i=this.viewStore?.get(hi.KEY_SPREAD),r=this.viewStore?.get(hi.KEY_SCALE),s=this.viewStore?.get(hi.KEY_ROTATE);this.pdfViewer.currentScaleValue=r??"page-fit",t!=null&&(this.pdfViewer.scrollMode=Number(t)),i!=null&&(this.pdfViewer.spreadMode=Number(i)),s!=null&&(this.pdfViewer.pagesRotation=Number(s))}annotationKey(t){return`pdf-ann-${t||this.resourceIndex}`}static toJsonSafe(t){if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))return Array.from(t);if(Array.isArray(t))return t.map(hi.toJsonSafe);if(t!==null&&typeof t=="object"){let i={};for(let[r,s]of Object.entries(t))i[r]=hi.toJsonSafe(s);return i}return t}saveAnnotations(t){if(!this.viewStore||!this.pdfDoc)return;let i=this.annotationKey(t),r={},{map:s}=this.pdfDoc.annotationStorage.serializable;if(s)for(let[o,a]of s)a.bitmap||(r[o]=hi.toJsonSafe(a));if(this._pendingAnnotations){let o=0;for(let[a,u]of this._pendingAnnotations)for(let l of u)r[`_pending_p${a}_${o++}`]=l}Object.keys(r).length===0?this.viewStore.remove(i):this.viewStore.set(i,JSON.stringify(r))}restoreAnnotations(t){if(this._pendingAnnotations=null,!this.viewStore)return;let i=this.annotationKey(t),r=this.viewStore.get(i);if(r)try{let s=JSON.parse(r),o=new Map;for(let a of Object.values(s)){let u=a,l=u.pageIndex??0;o.has(l)||o.set(l,[]),o.get(l).push(u)}this._pendingAnnotations=o}catch{}}fitToWidth(){this.pdfViewer.currentScaleValue="page-width",this.saveViewSetting(hi.KEY_SCALE,"page-width")}fitToPage(){this.pdfViewer.currentScaleValue="page-fit",this.saveViewSetting(hi.KEY_SCALE,"page-fit")}zoomIn(){this.pdfViewer.increaseScale(),this.saveViewSetting(hi.KEY_SCALE,this.pdfViewer.currentScaleValue)}zoomOut(){this.pdfViewer.decreaseScale(),this.saveViewSetting(hi.KEY_SCALE,this.pdfViewer.currentScaleValue)}rotateCw(){this.pdfViewer.pagesRotation=(this.pdfViewer.pagesRotation+90)%360,this.saveViewSetting(hi.KEY_ROTATE,this.pdfViewer.pagesRotation)}rotateCcw(){this.pdfViewer.pagesRotation=(this.pdfViewer.pagesRotation+270)%360,this.saveViewSetting(hi.KEY_ROTATE,this.pdfViewer.pagesRotation)}setSpreadMode(t){this.pdfViewer.spreadMode=t,this.saveViewSetting(hi.KEY_SPREAD,t)}setAnnotationEditorMode(t){this.pdfViewer.annotationEditorMode={mode:t}}get annotationStorage(){return this.pdfDoc?.annotationStorage}getAllAnnotations(){let t=[],{map:i}=this.pdfDoc?.annotationStorage.serializable??{};if(i)for(let r of i.values())t.push(hi.toJsonSafe(r));if(this._pendingAnnotations)for(let r of this._pendingAnnotations.values())for(let s of r)t.push(s);return t.sort((r,s)=>(r.pageIndex??0)-(s.pageIndex??0)),t}clearAnnotations(){if(!this.pdfDoc)return;let t=this.pdfDoc.annotationStorage,{map:i}=t.serializable;if(i)for(let r of i.keys())t.remove(r);this.viewStore&&this.pdfDoc.fingerprints[0]&&this.viewStore.remove(this.annotationKey(this.pdfDoc.fingerprints[0]))}makeBookmark(){return{id:crypto.randomUUID(),href:this.resource?this.publication.getAbsoluteHref(this.resource.Href):"",locations:{position:this.pageNum},type:"application/pdf",title:`Page ${this.pageNum}`,created:new Date}}saveBookmark(){return!this.annotator||this.isCurrentPageBookmarked()?null:this.annotator.saveBookmark(this.makeBookmark())}deleteBookmark(t){this.annotator?.deleteBookmark(t)}getBookmarks(){return!this.annotator||!this.resource?[]:this.annotator.getBookmarks(this.publication.getAbsoluteHref(this.resource.Href))}isCurrentPageBookmarked(){return this.getBookmarks().some(t=>t.locations?.position===this.pageNum)}activateHand(){this.handTool.activate()}deactivateHand(){this.handTool.deactivate()}async scroll(t,i){let r=t?i==="horizontal"?ct.HORIZONTAL:i==="wrapped"?ct.WRAPPED:ct.VERTICAL:ct.PAGE;this.pdfViewer.scrollMode=r,this.saveViewSetting(hi.KEY_SCROLL,r)}find(t,i){this.eventBus.dispatch("find",{query:t,caseSensitive:i?.caseSensitive??!1,highlightAll:i?.highlightAll??!0,findPrevious:i?.findPrevious??!1,type:""})}findNext(){this.eventBus.dispatch("find",{query:this.findController.state?.query??"",caseSensitive:!1,highlightAll:!0,findPrevious:!1,type:"again"})}findPrevious(){this.eventBus.dispatch("find",{query:this.findController.state?.query??"",caseSensitive:!1,highlightAll:!0,findPrevious:!0,type:"again"})}saveLastReadingPosition(){if(!this.annotator||!this.resource)return;let t={href:this.publication.getAbsoluteHref(this.resource.Href),locations:{position:this.pageNum},type:"application/pdf",created:new Date};this.api?.updateCurrentLocation?this.api.updateCurrentLocation(t).then(()=>{this.annotator.saveLastReadingPosition(t)}):this.annotator.saveLastReadingPosition(t)}async restoreLastReadingPosition(){if(this.initialLastReadingPosition&&this.annotator?.initLastReadingPosition(this.initialLastReadingPosition),!this.annotator)return;let t=this.annotator.getLastReadingPosition();if(!t)return;let i=t.locations?.position??1,r=this.publication.readingOrder.findIndex(s=>s.Href&&this.publication.getAbsoluteHref(s.Href)===t.href);r>=0&&r!==this.resourceIndex?(this.resourceIndex=r,this.resource=this.publication.readingOrder[this.resourceIndex],await this.loadDocument(this.publication.getAbsoluteHref(this.resource.Href),i)):this.pdfViewer.currentPageNumber=i}stop(){Se(window,"resize",this.onResize),this.pdfViewer?.setDocument(null),this.pdfDoc?.destroy(),this.pdfDoc=null}};hi.KEY_SCROLL="pdf-scroll-mode",hi.KEY_SPREAD="pdf-spread-mode",hi.KEY_SCALE="pdf-scale-value",hi.KEY_ROTATE="pdf-rotation";y4=hi});var jee={};Ef(jee,{AnnotationMarker:()=>vs,Link:()=>Rl,default:()=>Hee,load:()=>Uee});_();_();_();var GS=Qe(US()),WS=Qe(Ji());_();var jS=Qe(Ji());function Sa(n,e){return jS.TaJson.deserialize(n,e)}var zs=class extends GS.Publication{static async fromUrl(e,t){let r=await(await fetch(e.href,t)).json(),s=Sa(r,zs);return s.manifestUrl=e,s}get readingOrder(){return this.Spine??[]}get resources(){return this.Resources??[]}get tableOfContents(){return this.sample?.isSampleRead&&this.positions?.length>0?this.limitedTOC():this.TOC||[]}limitedTOC(){function e(i){for(let r=0;r<(i.Children?.length??0);r++){let s=i.Children[r];s.Href=void 0,s.Children&&e(s)}}return this.TOC?.map(i=>{if(i.Href){let r=this.positionsByHref(this.getRelativeHref(i.Href));if(r?.length>0){let s=r[0],o=Math.round((s.locations.totalProgression?s.locations.totalProgression:0)*100);this.sample?.limit&&(o<=this.sample?.limit||(i.Href=void 0,i.Children&&e(i)))}}return i})||[]}get landmarks(){return this.Landmarks}get pageList(){return this.PageList}get isFixedLayout(){return this.Metadata.Rendition?.Layout==="fixed"}get isReflowable(){return!this.isFixedLayout}get layout(){return this.isFixedLayout?"fixed":"reflowable"}get hasMediaOverlays(){return this.readingOrder?this.readingOrder.filter(e=>e.Properties?.MediaOverlay).length>0:!1}getStartLink(){if(this.readingOrder!==void 0&&this.readingOrder.length>0)return this.readingOrder[0]}getPreviousSpineItem(e){let t=this.getSpineIndex(e);if(t!==void 0&&this.readingOrder!==void 0&&t>0)return this.readingOrder[t-1]}getNextSpineItem(e){let t=this.getSpineIndex(e);if(t!==void 0&&this.readingOrder!==void 0&&t<this.readingOrder.length-1)return this.readingOrder[t+1]}getSpineItem(e){let t=this.getSpineIndex(e);if(t!==void 0&&this.readingOrder!==void 0)return this.readingOrder[t]}getSpineIndex(e){return this.readingOrder?.findIndex(t=>t.Href&&this.getAbsoluteHref(t.Href)===e)}getAbsoluteHref(e){return new URL(e,this.manifestUrl.href).href}getRelativeHref(e){let t=this.manifestUrl.href.replace("/manifest.json",""),i=e.replace(t,"");return i.indexOf("#")>0&&(i=i.slice(0,i.indexOf("#"))),i.charAt(0)==="/"&&(i=i.substring(1)),i}getTOCItemAbsolute(e){let t=this.getAbsoluteHref(e),i=(s,o)=>{for(let a=0;a<o.length;a++){let u=o[a];if(u.Href){let l=u.Href.indexOf("#")!==-1?u.Href.slice(0,u.Href.indexOf("#")):u.Href;if(this.getAbsoluteHref(l)===s)return u}if(u.Children){let l=i(s,u.Children);if(l!==void 0)return l}}},r=i(t,this.tableOfContents);return r===void 0&&this.readingOrder!==void 0&&(r=i(t,this.readingOrder)),r}getTOCItem(e){let t=(r,s)=>{for(let o=0;o<s.length;o++){let a=s[o];if(a.Href&&this.getAbsoluteHref(a.Href)===r)return a;if(a.Children){let u=t(r,a.Children);if(u!==void 0)return u}}},i=t(e,this.tableOfContents);if(i===void 0&&this.readingOrder!==void 0&&(i=t(e,this.readingOrder)),i===void 0&&e.indexOf("#")!==-1){let r=e.slice(0,e.indexOf("#"));i=t(r,this.tableOfContents),i===void 0&&this.readingOrder!==void 0&&(i=t(r,this.readingOrder))}return i}positionsByHref(e){let t=decodeURI(e)??"";return this.positions?.filter(i=>t.includes(i.href))}async autoGeneratePositions(e,t=VW){let i=0,r=0,s=[];if(this.readingOrder!==void 0)for(let a of this.readingOrder)if(this.isFixedLayout){let u={href:a.Href,locations:{progression:0,position:i+1},type:a.TypeLink};s.push(u),i=i+1}else{let u=this.getAbsoluteHref(a.Href),l=await t(u,e);a.contentLength=l,r+=l;let h=Math.max(1,Math.ceil(l/1024));for(let f=0;f<h;f++){let m={href:a.Href,locations:{progression:f/h,position:i+(f+1)},type:a.TypeLink};s.push(m)}i=i+h}var o=0;if(this.isReflowable&&this.readingOrder!==void 0)for(let a of this.readingOrder){if(!a.contentLength){console.error("Link is missing contentLength",a);return}a.contentWeight=100/r*a.contentLength,o=o+a.contentWeight}for(let a of s){let u=s.filter(c=>c.href===decodeURI(a.href)),l=Math.ceil((a.locations.progression?a.locations.progression:0)*(u.length-1));a.locations.position&&(a.locations.totalProgression=(a.locations.position-1)/s.length),a.locations.remainingPositions=Math.abs(l-(u.length-1)),a.locations.position&&(a.locations.totalRemainingPositions=Math.abs(a.locations.position-1-(s.length-1)))}this.positions=s}async fetchPositionsFromService(e,t){let r=await(await fetch(e,t)).json();this.positions=r.positions}async fetchWeightsFromService(e,t){if(this.isFixedLayout){console.warn("Not fetching weights from service for fixed layout publication.");return}let r=await(await fetch(e,t)).json();this.readingOrder!==void 0&&this.readingOrder.forEach(s=>{s.contentWeight=r[s.Href]})}};zs=Cf([(0,WS.JsonObject)()],zs);var VW=async(n,e)=>(await(await fetch(n,e)).blob()).size;_();_();var _a=class{json(){return JSON.stringify(this)}},ab=class extends _a{constructor(e,t,i){super(),this.value=e,this.ref=t,this.name=i}toString(){return this.value}},ub=class extends _a{constructor(e,t,i){super(),this.value=e,this.ref=t,this.name=i}toString(){return this.value}toJson(){return JSON.parse(this.value)}},lb=class extends _a{constructor(e,t,i,r){super(),this.value=e,this.values=t,this.ref=i,this.name=r}toString(){return this.values[this.value]}},cb=class extends _a{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)}},ju=class extends _a{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}},ds=class{constructor(){this.properties=[]}addIncremental(e,t,i,r,s,o,a){this.properties.push(new cb(e,t,i,r,s,o,a))}addStringable(e,t,i){this.properties.push(new ab(e,t,i))}addJSONable(e,t,i){this.properties.push(new ub(e,t,i))}addSwitchable(e,t,i,r,s){this.properties.push(new ju(e,t,i,r,s))}addEnumerable(e,t,i,r){this.properties.push(new lb(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}};_();var Fe=class Fe{};Fe.FONT_SIZE_REF="fontSize",Fe.FONT_FAMILY_REF="fontFamily",Fe.FONT_OVERRIDE_REF="fontOverride",Fe.APPEARANCE_REF="appearance",Fe.SCROLL_REF="scroll",Fe.ADVANCED_SETTINGS_REF="advancedSettings",Fe.TEXT_ALIGNMENT_REF="textAlign",Fe.COLUMN_COUNT_REF="colCount",Fe.DIRECTION_REF="direction",Fe.WORD_SPACING_REF="wordSpacing",Fe.LETTER_SPACING_REF="letterSpacing",Fe.PAGE_MARGINS_REF="pageMargins",Fe.LINE_HEIGHT_REF="lineHeight",Fe.BODY_HYPHENS_REF="bodyHyphens",Fe.PARA_SPACING_REF="paraSpacing",Fe.PARA_INDENT_REF="paraIndent",Fe.TYPE_SCALE_REF="typeScale",Fe.BACKGROUND_COLOR_REF="backgroundColor",Fe.TEXT_COLOR_REF="textColor",Fe.FONT_SIZE_KEY="--USER__"+Fe.FONT_SIZE_REF,Fe.FONT_FAMILY_KEY="--USER__"+Fe.FONT_FAMILY_REF,Fe.FONT_OVERRIDE_KEY="--USER__"+Fe.FONT_OVERRIDE_REF,Fe.APPEARANCE_KEY="--USER__"+Fe.APPEARANCE_REF,Fe.SCROLL_KEY="--USER__"+Fe.SCROLL_REF,Fe.ADVANCED_SETTINGS_KEY="--USER__"+Fe.ADVANCED_SETTINGS_REF,Fe.TEXT_ALIGNMENT_KEY="--USER__"+Fe.TEXT_ALIGNMENT_REF,Fe.COLUMN_COUNT_KEY="--USER__"+Fe.COLUMN_COUNT_REF,Fe.DIRECTION_KEY="--USER__"+Fe.DIRECTION_REF,Fe.WORD_SPACING_KEY="--USER__"+Fe.WORD_SPACING_REF,Fe.LETTER_SPACING_KEY="--USER__"+Fe.LETTER_SPACING_REF,Fe.PAGE_MARGINS_KEY="--USER__"+Fe.PAGE_MARGINS_REF,Fe.LINE_HEIGHT_KEY="--USER__"+Fe.LINE_HEIGHT_REF,Fe.BODY_HYPHENS_KEY="--USER__"+Fe.BODY_HYPHENS_REF,Fe.PARA_SPACING_KEY="--USER__"+Fe.PARA_SPACING_REF,Fe.PARA_INDENT_KEY="--USER__"+Fe.PARA_INDENT_REF,Fe.TYPE_SCALE_KEY="--USER__"+Fe.TYPE_SCALE_REF,Fe.BACKGROUND_COLOR_KEY="--USER__"+Fe.BACKGROUND_COLOR_REF,Fe.TEXT_COLOR_KEY="--USER__"+Fe.TEXT_COLOR_REF;var W=Fe;ui();yn();_();ui();_();ui();function K7(){return gt(document,"#iframe-wrapper").clientWidth}function zr(){return gt(document,"#iframe-wrapper").clientHeight}var q7=Qe(eo()),md=class{constructor(e){this.layout="reflowable";this.USERSETTINGS="userSetting";this.sideMargin=20;this.height=0;this.attributes={margin:0};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=Pi(t,"head");if(i){let o=ge(i,"meta[name=viewport]");o&&o.remove()}let r=Pi(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=zr()-40-this.attributes.margin,this.name="readium-scroll-off",this.label="Paginated",this.checkForFixedScrollWidth();let t=this.iframe.contentDocument;if(t){let i=Pi(t,"html");i&&i.style.setProperty("--USER__scroll","readium-scroll-off")}this.setSize(),this.padOddColumns()}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate()}start(){if(this.scrollMode){let e=this.iframe.contentDocument;if(e){let t=Pi(e,"head");if(t){let i=ge(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=Pi(this.iframe.contentDocument,"body"),i=Array.prototype.slice.call(t.querySelectorAll("img"));for(let r of i)r.style.maxWidth=""}}getCurrentPosition(){let e=gt(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=gt(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.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(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.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)}}atStart(){return this.scrollMode?gt(document,"#iframe-wrapper").scrollTop===0:this.getLeftColumnsWidth()<=0}atEnd(){if(this.scrollMode){let e=gt(document,"#iframe-wrapper");return Math.ceil(this.scrollingElement.scrollHeight-e.scrollTop)-1<=zr()}else{let e=Math.floor(this.getRightColumnsWidth());return e<=0?!0:this.iframe.contentDocument?.getElementById("r2d2bc-column-spacer")?e<=5:Math.ceil(this.getCurrentPage())===this.getPageCount()}}goToPreviousPage(){let e=gt(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.navigator.checkResourcePosition()}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate()}goToNextPage(){let e=gt(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.navigator.checkResourcePosition()}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate()}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=Pi(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=Pi(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 gt(document,"#iframe-wrapper").clientHeight}setIframeHeight(e){(0,q7.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=zr()-this.attributes.margin;i.height=Math.max(a,o)+"px"}}},200)(e)}checkForFixedScrollWidth(){let e=this.iframe.contentDocument;if(e){let t=Pi(e,"body"),i=t?.scrollWidth;this.hasFixedScrollWidth=t?.scrollWidth===i}}setSize(){if(this.iframe.width=K7()+"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();if(r%s>s*.25){let a=e.createElement("div");return a.id="r2d2bc-column-spacer",a.style.breakBefore="column",a.style.height="100%",a.style.visibility="hidden",i.appendChild(a),i.scrollWidth,!0}return!1}};_();ui();var bd=class{constructor(){this.layout="fixed";this.sideMargin=20;this.height=0;this.attributes={margin:0}}start(){}stop(){}getCurrentPosition(){return 0}getScreenHeight(){return gt(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 On=Qe(Qt()),at=class at{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.settingsChangeCallback=()=>{};this.settingsColumnsChangeCallback=()=>{};this.viewChangeCallback=()=>{};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",W.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(W.SCROLL_REF);r&&(r.value=t.verticalScroll,await t.saveProperty(r)),On.default.log(t.verticalScroll)}if(i.appearance){t.appearance=at.parseAppearanceSetting(i.appearance);let r=t.userProperties.getByRef(W.APPEARANCE_REF);r&&(r.value=t.appearance,await t.saveProperty(r)),On.default.log(t.appearance)}if(i.fontSize){t.fontSize=i.fontSize;let r=t.userProperties.getByRef(W.FONT_SIZE_REF);r&&(r.value=t.fontSize,await t.saveProperty(r)),On.default.log(t.fontSize)}if(i.fontFamily){t.fontFamily=at.fontFamilyValues.findIndex(s=>s===i.fontFamily);let r=t.userProperties.getByRef(W.FONT_FAMILY_REF);r&&(r.value=t.fontFamily,await t.saveProperty(r)),On.default.log(t.fontFamily),t.fontFamily!==0&&(t.fontOverride=!0)}if(i.textAlignment){t.textAlignment=at.textAlignmentValues.findIndex(s=>s===i.textAlignment);let r=t.userProperties.getByRef(W.TEXT_ALIGNMENT_REF);r&&(r.value=t.textAlignment,await t.saveProperty(r)),On.default.log(t.textAlignment)}if(i.columnCount){t.columnCount=at.columnCountValues.findIndex(s=>s===i.columnCount);let r=t.userProperties.getByRef(W.COLUMN_COUNT_REF);r&&(r.value=t.columnCount,await t.saveProperty(r)),On.default.log(t.columnCount)}if(i.direction){t.direction=at.directionValues.findIndex(s=>s===i.direction);let r=t.userProperties.getByRef(W.DIRECTION_REF);r&&(r.value=t.direction,await t.saveProperty(r)),On.default.log(t.direction)}if(i.wordSpacing){t.wordSpacing=i.wordSpacing;let r=t.userProperties.getByRef(W.WORD_SPACING_REF);r&&(r.value=t.wordSpacing,await t.saveProperty(r)),On.default.log(t.wordSpacing)}if(i.letterSpacing){t.letterSpacing=i.letterSpacing;let r=t.userProperties.getByRef(W.LETTER_SPACING_REF);r&&(r.value=t.letterSpacing,await t.saveProperty(r)),On.default.log(t.letterSpacing)}if(i.pageMargins){t.pageMargins=i.pageMargins;let r=t.userProperties.getByRef(W.PAGE_MARGINS_REF);r&&(r.value=t.pageMargins,await t.saveProperty(r)),On.default.log(t.pageMargins)}if(i.lineHeight){t.lineHeight=i.lineHeight;let r=t.userProperties.getByRef(W.LINE_HEIGHT_REF);r&&(r.value=t.lineHeight,await t.saveProperty(r)),On.default.log(t.lineHeight)}if(i.bodyHyphens!==void 0){t.bodyHyphens=i.bodyHyphens;let r=t.userProperties.getByRef(W.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(W.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(W.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(W.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(W.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(W.TEXT_COLOR_REF);r&&(r.value=t.textColor,await t.saveProperty(r))}t.userProperties=t.getUserSettings(),await t.initialise()}return await t.initializeSelections(),new Promise(i=>i(t))}stop(){On.default.log("book settings stop")}async initialise(){this.appearance=await this.getPropertyAndFallback("appearance",W.APPEARANCE_KEY),this.verticalScroll=await this.getPropertyAndFallback("verticalScroll",W.SCROLL_KEY),this.fontFamily=await this.getPropertyAndFallback("fontFamily",W.FONT_FAMILY_KEY),this.fontFamily!==0&&(this.fontOverride=!0),this.textAlignment=await this.getPropertyAndFallback("textAlignment",W.TEXT_ALIGNMENT_KEY),this.columnCount=await this.getPropertyAndFallback("columnCount",W.COLUMN_COUNT_KEY),this.direction=await this.getPropertyAndFallback("direction",W.DIRECTION_KEY),this.fontSize=await this.getPropertyAndFallback("fontSize",W.FONT_SIZE_KEY),this.wordSpacing=await this.getPropertyAndFallback("wordSpacing",W.WORD_SPACING_KEY),this.letterSpacing=await this.getPropertyAndFallback("letterSpacing",W.LETTER_SPACING_KEY),this.pageMargins=await this.getPropertyAndFallback("pageMargins",W.PAGE_MARGINS_KEY),this.lineHeight=await this.getPropertyAndFallback("lineHeight",W.LINE_HEIGHT_KEY),this.bodyHyphens=await this.getPropertyAndFallback("bodyHyphens",W.BODY_HYPHENS_KEY),this.paraSpacing=await this.getPropertyAndFallback("paraSpacing",W.PARA_SPACING_KEY),this.paraIndent=await this.getPropertyAndFallback("paraIndent",W.PARA_INDENT_KEY),this.typeScale=await this.getPropertyAndFallback("typeScale",W.TYPE_SCALE_KEY),this.backgroundColor=await this.getPropertyAndFallback("backgroundColor",W.BACKGROUND_COLOR_KEY),this.textColor=await this.getPropertyAndFallback("textColor",W.TEXT_COLOR_KEY),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=Pi(e,"html");if(t){let i=ge(document,"#root")||document.documentElement,r=ge(t,"body");t.style.removeProperty(W.FONT_SIZE_KEY),t.style.removeProperty(W.WORD_SPACING_KEY),t.style.removeProperty(W.LETTER_SPACING_KEY),t.style.removeProperty(W.COLUMN_COUNT_KEY),t.style.removeProperty(W.DIRECTION_KEY),t.style.removeProperty(W.TEXT_ALIGNMENT_KEY),t.style.removeProperty(W.LINE_HEIGHT_KEY),t.style.removeProperty(W.PAGE_MARGINS_KEY),t.style.removeProperty(W.BODY_HYPHENS_KEY),t.style.removeProperty(W.PARA_SPACING_KEY),t.style.removeProperty(W.PARA_INDENT_KEY),t.style.removeProperty(W.TYPE_SCALE_KEY),t.style.removeProperty(W.BACKGROUND_COLOR_KEY),t.style.removeProperty(W.TEXT_COLOR_KEY),t.style.removeProperty(W.APPEARANCE_KEY),i&&en(i,"data-viewer-theme","day"),r&&en(r,"data-viewer-theme","day"),t.style.removeProperty(W.FONT_FAMILY_KEY),en(t,"data-viewer-font","publisher"),t.style.setProperty(W.FONT_OVERRIDE_KEY,"readium-font-off")}}}async initializeSelections(){this.headerMenu&&(this.settingsView=ge(this.headerMenu,"#container-view-settings"))}async applyProperties(){this.userProperties=this.getUserSettings();let e=this.iframe.contentDocument;if(e){let t=Pi(e,"html");if(t){let i=ge(document,"#root")||document.documentElement,r=ge(t,"body");if(this.view?.navigator.publication.isReflowable&&(await this.getProperty(W.FONT_SIZE_KEY)&&t.style.setProperty(W.FONT_SIZE_KEY,this.userProperties.getByRef(W.FONT_SIZE_REF)?.toString()??null),await this.getProperty(W.WORD_SPACING_KEY)&&t.style.setProperty(W.WORD_SPACING_KEY,this.userProperties.getByRef(W.WORD_SPACING_REF)?.toString()??null),await this.getProperty(W.LETTER_SPACING_KEY)&&t.style.setProperty(W.LETTER_SPACING_KEY,this.userProperties.getByRef(W.LETTER_SPACING_REF)?.toString()??null)),await this.getProperty(W.COLUMN_COUNT_KEY)&&t.style.setProperty(W.COLUMN_COUNT_KEY,this.userProperties.getByRef(W.COLUMN_COUNT_REF)?.toString()??null),this.view?.navigator.publication.isReflowable&&(await this.getProperty(W.TEXT_ALIGNMENT_KEY)&&(this.userProperties.getByRef(W.TEXT_ALIGNMENT_REF)?.toString()==="auto"?t.style.removeProperty(W.TEXT_ALIGNMENT_KEY):t.style.setProperty(W.TEXT_ALIGNMENT_KEY,this.userProperties.getByRef(W.TEXT_ALIGNMENT_REF)?.toString()??null)),await this.getProperty(W.LINE_HEIGHT_KEY)&&t.style.setProperty(W.LINE_HEIGHT_KEY,this.userProperties.getByRef(W.LINE_HEIGHT_REF)?.toString()??null),await this.getProperty(W.PAGE_MARGINS_KEY)&&t.style.setProperty(W.PAGE_MARGINS_KEY,this.userProperties.getByRef(W.PAGE_MARGINS_REF)?.toString()??null),await this.getProperty(W.BODY_HYPHENS_KEY)&&t.style.setProperty(W.BODY_HYPHENS_KEY,this.userProperties.getByRef(W.BODY_HYPHENS_REF)?.toString()??null),await this.getProperty(W.PARA_SPACING_KEY)&&t.style.setProperty(W.PARA_SPACING_KEY,this.userProperties.getByRef(W.PARA_SPACING_REF)?.toString()??null),await this.getProperty(W.PARA_INDENT_KEY)&&t.style.setProperty(W.PARA_INDENT_KEY,this.userProperties.getByRef(W.PARA_INDENT_REF)?.toString()??null),await this.getProperty(W.TYPE_SCALE_KEY)&&t.style.setProperty(W.TYPE_SCALE_KEY,this.userProperties.getByRef(W.TYPE_SCALE_REF)?.toString()??null),await this.getProperty(W.BACKGROUND_COLOR_KEY)&&t.style.setProperty(W.BACKGROUND_COLOR_KEY,this.userProperties.getByRef(W.BACKGROUND_COLOR_REF)?.toString()??null),await this.getProperty(W.TEXT_COLOR_KEY)&&t.style.setProperty(W.TEXT_COLOR_KEY,this.userProperties.getByRef(W.TEXT_COLOR_REF)?.toString()??null)),await this.getProperty(W.APPEARANCE_KEY)?(t.style.setProperty(W.APPEARANCE_KEY,this.userProperties.getByRef(W.APPEARANCE_REF)?.toString()??null),this.userProperties.getByRef(W.APPEARANCE_REF)?.value===0?(i&&en(i,"data-viewer-theme","day"),r&&en(r,"data-viewer-theme","day")):this.userProperties.getByRef(W.APPEARANCE_REF)?.value===1?(i&&en(i,"data-viewer-theme","sepia"),r&&en(r,"data-viewer-theme","sepia")):this.userProperties.getByRef(W.APPEARANCE_REF)?.value===2&&(i&&en(i,"data-viewer-theme","night"),r&&en(r,"data-viewer-theme","night"))):(t.style.setProperty(W.APPEARANCE_KEY,this.userProperties.getByRef(W.APPEARANCE_REF)?.toString()??null),i&&en(i,"data-viewer-theme","day"),r&&en(r,"data-viewer-theme","day")),this.view?.navigator.publication.isFixedLayout&&await this.getProperty(W.DIRECTION_KEY)){let s=this.userProperties.getByRef(W.DIRECTION_REF)?.toString()??null;t.style.setProperty(W.DIRECTION_KEY,s),this.view.navigator.setDirection(s)}if(this.view?.navigator.publication.isReflowable){if(await this.getProperty(W.FONT_FAMILY_KEY))if(t.style.setProperty(W.FONT_FAMILY_KEY,this.userProperties.getByRef(W.FONT_FAMILY_REF)?.toString()??null),this.userProperties.getByRef(W.FONT_FAMILY_REF)?.value===0)en(t,"data-viewer-font","publisher"),t.style.setProperty(W.FONT_OVERRIDE_KEY,"readium-font-off");else if(this.userProperties.getByRef(W.FONT_FAMILY_REF)?.value===1)en(t,"data-viewer-font","serif"),t.style.setProperty(W.FONT_OVERRIDE_KEY,"readium-font-on");else if(this.userProperties.getByRef(W.FONT_FAMILY_REF)?.value===2)en(t,"data-viewer-font","sans"),t.style.setProperty(W.FONT_OVERRIDE_KEY,"readium-font-on");else{let s=this.userProperties.getByRef(W.FONT_FAMILY_REF);s&&en(t,"data-viewer-font",s.toString()),t.style.setProperty(W.FONT_OVERRIDE_KEY,"readium-font-on")}else t.style.setProperty(W.FONT_FAMILY_KEY,this.userProperties.getByRef(W.FONT_FAMILY_REF)?.toString()??null),en(t,"data-viewer-font","publisher"),t.style.setProperty(W.FONT_OVERRIDE_KEY,"readium-font-off");await this.getProperty(W.SCROLL_KEY)?this.userProperties.getByRef(W.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&&at.renderControls(this.settingsView)}static renderControls(e){te(ge(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){at.appearanceValues.includes(e)||at.appearanceValues.push(e)}initAddedAppearance(){this.applyProperties()}addFont(e){at.fontFamilyValues.includes(e)||at.fontFamilyValues.push(e)}initAddedFont(){this.applyProperties()}async updateUserSettings(){let e={fontFamily:at.fontFamilyValues[await this.userProperties?.getByRef(W.FONT_FAMILY_REF)?.value],fontSize:this.userProperties?.getByRef(W.FONT_SIZE_REF)?.value,appearance:at.appearanceValues[await this.userProperties?.getByRef(W.APPEARANCE_REF)?.value],textAlignment:at.textAlignmentValues[await this.userProperties?.getByRef(W.TEXT_ALIGNMENT_REF)?.value],columnCount:at.columnCountValues[await this.userProperties?.getByRef(W.COLUMN_COUNT_REF)?.value],direction:at.directionValues[await this.userProperties?.getByRef(W.DIRECTION_REF)?.value],wordSpacing:this.userProperties?.getByRef(W.WORD_SPACING_REF)?.value,letterSpacing:this.userProperties?.getByRef(W.LETTER_SPACING_REF)?.value,verticalScroll:this.userProperties?.getByRef(W.SCROLL_REF)?.value,bodyHyphens:this.userProperties?.getByRef(W.BODY_HYPHENS_REF)?.value,paraSpacing:this.userProperties?.getByRef(W.PARA_SPACING_REF)?.value,paraIndent:this.userProperties?.getByRef(W.PARA_INDENT_REF)?.value,typeScale:this.userProperties?.getByRef(W.TYPE_SCALE_REF)?.value,backgroundColor:this.userProperties?.getByRef(W.BACKGROUND_COLOR_REF)?.value,textColor:this.userProperties?.getByRef(W.TEXT_COLOR_REF)?.value};this.api?.updateSettings&&this.api?.updateSettings(e).then(t=>{On.default.log("api updated user settings",JSON.stringify(e))})}getUserSettings(){let e=new ds;return e.addSwitchable("readium-font-on","readium-font-off",this.fontOverride,W.FONT_OVERRIDE_REF,W.FONT_OVERRIDE_KEY),e.addEnumerable(this.columnCount,at.columnCountValues,W.COLUMN_COUNT_REF,W.COLUMN_COUNT_KEY),e.addEnumerable(this.direction,at.directionValues,W.DIRECTION_REF,W.DIRECTION_KEY),e.addEnumerable(this.appearance,at.appearanceValues,W.APPEARANCE_REF,W.APPEARANCE_KEY),e.addIncremental(this.pageMargins,.5,4,.25,"",W.PAGE_MARGINS_REF,W.PAGE_MARGINS_KEY),e.addEnumerable(this.textAlignment,at.textAlignmentValues,W.TEXT_ALIGNMENT_REF,W.TEXT_ALIGNMENT_KEY),e.addEnumerable(this.fontFamily,at.fontFamilyValues,W.FONT_FAMILY_REF,W.FONT_FAMILY_KEY),e.addIncremental(this.fontSize,100,300,25,"%",W.FONT_SIZE_REF,W.FONT_SIZE_KEY),e.addIncremental(this.lineHeight,1,2,.25,"em",W.LINE_HEIGHT_REF,W.LINE_HEIGHT_KEY),e.addIncremental(this.wordSpacing,0,1,.25,"rem",W.WORD_SPACING_REF,W.WORD_SPACING_KEY),e.addIncremental(this.letterSpacing,0,.5,.0625,"em",W.LETTER_SPACING_REF,W.LETTER_SPACING_KEY),e.addSwitchable("readium-scroll-on","readium-scroll-off",this.verticalScroll,W.SCROLL_REF,W.SCROLL_KEY),e.addSwitchable("auto","none",this.bodyHyphens,W.BODY_HYPHENS_REF,W.BODY_HYPHENS_KEY),e.addIncremental(this.paraSpacing,0,3,.5,"rem",W.PARA_SPACING_REF,W.PARA_SPACING_KEY),e.addIncremental(this.paraIndent,0,3,.5,"em",W.PARA_INDENT_REF,W.PARA_INDENT_KEY),e.addIncremental(this.typeScale,1,1.5,.1,"",W.TYPE_SCALE_REF,W.TYPE_SCALE_KEY),e.addStringable(this.backgroundColor,W.BACKGROUND_COLOR_REF,W.BACKGROUND_COLOR_KEY),e.addStringable(this.textColor,W.TEXT_COLOR_REF,W.TEXT_COLOR_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:at.appearanceValues[this.userProperties?.getByRef(W.APPEARANCE_REF)?.value],fontFamily:at.fontFamilyValues[this.userProperties?.getByRef(W.FONT_FAMILY_REF)?.value],textAlignment:at.textAlignmentValues[this.userProperties?.getByRef(W.TEXT_ALIGNMENT_REF)?.value],columnCount:at.columnCountValues[this.userProperties?.getByRef(W.COLUMN_COUNT_REF)?.value],direction:at.directionValues[this.userProperties?.getByRef(W.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=at.parseAppearanceSetting(e.appearance);let t=this.userProperties?.getByRef(W.APPEARANCE_REF);t&&(t.value=this.appearance,await this.storeProperty(t))}if(e.fontSize){this.fontSize=e.fontSize;let t=this.userProperties?.getByRef(W.FONT_SIZE_REF);t&&(t.value=this.fontSize,await this.storeProperty(t))}if(e.fontFamily){this.fontFamily=at.fontFamilyValues.findIndex(i=>i===e.fontFamily);let t=this.userProperties?.getByRef(W.FONT_FAMILY_REF);t&&(t.value=this.fontFamily,await this.storeProperty(t))}if(e.letterSpacing){this.letterSpacing=e.letterSpacing;let t=this.userProperties?.getByRef(W.LETTER_SPACING_REF);t&&(t.value=this.letterSpacing,await this.storeProperty(t))}if(e.wordSpacing){this.wordSpacing=e.wordSpacing;let t=this.userProperties?.getByRef(W.WORD_SPACING_REF);t&&(t.value=this.wordSpacing,await this.storeProperty(t))}if(e.columnCount){this.columnCount=at.columnCountValues.findIndex(i=>i===e.columnCount);let t=this.userProperties?.getByRef(W.COLUMN_COUNT_REF);t&&(t.value=this.columnCount,await this.storeProperty(t)),this.settingsColumnsChangeCallback()}if(e.direction){this.direction=at.directionValues.findIndex(i=>i===e.direction);let t=this.userProperties?.getByRef(W.DIRECTION_REF);t&&(t.value=this.direction,await this.storeProperty(t))}if(e.textAlignment){this.textAlignment=at.textAlignmentValues.findIndex(i=>i===e.textAlignment);let t=this.userProperties?.getByRef(W.TEXT_ALIGNMENT_REF);t&&(t.value=this.textAlignment,await this.storeProperty(t))}if(e.lineHeight){this.lineHeight=e.lineHeight;let t=this.userProperties?.getByRef(W.LINE_HEIGHT_REF);t&&(t.value=this.lineHeight,await this.storeProperty(t))}if(e.pageMargins){this.pageMargins=e.pageMargins;let t=this.userProperties?.getByRef(W.PAGE_MARGINS_REF);t&&(t.value=this.pageMargins,await this.storeProperty(t))}if(e.verticalScroll!==void 0){let t=this.view?.getCurrentPosition();this.verticalScroll=at.parseScrollSetting(e.verticalScroll);let i=this.userProperties?.getByRef(W.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(W.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(W.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(W.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(W.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(W.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(W.TEXT_COLOR_REF);t&&(t.value=this.textColor,await this.storeProperty(t))}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=at.appearanceValues[0]:e==="sepia"||e==="readium-sepia-on"?t=at.appearanceValues[1]:e==="night"||e==="readium-night-on"?t=at.appearanceValues[2]:t=e,at.appearanceValues.findIndex(i=>i===t)}async scroll(e){let t=this.view?.getCurrentPosition();this.verticalScroll=e;let i=this.userProperties?.getByRef(W.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(W.FONT_SIZE_REF)).increment(),this.fontSize=this.userProperties?.getByRef(W.FONT_SIZE_REF)?.value;let t=this.userProperties?.getByRef(W.FONT_SIZE_REF);t&&await this.storeProperty(t)}else if(e==="letterSpacing"){(this.userProperties?.getByRef(W.LETTER_SPACING_REF)).increment(),this.letterSpacing=this.userProperties?.getByRef(W.LETTER_SPACING_REF)?.value;let t=this.userProperties?.getByRef(W.LETTER_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="wordSpacing"){(this.userProperties?.getByRef(W.WORD_SPACING_REF)).increment(),this.wordSpacing=this.userProperties?.getByRef(W.WORD_SPACING_REF)?.value;let t=this.userProperties?.getByRef(W.WORD_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="lineHeight"){(this.userProperties?.getByRef(W.LINE_HEIGHT_REF)).increment(),this.lineHeight=this.userProperties?.getByRef(W.LINE_HEIGHT_REF)?.value;let t=this.userProperties?.getByRef(W.LINE_HEIGHT_REF);t&&await this.storeProperty(t)}else if(e==="paraSpacing"){(this.userProperties?.getByRef(W.PARA_SPACING_REF)).increment(),this.paraSpacing=this.userProperties?.getByRef(W.PARA_SPACING_REF)?.value;let t=this.userProperties?.getByRef(W.PARA_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="paraIndent"){(this.userProperties?.getByRef(W.PARA_INDENT_REF)).increment(),this.paraIndent=this.userProperties?.getByRef(W.PARA_INDENT_REF)?.value;let t=this.userProperties?.getByRef(W.PARA_INDENT_REF);t&&await this.storeProperty(t)}else if(e==="typeScale"){(this.userProperties?.getByRef(W.TYPE_SCALE_REF)).increment(),this.typeScale=this.userProperties?.getByRef(W.TYPE_SCALE_REF)?.value;let t=this.userProperties?.getByRef(W.TYPE_SCALE_REF);t&&await this.storeProperty(t)}await this.applyProperties(),this.settingsChangeCallback()}async decrease(e){if(e==="fontSize"){(this.userProperties?.getByRef(W.FONT_SIZE_REF)).decrement(),this.fontSize=this.userProperties?.getByRef(W.FONT_SIZE_REF)?.value;let t=this.userProperties?.getByRef(W.FONT_SIZE_REF);t&&await this.storeProperty(t)}else if(e==="letterSpacing"){(this.userProperties?.getByRef(W.LETTER_SPACING_REF)).decrement(),this.letterSpacing=this.userProperties?.getByRef(W.LETTER_SPACING_REF)?.value;let t=this.userProperties?.getByRef(W.LETTER_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="wordSpacing"){(this.userProperties?.getByRef(W.WORD_SPACING_REF)).decrement(),this.wordSpacing=this.userProperties?.getByRef(W.WORD_SPACING_REF)?.value;let t=this.userProperties?.getByRef(W.WORD_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="lineHeight"){(this.userProperties?.getByRef(W.LINE_HEIGHT_REF)).decrement(),this.lineHeight=this.userProperties?.getByRef(W.LINE_HEIGHT_REF)?.value;let t=this.userProperties?.getByRef(W.LINE_HEIGHT_REF);t&&await this.storeProperty(t)}else if(e==="paraSpacing"){(this.userProperties?.getByRef(W.PARA_SPACING_REF)).decrement(),this.paraSpacing=this.userProperties?.getByRef(W.PARA_SPACING_REF)?.value;let t=this.userProperties?.getByRef(W.PARA_SPACING_REF);t&&await this.storeProperty(t)}else if(e==="paraIndent"){(this.userProperties?.getByRef(W.PARA_INDENT_REF)).decrement(),this.paraIndent=this.userProperties?.getByRef(W.PARA_INDENT_REF)?.value;let t=this.userProperties?.getByRef(W.PARA_INDENT_REF);t&&await this.storeProperty(t)}else if(e==="typeScale"){(this.userProperties?.getByRef(W.TYPE_SCALE_REF)).decrement(),this.typeScale=this.userProperties?.getByRef(W.TYPE_SCALE_REF)?.value;let t=this.userProperties?.getByRef(W.TYPE_SCALE_REF);t&&await this.storeProperty(t)}await this.applyProperties(),this.settingsChangeCallback()}};at.appearanceValues=["readium-default-on","readium-sepia-on","readium-night-on"],at.fontFamilyValues=["Original","serif","sans-serif"],at.textAlignmentValues=["auto","justify","start"],at.columnCountValues=["auto","1","2"],at.directionValues=["auto","ltr","rtl"];var yd=at;_();ui();_();_();_();_();_();_();_();var Y7={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 or(t,e/2)}};_();_();var J7=typeof navigator<"u"&&navigator.userAgent?navigator.userAgent.toLowerCase():"",Ba=(()=>{let n=parseInt((/msie (\d+)/.exec(J7)||[])[1],10);return isNaN(n)?(n=parseInt((/trident\/.*; rv:(\d+)/.exec(J7)||[])[1],10),isNaN(n)?!1:n):n})();function $7(n,e){return Ba===!1?!1:e?n==="<"?Ba<e:n==="<="?Ba<=e:n===">"?Ba>e:n===">="?Ba>=e:Ba===e:!0}function Oq(){if(typeof window<"u"){let n=window.crypto||window.msCrypto;if(!n){if($7("<",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 Y6=="function")return function(){return __non_webpack_require__("crypto").randomBytes(4).readInt32LE()}}throw new Error("Unable to find crypto module")}var Q7=Oq();var or=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):Y7.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(Q7());return new n(t,e)}};_();_();var Iy={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 or(t,e)}};var X7={stringify(n){try{return decodeURIComponent(escape(Iy.stringify(n)))}catch{throw new Error("Malformed UTF-8 data")}},parse(n){return Iy.parse(unescape(encodeURIComponent(n)))}};var pp=class{constructor(e){this._minBufferSize=0,this._blockSize=0,this._props=e,this._data=e&&typeof e.data<"u"?e.data.clone():new or,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 or,this._nBytes=typeof t=="number"?t:0}_append(e){let t=typeof e=="string"?X7.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 or(t,l)}_doProcessBlock(e,t){throw new Error("Not implemented")}};var gp=class extends pp{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 Py=[],eT=[];function Bq(n){let e=Math.sqrt(n);for(let t=2;t<=e;t++)if(!(n%t))return!1;return!0}function Z7(n){return(n-(n|0))*4294967296|0}(function(){let e=2,t=0;for(;t<64;)Bq(e)&&(t<8&&(Py[t]=Z7(Math.pow(e,1/2))),eT[t]=Z7(Math.pow(e,1/3)),t++),e++})();var Na=[],ys=class n extends gp{constructor(e){super(e),this._hash=new or(Py.slice(0)),this._props=e,e&&typeof e.hash<"u"&&(this._hash=e.hash.clone())}_doReset(){this._hash=new or(Py.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],h=i[7];for(let f=0;f<64;f++){if(f<16)Na[f]=e[t+f]|0;else{let E=Na[f-15],S=(E<<25|E>>>7)^(E<<14|E>>>18)^E>>>3,C=Na[f-2],T=(C<<15|C>>>17)^(C<<13|C>>>19)^C>>>10;Na[f]=S+Na[f-7]+T+Na[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),A=h+b+m+eT[f]+Na[f],v=g+y;h=c,c=l,l=u,u=a+A|0,a=o,o=s,s=r,r=A+v|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]+h|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 Ed=Qe(eo());_();_();var un=Qe(Qt());function bp(n,e){let t=n.getClientRects();return My(t,e)}function My(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=iT(i,1,e),s=jq(r,1),o=nT(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)un.default.log("CLIENT RECT: remove small"),o.splice(u,1);else{un.default.log("CLIENT RECT: remove small, but keep otherwise empty!");break}}return rT(o),un.default.log(`CLIENT RECT: reduced ${i.length} --> ${o.length}`),o}function Tr(n,e,t){return Math.abs(n-e)<=t}function Nq(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 tT(n,e){let t=Nq(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 mp(n,e,t,i){return(n.left<e||Tr(n.left,e,i))&&(n.right>e||Tr(n.right,e,i))&&(n.top<t||Tr(n.top,t,i))&&(n.bottom>t||Tr(n.bottom,t,i))}function Dq(n,e,t){return mp(n,e.left,e.top,t)&&mp(n,e.right,e.top,t)&&mp(n,e.left,e.bottom,t)&&mp(n,e.right,e.bottom,t)}function Fq(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 Ly(n,e,t){return(n.left<e.right||t>=0&&Tr(n.left,e.right,t))&&(e.left<n.right||t>=0&&Tr(e.left,n.right,t))&&(n.top<e.bottom||t>=0&&Tr(n.top,e.bottom,t))&&(e.top<n.bottom||t>=0&&Tr(e.top,n.bottom,t))}function iT(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){un.default.log("mergeTouchingRects rect1 === rect2 ??!");continue}let a=Tr(s.top,o.top,e)&&Tr(s.bottom,o.bottom,e),u=Tr(s.left,o.left,e)&&Tr(s.right,o.right,e);if((u&&!t||a&&!u)&&Ly(s,o,e)){un.default.log(`CLIENT RECT: merging two into one, VERTICAL: ${a} HORIZONTAL: ${u} (${t})`);let f=n.filter(y=>y!==s&&y!==o),m=Fq(s,o);return f.push(m),iT(f,e,t)}}return n}function nT(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){un.default.log("replaceOverlappingRects rect1 === rect2 ??!");continue}if(Ly(i,r,-1)){let s=[],o,a,u=tT(i,r);if(u.length===1)s=u,o=i,a=r;else{let h=tT(r,i);u.length<h.length?(s=u,o=i,a=r):(s=h,o=r,a=i)}let l=[];l.push(a),Array.prototype.push.apply(l,s),rT(l),un.default.log(`CLIENT RECT: overlap, cut one rect into ${s.length}`);let c=n.filter(h=>h!==o);return Array.prototype.push.apply(c,s),nT(c)}}return n}function Hq(n,e){return Math.max(0,Math.min(n.right,e.right)-Math.max(n.left,e.left))}function Uq(n,e){return Math.max(0,Math.min(n.bottom,e.bottom)-Math.max(n.top,e.top))}function jq(n,e){let t=new Set(n);for(let i of n){if(!(i.width>1&&i.height>1)){un.default.log("CLIENT RECT: remove tiny"),t.delete(i);continue}for(let s of n)if(i!==s&&t.has(s)&&Dq(s,i,e)){un.default.log("CLIENT RECT: remove contained"),t.delete(i);break}}return Array.from(t)}function rT(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)&&Ly(t,i,-1)){r||e.push(t),s||e.push(i),un.default.log("CLIENT RECT: overlap ---"),un.default.log(`#1 TOP:${t.top} BOTTOM:${t.bottom} LEFT:${t.left} RIGHT:${t.right} WIDTH:${t.width} HEIGHT:${t.height}`),un.default.log(`#2 TOP:${i.top} BOTTOM:${i.bottom} LEFT:${i.left} RIGHT:${i.right} WIDTH:${i.width} HEIGHT:${i.height}`);let o=Hq(t,i);un.default.log(`xOverlap: ${o}`);let a=Uq(t,i);un.default.log(`yOverlap: ${a}`)}}e.length&&un.default.log(`CLIENT RECT: overlaps ${e.length}`)}_();var Gt=Qe(Qt());function As(n,e){let t=n?n.getSelection():null;if(!t)return;if(t.isCollapsed){Gt.default.log("^^^ SELECTION COLLAPSED.");return}let i=t.toString(),r=i.trim().replace(/\n/g," ").replace(/\s\s+/g," ");if(r.length===0){Gt.default.log("^^^ SELECTION TEXT EMPTY.");return}if(!t.anchorNode||!t.focusNode)return;let s=t.rangeCount===1?t.getRangeAt(0):aT(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset);if(!s||s.collapsed){Gt.default.log("$$$$$$$$$$$$$$$$$ CANNOT GET NON-COLLAPSED SELECTION RANGE?!");return}let o=Wq(s);o.startContainer!==s.startContainer&&(Gt.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startContainer"),Gt.default.log(o.startContainer),Gt.default.log(s.startContainer)),o.startOffset!==s.startOffset&&(Gt.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startOffset"),Gt.default.log(`${o.startOffset} !== ${s.startOffset}`)),o.endContainer!==s.endContainer&&(Gt.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endContainer"),Gt.default.log(o.endContainer),Gt.default.log(s.endContainer)),o.endOffset!==s.endOffset&&(Gt.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endOffset"),Gt.default.log(`${o.endOffset} !== ${s.endOffset}`));let a=to(o,e);if(!a){Gt.default.log("^^^ SELECTION RANGE INFO FAIL?!");return}return{rangeInfo:a,cleanText:r,rawText:i,range:o}}function aT(n,e,t,i){try{let r=new Range;if(r.setStart(n,e),r.setEnd(t,i),!r.collapsed)return Gt.default.log(">>> createOrderedRange RANGE OK"),r;Gt.default.log(">>> createOrderedRange COLLAPSED ... RANGE REVERSE?");let s=new Range;if(s.setStart(t,i),s.setEnd(n,e),!s.collapsed)return Gt.default.log(">>> createOrderedRange RANGE REVERSE OK."),r;Gt.default.log(">>> createOrderedRange RANGE REVERSE ALSO COLLAPSED?!");return}catch(r){console.warn(r.message);return}}function to(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=Gq(n.startContainer,n.endContainer);if(!c){Gt.default.log("^^^ NO RANGE COMMON ANCESTOR?!");return}if(n.commonAncestorContainer){let h=n.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?n.commonAncestorContainer:n.commonAncestorContainer.parentNode;h&&h.nodeType===Node.ELEMENT_NODE&&c!==h&&(Gt.default.log(">>>>>> COMMON ANCESTOR CONTAINER DIFF??!"),Gt.default.log(e(c)),Gt.default.log(e(h)))}if(l&&s)return{endContainerChildTextNodeIndex:u,endContainerElementCssSelector:l,endOffset:n.endOffset,startContainerChildTextNodeIndex:r,startContainerElementCssSelector:s,startOffset:n.startOffset}}function yp(n,e){let t=n.querySelector(e.startContainerElementCssSelector);if(!t){Gt.default.log("^^^ convertRangeInfo NO START ELEMENT CSS SELECTOR?!");return}let i=t;if(e.startContainerChildTextNodeIndex>=0){if(e.startContainerChildTextNodeIndex>=t.childNodes.length){Gt.default.log("^^^ convertRangeInfo rangeInfo.startContainerChildTextNodeIndex >= startElement.childNodes.length?!");return}if(i=t.childNodes[e.startContainerChildTextNodeIndex],i.nodeType!==Node.TEXT_NODE){Gt.default.log("^^^ convertRangeInfo startContainer.nodeType !== Node.TEXT_NODE?!");return}}let r=n.querySelector(e.endContainerElementCssSelector);if(!r){Gt.default.log("^^^ convertRangeInfo NO END ELEMENT CSS SELECTOR?!");return}let s=r;if(e.endContainerChildTextNodeIndex>=0){if(e.endContainerChildTextNodeIndex>=r.childNodes.length){Gt.default.log("^^^ convertRangeInfo rangeInfo.endContainerChildTextNodeIndex >= endElement.childNodes.length?!");return}if(s=r.childNodes[e.endContainerChildTextNodeIndex],s.nodeType!==Node.TEXT_NODE){Gt.default.log("^^^ convertRangeInfo endContainer.nodeType !== Node.TEXT_NODE?!");return}}return aT(i,e.startOffset,s,e.endOffset)}function Gq(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 Wq(n){let e=n.cloneRange(),t=e.startContainer,i=e.startOffset,r=e.endContainer,s=e.endOffset;t.childNodes.length&&i>0&&(t=oT(t.childNodes[i-1]),i=t.length||0),s<r.childNodes.length&&(r=sT(r.childNodes[s]),s=0);let o=sT(t),a=oT(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=Vq(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=Kq(a);return a===r?e.setEnd(r,s):a!==null&&(a.nodeType===3?e.setEnd(a,a.length):e.setEndAfter(a)),e}function Vq(n){if(n.firstChild)return n.firstChild;let e=n;for(;!e.nextSibling;)if(e=e.parentNode,!e)return null;return e.nextSibling}function Kq(n){if(n.lastChild)return n.lastChild;let e=n;for(;!e.previousSibling;)if(e=e.parentNode,!e)return null;return e.previousSibling}function sT(n){for(;n.firstChild;)n=n.firstChild;return n}function oT(n){for(;n.lastChild;)n=n.lastChild;return n}_();var Dy=Qe(lT());var io,Fy;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};io={...i,...t},Fy=Xq(io.root,i);let r=ky(n,0,()=>ky(n,1,()=>ky(n,2)));if(r){let s=pT(gT(r,n));return s.length>0&&(r=s[0]),Ap(r)}else throw new Error("Selector was not found.")}function Xq(n,e){return n.nodeType===Node.DOCUMENT_NODE?n:n===e.root?n.ownerDocument:n}function ky(n,e,t){let i=null,r=[],s=n,o=0;for(;s&&s!==io.root.parentElement;){let a=Ny(Zq(s))||Ny(...eY(s))||Ny(tY(s))||[iY()],u=nY(s);if(e===0)u&&(a=a.concat(a.filter(By).map(l=>Oy(l,u))));else if(e===1)a=a.slice(0,1),u&&(a=a.concat(a.filter(By).map(l=>Oy(l,u))));else if(e===2){let[l]=a=a.slice(0,1);u&&By(l)&&(a=[Oy(l,u)])}for(let l of a)l.level=o;if(r.push(a),r.length>=io.seedMinLength&&(i=cT(r,t),i))break;s=s.parentElement,o++}return i||(i=cT(r,t)),i}function cT(n,e){let t=pT(fT(n));if(t.length>io.threshold)return e?e():null;for(let i of t)if(hT(i))return i;return null}function Ap(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 dT(n){return n.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function hT(n){switch(Fy.querySelectorAll(Ap(n)).length){case 0:throw new Error(`Can't select any node with this selector: ${Ap(n)}`);case 1:return!0;default:return!1}}function Zq(n){let e=n.getAttribute("id");return e&&io.idName(e)?{name:"#"+(0,Dy.default)(e,{isIdentifier:!0}),penalty:0}:null}function eY(n){return Array.from(n.classList).filter(io.className).map(t=>({name:"."+(0,Dy.default)(t,{isIdentifier:!0}),penalty:1}))}function tY(n){let e=n.tagName.toLowerCase();return io.tagName(e)?{name:e,penalty:2}:null}function iY(){return{name:"*",penalty:3}}function nY(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 Oy(n,e){return{name:n.name+`:nth-child(${e})`,penalty:n.penalty+1}}function By(n){return n.name!=="html"&&!n.name.startsWith("#")}function Ny(...n){let e=n.filter(rY);return e.length>0?e:null}function rY(n){return n!=null}function*fT(n,e=[]){if(n.length>0)for(let t of n[0])yield*fT(n.slice(1,n.length),e.concat(t));else yield e}function pT(n){return Array.from(n).sort((e,t)=>dT(e)-dT(t))}function*gT(n,e){if(n.length>2&&n.length>io.optimizedMinLength)for(let t=1;t<n.length-1;t++){let i=[...n];i.splice(t,1),hT(i)&&sY(i,e)&&(yield i,yield*gT(i,e))}}function sY(n,e){return Fy.querySelector(Ap(n))===e}_();var vs=(s=>(s[s.Highlight=0]="Highlight",s[s.Underline=1]="Underline",s[s.Bookmark=2]="Bookmark",s[s.Custom=3]="Custom",s[s.Comment=4]="Comment",s))(vs||{});Ad();ui();var jy=Qe(vp());_y();var An=Qe(Qt()),Da=(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))(Da||{}),yT="R2_CLASS_HIGHLIGHT_CONTAINER",Cd="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",ln="R2_CLASS_HIGHLIGHT_AREA",wd="R2_CLASS_HIGHLIGHT_ICON",ws=.5,bT=.75,Fa={blue:100,green:50,red:230},li=[],uY="data-highlighted",lY="data-timestamp",ol={ELEMENT_NODE:1,TEXT_NODE:3};var ar=["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",yT,ln,Cd],Hy=-1,Uy=-1,Xt=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,Ed.default)(e=>{this.isAndroid()||this.snapSelectionToWord(e),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,Ed.default)(()=>{this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen(),this.navigator.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,Ed.default)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.navigator.emit("toolbox.closed","closed"))},100);this.selection=(0,Ed.default)((e,t)=>{this.api?.selection&&this.api?.selection(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(),Hy=-1,Uy=-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===ol.TEXT_NODE?e.endOffset<i.nodeValue.length&&i.splitText(e.endOffset):e.endOffset>0&&(i=i.childNodes.item(e.endOffset-1));return t.nodeType===ol.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(lY);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===ol.TEXT_NODE)for(;e.nextSibling&&e.nextSibling.nodeType===ol.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(Hy=e.clientX,Uy=e.clientY,this.properties?.preventScrollOnSelection){let t=gt(document,"#iframe-wrapper");t.style.overflow="hidden"}}async mouseup(e){Math.abs(Hy-e.clientX)<3&&Math.abs(Uy-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=qr.close,s.addEventListener("click",function(){u.toolboxMode("add")})),o&&(o.innerHTML=qr.close,o.addEventListener("click",function(){u.toolboxMode("add")})),i){i.style.position="relative",i.style.zIndex="20",this.colors.forEach(h=>{let f=document.getElementById(h),m=document.getElementById(`c${h}`);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 h=10;this.colors.forEach(f=>{h--;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=`${h}`,m.style.marginLeft="-30px",c.push(m),t?.insertBefore(m,a)})}this.colors.forEach(h=>{let f=i?.cloneNode(!0),m=f.lastChild;m.style.backgroundColor=h,f.id=h,f.style.position="relative",f.style.display="unset",l.push(f),i&&f.addEventListener("click",function(){u.setColor(h);let y=i?.lastChild;y&&(y.style.backgroundColor=h);let g=document.getElementById("highlightIcon"),b=document.getElementById("underlineIcon"),A=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()),(A?.getElementsByTagName?.("span").length??0)>0&&((A?.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=gt(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 A=b.match(new RegExp("[^a-zA-Z0-9]+$"));return!A||!A.index?b:b.slice(0,A.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 h=document.createRange();e?(h.setStart(s.anchorNode,s.anchorOffset+a),h.setEnd(s.focusNode,s.focusOffset-u)):(h.setStart(s.anchorNode,s.anchorOffset),h.setEnd(s.focusNode,s.focusOffset));let f=h.collapsed;h.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=>ar.indexOf(f)<0,idName:f=>ar.indexOf(f)<0},h=e.navigator.iframes[0].contentDocument;if(h)return Vi(l,h,c)}let a=e.navigator.iframes[0].contentWindow,u=As(a,o);u&&e.navigator.annotationModule?.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");i&&(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")):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")):(this.navigator.view?.isPaginated()?i.style.top=t.top+(this.navigator.attributes?.navHeight??0)+"px":i.style.top=t.top+"px",i.style.left=(t.right-t.left)/2+t.left+"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)},h=r.cloneNode(!0);r?.parentNode?.replaceChild(h,r),r=document.getElementById("highlightIcon"),r?.addEventListener("click",c)}if(o){let c=function(){i.doHighlight(!1,1),i.toolboxHide(),o?.removeEventListener("click",c)},h=o.cloneNode(!0);o?.parentNode?.replaceChild(h,o),o=document.getElementById("underlineIcon"),o?.addEventListener("click",c)}if(a){let c=function(){i.doHighlight(!1,4),i.toolboxHide(),a?.removeEventListener("click",c)},h=a.cloneNode(!0);a?.parentNode?.replaceChild(h,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()},h=l.cloneNode(!0);l?.parentNode?.replaceChild(h,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 h=document.getElementById(c.id),f=this;function m(){h?.removeEventListener("click",m);function y(b){let A={className:E=>ar.indexOf(E)<0,idName:E=>ar.indexOf(E)<0},v=f.navigator.iframes[0].contentDocument;if(v)return Vi(b,v,A)}let g=f.navigator.iframes[0].contentWindow;if(g){let b=As(g,y);if(b===void 0){let A=f.navigator.iframes[0].contentDocument;b=f.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(A)??void 0}if(b!==void 0)if(c.callback)c.callback(b.cleanText,b.range?.startContainer.parentElement);else{let A=c.highlight?.style,v=c.marker?c.marker:3;if(v===3&&f.navigator.rights.enableAnnotations||v===2&&f.navigator.rights.enableBookmarks){let E=f.navigator.iframes[0].contentDocument;if(E){let S=f.createHighlight(f.dom(E.body).getWindow(),b,c.highlight?.color,!0,v,c.icon,c.popup,A);f.options.onAfterHighlight(S,v),f.navigator.rights.enableAnnotations?f.navigator.annotationModule?.saveAnnotation(S[0]).then(C=>{c?.note&&C.highlight&&f.navigator.annotationModule?.api?.addCommentToAnnotation(C).then(T=>{f.navigator.annotationModule?.updateAnnotation(T).then(async()=>{An.default.log("update highlight "+T.id)})})}):f.navigator.rights.enableBookmarks&&f.navigator.bookmarkModule?.saveAnnotation(S[0])}}}}f.callbackComplete()}if(h){let y=h.cloneNode(!0);h?.parentNode?.replaceChild(y,h),h=document.getElementById(c.id),h?.addEventListener("click",m)}})}}doHighlight(e,t){let i=this;function r(o){let a={className:l=>ar.indexOf(l)<0,idName:l=>ar.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=As(s,r);if(o===void 0){let a=i.navigator.iframes[0].contentDocument;o=this.navigator.annotationModule?.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.annotationModule?.saveAnnotation(l[0]):this.navigator.rights.enableBookmarks&&t===2&&this.navigator.bookmarkModule?.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=>ar.indexOf(l)<0,idName:l=>ar.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=As(i,t);if(o===void 0){let a=e.navigator.iframes[0].contentDocument;o=e.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(a)??void 0}o!==void 0&&this.navigator.ttsModule.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=gt(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,h=s<i,f=e.left>r;return l||c||h||f}isInsideViewport(e){let t=gt(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,h=l<u;return s&&o&&c&&h}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:h,left:f,width:m}=s(l);return{top:c,height:h,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){An.default.log("measureTextNode "+u),An.default.log("measureTextNode "+a),An.default.log(`${a.textContent}`)}},t=qs(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.ttsModule.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===ol.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===ol.ELEMENT_NODE&&e.hasAttribute(uY)}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=li.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}, ${ws})`,"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}, ${ws})`,"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(wd);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}, ${bT})`,"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}, ${bT})`,"important")}else r.classList.add("hover");if(i.type!==4){let o=e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER").querySelector(`#${i.id}`).getElementsByClassName(wd);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(`.${ln}`));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 h=u.color;o.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${ws})`,"important")}else if(n.isHexColor(u.color)){let h=n.hexToRgbChannels(u.color);o.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${ws})`,"important")}else o.classList.remove("hover");let c=i.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${u.id}`).getElementsByClassName(wd);if(c.length>0){let h=c.item(0).getElementsByClassName("icon-tooltip");h.length>0&&h.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}, ${ws})`,"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}, ${ws})`,"important")}else o.classList.remove("hover");let l=i.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${e.id}`).getElementsByClassName(wd);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=li.find(s=>s.id===e.target.parentElement?.id);if(!r||!i){for(let s in Da){let o=t.getElementById(s);if(o){let a=o.querySelectorAll(`.${Cd}`);for(let l of a)this.resetHighlightBoundingStyle(l);let u=Array.from(o.querySelectorAll(`.${ln}`));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};An.default.log(JSON.stringify(s));let o=this,a;if(o.navigator.rights.enableAnnotations?a=await this.navigator.annotationModule?.getAnnotation(s.highlight):o.navigator.rights.enableBookmarks&&(a=await this.navigator.bookmarkModule?.getAnnotation(s.highlight)),s.highlight.type===0&&this.navigator.annotationModule?.api?.selectedAnnotation(a).then(async()=>{}),a?.id){An.default.log("selected highlight "+a.id),o.lastSelectedHighlight=a.id;let u=document.getElementById("highlight-toolbox");if(u)if(u.style.top=e.clientY+(this.navigator.attributes?.navHeight??0)+"px",u.style.left=e.clientX+"px",getComputedStyle(u).display==="none"){let h=function(){o.navigator.annotationModule?.api?.addCommentToAnnotation(a).then(A=>{o.navigator.annotationModule?.updateAnnotation(A).then(async()=>{An.default.log("update highlight "+A.id),u&&(u.style.display="none"),o.selectionMenuClosed()}),u&&(u.style.display="none"),o.selectionMenuClosed(),f?.removeEventListener("click",h,!1)})},y=function(){o.navigator.rights.enableAnnotations?o.navigator.annotationModule?.deleteSelectedHighlight(a).then(async()=>{An.default.log("delete highlight "+a.id),u&&(u.style.display="none"),o.selectionMenuClosed()}):o.navigator.rights.enableBookmarks&&o.navigator.bookmarkModule?.deleteSelectedHighlight(a).then(async()=>{An.default.log("delete highlight "+a.id),u&&(u.style.display="none"),o.selectionMenuClosed()})};u.style.display="block",this.toolboxMode("edit");let l=document.getElementById("colorIcon"),c=document.getElementById("highlightIcon");l&&(l.style.display="none"),c&&(c.style.display="none");let f=document.getElementById("commentIcon"),m=document.getElementById("cloneCommentIcon");if(m){let A=m.parentElement;A&&A.removeChild(m)}if(f){f.style.display="none";let A=f.cloneNode(!0),v=f.parentElement;A.style.display="unset",A.id="cloneCommentIcon",A.addEventListener("click",h,!1),v&&v.append(A)}let g=document.getElementById("deleteIcon"),b=document.getElementById("cloneDeleteIcon");if(b){let A=b.parentElement;A&&A.removeChild(b)}if(g){g.style.display="none";let A=g.cloneNode(!0),v=g.parentElement;A.style.display="unset",A.id="cloneDeleteIcon",A.addEventListener("click",y,!1),v&&v.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 il(this.navigator).showPopup(u.dataset.definition,e);let l=this.navigator.definitionsModule?.properties?.definitions?.filter(c=>c.order===Number(u?.dataset.order))[0];An.default.log(l),this.navigator.definitionsModule?.api?.click&&(this.navigator.definitionsModule.api?.click(jy.omit(l,"callbacks"),jy.omit(r,"definition")),this.navigator.emit("definition.click",l,r))}}}async prepareContainers(e){for(let t in Da)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),li.splice(0,li.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),li.splice(0,li.length);break}}}destroyHighlight(e,t){if(!e)return;let i=-1;li.find((o,a)=>(i=a,o.id===t))&&i>=0&&i<li.length&&li.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 h=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,f=ys.hash(h),m=(c||"R2_HIGHLIGHT_")+f;this.destroyHighlight(e.document,m);let y=`rgb(${Fa.red}, ${Fa.green}, ${Fa.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)&&li.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(h){throw"Can't create highlight: "+h}}createHighlightDom(e,t){let i=e.document,r=yp(i,t.selectionInfo.rangeInfo);if(!r)return;for(let N in Da)this.ensureHighlightsContainer(e,N);let s=i.createElement("div");s.setAttribute("id",t.id),s.setAttribute("class",yT),s.style.setProperty("pointer-events","none"),t.pointerInteraction&&(s.setAttribute("data-click","1"),s.addEventListener("mouseover",N=>{if(N.target.classList.contains("R2_CLASS_HIGHLIGHT_AREA")){let H=N.currentTarget,j=li.find(U=>U.id===N.currentTarget.id);if(N.type==="mouseover"&&H.parentElement?.style.display!=="none"&&j){let U=Array.from(H.querySelectorAll(`.${ln}`));this.setHighlightAreaStyle(i,U,j)}}}),s.addEventListener("mouseleave",N=>{let H=N.currentTarget,j=Array.from(H.querySelectorAll(`.${ln}`));for(let V of j)this.resetHighlightAreaStyle(V,H.id);let U=H.querySelector(`.${Cd}`),z=H.querySelectorAll(`.${Cd}`);for(let V of z)(!U||V!==U)&&this.resetHighlightBoundingStyle(V)}));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,h=1,f=!1,m=!1,g=f||m||!1;An.default.debug(g),g=!0;let b=bp(r,g),A=3,v=2,E=3,S=0,C=24,T,M;for(let N of b){let H=i.createElement("div");H.setAttribute("class",ln),H.dataset.marker=""+t.marker;let j="";if(f&&t.marker!==3&&t.marker!==2&&t.marker!==4){let J=t.color;n.isHexColor(J)&&(J=n.hexToRgbChannels(J)),j+=`border-bottom: ${v*h}px solid rgba(${J.red}, ${J.green}, ${J.blue}, ${ws}) !important`}if(t.marker===3||t.marker===2)if(t.style?.default){for(let J=0;J<t.style?.default?.length;J++){let Q=t.style?.default[J];j+=`${Q.property}: ${Q.value} !${Q.priority};`}H.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${A}px !important; ${j}`)}else t.style?.defaultClass&&(H.classList.add(t.style?.defaultClass),H.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${A}px !important; ${j}`));else if(t.marker===1||t.marker===4)if(typeof t.color=="object"){let J=t.color;H.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${A}px !important; background-color: rgba(${J.red}, ${J.green}, ${J.blue}, 0) !important; ${j}`),H.style.setProperty("border-bottom",`2px solid rgba(${J.red}, ${J.green}, ${J.blue}, 1)`,"important")}else if(n.isHexColor(t.color)){let J=n.hexToRgbChannels(t.color);H.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${A}px !important; background-color: rgba(${J.red}, ${J.green}, ${J.blue}, 0) !important; ${j}`),H.style.setProperty("border-bottom",`2px solid rgba(${J.red}, ${J.green}, ${J.blue}, 1)`,"important")}else H.setAttribute("style",`border-radius: ${A}px !important; ${j}`);else if(typeof t.color=="object"){let J=t.color;H.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${A}px !important; background-color: rgba(${J.red}, ${J.green}, ${J.blue}, ${ws}) !important; ${j}`)}else if(n.isHexColor(t.color)){let J=n.hexToRgbChannels(t.color);H.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${A}px !important; background-color: rgba(${J.red}, ${J.green}, ${J.blue}, ${ws}) !important; ${j}`)}else H.setAttribute("style",`border-radius: ${A}px !important; ${j}`);t.type===1||t.type===2||t.type===5||t.type===3?H.style.setProperty("pointer-events","none"):(H.style.setProperty("pointer-events","all"),H.style.setProperty("cursor","hand")),H.style.position="absolute",H.scale=h,H.rect={height:N.height,left:N.left-l,top:N.top-c,width:N.width},t.pointerInteraction&&(H.setAttribute("data-click","1"),H.tabIndex=0),H.style.width=`${H.rect.width*h}px`,H.style.height=`${H.rect.height*h}px`,H.style.left=`${H.rect.left*h}px`,H.style.top=`${H.rect.top*h}px`,s.append(H);let U=parseInt(H.style.top.replace("px",""));if((U<S||S===0)&&(S=U),C=parseInt(H.style.height.replace("px","")),m){let J=i.createElement("div");J.setAttribute("class",ln);let Q=t.color;n.isHexColor(Q)&&(Q=n.hexToRgbChannels(Q)),J.setAttribute("style",`background-color: rgba(${Q.red}, ${Q.green}, ${Q.blue}, ${ws}) !important;`),t.type===1||t.type===2||t.type===5||t.type===3?J.style.setProperty("pointer-events","none"):(J.style.setProperty("pointer-events","all"),J.style.setProperty("cursor","hand")),J.style.position="absolute",J.scale=h,J.rect={height:N.height,left:N.left-l,top:N.top-c,width:N.width},J.style.width=`${J.rect.width*h}px`,J.style.height=`${E*h}px`,J.style.left=`${J.rect.left*h}px`,J.style.top=`${(J.rect.top+J.rect.height/2-E/2)*h}px`,s.append(J)}let z=this.navigator.iframes[0].contentWindow?.innerWidth,V=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-count")),ee=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-width")),ae=parseInt(getComputedStyle(i.body).getPropertyValue("padding-left")),Ae=z/(V||1);Ae<ee&&(Ae=z),o||(Ae=parseInt(getComputedStyle(i.body).width.replace("px","")));let ce=this.navigator.settings.fontSize/100,be=20*ce;ce<=1&&(be=-60);let oe=0*ce;ce<=1&&(oe=-60),T=Math.floor(N.left/Ae)*Ae+Ae-(C<40?40:C)+oe,M=Math.floor(N.left/Ae)*Ae+(C<40?40:C)-be;let fe=parseInt(this.navigator.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));fe>=2&&(M=M+ae/V,T=T-ae/V),o||(T=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px","")),M=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px",""))-Ae,fe>=2&&(M=M+ae/2,T=T-ae/2))}let I=r.getBoundingClientRect(),L=i.createElement("div");L.setAttribute("class",Cd),L.style.setProperty("pointer-events","none"),L.style.position="absolute",L.scale=h,L.rect={height:I.height,left:I.left-l,top:I.top-c,width:I.width},L.style.width=`${L.rect.width*h}px`,L.style.height=`${L.rect.height*h}px`,L.style.left=`${L.rect.left*h}px`,L.style.top=`${L.rect.top*h}px`,s.append(L);let R=i.createElement("div");if(R.setAttribute("class",wd),t.icon?.position==="left")R.setAttribute("style",`position: absolute;top:${S}px;left:${M+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${C}px; width:${C}px;`);else if(t.icon?.position==="inline")R.setAttribute("style",`position: absolute;top:${S-C/2}px;left:${parseInt(L.style.left.replace("px",""))+parseInt(L.style.width.replace("px",""))-C/2}px;height:${C}px; width:${C}px;`);else if(t.icon?.position==="center"){let H=C/3*2;R.setAttribute("style",`position: absolute;top:${S}px;left:${parseInt(L.style.left.replace("px",""))+parseInt(L.style.width.replace("px",""))-H}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?R.setAttribute("style",`position: absolute;top:${S-C/2}px;left:${parseInt(L.style.left.replace("px",""))+parseInt(L.style.width.replace("px",""))-C/2}px;height:${C}px; width:${C}px;`):t.note&&t.marker===4||t.marker===0||t.marker===1?R.setAttribute("style",`position: absolute;top:${S}px;left:${T+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${C}px; width:${C}px;`):R.setAttribute("style",`position: absolute;top:${S}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?(R.classList.add(t.icon?.class),R.id=t.icon?.id):t.icon?.svgPath?R.innerHTML=rl(`${t.icon?.id}`,`${t.icon?.title}`,`${t.icon?.svgPath}`,"icon open",C,`${t.icon?.color} !important`):t.icon?.title&&(R.innerHTML=t.icon?.title);else if(t.note){let N=t.color;n.isHexColor(N)&&(N=n.hexToRgbChannels(N)),t.marker===4||t.marker===0||t.marker===1?R.innerHTML=rl("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",C/2,`rgba(${N.red}, ${N.green}, ${N.blue}, 1) !important`):R.innerHTML=rl("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(${N.red}, ${N.green}, ${N.blue}, 1) !important`)}t.type===1||t.type===2||t.type===5||t.type===3?R.style.setProperty("pointer-events","none"):(R.style.setProperty("pointer-events","all"),R.style.setProperty("cursor","hand"));let B=this;if(t.type!==3&&t.type!==4&&R.addEventListener("click",async function(N){let H;B.navigator.rights.enableAnnotations?(H=await B.navigator.annotationModule?.getAnnotationByID(t.id),B.navigator.annotationModule?.api?.selectedAnnotation(H).then(async()=>{})):B.navigator.rights.enableBookmarks&&(H=await B.navigator.bookmarkModule?.getAnnotationByID(t.id)),An.default.log("selected highlight "+H.id),B.lastSelectedHighlight=H.id;let j=document.getElementById("highlight-toolbox");if(j)if(j.style.top=N.clientY+(B.navigator.attributes?.navHeight??0)+"px",j.style.left=N.clientX+"px",getComputedStyle(j).display==="none"){let Ae=function(){B.navigator.rights.enableAnnotations?B.navigator.annotationModule?.deleteSelectedHighlight(H).then(async()=>{An.default.log("delete highlight "+H.id),j.style.display="none",B.selectionMenuClosed()}):B.navigator.rights.enableBookmarks&&B.navigator.bookmarkModule?.deleteSelectedHighlight(H).then(async()=>{An.default.log("delete highlight "+H.id),j.style.display="none",B.selectionMenuClosed()})};j.style.display="block",B.toolboxMode("edit");let z=document.getElementById("colorIcon"),V=document.getElementById("highlightIcon");z&&(z.style.display="none"),V&&(V.style.display="none");let ee=document.getElementById("commentIcon"),ae=document.getElementById("cloneCommentIcon");if(ae){let oe=ae.parentElement;oe&&oe.removeChild(ae)}ee&&(ee.style.display="none");let ce=document.getElementById("deleteIcon"),be=document.getElementById("cloneDeleteIcon");if(be){let oe=be.parentElement;oe&&oe.removeChild(be)}if(ce){ce.style.display="none";let oe=ce.cloneNode(!0),fe=ce.parentElement;oe.style.display="unset",oe.id="cloneDeleteIcon",oe.addEventListener("click",Ae,!1),fe&&fe.append(oe)}}else j.style.display="none",B.selectionMenuClosed(),j.offsetWidth,j.style.display="block";let U=Array.from(s.querySelectorAll(`.${ln}`));B.setHighlightAreaStyle(i,U,t)}),t.note){let N=document.createElement("span");N.innerHTML=t.note,N.className="icon-tooltip",t.marker===3||t.marker===2?(t.popup?.background&&N.style.setProperty("background",t.popup.background),t.popup?.textColor&&N.style.setProperty("color",t.popup.textColor),t.popup?.class&&N.classList.add(t.popup.class)):(N.style.setProperty("background","lightyellow"),N.style.setProperty("color","black"))}switch((t.note||t.marker===3||t.marker===2)&&s.append(R),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)}};yn();Ad();_();_();var tn=[];for(let n=0;n<256;++n)tn.push((n+256).toString(16).slice(1));function AT(n,e=0){return(tn[n[e+0]]+tn[n[e+1]]+tn[n[e+2]]+tn[n[e+3]]+"-"+tn[n[e+4]]+tn[n[e+5]]+"-"+tn[n[e+6]]+tn[n[e+7]]+"-"+tn[n[e+8]]+tn[n[e+9]]+"-"+tn[n[e+10]]+tn[n[e+11]]+tn[n[e+12]]+tn[n[e+13]]+tn[n[e+14]]+tn[n[e+15]]).toLowerCase()}_();var Gy,cY=new Uint8Array(16);function Wy(){if(!Gy){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Gy=crypto.getRandomValues.bind(crypto)}return Gy(cY)}_();_();var dY=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Vy={randomUUID:dY};function hY(n,e,t){if(Vy.randomUUID&&!e&&!n)return Vy.randomUUID();n=n||{};let i=n.random??n.rng?.()??Wy();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 AT(i)}var al=hY;_();var fY=Qe(Qt());var Vo={className:n=>!0,idName:n=>!0,tagName:n=>!0};var ET=Qe(vp()),Ir=Qe(Qt());_();var vT=Qe(Qt());var ul=class{constructor(e,t,i){this.currSeconds=0;this.publication=e,this.properties=t,this.api=i}static async create(e){let t=new this(e.publication,e,e.api);return await t.start(),t}async start(){this.startResearchSession()}async stop(){vT.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)}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.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)}};var ll=class n{constructor(e,t,i,r,s,o,a,u){this.hide=ge(document,"#menu-button-hide");this.show=ge(document,"#menu-button-show");this.annotator=e,this.rights=t,this.publication=i,this.headerMenu=u,this.initialAnnotations=r,this.highlighter=o,this.properties=s,this.api=a}static async create(e){let t=new this(e.annotator,e.rights||{enableAnnotations:!1,enableTTS:!1},e.publication,e.initialAnnotations||null,e,e.highlighter,e.api,e.headerMenu);return await t.start(),t}async stop(){Ir.default.log("Annotation module stop")}async start(){if(this.headerMenu&&(this.highlightsView=ge(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var e=this.initialAnnotations.highlights||null;e&&this.annotator?.initAnnotations(e)}setTimeout(()=>{this.properties?.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)}hideAnnotationLayer(){let e=this.navigator.iframes[0].contentDocument;if(e){let t=ge(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.navigator.iframes[0].contentDocument;if(e){let t=ge(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.rights.enableAnnotations&&setTimeout(()=>{this.drawHighlights(),this.showHighlights(),te(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=ET.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.navigator.iframes[0].contentDocument;if(r){let l=function(h){try{let f=u.navigator.iframes[0].contentDocument;return f?Vi(h,f,Vo):""}catch(f){return Ir.default.log("uniqueCssSelector:"),Ir.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=to(o,l);if(s.removeAllRanges(),c){let h={rangeInfo:c},f=this.navigator.highlighter?.createHighlight(this.navigator.highlighter?.dom(r.body).getWindow(),h,i.highlight?.color,!0,2,i.icon,i.popup,i.highlight?.style);f&&this.saveAnnotation(f[0]).then(m=>{Ir.default.log("saved bookmark "+m.id)})}r.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(e){Ir.default.log("still need to scroll to "+e);var t=await this.annotator?.getAnnotationElement(e,this.navigator.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 Ir.default.log("Highlight deleted "+JSON.stringify(t)),Ir.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 Ir.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)}async addAnnotation(e){await this.annotator?.saveAnnotation(e),await this.showHighlights(),await this.drawHighlights()}async deleteHighlight(e){this.api?.deleteAnnotation?this.api?.deleteAnnotation(e).then(async()=>{this.deleteLocalHighlight(e.id)}):this.deleteLocalHighlight(e.id)}async deleteSelectedHighlight(e){this.api?.deleteAnnotation?this.api.deleteAnnotation(e).then(async()=>{this.deleteLocalHighlight(e.id)}):this.deleteLocalHighlight(e.id)}async updateAnnotation(e){this.api?.updateAnnotation?this.api.updateAnnotation(e).then(async()=>{this.updateLocalHighlight(e)}):this.updateLocalHighlight(e)}async saveAnnotation(e){if(this.annotator){var t=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let i=this.navigator.view?.getCurrentPosition(),r=this.navigator.iframes[0].contentDocument;if(r){let s=qs(r,"body"),o=e.position?e.position/s.scrollHeight:i,a=al(),u;if(t){let l=t.Href;if(l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let c=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),h=Math.ceil((o??0)*(c.length-1));u={...c[h],id:a,href:l,created:new Date,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}else u={id:a,href:l,locations:{progression:o},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}if(u)if(this.navigator.consumptionModule?.trackAction(u,"HighlightCreated"),this.api?.addAnnotation)try{let l=await this.api.addAnnotation(u),c=await this.annotator.saveAnnotation(l);return await this.showHighlights(),await this.drawHighlights(),new Promise(h=>h(c))}catch{await this.showHighlights(),await this.drawHighlights()}else{let l=await this.annotator.saveAnnotation(u);return 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=>{li.push(t.highlight)}))),this.highlightsView&&this.createTree(1,e,this.highlightsView)}async drawHighlights(){if(this.rights.enableAnnotations&&this.highlighter){if(this.api){let t=[];if(this.annotator&&(t=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&t&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(0);for(let i of t){li.push(i.highlight);let r=i,s=this.navigator.currentChapterLink.href;var e=this.publication.getTOCItem(s);if(this.navigator.currentTocUrl!==void 0&&(e=this.publication.getTOCItem(this.navigator.currentTocUrl)),e===null&&(e=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),e){let o=e.Href;o.indexOf("#")>0&&(o=o.slice(0,o.indexOf("#"))),r.href===o&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(r.highlight?.marker===1){let u='<div class="comment" style="top: '+await this.annotator?.getAnnotationPosition(i.id,this.navigator.iframes[0].contentWindow)+'px;width:20px"></div>',l=document.createElement("div");l.innerHTML=u;let c=l.childNodes[0],h=document.createElement("i");h.innerHTML="sticky_note_2",h.className="material-icons",h.style.color=r.highlight.color,c.appendChild(h),te(l,"click",f=>{f.preventDefault(),f.stopPropagation(),this.scrollToHighlight(r.id)})}},100))}}}}else{let t=[];if(this.annotator&&(t=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&t&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(0);for(let i of t){li.push(i.highlight);let r=i,s=this.navigator.currentChapterLink.href,o=this.publication.getTOCItem(s);if(this.navigator.currentTocUrl&&(o=this.publication.getTOCItem(this.navigator.currentTocUrl)),o===null&&(o=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),o){let a=o.Href;a.indexOf("#")>0&&(a=a.slice(0,a.indexOf("#"))),r.href===a&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(r.highlight?.marker===1){let l='<div class="comment" style="top: '+await this.annotator?.getAnnotationPosition(i.id,this.navigator.iframes[0].contentWindow)+"px;background: "+r.highlight?.color+';width:20px"></div>',c=document.createElement("div");c.innerHTML=l,c.childNodes[0].innerHTML=qr.note,te(c,"click",h=>{h.preventDefault(),h.stopPropagation(),this.scrollToHighlight(r.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){let e=this.navigator.iframes[0].contentDocument;if(e&&(this.commentGutter=e.getElementById("R2_ID_GUTTER_RIGHT_CONTAINER"),this.navigator.view?.isScrollMode()&&this.properties?.enableComments?this.commentGutter?.style.removeProperty("display"):this.commentGutter?.style.setProperty("display","none"),this.commentGutter&&this.navigator.view?.isScrollMode()&&this.properties?.enableComments)){this.commentGutter.innerHTML="";let t=[];this.annotator&&(t=this.annotator.getAnnotationsByChapter(this.navigator.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(ln)[0];let l=parseInt(a.style.height.replace("px","")),c=i.highlight.position,h=e.createElement("div");h.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");h.appendChild(f);let m=i.highlight.color;Xt.isHexColor(m)&&(m=Xt.hexToRgbChannels(m)),h.innerHTML=rl("","",'<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;`),h.appendChild(y),te(h,"click",g=>{g.preventDefault(),g.stopPropagation(),this.scrollToHighlight(i.highlight.id)}),this.commentGutter?.appendChild(h)})))}}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 h=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||"",h.appendChild(f)}else m.innerHTML=c.Title||"",m.className="chapter-title",h.appendChild(m);te(f,"click",g=>{g.preventDefault(),g.stopPropagation();let b={href:f.href,locations:{progression:0},type:c.TypeLink,title:f.title};this.navigator.stopReadAloud(),this.navigator.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 A=document.createElement("li");A.className="annotation-item";let v=document.createElement("a");if(v.setAttribute("href",g.href),e===1){v.className="highlight-link";let S=document.createElement("span"),C=document.createElement("span");if(S.className="title",C.innerHTML=g.highlight.selectionInfo.cleanText,g.highlight?.marker===1)if(typeof g.highlight?.color=="object"){let I=g.highlight?.color;I&&C.style.setProperty("border-bottom",`2px solid ${Xt.hexToRgbA(I)}`,"important")}else C.style.setProperty("border-bottom",`2px solid ${g.highlight?.color}`,"important");else if(typeof g.highlight?.color=="object"){let I=g.highlight?.color;I&&(C.style.backgroundColor=Xt.hexToRgbA(I))}else{let I=g.highlight?.color;I&&(C.style.backgroundColor=I)}S.appendChild(C),v.appendChild(S);let T=document.createElement("span"),M=Math.round((g.locations.progression??0)*100)+"% through resource";T.className="subtitle",T.innerHTML=M,v.appendChild(T)}let E=document.createElement("span");if(E.className="timestamp",E.innerHTML=n.readableTimestamp(g.created),v.appendChild(E),te(v,"click",S=>{S.preventDefault(),S.stopPropagation(),r.handleAnnotationLinkClick(S,g)}),A.appendChild(v),r.navigator.sideNavExpanded){let S=document.createElement("button");S.className="delete",S.innerHTML=qr.delete,te(S,"click",C=>{C.preventDefault(),C.stopPropagation(),r.handleAnnotationLinkDeleteClick(e,C,g)}),A.appendChild(S)}y.appendChild(A)}}),y.children.length>0&&(l.appendChild(h),l.appendChild(y)),l.children.length>0&&a.appendChild(l),c.Children&&c.Children.length>0&&o(a,c.Children)}};i.innerHTML="",o(i,s)}}}handleAnnotationLinkClick(e,t){t?(t.href=this.publication.getAbsoluteHref(t.href),this.navigator.stopReadAloud(),this.navigator.navigate(t)):Ir.default.log("annotation data missing: ",e)}handleAnnotationLinkDeleteClick(e,t,i){Ir.default.log("annotation data locator: ",i),i?e===1&&this.deleteHighlight(i):Ir.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.navigator.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(ln)[0];let c=parseInt(u.style.top.replace("px","")),h={...s,highlight:{...s.highlight,position:c}};return[...r,h]};return e.reduce(i,[])}reposition(e){let t=this.navigator.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(ln)[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,A=b>m?b:m,v={...s,highlight:{...s.highlight,position:A}};return[...r,v]};return e.sort(function(r,s){return r.highlight.position-s.highlight.position}).reduce(i,[])}};_();ui();yn();Ad();var Pr=Qe(Qt());var cl=class n{static async create(e){let t=new this(e.annotator,e.rights||{enableBookmarks:!1},e.publication,e,e.initialAnnotations,e.api,e.headerMenu);return await t.start(),new Promise(i=>i(t))}constructor(e,t,i,r,s,o,a){this.annotator=e,this.rights=t,this.publication=i,this.headerMenu=a,this.initialAnnotations=s,this.properties=r,this.api=o}stop(){Pr.default.log("Bookmark module stop")}async start(){if(this.headerMenu&&(this.bookmarksView=ge(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=ge(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let e=ge(this.headerMenu,"#menu-button-bookmark");e&&e.parentElement?.style.removeProperty("display"),e&&te(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.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)},100)}initialize(){return new Promise(async e=>{await document.fonts.ready,this.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 Pr.default.log("Bookmark deleted "+JSON.stringify(t)),await this.showBookmarks(),await this.drawBookmarks(),t}else{let t=await this.annotator.deleteBookmark(e);return Pr.default.log("Bookmark deleted "+JSON.stringify(t)),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.navigator.currentChapterLink.href);if(this.navigator.currentTocUrl&&(e=this.publication.getTOCItem(this.navigator.currentTocUrl)),e===void 0&&(e=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),e){let t=e.Href;t.indexOf("#")>0&&(t=t.slice(0,t.indexOf("#")));let i=this.navigator.view?.getCurrentPosition(),r=al(),s;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let o=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),a=Math.ceil((i??0)*(o.length-1));s={...o[a],id:r,href:t,created:new Date,title:this.navigator.currentChapterLink.title}}else s={id:r,href:t,locations:{progression:i},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title};if(!this.annotator.locatorExists(s,0))if(this.navigator.consumptionModule?.trackAction(s,"BookmarkCreated"),this.api?.addBookmark){let o=await this.api.addBookmark(s);o&&(s=o),Pr.default.log(s);let a=this.annotator.saveBookmark(s);return Pr.default.log("Bookmark added "+JSON.stringify(a)),this.showBookmarks(),await this.drawBookmarks(),a}else{let o=this.annotator.saveBookmark(s);return Pr.default.log("Bookmark added "+JSON.stringify(o)),this.showBookmarks(),await this.drawBookmarks(),o}}}}async addBookmarkPlus(){let e=this,t=this.navigator.highlighter?.visibleTextRects[0],i=this.navigator.iframes[0].contentDocument;if(i){let a=this.navigator.highlighter?.dom(i.body).getWindow().document.createRange(),u=this.navigator.highlighter?.dom(this.navigator.iframes[0].contentDocument?.body).getSelection();u.removeAllRanges(),t&&a.selectNodeContents(t.node),u.addRange(a);let l=bp(a,!1),c=0;for(let h of l){if(!this.navigator.highlighter?.isOutsideViewport(h)){let f=u.focusNode,m=u.focusOffset;u.collapse(u.anchorNode,u.anchorOffset);for(let A=0;A<c;A++)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.navigator.iframes[0].contentDocument;if(l)return Vi(a,e.navigator.highlighter?.dom(l.body).getDocument(),u)}let s=this.navigator.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=As(s,r);if(a===void 0){let l=e.navigator.iframes[0].contentDocument;a=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(l)??void 0}let u=e.navigator.iframes[0].contentDocument;if(a&&u){let l=this.navigator.highlighter?.createHighlight(this.navigator.highlighter?.dom(u.body).getWindow(),a,o.highlight?.color,!0,2,o.icon,o.popup,o.highlight?.style);if(this.navigator.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),l)return this.saveAnnotation(l[0]).then(c=>{Pr.default.log("saved bookmark "+c?.id)})}}}async saveAnnotation(e){if(this.annotator){var t=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let i=this.navigator.view?.getCurrentPosition(),r=this.navigator.iframes[0].contentDocument;if(r){let s=qs(r,"body"),o=e.position?e.position/s.scrollHeight:i,a=al(),u;if(t){let l=t.Href;if(l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let c=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),h=Math.ceil((o??0)*(c.length-1));u={...c[h],id:a,href:l,created:new Date,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}else u={id:a,href:l,locations:{progression:o},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}if(u)if(this.navigator.consumptionModule?.trackAction(u,"BookmarkCreated"),this.api?.addBookmark){let l=await this.api.addBookmark(u),c=await this.annotator.saveAnnotation(l);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(h=>h(c))}else{let l=await this.annotator.saveAnnotation(u);return 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.rights.enableBookmarks&&this.navigator.highlighter)if(this.api){let t=[];if(this.annotator&&(t=await this.annotator.getAnnotations()),this.navigator.highlighter&&t&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.navigator.highlighter.destroyHighlights(0);for(let i of t){li.push(i.highlight);let r=i,s=this.navigator.currentChapterLink.href;var e=this.publication.getTOCItem(s);if(this.navigator.currentTocUrl&&(e=this.publication.getTOCItem(this.navigator.currentTocUrl)),e===void 0&&(e=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),e){let o=e.Href;o.indexOf("#")>0&&(o=o.slice(0,o.indexOf("#"))),r.href===o&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight)}}}}else{let t=[];if(this.annotator&&(t=await this.annotator.getAnnotations()),this.navigator.highlighter&&t&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.navigator.highlighter.destroyHighlights(0);for(let i of t){li.push(i.highlight);let r=i,s=this.navigator.currentChapterLink.href,o=this.publication.getTOCItem(s);if(this.navigator.currentTocUrl&&(o=this.publication.getTOCItem(this.navigator.currentTocUrl)),o===void 0&&(o=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),o){let a=o.Href;a.indexOf("#")>0&&(a=a.slice(0,a.indexOf("#"))),r.href===a&&await this.navigator.highlighter.createHighlightDom(this.navigator.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 Pr.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 h=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||"",h.appendChild(f)}else m.innerHTML=c.Title||"",m.className="chapter-title",h.appendChild(m);te(f,"click",g=>{g.preventDefault(),g.stopPropagation();let b={href:f.href,locations:{progression:0},type:c.TypeLink,title:f.title};this.navigator.stopReadAloud(),this.navigator.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 A=document.createElement("li");A.className="annotation-item";let v=document.createElement("a");if(v.setAttribute("href",g.href),e===0){v.className="bookmark-link";let S=document.createElement("span"),C=Math.round((g.locations.progression??0)*100)+"% through resource";S.className="title",S.innerHTML=C,v.appendChild(S)}let E=document.createElement("span");if(E.className="timestamp",E.innerHTML=n.readableTimestamp(g.created),v.appendChild(E),te(v,"click",S=>{S.preventDefault(),S.stopPropagation(),r.handleAnnotationLinkClick(S,g)}),A.appendChild(v),r.navigator.sideNavExpanded){let S=document.createElement("button");S.className="delete",S.innerHTML=qr.delete,te(S,"click",C=>{C.preventDefault(),C.stopPropagation(),r.handleAnnotationLinkDeleteClick(e,C,g)}),A.appendChild(S)}y.appendChild(A)}}),y.children.length>0&&(l.appendChild(h),l.appendChild(y)),l.children.length>0&&a.appendChild(l),c.Children&&c.Children.length>0&&o(a,c.Children)}};i.innerHTML="",o(i,s)}}}handleAnnotationLinkClick(e,t){t?(t.href=this.publication.getAbsoluteHref(t.href),this.navigator.stopReadAloud(),this.navigator.navigate(t)):Pr.default.log("bookmark data missing: ",e)}handleAnnotationLinkDeleteClick(e,t,i){Pr.default.log("bookmark data locator: ",i),i?e===0&&this.deleteBookmark(i):Pr.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)}};_();var zy=Qe(CT());_();ui();yn();var Nn=Qe(Qt()),Ky="r2-mo-active",nn=class nn{};nn.COLOR_REF="color",nn.AUTO_SCROLL_REF="autoscroll",nn.AUTO_TURN_REF="autoturn",nn.VOLUME_REF="volume",nn.RATE_REF="rate",nn.COLOR_KEY="mediaoverlay-"+nn.COLOR_REF,nn.AUTO_SCROLL_KEY="mediaoverlay-"+nn.AUTO_SCROLL_REF,nn.AUTO_TURN_KEY="mediaoverlay-"+nn.AUTO_TURN_REF,nn.VOLUME_KEY="mediaoverlay-"+nn.VOLUME_REF,nn.RATE_KEY="mediaoverlay-"+nn.RATE_REF;var Je=nn,wp=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(),Nn.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,Nn.default.log(t.color)),i?.autoScroll&&(t.autoScroll=i.autoScroll,Nn.default.log(t.autoScroll)),i?.autoTurn&&(t.autoTurn=i.autoTurn,Nn.default.log(t.autoScroll)),i?.volume&&(t.volume=i.volume,Nn.default.log(t.volume)),i?.rate&&(t.rate=i.rate,Nn.default.log(t.rate)),i?.wait&&(t.wait=i.wait,Nn.default.log(t.wait))}return t.initializeSelections(),t}stop(){Nn.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(Je.AUTO_SCROLL_KEY)!=null?this.getProperty(Je.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(Je.AUTO_TURN_KEY)!=null?this.getProperty(Je.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(Je.COLOR_KEY)!=null?this.getProperty(Je.COLOR_KEY).value:this.color,this.volume=this.getProperty(Je.VOLUME_KEY)!=null?this.getProperty(Je.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(Je.RATE_KEY)!=null?this.getProperty(Je.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=ge(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechAutoTurn=ge(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=ge(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=ge(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=ge(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()),te(ge(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(Je.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Je.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(Je.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(Je.VOLUME_REF)?.value,rate:this.userProperties.getByRef(Je.RATE_REF)?.value};this.applyMediaOverlaySettings(e),this.api?.updateSettings&&this.api?.updateSettings(e).then(async t=>{Nn.default.log("api updated sync settings",t)})}getMediaOverlaySettings(){let e=new ds;return e.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,Je.AUTO_SCROLL_REF,Je.AUTO_SCROLL_KEY),e.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,Je.AUTO_TURN_REF,Je.AUTO_TURN_KEY),e.addStringable(this.color,Je.COLOR_REF,Je.COLOR_KEY),e.addIncremental(this.volume,.1,1,.1,"",Je.VOLUME_REF,Je.VOLUME_KEY),e.addIncremental(this.rate,.1,3,.1,"",Je.RATE_REF,Je.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(Je.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){Nn.default.log("autoScroll "+this.autoScroll),this.autoScroll=e.autoScroll;let t=this.userProperties.getByRef(Je.AUTO_SCROLL_REF);t&&(t.value=this.autoScroll,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoTurn!==void 0){Nn.default.log("autoTurn "+this.autoTurn),this.autoTurn=e.autoTurn;let t=this.userProperties.getByRef(Je.AUTO_TURN_REF);t&&(t.value=this.autoTurn,this.saveProperty(t)),this.settingsChangeCallback()}if(e.volume){Nn.default.log("volume "+this.volume),this.volume=e.volume;let t=this.userProperties.getByRef(Je.VOLUME_REF);t&&(t.value=this.volume,this.saveProperty(t)),this.settingsChangeCallback()}if(e.rate){Nn.default.log("rate "+this.rate),this.rate=e.rate;let t=this.userProperties.getByRef(Je.RATE_REF);t&&(t.value=this.rate,this.saveProperty(t)),this.settingsChangeCallback()}}applyMediaOverlaySetting(e,t){if(e===Je.COLOR_REF){this.color=t;let i=this.userProperties.getByRef(Je.COLOR_REF);i&&(i.value=this.color,this.saveProperty(i)),this.settingsChangeCallback()}else if(e===Je.AUTO_SCROLL_REF){this.autoScroll=t;let i=this.userProperties.getByRef(Je.AUTO_SCROLL_REF);i&&(i.value=this.autoScroll,this.saveProperty(i)),this.settingsChangeCallback()}else if(e===Je.AUTO_TURN_REF){this.autoTurn=t;let i=this.userProperties.getByRef(Je.AUTO_TURN_REF);i&&(i.value=this.autoTurn,this.saveProperty(i)),this.settingsChangeCallback()}}increase(e){if(e==="mo_volume"){this.userProperties.getByRef(Je.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(Je.VOLUME_REF)?.value;let t=this.userProperties.getByRef(Je.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(Je.RATE_REF).increment(),this.rate=this.userProperties.getByRef(Je.RATE_REF)?.value;let t=this.userProperties.getByRef(Je.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback()}}decrease(e){if(e==="mo_volume"){this.userProperties.getByRef(Je.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(Je.VOLUME_REF)?.value;let t=this.userProperties.getByRef(Je.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(Je.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(Je.RATE_REF)?.value;let t=this.userProperties.getByRef(Je.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback()}}};ui();var He=Qe(Qt()),hl=class{constructor(e,t,i){this.play=ge(document,"#menu-button-play");this.pause=ge(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async e=>{He.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}static create(e){let t=new this(e.publication,e.settings,e);return t.start(),t}stop(){He.default.log("MediaOverlay module stop")}start(){He.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?.Properties?.MediaOverlay){this.ensureOnTimeUpdate(!1,!1);let t=e.Properties?.MediaOverlay,r=new URL(t,this.publication.manifestUrl).toString(),s;try{s=await fetch(r,this.navigator.requestConfig)}catch(l){console.error(l,r);return}s.ok||He.default.log("BAD RESPONSE?!");let o;try{o=await s.json()}catch(l){console.error(l)}if(!o){He.default.log("## moJson"+o);return}e.MediaOverlays=Sa(o,zy.MediaOverlayNode),e.MediaOverlays.initialized=!0;let a=e.HrefDecoded||e.Href,u=new URL("https://dita.digital/"+a);await this.playMediaOverlays(u.pathname.substr(1),e.MediaOverlays,void 0)}else this.audioElement&&await this.audioElement.pause(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement&&await this.audioElement.pause(),this.navigator.nextResource()):await this.stopReadAloud()}bindClickHandler(){this.unbindClickHandler();let e=this.handleContentClick.bind(this);this.clickHandler=e;for(let t of this.navigator.iframes)t.contentDocument?.body?.addEventListener("click",e)}unbindClickHandler(){let e=this.clickHandler;if(e){for(let t of this.navigator.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 h=0;h<this.navigator.iframes.length;h++)if(this.navigator.iframes[h].contentDocument===r){s=h;break}let o=this.currentLinks[s];if(!o)return;if(s!==this.currentLinkIndex||!this.mediaOverlayRoot){if(!o.MediaOverlays?.initialized)if(o.Properties?.MediaOverlay){let h=o.Properties.MediaOverlay,f=new URL(h,this.publication.manifestUrl);try{let m=await fetch(f.toString(),this.navigator.requestConfig);if(m.ok){let y=await m.json();y&&(o.MediaOverlays=Sa(y,zy.MediaOverlayNode),o.MediaOverlays.initialized=!0)}}catch{He.default.log("handleContentClick() - failed to load MO for clicked page");return}}else return;this.currentLinkIndex=s,this.mediaOverlayRoot=o.MediaOverlays}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.navigator.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement&&this.currentLinks[this.currentLinkIndex]?.Properties?.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.navigator.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"),this.bindClickHandler()}}async stopReadAloud(){this.navigator.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.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"))}findDepthFirstTextAudioPair(e,t,i){He.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(He.default.log("isFragmentIDMatch: "+s),He.default.log("isTextUrlMatch: "+r),!t.Children||!t.Children.length){if(He.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!r){He.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return s||r&&!i?(He.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),t):void 0}let o=i,a=i;for(let u of t.Children){He.default.log("findDepthFirstTextAudioPair() - child"),He.default.log(JSON.stringify(u));let l=this.findDepthFirstTextAudioPair(e,u,a);if(l===null&&(He.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),a=void 0),l)return He.default.log("findDepthFirstTextAudioPair() - child - match"),He.default.log(JSON.stringify(l)),l}if(s){He.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let u=this.findDepthFirstTextAudioPair(e,t,void 0);return u&&(He.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),He.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&&(He.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(He.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let t=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!e);if(!t)He.default.log("mediaOverlaysNext() - navLeftOrRight()"),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.navigator.nextResource()):this.stopReadAloud());else{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&&(He.default.log("mediaOverlaysNext() SWITCH! "+r.pathname+" != "+s.pathname),i=!0)}i?this.mediaOverlaysStop():(He.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(t,void 0,void 0)},0))}}else He.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.navigator.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){He.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){He.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 He.default.log("findNextTextAudioPair() - prevMo === moToMatch"),e;He.default.log("findNextTextAudioPair() - set previous"),He.default.log(JSON.stringify(e)),i.prev=e;return}for(let s of e.Children){He.default.log("findNextTextAudioPair() - child"),He.default.log(JSON.stringify(s));let o=this.findNextTextAudioPair(s,t,i,r);if(o)return He.default.log("findNextTextAudioPair() - match"),He.default.log(JSON.stringify(o)),o}}async playMediaOverlaysAudio(e,t,i){if(He.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 h=r.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(h&&h.length>=1){let f=h[1];try{this.currentAudioBegin=parseFloat(f)}catch(m){He.default.error(m)}if(h.length>=3){let m=h[3];try{this.currentAudioEnd=parseFloat(m)}catch(y){He.default.error(y)}}}}}else this.currentAudioBegin=t,this.currentAudioEnd=i;He.default.log(`${s} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let c=async h=>{if(!this.audioElement)return;let f=this.currentAudioBegin?this.currentAudioBegin:0;if(h||this.audioElement.paused)if(h&&!f||this.audioElement.currentTime===f){if(He.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{He.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let m=async y=>{if(this.audioElement.removeEventListener("timeupdate",m),He.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?He.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(He.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=f)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||a!==this.currentAudioUrl){this.currentAudioUrl=a,He.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=>{He.default.log("-1) error: "+(this.currentAudioUrl!==m.currentTarget.src?this.currentAudioUrl+" -- ":"")+m.currentTarget.src.substr(m.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(He.default.log(this.audioElement.error.code),He.default.log(this.audioElement.error.message))});let h=async m=>{m.currentTarget.removeEventListener("canplaythrough",h),He.default.log("oncanplaythrough"),await c(!0)};this.audioElement.addEventListener("canplaythrough",h);let f=async m=>{He.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.navigator.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",f),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else He.default.log("playMediaOverlaysAudio() - playClip()"),await c(!1)}async playMediaOverlays(e,t,i){He.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&&(He.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),He.default.log(JSON.stringify(r,null,4)),He.default.log(JSON.stringify(t,null,4)),s=this.findDepthFirstTextAudioPair(e,t,void 0)),s?s.Audio&&(He.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=t,await this.playMediaOverlaysAudio(s,void 0,void 0)):He.default.log("playMediaOverlays() - !moTextAudioPair "+e)}mediaOverlayHighlight(e){He.default.log("moHighlight: ## "+e);let t=this.publication.Metadata?.MediaOverlay?.ActiveClass;t||(t=this.settings.color);let i=this.navigator.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.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&(t=r||s?Ky:t||Ky),this.pid)for(let a of this.navigator.iframes){let u=a.contentDocument?.getElementById(this.pid);u&&u.classList.remove(t)}let o;e&&(this.currentLinkIndex===0?o=this.navigator.iframes[0].contentDocument?.getElementById(e):o=this.navigator.iframes[1].contentDocument?.getElementById(e),o&&o.classList.add(t),this.pid=e),o&&(this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&o.scrollIntoView({block:"center",behavior:"smooth"})}};_();ui();yn();var qy=Qe(Qt()),fl=class{static async create(e){let t=new this(e.publication);return await t.start(),t}constructor(e){this.publication=e}async stop(){qy.default.log("Timeline module stop")}async start(){this.timelineContainer=ge(document,"#container-view-timeline"),this.positionSlider=ge(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.navigator.currentLocator();(this.navigator.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.navigator.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)}te(l,"click",h=>{h.preventDefault(),h.stopPropagation();var f;this.publication.positions||this.navigator.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.TypeLink,title:i.Title},qy.default.log(f),this.navigator.navigate(f)}),a===this.navigator.currentChapterLink.href?l.className+=" active":l.className=l.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(l)}),e()})}};_();ui();yn();var BA=Qe(eo());_();var ST=Qe(Qt());function _T(n,e){return new Promise(function(t){setTimeout(t.bind(null,e),n)})}var bY=!1;ST.default.setLevel(bY?"trace":"warn",!0);var t1=Qe(xT()),rn=Qe(Qt());_();var QP=Qe(x9(),1),$r=Qe(GP(),1);_();var WP=[{regex:/IE (\d+)\.(\d+)/,family:"ie",maxVersion:[7,1/0,1/0]},{regex:/Trident\/4\.0/,family:"ie",version:[8,0,0]},{regex:/Trident\/5\.0/,family:"ie",version:[9,0,0]},{regex:/Trident\/6\.0/,family:"ie",version:[10,0,0]},{regex:/Trident\/[78]\.0/,family:"ie",version:[11,0,0]},{regex:/Edge?\/(\d+)\.(\d+)(\.(\d+)|)/,family:"edge"},{regex:/Firefox\/(\d+)\.(\d+)(\.(\d+)|)/,family:"firefox"},{regex:/Chrom(ium|e)\/(\d+)\.(\d+)(\.(\d+)|)/,family:"chrome"},{regex:/Chrom(ium|e)\/(\d+)\.(\d+)(\.(\d+)|)([\d.]+$|.*Safari\/(?![\d.]+ Edge\/[\d.]+$))/,family:"chrome",maxVersion:[70,1/0,1/0]},{regex:/(Maci|X11).+ Version\/(\d+)\.(\d+)([.,](\d+)|)( \(\w+\)|)( Mobile\/\w+|) Safari\//,family:"safari"},{regex:/Opera\/9\.80.+Version\/(\d+)\.(\d+)(\.(\d+)|)/,family:"opera",maxVersion:[12,15,0]},{regex:/Chrome.+OPR\/(\d+)\.(\d+)\.(\d+)/,family:"opera",minVersion:[15,0,0]},{regex:/(CPU[ +]OS|iPhone[ +]OS|CPU[ +]iPhone|CPU IPhone OS|CPU iPad OS)[ +]+(\d+)[_.](\d+)([_.](\d+)|)/,family:"ios_saf"},{regex:/[^e] (CPU[ +]OS|iPhone[ +]OS|CPU[ +]iPhone|CPU IPhone OS|CPU iPad OS)[ +]+(\d+)[_.](\d+)([_.](\d+)|)/,family:"ios_saf",version:[7,0,3]},{regex:/Opera Mini/,family:"op_mini"},{regex:/Android Donut/,family:"android",version:[1,2,0]},{regex:/Android Eclair/,family:"android",version:[2,1,0]},{regex:/Android Froyo/,family:"android",version:[2,2,0]},{regex:/Android Gingerbread/,family:"android",version:[2,3,0]},{regex:/Android Honeycomb/,family:"android",version:[3,0,0]},{regex:/Android:?[ /-](\d+)(\.(\d+)|)(\.(\d+)|)/,family:"android"},{regex:/Android:?[ /-](\d+)(\.(\d+)|)(\.(\d+)|);(?! ARM; Trident)/,family:"android",version:[4,0,0]},{regex:/PlayBook.+RIM Tablet OS (\d+)\.(\d+)\.(\d+)/,family:"bb"},{regex:/(Black[bB]erry|BB10).+Version\/(\d+)\.(\d+)\.(\d+)/,family:"bb"},{regex:/Opera\/.+Opera Mobi.+Version\/(\d+)\.(\d+)/,family:"op_mob",maxVersion:[12,16,0]},{regex:/Mobile Safari.+OPR\/(\d+)\.(\d+)\.(\d+)/,family:"op_mob",minVersion:[14,0,0]},{regex:/Android.+Firefox\/(\d+)\.(\d+)(\.(\d+)|)/,family:"and_ff"},{regex:/Android.+Chrom(ium|e)\/(\d+)\.(\d+)(\.(\d+)|)/,family:"and_chr"},{regex:/IEMobile[ /](\d+)\.(\d+)/,family:"ie_mob"},{regex:/Android.+(UC? ?Browser|UCWEB|U3)[ /]?(\d+)\.(\d+)\.(\d+)/,family:"and_uc"},{regex:/SamsungBrowser\/(\d+)\.(\d+)/,family:"samsung"},{regex:/Android.+MQQBrowser\/(\d+)(\.(\d+)|)(\.(\d+)|)/,family:"and_qq"},{regex:/baidubrowser[/\s](\d+)(\.(\d+)|)(\.(\d+)|)/,family:"baidu"},{regex:/K[Aa][Ii]OS\/(\d+)\.(\d+)(\.(\d+)|)/,family:"kaios"}];function MA(n){return typeof n=="number"?n:n.length===1?n[0]:[n[0],n[n.length-1]]}var Li;(function(n){n[n.Major=0]="Major",n[n.Minor=1]="Minor",n[n.Patch=2]="Patch"})(Li||(Li={}));function VP(n){let e=Array.isArray(n)?n:n.toString().split(".");if(e[0]==="all")return[1/0,0,0];let t=null,i=null,r=[0,0,0];for(let s=0;s<3;s++)if(t=e[s],!(typeof t>"u")){if(i=typeof t=="number"?t:parseInt(t,10),isNaN(i))return null;r[s]=i}return r}function AQ(n,e){let t=0,i=[];for(let r=2;r>=0;r--)if(n[r]!==e[r]){t=r;break}for(let r=n[t],s=e[t];r<=s;r++)i.push(n.map((o,a)=>a===t?r:o));return i}function KP(n,e,t){let[i,r,s]=n,[o,a,u]=e,{ignoreMinor:l,ignorePatch:c,allowHigherVersions:h}=t;if(o===1/0)return!0;let f=!l,m=f&&!c;return h?m&&s<u||f&&r<a?!1:i>=o:m&&s!==u||f&&r!==a?!1:i===o}function vQ(n,e){let{ignoreMinor:t,ignorePatch:i,allowZeroSubversions:r}=e,s=t?1:i?2:3;if(r)for(let o=s-1;o>0&&!(n[o]!==0||s===1);o--)s--;return s}function wQ(n){return n.reduce((e,t)=>{let[i,r,s]=t.split(/ |-/),o=VP(r);return(o?s?AQ(o,VP(s)):[o]:[]).reduce((u,l)=>(l&&u.push({family:i,version:l}),u),e)},[])}function EQ(n={}){let{browsers:e,...t}=n,i=(0,QP.default)(e,t);return wQ(i)}function CQ(n,e,t=0){let i=n.length;for(let r=t;r<i;r++)if(n[r]!==e[r])return!1;return!0}function XP(n){if(n===null||typeof n!="object")return n;let e=Array.isArray(n)?[]:{},t;for(t in n)e[t]=XP(n[t]);return e}function Zp(n){return[].concat(...n)}function SQ(n){let e=new Map;return n.forEach(({family:t,version:i})=>{let r=e.get(t);if(r){let s=i.join(".");r.every(o=>o.join(".")!==s)&&r.push(i);return}e.set(t,[i])}),e.forEach(t=>{t.sort((i,r)=>{for(let s in i)if(i[s]!==r[s])return i[s]-r[s];return 0})}),e}function _Q(n){if(n.length<2)return n;let e=n.length+1,t=[],i=null,r=n[0],s=[r[Li.Major]],o=[r[Li.Minor]],a=[r[Li.Patch]],u=null;for(let l=1;l<e;l++){i=n[l-1],r=n[l]||[];for(let c=Li.Major;c<=Li.Patch;c++){if((c===u||u===null)&&i[c]+1===r[c]&&CQ(i,r,c+1)){u=c,c===Li.Major?s.push(r[Li.Major]):s=r[Li.Major],c===Li.Minor?o.push(r[Li.Minor]):o=r[Li.Minor],c===Li.Patch?a.push(r[Li.Patch]):a=r[Li.Patch];break}if(u===c||i[c]!==r[c]){t.push([MA(s),MA(o),MA(a)]),s=[r[Li.Major]],o=[r[Li.Minor]],a=[r[Li.Patch]],u=null;break}}}return t}function xQ(n){return{type:"RegExp",body:n,flags:""}}function lo(...n){let e=Zp(n).filter(Boolean);return e.length===1?e[0]:{type:"Alternative",expressions:e}}function Mr(n){return{type:"Char",kind:"simple",value:String(n),codePoint:NaN}}function TQ(n){return{type:"Char",kind:"meta",value:n,codePoint:NaN}}function ZP(n,e){return{type:"ClassRange",from:n,to:e}}function LA(...n){return{type:"CharacterClass",expressions:Zp(n).filter(Boolean)}}function IQ(n){return{type:"Quantifier",kind:n,greedy:!0}}function PQ(n,e){return{type:"Quantifier",kind:"Range",from:n,to:e,greedy:!0}}function eM(n){return{type:"Group",capturing:!0,expression:n,number:null}}function MQ(n,e){return{type:"Repetition",expression:n,quantifier:e}}function LQ(...n){let e=Zp(n).filter(Boolean);if(e.length===1)return e[0];let t={type:"Disjunction",left:null,right:e.pop()};return e.reduceRight((i,r,s)=>s===0?(i.left=r,i):(i.left={type:"Disjunction",left:null,right:r},i.left),t),t}function e1(...n){let e=LQ(...n);return e.type==="Disjunction"?eM(e):e}function Sl(){return TQ("\\d")}function Cl(n=IQ("+")){return MQ(Sl(),n)}function zP(n){return lo(Array.from(String(n),Mr))}function Xp(n){if(n.type==="Group"&&n.expression.type==="Repetition"){let{expression:e,quantifier:t}=n.expression;return e.type==="Char"&&e.value==="\\d"&&t.kind==="+"&&t.greedy}return!1}function El(n,e){return n&&n.type==="Char"?typeof e>"u"||e instanceof RegExp&&e.test(n.value)||String(e)===n.value:!1}function qP(n){if(n.type==="CharacterClass"&&n.expressions.length===1){let[e]=n.expressions;return e.type==="ClassRange"&&El(e.from,/\d/)&&El(e.to,/\d/)}return!1}function YP(n){return n.type!=="RegExp"&&n.type!=="ClassRange"&&n.type!=="Quantifier"}function _l(n){return typeof n=="string"?$r.default.parse(n.replace(/^([^/])/,"/$1").replace(/([^/])$/,"$1/")):n instanceof RegExp?$r.default.parse(n):n}function RQ(n){return typeof n=="string"?new RegExp(n):new RegExp($r.default.generate(n.body),n.flags)}function kQ(n){return typeof n=="string"?n:n instanceof RegExp?n.toString():$r.default.generate(n)}var OQ=["RegExp","Disjunction","Alternative","Assertion","Char","CharacterClass","ClassRange","Backreference","Group","Repetition","Quantifier"];function OA(n){let{every:e}=n;return e?typeof e=="function"?{"*":e,...n}:OQ.reduce((t,i)=>{let r=n[i],s=r?"pre"in r?r.pre:r:null,o=r&&"post"in r?r.post:null;return t[i]={pre(a){return e.pre(a)!==!1&&s?s(a):!0},post(a){return e.post(a)!==!1&&o?o(a):!0}},t},{}):n}function BQ(n){let e=$r.default.optimize(_l(kQ(n))).getAST();return $r.default.traverse(e,{Group(t){let{parent:i,node:r}=t,{expression:s}=r;r.capturing=!0,(i.type==="RegExp"||s.type!=="Disjunction"&&i.type!=="Repetition"||s.type==="Disjunction"&&i.type==="Disjunction")&&t.replace(t.node.expression)}}),e}function NQ(n,e){return El(n)&&El(e)&&n.value===e.value?e:El(n,/\d/)&&qP(e)&&Number(e.expressions[0].from.value)-Number(n.value)===1?{...e,expressions:[{...e.expressions[0],from:n}]}:qP(n)&&El(e,/\d/)&&Number(e.value)-Number(n.expressions[0].to.value)===1?{...n,expressions:[{...n.expressions[0],to:e}]}:null}function DQ(n){return n.reduce((e,t)=>{let i=e[e.length-1];if(i&&t.type==="Alternative"&&i.type==="Alternative"&&t.expressions.length===i.expressions.length){let r=i.expressions.reduceRight((s,o,a)=>{if(!s)return s;let u=NQ(o,t.expressions[a]);if(u)s.unshift(u);else return null;return s},[]);r&&(t.expressions=r,e.pop())}return e.push(t),e},[])}function RA(n){return Array.from(n.toString(),Number)}function JP(n,e){let t=n+ +!e;return t===0?Sl():t===9?Mr("9"):t>9?null:LA(ZP(Mr(t),Mr("9")))}function FQ(n){if(n===0)return[Cl()];let e=RA(n),t=e.length,i=Cl(PQ(t+1)),r=t-1;if(n/Math.pow(10,r)===e[0])return[lo(JP(e[0],!0),Array.from({length:r},Sl)),i];let o=e.reduce((a,u,l)=>{let c=t-l-1,h=l===0,f=Mr(""),m=e.reduce((y,g,b)=>{if(b<c)y.push(Mr(g));else if(f)if(b>c)y.push(Sl());else if(f=JP(g,h),f)y.push(f);else return[];return y},[]);return m.length&&a.push(m),a},[]).map(a=>lo(a));return o.push(i),o}function wl(n,e,t){if(e<n)return null;let i=Mr(n),r=Mr(e),s=typeof t=="number"&&t>0?Array.from({length:t},()=>Mr(0)):[],o=s.length?a=>lo(s,a):a=>a;return n===e?o(i):n===0&&e===9?o(Sl()):e-n===1?o(LA(i,r)):o(LA(ZP(i,r)))}function HQ(n,e){let t=[],i=n,r=1;do r*=10,i<r&&(t.push([i,Math.min(r-1,e)]),i=r);while(r<=e);return t}function UQ(n,e){let t=n.length;if(t!==e.length||n[0]!==e[0])return null;let i=n[0].toString(),r=0,s=0,o="",a="";for(let u=1;u<t;u++)r=n[u],s=e[u],r===s&&o===""&&a===""?i+=r:(o+=r,a+=s);return[i,parseInt(o,10),parseInt(a,10)]}function kA(n,e,t=0){let i=RA(n),r=i.length;if(n<10&&e<10||n===e){let c=t-r;return[wl(n,e,c)]}let s=RA(e);if(r!==s.length){let c=HQ(n,e);return Zp(c.map(([f,m])=>kA(f,m,t)))}let o=UQ(i,s);if(Array.isArray(o)){let[c,h,f]=o,m=r-c.length,y=kA(h,f,m);return[lo(Array.from(c,Mr),e1(y))]}let a=Array.from({length:r-1}),u=wl(i[0]+1,s[0]-1),l=[...a.map((c,h)=>{let f=r-h-1,m=+(h>0);return lo(i.map((y,g)=>g<f?Mr(y):g>f?wl(0,9):wl(y+m,9)))}),...u?[lo(u,Array.from({length:r-1},()=>Sl()))]:[],...a.map((c,h)=>{let f=r-h-1,m=+(h>0);return lo(s.map((y,g)=>g<f?Mr(y):g>f?wl(0,9):wl(0,y-m)))})];return DQ(l)}function $P(n,e=1/0){if(n===1/0)return Cl();let t=e===1/0?FQ(n):kA(n,e);return e1(t)}function jQ(n,e,t,i){let r={...i,allowHigherVersions:!0},s=u=>KP(u,n,r),o=u=>KP(e,u,r),a=n&&e?u=>s(u)&&o(u):n?s:e?o:()=>!0;return t.filter(a)}function GQ(n,e,t=WP){let i=[],r="",s=!1;return t.forEach(o=>{let a=n.get(o.family);if(!a)return;let{version:u,minVersion:l,maxVersion:c}=o;u&&(l=u,c=u);let h=jQ(l,c,a,e);h.length&&(r===o.family&&s&&(u=void 0,l=void 0,c=void 0,h=a,i.pop()),i.push({...o,version:u,minVersion:l,maxVersion:c,requestVersions:a,matchedVersions:h})),s=!u&&!l&&!c,r=o.family}),i}function WQ(n){let e=n.map(({regexAst:i})=>eM(i.body)),t=BQ(xQ(e1(e)));return RQ(t)}function VQ(n){let e=_l(n),t=0;return $r.default.traverse(e,{Group(i){Xp(i.node)&&t++}}),t}function KQ(n,e,t){let i=_l(n),r=typeof t=="number"&&t<e.length?e.slice(0,t):e.slice();return $r.default.traverse(i,OA({every(){return!!r.length},Group(s){return Xp(s.node)&&r.length?(i===s.node?i=r.shift():s.replace(r.shift()),!1):!0}})),i}function tM(n,e){let t=_l(n),i=Math.min(VQ(t),e||1/0),r=[],s=0,o=!1;return $r.default.traverse(t,OA({every:{pre({node:a,parent:u}){return a===t?!0:YP(a)?(u===t&&(o=!1),s<i):!1},post({node:a,parent:u}){a!==t&&u===t&&YP(a)&&(o||s>0&&s<i)&&r.push(a)}},Group(a){return Xp(a.node)&&s<i?(o=!0,s++,!1):!0}})),r.length===1&&!Xp(r[0])?tM(r[0],i):r}function zQ(n,e){let{ignoreMinor:t,ignorePatch:i,allowHigherVersions:r}=e,s=n[0]===1/0?0:t?1:i?2:3;if(r){let a=[],u=!0,l=0,c=0,h=f=>(m,y)=>y>=s?Cl():(c=Array.isArray(m)?m[0]:m,y<f?zP(c):y>f?Cl():$P(c+l));for(let f=s-1;f>=0;f--)u&&!n[f]||(u=!1,a.push(n.map(h(f))),l=1);return a}return[n.map((a,u)=>u>=s?Cl():Array.isArray(a)?$P(a[0],a[1]):zP(a))]}function qQ(n,e,t){let{allowHigherVersions:i}=t,r=_l(n),s=i&&e.length?[e[0]]:e,o=s.reduce((l,c)=>Math.max(l,vQ(c,t)),1),a=tM(r,o),u=e1(...s.map(l=>zQ(l,t).map(c=>KQ(lo(XP(a)),c,o))));return $r.default.traverse(r,OA({every(l){return a.length?(l.node===a[0]&&(a.length===1?l.replace(u):l.remove(),a.shift()),!0):!1}})),r}function YQ(n,e){return n.map(({regex:t,version:i,maxVersion:r,matchedVersions:s,...o})=>{let a=_l(t);return i||(a=qQ(a,_Q(s),{...e,allowHigherVersions:!r&&e.allowHigherVersions})),{regex:null,sourceRegex:t,regexAst:a,version:i,maxVersion:r,matchedVersions:s,...o}})}var JQ={ignoreMinor:!1,ignorePatch:!0,allowZeroSubversions:!1,allowHigherVersions:!1};function $Q(n={}){let e={...JQ,...n},t=EQ(e),i=SQ(t),r=GQ(i,e);return YQ(r,e)}function iM(n={}){return WQ($Q(n))}var ja=class{constructor(e){this.hasEventListener=!1;this.isHacked=!1;this.properties=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,t1.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,t1.launch)(),await _T(e.detectInspectInitDelay??100)}static isCurrentBrowserSupported(e){if(!e.enforceSupportedBrowsers)return!0;let t=[];return(e.supportedBrowsers??[]).forEach(r=>{t.push("last 1 "+r+" version")}),iM({browsers:t,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.properties?.enableObfuscation){this.wrapper=gt(document,"#iframe-wrapper"),this.securityContainer=ge(document,"#container-view-security");var e=this;this.mutationObserver=new MutationObserver(function(t){t.forEach(function(i){rn.default.log(i.type),e.isHacked=!0})})}}async stop(){if(rn.default.log("Protection module stop"),this.properties?.enableObfuscation&&this.mutationObserver.disconnect(),this.properties?.disableKeys){Se(this.navigator.mainElement,"keydown",this.disableSave),Se(this.navigator.headerMenu,"keydown",this.disableSave);for(let e of this.navigator.iframes)Se(e.contentDocument,"keydown",this.disableSave),Se(e.contentWindow,"keydown",this.disableSave);Se(window,"keydown",this.disableSave),Se(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){Se(this.navigator.mainElement,"copy",this.preventCopy),Se(this.navigator.headerMenu,"copy",this.preventCopy);for(let e of this.navigator.iframes)Se(e.contentDocument,"copy",this.preventCopy),Se(e.contentWindow,"copy",this.preventCopy);Se(window,"copy",this.preventCopy),Se(document,"copy",this.preventCopy),Se(this.navigator.mainElement,"cut",this.preventCopy),Se(this.navigator.headerMenu,"cut",this.preventCopy);for(let e of this.navigator.iframes)Se(e.contentDocument,"cut",this.preventCopy),Se(e.contentWindow,"cut",this.preventCopy);Se(window,"cut",this.preventCopy),Se(document,"cut",this.preventCopy),Se(this.navigator.mainElement,"keydown",this.preventCopyKey),Se(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let e of this.navigator.iframes)Se(e.contentDocument,"keydown",this.preventCopyKey),Se(e.contentWindow,"keydown",this.preventCopyKey);Se(window,"keydown",this.preventCopyKey),Se(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){Se(this.navigator.mainElement,"copy",this.restrictCopy),Se(this.navigator.headerMenu,"copy",this.restrictCopy);for(let e of this.navigator.iframes)Se(e.contentDocument,"copy",this.restrictCopy),Se(e.contentWindow,"copy",this.restrictCopy);Se(window,"copy",this.restrictCopy),Se(document,"copy",this.restrictCopy),Se(this.navigator.mainElement,"cut",this.restrictCopy),Se(this.navigator.headerMenu,"cut",this.restrictCopy);for(let e of this.navigator.iframes)Se(e.contentDocument,"cut",this.restrictCopy),Se(e.contentWindow,"cut",this.restrictCopy);Se(window,"cut",this.restrictCopy),Se(document,"cut",this.restrictCopy),Se(this.navigator.mainElement,"keydown",this.restrictCopyKey),Se(this.navigator.headerMenu,"keydown",this.restrictCopyKey);for(let e of this.navigator.iframes)Se(e.contentDocument,"keydown",this.restrictCopyKey),Se(e.contentWindow,"keydown",this.restrictCopyKey);Se(window,"keydown",this.restrictCopyKey),Se(document,"keydown",this.restrictCopyKey)}if(this.properties?.disablePrint){Se(this.navigator.mainElement,"beforeprint",this.beforePrint.bind(this)),Se(this.navigator.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let e of this.navigator.iframes)Se(e.contentDocument,"beforeprint",this.beforePrint),Se(e.contentWindow,"beforeprint",this.beforePrint);Se(window,"beforeprint",this.beforePrint),Se(document,"beforeprint",this.beforePrint),Se(this.navigator.mainElement,"afterprint",this.afterPrint.bind(this)),Se(this.navigator.headerMenu,"afterprint",this.afterPrint.bind(this));for(let e of this.navigator.iframes)Se(e.contentDocument,"afterprint",this.afterPrint.bind(this)),Se(e.contentWindow,"afterprint",this.afterPrint.bind(this));Se(window,"afterprint",this.afterPrint.bind(this)),Se(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){Se(this.navigator.mainElement,"contextmenu",this.disableContext),Se(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let e of this.navigator.iframes)Se(e.contentDocument,"contextmenu",this.disableContext),Se(e.contentWindow,"contextmenu",this.disableContext);Se(window,"contextmenu",this.disableContext),Se(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),Se(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.navigator.iframes)if(e.contentDocument){let t=qs(e.contentDocument,"body");this.rects=this.findRects(t),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){te(this.navigator.mainElement,"keydown",this.disableSave),te(this.navigator.headerMenu,"keydown",this.disableSave);for(let e of this.navigator.iframes)te(e,"keydown",this.disableSave),te(e.ownerDocument,"keydown",this.disableSave),te(e.contentDocument,"keydown",this.disableSave),te(e.contentWindow,"keydown",this.disableSave),te(e.contentWindow?.document,"keydown",this.disableSave);te(window,"keydown",this.disableSave),te(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){te(this.navigator.mainElement,"copy",this.preventCopy),te(this.navigator.headerMenu,"copy",this.preventCopy);for(let e of this.navigator.iframes)te(e,"copy",this.preventCopy),te(e.ownerDocument,"copy",this.preventCopy),te(e.contentDocument,"copy",this.preventCopy),te(e.contentWindow,"copy",this.preventCopy),te(e.contentWindow?.document,"copy",this.preventCopy);te(window,"copy",this.preventCopy),te(document,"copy",this.preventCopy),te(this.navigator.mainElement,"cut",this.preventCopy),te(this.navigator.headerMenu,"cut",this.preventCopy);for(let e of this.navigator.iframes)te(e,"cut",this.preventCopy),te(e.ownerDocument,"cut",this.preventCopy),te(e.contentDocument,"cut",this.preventCopy),te(e.contentWindow,"cut",this.preventCopy),te(e.contentWindow?.document,"cut",this.preventCopy);te(window,"cut",this.preventCopy),te(document,"cut",this.preventCopy),te(this.navigator.mainElement,"keydown",this.preventCopyKey),te(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let e of this.navigator.iframes)te(e,"keydown",this.preventCopyKey),te(e.ownerDocument,"keydown",this.preventCopyKey),te(e.contentDocument,"keydown",this.preventCopyKey),te(e.contentWindow,"keydown",this.preventCopyKey),te(e.contentWindow?.document,"keydown",this.preventCopyKey);te(window,"keydown",this.preventCopyKey),te(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){te(this.navigator.mainElement,"copy",this.restrictCopy.bind(this)),te(this.navigator.headerMenu,"copy",this.restrictCopy.bind(this));for(let e of this.navigator.iframes)te(e,"copy",this.restrictCopy),te(e.ownerDocument,"copy",this.restrictCopy.bind(this)),te(e.contentDocument,"copy",this.restrictCopy.bind(this)),te(e.contentWindow,"copy",this.restrictCopy.bind(this)),te(e.contentWindow?.document,"copy",this.restrictCopy.bind(this));te(window,"copy",this.restrictCopy.bind(this)),te(document,"copy",this.restrictCopy.bind(this)),te(this.navigator.mainElement,"cut",this.restrictCopy.bind(this)),te(this.navigator.headerMenu,"cut",this.restrictCopy.bind(this));for(let e of this.navigator.iframes)te(e,"cut",this.restrictCopy.bind(this)),te(e.ownerDocument,"cut",this.restrictCopy.bind(this)),te(e.contentDocument,"cut",this.restrictCopy.bind(this)),te(e.contentWindow,"cut",this.restrictCopy.bind(this)),te(e.contentWindow?.document,"cut",this.restrictCopy.bind(this));te(window,"cut",this.restrictCopy.bind(this)),te(document,"cut",this.restrictCopy.bind(this)),te(this.navigator.mainElement,"keydown",this.restrictCopyKey.bind(this)),te(this.navigator.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let e of this.navigator.iframes)te(e,"keydown",this.restrictCopyKey.bind(this)),te(e.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),te(e.contentDocument,"keydown",this.restrictCopyKey.bind(this)),te(e.contentWindow,"keydown",this.restrictCopyKey.bind(this)),te(e.contentWindow?.document,"keydown",this.restrictCopyKey.bind(this));te(window,"keydown",this.restrictCopyKey.bind(this)),te(document,"keydown",this.restrictCopyKey.bind(this))}if(this.properties?.disablePrint){te(this.navigator.mainElement,"beforeprint",this.beforePrint),te(this.navigator.headerMenu,"beforeprint",this.beforePrint);for(let e of this.navigator.iframes)te(e,"beforeprint",this.beforePrint.bind(this)),te(e.ownerDocument,"beforeprint",this.beforePrint.bind(this)),te(e.contentDocument,"beforeprint",this.beforePrint.bind(this)),te(e.contentWindow,"beforeprint",this.beforePrint.bind(this)),te(e.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));te(window,"beforeprint",this.beforePrint.bind(this)),te(document,"beforeprint",this.beforePrint.bind(this)),te(this.navigator.mainElement,"afterprint",this.afterPrint),te(this.navigator.headerMenu,"afterprint",this.afterPrint);for(let e of this.navigator.iframes)te(e,"afterprint",this.afterPrint.bind(this)),te(e.ownerDocument,"afterprint",this.afterPrint.bind(this)),te(e.contentDocument,"afterprint",this.afterPrint.bind(this)),te(e.contentWindow,"afterprint",this.afterPrint.bind(this)),te(e.contentWindow?.document,"afterprint",this.afterPrint.bind(this));te(window,"afterprint",this.afterPrint.bind(this)),te(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){te(this.navigator.mainElement,"contextmenu",this.disableContext),te(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let e of this.navigator.iframes)te(e,"contextmenu",this.disableContext),te(e.ownerDocument,"contextmenu",this.disableContext),te(e.contentDocument,"contextmenu",this.disableContext),te(e.contentWindow,"contextmenu",this.disableContext),te(e.contentWindow?.document,"contextmenu",this.disableContext);te(window,"contextmenu",this.disableContext),te(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=qs(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,te(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,BA.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 rn.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;rn.default.log("copy action initiated");let t=this.navigator.iframes[0].contentWindow;if(t){let r=function(o){let a={className:l=>ar.indexOf(l)<0,idName:l=>ar.indexOf(l)<0},u=i.navigator.iframes[0].contentDocument;if(u)return Vi(o,u,a)},i=this,s=As(t,r);if(s===void 0){let o=this.navigator.iframes[0].contentDocument;s=this.navigator.annotationModule?.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.navigator.iframes[0].contentWindow;if(t){let r=function(o){let a={className:l=>ar.indexOf(l)<0,idName:l=>ar.indexOf(l)<0},u=i.navigator.iframes[0].contentDocument;if(u)return Vi(o,u,a)},i=this,s=As(t,r);if(s===void 0){let o=this.navigator.iframes[0].contentDocument;s=this.navigator.annotationModule?.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 rn.default.log("before print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.display="none",this.navigator.mainElement.style.display="none"),e.stopPropagation(),e.preventDefault(),!1}afterPrint(e){return rn.default.log("after print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.removeProperty("display"),this.navigator.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.navigator.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.navigator.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,BA.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){rn.default.log("error "+i),rn.default.log(t),rn.default.log(t.node),rn.default.log("scrambledTextContent "+t.scrambledTextContent),rn.default.log("textContent "+t.textContent),rn.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){rn.default.log("measureTextNode "+t),rn.default.log("measureTextNode "+e),rn.default.log(e.textContent)}}isBeingHacked(e){return e.style.animation||e.style.transition||e.style.position||e.hasAttribute("style")?(rn.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,h=e.left>i+window.innerWidth;return u||l||c||h}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(" ")}};_();ui();yn();var uM=Qe(rM());_();var i1=n=>n.replace(/\n/g," ").replace(/\s\s+/g," "),QQ=n=>i1(n).trim(),oM=/[\\^$.*+?()[\]{}|]/g,XQ=RegExp(oM.source);function sM(n){return n&&XQ.test(n)?n.replace(oM,"\\$&"):n||""}var n1=0,ZQ=()=>()=>Number.isSafeInteger(++n1)?n1:n1=1,aM=()=>{n1=0},eX=ZQ(),tX=n=>e=>{try{return Vi(e,n,Vo)}catch(t){return console.error("uniqueCssSelector:",t),""}};async function Jo(n,e,t,i,r=!1){if(!e)return[];let s=e.body?.textContent;if(!s)return[];if(n=QQ(n),!n.length)return[];let o=e.createNodeIterator(e.body,NodeFilter.SHOW_TEXT,{acceptNode:m=>NodeFilter.FILTER_ACCEPT}),a=new RegExp(sM(n).replace(/ /g,"\\s+"),"gim");r&&(a=new RegExp("\\b"+sM(n).replace(/ /g,"\\s+")+"\\b","gim"));let u=[],l=100,c=30,h=0,f;for(;f=a.exec(s);){let m=Math.max(0,f.index-l),y=Math.min(l,f.index),g=i1(s.substr(m,y));g=g.substr(g.length-c),m=a.lastIndex,y=Math.min(l,s.length-m);let b=i1(s.substr(m,y)).substr(0,c),A=new Range,v=f.index;for(;h<=v;){let C=o.nextNode();C&&C.nodeValue&&(h+=C.nodeValue.length)}let E=o.referenceNode.nodeValue?o.referenceNode.nodeValue?.length-(h-v):0;for(A.setStart(o.referenceNode,E),v=f.index+f[0].length;h<=v;){let T=o.nextNode()?.nodeValue;T&&(h+=T.length)}E=o.referenceNode.nodeValue?o.referenceNode.nodeValue?.length-(h-v):0,A.setEnd(o.referenceNode,E),e.getCssSelector||(e.getCssSelector=tX(e));let S=to(A,e.getCssSelector);S&&u.push({textMatch:i1(f[0]),textBefore:g,textAfter:b,rangeInfo:S,href:t,title:i,uuid:eX().toString()})}return u}var lM=Qe(Qt()),iX="#fff059",nX="#ff6600",xl=class{constructor(e,t,i,r,s){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.headerMenu=s,this.publication=e,this.properties={...t,color:t.color??iX,current:t.current??nX},this.api=r,this.highlighter=i}static async create(e){let t=new this(e.publication,e,e.highlighter,e.api,e.headerMenu);return await t.start(),t}async stop(){lM.default.log("Search module stop"),Se(this.searchInput,"keypress",this.handleSearch.bind(this)),Se(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.headerMenu){this.searchInput=ge(this.headerMenu,"#searchInput"),te(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=ge(this.headerMenu,"#searchGo"),te(this.searchGo,"click",this.handleSearch.bind(this));var e=ge(this.headerMenu,"#menu-button-search");e&&e.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("search"):this.navigator.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.navigator.currentChapterLink.href,s=this.publication.getSpineItem(r);if(this.headerMenu)var o=ge(document,"#searchResultChapter");t.currentChapterSearchResult=[],t.currentSearchHighlights=[];var a=[];await this.searchAndPaintChapter(i,e,async l=>{a=l,u(1),this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)});async function u(l){o.innerHTML="";var c;if(c=t.paginate(a,l,10),c.total===0){let h=document.createElement("a");h.className="collection-item",h.innerHTML="nothing found",o.appendChild(h)}else{for(let g=0;g<c.data.length;g++){let b=document.createElement("a"),A=c.data[g];b.className="collection-item",b.href=s?.Href??"",b.innerHTML="..."+A.textBefore+"<mark>"+A.textMatch+"</mark>"+A.textAfter+"...",te(b,"click",v=>{v.preventDefault(),v.stopPropagation(),t.jumpToMark(g+l*10-10)}),o.appendChild(b)}let h=document.createElement("div");h.style.textAlign="center",h.style.marginTop="10px";let f=document.createElement("ul");f.className="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",te(m,"click",b=>{b.preventDefault(),b.stopPropagation(),u(g)})}f.appendChild(m);for(let g=1;g<=c.total_pages;g++){let b,A=document.createElement("li");A.className="waves-effect",g===c.page&&(A.className="active",b=A),A.innerHTML='<a href="#!">'+g+"</a>",te(A,"click",v=>{v.preventDefault(),v.stopPropagation(),b&&(b.className="waves-effect"),A.className="active",b=A,u(g)}),f.appendChild(A)}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",te(y,"click",b=>{b.preventDefault(),b.stopPropagation(),u(g)})}f.appendChild(y),h.appendChild(f),o.appendChild(h)}}}async searchAndPaintChapter(e,t=0,i){this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate();let r=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),s=this.publication.getTOCItem(r);s===null&&(s=this.publication.readingOrder[this.navigator.currentResource()??0]);let o=[];this.highlighter?.destroyHighlights(1),this.navigator.rights.enableSearch&&this.drawSearch();let a=0;if(s){let u=this.navigator.iframes[0].contentDocument;u&&s&&Jo(e,u,s.Href,s.Title).then(l=>{l.forEach(c=>{let h={rangeInfo:c.rangeInfo};setTimeout(()=>{let f;a===t?(f=this.createSearchHighlight(h,this.properties?.current),this.jumpToMark(t)):f=this.createSearchHighlight(h,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;Xt.isHexColor(i)&&(i=Xt.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_"+uM.SHA256.hash(s);var r=!1;let u={color:i||Fa,id:a,pointerInteraction:r,selectionInfo:e,marker:0,type:1},l=this.highlighter?.createHighlightDom(this.navigator.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)}async search(e,t){return this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],aM(),await this.searchAndPaintChapter(e,0,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.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.navigator.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"},h=this.publication.positionsByHref(c.href);h?.length>0&&(c.locations.totalProgression=h[0].locations.totalProgression,c.locations.position=h[0].locations.position),this.navigator.navigate(c),setTimeout(()=>{this.searchAndPaintChapter(s.textMatch,r,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)})},300)}}async goToSearchIndex(e,t,i){var r=t,s;let o=this.navigator.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"},h=this.publication.positionsByHref(c.href);h?.length>0&&(c.locations.totalProgression=h[0].locations.totalProgression,c.locations.position=h[0].locations.position),this.navigator.navigate(c),setTimeout(()=>{this.searchAndPaintChapter(s.textMatch,r,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)})},300)}}async handleSearchBook(){var e=this,t=this.searchInput.value;if(e.headerMenu)var i=ge(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 A=document.createElement("a");A.className="collection-item";var v=e.publication.getAbsoluteHref(b.href);A.innerHTML="..."+b.textBefore+"<mark>"+b.textMatch+"</mark>"+b.textAfter+"...",te(A,"click",E=>{E.preventDefault(),E.stopPropagation();let C=u.filter(M=>M.href===b.href).findIndex(M=>M===b);if(e.navigator.currentChapterLink.href===v)e.jumpToMark(C);else{let I={href:v,locations:{progression:0},title:"title"},L=e.publication.positionsByHref(I.href);L?.length>0&&(I.locations.totalProgression=L[0].locations.totalProgression,I.locations.position=L[0].locations.position),e.navigator.navigate(I),setTimeout(()=>{e.handleSearchChapter(C)},300)}}),g.appendChild(A)})});let c=document.createElement("div");c.style.textAlign="center",c.style.marginTop="10px";let h=document.createElement("ul");h.className="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",te(f,"click",g=>{g.preventDefault(),g.stopPropagation(),r(y)})}h.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="active",g=b),b.innerHTML='<a href="#!">'+y+"</a>",te(b,"click",A=>{A.preventDefault(),A.stopPropagation(),g&&(g.className="waves-effect"),b.className="active",g=b,r(y)}),h.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",te(m,"click",g=>{g.preventDefault(),g.stopPropagation(),r(y)})}h.appendChild(m),c.appendChild(h),i.appendChild(c)}}function s(o,a){let u=new Map;return o.forEach(l=>{let c=a(l),h=u.get(c);h?h.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);this.navigator.api?.getContent?await this.navigator.api?.getContent(o).then(a=>{let l=new DOMParser().parseFromString(a,"application/xhtml+xml");s&&Jo(e,l,s.Href,s.Title).then(c=>{c.forEach(h=>{t.push(h),this.bookSearchResult.push(h)})})}):await fetch(o,this.navigator.requestConfig).then(a=>a.text()).then(async a=>{let l=new DOMParser().parseFromString(this.navigator.requestConfig?.encoded?this.decodeBase64(a):a,"application/xhtml+xml");s&&Jo(e,l,s.Href,s.Title).then(c=>{c.forEach(h=>{t.push(h),this.bookSearchResult.push(h)})})})}if(i===this.publication.readingOrder.length-1)return t}}decodeBase64(e){let t=atob(e),i=t.length,r=new Uint8Array(i);for(let o=0;o<i;o++)r[o]=t.charCodeAt(o);return new TextDecoder().decode(r)}async searchChapter(e){let t=[],i=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),r=this.publication.getTOCItem(i);if(r===null&&(r=this.publication.readingOrder[this.navigator.currentResource()??0]),r){let s=this.publication.getAbsoluteHref(r.Href);this.navigator.api?.getContent?await this.navigator.api?.getContent(s).then(o=>{let u=new DOMParser().parseFromString(o,"application/xhtml+xml");r&&Jo(e,u,r.Href,r.Title).then(l=>{l.forEach(c=>{t.push(c)})})}):await fetch(s,this.navigator.requestConfig).then(o=>o.text()).then(async o=>{let u=new DOMParser().parseFromString(this.navigator.requestConfig?.encoded?this.decodeBase64(o):o,"application/xhtml+xml");r&&Jo(e,u,r.Href,r.Title).then(l=>{l.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;Xt.isHexColor(s)&&(s=Xt.hexToRgbChannels(s)),r.color=s});var i=this.properties?.current;Xt.isHexColor(i)&&(i=Xt.hexToRgbChannels(i)),t.highlight.color=i,this.highlighter?.setAndResetSearchHighlight(t.highlight,this.currentSearchHighlights),this.navigator.view?.goToCssSelector(t.rangeInfo.startContainerElementCssSelector),this.navigator.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}}};_();ui();yn();var Fn=Qe(Qt()),Ci=class Ci{};Ci.COLOR_REF="color",Ci.AUTO_SCROLL_REF="autoscroll",Ci.RATE_REF="rate",Ci.PITCH_REF="pitch",Ci.VOLUME_REF="volume",Ci.VOICE_REF="voice",Ci.COLOR_KEY="tts-"+Ci.COLOR_REF,Ci.AUTO_SCROLL_KEY="tts-"+Ci.AUTO_SCROLL_REF,Ci.RATE_KEY="tts-"+Ci.RATE_REF,Ci.PITCH_KEY="tts-"+Ci.PITCH_REF,Ci.VOLUME_KEY="tts-"+Ci.VOLUME_REF,Ci.VOICE_KEY="tts-"+Ci.VOICE_REF;var $e=Ci,r1=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,Fn.default.log(t.rate)),i?.pitch&&(t.pitch=i.pitch,Fn.default.log(t.pitch)),i?.volume&&(t.volume=i.volume,Fn.default.log(t.volume)),i?.color&&(t.color=i.color,Fn.default.log(t.color)),i?.autoScroll&&(t.autoScroll=i.autoScroll,Fn.default.log(t.autoScroll)),i?.voice&&(t.voice=i.voice,Fn.default.log(t.voice))}return t.initializeSelections(),t}stop(){Fn.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty($e.AUTO_SCROLL_KEY)!=null?this.getProperty($e.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty($e.RATE_KEY)!=null?this.getProperty($e.RATE_KEY).value:this.rate,this.pitch=this.getProperty($e.PITCH_KEY)!=null?this.getProperty($e.PITCH_KEY).value:this.pitch,this.volume=this.getProperty($e.VOLUME_KEY)!=null?this.getProperty($e.VOLUME_KEY).value:this.volume,this.color=this.getProperty($e.COLOR_KEY)!=null?this.getProperty($e.COLOR_KEY).value:this.color,this.voice=this.getProperty($e.VOICE_REF)!=null?this.getProperty($e.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=ge(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechRate=ge(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=ge(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=ge(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=ge(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),te(ge(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($e.RATE_REF)?.value,pitch:this.userProperties.getByRef($e.PITCH_REF)?.value,volume:this.userProperties.getByRef($e.VOLUME_REF)?.value,voice:this.userProperties.getByRef($e.VOLUME_REF)?.value,color:this.userProperties.getByRef($e.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef($e.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(e),this.api?.updateSettings&&this.api?.updateSettings(e).then(async t=>{Fn.default.log("api updated tts settings",t)})}getTTSSettings(){var e=new ds;return e.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,$e.AUTO_SCROLL_REF,$e.AUTO_SCROLL_KEY),e.addIncremental(this.rate,.1,10,.1,"",$e.RATE_REF,$e.RATE_KEY),e.addIncremental(this.pitch,.1,2,.1,"",$e.PITCH_REF,$e.PITCH_KEY),e.addIncremental(this.volume,.1,1,.1,"",$e.VOLUME_REF,$e.VOLUME_KEY),e.addStringable(this.color,$e.COLOR_REF,$e.COLOR_KEY),e.addJSONable(JSON.stringify(this.voice),$e.VOICE_REF,$e.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){Fn.default.log("rate "+this.rate),this.rate=e.rate;let t=this.userProperties.getByRef($e.RATE_REF);t&&(t.value=this.rate,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.pitch){Fn.default.log("pitch "+this.pitch),this.pitch=e.pitch;let t=this.userProperties.getByRef($e.PITCH_REF);t&&(t.value=this.pitch,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.volume){Fn.default.log("volume "+this.volume),this.volume=e.volume;let t=this.userProperties.getByRef($e.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($e.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){Fn.default.log("autoScroll "+this.autoScroll),this.autoScroll=e.autoScroll;let t=this.userProperties.getByRef($e.AUTO_SCROLL_REF);t&&(t.value=this.autoScroll,this.saveProperty(t)),this.settingsChangeCallback()}if(e.voice){Fn.default.log("voice "+this.voice),this.voice=e.voice;let t=this.userProperties.getByRef($e.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($e.RATE_REF).increment();let t=this.userProperties.getByRef($e.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef($e.PITCH_REF).increment();let t=this.userProperties.getByRef($e.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef($e.VOLUME_REF).increment();let t=this.userProperties.getByRef($e.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}decrease(e){if(e==="rate"){this.userProperties.getByRef($e.RATE_REF).decrement();let t=this.userProperties.getByRef($e.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef($e.PITCH_REF).decrement();let t=this.userProperties.getByRef($e.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef($e.VOLUME_REF).decrement();let t=this.userProperties.getByRef($e.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}};_();yn();ui();DA();var l1=Qe(eo());_();var co=class co{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)<co.TAP_TOLERANCE&&Math.abs(c)<co.TAP_TOLERANCE){if(i){t=null,i=null;return}if(s.timeStamp-t.timeStamp>co.LONG_PRESS_MS){t=null,i=null;return}t=null,i=s;return}if(i=null,s.timeStamp-t.timeStamp>co.SLOW_SWIPE_MS){t=null;return}let h=(o.clientY-a.clientY)/(o.clientX-a.clientX);if(Math.abs(h)>.5){t=null;return}l<0?r.onBackwardSwipe(s):r.onForwardSwipe(s),t=null},!1))};this.navigator=e}};co.TAP_TOLERANCE=10,co.LONG_PRESS_MS=500,co.SLOW_SWIPE_MS=500;var Od=co;_();var Bd=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)})}};_();var dM=Qe(eo()),Nd=class{constructor(e){this.enforceSampleRead=(0,dM.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 h;function f(y){y=y||window.event;let g=y.target||y.srcElement,b=y.touches[0].clientY;if(!(b>h)){if(b<h&&!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 h=b,!1}function m(y){return y=y||window.event,h=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}};_();ui();yn();var Dd=Qe(Qt()),Tl=class{static async create(e){let t=new this(e.publication,e,e.headerMenu);return await t.start(),t}constructor(e,t,i){this.headerMenu=i,this.publication=e,this.properties=t}async stop(){Dd.default.log("Page Break module stop")}async start(){this.headerMenu&&(this.goToPageView=ge(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=ge(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=ge(this.headerMenu,"#goToPageNumberButton")),te(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),te(this.goToPageNumberButton,"click",this.goToPageNumber.bind(this)),this.goToPageView&&(this.publication.pageList?.length||this.goToPageView.parentElement?.removeChild(this.goToPageView)),setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("pagebreak"):this.navigator.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.TypeLink,title:i.Title};this.navigator.goTo(s)}}}async handleResize(){await this.navigator.highlighter?.destroyHighlights(3),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{let e=this.navigator.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.navigator.iframes[0].contentDocument;return o?Vi(s,o,Vo):""}catch(o){return Dd.default.log("uniqueCssSelector:"),Dd.default.error(o),""}}if(t)for(let s=0;s<t.length;s++){let o=t[s];Dd.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.navigator.iframes[0].contentDocument;if(l){let c=this.navigator.highlighter?.dom(l.body).getWindow().document.createRange(),h=this.navigator.highlighter?.dom(l.body).getSelection();if(h.removeAllRanges(),c.selectNodeContents(o),h.addRange(c),!h.isCollapsed){let f=to(c,r);h.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_"+ys.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};li.push(a);let u=this.navigator.highlighter?.createHighlightDom(this.navigator.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}}};_();ui();yn();var fM=Qe(Sy());var pM=Qe(eo());var Tt=Qe(Qt()),Il=class{constructor(e,t,i,r,s,o){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,pM.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=o,this.rights=t,this.highlighter=i,this.properties=r,this.api=s}initialize(e){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=e,this.clean=(0,fM.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),this.wrapper=gt(document,"#iframe-wrapper"),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,te(document,"wheel",this.wheel.bind(this)),te(this.body,"wheel",this.wheel.bind(this)),te(document,"keydown",this.wheel.bind(this)),te(this.navigator.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),te(this.body,"mousedown",this.clickStart.bind(this)),te(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.navigator.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(Tt.default.log(r),this.voices=[],r.forEach(o=>{o.localService===!0&&this.voices.push(o)}),Tt.default.log(this.voices),e&&this.headerMenu){var s=ge(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.api?.stopped&&this.api?.stopped(),this.navigator.emit("readaloud.stopped","stopped")),this.userScrolled=!1,this.speaking=!1,setTimeout(()=>{window.speechSynthesis.cancel()},0),this._ttsQueueItemHighlightsWord&&(this.navigator.highlighter?.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0)}async speak(e,t,i){t||this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate(),this.api?.started&&this.api?.started(),this.navigator.emit("readaloud.started","started");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.navigator.iframes[0].contentDocument;if(m){let y=this.highlighter.dom(m.body).getSelection();if(y.isCollapsed){let g=r.navigator.iframes[0].contentDocument,b=r.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(g);b?.range&&y.addRange(b.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=Ga(o,a),b=Ga(o,u);var l;if(g&&e&&e.cleanText){let A=Wa(g),v=e.rangeInfo.startOffset,E=e.cleanText;if(b&&a+1===u){let C=Wa(b);v=(A+" "+C).indexOf(e.cleanText),E=A.slice(v,A.length),l=e.cleanText.replace(E,"").trim()}else if(u>a){let C="";for(let T=a+1;T<u;T++){let M=Ga(o,T);if(M){let I=Wa(M);C+=I,l=e.cleanText.replace(I,"")}}if(b){let T=Wa(b);C+=" "+T}v=(A+" "+C).indexOf(e.cleanText),E=A.slice(v,A.length),l=l.replace(E,"").trim()}s=new SpeechSynthesisUtterance(E),s.rate=this.tts.rate,s.pitch=this.tts.pitch,s.volume=this.tts.volume,this.setVoice(this,s),Tt.default.log(e),Tt.default.log(E,e.range?.commonAncestorContainer.textContent),Tt.default.log(g),Tt.default.log(g.item.textNodes),Tt.default.log(v),Tt.default.log(g.item.combinedText);let S=g.item.textNodes.filter(C=>C===e.range?.commonAncestorContainer)[0];Tt.default.log(S),s.onboundary=C=>{this.updateTTSInfo(g,C.charIndex,C.charLength,v,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 h=Ga(o,a);if(h){let f=Wa(h);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(h,m.charIndex,m.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s)},0),c()}}else{let h=Ga(o,a);h&&(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(h,f.charIndex,f.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s)},0),c()),a>u&&(Tt.default.log("utterance ended"),r.highlighter.doneSpeaking(),r.api?.finished(),r.navigator.emit("readaloud.finished","finished"))}else Tt.default.log("utterance ended"),r.highlighter.doneSpeaking(),r.api?.finished(),r.navigator.emit("readaloud.finished","finished")}}setTimeout(()=>{window.speechSynthesis.speak(s),t||this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)},0),c(),i()}setVoice(e,t){Tt.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)),Tt.default.log("initialVoiceHasHyphen",i),Tt.default.log("voices",this.voices);let r;i?(r=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(l=>{var c=l.lang.replace("_","-");return c===this.tts.voice.lang&&l.name===this.tts.voice.name})[0]:void 0,r===void 0&&(r=this.tts.voice&&this.tts.voice.lang?this.voices.filter(l=>l.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(r=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(l=>l.lang===this.tts.voice.lang&&l.name===this.tts.voice.name)[0]:void 0,r===void 0&&(r=this.tts.voice&&this.tts.voice.lang?this.voices.filter(l=>l.lang===this.tts.voice.lang)[0]:void 0)),Tt.default.log("initialVoice",r);let s=e.navigator.publication.Metadata.Language[0].indexOf("-")!==-1;Tt.default.log("publicationVoiceHasHyphen",s);let o;s?o=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(l=>{var c=l.lang.replace("_","-");return c.startsWith(e.navigator.publication.Metadata.Language[0])||c.endsWith(e.navigator.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:o=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(l=>l.lang.startsWith(e.navigator.publication.Metadata.Language[0])||l.lang.endsWith(e.navigator.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Tt.default.log("publicationVoice",o);let a=navigator.language.indexOf("-")!==-1;Tt.default.log("defaultVoiceHasHyphen",a);let u;a?u=this.voices.filter(l=>l.lang.replace("_","-")===navigator.language&&l.localService)[0]:u=this.voices.filter(l=>l.lang===navigator.language&&l.localService)[0],u===void 0&&(u=this.voices.filter(l=>l.lang.includes(navigator.language)&&l.localService)[0]),Tt.default.log("defaultVoice",u),r?(Tt.default.log("initialVoice"),t.voice=r):o?(Tt.default.log("publicationVoice"),t.voice=o):u&&(Tt.default.log("defaultVoice"),t.voice=u),t.voice!==void 0&&t.voice!==null&&(t.lang=t.voice.lang,Tt.default.log("utterance.voice.lang",t.voice.lang),Tt.default.log("utterance.lang",t.lang)),Tt.default.log("navigator.language",navigator.language)}speakPlay(){this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate(),this.scrollPartial=!0,this.cancel(!1),this.api?.started&&this.api?.started(),this.navigator.emit("readaloud.started","started");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.navigator.iframes[0].contentDocument;if(u){let l=e.highlighter.dom(u.body).getWindow().document.createRange(),c=e.highlighter.dom(e.navigator.iframes[0].contentDocument?.body).getSelection();c.removeAllRanges(),l.selectNodeContents(a.node),c.addRange(l);let h=0,f=c.focusNode,m=c.focusOffset;c.collapse(c.anchorNode,c.anchorOffset);for(let y=0;y<h;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.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)}speakPause(){window.speechSynthesis.speaking&&(this.api?.paused&&this.api?.paused(),this.navigator.emit("readaloud.paused","paused"),this.userScrolled=!1,window.speechSynthesis.pause(),this.speaking=!1,this._ttsQueueItemHighlightsWord&&(this.navigator.highlighter?.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0))}speakResume(){window.speechSynthesis.speaking&&(this.api?.resumed&&this.api?.resumed(),this.navigator.emit("readaloud.resumed","resumed"),this.userScrolled=!1,window.speechSynthesis.resume(),this.speaking=!0)}static async create(e){let t=new this(e.tts,e.rights,e.highlighter,e,e.api,e.headerMenu);return await t.start(),t}async start(){if(this.headerMenu){var e=ge(this.headerMenu,"#menu-button-tts");e&&e.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties?.hideLayer?this.navigator.hideLayer("readaloud"):this.navigator.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(){Tt.default.log("TTS module stop"),Se(document,"wheel",this.wheel.bind(this)),Se(this.body,"wheel",this.wheel.bind(this)),Se(document,"keydown",this.wheel.bind(this)),Se(this.navigator.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),Se(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?hM(u.parentElement):void 0,h=u.parentElement?rX(u.parentElement):void 0,f=t[t.length-1];(!f||f.parentElement!==l||f.lang!==c||f.dir!==h)&&(f={combinedText:"",dir:h,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 h=c;if(!h.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))o(h);else if(h.tagName&&h.tagName.toLowerCase()==="img"&&h.src){let m=h.getAttribute("alt");if(m){let y=m.trim();if(y){let g=hM(h);t.push({combinedText:y,dir:void 0,lang:g,parentElement:h,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=sX(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(!Ga(e,t)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(t,e)}ttsPlayQueueIndex(e,t){if(e<0){this.cancel();return}let i=Ga(t,e);if(!i){this.cancel();return}let r=Wa(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=>{Tt.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;Tt.default.log(e,t,i,s);let o=s||Wa(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 h=s.substring(t).match(/^[a-z\d']*/i);h&&(i=h[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){Tt.default.log(e),Tt.default.log(t),Tt.default.log(i,r,s,o,a),this._ttsQueueItemHighlightsWord&&(this.navigator.highlighter?.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0);let u=e.item,l=i,c=0,h,f=-1,m,y=-1,g=l+r;for(let b of u.textNodes){if(!b.nodeValue&&b.nodeValue!=="")continue;let A=b.nodeValue.length;if(c+=A,h||l<c&&(h=b,f=A-(c-l)),h&&g<=c&&(m=b,y=A-(c-g)),m)break}if(h&&m){let v=function(C){try{let T=A.navigator.iframes[0].contentDocument;return T?Vi(C,T,Vo):""}catch(T){return Tt.default.log("uniqueCssSelector:"),Tt.default.error(T),""}},b=new Range;b.setStart(h,f),b.setEnd(m,y);let A=this,E=to(b,v);if(!E)return;let S=this.navigator.highlighter?.createHighlight(this.navigator.iframes[0].contentWindow,{rangeInfo:E,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(S){this._ttsQueueItemHighlightsWord=S[0];let M=(S[1]?.firstChild?.getBoundingClientRect()).top-this.wrapper.scrollTop>window.innerHeight/2-65;this.navigator.view?.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&this.scrollPartial&&M?S[1]?.firstChild?.scrollIntoView({block:"center",behavior:"smooth"}):this.navigator.view?.isPaginated()&&A.navigator.view?.snap(S[1]?.firstChild)}}}};function hM(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 rX(n){let e=n;for(;e&&e.nodeType===Node.ELEMENT_NODE;){let t=e.getAttribute("dir");if(t)return t;e=e.parentNode}}function sX(n,e){if(n&&n.length){let t="";for(let i of n)i.nodeValue&&(t+=e?i.nodeValue:aX(i.nodeValue));return t}return""}function oX(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function aX(n){return oX(n).replace(/\n/g," ").replace(/\s\s+/g," ")}function Ga(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 Wa(n){return n.item.combinedText}_();var Fd=Qe(vp());var gM=Qe(eo());var mM=Qe(Qt()),Pl=class{constructor(e,t,i,r){this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,gM.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}static async create(e){let t=new this(e.publication,e,e.highlighter,e.api);return await t.start(),t}async stop(){mM.default.log("Definitions module stop")}async start(){setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("definitions"):this.navigator.showLayer("definitions")},10)}async searchAndPaint(e,t){let i=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[this.navigator.currentResource()??0].Href:""),r=this.publication.getTOCItem(i);r===void 0&&this.publication.readingOrder&&(r=this.publication.readingOrder[this.navigator.currentResource()??0]);let s=[];if(r)for(let o of e.terms){let a=e.terms.indexOf(o);r&&await Jo(o,this.navigator.iframes[0].contentDocument,r.Href,r.Title,this.navigator.definitionsModule?.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,h)=>{if(l===void 0||l===h){let f={rangeInfo:c.rangeInfo},m=this.createDefinitionHighlight(f,e);c.highlight=m,s.push(Fd.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(Fd.omit(e,"callbacks"),t),this.navigator.emit("definition.success",t),this.api?.visible&&t.forEach(i=>{let s=this.navigator.iframes[0].contentDocument?.querySelector(`#${i.id}`)?.querySelectorAll(`.${ln}`),o=new IntersectionObserver((a,u)=>{a.forEach(l=>{l.intersectionRatio===1&&(this.api?.visible(Fd.omit(e,"callbacks"),Fd.omit(i,"definition")),this.navigator.emit("definition.visible",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.navigator.definitionsModule?.properties.color;Xt.isHexColor(i)&&(i=Xt.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_"+ys.hash(r);this.highlighter.destroyHighlight(this.navigator.iframes[0].contentDocument,o);let a={color:i||Fa,id:o,pointerInteraction:!0,selectionInfo:e,marker:1,type:4};li.push(a);let u=this.highlighter.createHighlightDom(this.navigator.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)}};HA();_();ui();yn();var $o=Qe(Qt()),vM=.5,Va=class{constructor(e,t,i){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}static async create(e){let t=new this(e,e.highlighter,e.api);return await t.start(),t}async stop(){$o.default.log("Definitions module stop"),this.hasEventListener=!1,Se(document,"keydown",this.keydown.bind(this)),Se(document,"keyup",this.keyup.bind(this)),Se(this.navigator.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),Se(this.navigator.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){let e=gt(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,te(document,"keydown",this.keydown.bind(this)),te(document,"keyup",this.keyup.bind(this)),te(e.contentDocument,"keydown",this.keydown.bind(this)),te(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.navigator.settings.scroll(!0),this.lineFocus()}disableLineFocus(e=!0){this.isActive=!1;let t=gt(document,"#iframe-wrapper");this.wrapperHeight&&(t.style.height=this.wrapperHeight),e||(this.index=0);let i=this.navigator.iframes[0].contentDocument;Pi(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=gt(document,"#iframe-wrapper"),t=this.navigator.iframes[0].contentDocument,i=Pi(t,"html"),r=this.properties.maxHeight?zr()*this.properties.maxHeight/100:zr()/2;i.style.setProperty("--USER__maxMediaHeight",r+"px");function s(c,h){c.parentNode.insertBefore(h,c.nextSibling)}function o(c,h){c.parentNode.insertBefore(h,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 v=Math.round,E=Math.random,S=255;return{blue:v(E()*S),green:v(E()*S),red:v(E()*S)}},m=function(v,E){let S=[];for(let C=0,T=0;C<v.length;C++)C>=E&&C%E===0&&T++,S[T]=S[T]||[],S[T].push(v[C]);return S},y=function(v,E){let S=Math.min(v.left,E.left),C=Math.max(v.right,E.right),T=Math.min(v.top,E.top),M=Math.max(v.bottom,E.bottom);return{bottom:M,height:M-T,left:S,right:C,top:T,width:C-S}},g=function(v){if(v.length>1){let E=y(v[0],v[1]);if(v.length>2){let S=y(E,v[2]);if(v.length>3){let C=y(S,v[3]);return v.length>4?y(C,v[4]):C}return S}return E}return v[0]},c=this.findRects(t.body);c=My(c,!0),c=c.sort(function(v,E){return v.top-E.top});let h=[];c=c.filter(function(v){let E=v.top;return h.indexOf(E)===-1&&h.indexOf(E+1)===-1&&h.indexOf(E+2)===-1&&h.indexOf(E+3)===-1&&h.indexOf(E+4)===-1&&h.indexOf(E-1)===-1&&h.indexOf(E-2)===-1&&h.indexOf(E-3)===-1&&h.indexOf(E-4)===-1?(h.push(E),!0):!1}),this.highlighter.destroyHighlights(5);let b=[];this.properties.lines&&this.properties.lines>1?m(c,this.properties.lines).forEach(E=>{b.push(g(E))}):b=c;let A=ge(t,"#R2_ID_LINEFOCUS_CONTAINER");if(A)for(let v of b){let E=document.createElement("div");E.setAttribute("class",ln);let S=f();if(Xt.isHexColor(S)&&(S=Xt.hexToRgbChannels(S)),this.isDebug){let ae=`border-bottom: 1px solid rgba(${S.red}, ${S.green}, ${S.blue}, ${vM}) !important`;E.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${S.red}, ${S.green}, ${S.blue}, ${vM}) !important; ${ae}`)}E.style.outline="none",E.tabIndex=0;let C=this.navigator.iframes[0].contentWindow.document,T=this.navigator.view.isPaginated();T?C.body.style.position="revert":C.body.style.position="relative";let M=C.body.getBoundingClientRect(),I=this.highlighter.getScrollingElement(C),L=T?-I.scrollLeft:M.left,R=T?-I.scrollTop:M.top,B=1,N=24,H,j,U=this.navigator.iframes[0].contentWindow?.innerWidth,z=parseInt(getComputedStyle(t.documentElement).getPropertyValue("column-count")),V=parseInt(getComputedStyle(t.documentElement).getPropertyValue("column-width")),ee=parseInt(getComputedStyle(t.body).getPropertyValue("padding-left"));if(U){let ae=U/(z||1);ae<V&&(ae=U),T||(ae=parseInt(getComputedStyle(t.body).width.replace("px","")));let Ae=this.navigator.settings.fontSize/100,ce=20*Ae;Ae<=1&&(ce=-60);let be=0;Ae<=1&&(be=-60),H=Math.floor(v.left/ae)*ae+ae-(N<40?40:N)+be,j=Math.floor(v.left/ae)*ae+(N<40?40:N)-ce;let oe=parseInt(t.documentElement.style.getPropertyValue("--USER__pageMargins"));oe>=2&&(j=j+ee/z,H=H-ee/z),T||(H=parseInt(getComputedStyle(t.body).width.replace("px","")),j=parseInt(getComputedStyle(t.body).width.replace("px",""))-ae,oe>=2&&(j=j+ee/2,H=H-ee/2))}E.style.setProperty("pointer-events","none"),E.style.position="absolute",E.scale=B,E.rect={height:v.height,left:v.left-L,top:v.top-R,width:v.width},E.style.width=`${E.rect.width*B}px`,E.style.height=`${E.rect.height*B}px`,E.style.left=`${E.rect.left*B}px`,E.style.top=`${E.rect.top*B}px`,this.lines.push(E),A.append(E)}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){$o.default.log("measureTextNode "+t),$o.default.log("measureTextNode "+e),$o.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){$o.default.log("measureTextNode "+t),$o.default.log("measureTextNode "+e),$o.default.log(`${e.textContent}`)}}};_();ui();yn();var wM=Qe(Qt()),Ml=class{constructor(e,t,i,r){this.history=[];this.headerMenu=r,this.publication=t,this.properties=i,this.annotator=e}static async create(e){let t=new this(e.annotator,e.publication,e,e.headerMenu);return await t.start(),t}async stop(){wM.default.log("Page Break module stop"),Se(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),Se(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=ge(this.headerMenu,"#history-forward")),this.headerMenu&&(this.historyBackAnchorElement=ge(this.headerMenu,"#history-back")),this.historyCurrentIndex=this.history.length-1,te(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),te(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.navigator.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.navigator.navigate(this.history[this.historyCurrentIndex],!1))}};_();var EM=Qe(Qt()),u1=(i=>(i[i.Chicago=0]="Chicago",i[i.MLA=1]="MLA",i[i.APA=2]="APA",i))(u1||{});function Qo(n){if(typeof n.Name=="string")return n.Name;if(n.Name&&typeof n.Name=="object"){let e=Object.values(n.Name);return e.length>0?String(e[0]):""}return""}var Lr=["","",""],Ka=class{constructor(e,t,i,r){this.highlighter=t,this.properties=i,this.publication=e,this.api=r}static async create(e){let t=new this(e.publication,e.highlighter,e,e.api);return await t.start(),t}async stop(){EM.default.log("Citation module stop")}copyToClipboard(e){if(this.navigator?.contentProtectionModule&&(this.navigator.contentProtectionModule.citation=!0),navigator.clipboard){let t=document.createElement("div");t.innerHTML=e;let i=t.textContent??t.innerText??e;navigator.clipboard.writeText(i).then(()=>this.api?.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=!1;try{i=document.execCommand("copy")}catch{i=!1}document.body.removeChild(t),i?this.api?.citationCreated("The text was copied to the clipboard!"):this.api?.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.Author?.length>0){let s=this.publication.Metadata.Author.map(o=>Qo(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+". "]:Lr}yearPublishedFormatted(){let e="",t="",i="";if(this.properties.publisher)t+=this.properties.publisher,e+=this.properties.publisher;else if(this.publication.Metadata.Publisher?.length>0&&Qo(this.publication.Metadata.Publisher[0])){let s=Qo(this.publication.Metadata.Publisher[0]);t+=s,e+=s}let r="";if(this.properties.published)r=this.properties.published;else if(this.publication.Metadata.PublicationDate){let s=this.publication.Metadata.PublicationDate.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+". ":""]:Lr}bookTitleFormatted(){let e=this.properties.title||this.publication.Metadata.Title||"";if(e){let t="<em>"+e+"</em>. ";return[t,t,t]}return Lr}editionFormatted(){return Lr}publisherFormatted(){let e="";return this.properties.publisher?e=this.properties.publisher:this.publication.Metadata.Publisher?.length>0&&Qo(this.publication.Metadata.Publisher[0])&&(e=Qo(this.publication.Metadata.Publisher[0])),e?["","",e+". "]:Lr}contributorsFormatted(){let e=[],t=this.publication.Metadata.Editor;if(t?.length>0){let r=t.map(s=>Qo(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.Translator;if(i?.length>0){let r=i.map(s=>Qo(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 Lr}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 Lr}locationFormatted(){return Lr}libraryFormatted(){if(this.properties.library){let e="Retrieved from "+this.properties.library+". ";return[e,e,e]}return Lr}appNameFormatted(){if(this.properties.appName){let e=this.properties.appName+". ";return[e,e,e]}return Lr}appLinkFormatted(){if(this.properties.appLink){let e=this.properties.appLink+". ";return[e,e,e]}return Lr}seriesFormatted(){let e=this.publication.Metadata.BelongsTo?.Series;if(e&&e.length>0){let t=Qo(e[0]);if(t)return[t+". ",t+". ",t+". "]}return Lr}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(),h=this.appNameFormatted(),f=this.appLinkFormatted(),m=this.seriesFormatted(),y=0,g=1,b=2,A=t[y]+r[y]+a[y]+s[y]+l[y]+i[y]+u[y]+c[y]+h[y]+f[y],v=t[b]+i[b]+r[b]+s[b]+o[b]+a[b]+u[b]+l[b]+c[b]+h[b]+f[b],E=t[g]+r[g]+a[g]+s[g]+l[g]+i[g]+m[g]+c[g]+h[g]+f[g],S=this.properties.characters??200,C="\u201C"+this.selectedText(e,S)+"\u201D",T="";return this.properties.styles?.includes(u1[0])&&(this.properties.styles.length>1&&(T+="Chicago: <br>"),T+=C+"<br><br>"+A+"<br><br>"),this.properties.styles?.includes(u1[2])&&(this.properties.styles.length>1&&(T+="APA: <br>"),T+=C+"<br><br>"+v+"<br><br>"),this.properties.styles?.includes(u1[1])&&(this.properties.styles.length>1&&(T+="MLA: <br>"),T+=C+"<br><br>"+E+"<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)}};var Hn=Qe(Qt());var _t=class n extends a1{constructor(t,i=void 0,r=void 0,s,o,a,u,l,c,h,f,m,y,g){super();this.iframes=[];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.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);Hn.default.log(t.href),Hn.default.log(i),t.href=i,await this.navigate(t)}};this.savePosition=(0,l1.default)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,l1.default)(()=>{this.view?.atStart()&&this.view?.atEnd()?(this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit("resource.fits")):this.view?.atEnd()?(this.api?.resourceAtEnd&&this.api?.resourceAtEnd(),this.emit("resource.end")):this.view?.atStart()&&(this.api?.resourceAtStart&&this.api?.resourceAtStart(),this.emit("resource.start"))},200);this.highlighter=y,this.highlighter&&(this.highlighter.navigator=this);for(let b of g??[])b&&(b.navigator=this,b instanceof ll?this.annotationModule=b:b instanceof cl?this.bookmarkModule=b:b instanceof Il?this.ttsModule=b:b instanceof xl?this.searchModule=b:b instanceof Pl?this.definitionsModule=b:b instanceof fl?this.timelineModule=b:b instanceof ja?this.contentProtectionModule=b:b instanceof Ka?this.citationModule=b:b instanceof hl?this.mediaOverlayModule=b:b instanceof Tl?this.pageBreakModule=b:b instanceof Va?this.lineFocusModule=b:b instanceof Ml?this.historyModule=b:b instanceof ul&&(this.consumptionModule=b));this.settings=t,this.annotator=i,this.view=t.view,this.view.attributes=c,this.view.navigator=this,this.eventHandler=new gd(this),this.touchEventHandler=new Od(this),this.keyboardEventHandler=new Bd(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.attributes=c||{margin:0},this.services=h,this.sample=f,this.requestConfig=m,this.sampleReadEventHandler=new Nd(this)}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||{margin:0},t.services,t.sample,t.requestConfig,t.highlighter,t.modules);return await i.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(r=>r(i))}stop(){Hn.default.log("Iframe navigator stop"),Se(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),Se(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),Se(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Se(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),Se(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Se(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),Se(this.tryAgainButton,"click",this.tryAgain.bind(this)),Se(this.goBackButton,"click",n.goBack.bind(this)),Se(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),Se(window,"resize",this.onResize),this.iframes.forEach(t=>{Se(t,"resize",this.onResize)}),this.didInitKeyboardEventHandler&&this.keyboardEventHandler.removeEvents(document)}setDirection(t){let i="";(t==="rtl"||t==="ltr")&&(i=t),t==="auto"&&(i=this.publication.Metadata.Direction2),i&&(i==="rtl"&&(this.spreads.style.flexDirection="row-reverse"),i==="ltr"&&(this.spreads.style.flexDirection="row"),this.keyboardEventHandler.rtl=i==="rtl",this.api?.direction&&this.api?.direction(i),this.emit("direction",i))}async start(t,i,r){this.headerMenu=i,this.mainElement=t;try{let y=gt(t,"main#iframe-wrapper");y.style.overflow="auto";let g=ge(t,"main#iframe-wrapper iframe"),b=ge(t,"#second");if(g&&this.iframes.push(g),b&&this.iframes.push(b),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.iframes.length===0){y.style.overflow="auto";let A=document.createElement("iframe");if(A.setAttribute("SCROLLING","no"),A.setAttribute("allowtransparency","true"),this.iframes.push(A),this.publication.isFixedLayout){this.spreads=document.createElement("div"),this.firstSpread=document.createElement("div"),this.spreads.style.display="flex",this.spreads.style.alignItems="center",this.spreads.style.justifyContent="center",this.spreads.appendChild(this.firstSpread),this.firstSpread.appendChild(this.iframes[0]),y.appendChild(this.spreads);let v="";switch(this.settings.direction){case 0:v="auto";break;case 1:v="ltr";break;case 2:v="rtl";break}this.setDirection(v)}else A.setAttribute("height","100%"),A.setAttribute("width","100%"),y.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 E=document.createElement("iframe");E.setAttribute("SCROLLING","no"),E.setAttribute("allowtransparency","true"),E.style.opacity="1",E.style.border="none",E.style.overflow="hidden",this.iframes.push(E),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 this.iframes[0].style.paddingTop=(this.attributes?.iframePaddingTop??0)+"px"}if(this.publication.isFixedLayout){let A=y.clientHeight;var s=this.iframes[0].parentElement?.parentElement;s.style.height=A+40+"px"}else this.iframes.length===2&&this.iframes.pop();if(this.loadingMessage=ge(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=s1,this.loadingMessage.style.display="none"),this.errorMessage=ge(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=cM,this.errorMessage.style.display="none"),this.tryAgainButton=ge(t,"button[class=try-again]"),this.goBackButton=ge(t,"button[class=go-back]"),this.infoTop=ge(t,"div[class='info top']"),this.infoBottom=ge(t,"div[class='info bottom']"),this.headerMenu&&(this.bookTitle=ge(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=ge(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=ge(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=ge(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=ge(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=ge(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=ge(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=ge(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=ge(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=ge(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=ge(this.headerMenu,"#container-view-pagelist")),r&&(this.linksBottom=ge(r,"ul.links.bottom")),r&&(this.linksMiddle=ge(r,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=ge(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=ge(t,"#next-chapter")),r&&(this.nextPageAnchorElement=ge(r,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=ge(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=ge(t,"#previous-chapter")),r&&(this.previousPageAnchorElement=ge(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 o=ge(this.headerMenu,"#menu-button-search"),a=ge(this.headerMenu,"#menu-button-tts"),u=ge(this.headerMenu,"#menu-button-bookmark"),l=ge(this.headerMenu,"#menu-button-play"),c=ge(this.headerMenu,"#menu-button-pause"),h=ge(this.headerMenu,"#menu-button-mediaoverlay");if(!this.rights.enableBookmarks){u&&u.parentElement?.style.setProperty("display","none");var f=ge(this.headerMenu,"#sidenav-section-bookmarks");f&&f.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var m=ge(this.headerMenu,"#sidenav-section-highlights");m&&m.style.setProperty("display","none")}this.rights.enableTTS||a&&a.parentElement?.style.setProperty("display","none"),this.rights.enableSearch||o&&o.parentElement?.style.setProperty("display","none"),o&&this.view?.navigator.publication.isFixedLayout&&o.parentElement?.style.setProperty("display","none"),this.hasMediaOverlays?(l&&l.parentElement?.style.removeProperty("display"),c&&c.parentElement?.style.removeProperty("display"),h&&h.parentElement?.style.removeProperty("display")):(l&&l.parentElement?.style.setProperty("display","none"),c&&c.parentElement?.style.setProperty("display","none"),h&&h.parentElement?.style.setProperty("display","none"))}else o&&o.parentElement?.style.setProperty("display","none"),a&&a.parentElement?.style.setProperty("display","none"),u&&u.parentElement?.style.setProperty("display","none");return this.setupEvents(),await this.loadManifest()}catch(y){return Hn.default.error(y),this.abortOnError(y),Promise.reject(y)}}setupEvents(){for(let t of this.iframes)te(t,"load",this.handleIFrameLoad.bind(this,t));te(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),te(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),te(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),te(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),te(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),te(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),te(this.tryAgainButton,"click",this.tryAgain.bind(this)),te(this.goBackButton,"click",n.goBack.bind(this)),te(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),te(window,"resize",this.onResize);for(let t of this.iframes)te(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=zr()-40-(this.attributes?.margin??0),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,l1.default)(()=>{this.isScrolling=!1},200),s=gt(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.annotationModule&&await this.annotationModule.drawHighlights(),this.rights.enableBookmarks&&this.bookmarkModule&&await this.bookmarkModule.drawBookmarks(),this.rights.enableSearch&&this.searchModule&&(await this.highlighter.destroyHighlights(1),this.searchModule.drawSearch()),this.rights.enablePageBreaks&&this.pageBreakModule&&(await this.highlighter.destroyHighlights(3),await this.pageBreakModule.drawPageBreaks()),this.rights.enableDefinitions&&this.definitionsModule&&await this.definitionsModule.drawDefinitions())},200))}async loadManifest(){try{let t=(l,c,h=!1)=>{var f=document.createElement("ul");h&&(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 A="";m.Href?(A=this.publication.getAbsoluteHref(m.Href),g.href=A,g.innerHTML=m.Title||"",y.appendChild(g)):(b.innerHTML=m.Title||"",b.className="chapter-title",y.appendChild(b)),m.Children&&m.Children.length>0&&t(y,m.Children,!0),f.appendChild(y)}te(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 A=y.href.slice(y.href.indexOf("#")+1);A!==void 0&&(g={fragment:A})}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);Hn.default.log(o.href),Hn.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 Hn.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.TypeLink})}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.TypeLink}: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.historyModule&&this.historyModule.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.TypeLink);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.TypeLink&&(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("chapterinfo",this.currentChapterLink.title)):(this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),this.api?.chapterInfo&&this.api.chapterInfo(void 0),this.emit("chapterinfo",void 0)),await this.injectInjectablesIntoIframeHead(t),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 h=>{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.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(t.height="0",this.view?.setIframeHeight?.(t)),this.rights.enableContentProtection&&this.contentProtectionModule&&await this.contentProtectionModule.initialize(t),this.rights.enableConsumption&&this.consumptionModule&&await this.consumptionModule.initialize(t),this.rights.enableAnnotations&&this.annotationModule&&await this.annotationModule.initialize(t),this.rights.enableBookmarks&&this.bookmarkModule&&await this.bookmarkModule.initialize(),this.rights.enableLineFocus&&this.lineFocusModule&&await this.lineFocusModule.initialize(t),this.rights.enableTTS&&this.ttsModule){let c=t.contentDocument?.body;await this.ttsModule.initialize(c)}return this.rights.enableTimeline&&this.timelineModule&&await this.timelineModule.initialize(),this.rights.enableMediaOverlays&&this.mediaOverlayModule&&this.hasMediaOverlays&&await this.mediaOverlayModule.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?.goToProgression(i);if(this.newPosition=void 0,this.rights?.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(10),this.hideLoadingMessage(),this.showIframeContents(t),this.rights.enableMediaOverlays&&this.mediaOverlayModule&&this.hasMediaOverlays){let c=this.currentLink();await this.mediaOverlayModule?.initializeResource(c)}await this.updatePositionInfo(),await this.view?.setSize(),setTimeout(()=>{this.mediaOverlayModule&&(this.mediaOverlayModule.settings.resourceReady=!0)},300)},200),new Promise(c=>c())}catch(i){return Hn.default.error(i),this.abortOnError(i),Promise.reject(i)}}async injectInjectablesIntoIframeHead(t){let i=[],r=o=>{let a=new Promise((u,l)=>{o.onload=()=>{u(!0)},o.onerror=c=>{let h=typeof c=="string"?c:`Injectable failed to load at: ${"href"in o?o.href:o.src}`;l(new Error(h))}});i.push(a)},s=t.contentDocument?.head;s&&(t.contentDocument.getElementsByTagName("base").length===0&&s.insertBefore(n.createBase(this.currentChapterLink.href),s.firstChild),this.injectables?.forEach(a=>{if(a.type==="style"){if(a.fontFamily){if(this.settings.initAddedFont(),!a.systemFont&&a.url){let u=n.createCssLink(a.url);s.appendChild(u),r(u)}}else if(a.r2before&&a.url){let u=n.createCssLink(a.url);s.insertBefore(u,s.firstChild),r(u)}else if(a.r2default&&a.url){let u=n.createCssLink(a.url);s.insertBefore(u,s.childNodes[1]),r(u)}else if(a.r2after&&a.url){a.appearance&&this.settings.initAddedAppearance();let u=n.createCssLink(a.url);s.appendChild(u),r(u)}else if(a.url){let u=n.createCssLink(a.url);s.appendChild(u),r(u)}}else if(a.type==="script"&&a.url){let u=n.createJavascriptLink(a.url,a.async??!1);s.appendChild(u),r(u)}})),i.length!==0&&await Promise.all(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 IFrameNavigator.");this.api.onError(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),r=(i??0)%2===1;this.showLoadingMessageAfterDelay(),this.currentSpreadLinks={};function s(l,c){let f=new DOMParser().parseFromString(l,"application/xhtml+xml");f.head&&f.getElementsByTagName("base").length===0&&f.head.insertBefore(n.createBase(c),f.head.firstChild);let m=f.documentElement.outerHTML,y=t.iframes[0].contentDocument;y&&(y.open(),y.write(m),y.close())}function o(l,c){let f=new DOMParser().parseFromString(l,"application/xhtml+xml");f.head&&f.getElementsByTagName("base").length===0&&f.head.insertBefore(n.createBase(c),f.head.firstChild);let m=f.documentElement.outerHTML,y=t.iframes[1].contentDocument;y&&(y.open(),y.write(m),y.close())}let a=new URL(this.currentChapterLink.href),u=window.location.protocol===a.protocol&&window.location.port===a.port&&window.location.hostname===a.hostname;if(this.api?.getContent)if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(r){if(this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(l=>{l===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{s.call(this,c,this.currentChapterLink.href)}):s.call(this,l,this.currentChapterLink.href)}),this.iframes.length===2)if((i??0)<this.publication.readingOrder.length-1){let l=this.publication.getNextSpineItem(this.currentChapterLink.href);if(l){let c=this.publication.getAbsoluteHref(l.Href);this.currentSpreadLinks.right={href:c},this.api?.getContent(c).then(h=>{h===void 0?u?this.iframes[1].src=c:fetch(c,this.requestConfig).then(f=>f.text()).then(async f=>{o.call(this,f,c),this.currentSpreadLinks.right={href:c}}):o.call(this,h,c)})}}else this.iframes[1].src="about:blank",this.currentSpreadLinks.right=void 0}else{if((i??0)>0){let l=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(l){let c=this.publication.getAbsoluteHref(l.Href);this.currentSpreadLinks.left={href:c},this.api?.getContent(c).then(h=>{h===void 0?u?this.iframes[0].src=c:fetch(c,this.requestConfig).then(f=>f.text()).then(async f=>{s.call(this,f,c)}):s.call(this,h,c)})}}else this.iframes[0].src="about:blank",this.currentSpreadLinks.left=void 0;this.iframes.length===2&&this.publication.isFixedLayout&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},this.api.getContent(this.currentChapterLink.href).then(l=>{l===void 0?u?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{o.call(this,c,this.currentChapterLink.href)}):o.call(this,l,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(l=>{l===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{s.call(this,c,this.currentChapterLink.href)}):s.call(this,l,this.currentChapterLink.href)});else this.api?.getContent(this.currentChapterLink.href).then(l=>{this.currentSpreadLinks.left={href:this.currentChapterLink.href},l===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{s.call(this,c,this.currentChapterLink.href)}):s.call(this,l,this.currentChapterLink.href)});else if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(r){if(u){if(this.iframes[0].src=this.currentChapterLink.href,this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.iframes.length===2)if((i??0)<this.publication.readingOrder.length-1){let l=this.publication.getNextSpineItem(this.currentChapterLink.href);if(l){let c=this.publication.getAbsoluteHref(l.Href);this.iframes[1].src=c,this.currentSpreadLinks.right={href:c}}}else this.iframes[1].src="about:blank",this.currentSpreadLinks.right=void 0}else if(fetch(this.currentChapterLink.href,this.requestConfig).then(l=>l.text()).then(async l=>{s.call(this,l,this.currentChapterLink.href)}),this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.iframes.length===2)if((i??0)<this.publication.readingOrder.length-1){let l=this.publication.getNextSpineItem(this.currentChapterLink.href);if(l){let c=this.publication.getAbsoluteHref(l.Href);this.currentSpreadLinks.right={href:c},fetch(c,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,c)})}}else this.iframes[1].src="about:blank",this.currentSpreadLinks.right=void 0}else if((i??0)>0){let l=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(l){let c=this.publication.getAbsoluteHref(l.Href);this.currentSpreadLinks.left={href:c},u?(this.iframes[0].src=c,this.iframes.length===2&&(this.iframes[1].src=this.currentChapterLink.href,this.currentSpreadLinks.right={href:this.currentChapterLink.href})):(fetch(c,this.requestConfig).then(h=>h.text()).then(async h=>{s.call(this,h,c)}),this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)})))}}else this.iframes[0].src="about:blank",this.currentSpreadLinks.left=void 0,this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},u?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(l=>l.text()).then(async l=>{o.call(this,l,this.currentChapterLink.href)}));else this.currentSpreadLinks.left={href:this.currentChapterLink.href},u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(l=>l.text()).then(async l=>{s.call(this,l,this.currentChapterLink.href)});else this.currentSpreadLinks.left={href:this.currentChapterLink.href},u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(l=>l.text()).then(async l=>{s.call(this,l,this.currentChapterLink.href)});this.publication.isFixedLayout&&setTimeout(()=>{let l,c,h;if(i===0&&this.iframes?.length===2?h=this.iframes[1].contentDocument:h=this.iframes[0].contentDocument,h&&h.body&&(l=getComputedStyle(h.body).height,c=getComputedStyle(h.body).width,parseInt(l.toString().replace("px",""))===0||parseInt(c.toString().replace("px",""))===0)){let v=Pi(h,"head");if(v){let E=ge(v,"meta[name=viewport]");if(E){var f=E.content,m=f.split(",").reduce((S,C)=>{var[T,M]=C.match(/[^\s;=]+/g);return S[T]=isNaN(Number(M))?M:+M,S},{});l=m.height+"px",c=m.width+"px"}}}var y=i===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(y&&c){let v=this.attributes?.fixedLayoutMargin??100;var g=(parseInt(getComputedStyle(y).width)-v)/(this.iframes.length===2?parseInt(c.toString().replace("px",""))*2+v*2:parseInt(c.toString().replace("px",""))),b=(parseInt(getComputedStyle(y).height)-v)/parseInt(l.toString().replace("px","")),A=Math.min(g,b);y.style.transform="scale("+A+")";for(let E of this.iframes)E.style.height=l,E.style.width=c,E.parentElement&&(E.parentElement.style.height=l)}},400)}static goBack(){window.history.back()}handleEditClick(t){var i=t.target;if(this.headerMenu){var r=ge(document,".sidenav");i.className.indexOf(" active")===-1?(i.className+=" active",r.className+=" expanded",i.innerText="unfold_less",this.sideNavExpanded=!0,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights()):(i.className=i.className.replace(" active",""),r.className=r.className.replace(" expanded",""),i.innerText="unfold_more",this.sideNavExpanded=!1,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights())}t.preventDefault(),t.stopPropagation()}get hasMediaOverlays(){return this.publication.hasMediaOverlays}startReadAloud(){this.rights.enableTTS&&this.ttsModule.speakPlay()}startReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.startReadAloud()}stopReadAloud(){this.rights.enableTTS&&this.highlighter?.stopReadAloud()}stopReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.stopReadAloud()}pauseReadAloud(){this.rights.enableTTS&&(this.ttsModule.speakPause(),this.annotationModule!==void 0&&this.annotationModule.drawHighlights())}pauseReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.pauseReadAloud()}resumeReadAloud(){this.rights.enableTTS&&this.ttsModule.speakResume()}resumeReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.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);Hn.default.log(t.href),Hn.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.pageBreakModule!==void 0&&await this.pageBreakModule.goToPageNumber(t)}snapToSelector(t){let i=this.iframes[0].contentDocument;if(i){Hn.default.log(t);let r=i.querySelectorAll(t);r.length>0&&this.view?.snap(r[0])}}applyAttributes(t){this.attributes=t,this.view.attributes=t,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("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);let c=zr()-40-(this.attributes?.margin??0);var i=t===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(i){i.style.height=c+40+"px";let h,f,m;t===0&&this.iframes?.length===2?m=this.iframes[1].contentDocument:m=this.iframes[0].contentDocument,m&&m.body&&(h=getComputedStyle(m.body).height,f=getComputedStyle(m.body).width);let y=Pi(m,"head");if(y){let b=ge(y,"meta[name=viewport]");if(b){var r=b.content,s={};r.split(",").forEach(A=>{let v=A.match(/[^\s;=]+/g);if(v&&v.length>=2){let[E,S]=v;s[E]=isNaN(Number(S))?S:+S}}),(parseInt(String(s.height))!==0||parseInt(String(s.width))!==0)&&(h=s.height.toString().endsWith("px")?s.height:s.height+"px",f=s.width.toString().endsWith("px")?s.width:s.width+"px")}}let g=this.attributes?.fixedLayoutMargin??100;var o=(parseInt(getComputedStyle(i).width)-g)/(this.iframes.length===2?parseInt(f.toString().endsWith("px")?f?.replace("px",""):f)*2+g*2:parseInt(f.toString().endsWith("px")?f?.replace("px",""):f)),a=(parseInt(getComputedStyle(i).height)-g)/parseInt(h.toString().replace("px","")),u=Math.min(o,a);i.style.transform="scale("+u+")";for(let b of this.iframes)b.style.height=h,b.style.width=f,b.parentElement&&(b.parentElement.style.height=h)}}let l=this.view?.getCurrentPosition();await this.settings.applyProperties(),this.infoTop&&(this.infoTop.style.height="0px"),this.infoTop&&(this.infoTop.style.minHeight="0px"),this.infoBottom&&(this.infoBottom.style.height=this.attributes?.bottomInfoHeight?this.attributes.bottomInfoHeight+"px":"40px"),this.view?.layout!=="fixed"&&this.settings.isPaginated().then(c=>{c?(this.view.height=zr()-40-(this.attributes?.margin??0),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()=>{l&&this.view?.goToProgression(l),this.updatePositionInfo(!1),this.contentProtectionModule!==void 0&&await this.contentProtectionModule.handleResize(),this.annotationModule!==void 0&&await this.annotationModule.handleResize(),this.bookmarkModule!==void 0&&await this.bookmarkModule.handleResize(),this.searchModule!==void 0&&await this.searchModule.handleResize(),this.definitionsModule!==void 0&&await this.definitionsModule.handleResize(),this.pageBreakModule!==void 0&&await this.pageBreakModule.handleResize(),this.lineFocusModule!==void 0&&this.lineFocusModule.handleResize(),this.historyModule!==void 0&&await this.historyModule.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("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.TypeLink,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.TypeLink,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("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(" active","");let r=this.tocView.querySelector('li > a[href^="'+t+'"]');r&&(r.className+=" active")}}async navigate(t,i=!0){if(this.rights.enableConsumption&&this.consumptionModule&&i&&this.consumptionModule.startReadingSession(t),this.historyModule&&await this.historyModule.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 h=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:h}}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.newElementId){for(let h of this.iframes){let f=h.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(f)}this.newElementId=void 0}else if(t.highlight){let h=t.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;h&&this.view?.goToCssSelector(h)}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.TypeLink,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.TypeLink,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.TypeLink);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.TypeLink&&(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("chapterinfo",this.currentChapterLink.title)):(this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),this.api?.chapterInfo&&this.api.chapterInfo(void 0),this.emit("chapterinfo",void 0)),await this.updatePositionInfo()}else this.lineFocusModule!==void 0&&this.lineFocusModule.disableLineFocus(!1),this.searchModule!==void 0&&this.searchModule.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.contentProtectionModule!==void 0&&await this.contentProtectionModule.initializeResource(),this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&await this.mediaOverlayModule.initializeResource(this.currentLink()),this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(300),this.bookmarkModule&&(await this.bookmarkModule.drawBookmarks(),await this.bookmarkModule.showBookmarks()),this.pageBreakModule&&(await this.highlighter?.destroyHighlights(3),await this.pageBreakModule.drawPageBreaks()),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(1),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule&&this.highlighter&&await this.definitionsModule.drawDefinitions(),this.rights.enableConsumption&&this.consumptionModule&&this.consumptionModule.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("resource.fits")):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.mediaOverlayModule!==void 0&&(this.mediaOverlayModule.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(()=>{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("resource.fits")):this.view?.atEnd()?(this.api?.resourceAtEnd&&this.api?.resourceAtEnd(),this.emit("resource.end")):this.view?.atStart()&&(this.api?.resourceAtStart&&this.api?.resourceAtStart(),this.emit("resource.start"))),this.api?.resourceReady&&this.api?.resourceReady(),this.emit("resource.ready")},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.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){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=>(Hn.default.log("api updated current location",r),this.annotator?.saveLastReadingPosition(r))):(Hn.default.log("save last reading position",r),this.annotator.saveLastReadingPosition(r)),this.consumptionModule&&this.consumptionModule.continueReadingSession(r))}}}static createBase(t){let i=document.createElement("base");return i.target="_self",i.href=t,i}static createCssLink(t){let i=document.createElement("link");return i.rel="stylesheet",i.type="text/css",i.href=t,i}static createJavascriptLink(t,i){let r=document.createElement("script");return r.type="text/javascript",r.src=t,r.async=i,r}activateMarker(t,i){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId===void 0||this.annotationModule.activeAnnotationMarkerId!==t?(this.annotationModule.activeAnnotationMarkerId=t,this.annotationModule.activeAnnotationMarkerPosition=i,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=t)):this.deactivateMarker())}deactivateMarker(){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId=void 0,this.annotationModule.activeAnnotationMarkerPosition=void 0,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=void 0))}showLayer(t){let i="#",r=new ju("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=ge(s,i);o&&(o.style.display="block")}}hideLayer(t){let i="#",r=new ju("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=ge(s,i);o&&(o.style.display="none")}}};_();var wt=class wt{constructor(e){this.store=e.store}getLastReadingPosition(){let e=this.store.get(wt.LAST_READING_POSITION);return e?JSON.parse(e):null}initLastReadingPosition(e){if(typeof e=="string")this.store.set(wt.LAST_READING_POSITION,e);else{let t=JSON.stringify(e);this.store.set(wt.LAST_READING_POSITION,t)}}saveLastReadingPosition(e){if(typeof e=="string")this.store.set(wt.LAST_READING_POSITION,e);else{let t=JSON.stringify(e);this.store.set(wt.LAST_READING_POSITION,t)}}initBookmarks(e){if(typeof e=="string"){let t=JSON.parse(e);this.store.set(wt.BOOKMARKS,JSON.stringify(t))}else this.store.set(wt.BOOKMARKS,JSON.stringify(e));return e}saveBookmark(e){let t=this.store.get(wt.BOOKMARKS);if(t){let i=JSON.parse(t);i.push(e),this.store.set(wt.BOOKMARKS,JSON.stringify(i))}else{let i=[];i.push(e),this.store.set(wt.BOOKMARKS,JSON.stringify(i))}return e}locatorExists(e,t){let i;t===0&&(i=wt.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(wt.BOOKMARKS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.id!==e.id),this.store.set(wt.BOOKMARKS,JSON.stringify(i))}return e}getBookmarks(e){let t=this.store.get(wt.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=ys.hash(s);r.highlight.id="R2_HIGHLIGHT_"+o;let a;r.highlight.color?a=r.highlight.color:r.color&&(a=r.color),Xt.isHexColor(a)&&(a=Xt.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(wt.ANNOTATIONS,JSON.stringify(i)),i}saveTemporarySelectionInfo(e){this.store.set(wt.SELECTIONINFO,JSON.stringify(e))}getTemporarySelectionInfo(e){if(!e)return null;let t=this.store.get(wt.SELECTIONINFO);if(t){let i=JSON.parse(t);return i.range=yp(e,i.rangeInfo),i}return null}deleteTemporarySelectionInfo(){this.store.remove(wt.SELECTIONINFO)}saveAnnotation(e){let t=this.store.get(wt.ANNOTATIONS);if(t){let i=JSON.parse(t);i.push(e),this.store.set(wt.ANNOTATIONS,JSON.stringify(i))}else{let i=[];i.push(e),this.store.set(wt.ANNOTATIONS,JSON.stringify(i))}return e}deleteAnnotation(e){let t=this.store.get(wt.ANNOTATIONS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.id!==e),this.store.set(wt.ANNOTATIONS,JSON.stringify(i))}return e}deleteSelectedAnnotation(e){let t=this.store.get(wt.ANNOTATIONS);if(t){let i=JSON.parse(t);i=i.filter(r=>r.highlight?.id!==e.highlight.id),this.store.set(wt.ANNOTATIONS,JSON.stringify(i))}return e}getAnnotations(){let e=this.store.get(wt.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(wt.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(wt.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(wt.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(wt.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(wt.ANNOTATIONS);if(t){let r=JSON.parse(t).filter(s=>s.highlight?.id===e);if(r.length>0)return r[0]}return null}};wt.LAST_READING_POSITION="last-reading-position",wt.BOOKMARKS="bookmarks",wt.ANNOTATIONS="annotations",wt.SELECTIONINFO="selectionInfo";var Ud=wt;_();_();var Ll=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 za=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 Ll: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 Ll}}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))}};ui();_();var CM=Qe(Ic()),SM=Qe(Ji());var Rl=class extends CM.Link{};Rl=Cf([(0,SM.JsonObject)()],Rl);function qa(n){let e,t,i,r;if(n instanceof Array)return n.map(function(s){return typeof s=="object"&&(s=qa(s)),s});e={};for(t in n)n.hasOwnProperty(t)&&(i=(t.charAt(0).toLowerCase()+t.slice(1)||t).toString(),r=n[t],(r instanceof Array||r!=null&&r.constructor===Object)&&(r=qa(r)),i==="href1"?e.href=r:i==="typeLink"?e.type=r:e[i]=r);return e}_();var _M=Qe(Qt()),c1=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(){_M.default.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let e=new ds,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}};var A4;async function Dee(){return A4||(A4=(await Promise.resolve().then(()=>(lR(),uR))).PDFNavigator),A4}function ra(n){return n?.isPDF===!0}var Zl=class n{constructor(e,t,i,r,s,o,a,u,l,c,h,f,m,y,g,b,A,v){this.settings=e;this.navigator=t;this.highlighter=i;this.bookmarkModule=r;this.annotationModule=s;this.ttsSettings=o;this.ttsModule=a;this.searchModule=u;this.definitionsModule=l;this.contentProtectionModule=c;this.timelineModule=h;this.mediaOverlaySettings=f;this.mediaOverlayModule=m;this.pageBreakModule=y;this.lineFocusModule=g;this.historyModule=b;this.citationModule=A;this.consumptionModule=v;this.startReadAloud=()=>{this.navigator instanceof _t&&this.navigator.startReadAloud()};this.stopReadAloud=()=>{this.navigator instanceof _t&&this.navigator.stopReadAloud()};this.pauseReadAloud=()=>{this.navigator instanceof _t&&this.navigator.pauseReadAloud()};this.resumeReadAloud=()=>{this.navigator instanceof _t&&this.navigator.resumeReadAloud()};this.startReadAlong=()=>{this.navigator instanceof _t&&this.navigator.startReadAlong()};this.stopReadAlong=()=>{this.navigator instanceof _t&&this.navigator.stopReadAlong()};this.pauseReadAlong=()=>{this.navigator instanceof _t&&this.navigator.pauseReadAlong()};this.resumeReadAlong=()=>{this.navigator instanceof _t&&this.navigator.resumeReadAlong()};this.saveBookmark=async()=>await this.bookmarkModule?.saveBookmark()??!1;this.saveBookmarkPlus=async()=>this.bookmarkModule?.saveBookmarkPlus();this.deleteBookmark=async e=>await this.bookmarkModule?.deleteBookmark(e)??!1;this.deleteAnnotation=async e=>await this.annotationModule?.deleteAnnotation(e)??!1;this.addAnnotation=async e=>await this.annotationModule?.addAnnotation(e)??!1;this.updateAnnotation=async e=>await this.annotationModule?.updateAnnotation(e)??!1;this.changeHighlighterColor=e=>{this.highlighter?.setColor(e)};this.hideAnnotationLayer=()=>this.annotationModule?.hideAnnotationLayer();this.showAnnotationLayer=()=>this.annotationModule?.showAnnotationLayer();this.hideLayer=e=>this.navigator instanceof _t?this.navigator?.hideLayer(e):!1;this.showLayer=e=>this.navigator instanceof _t?this.navigator?.showLayer(e):!1;this.activateMarker=(e,t)=>this.navigator instanceof _t?this.navigator?.activateMarker(e,t):!1;this.deactivateMarker=()=>this.navigator instanceof _t?this.navigator?.deactivateMarker():!1;this.clearDefinitions=async()=>{await this.definitionsModule?.clearDefinitions()};this.addDefinition=async e=>{await this.definitionsModule?.addDefinition(e)};this.historyBack=async()=>this.historyModule?.historyBack();this.historyForward=async()=>this.historyModule?.historyForward();this.search=async(e,t)=>await this.searchModule?.search(e,t)??[];this.goToSearchIndex=async(e,t,i)=>{this.navigator instanceof _t&&this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchIndex(e,t,i)};this.goToSearchID=async(e,t,i)=>{this.navigator instanceof _t&&this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchID(e,t,i)};this.clearSearch=async()=>{this.navigator instanceof _t&&this.navigator.rights.enableSearch&&await this.searchModule?.clearSearch()};this.resetUserSettings=async()=>await this.settings.resetUserSettings();this.applyUserSettings=async e=>await this.settings.applyUserSettings(e);this.scroll=async(e,t)=>ra(this.navigator)?this.navigator.scroll(e,t):await this.settings.scroll(e);this.increase=async e=>{this.isTTSIncrementable(e)?this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.increase(e):this.isMOIncrementable(e)?this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.increase(e):await this.settings.increase(e)};this.decrease=async e=>{this.isTTSIncrementable(e)?this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.decrease(e):this.isMOIncrementable(e)?this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.decrease(e):await this.settings.decrease(e)};this.resetTTSSettings=()=>{this.navigator instanceof _t&&this.navigator.rights.enableTTS&&this.ttsSettings?.resetTTSSettings()};this.applyTTSSettings=async e=>{this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.applyTTSSettings(e)};this.applyPreferredVoice=async e=>{this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.applyPreferredVoice(e)};this.resetMediaOverlaySettings=async()=>{this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.resetMediaOverlaySettings()};this.applyMediaOverlaySettings=async e=>{this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&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=()=>{ra(this.navigator)&&this.navigator.fitToPage()};this.fitToWidth=()=>{ra(this.navigator)&&this.navigator.fitToWidth()};this.zoomIn=()=>{ra(this.navigator)&&this.navigator.zoomIn()};this.zoomOut=()=>{ra(this.navigator)&&this.navigator.zoomOut()};this.activateHand=()=>{ra(this.navigator)&&this.navigator.activateHand()};this.deactivateHand=()=>{ra(this.navigator)&&this.navigator.deactivateHand()};this.copyToClipboard=e=>{this.contentProtectionModule?.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 instanceof _t&&this.navigator.snapToSelector(e)};this.applyAttributes=e=>{this.navigator instanceof _t&&this.navigator.applyAttributes(e)};this.stop=()=>{document.body.onscroll=()=>{},this.navigator.stop(),this.settings.stop(),this.ttsSettings?.stop(),this.ttsModule?.stop(),this.bookmarkModule?.stop(),this.annotationModule?.stop(),this.searchModule?.stop(),this.definitionsModule?.stop(),this.contentProtectionModule?.stop(),this.timelineModule?.stop(),this.mediaOverlaySettings?.stop(),this.mediaOverlayModule?.stop(),this.pageBreakModule?.stop(),this.lineFocusModule?.stop(),this.citationModule?.stop(),this.consumptionModule?.stop()}}addEventListener(e,t){(this.navigator instanceof _t||ra(this.navigator))&&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 ja.setupPreloadProtection(e.protection);let i=gt(document,"#D2Reader-Container"),r=ge(document,"#headerMenu"),s=ge(document,"#footerMenu"),o=e.url,a;e.publication?(a=Sa(e.publication,zs),a.manifestUrl=new URL(o)):a=await zs.fromUrl(o,e.requestConfig);let u=new za({prefix:a.manifestUrl,useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),l=new za({prefix:"r2d2bc-reader",useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),c=new za({prefix:"r2d2bc-layers",useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),h=new Ud({store:u});if(a.sample=e.sample,t=Fee(t,a),a.Metadata.ConformsTo&&a.Metadata.ConformsTo.includes("https://readium.org/webpub-manifest/profiles/pdf")){let f=await yd.create({store:l,initialUserSettings:e.userSettings,layout:""}),y=await(await Dee()).create({mainElement:i,publication:a,settings:f,api:e.api,workerSrc:e.workerSrc,annotator:h,initialLastReadingPosition:e.lastReadingPosition,store:u});return new n(f,y)}else{t.autoGeneratePositions?await a.autoGeneratePositions(e.requestConfig):(e.services?.positions&&await a.fetchPositionsFromService(e.services?.positions.href,e.requestConfig),e.services?.weight&&await a.fetchWeightsFromService(e.services?.weight.href,e.requestConfig));let f=await c1.create({store:c}),m=await yd.create({store:l,initialUserSettings:e.userSettings,headerMenu:r,api:e.api,injectables:(a.Metadata.Rendition?.Layout??"unknown")==="fixed"?e.injectablesFixed:e.injectables,layout:(a.Metadata.Rendition?.Layout??"unknown")==="fixed"?"fixed":"reflowable"}),y=await Xt.create({layerSettings:f,...e.highlighter}),g=t.enableBookmarks?await cl.create({annotator:h,headerMenu:r,rights:t,publication:a,initialAnnotations:e.initialAnnotations,...e.bookmarks}):void 0,b=t.enableAnnotations?await ll.create({annotator:h,rights:t,publication:a,initialAnnotations:e.initialAnnotations,highlighter:y,headerMenu:r,...e.annotations}):void 0,A=t.enableTTS,v=A?await r1.create({store:l,initialTTSSettings:e.tts,headerMenu:r}):void 0,E;A&&v&&(E=await Il.create({tts:v,headerMenu:r,rights:t,highlighter:y,...e.tts}));let S=t.enableSearch?await xl.create({headerMenu:r,publication:a,highlighter:y,...e.search}):void 0,C=t.enableDefinitions?await Pl.create({publication:a,highlighter:y,...e.define}):void 0,T=t.enableTimeline?await fl.create({publication:a}):void 0,M=t.enableContentProtection?await ja.create({...e.protection}):void 0,I=t.enableCitations?await Ka.create({publication:a,highlighter:y,...e.citations}):void 0,L=t.enableMediaOverlays,R=L?await wp.create({store:l,initialMediaOverlaySettings:e.mediaOverlays,headerMenu:r,...e.mediaOverlays}):void 0,B=L?await hl.create({publication:a,settings:R,...e.mediaOverlays}):void 0,H=t.enablePageBreaks&&a.isReflowable?await Tl.create({publication:a,headerMenu:r,...e.pagebreak}):void 0,j=t.enableLineFocus?await Va.create({publication:a,highlighter:y,...e.lineFocus}):void 0,U=t.enableHistory?await Ml.create({annotator:h,publication:a,headerMenu:r}):void 0,z=t.enableConsumption?await ul.create({publication:a,...e.consumption}):void 0,V=await _t.create({mainElement:i,headerMenu:r,footerMenu:s,publication:a,settings:m,annotator:h,initialLastReadingPosition:e.lastReadingPosition,api:e.api,rights:t,tts:e.tts,sample:e.sample,requestConfig:e.requestConfig,injectables:(a.Metadata.Rendition?.Layout??"unknown")==="fixed"?e.injectablesFixed??[]:e.injectables,attributes:e.attributes,services:e.services,highlighter:y,modules:[g,b,E,S,C,T,M,I,B,H,j,U,z]});return new n(m,V,y,g,b,v,E,S,C,M,T,R,B,H,j,U,I,z)}}get hasMediaOverlays(){return this.navigator instanceof _t?this.navigator.hasMediaOverlays:!1}get tableOfContents(){return qa(this.navigator.tableOfContents())??[]}get landmarks(){return qa(this.navigator.landmarks())??[]}get pageList(){return qa(this.navigator.pageList())??[]}get readingOrder(){return qa(this.navigator.readingOrder())??[]}get bookmarks(){return this.bookmarkModule?.getBookmarks()??[]}get annotations(){return this.annotationModule?.getAnnotations()}get publicationLayout(){return this.navigator.publication.layout}get history(){return this.historyModule?.history}get historyCurrentIndex(){return this.historyModule?.historyCurrentIndex}get currentResource(){return this.navigator.currentResource()}get mostRecentNavigatedTocItem(){return this.navigator instanceof _t?this.navigator.mostRecentNavigatedTocItem():!1}get totalResources(){return this.navigator.totalResources()}get publicationLanguage(){return this.navigator.publication.Metadata.Language}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 instanceof _t?this.navigator.atStart():!1}get atEnd(){return this.navigator instanceof _t?this.navigator.atEnd():!1}async applyLineFocusSettings(e){if(e.lines&&this.lineFocusModule){let t=this.lineFocusModule.properties.lines??1;this.lineFocusModule.index=this.lineFocusModule.index*t/parseInt(e.lines),this.lineFocusModule.index=Math.abs(parseInt(this.lineFocusModule.index.toFixed())),this.lineFocusModule.properties.lines=parseInt(e.lines),this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus()}e.debug!==void 0&&this.lineFocusModule&&(this.lineFocusModule.isDebug=e.debug,this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus())}lineUp(){this.lineFocusModule?.lineUp()}lineDown(){this.lineFocusModule?.lineDown()}async enableLineFocus(){await this.lineFocusModule?.enableLineFocus()}async lineFocus(e){e?await this.lineFocusModule?.enableLineFocus():this.lineFocusModule?.disableLineFocus()}disableLineFocus(){this.lineFocusModule?.disableLineFocus()}};function Fee(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}var Hee=Zl,Uee=Zl.load;return Qn(jee);})();
|
|
603
603
|
/*! Bundled license information:
|
|
604
604
|
|
|
605
605
|
reflect-metadata/Reflect.js:
|