@d-i-t-a/reader 2.1.1 → 2.1.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
@@ -72,14 +72,14 @@ function print() { __p += __j.call(arguments, '') }
72
72
  </svg>`,$s=(i,t,n,r="icon",o,a)=>`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" height="${o}" viewBox="${O4}" style="fill:${a}" preserveAspectRatio="xMidYMid meet" role="img" class="${r}" aria-labelledBy="${i}">
73
73
  <title id="${i}">${t}</title>
74
74
  ${n}
75
- </svg>`,$r={error:Gn("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:Gn("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:O8("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:Gn("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:Gn("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:Gn("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:Gn("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:Gn("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:Gn("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:Gn("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:Gn("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:Gn("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:Gn("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:Gn("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:Gn("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 p0=Je(Ed());var Mn=Je(Dt()),Re;(function(d){d.R2_ID_HIGHLIGHTS_CONTAINER="R2_ID_HIGHLIGHTS_CONTAINER",d.R2_ID_BOOKMAKRS_CONTAINER="R2_ID_BOOKMAKRS_CONTAINER",d.R2_ID_READALOUD_CONTAINER="R2_ID_READALOUD_CONTAINER",d.R2_ID_PAGEBREAK_CONTAINER="R2_ID_PAGEBREAK_CONTAINER",d.R2_ID_SEARCH_CONTAINER="R2_ID_SEARCH_CONTAINER",d.R2_ID_DEFINITIONS_CONTAINER="R2_ID_DEFINITIONS_CONTAINER",d.R2_ID_LINEFOCUS_CONTAINER="R2_ID_LINEFOCUS_CONTAINER",d.R2_ID_GUTTER_RIGHT_CONTAINER="R2_ID_GUTTER_RIGHT_CONTAINER"})(Re||(Re={}));var x4="R2_CLASS_HIGHLIGHT_CONTAINER",Ya="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",hn="R2_CLASS_HIGHLIGHT_AREA",Za="R2_CLASS_HIGHLIGHT_ICON",ii=.5,_4=.75,Fo={blue:100,green:50,red:230},zt=[],x8="data-highlighted",_8="data-timestamp",qs={ELEMENT_NODE:1,TEXT_NODE:3},to=[Re.R2_ID_HIGHLIGHTS_CONTAINER,Re.R2_ID_PAGEBREAK_CONTAINER,Re.R2_ID_SEARCH_CONTAINER,Re.R2_ID_READALOUD_CONTAINER,Re.R2_ID_BOOKMAKRS_CONTAINER,Re.R2_ID_DEFINITIONS_CONTAINER,Re.R2_ID_LINEFOCUS_CONTAINER,Re.R2_ID_GUTTER_RIGHT_CONTAINER,x4,hn,Ya],g0=-1,m0=-1,De=class{constructor(t,n,r,o,a,l){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.showTool=(0,Ka.debounce)(t=>{this.isAndroid()||this.snapSelectionToWord(t),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,Ka.debounce)(()=>{this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen(),this.delegate.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,Ka.debounce)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.delegate.emit("toolbox.closed","closed"))},100);this.selection=(0,Ka.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=r,this.api=l,this.hasEventListener=o,this.options=this.defaults(a,{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(r=>r(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(),g0=-1,m0=-1;let n=this;async function r(){n.lastSelectedHighlight===void 0||(n.lastSelectedHighlight=void 0)}setTimeout(async()=>{let o=this.delegate.iframes[0].contentDocument;o&&await o.body?.addEventListener("click",r)},100)}haveSameColor(t,n){return this.dom(t).color()===this.dom(n).color()}defaults(t,n){t=t||{};for(let r in n)n.hasOwnProperty(r)&&t[r]===void 0&&(t[r]=n[r]);return t}unique(t){return t.filter(function(n,r,o){return o.indexOf(n)===r})}refineRangeBoundaries(t){let n=t.startContainer,r=t.endContainer,o=t.commonAncestorContainer,a=!0;if(t.endOffset===0){for(;!r.previousSibling&&r.parentNode!==o;)r=r.parentNode;r=r.previousSibling}else r.nodeType===qs.TEXT_NODE?t.endOffset<r.nodeValue.length&&r.splitText(t.endOffset):t.endOffset>0&&(r=r.childNodes.item(t.endOffset-1));return n.nodeType===qs.TEXT_NODE?t.startOffset===n.nodeValue.length?a=!1:t.startOffset>0&&(n=n.splitText(t.startOffset),r===n.previousSibling&&(r=n)):t.startOffset<n.childNodes.length?n=n.childNodes.item(t.startOffset):n=n.nextSibling,{startContainer:n,endContainer:r,goDeeper:a}}sortByDepth(t,n){let r=this;t.sort(function(o,a){return r.dom(n?a:o).parents().length-r.dom(n?o:a).parents().length})}groupHighlights(t){let n=[],r={},o=[];return t.forEach(function(a){let l=a.getAttribute(_8);typeof r[l]=="undefined"&&(r[l]=[],n.push(l)),r[l].push(a)}),n.forEach(function(a){let l=r[a];o.push({chunks:l,timestamp:a,toString:function(){return l.map(function(u){return u.textContent}).join("")}})}),o}dom(t){let n=this;return{addClass:function(r){t.classList?t.classList.add(r):t.className+=" "+r},removeClass:function(r){t.classList?t.classList.remove(r):t.className=t.className.replace(new RegExp("(^|\\b)"+r+"(\\b|$)","gi")," ")},prepend:function(r){let o=Array.prototype.slice.call(r),a=o.length;for(;a--;)t.insertBefore(o[a],t.firstChild)},append:function(r){let o=Array.prototype.slice.call(r);for(let a=0,l=o.length;a<l;++a)t.appendChild(o[a])},insertAfter:function(r){return r.parentNode?.insertBefore(t,r.nextSibling)},insertBefore:function(r){return r.parentNode?.insertBefore(t,r)},remove:function(){t.parentNode.removeChild(t),t=null},contains:function(r){return t!==r&&t.contains(r)},wrap:function(r){return t.parentNode&&t.parentNode.insertBefore(r,t),r.appendChild(t),r},unwrap:function(){let r=Array.prototype.slice.call(t.childNodes),o;return r.forEach(function(a){o=a.parentNode,n.dom(a).insertBefore(a.parentNode),n.dom(o).remove()}),r},parents:function(){let r,o=[];for(;r=t.parentNode;)o.push(r),t=r;return o},normalizeTextNodes:function(){if(!!t){if(t.nodeType===qs.TEXT_NODE)for(;t.nextSibling&&t.nextSibling.nodeType===qs.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(r){let o=document.createElement("div");return o.innerHTML=r,o.childNodes},getRange:function(){let r=n.dom(t)?.getSelection(),o;return r?.rangeCount>0&&(o=r?.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,r){let o=t.ownerDocument;t.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),r||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){g0=t.clientX,m0=t.clientY}async mouseup(t){Math.abs(g0-t.clientX)<3&&Math.abs(m0-t.clientY)<3&&await this.processMouseEvent(t)}async mousemove(t){await this.processMouseEvent(t)}unbindEvents(t,n){let r=t.ownerDocument;t.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),r.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"),r=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],o=document.getElementById("colorIcon"),a=document.getElementById("actionIcon"),l=document.getElementById("dismissIcon"),u=document.getElementById("collapseIcon"),d=document.getElementById("highlightIcon"),f=this;if(l&&(l.innerHTML=$r.close,l.addEventListener("click",function(){f.toolboxMode("add")})),u&&(u.innerHTML=$r.close,u.addEventListener("click",function(){f.toolboxMode("add")})),o){o.style.position="relative",o.style.zIndex="20",r.forEach(v=>{let S=document.getElementById(v),w=document.getElementById(`c${v}`);S&&t?.contains(S)&&t.removeChild(S),n&&w&&n.contains(w)&&n.removeChild(w)});let g=[],y=[];if(o.addEventListener("click",function(){f.toolboxMode("colors")}),this.delegate.rights.enableAnnotations){let v=10;r.forEach(S=>{v--;let w=o?.cloneNode(!0),b=w.lastChild,m=De.hexToRgbChannels(S);b.style.backgroundColor="rgba("+[m.red,m.green,m.blue].join(",")+",.5)",w.id=`c${S}`,w.style.display="unset",w.style.position="relative",w.style.zIndex=`${v}`,w.style.marginLeft="-30px",y.push(w),n?.insertBefore(w,d)})}r.forEach(v=>{let S=o?.cloneNode(!0),w=S.lastChild;w.style.backgroundColor=v,S.id=v,S.style.position="relative",S.style.display="unset",g.push(S),o&&S.addEventListener("click",function(){f.setColor(v);let b=o?.lastChild;b&&(b.style.backgroundColor=v);let m=document.getElementById("highlightIcon"),E=document.getElementById("underlineIcon"),O=document.getElementById("noteIcon");(m?.getElementsByTagName?.("span").length??0)>0&&((m?.getElementsByTagName("span")[0]).style.background=f.getColor()),(E?.getElementsByTagName?.("span").length??0)>0&&((E?.getElementsByTagName("span")[0]).style.borderBottomColor=f.getColor()),(O?.getElementsByTagName?.("span").length??0)>0&&((O?.getElementsByTagName("span")[0]).style.borderBottomColor=f.getColor()),f.toolboxMode("add")}),t?.insertBefore(S,l)})}a&&a.addEventListener("click",function(){f.toolboxMode("action")}),f.toolboxMode("add")}toolboxMode(t){let n=document.getElementById("highlight-toolbox-mode-colors"),r=document.getElementById("highlight-toolbox-mode-add"),o=document.getElementById("highlight-toolbox-mode-edit"),a=document.getElementById("highlight-toolbox-mode-action");switch(t){case"colors":n&&(n.style.display="unset"),r&&(r.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="none");break;case"edit":n&&(n.style.display="none"),r&&(r.style.display="none"),o&&(o.style.display="unset"),a&&(a.style.display="none");break;case"action":n&&(n.style.display="none"),r&&(r.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="unset");break;default:n&&(n.style.display="none"),r&&(r.style.display="unset"),o&&(o.style.display="none"),a&&(a.style.display="none");break}}toolboxHide(){let t=document.getElementById("highlight-toolbox");t&&(t.style.display="none"),this.selectionMenuClosed()}toolboxShowDelayed(t){this.showTool(t.detail===1)}snapSelectionToWord(t=!1){let n=this,r=this.delegate.iframes[0].contentDocument;if(r){let a=n.dom(r.body)?.getSelection();if(n.dom(r.body)&&a&&!a?.isCollapsed){let f=function(m){let E=m.match(new RegExp("[^a-zA-Z0-9]+$"));return!E||!E.index?m:m.slice(0,E.index)},l=a.toString(),u=l.length-l.trimStart().length,d=l.length-l.trimEnd().length,g=l.length;var o=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;l=l.replace(o,""),u=g-l.trimStart().length,l=f(l),d=g-l.trimEnd().length;let y=document.createRange();t?(y.setStart(a.anchorNode,a.anchorOffset+u),y.setEnd(a.focusNode,a.focusOffset-d)):(y.setStart(a.anchorNode,a.anchorOffset),y.setEnd(a.focusNode,a.focusOffset));let v=y.collapsed;y.detach();let S=a.focusNode,w;t?(w=a.focusOffset-d,a.collapse(a.anchorNode,a.anchorOffset+u)):(w=a.focusOffset,a.collapse(a.anchorNode,a.anchorOffset));let b=["forward","backward"];v&&(b=["backward","forward"]),t?(a.modify("move",b[0],"character"),a.modify("move",b[1],"word"),a.extend(S,w),a.modify("extend",b[1],"character"),a.modify("extend",b[0],"word")):a.extend(S,w),this.selection(a.toString(),a)}return a}}toolboxShow(){if(this.activeAnnotationMarkerId===void 0){let t=this,n=document.getElementById("highlight-toolbox-mode-add"),r=this.dom(this.delegate.iframes[0].contentDocument?.body).getRange();if((!r||r.collapsed)&&n){getComputedStyle(n).display!=="none"&&t.toolboxHide();return}this.isIOS()&&setTimeout(function(){let o=t.delegate.iframes[0].contentDocument;if(o){let a=t.dom(o.body).getSelection();a.removeAllRanges(),setTimeout(function(){a.addRange(r);function l(f){let g={className:v=>to.indexOf(v)<0,idName:v=>to.indexOf(v)<0},y=t.delegate.iframes[0].contentDocument;if(y)return Rn(f,y,g)}let u=t.delegate.iframes[0].contentWindow,d=Do(u,l);t.delegate.annotationModule?.annotator?.saveTemporarySelectionInfo(d)},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(),r=document.getElementById("highlight-toolbox");r&&(this.delegate.view?.isPaginated()?r.style.top=n.top+(this.delegate.attributes?.navHeight??0)+"px":r.style.top=n.top+"px",r.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 r=this;r.toolboxMode("add");let o=document.getElementById("highlightIcon"),a=document.getElementById("collapseIcon"),l=document.getElementById("underlineIcon"),u=document.getElementById("noteIcon"),d=document.getElementById("colorIcon"),f=document.getElementById("speakIcon");if(this.delegate.rights.enableAnnotations){if(o&&(o.style.display="unset",d&&o.getElementsByTagName("span").length>0&&(o.getElementsByTagName("span")[0].style.background=this.getColor())),l&&(l.style.display="unset",d&&l.getElementsByTagName("span").length>0&&(l.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),u&&(u.style.display="unset",d&&u.getElementsByTagName("span").length>0&&(u.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),d){d.style.display="unset";let g=d.lastChild;g.style.backgroundColor=this.getColor()}if(o){let g=function(){r.doHighlight(!1,Le.Highlight),r.toolboxHide(),o?.removeEventListener("click",g)},y=o.cloneNode(!0);o?.parentNode?.replaceChild(y,o),o=document.getElementById("highlightIcon"),o?.addEventListener("click",g)}if(l){let g=function(){r.doHighlight(!1,Le.Underline),r.toolboxHide(),l?.removeEventListener("click",g)},y=l.cloneNode(!0);l?.parentNode?.replaceChild(y,l),l=document.getElementById("underlineIcon"),l?.addEventListener("click",g)}if(u){let g=function(){r.doHighlight(!1,Le.Comment),r.toolboxHide(),u?.removeEventListener("click",g)},y=u.cloneNode(!0);u?.parentNode?.replaceChild(y,u),u=document.getElementById("noteIcon"),u?.addEventListener("click",g)}}else o&&o.style.setProperty("display","none"),l&&l.style.setProperty("display","none"),u&&u.style.setProperty("display","none"),d&&d.style.setProperty("display","none"),a&&a.style.setProperty("display","none");if(this.delegate.rights.enableTTS){if(f){let g=function(){f?.removeEventListener("click",g),r.speak()},y=f.cloneNode(!0);f?.parentNode?.replaceChild(y,f),f=document.getElementById("speakIcon"),f?.addEventListener("click",g)}}else f&&f.style.setProperty("display","none");(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).forEach(g=>{g.icon&&(g.icon.id=g.id);let y=document.getElementById(g.id),v=this;function S(){y?.removeEventListener("click",S);function w(m){let E={className:_=>to.indexOf(_)<0,idName:_=>to.indexOf(_)<0},O=v.delegate.iframes[0].contentDocument;if(O)return Rn(m,O,E)}let b=v.delegate.iframes[0].contentWindow;if(b){let m=Do(b,w);if(m===void 0){let E=v.delegate.iframes[0].contentDocument;m=v.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(E)}if(m!==void 0)if(g.callback)g.callback(m.cleanText,m.range?.startContainer.parentElement);else{let E=g.highlight?.style,O=g.marker?g.marker:Le.Custom;if(O===Le.Custom&&v.delegate.rights.enableAnnotations||O===Le.Bookmark&&v.delegate.rights.enableBookmarks){let _=v.delegate.iframes[0].contentDocument;if(_){let A=v.createHighlight(v.dom(_.body).getWindow(),m,g.highlight?.color,!0,O,g.icon,g.popup,E);v.options.onAfterHighlight(A,O),v.delegate.rights.enableAnnotations?v.delegate.annotationModule?.saveAnnotation(A[0]).then(T=>{g?.note&&T.highlight&&v.delegate.annotationModule?.api?.addCommentToAnnotation(T).then(M=>{v.delegate.annotationModule?.updateAnnotation(M).then(async()=>{Mn.default.log("update highlight "+M.id)})})}):v.delegate.rights.enableBookmarks&&v.delegate.bookmarkModule?.saveAnnotation(A[0])}}}}v.callbackComplete()}if(y){let w=y.cloneNode(!0);y?.parentNode?.replaceChild(w,y),y=document.getElementById(g.id),y?.addEventListener("click",S)}})}}doHighlight(t,n){let r=this;function o(l){let u={className:f=>to.indexOf(f)<0,idName:f=>to.indexOf(f)<0},d=r.delegate.iframes[0].contentDocument;if(d)return Rn(l,d,u)}let a=r.delegate.iframes[0].contentWindow;if(a){let l=Do(a,o);if(l===void 0){let u=r.delegate.iframes[0].contentDocument;l=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(u)}if(l){if(this.options.onBeforeHighlight(l)===!0){let u;u=this.getColor(),De.isHexColor(u)&&(u=De.hexToRgbChannels(u));let d=r.delegate.iframes[0].contentDocument;if(d){let f=this.createHighlight(r.dom(d.body).getWindow(),l,u,!0,n??Le.Highlight);this.options.onAfterHighlight(f,n),this.delegate.rights.enableAnnotations&&n!==Le.Bookmark?this.delegate.annotationModule?.saveAnnotation(f[0]):this.delegate.rights.enableBookmarks&&n===Le.Bookmark&&this.delegate.bookmarkModule?.saveAnnotation(f[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(l){let u={className:f=>to.indexOf(f)<0,idName:f=>to.indexOf(f)<0},d=t.delegate.iframes[0].contentDocument;if(d)return Rn(l,d,u)},t=this,r=t.delegate.iframes[0].contentWindow;if(r){let l=Do(r,n);if(l===void 0){let u=t.delegate.iframes[0].contentDocument;l=t.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(u)}l!==void 0&&this.delegate.ttsModule.speak(l,!0,()=>{})}let o=t.delegate.iframes[0].contentDocument;o&&t.dom(o.body).getSelection().removeAllRanges();let a=document.getElementById("highlight-toolbox");a&&(a.style.display="none"),this.selectionMenuClosed()}}stopReadAloud(){this.delegate.rights.enableTTS&&this.doneSpeaking()}callbackComplete(){this.toolboxHide();let t=this.delegate.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges()}isOutsideViewport(t){let n=dt(document,"#iframe-wrapper"),r=n.scrollLeft,o=r+n.clientWidth,a=t.left+t.width,l=t.top+t.height,u=n.scrollTop,d=u+n.clientHeight,f=l<u,g=t.top>d,y=a<r,v=t.left>o;return f||g||y||v}isInsideViewport(t){let n=dt(document,"#iframe-wrapper"),r=n.scrollTop,o=r+n.clientHeight,a=t.top+20>=r,l=t.top<=o,u=n.scrollLeft,d=u+n.clientWidth,f=t.left+t.width,g=t.left>u,y=f<d;return a&&l&&g&&y}get visibleTextRects(){let t=this.delegate.iframes[0].contentDocument;if(t){let r=function(u,d=[]){let f=u.firstChild;for(;f;)f.nodeType===1&&r(f,d),f.nodeType===3&&f.textContent?.trim()&&d.push(f),f=f.nextSibling;return d},o=function(u){return r(u).map(f=>{let{top:g,height:y,left:v,width:S}=a(f);return{top:g,height:y,width:S,left:v,node:f,textContent:f.textContent??""}})},a=function(u){try{let d=document.createRange();d.selectNode(u);let f=d.getBoundingClientRect();return d.detach(),f}catch(d){Mn.default.log("measureTextNode "+d),Mn.default.log("measureTextNode "+u),Mn.default.log(`${u.textContent}`)}},n=Oi(t,"body");return o(n).filter(u=>this.isInsideViewport(u))}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.ttsModule.cancel(),t&&this.delegate.reload()}}normalizeHighlights(t){var n;return n=t.filter(function(r){return r.parentElement?r:null}),n=this.unique(n),n.sort(function(r,o){return r.offsetTop-o.offsetTop||r.offsetLeft-o.offsetLeft}),n}flattenNestedHighlights(t){let n,r=this;r.sortByDepth(t,!0);function o(){let a=!1;return t.forEach(function(l,u){let d=l.parentElement,f=d.previousSibling,g=d.nextSibling;r.isHighlight(d)&&(r.haveSameColor(d,l)?(d.replaceChild(l.firstChild,l),t[u]=d,a=!0):(l.nextSibling||(r.dom(l).insertBefore(g||d),a=!0),l.previousSibling||(r.dom(l).insertAfter(f||d),a=!0),d.hasChildNodes()||r.dom(d).remove()))}),a}do n=o();while(n)}mergeSiblingHighlights(t){let n=this;function r(o,a){return a&&a.nodeType===qs.ELEMENT_NODE&&n.haveSameColor(o,a)&&n.isHighlight(a)}t.forEach(function(o){let a=o.previousSibling,l=o.nextSibling;r(o,a)&&(n.dom(o).prepend(a.childNodes),n.dom(a).remove()),r(o,l)&&(n.dom(o).append(l.childNodes),n.dom(l).remove()),n.dom(o).normalizeTextNodes()})}setColor(t){this.options.color=t}getColor(){return this.options.color}isHighlight(t){return t&&t.nodeType===qs.ELEMENT_NODE&&t.hasAttribute(x8)}createWrapper(){let t=document.createElement("mark");return t.style.background="linear-gradient("+De.hexToRgbA(this.options.color)+", "+De.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 r=t;return"rgba("+[r.red,r.green,r.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(t,n){let r;if(this.isHexColor(t))return r=this.hexToRgbChannels(t),"rgba("+[r.red,r.green,r.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 r=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 a=zt.find(l=>l.id===o);if(a){if(a.marker===Le.Custom||a.marker===Le.Bookmark)if(a.style?.hover){if(a.style?.hover)for(let d=0;d<a.style?.hover?.length;d++){let f=a.style?.hover[d];t.style.removeProperty(f.property)}let u="";if(a.style?.default)for(let d=0;d<a.style?.default?.length;d++){let f=a.style?.default[d];t.style.removeProperty(f.property),u+=`${f.property}: ${f.value} !${f.priority};`}t.setAttribute("style",`${t.getAttribute("style")}; ${u}`)}else if(a.style?.hoverClass){a.style?.hoverClass&&t.classList.remove(a.style?.hoverClass);let u="";a.style?.defaultClass&&t.classList.add(a.style?.defaultClass),t.setAttribute("style",`${t.getAttribute("style")}; ${u}`)}else if(De.isHexColor(a.color)){let u=De.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${0})`,"important")}else t.classList.remove("hover");else if(a.marker===Le.Underline||a.marker===Le.Comment)if(typeof a.color=="object"){let u=a.color;t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${u.red}, ${u.green}, ${u.blue}, ${1})`,"important")}else if(De.isHexColor(a.color)){let u=De.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${u.red}, ${u.green}, ${u.blue}, ${1})`,"important")}else t.classList.remove("hover");else if(typeof a.color=="object"){let u=a.color;t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${ii})`,"important")}else if(De.isHexColor(a.color)){let u=De.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${ii})`,"important")}else t.classList.remove("hover");let l;if(r){let u=r.getElementById(n);u&&(l=u.querySelector(`#${a.id}`))}if(l){let u=l.getElementsByClassName(Za);if(u.length>0){let d=u.item(0).getElementsByClassName("icon-tooltip");d.length>0&&d.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(t,n,r){for(let o of n){if(r.marker===Le.Custom||r.marker===Le.Bookmark)if(r.style?.hover){if(r.style?.default)for(let l=0;l<r.style?.default?.length;l++){let u=r.style?.default[l];o.style.removeProperty(u.property)}let a="";for(let l=0;l<r.style?.hover?.length;l++){let u=r.style?.hover[l];o.style.removeProperty(u.property),a+=`${u.property}: ${u.value} !${u.priority};`}o.setAttribute("style",`${o.getAttribute("style")}; ${a}`)}else if(r.style?.hoverClass){r.style?.defaultClass&&o.classList.remove(r.style?.defaultClass);let a="";o.classList.add(r.style?.hoverClass),o.setAttribute("style",`${o.getAttribute("style")}; ${a}`)}else if(De.isHexColor(r.color)){let a=De.hexToRgbChannels(r.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important")}else o.classList.add("hover");else if(r.marker===Le.Underline||r.marker===Le.Comment)if(typeof r.color=="object"){let a=r.color;o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, ${1})`,"important")}else if(De.isHexColor(r.color)){let a=De.hexToRgbChannels(r.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, ${1})`,"important")}else o.classList.add("hover");else if(typeof r.color=="object"){let a=r.color;o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${_4})`,"important")}else if(De.isHexColor(r.color)){let a=De.hexToRgbChannels(r.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${_4})`,"important")}else o.classList.add("hover");if(r.type!==qe.Definition){let l=t.getElementById(Re.R2_ID_HIGHLIGHTS_CONTAINER).querySelector(`#${r.id}`).getElementsByClassName(Za);if(l.length>0){let u=l.item(0).getElementsByClassName("icon-tooltip");u.length>0&&u.item(0).style.setProperty("display","block")}}}}setAndResetSearchHighlight(t,n){let r=this.delegate.iframes[0].contentWindow?.document,o=Array.from(r.getElementById(Re.R2_ID_SEARCH_CONTAINER).querySelectorAll(`.${hn}`));for(let a of o){let l=a,u=l.parentNode&&l.parentNode.nodeType===Node.ELEMENT_NODE&&l.parentNode.getAttribute?l.parentNode.getAttribute("id"):void 0;if(n.forEach(d=>{if(u===d.id&&d){if(typeof d.color=="object"){let y=d.color;l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${ii})`,"important")}else if(De.isHexColor(d.color)){let y=De.hexToRgbChannels(d.color);l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${ii})`,"important")}else l.classList.remove("hover");let g=r.getElementById(Re.R2_ID_SEARCH_CONTAINER).querySelector(`#${d.id}`).getElementsByClassName(Za);if(g.length>0){let y=g.item(0).getElementsByClassName("icon-tooltip");y.length>0&&y.item(0).style.removeProperty("display")}}}),u===t.id&&t){if(typeof t.color=="object"){let g=t.color;l.style.setProperty("background-color",`rgba(${g.red}, ${g.green}, ${g.blue}, ${ii})`,"important")}else if(De.isHexColor(t.color)){let g=De.hexToRgbChannels(t.color);l.style.setProperty("background-color",`rgba(${g.red}, ${g.green}, ${g.blue}, ${ii})`,"important")}else l.classList.remove("hover");let f=r.getElementById(Re.R2_ID_SEARCH_CONTAINER).querySelector(`#${t.id}`).getElementsByClassName(Za);if(f.length>0){let g=f.item(0).getElementsByClassName("icon-tooltip");g.length>0&&g.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,r=t.clientX,o=t.clientY;if(!n||!n.getElementById(Re.R2_ID_HIGHLIGHTS_CONTAINER)&&!n.getElementById(Re.R2_ID_SEARCH_CONTAINER)&&!n.getElementById(Re.R2_ID_PAGEBREAK_CONTAINER)&&!n.getElementById(Re.R2_ID_READALOUD_CONTAINER)&&!n.getElementById(Re.R2_ID_DEFINITIONS_CONTAINER))return;let a=this.delegate.view?.isPaginated(),l=n.body.getBoundingClientRect(),u=this.getScrollingElement(n),d=a?-u.scrollLeft:l.left,f=a?-u.scrollTop:l.top,g,y;for(let v=zt.length-1;v>=0;v--){let S=zt[v],w=n.getElementById(`${S.id}`);if(!w){let E=n.getElementById(Re.R2_ID_HIGHLIGHTS_CONTAINER);E&&(w=E.querySelector(`#${S.id}`))}if(!w)continue;let b=!1,m=w.querySelectorAll(`.${hn}`);for(let E of m){let O=E,_=O.rect.left+d,A=O.rect.top+f;if(r>=_&&r<_+O.rect.width&&o>=A&&o<A+O.rect.height){b=!0;break}}if(b){g=S,y=w;break}}if(!g||!y){for(let v in Re){let S=n.getElementById(v);if(S){let w=S.querySelectorAll(`.${Ya}`);for(let m of w)this.resetHighlightBoundingStyle(m);let b=Array.from(S.querySelectorAll(`.${hn}`));for(let m of b)this.resetHighlightAreaStyle(m,v)}}return}if(y.getAttribute("data-click")){if((t.type==="mousemove"||t.type==="touchmove")&&y.parentElement?.style.display!=="none"){let v=Array.from(y.querySelectorAll(`.${hn}`));for(let w in Re){let b=n.getElementById(w);if(b){let m=b.querySelectorAll(`.${hn}`);for(let E of m)v.indexOf(E)<0&&this.resetHighlightAreaStyle(E,w)}}this.setHighlightAreaStyle(n,v,g);let S=y.querySelector(`.${Ya}`);for(let w in Re){let b=n.getElementById(w);if(b){let m=b.querySelectorAll(`.${Ya}`);for(let E of m)(!S||E!==S)&&this.resetHighlightBoundingStyle(E)}}}else if((t.type==="mouseup"||t.type==="click"||t.type==="touchup")&&y.parentElement?.style.display!=="none"){let v={highlight:g};Mn.default.log(JSON.stringify(v));let S=this,w;if(S.delegate.rights.enableAnnotations?w=await this.delegate.annotationModule?.getAnnotation(v.highlight):S.delegate.rights.enableBookmarks&&(w=await this.delegate.bookmarkModule?.getAnnotation(v.highlight)),v.highlight.type===qe.Annotation&&this.delegate.annotationModule?.api?.selectedAnnotation(w).then(async()=>{}),w?.id){Mn.default.log("selected highlight "+w.id),S.lastSelectedHighlight=w.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 O=function(){S.delegate.annotationModule?.api?.addCommentToAnnotation(w).then(P=>{S.delegate.annotationModule?.updateAnnotation(P).then(async()=>{Mn.default.log("update highlight "+P.id),b&&(b.style.display="none"),S.selectionMenuClosed()}),b&&(b.style.display="none"),S.selectionMenuClosed(),_?.removeEventListener("click",O,!1)})},T=function(){S.delegate.rights.enableAnnotations?S.delegate.annotationModule?.deleteSelectedHighlight(w).then(async()=>{Mn.default.log("delete highlight "+w.id),b&&(b.style.display="none"),S.selectionMenuClosed()}):S.delegate.rights.enableBookmarks&&S.delegate.bookmarkModule?.deleteSelectedHighlight(w).then(async()=>{Mn.default.log("delete highlight "+w.id),b&&(b.style.display="none"),S.selectionMenuClosed()})};b.style.display="block",this.toolboxMode("edit");let m=document.getElementById("colorIcon"),E=document.getElementById("highlightIcon");m&&(m.style.display="none"),E&&(E.style.display="none");let _=document.getElementById("commentIcon"),A=document.getElementById("cloneCommentIcon");if(A){let P=A.parentElement;P&&P.removeChild(A)}if(_){_.style.display="none";let P=_.cloneNode(!0),q=_.parentElement;P.style.display="unset",P.id="cloneCommentIcon",P.addEventListener("click",O,!1),q&&q.append(P)}let M=document.getElementById("deleteIcon"),j=document.getElementById("cloneDeleteIcon");if(j){let P=j.parentElement;P&&P.removeChild(j)}if(M){M.style.display="none";let P=M.cloneNode(!0),q=M.parentElement;P.style.display="unset",P.id="cloneDeleteIcon",P.addEventListener("click",T,!1),q&&q.append(P)}}else b.style.display="none",this.selectionMenuClosed(),b.offsetWidth,b.style.display="block"}else{y.dataset.definition&&new Va(this.delegate).showPopup(y.dataset.definition,t);let b=this.delegate.definitionsModule?.properties?.definitions?.filter(m=>m.order===Number(y?.dataset.order))[0];Mn.default.log(b),this.delegate.definitionsModule?.api?.click&&(this.delegate.definitionsModule.api?.click(p0.omit(b,"callbacks"),p0.omit(g,"definition")),this.delegate.emit("definition.click",b,g))}}}}async prepareContainers(t){for(let n in Re)await this.ensureHighlightsContainer(t,n)}async ensureHighlightsContainer(t,n){let r=t.document;if(!r.getElementById(n)){let o=r.createElement("div");o.setAttribute("id",n),n!==Re.R2_ID_GUTTER_RIGHT_CONTAINER&&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")),r.body&&r.body.append(o),(await this.layerSettings.getProperty(n))?.value===!1&&(o.style.display="none")}return r.getElementById(n)}hideAllhighlights(t){this.removeAllChildNodes(t.getElementById(Re.R2_ID_HIGHLIGHTS_CONTAINER)),this.removeAllChildNodes(t.getElementById(Re.R2_ID_SEARCH_CONTAINER)),this.removeAllChildNodes(t.getElementById(Re.R2_ID_READALOUD_CONTAINER)),this.removeAllChildNodes(t.getElementById(Re.R2_ID_PAGEBREAK_CONTAINER)),this.removeAllChildNodes(t.getElementById(Re.R2_ID_DEFINITIONS_CONTAINER))}destroyAllhighlights(t){this.hideAllhighlights(t),zt.splice(0,zt.length)}removeAllChildNodes(t){for(;t.firstChild;)t.removeChild(t.firstChild)}destroyHighlights(t){let n=this.delegate.iframes[0].contentWindow?.document;if(n){let r;switch(t){case qe.ReadAloud:r=n.getElementById(Re.R2_ID_READALOUD_CONTAINER),r&&this.removeAllChildNodes(r);break;case qe.Search:r=n.getElementById(Re.R2_ID_SEARCH_CONTAINER),r&&this.removeAllChildNodes(r);break;case qe.PageBreak:r=n.getElementById(Re.R2_ID_PAGEBREAK_CONTAINER),r&&this.removeAllChildNodes(r);break;case qe.Definition:r=n.getElementById(Re.R2_ID_DEFINITIONS_CONTAINER),r&&this.removeAllChildNodes(r);break;case qe.LineFocus:r=n.getElementById(Re.R2_ID_LINEFOCUS_CONTAINER),r&&this.removeAllChildNodes(r);break;case qe.Comment:r=n.getElementById(Re.R2_ID_GUTTER_RIGHT_CONTAINER),r&&this.removeAllChildNodes(r);break;default:r=n.getElementById(Re.R2_ID_HIGHLIGHTS_CONTAINER),r&&this.removeAllChildNodes(r),zt.splice(0,zt.length);break}}}destroyHighlight(t,n){if(!t)return;let r=-1;zt.find((l,u)=>(r=u,l.id===n))&&r>=0&&r<zt.length&&zt.splice(r,1);let a=t.getElementById(n);a&&this.removeAllChildNodes(a)}createHighlight(t,n,r,o,a,l,u,d,f,g){try{let y=`${n.rangeInfo.startContainerElementCssSelector}${n.rangeInfo.startContainerChildTextNodeIndex}${n.rangeInfo.startOffset}${n.rangeInfo.endContainerElementCssSelector}${n.rangeInfo.endContainerChildTextNodeIndex}${n.rangeInfo.endOffset}`,v=Tr.hash(y),S=(g||"R2_HIGHLIGHT_")+v;this.destroyHighlight(t.document,S);let w=`rgb(${Fo.red}, ${Fo.green}, ${Fo.blue})`,b={color:r||w,id:S,pointerInteraction:o,selectionInfo:n,marker:a,icon:l,popup:u,style:d,type:f||qe.Annotation};(f===qe.Annotation||f===qe.Definition||f===void 0)&&zt.push(b);let m=this.createHighlightDom(t,b);return b.position=parseInt((m?.hasChildNodes()?m.childNodes[0]:m).style.top.replace("px","")),[b,m]}catch(y){throw"Can't create highlight: "+y}}createHighlightDom(t,n){let r=t.document,o=vd(r,n.selectionInfo.rangeInfo);if(!o)return;for(let B in Re)this.ensureHighlightsContainer(t,B);let a=r.createElement("div");a.setAttribute("id",n.id),a.setAttribute("class",x4),a.style.setProperty("pointer-events","none"),n.pointerInteraction&&a.setAttribute("data-click","1");let l=this.delegate.view?.isPaginated();l?r.body.style.position="revert":r.body.style.position="relative";let u=r.body.getBoundingClientRect(),d=this.getScrollingElement(r),f=l?-d.scrollLeft:u.left,g=l?-d.scrollTop:u.top,y=1,v=!1,S=!1,m=yd(o,v||S||!1),E=3,O=2,_=3,A=0,T=24,M,j;for(let B of m){let N=r.createElement("div");N.setAttribute("class",hn),N.dataset.marker=""+n.marker;let W="";if(v&&n.marker!==Le.Custom&&n.marker!==Le.Bookmark&&n.marker!==Le.Comment){let V=n.color;De.isHexColor(V)&&(V=De.hexToRgbChannels(V)),W+=`border-bottom: ${O*y}px solid rgba(${V.red}, ${V.green}, ${V.blue}, ${ii}) !important`}if(n.marker===Le.Custom||n.marker===Le.Bookmark)if(n.style?.default){for(let V=0;V<n.style?.default?.length;V++){let Q=n.style?.default[V];W+=`${Q.property}: ${Q.value} !${Q.priority};`}N.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${E}px !important; ${W}`)}else n.style?.defaultClass&&(N.classList.add(n.style?.defaultClass),N.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${E}px !important; ${W}`));else if(n.marker===Le.Underline||n.marker===Le.Comment)if(typeof n.color=="object"){let V=n.color;N.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${E}px !important; background-color: rgba(${V.red}, ${V.green}, ${V.blue}, ${0}) !important; ${W}`),N.style.setProperty("border-bottom",`2px solid rgba(${V.red}, ${V.green}, ${V.blue}, ${1})`,"important")}else if(De.isHexColor(n.color)){let V=De.hexToRgbChannels(n.color);N.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${E}px !important; background-color: rgba(${V.red}, ${V.green}, ${V.blue}, ${0}) !important; ${W}`),N.style.setProperty("border-bottom",`2px solid rgba(${V.red}, ${V.green}, ${V.blue}, ${1})`,"important")}else N.setAttribute("style",`border-radius: ${E}px !important; ${W}`);else if(typeof n.color=="object"){let V=n.color;N.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${E}px !important; background-color: rgba(${V.red}, ${V.green}, ${V.blue}, ${ii}) !important; ${W}`)}else if(De.isHexColor(n.color)){let V=De.hexToRgbChannels(n.color);N.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${E}px !important; background-color: rgba(${V.red}, ${V.green}, ${V.blue}, ${ii}) !important; ${W}`)}else N.setAttribute("style",`border-radius: ${E}px !important; ${W}`);N.style.setProperty("pointer-events","none"),N.style.position="absolute",N.scale=y,N.rect={height:B.height,left:B.left-f,top:B.top-g,width:B.width},n.pointerInteraction&&(N.setAttribute("data-click","1"),N.tabIndex=0),N.style.width=`${N.rect.width*y}px`,N.style.height=`${N.rect.height*y}px`,N.style.left=`${N.rect.left*y}px`,N.style.top=`${N.rect.top*y}px`,a.append(N);let ye=parseInt(N.style.top.replace("px",""));if((ye<A||A===0)&&(A=ye),T=parseInt(N.style.height.replace("px","")),S){let V=r.createElement("div");V.setAttribute("class",hn);let Q=n.color;De.isHexColor(Q)&&(Q=De.hexToRgbChannels(Q)),V.setAttribute("style",`background-color: rgba(${Q.red}, ${Q.green}, ${Q.blue}, ${ii}) !important;`),V.style.setProperty("pointer-events","none"),V.style.position="absolute",V.scale=y,V.rect={height:B.height,left:B.left-f,top:B.top-g,width:B.width},V.style.width=`${V.rect.width*y}px`,V.style.height=`${_*y}px`,V.style.left=`${V.rect.left*y}px`,V.style.top=`${(V.rect.top+V.rect.height/2-_/2)*y}px`,a.append(V)}let be=this.delegate.iframes[0].contentWindow?.innerWidth,fe=parseInt(getComputedStyle(r.documentElement).getPropertyValue("column-count")),re=parseInt(getComputedStyle(r.documentElement).getPropertyValue("column-width")),he=parseInt(getComputedStyle(r.body).getPropertyValue("padding-left")),Ae=be/(fe||1);Ae<re&&(Ae=be),l||(Ae=parseInt(getComputedStyle(r.body).width.replace("px","")));let ue=this.delegate.settings.fontSize/100,Oe=20*ue;ue<=1&&(Oe=-60);let Ce=0*ue;ue<=1&&(Ce=-60),M=Math.floor(B.left/Ae)*Ae+Ae-(T<40?40:T)+Ce,j=Math.floor(B.left/Ae)*Ae+(T<40?40:T)-Oe;let Ee=parseInt(this.delegate.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));Ee>=2&&(j=j+he/fe,M=M-he/fe),l||(M=parseInt(getComputedStyle(this.delegate.iframes[0].contentDocument?.body).width.replace("px","")),j=parseInt(getComputedStyle(this.delegate.iframes[0].contentDocument?.body).width.replace("px",""))-Ae,Ee>=2&&(j=j+he/2,M=M-he/2))}let P=o.getBoundingClientRect(),q=r.createElement("div");q.setAttribute("class",Ya),q.style.setProperty("pointer-events","none"),q.style.position="absolute",q.scale=y,q.rect={height:P.height,left:P.left-f,top:P.top-g,width:P.width},q.style.width=`${q.rect.width*y}px`,q.style.height=`${q.rect.height*y}px`,q.style.left=`${q.rect.left*y}px`,q.style.top=`${q.rect.top*y}px`,a.append(q);let U=r.createElement("div");if(U.setAttribute("class",Za),n.icon?.position==="left")U.setAttribute("style",`position: absolute;top:${A}px;left:${j+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${T}px; width:${T}px;`);else if(n.icon?.position==="inline")U.setAttribute("style",`position: absolute;top:${A-T/2}px;left:${parseInt(q.style.left.replace("px",""))+parseInt(q.style.width.replace("px",""))-T/2}px;height:${T}px; width:${T}px;`);else if(n.icon?.position==="center"){let N=T/3*2;U.setAttribute("style",`position: absolute;top:${A}px;left:${parseInt(q.style.left.replace("px",""))+parseInt(q.style.width.replace("px",""))-N}px;height:${T}px; width:${T}px;`)}else n.note&&n.marker!==Le.Custom&&n.marker!==Le.Bookmark&&n.marker!==Le.Comment&&n.marker!==Le.Highlight&&n.marker!==Le.Underline?U.setAttribute("style",`position: absolute;top:${A-T/2}px;left:${parseInt(q.style.left.replace("px",""))+parseInt(q.style.width.replace("px",""))-T/2}px;height:${T}px; width:${T}px;`):n.note&&n.marker===Le.Comment||n.marker===Le.Highlight||n.marker===Le.Underline?U.setAttribute("style",`position: absolute;top:${A}px;left:${M+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${T}px; width:${T}px;`):U.setAttribute("style",`position: absolute;top:${A}px;left:${M+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${T}px; width:${T}px;`);if(n.marker===Le.Custom||n.marker===Le.Bookmark)n.icon?.class?(U.classList.add(n.icon?.class),U.id=n.icon?.id):n.icon?.svgPath?U.innerHTML=$s(`${n.icon?.id}`,`${n.icon?.title}`,`${n.icon?.svgPath}`,"icon open",T,`${n.icon?.color} !important`):n.icon?.title&&(U.innerHTML=n.icon?.title);else if(n.note){let B=n.color;De.isHexColor(B)&&(B=De.hexToRgbChannels(B)),n.marker===Le.Comment||n.marker===Le.Highlight||n.marker===Le.Underline?U.innerHTML=$s("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",T/2,`rgba(${B.red}, ${B.green}, ${B.blue}, 1) !important`):U.innerHTML=$s("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",T,`rgba(${B.red}, ${B.green}, ${B.blue}, 1) !important`)}U.style.setProperty("pointer-events","all");let k=this;if(n.type!==qe.PageBreak&&n.type!==qe.Definition&&U.addEventListener("click",async function(B){let N;k.delegate.rights.enableAnnotations?(N=await k.delegate.annotationModule?.getAnnotationByID(n.id),k.delegate.annotationModule?.api?.selectedAnnotation(N).then(async()=>{})):k.delegate.rights.enableBookmarks&&(N=await k.delegate.bookmarkModule?.getAnnotationByID(n.id)),Mn.default.log("selected highlight "+N.id),k.lastSelectedHighlight=N.id;let W=document.getElementById("highlight-toolbox");if(W)if(W.style.top=B.clientY+(k.delegate.attributes?.navHeight??0)+"px",W.style.left=B.clientX+"px",getComputedStyle(W).display==="none"){let re=function(){k.delegate.annotationModule?.api?.addCommentToAnnotation(N).then(Ee=>{k.delegate.annotationModule?.updateAnnotation(Ee).then(async()=>{Mn.default.log("update highlight "+Ee.id),W.style.display="none",k.selectionMenuClosed()}),W.style.display="none",k.selectionMenuClosed()})},ue=function(){k.delegate.rights.enableAnnotations?k.delegate.annotationModule?.deleteSelectedHighlight(N).then(async()=>{Mn.default.log("delete highlight "+N.id),W.style.display="none",k.selectionMenuClosed()}):k.delegate.rights.enableBookmarks&&k.delegate.bookmarkModule?.deleteSelectedHighlight(N).then(async()=>{Mn.default.log("delete highlight "+N.id),W.style.display="none",k.selectionMenuClosed()})};W.style.display="block",k.toolboxMode("edit");let be=document.getElementById("colorIcon"),fe=document.getElementById("highlightIcon");be&&(be.style.display="none"),fe&&(fe.style.display="none");let he=document.getElementById("commentIcon"),Ae=document.getElementById("cloneCommentIcon");if(Ae){let Ee=Ae.parentElement;Ee&&Ee.removeChild(Ae)}if(he){he.style.display="none";let Ee=he.cloneNode(!0),V=he.parentElement;Ee.style.display="unset",Ee.id="cloneCommentIcon",Ee.addEventListener("click",re,!1),V&&V.append(Ee)}let Oe=document.getElementById("deleteIcon"),Ce=document.getElementById("cloneDeleteIcon");if(Ce){let Ee=Ce.parentElement;Ee&&Ee.removeChild(Ce)}if(Oe){Oe.style.display="none";let Ee=Oe.cloneNode(!0),V=Oe.parentElement;Ee.style.display="unset",Ee.id="cloneDeleteIcon",Ee.addEventListener("click",ue,!1),V&&V.append(Ee)}}else W.style.display="none",k.selectionMenuClosed(),W.offsetWidth,W.style.display="block";let ye=Array.from(a.querySelectorAll(`.${hn}`));k.setHighlightAreaStyle(r,ye,n)}),n.note){let B=document.createElement("span");B.innerHTML=n.note,B.className="icon-tooltip",n.marker===Le.Custom||n.marker===Le.Bookmark?(n.popup?.background&&B.style.setProperty("background",n.popup.background),n.popup?.textColor&&B.style.setProperty("color",n.popup.textColor),n.popup?.class&&B.classList.add(n.popup.class)):(B.style.setProperty("background","lightyellow"),B.style.setProperty("color","black"))}switch((n.note||n.marker===Le.Custom||n.marker===Le.Bookmark)&&a.append(U),n.type){case qe.Search:r.getElementById(Re.R2_ID_SEARCH_CONTAINER).append(a);break;case qe.ReadAloud:r.getElementById(Re.R2_ID_READALOUD_CONTAINER).append(a);break;case qe.PageBreak:r.getElementById(Re.R2_ID_PAGEBREAK_CONTAINER).append(a);break;case qe.Definition:r.getElementById(Re.R2_ID_DEFINITIONS_CONTAINER).append(a);break;default:r.getElementById(Re.R2_ID_HIGHLIGHTS_CONTAINER).append(a);break}return a}addSelectionMenuItem(t){(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).push(t)}};var N4=Je(T0());C();var B8=Je(Dt());var no={className:i=>!0,idName:i=>!0,tagName:i=>!0};var H4=Je(Ed()),Cr=Je(Dt()),Qa=class{constructor(t,n,r,o,a,l,u,d,f){this.hide=de(document,"#menu-button-hide");this.show=de(document,"#menu-button-show");this.annotator=t,this.rights=n,this.publication=r,this.headerMenu=f,this.delegate=o,this.initialAnnotations=a,this.highlighter=u,this.properties=l,this.api=d}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(){Cr.default.log("Annotation module stop")}async start(){if(this.delegate.annotationModule=this,this.headerMenu&&(this.highlightsView=de(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=de(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=de(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()},200)}initialize(){return new Promise(async t=>{await document.fonts.ready,this.rights.enableAnnotations&&setTimeout(()=>{this.drawHighlights(),this.showHighlights(),ne(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(r=>r.id===this.activeAnnotationMarkerId);if(n&&n?.length>0){let r=H4.cloneDeep(n[0]);r.marker=Le.Custom,this.activeAnnotationMarkerPosition&&(r.icon.position=this.activeAnnotationMarkerPosition),r.highlight.style.default=null,r.highlight.style.hover=null;let o=this.delegate.iframes[0].contentDocument;if(o){let f=function(y){try{let v=d.delegate.iframes[0].contentDocument;return v?Rn(y,v,no):""}catch(v){return Cr.default.log("uniqueCssSelector:"),Cr.default.error(v),""}},a=this.highlighter?.dom(o.body).getSelection(),l=a.getRangeAt(0),u=a.anchorNode;l.setStart(u,l.startOffset),l.setEnd(u,l.endOffset+1),a.removeAllRanges(),a.addRange(l);let d=this,g=Ri(l,f);if(a.removeAllRanges(),g){let y={rangeInfo:g},v=this.delegate.highlighter?.createHighlight(this.delegate.highlighter?.dom(o.body).getWindow(),y,r.highlight.color,!0,Le.Bookmark,r.icon,r.popup,r.highlight.style);v&&this.saveAnnotation(v[0]).then(S=>{Cr.default.log("saved bookmark "+S.id)})}o.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(t){Cr.default.log("still need to scroll to "+t);var n=await this.annotator?.getAnnotationElement(t,this.delegate.iframes[0].contentWindow);n.scrollIntoView({block:"center",behavior:"smooth"})}async updateLocalHighlight(t){if(this.annotator){let n=await this.annotator.deleteAnnotation(t.id),r=await this.addAnnotation(t);return Cr.default.log("Highlight deleted "+JSON.stringify(n)),Cr.default.log("Highlight added "+JSON.stringify(r)),await this.showHighlights(),await this.drawHighlights(),r}else return new Promise(n=>n(null))}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return Cr.default.log("Highlight deleted "+JSON.stringify(n)),await this.showHighlights(),await this.drawHighlights(),n}else return new Promise(r=>r(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 r=this.delegate.view?.getCurrentPosition(),o=this.delegate.iframes[0].contentDocument;if(o){let a=Oi(o,"body"),l=t.position?t.position/a.scrollHeight:r,u=(0,N4.v4)(),d;if(n){let f=n.Href;if(f.indexOf("#")>0&&(f=f.slice(0,f.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let g=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),y=Math.ceil((l??0)*(g.length-1)),v=g[y];d=jt(Fe({},v),{id:u,href:f,created:new Date,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else d={id:u,href:f,locations:{progression:l},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(d)if(this.api?.addAnnotation)try{let f=await this.api.addAnnotation(d),g=await this.annotator.saveAnnotation(f);return await this.showHighlights(),await this.drawHighlights(),new Promise(y=>y(g))}catch(f){await this.showHighlights(),await this.drawHighlights()}else{let f=await this.annotator.saveAnnotation(d);return await this.showHighlights(),await this.drawHighlights(),new Promise(g=>g(f))}}}return new Promise(r=>r(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!==Le.Bookmark),t.forEach(n=>{zt.push(n.highlight)}))),this.highlightsView&&this.createTree(fr.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(qe.Annotation);for(let r of n){zt.push(r.highlight);let o=r,a=this.delegate.currentChapterLink.href;var t=this.publication.getTOCItem(a);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 l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&(await this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,r.highlight),setTimeout(async()=>{if(o.highlight?.marker===Le.Underline){let u=await this.annotator?.getAnnotationPosition(r.id,this.delegate.iframes[0].contentWindow),d='<div class="comment" style="top: '+u+'px;width:20px"></div>',f=document.createElement("div");f.innerHTML=d;let g=f.childNodes[0],y=document.createElement("i");y.innerHTML="sticky_note_2",y.className="material-icons",y.style.color=o.highlight.color,g.appendChild(y),ne(f,"click",v=>{v.preventDefault(),v.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(qe.Annotation);for(let r of n){zt.push(r.highlight);let o=r,a=this.delegate.currentChapterLink.href,l=this.publication.getTOCItem(a);if(this.delegate.currentTocUrl&&(l=this.publication.getTOCItem(this.delegate.currentTocUrl)),l===null&&(l=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),l){let u=l.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),o.href===u&&(await this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,r.highlight),setTimeout(async()=>{if(o.highlight?.marker===Le.Underline){let d=await this.annotator?.getAnnotationPosition(r.id,this.delegate.iframes[0].contentWindow),f='<div class="comment" style="top: '+d+"px;background: "+o.highlight?.color+';width:20px"></div>',g=document.createElement("div");g.innerHTML=f,g.childNodes[0].innerHTML=$r.note,ne(g,"click",y=>{y.preventDefault(),y.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){let t=this.delegate.iframes[0].contentDocument;if(t&&(this.commentGutter=t.getElementById(Re.R2_ID_GUTTER_RIGHT_CONTAINER),this.delegate.view?.isScrollMode()&&this.properties?.enableComments?this.commentGutter.style.removeProperty("display"):this.commentGutter.style.setProperty("display","none"),this.commentGutter&&this.delegate.view?.isScrollMode())){this.commentGutter.innerHTML="";let n=[];this.annotator&&(n=this.annotator.getAnnotations(),n&&(n=n.filter(r=>r.highlight?.note?.length>0),n=this.syncPosition(n),n=this.reposition(n),n.forEach(r=>{let o=document.createElement("i");o.innerHTML="sticky_note_2",o.className="material-icons",o.style.color=r.highlight.color;let a=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),l,u;a&&(l=a.querySelector(`#${r.highlight.id}`)),u=l.getElementsByClassName(hn)[0];let f=parseInt(u.style.height.replace("px","")),g=r.highlight.position,y=t.createElement("div");y.setAttribute("style",`position: absolute;top:${g}px;display: flex;max-width: 250px !important;height:${f}px;width: 200px;align-items: center;`);let v=t.createElement("div");y.appendChild(v);let S=r.highlight.color;De.isHexColor(S)&&(S=De.hexToRgbChannels(S)),y.innerHTML=$s("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="8"/>',"icon open",10,`rgba(${S.red}, ${S.green}, ${S.blue}, 1) !important`);let w=t.createElement("div");w.innerHTML=r.highlight?.note,w.setAttribute("style",`height:${f}px;overflow: hidden;padding-left: 5px;`),y.appendChild(w),ne(y,"click",b=>{b.preventDefault(),b.stopPropagation(),this.scrollToHighlight(r.highlight.id)}),this.commentGutter?.appendChild(y)})))}}createTree(t,n,r){if(n){let o=this,a=this.publication.readingOrder;if(a.length){let l=(u,d)=>{let f=document.createElement("ul");f.className="sidenav-annotations";for(let g of d){let y=document.createElement("li"),v=document.createElement("a"),S=document.createElement("span");if(v.tabIndex=-1,v.className="chapter-link",g.Href){let b=this.publication.getAbsoluteHref(g.Href),m=this.publication.getTOCItemAbsolute(b);v.href=b,v.innerHTML=m?.Title||"",y.appendChild(v)}else S.innerHTML=g.Title||"",S.className="chapter-title",y.appendChild(S);ne(v,"click",b=>{b.preventDefault(),b.stopPropagation();let m={href:v.href,locations:{progression:0},type:g.TypeLink,title:v.title};this.delegate.stopReadAloud(),this.delegate.navigate(m)});let w=document.createElement("ol");n.forEach(function(b){let m=g.Href.indexOf("#")!==-1?g.Href.slice(0,g.Href.indexOf("#")):g.Href;if(g.Href&&b.href.endsWith(m)){let E=document.createElement("li");E.className="annotation-item";let O=document.createElement("a");if(O.setAttribute("href",b.href),t===fr.Annotation){O.className="highlight-link";let A=document.createElement("span"),T=document.createElement("span");if(A.className="title",T.innerHTML=b.highlight.selectionInfo.cleanText,b.highlight?.marker===Le.Underline)if(typeof b.highlight?.color=="object"){let P=b.highlight?.color;P&&T.style.setProperty("border-bottom",`2px solid ${De.hexToRgbA(P)}`,"important")}else T.style.setProperty("border-bottom",`2px solid ${b.highlight?.color}`,"important");else if(typeof b.highlight?.color=="object"){let P=b.highlight?.color;P&&(T.style.backgroundColor=De.hexToRgbA(P))}else{let P=b.highlight?.color;P&&(T.style.backgroundColor=P)}A.appendChild(T),O.appendChild(A);let M=document.createElement("span"),j=Math.round((b.locations.progression??0)*100)+"% through resource";M.className="subtitle",M.innerHTML=j,O.appendChild(M)}let _=document.createElement("span");if(_.className="timestamp",_.innerHTML=Qa.readableTimestamp(b.created),O.appendChild(_),ne(O,"click",A=>{A.preventDefault(),A.stopPropagation(),o.handleAnnotationLinkClick(A,b)}),E.appendChild(O),o.delegate.sideNavExpanded){let A=document.createElement("button");A.className="delete",A.innerHTML=$r.delete,ne(A,"click",T=>{T.preventDefault(),T.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,T,b)}),E.appendChild(A)}w.appendChild(E)}}),w.children.length>0&&(f.appendChild(y),f.appendChild(w)),f.children.length>0&&u.appendChild(f),g.Children&&g.Children.length>0&&l(u,g.Children)}};r.innerHTML="",l(r,a)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.delegate.stopReadAloud(),this.delegate.navigate(n)):Cr.default.log("annotation data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,r){Cr.default.log("annotation data locator: ",r),r?t===fr.Annotation&&this.deleteHighlight(r):Cr.default.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)}syncPosition(t){let n=this.delegate.iframes[0].contentDocument,r=(o,a)=>{let l=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),u,d;l&&(u=l.querySelector(`#${a.highlight.id}`)),d=u.getElementsByClassName(hn)[0];let g=parseInt(d.style.top.replace("px","")),y=jt(Fe({},a),{highlight:jt(Fe({},a.highlight),{position:g})});return[...o,y]};return t.reduce(r,[])}reposition(t){let n=this.delegate.iframes[0].contentDocument,r=(o,a,l)=>{let u=t[0],d=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),f,g;d&&(f=d.querySelector(`#${u.highlight.id}`)),g=f.getElementsByClassName(hn)[0];let v=parseInt(g.style.height.replace("px","")),S=a.highlight.position,w=o[l-1]&&o[l-1].highlight.position,m=l===0?0:w+v+0,E=m>S?m:S,O=jt(Fe({},a),{highlight:jt(Fe({},a.highlight),{position:E})});return[...o,O]};return t.sort(function(o,a){return o.highlight.position-a.highlight.position}).reduce(r,[])}};C();var A0=Je(T0());var Rr=Je(Dt()),el=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(r=>r(n))}constructor(t,n,r,o,a,l,u,d){this.annotator=t,this.rights=n,this.publication=r,this.headerMenu=d,this.delegate=o,this.initialAnnotations=l,this.properties=a,this.api=u}stop(){Rr.default.log("Bookmark module stop")}async start(){if(this.delegate.bookmarkModule=this,this.headerMenu&&(this.bookmarksView=de(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=de(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let t=de(this.headerMenu,"#menu-button-bookmark");t&&t.parentElement?.style.removeProperty("display"),t&&ne(t,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let t=this.initialAnnotations.bookmarks||null;t&&this.annotator?.initBookmarks(t)}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 Rr.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else{let n=await this.annotator.deleteBookmark(t);return Rr.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),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 r=this.delegate.view?.getCurrentPosition(),o=(0,A0.v4)(),a;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let l=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),u=Math.ceil((r??0)*(l.length-1)),d=l[u];a=jt(Fe({},d),{id:o,href:n,created:new Date,title:this.delegate.currentChapterLink.title})}else a={id:o,href:n,locations:{progression:r},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title};if(!this.annotator.locatorExists(a,fr.Bookmark))if(this.api?.addBookmark){let l=await this.api.addBookmark(a);l&&(a=l),Rr.default.log(a);let u=this.annotator.saveBookmark(a);return Rr.default.log("Bookmark added "+JSON.stringify(u)),this.showBookmarks(),await this.drawBookmarks(),u}else{let l=this.annotator.saveBookmark(a);return Rr.default.log("Bookmark added "+JSON.stringify(l)),this.showBookmarks(),await this.drawBookmarks(),l}}}}async addBookmarkPlus(){let t=this,n=this.delegate.highlighter?.visibleTextRects[0],r=this.delegate.iframes[0].contentDocument;if(r){let u=this.delegate.highlighter?.dom(r.body).getWindow().document.createRange(),d=this.delegate.highlighter?.dom(this.delegate.iframes[0].contentDocument?.body).getSelection();d.removeAllRanges(),n&&u.selectNodeContents(n.node),d.addRange(u);let f=yd(u,!1),g=0;for(let y of f){if(!this.delegate.highlighter?.isOutsideViewport(y)){let v=d.focusNode,S=d.focusOffset;d.collapse(d.anchorNode,d.anchorOffset);for(let E=0;E<g;E++)d.modify("move","forward","line");d.extend(v,S);let w=d.focusNode,b=d.focusNode.length;d.collapse(d.anchorNode,d.anchorOffset);let m=b;d.anchorOffset>b?m=b:m=d.anchorOffset+1,d.modify("move","forward","character"),d.modify("move","backward","word"),d.extend(w,m),d.modify("extend","backward","character"),d.modify("extend","forward","word");break}g++}}function o(u){let d={},f=t.delegate.iframes[0].contentDocument;if(f)return Rn(u,t.delegate.highlighter?.dom(f.body).getDocument(),d)}let a=this.delegate.iframes[0].contentWindow,l={id:"bookmarkIcon",marker:Le.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(a!==null){let u=Do(a,o);if(u===void 0){let f=t.delegate.iframes[0].contentDocument;u=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(f)}let d=t.delegate.iframes[0].contentDocument;if(u&&d){let f=this.delegate.highlighter?.createHighlight(this.delegate.highlighter?.dom(d.body).getWindow(),u,l.highlight?.color,!0,Le.Bookmark,l.icon,l.popup,l.highlight?.style);if(this.delegate.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),f)return this.saveAnnotation(f[0]).then(g=>{Rr.default.log("saved bookmark "+g?.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 r=this.delegate.view?.getCurrentPosition(),o=this.delegate.iframes[0].contentDocument;if(o){let a=Oi(o,"body"),l=t.position?t.position/a.scrollHeight:r,u=(0,A0.v4)(),d;if(n){let f=n.Href;if(f.indexOf("#")>0&&(f=f.slice(0,f.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let g=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),y=Math.ceil((l??0)*(g.length-1)),v=g[y];d=jt(Fe({},v),{id:u,href:f,created:new Date,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else d={id:u,href:f,locations:{progression:l},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(d)if(this.api?.addBookmark){let f=await this.api.addBookmark(d),g=await this.annotator.saveAnnotation(f);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(y=>y(g))}else{let f=await this.annotator.saveAnnotation(d);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(g=>g(f))}}}return new Promise(r=>r(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(r=>r.highlight.marker===Le.Bookmark),t?t.push.apply(t,n):t=n)),this.bookmarksView&&this.createTree(fr.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(qe.Annotation);for(let r of n){zt.push(r.highlight);let o=r,a=this.delegate.currentChapterLink.href;var t=this.publication.getTOCItem(a);if(this.delegate.currentTocUrl&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&await this.delegate.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,r.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(qe.Annotation);for(let r of n){zt.push(r.highlight);let o=r,a=this.delegate.currentChapterLink.href,l=this.publication.getTOCItem(a);if(this.delegate.currentTocUrl&&(l=this.publication.getTOCItem(this.delegate.currentTocUrl)),l===void 0&&(l=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),l){let u=l.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),o.href===u&&await this.delegate.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,r.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 Rr.default.log("Highlight deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else return new Promise(r=>r(null))}createTree(t,n,r){if(n){let o=this,a=this.publication.readingOrder;if(a.length){let l=(u,d)=>{let f=document.createElement("ul");f.className="sidenav-annotations";for(let g of d){let y=document.createElement("li"),v=document.createElement("a"),S=document.createElement("span");if(v.tabIndex=-1,v.className="chapter-link",g.Href){let b=this.publication.getAbsoluteHref(g.Href),m=this.publication.getTOCItemAbsolute(b);v.href=b,v.innerHTML=m?.Title||"",y.appendChild(v)}else S.innerHTML=g.Title||"",S.className="chapter-title",y.appendChild(S);ne(v,"click",b=>{b.preventDefault(),b.stopPropagation();let m={href:v.href,locations:{progression:0},type:g.TypeLink,title:v.title};this.delegate.stopReadAloud(),this.delegate.navigate(m)});let w=document.createElement("ol");n.forEach(function(b){let m=g.Href.indexOf("#")!==-1?g.Href.slice(0,g.Href.indexOf("#")):g.Href;if(g.Href&&b.href.endsWith(m)){let E=document.createElement("li");E.className="annotation-item";let O=document.createElement("a");if(O.setAttribute("href",b.href),t===fr.Bookmark){O.className="bookmark-link";let A=document.createElement("span"),T=Math.round((b.locations.progression??0)*100)+"% through resource";A.className="title",A.innerHTML=T,O.appendChild(A)}let _=document.createElement("span");if(_.className="timestamp",_.innerHTML=el.readableTimestamp(b.created),O.appendChild(_),ne(O,"click",A=>{A.preventDefault(),A.stopPropagation(),o.handleAnnotationLinkClick(A,b)}),E.appendChild(O),o.delegate.sideNavExpanded){let A=document.createElement("button");A.className="delete",A.innerHTML=$r.delete,ne(A,"click",T=>{T.preventDefault(),T.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,T,b)}),E.appendChild(A)}w.appendChild(E)}}),w.children.length>0&&(f.appendChild(y),f.appendChild(w)),f.children.length>0&&u.appendChild(f),g.Children&&g.Children.length>0&&l(u,g.Children)}};r.innerHTML="",l(r,a)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.delegate.stopReadAloud(),this.delegate.navigate(n)):Rr.default.log("bookmark data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,r){Rr.default.log("bookmark data locator: ",r),r?t===fr.Bookmark&&this.deleteBookmark(r):Rr.default.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)}};C();var D4=Je(j4());C();var Vn=Je(Dt()),R0="r2-mo-active",Uo=class{},Ne=Uo;Ne.COLOR_REF="color",Ne.AUTO_SCROLL_REF="autoscroll",Ne.AUTO_TURN_REF="autoturn",Ne.VOLUME_REF="volume",Ne.RATE_REF="rate",Ne.COLOR_KEY="mediaoverlay-"+Uo.COLOR_REF,Ne.AUTO_SCROLL_KEY="mediaoverlay-"+Uo.AUTO_SCROLL_REF,Ne.AUTO_TURN_KEY="mediaoverlay-"+Uo.AUTO_TURN_REF,Ne.VOLUME_KEY="mediaoverlay-"+Uo.VOLUME_REF,Ne.RATE_KEY="mediaoverlay-"+Uo.RATE_REF;var M0=class{constructor(t,n,r){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=r,this.initialise(),Vn.default.log(this.api)}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialMediaOverlaySettings){let r=t.initialMediaOverlaySettings;r?.color&&(n.color=r.color,Vn.default.log(n.color)),r?.autoScroll&&(n.autoScroll=r.autoScroll,Vn.default.log(n.autoScroll)),r?.autoTurn&&(n.autoTurn=r.autoTurn,Vn.default.log(n.autoScroll)),r?.volume&&(n.volume=r.volume,Vn.default.log(n.volume)),r?.rate&&(n.rate=r.rate,Vn.default.log(n.rate)),r?.wait&&(n.wait=r.wait,Vn.default.log(n.wait))}return n.initializeSelections(),n}stop(){Vn.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(Ne.AUTO_SCROLL_KEY)!=null?this.getProperty(Ne.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(Ne.AUTO_TURN_KEY)!=null?this.getProperty(Ne.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(Ne.COLOR_KEY)!=null?this.getProperty(Ne.COLOR_KEY).value:this.color,this.volume=this.getProperty(Ne.VOLUME_KEY)!=null?this.getProperty(Ne.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(Ne.RATE_KEY)!=null?this.getProperty(Ne.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=de(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechAutoTurn=de(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=de(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=de(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=de(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()),ne(de(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(Ne.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Ne.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(Ne.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(Ne.VOLUME_REF)?.value,rate:this.userProperties.getByRef(Ne.RATE_REF)?.value};this.applyMediaOverlaySettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{Vn.default.log("api updated sync settings",n)})}getMediaOverlaySettings(){let t=new Si;return t.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,Ne.AUTO_SCROLL_REF,Ne.AUTO_SCROLL_KEY),t.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,Ne.AUTO_TURN_REF,Ne.AUTO_TURN_KEY),t.addStringable(this.color,Ne.COLOR_REF,Ne.COLOR_KEY),t.addIncremental(this.volume,.1,1,.1,"",Ne.VOLUME_REF,Ne.VOLUME_KEY),t.addIncremental(this.rate,.1,3,.1,"",Ne.RATE_REF,Ne.RATE_KEY),t}saveProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let r=JSON.parse(n);r=r.filter(o=>o.name!==t.name),r.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(r))}else{let r=[];r.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(r))}return t}getProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let r=JSON.parse(n);return r=r.filter(o=>o.name===t),r.length===0?null:r[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(Ne.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){Vn.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Ne.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoTurn!==void 0){Vn.default.log("autoTurn "+this.autoTurn),this.autoTurn=t.autoTurn;let n=this.userProperties.getByRef(Ne.AUTO_TURN_REF);n&&(n.value=this.autoTurn,this.saveProperty(n)),this.settingsChangeCallback()}if(t.volume){Vn.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Ne.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback()}if(t.rate){Vn.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Ne.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback()}}applyMediaOverlaySetting(t,n){if(t===Ne.COLOR_REF){this.color=n;let r=this.userProperties.getByRef(Ne.COLOR_REF);r&&(r.value=this.color,this.saveProperty(r)),this.settingsChangeCallback()}else if(t===Ne.AUTO_SCROLL_REF){this.autoScroll=n;let r=this.userProperties.getByRef(Ne.AUTO_SCROLL_REF);r&&(r.value=this.autoScroll,this.saveProperty(r)),this.settingsChangeCallback()}else if(t===Ne.AUTO_TURN_REF){this.autoTurn=n;let r=this.userProperties.getByRef(Ne.AUTO_TURN_REF);r&&(r.value=this.autoTurn,this.saveProperty(r)),this.settingsChangeCallback()}}increase(t){if(t==="mo_volume"){this.userProperties.getByRef(Ne.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(Ne.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Ne.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Ne.RATE_REF).increment(),this.rate=this.userProperties.getByRef(Ne.RATE_REF)?.value;let n=this.userProperties.getByRef(Ne.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}decrease(t){if(t==="mo_volume"){this.userProperties.getByRef(Ne.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(Ne.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Ne.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Ne.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(Ne.RATE_REF)?.value;let n=this.userProperties.getByRef(Ne.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}};var He=Je(Dt()),P0=class{constructor(t,n,r,o){this.play=de(document,"#menu-button-play");this.pause=de(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async t=>{He.default.log("ontimeupdate"),this.trackCurrentTime()};this.ensureOnTimeUpdate=(t,n)=>{t?this.__ontimeupdate&&(this.__ontimeupdate=!1,this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),cancelAnimationFrame(this.myReq)):(!this.__ontimeupdate||n)&&(this.__ontimeupdate=!0,n&&(this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),this.audioElement.addEventListener("timeupdate",this.ontimeupdate)))};this.delegate=t,this.publication=n,this.settings=r,this.properties=o}static create(t){let n=new this(t.delegate,t.publication,t.settings,t);return n.start(),n}stop(){He.default.log("MediaOverlay module stop")}start(){this.delegate.mediaOverlayModule=this,He.default.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(),a;try{a=await fetch(o,this.delegate.requestConfig)}catch(f){console.error(f,o);return}a.ok||He.default.log("BAD RESPONSE?!");let l;try{l=await a.json()}catch(f){console.error(f)}if(!l){He.default.log("## moJson"+l);return}t.MediaOverlays=Ts(l,D4.MediaOverlayNode),t.MediaOverlays.initialized=!0;let u=t.HrefDecoded||t.Href,d=new URL("https://dita.digital/"+u);await this.playMediaOverlays(d.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&&await this.audioElement.pause(),this.delegate.nextResource()):await this.stopReadAloud()}async startReadAloud(){if(this.delegate.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement&&this.currentLinks[this.currentLinkIndex]?.Properties.MediaOverlay){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.removeProperty("display")}}async stopReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"))}findDepthFirstTextAudioPair(t,n,r){He.default.log("findDepthFirstTextAudioPair()");let o,a;if(n.Text){let d=new URL("https://dita.digital/"+n.Text);if(d.pathname.substr(1)===t){if(o=!0,d.hash&&r){a=!1;let f=d.hash.substr(1);for(let g of r)if(g===f){a=!0;break}}}else o=!1}if(He.default.log("isFragmentIDMatch: "+a),He.default.log("isTextUrlMatch: "+o),!n.Children||!n.Children.length){if(He.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!o){He.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return a||o&&!r?(He.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),n):void 0}let l=r,u=r;for(let d of n.Children){He.default.log("findDepthFirstTextAudioPair() - child"),He.default.log(JSON.stringify(d));let f=this.findDepthFirstTextAudioPair(t,d,u);if(f===null&&(He.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),u=void 0),f)return He.default.log("findDepthFirstTextAudioPair() - child - match"),He.default.log(JSON.stringify(f)),f}if(a){He.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let d=this.findDepthFirstTextAudioPair(t,n,void 0);return d&&(He.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),He.default.log(JSON.stringify(d)),d)}if(l&&!u)return null}trackCurrentTime(){if(cancelAnimationFrame(this.myReq),this.mediaOverlayTextAudioPair)try{this.currentAudioEnd&&this.audioElement.currentTime>=this.currentAudioEnd-.05&&(He.default.log("ontimeupdate - mediaOverlaysNext()"),this.mediaOverlaysNext());let 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(He.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let n=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!t);if(!n)He.default.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud());else{let r=!1;if(this.mediaOverlayTextAudioPair.Text&&n.Text){let o=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),a=new URL("https://dita.digital/"+n.Text);o.pathname!==a.pathname&&(He.default.log("mediaOverlaysNext() SWITCH! "+o.pathname+" != "+a.pathname),r=!0)}r?this.mediaOverlaysStop():(He.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(n,void 0,void 0)},0))}}else He.default.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){He.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){He.default.log("mediaOverlaysPause()"),this.mediaOverlayHighlight(void 0),this.audioElement&&this.audioElement.pause()}findNextTextAudioPair(t,n,r,o){if(!t.Children||!t.Children.length){if(r?.prev===n)return He.default.log("findNextTextAudioPair() - prevMo === moToMatch"),t;He.default.log("findNextTextAudioPair() - set previous"),He.default.log(JSON.stringify(t)),r.prev=t;return}for(let a of t.Children){He.default.log("findNextTextAudioPair() - child"),He.default.log(JSON.stringify(a));let l=this.findNextTextAudioPair(a,n,r,o);if(l)return He.default.log("findNextTextAudioPair() - match"),He.default.log(JSON.stringify(l)),l}}async playMediaOverlaysAudio(t,n,r){if(He.default.log("playMediaOverlaysAudio()"),this.mediaOverlayTextAudioPair=t,!t.Audio)return;let o=new URL(t.Audio,this.publication.manifestUrl),a=o.toString(),l=new URL(a);l.hash="",l.search="";let u=l.toString(),d=typeof n!="undefined",f=typeof r!="undefined";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!d&&!f){if(o.hash){let y=o.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(y&&y.length>=1){let v=y[1];try{this.currentAudioBegin=parseFloat(v)}catch(S){He.default.error(S)}if(y.length>=3){let S=y[3];try{this.currentAudioEnd=parseFloat(S)}catch(w){He.default.error(w)}}}}}else this.currentAudioBegin=n,this.currentAudioEnd=r;He.default.log(`${a} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let g=async y=>{if(!this.audioElement)return;let v=this.currentAudioBegin?this.currentAudioBegin:0;if(y||this.audioElement.paused)if(y&&!v||this.audioElement.currentTime===v){if(He.default.log("playMediaOverlaysAudio() - playClip() - _currentAudioElement.play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing){let w=function(){S.settings.resourceReady?setTimeout(async()=>{await S.audioElement.play(),S.ensureOnTimeUpdate(!1,!0)},S.settings.wait*1e3):setTimeout(w,200)},S=this;w()}}else{He.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let S=async w=>{if(this.audioElement.removeEventListener("timeupdate",S),He.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked - .play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement&&(this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing)){let m=function(){b.settings.resourceReady?setTimeout(async()=>{await b.audioElement.play(),b.ensureOnTimeUpdate(!1,!0)},b.settings.wait*1e3):setTimeout(m,200)},b=this;m()}};this.audioElement.addEventListener("timeupdate",S),this.audioElement.currentTime=v}else{let S=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd!="undefined"&&this.previousAudioEnd>v-.02&&this.previousAudioEnd<=v&&this.audioElement.currentTime>=v-.1;this.ensureOnTimeUpdate(!1,!1),S?He.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(He.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=v)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||u!==this.currentAudioUrl){this.currentAudioUrl=u,He.default.log("playMediaOverlaysAudio() - RESET: "+this.previousAudioUrl+" => "+this.currentAudioUrl),this.audioElement=document.getElementById("AUDIO_MO_ID"),this.audioElement&&(this.audioElement.pause(),this.audioElement.setAttribute("src",""),this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement)),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("style","display: none"),this.audioElement.setAttribute("id","AUDIO_MO_ID"),this.audioElement.setAttribute("role","media-overlays"),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate,document.body.appendChild(this.audioElement),this.audioElement.addEventListener("error",S=>{He.default.log("-1) error: "+(this.currentAudioUrl!==S.currentTarget.src?this.currentAudioUrl+" -- ":"")+S.currentTarget.src.substr(S.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(He.default.log(this.audioElement.error.code),He.default.log(this.audioElement.error.message))});let y=async S=>{S.currentTarget.removeEventListener("canplaythrough",y),He.default.log("oncanplaythrough"),await g(!0)};this.audioElement.addEventListener("canplaythrough",y);let v=async S=>{He.default.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",v),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else He.default.log("playMediaOverlaysAudio() - playClip()"),await g(!1)}async playMediaOverlays(t,n,r){He.default.log("playMediaOverlays()");let o=r?r.filter(l=>l):void 0;o&&o.length===0&&(o=void 0);let a=this.findDepthFirstTextAudioPair(t,n,o);!a&&o&&(He.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),He.default.log(JSON.stringify(o,null,4)),He.default.log(JSON.stringify(n,null,4)),a=this.findDepthFirstTextAudioPair(t,n,void 0)),a?a.Audio&&(He.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=n,await this.playMediaOverlaysAudio(a,void 0,void 0)):He.default.log("playMediaOverlays() - !moTextAudioPair "+t)}mediaOverlayHighlight(t){He.default.log("moHighlight: ## "+t);let n=this.publication.Metadata?.MediaOverlay?.ActiveClass;n||(n=this.settings.color);let r=this.delegate.iframes[0].contentDocument?.documentElement.getAttribute("style"),o=r?r.indexOf("readium-night-on")>0:!1,a=r?r.indexOf("readium-sepia-on")>0:!1;if((this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&(n=o||a?R0:n||R0),this.pid){let u;this.currentLinkIndex===0?u=this.delegate.iframes[0].contentDocument?.getElementById(this.pid):u=this.delegate.iframes[1].contentDocument?.getElementById(this.pid),u&&u.classList.remove(n)}let l;t&&(this.currentLinkIndex===0?l=this.delegate.iframes[0].contentDocument?.getElementById(t):l=this.delegate.iframes[1].contentDocument?.getElementById(t),l&&l.classList.add(n),this.pid=t),l&&(this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&l.scrollIntoView({block:"center",behavior:"smooth"})}};C();var I0=Je(Dt()),L0=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(){I0.default.log("Timeline module stop")}async start(){this.delegate.timelineModule=this,this.timelineContainer=de(document,"#container-view-timeline"),this.positionSlider=de(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.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(r=>{let o=this.publication.getAbsoluteHref(r.Href),a=this.publication.getTOCItemAbsolute(o),l=a?.Href.indexOf("#")!==-1?a?.Href.slice(0,a?.Href.indexOf("#")):a.Href,u=this.publication.getAbsoluteHref(l??"");var d;this.publication.positions&&this.delegate.view?.layout!=="fixed"?r.contentWeight?d=r.contentWeight:d=1:d=100/(this.publication.readingOrder?.length??0);var f=document.createElement("div");if(f.style.height=d+"%",f.style.width="100%",f.className="chapter",a?.Title!==void 0){var g=document.createElement("span");g.innerHTML=a.Title,g.className="chapter-tooltip",f.appendChild(g)}ne(f,"click",y=>{y.preventDefault(),y.stopPropagation();var v;this.publication.positions||this.delegate.rights.autoGeneratePositions&&this.publication.positions?(v=Fe({},this.publication.positions.filter(S=>S.href===r.Href)[0]),v.href=this.publication.getAbsoluteHref(v.href)):v={href:u,locations:{progression:0},type:r.TypeLink,title:r.Title},I0.default.log(v),this.delegate.navigate(v)}),u===this.delegate.currentChapterLink.href?f.className+=" active":f.className=f.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(f)}),t()})}};C();var Q0=Je(Qi());C();var F4=Je(Dt());function $4(i,t){return new Promise(function(n){setTimeout(n.bind(null,t),i)})}var H8=!1;F4.default.setLevel(H8?"trace":"warn",!0);var y3=Je(g3()),Hd=Je(m3()),wn=Je(Dt()),jd=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){(0,Hd.addListener)(r=>{r&&(t.clearOnInspect&&(console.clear(),window.localStorage.clear(),window.sessionStorage.clear(),window.location.replace(window.location.origin)),t.detectInspect&&typeof t.api?.inspectDetected=="function"&&t.api.inspectDetected())}),(0,Hd.launch)(),await $4(t.detectInspectInitDelay??100)}static isCurrentBrowserSupported(t){if(!t.enforceSupportedBrowsers)return!0;let n=[];return(t.supportedBrowsers??[]).forEach(o=>{n.push("last 1 "+o+" version")}),(0,y3.getUserAgentRegExp)({browsers:n,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.delegate.contentProtectionModule=this,this.properties?.enableObfuscation){this.wrapper=dt(document,"#iframe-wrapper"),this.securityContainer=de(document,"#container-view-security");var t=this;this.mutationObserver=new MutationObserver(function(n){n.forEach(function(r){wn.default.log(r.type),t.isHacked=!0})})}}async stop(){if(wn.default.log("Protection module stop"),this.mutationObserver.disconnect(),this.properties?.disableKeys){Pe(this.delegate.mainElement,"keydown",this.disableSave),Pe(this.delegate.headerMenu,"keydown",this.disableSave);for(let t of this.delegate.iframes)Pe(t.contentDocument,"keydown",this.disableSave),Pe(t.contentWindow,"keydown",this.disableSave);Pe(window,"keydown",this.disableSave),Pe(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){Pe(this.delegate.mainElement,"copy",this.preventCopy),Pe(this.delegate.headerMenu,"copy",this.preventCopy);for(let t of this.delegate.iframes)Pe(t.contentDocument,"copy",this.preventCopy),Pe(t.contentWindow,"copy",this.preventCopy);Pe(window,"copy",this.preventCopy),Pe(document,"copy",this.preventCopy),Pe(this.delegate.mainElement,"cut",this.preventCopy),Pe(this.delegate.headerMenu,"cut",this.preventCopy);for(let t of this.delegate.iframes)Pe(t.contentDocument,"cut",this.preventCopy),Pe(t.contentWindow,"cut",this.preventCopy);Pe(window,"cut",this.preventCopy),Pe(document,"cut",this.preventCopy)}if(this.properties?.disablePrint){Pe(this.delegate.mainElement,"beforeprint",this.beforePrint.bind(this)),Pe(this.delegate.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let t of this.delegate.iframes)Pe(t.contentDocument,"beforeprint",this.beforePrint),Pe(t.contentWindow,"beforeprint",this.beforePrint);Pe(window,"beforeprint",this.beforePrint),Pe(document,"beforeprint",this.beforePrint),Pe(this.delegate.mainElement,"afterprint",this.afterPrint.bind(this)),Pe(this.delegate.headerMenu,"afterprint",this.afterPrint.bind(this));for(let t of this.delegate.iframes)Pe(t.contentDocument,"afterprint",this.afterPrint.bind(this)),Pe(t.contentWindow,"afterprint",this.afterPrint.bind(this));Pe(window,"afterprint",this.afterPrint.bind(this)),Pe(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){Pe(this.delegate.mainElement,"contextmenu",this.disableContext),Pe(this.delegate.headerMenu,"contextmenu",this.disableContext);for(let t of this.delegate.iframes)Pe(t.contentDocument,"contextmenu",this.disableContext),Pe(t.contentWindow,"contextmenu",this.disableContext);Pe(window,"contextmenu",this.disableContext),Pe(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),Pe(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=Oi(t.contentDocument,"body");this.rects=this.findRects(n),this.rects.forEach(r=>this.toggleRect(r,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){ne(this.delegate.mainElement,"keydown",this.disableSave),ne(this.delegate.headerMenu,"keydown",this.disableSave);for(let t of this.delegate.iframes)ne(t,"keydown",this.disableSave),ne(t.ownerDocument,"keydown",this.disableSave),ne(t.contentDocument,"keydown",this.disableSave),ne(t.contentWindow,"keydown",this.disableSave),ne(t.contentWindow?.document,"keydown",this.disableSave);ne(window,"keydown",this.disableSave),ne(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){ne(this.delegate.mainElement,"copy",this.preventCopy),ne(this.delegate.headerMenu,"copy",this.preventCopy);for(let t of this.delegate.iframes)ne(t,"copy",this.preventCopy),ne(t.ownerDocument,"copy",this.preventCopy),ne(t.contentDocument,"copy",this.preventCopy),ne(t.contentWindow,"copy",this.preventCopy),ne(t.contentWindow?.document,"copy",this.preventCopy);ne(window,"copy",this.preventCopy),ne(document,"copy",this.preventCopy),ne(this.delegate.mainElement,"cut",this.preventCopy),ne(this.delegate.headerMenu,"cut",this.preventCopy);for(let t of this.delegate.iframes)ne(t,"cut",this.preventCopy),ne(t.ownerDocument,"cut",this.preventCopy),ne(t.contentDocument,"cut",this.preventCopy),ne(t.contentWindow,"cut",this.preventCopy),ne(t.contentWindow?.document,"cut",this.preventCopy);ne(window,"cut",this.preventCopy),ne(document,"cut",this.preventCopy)}if(this.properties?.disablePrint){ne(this.delegate.mainElement,"beforeprint",this.beforePrint),ne(this.delegate.headerMenu,"beforeprint",this.beforePrint);for(let t of this.delegate.iframes)ne(t,"beforeprint",this.beforePrint.bind(this)),ne(t.ownerDocument,"beforeprint",this.beforePrint.bind(this)),ne(t.contentDocument,"beforeprint",this.beforePrint.bind(this)),ne(t.contentWindow,"beforeprint",this.beforePrint.bind(this)),ne(t.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));ne(window,"beforeprint",this.beforePrint.bind(this)),ne(document,"beforeprint",this.beforePrint.bind(this)),ne(this.delegate.mainElement,"afterprint",this.afterPrint),ne(this.delegate.headerMenu,"afterprint",this.afterPrint);for(let t of this.delegate.iframes)ne(t,"afterprint",this.afterPrint.bind(this)),ne(t.ownerDocument,"afterprint",this.afterPrint.bind(this)),ne(t.contentDocument,"afterprint",this.afterPrint.bind(this)),ne(t.contentWindow,"afterprint",this.afterPrint.bind(this)),ne(t.contentWindow?.document,"afterprint",this.afterPrint.bind(this));ne(window,"afterprint",this.afterPrint.bind(this)),ne(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){ne(this.delegate.mainElement,"contextmenu",this.disableContext),ne(this.delegate.headerMenu,"contextmenu",this.disableContext);for(let t of this.delegate.iframes)ne(t,"contextmenu",this.disableContext),ne(t.ownerDocument,"contextmenu",this.disableContext),ne(t.contentDocument,"contextmenu",this.disableContext),ne(t.contentWindow,"contextmenu",this.disableContext),ne(t.contentWindow?.document,"contextmenu",this.disableContext);ne(window,"contextmenu",this.disableContext),ne(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 r=Oi(n.contentDocument,"body");this.observe(),setTimeout(()=>{this.rects=this.findRects(r),this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),this.setupEvents(),this.hasEventListener||(this.hasEventListener=!0,ne(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,Q0.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 wn.default.log("copy action initiated"),t.clipboardData.setData("text/plain","copy not allowed"),t.stopPropagation(),t.preventDefault(),!1}beforePrint(t){return wn.default.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 wn.default.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(r){r.preventDefault();let o=r.currentTarget.getAttribute("data-href-resolved"),a=document.createElement("a");a.setAttribute("href",o),a.click()}for(let r of this.delegate.iframes){let o=r.contentDocument?.querySelectorAll("a");o?.forEach(a=>{let l=a.getAttribute("data-href"),u=a.getAttribute("href");!l&&u&&(a.setAttribute("data-href",u),a.setAttribute("data-href-resolved",a.href))}),t?o?.forEach(a=>{a.setAttribute("href",""),a.addEventListener("click",n)}):o?.forEach(a=>{let l=a.getAttribute("data-href");l&&a.setAttribute("href",l),a.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;",r=o=>{o.preventDefault()};for(let o of this.delegate.iframes){let a=o.contentDocument?.body.getAttribute("style")||"";t?(o.contentDocument?.body.addEventListener("dragstart",r),o.contentDocument?.body.setAttribute("style",a+n)):(o.contentDocument?.body.removeEventListener("dragstart",r),o.contentDocument?.body.setAttribute("style",a.replace(n,"")))}}recalculate(t=0){return new Promise(n=>{if(this.properties?.enableObfuscation){let r=(0,Q0.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(),r()):n(!1)}else n(!1)})}calcRects(t){t!==void 0&&t.forEach(n=>{try{let{top:r,height:o,left:a,width:l}=this.measureTextNode(n.node);n.top=r,n.height=o,n.width=l,n.left=a}catch(r){wn.default.log("error "+r),wn.default.log(n),wn.default.log(n.node),wn.default.log("scrambledTextContent "+n.scrambledTextContent),wn.default.log("textContent "+n.textContent),wn.default.log("isObfuscated "+n.isObfuscated)}})}deactivateRect(t,n,r){this.isBeingHacked(n)||r?(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0):(t.node.textContent=t.textContent,t.isObfuscated=!1)}toggleRect(t,n,r){let o=this.isOutsideViewport(t),a=this.isBeingHacked(n);t.isObfuscated&&!o&&!a&&!r&&(t.node.textContent=t.textContent,t.isObfuscated=!1),!t.isObfuscated&&(o||a||r)&&(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0)}findRects(t){return this.findTextNodes(t).map(r=>{let{top:o,height:a,left:l,width:u}=this.measureTextNode(r),d=r.parentElement?.nodeName==="option"||r.parentElement?.nodeName==="script"?r.textContent:this.obfuscateText(r.textContent??"");return{top:o,height:a,width:u,left:l,node:r,textContent:r.textContent??"",scrambledTextContent:d??"",isObfuscated:!1}})}obfuscateText(t){return this.scramble(t,!0)}measureTextNode(t){try{let n=document.createRange();n.selectNode(t);let r=n.getBoundingClientRect();return n.detach(),r}catch(n){wn.default.log("measureTextNode "+n),wn.default.log("measureTextNode "+t),wn.default.log(t.textContent)}}isBeingHacked(t){return t.style.animation||t.style.transition||t.style.position||t.hasAttribute("style")?(wn.default.log("content being hacked"),!0):!1}isOutsideViewport(t){let n=this.wrapper.scrollLeft,r=n+this.wrapper.clientWidth,o=t.left+t.width,a=t.top+t.height,l=this.wrapper.scrollTop,u=l+this.wrapper.clientHeight,d=a<l,f=t.top>u,g=o<n-window.innerWidth,y=t.left>r+window.innerWidth;return d||f||g||y}findTextNodes(t,n=[]){let r=t.firstChild;for(;r;)r.nodeType===1&&this.findTextNodes(r,n),r.nodeType===3&&r.textContent?.trim()&&n.push(r),r=r.nextSibling;return n}scramble(t,n=!1,r=!1){var o=t.split(" ");function a(l){for(var u=l.length,d,f;u>0;)f=Math.floor(Math.random()*u),u--,d=l[u],l[u]=l[f],l[f]=d;return l}return n&&(o=o.map(function(l){return a(l.split("")).join("")})),r?a(o).join(" "):o.join(" ")}};C();var O3=Je(v3());C();var Dd=i=>i.replace(/\n/g," ").replace(/\s\s+/g," "),eN=i=>Dd(i).trim(),w3=/[\\^$.*+?()[\]{}|]/g,tN=RegExp(w3.source);function E3(i){return i&&tN.test(i)?i.replace(w3,"\\$&"):i||""}var Fd=0,nN=()=>()=>Number.isSafeInteger(++Fd)?Fd:Fd=1,S3=()=>{Fd=0},rN=nN(),iN=i=>t=>{try{return Rn(t,i,no)}catch(n){return console.error("uniqueCssSelector:",n),""}};async function Js(i,t,n,r,o=!1){if(!t)return[];let a=t.body?.textContent;if(!a)return[];if(i=eN(i),!i.length)return[];let l=t.createNodeIterator(t.body,NodeFilter.SHOW_TEXT,{acceptNode:S=>NodeFilter.FILTER_ACCEPT}),u=new RegExp(E3(i).replace(/ /g,"\\s+"),"gim");o&&(u=new RegExp("\\b"+E3(i).replace(/ /g,"\\s+")+"\\b","gim"));let d=[],f=100,g=30,y=0,v;for(;v=u.exec(a);){let S=Math.max(0,v.index-f),w=Math.min(f,v.index),b=Dd(a.substr(S,w));b=b.substr(b.length-g),S=u.lastIndex,w=Math.min(f,a.length-S);let m=Dd(a.substr(S,w)).substr(0,g),E=new Range,O=v.index;for(;y<=O;){let T=l.nextNode();T&&T.nodeValue&&(y+=T.nodeValue.length)}let _=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(y-O):0;for(E.setStart(l.referenceNode,_),O=v.index+v[0].length;y<=O;){let M=l.nextNode()?.nodeValue;M&&(y+=M.length)}_=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(y-O):0,E.setEnd(l.referenceNode,_),t.getCssSelector||(t.getCssSelector=iN(t));let A=Ri(E,t.getCssSelector);A&&d.push({textMatch:Dd(v[0]),textBefore:b,textAfter:m,rangeInfo:A,href:n,title:r,uuid:rN().toString()})}return d}var x3=Je(Dt()),tg=class{constructor(t,n,r,o,a,l){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.delegate=t,this.headerMenu=l,this.publication=n,this.properties=r,this.api=a,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(){x3.default.log("Search module stop"),Pe(this.searchInput,"keypress",this.handleSearch.bind(this)),Pe(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.delegate.searchModule=this,this.headerMenu){this.searchInput=de(this.headerMenu,"#searchInput"),ne(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=de(this.headerMenu,"#searchGo"),ne(this.searchGo,"click",this.handleSearch.bind(this));var t=de(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,r=this.searchInput.value;let o=this.delegate.currentChapterLink.href,a=this.publication.getSpineItem(o);if(this.headerMenu)var l=de(document,"#searchResultChapter");n.currentChapterSearchResult=[],n.currentSearchHighlights=[];var u=[];this.delegate.rights.enableContentProtection&&this.delegate.contentProtectionModule?.deactivate(),await this.searchAndPaintChapter(r,t,async f=>{u=f,d(1),this.delegate.rights.enableContentProtection&&this.delegate.contentProtectionModule?.recalculate(200)});async function d(f){l.innerHTML="";var g;if(g=n.paginate(u,f,10),g.total===0){let y=document.createElement("a");y.className="collection-item",y.innerHTML="nothing found",l.appendChild(y)}else{for(let b=0;b<g.data.length;b++){let m=document.createElement("a"),E=g.data[b];m.className="collection-item",m.href=a?.Href??"",m.innerHTML="..."+E.textBefore+"<mark>"+E.textMatch+"</mark>"+E.textAfter+"...",ne(m,"click",O=>{O.preventDefault(),O.stopPropagation(),n.jumpToMark(b+f*10-10)}),l.appendChild(m)}let y=document.createElement("div");y.style.textAlign="center",y.style.marginTop="10px";let v=document.createElement("ul");v.className="pagination";let S=document.createElement("li");if(S.className="disabled",S.innerHTML='<a href="#!"> < </a>',g.pre_page!==void 0){let b=g.pre_page;S.className="waves-effect",ne(S,"click",m=>{m.preventDefault(),m.stopPropagation(),d(b)})}v.appendChild(S);for(let b=1;b<=g.total_pages;b++){let m,E=document.createElement("li");E.className="waves-effect",b===g.page&&(E.className="active",m=E),E.innerHTML='<a href="#!">'+b+"</a>",ne(E,"click",O=>{O.preventDefault(),O.stopPropagation(),m&&(m.className="waves-effect"),E.className="active",m=E,d(b)}),v.appendChild(E)}let w=document.createElement("li");if(w.className="disabled",w.innerHTML='<a href="#!"> > </a>',g.next_page!==void 0){let b=g.next_page;w.className="waves-effect",ne(w,"click",m=>{m.preventDefault(),m.stopPropagation(),d(b)})}v.appendChild(w),y.appendChild(v),l.appendChild(y)}}}async searchAndPaintChapter(t,n=0,r){let o=this.publication.getAbsoluteHref(this.publication.readingOrder[this.delegate.currentResource()??0].Href),a=this.publication.getTOCItem(o);a===null&&(a=this.publication.readingOrder[this.delegate.currentResource()??0]);let l=[];this.highlighter?.destroyHighlights(qe.Search),this.delegate.rights.enableSearch&&this.drawSearch();let u=0;if(a){let d=this.delegate.iframes[0].contentDocument;d&&a&&Js(t,d,a.Href,a.Title).then(f=>{f.forEach(g=>{let y={rangeInfo:g.rangeInfo};setTimeout(()=>{let v;u===n?(v=this.createSearchHighlight(y,this.properties?.current),this.jumpToMark(n)):v=this.createSearchHighlight(y,this.properties?.color),g.highlight=v,l.push(g),this.currentChapterSearchResult.push(g),this.currentSearchHighlights.push(v),u++},500)}),setTimeout(()=>{r(l)},500)})}}createSearchHighlight(t,n){try{var r=n;De.isHexColor(r)&&(r=De.hexToRgbChannels(r));let a=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,l=O3.SHA256.hash(a),u="R2_SEARCH_"+l;var o=!1;let d={color:r||Fo,id:u,pointerInteraction:o,selectionInfo:t,marker:Le.Highlight,type:qe.Search},f=this.highlighter?.createHighlightDom(this.delegate.iframes[0].contentWindow,d);return d.position=parseInt((f?.hasChildNodes()?f.childNodes[0]:f).style.top.replace("px","")),d}catch(a){throw"Can't create highlight: "+a}}clearSearch(){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.highlighter?.destroyHighlights(qe.Search)}async search(t,n){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],S3(),this.searchAndPaintChapter(t,0,async()=>{});var r=this.searchChapter(t),o=this.searchBook(t);return n?r:o}async goToSearchID(t,n,r){var o=n,a;let l=this.delegate.currentChapterLink.href;var u=this.publication.getAbsoluteHref(t);let d=this.bookSearchResult.filter(f=>f.href===t);if(r?(a=this.currentChapterSearchResult.filter(f=>f.uuid===n)[0],o=this.currentChapterSearchResult.findIndex(f=>f.uuid===n)):(a=d.filter(f=>f.uuid===n)[0],o=d.findIndex(f=>f.uuid===n)),a!==void 0)if(l===u)this.jumpToMark(o);else{let g={href:u,locations:{progression:0},title:"title"};this.delegate.navigate(g),setTimeout(()=>{this.searchAndPaintChapter(a.textMatch,o,async()=>{})},300)}}async goToSearchIndex(t,n,r){var o=n,a;let l=this.delegate.currentChapterLink.href;var u=this.publication.getAbsoluteHref(t);let d=this.bookSearchResult.filter(f=>f.href===t);if(r?a=this.currentChapterSearchResult[o]:a=d[o],a!==void 0)if(l===u)this.jumpToMark(o);else{let g={href:u,locations:{progression:0},title:"title"};this.delegate.navigate(g),setTimeout(()=>{this.searchAndPaintChapter(a.textMatch,o,async()=>{})},300)}}async handleSearchBook(){var t=this,n=this.searchInput.value;if(t.headerMenu)var r=de(document,"#searchResultBook");o(1);async function o(l){r.innerHTML="";var u,d=await t.searchBook(n);if(u=t.paginate(d,l,10),u.total===0){let f=document.createElement("a");f.className="collection-item",f.innerHTML="nothing found",r.appendChild(f)}else{a(u.data,w=>w.href).forEach(w=>{let b=document.createElement("div");if(b.style.marginBottom="10px",w[0].title){let m=document.createElement("span");m.className="collection-item",m.style.display="block",m.innerHTML=w[0].title,b.appendChild(m)}r.appendChild(b),w.forEach(m=>{let E=document.createElement("a");E.className="collection-item";var O=t.publication.getAbsoluteHref(m.href);E.innerHTML="..."+m.textBefore+"<mark>"+m.textMatch+"</mark>"+m.textAfter+"...",ne(E,"click",_=>{_.preventDefault(),_.stopPropagation();let T=d.filter(j=>j.href===m.href).findIndex(j=>j===m);if(t.delegate.currentChapterLink.href===O)t.jumpToMark(T);else{let P={href:O,locations:{progression:0},title:"title"};t.delegate.navigate(P),setTimeout(()=>{t.handleSearchChapter(T)},300)}}),b.appendChild(E)})});let g=document.createElement("div");g.style.textAlign="center",g.style.marginTop="10px";let y=document.createElement("ul");y.className="pagination";let v=document.createElement("li");if(v.className="disabled",v.innerHTML='<a href="#!"> < </a>',u.pre_page!=null){let w=u.pre_page;v.className="waves-effect",ne(v,"click",b=>{b.preventDefault(),b.stopPropagation(),o(w)})}y.appendChild(v);for(let w=1;w<=u.total_pages;w++){let b,m=document.createElement("li");m.className="waves-effect",w===u.page&&(m.className="active",b=m),m.innerHTML='<a href="#!">'+w+"</a>",ne(m,"click",E=>{E.preventDefault(),E.stopPropagation(),b&&(b.className="waves-effect"),m.className="active",b=m,o(w)}),y.appendChild(m)}let S=document.createElement("li");if(S.className="disabled",S.innerHTML='<a href="#!"> > </a>',u.next_page!=null){let w=u.next_page;S.className="waves-effect",ne(S,"click",b=>{b.preventDefault(),b.stopPropagation(),o(w)})}y.appendChild(S),g.appendChild(y),r.appendChild(g)}}function a(l,u){let d=new Map;return l.forEach(f=>{let g=u(f),y=d.get(g);y?y.push(f):d.set(g,[f])}),Array.from(d.values())}}async searchBook(t){this.bookSearchResult=[];let n=[];for(let r=0;r<this.publication.readingOrder.length;r++){let o=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[r].Href:""),a=this.publication.getTOCItem(o);if(a===void 0&&this.publication.readingOrder&&(a=this.publication.readingOrder[r]),a){let l=this.publication.getAbsoluteHref(a.Href);await fetch(l,this.delegate.requestConfig).then(u=>u.text()).then(async u=>{let f=new DOMParser().parseFromString(this.delegate.requestConfig?.encoded?this.decodeBase64(u):u,"application/xhtml+xml");a&&Js(t,f,a.Href,a.Title).then(g=>{g.forEach(y=>{n.push(y),this.bookSearchResult.push(y)})})})}if(r===this.publication.readingOrder.length-1)return n}}decodeBase64(t){let n=atob(t),r=n.length,o=new Uint8Array(r);for(let l=0;l<r;l++)o[l]=n.charCodeAt(l);return new TextDecoder().decode(o)}async searchChapter(t){let n=[],r=this.publication.getAbsoluteHref(this.publication.readingOrder[this.delegate.currentResource()??0].Href),o=this.publication.getTOCItem(r);if(o===null&&(o=this.publication.readingOrder[this.delegate.currentResource()??0]),o){let a=this.publication.getAbsoluteHref(o.Href);await fetch(a,this.delegate.requestConfig).then(l=>l.text()).then(async l=>{let d=new DOMParser().parseFromString(this.delegate.requestConfig?.encoded?this.decodeBase64(l):l,"application/xhtml+xml");o&&Js(t,d,o.Href,o.Title).then(f=>{f.forEach(g=>{n.push(g)})})})}return n}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(t=>{let n={rangeInfo:t.rangeInfo};if(this.properties?.color){let r=this.createSearchHighlight(n,this.properties?.color);t.highlight=r,this.currentSearchHighlights.push(r)}})},100)}async handleResize(){await this.highlighter?.destroyHighlights(qe.Search),this.drawSearch()}jumpToMark(t){setTimeout(()=>{if(this.currentChapterSearchResult.length){var n=this.currentChapterSearchResult[t];this.currentSearchHighlights.forEach(o=>{var a=this.properties?.color;De.isHexColor(a)&&(a=De.hexToRgbChannels(a)),o.color=a});var r=this.properties?.current;De.isHexColor(r)&&(r=De.hexToRgbChannels(r)),n.highlight.color=r,this.highlighter?.setAndResetSearchHighlight(n.highlight,this.currentSearchHighlights),this.delegate.view?.goToCssSelector(n.rangeInfo.startContainerElementCssSelector),this.delegate.updatePositionInfo()}},200)}paginate(t,n,r){let o=n||1,a=r||10,l=(o-1)*a,u=t.slice(l).slice(0,a),d=Math.ceil(t.length/a);return{page:o,per_page:a,pre_page:o-1?o-1:void 0,next_page:d>o?o+1:void 0,total:t.length,total_pages:d,data:u}}};C();var Kn=Je(Dt()),ao=class{},Be=ao;Be.COLOR_REF="color",Be.AUTO_SCROLL_REF="autoscroll",Be.RATE_REF="rate",Be.PITCH_REF="pitch",Be.VOLUME_REF="volume",Be.VOICE_REF="voice",Be.COLOR_KEY="tts-"+ao.COLOR_REF,Be.AUTO_SCROLL_KEY="tts-"+ao.AUTO_SCROLL_REF,Be.RATE_KEY="tts-"+ao.RATE_REF,Be.PITCH_KEY="tts-"+ao.PITCH_REF,Be.VOLUME_KEY="tts-"+ao.VOLUME_REF,Be.VOICE_KEY="tts-"+ao.VOICE_REF;var ng=class{constructor(t,n,r){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=r,this.initialise()}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialTTSSettings){let r=t.initialTTSSettings;r?.rate&&(n.rate=r.rate,Kn.default.log(n.rate)),r?.pitch&&(n.pitch=r.pitch,Kn.default.log(n.pitch)),r?.volume&&(n.volume=r.volume,Kn.default.log(n.volume)),r?.color&&(n.color=r.color,Kn.default.log(n.color)),r?.autoScroll&&(n.autoScroll=r.autoScroll,Kn.default.log(n.autoScroll)),r?.voice&&(n.voice=r.voice,Kn.default.log(n.voice))}return n.initializeSelections(),n}stop(){Kn.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(Be.AUTO_SCROLL_KEY)!=null?this.getProperty(Be.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(Be.RATE_KEY)!=null?this.getProperty(Be.RATE_KEY).value:this.rate,this.pitch=this.getProperty(Be.PITCH_KEY)!=null?this.getProperty(Be.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(Be.VOLUME_KEY)!=null?this.getProperty(Be.VOLUME_KEY).value:this.volume,this.color=this.getProperty(Be.COLOR_KEY)!=null?this.getProperty(Be.COLOR_KEY).value:this.color,this.voice=this.getProperty(Be.VOICE_REF)!=null?this.getProperty(Be.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=de(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechRate=de(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=de(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=de(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=de(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),ne(de(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(Be.RATE_REF)?.value,pitch:this.userProperties.getByRef(Be.PITCH_REF)?.value,volume:this.userProperties.getByRef(Be.VOLUME_REF)?.value,voice:this.userProperties.getByRef(Be.VOLUME_REF)?.value,color:this.userProperties.getByRef(Be.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Be.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{Kn.default.log("api updated tts settings",n)})}getTTSSettings(){var t=new Si;return t.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,Be.AUTO_SCROLL_REF,Be.AUTO_SCROLL_KEY),t.addIncremental(this.rate,.1,10,.1,"",Be.RATE_REF,Be.RATE_KEY),t.addIncremental(this.pitch,.1,2,.1,"",Be.PITCH_REF,Be.PITCH_KEY),t.addIncremental(this.volume,.1,1,.1,"",Be.VOLUME_REF,Be.VOLUME_KEY),t.addStringable(this.color,Be.COLOR_REF,Be.COLOR_KEY),t.addJSONable(JSON.stringify(this.voice),Be.VOICE_REF,Be.VOICE_KEY),t}saveProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let r=JSON.parse(n);r=r.filter(o=>o.name!==t.name),r.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(r))}else{let r=[];r.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(r))}return t}getProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let r=JSON.parse(n);return r=r.filter(o=>o.name===t),r.length===0?void 0:r[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(t){if(t.rate){Kn.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Be.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.pitch){Kn.default.log("pitch "+this.pitch),this.pitch=t.pitch;let n=this.userProperties.getByRef(Be.PITCH_REF);n&&(n.value=this.pitch,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.volume){Kn.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Be.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(Be.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){Kn.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Be.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.voice){Kn.default.log("voice "+this.voice),this.voice=t.voice;let n=this.userProperties.getByRef(Be.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,r=t.indexOf(":")!==-1?t.slice(t.indexOf(":")+1):t;n!==void 0&&r!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:n,lang:r}}):r!==void 0&&n===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:r}})}increase(t){if(t==="rate"){this.userProperties.getByRef(Be.RATE_REF).increment();let n=this.userProperties.getByRef(Be.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(Be.PITCH_REF).increment();let n=this.userProperties.getByRef(Be.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(Be.VOLUME_REF).increment();let n=this.userProperties.getByRef(Be.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}decrease(t){if(t==="rate"){this.userProperties.getByRef(Be.RATE_REF).decrement();let n=this.userProperties.getByRef(Be.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(Be.PITCH_REF).decrement();let n=this.userProperties.getByRef(Be.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(Be.VOLUME_REF).decrement();let n=this.userProperties.getByRef(Be.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}};C();C();var _3=`${$r.loading}`,T3=`
75
+ </svg>`,$r={error:Gn("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:Gn("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:O8("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:Gn("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:Gn("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:Gn("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:Gn("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:Gn("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:Gn("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:Gn("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:Gn("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:Gn("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:Gn("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:Gn("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:Gn("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 p0=Je(Ed());var Mn=Je(Dt()),Re;(function(d){d.R2_ID_HIGHLIGHTS_CONTAINER="R2_ID_HIGHLIGHTS_CONTAINER",d.R2_ID_BOOKMAKRS_CONTAINER="R2_ID_BOOKMAKRS_CONTAINER",d.R2_ID_READALOUD_CONTAINER="R2_ID_READALOUD_CONTAINER",d.R2_ID_PAGEBREAK_CONTAINER="R2_ID_PAGEBREAK_CONTAINER",d.R2_ID_SEARCH_CONTAINER="R2_ID_SEARCH_CONTAINER",d.R2_ID_DEFINITIONS_CONTAINER="R2_ID_DEFINITIONS_CONTAINER",d.R2_ID_LINEFOCUS_CONTAINER="R2_ID_LINEFOCUS_CONTAINER",d.R2_ID_GUTTER_RIGHT_CONTAINER="R2_ID_GUTTER_RIGHT_CONTAINER"})(Re||(Re={}));var x4="R2_CLASS_HIGHLIGHT_CONTAINER",Ya="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",hn="R2_CLASS_HIGHLIGHT_AREA",Za="R2_CLASS_HIGHLIGHT_ICON",ii=.5,_4=.75,Fo={blue:100,green:50,red:230},zt=[],x8="data-highlighted",_8="data-timestamp",qs={ELEMENT_NODE:1,TEXT_NODE:3},to=[Re.R2_ID_HIGHLIGHTS_CONTAINER,Re.R2_ID_PAGEBREAK_CONTAINER,Re.R2_ID_SEARCH_CONTAINER,Re.R2_ID_READALOUD_CONTAINER,Re.R2_ID_BOOKMAKRS_CONTAINER,Re.R2_ID_DEFINITIONS_CONTAINER,Re.R2_ID_LINEFOCUS_CONTAINER,Re.R2_ID_GUTTER_RIGHT_CONTAINER,x4,hn,Ya],g0=-1,m0=-1,De=class{constructor(t,n,r,o,a,l){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.showTool=(0,Ka.debounce)(t=>{this.isAndroid()||this.snapSelectionToWord(t),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,Ka.debounce)(()=>{this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen(),this.delegate.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,Ka.debounce)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.delegate.emit("toolbox.closed","closed"))},100);this.selection=(0,Ka.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=r,this.api=l,this.hasEventListener=o,this.options=this.defaults(a,{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(r=>r(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(),g0=-1,m0=-1;let n=this;async function r(){n.lastSelectedHighlight===void 0||(n.lastSelectedHighlight=void 0)}setTimeout(async()=>{let o=this.delegate.iframes[0].contentDocument;o&&await o.body?.addEventListener("click",r)},100)}haveSameColor(t,n){return this.dom(t).color()===this.dom(n).color()}defaults(t,n){t=t||{};for(let r in n)n.hasOwnProperty(r)&&t[r]===void 0&&(t[r]=n[r]);return t}unique(t){return t.filter(function(n,r,o){return o.indexOf(n)===r})}refineRangeBoundaries(t){let n=t.startContainer,r=t.endContainer,o=t.commonAncestorContainer,a=!0;if(t.endOffset===0){for(;!r.previousSibling&&r.parentNode!==o;)r=r.parentNode;r=r.previousSibling}else r.nodeType===qs.TEXT_NODE?t.endOffset<r.nodeValue.length&&r.splitText(t.endOffset):t.endOffset>0&&(r=r.childNodes.item(t.endOffset-1));return n.nodeType===qs.TEXT_NODE?t.startOffset===n.nodeValue.length?a=!1:t.startOffset>0&&(n=n.splitText(t.startOffset),r===n.previousSibling&&(r=n)):t.startOffset<n.childNodes.length?n=n.childNodes.item(t.startOffset):n=n.nextSibling,{startContainer:n,endContainer:r,goDeeper:a}}sortByDepth(t,n){let r=this;t.sort(function(o,a){return r.dom(n?a:o).parents().length-r.dom(n?o:a).parents().length})}groupHighlights(t){let n=[],r={},o=[];return t.forEach(function(a){let l=a.getAttribute(_8);typeof r[l]=="undefined"&&(r[l]=[],n.push(l)),r[l].push(a)}),n.forEach(function(a){let l=r[a];o.push({chunks:l,timestamp:a,toString:function(){return l.map(function(u){return u.textContent}).join("")}})}),o}dom(t){let n=this;return{addClass:function(r){t.classList?t.classList.add(r):t.className+=" "+r},removeClass:function(r){t.classList?t.classList.remove(r):t.className=t.className.replace(new RegExp("(^|\\b)"+r+"(\\b|$)","gi")," ")},prepend:function(r){let o=Array.prototype.slice.call(r),a=o.length;for(;a--;)t.insertBefore(o[a],t.firstChild)},append:function(r){let o=Array.prototype.slice.call(r);for(let a=0,l=o.length;a<l;++a)t.appendChild(o[a])},insertAfter:function(r){return r.parentNode?.insertBefore(t,r.nextSibling)},insertBefore:function(r){return r.parentNode?.insertBefore(t,r)},remove:function(){t.parentNode.removeChild(t),t=null},contains:function(r){return t!==r&&t.contains(r)},wrap:function(r){return t.parentNode&&t.parentNode.insertBefore(r,t),r.appendChild(t),r},unwrap:function(){let r=Array.prototype.slice.call(t.childNodes),o;return r.forEach(function(a){o=a.parentNode,n.dom(a).insertBefore(a.parentNode),n.dom(o).remove()}),r},parents:function(){let r,o=[];for(;r=t.parentNode;)o.push(r),t=r;return o},normalizeTextNodes:function(){if(!!t){if(t.nodeType===qs.TEXT_NODE)for(;t.nextSibling&&t.nextSibling.nodeType===qs.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(r){let o=document.createElement("div");return o.innerHTML=r,o.childNodes},getRange:function(){let r=n.dom(t)?.getSelection(),o;return r?.rangeCount>0&&(o=r?.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,r){let o=t.ownerDocument;t.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),o.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),o.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),r||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){g0=t.clientX,m0=t.clientY}async mouseup(t){Math.abs(g0-t.clientX)<3&&Math.abs(m0-t.clientY)<3&&await this.processMouseEvent(t)}async mousemove(t){await this.processMouseEvent(t)}unbindEvents(t,n){let r=t.ownerDocument;t.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),r.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),r.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),r.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"),r=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],o=document.getElementById("colorIcon"),a=document.getElementById("actionIcon"),l=document.getElementById("dismissIcon"),u=document.getElementById("collapseIcon"),d=document.getElementById("highlightIcon"),f=this;if(l&&(l.innerHTML=$r.close,l.addEventListener("click",function(){f.toolboxMode("add")})),u&&(u.innerHTML=$r.close,u.addEventListener("click",function(){f.toolboxMode("add")})),o){o.style.position="relative",o.style.zIndex="20",r.forEach(v=>{let S=document.getElementById(v),w=document.getElementById(`c${v}`);S&&t?.contains(S)&&t.removeChild(S),n&&w&&n.contains(w)&&n.removeChild(w)});let g=[],y=[];if(o.addEventListener("click",function(){f.toolboxMode("colors")}),this.delegate.rights.enableAnnotations){let v=10;r.forEach(S=>{v--;let w=o?.cloneNode(!0),b=w.lastChild,m=De.hexToRgbChannels(S);b.style.backgroundColor="rgba("+[m.red,m.green,m.blue].join(",")+",.5)",w.id=`c${S}`,w.style.display="unset",w.style.position="relative",w.style.zIndex=`${v}`,w.style.marginLeft="-30px",y.push(w),n?.insertBefore(w,d)})}r.forEach(v=>{let S=o?.cloneNode(!0),w=S.lastChild;w.style.backgroundColor=v,S.id=v,S.style.position="relative",S.style.display="unset",g.push(S),o&&S.addEventListener("click",function(){f.setColor(v);let b=o?.lastChild;b&&(b.style.backgroundColor=v);let m=document.getElementById("highlightIcon"),E=document.getElementById("underlineIcon"),O=document.getElementById("noteIcon");(m?.getElementsByTagName?.("span").length??0)>0&&((m?.getElementsByTagName("span")[0]).style.background=f.getColor()),(E?.getElementsByTagName?.("span").length??0)>0&&((E?.getElementsByTagName("span")[0]).style.borderBottomColor=f.getColor()),(O?.getElementsByTagName?.("span").length??0)>0&&((O?.getElementsByTagName("span")[0]).style.borderBottomColor=f.getColor()),f.toolboxMode("add")}),t?.insertBefore(S,l)})}a&&a.addEventListener("click",function(){f.toolboxMode("action")}),f.toolboxMode("add")}toolboxMode(t){let n=document.getElementById("highlight-toolbox-mode-colors"),r=document.getElementById("highlight-toolbox-mode-add"),o=document.getElementById("highlight-toolbox-mode-edit"),a=document.getElementById("highlight-toolbox-mode-action");switch(t){case"colors":n&&(n.style.display="unset"),r&&(r.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="none");break;case"edit":n&&(n.style.display="none"),r&&(r.style.display="none"),o&&(o.style.display="unset"),a&&(a.style.display="none");break;case"action":n&&(n.style.display="none"),r&&(r.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="unset");break;default:n&&(n.style.display="none"),r&&(r.style.display="unset"),o&&(o.style.display="none"),a&&(a.style.display="none");break}}toolboxHide(){let t=document.getElementById("highlight-toolbox");t&&(t.style.display="none"),this.selectionMenuClosed()}toolboxShowDelayed(t){this.showTool(t.detail===1)}snapSelectionToWord(t=!1){let n=this,r=this.delegate.iframes[0].contentDocument;if(r){let a=n.dom(r.body)?.getSelection();if(n.dom(r.body)&&a&&!a?.isCollapsed){let f=function(m){let E=m.match(new RegExp("[^a-zA-Z0-9]+$"));return!E||!E.index?m:m.slice(0,E.index)},l=a.toString(),u=l.length-l.trimStart().length,d=l.length-l.trimEnd().length,g=l.length;var o=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;l=l.replace(o,""),u=g-l.trimStart().length,l=f(l),d=g-l.trimEnd().length;let y=document.createRange();t?(y.setStart(a.anchorNode,a.anchorOffset+u),y.setEnd(a.focusNode,a.focusOffset-d)):(y.setStart(a.anchorNode,a.anchorOffset),y.setEnd(a.focusNode,a.focusOffset));let v=y.collapsed;y.detach();let S=a.focusNode,w;t?(w=a.focusOffset-d,a.collapse(a.anchorNode,a.anchorOffset+u)):(w=a.focusOffset,a.collapse(a.anchorNode,a.anchorOffset));let b=["forward","backward"];v&&(b=["backward","forward"]),t?(a.modify("move",b[0],"character"),a.modify("move",b[1],"word"),a.extend(S,w),a.modify("extend",b[1],"character"),a.modify("extend",b[0],"word")):a.extend(S,w),this.selection(a.toString(),a)}return a}}toolboxShow(){if(this.activeAnnotationMarkerId===void 0){let t=this,n=document.getElementById("highlight-toolbox-mode-add"),r=this.dom(this.delegate.iframes[0].contentDocument?.body).getRange();if((!r||r.collapsed)&&n){getComputedStyle(n).display!=="none"&&t.toolboxHide();return}this.isIOS()&&setTimeout(function(){let o=t.delegate.iframes[0].contentDocument;if(o){let a=t.dom(o.body).getSelection();a.removeAllRanges(),setTimeout(function(){a.addRange(r);function l(f){let g={className:v=>to.indexOf(v)<0,idName:v=>to.indexOf(v)<0},y=t.delegate.iframes[0].contentDocument;if(y)return Rn(f,y,g)}let u=t.delegate.iframes[0].contentWindow,d=Do(u,l);t.delegate.annotationModule?.annotator?.saveTemporarySelectionInfo(d)},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(),r=document.getElementById("highlight-toolbox");r&&(this.delegate.view?.isPaginated()?r.style.top=n.top+(this.delegate.attributes?.navHeight??0)+"px":r.style.top=n.top+"px",r.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 r=this;r.toolboxMode("add");let o=document.getElementById("highlightIcon"),a=document.getElementById("collapseIcon"),l=document.getElementById("underlineIcon"),u=document.getElementById("noteIcon"),d=document.getElementById("colorIcon"),f=document.getElementById("speakIcon");if(this.delegate.rights.enableAnnotations){if(o&&(o.style.display="unset",d&&o.getElementsByTagName("span").length>0&&(o.getElementsByTagName("span")[0].style.background=this.getColor())),l&&(l.style.display="unset",d&&l.getElementsByTagName("span").length>0&&(l.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),u&&(u.style.display="unset",d&&u.getElementsByTagName("span").length>0&&(u.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),d){d.style.display="unset";let g=d.lastChild;g.style.backgroundColor=this.getColor()}if(o){let g=function(){r.doHighlight(!1,Le.Highlight),r.toolboxHide(),o?.removeEventListener("click",g)},y=o.cloneNode(!0);o?.parentNode?.replaceChild(y,o),o=document.getElementById("highlightIcon"),o?.addEventListener("click",g)}if(l){let g=function(){r.doHighlight(!1,Le.Underline),r.toolboxHide(),l?.removeEventListener("click",g)},y=l.cloneNode(!0);l?.parentNode?.replaceChild(y,l),l=document.getElementById("underlineIcon"),l?.addEventListener("click",g)}if(u){let g=function(){r.doHighlight(!1,Le.Comment),r.toolboxHide(),u?.removeEventListener("click",g)},y=u.cloneNode(!0);u?.parentNode?.replaceChild(y,u),u=document.getElementById("noteIcon"),u?.addEventListener("click",g)}}else o&&o.style.setProperty("display","none"),l&&l.style.setProperty("display","none"),u&&u.style.setProperty("display","none"),d&&d.style.setProperty("display","none"),a&&a.style.setProperty("display","none");if(this.delegate.rights.enableTTS){if(f){let g=function(){f?.removeEventListener("click",g),r.speak()},y=f.cloneNode(!0);f?.parentNode?.replaceChild(y,f),f=document.getElementById("speakIcon"),f?.addEventListener("click",g)}}else f&&f.style.setProperty("display","none");(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).forEach(g=>{g.icon&&(g.icon.id=g.id);let y=document.getElementById(g.id),v=this;function S(){y?.removeEventListener("click",S);function w(m){let E={className:_=>to.indexOf(_)<0,idName:_=>to.indexOf(_)<0},O=v.delegate.iframes[0].contentDocument;if(O)return Rn(m,O,E)}let b=v.delegate.iframes[0].contentWindow;if(b){let m=Do(b,w);if(m===void 0){let E=v.delegate.iframes[0].contentDocument;m=v.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(E)}if(m!==void 0)if(g.callback)g.callback(m.cleanText,m.range?.startContainer.parentElement);else{let E=g.highlight?.style,O=g.marker?g.marker:Le.Custom;if(O===Le.Custom&&v.delegate.rights.enableAnnotations||O===Le.Bookmark&&v.delegate.rights.enableBookmarks){let _=v.delegate.iframes[0].contentDocument;if(_){let A=v.createHighlight(v.dom(_.body).getWindow(),m,g.highlight?.color,!0,O,g.icon,g.popup,E);v.options.onAfterHighlight(A,O),v.delegate.rights.enableAnnotations?v.delegate.annotationModule?.saveAnnotation(A[0]).then(T=>{g?.note&&T.highlight&&v.delegate.annotationModule?.api?.addCommentToAnnotation(T).then(M=>{v.delegate.annotationModule?.updateAnnotation(M).then(async()=>{Mn.default.log("update highlight "+M.id)})})}):v.delegate.rights.enableBookmarks&&v.delegate.bookmarkModule?.saveAnnotation(A[0])}}}}v.callbackComplete()}if(y){let w=y.cloneNode(!0);y?.parentNode?.replaceChild(w,y),y=document.getElementById(g.id),y?.addEventListener("click",S)}})}}doHighlight(t,n){let r=this;function o(l){let u={className:f=>to.indexOf(f)<0,idName:f=>to.indexOf(f)<0},d=r.delegate.iframes[0].contentDocument;if(d)return Rn(l,d,u)}let a=r.delegate.iframes[0].contentWindow;if(a){let l=Do(a,o);if(l===void 0){let u=r.delegate.iframes[0].contentDocument;l=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(u)}if(l){if(this.options.onBeforeHighlight(l)===!0){let u;u=this.getColor(),De.isHexColor(u)&&(u=De.hexToRgbChannels(u));let d=r.delegate.iframes[0].contentDocument;if(d){let f=this.createHighlight(r.dom(d.body).getWindow(),l,u,!0,n??Le.Highlight);this.options.onAfterHighlight(f,n),this.delegate.rights.enableAnnotations&&n!==Le.Bookmark?this.delegate.annotationModule?.saveAnnotation(f[0]):this.delegate.rights.enableBookmarks&&n===Le.Bookmark&&this.delegate.bookmarkModule?.saveAnnotation(f[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(l){let u={className:f=>to.indexOf(f)<0,idName:f=>to.indexOf(f)<0},d=t.delegate.iframes[0].contentDocument;if(d)return Rn(l,d,u)},t=this,r=t.delegate.iframes[0].contentWindow;if(r){let l=Do(r,n);if(l===void 0){let u=t.delegate.iframes[0].contentDocument;l=t.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(u)}l!==void 0&&this.delegate.ttsModule.speak(l,!0,()=>{})}let o=t.delegate.iframes[0].contentDocument;o&&t.dom(o.body).getSelection().removeAllRanges();let a=document.getElementById("highlight-toolbox");a&&(a.style.display="none"),this.selectionMenuClosed()}}stopReadAloud(){this.delegate.rights.enableTTS&&this.doneSpeaking()}callbackComplete(){this.toolboxHide();let t=this.delegate.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges()}isOutsideViewport(t){let n=dt(document,"#iframe-wrapper"),r=n.scrollLeft,o=r+n.clientWidth,a=t.left+t.width,l=t.top+t.height,u=n.scrollTop,d=u+n.clientHeight,f=l<u,g=t.top>d,y=a<r,v=t.left>o;return f||g||y||v}isInsideViewport(t){let n=dt(document,"#iframe-wrapper"),r=n.scrollTop,o=r+n.clientHeight,a=t.top+20>=r,l=t.top<=o,u=n.scrollLeft,d=u+n.clientWidth,f=t.left+t.width,g=t.left>u,y=f<d;return a&&l&&g&&y}get visibleTextRects(){let t=this.delegate.iframes[0].contentDocument;if(t){let r=function(u,d=[]){let f=u.firstChild;for(;f;)f.nodeType===1&&r(f,d),f.nodeType===3&&f.textContent?.trim()&&d.push(f),f=f.nextSibling;return d},o=function(u){return r(u).map(f=>{let{top:g,height:y,left:v,width:S}=a(f);return{top:g,height:y,width:S,left:v,node:f,textContent:f.textContent??""}})},a=function(u){try{let d=document.createRange();d.selectNode(u);let f=d.getBoundingClientRect();return d.detach(),f}catch(d){Mn.default.log("measureTextNode "+d),Mn.default.log("measureTextNode "+u),Mn.default.log(`${u.textContent}`)}},n=Oi(t,"body");return o(n).filter(u=>this.isInsideViewport(u))}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.ttsModule.cancel(),t&&this.delegate.reload()}}normalizeHighlights(t){var n;return n=t.filter(function(r){return r.parentElement?r:null}),n=this.unique(n),n.sort(function(r,o){return r.offsetTop-o.offsetTop||r.offsetLeft-o.offsetLeft}),n}flattenNestedHighlights(t){let n,r=this;r.sortByDepth(t,!0);function o(){let a=!1;return t.forEach(function(l,u){let d=l.parentElement,f=d.previousSibling,g=d.nextSibling;r.isHighlight(d)&&(r.haveSameColor(d,l)?(d.replaceChild(l.firstChild,l),t[u]=d,a=!0):(l.nextSibling||(r.dom(l).insertBefore(g||d),a=!0),l.previousSibling||(r.dom(l).insertAfter(f||d),a=!0),d.hasChildNodes()||r.dom(d).remove()))}),a}do n=o();while(n)}mergeSiblingHighlights(t){let n=this;function r(o,a){return a&&a.nodeType===qs.ELEMENT_NODE&&n.haveSameColor(o,a)&&n.isHighlight(a)}t.forEach(function(o){let a=o.previousSibling,l=o.nextSibling;r(o,a)&&(n.dom(o).prepend(a.childNodes),n.dom(a).remove()),r(o,l)&&(n.dom(o).append(l.childNodes),n.dom(l).remove()),n.dom(o).normalizeTextNodes()})}setColor(t){this.options.color=t}getColor(){return this.options.color}isHighlight(t){return t&&t.nodeType===qs.ELEMENT_NODE&&t.hasAttribute(x8)}createWrapper(){let t=document.createElement("mark");return t.style.background="linear-gradient("+De.hexToRgbA(this.options.color)+", "+De.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 r=t;return"rgba("+[r.red,r.green,r.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(t,n){let r;if(this.isHexColor(t))return r=this.hexToRgbChannels(t),"rgba("+[r.red,r.green,r.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 r=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 a=zt.find(l=>l.id===o);if(a){if(a.marker===Le.Custom||a.marker===Le.Bookmark)if(a.style?.hover){if(a.style?.hover)for(let d=0;d<a.style?.hover?.length;d++){let f=a.style?.hover[d];t.style.removeProperty(f.property)}let u="";if(a.style?.default)for(let d=0;d<a.style?.default?.length;d++){let f=a.style?.default[d];t.style.removeProperty(f.property),u+=`${f.property}: ${f.value} !${f.priority};`}t.setAttribute("style",`${t.getAttribute("style")}; ${u}`)}else if(a.style?.hoverClass){a.style?.hoverClass&&t.classList.remove(a.style?.hoverClass);let u="";a.style?.defaultClass&&t.classList.add(a.style?.defaultClass),t.setAttribute("style",`${t.getAttribute("style")}; ${u}`)}else if(De.isHexColor(a.color)){let u=De.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${0})`,"important")}else t.classList.remove("hover");else if(a.marker===Le.Underline||a.marker===Le.Comment)if(typeof a.color=="object"){let u=a.color;t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${u.red}, ${u.green}, ${u.blue}, ${1})`,"important")}else if(De.isHexColor(a.color)){let u=De.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${u.red}, ${u.green}, ${u.blue}, ${1})`,"important")}else t.classList.remove("hover");else if(typeof a.color=="object"){let u=a.color;t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${ii})`,"important")}else if(De.isHexColor(a.color)){let u=De.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${ii})`,"important")}else t.classList.remove("hover");let l;if(r){let u=r.getElementById(n);u&&(l=u.querySelector(`#${a.id}`))}if(l){let u=l.getElementsByClassName(Za);if(u.length>0){let d=u.item(0).getElementsByClassName("icon-tooltip");d.length>0&&d.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(t,n,r){for(let o of n){if(r.marker===Le.Custom||r.marker===Le.Bookmark)if(r.style?.hover){if(r.style?.default)for(let l=0;l<r.style?.default?.length;l++){let u=r.style?.default[l];o.style.removeProperty(u.property)}let a="";for(let l=0;l<r.style?.hover?.length;l++){let u=r.style?.hover[l];o.style.removeProperty(u.property),a+=`${u.property}: ${u.value} !${u.priority};`}o.setAttribute("style",`${o.getAttribute("style")}; ${a}`)}else if(r.style?.hoverClass){r.style?.defaultClass&&o.classList.remove(r.style?.defaultClass);let a="";o.classList.add(r.style?.hoverClass),o.setAttribute("style",`${o.getAttribute("style")}; ${a}`)}else if(De.isHexColor(r.color)){let a=De.hexToRgbChannels(r.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important")}else o.classList.add("hover");else if(r.marker===Le.Underline||r.marker===Le.Comment)if(typeof r.color=="object"){let a=r.color;o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, ${1})`,"important")}else if(De.isHexColor(r.color)){let a=De.hexToRgbChannels(r.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, ${1})`,"important")}else o.classList.add("hover");else if(typeof r.color=="object"){let a=r.color;o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${_4})`,"important")}else if(De.isHexColor(r.color)){let a=De.hexToRgbChannels(r.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${_4})`,"important")}else o.classList.add("hover");if(r.type!==qe.Definition){let l=t.getElementById(Re.R2_ID_HIGHLIGHTS_CONTAINER).querySelector(`#${r.id}`).getElementsByClassName(Za);if(l.length>0){let u=l.item(0).getElementsByClassName("icon-tooltip");u.length>0&&u.item(0).style.setProperty("display","block")}}}}setAndResetSearchHighlight(t,n){let r=this.delegate.iframes[0].contentWindow?.document,o=Array.from(r.getElementById(Re.R2_ID_SEARCH_CONTAINER).querySelectorAll(`.${hn}`));for(let a of o){let l=a,u=l.parentNode&&l.parentNode.nodeType===Node.ELEMENT_NODE&&l.parentNode.getAttribute?l.parentNode.getAttribute("id"):void 0;if(n.forEach(d=>{if(u===d.id&&d){if(typeof d.color=="object"){let y=d.color;l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${ii})`,"important")}else if(De.isHexColor(d.color)){let y=De.hexToRgbChannels(d.color);l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${ii})`,"important")}else l.classList.remove("hover");let g=r.getElementById(Re.R2_ID_SEARCH_CONTAINER).querySelector(`#${d.id}`).getElementsByClassName(Za);if(g.length>0){let y=g.item(0).getElementsByClassName("icon-tooltip");y.length>0&&y.item(0).style.removeProperty("display")}}}),u===t.id&&t){if(typeof t.color=="object"){let g=t.color;l.style.setProperty("background-color",`rgba(${g.red}, ${g.green}, ${g.blue}, ${ii})`,"important")}else if(De.isHexColor(t.color)){let g=De.hexToRgbChannels(t.color);l.style.setProperty("background-color",`rgba(${g.red}, ${g.green}, ${g.blue}, ${ii})`,"important")}else l.classList.remove("hover");let f=r.getElementById(Re.R2_ID_SEARCH_CONTAINER).querySelector(`#${t.id}`).getElementsByClassName(Za);if(f.length>0){let g=f.item(0).getElementsByClassName("icon-tooltip");g.length>0&&g.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,r=t.clientX,o=t.clientY;if(!n||!n.getElementById(Re.R2_ID_HIGHLIGHTS_CONTAINER)&&!n.getElementById(Re.R2_ID_SEARCH_CONTAINER)&&!n.getElementById(Re.R2_ID_PAGEBREAK_CONTAINER)&&!n.getElementById(Re.R2_ID_READALOUD_CONTAINER)&&!n.getElementById(Re.R2_ID_DEFINITIONS_CONTAINER))return;let a=this.delegate.view?.isPaginated(),l=n.body.getBoundingClientRect(),u=this.getScrollingElement(n),d=a?-u.scrollLeft:l.left,f=a?-u.scrollTop:l.top,g,y;for(let v=zt.length-1;v>=0;v--){let S=zt[v],w=n.getElementById(`${S.id}`);if(!w){let E=n.getElementById(Re.R2_ID_HIGHLIGHTS_CONTAINER);E&&(w=E.querySelector(`#${S.id}`))}if(!w)continue;let b=!1,m=w.querySelectorAll(`.${hn}`);for(let E of m){let O=E,_=O.rect.left+d,A=O.rect.top+f;if(r>=_&&r<_+O.rect.width&&o>=A&&o<A+O.rect.height){b=!0;break}}if(b){g=S,y=w;break}}if(!g||!y){for(let v in Re){let S=n.getElementById(v);if(S){let w=S.querySelectorAll(`.${Ya}`);for(let m of w)this.resetHighlightBoundingStyle(m);let b=Array.from(S.querySelectorAll(`.${hn}`));for(let m of b)this.resetHighlightAreaStyle(m,v)}}return}if(y.getAttribute("data-click")){if((t.type==="mousemove"||t.type==="touchmove")&&y.parentElement?.style.display!=="none"){let v=Array.from(y.querySelectorAll(`.${hn}`));for(let w in Re){let b=n.getElementById(w);if(b){let m=b.querySelectorAll(`.${hn}`);for(let E of m)v.indexOf(E)<0&&this.resetHighlightAreaStyle(E,w)}}this.setHighlightAreaStyle(n,v,g);let S=y.querySelector(`.${Ya}`);for(let w in Re){let b=n.getElementById(w);if(b){let m=b.querySelectorAll(`.${Ya}`);for(let E of m)(!S||E!==S)&&this.resetHighlightBoundingStyle(E)}}}else if((t.type==="mouseup"||t.type==="click"||t.type==="touchup")&&y.parentElement?.style.display!=="none"){let v={highlight:g};Mn.default.log(JSON.stringify(v));let S=this,w;if(S.delegate.rights.enableAnnotations?w=await this.delegate.annotationModule?.getAnnotation(v.highlight):S.delegate.rights.enableBookmarks&&(w=await this.delegate.bookmarkModule?.getAnnotation(v.highlight)),v.highlight.type===qe.Annotation&&this.delegate.annotationModule?.api?.selectedAnnotation(w).then(async()=>{}),w?.id){Mn.default.log("selected highlight "+w.id),S.lastSelectedHighlight=w.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 O=function(){S.delegate.annotationModule?.api?.addCommentToAnnotation(w).then(P=>{S.delegate.annotationModule?.updateAnnotation(P).then(async()=>{Mn.default.log("update highlight "+P.id),b&&(b.style.display="none"),S.selectionMenuClosed()}),b&&(b.style.display="none"),S.selectionMenuClosed(),_?.removeEventListener("click",O,!1)})},T=function(){S.delegate.rights.enableAnnotations?S.delegate.annotationModule?.deleteSelectedHighlight(w).then(async()=>{Mn.default.log("delete highlight "+w.id),b&&(b.style.display="none"),S.selectionMenuClosed()}):S.delegate.rights.enableBookmarks&&S.delegate.bookmarkModule?.deleteSelectedHighlight(w).then(async()=>{Mn.default.log("delete highlight "+w.id),b&&(b.style.display="none"),S.selectionMenuClosed()})};b.style.display="block",this.toolboxMode("edit");let m=document.getElementById("colorIcon"),E=document.getElementById("highlightIcon");m&&(m.style.display="none"),E&&(E.style.display="none");let _=document.getElementById("commentIcon"),A=document.getElementById("cloneCommentIcon");if(A){let P=A.parentElement;P&&P.removeChild(A)}if(_){_.style.display="none";let P=_.cloneNode(!0),q=_.parentElement;P.style.display="unset",P.id="cloneCommentIcon",P.addEventListener("click",O,!1),q&&q.append(P)}let M=document.getElementById("deleteIcon"),j=document.getElementById("cloneDeleteIcon");if(j){let P=j.parentElement;P&&P.removeChild(j)}if(M){M.style.display="none";let P=M.cloneNode(!0),q=M.parentElement;P.style.display="unset",P.id="cloneDeleteIcon",P.addEventListener("click",T,!1),q&&q.append(P)}}else b.style.display="none",this.selectionMenuClosed(),b.offsetWidth,b.style.display="block"}else{y.dataset.definition&&new Va(this.delegate).showPopup(y.dataset.definition,t);let b=this.delegate.definitionsModule?.properties?.definitions?.filter(m=>m.order===Number(y?.dataset.order))[0];Mn.default.log(b),this.delegate.definitionsModule?.api?.click&&(this.delegate.definitionsModule.api?.click(p0.omit(b,"callbacks"),p0.omit(g,"definition")),this.delegate.emit("definition.click",b,g))}}}}async prepareContainers(t){for(let n in Re)await this.ensureHighlightsContainer(t,n)}async ensureHighlightsContainer(t,n){let r=t.document;if(!r.getElementById(n)){let o=r.createElement("div");o.setAttribute("id",n),n!==Re.R2_ID_GUTTER_RIGHT_CONTAINER&&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")),r.body&&r.body.append(o),(await this.layerSettings.getProperty(n))?.value===!1&&(o.style.display="none")}return r.getElementById(n)}hideAllhighlights(t){this.removeAllChildNodes(t.getElementById(Re.R2_ID_HIGHLIGHTS_CONTAINER)),this.removeAllChildNodes(t.getElementById(Re.R2_ID_SEARCH_CONTAINER)),this.removeAllChildNodes(t.getElementById(Re.R2_ID_READALOUD_CONTAINER)),this.removeAllChildNodes(t.getElementById(Re.R2_ID_PAGEBREAK_CONTAINER)),this.removeAllChildNodes(t.getElementById(Re.R2_ID_DEFINITIONS_CONTAINER))}destroyAllhighlights(t){this.hideAllhighlights(t),zt.splice(0,zt.length)}removeAllChildNodes(t){for(;t.firstChild;)t.removeChild(t.firstChild)}destroyHighlights(t){let n=this.delegate.iframes[0].contentWindow?.document;if(n){let r;switch(t){case qe.ReadAloud:r=n.getElementById(Re.R2_ID_READALOUD_CONTAINER),r&&this.removeAllChildNodes(r);break;case qe.Search:r=n.getElementById(Re.R2_ID_SEARCH_CONTAINER),r&&this.removeAllChildNodes(r);break;case qe.PageBreak:r=n.getElementById(Re.R2_ID_PAGEBREAK_CONTAINER),r&&this.removeAllChildNodes(r);break;case qe.Definition:r=n.getElementById(Re.R2_ID_DEFINITIONS_CONTAINER),r&&this.removeAllChildNodes(r);break;case qe.LineFocus:r=n.getElementById(Re.R2_ID_LINEFOCUS_CONTAINER),r&&this.removeAllChildNodes(r);break;case qe.Comment:r=n.getElementById(Re.R2_ID_GUTTER_RIGHT_CONTAINER),r&&this.removeAllChildNodes(r);break;default:r=n.getElementById(Re.R2_ID_HIGHLIGHTS_CONTAINER),r&&this.removeAllChildNodes(r),zt.splice(0,zt.length);break}}}destroyHighlight(t,n){if(!t)return;let r=-1;zt.find((l,u)=>(r=u,l.id===n))&&r>=0&&r<zt.length&&zt.splice(r,1);let a=t.getElementById(n);a&&this.removeAllChildNodes(a)}createHighlight(t,n,r,o,a,l,u,d,f,g){try{let y=`${n.rangeInfo.startContainerElementCssSelector}${n.rangeInfo.startContainerChildTextNodeIndex}${n.rangeInfo.startOffset}${n.rangeInfo.endContainerElementCssSelector}${n.rangeInfo.endContainerChildTextNodeIndex}${n.rangeInfo.endOffset}`,v=Tr.hash(y),S=(g||"R2_HIGHLIGHT_")+v;this.destroyHighlight(t.document,S);let w=`rgb(${Fo.red}, ${Fo.green}, ${Fo.blue})`,b={color:r||w,id:S,pointerInteraction:o,selectionInfo:n,marker:a,icon:l,popup:u,style:d,type:f||qe.Annotation};(f===qe.Annotation||f===qe.Definition||f===void 0)&&zt.push(b);let m=this.createHighlightDom(t,b);return b.position=parseInt((m?.hasChildNodes()?m.childNodes[0]:m).style.top.replace("px","")),[b,m]}catch(y){throw"Can't create highlight: "+y}}createHighlightDom(t,n){let r=t.document,o=vd(r,n.selectionInfo.rangeInfo);if(!o)return;for(let B in Re)this.ensureHighlightsContainer(t,B);let a=r.createElement("div");a.setAttribute("id",n.id),a.setAttribute("class",x4),a.style.setProperty("pointer-events","none"),n.pointerInteraction&&a.setAttribute("data-click","1");let l=this.delegate.view?.isPaginated();l?r.body.style.position="revert":r.body.style.position="relative";let u=r.body.getBoundingClientRect(),d=this.getScrollingElement(r),f=l?-d.scrollLeft:u.left,g=l?-d.scrollTop:u.top,y=1,v=!1,S=!1,m=yd(o,v||S||!1),E=3,O=2,_=3,A=0,T=24,M,j;for(let B of m){let N=r.createElement("div");N.setAttribute("class",hn),N.dataset.marker=""+n.marker;let W="";if(v&&n.marker!==Le.Custom&&n.marker!==Le.Bookmark&&n.marker!==Le.Comment){let V=n.color;De.isHexColor(V)&&(V=De.hexToRgbChannels(V)),W+=`border-bottom: ${O*y}px solid rgba(${V.red}, ${V.green}, ${V.blue}, ${ii}) !important`}if(n.marker===Le.Custom||n.marker===Le.Bookmark)if(n.style?.default){for(let V=0;V<n.style?.default?.length;V++){let Q=n.style?.default[V];W+=`${Q.property}: ${Q.value} !${Q.priority};`}N.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${E}px !important; ${W}`)}else n.style?.defaultClass&&(N.classList.add(n.style?.defaultClass),N.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${E}px !important; ${W}`));else if(n.marker===Le.Underline||n.marker===Le.Comment)if(typeof n.color=="object"){let V=n.color;N.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${E}px !important; background-color: rgba(${V.red}, ${V.green}, ${V.blue}, ${0}) !important; ${W}`),N.style.setProperty("border-bottom",`2px solid rgba(${V.red}, ${V.green}, ${V.blue}, ${1})`,"important")}else if(De.isHexColor(n.color)){let V=De.hexToRgbChannels(n.color);N.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${E}px !important; background-color: rgba(${V.red}, ${V.green}, ${V.blue}, ${0}) !important; ${W}`),N.style.setProperty("border-bottom",`2px solid rgba(${V.red}, ${V.green}, ${V.blue}, ${1})`,"important")}else N.setAttribute("style",`border-radius: ${E}px !important; ${W}`);else if(typeof n.color=="object"){let V=n.color;N.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${E}px !important; background-color: rgba(${V.red}, ${V.green}, ${V.blue}, ${ii}) !important; ${W}`)}else if(De.isHexColor(n.color)){let V=De.hexToRgbChannels(n.color);N.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${E}px !important; background-color: rgba(${V.red}, ${V.green}, ${V.blue}, ${ii}) !important; ${W}`)}else N.setAttribute("style",`border-radius: ${E}px !important; ${W}`);N.style.setProperty("pointer-events","none"),N.style.position="absolute",N.scale=y,N.rect={height:B.height,left:B.left-f,top:B.top-g,width:B.width},n.pointerInteraction&&(N.setAttribute("data-click","1"),N.tabIndex=0),N.style.width=`${N.rect.width*y}px`,N.style.height=`${N.rect.height*y}px`,N.style.left=`${N.rect.left*y}px`,N.style.top=`${N.rect.top*y}px`,a.append(N);let ye=parseInt(N.style.top.replace("px",""));if((ye<A||A===0)&&(A=ye),T=parseInt(N.style.height.replace("px","")),S){let V=r.createElement("div");V.setAttribute("class",hn);let Q=n.color;De.isHexColor(Q)&&(Q=De.hexToRgbChannels(Q)),V.setAttribute("style",`background-color: rgba(${Q.red}, ${Q.green}, ${Q.blue}, ${ii}) !important;`),V.style.setProperty("pointer-events","none"),V.style.position="absolute",V.scale=y,V.rect={height:B.height,left:B.left-f,top:B.top-g,width:B.width},V.style.width=`${V.rect.width*y}px`,V.style.height=`${_*y}px`,V.style.left=`${V.rect.left*y}px`,V.style.top=`${(V.rect.top+V.rect.height/2-_/2)*y}px`,a.append(V)}let be=this.delegate.iframes[0].contentWindow?.innerWidth,fe=parseInt(getComputedStyle(r.documentElement).getPropertyValue("column-count")),re=parseInt(getComputedStyle(r.documentElement).getPropertyValue("column-width")),he=parseInt(getComputedStyle(r.body).getPropertyValue("padding-left")),Ae=be/(fe||1);Ae<re&&(Ae=be),l||(Ae=parseInt(getComputedStyle(r.body).width.replace("px","")));let ue=this.delegate.settings.fontSize/100,Oe=20*ue;ue<=1&&(Oe=-60);let Ce=0*ue;ue<=1&&(Ce=-60),M=Math.floor(B.left/Ae)*Ae+Ae-(T<40?40:T)+Ce,j=Math.floor(B.left/Ae)*Ae+(T<40?40:T)-Oe;let Ee=parseInt(this.delegate.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));Ee>=2&&(j=j+he/fe,M=M-he/fe),l||(M=parseInt(getComputedStyle(this.delegate.iframes[0].contentDocument?.body).width.replace("px","")),j=parseInt(getComputedStyle(this.delegate.iframes[0].contentDocument?.body).width.replace("px",""))-Ae,Ee>=2&&(j=j+he/2,M=M-he/2))}let P=o.getBoundingClientRect(),q=r.createElement("div");q.setAttribute("class",Ya),q.style.setProperty("pointer-events","none"),q.style.position="absolute",q.scale=y,q.rect={height:P.height,left:P.left-f,top:P.top-g,width:P.width},q.style.width=`${q.rect.width*y}px`,q.style.height=`${q.rect.height*y}px`,q.style.left=`${q.rect.left*y}px`,q.style.top=`${q.rect.top*y}px`,a.append(q);let U=r.createElement("div");if(U.setAttribute("class",Za),n.icon?.position==="left")U.setAttribute("style",`position: absolute;top:${A}px;left:${j+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${T}px; width:${T}px;`);else if(n.icon?.position==="inline")U.setAttribute("style",`position: absolute;top:${A-T/2}px;left:${parseInt(q.style.left.replace("px",""))+parseInt(q.style.width.replace("px",""))-T/2}px;height:${T}px; width:${T}px;`);else if(n.icon?.position==="center"){let N=T/3*2;U.setAttribute("style",`position: absolute;top:${A}px;left:${parseInt(q.style.left.replace("px",""))+parseInt(q.style.width.replace("px",""))-N}px;height:${T}px; width:${T}px;`)}else n.note&&n.marker!==Le.Custom&&n.marker!==Le.Bookmark&&n.marker!==Le.Comment&&n.marker!==Le.Highlight&&n.marker!==Le.Underline?U.setAttribute("style",`position: absolute;top:${A-T/2}px;left:${parseInt(q.style.left.replace("px",""))+parseInt(q.style.width.replace("px",""))-T/2}px;height:${T}px; width:${T}px;`):n.note&&n.marker===Le.Comment||n.marker===Le.Highlight||n.marker===Le.Underline?U.setAttribute("style",`position: absolute;top:${A}px;left:${M+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${T}px; width:${T}px;`):U.setAttribute("style",`position: absolute;top:${A}px;left:${M+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${T}px; width:${T}px;`);if(n.marker===Le.Custom||n.marker===Le.Bookmark)n.icon?.class?(U.classList.add(n.icon?.class),U.id=n.icon?.id):n.icon?.svgPath?U.innerHTML=$s(`${n.icon?.id}`,`${n.icon?.title}`,`${n.icon?.svgPath}`,"icon open",T,`${n.icon?.color} !important`):n.icon?.title&&(U.innerHTML=n.icon?.title);else if(n.note){let B=n.color;De.isHexColor(B)&&(B=De.hexToRgbChannels(B)),n.marker===Le.Comment||n.marker===Le.Highlight||n.marker===Le.Underline?U.innerHTML=$s("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",T/2,`rgba(${B.red}, ${B.green}, ${B.blue}, 1) !important`):U.innerHTML=$s("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",T,`rgba(${B.red}, ${B.green}, ${B.blue}, 1) !important`)}U.style.setProperty("pointer-events","all");let k=this;if(n.type!==qe.PageBreak&&n.type!==qe.Definition&&U.addEventListener("click",async function(B){let N;k.delegate.rights.enableAnnotations?(N=await k.delegate.annotationModule?.getAnnotationByID(n.id),k.delegate.annotationModule?.api?.selectedAnnotation(N).then(async()=>{})):k.delegate.rights.enableBookmarks&&(N=await k.delegate.bookmarkModule?.getAnnotationByID(n.id)),Mn.default.log("selected highlight "+N.id),k.lastSelectedHighlight=N.id;let W=document.getElementById("highlight-toolbox");if(W)if(W.style.top=B.clientY+(k.delegate.attributes?.navHeight??0)+"px",W.style.left=B.clientX+"px",getComputedStyle(W).display==="none"){let re=function(){k.delegate.annotationModule?.api?.addCommentToAnnotation(N).then(Ee=>{k.delegate.annotationModule?.updateAnnotation(Ee).then(async()=>{Mn.default.log("update highlight "+Ee.id),W.style.display="none",k.selectionMenuClosed()}),W.style.display="none",k.selectionMenuClosed()})},ue=function(){k.delegate.rights.enableAnnotations?k.delegate.annotationModule?.deleteSelectedHighlight(N).then(async()=>{Mn.default.log("delete highlight "+N.id),W.style.display="none",k.selectionMenuClosed()}):k.delegate.rights.enableBookmarks&&k.delegate.bookmarkModule?.deleteSelectedHighlight(N).then(async()=>{Mn.default.log("delete highlight "+N.id),W.style.display="none",k.selectionMenuClosed()})};W.style.display="block",k.toolboxMode("edit");let be=document.getElementById("colorIcon"),fe=document.getElementById("highlightIcon");be&&(be.style.display="none"),fe&&(fe.style.display="none");let he=document.getElementById("commentIcon"),Ae=document.getElementById("cloneCommentIcon");if(Ae){let Ee=Ae.parentElement;Ee&&Ee.removeChild(Ae)}if(he){he.style.display="none";let Ee=he.cloneNode(!0),V=he.parentElement;Ee.style.display="unset",Ee.id="cloneCommentIcon",Ee.addEventListener("click",re,!1),V&&V.append(Ee)}let Oe=document.getElementById("deleteIcon"),Ce=document.getElementById("cloneDeleteIcon");if(Ce){let Ee=Ce.parentElement;Ee&&Ee.removeChild(Ce)}if(Oe){Oe.style.display="none";let Ee=Oe.cloneNode(!0),V=Oe.parentElement;Ee.style.display="unset",Ee.id="cloneDeleteIcon",Ee.addEventListener("click",ue,!1),V&&V.append(Ee)}}else W.style.display="none",k.selectionMenuClosed(),W.offsetWidth,W.style.display="block";let ye=Array.from(a.querySelectorAll(`.${hn}`));k.setHighlightAreaStyle(r,ye,n)}),n.note){let B=document.createElement("span");B.innerHTML=n.note,B.className="icon-tooltip",n.marker===Le.Custom||n.marker===Le.Bookmark?(n.popup?.background&&B.style.setProperty("background",n.popup.background),n.popup?.textColor&&B.style.setProperty("color",n.popup.textColor),n.popup?.class&&B.classList.add(n.popup.class)):(B.style.setProperty("background","lightyellow"),B.style.setProperty("color","black"))}switch((n.note||n.marker===Le.Custom||n.marker===Le.Bookmark)&&a.append(U),n.type){case qe.Search:r.getElementById(Re.R2_ID_SEARCH_CONTAINER).append(a);break;case qe.ReadAloud:r.getElementById(Re.R2_ID_READALOUD_CONTAINER).append(a);break;case qe.PageBreak:r.getElementById(Re.R2_ID_PAGEBREAK_CONTAINER).append(a);break;case qe.Definition:r.getElementById(Re.R2_ID_DEFINITIONS_CONTAINER).append(a);break;default:r.getElementById(Re.R2_ID_HIGHLIGHTS_CONTAINER).append(a);break}return a}addSelectionMenuItem(t){(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).push(t)}};var N4=Je(T0());C();var B8=Je(Dt());var no={className:i=>!0,idName:i=>!0,tagName:i=>!0};var H4=Je(Ed()),Cr=Je(Dt()),Qa=class{constructor(t,n,r,o,a,l,u,d,f){this.hide=de(document,"#menu-button-hide");this.show=de(document,"#menu-button-show");this.annotator=t,this.rights=n,this.publication=r,this.headerMenu=f,this.delegate=o,this.initialAnnotations=a,this.highlighter=u,this.properties=l,this.api=d}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(){Cr.default.log("Annotation module stop")}async start(){if(this.delegate.annotationModule=this,this.headerMenu&&(this.highlightsView=de(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=de(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=de(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()},200)}initialize(){return new Promise(async t=>{await document.fonts.ready,this.rights.enableAnnotations&&setTimeout(()=>{this.drawHighlights(),this.showHighlights(),ne(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(r=>r.id===this.activeAnnotationMarkerId);if(n&&n?.length>0){let r=H4.cloneDeep(n[0]);r.marker=Le.Custom,this.activeAnnotationMarkerPosition&&(r.icon.position=this.activeAnnotationMarkerPosition),r.highlight.style.default=null,r.highlight.style.hover=null;let o=this.delegate.iframes[0].contentDocument;if(o){let f=function(y){try{let v=d.delegate.iframes[0].contentDocument;return v?Rn(y,v,no):""}catch(v){return Cr.default.log("uniqueCssSelector:"),Cr.default.error(v),""}},a=this.highlighter?.dom(o.body).getSelection(),l=a.getRangeAt(0),u=a.anchorNode;l.setStart(u,l.startOffset),l.setEnd(u,l.endOffset+1),a.removeAllRanges(),a.addRange(l);let d=this,g=Ri(l,f);if(a.removeAllRanges(),g){let y={rangeInfo:g},v=this.delegate.highlighter?.createHighlight(this.delegate.highlighter?.dom(o.body).getWindow(),y,r.highlight.color,!0,Le.Bookmark,r.icon,r.popup,r.highlight.style);v&&this.saveAnnotation(v[0]).then(S=>{Cr.default.log("saved bookmark "+S.id)})}o.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(t){Cr.default.log("still need to scroll to "+t);var n=await this.annotator?.getAnnotationElement(t,this.delegate.iframes[0].contentWindow);n.scrollIntoView({block:"center",behavior:"smooth"})}async updateLocalHighlight(t){if(this.annotator){let n=await this.annotator.deleteAnnotation(t.id),r=await this.addAnnotation(t);return Cr.default.log("Highlight deleted "+JSON.stringify(n)),Cr.default.log("Highlight added "+JSON.stringify(r)),await this.showHighlights(),await this.drawHighlights(),r}else return new Promise(n=>n(null))}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return Cr.default.log("Highlight deleted "+JSON.stringify(n)),await this.showHighlights(),await this.drawHighlights(),n}else return new Promise(r=>r(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 r=this.delegate.view?.getCurrentPosition(),o=this.delegate.iframes[0].contentDocument;if(o){let a=Oi(o,"body"),l=t.position?t.position/a.scrollHeight:r,u=(0,N4.v4)(),d;if(n){let f=n.Href;if(f.indexOf("#")>0&&(f=f.slice(0,f.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let g=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),y=Math.ceil((l??0)*(g.length-1)),v=g[y];d=jt(Fe({},v),{id:u,href:f,created:new Date,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else d={id:u,href:f,locations:{progression:l},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(d)if(this.api?.addAnnotation)try{let f=await this.api.addAnnotation(d),g=await this.annotator.saveAnnotation(f);return await this.showHighlights(),await this.drawHighlights(),new Promise(y=>y(g))}catch(f){await this.showHighlights(),await this.drawHighlights()}else{let f=await this.annotator.saveAnnotation(d);return await this.showHighlights(),await this.drawHighlights(),new Promise(g=>g(f))}}}return new Promise(r=>r(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!==Le.Bookmark),t.forEach(n=>{zt.push(n.highlight)}))),this.highlightsView&&this.createTree(fr.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(qe.Annotation);for(let r of n){zt.push(r.highlight);let o=r,a=this.delegate.currentChapterLink.href;var t=this.publication.getTOCItem(a);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 l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&(await this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,r.highlight),setTimeout(async()=>{if(o.highlight?.marker===Le.Underline){let u=await this.annotator?.getAnnotationPosition(r.id,this.delegate.iframes[0].contentWindow),d='<div class="comment" style="top: '+u+'px;width:20px"></div>',f=document.createElement("div");f.innerHTML=d;let g=f.childNodes[0],y=document.createElement("i");y.innerHTML="sticky_note_2",y.className="material-icons",y.style.color=o.highlight.color,g.appendChild(y),ne(f,"click",v=>{v.preventDefault(),v.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(qe.Annotation);for(let r of n){zt.push(r.highlight);let o=r,a=this.delegate.currentChapterLink.href,l=this.publication.getTOCItem(a);if(this.delegate.currentTocUrl&&(l=this.publication.getTOCItem(this.delegate.currentTocUrl)),l===null&&(l=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),l){let u=l.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),o.href===u&&(await this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,r.highlight),setTimeout(async()=>{if(o.highlight?.marker===Le.Underline){let d=await this.annotator?.getAnnotationPosition(r.id,this.delegate.iframes[0].contentWindow),f='<div class="comment" style="top: '+d+"px;background: "+o.highlight?.color+';width:20px"></div>',g=document.createElement("div");g.innerHTML=f,g.childNodes[0].innerHTML=$r.note,ne(g,"click",y=>{y.preventDefault(),y.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){let t=this.delegate.iframes[0].contentDocument;if(t&&(this.commentGutter=t.getElementById(Re.R2_ID_GUTTER_RIGHT_CONTAINER),this.delegate.view?.isScrollMode()&&this.properties?.enableComments?this.commentGutter.style.removeProperty("display"):this.commentGutter.style.setProperty("display","none"),this.commentGutter&&this.delegate.view?.isScrollMode())){this.commentGutter.innerHTML="";let n=[];this.annotator&&(n=this.annotator.getAnnotations(),n&&(n=n.filter(r=>r.highlight?.note?.length>0),n=this.syncPosition(n),n=this.reposition(n),n.forEach(r=>{let o=document.createElement("i");o.innerHTML="sticky_note_2",o.className="material-icons",o.style.color=r.highlight.color;let a=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),l,u;a&&(l=a.querySelector(`#${r.highlight.id}`)),u=l.getElementsByClassName(hn)[0];let f=parseInt(u.style.height.replace("px","")),g=r.highlight.position,y=t.createElement("div");y.setAttribute("style",`position: absolute;top:${g}px;display: flex;max-width: 250px !important;height:${f}px;width: 200px;align-items: center;`);let v=t.createElement("div");y.appendChild(v);let S=r.highlight.color;De.isHexColor(S)&&(S=De.hexToRgbChannels(S)),y.innerHTML=$s("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="8"/>',"icon open",10,`rgba(${S.red}, ${S.green}, ${S.blue}, 1) !important`);let w=t.createElement("div");w.innerHTML=r.highlight?.note,w.setAttribute("style",`height:${f}px;overflow: hidden;padding-left: 5px;`),y.appendChild(w),ne(y,"click",b=>{b.preventDefault(),b.stopPropagation(),this.scrollToHighlight(r.highlight.id)}),this.commentGutter?.appendChild(y)})))}}createTree(t,n,r){if(n){let o=this,a=this.publication.readingOrder;if(a.length){let l=(u,d)=>{let f=document.createElement("ul");f.className="sidenav-annotations";for(let g of d){let y=document.createElement("li"),v=document.createElement("a"),S=document.createElement("span");if(v.tabIndex=-1,v.className="chapter-link",g.Href){let b=this.publication.getAbsoluteHref(g.Href),m=this.publication.getTOCItemAbsolute(b);v.href=b,v.innerHTML=m?.Title||"",y.appendChild(v)}else S.innerHTML=g.Title||"",S.className="chapter-title",y.appendChild(S);ne(v,"click",b=>{b.preventDefault(),b.stopPropagation();let m={href:v.href,locations:{progression:0},type:g.TypeLink,title:v.title};this.delegate.stopReadAloud(),this.delegate.navigate(m)});let w=document.createElement("ol");n.forEach(function(b){let m=g.Href.indexOf("#")!==-1?g.Href.slice(0,g.Href.indexOf("#")):g.Href;if(g.Href&&b.href.endsWith(m)){let E=document.createElement("li");E.className="annotation-item";let O=document.createElement("a");if(O.setAttribute("href",b.href),t===fr.Annotation){O.className="highlight-link";let A=document.createElement("span"),T=document.createElement("span");if(A.className="title",T.innerHTML=b.highlight.selectionInfo.cleanText,b.highlight?.marker===Le.Underline)if(typeof b.highlight?.color=="object"){let P=b.highlight?.color;P&&T.style.setProperty("border-bottom",`2px solid ${De.hexToRgbA(P)}`,"important")}else T.style.setProperty("border-bottom",`2px solid ${b.highlight?.color}`,"important");else if(typeof b.highlight?.color=="object"){let P=b.highlight?.color;P&&(T.style.backgroundColor=De.hexToRgbA(P))}else{let P=b.highlight?.color;P&&(T.style.backgroundColor=P)}A.appendChild(T),O.appendChild(A);let M=document.createElement("span"),j=Math.round((b.locations.progression??0)*100)+"% through resource";M.className="subtitle",M.innerHTML=j,O.appendChild(M)}let _=document.createElement("span");if(_.className="timestamp",_.innerHTML=Qa.readableTimestamp(b.created),O.appendChild(_),ne(O,"click",A=>{A.preventDefault(),A.stopPropagation(),o.handleAnnotationLinkClick(A,b)}),E.appendChild(O),o.delegate.sideNavExpanded){let A=document.createElement("button");A.className="delete",A.innerHTML=$r.delete,ne(A,"click",T=>{T.preventDefault(),T.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,T,b)}),E.appendChild(A)}w.appendChild(E)}}),w.children.length>0&&(f.appendChild(y),f.appendChild(w)),f.children.length>0&&u.appendChild(f),g.Children&&g.Children.length>0&&l(u,g.Children)}};r.innerHTML="",l(r,a)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.delegate.stopReadAloud(),this.delegate.navigate(n)):Cr.default.log("annotation data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,r){Cr.default.log("annotation data locator: ",r),r?t===fr.Annotation&&this.deleteHighlight(r):Cr.default.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)}syncPosition(t){let n=this.delegate.iframes[0].contentDocument,r=(o,a)=>{let l=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),u,d;l&&(u=l.querySelector(`#${a.highlight.id}`)),d=u.getElementsByClassName(hn)[0];let g=parseInt(d.style.top.replace("px","")),y=jt(Fe({},a),{highlight:jt(Fe({},a.highlight),{position:g})});return[...o,y]};return t.reduce(r,[])}reposition(t){let n=this.delegate.iframes[0].contentDocument,r=(o,a,l)=>{let u=t[0],d=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),f,g;d&&(f=d.querySelector(`#${u.highlight.id}`)),g=f.getElementsByClassName(hn)[0];let v=parseInt(g.style.height.replace("px","")),S=a.highlight.position,w=o[l-1]&&o[l-1].highlight.position,m=l===0?0:w+v+0,E=m>S?m:S,O=jt(Fe({},a),{highlight:jt(Fe({},a.highlight),{position:E})});return[...o,O]};return t.sort(function(o,a){return o.highlight.position-a.highlight.position}).reduce(r,[])}};C();var A0=Je(T0());var Rr=Je(Dt()),el=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(r=>r(n))}constructor(t,n,r,o,a,l,u,d){this.annotator=t,this.rights=n,this.publication=r,this.headerMenu=d,this.delegate=o,this.initialAnnotations=l,this.properties=a,this.api=u}stop(){Rr.default.log("Bookmark module stop")}async start(){if(this.delegate.bookmarkModule=this,this.headerMenu&&(this.bookmarksView=de(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=de(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let t=de(this.headerMenu,"#menu-button-bookmark");t&&t.parentElement?.style.removeProperty("display"),t&&ne(t,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let t=this.initialAnnotations.bookmarks||null;t&&this.annotator?.initBookmarks(t)}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 Rr.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else{let n=await this.annotator.deleteBookmark(t);return Rr.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),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 r=this.delegate.view?.getCurrentPosition(),o=(0,A0.v4)(),a;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let l=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),u=Math.ceil((r??0)*(l.length-1)),d=l[u];a=jt(Fe({},d),{id:o,href:n,created:new Date,title:this.delegate.currentChapterLink.title})}else a={id:o,href:n,locations:{progression:r},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title};if(!this.annotator.locatorExists(a,fr.Bookmark))if(this.api?.addBookmark){let l=await this.api.addBookmark(a);l&&(a=l),Rr.default.log(a);let u=this.annotator.saveBookmark(a);return Rr.default.log("Bookmark added "+JSON.stringify(u)),this.showBookmarks(),await this.drawBookmarks(),u}else{let l=this.annotator.saveBookmark(a);return Rr.default.log("Bookmark added "+JSON.stringify(l)),this.showBookmarks(),await this.drawBookmarks(),l}}}}async addBookmarkPlus(){let t=this,n=this.delegate.highlighter?.visibleTextRects[0],r=this.delegate.iframes[0].contentDocument;if(r){let u=this.delegate.highlighter?.dom(r.body).getWindow().document.createRange(),d=this.delegate.highlighter?.dom(this.delegate.iframes[0].contentDocument?.body).getSelection();d.removeAllRanges(),n&&u.selectNodeContents(n.node),d.addRange(u);let f=yd(u,!1),g=0;for(let y of f){if(!this.delegate.highlighter?.isOutsideViewport(y)){let v=d.focusNode,S=d.focusOffset;d.collapse(d.anchorNode,d.anchorOffset);for(let E=0;E<g;E++)d.modify("move","forward","line");d.extend(v,S);let w=d.focusNode,b=d.focusNode.length;d.collapse(d.anchorNode,d.anchorOffset);let m=b;d.anchorOffset>b?m=b:m=d.anchorOffset+1,d.modify("move","forward","character"),d.modify("move","backward","word"),d.extend(w,m),d.modify("extend","backward","character"),d.modify("extend","forward","word");break}g++}}function o(u){let d={},f=t.delegate.iframes[0].contentDocument;if(f)return Rn(u,t.delegate.highlighter?.dom(f.body).getDocument(),d)}let a=this.delegate.iframes[0].contentWindow,l={id:"bookmarkIcon",marker:Le.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(a!==null){let u=Do(a,o);if(u===void 0){let f=t.delegate.iframes[0].contentDocument;u=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(f)}let d=t.delegate.iframes[0].contentDocument;if(u&&d){let f=this.delegate.highlighter?.createHighlight(this.delegate.highlighter?.dom(d.body).getWindow(),u,l.highlight?.color,!0,Le.Bookmark,l.icon,l.popup,l.highlight?.style);if(this.delegate.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),f)return this.saveAnnotation(f[0]).then(g=>{Rr.default.log("saved bookmark "+g?.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 r=this.delegate.view?.getCurrentPosition(),o=this.delegate.iframes[0].contentDocument;if(o){let a=Oi(o,"body"),l=t.position?t.position/a.scrollHeight:r,u=(0,A0.v4)(),d;if(n){let f=n.Href;if(f.indexOf("#")>0&&(f=f.slice(0,f.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let g=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),y=Math.ceil((l??0)*(g.length-1)),v=g[y];d=jt(Fe({},v),{id:u,href:f,created:new Date,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else d={id:u,href:f,locations:{progression:l},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(d)if(this.api?.addBookmark){let f=await this.api.addBookmark(d),g=await this.annotator.saveAnnotation(f);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(y=>y(g))}else{let f=await this.annotator.saveAnnotation(d);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(g=>g(f))}}}return new Promise(r=>r(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(r=>r.highlight.marker===Le.Bookmark),t?t.push.apply(t,n):t=n)),this.bookmarksView&&this.createTree(fr.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(qe.Annotation);for(let r of n){zt.push(r.highlight);let o=r,a=this.delegate.currentChapterLink.href;var t=this.publication.getTOCItem(a);if(this.delegate.currentTocUrl&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&await this.delegate.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,r.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(qe.Annotation);for(let r of n){zt.push(r.highlight);let o=r,a=this.delegate.currentChapterLink.href,l=this.publication.getTOCItem(a);if(this.delegate.currentTocUrl&&(l=this.publication.getTOCItem(this.delegate.currentTocUrl)),l===void 0&&(l=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),l){let u=l.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),o.href===u&&await this.delegate.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,r.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 Rr.default.log("Highlight deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else return new Promise(r=>r(null))}createTree(t,n,r){if(n){let o=this,a=this.publication.readingOrder;if(a.length){let l=(u,d)=>{let f=document.createElement("ul");f.className="sidenav-annotations";for(let g of d){let y=document.createElement("li"),v=document.createElement("a"),S=document.createElement("span");if(v.tabIndex=-1,v.className="chapter-link",g.Href){let b=this.publication.getAbsoluteHref(g.Href),m=this.publication.getTOCItemAbsolute(b);v.href=b,v.innerHTML=m?.Title||"",y.appendChild(v)}else S.innerHTML=g.Title||"",S.className="chapter-title",y.appendChild(S);ne(v,"click",b=>{b.preventDefault(),b.stopPropagation();let m={href:v.href,locations:{progression:0},type:g.TypeLink,title:v.title};this.delegate.stopReadAloud(),this.delegate.navigate(m)});let w=document.createElement("ol");n.forEach(function(b){let m=g.Href.indexOf("#")!==-1?g.Href.slice(0,g.Href.indexOf("#")):g.Href;if(g.Href&&b.href.endsWith(m)){let E=document.createElement("li");E.className="annotation-item";let O=document.createElement("a");if(O.setAttribute("href",b.href),t===fr.Bookmark){O.className="bookmark-link";let A=document.createElement("span"),T=Math.round((b.locations.progression??0)*100)+"% through resource";A.className="title",A.innerHTML=T,O.appendChild(A)}let _=document.createElement("span");if(_.className="timestamp",_.innerHTML=el.readableTimestamp(b.created),O.appendChild(_),ne(O,"click",A=>{A.preventDefault(),A.stopPropagation(),o.handleAnnotationLinkClick(A,b)}),E.appendChild(O),o.delegate.sideNavExpanded){let A=document.createElement("button");A.className="delete",A.innerHTML=$r.delete,ne(A,"click",T=>{T.preventDefault(),T.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,T,b)}),E.appendChild(A)}w.appendChild(E)}}),w.children.length>0&&(f.appendChild(y),f.appendChild(w)),f.children.length>0&&u.appendChild(f),g.Children&&g.Children.length>0&&l(u,g.Children)}};r.innerHTML="",l(r,a)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.delegate.stopReadAloud(),this.delegate.navigate(n)):Rr.default.log("bookmark data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,r){Rr.default.log("bookmark data locator: ",r),r?t===fr.Bookmark&&this.deleteBookmark(r):Rr.default.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)}};C();var D4=Je(j4());C();var Vn=Je(Dt()),R0="r2-mo-active",Uo=class{},Ne=Uo;Ne.COLOR_REF="color",Ne.AUTO_SCROLL_REF="autoscroll",Ne.AUTO_TURN_REF="autoturn",Ne.VOLUME_REF="volume",Ne.RATE_REF="rate",Ne.COLOR_KEY="mediaoverlay-"+Uo.COLOR_REF,Ne.AUTO_SCROLL_KEY="mediaoverlay-"+Uo.AUTO_SCROLL_REF,Ne.AUTO_TURN_KEY="mediaoverlay-"+Uo.AUTO_TURN_REF,Ne.VOLUME_KEY="mediaoverlay-"+Uo.VOLUME_REF,Ne.RATE_KEY="mediaoverlay-"+Uo.RATE_REF;var M0=class{constructor(t,n,r){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=r,this.initialise(),Vn.default.log(this.api)}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialMediaOverlaySettings){let r=t.initialMediaOverlaySettings;r?.color&&(n.color=r.color,Vn.default.log(n.color)),r?.autoScroll&&(n.autoScroll=r.autoScroll,Vn.default.log(n.autoScroll)),r?.autoTurn&&(n.autoTurn=r.autoTurn,Vn.default.log(n.autoScroll)),r?.volume&&(n.volume=r.volume,Vn.default.log(n.volume)),r?.rate&&(n.rate=r.rate,Vn.default.log(n.rate)),r?.wait&&(n.wait=r.wait,Vn.default.log(n.wait))}return n.initializeSelections(),n}stop(){Vn.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(Ne.AUTO_SCROLL_KEY)!=null?this.getProperty(Ne.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(Ne.AUTO_TURN_KEY)!=null?this.getProperty(Ne.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(Ne.COLOR_KEY)!=null?this.getProperty(Ne.COLOR_KEY).value:this.color,this.volume=this.getProperty(Ne.VOLUME_KEY)!=null?this.getProperty(Ne.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(Ne.RATE_KEY)!=null?this.getProperty(Ne.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=de(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechAutoTurn=de(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=de(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=de(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=de(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()),ne(de(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(Ne.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Ne.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(Ne.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(Ne.VOLUME_REF)?.value,rate:this.userProperties.getByRef(Ne.RATE_REF)?.value};this.applyMediaOverlaySettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{Vn.default.log("api updated sync settings",n)})}getMediaOverlaySettings(){let t=new Si;return t.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,Ne.AUTO_SCROLL_REF,Ne.AUTO_SCROLL_KEY),t.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,Ne.AUTO_TURN_REF,Ne.AUTO_TURN_KEY),t.addStringable(this.color,Ne.COLOR_REF,Ne.COLOR_KEY),t.addIncremental(this.volume,.1,1,.1,"",Ne.VOLUME_REF,Ne.VOLUME_KEY),t.addIncremental(this.rate,.1,3,.1,"",Ne.RATE_REF,Ne.RATE_KEY),t}saveProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let r=JSON.parse(n);r=r.filter(o=>o.name!==t.name),r.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(r))}else{let r=[];r.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(r))}return t}getProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let r=JSON.parse(n);return r=r.filter(o=>o.name===t),r.length===0?null:r[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(Ne.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){Vn.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Ne.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoTurn!==void 0){Vn.default.log("autoTurn "+this.autoTurn),this.autoTurn=t.autoTurn;let n=this.userProperties.getByRef(Ne.AUTO_TURN_REF);n&&(n.value=this.autoTurn,this.saveProperty(n)),this.settingsChangeCallback()}if(t.volume){Vn.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Ne.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback()}if(t.rate){Vn.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Ne.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback()}}applyMediaOverlaySetting(t,n){if(t===Ne.COLOR_REF){this.color=n;let r=this.userProperties.getByRef(Ne.COLOR_REF);r&&(r.value=this.color,this.saveProperty(r)),this.settingsChangeCallback()}else if(t===Ne.AUTO_SCROLL_REF){this.autoScroll=n;let r=this.userProperties.getByRef(Ne.AUTO_SCROLL_REF);r&&(r.value=this.autoScroll,this.saveProperty(r)),this.settingsChangeCallback()}else if(t===Ne.AUTO_TURN_REF){this.autoTurn=n;let r=this.userProperties.getByRef(Ne.AUTO_TURN_REF);r&&(r.value=this.autoTurn,this.saveProperty(r)),this.settingsChangeCallback()}}increase(t){if(t==="mo_volume"){this.userProperties.getByRef(Ne.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(Ne.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Ne.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Ne.RATE_REF).increment(),this.rate=this.userProperties.getByRef(Ne.RATE_REF)?.value;let n=this.userProperties.getByRef(Ne.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}decrease(t){if(t==="mo_volume"){this.userProperties.getByRef(Ne.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(Ne.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Ne.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Ne.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(Ne.RATE_REF)?.value;let n=this.userProperties.getByRef(Ne.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}};var He=Je(Dt()),P0=class{constructor(t,n,r,o){this.play=de(document,"#menu-button-play");this.pause=de(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async t=>{He.default.log("ontimeupdate"),this.trackCurrentTime()};this.ensureOnTimeUpdate=(t,n)=>{t?this.__ontimeupdate&&(this.__ontimeupdate=!1,this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),cancelAnimationFrame(this.myReq)):(!this.__ontimeupdate||n)&&(this.__ontimeupdate=!0,n&&(this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),this.audioElement.addEventListener("timeupdate",this.ontimeupdate)))};this.delegate=t,this.publication=n,this.settings=r,this.properties=o}static create(t){let n=new this(t.delegate,t.publication,t.settings,t);return n.start(),n}stop(){He.default.log("MediaOverlay module stop")}start(){this.delegate.mediaOverlayModule=this,He.default.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(),a;try{a=await fetch(o,this.delegate.requestConfig)}catch(f){console.error(f,o);return}a.ok||He.default.log("BAD RESPONSE?!");let l;try{l=await a.json()}catch(f){console.error(f)}if(!l){He.default.log("## moJson"+l);return}t.MediaOverlays=Ts(l,D4.MediaOverlayNode),t.MediaOverlays.initialized=!0;let u=t.HrefDecoded||t.Href,d=new URL("https://dita.digital/"+u);await this.playMediaOverlays(d.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&&await this.audioElement.pause(),this.delegate.nextResource()):await this.stopReadAloud()}async startReadAloud(){if(this.delegate.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement&&this.currentLinks[this.currentLinkIndex]?.Properties.MediaOverlay){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.removeProperty("display")}}async stopReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"))}findDepthFirstTextAudioPair(t,n,r){He.default.log("findDepthFirstTextAudioPair()");let o,a;if(n.Text){let d=new URL("https://dita.digital/"+n.Text);if(d.pathname.substr(1)===t){if(o=!0,d.hash&&r){a=!1;let f=d.hash.substr(1);for(let g of r)if(g===f){a=!0;break}}}else o=!1}if(He.default.log("isFragmentIDMatch: "+a),He.default.log("isTextUrlMatch: "+o),!n.Children||!n.Children.length){if(He.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!o){He.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return a||o&&!r?(He.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),n):void 0}let l=r,u=r;for(let d of n.Children){He.default.log("findDepthFirstTextAudioPair() - child"),He.default.log(JSON.stringify(d));let f=this.findDepthFirstTextAudioPair(t,d,u);if(f===null&&(He.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),u=void 0),f)return He.default.log("findDepthFirstTextAudioPair() - child - match"),He.default.log(JSON.stringify(f)),f}if(a){He.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let d=this.findDepthFirstTextAudioPair(t,n,void 0);return d&&(He.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),He.default.log(JSON.stringify(d)),d)}if(l&&!u)return null}trackCurrentTime(){if(cancelAnimationFrame(this.myReq),this.mediaOverlayTextAudioPair)try{this.currentAudioEnd&&this.audioElement.currentTime>=this.currentAudioEnd-.05&&(He.default.log("ontimeupdate - mediaOverlaysNext()"),this.mediaOverlaysNext());let 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(He.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let n=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!t);if(!n)He.default.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud());else{let r=!1;if(this.mediaOverlayTextAudioPair.Text&&n.Text){let o=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),a=new URL("https://dita.digital/"+n.Text);o.pathname!==a.pathname&&(He.default.log("mediaOverlaysNext() SWITCH! "+o.pathname+" != "+a.pathname),r=!0)}r?this.mediaOverlaysStop():(He.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(n,void 0,void 0)},0))}}else He.default.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){He.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){He.default.log("mediaOverlaysPause()"),this.mediaOverlayHighlight(void 0),this.audioElement&&this.audioElement.pause()}findNextTextAudioPair(t,n,r,o){if(!t.Children||!t.Children.length){if(r?.prev===n)return He.default.log("findNextTextAudioPair() - prevMo === moToMatch"),t;He.default.log("findNextTextAudioPair() - set previous"),He.default.log(JSON.stringify(t)),r.prev=t;return}for(let a of t.Children){He.default.log("findNextTextAudioPair() - child"),He.default.log(JSON.stringify(a));let l=this.findNextTextAudioPair(a,n,r,o);if(l)return He.default.log("findNextTextAudioPair() - match"),He.default.log(JSON.stringify(l)),l}}async playMediaOverlaysAudio(t,n,r){if(He.default.log("playMediaOverlaysAudio()"),this.mediaOverlayTextAudioPair=t,!t.Audio)return;let o=new URL(t.Audio,this.publication.manifestUrl),a=o.toString(),l=new URL(a);l.hash="",l.search="";let u=l.toString(),d=typeof n!="undefined",f=typeof r!="undefined";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!d&&!f){if(o.hash){let y=o.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(y&&y.length>=1){let v=y[1];try{this.currentAudioBegin=parseFloat(v)}catch(S){He.default.error(S)}if(y.length>=3){let S=y[3];try{this.currentAudioEnd=parseFloat(S)}catch(w){He.default.error(w)}}}}}else this.currentAudioBegin=n,this.currentAudioEnd=r;He.default.log(`${a} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let g=async y=>{if(!this.audioElement)return;let v=this.currentAudioBegin?this.currentAudioBegin:0;if(y||this.audioElement.paused)if(y&&!v||this.audioElement.currentTime===v){if(He.default.log("playMediaOverlaysAudio() - playClip() - _currentAudioElement.play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing){let w=function(){S.settings.resourceReady?setTimeout(async()=>{await S.audioElement.play(),S.ensureOnTimeUpdate(!1,!0)},S.settings.wait*1e3):setTimeout(w,200)},S=this;w()}}else{He.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let S=async w=>{if(this.audioElement.removeEventListener("timeupdate",S),He.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked - .play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement&&(this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing)){let m=function(){b.settings.resourceReady?setTimeout(async()=>{await b.audioElement.play(),b.ensureOnTimeUpdate(!1,!0)},b.settings.wait*1e3):setTimeout(m,200)},b=this;m()}};this.audioElement.addEventListener("timeupdate",S),this.audioElement.currentTime=v}else{let S=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd!="undefined"&&this.previousAudioEnd>v-.02&&this.previousAudioEnd<=v&&this.audioElement.currentTime>=v-.1;this.ensureOnTimeUpdate(!1,!1),S?He.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(He.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=v)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||u!==this.currentAudioUrl){this.currentAudioUrl=u,He.default.log("playMediaOverlaysAudio() - RESET: "+this.previousAudioUrl+" => "+this.currentAudioUrl),this.audioElement=document.getElementById("AUDIO_MO_ID"),this.audioElement&&(this.audioElement.pause(),this.audioElement.setAttribute("src",""),this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement)),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("style","display: none"),this.audioElement.setAttribute("id","AUDIO_MO_ID"),this.audioElement.setAttribute("role","media-overlays"),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate,document.body.appendChild(this.audioElement),this.audioElement.addEventListener("error",S=>{He.default.log("-1) error: "+(this.currentAudioUrl!==S.currentTarget.src?this.currentAudioUrl+" -- ":"")+S.currentTarget.src.substr(S.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(He.default.log(this.audioElement.error.code),He.default.log(this.audioElement.error.message))});let y=async S=>{S.currentTarget.removeEventListener("canplaythrough",y),He.default.log("oncanplaythrough"),await g(!0)};this.audioElement.addEventListener("canplaythrough",y);let v=async S=>{He.default.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",v),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else He.default.log("playMediaOverlaysAudio() - playClip()"),await g(!1)}async playMediaOverlays(t,n,r){He.default.log("playMediaOverlays()");let o=r?r.filter(l=>l):void 0;o&&o.length===0&&(o=void 0);let a=this.findDepthFirstTextAudioPair(t,n,o);!a&&o&&(He.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),He.default.log(JSON.stringify(o,null,4)),He.default.log(JSON.stringify(n,null,4)),a=this.findDepthFirstTextAudioPair(t,n,void 0)),a?a.Audio&&(He.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=n,await this.playMediaOverlaysAudio(a,void 0,void 0)):He.default.log("playMediaOverlays() - !moTextAudioPair "+t)}mediaOverlayHighlight(t){He.default.log("moHighlight: ## "+t);let n=this.publication.Metadata?.MediaOverlay?.ActiveClass;n||(n=this.settings.color);let r=this.delegate.iframes[0].contentDocument?.documentElement.getAttribute("style"),o=r?r.indexOf("readium-night-on")>0:!1,a=r?r.indexOf("readium-sepia-on")>0:!1;if((this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&(n=o||a?R0:n||R0),this.pid){let u;this.currentLinkIndex===0?u=this.delegate.iframes[0].contentDocument?.getElementById(this.pid):u=this.delegate.iframes[1].contentDocument?.getElementById(this.pid),u&&u.classList.remove(n)}let l;t&&(this.currentLinkIndex===0?l=this.delegate.iframes[0].contentDocument?.getElementById(t):l=this.delegate.iframes[1].contentDocument?.getElementById(t),l&&l.classList.add(n),this.pid=t),l&&(this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&l.scrollIntoView({block:"center",behavior:"smooth"})}};C();var I0=Je(Dt()),L0=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(){I0.default.log("Timeline module stop")}async start(){this.delegate.timelineModule=this,this.timelineContainer=de(document,"#container-view-timeline"),this.positionSlider=de(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.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(r=>{let o=this.publication.getAbsoluteHref(r.Href),a=this.publication.getTOCItemAbsolute(o),l=a?.Href.indexOf("#")!==-1?a?.Href.slice(0,a?.Href.indexOf("#")):a.Href,u=this.publication.getAbsoluteHref(l??"");var d;this.publication.positions&&this.delegate.view?.layout!=="fixed"?r.contentWeight?d=r.contentWeight:d=1:d=100/(this.publication.readingOrder?.length??0);var f=document.createElement("div");if(f.style.height=d+"%",f.style.width="100%",f.className="chapter",a?.Title!==void 0){var g=document.createElement("span");g.innerHTML=a.Title,g.className="chapter-tooltip",f.appendChild(g)}ne(f,"click",y=>{y.preventDefault(),y.stopPropagation();var v;this.publication.positions||this.delegate.rights.autoGeneratePositions&&this.publication.positions?(v=Fe({},this.publication.positions.filter(S=>S.href===r.Href)[0]),v.href=this.publication.getAbsoluteHref(v.href)):v={href:u,locations:{progression:0},type:r.TypeLink,title:r.Title},I0.default.log(v),this.delegate.navigate(v)}),u===this.delegate.currentChapterLink.href?f.className+=" active":f.className=f.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(f)}),t()})}};C();var Q0=Je(Qi());C();var F4=Je(Dt());function $4(i,t){return new Promise(function(n){setTimeout(n.bind(null,t),i)})}var H8=!1;F4.default.setLevel(H8?"trace":"warn",!0);var y3=Je(g3()),Hd=Je(m3()),wn=Je(Dt()),jd=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){(0,Hd.addListener)(r=>{r&&(t.clearOnInspect&&(console.clear(),window.localStorage.clear(),window.sessionStorage.clear(),window.location.replace(window.location.origin)),t.detectInspect&&typeof t.api?.inspectDetected=="function"&&t.api.inspectDetected())}),(0,Hd.launch)(),await $4(t.detectInspectInitDelay??100)}static isCurrentBrowserSupported(t){if(!t.enforceSupportedBrowsers)return!0;let n=[];return(t.supportedBrowsers??[]).forEach(o=>{n.push("last 1 "+o+" version")}),(0,y3.getUserAgentRegExp)({browsers:n,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.delegate.contentProtectionModule=this,this.properties?.enableObfuscation){this.wrapper=dt(document,"#iframe-wrapper"),this.securityContainer=de(document,"#container-view-security");var t=this;this.mutationObserver=new MutationObserver(function(n){n.forEach(function(r){wn.default.log(r.type),t.isHacked=!0})})}}async stop(){if(wn.default.log("Protection module stop"),this.mutationObserver.disconnect(),this.properties?.disableKeys){Pe(this.delegate.mainElement,"keydown",this.disableSave),Pe(this.delegate.headerMenu,"keydown",this.disableSave);for(let t of this.delegate.iframes)Pe(t.contentDocument,"keydown",this.disableSave),Pe(t.contentWindow,"keydown",this.disableSave);Pe(window,"keydown",this.disableSave),Pe(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){Pe(this.delegate.mainElement,"copy",this.preventCopy),Pe(this.delegate.headerMenu,"copy",this.preventCopy);for(let t of this.delegate.iframes)Pe(t.contentDocument,"copy",this.preventCopy),Pe(t.contentWindow,"copy",this.preventCopy);Pe(window,"copy",this.preventCopy),Pe(document,"copy",this.preventCopy),Pe(this.delegate.mainElement,"cut",this.preventCopy),Pe(this.delegate.headerMenu,"cut",this.preventCopy);for(let t of this.delegate.iframes)Pe(t.contentDocument,"cut",this.preventCopy),Pe(t.contentWindow,"cut",this.preventCopy);Pe(window,"cut",this.preventCopy),Pe(document,"cut",this.preventCopy)}if(this.properties?.disablePrint){Pe(this.delegate.mainElement,"beforeprint",this.beforePrint.bind(this)),Pe(this.delegate.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let t of this.delegate.iframes)Pe(t.contentDocument,"beforeprint",this.beforePrint),Pe(t.contentWindow,"beforeprint",this.beforePrint);Pe(window,"beforeprint",this.beforePrint),Pe(document,"beforeprint",this.beforePrint),Pe(this.delegate.mainElement,"afterprint",this.afterPrint.bind(this)),Pe(this.delegate.headerMenu,"afterprint",this.afterPrint.bind(this));for(let t of this.delegate.iframes)Pe(t.contentDocument,"afterprint",this.afterPrint.bind(this)),Pe(t.contentWindow,"afterprint",this.afterPrint.bind(this));Pe(window,"afterprint",this.afterPrint.bind(this)),Pe(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){Pe(this.delegate.mainElement,"contextmenu",this.disableContext),Pe(this.delegate.headerMenu,"contextmenu",this.disableContext);for(let t of this.delegate.iframes)Pe(t.contentDocument,"contextmenu",this.disableContext),Pe(t.contentWindow,"contextmenu",this.disableContext);Pe(window,"contextmenu",this.disableContext),Pe(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),Pe(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=Oi(t.contentDocument,"body");this.rects=this.findRects(n),this.rects.forEach(r=>this.toggleRect(r,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){ne(this.delegate.mainElement,"keydown",this.disableSave),ne(this.delegate.headerMenu,"keydown",this.disableSave);for(let t of this.delegate.iframes)ne(t,"keydown",this.disableSave),ne(t.ownerDocument,"keydown",this.disableSave),ne(t.contentDocument,"keydown",this.disableSave),ne(t.contentWindow,"keydown",this.disableSave),ne(t.contentWindow?.document,"keydown",this.disableSave);ne(window,"keydown",this.disableSave),ne(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){ne(this.delegate.mainElement,"copy",this.preventCopy),ne(this.delegate.headerMenu,"copy",this.preventCopy);for(let t of this.delegate.iframes)ne(t,"copy",this.preventCopy),ne(t.ownerDocument,"copy",this.preventCopy),ne(t.contentDocument,"copy",this.preventCopy),ne(t.contentWindow,"copy",this.preventCopy),ne(t.contentWindow?.document,"copy",this.preventCopy);ne(window,"copy",this.preventCopy),ne(document,"copy",this.preventCopy),ne(this.delegate.mainElement,"cut",this.preventCopy),ne(this.delegate.headerMenu,"cut",this.preventCopy);for(let t of this.delegate.iframes)ne(t,"cut",this.preventCopy),ne(t.ownerDocument,"cut",this.preventCopy),ne(t.contentDocument,"cut",this.preventCopy),ne(t.contentWindow,"cut",this.preventCopy),ne(t.contentWindow?.document,"cut",this.preventCopy);ne(window,"cut",this.preventCopy),ne(document,"cut",this.preventCopy)}if(this.properties?.disablePrint){ne(this.delegate.mainElement,"beforeprint",this.beforePrint),ne(this.delegate.headerMenu,"beforeprint",this.beforePrint);for(let t of this.delegate.iframes)ne(t,"beforeprint",this.beforePrint.bind(this)),ne(t.ownerDocument,"beforeprint",this.beforePrint.bind(this)),ne(t.contentDocument,"beforeprint",this.beforePrint.bind(this)),ne(t.contentWindow,"beforeprint",this.beforePrint.bind(this)),ne(t.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));ne(window,"beforeprint",this.beforePrint.bind(this)),ne(document,"beforeprint",this.beforePrint.bind(this)),ne(this.delegate.mainElement,"afterprint",this.afterPrint),ne(this.delegate.headerMenu,"afterprint",this.afterPrint);for(let t of this.delegate.iframes)ne(t,"afterprint",this.afterPrint.bind(this)),ne(t.ownerDocument,"afterprint",this.afterPrint.bind(this)),ne(t.contentDocument,"afterprint",this.afterPrint.bind(this)),ne(t.contentWindow,"afterprint",this.afterPrint.bind(this)),ne(t.contentWindow?.document,"afterprint",this.afterPrint.bind(this));ne(window,"afterprint",this.afterPrint.bind(this)),ne(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){ne(this.delegate.mainElement,"contextmenu",this.disableContext),ne(this.delegate.headerMenu,"contextmenu",this.disableContext);for(let t of this.delegate.iframes)ne(t,"contextmenu",this.disableContext),ne(t.ownerDocument,"contextmenu",this.disableContext),ne(t.contentDocument,"contextmenu",this.disableContext),ne(t.contentWindow,"contextmenu",this.disableContext),ne(t.contentWindow?.document,"contextmenu",this.disableContext);ne(window,"contextmenu",this.disableContext),ne(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 r=Oi(n.contentDocument,"body");this.observe(),setTimeout(()=>{this.rects=this.findRects(r),this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),this.setupEvents(),this.hasEventListener||(this.hasEventListener=!0,ne(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,Q0.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 wn.default.log("copy action initiated"),t.clipboardData.setData("text/plain","copy not allowed"),t.stopPropagation(),t.preventDefault(),!1}beforePrint(t){return wn.default.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 wn.default.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(r){r.preventDefault();let o=r.currentTarget.getAttribute("data-href-resolved"),a=document.createElement("a");a.setAttribute("href",o),a.click()}for(let r of this.delegate.iframes){let o=r.contentDocument?.querySelectorAll("a");o?.forEach(a=>{let l=a.getAttribute("data-href"),u=a.getAttribute("href");!l&&u&&(a.setAttribute("data-href",u),a.setAttribute("data-href-resolved",a.href))}),t?o?.forEach(a=>{a.setAttribute("href",""),a.addEventListener("click",n)}):o?.forEach(a=>{let l=a.getAttribute("data-href");l&&a.setAttribute("href",l),a.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;",r=o=>{o.preventDefault()};for(let o of this.delegate.iframes){let a=o.contentDocument?.body.getAttribute("style")||"";t?(o.contentDocument?.body.addEventListener("dragstart",r),o.contentDocument?.body.setAttribute("style",a+n)):(o.contentDocument?.body.removeEventListener("dragstart",r),o.contentDocument?.body.setAttribute("style",a.replace(n,"")))}}recalculate(t=0){return new Promise(n=>{if(this.properties?.enableObfuscation){let r=(0,Q0.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(),r()):n(!1)}else n(!1)})}calcRects(t){t!==void 0&&t.forEach(n=>{try{let{top:r,height:o,left:a,width:l}=this.measureTextNode(n.node);n.top=r,n.height=o,n.width=l,n.left=a}catch(r){wn.default.log("error "+r),wn.default.log(n),wn.default.log(n.node),wn.default.log("scrambledTextContent "+n.scrambledTextContent),wn.default.log("textContent "+n.textContent),wn.default.log("isObfuscated "+n.isObfuscated)}})}deactivateRect(t,n,r){this.isBeingHacked(n)||r?(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0):(t.node.textContent=t.textContent,t.isObfuscated=!1)}toggleRect(t,n,r){let o=this.isOutsideViewport(t),a=this.isBeingHacked(n);t.isObfuscated&&!o&&!a&&!r&&(t.node.textContent=t.textContent,t.isObfuscated=!1),!t.isObfuscated&&(o||a||r)&&(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0)}findRects(t){return this.findTextNodes(t).map(r=>{let{top:o,height:a,left:l,width:u}=this.measureTextNode(r),d=r.parentElement?.nodeName==="option"||r.parentElement?.nodeName==="script"?r.textContent:this.obfuscateText(r.textContent??"");return{top:o,height:a,width:u,left:l,node:r,textContent:r.textContent??"",scrambledTextContent:d??"",isObfuscated:!1}})}obfuscateText(t){return this.scramble(t,!0)}measureTextNode(t){try{let n=document.createRange();n.selectNode(t);let r=n.getBoundingClientRect();return n.detach(),r}catch(n){wn.default.log("measureTextNode "+n),wn.default.log("measureTextNode "+t),wn.default.log(t.textContent)}}isBeingHacked(t){return t.style.animation||t.style.transition||t.style.position||t.hasAttribute("style")?(wn.default.log("content being hacked"),!0):!1}isOutsideViewport(t){let n=this.wrapper.scrollLeft,r=n+this.wrapper.clientWidth,o=t.left+t.width,a=t.top+t.height,l=this.wrapper.scrollTop,u=l+this.wrapper.clientHeight,d=a<l,f=t.top>u,g=o<n-window.innerWidth,y=t.left>r+window.innerWidth;return d||f||g||y}findTextNodes(t,n=[]){let r=t.firstChild;for(;r;)r.nodeType===1&&this.findTextNodes(r,n),r.nodeType===3&&r.textContent?.trim()&&n.push(r),r=r.nextSibling;return n}scramble(t,n=!1,r=!1){var o=t.split(" ");function a(l){for(var u=l.length,d,f;u>0;)f=Math.floor(Math.random()*u),u--,d=l[u],l[u]=l[f],l[f]=d;return l}return n&&(o=o.map(function(l){return a(l.split("")).join("")})),r?a(o).join(" "):o.join(" ")}};C();var O3=Je(v3());C();var Dd=i=>i.replace(/\n/g," ").replace(/\s\s+/g," "),eN=i=>Dd(i).trim(),w3=/[\\^$.*+?()[\]{}|]/g,tN=RegExp(w3.source);function E3(i){return i&&tN.test(i)?i.replace(w3,"\\$&"):i||""}var Fd=0,nN=()=>()=>Number.isSafeInteger(++Fd)?Fd:Fd=1,S3=()=>{Fd=0},rN=nN(),iN=i=>t=>{try{return Rn(t,i,no)}catch(n){return console.error("uniqueCssSelector:",n),""}};async function Js(i,t,n,r,o=!1){if(!t)return[];let a=t.body?.textContent;if(!a)return[];if(i=eN(i),!i.length)return[];let l=t.createNodeIterator(t.body,NodeFilter.SHOW_TEXT,{acceptNode:S=>NodeFilter.FILTER_ACCEPT}),u=new RegExp(E3(i).replace(/ /g,"\\s+"),"gim");o&&(u=new RegExp("\\b"+E3(i).replace(/ /g,"\\s+")+"\\b","gim"));let d=[],f=100,g=30,y=0,v;for(;v=u.exec(a);){let S=Math.max(0,v.index-f),w=Math.min(f,v.index),b=Dd(a.substr(S,w));b=b.substr(b.length-g),S=u.lastIndex,w=Math.min(f,a.length-S);let m=Dd(a.substr(S,w)).substr(0,g),E=new Range,O=v.index;for(;y<=O;){let T=l.nextNode();T&&T.nodeValue&&(y+=T.nodeValue.length)}let _=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(y-O):0;for(E.setStart(l.referenceNode,_),O=v.index+v[0].length;y<=O;){let M=l.nextNode()?.nodeValue;M&&(y+=M.length)}_=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(y-O):0,E.setEnd(l.referenceNode,_),t.getCssSelector||(t.getCssSelector=iN(t));let A=Ri(E,t.getCssSelector);A&&d.push({textMatch:Dd(v[0]),textBefore:b,textAfter:m,rangeInfo:A,href:n,title:r,uuid:rN().toString()})}return d}var x3=Je(Dt()),tg=class{constructor(t,n,r,o,a,l){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.delegate=t,this.headerMenu=l,this.publication=n,this.properties=r,this.api=a,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(){x3.default.log("Search module stop"),Pe(this.searchInput,"keypress",this.handleSearch.bind(this)),Pe(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.delegate.searchModule=this,this.headerMenu){this.searchInput=de(this.headerMenu,"#searchInput"),ne(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=de(this.headerMenu,"#searchGo"),ne(this.searchGo,"click",this.handleSearch.bind(this));var t=de(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,r=this.searchInput.value;let o=this.delegate.currentChapterLink.href,a=this.publication.getSpineItem(o);if(this.headerMenu)var l=de(document,"#searchResultChapter");n.currentChapterSearchResult=[],n.currentSearchHighlights=[];var u=[];this.delegate.rights.enableContentProtection&&this.delegate.contentProtectionModule?.deactivate(),await this.searchAndPaintChapter(r,t,async f=>{u=f,d(1),this.delegate.rights.enableContentProtection&&this.delegate.contentProtectionModule?.recalculate(200)});async function d(f){l.innerHTML="";var g;if(g=n.paginate(u,f,10),g.total===0){let y=document.createElement("a");y.className="collection-item",y.innerHTML="nothing found",l.appendChild(y)}else{for(let b=0;b<g.data.length;b++){let m=document.createElement("a"),E=g.data[b];m.className="collection-item",m.href=a?.Href??"",m.innerHTML="..."+E.textBefore+"<mark>"+E.textMatch+"</mark>"+E.textAfter+"...",ne(m,"click",O=>{O.preventDefault(),O.stopPropagation(),n.jumpToMark(b+f*10-10)}),l.appendChild(m)}let y=document.createElement("div");y.style.textAlign="center",y.style.marginTop="10px";let v=document.createElement("ul");v.className="pagination";let S=document.createElement("li");if(S.className="disabled",S.innerHTML='<a href="#!"> < </a>',g.pre_page!==void 0){let b=g.pre_page;S.className="waves-effect",ne(S,"click",m=>{m.preventDefault(),m.stopPropagation(),d(b)})}v.appendChild(S);for(let b=1;b<=g.total_pages;b++){let m,E=document.createElement("li");E.className="waves-effect",b===g.page&&(E.className="active",m=E),E.innerHTML='<a href="#!">'+b+"</a>",ne(E,"click",O=>{O.preventDefault(),O.stopPropagation(),m&&(m.className="waves-effect"),E.className="active",m=E,d(b)}),v.appendChild(E)}let w=document.createElement("li");if(w.className="disabled",w.innerHTML='<a href="#!"> > </a>',g.next_page!==void 0){let b=g.next_page;w.className="waves-effect",ne(w,"click",m=>{m.preventDefault(),m.stopPropagation(),d(b)})}v.appendChild(w),y.appendChild(v),l.appendChild(y)}}}async searchAndPaintChapter(t,n=0,r){let o=this.publication.getAbsoluteHref(this.publication.readingOrder[this.delegate.currentResource()??0].Href),a=this.publication.getTOCItem(o);a===null&&(a=this.publication.readingOrder[this.delegate.currentResource()??0]);let l=[];this.highlighter?.destroyHighlights(qe.Search),this.delegate.rights.enableSearch&&this.drawSearch();let u=0;if(a){let d=this.delegate.iframes[0].contentDocument;d&&a&&Js(t,d,a.Href,a.Title).then(f=>{f.forEach(g=>{let y={rangeInfo:g.rangeInfo};setTimeout(()=>{let v;u===n?(v=this.createSearchHighlight(y,this.properties?.current),this.jumpToMark(n)):v=this.createSearchHighlight(y,this.properties?.color),g.highlight=v,l.push(g),this.currentChapterSearchResult.push(g),this.currentSearchHighlights.push(v),u++},500)}),setTimeout(()=>{r(l)},500)})}}createSearchHighlight(t,n){try{var r=n;De.isHexColor(r)&&(r=De.hexToRgbChannels(r));let a=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,l=O3.SHA256.hash(a),u="R2_SEARCH_"+l;var o=!1;let d={color:r||Fo,id:u,pointerInteraction:o,selectionInfo:t,marker:Le.Highlight,type:qe.Search},f=this.highlighter?.createHighlightDom(this.delegate.iframes[0].contentWindow,d);return d.position=parseInt((f?.hasChildNodes()?f.childNodes[0]:f).style.top.replace("px","")),d}catch(a){throw"Can't create highlight: "+a}}clearSearch(){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.highlighter?.destroyHighlights(qe.Search)}async search(t,n){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],S3(),this.searchAndPaintChapter(t,0,async()=>{});var r=this.searchChapter(t),o=this.searchBook(t);return n?r:o}async goToSearchID(t,n,r){var o=n,a;let l=this.delegate.currentChapterLink.href;var u=this.publication.getAbsoluteHref(t);let d=this.bookSearchResult.filter(f=>f.href===t);if(r?(a=this.currentChapterSearchResult.filter(f=>f.uuid===n)[0],o=this.currentChapterSearchResult.findIndex(f=>f.uuid===n)):(a=d.filter(f=>f.uuid===n)[0],o=d.findIndex(f=>f.uuid===n)),a!==void 0)if(l===u)this.jumpToMark(o);else{let g={href:u,locations:{progression:0},title:"title"};this.delegate.navigate(g),setTimeout(()=>{this.searchAndPaintChapter(a.textMatch,o,async()=>{})},300)}}async goToSearchIndex(t,n,r){var o=n,a;let l=this.delegate.currentChapterLink.href;var u=this.publication.getAbsoluteHref(t);let d=this.bookSearchResult.filter(f=>f.href===t);if(r?a=this.currentChapterSearchResult[o]:a=d[o],a!==void 0)if(l===u)this.jumpToMark(o);else{let g={href:u,locations:{progression:0},title:"title"};this.delegate.navigate(g),setTimeout(()=>{this.searchAndPaintChapter(a.textMatch,o,async()=>{})},300)}}async handleSearchBook(){var t=this,n=this.searchInput.value;if(t.headerMenu)var r=de(document,"#searchResultBook");o(1);async function o(l){r.innerHTML="";var u,d=await t.searchBook(n);if(u=t.paginate(d,l,10),u.total===0){let f=document.createElement("a");f.className="collection-item",f.innerHTML="nothing found",r.appendChild(f)}else{a(u.data,w=>w.href).forEach(w=>{let b=document.createElement("div");if(b.style.marginBottom="10px",w[0].title){let m=document.createElement("span");m.className="collection-item",m.style.display="block",m.innerHTML=w[0].title,b.appendChild(m)}r.appendChild(b),w.forEach(m=>{let E=document.createElement("a");E.className="collection-item";var O=t.publication.getAbsoluteHref(m.href);E.innerHTML="..."+m.textBefore+"<mark>"+m.textMatch+"</mark>"+m.textAfter+"...",ne(E,"click",_=>{_.preventDefault(),_.stopPropagation();let T=d.filter(j=>j.href===m.href).findIndex(j=>j===m);if(t.delegate.currentChapterLink.href===O)t.jumpToMark(T);else{let P={href:O,locations:{progression:0},title:"title"};t.delegate.navigate(P),setTimeout(()=>{t.handleSearchChapter(T)},300)}}),b.appendChild(E)})});let g=document.createElement("div");g.style.textAlign="center",g.style.marginTop="10px";let y=document.createElement("ul");y.className="pagination";let v=document.createElement("li");if(v.className="disabled",v.innerHTML='<a href="#!"> < </a>',u.pre_page!=null){let w=u.pre_page;v.className="waves-effect",ne(v,"click",b=>{b.preventDefault(),b.stopPropagation(),o(w)})}y.appendChild(v);for(let w=1;w<=u.total_pages;w++){let b,m=document.createElement("li");m.className="waves-effect",w===u.page&&(m.className="active",b=m),m.innerHTML='<a href="#!">'+w+"</a>",ne(m,"click",E=>{E.preventDefault(),E.stopPropagation(),b&&(b.className="waves-effect"),m.className="active",b=m,o(w)}),y.appendChild(m)}let S=document.createElement("li");if(S.className="disabled",S.innerHTML='<a href="#!"> > </a>',u.next_page!=null){let w=u.next_page;S.className="waves-effect",ne(S,"click",b=>{b.preventDefault(),b.stopPropagation(),o(w)})}y.appendChild(S),g.appendChild(y),r.appendChild(g)}}function a(l,u){let d=new Map;return l.forEach(f=>{let g=u(f),y=d.get(g);y?y.push(f):d.set(g,[f])}),Array.from(d.values())}}async searchBook(t){this.bookSearchResult=[];let n=[];for(let r=0;r<this.publication.readingOrder.length;r++){let o=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[r].Href:""),a=this.publication.getTOCItem(o);if(a===void 0&&this.publication.readingOrder&&(a=this.publication.readingOrder[r]),a){let l=this.publication.getAbsoluteHref(a.Href);await fetch(l,this.delegate.requestConfig).then(u=>u.text()).then(async u=>{let f=new DOMParser().parseFromString(this.delegate.requestConfig?.encoded?this.decodeBase64(u):u,"application/xhtml+xml");a&&Js(t,f,a.Href,a.Title).then(g=>{g.forEach(y=>{n.push(y),this.bookSearchResult.push(y)})})})}if(r===this.publication.readingOrder.length-1)return n}}decodeBase64(t){let n=atob(t),r=n.length,o=new Uint8Array(r);for(let l=0;l<r;l++)o[l]=n.charCodeAt(l);return new TextDecoder().decode(o)}async searchChapter(t){let n=[],r=this.publication.getAbsoluteHref(this.publication.readingOrder[this.delegate.currentResource()??0].Href),o=this.publication.getTOCItem(r);if(o===null&&(o=this.publication.readingOrder[this.delegate.currentResource()??0]),o){let a=this.publication.getAbsoluteHref(o.Href);await fetch(a,this.delegate.requestConfig).then(l=>l.text()).then(async l=>{let d=new DOMParser().parseFromString(this.delegate.requestConfig?.encoded?this.decodeBase64(l):l,"application/xhtml+xml");o&&Js(t,d,o.Href,o.Title).then(f=>{f.forEach(g=>{n.push(g)})})})}return n}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(t=>{let n={rangeInfo:t.rangeInfo};if(this.properties?.color){let r=this.createSearchHighlight(n,this.properties?.color);t.highlight=r,this.currentSearchHighlights.push(r)}})},100)}async handleResize(){await this.highlighter?.destroyHighlights(qe.Search),this.drawSearch()}jumpToMark(t){setTimeout(()=>{if(this.currentChapterSearchResult.length){var n=this.currentChapterSearchResult[t];this.currentSearchHighlights.forEach(o=>{var a=this.properties?.color;De.isHexColor(a)&&(a=De.hexToRgbChannels(a)),o.color=a});var r=this.properties?.current;De.isHexColor(r)&&(r=De.hexToRgbChannels(r)),n.highlight.color=r,this.highlighter?.setAndResetSearchHighlight(n.highlight,this.currentSearchHighlights),this.delegate.view?.goToCssSelector(n.rangeInfo.startContainerElementCssSelector),this.delegate.updatePositionInfo()}},200)}paginate(t,n,r){let o=n||1,a=r||10,l=(o-1)*a,u=t.slice(l).slice(0,a),d=Math.ceil(t.length/a);return{page:o,per_page:a,pre_page:o-1?o-1:void 0,next_page:d>o?o+1:void 0,total:t.length,total_pages:d,data:u}}};C();var Kn=Je(Dt()),ao=class{},Be=ao;Be.COLOR_REF="color",Be.AUTO_SCROLL_REF="autoscroll",Be.RATE_REF="rate",Be.PITCH_REF="pitch",Be.VOLUME_REF="volume",Be.VOICE_REF="voice",Be.COLOR_KEY="tts-"+ao.COLOR_REF,Be.AUTO_SCROLL_KEY="tts-"+ao.AUTO_SCROLL_REF,Be.RATE_KEY="tts-"+ao.RATE_REF,Be.PITCH_KEY="tts-"+ao.PITCH_REF,Be.VOLUME_KEY="tts-"+ao.VOLUME_REF,Be.VOICE_KEY="tts-"+ao.VOICE_REF;var ng=class{constructor(t,n,r){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=r,this.initialise()}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialTTSSettings){let r=t.initialTTSSettings;r?.rate&&(n.rate=r.rate,Kn.default.log(n.rate)),r?.pitch&&(n.pitch=r.pitch,Kn.default.log(n.pitch)),r?.volume&&(n.volume=r.volume,Kn.default.log(n.volume)),r?.color&&(n.color=r.color,Kn.default.log(n.color)),r?.autoScroll&&(n.autoScroll=r.autoScroll,Kn.default.log(n.autoScroll)),r?.voice&&(n.voice=r.voice,Kn.default.log(n.voice))}return n.initializeSelections(),n}stop(){Kn.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(Be.AUTO_SCROLL_KEY)!=null?this.getProperty(Be.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(Be.RATE_KEY)!=null?this.getProperty(Be.RATE_KEY).value:this.rate,this.pitch=this.getProperty(Be.PITCH_KEY)!=null?this.getProperty(Be.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(Be.VOLUME_KEY)!=null?this.getProperty(Be.VOLUME_KEY).value:this.volume,this.color=this.getProperty(Be.COLOR_KEY)!=null?this.getProperty(Be.COLOR_KEY).value:this.color,this.voice=this.getProperty(Be.VOICE_REF)!=null?this.getProperty(Be.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=de(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechRate=de(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=de(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=de(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=de(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),ne(de(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(Be.RATE_REF)?.value,pitch:this.userProperties.getByRef(Be.PITCH_REF)?.value,volume:this.userProperties.getByRef(Be.VOLUME_REF)?.value,voice:this.userProperties.getByRef(Be.VOLUME_REF)?.value,color:this.userProperties.getByRef(Be.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Be.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{Kn.default.log("api updated tts settings",n)})}getTTSSettings(){var t=new Si;return t.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,Be.AUTO_SCROLL_REF,Be.AUTO_SCROLL_KEY),t.addIncremental(this.rate,.1,10,.1,"",Be.RATE_REF,Be.RATE_KEY),t.addIncremental(this.pitch,.1,2,.1,"",Be.PITCH_REF,Be.PITCH_KEY),t.addIncremental(this.volume,.1,1,.1,"",Be.VOLUME_REF,Be.VOLUME_KEY),t.addStringable(this.color,Be.COLOR_REF,Be.COLOR_KEY),t.addJSONable(JSON.stringify(this.voice),Be.VOICE_REF,Be.VOICE_KEY),t}saveProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let r=JSON.parse(n);r=r.filter(o=>o.name!==t.name),r.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(r))}else{let r=[];r.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(r))}return t}getProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let r=JSON.parse(n);return r=r.filter(o=>o.name===t),r.length===0?void 0:r[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(t){if(t.rate){Kn.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Be.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.pitch){Kn.default.log("pitch "+this.pitch),this.pitch=t.pitch;let n=this.userProperties.getByRef(Be.PITCH_REF);n&&(n.value=this.pitch,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.volume){Kn.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Be.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(Be.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){Kn.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Be.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.voice){Kn.default.log("voice "+this.voice),this.voice=t.voice;let n=this.userProperties.getByRef(Be.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,r=t.indexOf(":")!==-1?t.slice(t.indexOf(":")+1):t;n!==void 0&&r!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:n,lang:r}}):r!==void 0&&n===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:r}})}increase(t){if(t==="rate"){this.userProperties.getByRef(Be.RATE_REF).increment();let n=this.userProperties.getByRef(Be.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(Be.PITCH_REF).increment();let n=this.userProperties.getByRef(Be.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(Be.VOLUME_REF).increment();let n=this.userProperties.getByRef(Be.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}decrease(t){if(t==="rate"){this.userProperties.getByRef(Be.RATE_REF).decrement();let n=this.userProperties.getByRef(Be.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(Be.PITCH_REF).decrement();let n=this.userProperties.getByRef(Be.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(Be.VOLUME_REF).decrement();let n=this.userProperties.getByRef(Be.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}};C();C();var _3=`${$r.loading}`,T3=`
76
76
  <span>
77
77
  ${$r.error}
78
78
  </span>
79
79
  <span>There was an error loading this page.</span>
80
80
  <button class="go-back">Go back</button>
81
81
  <button class="try-again">Try again</button>
82
- `;var zd=Je(Qi());C();var Ks=class{constructor(t){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{let n=null,r=null,o=this;t&&(t.addEventListener("touchstart",function(a){a.changedTouches.length===1&&(n=a)},!1),t.addEventListener("touchend",function(a){if(a.changedTouches.length!==1||!n)return;let l=n.changedTouches[0],u=a.changedTouches[0];if(!l)return;let d=window.devicePixelRatio,f=(l.clientX-u.clientX)/d,g=(l.clientY-u.clientY)/d;if(Math.abs(f)<Ks.TAP_TOLERANCE&&Math.abs(g)<Ks.TAP_TOLERANCE){if(r){n=null,r=null;return}if(a.timeStamp-n.timeStamp>Ks.LONG_PRESS_MS){n=null,r=null;return}n=null,r=a;return}if(r=null,a.timeStamp-n.timeStamp>Ks.SLOW_SWIPE_MS){n=null;return}let y=(l.clientY-u.clientY)/(l.clientX-u.clientX);if(Math.abs(y)>.5){n=null;return}f<0?o.onBackwardSwipe(a):o.onForwardSwipe(a),n=null},!1))};this.navigator=t}},Go=Ks;Go.TAP_TOLERANCE=10,Go.LONG_PRESS_MS=500,Go.SLOW_SWIPE_MS=500;C();var $d=class{constructor(t){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{t&&(this.focusin(t),this.keydown(t))};this.focusin=t=>{let n=this;t.addEventListener("focusin",function(r){n.navigator.view?.snap(r.target)},!0)};this.keydown=t=>{let n=this;this.navigator.rights.customKeyboardEvents||t.addEventListener("keydown",function(r){let o=r.target;if(/input|select|option|textarea/i.test(o.tagName)||!(o.ownerDocument||o).defaultView.getSelection().isCollapsed)return;switch(r.key){case"ArrowRight":n.onForwardSwipe(r);break;case"ArrowLeft":n.onBackwardSwipe(r);break}},!1)};this.navigator=t}};C();var A3=Je(Qi()),Ud=class{constructor(t){this.enforceSampleRead=(0,A3.debounce)(t=>{let n=Math.round(t.locations.totalProgression*100),r=!1;this.delegate.sample?.limit&&(r=n<=this.delegate.sample?.limit,this.delegate.view?.layout==="fixed"&&!r&&this.delegate.sample?.minimum&&t.locations.position<=this.delegate.sample?.minimum&&(r=!0));let o={37:1,38:0,39:1,40:1,32:1,33:1,34:1,35:1,36:1};function a(w){w.preventDefault()}function l(w){o[w.keyCode]&&!r&&a(w)}let u=!1,d=Object.defineProperty&&Object.defineProperty({},"passive",{get:function(){u=!0}});window.addEventListener("test",function(){},d);let f=u?{passive:!1}:!1;function g(w){w=w||window.event;let b=Math.max(-1,Math.min(1,w.wheelDelta||-w.detail));return b===-1&&!r&&w.preventDefault(),!1}let y;function v(w){w=w||window.event;let b=w.target||w.srcElement,m=w.touches[0].clientY;if(!(m>y)){if(m<y&&!r)return b.className.match(/\baltNav\b/)||(w.returnValue=!1,w.cancelable&&(w.cancelBubble=!0),w.preventDefault&&w.cancelable&&(w.preventDefault(),w.stopPropagation())),!1}return y=m,!1}function S(w){return w=w||window.event,y=w.touches[0].clientY,!1}window.addEventListener("mousewheel",g,f),window.addEventListener("DOMMouseScroll",g,f),window.addEventListener("keydown",l,f),window.addEventListener("touchmove",v,f),window.addEventListener("touchstart",S,f),r?(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 M3=Je(R3()),Yn=Je(Dt()),Ln=class extends M3.default{constructor(t,n=void 0,r=void 0,o,a,l,u,d,f,g,y,v){super();this.iframes=[];this.sideNavExpanded=!1;this.currentChapterLink={href:""};this.currentSpreadLinks={};this.rights={autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};this.didInitKeyboardEventHandler=!1;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.reload=async()=>{let t;if(this.annotator&&(t=await this.annotator.getLastReadingPosition()),t){let n=this.publication.getAbsoluteHref(t.href);Yn.default.log(t.href),Yn.default.log(n),t.href=n,await this.navigate(t)}};this.savePosition=(0,zd.debounce)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,zd.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=f,this.view.delegate=this,this.eventHandler=new pd(this),this.touchEventHandler=new Go(this),this.keyboardEventHandler=new $d(this),this.initialLastReadingPosition=r,this.publication=o,this.api=a,this.rights=l??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1},this.tts=u,this.injectables=d,this.attributes=f||{margin:0},this.services=g,this.sample=y,this.requestConfig=v,this.sampleReadEventHandler=new Ud(this)}static async create(t){let n=new this(t.settings,t.annotator||void 0,t.initialLastReadingPosition||void 0,t.publication,t.api,t.rights,t.tts,t.injectables,t.attributes||{margin:0},t.services,t.sample,t.requestConfig);return await n.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(r=>r(n))}stop(){Yn.default.log("Iframe navigator stop"),Pe(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),Pe(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),Pe(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Pe(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),Pe(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Pe(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),Pe(this.tryAgainButton,"click",this.tryAgain.bind(this)),Pe(this.goBackButton,"click",Ln.goBack.bind(this)),Pe(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),Pe(window,"resize",this.onResize),this.iframes.forEach(t=>{Pe(t,"resize",this.onResize)})}async start(t,n,r){this.headerMenu=n,this.mainElement=t;try{let S=dt(t,"main#iframe-wrapper");S.style.overflow="auto";let w=de(t,"main#iframe-wrapper iframe"),b=de(t,"#second");if(w&&this.iframes.push(w),b&&this.iframes.push(b),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.iframes.length===0){S.style.overflow="auto";let m=document.createElement("iframe");if(m.setAttribute("SCROLLING","no"),m.setAttribute("allowtransparency","true"),this.iframes.push(m),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]),S.appendChild(this.spreads)):(m.setAttribute("height","100%"),m.setAttribute("width","100%"),S.appendChild(this.iframes[0])),this.publication.isFixedLayout)if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){let E=document.createElement("div");this.spreads.appendChild(E);let O=document.createElement("iframe");O.setAttribute("SCROLLING","no"),O.setAttribute("allowtransparency","true"),O.style.opacity="1",O.style.border="none",O.style.overflow="hidden",this.iframes.push(O),E.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",E.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",E.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 m=S.clientHeight;var o=this.iframes[0].parentElement?.parentElement;o.style.height=m+40+"px"}else this.iframes.length===2&&this.iframes.pop();if(this.loadingMessage=de(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=_3,this.loadingMessage.style.display="none"),this.errorMessage=de(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=T3,this.errorMessage.style.display="none"),this.tryAgainButton=de(t,"button[class=try-again]"),this.goBackButton=de(t,"button[class=go-back]"),this.infoTop=de(t,"div[class='info top']"),this.infoBottom=de(t,"div[class='info bottom']"),this.headerMenu&&(this.bookTitle=de(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=de(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=de(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=de(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=de(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=de(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=de(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=de(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=de(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=de(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=de(this.headerMenu,"#container-view-pagelist")),r&&(this.linksBottom=de(r,"ul.links.bottom")),r&&(this.linksMiddle=de(r,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=de(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=de(t,"#next-chapter")),r&&(this.nextPageAnchorElement=de(r,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=de(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=de(t,"#previous-chapter")),r&&(this.previousPageAnchorElement=de(r,"a[rel=prev]")),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.newPosition=void 0,this.newElementId=void 0,this.isBeingStyled=!0,this.isLoading=!0,this.settings.setIframe(this.iframes[0]),this.settings.onSettingsChange(this.handleResize.bind(this)),this.settings.onColumnSettingsChange(this.handleNumberOfIframes.bind(this)),this.settings.onViewChange(this.updateBookView.bind(this)),this.initialLastReadingPosition&&this.annotator?.initLastReadingPosition(this.initialLastReadingPosition),this.headerMenu){var a=de(this.headerMenu,"#menu-button-search"),l=de(this.headerMenu,"#menu-button-tts"),u=de(this.headerMenu,"#menu-button-bookmark"),d=de(this.headerMenu,"#menu-button-play"),f=de(this.headerMenu,"#menu-button-pause"),g=de(this.headerMenu,"#menu-button-mediaoverlay");if(!this.rights.enableBookmarks){u&&u.parentElement?.style.setProperty("display","none");var y=de(this.headerMenu,"#sidenav-section-bookmarks");y&&y.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var v=de(this.headerMenu,"#sidenav-section-highlights");v&&v.style.setProperty("display","none")}this.rights.enableTTS||l&&l.parentElement?.style.setProperty("display","none"),this.rights.enableSearch||a&&a.parentElement?.style.setProperty("display","none"),a&&this.view?.delegate.publication.isFixedLayout&&a.parentElement?.style.setProperty("display","none"),this.hasMediaOverlays?(d&&d.parentElement?.style.removeProperty("display"),f&&f.parentElement?.style.removeProperty("display"),g&&g.parentElement?.style.removeProperty("display")):(d&&d.parentElement?.style.setProperty("display","none"),f&&f.parentElement?.style.setProperty("display","none"),g&&g.parentElement?.style.setProperty("display","none"))}else a&&a.parentElement?.style.setProperty("display","none"),l&&l.parentElement?.style.setProperty("display","none"),u&&u.parentElement?.style.setProperty("display","none");return this.setupEvents(),await this.loadManifest()}catch(S){return Yn.default.error(S),this.abortOnError(S),Promise.reject(S)}}setupEvents(){for(let t of this.iframes)ne(t,"load",this.handleIFrameLoad.bind(this));ne(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),ne(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),ne(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ne(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),ne(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ne(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),ne(this.tryAgainButton,"click",this.tryAgain.bind(this)),ne(this.goBackButton,"click",Ln.goBack.bind(this)),ne(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),ne(window,"resize",this.onResize);for(let t of this.iframes)ne(t,"resize",this.onResize)}updateBookView(){this.view?.layout==="fixed"?(this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousChapterClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextChapterClick.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this))):(this.settings.isPaginated().then(t=>{if(t)this.view.height=Fr()-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,zd.debounce)(()=>{this.isScrolling=!1},200),r=dt(document,"#iframe-wrapper");r.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(qe.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(qe.Search),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule!==void 0&&this.highlighter!==void 0&&await this.definitionsModule.drawDefinitions()},200))}async loadManifest(){try{let t=(d,f,g=!1)=>{var y=document.createElement("ul");g&&(y=document.createElement("ol")),y.className="sidenav-toc";for(let v of f){let S=document.createElement("li"),w=document.createElement("a"),b=document.createElement("span");w.className="chapter-link",w.tabIndex=-1;let m="";v.Href?(m=this.publication.getAbsoluteHref(v.Href),w.href=m,w.innerHTML=v.Title||"",S.appendChild(w)):(b.innerHTML=v.Title||"",b.className="chapter-title",S.appendChild(b)),v.Children&&v.Children.length>0&&t(S,v.Children,!0),y.appendChild(S)}ne(y,"click",v=>{if(v.preventDefault(),v.stopPropagation(),v.target&&v.target.tagName.toLowerCase()==="a"){let S=v.target;if(S.className.indexOf("active")!==-1)this.hideView();else{let w={progression:0};if(S.href.indexOf("#")!==-1){let m=S.href.slice(S.href.indexOf("#")+1);m!==void 0&&(w={fragment:m})}let b={href:S.href,locations:w,type:S.type,title:S.title};this.hideView(),this.navigate(b)}}}),d.appendChild(y)},n=this.publication.tableOfContents,r=this.publication.landmarks,o=this.publication.pageList;this.tocView&&(n.length?t(this.tocView,n):this.tocView.parentElement?.parentElement?.removeChild(this.tocView.parentElement)),this.pageListView&&(o?.length?t(this.pageListView,o):this.pageListView.parentElement?.parentElement?.removeChild(this.pageListView.parentElement)),this.landmarksView&&(r?.length?t(this.landmarksView,r):this.landmarksSection.parentElement?.removeChild(this.landmarksSection));let a;this.annotator&&(a=await this.annotator.getLastReadingPosition());let l=this.publication.getStartLink(),u;if(l&&l.Href&&(u=this.publication.getAbsoluteHref(l.Href)),a){let d=this.publication.getAbsoluteHref(a.href);Yn.default.log(a.href),Yn.default.log(d),a.href=d,await this.navigate(a)}else if(u){let d={href:u,locations:{progression:0},created:new Date,title:l?.Title};await this.navigate(d)}return new Promise(d=>d())}catch(t){return Yn.default.error(t),this.abortOnError(t),new Promise((n,r)=>r(t)).catch(()=>{})}}async handleIFrameLoad(){this.errorMessage&&(this.errorMessage.style.display="none"),this.showLoadingMessageAfterDelay();try{let t=0;this.newPosition&&(t=this.newPosition.locations.progression),await this.handleResize(),this.updateBookView(),await this.settings.applyProperties();let n=this.currentChapterLink.href;if(n){let d=this.publication.getPreviousSpineItem(n);d&&d.Href&&(this.previousChapterLink={href:d.Href,title:d.Title,type:d.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 r=this.publication.getNextSpineItem(n);r?this.nextChapterLink={href:r.Href,title:r.Title,type:r.TypeLink}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink&&this.nextChapterLink.href?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.historyModule&&this.historyModule.setup(),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(n),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let o=this.publication.getSpineItem(n);o!==void 0&&(this.currentChapterLink.title=o.Title,this.currentChapterLink.type=o.TypeLink);let a=this.publication.getTOCItem(n);this.currentTocUrl!==void 0&&(a=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&a!==void 0&&a.Title&&(this.currentChapterLink.title=a.Title),!this.currentChapterLink.type&&a!==void 0&&a.TypeLink&&(this.currentChapterLink.title=a.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),await this.injectInjectablesIntoIframeHead(),this.highlighter!==void 0&&await this.highlighter.initialize();let u=this.iframes[0].contentDocument?.body?.querySelector("details");if(u){let d=this;u.addEventListener("toggle",async f=>{await d.view?.setIframeHeight?.(this.iframes[0])})}if(this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.initialize(),this.eventHandler){for(let d of this.iframes)this.eventHandler.setupEvents(d.contentDocument),this.touchEventHandler.setupEvents(d.contentDocument),this.keyboardEventHandler.setupEvents(d.contentDocument);this.touchEventHandler.setupEvents(this.errorMessage),this.didInitKeyboardEventHandler||(this.keyboardEventHandler.keydown(document),this.didInitKeyboardEventHandler=!0)}if(this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(this.iframes[0].height="0",this.view?.setIframeHeight?.(this.iframes[0])),this.annotationModule!==void 0&&await this.annotationModule.initialize(),this.bookmarkModule!==void 0&&await this.bookmarkModule.initialize(),this.rights.enableTTS)for(let d of this.iframes){let f=d.contentDocument?.body;this.ttsModule!==void 0&&await this.ttsModule.initialize(f)}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 d=this.iframes[0].contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(d),this.newElementId=void 0}else if(this.newPosition&&this.newPosition.highlight){let d=this.newPosition.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;d&&this.view?.goToCssSelector(d)}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 d=this.currentLink();await this.mediaOverlayModule?.initializeResource(d)}await this.updatePositionInfo(),await this.view?.setSize(),setTimeout(()=>{this.mediaOverlayModule!==void 0&&(this.mediaOverlayModule.settings.resourceReady=!0)},300)},200),new Promise(d=>d())}catch(t){return Yn.default.error(t),this.abortOnError(t),Promise.reject(t)}}async injectInjectablesIntoIframeHead(){let t=[],n=r=>{let o=new Promise((a,l)=>{r.onload=()=>{a(!0)},r.onerror=u=>{let d=typeof u=="string"?u:`Injectable failed to load at: ${"href"in r?r.href:r.src}`;l(new Error(d))}});t.push(o)};for(let r of this.iframes){let o=r.contentDocument?.head;o&&(r.contentDocument.getElementsByTagName("base").length===0&&o.insertBefore(Ln.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 u=Ln.createCssLink(l.url);o.appendChild(u),n(u)}}else if(l.r2before&&l.url){let u=Ln.createCssLink(l.url);o.insertBefore(u,o.firstChild),n(u)}else if(l.r2default&&l.url){let u=Ln.createCssLink(l.url);o.insertBefore(u,o.childNodes[1]),n(u)}else if(l.r2after&&l.url){l.appearance&&this.settings.initAddedAppearance();let u=Ln.createCssLink(l.url);o.appendChild(u),n(u)}else if(l.url){let u=Ln.createCssLink(l.url);o.appendChild(u),n(u)}}else if(l.type==="script"&&l.url){let u=Ln.createJavascriptLink(l.url,l.async??!1);o.appendChild(u),n(u)}}))}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),r=(n??0)%2==1;this.showLoadingMessageAfterDelay();function o(d,f){let y=new DOMParser().parseFromString(d,"application/xhtml+xml");y.head&&y.getElementsByTagName("base").length===0&&y.head.insertBefore(Ln.createBase(f),y.head.firstChild);let v=y.documentElement.outerHTML,S=t.iframes[0].contentDocument;S&&(S.open(),S.write(v),S.close())}function a(d,f){let y=new DOMParser().parseFromString(d,"application/xhtml+xml");y.head&&y.getElementsByTagName("base").length===0&&y.head.insertBefore(Ln.createBase(f),y.head.firstChild);let v=y.documentElement.outerHTML,S=t.iframes[1].contentDocument;S&&(S.open(),S.write(v),S.close())}let l=new URL(this.currentChapterLink.href),u=window.location.protocol===l.protocol&&window.location.port===l.port&&window.location.hostname===l.hostname;if(this.api?.getContent)if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(r){if(this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(d=>{d===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(f=>f.text()).then(async f=>{o.call(this,f,this.currentChapterLink.href)}):o.call(this,d,this.currentChapterLink.href)}),this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let d=this.publication.getNextSpineItem(this.currentChapterLink.href);if(d){let f=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.right={href:f},this.api?.getContent(f).then(g=>{g===void 0?u?this.iframes[1].src=f:fetch(f,this.requestConfig).then(y=>y.text()).then(async y=>{a.call(this,y,f),this.currentSpreadLinks.right={href:f}}):a.call(this,g,f)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let d=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(d){let f=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.left={href:f},this.api?.getContent(f).then(g=>{g===void 0?u?this.iframes[0].src=f:fetch(f,this.requestConfig).then(y=>y.text()).then(async y=>{o.call(this,y,f)}):o.call(this,g,f)})}}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(d=>{d===void 0?u?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(f=>f.text()).then(async f=>{a.call(this,f,this.currentChapterLink.href)}):a.call(this,d,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(d=>{d===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(f=>f.text()).then(async f=>{o.call(this,f,this.currentChapterLink.href)}):o.call(this,d,this.currentChapterLink.href)});else this.api?.getContent(this.currentChapterLink.href).then(d=>{this.currentSpreadLinks.left={href:this.currentChapterLink.href},d===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(f=>f.text()).then(async f=>{o.call(this,f,this.currentChapterLink.href)}):o.call(this,d,this.currentChapterLink.href)});else if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(r){if(u){if(this.iframes[0].src=this.currentChapterLink.href,this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let d=this.publication.getNextSpineItem(this.currentChapterLink.href);if(d){let f=this.publication.getAbsoluteHref(d.Href);this.iframes[1].src=f,this.currentSpreadLinks.right={href:f}}}else this.iframes[1].src="about:blank"}else if(fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)}),this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let d=this.publication.getNextSpineItem(this.currentChapterLink.href);if(d){let f=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.right={href:f},fetch(f,this.requestConfig).then(g=>g.text()).then(async g=>{a.call(this,g,f)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let d=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(d){let f=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.left={href:f},u?(this.iframes[0].src=f,this.iframes.length===2&&(this.iframes[1].src=this.currentChapterLink.href)):(fetch(f,this.requestConfig).then(g=>g.text()).then(async g=>{o.call(this,g,f)}),this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},fetch(this.currentChapterLink.href,this.requestConfig).then(g=>g.text()).then(async g=>{a.call(this,g,this.currentChapterLink.href)})))}}else this.iframes[0].src="about:blank";this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},u?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{a.call(this,d,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)});else this.currentSpreadLinks.left={href:this.currentChapterLink.href},u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)});this.publication.isFixedLayout&&setTimeout(()=>{let d,f,g;if(n===0&&this.iframes?.length===2?g=this.iframes[1].contentDocument:g=this.iframes[0].contentDocument,g&&g.body&&(d=getComputedStyle(g.body).height,f=getComputedStyle(g.body).width,parseInt(d?.replace("px",""))===0||parseInt(f?.replace("px",""))===0)){let E=Qt(g,"head");if(E){let O=de(E,"meta[name=viewport]");if(O){var y=O.content,v=y.split(",").reduce((_,A)=>{var[T,M]=A.match(/[^\s;=]+/g);return _[T]=isNaN(Number(M))?M:+M,_},{});d=v.height+"px",f=v.width+"px"}}}var S=n===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(S&&f){var w=(parseInt(getComputedStyle(S).width)-100)/(this.iframes.length===2?parseInt(f?.replace("px",""))*2+200:parseInt(f?.replace("px",""))),b=(parseInt(getComputedStyle(S).height)-100)/parseInt(d?.replace("px","")),m=Math.min(w,b);S.style.transform="scale("+m+")";for(let E of this.iframes)E.style.height=d,E.style.width=f,E.parentElement&&(E.parentElement.style.height=d)}},400)}static goBack(){window.history.back()}handleEditClick(t){var n=t.target;if(this.headerMenu){var r=de(document,".sidenav");n.className.indexOf(" active")===-1?(n.className+=" active",r.className+=" expanded",n.innerText="unfold_less",this.sideNavExpanded=!0,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights()):(n.className=n.className.replace(" active",""),r.className=r.className.replace(" expanded",""),n.innerText="unfold_more",this.sideNavExpanded=!1,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights())}t.preventDefault(),t.stopPropagation()}get hasMediaOverlays(){return this.publication.hasMediaOverlays}startReadAloud(){this.rights.enableTTS&&this.ttsModule.speakPlay()}startReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.startReadAloud()}stopReadAloud(){this.rights.enableTTS&&this.highlighter?.stopReadAloud()}stopReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.stopReadAloud()}pauseReadAloud(){this.rights.enableTTS&&(this.ttsModule.speakPause(),this.annotationModule!==void 0&&this.annotationModule.drawHighlights())}pauseReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.pauseReadAloud()}resumeReadAloud(){this.rights.enableTTS&&this.ttsModule.speakResume()}resumeReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.resumeReadAloud()}totalResources(){return this.publication.readingOrder.length}mostRecentNavigatedTocItem(){return this.publication.getRelativeHref(this.currentTOCRawLink)}currentResource(){let t=this.currentChapterLink.href;return this.publication.getSpineIndex(t)}currentLink(){if(this.settings.columnCount!==1&&this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0){let n=this.publication.getSpineItem(this.currentSpreadLinks.left.href),r=this.publication.getSpineItem(this.currentSpreadLinks.right.href);return[n,r]}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 a=t.href.slice(t.href.indexOf("#")+1);a!==void 0&&(n=jt(Fe({},n),{fragment:a}))}let r=Fe({},t);r.locations=n;let o=this.publication.getAbsoluteHref(t.href);Yn.default.log(t.href),Yn.default.log(o),r.href=o,this.stopReadAloud(),this.navigate(r)}currentLocator(){let t;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let n=this.publication.positionsByHref(this.publication.getRelativeHref(this.currentChapterLink.href)),r=Math.ceil((this.view?.getCurrentPosition()??0)*(n.length-1));t=n[r]}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(r=>r.locations.position===parseInt(String(t)))[0];this.goTo(n)}}snapToSelector(t){let n=this.iframes[0].contentDocument;if(n){Yn.default.log(t);let r=n.querySelectorAll(t);r.length>0&&this.view?.snap(r[0])}}applyAttributes(t){this.attributes=t,this.view.attributes=t,this.handleResize()}handlePreviousPageClick(t){this.stopReadAloud(),this.view?.layout==="fixed"?this.handlePreviousChapterClick(t):(this.view?.atStart()?this.handlePreviousChapterClick(t):(this.view?.goToPreviousPage?.(),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))}handleNextPageClick(t){let n=!0;if(this.sample?.isSampleRead&&this.publication.positions){let r=this.currentLocator(),o=Math.round((r.locations.totalProgression??0)*100);this.sample?.limit&&(n=o<=this.sample?.limit,this.view?.layout==="fixed"&&((!n&&this.sample?.minimum&&r.locations.position)??0<=(this.sample?.minimum??0))&&(n=!0))}(n&&this.sample?.isSampleRead&&this.publication.positions||!this.sample?.isSampleRead||!this.publication.positions)&&(this.stopReadAloud(),this.view?.layout==="fixed"?this.handleNextChapterClick(t):(this.view?.atEnd()?this.handleNextChapterClick(t):(this.view?.goToNextPage?.(),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))),!n&&this.sample?.isSampleRead&&this.publication.positions&&t&&(t.preventDefault(),t.stopPropagation())}handleClickThrough(t){}handleInternalLink(t){let n=t.target,r={progression:0},o=n;if(o.href.indexOf("#")!==-1){let l=o.href.slice(o.href.indexOf("#")+1);l!==void 0&&(r={fragment:l})}let a={href:o.href,locations:r,type:o.type,title:o.title};t.preventDefault(),t.stopPropagation(),this.stopReadAloud(),this.navigate(a)}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 f=Fr()-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=f+40+"px";let g,y,v;t===0&&this.iframes?.length===2?v=this.iframes[1].contentDocument:v=this.iframes[0].contentDocument,v&&v.body&&(g=getComputedStyle(v.body).height,y=getComputedStyle(v.body).width);let S=Qt(v,"head");if(S){let w=de(S,"meta[name=viewport]");if(w){var r=w.content,o=r.split(",").reduce((b,m)=>{var[E,O]=m.match(/[^\s;=]+/g);return b[E]=isNaN(Number(O))?O:+O,b},{});(parseInt(o.height)!==0||parseInt(o.width)!==0)&&(g=o.height+"px",y=o.width+"px")}}var a=(parseInt(getComputedStyle(n).width)-100)/(this.iframes.length===2?parseInt(y?.replace("px",""))*2+200:parseInt(y?.replace("px",""))),l=(parseInt(getComputedStyle(n).height)-100)/parseInt(g?.replace("px","")),u=Math.min(a,l);n.style.transform="scale("+u+")";for(let w of this.iframes)w.style.height=g,w.style.width=y,w.parentElement&&(w.parentElement.style.height=g)}}let d=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(f=>{f?(this.view.height=Fr()-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()=>{d&&this.view?.goToProgression(d),await this.updatePositionInfo(!1),this.annotationModule!==void 0&&await this.annotationModule.handleResize(),this.bookmarkModule!==void 0&&await this.bookmarkModule.handleResize(),this.searchModule!==void 0&&await this.searchModule.handleResize(),this.definitionsModule!==void 0&&await this.definitionsModule.handleResize(),this.pageBreakModule!==void 0&&await this.pageBreakModule.handleResize(),this.contentProtectionModule!==void 0&&this.contentProtectionModule.handleResize(),this.lineFocusModule!==void 0&&this.lineFocusModule.handleResize(),this.historyModule!==void 0&&this.historyModule.handleResize()},150)}updatePositionInfo(t=!0){if(this.view?.layout==="fixed")this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");else if(this.view?.isPaginated()){let n=this.currentLocator();if(n){let r=n.displayInfo.resourceScreenIndex,o=n.displayInfo.resourceScreenCount;this.chapterPosition&&(this.chapterPosition.innerHTML="Page "+r+" 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 r=this.publication.readingOrder[n],o={href:this.publication.getAbsoluteHref(r.Href),locations:{progression:0},type:r.TypeLink,title:r.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 r=this.publication.readingOrder[n],o={href:this.publication.getAbsoluteHref(r.Href),locations:{progression:0},type:r.TypeLink,title:r.Title};this.stopReadAloud(),this.navigate(o)}else if(this.nextChapterLink){let n={href:this.publication.getAbsoluteHref(this.nextChapterLink.href),locations:{progression:0},type:this.nextChapterLink.type,title:this.nextChapterLink.title};this.stopReadAloud(),this.navigate(n)}t&&(t.preventDefault(),t.stopPropagation())}hideView(){this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(document.body.style.overflow="auto")}setActiveTOCItem(t){if(this.tocView){let n=Array.prototype.slice.call(this.tocView.querySelectorAll("li > a"));for(let o of n)o.className=o.className.replace(" active","");let r=this.tocView.querySelector('li > a[href^="'+t+'"]');r&&(r.className+=" active")}}async navigate(t,n=!0){if(this.historyModule&&this.historyModule.push(t,n),this.publication.getTOCItem(t.href)){var o=!1;if(t.href.indexOf("#")!==-1){let a=t.href.slice(0,t.href.indexOf("#"));a===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=a,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title}else t.href===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=t.href,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title;if(this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0&&(t.href===this.currentSpreadLinks.left.href||t.href===this.currentSpreadLinks.right.href))return;if(o){if(t.href.indexOf("#")!==-1){let g=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:g}}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 g of this.iframes){let y=g.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(y)}this.newElementId=void 0}else if(t.highlight){let g=t.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;g&&this.view?.goToCssSelector(g)}else this.view?.goToProgression(t.locations.progression??0);let a=this.currentChapterLink.href,l=this.publication.getPreviousSpineItem(a);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 u=this.publication.getNextSpineItem(a);u?this.nextChapterLink={href:u.Href,type:u.TypeLink,title:u.Title}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(a),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let d=this.publication.getSpineItem(a);d!==void 0&&(this.currentChapterLink.title=d.Title,this.currentChapterLink.type=d.TypeLink);let f=this.publication.getTOCItem(a);this.currentTocUrl!==void 0&&(f=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&f!==void 0&&f.Title&&(this.currentChapterLink.title=f.Title),!this.currentChapterLink.type&&f!==void 0&&f.TypeLink&&(this.currentChapterLink.title=f.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(qe.PageBreak),await this.pageBreakModule.drawPageBreaks()),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(qe.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(a=>{a||(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 a=this.publication.getStartLink(),l;if(a&&a.Href&&(l=this.publication.getAbsoluteHref(a.Href),l)){let u={href:l,locations:{progression:0},created:new Date,title:a.Title};await this.navigate(u)}}}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 r;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 a=Math.ceil((n.progression??0)*(o.length-1)),l=o[a];l&&(l.locations.fragment=n.fragment,r=jt(Fe({},l),{href:t.Href,created:new Date,title:this.currentChapterLink.title}))}}else r={href:t.Href,locations:n,created:new Date,type:this.currentChapterLink.type,title:this.currentChapterLink.title};r&&(this.sample?.isSampleRead&&this.publication.positions&&this.sampleReadEventHandler?.enforceSampleRead(r),this.api?.updateCurrentLocation?this.api?.updateCurrentLocation(r).then(async o=>(Yn.default.log("api updated current location",r),this.annotator?.saveLastReadingPosition(r))):(Yn.default.log("save last reading position",r),this.annotator.saveLastReadingPosition(r)))}}}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 r=document.createElement("script");return r.type="text/javascript",r.src=t,r.async=n,r}activateMarker(t,n){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId===void 0||this.annotationModule.activeAnnotationMarkerId!==t?(this.annotationModule.activeAnnotationMarkerId=t,this.annotationModule.activeAnnotationMarkerPosition=n,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=t)):this.deactivateMarker())}deactivateMarker(){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId=void 0,this.annotationModule.activeAnnotationMarkerPosition=void 0,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=void 0))}showLayer(t){let n="#",r=new xa("layer-on","layer-off",!0,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=Re.R2_ID_HIGHLIGHTS_CONTAINER,r.name=Re.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=Re.R2_ID_READALOUD_CONTAINER,r.name=Re.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=Re.R2_ID_PAGEBREAK_CONTAINER,r.name=Re.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=Re.R2_ID_SEARCH_CONTAINER,r.name=Re.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=Re.R2_ID_DEFINITIONS_CONTAINER,r.name=Re.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(r);let o=this.iframes[0].contentDocument;if(o){let a=de(o,n);a&&(a.style.display="block")}}hideLayer(t){let n="#",r=new xa("layer-on","layer-off",!1,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=Re.R2_ID_HIGHLIGHTS_CONTAINER,r.name=Re.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=Re.R2_ID_READALOUD_CONTAINER,r.name=Re.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=Re.R2_ID_PAGEBREAK_CONTAINER,r.name=Re.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=Re.R2_ID_SEARCH_CONTAINER,r.name=Re.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=Re.R2_ID_DEFINITIONS_CONTAINER,r.name=Re.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(r);let o=this.iframes[0].contentDocument;if(o){let a=de(o,n);a&&(a.style.display="none")}}};C();var yt=class{constructor(t){this.store=t.store}getLastReadingPosition(){let t=this.store.get(yt.LAST_READING_POSITION);return t?JSON.parse(t):null}initLastReadingPosition(t){if(typeof t=="string")this.store.set(yt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(yt.LAST_READING_POSITION,n)}}saveLastReadingPosition(t){if(typeof t=="string")this.store.set(yt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(yt.LAST_READING_POSITION,n)}}initBookmarks(t){if(typeof t=="string"){let n=JSON.parse(t);this.store.set(yt.BOOKMARKS,JSON.stringify(n))}else this.store.set(yt.BOOKMARKS,JSON.stringify(t));return t}saveBookmark(t){let n=this.store.get(yt.BOOKMARKS);if(n){let r=JSON.parse(n);r.push(t),this.store.set(yt.BOOKMARKS,JSON.stringify(r))}else{let r=[];r.push(t),this.store.set(yt.BOOKMARKS,JSON.stringify(r))}return t}locatorExists(t,n){let r;switch(n){case fr.Bookmark:r=yt.BOOKMARKS;break}let o=this.store.get(r);return o&&JSON.parse(o).filter(u=>u.href===t.href&&u.locations.progression===t.locations.progression).length>0?t:null}deleteBookmark(t){let n=this.store.get(yt.BOOKMARKS);if(n){let r=JSON.parse(n);r=r.filter(o=>o.id!==t.id),this.store.set(yt.BOOKMARKS,JSON.stringify(r))}return t}getBookmarks(t){let n=this.store.get(yt.BOOKMARKS);if(n){let r=JSON.parse(n);if(t){let o=r.filter(a=>a.href===t);return o=o.sort((a,l)=>{if(a.locations.progression&&l.locations.progression)return a.locations.progression-l.locations.progression}),o}return r=r.sort((o,a)=>{if(o.locations.progression&&a.locations.progression)return o.locations.progression-a.locations.progression}),r}return[]}initAnnotations(t){let n;typeof t=="string"?n=JSON.parse(t):n=t;let r=[];return n.forEach(o=>{let a=`${o.highlight.selectionInfo.rangeInfo.startContainerElementCssSelector}${o.highlight.selectionInfo.rangeInfo.startContainerChildTextNodeIndex}${o.highlight.selectionInfo.rangeInfo.startOffset}${o.highlight.selectionInfo.rangeInfo.endContainerElementCssSelector}${o.highlight.selectionInfo.rangeInfo.endContainerChildTextNodeIndex}${o.highlight.selectionInfo.rangeInfo.endOffset}`,l=Tr.hash(a);o.highlight.id="R2_HIGHLIGHT_"+l;let u;o.highlight.color?u=o.highlight.color:o.color&&(u=o.color),De.isHexColor(u)&&(u=De.hexToRgbString(u)),o.highlight.color=u,o.highlight.pointerInteraction=!0,o.highlight.selectionInfo.cleanText=o.highlight.selectionInfo.rawText.trim().replace(/\n/g," ").replace(/\s\s+/g," "),r.push(o)}),this.store.set(yt.ANNOTATIONS,JSON.stringify(r)),r}saveTemporarySelectionInfo(t){this.store.set(yt.SELECTIONINFO,JSON.stringify(t))}getTemporarySelectionInfo(t){let n=this.store.get(yt.SELECTIONINFO);if(n){let r=JSON.parse(n);return r.range=vd(t,r.rangeInfo),r}return[]}deleteTemporarySelectionInfo(){this.store.remove(yt.SELECTIONINFO)}saveAnnotation(t){let n=this.store.get(yt.ANNOTATIONS);if(n){let r=JSON.parse(n);r.push(t),this.store.set(yt.ANNOTATIONS,JSON.stringify(r))}else{let r=[];r.push(t),this.store.set(yt.ANNOTATIONS,JSON.stringify(r))}return t}deleteAnnotation(t){let n=this.store.get(yt.ANNOTATIONS);if(n){let r=JSON.parse(n);r=r.filter(o=>o.id!==t),this.store.set(yt.ANNOTATIONS,JSON.stringify(r))}return t}deleteSelectedAnnotation(t){let n=this.store.get(yt.ANNOTATIONS);if(n){let r=JSON.parse(n);r=r.filter(o=>o.highlight?.id!==t.highlight.id),this.store.set(yt.ANNOTATIONS,JSON.stringify(r))}return t}getAnnotations(){let t=this.store.get(yt.ANNOTATIONS);if(t){let n=JSON.parse(t);return n=n.sort((r,o)=>{if(r.locations.progression&&o.locations.progression)return r.locations.progression-o.locations.progression}),n}return[]}getAnnotationPosition(t,n){let r=this.store.get(yt.ANNOTATIONS);if(r){let a=JSON.parse(r).filter(l=>l.highlight?.id===t||l.id===t);if(a.length>0){let l=n.document.getElementById(`${a[0].highlight.id}`);if(l){let u=0;if(l.hasChildNodes)for(let d=0;d<l.childNodes.length;d++){let f=l.childNodes[d],g=parseInt(f.style.top.replace("px",""));(g<u||u===0)&&(u=g)}else u=parseInt(l.style.top.replace("px",""));return u}}}return null}getAnnotationElement(t,n){let r=this.store.get(yt.ANNOTATIONS);if(r){let a=JSON.parse(r).filter(l=>l.highlight?.id===t);if(a.length>0){let l=n.document.getElementById(`${a[0].highlight.id}`);if(l){let u=0;if(l.hasChildNodes)for(let d=0;d<l.childNodes.length;d++){let f=l.childNodes[d],g=parseInt(f.style.top.replace("px",""));if(g<u||u===0)return u=g,f}else u=parseInt(l.style.top.replace("px",""));return l}}}return null}getAnnotation(t){let n=this.store.get(yt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(a=>a.highlight?.id===t.id);if(o.length>0)return o[0]}return null}getAnnotationByID(t){let n=this.store.get(yt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(a=>a.highlight?.id===t);if(o.length>0)return o[0]}return null}},lo=yt;lo.LAST_READING_POSITION="last-reading-position",lo.BOOKMARKS="bookmarks",lo.ANNOTATIONS="annotations",lo.SELECTIONINFO="selectionInfo";C();C();var Wd=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 Wd}}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))}};C();var P3=Je(va()),I3=Je(Cn());var sl=class extends P3.Link{};sl=ac([(0,I3.JsonObject)()],sl);function al(i){let t,n,r,o;if(i instanceof Array)return i.map(function(a){return typeof a=="object"&&(a=al(a)),a});t={};for(n in i)i.hasOwnProperty(n)&&(r=(n.charAt(0).toLowerCase()+n.slice(1)||n).toString(),o=i[n],(o instanceof Array||o!==null&&o.constructor===Object)&&(o=al(o)),r==="href1"?t.href=o:r==="typeLink"?t.type=o:t[r]=o);return t}C();var L3=Je(Dt()),ig=class{constructor(t){this.LAYERSETTINGS="layerSetting";this.store=t,this.initialize()}static async create(t){let n=new this(t.store);return new Promise(r=>r(n))}async stop(){L3.default.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let t=new Si,n=await this.store.get(this.LAYERSETTINGS);if(n){let r=JSON.parse(n);t.properties=r}return t}async saveProperty(t){let n=await this.store.get(this.LAYERSETTINGS);if(n){let r=JSON.parse(n);r=r.filter(o=>o.name!==t.name),r.push(t),await this.store.set(this.LAYERSETTINGS,JSON.stringify(r))}else{let r=[];r.push(t),await this.store.set(this.LAYERSETTINGS,JSON.stringify(r))}return new Promise(r=>r(t))}async getProperty(t){let n=await this.store.get(this.LAYERSETTINGS);if(n){let r=JSON.parse(n);return r=r.filter(o=>o.name===t),r.length===0?null:r[0]}return null}};C();var ll=Je(Dt()),og=class{static async create(t){let n=new this(t.delegate,t.publication,t,t.headerMenu);return await n.start(),n}constructor(t,n,r,o){this.headerMenu=o,this.delegate=t,this.publication=n,this.properties=r}async stop(){ll.default.log("Page Break module stop")}async start(){this.delegate.pageBreakModule=this,this.headerMenu&&(this.goToPageView=de(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=de(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=de(this.headerMenu,"#goToPageNumberButton")),ne(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),ne(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 r=n[0];let o={progression:0};if(r.Href.indexOf("#")!==-1){let l=r.Href.slice(r.Href.indexOf("#")+1);l!==null&&(o={fragment:l})}let a={href:this.publication.getAbsoluteHref(r.Href),locations:o,type:r.TypeLink,title:r.Title};this.delegate.goTo(a)}}}async handleResize(){await this.delegate.highlighter?.destroyHighlights(qe.PageBreak),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{let t=this.delegate.iframes[0].contentDocument?.body,n=t?.querySelectorAll('[*|type="pagebreak"]');n?.length===0&&(n=t?.querySelectorAll("[epub\\:type='pagebreak']"));let r=this;function o(a){try{let l=r.delegate.iframes[0].contentDocument;return l?Rn(a,l,no):""}catch(l){return ll.default.log("uniqueCssSelector:"),ll.default.error(l),""}}if(n)for(let a=0;a<n.length;a++){let l=n[a];ll.default.log(l);let u=l.innerHTML,d=!1;l.innerHTML.length===0&&(u=l.getAttribute("title")??"",l.innerHTML=u,d=!0),l.innerHTML.length===0&&(u=(l.getAttribute("id")??"").replace(/[^0-9]/g,""),l.innerHTML=u,d=!0);let f=this.delegate.iframes[0].contentDocument;if(f){let g=this.delegate.highlighter?.dom(f.body).getWindow().document.createRange(),y=this.delegate.highlighter?.dom(f.body).getSelection();if(y.removeAllRanges(),g.selectNodeContents(l),y.addRange(g),!y.isCollapsed){let v=Ri(g,o);y.removeAllRanges(),v&&this.createPageBreakHighlight({rangeInfo:v,cleanText:"",rawText:""},u)}}d&&(l.innerHTML="")}},200)}createPageBreakHighlight(t,n){try{let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,a=Tr.hash(o),l="R2_PAGEBREAK_"+a;var r=!1;let u={color:"#000000",id:l,pointerInteraction:r,selectionInfo:t,marker:Le.Custom,icon:{id:"pageBreak",title:n,color:"#000000",position:"left"},type:qe.PageBreak};zt.push(u);let d=this.delegate.highlighter?.createHighlightDom(this.delegate.iframes[0].contentWindow,u);return u.position=parseInt((d?.hasChildNodes()?d.childNodes[0]:d).style.top.replace("px","")),u}catch(o){throw"Can't create highlight: "+o}}};C();var B3=Je(Xp());var k3=Je(Qi());var Ke=Je(Dt()),sg=class{constructor(t,n,r,o,a,l,u){this.voices=[];this.hasEventListener=!1;this.startX=0;this.startY=0;this.index=0;this.userScrolled=!1;this.scrollPartial=!1;this.speaking=!1;this.restartIndex=-1;this.ttsQueueIndex=-1;this.ttsQueue=void 0;this.ttsPlayQueueIndexDebounced=(0,k3.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=u,this.rights=r,this.highlighter=o,this.properties=a,this.api=l}initialize(t){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=t,this.clean=(0,B3.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),this.wrapper=dt(document,"#iframe-wrapper"),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,ne(document,"wheel",this.wheel.bind(this)),ne(this.body,"wheel",this.wheel.bind(this)),ne(document,"keydown",this.wheel.bind(this)),ne(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),ne(this.body,"mousedown",this.clickStart.bind(this)),ne(this.body,"mouseup",this.click.bind(this)))}clickStart(t){"clientX"in t&&(this.startX=t.clientX),"clientY"in t&&(this.startY=t.clientY)}click(t){let n=0,r=0;if("clientX"in t&&(n=t.clientX),"clientY"in t&&(r=t.clientY),window.speechSynthesis.speaking&&this.speaking&&n===this.startX&&r===this.startY){let o=this.delegate.iframes[0].contentDocument;if(o){let a=this.highlighter.dom(o.body).getSelection();if(a.isCollapsed){let g=this.delegate.iframes[0].contentDocument,y=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(g);a.addRange(y.range)}let l=a.getRangeAt(0),u=a.anchorNode;for(;l.toString().indexOf(" ")!==0;)try{l.setStart(u,l.startOffset-1)}catch(g){break}l.setStart(u,l.startOffset+1);do l.setEnd(u,u.length<l.endOffset?l.endOffset+1:u.length);while(l.toString().indexOf(" ")===-1&&l.toString().trim()!=="");let f=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(this.ttsQueue&&f){let g=this.findTtsQueueItemIndex(this.ttsQueue,a.anchorNode,a.anchorNode,a.anchorOffset,f);a.removeAllRanges(),g>=0&&(window.speechSynthesis.cancel(),this.restartIndex=g,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}}}}initVoices(t){function n(){return new Promise(function(o,a){let l=window.speechSynthesis,u;u=setInterval(()=>{l.getVoices().length!==0&&(o(l.getVoices()),clearInterval(u))},10)})}n().then(async o=>{if(Ke.default.log(o),this.voices=[],o.forEach(l=>{l.localService===!0&&this.voices.push(l)}),Ke.default.log(this.voices),t&&this.headerMenu){var a=de(this.headerMenu,"#preferred-languages");a&&this.voices.forEach(l=>{var u=document.createElement("option");u.value=l.name+":"+l.lang,u.innerHTML=l.name+" ("+l.lang+")",a.add(u)})}})}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(qe.ReadAloud),this._ttsQueueItemHighlightsWord=void 0)}async speak(t,n,r){this.api?.started&&this.api?.started(),this.delegate.emit("readaloud.started","started");let o=this;this.userScrolled=!1,this.cancel(!1);let a;if(n){let O=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body,_=this.delegate.iframes[0].contentDocument;if(_){let A=this.highlighter.dom(_.body).getSelection();if(A.isCollapsed){let T=o.delegate.iframes[0].contentDocument,M=o.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(T);A.addRange(M.range)}if(O){var l=this.generateTtsQueue(O);if(!l.length)return;var u=this.findTtsQueueItemIndex(l,A.anchorNode,A.anchorNode,A.anchorOffset,O),d=this.findTtsQueueItemIndex(l,A.focusNode,A.focusNode,A.focusOffset,O);let T=Vo(l,u),M=Vo(l,d);var f;if(T&&t&&t.cleanText){let j=Jo(T),P=t.rangeInfo.startOffset,q=t.cleanText;if(M&&u+1===d){let k=Jo(M);P=(j+" "+k).indexOf(t.cleanText),q=j.slice(P,j.length),f=t.cleanText.replace(q,"").trim()}else if(d>u){let k="";for(let B=u+1;B<d;B++){let N=Vo(l,B);if(N){let W=Jo(N);k+=W,f=t.cleanText.replace(W,"")}}if(M){let B=Jo(M);k+=" "+B}P=(j+" "+k).indexOf(t.cleanText),q=j.slice(P,j.length),f=f.replace(q,"").trim()}a=new SpeechSynthesisUtterance(q),Ke.default.log(t),Ke.default.log(q,t.range?.commonAncestorContainer.textContent),Ke.default.log(T),Ke.default.log(T.item.textNodes),Ke.default.log(P),Ke.default.log(T.item.combinedText);let U=T.item.textNodes.filter(k=>k===t.range?.commonAncestorContainer)[0];Ke.default.log(U),a.onboundary=k=>{this.updateTTSInfo(T,k.charIndex,k.charLength,P,a.text)}}}}}else a=new SpeechSynthesisUtterance(this.clean);a.rate=this.tts.rate,a.pitch=this.tts.pitch,a.volume=this.tts.volume,Ke.default.log("this.tts.voice.lang",this.tts.voice.lang);var g=!0;this.tts.voice&&this.tts.voice.lang&&(g=this.tts.voice.lang.indexOf("-")!==-1,g===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),g=!0)),Ke.default.log("initialVoiceHasHyphen",g),Ke.default.log("voices",this.voices);var y;g===!0?(y=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(E=>{var O=E.lang.replace("_","-");return O===this.tts.voice.lang&&E.name===this.tts.voice.name})[0]:void 0,y===void 0&&(y=this.tts.voice&&this.tts.voice.lang?this.voices.filter(E=>E.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(y=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(E=>E.lang===this.tts.voice.lang&&E.name===this.tts.voice.name)[0]:void 0,y===void 0&&(y=this.tts.voice&&this.tts.voice.lang?this.voices.filter(E=>E.lang===this.tts.voice.lang)[0]:void 0)),Ke.default.log("initialVoice",y);var v=o.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;Ke.default.log("publicationVoiceHasHyphen",v);var S;v===!0?S=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(E=>{var O=E.lang.replace("_","-");return O.startsWith(o.delegate.publication.Metadata.Language[0])||O.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:S=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(E=>E.lang.startsWith(o.delegate.publication.Metadata.Language[0])||E.lang.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Ke.default.log("publicationVoice",S);var w=navigator.language.indexOf("-")!==-1;Ke.default.log("defaultVoiceHasHyphen",w);var b;w===!0?b=this.voices.filter(E=>{var O=E.lang.replace("_","-");return O===navigator.language&&E.localService===!0})[0]:b=this.voices.filter(E=>{var O=E.lang;return O===navigator.language&&E.localService===!0})[0],b===void 0&&(b=this.voices.filter(E=>{var O=E.lang;return O.includes(navigator.language)&&E.localService===!0})[0]),Ke.default.log("defaultVoice",b),y?(Ke.default.log("initialVoice"),a.voice=y):S?(Ke.default.log("publicationVoice"),a.voice=S):b&&(Ke.default.log("defaultVoice"),a.voice=b),a.voice!==void 0&&a.voice!==null&&(a.lang=a.voice.lang,Ke.default.log("utterance.voice.lang",a.voice.lang),Ke.default.log("utterance.lang",a.lang)),Ke.default.log("navigator.language",navigator.language),setTimeout(()=>{window.speechSynthesis.speak(a)},0),this.index=0;function m(){a.onend=function(){if(d>u)if(u=u+1,u!==d){let E=Vo(l,u);if(E){let O=Jo(E);a=new SpeechSynthesisUtterance(O),a.onboundary=_=>{o.updateTTSInfo(E,_.charIndex,_.charLength,0,a.text)},setTimeout(()=>{window.speechSynthesis.speak(a)},0),m()}}else{let E=Vo(l,u);E&&(a=new SpeechSynthesisUtterance(f),a.onboundary=O=>{o.updateTTSInfo(E,O.charIndex,O.charLength,0,a.text)},setTimeout(()=>{window.speechSynthesis.speak(a)},0),m()),u>d&&(Ke.default.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.delegate.emit("readaloud.finished","finished"))}else Ke.default.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.delegate.emit("readaloud.finished","finished")}}m(),r()}speakPlay(){this.scrollPartial=!0,this.cancel(!1),this.api?.started&&this.api?.started(),this.delegate.emit("readaloud.started","started");let t=this,r=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(r){let l=function(){let u=t.highlighter.visibleTextRects[0],d=t.delegate.iframes[0].contentDocument;if(d){let f=t.highlighter.dom(d.body).getWindow().document.createRange(),g=t.highlighter.dom(t.delegate.iframes[0].contentDocument?.body).getSelection();g.removeAllRanges(),f.selectNodeContents(u.node),g.addRange(f);let y=0,v=g.focusNode,S=g.focusOffset;g.collapse(g.anchorNode,g.anchorOffset);for(let w=0;w<y;w++)g.modify("move","forward","line");if(g.extend(v,S),g.collapse(g.anchorNode,g.anchorOffset),r){let w=t.findTtsQueueItemIndex(o,g.anchorNode,g.anchorNode,g.anchorOffset,r);w>=0&&(a=w)}g.removeAllRanges()}},o=this.generateTtsQueue(r);if(!o.length)return;let a=0;l(),a<0&&(a=0),setTimeout(()=>{this.startTTSSession(o,a)},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(qe.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=de(this.headerMenu,"#menu-button-tts");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties?.hideLayer?this.delegate.hideLayer("readaloud"):this.delegate.showLayer("readaloud")},10)}wheel(t){if(t instanceof KeyboardEvent)switch(t.key){case"ArrowUp":this.userScrolled=!0;break;case"ArrowDown":this.userScrolled=!0;break}else this.userScrolled=!0}stop(){Ke.default.log("TTS module stop"),Pe(document,"wheel",this.wheel.bind(this)),Pe(this.body,"wheel",this.wheel.bind(this)),Pe(document,"keydown",this.wheel.bind(this)),Pe(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),Pe(this.body,"click",this.click.bind(this))}generateTtsQueue(t){let n=[],r=[];function o(d){if(d.nodeType!==Node.TEXT_NODE||!d.nodeValue||!d.nodeValue.trim().length)return;let f=r[r.length-1];if(!f)return;let g=d.parentElement?N3(d.parentElement):void 0,y=d.parentElement?aN(d.parentElement):void 0,v=n[n.length-1];(!v||v.parentElement!==f||v.lang!==g||v.dir!==y)&&(v={combinedText:"",dir:y,lang:g,parentElement:f,textNodes:[]},n.push(v)),v.textNodes.push(d)}let a=!0;function l(d){if(d.nodeType!==Node.ELEMENT_NODE)return;let f=a||d.matches("h1, h2, h3, h4, h5, h6, p, th, td, caption, li, blockquote, q, dt, dd, figcaption, div, pre");a=!1,f&&r.push(d);for(let g of d.childNodes)switch(g.nodeType){case Node.ELEMENT_NODE:let y=g;if(!y.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))l(y);else if(y.tagName&&y.tagName.toLowerCase()==="img"&&y.src){let S=y.getAttribute("alt");if(S){let w=S.trim();if(w){let b=N3(y),m=void 0;n.push({combinedText:w,dir:m,lang:b,parentElement:y,textNodes:[]})}}}break;case Node.TEXT_NODE:r.length!==0&&o(g);break;default:break}f&&r.pop()}l(t);function u(d){if(!d.textNodes||!d.textNodes.length){(!d.combinedText||!d.combinedText.length)&&(d.combinedText="");return}d.combinedText=lN(d.textNodes,!0).replace(/[\r\n]/g," ");let f=d.parentElement;for(;f;){if(f.tagName){let g=f.tagName.toLowerCase();if(g==="pre"||g==="code"||g==="video"||g==="audio")break}f=f.parentElement}}for(let d of n)u(d);return n}findTtsQueueItemIndex(t,n,r,o,a){let l=0;for(let u of t){if(r&&u.textNodes){if(u.textNodes.includes(r))return l}else if(n===u.parentElement||u.parentElement!==n.ownerDocument.body&&u.parentElement!==a&&u.parentElement.contains(n)||n.contains(u.parentElement))return l;l++}return-1}restart(){window.speechSynthesis.speaking&&(window.speechSynthesis.cancel(),this.restartIndex=this.ttsQueueIndex,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}startTTSSession(t,n){if(!Vo(t,n)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(n,t)}ttsPlayQueueIndex(t,n){if(t<0){this.cancel();return}let r=Vo(n,t);if(!r){this.cancel();return}let o=Jo(r);if(!o){this.cancel();return}let a=new SpeechSynthesisUtterance(o);a.rate=this.tts.rate,a.pitch=this.tts.pitch,a.volume=this.tts.volume,Ke.default.log("this.tts.voice.lang",this.tts.voice.lang);var l=!0;this.tts.voice&&this.tts.voice.lang&&(l=this.tts.voice.lang.indexOf("-")!==-1,l===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),l=!0)),Ke.default.log("initialVoiceHasHyphen",l),Ke.default.log("voices",this.voices);var u;l===!0?(u=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(S=>{var w=S.lang.replace("_","-");return w===this.tts.voice.lang&&S.name===this.tts.voice.name})[0]:void 0,u===void 0&&(u=this.tts.voice&&this.tts.voice.lang?this.voices.filter(S=>S.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(u=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(S=>S.lang===this.tts.voice.lang&&S.name===this.tts.voice.name)[0]:void 0,u===void 0&&(u=this.tts.voice&&this.tts.voice.lang?this.voices.filter(S=>S.lang===this.tts.voice.lang)[0]:void 0)),Ke.default.log("initialVoice",u);var d=this,f=d.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;Ke.default.log("publicationVoiceHasHyphen",f);var g;f===!0?g=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(S=>{var w=S.lang.replace("_","-");return w.startsWith(d.delegate.publication.Metadata.Language[0])||w.endsWith(d.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:g=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(S=>S.lang.startsWith(d.delegate.publication.Metadata.Language[0])||S.lang.endsWith(d.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Ke.default.log("publicationVoice",g);var y=navigator.language.indexOf("-")!==-1;Ke.default.log("defaultVoiceHasHyphen",y);var v;y===!0?v=this.voices.filter(S=>{var w=S.lang.replace("_","-");return w===navigator.language&&S.localService===!0})[0]:v=this.voices.filter(S=>{var w=S.lang;return w===navigator.language&&S.localService===!0})[0],v===void 0&&(v=this.voices.filter(S=>{var w=S.lang;return w.includes(navigator.language)&&S.localService===!0})[0]),Ke.default.log("defaultVoice",v),u?(Ke.default.log("initialVoice"),a.voice=u):g?(Ke.default.log("publicationVoice"),a.voice=g):v&&(Ke.default.log("defaultVoice"),a.voice=v),a.voice!==void 0&&a.voice!==null&&(a.lang=a.voice.lang,Ke.default.log("utterance.voice.lang",a.voice.lang),Ke.default.log("utterance.lang",a.lang)),Ke.default.log("navigator.language",navigator.language),a.onboundary=S=>{Ke.default.log(S.name),this.updateTTSInfo(r,S.charIndex,S.charLength,0,a.text)},setTimeout(()=>{window.speechSynthesis.speak(a),d.speaking||window.speechSynthesis.pause()},0),a.onend=function(){d.speaking&&d.ttsPlayQueueIndexDebounced(t+1,n)}}updateTTSInfo(t,n,r,o,a){if(!t)return;Ke.default.log(t,n,r,a);let l=a||Jo(t);if(n>=0&&a){let u=a.slice(0,n+1).search(/\S+$/),d=a.slice(n).search(/\s/),f=d<0?a.slice(u):a.slice(u,d+n),g=u+f.length;if(r===void 0){let y=a.substring(n).match(/^[a-z\d']*/i);y&&(r=y[0].length)}r===void 0&&(r=f.length),this.wrapHighlightWord(t,a,n+o,r,f,u,g)}return l}wrapHighlightWord(t,n,r,o,a,l,u){Ke.default.log(t),Ke.default.log(n),Ke.default.log(r,o,a,l,u),this._ttsQueueItemHighlightsWord&&(this.delegate.highlighter?.destroyHighlights(qe.ReadAloud),this._ttsQueueItemHighlightsWord=void 0);let d=t.item,f=r,g=0,y,v=-1,S,w=-1,b=f+o;for(let E of d.textNodes){if(!E.nodeValue&&E.nodeValue!=="")continue;let O=E.nodeValue.length;if(g+=O,y||f<g&&(y=E,v=O-(g-f)),y&&b<=g&&(S=E,w=O-(g-b)),S)break}if(y&&S){let O=function(T){try{let M=m.delegate.iframes[0].contentDocument;return M?Rn(T,M,no):""}catch(M){return Ke.default.log("uniqueCssSelector:"),Ke.default.error(M),""}},E=new Range;E.setStart(y,v),E.setEnd(S,w);var m=this;let _=Ri(E,O);if(!_)return;let A=this.delegate.highlighter?.createHighlight(this.delegate.iframes[0].contentWindow,{rangeInfo:_,cleanText:"",rawText:"",range:void 0},this.tts.color,!1,Le.Custom,{id:"tts",title:"",position:"right"},void 0,{defaultClass:this.tts.color},qe.ReadAloud,"R2_READALOUD_");if(A){this._ttsQueueItemHighlightsWord=A[0];let j=(A[1]?.firstChild?.getBoundingClientRect()).top-this.wrapper.scrollTop>window.innerHeight/2-65;this.delegate.view?.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&this.scrollPartial&&j?A[1]?.firstChild?.scrollIntoView({block:"center",behavior:"smooth"}):this.delegate.view?.isPaginated()&&m.delegate.view?.snap(A[1]?.firstChild)}}}};function N3(i){let t=i;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 aN(i){let t=i;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let n=t.getAttribute("dir");if(n)return n;t=t.parentNode}}function lN(i,t){if(i&&i.length){let n="";for(let r of i)r.nodeValue&&(n+=t?r.nodeValue:uN(r.nodeValue));return n}return""}function cN(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function uN(i){return cN(i).replace(/\n/g," ").replace(/\s\s+/g," ")}function Vo(i,t){let n=-1,r=-1;for(let o of i)if(r++,n++,t===n)return{item:o,iArray:r,iGlobal:n,iSentence:-1}}function Jo(i){return i.item.combinedText}C();var cl=Je(Ed());var H3=Je(Qi());var j3=Je(Dt()),ag=class{constructor(t,n,r,o,a){this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,H3.debounce)(async()=>{if(await this.highlighter.destroyHighlights(qe.Definition),this.properties.definitions)for(let t of this.properties.definitions)await this.define(t)},200);this.delegate=t,this.publication=n,this.properties=r,this.api=a,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(){j3.default.log("Definitions module stop")}async start(){this.delegate.definitionsModule=this,setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("definitions"):this.delegate.showLayer("definitions")},10)}async searchAndPaint(t,n){let r=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[this.delegate.currentResource()??0].Href:""),o=this.publication.getTOCItem(r);o===void 0&&this.publication.readingOrder&&(o=this.publication.readingOrder[this.delegate.currentResource()??0]);let a=[];if(o)for(let l of t.terms){let u=t.terms.indexOf(l);o&&await Js(l,this.delegate.iframes[0].contentDocument,o.Href,o.Title,this.delegate.definitionsModule?.properties.fullWordSearch).then(d=>{let f;t.result===1?f=0:t.result===2&&(f=Math.floor(Math.random()*d.length-1)+1),d.forEach((g,y)=>{if(f===void 0||f===y){let v={rangeInfo:g.rangeInfo},S=this.createDefinitionHighlight(v,t);g.highlight=S,a.push(cl.omit(S,"definition")),this.currentChapterPopupResult.push(g),this.currentPopupHighlights.push(S)}}),u===t.terms.length-1&&n(a)})}}async define(t){await this.searchAndPaint(t,async n=>{this.api?.success&&(this.api?.success(cl.omit(t,"callbacks"),n),this.delegate.emit("definition.success",n),this.api?.visible&&n.forEach(r=>{let a=this.delegate.iframes[0].contentDocument?.querySelector(`#${r.id}`)?.querySelectorAll(`.${hn}`),l=new IntersectionObserver((u,d)=>{u.forEach(f=>{f.intersectionRatio===1&&(this.api?.visible(cl.omit(t,"callbacks"),cl.omit(r,"definition")),this.delegate.emit("definition.visible",t,r))})},{threshold:1});a&&a.length>0&&l.observe(a[0])}))})}async drawDefinitions(){setTimeout(async()=>{await this.definitions()},100)}async handleResize(){await this.drawDefinitions()}createDefinitionHighlight(t,n){try{let r=this.delegate.definitionsModule?.properties.color;De.isHexColor(r)&&(r=De.hexToRgbChannels(r));let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,a=Tr.hash(o),l="R2_DEFINITION_"+a;this.highlighter.destroyHighlight(this.delegate.iframes[0].contentDocument,l);let u={color:r||Fo,id:l,pointerInteraction:!0,selectionInfo:t,marker:Le.Underline,type:qe.Definition};zt.push(u);let d=this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,u);return d&&(n.definition&&(d.dataset.definition=n.definition),d.dataset.order=String(n.order),u.definition=n,u.position=parseInt((d?.hasChildNodes()?d.childNodes[0]:d).style.top.replace("px",""))),u}catch(r){throw"Can't create definitions highlight: "+r}}async addDefinition(t){await this.define(t)}async clearDefinitions(){await this.highlighter.destroyHighlights(qe.Definition)}};C();var co=Je(Dt()),D3=.5,Gd=class{constructor(t,n,r,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=r}static async create(t){let n=new this(t.delegate,t,t.highlighter,t.api);return await n.start(),n}async stop(){co.default.log("Definitions module stop"),this.hasEventListener=!1,Pe(document,"keydown",this.keydown.bind(this)),Pe(document,"keyup",this.keyup.bind(this)),Pe(this.delegate.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),Pe(this.delegate.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){this.delegate.lineFocusModule=this;let t=dt(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,ne(document,"keydown",this.keydown.bind(this)),ne(document,"keyup",this.keyup.bind(this)),ne(this.delegate.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),ne(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=dt(document,"#iframe-wrapper");this.wrapperHeight&&(n.style.height=this.wrapperHeight),t||(this.index=0);let r=this.delegate.iframes[0].contentDocument;Qt(r,"html").style.removeProperty("--USER__maxMediaHeight"),this.wrapperHeight=void 0,this.lineFocusContainer&&(this.lineFocusContainer.style.display="none");let a=document.getElementById("container-view-timeline");a&&a.style.removeProperty("display");let l=document.getElementById("divBefore");l&&l.remove();let u=document.getElementById("divAfter");u&&u.remove(),this.highlighter.destroyHighlights(qe.LineFocus)}lineFocus(){let t=dt(document,"#iframe-wrapper"),n=this.delegate.iframes[0].contentDocument,r=Qt(n,"html"),o=this.properties.maxHeight?Fr()*this.properties.maxHeight/100:Fr()/2;r.style.setProperty("--USER__maxMediaHeight",o+"px");function a(g,y){g.parentNode.insertBefore(y,g.nextSibling)}function l(g,y){g.parentNode.insertBefore(y,g)}let u=document.getElementById("container-view-timeline");u&&(u.style.display="none"),this.lineFocusContainer&&this.lineFocusContainer.style.removeProperty("display");let d=document.getElementById("divBefore");if(d)d.style.height=t.clientHeight/2+"px";else{let g=document.createElement("div");g.style.height=t.clientHeight/2+"px",g.id="divBefore",l(t,g)}let f=document.getElementById("divAfter");if(f)f.style.height=t.clientHeight/2+"px";else{let g=document.createElement("div");g.style.height=t.clientHeight/2+"px",g.id="divAfter",a(t,g)}if(this.lines=[],n){let v=function(){let O=Math.round,_=Math.random,A=255;return{blue:O(_()*A),green:O(_()*A),red:O(_()*A)}},S=function(O,_){let A=[];for(let T=0,M=0;T<O.length;T++)T>=_&&T%_==0&&M++,A[M]=A[M]||[],A[M].push(O[T]);return A},w=function(O,_){let A=Math.min(O.left,_.left),T=Math.max(O.right,_.right),M=Math.min(O.top,_.top),j=Math.max(O.bottom,_.bottom);return{bottom:j,height:j-M,left:A,right:T,top:M,width:T-A}},b=function(O){if(O.length>1){let _=w(O[0],O[1]);if(O.length>2){let A=w(_,O[2]);if(O.length>3){let T=w(A,O[3]);return O.length>4?w(T,O[4]):T}return A}return _}return O[0]},g=this.findRects(n.body);g=i0(g,!0),g=g.sort(function(O,_){return O.top-_.top});let y=[];g=g.filter(function(O){let _=O.top;return y.indexOf(_)===-1&&y.indexOf(_+1)===-1&&y.indexOf(_+2)===-1&&y.indexOf(_+3)===-1&&y.indexOf(_+4)===-1&&y.indexOf(_-1)===-1&&y.indexOf(_-2)===-1&&y.indexOf(_-3)===-1&&y.indexOf(_-4)===-1?(y.push(_),!0):!1}),this.highlighter.destroyHighlights(qe.LineFocus);let m=[];this.properties.lines&&this.properties.lines>1?S(g,this.properties.lines).forEach(_=>{m.push(b(_))}):m=g;let E=de(n,"#"+Re.R2_ID_LINEFOCUS_CONTAINER);if(E)for(let O of m){let _=document.createElement("div");_.setAttribute("class",hn);let A=v();if(De.isHexColor(A)&&(A=De.hexToRgbChannels(A)),this.isDebug){let he=`border-bottom: 1px solid rgba(${A.red}, ${A.green}, ${A.blue}, ${D3}) !important`;_.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${A.red}, ${A.green}, ${A.blue}, ${D3}) !important; ${he}`)}_.style.outline="none",_.tabIndex=0;let T=this.delegate.iframes[0].contentWindow.document,M=this.delegate.view.isPaginated();M?T.body.style.position="revert":T.body.style.position="relative";let j=T.body.getBoundingClientRect(),P=this.highlighter.getScrollingElement(T),q=M?-P.scrollLeft:j.left,U=M?-P.scrollTop:j.top,k=1,B=24,N,W,ye=this.delegate.iframes[0].contentWindow?.innerWidth,be=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-count")),fe=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-width")),re=parseInt(getComputedStyle(n.body).getPropertyValue("padding-left"));if(ye){let he=ye/(be||1);he<fe&&(he=ye),M||(he=parseInt(getComputedStyle(n.body).width.replace("px","")));let Ae=this.delegate.settings.fontSize/100,ue=20*Ae;Ae<=1&&(ue=-60);let Oe=0;Ae<=1&&(Oe=-60),N=Math.floor(O.left/he)*he+he-(B<40?40:B)+Oe,W=Math.floor(O.left/he)*he+(B<40?40:B)-ue;let Ce=parseInt(n.documentElement.style.getPropertyValue("--USER__pageMargins"));Ce>=2&&(W=W+re/be,N=N-re/be),M||(N=parseInt(getComputedStyle(n.body).width.replace("px","")),W=parseInt(getComputedStyle(n.body).width.replace("px",""))-he,Ce>=2&&(W=W+re/2,N=N-re/2))}_.style.setProperty("pointer-events","none"),_.style.position="absolute",_.scale=k,_.rect={height:O.height,left:O.left-q,top:O.top-U,width:O.width},_.style.width=`${_.rect.width*k}px`,_.style.height=`${_.rect.height*k}px`,_.style.left=`${_.rect.left*k}px`,_.style.top=`${_.rect.top*k}px`,this.lines.push(_),E.append(_)}setTimeout(()=>{this.currentLine()},100)}}currentLine(){let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}lineDown(){if(this.index<this.lines.length-1){this.index+=1,this.index>this.lines.length-1&&(this.index=this.lines.length-1);let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}}lineUp(){if(this.index>0){this.index-=1,this.index<0&&(this.index=0);let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}}almostEqual(t,n,r){return Math.abs(t-n)<=r}findRects(t){let n=this.findTextNodes(t),r=Array.from(t.getElementsByTagName("img")),o=[];return n.forEach(a=>{o.push(...this.measureTextNodes(a))}),r.forEach(a=>{o.push(...this.measureImageNodes(a))}),o}findTextNodes(t,n=[]){let r=t.firstChild;for(;r;)r.nodeType===1&&this.findTextNodes(r,n),r.nodeType===3&&r.textContent?.trim()&&(r.textContent.trim().length>1||r.parentElement?.tagName.toLowerCase()==="h1"||r.parentElement?.tagName.toLowerCase()==="h2"||r.parentElement?.tagName.toLowerCase()==="h3"||r.parentElement?.tagName.toLowerCase()==="h4"||r.parentElement?.tagName.toLowerCase()==="h5"||r.parentElement?.tagName.toLowerCase()==="h6")&&r.parentElement&&getComputedStyle(r.parentElement).verticalAlign==="baseline"&&n.push(r),r=r.nextSibling;return n}measureTextNodes(t){try{let n=document.createRange();n.selectNodeContents(t);let r=Array.from(n.getClientRects());return n.detach(),r}catch(n){co.default.log("measureTextNode "+n),co.default.log("measureTextNode "+t),co.default.log(`${t.textContent}`)}}measureImageNodes(t){try{let n=document.createRange();n.selectNode(t);let r=Array.from(n.getClientRects());return n.detach(),r}catch(n){co.default.log("measureTextNode "+n),co.default.log("measureTextNode "+t),co.default.log(`${t.textContent}`)}}};C();var Vd=Je(Dt()),lg=class{constructor(t,n,r,o,a){this.history=[];this.headerMenu=a,this.delegate=n,this.publication=r,this.properties=o,this.annotator=t}static async create(t){let n=new this(t.annotator,t.delegate,t.publication,t,t.headerMenu);return await n.start(),n}async stop(){Vd.default.log("Page Break module stop"),Pe(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),Pe(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleResize(){await this.setup()}setup(){this.history.length>0&&(this.historyForwardAnchorElement&&this.historyCurrentIndex+1<this.history.length?this.historyForwardAnchorElement.className=this.historyForwardAnchorElement.className.replace(" disabled",""):this.historyForwardAnchorElement&&(this.historyForwardAnchorElement.removeAttribute("href"),this.historyForwardAnchorElement.className+=" disabled"),this.historyBackAnchorElement&&this.historyCurrentIndex>0?this.historyBackAnchorElement.className=this.historyBackAnchorElement.className.replace(" disabled",""):this.historyBackAnchorElement&&(this.historyBackAnchorElement.removeAttribute("href"),this.historyBackAnchorElement.className+=" disabled"))}async push(t,n){let r;if(n&&this.annotator){let o=await this.annotator.getLastReadingPosition();if(o&&o.locations.progression&&o.locations.progression>0&&(this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex)),r=this.history[this.history.length-1],r&&r.href!==o.href||r===void 0)){let a=this.publication.getAbsoluteHref(o.href);Vd.default.log(o.href),Vd.default.log(a),o.href=a,this.history.push(o),this.historyCurrentIndex=this.history.length-1}this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex)),r=this.history[this.history.length-1],(r&&r.href!==t.href||r===void 0)&&(this.history.push(t),this.historyCurrentIndex=this.history.length-1)}}async start(){this.delegate.historyModule=this,this.headerMenu&&(this.historyForwardAnchorElement=de(this.headerMenu,"#history-forward")),this.headerMenu&&(this.historyBackAnchorElement=de(this.headerMenu,"#history-back")),this.historyCurrentIndex=this.history.length-1,ne(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),ne(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleHistoryForwardClick(t){this.history.length>0&&this.historyCurrentIndex+1<this.history.length&&(this.historyCurrentIndex=this.historyCurrentIndex+1,await this.delegate.navigate(this.history[this.historyCurrentIndex],!1)),t.preventDefault(),t.stopPropagation()}async handleHistoryBackClick(t){this.history.length>0&&this.historyCurrentIndex>0&&(this.historyCurrentIndex=this.historyCurrentIndex-1,await this.delegate.navigate(this.history[this.historyCurrentIndex],!1)),t.preventDefault(),t.stopPropagation()}};C();var F3=Je(Dt()),it;(function(r){r[r.Chicago=0]="Chicago",r[r.MLA=1]="MLA",r[r.APA=2]="APA"})(it||(it={}));var $3;(function(o){o.Author="Author",o.Editor="Editor",o.Translator="Translator",o.Compiler="Compiler"})($3||($3={}));var Jd=class{constructor(t,n,r,o,a){this.highlighter=r,this.delegate=t,this.properties=o,this.publication=n,this.api=a}static async create(t){let n=new this(t.delegate,t.publication,t.highlighter,t,t.api);return await n.start(),n}async stop(){F3.default.log("Timeline module stop")}copyToClipboard(t){let n=!0;if(window.clipboardData)window.clipboardData.setData("text/plain",t);else{let r=this.createElementForExecCommand(t);this.selectContent(r);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),n=document.execCommand("copy",!1)}catch(o){n=!1}document.body.removeChild(r)}n?this.api?.citationCreated("The text was copied to the clipboard!"):this.api?.citationFailed("Your browser doesn't allow clipboard access!")}createElementForExecCommand(t){let n=document.createElement("div");return n.style.position="absolute",n.style.left="-10000px",n.style.top="-10000px",n.innerHTML=t,document.body.appendChild(n),n.contentEditable=!0,n}selectContent(t){let n=document.createRange();n.selectNodeContents(t);let r=window.getSelection();r?.removeAllRanges(),r?.addRange(n)}async start(){this.delegate.citationModule=this;let t=this,n={id:"citationIcon",callback:function(r){let o=function(){let P="",q="",U="";return t.publication.Metadata.Author?.length>0&&0===0&&t.publication.Metadata.Author[0].Name&&t.publication.Metadata.Author[0].Name.length>0&&(U=U+t.publication.Metadata.Author[0].Name,q=q+t.publication.Metadata.Author[0].Name,P=P+t.publication.Metadata.Author[0].Name),U.length>0&&q.length>0&&P.length>0?[P+". ",q+". ",U+". "]:["","",""]},a=function(){let P="",q="",U="";return t.publication.Metadata.Publisher&&t.publication.Metadata.Publisher[0].Name&&(q=q+t.publication.Metadata.Publisher[0].Name+", ",P=P+t.publication.Metadata.Publisher[0].Name+", "),t.publication.Metadata.PublicationDate&&t.publication.Metadata.PublicationDate.getFullYear()>0&&(U=U+"("+t.publication.Metadata.PublicationDate.getFullYear()+")",q=q+t.publication.Metadata.PublicationDate.getFullYear(),P=P+t.publication.Metadata.PublicationDate.getFullYear()),U.length>0&&q.length>0&&P.length>0?[P+". ",q+". ",U+". "]:["","",""]},l=function(){return t.publication.Metadata.Title?[t.publication.Metadata.Title+". ",t.publication.Metadata.Title+". ",t.publication.Metadata.Title+". "]:["","",""]},u=function(){return["","",""]},d=function(){let P="",q="",U="";return t.publication.Metadata.Publisher&&t.publication.Metadata.Publisher[0].Name&&(q=q+t.publication.Metadata.Publisher[0].Name+", ",P=P+t.publication.Metadata.Publisher[0].Name+", ",U=U+t.publication.Metadata.Publisher[0].Name+", "),U.length>0&&q.length>0&&P.length>0?[P+". ",q+". ",U+". "]:["","",""]},f=function(){return["","",""]},g=function(){return["","",""]},y=function(){return["","",""]},v=function(){return t.properties.library?["Retrieved from "+t.properties.library+". ","Retrieved from "+t.properties.library+". ","Retrieved from "+t.properties.library+". "]:["","",""]},S=function(){return t.properties.appName?[t.properties.appName+". ",t.properties.appName+". ",t.properties.appName+". "]:["","",""]},w=function(){return t.properties.appLink?[t.properties.appLink+". ",t.properties.appLink+". ",t.properties.appLink+". "]:["","",""]},b=function(){return["","",""]},m=function(P,q){return P.length>q?P.substring(0,q)+"...":P},E=o()[0]+l()[0]+f()[0]+u()[0]+y()[0]+a()[0]+g()[0]+v()[0]+S()[0]+w()[0],O=o()[2]+a()[2]+l()[2]+u()[2]+d()[2]+f()[2]+g()[2]+y()[2]+v()[2]+S()[2]+w()[2],_=o()[1]+l()[1]+f()[1]+u()[1]+y()[1]+a()[1]+b()[1]+v()[1]+S()[1]+w()[1],A="\u201C"+m(r,t.properties.characters)+"\u201C<br><br><em>"+E+"</em>",T="\u201C"+m(r,t.properties.characters)+"\u201C<br><br><em>"+O+"</em>",M="\u201C"+m(r,t.properties.characters)+"\u201C<br><br><em>"+_+"</em>",j="";t.properties.styles?.includes(it[0])&&(j=j+"Chicago: <br>"+A+"<br><br>"),t.properties.styles?.includes(it[2])&&(j=j+"APA: <br>"+T+"<br><br>"),t.properties.styles?.includes(it[1])&&(j=j+"MLA: <br>"+M+"<br><br>"),t.copyToClipboard(j)}};this.highlighter?.addSelectionMenuItem(n)}};var Ko=class{constructor(t,n,r,o,a,l,u,d,f,g,y,v,S,w,b,m,E){this.settings=t;this.navigator=n;this.highlighter=r;this.bookmarkModule=o;this.annotationModule=a;this.ttsSettings=l;this.ttsModule=u;this.searchModule=d;this.definitionsModule=f;this.contentProtectionModule=g;this.timelineModule=y;this.mediaOverlaySettings=v;this.mediaOverlayModule=S;this.pageBreakModule=w;this.lineFocusModule=b;this.historyModule=m;this.citationModule=E;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,r)=>{this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchIndex(t,n,r)};this.goToSearchID=async(t,n,r)=>{this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchID(t,n,r)};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.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,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};n.enableContentProtection&&t.protection&&await jd.setupPreloadProtection(t.protection);let r=dt(document,"#D2Reader-Container"),o=de(document,"#headerMenu"),a=de(document,"#footerMenu"),l=t.url,u;t.publication?(u=Ts(t.publication,Ji),u.manifestUrl=new URL(l)):u=await Ji.fromUrl(l,t.requestConfig);let d=new Ys({prefix:u.manifestUrl,useLocalStorage:t.useLocalStorage??!1}),f=new Ys({prefix:"r2d2bc-reader",useLocalStorage:t.useLocalStorage??!1}),g=new Ys({prefix:"r2d2bc-layers",useLocalStorage:t.useLocalStorage??!1}),y=new lo({store:d});u.sample=t.sample,n=dN(n,u),n.autoGeneratePositions?await u.autoGeneratePositions(t.requestConfig):(t.services?.positions&&await u.fetchPositionsFromService(t.services?.positions.href,t.requestConfig),t.services?.weight&&await u.fetchWeightsFromService(t.services?.weight.href,t.requestConfig));let v=await ig.create({store:g}),S=await No.create({store:f,initialUserSettings:t.userSettings,headerMenu:o,api:t.api,injectables:(u.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed:t.injectables,layout:(u.Metadata.Rendition?.Layout??"unknown")==="fixed"?"fixed":"reflowable"}),w=await Ln.create({mainElement:r,headerMenu:o,footerMenu:a,publication:u,settings:S,annotator:y,initialLastReadingPosition:t.lastReadingPosition,api:t.api,rights:n,tts:t.tts,sample:t.sample,requestConfig:t.requestConfig,injectables:(u.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed??[]:t.injectables,attributes:t.attributes,services:t.services}),b=await De.create(Fe({delegate:w,layerSettings:v},t.highlighter)),m=n.enableBookmarks?await el.create(Fe({annotator:y,headerMenu:o,rights:n,publication:u,delegate:w,initialAnnotations:t.initialAnnotations},t.bookmarks)):void 0,E=n.enableAnnotations?await Qa.create(Fe({annotator:y,rights:n,publication:u,delegate:w,initialAnnotations:t.initialAnnotations,highlighter:b,headerMenu:o},t.annotations)):void 0,O=n.enableTTS,_=O?await ng.create({store:f,initialTTSSettings:t.tts,headerMenu:o}):void 0,A;O&&_&&(A=await sg.create(Fe({delegate:w,tts:_,headerMenu:o,rights:n,highlighter:b},t.tts)));let T=n.enableSearch?await tg.create(Fe({headerMenu:o,delegate:w,publication:u,highlighter:b},t.search)):void 0,M=n.enableDefinitions?await ag.create(Fe({delegate:w,publication:u,highlighter:b},t.define)):void 0,j=n.enableTimeline?await L0.create({publication:u,delegate:w}):void 0,P=n.enableContentProtection?await jd.create(Fe({delegate:w},t.protection)):void 0,q=n.enableMediaOverlays,U=q?await M0.create(Fe({store:f,initialMediaOverlaySettings:t.mediaOverlays,headerMenu:o},t.mediaOverlays)):void 0,k=q?await P0.create(Fe({publication:u,delegate:w,settings:U},t.mediaOverlays)):void 0,N=n.enablePageBreaks&&u.isReflowable?await og.create(Fe({publication:u,headerMenu:o,delegate:w},t.pagebreak)):void 0,W=n.enableLineFocus?await Gd.create(Fe({publication:u,delegate:w,highlighter:b},t.lineFocus)):void 0,ye=n.enableHistory?await lg.create({annotator:y,publication:u,delegate:w,headerMenu:o}):void 0,be=n.enableCitations?await Jd.create(Fe({publication:u,delegate:w,highlighter:b},t.citations)):void 0;return new Ko(S,w,b,m,E,_,A,T,M,P,j,U,k,N,W,ye,be)}get hasMediaOverlays(){return this.navigator.hasMediaOverlays}get tableOfContents(){return al(this.navigator.tableOfContents())??[]}get readingOrder(){return al(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 dN(i,t){return t.isFixedLayout&&(i.enableAnnotations=!1,i.enableSearch=!1,i.enableTTS=!1,i.enableDefinitions=!1,i.enablePageBreaks=!1,i.enableLineFocus=!1),t.sample?.isSampleRead&&(i.enableAnnotations=!1,i.enableSearch=!1,i.enableTTS=!1,i.enableDefinitions=!1,i.enableTimeline=!1,i.enableMediaOverlays=!1,i.enablePageBreaks=!1,i.enableLineFocus=!1),i}var fN=Ko,hN=Ko.load;return pN;})();
82
+ `;var zd=Je(Qi());C();var Ks=class{constructor(t){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{let n=null,r=null,o=this;t&&(t.addEventListener("touchstart",function(a){a.changedTouches.length===1&&(n=a)},!1),t.addEventListener("touchend",function(a){if(a.changedTouches.length!==1||!n)return;let l=n.changedTouches[0],u=a.changedTouches[0];if(!l)return;let d=window.devicePixelRatio,f=(l.clientX-u.clientX)/d,g=(l.clientY-u.clientY)/d;if(Math.abs(f)<Ks.TAP_TOLERANCE&&Math.abs(g)<Ks.TAP_TOLERANCE){if(r){n=null,r=null;return}if(a.timeStamp-n.timeStamp>Ks.LONG_PRESS_MS){n=null,r=null;return}n=null,r=a;return}if(r=null,a.timeStamp-n.timeStamp>Ks.SLOW_SWIPE_MS){n=null;return}let y=(l.clientY-u.clientY)/(l.clientX-u.clientX);if(Math.abs(y)>.5){n=null;return}f<0?o.onBackwardSwipe(a):o.onForwardSwipe(a),n=null},!1))};this.navigator=t}},Go=Ks;Go.TAP_TOLERANCE=10,Go.LONG_PRESS_MS=500,Go.SLOW_SWIPE_MS=500;C();var $d=class{constructor(t){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{t&&(this.focusin(t),this.keydown(t))};this.focusin=t=>{let n=this;t.addEventListener("focusin",function(r){n.navigator.view?.snap(r.target)},!0)};this.keydown=t=>{let n=this;this.navigator.rights.customKeyboardEvents||t.addEventListener("keydown",function(r){let o=r.target;if(/input|select|option|textarea/i.test(o.tagName)||!(o.ownerDocument||o).defaultView.getSelection().isCollapsed)return;switch(r.key){case"ArrowRight":n.onForwardSwipe(r);break;case"ArrowLeft":n.onBackwardSwipe(r);break}},!1)};this.navigator=t}};C();var A3=Je(Qi()),Ud=class{constructor(t){this.enforceSampleRead=(0,A3.debounce)(t=>{let n=Math.round(t.locations.totalProgression*100),r=!1;this.delegate.sample?.limit&&(r=n<=this.delegate.sample?.limit,this.delegate.view?.layout==="fixed"&&!r&&this.delegate.sample?.minimum&&t.locations.position<=this.delegate.sample?.minimum&&(r=!0));let o={37:1,38:0,39:1,40:1,32:1,33:1,34:1,35:1,36:1};function a(w){w.preventDefault()}function l(w){o[w.keyCode]&&!r&&a(w)}let u=!1,d=Object.defineProperty&&Object.defineProperty({},"passive",{get:function(){u=!0}});window.addEventListener("test",function(){},d);let f=u?{passive:!1}:!1;function g(w){w=w||window.event;let b=Math.max(-1,Math.min(1,w.wheelDelta||-w.detail));return b===-1&&!r&&w.preventDefault(),!1}let y;function v(w){w=w||window.event;let b=w.target||w.srcElement,m=w.touches[0].clientY;if(!(m>y)){if(m<y&&!r)return b.className.match(/\baltNav\b/)||(w.returnValue=!1,w.cancelable&&(w.cancelBubble=!0),w.preventDefault&&w.cancelable&&(w.preventDefault(),w.stopPropagation())),!1}return y=m,!1}function S(w){return w=w||window.event,y=w.touches[0].clientY,!1}window.addEventListener("mousewheel",g,f),window.addEventListener("DOMMouseScroll",g,f),window.addEventListener("keydown",l,f),window.addEventListener("touchmove",v,f),window.addEventListener("touchstart",S,f),r?(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 M3=Je(R3()),Yn=Je(Dt()),Ln=class extends M3.default{constructor(t,n=void 0,r=void 0,o,a,l,u,d,f,g,y,v){super();this.iframes=[];this.sideNavExpanded=!1;this.currentChapterLink={href:""};this.currentSpreadLinks={};this.rights={autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};this.didInitKeyboardEventHandler=!1;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.reload=async()=>{let t;if(this.annotator&&(t=await this.annotator.getLastReadingPosition()),t){let n=this.publication.getAbsoluteHref(t.href);Yn.default.log(t.href),Yn.default.log(n),t.href=n,await this.navigate(t)}};this.savePosition=(0,zd.debounce)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,zd.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=f,this.view.delegate=this,this.eventHandler=new pd(this),this.touchEventHandler=new Go(this),this.keyboardEventHandler=new $d(this),this.initialLastReadingPosition=r,this.publication=o,this.api=a,this.rights=l??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1},this.tts=u,this.injectables=d,this.attributes=f||{margin:0},this.services=g,this.sample=y,this.requestConfig=v,this.sampleReadEventHandler=new Ud(this)}static async create(t){let n=new this(t.settings,t.annotator||void 0,t.initialLastReadingPosition||void 0,t.publication,t.api,t.rights,t.tts,t.injectables,t.attributes||{margin:0},t.services,t.sample,t.requestConfig);return await n.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(r=>r(n))}stop(){Yn.default.log("Iframe navigator stop"),Pe(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),Pe(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),Pe(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Pe(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),Pe(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Pe(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),Pe(this.tryAgainButton,"click",this.tryAgain.bind(this)),Pe(this.goBackButton,"click",Ln.goBack.bind(this)),Pe(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),Pe(window,"resize",this.onResize),this.iframes.forEach(t=>{Pe(t,"resize",this.onResize)})}async start(t,n,r){this.headerMenu=n,this.mainElement=t;try{let S=dt(t,"main#iframe-wrapper");S.style.overflow="auto";let w=de(t,"main#iframe-wrapper iframe"),b=de(t,"#second");if(w&&this.iframes.push(w),b&&this.iframes.push(b),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.iframes.length===0){S.style.overflow="auto";let m=document.createElement("iframe");if(m.setAttribute("SCROLLING","no"),m.setAttribute("allowtransparency","true"),this.iframes.push(m),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]),S.appendChild(this.spreads)):(m.setAttribute("height","100%"),m.setAttribute("width","100%"),S.appendChild(this.iframes[0])),this.publication.isFixedLayout)if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){let E=document.createElement("div");this.spreads.appendChild(E);let O=document.createElement("iframe");O.setAttribute("SCROLLING","no"),O.setAttribute("allowtransparency","true"),O.style.opacity="1",O.style.border="none",O.style.overflow="hidden",this.iframes.push(O),E.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",E.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",E.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 m=S.clientHeight;var o=this.iframes[0].parentElement?.parentElement;o.style.height=m+40+"px"}else this.iframes.length===2&&this.iframes.pop();if(this.loadingMessage=de(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=_3,this.loadingMessage.style.display="none"),this.errorMessage=de(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=T3,this.errorMessage.style.display="none"),this.tryAgainButton=de(t,"button[class=try-again]"),this.goBackButton=de(t,"button[class=go-back]"),this.infoTop=de(t,"div[class='info top']"),this.infoBottom=de(t,"div[class='info bottom']"),this.headerMenu&&(this.bookTitle=de(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=de(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=de(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=de(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=de(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=de(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=de(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=de(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=de(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=de(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=de(this.headerMenu,"#container-view-pagelist")),r&&(this.linksBottom=de(r,"ul.links.bottom")),r&&(this.linksMiddle=de(r,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=de(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=de(t,"#next-chapter")),r&&(this.nextPageAnchorElement=de(r,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=de(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=de(t,"#previous-chapter")),r&&(this.previousPageAnchorElement=de(r,"a[rel=prev]")),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.newPosition=void 0,this.newElementId=void 0,this.isBeingStyled=!0,this.isLoading=!0,this.settings.setIframe(this.iframes[0]),this.settings.onSettingsChange(this.handleResize.bind(this)),this.settings.onColumnSettingsChange(this.handleNumberOfIframes.bind(this)),this.settings.onViewChange(this.updateBookView.bind(this)),this.initialLastReadingPosition&&this.annotator?.initLastReadingPosition(this.initialLastReadingPosition),this.headerMenu){var a=de(this.headerMenu,"#menu-button-search"),l=de(this.headerMenu,"#menu-button-tts"),u=de(this.headerMenu,"#menu-button-bookmark"),d=de(this.headerMenu,"#menu-button-play"),f=de(this.headerMenu,"#menu-button-pause"),g=de(this.headerMenu,"#menu-button-mediaoverlay");if(!this.rights.enableBookmarks){u&&u.parentElement?.style.setProperty("display","none");var y=de(this.headerMenu,"#sidenav-section-bookmarks");y&&y.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var v=de(this.headerMenu,"#sidenav-section-highlights");v&&v.style.setProperty("display","none")}this.rights.enableTTS||l&&l.parentElement?.style.setProperty("display","none"),this.rights.enableSearch||a&&a.parentElement?.style.setProperty("display","none"),a&&this.view?.delegate.publication.isFixedLayout&&a.parentElement?.style.setProperty("display","none"),this.hasMediaOverlays?(d&&d.parentElement?.style.removeProperty("display"),f&&f.parentElement?.style.removeProperty("display"),g&&g.parentElement?.style.removeProperty("display")):(d&&d.parentElement?.style.setProperty("display","none"),f&&f.parentElement?.style.setProperty("display","none"),g&&g.parentElement?.style.setProperty("display","none"))}else a&&a.parentElement?.style.setProperty("display","none"),l&&l.parentElement?.style.setProperty("display","none"),u&&u.parentElement?.style.setProperty("display","none");return this.setupEvents(),await this.loadManifest()}catch(S){return Yn.default.error(S),this.abortOnError(S),Promise.reject(S)}}setupEvents(){for(let t of this.iframes)ne(t,"load",this.handleIFrameLoad.bind(this));ne(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),ne(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),ne(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ne(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),ne(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),ne(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),ne(this.tryAgainButton,"click",this.tryAgain.bind(this)),ne(this.goBackButton,"click",Ln.goBack.bind(this)),ne(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),ne(window,"resize",this.onResize);for(let t of this.iframes)ne(t,"resize",this.onResize)}updateBookView(){this.view?.layout==="fixed"?(this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousChapterClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextChapterClick.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this))):(this.settings.isPaginated().then(t=>{if(t)this.view.height=Fr()-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,zd.debounce)(()=>{this.isScrolling=!1},200),r=dt(document,"#iframe-wrapper");r.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(qe.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(qe.Search),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule!==void 0&&this.highlighter!==void 0&&await this.definitionsModule.drawDefinitions()},200))}async loadManifest(){try{let t=(d,f,g=!1)=>{var y=document.createElement("ul");g&&(y=document.createElement("ol")),y.className="sidenav-toc";for(let v of f){let S=document.createElement("li"),w=document.createElement("a"),b=document.createElement("span");w.className="chapter-link",w.tabIndex=-1;let m="";v.Href?(m=this.publication.getAbsoluteHref(v.Href),w.href=m,w.innerHTML=v.Title||"",S.appendChild(w)):(b.innerHTML=v.Title||"",b.className="chapter-title",S.appendChild(b)),v.Children&&v.Children.length>0&&t(S,v.Children,!0),y.appendChild(S)}ne(y,"click",v=>{if(v.preventDefault(),v.stopPropagation(),v.target&&v.target.tagName.toLowerCase()==="a"){let S=v.target;if(S.className.indexOf("active")!==-1)this.hideView();else{let w={progression:0};if(S.href.indexOf("#")!==-1){let m=S.href.slice(S.href.indexOf("#")+1);m!==void 0&&(w={fragment:m})}let b={href:S.href,locations:w,type:S.type,title:S.title};this.hideView(),this.navigate(b)}}}),d.appendChild(y)},n=this.publication.tableOfContents,r=this.publication.landmarks,o=this.publication.pageList;this.tocView&&(n.length?t(this.tocView,n):this.tocView.parentElement?.parentElement?.removeChild(this.tocView.parentElement)),this.pageListView&&(o?.length?t(this.pageListView,o):this.pageListView.parentElement?.parentElement?.removeChild(this.pageListView.parentElement)),this.landmarksView&&(r?.length?t(this.landmarksView,r):this.landmarksSection.parentElement?.removeChild(this.landmarksSection));let a;this.annotator&&(a=await this.annotator.getLastReadingPosition());let l=this.publication.getStartLink(),u;if(l&&l.Href&&(u=this.publication.getAbsoluteHref(l.Href)),a){let d=this.publication.getAbsoluteHref(a.href);Yn.default.log(a.href),Yn.default.log(d),a.href=d,await this.navigate(a)}else if(u){let d={href:u,locations:{progression:0},created:new Date,title:l?.Title};await this.navigate(d)}return new Promise(d=>d())}catch(t){return Yn.default.error(t),this.abortOnError(t),new Promise((n,r)=>r(t)).catch(()=>{})}}async handleIFrameLoad(){this.errorMessage&&(this.errorMessage.style.display="none"),this.showLoadingMessageAfterDelay();try{let t=0;this.newPosition&&(t=this.newPosition.locations.progression),await this.handleResize(),this.updateBookView(),await this.settings.applyProperties();let n=this.currentChapterLink.href;if(n){let d=this.publication.getPreviousSpineItem(n);d&&d.Href&&(this.previousChapterLink={href:d.Href,title:d.Title,type:d.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 r=this.publication.getNextSpineItem(n);r?this.nextChapterLink={href:r.Href,title:r.Title,type:r.TypeLink}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink&&this.nextChapterLink.href?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.historyModule&&this.historyModule.setup(),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(n),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let o=this.publication.getSpineItem(n);o!==void 0&&(this.currentChapterLink.title=o.Title,this.currentChapterLink.type=o.TypeLink);let a=this.publication.getTOCItem(n);this.currentTocUrl!==void 0&&(a=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&a!==void 0&&a.Title&&(this.currentChapterLink.title=a.Title),!this.currentChapterLink.type&&a!==void 0&&a.TypeLink&&(this.currentChapterLink.title=a.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),await this.injectInjectablesIntoIframeHead(),this.highlighter!==void 0&&await this.highlighter.initialize();let u=this.iframes[0].contentDocument?.body?.querySelector("details");if(u){let d=this;u.addEventListener("toggle",async f=>{await d.view?.setIframeHeight?.(this.iframes[0])})}if(this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.initialize(),this.eventHandler){for(let d of this.iframes)this.eventHandler.setupEvents(d.contentDocument),this.touchEventHandler.setupEvents(d.contentDocument),this.keyboardEventHandler.setupEvents(d.contentDocument);this.touchEventHandler.setupEvents(this.errorMessage),this.didInitKeyboardEventHandler||(this.keyboardEventHandler.keydown(document),this.didInitKeyboardEventHandler=!0)}if(this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(this.iframes[0].height="0",this.view?.setIframeHeight?.(this.iframes[0])),this.annotationModule!==void 0&&await this.annotationModule.initialize(),this.bookmarkModule!==void 0&&await this.bookmarkModule.initialize(),this.rights.enableTTS)for(let d of this.iframes){let f=d.contentDocument?.body;this.ttsModule!==void 0&&await this.ttsModule.initialize(f)}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 d=this.iframes[0].contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(d),this.newElementId=void 0}else if(this.newPosition&&this.newPosition.highlight){let d=this.newPosition.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;d&&this.view?.goToCssSelector(d)}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 d=this.currentLink();await this.mediaOverlayModule?.initializeResource(d)}await this.updatePositionInfo(),await this.view?.setSize(),setTimeout(()=>{this.mediaOverlayModule!==void 0&&(this.mediaOverlayModule.settings.resourceReady=!0)},300)},200),new Promise(d=>d())}catch(t){return Yn.default.error(t),this.abortOnError(t),Promise.reject(t)}}async injectInjectablesIntoIframeHead(){let t=[],n=r=>{let o=new Promise((a,l)=>{r.onload=()=>{a(!0)},r.onerror=u=>{let d=typeof u=="string"?u:`Injectable failed to load at: ${"href"in r?r.href:r.src}`;l(new Error(d))}});t.push(o)};for(let r of this.iframes){let o=r.contentDocument?.head;o&&(r.contentDocument.getElementsByTagName("base").length===0&&o.insertBefore(Ln.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 u=Ln.createCssLink(l.url);o.appendChild(u),n(u)}}else if(l.r2before&&l.url){let u=Ln.createCssLink(l.url);o.insertBefore(u,o.firstChild),n(u)}else if(l.r2default&&l.url){let u=Ln.createCssLink(l.url);o.insertBefore(u,o.childNodes[1]),n(u)}else if(l.r2after&&l.url){l.appearance&&this.settings.initAddedAppearance();let u=Ln.createCssLink(l.url);o.appendChild(u),n(u)}else if(l.url){let u=Ln.createCssLink(l.url);o.appendChild(u),n(u)}}else if(l.type==="script"&&l.url){let u=Ln.createJavascriptLink(l.url,l.async??!1);o.appendChild(u),n(u)}}))}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),r=(n??0)%2==1;this.showLoadingMessageAfterDelay();function o(d,f){let y=new DOMParser().parseFromString(d,"application/xhtml+xml");y.head&&y.getElementsByTagName("base").length===0&&y.head.insertBefore(Ln.createBase(f),y.head.firstChild);let v=y.documentElement.outerHTML,S=t.iframes[0].contentDocument;S&&(S.open(),S.write(v),S.close())}function a(d,f){let y=new DOMParser().parseFromString(d,"application/xhtml+xml");y.head&&y.getElementsByTagName("base").length===0&&y.head.insertBefore(Ln.createBase(f),y.head.firstChild);let v=y.documentElement.outerHTML,S=t.iframes[1].contentDocument;S&&(S.open(),S.write(v),S.close())}let l=new URL(this.currentChapterLink.href),u=window.location.protocol===l.protocol&&window.location.port===l.port&&window.location.hostname===l.hostname;if(this.api?.getContent)if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(r){if(this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(d=>{d===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(f=>f.text()).then(async f=>{o.call(this,f,this.currentChapterLink.href)}):o.call(this,d,this.currentChapterLink.href)}),this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let d=this.publication.getNextSpineItem(this.currentChapterLink.href);if(d){let f=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.right={href:f},this.api?.getContent(f).then(g=>{g===void 0?u?this.iframes[1].src=f:fetch(f,this.requestConfig).then(y=>y.text()).then(async y=>{a.call(this,y,f),this.currentSpreadLinks.right={href:f}}):a.call(this,g,f)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let d=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(d){let f=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.left={href:f},this.api?.getContent(f).then(g=>{g===void 0?u?this.iframes[0].src=f:fetch(f,this.requestConfig).then(y=>y.text()).then(async y=>{o.call(this,y,f)}):o.call(this,g,f)})}}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(d=>{d===void 0?u?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(f=>f.text()).then(async f=>{a.call(this,f,this.currentChapterLink.href)}):a.call(this,d,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(d=>{d===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(f=>f.text()).then(async f=>{o.call(this,f,this.currentChapterLink.href)}):o.call(this,d,this.currentChapterLink.href)});else this.api?.getContent(this.currentChapterLink.href).then(d=>{this.currentSpreadLinks.left={href:this.currentChapterLink.href},d===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(f=>f.text()).then(async f=>{o.call(this,f,this.currentChapterLink.href)}):o.call(this,d,this.currentChapterLink.href)});else if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(r){if(u){if(this.iframes[0].src=this.currentChapterLink.href,this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let d=this.publication.getNextSpineItem(this.currentChapterLink.href);if(d){let f=this.publication.getAbsoluteHref(d.Href);this.iframes[1].src=f,this.currentSpreadLinks.right={href:f}}}else this.iframes[1].src="about:blank"}else if(fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)}),this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let d=this.publication.getNextSpineItem(this.currentChapterLink.href);if(d){let f=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.right={href:f},fetch(f,this.requestConfig).then(g=>g.text()).then(async g=>{a.call(this,g,f)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let d=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(d){let f=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.left={href:f},u?(this.iframes[0].src=f,this.iframes.length===2&&(this.iframes[1].src=this.currentChapterLink.href)):(fetch(f,this.requestConfig).then(g=>g.text()).then(async g=>{o.call(this,g,f)}),this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},fetch(this.currentChapterLink.href,this.requestConfig).then(g=>g.text()).then(async g=>{a.call(this,g,this.currentChapterLink.href)})))}}else this.iframes[0].src="about:blank";this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},u?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{a.call(this,d,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)});else this.currentSpreadLinks.left={href:this.currentChapterLink.href},u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)});this.publication.isFixedLayout&&setTimeout(()=>{let d,f,g;if(n===0&&this.iframes?.length===2?g=this.iframes[1].contentDocument:g=this.iframes[0].contentDocument,g&&g.body&&(d=getComputedStyle(g.body).height,f=getComputedStyle(g.body).width,parseInt(d?.replace("px",""))===0||parseInt(f?.replace("px",""))===0)){let E=Qt(g,"head");if(E){let O=de(E,"meta[name=viewport]");if(O){var y=O.content,v=y.split(",").reduce((_,A)=>{var[T,M]=A.match(/[^\s;=]+/g);return _[T]=isNaN(Number(M))?M:+M,_},{});d=v.height+"px",f=v.width+"px"}}}var S=n===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(S&&f){var w=(parseInt(getComputedStyle(S).width)-100)/(this.iframes.length===2?parseInt(f?.replace("px",""))*2+200:parseInt(f?.replace("px",""))),b=(parseInt(getComputedStyle(S).height)-100)/parseInt(d?.replace("px","")),m=Math.min(w,b);S.style.transform="scale("+m+")";for(let E of this.iframes)E.style.height=d,E.style.width=f,E.parentElement&&(E.parentElement.style.height=d)}},400)}static goBack(){window.history.back()}handleEditClick(t){var n=t.target;if(this.headerMenu){var r=de(document,".sidenav");n.className.indexOf(" active")===-1?(n.className+=" active",r.className+=" expanded",n.innerText="unfold_less",this.sideNavExpanded=!0,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights()):(n.className=n.className.replace(" active",""),r.className=r.className.replace(" expanded",""),n.innerText="unfold_more",this.sideNavExpanded=!1,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights())}t.preventDefault(),t.stopPropagation()}get hasMediaOverlays(){return this.publication.hasMediaOverlays}startReadAloud(){this.rights.enableTTS&&this.ttsModule.speakPlay()}startReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.startReadAloud()}stopReadAloud(){this.rights.enableTTS&&this.highlighter?.stopReadAloud()}stopReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.stopReadAloud()}pauseReadAloud(){this.rights.enableTTS&&(this.ttsModule.speakPause(),this.annotationModule!==void 0&&this.annotationModule.drawHighlights())}pauseReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.pauseReadAloud()}resumeReadAloud(){this.rights.enableTTS&&this.ttsModule.speakResume()}resumeReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.resumeReadAloud()}totalResources(){return this.publication.readingOrder.length}mostRecentNavigatedTocItem(){return this.publication.getRelativeHref(this.currentTOCRawLink)}currentResource(){let t=this.currentChapterLink.href;return this.publication.getSpineIndex(t)}currentLink(){if(this.settings.columnCount!==1&&this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0){let n=this.publication.getSpineItem(this.currentSpreadLinks.left.href),r=this.publication.getSpineItem(this.currentSpreadLinks.right.href);return[n,r]}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 a=t.href.slice(t.href.indexOf("#")+1);a!==void 0&&(n=jt(Fe({},n),{fragment:a}))}let r=Fe({},t);r.locations=n;let o=this.publication.getAbsoluteHref(t.href);Yn.default.log(t.href),Yn.default.log(o),r.href=o,this.stopReadAloud(),this.navigate(r)}currentLocator(){let t;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let n=this.publication.positionsByHref(this.publication.getRelativeHref(this.currentChapterLink.href)),r=Math.ceil((this.view?.getCurrentPosition()??0)*(n.length-1));t=n[r]}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(r=>r.locations.position===parseInt(String(t)))[0];this.goTo(n)}}async goToPage(t){this.pageBreakModule!==void 0&&await this.pageBreakModule.goToPageNumber(t)}snapToSelector(t){let n=this.iframes[0].contentDocument;if(n){Yn.default.log(t);let r=n.querySelectorAll(t);r.length>0&&this.view?.snap(r[0])}}applyAttributes(t){this.attributes=t,this.view.attributes=t,this.handleResize()}handlePreviousPageClick(t){this.stopReadAloud(),this.view?.layout==="fixed"?this.handlePreviousChapterClick(t):(this.view?.atStart()?this.handlePreviousChapterClick(t):(this.view?.goToPreviousPage?.(),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))}handleNextPageClick(t){let n=!0;if(this.sample?.isSampleRead&&this.publication.positions){let r=this.currentLocator(),o=Math.round((r.locations.totalProgression??0)*100);this.sample?.limit&&(n=o<=this.sample?.limit,this.view?.layout==="fixed"&&((!n&&this.sample?.minimum&&r.locations.position)??0<=(this.sample?.minimum??0))&&(n=!0))}(n&&this.sample?.isSampleRead&&this.publication.positions||!this.sample?.isSampleRead||!this.publication.positions)&&(this.stopReadAloud(),this.view?.layout==="fixed"?this.handleNextChapterClick(t):(this.view?.atEnd()?this.handleNextChapterClick(t):(this.view?.goToNextPage?.(),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))),!n&&this.sample?.isSampleRead&&this.publication.positions&&t&&(t.preventDefault(),t.stopPropagation())}handleClickThrough(t){}handleInternalLink(t){let n=t.target,r={progression:0},o=n;if(o.href.indexOf("#")!==-1){let l=o.href.slice(o.href.indexOf("#")+1);l!==void 0&&(r={fragment:l})}let a={href:o.href,locations:r,type:o.type,title:o.title};t.preventDefault(),t.stopPropagation(),this.stopReadAloud(),this.navigate(a)}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 f=Fr()-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=f+40+"px";let g,y,v;t===0&&this.iframes?.length===2?v=this.iframes[1].contentDocument:v=this.iframes[0].contentDocument,v&&v.body&&(g=getComputedStyle(v.body).height,y=getComputedStyle(v.body).width);let S=Qt(v,"head");if(S){let w=de(S,"meta[name=viewport]");if(w){var r=w.content,o=r.split(",").reduce((b,m)=>{var[E,O]=m.match(/[^\s;=]+/g);return b[E]=isNaN(Number(O))?O:+O,b},{});(parseInt(o.height)!==0||parseInt(o.width)!==0)&&(g=o.height+"px",y=o.width+"px")}}var a=(parseInt(getComputedStyle(n).width)-100)/(this.iframes.length===2?parseInt(y?.replace("px",""))*2+200:parseInt(y?.replace("px",""))),l=(parseInt(getComputedStyle(n).height)-100)/parseInt(g?.replace("px","")),u=Math.min(a,l);n.style.transform="scale("+u+")";for(let w of this.iframes)w.style.height=g,w.style.width=y,w.parentElement&&(w.parentElement.style.height=g)}}let d=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(f=>{f?(this.view.height=Fr()-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()=>{d&&this.view?.goToProgression(d),await this.updatePositionInfo(!1),this.annotationModule!==void 0&&await this.annotationModule.handleResize(),this.bookmarkModule!==void 0&&await this.bookmarkModule.handleResize(),this.searchModule!==void 0&&await this.searchModule.handleResize(),this.definitionsModule!==void 0&&await this.definitionsModule.handleResize(),this.pageBreakModule!==void 0&&await this.pageBreakModule.handleResize(),this.contentProtectionModule!==void 0&&this.contentProtectionModule.handleResize(),this.lineFocusModule!==void 0&&this.lineFocusModule.handleResize(),this.historyModule!==void 0&&this.historyModule.handleResize()},150)}updatePositionInfo(t=!0){if(this.view?.layout==="fixed")this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");else if(this.view?.isPaginated()){let n=this.currentLocator();if(n){let r=n.displayInfo.resourceScreenIndex,o=n.displayInfo.resourceScreenCount;this.chapterPosition&&(this.chapterPosition.innerHTML="Page "+r+" 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 r=this.publication.readingOrder[n],o={href:this.publication.getAbsoluteHref(r.Href),locations:{progression:0},type:r.TypeLink,title:r.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 r=this.publication.readingOrder[n],o={href:this.publication.getAbsoluteHref(r.Href),locations:{progression:0},type:r.TypeLink,title:r.Title};this.stopReadAloud(),this.navigate(o)}else if(this.nextChapterLink){let n={href:this.publication.getAbsoluteHref(this.nextChapterLink.href),locations:{progression:0},type:this.nextChapterLink.type,title:this.nextChapterLink.title};this.stopReadAloud(),this.navigate(n)}t&&(t.preventDefault(),t.stopPropagation())}hideView(){this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(document.body.style.overflow="auto")}setActiveTOCItem(t){if(this.tocView){let n=Array.prototype.slice.call(this.tocView.querySelectorAll("li > a"));for(let o of n)o.className=o.className.replace(" active","");let r=this.tocView.querySelector('li > a[href^="'+t+'"]');r&&(r.className+=" active")}}async navigate(t,n=!0){if(this.historyModule&&this.historyModule.push(t,n),this.publication.getTOCItem(t.href)){var o=!1;if(t.href.indexOf("#")!==-1){let a=t.href.slice(0,t.href.indexOf("#"));a===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=a,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title}else t.href===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=t.href,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title;if(this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0&&(t.href===this.currentSpreadLinks.left.href||t.href===this.currentSpreadLinks.right.href))return;if(o){if(t.href.indexOf("#")!==-1){let g=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:g}}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 g of this.iframes){let y=g.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(y)}this.newElementId=void 0}else if(t.highlight){let g=t.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;g&&this.view?.goToCssSelector(g)}else this.view?.goToProgression(t.locations.progression??0);let a=this.currentChapterLink.href,l=this.publication.getPreviousSpineItem(a);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 u=this.publication.getNextSpineItem(a);u?this.nextChapterLink={href:u.Href,type:u.TypeLink,title:u.Title}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(a),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let d=this.publication.getSpineItem(a);d!==void 0&&(this.currentChapterLink.title=d.Title,this.currentChapterLink.type=d.TypeLink);let f=this.publication.getTOCItem(a);this.currentTocUrl!==void 0&&(f=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&f!==void 0&&f.Title&&(this.currentChapterLink.title=f.Title),!this.currentChapterLink.type&&f!==void 0&&f.TypeLink&&(this.currentChapterLink.title=f.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(qe.PageBreak),await this.pageBreakModule.drawPageBreaks()),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(qe.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(a=>{a||(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 a=this.publication.getStartLink(),l;if(a&&a.Href&&(l=this.publication.getAbsoluteHref(a.Href),l)){let u={href:l,locations:{progression:0},created:new Date,title:a.Title};await this.navigate(u)}}}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 r;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 a=Math.ceil((n.progression??0)*(o.length-1)),l=o[a];l&&(l.locations.fragment=n.fragment,r=jt(Fe({},l),{href:t.Href,created:new Date,title:this.currentChapterLink.title}))}}else r={href:t.Href,locations:n,created:new Date,type:this.currentChapterLink.type,title:this.currentChapterLink.title};r&&(this.sample?.isSampleRead&&this.publication.positions&&this.sampleReadEventHandler?.enforceSampleRead(r),this.api?.updateCurrentLocation?this.api?.updateCurrentLocation(r).then(async o=>(Yn.default.log("api updated current location",r),this.annotator?.saveLastReadingPosition(r))):(Yn.default.log("save last reading position",r),this.annotator.saveLastReadingPosition(r)))}}}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 r=document.createElement("script");return r.type="text/javascript",r.src=t,r.async=n,r}activateMarker(t,n){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId===void 0||this.annotationModule.activeAnnotationMarkerId!==t?(this.annotationModule.activeAnnotationMarkerId=t,this.annotationModule.activeAnnotationMarkerPosition=n,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=t)):this.deactivateMarker())}deactivateMarker(){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId=void 0,this.annotationModule.activeAnnotationMarkerPosition=void 0,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=void 0))}showLayer(t){let n="#",r=new xa("layer-on","layer-off",!0,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=Re.R2_ID_HIGHLIGHTS_CONTAINER,r.name=Re.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=Re.R2_ID_READALOUD_CONTAINER,r.name=Re.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=Re.R2_ID_PAGEBREAK_CONTAINER,r.name=Re.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=Re.R2_ID_SEARCH_CONTAINER,r.name=Re.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=Re.R2_ID_DEFINITIONS_CONTAINER,r.name=Re.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(r);let o=this.iframes[0].contentDocument;if(o){let a=de(o,n);a&&(a.style.display="block")}}hideLayer(t){let n="#",r=new xa("layer-on","layer-off",!1,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=Re.R2_ID_HIGHLIGHTS_CONTAINER,r.name=Re.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=Re.R2_ID_READALOUD_CONTAINER,r.name=Re.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=Re.R2_ID_PAGEBREAK_CONTAINER,r.name=Re.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=Re.R2_ID_SEARCH_CONTAINER,r.name=Re.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=Re.R2_ID_DEFINITIONS_CONTAINER,r.name=Re.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(r);let o=this.iframes[0].contentDocument;if(o){let a=de(o,n);a&&(a.style.display="none")}}};C();var yt=class{constructor(t){this.store=t.store}getLastReadingPosition(){let t=this.store.get(yt.LAST_READING_POSITION);return t?JSON.parse(t):null}initLastReadingPosition(t){if(typeof t=="string")this.store.set(yt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(yt.LAST_READING_POSITION,n)}}saveLastReadingPosition(t){if(typeof t=="string")this.store.set(yt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(yt.LAST_READING_POSITION,n)}}initBookmarks(t){if(typeof t=="string"){let n=JSON.parse(t);this.store.set(yt.BOOKMARKS,JSON.stringify(n))}else this.store.set(yt.BOOKMARKS,JSON.stringify(t));return t}saveBookmark(t){let n=this.store.get(yt.BOOKMARKS);if(n){let r=JSON.parse(n);r.push(t),this.store.set(yt.BOOKMARKS,JSON.stringify(r))}else{let r=[];r.push(t),this.store.set(yt.BOOKMARKS,JSON.stringify(r))}return t}locatorExists(t,n){let r;switch(n){case fr.Bookmark:r=yt.BOOKMARKS;break}let o=this.store.get(r);return o&&JSON.parse(o).filter(u=>u.href===t.href&&u.locations.progression===t.locations.progression).length>0?t:null}deleteBookmark(t){let n=this.store.get(yt.BOOKMARKS);if(n){let r=JSON.parse(n);r=r.filter(o=>o.id!==t.id),this.store.set(yt.BOOKMARKS,JSON.stringify(r))}return t}getBookmarks(t){let n=this.store.get(yt.BOOKMARKS);if(n){let r=JSON.parse(n);if(t){let o=r.filter(a=>a.href===t);return o=o.sort((a,l)=>{if(a.locations.progression&&l.locations.progression)return a.locations.progression-l.locations.progression}),o}return r=r.sort((o,a)=>{if(o.locations.progression&&a.locations.progression)return o.locations.progression-a.locations.progression}),r}return[]}initAnnotations(t){let n;typeof t=="string"?n=JSON.parse(t):n=t;let r=[];return n.forEach(o=>{let a=`${o.highlight.selectionInfo.rangeInfo.startContainerElementCssSelector}${o.highlight.selectionInfo.rangeInfo.startContainerChildTextNodeIndex}${o.highlight.selectionInfo.rangeInfo.startOffset}${o.highlight.selectionInfo.rangeInfo.endContainerElementCssSelector}${o.highlight.selectionInfo.rangeInfo.endContainerChildTextNodeIndex}${o.highlight.selectionInfo.rangeInfo.endOffset}`,l=Tr.hash(a);o.highlight.id="R2_HIGHLIGHT_"+l;let u;o.highlight.color?u=o.highlight.color:o.color&&(u=o.color),De.isHexColor(u)&&(u=De.hexToRgbString(u)),o.highlight.color=u,o.highlight.pointerInteraction=!0,o.highlight.selectionInfo.cleanText=o.highlight.selectionInfo.rawText.trim().replace(/\n/g," ").replace(/\s\s+/g," "),r.push(o)}),this.store.set(yt.ANNOTATIONS,JSON.stringify(r)),r}saveTemporarySelectionInfo(t){this.store.set(yt.SELECTIONINFO,JSON.stringify(t))}getTemporarySelectionInfo(t){let n=this.store.get(yt.SELECTIONINFO);if(n){let r=JSON.parse(n);return r.range=vd(t,r.rangeInfo),r}return[]}deleteTemporarySelectionInfo(){this.store.remove(yt.SELECTIONINFO)}saveAnnotation(t){let n=this.store.get(yt.ANNOTATIONS);if(n){let r=JSON.parse(n);r.push(t),this.store.set(yt.ANNOTATIONS,JSON.stringify(r))}else{let r=[];r.push(t),this.store.set(yt.ANNOTATIONS,JSON.stringify(r))}return t}deleteAnnotation(t){let n=this.store.get(yt.ANNOTATIONS);if(n){let r=JSON.parse(n);r=r.filter(o=>o.id!==t),this.store.set(yt.ANNOTATIONS,JSON.stringify(r))}return t}deleteSelectedAnnotation(t){let n=this.store.get(yt.ANNOTATIONS);if(n){let r=JSON.parse(n);r=r.filter(o=>o.highlight?.id!==t.highlight.id),this.store.set(yt.ANNOTATIONS,JSON.stringify(r))}return t}getAnnotations(){let t=this.store.get(yt.ANNOTATIONS);if(t){let n=JSON.parse(t);return n=n.sort((r,o)=>{if(r.locations.progression&&o.locations.progression)return r.locations.progression-o.locations.progression}),n}return[]}getAnnotationPosition(t,n){let r=this.store.get(yt.ANNOTATIONS);if(r){let a=JSON.parse(r).filter(l=>l.highlight?.id===t||l.id===t);if(a.length>0){let l=n.document.getElementById(`${a[0].highlight.id}`);if(l){let u=0;if(l.hasChildNodes)for(let d=0;d<l.childNodes.length;d++){let f=l.childNodes[d],g=parseInt(f.style.top.replace("px",""));(g<u||u===0)&&(u=g)}else u=parseInt(l.style.top.replace("px",""));return u}}}return null}getAnnotationElement(t,n){let r=this.store.get(yt.ANNOTATIONS);if(r){let a=JSON.parse(r).filter(l=>l.highlight?.id===t);if(a.length>0){let l=n.document.getElementById(`${a[0].highlight.id}`);if(l){let u=0;if(l.hasChildNodes)for(let d=0;d<l.childNodes.length;d++){let f=l.childNodes[d],g=parseInt(f.style.top.replace("px",""));if(g<u||u===0)return u=g,f}else u=parseInt(l.style.top.replace("px",""));return l}}}return null}getAnnotation(t){let n=this.store.get(yt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(a=>a.highlight?.id===t.id);if(o.length>0)return o[0]}return null}getAnnotationByID(t){let n=this.store.get(yt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(a=>a.highlight?.id===t);if(o.length>0)return o[0]}return null}},lo=yt;lo.LAST_READING_POSITION="last-reading-position",lo.BOOKMARKS="bookmarks",lo.ANNOTATIONS="annotations",lo.SELECTIONINFO="selectionInfo";C();C();var Wd=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 Wd}}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))}};C();var P3=Je(va()),I3=Je(Cn());var sl=class extends P3.Link{};sl=ac([(0,I3.JsonObject)()],sl);function al(i){let t,n,r,o;if(i instanceof Array)return i.map(function(a){return typeof a=="object"&&(a=al(a)),a});t={};for(n in i)i.hasOwnProperty(n)&&(r=(n.charAt(0).toLowerCase()+n.slice(1)||n).toString(),o=i[n],(o instanceof Array||o!==null&&o.constructor===Object)&&(o=al(o)),r==="href1"?t.href=o:r==="typeLink"?t.type=o:t[r]=o);return t}C();var L3=Je(Dt()),ig=class{constructor(t){this.LAYERSETTINGS="layerSetting";this.store=t,this.initialize()}static async create(t){let n=new this(t.store);return new Promise(r=>r(n))}async stop(){L3.default.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let t=new Si,n=await this.store.get(this.LAYERSETTINGS);if(n){let r=JSON.parse(n);t.properties=r}return t}async saveProperty(t){let n=await this.store.get(this.LAYERSETTINGS);if(n){let r=JSON.parse(n);r=r.filter(o=>o.name!==t.name),r.push(t),await this.store.set(this.LAYERSETTINGS,JSON.stringify(r))}else{let r=[];r.push(t),await this.store.set(this.LAYERSETTINGS,JSON.stringify(r))}return new Promise(r=>r(t))}async getProperty(t){let n=await this.store.get(this.LAYERSETTINGS);if(n){let r=JSON.parse(n);return r=r.filter(o=>o.name===t),r.length===0?null:r[0]}return null}};C();var ll=Je(Dt()),og=class{static async create(t){let n=new this(t.delegate,t.publication,t,t.headerMenu);return await n.start(),n}constructor(t,n,r,o){this.headerMenu=o,this.delegate=t,this.publication=n,this.properties=r}async stop(){ll.default.log("Page Break module stop")}async start(){this.delegate.pageBreakModule=this,this.headerMenu&&(this.goToPageView=de(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=de(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=de(this.headerMenu,"#goToPageNumberButton")),ne(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),ne(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 r=n[0];let o={progression:0};if(r.Href.indexOf("#")!==-1){let l=r.Href.slice(r.Href.indexOf("#")+1);l!==null&&(o={fragment:l})}let a={href:this.publication.getAbsoluteHref(r.Href),locations:o,type:r.TypeLink,title:r.Title};this.delegate.goTo(a)}}}async handleResize(){await this.delegate.highlighter?.destroyHighlights(qe.PageBreak),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{let t=this.delegate.iframes[0].contentDocument?.body,n=t?.querySelectorAll('[*|type="pagebreak"]');n?.length===0&&(n=t?.querySelectorAll("[epub\\:type='pagebreak']"));let r=this;function o(a){try{let l=r.delegate.iframes[0].contentDocument;return l?Rn(a,l,no):""}catch(l){return ll.default.log("uniqueCssSelector:"),ll.default.error(l),""}}if(n)for(let a=0;a<n.length;a++){let l=n[a];ll.default.log(l);let u=l.innerHTML,d=!1;l.innerHTML.length===0&&(u=l.getAttribute("title")??"",l.innerHTML=u,d=!0),l.innerHTML.length===0&&(u=(l.getAttribute("id")??"").replace(/[^0-9]/g,""),l.innerHTML=u,d=!0);let f=this.delegate.iframes[0].contentDocument;if(f){let g=this.delegate.highlighter?.dom(f.body).getWindow().document.createRange(),y=this.delegate.highlighter?.dom(f.body).getSelection();if(y.removeAllRanges(),g.selectNodeContents(l),y.addRange(g),!y.isCollapsed){let v=Ri(g,o);y.removeAllRanges(),v&&this.createPageBreakHighlight({rangeInfo:v,cleanText:"",rawText:""},u)}}d&&(l.innerHTML="")}},200)}createPageBreakHighlight(t,n){try{let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,a=Tr.hash(o),l="R2_PAGEBREAK_"+a;var r=!1;let u={color:"#000000",id:l,pointerInteraction:r,selectionInfo:t,marker:Le.Custom,icon:{id:"pageBreak",title:n,color:"#000000",position:"left"},type:qe.PageBreak};zt.push(u);let d=this.delegate.highlighter?.createHighlightDom(this.delegate.iframes[0].contentWindow,u);return u.position=parseInt((d?.hasChildNodes()?d.childNodes[0]:d).style.top.replace("px","")),u}catch(o){throw"Can't create highlight: "+o}}};C();var B3=Je(Xp());var k3=Je(Qi());var Ke=Je(Dt()),sg=class{constructor(t,n,r,o,a,l,u){this.voices=[];this.hasEventListener=!1;this.startX=0;this.startY=0;this.index=0;this.userScrolled=!1;this.scrollPartial=!1;this.speaking=!1;this.restartIndex=-1;this.ttsQueueIndex=-1;this.ttsQueue=void 0;this.ttsPlayQueueIndexDebounced=(0,k3.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=u,this.rights=r,this.highlighter=o,this.properties=a,this.api=l}initialize(t){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=t,this.clean=(0,B3.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),this.wrapper=dt(document,"#iframe-wrapper"),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,ne(document,"wheel",this.wheel.bind(this)),ne(this.body,"wheel",this.wheel.bind(this)),ne(document,"keydown",this.wheel.bind(this)),ne(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),ne(this.body,"mousedown",this.clickStart.bind(this)),ne(this.body,"mouseup",this.click.bind(this)))}clickStart(t){"clientX"in t&&(this.startX=t.clientX),"clientY"in t&&(this.startY=t.clientY)}click(t){let n=0,r=0;if("clientX"in t&&(n=t.clientX),"clientY"in t&&(r=t.clientY),window.speechSynthesis.speaking&&this.speaking&&n===this.startX&&r===this.startY){let o=this.delegate.iframes[0].contentDocument;if(o){let a=this.highlighter.dom(o.body).getSelection();if(a.isCollapsed){let g=this.delegate.iframes[0].contentDocument,y=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(g);a.addRange(y.range)}let l=a.getRangeAt(0),u=a.anchorNode;for(;l.toString().indexOf(" ")!==0;)try{l.setStart(u,l.startOffset-1)}catch(g){break}l.setStart(u,l.startOffset+1);do l.setEnd(u,u.length<l.endOffset?l.endOffset+1:u.length);while(l.toString().indexOf(" ")===-1&&l.toString().trim()!=="");let f=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(this.ttsQueue&&f){let g=this.findTtsQueueItemIndex(this.ttsQueue,a.anchorNode,a.anchorNode,a.anchorOffset,f);a.removeAllRanges(),g>=0&&(window.speechSynthesis.cancel(),this.restartIndex=g,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}}}}initVoices(t){function n(){return new Promise(function(o,a){let l=window.speechSynthesis,u;u=setInterval(()=>{l.getVoices().length!==0&&(o(l.getVoices()),clearInterval(u))},10)})}n().then(async o=>{if(Ke.default.log(o),this.voices=[],o.forEach(l=>{l.localService===!0&&this.voices.push(l)}),Ke.default.log(this.voices),t&&this.headerMenu){var a=de(this.headerMenu,"#preferred-languages");a&&this.voices.forEach(l=>{var u=document.createElement("option");u.value=l.name+":"+l.lang,u.innerHTML=l.name+" ("+l.lang+")",a.add(u)})}})}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(qe.ReadAloud),this._ttsQueueItemHighlightsWord=void 0)}async speak(t,n,r){this.api?.started&&this.api?.started(),this.delegate.emit("readaloud.started","started");let o=this;this.userScrolled=!1,this.cancel(!1);let a;if(n){let O=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body,_=this.delegate.iframes[0].contentDocument;if(_){let A=this.highlighter.dom(_.body).getSelection();if(A.isCollapsed){let T=o.delegate.iframes[0].contentDocument,M=o.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(T);A.addRange(M.range)}if(O){var l=this.generateTtsQueue(O);if(!l.length)return;var u=this.findTtsQueueItemIndex(l,A.anchorNode,A.anchorNode,A.anchorOffset,O),d=this.findTtsQueueItemIndex(l,A.focusNode,A.focusNode,A.focusOffset,O);let T=Vo(l,u),M=Vo(l,d);var f;if(T&&t&&t.cleanText){let j=Jo(T),P=t.rangeInfo.startOffset,q=t.cleanText;if(M&&u+1===d){let k=Jo(M);P=(j+" "+k).indexOf(t.cleanText),q=j.slice(P,j.length),f=t.cleanText.replace(q,"").trim()}else if(d>u){let k="";for(let B=u+1;B<d;B++){let N=Vo(l,B);if(N){let W=Jo(N);k+=W,f=t.cleanText.replace(W,"")}}if(M){let B=Jo(M);k+=" "+B}P=(j+" "+k).indexOf(t.cleanText),q=j.slice(P,j.length),f=f.replace(q,"").trim()}a=new SpeechSynthesisUtterance(q),Ke.default.log(t),Ke.default.log(q,t.range?.commonAncestorContainer.textContent),Ke.default.log(T),Ke.default.log(T.item.textNodes),Ke.default.log(P),Ke.default.log(T.item.combinedText);let U=T.item.textNodes.filter(k=>k===t.range?.commonAncestorContainer)[0];Ke.default.log(U),a.onboundary=k=>{this.updateTTSInfo(T,k.charIndex,k.charLength,P,a.text)}}}}}else a=new SpeechSynthesisUtterance(this.clean);a.rate=this.tts.rate,a.pitch=this.tts.pitch,a.volume=this.tts.volume,Ke.default.log("this.tts.voice.lang",this.tts.voice.lang);var g=!0;this.tts.voice&&this.tts.voice.lang&&(g=this.tts.voice.lang.indexOf("-")!==-1,g===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),g=!0)),Ke.default.log("initialVoiceHasHyphen",g),Ke.default.log("voices",this.voices);var y;g===!0?(y=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(E=>{var O=E.lang.replace("_","-");return O===this.tts.voice.lang&&E.name===this.tts.voice.name})[0]:void 0,y===void 0&&(y=this.tts.voice&&this.tts.voice.lang?this.voices.filter(E=>E.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(y=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(E=>E.lang===this.tts.voice.lang&&E.name===this.tts.voice.name)[0]:void 0,y===void 0&&(y=this.tts.voice&&this.tts.voice.lang?this.voices.filter(E=>E.lang===this.tts.voice.lang)[0]:void 0)),Ke.default.log("initialVoice",y);var v=o.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;Ke.default.log("publicationVoiceHasHyphen",v);var S;v===!0?S=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(E=>{var O=E.lang.replace("_","-");return O.startsWith(o.delegate.publication.Metadata.Language[0])||O.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:S=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(E=>E.lang.startsWith(o.delegate.publication.Metadata.Language[0])||E.lang.endsWith(o.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Ke.default.log("publicationVoice",S);var w=navigator.language.indexOf("-")!==-1;Ke.default.log("defaultVoiceHasHyphen",w);var b;w===!0?b=this.voices.filter(E=>{var O=E.lang.replace("_","-");return O===navigator.language&&E.localService===!0})[0]:b=this.voices.filter(E=>{var O=E.lang;return O===navigator.language&&E.localService===!0})[0],b===void 0&&(b=this.voices.filter(E=>{var O=E.lang;return O.includes(navigator.language)&&E.localService===!0})[0]),Ke.default.log("defaultVoice",b),y?(Ke.default.log("initialVoice"),a.voice=y):S?(Ke.default.log("publicationVoice"),a.voice=S):b&&(Ke.default.log("defaultVoice"),a.voice=b),a.voice!==void 0&&a.voice!==null&&(a.lang=a.voice.lang,Ke.default.log("utterance.voice.lang",a.voice.lang),Ke.default.log("utterance.lang",a.lang)),Ke.default.log("navigator.language",navigator.language),setTimeout(()=>{window.speechSynthesis.speak(a)},0),this.index=0;function m(){a.onend=function(){if(d>u)if(u=u+1,u!==d){let E=Vo(l,u);if(E){let O=Jo(E);a=new SpeechSynthesisUtterance(O),a.onboundary=_=>{o.updateTTSInfo(E,_.charIndex,_.charLength,0,a.text)},setTimeout(()=>{window.speechSynthesis.speak(a)},0),m()}}else{let E=Vo(l,u);E&&(a=new SpeechSynthesisUtterance(f),a.onboundary=O=>{o.updateTTSInfo(E,O.charIndex,O.charLength,0,a.text)},setTimeout(()=>{window.speechSynthesis.speak(a)},0),m()),u>d&&(Ke.default.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.delegate.emit("readaloud.finished","finished"))}else Ke.default.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.delegate.emit("readaloud.finished","finished")}}m(),r()}speakPlay(){this.scrollPartial=!0,this.cancel(!1),this.api?.started&&this.api?.started(),this.delegate.emit("readaloud.started","started");let t=this,r=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(r){let l=function(){let u=t.highlighter.visibleTextRects[0],d=t.delegate.iframes[0].contentDocument;if(d){let f=t.highlighter.dom(d.body).getWindow().document.createRange(),g=t.highlighter.dom(t.delegate.iframes[0].contentDocument?.body).getSelection();g.removeAllRanges(),f.selectNodeContents(u.node),g.addRange(f);let y=0,v=g.focusNode,S=g.focusOffset;g.collapse(g.anchorNode,g.anchorOffset);for(let w=0;w<y;w++)g.modify("move","forward","line");if(g.extend(v,S),g.collapse(g.anchorNode,g.anchorOffset),r){let w=t.findTtsQueueItemIndex(o,g.anchorNode,g.anchorNode,g.anchorOffset,r);w>=0&&(a=w)}g.removeAllRanges()}},o=this.generateTtsQueue(r);if(!o.length)return;let a=0;l(),a<0&&(a=0),setTimeout(()=>{this.startTTSSession(o,a)},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(qe.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=de(this.headerMenu,"#menu-button-tts");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties?.hideLayer?this.delegate.hideLayer("readaloud"):this.delegate.showLayer("readaloud")},10)}wheel(t){if(t instanceof KeyboardEvent)switch(t.key){case"ArrowUp":this.userScrolled=!0;break;case"ArrowDown":this.userScrolled=!0;break}else this.userScrolled=!0}stop(){Ke.default.log("TTS module stop"),Pe(document,"wheel",this.wheel.bind(this)),Pe(this.body,"wheel",this.wheel.bind(this)),Pe(document,"keydown",this.wheel.bind(this)),Pe(this.delegate.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),Pe(this.body,"click",this.click.bind(this))}generateTtsQueue(t){let n=[],r=[];function o(d){if(d.nodeType!==Node.TEXT_NODE||!d.nodeValue||!d.nodeValue.trim().length)return;let f=r[r.length-1];if(!f)return;let g=d.parentElement?N3(d.parentElement):void 0,y=d.parentElement?aN(d.parentElement):void 0,v=n[n.length-1];(!v||v.parentElement!==f||v.lang!==g||v.dir!==y)&&(v={combinedText:"",dir:y,lang:g,parentElement:f,textNodes:[]},n.push(v)),v.textNodes.push(d)}let a=!0;function l(d){if(d.nodeType!==Node.ELEMENT_NODE)return;let f=a||d.matches("h1, h2, h3, h4, h5, h6, p, th, td, caption, li, blockquote, q, dt, dd, figcaption, div, pre");a=!1,f&&r.push(d);for(let g of d.childNodes)switch(g.nodeType){case Node.ELEMENT_NODE:let y=g;if(!y.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))l(y);else if(y.tagName&&y.tagName.toLowerCase()==="img"&&y.src){let S=y.getAttribute("alt");if(S){let w=S.trim();if(w){let b=N3(y),m=void 0;n.push({combinedText:w,dir:m,lang:b,parentElement:y,textNodes:[]})}}}break;case Node.TEXT_NODE:r.length!==0&&o(g);break;default:break}f&&r.pop()}l(t);function u(d){if(!d.textNodes||!d.textNodes.length){(!d.combinedText||!d.combinedText.length)&&(d.combinedText="");return}d.combinedText=lN(d.textNodes,!0).replace(/[\r\n]/g," ");let f=d.parentElement;for(;f;){if(f.tagName){let g=f.tagName.toLowerCase();if(g==="pre"||g==="code"||g==="video"||g==="audio")break}f=f.parentElement}}for(let d of n)u(d);return n}findTtsQueueItemIndex(t,n,r,o,a){let l=0;for(let u of t){if(r&&u.textNodes){if(u.textNodes.includes(r))return l}else if(n===u.parentElement||u.parentElement!==n.ownerDocument.body&&u.parentElement!==a&&u.parentElement.contains(n)||n.contains(u.parentElement))return l;l++}return-1}restart(){window.speechSynthesis.speaking&&(window.speechSynthesis.cancel(),this.restartIndex=this.ttsQueueIndex,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}startTTSSession(t,n){if(!Vo(t,n)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(n,t)}ttsPlayQueueIndex(t,n){if(t<0){this.cancel();return}let r=Vo(n,t);if(!r){this.cancel();return}let o=Jo(r);if(!o){this.cancel();return}let a=new SpeechSynthesisUtterance(o);a.rate=this.tts.rate,a.pitch=this.tts.pitch,a.volume=this.tts.volume,Ke.default.log("this.tts.voice.lang",this.tts.voice.lang);var l=!0;this.tts.voice&&this.tts.voice.lang&&(l=this.tts.voice.lang.indexOf("-")!==-1,l===!1&&(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),l=!0)),Ke.default.log("initialVoiceHasHyphen",l),Ke.default.log("voices",this.voices);var u;l===!0?(u=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(S=>{var w=S.lang.replace("_","-");return w===this.tts.voice.lang&&S.name===this.tts.voice.name})[0]:void 0,u===void 0&&(u=this.tts.voice&&this.tts.voice.lang?this.voices.filter(S=>S.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(u=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(S=>S.lang===this.tts.voice.lang&&S.name===this.tts.voice.name)[0]:void 0,u===void 0&&(u=this.tts.voice&&this.tts.voice.lang?this.voices.filter(S=>S.lang===this.tts.voice.lang)[0]:void 0)),Ke.default.log("initialVoice",u);var d=this,f=d.delegate.publication.Metadata.Language[0].indexOf("-")!==-1;Ke.default.log("publicationVoiceHasHyphen",f);var g;f===!0?g=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(S=>{var w=S.lang.replace("_","-");return w.startsWith(d.delegate.publication.Metadata.Language[0])||w.endsWith(d.delegate.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:g=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(S=>S.lang.startsWith(d.delegate.publication.Metadata.Language[0])||S.lang.endsWith(d.delegate.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Ke.default.log("publicationVoice",g);var y=navigator.language.indexOf("-")!==-1;Ke.default.log("defaultVoiceHasHyphen",y);var v;y===!0?v=this.voices.filter(S=>{var w=S.lang.replace("_","-");return w===navigator.language&&S.localService===!0})[0]:v=this.voices.filter(S=>{var w=S.lang;return w===navigator.language&&S.localService===!0})[0],v===void 0&&(v=this.voices.filter(S=>{var w=S.lang;return w.includes(navigator.language)&&S.localService===!0})[0]),Ke.default.log("defaultVoice",v),u?(Ke.default.log("initialVoice"),a.voice=u):g?(Ke.default.log("publicationVoice"),a.voice=g):v&&(Ke.default.log("defaultVoice"),a.voice=v),a.voice!==void 0&&a.voice!==null&&(a.lang=a.voice.lang,Ke.default.log("utterance.voice.lang",a.voice.lang),Ke.default.log("utterance.lang",a.lang)),Ke.default.log("navigator.language",navigator.language),a.onboundary=S=>{Ke.default.log(S.name),this.updateTTSInfo(r,S.charIndex,S.charLength,0,a.text)},setTimeout(()=>{window.speechSynthesis.speak(a),d.speaking||window.speechSynthesis.pause()},0),a.onend=function(){d.speaking&&d.ttsPlayQueueIndexDebounced(t+1,n)}}updateTTSInfo(t,n,r,o,a){if(!t)return;Ke.default.log(t,n,r,a);let l=a||Jo(t);if(n>=0&&a){let u=a.slice(0,n+1).search(/\S+$/),d=a.slice(n).search(/\s/),f=d<0?a.slice(u):a.slice(u,d+n),g=u+f.length;if(r===void 0){let y=a.substring(n).match(/^[a-z\d']*/i);y&&(r=y[0].length)}r===void 0&&(r=f.length),this.wrapHighlightWord(t,a,n+o,r,f,u,g)}return l}wrapHighlightWord(t,n,r,o,a,l,u){Ke.default.log(t),Ke.default.log(n),Ke.default.log(r,o,a,l,u),this._ttsQueueItemHighlightsWord&&(this.delegate.highlighter?.destroyHighlights(qe.ReadAloud),this._ttsQueueItemHighlightsWord=void 0);let d=t.item,f=r,g=0,y,v=-1,S,w=-1,b=f+o;for(let E of d.textNodes){if(!E.nodeValue&&E.nodeValue!=="")continue;let O=E.nodeValue.length;if(g+=O,y||f<g&&(y=E,v=O-(g-f)),y&&b<=g&&(S=E,w=O-(g-b)),S)break}if(y&&S){let O=function(T){try{let M=m.delegate.iframes[0].contentDocument;return M?Rn(T,M,no):""}catch(M){return Ke.default.log("uniqueCssSelector:"),Ke.default.error(M),""}},E=new Range;E.setStart(y,v),E.setEnd(S,w);var m=this;let _=Ri(E,O);if(!_)return;let A=this.delegate.highlighter?.createHighlight(this.delegate.iframes[0].contentWindow,{rangeInfo:_,cleanText:"",rawText:"",range:void 0},this.tts.color,!1,Le.Custom,{id:"tts",title:"",position:"right"},void 0,{defaultClass:this.tts.color},qe.ReadAloud,"R2_READALOUD_");if(A){this._ttsQueueItemHighlightsWord=A[0];let j=(A[1]?.firstChild?.getBoundingClientRect()).top-this.wrapper.scrollTop>window.innerHeight/2-65;this.delegate.view?.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&this.scrollPartial&&j?A[1]?.firstChild?.scrollIntoView({block:"center",behavior:"smooth"}):this.delegate.view?.isPaginated()&&m.delegate.view?.snap(A[1]?.firstChild)}}}};function N3(i){let t=i;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 aN(i){let t=i;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let n=t.getAttribute("dir");if(n)return n;t=t.parentNode}}function lN(i,t){if(i&&i.length){let n="";for(let r of i)r.nodeValue&&(n+=t?r.nodeValue:uN(r.nodeValue));return n}return""}function cN(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function uN(i){return cN(i).replace(/\n/g," ").replace(/\s\s+/g," ")}function Vo(i,t){let n=-1,r=-1;for(let o of i)if(r++,n++,t===n)return{item:o,iArray:r,iGlobal:n,iSentence:-1}}function Jo(i){return i.item.combinedText}C();var cl=Je(Ed());var H3=Je(Qi());var j3=Je(Dt()),ag=class{constructor(t,n,r,o,a){this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,H3.debounce)(async()=>{if(await this.highlighter.destroyHighlights(qe.Definition),this.properties.definitions)for(let t of this.properties.definitions)await this.define(t)},200);this.delegate=t,this.publication=n,this.properties=r,this.api=a,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(){j3.default.log("Definitions module stop")}async start(){this.delegate.definitionsModule=this,setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("definitions"):this.delegate.showLayer("definitions")},10)}async searchAndPaint(t,n){let r=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[this.delegate.currentResource()??0].Href:""),o=this.publication.getTOCItem(r);o===void 0&&this.publication.readingOrder&&(o=this.publication.readingOrder[this.delegate.currentResource()??0]);let a=[];if(o)for(let l of t.terms){let u=t.terms.indexOf(l);o&&await Js(l,this.delegate.iframes[0].contentDocument,o.Href,o.Title,this.delegate.definitionsModule?.properties.fullWordSearch).then(d=>{let f;t.result===1?f=0:t.result===2&&(f=Math.floor(Math.random()*d.length-1)+1),d.forEach((g,y)=>{if(f===void 0||f===y){let v={rangeInfo:g.rangeInfo},S=this.createDefinitionHighlight(v,t);g.highlight=S,a.push(cl.omit(S,"definition")),this.currentChapterPopupResult.push(g),this.currentPopupHighlights.push(S)}}),u===t.terms.length-1&&n(a)})}}async define(t){await this.searchAndPaint(t,async n=>{this.api?.success&&(this.api?.success(cl.omit(t,"callbacks"),n),this.delegate.emit("definition.success",n),this.api?.visible&&n.forEach(r=>{let a=this.delegate.iframes[0].contentDocument?.querySelector(`#${r.id}`)?.querySelectorAll(`.${hn}`),l=new IntersectionObserver((u,d)=>{u.forEach(f=>{f.intersectionRatio===1&&(this.api?.visible(cl.omit(t,"callbacks"),cl.omit(r,"definition")),this.delegate.emit("definition.visible",t,r))})},{threshold:1});a&&a.length>0&&l.observe(a[0])}))})}async drawDefinitions(){setTimeout(async()=>{await this.definitions()},100)}async handleResize(){await this.drawDefinitions()}createDefinitionHighlight(t,n){try{let r=this.delegate.definitionsModule?.properties.color;De.isHexColor(r)&&(r=De.hexToRgbChannels(r));let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,a=Tr.hash(o),l="R2_DEFINITION_"+a;this.highlighter.destroyHighlight(this.delegate.iframes[0].contentDocument,l);let u={color:r||Fo,id:l,pointerInteraction:!0,selectionInfo:t,marker:Le.Underline,type:qe.Definition};zt.push(u);let d=this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,u);return d&&(n.definition&&(d.dataset.definition=n.definition),d.dataset.order=String(n.order),u.definition=n,u.position=parseInt((d?.hasChildNodes()?d.childNodes[0]:d).style.top.replace("px",""))),u}catch(r){throw"Can't create definitions highlight: "+r}}async addDefinition(t){await this.define(t)}async clearDefinitions(){await this.highlighter.destroyHighlights(qe.Definition)}};C();var co=Je(Dt()),D3=.5,Gd=class{constructor(t,n,r,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=r}static async create(t){let n=new this(t.delegate,t,t.highlighter,t.api);return await n.start(),n}async stop(){co.default.log("Definitions module stop"),this.hasEventListener=!1,Pe(document,"keydown",this.keydown.bind(this)),Pe(document,"keyup",this.keyup.bind(this)),Pe(this.delegate.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),Pe(this.delegate.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){this.delegate.lineFocusModule=this;let t=dt(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,ne(document,"keydown",this.keydown.bind(this)),ne(document,"keyup",this.keyup.bind(this)),ne(this.delegate.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),ne(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=dt(document,"#iframe-wrapper");this.wrapperHeight&&(n.style.height=this.wrapperHeight),t||(this.index=0);let r=this.delegate.iframes[0].contentDocument;Qt(r,"html").style.removeProperty("--USER__maxMediaHeight"),this.wrapperHeight=void 0,this.lineFocusContainer&&(this.lineFocusContainer.style.display="none");let a=document.getElementById("container-view-timeline");a&&a.style.removeProperty("display");let l=document.getElementById("divBefore");l&&l.remove();let u=document.getElementById("divAfter");u&&u.remove(),this.highlighter.destroyHighlights(qe.LineFocus)}lineFocus(){let t=dt(document,"#iframe-wrapper"),n=this.delegate.iframes[0].contentDocument,r=Qt(n,"html"),o=this.properties.maxHeight?Fr()*this.properties.maxHeight/100:Fr()/2;r.style.setProperty("--USER__maxMediaHeight",o+"px");function a(g,y){g.parentNode.insertBefore(y,g.nextSibling)}function l(g,y){g.parentNode.insertBefore(y,g)}let u=document.getElementById("container-view-timeline");u&&(u.style.display="none"),this.lineFocusContainer&&this.lineFocusContainer.style.removeProperty("display");let d=document.getElementById("divBefore");if(d)d.style.height=t.clientHeight/2+"px";else{let g=document.createElement("div");g.style.height=t.clientHeight/2+"px",g.id="divBefore",l(t,g)}let f=document.getElementById("divAfter");if(f)f.style.height=t.clientHeight/2+"px";else{let g=document.createElement("div");g.style.height=t.clientHeight/2+"px",g.id="divAfter",a(t,g)}if(this.lines=[],n){let v=function(){let O=Math.round,_=Math.random,A=255;return{blue:O(_()*A),green:O(_()*A),red:O(_()*A)}},S=function(O,_){let A=[];for(let T=0,M=0;T<O.length;T++)T>=_&&T%_==0&&M++,A[M]=A[M]||[],A[M].push(O[T]);return A},w=function(O,_){let A=Math.min(O.left,_.left),T=Math.max(O.right,_.right),M=Math.min(O.top,_.top),j=Math.max(O.bottom,_.bottom);return{bottom:j,height:j-M,left:A,right:T,top:M,width:T-A}},b=function(O){if(O.length>1){let _=w(O[0],O[1]);if(O.length>2){let A=w(_,O[2]);if(O.length>3){let T=w(A,O[3]);return O.length>4?w(T,O[4]):T}return A}return _}return O[0]},g=this.findRects(n.body);g=i0(g,!0),g=g.sort(function(O,_){return O.top-_.top});let y=[];g=g.filter(function(O){let _=O.top;return y.indexOf(_)===-1&&y.indexOf(_+1)===-1&&y.indexOf(_+2)===-1&&y.indexOf(_+3)===-1&&y.indexOf(_+4)===-1&&y.indexOf(_-1)===-1&&y.indexOf(_-2)===-1&&y.indexOf(_-3)===-1&&y.indexOf(_-4)===-1?(y.push(_),!0):!1}),this.highlighter.destroyHighlights(qe.LineFocus);let m=[];this.properties.lines&&this.properties.lines>1?S(g,this.properties.lines).forEach(_=>{m.push(b(_))}):m=g;let E=de(n,"#"+Re.R2_ID_LINEFOCUS_CONTAINER);if(E)for(let O of m){let _=document.createElement("div");_.setAttribute("class",hn);let A=v();if(De.isHexColor(A)&&(A=De.hexToRgbChannels(A)),this.isDebug){let he=`border-bottom: 1px solid rgba(${A.red}, ${A.green}, ${A.blue}, ${D3}) !important`;_.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${A.red}, ${A.green}, ${A.blue}, ${D3}) !important; ${he}`)}_.style.outline="none",_.tabIndex=0;let T=this.delegate.iframes[0].contentWindow.document,M=this.delegate.view.isPaginated();M?T.body.style.position="revert":T.body.style.position="relative";let j=T.body.getBoundingClientRect(),P=this.highlighter.getScrollingElement(T),q=M?-P.scrollLeft:j.left,U=M?-P.scrollTop:j.top,k=1,B=24,N,W,ye=this.delegate.iframes[0].contentWindow?.innerWidth,be=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-count")),fe=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-width")),re=parseInt(getComputedStyle(n.body).getPropertyValue("padding-left"));if(ye){let he=ye/(be||1);he<fe&&(he=ye),M||(he=parseInt(getComputedStyle(n.body).width.replace("px","")));let Ae=this.delegate.settings.fontSize/100,ue=20*Ae;Ae<=1&&(ue=-60);let Oe=0;Ae<=1&&(Oe=-60),N=Math.floor(O.left/he)*he+he-(B<40?40:B)+Oe,W=Math.floor(O.left/he)*he+(B<40?40:B)-ue;let Ce=parseInt(n.documentElement.style.getPropertyValue("--USER__pageMargins"));Ce>=2&&(W=W+re/be,N=N-re/be),M||(N=parseInt(getComputedStyle(n.body).width.replace("px","")),W=parseInt(getComputedStyle(n.body).width.replace("px",""))-he,Ce>=2&&(W=W+re/2,N=N-re/2))}_.style.setProperty("pointer-events","none"),_.style.position="absolute",_.scale=k,_.rect={height:O.height,left:O.left-q,top:O.top-U,width:O.width},_.style.width=`${_.rect.width*k}px`,_.style.height=`${_.rect.height*k}px`,_.style.left=`${_.rect.left*k}px`,_.style.top=`${_.rect.top*k}px`,this.lines.push(_),E.append(_)}setTimeout(()=>{this.currentLine()},100)}}currentLine(){let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}lineDown(){if(this.index<this.lines.length-1){this.index+=1,this.index>this.lines.length-1&&(this.index=this.lines.length-1);let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}}lineUp(){if(this.index>0){this.index-=1,this.index<0&&(this.index=0);let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}}almostEqual(t,n,r){return Math.abs(t-n)<=r}findRects(t){let n=this.findTextNodes(t),r=Array.from(t.getElementsByTagName("img")),o=[];return n.forEach(a=>{o.push(...this.measureTextNodes(a))}),r.forEach(a=>{o.push(...this.measureImageNodes(a))}),o}findTextNodes(t,n=[]){let r=t.firstChild;for(;r;)r.nodeType===1&&this.findTextNodes(r,n),r.nodeType===3&&r.textContent?.trim()&&(r.textContent.trim().length>1||r.parentElement?.tagName.toLowerCase()==="h1"||r.parentElement?.tagName.toLowerCase()==="h2"||r.parentElement?.tagName.toLowerCase()==="h3"||r.parentElement?.tagName.toLowerCase()==="h4"||r.parentElement?.tagName.toLowerCase()==="h5"||r.parentElement?.tagName.toLowerCase()==="h6")&&r.parentElement&&getComputedStyle(r.parentElement).verticalAlign==="baseline"&&n.push(r),r=r.nextSibling;return n}measureTextNodes(t){try{let n=document.createRange();n.selectNodeContents(t);let r=Array.from(n.getClientRects());return n.detach(),r}catch(n){co.default.log("measureTextNode "+n),co.default.log("measureTextNode "+t),co.default.log(`${t.textContent}`)}}measureImageNodes(t){try{let n=document.createRange();n.selectNode(t);let r=Array.from(n.getClientRects());return n.detach(),r}catch(n){co.default.log("measureTextNode "+n),co.default.log("measureTextNode "+t),co.default.log(`${t.textContent}`)}}};C();var Vd=Je(Dt()),lg=class{constructor(t,n,r,o,a){this.history=[];this.headerMenu=a,this.delegate=n,this.publication=r,this.properties=o,this.annotator=t}static async create(t){let n=new this(t.annotator,t.delegate,t.publication,t,t.headerMenu);return await n.start(),n}async stop(){Vd.default.log("Page Break module stop"),Pe(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),Pe(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleResize(){await this.setup()}setup(){this.history.length>0&&(this.historyForwardAnchorElement&&this.historyCurrentIndex+1<this.history.length?this.historyForwardAnchorElement.className=this.historyForwardAnchorElement.className.replace(" disabled",""):this.historyForwardAnchorElement&&(this.historyForwardAnchorElement.removeAttribute("href"),this.historyForwardAnchorElement.className+=" disabled"),this.historyBackAnchorElement&&this.historyCurrentIndex>0?this.historyBackAnchorElement.className=this.historyBackAnchorElement.className.replace(" disabled",""):this.historyBackAnchorElement&&(this.historyBackAnchorElement.removeAttribute("href"),this.historyBackAnchorElement.className+=" disabled"))}async push(t,n){let r;if(n&&this.annotator){let o=await this.annotator.getLastReadingPosition();if(o&&o.locations.progression&&o.locations.progression>0&&(this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex)),r=this.history[this.history.length-1],r&&r.href!==o.href||r===void 0)){let a=this.publication.getAbsoluteHref(o.href);Vd.default.log(o.href),Vd.default.log(a),o.href=a,this.history.push(o),this.historyCurrentIndex=this.history.length-1}this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex)),r=this.history[this.history.length-1],(r&&r.href!==t.href||r===void 0)&&(this.history.push(t),this.historyCurrentIndex=this.history.length-1)}}async start(){this.delegate.historyModule=this,this.headerMenu&&(this.historyForwardAnchorElement=de(this.headerMenu,"#history-forward")),this.headerMenu&&(this.historyBackAnchorElement=de(this.headerMenu,"#history-back")),this.historyCurrentIndex=this.history.length-1,ne(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),ne(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleHistoryForwardClick(t){this.history.length>0&&this.historyCurrentIndex+1<this.history.length&&(this.historyCurrentIndex=this.historyCurrentIndex+1,await this.delegate.navigate(this.history[this.historyCurrentIndex],!1)),t.preventDefault(),t.stopPropagation()}async handleHistoryBackClick(t){this.history.length>0&&this.historyCurrentIndex>0&&(this.historyCurrentIndex=this.historyCurrentIndex-1,await this.delegate.navigate(this.history[this.historyCurrentIndex],!1)),t.preventDefault(),t.stopPropagation()}};C();var F3=Je(Dt()),it;(function(r){r[r.Chicago=0]="Chicago",r[r.MLA=1]="MLA",r[r.APA=2]="APA"})(it||(it={}));var $3;(function(o){o.Author="Author",o.Editor="Editor",o.Translator="Translator",o.Compiler="Compiler"})($3||($3={}));var Jd=class{constructor(t,n,r,o,a){this.highlighter=r,this.delegate=t,this.properties=o,this.publication=n,this.api=a}static async create(t){let n=new this(t.delegate,t.publication,t.highlighter,t,t.api);return await n.start(),n}async stop(){F3.default.log("Timeline module stop")}copyToClipboard(t){let n=!0;if(window.clipboardData)window.clipboardData.setData("text/plain",t);else{let r=this.createElementForExecCommand(t);this.selectContent(r);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),n=document.execCommand("copy",!1)}catch(o){n=!1}document.body.removeChild(r)}n?this.api?.citationCreated("The text was copied to the clipboard!"):this.api?.citationFailed("Your browser doesn't allow clipboard access!")}createElementForExecCommand(t){let n=document.createElement("div");return n.style.position="absolute",n.style.left="-10000px",n.style.top="-10000px",n.innerHTML=t,document.body.appendChild(n),n.contentEditable=!0,n}selectContent(t){let n=document.createRange();n.selectNodeContents(t);let r=window.getSelection();r?.removeAllRanges(),r?.addRange(n)}async start(){this.delegate.citationModule=this;let t=this,n={id:"citationIcon",callback:function(r){let o=function(){let P="",q="",U="";return t.publication.Metadata.Author?.length>0&&0===0&&t.publication.Metadata.Author[0].Name&&t.publication.Metadata.Author[0].Name.length>0&&(U=U+t.publication.Metadata.Author[0].Name,q=q+t.publication.Metadata.Author[0].Name,P=P+t.publication.Metadata.Author[0].Name),U.length>0&&q.length>0&&P.length>0?[P+". ",q+". ",U+". "]:["","",""]},a=function(){let P="",q="",U="";return t.publication.Metadata.Publisher&&t.publication.Metadata.Publisher[0].Name&&(q=q+t.publication.Metadata.Publisher[0].Name+", ",P=P+t.publication.Metadata.Publisher[0].Name+", "),t.publication.Metadata.PublicationDate&&t.publication.Metadata.PublicationDate.getFullYear()>0&&(U=U+"("+t.publication.Metadata.PublicationDate.getFullYear()+")",q=q+t.publication.Metadata.PublicationDate.getFullYear(),P=P+t.publication.Metadata.PublicationDate.getFullYear()),U.length>0&&q.length>0&&P.length>0?[P+". ",q+". ",U+". "]:["","",""]},l=function(){return t.publication.Metadata.Title?[t.publication.Metadata.Title+". ",t.publication.Metadata.Title+". ",t.publication.Metadata.Title+". "]:["","",""]},u=function(){return["","",""]},d=function(){let P="",q="",U="";return t.publication.Metadata.Publisher&&t.publication.Metadata.Publisher[0].Name&&(q=q+t.publication.Metadata.Publisher[0].Name+", ",P=P+t.publication.Metadata.Publisher[0].Name+", ",U=U+t.publication.Metadata.Publisher[0].Name+", "),U.length>0&&q.length>0&&P.length>0?[P+". ",q+". ",U+". "]:["","",""]},f=function(){return["","",""]},g=function(){return["","",""]},y=function(){return["","",""]},v=function(){return t.properties.library?["Retrieved from "+t.properties.library+". ","Retrieved from "+t.properties.library+". ","Retrieved from "+t.properties.library+". "]:["","",""]},S=function(){return t.properties.appName?[t.properties.appName+". ",t.properties.appName+". ",t.properties.appName+". "]:["","",""]},w=function(){return t.properties.appLink?[t.properties.appLink+". ",t.properties.appLink+". ",t.properties.appLink+". "]:["","",""]},b=function(){return["","",""]},m=function(P,q){return P.length>q?P.substring(0,q)+"...":P},E=o()[0]+l()[0]+f()[0]+u()[0]+y()[0]+a()[0]+g()[0]+v()[0]+S()[0]+w()[0],O=o()[2]+a()[2]+l()[2]+u()[2]+d()[2]+f()[2]+g()[2]+y()[2]+v()[2]+S()[2]+w()[2],_=o()[1]+l()[1]+f()[1]+u()[1]+y()[1]+a()[1]+b()[1]+v()[1]+S()[1]+w()[1],A="\u201C"+m(r,t.properties.characters)+"\u201C<br><br><em>"+E+"</em>",T="\u201C"+m(r,t.properties.characters)+"\u201C<br><br><em>"+O+"</em>",M="\u201C"+m(r,t.properties.characters)+"\u201C<br><br><em>"+_+"</em>",j="";t.properties.styles?.includes(it[0])&&(j=j+"Chicago: <br>"+A+"<br><br>"),t.properties.styles?.includes(it[2])&&(j=j+"APA: <br>"+T+"<br><br>"),t.properties.styles?.includes(it[1])&&(j=j+"MLA: <br>"+M+"<br><br>"),t.copyToClipboard(j)}};this.highlighter?.addSelectionMenuItem(n)}};var Ko=class{constructor(t,n,r,o,a,l,u,d,f,g,y,v,S,w,b,m,E){this.settings=t;this.navigator=n;this.highlighter=r;this.bookmarkModule=o;this.annotationModule=a;this.ttsSettings=l;this.ttsModule=u;this.searchModule=d;this.definitionsModule=f;this.contentProtectionModule=g;this.timelineModule=y;this.mediaOverlaySettings=v;this.mediaOverlayModule=S;this.pageBreakModule=w;this.lineFocusModule=b;this.historyModule=m;this.citationModule=E;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,r)=>{this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchIndex(t,n,r)};this.goToSearchID=async(t,n,r)=>{this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchID(t,n,r)};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.goToPage=async t=>{await this.navigator.goToPage(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.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,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};n.enableContentProtection&&t.protection&&await jd.setupPreloadProtection(t.protection);let r=dt(document,"#D2Reader-Container"),o=de(document,"#headerMenu"),a=de(document,"#footerMenu"),l=t.url,u;t.publication?(u=Ts(t.publication,Ji),u.manifestUrl=new URL(l)):u=await Ji.fromUrl(l,t.requestConfig);let d=new Ys({prefix:u.manifestUrl,useLocalStorage:t.useLocalStorage??!1}),f=new Ys({prefix:"r2d2bc-reader",useLocalStorage:t.useLocalStorage??!1}),g=new Ys({prefix:"r2d2bc-layers",useLocalStorage:t.useLocalStorage??!1}),y=new lo({store:d});u.sample=t.sample,n=dN(n,u),n.autoGeneratePositions?await u.autoGeneratePositions(t.requestConfig):(t.services?.positions&&await u.fetchPositionsFromService(t.services?.positions.href,t.requestConfig),t.services?.weight&&await u.fetchWeightsFromService(t.services?.weight.href,t.requestConfig));let v=await ig.create({store:g}),S=await No.create({store:f,initialUserSettings:t.userSettings,headerMenu:o,api:t.api,injectables:(u.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed:t.injectables,layout:(u.Metadata.Rendition?.Layout??"unknown")==="fixed"?"fixed":"reflowable"}),w=await Ln.create({mainElement:r,headerMenu:o,footerMenu:a,publication:u,settings:S,annotator:y,initialLastReadingPosition:t.lastReadingPosition,api:t.api,rights:n,tts:t.tts,sample:t.sample,requestConfig:t.requestConfig,injectables:(u.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed??[]:t.injectables,attributes:t.attributes,services:t.services}),b=await De.create(Fe({delegate:w,layerSettings:v},t.highlighter)),m=n.enableBookmarks?await el.create(Fe({annotator:y,headerMenu:o,rights:n,publication:u,delegate:w,initialAnnotations:t.initialAnnotations},t.bookmarks)):void 0,E=n.enableAnnotations?await Qa.create(Fe({annotator:y,rights:n,publication:u,delegate:w,initialAnnotations:t.initialAnnotations,highlighter:b,headerMenu:o},t.annotations)):void 0,O=n.enableTTS,_=O?await ng.create({store:f,initialTTSSettings:t.tts,headerMenu:o}):void 0,A;O&&_&&(A=await sg.create(Fe({delegate:w,tts:_,headerMenu:o,rights:n,highlighter:b},t.tts)));let T=n.enableSearch?await tg.create(Fe({headerMenu:o,delegate:w,publication:u,highlighter:b},t.search)):void 0,M=n.enableDefinitions?await ag.create(Fe({delegate:w,publication:u,highlighter:b},t.define)):void 0,j=n.enableTimeline?await L0.create({publication:u,delegate:w}):void 0,P=n.enableContentProtection?await jd.create(Fe({delegate:w},t.protection)):void 0,q=n.enableMediaOverlays,U=q?await M0.create(Fe({store:f,initialMediaOverlaySettings:t.mediaOverlays,headerMenu:o},t.mediaOverlays)):void 0,k=q?await P0.create(Fe({publication:u,delegate:w,settings:U},t.mediaOverlays)):void 0,N=n.enablePageBreaks&&u.isReflowable?await og.create(Fe({publication:u,headerMenu:o,delegate:w},t.pagebreak)):void 0,W=n.enableLineFocus?await Gd.create(Fe({publication:u,delegate:w,highlighter:b},t.lineFocus)):void 0,ye=n.enableHistory?await lg.create({annotator:y,publication:u,delegate:w,headerMenu:o}):void 0,be=n.enableCitations?await Jd.create(Fe({publication:u,delegate:w,highlighter:b},t.citations)):void 0;return new Ko(S,w,b,m,E,_,A,T,M,P,j,U,k,N,W,ye,be)}get hasMediaOverlays(){return this.navigator.hasMediaOverlays}get tableOfContents(){return al(this.navigator.tableOfContents())??[]}get readingOrder(){return al(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 dN(i,t){return t.isFixedLayout&&(i.enableAnnotations=!1,i.enableSearch=!1,i.enableTTS=!1,i.enableDefinitions=!1,i.enablePageBreaks=!1,i.enableLineFocus=!1),t.sample?.isSampleRead&&(i.enableAnnotations=!1,i.enableSearch=!1,i.enableTTS=!1,i.enableDefinitions=!1,i.enableTimeline=!1,i.enableMediaOverlays=!1,i.enablePageBreaks=!1,i.enableLineFocus=!1),i}var fN=Ko,hN=Ko.load;return pN;})();
83
83
  /*!
84
84
  * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
85
85
  *