@d-i-t-a/reader 2.0.2 → 2.0.3

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
@@ -74,7 +74,7 @@ function print() { __p += __j.call(arguments, '') }
74
74
  </svg>`,A0=(r,t,n,i="icon",o,l)=>`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" height="${o}" viewBox="${T0}" style="fill:${l}" preserveAspectRatio="xMidYMid meet" role="img" class="${i}" aria-labelledBy="${r}">
75
75
  <title id="${r}">${t}</title>
76
76
  ${n}
77
- </svg>`,$i={error:Yn("error-icon","Warning",'<path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>'),home:'<path d="M12 5.69l5 4.5V18h-2v-6H9v6H7v-7.81l5-4.5M12 3L2 12h3v8h6v-6h2v6h6v-8h3L12 3z"/>',expand:Yn("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:gN("loading-icon","Loading",'<path fill="#BBBBBB" d="M145,241.6c-53.3,0-96.6-43.2-96.6-96.6c0-53.3,43.2-96.6,96.6-96.6c53.3,0,96.6,43.2,96.6,96.6 c0,26.7-10.8,50.9-28.3,68.3l7.6,7.6c19.4-19.4,31.5-46.3,31.5-75.9c0-59.3-48-107.3-107.3-107.3S37.7,85.7,37.7,145 c0,59.3,48,107.3,107.3,107.3V241.6z"/>',"0 0 290 290"),next:Yn("next-icon","Next Chapter",'<path d="M6.49 20.13l1.77 1.77 9.9-9.9-9.9-9.9-1.77 1.77L14.62 12l-8.13 8.13z"/>'),previous:Yn("previous-icon","Previous Chapter",'<path d="M17.51 3.87L15.73 2.1 5.84 12l9.9 9.9 1.77-1.77L9.38 12l8.13-8.13z"/>'),settings:Yn("settings-icon","Settings",'<path d="M19.43 12.98c.04-.32.07-.64.07-.98 0-.34-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.09-.16-.26-.25-.44-.25-.06 0-.12.01-.17.03l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.06-.02-.12-.03-.18-.03-.17 0-.34.09-.43.25l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98 0 .33.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.09.16.26.25.44.25.06 0 .12-.01.17-.03l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.06.02.12.03.18.03.17 0 .34-.09.43-.25l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zm-1.98-1.71c.04.31.05.52.05.73 0 .21-.02.43-.05.73l-.14 1.13.89.7 1.08.84-.7 1.21-1.27-.51-1.04-.42-.9.68c-.43.32-.84.56-1.25.73l-1.06.43-.16 1.13-.2 1.35h-1.4l-.19-1.35-.16-1.13-1.06-.43c-.43-.18-.83-.41-1.23-.71l-.91-.7-1.06.43-1.27.51-.7-1.21 1.08-.84.89-.7-.14-1.13c-.03-.31-.05-.54-.05-.74s.02-.43.05-.73l.14-1.13-.89-.7-1.08-.84.7-1.21 1.27.51 1.04.42.9-.68c.43-.32.84-.56 1.25-.73l1.06-.43.16-1.13.2-1.35h1.39l.19 1.35.16 1.13 1.06.43c.43.18.83.41 1.23.71l.91.7 1.06-.43 1.27-.51.7 1.21-1.07.85-.89.7.14 1.13zM12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>',"icon open"),toc:Yn("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:Yn("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:Yn("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:Yn("delete-icon","Delete",'<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>',"icon open"),close:Yn("close-icon","Close",'<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>',"icon open"),text:Yn("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:Yn("speak-icon","Speak",'<circle cx="9" cy="9" r="4"/><path d="M9 15c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4zm7.76-9.64l-1.68 1.69c.84 1.18.84 2.71 0 3.89l1.68 1.69c2.02-2.02 2.02-5.07 0-7.27zM20.07 2l-1.63 1.63c2.77 3.02 2.77 7.56 0 10.74L20.07 16c3.9-3.89 3.91-9.95 0-14z"/><path d="M0 0h24v24H0z" fill="none"/>',"icon open"),note:Yn("note-icon","Note",'<polygon points="17.71 24.66 22.3 20.07 17.71 20.07 17.71 24.66" fill="none"/><path d="M22.42.07H5.58A3.28,3.28,0,0,0,2.29,3.35V24.79a3.28,3.28,0,0,0,3.29,3.28H16.71a1,1,0,0,0,.71-.29l8-8a1,1,0,0,0,.29-.71V3.35A3.28,3.28,0,0,0,22.42.07Zm-8.17,15h-7v-2h7Zm-7-6v-2h13v2ZM16.5,25.86v-6a1,1,0,0,1,1-1h6Z" />',"icon open"),highlight:Yn("highlight-icon","Highlight",'<path d="M27.71,7.78,21.12,1.19a1,1,0,0,0-1.38,0L4.32,15A1,1,0,0,0,4,15.7a1,1,0,0,0,.3.73c1.22,1.22,1.2,2.37,0,3.62a1,1,0,0,0,0,1.41l3.2,3.2a1,1,0,0,0,1.41,0c1.28-1.28,2.36-1.29,3.62,0a1,1,0,0,0,1.45,0L27.74,9.16A1,1,0,0,0,27.71,7.78Z" /><path d="M3.09,22.59l-2.8,2.8a1,1,0,0,0-.21,1.09A1,1,0,0,0,1,27.1H4.6a1,1,0,0,0,.71-.29l1-1Z" />',"icon open")};var M0=At(Cd());var Ue;(function(a){a.R2_ID_HIGHLIGHTS_CONTAINER="R2_ID_HIGHLIGHTS_CONTAINER",a.R2_ID_BOOKMAKRS_CONTAINER="R2_ID_BOOKMAKRS_CONTAINER",a.R2_ID_READALOUD_CONTAINER="R2_ID_READALOUD_CONTAINER",a.R2_ID_PAGEBREAK_CONTAINER="R2_ID_PAGEBREAK_CONTAINER",a.R2_ID_SEARCH_CONTAINER="R2_ID_SEARCH_CONTAINER",a.R2_ID_DEFINITIONS_CONTAINER="R2_ID_DEFINITIONS_CONTAINER",a.R2_ID_LINEFOCUS_CONTAINER="R2_ID_LINEFOCUS_CONTAINER"})(Ue||(Ue={}));var J_="R2_CLASS_HIGHLIGHT_CONTAINER",Za="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",pi="R2_CLASS_HIGHLIGHT_AREA",Qa="R2_CLASS_HIGHLIGHT_ICON",rr=.5,K_=.75,jo={blue:100,green:50,red:230},Yt=[],mN="data-highlighted",vN="data-timestamp",Ws={ELEMENT_NODE:1,TEXT_NODE:3},to=[Ue.R2_ID_HIGHLIGHTS_CONTAINER,Ue.R2_ID_PAGEBREAK_CONTAINER,Ue.R2_ID_SEARCH_CONTAINER,Ue.R2_ID_READALOUD_CONTAINER,Ue.R2_ID_BOOKMAKRS_CONTAINER,Ue.R2_ID_DEFINITIONS_CONTAINER,Ue.R2_ID_LINEFOCUS_CONTAINER,J_,pi,Za],R0=-1,k0=-1,Ge=class{constructor(t,n,i,o,l,s){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,Td.debounce)(()=>{this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen(),this.delegate.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,Td.debounce)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.delegate.emit("toolbox.closed","closed"))},100);this.selection=(0,Td.debounce)((t,n)=>{this.api?.selection&&this.api?.selection(t,n)},100);this.getScrollingElement=t=>t?.scrollingElement?t?.scrollingElement:t?.body?t?.body:document.createElement("body");this.delegate=t,this.layerSettings=n,this.properties=i,this.api=s,this.hasEventListener=o,this.options=this.defaults(l,{color:"#fce300",highlightedClass:"highlighted",contextClass:"highlighter-context",onBeforeHighlight:function(){return!0},onAfterHighlight:function(){}}),this.delegate.highlighter=this}static async create(t){let n=new this(t.delegate,t.layerSettings,t,!1,{},t.api);return new Promise(i=>i(n))}async initialize(){let t=this.delegate.iframes[0].contentDocument;t&&this.dom(t.body).addClass(this.options.contextClass),this.bindEvents(this.delegate.iframes[0].contentDocument?.body,this,this.hasEventListener),this.initializeToolbox(),R0=-1,k0=-1;let n=this;async function i(){n.lastSelectedHighlight===void 0||(n.lastSelectedHighlight=void 0)}setTimeout(async()=>{let o=this.delegate.iframes[0].contentDocument;o&&await o.body?.addEventListener("click",i)},100)}haveSameColor(t,n){return this.dom(t).color()===this.dom(n).color()}defaults(t,n){t=t||{};for(let i in n)n.hasOwnProperty(i)&&t[i]===void 0&&(t[i]=n[i]);return t}unique(t){return t.filter(function(n,i,o){return o.indexOf(n)===i})}refineRangeBoundaries(t){let n=t.startContainer,i=t.endContainer,o=t.commonAncestorContainer,l=!0;if(t.endOffset===0){for(;!i.previousSibling&&i.parentNode!==o;)i=i.parentNode;i=i.previousSibling}else i.nodeType===Ws.TEXT_NODE?t.endOffset<i.nodeValue.length&&i.splitText(t.endOffset):t.endOffset>0&&(i=i.childNodes.item(t.endOffset-1));return n.nodeType===Ws.TEXT_NODE?t.startOffset===n.nodeValue.length?l=!1:t.startOffset>0&&(n=n.splitText(t.startOffset),i===n.previousSibling&&(i=n)):t.startOffset<n.childNodes.length?n=n.childNodes.item(t.startOffset):n=n.nextSibling,{startContainer:n,endContainer:i,goDeeper:l}}sortByDepth(t,n){let i=this;t.sort(function(o,l){return i.dom(n?l:o).parents().length-i.dom(n?o:l).parents().length})}groupHighlights(t){let n=[],i={},o=[];return t.forEach(function(l){let s=l.getAttribute(vN);typeof i[s]=="undefined"&&(i[s]=[],n.push(s)),i[s].push(l)}),n.forEach(function(l){let s=i[l];o.push({chunks:s,timestamp:l,toString:function(){return s.map(function(a){return a.textContent}).join("")}})}),o}dom(t){let n=this;return{addClass:function(i){t.classList?t.classList.add(i):t.className+=" "+i},removeClass:function(i){t.classList?t.classList.remove(i):t.className=t.className.replace(new RegExp("(^|\\b)"+i+"(\\b|$)","gi")," ")},prepend:function(i){let o=Array.prototype.slice.call(i),l=o.length;for(;l--;)t.insertBefore(o[l],t.firstChild)},append:function(i){let o=Array.prototype.slice.call(i);for(let l=0,s=o.length;l<s;++l)t.appendChild(o[l])},insertAfter:function(i){return i.parentNode?.insertBefore(t,i.nextSibling)},insertBefore:function(i){return i.parentNode?.insertBefore(t,i)},remove:function(){t.parentNode.removeChild(t),t=null},contains:function(i){return t!==i&&t.contains(i)},wrap:function(i){return t.parentNode&&t.parentNode.insertBefore(i,t),i.appendChild(t),i},unwrap:function(){let i=Array.prototype.slice.call(t.childNodes),o;return i.forEach(function(l){o=l.parentNode,n.dom(l).insertBefore(l.parentNode),n.dom(o).remove()}),i},parents:function(){let i,o=[];for(;i=t.parentNode;)o.push(i),t=i;return o},normalizeTextNodes:function(){if(!!t){if(t.nodeType===Ws.TEXT_NODE)for(;t.nextSibling&&t.nextSibling.nodeType===Ws.TEXT_NODE;)t.nodeValue+=t.nextSibling.nodeValue,t.parentNode.removeChild(t.nextSibling);else n.dom(t.firstChild).normalizeTextNodes();n.dom(t.nextSibling).normalizeTextNodes()}},color:function(){return t.style.backgroundColor},fromHTML:function(i){let o=document.createElement("div");return o.innerHTML=i,o.childNodes},getRange:function(){let i=n.dom(t)?.getSelection(),o;return i?.rangeCount>0&&(o=i?.getRangeAt(0)),o},removeAllRanges:function(){n.dom(t)?.getSelection()?.removeAllRanges(),n.toolboxHide()},getSelection:function(){return n.dom(t).getWindow()?.getSelection()},getWindow:function(){return n.dom(t).getDocument()?.defaultView},getDocument:function(){return t?.ownerDocument||t}}}disableContext(t){return t.preventDefault(),t.stopPropagation(),!1}bindEvents(t,n,i){let o=t.ownerDocument;o.addEventListener("keyup",this.toolboxShowDelayed.bind(this)),t.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),o.addEventListener("selectstart",this.toolboxShowDelayed.bind(this)),i||window.addEventListener("resize",this.toolboxPlacement.bind(this)),o.addEventListener("selectionchange",this.toolboxPlacement.bind(this)),t.addEventListener("mousedown",this.toolboxHide.bind(this)),t.addEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&t.addEventListener("contextmenu",this.disableContext),t.addEventListener("mousedown",this.mousedown.bind(this)),t.addEventListener("mouseup",this.mouseup.bind(this)),t.addEventListener("mousemove",this.mousemove.bind(this)),t.addEventListener("touchstart",this.mousedown.bind(this)),t.addEventListener("touchend",this.mouseup.bind(this)),t.addEventListener("touchmove",this.mousemove.bind(this)),this.hasEventListener=!0}async mousedown(t){R0=t.clientX,k0=t.clientY}async mouseup(t){Math.abs(R0-t.clientX)<3&&Math.abs(k0-t.clientY)<3&&await this.processMouseEvent(t)}async mousemove(t){await this.processMouseEvent(t)}unbindEvents(t,n){let i=t.ownerDocument;i.removeEventListener("keyup",this.toolboxShowDelayed.bind(this)),t.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),i.removeEventListener("selectstart",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),i.removeEventListener("selectionchange",this.toolboxPlacement.bind(this)),t.removeEventListener("mousedown",this.toolboxHide.bind(this)),t.removeEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&t.removeEventListener("contextmenu",this.disableContext),t.removeEventListener("mousedown",this.mousedown.bind(this)),t.removeEventListener("mouseup",this.mouseup.bind(this)),t.removeEventListener("mousemove",this.mousemove.bind(this)),t.removeEventListener("touchstart",this.mousedown.bind(this)),t.removeEventListener("touchend",this.mouseup.bind(this)),t.removeEventListener("touchmove",this.mousemove.bind(this)),this.hasEventListener=!1}destroy(){this.toolboxHide();let t=this.delegate.iframes[0].contentDocument;t&&(this.unbindEvents(t.body,this),this.dom(t.body).removeClass(this.options.contextClass))}initializeToolbox(){let t=document.getElementById("highlight-toolbox-mode-colors"),n=document.getElementById("highlight-toolbox-mode-add"),i=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],o=document.getElementById("colorIcon"),l=document.getElementById("actionIcon"),s=document.getElementById("dismissIcon"),a=document.getElementById("collapseIcon"),u=document.getElementById("highlightIcon"),h=this;if(s&&(s.innerHTML=$i.close,s.addEventListener("click",function(){h.toolboxMode("add")})),a&&(a.innerHTML=$i.close,a.addEventListener("click",function(){h.toolboxMode("add")})),o){o.style.position="relative",o.style.zIndex="20",i.forEach(g=>{let y=document.getElementById(g),E=document.getElementById(`c${g}`);y&&t?.contains(y)&&t.removeChild(y),n&&E&&n.contains(E)&&n.removeChild(E)});let f=[],p=[];if(o.addEventListener("click",function(){h.toolboxMode("colors")}),this.delegate.rights.enableAnnotations){let g=10;i.forEach(y=>{g--;let E=o?.cloneNode(!0),b=E.lastChild,w=Ge.hexToRgbChannels(y);b.style.backgroundColor="rgba("+[w.red,w.green,w.blue].join(",")+",.5)",E.id=`c${y}`,E.style.display="unset",E.style.position="relative",E.style.zIndex=`${g}`,E.style.marginLeft="-30px",p.push(E),n?.insertBefore(E,u)})}i.forEach(g=>{let y=o?.cloneNode(!0),E=y.lastChild;E.style.backgroundColor=g,y.id=g,y.style.position="relative",y.style.display="unset",f.push(y);let b=document.getElementById("highlightIcon"),w=document.getElementById("underlineIcon");o&&y.addEventListener("click",function(){h.setColor(g);let _=o?.lastChild;_&&(_.style.backgroundColor=g),(b?.getElementsByTagName?.("span").length??0)>0&&((b?.getElementsByTagName("span")[0]).style.background=h.getColor()),(w?.getElementsByTagName?.("span").length??0)>0&&((w?.getElementsByTagName("span")[0]).style.borderBottomColor=h.getColor()),h.toolboxMode("add")}),t?.insertBefore(y,s)})}l&&l.addEventListener("click",function(){h.toolboxMode("action")}),h.toolboxMode("add")}toolboxMode(t){let n=document.getElementById("highlight-toolbox-mode-colors"),i=document.getElementById("highlight-toolbox-mode-add"),o=document.getElementById("highlight-toolbox-mode-edit"),l=document.getElementById("highlight-toolbox-mode-action");switch(t){case"colors":n&&(n.style.display="unset"),i&&(i.style.display="none"),o&&(o.style.display="none"),l&&(l.style.display="none");break;case"edit":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="unset"),l&&(l.style.display="none");break;case"action":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),l&&(l.style.display="unset");break;default:n&&(n.style.display="none"),i&&(i.style.display="unset"),o&&(o.style.display="none"),l&&(l.style.display="none");break}}toolboxHide(){let t=document.getElementById("highlight-toolbox");t&&(t.style.display="none"),this.selectionMenuClosed()}toolboxShowDelayed(){let t=this;setTimeout(function(){t.isAndroid()||t.snapSelectionToWord(),t.toolboxShow()},100)}snapSelectionToWord(){let t=this,n=this.delegate.iframes[0].contentDocument;if(n){let i=t.dom(n.body)?.getWindow()?.getSelection();if(t.dom(n.body)&&i&&!i?.isCollapsed){let o=document.createRange();o.setStart(i.anchorNode,i.anchorOffset),o.setEnd(i.focusNode,i.focusOffset);let l=o.collapsed;o.detach();let s=i.focusNode,a=i.focusOffset;i.collapse(i.anchorNode,i.anchorOffset);let u=["forward","backward"];l&&(u=["backward","forward"]),i.modify("move",u[0],"character"),i.modify("move",u[1],"word"),i.extend(s,a),i.modify("extend",u[1],"character"),i.modify("extend",u[0],"word"),this.selection(i.toString(),i)}return i}}toolboxShow(){if(this.activeAnnotationMarkerId===void 0){let t=this,n=document.getElementById("highlight-toolbox-mode-add"),i=this.dom(this.delegate.iframes[0].contentDocument?.body).getRange();if((!i||i.collapsed)&&n){getComputedStyle(n).display!=="none"&&t.toolboxHide();return}this.isIOS()&&(this.delegate.iframes[0].contentDocument?.body.removeEventListener("selectionchange",this.toolboxPlacement.bind(this)),setTimeout(function(){let o=t.delegate.iframes[0].contentDocument;if(o){let l=t.dom(o.body).getSelection();l.removeAllRanges(),setTimeout(function(){l.addRange(i)},5)}},100)),this.toolboxPlacement(),this.toolboxHandler()}}toolboxPlacement(){let t=this.dom(this.delegate.iframes[0].contentDocument?.body).getRange();if(!t||t.collapsed)return;let n=t.getBoundingClientRect(),i=document.getElementById("highlight-toolbox");i&&(this.delegate.view?.isPaginated()?i.style.top=n.top+(this.delegate.attributes?.navHeight??0)+"px":i.style.top=n.top+"px",i.style.left=(n.right-n.left)/2+n.left+"px")}toolboxHandler(){let t=document.getElementById("highlight-toolbox");if(t&&getComputedStyle(t).display==="none"){t.style.display="block",this.delegate.view?.isPaginated()?t.style.position="absolute":t.style.position="relative",this.selectionMenuOpened();let i=this;i.toolboxMode("add");let o=document.getElementById("highlightIcon"),l=document.getElementById("collapseIcon"),s=document.getElementById("underlineIcon"),a=document.getElementById("colorIcon"),u=document.getElementById("speakIcon");if(this.delegate.rights.enableAnnotations){if(o&&(o.style.display="unset",a&&o.getElementsByTagName("span").length>0&&(o.getElementsByTagName("span")[0].style.background=this.getColor())),s&&(s.style.display="unset",a&&s.getElementsByTagName("span").length>0&&(s.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),a){a.style.display="unset";let h=a.lastChild;h.style.backgroundColor=this.getColor()}if(o){let h=function(){i.doHighlight(!1,ot.Highlight),i.toolboxHide(),o?.removeEventListener("click",h)};o.addEventListener("click",h)}if(s){let h=function(){i.doHighlight(!1,ot.Underline),i.toolboxHide(),s?.removeEventListener("click",h)};s.addEventListener("click",h)}}else o&&o.style.setProperty("display","none"),s&&s.style.setProperty("display","none"),a&&a.style.setProperty("display","none"),l&&l.style.setProperty("display","none");if(this.delegate.rights.enableTTS){if(u){let h=function(){u?.removeEventListener("click",h),i.speak()};u.addEventListener("click",h)}}else u&&u.style.setProperty("display","none");(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).forEach(h=>{h.icon&&(h.icon.id=h.id);let f=document.getElementById(h.id),p=this;function g(){f?.removeEventListener("click",g);function y(b){let w={className:S=>to.indexOf(S)<0,idName:S=>to.indexOf(S)<0},_=p.delegate.iframes[0].contentDocument;if(_)return Dn(b,_,w)}let E=p.delegate.iframes[0].contentWindow;if(E){let b=Qr(E,y);if(b!==void 0)if(h.callback)h.callback(b.cleanText,b.range?.startContainer.parentElement);else{let w=h.highlight?.style,_=h.marker?h.marker:ot.Custom;if(_===ot.Custom&&p.delegate.rights.enableAnnotations||_===ot.Bookmark&&p.delegate.rights.enableBookmarks){let S=p.delegate.iframes[0].contentDocument;if(S){let x=p.createHighlight(p.dom(S.body).getWindow(),b,h.highlight?.color,!0,_,h.icon,h.popup,w);p.options.onAfterHighlight(x,_),p.delegate.rights.enableAnnotations?p.delegate.annotationModule?.saveAnnotation(x[0]).then(R=>{h?.note&&(R.highlight&&(R.highlight.note=prompt("Add your note here:")),p.delegate.annotationModule?.updateAnnotation(R).then(async()=>{K&&console.log("update highlight "+R.id)}))}):p.delegate.rights.enableBookmarks&&p.delegate.bookmarkModule?.saveAnnotation(x[0])}}}}p.callbackComplete()}f&&f.addEventListener("click",g)})}}doHighlight(t,n){let i=this;function o(s){let a={className:h=>to.indexOf(h)<0,idName:h=>to.indexOf(h)<0},u=i.delegate.iframes[0].contentDocument;if(u)return Dn(s,u,a)}let l=i.delegate.iframes[0].contentWindow;if(l){let s=Qr(l,o);if(s){if(this.options.onBeforeHighlight(s)===!0){let a;a=this.getColor(),Ge.isHexColor(a)&&(a=Ge.hexToRgbChannels(a));let u=i.delegate.iframes[0].contentDocument;if(u){let h=this.createHighlight(i.dom(u.body).getWindow(),s,a,!0,n??ot.Highlight);this.options.onAfterHighlight(h,n),this.delegate.rights.enableAnnotations&&n!==ot.Bookmark?this.delegate.annotationModule?.saveAnnotation(h[0]):this.delegate.rights.enableBookmarks&&n===ot.Bookmark&&this.delegate.bookmarkModule?.saveAnnotation(h[0])}}t||this.dom(this.delegate.iframes[0].contentDocument?.body).removeAllRanges()}else t||this.dom(this.delegate.iframes[0].contentDocument?.body).removeAllRanges()}}speak(){if(this.delegate.rights.enableTTS){let n=function(s){let a={className:h=>to.indexOf(h)<0,idName:h=>to.indexOf(h)<0},u=t.delegate.iframes[0].contentDocument;if(u)return Dn(s,u,a)},t=this,i=t.delegate.iframes[0].contentWindow;if(i){let s=Qr(i,n);s!==void 0&&(this.delegate.tts?.enableSplitter?this.delegate.ttsModule.speak(s,!0,()=>{}):this.delegate.ttsModule.speak(s,!0,()=>{}))}let o=t.delegate.iframes[0].contentDocument;o&&t.dom(o.body).getSelection().removeAllRanges();let l=document.getElementById("highlight-toolbox");l&&(l.style.display="none"),this.selectionMenuClosed()}}stopReadAloud(){this.delegate.rights.enableTTS&&this.doneSpeaking()}speakAll(){if(this.delegate.rights.enableTTS){let i=function(l){let s={className:u=>to.indexOf(u)<0,idName:u=>to.indexOf(u)<0},a=n.delegate.iframes[0].contentDocument;if(a)return Dn(l,n.dom(a.body).getDocument(),s)},n=this,o=this.delegate.iframes[0].contentDocument;if(o)if(Qr(this.dom(o.body).getWindow(),i)!==void 0)n.speak();else{var t=this.dom(n.delegate.iframes[0].contentDocument?.body).getWindow().document.body;K&&console.log(o);let s=n.dom(o.body).getSelection(),a=this.dom(o.body).getWindow().document.createRange();a.selectNodeContents(t),s.removeAllRanges(),s.addRange(a);let u=this.delegate.iframes[0].contentWindow;if(u){let h=Qr(u,i);h!==void 0&&h.cleanText?this.delegate.tts?.enableSplitter?this.delegate.ttsModule.speak(h,!1,()=>{o&&n.dom(o.body).getSelection().removeAllRanges(),n.toolboxHide()}):this.delegate.ttsModule.speak(h,!1,()=>{o&&n.dom(o.body).getSelection().removeAllRanges(),n.toolboxHide()}):(n.dom(o.body).getSelection().removeAllRanges(),n.toolboxHide())}}}}callbackComplete(){this.toolboxHide();let t=this.delegate.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges()}isOutsideViewport(t){let n=St(document,"#iframe-wrapper"),i=n.scrollLeft,o=i+n.clientHeight,l=t.left+t.width,s=t.top+t.height,a=n.scrollTop,u=a+n.clientHeight,h=s<a,f=t.top>u,p=l<i,g=t.left>o;return h||f||p||g}get visibleTextRects(){let t=this.delegate.iframes[0].contentDocument;if(t){let i=function(a,u=[]){let h=a.firstChild;for(;h;)h.nodeType===1&&i(h,u),h.nodeType===3&&h.textContent?.trim()&&u.push(h),h=h.nextSibling;return u},o=function(a){return i(a).map(h=>{let{top:f,height:p,left:g,width:y}=l(h);return{top:f,height:p,width:y,left:g,node:h,textContent:h.textContent??""}})},l=function(a){try{let u=document.createRange();u.selectNode(a);let h=u.getBoundingClientRect();return u.detach(),h}catch(u){K&&(console.log("measureTextNode "+u),console.log("measureTextNode "+a),console.log(a.textContent))}},n=Sr(t,"body");return o(n).filter(a=>!this.isOutsideViewport(a))}return[]}doneSpeaking(t=!1){if(this.delegate.rights.enableTTS){this.toolboxHide();let n=this.delegate.iframes[0].contentDocument;n&&this.dom(n.body).removeAllRanges(),this.delegate.tts?.enableSplitter?this.delegate.ttsModule.cancel():this.delegate.ttsModule.cancel(),t&&this.delegate.reload()}}normalizeHighlights(t){var n;return n=t.filter(function(i){return i.parentElement?i:null}),n=this.unique(n),n.sort(function(i,o){return i.offsetTop-o.offsetTop||i.offsetLeft-o.offsetLeft}),n}flattenNestedHighlights(t){let n,i=this;i.sortByDepth(t,!0);function o(){let l=!1;return t.forEach(function(s,a){let u=s.parentElement,h=u.previousSibling,f=u.nextSibling;i.isHighlight(u)&&(i.haveSameColor(u,s)?(u.replaceChild(s.firstChild,s),t[a]=u,l=!0):(s.nextSibling||(i.dom(s).insertBefore(f||u),l=!0),s.previousSibling||(i.dom(s).insertAfter(h||u),l=!0),u.hasChildNodes()||i.dom(u).remove()))}),l}do n=o();while(n)}mergeSiblingHighlights(t){let n=this;function i(o,l){return l&&l.nodeType===Ws.ELEMENT_NODE&&n.haveSameColor(o,l)&&n.isHighlight(l)}t.forEach(function(o){let l=o.previousSibling,s=o.nextSibling;i(o,l)&&(n.dom(o).prepend(l.childNodes),n.dom(l).remove()),i(o,s)&&(n.dom(o).append(s.childNodes),n.dom(s).remove()),n.dom(o).normalizeTextNodes()})}setColor(t){this.options.color=t}getColor(){return this.options.color}isHighlight(t){return t&&t.nodeType===Ws.ELEMENT_NODE&&t.hasAttribute(mN)}createWrapper(){let t=document.createElement("mark");return t.style.background="linear-gradient("+Ge.hexToRgbA(this.options.color)+", "+Ge.hexToRgbA(this.options.color)+")",t.className=this.options.highlightedClass,t}static isHexColor(t){return/^#([A-Fa-f0-9]{3}){1,2}$/.test(t)}static hexToRgbString(t){let n;return n=t.substring(1).split(""),n.length===3&&(n=[n[0],n[0],n[1],n[1],n[2],n[2]]),n="0x"+n.join(""),n}static hexToRgbChannels(t){let n;if(this.isHexColor(t))return n=this.hexToRgbString(t),{red:n>>16&255,green:n>>8&255,blue:n&255};throw new Error("Bad Hex")}static hexToRgbA(t){let n;if(this.isHexColor(t))return n=this.hexToRgbChannels(t),"rgba("+[n.red,n.green,n.blue].join(",")+",.5)";if(typeof t=="object"){let i=t;return"rgba("+[i.red,i.green,i.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(t,n){let i;if(this.isHexColor(t))return i=this.hexToRgbChannels(t),"rgba("+[i.red,i.green,i.blue].join(",")+","+n+")";if(typeof t=="object"){let o=t;return"rgba("+[o.red,o.green,o.blue].join(",")+","+n+")"}throw new Error("Bad Hex")}resetHighlightBoundingStyle(t){t.style.outline="none",t.style.setProperty("background-color","transparent","important")}resetHighlightAreaStyle(t,n){let i=this.delegate.iframes[0].contentWindow?.document,o=t.parentNode&&t.parentNode.nodeType===Node.ELEMENT_NODE&&t.parentNode.getAttribute?t.parentNode.getAttribute("id"):void 0;if(o){let l=Yt.find(s=>s.id===o);if(l){if(l.marker===ot.Custom||l.marker===ot.Bookmark)if(l.style?.hover){if(l.style?.hover)for(let u=0;u<l.style?.hover?.length;u++){let h=l.style?.hover[u];t.style.removeProperty(h.property)}let a="";if(l.style?.default)for(let u=0;u<l.style?.default?.length;u++){let h=l.style?.default[u];t.style.removeProperty(h.property),a+=`${h.property}: ${h.value} !${h.priority};`}t.setAttribute("style",`${t.getAttribute("style")}; ${a}`)}else if(l.style?.hoverClass){l.style?.hoverClass&&t.classList.remove(l.style?.hoverClass);let a="";l.style?.defaultClass&&t.classList.add(l.style?.defaultClass),t.setAttribute("style",`${t.getAttribute("style")}; ${a}`)}else if(Ge.isHexColor(l.color)){let a=Ge.hexToRgbChannels(l.color);t.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${0})`,"important")}else t.classList.remove("hover");else if(l.marker===ot.Underline)if(typeof l.color=="object"){let a=l.color;t.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, ${1})`,"important")}else if(Ge.isHexColor(l.color)){let a=Ge.hexToRgbChannels(l.color);t.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, ${1})`,"important")}else t.classList.remove("hover");else if(typeof l.color=="object"){let a=l.color;t.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${rr})`,"important")}else if(Ge.isHexColor(l.color)){let a=Ge.hexToRgbChannels(l.color);t.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${rr})`,"important")}else t.classList.remove("hover");let s;if(i){let a=i.getElementById(n);a&&(s=a.querySelector(`#${l.id}`))}if(s){let a=s.getElementsByClassName(Qa);if(a.length>0){let u=a.item(0).getElementsByClassName("icon-tooltip");u.length>0&&u.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(t,n,i){for(let o of n){if(i.marker===ot.Custom||i.marker===ot.Bookmark)if(i.style?.hover){if(i.style?.default)for(let s=0;s<i.style?.default?.length;s++){let a=i.style?.default[s];o.style.removeProperty(a.property)}let l="";for(let s=0;s<i.style?.hover?.length;s++){let a=i.style?.hover[s];o.style.removeProperty(a.property),l+=`${a.property}: ${a.value} !${a.priority};`}o.setAttribute("style",`${o.getAttribute("style")}; ${l}`)}else if(i.style?.hoverClass){i.style?.defaultClass&&o.classList.remove(i.style?.defaultClass);let l="";o.classList.add(i.style?.hoverClass),o.setAttribute("style",`${o.getAttribute("style")}; ${l}`)}else if(Ge.isHexColor(i.color)){let l=Ge.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${l.red}, ${l.green}, ${l.blue}, ${.1})`,"important")}else o.classList.add("hover");else if(i.marker===ot.Underline)if(typeof i.color=="object"){let l=i.color;o.style.setProperty("background-color",`rgba(${l.red}, ${l.green}, ${l.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${l.red}, ${l.green}, ${l.blue}, ${1})`,"important")}else if(Ge.isHexColor(i.color)){let l=Ge.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${l.red}, ${l.green}, ${l.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${l.red}, ${l.green}, ${l.blue}, ${1})`,"important")}else o.classList.add("hover");else if(typeof i.color=="object"){let l=i.color;o.style.setProperty("background-color",`rgba(${l.red}, ${l.green}, ${l.blue}, ${K_})`,"important")}else if(Ge.isHexColor(i.color)){let l=Ge.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${l.red}, ${l.green}, ${l.blue}, ${K_})`,"important")}else o.classList.add("hover");if(i.type!==nt.Definition){let s=t.getElementById(Ue.R2_ID_HIGHLIGHTS_CONTAINER).querySelector(`#${i.id}`).getElementsByClassName(Qa);if(s.length>0){let a=s.item(0).getElementsByClassName("icon-tooltip");a.length>0&&a.item(0).style.setProperty("display","block")}}}}setAndResetSearchHighlight(t,n){let i=this.delegate.iframes[0].contentWindow?.document,o=Array.from(i.getElementById(Ue.R2_ID_SEARCH_CONTAINER).querySelectorAll(`.${pi}`));for(let l of o){let s=l,a=s.parentNode&&s.parentNode.nodeType===Node.ELEMENT_NODE&&s.parentNode.getAttribute?s.parentNode.getAttribute("id"):void 0;if(n.forEach(u=>{if(a===u.id&&u){if(typeof u.color=="object"){let p=u.color;s.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${rr})`,"important")}else if(Ge.isHexColor(u.color)){let p=Ge.hexToRgbChannels(u.color);s.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${rr})`,"important")}else s.classList.remove("hover");let f=i.getElementById(Ue.R2_ID_SEARCH_CONTAINER).querySelector(`#${u.id}`).getElementsByClassName(Qa);if(f.length>0){let p=f.item(0).getElementsByClassName("icon-tooltip");p.length>0&&p.item(0).style.removeProperty("display")}}}),a===t.id&&t){if(typeof t.color=="object"){let f=t.color;s.style.setProperty("background-color",`rgba(${f.red}, ${f.green}, ${f.blue}, ${rr})`,"important")}else if(Ge.isHexColor(t.color)){let f=Ge.hexToRgbChannels(t.color);s.style.setProperty("background-color",`rgba(${f.red}, ${f.green}, ${f.blue}, ${rr})`,"important")}else s.classList.remove("hover");let h=i.getElementById(Ue.R2_ID_SEARCH_CONTAINER).querySelector(`#${t.id}`).getElementsByClassName(Qa);if(h.length>0){let f=h.item(0).getElementsByClassName("icon-tooltip");f.length>0&&f.item(0).style.removeProperty("display")}}}}isIOS(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}isAndroid(){return navigator.userAgent.match(/Android/i)!=null}async processMouseEvent(t){let n=this.delegate.iframes[0].contentWindow?.document,i=t.clientX,o=t.clientY;if(!n||!n.getElementById(Ue.R2_ID_HIGHLIGHTS_CONTAINER)&&!n.getElementById(Ue.R2_ID_SEARCH_CONTAINER)&&!n.getElementById(Ue.R2_ID_PAGEBREAK_CONTAINER)&&!n.getElementById(Ue.R2_ID_READALOUD_CONTAINER)&&!n.getElementById(Ue.R2_ID_DEFINITIONS_CONTAINER))return;let l=this.delegate.view?.isPaginated(),s=n.body.getBoundingClientRect(),a=this.getScrollingElement(n),u=l?-a.scrollLeft:s.left,h=l?-a.scrollTop:s.top,f,p;for(let g=Yt.length-1;g>=0;g--){let y=Yt[g],E=n.getElementById(`${y.id}`);if(!E){let _=n.getElementById(Ue.R2_ID_HIGHLIGHTS_CONTAINER);_&&(E=_.querySelector(`#${y.id}`))}if(!E)continue;let b=!1,w=E.querySelectorAll(`.${pi}`);for(let _ of w){let S=_,x=S.rect.left+u,R=S.rect.top+h;if(i>=x&&i<x+S.rect.width&&o>=R&&o<R+S.rect.height){b=!0;break}}if(b){f=y,p=E;break}}if(!f||!p){for(let g in Ue){let y=n.getElementById(g);if(y){let E=y.querySelectorAll(`.${Za}`);for(let w of E)this.resetHighlightBoundingStyle(w);let b=Array.from(y.querySelectorAll(`.${pi}`));for(let w of b)this.resetHighlightAreaStyle(w,g)}}return}if(p.getAttribute("data-click")){if((t.type==="mousemove"||t.type==="touchmove")&&p.parentElement?.style.display!=="none"){let g=Array.from(p.querySelectorAll(`.${pi}`));for(let E in Ue){let b=n.getElementById(E);if(b){let w=b.querySelectorAll(`.${pi}`);for(let _ of w)g.indexOf(_)<0&&this.resetHighlightAreaStyle(_,E)}}this.setHighlightAreaStyle(n,g,f);let y=p.querySelector(`.${Za}`);for(let E in Ue){let b=n.getElementById(E);if(b){let w=b.querySelectorAll(`.${Za}`);for(let _ of w)(!y||_!==y)&&this.resetHighlightBoundingStyle(_)}}}else if((t.type==="mouseup"||t.type==="click"||t.type==="touchup")&&p.parentElement?.style.display!=="none"){let g={highlight:f};K&&console.log(g);let y=this,E;if(y.delegate.rights.enableAnnotations?E=await this.delegate.annotationModule?.getAnnotation(g.highlight):y.delegate.rights.enableBookmarks&&(E=await this.delegate.bookmarkModule?.getAnnotation(g.highlight)),g.highlight.type===nt.Annotation&&this.delegate.annotationModule?.api?.selectedAnnotation(E).then(async()=>{}),E?.id){K&&console.log("selected highlight "+E.id),y.lastSelectedHighlight=E.id;let b=document.getElementById("highlight-toolbox");if(b)if(b.style.top=t.clientY+(this.delegate.attributes?.navHeight??0)+"px",b.style.left=t.clientX+"px",getComputedStyle(b).display==="none"){let S=function(){E.highlight.note=prompt("Add your note here:"),y.delegate.annotationModule?.updateAnnotation(E).then(async()=>{K&&console.log("update highlight "+E.id),b&&(b.style.display="none"),y.selectionMenuClosed()}),b&&(b.style.display="none"),y.selectionMenuClosed(),x?.removeEventListener("click",S,!1)},C=function(){y.delegate.rights.enableAnnotations?y.delegate.annotationModule?.deleteSelectedHighlight(E).then(async()=>{K&&console.log("delete highlight "+E.id),b&&(b.style.display="none"),y.selectionMenuClosed()}):y.delegate.rights.enableBookmarks&&y.delegate.bookmarkModule?.deleteSelectedHighlight(E).then(async()=>{K&&console.log("delete highlight "+E.id),b&&(b.style.display="none"),y.selectionMenuClosed()})};b.style.display="block",this.toolboxMode("edit");let w=document.getElementById("colorIcon"),_=document.getElementById("highlightIcon");w&&(w.style.display="none"),_&&(_.style.display="none");let x=document.getElementById("commentIcon"),R=document.getElementById("cloneCommentIcon");if(R){let N=R.parentElement;N&&N.removeChild(R)}if(x){x.style.display="none";let N=x.cloneNode(!0),J=x.parentElement;N.style.display="unset",N.id="cloneCommentIcon",N.addEventListener("click",S,!1),J&&J.append(N)}let I=document.getElementById("deleteIcon"),z=document.getElementById("cloneDeleteIcon");if(z){let N=z.parentElement;N&&N.removeChild(z)}if(I){I.style.display="none";let N=I.cloneNode(!0),J=I.parentElement;N.style.display="unset",N.id="cloneDeleteIcon",N.addEventListener("click",C,!1),J&&J.append(N)}}else b.style.display="none",this.selectionMenuClosed(),b.offsetWidth,b.style.display="block"}else{p.dataset.definition&&new Ya(this.delegate).showPopup(p.dataset.definition,t);let b=this.delegate.definitionsModule?.properties?.definitions?.filter(w=>w.order===Number(p?.dataset.order))[0];console.log(b),this.delegate.definitionsModule?.api?.click&&(this.delegate.definitionsModule.api?.click(M0.omit(b,"callbacks"),M0.omit(f,"definition")),this.delegate.emit("definition.click",b,f))}}}}async prepareContainers(t){for(let n in Ue)await this.ensureHighlightsContainer(t,n)}async ensureHighlightsContainer(t,n){let i=t.document;if(!i.getElementById(n)){let o=i.createElement("div");o.setAttribute("id",n),o.style.setProperty("pointer-events","none"),this.delegate.view?.layout==="fixed"&&(o.style.setProperty("position","absolute"),o.style.setProperty("top","0"),o.style.setProperty("left","0")),i.body&&i.body.append(o),(await this.layerSettings.getProperty(n))?.value===!1&&(o.style.display="none")}return i.getElementById(n)}hideAllhighlights(t){this.removeAllChildNodes(t.getElementById(Ue.R2_ID_HIGHLIGHTS_CONTAINER)),this.removeAllChildNodes(t.getElementById(Ue.R2_ID_SEARCH_CONTAINER)),this.removeAllChildNodes(t.getElementById(Ue.R2_ID_READALOUD_CONTAINER)),this.removeAllChildNodes(t.getElementById(Ue.R2_ID_PAGEBREAK_CONTAINER)),this.removeAllChildNodes(t.getElementById(Ue.R2_ID_DEFINITIONS_CONTAINER))}destroyAllhighlights(t){this.hideAllhighlights(t),Yt.splice(0,Yt.length)}removeAllChildNodes(t){for(;t.firstChild;)t.removeChild(t.firstChild)}destroyHighlights(t){let n=this.delegate.iframes[0].contentWindow?.document;if(n){let i;switch(t){case nt.ReadAloud:i=n.getElementById(Ue.R2_ID_READALOUD_CONTAINER),i&&this.removeAllChildNodes(i);break;case nt.Search:i=n.getElementById(Ue.R2_ID_SEARCH_CONTAINER),i&&this.removeAllChildNodes(i);break;case nt.PageBreak:i=n.getElementById(Ue.R2_ID_PAGEBREAK_CONTAINER),i&&this.removeAllChildNodes(i);break;case nt.Definition:i=n.getElementById(Ue.R2_ID_DEFINITIONS_CONTAINER),i&&this.removeAllChildNodes(i);break;case nt.LineFocus:i=n.getElementById(Ue.R2_ID_LINEFOCUS_CONTAINER),i&&this.removeAllChildNodes(i);break;default:i=n.getElementById(Ue.R2_ID_HIGHLIGHTS_CONTAINER),i&&this.removeAllChildNodes(i),Yt.splice(0,Yt.length);break}}}destroyHighlight(t,n){if(!t)return;let i=-1;Yt.find((s,a)=>(i=a,s.id===n))&&i>=0&&i<Yt.length&&Yt.splice(i,1);let l=t.getElementById(n);l&&this.removeAllChildNodes(l)}createHighlight(t,n,i,o,l,s,a,u,h,f){try{let p=`${n.rangeInfo.startContainerElementCssSelector}${n.rangeInfo.startContainerChildTextNodeIndex}${n.rangeInfo.startOffset}${n.rangeInfo.endContainerElementCssSelector}${n.rangeInfo.endContainerChildTextNodeIndex}${n.rangeInfo.endOffset}`,g=Ai.hash(p),y=(f||"R2_HIGHLIGHT_")+g;this.destroyHighlight(t.document,y);let E=`rgb(${jo.red}, ${jo.green}, ${jo.blue})`,b={color:i||E,id:y,pointerInteraction:o,selectionInfo:n,marker:l,icon:s,popup:a,style:u,type:h||nt.Annotation};(h===nt.Annotation||h===nt.Definition||h===void 0)&&Yt.push(b);let w=this.createHighlightDom(t,b);return b.position=parseInt((w?.hasChildNodes()?w.childNodes[0]:w).style.top.replace("px","")),[b,w]}catch(p){throw"Can't create highlight: "+p}}createHighlightDom(t,n){let i=t.document,o=N_(i,n.selectionInfo.rangeInfo);if(!o)return;for(let D in Ue)this.ensureHighlightsContainer(t,D);let l=i.createElement("div");l.setAttribute("id",n.id),l.setAttribute("class",J_),l.style.setProperty("pointer-events","none"),n.pointerInteraction&&l.setAttribute("data-click","1");let s=this.delegate.view?.isPaginated();s?i.body.style.position="revert":i.body.style.position="relative";let a=i.body.getBoundingClientRect(),u=this.getScrollingElement(i),h=s?-u.scrollLeft:a.left,f=s?-u.scrollTop:a.top,p=1,g=!1,y=!1,w=_d(o,g||y||!1),_=3,S=2,x=3,R=0,C=24,I,z;for(let D of w){let U=i.createElement("div");U.setAttribute("class",pi),U.dataset.marker=""+n.marker;let Y="";if(g&&n.marker!==ot.Custom&&n.marker!==ot.Bookmark){let ee=n.color;Ge.isHexColor(ee)&&(ee=Ge.hexToRgbChannels(ee)),Y+=`border-bottom: ${S*p}px solid rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${rr}) !important`}if(n.marker===ot.Custom||n.marker===ot.Bookmark)if(n.style?.default){for(let ee=0;ee<n.style?.default?.length;ee++){let de=n.style?.default[ee];Y+=`${de.property}: ${de.value} !${de.priority};`}U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${_}px !important; ${Y}`)}else n.style?.defaultClass&&(U.classList.add(n.style?.defaultClass),U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${_}px !important; ${Y}`));else if(n.marker===ot.Underline)if(typeof n.color=="object"){let ee=n.color;U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${_}px !important; background-color: rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${0}) !important; ${Y}`),U.style.setProperty("border-bottom",`2px solid rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${1})`,"important")}else if(Ge.isHexColor(n.color)){let ee=Ge.hexToRgbChannels(n.color);U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${_}px !important; background-color: rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${0}) !important; ${Y}`),U.style.setProperty("border-bottom",`2px solid rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${1})`,"important")}else U.setAttribute("style",`border-radius: ${_}px !important; ${Y}`);else if(typeof n.color=="object"){let ee=n.color;U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${_}px !important; background-color: rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${rr}) !important; ${Y}`)}else if(Ge.isHexColor(n.color)){let ee=Ge.hexToRgbChannels(n.color);U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${_}px !important; background-color: rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${rr}) !important; ${Y}`)}else U.setAttribute("style",`border-radius: ${_}px !important; ${Y}`);U.style.setProperty("pointer-events","none"),U.style.position="absolute",U.scale=p,U.rect={height:D.height,left:D.left-h,top:D.top-f,width:D.width},n.pointerInteraction&&(U.setAttribute("data-click","1"),U.tabIndex=0),U.style.width=`${U.rect.width*p}px`,U.style.height=`${U.rect.height*p}px`,U.style.left=`${U.rect.left*p}px`,U.style.top=`${U.rect.top*p}px`,l.append(U);let be=parseInt(U.style.top.replace("px",""));if((be<R||R===0)&&(R=be),C=parseInt(U.style.height.replace("px","")),y){let ee=i.createElement("div");ee.setAttribute("class",pi);let de=n.color;Ge.isHexColor(de)&&(de=Ge.hexToRgbChannels(de)),ee.setAttribute("style",`background-color: rgba(${de.red}, ${de.green}, ${de.blue}, ${rr}) !important;`),ee.style.setProperty("pointer-events","none"),ee.style.position="absolute",ee.scale=p,ee.rect={height:D.height,left:D.left-h,top:D.top-f,width:D.width},ee.style.width=`${ee.rect.width*p}px`,ee.style.height=`${x*p}px`,ee.style.left=`${ee.rect.left*p}px`,ee.style.top=`${(ee.rect.top+ee.rect.height/2-x/2)*p}px`,l.append(ee)}let le=this.delegate.iframes[0].contentWindow?.innerWidth,_e=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-count")),me=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-width")),Ce=parseInt(getComputedStyle(i.body).getPropertyValue("padding-left")),De=le/(_e||1);De<me&&(De=le),s||(De=parseInt(getComputedStyle(i.body).width.replace("px","")));let ce=this.delegate.settings.fontSize/100,Pe=20*ce;ce<=1&&(Pe=-60);let Le=0*ce;ce<=1&&(Le=-60),I=Math.floor(D.left/De)*De+De-(C<40?40:C)+Le,z=Math.floor(D.left/De)*De+(C<40?40:C)-Pe;let Ie=parseInt(this.delegate.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));Ie>=2&&(z=z+Ce/_e,I=I-Ce/_e),s||(I=parseInt(getComputedStyle(this.delegate.iframes[0].contentDocument?.body).width.replace("px","")),z=parseInt(getComputedStyle(this.delegate.iframes[0].contentDocument?.body).width.replace("px",""))-De,Ie>=2&&(z=z+Ce/2,I=I-Ce/2))}let N=o.getBoundingClientRect(),J=i.createElement("div");J.setAttribute("class",Za),J.style.setProperty("pointer-events","none"),J.style.position="absolute",J.scale=p,J.rect={height:N.height,left:N.left-h,top:N.top-f,width:N.width},J.style.width=`${J.rect.width*p}px`,J.style.height=`${J.rect.height*p}px`,J.style.left=`${J.rect.left*p}px`,J.style.top=`${J.rect.top*p}px`,l.append(J);let V=i.createElement("div");if(V.setAttribute("class",Qa),n.icon?.position==="left")V.setAttribute("style",`position: absolute;top:${R}px;left:${z+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${C}px; width:${C}px;`);else if(n.icon?.position==="inline")V.setAttribute("style",`position: absolute;top:${R-C/2}px;left:${parseInt(J.style.left.replace("px",""))+parseInt(J.style.width.replace("px",""))-C/2}px;height:${C}px; width:${C}px;`);else if(n.icon?.position==="center"){let U=C/3*2;V.setAttribute("style",`position: absolute;top:${R}px;left:${parseInt(J.style.left.replace("px",""))+parseInt(J.style.width.replace("px",""))-U}px;height:${C}px; width:${C}px;`)}else n.note&&n.marker!==ot.Custom&&n.marker!==ot.Bookmark?V.setAttribute("style",`position: absolute;top:${R-C/2}px;left:${parseInt(J.style.left.replace("px",""))+parseInt(J.style.width.replace("px",""))-C/2}px;height:${C}px; width:${C}px;`):V.setAttribute("style",`position: absolute;top:${R}px;left:${I+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${C}px; width:${C}px;`);if(n.marker===ot.Custom||n.marker===ot.Bookmark)n.icon?.class?(V.classList.add(n.icon?.class),V.id=n.icon?.id):n.icon?.svgPath?V.innerHTML=A0(`${n.icon?.id}`,`${n.icon?.title}`,`${n.icon?.svgPath}`,"icon open",C,`${n.icon?.color} !important`):V.innerHTML=n.icon?.title;else if(n.note){let D=n.color;Ge.isHexColor(D)&&(D=Ge.hexToRgbChannels(D)),V.innerHTML=A0("note-icon","Note",'<rect fill="none" height="24" width="24"/><path d="M19,5v9l-5,0l0,5H5V5H19 M19,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h10l6-6V5C21,3.9,20.1,3,19,3z M12,14H7v-2h5V14z M17,10H7V8h10V10z"/>',"icon open",C,`rgba(${D.red}, ${D.green}, ${D.blue}, 1) !important`)}V.style.setProperty("pointer-events","all");let j=this;if(n.type!==nt.PageBreak&&n.type!==nt.Definition&&V.addEventListener("click",async function(D){let U;j.delegate.rights.enableAnnotations?(U=await j.delegate.annotationModule?.getAnnotationByID(n.id),j.delegate.annotationModule?.api?.selectedAnnotation(U).then(async()=>{})):j.delegate.rights.enableBookmarks&&(U=await j.delegate.bookmarkModule?.getAnnotationByID(n.id)),K&&console.log("selected highlight "+U.id),j.lastSelectedHighlight=U.id;let Y=document.getElementById("highlight-toolbox");if(Y)if(Y.style.top=D.clientY+(j.delegate.attributes?.navHeight??0)+"px",Y.style.left=D.clientX+"px",getComputedStyle(Y).display==="none"){let me=function(){U.highlight.note=prompt("Add your note here:"),j.delegate.annotationModule?.updateAnnotation(U).then(async()=>{K&&console.log("update highlight "+U.id),Y.style.display="none",j.selectionMenuClosed()}),Y.style.display="none",j.selectionMenuClosed()},ce=function(){j.delegate.rights.enableAnnotations?j.delegate.annotationModule?.deleteSelectedHighlight(U).then(async()=>{K&&console.log("delete highlight "+U.id),Y.style.display="none",j.selectionMenuClosed()}):j.delegate.rights.enableBookmarks&&j.delegate.bookmarkModule?.deleteSelectedHighlight(U).then(async()=>{K&&console.log("delete highlight "+U.id),Y.style.display="none",j.selectionMenuClosed()})};Y.style.display="block",j.toolboxMode("edit");let le=document.getElementById("colorIcon"),_e=document.getElementById("highlightIcon");le&&(le.style.display="none"),_e&&(_e.style.display="none");let Ce=document.getElementById("commentIcon"),De=document.getElementById("cloneCommentIcon");if(De){let Ie=De.parentElement;Ie&&Ie.removeChild(De)}if(Ce){Ce.style.display="none";let Ie=Ce.cloneNode(!0),ee=Ce.parentElement;Ie.style.display="unset",Ie.id="cloneCommentIcon",Ie.addEventListener("click",me,!1),ee&&ee.append(Ie)}let Pe=document.getElementById("deleteIcon"),Le=document.getElementById("cloneDeleteIcon");if(Le){let Ie=Le.parentElement;Ie&&Ie.removeChild(Le)}if(Pe){Pe.style.display="none";let Ie=Pe.cloneNode(!0),ee=Pe.parentElement;Ie.style.display="unset",Ie.id="cloneDeleteIcon",Ie.addEventListener("click",ce,!1),ee&&ee.append(Ie)}}else Y.style.display="none",j.selectionMenuClosed(),Y.offsetWidth,Y.style.display="block";let be=Array.from(l.querySelectorAll(`.${pi}`));j.setHighlightAreaStyle(i,be,n)}),n.note){let D=document.createElement("span");D.innerHTML=n.note,D.className="icon-tooltip",n.marker===ot.Custom||n.marker===ot.Bookmark?(n.popup?.background&&D.style.setProperty("background",n.popup.background),n.popup?.textColor&&D.style.setProperty("color",n.popup.textColor),n.popup?.class&&D.classList.add(n.popup.class)):(D.style.setProperty("background","lightyellow"),D.style.setProperty("color","black")),V.insertBefore(D,V.childNodes[0])}switch((n.note||n.marker===ot.Custom||n.marker===ot.Bookmark)&&l.append(V),n.type){case nt.Search:i.getElementById(Ue.R2_ID_SEARCH_CONTAINER).append(l);break;case nt.ReadAloud:i.getElementById(Ue.R2_ID_READALOUD_CONTAINER).append(l);break;case nt.PageBreak:i.getElementById(Ue.R2_ID_PAGEBREAK_CONTAINER).append(l);break;case nt.Definition:i.getElementById(Ue.R2_ID_DEFINITIONS_CONTAINER).append(l);break;default:i.getElementById(Ue.R2_ID_HIGHLIGHTS_CONTAINER).append(l);break}return l}};var U0=At(Ad());var aS=At($0());T();var no={className:r=>!0,idName:r=>!0,tagName:r=>!0};var lS=At(Cd()),nl=class{constructor(t,n,i,o,l,s,a,u,h){this.hide=xe(document,"#menu-button-hide");this.show=xe(document,"#menu-button-show");this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=h,this.delegate=o,this.initialAnnotations=l,this.highlighter=a,this.properties=s,this.api=u}static async create(t){let n=new this(t.annotator,t.rights||{enableAnnotations:!1,enableTTS:!1},t.publication,t.delegate,t.initialAnnotations||null,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){K&&console.log("Annotation module stop")}async start(){if(this.delegate.annotationModule=this,this.headerMenu&&(this.highlightsView=xe(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var t=this.initialAnnotations.highlights||null;t&&this.annotator?.initAnnotations(t)}setTimeout(()=>{this.properties?.hideLayer?this.delegate.hideLayer("highlights"):this.delegate.showLayer("highlights")},10)}hideAnnotationLayer(){let t=this.delegate.iframes[0].contentDocument;if(t){let n=xe(t,"#R2_ID_HIGHLIGHTS_CONTAINER");n&&(n.style.display="none")}this.show&&this.hide&&(this.show.style.display="block",this.hide.style.display="none")}showAnnotationLayer(){let t=this.delegate.iframes[0].contentDocument;if(t){let n=xe(t,"#R2_ID_HIGHLIGHTS_CONTAINER");n&&(n.style.display="block")}this.show&&this.hide&&(this.show.style.display="none",this.hide.style.display="block")}async handleResize(){setTimeout(async()=>{await this.drawHighlights(),await this.showHighlights()},100)}initialize(){return new Promise(async t=>{await document.fonts.ready,this.rights.enableAnnotations&&setTimeout(()=>{this.drawHighlights(),this.showHighlights(),ve(this.delegate.iframes[0].contentDocument?.body,"click",this.click.bind(this))},300),t(null)})}click(t){if(this.activeAnnotationMarkerId){let n=this.highlighter?.properties?.selectionMenuItems?.filter(i=>i.id===this.activeAnnotationMarkerId);if(n&&n?.length>0){let i=lS.cloneDeep(n[0]);i.marker=ot.Custom,this.activeAnnotationMarkerPosition&&(i.icon.position=this.activeAnnotationMarkerPosition),i.highlight.style.default=null,i.highlight.style.hover=null;let o=this.delegate.iframes[0].contentDocument;if(o){let h=function(p){try{let g=u.delegate.iframes[0].contentDocument;return g?Dn(p,g,no):""}catch(g){return console.log("uniqueCssSelector:"),console.log(g),""}},l=this.highlighter?.dom(o.body).getSelection(),s=l.getRangeAt(0),a=l.anchorNode;s.setStart(a,s.startOffset),s.setEnd(a,s.endOffset+1),l.removeAllRanges(),l.addRange(s);let u=this,f=Mr(s,h);if(l.removeAllRanges(),f){let p={rangeInfo:f},g=this.delegate.highlighter?.createHighlight(this.delegate.highlighter?.dom(o.body).getWindow(),p,i.highlight.color,!0,ot.Bookmark,i.icon,i.popup,i.highlight.style);g&&this.saveAnnotation(g[0]).then(y=>{K&&console.log("saved bookmark "+y.id)})}o.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(t){K&&console.log("still need to scroll to "+t);var n=await this.annotator?.getAnnotationPosition(t,this.delegate.iframes[0].contentWindow);window.scrollTo(0,n-window.innerHeight/3)}async updateLocalHighlight(t){if(this.annotator){let n=await this.annotator.deleteAnnotation(t.id),i=await this.addAnnotation(t);return K&&(console.log("Highlight deleted "+JSON.stringify(n)),console.log("Highlight added "+JSON.stringify(i))),await this.showHighlights(),await this.drawHighlights(),this.delegate.rights.enableMaterial&&(0,U0.toast)({html:"highlight updated"}),i}else return new Promise(n=>n(null))}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return K&&console.log("Highlight deleted "+JSON.stringify(n)),await this.showHighlights(),await this.drawHighlights(),this.delegate.rights.enableMaterial&&(0,U0.toast)({html:"highlight deleted"}),n}else return new Promise(i=>i(null))}async deleteAnnotation(t){await this.deleteLocalHighlight(t.id)}async addAnnotation(t){await this.annotator?.saveAnnotation(t),await this.showHighlights(),await this.drawHighlights()}async deleteHighlight(t){this.api?.deleteAnnotation?this.api?.deleteAnnotation(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteSelectedHighlight(t){this.api?.deleteAnnotation?this.api.deleteAnnotation(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async updateAnnotation(t){this.api?.updateAnnotation?this.api.updateAnnotation(t).then(async()=>{this.updateLocalHighlight(t)}):this.updateLocalHighlight(t)}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.delegate.currentChapterLink.href);this.delegate.currentTocUrl&&(n=this.publication.getTOCItem(this.delegate.currentTocUrl)),n===void 0&&(n=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href));let i=this.delegate.view?.getCurrentPosition(),o=this.delegate.iframes[0].contentDocument;if(o){let l=Sr(o,"body"),s=t.position?t.position/l.scrollHeight:i,a=(0,aS.v4)(),u;if(n){let h=n.Href;if(h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let f=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),p=Math.ceil((s??0)*(f.length-1)),g=f[p];u=ln(it({},g),{id:a,href:h,created:new Date,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else u={id:a,href:h,locations:{progression:s},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(u)if(this.api?.addAnnotation){let h=await this.api.addAnnotation(u),f=await this.annotator.saveAnnotation(h);return await this.showHighlights(),await this.drawHighlights(),new Promise(p=>p(f))}else{let h=await this.annotator.saveAnnotation(u);return await this.showHighlights(),await this.drawHighlights(),new Promise(f=>f(h))}}}return new Promise(i=>i(null))}getAnnotations(){let t=[];return this.annotator&&(t=this.annotator.getAnnotations()),t}showHighlights(){let t=[];this.annotator&&(t=this.annotator.getAnnotations(),t&&(t=t.filter(n=>n.highlight.marker!==ot.Bookmark),t.forEach(n=>{Yt.push(n.highlight)}))),this.highlightsView&&this.createTree(hi.Annotation,t,this.highlightsView)}async drawHighlights(){if(this.rights.enableAnnotations&&this.highlighter){if(this.api){let n=[];if(this.annotator&&(n=this.annotator.getAnnotations()),this.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(nt.Annotation);for(let i of n){Yt.push(i.highlight);let o=i,l=this.delegate.currentChapterLink.href;var t=this.publication.getTOCItem(l);if(this.delegate.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let s=t.Href;s.indexOf("#")>0&&(s=s.slice(0,s.indexOf("#"))),o.href===s&&(await this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===ot.Underline){let a=await this.annotator?.getAnnotationPosition(i.id,this.delegate.iframes[0].contentWindow),u='<div class="comment" style="top: '+a+'px;width:20px"></div>',h=document.createElement("div");h.innerHTML=u;let f=h.childNodes[0],p=document.createElement("i");p.innerHTML="sticky_note_2",p.className="material-icons",p.style.color=o.highlight.color,f.appendChild(p),ve(h,"click",g=>{g.preventDefault(),g.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}else{let n=[];if(this.annotator&&(n=this.annotator.getAnnotations()),this.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(nt.Annotation);for(let i of n){Yt.push(i.highlight);let o=i,l=this.delegate.currentChapterLink.href,s=this.publication.getTOCItem(l);if(this.delegate.currentTocUrl&&(s=this.publication.getTOCItem(this.delegate.currentTocUrl)),s===null&&(s=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),s){let a=s.Href;a.indexOf("#")>0&&(a=a.slice(0,a.indexOf("#"))),o.href===a&&(await this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===ot.Underline){let u=await this.annotator?.getAnnotationPosition(i.id,this.delegate.iframes[0].contentWindow),h='<div class="comment" style="top: '+u+"px;background: "+o.highlight?.color+';width:20px"></div>',f=document.createElement("div");f.innerHTML=h,f.childNodes[0].innerHTML=$i.note,ve(f,"click",p=>{p.preventDefault(),p.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor)}}createTree(t,n,i){if(n){let o=this,l=this.publication.readingOrder;if(l.length){let s=(a,u)=>{let h=document.createElement("ul");h.className="sidenav-annotations";for(let f of u){let p=document.createElement("li"),g=document.createElement("a"),y=document.createElement("span");if(g.tabIndex=-1,g.className="chapter-link",f.Href){let b=this.publication.getAbsoluteHref(f.Href),w=this.publication.getTOCItemAbsolute(b);g.href=b,g.innerHTML=w?.Title||"",p.appendChild(g)}else y.innerHTML=f.Title||"",y.className="chapter-title",p.appendChild(y);ve(g,"click",b=>{b.preventDefault(),b.stopPropagation();let w={href:g.href,locations:{progression:0},type:f.TypeLink,title:g.title};this.delegate.stopReadAloud(),this.delegate.navigate(w)});let E=document.createElement("ol");n.forEach(function(b){let w=f.Href.indexOf("#")!==-1?f.Href.slice(0,f.Href.indexOf("#")):f.Href;if(f.Href&&b.href.endsWith(w)){let _=document.createElement("li");_.className="annotation-item";let S=document.createElement("a");if(S.setAttribute("href",b.href),t===hi.Annotation){S.className="highlight-link";let R=document.createElement("span"),C=document.createElement("span");if(R.className="title",C.innerHTML=b.highlight.selectionInfo.cleanText,b.highlight?.marker===ot.Underline)if(typeof b.highlight?.color=="object"){let N=b.highlight?.color;N&&C.style.setProperty("border-bottom",`2px solid ${Ge.hexToRgbA(N)}`,"important")}else C.style.setProperty("border-bottom",`2px solid ${b.highlight?.color}`,"important");else if(typeof b.highlight?.color=="object"){let N=b.highlight?.color;N&&(C.style.backgroundColor=Ge.hexToRgbA(N))}else{let N=b.highlight?.color;N&&(C.style.backgroundColor=N)}R.appendChild(C),S.appendChild(R);let I=document.createElement("span"),z=Math.round((b.locations.progression??0)*100)+"% through resource";I.className="subtitle",I.innerHTML=z,S.appendChild(I)}let x=document.createElement("span");if(x.className="timestamp",x.innerHTML=nl.readableTimestamp(b.created),S.appendChild(x),ve(S,"click",R=>{R.preventDefault(),R.stopPropagation(),o.handleAnnotationLinkClick(R,b)}),_.appendChild(S),o.delegate.sideNavExpanded&&o.delegate.rights.enableMaterial||!o.delegate.rights.enableMaterial){let R=document.createElement("button");R.className="delete",R.innerHTML=$i.delete,ve(R,"click",C=>{C.preventDefault(),C.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,C,b)}),_.appendChild(R)}E.appendChild(_)}}),E.children.length>0&&(h.appendChild(p),h.appendChild(E)),h.children.length>0&&a.appendChild(h),f.Children&&f.Children.length>0&&s(a,f.Children)}};i.innerHTML="",s(i,l)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.delegate.stopReadAloud(),this.delegate.navigate(n)):K&&console.log("annotation data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){K&&console.log("annotation data locator: ",i),i?t===hi.Annotation&&this.deleteHighlight(i):K&&console.log("annotation data missing: ",n)}static readableTimestamp(t){let n=new Date(t);return n.toDateString()+" "+n.toLocaleTimeString()}async getAnnotation(t){return this.annotator?.getAnnotation(t)}async getAnnotationByID(t){return this.annotator?.getAnnotationByID(t)}};T();var $o=At(Ad()),W0=At($0());var il=class{static async create(t){let n=new this(t.annotator,t.rights||{enableBookmarks:!1},t.publication,t.delegate,t,t.initialAnnotations,t.api,t.headerMenu);return await n.start(),new Promise(i=>i(n))}constructor(t,n,i,o,l,s,a,u){this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=u,this.delegate=o,this.initialAnnotations=s,this.properties=l,this.api=a}stop(){K&&console.log("Bookmark module stop")}async start(){if(this.delegate.bookmarkModule=this,this.headerMenu&&(this.bookmarksView=xe(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=xe(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){var t=xe(this.headerMenu,"#menu-button-bookmark");this.rights.enableMaterial?(t&&t.parentElement?.style.removeProperty("display"),t&&ve(t,"click",this.saveBookmark.bind(this))):(t&&t.parentElement?.style.setProperty("display","none"),this.sideNavSectionBookmarks&&this.sideNavSectionBookmarks.style.setProperty("display","none"))}if(this.initialAnnotations){var n=this.initialAnnotations.bookmarks||null;n&&this.annotator?.initBookmarks(n)}await this.showBookmarks(),await this.drawBookmarks(),setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("highlights"):this.delegate.showLayer("highlights")},10)}async handleResize(){setTimeout(async()=>{await this.drawBookmarks(),await this.showBookmarks()},100)}initialize(){return new Promise(async t=>{await document.fonts.ready,this.rights.enableBookmarks&&setTimeout(()=>{this.drawBookmarks(),this.showBookmarks()},300),t(null)})}async deleteBookmark(t){if(this.annotator)if(this.api?.deleteBookmark){await this.api?.deleteBookmark(t);let n=await this.annotator.deleteBookmark(t);return K&&console.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),this.delegate.rights.enableMaterial&&(0,$o.toast)({html:"bookmark deleted"}),n}else{let n=await this.annotator.deleteBookmark(t);return K&&console.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),this.delegate.rights.enableMaterial&&(0,$o.toast)({html:"bookmark deleted"}),n}else return new Promise(n=>n(null))}async saveBookmarkPlus(){await this.addBookmarkPlus()}async saveBookmark(){if(this.annotator){var t=this.publication.getTOCItem(this.delegate.currentChapterLink.href);if(this.delegate.currentTocUrl&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let n=t.Href;n.indexOf("#")>0&&(n=n.slice(0,n.indexOf("#")));let i=this.delegate.view?.getCurrentPosition(),o=(0,W0.v4)(),l;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let s=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),a=Math.ceil((i??0)*(s.length-1)),u=s[a];l=ln(it({},u),{id:o,href:n,created:new Date,title:this.delegate.currentChapterLink.title})}else l={id:o,href:n,locations:{progression:i},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title};if(this.annotator.locatorExists(l,hi.Bookmark))this.delegate.rights.enableMaterial&&(0,$o.toast)({html:"bookmark exists"});else if(this.api?.addBookmark){let s=await this.api.addBookmark(l);s&&(l=s),K&&console.log(l);let a=this.annotator.saveBookmark(l);return K&&console.log("Bookmark added "+JSON.stringify(a)),this.delegate.rights.enableMaterial&&(0,$o.toast)({html:"bookmark added"}),this.showBookmarks(),await this.drawBookmarks(),a}else{let s=this.annotator.saveBookmark(l);return K&&console.log("Bookmark added "+JSON.stringify(s)),this.delegate.rights.enableMaterial&&(0,$o.toast)({html:"bookmark added"}),this.showBookmarks(),await this.drawBookmarks(),s}}}}async addBookmarkPlus(){let t=this,n=this.delegate.highlighter?.visibleTextRects[0],i=this.delegate.iframes[0].contentDocument;if(i){let a=this.delegate.highlighter?.dom(i.body).getWindow().document.createRange(),u=this.delegate.highlighter?.dom(this.delegate.iframes[0].contentDocument?.body).getSelection();u.removeAllRanges(),n&&a.selectNodeContents(n.node),u.addRange(a);let h=_d(a,!1),f=0;for(let p of h){if(!this.delegate.highlighter?.isOutsideViewport(p)){let g=u.focusNode,y=u.focusOffset;u.collapse(u.anchorNode,u.anchorOffset);for(let _=0;_<f;_++)u.modify("move","forward","line");u.extend(g,y);let E=u.focusNode,b=u.focusNode.length;u.collapse(u.anchorNode,u.anchorOffset);let w=b;u.anchorOffset>b?w=b:w=u.anchorOffset+1,u.modify("move","forward","character"),u.modify("move","backward","word"),u.extend(E,w),u.modify("extend","backward","character"),u.modify("extend","forward","word");break}f++}}function o(a){let u={},h=t.delegate.iframes[0].contentDocument;if(h)return Dn(a,t.delegate.highlighter?.dom(h.body).getDocument(),u)}let l=this.delegate.iframes[0].contentWindow,s={id:"bookmarkIcon",marker:ot.Bookmark,icon:{id:"bookmarkIcon",title:"Bookmark",svgPath:'<path d="M0 0h24v24H0V0z" fill="none"/><path d="M17 3H7c-1.1 0-2 .9-2 2v16l7-3 7 3V5c0-1.1-.9-2-2-2z"/>',color:"#000000",position:"left"},popup:{background:"#000000",textColor:"#ffffff"},highlight:{color:"#000000",style:{default:[{property:"border-bottom",value:"0px dashed #000000",priority:"important"}]}}};if(l!==null){let a=Qr(l,o),u=t.delegate.iframes[0].contentDocument;if(a&&u){let h=this.delegate.highlighter?.createHighlight(this.delegate.highlighter?.dom(u.body).getWindow(),a,s.highlight?.color,!0,ot.Bookmark,s.icon,s.popup,s.highlight?.style);if(this.delegate.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),h)return this.saveAnnotation(h[0]).then(f=>{K&&console.log("saved bookmark "+f?.id)})}}}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.delegate.currentChapterLink.href);this.delegate.currentTocUrl&&(n=this.publication.getTOCItem(this.delegate.currentTocUrl)),n===null&&(n=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href));let i=this.delegate.view?.getCurrentPosition(),o=this.delegate.iframes[0].contentDocument;if(o){let l=Sr(o,"body"),s=t.position?t.position/l.scrollHeight:i,a=(0,W0.v4)(),u;if(n){let h=n.Href;if(h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let f=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),p=Math.ceil((s??0)*(f.length-1)),g=f[p];u=ln(it({},g),{id:a,href:h,created:new Date,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else u={id:a,href:h,locations:{progression:s},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(u)if(this.api?.addBookmark){let h=await this.api.addBookmark(u),f=await this.annotator.saveAnnotation(h);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(p=>p(f))}else{let h=await this.annotator.saveAnnotation(u);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(f=>f(h))}}}return new Promise(i=>i(void 0))}getBookmarks(){let t=[];return this.annotator&&(t=this.annotator.getBookmarks()),t}showBookmarks(){let t=[];this.annotator&&(t=this.annotator.getBookmarks());let n=[];this.annotator&&(n=this.annotator.getAnnotations(),n&&(n=n.filter(i=>i.highlight.marker===ot.Bookmark),t?t.push.apply(t,n):t=n)),this.bookmarksView&&this.createTree(hi.Bookmark,t,this.bookmarksView)}async drawBookmarks(){if(this.rights.enableBookmarks&&this.delegate.highlighter)if(this.api){let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.delegate.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.delegate.highlighter.destroyHighlights(nt.Annotation);for(let i of n){Yt.push(i.highlight);let o=i,l=this.delegate.currentChapterLink.href;var t=this.publication.getTOCItem(l);if(this.delegate.currentTocUrl&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let s=t.Href;s.indexOf("#")>0&&(s=s.slice(0,s.indexOf("#"))),o.href===s&&await this.delegate.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight)}}}}else{let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.delegate.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.delegate.highlighter.destroyHighlights(nt.Annotation);for(let i of n){Yt.push(i.highlight);let o=i,l=this.delegate.currentChapterLink.href,s=this.publication.getTOCItem(l);if(this.delegate.currentTocUrl&&(s=this.publication.getTOCItem(this.delegate.currentTocUrl)),s===void 0&&(s=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),s){let a=s.Href;a.indexOf("#")>0&&(a=a.slice(0,a.indexOf("#"))),o.href===a&&await this.delegate.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight)}}}}}async deleteSelectedHighlight(t){this.api?.deleteBookmark?this.api.deleteBookmark(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return K&&console.log("Highlight deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),this.delegate.rights.enableMaterial&&(0,$o.toast)({html:"highlight deleted"}),n}else return new Promise(i=>i(null))}createTree(t,n,i){if(n){let o=this,l=this.publication.readingOrder;if(l.length){let s=(a,u)=>{let h=document.createElement("ul");h.className="sidenav-annotations";for(let f of u){let p=document.createElement("li"),g=document.createElement("a"),y=document.createElement("span");if(g.tabIndex=-1,g.className="chapter-link",f.Href){let b=this.publication.getAbsoluteHref(f.Href),w=this.publication.getTOCItemAbsolute(b);g.href=b,g.innerHTML=w?.Title||"",p.appendChild(g)}else y.innerHTML=f.Title||"",y.className="chapter-title",p.appendChild(y);ve(g,"click",b=>{b.preventDefault(),b.stopPropagation();let w={href:g.href,locations:{progression:0},type:f.TypeLink,title:g.title};this.delegate.stopReadAloud(),this.delegate.navigate(w)});let E=document.createElement("ol");n.forEach(function(b){let w=f.Href.indexOf("#")!==-1?f.Href.slice(0,f.Href.indexOf("#")):f.Href;if(f.Href&&b.href.endsWith(w)){let _=document.createElement("li");_.className="annotation-item";let S=document.createElement("a");if(S.setAttribute("href",b.href),t===hi.Bookmark){S.className="bookmark-link";let R=document.createElement("span"),C=Math.round((b.locations.progression??0)*100)+"% through resource";R.className="title",R.innerHTML=C,S.appendChild(R)}let x=document.createElement("span");if(x.className="timestamp",x.innerHTML=il.readableTimestamp(b.created),S.appendChild(x),ve(S,"click",R=>{R.preventDefault(),R.stopPropagation(),o.handleAnnotationLinkClick(R,b)}),_.appendChild(S),o.delegate.sideNavExpanded&&o.delegate.rights.enableMaterial||!o.delegate.rights.enableMaterial){let R=document.createElement("button");R.className="delete",R.innerHTML=$i.delete,ve(R,"click",C=>{C.preventDefault(),C.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,C,b)}),_.appendChild(R)}E.appendChild(_)}}),E.children.length>0&&(h.appendChild(p),h.appendChild(E)),h.children.length>0&&a.appendChild(h),f.Children&&f.Children.length>0&&s(a,f.Children)}};i.innerHTML="",s(i,l)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.delegate.stopReadAloud(),this.delegate.navigate(n)):K&&console.log("bookmark data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){K&&console.log("bookmark data locator: ",i),i?t===hi.Bookmark&&this.deleteBookmark(i):K&&console.log("bookmark data missing: ",n)}static readableTimestamp(t){let n=new Date(t);return n.toDateString()+" "+n.toLocaleTimeString()}async getAnnotation(t){return this.annotator?.getAnnotation(t)}async getAnnotationByID(t){return this.annotator?.getAnnotationByID(t)}};T();var uS=At(cS());T();var z0="r2-mo-active",Wo=class{},Ve=Wo;Ve.COLOR_REF="color",Ve.AUTO_SCROLL_REF="autoscroll",Ve.AUTO_TURN_REF="autoturn",Ve.VOLUME_REF="volume",Ve.RATE_REF="rate",Ve.COLOR_KEY="mediaoverlay-"+Wo.COLOR_REF,Ve.AUTO_SCROLL_KEY="mediaoverlay-"+Wo.AUTO_SCROLL_REF,Ve.AUTO_TURN_KEY="mediaoverlay-"+Wo.AUTO_TURN_REF,Ve.VOLUME_KEY="mediaoverlay-"+Wo.VOLUME_REF,Ve.RATE_KEY="mediaoverlay-"+Wo.RATE_REF;var V0=class{constructor(t,n,i){this.MEDIAOVERLAYSETTINGS="mediaOverlaySetting";this.color="r2-mo-active";this.autoScroll=!0;this.autoTurn=!0;this.volume=1;this.rate=1;this.playing=!1;this.resourceReady=!1;this.wait=1;this.settingsChangeCallback=()=>{};this.store=t,this.api=n,this.headerMenu=i,this.initialise(),console.log(this.api)}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialMediaOverlaySettings){let i=t.initialMediaOverlaySettings;i?.color&&(n.color=i.color,K&&console.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,K&&console.log(n.autoScroll)),i?.autoTurn&&(n.autoTurn=i.autoTurn,K&&console.log(n.autoTurn)),i?.volume&&(n.volume=i.volume,K&&console.log(n.volume)),i?.rate&&(n.rate=i.rate,K&&console.log(n.rate)),i?.wait&&(n.wait=i.wait,K&&console.log(n.wait))}return n.initializeSelections(),n}stop(){K&&console.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(Ve.AUTO_SCROLL_KEY)!=null?this.getProperty(Ve.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(Ve.AUTO_TURN_KEY)!=null?this.getProperty(Ve.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(Ve.COLOR_KEY)!=null?this.getProperty(Ve.COLOR_KEY).value:this.color,this.volume=this.getProperty(Ve.VOLUME_KEY)!=null?this.getProperty(Ve.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(Ve.RATE_KEY)!=null?this.getProperty(Ve.RATE_KEY).value:this.rate,this.userProperties=this.getMediaOverlaySettings()}reset(){this.color="redtext",this.autoScroll=!0,this.autoTurn=!0,this.volume=1,this.rate=1,this.wait=1,this.userProperties=this.getMediaOverlaySettings()}initializeSelections(){this.headerMenu&&(this.settingsView=xe(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechAutoTurn=xe(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=xe(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=xe(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=xe(this.headerMenu,"#mediaOverlayRate")),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),this.speechAutoTurn&&(this.speechAutoTurn.checked=this.autoTurn),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechRate&&(this.speechRate.value=this.volume.toString()),ve(xe(t,"ul"),"click",n=>{n.stopPropagation()})}onSettingsChange(t){this.settingsChangeCallback=t}storeProperty(t){this.updateUserSettings(),this.saveProperty(t)}updateUserSettings(){let t={color:this.userProperties.getByRef(Ve.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Ve.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(Ve.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(Ve.VOLUME_REF)?.value,rate:this.userProperties.getByRef(Ve.RATE_REF)?.value};this.applyMediaOverlaySettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{K&&console.log("api updated sync settings",n)})}getMediaOverlaySettings(){let t=new _r;return t.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,Ve.AUTO_SCROLL_REF,Ve.AUTO_SCROLL_KEY),t.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,Ve.AUTO_TURN_REF,Ve.AUTO_TURN_KEY),t.addStringable(this.color,Ve.COLOR_REF,Ve.COLOR_KEY),t.addIncremental(this.volume,.1,1,.1,"",Ve.VOLUME_REF,Ve.VOLUME_KEY),t.addIncremental(this.rate,.1,3,.1,"",Ve.RATE_REF,Ve.RATE_KEY),t}saveProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}return t}getProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}resetMediaOverlaySettings(){this.store.remove(this.MEDIAOVERLAYSETTINGS),this.reset(),this.settingsChangeCallback()}applyMediaOverlaySettings(t){if(t.color){this.color=t.color;let n=this.userProperties.getByRef(Ve.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){K&&console.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Ve.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoTurn!==void 0){K&&console.log("autoTurn "+this.autoTurn),this.autoTurn=t.autoTurn;let n=this.userProperties.getByRef(Ve.AUTO_TURN_REF);n&&(n.value=this.autoTurn,this.saveProperty(n)),this.settingsChangeCallback()}if(t.volume){K&&console.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Ve.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback()}if(t.rate){K&&console.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Ve.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback()}}applyMediaOverlaySetting(t,n){if(t===Ve.COLOR_REF){this.color=n;let i=this.userProperties.getByRef(Ve.COLOR_REF);i&&(i.value=this.color,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===Ve.AUTO_SCROLL_REF){this.autoScroll=n;let i=this.userProperties.getByRef(Ve.AUTO_SCROLL_REF);i&&(i.value=this.autoScroll,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===Ve.AUTO_TURN_REF){this.autoTurn=n;let i=this.userProperties.getByRef(Ve.AUTO_TURN_REF);i&&(i.value=this.autoTurn,this.saveProperty(i)),this.settingsChangeCallback()}}increase(t){if(t==="mo_volume"){this.userProperties.getByRef(Ve.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(Ve.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Ve.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Ve.RATE_REF).increment(),this.rate=this.userProperties.getByRef(Ve.RATE_REF)?.value;let n=this.userProperties.getByRef(Ve.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}decrease(t){if(t==="mo_volume"){this.userProperties.getByRef(Ve.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(Ve.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Ve.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Ve.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(Ve.RATE_REF)?.value;let n=this.userProperties.getByRef(Ve.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}};var G0=class{constructor(t,n,i,o){this.play=xe(document,"#menu-button-play");this.pause=xe(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async t=>{K&&console.log("ontimeupdate"),this.trackCurrentTime()};this.ensureOnTimeUpdate=(t,n)=>{this.audioElement&&(t?this.__ontimeupdate&&(this.__ontimeupdate=!1,this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),cancelAnimationFrame(this.myReq)):(!this.__ontimeupdate||n)&&(this.__ontimeupdate=!0,n&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),this.audioElement.addEventListener("timeupdate",this.ontimeupdate)))};this.delegate=t,this.publication=n,this.settings=i,this.properties=o}static create(t){let n=new this(t.delegate,t.publication,t.settings,t);return n.start(),n}stop(){K&&console.log("MediaOverlay module stop")}start(){this.delegate.mediaOverlayModule=this,K&&console.log("MediaOverlay module start")}async initialize(){return new Promise(async t=>{await document.fonts.ready,this.settings.setControls(),this.settings.onSettingsChange(()=>{this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}),t()})}async initializeResource(t){this.currentLinks=t,this.currentLinkIndex=0,await this.playLink()}async playLink(){let t=this.currentLinks[this.currentLinkIndex];if(t?.Properties?.MediaOverlay){this.ensureOnTimeUpdate(!1,!1);let n=t.Properties?.MediaOverlay,o=new URL(n,this.publication.manifestUrl).toString(),l;try{l=await fetch(o)}catch(h){console.error(h,o);return}l.ok||K&&console.log("BAD RESPONSE?!");let s;try{s=await l.json()}catch(h){console.error(h)}if(!s){K&&console.log("## moJson"+s);return}t.MediaOverlays=xu(s,uS.MediaOverlayNode),t.MediaOverlays.initialized=!0;let a=t.HrefDecoded||t.Href,u=new URL("https://dita.digital/"+a);await this.playMediaOverlays(u.pathname.substr(1),t.MediaOverlays,void 0)}else this.audioElement&&await this.audioElement.pause(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud()}async startReadAloud(){if(this.delegate.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement){let t=this.currentAudioBegin?this.currentAudioBegin:0;this.audioElement.currentTime=t,await this.audioElement.play(),this.ensureOnTimeUpdate(!1,!0),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}else this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?this.delegate.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&(this.pause.style.display="block")}}async stopReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.currentLinkIndex>0&&await this.playLink(),this.settings.playing=!1,this.audioElement?.pause(),this.play&&(this.play.style.display="block"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&(this.play.style.display="block"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&(this.pause.style.display="block"))}findDepthFirstTextAudioPair(t,n,i){K&&console.log("findDepthFirstTextAudioPair()");let o,l;if(n.Text){let u=new URL("https://dita.digital/"+n.Text);if(u.pathname.substr(1)===t){if(o=!0,u.hash&&i){l=!1;let h=u.hash.substr(1);for(let f of i)if(f===h){l=!0;break}}}else o=!1}if(K&&(console.log("isFragmentIDMatch: "+l),console.log("isTextUrlMatch: "+o)),!n.Children||!n.Children.length){if(K&&console.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!o){K&&console.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return l||o&&!i?(K&&console.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),n):void 0}let s=i,a=i;for(let u of n.Children){K&&(console.log("findDepthFirstTextAudioPair() - child"),console.log(JSON.stringify(u)));let h=this.findDepthFirstTextAudioPair(t,u,a);if(h===null&&(K&&console.log("findDepthFirstTextAudioPair() - child - match null (skip)"),a=void 0),h)return K&&(console.log("findDepthFirstTextAudioPair() - child - match"),console.log(JSON.stringify(h))),h}if(l){K&&console.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let u=this.findDepthFirstTextAudioPair(t,n,void 0);return u&&(K&&(console.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),console.log(JSON.stringify(u))),u)}if(s&&!a)return null}trackCurrentTime(){if(cancelAnimationFrame(this.myReq),this.mediaOverlayTextAudioPair)try{this.currentAudioEnd&&this.audioElement.currentTime>=this.currentAudioEnd-.05&&(K&&console.log("ontimeupdate - mediaOverlaysNext()"),this.mediaOverlaysNext());let t=this.mediaOverlayTextAudioPair.Text.lastIndexOf("#"),n=this.mediaOverlayTextAudioPair.Text.substr(t+1);this.mediaOverlayHighlight(n),this.myReq=requestAnimationFrame(this.trackCurrentTime.bind(this))}catch(t){}}mediaOverlaysNext(t){if(K&&console.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let n=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!t);if(!n)K&&console.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud());else{let i=!1;if(this.mediaOverlayTextAudioPair.Text&&n.Text){let o=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),l=new URL("https://dita.digital/"+n.Text);o.pathname!==l.pathname&&(K&&console.log("mediaOverlaysNext() SWITCH! "+o.pathname+" != "+l.pathname),i=!0)}i?this.mediaOverlaysStop():(K&&console.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(n,void 0,void 0)},0))}}else K&&console.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){K&&console.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){K&&console.log("mediaOverlaysPause()"),this.mediaOverlayHighlight(void 0),this.audioElement&&this.audioElement.pause()}findNextTextAudioPair(t,n,i,o){if(!t.Children||!t.Children.length){if(i?.prev===n)return K&&console.log("findNextTextAudioPair() - prevMo === moToMatch"),t;K&&(console.log("findNextTextAudioPair() - set previous"),console.log(JSON.stringify(t))),i.prev=t;return}for(let l of t.Children){K&&(console.log("findNextTextAudioPair() - child"),console.log(JSON.stringify(l)));let s=this.findNextTextAudioPair(l,n,i,o);if(s)return K&&(console.log("findNextTextAudioPair() - match"),console.log(JSON.stringify(s))),s}}async playMediaOverlaysAudio(t,n,i){if(K&&console.log("playMediaOverlaysAudio()"),this.mediaOverlayTextAudioPair=t,!t.Audio)return;let o=new URL(t.Audio,this.publication.manifestUrl),l=o.toString(),s=new URL(l);s.hash="",s.search="";let a=s.toString(),u=typeof n!="undefined",h=typeof i!="undefined";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!u&&!h){if(o.hash){let p=o.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(p&&p.length>=1){let g=p[1];try{this.currentAudioBegin=parseFloat(g)}catch(y){console.log(y)}if(p.length>=3){let y=p[3];try{this.currentAudioEnd=parseFloat(y)}catch(E){console.log(E)}}}}}else this.currentAudioBegin=n,this.currentAudioEnd=i;K&&console.log(`${l} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let f=async p=>{if(!this.audioElement)return;let g=this.currentAudioBegin?this.currentAudioBegin:0;if(p||this.audioElement.paused)if(p&&!g||this.audioElement.currentTime===g){if(K&&console.log("playMediaOverlaysAudio() - playClip() - _currentAudioElement.play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing){let E=function(){y.settings.resourceReady?setTimeout(async()=>{await y.audioElement.play(),y.ensureOnTimeUpdate(!1,!0)},y.settings.wait*1e3):setTimeout(E,200)},y=this;E()}}else{K&&console.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let y=async E=>{if(this.audioElement.removeEventListener("timeupdate",y),K&&console.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked - .play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement&&(this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing)){let w=function(){b.settings.resourceReady?setTimeout(async()=>{await b.audioElement.play(),b.ensureOnTimeUpdate(!1,!0)},b.settings.wait*1e3):setTimeout(w,200)},b=this;w()}};this.audioElement.addEventListener("timeupdate",y),this.audioElement.currentTime=g}else{let y=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd!="undefined"&&this.previousAudioEnd>g-.02&&this.previousAudioEnd<=g&&this.audioElement.currentTime>=g-.1;this.ensureOnTimeUpdate(!1,!1),y?K&&console.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(K&&console.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=g)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||a!==this.currentAudioUrl){this.currentAudioUrl=a,K&&console.log("playMediaOverlaysAudio() - RESET: "+this.previousAudioUrl+" => "+this.currentAudioUrl),this.audioElement=document.getElementById("AUDIO_MO_ID"),this.audioElement&&(this.audioElement.pause(),this.audioElement.setAttribute("src",""),this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement)),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("style","display: none"),this.audioElement.setAttribute("id","AUDIO_MO_ID"),this.audioElement.setAttribute("role","media-overlays"),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate,document.body.appendChild(this.audioElement),this.audioElement.addEventListener("error",y=>{console.log("-1) error: "+(this.currentAudioUrl!==y.currentTarget.src?this.currentAudioUrl+" -- ":"")+y.currentTarget.src.substr(y.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(console.log(this.audioElement.error.code),console.log(this.audioElement.error.message))});let p=async y=>{y.currentTarget.removeEventListener("canplaythrough",p),K&&console.log("oncanplaythrough"),await f(!0)};this.audioElement.addEventListener("canplaythrough",p);let g=async y=>{K&&console.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",g),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else K&&console.log("playMediaOverlaysAudio() - playClip()"),await f(!1)}async playMediaOverlays(t,n,i){K&&console.log("playMediaOverlays()");let o=i?i.filter(s=>s):void 0;o&&o.length===0&&(o=void 0);let l=this.findDepthFirstTextAudioPair(t,n,o);!l&&o&&(K&&(console.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),console.log(JSON.stringify(o,null,4)),console.log(JSON.stringify(n,null,4))),l=this.findDepthFirstTextAudioPair(t,n,void 0)),l?l.Audio&&(K&&console.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=n,await this.playMediaOverlaysAudio(l,void 0,void 0)):K&&console.log("playMediaOverlays() - !moTextAudioPair "+t)}mediaOverlayHighlight(t){K&&console.log("moHighlight: ## "+t);let n=this.publication.Metadata?.MediaOverlay?.ActiveClass;n||(n=this.settings.color);let i=this.delegate.iframes[0].contentDocument?.documentElement.getAttribute("style"),o=i?i.indexOf("readium-night-on")>0:!1,l=i?i.indexOf("readium-sepia-on")>0:!1;if((this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&(n=o||l?z0:n||z0),this.pid){let a;this.currentLinkIndex===0?a=this.delegate.iframes[0].contentDocument?.getElementById(this.pid):a=this.delegate.iframes[1].contentDocument?.getElementById(this.pid),a&&a.classList.remove(n)}let s;t&&(this.currentLinkIndex===0?s=this.delegate.iframes[0].contentDocument?.getElementById(t):s=this.delegate.iframes[1].contentDocument?.getElementById(t),s&&s.classList.add(n),this.pid=t),s&&(this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&s.scrollIntoView({block:"center",behavior:"smooth"})}};T();var J0=class{static async create(t){let n=new this(t.delegate,t.publication);return await n.start(),n}constructor(t,n){this.delegate=t,this.publication=n}async stop(){K&&console.log("Timeline module stop")}async start(){this.delegate.timelineModule=this,this.timelineContainer=xe(document,"#container-view-timeline"),this.delegate.rights.enableMaterial&&(this.positionSlider=xe(document,"#positionSlider")),this.publication.positions?this.positionSlider&&(this.positionSlider.style.display="block"):this.positionSlider&&(this.positionSlider.style.display="none")}async initialize(){return new Promise(async t=>{await document.fonts.ready;let n=this.delegate.currentLocator();this.delegate.rights.enableMaterial&&(this.delegate.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions)&&(this.positionSlider&&(this.positionSlider.value=(n.locations.position??0).toString()),this.positionSlider&&(this.positionSlider.max=((n.locations.totalRemainingPositions??0)+(n.locations.position??0)).toString())),this.timelineContainer&&(this.timelineContainer.innerHTML=""),this.publication.readingOrder?.forEach(i=>{let o=this.publication.getAbsoluteHref(i.Href),l=this.publication.getTOCItemAbsolute(o),s=l?.Href.indexOf("#")!==-1?l?.Href.slice(0,l?.Href.indexOf("#")):l.Href,a=this.publication.getAbsoluteHref(s??"");var u;this.publication.positions&&this.delegate.view?.layout!=="fixed"?i.contentWeight?u=i.contentWeight:u=1:u=100/(this.publication.readingOrder?.length??0);var h=document.createElement("div");if(h.style.height=u+"%",h.style.width="100%",h.className="chapter",l?.Title!==void 0){var f=document.createElement("span");f.innerHTML=l.Title,f.className="chapter-tooltip",h.appendChild(f)}ve(h,"click",p=>{p.preventDefault(),p.stopPropagation();var g;this.publication.positions||this.delegate.rights.autoGeneratePositions&&this.publication.positions?(g=it({},this.publication.positions.filter(y=>y.href===i.Href)[0]),g.href=this.publication.getAbsoluteHref(g.href)):g={href:a,locations:{progression:0},type:i.TypeLink,title:i.Title},K&&console.log(g),this.delegate.navigate(g)}),a===this.delegate.currentChapterLink.href?h.className+=" active":h.className=h.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(h)}),t()})}};T();var pg=At(Zr());var FO=At(HO()),ao=At(jO()),qd=class{constructor(t,n){this.hasEventListener=!1;this.isHacked=!1;this.delegate=t,this.properties=n}static async setupPreloadProtection(t){if(this.isCurrentBrowserSupported(t))t.detectInspect&&await this.startInspectorProtection(t);else throw new Error("Browser not supported")}static async create(t){let n=new this(t.delegate,t);return await n.start(),n}static async startInspectorProtection(t){let n=()=>{t.clearOnInspect&&(console.clear(),window.localStorage.clear(),window.sessionStorage.clear(),window.location.replace(window.location.origin)),typeof t.api?.inspectDetected=="function"&&t.api.inspectDetected()},i=new ao.DevtoolsDetector({checkers:[ao.checkers.elementIdChecker,ao.checkers.regToStringChecker,ao.checkers.functionToStringChecker,ao.checkers.depRegToStringChecker,ao.checkers.dateToStringChecker]});i.addListener(n),i.launch(),await Ow(t.detectInspectInitDelay??50)}static isCurrentBrowserSupported(t){if(!t.enforceSupportedBrowsers)return!0;let n=[];return(t.supportedBrowsers??[]).forEach(o=>{n.push("last 1 "+o+" version")}),(0,FO.getUserAgentRegExp)({browsers:n,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.delegate.contentProtectionModule=this,this.properties?.enableObfuscation){this.wrapper=St(document,"#iframe-wrapper"),this.securityContainer=xe(document,"#container-view-security");var t=this;this.mutationObserver=new MutationObserver(function(n){n.forEach(function(i){K&&console.log(i.type),t.isHacked=!0})})}}async stop(){if(K&&console.log("Protection module stop"),this.mutationObserver.disconnect(),this.properties?.disableKeys){He(this.delegate.mainElement,"keydown",this.disableSave),He(this.delegate.headerMenu,"keydown",this.disableSave);for(let t of this.delegate.iframes)He(t.contentDocument,"keydown",this.disableSave),He(t.contentWindow,"keydown",this.disableSave);He(window,"keydown",this.disableSave),He(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){He(this.delegate.mainElement,"copy",this.preventCopy),He(this.delegate.headerMenu,"copy",this.preventCopy);for(let t of this.delegate.iframes)He(t.contentDocument,"copy",this.preventCopy),He(t.contentWindow,"copy",this.preventCopy);He(window,"copy",this.preventCopy),He(document,"copy",this.preventCopy),He(this.delegate.mainElement,"cut",this.preventCopy),He(this.delegate.headerMenu,"cut",this.preventCopy);for(let t of this.delegate.iframes)He(t.contentDocument,"cut",this.preventCopy),He(t.contentWindow,"cut",this.preventCopy);He(window,"cut",this.preventCopy),He(document,"cut",this.preventCopy)}if(this.properties?.disablePrint){He(this.delegate.mainElement,"beforeprint",this.beforePrint.bind(this)),He(this.delegate.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let t of this.delegate.iframes)He(t.contentDocument,"beforeprint",this.beforePrint),He(t.contentWindow,"beforeprint",this.beforePrint);He(window,"beforeprint",this.beforePrint),He(document,"beforeprint",this.beforePrint),He(this.delegate.mainElement,"afterprint",this.afterPrint.bind(this)),He(this.delegate.headerMenu,"afterprint",this.afterPrint.bind(this));for(let t of this.delegate.iframes)He(t.contentDocument,"afterprint",this.afterPrint.bind(this)),He(t.contentWindow,"afterprint",this.afterPrint.bind(this));He(window,"afterprint",this.afterPrint.bind(this)),He(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){He(this.delegate.mainElement,"contextmenu",this.disableContext),He(this.delegate.headerMenu,"contextmenu",this.disableContext);for(let t of this.delegate.iframes)He(t.contentDocument,"contextmenu",this.disableContext),He(t.contentWindow,"contextmenu",this.disableContext);He(window,"contextmenu",this.disableContext),He(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),He(this.wrapper,"scroll",this.handleScroll.bind(this))}observe(){if(this.properties?.enableObfuscation){this.securityContainer.hasAttribute("style")&&(this.isHacked=!0),this.mutationObserver.disconnect();var t={attributes:!0,childList:!0,characterData:!0};this.mutationObserver.observe(this.securityContainer,t)}}async deactivate(){this.properties?.enableObfuscation&&(this.observe(),this.rects.forEach(t=>this.deactivateRect(t,this.securityContainer,this.isHacked)))}async activate(){if(this.properties?.enableObfuscation){this.observe();for(let t of this.delegate.iframes)if(t.contentDocument){let n=Sr(t.contentDocument,"body");this.rects=this.findRects(n),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){ve(this.delegate.mainElement,"keydown",this.disableSave),ve(this.delegate.headerMenu,"keydown",this.disableSave);for(let t of this.delegate.iframes)ve(t,"keydown",this.disableSave),ve(t.ownerDocument,"keydown",this.disableSave),ve(t.contentDocument,"keydown",this.disableSave),ve(t.contentWindow,"keydown",this.disableSave),ve(t.contentWindow?.document,"keydown",this.disableSave);ve(window,"keydown",this.disableSave),ve(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){ve(this.delegate.mainElement,"copy",this.preventCopy),ve(this.delegate.headerMenu,"copy",this.preventCopy);for(let t of this.delegate.iframes)ve(t,"copy",this.preventCopy),ve(t.ownerDocument,"copy",this.preventCopy),ve(t.contentDocument,"copy",this.preventCopy),ve(t.contentWindow,"copy",this.preventCopy),ve(t.contentWindow?.document,"copy",this.preventCopy);ve(window,"copy",this.preventCopy),ve(document,"copy",this.preventCopy),ve(this.delegate.mainElement,"cut",this.preventCopy),ve(this.delegate.headerMenu,"cut",this.preventCopy);for(let t of this.delegate.iframes)ve(t,"cut",this.preventCopy),ve(t.ownerDocument,"cut",this.preventCopy),ve(t.contentDocument,"cut",this.preventCopy),ve(t.contentWindow,"cut",this.preventCopy),ve(t.contentWindow?.document,"cut",this.preventCopy);ve(window,"cut",this.preventCopy),ve(document,"cut",this.preventCopy)}if(this.properties?.disablePrint){ve(this.delegate.mainElement,"beforeprint",this.beforePrint),ve(this.delegate.headerMenu,"beforeprint",this.beforePrint);for(let t of this.delegate.iframes)ve(t,"beforeprint",this.beforePrint.bind(this)),ve(t.ownerDocument,"beforeprint",this.beforePrint.bind(this)),ve(t.contentDocument,"beforeprint",this.beforePrint.bind(this)),ve(t.contentWindow,"beforeprint",this.beforePrint.bind(this)),ve(t.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));ve(window,"beforeprint",this.beforePrint.bind(this)),ve(document,"beforeprint",this.beforePrint.bind(this)),ve(this.delegate.mainElement,"afterprint",this.afterPrint),ve(this.delegate.headerMenu,"afterprint",this.afterPrint);for(let t of this.delegate.iframes)ve(t,"afterprint",this.afterPrint.bind(this)),ve(t.ownerDocument,"afterprint",this.afterPrint.bind(this)),ve(t.contentDocument,"afterprint",this.afterPrint.bind(this)),ve(t.contentWindow,"afterprint",this.afterPrint.bind(this)),ve(t.contentWindow?.document,"afterprint",this.afterPrint.bind(this));ve(window,"afterprint",this.afterPrint.bind(this)),ve(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){ve(this.delegate.mainElement,"contextmenu",this.disableContext),ve(this.delegate.headerMenu,"contextmenu",this.disableContext);for(let t of this.delegate.iframes)ve(t,"contextmenu",this.disableContext),ve(t.ownerDocument,"contextmenu",this.disableContext),ve(t.contentDocument,"contextmenu",this.disableContext),ve(t.contentWindow,"contextmenu",this.disableContext),ve(t.contentWindow?.document,"contextmenu",this.disableContext);ve(window,"contextmenu",this.disableContext),ve(document,"contextmenu",this.disableContext)}}initializeResource(){this.properties?.hideTargetUrl&&this.hideTargetUrls(!0),this.properties?.disableDrag&&this.preventDrag(!0)}async initialize(){if(this.properties?.enableObfuscation)return new Promise(async t=>{await document.fonts.ready;for(let n of this.delegate.iframes)if(n.contentDocument){let i=Sr(n.contentDocument,"body");this.observe(),setTimeout(()=>{this.rects=this.findRects(i),this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),this.setupEvents(),this.hasEventListener||(this.hasEventListener=!0,ve(this.wrapper,"scroll",this.handleScroll.bind(this))),t()},10)}})}handleScroll(){this.rects.forEach(t=>this.toggleRect(t,this.securityContainer,this.isHacked))}handleResize(){if(this.properties?.enableObfuscation){let t=(0,pg.debounce)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(n=>this.toggleRect(n,this.securityContainer,this.isHacked))},10);this.rects&&(this.observe(),t())}}disableContext(t){return t.preventDefault(),t.stopPropagation(),!1}disableSave(t){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?t.metaKey:t.ctrlKey&&(t.key==="s"||t.keyCode===83))?(t.preventDefault(),t.stopPropagation(),!1):!0}preventCopy(t){return K&&console.log("copy action initiated"),t.clipboardData.setData("text/plain","copy not allowed"),t.stopPropagation(),t.preventDefault(),!1}beforePrint(t){return K&&console.log("before print"),this.delegate&&this.delegate.headerMenu&&(this.delegate.headerMenu.style.display="none",this.delegate.mainElement.style.display="none"),t.stopPropagation(),t.preventDefault(),!1}afterPrint(t){return K&&console.log("after print"),this.delegate&&this.delegate.headerMenu&&(this.delegate.headerMenu.style.removeProperty("display"),this.delegate.mainElement.style.removeProperty("display")),t.stopPropagation(),t.preventDefault(),!1}hideTargetUrls(t){function n(i){i.preventDefault();let o=i.currentTarget.getAttribute("data-href-resolved"),l=document.createElement("a");l.setAttribute("href",o),l.click()}for(let i of this.delegate.iframes){let o=i.contentDocument?.querySelectorAll("a");o?.forEach(l=>{let s=l.getAttribute("data-href"),a=l.getAttribute("href");!s&&a&&(l.setAttribute("data-href",a),l.setAttribute("data-href-resolved",l.href))}),t?o?.forEach(l=>{l.setAttribute("href",""),l.addEventListener("click",n)}):o?.forEach(l=>{let s=l.getAttribute("data-href");s&&l.setAttribute("href",s),l.removeEventListener("click",n)})}}preventDrag(t){let n="-webkit-user-drag: none; -khtml-user-drag: none; -moz-user-drag: none; -ms-user-drag: none; user-drag: none; -webkit-pointer-events: none; -khtml-pointer-events: none; -moz-pointer-events: none; -ms-pointer-events: none; pointer-events: none;",i=o=>{o.preventDefault()};for(let o of this.delegate.iframes){let l=o.contentDocument?.body.getAttribute("style")||"";t?(o.contentDocument?.body.addEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",l+n)):(o.contentDocument?.body.removeEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",l.replace(n,"")))}}recalculate(t=0){return new Promise(n=>{if(this.properties?.enableObfuscation){let i=(0,pg.debounce)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),n(!0)},t);this.rects?(this.observe(),i()):n(!1)}else n(!1)})}calcRects(t){t!==void 0&&t.forEach(n=>{try{let{top:i,height:o,left:l,width:s}=this.measureTextNode(n.node);n.top=i,n.height=o,n.width=s,n.left=l}catch(i){K&&(console.log("error "+i),console.log(n),console.log(n.node),console.log("scrambledTextContent "+n.scrambledTextContent),console.log("textContent "+n.textContent),console.log("isObfuscated "+n.isObfuscated))}})}deactivateRect(t,n,i){this.isBeingHacked(n)||i?(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0):(t.node.textContent=t.textContent,t.isObfuscated=!1)}toggleRect(t,n,i){let o=this.isOutsideViewport(t),l=this.isBeingHacked(n);t.isObfuscated&&!o&&!l&&!i&&(t.node.textContent=t.textContent,t.isObfuscated=!1),!t.isObfuscated&&(o||l||i)&&(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0)}findRects(t){return this.findTextNodes(t).map(i=>{let{top:o,height:l,left:s,width:a}=this.measureTextNode(i),u=i.parentElement?.nodeName==="option"||i.parentElement?.nodeName==="script"?i.textContent:this.obfuscateText(i.textContent??"");return{top:o,height:l,width:a,left:s,node:i,textContent:i.textContent??"",scrambledTextContent:u??"",isObfuscated:!1}})}obfuscateText(t){return this.scramble(t,!0)}measureTextNode(t){try{let n=document.createRange();n.selectNode(t);let i=n.getBoundingClientRect();return n.detach(),i}catch(n){K&&(console.log("measureTextNode "+n),console.log("measureTextNode "+t),console.log(t.textContent))}}isBeingHacked(t){return t.style.animation||t.style.transition||t.style.position||t.hasAttribute("style")?(K&&console.log("content being hacked"),!0):!1}isOutsideViewport(t){let n=this.wrapper.scrollLeft,i=n+this.wrapper.clientWidth,o=t.left+t.width,l=t.top+t.height,s=this.wrapper.scrollTop,a=s+this.wrapper.clientHeight,u=l<s,h=t.top>a,f=o<n-window.innerWidth,p=t.left>i+window.innerWidth;return u||h||f||p}findTextNodes(t,n=[]){let i=t.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,n),i.nodeType===3&&i.textContent?.trim()&&n.push(i),i=i.nextSibling;return n}scramble(t,n=!1,i=!1){var o=t.split(" ");function l(s){for(var a=s.length,u,h;a>0;)h=Math.floor(Math.random()*a),a--,u=s[a],s[a]=s[h],s[h]=u;return s}return n&&(o=o.map(function(s){return l(s.split("")).join("")})),i?l(o).join(" "):o.join(" ")}};T();var zO=At($O());T();var zd=r=>r.replace(/\n/g," ").replace(/\s\s+/g," "),KN=r=>zd(r).trim(),UO=/[\\^$.*+?()[\]{}|]/g,YN=RegExp(UO.source);function WO(r){return r&&YN.test(r)?r.replace(UO,"\\$&"):r||""}var Vd=0,XN=()=>()=>Number.isSafeInteger(++Vd)?Vd:Vd=1,qO=()=>{Vd=0},ZN=XN(),QN=r=>t=>{try{return Dn(t,r,no)}catch(n){return console.error("uniqueCssSelector:",n),""}};async function Js(r,t,n,i,o=!1){if(!t)return[];let l=t.body?.textContent;if(!l)return[];if(r=KN(r),!r.length)return[];let s=t.createNodeIterator(t.body,NodeFilter.SHOW_TEXT,{acceptNode:y=>NodeFilter.FILTER_ACCEPT}),a=new RegExp(WO(r).replace(/ /g,"\\s+"),"gim");o&&(a=new RegExp("\\b"+WO(r).replace(/ /g,"\\s+")+"\\b","gim"));let u=[],h=100,f=30,p=0,g;for(;g=a.exec(l);){let y=Math.max(0,g.index-h),E=Math.min(h,g.index),b=zd(l.substr(y,E));b=b.substr(b.length-f),y=a.lastIndex,E=Math.min(h,l.length-y);let w=zd(l.substr(y,E)).substr(0,f),_=new Range,S=g.index;for(;p<=S;){let C=s.nextNode();C&&C.nodeValue&&(p+=C.nodeValue.length)}let x=s.referenceNode.nodeValue?s.referenceNode.nodeValue?.length-(p-S):0;for(_.setStart(s.referenceNode,x),S=g.index+g[0].length;p<=S;){let I=s.nextNode()?.nodeValue;I&&(p+=I.length)}x=s.referenceNode.nodeValue?s.referenceNode.nodeValue?.length-(p-S):0,_.setEnd(s.referenceNode,x),t.getCssSelector||(t.getCssSelector=QN(t));let R=Mr(_,t.getCssSelector);R&&u.push({textMatch:zd(g[0]),textBefore:b,textAfter:w,rangeInfo:R,href:n,title:i,uuid:ZN().toString()})}return u}var mg=class{constructor(t,n,i,o,l,s){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.delegate=t,this.headerMenu=s,this.publication=n,this.properties=i,this.api=l,this.highlighter=o}static async create(t){let n=new this(t.delegate,t.publication,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){K&&console.log("Search module stop"),He(this.searchInput,"keypress",this.handleSearch.bind(this)),He(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.delegate.searchModule=this,this.headerMenu){this.searchInput=xe(this.headerMenu,"#searchInput"),ve(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=xe(this.headerMenu,"#searchGo"),ve(this.searchGo,"click",this.handleSearch.bind(this));var t=xe(this.headerMenu,"#menu-button-search");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("search"):this.delegate.showLayer("search")},10)}async handleSearch(t){(t.key==="Enter"||t.type==="click")&&(await this.handleSearchChapter(),await this.handleSearchBook())}async handleSearchChapter(t){var n=this,i=this.searchInput.value;let o=this.delegate.currentChapterLink.href,l=this.publication.getSpineItem(o);if(this.headerMenu)var s=xe(this.headerMenu,"#searchResultChapter");n.currentChapterSearchResult=[],n.currentSearchHighlights=[];var a=[];this.delegate.rights.enableContentProtection&&this.delegate.contentProtectionModule?.deactivate(),await this.searchAndPaintChapter(i,t,async h=>{a=h,u(1),this.delegate.rights.enableContentProtection&&this.delegate.contentProtectionModule?.recalculate(200)});async function u(h){s.innerHTML="";var f;if(f=n.paginate(a,h,5),f.total===0){let p=document.createElement("a");p.className="collection-item",p.innerHTML="nothing found",s.appendChild(p)}else{for(let b=0;b<f.data.length;b++){let w=document.createElement("a"),_=f.data[b];w.className="collection-item",w.href=l?.Href??"",w.innerHTML="..."+_.textBefore+"<mark>"+_.textMatch+"</mark>"+_.textAfter+"...",ve(w,"click",S=>{S.preventDefault(),S.stopPropagation(),n.jumpToMark(b+h*5-5)}),s.appendChild(w)}let p=document.createElement("div");p.style.textAlign="center",p.style.marginTop="10px";let g=document.createElement("ul");g.className="pagination";let y=document.createElement("li");if(y.className="disabled",y.innerHTML='<a href="#!">left</a>',f.pre_page!==void 0){let b=f.pre_page;y.className="waves-effect",ve(y,"click",w=>{w.preventDefault(),w.stopPropagation(),u(b)})}g.appendChild(y);for(let b=1;b<=f.total_pages;b++){let w,_=document.createElement("li");_.className="waves-effect",b===f.page&&(_.className="active",w=_),_.innerHTML='<a href="#!">'+b+"</a>",ve(_,"click",S=>{S.preventDefault(),S.stopPropagation(),w&&(w.className="waves-effect"),_.className="active",w=_,u(b)}),g.appendChild(_)}let E=document.createElement("li");if(E.className="disabled",E.innerHTML='<a href="#!">right</a>',f.next_page!==void 0){let b=f.next_page;E.className="waves-effect",ve(E,"click",w=>{w.preventDefault(),w.stopPropagation(),u(b)})}g.appendChild(E),p.appendChild(g),s.appendChild(p)}}}async searchAndPaintChapter(t,n=0,i){let o=this.publication.getAbsoluteHref(this.publication.readingOrder[this.delegate.currentResource()??0].Href),l=this.publication.getTOCItem(o);l===null&&(l=this.publication.readingOrder[this.delegate.currentResource()??0]);let s=[];this.highlighter?.destroyHighlights(nt.Search),this.delegate.rights.enableSearch&&this.drawSearch();let a=0;if(l){let u=this.publication.getAbsoluteHref(l.Href),h=this.delegate.iframes[0].contentDocument;h&&await fetch(u).then(f=>f.text()).then(async f=>{l&&Js(t,h,l.Href,l.Title).then(p=>{p.forEach(g=>{let y={rangeInfo:g.rangeInfo};setTimeout(()=>{let E;a===n?(E=this.createSearchHighlight(y,this.properties?.current),this.jumpToMark(n)):E=this.createSearchHighlight(y,this.properties?.color),g.highlight=E,s.push(g),this.currentChapterSearchResult.push(g),this.currentSearchHighlights.push(E),a++},500)}),setTimeout(()=>{i(s)},500)})})}}createSearchHighlight(t,n){try{var i=n;Ge.isHexColor(i)&&(i=Ge.hexToRgbChannels(i));let l=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,s=zO.SHA256.hash(l),a="R2_SEARCH_"+s;var o=!1;let u={color:i||jo,id:a,pointerInteraction:o,selectionInfo:t,marker:ot.Highlight,type:nt.Search},h=this.highlighter?.createHighlightDom(this.delegate.iframes[0].contentWindow,u);return u.position=parseInt((h?.hasChildNodes()?h.childNodes[0]:h).style.top.replace("px","")),u}catch(l){throw"Can't create highlight: "+l}}clearSearch(){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.highlighter?.destroyHighlights(nt.Search)}async search(t,n){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],qO(),this.searchAndPaintChapter(t,0,async()=>{});var i=this.searchChapter(t),o=this.searchBook(t);return n?i:o}async goToSearchID(t,n,i){var o=n,l;let s=this.delegate.currentChapterLink.href;var a=this.publication.getAbsoluteHref(t);let u=this.bookSearchResult.filter(h=>h.href===t);if(i?(l=this.currentChapterSearchResult.filter(h=>h.uuid==n)[0],o=this.currentChapterSearchResult.findIndex(h=>h.uuid==n)):(l=u.filter(h=>h.uuid==n)[0],o=u.findIndex(h=>h.uuid==n)),l!==void 0)if(s===a)this.jumpToMark(o);else{let f={href:a,locations:{progression:0},title:"title"};this.delegate.navigate(f),setTimeout(()=>{this.searchAndPaintChapter(l.textMatch,o,async()=>{})},300)}}async goToSearchIndex(t,n,i){var o=n,l;let s=this.delegate.currentChapterLink.href;var a=this.publication.getAbsoluteHref(t);let u=this.bookSearchResult.filter(h=>h.href===t);if(i?l=this.currentChapterSearchResult[o]:l=u[o],l!==void 0)if(s===a)this.jumpToMark(o);else{let f={href:a,locations:{progression:0},title:"title"};this.delegate.navigate(f),setTimeout(()=>{this.searchAndPaintChapter(l.textMatch,o,async()=>{})},300)}}async handleSearchBook(){var t=this,n=this.searchInput.value;if(t.headerMenu)var i=xe(t.headerMenu,"#searchResultBook");o(1);async function o(s){i.innerHTML="";var a,u=await t.searchBook(n);if(a=t.paginate(u,s,5),a.total===0){let h=document.createElement("a");h.className="collection-item",h.innerHTML="nothing found",i.appendChild(h)}else{l(a.data,E=>E.href).forEach(E=>{let b=document.createElement("div");if(b.style.marginBottom="10px",E[0].title){let w=document.createElement("span");w.className="collection-item",w.style.display="block",w.innerHTML=E[0].title,b.appendChild(w)}i.appendChild(b),E.forEach(w=>{let _=document.createElement("a");_.className="collection-item";var S=t.publication.getAbsoluteHref(w.href);_.innerHTML="..."+w.textBefore+"<mark>"+w.textMatch+"</mark>"+w.textAfter+"...",ve(_,"click",x=>{x.preventDefault(),x.stopPropagation();let C=u.filter(z=>z.href===w.href).findIndex(z=>z===w);if(t.delegate.currentChapterLink.href===S)t.jumpToMark(C);else{let N={href:S,locations:{progression:0},title:"title"};t.delegate.navigate(N),setTimeout(()=>{t.handleSearchChapter(C)},300)}}),b.appendChild(_)})});let f=document.createElement("div");f.style.textAlign="center",f.style.marginTop="10px";let p=document.createElement("ul");p.className="pagination";let g=document.createElement("li");if(g.className="disabled",g.innerHTML='<a href="#!">left</a>',a.pre_page!=null){let E=a.pre_page;g.className="waves-effect",ve(g,"click",b=>{b.preventDefault(),b.stopPropagation(),o(E)})}p.appendChild(g);for(let E=1;E<=a.total_pages;E++){let b,w=document.createElement("li");w.className="waves-effect",E===a.page&&(w.className="active",b=w),w.innerHTML='<a href="#!">'+E+"</a>",ve(w,"click",_=>{_.preventDefault(),_.stopPropagation(),b&&(b.className="waves-effect"),w.className="active",b=w,o(E)}),p.appendChild(w)}let y=document.createElement("li");if(y.className="disabled",y.innerHTML='<a href="#!">right</a>',a.next_page!=null){let E=a.next_page;y.className="waves-effect",ve(y,"click",b=>{b.preventDefault(),b.stopPropagation(),o(E)})}p.appendChild(y),f.appendChild(p),i.appendChild(f)}}function l(s,a){let u=new Map;return s.forEach(h=>{let f=a(h),p=u.get(f);p?p.push(h):u.set(f,[h])}),Array.from(u.values())}}async searchBook(t){this.bookSearchResult=[];let n=[];for(let i=0;i<this.publication.readingOrder.length;i++){let o=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[i].Href:""),l=this.publication.getTOCItem(o);if(l===void 0&&this.publication.readingOrder&&(l=this.publication.readingOrder[i]),l){let s=this.publication.getAbsoluteHref(l.Href);await fetch(s).then(a=>a.text()).then(async a=>{let h=new DOMParser().parseFromString(a,"application/xhtml+xml");l&&Js(t,h,l.Href,l.Title).then(f=>{f.forEach(p=>{n.push(p),this.bookSearchResult.push(p)})})})}if(i===this.publication.readingOrder.length-1)return n}}async searchChapter(t){let n=[],i=this.publication.getAbsoluteHref(this.publication.readingOrder[this.delegate.currentResource()??0].Href),o=this.publication.getTOCItem(i);if(o===null&&(o=this.publication.readingOrder[this.delegate.currentResource()??0]),o){let l=this.publication.getAbsoluteHref(o.Href);await fetch(l).then(s=>s.text()).then(async s=>{let u=new DOMParser().parseFromString(s,"application/xhtml+xml");o&&Js(t,u,o.Href,o.Title).then(h=>{h.forEach(f=>{n.push(f)})})})}return n}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(t=>{let n={rangeInfo:t.rangeInfo};if(this.properties?.color){let i=this.createSearchHighlight(n,this.properties?.color);t.highlight=i,this.currentSearchHighlights.push(i)}})},100)}async handleResize(){await this.highlighter?.destroyHighlights(nt.Search),this.drawSearch()}jumpToMark(t){setTimeout(()=>{if(this.currentChapterSearchResult.length){var n=this.currentChapterSearchResult[t];this.currentSearchHighlights.forEach(o=>{var l=this.properties?.color;Ge.isHexColor(l)&&(l=Ge.hexToRgbChannels(l)),o.color=l});var i=this.properties?.current;Ge.isHexColor(i)&&(i=Ge.hexToRgbChannels(i)),n.highlight.color=i,this.highlighter?.setAndResetSearchHighlight(n.highlight,this.currentSearchHighlights),this.delegate.view?.goToCssSelector(n.rangeInfo.startContainerElementCssSelector),this.delegate.updatePositionInfo()}},200)}paginate(t,n,i){let o=n||1,l=i||10,s=(o-1)*l,a=t.slice(s).slice(0,l),u=Math.ceil(t.length/l);return{page:o,per_page:l,pre_page:o-1?o-1:void 0,next_page:u>o?o+1:void 0,total:t.length,total_pages:u,data:a}}};T();var lo=class{},qe=lo;qe.COLOR_REF="color",qe.AUTO_SCROLL_REF="autoscroll",qe.RATE_REF="rate",qe.PITCH_REF="pitch",qe.VOLUME_REF="volume",qe.VOICE_REF="voice",qe.COLOR_KEY="tts-"+lo.COLOR_REF,qe.AUTO_SCROLL_KEY="tts-"+lo.AUTO_SCROLL_REF,qe.RATE_KEY="tts-"+lo.RATE_REF,qe.PITCH_KEY="tts-"+lo.PITCH_REF,qe.VOLUME_KEY="tts-"+lo.VOLUME_REF,qe.VOICE_KEY="tts-"+lo.VOICE_REF;var vg=class{constructor(t,n,i){this.TTSSETTINGS="ttsSetting";this.color="orange";this.autoScroll=!0;this.rate=1;this.pitch=1;this.volume=1;this.voice={usePublication:!0};this.settingsChangeCallback=()=>{};this.restartCallback=()=>{};this.store=t,this.api=n,this.headerMenu=i,this.initialise()}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialTTSSettings){let i=t.initialTTSSettings;i?.rate&&(n.rate=i.rate,K&&console.log(n.rate)),i?.pitch&&(n.pitch=i.pitch,K&&console.log(n.pitch)),i?.volume&&(n.volume=i.volume,K&&console.log(n.volume)),i?.color&&(n.color=i.color,K&&console.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,K&&console.log(n.autoScroll)),i?.voice&&(n.voice=i.voice,K&&console.log(n.voice))}return n.initializeSelections(),n}stop(){K&&console.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(qe.AUTO_SCROLL_KEY)!=null?this.getProperty(qe.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(qe.RATE_KEY)!=null?this.getProperty(qe.RATE_KEY).value:this.rate,this.pitch=this.getProperty(qe.PITCH_KEY)!=null?this.getProperty(qe.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(qe.VOLUME_KEY)!=null?this.getProperty(qe.VOLUME_KEY).value:this.volume,this.color=this.getProperty(qe.COLOR_KEY)!=null?this.getProperty(qe.COLOR_KEY).value:this.color,this.voice=this.getProperty(qe.VOICE_REF)!=null?this.getProperty(qe.VOICE_REF).value:this.voice,this.userProperties=this.getTTSSettings()}reset(){this.color="orange",this.autoScroll=!0,this.rate=1,this.pitch=1,this.volume=1,this.voice={usePublication:!0},this.userProperties=this.getTTSSettings()}initializeSelections(){this.headerMenu&&(this.settingsView=xe(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechRate=xe(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=xe(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=xe(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=xe(this.headerMenu,"#autoScroll")),this.speechRate&&(this.speechRate.value=this.rate.toString()),this.speechPitch&&(this.speechPitch.value=this.pitch.toString()),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),ve(xe(t,"ul"),"click",n=>{n.stopPropagation()})}onSettingsChange(t){this.settingsChangeCallback=t}onRestart(t){this.restartCallback=t}storeProperty(t){this.updateUserSettings(),this.saveProperty(t)}updateUserSettings(){var t={rate:this.userProperties.getByRef(qe.RATE_REF)?.value,pitch:this.userProperties.getByRef(qe.PITCH_REF)?.value,volume:this.userProperties.getByRef(qe.VOLUME_REF)?.value,voice:this.userProperties.getByRef(qe.VOLUME_REF)?.value,color:this.userProperties.getByRef(qe.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(qe.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{K&&console.log("api updated tts settings",n)})}getTTSSettings(){var t=new _r;return t.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,qe.AUTO_SCROLL_REF,qe.AUTO_SCROLL_KEY),t.addIncremental(this.rate,.1,10,.1,"",qe.RATE_REF,qe.RATE_KEY),t.addIncremental(this.pitch,.1,2,.1,"",qe.PITCH_REF,qe.PITCH_KEY),t.addIncremental(this.volume,.1,1,.1,"",qe.VOLUME_REF,qe.VOLUME_KEY),t.addStringable(this.color,qe.COLOR_REF,qe.COLOR_KEY),t.addJSONable(JSON.stringify(this.voice),qe.VOICE_REF,qe.VOICE_KEY),t}saveProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}return t}getProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?void 0:i[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(t){if(t.rate){K&&console.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(qe.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.pitch){K&&console.log("pitch "+this.pitch),this.pitch=t.pitch;let n=this.userProperties.getByRef(qe.PITCH_REF);n&&(n.value=this.pitch,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.volume){K&&console.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(qe.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.color){this.color=t.color;let n=this.userProperties.getByRef(qe.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){K&&console.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(qe.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.voice){K&&console.log("voice "+this.voice),this.voice=t.voice;let n=this.userProperties.getByRef(qe.VOICE_REF);n&&(n.value=this.voice,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}}applyPreferredVoice(t){var n=t.indexOf(":")!==-1?t.slice(0,t.indexOf(":")):void 0,i=t.indexOf(":")!==-1?t.slice(t.indexOf(":")+1):t;n!==void 0&&i!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:n,lang:i}}):i!==void 0&&n===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:i}})}increase(t){if(t==="rate"){this.userProperties.getByRef(qe.RATE_REF).increment();let n=this.userProperties.getByRef(qe.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(qe.PITCH_REF).increment();let n=this.userProperties.getByRef(qe.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(qe.VOLUME_REF).increment();let n=this.userProperties.getByRef(qe.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}decrease(t){if(t==="rate"){this.userProperties.getByRef(qe.RATE_REF).decrement();let n=this.userProperties.getByRef(qe.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(qe.PITCH_REF).decrement();let n=this.userProperties.getByRef(qe.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(qe.VOLUME_REF).decrement();let n=this.userProperties.getByRef(qe.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}};T();T();var VO=(r,t,n)=>`
77
+ </svg>`,$i={error:Yn("error-icon","Warning",'<path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>'),home:'<path d="M12 5.69l5 4.5V18h-2v-6H9v6H7v-7.81l5-4.5M12 3L2 12h3v8h6v-6h2v6h6v-8h3L12 3z"/>',expand:Yn("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:gN("loading-icon","Loading",'<path fill="#BBBBBB" d="M145,241.6c-53.3,0-96.6-43.2-96.6-96.6c0-53.3,43.2-96.6,96.6-96.6c53.3,0,96.6,43.2,96.6,96.6 c0,26.7-10.8,50.9-28.3,68.3l7.6,7.6c19.4-19.4,31.5-46.3,31.5-75.9c0-59.3-48-107.3-107.3-107.3S37.7,85.7,37.7,145 c0,59.3,48,107.3,107.3,107.3V241.6z"/>',"0 0 290 290"),next:Yn("next-icon","Next Chapter",'<path d="M6.49 20.13l1.77 1.77 9.9-9.9-9.9-9.9-1.77 1.77L14.62 12l-8.13 8.13z"/>'),previous:Yn("previous-icon","Previous Chapter",'<path d="M17.51 3.87L15.73 2.1 5.84 12l9.9 9.9 1.77-1.77L9.38 12l8.13-8.13z"/>'),settings:Yn("settings-icon","Settings",'<path d="M19.43 12.98c.04-.32.07-.64.07-.98 0-.34-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.09-.16-.26-.25-.44-.25-.06 0-.12.01-.17.03l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.06-.02-.12-.03-.18-.03-.17 0-.34.09-.43.25l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98 0 .33.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.09.16.26.25.44.25.06 0 .12-.01.17-.03l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.06.02.12.03.18.03.17 0 .34-.09.43-.25l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zm-1.98-1.71c.04.31.05.52.05.73 0 .21-.02.43-.05.73l-.14 1.13.89.7 1.08.84-.7 1.21-1.27-.51-1.04-.42-.9.68c-.43.32-.84.56-1.25.73l-1.06.43-.16 1.13-.2 1.35h-1.4l-.19-1.35-.16-1.13-1.06-.43c-.43-.18-.83-.41-1.23-.71l-.91-.7-1.06.43-1.27.51-.7-1.21 1.08-.84.89-.7-.14-1.13c-.03-.31-.05-.54-.05-.74s.02-.43.05-.73l.14-1.13-.89-.7-1.08-.84.7-1.21 1.27.51 1.04.42.9-.68c.43-.32.84-.56 1.25-.73l1.06-.43.16-1.13.2-1.35h1.39l.19 1.35.16 1.13 1.06.43c.43.18.83.41 1.23.71l.91.7 1.06-.43 1.27-.51.7 1.21-1.07.85-.89.7.14 1.13zM12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>',"icon open"),toc:Yn("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:Yn("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:Yn("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:Yn("delete-icon","Delete",'<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>',"icon open"),close:Yn("close-icon","Close",'<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>',"icon open"),text:Yn("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:Yn("speak-icon","Speak",'<circle cx="9" cy="9" r="4"/><path d="M9 15c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4zm7.76-9.64l-1.68 1.69c.84 1.18.84 2.71 0 3.89l1.68 1.69c2.02-2.02 2.02-5.07 0-7.27zM20.07 2l-1.63 1.63c2.77 3.02 2.77 7.56 0 10.74L20.07 16c3.9-3.89 3.91-9.95 0-14z"/><path d="M0 0h24v24H0z" fill="none"/>',"icon open"),note:Yn("note-icon","Note",'<polygon points="17.71 24.66 22.3 20.07 17.71 20.07 17.71 24.66" fill="none"/><path d="M22.42.07H5.58A3.28,3.28,0,0,0,2.29,3.35V24.79a3.28,3.28,0,0,0,3.29,3.28H16.71a1,1,0,0,0,.71-.29l8-8a1,1,0,0,0,.29-.71V3.35A3.28,3.28,0,0,0,22.42.07Zm-8.17,15h-7v-2h7Zm-7-6v-2h13v2ZM16.5,25.86v-6a1,1,0,0,1,1-1h6Z" />',"icon open"),highlight:Yn("highlight-icon","Highlight",'<path d="M27.71,7.78,21.12,1.19a1,1,0,0,0-1.38,0L4.32,15A1,1,0,0,0,4,15.7a1,1,0,0,0,.3.73c1.22,1.22,1.2,2.37,0,3.62a1,1,0,0,0,0,1.41l3.2,3.2a1,1,0,0,0,1.41,0c1.28-1.28,2.36-1.29,3.62,0a1,1,0,0,0,1.45,0L27.74,9.16A1,1,0,0,0,27.71,7.78Z" /><path d="M3.09,22.59l-2.8,2.8a1,1,0,0,0-.21,1.09A1,1,0,0,0,1,27.1H4.6a1,1,0,0,0,.71-.29l1-1Z" />',"icon open")};var M0=At(Cd());var Ue;(function(a){a.R2_ID_HIGHLIGHTS_CONTAINER="R2_ID_HIGHLIGHTS_CONTAINER",a.R2_ID_BOOKMAKRS_CONTAINER="R2_ID_BOOKMAKRS_CONTAINER",a.R2_ID_READALOUD_CONTAINER="R2_ID_READALOUD_CONTAINER",a.R2_ID_PAGEBREAK_CONTAINER="R2_ID_PAGEBREAK_CONTAINER",a.R2_ID_SEARCH_CONTAINER="R2_ID_SEARCH_CONTAINER",a.R2_ID_DEFINITIONS_CONTAINER="R2_ID_DEFINITIONS_CONTAINER",a.R2_ID_LINEFOCUS_CONTAINER="R2_ID_LINEFOCUS_CONTAINER"})(Ue||(Ue={}));var J_="R2_CLASS_HIGHLIGHT_CONTAINER",Za="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",pi="R2_CLASS_HIGHLIGHT_AREA",Qa="R2_CLASS_HIGHLIGHT_ICON",rr=.5,K_=.75,jo={blue:100,green:50,red:230},Yt=[],mN="data-highlighted",vN="data-timestamp",Ws={ELEMENT_NODE:1,TEXT_NODE:3},to=[Ue.R2_ID_HIGHLIGHTS_CONTAINER,Ue.R2_ID_PAGEBREAK_CONTAINER,Ue.R2_ID_SEARCH_CONTAINER,Ue.R2_ID_READALOUD_CONTAINER,Ue.R2_ID_BOOKMAKRS_CONTAINER,Ue.R2_ID_DEFINITIONS_CONTAINER,Ue.R2_ID_LINEFOCUS_CONTAINER,J_,pi,Za],R0=-1,k0=-1,Ge=class{constructor(t,n,i,o,l,s){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,Td.debounce)(()=>{this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen(),this.delegate.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,Td.debounce)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.delegate.emit("toolbox.closed","closed"))},100);this.selection=(0,Td.debounce)((t,n)=>{this.api?.selection&&this.api?.selection(t,n)},100);this.getScrollingElement=t=>t?.scrollingElement?t?.scrollingElement:t?.body?t?.body:document.createElement("body");this.delegate=t,this.layerSettings=n,this.properties=i,this.api=s,this.hasEventListener=o,this.options=this.defaults(l,{color:"#fce300",highlightedClass:"highlighted",contextClass:"highlighter-context",onBeforeHighlight:function(){return!0},onAfterHighlight:function(){}}),this.delegate.highlighter=this}static async create(t){let n=new this(t.delegate,t.layerSettings,t,!1,{},t.api);return new Promise(i=>i(n))}async initialize(){let t=this.delegate.iframes[0].contentDocument;t&&this.dom(t.body).addClass(this.options.contextClass),this.bindEvents(this.delegate.iframes[0].contentDocument?.body,this,this.hasEventListener),this.initializeToolbox(),R0=-1,k0=-1;let n=this;async function i(){n.lastSelectedHighlight===void 0||(n.lastSelectedHighlight=void 0)}setTimeout(async()=>{let o=this.delegate.iframes[0].contentDocument;o&&await o.body?.addEventListener("click",i)},100)}haveSameColor(t,n){return this.dom(t).color()===this.dom(n).color()}defaults(t,n){t=t||{};for(let i in n)n.hasOwnProperty(i)&&t[i]===void 0&&(t[i]=n[i]);return t}unique(t){return t.filter(function(n,i,o){return o.indexOf(n)===i})}refineRangeBoundaries(t){let n=t.startContainer,i=t.endContainer,o=t.commonAncestorContainer,l=!0;if(t.endOffset===0){for(;!i.previousSibling&&i.parentNode!==o;)i=i.parentNode;i=i.previousSibling}else i.nodeType===Ws.TEXT_NODE?t.endOffset<i.nodeValue.length&&i.splitText(t.endOffset):t.endOffset>0&&(i=i.childNodes.item(t.endOffset-1));return n.nodeType===Ws.TEXT_NODE?t.startOffset===n.nodeValue.length?l=!1:t.startOffset>0&&(n=n.splitText(t.startOffset),i===n.previousSibling&&(i=n)):t.startOffset<n.childNodes.length?n=n.childNodes.item(t.startOffset):n=n.nextSibling,{startContainer:n,endContainer:i,goDeeper:l}}sortByDepth(t,n){let i=this;t.sort(function(o,l){return i.dom(n?l:o).parents().length-i.dom(n?o:l).parents().length})}groupHighlights(t){let n=[],i={},o=[];return t.forEach(function(l){let s=l.getAttribute(vN);typeof i[s]=="undefined"&&(i[s]=[],n.push(s)),i[s].push(l)}),n.forEach(function(l){let s=i[l];o.push({chunks:s,timestamp:l,toString:function(){return s.map(function(a){return a.textContent}).join("")}})}),o}dom(t){let n=this;return{addClass:function(i){t.classList?t.classList.add(i):t.className+=" "+i},removeClass:function(i){t.classList?t.classList.remove(i):t.className=t.className.replace(new RegExp("(^|\\b)"+i+"(\\b|$)","gi")," ")},prepend:function(i){let o=Array.prototype.slice.call(i),l=o.length;for(;l--;)t.insertBefore(o[l],t.firstChild)},append:function(i){let o=Array.prototype.slice.call(i);for(let l=0,s=o.length;l<s;++l)t.appendChild(o[l])},insertAfter:function(i){return i.parentNode?.insertBefore(t,i.nextSibling)},insertBefore:function(i){return i.parentNode?.insertBefore(t,i)},remove:function(){t.parentNode.removeChild(t),t=null},contains:function(i){return t!==i&&t.contains(i)},wrap:function(i){return t.parentNode&&t.parentNode.insertBefore(i,t),i.appendChild(t),i},unwrap:function(){let i=Array.prototype.slice.call(t.childNodes),o;return i.forEach(function(l){o=l.parentNode,n.dom(l).insertBefore(l.parentNode),n.dom(o).remove()}),i},parents:function(){let i,o=[];for(;i=t.parentNode;)o.push(i),t=i;return o},normalizeTextNodes:function(){if(!!t){if(t.nodeType===Ws.TEXT_NODE)for(;t.nextSibling&&t.nextSibling.nodeType===Ws.TEXT_NODE;)t.nodeValue+=t.nextSibling.nodeValue,t.parentNode.removeChild(t.nextSibling);else n.dom(t.firstChild).normalizeTextNodes();n.dom(t.nextSibling).normalizeTextNodes()}},color:function(){return t.style.backgroundColor},fromHTML:function(i){let o=document.createElement("div");return o.innerHTML=i,o.childNodes},getRange:function(){let i=n.dom(t)?.getSelection(),o;return i?.rangeCount>0&&(o=i?.getRangeAt(0)),o},removeAllRanges:function(){n.dom(t)?.getSelection()?.removeAllRanges(),n.toolboxHide()},getSelection:function(){return n.dom(t).getWindow()?.getSelection()},getWindow:function(){return n.dom(t).getDocument()?.defaultView},getDocument:function(){return t?.ownerDocument||t}}}disableContext(t){return t.preventDefault(),t.stopPropagation(),!1}bindEvents(t,n,i){let o=t.ownerDocument;o.addEventListener("keyup",this.toolboxShowDelayed.bind(this)),t.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),o.addEventListener("selectstart",this.toolboxShowDelayed.bind(this)),i||window.addEventListener("resize",this.toolboxPlacement.bind(this)),o.addEventListener("selectionchange",this.toolboxPlacement.bind(this)),t.addEventListener("mousedown",this.toolboxHide.bind(this)),t.addEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&t.addEventListener("contextmenu",this.disableContext),t.addEventListener("mousedown",this.mousedown.bind(this)),t.addEventListener("mouseup",this.mouseup.bind(this)),t.addEventListener("mousemove",this.mousemove.bind(this)),t.addEventListener("touchstart",this.mousedown.bind(this)),t.addEventListener("touchend",this.mouseup.bind(this)),t.addEventListener("touchmove",this.mousemove.bind(this)),this.hasEventListener=!0}async mousedown(t){R0=t.clientX,k0=t.clientY}async mouseup(t){Math.abs(R0-t.clientX)<3&&Math.abs(k0-t.clientY)<3&&await this.processMouseEvent(t)}async mousemove(t){await this.processMouseEvent(t)}unbindEvents(t,n){let i=t.ownerDocument;i.removeEventListener("keyup",this.toolboxShowDelayed.bind(this)),t.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),i.removeEventListener("selectstart",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),i.removeEventListener("selectionchange",this.toolboxPlacement.bind(this)),t.removeEventListener("mousedown",this.toolboxHide.bind(this)),t.removeEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&t.removeEventListener("contextmenu",this.disableContext),t.removeEventListener("mousedown",this.mousedown.bind(this)),t.removeEventListener("mouseup",this.mouseup.bind(this)),t.removeEventListener("mousemove",this.mousemove.bind(this)),t.removeEventListener("touchstart",this.mousedown.bind(this)),t.removeEventListener("touchend",this.mouseup.bind(this)),t.removeEventListener("touchmove",this.mousemove.bind(this)),this.hasEventListener=!1}destroy(){this.toolboxHide();let t=this.delegate.iframes[0].contentDocument;t&&(this.unbindEvents(t.body,this),this.dom(t.body).removeClass(this.options.contextClass))}initializeToolbox(){let t=document.getElementById("highlight-toolbox-mode-colors"),n=document.getElementById("highlight-toolbox-mode-add"),i=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],o=document.getElementById("colorIcon"),l=document.getElementById("actionIcon"),s=document.getElementById("dismissIcon"),a=document.getElementById("collapseIcon"),u=document.getElementById("highlightIcon"),h=this;if(s&&(s.innerHTML=$i.close,s.addEventListener("click",function(){h.toolboxMode("add")})),a&&(a.innerHTML=$i.close,a.addEventListener("click",function(){h.toolboxMode("add")})),o){o.style.position="relative",o.style.zIndex="20",i.forEach(g=>{let y=document.getElementById(g),E=document.getElementById(`c${g}`);y&&t?.contains(y)&&t.removeChild(y),n&&E&&n.contains(E)&&n.removeChild(E)});let f=[],p=[];if(o.addEventListener("click",function(){h.toolboxMode("colors")}),this.delegate.rights.enableAnnotations){let g=10;i.forEach(y=>{g--;let E=o?.cloneNode(!0),b=E.lastChild,w=Ge.hexToRgbChannels(y);b.style.backgroundColor="rgba("+[w.red,w.green,w.blue].join(",")+",.5)",E.id=`c${y}`,E.style.display="unset",E.style.position="relative",E.style.zIndex=`${g}`,E.style.marginLeft="-30px",p.push(E),n?.insertBefore(E,u)})}i.forEach(g=>{let y=o?.cloneNode(!0),E=y.lastChild;E.style.backgroundColor=g,y.id=g,y.style.position="relative",y.style.display="unset",f.push(y);let b=document.getElementById("highlightIcon"),w=document.getElementById("underlineIcon");o&&y.addEventListener("click",function(){h.setColor(g);let _=o?.lastChild;_&&(_.style.backgroundColor=g),(b?.getElementsByTagName?.("span").length??0)>0&&((b?.getElementsByTagName("span")[0]).style.background=h.getColor()),(w?.getElementsByTagName?.("span").length??0)>0&&((w?.getElementsByTagName("span")[0]).style.borderBottomColor=h.getColor()),h.toolboxMode("add")}),t?.insertBefore(y,s)})}l&&l.addEventListener("click",function(){h.toolboxMode("action")}),h.toolboxMode("add")}toolboxMode(t){let n=document.getElementById("highlight-toolbox-mode-colors"),i=document.getElementById("highlight-toolbox-mode-add"),o=document.getElementById("highlight-toolbox-mode-edit"),l=document.getElementById("highlight-toolbox-mode-action");switch(t){case"colors":n&&(n.style.display="unset"),i&&(i.style.display="none"),o&&(o.style.display="none"),l&&(l.style.display="none");break;case"edit":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="unset"),l&&(l.style.display="none");break;case"action":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),l&&(l.style.display="unset");break;default:n&&(n.style.display="none"),i&&(i.style.display="unset"),o&&(o.style.display="none"),l&&(l.style.display="none");break}}toolboxHide(){let t=document.getElementById("highlight-toolbox");t&&(t.style.display="none"),this.selectionMenuClosed()}toolboxShowDelayed(){let t=this;setTimeout(function(){t.isAndroid()||t.snapSelectionToWord(),t.toolboxShow()},100)}snapSelectionToWord(){let t=this,n=this.delegate.iframes[0].contentDocument;if(n){let i=t.dom(n.body)?.getWindow()?.getSelection();if(t.dom(n.body)&&i&&!i?.isCollapsed){let o=document.createRange();o.setStart(i.anchorNode,i.anchorOffset),o.setEnd(i.focusNode,i.focusOffset);let l=o.collapsed;o.detach();let s=i.focusNode,a=i.focusOffset;i.collapse(i.anchorNode,i.anchorOffset);let u=["forward","backward"];l&&(u=["backward","forward"]),i.modify("move",u[0],"character"),i.modify("move",u[1],"word"),i.extend(s,a),i.modify("extend",u[1],"character"),i.modify("extend",u[0],"word"),this.selection(i.toString(),i)}return i}}toolboxShow(){if(this.activeAnnotationMarkerId===void 0){let t=this,n=document.getElementById("highlight-toolbox-mode-add"),i=this.dom(this.delegate.iframes[0].contentDocument?.body).getRange();if((!i||i.collapsed)&&n){getComputedStyle(n).display!=="none"&&t.toolboxHide();return}this.isIOS()&&(this.delegate.iframes[0].contentDocument?.body.removeEventListener("selectionchange",this.toolboxPlacement.bind(this)),setTimeout(function(){let o=t.delegate.iframes[0].contentDocument;if(o){let l=t.dom(o.body).getSelection();l.removeAllRanges(),setTimeout(function(){l.addRange(i)},5)}},100)),this.toolboxPlacement(),this.toolboxHandler()}}toolboxPlacement(){let t=this.dom(this.delegate.iframes[0].contentDocument?.body).getRange();if(!t||t.collapsed)return;let n=t.getBoundingClientRect(),i=document.getElementById("highlight-toolbox");i&&(this.delegate.view?.isPaginated()?i.style.top=n.top+(this.delegate.attributes?.navHeight??0)+"px":i.style.top=n.top+"px",i.style.left=(n.right-n.left)/2+n.left+"px")}toolboxHandler(){let t=document.getElementById("highlight-toolbox");if(t&&getComputedStyle(t).display==="none"){t.style.display="block",this.delegate.view?.isPaginated()?t.style.position="absolute":t.style.position="relative",this.selectionMenuOpened();let i=this;i.toolboxMode("add");let o=document.getElementById("highlightIcon"),l=document.getElementById("collapseIcon"),s=document.getElementById("underlineIcon"),a=document.getElementById("colorIcon"),u=document.getElementById("speakIcon");if(this.delegate.rights.enableAnnotations){if(o&&(o.style.display="unset",a&&o.getElementsByTagName("span").length>0&&(o.getElementsByTagName("span")[0].style.background=this.getColor())),s&&(s.style.display="unset",a&&s.getElementsByTagName("span").length>0&&(s.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),a){a.style.display="unset";let h=a.lastChild;h.style.backgroundColor=this.getColor()}if(o){let h=function(){i.doHighlight(!1,ot.Highlight),i.toolboxHide(),o?.removeEventListener("click",h)};o.addEventListener("click",h)}if(s){let h=function(){i.doHighlight(!1,ot.Underline),i.toolboxHide(),s?.removeEventListener("click",h)};s.addEventListener("click",h)}}else o&&o.style.setProperty("display","none"),s&&s.style.setProperty("display","none"),a&&a.style.setProperty("display","none"),l&&l.style.setProperty("display","none");if(this.delegate.rights.enableTTS){if(u){let h=function(){u?.removeEventListener("click",h),i.speak()};u.addEventListener("click",h)}}else u&&u.style.setProperty("display","none");(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).forEach(h=>{h.icon&&(h.icon.id=h.id);let f=document.getElementById(h.id),p=this;function g(){f?.removeEventListener("click",g);function y(b){let w={className:S=>to.indexOf(S)<0,idName:S=>to.indexOf(S)<0},_=p.delegate.iframes[0].contentDocument;if(_)return Dn(b,_,w)}let E=p.delegate.iframes[0].contentWindow;if(E){let b=Qr(E,y);if(b!==void 0)if(h.callback)h.callback(b.cleanText,b.range?.startContainer.parentElement);else{let w=h.highlight?.style,_=h.marker?h.marker:ot.Custom;if(_===ot.Custom&&p.delegate.rights.enableAnnotations||_===ot.Bookmark&&p.delegate.rights.enableBookmarks){let S=p.delegate.iframes[0].contentDocument;if(S){let x=p.createHighlight(p.dom(S.body).getWindow(),b,h.highlight?.color,!0,_,h.icon,h.popup,w);p.options.onAfterHighlight(x,_),p.delegate.rights.enableAnnotations?p.delegate.annotationModule?.saveAnnotation(x[0]).then(R=>{h?.note&&(R.highlight&&(R.highlight.note=prompt("Add your note here:")),p.delegate.annotationModule?.updateAnnotation(R).then(async()=>{K&&console.log("update highlight "+R.id)}))}):p.delegate.rights.enableBookmarks&&p.delegate.bookmarkModule?.saveAnnotation(x[0])}}}}p.callbackComplete()}f&&f.addEventListener("click",g)})}}doHighlight(t,n){let i=this;function o(s){let a={className:h=>to.indexOf(h)<0,idName:h=>to.indexOf(h)<0},u=i.delegate.iframes[0].contentDocument;if(u)return Dn(s,u,a)}let l=i.delegate.iframes[0].contentWindow;if(l){let s=Qr(l,o);if(s){if(this.options.onBeforeHighlight(s)===!0){let a;a=this.getColor(),Ge.isHexColor(a)&&(a=Ge.hexToRgbChannels(a));let u=i.delegate.iframes[0].contentDocument;if(u){let h=this.createHighlight(i.dom(u.body).getWindow(),s,a,!0,n??ot.Highlight);this.options.onAfterHighlight(h,n),this.delegate.rights.enableAnnotations&&n!==ot.Bookmark?this.delegate.annotationModule?.saveAnnotation(h[0]):this.delegate.rights.enableBookmarks&&n===ot.Bookmark&&this.delegate.bookmarkModule?.saveAnnotation(h[0])}}t||this.dom(this.delegate.iframes[0].contentDocument?.body).removeAllRanges()}else t||this.dom(this.delegate.iframes[0].contentDocument?.body).removeAllRanges()}}speak(){if(this.delegate.rights.enableTTS){let n=function(s){let a={className:h=>to.indexOf(h)<0,idName:h=>to.indexOf(h)<0},u=t.delegate.iframes[0].contentDocument;if(u)return Dn(s,u,a)},t=this,i=t.delegate.iframes[0].contentWindow;if(i){let s=Qr(i,n);s!==void 0&&(this.delegate.tts?.enableSplitter?this.delegate.ttsModule.speak(s,!0,()=>{}):this.delegate.ttsModule.speak(s,!0,()=>{}))}let o=t.delegate.iframes[0].contentDocument;o&&t.dom(o.body).getSelection().removeAllRanges();let l=document.getElementById("highlight-toolbox");l&&(l.style.display="none"),this.selectionMenuClosed()}}stopReadAloud(){this.delegate.rights.enableTTS&&this.doneSpeaking()}speakAll(){if(this.delegate.rights.enableTTS){let i=function(l){let s={className:u=>to.indexOf(u)<0,idName:u=>to.indexOf(u)<0},a=n.delegate.iframes[0].contentDocument;if(a)return Dn(l,n.dom(a.body).getDocument(),s)},n=this,o=this.delegate.iframes[0].contentDocument;if(o)if(Qr(this.dom(o.body).getWindow(),i)!==void 0)n.speak();else{var t=this.dom(n.delegate.iframes[0].contentDocument?.body).getWindow().document.body;K&&console.log(o);let s=n.dom(o.body).getSelection(),a=this.dom(o.body).getWindow().document.createRange();a.selectNodeContents(t),s.removeAllRanges(),s.addRange(a);let u=this.delegate.iframes[0].contentWindow;if(u){let h=Qr(u,i);h!==void 0&&h.cleanText?this.delegate.tts?.enableSplitter?this.delegate.ttsModule.speak(h,!1,()=>{o&&n.dom(o.body).getSelection().removeAllRanges(),n.toolboxHide()}):this.delegate.ttsModule.speak(h,!1,()=>{o&&n.dom(o.body).getSelection().removeAllRanges(),n.toolboxHide()}):(n.dom(o.body).getSelection().removeAllRanges(),n.toolboxHide())}}}}callbackComplete(){this.toolboxHide();let t=this.delegate.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges()}isOutsideViewport(t){let n=St(document,"#iframe-wrapper"),i=n.scrollLeft,o=i+n.clientHeight,l=t.left+t.width,s=t.top+t.height,a=n.scrollTop,u=a+n.clientHeight,h=s<a,f=t.top>u,p=l<i,g=t.left>o;return h||f||p||g}get visibleTextRects(){let t=this.delegate.iframes[0].contentDocument;if(t){let i=function(a,u=[]){let h=a.firstChild;for(;h;)h.nodeType===1&&i(h,u),h.nodeType===3&&h.textContent?.trim()&&u.push(h),h=h.nextSibling;return u},o=function(a){return i(a).map(h=>{let{top:f,height:p,left:g,width:y}=l(h);return{top:f,height:p,width:y,left:g,node:h,textContent:h.textContent??""}})},l=function(a){try{let u=document.createRange();u.selectNode(a);let h=u.getBoundingClientRect();return u.detach(),h}catch(u){K&&(console.log("measureTextNode "+u),console.log("measureTextNode "+a),console.log(a.textContent))}},n=Sr(t,"body");return o(n).filter(a=>!this.isOutsideViewport(a))}return[]}doneSpeaking(t=!1){if(this.delegate.rights.enableTTS){this.toolboxHide();let n=this.delegate.iframes[0].contentDocument;n&&this.dom(n.body).removeAllRanges(),this.delegate.tts?.enableSplitter?this.delegate.ttsModule.cancel():this.delegate.ttsModule.cancel(),t&&this.delegate.reload()}}normalizeHighlights(t){var n;return n=t.filter(function(i){return i.parentElement?i:null}),n=this.unique(n),n.sort(function(i,o){return i.offsetTop-o.offsetTop||i.offsetLeft-o.offsetLeft}),n}flattenNestedHighlights(t){let n,i=this;i.sortByDepth(t,!0);function o(){let l=!1;return t.forEach(function(s,a){let u=s.parentElement,h=u.previousSibling,f=u.nextSibling;i.isHighlight(u)&&(i.haveSameColor(u,s)?(u.replaceChild(s.firstChild,s),t[a]=u,l=!0):(s.nextSibling||(i.dom(s).insertBefore(f||u),l=!0),s.previousSibling||(i.dom(s).insertAfter(h||u),l=!0),u.hasChildNodes()||i.dom(u).remove()))}),l}do n=o();while(n)}mergeSiblingHighlights(t){let n=this;function i(o,l){return l&&l.nodeType===Ws.ELEMENT_NODE&&n.haveSameColor(o,l)&&n.isHighlight(l)}t.forEach(function(o){let l=o.previousSibling,s=o.nextSibling;i(o,l)&&(n.dom(o).prepend(l.childNodes),n.dom(l).remove()),i(o,s)&&(n.dom(o).append(s.childNodes),n.dom(s).remove()),n.dom(o).normalizeTextNodes()})}setColor(t){this.options.color=t}getColor(){return this.options.color}isHighlight(t){return t&&t.nodeType===Ws.ELEMENT_NODE&&t.hasAttribute(mN)}createWrapper(){let t=document.createElement("mark");return t.style.background="linear-gradient("+Ge.hexToRgbA(this.options.color)+", "+Ge.hexToRgbA(this.options.color)+")",t.className=this.options.highlightedClass,t}static isHexColor(t){return/^#([A-Fa-f0-9]{3}){1,2}$/.test(t)}static hexToRgbString(t){let n;return n=t.substring(1).split(""),n.length===3&&(n=[n[0],n[0],n[1],n[1],n[2],n[2]]),n="0x"+n.join(""),n}static hexToRgbChannels(t){let n;if(this.isHexColor(t))return n=this.hexToRgbString(t),{red:n>>16&255,green:n>>8&255,blue:n&255};throw new Error("Bad Hex")}static hexToRgbA(t){let n;if(this.isHexColor(t))return n=this.hexToRgbChannels(t),"rgba("+[n.red,n.green,n.blue].join(",")+",.5)";if(typeof t=="object"){let i=t;return"rgba("+[i.red,i.green,i.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(t,n){let i;if(this.isHexColor(t))return i=this.hexToRgbChannels(t),"rgba("+[i.red,i.green,i.blue].join(",")+","+n+")";if(typeof t=="object"){let o=t;return"rgba("+[o.red,o.green,o.blue].join(",")+","+n+")"}throw new Error("Bad Hex")}resetHighlightBoundingStyle(t){t.style.outline="none",t.style.setProperty("background-color","transparent","important")}resetHighlightAreaStyle(t,n){let i=this.delegate.iframes[0].contentWindow?.document,o=t.parentNode&&t.parentNode.nodeType===Node.ELEMENT_NODE&&t.parentNode.getAttribute?t.parentNode.getAttribute("id"):void 0;if(o){let l=Yt.find(s=>s.id===o);if(l){if(l.marker===ot.Custom||l.marker===ot.Bookmark)if(l.style?.hover){if(l.style?.hover)for(let u=0;u<l.style?.hover?.length;u++){let h=l.style?.hover[u];t.style.removeProperty(h.property)}let a="";if(l.style?.default)for(let u=0;u<l.style?.default?.length;u++){let h=l.style?.default[u];t.style.removeProperty(h.property),a+=`${h.property}: ${h.value} !${h.priority};`}t.setAttribute("style",`${t.getAttribute("style")}; ${a}`)}else if(l.style?.hoverClass){l.style?.hoverClass&&t.classList.remove(l.style?.hoverClass);let a="";l.style?.defaultClass&&t.classList.add(l.style?.defaultClass),t.setAttribute("style",`${t.getAttribute("style")}; ${a}`)}else if(Ge.isHexColor(l.color)){let a=Ge.hexToRgbChannels(l.color);t.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${0})`,"important")}else t.classList.remove("hover");else if(l.marker===ot.Underline)if(typeof l.color=="object"){let a=l.color;t.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, ${1})`,"important")}else if(Ge.isHexColor(l.color)){let a=Ge.hexToRgbChannels(l.color);t.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, ${1})`,"important")}else t.classList.remove("hover");else if(typeof l.color=="object"){let a=l.color;t.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${rr})`,"important")}else if(Ge.isHexColor(l.color)){let a=Ge.hexToRgbChannels(l.color);t.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${rr})`,"important")}else t.classList.remove("hover");let s;if(i){let a=i.getElementById(n);a&&(s=a.querySelector(`#${l.id}`))}if(s){let a=s.getElementsByClassName(Qa);if(a.length>0){let u=a.item(0).getElementsByClassName("icon-tooltip");u.length>0&&u.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(t,n,i){for(let o of n){if(i.marker===ot.Custom||i.marker===ot.Bookmark)if(i.style?.hover){if(i.style?.default)for(let s=0;s<i.style?.default?.length;s++){let a=i.style?.default[s];o.style.removeProperty(a.property)}let l="";for(let s=0;s<i.style?.hover?.length;s++){let a=i.style?.hover[s];o.style.removeProperty(a.property),l+=`${a.property}: ${a.value} !${a.priority};`}o.setAttribute("style",`${o.getAttribute("style")}; ${l}`)}else if(i.style?.hoverClass){i.style?.defaultClass&&o.classList.remove(i.style?.defaultClass);let l="";o.classList.add(i.style?.hoverClass),o.setAttribute("style",`${o.getAttribute("style")}; ${l}`)}else if(Ge.isHexColor(i.color)){let l=Ge.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${l.red}, ${l.green}, ${l.blue}, ${.1})`,"important")}else o.classList.add("hover");else if(i.marker===ot.Underline)if(typeof i.color=="object"){let l=i.color;o.style.setProperty("background-color",`rgba(${l.red}, ${l.green}, ${l.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${l.red}, ${l.green}, ${l.blue}, ${1})`,"important")}else if(Ge.isHexColor(i.color)){let l=Ge.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${l.red}, ${l.green}, ${l.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${l.red}, ${l.green}, ${l.blue}, ${1})`,"important")}else o.classList.add("hover");else if(typeof i.color=="object"){let l=i.color;o.style.setProperty("background-color",`rgba(${l.red}, ${l.green}, ${l.blue}, ${K_})`,"important")}else if(Ge.isHexColor(i.color)){let l=Ge.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${l.red}, ${l.green}, ${l.blue}, ${K_})`,"important")}else o.classList.add("hover");if(i.type!==nt.Definition){let s=t.getElementById(Ue.R2_ID_HIGHLIGHTS_CONTAINER).querySelector(`#${i.id}`).getElementsByClassName(Qa);if(s.length>0){let a=s.item(0).getElementsByClassName("icon-tooltip");a.length>0&&a.item(0).style.setProperty("display","block")}}}}setAndResetSearchHighlight(t,n){let i=this.delegate.iframes[0].contentWindow?.document,o=Array.from(i.getElementById(Ue.R2_ID_SEARCH_CONTAINER).querySelectorAll(`.${pi}`));for(let l of o){let s=l,a=s.parentNode&&s.parentNode.nodeType===Node.ELEMENT_NODE&&s.parentNode.getAttribute?s.parentNode.getAttribute("id"):void 0;if(n.forEach(u=>{if(a===u.id&&u){if(typeof u.color=="object"){let p=u.color;s.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${rr})`,"important")}else if(Ge.isHexColor(u.color)){let p=Ge.hexToRgbChannels(u.color);s.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${rr})`,"important")}else s.classList.remove("hover");let f=i.getElementById(Ue.R2_ID_SEARCH_CONTAINER).querySelector(`#${u.id}`).getElementsByClassName(Qa);if(f.length>0){let p=f.item(0).getElementsByClassName("icon-tooltip");p.length>0&&p.item(0).style.removeProperty("display")}}}),a===t.id&&t){if(typeof t.color=="object"){let f=t.color;s.style.setProperty("background-color",`rgba(${f.red}, ${f.green}, ${f.blue}, ${rr})`,"important")}else if(Ge.isHexColor(t.color)){let f=Ge.hexToRgbChannels(t.color);s.style.setProperty("background-color",`rgba(${f.red}, ${f.green}, ${f.blue}, ${rr})`,"important")}else s.classList.remove("hover");let h=i.getElementById(Ue.R2_ID_SEARCH_CONTAINER).querySelector(`#${t.id}`).getElementsByClassName(Qa);if(h.length>0){let f=h.item(0).getElementsByClassName("icon-tooltip");f.length>0&&f.item(0).style.removeProperty("display")}}}}isIOS(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}isAndroid(){return navigator.userAgent.match(/Android/i)!=null}async processMouseEvent(t){let n=this.delegate.iframes[0].contentWindow?.document,i=t.clientX,o=t.clientY;if(!n||!n.getElementById(Ue.R2_ID_HIGHLIGHTS_CONTAINER)&&!n.getElementById(Ue.R2_ID_SEARCH_CONTAINER)&&!n.getElementById(Ue.R2_ID_PAGEBREAK_CONTAINER)&&!n.getElementById(Ue.R2_ID_READALOUD_CONTAINER)&&!n.getElementById(Ue.R2_ID_DEFINITIONS_CONTAINER))return;let l=this.delegate.view?.isPaginated(),s=n.body.getBoundingClientRect(),a=this.getScrollingElement(n),u=l?-a.scrollLeft:s.left,h=l?-a.scrollTop:s.top,f,p;for(let g=Yt.length-1;g>=0;g--){let y=Yt[g],E=n.getElementById(`${y.id}`);if(!E){let _=n.getElementById(Ue.R2_ID_HIGHLIGHTS_CONTAINER);_&&(E=_.querySelector(`#${y.id}`))}if(!E)continue;let b=!1,w=E.querySelectorAll(`.${pi}`);for(let _ of w){let S=_,x=S.rect.left+u,R=S.rect.top+h;if(i>=x&&i<x+S.rect.width&&o>=R&&o<R+S.rect.height){b=!0;break}}if(b){f=y,p=E;break}}if(!f||!p){for(let g in Ue){let y=n.getElementById(g);if(y){let E=y.querySelectorAll(`.${Za}`);for(let w of E)this.resetHighlightBoundingStyle(w);let b=Array.from(y.querySelectorAll(`.${pi}`));for(let w of b)this.resetHighlightAreaStyle(w,g)}}return}if(p.getAttribute("data-click")){if((t.type==="mousemove"||t.type==="touchmove")&&p.parentElement?.style.display!=="none"){let g=Array.from(p.querySelectorAll(`.${pi}`));for(let E in Ue){let b=n.getElementById(E);if(b){let w=b.querySelectorAll(`.${pi}`);for(let _ of w)g.indexOf(_)<0&&this.resetHighlightAreaStyle(_,E)}}this.setHighlightAreaStyle(n,g,f);let y=p.querySelector(`.${Za}`);for(let E in Ue){let b=n.getElementById(E);if(b){let w=b.querySelectorAll(`.${Za}`);for(let _ of w)(!y||_!==y)&&this.resetHighlightBoundingStyle(_)}}}else if((t.type==="mouseup"||t.type==="click"||t.type==="touchup")&&p.parentElement?.style.display!=="none"){let g={highlight:f};K&&console.log(g);let y=this,E;if(y.delegate.rights.enableAnnotations?E=await this.delegate.annotationModule?.getAnnotation(g.highlight):y.delegate.rights.enableBookmarks&&(E=await this.delegate.bookmarkModule?.getAnnotation(g.highlight)),g.highlight.type===nt.Annotation&&this.delegate.annotationModule?.api?.selectedAnnotation(E).then(async()=>{}),E?.id){K&&console.log("selected highlight "+E.id),y.lastSelectedHighlight=E.id;let b=document.getElementById("highlight-toolbox");if(b)if(b.style.top=t.clientY+(this.delegate.attributes?.navHeight??0)+"px",b.style.left=t.clientX+"px",getComputedStyle(b).display==="none"){let S=function(){E.highlight.note=prompt("Add your note here:"),y.delegate.annotationModule?.updateAnnotation(E).then(async()=>{K&&console.log("update highlight "+E.id),b&&(b.style.display="none"),y.selectionMenuClosed()}),b&&(b.style.display="none"),y.selectionMenuClosed(),x?.removeEventListener("click",S,!1)},C=function(){y.delegate.rights.enableAnnotations?y.delegate.annotationModule?.deleteSelectedHighlight(E).then(async()=>{K&&console.log("delete highlight "+E.id),b&&(b.style.display="none"),y.selectionMenuClosed()}):y.delegate.rights.enableBookmarks&&y.delegate.bookmarkModule?.deleteSelectedHighlight(E).then(async()=>{K&&console.log("delete highlight "+E.id),b&&(b.style.display="none"),y.selectionMenuClosed()})};b.style.display="block",this.toolboxMode("edit");let w=document.getElementById("colorIcon"),_=document.getElementById("highlightIcon");w&&(w.style.display="none"),_&&(_.style.display="none");let x=document.getElementById("commentIcon"),R=document.getElementById("cloneCommentIcon");if(R){let N=R.parentElement;N&&N.removeChild(R)}if(x){x.style.display="none";let N=x.cloneNode(!0),J=x.parentElement;N.style.display="unset",N.id="cloneCommentIcon",N.addEventListener("click",S,!1),J&&J.append(N)}let I=document.getElementById("deleteIcon"),z=document.getElementById("cloneDeleteIcon");if(z){let N=z.parentElement;N&&N.removeChild(z)}if(I){I.style.display="none";let N=I.cloneNode(!0),J=I.parentElement;N.style.display="unset",N.id="cloneDeleteIcon",N.addEventListener("click",C,!1),J&&J.append(N)}}else b.style.display="none",this.selectionMenuClosed(),b.offsetWidth,b.style.display="block"}else{p.dataset.definition&&new Ya(this.delegate).showPopup(p.dataset.definition,t);let b=this.delegate.definitionsModule?.properties?.definitions?.filter(w=>w.order===Number(p?.dataset.order))[0];console.log(b),this.delegate.definitionsModule?.api?.click&&(this.delegate.definitionsModule.api?.click(M0.omit(b,"callbacks"),M0.omit(f,"definition")),this.delegate.emit("definition.click",b,f))}}}}async prepareContainers(t){for(let n in Ue)await this.ensureHighlightsContainer(t,n)}async ensureHighlightsContainer(t,n){let i=t.document;if(!i.getElementById(n)){let o=i.createElement("div");o.setAttribute("id",n),o.style.setProperty("pointer-events","none"),this.delegate.view?.layout==="fixed"&&(o.style.setProperty("position","absolute"),o.style.setProperty("top","0"),o.style.setProperty("left","0")),i.body&&i.body.append(o),(await this.layerSettings.getProperty(n))?.value===!1&&(o.style.display="none")}return i.getElementById(n)}hideAllhighlights(t){this.removeAllChildNodes(t.getElementById(Ue.R2_ID_HIGHLIGHTS_CONTAINER)),this.removeAllChildNodes(t.getElementById(Ue.R2_ID_SEARCH_CONTAINER)),this.removeAllChildNodes(t.getElementById(Ue.R2_ID_READALOUD_CONTAINER)),this.removeAllChildNodes(t.getElementById(Ue.R2_ID_PAGEBREAK_CONTAINER)),this.removeAllChildNodes(t.getElementById(Ue.R2_ID_DEFINITIONS_CONTAINER))}destroyAllhighlights(t){this.hideAllhighlights(t),Yt.splice(0,Yt.length)}removeAllChildNodes(t){for(;t.firstChild;)t.removeChild(t.firstChild)}destroyHighlights(t){let n=this.delegate.iframes[0].contentWindow?.document;if(n){let i;switch(t){case nt.ReadAloud:i=n.getElementById(Ue.R2_ID_READALOUD_CONTAINER),i&&this.removeAllChildNodes(i);break;case nt.Search:i=n.getElementById(Ue.R2_ID_SEARCH_CONTAINER),i&&this.removeAllChildNodes(i);break;case nt.PageBreak:i=n.getElementById(Ue.R2_ID_PAGEBREAK_CONTAINER),i&&this.removeAllChildNodes(i);break;case nt.Definition:i=n.getElementById(Ue.R2_ID_DEFINITIONS_CONTAINER),i&&this.removeAllChildNodes(i);break;case nt.LineFocus:i=n.getElementById(Ue.R2_ID_LINEFOCUS_CONTAINER),i&&this.removeAllChildNodes(i);break;default:i=n.getElementById(Ue.R2_ID_HIGHLIGHTS_CONTAINER),i&&this.removeAllChildNodes(i),Yt.splice(0,Yt.length);break}}}destroyHighlight(t,n){if(!t)return;let i=-1;Yt.find((s,a)=>(i=a,s.id===n))&&i>=0&&i<Yt.length&&Yt.splice(i,1);let l=t.getElementById(n);l&&this.removeAllChildNodes(l)}createHighlight(t,n,i,o,l,s,a,u,h,f){try{let p=`${n.rangeInfo.startContainerElementCssSelector}${n.rangeInfo.startContainerChildTextNodeIndex}${n.rangeInfo.startOffset}${n.rangeInfo.endContainerElementCssSelector}${n.rangeInfo.endContainerChildTextNodeIndex}${n.rangeInfo.endOffset}`,g=Ai.hash(p),y=(f||"R2_HIGHLIGHT_")+g;this.destroyHighlight(t.document,y);let E=`rgb(${jo.red}, ${jo.green}, ${jo.blue})`,b={color:i||E,id:y,pointerInteraction:o,selectionInfo:n,marker:l,icon:s,popup:a,style:u,type:h||nt.Annotation};(h===nt.Annotation||h===nt.Definition||h===void 0)&&Yt.push(b);let w=this.createHighlightDom(t,b);return b.position=parseInt((w?.hasChildNodes()?w.childNodes[0]:w).style.top.replace("px","")),[b,w]}catch(p){throw"Can't create highlight: "+p}}createHighlightDom(t,n){let i=t.document,o=N_(i,n.selectionInfo.rangeInfo);if(!o)return;for(let D in Ue)this.ensureHighlightsContainer(t,D);let l=i.createElement("div");l.setAttribute("id",n.id),l.setAttribute("class",J_),l.style.setProperty("pointer-events","none"),n.pointerInteraction&&l.setAttribute("data-click","1");let s=this.delegate.view?.isPaginated();s?i.body.style.position="revert":i.body.style.position="relative";let a=i.body.getBoundingClientRect(),u=this.getScrollingElement(i),h=s?-u.scrollLeft:a.left,f=s?-u.scrollTop:a.top,p=1,g=!1,y=!1,w=_d(o,g||y||!1),_=3,S=2,x=3,R=0,C=24,I,z;for(let D of w){let U=i.createElement("div");U.setAttribute("class",pi),U.dataset.marker=""+n.marker;let Y="";if(g&&n.marker!==ot.Custom&&n.marker!==ot.Bookmark){let ee=n.color;Ge.isHexColor(ee)&&(ee=Ge.hexToRgbChannels(ee)),Y+=`border-bottom: ${S*p}px solid rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${rr}) !important`}if(n.marker===ot.Custom||n.marker===ot.Bookmark)if(n.style?.default){for(let ee=0;ee<n.style?.default?.length;ee++){let de=n.style?.default[ee];Y+=`${de.property}: ${de.value} !${de.priority};`}U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${_}px !important; ${Y}`)}else n.style?.defaultClass&&(U.classList.add(n.style?.defaultClass),U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${_}px !important; ${Y}`));else if(n.marker===ot.Underline)if(typeof n.color=="object"){let ee=n.color;U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${_}px !important; background-color: rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${0}) !important; ${Y}`),U.style.setProperty("border-bottom",`2px solid rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${1})`,"important")}else if(Ge.isHexColor(n.color)){let ee=Ge.hexToRgbChannels(n.color);U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${_}px !important; background-color: rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${0}) !important; ${Y}`),U.style.setProperty("border-bottom",`2px solid rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${1})`,"important")}else U.setAttribute("style",`border-radius: ${_}px !important; ${Y}`);else if(typeof n.color=="object"){let ee=n.color;U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${_}px !important; background-color: rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${rr}) !important; ${Y}`)}else if(Ge.isHexColor(n.color)){let ee=Ge.hexToRgbChannels(n.color);U.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${_}px !important; background-color: rgba(${ee.red}, ${ee.green}, ${ee.blue}, ${rr}) !important; ${Y}`)}else U.setAttribute("style",`border-radius: ${_}px !important; ${Y}`);U.style.setProperty("pointer-events","none"),U.style.position="absolute",U.scale=p,U.rect={height:D.height,left:D.left-h,top:D.top-f,width:D.width},n.pointerInteraction&&(U.setAttribute("data-click","1"),U.tabIndex=0),U.style.width=`${U.rect.width*p}px`,U.style.height=`${U.rect.height*p}px`,U.style.left=`${U.rect.left*p}px`,U.style.top=`${U.rect.top*p}px`,l.append(U);let be=parseInt(U.style.top.replace("px",""));if((be<R||R===0)&&(R=be),C=parseInt(U.style.height.replace("px","")),y){let ee=i.createElement("div");ee.setAttribute("class",pi);let de=n.color;Ge.isHexColor(de)&&(de=Ge.hexToRgbChannels(de)),ee.setAttribute("style",`background-color: rgba(${de.red}, ${de.green}, ${de.blue}, ${rr}) !important;`),ee.style.setProperty("pointer-events","none"),ee.style.position="absolute",ee.scale=p,ee.rect={height:D.height,left:D.left-h,top:D.top-f,width:D.width},ee.style.width=`${ee.rect.width*p}px`,ee.style.height=`${x*p}px`,ee.style.left=`${ee.rect.left*p}px`,ee.style.top=`${(ee.rect.top+ee.rect.height/2-x/2)*p}px`,l.append(ee)}let le=this.delegate.iframes[0].contentWindow?.innerWidth,_e=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-count")),me=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-width")),Ce=parseInt(getComputedStyle(i.body).getPropertyValue("padding-left")),De=le/(_e||1);De<me&&(De=le),s||(De=parseInt(getComputedStyle(i.body).width.replace("px","")));let ce=this.delegate.settings.fontSize/100,Pe=20*ce;ce<=1&&(Pe=-60);let Le=0*ce;ce<=1&&(Le=-60),I=Math.floor(D.left/De)*De+De-(C<40?40:C)+Le,z=Math.floor(D.left/De)*De+(C<40?40:C)-Pe;let Ie=parseInt(this.delegate.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));Ie>=2&&(z=z+Ce/_e,I=I-Ce/_e),s||(I=parseInt(getComputedStyle(this.delegate.iframes[0].contentDocument?.body).width.replace("px","")),z=parseInt(getComputedStyle(this.delegate.iframes[0].contentDocument?.body).width.replace("px",""))-De,Ie>=2&&(z=z+Ce/2,I=I-Ce/2))}let N=o.getBoundingClientRect(),J=i.createElement("div");J.setAttribute("class",Za),J.style.setProperty("pointer-events","none"),J.style.position="absolute",J.scale=p,J.rect={height:N.height,left:N.left-h,top:N.top-f,width:N.width},J.style.width=`${J.rect.width*p}px`,J.style.height=`${J.rect.height*p}px`,J.style.left=`${J.rect.left*p}px`,J.style.top=`${J.rect.top*p}px`,l.append(J);let V=i.createElement("div");if(V.setAttribute("class",Qa),n.icon?.position==="left")V.setAttribute("style",`position: absolute;top:${R}px;left:${z+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${C}px; width:${C}px;`);else if(n.icon?.position==="inline")V.setAttribute("style",`position: absolute;top:${R-C/2}px;left:${parseInt(J.style.left.replace("px",""))+parseInt(J.style.width.replace("px",""))-C/2}px;height:${C}px; width:${C}px;`);else if(n.icon?.position==="center"){let U=C/3*2;V.setAttribute("style",`position: absolute;top:${R}px;left:${parseInt(J.style.left.replace("px",""))+parseInt(J.style.width.replace("px",""))-U}px;height:${C}px; width:${C}px;`)}else n.note&&n.marker!==ot.Custom&&n.marker!==ot.Bookmark?V.setAttribute("style",`position: absolute;top:${R-C/2}px;left:${parseInt(J.style.left.replace("px",""))+parseInt(J.style.width.replace("px",""))-C/2}px;height:${C}px; width:${C}px;`):V.setAttribute("style",`position: absolute;top:${R}px;left:${I+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${C}px; width:${C}px;`);if(n.marker===ot.Custom||n.marker===ot.Bookmark)n.icon?.class?(V.classList.add(n.icon?.class),V.id=n.icon?.id):n.icon?.svgPath?V.innerHTML=A0(`${n.icon?.id}`,`${n.icon?.title}`,`${n.icon?.svgPath}`,"icon open",C,`${n.icon?.color} !important`):V.innerHTML=n.icon?.title;else if(n.note){let D=n.color;Ge.isHexColor(D)&&(D=Ge.hexToRgbChannels(D)),V.innerHTML=A0("note-icon","Note",'<rect fill="none" height="24" width="24"/><path d="M19,5v9l-5,0l0,5H5V5H19 M19,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h10l6-6V5C21,3.9,20.1,3,19,3z M12,14H7v-2h5V14z M17,10H7V8h10V10z"/>',"icon open",C,`rgba(${D.red}, ${D.green}, ${D.blue}, 1) !important`)}V.style.setProperty("pointer-events","all");let j=this;if(n.type!==nt.PageBreak&&n.type!==nt.Definition&&V.addEventListener("click",async function(D){let U;j.delegate.rights.enableAnnotations?(U=await j.delegate.annotationModule?.getAnnotationByID(n.id),j.delegate.annotationModule?.api?.selectedAnnotation(U).then(async()=>{})):j.delegate.rights.enableBookmarks&&(U=await j.delegate.bookmarkModule?.getAnnotationByID(n.id)),K&&console.log("selected highlight "+U.id),j.lastSelectedHighlight=U.id;let Y=document.getElementById("highlight-toolbox");if(Y)if(Y.style.top=D.clientY+(j.delegate.attributes?.navHeight??0)+"px",Y.style.left=D.clientX+"px",getComputedStyle(Y).display==="none"){let me=function(){U.highlight.note=prompt("Add your note here:"),j.delegate.annotationModule?.updateAnnotation(U).then(async()=>{K&&console.log("update highlight "+U.id),Y.style.display="none",j.selectionMenuClosed()}),Y.style.display="none",j.selectionMenuClosed()},ce=function(){j.delegate.rights.enableAnnotations?j.delegate.annotationModule?.deleteSelectedHighlight(U).then(async()=>{K&&console.log("delete highlight "+U.id),Y.style.display="none",j.selectionMenuClosed()}):j.delegate.rights.enableBookmarks&&j.delegate.bookmarkModule?.deleteSelectedHighlight(U).then(async()=>{K&&console.log("delete highlight "+U.id),Y.style.display="none",j.selectionMenuClosed()})};Y.style.display="block",j.toolboxMode("edit");let le=document.getElementById("colorIcon"),_e=document.getElementById("highlightIcon");le&&(le.style.display="none"),_e&&(_e.style.display="none");let Ce=document.getElementById("commentIcon"),De=document.getElementById("cloneCommentIcon");if(De){let Ie=De.parentElement;Ie&&Ie.removeChild(De)}if(Ce){Ce.style.display="none";let Ie=Ce.cloneNode(!0),ee=Ce.parentElement;Ie.style.display="unset",Ie.id="cloneCommentIcon",Ie.addEventListener("click",me,!1),ee&&ee.append(Ie)}let Pe=document.getElementById("deleteIcon"),Le=document.getElementById("cloneDeleteIcon");if(Le){let Ie=Le.parentElement;Ie&&Ie.removeChild(Le)}if(Pe){Pe.style.display="none";let Ie=Pe.cloneNode(!0),ee=Pe.parentElement;Ie.style.display="unset",Ie.id="cloneDeleteIcon",Ie.addEventListener("click",ce,!1),ee&&ee.append(Ie)}}else Y.style.display="none",j.selectionMenuClosed(),Y.offsetWidth,Y.style.display="block";let be=Array.from(l.querySelectorAll(`.${pi}`));j.setHighlightAreaStyle(i,be,n)}),n.note){let D=document.createElement("span");D.innerHTML=n.note,D.className="icon-tooltip",n.marker===ot.Custom||n.marker===ot.Bookmark?(n.popup?.background&&D.style.setProperty("background",n.popup.background),n.popup?.textColor&&D.style.setProperty("color",n.popup.textColor),n.popup?.class&&D.classList.add(n.popup.class)):(D.style.setProperty("background","lightyellow"),D.style.setProperty("color","black")),V.insertBefore(D,V.childNodes[0])}switch((n.note||n.marker===ot.Custom||n.marker===ot.Bookmark)&&l.append(V),n.type){case nt.Search:i.getElementById(Ue.R2_ID_SEARCH_CONTAINER).append(l);break;case nt.ReadAloud:i.getElementById(Ue.R2_ID_READALOUD_CONTAINER).append(l);break;case nt.PageBreak:i.getElementById(Ue.R2_ID_PAGEBREAK_CONTAINER).append(l);break;case nt.Definition:i.getElementById(Ue.R2_ID_DEFINITIONS_CONTAINER).append(l);break;default:i.getElementById(Ue.R2_ID_HIGHLIGHTS_CONTAINER).append(l);break}return l}};var U0=At(Ad());var aS=At($0());T();var no={className:r=>!0,idName:r=>!0,tagName:r=>!0};var lS=At(Cd()),nl=class{constructor(t,n,i,o,l,s,a,u,h){this.hide=xe(document,"#menu-button-hide");this.show=xe(document,"#menu-button-show");this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=h,this.delegate=o,this.initialAnnotations=l,this.highlighter=a,this.properties=s,this.api=u}static async create(t){let n=new this(t.annotator,t.rights||{enableAnnotations:!1,enableTTS:!1},t.publication,t.delegate,t.initialAnnotations||null,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){K&&console.log("Annotation module stop")}async start(){if(this.delegate.annotationModule=this,this.headerMenu&&(this.highlightsView=xe(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var t=this.initialAnnotations.highlights||null;t&&this.annotator?.initAnnotations(t)}setTimeout(()=>{this.properties?.hideLayer?this.delegate.hideLayer("highlights"):this.delegate.showLayer("highlights")},10)}hideAnnotationLayer(){let t=this.delegate.iframes[0].contentDocument;if(t){let n=xe(t,"#R2_ID_HIGHLIGHTS_CONTAINER");n&&(n.style.display="none")}this.show&&this.hide&&(this.show.style.display="block",this.hide.style.display="none")}showAnnotationLayer(){let t=this.delegate.iframes[0].contentDocument;if(t){let n=xe(t,"#R2_ID_HIGHLIGHTS_CONTAINER");n&&(n.style.display="block")}this.show&&this.hide&&(this.show.style.display="none",this.hide.style.display="block")}async handleResize(){setTimeout(async()=>{await this.drawHighlights(),await this.showHighlights()},100)}initialize(){return new Promise(async t=>{await document.fonts.ready,this.rights.enableAnnotations&&setTimeout(()=>{this.drawHighlights(),this.showHighlights(),ve(this.delegate.iframes[0].contentDocument?.body,"click",this.click.bind(this))},300),t(null)})}click(t){if(this.activeAnnotationMarkerId){let n=this.highlighter?.properties?.selectionMenuItems?.filter(i=>i.id===this.activeAnnotationMarkerId);if(n&&n?.length>0){let i=lS.cloneDeep(n[0]);i.marker=ot.Custom,this.activeAnnotationMarkerPosition&&(i.icon.position=this.activeAnnotationMarkerPosition),i.highlight.style.default=null,i.highlight.style.hover=null;let o=this.delegate.iframes[0].contentDocument;if(o){let h=function(p){try{let g=u.delegate.iframes[0].contentDocument;return g?Dn(p,g,no):""}catch(g){return console.log("uniqueCssSelector:"),console.log(g),""}},l=this.highlighter?.dom(o.body).getSelection(),s=l.getRangeAt(0),a=l.anchorNode;s.setStart(a,s.startOffset),s.setEnd(a,s.endOffset+1),l.removeAllRanges(),l.addRange(s);let u=this,f=Mr(s,h);if(l.removeAllRanges(),f){let p={rangeInfo:f},g=this.delegate.highlighter?.createHighlight(this.delegate.highlighter?.dom(o.body).getWindow(),p,i.highlight.color,!0,ot.Bookmark,i.icon,i.popup,i.highlight.style);g&&this.saveAnnotation(g[0]).then(y=>{K&&console.log("saved bookmark "+y.id)})}o.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(t){K&&console.log("still need to scroll to "+t);var n=await this.annotator?.getAnnotationPosition(t,this.delegate.iframes[0].contentWindow);window.scrollTo(0,n-window.innerHeight/3)}async updateLocalHighlight(t){if(this.annotator){let n=await this.annotator.deleteAnnotation(t.id),i=await this.addAnnotation(t);return K&&(console.log("Highlight deleted "+JSON.stringify(n)),console.log("Highlight added "+JSON.stringify(i))),await this.showHighlights(),await this.drawHighlights(),this.delegate.rights.enableMaterial&&(0,U0.toast)({html:"highlight updated"}),i}else return new Promise(n=>n(null))}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return K&&console.log("Highlight deleted "+JSON.stringify(n)),await this.showHighlights(),await this.drawHighlights(),this.delegate.rights.enableMaterial&&(0,U0.toast)({html:"highlight deleted"}),n}else return new Promise(i=>i(null))}async deleteAnnotation(t){await this.deleteLocalHighlight(t.id)}async addAnnotation(t){await this.annotator?.saveAnnotation(t),await this.showHighlights(),await this.drawHighlights()}async deleteHighlight(t){this.api?.deleteAnnotation?this.api?.deleteAnnotation(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteSelectedHighlight(t){this.api?.deleteAnnotation?this.api.deleteAnnotation(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async updateAnnotation(t){this.api?.updateAnnotation?this.api.updateAnnotation(t).then(async()=>{this.updateLocalHighlight(t)}):this.updateLocalHighlight(t)}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.delegate.currentChapterLink.href);this.delegate.currentTocUrl&&(n=this.publication.getTOCItem(this.delegate.currentTocUrl)),n===void 0&&(n=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href));let i=this.delegate.view?.getCurrentPosition(),o=this.delegate.iframes[0].contentDocument;if(o){let l=Sr(o,"body"),s=t.position?t.position/l.scrollHeight:i,a=(0,aS.v4)(),u;if(n){let h=n.Href;if(h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let f=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),p=Math.ceil((s??0)*(f.length-1)),g=f[p];u=ln(it({},g),{id:a,href:h,created:new Date,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else u={id:a,href:h,locations:{progression:s},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(u)if(this.api?.addAnnotation){let h=await this.api.addAnnotation(u),f=await this.annotator.saveAnnotation(h);return await this.showHighlights(),await this.drawHighlights(),new Promise(p=>p(f))}else{let h=await this.annotator.saveAnnotation(u);return await this.showHighlights(),await this.drawHighlights(),new Promise(f=>f(h))}}}return new Promise(i=>i(null))}getAnnotations(){let t=[];return this.annotator&&(t=this.annotator.getAnnotations()),t}showHighlights(){let t=[];this.annotator&&(t=this.annotator.getAnnotations(),t&&(t=t.filter(n=>n.highlight.marker!==ot.Bookmark),t.forEach(n=>{Yt.push(n.highlight)}))),this.highlightsView&&this.createTree(hi.Annotation,t,this.highlightsView)}async drawHighlights(){if(this.rights.enableAnnotations&&this.highlighter){if(this.api){let n=[];if(this.annotator&&(n=this.annotator.getAnnotations()),this.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(nt.Annotation);for(let i of n){Yt.push(i.highlight);let o=i,l=this.delegate.currentChapterLink.href;var t=this.publication.getTOCItem(l);if(this.delegate.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let s=t.Href;s.indexOf("#")>0&&(s=s.slice(0,s.indexOf("#"))),o.href===s&&(await this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===ot.Underline){let a=await this.annotator?.getAnnotationPosition(i.id,this.delegate.iframes[0].contentWindow),u='<div class="comment" style="top: '+a+'px;width:20px"></div>',h=document.createElement("div");h.innerHTML=u;let f=h.childNodes[0],p=document.createElement("i");p.innerHTML="sticky_note_2",p.className="material-icons",p.style.color=o.highlight.color,f.appendChild(p),ve(h,"click",g=>{g.preventDefault(),g.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}else{let n=[];if(this.annotator&&(n=this.annotator.getAnnotations()),this.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(nt.Annotation);for(let i of n){Yt.push(i.highlight);let o=i,l=this.delegate.currentChapterLink.href,s=this.publication.getTOCItem(l);if(this.delegate.currentTocUrl&&(s=this.publication.getTOCItem(this.delegate.currentTocUrl)),s===null&&(s=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),s){let a=s.Href;a.indexOf("#")>0&&(a=a.slice(0,a.indexOf("#"))),o.href===a&&(await this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===ot.Underline){let u=await this.annotator?.getAnnotationPosition(i.id,this.delegate.iframes[0].contentWindow),h='<div class="comment" style="top: '+u+"px;background: "+o.highlight?.color+';width:20px"></div>',f=document.createElement("div");f.innerHTML=h,f.childNodes[0].innerHTML=$i.note,ve(f,"click",p=>{p.preventDefault(),p.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor)}}createTree(t,n,i){if(n){let o=this,l=this.publication.readingOrder;if(l.length){let s=(a,u)=>{let h=document.createElement("ul");h.className="sidenav-annotations";for(let f of u){let p=document.createElement("li"),g=document.createElement("a"),y=document.createElement("span");if(g.tabIndex=-1,g.className="chapter-link",f.Href){let b=this.publication.getAbsoluteHref(f.Href),w=this.publication.getTOCItemAbsolute(b);g.href=b,g.innerHTML=w?.Title||"",p.appendChild(g)}else y.innerHTML=f.Title||"",y.className="chapter-title",p.appendChild(y);ve(g,"click",b=>{b.preventDefault(),b.stopPropagation();let w={href:g.href,locations:{progression:0},type:f.TypeLink,title:g.title};this.delegate.stopReadAloud(),this.delegate.navigate(w)});let E=document.createElement("ol");n.forEach(function(b){let w=f.Href.indexOf("#")!==-1?f.Href.slice(0,f.Href.indexOf("#")):f.Href;if(f.Href&&b.href.endsWith(w)){let _=document.createElement("li");_.className="annotation-item";let S=document.createElement("a");if(S.setAttribute("href",b.href),t===hi.Annotation){S.className="highlight-link";let R=document.createElement("span"),C=document.createElement("span");if(R.className="title",C.innerHTML=b.highlight.selectionInfo.cleanText,b.highlight?.marker===ot.Underline)if(typeof b.highlight?.color=="object"){let N=b.highlight?.color;N&&C.style.setProperty("border-bottom",`2px solid ${Ge.hexToRgbA(N)}`,"important")}else C.style.setProperty("border-bottom",`2px solid ${b.highlight?.color}`,"important");else if(typeof b.highlight?.color=="object"){let N=b.highlight?.color;N&&(C.style.backgroundColor=Ge.hexToRgbA(N))}else{let N=b.highlight?.color;N&&(C.style.backgroundColor=N)}R.appendChild(C),S.appendChild(R);let I=document.createElement("span"),z=Math.round((b.locations.progression??0)*100)+"% through resource";I.className="subtitle",I.innerHTML=z,S.appendChild(I)}let x=document.createElement("span");if(x.className="timestamp",x.innerHTML=nl.readableTimestamp(b.created),S.appendChild(x),ve(S,"click",R=>{R.preventDefault(),R.stopPropagation(),o.handleAnnotationLinkClick(R,b)}),_.appendChild(S),o.delegate.sideNavExpanded&&o.delegate.rights.enableMaterial||!o.delegate.rights.enableMaterial){let R=document.createElement("button");R.className="delete",R.innerHTML=$i.delete,ve(R,"click",C=>{C.preventDefault(),C.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,C,b)}),_.appendChild(R)}E.appendChild(_)}}),E.children.length>0&&(h.appendChild(p),h.appendChild(E)),h.children.length>0&&a.appendChild(h),f.Children&&f.Children.length>0&&s(a,f.Children)}};i.innerHTML="",s(i,l)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.delegate.stopReadAloud(),this.delegate.navigate(n)):K&&console.log("annotation data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){K&&console.log("annotation data locator: ",i),i?t===hi.Annotation&&this.deleteHighlight(i):K&&console.log("annotation data missing: ",n)}static readableTimestamp(t){let n=new Date(t);return n.toDateString()+" "+n.toLocaleTimeString()}async getAnnotation(t){return this.annotator?.getAnnotation(t)}async getAnnotationByID(t){return this.annotator?.getAnnotationByID(t)}};T();var $o=At(Ad()),W0=At($0());var il=class{static async create(t){let n=new this(t.annotator,t.rights||{enableBookmarks:!1},t.publication,t.delegate,t,t.initialAnnotations,t.api,t.headerMenu);return await n.start(),new Promise(i=>i(n))}constructor(t,n,i,o,l,s,a,u){this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=u,this.delegate=o,this.initialAnnotations=s,this.properties=l,this.api=a}stop(){K&&console.log("Bookmark module stop")}async start(){if(this.delegate.bookmarkModule=this,this.headerMenu&&(this.bookmarksView=xe(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=xe(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){var t=xe(this.headerMenu,"#menu-button-bookmark");this.rights.enableMaterial?(t&&t.parentElement?.style.removeProperty("display"),t&&ve(t,"click",this.saveBookmark.bind(this))):(t&&t.parentElement?.style.setProperty("display","none"),this.sideNavSectionBookmarks&&this.sideNavSectionBookmarks.style.setProperty("display","none"))}if(this.initialAnnotations){var n=this.initialAnnotations.bookmarks||null;n&&this.annotator?.initBookmarks(n)}await this.showBookmarks(),await this.drawBookmarks(),setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("highlights"):this.delegate.showLayer("highlights")},10)}async handleResize(){setTimeout(async()=>{await this.drawBookmarks(),await this.showBookmarks()},100)}initialize(){return new Promise(async t=>{await document.fonts.ready,this.rights.enableBookmarks&&setTimeout(()=>{this.drawBookmarks(),this.showBookmarks()},300),t(null)})}async deleteBookmark(t){if(this.annotator)if(this.api?.deleteBookmark){await this.api?.deleteBookmark(t);let n=await this.annotator.deleteBookmark(t);return K&&console.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),this.delegate.rights.enableMaterial&&(0,$o.toast)({html:"bookmark deleted"}),n}else{let n=await this.annotator.deleteBookmark(t);return K&&console.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),this.delegate.rights.enableMaterial&&(0,$o.toast)({html:"bookmark deleted"}),n}else return new Promise(n=>n(null))}async saveBookmarkPlus(){await this.addBookmarkPlus()}async saveBookmark(){if(this.annotator){var t=this.publication.getTOCItem(this.delegate.currentChapterLink.href);if(this.delegate.currentTocUrl&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let n=t.Href;n.indexOf("#")>0&&(n=n.slice(0,n.indexOf("#")));let i=this.delegate.view?.getCurrentPosition(),o=(0,W0.v4)(),l;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let s=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),a=Math.ceil((i??0)*(s.length-1)),u=s[a];l=ln(it({},u),{id:o,href:n,created:new Date,title:this.delegate.currentChapterLink.title})}else l={id:o,href:n,locations:{progression:i},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title};if(this.annotator.locatorExists(l,hi.Bookmark))this.delegate.rights.enableMaterial&&(0,$o.toast)({html:"bookmark exists"});else if(this.api?.addBookmark){let s=await this.api.addBookmark(l);s&&(l=s),K&&console.log(l);let a=this.annotator.saveBookmark(l);return K&&console.log("Bookmark added "+JSON.stringify(a)),this.delegate.rights.enableMaterial&&(0,$o.toast)({html:"bookmark added"}),this.showBookmarks(),await this.drawBookmarks(),a}else{let s=this.annotator.saveBookmark(l);return K&&console.log("Bookmark added "+JSON.stringify(s)),this.delegate.rights.enableMaterial&&(0,$o.toast)({html:"bookmark added"}),this.showBookmarks(),await this.drawBookmarks(),s}}}}async addBookmarkPlus(){let t=this,n=this.delegate.highlighter?.visibleTextRects[0],i=this.delegate.iframes[0].contentDocument;if(i){let a=this.delegate.highlighter?.dom(i.body).getWindow().document.createRange(),u=this.delegate.highlighter?.dom(this.delegate.iframes[0].contentDocument?.body).getSelection();u.removeAllRanges(),n&&a.selectNodeContents(n.node),u.addRange(a);let h=_d(a,!1),f=0;for(let p of h){if(!this.delegate.highlighter?.isOutsideViewport(p)){let g=u.focusNode,y=u.focusOffset;u.collapse(u.anchorNode,u.anchorOffset);for(let _=0;_<f;_++)u.modify("move","forward","line");u.extend(g,y);let E=u.focusNode,b=u.focusNode.length;u.collapse(u.anchorNode,u.anchorOffset);let w=b;u.anchorOffset>b?w=b:w=u.anchorOffset+1,u.modify("move","forward","character"),u.modify("move","backward","word"),u.extend(E,w),u.modify("extend","backward","character"),u.modify("extend","forward","word");break}f++}}function o(a){let u={},h=t.delegate.iframes[0].contentDocument;if(h)return Dn(a,t.delegate.highlighter?.dom(h.body).getDocument(),u)}let l=this.delegate.iframes[0].contentWindow,s={id:"bookmarkIcon",marker:ot.Bookmark,icon:{id:"bookmarkIcon",title:"Bookmark",svgPath:'<path d="M0 0h24v24H0V0z" fill="none"/><path d="M17 3H7c-1.1 0-2 .9-2 2v16l7-3 7 3V5c0-1.1-.9-2-2-2z"/>',color:"#000000",position:"left"},popup:{background:"#000000",textColor:"#ffffff"},highlight:{color:"#000000",style:{default:[{property:"border-bottom",value:"0px dashed #000000",priority:"important"}]}}};if(l!==null){let a=Qr(l,o),u=t.delegate.iframes[0].contentDocument;if(a&&u){let h=this.delegate.highlighter?.createHighlight(this.delegate.highlighter?.dom(u.body).getWindow(),a,s.highlight?.color,!0,ot.Bookmark,s.icon,s.popup,s.highlight?.style);if(this.delegate.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),h)return this.saveAnnotation(h[0]).then(f=>{K&&console.log("saved bookmark "+f?.id)})}}}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.delegate.currentChapterLink.href);this.delegate.currentTocUrl&&(n=this.publication.getTOCItem(this.delegate.currentTocUrl)),n===null&&(n=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href));let i=this.delegate.view?.getCurrentPosition(),o=this.delegate.iframes[0].contentDocument;if(o){let l=Sr(o,"body"),s=t.position?t.position/l.scrollHeight:i,a=(0,W0.v4)(),u;if(n){let h=n.Href;if(h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let f=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),p=Math.ceil((s??0)*(f.length-1)),g=f[p];u=ln(it({},g),{id:a,href:h,created:new Date,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else u={id:a,href:h,locations:{progression:s},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(u)if(this.api?.addBookmark){let h=await this.api.addBookmark(u),f=await this.annotator.saveAnnotation(h);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(p=>p(f))}else{let h=await this.annotator.saveAnnotation(u);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(f=>f(h))}}}return new Promise(i=>i(void 0))}getBookmarks(){let t=[];return this.annotator&&(t=this.annotator.getBookmarks()),t}showBookmarks(){let t=[];this.annotator&&(t=this.annotator.getBookmarks());let n=[];this.annotator&&(n=this.annotator.getAnnotations(),n&&(n=n.filter(i=>i.highlight.marker===ot.Bookmark),t?t.push.apply(t,n):t=n)),this.bookmarksView&&this.createTree(hi.Bookmark,t,this.bookmarksView)}async drawBookmarks(){if(this.rights.enableBookmarks&&this.delegate.highlighter)if(this.api){let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.delegate.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.delegate.highlighter.destroyHighlights(nt.Annotation);for(let i of n){Yt.push(i.highlight);let o=i,l=this.delegate.currentChapterLink.href;var t=this.publication.getTOCItem(l);if(this.delegate.currentTocUrl&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let s=t.Href;s.indexOf("#")>0&&(s=s.slice(0,s.indexOf("#"))),o.href===s&&await this.delegate.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight)}}}}else{let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.delegate.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.delegate.highlighter.destroyHighlights(nt.Annotation);for(let i of n){Yt.push(i.highlight);let o=i,l=this.delegate.currentChapterLink.href,s=this.publication.getTOCItem(l);if(this.delegate.currentTocUrl&&(s=this.publication.getTOCItem(this.delegate.currentTocUrl)),s===void 0&&(s=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),s){let a=s.Href;a.indexOf("#")>0&&(a=a.slice(0,a.indexOf("#"))),o.href===a&&await this.delegate.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight)}}}}}async deleteSelectedHighlight(t){this.api?.deleteBookmark?this.api.deleteBookmark(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return K&&console.log("Highlight deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),this.delegate.rights.enableMaterial&&(0,$o.toast)({html:"highlight deleted"}),n}else return new Promise(i=>i(null))}createTree(t,n,i){if(n){let o=this,l=this.publication.readingOrder;if(l.length){let s=(a,u)=>{let h=document.createElement("ul");h.className="sidenav-annotations";for(let f of u){let p=document.createElement("li"),g=document.createElement("a"),y=document.createElement("span");if(g.tabIndex=-1,g.className="chapter-link",f.Href){let b=this.publication.getAbsoluteHref(f.Href),w=this.publication.getTOCItemAbsolute(b);g.href=b,g.innerHTML=w?.Title||"",p.appendChild(g)}else y.innerHTML=f.Title||"",y.className="chapter-title",p.appendChild(y);ve(g,"click",b=>{b.preventDefault(),b.stopPropagation();let w={href:g.href,locations:{progression:0},type:f.TypeLink,title:g.title};this.delegate.stopReadAloud(),this.delegate.navigate(w)});let E=document.createElement("ol");n.forEach(function(b){let w=f.Href.indexOf("#")!==-1?f.Href.slice(0,f.Href.indexOf("#")):f.Href;if(f.Href&&b.href.endsWith(w)){let _=document.createElement("li");_.className="annotation-item";let S=document.createElement("a");if(S.setAttribute("href",b.href),t===hi.Bookmark){S.className="bookmark-link";let R=document.createElement("span"),C=Math.round((b.locations.progression??0)*100)+"% through resource";R.className="title",R.innerHTML=C,S.appendChild(R)}let x=document.createElement("span");if(x.className="timestamp",x.innerHTML=il.readableTimestamp(b.created),S.appendChild(x),ve(S,"click",R=>{R.preventDefault(),R.stopPropagation(),o.handleAnnotationLinkClick(R,b)}),_.appendChild(S),o.delegate.sideNavExpanded&&o.delegate.rights.enableMaterial||!o.delegate.rights.enableMaterial){let R=document.createElement("button");R.className="delete",R.innerHTML=$i.delete,ve(R,"click",C=>{C.preventDefault(),C.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,C,b)}),_.appendChild(R)}E.appendChild(_)}}),E.children.length>0&&(h.appendChild(p),h.appendChild(E)),h.children.length>0&&a.appendChild(h),f.Children&&f.Children.length>0&&s(a,f.Children)}};i.innerHTML="",s(i,l)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.delegate.stopReadAloud(),this.delegate.navigate(n)):K&&console.log("bookmark data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){K&&console.log("bookmark data locator: ",i),i?t===hi.Bookmark&&this.deleteBookmark(i):K&&console.log("bookmark data missing: ",n)}static readableTimestamp(t){let n=new Date(t);return n.toDateString()+" "+n.toLocaleTimeString()}async getAnnotation(t){return this.annotator?.getAnnotation(t)}async getAnnotationByID(t){return this.annotator?.getAnnotationByID(t)}};T();var uS=At(cS());T();var z0="r2-mo-active",Wo=class{},Ve=Wo;Ve.COLOR_REF="color",Ve.AUTO_SCROLL_REF="autoscroll",Ve.AUTO_TURN_REF="autoturn",Ve.VOLUME_REF="volume",Ve.RATE_REF="rate",Ve.COLOR_KEY="mediaoverlay-"+Wo.COLOR_REF,Ve.AUTO_SCROLL_KEY="mediaoverlay-"+Wo.AUTO_SCROLL_REF,Ve.AUTO_TURN_KEY="mediaoverlay-"+Wo.AUTO_TURN_REF,Ve.VOLUME_KEY="mediaoverlay-"+Wo.VOLUME_REF,Ve.RATE_KEY="mediaoverlay-"+Wo.RATE_REF;var V0=class{constructor(t,n,i){this.MEDIAOVERLAYSETTINGS="mediaOverlaySetting";this.color="r2-mo-active";this.autoScroll=!0;this.autoTurn=!0;this.volume=1;this.rate=1;this.playing=!1;this.resourceReady=!1;this.wait=1;this.settingsChangeCallback=()=>{};this.store=t,this.api=n,this.headerMenu=i,this.initialise(),console.log(this.api)}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialMediaOverlaySettings){let i=t.initialMediaOverlaySettings;i?.color&&(n.color=i.color,K&&console.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,K&&console.log(n.autoScroll)),i?.autoTurn&&(n.autoTurn=i.autoTurn,K&&console.log(n.autoTurn)),i?.volume&&(n.volume=i.volume,K&&console.log(n.volume)),i?.rate&&(n.rate=i.rate,K&&console.log(n.rate)),i?.wait&&(n.wait=i.wait,K&&console.log(n.wait))}return n.initializeSelections(),n}stop(){K&&console.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(Ve.AUTO_SCROLL_KEY)!=null?this.getProperty(Ve.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(Ve.AUTO_TURN_KEY)!=null?this.getProperty(Ve.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(Ve.COLOR_KEY)!=null?this.getProperty(Ve.COLOR_KEY).value:this.color,this.volume=this.getProperty(Ve.VOLUME_KEY)!=null?this.getProperty(Ve.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(Ve.RATE_KEY)!=null?this.getProperty(Ve.RATE_KEY).value:this.rate,this.userProperties=this.getMediaOverlaySettings()}reset(){this.color="redtext",this.autoScroll=!0,this.autoTurn=!0,this.volume=1,this.rate=1,this.wait=1,this.userProperties=this.getMediaOverlaySettings()}initializeSelections(){this.headerMenu&&(this.settingsView=xe(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechAutoTurn=xe(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=xe(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=xe(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=xe(this.headerMenu,"#mediaOverlayRate")),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),this.speechAutoTurn&&(this.speechAutoTurn.checked=this.autoTurn),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechRate&&(this.speechRate.value=this.volume.toString()),ve(xe(t,"ul"),"click",n=>{n.stopPropagation()})}onSettingsChange(t){this.settingsChangeCallback=t}storeProperty(t){this.updateUserSettings(),this.saveProperty(t)}updateUserSettings(){let t={color:this.userProperties.getByRef(Ve.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Ve.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(Ve.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(Ve.VOLUME_REF)?.value,rate:this.userProperties.getByRef(Ve.RATE_REF)?.value};this.applyMediaOverlaySettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{K&&console.log("api updated sync settings",n)})}getMediaOverlaySettings(){let t=new _r;return t.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,Ve.AUTO_SCROLL_REF,Ve.AUTO_SCROLL_KEY),t.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,Ve.AUTO_TURN_REF,Ve.AUTO_TURN_KEY),t.addStringable(this.color,Ve.COLOR_REF,Ve.COLOR_KEY),t.addIncremental(this.volume,.1,1,.1,"",Ve.VOLUME_REF,Ve.VOLUME_KEY),t.addIncremental(this.rate,.1,3,.1,"",Ve.RATE_REF,Ve.RATE_KEY),t}saveProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}return t}getProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}resetMediaOverlaySettings(){this.store.remove(this.MEDIAOVERLAYSETTINGS),this.reset(),this.settingsChangeCallback()}applyMediaOverlaySettings(t){if(t.color){this.color=t.color;let n=this.userProperties.getByRef(Ve.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){K&&console.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Ve.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoTurn!==void 0){K&&console.log("autoTurn "+this.autoTurn),this.autoTurn=t.autoTurn;let n=this.userProperties.getByRef(Ve.AUTO_TURN_REF);n&&(n.value=this.autoTurn,this.saveProperty(n)),this.settingsChangeCallback()}if(t.volume){K&&console.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Ve.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback()}if(t.rate){K&&console.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Ve.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback()}}applyMediaOverlaySetting(t,n){if(t===Ve.COLOR_REF){this.color=n;let i=this.userProperties.getByRef(Ve.COLOR_REF);i&&(i.value=this.color,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===Ve.AUTO_SCROLL_REF){this.autoScroll=n;let i=this.userProperties.getByRef(Ve.AUTO_SCROLL_REF);i&&(i.value=this.autoScroll,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===Ve.AUTO_TURN_REF){this.autoTurn=n;let i=this.userProperties.getByRef(Ve.AUTO_TURN_REF);i&&(i.value=this.autoTurn,this.saveProperty(i)),this.settingsChangeCallback()}}increase(t){if(t==="mo_volume"){this.userProperties.getByRef(Ve.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(Ve.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Ve.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Ve.RATE_REF).increment(),this.rate=this.userProperties.getByRef(Ve.RATE_REF)?.value;let n=this.userProperties.getByRef(Ve.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}decrease(t){if(t==="mo_volume"){this.userProperties.getByRef(Ve.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(Ve.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Ve.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Ve.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(Ve.RATE_REF)?.value;let n=this.userProperties.getByRef(Ve.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}};var G0=class{constructor(t,n,i,o){this.play=xe(document,"#menu-button-play");this.pause=xe(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async t=>{K&&console.log("ontimeupdate"),this.trackCurrentTime()};this.ensureOnTimeUpdate=(t,n)=>{this.audioElement&&(t?this.__ontimeupdate&&(this.__ontimeupdate=!1,this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),cancelAnimationFrame(this.myReq)):(!this.__ontimeupdate||n)&&(this.__ontimeupdate=!0,n&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),this.audioElement.addEventListener("timeupdate",this.ontimeupdate)))};this.delegate=t,this.publication=n,this.settings=i,this.properties=o}static create(t){let n=new this(t.delegate,t.publication,t.settings,t);return n.start(),n}stop(){K&&console.log("MediaOverlay module stop")}start(){this.delegate.mediaOverlayModule=this,K&&console.log("MediaOverlay module start")}async initialize(){return new Promise(async t=>{await document.fonts.ready,this.settings.setControls(),this.settings.onSettingsChange(()=>{this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}),t()})}async initializeResource(t){this.currentLinks=t,this.currentLinkIndex=0,await this.playLink()}async playLink(){let t=this.currentLinks[this.currentLinkIndex];if(t?.Properties?.MediaOverlay){this.ensureOnTimeUpdate(!1,!1);let n=t.Properties?.MediaOverlay,o=new URL(n,this.publication.manifestUrl).toString(),l;try{l=await fetch(o)}catch(h){console.error(h,o);return}l.ok||K&&console.log("BAD RESPONSE?!");let s;try{s=await l.json()}catch(h){console.error(h)}if(!s){K&&console.log("## moJson"+s);return}t.MediaOverlays=xu(s,uS.MediaOverlayNode),t.MediaOverlays.initialized=!0;let a=t.HrefDecoded||t.Href,u=new URL("https://dita.digital/"+a);await this.playMediaOverlays(u.pathname.substr(1),t.MediaOverlays,void 0)}else this.audioElement&&await this.audioElement.pause(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud()}async startReadAloud(){if(this.delegate.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement){let t=this.currentAudioBegin?this.currentAudioBegin:0;this.audioElement.currentTime=t,await this.audioElement.play(),this.ensureOnTimeUpdate(!1,!0),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}else this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?this.delegate.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&(this.pause.style.display="block")}}async stopReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.currentLinkIndex>0&&await this.playLink(),this.settings.playing=!1,this.audioElement?.pause(),this.play&&(this.play.style.display="block"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&(this.play.style.display="block"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&(this.pause.style.display="block"))}findDepthFirstTextAudioPair(t,n,i){K&&console.log("findDepthFirstTextAudioPair()");let o,l;if(n.Text){let u=new URL("https://dita.digital/"+n.Text);if(u.pathname.substr(1)===t){if(o=!0,u.hash&&i){l=!1;let h=u.hash.substr(1);for(let f of i)if(f===h){l=!0;break}}}else o=!1}if(K&&(console.log("isFragmentIDMatch: "+l),console.log("isTextUrlMatch: "+o)),!n.Children||!n.Children.length){if(K&&console.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!o){K&&console.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return l||o&&!i?(K&&console.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),n):void 0}let s=i,a=i;for(let u of n.Children){K&&(console.log("findDepthFirstTextAudioPair() - child"),console.log(JSON.stringify(u)));let h=this.findDepthFirstTextAudioPair(t,u,a);if(h===null&&(K&&console.log("findDepthFirstTextAudioPair() - child - match null (skip)"),a=void 0),h)return K&&(console.log("findDepthFirstTextAudioPair() - child - match"),console.log(JSON.stringify(h))),h}if(l){K&&console.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let u=this.findDepthFirstTextAudioPair(t,n,void 0);return u&&(K&&(console.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),console.log(JSON.stringify(u))),u)}if(s&&!a)return null}trackCurrentTime(){if(cancelAnimationFrame(this.myReq),this.mediaOverlayTextAudioPair)try{this.currentAudioEnd&&this.audioElement.currentTime>=this.currentAudioEnd-.05&&(K&&console.log("ontimeupdate - mediaOverlaysNext()"),this.mediaOverlaysNext());let t=this.mediaOverlayTextAudioPair.Text.lastIndexOf("#"),n=this.mediaOverlayTextAudioPair.Text.substr(t+1);this.mediaOverlayHighlight(n),this.myReq=requestAnimationFrame(this.trackCurrentTime.bind(this))}catch(t){}}mediaOverlaysNext(t){if(K&&console.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let n=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!t);if(!n)K&&console.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud());else{let i=!1;if(this.mediaOverlayTextAudioPair.Text&&n.Text){let o=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),l=new URL("https://dita.digital/"+n.Text);o.pathname!==l.pathname&&(K&&console.log("mediaOverlaysNext() SWITCH! "+o.pathname+" != "+l.pathname),i=!0)}i?this.mediaOverlaysStop():(K&&console.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(n,void 0,void 0)},0))}}else K&&console.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){K&&console.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){K&&console.log("mediaOverlaysPause()"),this.mediaOverlayHighlight(void 0),this.audioElement&&this.audioElement.pause()}findNextTextAudioPair(t,n,i,o){if(!t.Children||!t.Children.length){if(i?.prev===n)return K&&console.log("findNextTextAudioPair() - prevMo === moToMatch"),t;K&&(console.log("findNextTextAudioPair() - set previous"),console.log(JSON.stringify(t))),i.prev=t;return}for(let l of t.Children){K&&(console.log("findNextTextAudioPair() - child"),console.log(JSON.stringify(l)));let s=this.findNextTextAudioPair(l,n,i,o);if(s)return K&&(console.log("findNextTextAudioPair() - match"),console.log(JSON.stringify(s))),s}}async playMediaOverlaysAudio(t,n,i){if(K&&console.log("playMediaOverlaysAudio()"),this.mediaOverlayTextAudioPair=t,!t.Audio)return;let o=new URL(t.Audio,this.publication.manifestUrl),l=o.toString(),s=new URL(l);s.hash="",s.search="";let a=s.toString(),u=typeof n!="undefined",h=typeof i!="undefined";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!u&&!h){if(o.hash){let p=o.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(p&&p.length>=1){let g=p[1];try{this.currentAudioBegin=parseFloat(g)}catch(y){console.log(y)}if(p.length>=3){let y=p[3];try{this.currentAudioEnd=parseFloat(y)}catch(E){console.log(E)}}}}}else this.currentAudioBegin=n,this.currentAudioEnd=i;K&&console.log(`${l} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let f=async p=>{if(!this.audioElement)return;let g=this.currentAudioBegin?this.currentAudioBegin:0;if(p||this.audioElement.paused)if(p&&!g||this.audioElement.currentTime===g){if(K&&console.log("playMediaOverlaysAudio() - playClip() - _currentAudioElement.play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing){let E=function(){y.settings.resourceReady?setTimeout(async()=>{await y.audioElement.play(),y.ensureOnTimeUpdate(!1,!0)},y.settings.wait*1e3):setTimeout(E,200)},y=this;E()}}else{K&&console.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let y=async E=>{if(this.audioElement.removeEventListener("timeupdate",y),K&&console.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked - .play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement&&(this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing)){let w=function(){b.settings.resourceReady?setTimeout(async()=>{await b.audioElement.play(),b.ensureOnTimeUpdate(!1,!0)},b.settings.wait*1e3):setTimeout(w,200)},b=this;w()}};this.audioElement.addEventListener("timeupdate",y),this.audioElement.currentTime=g}else{let y=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd!="undefined"&&this.previousAudioEnd>g-.02&&this.previousAudioEnd<=g&&this.audioElement.currentTime>=g-.1;this.ensureOnTimeUpdate(!1,!1),y?K&&console.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(K&&console.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=g)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||a!==this.currentAudioUrl){this.currentAudioUrl=a,K&&console.log("playMediaOverlaysAudio() - RESET: "+this.previousAudioUrl+" => "+this.currentAudioUrl),this.audioElement=document.getElementById("AUDIO_MO_ID"),this.audioElement&&(this.audioElement.pause(),this.audioElement.setAttribute("src",""),this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement)),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("style","display: none"),this.audioElement.setAttribute("id","AUDIO_MO_ID"),this.audioElement.setAttribute("role","media-overlays"),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate,document.body.appendChild(this.audioElement),this.audioElement.addEventListener("error",y=>{console.log("-1) error: "+(this.currentAudioUrl!==y.currentTarget.src?this.currentAudioUrl+" -- ":"")+y.currentTarget.src.substr(y.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(console.log(this.audioElement.error.code),console.log(this.audioElement.error.message))});let p=async y=>{y.currentTarget.removeEventListener("canplaythrough",p),K&&console.log("oncanplaythrough"),await f(!0)};this.audioElement.addEventListener("canplaythrough",p);let g=async y=>{K&&console.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",g),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else K&&console.log("playMediaOverlaysAudio() - playClip()"),await f(!1)}async playMediaOverlays(t,n,i){K&&console.log("playMediaOverlays()");let o=i?i.filter(s=>s):void 0;o&&o.length===0&&(o=void 0);let l=this.findDepthFirstTextAudioPair(t,n,o);!l&&o&&(K&&(console.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),console.log(JSON.stringify(o,null,4)),console.log(JSON.stringify(n,null,4))),l=this.findDepthFirstTextAudioPair(t,n,void 0)),l?l.Audio&&(K&&console.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=n,await this.playMediaOverlaysAudio(l,void 0,void 0)):K&&console.log("playMediaOverlays() - !moTextAudioPair "+t)}mediaOverlayHighlight(t){K&&console.log("moHighlight: ## "+t);let n=this.publication.Metadata?.MediaOverlay?.ActiveClass;n||(n=this.settings.color);let i=this.delegate.iframes[0].contentDocument?.documentElement.getAttribute("style"),o=i?i.indexOf("readium-night-on")>0:!1,l=i?i.indexOf("readium-sepia-on")>0:!1;if((this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&(n=o||l?z0:n||z0),this.pid){let a;this.currentLinkIndex===0?a=this.delegate.iframes[0].contentDocument?.getElementById(this.pid):a=this.delegate.iframes[1].contentDocument?.getElementById(this.pid),a&&a.classList.remove(n)}let s;t&&(this.currentLinkIndex===0?s=this.delegate.iframes[0].contentDocument?.getElementById(t):s=this.delegate.iframes[1].contentDocument?.getElementById(t),s&&s.classList.add(n),this.pid=t),s&&(this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&s.scrollIntoView({block:"center",behavior:"smooth"})}};T();var J0=class{static async create(t){let n=new this(t.delegate,t.publication);return await n.start(),n}constructor(t,n){this.delegate=t,this.publication=n}async stop(){K&&console.log("Timeline module stop")}async start(){this.delegate.timelineModule=this,this.timelineContainer=xe(document,"#container-view-timeline"),this.delegate.rights.enableMaterial&&(this.positionSlider=xe(document,"#positionSlider")),this.publication.positions?this.positionSlider&&(this.positionSlider.style.display="block"):this.positionSlider&&(this.positionSlider.style.display="none")}async initialize(){return new Promise(async t=>{await document.fonts.ready;let n=this.delegate.currentLocator();this.delegate.rights.enableMaterial&&(this.delegate.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions)&&(this.positionSlider&&(this.positionSlider.value=(n.locations.position??0).toString()),this.positionSlider&&(this.positionSlider.max=((n.locations.totalRemainingPositions??0)+(n.locations.position??0)).toString())),this.timelineContainer&&(this.timelineContainer.innerHTML=""),this.publication.readingOrder?.forEach(i=>{let o=this.publication.getAbsoluteHref(i.Href),l=this.publication.getTOCItemAbsolute(o),s=l?.Href.indexOf("#")!==-1?l?.Href.slice(0,l?.Href.indexOf("#")):l.Href,a=this.publication.getAbsoluteHref(s??"");var u;this.publication.positions&&this.delegate.view?.layout!=="fixed"?i.contentWeight?u=i.contentWeight:u=1:u=100/(this.publication.readingOrder?.length??0);var h=document.createElement("div");if(h.style.height=u+"%",h.style.width="100%",h.className="chapter",l?.Title!==void 0){var f=document.createElement("span");f.innerHTML=l.Title,f.className="chapter-tooltip",h.appendChild(f)}ve(h,"click",p=>{p.preventDefault(),p.stopPropagation();var g;this.publication.positions||this.delegate.rights.autoGeneratePositions&&this.publication.positions?(g=it({},this.publication.positions.filter(y=>y.href===i.Href)[0]),g.href=this.publication.getAbsoluteHref(g.href)):g={href:a,locations:{progression:0},type:i.TypeLink,title:i.Title},K&&console.log(g),this.delegate.navigate(g)}),a===this.delegate.currentChapterLink.href?h.className+=" active":h.className=h.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(h)}),t()})}};T();var pg=At(Zr());var FO=At(HO()),ao=At(jO()),qd=class{constructor(t,n){this.hasEventListener=!1;this.isHacked=!1;this.delegate=t,this.properties=n}static async setupPreloadProtection(t){if(this.isCurrentBrowserSupported(t))t.detectInspect&&await this.startInspectorProtection(t);else throw new Error("Browser not supported")}static async create(t){let n=new this(t.delegate,t);return await n.start(),n}static async startInspectorProtection(t){let n=()=>{t.clearOnInspect&&(console.clear(),window.localStorage.clear(),window.sessionStorage.clear(),window.location.replace(window.location.origin)),typeof t.api?.inspectDetected=="function"&&t.api.inspectDetected()},i=new ao.DevtoolsDetector({checkers:[ao.checkers.elementIdChecker,ao.checkers.regToStringChecker,ao.checkers.functionToStringChecker,ao.checkers.depRegToStringChecker,ao.checkers.dateToStringChecker]});i.addListener(n),i.launch(),await Ow(t.detectInspectInitDelay??50)}static isCurrentBrowserSupported(t){if(!t.enforceSupportedBrowsers)return!0;let n=[];return(t.supportedBrowsers??[]).forEach(o=>{n.push("last 1 "+o+" version")}),(0,FO.getUserAgentRegExp)({browsers:n,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.delegate.contentProtectionModule=this,this.properties?.enableObfuscation){this.wrapper=St(document,"#iframe-wrapper"),this.securityContainer=xe(document,"#container-view-security");var t=this;this.mutationObserver=new MutationObserver(function(n){n.forEach(function(i){K&&console.log(i.type),t.isHacked=!0})})}}async stop(){if(K&&console.log("Protection module stop"),this.mutationObserver.disconnect(),this.properties?.disableKeys){He(this.delegate.mainElement,"keydown",this.disableSave),He(this.delegate.headerMenu,"keydown",this.disableSave);for(let t of this.delegate.iframes)He(t.contentDocument,"keydown",this.disableSave),He(t.contentWindow,"keydown",this.disableSave);He(window,"keydown",this.disableSave),He(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){He(this.delegate.mainElement,"copy",this.preventCopy),He(this.delegate.headerMenu,"copy",this.preventCopy);for(let t of this.delegate.iframes)He(t.contentDocument,"copy",this.preventCopy),He(t.contentWindow,"copy",this.preventCopy);He(window,"copy",this.preventCopy),He(document,"copy",this.preventCopy),He(this.delegate.mainElement,"cut",this.preventCopy),He(this.delegate.headerMenu,"cut",this.preventCopy);for(let t of this.delegate.iframes)He(t.contentDocument,"cut",this.preventCopy),He(t.contentWindow,"cut",this.preventCopy);He(window,"cut",this.preventCopy),He(document,"cut",this.preventCopy)}if(this.properties?.disablePrint){He(this.delegate.mainElement,"beforeprint",this.beforePrint.bind(this)),He(this.delegate.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let t of this.delegate.iframes)He(t.contentDocument,"beforeprint",this.beforePrint),He(t.contentWindow,"beforeprint",this.beforePrint);He(window,"beforeprint",this.beforePrint),He(document,"beforeprint",this.beforePrint),He(this.delegate.mainElement,"afterprint",this.afterPrint.bind(this)),He(this.delegate.headerMenu,"afterprint",this.afterPrint.bind(this));for(let t of this.delegate.iframes)He(t.contentDocument,"afterprint",this.afterPrint.bind(this)),He(t.contentWindow,"afterprint",this.afterPrint.bind(this));He(window,"afterprint",this.afterPrint.bind(this)),He(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){He(this.delegate.mainElement,"contextmenu",this.disableContext),He(this.delegate.headerMenu,"contextmenu",this.disableContext);for(let t of this.delegate.iframes)He(t.contentDocument,"contextmenu",this.disableContext),He(t.contentWindow,"contextmenu",this.disableContext);He(window,"contextmenu",this.disableContext),He(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),He(this.wrapper,"scroll",this.handleScroll.bind(this))}observe(){if(this.properties?.enableObfuscation){this.securityContainer.hasAttribute("style")&&(this.isHacked=!0),this.mutationObserver.disconnect();var t={attributes:!0,childList:!0,characterData:!0};this.mutationObserver.observe(this.securityContainer,t)}}async deactivate(){this.properties?.enableObfuscation&&(this.observe(),this.rects.forEach(t=>this.deactivateRect(t,this.securityContainer,this.isHacked)))}async activate(){if(this.properties?.enableObfuscation){this.observe();for(let t of this.delegate.iframes)if(t.contentDocument){let n=Sr(t.contentDocument,"body");this.rects=this.findRects(n),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){ve(this.delegate.mainElement,"keydown",this.disableSave),ve(this.delegate.headerMenu,"keydown",this.disableSave);for(let t of this.delegate.iframes)ve(t,"keydown",this.disableSave),ve(t.ownerDocument,"keydown",this.disableSave),ve(t.contentDocument,"keydown",this.disableSave),ve(t.contentWindow,"keydown",this.disableSave),ve(t.contentWindow?.document,"keydown",this.disableSave);ve(window,"keydown",this.disableSave),ve(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){ve(this.delegate.mainElement,"copy",this.preventCopy),ve(this.delegate.headerMenu,"copy",this.preventCopy);for(let t of this.delegate.iframes)ve(t,"copy",this.preventCopy),ve(t.ownerDocument,"copy",this.preventCopy),ve(t.contentDocument,"copy",this.preventCopy),ve(t.contentWindow,"copy",this.preventCopy),ve(t.contentWindow?.document,"copy",this.preventCopy);ve(window,"copy",this.preventCopy),ve(document,"copy",this.preventCopy),ve(this.delegate.mainElement,"cut",this.preventCopy),ve(this.delegate.headerMenu,"cut",this.preventCopy);for(let t of this.delegate.iframes)ve(t,"cut",this.preventCopy),ve(t.ownerDocument,"cut",this.preventCopy),ve(t.contentDocument,"cut",this.preventCopy),ve(t.contentWindow,"cut",this.preventCopy),ve(t.contentWindow?.document,"cut",this.preventCopy);ve(window,"cut",this.preventCopy),ve(document,"cut",this.preventCopy)}if(this.properties?.disablePrint){ve(this.delegate.mainElement,"beforeprint",this.beforePrint),ve(this.delegate.headerMenu,"beforeprint",this.beforePrint);for(let t of this.delegate.iframes)ve(t,"beforeprint",this.beforePrint.bind(this)),ve(t.ownerDocument,"beforeprint",this.beforePrint.bind(this)),ve(t.contentDocument,"beforeprint",this.beforePrint.bind(this)),ve(t.contentWindow,"beforeprint",this.beforePrint.bind(this)),ve(t.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));ve(window,"beforeprint",this.beforePrint.bind(this)),ve(document,"beforeprint",this.beforePrint.bind(this)),ve(this.delegate.mainElement,"afterprint",this.afterPrint),ve(this.delegate.headerMenu,"afterprint",this.afterPrint);for(let t of this.delegate.iframes)ve(t,"afterprint",this.afterPrint.bind(this)),ve(t.ownerDocument,"afterprint",this.afterPrint.bind(this)),ve(t.contentDocument,"afterprint",this.afterPrint.bind(this)),ve(t.contentWindow,"afterprint",this.afterPrint.bind(this)),ve(t.contentWindow?.document,"afterprint",this.afterPrint.bind(this));ve(window,"afterprint",this.afterPrint.bind(this)),ve(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){ve(this.delegate.mainElement,"contextmenu",this.disableContext),ve(this.delegate.headerMenu,"contextmenu",this.disableContext);for(let t of this.delegate.iframes)ve(t,"contextmenu",this.disableContext),ve(t.ownerDocument,"contextmenu",this.disableContext),ve(t.contentDocument,"contextmenu",this.disableContext),ve(t.contentWindow,"contextmenu",this.disableContext),ve(t.contentWindow?.document,"contextmenu",this.disableContext);ve(window,"contextmenu",this.disableContext),ve(document,"contextmenu",this.disableContext)}}initializeResource(){this.properties?.hideTargetUrl&&this.hideTargetUrls(!0),this.properties?.disableDrag&&this.preventDrag(!0)}async initialize(){if(this.properties?.enableObfuscation)return new Promise(async t=>{await document.fonts.ready;for(let n of this.delegate.iframes)if(n.contentDocument){let i=Sr(n.contentDocument,"body");this.observe(),setTimeout(()=>{this.rects=this.findRects(i),this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),this.setupEvents(),this.hasEventListener||(this.hasEventListener=!0,ve(this.wrapper,"scroll",this.handleScroll.bind(this))),t()},10)}})}handleScroll(){this.rects.forEach(t=>this.toggleRect(t,this.securityContainer,this.isHacked))}handleResize(){if(this.properties?.enableObfuscation){let t=(0,pg.debounce)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(n=>this.toggleRect(n,this.securityContainer,this.isHacked))},10);this.rects&&(this.observe(),t())}}disableContext(t){return t.preventDefault(),t.stopPropagation(),!1}disableSave(t){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?t.metaKey:t.ctrlKey&&(t.key==="s"||t.keyCode===83))?(t.preventDefault(),t.stopPropagation(),!1):!0}preventCopy(t){return K&&console.log("copy action initiated"),t.clipboardData.setData("text/plain","copy not allowed"),t.stopPropagation(),t.preventDefault(),!1}beforePrint(t){return K&&console.log("before print"),this.delegate&&this.delegate.headerMenu&&(this.delegate.headerMenu.style.display="none",this.delegate.mainElement.style.display="none"),t.stopPropagation(),t.preventDefault(),!1}afterPrint(t){return K&&console.log("after print"),this.delegate&&this.delegate.headerMenu&&(this.delegate.headerMenu.style.removeProperty("display"),this.delegate.mainElement.style.removeProperty("display")),t.stopPropagation(),t.preventDefault(),!1}hideTargetUrls(t){function n(i){i.preventDefault();let o=i.currentTarget.getAttribute("data-href-resolved"),l=document.createElement("a");l.setAttribute("href",o),l.click()}for(let i of this.delegate.iframes){let o=i.contentDocument?.querySelectorAll("a");o?.forEach(l=>{let s=l.getAttribute("data-href"),a=l.getAttribute("href");!s&&a&&(l.setAttribute("data-href",a),l.setAttribute("data-href-resolved",l.href))}),t?o?.forEach(l=>{l.setAttribute("href",""),l.addEventListener("click",n)}):o?.forEach(l=>{let s=l.getAttribute("data-href");s&&l.setAttribute("href",s),l.removeEventListener("click",n)})}}preventDrag(t){let n="-webkit-user-drag: none; -khtml-user-drag: none; -moz-user-drag: none; -ms-user-drag: none; user-drag: none; -webkit-pointer-events: none; -khtml-pointer-events: none; -moz-pointer-events: none; -ms-pointer-events: none; pointer-events: none;",i=o=>{o.preventDefault()};for(let o of this.delegate.iframes){let l=o.contentDocument?.body.getAttribute("style")||"";t?(o.contentDocument?.body.addEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",l+n)):(o.contentDocument?.body.removeEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",l.replace(n,"")))}}recalculate(t=0){return new Promise(n=>{if(this.properties?.enableObfuscation){let i=(0,pg.debounce)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),n(!0)},t);this.rects?(this.observe(),i()):n(!1)}else n(!1)})}calcRects(t){t!==void 0&&t.forEach(n=>{try{let{top:i,height:o,left:l,width:s}=this.measureTextNode(n.node);n.top=i,n.height=o,n.width=s,n.left=l}catch(i){K&&(console.log("error "+i),console.log(n),console.log(n.node),console.log("scrambledTextContent "+n.scrambledTextContent),console.log("textContent "+n.textContent),console.log("isObfuscated "+n.isObfuscated))}})}deactivateRect(t,n,i){this.isBeingHacked(n)||i?(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0):(t.node.textContent=t.textContent,t.isObfuscated=!1)}toggleRect(t,n,i){let o=this.isOutsideViewport(t),l=this.isBeingHacked(n);t.isObfuscated&&!o&&!l&&!i&&(t.node.textContent=t.textContent,t.isObfuscated=!1),!t.isObfuscated&&(o||l||i)&&(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0)}findRects(t){return this.findTextNodes(t).map(i=>{let{top:o,height:l,left:s,width:a}=this.measureTextNode(i),u=i.parentElement?.nodeName==="option"||i.parentElement?.nodeName==="script"?i.textContent:this.obfuscateText(i.textContent??"");return{top:o,height:l,width:a,left:s,node:i,textContent:i.textContent??"",scrambledTextContent:u??"",isObfuscated:!1}})}obfuscateText(t){return this.scramble(t,!0)}measureTextNode(t){try{let n=document.createRange();n.selectNode(t);let i=n.getBoundingClientRect();return n.detach(),i}catch(n){K&&(console.log("measureTextNode "+n),console.log("measureTextNode "+t),console.log(t.textContent))}}isBeingHacked(t){return t.style.animation||t.style.transition||t.style.position||t.hasAttribute("style")?(K&&console.log("content being hacked"),!0):!1}isOutsideViewport(t){let n=this.wrapper.scrollLeft,i=n+this.wrapper.clientWidth,o=t.left+t.width,l=t.top+t.height,s=this.wrapper.scrollTop,a=s+this.wrapper.clientHeight,u=l<s,h=t.top>a,f=o<n-window.innerWidth,p=t.left>i+window.innerWidth;return u||h||f||p}findTextNodes(t,n=[]){let i=t.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,n),i.nodeType===3&&i.textContent?.trim()&&n.push(i),i=i.nextSibling;return n}scramble(t,n=!1,i=!1){var o=t.split(" ");function l(s){for(var a=s.length,u,h;a>0;)h=Math.floor(Math.random()*a),a--,u=s[a],s[a]=s[h],s[h]=u;return s}return n&&(o=o.map(function(s){return l(s.split("")).join("")})),i?l(o).join(" "):o.join(" ")}};T();var zO=At($O());T();var zd=r=>r.replace(/\n/g," ").replace(/\s\s+/g," "),KN=r=>zd(r).trim(),UO=/[\\^$.*+?()[\]{}|]/g,YN=RegExp(UO.source);function WO(r){return r&&YN.test(r)?r.replace(UO,"\\$&"):r||""}var Vd=0,XN=()=>()=>Number.isSafeInteger(++Vd)?Vd:Vd=1,qO=()=>{Vd=0},ZN=XN(),QN=r=>t=>{try{return Dn(t,r,no)}catch(n){return console.error("uniqueCssSelector:",n),""}};async function Js(r,t,n,i,o=!1){if(!t)return[];let l=t.body?.textContent;if(!l)return[];if(r=KN(r),!r.length)return[];let s=t.createNodeIterator(t.body,NodeFilter.SHOW_TEXT,{acceptNode:y=>NodeFilter.FILTER_ACCEPT}),a=new RegExp(WO(r).replace(/ /g,"\\s+"),"gim");o&&(a=new RegExp("\\b"+WO(r).replace(/ /g,"\\s+")+"\\b","gim"));let u=[],h=100,f=30,p=0,g;for(;g=a.exec(l);){let y=Math.max(0,g.index-h),E=Math.min(h,g.index),b=zd(l.substr(y,E));b=b.substr(b.length-f),y=a.lastIndex,E=Math.min(h,l.length-y);let w=zd(l.substr(y,E)).substr(0,f),_=new Range,S=g.index;for(;p<=S;){let C=s.nextNode();C&&C.nodeValue&&(p+=C.nodeValue.length)}let x=s.referenceNode.nodeValue?s.referenceNode.nodeValue?.length-(p-S):0;for(_.setStart(s.referenceNode,x),S=g.index+g[0].length;p<=S;){let I=s.nextNode()?.nodeValue;I&&(p+=I.length)}x=s.referenceNode.nodeValue?s.referenceNode.nodeValue?.length-(p-S):0,_.setEnd(s.referenceNode,x),t.getCssSelector||(t.getCssSelector=QN(t));let R=Mr(_,t.getCssSelector);R&&u.push({textMatch:zd(g[0]),textBefore:b,textAfter:w,rangeInfo:R,href:n,title:i,uuid:ZN().toString()})}return u}var mg=class{constructor(t,n,i,o,l,s){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.delegate=t,this.headerMenu=s,this.publication=n,this.properties=i,this.api=l,this.highlighter=o}static async create(t){let n=new this(t.delegate,t.publication,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){K&&console.log("Search module stop"),He(this.searchInput,"keypress",this.handleSearch.bind(this)),He(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.delegate.searchModule=this,this.headerMenu){this.searchInput=xe(this.headerMenu,"#searchInput"),ve(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=xe(this.headerMenu,"#searchGo"),ve(this.searchGo,"click",this.handleSearch.bind(this));var t=xe(this.headerMenu,"#menu-button-search");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("search"):this.delegate.showLayer("search")},10)}async handleSearch(t){(t.key==="Enter"||t.type==="click")&&(await this.handleSearchChapter(),await this.handleSearchBook())}async handleSearchChapter(t){var n=this,i=this.searchInput.value;let o=this.delegate.currentChapterLink.href,l=this.publication.getSpineItem(o);if(this.headerMenu)var s=xe(this.headerMenu,"#searchResultChapter");n.currentChapterSearchResult=[],n.currentSearchHighlights=[];var a=[];this.delegate.rights.enableContentProtection&&this.delegate.contentProtectionModule?.deactivate(),await this.searchAndPaintChapter(i,t,async h=>{a=h,u(1),this.delegate.rights.enableContentProtection&&this.delegate.contentProtectionModule?.recalculate(200)});async function u(h){s.innerHTML="";var f;if(f=n.paginate(a,h,5),f.total===0){let p=document.createElement("a");p.className="collection-item",p.innerHTML="nothing found",s.appendChild(p)}else{for(let b=0;b<f.data.length;b++){let w=document.createElement("a"),_=f.data[b];w.className="collection-item",w.href=l?.Href??"",w.innerHTML="..."+_.textBefore+"<mark>"+_.textMatch+"</mark>"+_.textAfter+"...",ve(w,"click",S=>{S.preventDefault(),S.stopPropagation(),n.jumpToMark(b+h*5-5)}),s.appendChild(w)}let p=document.createElement("div");p.style.textAlign="center",p.style.marginTop="10px";let g=document.createElement("ul");g.className="pagination";let y=document.createElement("li");if(y.className="disabled",y.innerHTML='<a href="#!">left</a>',f.pre_page!==void 0){let b=f.pre_page;y.className="waves-effect",ve(y,"click",w=>{w.preventDefault(),w.stopPropagation(),u(b)})}g.appendChild(y);for(let b=1;b<=f.total_pages;b++){let w,_=document.createElement("li");_.className="waves-effect",b===f.page&&(_.className="active",w=_),_.innerHTML='<a href="#!">'+b+"</a>",ve(_,"click",S=>{S.preventDefault(),S.stopPropagation(),w&&(w.className="waves-effect"),_.className="active",w=_,u(b)}),g.appendChild(_)}let E=document.createElement("li");if(E.className="disabled",E.innerHTML='<a href="#!">right</a>',f.next_page!==void 0){let b=f.next_page;E.className="waves-effect",ve(E,"click",w=>{w.preventDefault(),w.stopPropagation(),u(b)})}g.appendChild(E),p.appendChild(g),s.appendChild(p)}}}async searchAndPaintChapter(t,n=0,i){let o=this.publication.getAbsoluteHref(this.publication.readingOrder[this.delegate.currentResource()??0].Href),l=this.publication.getTOCItem(o);l===null&&(l=this.publication.readingOrder[this.delegate.currentResource()??0]);let s=[];this.highlighter?.destroyHighlights(nt.Search),this.delegate.rights.enableSearch&&this.drawSearch();let a=0;if(l){let u=this.delegate.iframes[0].contentDocument;u&&l&&Js(t,u,l.Href,l.Title).then(h=>{h.forEach(f=>{let p={rangeInfo:f.rangeInfo};setTimeout(()=>{let g;a===n?(g=this.createSearchHighlight(p,this.properties?.current),this.jumpToMark(n)):g=this.createSearchHighlight(p,this.properties?.color),f.highlight=g,s.push(f),this.currentChapterSearchResult.push(f),this.currentSearchHighlights.push(g),a++},500)}),setTimeout(()=>{i(s)},500)})}}createSearchHighlight(t,n){try{var i=n;Ge.isHexColor(i)&&(i=Ge.hexToRgbChannels(i));let l=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,s=zO.SHA256.hash(l),a="R2_SEARCH_"+s;var o=!1;let u={color:i||jo,id:a,pointerInteraction:o,selectionInfo:t,marker:ot.Highlight,type:nt.Search},h=this.highlighter?.createHighlightDom(this.delegate.iframes[0].contentWindow,u);return u.position=parseInt((h?.hasChildNodes()?h.childNodes[0]:h).style.top.replace("px","")),u}catch(l){throw"Can't create highlight: "+l}}clearSearch(){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.highlighter?.destroyHighlights(nt.Search)}async search(t,n){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],qO(),this.searchAndPaintChapter(t,0,async()=>{});var i=this.searchChapter(t),o=this.searchBook(t);return n?i:o}async goToSearchID(t,n,i){var o=n,l;let s=this.delegate.currentChapterLink.href;var a=this.publication.getAbsoluteHref(t);let u=this.bookSearchResult.filter(h=>h.href===t);if(i?(l=this.currentChapterSearchResult.filter(h=>h.uuid==n)[0],o=this.currentChapterSearchResult.findIndex(h=>h.uuid==n)):(l=u.filter(h=>h.uuid==n)[0],o=u.findIndex(h=>h.uuid==n)),l!==void 0)if(s===a)this.jumpToMark(o);else{let f={href:a,locations:{progression:0},title:"title"};this.delegate.navigate(f),setTimeout(()=>{this.searchAndPaintChapter(l.textMatch,o,async()=>{})},300)}}async goToSearchIndex(t,n,i){var o=n,l;let s=this.delegate.currentChapterLink.href;var a=this.publication.getAbsoluteHref(t);let u=this.bookSearchResult.filter(h=>h.href===t);if(i?l=this.currentChapterSearchResult[o]:l=u[o],l!==void 0)if(s===a)this.jumpToMark(o);else{let f={href:a,locations:{progression:0},title:"title"};this.delegate.navigate(f),setTimeout(()=>{this.searchAndPaintChapter(l.textMatch,o,async()=>{})},300)}}async handleSearchBook(){var t=this,n=this.searchInput.value;if(t.headerMenu)var i=xe(t.headerMenu,"#searchResultBook");o(1);async function o(s){i.innerHTML="";var a,u=await t.searchBook(n);if(a=t.paginate(u,s,5),a.total===0){let h=document.createElement("a");h.className="collection-item",h.innerHTML="nothing found",i.appendChild(h)}else{l(a.data,E=>E.href).forEach(E=>{let b=document.createElement("div");if(b.style.marginBottom="10px",E[0].title){let w=document.createElement("span");w.className="collection-item",w.style.display="block",w.innerHTML=E[0].title,b.appendChild(w)}i.appendChild(b),E.forEach(w=>{let _=document.createElement("a");_.className="collection-item";var S=t.publication.getAbsoluteHref(w.href);_.innerHTML="..."+w.textBefore+"<mark>"+w.textMatch+"</mark>"+w.textAfter+"...",ve(_,"click",x=>{x.preventDefault(),x.stopPropagation();let C=u.filter(z=>z.href===w.href).findIndex(z=>z===w);if(t.delegate.currentChapterLink.href===S)t.jumpToMark(C);else{let N={href:S,locations:{progression:0},title:"title"};t.delegate.navigate(N),setTimeout(()=>{t.handleSearchChapter(C)},300)}}),b.appendChild(_)})});let f=document.createElement("div");f.style.textAlign="center",f.style.marginTop="10px";let p=document.createElement("ul");p.className="pagination";let g=document.createElement("li");if(g.className="disabled",g.innerHTML='<a href="#!">left</a>',a.pre_page!=null){let E=a.pre_page;g.className="waves-effect",ve(g,"click",b=>{b.preventDefault(),b.stopPropagation(),o(E)})}p.appendChild(g);for(let E=1;E<=a.total_pages;E++){let b,w=document.createElement("li");w.className="waves-effect",E===a.page&&(w.className="active",b=w),w.innerHTML='<a href="#!">'+E+"</a>",ve(w,"click",_=>{_.preventDefault(),_.stopPropagation(),b&&(b.className="waves-effect"),w.className="active",b=w,o(E)}),p.appendChild(w)}let y=document.createElement("li");if(y.className="disabled",y.innerHTML='<a href="#!">right</a>',a.next_page!=null){let E=a.next_page;y.className="waves-effect",ve(y,"click",b=>{b.preventDefault(),b.stopPropagation(),o(E)})}p.appendChild(y),f.appendChild(p),i.appendChild(f)}}function l(s,a){let u=new Map;return s.forEach(h=>{let f=a(h),p=u.get(f);p?p.push(h):u.set(f,[h])}),Array.from(u.values())}}async searchBook(t){this.bookSearchResult=[];let n=[];for(let i=0;i<this.publication.readingOrder.length;i++){let o=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[i].Href:""),l=this.publication.getTOCItem(o);if(l===void 0&&this.publication.readingOrder&&(l=this.publication.readingOrder[i]),l){let s=this.publication.getAbsoluteHref(l.Href);await fetch(s).then(a=>a.text()).then(async a=>{let h=new DOMParser().parseFromString(a,"application/xhtml+xml");l&&Js(t,h,l.Href,l.Title).then(f=>{f.forEach(p=>{n.push(p),this.bookSearchResult.push(p)})})})}if(i===this.publication.readingOrder.length-1)return n}}async searchChapter(t){let n=[],i=this.publication.getAbsoluteHref(this.publication.readingOrder[this.delegate.currentResource()??0].Href),o=this.publication.getTOCItem(i);if(o===null&&(o=this.publication.readingOrder[this.delegate.currentResource()??0]),o){let l=this.publication.getAbsoluteHref(o.Href);await fetch(l).then(s=>s.text()).then(async s=>{let u=new DOMParser().parseFromString(s,"application/xhtml+xml");o&&Js(t,u,o.Href,o.Title).then(h=>{h.forEach(f=>{n.push(f)})})})}return n}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(t=>{let n={rangeInfo:t.rangeInfo};if(this.properties?.color){let i=this.createSearchHighlight(n,this.properties?.color);t.highlight=i,this.currentSearchHighlights.push(i)}})},100)}async handleResize(){await this.highlighter?.destroyHighlights(nt.Search),this.drawSearch()}jumpToMark(t){setTimeout(()=>{if(this.currentChapterSearchResult.length){var n=this.currentChapterSearchResult[t];this.currentSearchHighlights.forEach(o=>{var l=this.properties?.color;Ge.isHexColor(l)&&(l=Ge.hexToRgbChannels(l)),o.color=l});var i=this.properties?.current;Ge.isHexColor(i)&&(i=Ge.hexToRgbChannels(i)),n.highlight.color=i,this.highlighter?.setAndResetSearchHighlight(n.highlight,this.currentSearchHighlights),this.delegate.view?.goToCssSelector(n.rangeInfo.startContainerElementCssSelector),this.delegate.updatePositionInfo()}},200)}paginate(t,n,i){let o=n||1,l=i||10,s=(o-1)*l,a=t.slice(s).slice(0,l),u=Math.ceil(t.length/l);return{page:o,per_page:l,pre_page:o-1?o-1:void 0,next_page:u>o?o+1:void 0,total:t.length,total_pages:u,data:a}}};T();var lo=class{},qe=lo;qe.COLOR_REF="color",qe.AUTO_SCROLL_REF="autoscroll",qe.RATE_REF="rate",qe.PITCH_REF="pitch",qe.VOLUME_REF="volume",qe.VOICE_REF="voice",qe.COLOR_KEY="tts-"+lo.COLOR_REF,qe.AUTO_SCROLL_KEY="tts-"+lo.AUTO_SCROLL_REF,qe.RATE_KEY="tts-"+lo.RATE_REF,qe.PITCH_KEY="tts-"+lo.PITCH_REF,qe.VOLUME_KEY="tts-"+lo.VOLUME_REF,qe.VOICE_KEY="tts-"+lo.VOICE_REF;var vg=class{constructor(t,n,i){this.TTSSETTINGS="ttsSetting";this.color="orange";this.autoScroll=!0;this.rate=1;this.pitch=1;this.volume=1;this.voice={usePublication:!0};this.settingsChangeCallback=()=>{};this.restartCallback=()=>{};this.store=t,this.api=n,this.headerMenu=i,this.initialise()}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialTTSSettings){let i=t.initialTTSSettings;i?.rate&&(n.rate=i.rate,K&&console.log(n.rate)),i?.pitch&&(n.pitch=i.pitch,K&&console.log(n.pitch)),i?.volume&&(n.volume=i.volume,K&&console.log(n.volume)),i?.color&&(n.color=i.color,K&&console.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,K&&console.log(n.autoScroll)),i?.voice&&(n.voice=i.voice,K&&console.log(n.voice))}return n.initializeSelections(),n}stop(){K&&console.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(qe.AUTO_SCROLL_KEY)!=null?this.getProperty(qe.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(qe.RATE_KEY)!=null?this.getProperty(qe.RATE_KEY).value:this.rate,this.pitch=this.getProperty(qe.PITCH_KEY)!=null?this.getProperty(qe.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(qe.VOLUME_KEY)!=null?this.getProperty(qe.VOLUME_KEY).value:this.volume,this.color=this.getProperty(qe.COLOR_KEY)!=null?this.getProperty(qe.COLOR_KEY).value:this.color,this.voice=this.getProperty(qe.VOICE_REF)!=null?this.getProperty(qe.VOICE_REF).value:this.voice,this.userProperties=this.getTTSSettings()}reset(){this.color="orange",this.autoScroll=!0,this.rate=1,this.pitch=1,this.volume=1,this.voice={usePublication:!0},this.userProperties=this.getTTSSettings()}initializeSelections(){this.headerMenu&&(this.settingsView=xe(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechRate=xe(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=xe(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=xe(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=xe(this.headerMenu,"#autoScroll")),this.speechRate&&(this.speechRate.value=this.rate.toString()),this.speechPitch&&(this.speechPitch.value=this.pitch.toString()),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),ve(xe(t,"ul"),"click",n=>{n.stopPropagation()})}onSettingsChange(t){this.settingsChangeCallback=t}onRestart(t){this.restartCallback=t}storeProperty(t){this.updateUserSettings(),this.saveProperty(t)}updateUserSettings(){var t={rate:this.userProperties.getByRef(qe.RATE_REF)?.value,pitch:this.userProperties.getByRef(qe.PITCH_REF)?.value,volume:this.userProperties.getByRef(qe.VOLUME_REF)?.value,voice:this.userProperties.getByRef(qe.VOLUME_REF)?.value,color:this.userProperties.getByRef(qe.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(qe.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{K&&console.log("api updated tts settings",n)})}getTTSSettings(){var t=new _r;return t.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,qe.AUTO_SCROLL_REF,qe.AUTO_SCROLL_KEY),t.addIncremental(this.rate,.1,10,.1,"",qe.RATE_REF,qe.RATE_KEY),t.addIncremental(this.pitch,.1,2,.1,"",qe.PITCH_REF,qe.PITCH_KEY),t.addIncremental(this.volume,.1,1,.1,"",qe.VOLUME_REF,qe.VOLUME_KEY),t.addStringable(this.color,qe.COLOR_REF,qe.COLOR_KEY),t.addJSONable(JSON.stringify(this.voice),qe.VOICE_REF,qe.VOICE_KEY),t}saveProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}return t}getProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?void 0:i[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(t){if(t.rate){K&&console.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(qe.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.pitch){K&&console.log("pitch "+this.pitch),this.pitch=t.pitch;let n=this.userProperties.getByRef(qe.PITCH_REF);n&&(n.value=this.pitch,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.volume){K&&console.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(qe.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.color){this.color=t.color;let n=this.userProperties.getByRef(qe.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){K&&console.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(qe.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.voice){K&&console.log("voice "+this.voice),this.voice=t.voice;let n=this.userProperties.getByRef(qe.VOICE_REF);n&&(n.value=this.voice,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}}applyPreferredVoice(t){var n=t.indexOf(":")!==-1?t.slice(0,t.indexOf(":")):void 0,i=t.indexOf(":")!==-1?t.slice(t.indexOf(":")+1):t;n!==void 0&&i!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:n,lang:i}}):i!==void 0&&n===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:i}})}increase(t){if(t==="rate"){this.userProperties.getByRef(qe.RATE_REF).increment();let n=this.userProperties.getByRef(qe.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(qe.PITCH_REF).increment();let n=this.userProperties.getByRef(qe.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(qe.VOLUME_REF).increment();let n=this.userProperties.getByRef(qe.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}decrease(t){if(t==="rate"){this.userProperties.getByRef(qe.RATE_REF).decrement();let n=this.userProperties.getByRef(qe.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(qe.PITCH_REF).decrement();let n=this.userProperties.getByRef(qe.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(qe.VOLUME_REF).decrement();let n=this.userProperties.getByRef(qe.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}};T();T();var VO=(r,t,n)=>`
78
78
  <a rel="up" href='${r}' aria-label="${n}" style="padding: 0px"><i class="material-icons show-on-large">arrow_back_ios</i></a>
79
79
  `;var GO=`${$i.loading}`,JO=`
80
80
  <span>
@@ -83,7 +83,7 @@ function print() { __p += __j.call(arguments, '') }
83
83
  <span>There was an error loading this page.</span>
84
84
  <button class="go-back">Go back</button>
85
85
  <button class="try-again">Try again</button>
86
- `;var co=At(Ad());var QO=At(KO());var Yd=At(Zr());T();var Ks=class{constructor(){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{let n=null,i=null,o=this;t&&(t.addEventListener("touchstart",function(l){l.changedTouches.length===1&&(n=l)},!1),t.addEventListener("touchend",function(l){if(l.changedTouches.length!==1||!n)return;let s=n.changedTouches[0],a=l.changedTouches[0];if(!s)return;let u=window.devicePixelRatio,h=(s.clientX-a.clientX)/u,f=(s.clientY-a.clientY)/u;if(Math.abs(h)<Ks.TAP_TOLERANCE&&Math.abs(f)<Ks.TAP_TOLERANCE){if(i){n=null,i=null;return}if(l.timeStamp-n.timeStamp>Ks.LONG_PRESS_MS){n=null,i=null;return}n=null,i=l;return}if(i=null,l.timeStamp-n.timeStamp>Ks.SLOW_SWIPE_MS){n=null;return}let p=(s.clientY-a.clientY)/(s.clientX-a.clientX);if(Math.abs(p)>.5){n=null;return}h<0?o.onBackwardSwipe(l):o.onForwardSwipe(l),n=null},!1))}}},Go=Ks;Go.TAP_TOLERANCE=10,Go.LONG_PRESS_MS=500,Go.SLOW_SWIPE_MS=500;T();var Gd=class{constructor(){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.delegate.view?.snap(i.target)},!0)};this.keydown=t=>{let n=this;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)}}};T();var YO=At(Zr()),Jd=class{constructor(t){this.enforceSampleRead=(0,YO.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 l(E){E.preventDefault()}function s(E){o[E.keyCode]&&!i&&l(E)}let a=!1,u=Object.defineProperty&&Object.defineProperty({},"passive",{get:function(){a=!0}});window.addEventListener("test",function(){},u);let h=a?{passive:!1}:!1;function f(E){E=E||window.event;let b=Math.max(-1,Math.min(1,E.wheelDelta||-E.detail));return b===-1&&!i&&E.preventDefault(),!1}let p;function g(E){E=E||window.event;let b=E.target||E.srcElement,w=E.touches[0].clientY;if(!(w>p)){if(w<p&&!i)return b.className.match(/\baltNav\b/)||(E.returnValue=!1,E.cancelable&&(E.cancelBubble=!0),E.preventDefault&&E.cancelable&&(E.preventDefault(),E.stopPropagation())),!1}return p=w,!1}function y(E){return E=E||window.event,p=E.touches[0].clientY,!1}window.addEventListener("mousewheel",f,h),window.addEventListener("DOMMouseScroll",f,h),window.addEventListener("keydown",s,h),window.addEventListener("touchmove",g,h),window.addEventListener("touchstart",y,h),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 ex=At(ZO()),fn=class extends ex.default{constructor(t,n=void 0,i=void 0,o=void 0,l,s,a,u,h,f,p,g,y){super();this.iframes=[];this.sideNavExpanded=!1;this.material=!1;this.currentChapterLink={href:""};this.currentSpreadLinks={};this.upLink=void 0;this.rights={autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMaterial:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!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);K&&console.log(t.href),K&&console.log(n),t.href=n,await this.navigate(t)}};this.savePosition=(0,Yd.debounce)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,Yd.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=p,this.view.delegate=this,this.eventHandler=new bd(this),this.touchEventHandler=new Go,this.keyboardEventHandler=new Gd,this.upLinkConfig=i,this.initialLastReadingPosition=o,this.publication=l,this.material=s,this.api=a,this.rights=u??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMaterial:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1},this.tts=h,this.injectables=f,this.attributes=p||{margin:0},this.services=g,this.sample=y,this.sampleReadEventHandler=new Jd(this)}static async create(t){let n=new this(t.settings,t.annotator||void 0,t.upLink||void 0,t.initialLastReadingPosition||void 0,t.publication,t.material,t.api,t.rights,t.tts,t.injectables,t.attributes||{margin:0},t.services,t.sample);return await n.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(n))}stop(){K&&console.log("Iframe navigator stop"),He(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),He(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),He(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),He(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),He(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),He(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),He(this.tryAgainButton,"click",this.tryAgain.bind(this)),He(this.goBackButton,"click",fn.goBack.bind(this)),He(this.bookmarksControl,"keydown",this.hideBookmarksOnEscape.bind(this)),He(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),He(window,"resize",this.onResize),this.iframes.forEach(t=>{He(t,"resize",this.onResize)}),this.rights.enableMaterial&&(this.mDropdowns&&this.mDropdowns.forEach(t=>{t.destroy()}),this.mCollapsibles&&this.mCollapsibles.forEach(t=>{t.destroy()}),this.mSidenav&&this.mSidenav.destroy(),this.mTabs&&this.mTabs.forEach(t=>{t.destroy()}))}async start(t,n,i){this.headerMenu=n,this.mainElement=t;try{let E=St(t,"main#iframe-wrapper");E.style.overflow="auto";let b=xe(t,"main#iframe-wrapper iframe"),w=xe(t,"#second");if(b&&this.iframes.push(b),w&&this.iframes.push(w),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.iframes.length===0){E.style.overflow="auto";let _=document.createElement("iframe");if(_.setAttribute("SCROLLING","no"),_.setAttribute("allowtransparency","true"),this.iframes.push(_),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]),E.appendChild(this.spreads)):(_.setAttribute("height","100%"),_.setAttribute("width","100%"),E.appendChild(this.iframes[0])),this.publication.isFixedLayout)if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){let S=document.createElement("div");this.spreads.appendChild(S);let x=document.createElement("iframe");x.setAttribute("SCROLLING","no"),x.setAttribute("allowtransparency","true"),x.style.opacity="1",x.style.border="none",x.style.overflow="hidden",this.iframes.push(x),S.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",S.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",S.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 _=E.clientHeight;var o=this.iframes[0].parentElement?.parentElement;o.style.height=_+40+"px"}else this.iframes.length===2&&this.iframes.pop();this.loadingMessage=xe(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=GO,this.loadingMessage.style.display="none"),this.errorMessage=xe(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=JO,this.errorMessage.style.display="none"),this.tryAgainButton=xe(t,"button[class=try-again]"),this.goBackButton=xe(t,"button[class=go-back]"),this.infoTop=xe(t,"div[class='info top']"),this.infoBottom=xe(t,"div[class='info bottom']"),this.headerMenu&&(this.bookTitle=xe(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=xe(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=xe(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=xe(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=xe(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=xe(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=xe(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=xe(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=xe(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=xe(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=xe(this.headerMenu,"#container-view-pagelist")),i&&(this.linksBottom=xe(i,"ul.links.bottom")),i&&(this.linksMiddle=xe(i,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=xe(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=xe(t,"#next-chapter")),i&&(this.nextPageAnchorElement=xe(i,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=xe(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=xe(t,"#previous-chapter")),i&&(this.previousPageAnchorElement=xe(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.setupEvents(),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);var l=this;if(this.headerMenu){var s=xe(this.headerMenu,"#menu-button-search"),a=xe(this.headerMenu,"#menu-button-tts"),u=xe(this.headerMenu,"#menu-button-bookmark"),h=xe(this.headerMenu,"#menu-button-play"),f=xe(this.headerMenu,"#menu-button-pause"),p=xe(this.headerMenu,"#menu-button-mediaoverlay");if(this.rights.enableMaterial){if(!this.rights.enableBookmarks){u&&u.parentElement?.style.setProperty("display","none");var g=xe(this.headerMenu,"#sidenav-section-bookmarks");g&&g.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var y=xe(this.headerMenu,"#sidenav-section-highlights");y&&y.style.setProperty("display","none")}this.rights.enableTTS||a&&a.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?(h&&h.parentElement?.style.setProperty("display","block"),f&&f.parentElement?.style.setProperty("display","block"),p&&p.parentElement?.style.setProperty("display","block")):(h&&h.parentElement?.style.setProperty("display","none"),f&&f.parentElement?.style.setProperty("display","none"),p&&p.parentElement?.style.setProperty("display","none"))}else s&&s.parentElement?.style.setProperty("display","none"),a&&a.parentElement?.style.setProperty("display","none"),u&&u.parentElement?.style.setProperty("display","none")}if(this.rights.enableMaterial){let _=document.querySelectorAll(".sidenav");_&&(l.mSidenav=co.Sidenav.init(_,{edge:this.attributes?.sideNavPosition??"left"}));let S=document.querySelectorAll(".collapsible");S&&(l.mCollapsibles=co.Collapsible.init(S,{accordion:!0}));let x=document.querySelectorAll(".dropdown-trigger");x&&(l.mDropdowns=co.Dropdown.init(x,{alignment:"right",constrainWidth:!1,coverTrigger:!1,closeOnClick:!1,autoTrigger:!1,onOpenEnd:function(){l.mTabs.forEach(C=>{C.updateTabIndicator()})}}));let R=document.querySelectorAll(".tabs");R&&(l.mTabs=co.Tabs.init(R))}return await this.loadManifest()}catch(E){return console.error(E),this.abortOnError(E),Promise.reject(E)}}setupEvents(){for(let t of this.iframes)ve(t,"load",this.handleIFrameLoad.bind(this));ve(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),ve(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),ve(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ve(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),ve(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ve(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),ve(this.tryAgainButton,"click",this.tryAgain.bind(this)),ve(this.goBackButton,"click",fn.goBack.bind(this)),ve(this.bookmarksControl,"keydown",this.hideBookmarksOnEscape.bind(this)),ve(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),ve(window,"resize",this.onResize);for(let t of this.iframes)ve(t,"resize",this.onResize)}setupModalFocusTrap(t,n,i){let o=9;n.addEventListener("keydown",l=>{if(fn.isDisplayed(t)){let s=l.keyCode===o,a=l.shiftKey;s&&a&&(i.focus(),l.preventDefault(),l.stopPropagation())}}),i.addEventListener("keydown",l=>{if(fn.isDisplayed(t)){let s=l.keyCode===o,a=l.shiftKey;s&&!a&&(n.focus(),l.preventDefault(),l.stopPropagation())}})}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=Fi()-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,Yd.debounce)(()=>{this.isScrolling=!1},200),i=St(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(nt.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(nt.Search),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule!==void 0&&this.highlighter!==void 0&&await this.definitionsModule.drawDefinitions()},200))}async loadManifest(){try{let n=(h,f,p,g=!1)=>{let y,E;p&&(y=p,h instanceof HTMLDivElement&&(E=h));var b=document.createElement("ul");g&&(b=document.createElement("ol")),b.className="sidenav-toc";let w;for(let _ of f){let S=document.createElement("li"),x=document.createElement("a"),R=document.createElement("span");x.className="chapter-link",x.tabIndex=-1;let C="";_.Href?(C=this.publication.getAbsoluteHref(_.Href),x.href=C,x.innerHTML=_.Title||"",S.appendChild(x)):(R.innerHTML=_.Title||"",R.className="chapter-title",S.appendChild(R)),_.Children&&_.Children.length>0&&n(S,_.Children,void 0,!0),b.appendChild(S),w=x}w&&y&&E&&this.setupModalFocusTrap(E,y,w),ve(b,"click",_=>{if(_.preventDefault(),_.stopPropagation(),_.target&&_.target.tagName.toLowerCase()==="a"){let S=_.target;if(S.className.indexOf("active")!==-1)this.hideView();else{y?.focus();let x={progression:0};if(S.href.indexOf("#")!==-1){let C=S.href.slice(S.href.indexOf("#")+1);C!==void 0&&(x={fragment:C})}let R={href:S.href,locations:x,type:S.type,title:S.title};this.hideView(),this.navigate(R)}}}),h.appendChild(b)},i=this.publication.tableOfContents,o=this.publication.landmarks,l=this.publication.pageList;if(this.tocView&&(i.length?n(this.tocView,i):this.tocView.parentElement?.parentElement?.removeChild(this.tocView.parentElement)),this.pageListView&&(l?.length?n(this.pageListView,l):this.pageListView.parentElement?.parentElement?.removeChild(this.pageListView.parentElement)),this.landmarksView&&(o?.length?n(this.landmarksView,o):this.landmarksSection.parentElement?.removeChild(this.landmarksSection)),(this.links||this.linksTopLeft)&&this.upLinkConfig&&this.upLinkConfig.url){let h=this.upLinkConfig.url,f=this.upLinkConfig.label||"",p=this.upLinkConfig.ariaLabel||f;var t=VO(h.href,f,p);let g=document.createElement("li");g.classList.add("uplink-wrapper"),g.innerHTML=t,this.links?(this.links.insertBefore(g,this.links.firstChild),this.upLink=St(this.links,"a[rel=up]")):(this.linksTopLeft.insertBefore(g,this.linksTopLeft.firstChild),this.upLink=St(this.linksTopLeft,"a[rel=up]"))}let s;this.annotator&&(s=await this.annotator.getLastReadingPosition());let a=this.publication.getStartLink(),u;if(a&&a.Href&&(u=this.publication.getAbsoluteHref(a.Href)),s){let h=this.publication.getAbsoluteHref(s.href);K&&console.log(s.href),K&&console.log(h),s.href=h,await this.navigate(s)}else if(u){let h={href:u,locations:{progression:0},created:new Date,title:a?.Title};await this.navigate(h)}return new Promise(h=>h())}catch(n){return console.error(n),this.abortOnError(n),new Promise((i,o)=>o(n)).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.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 l=this.publication.getTOCItem(n);this.currentTocUrl!==void 0&&(l=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&l!==void 0&&l.Title&&(this.currentChapterLink.title=l.Title),!this.currentChapterLink.type&&l!==void 0&&l.TypeLink&&(this.currentChapterLink.title=l.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 s=this.iframes[0].contentDocument?.body;this.rights.enableTTS&&this.tts?.enableSplitter&&(0,QO.default)({target:s,by:"lines"});let a=s?.querySelector("details");if(a){let u=this;a.addEventListener("toggle",async h=>{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.delegate=this,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 h=u.contentDocument?.body;this.ttsModule!==void 0&&(this.tts?.enableSplitter?await this.ttsModule.initialize(h):await this.ttsModule.initialize(h))}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 console.error(t),this.abortOnError(t),Promise.reject(t)}}async injectInjectablesIntoIframeHead(){let t=[],n=i=>{let o=new Promise((l,s)=>{i.onload=()=>{l(!0)},i.onerror=a=>{let u=typeof a=="string"?a:`Injectable failed to load at: ${"href"in i?i.href:i.src}`;s(new Error(u))}});t.push(o)};for(let i of this.iframes){let o=i.contentDocument?.head;o&&(o.insertBefore(fn.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 s=fn.createCssLink(l.url);o.appendChild(s),n(s)}}else if(l.r2before&&l.url){let s=fn.createCssLink(l.url);o.insertBefore(s,o.firstChild),n(s)}else if(l.r2default&&l.url){let s=fn.createCssLink(l.url);o.insertBefore(s,o.childNodes[1]),n(s)}else if(l.r2after&&l.url){l.appearance&&this.settings.initAddedAppearance();let s=fn.createCssLink(l.url);o.appendChild(s),n(s)}else if(l.url){let s=fn.createCssLink(l.url);o.appendChild(s),n(s)}}else if(l.type==="script"&&l.url){let s=fn.createJavascriptLink(l.url,l.async??!1);o.appendChild(s),n(s)}}))}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,h){let p=new DOMParser().parseFromString(u,"application/xhtml+xml");p.head&&p.head.insertBefore(fn.createBase(h),p.head.firstChild);let g=p.documentElement.outerHTML,y=t.iframes[0].contentDocument;y&&(y.open(),y.write(g),y.close())}function l(u,h){let p=new DOMParser().parseFromString(u,"application/xhtml+xml");p.head&&p.head.insertBefore(fn.createBase(h),p.head.firstChild);let g=p.documentElement.outerHTML,y=t.iframes[1].contentDocument;y&&(y.open(),y.write(g),y.close())}let s=new URL(this.currentChapterLink.href),a=window.location.protocol===s.protocol&&window.location.port===s.port&&window.location.hostname===s.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?a?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(h=>h.text()).then(async h=>{o.call(this,h,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 h=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.right={href:h},this.api?.getContent(h).then(f=>{f===void 0?a?this.iframes[1].src=h:fetch(h).then(p=>p.text()).then(async p=>{l.call(this,p,h),this.currentSpreadLinks.right={href:h}}):l.call(this,f,h)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let u=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(u){let h=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.left={href:h},this.api?.getContent(h).then(f=>{f===void 0?a?this.iframes[0].src=h:fetch(h).then(p=>p.text()).then(async p=>{o.call(this,p,h)}):o.call(this,f,h)})}}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?a?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(h=>h.text()).then(async h=>{l.call(this,h,this.currentChapterLink.href)}):l.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?a?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(h=>h.text()).then(async h=>{o.call(this,h,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?a?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)}):o.call(this,u,this.currentChapterLink.href)});else if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(a){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 h=this.publication.getAbsoluteHref(u.Href);this.iframes[1].src=h,this.currentSpreadLinks.right={href:h}}}else this.iframes[1].src="about:blank"}else if(fetch(this.currentChapterLink.href).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 h=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.right={href:h},fetch(h).then(f=>f.text()).then(async f=>{l.call(this,f,h)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let u=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(u){let h=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.left={href:h},a?(this.iframes[0].src=h,this.iframes.length===2&&(this.iframes[1].src=this.currentChapterLink.href)):(fetch(h).then(f=>f.text()).then(async f=>{o.call(this,f,h)}),this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},fetch(this.currentChapterLink.href).then(f=>f.text()).then(async f=>{l.call(this,f,this.currentChapterLink.href)})))}}else this.iframes[0].src="about:blank";this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},a?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(u=>u.text()).then(async u=>{l.call(this,u,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},a?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(u=>u.text()).then(async u=>{o.call(this,u,this.currentChapterLink.href)});else this.currentSpreadLinks.left={href:this.currentChapterLink.href},a?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(u=>u.text()).then(async u=>{o.call(this,u,this.currentChapterLink.href)});this.publication.isFixedLayout&&setTimeout(()=>{let u,h,f;if(n===0&&this.iframes?.length===2?f=this.iframes[1].contentDocument:f=this.iframes[0].contentDocument,f&&f.body&&(u=getComputedStyle(f.body).height,h=getComputedStyle(f.body).width,parseInt(u?.replace("px",""))===0||parseInt(h?.replace("px",""))===0)){let _=hn(f,"head");if(_){let S=xe(_,"meta[name=viewport]");if(S){var p=S.content,g=p.split(",").reduce((x,R)=>{var[C,I]=R.match(/[^\s;=]+/g);return x[C]=isNaN(Number(I))?I:+I,x},{});u=g.height+"px",h=g.width+"px"}}}var y=n===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(y&&h){var E=(parseInt(getComputedStyle(y).width)-100)/(this.iframes.length===2?parseInt(h?.replace("px",""))*2+200:parseInt(h?.replace("px",""))),b=(parseInt(getComputedStyle(y).height)-100)/parseInt(u?.replace("px","")),w=Math.min(E,b);y.style.transform="scale("+w+")";for(let _ of this.iframes)_.style.height=u,_.style.width=h,_.parentElement&&(_.parentElement.style.height=u)}},400)}static goBack(){window.history.back()}static isDisplayed(t){return t?t.className.indexOf(" active")!==-1:!1}static showElement(t,n){if(t){if(t.className=t.className.replace(" inactive",""),t.className.indexOf(" active")===-1&&(t.className+=" active"),t.setAttribute("aria-hidden","false"),n){n.setAttribute("aria-expanded","true");let l=n.querySelector(".icon.open");if(l&&(l.getAttribute("class")||"").indexOf(" inactive-icon")===-1){let a=(l.getAttribute("class")||"")+" inactive-icon";l.setAttribute("class",a)}let s=n.querySelector(".icon.close");if(s){let a=(s.getAttribute("class")||"").replace(" inactive-icon","");s.setAttribute("class",a)}}let i=Array.prototype.slice.call(t.querySelectorAll("button")),o=Array.prototype.slice.call(t.querySelectorAll("a"));for(let l of i)l.tabIndex=0;for(let l of o)l.tabIndex=0}}static hideElement(t,n){if(t){if(t.className=t.className.replace(" active",""),t.className.indexOf(" inactive")===-1&&(t.className+=" inactive"),t.setAttribute("aria-hidden","true"),n){n.setAttribute("aria-expanded","false");let l=n.querySelector(".icon.open");if(l){let a=(l.getAttribute("class")||"").replace(" inactive-icon","");l.setAttribute("class",a)}let s=n.querySelector(".icon.close");if(s&&(s.getAttribute("class")||"").indexOf(" inactive-icon")===-1){let a=(s.getAttribute("class")||"")+" inactive-icon";s.setAttribute("class",a)}}let i=Array.prototype.slice.call(t.querySelectorAll("button")),o=Array.prototype.slice.call(t.querySelectorAll("a"));for(let l of i)l.tabIndex=-1;for(let l of o)l.tabIndex=-1}}hideModal(t,n){for(let i of this.iframes)i.setAttribute("aria-hidden","false");this.upLink&&this.upLink.setAttribute("aria-hidden","false"),this.linksBottom&&this.linksBottom.setAttribute("aria-hidden","false"),this.linksMiddle&&this.linksMiddle.setAttribute("aria-hidden","false"),this.loadingMessage&&this.loadingMessage.setAttribute("aria-hidden","false"),this.errorMessage&&this.errorMessage.setAttribute("aria-hidden","false"),this.infoTop&&this.infoTop.setAttribute("aria-hidden","false"),this.infoBottom&&this.infoBottom.setAttribute("aria-hidden","false"),fn.hideElement(t,n)}handleEditClick(t){var n=t.target;if(this.headerMenu){var i=xe(this.headerMenu,".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.tts?.enableSplitter?this.highlighter?.speakAll():this.ttsModule.speakPlay())}startReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.startReadAloud()}stopReadAloud(){this.rights.enableTTS&&(this.highlighter?.stopReadAloud(),this.tts?.enableSplitter||this.annotationModule!==void 0&&this.annotationModule.drawHighlights())}stopReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.stopReadAloud()}pauseReadAloud(){this.rights.enableTTS&&(this.tts?.enableSplitter?this.ttsModule.speakPause():(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.tts?.enableSplitter?this.ttsModule.speakResume():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 l=t.href.slice(t.href.indexOf("#")+1);l!==void 0&&(n=ln(it({},n),{fragment:l}))}let i=it({},t);i.locations=n;let o=this.publication.getAbsoluteHref(t.href);K&&console.log(t.href),K&&console.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)}}snapToSelector(t){let n=this.iframes[0].contentDocument;if(n){console.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){this.mDropdowns&&this.mDropdowns.forEach(n=>{n.close()})}handleInternalLink(t){let n=t.target,i={progression:0},o=n;if(o.href.indexOf("#")!==-1){let s=o.href.slice(o.href.indexOf("#")+1);s!==void 0&&(i={fragment:s})}let l={href:o.href,locations:i,type:o.type,title:o.title};t.preventDefault(),t.stopPropagation(),this.stopReadAloud(),this.navigate(l)}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 h=Fi()-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=h+40+"px";let f,p,g;t===0&&this.iframes?.length===2?g=this.iframes[1].contentDocument:g=this.iframes[0].contentDocument,g&&g.body&&(f=getComputedStyle(g.body).height,p=getComputedStyle(g.body).width);let y=hn(g,"head");if(y){let E=xe(y,"meta[name=viewport]");if(E){var i=E.content,o=i.split(",").reduce((b,w)=>{var[_,S]=w.match(/[^\s;=]+/g);return b[_]=isNaN(Number(S))?S:+S,b},{});(parseInt(o.height)!==0||parseInt(o.width)!==0)&&(f=o.height+"px",p=o.width+"px")}}var l=(parseInt(getComputedStyle(n).width)-100)/(this.iframes.length===2?parseInt(p?.replace("px",""))*2+200:parseInt(p?.replace("px",""))),s=(parseInt(getComputedStyle(n).height)-100)/parseInt(f?.replace("px","")),a=Math.min(l,s);n.style.transform="scale("+a+")";for(let E of this.iframes)E.style.height=f,E.style.width=p,E.parentElement&&(E.parentElement.style.height=f)}}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(h=>{h?(this.view.height=Fi()-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()},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())}hideBookmarksOnEscape(t){let n=27;fn.isDisplayed(this.bookmarksView)&&t.keyCode===n&&this.hideModal(this.bookmarksView,this.bookmarksControl)}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){if(this.publication.getTOCItem(t.href)){var i=!1;if(t.href.indexOf("#")!==-1){let o=t.href.slice(0,t.href.indexOf("#"));o===this.currentChapterLink.href&&(i=!0),this.currentChapterLink.href=o,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title}else t.href===this.currentChapterLink.href&&(i=!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(i){if(t.href.indexOf("#")!==-1){let h=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:h}}if(this.newPosition=t,this.currentTOCRawLink=t.href,t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.newElementId){for(let h of this.iframes){let f=h.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(f)}this.newElementId=void 0}else if(t.highlight){let h=t.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;h&&this.view?.goToCssSelector(h)}else this.view?.goToProgression(t.locations.progression??0);let o=this.currentChapterLink.href,l=this.publication.getPreviousSpineItem(o);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 s=this.publication.getNextSpineItem(o);s?this.nextChapterLink={href:s.Href,type:s.TypeLink,title:s.Title}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(o),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let a=this.publication.getSpineItem(o);a!==void 0&&(this.currentChapterLink.title=a.Title,this.currentChapterLink.type=a.TypeLink);let u=this.publication.getTOCItem(o);this.currentTocUrl!==void 0&&(u=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&u!==void 0&&u.Title&&(this.currentChapterLink.title=u.Title),!this.currentChapterLink.type&&u!==void 0&&u.TypeLink&&(this.currentChapterLink.title=u.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(nt.PageBreak),await this.pageBreakModule.drawPageBreaks()),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(nt.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(o=>{o||(this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))})}else{let o=this.publication.getStartLink(),l;if(o&&o.Href&&(l=this.publication.getAbsoluteHref(o.Href),l)){let s={href:l,locations:{progression:0},created:new Date,title:o.Title};await this.navigate(s)}}}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 l=Math.ceil((n.progression??0)*(o.length-1)),s=o[l];s&&(s.locations.fragment=n.fragment,i=ln(it({},s),{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=>(K&&console.log("api updated current location",i),this.annotator?.saveLastReadingPosition(i))):(K&&console.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=t,this.annotationModule.activeAnnotationMarkerPosition=n,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=t))}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 Ta("layer-on","layer-off",!0,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=Ue.R2_ID_HIGHLIGHTS_CONTAINER,i.name=Ue.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=Ue.R2_ID_READALOUD_CONTAINER,i.name=Ue.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=Ue.R2_ID_PAGEBREAK_CONTAINER,i.name=Ue.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=Ue.R2_ID_SEARCH_CONTAINER,i.name=Ue.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=Ue.R2_ID_DEFINITIONS_CONTAINER,i.name=Ue.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let l=xe(o,n);l&&(l.style.display="block")}}hideLayer(t){let n="#",i=new Ta("layer-on","layer-off",!1,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=Ue.R2_ID_HIGHLIGHTS_CONTAINER,i.name=Ue.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=Ue.R2_ID_READALOUD_CONTAINER,i.name=Ue.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=Ue.R2_ID_PAGEBREAK_CONTAINER,i.name=Ue.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=Ue.R2_ID_SEARCH_CONTAINER,i.name=Ue.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=Ue.R2_ID_DEFINITIONS_CONTAINER,i.name=Ue.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let l=xe(o,n);l&&(l.style.display="none")}}};T();var Nt=class{constructor(t){this.store=t.store}getLastReadingPosition(){let t=this.store.get(Nt.LAST_READING_POSITION);return t?JSON.parse(t):null}initLastReadingPosition(t){if(typeof t=="string")this.store.set(Nt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(Nt.LAST_READING_POSITION,n)}}saveLastReadingPosition(t){if(typeof t=="string")this.store.set(Nt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(Nt.LAST_READING_POSITION,n)}}initBookmarks(t){if(typeof t=="string"){let n=JSON.parse(t);this.store.set(Nt.BOOKMARKS,JSON.stringify(n))}else this.store.set(Nt.BOOKMARKS,JSON.stringify(t));return t}saveBookmark(t){let n=this.store.get(Nt.BOOKMARKS);if(n){let i=JSON.parse(n);i.push(t),this.store.set(Nt.BOOKMARKS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(Nt.BOOKMARKS,JSON.stringify(i))}return t}locatorExists(t,n){let i;switch(n){case hi.Bookmark:i=Nt.BOOKMARKS;break}let o=this.store.get(i);return o&&JSON.parse(o).filter(a=>a.href===t.href&&a.locations.progression===t.locations.progression).length>0?t:null}deleteBookmark(t){let n=this.store.get(Nt.BOOKMARKS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.id!==t.id),this.store.set(Nt.BOOKMARKS,JSON.stringify(i))}return t}getBookmarks(t){let n=this.store.get(Nt.BOOKMARKS);if(n){let i=JSON.parse(n);if(t){let o=i.filter(l=>l.href===t);return o=o.sort((l,s)=>{if(l.locations.progression&&s.locations.progression)return l.locations.progression-s.locations.progression}),o}return i=i.sort((o,l)=>{if(o.locations.progression&&l.locations.progression)return o.locations.progression-l.locations.progression}),i}return[]}initAnnotations(t){let n;typeof t=="string"?n=JSON.parse(t):n=t;let i=[];return n.forEach(o=>{let l=`${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}`,s=Ai.hash(l);o.highlight.id="R2_HIGHLIGHT_"+s;var a;a=o.color,Ge.isHexColor(a)&&(a=Ge.hexToRgbString(a)),o.highlight.color=a,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(Nt.ANNOTATIONS,JSON.stringify(i)),i}saveAnnotation(t){let n=this.store.get(Nt.ANNOTATIONS);if(n){let i=JSON.parse(n);i.push(t),this.store.set(Nt.ANNOTATIONS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(Nt.ANNOTATIONS,JSON.stringify(i))}return t}deleteAnnotation(t){let n=this.store.get(Nt.ANNOTATIONS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.id!==t),this.store.set(Nt.ANNOTATIONS,JSON.stringify(i))}return t}deleteSelectedAnnotation(t){let n=this.store.get(Nt.ANNOTATIONS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.highlight?.id!==t.highlight.id),this.store.set(Nt.ANNOTATIONS,JSON.stringify(i))}return t}getAnnotations(){let t=this.store.get(Nt.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(Nt.ANNOTATIONS);if(i){let l=JSON.parse(i).filter(s=>s.id===t);if(l.length>0){let s=n.document.getElementById(`${l[0].highlight.id}`);if(s){let a=0;if(s.hasChildNodes)for(let u=0;u<s.childNodes.length;u++){let h=s.childNodes[u],f=parseInt(h.style.top.replace("px",""));(f<a||a===0)&&(a=f)}else a=parseInt(s.style.top.replace("px",""));return a}}}return null}getAnnotation(t){let n=this.store.get(Nt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(l=>l.highlight?.id===t.id);if(o.length>0)return o[0]}return null}getAnnotationByID(t){let n=this.store.get(Nt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(l=>l.highlight?.id===t);if(o.length>0)return o[0]}return null}},Jo=Nt;Jo.LAST_READING_POSITION="last-reading-position",Jo.BOOKMARKS="bookmarks",Jo.ANNOTATIONS="annotations";T();T();var Xd=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 Ys=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 Xd}}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))}};T();var tx=At(_a()),nx=At(Bn());var cl=class extends tx.Link{};cl=hc([(0,nx.JsonObject)()],cl);function ul(r){let t,n,i,o;if(r instanceof Array)return r.map(function(l){return typeof l=="object"&&(l=ul(l)),l});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=ul(o)),i==="href1"?t.href=o:i==="typeLink"?t.type=o:t[i]=o);return t}T();var Eg=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(){K&&console.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let t=new _r,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}};T();var _g=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(){K&&console.log("Page Break module stop")}async start(){this.delegate.pageBreakModule=this,this.headerMenu&&(this.goToPageView=xe(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=xe(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=xe(this.headerMenu,"#goToPageNumberButton")),ve(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),ve(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 s=i.Href.slice(i.Href.indexOf("#")+1);s!==null&&(o={fragment:s})}let l={href:this.publication.getAbsoluteHref(i.Href),locations:o,type:i.TypeLink,title:i.Title};this.delegate.goTo(l)}}}async handleResize(){await this.delegate.highlighter?.destroyHighlights(nt.PageBreak),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{let n=this.delegate.iframes[0].contentDocument?.body?.querySelectorAll('[*|type="pagebreak"]'),i=this;function o(l){try{let s=i.delegate.iframes[0].contentDocument;return s?Dn(l,s,no):""}catch(s){return console.log("uniqueCssSelector:"),console.log(s),""}}if(n)for(let l=0;l<n.length;l++){let s=n[l];K&&console.log(s);let a=s.innerHTML,u=!1;s.innerHTML.length===0&&(a=s.getAttribute("title")??"",s.innerHTML=a,u=!0),s.innerHTML.length===0&&(a=(s.getAttribute("id")??"").replace(/[^0-9]/g,""),s.innerHTML=a,u=!0);let h=this.delegate.iframes[0].contentDocument;if(h){let f=this.delegate.highlighter?.dom(h.body).getWindow().document.createRange(),p=this.delegate.highlighter?.dom(h.body).getSelection();if(p.removeAllRanges(),f.selectNodeContents(s),p.addRange(f),!p.isCollapsed){let g=Mr(f,o);p.removeAllRanges(),g&&this.createPageBreakHighlight({rangeInfo:g,cleanText:"",rawText:""},a)}}u&&(s.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}`,l=Ai.hash(o),s="R2_PAGEBREAK_"+l;var i=!1;let a={color:"#000000",id:s,pointerInteraction:i,selectionInfo:t,marker:ot.Custom,icon:{id:"pageBreak",title:n,color:"#000000",position:"left"},type:nt.PageBreak};Yt.push(a);let u=this.delegate.highlighter?.createHighlightDom(this.delegate.iframes[0].contentWindow,a);return a.position=parseInt((u?.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px","")),a}catch(o){throw"Can't create highlight: "+o}}};T();var ix=At(yd()),Sg=class{constructor(t,n,i,o,l,s,a){this.voices=[];this.hasEventListener=!1;this.index=0;this.userScrolled=!1;this.delegate=t,this.tts=n,this.headerMenu=a,this.rights=i,this.highlighter=o,this.properties=l,this.api=s}initialize(t){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onSettingsChange(this.handleResize.bind(this)),this.body=t,this.clean=(0,ix.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),t.querySelectorAll("[data-word]").forEach(o=>{o.dataset.ttsColor=this.tts.color}),t.querySelectorAll("[data-whitespace]").forEach(o=>{o.dataset.ttsColor=this.tts.color}),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,ve(document,"wheel",this.wheel.bind(this)),ve(this.body,"wheel",this.wheel.bind(this)),ve(document,"keydown",this.wheel.bind(this)),ve(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this))))}initVoices(t){function n(){return new Promise(function(o,l){let s=window.speechSynthesis,a;a=setInterval(()=>{s.getVoices().length!==0&&(o(s.getVoices()),clearInterval(a))},10)})}n().then(async o=>{if(K&&console.log(o),this.voices=[],o.forEach(s=>{s.localService===!0&&this.voices.push(s)}),K&&console.log(this.voices),t&&this.headerMenu){var l=xe(this.headerMenu,"#preferred-languages");l&&this.voices.forEach(s=>{var a=document.createElement("option");a.value=s.name+":"+s.lang,a.innerHTML=s.name+" ("+s.lang+")",l.add(a)})}})}cancel(t=!0){t&&(this.api?.stopped&&this.api?.stopped(),this.delegate.emit("readaloud.stopped","stopped")),this.userScrolled=!1,window.speechSynthesis.cancel(),this.splittingResult&&this.delegate.tts?.enableSplitter&&this.splittingResult.forEach(n=>{n.dataset.ttsCurrentWord="false",n.dataset.ttsCurrentLine="false"})}handleResize(){this.body.querySelectorAll("[data-word]").forEach(i=>{i.dataset.ttsColor=this.tts.color,i.dataset.ttsCurrentWord="false",i.dataset.ttsCurrentLine="false"}),this.body.querySelectorAll("[data-whitespace]").forEach(i=>{i.dataset.ttsColor=this.tts.color,i.dataset.ttsCurrentWord="false",i.dataset.ttsCurrentLine="false"})}async speak(t,n,i){this.api?.started&&this.api?.started();var o=this;if(this.userScrolled=!1,this.cancel(!1),this.delegate.tts?.enableSplitter)if(n){var l=o.body.querySelectorAll("[data-word]"),s=t.range?.startContainer.parentElement;s?.tagName.toLowerCase()==="a"&&(s=s.parentElement),s?.dataset===void 0&&(s=s?.nextElementSibling);var a=t.range?.endContainer.parentElement;a?.tagName.toLowerCase()==="a"&&(a=a?.parentElement),a?.dataset===void 0&&(a=a?.previousElementSibling);var u=parseInt(s.dataset.wordIndex??""),h=parseInt(a.dataset.wordIndex??"")+1;let x=Array.from(l);this.splittingResult=x.slice(u,h)}else document.scrollingElement&&(document.scrollingElement.scrollTop=0),this.splittingResult=o.body.querySelectorAll("[data-word]");let f=n?new SpeechSynthesisUtterance(t?.cleanText):new SpeechSynthesisUtterance(this.clean);f.rate=this.tts.rate,f.pitch=this.tts.pitch,f.volume=this.tts.volume,K&&console.log("this.tts.voice.lang",this.tts.voice.lang);var p=!0;this.tts.voice&&this.tts.voice.lang&&(p=this.tts.voice.lang.indexOf("-")!==-1,p===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),p=!0)),K&&console.log("initialVoiceHasHyphen",p),K&&console.log("voices",this.voices);var g;p===!0?(g=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(x=>{var R=x.lang.replace("_","-");return R===this.tts.voice.lang&&x.name===this.tts.voice.name})[0]:void 0,g===void 0&&(g=this.tts.voice&&this.tts.voice.lang?this.voices.filter(x=>x.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(g=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(x=>x.lang===this.tts.voice.lang&&x.name===this.tts.voice.name)[0]:void 0,g===void 0&&(g=this.tts.voice&&this.tts.voice.lang?this.voices.filter(x=>x.lang===this.tts.voice.lang)[0]:void 0)),K&&console.log("initialVoice",g);var y=o.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;K&&console.log("publicationVoiceHasHyphen",y);var E;y===!0?E=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(x=>{var R=x.lang.replace("_","-");return R.startsWith(o.delegate.publication.Metadata.Language[0])||R.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:E=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(x=>x.lang.startsWith(o.delegate.publication.Metadata.Language[0])||x.lang.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,K&&console.log("publicationVoice",E);var b=navigator.language.indexOf("-")!==-1;K&&console.log("defaultVoiceHasHyphen",b);var w;b===!0?w=this.voices.filter(x=>{var R=x.lang.replace("_","-");return R===navigator.language&&x.localService===!0})[0]:w=this.voices.filter(x=>{var R=x.lang;return R===navigator.language&&x.localService===!0})[0],w===void 0&&(w=this.voices.filter(x=>{var R=x.lang;return R.includes(navigator.language)&&x.localService===!0})[0]),K&&console.log("defaultVoice",w),g?(K&&console.log("initialVoice"),f.voice=g):E?(K&&console.log("publicationVoice"),f.voice=E):w&&(K&&console.log("defaultVoice"),f.voice=w),f.voice!==void 0&&f.voice!==null&&(f.lang=f.voice.lang,K&&console.log("utterance.voice.lang",f.voice.lang),K&&console.log("utterance.lang",f.lang)),K&&console.log("navigator.language",navigator.language),window.speechSynthesis.speak(f),this.index=0;var _=void 0;f.onboundary=function(x){if(x.name==="sentence"&&K&&console.log("sentence boundary",x.charIndex,x.charLength,f.text.slice(x.charIndex,x.charIndex+x.charLength)),x.name==="word"){let C=function(I,z){I=String(I),z=Number(z)>>>0;var N=I.slice(0,z+1).search(/\S+$/),J=I.slice(z).search(/\s/);return J<0?I.slice(N):I.slice(N,J+z)}(f.text,x.charIndex);_===C&&o.index--,_=C,o.delegate.tts?.enableSplitter&&S(C)}};async function S(x){var R=x.replace(/[^a-zA-Z0-9 ]/g,"");K&&console.log("spokenWordCleaned",R);let C=o.splittingResult[o.index];var I=C?.dataset.word?.replace(/[^a-zA-Z0-9 ]/g,"");if(K&&console.log("splittingWordCleaned",I),I?.length===0&&(o.index++,C=o.splittingResult[o.index],I=C?.dataset.word?.replace(/[^a-zA-Z0-9 ]/g,""),K&&console.log("splittingWordCleaned",I)),C){var z=C.parentElement?.tagName.toLowerCase()==="a";z||(R.length>0&&I!==void 0&&I.length>0?I.startsWith(R)||I.endsWith(R)||R.startsWith(I)||R.endsWith(I)?(o.index>0&&(o.body.querySelectorAll("[data-word]").forEach(V=>{V.dataset.ttsColor=o.tts.color,V.dataset.ttsCurrentWord="false",V.dataset.ttsCurrentLine="false"}),o.body.querySelectorAll("[data-whitespace]").forEach(V=>{V.dataset.ttsColor=o.tts.color,V.dataset.ttsCurrentWord="false",V.dataset.ttsCurrentLine="false"})),C.dataset.ttsCurrentWord="true",o.delegate.view?.isScrollMode()&&o.tts.autoScroll&&!o.userScrolled&&C.scrollIntoView({block:"center",behavior:"smooth"})):o.index++:R.length===0&&o.index--),o.index++}}f.onend=function(){K&&console.log("utterance ended"),o.highlighter.doneSpeaking(),o.delegate.tts?.enableSplitter&&(o.body.querySelectorAll("[data-word]").forEach(C=>{C.dataset.ttsColor=o.tts.color,C.dataset.ttsCurrentWord="false",C.dataset.ttsCurrentLine="false"}),o.body.querySelectorAll("[data-whitespace]").forEach(C=>{C.dataset.ttsColor=o.tts.color,C.dataset.ttsCurrentWord="false",C.dataset.ttsCurrentLine="false"})),o.api?.finished()},i()}speakPause(){window.speechSynthesis.speaking&&(this.api?.paused&&this.api?.paused(),this.userScrolled=!1,window.speechSynthesis.pause())}speakResume(){window.speechSynthesis.speaking&&(this.api?.resumed&&this.api?.resumed(),this.userScrolled=!1,window.speechSynthesis.resume())}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=xe(this.headerMenu,"#menu-button-tts");this.rights.enableMaterial?t&&t.parentElement?.style.removeProperty("display"):t&&t.parentElement?.style.setProperty("display","none")}}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(){K&&console.log("TTS module stop"),He(document,"wheel",this.wheel.bind(this)),He(this.body,"wheel",this.wheel.bind(this)),He(document,"keydown",this.wheel.bind(this)),He(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this))}};T();var Mx=At(yd());var Rx=At(Zr()),kx=At(Ax());var Mg=class{constructor(t,n,i,o,l,s,a){this.voices=[];this.hasEventListener=!1;this.index=0;this.userScrolled=!1;this.speaking=!1;this.restartIndex=-1;this.ttsQueueIndex=-1;this.ttsQueue=void 0;this.ttsPlayQueueIndexDebounced=(0,Rx.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=a,this.rights=i,this.highlighter=o,this.properties=l,this.api=s}initialize(t){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=t,this.clean=(0,Mx.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,ve(document,"wheel",this.wheel.bind(this)),ve(this.body,"wheel",this.wheel.bind(this)),ve(document,"keydown",this.wheel.bind(this)),ve(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),ve(this.body,"click",this.click.bind(this)))}click(t){if(window.speechSynthesis.speaking&&this.speaking){let n=this.delegate.iframes[0].contentDocument;if(n){let i=this.highlighter.dom(n.body).getSelection(),o=i.getRangeAt(0),l=i.anchorNode;for(;o.toString().indexOf(" ")!==0;)try{o.setStart(l,o.startOffset-1)}catch(u){break}o.setStart(l,o.startOffset+1);do o.setEnd(l,l.length<o.endOffset?o.endOffset+1:l.length);while(o.toString().indexOf(" ")===-1&&o.toString().trim()!=="");let a=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(this.ttsQueue&&a){let u=this.findTtsQueueItemIndex(this.ttsQueue,i.anchorNode,i.focusNode,i.focusOffset,a);i.removeAllRanges(),u>=0&&(window.speechSynthesis.cancel(),this.restartIndex=u,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}}}}initVoices(t){function n(){return new Promise(function(o,l){let s=window.speechSynthesis,a;a=setInterval(()=>{s.getVoices().length!==0&&(o(s.getVoices()),clearInterval(a))},10)})}n().then(async o=>{if(K&&console.log(o),this.voices=[],o.forEach(s=>{s.localService===!0&&this.voices.push(s)}),K&&console.log(this.voices),t&&this.headerMenu){var l=xe(this.headerMenu,"#preferred-languages");l&&this.voices.forEach(s=>{var a=document.createElement("option");a.value=s.name+":"+s.lang,a.innerHTML=s.name+" ("+s.lang+")",l.add(a)})}})}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(nt.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 l;if(n){let y=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body,E=this.delegate.iframes[0].contentDocument;if(E){let b=this.highlighter.dom(E.body).getSelection();if(y){let w=this.generateTtsQueue(y,!0);if(!w.length)return;let _=this.findTtsQueueItemIndex(w,b.anchorNode,b.focusNode,b.focusOffset,y),S=Rg(w,_);if(S&&t&&t.cleanText){let R=kg(S).indexOf(t.cleanText);l=new SpeechSynthesisUtterance(t.cleanText),l.onboundary=C=>{console.log(C),this.updateTTSInfo(S,C.charIndex+R,C.charLength,l.text)}}}}}else l=new SpeechSynthesisUtterance(this.clean);l.rate=this.tts.rate,l.pitch=this.tts.pitch,l.volume=this.tts.volume,K&&console.log("this.tts.voice.lang",this.tts.voice.lang);var s=!0;this.tts.voice&&this.tts.voice.lang&&(s=this.tts.voice.lang.indexOf("-")!==-1,s===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),s=!0)),K&&console.log("initialVoiceHasHyphen",s),K&&console.log("voices",this.voices);var a;s===!0?(a=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(g=>{var y=g.lang.replace("_","-");return y===this.tts.voice.lang&&g.name===this.tts.voice.name})[0]:void 0,a===void 0&&(a=this.tts.voice&&this.tts.voice.lang?this.voices.filter(g=>g.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(a=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(g=>g.lang===this.tts.voice.lang&&g.name===this.tts.voice.name)[0]:void 0,a===void 0&&(a=this.tts.voice&&this.tts.voice.lang?this.voices.filter(g=>g.lang===this.tts.voice.lang)[0]:void 0)),K&&console.log("initialVoice",a);var u=o.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;K&&console.log("publicationVoiceHasHyphen",u);var h;u===!0?h=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(g=>{var y=g.lang.replace("_","-");return y.startsWith(o.delegate.publication.Metadata.Language[0])||y.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:h=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(g=>g.lang.startsWith(o.delegate.publication.Metadata.Language[0])||g.lang.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,K&&console.log("publicationVoice",h);var f=navigator.language.indexOf("-")!==-1;K&&console.log("defaultVoiceHasHyphen",f);var p;f===!0?p=this.voices.filter(g=>{var y=g.lang.replace("_","-");return y===navigator.language&&g.localService===!0})[0]:p=this.voices.filter(g=>{var y=g.lang;return y===navigator.language&&g.localService===!0})[0],p===void 0&&(p=this.voices.filter(g=>{var y=g.lang;return y.includes(navigator.language)&&g.localService===!0})[0]),K&&console.log("defaultVoice",p),a?(K&&console.log("initialVoice"),l.voice=a):h?(K&&console.log("publicationVoice"),l.voice=h):p&&(K&&console.log("defaultVoice"),l.voice=p),l.voice!==void 0&&l.voice!==null&&(l.lang=l.voice.lang,K&&console.log("utterance.voice.lang",l.voice.lang),K&&console.log("utterance.lang",l.lang)),K&&console.log("navigator.language",navigator.language),setTimeout(()=>{window.speechSynthesis.speak(l)},0),this.index=0,l.onend=function(){K&&console.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.delegate.emit("readaloud.finished","finished")},i()}speakPlay(){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 s=function(){let a=t.highlighter.visibleTextRects[0],u=t.delegate.iframes[0].contentDocument;if(u){let h=t.highlighter.dom(u.body).getWindow().document.createRange(),f=t.highlighter.dom(t.delegate.iframes[0].contentDocument?.body).getSelection();f.removeAllRanges(),h.selectNodeContents(a.node),f.addRange(h);let p=0,g=f.focusNode,y=f.focusOffset;f.collapse(f.anchorNode,f.anchorOffset);for(let E=0;E<p;E++)f.modify("move","forward","line");if(f.extend(g,y),f.collapse(f.anchorNode,f.anchorOffset),i){let E=t.findTtsQueueItemIndex(o,f.anchorNode,f.focusNode,f.focusOffset,i);E>=0&&(l=E)}f.removeAllRanges()}},o=this.generateTtsQueue(i,!0);if(!o.length)return;let l=0;s(),l<0&&(l=0),setTimeout(()=>{this.startTTSSession(o,l)},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(nt.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=xe(this.headerMenu,"#menu-button-tts");this.rights.enableMaterial?t&&t.parentElement?.style.removeProperty("display"):t&&t.parentElement?.style.setProperty("display","none")}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(){K&&console.log("TTS module stop"),He(document,"wheel",this.wheel.bind(this)),He(this.body,"wheel",this.wheel.bind(this)),He(document,"keydown",this.wheel.bind(this)),He(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),He(this.body,"click",this.click.bind(this))}generateTtsQueue(t,n){let i=[],o=[];function l(h){if(h.nodeType!==Node.TEXT_NODE||!h.nodeValue||!h.nodeValue.trim().length)return;let f=o[o.length-1];if(!f)return;let p=h.parentElement?Px(h.parentElement):void 0,g=h.parentElement?kD(h.parentElement):void 0,y=i[i.length-1];(!y||y.parentElement!==f||y.lang!==p||y.dir!==g)&&(y={combinedText:"",combinedTextSentences:void 0,combinedTextSentencesRangeBegin:void 0,combinedTextSentencesRangeEnd:void 0,dir:g,lang:p,parentElement:f,textNodes:[]},i.push(y)),y.textNodes.push(h)}let s=!0;function a(h){if(h.nodeType!==Node.ELEMENT_NODE)return;let f=s||h.matches("h1, h2, h3, h4, h5, h6, p, th, td, caption, li, blockquote, q, dt, dd, figcaption, div, pre");s=!1,f&&o.push(h);for(let p of h.childNodes)switch(p.nodeType){case Node.ELEMENT_NODE:let g=p;if(!g.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))a(g);else if(g.tagName&&g.tagName.toLowerCase()==="img"&&g.src){let E=g.getAttribute("alt");if(E){let b=E.trim();if(b){let w=Px(g),_=void 0;i.push({combinedText:b,combinedTextSentences:void 0,combinedTextSentencesRangeBegin:void 0,combinedTextSentencesRangeEnd:void 0,dir:_,lang:w,parentElement:g,textNodes:[]})}}}break;case Node.TEXT_NODE:o.length!==0&&l(p);break;default:break}f&&o.pop()}a(t);function u(h){if(!h.textNodes||!h.textNodes.length){(!h.combinedText||!h.combinedText.length)&&(h.combinedText=""),h.combinedTextSentences=void 0;return}h.combinedText=PD(h.textNodes,!0).replace(/[\r\n]/g," ");let f=!1,p=h.parentElement;for(;p;){if(p.tagName){let g=p.tagName.toLowerCase();if(g==="pre"||g==="code"||g==="video"||g==="audio"){f=!0;break}}p=p.parentElement}if(n&&!f)try{let g=h.combinedText;h.combinedTextSentences=void 0;let y=(0,kx.split)(g);h.combinedTextSentences=[],h.combinedTextSentencesRangeBegin=[],h.combinedTextSentencesRangeEnd=[];for(let E of y)E.type==="Sentence"&&(h.combinedTextSentences.push(E.raw),h.combinedTextSentencesRangeBegin.push(E.range[0]),h.combinedTextSentencesRangeEnd.push(E.range[1]));(h.combinedTextSentences.length===0||h.combinedTextSentences.length===1)&&(h.combinedTextSentences=void 0)}catch(g){console.log(g),h.combinedTextSentences=void 0}else h.combinedTextSentences=void 0}for(let h of i)u(h);return i}findTtsQueueItemIndex(t,n,i,o,l){let s=0;for(let a of t){if(i&&a.textNodes){if(a.textNodes.includes(i))if(a.combinedTextSentences&&a.combinedTextSentencesRangeBegin&&a.combinedTextSentencesRangeEnd){let u=0;for(let f of a.textNodes)if(!(!f.nodeValue&&f.nodeValue!=="")){if(f===i){u+=o;break}u+=f.nodeValue.length}let h=s-1;for(let f of a.combinedTextSentencesRangeEnd)if(h++,!(f<u))return h;return s}else return s}else if(n===a.parentElement||a.parentElement!==n.ownerDocument.body&&a.parentElement!==l&&a.parentElement.contains(n)||n.contains(a.parentElement))return s;a.combinedTextSentences?s+=a.combinedTextSentences.length:s++}return-1}restart(){window.speechSynthesis.speaking&&(window.speechSynthesis.cancel(),this.restartIndex=this.ttsQueueIndex,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}startTTSSession(t,n){if(!Rg(t,n)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(n,t)}ttsPlayQueueIndex(t,n){if(t<0){this.cancel();return}let i=Rg(n,t);if(!i){this.cancel();return}let o=kg(i);if(!o){this.cancel();return}let l=new SpeechSynthesisUtterance(o);l.rate=this.tts.rate,l.pitch=this.tts.pitch,l.volume=this.tts.volume,K&&console.log("this.tts.voice.lang",this.tts.voice.lang);var s=!0;this.tts.voice&&this.tts.voice.lang&&(s=this.tts.voice.lang.indexOf("-")!==-1,s===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),s=!0)),K&&console.log("initialVoiceHasHyphen",s),K&&console.log("voices",this.voices);var a;s===!0?(a=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(y=>{var E=y.lang.replace("_","-");return E===this.tts.voice.lang&&y.name===this.tts.voice.name})[0]:void 0,a===void 0&&(a=this.tts.voice&&this.tts.voice.lang?this.voices.filter(y=>y.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(a=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(y=>y.lang===this.tts.voice.lang&&y.name===this.tts.voice.name)[0]:void 0,a===void 0&&(a=this.tts.voice&&this.tts.voice.lang?this.voices.filter(y=>y.lang===this.tts.voice.lang)[0]:void 0)),K&&console.log("initialVoice",a);var u=this,h=u.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;K&&console.log("publicationVoiceHasHyphen",h);var f;h===!0?f=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(y=>{var E=y.lang.replace("_","-");return E.startsWith(u.delegate.publication.Metadata.Language[0])||E.endsWith(u.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:f=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(y=>y.lang.startsWith(u.delegate.publication.Metadata.Language[0])||y.lang.endsWith(u.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,K&&console.log("publicationVoice",f);var p=navigator.language.indexOf("-")!==-1;K&&console.log("defaultVoiceHasHyphen",p);var g;p===!0?g=this.voices.filter(y=>{var E=y.lang.replace("_","-");return E===navigator.language&&y.localService===!0})[0]:g=this.voices.filter(y=>{var E=y.lang;return E===navigator.language&&y.localService===!0})[0],g===void 0&&(g=this.voices.filter(y=>{var E=y.lang;return E.includes(navigator.language)&&y.localService===!0})[0]),K&&console.log("defaultVoice",g),a?(K&&console.log("initialVoice"),l.voice=a):f?(K&&console.log("publicationVoice"),l.voice=f):g&&(K&&console.log("defaultVoice"),l.voice=g),l.voice!==void 0&&l.voice!==null&&(l.lang=l.voice.lang,K&&console.log("utterance.voice.lang",l.voice.lang),K&&console.log("utterance.lang",l.lang)),K&&console.log("navigator.language",navigator.language),l.onboundary=y=>{console.log(y.name),this.updateTTSInfo(i,y.charIndex,y.charLength,l.text)},setTimeout(()=>{window.speechSynthesis.speak(l),u.speaking||window.speechSynthesis.pause()},0),l.onend=function(){u.speaking&&u.ttsPlayQueueIndexDebounced(t+1,n)}}updateTTSInfo(t,n,i,o){if(!t)return;let l=o||kg(t);if(n>=0&&o){let s=o.slice(0,n+1).search(/\S+$/),a=o.slice(n).search(/\s/),u=a<0?o.slice(s):o.slice(s,a+n),h=s+u.length,f=!1;i?f=!1:(i=u.length,f=!0),this.wrapHighlightWord(t,o,f?s:n,i,u,s,h)}return l}wrapHighlightWord(t,n,i,o,l,s,a){this._ttsQueueItemHighlightsWord&&(this.delegate.highlighter?.destroyHighlights(nt.ReadAloud),this._ttsQueueItemHighlightsWord=void 0);let u=t.item,h=t.item.combinedText,f=i;if(u.combinedTextSentences&&u.combinedTextSentencesRangeBegin&&u.combinedTextSentencesRangeEnd&&t.iSentence>=0&&(f+=u.combinedTextSentencesRangeBegin[t.iSentence],h=u.combinedTextSentences[t.iSentence]),K){n!==h&&console.log("TTS utteranceText DIFF?? ",`[[${n}]]`,`[[${h}]]`);let S=n.substr(i,o);S!==l&&console.log("TTS word DIFF?? ",`[[${S}]]`,`[[${l}]]`,`${i}--${o}`,`${s}--${a-s}`)}let p=0,g,y=-1,E,b=-1,w=f+o;for(let S of u.textNodes){if(!S.nodeValue&&S.nodeValue!=="")continue;let x=S.nodeValue.length;if(p+=x,g||f<p&&(g=S,y=x-(p-f)),g&&w<=p&&(E=S,b=x-(p-w)),E)break}if(g&&E){let x=function(I){try{let z=_.delegate.iframes[0].contentDocument;return z?Dn(I,z,no):""}catch(z){return console.log("uniqueCssSelector:"),console.log(z),""}},S=new Range;S.setStart(g,y),S.setEnd(E,b);var _=this;let R=Mr(S,x);if(!R)return;let C=this.delegate.highlighter?.createHighlight(this.delegate.iframes[0].contentWindow,{rangeInfo:R,cleanText:"",rawText:"",range:void 0},this.tts.color,!1,ot.Custom,{id:"tts",title:"",position:"right"},void 0,{defaultClass:this.tts.color},nt.ReadAloud,"R2_READALOUD_");C&&(this._ttsQueueItemHighlightsWord=C[0],this.delegate.view?.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&C[1]?.firstChild?.scrollIntoView({block:"center",behavior:"smooth"}))}}};function Px(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 kD(r){let t=r;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let n=t.getAttribute("dir");if(n)return n;t=t.parentNode}}function PD(r,t){if(r&&r.length){let n="";for(let i of r)i.nodeValue&&(n+=t?i.nodeValue:ID(i.nodeValue));return n}return""}function LD(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ID(r){return LD(r).replace(/\n/g," ").replace(/\s\s+/g," ")}function Rg(r,t){let n=-1,i=-1;for(let o of r)if(i++,o.combinedTextSentences){let l=-1;for(let s of o.combinedTextSentences)if(l++,n++,t===n)return{item:o,iArray:i,iGlobal:n,iSentence:l}}else if(n++,t===n)return{item:o,iArray:i,iGlobal:n,iSentence:-1}}function kg(r){return r.iSentence===-1?r.item.combinedText:r.item.combinedTextSentences?r.item.combinedTextSentences[r.iSentence]:""}T();var pl=At(Cd());var Lx=At(Zr());var Pg=class{constructor(t,n,i,o,l){this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,Lx.debounce)(async()=>{if(await this.highlighter.destroyHighlights(nt.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=l,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(){K&&console.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 l=[];if(o){let s=this.publication.getAbsoluteHref(o.Href);await fetch(s).then(a=>a.text()).then(async a=>{for(let u of t.terms){let h=t.terms.indexOf(u);o&&await Js(u,this.delegate.iframes[0].contentDocument,o.Href,o.Title,this.delegate.definitionsModule?.properties.fullWordSearch).then(f=>{let p;t.result==1?p=0:t.result==2&&(p=Math.floor(Math.random()*f.length-1)+1),f.forEach((g,y)=>{if(p===void 0||p===y){let E={rangeInfo:g.rangeInfo},b=this.createDefinitionHighlight(E,t);g.highlight=b,l.push(pl.omit(b,"definition")),this.currentChapterPopupResult.push(g),this.currentPopupHighlights.push(b)}}),h===t.terms.length-1&&n(l)})}})}}async define(t){await this.searchAndPaint(t,async n=>{this.api?.success&&(this.api?.success(pl.omit(t,"callbacks"),n),this.delegate.emit("definition.success",n),this.api?.visible&&n.forEach(i=>{let l=this.delegate.iframes[0].contentDocument?.querySelector(`#${i.id}`)?.querySelectorAll(`.${pi}`),s=new IntersectionObserver((a,u)=>{a.forEach(h=>{h.intersectionRatio===1&&(this.api?.visible(pl.omit(t,"callbacks"),pl.omit(i,"definition")),this.delegate.emit("definition.visible",t,i))})},{threshold:1});l&&l.length>0&&s.observe(l[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;Ge.isHexColor(i)&&(i=Ge.hexToRgbChannels(i));let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,l=Ai.hash(o),s="R2_DEFINITION_"+l;this.highlighter.destroyHighlight(this.delegate.iframes[0].contentDocument,s);let a={color:i||jo,id:s,pointerInteraction:!0,selectionInfo:t,marker:ot.Underline,type:nt.Definition};Yt.push(a);let u=this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,a);return u&&(n.definition&&(u.dataset.definition=n.definition),u.dataset.order=String(n.order),a.definition=n,a.position=parseInt((u?.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px",""))),a}catch(i){throw"Can't create definitions highlight: "+i}}async addDefinition(t){await this.define(t)}async clearDefinitions(){await this.highlighter.destroyHighlights(nt.Definition)}};T();var Ix=.5,ch=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(){K&&console.log("Definitions module stop"),this.hasEventListener=!1,He(document,"keydown",this.keydown.bind(this)),He(document,"keyup",this.keyup.bind(this)),He(this.delegate.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),He(this.delegate.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){this.delegate.lineFocusModule=this;let t=St(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,ve(document,"keydown",this.keydown.bind(this)),ve(document,"keyup",this.keyup.bind(this)),ve(this.delegate.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),ve(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=St(document,"#iframe-wrapper");this.wrapperHeight&&(n.style.height=this.wrapperHeight),t||(this.index=0);let i=this.delegate.iframes[0].contentDocument;hn(i,"html").style.removeProperty("--USER__maxMediaHeight"),this.wrapperHeight=void 0,this.lineFocusContainer&&(this.lineFocusContainer.style.display="none");let l=document.getElementById("container-view-timeline");l&&l.style.removeProperty("display");let s=document.getElementById("divBefore");s&&s.remove();let a=document.getElementById("divAfter");a&&a.remove(),this.highlighter.destroyHighlights(nt.LineFocus)}lineFocus(){let t=St(document,"#iframe-wrapper"),n=this.delegate.iframes[0].contentDocument,i=hn(n,"html"),o=this.properties.maxHeight?Fi()*this.properties.maxHeight/100:Fi()/2;i.style.setProperty("--USER__maxMediaHeight",o+"px");function l(f,p){f.parentNode.insertBefore(p,f.nextSibling)}function s(f,p){f.parentNode.insertBefore(p,f)}let a=document.getElementById("container-view-timeline");a&&(a.style.display="none"),this.lineFocusContainer&&this.lineFocusContainer.style.removeProperty("display");let u=document.getElementById("divBefore");if(u)u.style.height=t.clientHeight/2+"px";else{let f=document.createElement("div");f.style.height=t.clientHeight/2+"px",f.id="divBefore",s(t,f)}let h=document.getElementById("divAfter");if(h)h.style.height=t.clientHeight/2+"px";else{let f=document.createElement("div");f.style.height=t.clientHeight/2+"px",f.id="divAfter",l(t,f)}if(this.lines=[],n){let g=function(){let S=Math.round,x=Math.random,R=255;return{blue:S(x()*R),green:S(x()*R),red:S(x()*R)}},y=function(S,x){let R=[];for(let C=0,I=0;C<S.length;C++)C>=x&&C%x==0&&I++,R[I]=R[I]||[],R[I].push(S[C]);return R},E=function(S,x){let R=Math.min(S.left,x.left),C=Math.max(S.right,x.right),I=Math.min(S.top,x.top),z=Math.max(S.bottom,x.bottom);return{bottom:z,height:z-I,left:R,right:C,top:I,width:C-R}},b=function(S){if(S.length>1){let x=E(S[0],S[1]);if(S.length>2){let R=E(x,S[2]);if(S.length>3){let C=E(R,S[3]);return S.length>4?E(C,S[4]):C}return R}return x}return S[0]},f=this.findRects(n.body);f=y0(f,!0),f=f.sort(function(S,x){return S.top-x.top});let p=[];f=f.filter(function(S){let x=S.top;return p.indexOf(x)===-1&&p.indexOf(x+1)===-1&&p.indexOf(x+2)===-1&&p.indexOf(x+3)===-1&&p.indexOf(x+4)===-1&&p.indexOf(x-1)===-1&&p.indexOf(x-2)===-1&&p.indexOf(x-3)===-1&&p.indexOf(x-4)===-1?(p.push(x),!0):!1}),this.highlighter.destroyHighlights(nt.LineFocus);let w=[];this.properties.lines&&this.properties.lines>1?y(f,this.properties.lines).forEach(x=>{w.push(b(x))}):w=f;let _=xe(n,"#"+Ue.R2_ID_LINEFOCUS_CONTAINER);if(_)for(let S of w){let x=document.createElement("div");x.setAttribute("class",pi);let R=g();if(Ge.isHexColor(R)&&(R=Ge.hexToRgbChannels(R)),this.isDebug){let Ce=`border-bottom: 1px solid rgba(${R.red}, ${R.green}, ${R.blue}, ${Ix}) !important`;x.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${R.red}, ${R.green}, ${R.blue}, ${Ix}) !important; ${Ce}`)}x.style.outline="none",x.tabIndex=0;let C=this.delegate.iframes[0].contentWindow.document,I=this.delegate.view.isPaginated();I?C.body.style.position="revert":C.body.style.position="relative";let z=C.body.getBoundingClientRect(),N=this.highlighter.getScrollingElement(C),J=I?-N.scrollLeft:z.left,V=I?-N.scrollTop:z.top,j=1,D=24,U,Y,be=this.delegate.iframes[0].contentWindow?.innerWidth,le=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-count")),_e=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-width")),me=parseInt(getComputedStyle(n.body).getPropertyValue("padding-left"));if(be){let Ce=be/(le||1);Ce<_e&&(Ce=be),I||(Ce=parseInt(getComputedStyle(n.body).width.replace("px","")));let De=this.delegate.settings.fontSize/100,ce=20*De;De<=1&&(ce=-60);let Pe=0;De<=1&&(Pe=-60),U=Math.floor(S.left/Ce)*Ce+Ce-(D<40?40:D)+Pe,Y=Math.floor(S.left/Ce)*Ce+(D<40?40:D)-ce;let Le=parseInt(n.documentElement.style.getPropertyValue("--USER__pageMargins"));Le>=2&&(Y=Y+me/le,U=U-me/le),I||(U=parseInt(getComputedStyle(n.body).width.replace("px","")),Y=parseInt(getComputedStyle(n.body).width.replace("px",""))-Ce,Le>=2&&(Y=Y+me/2,U=U-me/2))}x.style.setProperty("pointer-events","none"),x.style.position="absolute",x.scale=j,x.rect={height:S.height,left:S.left-J,top:S.top-V,width:S.width},x.style.width=`${x.rect.width*j}px`,x.style.height=`${x.rect.height*j}px`,x.style.left=`${x.rect.left*j}px`,x.style.top=`${x.rect.top*j}px`,this.lines.push(x),_.append(x)}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 s=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=s+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=s+"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 s=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=s+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=s+"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 s=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=s+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=s+"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(l=>{o.push(...this.measureTextNodes(l))}),i.forEach(l=>{o.push(...this.measureImageNodes(l))}),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){K&&(console.log("measureTextNode "+n),console.log("measureTextNode "+t),console.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){K&&(console.log("measureTextNode "+n),console.log("measureTextNode "+t),console.log(t.textContent))}}};var Yo=class{constructor(t,n,i,o,l,s,a,u,h,f,p,g,y,E,b){this.settings=t;this.navigator=n;this.highlighter=i;this.bookmarkModule=o;this.annotationModule=l;this.ttsSettings=s;this.ttsModule=a;this.searchModule=u;this.definitionsModule=h;this.contentProtectionModule=f;this.timelineModule=p;this.mediaOverlaySettings=g;this.mediaOverlayModule=y;this.pageBreakModule=E;this.lineFocusModule=b;this.startReadAloud=()=>{this.navigator.startReadAloud()};this.stopReadAloud=()=>{this.navigator.stopReadAloud()};this.pauseReadAloud=()=>{this.navigator.pauseReadAloud()};this.resumeReadAloud=()=>{this.navigator.resumeReadAloud()};this.startReadAlong=()=>{this.navigator.startReadAlong()};this.stopReadAlong=()=>{this.navigator.stopReadAlong()};this.pauseReadAlong=()=>{this.navigator.pauseReadAlong()};this.resumeReadAlong=()=>{this.navigator.resumeReadAlong()};this.saveBookmark=async()=>await this.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?.hideLayer(t);this.showLayer=t=>this.navigator?.showLayer(t);this.activateMarker=(t,n)=>this.navigator?.activateMarker(t,n);this.deactivateMarker=()=>this.navigator?.deactivateMarker();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.rights.enableSearch&&await this.searchModule?.goToSearchIndex(t,n,i)};this.goToSearchID=async(t,n,i)=>{this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchID(t,n,i)};this.clearSearch=async()=>{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=>await this.settings.scroll(t);this.increase=async t=>{this.isTTSIncrementable(t)?this.navigator.rights.enableTTS&&await this.ttsSettings?.increase(t):this.isMOIncrementable(t)?this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.increase(t):await this.settings.increase(t)};this.decrease=async t=>{this.isTTSIncrementable(t)?this.navigator.rights.enableTTS&&await this.ttsSettings?.decrease(t):this.isMOIncrementable(t)?this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.decrease(t):await this.settings.decrease(t)};this.resetTTSSettings=()=>{this.navigator.rights.enableTTS&&this.ttsSettings?.resetTTSSettings()};this.applyTTSSettings=async t=>{this.navigator.rights.enableTTS&&await this.ttsSettings?.applyTTSSettings(t)};this.applyPreferredVoice=async t=>{this.navigator.rights.enableTTS&&await this.ttsSettings?.applyPreferredVoice(t)};this.resetMediaOverlaySettings=async()=>{this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.resetMediaOverlaySettings()};this.applyMediaOverlaySettings=async 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.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.snapToSelector(t)};this.applyAttributes=t=>{this.navigator.applyAttributes(t)};this.stop=()=>{document.body.onscroll=()=>{},this.navigator.stop(),this.settings.stop(),this.ttsSettings?.stop(),this.ttsSettings?.enableSplitter?this.ttsModule?.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.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,enableMaterial:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1};n.enableContentProtection&&t.protection&&await qd.setupPreloadProtection(t.protection);let i=St(document,"#D2Reader-Container"),o=xe(document,"#headerMenu"),l=xe(document,"#footerMenu"),s=t.url,a=new Ys({prefix:s.href,useLocalStorage:t.useLocalStorage??!1}),u=new Ys({prefix:"r2d2bc-reader",useLocalStorage:t.useLocalStorage??!1}),h=new Ys({prefix:"r2d2bc-layers",useLocalStorage:t.useLocalStorage??!1}),f=new Jo({store:a}),p=t.upLinkUrl??void 0,g=await Mo.fromUrl(s);g.sample=t.sample,n=BD(n,g),n.autoGeneratePositions?await g.autoGeneratePositions():(t.services?.positions&&await g.fetchPositionsFromService(t.services?.positions.href),t.services?.weight&&await g.fetchWeightsFromService(t.services?.weight.href));let y=await Eg.create({store:h}),E=await No.create({store:u,initialUserSettings:t.userSettings,headerMenu:o,material:t.material,api:t.api,injectables:(g.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed:t.injectables,layout:(g.Metadata.Rendition?.Layout??"unknown")==="fixed"?"fixed":"reflowable"}),b=await fn.create({mainElement:i,headerMenu:o,footerMenu:l,publication:g,settings:E,annotator:f,upLink:p,initialLastReadingPosition:t.lastReadingPosition,material:t.material,api:t.api,rights:n,tts:t.tts,sample:t.sample,injectables:(g.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed:t.injectables,attributes:t.attributes,services:t.services}),w=await Ge.create(it({delegate:b,layerSettings:y},t.highlighter)),_=n.enableBookmarks?await il.create(it({annotator:f,headerMenu:o,rights:n,publication:g,delegate:b,initialAnnotations:t.initialAnnotations},t.bookmarks)):void 0,S=n.enableAnnotations?await nl.create(it({annotator:f,rights:n,publication:g,delegate:b,initialAnnotations:t.initialAnnotations,highlighter:w,headerMenu:o},t.annotations)):void 0,x=n.enableTTS,R=x?await vg.create({store:u,initialTTSSettings:t.tts,headerMenu:o}):void 0,C;t.tts?.enableSplitter??!1?x&&R&&(C=await Sg.create(it({delegate:b,tts:R,headerMenu:o,rights:n,highlighter:w},t.tts))):x&&R&&(C=await Mg.create(it({delegate:b,tts:R,headerMenu:o,rights:n,highlighter:w},t.tts)));let I=n.enableSearch?await mg.create(it({headerMenu:o,delegate:b,publication:g,highlighter:w},t.search)):void 0,z=n.enableDefinitions?await Pg.create(it({delegate:b,publication:g,highlighter:w},t.define)):void 0,N=n.enableTimeline?await J0.create({publication:g,delegate:b}):void 0,J=n.enableContentProtection?await qd.create(it({delegate:b},t.protection)):void 0,V=n.enableMediaOverlays,j=V?await V0.create(it({store:u,initialMediaOverlaySettings:t.mediaOverlays,headerMenu:o},t.mediaOverlays)):void 0,D=V?await G0.create(it({publication:g,delegate:b,settings:j},t.mediaOverlays)):void 0,Y=n.enablePageBreaks&&g.isReflowable?await _g.create(it({publication:g,headerMenu:o,delegate:b},t.pagebreak)):void 0,be=n.enableLineFocus?await ch.create(it({publication:g,delegate:b,highlighter:w},t.lineFocus)):void 0;return new Yo(E,b,w,_,S,R,C,I,z,J,N,j,D,Y,be)}get hasMediaOverlays(){return this.navigator.hasMediaOverlays}get tableOfContents(){return ul(this.navigator.tableOfContents())??[]}get readingOrder(){return ul(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.mostRecentNavigatedTocItem()}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.atStart()}get atEnd(){return this.navigator.atEnd()}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 BD(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 ND=Yo,DD=Yo.load;return HD;})();
86
+ `;var co=At(Ad());var QO=At(KO());var Yd=At(Zr());T();var Ks=class{constructor(){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{let n=null,i=null,o=this;t&&(t.addEventListener("touchstart",function(l){l.changedTouches.length===1&&(n=l)},!1),t.addEventListener("touchend",function(l){if(l.changedTouches.length!==1||!n)return;let s=n.changedTouches[0],a=l.changedTouches[0];if(!s)return;let u=window.devicePixelRatio,h=(s.clientX-a.clientX)/u,f=(s.clientY-a.clientY)/u;if(Math.abs(h)<Ks.TAP_TOLERANCE&&Math.abs(f)<Ks.TAP_TOLERANCE){if(i){n=null,i=null;return}if(l.timeStamp-n.timeStamp>Ks.LONG_PRESS_MS){n=null,i=null;return}n=null,i=l;return}if(i=null,l.timeStamp-n.timeStamp>Ks.SLOW_SWIPE_MS){n=null;return}let p=(s.clientY-a.clientY)/(s.clientX-a.clientX);if(Math.abs(p)>.5){n=null;return}h<0?o.onBackwardSwipe(l):o.onForwardSwipe(l),n=null},!1))}}},Go=Ks;Go.TAP_TOLERANCE=10,Go.LONG_PRESS_MS=500,Go.SLOW_SWIPE_MS=500;T();var Gd=class{constructor(){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.delegate.view?.snap(i.target)},!0)};this.keydown=t=>{let n=this;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)}}};T();var YO=At(Zr()),Jd=class{constructor(t){this.enforceSampleRead=(0,YO.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 l(E){E.preventDefault()}function s(E){o[E.keyCode]&&!i&&l(E)}let a=!1,u=Object.defineProperty&&Object.defineProperty({},"passive",{get:function(){a=!0}});window.addEventListener("test",function(){},u);let h=a?{passive:!1}:!1;function f(E){E=E||window.event;let b=Math.max(-1,Math.min(1,E.wheelDelta||-E.detail));return b===-1&&!i&&E.preventDefault(),!1}let p;function g(E){E=E||window.event;let b=E.target||E.srcElement,w=E.touches[0].clientY;if(!(w>p)){if(w<p&&!i)return b.className.match(/\baltNav\b/)||(E.returnValue=!1,E.cancelable&&(E.cancelBubble=!0),E.preventDefault&&E.cancelable&&(E.preventDefault(),E.stopPropagation())),!1}return p=w,!1}function y(E){return E=E||window.event,p=E.touches[0].clientY,!1}window.addEventListener("mousewheel",f,h),window.addEventListener("DOMMouseScroll",f,h),window.addEventListener("keydown",s,h),window.addEventListener("touchmove",g,h),window.addEventListener("touchstart",y,h),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 ex=At(ZO()),fn=class extends ex.default{constructor(t,n=void 0,i=void 0,o=void 0,l,s,a,u,h,f,p,g,y){super();this.iframes=[];this.sideNavExpanded=!1;this.material=!1;this.currentChapterLink={href:""};this.currentSpreadLinks={};this.upLink=void 0;this.rights={autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMaterial:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!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);K&&console.log(t.href),K&&console.log(n),t.href=n,await this.navigate(t)}};this.savePosition=(0,Yd.debounce)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,Yd.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=p,this.view.delegate=this,this.eventHandler=new bd(this),this.touchEventHandler=new Go,this.keyboardEventHandler=new Gd,this.upLinkConfig=i,this.initialLastReadingPosition=o,this.publication=l,this.material=s,this.api=a,this.rights=u??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMaterial:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1},this.tts=h,this.injectables=f,this.attributes=p||{margin:0},this.services=g,this.sample=y,this.sampleReadEventHandler=new Jd(this)}static async create(t){let n=new this(t.settings,t.annotator||void 0,t.upLink||void 0,t.initialLastReadingPosition||void 0,t.publication,t.material,t.api,t.rights,t.tts,t.injectables,t.attributes||{margin:0},t.services,t.sample);return await n.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(n))}stop(){K&&console.log("Iframe navigator stop"),He(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),He(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),He(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),He(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),He(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),He(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),He(this.tryAgainButton,"click",this.tryAgain.bind(this)),He(this.goBackButton,"click",fn.goBack.bind(this)),He(this.bookmarksControl,"keydown",this.hideBookmarksOnEscape.bind(this)),He(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),He(window,"resize",this.onResize),this.iframes.forEach(t=>{He(t,"resize",this.onResize)}),this.rights.enableMaterial&&(this.mDropdowns&&this.mDropdowns.forEach(t=>{t.destroy()}),this.mCollapsibles&&this.mCollapsibles.forEach(t=>{t.destroy()}),this.mSidenav&&this.mSidenav.destroy(),this.mTabs&&this.mTabs.forEach(t=>{t.destroy()}))}async start(t,n,i){this.headerMenu=n,this.mainElement=t;try{let E=St(t,"main#iframe-wrapper");E.style.overflow="auto";let b=xe(t,"main#iframe-wrapper iframe"),w=xe(t,"#second");if(b&&this.iframes.push(b),w&&this.iframes.push(w),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.iframes.length===0){E.style.overflow="auto";let _=document.createElement("iframe");if(_.setAttribute("SCROLLING","no"),_.setAttribute("allowtransparency","true"),this.iframes.push(_),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]),E.appendChild(this.spreads)):(_.setAttribute("height","100%"),_.setAttribute("width","100%"),E.appendChild(this.iframes[0])),this.publication.isFixedLayout)if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){let S=document.createElement("div");this.spreads.appendChild(S);let x=document.createElement("iframe");x.setAttribute("SCROLLING","no"),x.setAttribute("allowtransparency","true"),x.style.opacity="1",x.style.border="none",x.style.overflow="hidden",this.iframes.push(x),S.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",S.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",S.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 _=E.clientHeight;var o=this.iframes[0].parentElement?.parentElement;o.style.height=_+40+"px"}else this.iframes.length===2&&this.iframes.pop();this.loadingMessage=xe(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=GO,this.loadingMessage.style.display="none"),this.errorMessage=xe(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=JO,this.errorMessage.style.display="none"),this.tryAgainButton=xe(t,"button[class=try-again]"),this.goBackButton=xe(t,"button[class=go-back]"),this.infoTop=xe(t,"div[class='info top']"),this.infoBottom=xe(t,"div[class='info bottom']"),this.headerMenu&&(this.bookTitle=xe(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=xe(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=xe(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=xe(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=xe(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=xe(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=xe(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=xe(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=xe(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=xe(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=xe(this.headerMenu,"#container-view-pagelist")),i&&(this.linksBottom=xe(i,"ul.links.bottom")),i&&(this.linksMiddle=xe(i,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=xe(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=xe(t,"#next-chapter")),i&&(this.nextPageAnchorElement=xe(i,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=xe(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=xe(t,"#previous-chapter")),i&&(this.previousPageAnchorElement=xe(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.setupEvents(),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);var l=this;if(this.headerMenu){var s=xe(this.headerMenu,"#menu-button-search"),a=xe(this.headerMenu,"#menu-button-tts"),u=xe(this.headerMenu,"#menu-button-bookmark"),h=xe(this.headerMenu,"#menu-button-play"),f=xe(this.headerMenu,"#menu-button-pause"),p=xe(this.headerMenu,"#menu-button-mediaoverlay");if(this.rights.enableMaterial){if(!this.rights.enableBookmarks){u&&u.parentElement?.style.setProperty("display","none");var g=xe(this.headerMenu,"#sidenav-section-bookmarks");g&&g.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var y=xe(this.headerMenu,"#sidenav-section-highlights");y&&y.style.setProperty("display","none")}this.rights.enableTTS||a&&a.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?(h&&h.parentElement?.style.setProperty("display","block"),f&&f.parentElement?.style.setProperty("display","block"),p&&p.parentElement?.style.setProperty("display","block")):(h&&h.parentElement?.style.setProperty("display","none"),f&&f.parentElement?.style.setProperty("display","none"),p&&p.parentElement?.style.setProperty("display","none"))}else s&&s.parentElement?.style.setProperty("display","none"),a&&a.parentElement?.style.setProperty("display","none"),u&&u.parentElement?.style.setProperty("display","none")}if(this.rights.enableMaterial){let _=document.querySelectorAll(".sidenav");_&&(l.mSidenav=co.Sidenav.init(_,{edge:this.attributes?.sideNavPosition??"left"}));let S=document.querySelectorAll(".collapsible");S&&(l.mCollapsibles=co.Collapsible.init(S,{accordion:!0}));let x=document.querySelectorAll(".dropdown-trigger");x&&(l.mDropdowns=co.Dropdown.init(x,{alignment:"right",constrainWidth:!1,coverTrigger:!1,closeOnClick:!1,autoTrigger:!1,onOpenEnd:function(){l.mTabs.forEach(C=>{C.updateTabIndicator()})}}));let R=document.querySelectorAll(".tabs");R&&(l.mTabs=co.Tabs.init(R))}return await this.loadManifest()}catch(E){return console.error(E),this.abortOnError(E),Promise.reject(E)}}setupEvents(){for(let t of this.iframes)ve(t,"load",this.handleIFrameLoad.bind(this));ve(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),ve(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),ve(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ve(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),ve(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ve(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),ve(this.tryAgainButton,"click",this.tryAgain.bind(this)),ve(this.goBackButton,"click",fn.goBack.bind(this)),ve(this.bookmarksControl,"keydown",this.hideBookmarksOnEscape.bind(this)),ve(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),ve(window,"resize",this.onResize);for(let t of this.iframes)ve(t,"resize",this.onResize)}setupModalFocusTrap(t,n,i){let o=9;n.addEventListener("keydown",l=>{if(fn.isDisplayed(t)){let s=l.keyCode===o,a=l.shiftKey;s&&a&&(i.focus(),l.preventDefault(),l.stopPropagation())}}),i.addEventListener("keydown",l=>{if(fn.isDisplayed(t)){let s=l.keyCode===o,a=l.shiftKey;s&&!a&&(n.focus(),l.preventDefault(),l.stopPropagation())}})}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=Fi()-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,Yd.debounce)(()=>{this.isScrolling=!1},200),i=St(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(nt.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(nt.Search),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule!==void 0&&this.highlighter!==void 0&&await this.definitionsModule.drawDefinitions()},200))}async loadManifest(){try{let n=(h,f,p,g=!1)=>{let y,E;p&&(y=p,h instanceof HTMLDivElement&&(E=h));var b=document.createElement("ul");g&&(b=document.createElement("ol")),b.className="sidenav-toc";let w;for(let _ of f){let S=document.createElement("li"),x=document.createElement("a"),R=document.createElement("span");x.className="chapter-link",x.tabIndex=-1;let C="";_.Href?(C=this.publication.getAbsoluteHref(_.Href),x.href=C,x.innerHTML=_.Title||"",S.appendChild(x)):(R.innerHTML=_.Title||"",R.className="chapter-title",S.appendChild(R)),_.Children&&_.Children.length>0&&n(S,_.Children,void 0,!0),b.appendChild(S),w=x}w&&y&&E&&this.setupModalFocusTrap(E,y,w),ve(b,"click",_=>{if(_.preventDefault(),_.stopPropagation(),_.target&&_.target.tagName.toLowerCase()==="a"){let S=_.target;if(S.className.indexOf("active")!==-1)this.hideView();else{y?.focus();let x={progression:0};if(S.href.indexOf("#")!==-1){let C=S.href.slice(S.href.indexOf("#")+1);C!==void 0&&(x={fragment:C})}let R={href:S.href,locations:x,type:S.type,title:S.title};this.hideView(),this.navigate(R)}}}),h.appendChild(b)},i=this.publication.tableOfContents,o=this.publication.landmarks,l=this.publication.pageList;if(this.tocView&&(i.length?n(this.tocView,i):this.tocView.parentElement?.parentElement?.removeChild(this.tocView.parentElement)),this.pageListView&&(l?.length?n(this.pageListView,l):this.pageListView.parentElement?.parentElement?.removeChild(this.pageListView.parentElement)),this.landmarksView&&(o?.length?n(this.landmarksView,o):this.landmarksSection.parentElement?.removeChild(this.landmarksSection)),(this.links||this.linksTopLeft)&&this.upLinkConfig&&this.upLinkConfig.url){let h=this.upLinkConfig.url,f=this.upLinkConfig.label||"",p=this.upLinkConfig.ariaLabel||f;var t=VO(h.href,f,p);let g=document.createElement("li");g.classList.add("uplink-wrapper"),g.innerHTML=t,this.links?(this.links.insertBefore(g,this.links.firstChild),this.upLink=St(this.links,"a[rel=up]")):(this.linksTopLeft.insertBefore(g,this.linksTopLeft.firstChild),this.upLink=St(this.linksTopLeft,"a[rel=up]"))}let s;this.annotator&&(s=await this.annotator.getLastReadingPosition());let a=this.publication.getStartLink(),u;if(a&&a.Href&&(u=this.publication.getAbsoluteHref(a.Href)),s){let h=this.publication.getAbsoluteHref(s.href);K&&console.log(s.href),K&&console.log(h),s.href=h,await this.navigate(s)}else if(u){let h={href:u,locations:{progression:0},created:new Date,title:a?.Title};await this.navigate(h)}return new Promise(h=>h())}catch(n){return console.error(n),this.abortOnError(n),new Promise((i,o)=>o(n)).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.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 l=this.publication.getTOCItem(n);this.currentTocUrl!==void 0&&(l=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&l!==void 0&&l.Title&&(this.currentChapterLink.title=l.Title),!this.currentChapterLink.type&&l!==void 0&&l.TypeLink&&(this.currentChapterLink.title=l.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 s=this.iframes[0].contentDocument?.body;this.rights.enableTTS&&this.tts?.enableSplitter&&(0,QO.default)({target:s,by:"lines"});let a=s?.querySelector("details");if(a){let u=this;a.addEventListener("toggle",async h=>{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.delegate=this,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 h=u.contentDocument?.body;this.ttsModule!==void 0&&(this.tts?.enableSplitter?await this.ttsModule.initialize(h):await this.ttsModule.initialize(h))}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 console.error(t),this.abortOnError(t),Promise.reject(t)}}async injectInjectablesIntoIframeHead(){let t=[],n=i=>{let o=new Promise((l,s)=>{i.onload=()=>{l(!0)},i.onerror=a=>{let u=typeof a=="string"?a:`Injectable failed to load at: ${"href"in i?i.href:i.src}`;s(new Error(u))}});t.push(o)};for(let i of this.iframes){let o=i.contentDocument?.head;o&&(o.insertBefore(fn.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 s=fn.createCssLink(l.url);o.appendChild(s),n(s)}}else if(l.r2before&&l.url){let s=fn.createCssLink(l.url);o.insertBefore(s,o.firstChild),n(s)}else if(l.r2default&&l.url){let s=fn.createCssLink(l.url);o.insertBefore(s,o.childNodes[1]),n(s)}else if(l.r2after&&l.url){l.appearance&&this.settings.initAddedAppearance();let s=fn.createCssLink(l.url);o.appendChild(s),n(s)}else if(l.url){let s=fn.createCssLink(l.url);o.appendChild(s),n(s)}}else if(l.type==="script"&&l.url){let s=fn.createJavascriptLink(l.url,l.async??!1);o.appendChild(s),n(s)}}))}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,h){let p=new DOMParser().parseFromString(u,"application/xhtml+xml");p.head&&p.head.insertBefore(fn.createBase(h),p.head.firstChild);let g=p.documentElement.outerHTML,y=t.iframes[0].contentDocument;y&&(y.open(),y.write(g),y.close())}function l(u,h){let p=new DOMParser().parseFromString(u,"application/xhtml+xml");p.head&&p.head.insertBefore(fn.createBase(h),p.head.firstChild);let g=p.documentElement.outerHTML,y=t.iframes[1].contentDocument;y&&(y.open(),y.write(g),y.close())}let s=new URL(this.currentChapterLink.href),a=window.location.protocol===s.protocol&&window.location.port===s.port&&window.location.hostname===s.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?a?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(h=>h.text()).then(async h=>{o.call(this,h,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 h=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.right={href:h},this.api?.getContent(h).then(f=>{f===void 0?a?this.iframes[1].src=h:fetch(h).then(p=>p.text()).then(async p=>{l.call(this,p,h),this.currentSpreadLinks.right={href:h}}):l.call(this,f,h)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let u=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(u){let h=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.left={href:h},this.api?.getContent(h).then(f=>{f===void 0?a?this.iframes[0].src=h:fetch(h).then(p=>p.text()).then(async p=>{o.call(this,p,h)}):o.call(this,f,h)})}}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?a?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(h=>h.text()).then(async h=>{l.call(this,h,this.currentChapterLink.href)}):l.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?a?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(h=>h.text()).then(async h=>{o.call(this,h,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?a?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)}):o.call(this,u,this.currentChapterLink.href)});else if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(a){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 h=this.publication.getAbsoluteHref(u.Href);this.iframes[1].src=h,this.currentSpreadLinks.right={href:h}}}else this.iframes[1].src="about:blank"}else if(fetch(this.currentChapterLink.href).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 h=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.right={href:h},fetch(h).then(f=>f.text()).then(async f=>{l.call(this,f,h)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let u=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(u){let h=this.publication.getAbsoluteHref(u.Href);this.currentSpreadLinks.left={href:h},a?(this.iframes[0].src=h,this.iframes.length===2&&(this.iframes[1].src=this.currentChapterLink.href)):(fetch(h).then(f=>f.text()).then(async f=>{o.call(this,f,h)}),this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},fetch(this.currentChapterLink.href).then(f=>f.text()).then(async f=>{l.call(this,f,this.currentChapterLink.href)})))}}else this.iframes[0].src="about:blank";this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},a?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(u=>u.text()).then(async u=>{l.call(this,u,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},a?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(u=>u.text()).then(async u=>{o.call(this,u,this.currentChapterLink.href)});else this.currentSpreadLinks.left={href:this.currentChapterLink.href},a?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href).then(u=>u.text()).then(async u=>{o.call(this,u,this.currentChapterLink.href)});this.publication.isFixedLayout&&setTimeout(()=>{let u,h,f;if(n===0&&this.iframes?.length===2?f=this.iframes[1].contentDocument:f=this.iframes[0].contentDocument,f&&f.body&&(u=getComputedStyle(f.body).height,h=getComputedStyle(f.body).width,parseInt(u?.replace("px",""))===0||parseInt(h?.replace("px",""))===0)){let _=hn(f,"head");if(_){let S=xe(_,"meta[name=viewport]");if(S){var p=S.content,g=p.split(",").reduce((x,R)=>{var[C,I]=R.match(/[^\s;=]+/g);return x[C]=isNaN(Number(I))?I:+I,x},{});u=g.height+"px",h=g.width+"px"}}}var y=n===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(y&&h){var E=(parseInt(getComputedStyle(y).width)-100)/(this.iframes.length===2?parseInt(h?.replace("px",""))*2+200:parseInt(h?.replace("px",""))),b=(parseInt(getComputedStyle(y).height)-100)/parseInt(u?.replace("px","")),w=Math.min(E,b);y.style.transform="scale("+w+")";for(let _ of this.iframes)_.style.height=u,_.style.width=h,_.parentElement&&(_.parentElement.style.height=u)}},400)}static goBack(){window.history.back()}static isDisplayed(t){return t?t.className.indexOf(" active")!==-1:!1}static showElement(t,n){if(t){if(t.className=t.className.replace(" inactive",""),t.className.indexOf(" active")===-1&&(t.className+=" active"),t.setAttribute("aria-hidden","false"),n){n.setAttribute("aria-expanded","true");let l=n.querySelector(".icon.open");if(l&&(l.getAttribute("class")||"").indexOf(" inactive-icon")===-1){let a=(l.getAttribute("class")||"")+" inactive-icon";l.setAttribute("class",a)}let s=n.querySelector(".icon.close");if(s){let a=(s.getAttribute("class")||"").replace(" inactive-icon","");s.setAttribute("class",a)}}let i=Array.prototype.slice.call(t.querySelectorAll("button")),o=Array.prototype.slice.call(t.querySelectorAll("a"));for(let l of i)l.tabIndex=0;for(let l of o)l.tabIndex=0}}static hideElement(t,n){if(t){if(t.className=t.className.replace(" active",""),t.className.indexOf(" inactive")===-1&&(t.className+=" inactive"),t.setAttribute("aria-hidden","true"),n){n.setAttribute("aria-expanded","false");let l=n.querySelector(".icon.open");if(l){let a=(l.getAttribute("class")||"").replace(" inactive-icon","");l.setAttribute("class",a)}let s=n.querySelector(".icon.close");if(s&&(s.getAttribute("class")||"").indexOf(" inactive-icon")===-1){let a=(s.getAttribute("class")||"")+" inactive-icon";s.setAttribute("class",a)}}let i=Array.prototype.slice.call(t.querySelectorAll("button")),o=Array.prototype.slice.call(t.querySelectorAll("a"));for(let l of i)l.tabIndex=-1;for(let l of o)l.tabIndex=-1}}hideModal(t,n){for(let i of this.iframes)i.setAttribute("aria-hidden","false");this.upLink&&this.upLink.setAttribute("aria-hidden","false"),this.linksBottom&&this.linksBottom.setAttribute("aria-hidden","false"),this.linksMiddle&&this.linksMiddle.setAttribute("aria-hidden","false"),this.loadingMessage&&this.loadingMessage.setAttribute("aria-hidden","false"),this.errorMessage&&this.errorMessage.setAttribute("aria-hidden","false"),this.infoTop&&this.infoTop.setAttribute("aria-hidden","false"),this.infoBottom&&this.infoBottom.setAttribute("aria-hidden","false"),fn.hideElement(t,n)}handleEditClick(t){var n=t.target;if(this.headerMenu){var i=xe(this.headerMenu,".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.tts?.enableSplitter?this.highlighter?.speakAll():this.ttsModule.speakPlay())}startReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.startReadAloud()}stopReadAloud(){this.rights.enableTTS&&(this.highlighter?.stopReadAloud(),this.tts?.enableSplitter||this.annotationModule!==void 0&&this.annotationModule.drawHighlights())}stopReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.stopReadAloud()}pauseReadAloud(){this.rights.enableTTS&&(this.tts?.enableSplitter?this.ttsModule.speakPause():(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.tts?.enableSplitter?this.ttsModule.speakResume():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 l=t.href.slice(t.href.indexOf("#")+1);l!==void 0&&(n=ln(it({},n),{fragment:l}))}let i=it({},t);i.locations=n;let o=this.publication.getAbsoluteHref(t.href);K&&console.log(t.href),K&&console.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)}}snapToSelector(t){let n=this.iframes[0].contentDocument;if(n){console.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){this.mDropdowns&&this.mDropdowns.forEach(n=>{n.close()})}handleInternalLink(t){let n=t.target,i={progression:0},o=n;if(o.href.indexOf("#")!==-1){let s=o.href.slice(o.href.indexOf("#")+1);s!==void 0&&(i={fragment:s})}let l={href:o.href,locations:i,type:o.type,title:o.title};t.preventDefault(),t.stopPropagation(),this.stopReadAloud(),this.navigate(l)}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 h=Fi()-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=h+40+"px";let f,p,g;t===0&&this.iframes?.length===2?g=this.iframes[1].contentDocument:g=this.iframes[0].contentDocument,g&&g.body&&(f=getComputedStyle(g.body).height,p=getComputedStyle(g.body).width);let y=hn(g,"head");if(y){let E=xe(y,"meta[name=viewport]");if(E){var i=E.content,o=i.split(",").reduce((b,w)=>{var[_,S]=w.match(/[^\s;=]+/g);return b[_]=isNaN(Number(S))?S:+S,b},{});(parseInt(o.height)!==0||parseInt(o.width)!==0)&&(f=o.height+"px",p=o.width+"px")}}var l=(parseInt(getComputedStyle(n).width)-100)/(this.iframes.length===2?parseInt(p?.replace("px",""))*2+200:parseInt(p?.replace("px",""))),s=(parseInt(getComputedStyle(n).height)-100)/parseInt(f?.replace("px","")),a=Math.min(l,s);n.style.transform="scale("+a+")";for(let E of this.iframes)E.style.height=f,E.style.width=p,E.parentElement&&(E.parentElement.style.height=f)}}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(h=>{h?(this.view.height=Fi()-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()},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())}hideBookmarksOnEscape(t){let n=27;fn.isDisplayed(this.bookmarksView)&&t.keyCode===n&&this.hideModal(this.bookmarksView,this.bookmarksControl)}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){if(this.publication.getTOCItem(t.href)){var i=!1;if(t.href.indexOf("#")!==-1){let o=t.href.slice(0,t.href.indexOf("#"));o===this.currentChapterLink.href&&(i=!0),this.currentChapterLink.href=o,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title}else t.href===this.currentChapterLink.href&&(i=!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(i){if(t.href.indexOf("#")!==-1){let h=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:h}}if(this.newPosition=t,this.currentTOCRawLink=t.href,t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.newElementId){for(let h of this.iframes){let f=h.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(f)}this.newElementId=void 0}else if(t.highlight){let h=t.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;h&&this.view?.goToCssSelector(h)}else this.view?.goToProgression(t.locations.progression??0);let o=this.currentChapterLink.href,l=this.publication.getPreviousSpineItem(o);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 s=this.publication.getNextSpineItem(o);s?this.nextChapterLink={href:s.Href,type:s.TypeLink,title:s.Title}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(o),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let a=this.publication.getSpineItem(o);a!==void 0&&(this.currentChapterLink.title=a.Title,this.currentChapterLink.type=a.TypeLink);let u=this.publication.getTOCItem(o);this.currentTocUrl!==void 0&&(u=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&u!==void 0&&u.Title&&(this.currentChapterLink.title=u.Title),!this.currentChapterLink.type&&u!==void 0&&u.TypeLink&&(this.currentChapterLink.title=u.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(nt.PageBreak),await this.pageBreakModule.drawPageBreaks()),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(nt.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(o=>{o||(this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))})}else{let o=this.publication.getStartLink(),l;if(o&&o.Href&&(l=this.publication.getAbsoluteHref(o.Href),l)){let s={href:l,locations:{progression:0},created:new Date,title:o.Title};await this.navigate(s)}}}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 l=Math.ceil((n.progression??0)*(o.length-1)),s=o[l];s&&(s.locations.fragment=n.fragment,i=ln(it({},s),{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=>(K&&console.log("api updated current location",i),this.annotator?.saveLastReadingPosition(i))):(K&&console.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=t,this.annotationModule.activeAnnotationMarkerPosition=n,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=t))}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 Ta("layer-on","layer-off",!0,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=Ue.R2_ID_HIGHLIGHTS_CONTAINER,i.name=Ue.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=Ue.R2_ID_READALOUD_CONTAINER,i.name=Ue.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=Ue.R2_ID_PAGEBREAK_CONTAINER,i.name=Ue.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=Ue.R2_ID_SEARCH_CONTAINER,i.name=Ue.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=Ue.R2_ID_DEFINITIONS_CONTAINER,i.name=Ue.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let l=xe(o,n);l&&(l.style.display="block")}}hideLayer(t){let n="#",i=new Ta("layer-on","layer-off",!1,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=Ue.R2_ID_HIGHLIGHTS_CONTAINER,i.name=Ue.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=Ue.R2_ID_READALOUD_CONTAINER,i.name=Ue.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=Ue.R2_ID_PAGEBREAK_CONTAINER,i.name=Ue.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=Ue.R2_ID_SEARCH_CONTAINER,i.name=Ue.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=Ue.R2_ID_DEFINITIONS_CONTAINER,i.name=Ue.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let l=xe(o,n);l&&(l.style.display="none")}}};T();var Nt=class{constructor(t){this.store=t.store}getLastReadingPosition(){let t=this.store.get(Nt.LAST_READING_POSITION);return t?JSON.parse(t):null}initLastReadingPosition(t){if(typeof t=="string")this.store.set(Nt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(Nt.LAST_READING_POSITION,n)}}saveLastReadingPosition(t){if(typeof t=="string")this.store.set(Nt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(Nt.LAST_READING_POSITION,n)}}initBookmarks(t){if(typeof t=="string"){let n=JSON.parse(t);this.store.set(Nt.BOOKMARKS,JSON.stringify(n))}else this.store.set(Nt.BOOKMARKS,JSON.stringify(t));return t}saveBookmark(t){let n=this.store.get(Nt.BOOKMARKS);if(n){let i=JSON.parse(n);i.push(t),this.store.set(Nt.BOOKMARKS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(Nt.BOOKMARKS,JSON.stringify(i))}return t}locatorExists(t,n){let i;switch(n){case hi.Bookmark:i=Nt.BOOKMARKS;break}let o=this.store.get(i);return o&&JSON.parse(o).filter(a=>a.href===t.href&&a.locations.progression===t.locations.progression).length>0?t:null}deleteBookmark(t){let n=this.store.get(Nt.BOOKMARKS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.id!==t.id),this.store.set(Nt.BOOKMARKS,JSON.stringify(i))}return t}getBookmarks(t){let n=this.store.get(Nt.BOOKMARKS);if(n){let i=JSON.parse(n);if(t){let o=i.filter(l=>l.href===t);return o=o.sort((l,s)=>{if(l.locations.progression&&s.locations.progression)return l.locations.progression-s.locations.progression}),o}return i=i.sort((o,l)=>{if(o.locations.progression&&l.locations.progression)return o.locations.progression-l.locations.progression}),i}return[]}initAnnotations(t){let n;typeof t=="string"?n=JSON.parse(t):n=t;let i=[];return n.forEach(o=>{let l=`${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}`,s=Ai.hash(l);o.highlight.id="R2_HIGHLIGHT_"+s;var a;a=o.color,Ge.isHexColor(a)&&(a=Ge.hexToRgbString(a)),o.highlight.color=a,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(Nt.ANNOTATIONS,JSON.stringify(i)),i}saveAnnotation(t){let n=this.store.get(Nt.ANNOTATIONS);if(n){let i=JSON.parse(n);i.push(t),this.store.set(Nt.ANNOTATIONS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(Nt.ANNOTATIONS,JSON.stringify(i))}return t}deleteAnnotation(t){let n=this.store.get(Nt.ANNOTATIONS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.id!==t),this.store.set(Nt.ANNOTATIONS,JSON.stringify(i))}return t}deleteSelectedAnnotation(t){let n=this.store.get(Nt.ANNOTATIONS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.highlight?.id!==t.highlight.id),this.store.set(Nt.ANNOTATIONS,JSON.stringify(i))}return t}getAnnotations(){let t=this.store.get(Nt.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(Nt.ANNOTATIONS);if(i){let l=JSON.parse(i).filter(s=>s.id===t);if(l.length>0){let s=n.document.getElementById(`${l[0].highlight.id}`);if(s){let a=0;if(s.hasChildNodes)for(let u=0;u<s.childNodes.length;u++){let h=s.childNodes[u],f=parseInt(h.style.top.replace("px",""));(f<a||a===0)&&(a=f)}else a=parseInt(s.style.top.replace("px",""));return a}}}return null}getAnnotation(t){let n=this.store.get(Nt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(l=>l.highlight?.id===t.id);if(o.length>0)return o[0]}return null}getAnnotationByID(t){let n=this.store.get(Nt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(l=>l.highlight?.id===t);if(o.length>0)return o[0]}return null}},Jo=Nt;Jo.LAST_READING_POSITION="last-reading-position",Jo.BOOKMARKS="bookmarks",Jo.ANNOTATIONS="annotations";T();T();var Xd=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 Ys=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 Xd}}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))}};T();var tx=At(_a()),nx=At(Bn());var cl=class extends tx.Link{};cl=hc([(0,nx.JsonObject)()],cl);function ul(r){let t,n,i,o;if(r instanceof Array)return r.map(function(l){return typeof l=="object"&&(l=ul(l)),l});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=ul(o)),i==="href1"?t.href=o:i==="typeLink"?t.type=o:t[i]=o);return t}T();var Eg=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(){K&&console.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let t=new _r,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}};T();var _g=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(){K&&console.log("Page Break module stop")}async start(){this.delegate.pageBreakModule=this,this.headerMenu&&(this.goToPageView=xe(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=xe(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=xe(this.headerMenu,"#goToPageNumberButton")),ve(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),ve(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 s=i.Href.slice(i.Href.indexOf("#")+1);s!==null&&(o={fragment:s})}let l={href:this.publication.getAbsoluteHref(i.Href),locations:o,type:i.TypeLink,title:i.Title};this.delegate.goTo(l)}}}async handleResize(){await this.delegate.highlighter?.destroyHighlights(nt.PageBreak),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{let n=this.delegate.iframes[0].contentDocument?.body?.querySelectorAll('[*|type="pagebreak"]'),i=this;function o(l){try{let s=i.delegate.iframes[0].contentDocument;return s?Dn(l,s,no):""}catch(s){return console.log("uniqueCssSelector:"),console.log(s),""}}if(n)for(let l=0;l<n.length;l++){let s=n[l];K&&console.log(s);let a=s.innerHTML,u=!1;s.innerHTML.length===0&&(a=s.getAttribute("title")??"",s.innerHTML=a,u=!0),s.innerHTML.length===0&&(a=(s.getAttribute("id")??"").replace(/[^0-9]/g,""),s.innerHTML=a,u=!0);let h=this.delegate.iframes[0].contentDocument;if(h){let f=this.delegate.highlighter?.dom(h.body).getWindow().document.createRange(),p=this.delegate.highlighter?.dom(h.body).getSelection();if(p.removeAllRanges(),f.selectNodeContents(s),p.addRange(f),!p.isCollapsed){let g=Mr(f,o);p.removeAllRanges(),g&&this.createPageBreakHighlight({rangeInfo:g,cleanText:"",rawText:""},a)}}u&&(s.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}`,l=Ai.hash(o),s="R2_PAGEBREAK_"+l;var i=!1;let a={color:"#000000",id:s,pointerInteraction:i,selectionInfo:t,marker:ot.Custom,icon:{id:"pageBreak",title:n,color:"#000000",position:"left"},type:nt.PageBreak};Yt.push(a);let u=this.delegate.highlighter?.createHighlightDom(this.delegate.iframes[0].contentWindow,a);return a.position=parseInt((u?.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px","")),a}catch(o){throw"Can't create highlight: "+o}}};T();var ix=At(yd()),Sg=class{constructor(t,n,i,o,l,s,a){this.voices=[];this.hasEventListener=!1;this.index=0;this.userScrolled=!1;this.delegate=t,this.tts=n,this.headerMenu=a,this.rights=i,this.highlighter=o,this.properties=l,this.api=s}initialize(t){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onSettingsChange(this.handleResize.bind(this)),this.body=t,this.clean=(0,ix.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),t.querySelectorAll("[data-word]").forEach(o=>{o.dataset.ttsColor=this.tts.color}),t.querySelectorAll("[data-whitespace]").forEach(o=>{o.dataset.ttsColor=this.tts.color}),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,ve(document,"wheel",this.wheel.bind(this)),ve(this.body,"wheel",this.wheel.bind(this)),ve(document,"keydown",this.wheel.bind(this)),ve(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this))))}initVoices(t){function n(){return new Promise(function(o,l){let s=window.speechSynthesis,a;a=setInterval(()=>{s.getVoices().length!==0&&(o(s.getVoices()),clearInterval(a))},10)})}n().then(async o=>{if(K&&console.log(o),this.voices=[],o.forEach(s=>{s.localService===!0&&this.voices.push(s)}),K&&console.log(this.voices),t&&this.headerMenu){var l=xe(this.headerMenu,"#preferred-languages");l&&this.voices.forEach(s=>{var a=document.createElement("option");a.value=s.name+":"+s.lang,a.innerHTML=s.name+" ("+s.lang+")",l.add(a)})}})}cancel(t=!0){t&&(this.api?.stopped&&this.api?.stopped(),this.delegate.emit("readaloud.stopped","stopped")),this.userScrolled=!1,window.speechSynthesis.cancel(),this.splittingResult&&this.delegate.tts?.enableSplitter&&this.splittingResult.forEach(n=>{n.dataset.ttsCurrentWord="false",n.dataset.ttsCurrentLine="false"})}handleResize(){this.body.querySelectorAll("[data-word]").forEach(i=>{i.dataset.ttsColor=this.tts.color,i.dataset.ttsCurrentWord="false",i.dataset.ttsCurrentLine="false"}),this.body.querySelectorAll("[data-whitespace]").forEach(i=>{i.dataset.ttsColor=this.tts.color,i.dataset.ttsCurrentWord="false",i.dataset.ttsCurrentLine="false"})}async speak(t,n,i){this.api?.started&&this.api?.started();var o=this;if(this.userScrolled=!1,this.cancel(!1),this.delegate.tts?.enableSplitter)if(n){var l=o.body.querySelectorAll("[data-word]"),s=t.range?.startContainer.parentElement;s?.tagName.toLowerCase()==="a"&&(s=s.parentElement),s?.dataset===void 0&&(s=s?.nextElementSibling);var a=t.range?.endContainer.parentElement;a?.tagName.toLowerCase()==="a"&&(a=a?.parentElement),a?.dataset===void 0&&(a=a?.previousElementSibling);var u=parseInt(s.dataset.wordIndex??""),h=parseInt(a.dataset.wordIndex??"")+1;let x=Array.from(l);this.splittingResult=x.slice(u,h)}else document.scrollingElement&&(document.scrollingElement.scrollTop=0),this.splittingResult=o.body.querySelectorAll("[data-word]");let f=n?new SpeechSynthesisUtterance(t?.cleanText):new SpeechSynthesisUtterance(this.clean);f.rate=this.tts.rate,f.pitch=this.tts.pitch,f.volume=this.tts.volume,K&&console.log("this.tts.voice.lang",this.tts.voice.lang);var p=!0;this.tts.voice&&this.tts.voice.lang&&(p=this.tts.voice.lang.indexOf("-")!==-1,p===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),p=!0)),K&&console.log("initialVoiceHasHyphen",p),K&&console.log("voices",this.voices);var g;p===!0?(g=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(x=>{var R=x.lang.replace("_","-");return R===this.tts.voice.lang&&x.name===this.tts.voice.name})[0]:void 0,g===void 0&&(g=this.tts.voice&&this.tts.voice.lang?this.voices.filter(x=>x.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(g=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(x=>x.lang===this.tts.voice.lang&&x.name===this.tts.voice.name)[0]:void 0,g===void 0&&(g=this.tts.voice&&this.tts.voice.lang?this.voices.filter(x=>x.lang===this.tts.voice.lang)[0]:void 0)),K&&console.log("initialVoice",g);var y=o.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;K&&console.log("publicationVoiceHasHyphen",y);var E;y===!0?E=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(x=>{var R=x.lang.replace("_","-");return R.startsWith(o.delegate.publication.Metadata.Language[0])||R.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:E=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(x=>x.lang.startsWith(o.delegate.publication.Metadata.Language[0])||x.lang.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,K&&console.log("publicationVoice",E);var b=navigator.language.indexOf("-")!==-1;K&&console.log("defaultVoiceHasHyphen",b);var w;b===!0?w=this.voices.filter(x=>{var R=x.lang.replace("_","-");return R===navigator.language&&x.localService===!0})[0]:w=this.voices.filter(x=>{var R=x.lang;return R===navigator.language&&x.localService===!0})[0],w===void 0&&(w=this.voices.filter(x=>{var R=x.lang;return R.includes(navigator.language)&&x.localService===!0})[0]),K&&console.log("defaultVoice",w),g?(K&&console.log("initialVoice"),f.voice=g):E?(K&&console.log("publicationVoice"),f.voice=E):w&&(K&&console.log("defaultVoice"),f.voice=w),f.voice!==void 0&&f.voice!==null&&(f.lang=f.voice.lang,K&&console.log("utterance.voice.lang",f.voice.lang),K&&console.log("utterance.lang",f.lang)),K&&console.log("navigator.language",navigator.language),window.speechSynthesis.speak(f),this.index=0;var _=void 0;f.onboundary=function(x){if(x.name==="sentence"&&K&&console.log("sentence boundary",x.charIndex,x.charLength,f.text.slice(x.charIndex,x.charIndex+x.charLength)),x.name==="word"){let C=function(I,z){I=String(I),z=Number(z)>>>0;var N=I.slice(0,z+1).search(/\S+$/),J=I.slice(z).search(/\s/);return J<0?I.slice(N):I.slice(N,J+z)}(f.text,x.charIndex);_===C&&o.index--,_=C,o.delegate.tts?.enableSplitter&&S(C)}};async function S(x){var R=x.replace(/[^a-zA-Z0-9 ]/g,"");K&&console.log("spokenWordCleaned",R);let C=o.splittingResult[o.index];var I=C?.dataset.word?.replace(/[^a-zA-Z0-9 ]/g,"");if(K&&console.log("splittingWordCleaned",I),I?.length===0&&(o.index++,C=o.splittingResult[o.index],I=C?.dataset.word?.replace(/[^a-zA-Z0-9 ]/g,""),K&&console.log("splittingWordCleaned",I)),C){var z=C.parentElement?.tagName.toLowerCase()==="a";z||(R.length>0&&I!==void 0&&I.length>0?I.startsWith(R)||I.endsWith(R)||R.startsWith(I)||R.endsWith(I)?(o.index>0&&(o.body.querySelectorAll("[data-word]").forEach(V=>{V.dataset.ttsColor=o.tts.color,V.dataset.ttsCurrentWord="false",V.dataset.ttsCurrentLine="false"}),o.body.querySelectorAll("[data-whitespace]").forEach(V=>{V.dataset.ttsColor=o.tts.color,V.dataset.ttsCurrentWord="false",V.dataset.ttsCurrentLine="false"})),C.dataset.ttsCurrentWord="true",o.delegate.view?.isScrollMode()&&o.tts.autoScroll&&!o.userScrolled&&C.scrollIntoView({block:"center",behavior:"smooth"})):o.index++:R.length===0&&o.index--),o.index++}}f.onend=function(){K&&console.log("utterance ended"),o.highlighter.doneSpeaking(),o.delegate.tts?.enableSplitter&&(o.body.querySelectorAll("[data-word]").forEach(C=>{C.dataset.ttsColor=o.tts.color,C.dataset.ttsCurrentWord="false",C.dataset.ttsCurrentLine="false"}),o.body.querySelectorAll("[data-whitespace]").forEach(C=>{C.dataset.ttsColor=o.tts.color,C.dataset.ttsCurrentWord="false",C.dataset.ttsCurrentLine="false"})),o.api?.finished()},i()}speakPause(){window.speechSynthesis.speaking&&(this.api?.paused&&this.api?.paused(),this.userScrolled=!1,window.speechSynthesis.pause())}speakResume(){window.speechSynthesis.speaking&&(this.api?.resumed&&this.api?.resumed(),this.userScrolled=!1,window.speechSynthesis.resume())}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=xe(this.headerMenu,"#menu-button-tts");this.rights.enableMaterial?t&&t.parentElement?.style.removeProperty("display"):t&&t.parentElement?.style.setProperty("display","none")}}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(){K&&console.log("TTS module stop"),He(document,"wheel",this.wheel.bind(this)),He(this.body,"wheel",this.wheel.bind(this)),He(document,"keydown",this.wheel.bind(this)),He(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this))}};T();var Mx=At(yd());var Rx=At(Zr()),kx=At(Ax());var Mg=class{constructor(t,n,i,o,l,s,a){this.voices=[];this.hasEventListener=!1;this.index=0;this.userScrolled=!1;this.speaking=!1;this.restartIndex=-1;this.ttsQueueIndex=-1;this.ttsQueue=void 0;this.ttsPlayQueueIndexDebounced=(0,Rx.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=a,this.rights=i,this.highlighter=o,this.properties=l,this.api=s}initialize(t){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=t,this.clean=(0,Mx.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,ve(document,"wheel",this.wheel.bind(this)),ve(this.body,"wheel",this.wheel.bind(this)),ve(document,"keydown",this.wheel.bind(this)),ve(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),ve(this.body,"click",this.click.bind(this)))}click(t){if(window.speechSynthesis.speaking&&this.speaking){let n=this.delegate.iframes[0].contentDocument;if(n){let i=this.highlighter.dom(n.body).getSelection(),o=i.getRangeAt(0),l=i.anchorNode;for(;o.toString().indexOf(" ")!==0;)try{o.setStart(l,o.startOffset-1)}catch(u){break}o.setStart(l,o.startOffset+1);do o.setEnd(l,l.length<o.endOffset?o.endOffset+1:l.length);while(o.toString().indexOf(" ")===-1&&o.toString().trim()!=="");let a=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(this.ttsQueue&&a){let u=this.findTtsQueueItemIndex(this.ttsQueue,i.anchorNode,i.focusNode,i.focusOffset,a);i.removeAllRanges(),u>=0&&(window.speechSynthesis.cancel(),this.restartIndex=u,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}}}}initVoices(t){function n(){return new Promise(function(o,l){let s=window.speechSynthesis,a;a=setInterval(()=>{s.getVoices().length!==0&&(o(s.getVoices()),clearInterval(a))},10)})}n().then(async o=>{if(K&&console.log(o),this.voices=[],o.forEach(s=>{s.localService===!0&&this.voices.push(s)}),K&&console.log(this.voices),t&&this.headerMenu){var l=xe(this.headerMenu,"#preferred-languages");l&&this.voices.forEach(s=>{var a=document.createElement("option");a.value=s.name+":"+s.lang,a.innerHTML=s.name+" ("+s.lang+")",l.add(a)})}})}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(nt.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 l;if(n){let y=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body,E=this.delegate.iframes[0].contentDocument;if(E){let b=this.highlighter.dom(E.body).getSelection();if(y){let w=this.generateTtsQueue(y,!0);if(!w.length)return;let _=this.findTtsQueueItemIndex(w,b.anchorNode,b.focusNode,b.focusOffset,y),S=Rg(w,_);if(S&&t&&t.cleanText){let R=kg(S).indexOf(t.cleanText);l=new SpeechSynthesisUtterance(t.cleanText),l.onboundary=C=>{console.log(C),this.updateTTSInfo(S,C.charIndex+R,C.charLength,l.text)}}}}}else l=new SpeechSynthesisUtterance(this.clean);l.rate=this.tts.rate,l.pitch=this.tts.pitch,l.volume=this.tts.volume,K&&console.log("this.tts.voice.lang",this.tts.voice.lang);var s=!0;this.tts.voice&&this.tts.voice.lang&&(s=this.tts.voice.lang.indexOf("-")!==-1,s===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),s=!0)),K&&console.log("initialVoiceHasHyphen",s),K&&console.log("voices",this.voices);var a;s===!0?(a=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(g=>{var y=g.lang.replace("_","-");return y===this.tts.voice.lang&&g.name===this.tts.voice.name})[0]:void 0,a===void 0&&(a=this.tts.voice&&this.tts.voice.lang?this.voices.filter(g=>g.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(a=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(g=>g.lang===this.tts.voice.lang&&g.name===this.tts.voice.name)[0]:void 0,a===void 0&&(a=this.tts.voice&&this.tts.voice.lang?this.voices.filter(g=>g.lang===this.tts.voice.lang)[0]:void 0)),K&&console.log("initialVoice",a);var u=o.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;K&&console.log("publicationVoiceHasHyphen",u);var h;u===!0?h=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(g=>{var y=g.lang.replace("_","-");return y.startsWith(o.delegate.publication.Metadata.Language[0])||y.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:h=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(g=>g.lang.startsWith(o.delegate.publication.Metadata.Language[0])||g.lang.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,K&&console.log("publicationVoice",h);var f=navigator.language.indexOf("-")!==-1;K&&console.log("defaultVoiceHasHyphen",f);var p;f===!0?p=this.voices.filter(g=>{var y=g.lang.replace("_","-");return y===navigator.language&&g.localService===!0})[0]:p=this.voices.filter(g=>{var y=g.lang;return y===navigator.language&&g.localService===!0})[0],p===void 0&&(p=this.voices.filter(g=>{var y=g.lang;return y.includes(navigator.language)&&g.localService===!0})[0]),K&&console.log("defaultVoice",p),a?(K&&console.log("initialVoice"),l.voice=a):h?(K&&console.log("publicationVoice"),l.voice=h):p&&(K&&console.log("defaultVoice"),l.voice=p),l.voice!==void 0&&l.voice!==null&&(l.lang=l.voice.lang,K&&console.log("utterance.voice.lang",l.voice.lang),K&&console.log("utterance.lang",l.lang)),K&&console.log("navigator.language",navigator.language),setTimeout(()=>{window.speechSynthesis.speak(l)},0),this.index=0,l.onend=function(){K&&console.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.delegate.emit("readaloud.finished","finished")},i()}speakPlay(){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 s=function(){let a=t.highlighter.visibleTextRects[0],u=t.delegate.iframes[0].contentDocument;if(u){let h=t.highlighter.dom(u.body).getWindow().document.createRange(),f=t.highlighter.dom(t.delegate.iframes[0].contentDocument?.body).getSelection();f.removeAllRanges(),h.selectNodeContents(a.node),f.addRange(h);let p=0,g=f.focusNode,y=f.focusOffset;f.collapse(f.anchorNode,f.anchorOffset);for(let E=0;E<p;E++)f.modify("move","forward","line");if(f.extend(g,y),f.collapse(f.anchorNode,f.anchorOffset),i){let E=t.findTtsQueueItemIndex(o,f.anchorNode,f.focusNode,f.focusOffset,i);E>=0&&(l=E)}f.removeAllRanges()}},o=this.generateTtsQueue(i,!0);if(!o.length)return;let l=0;s(),l<0&&(l=0),setTimeout(()=>{this.startTTSSession(o,l)},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(nt.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=xe(this.headerMenu,"#menu-button-tts");this.rights.enableMaterial?t&&t.parentElement?.style.removeProperty("display"):t&&t.parentElement?.style.setProperty("display","none")}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(){K&&console.log("TTS module stop"),He(document,"wheel",this.wheel.bind(this)),He(this.body,"wheel",this.wheel.bind(this)),He(document,"keydown",this.wheel.bind(this)),He(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),He(this.body,"click",this.click.bind(this))}generateTtsQueue(t,n){let i=[],o=[];function l(h){if(h.nodeType!==Node.TEXT_NODE||!h.nodeValue||!h.nodeValue.trim().length)return;let f=o[o.length-1];if(!f)return;let p=h.parentElement?Px(h.parentElement):void 0,g=h.parentElement?kD(h.parentElement):void 0,y=i[i.length-1];(!y||y.parentElement!==f||y.lang!==p||y.dir!==g)&&(y={combinedText:"",combinedTextSentences:void 0,combinedTextSentencesRangeBegin:void 0,combinedTextSentencesRangeEnd:void 0,dir:g,lang:p,parentElement:f,textNodes:[]},i.push(y)),y.textNodes.push(h)}let s=!0;function a(h){if(h.nodeType!==Node.ELEMENT_NODE)return;let f=s||h.matches("h1, h2, h3, h4, h5, h6, p, th, td, caption, li, blockquote, q, dt, dd, figcaption, div, pre");s=!1,f&&o.push(h);for(let p of h.childNodes)switch(p.nodeType){case Node.ELEMENT_NODE:let g=p;if(!g.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))a(g);else if(g.tagName&&g.tagName.toLowerCase()==="img"&&g.src){let E=g.getAttribute("alt");if(E){let b=E.trim();if(b){let w=Px(g),_=void 0;i.push({combinedText:b,combinedTextSentences:void 0,combinedTextSentencesRangeBegin:void 0,combinedTextSentencesRangeEnd:void 0,dir:_,lang:w,parentElement:g,textNodes:[]})}}}break;case Node.TEXT_NODE:o.length!==0&&l(p);break;default:break}f&&o.pop()}a(t);function u(h){if(!h.textNodes||!h.textNodes.length){(!h.combinedText||!h.combinedText.length)&&(h.combinedText=""),h.combinedTextSentences=void 0;return}h.combinedText=PD(h.textNodes,!0).replace(/[\r\n]/g," ");let f=!1,p=h.parentElement;for(;p;){if(p.tagName){let g=p.tagName.toLowerCase();if(g==="pre"||g==="code"||g==="video"||g==="audio"){f=!0;break}}p=p.parentElement}if(n&&!f)try{let g=h.combinedText;h.combinedTextSentences=void 0;let y=(0,kx.split)(g);h.combinedTextSentences=[],h.combinedTextSentencesRangeBegin=[],h.combinedTextSentencesRangeEnd=[];for(let E of y)E.type==="Sentence"&&(h.combinedTextSentences.push(E.raw),h.combinedTextSentencesRangeBegin.push(E.range[0]),h.combinedTextSentencesRangeEnd.push(E.range[1]));(h.combinedTextSentences.length===0||h.combinedTextSentences.length===1)&&(h.combinedTextSentences=void 0)}catch(g){console.log(g),h.combinedTextSentences=void 0}else h.combinedTextSentences=void 0}for(let h of i)u(h);return i}findTtsQueueItemIndex(t,n,i,o,l){let s=0;for(let a of t){if(i&&a.textNodes){if(a.textNodes.includes(i))if(a.combinedTextSentences&&a.combinedTextSentencesRangeBegin&&a.combinedTextSentencesRangeEnd){let u=0;for(let f of a.textNodes)if(!(!f.nodeValue&&f.nodeValue!=="")){if(f===i){u+=o;break}u+=f.nodeValue.length}let h=s-1;for(let f of a.combinedTextSentencesRangeEnd)if(h++,!(f<u))return h;return s}else return s}else if(n===a.parentElement||a.parentElement!==n.ownerDocument.body&&a.parentElement!==l&&a.parentElement.contains(n)||n.contains(a.parentElement))return s;a.combinedTextSentences?s+=a.combinedTextSentences.length:s++}return-1}restart(){window.speechSynthesis.speaking&&(window.speechSynthesis.cancel(),this.restartIndex=this.ttsQueueIndex,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}startTTSSession(t,n){if(!Rg(t,n)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(n,t)}ttsPlayQueueIndex(t,n){if(t<0){this.cancel();return}let i=Rg(n,t);if(!i){this.cancel();return}let o=kg(i);if(!o){this.cancel();return}let l=new SpeechSynthesisUtterance(o);l.rate=this.tts.rate,l.pitch=this.tts.pitch,l.volume=this.tts.volume,K&&console.log("this.tts.voice.lang",this.tts.voice.lang);var s=!0;this.tts.voice&&this.tts.voice.lang&&(s=this.tts.voice.lang.indexOf("-")!==-1,s===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),s=!0)),K&&console.log("initialVoiceHasHyphen",s),K&&console.log("voices",this.voices);var a;s===!0?(a=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(y=>{var E=y.lang.replace("_","-");return E===this.tts.voice.lang&&y.name===this.tts.voice.name})[0]:void 0,a===void 0&&(a=this.tts.voice&&this.tts.voice.lang?this.voices.filter(y=>y.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(a=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(y=>y.lang===this.tts.voice.lang&&y.name===this.tts.voice.name)[0]:void 0,a===void 0&&(a=this.tts.voice&&this.tts.voice.lang?this.voices.filter(y=>y.lang===this.tts.voice.lang)[0]:void 0)),K&&console.log("initialVoice",a);var u=this,h=u.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;K&&console.log("publicationVoiceHasHyphen",h);var f;h===!0?f=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(y=>{var E=y.lang.replace("_","-");return E.startsWith(u.delegate.publication.Metadata.Language[0])||E.endsWith(u.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:f=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(y=>y.lang.startsWith(u.delegate.publication.Metadata.Language[0])||y.lang.endsWith(u.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,K&&console.log("publicationVoice",f);var p=navigator.language.indexOf("-")!==-1;K&&console.log("defaultVoiceHasHyphen",p);var g;p===!0?g=this.voices.filter(y=>{var E=y.lang.replace("_","-");return E===navigator.language&&y.localService===!0})[0]:g=this.voices.filter(y=>{var E=y.lang;return E===navigator.language&&y.localService===!0})[0],g===void 0&&(g=this.voices.filter(y=>{var E=y.lang;return E.includes(navigator.language)&&y.localService===!0})[0]),K&&console.log("defaultVoice",g),a?(K&&console.log("initialVoice"),l.voice=a):f?(K&&console.log("publicationVoice"),l.voice=f):g&&(K&&console.log("defaultVoice"),l.voice=g),l.voice!==void 0&&l.voice!==null&&(l.lang=l.voice.lang,K&&console.log("utterance.voice.lang",l.voice.lang),K&&console.log("utterance.lang",l.lang)),K&&console.log("navigator.language",navigator.language),l.onboundary=y=>{console.log(y.name),this.updateTTSInfo(i,y.charIndex,y.charLength,l.text)},setTimeout(()=>{window.speechSynthesis.speak(l),u.speaking||window.speechSynthesis.pause()},0),l.onend=function(){u.speaking&&u.ttsPlayQueueIndexDebounced(t+1,n)}}updateTTSInfo(t,n,i,o){if(!t)return;let l=o||kg(t);if(n>=0&&o){let s=o.slice(0,n+1).search(/\S+$/),a=o.slice(n).search(/\s/),u=a<0?o.slice(s):o.slice(s,a+n),h=s+u.length,f=!1;i?f=!1:(i=u.length,f=!0),this.wrapHighlightWord(t,o,f?s:n,i,u,s,h)}return l}wrapHighlightWord(t,n,i,o,l,s,a){this._ttsQueueItemHighlightsWord&&(this.delegate.highlighter?.destroyHighlights(nt.ReadAloud),this._ttsQueueItemHighlightsWord=void 0);let u=t.item,h=t.item.combinedText,f=i;if(u.combinedTextSentences&&u.combinedTextSentencesRangeBegin&&u.combinedTextSentencesRangeEnd&&t.iSentence>=0&&(f+=u.combinedTextSentencesRangeBegin[t.iSentence],h=u.combinedTextSentences[t.iSentence]),K){n!==h&&console.log("TTS utteranceText DIFF?? ",`[[${n}]]`,`[[${h}]]`);let S=n.substr(i,o);S!==l&&console.log("TTS word DIFF?? ",`[[${S}]]`,`[[${l}]]`,`${i}--${o}`,`${s}--${a-s}`)}let p=0,g,y=-1,E,b=-1,w=f+o;for(let S of u.textNodes){if(!S.nodeValue&&S.nodeValue!=="")continue;let x=S.nodeValue.length;if(p+=x,g||f<p&&(g=S,y=x-(p-f)),g&&w<=p&&(E=S,b=x-(p-w)),E)break}if(g&&E){let x=function(I){try{let z=_.delegate.iframes[0].contentDocument;return z?Dn(I,z,no):""}catch(z){return console.log("uniqueCssSelector:"),console.log(z),""}},S=new Range;S.setStart(g,y),S.setEnd(E,b);var _=this;let R=Mr(S,x);if(!R)return;let C=this.delegate.highlighter?.createHighlight(this.delegate.iframes[0].contentWindow,{rangeInfo:R,cleanText:"",rawText:"",range:void 0},this.tts.color,!1,ot.Custom,{id:"tts",title:"",position:"right"},void 0,{defaultClass:this.tts.color},nt.ReadAloud,"R2_READALOUD_");C&&(this._ttsQueueItemHighlightsWord=C[0],this.delegate.view?.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&C[1]?.firstChild?.scrollIntoView({block:"center",behavior:"smooth"}))}}};function Px(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 kD(r){let t=r;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let n=t.getAttribute("dir");if(n)return n;t=t.parentNode}}function PD(r,t){if(r&&r.length){let n="";for(let i of r)i.nodeValue&&(n+=t?i.nodeValue:ID(i.nodeValue));return n}return""}function LD(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ID(r){return LD(r).replace(/\n/g," ").replace(/\s\s+/g," ")}function Rg(r,t){let n=-1,i=-1;for(let o of r)if(i++,o.combinedTextSentences){let l=-1;for(let s of o.combinedTextSentences)if(l++,n++,t===n)return{item:o,iArray:i,iGlobal:n,iSentence:l}}else if(n++,t===n)return{item:o,iArray:i,iGlobal:n,iSentence:-1}}function kg(r){return r.iSentence===-1?r.item.combinedText:r.item.combinedTextSentences?r.item.combinedTextSentences[r.iSentence]:""}T();var pl=At(Cd());var Lx=At(Zr());var Pg=class{constructor(t,n,i,o,l){this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,Lx.debounce)(async()=>{if(await this.highlighter.destroyHighlights(nt.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=l,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(){K&&console.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 l=[];if(o)for(let s of t.terms){let a=t.terms.indexOf(s);o&&await Js(s,this.delegate.iframes[0].contentDocument,o.Href,o.Title,this.delegate.definitionsModule?.properties.fullWordSearch).then(u=>{let h;t.result==1?h=0:t.result==2&&(h=Math.floor(Math.random()*u.length-1)+1),u.forEach((f,p)=>{if(h===void 0||h===p){let g={rangeInfo:f.rangeInfo},y=this.createDefinitionHighlight(g,t);f.highlight=y,l.push(pl.omit(y,"definition")),this.currentChapterPopupResult.push(f),this.currentPopupHighlights.push(y)}}),a===t.terms.length-1&&n(l)})}}async define(t){await this.searchAndPaint(t,async n=>{this.api?.success&&(this.api?.success(pl.omit(t,"callbacks"),n),this.delegate.emit("definition.success",n),this.api?.visible&&n.forEach(i=>{let l=this.delegate.iframes[0].contentDocument?.querySelector(`#${i.id}`)?.querySelectorAll(`.${pi}`),s=new IntersectionObserver((a,u)=>{a.forEach(h=>{h.intersectionRatio===1&&(this.api?.visible(pl.omit(t,"callbacks"),pl.omit(i,"definition")),this.delegate.emit("definition.visible",t,i))})},{threshold:1});l&&l.length>0&&s.observe(l[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;Ge.isHexColor(i)&&(i=Ge.hexToRgbChannels(i));let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,l=Ai.hash(o),s="R2_DEFINITION_"+l;this.highlighter.destroyHighlight(this.delegate.iframes[0].contentDocument,s);let a={color:i||jo,id:s,pointerInteraction:!0,selectionInfo:t,marker:ot.Underline,type:nt.Definition};Yt.push(a);let u=this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,a);return u&&(n.definition&&(u.dataset.definition=n.definition),u.dataset.order=String(n.order),a.definition=n,a.position=parseInt((u?.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px",""))),a}catch(i){throw"Can't create definitions highlight: "+i}}async addDefinition(t){await this.define(t)}async clearDefinitions(){await this.highlighter.destroyHighlights(nt.Definition)}};T();var Ix=.5,ch=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(){K&&console.log("Definitions module stop"),this.hasEventListener=!1,He(document,"keydown",this.keydown.bind(this)),He(document,"keyup",this.keyup.bind(this)),He(this.delegate.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),He(this.delegate.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){this.delegate.lineFocusModule=this;let t=St(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,ve(document,"keydown",this.keydown.bind(this)),ve(document,"keyup",this.keyup.bind(this)),ve(this.delegate.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),ve(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=St(document,"#iframe-wrapper");this.wrapperHeight&&(n.style.height=this.wrapperHeight),t||(this.index=0);let i=this.delegate.iframes[0].contentDocument;hn(i,"html").style.removeProperty("--USER__maxMediaHeight"),this.wrapperHeight=void 0,this.lineFocusContainer&&(this.lineFocusContainer.style.display="none");let l=document.getElementById("container-view-timeline");l&&l.style.removeProperty("display");let s=document.getElementById("divBefore");s&&s.remove();let a=document.getElementById("divAfter");a&&a.remove(),this.highlighter.destroyHighlights(nt.LineFocus)}lineFocus(){let t=St(document,"#iframe-wrapper"),n=this.delegate.iframes[0].contentDocument,i=hn(n,"html"),o=this.properties.maxHeight?Fi()*this.properties.maxHeight/100:Fi()/2;i.style.setProperty("--USER__maxMediaHeight",o+"px");function l(f,p){f.parentNode.insertBefore(p,f.nextSibling)}function s(f,p){f.parentNode.insertBefore(p,f)}let a=document.getElementById("container-view-timeline");a&&(a.style.display="none"),this.lineFocusContainer&&this.lineFocusContainer.style.removeProperty("display");let u=document.getElementById("divBefore");if(u)u.style.height=t.clientHeight/2+"px";else{let f=document.createElement("div");f.style.height=t.clientHeight/2+"px",f.id="divBefore",s(t,f)}let h=document.getElementById("divAfter");if(h)h.style.height=t.clientHeight/2+"px";else{let f=document.createElement("div");f.style.height=t.clientHeight/2+"px",f.id="divAfter",l(t,f)}if(this.lines=[],n){let g=function(){let S=Math.round,x=Math.random,R=255;return{blue:S(x()*R),green:S(x()*R),red:S(x()*R)}},y=function(S,x){let R=[];for(let C=0,I=0;C<S.length;C++)C>=x&&C%x==0&&I++,R[I]=R[I]||[],R[I].push(S[C]);return R},E=function(S,x){let R=Math.min(S.left,x.left),C=Math.max(S.right,x.right),I=Math.min(S.top,x.top),z=Math.max(S.bottom,x.bottom);return{bottom:z,height:z-I,left:R,right:C,top:I,width:C-R}},b=function(S){if(S.length>1){let x=E(S[0],S[1]);if(S.length>2){let R=E(x,S[2]);if(S.length>3){let C=E(R,S[3]);return S.length>4?E(C,S[4]):C}return R}return x}return S[0]},f=this.findRects(n.body);f=y0(f,!0),f=f.sort(function(S,x){return S.top-x.top});let p=[];f=f.filter(function(S){let x=S.top;return p.indexOf(x)===-1&&p.indexOf(x+1)===-1&&p.indexOf(x+2)===-1&&p.indexOf(x+3)===-1&&p.indexOf(x+4)===-1&&p.indexOf(x-1)===-1&&p.indexOf(x-2)===-1&&p.indexOf(x-3)===-1&&p.indexOf(x-4)===-1?(p.push(x),!0):!1}),this.highlighter.destroyHighlights(nt.LineFocus);let w=[];this.properties.lines&&this.properties.lines>1?y(f,this.properties.lines).forEach(x=>{w.push(b(x))}):w=f;let _=xe(n,"#"+Ue.R2_ID_LINEFOCUS_CONTAINER);if(_)for(let S of w){let x=document.createElement("div");x.setAttribute("class",pi);let R=g();if(Ge.isHexColor(R)&&(R=Ge.hexToRgbChannels(R)),this.isDebug){let Ce=`border-bottom: 1px solid rgba(${R.red}, ${R.green}, ${R.blue}, ${Ix}) !important`;x.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${R.red}, ${R.green}, ${R.blue}, ${Ix}) !important; ${Ce}`)}x.style.outline="none",x.tabIndex=0;let C=this.delegate.iframes[0].contentWindow.document,I=this.delegate.view.isPaginated();I?C.body.style.position="revert":C.body.style.position="relative";let z=C.body.getBoundingClientRect(),N=this.highlighter.getScrollingElement(C),J=I?-N.scrollLeft:z.left,V=I?-N.scrollTop:z.top,j=1,D=24,U,Y,be=this.delegate.iframes[0].contentWindow?.innerWidth,le=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-count")),_e=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-width")),me=parseInt(getComputedStyle(n.body).getPropertyValue("padding-left"));if(be){let Ce=be/(le||1);Ce<_e&&(Ce=be),I||(Ce=parseInt(getComputedStyle(n.body).width.replace("px","")));let De=this.delegate.settings.fontSize/100,ce=20*De;De<=1&&(ce=-60);let Pe=0;De<=1&&(Pe=-60),U=Math.floor(S.left/Ce)*Ce+Ce-(D<40?40:D)+Pe,Y=Math.floor(S.left/Ce)*Ce+(D<40?40:D)-ce;let Le=parseInt(n.documentElement.style.getPropertyValue("--USER__pageMargins"));Le>=2&&(Y=Y+me/le,U=U-me/le),I||(U=parseInt(getComputedStyle(n.body).width.replace("px","")),Y=parseInt(getComputedStyle(n.body).width.replace("px",""))-Ce,Le>=2&&(Y=Y+me/2,U=U-me/2))}x.style.setProperty("pointer-events","none"),x.style.position="absolute",x.scale=j,x.rect={height:S.height,left:S.left-J,top:S.top-V,width:S.width},x.style.width=`${x.rect.width*j}px`,x.style.height=`${x.rect.height*j}px`,x.style.left=`${x.rect.left*j}px`,x.style.top=`${x.rect.top*j}px`,this.lines.push(x),_.append(x)}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 s=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=s+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=s+"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 s=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=s+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=s+"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 s=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=s+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=s+"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(l=>{o.push(...this.measureTextNodes(l))}),i.forEach(l=>{o.push(...this.measureImageNodes(l))}),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){K&&(console.log("measureTextNode "+n),console.log("measureTextNode "+t),console.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){K&&(console.log("measureTextNode "+n),console.log("measureTextNode "+t),console.log(t.textContent))}}};var Yo=class{constructor(t,n,i,o,l,s,a,u,h,f,p,g,y,E,b){this.settings=t;this.navigator=n;this.highlighter=i;this.bookmarkModule=o;this.annotationModule=l;this.ttsSettings=s;this.ttsModule=a;this.searchModule=u;this.definitionsModule=h;this.contentProtectionModule=f;this.timelineModule=p;this.mediaOverlaySettings=g;this.mediaOverlayModule=y;this.pageBreakModule=E;this.lineFocusModule=b;this.startReadAloud=()=>{this.navigator.startReadAloud()};this.stopReadAloud=()=>{this.navigator.stopReadAloud()};this.pauseReadAloud=()=>{this.navigator.pauseReadAloud()};this.resumeReadAloud=()=>{this.navigator.resumeReadAloud()};this.startReadAlong=()=>{this.navigator.startReadAlong()};this.stopReadAlong=()=>{this.navigator.stopReadAlong()};this.pauseReadAlong=()=>{this.navigator.pauseReadAlong()};this.resumeReadAlong=()=>{this.navigator.resumeReadAlong()};this.saveBookmark=async()=>await this.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?.hideLayer(t);this.showLayer=t=>this.navigator?.showLayer(t);this.activateMarker=(t,n)=>this.navigator?.activateMarker(t,n);this.deactivateMarker=()=>this.navigator?.deactivateMarker();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.rights.enableSearch&&await this.searchModule?.goToSearchIndex(t,n,i)};this.goToSearchID=async(t,n,i)=>{this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchID(t,n,i)};this.clearSearch=async()=>{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=>await this.settings.scroll(t);this.increase=async t=>{this.isTTSIncrementable(t)?this.navigator.rights.enableTTS&&await this.ttsSettings?.increase(t):this.isMOIncrementable(t)?this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.increase(t):await this.settings.increase(t)};this.decrease=async t=>{this.isTTSIncrementable(t)?this.navigator.rights.enableTTS&&await this.ttsSettings?.decrease(t):this.isMOIncrementable(t)?this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.decrease(t):await this.settings.decrease(t)};this.resetTTSSettings=()=>{this.navigator.rights.enableTTS&&this.ttsSettings?.resetTTSSettings()};this.applyTTSSettings=async t=>{this.navigator.rights.enableTTS&&await this.ttsSettings?.applyTTSSettings(t)};this.applyPreferredVoice=async t=>{this.navigator.rights.enableTTS&&await this.ttsSettings?.applyPreferredVoice(t)};this.resetMediaOverlaySettings=async()=>{this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.resetMediaOverlaySettings()};this.applyMediaOverlaySettings=async 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.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.snapToSelector(t)};this.applyAttributes=t=>{this.navigator.applyAttributes(t)};this.stop=()=>{document.body.onscroll=()=>{},this.navigator.stop(),this.settings.stop(),this.ttsSettings?.stop(),this.ttsSettings?.enableSplitter?this.ttsModule?.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.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,enableMaterial:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1};n.enableContentProtection&&t.protection&&await qd.setupPreloadProtection(t.protection);let i=St(document,"#D2Reader-Container"),o=xe(document,"#headerMenu"),l=xe(document,"#footerMenu"),s=t.url,a=new Ys({prefix:s.href,useLocalStorage:t.useLocalStorage??!1}),u=new Ys({prefix:"r2d2bc-reader",useLocalStorage:t.useLocalStorage??!1}),h=new Ys({prefix:"r2d2bc-layers",useLocalStorage:t.useLocalStorage??!1}),f=new Jo({store:a}),p=t.upLinkUrl??void 0,g=await Mo.fromUrl(s);g.sample=t.sample,n=BD(n,g),n.autoGeneratePositions?await g.autoGeneratePositions():(t.services?.positions&&await g.fetchPositionsFromService(t.services?.positions.href),t.services?.weight&&await g.fetchWeightsFromService(t.services?.weight.href));let y=await Eg.create({store:h}),E=await No.create({store:u,initialUserSettings:t.userSettings,headerMenu:o,material:t.material,api:t.api,injectables:(g.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed:t.injectables,layout:(g.Metadata.Rendition?.Layout??"unknown")==="fixed"?"fixed":"reflowable"}),b=await fn.create({mainElement:i,headerMenu:o,footerMenu:l,publication:g,settings:E,annotator:f,upLink:p,initialLastReadingPosition:t.lastReadingPosition,material:t.material,api:t.api,rights:n,tts:t.tts,sample:t.sample,injectables:(g.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed:t.injectables,attributes:t.attributes,services:t.services}),w=await Ge.create(it({delegate:b,layerSettings:y},t.highlighter)),_=n.enableBookmarks?await il.create(it({annotator:f,headerMenu:o,rights:n,publication:g,delegate:b,initialAnnotations:t.initialAnnotations},t.bookmarks)):void 0,S=n.enableAnnotations?await nl.create(it({annotator:f,rights:n,publication:g,delegate:b,initialAnnotations:t.initialAnnotations,highlighter:w,headerMenu:o},t.annotations)):void 0,x=n.enableTTS,R=x?await vg.create({store:u,initialTTSSettings:t.tts,headerMenu:o}):void 0,C;t.tts?.enableSplitter??!1?x&&R&&(C=await Sg.create(it({delegate:b,tts:R,headerMenu:o,rights:n,highlighter:w},t.tts))):x&&R&&(C=await Mg.create(it({delegate:b,tts:R,headerMenu:o,rights:n,highlighter:w},t.tts)));let I=n.enableSearch?await mg.create(it({headerMenu:o,delegate:b,publication:g,highlighter:w},t.search)):void 0,z=n.enableDefinitions?await Pg.create(it({delegate:b,publication:g,highlighter:w},t.define)):void 0,N=n.enableTimeline?await J0.create({publication:g,delegate:b}):void 0,J=n.enableContentProtection?await qd.create(it({delegate:b},t.protection)):void 0,V=n.enableMediaOverlays,j=V?await V0.create(it({store:u,initialMediaOverlaySettings:t.mediaOverlays,headerMenu:o},t.mediaOverlays)):void 0,D=V?await G0.create(it({publication:g,delegate:b,settings:j},t.mediaOverlays)):void 0,Y=n.enablePageBreaks&&g.isReflowable?await _g.create(it({publication:g,headerMenu:o,delegate:b},t.pagebreak)):void 0,be=n.enableLineFocus?await ch.create(it({publication:g,delegate:b,highlighter:w},t.lineFocus)):void 0;return new Yo(E,b,w,_,S,R,C,I,z,J,N,j,D,Y,be)}get hasMediaOverlays(){return this.navigator.hasMediaOverlays}get tableOfContents(){return ul(this.navigator.tableOfContents())??[]}get readingOrder(){return ul(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.mostRecentNavigatedTocItem()}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.atStart()}get atEnd(){return this.navigator.atEnd()}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 BD(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 ND=Yo,DD=Yo.load;return HD;})();
87
87
  /*!
88
88
  * Materialize v1.0.0 (http://materializecss.com)
89
89
  * Copyright 2014-2017 Materialize