@d-i-t-a/reader 2.2.0-beta.4 → 2.2.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/reader.js
CHANGED
|
@@ -85,7 +85,7 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
85
85
|
<span>There was an error loading this page.</span>
|
|
86
86
|
<button class="go-back">Go back</button>
|
|
87
87
|
<button class="try-again">Try again</button>
|
|
88
|
-
`;var gh=vt(Mo());H();var _a=class{constructor(t){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{let n=null,i=null,o=this;t&&(t.addEventListener("touchstart",function(s){s.changedTouches.length===1&&(n=s)},!1),t.addEventListener("touchend",function(s){if(s.changedTouches.length!==1||!n)return;let l=n.changedTouches[0],h=s.changedTouches[0];if(!l)return;let u=window.devicePixelRatio,d=(l.clientX-h.clientX)/u,m=(l.clientY-h.clientY)/u;if(Math.abs(d)<_a.TAP_TOLERANCE&&Math.abs(m)<_a.TAP_TOLERANCE){if(i){n=null,i=null;return}if(s.timeStamp-n.timeStamp>_a.LONG_PRESS_MS){n=null,i=null;return}n=null,i=s;return}if(i=null,s.timeStamp-n.timeStamp>_a.SLOW_SWIPE_MS){n=null;return}let y=(l.clientY-h.clientY)/(l.clientX-h.clientX);if(Math.abs(y)>.5){n=null;return}d<0?o.onBackwardSwipe(s):o.onForwardSwipe(s),n=null},!1))};this.navigator=t}},Es=_a;Es.TAP_TOLERANCE=10,Es.LONG_PRESS_MS=500,Es.SLOW_SWIPE_MS=500;H();var hh=class{constructor(t){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{t&&(this.focusin(t),this.keydown(t))};this.focusin=t=>{let n=this;t.addEventListener("focusin",function(i){n.navigator.view?.snap(i.target)},!0)};this.keydown=t=>{let n=this;this.navigator.rights.customKeyboardEvents||t.addEventListener("keydown",function(i){let o=i.target;if(/input|select|option|textarea/i.test(o.tagName)||!(o.ownerDocument||o).defaultView.getSelection().isCollapsed)return;switch(i.key){case"ArrowRight":n.onForwardSwipe(i);break;case"ArrowLeft":n.onBackwardSwipe(i);break}},!1)};this.navigator=t}};H();var QA=vt(Mo()),fh=class{constructor(t){this.enforceSampleRead=(0,QA.debounce)(t=>{let n=Math.round(t.locations.totalProgression*100),i=!1;this.delegate.sample?.limit&&(i=n<=this.delegate.sample?.limit,this.delegate.view?.layout==="fixed"&&!i&&this.delegate.sample?.minimum&&t.locations.position<=this.delegate.sample?.minimum&&(i=!0));let o={37:1,38:0,39:1,40:1,32:1,33:1,34:1,35:1,36:1};function s(g){g.preventDefault()}function l(g){o[g.keyCode]&&!i&&s(g)}let h=!1,u=Object.defineProperty&&Object.defineProperty({},"passive",{get:function(){h=!0}});window.addEventListener("test",function(){},u);let d=h?{passive:!1}:!1;function m(g){g=g||window.event;let f=Math.max(-1,Math.min(1,g.wheelDelta||-g.detail));return f===-1&&!i&&g.preventDefault(),!1}let y;function w(g){g=g||window.event;let f=g.target||g.srcElement,p=g.touches[0].clientY;if(!(p>y)){if(p<y&&!i)return f.className.match(/\baltNav\b/)||(g.returnValue=!1,g.cancelable&&(g.cancelBubble=!0),g.preventDefault&&g.cancelable&&(g.preventDefault(),g.stopPropagation())),!1}return y=p,!1}function v(g){return g=g||window.event,y=g.touches[0].clientY,!1}window.addEventListener("mousewheel",m,d),window.addEventListener("DOMMouseScroll",m,d),window.addEventListener("keydown",l,d),window.addEventListener("touchmove",w,d),window.addEventListener("touchstart",v,d),i?(this.delegate.iframes[0].focus(),this.delegate.errorMessage&&(this.delegate.errorMessage.style.display="none",this.delegate.errorMessage.style.removeProperty("background-color"))):(this.delegate.iframes[0].blur(),this.delegate.errorMessage&&(this.delegate.errorMessage.style.display="block",this.delegate.errorMessage.style.backgroundColor="rgb(255, 255, 255)",this.delegate.errorMessage.innerHTML=this.delegate.sample?.popup??""))},300);this.delegate=t}};var tx=vt(Og()),Ei=vt(dn()),_t=class extends tx.default{constructor(t,n=void 0,i=void 0,o,s,l,h,u,d,m,y,w){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 n=this.publication.getAbsoluteHref(t.href);Ei.default.log(t.href),Ei.default.log(n),t.href=n,await this.navigate(t)}};this.savePosition=(0,gh.debounce)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,gh.debounce)(()=>{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.settings=t,this.annotator=n,this.view=t.view,this.view.attributes=d,this.view.delegate=this,this.eventHandler=new Fd(this),this.touchEventHandler=new Es(this),this.keyboardEventHandler=new hh(this),this.initialLastReadingPosition=i,this.publication=o,this.api=s,this.rights=l??{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=h,this.injectables=u,this.attributes=d||{margin:0},this.services=m,this.sample=y,this.requestConfig=w,this.sampleReadEventHandler=new fh(this)}static async create(t){let n=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);return await n.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(n))}stop(){Ei.default.log("Iframe navigator stop"),ze(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),ze(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),ze(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ze(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),ze(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ze(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),ze(this.tryAgainButton,"click",this.tryAgain.bind(this)),ze(this.goBackButton,"click",_t.goBack.bind(this)),ze(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),ze(window,"resize",this.onResize),this.iframes.forEach(t=>{ze(t,"resize",this.onResize)})}async start(t,n,i){this.headerMenu=n,this.mainElement=t;try{let v=Rt(t,"main#iframe-wrapper");v.style.overflow="auto";let g=$e(t,"main#iframe-wrapper iframe"),f=$e(t,"#second");if(g&&this.iframes.push(g),f&&this.iframes.push(f),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.iframes.length===0){v.style.overflow="auto";let p=document.createElement("iframe");if(p.setAttribute("SCROLLING","no"),p.setAttribute("allowtransparency","true"),this.iframes.push(p),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]),v.appendChild(this.spreads)):(p.setAttribute("height","100%"),p.setAttribute("width","100%"),v.appendChild(this.iframes[0])),this.publication.isFixedLayout)if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){let b=document.createElement("div");this.spreads.appendChild(b);let S=document.createElement("iframe");S.setAttribute("SCROLLING","no"),S.setAttribute("allowtransparency","true"),S.style.opacity="1",S.style.border="none",S.style.overflow="hidden",this.iframes.push(S),b.appendChild(this.iframes[1]),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",b.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",b.style.boxShadow="0 0 8px 2px #ccc"}else 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 p=v.clientHeight;var o=this.iframes[0].parentElement?.parentElement;o.style.height=p+40+"px"}else this.iframes.length===2&&this.iframes.pop();if(this.loadingMessage=$e(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=dh,this.loadingMessage.style.display="none"),this.errorMessage=$e(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=ZA,this.errorMessage.style.display="none"),this.tryAgainButton=$e(t,"button[class=try-again]"),this.goBackButton=$e(t,"button[class=go-back]"),this.infoTop=$e(t,"div[class='info top']"),this.infoBottom=$e(t,"div[class='info bottom']"),this.headerMenu&&(this.bookTitle=$e(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=$e(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=$e(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=$e(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=$e(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=$e(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=$e(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=$e(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=$e(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=$e(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=$e(this.headerMenu,"#container-view-pagelist")),i&&(this.linksBottom=$e(i,"ul.links.bottom")),i&&(this.linksMiddle=$e(i,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=$e(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=$e(t,"#next-chapter")),i&&(this.nextPageAnchorElement=$e(i,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=$e(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=$e(t,"#previous-chapter")),i&&(this.previousPageAnchorElement=$e(i,"a[rel=prev]")),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.newPosition=void 0,this.newElementId=void 0,this.isBeingStyled=!0,this.isLoading=!0,this.settings.setIframe(this.iframes[0]),this.settings.onSettingsChange(this.handleResize.bind(this)),this.settings.onColumnSettingsChange(this.handleNumberOfIframes.bind(this)),this.settings.onViewChange(this.updateBookView.bind(this)),this.initialLastReadingPosition&&this.annotator?.initLastReadingPosition(this.initialLastReadingPosition),this.headerMenu){var s=$e(this.headerMenu,"#menu-button-search"),l=$e(this.headerMenu,"#menu-button-tts"),h=$e(this.headerMenu,"#menu-button-bookmark"),u=$e(this.headerMenu,"#menu-button-play"),d=$e(this.headerMenu,"#menu-button-pause"),m=$e(this.headerMenu,"#menu-button-mediaoverlay");if(!this.rights.enableBookmarks){h&&h.parentElement?.style.setProperty("display","none");var y=$e(this.headerMenu,"#sidenav-section-bookmarks");y&&y.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var w=$e(this.headerMenu,"#sidenav-section-highlights");w&&w.style.setProperty("display","none")}this.rights.enableTTS||l&&l.parentElement?.style.setProperty("display","none"),this.rights.enableSearch||s&&s.parentElement?.style.setProperty("display","none"),s&&this.view?.delegate.publication.isFixedLayout&&s.parentElement?.style.setProperty("display","none"),this.hasMediaOverlays?(u&&u.parentElement?.style.removeProperty("display"),d&&d.parentElement?.style.removeProperty("display"),m&&m.parentElement?.style.removeProperty("display")):(u&&u.parentElement?.style.setProperty("display","none"),d&&d.parentElement?.style.setProperty("display","none"),m&&m.parentElement?.style.setProperty("display","none"))}else s&&s.parentElement?.style.setProperty("display","none"),l&&l.parentElement?.style.setProperty("display","none"),h&&h.parentElement?.style.setProperty("display","none");return this.setupEvents(),await this.loadManifest()}catch(v){return Ei.default.error(v),this.abortOnError(v),Promise.reject(v)}}setupEvents(){for(let t of this.iframes)Ce(t,"load",this.handleIFrameLoad.bind(this));Ce(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),Ce(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),Ce(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ce(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),Ce(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ce(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),Ce(this.tryAgainButton,"click",this.tryAgain.bind(this)),Ce(this.goBackButton,"click",_t.goBack.bind(this)),Ce(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),Ce(window,"resize",this.onResize);for(let t of this.iframes)Ce(t,"resize",this.onResize)}updateBookView(){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.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousChapterClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextChapterClick.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this))):(this.settings.isPaginated().then(t=>{if(t)this.view.height=gr()-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));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 n=(0,gh.debounce)(()=>{this.isScrolling=!1},200),i=Rt(document,"#iframe-wrapper");i.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()),n()},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))}}),setTimeout(async()=>{await this.highlighter?.prepareContainers(this.iframes[0].contentWindow),this.pageBreakModule!==void 0&&(await this.highlighter?.destroyHighlights(gt.PageBreak),await this.pageBreakModule.drawPageBreaks()),this.annotationModule!==void 0&&await this.annotationModule.drawHighlights(),this.bookmarkModule!==void 0&&await this.bookmarkModule.drawBookmarks(),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(gt.Search),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule!==void 0&&this.highlighter!==void 0&&await this.definitionsModule.drawDefinitions()},200))}async loadManifest(){try{let t=(u,d,m=!1)=>{var y=document.createElement("ul");m&&(y=document.createElement("ol")),y.className="sidenav-toc";for(let w of d){let v=document.createElement("li"),g=document.createElement("a"),f=document.createElement("span");g.className="chapter-link",g.tabIndex=-1;let p="";w.Href?(p=this.publication.getAbsoluteHref(w.Href),g.href=p,g.innerHTML=w.Title||"",v.appendChild(g)):(f.innerHTML=w.Title||"",f.className="chapter-title",v.appendChild(f)),w.Children&&w.Children.length>0&&t(v,w.Children,!0),y.appendChild(v)}Ce(y,"click",w=>{if(w.preventDefault(),w.stopPropagation(),w.target&&w.target.tagName.toLowerCase()==="a"){let v=w.target;if(v.className.indexOf("active")!==-1)this.hideView();else{let g={progression:0};if(v.href.indexOf("#")!==-1){let p=v.href.slice(v.href.indexOf("#")+1);p!==void 0&&(g={fragment:p})}let f={href:v.href,locations:g,type:v.type,title:v.title};this.hideView(),this.navigate(f)}}}),u.appendChild(y)},n=this.publication.tableOfContents,i=this.publication.landmarks,o=this.publication.pageList;this.tocView&&(n.length?t(this.tocView,n):this.tocView.parentElement?.parentElement?.removeChild(this.tocView.parentElement)),this.pageListView&&(o?.length?t(this.pageListView,o):this.pageListView.parentElement?.parentElement?.removeChild(this.pageListView.parentElement)),this.landmarksView&&(i?.length?t(this.landmarksView,i):this.landmarksSection.parentElement?.removeChild(this.landmarksSection));let s;this.annotator&&(s=await this.annotator.getLastReadingPosition());let l=this.publication.getStartLink(),h;if(l&&l.Href&&(h=this.publication.getAbsoluteHref(l.Href)),s){let u=this.publication.getAbsoluteHref(s.href);Ei.default.log(s.href),Ei.default.log(u),s.href=u,await this.navigate(s)}else if(h){let u={href:h,locations:{progression:0},created:new Date,title:l?.Title};await this.navigate(u)}return new Promise(u=>u())}catch(t){return Ei.default.error(t),this.abortOnError(t),new Promise((n,i)=>i(t)).catch(()=>{})}}async handleIFrameLoad(){this.errorMessage&&(this.errorMessage.style.display="none"),this.showLoadingMessageAfterDelay();try{let t=0;this.newPosition&&(t=this.newPosition.locations.progression),await this.handleResize(),this.updateBookView(),await this.settings.applyProperties();let n=this.currentChapterLink.href;if(n){let u=this.publication.getPreviousSpineItem(n);u&&u.Href&&(this.previousChapterLink={href:u.Href,title:u.Title,type:u.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 i=this.publication.getNextSpineItem(n);i?this.nextChapterLink={href:i.Href,title:i.Title,type:i.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(n),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let o=this.publication.getSpineItem(n);o!==void 0&&(this.currentChapterLink.title=o.Title,this.currentChapterLink.type=o.TypeLink);let s=this.publication.getTOCItem(n);this.currentTocUrl!==void 0&&(s=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&s!==void 0&&s.Title&&(this.currentChapterLink.title=s.Title),!this.currentChapterLink.type&&s!==void 0&&s.TypeLink&&(this.currentChapterLink.title=s.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),await this.injectInjectablesIntoIframeHead(),this.highlighter!==void 0&&await this.highlighter.initialize();let h=this.iframes[0].contentDocument?.body?.querySelector("details");if(h){let u=this;h.addEventListener("toggle",async d=>{await u.view?.setIframeHeight?.(this.iframes[0])})}if(this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.initialize(),this.eventHandler){for(let u of this.iframes)this.eventHandler.setupEvents(u.contentDocument),this.touchEventHandler.setupEvents(u.contentDocument),this.keyboardEventHandler.setupEvents(u.contentDocument);this.touchEventHandler.setupEvents(this.errorMessage),this.didInitKeyboardEventHandler||(this.keyboardEventHandler.keydown(document),this.didInitKeyboardEventHandler=!0)}if(this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(this.iframes[0].height="0",this.view?.setIframeHeight?.(this.iframes[0])),this.annotationModule!==void 0&&await this.annotationModule.initialize(),this.bookmarkModule!==void 0&&await this.bookmarkModule.initialize(),this.rights.enableTTS)for(let u of this.iframes){let d=u.contentDocument?.body;this.ttsModule!==void 0&&await this.ttsModule.initialize(d)}return this.timelineModule!==void 0&&await this.timelineModule.initialize(),this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&await this.mediaOverlayModule.initialize(),setTimeout(async()=>{if(this.newElementId){let u=this.iframes[0].contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(u),this.newElementId=void 0}else if(this.newPosition&&this.newPosition.highlight){let u=this.newPosition.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;u&&this.view?.goToCssSelector(u)}else t&&t>=0&&this.view?.goToProgression(t);if(this.newPosition=void 0,this.rights?.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(10),this.hideLoadingMessage(),this.showIframeContents(),this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays){let u=this.currentLink();await this.mediaOverlayModule?.initializeResource(u)}await this.updatePositionInfo(),await this.view?.setSize(),setTimeout(()=>{this.mediaOverlayModule!==void 0&&(this.mediaOverlayModule.settings.resourceReady=!0)},300)},200),new Promise(u=>u())}catch(t){return Ei.default.error(t),this.abortOnError(t),Promise.reject(t)}}async injectInjectablesIntoIframeHead(){let t=[],n=i=>{let o=new Promise((s,l)=>{i.onload=()=>{s(!0)},i.onerror=h=>{let u=typeof h=="string"?h:`Injectable failed to load at: ${"href"in i?i.href:i.src}`;l(new Error(u))}});t.push(o)};for(let i of this.iframes){let o=i.contentDocument?.head;o&&(i.contentDocument.getElementsByTagName("base").length===0&&o.insertBefore(_t.createBase(this.currentChapterLink.href),o.firstChild),this.injectables?.forEach(l=>{if(l.type==="style"){if(l.fontFamily){if(this.settings.initAddedFont(),!l.systemFont&&l.url){let h=_t.createCssLink(l.url);o.appendChild(h),n(h)}}else if(l.r2before&&l.url){let h=_t.createCssLink(l.url);o.insertBefore(h,o.firstChild),n(h)}else if(l.r2default&&l.url){let h=_t.createCssLink(l.url);o.insertBefore(h,o.childNodes[1]),n(h)}else if(l.r2after&&l.url){l.appearance&&this.settings.initAddedAppearance();let h=_t.createCssLink(l.url);o.appendChild(h),n(h)}else if(l.url){let h=_t.createCssLink(l.url);o.appendChild(h),n(h)}}else if(l.type==="script"&&l.url){let h=_t.createJavascriptLink(l.url,l.async??!1);o.appendChild(h),n(h)}}))}t.length!==0&&await Promise.all(t)}abortOnError(t){if(this.api?.onError){let n=t instanceof Error?t:typeof t=="string"?new Error(t):new Error("An unknown error occurred in the IFrameNavigator.");this.api.onError(n)}else this.errorMessage&&(this.errorMessage.style.display="block"),this.isLoading&&this.hideLoadingMessage()}tryAgain(){this.precessContentForIframe()}precessContentForIframe(){let t=this;var n=this.publication.getSpineIndex(this.currentChapterLink.href),i=(n??0)%2==1;this.showLoadingMessageAfterDelay();function o(u,d){let y=new DOMParser().parseFromString(u,"application/xhtml+xml");y.head&&y.getElementsByTagName("base").length===0&&y.head.insertBefore(_t.createBase(d),y.head.firstChild);let w=y.documentElement.outerHTML,v=t.iframes[0].contentDocument;v&&(v.open(),v.write(w),v.close())}function s(u,d){let y=new DOMParser().parseFromString(u,"application/xhtml+xml");y.head&&y.getElementsByTagName("base").length===0&&y.head.insertBefore(_t.createBase(d),y.head.firstChild);let w=y.documentElement.outerHTML,v=t.iframes[1].contentDocument;v&&(v.open(),v.write(w),v.close())}let l=new URL(this.currentChapterLink.href),h=window.location.protocol===l.protocol&&window.location.port===l.port&&window.location.hostname===l.hostname;if(this.api?.getContent)if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(u=>{u===void 0?h?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)}):o.call(this,u,this.currentChapterLink.href)}),this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let u=this.publication.getNextSpineItem(this.currentChapterLink.href);if(u){let d=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.right={href:d},this.api?.getContent(d).then(m=>{m===void 0?h?this.iframes[1].src=d:fetch(d,this.requestConfig).then(y=>y.text()).then(async y=>{s.call(this,y,d),this.currentSpreadLinks.right={href:d}}):s.call(this,m,d)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let u=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(u){let d=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.left={href:d},this.api?.getContent(d).then(m=>{m===void 0?h?this.iframes[0].src=d:fetch(d,this.requestConfig).then(y=>y.text()).then(async y=>{o.call(this,y,d)}):o.call(this,m,d)})}}else this.iframes[0].src="about:blank";this.iframes.length===2&&this.publication.isFixedLayout&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},this.api.getContent(this.currentChapterLink.href).then(u=>{u===void 0?h?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{s.call(this,d,this.currentChapterLink.href)}):s.call(this,u,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(u=>{u===void 0?h?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)}):o.call(this,u,this.currentChapterLink.href)});else this.api?.getContent(this.currentChapterLink.href).then(u=>{this.currentSpreadLinks.left={href:this.currentChapterLink.href},u===void 0?h?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)}):o.call(this,u,this.currentChapterLink.href)});else if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(h){if(this.iframes[0].src=this.currentChapterLink.href,this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let u=this.publication.getNextSpineItem(this.currentChapterLink.href);if(u){let d=this.publication.getAbsoluteHref(u.Href);this.iframes[1].src=d,this.currentSpreadLinks.right={href:d}}}else this.iframes[1].src="about:blank"}else if(fetch(this.currentChapterLink.href,this.requestConfig).then(u=>u.text()).then(async u=>{o.call(this,u,this.currentChapterLink.href)}),this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let u=this.publication.getNextSpineItem(this.currentChapterLink.href);if(u){let d=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.right={href:d},fetch(d,this.requestConfig).then(m=>m.text()).then(async m=>{s.call(this,m,d)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let u=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(u){let d=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.left={href:d},h?(this.iframes[0].src=d,this.iframes.length===2&&(this.iframes[1].src=this.currentChapterLink.href)):(fetch(d,this.requestConfig).then(m=>m.text()).then(async m=>{o.call(this,m,d)}),this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},fetch(this.currentChapterLink.href,this.requestConfig).then(m=>m.text()).then(async m=>{s.call(this,m,this.currentChapterLink.href)})))}}else this.iframes[0].src="about:blank";this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},h?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(u=>u.text()).then(async u=>{s.call(this,u,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},h?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(u=>u.text()).then(async u=>{o.call(this,u,this.currentChapterLink.href)});else this.currentSpreadLinks.left={href:this.currentChapterLink.href},h?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(u=>u.text()).then(async u=>{o.call(this,u,this.currentChapterLink.href)});this.publication.isFixedLayout&&setTimeout(()=>{let u,d,m;if(n===0&&this.iframes?.length===2?m=this.iframes[1].contentDocument:m=this.iframes[0].contentDocument,m&&m.body&&(u=getComputedStyle(m.body).height,d=getComputedStyle(m.body).width,parseInt(u?.replace("px",""))===0||parseInt(d?.replace("px",""))===0)){let b=On(m,"head");if(b){let S=$e(b,"meta[name=viewport]");if(S){var y=S.content,w=y.split(",").reduce((C,x)=>{var[E,T]=x.match(/[^\s;=]+/g);return C[E]=isNaN(Number(T))?T:+T,C},{});u=w.height+"px",d=w.width+"px"}}}var v=n===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(v&&d){var g=(parseInt(getComputedStyle(v).width)-100)/(this.iframes.length===2?parseInt(d?.replace("px",""))*2+200:parseInt(d?.replace("px",""))),f=(parseInt(getComputedStyle(v).height)-100)/parseInt(u?.replace("px","")),p=Math.min(g,f);v.style.transform="scale("+p+")";for(let b of this.iframes)b.style.height=u,b.style.width=d,b.parentElement&&(b.parentElement.style.height=u)}},400)}static goBack(){window.history.back()}handleEditClick(t){var n=t.target;if(this.headerMenu){var i=$e(document,".sidenav");n.className.indexOf(" active")===-1?(n.className+=" active",i.className+=" expanded",n.innerText="unfold_less",this.sideNavExpanded=!0,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights()):(n.className=n.className.replace(" active",""),i.className=i.className.replace(" expanded",""),n.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 n=this.publication.getSpineItem(this.currentSpreadLinks.left.href),i=this.publication.getSpineItem(this.currentSpreadLinks.right.href);return[n,i]}let t=this.currentChapterLink.href;return[this.publication.getSpineItem(t)]}tableOfContents(){return this.publication.tableOfContents}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 n=t.locations??{progression:0};if(t.href.indexOf("#")!==-1){let s=t.href.slice(t.href.indexOf("#")+1);s!==void 0&&(n=nn(dt({},n),{fragment:s}))}let i=dt({},t);i.locations=n;let o=this.publication.getAbsoluteHref(t.href);Ei.default.log(t.href),Ei.default.log(o),i.href=o,this.stopReadAloud(),this.navigate(i)}currentLocator(){let t;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let n=this.publication.positionsByHref(this.publication.getRelativeHref(this.currentChapterLink.href)),i=Math.ceil((this.view?.getCurrentPosition()??0)*(n.length-1));t=n[i]}else{let n=this.publication.getTOCItem(this.currentChapterLink.href);n&&(this.currentTocUrl!==void 0&&(n=this.publication.getTOCItem(this.currentTocUrl)),n===void 0&&(n=this.publication.getTOCItemAbsolute(this.currentChapterLink.href)),n&&(t={href:n.Href,type:this.currentChapterLink.type,title:this.currentChapterLink.title,locations:{}}))}return t&&(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?this.publication.positions:[]}goToPosition(t){if(this.publication.positions){let n=this.publication.positions.filter(i=>i.locations.position===parseInt(String(t)))[0];this.goTo(n)}}async goToPage(t){this.pageBreakModule!==void 0&&await this.pageBreakModule.goToPageNumber(t)}snapToSelector(t){let n=this.iframes[0].contentDocument;if(n){Ei.default.log(t);let i=n.querySelectorAll(t);i.length>0&&this.view?.snap(i[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 n=!0;if(this.sample?.isSampleRead&&this.publication.positions){let i=this.currentLocator(),o=Math.round((i.locations.totalProgression??0)*100);this.sample?.limit&&(n=o<=this.sample?.limit,this.view?.layout==="fixed"&&((!n&&this.sample?.minimum&&i.locations.position)??0<=(this.sample?.minimum??0))&&(n=!0))}(n&&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()))),!n&&this.sample?.isSampleRead&&this.publication.positions&&t&&(t.preventDefault(),t.stopPropagation())}handleClickThrough(t){}handleInternalLink(t){let n=t.target,i={progression:0},o=n;if(o.href.indexOf("#")!==-1){let l=o.href.slice(o.href.indexOf("#")+1);l!==void 0&&(i={fragment:l})}let s={href:o.href,locations:i,type:o.type,title:o.title};t.preventDefault(),t.stopPropagation(),this.stopReadAloud(),this.navigate(s)}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 n=document.createElement("div");this.spreads.appendChild(n),n.appendChild(this.iframes[1]),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",n.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",n.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.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 d=gr()-40-(this.attributes?.margin??0);var n=t===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(n){n.style.height=d+40+"px";let m,y,w;t===0&&this.iframes?.length===2?w=this.iframes[1].contentDocument:w=this.iframes[0].contentDocument,w&&w.body&&(m=getComputedStyle(w.body).height,y=getComputedStyle(w.body).width);let v=On(w,"head");if(v){let g=$e(v,"meta[name=viewport]");if(g){var i=g.content,o=i.split(",").reduce((f,p)=>{var[b,S]=p.match(/[^\s;=]+/g);return f[b]=isNaN(Number(S))?S:+S,f},{});(parseInt(o.height)!==0||parseInt(o.width)!==0)&&(m=o.height+"px",y=o.width+"px")}}var s=(parseInt(getComputedStyle(n).width)-100)/(this.iframes.length===2?parseInt(y?.replace("px",""))*2+200:parseInt(y?.replace("px",""))),l=(parseInt(getComputedStyle(n).height)-100)/parseInt(m?.replace("px","")),h=Math.min(s,l);n.style.transform="scale("+h+")";for(let g of this.iframes)g.style.height=m,g.style.width=y,g.parentElement&&(g.parentElement.style.height=m)}}let u=this.view?.getCurrentPosition();await this.settings.applyProperties(),this.infoTop&&(this.infoTop.style.height=0+"px"),this.infoTop&&(this.infoTop.style.minHeight=0+"px"),this.infoBottom&&(this.infoBottom.style.height=this.attributes?.bottomInfoHeight?this.attributes.bottomInfoHeight+"px":40+"px"),this.view?.layout!=="fixed"&&this.settings.isPaginated().then(d=>{d?(this.view.height=gr()-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()=>{u&&this.view?.goToProgression(u),await this.updatePositionInfo(!1),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.contentProtectionModule!==void 0&&this.contentProtectionModule.handleResize(),this.lineFocusModule!==void 0&&this.lineFocusModule.handleResize(),this.historyModule!==void 0&&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 n=this.currentLocator();if(n){let i=n.displayInfo.resourceScreenIndex,o=n.displayInfo.resourceScreenCount;this.chapterPosition&&(this.chapterPosition.innerHTML="Page "+i+" of "+o)}}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 n=this.publication.getSpineIndex(this.currentChapterLink.href)??0;n=n-2,n<0&&(n=0);let i=this.publication.readingOrder[n],o={href:this.publication.getAbsoluteHref(i.Href),locations:{progression:0},type:i.TypeLink,title:i.Title};this.stopReadAloud(),this.navigate(o)}else if(this.previousChapterLink){let n={href:this.publication.getAbsoluteHref(this.previousChapterLink.href),locations:{progression:1},type:this.previousChapterLink.type,title:this.previousChapterLink.title};this.stopReadAloud(),this.navigate(n)}t&&(t.preventDefault(),t.stopPropagation())}handleNextChapterClick(t){if(this.view?.layout==="fixed"&&this.settings.columnCount!==1){let n=this.publication.getSpineIndex(this.currentChapterLink.href)??0;n=n+2,n>=this.publication.readingOrder.length-1&&(n=this.publication.readingOrder.length-1);let i=this.publication.readingOrder[n],o={href:this.publication.getAbsoluteHref(i.Href),locations:{progression:0},type:i.TypeLink,title:i.Title};this.stopReadAloud(),this.navigate(o)}else if(this.nextChapterLink){let n={href:this.publication.getAbsoluteHref(this.nextChapterLink.href),locations:{progression:0},type:this.nextChapterLink.type,title:this.nextChapterLink.title};this.stopReadAloud(),this.navigate(n)}t&&(t.preventDefault(),t.stopPropagation())}hideView(){this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(document.body.style.overflow="auto")}setActiveTOCItem(t){if(this.tocView){let n=Array.prototype.slice.call(this.tocView.querySelectorAll("li > a"));for(let o of n)o.className=o.className.replace(" active","");let i=this.tocView.querySelector('li > a[href^="'+t+'"]');i&&(i.className+=" active")}}async navigate(t,n=!0){if(this.historyModule&&this.historyModule.push(t,n),this.publication.getTOCItem(t.href)){var o=!1;if(t.href.indexOf("#")!==-1){let s=t.href.slice(0,t.href.indexOf("#"));s===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=s,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title}else t.href===this.currentChapterLink.href&&(o=!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(o){if(t.href.indexOf("#")!==-1){let m=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:m}}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 m of this.iframes){let y=m.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(y)}this.newElementId=void 0}else if(t.highlight){let m=t.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;m&&this.view?.goToCssSelector(m)}else this.view?.goToProgression(t.locations.progression??0);let s=this.currentChapterLink.href,l=this.publication.getPreviousSpineItem(s);l&&l.Href&&(this.previousChapterLink={href:l.Href,type:l.TypeLink,title:l.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 h=this.publication.getNextSpineItem(s);h?this.nextChapterLink={href:h.Href,type:h.TypeLink,title:h.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(s),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let u=this.publication.getSpineItem(s);u!==void 0&&(this.currentChapterLink.title=u.Title,this.currentChapterLink.type=u.TypeLink);let d=this.publication.getTOCItem(s);this.currentTocUrl!==void 0&&(d=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&d!==void 0&&d.Title&&(this.currentChapterLink.title=d.Title),!this.currentChapterLink.type&&d!==void 0&&d.TypeLink&&(this.currentChapterLink.title=d.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),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&&this.contentProtectionModule.recalculate(300),this.annotationModule!==void 0&&(await this.annotationModule.drawHighlights(),await this.annotationModule.showHighlights()),this.bookmarkModule!==void 0&&(await this.bookmarkModule.drawBookmarks(),await this.bookmarkModule.showBookmarks()),this.pageBreakModule!==void 0&&(await this.highlighter?.destroyHighlights(gt.PageBreak),await this.pageBreakModule.drawPageBreaks()),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(gt.Search),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule!==void 0&&this.highlighter!==void 0&&this.definitionsModule.drawDefinitions(),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(s=>{s||(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 s=this.publication.getStartLink(),l;if(s&&s.Href&&(l=this.publication.getAbsoluteHref(s.Href),l)){let h={href:l,locations:{progression:0},created:new Date,title:s.Title};await this.navigate(h)}}}showIframeContents(){this.isBeingStyled=!1,setTimeout(()=>{this.isBeingStyled||this.iframes.forEach(t=>{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?.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 n={progression:this.view?.getCurrentPosition()};if(t){if(t.Href.indexOf("#")!==-1){let o=t.Href.slice(t.Href.indexOf("#")+1);o!==void 0&&(n={progression:this.view?.getCurrentPosition(),fragment:o})}let i;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let o=this.publication.positionsByHref(this.publication.getRelativeHref(t.Href));if(o.length>0){let s=Math.ceil((n.progression??0)*(o.length-1)),l=o[s];l&&(l.locations.fragment=n.fragment,i=nn(dt({},l),{href:t.Href,created:new Date,title:this.currentChapterLink.title}))}}else i={href:t.Href,locations:n,created:new Date,type:this.currentChapterLink.type,title:this.currentChapterLink.title};i&&(this.sample?.isSampleRead&&this.publication.positions&&this.sampleReadEventHandler?.enforceSampleRead(i),this.api?.updateCurrentLocation?this.api?.updateCurrentLocation(i).then(async o=>(Ei.default.log("api updated current location",i),this.annotator?.saveLastReadingPosition(i))):(Ei.default.log("save last reading position",i),this.annotator.saveLastReadingPosition(i)))}}}static createBase(t){let n=document.createElement("base");return n.target="_self",n.href=t,n}static createCssLink(t){let n=document.createElement("link");return n.rel="stylesheet",n.type="text/css",n.href=t,n}static createJavascriptLink(t,n){let i=document.createElement("script");return i.type="text/javascript",i.src=t,i.async=n,i}activateMarker(t,n){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId===void 0||this.annotationModule.activeAnnotationMarkerId!==t?(this.annotationModule.activeAnnotationMarkerId=t,this.annotationModule.activeAnnotationMarkerPosition=n,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 n="#",i=new Za("layer-on","layer-off",!0,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=et.R2_ID_HIGHLIGHTS_CONTAINER,i.name=et.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=et.R2_ID_READALOUD_CONTAINER,i.name=et.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=et.R2_ID_PAGEBREAK_CONTAINER,i.name=et.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=et.R2_ID_SEARCH_CONTAINER,i.name=et.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=et.R2_ID_DEFINITIONS_CONTAINER,i.name=et.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let s=$e(o,n);s&&(s.style.display="block")}}hideLayer(t){let n="#",i=new Za("layer-on","layer-off",!1,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=et.R2_ID_HIGHLIGHTS_CONTAINER,i.name=et.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=et.R2_ID_READALOUD_CONTAINER,i.name=et.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=et.R2_ID_PAGEBREAK_CONTAINER,i.name=et.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=et.R2_ID_SEARCH_CONTAINER,i.name=et.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=et.R2_ID_DEFINITIONS_CONTAINER,i.name=et.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let s=$e(o,n);s&&(s.style.display="none")}}};H();var qt=class{constructor(t){this.store=t.store}getLastReadingPosition(){let t=this.store.get(qt.LAST_READING_POSITION);return t?JSON.parse(t):null}initLastReadingPosition(t){if(typeof t=="string")this.store.set(qt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(qt.LAST_READING_POSITION,n)}}saveLastReadingPosition(t){if(typeof t=="string")this.store.set(qt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(qt.LAST_READING_POSITION,n)}}initBookmarks(t){if(typeof t=="string"){let n=JSON.parse(t);this.store.set(qt.BOOKMARKS,JSON.stringify(n))}else this.store.set(qt.BOOKMARKS,JSON.stringify(t));return t}saveBookmark(t){let n=this.store.get(qt.BOOKMARKS);if(n){let i=JSON.parse(n);i.push(t),this.store.set(qt.BOOKMARKS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(qt.BOOKMARKS,JSON.stringify(i))}return t}locatorExists(t,n){let i;switch(n){case Fi.Bookmark:i=qt.BOOKMARKS;break}let o=this.store.get(i);return o&&JSON.parse(o).filter(h=>h.href===t.href&&h.locations.progression===t.locations.progression).length>0?t:null}deleteBookmark(t){let n=this.store.get(qt.BOOKMARKS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.id!==t.id),this.store.set(qt.BOOKMARKS,JSON.stringify(i))}return t}getBookmarks(t){let n=this.store.get(qt.BOOKMARKS);if(n){let i=JSON.parse(n);if(t){let o=i.filter(s=>s.href===t);return o=o.sort((s,l)=>{if(s.locations.progression&&l.locations.progression)return s.locations.progression-l.locations.progression}),o}return i=i.sort((o,s)=>{if(o.locations.progression&&s.locations.progression)return o.locations.progression-s.locations.progression}),i}return[]}initAnnotations(t){let n;typeof t=="string"?n=JSON.parse(t):n=t;let i=[];return n.forEach(o=>{let s=`${o.highlight.selectionInfo.rangeInfo.startContainerElementCssSelector}${o.highlight.selectionInfo.rangeInfo.startContainerChildTextNodeIndex}${o.highlight.selectionInfo.rangeInfo.startOffset}${o.highlight.selectionInfo.rangeInfo.endContainerElementCssSelector}${o.highlight.selectionInfo.rangeInfo.endContainerChildTextNodeIndex}${o.highlight.selectionInfo.rangeInfo.endOffset}`,l=er.hash(s);o.highlight.id="R2_HIGHLIGHT_"+l;let h;o.highlight.color?h=o.highlight.color:o.color&&(h=o.color),ht.isHexColor(h)&&(h=ht.hexToRgbString(h)),o.highlight.color=h,o.highlight.pointerInteraction=!0,o.highlight.selectionInfo.cleanText=o.highlight.selectionInfo.rawText.trim().replace(/\n/g," ").replace(/\s\s+/g," "),i.push(o)}),this.store.set(qt.ANNOTATIONS,JSON.stringify(i)),i}saveTemporarySelectionInfo(t){this.store.set(qt.SELECTIONINFO,JSON.stringify(t))}getTemporarySelectionInfo(t){let n=this.store.get(qt.SELECTIONINFO);if(n){let i=JSON.parse(n);return i.range=qd(t,i.rangeInfo),i}return[]}deleteTemporarySelectionInfo(){this.store.remove(qt.SELECTIONINFO)}saveAnnotation(t){let n=this.store.get(qt.ANNOTATIONS);if(n){let i=JSON.parse(n);i.push(t),this.store.set(qt.ANNOTATIONS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(qt.ANNOTATIONS,JSON.stringify(i))}return t}deleteAnnotation(t){let n=this.store.get(qt.ANNOTATIONS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.id!==t),this.store.set(qt.ANNOTATIONS,JSON.stringify(i))}return t}deleteSelectedAnnotation(t){let n=this.store.get(qt.ANNOTATIONS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.highlight?.id!==t.highlight.id),this.store.set(qt.ANNOTATIONS,JSON.stringify(i))}return t}getAnnotations(){let t=this.store.get(qt.ANNOTATIONS);if(t){let n=JSON.parse(t);return n=n.sort((i,o)=>{if(i.locations.progression&&o.locations.progression)return i.locations.progression-o.locations.progression}),n}return[]}getAnnotationPosition(t,n){let i=this.store.get(qt.ANNOTATIONS);if(i){let s=JSON.parse(i).filter(l=>l.highlight?.id===t||l.id===t);if(s.length>0){let l=n.document.getElementById(`${s[0].highlight.id}`);if(l){let h=0;if(l.hasChildNodes)for(let u=0;u<l.childNodes.length;u++){let d=l.childNodes[u],m=parseInt(d.style.top.replace("px",""));(m<h||h===0)&&(h=m)}else h=parseInt(l.style.top.replace("px",""));return h}}}return null}getAnnotationElement(t,n){let i=this.store.get(qt.ANNOTATIONS);if(i){let s=JSON.parse(i).filter(l=>l.highlight?.id===t);if(s.length>0){let l=n.document.getElementById(`${s[0].highlight.id}`);if(l){let h=0;if(l.hasChildNodes)for(let u=0;u<l.childNodes.length;u++){let d=l.childNodes[u],m=parseInt(d.style.top.replace("px",""));if(m<h||h===0)return h=m,d}else h=parseInt(l.style.top.replace("px",""));return l}}}return null}getAnnotation(t){let n=this.store.get(qt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(s=>s.highlight?.id===t.id);if(o.length>0)return o[0]}return null}getAnnotationByID(t){let n=this.store.get(qt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(s=>s.highlight?.id===t);if(o.length>0)return o[0]}return null}},Uo=qt;Uo.LAST_READING_POSITION="last-reading-position",Uo.BOOKMARKS="bookmarks",Uo.ANNOTATIONS="annotations",Uo.SELECTIONINFO="selectionInfo";H();H();var mh=class{constructor(){this.store={}}get(t){return this.store[t]||null}set(t,n){this.store[t]=n}remove(t){this.store[t]=null}};var Sa=class{constructor(t){this.prefix=t.prefix,this.useLocalStorage=t.useLocalStorage;try{let n=t.prefix+"-"+String(Math.random());this.useLocalStorage?(window.localStorage.setItem(n,"test"),window.localStorage.removeItem(n)):(window.sessionStorage.setItem(n,"test"),window.sessionStorage.removeItem(n)),this.fallbackStore=null}catch(n){this.fallbackStore=new mh}}getLocalStorageKey(t){return this.prefix+"-"+t}get(t){let n;return this.fallbackStore?n=this.fallbackStore.get(t):this.useLocalStorage?n=window.localStorage.getItem(this.getLocalStorageKey(t)):n=window.sessionStorage.getItem(this.getLocalStorageKey(t)),n}set(t,n){this.fallbackStore?this.fallbackStore.set(t,n):this.useLocalStorage?window.localStorage.setItem(this.getLocalStorageKey(t),n):window.sessionStorage.setItem(this.getLocalStorageKey(t),n)}remove(t){this.fallbackStore?this.fallbackStore.remove(t):this.useLocalStorage?window.localStorage.removeItem(this.getLocalStorageKey(t)):window.sessionStorage.removeItem(this.getLocalStorageKey(t))}};H();var nx=vt(Va()),ix=vt(ii());var Ll=class extends nx.Link{};Ll=Rc([(0,ix.JsonObject)()],Ll);function Bl(r){let t,n,i,o;if(r instanceof Array)return r.map(function(s){return typeof s=="object"&&(s=Bl(s)),s});t={};for(n in r)r.hasOwnProperty(n)&&(i=(n.charAt(0).toLowerCase()+n.slice(1)||n).toString(),o=r[n],(o instanceof Array||o!==null&&o.constructor===Object)&&(o=Bl(o)),i==="href1"?t.href=o:i==="typeLink"?t.type=o:t[i]=o);return t}H();var rx=vt(dn()),Rg=class{constructor(t){this.LAYERSETTINGS="layerSetting";this.store=t,this.initialize()}static async create(t){let n=new this(t.store);return new Promise(i=>i(n))}async stop(){rx.default.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let t=new Zr,n=await this.store.get(this.LAYERSETTINGS);if(n){let i=JSON.parse(n);t.properties=i}return t}async saveProperty(t){let n=await this.store.get(this.LAYERSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),await this.store.set(this.LAYERSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),await this.store.set(this.LAYERSETTINGS,JSON.stringify(i))}return new Promise(i=>i(t))}async getProperty(t){let n=await this.store.get(this.LAYERSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}};H();var Nl=vt(dn()),Pg=class{static async create(t){let n=new this(t.delegate,t.publication,t,t.headerMenu);return await n.start(),n}constructor(t,n,i,o){this.headerMenu=o,this.delegate=t,this.publication=n,this.properties=i}async stop(){Nl.default.log("Page Break module stop")}async start(){this.delegate.pageBreakModule=this,this.headerMenu&&(this.goToPageView=$e(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=$e(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=$e(this.headerMenu,"#goToPageNumberButton")),Ce(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),Ce(this.goToPageNumberButton,"click",this.goToPageNumber.bind(this)),this.goToPageView&&(this.publication.pageList?.length||this.goToPageView.parentElement?.removeChild(this.goToPageView)),setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("pagebreak"):this.delegate.showLayer("pagebreak")},10)}async goToPageNumber(t){if(this.goToPageNumberInput.value&&(t.key==="Enter"||t.type==="click")){var n=this.publication.pageList?.filter(o=>o.Href.slice(o.Href.indexOf("#")+1).replace(/[^0-9]/g,"")===this.goToPageNumberInput.value);if(n&&n.length>0){var i=n[0];let o={progression:0};if(i.Href.indexOf("#")!==-1){let l=i.Href.slice(i.Href.indexOf("#")+1);l!==null&&(o={fragment:l})}let s={href:this.publication.getAbsoluteHref(i.Href),locations:o,type:i.TypeLink,title:i.Title};this.delegate.goTo(s)}}}async handleResize(){await this.delegate.highlighter?.destroyHighlights(gt.PageBreak),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{let t=this.delegate.iframes[0].contentDocument?.body,n=t?.querySelectorAll('[*|type="pagebreak"]');n?.length===0&&(n=t?.querySelectorAll("[epub\\:type='pagebreak']"));let i=this;function o(s){try{let l=i.delegate.iframes[0].contentDocument;return l?Nn(s,l,Lo):""}catch(l){return Nl.default.log("uniqueCssSelector:"),Nl.default.error(l),""}}if(n)for(let s=0;s<n.length;s++){let l=n[s];Nl.default.log(l);let h=l.innerHTML,u=!1;l.innerHTML.length===0&&(h=l.getAttribute("title")??"",l.innerHTML=h,u=!0),l.innerHTML.length===0&&(h=(l.getAttribute("id")??"").replace(/[^0-9]/g,""),l.innerHTML=h,u=!0);let d=this.delegate.iframes[0].contentDocument;if(d){let m=this.delegate.highlighter?.dom(d.body).getWindow().document.createRange(),y=this.delegate.highlighter?.dom(d.body).getSelection();if(y.removeAllRanges(),m.selectNodeContents(l),y.addRange(m),!y.isCollapsed){let w=oo(m,o);y.removeAllRanges(),w&&this.createPageBreakHighlight({rangeInfo:w,cleanText:"",rawText:""},h)}}u&&(l.innerHTML="")}},200)}createPageBreakHighlight(t,n){try{let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,s=er.hash(o),l="R2_PAGEBREAK_"+s;var i=!1;let h={color:"#000000",id:l,pointerInteraction:i,selectionInfo:t,marker:ot.Custom,icon:{id:"pageBreak",title:n,color:"#000000",position:"left"},type:gt.PageBreak};yn.push(h);let u=this.delegate.highlighter?.createHighlightDom(this.delegate.iframes[0].contentWindow,h);return h.position=parseInt((u?.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px","")),h}catch(o){throw"Can't create highlight: "+o}}};H();var ox=vt(_0());var sx=vt(Mo());var Et=vt(dn()),Mg=class{constructor(t,n,i,o,s,l,h){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,sx.debounce)((t,n)=>{this.restartIndex>=0?(this.ttsQueueIndex=this.restartIndex,this.restartIndex=-1):this.ttsQueueIndex=t,this.ttsQueue=n,this.ttsPlayQueueIndex(this.ttsQueueIndex,n)},150);this.delegate=t,this.tts=n,this.headerMenu=h,this.rights=i,this.highlighter=o,this.properties=s,this.api=l}initialize(t){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=t,this.clean=(0,ox.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),this.wrapper=Rt(document,"#iframe-wrapper"),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,Ce(document,"wheel",this.wheel.bind(this)),Ce(this.body,"wheel",this.wheel.bind(this)),Ce(document,"keydown",this.wheel.bind(this)),Ce(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),Ce(this.body,"mousedown",this.clickStart.bind(this)),Ce(this.body,"mouseup",this.click.bind(this)))}clickStart(t){"clientX"in t&&(this.startX=t.clientX),"clientY"in t&&(this.startY=t.clientY)}click(t){let n=0,i=0;if("clientX"in t&&(n=t.clientX),"clientY"in t&&(i=t.clientY),window.speechSynthesis.speaking&&this.speaking&&n===this.startX&&i===this.startY){let o=this.delegate.iframes[0].contentDocument;if(o){let s=this.highlighter.dom(o.body).getSelection();if(s.isCollapsed){let m=this.delegate.iframes[0].contentDocument,y=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(m);s.addRange(y.range)}let l=s.getRangeAt(0),h=s.anchorNode;for(;l.toString().indexOf(" ")!==0;)try{l.setStart(h,l.startOffset-1)}catch(m){break}l.setStart(h,l.startOffset+1);do l.setEnd(h,h.length<l.endOffset?l.endOffset+1:h.length);while(l.toString().indexOf(" ")===-1&&l.toString().trim()!=="");let d=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(this.ttsQueue&&d){let m=this.findTtsQueueItemIndex(this.ttsQueue,s.anchorNode,s.anchorNode,s.anchorOffset,d);s.removeAllRanges(),m>=0&&(window.speechSynthesis.cancel(),this.restartIndex=m,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}}}}initVoices(t){function n(){return new Promise(function(o,s){let l=window.speechSynthesis,h;h=setInterval(()=>{l.getVoices().length!==0&&(o(l.getVoices()),clearInterval(h))},10)})}n().then(async o=>{if(Et.default.log(o),this.voices=[],o.forEach(l=>{l.localService===!0&&this.voices.push(l)}),Et.default.log(this.voices),t&&this.headerMenu){var s=$e(this.headerMenu,"#preferred-languages");s&&this.voices.forEach(l=>{var h=document.createElement("option");h.value=l.name+":"+l.lang,h.innerHTML=l.name+" ("+l.lang+")",s.add(h)})}})}cancel(t=!0){t&&(this.api?.stopped&&this.api?.stopped(),this.delegate.emit("readaloud.stopped","stopped")),this.userScrolled=!1,this.speaking=!1,setTimeout(()=>{window.speechSynthesis.cancel()},0),this._ttsQueueItemHighlightsWord&&(this.delegate.highlighter?.destroyHighlights(gt.ReadAloud),this._ttsQueueItemHighlightsWord=void 0)}async speak(t,n,i){this.api?.started&&this.api?.started(),this.delegate.emit("readaloud.started","started");let o=this;this.userScrolled=!1,this.cancel(!1);let s;if(n){let S=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body,C=this.delegate.iframes[0].contentDocument;if(C){let x=this.highlighter.dom(C.body).getSelection();if(x.isCollapsed){let E=o.delegate.iframes[0].contentDocument,T=o.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(E);x.addRange(T.range)}if(S){var l=this.generateTtsQueue(S);if(!l.length)return;var h=this.findTtsQueueItemIndex(l,x.anchorNode,x.anchorNode,x.anchorOffset,S),u=this.findTtsQueueItemIndex(l,x.focusNode,x.focusNode,x.focusOffset,S);let E=_s(l,h),T=_s(l,u);var d;if(E&&t&&t.cleanText){let R=Ss(E),O=t.rangeInfo.startOffset,L=t.cleanText;if(T&&h+1===u){let k=Ss(T);O=(R+" "+k).indexOf(t.cleanText),L=R.slice(O,R.length),d=t.cleanText.replace(L,"").trim()}else if(u>h){let k="";for(let F=h+1;F<u;F++){let q=_s(l,F);if(q){let G=Ss(q);k+=G,d=t.cleanText.replace(G,"")}}if(T){let F=Ss(T);k+=" "+F}O=(R+" "+k).indexOf(t.cleanText),L=R.slice(O,R.length),d=d.replace(L,"").trim()}s=new SpeechSynthesisUtterance(L),Et.default.log(t),Et.default.log(L,t.range?.commonAncestorContainer.textContent),Et.default.log(E),Et.default.log(E.item.textNodes),Et.default.log(O),Et.default.log(E.item.combinedText);let M=E.item.textNodes.filter(k=>k===t.range?.commonAncestorContainer)[0];Et.default.log(M),s.onboundary=k=>{this.updateTTSInfo(E,k.charIndex,k.charLength,O,s.text)}}}}}else s=new SpeechSynthesisUtterance(this.clean);s.rate=this.tts.rate,s.pitch=this.tts.pitch,s.volume=this.tts.volume,Et.default.log("this.tts.voice.lang",this.tts.voice.lang);var m=!0;this.tts.voice&&this.tts.voice.lang&&(m=this.tts.voice.lang.indexOf("-")!==-1,m===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),m=!0)),Et.default.log("initialVoiceHasHyphen",m),Et.default.log("voices",this.voices);var y;m===!0?(y=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(b=>{var S=b.lang.replace("_","-");return S===this.tts.voice.lang&&b.name===this.tts.voice.name})[0]:void 0,y===void 0&&(y=this.tts.voice&&this.tts.voice.lang?this.voices.filter(b=>b.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(y=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(b=>b.lang===this.tts.voice.lang&&b.name===this.tts.voice.name)[0]:void 0,y===void 0&&(y=this.tts.voice&&this.tts.voice.lang?this.voices.filter(b=>b.lang===this.tts.voice.lang)[0]:void 0)),Et.default.log("initialVoice",y);var w=o.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;Et.default.log("publicationVoiceHasHyphen",w);var v;w===!0?v=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(b=>{var S=b.lang.replace("_","-");return S.startsWith(o.delegate.publication.Metadata.Language[0])||S.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:v=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(b=>b.lang.startsWith(o.delegate.publication.Metadata.Language[0])||b.lang.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Et.default.log("publicationVoice",v);var g=navigator.language.indexOf("-")!==-1;Et.default.log("defaultVoiceHasHyphen",g);var f;g===!0?f=this.voices.filter(b=>{var S=b.lang.replace("_","-");return S===navigator.language&&b.localService===!0})[0]:f=this.voices.filter(b=>{var S=b.lang;return S===navigator.language&&b.localService===!0})[0],f===void 0&&(f=this.voices.filter(b=>{var S=b.lang;return S.includes(navigator.language)&&b.localService===!0})[0]),Et.default.log("defaultVoice",f),y?(Et.default.log("initialVoice"),s.voice=y):v?(Et.default.log("publicationVoice"),s.voice=v):f&&(Et.default.log("defaultVoice"),s.voice=f),s.voice!==void 0&&s.voice!==null&&(s.lang=s.voice.lang,Et.default.log("utterance.voice.lang",s.voice.lang),Et.default.log("utterance.lang",s.lang)),Et.default.log("navigator.language",navigator.language),setTimeout(()=>{window.speechSynthesis.speak(s)},0),this.index=0;function p(){s.onend=function(){if(u>h)if(h=h+1,h!==u){let b=_s(l,h);if(b){let S=Ss(b);s=new SpeechSynthesisUtterance(S),s.onboundary=C=>{o.updateTTSInfo(b,C.charIndex,C.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s)},0),p()}}else{let b=_s(l,h);b&&(s=new SpeechSynthesisUtterance(d),s.onboundary=S=>{o.updateTTSInfo(b,S.charIndex,S.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s)},0),p()),h>u&&(Et.default.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.delegate.emit("readaloud.finished","finished"))}else Et.default.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.delegate.emit("readaloud.finished","finished")}}p(),i()}speakPlay(){this.scrollPartial=!0,this.cancel(!1),this.api?.started&&this.api?.started(),this.delegate.emit("readaloud.started","started");let t=this,i=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(i){let l=function(){let h=t.highlighter.visibleTextRects[0],u=t.delegate.iframes[0].contentDocument;if(u){let d=t.highlighter.dom(u.body).getWindow().document.createRange(),m=t.highlighter.dom(t.delegate.iframes[0].contentDocument?.body).getSelection();m.removeAllRanges(),d.selectNodeContents(h.node),m.addRange(d);let y=0,w=m.focusNode,v=m.focusOffset;m.collapse(m.anchorNode,m.anchorOffset);for(let g=0;g<y;g++)m.modify("move","forward","line");if(m.extend(w,v),m.collapse(m.anchorNode,m.anchorOffset),i){let g=t.findTtsQueueItemIndex(o,m.anchorNode,m.anchorNode,m.anchorOffset,i);g>=0&&(s=g)}m.removeAllRanges()}},o=this.generateTtsQueue(i);if(!o.length)return;let s=0;l(),s<0&&(s=0),setTimeout(()=>{this.startTTSSession(o,s)},200)}}speakPause(){window.speechSynthesis.speaking&&(this.api?.paused&&this.api?.paused(),this.delegate.emit("readaloud.paused","paused"),this.userScrolled=!1,window.speechSynthesis.pause(),this.speaking=!1,this._ttsQueueItemHighlightsWord&&(this.delegate.highlighter?.destroyHighlights(gt.ReadAloud),this._ttsQueueItemHighlightsWord=void 0))}speakResume(){window.speechSynthesis.speaking&&(this.api?.resumed&&this.api?.resumed(),this.delegate.emit("readaloud.resumed","resumed"),this.userScrolled=!1,window.speechSynthesis.resume(),this.speaking=!0)}static async create(t){let n=new this(t.delegate,t.tts,t.rights,t.highlighter,t,t.api,t.headerMenu);return await n.start(),n}async start(){if(this.delegate.ttsModule=this,this.headerMenu){var t=$e(this.headerMenu,"#menu-button-tts");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties?.hideLayer?this.delegate.hideLayer("readaloud"):this.delegate.showLayer("readaloud")},10)}wheel(t){if(t instanceof KeyboardEvent)switch(t.key){case"ArrowUp":this.userScrolled=!0;break;case"ArrowDown":this.userScrolled=!0;break}else this.userScrolled=!0}stop(){Et.default.log("TTS module stop"),ze(document,"wheel",this.wheel.bind(this)),ze(this.body,"wheel",this.wheel.bind(this)),ze(document,"keydown",this.wheel.bind(this)),ze(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),ze(this.body,"click",this.click.bind(this))}generateTtsQueue(t){let n=[],i=[];function o(u){if(u.nodeType!==Node.TEXT_NODE||!u.nodeValue||!u.nodeValue.trim().length)return;let d=i[i.length-1];if(!d)return;let m=u.parentElement?ax(u.parentElement):void 0,y=u.parentElement?QD(u.parentElement):void 0,w=n[n.length-1];(!w||w.parentElement!==d||w.lang!==m||w.dir!==y)&&(w={combinedText:"",dir:y,lang:m,parentElement:d,textNodes:[]},n.push(w)),w.textNodes.push(u)}let s=!0;function l(u){if(u.nodeType!==Node.ELEMENT_NODE)return;let d=s||u.matches("h1, h2, h3, h4, h5, h6, p, th, td, caption, li, blockquote, q, dt, dd, figcaption, div, pre");s=!1,d&&i.push(u);for(let m of u.childNodes)switch(m.nodeType){case Node.ELEMENT_NODE:let y=m;if(!y.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))l(y);else if(y.tagName&&y.tagName.toLowerCase()==="img"&&y.src){let v=y.getAttribute("alt");if(v){let g=v.trim();if(g){let f=ax(y),p=void 0;n.push({combinedText:g,dir:p,lang:f,parentElement:y,textNodes:[]})}}}break;case Node.TEXT_NODE:i.length!==0&&o(m);break;default:break}d&&i.pop()}l(t);function h(u){if(!u.textNodes||!u.textNodes.length){(!u.combinedText||!u.combinedText.length)&&(u.combinedText="");return}u.combinedText=e8(u.textNodes,!0).replace(/[\r\n]/g," ");let d=u.parentElement;for(;d;){if(d.tagName){let m=d.tagName.toLowerCase();if(m==="pre"||m==="code"||m==="video"||m==="audio")break}d=d.parentElement}}for(let u of n)h(u);return n}findTtsQueueItemIndex(t,n,i,o,s){let l=0;for(let h of t){if(i&&h.textNodes){if(h.textNodes.includes(i))return l}else if(n===h.parentElement||h.parentElement!==n.ownerDocument.body&&h.parentElement!==s&&h.parentElement.contains(n)||n.contains(h.parentElement))return l;l++}return-1}restart(){window.speechSynthesis.speaking&&(window.speechSynthesis.cancel(),this.restartIndex=this.ttsQueueIndex,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}startTTSSession(t,n){if(!_s(t,n)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(n,t)}ttsPlayQueueIndex(t,n){if(t<0){this.cancel();return}let i=_s(n,t);if(!i){this.cancel();return}let o=Ss(i);if(!o){this.cancel();return}let s=new SpeechSynthesisUtterance(o);s.rate=this.tts.rate,s.pitch=this.tts.pitch,s.volume=this.tts.volume,Et.default.log("this.tts.voice.lang",this.tts.voice.lang);var l=!0;this.tts.voice&&this.tts.voice.lang&&(l=this.tts.voice.lang.indexOf("-")!==-1,l===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),l=!0)),Et.default.log("initialVoiceHasHyphen",l),Et.default.log("voices",this.voices);var h;l===!0?(h=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(v=>{var g=v.lang.replace("_","-");return g===this.tts.voice.lang&&v.name===this.tts.voice.name})[0]:void 0,h===void 0&&(h=this.tts.voice&&this.tts.voice.lang?this.voices.filter(v=>v.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(h=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(v=>v.lang===this.tts.voice.lang&&v.name===this.tts.voice.name)[0]:void 0,h===void 0&&(h=this.tts.voice&&this.tts.voice.lang?this.voices.filter(v=>v.lang===this.tts.voice.lang)[0]:void 0)),Et.default.log("initialVoice",h);var u=this,d=u.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;Et.default.log("publicationVoiceHasHyphen",d);var m;d===!0?m=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(v=>{var g=v.lang.replace("_","-");return g.startsWith(u.delegate.publication.Metadata.Language[0])||g.endsWith(u.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:m=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(v=>v.lang.startsWith(u.delegate.publication.Metadata.Language[0])||v.lang.endsWith(u.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Et.default.log("publicationVoice",m);var y=navigator.language.indexOf("-")!==-1;Et.default.log("defaultVoiceHasHyphen",y);var w;y===!0?w=this.voices.filter(v=>{var g=v.lang.replace("_","-");return g===navigator.language&&v.localService===!0})[0]:w=this.voices.filter(v=>{var g=v.lang;return g===navigator.language&&v.localService===!0})[0],w===void 0&&(w=this.voices.filter(v=>{var g=v.lang;return g.includes(navigator.language)&&v.localService===!0})[0]),Et.default.log("defaultVoice",w),h?(Et.default.log("initialVoice"),s.voice=h):m?(Et.default.log("publicationVoice"),s.voice=m):w&&(Et.default.log("defaultVoice"),s.voice=w),s.voice!==void 0&&s.voice!==null&&(s.lang=s.voice.lang,Et.default.log("utterance.voice.lang",s.voice.lang),Et.default.log("utterance.lang",s.lang)),Et.default.log("navigator.language",navigator.language),s.onboundary=v=>{Et.default.log(v.name),this.updateTTSInfo(i,v.charIndex,v.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s),u.speaking||window.speechSynthesis.pause()},0),s.onend=function(){u.speaking&&u.ttsPlayQueueIndexDebounced(t+1,n)}}updateTTSInfo(t,n,i,o,s){if(!t)return;Et.default.log(t,n,i,s);let l=s||Ss(t);if(n>=0&&s){let h=s.slice(0,n+1).search(/\S+$/),u=s.slice(n).search(/\s/),d=u<0?s.slice(h):s.slice(h,u+n),m=h+d.length;if(i===void 0){let y=s.substring(n).match(/^[a-z\d']*/i);y&&(i=y[0].length)}i===void 0&&(i=d.length),this.wrapHighlightWord(t,s,n+o,i,d,h,m)}return l}wrapHighlightWord(t,n,i,o,s,l,h){Et.default.log(t),Et.default.log(n),Et.default.log(i,o,s,l,h),this._ttsQueueItemHighlightsWord&&(this.delegate.highlighter?.destroyHighlights(gt.ReadAloud),this._ttsQueueItemHighlightsWord=void 0);let u=t.item,d=i,m=0,y,w=-1,v,g=-1,f=d+o;for(let b of u.textNodes){if(!b.nodeValue&&b.nodeValue!=="")continue;let S=b.nodeValue.length;if(m+=S,y||d<m&&(y=b,w=S-(m-d)),y&&f<=m&&(v=b,g=S-(m-f)),v)break}if(y&&v){let S=function(E){try{let T=p.delegate.iframes[0].contentDocument;return T?Nn(E,T,Lo):""}catch(T){return Et.default.log("uniqueCssSelector:"),Et.default.error(T),""}},b=new Range;b.setStart(y,w),b.setEnd(v,g);var p=this;let C=oo(b,S);if(!C)return;let x=this.delegate.highlighter?.createHighlight(this.delegate.iframes[0].contentWindow,{rangeInfo:C,cleanText:"",rawText:"",range:void 0},this.tts.color,!1,ot.Custom,{id:"tts",title:"",position:"right"},void 0,{defaultClass:this.tts.color},gt.ReadAloud,"R2_READALOUD_");if(x){this._ttsQueueItemHighlightsWord=x[0];let R=(x[1]?.firstChild?.getBoundingClientRect()).top-this.wrapper.scrollTop>window.innerHeight/2-65;this.delegate.view?.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&this.scrollPartial&&R?x[1]?.firstChild?.scrollIntoView({block:"center",behavior:"smooth"}):this.delegate.view?.isPaginated()&&p.delegate.view?.snap(x[1]?.firstChild)}}}};function ax(r){let t=r;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let n=t.getAttribute("xml:lang");if(n||(n=t.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang")),n||(n=t.getAttribute("lang")),n)return n;t=t.parentNode}}function QD(r){let t=r;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let n=t.getAttribute("dir");if(n)return n;t=t.parentNode}}function e8(r,t){if(r&&r.length){let n="";for(let i of r)i.nodeValue&&(n+=t?i.nodeValue:n8(i.nodeValue));return n}return""}function t8(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function n8(r){return t8(r).replace(/\n/g," ").replace(/\s\s+/g," ")}function _s(r,t){let n=-1,i=-1;for(let o of r)if(i++,n++,t===n)return{item:o,iArray:i,iGlobal:n,iSentence:-1}}function Ss(r){return r.item.combinedText}H();var Dl=vt(zd());var lx=vt(Mo());var cx=vt(dn()),kg=class{constructor(t,n,i,o,s){this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,lx.debounce)(async()=>{if(await this.highlighter.destroyHighlights(gt.Definition),this.properties.definitions)for(let t of this.properties.definitions)await this.define(t)},200);this.delegate=t,this.publication=n,this.properties=i,this.api=s,this.highlighter=o}static async create(t){let n=new this(t.delegate,t.publication,t,t.highlighter,t.api);return await n.start(),n}async stop(){cx.default.log("Definitions module stop")}async start(){this.delegate.definitionsModule=this,setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("definitions"):this.delegate.showLayer("definitions")},10)}async searchAndPaint(t,n){let i=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[this.delegate.currentResource()??0].Href:""),o=this.publication.getTOCItem(i);o===void 0&&this.publication.readingOrder&&(o=this.publication.readingOrder[this.delegate.currentResource()??0]);let s=[];if(o)for(let l of t.terms){let h=t.terms.indexOf(l);o&&await jo(l,this.delegate.iframes[0].contentDocument,o.Href,o.Title,this.delegate.definitionsModule?.properties.fullWordSearch).then(u=>{let d;t.result===1?d=0:t.result===2&&(d=Math.floor(Math.random()*u.length-1)+1),u.forEach((m,y)=>{if(d===void 0||d===y){let w={rangeInfo:m.rangeInfo},v=this.createDefinitionHighlight(w,t);m.highlight=v,s.push(Dl.omit(v,"definition")),this.currentChapterPopupResult.push(m),this.currentPopupHighlights.push(v)}}),h===t.terms.length-1&&n(s)})}}async define(t){await this.searchAndPaint(t,async n=>{this.api?.success&&(this.api?.success(Dl.omit(t,"callbacks"),n),this.delegate.emit("definition.success",n),this.api?.visible&&n.forEach(i=>{let s=this.delegate.iframes[0].contentDocument?.querySelector(`#${i.id}`)?.querySelectorAll(`.${$n}`),l=new IntersectionObserver((h,u)=>{h.forEach(d=>{d.intersectionRatio===1&&(this.api?.visible(Dl.omit(t,"callbacks"),Dl.omit(i,"definition")),this.delegate.emit("definition.visible",t,i))})},{threshold:1});s&&s.length>0&&l.observe(s[0])}))})}async drawDefinitions(){setTimeout(async()=>{await this.definitions()},100)}async handleResize(){await this.drawDefinitions()}createDefinitionHighlight(t,n){try{let i=this.delegate.definitionsModule?.properties.color;ht.isHexColor(i)&&(i=ht.hexToRgbChannels(i));let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,s=er.hash(o),l="R2_DEFINITION_"+s;this.highlighter.destroyHighlight(this.delegate.iframes[0].contentDocument,l);let h={color:i||gs,id:l,pointerInteraction:!0,selectionInfo:t,marker:ot.Underline,type:gt.Definition};yn.push(h);let u=this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,h);return u&&(n.definition&&(u.dataset.definition=n.definition),u.dataset.order=String(n.order),h.definition=n,h.position=parseInt((u?.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px",""))),h}catch(i){throw"Can't create definitions highlight: "+i}}async addDefinition(t){await this.define(t)}async clearDefinitions(){await this.highlighter.destroyHighlights(gt.Definition)}};H();var $o=vt(dn()),ux=.5,yh=class{constructor(t,n,i,o){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.delegate=t,this.properties=n,this.api=o,this.highlighter=i}static async create(t){let n=new this(t.delegate,t,t.highlighter,t.api);return await n.start(),n}async stop(){$o.default.log("Definitions module stop"),this.hasEventListener=!1,ze(document,"keydown",this.keydown.bind(this)),ze(document,"keyup",this.keyup.bind(this)),ze(this.delegate.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),ze(this.delegate.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){this.delegate.lineFocusModule=this;let t=Rt(document,"#iframe-wrapper");t.style.height.length>0&&(this.wrapperHeight=t.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")),this.hasEventListener||(this.hasEventListener=!0,Ce(document,"keydown",this.keydown.bind(this)),Ce(document,"keyup",this.keyup.bind(this)),Ce(this.delegate.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),Ce(this.delegate.iframes[0].contentDocument,"keyup",this.keyup.bind(this)))}keydown(t){if(t instanceof KeyboardEvent&&this.isActive)switch(t.key){case"ArrowUp":t.stopPropagation();break;case"ArrowDown":t.stopPropagation();break}}keyup(t){if(t instanceof KeyboardEvent&&this.isActive)switch(t.key){case"ArrowUp":this.lineUp();break;case"ArrowDown":this.lineDown();break}}handleResize(){this.isActive&&this.lineFocus()}async enableLineFocus(){this.isActive=!0,await this.delegate.settings.scroll(!0),this.lineFocus()}disableLineFocus(t=!0){this.isActive=!1;let n=Rt(document,"#iframe-wrapper");this.wrapperHeight&&(n.style.height=this.wrapperHeight),t||(this.index=0);let i=this.delegate.iframes[0].contentDocument;On(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 l=document.getElementById("divBefore");l&&l.remove();let h=document.getElementById("divAfter");h&&h.remove(),this.highlighter.destroyHighlights(gt.LineFocus)}lineFocus(){let t=Rt(document,"#iframe-wrapper"),n=this.delegate.iframes[0].contentDocument,i=On(n,"html"),o=this.properties.maxHeight?gr()*this.properties.maxHeight/100:gr()/2;i.style.setProperty("--USER__maxMediaHeight",o+"px");function s(m,y){m.parentNode.insertBefore(y,m.nextSibling)}function l(m,y){m.parentNode.insertBefore(y,m)}let h=document.getElementById("container-view-timeline");h&&(h.style.display="none"),this.lineFocusContainer&&this.lineFocusContainer.style.removeProperty("display");let u=document.getElementById("divBefore");if(u)u.style.height=t.clientHeight/2+"px";else{let m=document.createElement("div");m.style.height=t.clientHeight/2+"px",m.id="divBefore",l(t,m)}let d=document.getElementById("divAfter");if(d)d.style.height=t.clientHeight/2+"px";else{let m=document.createElement("div");m.style.height=t.clientHeight/2+"px",m.id="divAfter",s(t,m)}if(this.lines=[],n){let w=function(){let S=Math.round,C=Math.random,x=255;return{blue:S(C()*x),green:S(C()*x),red:S(C()*x)}},v=function(S,C){let x=[];for(let E=0,T=0;E<S.length;E++)E>=C&&E%C==0&&T++,x[T]=x[T]||[],x[T].push(S[E]);return x},g=function(S,C){let x=Math.min(S.left,C.left),E=Math.max(S.right,C.right),T=Math.min(S.top,C.top),R=Math.max(S.bottom,C.bottom);return{bottom:R,height:R-T,left:x,right:E,top:T,width:E-x}},f=function(S){if(S.length>1){let C=g(S[0],S[1]);if(S.length>2){let x=g(C,S[2]);if(S.length>3){let E=g(x,S[3]);return S.length>4?g(E,S[4]):E}return x}return C}return S[0]},m=this.findRects(n.body);m=O0(m,!0),m=m.sort(function(S,C){return S.top-C.top});let y=[];m=m.filter(function(S){let C=S.top;return y.indexOf(C)===-1&&y.indexOf(C+1)===-1&&y.indexOf(C+2)===-1&&y.indexOf(C+3)===-1&&y.indexOf(C+4)===-1&&y.indexOf(C-1)===-1&&y.indexOf(C-2)===-1&&y.indexOf(C-3)===-1&&y.indexOf(C-4)===-1?(y.push(C),!0):!1}),this.highlighter.destroyHighlights(gt.LineFocus);let p=[];this.properties.lines&&this.properties.lines>1?v(m,this.properties.lines).forEach(C=>{p.push(f(C))}):p=m;let b=$e(n,"#"+et.R2_ID_LINEFOCUS_CONTAINER);if(b)for(let S of p){let C=document.createElement("div");C.setAttribute("class",$n);let x=w();if(ht.isHexColor(x)&&(x=ht.hexToRgbChannels(x)),this.isDebug){let ce=`border-bottom: 1px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${ux}) !important`;C.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${ux}) !important; ${ce}`)}C.style.outline="none",C.tabIndex=0;let E=this.delegate.iframes[0].contentWindow.document,T=this.delegate.view.isPaginated();T?E.body.style.position="revert":E.body.style.position="relative";let R=E.body.getBoundingClientRect(),O=this.highlighter.getScrollingElement(E),L=T?-O.scrollLeft:R.left,M=T?-O.scrollTop:R.top,k=1,F=24,q,G,ie=this.delegate.iframes[0].contentWindow?.innerWidth,ee=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-count")),Q=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-width")),X=parseInt(getComputedStyle(n.body).getPropertyValue("padding-left"));if(ie){let ce=ie/(ee||1);ce<Q&&(ce=ie),T||(ce=parseInt(getComputedStyle(n.body).width.replace("px","")));let we=this.delegate.settings.fontSize/100,ve=20*we;we<=1&&(ve=-60);let Z=0;we<=1&&(Z=-60),q=Math.floor(S.left/ce)*ce+ce-(F<40?40:F)+Z,G=Math.floor(S.left/ce)*ce+(F<40?40:F)-ve;let N=parseInt(n.documentElement.style.getPropertyValue("--USER__pageMargins"));N>=2&&(G=G+X/ee,q=q-X/ee),T||(q=parseInt(getComputedStyle(n.body).width.replace("px","")),G=parseInt(getComputedStyle(n.body).width.replace("px",""))-ce,N>=2&&(G=G+X/2,q=q-X/2))}C.style.setProperty("pointer-events","none"),C.style.position="absolute",C.scale=k,C.rect={height:S.height,left:S.left-L,top:S.top-M,width:S.width},C.style.width=`${C.rect.width*k}px`,C.style.height=`${C.rect.height*k}px`,C.style.left=`${C.rect.left*k}px`,C.style.top=`${C.rect.top*k}px`,this.lines.push(C),b.append(C)}setTimeout(()=>{this.currentLine()},100)}}currentLine(){let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.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 t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}}lineUp(){if(this.index>0){this.index-=1,this.index<0&&(this.index=0);let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}}almostEqual(t,n,i){return Math.abs(t-n)<=i}findRects(t){let n=this.findTextNodes(t),i=Array.from(t.getElementsByTagName("img")),o=[];return n.forEach(s=>{o.push(...this.measureTextNodes(s))}),i.forEach(s=>{o.push(...this.measureImageNodes(s))}),o}findTextNodes(t,n=[]){let i=t.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,n),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"&&n.push(i),i=i.nextSibling;return n}measureTextNodes(t){try{let n=document.createRange();n.selectNodeContents(t);let i=Array.from(n.getClientRects());return n.detach(),i}catch(n){$o.default.log("measureTextNode "+n),$o.default.log("measureTextNode "+t),$o.default.log(`${t.textContent}`)}}measureImageNodes(t){try{let n=document.createRange();n.selectNode(t);let i=Array.from(n.getClientRects());return n.detach(),i}catch(n){$o.default.log("measureTextNode "+n),$o.default.log("measureTextNode "+t),$o.default.log(`${t.textContent}`)}}};H();var bh=vt(dn()),Ig=class{constructor(t,n,i,o,s){this.history=[];this.headerMenu=s,this.delegate=n,this.publication=i,this.properties=o,this.annotator=t}static async create(t){let n=new this(t.annotator,t.delegate,t.publication,t,t.headerMenu);return await n.start(),n}async stop(){bh.default.log("Page Break module stop"),ze(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),ze(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(t,n){let i;if(n&&this.annotator){let o=await this.annotator.getLastReadingPosition();if(o&&o.locations.progression&&o.locations.progression>0&&(this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex)),i=this.history[this.history.length-1],i&&i.href!==o.href||i===void 0)){let s=this.publication.getAbsoluteHref(o.href);bh.default.log(o.href),bh.default.log(s),o.href=s,this.history.push(o),this.historyCurrentIndex=this.history.length-1}this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex)),i=this.history[this.history.length-1],(i&&i.href!==t.href||i===void 0)&&(this.history.push(t),this.historyCurrentIndex=this.history.length-1)}}async start(){this.delegate.historyModule=this,this.headerMenu&&(this.historyForwardAnchorElement=$e(this.headerMenu,"#history-forward")),this.headerMenu&&(this.historyBackAnchorElement=$e(this.headerMenu,"#history-back")),this.historyCurrentIndex=this.history.length-1,Ce(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),Ce(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleHistoryForwardClick(t){this.history.length>0&&this.historyCurrentIndex+1<this.history.length&&(this.historyCurrentIndex=this.historyCurrentIndex+1,await this.delegate.navigate(this.history[this.historyCurrentIndex],!1)),t.preventDefault(),t.stopPropagation()}async handleHistoryBackClick(t){this.history.length>0&&this.historyCurrentIndex>0&&(this.historyCurrentIndex=this.historyCurrentIndex-1,await this.delegate.navigate(this.history[this.historyCurrentIndex],!1)),t.preventDefault(),t.stopPropagation()}};H();var dx=vt(dn()),Pt;(function(i){i[i.Chicago=0]="Chicago",i[i.MLA=1]="MLA",i[i.APA=2]="APA"})(Pt||(Pt={}));var hx;(function(o){o.Author="Author",o.Editor="Editor",o.Translator="Translator",o.Compiler="Compiler"})(hx||(hx={}));var vh=class{constructor(t,n,i,o,s){this.highlighter=i,this.delegate=t,this.properties=o,this.publication=n,this.api=s}static async create(t){let n=new this(t.delegate,t.publication,t.highlighter,t,t.api);return await n.start(),n}async stop(){dx.default.log("Citation module stop")}copyToClipboard(t){this.delegate?.contentProtectionModule&&(this.delegate.contentProtectionModule.citation=!0);let n=!0;if(window.clipboardData)window.clipboardData.setData("text/plain",t);else{let i=this.createElementForExecCommand(t);this.selectContent(i);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),n=document.execCommand("copy",!1)}catch(o){n=!1}document.body.removeChild(i)}n?this.api?.citationCreated("The text was copied to the clipboard!"):this.api?.citationFailed("Your browser doesn't allow clipboard access!")}createElementForExecCommand(t){let n=document.createElement("div");return n.style.position="absolute",n.style.left="-10000px",n.style.top="-10000px",n.innerHTML=t,document.body.appendChild(n),n.contentEditable=!0,n}selectContent(t){let n=document.createRange();n.selectNodeContents(t);let i=window.getSelection();i?.removeAllRanges(),i?.addRange(n)}async start(){this.delegate.citationModule=this;let t=this,n={id:"citationIcon",callback:function(i){let o=function(){let O="",L="",M="";return t.properties.author?(M=M+t.properties.author,L=L+t.properties.author,O=O+t.properties.author):t.publication.Metadata.Author?.length>0&&0===0&&t.publication.Metadata.Author[0].Name&&t.publication.Metadata.Author[0].Name.length>0&&(M=M+t.publication.Metadata.Author[0].Name,L=L+t.publication.Metadata.Author[0].Name,O=O+t.publication.Metadata.Author[0].Name),M.length>0&&L.length>0&&O.length>0?[O+". ",L+". ",M+". "]:["","",""]},s=function(){let O="",L="",M="";return t.properties.publisher?(L=L+t.properties.publisher+", ",O=O+t.properties.publisher+", "):t.publication.Metadata.Publisher&&t.publication.Metadata.Publisher[0].Name&&(L=L+t.publication.Metadata.Publisher[0].Name+", ",O=O+t.publication.Metadata.Publisher[0].Name+", "),t.properties.published?(M=M+"("+t.properties.published+")",L=L+t.properties.published,O=O+t.properties.published):t.publication.Metadata.PublicationDate&&t.publication.Metadata.PublicationDate.getFullYear()>0&&(M=M+"("+t.publication.Metadata.PublicationDate.getFullYear()+")",L=L+t.publication.Metadata.PublicationDate.getFullYear(),O=O+t.publication.Metadata.PublicationDate.getFullYear()),M.length>0&&L.length>0&&O.length>0?[O+". ",L+". ",M+". "]:["","",""]},l=function(){return t.properties.title?[t.properties.title+". ",t.properties.title+". ",t.properties.title+". "]:t.publication.Metadata.Title?[t.publication.Metadata.Title+". ",t.publication.Metadata.Title+". ",t.publication.Metadata.Title+". "]:["","",""]},h=function(){return["","",""]},u=function(){let O="",L="",M="";return t.properties.publisher?(L=L+t.properties.publisher+", ",O=O+t.properties.publisher+", ",M=M+t.properties.publisher+", "):t.publication.Metadata.Publisher&&t.publication.Metadata.Publisher[0].Name&&(L=L+t.publication.Metadata.Publisher[0].Name+", ",O=O+t.publication.Metadata.Publisher[0].Name+", ",M=M+t.publication.Metadata.Publisher[0].Name+", "),M.length>0&&L.length>0&&O.length>0?[O+". ",L+". ",M+". "]:["","",""]},d=function(){return["","",""]},m=function(){return["","",""]},y=function(){return["","",""]},w=function(){return t.properties.library?["Retrieved from "+t.properties.library+". ","Retrieved from "+t.properties.library+". ","Retrieved from "+t.properties.library+". "]:["","",""]},v=function(){return t.properties.appName?[t.properties.appName+". ",t.properties.appName+". ",t.properties.appName+". "]:["","",""]},g=function(){return t.properties.appLink?[t.properties.appLink+". ",t.properties.appLink+". ",t.properties.appLink+". "]:["","",""]},f=function(){return["","",""]},p=function(O,L){return O.length>L?O.substring(0,L)+"...":O},b=o()[0]+l()[0]+d()[0]+h()[0]+y()[0]+s()[0]+m()[0]+w()[0]+v()[0]+g()[0],S=o()[2]+s()[2]+l()[2]+h()[2]+u()[2]+d()[2]+m()[2]+y()[2]+w()[2]+v()[2]+g()[2],C=o()[1]+l()[1]+d()[1]+h()[1]+y()[1]+s()[1]+f()[1]+w()[1]+v()[1]+g()[1],x="\u201C"+p(i,t.properties.characters)+"\u201C<br><br><em>"+b+"</em>",E="\u201C"+p(i,t.properties.characters)+"\u201C<br><br><em>"+S+"</em>",T="\u201C"+p(i,t.properties.characters)+"\u201C<br><br><em>"+C+"</em>",R="";t.properties.styles?.includes(Pt[0])&&(R=R+"Chicago: <br>"+x+"<br><br>"),t.properties.styles?.includes(Pt[2])&&(R=R+"APA: <br>"+E+"<br><br>"),t.properties.styles?.includes(Pt[1])&&(R=R+"MLA: <br>"+T+"<br><br>"),t.copyToClipboard(R)}};this.highlighter?.addSelectionMenuItem(n)}};H();var Nx=vt(Og()),Aa=vt(Lx());H();var Bx="grab-to-pan-grab",_h,S8,Sh,A8,Ah,x8,jg=class{constructor(t){ke(this,_h);ke(this,Sh);ke(this,Ah);this.element=t.element,this.document=t.element.ownerDocument,typeof t.ignoreTarget=="function"&&(this.ignoreTarget=t.ignoreTarget),this.onActiveChanged=t.onActiveChanged,this.activate=this.activate.bind(this),this.deactivate=this.deactivate.bind(this),this.toggle=this.toggle.bind(this),this._onMouseDown=De(this,_h,S8).bind(this),this._onMouseMove=De(this,Sh,A8).bind(this),this._endPan=De(this,Ah,x8).bind(this);let n=this.overlay=document.createElement("div");n.className="grab-to-pan-grabbing"}activate(){this.active||(this.active=!0,this.element.addEventListener("mousedown",this._onMouseDown,!0),this.element.classList.add(Bx),this.onActiveChanged?.(!0))}deactivate(){this.active&&(this.active=!1,this.element.removeEventListener("mousedown",this._onMouseDown,!0),this._endPan(),this.element.classList.remove(Bx),this.onActiveChanged?.(!1))}toggle(){this.active?this.deactivate():this.activate()}ignoreTarget(t){return t.matches("a[href], a[href] *, input, textarea, button, button *, select, option")}};_h=new WeakSet,S8=function(t){if(t.button!==0||this.ignoreTarget(t.target))return;if(t.originalTarget)try{t.originalTarget.tagName}catch(i){return}this.scrollLeftStart=this.element.scrollLeft,this.scrollTopStart=this.element.scrollTop,this.clientXStart=t.clientX,this.clientYStart=t.clientY,this.document.addEventListener("mousemove",this._onMouseMove,!0),this.document.addEventListener("mouseup",this._endPan,!0),this.element.addEventListener("scroll",this._endPan,!0),t.preventDefault(),t.stopPropagation();let n=document.activeElement;n&&!n.contains(t.target)&&n.blur()},Sh=new WeakSet,A8=function(t){if(this.element.removeEventListener("scroll",this._endPan,!0),!(t.buttons&1)){this._endPan();return}let n=t.clientX-this.clientXStart,i=t.clientY-this.clientYStart,o=this.scrollTopStart-i,s=this.scrollLeftStart-n;this.element.scrollTo?this.element.scrollTo({top:o,left:s,behavior:"instant"}):(this.element.scrollTop=o,this.element.scrollLeft=s),this.overlay.parentNode||document.body.append(this.overlay)},Ah=new WeakSet,x8=function(){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 xa;(function(n){n[n.Page=0]="Page",n[n.Width=1]="Width"})(xa||(xa={}));var Nr=class extends Nx.default{constructor(t,n,i){super();this.pdfDoc=null;this.pageNum=1;this.scaleType=0;this.pageRendering=!1;this.pageNumPending=null;this.scale=1;this.resourceIndex=0;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.settings=t,this.publication=n,this.api=i}static async create(t){let n=new this(t.settings,t.publication,t.api);return await n.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(n))}async start(t,n,i){this.headerMenu=n,this.footerMenu=i,this.mainElement=t,this.resourceIndex=0,this.resource=this.publication.readingOrder[this.resourceIndex],console.log(this.resource),console.log(this.resource.Href1),Aa.GlobalWorkerOptions.workerSrc="//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.js",this.wrapper=Rt(this.mainElement,"main#iframe-wrapper"),this.pdfContainer=Rt(this.mainElement,"#pdf-container"),this.handTool=new jg({element:this.pdfContainer});let o=this,s=document.createElement("div");s.id="loadingpdf",s.innerHTML=dh,s.style.width=getComputedStyle(this.wrapper).width,s.style.height=getComputedStyle(this.wrapper).height,s.style.display="flex",s.style.zIndex="100",s.style.position="absolute",s.style.alignItems="center",s.style.justifyContent="center",s.style.background="white",s.className="loading is-loading",this.pdfContainer.appendChild(s),(0,Aa.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(l){o.pdfDoc=l,o.loadPDFJS(o.pageNum)}),this.setupEvents()}async handleResize(){this.loadPDFJS(this.pageNum)}setupEvents(){Ce(window,"resize",this.onResize)}loadPDFJS(t){let n=this,i=1;this.wrapper.style.height="calc(100vh - 10px)",this.pdfContainer.style.height="calc(100vh - 10px)",this.pdfContainer.style.flexDirection="column";let o=document.getElementsByTagName("canvas");Array.from(o).forEach(function(l){l?.parentNode?.removeChild(l)});function s(l){let h=document.createElement("canvas");h.id=String(i),h.style.border="1px solid gray",h.style.margin="1px";let u=l.getViewport({scale:n.scale});if(n.scale===1){let v=n.wrapper.clientHeight/u.height,g=n.wrapper.clientWidth/u.width;console.log(v,g),n.scaleType===0?u=l.getViewport({scale:v<g?v:g}):u=l.getViewport({scale:g})}n.pdfContainer.appendChild(h);let d=h.getContext("2d");h.height=u.height,h.width=u.width;let m={canvasContext:d,viewport:u},y=document.getElementById("loadingpdf");y.style.display="flex",y.style.width=getComputedStyle(n.wrapper).width,y.style.height=getComputedStyle(n.wrapper).height,l.render(m).promise.then(function(){i<n.pdfDoc.numPages?(i++,n.pdfDoc.getPage(i).then(s)):(document.getElementById(String(t))?.scrollIntoView(),y.style.display="none")})}this.pdfDoc.getPage(i).then(s)}queueRenderPage(t){let n=this;n.pageRendering?n.pageNumPending=t:(this.pageNum=t,document.getElementById(String(t))?.scrollIntoView())}readingOrder(){return this.publication.readingOrder}tableOfContents(){return this.publication.tableOfContents}currentResource(){}totalResources(){return this.publication.readingOrder.length}currentLocator(){}positions(){return this.publication.positions?this.publication.positions:[]}nextPage(){let t=this;if(t.pageNum>=t.pdfDoc.numPages){this.nextResource();return}this.pageNum++,this.queueRenderPage(t.pageNum)}previousPage(){let t=this;if(t.pageNum<=1){this.previousResource();return}t.pageNum--,t.queueRenderPage(t.pageNum)}nextResource(){let t=this;console.log(t.resourceIndex,this.publication.readingOrder.length-1),!(this.resourceIndex>=this.publication.readingOrder.length-1)&&(t.resourceIndex++,t.resource=this.publication.readingOrder[t.resourceIndex],console.log(this.resource.Href1),(0,Aa.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(n){t.pdfDoc=n,t.pageNum=1,t.loadPDFJS(t.pageNum)}))}previousResource(){let t=this;console.log(t.resourceIndex,this.publication.readingOrder.length-1),this.resourceIndex!==0&&(t.resourceIndex--,t.resource=this.publication.readingOrder[t.resourceIndex],console.log(this.resource.Href1),(0,Aa.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(n){t.pdfDoc=n,t.pageNum=t.pdfDoc.numPages,t.loadPDFJS(t.pageNum)}))}goTo(t){console.log(t);let n=new URL(t.href);if(n.searchParams.has("start")){let i=n.searchParams.get("start");i&&this.queueRenderPage(parseInt(i))}else this.queueRenderPage(1)}goToPosition(t){console.log(t),this.queueRenderPage(t)}async goToPage(t){console.log(t),this.queueRenderPage(t)}fitToWidth(){console.log("fit to width",this.pageNum),this.scale=1,this.scaleType=1,this.loadPDFJS(this.pageNum)}fitToPage(){console.log("fit to page",this.pageNum),this.scale=1,this.scaleType=0,this.loadPDFJS(this.pageNum)}zoomIn(){this.scale=this.scale+.2,this.loadPDFJS(this.pageNum)}zoomOut(){this.scale=this.scale-.2,this.loadPDFJS(this.pageNum)}activateHand(){this.handTool.activate()}deactivateHand(){this.handTool.deactivate()}async scroll(t,n){t?(n==="horizontal"?this.pdfContainer.style.flexDirection="row":this.pdfContainer.style.flexDirection="column",this.pdfContainer.style.overflow="auto"):(this.pdfContainer.style.flexDirection="column",this.pdfContainer.style.overflow="hidden")}stop(){ze(window,"resize",this.onResize)}};var qo=class{constructor(t,n,i,o,s,l,h,u,d,m,y,w,v,g,f,p,b){this.settings=t;this.navigator=n;this.highlighter=i;this.bookmarkModule=o;this.annotationModule=s;this.ttsSettings=l;this.ttsModule=h;this.searchModule=u;this.definitionsModule=d;this.contentProtectionModule=m;this.timelineModule=y;this.mediaOverlaySettings=w;this.mediaOverlayModule=v;this.pageBreakModule=g;this.lineFocusModule=f;this.historyModule=p;this.citationModule=b;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 t=>await this.bookmarkModule?.deleteBookmark(t)??!1;this.deleteAnnotation=async t=>await this.annotationModule?.deleteAnnotation(t)??!1;this.addAnnotation=async t=>await this.annotationModule?.addAnnotation(t)??!1;this.hideAnnotationLayer=()=>this.annotationModule?.hideAnnotationLayer();this.showAnnotationLayer=()=>this.annotationModule?.showAnnotationLayer();this.hideLayer=t=>this.navigator instanceof _t?this.navigator?.hideLayer(t):!1;this.showLayer=t=>this.navigator instanceof _t?this.navigator?.showLayer(t):!1;this.activateMarker=(t,n)=>this.navigator instanceof _t?this.navigator?.activateMarker(t,n):!1;this.deactivateMarker=()=>this.navigator instanceof _t?this.navigator?.deactivateMarker():!1;this.clearDefinitions=async()=>{await this.definitionsModule?.clearDefinitions()};this.addDefinition=async t=>{await this.definitionsModule?.addDefinition(t)};this.search=async(t,n)=>await this.searchModule?.search(t,n)??[];this.goToSearchIndex=async(t,n,i)=>{this.navigator instanceof _t&&this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchIndex(t,n,i)};this.goToSearchID=async(t,n,i)=>{this.navigator instanceof _t&&this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchID(t,n,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 t=>await this.settings.applyUserSettings(t);this.scroll=async(t,n)=>this.navigator instanceof Nr?this.navigator.scroll(t,n):await this.settings.scroll(t);this.increase=async t=>{this.isTTSIncrementable(t)?this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.increase(t):this.isMOIncrementable(t)?this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.increase(t):await this.settings.increase(t)};this.decrease=async t=>{this.isTTSIncrementable(t)?this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.decrease(t):this.isMOIncrementable(t)?this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.decrease(t):await this.settings.decrease(t)};this.resetTTSSettings=()=>{this.navigator instanceof _t&&this.navigator.rights.enableTTS&&this.ttsSettings?.resetTTSSettings()};this.applyTTSSettings=async t=>{this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.applyTTSSettings(t)};this.applyPreferredVoice=async t=>{this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.applyPreferredVoice(t)};this.resetMediaOverlaySettings=async()=>{this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.resetMediaOverlaySettings()};this.applyMediaOverlaySettings=async t=>{this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.applyMediaOverlaySettings(t)};this.goTo=async t=>{this.navigator.goTo(t)};this.goToPosition=async t=>this.navigator.goToPosition(t);this.goToPage=async t=>{await this.navigator.goToPage(t)};this.fitToPage=()=>{this.navigator instanceof Nr&&this.navigator.fitToPage()};this.fitToWidth=()=>{this.navigator instanceof Nr&&this.navigator.fitToWidth()};this.zoomIn=()=>{this.navigator instanceof Nr&&this.navigator.zoomIn()};this.zoomOut=()=>{this.navigator instanceof Nr&&this.navigator.zoomOut()};this.activateHand=()=>{this.navigator instanceof Nr&&this.navigator.activateHand()};this.deactivateHand=()=>{this.navigator instanceof Nr&&this.navigator.deactivateHand()};this.copyToClipboard=t=>{this.contentProtectionModule?.copyToClipboard(t)};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 t=>{this.navigator instanceof _t&&this.navigator.snapToSelector(t)};this.applyAttributes=t=>{this.navigator instanceof _t&&this.navigator.applyAttributes(t)};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()}}addEventListener(){this.navigator instanceof _t&&this.navigator.addListener(arguments[0],arguments[1])}static async load(t){let n=t.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};n.enableContentProtection&&t.protection&&await lh.setupPreloadProtection(t.protection);let i=Rt(document,"#D2Reader-Container"),o=$e(document,"#headerMenu"),s=$e(document,"#footerMenu"),l=t.url,h;t.publication?(h=ea(t.publication,Co),h.manifestUrl=new URL(l)):h=await Co.fromUrl(l,t.requestConfig);let u=new Sa({prefix:h.manifestUrl,useLocalStorage:t.useLocalStorage??!1}),d=new Sa({prefix:"r2d2bc-reader",useLocalStorage:t.useLocalStorage??!1}),m=new Sa({prefix:"r2d2bc-layers",useLocalStorage:t.useLocalStorage??!1}),y=new Uo({store:u});if(h.sample=t.sample,n=C8(n,h),h.Metadata.ConformsTo&&h.Metadata.ConformsTo.includes("https://readium.org/webpub-manifest/profiles/pdf")){let w=await ko.create({store:d,initialUserSettings:t.userSettings,layout:""}),v=await Nr.create({mainElement:i,publication:h,settings:w});return new qo(w,v)}else{n.autoGeneratePositions?await h.autoGeneratePositions(t.requestConfig):(t.services?.positions&&await h.fetchPositionsFromService(t.services?.positions.href,t.requestConfig),t.services?.weight&&await h.fetchWeightsFromService(t.services?.weight.href,t.requestConfig));let w=await Rg.create({store:m}),v=await ko.create({store:d,initialUserSettings:t.userSettings,headerMenu:o,api:t.api,injectables:(h.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed:t.injectables,layout:(h.Metadata.Rendition?.Layout??"unknown")==="fixed"?"fixed":"reflowable"}),g=await _t.create({mainElement:i,headerMenu:o,footerMenu:s,publication:h,settings:v,annotator:y,initialLastReadingPosition:t.lastReadingPosition,api:t.api,rights:n,tts:t.tts,sample:t.sample,requestConfig:t.requestConfig,injectables:(h.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed??[]:t.injectables,attributes:t.attributes,services:t.services}),f=await ht.create(dt({delegate:g,layerSettings:w},t.highlighter)),p=n.enableBookmarks?await Ol.create(dt({annotator:y,headerMenu:o,rights:n,publication:h,delegate:g,initialAnnotations:t.initialAnnotations},t.bookmarks)):void 0,b=n.enableAnnotations?await Tl.create(dt({annotator:y,rights:n,publication:h,delegate:g,initialAnnotations:t.initialAnnotations,highlighter:f,headerMenu:o},t.annotations)):void 0,S=n.enableTTS,C=S?await Cg.create({store:d,initialTTSSettings:t.tts,headerMenu:o}):void 0,x;S&&C&&(x=await Mg.create(dt({delegate:g,tts:C,headerMenu:o,rights:n,highlighter:f},t.tts)));let E=n.enableSearch?await xg.create(dt({headerMenu:o,delegate:g,publication:h,highlighter:f},t.search)):void 0,T=n.enableDefinitions?await kg.create(dt({delegate:g,publication:h,highlighter:f},t.define)):void 0,R=n.enableTimeline?await ig.create({publication:h,delegate:g}):void 0,O=n.enableContentProtection?await lh.create(dt({delegate:g},t.protection)):void 0,L=n.enableCitations?await vh.create(dt({publication:h,delegate:g,highlighter:f},t.citations)):void 0,M=n.enableMediaOverlays,k=M?await eg.create(dt({store:d,initialMediaOverlaySettings:t.mediaOverlays,headerMenu:o},t.mediaOverlays)):void 0,F=M?await tg.create(dt({publication:h,delegate:g,settings:k},t.mediaOverlays)):void 0,G=n.enablePageBreaks&&h.isReflowable?await Pg.create(dt({publication:h,headerMenu:o,delegate:g},t.pagebreak)):void 0,ie=n.enableLineFocus?await yh.create(dt({publication:h,delegate:g,highlighter:f},t.lineFocus)):void 0,ee=n.enableHistory?await Ig.create({annotator:y,publication:h,delegate:g,headerMenu:o}):void 0;return new qo(v,g,f,p,b,C,x,E,T,O,R,k,F,G,ie,ee,L)}}get hasMediaOverlays(){return this.navigator instanceof _t?this.navigator.hasMediaOverlays:!1}get tableOfContents(){return Bl(this.navigator.tableOfContents())??[]}get readingOrder(){return Bl(this.navigator.readingOrder())??[]}get bookmarks(){return this.bookmarkModule?.getBookmarks()??[]}get annotations(){return this.annotationModule?.getAnnotations()}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(t){return t==="pitch"||t==="rate"||t==="volume"}isMOIncrementable(t){return t==="mo_rate"||t==="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(t){if(t.lines&&this.lineFocusModule){let n=this.lineFocusModule.properties.lines??1;this.lineFocusModule.index=this.lineFocusModule.index*n/parseInt(t.lines),this.lineFocusModule.index=Math.abs(parseInt(this.lineFocusModule.index.toFixed())),this.lineFocusModule.properties.lines=parseInt(t.lines),this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus()}t.debug!==void 0&&this.lineFocusModule&&(this.lineFocusModule.isDebug=t.debug,this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus())}lineUp(){this.lineFocusModule?.lineUp()}lineDown(){this.lineFocusModule?.lineDown()}async enableLineFocus(){await this.lineFocusModule?.enableLineFocus()}async lineFocus(t){t?await this.lineFocusModule?.enableLineFocus():this.lineFocusModule?.disableLineFocus()}disableLineFocus(){this.lineFocusModule?.disableLineFocus()}};function C8(r,t){return t.isFixedLayout&&(r.enableAnnotations=!1,r.enableSearch=!1,r.enableTTS=!1,r.enableDefinitions=!1,r.enablePageBreaks=!1,r.enableLineFocus=!1),t.sample?.isSampleRead&&(r.enableAnnotations=!1,r.enableSearch=!1,r.enableTTS=!1,r.enableDefinitions=!1,r.enableTimeline=!1,r.enableMediaOverlays=!1,r.enablePageBreaks=!1,r.enableLineFocus=!1),r}var T8=qo,O8=qo.load;return R8;})();
|
|
88
|
+
`;var gh=vt(Mo());H();var _a=class{constructor(t){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{let n=null,i=null,o=this;t&&(t.addEventListener("touchstart",function(s){s.changedTouches.length===1&&(n=s)},!1),t.addEventListener("touchend",function(s){if(s.changedTouches.length!==1||!n)return;let l=n.changedTouches[0],h=s.changedTouches[0];if(!l)return;let u=window.devicePixelRatio,d=(l.clientX-h.clientX)/u,m=(l.clientY-h.clientY)/u;if(Math.abs(d)<_a.TAP_TOLERANCE&&Math.abs(m)<_a.TAP_TOLERANCE){if(i){n=null,i=null;return}if(s.timeStamp-n.timeStamp>_a.LONG_PRESS_MS){n=null,i=null;return}n=null,i=s;return}if(i=null,s.timeStamp-n.timeStamp>_a.SLOW_SWIPE_MS){n=null;return}let y=(l.clientY-h.clientY)/(l.clientX-h.clientX);if(Math.abs(y)>.5){n=null;return}d<0?o.onBackwardSwipe(s):o.onForwardSwipe(s),n=null},!1))};this.navigator=t}},Es=_a;Es.TAP_TOLERANCE=10,Es.LONG_PRESS_MS=500,Es.SLOW_SWIPE_MS=500;H();var hh=class{constructor(t){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{t&&(this.focusin(t),this.keydown(t))};this.focusin=t=>{let n=this;t.addEventListener("focusin",function(i){n.navigator.view?.snap(i.target)},!0)};this.keydown=t=>{let n=this;this.navigator.rights.customKeyboardEvents||t.addEventListener("keydown",function(i){let o=i.target;if(/input|select|option|textarea/i.test(o.tagName)||!(o.ownerDocument||o).defaultView.getSelection().isCollapsed)return;switch(i.key){case"ArrowRight":n.onForwardSwipe(i);break;case"ArrowLeft":n.onBackwardSwipe(i);break}},!1)};this.navigator=t}};H();var QA=vt(Mo()),fh=class{constructor(t){this.enforceSampleRead=(0,QA.debounce)(t=>{let n=Math.round(t.locations.totalProgression*100),i=!1;this.delegate.sample?.limit&&(i=n<=this.delegate.sample?.limit,this.delegate.view?.layout==="fixed"&&!i&&this.delegate.sample?.minimum&&t.locations.position<=this.delegate.sample?.minimum&&(i=!0));let o={37:1,38:0,39:1,40:1,32:1,33:1,34:1,35:1,36:1};function s(g){g.preventDefault()}function l(g){o[g.keyCode]&&!i&&s(g)}let h=!1,u=Object.defineProperty&&Object.defineProperty({},"passive",{get:function(){h=!0}});window.addEventListener("test",function(){},u);let d=h?{passive:!1}:!1;function m(g){g=g||window.event;let f=Math.max(-1,Math.min(1,g.wheelDelta||-g.detail));return f===-1&&!i&&g.preventDefault(),!1}let y;function w(g){g=g||window.event;let f=g.target||g.srcElement,p=g.touches[0].clientY;if(!(p>y)){if(p<y&&!i)return f.className.match(/\baltNav\b/)||(g.returnValue=!1,g.cancelable&&(g.cancelBubble=!0),g.preventDefault&&g.cancelable&&(g.preventDefault(),g.stopPropagation())),!1}return y=p,!1}function v(g){return g=g||window.event,y=g.touches[0].clientY,!1}window.addEventListener("mousewheel",m,d),window.addEventListener("DOMMouseScroll",m,d),window.addEventListener("keydown",l,d),window.addEventListener("touchmove",w,d),window.addEventListener("touchstart",v,d),i?(this.delegate.iframes[0].focus(),this.delegate.errorMessage&&(this.delegate.errorMessage.style.display="none",this.delegate.errorMessage.style.removeProperty("background-color"))):(this.delegate.iframes[0].blur(),this.delegate.errorMessage&&(this.delegate.errorMessage.style.display="block",this.delegate.errorMessage.style.backgroundColor="rgb(255, 255, 255)",this.delegate.errorMessage.innerHTML=this.delegate.sample?.popup??""))},300);this.delegate=t}};var tx=vt(Og()),Ei=vt(dn()),_t=class extends tx.default{constructor(t,n=void 0,i=void 0,o,s,l,h,u,d,m,y,w){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 n=this.publication.getAbsoluteHref(t.href);Ei.default.log(t.href),Ei.default.log(n),t.href=n,await this.navigate(t)}};this.savePosition=(0,gh.debounce)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,gh.debounce)(()=>{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.settings=t,this.annotator=n,this.view=t.view,this.view.attributes=d,this.view.delegate=this,this.eventHandler=new Fd(this),this.touchEventHandler=new Es(this),this.keyboardEventHandler=new hh(this),this.initialLastReadingPosition=i,this.publication=o,this.api=s,this.rights=l??{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=h,this.injectables=u,this.attributes=d||{margin:0},this.services=m,this.sample=y,this.requestConfig=w,this.sampleReadEventHandler=new fh(this)}static async create(t){let n=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);return await n.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(n))}stop(){Ei.default.log("Iframe navigator stop"),ze(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),ze(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),ze(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ze(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),ze(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ze(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),ze(this.tryAgainButton,"click",this.tryAgain.bind(this)),ze(this.goBackButton,"click",_t.goBack.bind(this)),ze(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),ze(window,"resize",this.onResize),this.iframes.forEach(t=>{ze(t,"resize",this.onResize)})}async start(t,n,i){this.headerMenu=n,this.mainElement=t;try{let v=Rt(t,"main#iframe-wrapper");v.style.overflow="auto";let g=$e(t,"main#iframe-wrapper iframe"),f=$e(t,"#second");if(g&&this.iframes.push(g),f&&this.iframes.push(f),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.iframes.length===0){v.style.overflow="auto";let p=document.createElement("iframe");if(p.setAttribute("SCROLLING","no"),p.setAttribute("allowtransparency","true"),this.iframes.push(p),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]),v.appendChild(this.spreads)):(p.setAttribute("height","100%"),p.setAttribute("width","100%"),v.appendChild(this.iframes[0])),this.publication.isFixedLayout)if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){let b=document.createElement("div");this.spreads.appendChild(b);let S=document.createElement("iframe");S.setAttribute("SCROLLING","no"),S.setAttribute("allowtransparency","true"),S.style.opacity="1",S.style.border="none",S.style.overflow="hidden",this.iframes.push(S),b.appendChild(this.iframes[1]),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",b.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",b.style.boxShadow="0 0 8px 2px #ccc"}else 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 p=v.clientHeight;var o=this.iframes[0].parentElement?.parentElement;o.style.height=p+40+"px"}else this.iframes.length===2&&this.iframes.pop();if(this.loadingMessage=$e(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=dh,this.loadingMessage.style.display="none"),this.errorMessage=$e(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=ZA,this.errorMessage.style.display="none"),this.tryAgainButton=$e(t,"button[class=try-again]"),this.goBackButton=$e(t,"button[class=go-back]"),this.infoTop=$e(t,"div[class='info top']"),this.infoBottom=$e(t,"div[class='info bottom']"),this.headerMenu&&(this.bookTitle=$e(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=$e(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=$e(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=$e(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=$e(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=$e(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=$e(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=$e(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=$e(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=$e(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=$e(this.headerMenu,"#container-view-pagelist")),i&&(this.linksBottom=$e(i,"ul.links.bottom")),i&&(this.linksMiddle=$e(i,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=$e(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=$e(t,"#next-chapter")),i&&(this.nextPageAnchorElement=$e(i,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=$e(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=$e(t,"#previous-chapter")),i&&(this.previousPageAnchorElement=$e(i,"a[rel=prev]")),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.newPosition=void 0,this.newElementId=void 0,this.isBeingStyled=!0,this.isLoading=!0,this.settings.setIframe(this.iframes[0]),this.settings.onSettingsChange(this.handleResize.bind(this)),this.settings.onColumnSettingsChange(this.handleNumberOfIframes.bind(this)),this.settings.onViewChange(this.updateBookView.bind(this)),this.initialLastReadingPosition&&this.annotator?.initLastReadingPosition(this.initialLastReadingPosition),this.headerMenu){var s=$e(this.headerMenu,"#menu-button-search"),l=$e(this.headerMenu,"#menu-button-tts"),h=$e(this.headerMenu,"#menu-button-bookmark"),u=$e(this.headerMenu,"#menu-button-play"),d=$e(this.headerMenu,"#menu-button-pause"),m=$e(this.headerMenu,"#menu-button-mediaoverlay");if(!this.rights.enableBookmarks){h&&h.parentElement?.style.setProperty("display","none");var y=$e(this.headerMenu,"#sidenav-section-bookmarks");y&&y.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var w=$e(this.headerMenu,"#sidenav-section-highlights");w&&w.style.setProperty("display","none")}this.rights.enableTTS||l&&l.parentElement?.style.setProperty("display","none"),this.rights.enableSearch||s&&s.parentElement?.style.setProperty("display","none"),s&&this.view?.delegate.publication.isFixedLayout&&s.parentElement?.style.setProperty("display","none"),this.hasMediaOverlays?(u&&u.parentElement?.style.removeProperty("display"),d&&d.parentElement?.style.removeProperty("display"),m&&m.parentElement?.style.removeProperty("display")):(u&&u.parentElement?.style.setProperty("display","none"),d&&d.parentElement?.style.setProperty("display","none"),m&&m.parentElement?.style.setProperty("display","none"))}else s&&s.parentElement?.style.setProperty("display","none"),l&&l.parentElement?.style.setProperty("display","none"),h&&h.parentElement?.style.setProperty("display","none");return this.setupEvents(),await this.loadManifest()}catch(v){return Ei.default.error(v),this.abortOnError(v),Promise.reject(v)}}setupEvents(){for(let t of this.iframes)Ce(t,"load",this.handleIFrameLoad.bind(this));Ce(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),Ce(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),Ce(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ce(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),Ce(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ce(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),Ce(this.tryAgainButton,"click",this.tryAgain.bind(this)),Ce(this.goBackButton,"click",_t.goBack.bind(this)),Ce(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),Ce(window,"resize",this.onResize);for(let t of this.iframes)Ce(t,"resize",this.onResize)}updateBookView(){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.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousChapterClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextChapterClick.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this))):(this.settings.isPaginated().then(t=>{if(t)this.view.height=gr()-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));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 n=(0,gh.debounce)(()=>{this.isScrolling=!1},200),i=Rt(document,"#iframe-wrapper");i.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()),n()},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))}}),setTimeout(async()=>{await this.highlighter?.prepareContainers(this.iframes[0].contentWindow),this.pageBreakModule!==void 0&&(await this.highlighter?.destroyHighlights(gt.PageBreak),await this.pageBreakModule.drawPageBreaks()),this.annotationModule!==void 0&&await this.annotationModule.drawHighlights(),this.bookmarkModule!==void 0&&await this.bookmarkModule.drawBookmarks(),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(gt.Search),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule!==void 0&&this.highlighter!==void 0&&await this.definitionsModule.drawDefinitions()},200))}async loadManifest(){try{let t=(u,d,m=!1)=>{var y=document.createElement("ul");m&&(y=document.createElement("ol")),y.className="sidenav-toc";for(let w of d){let v=document.createElement("li"),g=document.createElement("a"),f=document.createElement("span");g.className="chapter-link",g.tabIndex=-1;let p="";w.Href?(p=this.publication.getAbsoluteHref(w.Href),g.href=p,g.innerHTML=w.Title||"",v.appendChild(g)):(f.innerHTML=w.Title||"",f.className="chapter-title",v.appendChild(f)),w.Children&&w.Children.length>0&&t(v,w.Children,!0),y.appendChild(v)}Ce(y,"click",w=>{if(w.preventDefault(),w.stopPropagation(),w.target&&w.target.tagName.toLowerCase()==="a"){let v=w.target;if(v.className.indexOf("active")!==-1)this.hideView();else{let g={progression:0};if(v.href.indexOf("#")!==-1){let p=v.href.slice(v.href.indexOf("#")+1);p!==void 0&&(g={fragment:p})}let f={href:v.href,locations:g,type:v.type,title:v.title};this.hideView(),this.navigate(f)}}}),u.appendChild(y)},n=this.publication.tableOfContents,i=this.publication.landmarks,o=this.publication.pageList;this.tocView&&(n.length?t(this.tocView,n):this.tocView.parentElement?.parentElement?.removeChild(this.tocView.parentElement)),this.pageListView&&(o?.length?t(this.pageListView,o):this.pageListView.parentElement?.parentElement?.removeChild(this.pageListView.parentElement)),this.landmarksView&&(i?.length?t(this.landmarksView,i):this.landmarksSection.parentElement?.removeChild(this.landmarksSection));let s;this.annotator&&(s=await this.annotator.getLastReadingPosition());let l=this.publication.getStartLink(),h;if(l&&l.Href&&(h=this.publication.getAbsoluteHref(l.Href)),s){let u=this.publication.getAbsoluteHref(s.href);Ei.default.log(s.href),Ei.default.log(u),s.href=u,await this.navigate(s)}else if(h){let u={href:h,locations:{progression:0},created:new Date,title:l?.Title};await this.navigate(u)}return new Promise(u=>u())}catch(t){return Ei.default.error(t),this.abortOnError(t),new Promise((n,i)=>i(t)).catch(()=>{})}}async handleIFrameLoad(){this.errorMessage&&(this.errorMessage.style.display="none"),this.showLoadingMessageAfterDelay();try{let t=0;this.newPosition&&(t=this.newPosition.locations.progression),await this.handleResize(),this.updateBookView(),await this.settings.applyProperties();let n=this.currentChapterLink.href;if(n){let u=this.publication.getPreviousSpineItem(n);u&&u.Href&&(this.previousChapterLink={href:u.Href,title:u.Title,type:u.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 i=this.publication.getNextSpineItem(n);i?this.nextChapterLink={href:i.Href,title:i.Title,type:i.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(n),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let o=this.publication.getSpineItem(n);o!==void 0&&(this.currentChapterLink.title=o.Title,this.currentChapterLink.type=o.TypeLink);let s=this.publication.getTOCItem(n);this.currentTocUrl!==void 0&&(s=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&s!==void 0&&s.Title&&(this.currentChapterLink.title=s.Title),!this.currentChapterLink.type&&s!==void 0&&s.TypeLink&&(this.currentChapterLink.title=s.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),await this.injectInjectablesIntoIframeHead(),this.highlighter!==void 0&&await this.highlighter.initialize();let h=this.iframes[0].contentDocument?.body?.querySelector("details");if(h){let u=this;h.addEventListener("toggle",async d=>{await u.view?.setIframeHeight?.(this.iframes[0])})}if(this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.initialize(),this.eventHandler){for(let u of this.iframes)this.eventHandler.setupEvents(u.contentDocument),this.touchEventHandler.setupEvents(u.contentDocument),this.keyboardEventHandler.setupEvents(u.contentDocument);this.touchEventHandler.setupEvents(this.errorMessage),this.didInitKeyboardEventHandler||(this.keyboardEventHandler.keydown(document),this.didInitKeyboardEventHandler=!0)}if(this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(this.iframes[0].height="0",this.view?.setIframeHeight?.(this.iframes[0])),this.annotationModule!==void 0&&await this.annotationModule.initialize(),this.bookmarkModule!==void 0&&await this.bookmarkModule.initialize(),this.rights.enableTTS)for(let u of this.iframes){let d=u.contentDocument?.body;this.ttsModule!==void 0&&await this.ttsModule.initialize(d)}return this.timelineModule!==void 0&&await this.timelineModule.initialize(),this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&await this.mediaOverlayModule.initialize(),setTimeout(async()=>{if(this.newElementId){let u=this.iframes[0].contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(u),this.newElementId=void 0}else if(this.newPosition&&this.newPosition.highlight){let u=this.newPosition.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;u&&this.view?.goToCssSelector(u)}else t&&t>=0&&this.view?.goToProgression(t);if(this.newPosition=void 0,this.rights?.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(10),this.hideLoadingMessage(),this.showIframeContents(),this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays){let u=this.currentLink();await this.mediaOverlayModule?.initializeResource(u)}await this.updatePositionInfo(),await this.view?.setSize(),setTimeout(()=>{this.mediaOverlayModule!==void 0&&(this.mediaOverlayModule.settings.resourceReady=!0)},300)},200),new Promise(u=>u())}catch(t){return Ei.default.error(t),this.abortOnError(t),Promise.reject(t)}}async injectInjectablesIntoIframeHead(){let t=[],n=i=>{let o=new Promise((s,l)=>{i.onload=()=>{s(!0)},i.onerror=h=>{let u=typeof h=="string"?h:`Injectable failed to load at: ${"href"in i?i.href:i.src}`;l(new Error(u))}});t.push(o)};for(let i of this.iframes){let o=i.contentDocument?.head;o&&(i.contentDocument.getElementsByTagName("base").length===0&&o.insertBefore(_t.createBase(this.currentChapterLink.href),o.firstChild),this.injectables?.forEach(l=>{if(l.type==="style"){if(l.fontFamily){if(this.settings.initAddedFont(),!l.systemFont&&l.url){let h=_t.createCssLink(l.url);o.appendChild(h),n(h)}}else if(l.r2before&&l.url){let h=_t.createCssLink(l.url);o.insertBefore(h,o.firstChild),n(h)}else if(l.r2default&&l.url){let h=_t.createCssLink(l.url);o.insertBefore(h,o.childNodes[1]),n(h)}else if(l.r2after&&l.url){l.appearance&&this.settings.initAddedAppearance();let h=_t.createCssLink(l.url);o.appendChild(h),n(h)}else if(l.url){let h=_t.createCssLink(l.url);o.appendChild(h),n(h)}}else if(l.type==="script"&&l.url){let h=_t.createJavascriptLink(l.url,l.async??!1);o.appendChild(h),n(h)}}))}t.length!==0&&await Promise.all(t)}abortOnError(t){if(this.api?.onError){let n=t instanceof Error?t:typeof t=="string"?new Error(t):new Error("An unknown error occurred in the IFrameNavigator.");this.api.onError(n)}else this.errorMessage&&(this.errorMessage.style.display="block"),this.isLoading&&this.hideLoadingMessage()}tryAgain(){this.precessContentForIframe()}precessContentForIframe(){let t=this;var n=this.publication.getSpineIndex(this.currentChapterLink.href),i=(n??0)%2==1;this.showLoadingMessageAfterDelay();function o(u,d){let y=new DOMParser().parseFromString(u,"application/xhtml+xml");y.head&&y.getElementsByTagName("base").length===0&&y.head.insertBefore(_t.createBase(d),y.head.firstChild);let w=y.documentElement.outerHTML,v=t.iframes[0].contentDocument;v&&(v.open(),v.write(w),v.close())}function s(u,d){let y=new DOMParser().parseFromString(u,"application/xhtml+xml");y.head&&y.getElementsByTagName("base").length===0&&y.head.insertBefore(_t.createBase(d),y.head.firstChild);let w=y.documentElement.outerHTML,v=t.iframes[1].contentDocument;v&&(v.open(),v.write(w),v.close())}let l=new URL(this.currentChapterLink.href),h=window.location.protocol===l.protocol&&window.location.port===l.port&&window.location.hostname===l.hostname;if(this.api?.getContent)if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(u=>{u===void 0?h?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)}):o.call(this,u,this.currentChapterLink.href)}),this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let u=this.publication.getNextSpineItem(this.currentChapterLink.href);if(u){let d=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.right={href:d},this.api?.getContent(d).then(m=>{m===void 0?h?this.iframes[1].src=d:fetch(d,this.requestConfig).then(y=>y.text()).then(async y=>{s.call(this,y,d),this.currentSpreadLinks.right={href:d}}):s.call(this,m,d)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let u=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(u){let d=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.left={href:d},this.api?.getContent(d).then(m=>{m===void 0?h?this.iframes[0].src=d:fetch(d,this.requestConfig).then(y=>y.text()).then(async y=>{o.call(this,y,d)}):o.call(this,m,d)})}}else this.iframes[0].src="about:blank";this.iframes.length===2&&this.publication.isFixedLayout&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},this.api.getContent(this.currentChapterLink.href).then(u=>{u===void 0?h?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{s.call(this,d,this.currentChapterLink.href)}):s.call(this,u,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(u=>{u===void 0?h?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)}):o.call(this,u,this.currentChapterLink.href)});else this.api?.getContent(this.currentChapterLink.href).then(u=>{this.currentSpreadLinks.left={href:this.currentChapterLink.href},u===void 0?h?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)}):o.call(this,u,this.currentChapterLink.href)});else if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(h){if(this.iframes[0].src=this.currentChapterLink.href,this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let u=this.publication.getNextSpineItem(this.currentChapterLink.href);if(u){let d=this.publication.getAbsoluteHref(u.Href);this.iframes[1].src=d,this.currentSpreadLinks.right={href:d}}}else this.iframes[1].src="about:blank"}else if(fetch(this.currentChapterLink.href,this.requestConfig).then(u=>u.text()).then(async u=>{o.call(this,u,this.currentChapterLink.href)}),this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let u=this.publication.getNextSpineItem(this.currentChapterLink.href);if(u){let d=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.right={href:d},fetch(d,this.requestConfig).then(m=>m.text()).then(async m=>{s.call(this,m,d)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let u=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(u){let d=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.left={href:d},h?(this.iframes[0].src=d,this.iframes.length===2&&(this.iframes[1].src=this.currentChapterLink.href)):(fetch(d,this.requestConfig).then(m=>m.text()).then(async m=>{o.call(this,m,d)}),this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},fetch(this.currentChapterLink.href,this.requestConfig).then(m=>m.text()).then(async m=>{s.call(this,m,this.currentChapterLink.href)})))}}else this.iframes[0].src="about:blank";this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},h?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(u=>u.text()).then(async u=>{s.call(this,u,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},h?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(u=>u.text()).then(async u=>{o.call(this,u,this.currentChapterLink.href)});else this.currentSpreadLinks.left={href:this.currentChapterLink.href},h?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(u=>u.text()).then(async u=>{o.call(this,u,this.currentChapterLink.href)});this.publication.isFixedLayout&&setTimeout(()=>{let u,d,m;if(n===0&&this.iframes?.length===2?m=this.iframes[1].contentDocument:m=this.iframes[0].contentDocument,m&&m.body&&(u=getComputedStyle(m.body).height,d=getComputedStyle(m.body).width,parseInt(u?.replace("px",""))===0||parseInt(d?.replace("px",""))===0)){let b=On(m,"head");if(b){let S=$e(b,"meta[name=viewport]");if(S){var y=S.content,w=y.split(",").reduce((C,x)=>{var[E,T]=x.match(/[^\s;=]+/g);return C[E]=isNaN(Number(T))?T:+T,C},{});u=w.height+"px",d=w.width+"px"}}}var v=n===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(v&&d){var g=(parseInt(getComputedStyle(v).width)-100)/(this.iframes.length===2?parseInt(d?.replace("px",""))*2+200:parseInt(d?.replace("px",""))),f=(parseInt(getComputedStyle(v).height)-100)/parseInt(u?.replace("px","")),p=Math.min(g,f);v.style.transform="scale("+p+")";for(let b of this.iframes)b.style.height=u,b.style.width=d,b.parentElement&&(b.parentElement.style.height=u)}},400)}static goBack(){window.history.back()}handleEditClick(t){var n=t.target;if(this.headerMenu){var i=$e(document,".sidenav");n.className.indexOf(" active")===-1?(n.className+=" active",i.className+=" expanded",n.innerText="unfold_less",this.sideNavExpanded=!0,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights()):(n.className=n.className.replace(" active",""),i.className=i.className.replace(" expanded",""),n.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 n=this.publication.getSpineItem(this.currentSpreadLinks.left.href),i=this.publication.getSpineItem(this.currentSpreadLinks.right.href);return[n,i]}let t=this.currentChapterLink.href;return[this.publication.getSpineItem(t)]}tableOfContents(){return this.publication.tableOfContents}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 n=t.locations??{progression:0};if(t.href.indexOf("#")!==-1){let s=t.href.slice(t.href.indexOf("#")+1);s!==void 0&&(n=nn(dt({},n),{fragment:s}))}let i=dt({},t);i.locations=n;let o=this.publication.getAbsoluteHref(t.href);Ei.default.log(t.href),Ei.default.log(o),i.href=o,this.stopReadAloud(),this.navigate(i)}currentLocator(){let t;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let n=this.publication.positionsByHref(this.publication.getRelativeHref(this.currentChapterLink.href)),i=Math.ceil((this.view?.getCurrentPosition()??0)*(n.length-1));t=n[i]}else{let n=this.publication.getTOCItem(this.currentChapterLink.href);n&&(this.currentTocUrl!==void 0&&(n=this.publication.getTOCItem(this.currentTocUrl)),n===void 0&&(n=this.publication.getTOCItemAbsolute(this.currentChapterLink.href)),n&&(t={href:n.Href,type:this.currentChapterLink.type,title:this.currentChapterLink.title,locations:{}}))}return t&&(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?this.publication.positions:[]}goToPosition(t){if(this.publication.positions){let n=this.publication.positions.filter(i=>i.locations.position===parseInt(String(t)))[0];this.goTo(n)}}async goToPage(t){this.pageBreakModule!==void 0&&await this.pageBreakModule.goToPageNumber(t)}snapToSelector(t){let n=this.iframes[0].contentDocument;if(n){Ei.default.log(t);let i=n.querySelectorAll(t);i.length>0&&this.view?.snap(i[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 n=!0;if(this.sample?.isSampleRead&&this.publication.positions){let i=this.currentLocator(),o=Math.round((i.locations.totalProgression??0)*100);this.sample?.limit&&(n=o<=this.sample?.limit,this.view?.layout==="fixed"&&((!n&&this.sample?.minimum&&i.locations.position)??0<=(this.sample?.minimum??0))&&(n=!0))}(n&&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()))),!n&&this.sample?.isSampleRead&&this.publication.positions&&t&&(t.preventDefault(),t.stopPropagation())}handleClickThrough(t){}handleInternalLink(t){let n=t.target,i={progression:0},o=n;if(o.href.indexOf("#")!==-1){let l=o.href.slice(o.href.indexOf("#")+1);l!==void 0&&(i={fragment:l})}let s={href:o.href,locations:i,type:o.type,title:o.title};t.preventDefault(),t.stopPropagation(),this.stopReadAloud(),this.navigate(s)}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 n=document.createElement("div");this.spreads.appendChild(n),n.appendChild(this.iframes[1]),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",n.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",n.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.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 d=gr()-40-(this.attributes?.margin??0);var n=t===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(n){n.style.height=d+40+"px";let m,y,w;t===0&&this.iframes?.length===2?w=this.iframes[1].contentDocument:w=this.iframes[0].contentDocument,w&&w.body&&(m=getComputedStyle(w.body).height,y=getComputedStyle(w.body).width);let v=On(w,"head");if(v){let g=$e(v,"meta[name=viewport]");if(g){var i=g.content,o=i.split(",").reduce((f,p)=>{var[b,S]=p.match(/[^\s;=]+/g);return f[b]=isNaN(Number(S))?S:+S,f},{});(parseInt(o.height)!==0||parseInt(o.width)!==0)&&(m=o.height+"px",y=o.width+"px")}}var s=(parseInt(getComputedStyle(n).width)-100)/(this.iframes.length===2?parseInt(y?.replace("px",""))*2+200:parseInt(y?.replace("px",""))),l=(parseInt(getComputedStyle(n).height)-100)/parseInt(m?.replace("px","")),h=Math.min(s,l);n.style.transform="scale("+h+")";for(let g of this.iframes)g.style.height=m,g.style.width=y,g.parentElement&&(g.parentElement.style.height=m)}}let u=this.view?.getCurrentPosition();await this.settings.applyProperties(),this.infoTop&&(this.infoTop.style.height=0+"px"),this.infoTop&&(this.infoTop.style.minHeight=0+"px"),this.infoBottom&&(this.infoBottom.style.height=this.attributes?.bottomInfoHeight?this.attributes.bottomInfoHeight+"px":40+"px"),this.view?.layout!=="fixed"&&this.settings.isPaginated().then(d=>{d?(this.view.height=gr()-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()=>{u&&this.view?.goToProgression(u),await this.updatePositionInfo(!1),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.contentProtectionModule!==void 0&&this.contentProtectionModule.handleResize(),this.lineFocusModule!==void 0&&this.lineFocusModule.handleResize(),this.historyModule!==void 0&&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 n=this.currentLocator();if(n){let i=n.displayInfo.resourceScreenIndex,o=n.displayInfo.resourceScreenCount;this.chapterPosition&&(this.chapterPosition.innerHTML="Page "+i+" of "+o)}}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 n=this.publication.getSpineIndex(this.currentChapterLink.href)??0;n=n-2,n<0&&(n=0);let i=this.publication.readingOrder[n],o={href:this.publication.getAbsoluteHref(i.Href),locations:{progression:0},type:i.TypeLink,title:i.Title};this.stopReadAloud(),this.navigate(o)}else if(this.previousChapterLink){let n={href:this.publication.getAbsoluteHref(this.previousChapterLink.href),locations:{progression:1},type:this.previousChapterLink.type,title:this.previousChapterLink.title};this.stopReadAloud(),this.navigate(n)}t&&(t.preventDefault(),t.stopPropagation())}handleNextChapterClick(t){if(this.view?.layout==="fixed"&&this.settings.columnCount!==1){let n=this.publication.getSpineIndex(this.currentChapterLink.href)??0;n=n+2,n>=this.publication.readingOrder.length-1&&(n=this.publication.readingOrder.length-1);let i=this.publication.readingOrder[n],o={href:this.publication.getAbsoluteHref(i.Href),locations:{progression:0},type:i.TypeLink,title:i.Title};this.stopReadAloud(),this.navigate(o)}else if(this.nextChapterLink){let n={href:this.publication.getAbsoluteHref(this.nextChapterLink.href),locations:{progression:0},type:this.nextChapterLink.type,title:this.nextChapterLink.title};this.stopReadAloud(),this.navigate(n)}t&&(t.preventDefault(),t.stopPropagation())}hideView(){this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(document.body.style.overflow="auto")}setActiveTOCItem(t){if(this.tocView){let n=Array.prototype.slice.call(this.tocView.querySelectorAll("li > a"));for(let o of n)o.className=o.className.replace(" active","");let i=this.tocView.querySelector('li > a[href^="'+t+'"]');i&&(i.className+=" active")}}async navigate(t,n=!0){if(this.historyModule&&this.historyModule.push(t,n),this.publication.getTOCItem(t.href)){var o=!1;if(t.href.indexOf("#")!==-1){let s=t.href.slice(0,t.href.indexOf("#"));s===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=s,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title}else t.href===this.currentChapterLink.href&&(o=!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(o){if(t.href.indexOf("#")!==-1){let m=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:m}}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 m of this.iframes){let y=m.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(y)}this.newElementId=void 0}else if(t.highlight){let m=t.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;m&&this.view?.goToCssSelector(m)}else this.view?.goToProgression(t.locations.progression??0);let s=this.currentChapterLink.href,l=this.publication.getPreviousSpineItem(s);l&&l.Href&&(this.previousChapterLink={href:l.Href,type:l.TypeLink,title:l.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 h=this.publication.getNextSpineItem(s);h?this.nextChapterLink={href:h.Href,type:h.TypeLink,title:h.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(s),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let u=this.publication.getSpineItem(s);u!==void 0&&(this.currentChapterLink.title=u.Title,this.currentChapterLink.type=u.TypeLink);let d=this.publication.getTOCItem(s);this.currentTocUrl!==void 0&&(d=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&d!==void 0&&d.Title&&(this.currentChapterLink.title=d.Title),!this.currentChapterLink.type&&d!==void 0&&d.TypeLink&&(this.currentChapterLink.title=d.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),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&&this.contentProtectionModule.recalculate(300),this.annotationModule!==void 0&&(await this.annotationModule.drawHighlights(),await this.annotationModule.showHighlights()),this.bookmarkModule!==void 0&&(await this.bookmarkModule.drawBookmarks(),await this.bookmarkModule.showBookmarks()),this.pageBreakModule!==void 0&&(await this.highlighter?.destroyHighlights(gt.PageBreak),await this.pageBreakModule.drawPageBreaks()),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(gt.Search),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule!==void 0&&this.highlighter!==void 0&&this.definitionsModule.drawDefinitions(),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(s=>{s||(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 s=this.publication.getStartLink(),l;if(s&&s.Href&&(l=this.publication.getAbsoluteHref(s.Href),l)){let h={href:l,locations:{progression:0},created:new Date,title:s.Title};await this.navigate(h)}}}showIframeContents(){this.isBeingStyled=!1,setTimeout(()=>{this.isBeingStyled||this.iframes.forEach(t=>{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?.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 n={progression:this.view?.getCurrentPosition()};if(t){if(t.Href.indexOf("#")!==-1){let o=t.Href.slice(t.Href.indexOf("#")+1);o!==void 0&&(n={progression:this.view?.getCurrentPosition(),fragment:o})}let i;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let o=this.publication.positionsByHref(this.publication.getRelativeHref(t.Href));if(o.length>0){let s=Math.ceil((n.progression??0)*(o.length-1)),l=o[s];l&&(l.locations.fragment=n.fragment,i=nn(dt({},l),{href:t.Href,created:new Date,title:this.currentChapterLink.title}))}}else i={href:t.Href,locations:n,created:new Date,type:this.currentChapterLink.type,title:this.currentChapterLink.title};i&&(this.sample?.isSampleRead&&this.publication.positions&&this.sampleReadEventHandler?.enforceSampleRead(i),this.api?.updateCurrentLocation?this.api?.updateCurrentLocation(i).then(async o=>(Ei.default.log("api updated current location",i),this.annotator?.saveLastReadingPosition(i))):(Ei.default.log("save last reading position",i),this.annotator.saveLastReadingPosition(i)))}}}static createBase(t){let n=document.createElement("base");return n.target="_self",n.href=t,n}static createCssLink(t){let n=document.createElement("link");return n.rel="stylesheet",n.type="text/css",n.href=t,n}static createJavascriptLink(t,n){let i=document.createElement("script");return i.type="text/javascript",i.src=t,i.async=n,i}activateMarker(t,n){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId===void 0||this.annotationModule.activeAnnotationMarkerId!==t?(this.annotationModule.activeAnnotationMarkerId=t,this.annotationModule.activeAnnotationMarkerPosition=n,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 n="#",i=new Za("layer-on","layer-off",!0,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=et.R2_ID_HIGHLIGHTS_CONTAINER,i.name=et.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=et.R2_ID_READALOUD_CONTAINER,i.name=et.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=et.R2_ID_PAGEBREAK_CONTAINER,i.name=et.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=et.R2_ID_SEARCH_CONTAINER,i.name=et.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=et.R2_ID_DEFINITIONS_CONTAINER,i.name=et.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let s=$e(o,n);s&&(s.style.display="block")}}hideLayer(t){let n="#",i=new Za("layer-on","layer-off",!1,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=et.R2_ID_HIGHLIGHTS_CONTAINER,i.name=et.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=et.R2_ID_READALOUD_CONTAINER,i.name=et.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=et.R2_ID_PAGEBREAK_CONTAINER,i.name=et.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=et.R2_ID_SEARCH_CONTAINER,i.name=et.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=et.R2_ID_DEFINITIONS_CONTAINER,i.name=et.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let s=$e(o,n);s&&(s.style.display="none")}}};H();var qt=class{constructor(t){this.store=t.store}getLastReadingPosition(){let t=this.store.get(qt.LAST_READING_POSITION);return t?JSON.parse(t):null}initLastReadingPosition(t){if(typeof t=="string")this.store.set(qt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(qt.LAST_READING_POSITION,n)}}saveLastReadingPosition(t){if(typeof t=="string")this.store.set(qt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(qt.LAST_READING_POSITION,n)}}initBookmarks(t){if(typeof t=="string"){let n=JSON.parse(t);this.store.set(qt.BOOKMARKS,JSON.stringify(n))}else this.store.set(qt.BOOKMARKS,JSON.stringify(t));return t}saveBookmark(t){let n=this.store.get(qt.BOOKMARKS);if(n){let i=JSON.parse(n);i.push(t),this.store.set(qt.BOOKMARKS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(qt.BOOKMARKS,JSON.stringify(i))}return t}locatorExists(t,n){let i;switch(n){case Fi.Bookmark:i=qt.BOOKMARKS;break}let o=this.store.get(i);return o&&JSON.parse(o).filter(h=>h.href===t.href&&h.locations.progression===t.locations.progression).length>0?t:null}deleteBookmark(t){let n=this.store.get(qt.BOOKMARKS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.id!==t.id),this.store.set(qt.BOOKMARKS,JSON.stringify(i))}return t}getBookmarks(t){let n=this.store.get(qt.BOOKMARKS);if(n){let i=JSON.parse(n);if(t){let o=i.filter(s=>s.href===t);return o=o.sort((s,l)=>{if(s.locations.progression&&l.locations.progression)return s.locations.progression-l.locations.progression}),o}return i=i.sort((o,s)=>{if(o.locations.progression&&s.locations.progression)return o.locations.progression-s.locations.progression}),i}return[]}initAnnotations(t){let n;typeof t=="string"?n=JSON.parse(t):n=t;let i=[];return n.forEach(o=>{let s=`${o.highlight.selectionInfo.rangeInfo.startContainerElementCssSelector}${o.highlight.selectionInfo.rangeInfo.startContainerChildTextNodeIndex}${o.highlight.selectionInfo.rangeInfo.startOffset}${o.highlight.selectionInfo.rangeInfo.endContainerElementCssSelector}${o.highlight.selectionInfo.rangeInfo.endContainerChildTextNodeIndex}${o.highlight.selectionInfo.rangeInfo.endOffset}`,l=er.hash(s);o.highlight.id="R2_HIGHLIGHT_"+l;let h;o.highlight.color?h=o.highlight.color:o.color&&(h=o.color),ht.isHexColor(h)&&(h=ht.hexToRgbString(h)),o.highlight.color=h,o.highlight.pointerInteraction=!0,o.highlight.selectionInfo.cleanText=o.highlight.selectionInfo.rawText.trim().replace(/\n/g," ").replace(/\s\s+/g," "),i.push(o)}),this.store.set(qt.ANNOTATIONS,JSON.stringify(i)),i}saveTemporarySelectionInfo(t){this.store.set(qt.SELECTIONINFO,JSON.stringify(t))}getTemporarySelectionInfo(t){let n=this.store.get(qt.SELECTIONINFO);if(n){let i=JSON.parse(n);return i.range=qd(t,i.rangeInfo),i}return[]}deleteTemporarySelectionInfo(){this.store.remove(qt.SELECTIONINFO)}saveAnnotation(t){let n=this.store.get(qt.ANNOTATIONS);if(n){let i=JSON.parse(n);i.push(t),this.store.set(qt.ANNOTATIONS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(qt.ANNOTATIONS,JSON.stringify(i))}return t}deleteAnnotation(t){let n=this.store.get(qt.ANNOTATIONS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.id!==t),this.store.set(qt.ANNOTATIONS,JSON.stringify(i))}return t}deleteSelectedAnnotation(t){let n=this.store.get(qt.ANNOTATIONS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.highlight?.id!==t.highlight.id),this.store.set(qt.ANNOTATIONS,JSON.stringify(i))}return t}getAnnotations(){let t=this.store.get(qt.ANNOTATIONS);if(t){let n=JSON.parse(t);return n=n.sort((i,o)=>{if(i.locations.progression&&o.locations.progression)return i.locations.progression-o.locations.progression}),n}return[]}getAnnotationPosition(t,n){let i=this.store.get(qt.ANNOTATIONS);if(i){let s=JSON.parse(i).filter(l=>l.highlight?.id===t||l.id===t);if(s.length>0){let l=n.document.getElementById(`${s[0].highlight.id}`);if(l){let h=0;if(l.hasChildNodes)for(let u=0;u<l.childNodes.length;u++){let d=l.childNodes[u],m=parseInt(d.style.top.replace("px",""));(m<h||h===0)&&(h=m)}else h=parseInt(l.style.top.replace("px",""));return h}}}return null}getAnnotationElement(t,n){let i=this.store.get(qt.ANNOTATIONS);if(i){let s=JSON.parse(i).filter(l=>l.highlight?.id===t);if(s.length>0){let l=n.document.getElementById(`${s[0].highlight.id}`);if(l){let h=0;if(l.hasChildNodes)for(let u=0;u<l.childNodes.length;u++){let d=l.childNodes[u],m=parseInt(d.style.top.replace("px",""));if(m<h||h===0)return h=m,d}else h=parseInt(l.style.top.replace("px",""));return l}}}return null}getAnnotation(t){let n=this.store.get(qt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(s=>s.highlight?.id===t.id);if(o.length>0)return o[0]}return null}getAnnotationByID(t){let n=this.store.get(qt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(s=>s.highlight?.id===t);if(o.length>0)return o[0]}return null}},Uo=qt;Uo.LAST_READING_POSITION="last-reading-position",Uo.BOOKMARKS="bookmarks",Uo.ANNOTATIONS="annotations",Uo.SELECTIONINFO="selectionInfo";H();H();var mh=class{constructor(){this.store={}}get(t){return this.store[t]||null}set(t,n){this.store[t]=n}remove(t){this.store[t]=null}};var Sa=class{constructor(t){this.prefix=t.prefix,this.useLocalStorage=t.useLocalStorage;try{let n=t.prefix+"-"+String(Math.random());this.useLocalStorage?(window.localStorage.setItem(n,"test"),window.localStorage.removeItem(n)):(window.sessionStorage.setItem(n,"test"),window.sessionStorage.removeItem(n)),this.fallbackStore=null}catch(n){this.fallbackStore=new mh}}getLocalStorageKey(t){return this.prefix+"-"+t}get(t){let n;return this.fallbackStore?n=this.fallbackStore.get(t):this.useLocalStorage?n=window.localStorage.getItem(this.getLocalStorageKey(t)):n=window.sessionStorage.getItem(this.getLocalStorageKey(t)),n}set(t,n){this.fallbackStore?this.fallbackStore.set(t,n):this.useLocalStorage?window.localStorage.setItem(this.getLocalStorageKey(t),n):window.sessionStorage.setItem(this.getLocalStorageKey(t),n)}remove(t){this.fallbackStore?this.fallbackStore.remove(t):this.useLocalStorage?window.localStorage.removeItem(this.getLocalStorageKey(t)):window.sessionStorage.removeItem(this.getLocalStorageKey(t))}};H();var nx=vt(Va()),ix=vt(ii());var Ll=class extends nx.Link{};Ll=Rc([(0,ix.JsonObject)()],Ll);function Bl(r){let t,n,i,o;if(r instanceof Array)return r.map(function(s){return typeof s=="object"&&(s=Bl(s)),s});t={};for(n in r)r.hasOwnProperty(n)&&(i=(n.charAt(0).toLowerCase()+n.slice(1)||n).toString(),o=r[n],(o instanceof Array||o!==null&&o.constructor===Object)&&(o=Bl(o)),i==="href1"?t.href=o:i==="typeLink"?t.type=o:t[i]=o);return t}H();var rx=vt(dn()),Rg=class{constructor(t){this.LAYERSETTINGS="layerSetting";this.store=t,this.initialize()}static async create(t){let n=new this(t.store);return new Promise(i=>i(n))}async stop(){rx.default.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let t=new Zr,n=await this.store.get(this.LAYERSETTINGS);if(n){let i=JSON.parse(n);t.properties=i}return t}async saveProperty(t){let n=await this.store.get(this.LAYERSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),await this.store.set(this.LAYERSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),await this.store.set(this.LAYERSETTINGS,JSON.stringify(i))}return new Promise(i=>i(t))}async getProperty(t){let n=await this.store.get(this.LAYERSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}};H();var Nl=vt(dn()),Pg=class{static async create(t){let n=new this(t.delegate,t.publication,t,t.headerMenu);return await n.start(),n}constructor(t,n,i,o){this.headerMenu=o,this.delegate=t,this.publication=n,this.properties=i}async stop(){Nl.default.log("Page Break module stop")}async start(){this.delegate.pageBreakModule=this,this.headerMenu&&(this.goToPageView=$e(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=$e(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=$e(this.headerMenu,"#goToPageNumberButton")),Ce(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),Ce(this.goToPageNumberButton,"click",this.goToPageNumber.bind(this)),this.goToPageView&&(this.publication.pageList?.length||this.goToPageView.parentElement?.removeChild(this.goToPageView)),setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("pagebreak"):this.delegate.showLayer("pagebreak")},10)}async goToPageNumber(t){if(this.goToPageNumberInput.value&&(t.key==="Enter"||t.type==="click")){var n=this.publication.pageList?.filter(o=>o.Href.slice(o.Href.indexOf("#")+1).replace(/[^0-9]/g,"")===this.goToPageNumberInput.value);if(n&&n.length>0){var i=n[0];let o={progression:0};if(i.Href.indexOf("#")!==-1){let l=i.Href.slice(i.Href.indexOf("#")+1);l!==null&&(o={fragment:l})}let s={href:this.publication.getAbsoluteHref(i.Href),locations:o,type:i.TypeLink,title:i.Title};this.delegate.goTo(s)}}}async handleResize(){await this.delegate.highlighter?.destroyHighlights(gt.PageBreak),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{let t=this.delegate.iframes[0].contentDocument?.body,n=t?.querySelectorAll('[*|type="pagebreak"]');n?.length===0&&(n=t?.querySelectorAll("[epub\\:type='pagebreak']"));let i=this;function o(s){try{let l=i.delegate.iframes[0].contentDocument;return l?Nn(s,l,Lo):""}catch(l){return Nl.default.log("uniqueCssSelector:"),Nl.default.error(l),""}}if(n)for(let s=0;s<n.length;s++){let l=n[s];Nl.default.log(l);let h=l.innerHTML,u=!1;l.innerHTML.length===0&&(h=l.getAttribute("title")??"",l.innerHTML=h,u=!0),l.innerHTML.length===0&&(h=(l.getAttribute("id")??"").replace(/[^0-9]/g,""),l.innerHTML=h,u=!0);let d=this.delegate.iframes[0].contentDocument;if(d){let m=this.delegate.highlighter?.dom(d.body).getWindow().document.createRange(),y=this.delegate.highlighter?.dom(d.body).getSelection();if(y.removeAllRanges(),m.selectNodeContents(l),y.addRange(m),!y.isCollapsed){let w=oo(m,o);y.removeAllRanges(),w&&this.createPageBreakHighlight({rangeInfo:w,cleanText:"",rawText:""},h)}}u&&(l.innerHTML="")}},200)}createPageBreakHighlight(t,n){try{let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,s=er.hash(o),l="R2_PAGEBREAK_"+s;var i=!1;let h={color:"#000000",id:l,pointerInteraction:i,selectionInfo:t,marker:ot.Custom,icon:{id:"pageBreak",title:n,color:"#000000",position:"left"},type:gt.PageBreak};yn.push(h);let u=this.delegate.highlighter?.createHighlightDom(this.delegate.iframes[0].contentWindow,h);return h.position=parseInt((u?.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px","")),h}catch(o){throw"Can't create highlight: "+o}}};H();var ox=vt(_0());var sx=vt(Mo());var Et=vt(dn()),Mg=class{constructor(t,n,i,o,s,l,h){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,sx.debounce)((t,n)=>{this.restartIndex>=0?(this.ttsQueueIndex=this.restartIndex,this.restartIndex=-1):this.ttsQueueIndex=t,this.ttsQueue=n,this.ttsPlayQueueIndex(this.ttsQueueIndex,n)},150);this.delegate=t,this.tts=n,this.headerMenu=h,this.rights=i,this.highlighter=o,this.properties=s,this.api=l}initialize(t){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=t,this.clean=(0,ox.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),this.wrapper=Rt(document,"#iframe-wrapper"),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,Ce(document,"wheel",this.wheel.bind(this)),Ce(this.body,"wheel",this.wheel.bind(this)),Ce(document,"keydown",this.wheel.bind(this)),Ce(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),Ce(this.body,"mousedown",this.clickStart.bind(this)),Ce(this.body,"mouseup",this.click.bind(this)))}clickStart(t){"clientX"in t&&(this.startX=t.clientX),"clientY"in t&&(this.startY=t.clientY)}click(t){let n=0,i=0;if("clientX"in t&&(n=t.clientX),"clientY"in t&&(i=t.clientY),window.speechSynthesis.speaking&&this.speaking&&n===this.startX&&i===this.startY){let o=this.delegate.iframes[0].contentDocument;if(o){let s=this.highlighter.dom(o.body).getSelection();if(s.isCollapsed){let m=this.delegate.iframes[0].contentDocument,y=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(m);s.addRange(y.range)}let l=s.getRangeAt(0),h=s.anchorNode;for(;l.toString().indexOf(" ")!==0;)try{l.setStart(h,l.startOffset-1)}catch(m){break}l.setStart(h,l.startOffset+1);do l.setEnd(h,h.length<l.endOffset?l.endOffset+1:h.length);while(l.toString().indexOf(" ")===-1&&l.toString().trim()!=="");let d=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(this.ttsQueue&&d){let m=this.findTtsQueueItemIndex(this.ttsQueue,s.anchorNode,s.anchorNode,s.anchorOffset,d);s.removeAllRanges(),m>=0&&(window.speechSynthesis.cancel(),this.restartIndex=m,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}}}}initVoices(t){function n(){return new Promise(function(o,s){let l=window.speechSynthesis,h;h=setInterval(()=>{l.getVoices().length!==0&&(o(l.getVoices()),clearInterval(h))},10)})}n().then(async o=>{if(Et.default.log(o),this.voices=[],o.forEach(l=>{l.localService===!0&&this.voices.push(l)}),Et.default.log(this.voices),t&&this.headerMenu){var s=$e(this.headerMenu,"#preferred-languages");s&&this.voices.forEach(l=>{var h=document.createElement("option");h.value=l.name+":"+l.lang,h.innerHTML=l.name+" ("+l.lang+")",s.add(h)})}})}cancel(t=!0){t&&(this.api?.stopped&&this.api?.stopped(),this.delegate.emit("readaloud.stopped","stopped")),this.userScrolled=!1,this.speaking=!1,setTimeout(()=>{window.speechSynthesis.cancel()},0),this._ttsQueueItemHighlightsWord&&(this.delegate.highlighter?.destroyHighlights(gt.ReadAloud),this._ttsQueueItemHighlightsWord=void 0)}async speak(t,n,i){this.api?.started&&this.api?.started(),this.delegate.emit("readaloud.started","started");let o=this;this.userScrolled=!1,this.cancel(!1);let s;if(n){let S=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body,C=this.delegate.iframes[0].contentDocument;if(C){let x=this.highlighter.dom(C.body).getSelection();if(x.isCollapsed){let E=o.delegate.iframes[0].contentDocument,T=o.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(E);x.addRange(T.range)}if(S){var l=this.generateTtsQueue(S);if(!l.length)return;var h=this.findTtsQueueItemIndex(l,x.anchorNode,x.anchorNode,x.anchorOffset,S),u=this.findTtsQueueItemIndex(l,x.focusNode,x.focusNode,x.focusOffset,S);let E=_s(l,h),T=_s(l,u);var d;if(E&&t&&t.cleanText){let R=Ss(E),O=t.rangeInfo.startOffset,L=t.cleanText;if(T&&h+1===u){let k=Ss(T);O=(R+" "+k).indexOf(t.cleanText),L=R.slice(O,R.length),d=t.cleanText.replace(L,"").trim()}else if(u>h){let k="";for(let F=h+1;F<u;F++){let q=_s(l,F);if(q){let G=Ss(q);k+=G,d=t.cleanText.replace(G,"")}}if(T){let F=Ss(T);k+=" "+F}O=(R+" "+k).indexOf(t.cleanText),L=R.slice(O,R.length),d=d.replace(L,"").trim()}s=new SpeechSynthesisUtterance(L),Et.default.log(t),Et.default.log(L,t.range?.commonAncestorContainer.textContent),Et.default.log(E),Et.default.log(E.item.textNodes),Et.default.log(O),Et.default.log(E.item.combinedText);let M=E.item.textNodes.filter(k=>k===t.range?.commonAncestorContainer)[0];Et.default.log(M),s.onboundary=k=>{this.updateTTSInfo(E,k.charIndex,k.charLength,O,s.text)}}}}}else s=new SpeechSynthesisUtterance(this.clean);s.rate=this.tts.rate,s.pitch=this.tts.pitch,s.volume=this.tts.volume,Et.default.log("this.tts.voice.lang",this.tts.voice.lang);var m=!0;this.tts.voice&&this.tts.voice.lang&&(m=this.tts.voice.lang.indexOf("-")!==-1,m===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),m=!0)),Et.default.log("initialVoiceHasHyphen",m),Et.default.log("voices",this.voices);var y;m===!0?(y=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(b=>{var S=b.lang.replace("_","-");return S===this.tts.voice.lang&&b.name===this.tts.voice.name})[0]:void 0,y===void 0&&(y=this.tts.voice&&this.tts.voice.lang?this.voices.filter(b=>b.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(y=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(b=>b.lang===this.tts.voice.lang&&b.name===this.tts.voice.name)[0]:void 0,y===void 0&&(y=this.tts.voice&&this.tts.voice.lang?this.voices.filter(b=>b.lang===this.tts.voice.lang)[0]:void 0)),Et.default.log("initialVoice",y);var w=o.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;Et.default.log("publicationVoiceHasHyphen",w);var v;w===!0?v=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(b=>{var S=b.lang.replace("_","-");return S.startsWith(o.delegate.publication.Metadata.Language[0])||S.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:v=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(b=>b.lang.startsWith(o.delegate.publication.Metadata.Language[0])||b.lang.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Et.default.log("publicationVoice",v);var g=navigator.language.indexOf("-")!==-1;Et.default.log("defaultVoiceHasHyphen",g);var f;g===!0?f=this.voices.filter(b=>{var S=b.lang.replace("_","-");return S===navigator.language&&b.localService===!0})[0]:f=this.voices.filter(b=>{var S=b.lang;return S===navigator.language&&b.localService===!0})[0],f===void 0&&(f=this.voices.filter(b=>{var S=b.lang;return S.includes(navigator.language)&&b.localService===!0})[0]),Et.default.log("defaultVoice",f),y?(Et.default.log("initialVoice"),s.voice=y):v?(Et.default.log("publicationVoice"),s.voice=v):f&&(Et.default.log("defaultVoice"),s.voice=f),s.voice!==void 0&&s.voice!==null&&(s.lang=s.voice.lang,Et.default.log("utterance.voice.lang",s.voice.lang),Et.default.log("utterance.lang",s.lang)),Et.default.log("navigator.language",navigator.language),setTimeout(()=>{window.speechSynthesis.speak(s)},0),this.index=0;function p(){s.onend=function(){if(u>h)if(h=h+1,h!==u){let b=_s(l,h);if(b){let S=Ss(b);s=new SpeechSynthesisUtterance(S),s.onboundary=C=>{o.updateTTSInfo(b,C.charIndex,C.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s)},0),p()}}else{let b=_s(l,h);b&&(s=new SpeechSynthesisUtterance(d),s.onboundary=S=>{o.updateTTSInfo(b,S.charIndex,S.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s)},0),p()),h>u&&(Et.default.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.delegate.emit("readaloud.finished","finished"))}else Et.default.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.delegate.emit("readaloud.finished","finished")}}p(),i()}speakPlay(){this.scrollPartial=!0,this.cancel(!1),this.api?.started&&this.api?.started(),this.delegate.emit("readaloud.started","started");let t=this,i=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(i){let l=function(){let h=t.highlighter.visibleTextRects[0],u=t.delegate.iframes[0].contentDocument;if(u){let d=t.highlighter.dom(u.body).getWindow().document.createRange(),m=t.highlighter.dom(t.delegate.iframes[0].contentDocument?.body).getSelection();m.removeAllRanges(),d.selectNodeContents(h.node),m.addRange(d);let y=0,w=m.focusNode,v=m.focusOffset;m.collapse(m.anchorNode,m.anchorOffset);for(let g=0;g<y;g++)m.modify("move","forward","line");if(m.extend(w,v),m.collapse(m.anchorNode,m.anchorOffset),i){let g=t.findTtsQueueItemIndex(o,m.anchorNode,m.anchorNode,m.anchorOffset,i);g>=0&&(s=g)}m.removeAllRanges()}},o=this.generateTtsQueue(i);if(!o.length)return;let s=0;l(),s<0&&(s=0),setTimeout(()=>{this.startTTSSession(o,s)},200)}}speakPause(){window.speechSynthesis.speaking&&(this.api?.paused&&this.api?.paused(),this.delegate.emit("readaloud.paused","paused"),this.userScrolled=!1,window.speechSynthesis.pause(),this.speaking=!1,this._ttsQueueItemHighlightsWord&&(this.delegate.highlighter?.destroyHighlights(gt.ReadAloud),this._ttsQueueItemHighlightsWord=void 0))}speakResume(){window.speechSynthesis.speaking&&(this.api?.resumed&&this.api?.resumed(),this.delegate.emit("readaloud.resumed","resumed"),this.userScrolled=!1,window.speechSynthesis.resume(),this.speaking=!0)}static async create(t){let n=new this(t.delegate,t.tts,t.rights,t.highlighter,t,t.api,t.headerMenu);return await n.start(),n}async start(){if(this.delegate.ttsModule=this,this.headerMenu){var t=$e(this.headerMenu,"#menu-button-tts");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties?.hideLayer?this.delegate.hideLayer("readaloud"):this.delegate.showLayer("readaloud")},10)}wheel(t){if(t instanceof KeyboardEvent)switch(t.key){case"ArrowUp":this.userScrolled=!0;break;case"ArrowDown":this.userScrolled=!0;break}else this.userScrolled=!0}stop(){Et.default.log("TTS module stop"),ze(document,"wheel",this.wheel.bind(this)),ze(this.body,"wheel",this.wheel.bind(this)),ze(document,"keydown",this.wheel.bind(this)),ze(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),ze(this.body,"click",this.click.bind(this))}generateTtsQueue(t){let n=[],i=[];function o(u){if(u.nodeType!==Node.TEXT_NODE||!u.nodeValue||!u.nodeValue.trim().length)return;let d=i[i.length-1];if(!d)return;let m=u.parentElement?ax(u.parentElement):void 0,y=u.parentElement?QD(u.parentElement):void 0,w=n[n.length-1];(!w||w.parentElement!==d||w.lang!==m||w.dir!==y)&&(w={combinedText:"",dir:y,lang:m,parentElement:d,textNodes:[]},n.push(w)),w.textNodes.push(u)}let s=!0;function l(u){if(u.nodeType!==Node.ELEMENT_NODE)return;let d=s||u.matches("h1, h2, h3, h4, h5, h6, p, th, td, caption, li, blockquote, q, dt, dd, figcaption, div, pre");s=!1,d&&i.push(u);for(let m of u.childNodes)switch(m.nodeType){case Node.ELEMENT_NODE:let y=m;if(!y.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))l(y);else if(y.tagName&&y.tagName.toLowerCase()==="img"&&y.src){let v=y.getAttribute("alt");if(v){let g=v.trim();if(g){let f=ax(y),p=void 0;n.push({combinedText:g,dir:p,lang:f,parentElement:y,textNodes:[]})}}}break;case Node.TEXT_NODE:i.length!==0&&o(m);break;default:break}d&&i.pop()}l(t);function h(u){if(!u.textNodes||!u.textNodes.length){(!u.combinedText||!u.combinedText.length)&&(u.combinedText="");return}u.combinedText=e8(u.textNodes,!0).replace(/[\r\n]/g," ");let d=u.parentElement;for(;d;){if(d.tagName){let m=d.tagName.toLowerCase();if(m==="pre"||m==="code"||m==="video"||m==="audio")break}d=d.parentElement}}for(let u of n)h(u);return n}findTtsQueueItemIndex(t,n,i,o,s){let l=0;for(let h of t){if(i&&h.textNodes){if(h.textNodes.includes(i))return l}else if(n===h.parentElement||h.parentElement!==n.ownerDocument.body&&h.parentElement!==s&&h.parentElement.contains(n)||n.contains(h.parentElement))return l;l++}return-1}restart(){window.speechSynthesis.speaking&&(window.speechSynthesis.cancel(),this.restartIndex=this.ttsQueueIndex,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}startTTSSession(t,n){if(!_s(t,n)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(n,t)}ttsPlayQueueIndex(t,n){if(t<0){this.cancel();return}let i=_s(n,t);if(!i){this.cancel();return}let o=Ss(i);if(!o){this.cancel();return}let s=new SpeechSynthesisUtterance(o);s.rate=this.tts.rate,s.pitch=this.tts.pitch,s.volume=this.tts.volume,Et.default.log("this.tts.voice.lang",this.tts.voice.lang);var l=!0;this.tts.voice&&this.tts.voice.lang&&(l=this.tts.voice.lang.indexOf("-")!==-1,l===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),l=!0)),Et.default.log("initialVoiceHasHyphen",l),Et.default.log("voices",this.voices);var h;l===!0?(h=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(v=>{var g=v.lang.replace("_","-");return g===this.tts.voice.lang&&v.name===this.tts.voice.name})[0]:void 0,h===void 0&&(h=this.tts.voice&&this.tts.voice.lang?this.voices.filter(v=>v.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(h=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(v=>v.lang===this.tts.voice.lang&&v.name===this.tts.voice.name)[0]:void 0,h===void 0&&(h=this.tts.voice&&this.tts.voice.lang?this.voices.filter(v=>v.lang===this.tts.voice.lang)[0]:void 0)),Et.default.log("initialVoice",h);var u=this,d=u.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;Et.default.log("publicationVoiceHasHyphen",d);var m;d===!0?m=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(v=>{var g=v.lang.replace("_","-");return g.startsWith(u.delegate.publication.Metadata.Language[0])||g.endsWith(u.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:m=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(v=>v.lang.startsWith(u.delegate.publication.Metadata.Language[0])||v.lang.endsWith(u.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Et.default.log("publicationVoice",m);var y=navigator.language.indexOf("-")!==-1;Et.default.log("defaultVoiceHasHyphen",y);var w;y===!0?w=this.voices.filter(v=>{var g=v.lang.replace("_","-");return g===navigator.language&&v.localService===!0})[0]:w=this.voices.filter(v=>{var g=v.lang;return g===navigator.language&&v.localService===!0})[0],w===void 0&&(w=this.voices.filter(v=>{var g=v.lang;return g.includes(navigator.language)&&v.localService===!0})[0]),Et.default.log("defaultVoice",w),h?(Et.default.log("initialVoice"),s.voice=h):m?(Et.default.log("publicationVoice"),s.voice=m):w&&(Et.default.log("defaultVoice"),s.voice=w),s.voice!==void 0&&s.voice!==null&&(s.lang=s.voice.lang,Et.default.log("utterance.voice.lang",s.voice.lang),Et.default.log("utterance.lang",s.lang)),Et.default.log("navigator.language",navigator.language),s.onboundary=v=>{Et.default.log(v.name),this.updateTTSInfo(i,v.charIndex,v.charLength,0,s.text)},setTimeout(()=>{window.speechSynthesis.speak(s),u.speaking||window.speechSynthesis.pause()},0),s.onend=function(){u.speaking&&u.ttsPlayQueueIndexDebounced(t+1,n)}}updateTTSInfo(t,n,i,o,s){if(!t)return;Et.default.log(t,n,i,s);let l=s||Ss(t);if(n>=0&&s){let h=s.slice(0,n+1).search(/\S+$/),u=s.slice(n).search(/\s/),d=u<0?s.slice(h):s.slice(h,u+n),m=h+d.length;if(i===void 0){let y=s.substring(n).match(/^[a-z\d']*/i);y&&(i=y[0].length)}i===void 0&&(i=d.length),this.wrapHighlightWord(t,s,n+o,i,d,h,m)}return l}wrapHighlightWord(t,n,i,o,s,l,h){Et.default.log(t),Et.default.log(n),Et.default.log(i,o,s,l,h),this._ttsQueueItemHighlightsWord&&(this.delegate.highlighter?.destroyHighlights(gt.ReadAloud),this._ttsQueueItemHighlightsWord=void 0);let u=t.item,d=i,m=0,y,w=-1,v,g=-1,f=d+o;for(let b of u.textNodes){if(!b.nodeValue&&b.nodeValue!=="")continue;let S=b.nodeValue.length;if(m+=S,y||d<m&&(y=b,w=S-(m-d)),y&&f<=m&&(v=b,g=S-(m-f)),v)break}if(y&&v){let S=function(E){try{let T=p.delegate.iframes[0].contentDocument;return T?Nn(E,T,Lo):""}catch(T){return Et.default.log("uniqueCssSelector:"),Et.default.error(T),""}},b=new Range;b.setStart(y,w),b.setEnd(v,g);var p=this;let C=oo(b,S);if(!C)return;let x=this.delegate.highlighter?.createHighlight(this.delegate.iframes[0].contentWindow,{rangeInfo:C,cleanText:"",rawText:"",range:void 0},this.tts.color,!1,ot.Custom,{id:"tts",title:"",position:"right"},void 0,{defaultClass:this.tts.color},gt.ReadAloud,"R2_READALOUD_");if(x){this._ttsQueueItemHighlightsWord=x[0];let R=(x[1]?.firstChild?.getBoundingClientRect()).top-this.wrapper.scrollTop>window.innerHeight/2-65;this.delegate.view?.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&this.scrollPartial&&R?x[1]?.firstChild?.scrollIntoView({block:"center",behavior:"smooth"}):this.delegate.view?.isPaginated()&&p.delegate.view?.snap(x[1]?.firstChild)}}}};function ax(r){let t=r;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let n=t.getAttribute("xml:lang");if(n||(n=t.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang")),n||(n=t.getAttribute("lang")),n)return n;t=t.parentNode}}function QD(r){let t=r;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let n=t.getAttribute("dir");if(n)return n;t=t.parentNode}}function e8(r,t){if(r&&r.length){let n="";for(let i of r)i.nodeValue&&(n+=t?i.nodeValue:n8(i.nodeValue));return n}return""}function t8(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function n8(r){return t8(r).replace(/\n/g," ").replace(/\s\s+/g," ")}function _s(r,t){let n=-1,i=-1;for(let o of r)if(i++,n++,t===n)return{item:o,iArray:i,iGlobal:n,iSentence:-1}}function Ss(r){return r.item.combinedText}H();var Dl=vt(zd());var lx=vt(Mo());var cx=vt(dn()),kg=class{constructor(t,n,i,o,s){this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,lx.debounce)(async()=>{if(await this.highlighter.destroyHighlights(gt.Definition),this.properties.definitions)for(let t of this.properties.definitions)await this.define(t)},200);this.delegate=t,this.publication=n,this.properties=i,this.api=s,this.highlighter=o}static async create(t){let n=new this(t.delegate,t.publication,t,t.highlighter,t.api);return await n.start(),n}async stop(){cx.default.log("Definitions module stop")}async start(){this.delegate.definitionsModule=this,setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("definitions"):this.delegate.showLayer("definitions")},10)}async searchAndPaint(t,n){let i=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[this.delegate.currentResource()??0].Href:""),o=this.publication.getTOCItem(i);o===void 0&&this.publication.readingOrder&&(o=this.publication.readingOrder[this.delegate.currentResource()??0]);let s=[];if(o)for(let l of t.terms){let h=t.terms.indexOf(l);o&&await jo(l,this.delegate.iframes[0].contentDocument,o.Href,o.Title,this.delegate.definitionsModule?.properties.fullWordSearch).then(u=>{let d;t.result===1?d=0:t.result===2&&(d=Math.floor(Math.random()*u.length-1)+1),u.forEach((m,y)=>{if(d===void 0||d===y){let w={rangeInfo:m.rangeInfo},v=this.createDefinitionHighlight(w,t);m.highlight=v,s.push(Dl.omit(v,"definition")),this.currentChapterPopupResult.push(m),this.currentPopupHighlights.push(v)}}),h===t.terms.length-1&&n(s)})}}async define(t){await this.searchAndPaint(t,async n=>{this.api?.success&&(this.api?.success(Dl.omit(t,"callbacks"),n),this.delegate.emit("definition.success",n),this.api?.visible&&n.forEach(i=>{let s=this.delegate.iframes[0].contentDocument?.querySelector(`#${i.id}`)?.querySelectorAll(`.${$n}`),l=new IntersectionObserver((h,u)=>{h.forEach(d=>{d.intersectionRatio===1&&(this.api?.visible(Dl.omit(t,"callbacks"),Dl.omit(i,"definition")),this.delegate.emit("definition.visible",t,i))})},{threshold:1});s&&s.length>0&&l.observe(s[0])}))})}async drawDefinitions(){setTimeout(async()=>{await this.definitions()},100)}async handleResize(){await this.drawDefinitions()}createDefinitionHighlight(t,n){try{let i=this.delegate.definitionsModule?.properties.color;ht.isHexColor(i)&&(i=ht.hexToRgbChannels(i));let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,s=er.hash(o),l="R2_DEFINITION_"+s;this.highlighter.destroyHighlight(this.delegate.iframes[0].contentDocument,l);let h={color:i||gs,id:l,pointerInteraction:!0,selectionInfo:t,marker:ot.Underline,type:gt.Definition};yn.push(h);let u=this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,h);return u&&(n.definition&&(u.dataset.definition=n.definition),u.dataset.order=String(n.order),h.definition=n,h.position=parseInt((u?.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px",""))),h}catch(i){throw"Can't create definitions highlight: "+i}}async addDefinition(t){await this.define(t)}async clearDefinitions(){await this.highlighter.destroyHighlights(gt.Definition)}};H();var $o=vt(dn()),ux=.5,yh=class{constructor(t,n,i,o){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.delegate=t,this.properties=n,this.api=o,this.highlighter=i}static async create(t){let n=new this(t.delegate,t,t.highlighter,t.api);return await n.start(),n}async stop(){$o.default.log("Definitions module stop"),this.hasEventListener=!1,ze(document,"keydown",this.keydown.bind(this)),ze(document,"keyup",this.keyup.bind(this)),ze(this.delegate.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),ze(this.delegate.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){this.delegate.lineFocusModule=this;let t=Rt(document,"#iframe-wrapper");t.style.height.length>0&&(this.wrapperHeight=t.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")),this.hasEventListener||(this.hasEventListener=!0,Ce(document,"keydown",this.keydown.bind(this)),Ce(document,"keyup",this.keyup.bind(this)),Ce(this.delegate.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),Ce(this.delegate.iframes[0].contentDocument,"keyup",this.keyup.bind(this)))}keydown(t){if(t instanceof KeyboardEvent&&this.isActive)switch(t.key){case"ArrowUp":t.stopPropagation();break;case"ArrowDown":t.stopPropagation();break}}keyup(t){if(t instanceof KeyboardEvent&&this.isActive)switch(t.key){case"ArrowUp":this.lineUp();break;case"ArrowDown":this.lineDown();break}}handleResize(){this.isActive&&this.lineFocus()}async enableLineFocus(){this.isActive=!0,await this.delegate.settings.scroll(!0),this.lineFocus()}disableLineFocus(t=!0){this.isActive=!1;let n=Rt(document,"#iframe-wrapper");this.wrapperHeight&&(n.style.height=this.wrapperHeight),t||(this.index=0);let i=this.delegate.iframes[0].contentDocument;On(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 l=document.getElementById("divBefore");l&&l.remove();let h=document.getElementById("divAfter");h&&h.remove(),this.highlighter.destroyHighlights(gt.LineFocus)}lineFocus(){let t=Rt(document,"#iframe-wrapper"),n=this.delegate.iframes[0].contentDocument,i=On(n,"html"),o=this.properties.maxHeight?gr()*this.properties.maxHeight/100:gr()/2;i.style.setProperty("--USER__maxMediaHeight",o+"px");function s(m,y){m.parentNode.insertBefore(y,m.nextSibling)}function l(m,y){m.parentNode.insertBefore(y,m)}let h=document.getElementById("container-view-timeline");h&&(h.style.display="none"),this.lineFocusContainer&&this.lineFocusContainer.style.removeProperty("display");let u=document.getElementById("divBefore");if(u)u.style.height=t.clientHeight/2+"px";else{let m=document.createElement("div");m.style.height=t.clientHeight/2+"px",m.id="divBefore",l(t,m)}let d=document.getElementById("divAfter");if(d)d.style.height=t.clientHeight/2+"px";else{let m=document.createElement("div");m.style.height=t.clientHeight/2+"px",m.id="divAfter",s(t,m)}if(this.lines=[],n){let w=function(){let S=Math.round,C=Math.random,x=255;return{blue:S(C()*x),green:S(C()*x),red:S(C()*x)}},v=function(S,C){let x=[];for(let E=0,T=0;E<S.length;E++)E>=C&&E%C==0&&T++,x[T]=x[T]||[],x[T].push(S[E]);return x},g=function(S,C){let x=Math.min(S.left,C.left),E=Math.max(S.right,C.right),T=Math.min(S.top,C.top),R=Math.max(S.bottom,C.bottom);return{bottom:R,height:R-T,left:x,right:E,top:T,width:E-x}},f=function(S){if(S.length>1){let C=g(S[0],S[1]);if(S.length>2){let x=g(C,S[2]);if(S.length>3){let E=g(x,S[3]);return S.length>4?g(E,S[4]):E}return x}return C}return S[0]},m=this.findRects(n.body);m=O0(m,!0),m=m.sort(function(S,C){return S.top-C.top});let y=[];m=m.filter(function(S){let C=S.top;return y.indexOf(C)===-1&&y.indexOf(C+1)===-1&&y.indexOf(C+2)===-1&&y.indexOf(C+3)===-1&&y.indexOf(C+4)===-1&&y.indexOf(C-1)===-1&&y.indexOf(C-2)===-1&&y.indexOf(C-3)===-1&&y.indexOf(C-4)===-1?(y.push(C),!0):!1}),this.highlighter.destroyHighlights(gt.LineFocus);let p=[];this.properties.lines&&this.properties.lines>1?v(m,this.properties.lines).forEach(C=>{p.push(f(C))}):p=m;let b=$e(n,"#"+et.R2_ID_LINEFOCUS_CONTAINER);if(b)for(let S of p){let C=document.createElement("div");C.setAttribute("class",$n);let x=w();if(ht.isHexColor(x)&&(x=ht.hexToRgbChannels(x)),this.isDebug){let ce=`border-bottom: 1px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${ux}) !important`;C.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${ux}) !important; ${ce}`)}C.style.outline="none",C.tabIndex=0;let E=this.delegate.iframes[0].contentWindow.document,T=this.delegate.view.isPaginated();T?E.body.style.position="revert":E.body.style.position="relative";let R=E.body.getBoundingClientRect(),O=this.highlighter.getScrollingElement(E),L=T?-O.scrollLeft:R.left,M=T?-O.scrollTop:R.top,k=1,F=24,q,G,ie=this.delegate.iframes[0].contentWindow?.innerWidth,ee=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-count")),Q=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-width")),X=parseInt(getComputedStyle(n.body).getPropertyValue("padding-left"));if(ie){let ce=ie/(ee||1);ce<Q&&(ce=ie),T||(ce=parseInt(getComputedStyle(n.body).width.replace("px","")));let we=this.delegate.settings.fontSize/100,ve=20*we;we<=1&&(ve=-60);let Z=0;we<=1&&(Z=-60),q=Math.floor(S.left/ce)*ce+ce-(F<40?40:F)+Z,G=Math.floor(S.left/ce)*ce+(F<40?40:F)-ve;let N=parseInt(n.documentElement.style.getPropertyValue("--USER__pageMargins"));N>=2&&(G=G+X/ee,q=q-X/ee),T||(q=parseInt(getComputedStyle(n.body).width.replace("px","")),G=parseInt(getComputedStyle(n.body).width.replace("px",""))-ce,N>=2&&(G=G+X/2,q=q-X/2))}C.style.setProperty("pointer-events","none"),C.style.position="absolute",C.scale=k,C.rect={height:S.height,left:S.left-L,top:S.top-M,width:S.width},C.style.width=`${C.rect.width*k}px`,C.style.height=`${C.rect.height*k}px`,C.style.left=`${C.rect.left*k}px`,C.style.top=`${C.rect.top*k}px`,this.lines.push(C),b.append(C)}setTimeout(()=>{this.currentLine()},100)}}currentLine(){let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.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 t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}}lineUp(){if(this.index>0){this.index-=1,this.index<0&&(this.index=0);let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}}almostEqual(t,n,i){return Math.abs(t-n)<=i}findRects(t){let n=this.findTextNodes(t),i=Array.from(t.getElementsByTagName("img")),o=[];return n.forEach(s=>{o.push(...this.measureTextNodes(s))}),i.forEach(s=>{o.push(...this.measureImageNodes(s))}),o}findTextNodes(t,n=[]){let i=t.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,n),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"&&n.push(i),i=i.nextSibling;return n}measureTextNodes(t){try{let n=document.createRange();n.selectNodeContents(t);let i=Array.from(n.getClientRects());return n.detach(),i}catch(n){$o.default.log("measureTextNode "+n),$o.default.log("measureTextNode "+t),$o.default.log(`${t.textContent}`)}}measureImageNodes(t){try{let n=document.createRange();n.selectNode(t);let i=Array.from(n.getClientRects());return n.detach(),i}catch(n){$o.default.log("measureTextNode "+n),$o.default.log("measureTextNode "+t),$o.default.log(`${t.textContent}`)}}};H();var bh=vt(dn()),Ig=class{constructor(t,n,i,o,s){this.history=[];this.headerMenu=s,this.delegate=n,this.publication=i,this.properties=o,this.annotator=t}static async create(t){let n=new this(t.annotator,t.delegate,t.publication,t,t.headerMenu);return await n.start(),n}async stop(){bh.default.log("Page Break module stop"),ze(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),ze(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(t,n){let i;if(n&&this.annotator){let o=await this.annotator.getLastReadingPosition();if(o&&o.locations.progression&&o.locations.progression>0&&(this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex)),i=this.history[this.history.length-1],i&&i.href!==o.href||i===void 0)){let s=this.publication.getAbsoluteHref(o.href);bh.default.log(o.href),bh.default.log(s),o.href=s,this.history.push(o),this.historyCurrentIndex=this.history.length-1}this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex)),i=this.history[this.history.length-1],(i&&i.href!==t.href||i===void 0)&&(this.history.push(t),this.historyCurrentIndex=this.history.length-1)}}async start(){this.delegate.historyModule=this,this.headerMenu&&(this.historyForwardAnchorElement=$e(this.headerMenu,"#history-forward")),this.headerMenu&&(this.historyBackAnchorElement=$e(this.headerMenu,"#history-back")),this.historyCurrentIndex=this.history.length-1,Ce(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),Ce(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleHistoryForwardClick(t){await this.historyForward(),t.preventDefault(),t.stopPropagation()}async historyForward(){this.history.length>0&&this.historyCurrentIndex+1<this.history.length&&(this.historyCurrentIndex=this.historyCurrentIndex+1,await this.delegate.navigate(this.history[this.historyCurrentIndex],!1))}async handleHistoryBackClick(t){await this.historyBack(),t.preventDefault(),t.stopPropagation()}async historyBack(){this.history.length>0&&this.historyCurrentIndex>0&&(this.historyCurrentIndex=this.historyCurrentIndex-1,await this.delegate.navigate(this.history[this.historyCurrentIndex],!1))}};H();var dx=vt(dn()),Pt;(function(i){i[i.Chicago=0]="Chicago",i[i.MLA=1]="MLA",i[i.APA=2]="APA"})(Pt||(Pt={}));var hx;(function(o){o.Author="Author",o.Editor="Editor",o.Translator="Translator",o.Compiler="Compiler"})(hx||(hx={}));var vh=class{constructor(t,n,i,o,s){this.highlighter=i,this.delegate=t,this.properties=o,this.publication=n,this.api=s}static async create(t){let n=new this(t.delegate,t.publication,t.highlighter,t,t.api);return await n.start(),n}async stop(){dx.default.log("Citation module stop")}copyToClipboard(t){this.delegate?.contentProtectionModule&&(this.delegate.contentProtectionModule.citation=!0);let n=!0;if(window.clipboardData)window.clipboardData.setData("text/plain",t);else{let i=this.createElementForExecCommand(t);this.selectContent(i);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),n=document.execCommand("copy",!1)}catch(o){n=!1}document.body.removeChild(i)}n?this.api?.citationCreated("The text was copied to the clipboard!"):this.api?.citationFailed("Your browser doesn't allow clipboard access!")}createElementForExecCommand(t){let n=document.createElement("div");return n.style.position="absolute",n.style.left="-10000px",n.style.top="-10000px",n.innerHTML=t,document.body.appendChild(n),n.contentEditable=!0,n}selectContent(t){let n=document.createRange();n.selectNodeContents(t);let i=window.getSelection();i?.removeAllRanges(),i?.addRange(n)}async start(){this.delegate.citationModule=this;let t=this,n={id:"citationIcon",callback:function(i){let o=function(){let O="",L="",M="";return t.properties.author?(M=M+t.properties.author,L=L+t.properties.author,O=O+t.properties.author):t.publication.Metadata.Author?.length>0&&0===0&&t.publication.Metadata.Author[0].Name&&t.publication.Metadata.Author[0].Name.length>0&&(M=M+t.publication.Metadata.Author[0].Name,L=L+t.publication.Metadata.Author[0].Name,O=O+t.publication.Metadata.Author[0].Name),M.length>0&&L.length>0&&O.length>0?[O+". ",L+". ",M+". "]:["","",""]},s=function(){let O="",L="",M="";return t.properties.publisher?(L=L+t.properties.publisher+", ",O=O+t.properties.publisher+", "):t.publication.Metadata.Publisher&&t.publication.Metadata.Publisher[0].Name&&(L=L+t.publication.Metadata.Publisher[0].Name+", ",O=O+t.publication.Metadata.Publisher[0].Name+", "),t.properties.published?(M=M+"("+t.properties.published+")",L=L+t.properties.published,O=O+t.properties.published):t.publication.Metadata.PublicationDate&&t.publication.Metadata.PublicationDate.getFullYear()>0&&(M=M+"("+t.publication.Metadata.PublicationDate.getFullYear()+")",L=L+t.publication.Metadata.PublicationDate.getFullYear(),O=O+t.publication.Metadata.PublicationDate.getFullYear()),M.length>0&&L.length>0&&O.length>0?[O+". ",L+". ",M+". "]:["","",""]},l=function(){return t.properties.title?[t.properties.title+". ",t.properties.title+". ",t.properties.title+". "]:t.publication.Metadata.Title?[t.publication.Metadata.Title+". ",t.publication.Metadata.Title+". ",t.publication.Metadata.Title+". "]:["","",""]},h=function(){return["","",""]},u=function(){let O="",L="",M="";return t.properties.publisher?(L=L+t.properties.publisher+", ",O=O+t.properties.publisher+", ",M=M+t.properties.publisher+", "):t.publication.Metadata.Publisher&&t.publication.Metadata.Publisher[0].Name&&(L=L+t.publication.Metadata.Publisher[0].Name+", ",O=O+t.publication.Metadata.Publisher[0].Name+", ",M=M+t.publication.Metadata.Publisher[0].Name+", "),M.length>0&&L.length>0&&O.length>0?[O+". ",L+". ",M+". "]:["","",""]},d=function(){return["","",""]},m=function(){return["","",""]},y=function(){return["","",""]},w=function(){return t.properties.library?["Retrieved from "+t.properties.library+". ","Retrieved from "+t.properties.library+". ","Retrieved from "+t.properties.library+". "]:["","",""]},v=function(){return t.properties.appName?[t.properties.appName+". ",t.properties.appName+". ",t.properties.appName+". "]:["","",""]},g=function(){return t.properties.appLink?[t.properties.appLink+". ",t.properties.appLink+". ",t.properties.appLink+". "]:["","",""]},f=function(){return["","",""]},p=function(O,L){return O.length>L?O.substring(0,L)+"...":O},b=o()[0]+l()[0]+d()[0]+h()[0]+y()[0]+s()[0]+m()[0]+w()[0]+v()[0]+g()[0],S=o()[2]+s()[2]+l()[2]+h()[2]+u()[2]+d()[2]+m()[2]+y()[2]+w()[2]+v()[2]+g()[2],C=o()[1]+l()[1]+d()[1]+h()[1]+y()[1]+s()[1]+f()[1]+w()[1]+v()[1]+g()[1],x="\u201C"+p(i,t.properties.characters)+"\u201C<br><br><em>"+b+"</em>",E="\u201C"+p(i,t.properties.characters)+"\u201C<br><br><em>"+S+"</em>",T="\u201C"+p(i,t.properties.characters)+"\u201C<br><br><em>"+C+"</em>",R="";t.properties.styles?.includes(Pt[0])&&(R=R+"Chicago: <br>"+x+"<br><br>"),t.properties.styles?.includes(Pt[2])&&(R=R+"APA: <br>"+E+"<br><br>"),t.properties.styles?.includes(Pt[1])&&(R=R+"MLA: <br>"+T+"<br><br>"),t.copyToClipboard(R)}};this.highlighter?.addSelectionMenuItem(n)}};H();var Nx=vt(Og()),Aa=vt(Lx());H();var Bx="grab-to-pan-grab",_h,S8,Sh,A8,Ah,x8,jg=class{constructor(t){ke(this,_h);ke(this,Sh);ke(this,Ah);this.element=t.element,this.document=t.element.ownerDocument,typeof t.ignoreTarget=="function"&&(this.ignoreTarget=t.ignoreTarget),this.onActiveChanged=t.onActiveChanged,this.activate=this.activate.bind(this),this.deactivate=this.deactivate.bind(this),this.toggle=this.toggle.bind(this),this._onMouseDown=De(this,_h,S8).bind(this),this._onMouseMove=De(this,Sh,A8).bind(this),this._endPan=De(this,Ah,x8).bind(this);let n=this.overlay=document.createElement("div");n.className="grab-to-pan-grabbing"}activate(){this.active||(this.active=!0,this.element.addEventListener("mousedown",this._onMouseDown,!0),this.element.classList.add(Bx),this.onActiveChanged?.(!0))}deactivate(){this.active&&(this.active=!1,this.element.removeEventListener("mousedown",this._onMouseDown,!0),this._endPan(),this.element.classList.remove(Bx),this.onActiveChanged?.(!1))}toggle(){this.active?this.deactivate():this.activate()}ignoreTarget(t){return t.matches("a[href], a[href] *, input, textarea, button, button *, select, option")}};_h=new WeakSet,S8=function(t){if(t.button!==0||this.ignoreTarget(t.target))return;if(t.originalTarget)try{t.originalTarget.tagName}catch(i){return}this.scrollLeftStart=this.element.scrollLeft,this.scrollTopStart=this.element.scrollTop,this.clientXStart=t.clientX,this.clientYStart=t.clientY,this.document.addEventListener("mousemove",this._onMouseMove,!0),this.document.addEventListener("mouseup",this._endPan,!0),this.element.addEventListener("scroll",this._endPan,!0),t.preventDefault(),t.stopPropagation();let n=document.activeElement;n&&!n.contains(t.target)&&n.blur()},Sh=new WeakSet,A8=function(t){if(this.element.removeEventListener("scroll",this._endPan,!0),!(t.buttons&1)){this._endPan();return}let n=t.clientX-this.clientXStart,i=t.clientY-this.clientYStart,o=this.scrollTopStart-i,s=this.scrollLeftStart-n;this.element.scrollTo?this.element.scrollTo({top:o,left:s,behavior:"instant"}):(this.element.scrollTop=o,this.element.scrollLeft=s),this.overlay.parentNode||document.body.append(this.overlay)},Ah=new WeakSet,x8=function(){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 xa;(function(n){n[n.Page=0]="Page",n[n.Width=1]="Width"})(xa||(xa={}));var Nr=class extends Nx.default{constructor(t,n,i){super();this.pdfDoc=null;this.pageNum=1;this.scaleType=0;this.pageRendering=!1;this.pageNumPending=null;this.scale=1;this.resourceIndex=0;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.settings=t,this.publication=n,this.api=i}static async create(t){let n=new this(t.settings,t.publication,t.api);return await n.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(n))}async start(t,n,i){this.headerMenu=n,this.footerMenu=i,this.mainElement=t,this.resourceIndex=0,this.resource=this.publication.readingOrder[this.resourceIndex],console.log(this.resource),console.log(this.resource.Href1),Aa.GlobalWorkerOptions.workerSrc="//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.js",this.wrapper=Rt(this.mainElement,"main#iframe-wrapper"),this.pdfContainer=Rt(this.mainElement,"#pdf-container"),this.handTool=new jg({element:this.pdfContainer});let o=this,s=document.createElement("div");s.id="loadingpdf",s.innerHTML=dh,s.style.width=getComputedStyle(this.wrapper).width,s.style.height=getComputedStyle(this.wrapper).height,s.style.display="flex",s.style.zIndex="100",s.style.position="absolute",s.style.alignItems="center",s.style.justifyContent="center",s.style.background="white",s.className="loading is-loading",this.pdfContainer.appendChild(s),(0,Aa.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(l){o.pdfDoc=l,o.loadPDFJS(o.pageNum)}),this.setupEvents()}async handleResize(){this.loadPDFJS(this.pageNum)}setupEvents(){Ce(window,"resize",this.onResize)}loadPDFJS(t){let n=this,i=1;this.wrapper.style.height="calc(100vh - 10px)",this.pdfContainer.style.height="calc(100vh - 10px)",this.pdfContainer.style.flexDirection="column";let o=document.getElementsByTagName("canvas");Array.from(o).forEach(function(l){l?.parentNode?.removeChild(l)});function s(l){let h=document.createElement("canvas");h.id=String(i),h.style.border="1px solid gray",h.style.margin="1px";let u=l.getViewport({scale:n.scale});if(n.scale===1){let v=n.wrapper.clientHeight/u.height,g=n.wrapper.clientWidth/u.width;console.log(v,g),n.scaleType===0?u=l.getViewport({scale:v<g?v:g}):u=l.getViewport({scale:g})}n.pdfContainer.appendChild(h);let d=h.getContext("2d");h.height=u.height,h.width=u.width;let m={canvasContext:d,viewport:u},y=document.getElementById("loadingpdf");y.style.display="flex",y.style.width=getComputedStyle(n.wrapper).width,y.style.height=getComputedStyle(n.wrapper).height,l.render(m).promise.then(function(){i<n.pdfDoc.numPages?(i++,n.pdfDoc.getPage(i).then(s)):(document.getElementById(String(t))?.scrollIntoView(),y.style.display="none",n.api?.resourceReady&&n.api?.resourceReady(),n.emit("resource.ready"))})}this.pdfDoc.getPage(i).then(s)}queueRenderPage(t){let n=this;n.pageRendering?n.pageNumPending=t:(this.pageNum=t,document.getElementById(String(t))?.scrollIntoView())}readingOrder(){return this.publication.readingOrder}tableOfContents(){return this.publication.tableOfContents}currentResource(){}totalResources(){return this.publication.readingOrder.length}currentLocator(){}positions(){return this.publication.positions?this.publication.positions:[]}nextPage(){let t=this;if(t.pageNum>=t.pdfDoc.numPages){this.nextResource();return}this.pageNum++,this.queueRenderPage(t.pageNum)}previousPage(){let t=this;if(t.pageNum<=1){this.previousResource();return}t.pageNum--,t.queueRenderPage(t.pageNum)}nextResource(){let t=this;console.log(t.resourceIndex,this.publication.readingOrder.length-1),!(this.resourceIndex>=this.publication.readingOrder.length-1)&&(t.resourceIndex++,t.resource=this.publication.readingOrder[t.resourceIndex],console.log(this.resource.Href1),(0,Aa.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(n){t.pdfDoc=n,t.pageNum=1,t.loadPDFJS(t.pageNum)}))}previousResource(){let t=this;console.log(t.resourceIndex,this.publication.readingOrder.length-1),this.resourceIndex!==0&&(t.resourceIndex--,t.resource=this.publication.readingOrder[t.resourceIndex],console.log(this.resource.Href1),(0,Aa.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(n){t.pdfDoc=n,t.pageNum=t.pdfDoc.numPages,t.loadPDFJS(t.pageNum)}))}goTo(t){console.log(t);let n=new URL(t.href);if(n.searchParams.has("start")){let i=n.searchParams.get("start");i&&this.queueRenderPage(parseInt(i))}else this.queueRenderPage(1)}goToPosition(t){console.log(t),this.queueRenderPage(t)}async goToPage(t){console.log(t),this.queueRenderPage(t)}fitToWidth(){console.log("fit to width",this.pageNum),this.scale=1,this.scaleType=1,this.loadPDFJS(this.pageNum)}fitToPage(){console.log("fit to page",this.pageNum),this.scale=1,this.scaleType=0,this.loadPDFJS(this.pageNum)}zoomIn(){this.scale=this.scale+.2,this.loadPDFJS(this.pageNum)}zoomOut(){this.scale=this.scale-.2,this.loadPDFJS(this.pageNum)}activateHand(){this.handTool.activate()}deactivateHand(){this.handTool.deactivate()}async scroll(t,n){t?(n==="horizontal"?this.pdfContainer.style.flexDirection="row":this.pdfContainer.style.flexDirection="column",this.pdfContainer.style.overflow="auto"):(this.pdfContainer.style.flexDirection="column",this.pdfContainer.style.overflow="hidden")}stop(){ze(window,"resize",this.onResize)}};var qo=class{constructor(t,n,i,o,s,l,h,u,d,m,y,w,v,g,f,p,b){this.settings=t;this.navigator=n;this.highlighter=i;this.bookmarkModule=o;this.annotationModule=s;this.ttsSettings=l;this.ttsModule=h;this.searchModule=u;this.definitionsModule=d;this.contentProtectionModule=m;this.timelineModule=y;this.mediaOverlaySettings=w;this.mediaOverlayModule=v;this.pageBreakModule=g;this.lineFocusModule=f;this.historyModule=p;this.citationModule=b;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 t=>await this.bookmarkModule?.deleteBookmark(t)??!1;this.deleteAnnotation=async t=>await this.annotationModule?.deleteAnnotation(t)??!1;this.addAnnotation=async t=>await this.annotationModule?.addAnnotation(t)??!1;this.hideAnnotationLayer=()=>this.annotationModule?.hideAnnotationLayer();this.showAnnotationLayer=()=>this.annotationModule?.showAnnotationLayer();this.hideLayer=t=>this.navigator instanceof _t?this.navigator?.hideLayer(t):!1;this.showLayer=t=>this.navigator instanceof _t?this.navigator?.showLayer(t):!1;this.activateMarker=(t,n)=>this.navigator instanceof _t?this.navigator?.activateMarker(t,n):!1;this.deactivateMarker=()=>this.navigator instanceof _t?this.navigator?.deactivateMarker():!1;this.clearDefinitions=async()=>{await this.definitionsModule?.clearDefinitions()};this.addDefinition=async t=>{await this.definitionsModule?.addDefinition(t)};this.historyBack=async()=>this.historyModule?.historyBack();this.historyForward=async()=>this.historyModule?.historyForward();this.search=async(t,n)=>await this.searchModule?.search(t,n)??[];this.goToSearchIndex=async(t,n,i)=>{this.navigator instanceof _t&&this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchIndex(t,n,i)};this.goToSearchID=async(t,n,i)=>{this.navigator instanceof _t&&this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchID(t,n,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 t=>await this.settings.applyUserSettings(t);this.scroll=async(t,n)=>this.navigator instanceof Nr?this.navigator.scroll(t,n):await this.settings.scroll(t);this.increase=async t=>{this.isTTSIncrementable(t)?this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.increase(t):this.isMOIncrementable(t)?this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.increase(t):await this.settings.increase(t)};this.decrease=async t=>{this.isTTSIncrementable(t)?this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.decrease(t):this.isMOIncrementable(t)?this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.decrease(t):await this.settings.decrease(t)};this.resetTTSSettings=()=>{this.navigator instanceof _t&&this.navigator.rights.enableTTS&&this.ttsSettings?.resetTTSSettings()};this.applyTTSSettings=async t=>{this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.applyTTSSettings(t)};this.applyPreferredVoice=async t=>{this.navigator instanceof _t&&this.navigator.rights.enableTTS&&await this.ttsSettings?.applyPreferredVoice(t)};this.resetMediaOverlaySettings=async()=>{this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.resetMediaOverlaySettings()};this.applyMediaOverlaySettings=async t=>{this.navigator instanceof _t&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.applyMediaOverlaySettings(t)};this.goTo=async t=>{this.navigator.goTo(t)};this.goToPosition=async t=>this.navigator.goToPosition(t);this.goToPage=async t=>{await this.navigator.goToPage(t)};this.fitToPage=()=>{this.navigator instanceof Nr&&this.navigator.fitToPage()};this.fitToWidth=()=>{this.navigator instanceof Nr&&this.navigator.fitToWidth()};this.zoomIn=()=>{this.navigator instanceof Nr&&this.navigator.zoomIn()};this.zoomOut=()=>{this.navigator instanceof Nr&&this.navigator.zoomOut()};this.activateHand=()=>{this.navigator instanceof Nr&&this.navigator.activateHand()};this.deactivateHand=()=>{this.navigator instanceof Nr&&this.navigator.deactivateHand()};this.copyToClipboard=t=>{this.contentProtectionModule?.copyToClipboard(t)};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 t=>{this.navigator instanceof _t&&this.navigator.snapToSelector(t)};this.applyAttributes=t=>{this.navigator instanceof _t&&this.navigator.applyAttributes(t)};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()}}addEventListener(){this.navigator instanceof _t&&this.navigator.addListener(arguments[0],arguments[1])}static async load(t){let n=t.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};n.enableContentProtection&&t.protection&&await lh.setupPreloadProtection(t.protection);let i=Rt(document,"#D2Reader-Container"),o=$e(document,"#headerMenu"),s=$e(document,"#footerMenu"),l=t.url,h;t.publication?(h=ea(t.publication,Co),h.manifestUrl=new URL(l)):h=await Co.fromUrl(l,t.requestConfig);let u=new Sa({prefix:h.manifestUrl,useLocalStorage:t.useLocalStorage??!1}),d=new Sa({prefix:"r2d2bc-reader",useLocalStorage:t.useLocalStorage??!1}),m=new Sa({prefix:"r2d2bc-layers",useLocalStorage:t.useLocalStorage??!1}),y=new Uo({store:u});if(h.sample=t.sample,n=C8(n,h),h.Metadata.ConformsTo&&h.Metadata.ConformsTo.includes("https://readium.org/webpub-manifest/profiles/pdf")){let w=await ko.create({store:d,initialUserSettings:t.userSettings,layout:""}),v=await Nr.create({mainElement:i,publication:h,settings:w});return new qo(w,v)}else{n.autoGeneratePositions?await h.autoGeneratePositions(t.requestConfig):(t.services?.positions&&await h.fetchPositionsFromService(t.services?.positions.href,t.requestConfig),t.services?.weight&&await h.fetchWeightsFromService(t.services?.weight.href,t.requestConfig));let w=await Rg.create({store:m}),v=await ko.create({store:d,initialUserSettings:t.userSettings,headerMenu:o,api:t.api,injectables:(h.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed:t.injectables,layout:(h.Metadata.Rendition?.Layout??"unknown")==="fixed"?"fixed":"reflowable"}),g=await _t.create({mainElement:i,headerMenu:o,footerMenu:s,publication:h,settings:v,annotator:y,initialLastReadingPosition:t.lastReadingPosition,api:t.api,rights:n,tts:t.tts,sample:t.sample,requestConfig:t.requestConfig,injectables:(h.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed??[]:t.injectables,attributes:t.attributes,services:t.services}),f=await ht.create(dt({delegate:g,layerSettings:w},t.highlighter)),p=n.enableBookmarks?await Ol.create(dt({annotator:y,headerMenu:o,rights:n,publication:h,delegate:g,initialAnnotations:t.initialAnnotations},t.bookmarks)):void 0,b=n.enableAnnotations?await Tl.create(dt({annotator:y,rights:n,publication:h,delegate:g,initialAnnotations:t.initialAnnotations,highlighter:f,headerMenu:o},t.annotations)):void 0,S=n.enableTTS,C=S?await Cg.create({store:d,initialTTSSettings:t.tts,headerMenu:o}):void 0,x;S&&C&&(x=await Mg.create(dt({delegate:g,tts:C,headerMenu:o,rights:n,highlighter:f},t.tts)));let E=n.enableSearch?await xg.create(dt({headerMenu:o,delegate:g,publication:h,highlighter:f},t.search)):void 0,T=n.enableDefinitions?await kg.create(dt({delegate:g,publication:h,highlighter:f},t.define)):void 0,R=n.enableTimeline?await ig.create({publication:h,delegate:g}):void 0,O=n.enableContentProtection?await lh.create(dt({delegate:g},t.protection)):void 0,L=n.enableCitations?await vh.create(dt({publication:h,delegate:g,highlighter:f},t.citations)):void 0,M=n.enableMediaOverlays,k=M?await eg.create(dt({store:d,initialMediaOverlaySettings:t.mediaOverlays,headerMenu:o},t.mediaOverlays)):void 0,F=M?await tg.create(dt({publication:h,delegate:g,settings:k},t.mediaOverlays)):void 0,G=n.enablePageBreaks&&h.isReflowable?await Pg.create(dt({publication:h,headerMenu:o,delegate:g},t.pagebreak)):void 0,ie=n.enableLineFocus?await yh.create(dt({publication:h,delegate:g,highlighter:f},t.lineFocus)):void 0,ee=n.enableHistory?await Ig.create({annotator:y,publication:h,delegate:g,headerMenu:o}):void 0;return new qo(v,g,f,p,b,C,x,E,T,O,R,k,F,G,ie,ee,L)}}get hasMediaOverlays(){return this.navigator instanceof _t?this.navigator.hasMediaOverlays:!1}get tableOfContents(){return Bl(this.navigator.tableOfContents())??[]}get readingOrder(){return Bl(this.navigator.readingOrder())??[]}get bookmarks(){return this.bookmarkModule?.getBookmarks()??[]}get annotations(){return this.annotationModule?.getAnnotations()}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(t){return t==="pitch"||t==="rate"||t==="volume"}isMOIncrementable(t){return t==="mo_rate"||t==="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(t){if(t.lines&&this.lineFocusModule){let n=this.lineFocusModule.properties.lines??1;this.lineFocusModule.index=this.lineFocusModule.index*n/parseInt(t.lines),this.lineFocusModule.index=Math.abs(parseInt(this.lineFocusModule.index.toFixed())),this.lineFocusModule.properties.lines=parseInt(t.lines),this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus()}t.debug!==void 0&&this.lineFocusModule&&(this.lineFocusModule.isDebug=t.debug,this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus())}lineUp(){this.lineFocusModule?.lineUp()}lineDown(){this.lineFocusModule?.lineDown()}async enableLineFocus(){await this.lineFocusModule?.enableLineFocus()}async lineFocus(t){t?await this.lineFocusModule?.enableLineFocus():this.lineFocusModule?.disableLineFocus()}disableLineFocus(){this.lineFocusModule?.disableLineFocus()}};function C8(r,t){return t.isFixedLayout&&(r.enableAnnotations=!1,r.enableSearch=!1,r.enableTTS=!1,r.enableDefinitions=!1,r.enablePageBreaks=!1,r.enableLineFocus=!1),t.sample?.isSampleRead&&(r.enableAnnotations=!1,r.enableSearch=!1,r.enableTTS=!1,r.enableDefinitions=!1,r.enableTimeline=!1,r.enableMediaOverlays=!1,r.enablePageBreaks=!1,r.enableLineFocus=!1),r}var T8=qo,O8=qo.load;return R8;})();
|
|
89
89
|
/*!
|
|
90
90
|
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
|
|
91
91
|
*
|