@d-i-t-a/reader 2.3.6 → 2.3.8

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
@@ -76,7 +76,7 @@ function print() { __p += __j.call(arguments, '') }
76
76
  </svg>`,ua=(r,t,n,i="icon",o,a)=>`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" height="${o}" viewBox="${D_}" style="fill:${a}" preserveAspectRatio="xMidYMid meet" role="img" class="${i}" aria-labelledBy="${r}">
77
77
  <title id="${r}">${t}</title>
78
78
  ${n}
79
- </svg>`,nr={error:ti("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:ti("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:z5("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:ti("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:ti("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:ti("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:ti("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:ti("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:ti("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:ti("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:ti("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:ti("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:ti("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:ti("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:ti("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 N0=nt(Kd());var ni=nt(Jt()),qe;(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"})(qe||(qe={}));var j_="R2_CLASS_HIGHLIGHT_CONTAINER",Sl="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",Tn="R2_CLASS_HIGHLIGHT_AREA",Al="R2_CLASS_HIGHLIGHT_ICON",_r=.5,F_=.75,ls={blue:100,green:50,red:230},tn=[],V5="data-highlighted",J5="data-timestamp",ha={ELEMENT_NODE:1,TEXT_NODE:3},Ai=[qe.R2_ID_HIGHLIGHTS_CONTAINER,qe.R2_ID_PAGEBREAK_CONTAINER,qe.R2_ID_SEARCH_CONTAINER,qe.R2_ID_READALOUD_CONTAINER,qe.R2_ID_BOOKMAKRS_CONTAINER,qe.R2_ID_DEFINITIONS_CONTAINER,qe.R2_ID_LINEFOCUS_CONTAINER,qe.R2_ID_GUTTER_RIGHT_CONTAINER,j_,Tn,Sl],D0=-1,j0=-1,Qe=class{constructor(t,n,i,o,a){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.showTool=(0,_l.debounce)(t=>{this.isAndroid()||this.snapSelectionToWord(t),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,_l.debounce)(()=>{this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen(),this.navigator.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,_l.debounce)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.navigator.emit("toolbox.closed","closed"))},100);this.selection=(0,_l.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.layerSettings=t,this.properties=n,this.api=a,this.hasEventListener=i,this.options=this.defaults(o,{color:"#fce300",highlightedClass:"highlighted",contextClass:"highlighter-context",onBeforeHighlight:function(){return!0},onAfterHighlight:function(){}})}static async create(t){let n=new this(t.layerSettings,t,!1,{},t.api);return new Promise(i=>i(n))}async initialize(){let t=this.navigator.iframes[0].contentDocument;t&&this.dom(t.body).addClass(this.options.contextClass),this.bindEvents(this.navigator.iframes[0].contentDocument?.body,this,this.hasEventListener),this.initializeToolbox(),D0=-1,j0=-1;let n=this;async function i(){n.lastSelectedHighlight===void 0||(n.lastSelectedHighlight=void 0)}setTimeout(async()=>{let o=this.navigator.iframes[0].contentDocument;o&&await o.body?.addEventListener("click",i)},100)}haveSameColor(t,n){return this.dom(t).color()===this.dom(n).color()}defaults(t,n){t=t||{};for(let i in n)n.hasOwnProperty(i)&&t[i]===void 0&&(t[i]=n[i]);return t}unique(t){return t.filter(function(n,i,o){return o.indexOf(n)===i})}refineRangeBoundaries(t){let n=t.startContainer,i=t.endContainer,o=t.commonAncestorContainer,a=!0;if(t.endOffset===0){for(;!i.previousSibling&&i.parentNode!==o;)i=i.parentNode;i=i.previousSibling}else i.nodeType===ha.TEXT_NODE?t.endOffset<i.nodeValue.length&&i.splitText(t.endOffset):t.endOffset>0&&(i=i.childNodes.item(t.endOffset-1));return n.nodeType===ha.TEXT_NODE?t.startOffset===n.nodeValue.length?a=!1:t.startOffset>0&&(n=n.splitText(t.startOffset),i===n.previousSibling&&(i=n)):t.startOffset<n.childNodes.length?n=n.childNodes.item(t.startOffset):n=n.nextSibling,{startContainer:n,endContainer:i,goDeeper:a}}sortByDepth(t,n){let i=this;t.sort(function(o,a){return i.dom(n?a:o).parents().length-i.dom(n?o:a).parents().length})}groupHighlights(t){let n=[],i={},o=[];return t.forEach(function(a){let l=a.getAttribute(J5);typeof i[l]=="undefined"&&(i[l]=[],n.push(l)),i[l].push(a)}),n.forEach(function(a){let l=i[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(i){t.classList?t.classList.add(i):t.className+=" "+i},removeClass:function(i){t.classList?t.classList.remove(i):t.className=t.className.replace(new RegExp("(^|\\b)"+i+"(\\b|$)","gi")," ")},prepend:function(i){let o=Array.prototype.slice.call(i),a=o.length;for(;a--;)t.insertBefore(o[a],t.firstChild)},append:function(i){let o=Array.prototype.slice.call(i);for(let a=0,l=o.length;a<l;++a)t.appendChild(o[a])},insertAfter:function(i){return i.parentNode?.insertBefore(t,i.nextSibling)},insertBefore:function(i){return i.parentNode?.insertBefore(t,i)},remove:function(){t.parentNode.removeChild(t),t=null},contains:function(i){return t!==i&&t.contains(i)},wrap:function(i){return t.parentNode&&t.parentNode.insertBefore(i,t),i.appendChild(t),i},unwrap:function(){let i=Array.prototype.slice.call(t.childNodes),o;return i.forEach(function(a){o=a.parentNode,n.dom(a).insertBefore(a.parentNode),n.dom(o).remove()}),i},parents:function(){let i,o=[];for(;i=t.parentNode;)o.push(i),t=i;return o},normalizeTextNodes:function(){if(!!t){if(t.nodeType===ha.TEXT_NODE)for(;t.nextSibling&&t.nextSibling.nodeType===ha.TEXT_NODE;)t.nodeValue+=t.nextSibling.nodeValue,t.parentNode.removeChild(t.nextSibling);else n.dom(t.firstChild).normalizeTextNodes();n.dom(t.nextSibling).normalizeTextNodes()}},color:function(){return t.style.backgroundColor},fromHTML:function(i){let o=document.createElement("div");return o.innerHTML=i,o.childNodes},getRange:function(){let i=n.dom(t)?.getSelection(),o;return i?.rangeCount>0&&(o=i?.getRangeAt(0)),o},removeAllRanges:function(){n.dom(t)?.getSelection()?.removeAllRanges(),n.toolboxHide()},getSelection:function(){return n.dom(t).getWindow()?.getSelection()},getWindow:function(){return n.dom(t).getDocument()?.defaultView},getDocument:function(){return t?.ownerDocument||t}}}disableContext(t){return t.preventDefault(),t.stopPropagation(),!1}bindEvents(t,n,i){let o=t.ownerDocument;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)),i||window.addEventListener("resize",this.toolboxPlacement.bind(this)),o.addEventListener("selectionchange",this.toolboxPlacement.bind(this)),t.addEventListener("mousedown",this.toolboxHide.bind(this)),t.addEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&t.addEventListener("contextmenu",this.disableContext),t.addEventListener("mousedown",this.mousedown.bind(this)),t.addEventListener("mouseup",this.mouseup.bind(this)),t.addEventListener("mousemove",this.mousemove.bind(this)),t.addEventListener("touchstart",this.mousedown.bind(this)),t.addEventListener("touchend",this.mouseup.bind(this)),t.addEventListener("touchmove",this.mousemove.bind(this)),this.hasEventListener=!0}async mousedown(t){D0=t.clientX,j0=t.clientY}async mouseup(t){Math.abs(D0-t.clientX)<3&&Math.abs(j0-t.clientY)<3&&await this.processMouseEvent(t)}async mousemove(t){await this.processMouseEvent(t)}unbindEvents(t,n){let i=t.ownerDocument;t.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),i.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),i.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),i.removeEventListener("selectionchange",this.toolboxPlacement.bind(this)),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.navigator.iframes[0].contentDocument;t&&(this.unbindEvents(t.body,this),this.dom(t.body).removeClass(this.options.contextClass))}initializeToolbox(){let t=document.getElementById("highlight-toolbox-mode-colors"),n=document.getElementById("highlight-toolbox-mode-add"),i=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],o=document.getElementById("colorIcon"),a=document.getElementById("actionIcon"),l=document.getElementById("dismissIcon"),u=document.getElementById("collapseIcon"),d=document.getElementById("highlightIcon"),h=this;if(l&&(l.innerHTML=nr.close,l.addEventListener("click",function(){h.toolboxMode("add")})),u&&(u.innerHTML=nr.close,u.addEventListener("click",function(){h.toolboxMode("add")})),o){o.style.position="relative",o.style.zIndex="20",i.forEach(w=>{let p=document.getElementById(w),m=document.getElementById(`c${w}`);p&&t?.contains(p)&&t.removeChild(p),n&&m&&n.contains(m)&&n.removeChild(m)});let y=[],b=[];if(o.addEventListener("click",function(){h.toolboxMode("colors")}),this.navigator.rights.enableAnnotations){let w=10;i.forEach(p=>{w--;let m=o?.cloneNode(!0),f=m.lastChild,g=Qe.hexToRgbChannels(p);f.style.backgroundColor="rgba("+[g.red,g.green,g.blue].join(",")+",.5)",m.id=`c${p}`,m.style.display="unset",m.style.position="relative",m.style.zIndex=`${w}`,m.style.marginLeft="-30px",b.push(m),n?.insertBefore(m,d)})}i.forEach(w=>{let p=o?.cloneNode(!0),m=p.lastChild;m.style.backgroundColor=w,p.id=w,p.style.position="relative",p.style.display="unset",y.push(p),o&&p.addEventListener("click",function(){h.setColor(w);let f=o?.lastChild;f&&(f.style.backgroundColor=w);let g=document.getElementById("highlightIcon"),v=document.getElementById("underlineIcon"),A=document.getElementById("noteIcon");(g?.getElementsByTagName?.("span").length??0)>0&&((g?.getElementsByTagName("span")[0]).style.background=h.getColor()),(v?.getElementsByTagName?.("span").length??0)>0&&((v?.getElementsByTagName("span")[0]).style.borderBottomColor=h.getColor()),(A?.getElementsByTagName?.("span").length??0)>0&&((A?.getElementsByTagName("span")[0]).style.borderBottomColor=h.getColor()),h.toolboxMode("add")}),t?.insertBefore(p,l)})}a&&a.addEventListener("click",function(){h.toolboxMode("action")}),h.toolboxMode("add")}toolboxMode(t){let n=document.getElementById("highlight-toolbox-mode-colors"),i=document.getElementById("highlight-toolbox-mode-add"),o=document.getElementById("highlight-toolbox-mode-edit"),a=document.getElementById("highlight-toolbox-mode-action");switch(t){case"colors":n&&(n.style.display="unset"),i&&(i.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="none");break;case"edit":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="unset"),a&&(a.style.display="none");break;case"action":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="unset");break;default:n&&(n.style.display="none"),i&&(i.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,i=this.navigator.iframes[0].contentDocument;if(i){let a=n.dom(i.body)?.getSelection();if(n.dom(i.body)&&a&&!a?.isCollapsed){let h=function(g){let v=g.match(new RegExp("[^a-zA-Z0-9]+$"));return!v||!v.index?g:g.slice(0,v.index)},l=a.toString(),u=l.length-l.trimStart().length,d=l.length-l.trimEnd().length,y=l.length;var o=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;l=l.replace(o,""),u=y-l.trimStart().length,l=h(l),d=y-l.trimEnd().length;let b=document.createRange();t?(b.setStart(a.anchorNode,a.anchorOffset+u),b.setEnd(a.focusNode,a.focusOffset-d)):(b.setStart(a.anchorNode,a.anchorOffset),b.setEnd(a.focusNode,a.focusOffset));let w=b.collapsed;b.detach();let p=a.focusNode,m;t?(m=a.focusOffset-d,a.collapse(a.anchorNode,a.anchorOffset+u)):(m=a.focusOffset,a.collapse(a.anchorNode,a.anchorOffset));let f=["forward","backward"];w&&(f=["backward","forward"]),t?(a.modify("move",f[0],"character"),a.modify("move",f[1],"word"),a.extend(p,m),a.modify("extend",f[1],"character"),a.modify("extend",f[0],"word")):a.extend(p,m),this.selection(a.toString(),a)}return a}}toolboxShow(){if(this.activeAnnotationMarkerId===void 0){let t=this,n=document.getElementById("highlight-toolbox-mode-add"),i=this.dom(this.navigator.iframes[0].contentDocument?.body).getRange();if((!i||i.collapsed)&&n){getComputedStyle(n).display!=="none"&&t.toolboxHide();return}this.isIOS()&&setTimeout(function(){let o=t.navigator.iframes[0].contentDocument;if(o){let a=t.dom(o.body).getSelection();a.removeAllRanges(),setTimeout(function(){a.addRange(i);function l(h){let y={className:w=>Ai.indexOf(w)<0,idName:w=>Ai.indexOf(w)<0},b=t.navigator.iframes[0].contentDocument;if(b)return wn(h,b,y)}let u=t.navigator.iframes[0].contentWindow,d=Er(u,l);t.navigator.annotationModule?.annotator?.saveTemporarySelectionInfo(d)},5)}},100),this.toolboxPlacement(),this.toolboxHandler()}}toolboxPlacement(){let t=this.dom(this.navigator.iframes[0].contentDocument?.body).getRange();if(!t||t.collapsed)return;let n=t.getBoundingClientRect(),i=document.getElementById("highlight-toolbox");i&&(this.navigator.view?.isPaginated()?i.style.top=n.top+(this.navigator.attributes?.navHeight??0)+"px":i.style.top=n.top+"px",i.style.left=(n.right-n.left)/2+n.left+"px")}toolboxHandler(){let t=document.getElementById("highlight-toolbox");if(t&&getComputedStyle(t).display==="none"){t.style.display="block",this.navigator.view?.isPaginated()?t.style.position="absolute":t.style.position="relative",this.selectionMenuOpened();let i=this;i.toolboxMode("add");let o=document.getElementById("highlightIcon"),a=document.getElementById("collapseIcon"),l=document.getElementById("underlineIcon"),u=document.getElementById("noteIcon"),d=document.getElementById("colorIcon"),h=document.getElementById("speakIcon");if(this.navigator.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 y=d.lastChild;y.style.backgroundColor=this.getColor()}if(o){let y=function(){i.doHighlight(!1,Ve.Highlight),i.toolboxHide(),o?.removeEventListener("click",y)},b=o.cloneNode(!0);o?.parentNode?.replaceChild(b,o),o=document.getElementById("highlightIcon"),o?.addEventListener("click",y)}if(l){let y=function(){i.doHighlight(!1,Ve.Underline),i.toolboxHide(),l?.removeEventListener("click",y)},b=l.cloneNode(!0);l?.parentNode?.replaceChild(b,l),l=document.getElementById("underlineIcon"),l?.addEventListener("click",y)}if(u){let y=function(){i.doHighlight(!1,Ve.Comment),i.toolboxHide(),u?.removeEventListener("click",y)},b=u.cloneNode(!0);u?.parentNode?.replaceChild(b,u),u=document.getElementById("noteIcon"),u?.addEventListener("click",y)}}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.navigator.rights.enableTTS){if(h){let y=function(){h?.removeEventListener("click",y),i.speak()},b=h.cloneNode(!0);h?.parentNode?.replaceChild(b,h),h=document.getElementById("speakIcon"),h?.addEventListener("click",y)}}else h&&h.style.setProperty("display","none");(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).forEach(y=>{y.icon&&(y.icon.id=y.id);let b=document.getElementById(y.id),w=this;function p(){b?.removeEventListener("click",p);function m(g){let v={className:C=>Ai.indexOf(C)<0,idName:C=>Ai.indexOf(C)<0},A=w.navigator.iframes[0].contentDocument;if(A)return wn(g,A,v)}let f=w.navigator.iframes[0].contentWindow;if(f){let g=Er(f,m);if(g===void 0){let v=w.navigator.iframes[0].contentDocument;g=w.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(v)}if(g!==void 0)if(y.callback)y.callback(g.cleanText,g.range?.startContainer.parentElement);else{let v=y.highlight?.style,A=y.marker?y.marker:Ve.Custom;if(A===Ve.Custom&&w.navigator.rights.enableAnnotations||A===Ve.Bookmark&&w.navigator.rights.enableBookmarks){let C=w.navigator.iframes[0].contentDocument;if(C){let O=w.createHighlight(w.dom(C.body).getWindow(),g,y.highlight?.color,!0,A,y.icon,y.popup,v);w.options.onAfterHighlight(O,A),w.navigator.rights.enableAnnotations?w.navigator.annotationModule?.saveAnnotation(O[0]).then(E=>{y?.note&&E.highlight&&w.navigator.annotationModule?.api?.addCommentToAnnotation(E).then(T=>{w.navigator.annotationModule?.updateAnnotation(T).then(async()=>{ni.default.log("update highlight "+T.id)})})}):w.navigator.rights.enableBookmarks&&w.navigator.bookmarkModule?.saveAnnotation(O[0])}}}}w.callbackComplete()}if(b){let m=b.cloneNode(!0);b?.parentNode?.replaceChild(m,b),b=document.getElementById(y.id),b?.addEventListener("click",p)}})}}doHighlight(t,n){let i=this;function o(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=i.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)}let a=i.navigator.iframes[0].contentWindow;if(a){let l=Er(a,o);if(l===void 0){let u=i.navigator.iframes[0].contentDocument;l=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(u)}if(l){if(this.options.onBeforeHighlight(l)===!0){let u;u=this.getColor(),Qe.isHexColor(u)&&(u=Qe.hexToRgbChannels(u));let d=i.navigator.iframes[0].contentDocument;if(d){let h=this.createHighlight(i.dom(d.body).getWindow(),l,u,!0,n??Ve.Highlight);this.options.onAfterHighlight(h,n),this.navigator.rights.enableAnnotations&&n!==Ve.Bookmark?this.navigator.annotationModule?.saveAnnotation(h[0]):this.navigator.rights.enableBookmarks&&n===Ve.Bookmark&&this.navigator.bookmarkModule?.saveAnnotation(h[0])}}t||this.dom(this.navigator.iframes[0].contentDocument?.body).removeAllRanges()}else t||this.dom(this.navigator.iframes[0].contentDocument?.body).removeAllRanges()}}speak(){if(this.navigator.rights.enableTTS){let n=function(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=t.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)},t=this,i=t.navigator.iframes[0].contentWindow;if(i){let l=Er(i,n);if(l===void 0){let u=t.navigator.iframes[0].contentDocument;l=t.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(u)}l!==void 0&&this.navigator.ttsModule.speak(l,!0,()=>{})}let o=t.navigator.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.navigator.rights.enableTTS&&this.doneSpeaking()}callbackComplete(){this.toolboxHide();let t=this.navigator.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges()}isOutsideViewport(t){let n=yt(document,"#iframe-wrapper"),i=n.scrollLeft,o=i+n.clientWidth,a=t.left+t.width,l=t.top+t.height,u=n.scrollTop,d=u+n.clientHeight,h=l<u,y=t.top>d,b=a<i,w=t.left>o;return h||y||b||w}isInsideViewport(t){let n=yt(document,"#iframe-wrapper"),i=n.scrollTop,o=i+n.clientHeight,a=t.top+20>=i,l=t.top<=o,u=n.scrollLeft,d=u+n.clientWidth,h=t.left+t.width,y=t.left>u,b=h<d;return a&&l&&y&&b}get visibleTextRects(){let t=this.navigator.iframes[0].contentDocument;if(t){let i=function(u,d=[]){let h=u.firstChild;for(;h;)h.nodeType===1&&i(h,d),h.nodeType===3&&h.textContent?.trim()&&d.push(h),h=h.nextSibling;return d},o=function(u){return i(u).map(h=>{let{top:y,height:b,left:w,width:p}=a(h);return{top:y,height:b,width:p,left:w,node:h,textContent:h.textContent??""}})},a=function(u){try{let d=document.createRange();d.selectNode(u);let h=d.getBoundingClientRect();return d.detach(),h}catch(d){ni.default.log("measureTextNode "+d),ni.default.log("measureTextNode "+u),ni.default.log(`${u.textContent}`)}},n=Gr(t,"body");return o(n).filter(u=>this.isInsideViewport(u))}return[]}doneSpeaking(t=!1){if(this.navigator.rights.enableTTS){this.toolboxHide();let n=this.navigator.iframes[0].contentDocument;n&&this.dom(n.body).removeAllRanges(),this.navigator.ttsModule.cancel(),t&&this.navigator.reload()}}normalizeHighlights(t){var n;return n=t.filter(function(i){return i.parentElement?i:null}),n=this.unique(n),n.sort(function(i,o){return i.offsetTop-o.offsetTop||i.offsetLeft-o.offsetLeft}),n}flattenNestedHighlights(t){let n,i=this;i.sortByDepth(t,!0);function o(){let a=!1;return t.forEach(function(l,u){let d=l.parentElement,h=d.previousSibling,y=d.nextSibling;i.isHighlight(d)&&(i.haveSameColor(d,l)?(d.replaceChild(l.firstChild,l),t[u]=d,a=!0):(l.nextSibling||(i.dom(l).insertBefore(y||d),a=!0),l.previousSibling||(i.dom(l).insertAfter(h||d),a=!0),d.hasChildNodes()||i.dom(d).remove()))}),a}do n=o();while(n)}mergeSiblingHighlights(t){let n=this;function i(o,a){return a&&a.nodeType===ha.ELEMENT_NODE&&n.haveSameColor(o,a)&&n.isHighlight(a)}t.forEach(function(o){let a=o.previousSibling,l=o.nextSibling;i(o,a)&&(n.dom(o).prepend(a.childNodes),n.dom(a).remove()),i(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===ha.ELEMENT_NODE&&t.hasAttribute(V5)}createWrapper(){let t=document.createElement("mark");return t.style.background="linear-gradient("+Qe.hexToRgbA(this.options.color)+", "+Qe.hexToRgbA(this.options.color)+")",t.className=this.options.highlightedClass,t}static isHexColor(t){return/^#([A-Fa-f0-9]{3}){1,2}$/.test(t)}static hexToRgbString(t){let n;return n=t.substring(1).split(""),n.length===3&&(n=[n[0],n[0],n[1],n[1],n[2],n[2]]),n="0x"+n.join(""),n}static hexToRgbChannels(t){let n;if(this.isHexColor(t))return n=this.hexToRgbString(t),{red:n>>16&255,green:n>>8&255,blue:n&255};throw new Error("Bad Hex")}static hexToRgbA(t){let n;if(this.isHexColor(t))return n=this.hexToRgbChannels(t),"rgba("+[n.red,n.green,n.blue].join(",")+",.5)";if(typeof t=="object"){let i=t;return"rgba("+[i.red,i.green,i.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(t,n){let i;if(this.isHexColor(t))return i=this.hexToRgbChannels(t),"rgba("+[i.red,i.green,i.blue].join(",")+","+n+")";if(typeof t=="object"){let o=t;return"rgba("+[o.red,o.green,o.blue].join(",")+","+n+")"}throw new Error("Bad Hex")}resetHighlightBoundingStyle(t){t.style.outline="none",t.style.setProperty("background-color","transparent","important")}resetHighlightAreaStyle(t,n){let i=this.navigator.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=tn.find(l=>l.id===o);if(a){if(a.marker===Ve.Custom||a.marker===Ve.Bookmark)if(a.style?.hover){if(a.style?.hover)for(let d=0;d<a.style?.hover?.length;d++){let h=a.style?.hover[d];t.style.removeProperty(h.property)}let u="";if(a.style?.default)for(let d=0;d<a.style?.default?.length;d++){let h=a.style?.default[d];t.style.removeProperty(h.property),u+=`${h.property}: ${h.value} !${h.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(Qe.isHexColor(a.color)){let u=Qe.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===Ve.Underline||a.marker===Ve.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(Qe.isHexColor(a.color)){let u=Qe.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}, ${_r})`,"important")}else if(Qe.isHexColor(a.color)){let u=Qe.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${_r})`,"important")}else t.classList.remove("hover");let l;if(i){let u=i.getElementById(n);u&&(l=u.querySelector(`#${a.id}`))}if(l){let u=l.getElementsByClassName(Al);if(u.length>0){let d=u.item(0).getElementsByClassName("icon-tooltip");d.length>0&&d.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(t,n,i){for(let o of n){if(i.marker===Ve.Custom||i.marker===Ve.Bookmark)if(i.style?.hover){if(i.style?.default)for(let l=0;l<i.style?.default?.length;l++){let u=i.style?.default[l];o.style.removeProperty(u.property)}let a="";for(let l=0;l<i.style?.hover?.length;l++){let u=i.style?.hover[l];o.style.removeProperty(u.property),a+=`${u.property}: ${u.value} !${u.priority};`}o.setAttribute("style",`${o.getAttribute("style")}; ${a}`)}else if(i.style?.hoverClass){i.style?.defaultClass&&o.classList.remove(i.style?.defaultClass);let a="";o.classList.add(i.style?.hoverClass),o.setAttribute("style",`${o.getAttribute("style")}; ${a}`)}else if(Qe.isHexColor(i.color)){let a=Qe.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important")}else o.classList.add("hover");else if(i.marker===Ve.Underline||i.marker===Ve.Comment)if(typeof i.color=="object"){let a=i.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(Qe.isHexColor(i.color)){let a=Qe.hexToRgbChannels(i.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 i.color=="object"){let a=i.color;o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${F_})`,"important")}else if(Qe.isHexColor(i.color)){let a=Qe.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${F_})`,"important")}else o.classList.add("hover");if(i.type!==it.Definition){let l=t.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER).querySelector(`#${i.id}`).getElementsByClassName(Al);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 i=this.navigator.iframes[0].contentWindow?.document,o=Array.from(i.getElementById(qe.R2_ID_SEARCH_CONTAINER).querySelectorAll(`.${Tn}`));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 b=d.color;l.style.setProperty("background-color",`rgba(${b.red}, ${b.green}, ${b.blue}, ${_r})`,"important")}else if(Qe.isHexColor(d.color)){let b=Qe.hexToRgbChannels(d.color);l.style.setProperty("background-color",`rgba(${b.red}, ${b.green}, ${b.blue}, ${_r})`,"important")}else l.classList.remove("hover");let y=i.getElementById(qe.R2_ID_SEARCH_CONTAINER).querySelector(`#${d.id}`).getElementsByClassName(Al);if(y.length>0){let b=y.item(0).getElementsByClassName("icon-tooltip");b.length>0&&b.item(0).style.removeProperty("display")}}}),u===t.id&&t){if(typeof t.color=="object"){let y=t.color;l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${_r})`,"important")}else if(Qe.isHexColor(t.color)){let y=Qe.hexToRgbChannels(t.color);l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${_r})`,"important")}else l.classList.remove("hover");let h=i.getElementById(qe.R2_ID_SEARCH_CONTAINER).querySelector(`#${t.id}`).getElementsByClassName(Al);if(h.length>0){let y=h.item(0).getElementsByClassName("icon-tooltip");y.length>0&&y.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.navigator.iframes[0].contentWindow?.document,i=t.clientX,o=t.clientY;if(!n||!n.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER)&&!n.getElementById(qe.R2_ID_SEARCH_CONTAINER)&&!n.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER)&&!n.getElementById(qe.R2_ID_READALOUD_CONTAINER)&&!n.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER))return;let a=this.navigator.view?.isPaginated(),l=n.body.getBoundingClientRect(),u=this.getScrollingElement(n),d=a?-u.scrollLeft:l.left,h=a?-u.scrollTop:l.top,y,b;for(let w=tn.length-1;w>=0;w--){let p=tn[w],m=n.getElementById(`${p.id}`);if(!m){let v=n.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER);v&&(m=v.querySelector(`#${p.id}`))}if(!m)continue;let f=!1,g=m.querySelectorAll(`.${Tn}`);for(let v of g){let A=v,C=A.rect.left+d,O=A.rect.top+h;if(i>=C&&i<C+A.rect.width&&o>=O&&o<O+A.rect.height){f=!0;break}}if(f){y=p,b=m;break}}if(!y||!b){for(let w in qe){let p=n.getElementById(w);if(p){let m=p.querySelectorAll(`.${Sl}`);for(let g of m)this.resetHighlightBoundingStyle(g);let f=Array.from(p.querySelectorAll(`.${Tn}`));for(let g of f)this.resetHighlightAreaStyle(g,w)}}return}if(b.getAttribute("data-click")){if((t.type==="mousemove"||t.type==="touchmove")&&b.parentElement?.style.display!=="none"){let w=Array.from(b.querySelectorAll(`.${Tn}`));for(let m in qe){let f=n.getElementById(m);if(f){let g=f.querySelectorAll(`.${Tn}`);for(let v of g)w.indexOf(v)<0&&this.resetHighlightAreaStyle(v,m)}}this.setHighlightAreaStyle(n,w,y);let p=b.querySelector(`.${Sl}`);for(let m in qe){let f=n.getElementById(m);if(f){let g=f.querySelectorAll(`.${Sl}`);for(let v of g)(!p||v!==p)&&this.resetHighlightBoundingStyle(v)}}}else if((t.type==="mouseup"||t.type==="click"||t.type==="touchup")&&b.parentElement?.style.display!=="none"){let w={highlight:y};ni.default.log(JSON.stringify(w));let p=this,m;if(p.navigator.rights.enableAnnotations?m=await this.navigator.annotationModule?.getAnnotation(w.highlight):p.navigator.rights.enableBookmarks&&(m=await this.navigator.bookmarkModule?.getAnnotation(w.highlight)),w.highlight.type===it.Annotation&&this.navigator.annotationModule?.api?.selectedAnnotation(m).then(async()=>{}),m?.id){ni.default.log("selected highlight "+m.id),p.lastSelectedHighlight=m.id;let f=document.getElementById("highlight-toolbox");if(f)if(f.style.top=t.clientY+(this.navigator.attributes?.navHeight??0)+"px",f.style.left=t.clientX+"px",getComputedStyle(f).display==="none"){let A=function(){p.navigator.annotationModule?.api?.addCommentToAnnotation(m).then(M=>{p.navigator.annotationModule?.updateAnnotation(M).then(async()=>{ni.default.log("update highlight "+M.id),f&&(f.style.display="none"),p.selectionMenuClosed()}),f&&(f.style.display="none"),p.selectionMenuClosed(),C?.removeEventListener("click",A,!1)})},E=function(){p.navigator.rights.enableAnnotations?p.navigator.annotationModule?.deleteSelectedHighlight(m).then(async()=>{ni.default.log("delete highlight "+m.id),f&&(f.style.display="none"),p.selectionMenuClosed()}):p.navigator.rights.enableBookmarks&&p.navigator.bookmarkModule?.deleteSelectedHighlight(m).then(async()=>{ni.default.log("delete highlight "+m.id),f&&(f.style.display="none"),p.selectionMenuClosed()})};f.style.display="block",this.toolboxMode("edit");let g=document.getElementById("colorIcon"),v=document.getElementById("highlightIcon");g&&(g.style.display="none"),v&&(v.style.display="none");let C=document.getElementById("commentIcon"),O=document.getElementById("cloneCommentIcon");if(O){let M=O.parentElement;M&&M.removeChild(O)}if(C){C.style.display="none";let M=C.cloneNode(!0),D=C.parentElement;M.style.display="unset",M.id="cloneCommentIcon",M.addEventListener("click",A,!1),D&&D.append(M)}let T=document.getElementById("deleteIcon"),B=document.getElementById("cloneDeleteIcon");if(B){let M=B.parentElement;M&&M.removeChild(B)}if(T){T.style.display="none";let M=T.cloneNode(!0),D=T.parentElement;M.style.display="unset",M.id="cloneDeleteIcon",M.addEventListener("click",E,!1),D&&D.append(M)}}else f.style.display="none",this.selectionMenuClosed(),f.offsetWidth,f.style.display="block"}else{b.dataset.definition&&new wl(this.navigator).showPopup(b.dataset.definition,t);let f=this.navigator.definitionsModule?.properties?.definitions?.filter(g=>g.order===Number(b?.dataset.order))[0];ni.default.log(f),this.navigator.definitionsModule?.api?.click&&(this.navigator.definitionsModule.api?.click(N0.omit(f,"callbacks"),N0.omit(y,"definition")),this.navigator.emit("definition.click",f,y))}}}}async prepareContainers(t){for(let n in qe)await this.ensureHighlightsContainer(t,n)}async ensureHighlightsContainer(t,n){let i=t.document;if(!i.getElementById(n)){let o=i.createElement("div");o.setAttribute("id",n),n!==qe.R2_ID_GUTTER_RIGHT_CONTAINER&&o.style.setProperty("pointer-events","none"),this.navigator.view?.layout==="fixed"&&(o.style.setProperty("position","absolute"),o.style.setProperty("top","0"),o.style.setProperty("left","0")),i.body&&i.body.append(o),(await this.layerSettings.getProperty(n))?.value===!1&&(o.style.display="none")}return i.getElementById(n)}hideAllhighlights(t){this.removeAllChildNodes(t.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_SEARCH_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_READALOUD_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER))}destroyAllhighlights(t){this.hideAllhighlights(t),tn.splice(0,tn.length)}removeAllChildNodes(t){for(;t.firstChild;)t.removeChild(t.firstChild)}destroyHighlights(t){let n=this.navigator.iframes[0].contentWindow?.document;if(n){let i;switch(t){case it.ReadAloud:i=n.getElementById(qe.R2_ID_READALOUD_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.Search:i=n.getElementById(qe.R2_ID_SEARCH_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.PageBreak:i=n.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.Definition:i=n.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.LineFocus:i=n.getElementById(qe.R2_ID_LINEFOCUS_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.Comment:i=n.getElementById(qe.R2_ID_GUTTER_RIGHT_CONTAINER),i&&this.removeAllChildNodes(i);break;default:i=n.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER),i&&this.removeAllChildNodes(i),tn.splice(0,tn.length);break}}}destroyHighlight(t,n){if(!t)return;let i=-1;tn.find((l,u)=>(i=u,l.id===n))&&i>=0&&i<tn.length&&tn.splice(i,1);let a=t.getElementById(n);a&&this.removeAllChildNodes(a)}createHighlight(t,n,i,o,a,l,u,d,h,y){try{let b=`${n.rangeInfo.startContainerElementCssSelector}${n.rangeInfo.startContainerChildTextNodeIndex}${n.rangeInfo.startOffset}${n.rangeInfo.endContainerElementCssSelector}${n.rangeInfo.endContainerChildTextNodeIndex}${n.rangeInfo.endOffset}`,w=Fi.hash(b),p=(y||"R2_HIGHLIGHT_")+w;this.destroyHighlight(t.document,p);let m=`rgb(${ls.red}, ${ls.green}, ${ls.blue})`,f={color:i||m,id:p,pointerInteraction:o,selectionInfo:n,marker:a,icon:l,popup:u,style:d,type:h||it.Annotation};(h===it.Annotation||h===it.Definition||h===void 0)&&tn.push(f);let g=this.createHighlightDom(t,f);return f.position=parseInt((g?.hasChildNodes()?g.childNodes[0]:g).style.top.replace("px","")),[f,g]}catch(b){throw"Can't create highlight: "+b}}createHighlightDom(t,n){let i=t.document,o=Vd(i,n.selectionInfo.rangeInfo);if(!o)return;for(let N in qe)this.ensureHighlightsContainer(t,N);let a=i.createElement("div");a.setAttribute("id",n.id),a.setAttribute("class",j_),a.style.setProperty("pointer-events","none"),n.pointerInteraction&&a.setAttribute("data-click","1");let l=this.navigator.view?.isPaginated();l?i.body.style.position="revert":i.body.style.position="relative";let u=i.body.getBoundingClientRect(),d=this.getScrollingElement(i),h=l?-d.scrollLeft:u.left,y=l?-d.scrollTop:u.top,b=1,w=!1,p=!1,g=Gd(o,w||p||!1),v=3,A=2,C=3,O=0,E=24,T,B;for(let N of g){let q=i.createElement("div");q.setAttribute("class",Tn),q.dataset.marker=""+n.marker;let z="";if(w&&n.marker!==Ve.Custom&&n.marker!==Ve.Bookmark&&n.marker!==Ve.Comment){let x=n.color;Qe.isHexColor(x)&&(x=Qe.hexToRgbChannels(x)),z+=`border-bottom: ${A*b}px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${_r}) !important`}if(n.marker===Ve.Custom||n.marker===Ve.Bookmark)if(n.style?.default){for(let x=0;x<n.style?.default?.length;x++){let R=n.style?.default[x];z+=`${R.property}: ${R.value} !${R.priority};`}q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; ${z}`)}else n.style?.defaultClass&&(q.classList.add(n.style?.defaultClass),q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; ${z}`));else if(n.marker===Ve.Underline||n.marker===Ve.Comment)if(typeof n.color=="object"){let x=n.color;q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${0}) !important; ${z}`),q.style.setProperty("border-bottom",`2px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${1})`,"important")}else if(Qe.isHexColor(n.color)){let x=Qe.hexToRgbChannels(n.color);q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${0}) !important; ${z}`),q.style.setProperty("border-bottom",`2px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${1})`,"important")}else q.setAttribute("style",`border-radius: ${v}px !important; ${z}`);else if(typeof n.color=="object"){let x=n.color;q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${_r}) !important; ${z}`)}else if(Qe.isHexColor(n.color)){let x=Qe.hexToRgbChannels(n.color);q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${_r}) !important; ${z}`)}else q.setAttribute("style",`border-radius: ${v}px !important; ${z}`);q.style.setProperty("pointer-events","none"),q.style.position="absolute",q.scale=b,q.rect={height:N.height,left:N.left-h,top:N.top-y,width:N.width},n.pointerInteraction&&(q.setAttribute("data-click","1"),q.tabIndex=0),q.style.width=`${q.rect.width*b}px`,q.style.height=`${q.rect.height*b}px`,q.style.left=`${q.rect.left*b}px`,q.style.top=`${q.rect.top*b}px`,a.append(q);let ne=parseInt(q.style.top.replace("px",""));if((ne<O||O===0)&&(O=ne),E=parseInt(q.style.height.replace("px","")),p){let x=i.createElement("div");x.setAttribute("class",Tn);let R=n.color;Qe.isHexColor(R)&&(R=Qe.hexToRgbChannels(R)),x.setAttribute("style",`background-color: rgba(${R.red}, ${R.green}, ${R.blue}, ${_r}) !important;`),x.style.setProperty("pointer-events","none"),x.style.position="absolute",x.scale=b,x.rect={height:N.height,left:N.left-h,top:N.top-y,width:N.width},x.style.width=`${x.rect.width*b}px`,x.style.height=`${C*b}px`,x.style.left=`${x.rect.left*b}px`,x.style.top=`${(x.rect.top+x.rect.height/2-C/2)*b}px`,a.append(x)}let oe=this.navigator.iframes[0].contentWindow?.innerWidth,ae=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-count")),te=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-width")),le=parseInt(getComputedStyle(i.body).getPropertyValue("padding-left")),xe=oe/(ae||1);xe<te&&(xe=oe),l||(xe=parseInt(getComputedStyle(i.body).width.replace("px","")));let fe=this.navigator.settings.fontSize/100,J=20*fe;fe<=1&&(J=-60);let j=0*fe;fe<=1&&(j=-60),T=Math.floor(N.left/xe)*xe+xe-(E<40?40:E)+j,B=Math.floor(N.left/xe)*xe+(E<40?40:E)-J;let k=parseInt(this.navigator.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));k>=2&&(B=B+le/ae,T=T-le/ae),l||(T=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px","")),B=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px",""))-xe,k>=2&&(B=B+le/2,T=T-le/2))}let M=o.getBoundingClientRect(),D=i.createElement("div");D.setAttribute("class",Sl),D.style.setProperty("pointer-events","none"),D.style.position="absolute",D.scale=b,D.rect={height:M.height,left:M.left-h,top:M.top-y,width:M.width},D.style.width=`${D.rect.width*b}px`,D.style.height=`${D.rect.height*b}px`,D.style.left=`${D.rect.left*b}px`,D.style.top=`${D.rect.top*b}px`,a.append(D);let U=i.createElement("div");if(U.setAttribute("class",Al),n.icon?.position==="left")U.setAttribute("style",`position: absolute;top:${O}px;left:${B+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`);else if(n.icon?.position==="inline")U.setAttribute("style",`position: absolute;top:${O-E/2}px;left:${parseInt(D.style.left.replace("px",""))+parseInt(D.style.width.replace("px",""))-E/2}px;height:${E}px; width:${E}px;`);else if(n.icon?.position==="center"){let q=E/3*2;U.setAttribute("style",`position: absolute;top:${O}px;left:${parseInt(D.style.left.replace("px",""))+parseInt(D.style.width.replace("px",""))-q}px;height:${E}px; width:${E}px;`)}else n.note&&n.marker!==Ve.Custom&&n.marker!==Ve.Bookmark&&n.marker!==Ve.Comment&&n.marker!==Ve.Highlight&&n.marker!==Ve.Underline?U.setAttribute("style",`position: absolute;top:${O-E/2}px;left:${parseInt(D.style.left.replace("px",""))+parseInt(D.style.width.replace("px",""))-E/2}px;height:${E}px; width:${E}px;`):n.note&&n.marker===Ve.Comment||n.marker===Ve.Highlight||n.marker===Ve.Underline?U.setAttribute("style",`position: absolute;top:${O}px;left:${T+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`):U.setAttribute("style",`position: absolute;top:${O}px;left:${T+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`);if(n.marker===Ve.Custom||n.marker===Ve.Bookmark)n.icon?.class?(U.classList.add(n.icon?.class),U.id=n.icon?.id):n.icon?.svgPath?U.innerHTML=ua(`${n.icon?.id}`,`${n.icon?.title}`,`${n.icon?.svgPath}`,"icon open",E,`${n.icon?.color} !important`):n.icon?.title&&(U.innerHTML=n.icon?.title);else if(n.note){let N=n.color;Qe.isHexColor(N)&&(N=Qe.hexToRgbChannels(N)),n.marker===Ve.Comment||n.marker===Ve.Highlight||n.marker===Ve.Underline?U.innerHTML=ua("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",E/2,`rgba(${N.red}, ${N.green}, ${N.blue}, 1) !important`):U.innerHTML=ua("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",E,`rgba(${N.red}, ${N.green}, ${N.blue}, 1) !important`)}U.style.setProperty("pointer-events","all");let I=this;if(n.type!==it.PageBreak&&n.type!==it.Definition&&U.addEventListener("click",async function(N){let q;I.navigator.rights.enableAnnotations?(q=await I.navigator.annotationModule?.getAnnotationByID(n.id),I.navigator.annotationModule?.api?.selectedAnnotation(q).then(async()=>{})):I.navigator.rights.enableBookmarks&&(q=await I.navigator.bookmarkModule?.getAnnotationByID(n.id)),ni.default.log("selected highlight "+q.id),I.lastSelectedHighlight=q.id;let z=document.getElementById("highlight-toolbox");if(z)if(z.style.top=N.clientY+(I.navigator.attributes?.navHeight??0)+"px",z.style.left=N.clientX+"px",getComputedStyle(z).display==="none"){let xe=function(){I.navigator.rights.enableAnnotations?I.navigator.annotationModule?.deleteSelectedHighlight(q).then(async()=>{ni.default.log("delete highlight "+q.id),z.style.display="none",I.selectionMenuClosed()}):I.navigator.rights.enableBookmarks&&I.navigator.bookmarkModule?.deleteSelectedHighlight(q).then(async()=>{ni.default.log("delete highlight "+q.id),z.style.display="none",I.selectionMenuClosed()})};z.style.display="block",I.toolboxMode("edit");let oe=document.getElementById("colorIcon"),ae=document.getElementById("highlightIcon");oe&&(oe.style.display="none"),ae&&(ae.style.display="none");let te=document.getElementById("commentIcon"),le=document.getElementById("cloneCommentIcon");if(le){let j=le.parentElement;j&&j.removeChild(le)}te&&(te.style.display="none");let fe=document.getElementById("deleteIcon"),J=document.getElementById("cloneDeleteIcon");if(J){let j=J.parentElement;j&&j.removeChild(J)}if(fe){fe.style.display="none";let j=fe.cloneNode(!0),k=fe.parentElement;j.style.display="unset",j.id="cloneDeleteIcon",j.addEventListener("click",xe,!1),k&&k.append(j)}}else z.style.display="none",I.selectionMenuClosed(),z.offsetWidth,z.style.display="block";let ne=Array.from(a.querySelectorAll(`.${Tn}`));I.setHighlightAreaStyle(i,ne,n)}),n.note){let N=document.createElement("span");N.innerHTML=n.note,N.className="icon-tooltip",n.marker===Ve.Custom||n.marker===Ve.Bookmark?(n.popup?.background&&N.style.setProperty("background",n.popup.background),n.popup?.textColor&&N.style.setProperty("color",n.popup.textColor),n.popup?.class&&N.classList.add(n.popup.class)):(N.style.setProperty("background","lightyellow"),N.style.setProperty("color","black"))}switch((n.note||n.marker===Ve.Custom||n.marker===Ve.Bookmark)&&a.append(U),n.type){case it.Search:i.getElementById(qe.R2_ID_SEARCH_CONTAINER).append(a);break;case it.ReadAloud:i.getElementById(qe.R2_ID_READALOUD_CONTAINER).append(a);break;case it.PageBreak:i.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER).append(a);break;case it.Definition:i.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER).append(a);break;default:i.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER).append(a);break}return a}addSelectionMenuItem(t){(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).push(t)}};var X_=nt(J0());H();var i8=nt(Jt());var Co={className:r=>!0,idName:r=>!0,tagName:r=>!0};var Z_=nt(Kd()),Ui=nt(Jt());H();var Y_=nt(Jt()),cs;(function(n){n.BookmarkCreated="BookmarkCreated",n.HighlightCreated="HighlightCreated"})(cs||(cs={}));var Cl=class{constructor(t,n,i){this.currSeconds=0;this.publication=t,this.properties=n,this.api=i}static async create(t){let n=new this(t.publication,t,t.api);return await n.start(),n}async start(){this.startResearchSession()}async stop(){Y_.default.log("Consumption module stop"),this.endResearchSession()}initialize(){let t=this.navigator.iframes[0].contentWindow;if(t){let n=this;t.onload=function(){n.resetTimer()},t.onmousemove=function(){n.resetTimer()},t.onmousedown=function(){n.resetTimer()},t.ontouchstart=function(){n.resetTimer()},t.onclick=function(){n.resetTimer()},t.onkeypress=function(){n.resetTimer()}}}trackAction(t,n){this.api?.actionTracked(t,n)}startReadingSession(t){if(this.firstReadingLocator&&this.lastReadingLocator){let n=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,i=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:i,progress:Math.round(n*100)})}this.firstReadingLocator=t,this.startReadingTimer=new Date}continueReadingSession(t){this.properties.enableTrackingSession&&(this.startResearchTimer===void 0&&this.startResearchSession(),(this.lastReadingLocator===void 0||this.lastReadingLocator.locations.totalProgression<t.locations.totalProgression)&&(this.lastReadingLocator=t),this.firstReadingLocator===void 0&&(this.firstReadingLocator=t),this.startReadingTimer===void 0&&(this.startReadingTimer=new Date))}startResearchSession(){if(this.properties.enableTrackingSession){this.startResearchTimer=new Date,this.readingSessions=[],clearInterval(this.readingSessionsInterval);let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.researchSessionId=this.api?.startResearchSession(this.readingSessions,Math.round(t));let n=this;this.readingSessionsInterval=setInterval(function(){n.updateResearchSession()},this.properties.updateSessionInterval*1e3)}}updateResearchSession(){if(this.properties.enableTrackingSession){let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.api?.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(t))}}endResearchSession(){if(this.properties.enableTrackingSession){if(this.firstReadingLocator&&this.lastReadingLocator){let n=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,i=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:i,progress:Math.round(n*100)})}let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.api?.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(t)),this.api?.endResearchSession(this.researchSessionId,this.readingSessions,Math.round(t)),this.researchSessionId=void 0,this.readingSessions=[],this.startResearchTimer=void 0,clearInterval(this.readingSessionsInterval),clearInterval(this.timer)}}startIdleTimer(){this.currSeconds++,this.currSeconds===this.properties.idleTimeout&&(this.api?.idleSince(this.currSeconds),this.startResearchTimer!==void 0?this.updateResearchSession():this.startResearchSession()),this.currSeconds===this.properties.idleTimeout+this.properties.responseTimeout&&this.endResearchSession()}resetTimer(){clearInterval(this.timer),this.currSeconds=0;let t=this;this.timer=setInterval(function(){t.startIdleTimer()},1e3)}};var us=class{constructor(t,n,i,o,a,l,u,d){this.hide=Ie(document,"#menu-button-hide");this.show=Ie(document,"#menu-button-show");this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=d,this.initialAnnotations=o,this.highlighter=l,this.properties=a,this.api=u}static async create(t){let n=new this(t.annotator,t.rights||{enableAnnotations:!1,enableTTS:!1},t.publication,t.initialAnnotations||null,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){Ui.default.log("Annotation module stop")}async start(){if(this.headerMenu&&(this.highlightsView=Ie(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var t=this.initialAnnotations.highlights||null;t&&this.annotator?.initAnnotations(t)}setTimeout(()=>{this.properties?.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)}hideAnnotationLayer(){let t=this.navigator.iframes[0].contentDocument;if(t){let n=Ie(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.navigator.iframes[0].contentDocument;if(t){let n=Ie(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(),Ee(this.navigator.iframes[0].contentDocument?.body,"click",this.click.bind(this))},300),t(null)})}click(t){if(this.activeAnnotationMarkerId){let n=this.highlighter?.properties?.selectionMenuItems?.filter(i=>i.id===this.activeAnnotationMarkerId);if(n&&n?.length>0){let i=Z_.cloneDeep(n[0]);i.marker=Ve.Custom,this.activeAnnotationMarkerPosition&&(i.icon.position=this.activeAnnotationMarkerPosition),i.highlight.style.default=null,i.highlight.style.hover=null;let o=this.navigator.iframes[0].contentDocument;if(o){let h=function(b){try{let w=d.navigator.iframes[0].contentDocument;return w?wn(b,w,Co):""}catch(w){return Ui.default.log("uniqueCssSelector:"),Ui.default.error(w),""}},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,y=Xr(l,h);if(a.removeAllRanges(),y){let b={rangeInfo:y},w=this.navigator.highlighter?.createHighlight(this.navigator.highlighter?.dom(o.body).getWindow(),b,i.highlight.color,!0,Ve.Bookmark,i.icon,i.popup,i.highlight.style);w&&this.saveAnnotation(w[0]).then(p=>{Ui.default.log("saved bookmark "+p.id)})}o.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(t){Ui.default.log("still need to scroll to "+t);var n=await this.annotator?.getAnnotationElement(t,this.navigator.iframes[0].contentWindow);n.scrollIntoView({block:"center",behavior:"smooth"})}async updateLocalHighlight(t){if(this.annotator){let n=await this.annotator.deleteAnnotation(t.id),i=await this.addAnnotation(t);return Ui.default.log("Highlight deleted "+JSON.stringify(n)),Ui.default.log("Highlight added "+JSON.stringify(i)),await this.showHighlights(),await this.drawHighlights(),i}else return new Promise(n=>n(null))}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return Ui.default.log("Highlight deleted "+JSON.stringify(n)),await this.showHighlights(),await this.drawHighlights(),n}else return new Promise(i=>i(null))}async deleteAnnotation(t){await this.deleteLocalHighlight(t.id)}async addAnnotation(t){await this.annotator?.saveAnnotation(t),await this.showHighlights(),await this.drawHighlights()}async deleteHighlight(t){this.api?.deleteAnnotation?this.api?.deleteAnnotation(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteSelectedHighlight(t){this.api?.deleteAnnotation?this.api.deleteAnnotation(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async updateAnnotation(t){this.api?.updateAnnotation?this.api.updateAnnotation(t).then(async()=>{this.updateLocalHighlight(t)}):this.updateLocalHighlight(t)}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(n=this.publication.getTOCItem(this.navigator.currentTocUrl)),n===void 0&&(n=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let i=this.navigator.view?.getCurrentPosition(),o=this.navigator.iframes[0].contentDocument;if(o){let a=Gr(o,"body"),l=t.position?t.position/a.scrollHeight:i,u=(0,X_.v4)(),d;if(n){let h=n.Href;if(h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let y=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),b=Math.ceil((l??0)*(y.length-1)),w=y[b];d=Yt(et({},w),{id:u,href:h,created:new Date,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else d={id:u,href:h,locations:{progression:l},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(d)if(this.navigator.consumptionModule?.trackAction(d,cs.HighlightCreated),this.api?.addAnnotation)try{let h=await this.api.addAnnotation(d),y=await this.annotator.saveAnnotation(h);return await this.showHighlights(),await this.drawHighlights(),new Promise(b=>b(y))}catch(h){await this.showHighlights(),await this.drawHighlights()}else{let h=await this.annotator.saveAnnotation(d);return await this.showHighlights(),await this.drawHighlights(),new Promise(y=>y(h))}}}return new Promise(i=>i(null))}getAnnotations(){let t=[];return this.annotator&&(t=this.annotator.getAnnotations()),t}showHighlights(){let t=[];this.annotator&&(t=this.annotator.getAnnotations(),t&&(t=t.filter(n=>n.highlight.marker!==Ve.Bookmark),t.forEach(n=>{tn.push(n.highlight)}))),this.highlightsView&&this.createTree(Si.Annotation,t,this.highlightsView)}async drawHighlights(){if(this.rights.enableAnnotations&&this.highlighter){if(this.api){let n=[];if(this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href;var t=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===Ve.Underline){let u=await this.annotator?.getAnnotationPosition(i.id,this.navigator.iframes[0].contentWindow),d='<div class="comment" style="top: '+u+'px;width:20px"></div>',h=document.createElement("div");h.innerHTML=d;let y=h.childNodes[0],b=document.createElement("i");b.innerHTML="sticky_note_2",b.className="material-icons",b.style.color=o.highlight.color,y.appendChild(b),Ee(h,"click",w=>{w.preventDefault(),w.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}else{let n=[];if(this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href,l=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl&&(l=this.publication.getTOCItem(this.navigator.currentTocUrl)),l===null&&(l=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),l){let u=l.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),o.href===u&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===Ve.Underline){let d=await this.annotator?.getAnnotationPosition(i.id,this.navigator.iframes[0].contentWindow),h='<div class="comment" style="top: '+d+"px;background: "+o.highlight?.color+';width:20px"></div>',y=document.createElement("div");y.innerHTML=h,y.childNodes[0].innerHTML=nr.note,Ee(y,"click",b=>{b.preventDefault(),b.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){let t=this.navigator.iframes[0].contentDocument;if(t&&(this.commentGutter=t.getElementById(qe.R2_ID_GUTTER_RIGHT_CONTAINER),this.navigator.view?.isScrollMode()&&this.properties?.enableComments?this.commentGutter?.style.removeProperty("display"):this.commentGutter?.style.setProperty("display","none"),this.commentGutter&&this.navigator.view?.isScrollMode()&&this.properties?.enableComments)){this.commentGutter.innerHTML="";let n=[];this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href),n&&(n=n.filter(i=>i.highlight?.note?.length>0),n=this.syncPosition(n),n=this.reposition(n),n.forEach(i=>{let o=document.createElement("i");o.innerHTML="sticky_note_2",o.className="material-icons",o.style.color=i.highlight.color;let a=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),l,u;a&&(l=a.querySelector(`#${i.highlight.id}`)),u=l.getElementsByClassName(Tn)[0];let h=parseInt(u.style.height.replace("px","")),y=i.highlight.position,b=t.createElement("div");b.setAttribute("style",`position: absolute;top:${y}px;display: flex;max-width: 250px !important;height:${h}px;width: 200px;align-items: center;`);let w=t.createElement("div");b.appendChild(w);let p=i.highlight.color;Qe.isHexColor(p)&&(p=Qe.hexToRgbChannels(p)),b.innerHTML=ua("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="8"/>',"icon open",10,`rgba(${p.red}, ${p.green}, ${p.blue}, 1) !important`);let m=t.createElement("div");m.innerHTML=i.highlight?.note,m.setAttribute("style",`height:${h}px;overflow: hidden;padding-left: 5px;`),b.appendChild(m),Ee(b,"click",f=>{f.preventDefault(),f.stopPropagation(),this.scrollToHighlight(i.highlight.id)}),this.commentGutter?.appendChild(b)})))}}createTree(t,n,i){if(n){let o=this,a=this.publication.readingOrder;if(a.length){let l=(u,d)=>{let h=document.createElement("ul");h.className="sidenav-annotations";for(let y of d){let b=document.createElement("li"),w=document.createElement("a"),p=document.createElement("span");if(w.tabIndex=-1,w.className="chapter-link",y.Href){let f=this.publication.getAbsoluteHref(y.Href),g=this.publication.getTOCItemAbsolute(f);w.href=f,w.innerHTML=g?.Title||"",b.appendChild(w)}else p.innerHTML=y.Title||"",p.className="chapter-title",b.appendChild(p);Ee(w,"click",f=>{f.preventDefault(),f.stopPropagation();let g={href:w.href,locations:{progression:0},type:y.TypeLink,title:w.title};this.navigator.stopReadAloud(),this.navigator.navigate(g)});let m=document.createElement("ol");n.forEach(function(f){let g=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&f.href.endsWith(g)){let v=document.createElement("li");v.className="annotation-item";let A=document.createElement("a");if(A.setAttribute("href",f.href),t===Si.Annotation){A.className="highlight-link";let O=document.createElement("span"),E=document.createElement("span");if(O.className="title",E.innerHTML=f.highlight.selectionInfo.cleanText,f.highlight?.marker===Ve.Underline)if(typeof f.highlight?.color=="object"){let M=f.highlight?.color;M&&E.style.setProperty("border-bottom",`2px solid ${Qe.hexToRgbA(M)}`,"important")}else E.style.setProperty("border-bottom",`2px solid ${f.highlight?.color}`,"important");else if(typeof f.highlight?.color=="object"){let M=f.highlight?.color;M&&(E.style.backgroundColor=Qe.hexToRgbA(M))}else{let M=f.highlight?.color;M&&(E.style.backgroundColor=M)}O.appendChild(E),A.appendChild(O);let T=document.createElement("span"),B=Math.round((f.locations.progression??0)*100)+"% through resource";T.className="subtitle",T.innerHTML=B,A.appendChild(T)}let C=document.createElement("span");if(C.className="timestamp",C.innerHTML=us.readableTimestamp(f.created),A.appendChild(C),Ee(A,"click",O=>{O.preventDefault(),O.stopPropagation(),o.handleAnnotationLinkClick(O,f)}),v.appendChild(A),o.navigator.sideNavExpanded){let O=document.createElement("button");O.className="delete",O.innerHTML=nr.delete,Ee(O,"click",E=>{E.preventDefault(),E.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,E,f)}),v.appendChild(O)}m.appendChild(v)}}),m.children.length>0&&(h.appendChild(b),h.appendChild(m)),h.children.length>0&&u.appendChild(h),y.Children&&y.Children.length>0&&l(u,y.Children)}};i.innerHTML="",l(i,a)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.navigator.stopReadAloud(),this.navigator.navigate(n)):Ui.default.log("annotation data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){Ui.default.log("annotation data locator: ",i),i?t===Si.Annotation&&this.deleteHighlight(i):Ui.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.navigator.iframes[0].contentDocument,i=(o,a)=>{let l=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),u,d;l&&(u=l.querySelector(`#${a.highlight.id}`)),d=u.getElementsByClassName(Tn)[0];let y=parseInt(d.style.top.replace("px","")),b=Yt(et({},a),{highlight:Yt(et({},a.highlight),{position:y})});return[...o,b]};return t.reduce(i,[])}reposition(t){let n=this.navigator.iframes[0].contentDocument,i=(o,a,l)=>{let u=t[0],d=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),h,y;d&&(h=d.querySelector(`#${u.highlight.id}`)),y=h.getElementsByClassName(Tn)[0];let w=parseInt(y.style.height.replace("px","")),p=a.highlight.position,m=o[l-1]&&o[l-1].highlight.position,g=l===0?0:m+w+0,v=g>p?g:p,A=Yt(et({},a),{highlight:Yt(et({},a.highlight),{position:v})});return[...o,A]};return t.sort(function(o,a){return o.highlight.position-a.highlight.position}).reduce(i,[])}};H();var K0=nt(J0());var $i=nt(Jt());var ds=class{static async create(t){let n=new this(t.annotator,t.rights||{enableBookmarks:!1},t.publication,t,t.initialAnnotations,t.api,t.headerMenu);return await n.start(),new Promise(i=>i(n))}constructor(t,n,i,o,a,l,u){this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=u,this.initialAnnotations=a,this.properties=o,this.api=l}stop(){$i.default.log("Bookmark module stop")}async start(){if(this.headerMenu&&(this.bookmarksView=Ie(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=Ie(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let t=Ie(this.headerMenu,"#menu-button-bookmark");t&&t.parentElement?.style.removeProperty("display"),t&&Ee(t,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let t=this.initialAnnotations.bookmarks||null;t&&this.annotator?.initBookmarks(t)}}async handleResize(){setTimeout(async()=>{await this.drawBookmarks(),await this.showBookmarks(),setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)},100)}initialize(){return new Promise(async 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 $i.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else{let n=await this.annotator.deleteBookmark(t);return $i.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.navigator.currentChapterLink.href);if(this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),t){let n=t.Href;n.indexOf("#")>0&&(n=n.slice(0,n.indexOf("#")));let i=this.navigator.view?.getCurrentPosition(),o=(0,K0.v4)(),a;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let l=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),u=Math.ceil((i??0)*(l.length-1)),d=l[u];a=Yt(et({},d),{id:o,href:n,created:new Date,title:this.navigator.currentChapterLink.title})}else a={id:o,href:n,locations:{progression:i},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title};if(!this.annotator.locatorExists(a,Si.Bookmark))if(this.navigator.consumptionModule?.trackAction(a,cs.BookmarkCreated),this.api?.addBookmark){let l=await this.api.addBookmark(a);l&&(a=l),$i.default.log(a);let u=this.annotator.saveBookmark(a);return $i.default.log("Bookmark added "+JSON.stringify(u)),this.showBookmarks(),await this.drawBookmarks(),u}else{let l=this.annotator.saveBookmark(a);return $i.default.log("Bookmark added "+JSON.stringify(l)),this.showBookmarks(),await this.drawBookmarks(),l}}}}async addBookmarkPlus(){let t=this,n=this.navigator.highlighter?.visibleTextRects[0],i=this.navigator.iframes[0].contentDocument;if(i){let u=this.navigator.highlighter?.dom(i.body).getWindow().document.createRange(),d=this.navigator.highlighter?.dom(this.navigator.iframes[0].contentDocument?.body).getSelection();d.removeAllRanges(),n&&u.selectNodeContents(n.node),d.addRange(u);let h=Gd(u,!1),y=0;for(let b of h){if(!this.navigator.highlighter?.isOutsideViewport(b)){let w=d.focusNode,p=d.focusOffset;d.collapse(d.anchorNode,d.anchorOffset);for(let v=0;v<y;v++)d.modify("move","forward","line");d.extend(w,p);let m=d.focusNode,f=d.focusNode.length;d.collapse(d.anchorNode,d.anchorOffset);let g=f;d.anchorOffset>f?g=f:g=d.anchorOffset+1,d.modify("move","forward","character"),d.modify("move","backward","word"),d.extend(m,g),d.modify("extend","backward","character"),d.modify("extend","forward","word");break}y++}}function o(u){let d={},h=t.navigator.iframes[0].contentDocument;if(h)return wn(u,t.navigator.highlighter?.dom(h.body).getDocument(),d)}let a=this.navigator.iframes[0].contentWindow,l={id:"bookmarkIcon",marker:Ve.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=Er(a,o);if(u===void 0){let h=t.navigator.iframes[0].contentDocument;u=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(h)}let d=t.navigator.iframes[0].contentDocument;if(u&&d){let h=this.navigator.highlighter?.createHighlight(this.navigator.highlighter?.dom(d.body).getWindow(),u,l.highlight?.color,!0,Ve.Bookmark,l.icon,l.popup,l.highlight?.style);if(this.navigator.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),h)return this.saveAnnotation(h[0]).then(y=>{$i.default.log("saved bookmark "+y?.id)})}}}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(n=this.publication.getTOCItem(this.navigator.currentTocUrl)),n===null&&(n=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let i=this.navigator.view?.getCurrentPosition(),o=this.navigator.iframes[0].contentDocument;if(o){let a=Gr(o,"body"),l=t.position?t.position/a.scrollHeight:i,u=(0,K0.v4)(),d;if(n){let h=n.Href;if(h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let y=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),b=Math.ceil((l??0)*(y.length-1)),w=y[b];d=Yt(et({},w),{id:u,href:h,created:new Date,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else d={id:u,href:h,locations:{progression:l},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(d)if(this.navigator.consumptionModule?.trackAction(d,cs.BookmarkCreated),this.api?.addBookmark){let h=await this.api.addBookmark(d),y=await this.annotator.saveAnnotation(h);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(b=>b(y))}else{let h=await this.annotator.saveAnnotation(d);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(y=>y(h))}}}return new Promise(i=>i(void 0))}getBookmarks(){let t=[];return this.annotator&&(t=this.annotator.getBookmarks()),t}showBookmarks(){let t=[];this.annotator&&(t=this.annotator.getBookmarks());let n=[];this.annotator&&(n=this.annotator.getAnnotations(),n&&(n=n.filter(i=>i.highlight.marker===Ve.Bookmark),t?t.push.apply(t,n):t=n)),this.bookmarksView&&this.createTree(Si.Bookmark,t,this.bookmarksView)}async drawBookmarks(){if(this.rights.enableBookmarks&&this.navigator.highlighter)if(this.api){let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.navigator.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.navigator.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href;var t=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight)}}}}else{let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.navigator.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.navigator.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href,l=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl&&(l=this.publication.getTOCItem(this.navigator.currentTocUrl)),l===void 0&&(l=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),l){let u=l.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),o.href===u&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight)}}}}}async deleteSelectedHighlight(t){this.api?.deleteBookmark?this.api.deleteBookmark(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return $i.default.log("Highlight deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else return new Promise(i=>i(null))}createTree(t,n,i){if(n){let o=this,a=this.publication.readingOrder;if(a.length){let l=(u,d)=>{let h=document.createElement("ul");h.className="sidenav-annotations";for(let y of d){let b=document.createElement("li"),w=document.createElement("a"),p=document.createElement("span");if(w.tabIndex=-1,w.className="chapter-link",y.Href){let f=this.publication.getAbsoluteHref(y.Href),g=this.publication.getTOCItemAbsolute(f);w.href=f,w.innerHTML=g?.Title||"",b.appendChild(w)}else p.innerHTML=y.Title||"",p.className="chapter-title",b.appendChild(p);Ee(w,"click",f=>{f.preventDefault(),f.stopPropagation();let g={href:w.href,locations:{progression:0},type:y.TypeLink,title:w.title};this.navigator.stopReadAloud(),this.navigator.navigate(g)});let m=document.createElement("ol");n.forEach(function(f){let g=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&f.href.endsWith(g)){let v=document.createElement("li");v.className="annotation-item";let A=document.createElement("a");if(A.setAttribute("href",f.href),t===Si.Bookmark){A.className="bookmark-link";let O=document.createElement("span"),E=Math.round((f.locations.progression??0)*100)+"% through resource";O.className="title",O.innerHTML=E,A.appendChild(O)}let C=document.createElement("span");if(C.className="timestamp",C.innerHTML=ds.readableTimestamp(f.created),A.appendChild(C),Ee(A,"click",O=>{O.preventDefault(),O.stopPropagation(),o.handleAnnotationLinkClick(O,f)}),v.appendChild(A),o.navigator.sideNavExpanded){let O=document.createElement("button");O.className="delete",O.innerHTML=nr.delete,Ee(O,"click",E=>{E.preventDefault(),E.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,E,f)}),v.appendChild(O)}m.appendChild(v)}}),m.children.length>0&&(h.appendChild(b),h.appendChild(m)),h.children.length>0&&u.appendChild(h),y.Children&&y.Children.length>0&&l(u,y.Children)}};i.innerHTML="",l(i,a)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.navigator.stopReadAloud(),this.navigator.navigate(n)):$i.default.log("bookmark data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){$i.default.log("bookmark data locator: ",i),i?t===Si.Bookmark&&this.deleteBookmark(i):$i.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)}};H();var eS=nt(Q_());H();var ii=nt(Jt()),X0="r2-mo-active",fs=class{},Xe=fs;Xe.COLOR_REF="color",Xe.AUTO_SCROLL_REF="autoscroll",Xe.AUTO_TURN_REF="autoturn",Xe.VOLUME_REF="volume",Xe.RATE_REF="rate",Xe.COLOR_KEY="mediaoverlay-"+fs.COLOR_REF,Xe.AUTO_SCROLL_KEY="mediaoverlay-"+fs.AUTO_SCROLL_REF,Xe.AUTO_TURN_KEY="mediaoverlay-"+fs.AUTO_TURN_REF,Xe.VOLUME_KEY="mediaoverlay-"+fs.VOLUME_REF,Xe.RATE_KEY="mediaoverlay-"+fs.RATE_REF;var Z0=class{constructor(t,n,i){this.MEDIAOVERLAYSETTINGS="mediaOverlaySetting";this.color="r2-mo-active";this.autoScroll=!0;this.autoTurn=!0;this.volume=1;this.rate=1;this.playing=!1;this.resourceReady=!1;this.wait=1;this.settingsChangeCallback=()=>{};this.store=t,this.api=n,this.headerMenu=i,this.initialise(),ii.default.log(this.api)}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialMediaOverlaySettings){let i=t.initialMediaOverlaySettings;i?.color&&(n.color=i.color,ii.default.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,ii.default.log(n.autoScroll)),i?.autoTurn&&(n.autoTurn=i.autoTurn,ii.default.log(n.autoScroll)),i?.volume&&(n.volume=i.volume,ii.default.log(n.volume)),i?.rate&&(n.rate=i.rate,ii.default.log(n.rate)),i?.wait&&(n.wait=i.wait,ii.default.log(n.wait))}return n.initializeSelections(),n}stop(){ii.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(Xe.AUTO_SCROLL_KEY)!=null?this.getProperty(Xe.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(Xe.AUTO_TURN_KEY)!=null?this.getProperty(Xe.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(Xe.COLOR_KEY)!=null?this.getProperty(Xe.COLOR_KEY).value:this.color,this.volume=this.getProperty(Xe.VOLUME_KEY)!=null?this.getProperty(Xe.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(Xe.RATE_KEY)!=null?this.getProperty(Xe.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=Ie(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechAutoTurn=Ie(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=Ie(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=Ie(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=Ie(this.headerMenu,"#mediaOverlayRate")),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),this.speechAutoTurn&&(this.speechAutoTurn.checked=this.autoTurn),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechRate&&(this.speechRate.value=this.volume.toString()),Ee(Ie(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(Xe.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Xe.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(Xe.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(Xe.VOLUME_REF)?.value,rate:this.userProperties.getByRef(Xe.RATE_REF)?.value};this.applyMediaOverlaySettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{ii.default.log("api updated sync settings",n)})}getMediaOverlaySettings(){let t=new Wr;return t.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,Xe.AUTO_SCROLL_REF,Xe.AUTO_SCROLL_KEY),t.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,Xe.AUTO_TURN_REF,Xe.AUTO_TURN_KEY),t.addStringable(this.color,Xe.COLOR_REF,Xe.COLOR_KEY),t.addIncremental(this.volume,.1,1,.1,"",Xe.VOLUME_REF,Xe.VOLUME_KEY),t.addIncremental(this.rate,.1,3,.1,"",Xe.RATE_REF,Xe.RATE_KEY),t}saveProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}return t}getProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}resetMediaOverlaySettings(){this.store.remove(this.MEDIAOVERLAYSETTINGS),this.reset(),this.settingsChangeCallback()}applyMediaOverlaySettings(t){if(t.color){this.color=t.color;let n=this.userProperties.getByRef(Xe.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){ii.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Xe.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoTurn!==void 0){ii.default.log("autoTurn "+this.autoTurn),this.autoTurn=t.autoTurn;let n=this.userProperties.getByRef(Xe.AUTO_TURN_REF);n&&(n.value=this.autoTurn,this.saveProperty(n)),this.settingsChangeCallback()}if(t.volume){ii.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Xe.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback()}if(t.rate){ii.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Xe.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback()}}applyMediaOverlaySetting(t,n){if(t===Xe.COLOR_REF){this.color=n;let i=this.userProperties.getByRef(Xe.COLOR_REF);i&&(i.value=this.color,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===Xe.AUTO_SCROLL_REF){this.autoScroll=n;let i=this.userProperties.getByRef(Xe.AUTO_SCROLL_REF);i&&(i.value=this.autoScroll,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===Xe.AUTO_TURN_REF){this.autoTurn=n;let i=this.userProperties.getByRef(Xe.AUTO_TURN_REF);i&&(i.value=this.autoTurn,this.saveProperty(i)),this.settingsChangeCallback()}}increase(t){if(t==="mo_volume"){this.userProperties.getByRef(Xe.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(Xe.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Xe.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Xe.RATE_REF).increment(),this.rate=this.userProperties.getByRef(Xe.RATE_REF)?.value;let n=this.userProperties.getByRef(Xe.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}decrease(t){if(t==="mo_volume"){this.userProperties.getByRef(Xe.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(Xe.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Xe.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Xe.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(Xe.RATE_REF)?.value;let n=this.userProperties.getByRef(Xe.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}};var Ze=nt(Jt()),Tl=class{constructor(t,n,i){this.play=Ie(document,"#menu-button-play");this.pause=Ie(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async t=>{Ze.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.publication=t,this.settings=n,this.properties=i}static create(t){let n=new this(t.publication,t.settings,t);return n.start(),n}stop(){Ze.default.log("MediaOverlay module stop")}start(){Ze.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.navigator.requestConfig)}catch(h){console.error(h,o);return}a.ok||Ze.default.log("BAD RESPONSE?!");let l;try{l=await a.json()}catch(h){console.error(h)}if(!l){Ze.default.log("## moJson"+l);return}t.MediaOverlays=Ks(l,eS.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.navigator.nextResource()):await this.stopReadAloud()}async startReadAloud(){if(this.navigator.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.navigator.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display")}}async stopReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement&&this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"))}findDepthFirstTextAudioPair(t,n,i){Ze.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&&i){a=!1;let h=d.hash.substr(1);for(let y of i)if(y===h){a=!0;break}}}else o=!1}if(Ze.default.log("isFragmentIDMatch: "+a),Ze.default.log("isTextUrlMatch: "+o),!n.Children||!n.Children.length){if(Ze.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!o){Ze.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return a||o&&!i?(Ze.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),n):void 0}let l=i,u=i;for(let d of n.Children){Ze.default.log("findDepthFirstTextAudioPair() - child"),Ze.default.log(JSON.stringify(d));let h=this.findDepthFirstTextAudioPair(t,d,u);if(h===null&&(Ze.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),u=void 0),h)return Ze.default.log("findDepthFirstTextAudioPair() - child - match"),Ze.default.log(JSON.stringify(h)),h}if(a){Ze.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let d=this.findDepthFirstTextAudioPair(t,n,void 0);return d&&(Ze.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),Ze.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&&(Ze.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(Ze.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let n=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!t);if(!n)Ze.default.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud());else{let i=!1;if(this.mediaOverlayTextAudioPair.Text&&n.Text){let o=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),a=new URL("https://dita.digital/"+n.Text);o.pathname!==a.pathname&&(Ze.default.log("mediaOverlaysNext() SWITCH! "+o.pathname+" != "+a.pathname),i=!0)}i?this.mediaOverlaysStop():(Ze.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(n,void 0,void 0)},0))}}else Ze.default.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){Ze.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){Ze.default.log("mediaOverlaysPause()"),this.mediaOverlayHighlight(void 0),this.audioElement&&this.audioElement.pause()}findNextTextAudioPair(t,n,i,o){if(!t.Children||!t.Children.length){if(i?.prev===n)return Ze.default.log("findNextTextAudioPair() - prevMo === moToMatch"),t;Ze.default.log("findNextTextAudioPair() - set previous"),Ze.default.log(JSON.stringify(t)),i.prev=t;return}for(let a of t.Children){Ze.default.log("findNextTextAudioPair() - child"),Ze.default.log(JSON.stringify(a));let l=this.findNextTextAudioPair(a,n,i,o);if(l)return Ze.default.log("findNextTextAudioPair() - match"),Ze.default.log(JSON.stringify(l)),l}}async playMediaOverlaysAudio(t,n,i){if(Ze.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",h=typeof i!="undefined";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!d&&!h){if(o.hash){let b=o.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(b&&b.length>=1){let w=b[1];try{this.currentAudioBegin=parseFloat(w)}catch(p){Ze.default.error(p)}if(b.length>=3){let p=b[3];try{this.currentAudioEnd=parseFloat(p)}catch(m){Ze.default.error(m)}}}}}else this.currentAudioBegin=n,this.currentAudioEnd=i;Ze.default.log(`${a} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let y=async b=>{if(!this.audioElement)return;let w=this.currentAudioBegin?this.currentAudioBegin:0;if(b||this.audioElement.paused)if(b&&!w||this.audioElement.currentTime===w){if(Ze.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 m=function(){p.settings.resourceReady?setTimeout(async()=>{await p.audioElement.play(),p.ensureOnTimeUpdate(!1,!0)},p.settings.wait*1e3):setTimeout(m,200)},p=this;m()}}else{Ze.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let p=async m=>{if(this.audioElement.removeEventListener("timeupdate",p),Ze.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 g=function(){f.settings.resourceReady?setTimeout(async()=>{await f.audioElement.play(),f.ensureOnTimeUpdate(!1,!0)},f.settings.wait*1e3):setTimeout(g,200)},f=this;g()}};this.audioElement.addEventListener("timeupdate",p),this.audioElement.currentTime=w}else{let p=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd!="undefined"&&this.previousAudioEnd>w-.02&&this.previousAudioEnd<=w&&this.audioElement.currentTime>=w-.1;this.ensureOnTimeUpdate(!1,!1),p?Ze.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(Ze.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=w)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||u!==this.currentAudioUrl){this.currentAudioUrl=u,Ze.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",p=>{Ze.default.log("-1) error: "+(this.currentAudioUrl!==p.currentTarget.src?this.currentAudioUrl+" -- ":"")+p.currentTarget.src.substr(p.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(Ze.default.log(this.audioElement.error.code),Ze.default.log(this.audioElement.error.message))});let b=async p=>{p.currentTarget.removeEventListener("canplaythrough",b),Ze.default.log("oncanplaythrough"),await y(!0)};this.audioElement.addEventListener("canplaythrough",b);let w=async p=>{Ze.default.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",w),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else Ze.default.log("playMediaOverlaysAudio() - playClip()"),await y(!1)}async playMediaOverlays(t,n,i){Ze.default.log("playMediaOverlays()");let o=i?i.filter(l=>l):void 0;o&&o.length===0&&(o=void 0);let a=this.findDepthFirstTextAudioPair(t,n,o);!a&&o&&(Ze.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),Ze.default.log(JSON.stringify(o,null,4)),Ze.default.log(JSON.stringify(n,null,4)),a=this.findDepthFirstTextAudioPair(t,n,void 0)),a?a.Audio&&(Ze.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=n,await this.playMediaOverlaysAudio(a,void 0,void 0)):Ze.default.log("playMediaOverlays() - !moTextAudioPair "+t)}mediaOverlayHighlight(t){Ze.default.log("moHighlight: ## "+t);let n=this.publication.Metadata?.MediaOverlay?.ActiveClass;n||(n=this.settings.color);let i=this.navigator.iframes[0].contentDocument?.documentElement.getAttribute("style"),o=i?i.indexOf("readium-night-on")>0:!1,a=i?i.indexOf("readium-sepia-on")>0:!1;if((this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&(n=o||a?X0:n||X0),this.pid){let u;this.currentLinkIndex===0?u=this.navigator.iframes[0].contentDocument?.getElementById(this.pid):u=this.navigator.iframes[1].contentDocument?.getElementById(this.pid),u&&u.classList.remove(n)}let l;t&&(this.currentLinkIndex===0?l=this.navigator.iframes[0].contentDocument?.getElementById(t):l=this.navigator.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"})}};H();var Q0=nt(Jt()),Ol=class{static async create(t){let n=new this(t.publication);return await n.start(),n}constructor(t){this.publication=t}async stop(){Q0.default.log("Timeline module stop")}async start(){this.timelineContainer=Ie(document,"#container-view-timeline"),this.positionSlider=Ie(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.navigator.currentLocator();(this.navigator.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions)&&(this.positionSlider&&(this.positionSlider.value=(n.locations.position??0).toString()),this.positionSlider&&(this.positionSlider.max=((n.locations.totalRemainingPositions??0)+(n.locations.position??0)).toString())),this.timelineContainer&&(this.timelineContainer.innerHTML=""),this.publication.readingOrder?.forEach(i=>{let o=this.publication.getAbsoluteHref(i.Href),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.navigator.view?.layout!=="fixed"?i.contentWeight?d=i.contentWeight:d=1:d=100/(this.publication.readingOrder?.length??0);var h=document.createElement("div");if(h.style.height=d+"%",h.style.width="100%",h.className="chapter",a?.Title!==void 0){var y=document.createElement("span");y.innerHTML=a.Title,y.className="chapter-tooltip",h.appendChild(y)}Ee(h,"click",b=>{b.preventDefault(),b.stopPropagation();var w;this.publication.positions||this.navigator.rights.autoGeneratePositions&&this.publication.positions?(w=et({},this.publication.positions.filter(p=>p.href===i.Href)[0]),w.href=this.publication.getAbsoluteHref(w.href)):w={href:u,locations:{progression:0},type:i.TypeLink,title:i.Title},Q0.default.log(w),this.navigator.navigate(w)}),u===this.navigator.currentChapterLink.href?h.className+=" active":h.className=h.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(h)}),t()})}};H();var vg=nt(So());H();var tS=nt(Jt());function nS(r,t){return new Promise(function(n){setTimeout(n.bind(null,t),r)})}var s8=!1;tS.default.setLevel(s8?"trace":"warn",!0);var kA=nt(PA()),dh=nt(MA()),On=nt(Jt());var ya=class{constructor(t){this.hasEventListener=!1;this.isHacked=!1;this.properties=t}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);return await n.start(),n}static async startInspectorProtection(t){(0,dh.addListener)(i=>{i&&(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,dh.launch)(),await nS(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,kA.getUserAgentRegExp)({browsers:n,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.properties?.enableObfuscation){this.wrapper=yt(document,"#iframe-wrapper"),this.securityContainer=Ie(document,"#container-view-security");var t=this;this.mutationObserver=new MutationObserver(function(n){n.forEach(function(i){On.default.log(i.type),t.isHacked=!0})})}}async stop(){if(On.default.log("Protection module stop"),this.properties?.enableObfuscation&&this.mutationObserver.disconnect(),this.properties?.disableKeys){je(this.navigator.mainElement,"keydown",this.disableSave),je(this.navigator.headerMenu,"keydown",this.disableSave);for(let t of this.navigator.iframes)je(t.contentDocument,"keydown",this.disableSave),je(t.contentWindow,"keydown",this.disableSave);je(window,"keydown",this.disableSave),je(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){je(this.navigator.mainElement,"copy",this.preventCopy),je(this.navigator.headerMenu,"copy",this.preventCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"copy",this.preventCopy),je(t.contentWindow,"copy",this.preventCopy);je(window,"copy",this.preventCopy),je(document,"copy",this.preventCopy),je(this.navigator.mainElement,"cut",this.preventCopy),je(this.navigator.headerMenu,"cut",this.preventCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"cut",this.preventCopy),je(t.contentWindow,"cut",this.preventCopy);je(window,"cut",this.preventCopy),je(document,"cut",this.preventCopy),je(this.navigator.mainElement,"keydown",this.preventCopyKey),je(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let t of this.navigator.iframes)je(t.contentDocument,"keydown",this.preventCopyKey),je(t.contentWindow,"keydown",this.preventCopyKey);je(window,"keydown",this.preventCopyKey),je(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){je(this.navigator.mainElement,"copy",this.restrictCopy),je(this.navigator.headerMenu,"copy",this.restrictCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"copy",this.restrictCopy),je(t.contentWindow,"copy",this.restrictCopy);je(window,"copy",this.restrictCopy),je(document,"copy",this.restrictCopy),je(this.navigator.mainElement,"cut",this.restrictCopy),je(this.navigator.headerMenu,"cut",this.restrictCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"cut",this.restrictCopy),je(t.contentWindow,"cut",this.restrictCopy);je(window,"cut",this.restrictCopy),je(document,"cut",this.restrictCopy),je(this.navigator.mainElement,"keydown",this.restrictCopyKey),je(this.navigator.headerMenu,"keydown",this.restrictCopyKey);for(let t of this.navigator.iframes)je(t.contentDocument,"keydown",this.restrictCopyKey),je(t.contentWindow,"keydown",this.restrictCopyKey);je(window,"keydown",this.restrictCopyKey),je(document,"keydown",this.restrictCopyKey)}if(this.properties?.disablePrint){je(this.navigator.mainElement,"beforeprint",this.beforePrint.bind(this)),je(this.navigator.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let t of this.navigator.iframes)je(t.contentDocument,"beforeprint",this.beforePrint),je(t.contentWindow,"beforeprint",this.beforePrint);je(window,"beforeprint",this.beforePrint),je(document,"beforeprint",this.beforePrint),je(this.navigator.mainElement,"afterprint",this.afterPrint.bind(this)),je(this.navigator.headerMenu,"afterprint",this.afterPrint.bind(this));for(let t of this.navigator.iframes)je(t.contentDocument,"afterprint",this.afterPrint.bind(this)),je(t.contentWindow,"afterprint",this.afterPrint.bind(this));je(window,"afterprint",this.afterPrint.bind(this)),je(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){je(this.navigator.mainElement,"contextmenu",this.disableContext),je(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let t of this.navigator.iframes)je(t.contentDocument,"contextmenu",this.disableContext),je(t.contentWindow,"contextmenu",this.disableContext);je(window,"contextmenu",this.disableContext),je(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),je(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.navigator.iframes)if(t.contentDocument){let n=Gr(t.contentDocument,"body");this.rects=this.findRects(n),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){Ee(this.navigator.mainElement,"keydown",this.disableSave),Ee(this.navigator.headerMenu,"keydown",this.disableSave);for(let t of this.navigator.iframes)Ee(t,"keydown",this.disableSave),Ee(t.ownerDocument,"keydown",this.disableSave),Ee(t.contentDocument,"keydown",this.disableSave),Ee(t.contentWindow,"keydown",this.disableSave),Ee(t.contentWindow?.document,"keydown",this.disableSave);Ee(window,"keydown",this.disableSave),Ee(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){Ee(this.navigator.mainElement,"copy",this.preventCopy),Ee(this.navigator.headerMenu,"copy",this.preventCopy);for(let t of this.navigator.iframes)Ee(t,"copy",this.preventCopy),Ee(t.ownerDocument,"copy",this.preventCopy),Ee(t.contentDocument,"copy",this.preventCopy),Ee(t.contentWindow,"copy",this.preventCopy),Ee(t.contentWindow?.document,"copy",this.preventCopy);Ee(window,"copy",this.preventCopy),Ee(document,"copy",this.preventCopy),Ee(this.navigator.mainElement,"cut",this.preventCopy),Ee(this.navigator.headerMenu,"cut",this.preventCopy);for(let t of this.navigator.iframes)Ee(t,"cut",this.preventCopy),Ee(t.ownerDocument,"cut",this.preventCopy),Ee(t.contentDocument,"cut",this.preventCopy),Ee(t.contentWindow,"cut",this.preventCopy),Ee(t.contentWindow?.document,"cut",this.preventCopy);Ee(window,"cut",this.preventCopy),Ee(document,"cut",this.preventCopy),Ee(this.navigator.mainElement,"keydown",this.preventCopyKey),Ee(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let t of this.navigator.iframes)Ee(t,"keydown",this.preventCopyKey),Ee(t.ownerDocument,"keydown",this.preventCopyKey),Ee(t.contentDocument,"keydown",this.preventCopyKey),Ee(t.contentWindow,"keydown",this.preventCopyKey),Ee(t.contentWindow?.document,"keydown",this.preventCopyKey);Ee(window,"keydown",this.preventCopyKey),Ee(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){Ee(this.navigator.mainElement,"copy",this.restrictCopy.bind(this)),Ee(this.navigator.headerMenu,"copy",this.restrictCopy.bind(this));for(let t of this.navigator.iframes)Ee(t,"copy",this.restrictCopy),Ee(t.ownerDocument,"copy",this.restrictCopy.bind(this)),Ee(t.contentDocument,"copy",this.restrictCopy.bind(this)),Ee(t.contentWindow,"copy",this.restrictCopy.bind(this)),Ee(t.contentWindow?.document,"copy",this.restrictCopy.bind(this));Ee(window,"copy",this.restrictCopy.bind(this)),Ee(document,"copy",this.restrictCopy.bind(this)),Ee(this.navigator.mainElement,"cut",this.restrictCopy.bind(this)),Ee(this.navigator.headerMenu,"cut",this.restrictCopy.bind(this));for(let t of this.navigator.iframes)Ee(t,"cut",this.restrictCopy.bind(this)),Ee(t.ownerDocument,"cut",this.restrictCopy.bind(this)),Ee(t.contentDocument,"cut",this.restrictCopy.bind(this)),Ee(t.contentWindow,"cut",this.restrictCopy.bind(this)),Ee(t.contentWindow?.document,"cut",this.restrictCopy.bind(this));Ee(window,"cut",this.restrictCopy.bind(this)),Ee(document,"cut",this.restrictCopy.bind(this)),Ee(this.navigator.mainElement,"keydown",this.restrictCopyKey.bind(this)),Ee(this.navigator.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let t of this.navigator.iframes)Ee(t,"keydown",this.restrictCopyKey.bind(this)),Ee(t.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),Ee(t.contentDocument,"keydown",this.restrictCopyKey.bind(this)),Ee(t.contentWindow,"keydown",this.restrictCopyKey.bind(this)),Ee(t.contentWindow?.document,"keydown",this.restrictCopyKey.bind(this));Ee(window,"keydown",this.restrictCopyKey.bind(this)),Ee(document,"keydown",this.restrictCopyKey.bind(this))}if(this.properties?.disablePrint){Ee(this.navigator.mainElement,"beforeprint",this.beforePrint),Ee(this.navigator.headerMenu,"beforeprint",this.beforePrint);for(let t of this.navigator.iframes)Ee(t,"beforeprint",this.beforePrint.bind(this)),Ee(t.ownerDocument,"beforeprint",this.beforePrint.bind(this)),Ee(t.contentDocument,"beforeprint",this.beforePrint.bind(this)),Ee(t.contentWindow,"beforeprint",this.beforePrint.bind(this)),Ee(t.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));Ee(window,"beforeprint",this.beforePrint.bind(this)),Ee(document,"beforeprint",this.beforePrint.bind(this)),Ee(this.navigator.mainElement,"afterprint",this.afterPrint),Ee(this.navigator.headerMenu,"afterprint",this.afterPrint);for(let t of this.navigator.iframes)Ee(t,"afterprint",this.afterPrint.bind(this)),Ee(t.ownerDocument,"afterprint",this.afterPrint.bind(this)),Ee(t.contentDocument,"afterprint",this.afterPrint.bind(this)),Ee(t.contentWindow,"afterprint",this.afterPrint.bind(this)),Ee(t.contentWindow?.document,"afterprint",this.afterPrint.bind(this));Ee(window,"afterprint",this.afterPrint.bind(this)),Ee(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){Ee(this.navigator.mainElement,"contextmenu",this.disableContext),Ee(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let t of this.navigator.iframes)Ee(t,"contextmenu",this.disableContext),Ee(t.ownerDocument,"contextmenu",this.disableContext),Ee(t.contentDocument,"contextmenu",this.disableContext),Ee(t.contentWindow,"contextmenu",this.disableContext),Ee(t.contentWindow?.document,"contextmenu",this.disableContext);Ee(window,"contextmenu",this.disableContext),Ee(document,"contextmenu",this.disableContext)}}initializeResource(){this.properties?.hideTargetUrl&&this.hideTargetUrls(!0),this.properties?.disableDrag&&this.preventDrag(!0)}async initialize(){if(this.properties?.enableObfuscation)return new Promise(async t=>{await document.fonts.ready;for(let n of this.navigator.iframes)if(n.contentDocument){let i=Gr(n.contentDocument,"body");this.observe(),setTimeout(()=>{this.rects=this.findRects(i),this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),this.setupEvents(),this.hasEventListener||(this.hasEventListener=!0,Ee(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,vg.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 On.default.log("copy action initiated"),t.clipboardData.setData("text/plain","copy not allowed"),t.stopPropagation(),t.preventDefault(),!1}preventCopyKey(t){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?t.metaKey:t.ctrlKey&&(t.key==="c"||t.keyCode===67))?(t.preventDefault(),t.stopPropagation(),!1):!0}restrictCopy(t){if(this.citation)return;On.default.log("copy action initiated");let n=this.navigator.iframes[0].contentWindow;if(n){let o=function(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=i.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)},i=this,a=Er(n,o);if(a===void 0){let l=this.navigator.iframes[0].contentDocument;a=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(l)}t.clipboardData.setData("text/plain",a?.cleanText?.substring(0,this.properties?.charactersToCopy??0))}else t.clipboardData.setData("text/plain","");return t.stopPropagation(),t.preventDefault(),!1}restrictCopyKey(t){if(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?t.metaKey:t.ctrlKey&&(t.key==="c"||t.keyCode===67)){let n=this.navigator.iframes[0].contentWindow;if(n){let o=function(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=i.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)},i=this,a=Er(n,o);if(a===void 0){let l=this.navigator.iframes[0].contentDocument;a=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(l)}this.copyToClipboard(a?.cleanText?.substring(0,this.properties?.charactersToCopy??0))}else this.copyToClipboard("");return t.stopPropagation(),t.preventDefault(),!1}return!0}copyToClipboard(t){if(t=t.substring(0,this.properties?.charactersToCopy??0),window.clipboardData)window.clipboardData.setData("text/plain",t);else{let n=this.createElementForExecCommand(t);this.selectContent(n);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),document.execCommand("copy",!1)}catch(i){}document.body.removeChild(n)}}createElementForExecCommand(t){let n=document.createElement("div");return n.style.position="absolute",n.style.left="-10000px",n.style.top="-10000px",n.innerHTML=t,document.body.appendChild(n),n.contentEditable=!0,n}selectContent(t){let n=document.createRange();n.selectNodeContents(t);let i=window.getSelection();i?.removeAllRanges(),i?.addRange(n)}beforePrint(t){return On.default.log("before print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.display="none",this.navigator.mainElement.style.display="none"),t.stopPropagation(),t.preventDefault(),!1}afterPrint(t){return On.default.log("after print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.removeProperty("display"),this.navigator.mainElement.style.removeProperty("display")),t.stopPropagation(),t.preventDefault(),!1}hideTargetUrls(t){function n(i){i.preventDefault();let o=i.currentTarget.getAttribute("data-href-resolved"),a=document.createElement("a");a.setAttribute("href",o),a.click()}for(let i of this.navigator.iframes){let o=i.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;",i=o=>{o.preventDefault()};for(let o of this.navigator.iframes){let a=o.contentDocument?.body.getAttribute("style")||"";t?(o.contentDocument?.body.addEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",a+n)):(o.contentDocument?.body.removeEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",a.replace(n,"")))}}recalculate(t=0){return new Promise(n=>{if(this.properties?.enableObfuscation){let i=(0,vg.debounce)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),n(!0)},t);this.rects?(this.observe(),i()):n(!1)}else n(!1)})}calcRects(t){t!==void 0&&t.forEach(n=>{try{let{top:i,height:o,left:a,width:l}=this.measureTextNode(n.node);n.top=i,n.height=o,n.width=l,n.left=a}catch(i){On.default.log("error "+i),On.default.log(n),On.default.log(n.node),On.default.log("scrambledTextContent "+n.scrambledTextContent),On.default.log("textContent "+n.textContent),On.default.log("isObfuscated "+n.isObfuscated)}})}deactivateRect(t,n,i){this.isBeingHacked(n)||i?(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0):(t.node.textContent=t.textContent,t.isObfuscated=!1)}toggleRect(t,n,i){let o=this.isOutsideViewport(t),a=this.isBeingHacked(n);t.isObfuscated&&!o&&!a&&!i&&(t.node.textContent=t.textContent,t.isObfuscated=!1),!t.isObfuscated&&(o||a||i)&&(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0)}findRects(t){return this.findTextNodes(t).map(i=>{let{top:o,height:a,left:l,width:u}=this.measureTextNode(i),d=i.parentElement?.nodeName==="option"||i.parentElement?.nodeName==="script"?i.textContent:this.obfuscateText(i.textContent??"");return{top:o,height:a,width:u,left:l,node:i,textContent:i.textContent??"",scrambledTextContent:d??"",isObfuscated:!1}})}obfuscateText(t){return this.scramble(t,!0)}measureTextNode(t){try{let n=document.createRange();n.selectNode(t);let i=n.getBoundingClientRect();return n.detach(),i}catch(n){On.default.log("measureTextNode "+n),On.default.log("measureTextNode "+t),On.default.log(t.textContent)}}isBeingHacked(t){return t.style.animation||t.style.transition||t.style.position||t.hasAttribute("style")?(On.default.log("content being hacked"),!0):!1}isOutsideViewport(t){let n=this.wrapper.scrollLeft,i=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,h=t.top>u,y=o<n-window.innerWidth,b=t.left>i+window.innerWidth;return d||h||y||b}findTextNodes(t,n=[]){let i=t.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,n),i.nodeType===3&&i.textContent?.trim()&&n.push(i),i=i.nextSibling;return n}scramble(t,n=!1,i=!1){var o=t.split(" ");function a(l){for(var u=l.length,d,h;u>0;)h=Math.floor(Math.random()*u),u--,d=l[u],l[u]=l[h],l[h]=d;return l}return n&&(o=o.map(function(l){return l.includes("-")?l:a(l.split("")).join("")})),i?a(o).join(" "):o.join(" ")}};H();var jA=nt(IA());H();var hh=r=>r.replace(/\n/g," ").replace(/\s\s+/g," "),S8=r=>hh(r).trim(),BA=/[\\^$.*+?()[\]{}|]/g,A8=RegExp(BA.source);function NA(r){return r&&A8.test(r)?r.replace(BA,"\\$&"):r||""}var fh=0,x8=()=>()=>Number.isSafeInteger(++fh)?fh:fh=1,DA=()=>{fh=0},C8=x8(),T8=r=>t=>{try{return wn(t,r,Co)}catch(n){return console.error("uniqueCssSelector:",n),""}};async function Mo(r,t,n,i,o=!1){if(!t)return[];let a=t.body?.textContent;if(!a)return[];if(r=S8(r),!r.length)return[];let l=t.createNodeIterator(t.body,NodeFilter.SHOW_TEXT,{acceptNode:p=>NodeFilter.FILTER_ACCEPT}),u=new RegExp(NA(r).replace(/ /g,"\\s+"),"gim");o&&(u=new RegExp("\\b"+NA(r).replace(/ /g,"\\s+")+"\\b","gim"));let d=[],h=100,y=30,b=0,w;for(;w=u.exec(a);){let p=Math.max(0,w.index-h),m=Math.min(h,w.index),f=hh(a.substr(p,m));f=f.substr(f.length-y),p=u.lastIndex,m=Math.min(h,a.length-p);let g=hh(a.substr(p,m)).substr(0,y),v=new Range,A=w.index;for(;b<=A;){let E=l.nextNode();E&&E.nodeValue&&(b+=E.nodeValue.length)}let C=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(b-A):0;for(v.setStart(l.referenceNode,C),A=w.index+w[0].length;b<=A;){let T=l.nextNode()?.nodeValue;T&&(b+=T.length)}C=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(b-A):0,v.setEnd(l.referenceNode,C),t.getCssSelector||(t.getCssSelector=T8(t));let O=Xr(v,t.getCssSelector);O&&d.push({textMatch:hh(w[0]),textBefore:f,textAfter:g,rangeInfo:O,href:n,title:i,uuid:C8().toString()})}return d}var FA=nt(Jt()),Ll=class{constructor(t,n,i,o,a){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.headerMenu=a,this.publication=t,this.properties=n,this.api=o,this.highlighter=i}static async create(t){let n=new this(t.publication,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){FA.default.log("Search module stop"),je(this.searchInput,"keypress",this.handleSearch.bind(this)),je(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.headerMenu){this.searchInput=Ie(this.headerMenu,"#searchInput"),Ee(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=Ie(this.headerMenu,"#searchGo"),Ee(this.searchGo,"click",this.handleSearch.bind(this));var t=Ie(this.headerMenu,"#menu-button-search");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("search"):this.navigator.showLayer("search")},10)}async handleSearch(t){(t.key==="Enter"||t.type==="click")&&(await this.handleSearchChapter(),await this.handleSearchBook())}async handleSearchChapter(t){var n=this,i=this.searchInput.value;let o=this.navigator.currentChapterLink.href,a=this.publication.getSpineItem(o);if(this.headerMenu)var l=Ie(document,"#searchResultChapter");n.currentChapterSearchResult=[],n.currentSearchHighlights=[];var u=[];this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate(),await this.searchAndPaintChapter(i,t,async h=>{u=h,d(1),this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)});async function d(h){l.innerHTML="";var y;if(y=n.paginate(u,h,10),y.total===0){let b=document.createElement("a");b.className="collection-item",b.innerHTML="nothing found",l.appendChild(b)}else{for(let f=0;f<y.data.length;f++){let g=document.createElement("a"),v=y.data[f];g.className="collection-item",g.href=a?.Href??"",g.innerHTML="..."+v.textBefore+"<mark>"+v.textMatch+"</mark>"+v.textAfter+"...",Ee(g,"click",A=>{A.preventDefault(),A.stopPropagation(),n.jumpToMark(f+h*10-10)}),l.appendChild(g)}let b=document.createElement("div");b.style.textAlign="center",b.style.marginTop="10px";let w=document.createElement("ul");w.className="pagination";let p=document.createElement("li");if(p.className="disabled",p.innerHTML='<a href="#!"> < </a>',y.pre_page!==void 0){let f=y.pre_page;p.className="waves-effect",Ee(p,"click",g=>{g.preventDefault(),g.stopPropagation(),d(f)})}w.appendChild(p);for(let f=1;f<=y.total_pages;f++){let g,v=document.createElement("li");v.className="waves-effect",f===y.page&&(v.className="active",g=v),v.innerHTML='<a href="#!">'+f+"</a>",Ee(v,"click",A=>{A.preventDefault(),A.stopPropagation(),g&&(g.className="waves-effect"),v.className="active",g=v,d(f)}),w.appendChild(v)}let m=document.createElement("li");if(m.className="disabled",m.innerHTML='<a href="#!"> > </a>',y.next_page!==void 0){let f=y.next_page;m.className="waves-effect",Ee(m,"click",g=>{g.preventDefault(),g.stopPropagation(),d(f)})}w.appendChild(m),b.appendChild(w),l.appendChild(b)}}}async searchAndPaintChapter(t,n=0,i){let o=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),a=this.publication.getTOCItem(o);a===null&&(a=this.publication.readingOrder[this.navigator.currentResource()??0]);let l=[];this.highlighter?.destroyHighlights(it.Search),this.navigator.rights.enableSearch&&this.drawSearch();let u=0;if(a){let d=this.navigator.iframes[0].contentDocument;d&&a&&Mo(t,d,a.Href,a.Title).then(h=>{h.forEach(y=>{let b={rangeInfo:y.rangeInfo};setTimeout(()=>{let w;u===n?(w=this.createSearchHighlight(b,this.properties?.current),this.jumpToMark(n)):w=this.createSearchHighlight(b,this.properties?.color),y.highlight=w,l.push(y),this.currentChapterSearchResult.push(y),this.currentSearchHighlights.push(w),u++},500)}),setTimeout(()=>{i(l)},500)})}}createSearchHighlight(t,n){try{var i=n;Qe.isHexColor(i)&&(i=Qe.hexToRgbChannels(i));let a=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,l=jA.SHA256.hash(a),u="R2_SEARCH_"+l;var o=!1;let d={color:i||ls,id:u,pointerInteraction:o,selectionInfo:t,marker:Ve.Highlight,type:it.Search},h=this.highlighter?.createHighlightDom(this.navigator.iframes[0].contentWindow,d);return d.position=parseInt((h?.hasChildNodes()?h.childNodes[0]:h).style.top.replace("px","")),d}catch(a){throw"Can't create highlight: "+a}}clearSearch(){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.highlighter?.destroyHighlights(it.Search)}async search(t,n){return this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],DA(),await this.searchAndPaintChapter(t,0,async()=>{}),n?(await this.searchBook(t),await this.searchChapter(t)):(await this.searchChapter(t),await this.searchBook(t))}async goToSearchID(t,n,i){var o=n,a;let l=this.navigator.currentChapterLink.href;var u=this.publication.getAbsoluteHref(t);let d=this.bookSearchResult.filter(h=>h.href===t);if(i?(a=this.currentChapterSearchResult.filter(h=>h.uuid===n)[0],o=this.currentChapterSearchResult.findIndex(h=>h.uuid===n)):(a=d.filter(h=>h.uuid===n)[0],o=d.findIndex(h=>h.uuid===n)),a!==void 0)if(l===u)this.jumpToMark(o);else{let y={href:u,locations:{progression:0},title:"title"};this.navigator.navigate(y),setTimeout(()=>{this.searchAndPaintChapter(a.textMatch,o,async()=>{})},300)}}async goToSearchIndex(t,n,i){var o=n,a;let l=this.navigator.currentChapterLink.href;var u=this.publication.getAbsoluteHref(t);let d=this.bookSearchResult.filter(h=>h.href===t);if(i?a=this.currentChapterSearchResult[o]:a=d[o],a!==void 0)if(l===u)this.jumpToMark(o);else{let y={href:u,locations:{progression:0},title:"title"};this.navigator.navigate(y),setTimeout(()=>{this.searchAndPaintChapter(a.textMatch,o,async()=>{})},300)}}async handleSearchBook(){var t=this,n=this.searchInput.value;if(t.headerMenu)var i=Ie(document,"#searchResultBook");o(1);async function o(l){i.innerHTML="";var u,d=await t.searchBook(n);if(u=t.paginate(d,l,10),u.total===0){let h=document.createElement("a");h.className="collection-item",h.innerHTML="nothing found",i.appendChild(h)}else{a(u.data,m=>m.href).forEach(m=>{let f=document.createElement("div");if(f.style.marginBottom="10px",m[0].title){let g=document.createElement("span");g.className="collection-item",g.style.display="block",g.innerHTML=m[0].title,f.appendChild(g)}i.appendChild(f),m.forEach(g=>{let v=document.createElement("a");v.className="collection-item";var A=t.publication.getAbsoluteHref(g.href);v.innerHTML="..."+g.textBefore+"<mark>"+g.textMatch+"</mark>"+g.textAfter+"...",Ee(v,"click",C=>{C.preventDefault(),C.stopPropagation();let E=d.filter(B=>B.href===g.href).findIndex(B=>B===g);if(t.navigator.currentChapterLink.href===A)t.jumpToMark(E);else{let M={href:A,locations:{progression:0},title:"title"};t.navigator.navigate(M),setTimeout(()=>{t.handleSearchChapter(E)},300)}}),f.appendChild(v)})});let y=document.createElement("div");y.style.textAlign="center",y.style.marginTop="10px";let b=document.createElement("ul");b.className="pagination";let w=document.createElement("li");if(w.className="disabled",w.innerHTML='<a href="#!"> < </a>',u.pre_page!=null){let m=u.pre_page;w.className="waves-effect",Ee(w,"click",f=>{f.preventDefault(),f.stopPropagation(),o(m)})}b.appendChild(w);for(let m=1;m<=u.total_pages;m++){let f,g=document.createElement("li");g.className="waves-effect",m===u.page&&(g.className="active",f=g),g.innerHTML='<a href="#!">'+m+"</a>",Ee(g,"click",v=>{v.preventDefault(),v.stopPropagation(),f&&(f.className="waves-effect"),g.className="active",f=g,o(m)}),b.appendChild(g)}let p=document.createElement("li");if(p.className="disabled",p.innerHTML='<a href="#!"> > </a>',u.next_page!=null){let m=u.next_page;p.className="waves-effect",Ee(p,"click",f=>{f.preventDefault(),f.stopPropagation(),o(m)})}b.appendChild(p),y.appendChild(b),i.appendChild(y)}}function a(l,u){let d=new Map;return l.forEach(h=>{let y=u(h),b=d.get(y);b?b.push(h):d.set(y,[h])}),Array.from(d.values())}}async searchBook(t){this.bookSearchResult=[];let n=[];for(let i=0;i<this.publication.readingOrder.length;i++){let o=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[i].Href:""),a=this.publication.getTOCItem(o);if(a===void 0&&this.publication.readingOrder&&(a=this.publication.readingOrder[i]),a){let l=this.publication.getAbsoluteHref(a.Href);this.navigator.api?.getContent?await this.navigator.api?.getContent(l).then(u=>{let h=new DOMParser().parseFromString(u,"application/xhtml+xml");a&&Mo(t,h,a.Href,a.Title).then(y=>{y.forEach(b=>{n.push(b),this.bookSearchResult.push(b)})})}):await fetch(l,this.navigator.requestConfig).then(u=>u.text()).then(async u=>{let h=new DOMParser().parseFromString(this.navigator.requestConfig?.encoded?this.decodeBase64(u):u,"application/xhtml+xml");a&&Mo(t,h,a.Href,a.Title).then(y=>{y.forEach(b=>{n.push(b),this.bookSearchResult.push(b)})})})}if(i===this.publication.readingOrder.length-1)return n}}decodeBase64(t){let n=atob(t),i=n.length,o=new Uint8Array(i);for(let l=0;l<i;l++)o[l]=n.charCodeAt(l);return new TextDecoder().decode(o)}async searchChapter(t){let n=[],i=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),o=this.publication.getTOCItem(i);if(o===null&&(o=this.publication.readingOrder[this.navigator.currentResource()??0]),o){let a=this.publication.getAbsoluteHref(o.Href);this.navigator.api?.getContent?await this.navigator.api?.getContent(a).then(l=>{let d=new DOMParser().parseFromString(l,"application/xhtml+xml");o&&Mo(t,d,o.Href,o.Title).then(h=>{h.forEach(y=>{n.push(y)})})}):await fetch(a,this.navigator.requestConfig).then(l=>l.text()).then(async l=>{let d=new DOMParser().parseFromString(this.navigator.requestConfig?.encoded?this.decodeBase64(l):l,"application/xhtml+xml");o&&Mo(t,d,o.Href,o.Title).then(h=>{h.forEach(y=>{n.push(y)})})})}return n}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(t=>{let n={rangeInfo:t.rangeInfo};if(this.properties?.color){let i=this.createSearchHighlight(n,this.properties?.color);t.highlight=i,this.currentSearchHighlights.push(i)}})},100)}async handleResize(){await this.highlighter?.destroyHighlights(it.Search),this.drawSearch()}jumpToMark(t){setTimeout(()=>{if(this.currentChapterSearchResult.length){var n=this.currentChapterSearchResult[t];this.currentSearchHighlights.forEach(o=>{var a=this.properties?.color;Qe.isHexColor(a)&&(a=Qe.hexToRgbChannels(a)),o.color=a});var i=this.properties?.current;Qe.isHexColor(i)&&(i=Qe.hexToRgbChannels(i)),n.highlight.color=i,this.highlighter?.setAndResetSearchHighlight(n.highlight,this.currentSearchHighlights),this.navigator.view?.goToCssSelector(n.rangeInfo.startContainerElementCssSelector),this.navigator.updatePositionInfo()}},200)}paginate(t,n,i){let o=n||1,a=i||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}}};H();var oi=nt(Jt()),ko=class{},Ke=ko;Ke.COLOR_REF="color",Ke.AUTO_SCROLL_REF="autoscroll",Ke.RATE_REF="rate",Ke.PITCH_REF="pitch",Ke.VOLUME_REF="volume",Ke.VOICE_REF="voice",Ke.COLOR_KEY="tts-"+ko.COLOR_REF,Ke.AUTO_SCROLL_KEY="tts-"+ko.AUTO_SCROLL_REF,Ke.RATE_KEY="tts-"+ko.RATE_REF,Ke.PITCH_KEY="tts-"+ko.PITCH_REF,Ke.VOLUME_KEY="tts-"+ko.VOLUME_REF,Ke.VOICE_KEY="tts-"+ko.VOICE_REF;var Eg=class{constructor(t,n,i){this.TTSSETTINGS="ttsSetting";this.color="orange";this.autoScroll=!0;this.rate=1;this.pitch=1;this.volume=1;this.voice={usePublication:!0};this.settingsChangeCallback=()=>{};this.restartCallback=()=>{};this.store=t,this.api=n,this.headerMenu=i,this.initialise()}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialTTSSettings){let i=t.initialTTSSettings;i?.rate&&(n.rate=i.rate,oi.default.log(n.rate)),i?.pitch&&(n.pitch=i.pitch,oi.default.log(n.pitch)),i?.volume&&(n.volume=i.volume,oi.default.log(n.volume)),i?.color&&(n.color=i.color,oi.default.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,oi.default.log(n.autoScroll)),i?.voice&&(n.voice=i.voice,oi.default.log(n.voice))}return n.initializeSelections(),n}stop(){oi.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(Ke.AUTO_SCROLL_KEY)!=null?this.getProperty(Ke.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(Ke.RATE_KEY)!=null?this.getProperty(Ke.RATE_KEY).value:this.rate,this.pitch=this.getProperty(Ke.PITCH_KEY)!=null?this.getProperty(Ke.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(Ke.VOLUME_KEY)!=null?this.getProperty(Ke.VOLUME_KEY).value:this.volume,this.color=this.getProperty(Ke.COLOR_KEY)!=null?this.getProperty(Ke.COLOR_KEY).value:this.color,this.voice=this.getProperty(Ke.VOICE_REF)!=null?this.getProperty(Ke.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=Ie(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechRate=Ie(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=Ie(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=Ie(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=Ie(this.headerMenu,"#autoScroll")),this.speechRate&&(this.speechRate.value=this.rate.toString()),this.speechPitch&&(this.speechPitch.value=this.pitch.toString()),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),Ee(Ie(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(Ke.RATE_REF)?.value,pitch:this.userProperties.getByRef(Ke.PITCH_REF)?.value,volume:this.userProperties.getByRef(Ke.VOLUME_REF)?.value,voice:this.userProperties.getByRef(Ke.VOLUME_REF)?.value,color:this.userProperties.getByRef(Ke.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Ke.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{oi.default.log("api updated tts settings",n)})}getTTSSettings(){var t=new Wr;return t.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,Ke.AUTO_SCROLL_REF,Ke.AUTO_SCROLL_KEY),t.addIncremental(this.rate,.1,10,.1,"",Ke.RATE_REF,Ke.RATE_KEY),t.addIncremental(this.pitch,.1,2,.1,"",Ke.PITCH_REF,Ke.PITCH_KEY),t.addIncremental(this.volume,.1,1,.1,"",Ke.VOLUME_REF,Ke.VOLUME_KEY),t.addStringable(this.color,Ke.COLOR_REF,Ke.COLOR_KEY),t.addJSONable(JSON.stringify(this.voice),Ke.VOICE_REF,Ke.VOICE_KEY),t}saveProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}return t}getProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?void 0:i[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(t){if(t.rate){oi.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Ke.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.pitch){oi.default.log("pitch "+this.pitch),this.pitch=t.pitch;let n=this.userProperties.getByRef(Ke.PITCH_REF);n&&(n.value=this.pitch,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.volume){oi.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Ke.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(Ke.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){oi.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Ke.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.voice){oi.default.log("voice "+this.voice),this.voice=t.voice;let n=this.userProperties.getByRef(Ke.VOICE_REF);n&&(n.value=this.voice,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}}applyPreferredVoice(t){var n=t.indexOf(":")!==-1?t.slice(0,t.indexOf(":")):void 0,i=t.indexOf(":")!==-1?t.slice(t.indexOf(":")+1):t;n!==void 0&&i!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:n,lang:i}}):i!==void 0&&n===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:i}})}increase(t){if(t==="rate"){this.userProperties.getByRef(Ke.RATE_REF).increment();let n=this.userProperties.getByRef(Ke.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(Ke.PITCH_REF).increment();let n=this.userProperties.getByRef(Ke.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(Ke.VOLUME_REF).increment();let n=this.userProperties.getByRef(Ke.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}decrease(t){if(t==="rate"){this.userProperties.getByRef(Ke.RATE_REF).decrement();let n=this.userProperties.getByRef(Ke.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(Ke.PITCH_REF).decrement();let n=this.userProperties.getByRef(Ke.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(Ke.VOLUME_REF).decrement();let n=this.userProperties.getByRef(Ke.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}};H();H();var ph=`${nr.loading}`,HA=`
79
+ </svg>`,nr={error:ti("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:ti("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:z5("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:ti("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:ti("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:ti("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:ti("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:ti("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:ti("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:ti("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:ti("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:ti("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:ti("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:ti("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:ti("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 N0=nt(Kd());var ni=nt(Jt()),qe;(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"})(qe||(qe={}));var j_="R2_CLASS_HIGHLIGHT_CONTAINER",Sl="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",Tn="R2_CLASS_HIGHLIGHT_AREA",Al="R2_CLASS_HIGHLIGHT_ICON",_r=.5,F_=.75,ls={blue:100,green:50,red:230},tn=[],V5="data-highlighted",J5="data-timestamp",ha={ELEMENT_NODE:1,TEXT_NODE:3},Ai=[qe.R2_ID_HIGHLIGHTS_CONTAINER,qe.R2_ID_PAGEBREAK_CONTAINER,qe.R2_ID_SEARCH_CONTAINER,qe.R2_ID_READALOUD_CONTAINER,qe.R2_ID_BOOKMAKRS_CONTAINER,qe.R2_ID_DEFINITIONS_CONTAINER,qe.R2_ID_LINEFOCUS_CONTAINER,qe.R2_ID_GUTTER_RIGHT_CONTAINER,j_,Tn,Sl],D0=-1,j0=-1,Qe=class{constructor(t,n,i,o,a){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.showTool=(0,_l.debounce)(t=>{this.isAndroid()||this.snapSelectionToWord(t),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,_l.debounce)(()=>{this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen(),this.navigator.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,_l.debounce)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.navigator.emit("toolbox.closed","closed"))},100);this.selection=(0,_l.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.layerSettings=t,this.properties=n,this.api=a,this.hasEventListener=i,this.options=this.defaults(o,{color:"#fce300",highlightedClass:"highlighted",contextClass:"highlighter-context",onBeforeHighlight:function(){return!0},onAfterHighlight:function(){}})}static async create(t){let n=new this(t.layerSettings,t,!1,{},t.api);return new Promise(i=>i(n))}async initialize(){let t=this.navigator.iframes[0].contentDocument;t&&this.dom(t.body).addClass(this.options.contextClass),this.bindEvents(this.navigator.iframes[0].contentDocument?.body,this,this.hasEventListener),this.initializeToolbox(),D0=-1,j0=-1;let n=this;async function i(){n.lastSelectedHighlight===void 0||(n.lastSelectedHighlight=void 0)}setTimeout(async()=>{let o=this.navigator.iframes[0].contentDocument;o&&await o.body?.addEventListener("click",i)},100)}haveSameColor(t,n){return this.dom(t).color()===this.dom(n).color()}defaults(t,n){t=t||{};for(let i in n)n.hasOwnProperty(i)&&t[i]===void 0&&(t[i]=n[i]);return t}unique(t){return t.filter(function(n,i,o){return o.indexOf(n)===i})}refineRangeBoundaries(t){let n=t.startContainer,i=t.endContainer,o=t.commonAncestorContainer,a=!0;if(t.endOffset===0){for(;!i.previousSibling&&i.parentNode!==o;)i=i.parentNode;i=i.previousSibling}else i.nodeType===ha.TEXT_NODE?t.endOffset<i.nodeValue.length&&i.splitText(t.endOffset):t.endOffset>0&&(i=i.childNodes.item(t.endOffset-1));return n.nodeType===ha.TEXT_NODE?t.startOffset===n.nodeValue.length?a=!1:t.startOffset>0&&(n=n.splitText(t.startOffset),i===n.previousSibling&&(i=n)):t.startOffset<n.childNodes.length?n=n.childNodes.item(t.startOffset):n=n.nextSibling,{startContainer:n,endContainer:i,goDeeper:a}}sortByDepth(t,n){let i=this;t.sort(function(o,a){return i.dom(n?a:o).parents().length-i.dom(n?o:a).parents().length})}groupHighlights(t){let n=[],i={},o=[];return t.forEach(function(a){let l=a.getAttribute(J5);typeof i[l]=="undefined"&&(i[l]=[],n.push(l)),i[l].push(a)}),n.forEach(function(a){let l=i[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(i){t.classList?t.classList.add(i):t.className+=" "+i},removeClass:function(i){t.classList?t.classList.remove(i):t.className=t.className.replace(new RegExp("(^|\\b)"+i+"(\\b|$)","gi")," ")},prepend:function(i){let o=Array.prototype.slice.call(i),a=o.length;for(;a--;)t.insertBefore(o[a],t.firstChild)},append:function(i){let o=Array.prototype.slice.call(i);for(let a=0,l=o.length;a<l;++a)t.appendChild(o[a])},insertAfter:function(i){return i.parentNode?.insertBefore(t,i.nextSibling)},insertBefore:function(i){return i.parentNode?.insertBefore(t,i)},remove:function(){t.parentNode.removeChild(t),t=null},contains:function(i){return t!==i&&t.contains(i)},wrap:function(i){return t.parentNode&&t.parentNode.insertBefore(i,t),i.appendChild(t),i},unwrap:function(){let i=Array.prototype.slice.call(t.childNodes),o;return i.forEach(function(a){o=a.parentNode,n.dom(a).insertBefore(a.parentNode),n.dom(o).remove()}),i},parents:function(){let i,o=[];for(;i=t.parentNode;)o.push(i),t=i;return o},normalizeTextNodes:function(){if(!!t){if(t.nodeType===ha.TEXT_NODE)for(;t.nextSibling&&t.nextSibling.nodeType===ha.TEXT_NODE;)t.nodeValue+=t.nextSibling.nodeValue,t.parentNode.removeChild(t.nextSibling);else n.dom(t.firstChild).normalizeTextNodes();n.dom(t.nextSibling).normalizeTextNodes()}},color:function(){return t.style.backgroundColor},fromHTML:function(i){let o=document.createElement("div");return o.innerHTML=i,o.childNodes},getRange:function(){let i=n.dom(t)?.getSelection(),o;return i?.rangeCount>0&&(o=i?.getRangeAt(0)),o},removeAllRanges:function(){n.dom(t)?.getSelection()?.removeAllRanges(),n.toolboxHide()},getSelection:function(){return n.dom(t).getWindow()?.getSelection()},getWindow:function(){return n.dom(t).getDocument()?.defaultView},getDocument:function(){return t?.ownerDocument||t}}}disableContext(t){return t.preventDefault(),t.stopPropagation(),!1}bindEvents(t,n,i){let o=t.ownerDocument;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)),i||window.addEventListener("resize",this.toolboxPlacement.bind(this)),o.addEventListener("selectionchange",this.toolboxPlacement.bind(this)),o.addEventListener("selectionchange",this.toolboxShowDelayed.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){D0=t.clientX,j0=t.clientY}async mouseup(t){Math.abs(D0-t.clientX)<3&&Math.abs(j0-t.clientY)<3&&await this.processMouseEvent(t)}async mousemove(t){await this.processMouseEvent(t)}unbindEvents(t,n){let i=t.ownerDocument;t.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),i.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),i.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),i.removeEventListener("selectionchange",this.toolboxPlacement.bind(this)),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.navigator.iframes[0].contentDocument;t&&(this.unbindEvents(t.body,this),this.dom(t.body).removeClass(this.options.contextClass))}initializeToolbox(){let t=document.getElementById("highlight-toolbox-mode-colors"),n=document.getElementById("highlight-toolbox-mode-add"),i=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],o=document.getElementById("colorIcon"),a=document.getElementById("actionIcon"),l=document.getElementById("dismissIcon"),u=document.getElementById("collapseIcon"),d=document.getElementById("highlightIcon"),h=this;if(l&&(l.innerHTML=nr.close,l.addEventListener("click",function(){h.toolboxMode("add")})),u&&(u.innerHTML=nr.close,u.addEventListener("click",function(){h.toolboxMode("add")})),o){o.style.position="relative",o.style.zIndex="20",i.forEach(w=>{let p=document.getElementById(w),m=document.getElementById(`c${w}`);p&&t?.contains(p)&&t.removeChild(p),n&&m&&n.contains(m)&&n.removeChild(m)});let y=[],b=[];if(o.addEventListener("click",function(){h.toolboxMode("colors")}),this.navigator.rights.enableAnnotations){let w=10;i.forEach(p=>{w--;let m=o?.cloneNode(!0),f=m.lastChild,g=Qe.hexToRgbChannels(p);f.style.backgroundColor="rgba("+[g.red,g.green,g.blue].join(",")+",.5)",m.id=`c${p}`,m.style.display="unset",m.style.position="relative",m.style.zIndex=`${w}`,m.style.marginLeft="-30px",b.push(m),n?.insertBefore(m,d)})}i.forEach(w=>{let p=o?.cloneNode(!0),m=p.lastChild;m.style.backgroundColor=w,p.id=w,p.style.position="relative",p.style.display="unset",y.push(p),o&&p.addEventListener("click",function(){h.setColor(w);let f=o?.lastChild;f&&(f.style.backgroundColor=w);let g=document.getElementById("highlightIcon"),v=document.getElementById("underlineIcon"),A=document.getElementById("noteIcon");(g?.getElementsByTagName?.("span").length??0)>0&&((g?.getElementsByTagName("span")[0]).style.background=h.getColor()),(v?.getElementsByTagName?.("span").length??0)>0&&((v?.getElementsByTagName("span")[0]).style.borderBottomColor=h.getColor()),(A?.getElementsByTagName?.("span").length??0)>0&&((A?.getElementsByTagName("span")[0]).style.borderBottomColor=h.getColor()),h.toolboxMode("add")}),t?.insertBefore(p,l)})}a&&a.addEventListener("click",function(){h.toolboxMode("action")}),h.toolboxMode("add")}toolboxMode(t){let n=document.getElementById("highlight-toolbox-mode-colors"),i=document.getElementById("highlight-toolbox-mode-add"),o=document.getElementById("highlight-toolbox-mode-edit"),a=document.getElementById("highlight-toolbox-mode-action");switch(t){case"colors":n&&(n.style.display="unset"),i&&(i.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="none");break;case"edit":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="unset"),a&&(a.style.display="none");break;case"action":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="unset");break;default:n&&(n.style.display="none"),i&&(i.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,i=this.navigator.iframes[0].contentDocument;if(i){let a=n.dom(i.body)?.getSelection();if(n.dom(i.body)&&a&&!a?.isCollapsed){let h=function(g){let v=g.match(new RegExp("[^a-zA-Z0-9]+$"));return!v||!v.index?g:g.slice(0,v.index)},l=a.toString(),u=l.length-l.trimStart().length,d=l.length-l.trimEnd().length,y=l.length;var o=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;l=l.replace(o,""),u=y-l.trimStart().length,l=h(l),d=y-l.trimEnd().length;let b=document.createRange();t?(b.setStart(a.anchorNode,a.anchorOffset+u),b.setEnd(a.focusNode,a.focusOffset-d)):(b.setStart(a.anchorNode,a.anchorOffset),b.setEnd(a.focusNode,a.focusOffset));let w=b.collapsed;b.detach();let p=a.focusNode,m;t?(m=a.focusOffset-d,a.collapse(a.anchorNode,a.anchorOffset+u)):(m=a.focusOffset,a.collapse(a.anchorNode,a.anchorOffset));let f=["forward","backward"];w&&(f=["backward","forward"]),t?(a.modify("move",f[0],"character"),a.modify("move",f[1],"word"),a.extend(p,m),a.modify("extend",f[1],"character"),a.modify("extend",f[0],"word")):a.extend(p,m),this.selection(a.toString(),a)}return a}}toolboxShow(){if(this.activeAnnotationMarkerId===void 0){let t=this,n=document.getElementById("highlight-toolbox-mode-add"),i=this.dom(this.navigator.iframes[0].contentDocument?.body).getRange();if((!i||i.collapsed)&&n){getComputedStyle(n).display!=="none"&&t.toolboxHide();return}this.isIOS()&&setTimeout(function(){let o=t.navigator.iframes[0].contentDocument;if(o){let a=t.dom(o.body).getSelection();a.removeAllRanges(),setTimeout(function(){a.addRange(i);function l(h){let y={className:w=>Ai.indexOf(w)<0,idName:w=>Ai.indexOf(w)<0},b=t.navigator.iframes[0].contentDocument;if(b)return wn(h,b,y)}let u=t.navigator.iframes[0].contentWindow,d=Er(u,l);t.navigator.annotationModule?.annotator?.saveTemporarySelectionInfo(d)},5)}},100),this.toolboxPlacement(),this.toolboxHandler()}}toolboxPlacement(){let t=this.dom(this.navigator.iframes[0].contentDocument?.body).getRange();if(!t||t.collapsed)return;let n=t.getBoundingClientRect(),i=document.getElementById("highlight-toolbox");i&&(this.navigator.view?.isPaginated()?i.style.top=n.top+(this.navigator.attributes?.navHeight??0)+"px":i.style.top=n.top+"px",i.style.left=(n.right-n.left)/2+n.left+"px")}toolboxHandler(){let t=document.getElementById("highlight-toolbox");if(t&&getComputedStyle(t).display==="none"){t.style.display="block",this.navigator.view?.isPaginated()?t.style.position="absolute":t.style.position="relative",this.selectionMenuOpened();let i=this;i.toolboxMode("add");let o=document.getElementById("highlightIcon"),a=document.getElementById("collapseIcon"),l=document.getElementById("underlineIcon"),u=document.getElementById("noteIcon"),d=document.getElementById("colorIcon"),h=document.getElementById("speakIcon");if(this.navigator.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 y=d.lastChild;y.style.backgroundColor=this.getColor()}if(o){let y=function(){i.doHighlight(!1,Ve.Highlight),i.toolboxHide(),o?.removeEventListener("click",y)},b=o.cloneNode(!0);o?.parentNode?.replaceChild(b,o),o=document.getElementById("highlightIcon"),o?.addEventListener("click",y)}if(l){let y=function(){i.doHighlight(!1,Ve.Underline),i.toolboxHide(),l?.removeEventListener("click",y)},b=l.cloneNode(!0);l?.parentNode?.replaceChild(b,l),l=document.getElementById("underlineIcon"),l?.addEventListener("click",y)}if(u){let y=function(){i.doHighlight(!1,Ve.Comment),i.toolboxHide(),u?.removeEventListener("click",y)},b=u.cloneNode(!0);u?.parentNode?.replaceChild(b,u),u=document.getElementById("noteIcon"),u?.addEventListener("click",y)}}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.navigator.rights.enableTTS){if(h){let y=function(){h?.removeEventListener("click",y),i.speak()},b=h.cloneNode(!0);h?.parentNode?.replaceChild(b,h),h=document.getElementById("speakIcon"),h?.addEventListener("click",y)}}else h&&h.style.setProperty("display","none");(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).forEach(y=>{y.icon&&(y.icon.id=y.id);let b=document.getElementById(y.id),w=this;function p(){b?.removeEventListener("click",p);function m(g){let v={className:C=>Ai.indexOf(C)<0,idName:C=>Ai.indexOf(C)<0},A=w.navigator.iframes[0].contentDocument;if(A)return wn(g,A,v)}let f=w.navigator.iframes[0].contentWindow;if(f){let g=Er(f,m);if(g===void 0){let v=w.navigator.iframes[0].contentDocument;g=w.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(v)}if(g!==void 0)if(y.callback)y.callback(g.cleanText,g.range?.startContainer.parentElement);else{let v=y.highlight?.style,A=y.marker?y.marker:Ve.Custom;if(A===Ve.Custom&&w.navigator.rights.enableAnnotations||A===Ve.Bookmark&&w.navigator.rights.enableBookmarks){let C=w.navigator.iframes[0].contentDocument;if(C){let O=w.createHighlight(w.dom(C.body).getWindow(),g,y.highlight?.color,!0,A,y.icon,y.popup,v);w.options.onAfterHighlight(O,A),w.navigator.rights.enableAnnotations?w.navigator.annotationModule?.saveAnnotation(O[0]).then(E=>{y?.note&&E.highlight&&w.navigator.annotationModule?.api?.addCommentToAnnotation(E).then(T=>{w.navigator.annotationModule?.updateAnnotation(T).then(async()=>{ni.default.log("update highlight "+T.id)})})}):w.navigator.rights.enableBookmarks&&w.navigator.bookmarkModule?.saveAnnotation(O[0])}}}}w.callbackComplete()}if(b){let m=b.cloneNode(!0);b?.parentNode?.replaceChild(m,b),b=document.getElementById(y.id),b?.addEventListener("click",p)}})}}doHighlight(t,n){let i=this;function o(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=i.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)}let a=i.navigator.iframes[0].contentWindow;if(a){let l=Er(a,o);if(l===void 0){let u=i.navigator.iframes[0].contentDocument;l=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(u)}if(l){if(this.options.onBeforeHighlight(l)===!0){let u;u=this.getColor(),Qe.isHexColor(u)&&(u=Qe.hexToRgbChannels(u));let d=i.navigator.iframes[0].contentDocument;if(d){let h=this.createHighlight(i.dom(d.body).getWindow(),l,u,!0,n??Ve.Highlight);this.options.onAfterHighlight(h,n),this.navigator.rights.enableAnnotations&&n!==Ve.Bookmark?this.navigator.annotationModule?.saveAnnotation(h[0]):this.navigator.rights.enableBookmarks&&n===Ve.Bookmark&&this.navigator.bookmarkModule?.saveAnnotation(h[0])}}t||this.dom(this.navigator.iframes[0].contentDocument?.body).removeAllRanges()}else t||this.dom(this.navigator.iframes[0].contentDocument?.body).removeAllRanges()}}speak(){if(this.navigator.rights.enableTTS){let n=function(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=t.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)},t=this,i=t.navigator.iframes[0].contentWindow;if(i){let l=Er(i,n);if(l===void 0){let u=t.navigator.iframes[0].contentDocument;l=t.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(u)}l!==void 0&&this.navigator.ttsModule.speak(l,!0,()=>{})}let o=t.navigator.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.navigator.rights.enableTTS&&this.doneSpeaking()}callbackComplete(){this.toolboxHide();let t=this.navigator.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges()}isOutsideViewport(t){let n=yt(document,"#iframe-wrapper"),i=n.scrollLeft,o=i+n.clientWidth,a=t.left+t.width,l=t.top+t.height,u=n.scrollTop,d=u+n.clientHeight,h=l<u,y=t.top>d,b=a<i,w=t.left>o;return h||y||b||w}isInsideViewport(t){let n=yt(document,"#iframe-wrapper"),i=n.scrollTop,o=i+n.clientHeight,a=t.top+20>=i,l=t.top<=o,u=n.scrollLeft,d=u+n.clientWidth,h=t.left+t.width,y=t.left>u,b=h<d;return a&&l&&y&&b}get visibleTextRects(){let t=this.navigator.iframes[0].contentDocument;if(t){let i=function(u,d=[]){let h=u.firstChild;for(;h;)h.nodeType===1&&i(h,d),h.nodeType===3&&h.textContent?.trim()&&d.push(h),h=h.nextSibling;return d},o=function(u){return i(u).map(h=>{let{top:y,height:b,left:w,width:p}=a(h);return{top:y,height:b,width:p,left:w,node:h,textContent:h.textContent??""}})},a=function(u){try{let d=document.createRange();d.selectNode(u);let h=d.getBoundingClientRect();return d.detach(),h}catch(d){ni.default.log("measureTextNode "+d),ni.default.log("measureTextNode "+u),ni.default.log(`${u.textContent}`)}},n=Gr(t,"body");return o(n).filter(u=>this.isInsideViewport(u))}return[]}doneSpeaking(t=!1){if(this.navigator.rights.enableTTS){this.toolboxHide();let n=this.navigator.iframes[0].contentDocument;n&&this.dom(n.body).removeAllRanges(),this.navigator.ttsModule.cancel(),t&&this.navigator.reload()}}normalizeHighlights(t){var n;return n=t.filter(function(i){return i.parentElement?i:null}),n=this.unique(n),n.sort(function(i,o){return i.offsetTop-o.offsetTop||i.offsetLeft-o.offsetLeft}),n}flattenNestedHighlights(t){let n,i=this;i.sortByDepth(t,!0);function o(){let a=!1;return t.forEach(function(l,u){let d=l.parentElement,h=d.previousSibling,y=d.nextSibling;i.isHighlight(d)&&(i.haveSameColor(d,l)?(d.replaceChild(l.firstChild,l),t[u]=d,a=!0):(l.nextSibling||(i.dom(l).insertBefore(y||d),a=!0),l.previousSibling||(i.dom(l).insertAfter(h||d),a=!0),d.hasChildNodes()||i.dom(d).remove()))}),a}do n=o();while(n)}mergeSiblingHighlights(t){let n=this;function i(o,a){return a&&a.nodeType===ha.ELEMENT_NODE&&n.haveSameColor(o,a)&&n.isHighlight(a)}t.forEach(function(o){let a=o.previousSibling,l=o.nextSibling;i(o,a)&&(n.dom(o).prepend(a.childNodes),n.dom(a).remove()),i(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===ha.ELEMENT_NODE&&t.hasAttribute(V5)}createWrapper(){let t=document.createElement("mark");return t.style.background="linear-gradient("+Qe.hexToRgbA(this.options.color)+", "+Qe.hexToRgbA(this.options.color)+")",t.className=this.options.highlightedClass,t}static isHexColor(t){return/^#([A-Fa-f0-9]{3}){1,2}$/.test(t)}static hexToRgbString(t){let n;return n=t.substring(1).split(""),n.length===3&&(n=[n[0],n[0],n[1],n[1],n[2],n[2]]),n="0x"+n.join(""),n}static hexToRgbChannels(t){let n;if(this.isHexColor(t))return n=this.hexToRgbString(t),{red:n>>16&255,green:n>>8&255,blue:n&255};throw new Error("Bad Hex")}static hexToRgbA(t){let n;if(this.isHexColor(t))return n=this.hexToRgbChannels(t),"rgba("+[n.red,n.green,n.blue].join(",")+",.5)";if(typeof t=="object"){let i=t;return"rgba("+[i.red,i.green,i.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(t,n){let i;if(this.isHexColor(t))return i=this.hexToRgbChannels(t),"rgba("+[i.red,i.green,i.blue].join(",")+","+n+")";if(typeof t=="object"){let o=t;return"rgba("+[o.red,o.green,o.blue].join(",")+","+n+")"}throw new Error("Bad Hex")}resetHighlightBoundingStyle(t){t.style.outline="none",t.style.setProperty("background-color","transparent","important")}resetHighlightAreaStyle(t,n){let i=this.navigator.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=tn.find(l=>l.id===o);if(a){if(a.marker===Ve.Custom||a.marker===Ve.Bookmark)if(a.style?.hover){if(a.style?.hover)for(let d=0;d<a.style?.hover?.length;d++){let h=a.style?.hover[d];t.style.removeProperty(h.property)}let u="";if(a.style?.default)for(let d=0;d<a.style?.default?.length;d++){let h=a.style?.default[d];t.style.removeProperty(h.property),u+=`${h.property}: ${h.value} !${h.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(Qe.isHexColor(a.color)){let u=Qe.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===Ve.Underline||a.marker===Ve.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(Qe.isHexColor(a.color)){let u=Qe.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}, ${_r})`,"important")}else if(Qe.isHexColor(a.color)){let u=Qe.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${_r})`,"important")}else t.classList.remove("hover");let l;if(i){let u=i.getElementById(n);u&&(l=u.querySelector(`#${a.id}`))}if(l){let u=l.getElementsByClassName(Al);if(u.length>0){let d=u.item(0).getElementsByClassName("icon-tooltip");d.length>0&&d.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(t,n,i){for(let o of n){if(i.marker===Ve.Custom||i.marker===Ve.Bookmark)if(i.style?.hover){if(i.style?.default)for(let l=0;l<i.style?.default?.length;l++){let u=i.style?.default[l];o.style.removeProperty(u.property)}let a="";for(let l=0;l<i.style?.hover?.length;l++){let u=i.style?.hover[l];o.style.removeProperty(u.property),a+=`${u.property}: ${u.value} !${u.priority};`}o.setAttribute("style",`${o.getAttribute("style")}; ${a}`)}else if(i.style?.hoverClass){i.style?.defaultClass&&o.classList.remove(i.style?.defaultClass);let a="";o.classList.add(i.style?.hoverClass),o.setAttribute("style",`${o.getAttribute("style")}; ${a}`)}else if(Qe.isHexColor(i.color)){let a=Qe.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important")}else o.classList.add("hover");else if(i.marker===Ve.Underline||i.marker===Ve.Comment)if(typeof i.color=="object"){let a=i.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(Qe.isHexColor(i.color)){let a=Qe.hexToRgbChannels(i.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 i.color=="object"){let a=i.color;o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${F_})`,"important")}else if(Qe.isHexColor(i.color)){let a=Qe.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${F_})`,"important")}else o.classList.add("hover");if(i.type!==it.Definition){let l=t.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER).querySelector(`#${i.id}`).getElementsByClassName(Al);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 i=this.navigator.iframes[0].contentWindow?.document,o=Array.from(i.getElementById(qe.R2_ID_SEARCH_CONTAINER).querySelectorAll(`.${Tn}`));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 b=d.color;l.style.setProperty("background-color",`rgba(${b.red}, ${b.green}, ${b.blue}, ${_r})`,"important")}else if(Qe.isHexColor(d.color)){let b=Qe.hexToRgbChannels(d.color);l.style.setProperty("background-color",`rgba(${b.red}, ${b.green}, ${b.blue}, ${_r})`,"important")}else l.classList.remove("hover");let y=i.getElementById(qe.R2_ID_SEARCH_CONTAINER).querySelector(`#${d.id}`).getElementsByClassName(Al);if(y.length>0){let b=y.item(0).getElementsByClassName("icon-tooltip");b.length>0&&b.item(0).style.removeProperty("display")}}}),u===t.id&&t){if(typeof t.color=="object"){let y=t.color;l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${_r})`,"important")}else if(Qe.isHexColor(t.color)){let y=Qe.hexToRgbChannels(t.color);l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${_r})`,"important")}else l.classList.remove("hover");let h=i.getElementById(qe.R2_ID_SEARCH_CONTAINER).querySelector(`#${t.id}`).getElementsByClassName(Al);if(h.length>0){let y=h.item(0).getElementsByClassName("icon-tooltip");y.length>0&&y.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.navigator.iframes[0].contentWindow?.document,i=t.clientX,o=t.clientY;if(!n||!n.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER)&&!n.getElementById(qe.R2_ID_SEARCH_CONTAINER)&&!n.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER)&&!n.getElementById(qe.R2_ID_READALOUD_CONTAINER)&&!n.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER))return;let a=this.navigator.view?.isPaginated(),l=n.body.getBoundingClientRect(),u=this.getScrollingElement(n),d=a?-u.scrollLeft:l.left,h=a?-u.scrollTop:l.top,y,b;for(let w=tn.length-1;w>=0;w--){let p=tn[w],m=n.getElementById(`${p.id}`);if(!m){let v=n.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER);v&&(m=v.querySelector(`#${p.id}`))}if(!m)continue;let f=!1,g=m.querySelectorAll(`.${Tn}`);for(let v of g){let A=v,C=A.rect.left+d,O=A.rect.top+h;if(i>=C&&i<C+A.rect.width&&o>=O&&o<O+A.rect.height){f=!0;break}}if(f){y=p,b=m;break}}if(!y||!b){for(let w in qe){let p=n.getElementById(w);if(p){let m=p.querySelectorAll(`.${Sl}`);for(let g of m)this.resetHighlightBoundingStyle(g);let f=Array.from(p.querySelectorAll(`.${Tn}`));for(let g of f)this.resetHighlightAreaStyle(g,w)}}return}if(b.getAttribute("data-click")){if((t.type==="mousemove"||t.type==="touchmove")&&b.parentElement?.style.display!=="none"){let w=Array.from(b.querySelectorAll(`.${Tn}`));for(let m in qe){let f=n.getElementById(m);if(f){let g=f.querySelectorAll(`.${Tn}`);for(let v of g)w.indexOf(v)<0&&this.resetHighlightAreaStyle(v,m)}}this.setHighlightAreaStyle(n,w,y);let p=b.querySelector(`.${Sl}`);for(let m in qe){let f=n.getElementById(m);if(f){let g=f.querySelectorAll(`.${Sl}`);for(let v of g)(!p||v!==p)&&this.resetHighlightBoundingStyle(v)}}}else if((t.type==="mouseup"||t.type==="click"||t.type==="touchup")&&b.parentElement?.style.display!=="none"){let w={highlight:y};ni.default.log(JSON.stringify(w));let p=this,m;if(p.navigator.rights.enableAnnotations?m=await this.navigator.annotationModule?.getAnnotation(w.highlight):p.navigator.rights.enableBookmarks&&(m=await this.navigator.bookmarkModule?.getAnnotation(w.highlight)),w.highlight.type===it.Annotation&&this.navigator.annotationModule?.api?.selectedAnnotation(m).then(async()=>{}),m?.id){ni.default.log("selected highlight "+m.id),p.lastSelectedHighlight=m.id;let f=document.getElementById("highlight-toolbox");if(f)if(f.style.top=t.clientY+(this.navigator.attributes?.navHeight??0)+"px",f.style.left=t.clientX+"px",getComputedStyle(f).display==="none"){let A=function(){p.navigator.annotationModule?.api?.addCommentToAnnotation(m).then(M=>{p.navigator.annotationModule?.updateAnnotation(M).then(async()=>{ni.default.log("update highlight "+M.id),f&&(f.style.display="none"),p.selectionMenuClosed()}),f&&(f.style.display="none"),p.selectionMenuClosed(),C?.removeEventListener("click",A,!1)})},E=function(){p.navigator.rights.enableAnnotations?p.navigator.annotationModule?.deleteSelectedHighlight(m).then(async()=>{ni.default.log("delete highlight "+m.id),f&&(f.style.display="none"),p.selectionMenuClosed()}):p.navigator.rights.enableBookmarks&&p.navigator.bookmarkModule?.deleteSelectedHighlight(m).then(async()=>{ni.default.log("delete highlight "+m.id),f&&(f.style.display="none"),p.selectionMenuClosed()})};f.style.display="block",this.toolboxMode("edit");let g=document.getElementById("colorIcon"),v=document.getElementById("highlightIcon");g&&(g.style.display="none"),v&&(v.style.display="none");let C=document.getElementById("commentIcon"),O=document.getElementById("cloneCommentIcon");if(O){let M=O.parentElement;M&&M.removeChild(O)}if(C){C.style.display="none";let M=C.cloneNode(!0),D=C.parentElement;M.style.display="unset",M.id="cloneCommentIcon",M.addEventListener("click",A,!1),D&&D.append(M)}let T=document.getElementById("deleteIcon"),B=document.getElementById("cloneDeleteIcon");if(B){let M=B.parentElement;M&&M.removeChild(B)}if(T){T.style.display="none";let M=T.cloneNode(!0),D=T.parentElement;M.style.display="unset",M.id="cloneDeleteIcon",M.addEventListener("click",E,!1),D&&D.append(M)}}else f.style.display="none",this.selectionMenuClosed(),f.offsetWidth,f.style.display="block"}else{b.dataset.definition&&new wl(this.navigator).showPopup(b.dataset.definition,t);let f=this.navigator.definitionsModule?.properties?.definitions?.filter(g=>g.order===Number(b?.dataset.order))[0];ni.default.log(f),this.navigator.definitionsModule?.api?.click&&(this.navigator.definitionsModule.api?.click(N0.omit(f,"callbacks"),N0.omit(y,"definition")),this.navigator.emit("definition.click",f,y))}}}}async prepareContainers(t){for(let n in qe)await this.ensureHighlightsContainer(t,n)}async ensureHighlightsContainer(t,n){let i=t.document;if(!i.getElementById(n)){let o=i.createElement("div");o.setAttribute("id",n),n!==qe.R2_ID_GUTTER_RIGHT_CONTAINER&&o.style.setProperty("pointer-events","none"),this.navigator.view?.layout==="fixed"&&(o.style.setProperty("position","absolute"),o.style.setProperty("top","0"),o.style.setProperty("left","0")),i.body&&i.body.append(o),(await this.layerSettings.getProperty(n))?.value===!1&&(o.style.display="none")}return i.getElementById(n)}hideAllhighlights(t){this.removeAllChildNodes(t.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_SEARCH_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_READALOUD_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER))}destroyAllhighlights(t){this.hideAllhighlights(t),tn.splice(0,tn.length)}removeAllChildNodes(t){for(;t.firstChild;)t.removeChild(t.firstChild)}destroyHighlights(t){let n=this.navigator.iframes[0].contentWindow?.document;if(n){let i;switch(t){case it.ReadAloud:i=n.getElementById(qe.R2_ID_READALOUD_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.Search:i=n.getElementById(qe.R2_ID_SEARCH_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.PageBreak:i=n.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.Definition:i=n.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.LineFocus:i=n.getElementById(qe.R2_ID_LINEFOCUS_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.Comment:i=n.getElementById(qe.R2_ID_GUTTER_RIGHT_CONTAINER),i&&this.removeAllChildNodes(i);break;default:i=n.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER),i&&this.removeAllChildNodes(i),tn.splice(0,tn.length);break}}}destroyHighlight(t,n){if(!t)return;let i=-1;tn.find((l,u)=>(i=u,l.id===n))&&i>=0&&i<tn.length&&tn.splice(i,1);let a=t.getElementById(n);a&&this.removeAllChildNodes(a)}createHighlight(t,n,i,o,a,l,u,d,h,y){try{let b=`${n.rangeInfo.startContainerElementCssSelector}${n.rangeInfo.startContainerChildTextNodeIndex}${n.rangeInfo.startOffset}${n.rangeInfo.endContainerElementCssSelector}${n.rangeInfo.endContainerChildTextNodeIndex}${n.rangeInfo.endOffset}`,w=Fi.hash(b),p=(y||"R2_HIGHLIGHT_")+w;this.destroyHighlight(t.document,p);let m=`rgb(${ls.red}, ${ls.green}, ${ls.blue})`,f={color:i||m,id:p,pointerInteraction:o,selectionInfo:n,marker:a,icon:l,popup:u,style:d,type:h||it.Annotation};(h===it.Annotation||h===it.Definition||h===void 0)&&tn.push(f);let g=this.createHighlightDom(t,f);return f.position=parseInt((g?.hasChildNodes()?g.childNodes[0]:g).style.top.replace("px","")),[f,g]}catch(b){throw"Can't create highlight: "+b}}createHighlightDom(t,n){let i=t.document,o=Vd(i,n.selectionInfo.rangeInfo);if(!o)return;for(let N in qe)this.ensureHighlightsContainer(t,N);let a=i.createElement("div");a.setAttribute("id",n.id),a.setAttribute("class",j_),a.style.setProperty("pointer-events","none"),n.pointerInteraction&&a.setAttribute("data-click","1");let l=this.navigator.view?.isPaginated();l?i.body.style.position="revert":i.body.style.position="relative";let u=i.body.getBoundingClientRect(),d=this.getScrollingElement(i),h=l?-d.scrollLeft:u.left,y=l?-d.scrollTop:u.top,b=1,w=!1,p=!1,g=Gd(o,w||p||!1),v=3,A=2,C=3,O=0,E=24,T,B;for(let N of g){let q=i.createElement("div");q.setAttribute("class",Tn),q.dataset.marker=""+n.marker;let z="";if(w&&n.marker!==Ve.Custom&&n.marker!==Ve.Bookmark&&n.marker!==Ve.Comment){let x=n.color;Qe.isHexColor(x)&&(x=Qe.hexToRgbChannels(x)),z+=`border-bottom: ${A*b}px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${_r}) !important`}if(n.marker===Ve.Custom||n.marker===Ve.Bookmark)if(n.style?.default){for(let x=0;x<n.style?.default?.length;x++){let R=n.style?.default[x];z+=`${R.property}: ${R.value} !${R.priority};`}q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; ${z}`)}else n.style?.defaultClass&&(q.classList.add(n.style?.defaultClass),q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; ${z}`));else if(n.marker===Ve.Underline||n.marker===Ve.Comment)if(typeof n.color=="object"){let x=n.color;q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${0}) !important; ${z}`),q.style.setProperty("border-bottom",`2px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${1})`,"important")}else if(Qe.isHexColor(n.color)){let x=Qe.hexToRgbChannels(n.color);q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${0}) !important; ${z}`),q.style.setProperty("border-bottom",`2px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${1})`,"important")}else q.setAttribute("style",`border-radius: ${v}px !important; ${z}`);else if(typeof n.color=="object"){let x=n.color;q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${_r}) !important; ${z}`)}else if(Qe.isHexColor(n.color)){let x=Qe.hexToRgbChannels(n.color);q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${_r}) !important; ${z}`)}else q.setAttribute("style",`border-radius: ${v}px !important; ${z}`);q.style.setProperty("pointer-events","none"),q.style.position="absolute",q.scale=b,q.rect={height:N.height,left:N.left-h,top:N.top-y,width:N.width},n.pointerInteraction&&(q.setAttribute("data-click","1"),q.tabIndex=0),q.style.width=`${q.rect.width*b}px`,q.style.height=`${q.rect.height*b}px`,q.style.left=`${q.rect.left*b}px`,q.style.top=`${q.rect.top*b}px`,a.append(q);let ne=parseInt(q.style.top.replace("px",""));if((ne<O||O===0)&&(O=ne),E=parseInt(q.style.height.replace("px","")),p){let x=i.createElement("div");x.setAttribute("class",Tn);let R=n.color;Qe.isHexColor(R)&&(R=Qe.hexToRgbChannels(R)),x.setAttribute("style",`background-color: rgba(${R.red}, ${R.green}, ${R.blue}, ${_r}) !important;`),x.style.setProperty("pointer-events","none"),x.style.position="absolute",x.scale=b,x.rect={height:N.height,left:N.left-h,top:N.top-y,width:N.width},x.style.width=`${x.rect.width*b}px`,x.style.height=`${C*b}px`,x.style.left=`${x.rect.left*b}px`,x.style.top=`${(x.rect.top+x.rect.height/2-C/2)*b}px`,a.append(x)}let oe=this.navigator.iframes[0].contentWindow?.innerWidth,ae=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-count")),te=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-width")),le=parseInt(getComputedStyle(i.body).getPropertyValue("padding-left")),xe=oe/(ae||1);xe<te&&(xe=oe),l||(xe=parseInt(getComputedStyle(i.body).width.replace("px","")));let fe=this.navigator.settings.fontSize/100,J=20*fe;fe<=1&&(J=-60);let j=0*fe;fe<=1&&(j=-60),T=Math.floor(N.left/xe)*xe+xe-(E<40?40:E)+j,B=Math.floor(N.left/xe)*xe+(E<40?40:E)-J;let k=parseInt(this.navigator.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));k>=2&&(B=B+le/ae,T=T-le/ae),l||(T=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px","")),B=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px",""))-xe,k>=2&&(B=B+le/2,T=T-le/2))}let M=o.getBoundingClientRect(),D=i.createElement("div");D.setAttribute("class",Sl),D.style.setProperty("pointer-events","none"),D.style.position="absolute",D.scale=b,D.rect={height:M.height,left:M.left-h,top:M.top-y,width:M.width},D.style.width=`${D.rect.width*b}px`,D.style.height=`${D.rect.height*b}px`,D.style.left=`${D.rect.left*b}px`,D.style.top=`${D.rect.top*b}px`,a.append(D);let U=i.createElement("div");if(U.setAttribute("class",Al),n.icon?.position==="left")U.setAttribute("style",`position: absolute;top:${O}px;left:${B+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`);else if(n.icon?.position==="inline")U.setAttribute("style",`position: absolute;top:${O-E/2}px;left:${parseInt(D.style.left.replace("px",""))+parseInt(D.style.width.replace("px",""))-E/2}px;height:${E}px; width:${E}px;`);else if(n.icon?.position==="center"){let q=E/3*2;U.setAttribute("style",`position: absolute;top:${O}px;left:${parseInt(D.style.left.replace("px",""))+parseInt(D.style.width.replace("px",""))-q}px;height:${E}px; width:${E}px;`)}else n.note&&n.marker!==Ve.Custom&&n.marker!==Ve.Bookmark&&n.marker!==Ve.Comment&&n.marker!==Ve.Highlight&&n.marker!==Ve.Underline?U.setAttribute("style",`position: absolute;top:${O-E/2}px;left:${parseInt(D.style.left.replace("px",""))+parseInt(D.style.width.replace("px",""))-E/2}px;height:${E}px; width:${E}px;`):n.note&&n.marker===Ve.Comment||n.marker===Ve.Highlight||n.marker===Ve.Underline?U.setAttribute("style",`position: absolute;top:${O}px;left:${T+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`):U.setAttribute("style",`position: absolute;top:${O}px;left:${T+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`);if(n.marker===Ve.Custom||n.marker===Ve.Bookmark)n.icon?.class?(U.classList.add(n.icon?.class),U.id=n.icon?.id):n.icon?.svgPath?U.innerHTML=ua(`${n.icon?.id}`,`${n.icon?.title}`,`${n.icon?.svgPath}`,"icon open",E,`${n.icon?.color} !important`):n.icon?.title&&(U.innerHTML=n.icon?.title);else if(n.note){let N=n.color;Qe.isHexColor(N)&&(N=Qe.hexToRgbChannels(N)),n.marker===Ve.Comment||n.marker===Ve.Highlight||n.marker===Ve.Underline?U.innerHTML=ua("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",E/2,`rgba(${N.red}, ${N.green}, ${N.blue}, 1) !important`):U.innerHTML=ua("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",E,`rgba(${N.red}, ${N.green}, ${N.blue}, 1) !important`)}U.style.setProperty("pointer-events","all");let I=this;if(n.type!==it.PageBreak&&n.type!==it.Definition&&U.addEventListener("click",async function(N){let q;I.navigator.rights.enableAnnotations?(q=await I.navigator.annotationModule?.getAnnotationByID(n.id),I.navigator.annotationModule?.api?.selectedAnnotation(q).then(async()=>{})):I.navigator.rights.enableBookmarks&&(q=await I.navigator.bookmarkModule?.getAnnotationByID(n.id)),ni.default.log("selected highlight "+q.id),I.lastSelectedHighlight=q.id;let z=document.getElementById("highlight-toolbox");if(z)if(z.style.top=N.clientY+(I.navigator.attributes?.navHeight??0)+"px",z.style.left=N.clientX+"px",getComputedStyle(z).display==="none"){let xe=function(){I.navigator.rights.enableAnnotations?I.navigator.annotationModule?.deleteSelectedHighlight(q).then(async()=>{ni.default.log("delete highlight "+q.id),z.style.display="none",I.selectionMenuClosed()}):I.navigator.rights.enableBookmarks&&I.navigator.bookmarkModule?.deleteSelectedHighlight(q).then(async()=>{ni.default.log("delete highlight "+q.id),z.style.display="none",I.selectionMenuClosed()})};z.style.display="block",I.toolboxMode("edit");let oe=document.getElementById("colorIcon"),ae=document.getElementById("highlightIcon");oe&&(oe.style.display="none"),ae&&(ae.style.display="none");let te=document.getElementById("commentIcon"),le=document.getElementById("cloneCommentIcon");if(le){let j=le.parentElement;j&&j.removeChild(le)}te&&(te.style.display="none");let fe=document.getElementById("deleteIcon"),J=document.getElementById("cloneDeleteIcon");if(J){let j=J.parentElement;j&&j.removeChild(J)}if(fe){fe.style.display="none";let j=fe.cloneNode(!0),k=fe.parentElement;j.style.display="unset",j.id="cloneDeleteIcon",j.addEventListener("click",xe,!1),k&&k.append(j)}}else z.style.display="none",I.selectionMenuClosed(),z.offsetWidth,z.style.display="block";let ne=Array.from(a.querySelectorAll(`.${Tn}`));I.setHighlightAreaStyle(i,ne,n)}),n.note){let N=document.createElement("span");N.innerHTML=n.note,N.className="icon-tooltip",n.marker===Ve.Custom||n.marker===Ve.Bookmark?(n.popup?.background&&N.style.setProperty("background",n.popup.background),n.popup?.textColor&&N.style.setProperty("color",n.popup.textColor),n.popup?.class&&N.classList.add(n.popup.class)):(N.style.setProperty("background","lightyellow"),N.style.setProperty("color","black"))}switch((n.note||n.marker===Ve.Custom||n.marker===Ve.Bookmark)&&a.append(U),n.type){case it.Search:i.getElementById(qe.R2_ID_SEARCH_CONTAINER).append(a);break;case it.ReadAloud:i.getElementById(qe.R2_ID_READALOUD_CONTAINER).append(a);break;case it.PageBreak:i.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER).append(a);break;case it.Definition:i.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER).append(a);break;default:i.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER).append(a);break}return a}addSelectionMenuItem(t){(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).push(t)}};var X_=nt(J0());H();var i8=nt(Jt());var Co={className:r=>!0,idName:r=>!0,tagName:r=>!0};var Z_=nt(Kd()),Ui=nt(Jt());H();var Y_=nt(Jt()),cs;(function(n){n.BookmarkCreated="BookmarkCreated",n.HighlightCreated="HighlightCreated"})(cs||(cs={}));var Cl=class{constructor(t,n,i){this.currSeconds=0;this.publication=t,this.properties=n,this.api=i}static async create(t){let n=new this(t.publication,t,t.api);return await n.start(),n}async start(){this.startResearchSession()}async stop(){Y_.default.log("Consumption module stop"),this.endResearchSession()}initialize(){let t=this.navigator.iframes[0].contentWindow;if(t){let n=this;t.onload=function(){n.resetTimer()},t.onmousemove=function(){n.resetTimer()},t.onmousedown=function(){n.resetTimer()},t.ontouchstart=function(){n.resetTimer()},t.onclick=function(){n.resetTimer()},t.onkeypress=function(){n.resetTimer()}}}trackAction(t,n){this.api?.actionTracked(t,n)}startReadingSession(t){if(this.firstReadingLocator&&this.lastReadingLocator){let n=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,i=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:i,progress:Math.round(n*100)})}this.firstReadingLocator=t,this.startReadingTimer=new Date}continueReadingSession(t){this.properties.enableTrackingSession&&(this.startResearchTimer===void 0&&this.startResearchSession(),(this.lastReadingLocator===void 0||this.lastReadingLocator.locations.totalProgression<t.locations.totalProgression)&&(this.lastReadingLocator=t),this.firstReadingLocator===void 0&&(this.firstReadingLocator=t),this.startReadingTimer===void 0&&(this.startReadingTimer=new Date))}startResearchSession(){if(this.properties.enableTrackingSession){this.startResearchTimer=new Date,this.readingSessions=[],clearInterval(this.readingSessionsInterval);let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.researchSessionId=this.api?.startResearchSession(this.readingSessions,Math.round(t));let n=this;this.readingSessionsInterval=setInterval(function(){n.updateResearchSession()},this.properties.updateSessionInterval*1e3)}}updateResearchSession(){if(this.properties.enableTrackingSession){let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.api?.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(t))}}endResearchSession(){if(this.properties.enableTrackingSession){if(this.firstReadingLocator&&this.lastReadingLocator){let n=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,i=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:i,progress:Math.round(n*100)})}let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.api?.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(t)),this.api?.endResearchSession(this.researchSessionId,this.readingSessions,Math.round(t)),this.researchSessionId=void 0,this.readingSessions=[],this.startResearchTimer=void 0,clearInterval(this.readingSessionsInterval),clearInterval(this.timer)}}startIdleTimer(){this.currSeconds++,this.currSeconds===this.properties.idleTimeout&&(this.api?.idleSince(this.currSeconds),this.startResearchTimer!==void 0?this.updateResearchSession():this.startResearchSession()),this.currSeconds===this.properties.idleTimeout+this.properties.responseTimeout&&this.endResearchSession()}resetTimer(){clearInterval(this.timer),this.currSeconds=0;let t=this;this.timer=setInterval(function(){t.startIdleTimer()},1e3)}};var us=class{constructor(t,n,i,o,a,l,u,d){this.hide=Ie(document,"#menu-button-hide");this.show=Ie(document,"#menu-button-show");this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=d,this.initialAnnotations=o,this.highlighter=l,this.properties=a,this.api=u}static async create(t){let n=new this(t.annotator,t.rights||{enableAnnotations:!1,enableTTS:!1},t.publication,t.initialAnnotations||null,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){Ui.default.log("Annotation module stop")}async start(){if(this.headerMenu&&(this.highlightsView=Ie(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var t=this.initialAnnotations.highlights||null;t&&this.annotator?.initAnnotations(t)}setTimeout(()=>{this.properties?.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)}hideAnnotationLayer(){let t=this.navigator.iframes[0].contentDocument;if(t){let n=Ie(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.navigator.iframes[0].contentDocument;if(t){let n=Ie(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(),Ee(this.navigator.iframes[0].contentDocument?.body,"click",this.click.bind(this))},300),t(null)})}click(t){if(this.activeAnnotationMarkerId){let n=this.highlighter?.properties?.selectionMenuItems?.filter(i=>i.id===this.activeAnnotationMarkerId);if(n&&n?.length>0){let i=Z_.cloneDeep(n[0]);i.marker=Ve.Custom,this.activeAnnotationMarkerPosition&&(i.icon.position=this.activeAnnotationMarkerPosition),i.highlight.style.default=null,i.highlight.style.hover=null;let o=this.navigator.iframes[0].contentDocument;if(o){let h=function(b){try{let w=d.navigator.iframes[0].contentDocument;return w?wn(b,w,Co):""}catch(w){return Ui.default.log("uniqueCssSelector:"),Ui.default.error(w),""}},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,y=Xr(l,h);if(a.removeAllRanges(),y){let b={rangeInfo:y},w=this.navigator.highlighter?.createHighlight(this.navigator.highlighter?.dom(o.body).getWindow(),b,i.highlight.color,!0,Ve.Bookmark,i.icon,i.popup,i.highlight.style);w&&this.saveAnnotation(w[0]).then(p=>{Ui.default.log("saved bookmark "+p.id)})}o.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(t){Ui.default.log("still need to scroll to "+t);var n=await this.annotator?.getAnnotationElement(t,this.navigator.iframes[0].contentWindow);n.scrollIntoView({block:"center",behavior:"smooth"})}async updateLocalHighlight(t){if(this.annotator){let n=await this.annotator.deleteAnnotation(t.id),i=await this.addAnnotation(t);return Ui.default.log("Highlight deleted "+JSON.stringify(n)),Ui.default.log("Highlight added "+JSON.stringify(i)),await this.showHighlights(),await this.drawHighlights(),i}else return new Promise(n=>n(null))}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return Ui.default.log("Highlight deleted "+JSON.stringify(n)),await this.showHighlights(),await this.drawHighlights(),n}else return new Promise(i=>i(null))}async deleteAnnotation(t){await this.deleteLocalHighlight(t.id)}async addAnnotation(t){await this.annotator?.saveAnnotation(t),await this.showHighlights(),await this.drawHighlights()}async deleteHighlight(t){this.api?.deleteAnnotation?this.api?.deleteAnnotation(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteSelectedHighlight(t){this.api?.deleteAnnotation?this.api.deleteAnnotation(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async updateAnnotation(t){this.api?.updateAnnotation?this.api.updateAnnotation(t).then(async()=>{this.updateLocalHighlight(t)}):this.updateLocalHighlight(t)}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(n=this.publication.getTOCItem(this.navigator.currentTocUrl)),n===void 0&&(n=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let i=this.navigator.view?.getCurrentPosition(),o=this.navigator.iframes[0].contentDocument;if(o){let a=Gr(o,"body"),l=t.position?t.position/a.scrollHeight:i,u=(0,X_.v4)(),d;if(n){let h=n.Href;if(h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let y=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),b=Math.ceil((l??0)*(y.length-1)),w=y[b];d=Yt(et({},w),{id:u,href:h,created:new Date,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else d={id:u,href:h,locations:{progression:l},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(d)if(this.navigator.consumptionModule?.trackAction(d,cs.HighlightCreated),this.api?.addAnnotation)try{let h=await this.api.addAnnotation(d),y=await this.annotator.saveAnnotation(h);return await this.showHighlights(),await this.drawHighlights(),new Promise(b=>b(y))}catch(h){await this.showHighlights(),await this.drawHighlights()}else{let h=await this.annotator.saveAnnotation(d);return await this.showHighlights(),await this.drawHighlights(),new Promise(y=>y(h))}}}return new Promise(i=>i(null))}getAnnotations(){let t=[];return this.annotator&&(t=this.annotator.getAnnotations()),t}showHighlights(){let t=[];this.annotator&&(t=this.annotator.getAnnotations(),t&&(t=t.filter(n=>n.highlight.marker!==Ve.Bookmark),t.forEach(n=>{tn.push(n.highlight)}))),this.highlightsView&&this.createTree(Si.Annotation,t,this.highlightsView)}async drawHighlights(){if(this.rights.enableAnnotations&&this.highlighter){if(this.api){let n=[];if(this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href;var t=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===Ve.Underline){let u=await this.annotator?.getAnnotationPosition(i.id,this.navigator.iframes[0].contentWindow),d='<div class="comment" style="top: '+u+'px;width:20px"></div>',h=document.createElement("div");h.innerHTML=d;let y=h.childNodes[0],b=document.createElement("i");b.innerHTML="sticky_note_2",b.className="material-icons",b.style.color=o.highlight.color,y.appendChild(b),Ee(h,"click",w=>{w.preventDefault(),w.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}else{let n=[];if(this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href,l=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl&&(l=this.publication.getTOCItem(this.navigator.currentTocUrl)),l===null&&(l=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),l){let u=l.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),o.href===u&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===Ve.Underline){let d=await this.annotator?.getAnnotationPosition(i.id,this.navigator.iframes[0].contentWindow),h='<div class="comment" style="top: '+d+"px;background: "+o.highlight?.color+';width:20px"></div>',y=document.createElement("div");y.innerHTML=h,y.childNodes[0].innerHTML=nr.note,Ee(y,"click",b=>{b.preventDefault(),b.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){let t=this.navigator.iframes[0].contentDocument;if(t&&(this.commentGutter=t.getElementById(qe.R2_ID_GUTTER_RIGHT_CONTAINER),this.navigator.view?.isScrollMode()&&this.properties?.enableComments?this.commentGutter?.style.removeProperty("display"):this.commentGutter?.style.setProperty("display","none"),this.commentGutter&&this.navigator.view?.isScrollMode()&&this.properties?.enableComments)){this.commentGutter.innerHTML="";let n=[];this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href),n&&(n=n.filter(i=>i.highlight?.note?.length>0),n=this.syncPosition(n),n=this.reposition(n),n.forEach(i=>{let o=document.createElement("i");o.innerHTML="sticky_note_2",o.className="material-icons",o.style.color=i.highlight.color;let a=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),l,u;a&&(l=a.querySelector(`#${i.highlight.id}`)),u=l.getElementsByClassName(Tn)[0];let h=parseInt(u.style.height.replace("px","")),y=i.highlight.position,b=t.createElement("div");b.setAttribute("style",`position: absolute;top:${y}px;display: flex;max-width: 250px !important;height:${h}px;width: 200px;align-items: center;`);let w=t.createElement("div");b.appendChild(w);let p=i.highlight.color;Qe.isHexColor(p)&&(p=Qe.hexToRgbChannels(p)),b.innerHTML=ua("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="8"/>',"icon open",10,`rgba(${p.red}, ${p.green}, ${p.blue}, 1) !important`);let m=t.createElement("div");m.innerHTML=i.highlight?.note,m.setAttribute("style",`height:${h}px;overflow: hidden;padding-left: 5px;`),b.appendChild(m),Ee(b,"click",f=>{f.preventDefault(),f.stopPropagation(),this.scrollToHighlight(i.highlight.id)}),this.commentGutter?.appendChild(b)})))}}createTree(t,n,i){if(n){let o=this,a=this.publication.readingOrder;if(a.length){let l=(u,d)=>{let h=document.createElement("ul");h.className="sidenav-annotations";for(let y of d){let b=document.createElement("li"),w=document.createElement("a"),p=document.createElement("span");if(w.tabIndex=-1,w.className="chapter-link",y.Href){let f=this.publication.getAbsoluteHref(y.Href),g=this.publication.getTOCItemAbsolute(f);w.href=f,w.innerHTML=g?.Title||"",b.appendChild(w)}else p.innerHTML=y.Title||"",p.className="chapter-title",b.appendChild(p);Ee(w,"click",f=>{f.preventDefault(),f.stopPropagation();let g={href:w.href,locations:{progression:0},type:y.TypeLink,title:w.title};this.navigator.stopReadAloud(),this.navigator.navigate(g)});let m=document.createElement("ol");n.forEach(function(f){let g=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&f.href.endsWith(g)){let v=document.createElement("li");v.className="annotation-item";let A=document.createElement("a");if(A.setAttribute("href",f.href),t===Si.Annotation){A.className="highlight-link";let O=document.createElement("span"),E=document.createElement("span");if(O.className="title",E.innerHTML=f.highlight.selectionInfo.cleanText,f.highlight?.marker===Ve.Underline)if(typeof f.highlight?.color=="object"){let M=f.highlight?.color;M&&E.style.setProperty("border-bottom",`2px solid ${Qe.hexToRgbA(M)}`,"important")}else E.style.setProperty("border-bottom",`2px solid ${f.highlight?.color}`,"important");else if(typeof f.highlight?.color=="object"){let M=f.highlight?.color;M&&(E.style.backgroundColor=Qe.hexToRgbA(M))}else{let M=f.highlight?.color;M&&(E.style.backgroundColor=M)}O.appendChild(E),A.appendChild(O);let T=document.createElement("span"),B=Math.round((f.locations.progression??0)*100)+"% through resource";T.className="subtitle",T.innerHTML=B,A.appendChild(T)}let C=document.createElement("span");if(C.className="timestamp",C.innerHTML=us.readableTimestamp(f.created),A.appendChild(C),Ee(A,"click",O=>{O.preventDefault(),O.stopPropagation(),o.handleAnnotationLinkClick(O,f)}),v.appendChild(A),o.navigator.sideNavExpanded){let O=document.createElement("button");O.className="delete",O.innerHTML=nr.delete,Ee(O,"click",E=>{E.preventDefault(),E.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,E,f)}),v.appendChild(O)}m.appendChild(v)}}),m.children.length>0&&(h.appendChild(b),h.appendChild(m)),h.children.length>0&&u.appendChild(h),y.Children&&y.Children.length>0&&l(u,y.Children)}};i.innerHTML="",l(i,a)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.navigator.stopReadAloud(),this.navigator.navigate(n)):Ui.default.log("annotation data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){Ui.default.log("annotation data locator: ",i),i?t===Si.Annotation&&this.deleteHighlight(i):Ui.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.navigator.iframes[0].contentDocument,i=(o,a)=>{let l=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),u,d;l&&(u=l.querySelector(`#${a.highlight.id}`)),d=u.getElementsByClassName(Tn)[0];let y=parseInt(d.style.top.replace("px","")),b=Yt(et({},a),{highlight:Yt(et({},a.highlight),{position:y})});return[...o,b]};return t.reduce(i,[])}reposition(t){let n=this.navigator.iframes[0].contentDocument,i=(o,a,l)=>{let u=t[0],d=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),h,y;d&&(h=d.querySelector(`#${u.highlight.id}`)),y=h.getElementsByClassName(Tn)[0];let w=parseInt(y.style.height.replace("px","")),p=a.highlight.position,m=o[l-1]&&o[l-1].highlight.position,g=l===0?0:m+w+0,v=g>p?g:p,A=Yt(et({},a),{highlight:Yt(et({},a.highlight),{position:v})});return[...o,A]};return t.sort(function(o,a){return o.highlight.position-a.highlight.position}).reduce(i,[])}};H();var K0=nt(J0());var $i=nt(Jt());var ds=class{static async create(t){let n=new this(t.annotator,t.rights||{enableBookmarks:!1},t.publication,t,t.initialAnnotations,t.api,t.headerMenu);return await n.start(),new Promise(i=>i(n))}constructor(t,n,i,o,a,l,u){this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=u,this.initialAnnotations=a,this.properties=o,this.api=l}stop(){$i.default.log("Bookmark module stop")}async start(){if(this.headerMenu&&(this.bookmarksView=Ie(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=Ie(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let t=Ie(this.headerMenu,"#menu-button-bookmark");t&&t.parentElement?.style.removeProperty("display"),t&&Ee(t,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let t=this.initialAnnotations.bookmarks||null;t&&this.annotator?.initBookmarks(t)}}async handleResize(){setTimeout(async()=>{await this.drawBookmarks(),await this.showBookmarks(),setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)},100)}initialize(){return new Promise(async 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 $i.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else{let n=await this.annotator.deleteBookmark(t);return $i.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.navigator.currentChapterLink.href);if(this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),t){let n=t.Href;n.indexOf("#")>0&&(n=n.slice(0,n.indexOf("#")));let i=this.navigator.view?.getCurrentPosition(),o=(0,K0.v4)(),a;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let l=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),u=Math.ceil((i??0)*(l.length-1)),d=l[u];a=Yt(et({},d),{id:o,href:n,created:new Date,title:this.navigator.currentChapterLink.title})}else a={id:o,href:n,locations:{progression:i},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title};if(!this.annotator.locatorExists(a,Si.Bookmark))if(this.navigator.consumptionModule?.trackAction(a,cs.BookmarkCreated),this.api?.addBookmark){let l=await this.api.addBookmark(a);l&&(a=l),$i.default.log(a);let u=this.annotator.saveBookmark(a);return $i.default.log("Bookmark added "+JSON.stringify(u)),this.showBookmarks(),await this.drawBookmarks(),u}else{let l=this.annotator.saveBookmark(a);return $i.default.log("Bookmark added "+JSON.stringify(l)),this.showBookmarks(),await this.drawBookmarks(),l}}}}async addBookmarkPlus(){let t=this,n=this.navigator.highlighter?.visibleTextRects[0],i=this.navigator.iframes[0].contentDocument;if(i){let u=this.navigator.highlighter?.dom(i.body).getWindow().document.createRange(),d=this.navigator.highlighter?.dom(this.navigator.iframes[0].contentDocument?.body).getSelection();d.removeAllRanges(),n&&u.selectNodeContents(n.node),d.addRange(u);let h=Gd(u,!1),y=0;for(let b of h){if(!this.navigator.highlighter?.isOutsideViewport(b)){let w=d.focusNode,p=d.focusOffset;d.collapse(d.anchorNode,d.anchorOffset);for(let v=0;v<y;v++)d.modify("move","forward","line");d.extend(w,p);let m=d.focusNode,f=d.focusNode.length;d.collapse(d.anchorNode,d.anchorOffset);let g=f;d.anchorOffset>f?g=f:g=d.anchorOffset+1,d.modify("move","forward","character"),d.modify("move","backward","word"),d.extend(m,g),d.modify("extend","backward","character"),d.modify("extend","forward","word");break}y++}}function o(u){let d={},h=t.navigator.iframes[0].contentDocument;if(h)return wn(u,t.navigator.highlighter?.dom(h.body).getDocument(),d)}let a=this.navigator.iframes[0].contentWindow,l={id:"bookmarkIcon",marker:Ve.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=Er(a,o);if(u===void 0){let h=t.navigator.iframes[0].contentDocument;u=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(h)}let d=t.navigator.iframes[0].contentDocument;if(u&&d){let h=this.navigator.highlighter?.createHighlight(this.navigator.highlighter?.dom(d.body).getWindow(),u,l.highlight?.color,!0,Ve.Bookmark,l.icon,l.popup,l.highlight?.style);if(this.navigator.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),h)return this.saveAnnotation(h[0]).then(y=>{$i.default.log("saved bookmark "+y?.id)})}}}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(n=this.publication.getTOCItem(this.navigator.currentTocUrl)),n===null&&(n=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let i=this.navigator.view?.getCurrentPosition(),o=this.navigator.iframes[0].contentDocument;if(o){let a=Gr(o,"body"),l=t.position?t.position/a.scrollHeight:i,u=(0,K0.v4)(),d;if(n){let h=n.Href;if(h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let y=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),b=Math.ceil((l??0)*(y.length-1)),w=y[b];d=Yt(et({},w),{id:u,href:h,created:new Date,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else d={id:u,href:h,locations:{progression:l},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(d)if(this.navigator.consumptionModule?.trackAction(d,cs.BookmarkCreated),this.api?.addBookmark){let h=await this.api.addBookmark(d),y=await this.annotator.saveAnnotation(h);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(b=>b(y))}else{let h=await this.annotator.saveAnnotation(d);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(y=>y(h))}}}return new Promise(i=>i(void 0))}getBookmarks(){let t=[];return this.annotator&&(t=this.annotator.getBookmarks()),t}showBookmarks(){let t=[];this.annotator&&(t=this.annotator.getBookmarks());let n=[];this.annotator&&(n=this.annotator.getAnnotations(),n&&(n=n.filter(i=>i.highlight.marker===Ve.Bookmark),t?t.push.apply(t,n):t=n)),this.bookmarksView&&this.createTree(Si.Bookmark,t,this.bookmarksView)}async drawBookmarks(){if(this.rights.enableBookmarks&&this.navigator.highlighter)if(this.api){let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.navigator.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.navigator.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href;var t=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight)}}}}else{let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.navigator.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.navigator.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href,l=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl&&(l=this.publication.getTOCItem(this.navigator.currentTocUrl)),l===void 0&&(l=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),l){let u=l.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),o.href===u&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight)}}}}}async deleteSelectedHighlight(t){this.api?.deleteBookmark?this.api.deleteBookmark(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return $i.default.log("Highlight deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else return new Promise(i=>i(null))}createTree(t,n,i){if(n){let o=this,a=this.publication.readingOrder;if(a.length){let l=(u,d)=>{let h=document.createElement("ul");h.className="sidenav-annotations";for(let y of d){let b=document.createElement("li"),w=document.createElement("a"),p=document.createElement("span");if(w.tabIndex=-1,w.className="chapter-link",y.Href){let f=this.publication.getAbsoluteHref(y.Href),g=this.publication.getTOCItemAbsolute(f);w.href=f,w.innerHTML=g?.Title||"",b.appendChild(w)}else p.innerHTML=y.Title||"",p.className="chapter-title",b.appendChild(p);Ee(w,"click",f=>{f.preventDefault(),f.stopPropagation();let g={href:w.href,locations:{progression:0},type:y.TypeLink,title:w.title};this.navigator.stopReadAloud(),this.navigator.navigate(g)});let m=document.createElement("ol");n.forEach(function(f){let g=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&f.href.endsWith(g)){let v=document.createElement("li");v.className="annotation-item";let A=document.createElement("a");if(A.setAttribute("href",f.href),t===Si.Bookmark){A.className="bookmark-link";let O=document.createElement("span"),E=Math.round((f.locations.progression??0)*100)+"% through resource";O.className="title",O.innerHTML=E,A.appendChild(O)}let C=document.createElement("span");if(C.className="timestamp",C.innerHTML=ds.readableTimestamp(f.created),A.appendChild(C),Ee(A,"click",O=>{O.preventDefault(),O.stopPropagation(),o.handleAnnotationLinkClick(O,f)}),v.appendChild(A),o.navigator.sideNavExpanded){let O=document.createElement("button");O.className="delete",O.innerHTML=nr.delete,Ee(O,"click",E=>{E.preventDefault(),E.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,E,f)}),v.appendChild(O)}m.appendChild(v)}}),m.children.length>0&&(h.appendChild(b),h.appendChild(m)),h.children.length>0&&u.appendChild(h),y.Children&&y.Children.length>0&&l(u,y.Children)}};i.innerHTML="",l(i,a)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.navigator.stopReadAloud(),this.navigator.navigate(n)):$i.default.log("bookmark data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){$i.default.log("bookmark data locator: ",i),i?t===Si.Bookmark&&this.deleteBookmark(i):$i.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)}};H();var eS=nt(Q_());H();var ii=nt(Jt()),X0="r2-mo-active",fs=class{},Xe=fs;Xe.COLOR_REF="color",Xe.AUTO_SCROLL_REF="autoscroll",Xe.AUTO_TURN_REF="autoturn",Xe.VOLUME_REF="volume",Xe.RATE_REF="rate",Xe.COLOR_KEY="mediaoverlay-"+fs.COLOR_REF,Xe.AUTO_SCROLL_KEY="mediaoverlay-"+fs.AUTO_SCROLL_REF,Xe.AUTO_TURN_KEY="mediaoverlay-"+fs.AUTO_TURN_REF,Xe.VOLUME_KEY="mediaoverlay-"+fs.VOLUME_REF,Xe.RATE_KEY="mediaoverlay-"+fs.RATE_REF;var Z0=class{constructor(t,n,i){this.MEDIAOVERLAYSETTINGS="mediaOverlaySetting";this.color="r2-mo-active";this.autoScroll=!0;this.autoTurn=!0;this.volume=1;this.rate=1;this.playing=!1;this.resourceReady=!1;this.wait=1;this.settingsChangeCallback=()=>{};this.store=t,this.api=n,this.headerMenu=i,this.initialise(),ii.default.log(this.api)}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialMediaOverlaySettings){let i=t.initialMediaOverlaySettings;i?.color&&(n.color=i.color,ii.default.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,ii.default.log(n.autoScroll)),i?.autoTurn&&(n.autoTurn=i.autoTurn,ii.default.log(n.autoScroll)),i?.volume&&(n.volume=i.volume,ii.default.log(n.volume)),i?.rate&&(n.rate=i.rate,ii.default.log(n.rate)),i?.wait&&(n.wait=i.wait,ii.default.log(n.wait))}return n.initializeSelections(),n}stop(){ii.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(Xe.AUTO_SCROLL_KEY)!=null?this.getProperty(Xe.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(Xe.AUTO_TURN_KEY)!=null?this.getProperty(Xe.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(Xe.COLOR_KEY)!=null?this.getProperty(Xe.COLOR_KEY).value:this.color,this.volume=this.getProperty(Xe.VOLUME_KEY)!=null?this.getProperty(Xe.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(Xe.RATE_KEY)!=null?this.getProperty(Xe.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=Ie(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechAutoTurn=Ie(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=Ie(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=Ie(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=Ie(this.headerMenu,"#mediaOverlayRate")),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),this.speechAutoTurn&&(this.speechAutoTurn.checked=this.autoTurn),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechRate&&(this.speechRate.value=this.volume.toString()),Ee(Ie(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(Xe.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Xe.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(Xe.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(Xe.VOLUME_REF)?.value,rate:this.userProperties.getByRef(Xe.RATE_REF)?.value};this.applyMediaOverlaySettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{ii.default.log("api updated sync settings",n)})}getMediaOverlaySettings(){let t=new Wr;return t.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,Xe.AUTO_SCROLL_REF,Xe.AUTO_SCROLL_KEY),t.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,Xe.AUTO_TURN_REF,Xe.AUTO_TURN_KEY),t.addStringable(this.color,Xe.COLOR_REF,Xe.COLOR_KEY),t.addIncremental(this.volume,.1,1,.1,"",Xe.VOLUME_REF,Xe.VOLUME_KEY),t.addIncremental(this.rate,.1,3,.1,"",Xe.RATE_REF,Xe.RATE_KEY),t}saveProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}return t}getProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}resetMediaOverlaySettings(){this.store.remove(this.MEDIAOVERLAYSETTINGS),this.reset(),this.settingsChangeCallback()}applyMediaOverlaySettings(t){if(t.color){this.color=t.color;let n=this.userProperties.getByRef(Xe.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){ii.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Xe.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoTurn!==void 0){ii.default.log("autoTurn "+this.autoTurn),this.autoTurn=t.autoTurn;let n=this.userProperties.getByRef(Xe.AUTO_TURN_REF);n&&(n.value=this.autoTurn,this.saveProperty(n)),this.settingsChangeCallback()}if(t.volume){ii.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Xe.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback()}if(t.rate){ii.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Xe.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback()}}applyMediaOverlaySetting(t,n){if(t===Xe.COLOR_REF){this.color=n;let i=this.userProperties.getByRef(Xe.COLOR_REF);i&&(i.value=this.color,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===Xe.AUTO_SCROLL_REF){this.autoScroll=n;let i=this.userProperties.getByRef(Xe.AUTO_SCROLL_REF);i&&(i.value=this.autoScroll,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===Xe.AUTO_TURN_REF){this.autoTurn=n;let i=this.userProperties.getByRef(Xe.AUTO_TURN_REF);i&&(i.value=this.autoTurn,this.saveProperty(i)),this.settingsChangeCallback()}}increase(t){if(t==="mo_volume"){this.userProperties.getByRef(Xe.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(Xe.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Xe.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Xe.RATE_REF).increment(),this.rate=this.userProperties.getByRef(Xe.RATE_REF)?.value;let n=this.userProperties.getByRef(Xe.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}decrease(t){if(t==="mo_volume"){this.userProperties.getByRef(Xe.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(Xe.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Xe.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Xe.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(Xe.RATE_REF)?.value;let n=this.userProperties.getByRef(Xe.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}};var Ze=nt(Jt()),Tl=class{constructor(t,n,i){this.play=Ie(document,"#menu-button-play");this.pause=Ie(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async t=>{Ze.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.publication=t,this.settings=n,this.properties=i}static create(t){let n=new this(t.publication,t.settings,t);return n.start(),n}stop(){Ze.default.log("MediaOverlay module stop")}start(){Ze.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.navigator.requestConfig)}catch(h){console.error(h,o);return}a.ok||Ze.default.log("BAD RESPONSE?!");let l;try{l=await a.json()}catch(h){console.error(h)}if(!l){Ze.default.log("## moJson"+l);return}t.MediaOverlays=Ks(l,eS.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.navigator.nextResource()):await this.stopReadAloud()}async startReadAloud(){if(this.navigator.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.navigator.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display")}}async stopReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement&&this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"))}findDepthFirstTextAudioPair(t,n,i){Ze.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&&i){a=!1;let h=d.hash.substr(1);for(let y of i)if(y===h){a=!0;break}}}else o=!1}if(Ze.default.log("isFragmentIDMatch: "+a),Ze.default.log("isTextUrlMatch: "+o),!n.Children||!n.Children.length){if(Ze.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!o){Ze.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return a||o&&!i?(Ze.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),n):void 0}let l=i,u=i;for(let d of n.Children){Ze.default.log("findDepthFirstTextAudioPair() - child"),Ze.default.log(JSON.stringify(d));let h=this.findDepthFirstTextAudioPair(t,d,u);if(h===null&&(Ze.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),u=void 0),h)return Ze.default.log("findDepthFirstTextAudioPair() - child - match"),Ze.default.log(JSON.stringify(h)),h}if(a){Ze.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let d=this.findDepthFirstTextAudioPair(t,n,void 0);return d&&(Ze.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),Ze.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&&(Ze.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(Ze.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let n=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!t);if(!n)Ze.default.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud());else{let i=!1;if(this.mediaOverlayTextAudioPair.Text&&n.Text){let o=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),a=new URL("https://dita.digital/"+n.Text);o.pathname!==a.pathname&&(Ze.default.log("mediaOverlaysNext() SWITCH! "+o.pathname+" != "+a.pathname),i=!0)}i?this.mediaOverlaysStop():(Ze.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(n,void 0,void 0)},0))}}else Ze.default.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){Ze.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){Ze.default.log("mediaOverlaysPause()"),this.mediaOverlayHighlight(void 0),this.audioElement&&this.audioElement.pause()}findNextTextAudioPair(t,n,i,o){if(!t.Children||!t.Children.length){if(i?.prev===n)return Ze.default.log("findNextTextAudioPair() - prevMo === moToMatch"),t;Ze.default.log("findNextTextAudioPair() - set previous"),Ze.default.log(JSON.stringify(t)),i.prev=t;return}for(let a of t.Children){Ze.default.log("findNextTextAudioPair() - child"),Ze.default.log(JSON.stringify(a));let l=this.findNextTextAudioPair(a,n,i,o);if(l)return Ze.default.log("findNextTextAudioPair() - match"),Ze.default.log(JSON.stringify(l)),l}}async playMediaOverlaysAudio(t,n,i){if(Ze.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",h=typeof i!="undefined";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!d&&!h){if(o.hash){let b=o.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(b&&b.length>=1){let w=b[1];try{this.currentAudioBegin=parseFloat(w)}catch(p){Ze.default.error(p)}if(b.length>=3){let p=b[3];try{this.currentAudioEnd=parseFloat(p)}catch(m){Ze.default.error(m)}}}}}else this.currentAudioBegin=n,this.currentAudioEnd=i;Ze.default.log(`${a} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let y=async b=>{if(!this.audioElement)return;let w=this.currentAudioBegin?this.currentAudioBegin:0;if(b||this.audioElement.paused)if(b&&!w||this.audioElement.currentTime===w){if(Ze.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 m=function(){p.settings.resourceReady?setTimeout(async()=>{await p.audioElement.play(),p.ensureOnTimeUpdate(!1,!0)},p.settings.wait*1e3):setTimeout(m,200)},p=this;m()}}else{Ze.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let p=async m=>{if(this.audioElement.removeEventListener("timeupdate",p),Ze.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 g=function(){f.settings.resourceReady?setTimeout(async()=>{await f.audioElement.play(),f.ensureOnTimeUpdate(!1,!0)},f.settings.wait*1e3):setTimeout(g,200)},f=this;g()}};this.audioElement.addEventListener("timeupdate",p),this.audioElement.currentTime=w}else{let p=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd!="undefined"&&this.previousAudioEnd>w-.02&&this.previousAudioEnd<=w&&this.audioElement.currentTime>=w-.1;this.ensureOnTimeUpdate(!1,!1),p?Ze.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(Ze.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=w)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||u!==this.currentAudioUrl){this.currentAudioUrl=u,Ze.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",p=>{Ze.default.log("-1) error: "+(this.currentAudioUrl!==p.currentTarget.src?this.currentAudioUrl+" -- ":"")+p.currentTarget.src.substr(p.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(Ze.default.log(this.audioElement.error.code),Ze.default.log(this.audioElement.error.message))});let b=async p=>{p.currentTarget.removeEventListener("canplaythrough",b),Ze.default.log("oncanplaythrough"),await y(!0)};this.audioElement.addEventListener("canplaythrough",b);let w=async p=>{Ze.default.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",w),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else Ze.default.log("playMediaOverlaysAudio() - playClip()"),await y(!1)}async playMediaOverlays(t,n,i){Ze.default.log("playMediaOverlays()");let o=i?i.filter(l=>l):void 0;o&&o.length===0&&(o=void 0);let a=this.findDepthFirstTextAudioPair(t,n,o);!a&&o&&(Ze.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),Ze.default.log(JSON.stringify(o,null,4)),Ze.default.log(JSON.stringify(n,null,4)),a=this.findDepthFirstTextAudioPair(t,n,void 0)),a?a.Audio&&(Ze.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=n,await this.playMediaOverlaysAudio(a,void 0,void 0)):Ze.default.log("playMediaOverlays() - !moTextAudioPair "+t)}mediaOverlayHighlight(t){Ze.default.log("moHighlight: ## "+t);let n=this.publication.Metadata?.MediaOverlay?.ActiveClass;n||(n=this.settings.color);let i=this.navigator.iframes[0].contentDocument?.documentElement.getAttribute("style"),o=i?i.indexOf("readium-night-on")>0:!1,a=i?i.indexOf("readium-sepia-on")>0:!1;if((this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&(n=o||a?X0:n||X0),this.pid){let u;this.currentLinkIndex===0?u=this.navigator.iframes[0].contentDocument?.getElementById(this.pid):u=this.navigator.iframes[1].contentDocument?.getElementById(this.pid),u&&u.classList.remove(n)}let l;t&&(this.currentLinkIndex===0?l=this.navigator.iframes[0].contentDocument?.getElementById(t):l=this.navigator.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"})}};H();var Q0=nt(Jt()),Ol=class{static async create(t){let n=new this(t.publication);return await n.start(),n}constructor(t){this.publication=t}async stop(){Q0.default.log("Timeline module stop")}async start(){this.timelineContainer=Ie(document,"#container-view-timeline"),this.positionSlider=Ie(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.navigator.currentLocator();(this.navigator.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions)&&(this.positionSlider&&(this.positionSlider.value=(n.locations.position??0).toString()),this.positionSlider&&(this.positionSlider.max=((n.locations.totalRemainingPositions??0)+(n.locations.position??0)).toString())),this.timelineContainer&&(this.timelineContainer.innerHTML=""),this.publication.readingOrder?.forEach(i=>{let o=this.publication.getAbsoluteHref(i.Href),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.navigator.view?.layout!=="fixed"?i.contentWeight?d=i.contentWeight:d=1:d=100/(this.publication.readingOrder?.length??0);var h=document.createElement("div");if(h.style.height=d+"%",h.style.width="100%",h.className="chapter",a?.Title!==void 0){var y=document.createElement("span");y.innerHTML=a.Title,y.className="chapter-tooltip",h.appendChild(y)}Ee(h,"click",b=>{b.preventDefault(),b.stopPropagation();var w;this.publication.positions||this.navigator.rights.autoGeneratePositions&&this.publication.positions?(w=et({},this.publication.positions.filter(p=>p.href===i.Href)[0]),w.href=this.publication.getAbsoluteHref(w.href)):w={href:u,locations:{progression:0},type:i.TypeLink,title:i.Title},Q0.default.log(w),this.navigator.navigate(w)}),u===this.navigator.currentChapterLink.href?h.className+=" active":h.className=h.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(h)}),t()})}};H();var vg=nt(So());H();var tS=nt(Jt());function nS(r,t){return new Promise(function(n){setTimeout(n.bind(null,t),r)})}var s8=!1;tS.default.setLevel(s8?"trace":"warn",!0);var kA=nt(PA()),dh=nt(MA()),On=nt(Jt());var ya=class{constructor(t){this.hasEventListener=!1;this.isHacked=!1;this.properties=t}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);return await n.start(),n}static async startInspectorProtection(t){(0,dh.addListener)(i=>{i&&(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,dh.launch)(),await nS(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,kA.getUserAgentRegExp)({browsers:n,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.properties?.enableObfuscation){this.wrapper=yt(document,"#iframe-wrapper"),this.securityContainer=Ie(document,"#container-view-security");var t=this;this.mutationObserver=new MutationObserver(function(n){n.forEach(function(i){On.default.log(i.type),t.isHacked=!0})})}}async stop(){if(On.default.log("Protection module stop"),this.properties?.enableObfuscation&&this.mutationObserver.disconnect(),this.properties?.disableKeys){je(this.navigator.mainElement,"keydown",this.disableSave),je(this.navigator.headerMenu,"keydown",this.disableSave);for(let t of this.navigator.iframes)je(t.contentDocument,"keydown",this.disableSave),je(t.contentWindow,"keydown",this.disableSave);je(window,"keydown",this.disableSave),je(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){je(this.navigator.mainElement,"copy",this.preventCopy),je(this.navigator.headerMenu,"copy",this.preventCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"copy",this.preventCopy),je(t.contentWindow,"copy",this.preventCopy);je(window,"copy",this.preventCopy),je(document,"copy",this.preventCopy),je(this.navigator.mainElement,"cut",this.preventCopy),je(this.navigator.headerMenu,"cut",this.preventCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"cut",this.preventCopy),je(t.contentWindow,"cut",this.preventCopy);je(window,"cut",this.preventCopy),je(document,"cut",this.preventCopy),je(this.navigator.mainElement,"keydown",this.preventCopyKey),je(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let t of this.navigator.iframes)je(t.contentDocument,"keydown",this.preventCopyKey),je(t.contentWindow,"keydown",this.preventCopyKey);je(window,"keydown",this.preventCopyKey),je(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){je(this.navigator.mainElement,"copy",this.restrictCopy),je(this.navigator.headerMenu,"copy",this.restrictCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"copy",this.restrictCopy),je(t.contentWindow,"copy",this.restrictCopy);je(window,"copy",this.restrictCopy),je(document,"copy",this.restrictCopy),je(this.navigator.mainElement,"cut",this.restrictCopy),je(this.navigator.headerMenu,"cut",this.restrictCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"cut",this.restrictCopy),je(t.contentWindow,"cut",this.restrictCopy);je(window,"cut",this.restrictCopy),je(document,"cut",this.restrictCopy),je(this.navigator.mainElement,"keydown",this.restrictCopyKey),je(this.navigator.headerMenu,"keydown",this.restrictCopyKey);for(let t of this.navigator.iframes)je(t.contentDocument,"keydown",this.restrictCopyKey),je(t.contentWindow,"keydown",this.restrictCopyKey);je(window,"keydown",this.restrictCopyKey),je(document,"keydown",this.restrictCopyKey)}if(this.properties?.disablePrint){je(this.navigator.mainElement,"beforeprint",this.beforePrint.bind(this)),je(this.navigator.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let t of this.navigator.iframes)je(t.contentDocument,"beforeprint",this.beforePrint),je(t.contentWindow,"beforeprint",this.beforePrint);je(window,"beforeprint",this.beforePrint),je(document,"beforeprint",this.beforePrint),je(this.navigator.mainElement,"afterprint",this.afterPrint.bind(this)),je(this.navigator.headerMenu,"afterprint",this.afterPrint.bind(this));for(let t of this.navigator.iframes)je(t.contentDocument,"afterprint",this.afterPrint.bind(this)),je(t.contentWindow,"afterprint",this.afterPrint.bind(this));je(window,"afterprint",this.afterPrint.bind(this)),je(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){je(this.navigator.mainElement,"contextmenu",this.disableContext),je(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let t of this.navigator.iframes)je(t.contentDocument,"contextmenu",this.disableContext),je(t.contentWindow,"contextmenu",this.disableContext);je(window,"contextmenu",this.disableContext),je(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),je(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.navigator.iframes)if(t.contentDocument){let n=Gr(t.contentDocument,"body");this.rects=this.findRects(n),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){Ee(this.navigator.mainElement,"keydown",this.disableSave),Ee(this.navigator.headerMenu,"keydown",this.disableSave);for(let t of this.navigator.iframes)Ee(t,"keydown",this.disableSave),Ee(t.ownerDocument,"keydown",this.disableSave),Ee(t.contentDocument,"keydown",this.disableSave),Ee(t.contentWindow,"keydown",this.disableSave),Ee(t.contentWindow?.document,"keydown",this.disableSave);Ee(window,"keydown",this.disableSave),Ee(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){Ee(this.navigator.mainElement,"copy",this.preventCopy),Ee(this.navigator.headerMenu,"copy",this.preventCopy);for(let t of this.navigator.iframes)Ee(t,"copy",this.preventCopy),Ee(t.ownerDocument,"copy",this.preventCopy),Ee(t.contentDocument,"copy",this.preventCopy),Ee(t.contentWindow,"copy",this.preventCopy),Ee(t.contentWindow?.document,"copy",this.preventCopy);Ee(window,"copy",this.preventCopy),Ee(document,"copy",this.preventCopy),Ee(this.navigator.mainElement,"cut",this.preventCopy),Ee(this.navigator.headerMenu,"cut",this.preventCopy);for(let t of this.navigator.iframes)Ee(t,"cut",this.preventCopy),Ee(t.ownerDocument,"cut",this.preventCopy),Ee(t.contentDocument,"cut",this.preventCopy),Ee(t.contentWindow,"cut",this.preventCopy),Ee(t.contentWindow?.document,"cut",this.preventCopy);Ee(window,"cut",this.preventCopy),Ee(document,"cut",this.preventCopy),Ee(this.navigator.mainElement,"keydown",this.preventCopyKey),Ee(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let t of this.navigator.iframes)Ee(t,"keydown",this.preventCopyKey),Ee(t.ownerDocument,"keydown",this.preventCopyKey),Ee(t.contentDocument,"keydown",this.preventCopyKey),Ee(t.contentWindow,"keydown",this.preventCopyKey),Ee(t.contentWindow?.document,"keydown",this.preventCopyKey);Ee(window,"keydown",this.preventCopyKey),Ee(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){Ee(this.navigator.mainElement,"copy",this.restrictCopy.bind(this)),Ee(this.navigator.headerMenu,"copy",this.restrictCopy.bind(this));for(let t of this.navigator.iframes)Ee(t,"copy",this.restrictCopy),Ee(t.ownerDocument,"copy",this.restrictCopy.bind(this)),Ee(t.contentDocument,"copy",this.restrictCopy.bind(this)),Ee(t.contentWindow,"copy",this.restrictCopy.bind(this)),Ee(t.contentWindow?.document,"copy",this.restrictCopy.bind(this));Ee(window,"copy",this.restrictCopy.bind(this)),Ee(document,"copy",this.restrictCopy.bind(this)),Ee(this.navigator.mainElement,"cut",this.restrictCopy.bind(this)),Ee(this.navigator.headerMenu,"cut",this.restrictCopy.bind(this));for(let t of this.navigator.iframes)Ee(t,"cut",this.restrictCopy.bind(this)),Ee(t.ownerDocument,"cut",this.restrictCopy.bind(this)),Ee(t.contentDocument,"cut",this.restrictCopy.bind(this)),Ee(t.contentWindow,"cut",this.restrictCopy.bind(this)),Ee(t.contentWindow?.document,"cut",this.restrictCopy.bind(this));Ee(window,"cut",this.restrictCopy.bind(this)),Ee(document,"cut",this.restrictCopy.bind(this)),Ee(this.navigator.mainElement,"keydown",this.restrictCopyKey.bind(this)),Ee(this.navigator.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let t of this.navigator.iframes)Ee(t,"keydown",this.restrictCopyKey.bind(this)),Ee(t.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),Ee(t.contentDocument,"keydown",this.restrictCopyKey.bind(this)),Ee(t.contentWindow,"keydown",this.restrictCopyKey.bind(this)),Ee(t.contentWindow?.document,"keydown",this.restrictCopyKey.bind(this));Ee(window,"keydown",this.restrictCopyKey.bind(this)),Ee(document,"keydown",this.restrictCopyKey.bind(this))}if(this.properties?.disablePrint){Ee(this.navigator.mainElement,"beforeprint",this.beforePrint),Ee(this.navigator.headerMenu,"beforeprint",this.beforePrint);for(let t of this.navigator.iframes)Ee(t,"beforeprint",this.beforePrint.bind(this)),Ee(t.ownerDocument,"beforeprint",this.beforePrint.bind(this)),Ee(t.contentDocument,"beforeprint",this.beforePrint.bind(this)),Ee(t.contentWindow,"beforeprint",this.beforePrint.bind(this)),Ee(t.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));Ee(window,"beforeprint",this.beforePrint.bind(this)),Ee(document,"beforeprint",this.beforePrint.bind(this)),Ee(this.navigator.mainElement,"afterprint",this.afterPrint),Ee(this.navigator.headerMenu,"afterprint",this.afterPrint);for(let t of this.navigator.iframes)Ee(t,"afterprint",this.afterPrint.bind(this)),Ee(t.ownerDocument,"afterprint",this.afterPrint.bind(this)),Ee(t.contentDocument,"afterprint",this.afterPrint.bind(this)),Ee(t.contentWindow,"afterprint",this.afterPrint.bind(this)),Ee(t.contentWindow?.document,"afterprint",this.afterPrint.bind(this));Ee(window,"afterprint",this.afterPrint.bind(this)),Ee(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){Ee(this.navigator.mainElement,"contextmenu",this.disableContext),Ee(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let t of this.navigator.iframes)Ee(t,"contextmenu",this.disableContext),Ee(t.ownerDocument,"contextmenu",this.disableContext),Ee(t.contentDocument,"contextmenu",this.disableContext),Ee(t.contentWindow,"contextmenu",this.disableContext),Ee(t.contentWindow?.document,"contextmenu",this.disableContext);Ee(window,"contextmenu",this.disableContext),Ee(document,"contextmenu",this.disableContext)}}initializeResource(){this.properties?.hideTargetUrl&&this.hideTargetUrls(!0),this.properties?.disableDrag&&this.preventDrag(!0)}async initialize(){if(this.properties?.enableObfuscation)return new Promise(async t=>{await document.fonts.ready;for(let n of this.navigator.iframes)if(n.contentDocument){let i=Gr(n.contentDocument,"body");this.observe(),setTimeout(()=>{this.rects=this.findRects(i),this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),this.setupEvents(),this.hasEventListener||(this.hasEventListener=!0,Ee(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,vg.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 On.default.log("copy action initiated"),t.clipboardData.setData("text/plain","copy not allowed"),t.stopPropagation(),t.preventDefault(),!1}preventCopyKey(t){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?t.metaKey:t.ctrlKey&&(t.key==="c"||t.keyCode===67))?(t.preventDefault(),t.stopPropagation(),!1):!0}restrictCopy(t){if(this.citation)return;On.default.log("copy action initiated");let n=this.navigator.iframes[0].contentWindow;if(n){let o=function(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=i.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)},i=this,a=Er(n,o);if(a===void 0){let l=this.navigator.iframes[0].contentDocument;a=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(l)}t.clipboardData.setData("text/plain",a?.cleanText?.substring(0,this.properties?.charactersToCopy??0))}else t.clipboardData.setData("text/plain","");return t.stopPropagation(),t.preventDefault(),!1}restrictCopyKey(t){if(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?t.metaKey:t.ctrlKey&&(t.key==="c"||t.keyCode===67)){let n=this.navigator.iframes[0].contentWindow;if(n){let o=function(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=i.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)},i=this,a=Er(n,o);if(a===void 0){let l=this.navigator.iframes[0].contentDocument;a=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(l)}this.copyToClipboard(a?.cleanText?.substring(0,this.properties?.charactersToCopy??0))}else this.copyToClipboard("");return t.stopPropagation(),t.preventDefault(),!1}return!0}copyToClipboard(t){if(t=t.substring(0,this.properties?.charactersToCopy??0),window.clipboardData)window.clipboardData.setData("text/plain",t);else{let n=this.createElementForExecCommand(t);this.selectContent(n);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),document.execCommand("copy",!1)}catch(i){}document.body.removeChild(n)}}createElementForExecCommand(t){let n=document.createElement("div");return n.style.position="absolute",n.style.left="-10000px",n.style.top="-10000px",n.innerHTML=t,document.body.appendChild(n),n.contentEditable=!0,n}selectContent(t){let n=document.createRange();n.selectNodeContents(t);let i=window.getSelection();i?.removeAllRanges(),i?.addRange(n)}beforePrint(t){return On.default.log("before print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.display="none",this.navigator.mainElement.style.display="none"),t.stopPropagation(),t.preventDefault(),!1}afterPrint(t){return On.default.log("after print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.removeProperty("display"),this.navigator.mainElement.style.removeProperty("display")),t.stopPropagation(),t.preventDefault(),!1}hideTargetUrls(t){function n(i){i.preventDefault();let o=i.currentTarget.getAttribute("data-href-resolved"),a=document.createElement("a");a.setAttribute("href",o),a.click()}for(let i of this.navigator.iframes){let o=i.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;",i=o=>{o.preventDefault()};for(let o of this.navigator.iframes){let a=o.contentDocument?.body.getAttribute("style")||"";t?(o.contentDocument?.body.addEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",a+n)):(o.contentDocument?.body.removeEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",a.replace(n,"")))}}recalculate(t=0){return new Promise(n=>{if(this.properties?.enableObfuscation){let i=(0,vg.debounce)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),n(!0)},t);this.rects?(this.observe(),i()):n(!1)}else n(!1)})}calcRects(t){t!==void 0&&t.forEach(n=>{try{let{top:i,height:o,left:a,width:l}=this.measureTextNode(n.node);n.top=i,n.height=o,n.width=l,n.left=a}catch(i){On.default.log("error "+i),On.default.log(n),On.default.log(n.node),On.default.log("scrambledTextContent "+n.scrambledTextContent),On.default.log("textContent "+n.textContent),On.default.log("isObfuscated "+n.isObfuscated)}})}deactivateRect(t,n,i){this.isBeingHacked(n)||i?(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0):(t.node.textContent=t.textContent,t.isObfuscated=!1)}toggleRect(t,n,i){let o=this.isOutsideViewport(t),a=this.isBeingHacked(n);t.isObfuscated&&!o&&!a&&!i&&(t.node.textContent=t.textContent,t.isObfuscated=!1),!t.isObfuscated&&(o||a||i)&&(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0)}findRects(t){return this.findTextNodes(t).map(i=>{let{top:o,height:a,left:l,width:u}=this.measureTextNode(i),d=i.parentElement?.nodeName==="option"||i.parentElement?.nodeName==="script"?i.textContent:this.obfuscateText(i.textContent??"");return{top:o,height:a,width:u,left:l,node:i,textContent:i.textContent??"",scrambledTextContent:d??"",isObfuscated:!1}})}obfuscateText(t){return this.scramble(t,!0)}measureTextNode(t){try{let n=document.createRange();n.selectNode(t);let i=n.getBoundingClientRect();return n.detach(),i}catch(n){On.default.log("measureTextNode "+n),On.default.log("measureTextNode "+t),On.default.log(t.textContent)}}isBeingHacked(t){return t.style.animation||t.style.transition||t.style.position||t.hasAttribute("style")?(On.default.log("content being hacked"),!0):!1}isOutsideViewport(t){let n=this.wrapper.scrollLeft,i=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,h=t.top>u,y=o<n-window.innerWidth,b=t.left>i+window.innerWidth;return d||h||y||b}findTextNodes(t,n=[]){let i=t.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,n),i.nodeType===3&&i.textContent?.trim()&&n.push(i),i=i.nextSibling;return n}scramble(t,n=!1,i=!1){var o=t.split(" ");function a(l){for(var u=l.length,d,h;u>0;)h=Math.floor(Math.random()*u),u--,d=l[u],l[u]=l[h],l[h]=d;return l}return n&&(o=o.map(function(l){return l.includes("-")?l:a(l.split("")).join("")})),i?a(o).join(" "):o.join(" ")}};H();var jA=nt(IA());H();var hh=r=>r.replace(/\n/g," ").replace(/\s\s+/g," "),S8=r=>hh(r).trim(),BA=/[\\^$.*+?()[\]{}|]/g,A8=RegExp(BA.source);function NA(r){return r&&A8.test(r)?r.replace(BA,"\\$&"):r||""}var fh=0,x8=()=>()=>Number.isSafeInteger(++fh)?fh:fh=1,DA=()=>{fh=0},C8=x8(),T8=r=>t=>{try{return wn(t,r,Co)}catch(n){return console.error("uniqueCssSelector:",n),""}};async function Mo(r,t,n,i,o=!1){if(!t)return[];let a=t.body?.textContent;if(!a)return[];if(r=S8(r),!r.length)return[];let l=t.createNodeIterator(t.body,NodeFilter.SHOW_TEXT,{acceptNode:p=>NodeFilter.FILTER_ACCEPT}),u=new RegExp(NA(r).replace(/ /g,"\\s+"),"gim");o&&(u=new RegExp("\\b"+NA(r).replace(/ /g,"\\s+")+"\\b","gim"));let d=[],h=100,y=30,b=0,w;for(;w=u.exec(a);){let p=Math.max(0,w.index-h),m=Math.min(h,w.index),f=hh(a.substr(p,m));f=f.substr(f.length-y),p=u.lastIndex,m=Math.min(h,a.length-p);let g=hh(a.substr(p,m)).substr(0,y),v=new Range,A=w.index;for(;b<=A;){let E=l.nextNode();E&&E.nodeValue&&(b+=E.nodeValue.length)}let C=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(b-A):0;for(v.setStart(l.referenceNode,C),A=w.index+w[0].length;b<=A;){let T=l.nextNode()?.nodeValue;T&&(b+=T.length)}C=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(b-A):0,v.setEnd(l.referenceNode,C),t.getCssSelector||(t.getCssSelector=T8(t));let O=Xr(v,t.getCssSelector);O&&d.push({textMatch:hh(w[0]),textBefore:f,textAfter:g,rangeInfo:O,href:n,title:i,uuid:C8().toString()})}return d}var FA=nt(Jt()),Ll=class{constructor(t,n,i,o,a){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.headerMenu=a,this.publication=t,this.properties=n,this.api=o,this.highlighter=i}static async create(t){let n=new this(t.publication,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){FA.default.log("Search module stop"),je(this.searchInput,"keypress",this.handleSearch.bind(this)),je(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.headerMenu){this.searchInput=Ie(this.headerMenu,"#searchInput"),Ee(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=Ie(this.headerMenu,"#searchGo"),Ee(this.searchGo,"click",this.handleSearch.bind(this));var t=Ie(this.headerMenu,"#menu-button-search");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("search"):this.navigator.showLayer("search")},10)}async handleSearch(t){(t.key==="Enter"||t.type==="click")&&(await this.handleSearchChapter(),await this.handleSearchBook())}async handleSearchChapter(t){var n=this,i=this.searchInput.value;let o=this.navigator.currentChapterLink.href,a=this.publication.getSpineItem(o);if(this.headerMenu)var l=Ie(document,"#searchResultChapter");n.currentChapterSearchResult=[],n.currentSearchHighlights=[];var u=[];await this.searchAndPaintChapter(i,t,async h=>{u=h,d(1),this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)});async function d(h){l.innerHTML="";var y;if(y=n.paginate(u,h,10),y.total===0){let b=document.createElement("a");b.className="collection-item",b.innerHTML="nothing found",l.appendChild(b)}else{for(let f=0;f<y.data.length;f++){let g=document.createElement("a"),v=y.data[f];g.className="collection-item",g.href=a?.Href??"",g.innerHTML="..."+v.textBefore+"<mark>"+v.textMatch+"</mark>"+v.textAfter+"...",Ee(g,"click",A=>{A.preventDefault(),A.stopPropagation(),n.jumpToMark(f+h*10-10)}),l.appendChild(g)}let b=document.createElement("div");b.style.textAlign="center",b.style.marginTop="10px";let w=document.createElement("ul");w.className="pagination";let p=document.createElement("li");if(p.className="disabled",p.innerHTML='<a href="#!"> < </a>',y.pre_page!==void 0){let f=y.pre_page;p.className="waves-effect",Ee(p,"click",g=>{g.preventDefault(),g.stopPropagation(),d(f)})}w.appendChild(p);for(let f=1;f<=y.total_pages;f++){let g,v=document.createElement("li");v.className="waves-effect",f===y.page&&(v.className="active",g=v),v.innerHTML='<a href="#!">'+f+"</a>",Ee(v,"click",A=>{A.preventDefault(),A.stopPropagation(),g&&(g.className="waves-effect"),v.className="active",g=v,d(f)}),w.appendChild(v)}let m=document.createElement("li");if(m.className="disabled",m.innerHTML='<a href="#!"> > </a>',y.next_page!==void 0){let f=y.next_page;m.className="waves-effect",Ee(m,"click",g=>{g.preventDefault(),g.stopPropagation(),d(f)})}w.appendChild(m),b.appendChild(w),l.appendChild(b)}}}async searchAndPaintChapter(t,n=0,i){this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate();let o=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),a=this.publication.getTOCItem(o);a===null&&(a=this.publication.readingOrder[this.navigator.currentResource()??0]);let l=[];this.highlighter?.destroyHighlights(it.Search),this.navigator.rights.enableSearch&&this.drawSearch();let u=0;if(a){let d=this.navigator.iframes[0].contentDocument;d&&a&&Mo(t,d,a.Href,a.Title).then(h=>{h.forEach(y=>{let b={rangeInfo:y.rangeInfo};setTimeout(()=>{let w;u===n?(w=this.createSearchHighlight(b,this.properties?.current),this.jumpToMark(n)):w=this.createSearchHighlight(b,this.properties?.color),y.highlight=w,l.push(y),this.currentChapterSearchResult.push(y),this.currentSearchHighlights.push(w),u++},500)}),setTimeout(()=>{i(l)},500)})}}createSearchHighlight(t,n){try{var i=n;Qe.isHexColor(i)&&(i=Qe.hexToRgbChannels(i));let a=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,l=jA.SHA256.hash(a),u="R2_SEARCH_"+l;var o=!1;let d={color:i||ls,id:u,pointerInteraction:o,selectionInfo:t,marker:Ve.Highlight,type:it.Search},h=this.highlighter?.createHighlightDom(this.navigator.iframes[0].contentWindow,d);return d.position=parseInt((h?.hasChildNodes()?h.childNodes[0]:h).style.top.replace("px","")),d}catch(a){throw"Can't create highlight: "+a}}clearSearch(){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.highlighter?.destroyHighlights(it.Search)}async search(t,n){return this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],DA(),await this.searchAndPaintChapter(t,0,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)}),n?(await this.searchBook(t),await this.searchChapter(t)):(await this.searchChapter(t),await this.searchBook(t))}async goToSearchID(t,n,i){var o=n,a;let l=this.navigator.currentChapterLink.href;var u=this.publication.getAbsoluteHref(t);let d=this.bookSearchResult.filter(h=>h.href===t);if(i?(a=this.currentChapterSearchResult.filter(h=>h.uuid===n)[0],o=this.currentChapterSearchResult.findIndex(h=>h.uuid===n)):(a=d.filter(h=>h.uuid===n)[0],o=d.findIndex(h=>h.uuid===n)),a!==void 0)if(l===u)this.jumpToMark(o);else{let y={href:u,locations:{progression:0},title:"title"};this.navigator.navigate(y),setTimeout(()=>{this.searchAndPaintChapter(a.textMatch,o,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)})},300)}}async goToSearchIndex(t,n,i){var o=n,a;let l=this.navigator.currentChapterLink.href;var u=this.publication.getAbsoluteHref(t);let d=this.bookSearchResult.filter(h=>h.href===t);if(i?a=this.currentChapterSearchResult[o]:a=d[o],a!==void 0)if(l===u)this.jumpToMark(o);else{let y={href:u,locations:{progression:0},title:"title"};this.navigator.navigate(y),setTimeout(()=>{this.searchAndPaintChapter(a.textMatch,o,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)})},300)}}async handleSearchBook(){var t=this,n=this.searchInput.value;if(t.headerMenu)var i=Ie(document,"#searchResultBook");o(1);async function o(l){i.innerHTML="";var u,d=await t.searchBook(n);if(u=t.paginate(d,l,10),u.total===0){let h=document.createElement("a");h.className="collection-item",h.innerHTML="nothing found",i.appendChild(h)}else{a(u.data,m=>m.href).forEach(m=>{let f=document.createElement("div");if(f.style.marginBottom="10px",m[0].title){let g=document.createElement("span");g.className="collection-item",g.style.display="block",g.innerHTML=m[0].title,f.appendChild(g)}i.appendChild(f),m.forEach(g=>{let v=document.createElement("a");v.className="collection-item";var A=t.publication.getAbsoluteHref(g.href);v.innerHTML="..."+g.textBefore+"<mark>"+g.textMatch+"</mark>"+g.textAfter+"...",Ee(v,"click",C=>{C.preventDefault(),C.stopPropagation();let E=d.filter(B=>B.href===g.href).findIndex(B=>B===g);if(t.navigator.currentChapterLink.href===A)t.jumpToMark(E);else{let M={href:A,locations:{progression:0},title:"title"};t.navigator.navigate(M),setTimeout(()=>{t.handleSearchChapter(E)},300)}}),f.appendChild(v)})});let y=document.createElement("div");y.style.textAlign="center",y.style.marginTop="10px";let b=document.createElement("ul");b.className="pagination";let w=document.createElement("li");if(w.className="disabled",w.innerHTML='<a href="#!"> < </a>',u.pre_page!=null){let m=u.pre_page;w.className="waves-effect",Ee(w,"click",f=>{f.preventDefault(),f.stopPropagation(),o(m)})}b.appendChild(w);for(let m=1;m<=u.total_pages;m++){let f,g=document.createElement("li");g.className="waves-effect",m===u.page&&(g.className="active",f=g),g.innerHTML='<a href="#!">'+m+"</a>",Ee(g,"click",v=>{v.preventDefault(),v.stopPropagation(),f&&(f.className="waves-effect"),g.className="active",f=g,o(m)}),b.appendChild(g)}let p=document.createElement("li");if(p.className="disabled",p.innerHTML='<a href="#!"> > </a>',u.next_page!=null){let m=u.next_page;p.className="waves-effect",Ee(p,"click",f=>{f.preventDefault(),f.stopPropagation(),o(m)})}b.appendChild(p),y.appendChild(b),i.appendChild(y)}}function a(l,u){let d=new Map;return l.forEach(h=>{let y=u(h),b=d.get(y);b?b.push(h):d.set(y,[h])}),Array.from(d.values())}}async searchBook(t){this.bookSearchResult=[];let n=[];for(let i=0;i<this.publication.readingOrder.length;i++){let o=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[i].Href:""),a=this.publication.getTOCItem(o);if(a===void 0&&this.publication.readingOrder&&(a=this.publication.readingOrder[i]),a){let l=this.publication.getAbsoluteHref(a.Href);this.navigator.api?.getContent?await this.navigator.api?.getContent(l).then(u=>{let h=new DOMParser().parseFromString(u,"application/xhtml+xml");a&&Mo(t,h,a.Href,a.Title).then(y=>{y.forEach(b=>{n.push(b),this.bookSearchResult.push(b)})})}):await fetch(l,this.navigator.requestConfig).then(u=>u.text()).then(async u=>{let h=new DOMParser().parseFromString(this.navigator.requestConfig?.encoded?this.decodeBase64(u):u,"application/xhtml+xml");a&&Mo(t,h,a.Href,a.Title).then(y=>{y.forEach(b=>{n.push(b),this.bookSearchResult.push(b)})})})}if(i===this.publication.readingOrder.length-1)return n}}decodeBase64(t){let n=atob(t),i=n.length,o=new Uint8Array(i);for(let l=0;l<i;l++)o[l]=n.charCodeAt(l);return new TextDecoder().decode(o)}async searchChapter(t){let n=[],i=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),o=this.publication.getTOCItem(i);if(o===null&&(o=this.publication.readingOrder[this.navigator.currentResource()??0]),o){let a=this.publication.getAbsoluteHref(o.Href);this.navigator.api?.getContent?await this.navigator.api?.getContent(a).then(l=>{let d=new DOMParser().parseFromString(l,"application/xhtml+xml");o&&Mo(t,d,o.Href,o.Title).then(h=>{h.forEach(y=>{n.push(y)})})}):await fetch(a,this.navigator.requestConfig).then(l=>l.text()).then(async l=>{let d=new DOMParser().parseFromString(this.navigator.requestConfig?.encoded?this.decodeBase64(l):l,"application/xhtml+xml");o&&Mo(t,d,o.Href,o.Title).then(h=>{h.forEach(y=>{n.push(y)})})})}return n}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(t=>{let n={rangeInfo:t.rangeInfo};if(this.properties?.color){let i=this.createSearchHighlight(n,this.properties?.color);t.highlight=i,this.currentSearchHighlights.push(i)}})},100)}async handleResize(){await this.highlighter?.destroyHighlights(it.Search),this.drawSearch()}jumpToMark(t){setTimeout(()=>{if(this.currentChapterSearchResult.length){var n=this.currentChapterSearchResult[t];this.currentSearchHighlights.forEach(o=>{var a=this.properties?.color;Qe.isHexColor(a)&&(a=Qe.hexToRgbChannels(a)),o.color=a});var i=this.properties?.current;Qe.isHexColor(i)&&(i=Qe.hexToRgbChannels(i)),n.highlight.color=i,this.highlighter?.setAndResetSearchHighlight(n.highlight,this.currentSearchHighlights),this.navigator.view?.goToCssSelector(n.rangeInfo.startContainerElementCssSelector),this.navigator.updatePositionInfo()}},200)}paginate(t,n,i){let o=n||1,a=i||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}}};H();var oi=nt(Jt()),ko=class{},Ke=ko;Ke.COLOR_REF="color",Ke.AUTO_SCROLL_REF="autoscroll",Ke.RATE_REF="rate",Ke.PITCH_REF="pitch",Ke.VOLUME_REF="volume",Ke.VOICE_REF="voice",Ke.COLOR_KEY="tts-"+ko.COLOR_REF,Ke.AUTO_SCROLL_KEY="tts-"+ko.AUTO_SCROLL_REF,Ke.RATE_KEY="tts-"+ko.RATE_REF,Ke.PITCH_KEY="tts-"+ko.PITCH_REF,Ke.VOLUME_KEY="tts-"+ko.VOLUME_REF,Ke.VOICE_KEY="tts-"+ko.VOICE_REF;var Eg=class{constructor(t,n,i){this.TTSSETTINGS="ttsSetting";this.color="orange";this.autoScroll=!0;this.rate=1;this.pitch=1;this.volume=1;this.voice={usePublication:!0};this.settingsChangeCallback=()=>{};this.restartCallback=()=>{};this.store=t,this.api=n,this.headerMenu=i,this.initialise()}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialTTSSettings){let i=t.initialTTSSettings;i?.rate&&(n.rate=i.rate,oi.default.log(n.rate)),i?.pitch&&(n.pitch=i.pitch,oi.default.log(n.pitch)),i?.volume&&(n.volume=i.volume,oi.default.log(n.volume)),i?.color&&(n.color=i.color,oi.default.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,oi.default.log(n.autoScroll)),i?.voice&&(n.voice=i.voice,oi.default.log(n.voice))}return n.initializeSelections(),n}stop(){oi.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(Ke.AUTO_SCROLL_KEY)!=null?this.getProperty(Ke.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(Ke.RATE_KEY)!=null?this.getProperty(Ke.RATE_KEY).value:this.rate,this.pitch=this.getProperty(Ke.PITCH_KEY)!=null?this.getProperty(Ke.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(Ke.VOLUME_KEY)!=null?this.getProperty(Ke.VOLUME_KEY).value:this.volume,this.color=this.getProperty(Ke.COLOR_KEY)!=null?this.getProperty(Ke.COLOR_KEY).value:this.color,this.voice=this.getProperty(Ke.VOICE_REF)!=null?this.getProperty(Ke.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=Ie(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechRate=Ie(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=Ie(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=Ie(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=Ie(this.headerMenu,"#autoScroll")),this.speechRate&&(this.speechRate.value=this.rate.toString()),this.speechPitch&&(this.speechPitch.value=this.pitch.toString()),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),Ee(Ie(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(Ke.RATE_REF)?.value,pitch:this.userProperties.getByRef(Ke.PITCH_REF)?.value,volume:this.userProperties.getByRef(Ke.VOLUME_REF)?.value,voice:this.userProperties.getByRef(Ke.VOLUME_REF)?.value,color:this.userProperties.getByRef(Ke.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Ke.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{oi.default.log("api updated tts settings",n)})}getTTSSettings(){var t=new Wr;return t.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,Ke.AUTO_SCROLL_REF,Ke.AUTO_SCROLL_KEY),t.addIncremental(this.rate,.1,10,.1,"",Ke.RATE_REF,Ke.RATE_KEY),t.addIncremental(this.pitch,.1,2,.1,"",Ke.PITCH_REF,Ke.PITCH_KEY),t.addIncremental(this.volume,.1,1,.1,"",Ke.VOLUME_REF,Ke.VOLUME_KEY),t.addStringable(this.color,Ke.COLOR_REF,Ke.COLOR_KEY),t.addJSONable(JSON.stringify(this.voice),Ke.VOICE_REF,Ke.VOICE_KEY),t}saveProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}return t}getProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?void 0:i[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(t){if(t.rate){oi.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Ke.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.pitch){oi.default.log("pitch "+this.pitch),this.pitch=t.pitch;let n=this.userProperties.getByRef(Ke.PITCH_REF);n&&(n.value=this.pitch,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.volume){oi.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Ke.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(Ke.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){oi.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Ke.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.voice){oi.default.log("voice "+this.voice),this.voice=t.voice;let n=this.userProperties.getByRef(Ke.VOICE_REF);n&&(n.value=this.voice,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}}applyPreferredVoice(t){var n=t.indexOf(":")!==-1?t.slice(0,t.indexOf(":")):void 0,i=t.indexOf(":")!==-1?t.slice(t.indexOf(":")+1):t;n!==void 0&&i!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:n,lang:i}}):i!==void 0&&n===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:i}})}increase(t){if(t==="rate"){this.userProperties.getByRef(Ke.RATE_REF).increment();let n=this.userProperties.getByRef(Ke.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(Ke.PITCH_REF).increment();let n=this.userProperties.getByRef(Ke.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(Ke.VOLUME_REF).increment();let n=this.userProperties.getByRef(Ke.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}decrease(t){if(t==="rate"){this.userProperties.getByRef(Ke.RATE_REF).decrement();let n=this.userProperties.getByRef(Ke.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(Ke.PITCH_REF).decrement();let n=this.userProperties.getByRef(Ke.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(Ke.VOLUME_REF).decrement();let n=this.userProperties.getByRef(Ke.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}};H();H();var ph=`${nr.loading}`,HA=`
80
80
  <span>
81
81
  ${nr.error}
82
82
  </span>