@d-i-t-a/reader 2.2.1 → 2.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +5 -3
- package/dist/esm/index.js.map +2 -2
- package/dist/reader.js +1 -1
- package/dist/reader.js.map +2 -2
- package/package.json +1 -1
package/dist/reader.js
CHANGED
|
@@ -78,7 +78,7 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
78
78
|
</svg>`,ma=(r,t,n,i="icon",o,s)=>`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" height="${o}" viewBox="${Z_}" style="fill:${s}" preserveAspectRatio="xMidYMid meet" role="img" class="${i}" aria-labelledBy="${r}">
|
|
79
79
|
<title id="${r}">${t}</title>
|
|
80
80
|
${n}
|
|
81
|
-
</svg>`,mr={error:mi("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:mi("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:bD("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:mi("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:mi("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:mi("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:mi("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:mi("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:mi("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:mi("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:mi("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:mi("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:mi("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:mi("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:mi("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 j0=gt(Gd());var yi=gt(cn()),et;(function(c){c.R2_ID_HIGHLIGHTS_CONTAINER="R2_ID_HIGHLIGHTS_CONTAINER",c.R2_ID_BOOKMAKRS_CONTAINER="R2_ID_BOOKMAKRS_CONTAINER",c.R2_ID_READALOUD_CONTAINER="R2_ID_READALOUD_CONTAINER",c.R2_ID_PAGEBREAK_CONTAINER="R2_ID_PAGEBREAK_CONTAINER",c.R2_ID_SEARCH_CONTAINER="R2_ID_SEARCH_CONTAINER",c.R2_ID_DEFINITIONS_CONTAINER="R2_ID_DEFINITIONS_CONTAINER",c.R2_ID_LINEFOCUS_CONTAINER="R2_ID_LINEFOCUS_CONTAINER",c.R2_ID_GUTTER_RIGHT_CONTAINER="R2_ID_GUTTER_RIGHT_CONTAINER"})(et||(et={}));var Q_="R2_CLASS_HIGHLIGHT_CONTAINER",xl="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",$n="R2_CLASS_HIGHLIGHT_AREA",Cl="R2_CLASS_HIGHLIGHT_ICON",Lr=.5,eS=.75,gs={blue:100,green:50,red:230},yn=[],vD="data-highlighted",wD="data-timestamp",ba={ELEMENT_NODE:1,TEXT_NODE:3},ji=[et.R2_ID_HIGHLIGHTS_CONTAINER,et.R2_ID_PAGEBREAK_CONTAINER,et.R2_ID_SEARCH_CONTAINER,et.R2_ID_READALOUD_CONTAINER,et.R2_ID_BOOKMAKRS_CONTAINER,et.R2_ID_DEFINITIONS_CONTAINER,et.R2_ID_LINEFOCUS_CONTAINER,et.R2_ID_GUTTER_RIGHT_CONTAINER,Q_,$n,xl],H0=-1,U0=-1,ht=class{constructor(t,n,i,o,s,l){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.showTool=(0,Al.debounce)(t=>{this.isAndroid()||this.snapSelectionToWord(t),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,Al.debounce)(()=>{this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen(),this.delegate.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,Al.debounce)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.delegate.emit("toolbox.closed","closed"))},100);this.selection=(0,Al.debounce)((t,n)=>{this.api?.selection&&this.api?.selection(t,n)},100);this.getScrollingElement=t=>t?.scrollingElement?t?.scrollingElement:t?.body?t?.body:document.createElement("body");this.delegate=t,this.layerSettings=n,this.properties=i,this.api=l,this.hasEventListener=o,this.options=this.defaults(s,{color:"#fce300",highlightedClass:"highlighted",contextClass:"highlighter-context",onBeforeHighlight:function(){return!0},onAfterHighlight:function(){}}),this.delegate.highlighter=this}static async create(t){let n=new this(t.delegate,t.layerSettings,t,!1,{},t.api);return new Promise(i=>i(n))}async initialize(){let t=this.delegate.iframes[0].contentDocument;t&&this.dom(t.body).addClass(this.options.contextClass),this.bindEvents(this.delegate.iframes[0].contentDocument?.body,this,this.hasEventListener),this.initializeToolbox(),H0=-1,U0=-1;let n=this;async function i(){n.lastSelectedHighlight===void 0||(n.lastSelectedHighlight=void 0)}setTimeout(async()=>{let o=this.delegate.iframes[0].contentDocument;o&&await o.body?.addEventListener("click",i)},100)}haveSameColor(t,n){return this.dom(t).color()===this.dom(n).color()}defaults(t,n){t=t||{};for(let i in n)n.hasOwnProperty(i)&&t[i]===void 0&&(t[i]=n[i]);return t}unique(t){return t.filter(function(n,i,o){return o.indexOf(n)===i})}refineRangeBoundaries(t){let n=t.startContainer,i=t.endContainer,o=t.commonAncestorContainer,s=!0;if(t.endOffset===0){for(;!i.previousSibling&&i.parentNode!==o;)i=i.parentNode;i=i.previousSibling}else i.nodeType===ba.TEXT_NODE?t.endOffset<i.nodeValue.length&&i.splitText(t.endOffset):t.endOffset>0&&(i=i.childNodes.item(t.endOffset-1));return n.nodeType===ba.TEXT_NODE?t.startOffset===n.nodeValue.length?s=!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:s}}sortByDepth(t,n){let i=this;t.sort(function(o,s){return i.dom(n?s:o).parents().length-i.dom(n?o:s).parents().length})}groupHighlights(t){let n=[],i={},o=[];return t.forEach(function(s){let l=s.getAttribute(wD);typeof i[l]=="undefined"&&(i[l]=[],n.push(l)),i[l].push(s)}),n.forEach(function(s){let l=i[s];o.push({chunks:l,timestamp:s,toString:function(){return l.map(function(h){return h.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),s=o.length;for(;s--;)t.insertBefore(o[s],t.firstChild)},append:function(i){let o=Array.prototype.slice.call(i);for(let s=0,l=o.length;s<l;++s)t.appendChild(o[s])},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(s){o=s.parentNode,n.dom(s).insertBefore(s.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===ba.TEXT_NODE)for(;t.nextSibling&&t.nextSibling.nodeType===ba.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){H0=t.clientX,U0=t.clientY}async mouseup(t){Math.abs(H0-t.clientX)<3&&Math.abs(U0-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.delegate.iframes[0].contentDocument;t&&(this.unbindEvents(t.body,this),this.dom(t.body).removeClass(this.options.contextClass))}initializeToolbox(){let t=document.getElementById("highlight-toolbox-mode-colors"),n=document.getElementById("highlight-toolbox-mode-add"),i=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],o=document.getElementById("colorIcon"),s=document.getElementById("actionIcon"),l=document.getElementById("dismissIcon"),h=document.getElementById("collapseIcon"),c=document.getElementById("highlightIcon"),d=this;if(l&&(l.innerHTML=mr.close,l.addEventListener("click",function(){d.toolboxMode("add")})),h&&(h.innerHTML=mr.close,h.addEventListener("click",function(){d.toolboxMode("add")})),o){o.style.position="relative",o.style.zIndex="20",i.forEach(w=>{let v=document.getElementById(w),g=document.getElementById(`c${w}`);v&&t?.contains(v)&&t.removeChild(v),n&&g&&n.contains(g)&&n.removeChild(g)});let m=[],y=[];if(o.addEventListener("click",function(){d.toolboxMode("colors")}),this.delegate.rights.enableAnnotations){let w=10;i.forEach(v=>{w--;let g=o?.cloneNode(!0),f=g.lastChild,p=ht.hexToRgbChannels(v);f.style.backgroundColor="rgba("+[p.red,p.green,p.blue].join(",")+",.5)",g.id=`c${v}`,g.style.display="unset",g.style.position="relative",g.style.zIndex=`${w}`,g.style.marginLeft="-30px",y.push(g),n?.insertBefore(g,c)})}i.forEach(w=>{let v=o?.cloneNode(!0),g=v.lastChild;g.style.backgroundColor=w,v.id=w,v.style.position="relative",v.style.display="unset",m.push(v),o&&v.addEventListener("click",function(){d.setColor(w);let f=o?.lastChild;f&&(f.style.backgroundColor=w);let p=document.getElementById("highlightIcon"),b=document.getElementById("underlineIcon"),S=document.getElementById("noteIcon");(p?.getElementsByTagName?.("span").length??0)>0&&((p?.getElementsByTagName("span")[0]).style.background=d.getColor()),(b?.getElementsByTagName?.("span").length??0)>0&&((b?.getElementsByTagName("span")[0]).style.borderBottomColor=d.getColor()),(S?.getElementsByTagName?.("span").length??0)>0&&((S?.getElementsByTagName("span")[0]).style.borderBottomColor=d.getColor()),d.toolboxMode("add")}),t?.insertBefore(v,l)})}s&&s.addEventListener("click",function(){d.toolboxMode("action")}),d.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"),s=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"),s&&(s.style.display="none");break;case"edit":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="unset"),s&&(s.style.display="none");break;case"action":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),s&&(s.style.display="unset");break;default:n&&(n.style.display="none"),i&&(i.style.display="unset"),o&&(o.style.display="none"),s&&(s.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.delegate.iframes[0].contentDocument;if(i){let s=n.dom(i.body)?.getSelection();if(n.dom(i.body)&&s&&!s?.isCollapsed){let d=function(p){let b=p.match(new RegExp("[^a-zA-Z0-9]+$"));return!b||!b.index?p:p.slice(0,b.index)},l=s.toString(),h=l.length-l.trimStart().length,c=l.length-l.trimEnd().length,m=l.length;var o=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;l=l.replace(o,""),h=m-l.trimStart().length,l=d(l),c=m-l.trimEnd().length;let y=document.createRange();t?(y.setStart(s.anchorNode,s.anchorOffset+h),y.setEnd(s.focusNode,s.focusOffset-c)):(y.setStart(s.anchorNode,s.anchorOffset),y.setEnd(s.focusNode,s.focusOffset));let w=y.collapsed;y.detach();let v=s.focusNode,g;t?(g=s.focusOffset-c,s.collapse(s.anchorNode,s.anchorOffset+h)):(g=s.focusOffset,s.collapse(s.anchorNode,s.anchorOffset));let f=["forward","backward"];w&&(f=["backward","forward"]),t?(s.modify("move",f[0],"character"),s.modify("move",f[1],"word"),s.extend(v,g),s.modify("extend",f[1],"character"),s.modify("extend",f[0],"word")):s.extend(v,g),this.selection(s.toString(),s)}return s}}toolboxShow(){if(this.activeAnnotationMarkerId===void 0){let t=this,n=document.getElementById("highlight-toolbox-mode-add"),i=this.dom(this.delegate.iframes[0].contentDocument?.body).getRange();if((!i||i.collapsed)&&n){getComputedStyle(n).display!=="none"&&t.toolboxHide();return}this.isIOS()&&setTimeout(function(){let o=t.delegate.iframes[0].contentDocument;if(o){let s=t.dom(o.body).getSelection();s.removeAllRanges(),setTimeout(function(){s.addRange(i);function l(d){let m={className:w=>ji.indexOf(w)<0,idName:w=>ji.indexOf(w)<0},y=t.delegate.iframes[0].contentDocument;if(y)return Nn(d,y,m)}let h=t.delegate.iframes[0].contentWindow,c=Ir(h,l);t.delegate.annotationModule?.annotator?.saveTemporarySelectionInfo(c)},5)}},100),this.toolboxPlacement(),this.toolboxHandler()}}toolboxPlacement(){let t=this.dom(this.delegate.iframes[0].contentDocument?.body).getRange();if(!t||t.collapsed)return;let n=t.getBoundingClientRect(),i=document.getElementById("highlight-toolbox");i&&(this.delegate.view?.isPaginated()?i.style.top=n.top+(this.delegate.attributes?.navHeight??0)+"px":i.style.top=n.top+"px",i.style.left=(n.right-n.left)/2+n.left+"px")}toolboxHandler(){let t=document.getElementById("highlight-toolbox");if(t&&getComputedStyle(t).display==="none"){t.style.display="block",this.delegate.view?.isPaginated()?t.style.position="absolute":t.style.position="relative",this.selectionMenuOpened();let i=this;i.toolboxMode("add");let o=document.getElementById("highlightIcon"),s=document.getElementById("collapseIcon"),l=document.getElementById("underlineIcon"),h=document.getElementById("noteIcon"),c=document.getElementById("colorIcon"),d=document.getElementById("speakIcon");if(this.delegate.rights.enableAnnotations){if(o&&(o.style.display="unset",c&&o.getElementsByTagName("span").length>0&&(o.getElementsByTagName("span")[0].style.background=this.getColor())),l&&(l.style.display="unset",c&&l.getElementsByTagName("span").length>0&&(l.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),h&&(h.style.display="unset",c&&h.getElementsByTagName("span").length>0&&(h.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),c){c.style.display="unset";let m=c.lastChild;m.style.backgroundColor=this.getColor()}if(o){let m=function(){i.doHighlight(!1,ot.Highlight),i.toolboxHide(),o?.removeEventListener("click",m)},y=o.cloneNode(!0);o?.parentNode?.replaceChild(y,o),o=document.getElementById("highlightIcon"),o?.addEventListener("click",m)}if(l){let m=function(){i.doHighlight(!1,ot.Underline),i.toolboxHide(),l?.removeEventListener("click",m)},y=l.cloneNode(!0);l?.parentNode?.replaceChild(y,l),l=document.getElementById("underlineIcon"),l?.addEventListener("click",m)}if(h){let m=function(){i.doHighlight(!1,ot.Comment),i.toolboxHide(),h?.removeEventListener("click",m)},y=h.cloneNode(!0);h?.parentNode?.replaceChild(y,h),h=document.getElementById("noteIcon"),h?.addEventListener("click",m)}}else o&&o.style.setProperty("display","none"),l&&l.style.setProperty("display","none"),h&&h.style.setProperty("display","none"),c&&c.style.setProperty("display","none"),s&&s.style.setProperty("display","none");if(this.delegate.rights.enableTTS){if(d){let m=function(){d?.removeEventListener("click",m),i.speak()},y=d.cloneNode(!0);d?.parentNode?.replaceChild(y,d),d=document.getElementById("speakIcon"),d?.addEventListener("click",m)}}else d&&d.style.setProperty("display","none");(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).forEach(m=>{m.icon&&(m.icon.id=m.id);let y=document.getElementById(m.id),w=this;function v(){y?.removeEventListener("click",v);function g(p){let b={className:C=>ji.indexOf(C)<0,idName:C=>ji.indexOf(C)<0},S=w.delegate.iframes[0].contentDocument;if(S)return Nn(p,S,b)}let f=w.delegate.iframes[0].contentWindow;if(f){let p=Ir(f,g);if(p===void 0){let b=w.delegate.iframes[0].contentDocument;p=w.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(b)}if(p!==void 0)if(m.callback)m.callback(p.cleanText,p.range?.startContainer.parentElement);else{let b=m.highlight?.style,S=m.marker?m.marker:ot.Custom;if(S===ot.Custom&&w.delegate.rights.enableAnnotations||S===ot.Bookmark&&w.delegate.rights.enableBookmarks){let C=w.delegate.iframes[0].contentDocument;if(C){let x=w.createHighlight(w.dom(C.body).getWindow(),p,m.highlight?.color,!0,S,m.icon,m.popup,b);w.options.onAfterHighlight(x,S),w.delegate.rights.enableAnnotations?w.delegate.annotationModule?.saveAnnotation(x[0]).then(E=>{m?.note&&E.highlight&&w.delegate.annotationModule?.api?.addCommentToAnnotation(E).then(T=>{w.delegate.annotationModule?.updateAnnotation(T).then(async()=>{yi.default.log("update highlight "+T.id)})})}):w.delegate.rights.enableBookmarks&&w.delegate.bookmarkModule?.saveAnnotation(x[0])}}}}w.callbackComplete()}if(y){let g=y.cloneNode(!0);y?.parentNode?.replaceChild(g,y),y=document.getElementById(m.id),y?.addEventListener("click",v)}})}}doHighlight(t,n){let i=this;function o(l){let h={className:d=>ji.indexOf(d)<0,idName:d=>ji.indexOf(d)<0},c=i.delegate.iframes[0].contentDocument;if(c)return Nn(l,c,h)}let s=i.delegate.iframes[0].contentWindow;if(s){let l=Ir(s,o);if(l===void 0){let h=i.delegate.iframes[0].contentDocument;l=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(h)}if(l){if(this.options.onBeforeHighlight(l)===!0){let h;h=this.getColor(),ht.isHexColor(h)&&(h=ht.hexToRgbChannels(h));let c=i.delegate.iframes[0].contentDocument;if(c){let d=this.createHighlight(i.dom(c.body).getWindow(),l,h,!0,n??ot.Highlight);this.options.onAfterHighlight(d,n),this.delegate.rights.enableAnnotations&&n!==ot.Bookmark?this.delegate.annotationModule?.saveAnnotation(d[0]):this.delegate.rights.enableBookmarks&&n===ot.Bookmark&&this.delegate.bookmarkModule?.saveAnnotation(d[0])}}t||this.dom(this.delegate.iframes[0].contentDocument?.body).removeAllRanges()}else t||this.dom(this.delegate.iframes[0].contentDocument?.body).removeAllRanges()}}speak(){if(this.delegate.rights.enableTTS){let n=function(l){let h={className:d=>ji.indexOf(d)<0,idName:d=>ji.indexOf(d)<0},c=t.delegate.iframes[0].contentDocument;if(c)return Nn(l,c,h)},t=this,i=t.delegate.iframes[0].contentWindow;if(i){let l=Ir(i,n);if(l===void 0){let h=t.delegate.iframes[0].contentDocument;l=t.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(h)}l!==void 0&&this.delegate.ttsModule.speak(l,!0,()=>{})}let o=t.delegate.iframes[0].contentDocument;o&&t.dom(o.body).getSelection().removeAllRanges();let s=document.getElementById("highlight-toolbox");s&&(s.style.display="none"),this.selectionMenuClosed()}}stopReadAloud(){this.delegate.rights.enableTTS&&this.doneSpeaking()}callbackComplete(){this.toolboxHide();let t=this.delegate.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges()}isOutsideViewport(t){let n=Rt(document,"#iframe-wrapper"),i=n.scrollLeft,o=i+n.clientWidth,s=t.left+t.width,l=t.top+t.height,h=n.scrollTop,c=h+n.clientHeight,d=l<h,m=t.top>c,y=s<i,w=t.left>o;return d||m||y||w}isInsideViewport(t){let n=Rt(document,"#iframe-wrapper"),i=n.scrollTop,o=i+n.clientHeight,s=t.top+20>=i,l=t.top<=o,h=n.scrollLeft,c=h+n.clientWidth,d=t.left+t.width,m=t.left>h,y=d<c;return s&&l&&m&&y}get visibleTextRects(){let t=this.delegate.iframes[0].contentDocument;if(t){let i=function(h,c=[]){let d=h.firstChild;for(;d;)d.nodeType===1&&i(d,c),d.nodeType===3&&d.textContent?.trim()&&c.push(d),d=d.nextSibling;return c},o=function(h){return i(h).map(d=>{let{top:m,height:y,left:w,width:v}=s(d);return{top:m,height:y,width:v,left:w,node:d,textContent:d.textContent??""}})},s=function(h){try{let c=document.createRange();c.selectNode(h);let d=c.getBoundingClientRect();return c.detach(),d}catch(c){yi.default.log("measureTextNode "+c),yi.default.log("measureTextNode "+h),yi.default.log(`${h.textContent}`)}},n=Qr(t,"body");return o(n).filter(h=>this.isInsideViewport(h))}return[]}doneSpeaking(t=!1){if(this.delegate.rights.enableTTS){this.toolboxHide();let n=this.delegate.iframes[0].contentDocument;n&&this.dom(n.body).removeAllRanges(),this.delegate.ttsModule.cancel(),t&&this.delegate.reload()}}normalizeHighlights(t){var n;return n=t.filter(function(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 s=!1;return t.forEach(function(l,h){let c=l.parentElement,d=c.previousSibling,m=c.nextSibling;i.isHighlight(c)&&(i.haveSameColor(c,l)?(c.replaceChild(l.firstChild,l),t[h]=c,s=!0):(l.nextSibling||(i.dom(l).insertBefore(m||c),s=!0),l.previousSibling||(i.dom(l).insertAfter(d||c),s=!0),c.hasChildNodes()||i.dom(c).remove()))}),s}do n=o();while(n)}mergeSiblingHighlights(t){let n=this;function i(o,s){return s&&s.nodeType===ba.ELEMENT_NODE&&n.haveSameColor(o,s)&&n.isHighlight(s)}t.forEach(function(o){let s=o.previousSibling,l=o.nextSibling;i(o,s)&&(n.dom(o).prepend(s.childNodes),n.dom(s).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===ba.ELEMENT_NODE&&t.hasAttribute(vD)}createWrapper(){let t=document.createElement("mark");return t.style.background="linear-gradient("+ht.hexToRgbA(this.options.color)+", "+ht.hexToRgbA(this.options.color)+")",t.className=this.options.highlightedClass,t}static isHexColor(t){return/^#([A-Fa-f0-9]{3}){1,2}$/.test(t)}static hexToRgbString(t){let n;return n=t.substring(1).split(""),n.length===3&&(n=[n[0],n[0],n[1],n[1],n[2],n[2]]),n="0x"+n.join(""),n}static hexToRgbChannels(t){let n;if(this.isHexColor(t))return n=this.hexToRgbString(t),{red:n>>16&255,green:n>>8&255,blue:n&255};throw new Error("Bad Hex")}static hexToRgbA(t){let n;if(this.isHexColor(t))return n=this.hexToRgbChannels(t),"rgba("+[n.red,n.green,n.blue].join(",")+",.5)";if(typeof t=="object"){let i=t;return"rgba("+[i.red,i.green,i.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(t,n){let i;if(this.isHexColor(t))return i=this.hexToRgbChannels(t),"rgba("+[i.red,i.green,i.blue].join(",")+","+n+")";if(typeof t=="object"){let o=t;return"rgba("+[o.red,o.green,o.blue].join(",")+","+n+")"}throw new Error("Bad Hex")}resetHighlightBoundingStyle(t){t.style.outline="none",t.style.setProperty("background-color","transparent","important")}resetHighlightAreaStyle(t,n){let i=this.delegate.iframes[0].contentWindow?.document,o=t.parentNode&&t.parentNode.nodeType===Node.ELEMENT_NODE&&t.parentNode.getAttribute?t.parentNode.getAttribute("id"):void 0;if(o){let s=yn.find(l=>l.id===o);if(s){if(s.marker===ot.Custom||s.marker===ot.Bookmark)if(s.style?.hover){if(s.style?.hover)for(let c=0;c<s.style?.hover?.length;c++){let d=s.style?.hover[c];t.style.removeProperty(d.property)}let h="";if(s.style?.default)for(let c=0;c<s.style?.default?.length;c++){let d=s.style?.default[c];t.style.removeProperty(d.property),h+=`${d.property}: ${d.value} !${d.priority};`}t.setAttribute("style",`${t.getAttribute("style")}; ${h}`)}else if(s.style?.hoverClass){s.style?.hoverClass&&t.classList.remove(s.style?.hoverClass);let h="";s.style?.defaultClass&&t.classList.add(s.style?.defaultClass),t.setAttribute("style",`${t.getAttribute("style")}; ${h}`)}else if(ht.isHexColor(s.color)){let h=ht.hexToRgbChannels(s.color);t.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${0})`,"important")}else t.classList.remove("hover");else if(s.marker===ot.Underline||s.marker===ot.Comment)if(typeof s.color=="object"){let h=s.color;t.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${h.red}, ${h.green}, ${h.blue}, ${1})`,"important")}else if(ht.isHexColor(s.color)){let h=ht.hexToRgbChannels(s.color);t.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${h.red}, ${h.green}, ${h.blue}, ${1})`,"important")}else t.classList.remove("hover");else if(typeof s.color=="object"){let h=s.color;t.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${Lr})`,"important")}else if(ht.isHexColor(s.color)){let h=ht.hexToRgbChannels(s.color);t.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${Lr})`,"important")}else t.classList.remove("hover");let l;if(i){let h=i.getElementById(n);h&&(l=h.querySelector(`#${s.id}`))}if(l){let h=l.getElementsByClassName(Cl);if(h.length>0){let c=h.item(0).getElementsByClassName("icon-tooltip");c.length>0&&c.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(t,n,i){for(let o of n){if(i.marker===ot.Custom||i.marker===ot.Bookmark)if(i.style?.hover){if(i.style?.default)for(let l=0;l<i.style?.default?.length;l++){let h=i.style?.default[l];o.style.removeProperty(h.property)}let s="";for(let l=0;l<i.style?.hover?.length;l++){let h=i.style?.hover[l];o.style.removeProperty(h.property),s+=`${h.property}: ${h.value} !${h.priority};`}o.setAttribute("style",`${o.getAttribute("style")}; ${s}`)}else if(i.style?.hoverClass){i.style?.defaultClass&&o.classList.remove(i.style?.defaultClass);let s="";o.classList.add(i.style?.hoverClass),o.setAttribute("style",`${o.getAttribute("style")}; ${s}`)}else if(ht.isHexColor(i.color)){let s=ht.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${.1})`,"important")}else o.classList.add("hover");else if(i.marker===ot.Underline||i.marker===ot.Comment)if(typeof i.color=="object"){let s=i.color;o.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${s.red}, ${s.green}, ${s.blue}, ${1})`,"important")}else if(ht.isHexColor(i.color)){let s=ht.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${s.red}, ${s.green}, ${s.blue}, ${1})`,"important")}else o.classList.add("hover");else if(typeof i.color=="object"){let s=i.color;o.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${eS})`,"important")}else if(ht.isHexColor(i.color)){let s=ht.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${eS})`,"important")}else o.classList.add("hover");if(i.type!==mt.Definition){let l=t.getElementById(et.R2_ID_HIGHLIGHTS_CONTAINER).querySelector(`#${i.id}`).getElementsByClassName(Cl);if(l.length>0){let h=l.item(0).getElementsByClassName("icon-tooltip");h.length>0&&h.item(0).style.setProperty("display","block")}}}}setAndResetSearchHighlight(t,n){let i=this.delegate.iframes[0].contentWindow?.document,o=Array.from(i.getElementById(et.R2_ID_SEARCH_CONTAINER).querySelectorAll(`.${$n}`));for(let s of o){let l=s,h=l.parentNode&&l.parentNode.nodeType===Node.ELEMENT_NODE&&l.parentNode.getAttribute?l.parentNode.getAttribute("id"):void 0;if(n.forEach(c=>{if(h===c.id&&c){if(typeof c.color=="object"){let y=c.color;l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${Lr})`,"important")}else if(ht.isHexColor(c.color)){let y=ht.hexToRgbChannels(c.color);l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${Lr})`,"important")}else l.classList.remove("hover");let m=i.getElementById(et.R2_ID_SEARCH_CONTAINER).querySelector(`#${c.id}`).getElementsByClassName(Cl);if(m.length>0){let y=m.item(0).getElementsByClassName("icon-tooltip");y.length>0&&y.item(0).style.removeProperty("display")}}}),h===t.id&&t){if(typeof t.color=="object"){let m=t.color;l.style.setProperty("background-color",`rgba(${m.red}, ${m.green}, ${m.blue}, ${Lr})`,"important")}else if(ht.isHexColor(t.color)){let m=ht.hexToRgbChannels(t.color);l.style.setProperty("background-color",`rgba(${m.red}, ${m.green}, ${m.blue}, ${Lr})`,"important")}else l.classList.remove("hover");let d=i.getElementById(et.R2_ID_SEARCH_CONTAINER).querySelector(`#${t.id}`).getElementsByClassName(Cl);if(d.length>0){let m=d.item(0).getElementsByClassName("icon-tooltip");m.length>0&&m.item(0).style.removeProperty("display")}}}}isIOS(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}isAndroid(){return navigator.userAgent.match(/Android/i)!=null}async processMouseEvent(t){let n=this.delegate.iframes[0].contentWindow?.document,i=t.clientX,o=t.clientY;if(!n||!n.getElementById(et.R2_ID_HIGHLIGHTS_CONTAINER)&&!n.getElementById(et.R2_ID_SEARCH_CONTAINER)&&!n.getElementById(et.R2_ID_PAGEBREAK_CONTAINER)&&!n.getElementById(et.R2_ID_READALOUD_CONTAINER)&&!n.getElementById(et.R2_ID_DEFINITIONS_CONTAINER))return;let s=this.delegate.view?.isPaginated(),l=n.body.getBoundingClientRect(),h=this.getScrollingElement(n),c=s?-h.scrollLeft:l.left,d=s?-h.scrollTop:l.top,m,y;for(let w=yn.length-1;w>=0;w--){let v=yn[w],g=n.getElementById(`${v.id}`);if(!g){let b=n.getElementById(et.R2_ID_HIGHLIGHTS_CONTAINER);b&&(g=b.querySelector(`#${v.id}`))}if(!g)continue;let f=!1,p=g.querySelectorAll(`.${$n}`);for(let b of p){let S=b,C=S.rect.left+c,x=S.rect.top+d;if(i>=C&&i<C+S.rect.width&&o>=x&&o<x+S.rect.height){f=!0;break}}if(f){m=v,y=g;break}}if(!m||!y){for(let w in et){let v=n.getElementById(w);if(v){let g=v.querySelectorAll(`.${xl}`);for(let p of g)this.resetHighlightBoundingStyle(p);let f=Array.from(v.querySelectorAll(`.${$n}`));for(let p of f)this.resetHighlightAreaStyle(p,w)}}return}if(y.getAttribute("data-click")){if((t.type==="mousemove"||t.type==="touchmove")&&y.parentElement?.style.display!=="none"){let w=Array.from(y.querySelectorAll(`.${$n}`));for(let g in et){let f=n.getElementById(g);if(f){let p=f.querySelectorAll(`.${$n}`);for(let b of p)w.indexOf(b)<0&&this.resetHighlightAreaStyle(b,g)}}this.setHighlightAreaStyle(n,w,m);let v=y.querySelector(`.${xl}`);for(let g in et){let f=n.getElementById(g);if(f){let p=f.querySelectorAll(`.${xl}`);for(let b of p)(!v||b!==v)&&this.resetHighlightBoundingStyle(b)}}}else if((t.type==="mouseup"||t.type==="click"||t.type==="touchup")&&y.parentElement?.style.display!=="none"){let w={highlight:m};yi.default.log(JSON.stringify(w));let v=this,g;if(v.delegate.rights.enableAnnotations?g=await this.delegate.annotationModule?.getAnnotation(w.highlight):v.delegate.rights.enableBookmarks&&(g=await this.delegate.bookmarkModule?.getAnnotation(w.highlight)),w.highlight.type===mt.Annotation&&this.delegate.annotationModule?.api?.selectedAnnotation(g).then(async()=>{}),g?.id){yi.default.log("selected highlight "+g.id),v.lastSelectedHighlight=g.id;let f=document.getElementById("highlight-toolbox");if(f)if(f.style.top=t.clientY+(this.delegate.attributes?.navHeight??0)+"px",f.style.left=t.clientX+"px",getComputedStyle(f).display==="none"){let S=function(){v.delegate.annotationModule?.api?.addCommentToAnnotation(g).then(O=>{v.delegate.annotationModule?.updateAnnotation(O).then(async()=>{yi.default.log("update highlight "+O.id),f&&(f.style.display="none"),v.selectionMenuClosed()}),f&&(f.style.display="none"),v.selectionMenuClosed(),C?.removeEventListener("click",S,!1)})},E=function(){v.delegate.rights.enableAnnotations?v.delegate.annotationModule?.deleteSelectedHighlight(g).then(async()=>{yi.default.log("delete highlight "+g.id),f&&(f.style.display="none"),v.selectionMenuClosed()}):v.delegate.rights.enableBookmarks&&v.delegate.bookmarkModule?.deleteSelectedHighlight(g).then(async()=>{yi.default.log("delete highlight "+g.id),f&&(f.style.display="none"),v.selectionMenuClosed()})};f.style.display="block",this.toolboxMode("edit");let p=document.getElementById("colorIcon"),b=document.getElementById("highlightIcon");p&&(p.style.display="none"),b&&(b.style.display="none");let C=document.getElementById("commentIcon"),x=document.getElementById("cloneCommentIcon");if(x){let O=x.parentElement;O&&O.removeChild(x)}if(C){C.style.display="none";let O=C.cloneNode(!0),L=C.parentElement;O.style.display="unset",O.id="cloneCommentIcon",O.addEventListener("click",S,!1),L&&L.append(O)}let T=document.getElementById("deleteIcon"),R=document.getElementById("cloneDeleteIcon");if(R){let O=R.parentElement;O&&O.removeChild(R)}if(T){T.style.display="none";let O=T.cloneNode(!0),L=T.parentElement;O.style.display="unset",O.id="cloneDeleteIcon",O.addEventListener("click",E,!1),L&&L.append(O)}}else f.style.display="none",this.selectionMenuClosed(),f.offsetWidth,f.style.display="block"}else{y.dataset.definition&&new _l(this.delegate).showPopup(y.dataset.definition,t);let f=this.delegate.definitionsModule?.properties?.definitions?.filter(p=>p.order===Number(y?.dataset.order))[0];yi.default.log(f),this.delegate.definitionsModule?.api?.click&&(this.delegate.definitionsModule.api?.click(j0.omit(f,"callbacks"),j0.omit(m,"definition")),this.delegate.emit("definition.click",f,m))}}}}async prepareContainers(t){for(let n in et)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!==et.R2_ID_GUTTER_RIGHT_CONTAINER&&o.style.setProperty("pointer-events","none"),this.delegate.view?.layout==="fixed"&&(o.style.setProperty("position","absolute"),o.style.setProperty("top","0"),o.style.setProperty("left","0")),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(et.R2_ID_HIGHLIGHTS_CONTAINER)),this.removeAllChildNodes(t.getElementById(et.R2_ID_SEARCH_CONTAINER)),this.removeAllChildNodes(t.getElementById(et.R2_ID_READALOUD_CONTAINER)),this.removeAllChildNodes(t.getElementById(et.R2_ID_PAGEBREAK_CONTAINER)),this.removeAllChildNodes(t.getElementById(et.R2_ID_DEFINITIONS_CONTAINER))}destroyAllhighlights(t){this.hideAllhighlights(t),yn.splice(0,yn.length)}removeAllChildNodes(t){for(;t.firstChild;)t.removeChild(t.firstChild)}destroyHighlights(t){let n=this.delegate.iframes[0].contentWindow?.document;if(n){let i;switch(t){case mt.ReadAloud:i=n.getElementById(et.R2_ID_READALOUD_CONTAINER),i&&this.removeAllChildNodes(i);break;case mt.Search:i=n.getElementById(et.R2_ID_SEARCH_CONTAINER),i&&this.removeAllChildNodes(i);break;case mt.PageBreak:i=n.getElementById(et.R2_ID_PAGEBREAK_CONTAINER),i&&this.removeAllChildNodes(i);break;case mt.Definition:i=n.getElementById(et.R2_ID_DEFINITIONS_CONTAINER),i&&this.removeAllChildNodes(i);break;case mt.LineFocus:i=n.getElementById(et.R2_ID_LINEFOCUS_CONTAINER),i&&this.removeAllChildNodes(i);break;case mt.Comment:i=n.getElementById(et.R2_ID_GUTTER_RIGHT_CONTAINER),i&&this.removeAllChildNodes(i);break;default:i=n.getElementById(et.R2_ID_HIGHLIGHTS_CONTAINER),i&&this.removeAllChildNodes(i),yn.splice(0,yn.length);break}}}destroyHighlight(t,n){if(!t)return;let i=-1;yn.find((l,h)=>(i=h,l.id===n))&&i>=0&&i<yn.length&&yn.splice(i,1);let s=t.getElementById(n);s&&this.removeAllChildNodes(s)}createHighlight(t,n,i,o,s,l,h,c,d,m){try{let y=`${n.rangeInfo.startContainerElementCssSelector}${n.rangeInfo.startContainerChildTextNodeIndex}${n.rangeInfo.startOffset}${n.rangeInfo.endContainerElementCssSelector}${n.rangeInfo.endContainerChildTextNodeIndex}${n.rangeInfo.endOffset}`,w=er.hash(y),v=(m||"R2_HIGHLIGHT_")+w;this.destroyHighlight(t.document,v);let g=`rgb(${gs.red}, ${gs.green}, ${gs.blue})`,f={color:i||g,id:v,pointerInteraction:o,selectionInfo:n,marker:s,icon:l,popup:h,style:c,type:d||mt.Annotation};(d===mt.Annotation||d===mt.Definition||d===void 0)&&yn.push(f);let p=this.createHighlightDom(t,f);return f.position=parseInt((p?.hasChildNodes()?p.childNodes[0]:p).style.top.replace("px","")),[f,p]}catch(y){throw"Can't create highlight: "+y}}createHighlightDom(t,n){let i=t.document,o=Wd(i,n.selectionInfo.rangeInfo);if(!o)return;for(let F in et)this.ensureHighlightsContainer(t,F);let s=i.createElement("div");s.setAttribute("id",n.id),s.setAttribute("class",Q_),s.style.setProperty("pointer-events","none"),n.pointerInteraction&&s.setAttribute("data-click","1");let l=this.delegate.view?.isPaginated();l?i.body.style.position="revert":i.body.style.position="relative";let h=i.body.getBoundingClientRect(),c=this.getScrollingElement(i),d=l?-c.scrollLeft:h.left,m=l?-c.scrollTop:h.top,y=1,w=!1,v=!1,p=$d(o,w||v||!1),b=3,S=2,C=3,x=0,E=24,T,R;for(let F of p){let q=i.createElement("div");q.setAttribute("class",$n),q.dataset.marker=""+n.marker;let G="";if(w&&n.marker!==ot.Custom&&n.marker!==ot.Bookmark&&n.marker!==ot.Comment){let D=n.color;ht.isHexColor(D)&&(D=ht.hexToRgbChannels(D)),G+=`border-bottom: ${S*y}px solid rgba(${D.red}, ${D.green}, ${D.blue}, ${Lr}) !important`}if(n.marker===ot.Custom||n.marker===ot.Bookmark)if(n.style?.default){for(let D=0;D<n.style?.default?.length;D++){let W=n.style?.default[D];G+=`${W.property}: ${W.value} !${W.priority};`}q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${b}px !important; ${G}`)}else n.style?.defaultClass&&(q.classList.add(n.style?.defaultClass),q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${b}px !important; ${G}`));else if(n.marker===ot.Underline||n.marker===ot.Comment)if(typeof n.color=="object"){let D=n.color;q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${b}px !important; background-color: rgba(${D.red}, ${D.green}, ${D.blue}, ${0}) !important; ${G}`),q.style.setProperty("border-bottom",`2px solid rgba(${D.red}, ${D.green}, ${D.blue}, ${1})`,"important")}else if(ht.isHexColor(n.color)){let D=ht.hexToRgbChannels(n.color);q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${b}px !important; background-color: rgba(${D.red}, ${D.green}, ${D.blue}, ${0}) !important; ${G}`),q.style.setProperty("border-bottom",`2px solid rgba(${D.red}, ${D.green}, ${D.blue}, ${1})`,"important")}else q.setAttribute("style",`border-radius: ${b}px !important; ${G}`);else if(typeof n.color=="object"){let D=n.color;q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${b}px !important; background-color: rgba(${D.red}, ${D.green}, ${D.blue}, ${Lr}) !important; ${G}`)}else if(ht.isHexColor(n.color)){let D=ht.hexToRgbChannels(n.color);q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${b}px !important; background-color: rgba(${D.red}, ${D.green}, ${D.blue}, ${Lr}) !important; ${G}`)}else q.setAttribute("style",`border-radius: ${b}px !important; ${G}`);q.style.setProperty("pointer-events","none"),q.style.position="absolute",q.scale=y,q.rect={height:F.height,left:F.left-d,top:F.top-m,width:F.width},n.pointerInteraction&&(q.setAttribute("data-click","1"),q.tabIndex=0),q.style.width=`${q.rect.width*y}px`,q.style.height=`${q.rect.height*y}px`,q.style.left=`${q.rect.left*y}px`,q.style.top=`${q.rect.top*y}px`,s.append(q);let ie=parseInt(q.style.top.replace("px",""));if((ie<x||x===0)&&(x=ie),E=parseInt(q.style.height.replace("px","")),v){let D=i.createElement("div");D.setAttribute("class",$n);let W=n.color;ht.isHexColor(W)&&(W=ht.hexToRgbChannels(W)),D.setAttribute("style",`background-color: rgba(${W.red}, ${W.green}, ${W.blue}, ${Lr}) !important;`),D.style.setProperty("pointer-events","none"),D.style.position="absolute",D.scale=y,D.rect={height:F.height,left:F.left-d,top:F.top-m,width:F.width},D.style.width=`${D.rect.width*y}px`,D.style.height=`${C*y}px`,D.style.left=`${D.rect.left*y}px`,D.style.top=`${(D.rect.top+D.rect.height/2-C/2)*y}px`,s.append(D)}let ee=this.delegate.iframes[0].contentWindow?.innerWidth,Z=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-count")),X=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-width")),ce=parseInt(getComputedStyle(i.body).getPropertyValue("padding-left")),we=ee/(Z||1);we<X&&(we=ee),l||(we=parseInt(getComputedStyle(i.body).width.replace("px","")));let ve=this.delegate.settings.fontSize/100,Q=20*ve;ve<=1&&(Q=-60);let N=0*ve;ve<=1&&(N=-60),T=Math.floor(F.left/we)*we+we-(E<40?40:E)+N,R=Math.floor(F.left/we)*we+(E<40?40:E)-Q;let B=parseInt(this.delegate.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));B>=2&&(R=R+ce/Z,T=T-ce/Z),l||(T=parseInt(getComputedStyle(this.delegate.iframes[0].contentDocument?.body).width.replace("px","")),R=parseInt(getComputedStyle(this.delegate.iframes[0].contentDocument?.body).width.replace("px",""))-we,B>=2&&(R=R+ce/2,T=T-ce/2))}let O=o.getBoundingClientRect(),L=i.createElement("div");L.setAttribute("class",xl),L.style.setProperty("pointer-events","none"),L.style.position="absolute",L.scale=y,L.rect={height:O.height,left:O.left-d,top:O.top-m,width:O.width},L.style.width=`${L.rect.width*y}px`,L.style.height=`${L.rect.height*y}px`,L.style.left=`${L.rect.left*y}px`,L.style.top=`${L.rect.top*y}px`,s.append(L);let M=i.createElement("div");if(M.setAttribute("class",Cl),n.icon?.position==="left")M.setAttribute("style",`position: absolute;top:${x}px;left:${R+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`);else if(n.icon?.position==="inline")M.setAttribute("style",`position: absolute;top:${x-E/2}px;left:${parseInt(L.style.left.replace("px",""))+parseInt(L.style.width.replace("px",""))-E/2}px;height:${E}px; width:${E}px;`);else if(n.icon?.position==="center"){let q=E/3*2;M.setAttribute("style",`position: absolute;top:${x}px;left:${parseInt(L.style.left.replace("px",""))+parseInt(L.style.width.replace("px",""))-q}px;height:${E}px; width:${E}px;`)}else n.note&&n.marker!==ot.Custom&&n.marker!==ot.Bookmark&&n.marker!==ot.Comment&&n.marker!==ot.Highlight&&n.marker!==ot.Underline?M.setAttribute("style",`position: absolute;top:${x-E/2}px;left:${parseInt(L.style.left.replace("px",""))+parseInt(L.style.width.replace("px",""))-E/2}px;height:${E}px; width:${E}px;`):n.note&&n.marker===ot.Comment||n.marker===ot.Highlight||n.marker===ot.Underline?M.setAttribute("style",`position: absolute;top:${x}px;left:${T+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`):M.setAttribute("style",`position: absolute;top:${x}px;left:${T+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`);if(n.marker===ot.Custom||n.marker===ot.Bookmark)n.icon?.class?(M.classList.add(n.icon?.class),M.id=n.icon?.id):n.icon?.svgPath?M.innerHTML=ma(`${n.icon?.id}`,`${n.icon?.title}`,`${n.icon?.svgPath}`,"icon open",E,`${n.icon?.color} !important`):n.icon?.title&&(M.innerHTML=n.icon?.title);else if(n.note){let F=n.color;ht.isHexColor(F)&&(F=ht.hexToRgbChannels(F)),n.marker===ot.Comment||n.marker===ot.Highlight||n.marker===ot.Underline?M.innerHTML=ma("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",E/2,`rgba(${F.red}, ${F.green}, ${F.blue}, 1) !important`):M.innerHTML=ma("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(${F.red}, ${F.green}, ${F.blue}, 1) !important`)}M.style.setProperty("pointer-events","all");let k=this;if(n.type!==mt.PageBreak&&n.type!==mt.Definition&&M.addEventListener("click",async function(F){let q;k.delegate.rights.enableAnnotations?(q=await k.delegate.annotationModule?.getAnnotationByID(n.id),k.delegate.annotationModule?.api?.selectedAnnotation(q).then(async()=>{})):k.delegate.rights.enableBookmarks&&(q=await k.delegate.bookmarkModule?.getAnnotationByID(n.id)),yi.default.log("selected highlight "+q.id),k.lastSelectedHighlight=q.id;let G=document.getElementById("highlight-toolbox");if(G)if(G.style.top=F.clientY+(k.delegate.attributes?.navHeight??0)+"px",G.style.left=F.clientX+"px",getComputedStyle(G).display==="none"){let we=function(){k.delegate.rights.enableAnnotations?k.delegate.annotationModule?.deleteSelectedHighlight(q).then(async()=>{yi.default.log("delete highlight "+q.id),G.style.display="none",k.selectionMenuClosed()}):k.delegate.rights.enableBookmarks&&k.delegate.bookmarkModule?.deleteSelectedHighlight(q).then(async()=>{yi.default.log("delete highlight "+q.id),G.style.display="none",k.selectionMenuClosed()})};G.style.display="block",k.toolboxMode("edit");let ee=document.getElementById("colorIcon"),Z=document.getElementById("highlightIcon");ee&&(ee.style.display="none"),Z&&(Z.style.display="none");let X=document.getElementById("commentIcon"),ce=document.getElementById("cloneCommentIcon");if(ce){let N=ce.parentElement;N&&N.removeChild(ce)}X&&(X.style.display="none");let ve=document.getElementById("deleteIcon"),Q=document.getElementById("cloneDeleteIcon");if(Q){let N=Q.parentElement;N&&N.removeChild(Q)}if(ve){ve.style.display="none";let N=ve.cloneNode(!0),B=ve.parentElement;N.style.display="unset",N.id="cloneDeleteIcon",N.addEventListener("click",we,!1),B&&B.append(N)}}else G.style.display="none",k.selectionMenuClosed(),G.offsetWidth,G.style.display="block";let ie=Array.from(s.querySelectorAll(`.${$n}`));k.setHighlightAreaStyle(i,ie,n)}),n.note){let F=document.createElement("span");F.innerHTML=n.note,F.className="icon-tooltip",n.marker===ot.Custom||n.marker===ot.Bookmark?(n.popup?.background&&F.style.setProperty("background",n.popup.background),n.popup?.textColor&&F.style.setProperty("color",n.popup.textColor),n.popup?.class&&F.classList.add(n.popup.class)):(F.style.setProperty("background","lightyellow"),F.style.setProperty("color","black"))}switch((n.note||n.marker===ot.Custom||n.marker===ot.Bookmark)&&s.append(M),n.type){case mt.Search:i.getElementById(et.R2_ID_SEARCH_CONTAINER).append(s);break;case mt.ReadAloud:i.getElementById(et.R2_ID_READALOUD_CONTAINER).append(s);break;case mt.PageBreak:i.getElementById(et.R2_ID_PAGEBREAK_CONTAINER).append(s);break;case mt.Definition:i.getElementById(et.R2_ID_DEFINITIONS_CONTAINER).append(s);break;default:i.getElementById(et.R2_ID_HIGHLIGHTS_CONTAINER).append(s);break}return s}addSelectionMenuItem(t){(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).push(t)}};var hS=gt(X0());H();var RD=gt(cn());var Lo={className:r=>!0,idName:r=>!0,tagName:r=>!0};var fS=gt(Gd()),nr=gt(cn());H();var dS=gt(cn()),ms;(function(n){n.BookmarkCreated="BookmarkCreated",n.HighlightCreated="HighlightCreated"})(ms||(ms={}));var Z0=class{constructor(t,n,i,o){this.currSeconds=0;this.delegate=t,this.publication=n,this.properties=i,this.api=o}static async create(t){let n=new this(t.delegate,t.publication,t,t.api);return await n.start(),n}async start(){this.delegate.consumptionModule=this,this.startResearchSession()}async stop(){dS.default.log("Consumption module stop"),this.updateResearchSession()}initialize(){let t=this.delegate.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){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){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)}}startIdleTimer(){this.currSeconds++,this.currSeconds==this.properties.idleTimeout&&(this.api?.idleSince(this.currSeconds),this.updateResearchSession()),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 Ol=class{constructor(t,n,i,o,s,l,h,c,d){this.hide=$e(document,"#menu-button-hide");this.show=$e(document,"#menu-button-show");this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=d,this.delegate=o,this.initialAnnotations=s,this.highlighter=h,this.properties=l,this.api=c}static async create(t){let n=new this(t.annotator,t.rights||{enableAnnotations:!1,enableTTS:!1},t.publication,t.delegate,t.initialAnnotations||null,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){nr.default.log("Annotation module stop")}async start(){if(this.delegate.annotationModule=this,this.headerMenu&&(this.highlightsView=$e(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var t=this.initialAnnotations.highlights||null;t&&this.annotator?.initAnnotations(t)}setTimeout(()=>{this.properties?.hideLayer?this.delegate.hideLayer("highlights"):this.delegate.showLayer("highlights")},10)}hideAnnotationLayer(){let t=this.delegate.iframes[0].contentDocument;if(t){let n=$e(t,"#R2_ID_HIGHLIGHTS_CONTAINER");n&&(n.style.display="none")}this.show&&this.hide&&(this.show.style.display="block",this.hide.style.display="none")}showAnnotationLayer(){let t=this.delegate.iframes[0].contentDocument;if(t){let n=$e(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(),Ce(this.delegate.iframes[0].contentDocument?.body,"click",this.click.bind(this))},300),t(null)})}click(t){if(this.activeAnnotationMarkerId){let n=this.highlighter?.properties?.selectionMenuItems?.filter(i=>i.id===this.activeAnnotationMarkerId);if(n&&n?.length>0){let i=fS.cloneDeep(n[0]);i.marker=ot.Custom,this.activeAnnotationMarkerPosition&&(i.icon.position=this.activeAnnotationMarkerPosition),i.highlight.style.default=null,i.highlight.style.hover=null;let o=this.delegate.iframes[0].contentDocument;if(o){let d=function(y){try{let w=c.delegate.iframes[0].contentDocument;return w?Nn(y,w,Lo):""}catch(w){return nr.default.log("uniqueCssSelector:"),nr.default.error(w),""}},s=this.highlighter?.dom(o.body).getSelection(),l=s.getRangeAt(0),h=s.anchorNode;l.setStart(h,l.startOffset),l.setEnd(h,l.endOffset+1),s.removeAllRanges(),s.addRange(l);let c=this,m=oo(l,d);if(s.removeAllRanges(),m){let y={rangeInfo:m},w=this.delegate.highlighter?.createHighlight(this.delegate.highlighter?.dom(o.body).getWindow(),y,i.highlight.color,!0,ot.Bookmark,i.icon,i.popup,i.highlight.style);w&&this.saveAnnotation(w[0]).then(v=>{nr.default.log("saved bookmark "+v.id)})}o.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(t){nr.default.log("still need to scroll to "+t);var n=await this.annotator?.getAnnotationElement(t,this.delegate.iframes[0].contentWindow);n.scrollIntoView({block:"center",behavior:"smooth"})}async updateLocalHighlight(t){if(this.annotator){let n=await this.annotator.deleteAnnotation(t.id),i=await this.addAnnotation(t);return nr.default.log("Highlight deleted "+JSON.stringify(n)),nr.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 nr.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.delegate.currentChapterLink.href);this.delegate.currentTocUrl&&(n=this.publication.getTOCItem(this.delegate.currentTocUrl)),n===void 0&&(n=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href));let i=this.delegate.view?.getCurrentPosition(),o=this.delegate.iframes[0].contentDocument;if(o){let s=Qr(o,"body"),l=t.position?t.position/s.scrollHeight:i,h=(0,hS.v4)(),c;if(n){let d=n.Href;if(d.indexOf("#")>0&&(d=d.slice(0,d.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let m=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),y=Math.ceil((l??0)*(m.length-1)),w=m[y];c=nn(dt({},w),{id:h,href:d,created:new Date,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else c={id:h,href:d,locations:{progression:l},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(c)if(this.delegate.consumptionModule?.trackAction(c,ms.HighlightCreated),this.api?.addAnnotation)try{let d=await this.api.addAnnotation(c),m=await this.annotator.saveAnnotation(d);return await this.showHighlights(),await this.drawHighlights(),new Promise(y=>y(m))}catch(d){await this.showHighlights(),await this.drawHighlights()}else{let d=await this.annotator.saveAnnotation(c);return await this.showHighlights(),await this.drawHighlights(),new Promise(m=>m(d))}}}return new Promise(i=>i(null))}getAnnotations(){let t=[];return this.annotator&&(t=this.annotator.getAnnotations()),t}showHighlights(){let t=[];this.annotator&&(t=this.annotator.getAnnotations(),t&&(t=t.filter(n=>n.highlight.marker!==ot.Bookmark),t.forEach(n=>{yn.push(n.highlight)}))),this.highlightsView&&this.createTree(Fi.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.delegate.currentLocator().href)),this.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(mt.Annotation);for(let i of n){yn.push(i.highlight);let o=i,s=this.delegate.currentChapterLink.href;var t=this.publication.getTOCItem(s);if(this.delegate.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&(await this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===ot.Underline){let h=await this.annotator?.getAnnotationPosition(i.id,this.delegate.iframes[0].contentWindow),c='<div class="comment" style="top: '+h+'px;width:20px"></div>',d=document.createElement("div");d.innerHTML=c;let m=d.childNodes[0],y=document.createElement("i");y.innerHTML="sticky_note_2",y.className="material-icons",y.style.color=o.highlight.color,m.appendChild(y),Ce(d,"click",w=>{w.preventDefault(),w.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}else{let n=[];if(this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.delegate.currentLocator().href)),this.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(mt.Annotation);for(let i of n){yn.push(i.highlight);let o=i,s=this.delegate.currentChapterLink.href,l=this.publication.getTOCItem(s);if(this.delegate.currentTocUrl&&(l=this.publication.getTOCItem(this.delegate.currentTocUrl)),l===null&&(l=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),l){let h=l.Href;h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),o.href===h&&(await this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===ot.Underline){let c=await this.annotator?.getAnnotationPosition(i.id,this.delegate.iframes[0].contentWindow),d='<div class="comment" style="top: '+c+"px;background: "+o.highlight?.color+';width:20px"></div>',m=document.createElement("div");m.innerHTML=d,m.childNodes[0].innerHTML=mr.note,Ce(m,"click",y=>{y.preventDefault(),y.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){let t=this.delegate.iframes[0].contentDocument;if(t&&(this.commentGutter=t.getElementById(et.R2_ID_GUTTER_RIGHT_CONTAINER),this.delegate.view?.isScrollMode()&&this.properties?.enableComments?this.commentGutter?.style.removeProperty("display"):this.commentGutter?.style.setProperty("display","none"),this.commentGutter&&this.delegate.view?.isScrollMode())){this.commentGutter.innerHTML="";let n=[];this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.delegate.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 s=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),l,h;s&&(l=s.querySelector(`#${i.highlight.id}`)),h=l.getElementsByClassName($n)[0];let d=parseInt(h.style.height.replace("px","")),m=i.highlight.position,y=t.createElement("div");y.setAttribute("style",`position: absolute;top:${m}px;display: flex;max-width: 250px !important;height:${d}px;width: 200px;align-items: center;`);let w=t.createElement("div");y.appendChild(w);let v=i.highlight.color;ht.isHexColor(v)&&(v=ht.hexToRgbChannels(v)),y.innerHTML=ma("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="8"/>',"icon open",10,`rgba(${v.red}, ${v.green}, ${v.blue}, 1) !important`);let g=t.createElement("div");g.innerHTML=i.highlight?.note,g.setAttribute("style",`height:${d}px;overflow: hidden;padding-left: 5px;`),y.appendChild(g),Ce(y,"click",f=>{f.preventDefault(),f.stopPropagation(),this.scrollToHighlight(i.highlight.id)}),this.commentGutter?.appendChild(y)})))}}createTree(t,n,i){if(n){let o=this,s=this.publication.readingOrder;if(s.length){let l=(h,c)=>{let d=document.createElement("ul");d.className="sidenav-annotations";for(let m of c){let y=document.createElement("li"),w=document.createElement("a"),v=document.createElement("span");if(w.tabIndex=-1,w.className="chapter-link",m.Href){let f=this.publication.getAbsoluteHref(m.Href),p=this.publication.getTOCItemAbsolute(f);w.href=f,w.innerHTML=p?.Title||"",y.appendChild(w)}else v.innerHTML=m.Title||"",v.className="chapter-title",y.appendChild(v);Ce(w,"click",f=>{f.preventDefault(),f.stopPropagation();let p={href:w.href,locations:{progression:0},type:m.TypeLink,title:w.title};this.delegate.stopReadAloud(),this.delegate.navigate(p)});let g=document.createElement("ol");n.forEach(function(f){let p=m.Href.indexOf("#")!==-1?m.Href.slice(0,m.Href.indexOf("#")):m.Href;if(m.Href&&f.href.endsWith(p)){let b=document.createElement("li");b.className="annotation-item";let S=document.createElement("a");if(S.setAttribute("href",f.href),t===Fi.Annotation){S.className="highlight-link";let x=document.createElement("span"),E=document.createElement("span");if(x.className="title",E.innerHTML=f.highlight.selectionInfo.cleanText,f.highlight?.marker===ot.Underline)if(typeof f.highlight?.color=="object"){let O=f.highlight?.color;O&&E.style.setProperty("border-bottom",`2px solid ${ht.hexToRgbA(O)}`,"important")}else E.style.setProperty("border-bottom",`2px solid ${f.highlight?.color}`,"important");else if(typeof f.highlight?.color=="object"){let O=f.highlight?.color;O&&(E.style.backgroundColor=ht.hexToRgbA(O))}else{let O=f.highlight?.color;O&&(E.style.backgroundColor=O)}x.appendChild(E),S.appendChild(x);let T=document.createElement("span"),R=Math.round((f.locations.progression??0)*100)+"% through resource";T.className="subtitle",T.innerHTML=R,S.appendChild(T)}let C=document.createElement("span");if(C.className="timestamp",C.innerHTML=Ol.readableTimestamp(f.created),S.appendChild(C),Ce(S,"click",x=>{x.preventDefault(),x.stopPropagation(),o.handleAnnotationLinkClick(x,f)}),b.appendChild(S),o.delegate.sideNavExpanded){let x=document.createElement("button");x.className="delete",x.innerHTML=mr.delete,Ce(x,"click",E=>{E.preventDefault(),E.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,E,f)}),b.appendChild(x)}g.appendChild(b)}}),g.children.length>0&&(d.appendChild(y),d.appendChild(g)),d.children.length>0&&h.appendChild(d),m.Children&&m.Children.length>0&&l(h,m.Children)}};i.innerHTML="",l(i,s)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.delegate.stopReadAloud(),this.delegate.navigate(n)):nr.default.log("annotation data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){nr.default.log("annotation data locator: ",i),i?t===Fi.Annotation&&this.deleteHighlight(i):nr.default.log("annotation data missing: ",n)}static readableTimestamp(t){let n=new Date(t);return n.toDateString()+" "+n.toLocaleTimeString()}async getAnnotation(t){return this.annotator?.getAnnotation(t)}async getAnnotationByID(t){return this.annotator?.getAnnotationByID(t)}syncPosition(t){let n=this.delegate.iframes[0].contentDocument,i=(o,s)=>{let l=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),h,c;l&&(h=l.querySelector(`#${s.highlight.id}`)),c=h.getElementsByClassName($n)[0];let m=parseInt(c.style.top.replace("px","")),y=nn(dt({},s),{highlight:nn(dt({},s.highlight),{position:m})});return[...o,y]};return t.reduce(i,[])}reposition(t){let n=this.delegate.iframes[0].contentDocument,i=(o,s,l)=>{let h=t[0],c=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),d,m;c&&(d=c.querySelector(`#${h.highlight.id}`)),m=d.getElementsByClassName($n)[0];let w=parseInt(m.style.height.replace("px","")),v=s.highlight.position,g=o[l-1]&&o[l-1].highlight.position,p=l===0?0:g+w+0,b=p>v?p:v,S=nn(dt({},s),{highlight:nn(dt({},s.highlight),{position:b})});return[...o,S]};return t.sort(function(o,s){return o.highlight.position-s.highlight.position}).reduce(i,[])}};H();var Q0=gt(X0());var ir=gt(cn());var Rl=class{static async create(t){let n=new this(t.annotator,t.rights||{enableBookmarks:!1},t.publication,t.delegate,t,t.initialAnnotations,t.api,t.headerMenu);return await n.start(),new Promise(i=>i(n))}constructor(t,n,i,o,s,l,h,c){this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=c,this.delegate=o,this.initialAnnotations=l,this.properties=s,this.api=h}stop(){ir.default.log("Bookmark module stop")}async start(){if(this.delegate.bookmarkModule=this,this.headerMenu&&(this.bookmarksView=$e(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=$e(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let t=$e(this.headerMenu,"#menu-button-bookmark");t&&t.parentElement?.style.removeProperty("display"),t&&Ce(t,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let t=this.initialAnnotations.bookmarks||null;t&&this.annotator?.initBookmarks(t)}await this.showBookmarks(),await this.drawBookmarks(),setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("highlights"):this.delegate.showLayer("highlights")},10)}async handleResize(){setTimeout(async()=>{await this.drawBookmarks(),await this.showBookmarks()},100)}initialize(){return new Promise(async t=>{await document.fonts.ready,this.rights.enableBookmarks&&setTimeout(()=>{this.drawBookmarks(),this.showBookmarks()},300),t(null)})}async deleteBookmark(t){if(this.annotator)if(this.api?.deleteBookmark){await this.api?.deleteBookmark(t);let n=await this.annotator.deleteBookmark(t);return ir.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else{let n=await this.annotator.deleteBookmark(t);return ir.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else return new Promise(n=>n(null))}async saveBookmarkPlus(){await this.addBookmarkPlus()}async saveBookmark(){if(this.annotator){var t=this.publication.getTOCItem(this.delegate.currentChapterLink.href);if(this.delegate.currentTocUrl&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let n=t.Href;n.indexOf("#")>0&&(n=n.slice(0,n.indexOf("#")));let i=this.delegate.view?.getCurrentPosition(),o=(0,Q0.v4)(),s;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let l=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),h=Math.ceil((i??0)*(l.length-1)),c=l[h];s=nn(dt({},c),{id:o,href:n,created:new Date,title:this.delegate.currentChapterLink.title})}else s={id:o,href:n,locations:{progression:i},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title};if(!this.annotator.locatorExists(s,Fi.Bookmark))if(this.delegate.consumptionModule?.trackAction(s,ms.BookmarkCreated),this.api?.addBookmark){let l=await this.api.addBookmark(s);l&&(s=l),ir.default.log(s);let h=this.annotator.saveBookmark(s);return ir.default.log("Bookmark added "+JSON.stringify(h)),this.showBookmarks(),await this.drawBookmarks(),h}else{let l=this.annotator.saveBookmark(s);return ir.default.log("Bookmark added "+JSON.stringify(l)),this.showBookmarks(),await this.drawBookmarks(),l}}}}async addBookmarkPlus(){let t=this,n=this.delegate.highlighter?.visibleTextRects[0],i=this.delegate.iframes[0].contentDocument;if(i){let h=this.delegate.highlighter?.dom(i.body).getWindow().document.createRange(),c=this.delegate.highlighter?.dom(this.delegate.iframes[0].contentDocument?.body).getSelection();c.removeAllRanges(),n&&h.selectNodeContents(n.node),c.addRange(h);let d=$d(h,!1),m=0;for(let y of d){if(!this.delegate.highlighter?.isOutsideViewport(y)){let w=c.focusNode,v=c.focusOffset;c.collapse(c.anchorNode,c.anchorOffset);for(let b=0;b<m;b++)c.modify("move","forward","line");c.extend(w,v);let g=c.focusNode,f=c.focusNode.length;c.collapse(c.anchorNode,c.anchorOffset);let p=f;c.anchorOffset>f?p=f:p=c.anchorOffset+1,c.modify("move","forward","character"),c.modify("move","backward","word"),c.extend(g,p),c.modify("extend","backward","character"),c.modify("extend","forward","word");break}m++}}function o(h){let c={},d=t.delegate.iframes[0].contentDocument;if(d)return Nn(h,t.delegate.highlighter?.dom(d.body).getDocument(),c)}let s=this.delegate.iframes[0].contentWindow,l={id:"bookmarkIcon",marker:ot.Bookmark,icon:{id:"bookmarkIcon",title:"Bookmark",svgPath:'<path d="M0 0h24v24H0V0z" fill="none"/><path d="M17 3H7c-1.1 0-2 .9-2 2v16l7-3 7 3V5c0-1.1-.9-2-2-2z"/>',color:"#000000",position:"left"},popup:{background:"#000000",textColor:"#ffffff"},highlight:{color:"#000000",style:{default:[{property:"border-bottom",value:"0px dashed #000000",priority:"important"}]}}};if(s!==null){let h=Ir(s,o);if(h===void 0){let d=t.delegate.iframes[0].contentDocument;h=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(d)}let c=t.delegate.iframes[0].contentDocument;if(h&&c){let d=this.delegate.highlighter?.createHighlight(this.delegate.highlighter?.dom(c.body).getWindow(),h,l.highlight?.color,!0,ot.Bookmark,l.icon,l.popup,l.highlight?.style);if(this.delegate.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),d)return this.saveAnnotation(d[0]).then(m=>{ir.default.log("saved bookmark "+m?.id)})}}}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.delegate.currentChapterLink.href);this.delegate.currentTocUrl&&(n=this.publication.getTOCItem(this.delegate.currentTocUrl)),n===null&&(n=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href));let i=this.delegate.view?.getCurrentPosition(),o=this.delegate.iframes[0].contentDocument;if(o){let s=Qr(o,"body"),l=t.position?t.position/s.scrollHeight:i,h=(0,Q0.v4)(),c;if(n){let d=n.Href;if(d.indexOf("#")>0&&(d=d.slice(0,d.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let m=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),y=Math.ceil((l??0)*(m.length-1)),w=m[y];c=nn(dt({},w),{id:h,href:d,created:new Date,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else c={id:h,href:d,locations:{progression:l},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(c)if(this.delegate.consumptionModule?.trackAction(c,ms.BookmarkCreated),this.api?.addBookmark){let d=await this.api.addBookmark(c),m=await this.annotator.saveAnnotation(d);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(y=>y(m))}else{let d=await this.annotator.saveAnnotation(c);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(m=>m(d))}}}return new Promise(i=>i(void 0))}getBookmarks(){let t=[];return this.annotator&&(t=this.annotator.getBookmarks()),t}showBookmarks(){let t=[];this.annotator&&(t=this.annotator.getBookmarks());let n=[];this.annotator&&(n=this.annotator.getAnnotations(),n&&(n=n.filter(i=>i.highlight.marker===ot.Bookmark),t?t.push.apply(t,n):t=n)),this.bookmarksView&&this.createTree(Fi.Bookmark,t,this.bookmarksView)}async drawBookmarks(){if(this.rights.enableBookmarks&&this.delegate.highlighter)if(this.api){let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.delegate.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.delegate.highlighter.destroyHighlights(mt.Annotation);for(let i of n){yn.push(i.highlight);let o=i,s=this.delegate.currentChapterLink.href;var t=this.publication.getTOCItem(s);if(this.delegate.currentTocUrl&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&await this.delegate.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight)}}}}else{let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.delegate.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.delegate.highlighter.destroyHighlights(mt.Annotation);for(let i of n){yn.push(i.highlight);let o=i,s=this.delegate.currentChapterLink.href,l=this.publication.getTOCItem(s);if(this.delegate.currentTocUrl&&(l=this.publication.getTOCItem(this.delegate.currentTocUrl)),l===void 0&&(l=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),l){let h=l.Href;h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),o.href===h&&await this.delegate.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight)}}}}}async deleteSelectedHighlight(t){this.api?.deleteBookmark?this.api.deleteBookmark(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return ir.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,s=this.publication.readingOrder;if(s.length){let l=(h,c)=>{let d=document.createElement("ul");d.className="sidenav-annotations";for(let m of c){let y=document.createElement("li"),w=document.createElement("a"),v=document.createElement("span");if(w.tabIndex=-1,w.className="chapter-link",m.Href){let f=this.publication.getAbsoluteHref(m.Href),p=this.publication.getTOCItemAbsolute(f);w.href=f,w.innerHTML=p?.Title||"",y.appendChild(w)}else v.innerHTML=m.Title||"",v.className="chapter-title",y.appendChild(v);Ce(w,"click",f=>{f.preventDefault(),f.stopPropagation();let p={href:w.href,locations:{progression:0},type:m.TypeLink,title:w.title};this.delegate.stopReadAloud(),this.delegate.navigate(p)});let g=document.createElement("ol");n.forEach(function(f){let p=m.Href.indexOf("#")!==-1?m.Href.slice(0,m.Href.indexOf("#")):m.Href;if(m.Href&&f.href.endsWith(p)){let b=document.createElement("li");b.className="annotation-item";let S=document.createElement("a");if(S.setAttribute("href",f.href),t===Fi.Bookmark){S.className="bookmark-link";let x=document.createElement("span"),E=Math.round((f.locations.progression??0)*100)+"% through resource";x.className="title",x.innerHTML=E,S.appendChild(x)}let C=document.createElement("span");if(C.className="timestamp",C.innerHTML=Rl.readableTimestamp(f.created),S.appendChild(C),Ce(S,"click",x=>{x.preventDefault(),x.stopPropagation(),o.handleAnnotationLinkClick(x,f)}),b.appendChild(S),o.delegate.sideNavExpanded){let x=document.createElement("button");x.className="delete",x.innerHTML=mr.delete,Ce(x,"click",E=>{E.preventDefault(),E.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,E,f)}),b.appendChild(x)}g.appendChild(b)}}),g.children.length>0&&(d.appendChild(y),d.appendChild(g)),d.children.length>0&&h.appendChild(d),m.Children&&m.Children.length>0&&l(h,m.Children)}};i.innerHTML="",l(i,s)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.delegate.stopReadAloud(),this.delegate.navigate(n)):ir.default.log("bookmark data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){ir.default.log("bookmark data locator: ",i),i?t===Fi.Bookmark&&this.deleteBookmark(i):ir.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 gS=gt(pS());H();var bi=gt(cn()),tg="r2-mo-active",bs=class{},lt=bs;lt.COLOR_REF="color",lt.AUTO_SCROLL_REF="autoscroll",lt.AUTO_TURN_REF="autoturn",lt.VOLUME_REF="volume",lt.RATE_REF="rate",lt.COLOR_KEY="mediaoverlay-"+bs.COLOR_REF,lt.AUTO_SCROLL_KEY="mediaoverlay-"+bs.AUTO_SCROLL_REF,lt.AUTO_TURN_KEY="mediaoverlay-"+bs.AUTO_TURN_REF,lt.VOLUME_KEY="mediaoverlay-"+bs.VOLUME_REF,lt.RATE_KEY="mediaoverlay-"+bs.RATE_REF;var ng=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(),bi.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,bi.default.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,bi.default.log(n.autoScroll)),i?.autoTurn&&(n.autoTurn=i.autoTurn,bi.default.log(n.autoScroll)),i?.volume&&(n.volume=i.volume,bi.default.log(n.volume)),i?.rate&&(n.rate=i.rate,bi.default.log(n.rate)),i?.wait&&(n.wait=i.wait,bi.default.log(n.wait))}return n.initializeSelections(),n}stop(){bi.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(lt.AUTO_SCROLL_KEY)!=null?this.getProperty(lt.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(lt.AUTO_TURN_KEY)!=null?this.getProperty(lt.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(lt.COLOR_KEY)!=null?this.getProperty(lt.COLOR_KEY).value:this.color,this.volume=this.getProperty(lt.VOLUME_KEY)!=null?this.getProperty(lt.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(lt.RATE_KEY)!=null?this.getProperty(lt.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=$e(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechAutoTurn=$e(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=$e(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=$e(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=$e(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()),Ce($e(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(lt.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(lt.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(lt.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(lt.VOLUME_REF)?.value,rate:this.userProperties.getByRef(lt.RATE_REF)?.value};this.applyMediaOverlaySettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{bi.default.log("api updated sync settings",n)})}getMediaOverlaySettings(){let t=new Zr;return t.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,lt.AUTO_SCROLL_REF,lt.AUTO_SCROLL_KEY),t.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,lt.AUTO_TURN_REF,lt.AUTO_TURN_KEY),t.addStringable(this.color,lt.COLOR_REF,lt.COLOR_KEY),t.addIncremental(this.volume,.1,1,.1,"",lt.VOLUME_REF,lt.VOLUME_KEY),t.addIncremental(this.rate,.1,3,.1,"",lt.RATE_REF,lt.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(lt.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){bi.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(lt.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoTurn!==void 0){bi.default.log("autoTurn "+this.autoTurn),this.autoTurn=t.autoTurn;let n=this.userProperties.getByRef(lt.AUTO_TURN_REF);n&&(n.value=this.autoTurn,this.saveProperty(n)),this.settingsChangeCallback()}if(t.volume){bi.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(lt.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback()}if(t.rate){bi.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(lt.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback()}}applyMediaOverlaySetting(t,n){if(t===lt.COLOR_REF){this.color=n;let i=this.userProperties.getByRef(lt.COLOR_REF);i&&(i.value=this.color,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===lt.AUTO_SCROLL_REF){this.autoScroll=n;let i=this.userProperties.getByRef(lt.AUTO_SCROLL_REF);i&&(i.value=this.autoScroll,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===lt.AUTO_TURN_REF){this.autoTurn=n;let i=this.userProperties.getByRef(lt.AUTO_TURN_REF);i&&(i.value=this.autoTurn,this.saveProperty(i)),this.settingsChangeCallback()}}increase(t){if(t==="mo_volume"){this.userProperties.getByRef(lt.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(lt.VOLUME_REF)?.value;let n=this.userProperties.getByRef(lt.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(lt.RATE_REF).increment(),this.rate=this.userProperties.getByRef(lt.RATE_REF)?.value;let n=this.userProperties.getByRef(lt.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}decrease(t){if(t==="mo_volume"){this.userProperties.getByRef(lt.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(lt.VOLUME_REF)?.value;let n=this.userProperties.getByRef(lt.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(lt.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(lt.RATE_REF)?.value;let n=this.userProperties.getByRef(lt.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}};var ut=gt(cn()),ig=class{constructor(t,n,i,o){this.play=$e(document,"#menu-button-play");this.pause=$e(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async t=>{ut.default.log("ontimeupdate"),this.trackCurrentTime()};this.ensureOnTimeUpdate=(t,n)=>{t?this.__ontimeupdate&&(this.__ontimeupdate=!1,this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),cancelAnimationFrame(this.myReq)):(!this.__ontimeupdate||n)&&(this.__ontimeupdate=!0,n&&(this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),this.audioElement.addEventListener("timeupdate",this.ontimeupdate)))};this.delegate=t,this.publication=n,this.settings=i,this.properties=o}static create(t){let n=new this(t.delegate,t.publication,t.settings,t);return n.start(),n}stop(){ut.default.log("MediaOverlay module stop")}start(){this.delegate.mediaOverlayModule=this,ut.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(),s;try{s=await fetch(o,this.delegate.requestConfig)}catch(d){console.error(d,o);return}s.ok||ut.default.log("BAD RESPONSE?!");let l;try{l=await s.json()}catch(d){console.error(d)}if(!l){ut.default.log("## moJson"+l);return}t.MediaOverlays=ta(l,gS.MediaOverlayNode),t.MediaOverlays.initialized=!0;let h=t.HrefDecoded||t.Href,c=new URL("https://dita.digital/"+h);await this.playMediaOverlays(c.pathname.substr(1),t.MediaOverlays,void 0)}else this.audioElement&&await this.audioElement.pause(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement&&await this.audioElement.pause(),this.delegate.nextResource()):await this.stopReadAloud()}async startReadAloud(){if(this.delegate.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement&&this.currentLinks[this.currentLinkIndex]?.Properties.MediaOverlay){let t=this.currentAudioBegin?this.currentAudioBegin:0;this.audioElement.currentTime=t,await this.audioElement.play(),this.ensureOnTimeUpdate(!1,!0),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}else this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?this.delegate.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display")}}async stopReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"))}findDepthFirstTextAudioPair(t,n,i){ut.default.log("findDepthFirstTextAudioPair()");let o,s;if(n.Text){let c=new URL("https://dita.digital/"+n.Text);if(c.pathname.substr(1)===t){if(o=!0,c.hash&&i){s=!1;let d=c.hash.substr(1);for(let m of i)if(m===d){s=!0;break}}}else o=!1}if(ut.default.log("isFragmentIDMatch: "+s),ut.default.log("isTextUrlMatch: "+o),!n.Children||!n.Children.length){if(ut.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!o){ut.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return s||o&&!i?(ut.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),n):void 0}let l=i,h=i;for(let c of n.Children){ut.default.log("findDepthFirstTextAudioPair() - child"),ut.default.log(JSON.stringify(c));let d=this.findDepthFirstTextAudioPair(t,c,h);if(d===null&&(ut.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),h=void 0),d)return ut.default.log("findDepthFirstTextAudioPair() - child - match"),ut.default.log(JSON.stringify(d)),d}if(s){ut.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let c=this.findDepthFirstTextAudioPair(t,n,void 0);return c&&(ut.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),ut.default.log(JSON.stringify(c)),c)}if(l&&!h)return null}trackCurrentTime(){if(cancelAnimationFrame(this.myReq),this.mediaOverlayTextAudioPair)try{this.currentAudioEnd&&this.audioElement.currentTime>=this.currentAudioEnd-.05&&(ut.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(ut.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let n=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!t);if(!n)ut.default.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud());else{let i=!1;if(this.mediaOverlayTextAudioPair.Text&&n.Text){let o=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),s=new URL("https://dita.digital/"+n.Text);o.pathname!==s.pathname&&(ut.default.log("mediaOverlaysNext() SWITCH! "+o.pathname+" != "+s.pathname),i=!0)}i?this.mediaOverlaysStop():(ut.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(n,void 0,void 0)},0))}}else ut.default.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){ut.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){ut.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 ut.default.log("findNextTextAudioPair() - prevMo === moToMatch"),t;ut.default.log("findNextTextAudioPair() - set previous"),ut.default.log(JSON.stringify(t)),i.prev=t;return}for(let s of t.Children){ut.default.log("findNextTextAudioPair() - child"),ut.default.log(JSON.stringify(s));let l=this.findNextTextAudioPair(s,n,i,o);if(l)return ut.default.log("findNextTextAudioPair() - match"),ut.default.log(JSON.stringify(l)),l}}async playMediaOverlaysAudio(t,n,i){if(ut.default.log("playMediaOverlaysAudio()"),this.mediaOverlayTextAudioPair=t,!t.Audio)return;let o=new URL(t.Audio,this.publication.manifestUrl),s=o.toString(),l=new URL(s);l.hash="",l.search="";let h=l.toString(),c=typeof n!="undefined",d=typeof i!="undefined";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!c&&!d){if(o.hash){let y=o.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(y&&y.length>=1){let w=y[1];try{this.currentAudioBegin=parseFloat(w)}catch(v){ut.default.error(v)}if(y.length>=3){let v=y[3];try{this.currentAudioEnd=parseFloat(v)}catch(g){ut.default.error(g)}}}}}else this.currentAudioBegin=n,this.currentAudioEnd=i;ut.default.log(`${s} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let m=async y=>{if(!this.audioElement)return;let w=this.currentAudioBegin?this.currentAudioBegin:0;if(y||this.audioElement.paused)if(y&&!w||this.audioElement.currentTime===w){if(ut.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 g=function(){v.settings.resourceReady?setTimeout(async()=>{await v.audioElement.play(),v.ensureOnTimeUpdate(!1,!0)},v.settings.wait*1e3):setTimeout(g,200)},v=this;g()}}else{ut.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let v=async g=>{if(this.audioElement.removeEventListener("timeupdate",v),ut.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 p=function(){f.settings.resourceReady?setTimeout(async()=>{await f.audioElement.play(),f.ensureOnTimeUpdate(!1,!0)},f.settings.wait*1e3):setTimeout(p,200)},f=this;p()}};this.audioElement.addEventListener("timeupdate",v),this.audioElement.currentTime=w}else{let v=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd!="undefined"&&this.previousAudioEnd>w-.02&&this.previousAudioEnd<=w&&this.audioElement.currentTime>=w-.1;this.ensureOnTimeUpdate(!1,!1),v?ut.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(ut.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=w)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||h!==this.currentAudioUrl){this.currentAudioUrl=h,ut.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",v=>{ut.default.log("-1) error: "+(this.currentAudioUrl!==v.currentTarget.src?this.currentAudioUrl+" -- ":"")+v.currentTarget.src.substr(v.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(ut.default.log(this.audioElement.error.code),ut.default.log(this.audioElement.error.message))});let y=async v=>{v.currentTarget.removeEventListener("canplaythrough",y),ut.default.log("oncanplaythrough"),await m(!0)};this.audioElement.addEventListener("canplaythrough",y);let w=async v=>{ut.default.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",w),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else ut.default.log("playMediaOverlaysAudio() - playClip()"),await m(!1)}async playMediaOverlays(t,n,i){ut.default.log("playMediaOverlays()");let o=i?i.filter(l=>l):void 0;o&&o.length===0&&(o=void 0);let s=this.findDepthFirstTextAudioPair(t,n,o);!s&&o&&(ut.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),ut.default.log(JSON.stringify(o,null,4)),ut.default.log(JSON.stringify(n,null,4)),s=this.findDepthFirstTextAudioPair(t,n,void 0)),s?s.Audio&&(ut.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=n,await this.playMediaOverlaysAudio(s,void 0,void 0)):ut.default.log("playMediaOverlays() - !moTextAudioPair "+t)}mediaOverlayHighlight(t){ut.default.log("moHighlight: ## "+t);let n=this.publication.Metadata?.MediaOverlay?.ActiveClass;n||(n=this.settings.color);let i=this.delegate.iframes[0].contentDocument?.documentElement.getAttribute("style"),o=i?i.indexOf("readium-night-on")>0:!1,s=i?i.indexOf("readium-sepia-on")>0:!1;if((this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&(n=o||s?tg:n||tg),this.pid){let h;this.currentLinkIndex===0?h=this.delegate.iframes[0].contentDocument?.getElementById(this.pid):h=this.delegate.iframes[1].contentDocument?.getElementById(this.pid),h&&h.classList.remove(n)}let l;t&&(this.currentLinkIndex===0?l=this.delegate.iframes[0].contentDocument?.getElementById(t):l=this.delegate.iframes[1].contentDocument?.getElementById(t),l&&l.classList.add(n),this.pid=t),l&&(this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&l.scrollIntoView({block:"center",behavior:"smooth"})}};H();var rg=gt(cn()),og=class{static async create(t){let n=new this(t.delegate,t.publication);return await n.start(),n}constructor(t,n){this.delegate=t,this.publication=n}async stop(){rg.default.log("Timeline module stop")}async start(){this.delegate.timelineModule=this,this.timelineContainer=$e(document,"#container-view-timeline"),this.positionSlider=$e(document,"#positionSlider"),this.publication.positions?this.positionSlider&&(this.positionSlider.style.display="block"):this.positionSlider&&(this.positionSlider.style.display="none")}async initialize(){return new Promise(async t=>{await document.fonts.ready;let n=this.delegate.currentLocator();(this.delegate.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions)&&(this.positionSlider&&(this.positionSlider.value=(n.locations.position??0).toString()),this.positionSlider&&(this.positionSlider.max=((n.locations.totalRemainingPositions??0)+(n.locations.position??0)).toString())),this.timelineContainer&&(this.timelineContainer.innerHTML=""),this.publication.readingOrder?.forEach(i=>{let o=this.publication.getAbsoluteHref(i.Href),s=this.publication.getTOCItemAbsolute(o),l=s?.Href.indexOf("#")!==-1?s?.Href.slice(0,s?.Href.indexOf("#")):s.Href,h=this.publication.getAbsoluteHref(l??"");var c;this.publication.positions&&this.delegate.view?.layout!=="fixed"?i.contentWeight?c=i.contentWeight:c=1:c=100/(this.publication.readingOrder?.length??0);var d=document.createElement("div");if(d.style.height=c+"%",d.style.width="100%",d.className="chapter",s?.Title!==void 0){var m=document.createElement("span");m.innerHTML=s.Title,m.className="chapter-tooltip",d.appendChild(m)}Ce(d,"click",y=>{y.preventDefault(),y.stopPropagation();var w;this.publication.positions||this.delegate.rights.autoGeneratePositions&&this.publication.positions?(w=dt({},this.publication.positions.filter(v=>v.href===i.Href)[0]),w.href=this.publication.getAbsoluteHref(w.href)):w={href:h,locations:{progression:0},type:i.TypeLink,title:i.Title},rg.default.log(w),this.delegate.navigate(w)}),h===this.delegate.currentChapterLink.href?d.className+=" active":d.className=d.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(d)}),t()})}};H();var xg=gt(Mo());H();var mS=gt(cn());function yS(r,t){return new Promise(function(n){setTimeout(n.bind(null,t),r)})}var kD=!1;mS.default.setLevel(kD?"trace":"warn",!0);var VA=gt(zA()),lh=gt(GA()),qn=gt(cn());var ch=class{constructor(t,n){this.hasEventListener=!1;this.isHacked=!1;this.delegate=t,this.properties=n}static async setupPreloadProtection(t){if(this.isCurrentBrowserSupported(t))t.detectInspect&&await this.startInspectorProtection(t);else throw new Error("Browser not supported")}static async create(t){let n=new this(t.delegate,t);return await n.start(),n}static async startInspectorProtection(t){(0,lh.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,lh.launch)(),await yS(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,VA.getUserAgentRegExp)({browsers:n,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.delegate.contentProtectionModule=this,this.properties?.enableObfuscation){this.wrapper=Rt(document,"#iframe-wrapper"),this.securityContainer=$e(document,"#container-view-security");var t=this;this.mutationObserver=new MutationObserver(function(n){n.forEach(function(i){qn.default.log(i.type),t.isHacked=!0})})}}async stop(){if(qn.default.log("Protection module stop"),this.mutationObserver.disconnect(),this.properties?.disableKeys){ze(this.delegate.mainElement,"keydown",this.disableSave),ze(this.delegate.headerMenu,"keydown",this.disableSave);for(let t of this.delegate.iframes)ze(t.contentDocument,"keydown",this.disableSave),ze(t.contentWindow,"keydown",this.disableSave);ze(window,"keydown",this.disableSave),ze(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){ze(this.delegate.mainElement,"copy",this.preventCopy),ze(this.delegate.headerMenu,"copy",this.preventCopy);for(let t of this.delegate.iframes)ze(t.contentDocument,"copy",this.preventCopy),ze(t.contentWindow,"copy",this.preventCopy);ze(window,"copy",this.preventCopy),ze(document,"copy",this.preventCopy),ze(this.delegate.mainElement,"cut",this.preventCopy),ze(this.delegate.headerMenu,"cut",this.preventCopy);for(let t of this.delegate.iframes)ze(t.contentDocument,"cut",this.preventCopy),ze(t.contentWindow,"cut",this.preventCopy);ze(window,"cut",this.preventCopy),ze(document,"cut",this.preventCopy),ze(this.delegate.mainElement,"keydown",this.preventCopyKey),ze(this.delegate.headerMenu,"keydown",this.preventCopyKey);for(let t of this.delegate.iframes)ze(t.contentDocument,"keydown",this.preventCopyKey),ze(t.contentWindow,"keydown",this.preventCopyKey);ze(window,"keydown",this.preventCopyKey),ze(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){ze(this.delegate.mainElement,"copy",this.restrictCopy),ze(this.delegate.headerMenu,"copy",this.restrictCopy);for(let t of this.delegate.iframes)ze(t.contentDocument,"copy",this.restrictCopy),ze(t.contentWindow,"copy",this.restrictCopy);ze(window,"copy",this.restrictCopy),ze(document,"copy",this.restrictCopy),ze(this.delegate.mainElement,"cut",this.restrictCopy),ze(this.delegate.headerMenu,"cut",this.restrictCopy);for(let t of this.delegate.iframes)ze(t.contentDocument,"cut",this.restrictCopy),ze(t.contentWindow,"cut",this.restrictCopy);ze(window,"cut",this.restrictCopy),ze(document,"cut",this.restrictCopy),ze(this.delegate.mainElement,"keydown",this.restrictCopyKey),ze(this.delegate.headerMenu,"keydown",this.restrictCopyKey);for(let t of this.delegate.iframes)ze(t.contentDocument,"keydown",this.restrictCopyKey),ze(t.contentWindow,"keydown",this.restrictCopyKey);ze(window,"keydown",this.restrictCopyKey),ze(document,"keydown",this.restrictCopyKey)}if(this.properties?.disablePrint){ze(this.delegate.mainElement,"beforeprint",this.beforePrint.bind(this)),ze(this.delegate.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let t of this.delegate.iframes)ze(t.contentDocument,"beforeprint",this.beforePrint),ze(t.contentWindow,"beforeprint",this.beforePrint);ze(window,"beforeprint",this.beforePrint),ze(document,"beforeprint",this.beforePrint),ze(this.delegate.mainElement,"afterprint",this.afterPrint.bind(this)),ze(this.delegate.headerMenu,"afterprint",this.afterPrint.bind(this));for(let t of this.delegate.iframes)ze(t.contentDocument,"afterprint",this.afterPrint.bind(this)),ze(t.contentWindow,"afterprint",this.afterPrint.bind(this));ze(window,"afterprint",this.afterPrint.bind(this)),ze(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){ze(this.delegate.mainElement,"contextmenu",this.disableContext),ze(this.delegate.headerMenu,"contextmenu",this.disableContext);for(let t of this.delegate.iframes)ze(t.contentDocument,"contextmenu",this.disableContext),ze(t.contentWindow,"contextmenu",this.disableContext);ze(window,"contextmenu",this.disableContext),ze(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),ze(this.wrapper,"scroll",this.handleScroll.bind(this))}observe(){if(this.properties?.enableObfuscation){this.securityContainer.hasAttribute("style")&&(this.isHacked=!0),this.mutationObserver.disconnect();var t={attributes:!0,childList:!0,characterData:!0};this.mutationObserver.observe(this.securityContainer,t)}}async deactivate(){this.properties?.enableObfuscation&&(this.observe(),this.rects.forEach(t=>this.deactivateRect(t,this.securityContainer,this.isHacked)))}async activate(){if(this.properties?.enableObfuscation){this.observe();for(let t of this.delegate.iframes)if(t.contentDocument){let n=Qr(t.contentDocument,"body");this.rects=this.findRects(n),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){Ce(this.delegate.mainElement,"keydown",this.disableSave),Ce(this.delegate.headerMenu,"keydown",this.disableSave);for(let t of this.delegate.iframes)Ce(t,"keydown",this.disableSave),Ce(t.ownerDocument,"keydown",this.disableSave),Ce(t.contentDocument,"keydown",this.disableSave),Ce(t.contentWindow,"keydown",this.disableSave),Ce(t.contentWindow?.document,"keydown",this.disableSave);Ce(window,"keydown",this.disableSave),Ce(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){Ce(this.delegate.mainElement,"copy",this.preventCopy),Ce(this.delegate.headerMenu,"copy",this.preventCopy);for(let t of this.delegate.iframes)Ce(t,"copy",this.preventCopy),Ce(t.ownerDocument,"copy",this.preventCopy),Ce(t.contentDocument,"copy",this.preventCopy),Ce(t.contentWindow,"copy",this.preventCopy),Ce(t.contentWindow?.document,"copy",this.preventCopy);Ce(window,"copy",this.preventCopy),Ce(document,"copy",this.preventCopy),Ce(this.delegate.mainElement,"cut",this.preventCopy),Ce(this.delegate.headerMenu,"cut",this.preventCopy);for(let t of this.delegate.iframes)Ce(t,"cut",this.preventCopy),Ce(t.ownerDocument,"cut",this.preventCopy),Ce(t.contentDocument,"cut",this.preventCopy),Ce(t.contentWindow,"cut",this.preventCopy),Ce(t.contentWindow?.document,"cut",this.preventCopy);Ce(window,"cut",this.preventCopy),Ce(document,"cut",this.preventCopy),Ce(this.delegate.mainElement,"keydown",this.preventCopyKey),Ce(this.delegate.headerMenu,"keydown",this.preventCopyKey);for(let t of this.delegate.iframes)Ce(t,"keydown",this.preventCopyKey),Ce(t.ownerDocument,"keydown",this.preventCopyKey),Ce(t.contentDocument,"keydown",this.preventCopyKey),Ce(t.contentWindow,"keydown",this.preventCopyKey),Ce(t.contentWindow?.document,"keydown",this.preventCopyKey);Ce(window,"keydown",this.preventCopyKey),Ce(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){Ce(this.delegate.mainElement,"copy",this.restrictCopy.bind(this)),Ce(this.delegate.headerMenu,"copy",this.restrictCopy.bind(this));for(let t of this.delegate.iframes)Ce(t,"copy",this.restrictCopy),Ce(t.ownerDocument,"copy",this.restrictCopy.bind(this)),Ce(t.contentDocument,"copy",this.restrictCopy.bind(this)),Ce(t.contentWindow,"copy",this.restrictCopy.bind(this)),Ce(t.contentWindow?.document,"copy",this.restrictCopy.bind(this));Ce(window,"copy",this.restrictCopy.bind(this)),Ce(document,"copy",this.restrictCopy.bind(this)),Ce(this.delegate.mainElement,"cut",this.restrictCopy.bind(this)),Ce(this.delegate.headerMenu,"cut",this.restrictCopy.bind(this));for(let t of this.delegate.iframes)Ce(t,"cut",this.restrictCopy.bind(this)),Ce(t.ownerDocument,"cut",this.restrictCopy.bind(this)),Ce(t.contentDocument,"cut",this.restrictCopy.bind(this)),Ce(t.contentWindow,"cut",this.restrictCopy.bind(this)),Ce(t.contentWindow?.document,"cut",this.restrictCopy.bind(this));Ce(window,"cut",this.restrictCopy.bind(this)),Ce(document,"cut",this.restrictCopy.bind(this)),Ce(this.delegate.mainElement,"keydown",this.restrictCopyKey.bind(this)),Ce(this.delegate.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let t of this.delegate.iframes)Ce(t,"keydown",this.restrictCopyKey.bind(this)),Ce(t.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),Ce(t.contentDocument,"keydown",this.restrictCopyKey.bind(this)),Ce(t.contentWindow,"keydown",this.restrictCopyKey.bind(this)),Ce(t.contentWindow?.document,"keydown",this.restrictCopyKey.bind(this));Ce(window,"keydown",this.restrictCopyKey.bind(this)),Ce(document,"keydown",this.restrictCopyKey.bind(this))}if(this.properties?.disablePrint){Ce(this.delegate.mainElement,"beforeprint",this.beforePrint),Ce(this.delegate.headerMenu,"beforeprint",this.beforePrint);for(let t of this.delegate.iframes)Ce(t,"beforeprint",this.beforePrint.bind(this)),Ce(t.ownerDocument,"beforeprint",this.beforePrint.bind(this)),Ce(t.contentDocument,"beforeprint",this.beforePrint.bind(this)),Ce(t.contentWindow,"beforeprint",this.beforePrint.bind(this)),Ce(t.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));Ce(window,"beforeprint",this.beforePrint.bind(this)),Ce(document,"beforeprint",this.beforePrint.bind(this)),Ce(this.delegate.mainElement,"afterprint",this.afterPrint),Ce(this.delegate.headerMenu,"afterprint",this.afterPrint);for(let t of this.delegate.iframes)Ce(t,"afterprint",this.afterPrint.bind(this)),Ce(t.ownerDocument,"afterprint",this.afterPrint.bind(this)),Ce(t.contentDocument,"afterprint",this.afterPrint.bind(this)),Ce(t.contentWindow,"afterprint",this.afterPrint.bind(this)),Ce(t.contentWindow?.document,"afterprint",this.afterPrint.bind(this));Ce(window,"afterprint",this.afterPrint.bind(this)),Ce(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){Ce(this.delegate.mainElement,"contextmenu",this.disableContext),Ce(this.delegate.headerMenu,"contextmenu",this.disableContext);for(let t of this.delegate.iframes)Ce(t,"contextmenu",this.disableContext),Ce(t.ownerDocument,"contextmenu",this.disableContext),Ce(t.contentDocument,"contextmenu",this.disableContext),Ce(t.contentWindow,"contextmenu",this.disableContext),Ce(t.contentWindow?.document,"contextmenu",this.disableContext);Ce(window,"contextmenu",this.disableContext),Ce(document,"contextmenu",this.disableContext)}}initializeResource(){this.properties?.hideTargetUrl&&this.hideTargetUrls(!0),this.properties?.disableDrag&&this.preventDrag(!0)}async initialize(){if(this.properties?.enableObfuscation)return new Promise(async t=>{await document.fonts.ready;for(let n of this.delegate.iframes)if(n.contentDocument){let i=Qr(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,Ce(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,xg.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 qn.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;qn.default.log("copy action initiated");let n=this.delegate.iframes[0].contentWindow;if(n){let o=function(l){let h={className:d=>ji.indexOf(d)<0,idName:d=>ji.indexOf(d)<0},c=i.delegate.iframes[0].contentDocument;if(c)return Nn(l,c,h)},i=this,s=Ir(n,o);if(s===void 0){let l=this.delegate.iframes[0].contentDocument;s=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(l)}t.clipboardData.setData("text/plain",s?.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.delegate.iframes[0].contentWindow;if(n){let o=function(l){let h={className:d=>ji.indexOf(d)<0,idName:d=>ji.indexOf(d)<0},c=i.delegate.iframes[0].contentDocument;if(c)return Nn(l,c,h)},i=this,s=Ir(n,o);if(s===void 0){let l=this.delegate.iframes[0].contentDocument;s=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(l)}this.copyToClipboard(s?.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 qn.default.log("before print"),this.delegate&&this.delegate.headerMenu&&(this.delegate.headerMenu.style.display="none",this.delegate.mainElement.style.display="none"),t.stopPropagation(),t.preventDefault(),!1}afterPrint(t){return qn.default.log("after print"),this.delegate&&this.delegate.headerMenu&&(this.delegate.headerMenu.style.removeProperty("display"),this.delegate.mainElement.style.removeProperty("display")),t.stopPropagation(),t.preventDefault(),!1}hideTargetUrls(t){function n(i){i.preventDefault();let o=i.currentTarget.getAttribute("data-href-resolved"),s=document.createElement("a");s.setAttribute("href",o),s.click()}for(let i of this.delegate.iframes){let o=i.contentDocument?.querySelectorAll("a");o?.forEach(s=>{let l=s.getAttribute("data-href"),h=s.getAttribute("href");!l&&h&&(s.setAttribute("data-href",h),s.setAttribute("data-href-resolved",s.href))}),t?o?.forEach(s=>{s.setAttribute("href",""),s.addEventListener("click",n)}):o?.forEach(s=>{let l=s.getAttribute("data-href");l&&s.setAttribute("href",l),s.removeEventListener("click",n)})}}preventDrag(t){let n="-webkit-user-drag: none; -khtml-user-drag: none; -moz-user-drag: none; -ms-user-drag: none; user-drag: none; -webkit-pointer-events: none; -khtml-pointer-events: none; -moz-pointer-events: none; -ms-pointer-events: none; pointer-events: none;",i=o=>{o.preventDefault()};for(let o of this.delegate.iframes){let s=o.contentDocument?.body.getAttribute("style")||"";t?(o.contentDocument?.body.addEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",s+n)):(o.contentDocument?.body.removeEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",s.replace(n,"")))}}recalculate(t=0){return new Promise(n=>{if(this.properties?.enableObfuscation){let i=(0,xg.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:s,width:l}=this.measureTextNode(n.node);n.top=i,n.height=o,n.width=l,n.left=s}catch(i){qn.default.log("error "+i),qn.default.log(n),qn.default.log(n.node),qn.default.log("scrambledTextContent "+n.scrambledTextContent),qn.default.log("textContent "+n.textContent),qn.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),s=this.isBeingHacked(n);t.isObfuscated&&!o&&!s&&!i&&(t.node.textContent=t.textContent,t.isObfuscated=!1),!t.isObfuscated&&(o||s||i)&&(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0)}findRects(t){return this.findTextNodes(t).map(i=>{let{top:o,height:s,left:l,width:h}=this.measureTextNode(i),c=i.parentElement?.nodeName==="option"||i.parentElement?.nodeName==="script"?i.textContent:this.obfuscateText(i.textContent??"");return{top:o,height:s,width:h,left:l,node:i,textContent:i.textContent??"",scrambledTextContent:c??"",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){qn.default.log("measureTextNode "+n),qn.default.log("measureTextNode "+t),qn.default.log(t.textContent)}}isBeingHacked(t){return t.style.animation||t.style.transition||t.style.position||t.hasAttribute("style")?(qn.default.log("content being hacked"),!0):!1}isOutsideViewport(t){let n=this.wrapper.scrollLeft,i=n+this.wrapper.clientWidth,o=t.left+t.width,s=t.top+t.height,l=this.wrapper.scrollTop,h=l+this.wrapper.clientHeight,c=s<l,d=t.top>h,m=o<n-window.innerWidth,y=t.left>i+window.innerWidth;return c||d||m||y}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 s(l){for(var h=l.length,c,d;h>0;)d=Math.floor(Math.random()*h),h--,c=l[h],l[h]=l[d],l[d]=c;return l}return n&&(o=o.map(function(l){return s(l.split("")).join("")})),i?s(o).join(" "):o.join(" ")}};H();var QA=gt(KA());H();var uh=r=>r.replace(/\n/g," ").replace(/\s\s+/g," "),KD=r=>uh(r).trim(),YA=/[\\^$.*+?()[\]{}|]/g,YD=RegExp(YA.source);function XA(r){return r&&YD.test(r)?r.replace(YA,"\\$&"):r||""}var dh=0,XD=()=>()=>Number.isSafeInteger(++dh)?dh:dh=1,ZA=()=>{dh=0},ZD=XD(),QD=r=>t=>{try{return Nn(t,r,Lo)}catch(n){return console.error("uniqueCssSelector:",n),""}};async function jo(r,t,n,i,o=!1){if(!t)return[];let s=t.body?.textContent;if(!s)return[];if(r=KD(r),!r.length)return[];let l=t.createNodeIterator(t.body,NodeFilter.SHOW_TEXT,{acceptNode:v=>NodeFilter.FILTER_ACCEPT}),h=new RegExp(XA(r).replace(/ /g,"\\s+"),"gim");o&&(h=new RegExp("\\b"+XA(r).replace(/ /g,"\\s+")+"\\b","gim"));let c=[],d=100,m=30,y=0,w;for(;w=h.exec(s);){let v=Math.max(0,w.index-d),g=Math.min(d,w.index),f=uh(s.substr(v,g));f=f.substr(f.length-m),v=h.lastIndex,g=Math.min(d,s.length-v);let p=uh(s.substr(v,g)).substr(0,m),b=new Range,S=w.index;for(;y<=S;){let E=l.nextNode();E&&E.nodeValue&&(y+=E.nodeValue.length)}let C=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(y-S):0;for(b.setStart(l.referenceNode,C),S=w.index+w[0].length;y<=S;){let T=l.nextNode()?.nodeValue;T&&(y+=T.length)}C=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(y-S):0,b.setEnd(l.referenceNode,C),t.getCssSelector||(t.getCssSelector=QD(t));let x=oo(b,t.getCssSelector);x&&c.push({textMatch:uh(w[0]),textBefore:f,textAfter:p,rangeInfo:x,href:n,title:i,uuid:ZD().toString()})}return c}var ex=gt(cn()),Tg=class{constructor(t,n,i,o,s,l){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.delegate=t,this.headerMenu=l,this.publication=n,this.properties=i,this.api=s,this.highlighter=o}static async create(t){let n=new this(t.delegate,t.publication,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){ex.default.log("Search module stop"),ze(this.searchInput,"keypress",this.handleSearch.bind(this)),ze(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.delegate.searchModule=this,this.headerMenu){this.searchInput=$e(this.headerMenu,"#searchInput"),Ce(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=$e(this.headerMenu,"#searchGo"),Ce(this.searchGo,"click",this.handleSearch.bind(this));var t=$e(this.headerMenu,"#menu-button-search");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("search"):this.delegate.showLayer("search")},10)}async handleSearch(t){(t.key==="Enter"||t.type==="click")&&(await this.handleSearchChapter(),await this.handleSearchBook())}async handleSearchChapter(t){var n=this,i=this.searchInput.value;let o=this.delegate.currentChapterLink.href,s=this.publication.getSpineItem(o);if(this.headerMenu)var l=$e(document,"#searchResultChapter");n.currentChapterSearchResult=[],n.currentSearchHighlights=[];var h=[];this.delegate.rights.enableContentProtection&&this.delegate.contentProtectionModule?.deactivate(),await this.searchAndPaintChapter(i,t,async d=>{h=d,c(1),this.delegate.rights.enableContentProtection&&this.delegate.contentProtectionModule?.recalculate(200)});async function c(d){l.innerHTML="";var m;if(m=n.paginate(h,d,10),m.total===0){let y=document.createElement("a");y.className="collection-item",y.innerHTML="nothing found",l.appendChild(y)}else{for(let f=0;f<m.data.length;f++){let p=document.createElement("a"),b=m.data[f];p.className="collection-item",p.href=s?.Href??"",p.innerHTML="..."+b.textBefore+"<mark>"+b.textMatch+"</mark>"+b.textAfter+"...",Ce(p,"click",S=>{S.preventDefault(),S.stopPropagation(),n.jumpToMark(f+d*10-10)}),l.appendChild(p)}let y=document.createElement("div");y.style.textAlign="center",y.style.marginTop="10px";let w=document.createElement("ul");w.className="pagination";let v=document.createElement("li");if(v.className="disabled",v.innerHTML='<a href="#!"> < </a>',m.pre_page!==void 0){let f=m.pre_page;v.className="waves-effect",Ce(v,"click",p=>{p.preventDefault(),p.stopPropagation(),c(f)})}w.appendChild(v);for(let f=1;f<=m.total_pages;f++){let p,b=document.createElement("li");b.className="waves-effect",f===m.page&&(b.className="active",p=b),b.innerHTML='<a href="#!">'+f+"</a>",Ce(b,"click",S=>{S.preventDefault(),S.stopPropagation(),p&&(p.className="waves-effect"),b.className="active",p=b,c(f)}),w.appendChild(b)}let g=document.createElement("li");if(g.className="disabled",g.innerHTML='<a href="#!"> > </a>',m.next_page!==void 0){let f=m.next_page;g.className="waves-effect",Ce(g,"click",p=>{p.preventDefault(),p.stopPropagation(),c(f)})}w.appendChild(g),y.appendChild(w),l.appendChild(y)}}}async searchAndPaintChapter(t,n=0,i){let o=this.publication.getAbsoluteHref(this.publication.readingOrder[this.delegate.currentResource()??0].Href),s=this.publication.getTOCItem(o);s===null&&(s=this.publication.readingOrder[this.delegate.currentResource()??0]);let l=[];this.highlighter?.destroyHighlights(mt.Search),this.delegate.rights.enableSearch&&this.drawSearch();let h=0;if(s){let c=this.delegate.iframes[0].contentDocument;c&&s&&jo(t,c,s.Href,s.Title).then(d=>{d.forEach(m=>{let y={rangeInfo:m.rangeInfo};setTimeout(()=>{let w;h===n?(w=this.createSearchHighlight(y,this.properties?.current),this.jumpToMark(n)):w=this.createSearchHighlight(y,this.properties?.color),m.highlight=w,l.push(m),this.currentChapterSearchResult.push(m),this.currentSearchHighlights.push(w),h++},500)}),setTimeout(()=>{i(l)},500)})}}createSearchHighlight(t,n){try{var i=n;ht.isHexColor(i)&&(i=ht.hexToRgbChannels(i));let s=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,l=QA.SHA256.hash(s),h="R2_SEARCH_"+l;var o=!1;let c={color:i||gs,id:h,pointerInteraction:o,selectionInfo:t,marker:ot.Highlight,type:mt.Search},d=this.highlighter?.createHighlightDom(this.delegate.iframes[0].contentWindow,c);return c.position=parseInt((d?.hasChildNodes()?d.childNodes[0]:d).style.top.replace("px","")),c}catch(s){throw"Can't create highlight: "+s}}clearSearch(){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.highlighter?.destroyHighlights(mt.Search)}async search(t,n){return this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],ZA(),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,s;let l=this.delegate.currentChapterLink.href;var h=this.publication.getAbsoluteHref(t);let c=this.bookSearchResult.filter(d=>d.href===t);if(i?(s=this.currentChapterSearchResult.filter(d=>d.uuid===n)[0],o=this.currentChapterSearchResult.findIndex(d=>d.uuid===n)):(s=c.filter(d=>d.uuid===n)[0],o=c.findIndex(d=>d.uuid===n)),s!==void 0)if(l===h)this.jumpToMark(o);else{let m={href:h,locations:{progression:0},title:"title"};this.delegate.navigate(m),setTimeout(()=>{this.searchAndPaintChapter(s.textMatch,o,async()=>{})},300)}}async goToSearchIndex(t,n,i){var o=n,s;let l=this.delegate.currentChapterLink.href;var h=this.publication.getAbsoluteHref(t);let c=this.bookSearchResult.filter(d=>d.href===t);if(i?s=this.currentChapterSearchResult[o]:s=c[o],s!==void 0)if(l===h)this.jumpToMark(o);else{let m={href:h,locations:{progression:0},title:"title"};this.delegate.navigate(m),setTimeout(()=>{this.searchAndPaintChapter(s.textMatch,o,async()=>{})},300)}}async handleSearchBook(){var t=this,n=this.searchInput.value;if(t.headerMenu)var i=$e(document,"#searchResultBook");o(1);async function o(l){i.innerHTML="";var h,c=await t.searchBook(n);if(h=t.paginate(c,l,10),h.total===0){let d=document.createElement("a");d.className="collection-item",d.innerHTML="nothing found",i.appendChild(d)}else{s(h.data,g=>g.href).forEach(g=>{let f=document.createElement("div");if(f.style.marginBottom="10px",g[0].title){let p=document.createElement("span");p.className="collection-item",p.style.display="block",p.innerHTML=g[0].title,f.appendChild(p)}i.appendChild(f),g.forEach(p=>{let b=document.createElement("a");b.className="collection-item";var S=t.publication.getAbsoluteHref(p.href);b.innerHTML="..."+p.textBefore+"<mark>"+p.textMatch+"</mark>"+p.textAfter+"...",Ce(b,"click",C=>{C.preventDefault(),C.stopPropagation();let E=c.filter(R=>R.href===p.href).findIndex(R=>R===p);if(t.delegate.currentChapterLink.href===S)t.jumpToMark(E);else{let O={href:S,locations:{progression:0},title:"title"};t.delegate.navigate(O),setTimeout(()=>{t.handleSearchChapter(E)},300)}}),f.appendChild(b)})});let m=document.createElement("div");m.style.textAlign="center",m.style.marginTop="10px";let y=document.createElement("ul");y.className="pagination";let w=document.createElement("li");if(w.className="disabled",w.innerHTML='<a href="#!"> < </a>',h.pre_page!=null){let g=h.pre_page;w.className="waves-effect",Ce(w,"click",f=>{f.preventDefault(),f.stopPropagation(),o(g)})}y.appendChild(w);for(let g=1;g<=h.total_pages;g++){let f,p=document.createElement("li");p.className="waves-effect",g===h.page&&(p.className="active",f=p),p.innerHTML='<a href="#!">'+g+"</a>",Ce(p,"click",b=>{b.preventDefault(),b.stopPropagation(),f&&(f.className="waves-effect"),p.className="active",f=p,o(g)}),y.appendChild(p)}let v=document.createElement("li");if(v.className="disabled",v.innerHTML='<a href="#!"> > </a>',h.next_page!=null){let g=h.next_page;v.className="waves-effect",Ce(v,"click",f=>{f.preventDefault(),f.stopPropagation(),o(g)})}y.appendChild(v),m.appendChild(y),i.appendChild(m)}}function s(l,h){let c=new Map;return l.forEach(d=>{let m=h(d),y=c.get(m);y?y.push(d):c.set(m,[d])}),Array.from(c.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:""),s=this.publication.getTOCItem(o);if(s===void 0&&this.publication.readingOrder&&(s=this.publication.readingOrder[i]),s){let l=this.publication.getAbsoluteHref(s.Href);this.delegate.api?.getContent?await this.delegate.api?.getContent(l).then(h=>{let d=new DOMParser().parseFromString(h,"application/xhtml+xml");s&&jo(t,d,s.Href,s.Title).then(m=>{m.forEach(y=>{n.push(y),this.bookSearchResult.push(y)})})}):await fetch(l,this.delegate.requestConfig).then(h=>h.text()).then(async h=>{let d=new DOMParser().parseFromString(this.delegate.requestConfig?.encoded?this.decodeBase64(h):h,"application/xhtml+xml");s&&jo(t,d,s.Href,s.Title).then(m=>{m.forEach(y=>{n.push(y),this.bookSearchResult.push(y)})})})}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.delegate.currentResource()??0].Href),o=this.publication.getTOCItem(i);if(o===null&&(o=this.publication.readingOrder[this.delegate.currentResource()??0]),o){let s=this.publication.getAbsoluteHref(o.Href);this.delegate.api?.getContent?await this.delegate.api?.getContent(s).then(l=>{let c=new DOMParser().parseFromString(l,"application/xhtml+xml");o&&jo(t,c,o.Href,o.Title).then(d=>{d.forEach(m=>{n.push(m)})})}):await fetch(s,this.delegate.requestConfig).then(l=>l.text()).then(async l=>{let c=new DOMParser().parseFromString(this.delegate.requestConfig?.encoded?this.decodeBase64(l):l,"application/xhtml+xml");o&&jo(t,c,o.Href,o.Title).then(d=>{d.forEach(m=>{n.push(m)})})})}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(mt.Search),this.drawSearch()}jumpToMark(t){setTimeout(()=>{if(this.currentChapterSearchResult.length){var n=this.currentChapterSearchResult[t];this.currentSearchHighlights.forEach(o=>{var s=this.properties?.color;ht.isHexColor(s)&&(s=ht.hexToRgbChannels(s)),o.color=s});var i=this.properties?.current;ht.isHexColor(i)&&(i=ht.hexToRgbChannels(i)),n.highlight.color=i,this.highlighter?.setAndResetSearchHighlight(n.highlight,this.currentSearchHighlights),this.delegate.view?.goToCssSelector(n.rangeInfo.startContainerElementCssSelector),this.delegate.updatePositionInfo()}},200)}paginate(t,n,i){let o=n||1,s=i||10,l=(o-1)*s,h=t.slice(l).slice(0,s),c=Math.ceil(t.length/s);return{page:o,per_page:s,pre_page:o-1?o-1:void 0,next_page:c>o?o+1:void 0,total:t.length,total_pages:c,data:h}}};H();var wi=gt(cn()),Ho=class{},st=Ho;st.COLOR_REF="color",st.AUTO_SCROLL_REF="autoscroll",st.RATE_REF="rate",st.PITCH_REF="pitch",st.VOLUME_REF="volume",st.VOICE_REF="voice",st.COLOR_KEY="tts-"+Ho.COLOR_REF,st.AUTO_SCROLL_KEY="tts-"+Ho.AUTO_SCROLL_REF,st.RATE_KEY="tts-"+Ho.RATE_REF,st.PITCH_KEY="tts-"+Ho.PITCH_REF,st.VOLUME_KEY="tts-"+Ho.VOLUME_REF,st.VOICE_KEY="tts-"+Ho.VOICE_REF;var Og=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,wi.default.log(n.rate)),i?.pitch&&(n.pitch=i.pitch,wi.default.log(n.pitch)),i?.volume&&(n.volume=i.volume,wi.default.log(n.volume)),i?.color&&(n.color=i.color,wi.default.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,wi.default.log(n.autoScroll)),i?.voice&&(n.voice=i.voice,wi.default.log(n.voice))}return n.initializeSelections(),n}stop(){wi.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(st.AUTO_SCROLL_KEY)!=null?this.getProperty(st.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(st.RATE_KEY)!=null?this.getProperty(st.RATE_KEY).value:this.rate,this.pitch=this.getProperty(st.PITCH_KEY)!=null?this.getProperty(st.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(st.VOLUME_KEY)!=null?this.getProperty(st.VOLUME_KEY).value:this.volume,this.color=this.getProperty(st.COLOR_KEY)!=null?this.getProperty(st.COLOR_KEY).value:this.color,this.voice=this.getProperty(st.VOICE_REF)!=null?this.getProperty(st.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=$e(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechRate=$e(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=$e(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=$e(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=$e(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),Ce($e(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(st.RATE_REF)?.value,pitch:this.userProperties.getByRef(st.PITCH_REF)?.value,volume:this.userProperties.getByRef(st.VOLUME_REF)?.value,voice:this.userProperties.getByRef(st.VOLUME_REF)?.value,color:this.userProperties.getByRef(st.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(st.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{wi.default.log("api updated tts settings",n)})}getTTSSettings(){var t=new Zr;return t.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,st.AUTO_SCROLL_REF,st.AUTO_SCROLL_KEY),t.addIncremental(this.rate,.1,10,.1,"",st.RATE_REF,st.RATE_KEY),t.addIncremental(this.pitch,.1,2,.1,"",st.PITCH_REF,st.PITCH_KEY),t.addIncremental(this.volume,.1,1,.1,"",st.VOLUME_REF,st.VOLUME_KEY),t.addStringable(this.color,st.COLOR_REF,st.COLOR_KEY),t.addJSONable(JSON.stringify(this.voice),st.VOICE_REF,st.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){wi.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(st.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.pitch){wi.default.log("pitch "+this.pitch),this.pitch=t.pitch;let n=this.userProperties.getByRef(st.PITCH_REF);n&&(n.value=this.pitch,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.volume){wi.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(st.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(st.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){wi.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(st.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.voice){wi.default.log("voice "+this.voice),this.voice=t.voice;let n=this.userProperties.getByRef(st.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(st.RATE_REF).increment();let n=this.userProperties.getByRef(st.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(st.PITCH_REF).increment();let n=this.userProperties.getByRef(st.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(st.VOLUME_REF).increment();let n=this.userProperties.getByRef(st.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}decrease(t){if(t==="rate"){this.userProperties.getByRef(st.RATE_REF).decrement();let n=this.userProperties.getByRef(st.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(st.PITCH_REF).decrement();let n=this.userProperties.getByRef(st.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(st.VOLUME_REF).decrement();let n=this.userProperties.getByRef(st.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}};H();H();var hh=`${mr.loading}`,tx=`
|
|
81
|
+
</svg>`,mr={error:mi("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:mi("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:bD("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:mi("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:mi("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:mi("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:mi("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:mi("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:mi("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:mi("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:mi("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:mi("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:mi("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:mi("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:mi("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 j0=gt(Gd());var yi=gt(cn()),et;(function(c){c.R2_ID_HIGHLIGHTS_CONTAINER="R2_ID_HIGHLIGHTS_CONTAINER",c.R2_ID_BOOKMAKRS_CONTAINER="R2_ID_BOOKMAKRS_CONTAINER",c.R2_ID_READALOUD_CONTAINER="R2_ID_READALOUD_CONTAINER",c.R2_ID_PAGEBREAK_CONTAINER="R2_ID_PAGEBREAK_CONTAINER",c.R2_ID_SEARCH_CONTAINER="R2_ID_SEARCH_CONTAINER",c.R2_ID_DEFINITIONS_CONTAINER="R2_ID_DEFINITIONS_CONTAINER",c.R2_ID_LINEFOCUS_CONTAINER="R2_ID_LINEFOCUS_CONTAINER",c.R2_ID_GUTTER_RIGHT_CONTAINER="R2_ID_GUTTER_RIGHT_CONTAINER"})(et||(et={}));var Q_="R2_CLASS_HIGHLIGHT_CONTAINER",xl="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",$n="R2_CLASS_HIGHLIGHT_AREA",Cl="R2_CLASS_HIGHLIGHT_ICON",Lr=.5,eS=.75,gs={blue:100,green:50,red:230},yn=[],vD="data-highlighted",wD="data-timestamp",ba={ELEMENT_NODE:1,TEXT_NODE:3},ji=[et.R2_ID_HIGHLIGHTS_CONTAINER,et.R2_ID_PAGEBREAK_CONTAINER,et.R2_ID_SEARCH_CONTAINER,et.R2_ID_READALOUD_CONTAINER,et.R2_ID_BOOKMAKRS_CONTAINER,et.R2_ID_DEFINITIONS_CONTAINER,et.R2_ID_LINEFOCUS_CONTAINER,et.R2_ID_GUTTER_RIGHT_CONTAINER,Q_,$n,xl],H0=-1,U0=-1,ht=class{constructor(t,n,i,o,s,l){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.showTool=(0,Al.debounce)(t=>{this.isAndroid()||this.snapSelectionToWord(t),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,Al.debounce)(()=>{this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen(),this.delegate.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,Al.debounce)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.delegate.emit("toolbox.closed","closed"))},100);this.selection=(0,Al.debounce)((t,n)=>{this.api?.selection&&this.api?.selection(t,n)},100);this.getScrollingElement=t=>t?.scrollingElement?t?.scrollingElement:t?.body?t?.body:document.createElement("body");this.delegate=t,this.layerSettings=n,this.properties=i,this.api=l,this.hasEventListener=o,this.options=this.defaults(s,{color:"#fce300",highlightedClass:"highlighted",contextClass:"highlighter-context",onBeforeHighlight:function(){return!0},onAfterHighlight:function(){}}),this.delegate.highlighter=this}static async create(t){let n=new this(t.delegate,t.layerSettings,t,!1,{},t.api);return new Promise(i=>i(n))}async initialize(){let t=this.delegate.iframes[0].contentDocument;t&&this.dom(t.body).addClass(this.options.contextClass),this.bindEvents(this.delegate.iframes[0].contentDocument?.body,this,this.hasEventListener),this.initializeToolbox(),H0=-1,U0=-1;let n=this;async function i(){n.lastSelectedHighlight===void 0||(n.lastSelectedHighlight=void 0)}setTimeout(async()=>{let o=this.delegate.iframes[0].contentDocument;o&&await o.body?.addEventListener("click",i)},100)}haveSameColor(t,n){return this.dom(t).color()===this.dom(n).color()}defaults(t,n){t=t||{};for(let i in n)n.hasOwnProperty(i)&&t[i]===void 0&&(t[i]=n[i]);return t}unique(t){return t.filter(function(n,i,o){return o.indexOf(n)===i})}refineRangeBoundaries(t){let n=t.startContainer,i=t.endContainer,o=t.commonAncestorContainer,s=!0;if(t.endOffset===0){for(;!i.previousSibling&&i.parentNode!==o;)i=i.parentNode;i=i.previousSibling}else i.nodeType===ba.TEXT_NODE?t.endOffset<i.nodeValue.length&&i.splitText(t.endOffset):t.endOffset>0&&(i=i.childNodes.item(t.endOffset-1));return n.nodeType===ba.TEXT_NODE?t.startOffset===n.nodeValue.length?s=!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:s}}sortByDepth(t,n){let i=this;t.sort(function(o,s){return i.dom(n?s:o).parents().length-i.dom(n?o:s).parents().length})}groupHighlights(t){let n=[],i={},o=[];return t.forEach(function(s){let l=s.getAttribute(wD);typeof i[l]=="undefined"&&(i[l]=[],n.push(l)),i[l].push(s)}),n.forEach(function(s){let l=i[s];o.push({chunks:l,timestamp:s,toString:function(){return l.map(function(h){return h.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),s=o.length;for(;s--;)t.insertBefore(o[s],t.firstChild)},append:function(i){let o=Array.prototype.slice.call(i);for(let s=0,l=o.length;s<l;++s)t.appendChild(o[s])},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(s){o=s.parentNode,n.dom(s).insertBefore(s.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===ba.TEXT_NODE)for(;t.nextSibling&&t.nextSibling.nodeType===ba.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){H0=t.clientX,U0=t.clientY}async mouseup(t){Math.abs(H0-t.clientX)<3&&Math.abs(U0-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.delegate.iframes[0].contentDocument;t&&(this.unbindEvents(t.body,this),this.dom(t.body).removeClass(this.options.contextClass))}initializeToolbox(){let t=document.getElementById("highlight-toolbox-mode-colors"),n=document.getElementById("highlight-toolbox-mode-add"),i=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],o=document.getElementById("colorIcon"),s=document.getElementById("actionIcon"),l=document.getElementById("dismissIcon"),h=document.getElementById("collapseIcon"),c=document.getElementById("highlightIcon"),d=this;if(l&&(l.innerHTML=mr.close,l.addEventListener("click",function(){d.toolboxMode("add")})),h&&(h.innerHTML=mr.close,h.addEventListener("click",function(){d.toolboxMode("add")})),o){o.style.position="relative",o.style.zIndex="20",i.forEach(w=>{let v=document.getElementById(w),g=document.getElementById(`c${w}`);v&&t?.contains(v)&&t.removeChild(v),n&&g&&n.contains(g)&&n.removeChild(g)});let m=[],y=[];if(o.addEventListener("click",function(){d.toolboxMode("colors")}),this.delegate.rights.enableAnnotations){let w=10;i.forEach(v=>{w--;let g=o?.cloneNode(!0),f=g.lastChild,p=ht.hexToRgbChannels(v);f.style.backgroundColor="rgba("+[p.red,p.green,p.blue].join(",")+",.5)",g.id=`c${v}`,g.style.display="unset",g.style.position="relative",g.style.zIndex=`${w}`,g.style.marginLeft="-30px",y.push(g),n?.insertBefore(g,c)})}i.forEach(w=>{let v=o?.cloneNode(!0),g=v.lastChild;g.style.backgroundColor=w,v.id=w,v.style.position="relative",v.style.display="unset",m.push(v),o&&v.addEventListener("click",function(){d.setColor(w);let f=o?.lastChild;f&&(f.style.backgroundColor=w);let p=document.getElementById("highlightIcon"),b=document.getElementById("underlineIcon"),S=document.getElementById("noteIcon");(p?.getElementsByTagName?.("span").length??0)>0&&((p?.getElementsByTagName("span")[0]).style.background=d.getColor()),(b?.getElementsByTagName?.("span").length??0)>0&&((b?.getElementsByTagName("span")[0]).style.borderBottomColor=d.getColor()),(S?.getElementsByTagName?.("span").length??0)>0&&((S?.getElementsByTagName("span")[0]).style.borderBottomColor=d.getColor()),d.toolboxMode("add")}),t?.insertBefore(v,l)})}s&&s.addEventListener("click",function(){d.toolboxMode("action")}),d.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"),s=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"),s&&(s.style.display="none");break;case"edit":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="unset"),s&&(s.style.display="none");break;case"action":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),s&&(s.style.display="unset");break;default:n&&(n.style.display="none"),i&&(i.style.display="unset"),o&&(o.style.display="none"),s&&(s.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.delegate.iframes[0].contentDocument;if(i){let s=n.dom(i.body)?.getSelection();if(n.dom(i.body)&&s&&!s?.isCollapsed){let d=function(p){let b=p.match(new RegExp("[^a-zA-Z0-9]+$"));return!b||!b.index?p:p.slice(0,b.index)},l=s.toString(),h=l.length-l.trimStart().length,c=l.length-l.trimEnd().length,m=l.length;var o=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;l=l.replace(o,""),h=m-l.trimStart().length,l=d(l),c=m-l.trimEnd().length;let y=document.createRange();t?(y.setStart(s.anchorNode,s.anchorOffset+h),y.setEnd(s.focusNode,s.focusOffset-c)):(y.setStart(s.anchorNode,s.anchorOffset),y.setEnd(s.focusNode,s.focusOffset));let w=y.collapsed;y.detach();let v=s.focusNode,g;t?(g=s.focusOffset-c,s.collapse(s.anchorNode,s.anchorOffset+h)):(g=s.focusOffset,s.collapse(s.anchorNode,s.anchorOffset));let f=["forward","backward"];w&&(f=["backward","forward"]),t?(s.modify("move",f[0],"character"),s.modify("move",f[1],"word"),s.extend(v,g),s.modify("extend",f[1],"character"),s.modify("extend",f[0],"word")):s.extend(v,g),this.selection(s.toString(),s)}return s}}toolboxShow(){if(this.activeAnnotationMarkerId===void 0){let t=this,n=document.getElementById("highlight-toolbox-mode-add"),i=this.dom(this.delegate.iframes[0].contentDocument?.body).getRange();if((!i||i.collapsed)&&n){getComputedStyle(n).display!=="none"&&t.toolboxHide();return}this.isIOS()&&setTimeout(function(){let o=t.delegate.iframes[0].contentDocument;if(o){let s=t.dom(o.body).getSelection();s.removeAllRanges(),setTimeout(function(){s.addRange(i);function l(d){let m={className:w=>ji.indexOf(w)<0,idName:w=>ji.indexOf(w)<0},y=t.delegate.iframes[0].contentDocument;if(y)return Nn(d,y,m)}let h=t.delegate.iframes[0].contentWindow,c=Ir(h,l);t.delegate.annotationModule?.annotator?.saveTemporarySelectionInfo(c)},5)}},100),this.toolboxPlacement(),this.toolboxHandler()}}toolboxPlacement(){let t=this.dom(this.delegate.iframes[0].contentDocument?.body).getRange();if(!t||t.collapsed)return;let n=t.getBoundingClientRect(),i=document.getElementById("highlight-toolbox");i&&(this.delegate.view?.isPaginated()?i.style.top=n.top+(this.delegate.attributes?.navHeight??0)+"px":i.style.top=n.top+"px",i.style.left=(n.right-n.left)/2+n.left+"px")}toolboxHandler(){let t=document.getElementById("highlight-toolbox");if(t&&getComputedStyle(t).display==="none"){t.style.display="block",this.delegate.view?.isPaginated()?t.style.position="absolute":t.style.position="relative",this.selectionMenuOpened();let i=this;i.toolboxMode("add");let o=document.getElementById("highlightIcon"),s=document.getElementById("collapseIcon"),l=document.getElementById("underlineIcon"),h=document.getElementById("noteIcon"),c=document.getElementById("colorIcon"),d=document.getElementById("speakIcon");if(this.delegate.rights.enableAnnotations){if(o&&(o.style.display="unset",c&&o.getElementsByTagName("span").length>0&&(o.getElementsByTagName("span")[0].style.background=this.getColor())),l&&(l.style.display="unset",c&&l.getElementsByTagName("span").length>0&&(l.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),h&&(h.style.display="unset",c&&h.getElementsByTagName("span").length>0&&(h.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),c){c.style.display="unset";let m=c.lastChild;m.style.backgroundColor=this.getColor()}if(o){let m=function(){i.doHighlight(!1,ot.Highlight),i.toolboxHide(),o?.removeEventListener("click",m)},y=o.cloneNode(!0);o?.parentNode?.replaceChild(y,o),o=document.getElementById("highlightIcon"),o?.addEventListener("click",m)}if(l){let m=function(){i.doHighlight(!1,ot.Underline),i.toolboxHide(),l?.removeEventListener("click",m)},y=l.cloneNode(!0);l?.parentNode?.replaceChild(y,l),l=document.getElementById("underlineIcon"),l?.addEventListener("click",m)}if(h){let m=function(){i.doHighlight(!1,ot.Comment),i.toolboxHide(),h?.removeEventListener("click",m)},y=h.cloneNode(!0);h?.parentNode?.replaceChild(y,h),h=document.getElementById("noteIcon"),h?.addEventListener("click",m)}}else o&&o.style.setProperty("display","none"),l&&l.style.setProperty("display","none"),h&&h.style.setProperty("display","none"),c&&c.style.setProperty("display","none"),s&&s.style.setProperty("display","none");if(this.delegate.rights.enableTTS){if(d){let m=function(){d?.removeEventListener("click",m),i.speak()},y=d.cloneNode(!0);d?.parentNode?.replaceChild(y,d),d=document.getElementById("speakIcon"),d?.addEventListener("click",m)}}else d&&d.style.setProperty("display","none");(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).forEach(m=>{m.icon&&(m.icon.id=m.id);let y=document.getElementById(m.id),w=this;function v(){y?.removeEventListener("click",v);function g(p){let b={className:C=>ji.indexOf(C)<0,idName:C=>ji.indexOf(C)<0},S=w.delegate.iframes[0].contentDocument;if(S)return Nn(p,S,b)}let f=w.delegate.iframes[0].contentWindow;if(f){let p=Ir(f,g);if(p===void 0){let b=w.delegate.iframes[0].contentDocument;p=w.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(b)}if(p!==void 0)if(m.callback)m.callback(p.cleanText,p.range?.startContainer.parentElement);else{let b=m.highlight?.style,S=m.marker?m.marker:ot.Custom;if(S===ot.Custom&&w.delegate.rights.enableAnnotations||S===ot.Bookmark&&w.delegate.rights.enableBookmarks){let C=w.delegate.iframes[0].contentDocument;if(C){let x=w.createHighlight(w.dom(C.body).getWindow(),p,m.highlight?.color,!0,S,m.icon,m.popup,b);w.options.onAfterHighlight(x,S),w.delegate.rights.enableAnnotations?w.delegate.annotationModule?.saveAnnotation(x[0]).then(E=>{m?.note&&E.highlight&&w.delegate.annotationModule?.api?.addCommentToAnnotation(E).then(T=>{w.delegate.annotationModule?.updateAnnotation(T).then(async()=>{yi.default.log("update highlight "+T.id)})})}):w.delegate.rights.enableBookmarks&&w.delegate.bookmarkModule?.saveAnnotation(x[0])}}}}w.callbackComplete()}if(y){let g=y.cloneNode(!0);y?.parentNode?.replaceChild(g,y),y=document.getElementById(m.id),y?.addEventListener("click",v)}})}}doHighlight(t,n){let i=this;function o(l){let h={className:d=>ji.indexOf(d)<0,idName:d=>ji.indexOf(d)<0},c=i.delegate.iframes[0].contentDocument;if(c)return Nn(l,c,h)}let s=i.delegate.iframes[0].contentWindow;if(s){let l=Ir(s,o);if(l===void 0){let h=i.delegate.iframes[0].contentDocument;l=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(h)}if(l){if(this.options.onBeforeHighlight(l)===!0){let h;h=this.getColor(),ht.isHexColor(h)&&(h=ht.hexToRgbChannels(h));let c=i.delegate.iframes[0].contentDocument;if(c){let d=this.createHighlight(i.dom(c.body).getWindow(),l,h,!0,n??ot.Highlight);this.options.onAfterHighlight(d,n),this.delegate.rights.enableAnnotations&&n!==ot.Bookmark?this.delegate.annotationModule?.saveAnnotation(d[0]):this.delegate.rights.enableBookmarks&&n===ot.Bookmark&&this.delegate.bookmarkModule?.saveAnnotation(d[0])}}t||this.dom(this.delegate.iframes[0].contentDocument?.body).removeAllRanges()}else t||this.dom(this.delegate.iframes[0].contentDocument?.body).removeAllRanges()}}speak(){if(this.delegate.rights.enableTTS){let n=function(l){let h={className:d=>ji.indexOf(d)<0,idName:d=>ji.indexOf(d)<0},c=t.delegate.iframes[0].contentDocument;if(c)return Nn(l,c,h)},t=this,i=t.delegate.iframes[0].contentWindow;if(i){let l=Ir(i,n);if(l===void 0){let h=t.delegate.iframes[0].contentDocument;l=t.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(h)}l!==void 0&&this.delegate.ttsModule.speak(l,!0,()=>{})}let o=t.delegate.iframes[0].contentDocument;o&&t.dom(o.body).getSelection().removeAllRanges();let s=document.getElementById("highlight-toolbox");s&&(s.style.display="none"),this.selectionMenuClosed()}}stopReadAloud(){this.delegate.rights.enableTTS&&this.doneSpeaking()}callbackComplete(){this.toolboxHide();let t=this.delegate.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges()}isOutsideViewport(t){let n=Rt(document,"#iframe-wrapper"),i=n.scrollLeft,o=i+n.clientWidth,s=t.left+t.width,l=t.top+t.height,h=n.scrollTop,c=h+n.clientHeight,d=l<h,m=t.top>c,y=s<i,w=t.left>o;return d||m||y||w}isInsideViewport(t){let n=Rt(document,"#iframe-wrapper"),i=n.scrollTop,o=i+n.clientHeight,s=t.top+20>=i,l=t.top<=o,h=n.scrollLeft,c=h+n.clientWidth,d=t.left+t.width,m=t.left>h,y=d<c;return s&&l&&m&&y}get visibleTextRects(){let t=this.delegate.iframes[0].contentDocument;if(t){let i=function(h,c=[]){let d=h.firstChild;for(;d;)d.nodeType===1&&i(d,c),d.nodeType===3&&d.textContent?.trim()&&c.push(d),d=d.nextSibling;return c},o=function(h){return i(h).map(d=>{let{top:m,height:y,left:w,width:v}=s(d);return{top:m,height:y,width:v,left:w,node:d,textContent:d.textContent??""}})},s=function(h){try{let c=document.createRange();c.selectNode(h);let d=c.getBoundingClientRect();return c.detach(),d}catch(c){yi.default.log("measureTextNode "+c),yi.default.log("measureTextNode "+h),yi.default.log(`${h.textContent}`)}},n=Qr(t,"body");return o(n).filter(h=>this.isInsideViewport(h))}return[]}doneSpeaking(t=!1){if(this.delegate.rights.enableTTS){this.toolboxHide();let n=this.delegate.iframes[0].contentDocument;n&&this.dom(n.body).removeAllRanges(),this.delegate.ttsModule.cancel(),t&&this.delegate.reload()}}normalizeHighlights(t){var n;return n=t.filter(function(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 s=!1;return t.forEach(function(l,h){let c=l.parentElement,d=c.previousSibling,m=c.nextSibling;i.isHighlight(c)&&(i.haveSameColor(c,l)?(c.replaceChild(l.firstChild,l),t[h]=c,s=!0):(l.nextSibling||(i.dom(l).insertBefore(m||c),s=!0),l.previousSibling||(i.dom(l).insertAfter(d||c),s=!0),c.hasChildNodes()||i.dom(c).remove()))}),s}do n=o();while(n)}mergeSiblingHighlights(t){let n=this;function i(o,s){return s&&s.nodeType===ba.ELEMENT_NODE&&n.haveSameColor(o,s)&&n.isHighlight(s)}t.forEach(function(o){let s=o.previousSibling,l=o.nextSibling;i(o,s)&&(n.dom(o).prepend(s.childNodes),n.dom(s).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===ba.ELEMENT_NODE&&t.hasAttribute(vD)}createWrapper(){let t=document.createElement("mark");return t.style.background="linear-gradient("+ht.hexToRgbA(this.options.color)+", "+ht.hexToRgbA(this.options.color)+")",t.className=this.options.highlightedClass,t}static isHexColor(t){return/^#([A-Fa-f0-9]{3}){1,2}$/.test(t)}static hexToRgbString(t){let n;return n=t.substring(1).split(""),n.length===3&&(n=[n[0],n[0],n[1],n[1],n[2],n[2]]),n="0x"+n.join(""),n}static hexToRgbChannels(t){let n;if(this.isHexColor(t))return n=this.hexToRgbString(t),{red:n>>16&255,green:n>>8&255,blue:n&255};throw new Error("Bad Hex")}static hexToRgbA(t){let n;if(this.isHexColor(t))return n=this.hexToRgbChannels(t),"rgba("+[n.red,n.green,n.blue].join(",")+",.5)";if(typeof t=="object"){let i=t;return"rgba("+[i.red,i.green,i.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(t,n){let i;if(this.isHexColor(t))return i=this.hexToRgbChannels(t),"rgba("+[i.red,i.green,i.blue].join(",")+","+n+")";if(typeof t=="object"){let o=t;return"rgba("+[o.red,o.green,o.blue].join(",")+","+n+")"}throw new Error("Bad Hex")}resetHighlightBoundingStyle(t){t.style.outline="none",t.style.setProperty("background-color","transparent","important")}resetHighlightAreaStyle(t,n){let i=this.delegate.iframes[0].contentWindow?.document,o=t.parentNode&&t.parentNode.nodeType===Node.ELEMENT_NODE&&t.parentNode.getAttribute?t.parentNode.getAttribute("id"):void 0;if(o){let s=yn.find(l=>l.id===o);if(s){if(s.marker===ot.Custom||s.marker===ot.Bookmark)if(s.style?.hover){if(s.style?.hover)for(let c=0;c<s.style?.hover?.length;c++){let d=s.style?.hover[c];t.style.removeProperty(d.property)}let h="";if(s.style?.default)for(let c=0;c<s.style?.default?.length;c++){let d=s.style?.default[c];t.style.removeProperty(d.property),h+=`${d.property}: ${d.value} !${d.priority};`}t.setAttribute("style",`${t.getAttribute("style")}; ${h}`)}else if(s.style?.hoverClass){s.style?.hoverClass&&t.classList.remove(s.style?.hoverClass);let h="";s.style?.defaultClass&&t.classList.add(s.style?.defaultClass),t.setAttribute("style",`${t.getAttribute("style")}; ${h}`)}else if(ht.isHexColor(s.color)){let h=ht.hexToRgbChannels(s.color);t.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${0})`,"important")}else t.classList.remove("hover");else if(s.marker===ot.Underline||s.marker===ot.Comment)if(typeof s.color=="object"){let h=s.color;t.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${h.red}, ${h.green}, ${h.blue}, ${1})`,"important")}else if(ht.isHexColor(s.color)){let h=ht.hexToRgbChannels(s.color);t.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${h.red}, ${h.green}, ${h.blue}, ${1})`,"important")}else t.classList.remove("hover");else if(typeof s.color=="object"){let h=s.color;t.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${Lr})`,"important")}else if(ht.isHexColor(s.color)){let h=ht.hexToRgbChannels(s.color);t.style.setProperty("background-color",`rgba(${h.red}, ${h.green}, ${h.blue}, ${Lr})`,"important")}else t.classList.remove("hover");let l;if(i){let h=i.getElementById(n);h&&(l=h.querySelector(`#${s.id}`))}if(l){let h=l.getElementsByClassName(Cl);if(h.length>0){let c=h.item(0).getElementsByClassName("icon-tooltip");c.length>0&&c.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(t,n,i){for(let o of n){if(i.marker===ot.Custom||i.marker===ot.Bookmark)if(i.style?.hover){if(i.style?.default)for(let l=0;l<i.style?.default?.length;l++){let h=i.style?.default[l];o.style.removeProperty(h.property)}let s="";for(let l=0;l<i.style?.hover?.length;l++){let h=i.style?.hover[l];o.style.removeProperty(h.property),s+=`${h.property}: ${h.value} !${h.priority};`}o.setAttribute("style",`${o.getAttribute("style")}; ${s}`)}else if(i.style?.hoverClass){i.style?.defaultClass&&o.classList.remove(i.style?.defaultClass);let s="";o.classList.add(i.style?.hoverClass),o.setAttribute("style",`${o.getAttribute("style")}; ${s}`)}else if(ht.isHexColor(i.color)){let s=ht.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${.1})`,"important")}else o.classList.add("hover");else if(i.marker===ot.Underline||i.marker===ot.Comment)if(typeof i.color=="object"){let s=i.color;o.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${s.red}, ${s.green}, ${s.blue}, ${1})`,"important")}else if(ht.isHexColor(i.color)){let s=ht.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${s.red}, ${s.green}, ${s.blue}, ${1})`,"important")}else o.classList.add("hover");else if(typeof i.color=="object"){let s=i.color;o.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${eS})`,"important")}else if(ht.isHexColor(i.color)){let s=ht.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${s.red}, ${s.green}, ${s.blue}, ${eS})`,"important")}else o.classList.add("hover");if(i.type!==mt.Definition){let l=t.getElementById(et.R2_ID_HIGHLIGHTS_CONTAINER).querySelector(`#${i.id}`).getElementsByClassName(Cl);if(l.length>0){let h=l.item(0).getElementsByClassName("icon-tooltip");h.length>0&&h.item(0).style.setProperty("display","block")}}}}setAndResetSearchHighlight(t,n){let i=this.delegate.iframes[0].contentWindow?.document,o=Array.from(i.getElementById(et.R2_ID_SEARCH_CONTAINER).querySelectorAll(`.${$n}`));for(let s of o){let l=s,h=l.parentNode&&l.parentNode.nodeType===Node.ELEMENT_NODE&&l.parentNode.getAttribute?l.parentNode.getAttribute("id"):void 0;if(n.forEach(c=>{if(h===c.id&&c){if(typeof c.color=="object"){let y=c.color;l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${Lr})`,"important")}else if(ht.isHexColor(c.color)){let y=ht.hexToRgbChannels(c.color);l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${Lr})`,"important")}else l.classList.remove("hover");let m=i.getElementById(et.R2_ID_SEARCH_CONTAINER).querySelector(`#${c.id}`).getElementsByClassName(Cl);if(m.length>0){let y=m.item(0).getElementsByClassName("icon-tooltip");y.length>0&&y.item(0).style.removeProperty("display")}}}),h===t.id&&t){if(typeof t.color=="object"){let m=t.color;l.style.setProperty("background-color",`rgba(${m.red}, ${m.green}, ${m.blue}, ${Lr})`,"important")}else if(ht.isHexColor(t.color)){let m=ht.hexToRgbChannels(t.color);l.style.setProperty("background-color",`rgba(${m.red}, ${m.green}, ${m.blue}, ${Lr})`,"important")}else l.classList.remove("hover");let d=i.getElementById(et.R2_ID_SEARCH_CONTAINER).querySelector(`#${t.id}`).getElementsByClassName(Cl);if(d.length>0){let m=d.item(0).getElementsByClassName("icon-tooltip");m.length>0&&m.item(0).style.removeProperty("display")}}}}isIOS(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}isAndroid(){return navigator.userAgent.match(/Android/i)!=null}async processMouseEvent(t){let n=this.delegate.iframes[0].contentWindow?.document,i=t.clientX,o=t.clientY;if(!n||!n.getElementById(et.R2_ID_HIGHLIGHTS_CONTAINER)&&!n.getElementById(et.R2_ID_SEARCH_CONTAINER)&&!n.getElementById(et.R2_ID_PAGEBREAK_CONTAINER)&&!n.getElementById(et.R2_ID_READALOUD_CONTAINER)&&!n.getElementById(et.R2_ID_DEFINITIONS_CONTAINER))return;let s=this.delegate.view?.isPaginated(),l=n.body.getBoundingClientRect(),h=this.getScrollingElement(n),c=s?-h.scrollLeft:l.left,d=s?-h.scrollTop:l.top,m,y;for(let w=yn.length-1;w>=0;w--){let v=yn[w],g=n.getElementById(`${v.id}`);if(!g){let b=n.getElementById(et.R2_ID_HIGHLIGHTS_CONTAINER);b&&(g=b.querySelector(`#${v.id}`))}if(!g)continue;let f=!1,p=g.querySelectorAll(`.${$n}`);for(let b of p){let S=b,C=S.rect.left+c,x=S.rect.top+d;if(i>=C&&i<C+S.rect.width&&o>=x&&o<x+S.rect.height){f=!0;break}}if(f){m=v,y=g;break}}if(!m||!y){for(let w in et){let v=n.getElementById(w);if(v){let g=v.querySelectorAll(`.${xl}`);for(let p of g)this.resetHighlightBoundingStyle(p);let f=Array.from(v.querySelectorAll(`.${$n}`));for(let p of f)this.resetHighlightAreaStyle(p,w)}}return}if(y.getAttribute("data-click")){if((t.type==="mousemove"||t.type==="touchmove")&&y.parentElement?.style.display!=="none"){let w=Array.from(y.querySelectorAll(`.${$n}`));for(let g in et){let f=n.getElementById(g);if(f){let p=f.querySelectorAll(`.${$n}`);for(let b of p)w.indexOf(b)<0&&this.resetHighlightAreaStyle(b,g)}}this.setHighlightAreaStyle(n,w,m);let v=y.querySelector(`.${xl}`);for(let g in et){let f=n.getElementById(g);if(f){let p=f.querySelectorAll(`.${xl}`);for(let b of p)(!v||b!==v)&&this.resetHighlightBoundingStyle(b)}}}else if((t.type==="mouseup"||t.type==="click"||t.type==="touchup")&&y.parentElement?.style.display!=="none"){let w={highlight:m};yi.default.log(JSON.stringify(w));let v=this,g;if(v.delegate.rights.enableAnnotations?g=await this.delegate.annotationModule?.getAnnotation(w.highlight):v.delegate.rights.enableBookmarks&&(g=await this.delegate.bookmarkModule?.getAnnotation(w.highlight)),w.highlight.type===mt.Annotation&&this.delegate.annotationModule?.api?.selectedAnnotation(g).then(async()=>{}),g?.id){yi.default.log("selected highlight "+g.id),v.lastSelectedHighlight=g.id;let f=document.getElementById("highlight-toolbox");if(f)if(f.style.top=t.clientY+(this.delegate.attributes?.navHeight??0)+"px",f.style.left=t.clientX+"px",getComputedStyle(f).display==="none"){let S=function(){v.delegate.annotationModule?.api?.addCommentToAnnotation(g).then(O=>{v.delegate.annotationModule?.updateAnnotation(O).then(async()=>{yi.default.log("update highlight "+O.id),f&&(f.style.display="none"),v.selectionMenuClosed()}),f&&(f.style.display="none"),v.selectionMenuClosed(),C?.removeEventListener("click",S,!1)})},E=function(){v.delegate.rights.enableAnnotations?v.delegate.annotationModule?.deleteSelectedHighlight(g).then(async()=>{yi.default.log("delete highlight "+g.id),f&&(f.style.display="none"),v.selectionMenuClosed()}):v.delegate.rights.enableBookmarks&&v.delegate.bookmarkModule?.deleteSelectedHighlight(g).then(async()=>{yi.default.log("delete highlight "+g.id),f&&(f.style.display="none"),v.selectionMenuClosed()})};f.style.display="block",this.toolboxMode("edit");let p=document.getElementById("colorIcon"),b=document.getElementById("highlightIcon");p&&(p.style.display="none"),b&&(b.style.display="none");let C=document.getElementById("commentIcon"),x=document.getElementById("cloneCommentIcon");if(x){let O=x.parentElement;O&&O.removeChild(x)}if(C){C.style.display="none";let O=C.cloneNode(!0),L=C.parentElement;O.style.display="unset",O.id="cloneCommentIcon",O.addEventListener("click",S,!1),L&&L.append(O)}let T=document.getElementById("deleteIcon"),R=document.getElementById("cloneDeleteIcon");if(R){let O=R.parentElement;O&&O.removeChild(R)}if(T){T.style.display="none";let O=T.cloneNode(!0),L=T.parentElement;O.style.display="unset",O.id="cloneDeleteIcon",O.addEventListener("click",E,!1),L&&L.append(O)}}else f.style.display="none",this.selectionMenuClosed(),f.offsetWidth,f.style.display="block"}else{y.dataset.definition&&new _l(this.delegate).showPopup(y.dataset.definition,t);let f=this.delegate.definitionsModule?.properties?.definitions?.filter(p=>p.order===Number(y?.dataset.order))[0];yi.default.log(f),this.delegate.definitionsModule?.api?.click&&(this.delegate.definitionsModule.api?.click(j0.omit(f,"callbacks"),j0.omit(m,"definition")),this.delegate.emit("definition.click",f,m))}}}}async prepareContainers(t){for(let n in et)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!==et.R2_ID_GUTTER_RIGHT_CONTAINER&&o.style.setProperty("pointer-events","none"),this.delegate.view?.layout==="fixed"&&(o.style.setProperty("position","absolute"),o.style.setProperty("top","0"),o.style.setProperty("left","0")),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(et.R2_ID_HIGHLIGHTS_CONTAINER)),this.removeAllChildNodes(t.getElementById(et.R2_ID_SEARCH_CONTAINER)),this.removeAllChildNodes(t.getElementById(et.R2_ID_READALOUD_CONTAINER)),this.removeAllChildNodes(t.getElementById(et.R2_ID_PAGEBREAK_CONTAINER)),this.removeAllChildNodes(t.getElementById(et.R2_ID_DEFINITIONS_CONTAINER))}destroyAllhighlights(t){this.hideAllhighlights(t),yn.splice(0,yn.length)}removeAllChildNodes(t){for(;t.firstChild;)t.removeChild(t.firstChild)}destroyHighlights(t){let n=this.delegate.iframes[0].contentWindow?.document;if(n){let i;switch(t){case mt.ReadAloud:i=n.getElementById(et.R2_ID_READALOUD_CONTAINER),i&&this.removeAllChildNodes(i);break;case mt.Search:i=n.getElementById(et.R2_ID_SEARCH_CONTAINER),i&&this.removeAllChildNodes(i);break;case mt.PageBreak:i=n.getElementById(et.R2_ID_PAGEBREAK_CONTAINER),i&&this.removeAllChildNodes(i);break;case mt.Definition:i=n.getElementById(et.R2_ID_DEFINITIONS_CONTAINER),i&&this.removeAllChildNodes(i);break;case mt.LineFocus:i=n.getElementById(et.R2_ID_LINEFOCUS_CONTAINER),i&&this.removeAllChildNodes(i);break;case mt.Comment:i=n.getElementById(et.R2_ID_GUTTER_RIGHT_CONTAINER),i&&this.removeAllChildNodes(i);break;default:i=n.getElementById(et.R2_ID_HIGHLIGHTS_CONTAINER),i&&this.removeAllChildNodes(i),yn.splice(0,yn.length);break}}}destroyHighlight(t,n){if(!t)return;let i=-1;yn.find((l,h)=>(i=h,l.id===n))&&i>=0&&i<yn.length&&yn.splice(i,1);let s=t.getElementById(n);s&&this.removeAllChildNodes(s)}createHighlight(t,n,i,o,s,l,h,c,d,m){try{let y=`${n.rangeInfo.startContainerElementCssSelector}${n.rangeInfo.startContainerChildTextNodeIndex}${n.rangeInfo.startOffset}${n.rangeInfo.endContainerElementCssSelector}${n.rangeInfo.endContainerChildTextNodeIndex}${n.rangeInfo.endOffset}`,w=er.hash(y),v=(m||"R2_HIGHLIGHT_")+w;this.destroyHighlight(t.document,v);let g=`rgb(${gs.red}, ${gs.green}, ${gs.blue})`,f={color:i||g,id:v,pointerInteraction:o,selectionInfo:n,marker:s,icon:l,popup:h,style:c,type:d||mt.Annotation};(d===mt.Annotation||d===mt.Definition||d===void 0)&&yn.push(f);let p=this.createHighlightDom(t,f);return f.position=parseInt((p?.hasChildNodes()?p.childNodes[0]:p).style.top.replace("px","")),[f,p]}catch(y){throw"Can't create highlight: "+y}}createHighlightDom(t,n){let i=t.document,o=Wd(i,n.selectionInfo.rangeInfo);if(!o)return;for(let F in et)this.ensureHighlightsContainer(t,F);let s=i.createElement("div");s.setAttribute("id",n.id),s.setAttribute("class",Q_),s.style.setProperty("pointer-events","none"),n.pointerInteraction&&s.setAttribute("data-click","1");let l=this.delegate.view?.isPaginated();l?i.body.style.position="revert":i.body.style.position="relative";let h=i.body.getBoundingClientRect(),c=this.getScrollingElement(i),d=l?-c.scrollLeft:h.left,m=l?-c.scrollTop:h.top,y=1,w=!1,v=!1,p=$d(o,w||v||!1),b=3,S=2,C=3,x=0,E=24,T,R;for(let F of p){let q=i.createElement("div");q.setAttribute("class",$n),q.dataset.marker=""+n.marker;let G="";if(w&&n.marker!==ot.Custom&&n.marker!==ot.Bookmark&&n.marker!==ot.Comment){let D=n.color;ht.isHexColor(D)&&(D=ht.hexToRgbChannels(D)),G+=`border-bottom: ${S*y}px solid rgba(${D.red}, ${D.green}, ${D.blue}, ${Lr}) !important`}if(n.marker===ot.Custom||n.marker===ot.Bookmark)if(n.style?.default){for(let D=0;D<n.style?.default?.length;D++){let W=n.style?.default[D];G+=`${W.property}: ${W.value} !${W.priority};`}q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${b}px !important; ${G}`)}else n.style?.defaultClass&&(q.classList.add(n.style?.defaultClass),q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${b}px !important; ${G}`));else if(n.marker===ot.Underline||n.marker===ot.Comment)if(typeof n.color=="object"){let D=n.color;q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${b}px !important; background-color: rgba(${D.red}, ${D.green}, ${D.blue}, ${0}) !important; ${G}`),q.style.setProperty("border-bottom",`2px solid rgba(${D.red}, ${D.green}, ${D.blue}, ${1})`,"important")}else if(ht.isHexColor(n.color)){let D=ht.hexToRgbChannels(n.color);q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${b}px !important; background-color: rgba(${D.red}, ${D.green}, ${D.blue}, ${0}) !important; ${G}`),q.style.setProperty("border-bottom",`2px solid rgba(${D.red}, ${D.green}, ${D.blue}, ${1})`,"important")}else q.setAttribute("style",`border-radius: ${b}px !important; ${G}`);else if(typeof n.color=="object"){let D=n.color;q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${b}px !important; background-color: rgba(${D.red}, ${D.green}, ${D.blue}, ${Lr}) !important; ${G}`)}else if(ht.isHexColor(n.color)){let D=ht.hexToRgbChannels(n.color);q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${b}px !important; background-color: rgba(${D.red}, ${D.green}, ${D.blue}, ${Lr}) !important; ${G}`)}else q.setAttribute("style",`border-radius: ${b}px !important; ${G}`);q.style.setProperty("pointer-events","none"),q.style.position="absolute",q.scale=y,q.rect={height:F.height,left:F.left-d,top:F.top-m,width:F.width},n.pointerInteraction&&(q.setAttribute("data-click","1"),q.tabIndex=0),q.style.width=`${q.rect.width*y}px`,q.style.height=`${q.rect.height*y}px`,q.style.left=`${q.rect.left*y}px`,q.style.top=`${q.rect.top*y}px`,s.append(q);let ie=parseInt(q.style.top.replace("px",""));if((ie<x||x===0)&&(x=ie),E=parseInt(q.style.height.replace("px","")),v){let D=i.createElement("div");D.setAttribute("class",$n);let W=n.color;ht.isHexColor(W)&&(W=ht.hexToRgbChannels(W)),D.setAttribute("style",`background-color: rgba(${W.red}, ${W.green}, ${W.blue}, ${Lr}) !important;`),D.style.setProperty("pointer-events","none"),D.style.position="absolute",D.scale=y,D.rect={height:F.height,left:F.left-d,top:F.top-m,width:F.width},D.style.width=`${D.rect.width*y}px`,D.style.height=`${C*y}px`,D.style.left=`${D.rect.left*y}px`,D.style.top=`${(D.rect.top+D.rect.height/2-C/2)*y}px`,s.append(D)}let ee=this.delegate.iframes[0].contentWindow?.innerWidth,Z=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-count")),X=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-width")),ce=parseInt(getComputedStyle(i.body).getPropertyValue("padding-left")),we=ee/(Z||1);we<X&&(we=ee),l||(we=parseInt(getComputedStyle(i.body).width.replace("px","")));let ve=this.delegate.settings.fontSize/100,Q=20*ve;ve<=1&&(Q=-60);let N=0*ve;ve<=1&&(N=-60),T=Math.floor(F.left/we)*we+we-(E<40?40:E)+N,R=Math.floor(F.left/we)*we+(E<40?40:E)-Q;let B=parseInt(this.delegate.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));B>=2&&(R=R+ce/Z,T=T-ce/Z),l||(T=parseInt(getComputedStyle(this.delegate.iframes[0].contentDocument?.body).width.replace("px","")),R=parseInt(getComputedStyle(this.delegate.iframes[0].contentDocument?.body).width.replace("px",""))-we,B>=2&&(R=R+ce/2,T=T-ce/2))}let O=o.getBoundingClientRect(),L=i.createElement("div");L.setAttribute("class",xl),L.style.setProperty("pointer-events","none"),L.style.position="absolute",L.scale=y,L.rect={height:O.height,left:O.left-d,top:O.top-m,width:O.width},L.style.width=`${L.rect.width*y}px`,L.style.height=`${L.rect.height*y}px`,L.style.left=`${L.rect.left*y}px`,L.style.top=`${L.rect.top*y}px`,s.append(L);let M=i.createElement("div");if(M.setAttribute("class",Cl),n.icon?.position==="left")M.setAttribute("style",`position: absolute;top:${x}px;left:${R+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`);else if(n.icon?.position==="inline")M.setAttribute("style",`position: absolute;top:${x-E/2}px;left:${parseInt(L.style.left.replace("px",""))+parseInt(L.style.width.replace("px",""))-E/2}px;height:${E}px; width:${E}px;`);else if(n.icon?.position==="center"){let q=E/3*2;M.setAttribute("style",`position: absolute;top:${x}px;left:${parseInt(L.style.left.replace("px",""))+parseInt(L.style.width.replace("px",""))-q}px;height:${E}px; width:${E}px;`)}else n.note&&n.marker!==ot.Custom&&n.marker!==ot.Bookmark&&n.marker!==ot.Comment&&n.marker!==ot.Highlight&&n.marker!==ot.Underline?M.setAttribute("style",`position: absolute;top:${x-E/2}px;left:${parseInt(L.style.left.replace("px",""))+parseInt(L.style.width.replace("px",""))-E/2}px;height:${E}px; width:${E}px;`):n.note&&n.marker===ot.Comment||n.marker===ot.Highlight||n.marker===ot.Underline?M.setAttribute("style",`position: absolute;top:${x}px;left:${T+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`):M.setAttribute("style",`position: absolute;top:${x}px;left:${T+this.delegate.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`);if(n.marker===ot.Custom||n.marker===ot.Bookmark)n.icon?.class?(M.classList.add(n.icon?.class),M.id=n.icon?.id):n.icon?.svgPath?M.innerHTML=ma(`${n.icon?.id}`,`${n.icon?.title}`,`${n.icon?.svgPath}`,"icon open",E,`${n.icon?.color} !important`):n.icon?.title&&(M.innerHTML=n.icon?.title);else if(n.note){let F=n.color;ht.isHexColor(F)&&(F=ht.hexToRgbChannels(F)),n.marker===ot.Comment||n.marker===ot.Highlight||n.marker===ot.Underline?M.innerHTML=ma("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",E/2,`rgba(${F.red}, ${F.green}, ${F.blue}, 1) !important`):M.innerHTML=ma("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(${F.red}, ${F.green}, ${F.blue}, 1) !important`)}M.style.setProperty("pointer-events","all");let k=this;if(n.type!==mt.PageBreak&&n.type!==mt.Definition&&M.addEventListener("click",async function(F){let q;k.delegate.rights.enableAnnotations?(q=await k.delegate.annotationModule?.getAnnotationByID(n.id),k.delegate.annotationModule?.api?.selectedAnnotation(q).then(async()=>{})):k.delegate.rights.enableBookmarks&&(q=await k.delegate.bookmarkModule?.getAnnotationByID(n.id)),yi.default.log("selected highlight "+q.id),k.lastSelectedHighlight=q.id;let G=document.getElementById("highlight-toolbox");if(G)if(G.style.top=F.clientY+(k.delegate.attributes?.navHeight??0)+"px",G.style.left=F.clientX+"px",getComputedStyle(G).display==="none"){let we=function(){k.delegate.rights.enableAnnotations?k.delegate.annotationModule?.deleteSelectedHighlight(q).then(async()=>{yi.default.log("delete highlight "+q.id),G.style.display="none",k.selectionMenuClosed()}):k.delegate.rights.enableBookmarks&&k.delegate.bookmarkModule?.deleteSelectedHighlight(q).then(async()=>{yi.default.log("delete highlight "+q.id),G.style.display="none",k.selectionMenuClosed()})};G.style.display="block",k.toolboxMode("edit");let ee=document.getElementById("colorIcon"),Z=document.getElementById("highlightIcon");ee&&(ee.style.display="none"),Z&&(Z.style.display="none");let X=document.getElementById("commentIcon"),ce=document.getElementById("cloneCommentIcon");if(ce){let N=ce.parentElement;N&&N.removeChild(ce)}X&&(X.style.display="none");let ve=document.getElementById("deleteIcon"),Q=document.getElementById("cloneDeleteIcon");if(Q){let N=Q.parentElement;N&&N.removeChild(Q)}if(ve){ve.style.display="none";let N=ve.cloneNode(!0),B=ve.parentElement;N.style.display="unset",N.id="cloneDeleteIcon",N.addEventListener("click",we,!1),B&&B.append(N)}}else G.style.display="none",k.selectionMenuClosed(),G.offsetWidth,G.style.display="block";let ie=Array.from(s.querySelectorAll(`.${$n}`));k.setHighlightAreaStyle(i,ie,n)}),n.note){let F=document.createElement("span");F.innerHTML=n.note,F.className="icon-tooltip",n.marker===ot.Custom||n.marker===ot.Bookmark?(n.popup?.background&&F.style.setProperty("background",n.popup.background),n.popup?.textColor&&F.style.setProperty("color",n.popup.textColor),n.popup?.class&&F.classList.add(n.popup.class)):(F.style.setProperty("background","lightyellow"),F.style.setProperty("color","black"))}switch((n.note||n.marker===ot.Custom||n.marker===ot.Bookmark)&&s.append(M),n.type){case mt.Search:i.getElementById(et.R2_ID_SEARCH_CONTAINER).append(s);break;case mt.ReadAloud:i.getElementById(et.R2_ID_READALOUD_CONTAINER).append(s);break;case mt.PageBreak:i.getElementById(et.R2_ID_PAGEBREAK_CONTAINER).append(s);break;case mt.Definition:i.getElementById(et.R2_ID_DEFINITIONS_CONTAINER).append(s);break;default:i.getElementById(et.R2_ID_HIGHLIGHTS_CONTAINER).append(s);break}return s}addSelectionMenuItem(t){(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).push(t)}};var hS=gt(X0());H();var RD=gt(cn());var Lo={className:r=>!0,idName:r=>!0,tagName:r=>!0};var fS=gt(Gd()),nr=gt(cn());H();var dS=gt(cn()),ms;(function(n){n.BookmarkCreated="BookmarkCreated",n.HighlightCreated="HighlightCreated"})(ms||(ms={}));var Z0=class{constructor(t,n,i,o){this.currSeconds=0;this.delegate=t,this.publication=n,this.properties=i,this.api=o}static async create(t){let n=new this(t.delegate,t.publication,t,t.api);return await n.start(),n}async start(){this.delegate.consumptionModule=this,this.startResearchSession()}async stop(){dS.default.log("Consumption module stop"),this.endResearchSession()}initialize(){let t=this.delegate.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){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){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)}}startIdleTimer(){this.currSeconds++,this.currSeconds==this.properties.idleTimeout&&(this.api?.idleSince(this.currSeconds),this.updateResearchSession()),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 Ol=class{constructor(t,n,i,o,s,l,h,c,d){this.hide=$e(document,"#menu-button-hide");this.show=$e(document,"#menu-button-show");this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=d,this.delegate=o,this.initialAnnotations=s,this.highlighter=h,this.properties=l,this.api=c}static async create(t){let n=new this(t.annotator,t.rights||{enableAnnotations:!1,enableTTS:!1},t.publication,t.delegate,t.initialAnnotations||null,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){nr.default.log("Annotation module stop")}async start(){if(this.delegate.annotationModule=this,this.headerMenu&&(this.highlightsView=$e(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var t=this.initialAnnotations.highlights||null;t&&this.annotator?.initAnnotations(t)}setTimeout(()=>{this.properties?.hideLayer?this.delegate.hideLayer("highlights"):this.delegate.showLayer("highlights")},10)}hideAnnotationLayer(){let t=this.delegate.iframes[0].contentDocument;if(t){let n=$e(t,"#R2_ID_HIGHLIGHTS_CONTAINER");n&&(n.style.display="none")}this.show&&this.hide&&(this.show.style.display="block",this.hide.style.display="none")}showAnnotationLayer(){let t=this.delegate.iframes[0].contentDocument;if(t){let n=$e(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(),Ce(this.delegate.iframes[0].contentDocument?.body,"click",this.click.bind(this))},300),t(null)})}click(t){if(this.activeAnnotationMarkerId){let n=this.highlighter?.properties?.selectionMenuItems?.filter(i=>i.id===this.activeAnnotationMarkerId);if(n&&n?.length>0){let i=fS.cloneDeep(n[0]);i.marker=ot.Custom,this.activeAnnotationMarkerPosition&&(i.icon.position=this.activeAnnotationMarkerPosition),i.highlight.style.default=null,i.highlight.style.hover=null;let o=this.delegate.iframes[0].contentDocument;if(o){let d=function(y){try{let w=c.delegate.iframes[0].contentDocument;return w?Nn(y,w,Lo):""}catch(w){return nr.default.log("uniqueCssSelector:"),nr.default.error(w),""}},s=this.highlighter?.dom(o.body).getSelection(),l=s.getRangeAt(0),h=s.anchorNode;l.setStart(h,l.startOffset),l.setEnd(h,l.endOffset+1),s.removeAllRanges(),s.addRange(l);let c=this,m=oo(l,d);if(s.removeAllRanges(),m){let y={rangeInfo:m},w=this.delegate.highlighter?.createHighlight(this.delegate.highlighter?.dom(o.body).getWindow(),y,i.highlight.color,!0,ot.Bookmark,i.icon,i.popup,i.highlight.style);w&&this.saveAnnotation(w[0]).then(v=>{nr.default.log("saved bookmark "+v.id)})}o.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(t){nr.default.log("still need to scroll to "+t);var n=await this.annotator?.getAnnotationElement(t,this.delegate.iframes[0].contentWindow);n.scrollIntoView({block:"center",behavior:"smooth"})}async updateLocalHighlight(t){if(this.annotator){let n=await this.annotator.deleteAnnotation(t.id),i=await this.addAnnotation(t);return nr.default.log("Highlight deleted "+JSON.stringify(n)),nr.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 nr.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.delegate.currentChapterLink.href);this.delegate.currentTocUrl&&(n=this.publication.getTOCItem(this.delegate.currentTocUrl)),n===void 0&&(n=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href));let i=this.delegate.view?.getCurrentPosition(),o=this.delegate.iframes[0].contentDocument;if(o){let s=Qr(o,"body"),l=t.position?t.position/s.scrollHeight:i,h=(0,hS.v4)(),c;if(n){let d=n.Href;if(d.indexOf("#")>0&&(d=d.slice(0,d.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let m=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),y=Math.ceil((l??0)*(m.length-1)),w=m[y];c=nn(dt({},w),{id:h,href:d,created:new Date,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else c={id:h,href:d,locations:{progression:l},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(c)if(this.delegate.consumptionModule?.trackAction(c,ms.HighlightCreated),this.api?.addAnnotation)try{let d=await this.api.addAnnotation(c),m=await this.annotator.saveAnnotation(d);return await this.showHighlights(),await this.drawHighlights(),new Promise(y=>y(m))}catch(d){await this.showHighlights(),await this.drawHighlights()}else{let d=await this.annotator.saveAnnotation(c);return await this.showHighlights(),await this.drawHighlights(),new Promise(m=>m(d))}}}return new Promise(i=>i(null))}getAnnotations(){let t=[];return this.annotator&&(t=this.annotator.getAnnotations()),t}showHighlights(){let t=[];this.annotator&&(t=this.annotator.getAnnotations(),t&&(t=t.filter(n=>n.highlight.marker!==ot.Bookmark),t.forEach(n=>{yn.push(n.highlight)}))),this.highlightsView&&this.createTree(Fi.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.delegate.currentLocator().href)),this.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(mt.Annotation);for(let i of n){yn.push(i.highlight);let o=i,s=this.delegate.currentChapterLink.href;var t=this.publication.getTOCItem(s);if(this.delegate.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&(await this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===ot.Underline){let h=await this.annotator?.getAnnotationPosition(i.id,this.delegate.iframes[0].contentWindow),c='<div class="comment" style="top: '+h+'px;width:20px"></div>',d=document.createElement("div");d.innerHTML=c;let m=d.childNodes[0],y=document.createElement("i");y.innerHTML="sticky_note_2",y.className="material-icons",y.style.color=o.highlight.color,m.appendChild(y),Ce(d,"click",w=>{w.preventDefault(),w.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}else{let n=[];if(this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.delegate.currentLocator().href)),this.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(mt.Annotation);for(let i of n){yn.push(i.highlight);let o=i,s=this.delegate.currentChapterLink.href,l=this.publication.getTOCItem(s);if(this.delegate.currentTocUrl&&(l=this.publication.getTOCItem(this.delegate.currentTocUrl)),l===null&&(l=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),l){let h=l.Href;h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),o.href===h&&(await this.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===ot.Underline){let c=await this.annotator?.getAnnotationPosition(i.id,this.delegate.iframes[0].contentWindow),d='<div class="comment" style="top: '+c+"px;background: "+o.highlight?.color+';width:20px"></div>',m=document.createElement("div");m.innerHTML=d,m.childNodes[0].innerHTML=mr.note,Ce(m,"click",y=>{y.preventDefault(),y.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){let t=this.delegate.iframes[0].contentDocument;if(t&&(this.commentGutter=t.getElementById(et.R2_ID_GUTTER_RIGHT_CONTAINER),this.delegate.view?.isScrollMode()&&this.properties?.enableComments?this.commentGutter?.style.removeProperty("display"):this.commentGutter?.style.setProperty("display","none"),this.commentGutter&&this.delegate.view?.isScrollMode()&&this.properties?.enableComments)){this.commentGutter.innerHTML="";let n=[];this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.delegate.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 s=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),l,h;s&&(l=s.querySelector(`#${i.highlight.id}`)),h=l.getElementsByClassName($n)[0];let d=parseInt(h.style.height.replace("px","")),m=i.highlight.position,y=t.createElement("div");y.setAttribute("style",`position: absolute;top:${m}px;display: flex;max-width: 250px !important;height:${d}px;width: 200px;align-items: center;`);let w=t.createElement("div");y.appendChild(w);let v=i.highlight.color;ht.isHexColor(v)&&(v=ht.hexToRgbChannels(v)),y.innerHTML=ma("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="8"/>',"icon open",10,`rgba(${v.red}, ${v.green}, ${v.blue}, 1) !important`);let g=t.createElement("div");g.innerHTML=i.highlight?.note,g.setAttribute("style",`height:${d}px;overflow: hidden;padding-left: 5px;`),y.appendChild(g),Ce(y,"click",f=>{f.preventDefault(),f.stopPropagation(),this.scrollToHighlight(i.highlight.id)}),this.commentGutter?.appendChild(y)})))}}createTree(t,n,i){if(n){let o=this,s=this.publication.readingOrder;if(s.length){let l=(h,c)=>{let d=document.createElement("ul");d.className="sidenav-annotations";for(let m of c){let y=document.createElement("li"),w=document.createElement("a"),v=document.createElement("span");if(w.tabIndex=-1,w.className="chapter-link",m.Href){let f=this.publication.getAbsoluteHref(m.Href),p=this.publication.getTOCItemAbsolute(f);w.href=f,w.innerHTML=p?.Title||"",y.appendChild(w)}else v.innerHTML=m.Title||"",v.className="chapter-title",y.appendChild(v);Ce(w,"click",f=>{f.preventDefault(),f.stopPropagation();let p={href:w.href,locations:{progression:0},type:m.TypeLink,title:w.title};this.delegate.stopReadAloud(),this.delegate.navigate(p)});let g=document.createElement("ol");n.forEach(function(f){let p=m.Href.indexOf("#")!==-1?m.Href.slice(0,m.Href.indexOf("#")):m.Href;if(m.Href&&f.href.endsWith(p)){let b=document.createElement("li");b.className="annotation-item";let S=document.createElement("a");if(S.setAttribute("href",f.href),t===Fi.Annotation){S.className="highlight-link";let x=document.createElement("span"),E=document.createElement("span");if(x.className="title",E.innerHTML=f.highlight.selectionInfo.cleanText,f.highlight?.marker===ot.Underline)if(typeof f.highlight?.color=="object"){let O=f.highlight?.color;O&&E.style.setProperty("border-bottom",`2px solid ${ht.hexToRgbA(O)}`,"important")}else E.style.setProperty("border-bottom",`2px solid ${f.highlight?.color}`,"important");else if(typeof f.highlight?.color=="object"){let O=f.highlight?.color;O&&(E.style.backgroundColor=ht.hexToRgbA(O))}else{let O=f.highlight?.color;O&&(E.style.backgroundColor=O)}x.appendChild(E),S.appendChild(x);let T=document.createElement("span"),R=Math.round((f.locations.progression??0)*100)+"% through resource";T.className="subtitle",T.innerHTML=R,S.appendChild(T)}let C=document.createElement("span");if(C.className="timestamp",C.innerHTML=Ol.readableTimestamp(f.created),S.appendChild(C),Ce(S,"click",x=>{x.preventDefault(),x.stopPropagation(),o.handleAnnotationLinkClick(x,f)}),b.appendChild(S),o.delegate.sideNavExpanded){let x=document.createElement("button");x.className="delete",x.innerHTML=mr.delete,Ce(x,"click",E=>{E.preventDefault(),E.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,E,f)}),b.appendChild(x)}g.appendChild(b)}}),g.children.length>0&&(d.appendChild(y),d.appendChild(g)),d.children.length>0&&h.appendChild(d),m.Children&&m.Children.length>0&&l(h,m.Children)}};i.innerHTML="",l(i,s)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.delegate.stopReadAloud(),this.delegate.navigate(n)):nr.default.log("annotation data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){nr.default.log("annotation data locator: ",i),i?t===Fi.Annotation&&this.deleteHighlight(i):nr.default.log("annotation data missing: ",n)}static readableTimestamp(t){let n=new Date(t);return n.toDateString()+" "+n.toLocaleTimeString()}async getAnnotation(t){return this.annotator?.getAnnotation(t)}async getAnnotationByID(t){return this.annotator?.getAnnotationByID(t)}syncPosition(t){let n=this.delegate.iframes[0].contentDocument,i=(o,s)=>{let l=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),h,c;l&&(h=l.querySelector(`#${s.highlight.id}`)),c=h.getElementsByClassName($n)[0];let m=parseInt(c.style.top.replace("px","")),y=nn(dt({},s),{highlight:nn(dt({},s.highlight),{position:m})});return[...o,y]};return t.reduce(i,[])}reposition(t){let n=this.delegate.iframes[0].contentDocument,i=(o,s,l)=>{let h=t[0],c=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),d,m;c&&(d=c.querySelector(`#${h.highlight.id}`)),m=d.getElementsByClassName($n)[0];let w=parseInt(m.style.height.replace("px","")),v=s.highlight.position,g=o[l-1]&&o[l-1].highlight.position,p=l===0?0:g+w+0,b=p>v?p:v,S=nn(dt({},s),{highlight:nn(dt({},s.highlight),{position:b})});return[...o,S]};return t.sort(function(o,s){return o.highlight.position-s.highlight.position}).reduce(i,[])}};H();var Q0=gt(X0());var ir=gt(cn());var Rl=class{static async create(t){let n=new this(t.annotator,t.rights||{enableBookmarks:!1},t.publication,t.delegate,t,t.initialAnnotations,t.api,t.headerMenu);return await n.start(),new Promise(i=>i(n))}constructor(t,n,i,o,s,l,h,c){this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=c,this.delegate=o,this.initialAnnotations=l,this.properties=s,this.api=h}stop(){ir.default.log("Bookmark module stop")}async start(){if(this.delegate.bookmarkModule=this,this.headerMenu&&(this.bookmarksView=$e(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=$e(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let t=$e(this.headerMenu,"#menu-button-bookmark");t&&t.parentElement?.style.removeProperty("display"),t&&Ce(t,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let t=this.initialAnnotations.bookmarks||null;t&&this.annotator?.initBookmarks(t)}await this.showBookmarks(),await this.drawBookmarks(),setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("highlights"):this.delegate.showLayer("highlights")},10)}async handleResize(){setTimeout(async()=>{await this.drawBookmarks(),await this.showBookmarks()},100)}initialize(){return new Promise(async t=>{await document.fonts.ready,this.rights.enableBookmarks&&setTimeout(()=>{this.drawBookmarks(),this.showBookmarks()},300),t(null)})}async deleteBookmark(t){if(this.annotator)if(this.api?.deleteBookmark){await this.api?.deleteBookmark(t);let n=await this.annotator.deleteBookmark(t);return ir.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else{let n=await this.annotator.deleteBookmark(t);return ir.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else return new Promise(n=>n(null))}async saveBookmarkPlus(){await this.addBookmarkPlus()}async saveBookmark(){if(this.annotator){var t=this.publication.getTOCItem(this.delegate.currentChapterLink.href);if(this.delegate.currentTocUrl&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let n=t.Href;n.indexOf("#")>0&&(n=n.slice(0,n.indexOf("#")));let i=this.delegate.view?.getCurrentPosition(),o=(0,Q0.v4)(),s;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let l=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),h=Math.ceil((i??0)*(l.length-1)),c=l[h];s=nn(dt({},c),{id:o,href:n,created:new Date,title:this.delegate.currentChapterLink.title})}else s={id:o,href:n,locations:{progression:i},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title};if(!this.annotator.locatorExists(s,Fi.Bookmark))if(this.delegate.consumptionModule?.trackAction(s,ms.BookmarkCreated),this.api?.addBookmark){let l=await this.api.addBookmark(s);l&&(s=l),ir.default.log(s);let h=this.annotator.saveBookmark(s);return ir.default.log("Bookmark added "+JSON.stringify(h)),this.showBookmarks(),await this.drawBookmarks(),h}else{let l=this.annotator.saveBookmark(s);return ir.default.log("Bookmark added "+JSON.stringify(l)),this.showBookmarks(),await this.drawBookmarks(),l}}}}async addBookmarkPlus(){let t=this,n=this.delegate.highlighter?.visibleTextRects[0],i=this.delegate.iframes[0].contentDocument;if(i){let h=this.delegate.highlighter?.dom(i.body).getWindow().document.createRange(),c=this.delegate.highlighter?.dom(this.delegate.iframes[0].contentDocument?.body).getSelection();c.removeAllRanges(),n&&h.selectNodeContents(n.node),c.addRange(h);let d=$d(h,!1),m=0;for(let y of d){if(!this.delegate.highlighter?.isOutsideViewport(y)){let w=c.focusNode,v=c.focusOffset;c.collapse(c.anchorNode,c.anchorOffset);for(let b=0;b<m;b++)c.modify("move","forward","line");c.extend(w,v);let g=c.focusNode,f=c.focusNode.length;c.collapse(c.anchorNode,c.anchorOffset);let p=f;c.anchorOffset>f?p=f:p=c.anchorOffset+1,c.modify("move","forward","character"),c.modify("move","backward","word"),c.extend(g,p),c.modify("extend","backward","character"),c.modify("extend","forward","word");break}m++}}function o(h){let c={},d=t.delegate.iframes[0].contentDocument;if(d)return Nn(h,t.delegate.highlighter?.dom(d.body).getDocument(),c)}let s=this.delegate.iframes[0].contentWindow,l={id:"bookmarkIcon",marker:ot.Bookmark,icon:{id:"bookmarkIcon",title:"Bookmark",svgPath:'<path d="M0 0h24v24H0V0z" fill="none"/><path d="M17 3H7c-1.1 0-2 .9-2 2v16l7-3 7 3V5c0-1.1-.9-2-2-2z"/>',color:"#000000",position:"left"},popup:{background:"#000000",textColor:"#ffffff"},highlight:{color:"#000000",style:{default:[{property:"border-bottom",value:"0px dashed #000000",priority:"important"}]}}};if(s!==null){let h=Ir(s,o);if(h===void 0){let d=t.delegate.iframes[0].contentDocument;h=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(d)}let c=t.delegate.iframes[0].contentDocument;if(h&&c){let d=this.delegate.highlighter?.createHighlight(this.delegate.highlighter?.dom(c.body).getWindow(),h,l.highlight?.color,!0,ot.Bookmark,l.icon,l.popup,l.highlight?.style);if(this.delegate.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),d)return this.saveAnnotation(d[0]).then(m=>{ir.default.log("saved bookmark "+m?.id)})}}}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.delegate.currentChapterLink.href);this.delegate.currentTocUrl&&(n=this.publication.getTOCItem(this.delegate.currentTocUrl)),n===null&&(n=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href));let i=this.delegate.view?.getCurrentPosition(),o=this.delegate.iframes[0].contentDocument;if(o){let s=Qr(o,"body"),l=t.position?t.position/s.scrollHeight:i,h=(0,Q0.v4)(),c;if(n){let d=n.Href;if(d.indexOf("#")>0&&(d=d.slice(0,d.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let m=this.publication.positionsByHref(this.publication.getRelativeHref(this.delegate.currentChapterLink.href)),y=Math.ceil((l??0)*(m.length-1)),w=m[y];c=nn(dt({},w),{id:h,href:d,created:new Date,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else c={id:h,href:d,locations:{progression:l},created:new Date,type:this.delegate.currentChapterLink.type,title:this.delegate.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(c)if(this.delegate.consumptionModule?.trackAction(c,ms.BookmarkCreated),this.api?.addBookmark){let d=await this.api.addBookmark(c),m=await this.annotator.saveAnnotation(d);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(y=>y(m))}else{let d=await this.annotator.saveAnnotation(c);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(m=>m(d))}}}return new Promise(i=>i(void 0))}getBookmarks(){let t=[];return this.annotator&&(t=this.annotator.getBookmarks()),t}showBookmarks(){let t=[];this.annotator&&(t=this.annotator.getBookmarks());let n=[];this.annotator&&(n=this.annotator.getAnnotations(),n&&(n=n.filter(i=>i.highlight.marker===ot.Bookmark),t?t.push.apply(t,n):t=n)),this.bookmarksView&&this.createTree(Fi.Bookmark,t,this.bookmarksView)}async drawBookmarks(){if(this.rights.enableBookmarks&&this.delegate.highlighter)if(this.api){let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.delegate.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.delegate.highlighter.destroyHighlights(mt.Annotation);for(let i of n){yn.push(i.highlight);let o=i,s=this.delegate.currentChapterLink.href;var t=this.publication.getTOCItem(s);if(this.delegate.currentTocUrl&&(t=this.publication.getTOCItem(this.delegate.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&await this.delegate.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight)}}}}else{let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.delegate.highlighter&&n&&this.delegate.iframes[0].contentDocument?.readyState==="complete"){await this.delegate.highlighter.destroyHighlights(mt.Annotation);for(let i of n){yn.push(i.highlight);let o=i,s=this.delegate.currentChapterLink.href,l=this.publication.getTOCItem(s);if(this.delegate.currentTocUrl&&(l=this.publication.getTOCItem(this.delegate.currentTocUrl)),l===void 0&&(l=this.publication.getTOCItemAbsolute(this.delegate.currentChapterLink.href)),l){let h=l.Href;h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),o.href===h&&await this.delegate.highlighter.createHighlightDom(this.delegate.iframes[0].contentWindow,i.highlight)}}}}}async deleteSelectedHighlight(t){this.api?.deleteBookmark?this.api.deleteBookmark(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return ir.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,s=this.publication.readingOrder;if(s.length){let l=(h,c)=>{let d=document.createElement("ul");d.className="sidenav-annotations";for(let m of c){let y=document.createElement("li"),w=document.createElement("a"),v=document.createElement("span");if(w.tabIndex=-1,w.className="chapter-link",m.Href){let f=this.publication.getAbsoluteHref(m.Href),p=this.publication.getTOCItemAbsolute(f);w.href=f,w.innerHTML=p?.Title||"",y.appendChild(w)}else v.innerHTML=m.Title||"",v.className="chapter-title",y.appendChild(v);Ce(w,"click",f=>{f.preventDefault(),f.stopPropagation();let p={href:w.href,locations:{progression:0},type:m.TypeLink,title:w.title};this.delegate.stopReadAloud(),this.delegate.navigate(p)});let g=document.createElement("ol");n.forEach(function(f){let p=m.Href.indexOf("#")!==-1?m.Href.slice(0,m.Href.indexOf("#")):m.Href;if(m.Href&&f.href.endsWith(p)){let b=document.createElement("li");b.className="annotation-item";let S=document.createElement("a");if(S.setAttribute("href",f.href),t===Fi.Bookmark){S.className="bookmark-link";let x=document.createElement("span"),E=Math.round((f.locations.progression??0)*100)+"% through resource";x.className="title",x.innerHTML=E,S.appendChild(x)}let C=document.createElement("span");if(C.className="timestamp",C.innerHTML=Rl.readableTimestamp(f.created),S.appendChild(C),Ce(S,"click",x=>{x.preventDefault(),x.stopPropagation(),o.handleAnnotationLinkClick(x,f)}),b.appendChild(S),o.delegate.sideNavExpanded){let x=document.createElement("button");x.className="delete",x.innerHTML=mr.delete,Ce(x,"click",E=>{E.preventDefault(),E.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,E,f)}),b.appendChild(x)}g.appendChild(b)}}),g.children.length>0&&(d.appendChild(y),d.appendChild(g)),d.children.length>0&&h.appendChild(d),m.Children&&m.Children.length>0&&l(h,m.Children)}};i.innerHTML="",l(i,s)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.delegate.stopReadAloud(),this.delegate.navigate(n)):ir.default.log("bookmark data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){ir.default.log("bookmark data locator: ",i),i?t===Fi.Bookmark&&this.deleteBookmark(i):ir.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 gS=gt(pS());H();var bi=gt(cn()),tg="r2-mo-active",bs=class{},lt=bs;lt.COLOR_REF="color",lt.AUTO_SCROLL_REF="autoscroll",lt.AUTO_TURN_REF="autoturn",lt.VOLUME_REF="volume",lt.RATE_REF="rate",lt.COLOR_KEY="mediaoverlay-"+bs.COLOR_REF,lt.AUTO_SCROLL_KEY="mediaoverlay-"+bs.AUTO_SCROLL_REF,lt.AUTO_TURN_KEY="mediaoverlay-"+bs.AUTO_TURN_REF,lt.VOLUME_KEY="mediaoverlay-"+bs.VOLUME_REF,lt.RATE_KEY="mediaoverlay-"+bs.RATE_REF;var ng=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(),bi.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,bi.default.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,bi.default.log(n.autoScroll)),i?.autoTurn&&(n.autoTurn=i.autoTurn,bi.default.log(n.autoScroll)),i?.volume&&(n.volume=i.volume,bi.default.log(n.volume)),i?.rate&&(n.rate=i.rate,bi.default.log(n.rate)),i?.wait&&(n.wait=i.wait,bi.default.log(n.wait))}return n.initializeSelections(),n}stop(){bi.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(lt.AUTO_SCROLL_KEY)!=null?this.getProperty(lt.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(lt.AUTO_TURN_KEY)!=null?this.getProperty(lt.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(lt.COLOR_KEY)!=null?this.getProperty(lt.COLOR_KEY).value:this.color,this.volume=this.getProperty(lt.VOLUME_KEY)!=null?this.getProperty(lt.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(lt.RATE_KEY)!=null?this.getProperty(lt.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=$e(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechAutoTurn=$e(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=$e(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=$e(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=$e(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()),Ce($e(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(lt.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(lt.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(lt.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(lt.VOLUME_REF)?.value,rate:this.userProperties.getByRef(lt.RATE_REF)?.value};this.applyMediaOverlaySettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{bi.default.log("api updated sync settings",n)})}getMediaOverlaySettings(){let t=new Zr;return t.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,lt.AUTO_SCROLL_REF,lt.AUTO_SCROLL_KEY),t.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,lt.AUTO_TURN_REF,lt.AUTO_TURN_KEY),t.addStringable(this.color,lt.COLOR_REF,lt.COLOR_KEY),t.addIncremental(this.volume,.1,1,.1,"",lt.VOLUME_REF,lt.VOLUME_KEY),t.addIncremental(this.rate,.1,3,.1,"",lt.RATE_REF,lt.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(lt.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){bi.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(lt.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoTurn!==void 0){bi.default.log("autoTurn "+this.autoTurn),this.autoTurn=t.autoTurn;let n=this.userProperties.getByRef(lt.AUTO_TURN_REF);n&&(n.value=this.autoTurn,this.saveProperty(n)),this.settingsChangeCallback()}if(t.volume){bi.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(lt.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback()}if(t.rate){bi.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(lt.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback()}}applyMediaOverlaySetting(t,n){if(t===lt.COLOR_REF){this.color=n;let i=this.userProperties.getByRef(lt.COLOR_REF);i&&(i.value=this.color,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===lt.AUTO_SCROLL_REF){this.autoScroll=n;let i=this.userProperties.getByRef(lt.AUTO_SCROLL_REF);i&&(i.value=this.autoScroll,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===lt.AUTO_TURN_REF){this.autoTurn=n;let i=this.userProperties.getByRef(lt.AUTO_TURN_REF);i&&(i.value=this.autoTurn,this.saveProperty(i)),this.settingsChangeCallback()}}increase(t){if(t==="mo_volume"){this.userProperties.getByRef(lt.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(lt.VOLUME_REF)?.value;let n=this.userProperties.getByRef(lt.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(lt.RATE_REF).increment(),this.rate=this.userProperties.getByRef(lt.RATE_REF)?.value;let n=this.userProperties.getByRef(lt.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}decrease(t){if(t==="mo_volume"){this.userProperties.getByRef(lt.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(lt.VOLUME_REF)?.value;let n=this.userProperties.getByRef(lt.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(lt.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(lt.RATE_REF)?.value;let n=this.userProperties.getByRef(lt.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}};var ut=gt(cn()),ig=class{constructor(t,n,i,o){this.play=$e(document,"#menu-button-play");this.pause=$e(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async t=>{ut.default.log("ontimeupdate"),this.trackCurrentTime()};this.ensureOnTimeUpdate=(t,n)=>{t?this.__ontimeupdate&&(this.__ontimeupdate=!1,this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),cancelAnimationFrame(this.myReq)):(!this.__ontimeupdate||n)&&(this.__ontimeupdate=!0,n&&(this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),this.audioElement.addEventListener("timeupdate",this.ontimeupdate)))};this.delegate=t,this.publication=n,this.settings=i,this.properties=o}static create(t){let n=new this(t.delegate,t.publication,t.settings,t);return n.start(),n}stop(){ut.default.log("MediaOverlay module stop")}start(){this.delegate.mediaOverlayModule=this,ut.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(),s;try{s=await fetch(o,this.delegate.requestConfig)}catch(d){console.error(d,o);return}s.ok||ut.default.log("BAD RESPONSE?!");let l;try{l=await s.json()}catch(d){console.error(d)}if(!l){ut.default.log("## moJson"+l);return}t.MediaOverlays=ta(l,gS.MediaOverlayNode),t.MediaOverlays.initialized=!0;let h=t.HrefDecoded||t.Href,c=new URL("https://dita.digital/"+h);await this.playMediaOverlays(c.pathname.substr(1),t.MediaOverlays,void 0)}else this.audioElement&&await this.audioElement.pause(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement&&await this.audioElement.pause(),this.delegate.nextResource()):await this.stopReadAloud()}async startReadAloud(){if(this.delegate.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement&&this.currentLinks[this.currentLinkIndex]?.Properties.MediaOverlay){let t=this.currentAudioBegin?this.currentAudioBegin:0;this.audioElement.currentTime=t,await this.audioElement.play(),this.ensureOnTimeUpdate(!1,!0),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}else this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?this.delegate.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display")}}async stopReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.delegate.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"))}findDepthFirstTextAudioPair(t,n,i){ut.default.log("findDepthFirstTextAudioPair()");let o,s;if(n.Text){let c=new URL("https://dita.digital/"+n.Text);if(c.pathname.substr(1)===t){if(o=!0,c.hash&&i){s=!1;let d=c.hash.substr(1);for(let m of i)if(m===d){s=!0;break}}}else o=!1}if(ut.default.log("isFragmentIDMatch: "+s),ut.default.log("isTextUrlMatch: "+o),!n.Children||!n.Children.length){if(ut.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!o){ut.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return s||o&&!i?(ut.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),n):void 0}let l=i,h=i;for(let c of n.Children){ut.default.log("findDepthFirstTextAudioPair() - child"),ut.default.log(JSON.stringify(c));let d=this.findDepthFirstTextAudioPair(t,c,h);if(d===null&&(ut.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),h=void 0),d)return ut.default.log("findDepthFirstTextAudioPair() - child - match"),ut.default.log(JSON.stringify(d)),d}if(s){ut.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let c=this.findDepthFirstTextAudioPair(t,n,void 0);return c&&(ut.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),ut.default.log(JSON.stringify(c)),c)}if(l&&!h)return null}trackCurrentTime(){if(cancelAnimationFrame(this.myReq),this.mediaOverlayTextAudioPair)try{this.currentAudioEnd&&this.audioElement.currentTime>=this.currentAudioEnd-.05&&(ut.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(ut.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let n=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!t);if(!n)ut.default.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud());else{let i=!1;if(this.mediaOverlayTextAudioPair.Text&&n.Text){let o=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),s=new URL("https://dita.digital/"+n.Text);o.pathname!==s.pathname&&(ut.default.log("mediaOverlaysNext() SWITCH! "+o.pathname+" != "+s.pathname),i=!0)}i?this.mediaOverlaysStop():(ut.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(n,void 0,void 0)},0))}}else ut.default.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){ut.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){ut.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 ut.default.log("findNextTextAudioPair() - prevMo === moToMatch"),t;ut.default.log("findNextTextAudioPair() - set previous"),ut.default.log(JSON.stringify(t)),i.prev=t;return}for(let s of t.Children){ut.default.log("findNextTextAudioPair() - child"),ut.default.log(JSON.stringify(s));let l=this.findNextTextAudioPair(s,n,i,o);if(l)return ut.default.log("findNextTextAudioPair() - match"),ut.default.log(JSON.stringify(l)),l}}async playMediaOverlaysAudio(t,n,i){if(ut.default.log("playMediaOverlaysAudio()"),this.mediaOverlayTextAudioPair=t,!t.Audio)return;let o=new URL(t.Audio,this.publication.manifestUrl),s=o.toString(),l=new URL(s);l.hash="",l.search="";let h=l.toString(),c=typeof n!="undefined",d=typeof i!="undefined";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!c&&!d){if(o.hash){let y=o.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(y&&y.length>=1){let w=y[1];try{this.currentAudioBegin=parseFloat(w)}catch(v){ut.default.error(v)}if(y.length>=3){let v=y[3];try{this.currentAudioEnd=parseFloat(v)}catch(g){ut.default.error(g)}}}}}else this.currentAudioBegin=n,this.currentAudioEnd=i;ut.default.log(`${s} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let m=async y=>{if(!this.audioElement)return;let w=this.currentAudioBegin?this.currentAudioBegin:0;if(y||this.audioElement.paused)if(y&&!w||this.audioElement.currentTime===w){if(ut.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 g=function(){v.settings.resourceReady?setTimeout(async()=>{await v.audioElement.play(),v.ensureOnTimeUpdate(!1,!0)},v.settings.wait*1e3):setTimeout(g,200)},v=this;g()}}else{ut.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let v=async g=>{if(this.audioElement.removeEventListener("timeupdate",v),ut.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 p=function(){f.settings.resourceReady?setTimeout(async()=>{await f.audioElement.play(),f.ensureOnTimeUpdate(!1,!0)},f.settings.wait*1e3):setTimeout(p,200)},f=this;p()}};this.audioElement.addEventListener("timeupdate",v),this.audioElement.currentTime=w}else{let v=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd!="undefined"&&this.previousAudioEnd>w-.02&&this.previousAudioEnd<=w&&this.audioElement.currentTime>=w-.1;this.ensureOnTimeUpdate(!1,!1),v?ut.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(ut.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=w)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||h!==this.currentAudioUrl){this.currentAudioUrl=h,ut.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",v=>{ut.default.log("-1) error: "+(this.currentAudioUrl!==v.currentTarget.src?this.currentAudioUrl+" -- ":"")+v.currentTarget.src.substr(v.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(ut.default.log(this.audioElement.error.code),ut.default.log(this.audioElement.error.message))});let y=async v=>{v.currentTarget.removeEventListener("canplaythrough",y),ut.default.log("oncanplaythrough"),await m(!0)};this.audioElement.addEventListener("canplaythrough",y);let w=async v=>{ut.default.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.delegate.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",w),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else ut.default.log("playMediaOverlaysAudio() - playClip()"),await m(!1)}async playMediaOverlays(t,n,i){ut.default.log("playMediaOverlays()");let o=i?i.filter(l=>l):void 0;o&&o.length===0&&(o=void 0);let s=this.findDepthFirstTextAudioPair(t,n,o);!s&&o&&(ut.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),ut.default.log(JSON.stringify(o,null,4)),ut.default.log(JSON.stringify(n,null,4)),s=this.findDepthFirstTextAudioPair(t,n,void 0)),s?s.Audio&&(ut.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=n,await this.playMediaOverlaysAudio(s,void 0,void 0)):ut.default.log("playMediaOverlays() - !moTextAudioPair "+t)}mediaOverlayHighlight(t){ut.default.log("moHighlight: ## "+t);let n=this.publication.Metadata?.MediaOverlay?.ActiveClass;n||(n=this.settings.color);let i=this.delegate.iframes[0].contentDocument?.documentElement.getAttribute("style"),o=i?i.indexOf("readium-night-on")>0:!1,s=i?i.indexOf("readium-sepia-on")>0:!1;if((this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&(n=o||s?tg:n||tg),this.pid){let h;this.currentLinkIndex===0?h=this.delegate.iframes[0].contentDocument?.getElementById(this.pid):h=this.delegate.iframes[1].contentDocument?.getElementById(this.pid),h&&h.classList.remove(n)}let l;t&&(this.currentLinkIndex===0?l=this.delegate.iframes[0].contentDocument?.getElementById(t):l=this.delegate.iframes[1].contentDocument?.getElementById(t),l&&l.classList.add(n),this.pid=t),l&&(this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&l.scrollIntoView({block:"center",behavior:"smooth"})}};H();var rg=gt(cn()),og=class{static async create(t){let n=new this(t.delegate,t.publication);return await n.start(),n}constructor(t,n){this.delegate=t,this.publication=n}async stop(){rg.default.log("Timeline module stop")}async start(){this.delegate.timelineModule=this,this.timelineContainer=$e(document,"#container-view-timeline"),this.positionSlider=$e(document,"#positionSlider"),this.publication.positions?this.positionSlider&&(this.positionSlider.style.display="block"):this.positionSlider&&(this.positionSlider.style.display="none")}async initialize(){return new Promise(async t=>{await document.fonts.ready;let n=this.delegate.currentLocator();(this.delegate.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions)&&(this.positionSlider&&(this.positionSlider.value=(n.locations.position??0).toString()),this.positionSlider&&(this.positionSlider.max=((n.locations.totalRemainingPositions??0)+(n.locations.position??0)).toString())),this.timelineContainer&&(this.timelineContainer.innerHTML=""),this.publication.readingOrder?.forEach(i=>{let o=this.publication.getAbsoluteHref(i.Href),s=this.publication.getTOCItemAbsolute(o),l=s?.Href.indexOf("#")!==-1?s?.Href.slice(0,s?.Href.indexOf("#")):s.Href,h=this.publication.getAbsoluteHref(l??"");var c;this.publication.positions&&this.delegate.view?.layout!=="fixed"?i.contentWeight?c=i.contentWeight:c=1:c=100/(this.publication.readingOrder?.length??0);var d=document.createElement("div");if(d.style.height=c+"%",d.style.width="100%",d.className="chapter",s?.Title!==void 0){var m=document.createElement("span");m.innerHTML=s.Title,m.className="chapter-tooltip",d.appendChild(m)}Ce(d,"click",y=>{y.preventDefault(),y.stopPropagation();var w;this.publication.positions||this.delegate.rights.autoGeneratePositions&&this.publication.positions?(w=dt({},this.publication.positions.filter(v=>v.href===i.Href)[0]),w.href=this.publication.getAbsoluteHref(w.href)):w={href:h,locations:{progression:0},type:i.TypeLink,title:i.Title},rg.default.log(w),this.delegate.navigate(w)}),h===this.delegate.currentChapterLink.href?d.className+=" active":d.className=d.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(d)}),t()})}};H();var xg=gt(Mo());H();var mS=gt(cn());function yS(r,t){return new Promise(function(n){setTimeout(n.bind(null,t),r)})}var kD=!1;mS.default.setLevel(kD?"trace":"warn",!0);var VA=gt(zA()),lh=gt(GA()),qn=gt(cn());var ch=class{constructor(t,n){this.hasEventListener=!1;this.isHacked=!1;this.delegate=t,this.properties=n}static async setupPreloadProtection(t){if(this.isCurrentBrowserSupported(t))t.detectInspect&&await this.startInspectorProtection(t);else throw new Error("Browser not supported")}static async create(t){let n=new this(t.delegate,t);return await n.start(),n}static async startInspectorProtection(t){(0,lh.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,lh.launch)(),await yS(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,VA.getUserAgentRegExp)({browsers:n,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.delegate.contentProtectionModule=this,this.properties?.enableObfuscation){this.wrapper=Rt(document,"#iframe-wrapper"),this.securityContainer=$e(document,"#container-view-security");var t=this;this.mutationObserver=new MutationObserver(function(n){n.forEach(function(i){qn.default.log(i.type),t.isHacked=!0})})}}async stop(){if(qn.default.log("Protection module stop"),this.properties?.enableObfuscation&&this.mutationObserver.disconnect(),this.properties?.disableKeys){ze(this.delegate.mainElement,"keydown",this.disableSave),ze(this.delegate.headerMenu,"keydown",this.disableSave);for(let t of this.delegate.iframes)ze(t.contentDocument,"keydown",this.disableSave),ze(t.contentWindow,"keydown",this.disableSave);ze(window,"keydown",this.disableSave),ze(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){ze(this.delegate.mainElement,"copy",this.preventCopy),ze(this.delegate.headerMenu,"copy",this.preventCopy);for(let t of this.delegate.iframes)ze(t.contentDocument,"copy",this.preventCopy),ze(t.contentWindow,"copy",this.preventCopy);ze(window,"copy",this.preventCopy),ze(document,"copy",this.preventCopy),ze(this.delegate.mainElement,"cut",this.preventCopy),ze(this.delegate.headerMenu,"cut",this.preventCopy);for(let t of this.delegate.iframes)ze(t.contentDocument,"cut",this.preventCopy),ze(t.contentWindow,"cut",this.preventCopy);ze(window,"cut",this.preventCopy),ze(document,"cut",this.preventCopy),ze(this.delegate.mainElement,"keydown",this.preventCopyKey),ze(this.delegate.headerMenu,"keydown",this.preventCopyKey);for(let t of this.delegate.iframes)ze(t.contentDocument,"keydown",this.preventCopyKey),ze(t.contentWindow,"keydown",this.preventCopyKey);ze(window,"keydown",this.preventCopyKey),ze(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){ze(this.delegate.mainElement,"copy",this.restrictCopy),ze(this.delegate.headerMenu,"copy",this.restrictCopy);for(let t of this.delegate.iframes)ze(t.contentDocument,"copy",this.restrictCopy),ze(t.contentWindow,"copy",this.restrictCopy);ze(window,"copy",this.restrictCopy),ze(document,"copy",this.restrictCopy),ze(this.delegate.mainElement,"cut",this.restrictCopy),ze(this.delegate.headerMenu,"cut",this.restrictCopy);for(let t of this.delegate.iframes)ze(t.contentDocument,"cut",this.restrictCopy),ze(t.contentWindow,"cut",this.restrictCopy);ze(window,"cut",this.restrictCopy),ze(document,"cut",this.restrictCopy),ze(this.delegate.mainElement,"keydown",this.restrictCopyKey),ze(this.delegate.headerMenu,"keydown",this.restrictCopyKey);for(let t of this.delegate.iframes)ze(t.contentDocument,"keydown",this.restrictCopyKey),ze(t.contentWindow,"keydown",this.restrictCopyKey);ze(window,"keydown",this.restrictCopyKey),ze(document,"keydown",this.restrictCopyKey)}if(this.properties?.disablePrint){ze(this.delegate.mainElement,"beforeprint",this.beforePrint.bind(this)),ze(this.delegate.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let t of this.delegate.iframes)ze(t.contentDocument,"beforeprint",this.beforePrint),ze(t.contentWindow,"beforeprint",this.beforePrint);ze(window,"beforeprint",this.beforePrint),ze(document,"beforeprint",this.beforePrint),ze(this.delegate.mainElement,"afterprint",this.afterPrint.bind(this)),ze(this.delegate.headerMenu,"afterprint",this.afterPrint.bind(this));for(let t of this.delegate.iframes)ze(t.contentDocument,"afterprint",this.afterPrint.bind(this)),ze(t.contentWindow,"afterprint",this.afterPrint.bind(this));ze(window,"afterprint",this.afterPrint.bind(this)),ze(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){ze(this.delegate.mainElement,"contextmenu",this.disableContext),ze(this.delegate.headerMenu,"contextmenu",this.disableContext);for(let t of this.delegate.iframes)ze(t.contentDocument,"contextmenu",this.disableContext),ze(t.contentWindow,"contextmenu",this.disableContext);ze(window,"contextmenu",this.disableContext),ze(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),ze(this.wrapper,"scroll",this.handleScroll.bind(this))}observe(){if(this.properties?.enableObfuscation){this.securityContainer.hasAttribute("style")&&(this.isHacked=!0),this.mutationObserver.disconnect();var t={attributes:!0,childList:!0,characterData:!0};this.mutationObserver.observe(this.securityContainer,t)}}async deactivate(){this.properties?.enableObfuscation&&(this.observe(),this.rects.forEach(t=>this.deactivateRect(t,this.securityContainer,this.isHacked)))}async activate(){if(this.properties?.enableObfuscation){this.observe();for(let t of this.delegate.iframes)if(t.contentDocument){let n=Qr(t.contentDocument,"body");this.rects=this.findRects(n),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){Ce(this.delegate.mainElement,"keydown",this.disableSave),Ce(this.delegate.headerMenu,"keydown",this.disableSave);for(let t of this.delegate.iframes)Ce(t,"keydown",this.disableSave),Ce(t.ownerDocument,"keydown",this.disableSave),Ce(t.contentDocument,"keydown",this.disableSave),Ce(t.contentWindow,"keydown",this.disableSave),Ce(t.contentWindow?.document,"keydown",this.disableSave);Ce(window,"keydown",this.disableSave),Ce(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){Ce(this.delegate.mainElement,"copy",this.preventCopy),Ce(this.delegate.headerMenu,"copy",this.preventCopy);for(let t of this.delegate.iframes)Ce(t,"copy",this.preventCopy),Ce(t.ownerDocument,"copy",this.preventCopy),Ce(t.contentDocument,"copy",this.preventCopy),Ce(t.contentWindow,"copy",this.preventCopy),Ce(t.contentWindow?.document,"copy",this.preventCopy);Ce(window,"copy",this.preventCopy),Ce(document,"copy",this.preventCopy),Ce(this.delegate.mainElement,"cut",this.preventCopy),Ce(this.delegate.headerMenu,"cut",this.preventCopy);for(let t of this.delegate.iframes)Ce(t,"cut",this.preventCopy),Ce(t.ownerDocument,"cut",this.preventCopy),Ce(t.contentDocument,"cut",this.preventCopy),Ce(t.contentWindow,"cut",this.preventCopy),Ce(t.contentWindow?.document,"cut",this.preventCopy);Ce(window,"cut",this.preventCopy),Ce(document,"cut",this.preventCopy),Ce(this.delegate.mainElement,"keydown",this.preventCopyKey),Ce(this.delegate.headerMenu,"keydown",this.preventCopyKey);for(let t of this.delegate.iframes)Ce(t,"keydown",this.preventCopyKey),Ce(t.ownerDocument,"keydown",this.preventCopyKey),Ce(t.contentDocument,"keydown",this.preventCopyKey),Ce(t.contentWindow,"keydown",this.preventCopyKey),Ce(t.contentWindow?.document,"keydown",this.preventCopyKey);Ce(window,"keydown",this.preventCopyKey),Ce(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){Ce(this.delegate.mainElement,"copy",this.restrictCopy.bind(this)),Ce(this.delegate.headerMenu,"copy",this.restrictCopy.bind(this));for(let t of this.delegate.iframes)Ce(t,"copy",this.restrictCopy),Ce(t.ownerDocument,"copy",this.restrictCopy.bind(this)),Ce(t.contentDocument,"copy",this.restrictCopy.bind(this)),Ce(t.contentWindow,"copy",this.restrictCopy.bind(this)),Ce(t.contentWindow?.document,"copy",this.restrictCopy.bind(this));Ce(window,"copy",this.restrictCopy.bind(this)),Ce(document,"copy",this.restrictCopy.bind(this)),Ce(this.delegate.mainElement,"cut",this.restrictCopy.bind(this)),Ce(this.delegate.headerMenu,"cut",this.restrictCopy.bind(this));for(let t of this.delegate.iframes)Ce(t,"cut",this.restrictCopy.bind(this)),Ce(t.ownerDocument,"cut",this.restrictCopy.bind(this)),Ce(t.contentDocument,"cut",this.restrictCopy.bind(this)),Ce(t.contentWindow,"cut",this.restrictCopy.bind(this)),Ce(t.contentWindow?.document,"cut",this.restrictCopy.bind(this));Ce(window,"cut",this.restrictCopy.bind(this)),Ce(document,"cut",this.restrictCopy.bind(this)),Ce(this.delegate.mainElement,"keydown",this.restrictCopyKey.bind(this)),Ce(this.delegate.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let t of this.delegate.iframes)Ce(t,"keydown",this.restrictCopyKey.bind(this)),Ce(t.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),Ce(t.contentDocument,"keydown",this.restrictCopyKey.bind(this)),Ce(t.contentWindow,"keydown",this.restrictCopyKey.bind(this)),Ce(t.contentWindow?.document,"keydown",this.restrictCopyKey.bind(this));Ce(window,"keydown",this.restrictCopyKey.bind(this)),Ce(document,"keydown",this.restrictCopyKey.bind(this))}if(this.properties?.disablePrint){Ce(this.delegate.mainElement,"beforeprint",this.beforePrint),Ce(this.delegate.headerMenu,"beforeprint",this.beforePrint);for(let t of this.delegate.iframes)Ce(t,"beforeprint",this.beforePrint.bind(this)),Ce(t.ownerDocument,"beforeprint",this.beforePrint.bind(this)),Ce(t.contentDocument,"beforeprint",this.beforePrint.bind(this)),Ce(t.contentWindow,"beforeprint",this.beforePrint.bind(this)),Ce(t.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));Ce(window,"beforeprint",this.beforePrint.bind(this)),Ce(document,"beforeprint",this.beforePrint.bind(this)),Ce(this.delegate.mainElement,"afterprint",this.afterPrint),Ce(this.delegate.headerMenu,"afterprint",this.afterPrint);for(let t of this.delegate.iframes)Ce(t,"afterprint",this.afterPrint.bind(this)),Ce(t.ownerDocument,"afterprint",this.afterPrint.bind(this)),Ce(t.contentDocument,"afterprint",this.afterPrint.bind(this)),Ce(t.contentWindow,"afterprint",this.afterPrint.bind(this)),Ce(t.contentWindow?.document,"afterprint",this.afterPrint.bind(this));Ce(window,"afterprint",this.afterPrint.bind(this)),Ce(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){Ce(this.delegate.mainElement,"contextmenu",this.disableContext),Ce(this.delegate.headerMenu,"contextmenu",this.disableContext);for(let t of this.delegate.iframes)Ce(t,"contextmenu",this.disableContext),Ce(t.ownerDocument,"contextmenu",this.disableContext),Ce(t.contentDocument,"contextmenu",this.disableContext),Ce(t.contentWindow,"contextmenu",this.disableContext),Ce(t.contentWindow?.document,"contextmenu",this.disableContext);Ce(window,"contextmenu",this.disableContext),Ce(document,"contextmenu",this.disableContext)}}initializeResource(){this.properties?.hideTargetUrl&&this.hideTargetUrls(!0),this.properties?.disableDrag&&this.preventDrag(!0)}async initialize(){if(this.properties?.enableObfuscation)return new Promise(async t=>{await document.fonts.ready;for(let n of this.delegate.iframes)if(n.contentDocument){let i=Qr(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,Ce(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,xg.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 qn.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;qn.default.log("copy action initiated");let n=this.delegate.iframes[0].contentWindow;if(n){let o=function(l){let h={className:d=>ji.indexOf(d)<0,idName:d=>ji.indexOf(d)<0},c=i.delegate.iframes[0].contentDocument;if(c)return Nn(l,c,h)},i=this,s=Ir(n,o);if(s===void 0){let l=this.delegate.iframes[0].contentDocument;s=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(l)}t.clipboardData.setData("text/plain",s?.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.delegate.iframes[0].contentWindow;if(n){let o=function(l){let h={className:d=>ji.indexOf(d)<0,idName:d=>ji.indexOf(d)<0},c=i.delegate.iframes[0].contentDocument;if(c)return Nn(l,c,h)},i=this,s=Ir(n,o);if(s===void 0){let l=this.delegate.iframes[0].contentDocument;s=this.delegate.annotationModule?.annotator?.getTemporarySelectionInfo(l)}this.copyToClipboard(s?.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 qn.default.log("before print"),this.delegate&&this.delegate.headerMenu&&(this.delegate.headerMenu.style.display="none",this.delegate.mainElement.style.display="none"),t.stopPropagation(),t.preventDefault(),!1}afterPrint(t){return qn.default.log("after print"),this.delegate&&this.delegate.headerMenu&&(this.delegate.headerMenu.style.removeProperty("display"),this.delegate.mainElement.style.removeProperty("display")),t.stopPropagation(),t.preventDefault(),!1}hideTargetUrls(t){function n(i){i.preventDefault();let o=i.currentTarget.getAttribute("data-href-resolved"),s=document.createElement("a");s.setAttribute("href",o),s.click()}for(let i of this.delegate.iframes){let o=i.contentDocument?.querySelectorAll("a");o?.forEach(s=>{let l=s.getAttribute("data-href"),h=s.getAttribute("href");!l&&h&&(s.setAttribute("data-href",h),s.setAttribute("data-href-resolved",s.href))}),t?o?.forEach(s=>{s.setAttribute("href",""),s.addEventListener("click",n)}):o?.forEach(s=>{let l=s.getAttribute("data-href");l&&s.setAttribute("href",l),s.removeEventListener("click",n)})}}preventDrag(t){let n="-webkit-user-drag: none; -khtml-user-drag: none; -moz-user-drag: none; -ms-user-drag: none; user-drag: none; -webkit-pointer-events: none; -khtml-pointer-events: none; -moz-pointer-events: none; -ms-pointer-events: none; pointer-events: none;",i=o=>{o.preventDefault()};for(let o of this.delegate.iframes){let s=o.contentDocument?.body.getAttribute("style")||"";t?(o.contentDocument?.body.addEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",s+n)):(o.contentDocument?.body.removeEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",s.replace(n,"")))}}recalculate(t=0){return new Promise(n=>{if(this.properties?.enableObfuscation){let i=(0,xg.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:s,width:l}=this.measureTextNode(n.node);n.top=i,n.height=o,n.width=l,n.left=s}catch(i){qn.default.log("error "+i),qn.default.log(n),qn.default.log(n.node),qn.default.log("scrambledTextContent "+n.scrambledTextContent),qn.default.log("textContent "+n.textContent),qn.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),s=this.isBeingHacked(n);t.isObfuscated&&!o&&!s&&!i&&(t.node.textContent=t.textContent,t.isObfuscated=!1),!t.isObfuscated&&(o||s||i)&&(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0)}findRects(t){return this.findTextNodes(t).map(i=>{let{top:o,height:s,left:l,width:h}=this.measureTextNode(i),c=i.parentElement?.nodeName==="option"||i.parentElement?.nodeName==="script"?i.textContent:this.obfuscateText(i.textContent??"");return{top:o,height:s,width:h,left:l,node:i,textContent:i.textContent??"",scrambledTextContent:c??"",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){qn.default.log("measureTextNode "+n),qn.default.log("measureTextNode "+t),qn.default.log(t.textContent)}}isBeingHacked(t){return t.style.animation||t.style.transition||t.style.position||t.hasAttribute("style")?(qn.default.log("content being hacked"),!0):!1}isOutsideViewport(t){let n=this.wrapper.scrollLeft,i=n+this.wrapper.clientWidth,o=t.left+t.width,s=t.top+t.height,l=this.wrapper.scrollTop,h=l+this.wrapper.clientHeight,c=s<l,d=t.top>h,m=o<n-window.innerWidth,y=t.left>i+window.innerWidth;return c||d||m||y}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 s(l){for(var h=l.length,c,d;h>0;)d=Math.floor(Math.random()*h),h--,c=l[h],l[h]=l[d],l[d]=c;return l}return n&&(o=o.map(function(l){return s(l.split("")).join("")})),i?s(o).join(" "):o.join(" ")}};H();var QA=gt(KA());H();var uh=r=>r.replace(/\n/g," ").replace(/\s\s+/g," "),KD=r=>uh(r).trim(),YA=/[\\^$.*+?()[\]{}|]/g,YD=RegExp(YA.source);function XA(r){return r&&YD.test(r)?r.replace(YA,"\\$&"):r||""}var dh=0,XD=()=>()=>Number.isSafeInteger(++dh)?dh:dh=1,ZA=()=>{dh=0},ZD=XD(),QD=r=>t=>{try{return Nn(t,r,Lo)}catch(n){return console.error("uniqueCssSelector:",n),""}};async function jo(r,t,n,i,o=!1){if(!t)return[];let s=t.body?.textContent;if(!s)return[];if(r=KD(r),!r.length)return[];let l=t.createNodeIterator(t.body,NodeFilter.SHOW_TEXT,{acceptNode:v=>NodeFilter.FILTER_ACCEPT}),h=new RegExp(XA(r).replace(/ /g,"\\s+"),"gim");o&&(h=new RegExp("\\b"+XA(r).replace(/ /g,"\\s+")+"\\b","gim"));let c=[],d=100,m=30,y=0,w;for(;w=h.exec(s);){let v=Math.max(0,w.index-d),g=Math.min(d,w.index),f=uh(s.substr(v,g));f=f.substr(f.length-m),v=h.lastIndex,g=Math.min(d,s.length-v);let p=uh(s.substr(v,g)).substr(0,m),b=new Range,S=w.index;for(;y<=S;){let E=l.nextNode();E&&E.nodeValue&&(y+=E.nodeValue.length)}let C=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(y-S):0;for(b.setStart(l.referenceNode,C),S=w.index+w[0].length;y<=S;){let T=l.nextNode()?.nodeValue;T&&(y+=T.length)}C=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(y-S):0,b.setEnd(l.referenceNode,C),t.getCssSelector||(t.getCssSelector=QD(t));let x=oo(b,t.getCssSelector);x&&c.push({textMatch:uh(w[0]),textBefore:f,textAfter:p,rangeInfo:x,href:n,title:i,uuid:ZD().toString()})}return c}var ex=gt(cn()),Tg=class{constructor(t,n,i,o,s,l){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.delegate=t,this.headerMenu=l,this.publication=n,this.properties=i,this.api=s,this.highlighter=o}static async create(t){let n=new this(t.delegate,t.publication,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){ex.default.log("Search module stop"),ze(this.searchInput,"keypress",this.handleSearch.bind(this)),ze(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.delegate.searchModule=this,this.headerMenu){this.searchInput=$e(this.headerMenu,"#searchInput"),Ce(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=$e(this.headerMenu,"#searchGo"),Ce(this.searchGo,"click",this.handleSearch.bind(this));var t=$e(this.headerMenu,"#menu-button-search");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties.hideLayer?this.delegate.hideLayer("search"):this.delegate.showLayer("search")},10)}async handleSearch(t){(t.key==="Enter"||t.type==="click")&&(await this.handleSearchChapter(),await this.handleSearchBook())}async handleSearchChapter(t){var n=this,i=this.searchInput.value;let o=this.delegate.currentChapterLink.href,s=this.publication.getSpineItem(o);if(this.headerMenu)var l=$e(document,"#searchResultChapter");n.currentChapterSearchResult=[],n.currentSearchHighlights=[];var h=[];this.delegate.rights.enableContentProtection&&this.delegate.contentProtectionModule?.deactivate(),await this.searchAndPaintChapter(i,t,async d=>{h=d,c(1),this.delegate.rights.enableContentProtection&&this.delegate.contentProtectionModule?.recalculate(200)});async function c(d){l.innerHTML="";var m;if(m=n.paginate(h,d,10),m.total===0){let y=document.createElement("a");y.className="collection-item",y.innerHTML="nothing found",l.appendChild(y)}else{for(let f=0;f<m.data.length;f++){let p=document.createElement("a"),b=m.data[f];p.className="collection-item",p.href=s?.Href??"",p.innerHTML="..."+b.textBefore+"<mark>"+b.textMatch+"</mark>"+b.textAfter+"...",Ce(p,"click",S=>{S.preventDefault(),S.stopPropagation(),n.jumpToMark(f+d*10-10)}),l.appendChild(p)}let y=document.createElement("div");y.style.textAlign="center",y.style.marginTop="10px";let w=document.createElement("ul");w.className="pagination";let v=document.createElement("li");if(v.className="disabled",v.innerHTML='<a href="#!"> < </a>',m.pre_page!==void 0){let f=m.pre_page;v.className="waves-effect",Ce(v,"click",p=>{p.preventDefault(),p.stopPropagation(),c(f)})}w.appendChild(v);for(let f=1;f<=m.total_pages;f++){let p,b=document.createElement("li");b.className="waves-effect",f===m.page&&(b.className="active",p=b),b.innerHTML='<a href="#!">'+f+"</a>",Ce(b,"click",S=>{S.preventDefault(),S.stopPropagation(),p&&(p.className="waves-effect"),b.className="active",p=b,c(f)}),w.appendChild(b)}let g=document.createElement("li");if(g.className="disabled",g.innerHTML='<a href="#!"> > </a>',m.next_page!==void 0){let f=m.next_page;g.className="waves-effect",Ce(g,"click",p=>{p.preventDefault(),p.stopPropagation(),c(f)})}w.appendChild(g),y.appendChild(w),l.appendChild(y)}}}async searchAndPaintChapter(t,n=0,i){let o=this.publication.getAbsoluteHref(this.publication.readingOrder[this.delegate.currentResource()??0].Href),s=this.publication.getTOCItem(o);s===null&&(s=this.publication.readingOrder[this.delegate.currentResource()??0]);let l=[];this.highlighter?.destroyHighlights(mt.Search),this.delegate.rights.enableSearch&&this.drawSearch();let h=0;if(s){let c=this.delegate.iframes[0].contentDocument;c&&s&&jo(t,c,s.Href,s.Title).then(d=>{d.forEach(m=>{let y={rangeInfo:m.rangeInfo};setTimeout(()=>{let w;h===n?(w=this.createSearchHighlight(y,this.properties?.current),this.jumpToMark(n)):w=this.createSearchHighlight(y,this.properties?.color),m.highlight=w,l.push(m),this.currentChapterSearchResult.push(m),this.currentSearchHighlights.push(w),h++},500)}),setTimeout(()=>{i(l)},500)})}}createSearchHighlight(t,n){try{var i=n;ht.isHexColor(i)&&(i=ht.hexToRgbChannels(i));let s=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,l=QA.SHA256.hash(s),h="R2_SEARCH_"+l;var o=!1;let c={color:i||gs,id:h,pointerInteraction:o,selectionInfo:t,marker:ot.Highlight,type:mt.Search},d=this.highlighter?.createHighlightDom(this.delegate.iframes[0].contentWindow,c);return c.position=parseInt((d?.hasChildNodes()?d.childNodes[0]:d).style.top.replace("px","")),c}catch(s){throw"Can't create highlight: "+s}}clearSearch(){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.highlighter?.destroyHighlights(mt.Search)}async search(t,n){return this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],ZA(),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,s;let l=this.delegate.currentChapterLink.href;var h=this.publication.getAbsoluteHref(t);let c=this.bookSearchResult.filter(d=>d.href===t);if(i?(s=this.currentChapterSearchResult.filter(d=>d.uuid===n)[0],o=this.currentChapterSearchResult.findIndex(d=>d.uuid===n)):(s=c.filter(d=>d.uuid===n)[0],o=c.findIndex(d=>d.uuid===n)),s!==void 0)if(l===h)this.jumpToMark(o);else{let m={href:h,locations:{progression:0},title:"title"};this.delegate.navigate(m),setTimeout(()=>{this.searchAndPaintChapter(s.textMatch,o,async()=>{})},300)}}async goToSearchIndex(t,n,i){var o=n,s;let l=this.delegate.currentChapterLink.href;var h=this.publication.getAbsoluteHref(t);let c=this.bookSearchResult.filter(d=>d.href===t);if(i?s=this.currentChapterSearchResult[o]:s=c[o],s!==void 0)if(l===h)this.jumpToMark(o);else{let m={href:h,locations:{progression:0},title:"title"};this.delegate.navigate(m),setTimeout(()=>{this.searchAndPaintChapter(s.textMatch,o,async()=>{})},300)}}async handleSearchBook(){var t=this,n=this.searchInput.value;if(t.headerMenu)var i=$e(document,"#searchResultBook");o(1);async function o(l){i.innerHTML="";var h,c=await t.searchBook(n);if(h=t.paginate(c,l,10),h.total===0){let d=document.createElement("a");d.className="collection-item",d.innerHTML="nothing found",i.appendChild(d)}else{s(h.data,g=>g.href).forEach(g=>{let f=document.createElement("div");if(f.style.marginBottom="10px",g[0].title){let p=document.createElement("span");p.className="collection-item",p.style.display="block",p.innerHTML=g[0].title,f.appendChild(p)}i.appendChild(f),g.forEach(p=>{let b=document.createElement("a");b.className="collection-item";var S=t.publication.getAbsoluteHref(p.href);b.innerHTML="..."+p.textBefore+"<mark>"+p.textMatch+"</mark>"+p.textAfter+"...",Ce(b,"click",C=>{C.preventDefault(),C.stopPropagation();let E=c.filter(R=>R.href===p.href).findIndex(R=>R===p);if(t.delegate.currentChapterLink.href===S)t.jumpToMark(E);else{let O={href:S,locations:{progression:0},title:"title"};t.delegate.navigate(O),setTimeout(()=>{t.handleSearchChapter(E)},300)}}),f.appendChild(b)})});let m=document.createElement("div");m.style.textAlign="center",m.style.marginTop="10px";let y=document.createElement("ul");y.className="pagination";let w=document.createElement("li");if(w.className="disabled",w.innerHTML='<a href="#!"> < </a>',h.pre_page!=null){let g=h.pre_page;w.className="waves-effect",Ce(w,"click",f=>{f.preventDefault(),f.stopPropagation(),o(g)})}y.appendChild(w);for(let g=1;g<=h.total_pages;g++){let f,p=document.createElement("li");p.className="waves-effect",g===h.page&&(p.className="active",f=p),p.innerHTML='<a href="#!">'+g+"</a>",Ce(p,"click",b=>{b.preventDefault(),b.stopPropagation(),f&&(f.className="waves-effect"),p.className="active",f=p,o(g)}),y.appendChild(p)}let v=document.createElement("li");if(v.className="disabled",v.innerHTML='<a href="#!"> > </a>',h.next_page!=null){let g=h.next_page;v.className="waves-effect",Ce(v,"click",f=>{f.preventDefault(),f.stopPropagation(),o(g)})}y.appendChild(v),m.appendChild(y),i.appendChild(m)}}function s(l,h){let c=new Map;return l.forEach(d=>{let m=h(d),y=c.get(m);y?y.push(d):c.set(m,[d])}),Array.from(c.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:""),s=this.publication.getTOCItem(o);if(s===void 0&&this.publication.readingOrder&&(s=this.publication.readingOrder[i]),s){let l=this.publication.getAbsoluteHref(s.Href);this.delegate.api?.getContent?await this.delegate.api?.getContent(l).then(h=>{let d=new DOMParser().parseFromString(h,"application/xhtml+xml");s&&jo(t,d,s.Href,s.Title).then(m=>{m.forEach(y=>{n.push(y),this.bookSearchResult.push(y)})})}):await fetch(l,this.delegate.requestConfig).then(h=>h.text()).then(async h=>{let d=new DOMParser().parseFromString(this.delegate.requestConfig?.encoded?this.decodeBase64(h):h,"application/xhtml+xml");s&&jo(t,d,s.Href,s.Title).then(m=>{m.forEach(y=>{n.push(y),this.bookSearchResult.push(y)})})})}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.delegate.currentResource()??0].Href),o=this.publication.getTOCItem(i);if(o===null&&(o=this.publication.readingOrder[this.delegate.currentResource()??0]),o){let s=this.publication.getAbsoluteHref(o.Href);this.delegate.api?.getContent?await this.delegate.api?.getContent(s).then(l=>{let c=new DOMParser().parseFromString(l,"application/xhtml+xml");o&&jo(t,c,o.Href,o.Title).then(d=>{d.forEach(m=>{n.push(m)})})}):await fetch(s,this.delegate.requestConfig).then(l=>l.text()).then(async l=>{let c=new DOMParser().parseFromString(this.delegate.requestConfig?.encoded?this.decodeBase64(l):l,"application/xhtml+xml");o&&jo(t,c,o.Href,o.Title).then(d=>{d.forEach(m=>{n.push(m)})})})}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(mt.Search),this.drawSearch()}jumpToMark(t){setTimeout(()=>{if(this.currentChapterSearchResult.length){var n=this.currentChapterSearchResult[t];this.currentSearchHighlights.forEach(o=>{var s=this.properties?.color;ht.isHexColor(s)&&(s=ht.hexToRgbChannels(s)),o.color=s});var i=this.properties?.current;ht.isHexColor(i)&&(i=ht.hexToRgbChannels(i)),n.highlight.color=i,this.highlighter?.setAndResetSearchHighlight(n.highlight,this.currentSearchHighlights),this.delegate.view?.goToCssSelector(n.rangeInfo.startContainerElementCssSelector),this.delegate.updatePositionInfo()}},200)}paginate(t,n,i){let o=n||1,s=i||10,l=(o-1)*s,h=t.slice(l).slice(0,s),c=Math.ceil(t.length/s);return{page:o,per_page:s,pre_page:o-1?o-1:void 0,next_page:c>o?o+1:void 0,total:t.length,total_pages:c,data:h}}};H();var wi=gt(cn()),Ho=class{},st=Ho;st.COLOR_REF="color",st.AUTO_SCROLL_REF="autoscroll",st.RATE_REF="rate",st.PITCH_REF="pitch",st.VOLUME_REF="volume",st.VOICE_REF="voice",st.COLOR_KEY="tts-"+Ho.COLOR_REF,st.AUTO_SCROLL_KEY="tts-"+Ho.AUTO_SCROLL_REF,st.RATE_KEY="tts-"+Ho.RATE_REF,st.PITCH_KEY="tts-"+Ho.PITCH_REF,st.VOLUME_KEY="tts-"+Ho.VOLUME_REF,st.VOICE_KEY="tts-"+Ho.VOICE_REF;var Og=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,wi.default.log(n.rate)),i?.pitch&&(n.pitch=i.pitch,wi.default.log(n.pitch)),i?.volume&&(n.volume=i.volume,wi.default.log(n.volume)),i?.color&&(n.color=i.color,wi.default.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,wi.default.log(n.autoScroll)),i?.voice&&(n.voice=i.voice,wi.default.log(n.voice))}return n.initializeSelections(),n}stop(){wi.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(st.AUTO_SCROLL_KEY)!=null?this.getProperty(st.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(st.RATE_KEY)!=null?this.getProperty(st.RATE_KEY).value:this.rate,this.pitch=this.getProperty(st.PITCH_KEY)!=null?this.getProperty(st.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(st.VOLUME_KEY)!=null?this.getProperty(st.VOLUME_KEY).value:this.volume,this.color=this.getProperty(st.COLOR_KEY)!=null?this.getProperty(st.COLOR_KEY).value:this.color,this.voice=this.getProperty(st.VOICE_REF)!=null?this.getProperty(st.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=$e(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechRate=$e(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=$e(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=$e(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=$e(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),Ce($e(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(st.RATE_REF)?.value,pitch:this.userProperties.getByRef(st.PITCH_REF)?.value,volume:this.userProperties.getByRef(st.VOLUME_REF)?.value,voice:this.userProperties.getByRef(st.VOLUME_REF)?.value,color:this.userProperties.getByRef(st.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(st.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{wi.default.log("api updated tts settings",n)})}getTTSSettings(){var t=new Zr;return t.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,st.AUTO_SCROLL_REF,st.AUTO_SCROLL_KEY),t.addIncremental(this.rate,.1,10,.1,"",st.RATE_REF,st.RATE_KEY),t.addIncremental(this.pitch,.1,2,.1,"",st.PITCH_REF,st.PITCH_KEY),t.addIncremental(this.volume,.1,1,.1,"",st.VOLUME_REF,st.VOLUME_KEY),t.addStringable(this.color,st.COLOR_REF,st.COLOR_KEY),t.addJSONable(JSON.stringify(this.voice),st.VOICE_REF,st.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){wi.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(st.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.pitch){wi.default.log("pitch "+this.pitch),this.pitch=t.pitch;let n=this.userProperties.getByRef(st.PITCH_REF);n&&(n.value=this.pitch,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.volume){wi.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(st.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(st.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){wi.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(st.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.voice){wi.default.log("voice "+this.voice),this.voice=t.voice;let n=this.userProperties.getByRef(st.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(st.RATE_REF).increment();let n=this.userProperties.getByRef(st.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(st.PITCH_REF).increment();let n=this.userProperties.getByRef(st.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(st.VOLUME_REF).increment();let n=this.userProperties.getByRef(st.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}decrease(t){if(t==="rate"){this.userProperties.getByRef(st.RATE_REF).decrement();let n=this.userProperties.getByRef(st.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(st.PITCH_REF).decrement();let n=this.userProperties.getByRef(st.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(st.VOLUME_REF).decrement();let n=this.userProperties.getByRef(st.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}};H();H();var hh=`${mr.loading}`,tx=`
|
|
82
82
|
<span>
|
|
83
83
|
${mr.error}
|
|
84
84
|
</span>
|