hypothesis 1.1747.0 → 1.1749.0

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.
@@ -59,139 +59,140 @@ const t="https://h.readthedocs.io/projects/client/en/latest/publishers/config/#w
59
59
  get query(){return sn(n.query)||function(){const e=t.location.href.match(/#annotations:(query|q):(.+)$/i);if(e)try{return decodeURIComponent(e[2])}catch{}return null}()},get sideBySide(){return function(){const t=o("sideBySide");if(!function(t){return null!==t&&"object"==typeof t}(t))return{mode:"auto"};const e="mode"in t&&function(t){return"string"==typeof t&&["auto","manual"].includes(t)}(t.mode)?t.mode:"auto";return"auto"===e?{mode:e}:{mode:e,isActive:"isActive"in t&&"function"==typeof t.isActive?t.isActive:void 0}}()},hostPageSetting:o}}const ln=(t,e)=>t.hostPageSetting(e),cn={annotations:{allowInBrowserExt:!0,defaultValue:null,getValue:t=>t.annotations},appType:{allowInBrowserExt:!0,defaultValue:null,getValue:ln},branding:{defaultValue:null,allowInBrowserExt:!1,getValue:ln},bucketContainerSelector:{defaultValue:null,allowInBrowserExt:!1,getValue:ln},clientUrl:{allowInBrowserExt:!0,defaultValue:null,getValue:t=>t.clientUrl},contentInfoBanner:{allowInBrowserExt:!1,defaultValue:null,getValue:ln},
60
60
  contentReady:{allowInBrowserExt:!0,defaultValue:null,getValue:ln},enableExperimentalNewNoteButton:{allowInBrowserExt:!1,defaultValue:null,getValue:ln},group:{allowInBrowserExt:!0,defaultValue:null,getValue:t=>t.group},focus:{allowInBrowserExt:!1,defaultValue:null,getValue:ln},theme:{allowInBrowserExt:!1,defaultValue:null,getValue:ln},usernameUrl:{allowInBrowserExt:!1,defaultValue:null,getValue:ln},onLayoutChange:{allowInBrowserExt:!1,defaultValue:null,getValue:ln},openSidebar:{allowInBrowserExt:!0,defaultValue:!1,coerce:Fe,getValue:ln},query:{allowInBrowserExt:!0,defaultValue:null,getValue:t=>t.query},requestConfigFromFrame:{allowInBrowserExt:!1,defaultValue:null,getValue:ln},services:{allowInBrowserExt:!1,defaultValue:null,getValue:ln},showHighlights:{allowInBrowserExt:!1,defaultValue:"always",getValue:t=>t.showHighlights},notebookAppUrl:{allowInBrowserExt:!0,defaultValue:null,getValue:t=>t.notebookAppUrl},profileAppUrl:{allowInBrowserExt:!0,defaultValue:null,getValue:t=>t.profileAppUrl},sidebarAppUrl:{
61
61
  allowInBrowserExt:!0,defaultValue:null,getValue:t=>t.sidebarAppUrl},subFrameIdentifier:{allowInBrowserExt:!0,defaultValue:null,getValue:ln},externalContainerSelector:{allowInBrowserExt:!1,defaultValue:null,getValue:ln},sideBySide:{allowInBrowserExt:!0,getValue:t=>t.sideBySide},commentsMode:{defaultValue:!1,allowInBrowserExt:!1,getValue:ln},groupsAllowlist:{allowInBrowserExt:!1,getValue:ln}};function hn(t,e=window){const n=an(e),o={};for(const r of function(t){const e={annotator:["clientUrl","contentInfoBanner","contentReady","subFrameIdentifier","sideBySide","commentsMode"],sidebar:["appType","annotations","branding","bucketContainerSelector","enableExperimentalNewNoteButton","externalContainerSelector","focus","group","onLayoutChange","openSidebar","query","requestConfigFromFrame","services","showHighlights","sidebarAppUrl","theme","usernameUrl","commentsMode","groupsAllowlist"],notebook:["branding","group","notebookAppUrl","requestConfigFromFrame","services","theme","usernameUrl"],profile:["profileAppUrl"]}
62
- ;return"all"===t?Object.values(e).flat():e[t]}(t)){const t=cn[r],s=void 0!==t.defaultValue,a=!((i=rn(e,"sidebar","html")).startsWith("http://")||i.startsWith("https://"));if(!t.allowInBrowserExt&&a){s&&(o[r]=t.defaultValue);continue}const l=t.getValue(n,r);void 0!==l?o[r]=t.coerce?t.coerce(l):l:s&&(o[r]=t.defaultValue)}var i;return o}const dn={alt:1,ctrl:2,meta:4,shift:8};function un(t,e){if(!(t instanceof KeyboardEvent))return!1;const n=e.split("+").map((t=>t.toLowerCase()));let o=0,i=null;for(const t of n){const e=dn[t];if(e)o|=e;else{if(null!==i)throw new Error("Multiple non-modifier keys specified");i=t}}if(!i)throw new Error(`Invalid shortcut: ${e}`);return((t.ctrlKey?dn.ctrl:0)|(t.metaKey?dn.meta:0)|(t.altKey?dn.alt:0)|(t.shiftKey?dn.shift:0))===o&&t.key.toLowerCase()===i}function fn(t,e,{rootElement:n}={}){nt((()=>{if(t)return function(t,e,{rootElement:n=document.documentElement??void 0}={}){const o=n=>{un(n,t)&&e(n)};return n?(n.addEventListener("keydown",o),
63
- ()=>n.removeEventListener("keydown",o)):()=>{}}(t,e,{rootElement:n})}),[t,e,n])}const pn={applyUpdates:"l",openSearch:"/",annotateSelection:"a",highlightSelection:"h",toggleHighlights:"ctrl+shift+h",showSelection:"s",hideAdder:"Escape",activateRectMove:"ctrl+shift+y",activateRectResize:"ctrl+shift+j",activatePoint:"ctrl+shift+u"};let gn={...pn};const _n=new Set;function mn(t){const e={};return Object.keys(pn).forEach((n=>{const o=t[n];"string"!=typeof o&&null!==o||(e[n]=o)})),e}function bn(){return{...gn}}function yn(t){gn={...pn,...mn(t)},function(){const t={...gn};for(const e of _n)e(t)}()}function wn(){const[t,e]=et((()=>bn()));return nt((()=>{return t=e,_n.add(t),t({...gn}),()=>{_n.delete(t)};var t}),[]),t}const vn=(t=window)=>t.matchMedia("(pointer: coarse)").matches;function xn({badgeCount:t}){return St("span",{className:Tt("rounded px-1 py-0.5","bg-current"),children:St("span",{className:"font-bold text-color-text-inverted",children:t})})}function Cn({arrowDirection:t}){return St("div",{
64
- className:Tt("absolute left-1/2 -translate-x-1/2 z-2","fill-white text-grey-3",{"top-0 -translate-y-full":"up"===t}),children:St("up"===t?Gt:Yt,{})})}function Sn({badgeCount:t,icon:e,label:n,onClick:o,shortcut:i}){fn(i,o);const r=i?`${n} (${i})`:n;return St(ee,{classes:Tt("text-grey-7","group-hover:text-grey-5","hover:group-hover:text-grey-9"),onClick:o,title:r,size:"custom",variant:"custom",children:St("div",{className:Tt("flex flex-col items-center gap-y-1 py-2.5 px-2","text-annotator-sm leading-none"),children:[e&&St(e,{className:"text-annotator-lg",title:r}),"number"==typeof t&&St(xn,{badgeCount:t}),St("span",{"data-testid":"adder-button-label",children:n})]})})}function An({annotationCount:t,isVisible:e}){return St("div",{className:"sr-only",children:[St("span",{"aria-live":"polite","aria-atomic":"true",role:"status","data-testid":"annotation-count-announce",children:t>0&&St("span",{children:[t," ",1===t?"annotation":"annotations"," for this selection."]})}),St("ul",{"aria-live":"polite",
65
- "data-testid":"annotate-shortcuts-announce",children:e&&St(y,{children:[t>0&&St("li",{children:["Press ","'S'"," to show annotations."]}),St("li",{children:["Press ","'A'"," to annotate."]}),St("li",{children:["Press ","'H'"," to highlight."]})]})})]})}function kn({arrowDirection:t,isVisible:e,onCommand:n,annotationCount:o=0}){const i=wn(),r=e?i.annotateSelection:null,s=e?i.highlightSelection:null,a=e?i.showSelection:null;return fn(e?i.hideAdder:null,(()=>n("hide"))),St("div",{className:Tt("all-initial","border border-solid border-grey-3","absolute select-none bg-white rounded shadow-intense","opacity-5",{"animate-adder-pop-up":"up"===t&&e,"animate-adder-pop-down":"down"===t&&e}),"data-component":"AdderToolbar",dir:"ltr",style:{visibility:e?"visible":"hidden"},children:[St("div",{className:Tt("flex group"),children:[St(Sn,{icon:Ot,onClick:()=>n("annotate"),label:"Annotate",shortcut:r}),St(Sn,{icon:qt,onClick:()=>n("highlight"),label:"Highlight",shortcut:s}),o>0&&St(y,{children:[St("div",{
66
- className:Tt("m-1.5 border-r border-grey-4 border-solid")}),St(Sn,{badgeCount:o,onClick:()=>n("show"),label:"Show",shortcut:a})]})]}),St(Cn,{arrowDirection:t}),St(An,{annotationCount:o,isVisible:e})]})}let Mn;function Rn(t){const e=t.attachShadow({mode:"open"}),n=function(t){const e=document.querySelector('link[rel="preload"][href*="/build/styles/annotator.css"]')?.href;if(!e)return Promise.resolve();const n=document.createElement("link");if(n.rel="stylesheet",n.href=e,n.crossOrigin="anonymous",n.removeAttribute=()=>{},t.appendChild(n),void 0===Mn){Mn=new CSSStyleSheet;const t=Mn;n.addEventListener("load",(()=>{if(n.sheet){for(const e of n.sheet.rules)e instanceof CSSPropertyRule&&t.insertRule(e.cssText);document.adoptedStyleSheets.push(t)}}),{once:!0})}return new Promise((t=>{n.addEventListener("load",(()=>t()))}))}(e);return{shadowRoot:e,stylesLoaded:n}}class En{constructor(t,e){const n=`hypothesis-${t}`;this._element=document.createElement(n);const{shadowRoot:o}=Rn(this._element);this._shadowRoot=o,
67
- this._render=e}destroy(){H(null,this._shadowRoot),this._element.remove()}get element(){return this._element}render(){H(this._render(),this._shadowRoot)}}let Pn=function(t){return t[t.DOWN=1]="DOWN",t[t.UP=2]="UP",t}({});function Tn(t){return t.toString()+"px"}class Nn{constructor(t,e){this._view=t.ownerDocument.defaultView,this._isVisible=!1,this._arrowDirection="up",this._annotationsForSelection=[],this._onAnnotate=e.onAnnotate,this._onHighlight=e.onHighlight,this._onShowAnnotations=e.onShowAnnotations,this._container=new En("adder",(()=>this._render())),t.appendChild(this._container.element),Object.assign(this._container.element.style,{position:"absolute",top:0,left:0}),this._container.render()}get annotationsForSelection(){return this._annotationsForSelection}set annotationsForSelection(t){this._annotationsForSelection=t,this._container.render()}hide(){this._isVisible=!1,this._container.render(),Object.assign(this._container.element.style,{top:0,left:0})}destroy(){this._container.destroy()}show(t,e){
68
- const{left:n,top:o,arrowDirection:i}=this._calculateTarget(t,e);this._showAt(n,o),this._isVisible=!0,this._arrowDirection=i===Pn.UP?"up":"down",this._container.render()}_firstChild(){return this._container.element.shadowRoot.firstChild}_width(){return this._firstChild().getBoundingClientRect().width}_height(){return this._firstChild().getBoundingClientRect().height}_calculateTarget(t,e){let n,o,i;n=e&&!vn()?Pn.DOWN:Pn.UP;const r=Math.min(20,t.width),s=this._width(),a=vn()?10:0,l=this._height();return i=e?t.left-s/2+r:t.left+t.width-s/2-r,t.top-l<0&&n===Pn.DOWN?n=Pn.UP:t.top+l>this._view.innerHeight&&(n=Pn.DOWN),o=n===Pn.UP?t.top+t.height+10+a:t.top-l-10,i=Math.max(i,0),i=Math.min(i,this._view.innerWidth-s),o=Math.max(o,0),o=Math.min(o,this._view.innerHeight-l),{top:o,left:i,arrowDirection:n}}_findZindex(t,e){if(void 0===document.elementsFromPoint)return 32768;const n=this._width(),o=this._height(),i=t=>{const e=parseInt(getComputedStyle(t).zIndex);return Number.isInteger(e)?e:0
69
- },r=[...new Set([...document.elementsFromPoint(t,e),...document.elementsFromPoint(t,e+o),...document.elementsFromPoint(t+n/2,e+o/2),...document.elementsFromPoint(t+n,e),...document.elementsFromPoint(t+n,e+o)])].map(i).filter(Number.isInteger);let s=0;for(const t of document.querySelectorAll("hypothesis-highlight"))s=Math.max(s,i(t));return r.push(s),Math.max(...r)+1}_showAt(t,e){const n=function(t){let e=t.parentElement;for(;e.parentElement&&"static"===getComputedStyle(e).position;)e=e.parentElement;return e}(this._container.element).getBoundingClientRect(),o=this._findZindex(t,e);Object.assign(this._container.element.style,{left:Tn(t-n.left),top:Tn(e-n.top),zIndex:o})}_render(){return St(kn,{isVisible:this._isVisible,arrowDirection:this._arrowDirection,onCommand:t=>{switch(t){case"annotate":this._onAnnotate(),this.hide();break;case"highlight":this._onHighlight(),this.hide();break;case"show":this._onShowAnnotations(this.annotationsForSelection);break;case"hide":this.hide()}},
70
- annotationCount:this.annotationsForSelection.length})}}var Ln=function(t){return t[t.Forwards=1]="Forwards",t[t.Backwards=2]="Backwards",t}(Ln||{});function On(t,e,n){const o=n===Ln.Forwards?e:e-1;if(""!==t.charAt(o).trim())return e;let i,r;if(n===Ln.Backwards?(i=t.substring(0,e),r=i.trimEnd()):(i=t.substring(e),r=i.trimStart()),!r.length)return-1;const s=i.length-r.length;return n===Ln.Backwards?e-s:e+s}function In(t,e){const n=t.commonAncestorContainer.ownerDocument.createNodeIterator(t.commonAncestorContainer,NodeFilter.SHOW_TEXT),o=e===Ln.Forwards?t.startContainer:t.endContainer,i=e===Ln.Forwards?t.endContainer:t.startContainer;let r=n.nextNode();for(;r&&r!==o;)r=n.nextNode();e===Ln.Backwards&&(r=n.previousNode());let s=-1;const a=()=>{if(r=e===Ln.Forwards?n.nextNode():n.previousNode(),r){const t=r.textContent,n=e===Ln.Forwards?0:t.length;s=On(t,n,e)}};for(;r&&-1===s&&r!==i;)a();if(r&&s>=0)return{node:r,offset:s};throw new RangeError("No text nodes with non-whitespace text found in range")}function Bn(t){
71
- switch(t.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return t.textContent?.length??0;default:return 0}}function Dn(t){let e=t.previousSibling,n=0;for(;e;)n+=Bn(e),e=e.previousSibling;return n}function Fn(t,...e){let n=e.shift();const o=t.ownerDocument.createNodeIterator(t,NodeFilter.SHOW_TEXT),i=[];let r,s=o.nextNode(),a=0;for(;void 0!==n&&s;)r=s,a+r.data.length>n?(i.push({node:r,offset:n-a}),n=e.shift()):(s=o.nextNode(),a+=r.data.length);for(;void 0!==n&&r&&a===n;)i.push({node:r,offset:r.data.length}),n=e.shift();if(void 0!==n)throw new RangeError("Offset exceeds text length");return i}let Hn=function(t){return t[t.FORWARDS=1]="FORWARDS",t[t.BACKWARDS=2]="BACKWARDS",t}({});class zn{constructor(t,e){if(e<0)throw new Error("Offset is invalid");this.element=t,this.offset=e}relativeTo(t){if(!t.contains(this.element))throw new Error("Parent is not an ancestor of current element");let e=this.element,n=this.offset;for(;e!==t;)n+=Dn(e),e=e.parentElement;return new zn(e,n)}resolve(t={}){try{
72
- return Fn(this.element,this.offset)[0]}catch(e){if(0===this.offset&&void 0!==t.direction){const n=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);n.currentNode=this.element;const o=t.direction===Hn.FORWARDS,i=o?n.nextNode():n.previousNode();if(!i)throw e;return{node:i,offset:o?0:i.data.length}}throw e}}static fromCharOffset(t,e){switch(t.nodeType){case Node.TEXT_NODE:return zn.fromPoint(t,e);case Node.ELEMENT_NODE:return new zn(t,e);default:throw new Error("Node is not an element or text node")}}static fromPoint(t,e){switch(t.nodeType){case Node.TEXT_NODE:{if(e<0||e>t.data.length)throw new Error("Text node offset is out of range");if(!t.parentElement)throw new Error("Text node has no parent");const n=Dn(t)+e;return new zn(t.parentElement,n)}case Node.ELEMENT_NODE:{if(e<0||e>t.childNodes.length)throw new Error("Child node offset is out of range");let n=0;for(let o=0;o<e;o++)n+=Bn(t.childNodes[o]);return new zn(t,n)}default:throw new Error("Point is not in an element or text node")}}}
73
- class Vn{constructor(t,e){this.start=t,this.end=e}relativeTo(t){return new Vn(this.start.relativeTo(t),this.end.relativeTo(t))}toRange(){let t,e;this.start.element===this.end.element&&this.start.offset<=this.end.offset?[t,e]=Fn(this.start.element,this.start.offset,this.end.offset):(t=this.start.resolve({direction:Hn.FORWARDS}),e=this.end.resolve({direction:Hn.BACKWARDS}));const n=new Range;return n.setStart(t.node,t.offset),n.setEnd(e.node,e.offset),n}static fromRange(t){const e=zn.fromPoint(t.startContainer,t.startOffset),n=zn.fromPoint(t.endContainer,t.endOffset);return new Vn(e,n)}static fromOffsets(t,e,n){return new Vn(new zn(t,e),new zn(t,n))}static trimmedRange(t){return function(t){if(!t.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(t.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(t.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node")
74
- ;const e=t.cloneRange();let n=!1,o=!1;const i={start:On(t.startContainer.textContent,t.startOffset,Ln.Forwards),end:On(t.endContainer.textContent,t.endOffset,Ln.Backwards)};if(i.start>=0&&(e.setStart(t.startContainer,i.start),n=!0),i.end>0&&(e.setEnd(t.endContainer,i.end),o=!0),n&&o)return e;if(!n){const{node:t,offset:n}=In(e,Ln.Forwards);t&&n>=0&&e.setStart(t,n)}if(!o){const{node:t,offset:n}=In(e,Ln.Backwards);t&&n>0&&e.setEnd(t,n)}return e}(Vn.fromRange(t).toRange())}}const Un=".annotator-placeholder";function $n(t){return!!t.parentElement&&null!==t.parentElement.closest(Un)}function qn(t,e){const n=new Range;return t.compareBoundaryPoints(Range.START_TO_START,e)<=0?n.setStart(t.startContainer,t.startOffset):n.setStart(e.startContainer,e.startOffset),t.compareBoundaryPoints(Range.END_TO_END,e)>=0?n.setEnd(t.endContainer,t.endOffset):n.setEnd(e.endContainer,e.endOffset),n}function Wn(t=document.getSelection()){if(!t||0===t.rangeCount)return null;let e=t.getRangeAt(0)
75
- ;for(let n=1;n<t.rangeCount;n++)e=qn(e,t.getRangeAt(n));return e.collapsed?null:e}function jn(t){if(t.focusNode===t.anchorNode)return t.focusOffset<t.anchorOffset;return Wn(t).startContainer===t.focusNode}function Kn(t,e){try{const n=e.nodeValue?.length??e.childNodes.length;return t.comparePoint(e,0)<=0&&t.comparePoint(e,n)>=0}catch{return!1}}function Xn(t,e){const n=t.commonAncestorContainer,o=n.ownerDocument.createNodeIterator(n,NodeFilter.SHOW_ALL);let i;for(;i=o.nextNode();)Kn(t,i)&&e(i)}function Yn(t){const e=Wn(t);if(!e)return null;const n=function(t){const e=[];return Xn(t,(t=>{Ye(t)&&!t.textContent.match(/^\s*$/)&&e.push(t)})),e.flatMap((e=>{const n=e.ownerDocument.createRange();if(n.selectNodeContents(e),e===t.startContainer&&n.setStart(e,t.startOffset),e===t.endContainer&&n.setEnd(e,t.endOffset),n.collapsed)return[];const o=Array.from(n.getClientRects());return n.detach(),o}))}(e);return 0===n.length?null:jn(t)?n[0]:n[n.length-1]}
76
- const Gn="http://www.w3.org/2000/svg",Qn=["user-annotations","user-highlights","other-content"];class Jn{constructor(t=document.body){this.root=t}highlightShape(t){const{shape:e,anchor:n}=t,o=document.createElement("hypothesis-highlight");if(o.className="hypothesis-shape-highlight","rect"===e.type){const t=e.right-e.left,n=e.bottom-e.top;o.style.left=100*e.left+"%",o.style.top=100*e.top+"%",o.style.width=`calc(${100*t}% - 6px)`,o.style.height=`calc(${100*n}% - 6px)`}else if("point"===e.type){const t=7;o.style.left=`calc(${100*e.x}% - ${t+3}px)`,o.style.top=`calc(${100*e.y}% - ${t+3}px)`,o.style.width=2*t+"px",o.style.height=2*t+"px",o.style.borderRadius="50%"}return n.append(o),[o]}highlightRange(t,e){const n=function(t){if(t.collapsed)return[];let e=t.commonAncestorContainer;e&&e.nodeType!==Node.ELEMENT_NODE&&(e=e.parentElement);if(!e)return[];const n=[],o=e.ownerDocument.createNodeIterator(e,NodeFilter.SHOW_TEXT);let i;for(;i=o.nextNode();){if(!Kn(t,i))continue;const e=i
77
- ;e===t.startContainer&&t.startOffset>0?e.splitText(t.startOffset):(e===t.endContainer&&t.endOffset<e.data.length&&e.splitText(t.endOffset),n.push(e))}return n}(t),o=n.length>0&&$n(n[0]);let i=[],r=null,s=null;n.forEach((t=>{r&&r.nextSibling===t?s.push(t):(s=[t],i.push(s)),r=t}));const a=/^\s*$/;i=i.filter((t=>{const e=t[0].parentElement;return 1===e?.childNodes.length&&"SPAN"===e?.tagName||t.some((t=>!a.test(t.data)))}));const l=[];return i.forEach((t=>{const n=document.createElement("hypothesis-highlight");n.className=Tt("hypothesis-highlight",e);t[0].parentNode.replaceChild(n,t[0]),t.forEach((t=>n.appendChild(t))),l.push(n)})),o||function(t,e){if(0===t.length)return;const n=function(t){const e=t.closest(".page");if(!e)return null;const n=e.querySelector(".canvasWrapper > canvas");if(!n)return null;return n}(t[0]);if(!n||!n.parentElement)return;let o=n.parentElement.querySelector(".hypothesis-highlight-layer");if(!o){o=document.createElementNS(Gn,"svg"),o.setAttribute("class","hypothesis-highlight-layer"),
78
- n.parentElement.appendChild(o),n.parentElement.style.position="relative";const t=o.style;t.position="absolute",t.left="0",t.top="0",t.width="100%",t.height="100%",t.mixBlendMode="multiply"}const i=n.getBoundingClientRect(),r=t.map((t=>{const n=t.getBoundingClientRect(),o=document.createElementNS(Gn,"rect"),r=(n.left-i.left)/i.width,s=(n.top-i.top)/i.height,a=n.width/i.width,l=n.height/i.height;return o.setAttribute("x",100*r+"%"),o.setAttribute("y",100*s+"%"),o.setAttribute("width",100*a+"%"),o.setAttribute("height",100*l+"%"),o.setAttribute("class",Tt("hypothesis-svg-highlight",e)),t.classList.add("is-transparent"),t.svgHighlight=o,o}));o.append(...r)}(l,e),l}removeAllHighlights(){const t=Array.from(this.root.querySelectorAll("hypothesis-highlight"));this.removeHighlights(t)}removeHighlights(t){!function(t,e){t.forEach((t=>{t.svgHighlight?to(t.svgHighlight,e):t.classList.toggle("hypothesis-highlight-focused",e)}))}(t,!1);for(const e of t){if(e.parentNode){Zn(e,Array.from(e.childNodes))}
79
- e.svgHighlight&&e.svgHighlight.remove()}}setHighlightsFocused(t,e){t.forEach((t=>{t.svgHighlight?to(t.svgHighlight,e):t.classList.toggle("hypothesis-highlight-focused",e)}))}setHighlightsVisible(t){this.root.classList.toggle(eo,t)}getHighlightsFromPoint(t,e){return no(t,e)}}function Zn(t,e){const n=t.parentNode;e.forEach((e=>n.insertBefore(e,t))),t.remove()}function to(t,e){const n=t.parentNode,o=t.getAttribute("data-focused-id");if(Boolean(o)!==e)if(e){t.setAttribute("data-focused-id",Ce(8));const e=t.cloneNode();e.setAttribute("data-is-focused","data-is-focused"),n.append(e)}else{const e=n.querySelector(`[data-focused-id="${o}"][data-is-focused]`);e?.remove(),t.removeAttribute("data-focused-id")}}const eo="hypothesis-highlights-always-on";function no(t,e){const n=`.${eo}`,o=document.elementsFromPoint(t,e).filter((t=>"hypothesis-highlight"===t.localName&&t.closest(n))),i=[];for(const o of document.querySelectorAll("hypothesis-highlight.hypothesis-shape-highlight")){if(!o.closest(n))continue
80
- ;const r=o.getBoundingClientRect();t>=r.left&&t<r.right&&e>=r.top&&e<r.bottom&&i.push(o)}return[...o,...i]}function oo(t){so(ro(t)),function(t){for(const[e,n]of function(t){const e=new Map;for(const n of(t??document).getElementsByClassName("hypothesis-highlight-layer"))e.set(n,Array.from(n.querySelectorAll(".hypothesis-svg-highlight")));return e}(t)){n.every(((t,e,n)=>0===e||ao(t)>=ao(n[e-1])))||(n.sort(((t,e)=>ao(t)-ao(e))),e.replaceChildren(...n))}}(t)}const io=t=>"hypothesis-highlight"===t.tagName.toLowerCase();function ro(t){let e;return e=io(t)?Array.from(t.children).filter(io):Array.from(t.getElementsByTagName("hypothesis-highlight")).filter((t=>!t.parentElement||!io(t.parentElement))),e}function so(t,e="",n=0,o=0){for(const i of t){const t=Qn.find((t=>i.classList.contains(t)))??"other-content",r=e&&t===e?o+1:0;i.setAttribute("data-nesting-level",`${n}`),i.setAttribute("data-cluster-level",`${r}`),i.svgHighlight&&(i.svgHighlight.setAttribute("data-nesting-level",`${n}`),
81
- i.svgHighlight.setAttribute("data-cluster-level",`${r}`)),so(ro(i),t,n+1,r)}}function ao(t){return t.getAttribute("data-is-focused")?Number.MAX_SAFE_INTEGER:parseInt(t.getAttribute("data-nesting-level")??"0",10)}function lo(t){const e=[];return t.forEach((({annotation:t,highlights:n})=>{if(!n?.length)return;const{top:o,bottom:i}=function(t){const e=t.map((t=>t.getBoundingClientRect()));return e.reduce(((t,e)=>({top:Math.min(t.top,e.top),left:Math.min(t.left,e.left),bottom:Math.max(t.bottom,e.bottom),right:Math.max(t.right,e.right)})))}(n);o>=i||e.push({tag:t.$tag,top:o,bottom:i})})),e.sort(((t,e)=>t.top-e.top)),e}class co{constructor({contentContainer:t,hostRPC:e}){this._hostRPC=e,this._updatePending=!1,this._anchors=[],this._listeners=new mt,this._listeners.add(window,"resize",(()=>this.update())),this._listeners.add(window,"scroll",(()=>this.update())),this._listeners.add(t,"scroll",(()=>this.update()),{capture:!0})}destroy(){this._listeners.removeAll()}update(t){t&&(this._anchors=t),
82
- this._updatePending||(this._updatePending=!0,requestAnimationFrame((()=>{const t=lo(this._anchors);this._hostRPC.call("anchorsChanged",t),this._updatePending=!1})))}}const ho=["top-left","top-right","bottom-right","bottom-left"];function uo(t,e="short"){const n=t??"top-left";return"long"===e?`${n} corner pinned`:n}function fo({mode:t,tool:e,x:n,y:o,width:i,height:r,keyboardActive:s,pinnedCorner:a}){if(!s||!e)return null;let l="";if("point"===e)l="move"===t&&"number"==typeof n&&"number"==typeof o?`Pin position: ${Math.round(n)}, ${Math.round(o)}`:"resize"===t?"Pin annotation mode. Use arrow keys to move.":"Pin annotation mode. Use arrow keys to move, Enter to confirm.";else if("rect"===e)if("move"===t&&"number"==typeof n&&"number"==typeof o&&"number"==typeof i&&"number"==typeof r)l=`Rectangle position: ${Math.round(n)}, ${Math.round(o)}. Size: ${Math.round(i)} by ${Math.round(r)} pixels`;else if("resize"===t&&"number"==typeof i&&"number"==typeof r){const t=uo(a,"long")
83
- ;l=`Rectangle size: ${Math.round(i)} by ${Math.round(r)} pixels. ${t}. Press Tab to change pinned corner.`}else l="rect"===t?"Rectangle annotation mode. Click the mode button to switch to Move or Resize mode.":"Rectangle annotation mode. Use arrow keys to move, Ctrl+Shift+J to resize, Enter to confirm.";return St("div",{"aria-live":"polite","aria-atomic":"true",role:"status",className:"sr-only","data-testid":"draw-tool-announcer",children:l&&St("span",{children:l})})}function po({mode:t,keyboardActive:e,pinnedCorner:n}){if(!e||!t)return null;const o="move"===t?"Move":"resize"===t?"Resize":"Rectangle";let i;if("move"===t)i="Use arrow keys to move, click mode button to switch modes, Enter to confirm";else if("resize"===t){i=`Use arrow keys to resize (${uo(n,"short")} corner pinned), Tab to change corner, click mode button to switch modes, Enter to confirm`}else i="Rectangle mode. Click the mode button to switch to Move or Resize mode.";return St("div",{
84
- className:"fixed bottom-4 left-4 bg-white border border-grey-3 rounded shadow-lg p-3 z-50 pointer-events-none","data-testid":"draw-tool-keyboard-indicator",role:"status",children:[St("div",{className:"text-sm font-semibold text-grey-9",children:["Keyboard mode: ",o]}),St("div",{className:"text-xs text-grey-6 mt-1",children:i})]})}function go(t){return{type:"rect",left:Math.min(t.left,t.right),top:Math.min(t.top,t.bottom),right:Math.max(t.left,t.right),bottom:Math.max(t.top,t.bottom)}}function _o(t,e){const n=go(t),o=n.right-n.left,i=n.bottom-n.top,r=Math.max(e.minLeft,Math.min(n.left,e.maxRight-o)),s=Math.max(e.minTop,Math.min(n.top,e.maxBottom-i));return{type:"rect",left:r,top:s,right:r+o,bottom:s+i}}function mo(t){switch(t){case"top-left":return{top:!1,right:!0,bottom:!0,left:!1};case"top-right":return{top:!1,right:!1,bottom:!0,left:!0};case"bottom-right":return{top:!0,right:!1,bottom:!1,left:!0};case"bottom-left":return{top:!0,right:!0,bottom:!1,left:!1};default:return{top:!0,right:!0,bottom:!0,left:!0}}}
85
- const bo="#374151";function yo({shape:t,waitingForSecondClick:e,firstClickPoint:n,keyboardMode:o,keyboardActive:i,pinnedCorner:r}){if("rect"===t?.type){if(e&&n){const{x:t,y:e}=n;return St(y,{children:[St("circle",{stroke:"grey","stroke-width":"2px",fill:"none",cx:t,cy:e,r:8}),St("line",{stroke:"grey","stroke-width":"1px",x1:t-12,y1:e,x2:t+12,y2:e}),St("line",{stroke:"grey","stroke-width":"1px",x1:t,y1:e-12,x2:t,y2:e+12})]})}const s=go(t),a=s.right-s.left,l=s.bottom-s.top,c="resize"===o&&i?mo(r):{top:!1,right:!1,bottom:!1,left:!1};return St(y,{children:[St("rect",{stroke:"white","stroke-dasharray":"5","stroke-width":"1px",fill:"grey","fill-opacity":"0.5",x:s.left,y:s.top,width:a,height:l}),St("rect",{stroke:"grey","stroke-dasharray":"5","stroke-dashoffset":"5","stroke-width":"1px",fill:"none",x:s.left,y:s.top,width:a,height:l}),"resize"===o&&i&&St(y,{children:[St("line",{x1:s.left,y1:s.top,x2:s.right,y2:s.top,stroke:c.top?bo:"transparent","stroke-width":"3px","stroke-dasharray":"5","stroke-dashoffset":"5"
86
- }),St("line",{x1:s.right,y1:s.top,x2:s.right,y2:s.bottom,stroke:c.right?bo:"transparent","stroke-width":"3px","stroke-dasharray":"5","stroke-dashoffset":"5"}),St("line",{x1:s.left,y1:s.bottom,x2:s.right,y2:s.bottom,stroke:c.bottom?bo:"transparent","stroke-width":"3px","stroke-dasharray":"5","stroke-dashoffset":"5"}),St("line",{x1:s.left,y1:s.top,x2:s.left,y2:s.bottom,stroke:c.left?bo:"transparent","stroke-width":"3px","stroke-dasharray":"5","stroke-dashoffset":"5"})]})]})}if("point"===t?.type){const e=t;return St("circle",{stroke:"black","stroke-width":"1px",fill:"yellow",cx:e.x,cy:e.y,r:5})}return null}class wo extends Error{constructor(t,e="Drawing failed"){super(e),this.kind=t}}class vo{_waitingForSecondClick=!1;_hasMoved=!1;_dragThreshold=5;_keyboardMode=null;_keyboardActive=!1;_pinnedCorner="top-left";_keyboardMoveIncrement=10;_keyboardMoveIncrementLarge=50;_defaultRectangleSize=30;_minRectangleSize=20;_maxRectangleSizeRatio=.95;_rectInitiatedByKeyboard=!1;constructor(t){this._container=t,
87
- this._tool="rect",this._announcerContainer=document.createElement("div"),this._announcerContainer.setAttribute("data-testid","draw-tool-announcer-container"),t.appendChild(this._announcerContainer),this._indicatorContainer=document.createElement("div"),this._indicatorContainer.setAttribute("data-testid","draw-tool-indicator-container"),t.appendChild(this._indicatorContainer)}destroy(){this.cancel(),this._announcerContainer?.remove(),this._announcerContainer=void 0,this._indicatorContainer?.remove(),this._indicatorContainer=void 0,this._removeScrollListener()}getKeyboardModeState(){const t=this._keyboardActive&&null===this._keyboardMode?"rect":this._keyboardMode;return{keyboardActive:this._keyboardActive,keyboardMode:t}}async draw(t,e){this._tool=t,this.cancel("restarted");const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("data-testid","surface"),n.style.cursor="crosshair",n.style.touchAction="none",n.style.position="absolute",n.setAttribute("width","100%"),
88
- n.setAttribute("height","100%"),n.style.left="0px",n.style.top="0px",n.style.zIndex="10",this._container.append(n),this._surface=n;const{promise:o,resolve:i,reject:r}=function(){let t,e;return{promise:new Promise(((n,o)=>{t=n,e=o})),resolve:t,reject:e}}();return this._drawEnd=i,this._drawError=r,this._waitingForSecondClick=!1,this._firstClickPoint=void 0,this._hasMoved=!1,this._rectInitiatedByKeyboard=!1,this._surface.addEventListener("pointerdown",(t=>{switch(this._tool){case"rect":if(this._rectInitiatedByKeyboard=!1,this._waitingForSecondClick&&this._firstClickPoint)return this._shape={type:"rect",left:this._firstClickPoint.x,top:this._firstClickPoint.y,right:t.clientX,bottom:t.clientY},this._waitingForSecondClick=!1,this._firstClickPoint=void 0,i(go(this._shape)),this._abortDraw?.abort(),void t.stopPropagation();this._shape={type:"rect",left:t.clientX,top:t.clientY,right:t.clientX,bottom:t.clientY},this._hasMoved=!1,this._renderSurface();break;case"point":this._shape={type:"point",x:t.clientX,y:t.clientY}}
89
- this._renderSurface()})),this._surface.addEventListener("pointermove",(t=>{if(this._rectInitiatedByKeyboard&&"rect"===this._shape?.type)return this._shape=void 0,this._rectInitiatedByKeyboard=!1,this._waitingForSecondClick=!1,this._firstClickPoint=void 0,this._hasMoved=!1,this._deactivateKeyboardMode(),void this._renderSurface();if(this._shape){switch(this._shape.type){case"rect":if(!this._hasMoved){const e=Math.abs(t.clientX-this._shape.left),n=Math.abs(t.clientY-this._shape.top);this._hasMoved=e>=this._dragThreshold||n>=this._dragThreshold}this._shape.right=t.clientX,this._shape.bottom=t.clientY;break;case"point":this._shape.x=t.clientX,this._shape.y=t.clientY}this._renderSurface()}})),this._surface.addEventListener("pointerup",(t=>{if(this._waitingForSecondClick)t.stopPropagation();else if(this._shape){switch(this._shape.type){case"rect":if(this._hasMoved)this._shape.right=t.clientX,this._shape.bottom=t.clientY,i(go(this._shape));else{
90
- const e=Math.abs(t.clientX-this._shape.left),n=Math.abs(t.clientY-this._shape.top);if(e<this._dragThreshold&&n<this._dragThreshold)return this._firstClickPoint={x:this._shape.left,y:this._shape.top},this._waitingForSecondClick=!0,this._renderSurface(),void t.stopPropagation();this._shape.right=t.clientX,this._shape.bottom=t.clientY,i(go(this._shape))}break;case"point":this._shape.x=t.clientX,this._shape.y=t.clientY,i(this._shape)}this._abortDraw?.abort(),t.stopPropagation()}})),this._surface.addEventListener("wheel",(t=>{let e=Math.abs(t.deltaY),n=Math.abs(t.deltaX);for(const o of document.elementsFromPoint(t.clientX,t.clientY)){const i=o.scrollLeft;o.scrollLeft+=n*Math.sign(t.deltaX),n-=Math.abs(o.scrollLeft-i);const r=o.scrollTop;o.scrollTop+=e*Math.sign(t.deltaY),e-=Math.abs(o.scrollTop-r)}})),this._abortDraw=new AbortController,document.body.addEventListener("keydown",(t=>{if(!Ge(t.target)){if("Escape"===t.key)return this._keyboardActive&&this._deactivateKeyboardMode(),
91
- this._drawError&&this._drawError(new wo("canceled","Drawing canceled")),void this._abortDraw?.abort();if(this._keyboardActive){if("Tab"===t.key&&"resize"===this._keyboardMode&&"rect"===this._tool){t.preventDefault(),t.stopPropagation();const e=(ho.indexOf(this._pinnedCorner)+1)%ho.length;return this._pinnedCorner=ho[e],this._updateAnnouncer(),void this._renderSurface()}if("Enter"===t.key)return t.preventDefault(),t.stopPropagation(),void(this._shape&&("rect"===this._shape.type?i(go(this._shape)):i(this._shape),this._deactivateKeyboardMode(),this._abortDraw?.abort()));if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(t.key)){t.preventDefault(),t.stopPropagation();const e=t.metaKey||t.ctrlKey?this._keyboardMoveIncrementLarge:this._keyboardMoveIncrement;this._handleArrowKey(t.key,e)}else;}}}),{signal:this._abortDraw.signal}),this._abortDraw.signal.onabort=()=>{this._surface?.remove(),this._shape=void 0,this._surface=void 0,this._drawError=void 0,this._drawEnd=void 0,this._abortDraw=void 0,
92
- this._waitingForSecondClick=!1,this._firstClickPoint=void 0,this._hasMoved=!1,this._rectInitiatedByKeyboard=!1,this._deactivateKeyboardMode()},e&&(this._activateKeyboardMode(),this._keyboardMode=e,this._updateAnnouncer()),this._renderSurface(),o}static _RESERVED_VIEWPORT_TOP=40;_updateRectanglePosition(){this._shape=function(t,e,n,o){const{defaultRectangleSize:i,reservedViewportTop:r}=o,s=t.getBoundingClientRect(),a=t.scrollLeft||0,l=t.scrollTop||0;let c=a,h=l;const d=t.querySelectorAll(".page");let u=null,f=0;for(const t of d){const e=t.getBoundingClientRect(),n=Math.max(e.top,s.top,r),o=Math.min(e.bottom,s.bottom),i=Math.max(e.left,s.left),a=Math.min(e.right,s.right),l=Math.max(0,a-i)*Math.max(0,o-n);l>0&&e.bottom>s.top+50&&e.top<s.bottom-50&&l>f&&(f=l,u=t)}if(u){const t=u.getBoundingClientRect(),e=Math.max(t.top,s.top,r);c=Math.max(t.left,s.left)-s.left+a,h=e-s.top+l,c+=10,h+=10}else c+=10,h=Math.max(l+10,r-s.top+l+10);if(e&&"rect"===e.type)return{type:"rect",left:c,top:h,right:c+(e.right-e.left),
93
- bottom:h+(e.bottom-e.top)};return"point"===n?{type:"point",x:c,y:h}:{type:"rect",left:c,top:h,right:c+i,bottom:h+i}}(this._container,this._shape,this._tool,{defaultRectangleSize:this._defaultRectangleSize,reservedViewportTop:vo._RESERVED_VIEWPORT_TOP}),this._renderSurface()}_setupScrollListener(){this._removeScrollListener(),this._scrollListener=()=>{void 0!==this._scrollDebounceTimeout&&window.clearTimeout(this._scrollDebounceTimeout),this._scrollDebounceTimeout=window.setTimeout((()=>{this._keyboardActive&&"rect"===this._shape?.type&&(this._updateRectanglePosition(),this._updateAnnouncer())}),50)},this._container.addEventListener("scroll",this._scrollListener,{passive:!0})}_removeScrollListener(){this._scrollListener&&(this._container.removeEventListener("scroll",this._scrollListener),this._scrollListener=void 0),void 0!==this._scrollDebounceTimeout&&(window.clearTimeout(this._scrollDebounceTimeout),this._scrollDebounceTimeout=void 0)}_activateKeyboardMode(){this._keyboardActive=!0,this._keyboardMode=null,
94
- this._pinnedCorner="top-left",this._shape||(this._updateRectanglePosition(),this._rectInitiatedByKeyboard=!0),this._setupScrollListener(),this._updateAnnouncer()}_deactivateKeyboardMode(){this._keyboardActive=!1,this._keyboardMode=null,this._pinnedCorner="top-left",this._removeScrollListener(),this._updateAnnouncer()}_handleArrowKey(t,e){if(!this._shape||!this._keyboardMode)return;const n=function(t,e){const n=t.getBoundingClientRect(),o=t.scrollLeft||0,i=t.scrollTop||0;return{minLeft:o,minTop:i+Math.max(0,e-n.top),maxRight:o+t.clientWidth,maxBottom:i+t.clientHeight}}(this._container,vo._RESERVED_VIEWPORT_TOP);if("point"===this._shape.type&&"move"===this._keyboardMode)return this._shape=function(t,e,n,o){switch(e){case"ArrowUp":return{...t,y:Math.max(o.minTop,t.y-n)};case"ArrowDown":return{...t,y:Math.min(o.maxBottom,t.y+n)};case"ArrowLeft":return{...t,x:Math.max(o.minLeft,t.x-n)};case"ArrowRight":return{...t,x:Math.min(o.maxRight,t.x+n)};default:return t}}(this._shape,t,e,n),this._renderSurface(),
95
- void this._updateAnnouncer();if("rect"===this._shape.type){const o=go(this._shape);if("move"===this._keyboardMode)return this._shape=_o(function(t,e,n,o){const{left:i,top:r,right:s,bottom:a}=t;switch(e){case"ArrowUp":{const t=Math.max(o.minTop,r-n);return{type:"rect",left:i,top:t,right:s,bottom:a-(r-t)}}case"ArrowDown":{const t=Math.min(o.maxBottom,a+n);return{type:"rect",left:i,top:r+(t-a),right:s,bottom:t}}case"ArrowLeft":{const t=Math.max(o.minLeft,i-n);return{type:"rect",left:t,top:r,right:s-(i-t),bottom:a}}case"ArrowRight":{const t=Math.min(o.maxRight,s+n);return{type:"rect",left:i+(t-s),top:r,right:t,bottom:a}}default:return t}}(o,t,e,n),n),this._renderSurface(),void this._updateAnnouncer();if("resize"===this._keyboardMode){if(!function(t,e){const n=mo(e);switch(t){case"ArrowUp":return n.top||n.bottom;case"ArrowDown":return n.bottom||n.top;case"ArrowLeft":return n.left||n.right;case"ArrowRight":return n.right||n.left;default:return!1}}(t,this._pinnedCorner))return
96
- ;const i=n.maxRight-n.minLeft,r=n.maxBottom-n.minTop,s={minWidth:this._minRectangleSize,minHeight:this._minRectangleSize,maxWidth:i*this._maxRectangleSizeRatio,maxHeight:r*this._maxRectangleSizeRatio,increment:e};this._shape=_o(function(t,e,n,o){const{left:i,top:r,right:s,bottom:a}=t,{minWidth:l,minHeight:c,maxWidth:h,maxHeight:d,increment:u}=o,f={...t};switch(n){case"top-left":switch(e){case"ArrowRight":{const t=Math.min(i+h,s+u);f.right=t;break}case"ArrowDown":{const t=Math.min(r+d,a+u);f.bottom=t;break}case"ArrowLeft":f.right=Math.max(i+l,s-u);break;case"ArrowUp":f.bottom=Math.max(r+c,a-u)}break;case"top-right":switch(e){case"ArrowRight":f.left=Math.min(s-l,i+u);break;case"ArrowDown":{const t=Math.min(r+d,a+u);f.bottom=t;break}case"ArrowLeft":{const t=Math.max(s-h,i-u);f.left=t;break}case"ArrowUp":f.bottom=Math.max(r+c,a-u)}break;case"bottom-right":switch(e){case"ArrowRight":f.left=Math.min(s-l,i+u);break;case"ArrowDown":f.top=Math.min(a-c,r+u);break;case"ArrowLeft":{const t=Math.max(s-h,i-u);f.left=t
97
- ;break}case"ArrowUp":{const t=Math.max(a-d,r-u);f.top=t;break}}break;case"bottom-left":switch(e){case"ArrowRight":{const t=Math.min(i+h,s+u);f.right=t;break}case"ArrowDown":f.top=Math.min(a-c,r+u);break;case"ArrowLeft":f.right=Math.max(i+l,s-u);break;case"ArrowUp":{const t=Math.max(a-d,r-u);f.top=t;break}}}return f}(o,t,this._pinnedCorner,s),n),this._renderSurface(),this._updateAnnouncer()}}}setOnKeyboardModeChange(t){this._onKeyboardModeChange=t}setKeyboardMode(t){this._surface&&(this._keyboardActive||this._activateKeyboardMode(),this._keyboardMode!==t&&(this._keyboardMode=t,"resize"===t&&(this._pinnedCorner="top-left"),this._updateAnnouncer(),this._renderSurface()))}_updateAnnouncer(){if(!this._announcerContainer||!this._indicatorContainer)return;let t,e,n,o;if(this._shape)if("point"===this._shape.type)t=this._shape.x,e=this._shape.y;else{const i=go(this._shape);t=i.left,e=i.top,n=i.right-i.left,o=i.bottom-i.top}const i=this._keyboardActive&&null===this._keyboardMode?"rect":this._keyboardMode;H(St(fo,{
98
- mode:i,tool:this._tool,x:t,y:e,width:n,height:o,keyboardActive:this._keyboardActive,pinnedCorner:this._pinnedCorner}),this._announcerContainer),H(St(po,{mode:i,keyboardActive:this._keyboardActive,pinnedCorner:this._pinnedCorner}),this._indicatorContainer),this._onKeyboardModeChange&&this._onKeyboardModeChange({keyboardActive:this._keyboardActive,keyboardMode:i})}cancel(t="canceled"){this._drawError&&this._drawError(new wo(t,"Drawing canceled")),this._abortDraw?.abort(),this._waitingForSecondClick=!1,this._firstClickPoint=void 0,this._hasMoved=!1}_renderSurface(){this._surface&&H(St(yo,{shape:this._shape,waitingForSecondClick:this._waitingForSecondClick,firstClickPoint:this._firstClickPoint,keyboardMode:this._keyboardMode,keyboardActive:this._keyboardActive,pinnedCorner:this._pinnedCorner}),this._surface)}}class xo extends CustomEvent{constructor(t){super("hypothesis:layoutchange",{bubbles:!0,cancelable:!1,detail:t})}}const Co=new Set;function So(...t){const e=t.join();Co.has(e)||(console.warn(...t),Co.add(e))
99
- }So.reset=()=>{Co.clear()};const Ao=["pdf_image_annotation","styled_highlight_clusters","vpat_keyboard"];class ko extends Me{constructor(t=Ao){super(),this._flags=new Map,this._knownFlags=t}update(t){this._flags.clear();for(const[e,n]of Object.entries(t))this._flags.set(e,n);this.emit("flagsChanged")}flagEnabled(t){return this._knownFlags.includes(t)?this._flags.get(t)??!1:(So("Looked up unknown feature",t),!1)}allFlags(){return Object.fromEntries(this._flags)}}function Mo({cluster:t,label:e,onChange:n,currentStyles:o,highlightStyles:i}){const r=o[t],s="transparent"===r;return St("div",{className:"space-y-2",children:[St("div",{className:"flex items-center gap-x-2 text-annotator-base",children:St("div",{className:"grow text-color-text px-2 py-1 rounded",style:{backgroundColor:i[r].color},children:e})}),St("div",{className:"flex items-center gap-x-2",children:Object.keys(i).map((e=>St("div",{className:"relative",children:[St("input",{className:Tt("absolute w-6 h-6","opacity-[.00001]","cursor-pointer"),name:t,
100
- id:`hypothesis-${t}-${e}`,checked:r===e,onChange:n,type:"radio",value:e}),St("label",{className:"block",htmlFor:`${t}-${e}`,children:[St("div",{style:{backgroundColor:i[e].color},className:Tt("block w-6 h-6 rounded-full flex items-center justify-center",{"border-2 border-slate-0":r!==e,"border-2 border-slate-3":r===e}),children:"transparent"===e&&St($t,{className:Tt("w-3 h-3",{"text-slate-3":!s,"text-slate-7":s})})}),St("span",{className:"sr-only",children:e})]})]},`${t}-${e}`)))})]})}function Ro({active:t,availableStyles:e,currentStyles:n,onStyleChange:o}){const i=st((t=>{const e=t.target,n=e.name,i=e.value;o(n,i)}),[o]),[r,s]=et(!1);return t?St(Nt,{classes:"overflow-hidden",children:St("div",{className:"flex flex-col text-annotator-base text-color-text",children:[St(ee,{classes:"rounded-none","data-testid":"control-toggle-button",onClick:()=>s(!r),title:r?"Hide highlight settings":"Show highlight settings",children:St(y,r?{children:[St(Bt,{}),St("span",{children:"Highlight Appearance"})]}:{
101
- children:[St(Ft,{}),St(qt,{})]})}),r&&St(Lt,{"data-testid":"cluster-style-controls",size:"sm",children:[St(Mo,{highlightStyles:e,label:"My annotations",cluster:"user-annotations",onChange:i,currentStyles:n}),St(Mo,{highlightStyles:e,label:"My highlights",cluster:"user-highlights",onChange:i,currentStyles:n}),St(Mo,{highlightStyles:e,label:"Everybody's content",cluster:"other-content",onChange:i,currentStyles:n})]})]})}):null}const Eo={transparent:{color:"transparent",secondColor:"transparent",thirdColor:"transparent"},pink:{color:"var(--hypothesis-color-pink)",secondColor:"var(--hypothesis-color-pink-1)",thirdColor:"var(--hypothesis-color-pink-2)"},orange:{color:"var(--hypothesis-color-orange)",secondColor:"var(--hypothesis-color-orange-1)",thirdColor:"var(--hypothesis-color-orange-2)"},yellow:{color:"var(--hypothesis-color-yellow)",secondColor:"var(--hypothesis-color-yellow-1)",thirdColor:"var(--hypothesis-color-yellow-2)"},green:{color:"var(--hypothesis-color-green)",
102
- secondColor:"var(--hypothesis-color-green-1)",thirdColor:"var(--hypothesis-color-green-2)"},purple:{color:"var(--hypothesis-color-purple)",secondColor:"var(--hypothesis-color-purple-1)",thirdColor:"var(--hypothesis-color-purple-2)"},grey:{color:"var(--hypothesis-color-grey)",secondColor:"var(--hypothesis-color-grey-1)",thirdColor:"var(--hypothesis-color-grey-2)"}},Po={"other-content":"yellow","user-annotations":"orange","user-highlights":"purple"};class To{constructor(t,e){this._element=t,this._features=e.features,this._container=new En("highlight-cluster-toolbar",(()=>this._render())),this._element.appendChild(this._container.element),Object.assign(this._container.element.style,{position:"fixed",top:`${this._element.offsetTop+4}px`,left:"4px"}),this.appliedStyles=Po,this._init(),this._features.on("flagsChanged",(()=>{this._activate(this._isActive())})),this._container.render()}destroy(){clearTimeout(this._updateTimeout),this._activate(!1),this._container.destroy()}scheduleClusterUpdates(){
103
- clearTimeout(this._updateTimeout),this._updateTimeout=setTimeout((()=>this._updateClusters()),100)}_init(){for(const t of Object.keys(this.appliedStyles))this._setClusterStyles(t,this.appliedStyles[t]);this._activate(this._isActive())}_updateClusters(){this._isActive()&&oo(this._element)}_isActive(){return this._features.flagEnabled("styled_highlight_clusters")}_activate(t){this._element.classList.toggle("hypothesis-highlights-clustered",t),this._container.render()}_setClusterStyle(t,e){document.documentElement.style.setProperty(t,e)}_setClusterStyles(t,e){const n=Eo[e];for(const e of Object.keys(n))this._setClusterStyle(`--hypothesis-${t}-${e}`,n[e])}_onChangeClusterStyle(t,e){this.appliedStyles[t]=e,this._setClusterStyles(t,e),this._container.render()}_render(){return St(Ro,{active:this._isActive(),availableStyles:Eo,currentStyles:this.appliedStyles,onStyleChange:(t,e)=>this._onChangeClusterStyle(t,e)})}}function No(t){return t.split("").reverse().join("")}function Lo(t){return(t|-t)>>31&1}
104
- function Oo(t,e,n,o){let i=t.P[n],r=t.M[n];const s=o>>>31,a=e[n]|s,l=a|r,c=(a&i)+i^i|a;let h=r|~(c|i),d=i&c;const u=Lo(h&t.lastRowMask[n])-Lo(d&t.lastRowMask[n]);return h<<=1,d<<=1,d|=s,h|=Lo(o)-s,i=d|~(l|h),r=h&l,t.P[n]=i,t.M[n]=r,u}function Io(t,e,n){if(0===e.length)return[];n=Math.min(n,e.length);const o=[],i=32,r=Math.ceil(e.length/i)-1,s={P:new Uint32Array(r+1),M:new Uint32Array(r+1),lastRowMask:new Uint32Array(r+1)};s.lastRowMask.fill(1<<31),s.lastRowMask[r]=1<<(e.length-1)%i;const a=new Uint32Array(r+1),l=new Map,c=[];for(let t=0;t<256;t++)c.push(a);for(let t=0;t<e.length;t+=1){const n=e.charCodeAt(t);if(l.has(n))continue;const o=new Uint32Array(r+1);l.set(n,o),n<c.length&&(c[n]=o);for(let t=0;t<=r;t+=1){o[t]=0;for(let r=0;r<i;r+=1){const s=t*i+r;if(s>=e.length)continue;e.charCodeAt(s)===n&&(o[t]|=1<<r)}}}let h=Math.max(0,Math.ceil(n/i)-1);const d=new Uint32Array(r+1);for(let t=0;t<=h;t+=1)d[t]=(t+1)*i;d[r]=e.length;for(let t=0;t<=h;t+=1)s.P[t]=-1,s.M[t]=0;for(let u=0;u<t.length;u+=1){
105
- const f=t.charCodeAt(u);let p;f<c.length?p=c[f]:(p=l.get(f),void 0===p&&(p=a));let g=0;for(let t=0;t<=h;t+=1)g=Oo(s,p,t,g),d[t]+=g;if(d[h]-g<=n&&h<r&&(1&p[h+1]||g<0)){let t;if(h+=1,s.P[h]=-1,s.M[h]=0,h===r){const n=e.length%i;t=0===n?i:n}else t=i;d[h]=d[h-1]+t-g+Oo(s,p,h,g)}else for(;h>0&&d[h]>=n+i;)h-=1;h===r&&d[h]<=n&&(d[h]<n&&o.splice(0,o.length),o.push({start:-1,end:u+1,errors:d[h]}),n=d[h])}return o}function Bo(t,e,n){return function(t,e,n){const o=No(e);return n.map((n=>{const i=Math.max(0,n.end-e.length-n.errors);return{start:Io(No(t.slice(i,n.end)),o,n.errors).reduce(((t,e)=>n.end-e.end<t?n.end-e.end:t),n.end),end:n.end,errors:n.errors}}))}(t,e,Io(t,e,n))}function Do(t,e,n){let o=0;const i=[];for(;-1!==o;)o=t.indexOf(e,o),-1!==o&&(i.push({start:o,end:o+e.length,errors:0}),o+=1);return i.length>0?i:Bo(t,e,n)}function Fo(t,e){if(0===e.length||0===t.length)return 0;return 1-Do(t,e,e.length)[0].errors/e.length}function Ho(t,e,n={}){if(0===e.length)return null;const o=Math.min(256,e.length/2),i=Do(t,e,o)
106
- ;if(0===i.length)return null;const r=o=>{const i=1-o.errors/e.length,r=n.prefix?Fo(t.slice(Math.max(0,o.start-n.prefix.length),o.start),n.prefix):1,s=n.suffix?Fo(t.slice(o.end,o.end+n.suffix.length),n.suffix):1;let a=1;if("number"==typeof n.hint){a=1-Math.abs(o.start-n.hint)/t.length}return(50*i+20*r+20*s+2*a)/92},s=i.map((t=>({start:t.start,end:t.end,score:r(t)})));return s.sort(((t,e)=>e.score-t.score)),s[0]}function zo(t){const e=function(t){const e=t.nodeName.toLowerCase();return"#text"===e?"text()":e}(t),n=function(t){let e=0,n=t;for(;n;)n.nodeName===t.nodeName&&(e+=1),n=n.previousSibling;return e}(t);return`${e}[${n}]`}function Vo(t,e){let n="",o=t;for(;o!==e;){if(!o)throw new Error("Node is not a descendant of root");n=zo(o)+"/"+n,o=o.parentNode}return n="/"+n,n=n.replace(/\/$/,""),n}function Uo(t,e,n){e=e.toUpperCase();let o=-1;for(let i=0;i<t.children.length;i++){const r=t.children[i];if(r.nodeName.toUpperCase()===e&&(++o,o===n))return r}return null}function $o(t,e=document.body){try{
107
- return function(t,e){if(null===t.match(/^(\/[A-Za-z0-9-]+(\[[0-9]+\])?)+$/))throw new Error("Expression is not a simple XPath");const n=t.split("/");let o=e;n.shift();for(const t of n){let e,n;const i=t.indexOf("[");if(-1!==i){e=t.slice(0,i);const o=t.slice(i+1,t.indexOf("]"));if(n=parseInt(o)-1,n<0)return null}else e=t,n=0;const r=Uo(o,e,n);if(!r)return null;o=r}return o}(t,e)}catch{return document.evaluate("."+t,e,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}}class qo{constructor(t,e){this.root=t,this.range=e}static fromRange(t,e){return new qo(t,e)}static fromSelector(t,e){const n=$o(e.startContainer,t);if(!n)throw new Error("Failed to resolve startContainer XPath");const o=$o(e.endContainer,t);if(!o)throw new Error("Failed to resolve endContainer XPath");const i=zn.fromCharOffset(n,e.startOffset),r=zn.fromCharOffset(o,e.endOffset),s=new Vn(i,r).toRange();return new qo(t,s)}toRange(){return this.range}toSelector(){
108
- const t=Vn.fromRange(this.range).toRange(),e=Vn.fromRange(t),n=Vo(e.start.element,this.root),o=Vo(e.end.element,this.root);return{type:"RangeSelector",startContainer:n,startOffset:e.start.offset,endContainer:o,endOffset:e.end.offset}}}class Wo{constructor(t,e,n){this.root=t,this.start=e,this.end=n}static fromRange(t,e){const n=Vn.fromRange(e).relativeTo(t);return new Wo(t,n.start.offset,n.end.offset)}static fromSelector(t,e){return new Wo(t,e.start,e.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return Vn.fromOffsets(this.root,this.start,this.end).toRange()}}class jo{constructor(t,e,n={}){this.root=t,this.exact=e,this.context=n}static fromRange(t,e){const n=t.textContent,o=Vn.fromRange(e).relativeTo(t),i=o.start.offset,r=o.end.offset;return new jo(t,n.slice(i,r),{prefix:n.slice(Math.max(0,i-32),i),suffix:n.slice(r,Math.min(n.length,r+32))})}static fromSelector(t,e){const{prefix:n,suffix:o}=e;return new jo(t,e.exact,{prefix:n,suffix:o})}toSelector(){return{
109
- type:"TextQuoteSelector",exact:this.exact,prefix:this.context.prefix,suffix:this.context.suffix}}toRange(t={}){return this.toPositionAnchor(t).toRange()}toPositionAnchor(t={}){const e=Ho(this.root.textContent,this.exact,{...this.context,hint:t.hint});if(!e)throw new Error("Quote not found");return new Wo(this.root,e.start,e.end)}}function Ko(t){const e=parseFloat(t);return!Number.isFinite(e)||e<0?null:e}function Xo(t){return t instanceof Element?t:t.parentElement}function Yo(t,e=t){const n=Ko(t?.getAttribute("data-time-start")??""),o=Ko(e?.getAttribute("data-time-end")??"");return"number"!=typeof n||"number"!=typeof o||o<n?null:[n,o]}class Go{constructor(t,e,n){this.root=t,this.start=e,this.end=n}static fromRange(t,e){const n=Xo(e.startContainer)?.closest("[data-time-start]"),o=Xo(e.endContainer)?.closest("[data-time-end]"),i=Yo(n,o);if(!i)return null;const[r,s]=i;return new Go(t,r,s)}toRange(){const t=[...this.root.querySelectorAll("[data-time-start]")].map((t=>{const e=Yo(t);if(!e)return null;const[n,o]=e
110
- ;return{element:t,start:n,end:o}})).filter((t=>null!==t));t.sort(((t,e)=>t.start-e.start));const e=function(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}(t,(t=>t.start<=this.start&&t.end>=this.start));if(-1===e)throw new Error("Start segment not found");const n=e+t.slice(e).findIndex((t=>t.start<=this.end&&t.end>=this.end));if(-1===n)throw new Error("End segment not found");const o=new Range;o.setStart(t[e].element,0);const i=t[n].element;return o.setEnd(i,i.childNodes.length),o}static fromSelector(t,e){const{start:n,end:o}=e;return new Go(t,n,o)}toSelector(){return{type:"MediaTimeSelector",start:this.start,end:this.end}}}async function Qo(t,e){return t.toRange(e)}function Jo(t,e,n){const o=t[e];if("function"!=typeof o)throw new Error("Can only intercept functions");return t[e]=(...e)=>{const i=o.call(t,...e);return n(...e),i},()=>{t[e]=o}}function Zo(t){return t.replace(/#.*/,"")}class ti{constructor(t,e=(()=>location.href)){this._listeners=new mt;let n=e();const o=(o=e())=>{
111
- Zo(n)!==Zo(o)&&(n=o,t(o))},i=function(){const t=window.navigation;return"function"==typeof Navigation&&t instanceof Navigation?t:null}();if(i)this._listeners.add(i,"navigatesuccess",(()=>o()));else{const t=[Jo(window.history,"pushState",(()=>o())),Jo(window.history,"replaceState",(()=>o()))];this._unpatchHistory=()=>t.forEach((t=>t())),this._listeners.add(window,"popstate",(()=>o()))}}disconnect(){this._unpatchHistory?.(),this._listeners.removeAll()}}var ei,ni;var oi=function(){if(ni)return ei;ni=1;var t="complete",e="canceled";function n(t,e,n){t.self===t?t.scrollTo(e,n):(t.scrollLeft=e,t.scrollTop=n)}function o(e){var i=e._scrollSettings;if(i){var r=i.maxSynchronousAlignments,s=function(t,e){var n,o,i,r,s,a,l,c=t.align,h=t.target.getBoundingClientRect(),d=c&&null!=c.left?c.left:.5,u=c&&null!=c.top?c.top:.5,f=c&&null!=c.leftOffset?c.leftOffset:0,p=c&&null!=c.topOffset?c.topOffset:0,g=d,_=u;if(t.isWindow(e))a=Math.min(h.width,e.innerWidth),l=Math.min(h.height,e.innerHeight),
112
- o=h.left+e.pageXOffset-e.innerWidth*g+a*g,i=h.top+e.pageYOffset-e.innerHeight*_+l*_,o-=f,i-=p,o=t.align.lockX?e.pageXOffset:o,i=t.align.lockY?e.pageYOffset:i,r=o-e.pageXOffset,s=i-e.pageYOffset;else{a=h.width,l=h.height,n=e.getBoundingClientRect();var m=h.left-(n.left-e.scrollLeft),b=h.top-(n.top-e.scrollTop);o=m+a*g-e.clientWidth*g,i=b+l*_-e.clientHeight*_,o-=f,i-=p,o=Math.max(Math.min(o,e.scrollWidth-e.clientWidth),0),i=Math.max(Math.min(i,e.scrollHeight-e.clientHeight),0),o=t.align.lockX?e.scrollLeft:o,i=t.align.lockY?e.scrollTop:i,r=o-e.scrollLeft,s=i-e.scrollTop}return{x:o,y:i,differenceX:r,differenceY:s}}(i,e),a=Date.now()-i.startTime,l=Math.min(1/i.time*a,1);if(i.endIterations>=r)return n(e,s.x,s.y),e._scrollSettings=null,i.end(t);var c=1-i.ease(l);if(n(e,s.x-s.differenceX*c,s.y-s.differenceY*c),a>=i.time)return i.endIterations++,i.scrollAncestor&&o(i.scrollAncestor),void o(e);!function(t){if("requestAnimationFrame"in window)return window.requestAnimationFrame(t);setTimeout(t,16)}(o.bind(null,e))}}
113
- function i(t){return t.self===t}function r(t){return"pageXOffset"in t||(t.scrollHeight!==t.clientHeight||t.scrollWidth!==t.clientWidth)&&"hidden"!==getComputedStyle(t).overflow}function s(){return!0}function a(t){if(t.assignedSlot)return a(t.assignedSlot);if(t.parentElement)return"body"===t.parentElement.tagName.toLowerCase()?t.parentElement.ownerDocument.defaultView||t.parentElement.ownerDocument.ownerWindow:t.parentElement;if(t.getRootNode){var e=t.getRootNode();if(11===e.nodeType)return e.host}}return ei=function(n,l,c){if(n){"function"==typeof l&&(c=l,l=null),l||(l={}),l.time=isNaN(l.time)?1e3:l.time,l.ease=l.ease||function(t){return 1-Math.pow(1-t,t/2)},l.align=l.align||{};var h=a(n),d=1,u=l.validTarget||s,f=l.isScrollable;l.debug&&(console.log("About to scroll to",n),h||console.error("Target did not have a parent, is it mounted in the DOM?"));for(var p=[];h;)if(l.debug&&console.log("Scrolling parent node",h),u(h,d)&&(f?f(h,r):r(h))&&(d++,p.push(h)),!(h=a(h))){g(t);break}
114
- return p.reduce(((t,r,s)=>function(t,n,r,s,a){var l,c=!n._scrollSettings,h=n._scrollSettings,d=Date.now(),u={passive:!0};function f(t){n._scrollSettings=null,n.parentElement&&n.parentElement._scrollSettings&&n.parentElement._scrollSettings.end(t),r.debug&&console.log("Scrolling ended with type",t,"for",n),a(t),l&&(n.removeEventListener("touchstart",l,u),n.removeEventListener("wheel",l,u))}h&&h.end(e);var p=r.maxSynchronousAlignments;return null==p&&(p=3),n._scrollSettings={startTime:d,endIterations:0,target:t,time:r.time,ease:r.ease,align:r.align,isWindow:r.isWindow||i,maxSynchronousAlignments:p,end:f,scrollAncestor:s},"cancellable"in r&&!r.cancellable||(l=f.bind(null,e),n.addEventListener("touchstart",l,u),n.addEventListener("wheel",l,u)),c&&o(n),l}(n,r,l,p[s+1],g)),null)}function g(t){--d||c&&c(t)}},ei}(),ii=kt(oi);function ri(t,e,n){return t+n*(e-t)}async function si(t,e,{maxDuration:n=500}={}){const o=t.scrollTop,i=e,r=Date.now(),s=Math.min(Math.abs(i-o)/3,n);let a=0;for(;a<1;)await new Promise((t=>{
115
- requestAnimationFrame(t)})),a=Math.min(1,(Date.now()-r)/s),t.scrollTop=ri(o,i,a)}function ai(t,e=document.baseURI){return new URL(t,e).href.toString().replace(/#.*/,"")}class li{constructor(t={}){this.document=t.document||document}uri(){let t=this._getDocumentHref();try{t=decodeURIComponent(t)}catch(t){console.error("Error decoding URI:",t)}const e=this._getLinks();for(const n of e)"canonical"===n.rel&&(t=n.href);return t}getDocumentMetadata(){const t={title:document.title,link:[],dc:this._getMetaTags("name","dc."),eprints:this._getMetaTags("name","eprints."),facebook:this._getMetaTags("property","og:"),highwire:this._getMetaTags("name","citation_"),prism:this._getMetaTags("name","prism."),twitter:this._getMetaTags("name","twitter:")},e=this._getFavicon();e&&(t.favicon=e),t.title=this._getTitle(t),t.link=this._getLinks(t);const n=t.link.find((t=>t.href.startsWith("urn:x-dc")));return n&&(t.documentFingerprint=n.href),t}_getMetaTags(t,e){const n={}
116
- ;for(const o of Array.from(this.document.querySelectorAll("meta"))){const i=o.getAttribute(t),{content:r}=o;if(i&&r){const t=i.match(RegExp(`^${e}(.+)$`,"i"));if(t){const e=t[1].toLowerCase();n[e]?n[e].push(r):n[e]=[r]}}}return n}_getTitle(t){return t.highwire.title?t.highwire.title[0]:t.eprints.title?t.eprints.title[0]:t.prism.title?t.prism.title[0]:t.facebook.title?t.facebook.title[0]:t.twitter.title?t.twitter.title[0]:t.dc.title?t.dc.title[0]:this.document.title}_getLinks(t={dc:{},highwire:{}}){const e=[{href:this._getDocumentHref()}],n=Array.from(this.document.querySelectorAll("link"));for(const t of n)if(["alternate","canonical","bookmark","shortlink"].includes(t.rel)){if("alternate"===t.rel){if(t.type&&t.type.match(/^application\/(rss|atom)\+xml/))continue;if(t.hreflang)continue}try{const n=this._absoluteUrl(t.href);e.push({href:n,rel:t.rel,type:t.type})}catch{}}for(const n of Object.keys(t.highwire)){const o=t.highwire[n];if("pdf_url"===n)for(const t of o)try{e.push({href:this._absoluteUrl(t),
117
- type:"application/pdf"})}catch{}if("doi"===n)for(let t of o)"doi:"!==t.slice(0,4)&&(t=`doi:${t}`),e.push({href:t})}for(const n of Object.keys(t.dc)){const o=t.dc[n];if("identifier"===n)for(const t of o)"doi:"===t.slice(0,4)&&e.push({href:t})}const o=t.dc["relation.ispartof"],i=t.dc.identifier;if(o&&i){const t=o[o.length-1],n=i[i.length-1],r="urn:x-dc:"+encodeURIComponent(t)+"/"+encodeURIComponent(n);e.push({href:r})}return e}_getFavicon(){let t=null;for(const e of Array.from(this.document.querySelectorAll("link")))if(["shortcut icon","icon"].includes(e.rel))try{t=this._absoluteUrl(e.href)}catch{}return t}_absoluteUrl(t){return ai(t,this.document.baseURI)}_getDocumentHref(){const{href:t}=this.document.location,e=["http:","https:","file:"],n=new URL(t).protocol;return e.includes(n)?t:this.document.baseURI&&e.includes(new URL(this.document.baseURI).protocol)?this.document.baseURI:t}}class ci extends Me{constructor({features:t,container:e=document.body,sideBySideOptions:n}){super(),this.featureFlags=t,
118
- this.container=e,this._htmlMeta=new li,this._prevURI=this._htmlMeta.uri(),this._sideBySideEnabled=!0,this._sideBySideOptions=n??{mode:"auto"},this._sideBySideActive=!1,this._lastLayout=null,this._navObserver=new ti((()=>this._checkForURIChange())),this._metaObserver=new MutationObserver((()=>this._checkForURIChange())),this._metaObserver.observe(document.head,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["rel","href","name","content"]}),this._flagsChanged=()=>{},this.featureFlags.on("flagsChanged",this._flagsChanged)}anchor(t,e){return function(t,e,n={}){let o=null,i=null,r=null,s=null;for(const t of e)switch(t.type){case"TextPositionSelector":i=t,n.hint=i.start;break;case"TextQuoteSelector":r=t;break;case"RangeSelector":s=t;break;case"MediaTimeSelector":o=t}const a=t=>{if(r?.exact&&t.toString()!==r.exact)throw new Error("quote mismatch");return t};let l=Promise.reject("unable to anchor");if(s){const e=s;l=l.catch((()=>Qo(qo.fromSelector(t,e),n).then(a)))}if(i){const e=i
119
- ;l=l.catch((()=>Qo(Wo.fromSelector(t,e),n).then(a)))}if(r){const e=r;l=l.catch((()=>Qo(jo.fromSelector(t,e),n)))}if(o){const e=o;l=l.catch((()=>Go.fromSelector(t,e).toRange()))}return l}(t,e)}describe(t,e){if(e instanceof Range)return function(t,e){const n=[Go,qo,Wo,jo],o=[];for(const i of n)try{const n=i.fromRange(t,e);n&&o.push(n.toSelector())}catch{}return o}(t,e);throw new Error("Unsupported region type")}_checkForURIChange(){const t=this._htmlMeta.uri();t!==this._prevURI&&(this._prevURI=t,this.emit("uriChanged",t))}getAnnotatableRange(t){try{return Vn.trimmedRange(t)}catch(t){if(t instanceof RangeError)return null;throw t}}canStyleClusteredHighlights(){return!0}destroy(){this._deactivateSideBySide(),this._navObserver.disconnect(),this._metaObserver.disconnect(),this.featureFlags.off("flagsChanged",this._flagsChanged),super.destroy()}contentContainer(){return this.container}fitSideBySide(t){this._lastLayout=t
120
- ;const e=window.innerWidth-t.width,n=this._sideBySideEnabled&&"auto"===this._sideBySideOptions.mode&&t.expanded&&e>=480;return n?this._activateSideBySide(t.width):this._sideBySideActive&&this._deactivateSideBySide(),this._sideBySideActive=n,this.container.classList.toggle("hypothesis-sidebyside-active",this._sideBySideActive),n}sideBySideActive(){return this._sideBySideActive}supportedTools(){return["selection"]}_activateSideBySide(t){const e=t+12,n=t=>parseInt(window.getComputedStyle(t).marginLeft,10);on((()=>{document.body.style.marginLeft="",document.body.style.marginRight="";const t=n(document.body);document.body.style.marginRight=`${e}px`;const o=function(t){const e=new Map,n=new Map,o=Qe.join(","),i=Array.from(t.querySelectorAll(o)).map((t=>({rect:t.getBoundingClientRect(),textLength:t.textContent.length}))).filter((({rect:t})=>t.width>0&&t.height>0)).sort(((t,e)=>e.textLength-t.textLength)).slice(0,15);if(i.forEach((({rect:t})=>{let o=e.get(t.left)??0;o+=1,e.set(t.left,o);let i=n.get(t.right)??0;i+=1,
121
- n.set(t.right,i)})),0===e.size||0===n.size)return null;const r=[...e.entries()].sort(((t,e)=>e[1]-t[1])),s=[...n.entries()].sort(((t,e)=>e[1]-t[1])),[a]=r[0],[l]=s[0];return{left:a,right:l}}(document.body);if(o){const i=Math.max(0,window.innerWidth-e-o.right);if(i>0){const t=Math.max(0,e-i);document.body.style.marginRight=`${t}px`}n(document.body)>t&&(document.body.style.marginLeft=`${t}px`),o.left<12&&(document.body.style.marginLeft="12px")}else document.body.style.marginLeft="",document.body.style.marginRight=""}))}_deactivateSideBySide(){on((()=>{document.body.style.marginLeft="",document.body.style.marginRight=""}))}async getMetadata(){return this._htmlMeta.getDocumentMetadata()}async uri(){return this._htmlMeta.uri()}async scrollToAnchor(t){const e=t.highlights?.[0];e&&await async function(t,{maxDuration:e=500}={}){const n=t.closest("body");n&&"BODY"!==n.tagName&&Object.defineProperty(n,"tagName",{value:"BODY",configurable:!0});const o=t.closest("details");o&&!o.hasAttribute("open")&&(o.open=!0),
122
- await new Promise((n=>ii(t,{time:e},n)))}(e)}}var hi,di;var ui=function(){if(di)return hi;di=1;var t=NaN,e="[object Symbol]",n=/^\s+|\s+$/g,o=/^[-+]0x[0-9a-f]+$/i,i=/^0b[01]+$/i,r=/^0o[0-7]+$/i,s=parseInt,a="object"==typeof At&&At&&At.Object===Object&&At,l="object"==typeof self&&self&&self.Object===Object&&self,c=a||l||Function("return this")(),h=Object.prototype.toString,d=Math.max,u=Math.min,f=function(){return c.Date.now()};function p(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function g(a){if("number"==typeof a)return a;if(function(t){return"symbol"==typeof t||function(t){return!!t&&"object"==typeof t}(t)&&h.call(t)==e}(a))return t;if(p(a)){var l="function"==typeof a.valueOf?a.valueOf():a;a=p(l)?l+"":l}if("string"!=typeof a)return 0===a?a:+a;a=a.replace(n,"");var c=i.test(a);return c||r.test(a)?s(a.slice(2),c?2:8):o.test(a)?t:+a}return hi=function(t,e,n){var o,i,r,s,a,l,c=0,h=!1,_=!1,m=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function b(e){var n=o,r=i
123
- ;return o=i=void 0,c=e,s=t.apply(r,n)}function y(t){var n=t-l;return void 0===l||n>=e||n<0||_&&t-c>=r}function w(){var t=f();if(y(t))return v(t);a=setTimeout(w,function(t){var n=e-(t-l);return _?u(n,r-(t-c)):n}(t))}function v(t){return a=void 0,m&&o?b(t):(o=i=void 0,s)}function x(){var t=f(),n=y(t);if(o=arguments,i=this,l=t,n){if(void 0===a)return function(t){return c=t,a=setTimeout(w,e),h?b(t):s}(l);if(_)return a=setTimeout(w,e),b(l)}return void 0===a&&(a=setTimeout(w,e)),s}return e=g(e)||0,p(n)&&(h=!!n.leading,r=(_="maxWait"in n)?d(g(n.maxWait)||0,e):r,m="trailing"in n?!!n.trailing:m),x.cancel=function(){void 0!==a&&clearTimeout(a),c=0,o=l=i=a=void 0},x.flush=function(){return void 0===a?s:v(f())},x},hi}(),fi=kt(ui);function pi(t,e,n,o=0){let i=o;for(;i<t.length&&e>0;)n(t[i])&&--e,++i;return i}function gi(t,e,n,o){let i=0;for(let r=n;r<o;r++)e(t[r])&&++i;return i}const _i=new Map;function mi(t,e){const n=t.normalize("NFKD");if(n===t)return{input:t,output:n};const o=[],i=[];let r=0,s=0;for(const n of t){
124
- const t=n.codePointAt(0);let a=_i.get(t);if(void 0===a&&(a=n.normalize("NFKD").length,_i.set(t,a)),e.offsets){for(let t=0;t<n.length;t++)i.push(s);s+=a}if(e.reverseOffsets){for(let t=0;t<a;t++)o.push(r);r+=n.length}}return e.offsets&&i.push(n.length),e.reverseOffsets&&o.push(r),{input:t,output:n,reverseOffsets:o,offsets:i}}function bi(t,e,n,o,i,r={}){n=Math.max(0,Math.min(n,t.length)),o=Math.max(n,Math.min(o,t.length));const s=r.normalize?mi(t,{offsets:!0}):{output:t},a=r.normalize?mi(e,{reverseOffsets:!0}):{output:e},l=s.offsets?.[n]??n,c=s.offsets?.[o]??o,h=gi(s.output,i,0,l),d=gi(s.output,i,l,c);let u=pi(a.output,h,i);for(;u<a.output.length&&!i(a.output[u]);)++u;const f=pi(a.output,d,i,u);return[a.reverseOffsets?.[u]??u,a.reverseOffsets?.[f]??f]}const yi={INITIAL:0,FINISHED:3},wi=new Map,vi=new Map;function xi(t,e){return`${t}:${e}`}function Ci(t){const e="closest"in t?t:t.parentElement;return e?.closest(".textLayer")??null}function Si(){return PDFViewerApplication.pdfViewer}async function Ai(t){
125
- const e=Si();let n=e.getPageView(t);return n&&n.pdfPage||(n=await new Promise((n=>{const o=()=>{e.eventBus?e.eventBus.off("pagesloaded",o):document.removeEventListener("pagesloaded",o),n(e.getPageView(t))};e.eventBus?e.eventBus.on("pagesloaded",o):document.addEventListener("pagesloaded",o)}))),n}function ki(t,e){return document.elementsFromPoint(t,e).find((t=>t.classList.contains("textLayer")))}function Mi(t){const e=wi.get(t);if(e)return e;const n=(async()=>{const e=await Ai(t);return(await e.pdfPage.getTextContent({normalizeWhitespace:!0})).items.map((t=>t.str)).join("")})();return wi.set(t,n),n}async function Ri(t){const e=Si();let n=0,o=0,i="";for(let r=0;r<e.pagesCount;r++)if(i=await Mi(r),n=o,o+=i.length,o>=t)return{index:r,offset:n,text:i};return{index:e.pagesCount-1,offset:n,text:i}}function Ei(t){switch(t){case" ":case"\f":case"\n":case"\r":case"\t":case"\v":case" ":return!0;default:return!1}}const Pi=t=>!Ei(t);function Ti(t){
126
- return void 0!==t.renderingDone?t.renderingDone:!!t.div&&null!==t.div.querySelector(".endOfContent")}async function Ni(t,e,n){const[o,i]=await Promise.all([Ai(t),Mi(t)]);if(o.renderingState===yi.FINISHED&&o.textLayer&&Ti(o.textLayer)){const t=o.textLayer.textLayerDiv??o.textLayer.div;if(!t)throw new Error("Unable to find PDF.js text layer root");const r=t.textContent,[s,a]=bi(i,r,e,n,Pi,{normalize:!0}),l=Li(r.slice(s,a)),c=Li(i.slice(e,n));l.normalize("NFKD")!==c.normalize("NFKD")&&So("Text layer text does not match page text. Highlights will be mis-aligned.");const h=new zn(t,s),d=new zn(t,a);return new Vn(h,d).toRange()}const r=function(t){let e=t.querySelector(Un);return e||(e=document.createElement("span"),e.classList.add("annotator-placeholder"),e.textContent="Loading annotations...",t.appendChild(e),e)}(o.div),s=document.createRange();return s.setStartBefore(r),s.setEndAfter(r),s}function Li(t){let e="";for(let n=0;n<t.length;n++){const o=t[n];Ei(o)||(e+=o)}return e}async function Oi(t){
127
- const e=t.find((t=>"TextQuoteSelector"===t.type));if(!e)throw new Error("No quote selector found");const n=t.find((t=>"TextPositionSelector"===t.type));if(n){try{const{index:t,offset:o,text:i}=await Ri(n.start),r=n.start-o,s=n.end-o,a=i.substring(r,s);if(e.exact!==a)throw new Error("quote mismatch");return await Ni(t,r,s)}catch{}try{const t=xi(e.exact,n.start),o=vi.get(t);if(o){const{pageIndex:t,anchor:e}=o;return await Ni(t,e.start,e.end)}}catch{}}return async function(t,e){const n=Si().pagesCount,o=Array(n).fill(0).map(((t,e)=>e));let i,r;if(e){const{index:t,offset:n}=await Ri(e);i=t,r=e-n,o.sort(((e,n)=>Math.abs(e-t)-Math.abs(n-t)))}const s=void 0!==t.prefix?Li(t.prefix):void 0,a=void 0!==t.suffix?Li(t.suffix):void 0,l=Li(t.exact);let c;for(const t of o){const e=await Mi(t),n=Li(e);let o;void 0!==i&&void 0!==r&&(t<i?o=n.length:t===i?[o]=bi(e,n,r,r,Pi,{normalize:!1}):o=0);const h=Ho(n,l,{prefix:s,suffix:a,hint:o});if(h&&(!c||h.score>c.match.score)){const[o,i]=bi(n,e,h.start,h.end,Pi);c={page:t,match:{
128
- start:o,end:i,score:h.score}};const r=n.slice(h.start,h.end)===l,d=void 0!==s&&n.slice(Math.max(0,h.start-s.length),h.start)===s,u=void 0!==a&&n.slice(h.end,a.length)===a;if(r&&(d||u||void 0===s&&void 0===a))break}}if(c){const{page:n,match:o}=c;if(e){const i=xi(t.exact,e);vi.set(i,{pageIndex:n,anchor:o})}return Ni(n,o.start,o.end)}throw new Error("Quote not found")}(e,n?.start)}async function Ii(t){const e=t.find((t=>"PageSelector"===t.type)),n=t.find((t=>"ShapeSelector"===t.type));if(n){if(!e)throw new Error("Cannot anchor a shape selector without a page");return async function(t,e){const n=Si();if("number"!=typeof t.index||t.index<0||t.index>=n.pagesCount)throw new Error("PDF page index is invalid");const o=await Ai(t.index),i=o.div,r=o.viewport,s=t=>function(t,e,n){return Math.max(Math.min(t,n),e)}(t,0,1);let a;switch(e.shape.type){case"rect":{const t=e.shape;let[n,o]=r.convertToViewportPoint(t.left,t.top),[i,l]=r.convertToViewportPoint(t.right,t.bottom);i<n&&([n,i]=[i,n]),l<o&&([o,l]=[l,o]),a={
129
- type:"rect",left:s(n/r.width),top:s(o/r.height),right:s(i/r.width),bottom:s(l/r.height)}}break;case"point":{const t=e.shape,[n,i]=o.viewport.convertToViewportPoint(t.x,t.y);a={type:"point",x:s(n/r.width),y:s(i/r.height)}}break;default:throw new Error("Unsupported shape in shape selector")}return{anchor:i,shape:a,coordinates:"anchor"}}(e,n)}return Oi(t)}function Bi(t){try{t=Vn.fromRange(t).toRange()}catch{throw new Error("Selection does not contain text")}const e=Ci(t.startContainer),n=Ci(t.endContainer);if(!e||!n)throw new Error("Selection is outside page text");if(e!==n)throw new Error("Selecting across page breaks is not supported");return[t,e]}function Di(t){const e=t.closest(".page"),n=parseInt(e?.getAttribute("data-page-number")??"");if(!Number.isInteger(n))throw new Error("Unable to get page number from element");return n-1}async function Fi(t){
130
- const[e,n]=Bi(t),o=zn.fromPoint(e.startContainer,e.startOffset).relativeTo(n),i=zn.fromPoint(e.endContainer,e.endOffset).relativeTo(n),r=Di(n),s=await async function(t){if(t>=Si().pagesCount)throw new Error("Invalid page index");let e=0;for(let n=0;n<t;n++)e+=(await Mi(n)).length;return e}(r),a=await Ai(r);return[{type:"TextPositionSelector",start:s+o.offset,end:s+i.offset},jo.fromRange(a.div,e).toSelector(),zi(a,r)]}async function Hi(t,e){const n=document.elementsFromPoint(t,e);for(const o of n){if(!o.classList.contains("page"))continue;const n=Di(o),i=getComputedStyle(o),r=parseFloat(i.borderLeftWidth),s=parseFloat(i.borderTopWidth),a=o.getBoundingClientRect(),l=t-a.left-r,c=e-a.top-s,h=await Ai(n),[d,u]=h.getPagePoint(l,c);return{pageIndex:n,x:d,y:u}}return null}function zi(t,e){return{type:"PageSelector",index:e,label:t.pageLabel??`${e+1}`}}async function Vi(t){const e=t=>{const[e,n,o,i]=t.view;return{left:e,top:i,right:o,bottom:n}},n=(t,e)=>function(t,e){
131
- const n=t.ownerDocument.createNodeIterator(t,NodeFilter.SHOW_TEXT),o=[];let i,r;for(;r=n.nextNode();){const t=r,n=t.data.split(/\b/);let s=0;for(const r of n){const n=new Range;n.setStart(t,s);const a=s+r.length;n.setEnd(t,a);const l=n.getBoundingClientRect();$e(l,e)&&(i&&!qe(i,l)&&o.push(" "),o.push(r),i=l),s=a}}return o.join("")}(t,e).slice(0,256);switch(t.type){case"rect":{const[o,i]=await Promise.all([Hi(t.left,t.top),Hi(t.right,t.bottom)]);if(!o)throw new Error("Top-left point is not in a page");if(!i)throw new Error("Bottom-right point is not in a page");if(o.pageIndex!==i.pageIndex)throw new Error("Shape must start and end on same page");const r=await Ai(o.pageIndex),s={type:"rect",left:o.x,top:o.y,right:i.x,bottom:i.y},a=ki(t.left,t.top);let l;if(a){l=n(a,new DOMRect(t.left,t.top,t.right-t.left,t.bottom-t.top))}return[zi(r,o.pageIndex),{type:"ShapeSelector",anchor:"page",shape:s,view:e(r.pdfPage),text:l}]}case"point":{const o=await Hi(t.x,t.y);if(!o)throw new Error("Point is not in a page")
132
- ;const i=ki(t.x,t.y);let r;if(i){r=n(i,new DOMRect(t.x,t.y,1,1))}const s=await Ai(o.pageIndex);return[zi(s,o.pageIndex),{type:"ShapeSelector",anchor:"page",shape:{type:"point",x:o.x,y:o.y},text:r,view:e(s.pdfPage)}]}default:throw new Error("Unsupported shape")}}function Ui({children:t}){return St("div",{className:"flex flex-col",children:t})}function $i({info:t}){let e=t.item.title;return t.item.subtitle&&(e+=`: ${t.item.subtitle}`),St("div",{className:Tt("h-10 bg-white px-4 text-slate-7 text-annotator-base border-b","grid items-center","grid-cols-[100px_minmax(0,auto)]","2xl:grid-cols-[100px_minmax(0,auto)_minmax(0,auto)] 2xl:gap-x-3"),children:[St("div",{"data-testid":"content-logo",children:t.logo&&St(we,{href:t.logo.link,target:"_blank","data-testid":"logo-link",underline:"none",children:St("img",{alt:t.logo.title,src:t.logo.logo,"data-testid":"logo-image"})})}),St("div",{className:Tt("hidden","2xl:block 2xl:whitespace-nowrap 2xl:overflow-hidden 2xl:text-ellipsis","font-semibold"),
133
- "data-testid":"content-container-info",title:t.container.title,children:t.container.title}),St("div",{className:Tt("flex justify-center items-center gap-x-2"),"data-testid":"content-item-info",children:[St("div",{className:Tt("hidden","2xl:block 2xl:grow")}),t.links.previousItem&&St(y,{children:[St(we,{title:"Open previous item",href:t.links.previousItem,underline:"always",target:"_blank","data-testid":"content-previous-link",children:St("div",{className:"flex gap-x-1 items-center text-annotator-sm whitespace-nowrap",children:[St(Dt,{className:"w-em h-em"}),St("span",{children:"Previous"})]})}),St("div",{className:"text-annotator-sm",children:"|"})]}),St("div",{className:Tt("min-w-0 whitespace-nowrap overflow-hidden text-ellipsis shrink font-medium"),children:St(we,{title:e,href:t.links.currentItem,"data-testid":"content-item-link",target:"_blank",unstyled:!0,children:e})}),t.links.nextItem&&St(y,{children:[St("div",{className:"text-annotator-sm",children:"|"}),St(we,{title:"Open next item",
134
- href:t.links.nextItem,underline:"always",target:"_blank","data-testid":"content-next-link",children:St("div",{className:"flex gap gap-x-1 items-center text-annotator-sm whitespace-nowrap",children:[St("span",{children:"Next"}),St(Ft,{className:"w-em h-em"})]})})]})]})]})}function qi(){return St("div",{className:"bg-white",role:"alert",children:St("div",{className:Tt("flex items-center gap-x-2","border border-yellow-notice bg-yellow-notice/10 text-annotator-base"),children:[St("div",{className:"bg-yellow-notice text-white p-2",children:St(Ht,{className:"text-annotator-xl"})}),St("div",{children:[St("strong",{children:"Text annotation tools are unavailable because this PDF does not contain selectable text."})," ",St(we,{target:"_blank",href:"https://web.hypothes.is/help/how-to-ocr-optimize-pdfs/",underline:"always",children:"Learn more here"}),"."]})]})})}class Wi{constructor(t){this._loaded=function(t){return t.initializedPromise?t.initializedPromise:t.initialized?Promise.resolve():new Promise((e=>{
135
- const n=setInterval((()=>{t.initialized&&(clearTimeout(n),e())}),5)}))}(t).then((async()=>{const e=await async function(t){return void 0!==t.downloadComplete?t.downloadComplete:(await t.pdfDocument.getDownloadInfo(),!0)}(t);return e?t:new Promise((e=>{const n=()=>{t.eventBus?(t.eventBus.off("documentload",n),t.eventBus.off("documentloaded",n)):window.removeEventListener("documentload",n),e(t)};t.eventBus?(t.eventBus.on("documentloaded",n),t.eventBus.on("documentload",n)):window.addEventListener("documentload",n)}))}))}getUri(){return this._loaded.then((t=>{let e=Xi(t);return e||(e=Ki(ji(t))),e}))}async getMetadata(){const t=await this._loaded,{info:e,contentDispositionFilename:n,metadata:o}=await t.pdfDocument.getMetadata(),i=ji(t),r=Xi(t),s=o?.get("dc:title");let a;a=s&&"Untitled"!==s?s:e?.Title?e.Title:n||(r?function(t){const e=new URL(t),n=e.pathname.split("/");return n[n.length-1]}(r):"");const l=[{href:Ki(i)}];return r&&l.push({href:r}),{title:a,link:l,documentFingerprint:i}}}function ji(t){
136
- return Array.isArray(t.pdfDocument.fingerprints)?t.pdfDocument.fingerprints[0]:t.pdfDocument.fingerprint}function Ki(t){return`urn:x-pdf:${t}`}function Xi(t){if(!t.url)return null;const e=ai(t.url);return 0!==e.indexOf("file://")?e:null}function Yi(t){const e=t.highlights?.[0];return e&&$n(e)}function Gi(t){return new Promise((e=>setTimeout(e,t)))}class Qi{constructor(){this._pdfjsContainer=document.querySelector("#outerContainer"),this._contentInfo=null,this._noTextWarning=!1,this._container=null}setContentInfo(t){this._contentInfo=t,this._update()}showNoTextWarning(t){this._noTextWarning=t,this._update()}destroy(){this._container?.destroy()}_update(){if(!(this._noTextWarning||this._contentInfo))return this._container?.destroy(),this._container=null,void(this._pdfjsContainer.style.height="");this._container||(this._container=new En("banner",(()=>this._render())),document.body.prepend(this._container.element)),this._container.render();const t=this._container.element.getBoundingClientRect().height
137
- ;this._pdfjsContainer.style.height=`calc(100% - ${t}px)`}_render(){return St(Ui,{children:[this._contentInfo&&St($i,{info:this._contentInfo}),this._noTextWarning&&St(qi,{})]})}}class Ji extends Me{constructor({annotator:t,features:e,reanchoringMaxWait:n}){super(),this._annotator=t;const o=window,i=o.PDFViewerApplication;this._pdfViewer=i.pdfViewer,this._pdfViewer.viewer.classList.add("has-transparent-text-layer"),this._pdfContainer=i.appConfig?.appContainer??document.body,this._pdfMetadata=new Wi(i),this._observer=new MutationObserver(fi((()=>this._update()),100)),this._observer.observe(this._pdfViewer.viewer,{attributes:!0,attributeFilter:["data-loaded"],childList:!0,subtree:!0}),this._reanchoringMaxWait=n??3e3,this._banner=new Qi,this._checkForSelectableText(),this._sideBySideActive=!1,this._updateAnnotationLayerVisibility=()=>{const t=o.getSelection();this._pdfViewer.viewer.classList.toggle("is-selecting",!t.isCollapsed)},this._listeners=new mt,
138
- this._listeners.add(document,"selectionchange",this._updateAnnotationLayerVisibility),this._destroyed=!1,this._features=e,this._features.on("flagsChanged",(()=>{this.emit("supportedToolsChanged",this.supportedTools())})),this._pdfViewer.viewer.addEventListener("click",(t=>{const e=t.target;e instanceof HTMLAnchorElement&&(e.target="blank");no(t.clientX,t.clientY).length>0&&t.preventDefault()}))}destroy(){this.fitSideBySide({expanded:!1,width:0,toolbarWidth:0,height:window.innerHeight}),this._listeners.removeAll(),this._pdfViewer.viewer.classList.remove("has-transparent-text-layer"),this._observer.disconnect(),this._banner.destroy(),this._destroyed=!0,super.destroy()}uri(){return this._pdfMetadata.getUri()}getMetadata(){return this._pdfMetadata.getMetadata()}showContentInfo(t){this._banner.setContentInfo(t)}anchor(t,e){return Ii(e)}getAnnotatableRange(t){try{const e=Vn.trimmedRange(t);if(function(t){try{return Bi(t),!0}catch{return!1}}(e))return e}catch(t){if(!(t instanceof RangeError))throw t}return null}
139
- canStyleClusteredHighlights(){return!0}describe(t,e){return e instanceof Range?Fi(e):Vi(e)}async _checkForSelectableText(){try{await this.uri()}catch{return}if(!this._destroyed)try{const t=await async function(){const t=Si();let e=!1;for(let n=0;n<t.pagesCount;n++)if((await Mi(n)).trim().length>0){e=!0;break}return e}();this._banner.showNoTextWarning(!t)}catch(t){console.warn("Unable to check for text in PDF:",t)}}_update(){const t=[],e=this._pdfViewer.pagesCount;for(let t=0;t<e;t++){const e=this._pdfViewer.getPageView(t);if(e?.textLayer&&Ti(e.textLayer))switch(e.renderingState){case yi.INITIAL:e.textLayer=null;break;case yi.FINISHED:n=e.div,n.querySelector(Un)?.remove()}}var n;for(const e of this._annotator.anchors)if(e.highlights){if(t.includes(e.annotation))continue;for(let n=0;n<e.highlights.length;n++){const o=e.highlights[n];if(!document.body.contains(o)){e.highlights.splice(n,1),delete e.region,t.push(e.annotation);break}}}t.map((t=>this._annotator.anchor(t)))}contentContainer(){
140
- return document.querySelector("#viewerContainer")}fitSideBySide(t){const e=window.innerWidth-t.width,n=t.expanded&&e>=680,o=n?t.width:t.toolbarWidth;this._pdfContainer.style.width=`calc(100% - ${o}px)`;const i=this._pdfViewer.currentScaleValue;return"auto"!==i&&"page-fit"!==i&&"page-width"!==i||(this._pdfViewer.currentScaleValue=i),this._pdfViewer.update(),this._sideBySideActive=n,n}sideBySideActive(){return this._sideBySideActive}supportedTools(){const t=this._features?.flagEnabled("pdf_image_annotation");return t?["selection","rect","point"]:["selection"]}async scrollToAnchor(t){const e=t.annotation,n=Yi(t),o=this._anchorOffset(t);if(null!==o&&(await si(this.contentContainer(),o),n)){const t=await this._waitForAnnotationToBeAnchored(e,this._reanchoringMaxWait);if(!t)return;const n=this._anchorOffset(t);if(null===n)return;await si(this.contentContainer(),n)}}async _waitForAnnotationToBeAnchored(t,e){const n=Date.now();let o;do{o=this._annotator.anchors.find((e=>e.annotation===t)),o&&!Yi(o)||(o=null,
141
- await Gi(20))}while(!o&&Date.now()-n<e);return o??null}_anchorOffset(t){if(!t.highlights)return null;const e=t.highlights[0];return function(t,e,n={}){let o=0,i=e;for(;i!==t&&t.contains(i);)o+=i.offsetTop,i=i.offsetParent;if("center"===n.position){const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();o-=n.height/2-i.height/2}return o}(this.contentContainer(),e,{position:"center"})}async renderToBitmap(t,e){const n=t.target.selector?.find((t=>"ShapeSelector"===t.type)),o=t.target.selector?.find((t=>"PageSelector"===t.type));if(!o||!n)throw new Error("Can only render bitmaps for anchors with shapes");const i=this._pdfViewer.getPageView(o.index);if(!i)throw new Error("Failed to get page view");let r,s,a,l;switch(n.shape.type){case"rect":({left:r,right:s,top:a,bottom:l}=n.shape);break;case"point":{const{x:t,y:e}=n.shape,[o,,c]=i.pdfPage.view,h=.1*Math.abs(c-o);r=t-h,a=e+h,s=t+h,l=e-h}break;default:throw new Error("Unsupported shape type")}s<r&&([r,s]=[s,r]),s=Math.max(s,r+1),a<l&&([a,l]=[l,a]),
142
- a=Math.max(a,l+1);const c=i.pdfPage.rotate%360;if(c%90!=0)throw new Error("Page rotation is not a multiple of 90 degrees");let h,d;0===c||180===c?(h=Math.abs(s-r),d=Math.abs(l-a)):(h=Math.abs(l-a),d=Math.abs(s-r));const u=96/72,f=e.devicePixelRatio??1,p=h*u*f,g=h/d,_="number"==typeof e.maxWidth?Math.min(e.maxWidth,p):p,m=_/g,b=i.pdfPage.getViewport({scale:1}),y=_/p*u*f,w=new(0,b.constructor)({rotation:c,scale:y,userUnit:b.userUnit,viewBox:[r,l,s,a]}),v=Math.max(_,1),x=Math.max(m,1),C=new OffscreenCanvas(v,x),S=C.getContext("2d"),A=i.pdfPage.render({canvasContext:S,viewport:w});if(await A.promise,"point"===n.shape.type){S.save(),S.scale(y,y);const t=n.shape.x-r,e=n.shape.y-l,o=5;S.strokeStyle="black",S.fillStyle="yellow",S.beginPath(),S.arc(t,e,o,0,2*Math.PI),S.fill(),S.stroke(),S.restore()}return C.transferToImageBitmap()}}function Zi(t){if(!t.includes("["))return t;let e="",n=!1,o=!1;for(const i of t)n||"^"!==i?(n||"["!==i?!n&&o&&"]"===i?o=!1:o||(e+=i):o=!0,n=!1):n=!0;return e}function tr(t){
143
- const e=Zi(t),n=e.indexOf("!");return-1===n?e:e.slice(0,n)}class er{constructor(t,e,n){this._element=t,this._onFrameAdded=e,this._onFrameRemoved=n,this._annotatableFrames=new Set,this._isDisconnected=!1,this._mutationObserver=new MutationObserver(fi((()=>{this._discoverFrames()}),40)),this._discoverFrames(),this._mutationObserver.observe(this._element,{childList:!0,subtree:!0,attributeFilter:["enable-annotation"]})}disconnect(){this._isDisconnected=!0,this._mutationObserver.disconnect()}async _addFrame(t){this._annotatableFrames.add(t);try{if(await nr(t),this._isDisconnected)return;t.contentWindow.addEventListener("unload",(()=>{this._removeFrame(t)})),this._onFrameAdded(t)}catch{console.warn(`Unable to inject the Hypothesis client (from '${document.location.href}' into a cross-origin frame '${t.src}')`)}}_removeFrame(t){this._annotatableFrames.delete(t),this._onFrameRemoved(t)}_discoverFrames(){const t=new Set(this._element.querySelectorAll("iframe[enable-annotation]"))
144
- ;for(const e of t)this._annotatableFrames.has(e)||this._addFrame(e);for(const e of this._annotatableFrames)t.has(e)||this._removeFrame(e)}}function nr(t){return new Promise(((e,n)=>{const o=or(t,((t,i)=>{o(),i?e(i):n(t)}))}))}function or(t,e,{pollInterval:n=10}={}){let o,i;const r=new WeakSet,s=()=>{clearTimeout(o),o=void 0},a=()=>{const n=t.contentDocument;if(n){if(!r.has(n)){if(r.add(n),s(),!function(t){return"about:blank"===t.contentDocument?.location.href&&t.hasAttribute("src")&&"about:blank"!==t.src}(t)){"interactive"===n.readyState||"complete"===n.readyState?e(null,n):n.addEventListener("DOMContentLoaded",(()=>e(null,n)))}t.contentDocument&&t.contentWindow?.addEventListener("unload",i)}}else{s();const n=t.isConnected?"Frame is cross-origin":"Frame is disconnected";e(new Error(n))}};let l=!1;i=()=>{s(),l||(o=setInterval(a,n))},t.addEventListener("load",a);const c=setTimeout(a,0);return()=>{l=!0,clearTimeout(c),s(),t.removeEventListener("load",a)}}class ir{constructor(t,e){this._config=e,
145
- this._frameObserver=new er(t,(t=>rr(t,e)),(()=>{}))}destroy(){this._frameObserver.disconnect()}}async function rr(t,e,n){if(null!==t.contentDocument.querySelector("script.js-hypothesis-config"))return;await nr(t);const{assetRoot:o,notebookAppUrl:i,profileAppUrl:r,sidebarAppUrl:s}=He(document),a={...e,assetRoot:o,notebookAppUrl:i,profileAppUrl:r,sidebarAppUrl:s,subFrameIdentifier:n??Ce(10)},l=document.createElement("script");l.className="js-hypothesis-config",l.setAttribute("data-remove-on-unload",""),l.type="application/json",l.innerText=JSON.stringify(a);const c=document.createElement("script");c.async=!0,c.src=e.clientUrl;const h=t.contentDocument;h.body.appendChild(l),h.body.appendChild(c)}class sr{constructor(t,e,n){if(e.length!==n.length)throw new Error("Char boxes length does not match text length");const o=t.parentNode,i=document.createElement("hypothesis-text-layer");o.insertBefore(i,t.nextSibling),o.style.position="relative",i.style.position="absolute",i.style.top="0",i.style.left="0",
146
- i.style.color="transparent",i.style.textAlign="left",i.style.mixBlendMode="multiply";const r="sans-serif";i.style.fontSize="16px",i.style.fontFamily=r;const s=document.createElement("canvas").getContext("2d");s.font=`16px ${r}`;const a=(t,e,n="px")=>`calc(var(--${t}-scale) * ${e}${n})`,l=function(t,e){const n=[];let o={text:"",rect:new DOMRect};const i=()=>{o.text.length>0&&(n.push(o),o={text:"",rect:new DOMRect})};for(const[n,r]of t.entries()){const t=e[n],s=/\s/.test(t);o.text.length>0&&!qe(o.rect,r)&&i(),o.rect=je(o.rect,r),o.text+=s?" ":t,s&&i()}i();const r=[];let s={words:[],rect:new DOMRect};const a=()=>{s.words.length>0&&(r.push(s),s={words:[],rect:new DOMRect})};for(const t of n){const e=s.words[s.words.length-1];if(e){const n=Ke(e.rect),o=Ke(t.rect).x-n.x;(!qe(e.rect,t.rect)||o<0)&&a()}s.words.push(t),s.rect=je(s.rect,t.rect)}a();const l=[];let c={lines:[],rect:new DOMRect};const h=()=>{c.lines.length>0&&(l.push(c),c={lines:[],rect:new DOMRect})};for(const t of r){const e=c.lines[c.lines.length-1]
147
- ;if(e){const n=Ke(e.rect),o=Ke(t.rect).y-n.y;(!We(e.rect,t.rect)||qe(e.rect,t.rect)||o<0||o>4*t.rect.height)&&h()}c.lines.push(t),c.rect=je(c.rect,t.rect)}return h(),l}(e,n);for(const t of l){const e=document.createElement("hypothesis-text-column");e.style.display="block",e.style.position="absolute",e.style.left=a("x",t.rect.left),e.style.top=a("y",t.rect.top);let n=null;for(const o of t.lines){const i=document.createElement("hypothesis-text-line");i.style.display="block",i.style.marginLeft=a("x",o.rect.left-t.rect.left),i.style.height=a("y",o.rect.height),n&&(i.style.marginTop=a("y",o.rect.top-n.rect.bottom)),n=o,i.style.whiteSpace="nowrap";let r=null;for(const t of o.words){const e=document.createElement("hypothesis-text-word");e.style.display="inline-block",e.style.transformOrigin="top left",e.textContent=t.text,r&&(e.style.marginLeft=a("x",t.rect.left-r.rect.right)),r=t,e.style.width=a("x",t.rect.width),e.style.height=a("y",t.rect.height),e.style.whiteSpace="pre"
148
- ;const n=s.measureText(t.text),o=a("x",t.rect.width/n.width,""),l=a("y",t.rect.height/16,"");e.style.transform=`scale(${o}, ${l})`,i.append(e)}e.append(i)}i.append(e)}const c=()=>{const{width:e,height:n}=t.getBoundingClientRect();i.style.width=e+"px",i.style.height=n+"px",i.style.setProperty("--x-scale",`${e}`),i.style.setProperty("--y-scale",`${n}`)};c(),this.container=i,this._updateTextLayerSize=fi(c,{maxWait:50}),this._listeners=new mt,"undefined"!=typeof ResizeObserver&&(this._imageSizeObserver=new ResizeObserver((()=>{this._updateTextLayerSize()})),this._imageSizeObserver.observe(t)),this._listeners.add(window,"resize",this._updateTextLayerSize)}updateSync(){this._updateTextLayerSize(),this._updateTextLayerSize.flush()}destroy(){this.container.remove(),this._listeners.removeAll(),this._updateTextLayerSize.cancel(),this._imageSizeObserver?.disconnect()}}function ar(t=document){return t.querySelector("mosaic-book")}function lr(t=window){if(ar(t.document))return"container"
149
- ;const e=t.frameElement?.ownerDocument;return e&&ar(e)?"content":null}class cr{constructor(t){const e=ar();if(!e)throw new Error("Book container element not found");const n=new WeakSet,o=e.shadowRoot,i=()=>{const e=o.querySelector("iframe");e&&!n.has(e)&&(n.add(e),or(e,((n,o)=>{if(n)return;const i=o.body;i&&!i.querySelector("#page-content")&&rr(e,t,"vitalsource-content")})))};i(),this._frameObserver=new MutationObserver(i),this._frameObserver.observe(o,{childList:!0,subtree:!0})}destroy(){this._frameObserver.disconnect()}}function hr(){return document.querySelector("img#pbk-page")}class dr extends Me{constructor(t=document.body,e={}){super();const n=e.bookElement??ar(window.parent.document);if(!n)throw new Error("Failed to find <mosaic-book> element in container frame");this._bookElement=n;const o=new ko;this._htmlIntegration=new ci({container:t,features:o}),this._listeners=new mt;const i=["mouseup","mousedown","mouseout"];for(const t of i)this._listeners.add(document.documentElement,t,(t=>{
150
- t.stopPropagation()}));const r=window.frameElement;r&&function(t){if("no"!==t.getAttribute("scrolling"))return;const e=document.createElement("style");e.textContent="iframe { height: 100% !important; }",t.insertAdjacentElement("beforebegin",e);const n=()=>t.removeAttribute("scrolling");n(),new MutationObserver(n).observe(t,{attributes:!0})}(r);const s=hr(),a=window.innerPageData;if(s&&a){const t=a.glyphs.glyphs.map((t=>{const e=t.l/100,n=t.r/100,o=t.t/100,i=t.b/100;return new DOMRect(e,o,n-e,i-o)}));this._textLayer=new sr(s,t,a.words),this._textLayer.container.style.zIndex="100",this._sideBySideActive=!1}}getAnnotatableRange(t){return this._htmlIntegration.getAnnotatableRange(t)}destroy(){this._textLayer&&(this._textLayer.destroy(),this.fitSideBySide({expanded:!1,height:window.innerHeight,width:0,toolbarWidth:0})),this._listeners.removeAll(),this._htmlIntegration.destroy(),super.destroy()}anchor(t,e){return this._htmlIntegration.anchor(t,e)}async describe(t,e){
151
- const n=this._htmlIntegration.describe(t,e),{cfi:o,index:i,page:r,title:s,url:a}=await this._getPageInfo({includeTitle:!0,includePageIndex:!0}),l=[{type:"EPUBContentSelector",cfi:o,url:a,title:s}];if("number"==typeof i){const t={type:"PageSelector",index:i,label:r};l.push(t)}return n.push(...l),n}contentContainer(){return this._htmlIntegration.contentContainer()}fitSideBySide(t){const e=hr();if(e&&this._textLayer){const n=e.parentElement,o=this._textLayer,i=window.innerWidth-t.width;return this._sideBySideActive=!1,on((()=>{t.expanded&&i>480?(n.style.textAlign="left",e.style.width=`${i}px`,this._sideBySideActive=!0):(n.style.textAlign="",e.style.width=""),o.updateSync()})),this._sideBySideActive}return this._htmlIntegration.fitSideBySide(t)}sideBySideActive(){return"boolean"==typeof this._sideBySideActive?this._sideBySideActive:this._htmlIntegration.sideBySideActive()}supportedTools(){return["selection"]}async getMetadata(){return{title:this._bookElement.getBookInfo().title,link:[]}}navigateToSegment(t){
152
- const e=t.target[0].selector?.find((t=>"EPUBContentSelector"===t.type));if(e?.cfi)this._bookElement.goToCfi(e.cfi);else{if(!e?.url)throw new Error("No segment information available");this._bookElement.goToURL(function(t){const e=new URL(t,document.baseURI);return e.pathname+e.search}(e.url))}}persistFrame(){return!0}async _getPageInfo({includeTitle:t=!1,includePageIndex:e=!1}={}){const[n,o,i]=await Promise.all([this._bookElement.getCurrentPage(),t?this._bookElement.getTOC():void 0,e?this._bookElement.getPages():void 0]),r=["absoluteURL","cfi"];for(const t of r)if(!(t in n))throw new Error(`Page metadata field "${t}" is missing`);let s;if(o){s=n.chapterTitle;const t=tr(n.cfi),e=o.data?.find((e=>tr(e.cfi)===t));e&&(s=e.title)}let a=n.index;if(void 0===a&&i){const t=i.data?.findIndex((t=>t.cfi===n.cfi));-1!==t&&(a=t)}return{cfi:n.cfi,index:a,page:n.page,title:s,url:new URL(n.absoluteURL,document.baseURI).toString()}}async _getPageRange(t){let e=[];try{const t=await this._bookElement.getPageBreaks()
153
- ;t.ok&&t.data&&(e=t.data)}catch(t){console.error("Failed to get page breaks",t)}const n=Zi(t),o=e.filter((t=>t.cfiWithoutAssertions.split("!")[0]===n));let i;if(o.length>0){i={start:o[0].label,end:o[o.length-1].label}}return i}async segmentInfo(){const{cfi:t,url:e}=await this._getPageInfo();return{cfi:t,pages:await this._getPageRange(t),url:e}}async uri(){const t=this._bookElement.getBookInfo().isbn;if(!t)throw new Error("Unable to get book ID from VitalSource");return`https://bookshelf.vitalsource.com/reader/books/${t}`}async scrollToAnchor(t){return this._htmlIntegration.scrollToAnchor(t)}}function ur(t){if(void 0!==window.PDFViewerApplication)return new Ji({annotator:t,features:t.features});return"content"===lr()?new dr(document.body):new ci({features:t.features,sideBySideOptions:t.sideBySide})}function fr(){return St(_e,{classes:"fixed left-[10px] top-[10px]","data-testid":"outside-assignment-notice",status:"notice",variant:"raised",
154
- children:"You are outside the page range for this assignment. Annotations made here may not be counted."})}class pr{constructor(t){this._visible=!1,this._container=new En("notice",(()=>this._render())),t.appendChild(this._container.element)}destroy(){this._container.destroy()}setVisible(t){this._visible=t,this._container.render()}_render(){return this._visible?St(fr,{}):null}}class gr{constructor(t,e=document){let n=!1;this._pendingCallback=null;const o=(n=10)=>{this._pendingCallback=setTimeout((()=>{t(Wn(e.getSelection()))}),n)},i=t=>{if("mousedown"===t.type&&(n=!0),"mouseup"===t.type&&(n=!1),n)return;this._cancelPendingCallback();const e="mouseup"===t.type?10:100;o(e)};this._document=e,this._listeners=new mt,this._listeners.add(e,"selectionchange",i),this._listeners.add(e.body,"mousedown",i),this._listeners.add(e.body,"mouseup",i),o(1)}disconnect(){this._listeners.removeAll(),this._cancelPendingCallback()}_cancelPendingCallback(){this._pendingCallback&&(clearTimeout(this._pendingCallback),
155
- this._pendingCallback=null)}}function _r(t,e){if(t===e)return!0;if(t.parent!==e)return!1;if(!t.frameElement)return!1;return t.frameElement.getBoundingClientRect().width/t.parent.innerWidth>=.8}function mr(){return function(t,e){const n=new Set,o=new Set;return Xn(t,(t=>{for(;t&&!n.has(t);){n.add(t);const i=e(t);null!=i&&o.add(i),t=t.parentNode}})),[...o]}(Wn()??new Range,(t=>t._annotation?.$tag))}function br(t,e,n){return t.getHighlightsFromPoint(e,n).map((t=>t._annotation?.$tag)).filter((t=>void 0!==t))}function yr(t){if(!t.region)return null;if(!function(t){return void 0!==t&&"toRange"in t&&"function"==typeof t.toRange}(t.region))return t.region;try{return t.region.toRange()}catch{return null}}function wr(){document.getSelection()?.removeAllRanges()}class vr extends CustomEvent{constructor(t){super("scrolltorange",{bubbles:!0,cancelable:!0,detail:t}),this._ready=null}get ready(){return this._ready}waitUntil(t){this._ready=t}}class xr extends Me{constructor(t,e={},n=window){super(),this.element=t,
156
- this._contentReady=e.contentReady,this._commentsMode=e.commentsMode??!1,this._hostFrame=n,this._highlightsVisible=!1,this._isAdderVisible=!1,this._informHostOnNextSelectionClear=!0,this.selectedRanges=[],this._outsideAssignmentNotice=null,this._highlighter=new Jn(this.element),this._adder=new Nn(this.element,{onAnnotate:()=>this.createAnnotationFromSelection(),onHighlight:()=>this.createAnnotationFromSelection({highlight:!0}),onShowAnnotations:t=>this.selectAnnotations(t,{focusInSidebar:!0})}),this._drawTool=new vo(this.element),this._drawTool.setOnKeyboardModeChange((t=>{this._hostRPC.call("keyboardModeChanged",t)})),this._setupGlobalKeyboardListener(),this._selectionObserver=new gr((t=>{t?this._onSelection(t):this._onClearSelection()})),this.anchors=[],this._annotations=new Set,this._frameIdentifier=e.subFrameIdentifier||null,this._portFinder=new ke({hostFrame:this._hostFrame,source:"guest",sourceId:this._frameIdentifier??void 0}),this.features=new ko,this._featureFlagsReceived=new Promise((t=>{
157
- this.features.on("flagsChanged",t)})),this.sideBySide=e.sideBySide,this._integration=ur(this),this._integration.on("uriChanged",(()=>this._sendDocumentInfo())),e.contentInfoBanner&&this._integration.showContentInfo?.(e.contentInfoBanner),this._integration.canStyleClusteredHighlights?.()&&(this._clusterToolbar=new To(this._integration.contentContainer(),{features:this.features})),this._integration.on("supportedToolsChanged",(()=>this._notifySupportedToolsChanged())),this._hostRPC=new De,this._connectHost(n),this._sidebarRPC=new De,this._sidebarLayout=null,this._connectSidebar(),this._bucketBarClient=new co({contentContainer:this._integration.contentContainer(),hostRPC:this._hostRPC}),this._listeners=new mt,this._setupElementEvents(),this._hoveredAnnotations=new Set}_sideBySideActive(){return"manual"===this.sideBySide?.mode&&this.sideBySide.isActive?this.sideBySide.isActive():this._integration.sideBySideActive()}_setupElementEvents(){this._listeners.add(this.element,"mouseup",(t=>{
158
- if(!document.getSelection()?.isCollapsed)return;const{clientX:e,clientY:n,metaKey:o,ctrlKey:i}=t,r=br(this._highlighter,e,n);if(r.length){const t=o||i;this.selectAnnotations(r,{toggle:t})}})),this._listeners.add(this.element,"pointerdown",(t=>{this._sideBySideActive()||t.composedPath().some((t=>t instanceof Element&&t.localName.startsWith("hypothesis-")))||br(this._highlighter,t.clientX,t.clientY).length||_r(window,this._hostFrame)&&this._sidebarLayout?.expanded&&window.innerWidth-t.clientX<this._sidebarLayout.width||this._sidebarRPC.call("closeSidebar")})),this._listeners.add(this.element,"mouseover",(({clientX:t,clientY:e})=>{const n=br(this._highlighter,t,e);n.length&&this._sidebarRPC.call("hoverAnnotations",n)})),this._listeners.add(this.element,"mouseout",(()=>{this._highlightsVisible&&this._sidebarRPC.call("hoverAnnotations",[])})),this._listeners.add(this.element,"keydown",(t=>{this._handleShortcut(t)})),this._listeners.add(window,"resize",(()=>this._repositionAdder()))}async getDocumentInfo(){
159
- const[t,e,n]=await Promise.all([this._integration.uri(),this._integration.getMetadata(),this._integration.segmentInfo?.()]);return{uri:ai(t),metadata:e,segmentInfo:n,persistent:this._integration.persistFrame?.()??!1}}async _sendDocumentInfo(){this._integration.waitForFeatureFlags?.()&&await this._featureFlagsReceived;const t=await this.getDocumentInfo();this._sidebarRPC.call("documentInfoChanged",t)}_repositionAdder(){if(!this._isAdderVisible)return;const t=Wn();t&&this._onSelection(t)}async _connectHost(t){this._hostRPC.on("clearSelection",(()=>{Wn()&&(this._informHostOnNextSelectionClear=!1,wr())})),this._hostRPC.on("createAnnotation",(({tool:t})=>t?("rect"===t&&void 0===this._pendingKeyboardMode&&(this._pendingKeyboardMode="move"),this.createAnnotation(t)):(this._drawTool.cancel(),null))),this._hostRPC.on("hoverAnnotations",(t=>this._hoverAnnotations(t))),this._hostRPC.on("scrollToAnnotation",(t=>{this._scrollToAnnotation(t)})),this._hostRPC.on("selectAnnotations",((t,e)=>this.selectAnnotations(t,{toggle:e
160
- }))),this._hostRPC.on("setKeyboardMode",(({mode:t})=>{["move","resize","rect"].includes(t)&&this._drawTool.setKeyboardMode(t)})),this._hostRPC.on("activateMoveMode",(()=>{this._activateToolWithMoveMode("rect")})),this._hostRPC.on("activatePointMoveMode",(()=>{this._activateToolWithMoveMode("point")})),this._hostRPC.on("sidebarLayoutChanged",(e=>{_r(window,t)&&this.fitSideBySide(e),this.element.dispatchEvent(new xo({sidebarLayout:e,sideBySideActive:this._sideBySideActive()}))})),this._hostRPC.on("close",(()=>this.emit("hostDisconnected"))),this._notifySupportedToolsChanged();const e=await this._portFinder.discover("host");this._hostRPC.connect(e)}_notifySupportedToolsChanged(){this._hostRPC.call("supportedToolsChanged",this._integration.supportedTools())}async _scrollToAnchor(t){const e=yr(t);if(!e)return;let n;e instanceof Range?n=e:(n=new Range,n.selectNodeContents(e.anchor));const o=new vr(n);this.element.dispatchEvent(o)&&(await o.ready,await this._integration.scrollToAnchor(t))}
161
- async _scrollToAnnotation(t){const e=this.anchors.find((e=>e.annotation.$tag===t));e?.highlights&&await this._scrollToAnchor(e)}async _connectSidebar(){this._sidebarRPC.on("featureFlagsUpdated",(t=>this.features.update(t))),this._sidebarRPC.on("shortcutsUpdated",(t=>{yn(t)})),this._sidebarRPC.on("hoverAnnotations",(t=>this._hoverAnnotations(t))),this._sidebarRPC.on("scrollToAnnotation",(t=>{this._scrollToAnnotation(t)})),this._sidebarRPC.on("setHighlightsVisible",(t=>{this.setHighlightsVisible(t,!1)})),this._sidebarRPC.on("deleteAnnotation",(t=>this.detach(t))),this._sidebarRPC.on("getDocumentInfo",(async t=>t(await this.getDocumentInfo()))),this._sidebarRPC.on("loadAnnotations",(async t=>{try{await Promise.all(t.map((t=>this.anchor(t))))}catch(t){console.warn("Failed to anchor annotations:",t)}})),this._sidebarRPC.on("showContentInfo",(t=>this._integration.showContentInfo?.(t))),this._sidebarRPC.on("setOutsideAssignmentNoticeVisible",(t=>{this._setOutsideAssignmentNoticeVisible(t)})),
162
- this._sidebarRPC.on("navigateToSegment",(t=>this._integration.navigateToSegment?.(t))),this._sidebarRPC.on("renderThumbnail",((t,e,n)=>{(async()=>{if(!this._integration.renderToBitmap)throw new Error("Thumbnail rendering not supported for document type");const n=this.anchors.find((e=>e.annotation.$tag===t));if(!n)throw new Error("Annotation not anchored in guest");return this._integration.renderToBitmap(n,e)})().then((t=>n({ok:!0,value:t}))).catch((t=>n({ok:!1,error:t.message})))})),this._portFinder.discover("sidebar").then((t=>{this._sidebarRPC.connect(t)})),this._sendDocumentInfo()}destroy(){this._drawTool.destroy(),this._portFinder.destroy(),this._hostRPC.destroy(),this._sidebarRPC.destroy(),this._listeners.removeAll(),this._selectionObserver.disconnect(),this._adder.destroy(),this._bucketBarClient.destroy(),this._clusterToolbar?.destroy(),this._outsideAssignmentNotice?.destroy(),this._highlighter.removeAllHighlights(),this._integration.destroy(),this._globalKeyboardListenerCleanup?.(),super.destroy()}
163
- _isKeyboardAnnotationModeEnabled(){return this.features.flagEnabled("vpat_keyboard")}_setupGlobalKeyboardListener(){const t=t=>{if(Ge(t.target))return;if(!this._isKeyboardAnnotationModeEnabled())return;const e=bn(),n=this._integration.supportedTools(),o=n.includes("rect"),i=n.includes("point"),r=e.activateRectMove;if(r&&un(t,r)&&o){t.preventDefault(),t.stopPropagation();return void(this._drawTool.getKeyboardModeState().keyboardActive?this._drawTool.setKeyboardMode("move"):(this._pendingKeyboardMode="move",this.createAnnotation("rect").catch((()=>{this._pendingKeyboardMode=void 0}))))}const s=e.activateRectResize;if(s&&un(t,s)&&o){t.preventDefault(),t.stopPropagation();return void(this._drawTool.getKeyboardModeState().keyboardActive?this._drawTool.setKeyboardMode("resize"):(this._pendingKeyboardMode="resize",this.createAnnotation("rect").catch((()=>{this._pendingKeyboardMode=void 0}))))}const a=e.activatePoint;if(a&&un(t,a)&&i){t.preventDefault(),t.stopPropagation()
164
- ;this._drawTool.getKeyboardModeState().keyboardActive||(this._pendingKeyboardMode="move",this.createAnnotation("point").catch((()=>{this._pendingKeyboardMode=void 0})))}else;};document.body.addEventListener("keydown",t),this._globalKeyboardListenerCleanup=()=>{document.body.removeEventListener("keydown",t)}}async anchor(t){this._contentReady&&(await this._contentReady,this._contentReady=void 0);const e=t=>{const e=yr(t);if(!e)return;let n;n=e instanceof Range?this._highlighter.highlightRange(e,t.annotation?.$cluster):this._highlighter.highlightShape(e),n.forEach((e=>{e._annotation=t.annotation})),t.highlights=n,this._hoveredAnnotations.has(t.annotation.$tag)&&this._highlighter.setHighlightsFocused(n,!0)};this.detach(t.$tag,!1),this._annotations.add(t.$tag),t.target||(t.target=[]);const n=await Promise.all(t.target.map((async e=>{if(!e.selector||!e.selector.some((t=>"TextQuoteSelector"===t.type||"ShapeSelector"===t.type)))return{annotation:t,target:e};let n;try{
165
- const o=await this._integration.anchor(this.element,e.selector);if(o instanceof Range){const i=Vn.fromRange(o);n={annotation:t,target:e,region:i}}else n={annotation:t,target:e,region:o}}catch{n={annotation:t,target:e}}return n})));if(!this._annotations.has(t.$tag))return[];for(const t of n)e(t);return t.$orphan=n.length>0&&n.every((t=>t.target.selector&&!t.region)),this._updateAnchors(this.anchors.concat(n),!0),this._sidebarRPC.call("syncAnchoringStatus",t),n}detach(t,e=!0){this._annotations.delete(t);const n=[];for(const e of this.anchors)e.annotation.$tag!==t?n.push(e):e.highlights&&this._highlighter.removeHighlights(e.highlights);this._updateAnchors(n,e)}_updateAnchors(t,e){this.anchors=t,this._clusterToolbar?.scheduleClusterUpdates(),e&&this._bucketBarClient.update(this.anchors)}async createAnnotation(t){if("selection"===t)return this.createAnnotationFromSelection();if(!["rect","point"].includes(t))throw new Error("Unsupported annotation tool");{let e=!1;try{this._hostRPC.call("activeToolChanged",t)
166
- ;const e=this._pendingKeyboardMode;this._pendingKeyboardMode=void 0;const n=await this._drawTool.draw(t,e),o=await this.getDocumentInfo(),i=[{source:o.uri,selector:await this._integration.describe(this.element,n)}],r={uri:o.uri,document:o.metadata,target:i,$tag:"a:"+Ce(8)};return this._sidebarRPC.call("createAnnotation",r),this.anchor(r),r}catch(t){if(t instanceof wo&&["canceled","restarted"].includes(t.kind))return e="restarted"===t.kind,null;throw t}finally{e||this._hostRPC.call("activeToolChanged",null)}}}_activateToolWithMoveMode(t){this._drawTool.getKeyboardModeState().keyboardActive?this._drawTool.setKeyboardMode("move"):(this._pendingKeyboardMode="move",this.createAnnotation(t).catch((()=>{this._pendingKeyboardMode=void 0})))}async createAnnotationFromSelection({highlight:t=!1}={}){const e=this.selectedRanges;this.selectedRanges=[];const n=await this.getDocumentInfo(),o=this.element,i=(await Promise.all(e.map((t=>this._integration.describe(o,t))))).map((t=>({source:n.uri,selector:t}))),r={uri:n.uri,
167
- document:n.metadata,target:i,$highlight:t,$cluster:t?"user-highlights":"user-annotations",$tag:"a:"+Ce(8)};return this._sidebarRPC.call("createAnnotation",r),this.anchor(r),wr(),r}_hoverAnnotations(t){this._hoveredAnnotations.clear(),t.forEach((t=>this._hoveredAnnotations.add(t)));for(const e of this.anchors)if(e.highlights){const n=t.includes(e.annotation.$tag);this._highlighter.setHighlightsFocused(e.highlights,n)}this._sidebarRPC.call("hoverAnnotations",t)}_onSelection(t){const e=this._integration.getAnnotatableRange(t);if(!e)return void this._onClearSelection();const n=document.getSelection(),o=jn(n),i=Yn(n);i?(this.selectedRanges=[e],this._hostRPC.call("textSelected"),this._commentsMode||(this._adder.annotationsForSelection=mr(),this._isAdderVisible=!0,this._adder.show(i,o))):this._onClearSelection()}_onClearSelection(){this._isAdderVisible=!1,this._adder.hide(),this.selectedRanges=[],this._informHostOnNextSelectionClear&&this._hostRPC.call("textUnselected"),this._informHostOnNextSelectionClear=!0}
168
- selectAnnotations(t,{toggle:e=!1,focusInSidebar:n=!1}={}){e?this._sidebarRPC.call("toggleAnnotationSelection",t):this._sidebarRPC.call("showAnnotations",t,n),this._sidebarRPC.call("openSidebar")}setHighlightsVisible(t,e=!0){this._highlighter.setHighlightsVisible(t),this._highlightsVisible=t,e&&this._hostRPC.call("highlightsVisibleChanged",t)}get highlightsVisible(){return this._highlightsVisible}fitSideBySide(t){this._sidebarLayout=t,this._integration.fitSideBySide(t)}get hoveredAnnotationTags(){return this._hoveredAnnotations}_handleShortcut(t){const e=bn().toggleHighlights;e&&un(t,e)&&this.setHighlightsVisible(!this._highlightsVisible&&!this._commentsMode)}_setOutsideAssignmentNoticeVisible(t){this._outsideAssignmentNotice||(this._outsideAssignmentNotice=new pr(this.element)),this._outsideAssignmentNotice.setVisible(t)}}function Cr(t,e){const n=new URL(t),o=new URLSearchParams;return o.append("config",JSON.stringify(e)),n.hash=o.toString(),n.toString()}function Sr(t,e){const n={}
169
- ;for(const[t,o]of Object.entries(e))"notebookAppUrl"!==t&&"sidebarAppUrl"!==t&&null!=o&&(n[t]=o);n.origin=new URL(t).origin,n.version="1.1747.0";const o=new URL(window.location.href);if(o.hash="",n.hostURL=o.toString(),Array.isArray(n.services)&&n.services?.length>0){const t=n.services[0];t.onLoginRequest&&(t.onLoginRequestProvided=!0),t.onLogoutRequest&&(t.onLogoutRequestProvided=!0),t.onSignupRequest&&(t.onSignupRequestProvided=!0),t.onProfileRequest&&(t.onProfileRequestProvided=!0),t.onHelpRequest&&(t.onHelpRequestProvided=!0)}return n}function Ar({closed:t,onClose:e,children:n,className:o,"data-testid":i,"aria-label":r}){const s=it(null);return nt((()=>{t?s.current?.close():s.current?.showModal()}),[t]),nt((()=>{const t=s.current;return t?.addEventListener("cancel",e),()=>{t?.removeEventListener("cancel",e)}}),[e]),St("dialog",{ref:s,className:Tt("relative m-5 w-full h-full backdrop:bg-black/50",o),"data-testid":i,"aria-label":r,children:n})}function kr({closed:t,children:e,className:n,...o}){
170
- return St("div",{...o,className:Tt("fixed z-max top-0 left-0 right-0 bottom-0 p-3 bg-black/50",{hidden:t}),children:St("div",{className:Tt("relative w-full h-full",n),children:e})})}function Mr({document_:t=document,...e}){return St(rt((()=>function(t){return"function"==typeof t.createElement("dialog").showModal}(t)?Ar:kr),[t]),{...e})}function Rr({config:t,groupId:e}){return St("iframe",{title:"Hypothesis annotation notebook",className:"h-full w-full border-0",allow:"fullscreen; clipboard-write",src:Cr(t.notebookAppUrl,{...Sr(t.notebookAppUrl,t),group:e})})}function Er({eventBus:t,config:e}){const[n,o]=et(0),[i,r]=et(!0),[s,a]=et(null),l=it(""),c=it(null);nt((()=>(l.current=document.body.style.overflow,()=>{document.body.style.overflow=l.current})),[]),nt((()=>{document.body.style.overflow=i?l.current:"hidden"}),[i]),nt((()=>{const e=t.createEmitter();return e.subscribe("openNotebook",(t=>{r(!1),o((t=>t+1)),a(t)})),c.current=e,()=>{e.destroy()}}),[t]);const h=st((()=>{r(!0),
171
- c.current?.publish("closeNotebook")}),[]);return null===s?null:St(Mr,{closed:i,onClose:h,"data-testid":"notebook-outer","aria-label":"Hypothesis notebook",children:[St("div",{className:"absolute right-0 m-3",children:St(oe,{title:"Close notebook",onClick:h,variant:"dark",classes:Tt("!bg-transparent enabled:hover:!bg-grey-3"),"data-testid":"close-button",children:St(It,{className:"w-4 h-4"})})}),St(Rr,{config:e,groupId:s},n)]})}class Pr{constructor(t,e,n){this._container=new En("notebook",(()=>St(Er,{eventBus:e,config:n}))),t.append(this._container.element),this._container.render()}destroy(){this._container.destroy()}}function Tr({eventBus:t,config:e}){const[n,o]=et(!0),i=it(null);nt((()=>{const e=t.createEmitter();return e.subscribe("openProfile",(()=>{o(!1)})),i.current=e,()=>{e.destroy()}}),[t]);const r=()=>{o(!0),i.current?.publish("closeProfile")};return n?null:St(Mr,{closed:n,onClose:r,"data-testid":"profile-outer","aria-label":"Hypothesis profile",children:[St("div",{className:"absolute right-0 m-3",
172
- children:St(oe,{title:"Close profile dialog",onClick:r,variant:"dark",classes:Tt("!bg-transparent enabled:hover:!bg-grey-3"),children:St(It,{className:"w-4 h-4"})})}),St("iframe",{title:"Hypothesis profile",className:"h-full w-full border-0",src:e.profileAppUrl})]})}class Nr{constructor(t,e,n){this._container=new En("profile",(()=>St(Tr,{eventBus:e,config:n}))),t.append(this._container.element),this._container.render()}destroy(){this._container.destroy()}}function Lr({above:t,below:e,buckets:n,onFocusAnnotations:o,onScrollToAnnotation:i,onSelectAnnotations:r}){const s=t.anchors.length>0,a=e.anchors.length>0,l=t=>t.anchors.map((t=>t.tag));return St("ul",{className:"relative",children:[s&&St("li",{className:"absolute right-0 pointer-events-auto mt-[-11px]",style:{top:t.position},children:St(ve,{"data-testid":"up-navigation-button",direction:"up",onClick:()=>{const e=[...t.anchors].sort(((t,e)=>t.bottom-e.bottom)),n=e[e.length-1];i(n.tag)},onBlur:()=>o([]),onFocus:()=>o(l(t)),onMouseEnter:()=>o(l(t)),
173
- onMouseOut:()=>o([]),title:`Go up to next annotations (${t.anchors.length})`,children:t.anchors.length})}),n.map(((t,e)=>St("li",{className:"absolute right-0 pointer-events-auto mt-[-8px]",style:{top:t.position},children:St(ve,{direction:"left",onClick:e=>r(l(t),e.metaKey||e.ctrlKey),onBlur:()=>o([]),onFocus:()=>o(l(t)),onMouseEnter:()=>o(l(t)),onMouseOut:()=>o([]),title:`Select nearby annotations (${t.anchors.length})`,children:t.anchors.length})},e))),a&&St("li",{className:"absolute right-0 pointer-events-auto",style:{top:e.position},children:St(ve,{"data-testid":"down-navigation-button",direction:"down",onClick:()=>{const t=[...e.anchors].sort(((t,e)=>t.top-e.top)),n=t[0];i(n.tag)},onBlur:()=>o([]),onFocus:()=>o(l(e)),onMouseEnter:()=>o(l(e)),onMouseOut:()=>o([]),title:`Go up to next annotations (${e.anchors.length})`,children:e.anchors.length})})]})}class Or{constructor(t,{onFocusAnnotations:e,onScrollToAnnotation:n,onSelectAnnotations:o}){this._positions=[],
174
- this._container=new En("bucket-bar",(()=>this._render())),Object.assign(this._container.element.style,{display:"block",flexGrow:"1",width:"100%"}),t.appendChild(this._container.element),this._onFocusAnnotations=e,this._onScrollToAnnotation=n,this._onSelectAnnotations=o,this._container.render()}destroy(){this._container.destroy()}update(t){this._positions=t,this._container.render()}_render(){const t=function(t,e){const n=[],o=[],i=[];let r=null;function s(t){const{bottom:e,top:n}=t;return{bottom:e,position:n+(e-n)/2,anchors:[t],top:n}}const a=e.getBoundingClientRect(),l=t.map((t=>({tag:t.tag,top:t.top-a.top,bottom:t.bottom-a.top})));for(const t of l){const e=(t.top+t.bottom)/2;if(e<30){n.push(t);continue}if(e>a.height-30){o.push(t);continue}if(!r){r=s(t);continue}const l=t.top>r.top&&t.bottom<r.bottom;if(t.top-r.bottom>60&&!l)i.push(r),r=s(t);else{const e=t.bottom>r.bottom?t.bottom:r.bottom,n=e-r.top;r.anchors.push(t),r.bottom=e,r.position=r.top+n/2}}return r&&i.push(r),{above:{anchors:n,position:25},below:{
175
- anchors:o,position:a.height-30},buckets:i}}(this._positions,this._container.element);return St(Lr,{above:t.above,below:t.below,buckets:t.buckets,onFocusAnnotations:t=>this._onFocusAnnotations(t),onScrollToAnnotation:t=>this._onScrollToAnnotation(t),onSelectAnnotations:(t,e)=>this._onSelectAnnotations(t,e)})}}function Ir({emitter:t}){const[e,n]=et([]),o=st((t=>n((e=>[...e,t]))),[]),i=st((t=>n((e=>e.filter((e=>e.id!==t))))),[]);return nt((()=>(t.subscribe("toastMessageAdded",o),t.subscribe("toastMessageDismissed",i),()=>{t.unsubscribe("toastMessageAdded",o),t.unsubscribe("toastMessageDismissed",i)})),[t,i,o]),St(ye,{messages:e,onMessageDismiss:i})}function Br(t){return St("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",...t,children:[St("g",{"fill-rule":"evenodd",children:[St("path",{fill:"none",d:"M0 0h16v16H0z"}),St("path",{fill:"currentColor","clip-rule":"evenodd",
62
+ ;return"all"===t?Object.values(e).flat():e[t]}(t)){const t=cn[r],s=void 0!==t.defaultValue,a=!((i=rn(e,"sidebar","html")).startsWith("http://")||i.startsWith("https://"));if(!t.allowInBrowserExt&&a){s&&(o[r]=t.defaultValue);continue}const l=t.getValue(n,r);void 0!==l?o[r]=t.coerce?t.coerce(l):l:s&&(o[r]=t.defaultValue)}var i;return o}const dn={alt:1,ctrl:2,meta:4,shift:8};function un(t,e){if(!(t instanceof KeyboardEvent))return!1;const n=e.split("+").map((t=>t.toLowerCase()));let o=0,i=null;for(const t of n){const e=dn[t];if(e)o|=e;else{if(null!==i)throw new Error("Multiple non-modifier keys specified");i=t}}if(!i)throw new Error(`Invalid shortcut: ${e}`);return((t.ctrlKey?dn.ctrl:0)|(t.metaKey?dn.meta:0)|(t.altKey?dn.alt:0)|(t.shiftKey?dn.shift:0))===o&&t.key.toLowerCase()===i}function fn(t,e,{rootElement:n=document.documentElement??void 0,ignoreWhenEditable:o=!1}={}){const i=n=>{var i;o&&(i=n.target,i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA"].includes(i.tagName)))||un(n,t)&&e(n)}
63
+ ;return n?(n.addEventListener("keydown",i),()=>n.removeEventListener("keydown",i)):()=>{}}function pn(t,e,{rootElement:n,ignoreWhenEditable:o}={}){nt((()=>{if(t)return fn(t,e,{rootElement:n,ignoreWhenEditable:o})}),[t,e,n,o])}const gn={applyUpdates:"l",openSearch:"/",annotateSelection:"a",highlightSelection:"h",toggleHighlights:"ctrl+shift+h",showSelection:"s",hideAdder:"Escape",activateRectMove:"ctrl+shift+y",activateRectResize:"ctrl+shift+j",activatePoint:"ctrl+shift+u"};let _n={...gn};const mn=new Set;function bn(t){const e={};return Object.keys(gn).forEach((n=>{const o=t[n];"string"!=typeof o&&null!==o||(e[n]=o)})),e}function yn(){return{..._n}}function wn(t){_n={...gn,...bn(t)},function(){const t={..._n};for(const e of mn)e(t)}()}function vn(){const[t,e]=et((()=>yn()));return nt((()=>{return t=e,mn.add(t),t({..._n}),()=>{mn.delete(t)};var t}),[]),t}const xn=(t=window)=>t.matchMedia("(pointer: coarse)").matches;function Cn({badgeCount:t}){return St("span",{className:Tt("rounded px-1 py-0.5","bg-current"),
64
+ children:St("span",{className:"font-bold text-color-text-inverted",children:t})})}function Sn({arrowDirection:t}){return St("div",{className:Tt("absolute left-1/2 -translate-x-1/2 z-2","fill-white text-grey-3",{"top-0 -translate-y-full":"up"===t}),children:St("up"===t?Gt:Yt,{})})}function An({badgeCount:t,icon:e,label:n,onClick:o,shortcut:i}){pn(i,o);const r=i?`${n} (${i})`:n;return St(ee,{classes:Tt("text-grey-7","group-hover:text-grey-5","hover:group-hover:text-grey-9"),onClick:o,title:r,size:"custom",variant:"custom",children:St("div",{className:Tt("flex flex-col items-center gap-y-1 py-2.5 px-2","text-annotator-sm leading-none"),children:[e&&St(e,{className:"text-annotator-lg",title:r}),"number"==typeof t&&St(Cn,{badgeCount:t}),St("span",{"data-testid":"adder-button-label",children:n})]})})}function kn({annotationCount:t,isVisible:e}){return St("div",{className:"sr-only",children:[St("span",{"aria-live":"polite","aria-atomic":"true",role:"status","data-testid":"annotation-count-announce",
65
+ children:t>0&&St("span",{children:[t," ",1===t?"annotation":"annotations"," for this selection."]})}),St("ul",{"aria-live":"polite","data-testid":"annotate-shortcuts-announce",children:e&&St(y,{children:[t>0&&St("li",{children:["Press ","'S'"," to show annotations."]}),St("li",{children:["Press ","'A'"," to annotate."]}),St("li",{children:["Press ","'H'"," to highlight."]})]})})]})}function Mn({arrowDirection:t,isVisible:e,onCommand:n,annotationCount:o=0}){const i=vn(),r=e?i.annotateSelection:null,s=e?i.highlightSelection:null,a=e?i.showSelection:null;return pn(e?i.hideAdder:null,(()=>n("hide"))),St("div",{className:Tt("all-initial","border border-solid border-grey-3","absolute select-none bg-white rounded shadow-intense","opacity-5",{"animate-adder-pop-up":"up"===t&&e,"animate-adder-pop-down":"down"===t&&e}),"data-component":"AdderToolbar",dir:"ltr",style:{visibility:e?"visible":"hidden"},children:[St("div",{className:Tt("flex group"),children:[St(An,{icon:Ot,onClick:()=>n("annotate"),label:"Annotate",
66
+ shortcut:r}),St(An,{icon:qt,onClick:()=>n("highlight"),label:"Highlight",shortcut:s}),o>0&&St(y,{children:[St("div",{className:Tt("m-1.5 border-r border-grey-4 border-solid")}),St(An,{badgeCount:o,onClick:()=>n("show"),label:"Show",shortcut:a})]})]}),St(Sn,{arrowDirection:t}),St(kn,{annotationCount:o,isVisible:e})]})}let Rn;function En(t){const e=t.attachShadow({mode:"open"}),n=function(t){const e=document.querySelector('link[rel="preload"][href*="/build/styles/annotator.css"]')?.href;if(!e)return Promise.resolve();const n=document.createElement("link");if(n.rel="stylesheet",n.href=e,n.crossOrigin="anonymous",n.removeAttribute=()=>{},t.appendChild(n),void 0===Rn){Rn=new CSSStyleSheet;const t=Rn;n.addEventListener("load",(()=>{if(n.sheet){for(const e of n.sheet.rules)e instanceof CSSPropertyRule&&t.insertRule(e.cssText);document.adoptedStyleSheets.push(t)}}),{once:!0})}return new Promise((t=>{n.addEventListener("load",(()=>t()))}))}(e);return{shadowRoot:e,stylesLoaded:n}}class Pn{constructor(t,e){
67
+ const n=`hypothesis-${t}`;this._element=document.createElement(n);const{shadowRoot:o}=En(this._element);this._shadowRoot=o,this._render=e}destroy(){H(null,this._shadowRoot),this._element.remove()}get element(){return this._element}render(){H(this._render(),this._shadowRoot)}}let Tn=function(t){return t[t.DOWN=1]="DOWN",t[t.UP=2]="UP",t}({});function Nn(t){return t.toString()+"px"}class Ln{constructor(t,e){this._view=t.ownerDocument.defaultView,this._isVisible=!1,this._arrowDirection="up",this._annotationsForSelection=[],this._onAnnotate=e.onAnnotate,this._onHighlight=e.onHighlight,this._onShowAnnotations=e.onShowAnnotations,this._container=new Pn("adder",(()=>this._render())),t.appendChild(this._container.element),Object.assign(this._container.element.style,{position:"absolute",top:0,left:0}),this._container.render()}get annotationsForSelection(){return this._annotationsForSelection}set annotationsForSelection(t){this._annotationsForSelection=t,this._container.render()}hide(){this._isVisible=!1,
68
+ this._container.render(),Object.assign(this._container.element.style,{top:0,left:0})}destroy(){this._container.destroy()}show(t,e){const{left:n,top:o,arrowDirection:i}=this._calculateTarget(t,e);this._showAt(n,o),this._isVisible=!0,this._arrowDirection=i===Tn.UP?"up":"down",this._container.render()}_firstChild(){return this._container.element.shadowRoot.firstChild}_width(){return this._firstChild().getBoundingClientRect().width}_height(){return this._firstChild().getBoundingClientRect().height}_calculateTarget(t,e){let n,o,i;n=e&&!xn()?Tn.DOWN:Tn.UP;const r=Math.min(20,t.width),s=this._width(),a=xn()?10:0,l=this._height();return i=e?t.left-s/2+r:t.left+t.width-s/2-r,t.top-l<0&&n===Tn.DOWN?n=Tn.UP:t.top+l>this._view.innerHeight&&(n=Tn.DOWN),o=n===Tn.UP?t.top+t.height+10+a:t.top-l-10,i=Math.max(i,0),i=Math.min(i,this._view.innerWidth-s),o=Math.max(o,0),o=Math.min(o,this._view.innerHeight-l),{top:o,left:i,arrowDirection:n}}_findZindex(t,e){if(void 0===document.elementsFromPoint)return 32768
69
+ ;const n=this._width(),o=this._height(),i=t=>{const e=parseInt(getComputedStyle(t).zIndex);return Number.isInteger(e)?e:0},r=[...new Set([...document.elementsFromPoint(t,e),...document.elementsFromPoint(t,e+o),...document.elementsFromPoint(t+n/2,e+o/2),...document.elementsFromPoint(t+n,e),...document.elementsFromPoint(t+n,e+o)])].map(i).filter(Number.isInteger);let s=0;for(const t of document.querySelectorAll("hypothesis-highlight"))s=Math.max(s,i(t));return r.push(s),Math.max(...r)+1}_showAt(t,e){const n=function(t){let e=t.parentElement;for(;e.parentElement&&"static"===getComputedStyle(e).position;)e=e.parentElement;return e}(this._container.element).getBoundingClientRect(),o=this._findZindex(t,e);Object.assign(this._container.element.style,{left:Nn(t-n.left),top:Nn(e-n.top),zIndex:o})}_render(){return St(Mn,{isVisible:this._isVisible,arrowDirection:this._arrowDirection,onCommand:t=>{switch(t){case"annotate":this._onAnnotate(),this.hide();break;case"highlight":this._onHighlight(),this.hide();break
70
+ ;case"show":this._onShowAnnotations(this.annotationsForSelection);break;case"hide":this.hide()}},annotationCount:this.annotationsForSelection.length})}}var On=function(t){return t[t.Forwards=1]="Forwards",t[t.Backwards=2]="Backwards",t}(On||{});function In(t,e,n){const o=n===On.Forwards?e:e-1;if(""!==t.charAt(o).trim())return e;let i,r;if(n===On.Backwards?(i=t.substring(0,e),r=i.trimEnd()):(i=t.substring(e),r=i.trimStart()),!r.length)return-1;const s=i.length-r.length;return n===On.Backwards?e-s:e+s}function Bn(t,e){const n=t.commonAncestorContainer.ownerDocument.createNodeIterator(t.commonAncestorContainer,NodeFilter.SHOW_TEXT),o=e===On.Forwards?t.startContainer:t.endContainer,i=e===On.Forwards?t.endContainer:t.startContainer;let r=n.nextNode();for(;r&&r!==o;)r=n.nextNode();e===On.Backwards&&(r=n.previousNode());let s=-1;const a=()=>{if(r=e===On.Forwards?n.nextNode():n.previousNode(),r){const t=r.textContent,n=e===On.Forwards?0:t.length;s=In(t,n,e)}};for(;r&&-1===s&&r!==i;)a();if(r&&s>=0)return{node:r,
71
+ offset:s};throw new RangeError("No text nodes with non-whitespace text found in range")}function Dn(t){switch(t.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return t.textContent?.length??0;default:return 0}}function Fn(t){let e=t.previousSibling,n=0;for(;e;)n+=Dn(e),e=e.previousSibling;return n}function Hn(t,...e){let n=e.shift();const o=t.ownerDocument.createNodeIterator(t,NodeFilter.SHOW_TEXT),i=[];let r,s=o.nextNode(),a=0;for(;void 0!==n&&s;)r=s,a+r.data.length>n?(i.push({node:r,offset:n-a}),n=e.shift()):(s=o.nextNode(),a+=r.data.length);for(;void 0!==n&&r&&a===n;)i.push({node:r,offset:r.data.length}),n=e.shift();if(void 0!==n)throw new RangeError("Offset exceeds text length");return i}let zn=function(t){return t[t.FORWARDS=1]="FORWARDS",t[t.BACKWARDS=2]="BACKWARDS",t}({});class Vn{constructor(t,e){if(e<0)throw new Error("Offset is invalid");this.element=t,this.offset=e}relativeTo(t){if(!t.contains(this.element))throw new Error("Parent is not an ancestor of current element")
72
+ ;let e=this.element,n=this.offset;for(;e!==t;)n+=Fn(e),e=e.parentElement;return new Vn(e,n)}resolve(t={}){try{return Hn(this.element,this.offset)[0]}catch(e){if(0===this.offset&&void 0!==t.direction){const n=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);n.currentNode=this.element;const o=t.direction===zn.FORWARDS,i=o?n.nextNode():n.previousNode();if(!i)throw e;return{node:i,offset:o?0:i.data.length}}throw e}}static fromCharOffset(t,e){switch(t.nodeType){case Node.TEXT_NODE:return Vn.fromPoint(t,e);case Node.ELEMENT_NODE:return new Vn(t,e);default:throw new Error("Node is not an element or text node")}}static fromPoint(t,e){switch(t.nodeType){case Node.TEXT_NODE:{if(e<0||e>t.data.length)throw new Error("Text node offset is out of range");if(!t.parentElement)throw new Error("Text node has no parent");const n=Fn(t)+e;return new Vn(t.parentElement,n)}case Node.ELEMENT_NODE:{if(e<0||e>t.childNodes.length)throw new Error("Child node offset is out of range");let n=0
73
+ ;for(let o=0;o<e;o++)n+=Dn(t.childNodes[o]);return new Vn(t,n)}default:throw new Error("Point is not in an element or text node")}}}class Un{constructor(t,e){this.start=t,this.end=e}relativeTo(t){return new Un(this.start.relativeTo(t),this.end.relativeTo(t))}toRange(){let t,e;this.start.element===this.end.element&&this.start.offset<=this.end.offset?[t,e]=Hn(this.start.element,this.start.offset,this.end.offset):(t=this.start.resolve({direction:zn.FORWARDS}),e=this.end.resolve({direction:zn.BACKWARDS}));const n=new Range;return n.setStart(t.node,t.offset),n.setEnd(e.node,e.offset),n}static fromRange(t){const e=Vn.fromPoint(t.startContainer,t.startOffset),n=Vn.fromPoint(t.endContainer,t.endOffset);return new Un(e,n)}static fromOffsets(t,e,n){return new Un(new Vn(t,e),new Vn(t,n))}static trimmedRange(t){return function(t){if(!t.toString().trim().length)throw new RangeError("Range contains no non-whitespace text")
74
+ ;if(t.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(t.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const e=t.cloneRange();let n=!1,o=!1;const i={start:In(t.startContainer.textContent,t.startOffset,On.Forwards),end:In(t.endContainer.textContent,t.endOffset,On.Backwards)};if(i.start>=0&&(e.setStart(t.startContainer,i.start),n=!0),i.end>0&&(e.setEnd(t.endContainer,i.end),o=!0),n&&o)return e;if(!n){const{node:t,offset:n}=Bn(e,On.Forwards);t&&n>=0&&e.setStart(t,n)}if(!o){const{node:t,offset:n}=Bn(e,On.Backwards);t&&n>0&&e.setEnd(t,n)}return e}(Un.fromRange(t).toRange())}}const $n=".annotator-placeholder";function qn(t){return!!t.parentElement&&null!==t.parentElement.closest($n)}function Wn(t,e){const n=new Range;return t.compareBoundaryPoints(Range.START_TO_START,e)<=0?n.setStart(t.startContainer,t.startOffset):n.setStart(e.startContainer,e.startOffset),
75
+ t.compareBoundaryPoints(Range.END_TO_END,e)>=0?n.setEnd(t.endContainer,t.endOffset):n.setEnd(e.endContainer,e.endOffset),n}function jn(t=document.getSelection()){if(!t||0===t.rangeCount)return null;let e=t.getRangeAt(0);for(let n=1;n<t.rangeCount;n++)e=Wn(e,t.getRangeAt(n));return e.collapsed?null:e}function Kn(t){if(t.focusNode===t.anchorNode)return t.focusOffset<t.anchorOffset;return jn(t).startContainer===t.focusNode}function Xn(t,e){try{const n=e.nodeValue?.length??e.childNodes.length;return t.comparePoint(e,0)<=0&&t.comparePoint(e,n)>=0}catch{return!1}}function Yn(t,e){const n=t.commonAncestorContainer,o=n.ownerDocument.createNodeIterator(n,NodeFilter.SHOW_ALL);let i;for(;i=o.nextNode();)Xn(t,i)&&e(i)}function Gn(t){const e=jn(t);if(!e)return null;const n=function(t){const e=[];return Yn(t,(t=>{Ye(t)&&!t.textContent.match(/^\s*$/)&&e.push(t)})),e.flatMap((e=>{const n=e.ownerDocument.createRange();if(n.selectNodeContents(e),e===t.startContainer&&n.setStart(e,t.startOffset),
76
+ e===t.endContainer&&n.setEnd(e,t.endOffset),n.collapsed)return[];const o=Array.from(n.getClientRects());return n.detach(),o}))}(e);return 0===n.length?null:Kn(t)?n[0]:n[n.length-1]}const Qn="http://www.w3.org/2000/svg",Jn=["user-annotations","user-highlights","other-content"];class Zn{constructor(t=document.body){this.root=t}highlightShape(t){const{shape:e,anchor:n}=t,o=document.createElement("hypothesis-highlight");if(o.className="hypothesis-shape-highlight","rect"===e.type){const t=e.right-e.left,n=e.bottom-e.top;o.style.left=100*e.left+"%",o.style.top=100*e.top+"%",o.style.width=`calc(${100*t}% - 6px)`,o.style.height=`calc(${100*n}% - 6px)`}else if("point"===e.type){const t=7;o.style.left=`calc(${100*e.x}% - ${t+3}px)`,o.style.top=`calc(${100*e.y}% - ${t+3}px)`,o.style.width=2*t+"px",o.style.height=2*t+"px",o.style.borderRadius="50%"}return n.append(o),[o]}highlightRange(t,e){const n=function(t){if(t.collapsed)return[];let e=t.commonAncestorContainer;e&&e.nodeType!==Node.ELEMENT_NODE&&(e=e.parentElement)
77
+ ;if(!e)return[];const n=[],o=e.ownerDocument.createNodeIterator(e,NodeFilter.SHOW_TEXT);let i;for(;i=o.nextNode();){if(!Xn(t,i))continue;const e=i;e===t.startContainer&&t.startOffset>0?e.splitText(t.startOffset):(e===t.endContainer&&t.endOffset<e.data.length&&e.splitText(t.endOffset),n.push(e))}return n}(t),o=n.length>0&&qn(n[0]);let i=[],r=null,s=null;n.forEach((t=>{r&&r.nextSibling===t?s.push(t):(s=[t],i.push(s)),r=t}));const a=/^\s*$/;i=i.filter((t=>{const e=t[0].parentElement;return 1===e?.childNodes.length&&"SPAN"===e?.tagName||t.some((t=>!a.test(t.data)))}));const l=[];return i.forEach((t=>{const n=document.createElement("hypothesis-highlight");n.className=Tt("hypothesis-highlight",e);t[0].parentNode.replaceChild(n,t[0]),t.forEach((t=>n.appendChild(t))),l.push(n)})),o||function(t,e){if(0===t.length)return;const n=function(t){const e=t.closest(".page");if(!e)return null;const n=e.querySelector(".canvasWrapper > canvas");if(!n)return null;return n}(t[0]);if(!n||!n.parentElement)return
78
+ ;let o=n.parentElement.querySelector(".hypothesis-highlight-layer");if(!o){o=document.createElementNS(Qn,"svg"),o.setAttribute("class","hypothesis-highlight-layer"),n.parentElement.appendChild(o),n.parentElement.style.position="relative";const t=o.style;t.position="absolute",t.left="0",t.top="0",t.width="100%",t.height="100%",t.mixBlendMode="multiply"}const i=n.getBoundingClientRect(),r=t.map((t=>{const n=t.getBoundingClientRect(),o=document.createElementNS(Qn,"rect"),r=(n.left-i.left)/i.width,s=(n.top-i.top)/i.height,a=n.width/i.width,l=n.height/i.height;return o.setAttribute("x",100*r+"%"),o.setAttribute("y",100*s+"%"),o.setAttribute("width",100*a+"%"),o.setAttribute("height",100*l+"%"),o.setAttribute("class",Tt("hypothesis-svg-highlight",e)),t.classList.add("is-transparent"),t.svgHighlight=o,o}));o.append(...r)}(l,e),l}removeAllHighlights(){const t=Array.from(this.root.querySelectorAll("hypothesis-highlight"));this.removeHighlights(t)}removeHighlights(t){!function(t,e){t.forEach((t=>{
79
+ t.svgHighlight?eo(t.svgHighlight,e):t.classList.toggle("hypothesis-highlight-focused",e)}))}(t,!1);for(const e of t){if(e.parentNode){to(e,Array.from(e.childNodes))}e.svgHighlight&&e.svgHighlight.remove()}}setHighlightsFocused(t,e){t.forEach((t=>{t.svgHighlight?eo(t.svgHighlight,e):t.classList.toggle("hypothesis-highlight-focused",e)}))}setHighlightsVisible(t){this.root.classList.toggle(no,t)}getHighlightsFromPoint(t,e){return oo(t,e)}}function to(t,e){const n=t.parentNode;e.forEach((e=>n.insertBefore(e,t))),t.remove()}function eo(t,e){const n=t.parentNode,o=t.getAttribute("data-focused-id");if(Boolean(o)!==e)if(e){t.setAttribute("data-focused-id",Ce(8));const e=t.cloneNode();e.setAttribute("data-is-focused","data-is-focused"),n.append(e)}else{const e=n.querySelector(`[data-focused-id="${o}"][data-is-focused]`);e?.remove(),t.removeAttribute("data-focused-id")}}const no="hypothesis-highlights-always-on";function oo(t,e){
80
+ const n=`.${no}`,o=document.elementsFromPoint(t,e).filter((t=>"hypothesis-highlight"===t.localName&&t.closest(n))),i=[];for(const o of document.querySelectorAll("hypothesis-highlight.hypothesis-shape-highlight")){if(!o.closest(n))continue;const r=o.getBoundingClientRect();t>=r.left&&t<r.right&&e>=r.top&&e<r.bottom&&i.push(o)}return[...o,...i]}function io(t){ao(so(t)),function(t){for(const[e,n]of function(t){const e=new Map;for(const n of(t??document).getElementsByClassName("hypothesis-highlight-layer"))e.set(n,Array.from(n.querySelectorAll(".hypothesis-svg-highlight")));return e}(t)){n.every(((t,e,n)=>0===e||lo(t)>=lo(n[e-1])))||(n.sort(((t,e)=>lo(t)-lo(e))),e.replaceChildren(...n))}}(t)}const ro=t=>"hypothesis-highlight"===t.tagName.toLowerCase();function so(t){let e;return e=ro(t)?Array.from(t.children).filter(ro):Array.from(t.getElementsByTagName("hypothesis-highlight")).filter((t=>!t.parentElement||!ro(t.parentElement))),e}function ao(t,e="",n=0,o=0){for(const i of t){
81
+ const t=Jn.find((t=>i.classList.contains(t)))??"other-content",r=e&&t===e?o+1:0;i.setAttribute("data-nesting-level",`${n}`),i.setAttribute("data-cluster-level",`${r}`),i.svgHighlight&&(i.svgHighlight.setAttribute("data-nesting-level",`${n}`),i.svgHighlight.setAttribute("data-cluster-level",`${r}`)),ao(so(i),t,n+1,r)}}function lo(t){return t.getAttribute("data-is-focused")?Number.MAX_SAFE_INTEGER:parseInt(t.getAttribute("data-nesting-level")??"0",10)}function co(t){const e=[];return t.forEach((({annotation:t,highlights:n})=>{if(!n?.length)return;const{top:o,bottom:i}=function(t){const e=t.map((t=>t.getBoundingClientRect()));return e.reduce(((t,e)=>({top:Math.min(t.top,e.top),left:Math.min(t.left,e.left),bottom:Math.max(t.bottom,e.bottom),right:Math.max(t.right,e.right)})))}(n);o>=i||e.push({tag:t.$tag,top:o,bottom:i})})),e.sort(((t,e)=>t.top-e.top)),e}class ho{constructor({contentContainer:t,hostRPC:e}){this._hostRPC=e,this._updatePending=!1,this._anchors=[],this._listeners=new mt,
82
+ this._listeners.add(window,"resize",(()=>this.update())),this._listeners.add(window,"scroll",(()=>this.update())),this._listeners.add(t,"scroll",(()=>this.update()),{capture:!0})}destroy(){this._listeners.removeAll()}update(t){t&&(this._anchors=t),this._updatePending||(this._updatePending=!0,requestAnimationFrame((()=>{const t=co(this._anchors);this._hostRPC.call("anchorsChanged",t),this._updatePending=!1})))}}const uo=["top-left","top-right","bottom-right","bottom-left"];function fo(t,e="short"){const n=t??"top-left";return"long"===e?`${n} corner pinned`:n}function po({mode:t,tool:e,x:n,y:o,width:i,height:r,keyboardActive:s,pinnedCorner:a}){if(!s||!e)return null;let l=""
83
+ ;if("point"===e)l="move"===t&&"number"==typeof n&&"number"==typeof o?`Pin position: ${Math.round(n)}, ${Math.round(o)}`:"resize"===t?"Pin annotation mode. Use arrow keys to move.":"Pin annotation mode. Use arrow keys to move, Enter to confirm.";else if("rect"===e)if("move"===t&&"number"==typeof n&&"number"==typeof o&&"number"==typeof i&&"number"==typeof r)l=`Rectangle position: ${Math.round(n)}, ${Math.round(o)}. Size: ${Math.round(i)} by ${Math.round(r)} pixels`;else if("resize"===t&&"number"==typeof i&&"number"==typeof r){const t=fo(a,"long");l=`Rectangle size: ${Math.round(i)} by ${Math.round(r)} pixels. ${t}. Press Tab to change pinned corner.`}else l="rect"===t?"Rectangle annotation mode. Click the mode button to switch to Move or Resize mode.":"Rectangle annotation mode. Use arrow keys to move, Ctrl+Shift+J to resize, Enter to confirm.";return St("div",{"aria-live":"polite","aria-atomic":"true",role:"status",className:"sr-only","data-testid":"draw-tool-announcer",children:l&&St("span",{children:l})})}
84
+ function go({mode:t,keyboardActive:e,pinnedCorner:n}){if(!e||!t)return null;const o="move"===t?"Move":"resize"===t?"Resize":"Rectangle";let i;if("move"===t)i="Use arrow keys to move, click mode button to switch modes, Enter to confirm";else if("resize"===t){i=`Use arrow keys to resize (${fo(n,"short")} corner pinned), Tab to change corner, click mode button to switch modes, Enter to confirm`}else i="Rectangle mode. Click the mode button to switch to Move or Resize mode.";return St("div",{className:"fixed bottom-4 left-4 bg-white border border-grey-3 rounded shadow-lg p-3 z-50 pointer-events-none","data-testid":"draw-tool-keyboard-indicator",role:"status",children:[St("div",{className:"text-sm font-semibold text-grey-9",children:["Keyboard mode: ",o]}),St("div",{className:"text-xs text-grey-6 mt-1",children:i})]})}function _o(t){return{type:"rect",left:Math.min(t.left,t.right),top:Math.min(t.top,t.bottom),right:Math.max(t.left,t.right),bottom:Math.max(t.top,t.bottom)}}function mo(t,e){
85
+ const n=_o(t),o=n.right-n.left,i=n.bottom-n.top,r=Math.max(e.minLeft,Math.min(n.left,e.maxRight-o)),s=Math.max(e.minTop,Math.min(n.top,e.maxBottom-i));return{type:"rect",left:r,top:s,right:r+o,bottom:s+i}}function bo(t){switch(t){case"top-left":return{top:!1,right:!0,bottom:!0,left:!1};case"top-right":return{top:!1,right:!1,bottom:!0,left:!0};case"bottom-right":return{top:!0,right:!1,bottom:!1,left:!0};case"bottom-left":return{top:!0,right:!0,bottom:!1,left:!1};default:return{top:!0,right:!0,bottom:!0,left:!0}}}const yo="#374151";function wo({shape:t,waitingForSecondClick:e,firstClickPoint:n,keyboardMode:o,keyboardActive:i,pinnedCorner:r}){if("rect"===t?.type){if(e&&n){const{x:t,y:e}=n;return St(y,{children:[St("circle",{stroke:"grey","stroke-width":"2px",fill:"none",cx:t,cy:e,r:8}),St("line",{stroke:"grey","stroke-width":"1px",x1:t-12,y1:e,x2:t+12,y2:e}),St("line",{stroke:"grey","stroke-width":"1px",x1:t,y1:e-12,x2:t,y2:e+12})]})}const s=_o(t),a=s.right-s.left,l=s.bottom-s.top,c="resize"===o&&i?bo(r):{
86
+ top:!1,right:!1,bottom:!1,left:!1};return St(y,{children:[St("rect",{stroke:"white","stroke-dasharray":"5","stroke-width":"1px",fill:"grey","fill-opacity":"0.5",x:s.left,y:s.top,width:a,height:l}),St("rect",{stroke:"grey","stroke-dasharray":"5","stroke-dashoffset":"5","stroke-width":"1px",fill:"none",x:s.left,y:s.top,width:a,height:l}),"resize"===o&&i&&St(y,{children:[St("line",{x1:s.left,y1:s.top,x2:s.right,y2:s.top,stroke:c.top?yo:"transparent","stroke-width":"3px","stroke-dasharray":"5","stroke-dashoffset":"5"}),St("line",{x1:s.right,y1:s.top,x2:s.right,y2:s.bottom,stroke:c.right?yo:"transparent","stroke-width":"3px","stroke-dasharray":"5","stroke-dashoffset":"5"}),St("line",{x1:s.left,y1:s.bottom,x2:s.right,y2:s.bottom,stroke:c.bottom?yo:"transparent","stroke-width":"3px","stroke-dasharray":"5","stroke-dashoffset":"5"}),St("line",{x1:s.left,y1:s.top,x2:s.left,y2:s.bottom,stroke:c.left?yo:"transparent","stroke-width":"3px","stroke-dasharray":"5","stroke-dashoffset":"5"})]})]})}if("point"===t?.type){
87
+ const e=t;return St("circle",{stroke:"black","stroke-width":"1px",fill:"yellow",cx:e.x,cy:e.y,r:5})}return null}class vo extends Error{constructor(t,e="Drawing failed"){super(e),this.kind=t}}class xo{_waitingForSecondClick=!1;_hasMoved=!1;_dragThreshold=5;_keyboardMode=null;_keyboardActive=!1;_pinnedCorner="top-left";_keyboardMoveIncrement=10;_keyboardMoveIncrementLarge=50;_defaultRectangleSize=30;_minRectangleSize=20;_maxRectangleSizeRatio=.95;_rectInitiatedByKeyboard=!1;constructor(t){this._container=t,this._tool="rect",this._announcerContainer=document.createElement("div"),this._announcerContainer.setAttribute("data-testid","draw-tool-announcer-container"),t.appendChild(this._announcerContainer),this._indicatorContainer=document.createElement("div"),this._indicatorContainer.setAttribute("data-testid","draw-tool-indicator-container"),t.appendChild(this._indicatorContainer)}destroy(){this.cancel(),this._announcerContainer?.remove(),this._announcerContainer=void 0,this._indicatorContainer?.remove(),
88
+ this._indicatorContainer=void 0,this._removeScrollListener()}getKeyboardModeState(){const t=this._keyboardActive&&null===this._keyboardMode?"rect":this._keyboardMode;return{keyboardActive:this._keyboardActive,keyboardMode:t}}async draw(t,e){this._tool=t,this.cancel("restarted");const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("data-testid","surface"),n.style.cursor="crosshair",n.style.touchAction="none",n.style.position="absolute",n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.style.left="0px",n.style.top="0px",n.style.zIndex="10",this._container.append(n),this._surface=n;const{promise:o,resolve:i,reject:r}=function(){let t,e;return{promise:new Promise(((n,o)=>{t=n,e=o})),resolve:t,reject:e}}();return this._drawEnd=i,this._drawError=r,this._waitingForSecondClick=!1,this._firstClickPoint=void 0,this._hasMoved=!1,this._rectInitiatedByKeyboard=!1,this._surface.addEventListener("pointerdown",(t=>{switch(this._tool){case"rect":
89
+ if(this._rectInitiatedByKeyboard=!1,this._waitingForSecondClick&&this._firstClickPoint)return this._shape={type:"rect",left:this._firstClickPoint.x,top:this._firstClickPoint.y,right:t.clientX,bottom:t.clientY},this._waitingForSecondClick=!1,this._firstClickPoint=void 0,i(_o(this._shape)),this._abortDraw?.abort(),void t.stopPropagation();this._shape={type:"rect",left:t.clientX,top:t.clientY,right:t.clientX,bottom:t.clientY},this._hasMoved=!1,this._renderSurface();break;case"point":this._shape={type:"point",x:t.clientX,y:t.clientY}}this._renderSurface()})),this._surface.addEventListener("pointermove",(t=>{if(this._rectInitiatedByKeyboard&&"rect"===this._shape?.type)return this._shape=void 0,this._rectInitiatedByKeyboard=!1,this._waitingForSecondClick=!1,this._firstClickPoint=void 0,this._hasMoved=!1,this._deactivateKeyboardMode(),void this._renderSurface();if(this._shape){switch(this._shape.type){case"rect":if(!this._hasMoved){const e=Math.abs(t.clientX-this._shape.left),n=Math.abs(t.clientY-this._shape.top)
90
+ ;this._hasMoved=e>=this._dragThreshold||n>=this._dragThreshold}this._shape.right=t.clientX,this._shape.bottom=t.clientY;break;case"point":this._shape.x=t.clientX,this._shape.y=t.clientY}this._renderSurface()}})),this._surface.addEventListener("pointerup",(t=>{if(this._waitingForSecondClick)t.stopPropagation();else if(this._shape){switch(this._shape.type){case"rect":if(this._hasMoved)this._shape.right=t.clientX,this._shape.bottom=t.clientY,i(_o(this._shape));else{const e=Math.abs(t.clientX-this._shape.left),n=Math.abs(t.clientY-this._shape.top);if(e<this._dragThreshold&&n<this._dragThreshold)return this._firstClickPoint={x:this._shape.left,y:this._shape.top},this._waitingForSecondClick=!0,this._renderSurface(),void t.stopPropagation();this._shape.right=t.clientX,this._shape.bottom=t.clientY,i(_o(this._shape))}break;case"point":this._shape.x=t.clientX,this._shape.y=t.clientY,i(this._shape)}this._abortDraw?.abort(),t.stopPropagation()}})),this._surface.addEventListener("wheel",(t=>{
91
+ let e=Math.abs(t.deltaY),n=Math.abs(t.deltaX);for(const o of document.elementsFromPoint(t.clientX,t.clientY)){const i=o.scrollLeft;o.scrollLeft+=n*Math.sign(t.deltaX),n-=Math.abs(o.scrollLeft-i);const r=o.scrollTop;o.scrollTop+=e*Math.sign(t.deltaY),e-=Math.abs(o.scrollTop-r)}})),this._abortDraw=new AbortController,document.body.addEventListener("keydown",(t=>{if(!Ge(t.target)){if("Escape"===t.key)return this._keyboardActive&&this._deactivateKeyboardMode(),this._drawError&&this._drawError(new vo("canceled","Drawing canceled")),void this._abortDraw?.abort();if(this._keyboardActive){if("Tab"===t.key&&"resize"===this._keyboardMode&&"rect"===this._tool){t.preventDefault(),t.stopPropagation();const e=(uo.indexOf(this._pinnedCorner)+1)%uo.length;return this._pinnedCorner=uo[e],this._updateAnnouncer(),void this._renderSurface()}if("Enter"===t.key)return t.preventDefault(),t.stopPropagation(),void(this._shape&&("rect"===this._shape.type?i(_o(this._shape)):i(this._shape),this._deactivateKeyboardMode(),
92
+ this._abortDraw?.abort()));if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(t.key)){t.preventDefault(),t.stopPropagation();const e=t.metaKey||t.ctrlKey?this._keyboardMoveIncrementLarge:this._keyboardMoveIncrement;this._handleArrowKey(t.key,e)}else;}}}),{signal:this._abortDraw.signal}),this._abortDraw.signal.onabort=()=>{this._surface?.remove(),this._shape=void 0,this._surface=void 0,this._drawError=void 0,this._drawEnd=void 0,this._abortDraw=void 0,this._waitingForSecondClick=!1,this._firstClickPoint=void 0,this._hasMoved=!1,this._rectInitiatedByKeyboard=!1,this._deactivateKeyboardMode()},e&&(this._activateKeyboardMode(),this._keyboardMode=e,this._updateAnnouncer()),this._renderSurface(),o}static _RESERVED_VIEWPORT_TOP=40;_updateRectanglePosition(){this._shape=function(t,e,n,o){const{defaultRectangleSize:i,reservedViewportTop:r}=o,s=t.getBoundingClientRect(),a=t.scrollLeft||0,l=t.scrollTop||0;let c=a,h=l;const d=t.querySelectorAll(".page");let u=null,f=0;for(const t of d){
93
+ const e=t.getBoundingClientRect(),n=Math.max(e.top,s.top,r),o=Math.min(e.bottom,s.bottom),i=Math.max(e.left,s.left),a=Math.min(e.right,s.right),l=Math.max(0,a-i)*Math.max(0,o-n);l>0&&e.bottom>s.top+50&&e.top<s.bottom-50&&l>f&&(f=l,u=t)}if(u){const t=u.getBoundingClientRect(),e=Math.max(t.top,s.top,r);c=Math.max(t.left,s.left)-s.left+a,h=e-s.top+l,c+=10,h+=10}else c+=10,h=Math.max(l+10,r-s.top+l+10);if(e&&"rect"===e.type)return{type:"rect",left:c,top:h,right:c+(e.right-e.left),bottom:h+(e.bottom-e.top)};return"point"===n?{type:"point",x:c,y:h}:{type:"rect",left:c,top:h,right:c+i,bottom:h+i}}(this._container,this._shape,this._tool,{defaultRectangleSize:this._defaultRectangleSize,reservedViewportTop:xo._RESERVED_VIEWPORT_TOP}),this._renderSurface()}_setupScrollListener(){this._removeScrollListener(),this._scrollListener=()=>{void 0!==this._scrollDebounceTimeout&&window.clearTimeout(this._scrollDebounceTimeout),this._scrollDebounceTimeout=window.setTimeout((()=>{
94
+ this._keyboardActive&&"rect"===this._shape?.type&&(this._updateRectanglePosition(),this._updateAnnouncer())}),50)},this._container.addEventListener("scroll",this._scrollListener,{passive:!0})}_removeScrollListener(){this._scrollListener&&(this._container.removeEventListener("scroll",this._scrollListener),this._scrollListener=void 0),void 0!==this._scrollDebounceTimeout&&(window.clearTimeout(this._scrollDebounceTimeout),this._scrollDebounceTimeout=void 0)}_activateKeyboardMode(){this._keyboardActive=!0,this._keyboardMode=null,this._pinnedCorner="top-left",this._shape||(this._updateRectanglePosition(),this._rectInitiatedByKeyboard=!0),this._setupScrollListener(),this._updateAnnouncer()}_deactivateKeyboardMode(){this._keyboardActive=!1,this._keyboardMode=null,this._pinnedCorner="top-left",this._removeScrollListener(),this._updateAnnouncer()}_handleArrowKey(t,e){if(!this._shape||!this._keyboardMode)return;const n=function(t,e){const n=t.getBoundingClientRect(),o=t.scrollLeft||0,i=t.scrollTop||0;return{minLeft:o,
95
+ minTop:i+Math.max(0,e-n.top),maxRight:o+t.clientWidth,maxBottom:i+t.clientHeight}}(this._container,xo._RESERVED_VIEWPORT_TOP);if("point"===this._shape.type&&"move"===this._keyboardMode)return this._shape=function(t,e,n,o){switch(e){case"ArrowUp":return{...t,y:Math.max(o.minTop,t.y-n)};case"ArrowDown":return{...t,y:Math.min(o.maxBottom,t.y+n)};case"ArrowLeft":return{...t,x:Math.max(o.minLeft,t.x-n)};case"ArrowRight":return{...t,x:Math.min(o.maxRight,t.x+n)};default:return t}}(this._shape,t,e,n),this._renderSurface(),void this._updateAnnouncer();if("rect"===this._shape.type){const o=_o(this._shape);if("move"===this._keyboardMode)return this._shape=mo(function(t,e,n,o){const{left:i,top:r,right:s,bottom:a}=t;switch(e){case"ArrowUp":{const t=Math.max(o.minTop,r-n);return{type:"rect",left:i,top:t,right:s,bottom:a-(r-t)}}case"ArrowDown":{const t=Math.min(o.maxBottom,a+n);return{type:"rect",left:i,top:r+(t-a),right:s,bottom:t}}case"ArrowLeft":{const t=Math.max(o.minLeft,i-n);return{type:"rect",left:t,top:r,
96
+ right:s-(i-t),bottom:a}}case"ArrowRight":{const t=Math.min(o.maxRight,s+n);return{type:"rect",left:i+(t-s),top:r,right:t,bottom:a}}default:return t}}(o,t,e,n),n),this._renderSurface(),void this._updateAnnouncer();if("resize"===this._keyboardMode){if(!function(t,e){const n=bo(e);switch(t){case"ArrowUp":return n.top||n.bottom;case"ArrowDown":return n.bottom||n.top;case"ArrowLeft":return n.left||n.right;case"ArrowRight":return n.right||n.left;default:return!1}}(t,this._pinnedCorner))return;const i=n.maxRight-n.minLeft,r=n.maxBottom-n.minTop,s={minWidth:this._minRectangleSize,minHeight:this._minRectangleSize,maxWidth:i*this._maxRectangleSizeRatio,maxHeight:r*this._maxRectangleSizeRatio,increment:e};this._shape=mo(function(t,e,n,o){const{left:i,top:r,right:s,bottom:a}=t,{minWidth:l,minHeight:c,maxWidth:h,maxHeight:d,increment:u}=o,f={...t};switch(n){case"top-left":switch(e){case"ArrowRight":{const t=Math.min(i+h,s+u);f.right=t;break}case"ArrowDown":{const t=Math.min(r+d,a+u);f.bottom=t;break}case"ArrowLeft":
97
+ f.right=Math.max(i+l,s-u);break;case"ArrowUp":f.bottom=Math.max(r+c,a-u)}break;case"top-right":switch(e){case"ArrowRight":f.left=Math.min(s-l,i+u);break;case"ArrowDown":{const t=Math.min(r+d,a+u);f.bottom=t;break}case"ArrowLeft":{const t=Math.max(s-h,i-u);f.left=t;break}case"ArrowUp":f.bottom=Math.max(r+c,a-u)}break;case"bottom-right":switch(e){case"ArrowRight":f.left=Math.min(s-l,i+u);break;case"ArrowDown":f.top=Math.min(a-c,r+u);break;case"ArrowLeft":{const t=Math.max(s-h,i-u);f.left=t;break}case"ArrowUp":{const t=Math.max(a-d,r-u);f.top=t;break}}break;case"bottom-left":switch(e){case"ArrowRight":{const t=Math.min(i+h,s+u);f.right=t;break}case"ArrowDown":f.top=Math.min(a-c,r+u);break;case"ArrowLeft":f.right=Math.max(i+l,s-u);break;case"ArrowUp":{const t=Math.max(a-d,r-u);f.top=t;break}}}return f}(o,t,this._pinnedCorner,s),n),this._renderSurface(),this._updateAnnouncer()}}}setOnKeyboardModeChange(t){this._onKeyboardModeChange=t}setKeyboardMode(t){
98
+ this._surface&&(this._keyboardActive||this._activateKeyboardMode(),this._keyboardMode!==t&&(this._keyboardMode=t,"resize"===t&&(this._pinnedCorner="top-left"),this._updateAnnouncer(),this._renderSurface()))}_updateAnnouncer(){if(!this._announcerContainer||!this._indicatorContainer)return;let t,e,n,o;if(this._shape)if("point"===this._shape.type)t=this._shape.x,e=this._shape.y;else{const i=_o(this._shape);t=i.left,e=i.top,n=i.right-i.left,o=i.bottom-i.top}const i=this._keyboardActive&&null===this._keyboardMode?"rect":this._keyboardMode;H(St(po,{mode:i,tool:this._tool,x:t,y:e,width:n,height:o,keyboardActive:this._keyboardActive,pinnedCorner:this._pinnedCorner}),this._announcerContainer),H(St(go,{mode:i,keyboardActive:this._keyboardActive,pinnedCorner:this._pinnedCorner}),this._indicatorContainer),this._onKeyboardModeChange&&this._onKeyboardModeChange({keyboardActive:this._keyboardActive,keyboardMode:i})}cancel(t="canceled"){this._drawError&&this._drawError(new vo(t,"Drawing canceled")),this._abortDraw?.abort(),
99
+ this._waitingForSecondClick=!1,this._firstClickPoint=void 0,this._hasMoved=!1}_renderSurface(){this._surface&&H(St(wo,{shape:this._shape,waitingForSecondClick:this._waitingForSecondClick,firstClickPoint:this._firstClickPoint,keyboardMode:this._keyboardMode,keyboardActive:this._keyboardActive,pinnedCorner:this._pinnedCorner}),this._surface)}}class Co extends CustomEvent{constructor(t){super("hypothesis:layoutchange",{bubbles:!0,cancelable:!1,detail:t})}}const So=new Set;function Ao(...t){const e=t.join();So.has(e)||(console.warn(...t),So.add(e))}Ao.reset=()=>{So.clear()};const ko=["pdf_image_annotation","styled_highlight_clusters","vpat_keyboard"];class Mo extends Me{constructor(t=ko){super(),this._flags=new Map,this._knownFlags=t}update(t){this._flags.clear();for(const[e,n]of Object.entries(t))this._flags.set(e,n);this.emit("flagsChanged")}flagEnabled(t){return this._knownFlags.includes(t)?this._flags.get(t)??!1:(Ao("Looked up unknown feature",t),!1)}allFlags(){return Object.fromEntries(this._flags)}}
100
+ function Ro({cluster:t,label:e,onChange:n,currentStyles:o,highlightStyles:i}){const r=o[t],s="transparent"===r;return St("div",{className:"space-y-2",children:[St("div",{className:"flex items-center gap-x-2 text-annotator-base",children:St("div",{className:"grow text-color-text px-2 py-1 rounded",style:{backgroundColor:i[r].color},children:e})}),St("div",{className:"flex items-center gap-x-2",children:Object.keys(i).map((e=>St("div",{className:"relative",children:[St("input",{className:Tt("absolute w-6 h-6","opacity-[.00001]","cursor-pointer"),name:t,id:`hypothesis-${t}-${e}`,checked:r===e,onChange:n,type:"radio",value:e}),St("label",{className:"block",htmlFor:`${t}-${e}`,children:[St("div",{style:{backgroundColor:i[e].color},className:Tt("block w-6 h-6 rounded-full flex items-center justify-center",{"border-2 border-slate-0":r!==e,"border-2 border-slate-3":r===e}),children:"transparent"===e&&St($t,{className:Tt("w-3 h-3",{"text-slate-3":!s,"text-slate-7":s})})}),St("span",{className:"sr-only",children:e})]
101
+ })]},`${t}-${e}`)))})]})}function Eo({active:t,availableStyles:e,currentStyles:n,onStyleChange:o}){const i=st((t=>{const e=t.target,n=e.name,i=e.value;o(n,i)}),[o]),[r,s]=et(!1);return t?St(Nt,{classes:"overflow-hidden",children:St("div",{className:"flex flex-col text-annotator-base text-color-text",children:[St(ee,{classes:"rounded-none","data-testid":"control-toggle-button",onClick:()=>s(!r),title:r?"Hide highlight settings":"Show highlight settings",children:St(y,r?{children:[St(Bt,{}),St("span",{children:"Highlight Appearance"})]}:{children:[St(Ft,{}),St(qt,{})]})}),r&&St(Lt,{"data-testid":"cluster-style-controls",size:"sm",children:[St(Ro,{highlightStyles:e,label:"My annotations",cluster:"user-annotations",onChange:i,currentStyles:n}),St(Ro,{highlightStyles:e,label:"My highlights",cluster:"user-highlights",onChange:i,currentStyles:n}),St(Ro,{highlightStyles:e,label:"Everybody's content",cluster:"other-content",onChange:i,currentStyles:n})]})]})}):null}const Po={transparent:{color:"transparent",
102
+ secondColor:"transparent",thirdColor:"transparent"},pink:{color:"var(--hypothesis-color-pink)",secondColor:"var(--hypothesis-color-pink-1)",thirdColor:"var(--hypothesis-color-pink-2)"},orange:{color:"var(--hypothesis-color-orange)",secondColor:"var(--hypothesis-color-orange-1)",thirdColor:"var(--hypothesis-color-orange-2)"},yellow:{color:"var(--hypothesis-color-yellow)",secondColor:"var(--hypothesis-color-yellow-1)",thirdColor:"var(--hypothesis-color-yellow-2)"},green:{color:"var(--hypothesis-color-green)",secondColor:"var(--hypothesis-color-green-1)",thirdColor:"var(--hypothesis-color-green-2)"},purple:{color:"var(--hypothesis-color-purple)",secondColor:"var(--hypothesis-color-purple-1)",thirdColor:"var(--hypothesis-color-purple-2)"},grey:{color:"var(--hypothesis-color-grey)",secondColor:"var(--hypothesis-color-grey-1)",thirdColor:"var(--hypothesis-color-grey-2)"}},To={"other-content":"yellow","user-annotations":"orange","user-highlights":"purple"};class No{constructor(t,e){this._element=t,
103
+ this._features=e.features,this._container=new Pn("highlight-cluster-toolbar",(()=>this._render())),this._element.appendChild(this._container.element),Object.assign(this._container.element.style,{position:"fixed",top:`${this._element.offsetTop+4}px`,left:"4px"}),this.appliedStyles=To,this._init(),this._features.on("flagsChanged",(()=>{this._activate(this._isActive())})),this._container.render()}destroy(){clearTimeout(this._updateTimeout),this._activate(!1),this._container.destroy()}scheduleClusterUpdates(){clearTimeout(this._updateTimeout),this._updateTimeout=setTimeout((()=>this._updateClusters()),100)}_init(){for(const t of Object.keys(this.appliedStyles))this._setClusterStyles(t,this.appliedStyles[t]);this._activate(this._isActive())}_updateClusters(){this._isActive()&&io(this._element)}_isActive(){return this._features.flagEnabled("styled_highlight_clusters")}_activate(t){this._element.classList.toggle("hypothesis-highlights-clustered",t),this._container.render()}_setClusterStyle(t,e){
104
+ document.documentElement.style.setProperty(t,e)}_setClusterStyles(t,e){const n=Po[e];for(const e of Object.keys(n))this._setClusterStyle(`--hypothesis-${t}-${e}`,n[e])}_onChangeClusterStyle(t,e){this.appliedStyles[t]=e,this._setClusterStyles(t,e),this._container.render()}_render(){return St(Eo,{active:this._isActive(),availableStyles:Po,currentStyles:this.appliedStyles,onStyleChange:(t,e)=>this._onChangeClusterStyle(t,e)})}}function Lo(t){return t.split("").reverse().join("")}function Oo(t){return(t|-t)>>31&1}function Io(t,e,n,o){let i=t.P[n],r=t.M[n];const s=o>>>31,a=e[n]|s,l=a|r,c=(a&i)+i^i|a;let h=r|~(c|i),d=i&c;const u=Oo(h&t.lastRowMask[n])-Oo(d&t.lastRowMask[n]);return h<<=1,d<<=1,d|=s,h|=Oo(o)-s,i=d|~(l|h),r=h&l,t.P[n]=i,t.M[n]=r,u}function Bo(t,e,n){if(0===e.length)return[];n=Math.min(n,e.length);const o=[],i=32,r=Math.ceil(e.length/i)-1,s={P:new Uint32Array(r+1),M:new Uint32Array(r+1),lastRowMask:new Uint32Array(r+1)};s.lastRowMask.fill(1<<31),s.lastRowMask[r]=1<<(e.length-1)%i
105
+ ;const a=new Uint32Array(r+1),l=new Map,c=[];for(let t=0;t<256;t++)c.push(a);for(let t=0;t<e.length;t+=1){const n=e.charCodeAt(t);if(l.has(n))continue;const o=new Uint32Array(r+1);l.set(n,o),n<c.length&&(c[n]=o);for(let t=0;t<=r;t+=1){o[t]=0;for(let r=0;r<i;r+=1){const s=t*i+r;if(s>=e.length)continue;e.charCodeAt(s)===n&&(o[t]|=1<<r)}}}let h=Math.max(0,Math.ceil(n/i)-1);const d=new Uint32Array(r+1);for(let t=0;t<=h;t+=1)d[t]=(t+1)*i;d[r]=e.length;for(let t=0;t<=h;t+=1)s.P[t]=-1,s.M[t]=0;for(let u=0;u<t.length;u+=1){const f=t.charCodeAt(u);let p;f<c.length?p=c[f]:(p=l.get(f),void 0===p&&(p=a));let g=0;for(let t=0;t<=h;t+=1)g=Io(s,p,t,g),d[t]+=g;if(d[h]-g<=n&&h<r&&(1&p[h+1]||g<0)){let t;if(h+=1,s.P[h]=-1,s.M[h]=0,h===r){const n=e.length%i;t=0===n?i:n}else t=i;d[h]=d[h-1]+t-g+Io(s,p,h,g)}else for(;h>0&&d[h]>=n+i;)h-=1;h===r&&d[h]<=n&&(d[h]<n&&o.splice(0,o.length),o.push({start:-1,end:u+1,errors:d[h]}),n=d[h])}return o}function Do(t,e,n){return function(t,e,n){const o=Lo(e);return n.map((n=>{
106
+ const i=Math.max(0,n.end-e.length-n.errors);return{start:Bo(Lo(t.slice(i,n.end)),o,n.errors).reduce(((t,e)=>n.end-e.end<t?n.end-e.end:t),n.end),end:n.end,errors:n.errors}}))}(t,e,Bo(t,e,n))}function Fo(t,e,n){let o=0;const i=[];for(;-1!==o;)o=t.indexOf(e,o),-1!==o&&(i.push({start:o,end:o+e.length,errors:0}),o+=1);return i.length>0?i:Do(t,e,n)}function Ho(t,e){if(0===e.length||0===t.length)return 0;return 1-Fo(t,e,e.length)[0].errors/e.length}function zo(t,e,n={}){if(0===e.length)return null;const o=Math.min(256,e.length/2),i=Fo(t,e,o);if(0===i.length)return null;const r=o=>{const i=1-o.errors/e.length,r=n.prefix?Ho(t.slice(Math.max(0,o.start-n.prefix.length),o.start),n.prefix):1,s=n.suffix?Ho(t.slice(o.end,o.end+n.suffix.length),n.suffix):1;let a=1;if("number"==typeof n.hint){a=1-Math.abs(o.start-n.hint)/t.length}return(50*i+20*r+20*s+2*a)/92},s=i.map((t=>({start:t.start,end:t.end,score:r(t)})));return s.sort(((t,e)=>e.score-t.score)),s[0]}function Vo(t){const e=function(t){const e=t.nodeName.toLowerCase()
107
+ ;return"#text"===e?"text()":e}(t),n=function(t){let e=0,n=t;for(;n;)n.nodeName===t.nodeName&&(e+=1),n=n.previousSibling;return e}(t);return`${e}[${n}]`}function Uo(t,e){let n="",o=t;for(;o!==e;){if(!o)throw new Error("Node is not a descendant of root");n=Vo(o)+"/"+n,o=o.parentNode}return n="/"+n,n=n.replace(/\/$/,""),n}function $o(t,e,n){e=e.toUpperCase();let o=-1;for(let i=0;i<t.children.length;i++){const r=t.children[i];if(r.nodeName.toUpperCase()===e&&(++o,o===n))return r}return null}function qo(t,e=document.body){try{return function(t,e){if(null===t.match(/^(\/[A-Za-z0-9-]+(\[[0-9]+\])?)+$/))throw new Error("Expression is not a simple XPath");const n=t.split("/");let o=e;n.shift();for(const t of n){let e,n;const i=t.indexOf("[");if(-1!==i){e=t.slice(0,i);const o=t.slice(i+1,t.indexOf("]"));if(n=parseInt(o)-1,n<0)return null}else e=t,n=0;const r=$o(o,e,n);if(!r)return null;o=r}return o}(t,e)}catch{return document.evaluate("."+t,e,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}}class Wo{
108
+ constructor(t,e){this.root=t,this.range=e}static fromRange(t,e){return new Wo(t,e)}static fromSelector(t,e){const n=qo(e.startContainer,t);if(!n)throw new Error("Failed to resolve startContainer XPath");const o=qo(e.endContainer,t);if(!o)throw new Error("Failed to resolve endContainer XPath");const i=Vn.fromCharOffset(n,e.startOffset),r=Vn.fromCharOffset(o,e.endOffset),s=new Un(i,r).toRange();return new Wo(t,s)}toRange(){return this.range}toSelector(){const t=Un.fromRange(this.range).toRange(),e=Un.fromRange(t),n=Uo(e.start.element,this.root),o=Uo(e.end.element,this.root);return{type:"RangeSelector",startContainer:n,startOffset:e.start.offset,endContainer:o,endOffset:e.end.offset}}}class jo{constructor(t,e,n){this.root=t,this.start=e,this.end=n}static fromRange(t,e){const n=Un.fromRange(e).relativeTo(t);return new jo(t,n.start.offset,n.end.offset)}static fromSelector(t,e){return new jo(t,e.start,e.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){
109
+ return Un.fromOffsets(this.root,this.start,this.end).toRange()}}class Ko{constructor(t,e,n={}){this.root=t,this.exact=e,this.context=n}static fromRange(t,e){const n=t.textContent,o=Un.fromRange(e).relativeTo(t),i=o.start.offset,r=o.end.offset;return new Ko(t,n.slice(i,r),{prefix:n.slice(Math.max(0,i-32),i),suffix:n.slice(r,Math.min(n.length,r+32))})}static fromSelector(t,e){const{prefix:n,suffix:o}=e;return new Ko(t,e.exact,{prefix:n,suffix:o})}toSelector(){return{type:"TextQuoteSelector",exact:this.exact,prefix:this.context.prefix,suffix:this.context.suffix}}toRange(t={}){return this.toPositionAnchor(t).toRange()}toPositionAnchor(t={}){const e=zo(this.root.textContent,this.exact,{...this.context,hint:t.hint});if(!e)throw new Error("Quote not found");return new jo(this.root,e.start,e.end)}}function Xo(t){const e=parseFloat(t);return!Number.isFinite(e)||e<0?null:e}function Yo(t){return t instanceof Element?t:t.parentElement}function Go(t,e=t){
110
+ const n=Xo(t?.getAttribute("data-time-start")??""),o=Xo(e?.getAttribute("data-time-end")??"");return"number"!=typeof n||"number"!=typeof o||o<n?null:[n,o]}class Qo{constructor(t,e,n){this.root=t,this.start=e,this.end=n}static fromRange(t,e){const n=Yo(e.startContainer)?.closest("[data-time-start]"),o=Yo(e.endContainer)?.closest("[data-time-end]"),i=Go(n,o);if(!i)return null;const[r,s]=i;return new Qo(t,r,s)}toRange(){const t=[...this.root.querySelectorAll("[data-time-start]")].map((t=>{const e=Go(t);if(!e)return null;const[n,o]=e;return{element:t,start:n,end:o}})).filter((t=>null!==t));t.sort(((t,e)=>t.start-e.start));const e=function(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}(t,(t=>t.start<=this.start&&t.end>=this.start));if(-1===e)throw new Error("Start segment not found");const n=e+t.slice(e).findIndex((t=>t.start<=this.end&&t.end>=this.end));if(-1===n)throw new Error("End segment not found");const o=new Range;o.setStart(t[e].element,0);const i=t[n].element
111
+ ;return o.setEnd(i,i.childNodes.length),o}static fromSelector(t,e){const{start:n,end:o}=e;return new Qo(t,n,o)}toSelector(){return{type:"MediaTimeSelector",start:this.start,end:this.end}}}async function Jo(t,e){return t.toRange(e)}function Zo(t,e,n){const o=t[e];if("function"!=typeof o)throw new Error("Can only intercept functions");return t[e]=(...e)=>{const i=o.call(t,...e);return n(...e),i},()=>{t[e]=o}}function ti(t){return t.replace(/#.*/,"")}class ei{constructor(t,e=(()=>location.href)){this._listeners=new mt;let n=e();const o=(o=e())=>{ti(n)!==ti(o)&&(n=o,t(o))},i=function(){const t=window.navigation;return"function"==typeof Navigation&&t instanceof Navigation?t:null}();if(i)this._listeners.add(i,"navigatesuccess",(()=>o()));else{const t=[Zo(window.history,"pushState",(()=>o())),Zo(window.history,"replaceState",(()=>o()))];this._unpatchHistory=()=>t.forEach((t=>t())),this._listeners.add(window,"popstate",(()=>o()))}}disconnect(){this._unpatchHistory?.(),this._listeners.removeAll()}}var ni,oi
112
+ ;var ii=function(){if(oi)return ni;oi=1;var t="complete",e="canceled";function n(t,e,n){t.self===t?t.scrollTo(e,n):(t.scrollLeft=e,t.scrollTop=n)}function o(e){var i=e._scrollSettings;if(i){var r=i.maxSynchronousAlignments,s=function(t,e){var n,o,i,r,s,a,l,c=t.align,h=t.target.getBoundingClientRect(),d=c&&null!=c.left?c.left:.5,u=c&&null!=c.top?c.top:.5,f=c&&null!=c.leftOffset?c.leftOffset:0,p=c&&null!=c.topOffset?c.topOffset:0,g=d,_=u;if(t.isWindow(e))a=Math.min(h.width,e.innerWidth),l=Math.min(h.height,e.innerHeight),o=h.left+e.pageXOffset-e.innerWidth*g+a*g,i=h.top+e.pageYOffset-e.innerHeight*_+l*_,o-=f,i-=p,o=t.align.lockX?e.pageXOffset:o,i=t.align.lockY?e.pageYOffset:i,r=o-e.pageXOffset,s=i-e.pageYOffset;else{a=h.width,l=h.height,n=e.getBoundingClientRect();var m=h.left-(n.left-e.scrollLeft),b=h.top-(n.top-e.scrollTop);o=m+a*g-e.clientWidth*g,i=b+l*_-e.clientHeight*_,o-=f,i-=p,o=Math.max(Math.min(o,e.scrollWidth-e.clientWidth),0),i=Math.max(Math.min(i,e.scrollHeight-e.clientHeight),0),
113
+ o=t.align.lockX?e.scrollLeft:o,i=t.align.lockY?e.scrollTop:i,r=o-e.scrollLeft,s=i-e.scrollTop}return{x:o,y:i,differenceX:r,differenceY:s}}(i,e),a=Date.now()-i.startTime,l=Math.min(1/i.time*a,1);if(i.endIterations>=r)return n(e,s.x,s.y),e._scrollSettings=null,i.end(t);var c=1-i.ease(l);if(n(e,s.x-s.differenceX*c,s.y-s.differenceY*c),a>=i.time)return i.endIterations++,i.scrollAncestor&&o(i.scrollAncestor),void o(e);!function(t){if("requestAnimationFrame"in window)return window.requestAnimationFrame(t);setTimeout(t,16)}(o.bind(null,e))}}function i(t){return t.self===t}function r(t){return"pageXOffset"in t||(t.scrollHeight!==t.clientHeight||t.scrollWidth!==t.clientWidth)&&"hidden"!==getComputedStyle(t).overflow}function s(){return!0}function a(t){if(t.assignedSlot)return a(t.assignedSlot);if(t.parentElement)return"body"===t.parentElement.tagName.toLowerCase()?t.parentElement.ownerDocument.defaultView||t.parentElement.ownerDocument.ownerWindow:t.parentElement;if(t.getRootNode){var e=t.getRootNode()
114
+ ;if(11===e.nodeType)return e.host}}return ni=function(n,l,c){if(n){"function"==typeof l&&(c=l,l=null),l||(l={}),l.time=isNaN(l.time)?1e3:l.time,l.ease=l.ease||function(t){return 1-Math.pow(1-t,t/2)},l.align=l.align||{};var h=a(n),d=1,u=l.validTarget||s,f=l.isScrollable;l.debug&&(console.log("About to scroll to",n),h||console.error("Target did not have a parent, is it mounted in the DOM?"));for(var p=[];h;)if(l.debug&&console.log("Scrolling parent node",h),u(h,d)&&(f?f(h,r):r(h))&&(d++,p.push(h)),!(h=a(h))){g(t);break}return p.reduce(((t,r,s)=>function(t,n,r,s,a){var l,c=!n._scrollSettings,h=n._scrollSettings,d=Date.now(),u={passive:!0};function f(t){n._scrollSettings=null,n.parentElement&&n.parentElement._scrollSettings&&n.parentElement._scrollSettings.end(t),r.debug&&console.log("Scrolling ended with type",t,"for",n),a(t),l&&(n.removeEventListener("touchstart",l,u),n.removeEventListener("wheel",l,u))}h&&h.end(e);var p=r.maxSynchronousAlignments;return null==p&&(p=3),n._scrollSettings={startTime:d,
115
+ endIterations:0,target:t,time:r.time,ease:r.ease,align:r.align,isWindow:r.isWindow||i,maxSynchronousAlignments:p,end:f,scrollAncestor:s},"cancellable"in r&&!r.cancellable||(l=f.bind(null,e),n.addEventListener("touchstart",l,u),n.addEventListener("wheel",l,u)),c&&o(n),l}(n,r,l,p[s+1],g)),null)}function g(t){--d||c&&c(t)}},ni}(),ri=kt(ii);function si(t,e,n){return t+n*(e-t)}async function ai(t,e,{maxDuration:n=500}={}){const o=t.scrollTop,i=e,r=Date.now(),s=Math.min(Math.abs(i-o)/3,n);let a=0;for(;a<1;)await new Promise((t=>{requestAnimationFrame(t)})),a=Math.min(1,(Date.now()-r)/s),t.scrollTop=si(o,i,a)}function li(t,e=document.baseURI){return new URL(t,e).href.toString().replace(/#.*/,"")}class ci{constructor(t={}){this.document=t.document||document}uri(){let t=this._getDocumentHref();try{t=decodeURIComponent(t)}catch(t){console.error("Error decoding URI:",t)}const e=this._getLinks();for(const n of e)"canonical"===n.rel&&(t=n.href);return t}getDocumentMetadata(){const t={title:document.title,link:[],
116
+ dc:this._getMetaTags("name","dc."),eprints:this._getMetaTags("name","eprints."),facebook:this._getMetaTags("property","og:"),highwire:this._getMetaTags("name","citation_"),prism:this._getMetaTags("name","prism."),twitter:this._getMetaTags("name","twitter:")},e=this._getFavicon();e&&(t.favicon=e),t.title=this._getTitle(t),t.link=this._getLinks(t);const n=t.link.find((t=>t.href.startsWith("urn:x-dc")));return n&&(t.documentFingerprint=n.href),t}_getMetaTags(t,e){const n={};for(const o of Array.from(this.document.querySelectorAll("meta"))){const i=o.getAttribute(t),{content:r}=o;if(i&&r){const t=i.match(RegExp(`^${e}(.+)$`,"i"));if(t){const e=t[1].toLowerCase();n[e]?n[e].push(r):n[e]=[r]}}}return n}_getTitle(t){return t.highwire.title?t.highwire.title[0]:t.eprints.title?t.eprints.title[0]:t.prism.title?t.prism.title[0]:t.facebook.title?t.facebook.title[0]:t.twitter.title?t.twitter.title[0]:t.dc.title?t.dc.title[0]:this.document.title}_getLinks(t={dc:{},highwire:{}}){const e=[{href:this._getDocumentHref()
117
+ }],n=Array.from(this.document.querySelectorAll("link"));for(const t of n)if(["alternate","canonical","bookmark","shortlink"].includes(t.rel)){if("alternate"===t.rel){if(t.type&&t.type.match(/^application\/(rss|atom)\+xml/))continue;if(t.hreflang)continue}try{const n=this._absoluteUrl(t.href);e.push({href:n,rel:t.rel,type:t.type})}catch{}}for(const n of Object.keys(t.highwire)){const o=t.highwire[n];if("pdf_url"===n)for(const t of o)try{e.push({href:this._absoluteUrl(t),type:"application/pdf"})}catch{}if("doi"===n)for(let t of o)"doi:"!==t.slice(0,4)&&(t=`doi:${t}`),e.push({href:t})}for(const n of Object.keys(t.dc)){const o=t.dc[n];if("identifier"===n)for(const t of o)"doi:"===t.slice(0,4)&&e.push({href:t})}const o=t.dc["relation.ispartof"],i=t.dc.identifier;if(o&&i){const t=o[o.length-1],n=i[i.length-1],r="urn:x-dc:"+encodeURIComponent(t)+"/"+encodeURIComponent(n);e.push({href:r})}return e}_getFavicon(){let t=null
118
+ ;for(const e of Array.from(this.document.querySelectorAll("link")))if(["shortcut icon","icon"].includes(e.rel))try{t=this._absoluteUrl(e.href)}catch{}return t}_absoluteUrl(t){return li(t,this.document.baseURI)}_getDocumentHref(){const{href:t}=this.document.location,e=["http:","https:","file:"],n=new URL(t).protocol;return e.includes(n)?t:this.document.baseURI&&e.includes(new URL(this.document.baseURI).protocol)?this.document.baseURI:t}}class hi extends Me{constructor({features:t,container:e=document.body,sideBySideOptions:n}){super(),this.featureFlags=t,this.container=e,this._htmlMeta=new ci,this._prevURI=this._htmlMeta.uri(),this._sideBySideEnabled=!0,this._sideBySideOptions=n??{mode:"auto"},this._sideBySideActive=!1,this._lastLayout=null,this._navObserver=new ei((()=>this._checkForURIChange())),this._metaObserver=new MutationObserver((()=>this._checkForURIChange())),this._metaObserver.observe(document.head,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["rel","href","name","content"]}),
119
+ this._flagsChanged=()=>{},this.featureFlags.on("flagsChanged",this._flagsChanged)}anchor(t,e){return function(t,e,n={}){let o=null,i=null,r=null,s=null;for(const t of e)switch(t.type){case"TextPositionSelector":i=t,n.hint=i.start;break;case"TextQuoteSelector":r=t;break;case"RangeSelector":s=t;break;case"MediaTimeSelector":o=t}const a=t=>{if(r?.exact&&t.toString()!==r.exact)throw new Error("quote mismatch");return t};let l=Promise.reject("unable to anchor");if(s){const e=s;l=l.catch((()=>Jo(Wo.fromSelector(t,e),n).then(a)))}if(i){const e=i;l=l.catch((()=>Jo(jo.fromSelector(t,e),n).then(a)))}if(r){const e=r;l=l.catch((()=>Jo(Ko.fromSelector(t,e),n)))}if(o){const e=o;l=l.catch((()=>Qo.fromSelector(t,e).toRange()))}return l}(t,e)}describe(t,e){if(e instanceof Range)return function(t,e){const n=[Qo,Wo,jo,Ko],o=[];for(const i of n)try{const n=i.fromRange(t,e);n&&o.push(n.toSelector())}catch{}return o}(t,e);throw new Error("Unsupported region type")}_checkForURIChange(){const t=this._htmlMeta.uri()
120
+ ;t!==this._prevURI&&(this._prevURI=t,this.emit("uriChanged",t))}getAnnotatableRange(t){try{return Un.trimmedRange(t)}catch(t){if(t instanceof RangeError)return null;throw t}}canStyleClusteredHighlights(){return!0}destroy(){this._deactivateSideBySide(),this._navObserver.disconnect(),this._metaObserver.disconnect(),this.featureFlags.off("flagsChanged",this._flagsChanged),super.destroy()}contentContainer(){return this.container}fitSideBySide(t){this._lastLayout=t;const e=window.innerWidth-t.width,n=this._sideBySideEnabled&&"auto"===this._sideBySideOptions.mode&&t.expanded&&e>=480;return n?this._activateSideBySide(t.width):this._sideBySideActive&&this._deactivateSideBySide(),this._sideBySideActive=n,this.container.classList.toggle("hypothesis-sidebyside-active",this._sideBySideActive),n}sideBySideActive(){return this._sideBySideActive}supportedTools(){return["selection"]}_activateSideBySide(t){const e=t+12,n=t=>parseInt(window.getComputedStyle(t).marginLeft,10);on((()=>{document.body.style.marginLeft="",
121
+ document.body.style.marginRight="";const t=n(document.body);document.body.style.marginRight=`${e}px`;const o=function(t){const e=new Map,n=new Map,o=Qe.join(","),i=Array.from(t.querySelectorAll(o)).map((t=>({rect:t.getBoundingClientRect(),textLength:t.textContent.length}))).filter((({rect:t})=>t.width>0&&t.height>0)).sort(((t,e)=>e.textLength-t.textLength)).slice(0,15);if(i.forEach((({rect:t})=>{let o=e.get(t.left)??0;o+=1,e.set(t.left,o);let i=n.get(t.right)??0;i+=1,n.set(t.right,i)})),0===e.size||0===n.size)return null;const r=[...e.entries()].sort(((t,e)=>e[1]-t[1])),s=[...n.entries()].sort(((t,e)=>e[1]-t[1])),[a]=r[0],[l]=s[0];return{left:a,right:l}}(document.body);if(o){const i=Math.max(0,window.innerWidth-e-o.right);if(i>0){const t=Math.max(0,e-i);document.body.style.marginRight=`${t}px`}n(document.body)>t&&(document.body.style.marginLeft=`${t}px`),o.left<12&&(document.body.style.marginLeft="12px")}else document.body.style.marginLeft="",document.body.style.marginRight=""}))}_deactivateSideBySide(){
122
+ on((()=>{document.body.style.marginLeft="",document.body.style.marginRight=""}))}async getMetadata(){return this._htmlMeta.getDocumentMetadata()}async uri(){return this._htmlMeta.uri()}async scrollToAnchor(t){const e=t.highlights?.[0];e&&await async function(t,{maxDuration:e=500}={}){const n=t.closest("body");n&&"BODY"!==n.tagName&&Object.defineProperty(n,"tagName",{value:"BODY",configurable:!0});const o=t.closest("details");o&&!o.hasAttribute("open")&&(o.open=!0),await new Promise((n=>ri(t,{time:e},n)))}(e)}}var di,ui;var fi=function(){if(ui)return di;ui=1;var t=NaN,e="[object Symbol]",n=/^\s+|\s+$/g,o=/^[-+]0x[0-9a-f]+$/i,i=/^0b[01]+$/i,r=/^0o[0-7]+$/i,s=parseInt,a="object"==typeof At&&At&&At.Object===Object&&At,l="object"==typeof self&&self&&self.Object===Object&&self,c=a||l||Function("return this")(),h=Object.prototype.toString,d=Math.max,u=Math.min,f=function(){return c.Date.now()};function p(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function g(a){if("number"==typeof a)return a
123
+ ;if(function(t){return"symbol"==typeof t||function(t){return!!t&&"object"==typeof t}(t)&&h.call(t)==e}(a))return t;if(p(a)){var l="function"==typeof a.valueOf?a.valueOf():a;a=p(l)?l+"":l}if("string"!=typeof a)return 0===a?a:+a;a=a.replace(n,"");var c=i.test(a);return c||r.test(a)?s(a.slice(2),c?2:8):o.test(a)?t:+a}return di=function(t,e,n){var o,i,r,s,a,l,c=0,h=!1,_=!1,m=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function b(e){var n=o,r=i;return o=i=void 0,c=e,s=t.apply(r,n)}function y(t){var n=t-l;return void 0===l||n>=e||n<0||_&&t-c>=r}function w(){var t=f();if(y(t))return v(t);a=setTimeout(w,function(t){var n=e-(t-l);return _?u(n,r-(t-c)):n}(t))}function v(t){return a=void 0,m&&o?b(t):(o=i=void 0,s)}function x(){var t=f(),n=y(t);if(o=arguments,i=this,l=t,n){if(void 0===a)return function(t){return c=t,a=setTimeout(w,e),h?b(t):s}(l);if(_)return a=setTimeout(w,e),b(l)}return void 0===a&&(a=setTimeout(w,e)),s}return e=g(e)||0,p(n)&&(h=!!n.leading,
124
+ r=(_="maxWait"in n)?d(g(n.maxWait)||0,e):r,m="trailing"in n?!!n.trailing:m),x.cancel=function(){void 0!==a&&clearTimeout(a),c=0,o=l=i=a=void 0},x.flush=function(){return void 0===a?s:v(f())},x},di}(),pi=kt(fi);function gi(t,e,n,o=0){let i=o;for(;i<t.length&&e>0;)n(t[i])&&--e,++i;return i}function _i(t,e,n,o){let i=0;for(let r=n;r<o;r++)e(t[r])&&++i;return i}const mi=new Map;function bi(t,e){const n=t.normalize("NFKD");if(n===t)return{input:t,output:n};const o=[],i=[];let r=0,s=0;for(const n of t){const t=n.codePointAt(0);let a=mi.get(t);if(void 0===a&&(a=n.normalize("NFKD").length,mi.set(t,a)),e.offsets){for(let t=0;t<n.length;t++)i.push(s);s+=a}if(e.reverseOffsets){for(let t=0;t<a;t++)o.push(r);r+=n.length}}return e.offsets&&i.push(n.length),e.reverseOffsets&&o.push(r),{input:t,output:n,reverseOffsets:o,offsets:i}}function yi(t,e,n,o,i,r={}){n=Math.max(0,Math.min(n,t.length)),o=Math.max(n,Math.min(o,t.length));const s=r.normalize?bi(t,{offsets:!0}):{output:t},a=r.normalize?bi(e,{reverseOffsets:!0}):{output:e
125
+ },l=s.offsets?.[n]??n,c=s.offsets?.[o]??o,h=_i(s.output,i,0,l),d=_i(s.output,i,l,c);let u=gi(a.output,h,i);for(;u<a.output.length&&!i(a.output[u]);)++u;const f=gi(a.output,d,i,u);return[a.reverseOffsets?.[u]??u,a.reverseOffsets?.[f]??f]}const wi={INITIAL:0,FINISHED:3},vi=new Map,xi=new Map;function Ci(t,e){return`${t}:${e}`}function Si(t){const e="closest"in t?t:t.parentElement;return e?.closest(".textLayer")??null}function Ai(){return PDFViewerApplication.pdfViewer}async function ki(t){const e=Ai();let n=e.getPageView(t);return n&&n.pdfPage||(n=await new Promise((n=>{const o=()=>{e.eventBus?e.eventBus.off("pagesloaded",o):document.removeEventListener("pagesloaded",o),n(e.getPageView(t))};e.eventBus?e.eventBus.on("pagesloaded",o):document.addEventListener("pagesloaded",o)}))),n}function Mi(t,e){return document.elementsFromPoint(t,e).find((t=>t.classList.contains("textLayer")))}function Ri(t){const e=vi.get(t);if(e)return e;const n=(async()=>{const e=await ki(t);return(await e.pdfPage.getTextContent({
126
+ normalizeWhitespace:!0})).items.map((t=>t.str)).join("")})();return vi.set(t,n),n}async function Ei(t){const e=Ai();let n=0,o=0,i="";for(let r=0;r<e.pagesCount;r++)if(i=await Ri(r),n=o,o+=i.length,o>=t)return{index:r,offset:n,text:i};return{index:e.pagesCount-1,offset:n,text:i}}function Pi(t){switch(t){case" ":case"\f":case"\n":case"\r":case"\t":case"\v":case" ":return!0;default:return!1}}const Ti=t=>!Pi(t);function Ni(t){return void 0!==t.renderingDone?t.renderingDone:!!t.div&&null!==t.div.querySelector(".endOfContent")}async function Li(t,e,n){const[o,i]=await Promise.all([ki(t),Ri(t)]);if(o.renderingState===wi.FINISHED&&o.textLayer&&Ni(o.textLayer)){const t=o.textLayer.textLayerDiv??o.textLayer.div;if(!t)throw new Error("Unable to find PDF.js text layer root");const r=t.textContent,[s,a]=yi(i,r,e,n,Ti,{normalize:!0}),l=Oi(r.slice(s,a)),c=Oi(i.slice(e,n));l.normalize("NFKD")!==c.normalize("NFKD")&&Ao("Text layer text does not match page text. Highlights will be mis-aligned.")
127
+ ;const h=new Vn(t,s),d=new Vn(t,a);return new Un(h,d).toRange()}const r=function(t){let e=t.querySelector($n);return e||(e=document.createElement("span"),e.classList.add("annotator-placeholder"),e.textContent="Loading annotations...",t.appendChild(e),e)}(o.div),s=document.createRange();return s.setStartBefore(r),s.setEndAfter(r),s}function Oi(t){let e="";for(let n=0;n<t.length;n++){const o=t[n];Pi(o)||(e+=o)}return e}async function Ii(t){const e=t.find((t=>"TextQuoteSelector"===t.type));if(!e)throw new Error("No quote selector found");const n=t.find((t=>"TextPositionSelector"===t.type));if(n){try{const{index:t,offset:o,text:i}=await Ei(n.start),r=n.start-o,s=n.end-o,a=i.substring(r,s);if(e.exact!==a)throw new Error("quote mismatch");return await Li(t,r,s)}catch{}try{const t=Ci(e.exact,n.start),o=xi.get(t);if(o){const{pageIndex:t,anchor:e}=o;return await Li(t,e.start,e.end)}}catch{}}return async function(t,e){const n=Ai().pagesCount,o=Array(n).fill(0).map(((t,e)=>e));let i,r;if(e){
128
+ const{index:t,offset:n}=await Ei(e);i=t,r=e-n,o.sort(((e,n)=>Math.abs(e-t)-Math.abs(n-t)))}const s=void 0!==t.prefix?Oi(t.prefix):void 0,a=void 0!==t.suffix?Oi(t.suffix):void 0,l=Oi(t.exact);let c;for(const t of o){const e=await Ri(t),n=Oi(e);let o;void 0!==i&&void 0!==r&&(t<i?o=n.length:t===i?[o]=yi(e,n,r,r,Ti,{normalize:!1}):o=0);const h=zo(n,l,{prefix:s,suffix:a,hint:o});if(h&&(!c||h.score>c.match.score)){const[o,i]=yi(n,e,h.start,h.end,Ti);c={page:t,match:{start:o,end:i,score:h.score}};const r=n.slice(h.start,h.end)===l,d=void 0!==s&&n.slice(Math.max(0,h.start-s.length),h.start)===s,u=void 0!==a&&n.slice(h.end,a.length)===a;if(r&&(d||u||void 0===s&&void 0===a))break}}if(c){const{page:n,match:o}=c;if(e){const i=Ci(t.exact,e);xi.set(i,{pageIndex:n,anchor:o})}return Li(n,o.start,o.end)}throw new Error("Quote not found")}(e,n?.start)}async function Bi(t){const e=t.find((t=>"PageSelector"===t.type)),n=t.find((t=>"ShapeSelector"===t.type));if(n){
129
+ if(!e)throw new Error("Cannot anchor a shape selector without a page");return async function(t,e){const n=Ai();if("number"!=typeof t.index||t.index<0||t.index>=n.pagesCount)throw new Error("PDF page index is invalid");const o=await ki(t.index),i=o.div,r=o.viewport,s=t=>function(t,e,n){return Math.max(Math.min(t,n),e)}(t,0,1);let a;switch(e.shape.type){case"rect":{const t=e.shape;let[n,o]=r.convertToViewportPoint(t.left,t.top),[i,l]=r.convertToViewportPoint(t.right,t.bottom);i<n&&([n,i]=[i,n]),l<o&&([o,l]=[l,o]),a={type:"rect",left:s(n/r.width),top:s(o/r.height),right:s(i/r.width),bottom:s(l/r.height)}}break;case"point":{const t=e.shape,[n,i]=o.viewport.convertToViewportPoint(t.x,t.y);a={type:"point",x:s(n/r.width),y:s(i/r.height)}}break;default:throw new Error("Unsupported shape in shape selector")}return{anchor:i,shape:a,coordinates:"anchor"}}(e,n)}return Ii(t)}function Di(t){try{t=Un.fromRange(t).toRange()}catch{throw new Error("Selection does not contain text")}
130
+ const e=Si(t.startContainer),n=Si(t.endContainer);if(!e||!n)throw new Error("Selection is outside page text");if(e!==n)throw new Error("Selecting across page breaks is not supported");return[t,e]}function Fi(t){const e=t.closest(".page"),n=parseInt(e?.getAttribute("data-page-number")??"");if(!Number.isInteger(n))throw new Error("Unable to get page number from element");return n-1}async function Hi(t){const[e,n]=Di(t),o=Vn.fromPoint(e.startContainer,e.startOffset).relativeTo(n),i=Vn.fromPoint(e.endContainer,e.endOffset).relativeTo(n),r=Fi(n),s=await async function(t){if(t>=Ai().pagesCount)throw new Error("Invalid page index");let e=0;for(let n=0;n<t;n++)e+=(await Ri(n)).length;return e}(r),a=await ki(r);return[{type:"TextPositionSelector",start:s+o.offset,end:s+i.offset},Ko.fromRange(a.div,e).toSelector(),Vi(a,r)]}async function zi(t,e){const n=document.elementsFromPoint(t,e);for(const o of n){if(!o.classList.contains("page"))continue
131
+ ;const n=Fi(o),i=getComputedStyle(o),r=parseFloat(i.borderLeftWidth),s=parseFloat(i.borderTopWidth),a=o.getBoundingClientRect(),l=t-a.left-r,c=e-a.top-s,h=await ki(n),[d,u]=h.getPagePoint(l,c);return{pageIndex:n,x:d,y:u}}return null}function Vi(t,e){return{type:"PageSelector",index:e,label:t.pageLabel??`${e+1}`}}async function Ui(t){const e=t=>{const[e,n,o,i]=t.view;return{left:e,top:i,right:o,bottom:n}},n=(t,e)=>function(t,e){const n=t.ownerDocument.createNodeIterator(t,NodeFilter.SHOW_TEXT),o=[];let i,r;for(;r=n.nextNode();){const t=r,n=t.data.split(/\b/);let s=0;for(const r of n){const n=new Range;n.setStart(t,s);const a=s+r.length;n.setEnd(t,a);const l=n.getBoundingClientRect();$e(l,e)&&(i&&!qe(i,l)&&o.push(" "),o.push(r),i=l),s=a}}return o.join("")}(t,e).slice(0,256);switch(t.type){case"rect":{const[o,i]=await Promise.all([zi(t.left,t.top),zi(t.right,t.bottom)]);if(!o)throw new Error("Top-left point is not in a page");if(!i)throw new Error("Bottom-right point is not in a page")
132
+ ;if(o.pageIndex!==i.pageIndex)throw new Error("Shape must start and end on same page");const r=await ki(o.pageIndex),s={type:"rect",left:o.x,top:o.y,right:i.x,bottom:i.y},a=Mi(t.left,t.top);let l;if(a){l=n(a,new DOMRect(t.left,t.top,t.right-t.left,t.bottom-t.top))}return[Vi(r,o.pageIndex),{type:"ShapeSelector",anchor:"page",shape:s,view:e(r.pdfPage),text:l}]}case"point":{const o=await zi(t.x,t.y);if(!o)throw new Error("Point is not in a page");const i=Mi(t.x,t.y);let r;if(i){r=n(i,new DOMRect(t.x,t.y,1,1))}const s=await ki(o.pageIndex);return[Vi(s,o.pageIndex),{type:"ShapeSelector",anchor:"page",shape:{type:"point",x:o.x,y:o.y},text:r,view:e(s.pdfPage)}]}default:throw new Error("Unsupported shape")}}function $i({children:t}){return St("div",{className:"flex flex-col",children:t})}function qi({info:t}){let e=t.item.title;return t.item.subtitle&&(e+=`: ${t.item.subtitle}`),St("div",{
133
+ className:Tt("h-10 bg-white px-4 text-slate-7 text-annotator-base border-b","grid items-center","grid-cols-[100px_minmax(0,auto)]","2xl:grid-cols-[100px_minmax(0,auto)_minmax(0,auto)] 2xl:gap-x-3"),children:[St("div",{"data-testid":"content-logo",children:t.logo&&St(we,{href:t.logo.link,target:"_blank","data-testid":"logo-link",underline:"none",children:St("img",{alt:t.logo.title,src:t.logo.logo,"data-testid":"logo-image"})})}),St("div",{className:Tt("hidden","2xl:block 2xl:whitespace-nowrap 2xl:overflow-hidden 2xl:text-ellipsis","font-semibold"),"data-testid":"content-container-info",title:t.container.title,children:t.container.title}),St("div",{className:Tt("flex justify-center items-center gap-x-2"),"data-testid":"content-item-info",children:[St("div",{className:Tt("hidden","2xl:block 2xl:grow")}),t.links.previousItem&&St(y,{children:[St(we,{title:"Open previous item",href:t.links.previousItem,underline:"always",target:"_blank","data-testid":"content-previous-link",children:St("div",{
134
+ className:"flex gap-x-1 items-center text-annotator-sm whitespace-nowrap",children:[St(Dt,{className:"w-em h-em"}),St("span",{children:"Previous"})]})}),St("div",{className:"text-annotator-sm",children:"|"})]}),St("div",{className:Tt("min-w-0 whitespace-nowrap overflow-hidden text-ellipsis shrink font-medium"),children:St(we,{title:e,href:t.links.currentItem,"data-testid":"content-item-link",target:"_blank",unstyled:!0,children:e})}),t.links.nextItem&&St(y,{children:[St("div",{className:"text-annotator-sm",children:"|"}),St(we,{title:"Open next item",href:t.links.nextItem,underline:"always",target:"_blank","data-testid":"content-next-link",children:St("div",{className:"flex gap gap-x-1 items-center text-annotator-sm whitespace-nowrap",children:[St("span",{children:"Next"}),St(Ft,{className:"w-em h-em"})]})})]})]})]})}function Wi(){return St("div",{className:"bg-white",role:"alert",children:St("div",{
135
+ className:Tt("flex items-center gap-x-2","border border-yellow-notice bg-yellow-notice/10 text-annotator-base"),children:[St("div",{className:"bg-yellow-notice text-white p-2",children:St(Ht,{className:"text-annotator-xl"})}),St("div",{children:[St("strong",{children:"Text annotation tools are unavailable because this PDF does not contain selectable text."})," ",St(we,{target:"_blank",href:"https://web.hypothes.is/help/how-to-ocr-optimize-pdfs/",underline:"always",children:"Learn more here"}),"."]})]})})}class ji{constructor(t){this._loaded=function(t){return t.initializedPromise?t.initializedPromise:t.initialized?Promise.resolve():new Promise((e=>{const n=setInterval((()=>{t.initialized&&(clearTimeout(n),e())}),5)}))}(t).then((async()=>{const e=await async function(t){return void 0!==t.downloadComplete?t.downloadComplete:(await t.pdfDocument.getDownloadInfo(),!0)}(t);return e?t:new Promise((e=>{const n=()=>{t.eventBus?(t.eventBus.off("documentload",n),
136
+ t.eventBus.off("documentloaded",n)):window.removeEventListener("documentload",n),e(t)};t.eventBus?(t.eventBus.on("documentloaded",n),t.eventBus.on("documentload",n)):window.addEventListener("documentload",n)}))}))}getUri(){return this._loaded.then((t=>{let e=Yi(t);return e||(e=Xi(Ki(t))),e}))}async getMetadata(){const t=await this._loaded,{info:e,contentDispositionFilename:n,metadata:o}=await t.pdfDocument.getMetadata(),i=Ki(t),r=Yi(t),s=o?.get("dc:title");let a;a=s&&"Untitled"!==s?s:e?.Title?e.Title:n||(r?function(t){const e=new URL(t),n=e.pathname.split("/");return n[n.length-1]}(r):"");const l=[{href:Xi(i)}];return r&&l.push({href:r}),{title:a,link:l,documentFingerprint:i}}}function Ki(t){return Array.isArray(t.pdfDocument.fingerprints)?t.pdfDocument.fingerprints[0]:t.pdfDocument.fingerprint}function Xi(t){return`urn:x-pdf:${t}`}function Yi(t){if(!t.url)return null;const e=li(t.url);return 0!==e.indexOf("file://")?e:null}function Gi(t){const e=t.highlights?.[0];return e&&qn(e)}function Qi(t){
137
+ return new Promise((e=>setTimeout(e,t)))}class Ji{constructor(){this._pdfjsContainer=document.querySelector("#outerContainer"),this._contentInfo=null,this._noTextWarning=!1,this._container=null}setContentInfo(t){this._contentInfo=t,this._update()}showNoTextWarning(t){this._noTextWarning=t,this._update()}destroy(){this._container?.destroy()}_update(){if(!(this._noTextWarning||this._contentInfo))return this._container?.destroy(),this._container=null,void(this._pdfjsContainer.style.height="");this._container||(this._container=new Pn("banner",(()=>this._render())),document.body.prepend(this._container.element)),this._container.render();const t=this._container.element.getBoundingClientRect().height;this._pdfjsContainer.style.height=`calc(100% - ${t}px)`}_render(){return St($i,{children:[this._contentInfo&&St(qi,{info:this._contentInfo}),this._noTextWarning&&St(Wi,{})]})}}class Zi extends Me{constructor({annotator:t,features:e,reanchoringMaxWait:n}){super(),this._annotator=t;const o=window,i=o.PDFViewerApplication
138
+ ;this._pdfViewer=i.pdfViewer,this._pdfViewer.viewer.classList.add("has-transparent-text-layer"),this._pdfContainer=i.appConfig?.appContainer??document.body,this._pdfMetadata=new ji(i),this._observer=new MutationObserver(pi((()=>this._update()),100)),this._observer.observe(this._pdfViewer.viewer,{attributes:!0,attributeFilter:["data-loaded"],childList:!0,subtree:!0}),this._reanchoringMaxWait=n??3e3,this._banner=new Ji,this._checkForSelectableText(),this._sideBySideActive=!1,this._updateAnnotationLayerVisibility=()=>{const t=o.getSelection();this._pdfViewer.viewer.classList.toggle("is-selecting",!t.isCollapsed)},this._listeners=new mt,this._listeners.add(document,"selectionchange",this._updateAnnotationLayerVisibility),this._destroyed=!1,this._features=e,this._features.on("flagsChanged",(()=>{this.emit("supportedToolsChanged",this.supportedTools())})),this._pdfViewer.viewer.addEventListener("click",(t=>{const e=t.target;e instanceof HTMLAnchorElement&&(e.target="blank")
139
+ ;oo(t.clientX,t.clientY).length>0&&t.preventDefault()}))}destroy(){this.fitSideBySide({expanded:!1,width:0,toolbarWidth:0,height:window.innerHeight}),this._listeners.removeAll(),this._pdfViewer.viewer.classList.remove("has-transparent-text-layer"),this._observer.disconnect(),this._banner.destroy(),this._destroyed=!0,super.destroy()}uri(){return this._pdfMetadata.getUri()}getMetadata(){return this._pdfMetadata.getMetadata()}showContentInfo(t){this._banner.setContentInfo(t)}anchor(t,e){return Bi(e)}getAnnotatableRange(t){try{const e=Un.trimmedRange(t);if(function(t){try{return Di(t),!0}catch{return!1}}(e))return e}catch(t){if(!(t instanceof RangeError))throw t}return null}canStyleClusteredHighlights(){return!0}describe(t,e){return e instanceof Range?Hi(e):Ui(e)}async _checkForSelectableText(){try{await this.uri()}catch{return}if(!this._destroyed)try{const t=await async function(){const t=Ai();let e=!1;for(let n=0;n<t.pagesCount;n++)if((await Ri(n)).trim().length>0){e=!0;break}return e}()
140
+ ;this._banner.showNoTextWarning(!t)}catch(t){console.warn("Unable to check for text in PDF:",t)}}_update(){const t=[],e=this._pdfViewer.pagesCount;for(let t=0;t<e;t++){const e=this._pdfViewer.getPageView(t);if(e?.textLayer&&Ni(e.textLayer))switch(e.renderingState){case wi.INITIAL:e.textLayer=null;break;case wi.FINISHED:n=e.div,n.querySelector($n)?.remove()}}var n;for(const e of this._annotator.anchors)if(e.highlights){if(t.includes(e.annotation))continue;for(let n=0;n<e.highlights.length;n++){const o=e.highlights[n];if(!document.body.contains(o)){e.highlights.splice(n,1),delete e.region,t.push(e.annotation);break}}}t.map((t=>this._annotator.anchor(t)))}contentContainer(){return document.querySelector("#viewerContainer")}fitSideBySide(t){const e=window.innerWidth-t.width,n=t.expanded&&e>=680,o=n?t.width:t.toolbarWidth;this._pdfContainer.style.width=`calc(100% - ${o}px)`;const i=this._pdfViewer.currentScaleValue;return"auto"!==i&&"page-fit"!==i&&"page-width"!==i||(this._pdfViewer.currentScaleValue=i),
141
+ this._pdfViewer.update(),this._sideBySideActive=n,n}sideBySideActive(){return this._sideBySideActive}supportedTools(){const t=this._features?.flagEnabled("pdf_image_annotation");return t?["selection","rect","point"]:["selection"]}async scrollToAnchor(t){const e=t.annotation,n=Gi(t),o=this._anchorOffset(t);if(null!==o&&(await ai(this.contentContainer(),o),n)){const t=await this._waitForAnnotationToBeAnchored(e,this._reanchoringMaxWait);if(!t)return;const n=this._anchorOffset(t);if(null===n)return;await ai(this.contentContainer(),n)}}async _waitForAnnotationToBeAnchored(t,e){const n=Date.now();let o;do{o=this._annotator.anchors.find((e=>e.annotation===t)),o&&!Gi(o)||(o=null,await Qi(20))}while(!o&&Date.now()-n<e);return o??null}_anchorOffset(t){if(!t.highlights)return null;const e=t.highlights[0];return function(t,e,n={}){let o=0,i=e;for(;i!==t&&t.contains(i);)o+=i.offsetTop,i=i.offsetParent;if("center"===n.position){const n=t.getBoundingClientRect(),i=e.getBoundingClientRect();o-=n.height/2-i.height/2}return o
142
+ }(this.contentContainer(),e,{position:"center"})}async renderToBitmap(t,e){const n=t.target.selector?.find((t=>"ShapeSelector"===t.type)),o=t.target.selector?.find((t=>"PageSelector"===t.type));if(!o||!n)throw new Error("Can only render bitmaps for anchors with shapes");const i=this._pdfViewer.getPageView(o.index);if(!i)throw new Error("Failed to get page view");let r,s,a,l;switch(n.shape.type){case"rect":({left:r,right:s,top:a,bottom:l}=n.shape);break;case"point":{const{x:t,y:e}=n.shape,[o,,c]=i.pdfPage.view,h=.1*Math.abs(c-o);r=t-h,a=e+h,s=t+h,l=e-h}break;default:throw new Error("Unsupported shape type")}s<r&&([r,s]=[s,r]),s=Math.max(s,r+1),a<l&&([a,l]=[l,a]),a=Math.max(a,l+1);const c=i.pdfPage.rotate%360;if(c%90!=0)throw new Error("Page rotation is not a multiple of 90 degrees");let h,d;0===c||180===c?(h=Math.abs(s-r),d=Math.abs(l-a)):(h=Math.abs(l-a),d=Math.abs(s-r));const u=96/72,f=e.devicePixelRatio??1,p=h*u*f,g=h/d,_="number"==typeof e.maxWidth?Math.min(e.maxWidth,p):p,m=_/g,b=i.pdfPage.getViewport({
143
+ scale:1}),y=_/p*u*f,w=new(0,b.constructor)({rotation:c,scale:y,userUnit:b.userUnit,viewBox:[r,l,s,a]}),v=Math.max(_,1),x=Math.max(m,1),C=new OffscreenCanvas(v,x),S=C.getContext("2d"),A=i.pdfPage.render({canvasContext:S,viewport:w});if(await A.promise,"point"===n.shape.type){S.save(),S.scale(y,y);const t=n.shape.x-r,e=n.shape.y-l,o=5;S.strokeStyle="black",S.fillStyle="yellow",S.beginPath(),S.arc(t,e,o,0,2*Math.PI),S.fill(),S.stroke(),S.restore()}return C.transferToImageBitmap()}}function tr(t){if(!t.includes("["))return t;let e="",n=!1,o=!1;for(const i of t)n||"^"!==i?(n||"["!==i?!n&&o&&"]"===i?o=!1:o||(e+=i):o=!0,n=!1):n=!0;return e}function er(t){const e=tr(t),n=e.indexOf("!");return-1===n?e:e.slice(0,n)}class nr{constructor(t,e,n){this._element=t,this._onFrameAdded=e,this._onFrameRemoved=n,this._annotatableFrames=new Set,this._isDisconnected=!1,this._mutationObserver=new MutationObserver(pi((()=>{this._discoverFrames()}),40)),this._discoverFrames(),this._mutationObserver.observe(this._element,{childList:!0,
144
+ subtree:!0,attributeFilter:["enable-annotation"]})}disconnect(){this._isDisconnected=!0,this._mutationObserver.disconnect()}async _addFrame(t){this._annotatableFrames.add(t);try{if(await or(t),this._isDisconnected)return;t.contentWindow.addEventListener("unload",(()=>{this._removeFrame(t)})),this._onFrameAdded(t)}catch{console.warn(`Unable to inject the Hypothesis client (from '${document.location.href}' into a cross-origin frame '${t.src}')`)}}_removeFrame(t){this._annotatableFrames.delete(t),this._onFrameRemoved(t)}_discoverFrames(){const t=new Set(this._element.querySelectorAll("iframe[enable-annotation]"));for(const e of t)this._annotatableFrames.has(e)||this._addFrame(e);for(const e of this._annotatableFrames)t.has(e)||this._removeFrame(e)}}function or(t){return new Promise(((e,n)=>{const o=ir(t,((t,i)=>{o(),i?e(i):n(t)}))}))}function ir(t,e,{pollInterval:n=10}={}){let o,i;const r=new WeakSet,s=()=>{clearTimeout(o),o=void 0},a=()=>{const n=t.contentDocument;if(n){if(!r.has(n)){if(r.add(n),s(),
145
+ !function(t){return"about:blank"===t.contentDocument?.location.href&&t.hasAttribute("src")&&"about:blank"!==t.src}(t)){"interactive"===n.readyState||"complete"===n.readyState?e(null,n):n.addEventListener("DOMContentLoaded",(()=>e(null,n)))}t.contentDocument&&t.contentWindow?.addEventListener("unload",i)}}else{s();const n=t.isConnected?"Frame is cross-origin":"Frame is disconnected";e(new Error(n))}};let l=!1;i=()=>{s(),l||(o=setInterval(a,n))},t.addEventListener("load",a);const c=setTimeout(a,0);return()=>{l=!0,clearTimeout(c),s(),t.removeEventListener("load",a)}}class rr{constructor(t,e){this._config=e,this._frameObserver=new nr(t,(t=>sr(t,e)),(()=>{}))}destroy(){this._frameObserver.disconnect()}}async function sr(t,e,n){if(null!==t.contentDocument.querySelector("script.js-hypothesis-config"))return;await or(t);const{assetRoot:o,notebookAppUrl:i,profileAppUrl:r,sidebarAppUrl:s}=He(document),a={...e,assetRoot:o,notebookAppUrl:i,profileAppUrl:r,sidebarAppUrl:s,subFrameIdentifier:n??Ce(10)
146
+ },l=document.createElement("script");l.className="js-hypothesis-config",l.setAttribute("data-remove-on-unload",""),l.type="application/json",l.innerText=JSON.stringify(a);const c=document.createElement("script");c.async=!0,c.src=e.clientUrl;const h=t.contentDocument;h.body.appendChild(l),h.body.appendChild(c)}class ar{constructor(t,e,n){if(e.length!==n.length)throw new Error("Char boxes length does not match text length");const o=t.parentNode,i=document.createElement("hypothesis-text-layer");o.insertBefore(i,t.nextSibling),o.style.position="relative",i.style.position="absolute",i.style.top="0",i.style.left="0",i.style.color="transparent",i.style.textAlign="left",i.style.mixBlendMode="multiply";const r="sans-serif";i.style.fontSize="16px",i.style.fontFamily=r;const s=document.createElement("canvas").getContext("2d");s.font=`16px ${r}`;const a=(t,e,n="px")=>`calc(var(--${t}-scale) * ${e}${n})`,l=function(t,e){const n=[];let o={text:"",rect:new DOMRect};const i=()=>{o.text.length>0&&(n.push(o),o={text:"",
147
+ rect:new DOMRect})};for(const[n,r]of t.entries()){const t=e[n],s=/\s/.test(t);o.text.length>0&&!qe(o.rect,r)&&i(),o.rect=je(o.rect,r),o.text+=s?" ":t,s&&i()}i();const r=[];let s={words:[],rect:new DOMRect};const a=()=>{s.words.length>0&&(r.push(s),s={words:[],rect:new DOMRect})};for(const t of n){const e=s.words[s.words.length-1];if(e){const n=Ke(e.rect),o=Ke(t.rect).x-n.x;(!qe(e.rect,t.rect)||o<0)&&a()}s.words.push(t),s.rect=je(s.rect,t.rect)}a();const l=[];let c={lines:[],rect:new DOMRect};const h=()=>{c.lines.length>0&&(l.push(c),c={lines:[],rect:new DOMRect})};for(const t of r){const e=c.lines[c.lines.length-1];if(e){const n=Ke(e.rect),o=Ke(t.rect).y-n.y;(!We(e.rect,t.rect)||qe(e.rect,t.rect)||o<0||o>4*t.rect.height)&&h()}c.lines.push(t),c.rect=je(c.rect,t.rect)}return h(),l}(e,n);for(const t of l){const e=document.createElement("hypothesis-text-column");e.style.display="block",e.style.position="absolute",e.style.left=a("x",t.rect.left),e.style.top=a("y",t.rect.top);let n=null;for(const o of t.lines){
148
+ const i=document.createElement("hypothesis-text-line");i.style.display="block",i.style.marginLeft=a("x",o.rect.left-t.rect.left),i.style.height=a("y",o.rect.height),n&&(i.style.marginTop=a("y",o.rect.top-n.rect.bottom)),n=o,i.style.whiteSpace="nowrap";let r=null;for(const t of o.words){const e=document.createElement("hypothesis-text-word");e.style.display="inline-block",e.style.transformOrigin="top left",e.textContent=t.text,r&&(e.style.marginLeft=a("x",t.rect.left-r.rect.right)),r=t,e.style.width=a("x",t.rect.width),e.style.height=a("y",t.rect.height),e.style.whiteSpace="pre";const n=s.measureText(t.text),o=a("x",t.rect.width/n.width,""),l=a("y",t.rect.height/16,"");e.style.transform=`scale(${o}, ${l})`,i.append(e)}e.append(i)}i.append(e)}const c=()=>{const{width:e,height:n}=t.getBoundingClientRect();i.style.width=e+"px",i.style.height=n+"px",i.style.setProperty("--x-scale",`${e}`),i.style.setProperty("--y-scale",`${n}`)};c(),this.container=i,this._updateTextLayerSize=pi(c,{maxWait:50}),
149
+ this._listeners=new mt,"undefined"!=typeof ResizeObserver&&(this._imageSizeObserver=new ResizeObserver((()=>{this._updateTextLayerSize()})),this._imageSizeObserver.observe(t)),this._listeners.add(window,"resize",this._updateTextLayerSize)}updateSync(){this._updateTextLayerSize(),this._updateTextLayerSize.flush()}destroy(){this.container.remove(),this._listeners.removeAll(),this._updateTextLayerSize.cancel(),this._imageSizeObserver?.disconnect()}}function lr(t=document){return t.querySelector("mosaic-book")}function cr(t=window){if(lr(t.document))return"container";const e=t.frameElement?.ownerDocument;return e&&lr(e)?"content":null}class hr{constructor(t){const e=lr();if(!e)throw new Error("Book container element not found");const n=new WeakSet,o=e.shadowRoot,i=()=>{const e=o.querySelector("iframe");e&&!n.has(e)&&(n.add(e),ir(e,((n,o)=>{if(n)return;const i=o.body;i&&!i.querySelector("#page-content")&&sr(e,t,"vitalsource-content")})))};i(),this._frameObserver=new MutationObserver(i),
150
+ this._frameObserver.observe(o,{childList:!0,subtree:!0})}destroy(){this._frameObserver.disconnect()}}function dr(){return document.querySelector("img#pbk-page")}class ur extends Me{constructor(t=document.body,e={}){super();const n=e.bookElement??lr(window.parent.document);if(!n)throw new Error("Failed to find <mosaic-book> element in container frame");this._bookElement=n;const o=new Mo;this._htmlIntegration=new hi({container:t,features:o}),this._listeners=new mt;const i=["mouseup","mousedown","mouseout"];for(const t of i)this._listeners.add(document.documentElement,t,(t=>{t.stopPropagation()}));const r=window.frameElement;r&&function(t){if("no"!==t.getAttribute("scrolling"))return;const e=document.createElement("style");e.textContent="iframe { height: 100% !important; }",t.insertAdjacentElement("beforebegin",e);const n=()=>t.removeAttribute("scrolling");n(),new MutationObserver(n).observe(t,{attributes:!0})}(r);const s=dr(),a=window.innerPageData;if(s&&a){const t=a.glyphs.glyphs.map((t=>{
151
+ const e=t.l/100,n=t.r/100,o=t.t/100,i=t.b/100;return new DOMRect(e,o,n-e,i-o)}));this._textLayer=new ar(s,t,a.words),this._textLayer.container.style.zIndex="100",this._sideBySideActive=!1}}getAnnotatableRange(t){return this._htmlIntegration.getAnnotatableRange(t)}destroy(){this._textLayer&&(this._textLayer.destroy(),this.fitSideBySide({expanded:!1,height:window.innerHeight,width:0,toolbarWidth:0})),this._listeners.removeAll(),this._htmlIntegration.destroy(),super.destroy()}anchor(t,e){return this._htmlIntegration.anchor(t,e)}async describe(t,e){const n=this._htmlIntegration.describe(t,e),{cfi:o,index:i,page:r,title:s,url:a}=await this._getPageInfo({includeTitle:!0,includePageIndex:!0}),l=[{type:"EPUBContentSelector",cfi:o,url:a,title:s}];if("number"==typeof i){const t={type:"PageSelector",index:i,label:r};l.push(t)}return n.push(...l),n}contentContainer(){return this._htmlIntegration.contentContainer()}fitSideBySide(t){const e=dr();if(e&&this._textLayer){
152
+ const n=e.parentElement,o=this._textLayer,i=window.innerWidth-t.width;return this._sideBySideActive=!1,on((()=>{t.expanded&&i>480?(n.style.textAlign="left",e.style.width=`${i}px`,this._sideBySideActive=!0):(n.style.textAlign="",e.style.width=""),o.updateSync()})),this._sideBySideActive}return this._htmlIntegration.fitSideBySide(t)}sideBySideActive(){return"boolean"==typeof this._sideBySideActive?this._sideBySideActive:this._htmlIntegration.sideBySideActive()}supportedTools(){return["selection"]}async getMetadata(){return{title:this._bookElement.getBookInfo().title,link:[]}}navigateToSegment(t){const e=t.target[0].selector?.find((t=>"EPUBContentSelector"===t.type));if(e?.cfi)this._bookElement.goToCfi(e.cfi);else{if(!e?.url)throw new Error("No segment information available");this._bookElement.goToURL(function(t){const e=new URL(t,document.baseURI);return e.pathname+e.search}(e.url))}}persistFrame(){return!0}async _getPageInfo({includeTitle:t=!1,includePageIndex:e=!1}={}){
153
+ const[n,o,i]=await Promise.all([this._bookElement.getCurrentPage(),t?this._bookElement.getTOC():void 0,e?this._bookElement.getPages():void 0]),r=["absoluteURL","cfi"];for(const t of r)if(!(t in n))throw new Error(`Page metadata field "${t}" is missing`);let s;if(o){s=n.chapterTitle;const t=er(n.cfi),e=o.data?.find((e=>er(e.cfi)===t));e&&(s=e.title)}let a=n.index;if(void 0===a&&i){const t=i.data?.findIndex((t=>t.cfi===n.cfi));-1!==t&&(a=t)}return{cfi:n.cfi,index:a,page:n.page,title:s,url:new URL(n.absoluteURL,document.baseURI).toString()}}async _getPageRange(t){let e=[];try{const t=await this._bookElement.getPageBreaks();t.ok&&t.data&&(e=t.data)}catch(t){console.error("Failed to get page breaks",t)}const n=tr(t),o=e.filter((t=>t.cfiWithoutAssertions.split("!")[0]===n));let i;if(o.length>0){i={start:o[0].label,end:o[o.length-1].label}}return i}async segmentInfo(){const{cfi:t,url:e}=await this._getPageInfo();return{cfi:t,pages:await this._getPageRange(t),url:e}}async uri(){
154
+ const t=this._bookElement.getBookInfo().isbn;if(!t)throw new Error("Unable to get book ID from VitalSource");return`https://bookshelf.vitalsource.com/reader/books/${t}`}async scrollToAnchor(t){return this._htmlIntegration.scrollToAnchor(t)}}function fr(t){if(void 0!==window.PDFViewerApplication)return new Zi({annotator:t,features:t.features});return"content"===cr()?new ur(document.body):new hi({features:t.features,sideBySideOptions:t.sideBySide})}function pr(){return St(_e,{classes:"fixed left-[10px] top-[10px]","data-testid":"outside-assignment-notice",status:"notice",variant:"raised",children:"You are outside the page range for this assignment. Annotations made here may not be counted."})}class gr{constructor(t){this._visible=!1,this._container=new Pn("notice",(()=>this._render())),t.appendChild(this._container.element)}destroy(){this._container.destroy()}setVisible(t){this._visible=t,this._container.render()}_render(){return this._visible?St(pr,{}):null}}class _r{constructor(t,e=document){let n=!1
155
+ ;this._pendingCallback=null;const o=(n=10)=>{this._pendingCallback=setTimeout((()=>{t(jn(e.getSelection()))}),n)},i=t=>{if("mousedown"===t.type&&(n=!0),"mouseup"===t.type&&(n=!1),n)return;this._cancelPendingCallback();const e="mouseup"===t.type?10:100;o(e)};this._document=e,this._listeners=new mt,this._listeners.add(e,"selectionchange",i),this._listeners.add(e.body,"mousedown",i),this._listeners.add(e.body,"mouseup",i),o(1)}disconnect(){this._listeners.removeAll(),this._cancelPendingCallback()}_cancelPendingCallback(){this._pendingCallback&&(clearTimeout(this._pendingCallback),this._pendingCallback=null)}}function mr(t,e){if(t===e)return!0;if(t.parent!==e)return!1;if(!t.frameElement)return!1;return t.frameElement.getBoundingClientRect().width/t.parent.innerWidth>=.8}function br(){return function(t,e){const n=new Set,o=new Set;return Yn(t,(t=>{for(;t&&!n.has(t);){n.add(t);const i=e(t);null!=i&&o.add(i),t=t.parentNode}})),[...o]}(jn()??new Range,(t=>t._annotation?.$tag))}function yr(t,e,n){
156
+ return t.getHighlightsFromPoint(e,n).map((t=>t._annotation?.$tag)).filter((t=>void 0!==t))}function wr(t){if(!t.region)return null;if(!function(t){return void 0!==t&&"toRange"in t&&"function"==typeof t.toRange}(t.region))return t.region;try{return t.region.toRange()}catch{return null}}function vr(){document.getSelection()?.removeAllRanges()}class xr extends CustomEvent{constructor(t){super("scrolltorange",{bubbles:!0,cancelable:!0,detail:t}),this._ready=null}get ready(){return this._ready}waitUntil(t){this._ready=t}}class Cr extends Me{constructor(t,e={},n=window){super(),this.element=t,this._contentReady=e.contentReady,this._commentsMode=e.commentsMode??!1,this._hostFrame=n,this._highlightsVisible=!1,this._isAdderVisible=!1,this._informHostOnNextSelectionClear=!0,this.selectedRanges=[],this._outsideAssignmentNotice=null,this._highlighter=new Zn(this.element),this._adder=new Ln(this.element,{onAnnotate:()=>this.createAnnotationFromSelection(),onHighlight:()=>this.createAnnotationFromSelection({highlight:!0}),
157
+ onShowAnnotations:t=>this.selectAnnotations(t,{focusInSidebar:!0})}),this._drawTool=new xo(this.element),this._drawTool.setOnKeyboardModeChange((t=>{this._hostRPC.call("keyboardModeChanged",t)})),this._setupGlobalKeyboardListener(),this._selectionObserver=new _r((t=>{t?this._onSelection(t):this._onClearSelection()})),this.anchors=[],this._annotations=new Set,this._frameIdentifier=e.subFrameIdentifier||null,this._portFinder=new ke({hostFrame:this._hostFrame,source:"guest",sourceId:this._frameIdentifier??void 0}),this.features=new Mo,this._featureFlagsReceived=new Promise((t=>{this.features.on("flagsChanged",t)})),this.sideBySide=e.sideBySide,this._integration=fr(this),this._integration.on("uriChanged",(()=>this._sendDocumentInfo())),e.contentInfoBanner&&this._integration.showContentInfo?.(e.contentInfoBanner),this._integration.canStyleClusteredHighlights?.()&&(this._clusterToolbar=new No(this._integration.contentContainer(),{features:this.features})),
158
+ this._integration.on("supportedToolsChanged",(()=>this._notifySupportedToolsChanged())),this._hostRPC=new De,this._connectHost(n),this._sidebarRPC=new De,this._sidebarLayout=null,this._connectSidebar(),this._bucketBarClient=new ho({contentContainer:this._integration.contentContainer(),hostRPC:this._hostRPC}),this._listeners=new mt,this._setupElementEvents(),this._hoveredAnnotations=new Set}_sideBySideActive(){return"manual"===this.sideBySide?.mode&&this.sideBySide.isActive?this.sideBySide.isActive():this._integration.sideBySideActive()}_setupElementEvents(){this._listeners.add(this.element,"mouseup",(t=>{if(!document.getSelection()?.isCollapsed)return;const{clientX:e,clientY:n,metaKey:o,ctrlKey:i}=t,r=yr(this._highlighter,e,n);if(r.length){const t=o||i;this.selectAnnotations(r,{toggle:t})}})),this._listeners.add(this.element,"pointerdown",(t=>{
159
+ this._sideBySideActive()||t.composedPath().some((t=>t instanceof Element&&t.localName.startsWith("hypothesis-")))||yr(this._highlighter,t.clientX,t.clientY).length||mr(window,this._hostFrame)&&this._sidebarLayout?.expanded&&window.innerWidth-t.clientX<this._sidebarLayout.width||this._sidebarRPC.call("closeSidebar")})),this._listeners.add(this.element,"mouseover",(({clientX:t,clientY:e})=>{const n=yr(this._highlighter,t,e);n.length&&this._sidebarRPC.call("hoverAnnotations",n)})),this._listeners.add(this.element,"mouseout",(()=>{this._highlightsVisible&&this._sidebarRPC.call("hoverAnnotations",[])})),this._listeners.add(this.element,"keydown",(t=>{this._handleShortcut(t)})),this._listeners.add(window,"resize",(()=>this._repositionAdder()))}async getDocumentInfo(){const[t,e,n]=await Promise.all([this._integration.uri(),this._integration.getMetadata(),this._integration.segmentInfo?.()]);return{uri:li(t),metadata:e,segmentInfo:n,persistent:this._integration.persistFrame?.()??!1}}async _sendDocumentInfo(){
160
+ this._integration.waitForFeatureFlags?.()&&await this._featureFlagsReceived;const t=await this.getDocumentInfo();this._sidebarRPC.call("documentInfoChanged",t)}_repositionAdder(){if(!this._isAdderVisible)return;const t=jn();t&&this._onSelection(t)}async _connectHost(t){this._hostRPC.on("clearSelection",(()=>{jn()&&(this._informHostOnNextSelectionClear=!1,vr())})),this._hostRPC.on("createAnnotation",(({tool:t})=>t?("rect"===t&&void 0===this._pendingKeyboardMode&&(this._pendingKeyboardMode="move"),this.createAnnotation(t)):(this._drawTool.cancel(),null))),this._hostRPC.on("hoverAnnotations",(t=>this._hoverAnnotations(t))),this._hostRPC.on("scrollToAnnotation",(t=>{this._scrollToAnnotation(t)})),this._hostRPC.on("selectAnnotations",((t,e)=>this.selectAnnotations(t,{toggle:e}))),this._hostRPC.on("setKeyboardMode",(({mode:t})=>{["move","resize","rect"].includes(t)&&this._drawTool.setKeyboardMode(t)})),this._hostRPC.on("activateMoveMode",(()=>{this._activateToolWithMoveMode("rect")})),
161
+ this._hostRPC.on("activatePointMoveMode",(()=>{this._activateToolWithMoveMode("point")})),this._hostRPC.on("sidebarLayoutChanged",(e=>{mr(window,t)&&this.fitSideBySide(e),this.element.dispatchEvent(new Co({sidebarLayout:e,sideBySideActive:this._sideBySideActive()}))})),this._hostRPC.on("close",(()=>this.emit("hostDisconnected"))),this._notifySupportedToolsChanged();const e=await this._portFinder.discover("host");this._hostRPC.connect(e)}_notifySupportedToolsChanged(){this._hostRPC.call("supportedToolsChanged",this._integration.supportedTools())}async _scrollToAnchor(t){const e=wr(t);if(!e)return;let n;e instanceof Range?n=e:(n=new Range,n.selectNodeContents(e.anchor));const o=new xr(n);this.element.dispatchEvent(o)&&(await o.ready,await this._integration.scrollToAnchor(t))}async _scrollToAnnotation(t){const e=this.anchors.find((e=>e.annotation.$tag===t));e?.highlights&&await this._scrollToAnchor(e)}async _connectSidebar(){this._sidebarRPC.on("featureFlagsUpdated",(t=>this.features.update(t))),
162
+ this._sidebarRPC.on("shortcutsUpdated",(t=>{wn(t)})),this._sidebarRPC.on("hoverAnnotations",(t=>this._hoverAnnotations(t))),this._sidebarRPC.on("scrollToAnnotation",(t=>{this._scrollToAnnotation(t)})),this._sidebarRPC.on("setHighlightsVisible",(t=>{this.setHighlightsVisible(t,!1)})),this._sidebarRPC.on("deleteAnnotation",(t=>this.detach(t))),this._sidebarRPC.on("getDocumentInfo",(async t=>t(await this.getDocumentInfo()))),this._sidebarRPC.on("loadAnnotations",(async t=>{try{await Promise.all(t.map((t=>this.anchor(t))))}catch(t){console.warn("Failed to anchor annotations:",t)}})),this._sidebarRPC.on("showContentInfo",(t=>this._integration.showContentInfo?.(t))),this._sidebarRPC.on("setOutsideAssignmentNoticeVisible",(t=>{this._setOutsideAssignmentNoticeVisible(t)})),this._sidebarRPC.on("navigateToSegment",(t=>this._integration.navigateToSegment?.(t))),this._sidebarRPC.on("renderThumbnail",((t,e,n)=>{(async()=>{
163
+ if(!this._integration.renderToBitmap)throw new Error("Thumbnail rendering not supported for document type");const n=this.anchors.find((e=>e.annotation.$tag===t));if(!n)throw new Error("Annotation not anchored in guest");return this._integration.renderToBitmap(n,e)})().then((t=>n({ok:!0,value:t}))).catch((t=>n({ok:!1,error:t.message})))})),this._portFinder.discover("sidebar").then((t=>{this._sidebarRPC.connect(t)})),this._sendDocumentInfo()}destroy(){this._drawTool.destroy(),this._portFinder.destroy(),this._hostRPC.destroy(),this._sidebarRPC.destroy(),this._listeners.removeAll(),this._selectionObserver.disconnect(),this._adder.destroy(),this._bucketBarClient.destroy(),this._clusterToolbar?.destroy(),this._outsideAssignmentNotice?.destroy(),this._highlighter.removeAllHighlights(),this._integration.destroy(),this._globalKeyboardListenerCleanup?.(),super.destroy()}_isKeyboardAnnotationModeEnabled(){return this.features.flagEnabled("vpat_keyboard")}_setupGlobalKeyboardListener(){const t=t=>{if(Ge(t.target))return
164
+ ;if(!this._isKeyboardAnnotationModeEnabled())return;const e=yn(),n=this._integration.supportedTools(),o=n.includes("rect"),i=n.includes("point"),r=e.activateRectMove;if(r&&un(t,r)&&o){t.preventDefault(),t.stopPropagation();return void(this._drawTool.getKeyboardModeState().keyboardActive?this._drawTool.setKeyboardMode("move"):(this._pendingKeyboardMode="move",this.createAnnotation("rect").catch((()=>{this._pendingKeyboardMode=void 0}))))}const s=e.activateRectResize;if(s&&un(t,s)&&o){t.preventDefault(),t.stopPropagation();return void(this._drawTool.getKeyboardModeState().keyboardActive?this._drawTool.setKeyboardMode("resize"):(this._pendingKeyboardMode="resize",this.createAnnotation("rect").catch((()=>{this._pendingKeyboardMode=void 0}))))}const a=e.activatePoint;if(a&&un(t,a)&&i){t.preventDefault(),t.stopPropagation();this._drawTool.getKeyboardModeState().keyboardActive||(this._pendingKeyboardMode="move",this.createAnnotation("point").catch((()=>{this._pendingKeyboardMode=void 0})))}else;}
165
+ ;document.body.addEventListener("keydown",t),this._globalKeyboardListenerCleanup=()=>{document.body.removeEventListener("keydown",t)}}async anchor(t){this._contentReady&&(await this._contentReady,this._contentReady=void 0);const e=t=>{const e=wr(t);if(!e)return;let n;n=e instanceof Range?this._highlighter.highlightRange(e,t.annotation?.$cluster):this._highlighter.highlightShape(e),n.forEach((e=>{e._annotation=t.annotation})),t.highlights=n,this._hoveredAnnotations.has(t.annotation.$tag)&&this._highlighter.setHighlightsFocused(n,!0)};this.detach(t.$tag,!1),this._annotations.add(t.$tag),t.target||(t.target=[]);const n=await Promise.all(t.target.map((async e=>{if(!e.selector||!e.selector.some((t=>"TextQuoteSelector"===t.type||"ShapeSelector"===t.type)))return{annotation:t,target:e};let n;try{const o=await this._integration.anchor(this.element,e.selector);if(o instanceof Range){const i=Un.fromRange(o);n={annotation:t,target:e,region:i}}else n={annotation:t,target:e,region:o}}catch{n={annotation:t,target:e}}
166
+ return n})));if(!this._annotations.has(t.$tag))return[];for(const t of n)e(t);return t.$orphan=n.length>0&&n.every((t=>t.target.selector&&!t.region)),this._updateAnchors(this.anchors.concat(n),!0),this._sidebarRPC.call("syncAnchoringStatus",t),n}detach(t,e=!0){this._annotations.delete(t);const n=[];for(const e of this.anchors)e.annotation.$tag!==t?n.push(e):e.highlights&&this._highlighter.removeHighlights(e.highlights);this._updateAnchors(n,e)}_updateAnchors(t,e){this.anchors=t,this._clusterToolbar?.scheduleClusterUpdates(),e&&this._bucketBarClient.update(this.anchors)}async createAnnotation(t){if("selection"===t)return this.createAnnotationFromSelection();if(!["rect","point"].includes(t))throw new Error("Unsupported annotation tool");{let e=!1;try{this._hostRPC.call("activeToolChanged",t);const e=this._pendingKeyboardMode;this._pendingKeyboardMode=void 0;const n=await this._drawTool.draw(t,e),o=await this.getDocumentInfo(),i=[{source:o.uri,selector:await this._integration.describe(this.element,n)}],r={
167
+ uri:o.uri,document:o.metadata,target:i,$tag:"a:"+Ce(8)};return this._sidebarRPC.call("createAnnotation",r),this.anchor(r),r}catch(t){if(t instanceof vo&&["canceled","restarted"].includes(t.kind))return e="restarted"===t.kind,null;throw t}finally{e||this._hostRPC.call("activeToolChanged",null)}}}_activateToolWithMoveMode(t){this._drawTool.getKeyboardModeState().keyboardActive?this._drawTool.setKeyboardMode("move"):(this._pendingKeyboardMode="move",this.createAnnotation(t).catch((()=>{this._pendingKeyboardMode=void 0})))}async createAnnotationFromSelection({highlight:t=!1}={}){const e=this.selectedRanges;this.selectedRanges=[];const n=await this.getDocumentInfo(),o=this.element,i=(await Promise.all(e.map((t=>this._integration.describe(o,t))))).map((t=>({source:n.uri,selector:t}))),r={uri:n.uri,document:n.metadata,target:i,$highlight:t,$cluster:t?"user-highlights":"user-annotations",$tag:"a:"+Ce(8)};return this._sidebarRPC.call("createAnnotation",r),this.anchor(r),vr(),r}_hoverAnnotations(t){
168
+ this._hoveredAnnotations.clear(),t.forEach((t=>this._hoveredAnnotations.add(t)));for(const e of this.anchors)if(e.highlights){const n=t.includes(e.annotation.$tag);this._highlighter.setHighlightsFocused(e.highlights,n)}this._sidebarRPC.call("hoverAnnotations",t)}_onSelection(t){const e=this._integration.getAnnotatableRange(t);if(!e)return void this._onClearSelection();const n=document.getSelection(),o=Kn(n),i=Gn(n);i?(this.selectedRanges=[e],this._hostRPC.call("textSelected"),this._commentsMode||(this._adder.annotationsForSelection=br(),this._isAdderVisible=!0,this._adder.show(i,o))):this._onClearSelection()}_onClearSelection(){this._isAdderVisible=!1,this._adder.hide(),this.selectedRanges=[],this._informHostOnNextSelectionClear&&this._hostRPC.call("textUnselected"),this._informHostOnNextSelectionClear=!0}selectAnnotations(t,{toggle:e=!1,focusInSidebar:n=!1}={}){e?this._sidebarRPC.call("toggleAnnotationSelection",t):this._sidebarRPC.call("showAnnotations",t,n),this._sidebarRPC.call("openSidebar")}
169
+ setHighlightsVisible(t,e=!0){this._highlighter.setHighlightsVisible(t),this._highlightsVisible=t,e&&this._hostRPC.call("highlightsVisibleChanged",t)}get highlightsVisible(){return this._highlightsVisible}fitSideBySide(t){this._sidebarLayout=t,this._integration.fitSideBySide(t)}get hoveredAnnotationTags(){return this._hoveredAnnotations}_handleShortcut(t){const e=yn().toggleHighlights;e&&un(t,e)&&this.setHighlightsVisible(!this._highlightsVisible&&!this._commentsMode)}_setOutsideAssignmentNoticeVisible(t){this._outsideAssignmentNotice||(this._outsideAssignmentNotice=new gr(this.element)),this._outsideAssignmentNotice.setVisible(t)}}function Sr(t,e){const n=new URL(t),o=new URLSearchParams;return o.append("config",JSON.stringify(e)),n.hash=o.toString(),n.toString()}function Ar(t,e){const n={};for(const[t,o]of Object.entries(e))"notebookAppUrl"!==t&&"sidebarAppUrl"!==t&&null!=o&&(n[t]=o);n.origin=new URL(t).origin,n.version="1.1749.0";const o=new URL(window.location.href);if(o.hash="",n.hostURL=o.toString(),
170
+ Array.isArray(n.services)&&n.services?.length>0){const t=n.services[0];t.onLoginRequest&&(t.onLoginRequestProvided=!0),t.onLogoutRequest&&(t.onLogoutRequestProvided=!0),t.onSignupRequest&&(t.onSignupRequestProvided=!0),t.onProfileRequest&&(t.onProfileRequestProvided=!0),t.onHelpRequest&&(t.onHelpRequestProvided=!0)}return n}function kr({closed:t,onClose:e,children:n,className:o,"data-testid":i,"aria-label":r}){const s=it(null);return nt((()=>{t?s.current?.close():s.current?.showModal()}),[t]),nt((()=>{const t=s.current;return t?.addEventListener("cancel",e),()=>{t?.removeEventListener("cancel",e)}}),[e]),St("dialog",{ref:s,className:Tt("relative m-5 w-full h-full backdrop:bg-black/50",o),"data-testid":i,"aria-label":r,children:n})}function Mr({closed:t,children:e,className:n,...o}){return St("div",{...o,className:Tt("fixed z-max top-0 left-0 right-0 bottom-0 p-3 bg-black/50",{hidden:t}),children:St("div",{className:Tt("relative w-full h-full",n),children:e})})}function Rr({document_:t=document,...e}){
171
+ return St(rt((()=>function(t){return"function"==typeof t.createElement("dialog").showModal}(t)?kr:Mr),[t]),{...e})}function Er({config:t,groupId:e}){return St("iframe",{title:"Hypothesis annotation notebook",className:"h-full w-full border-0",allow:"fullscreen; clipboard-write",src:Sr(t.notebookAppUrl,{...Ar(t.notebookAppUrl,t),group:e})})}function Pr({eventBus:t,config:e}){const[n,o]=et(0),[i,r]=et(!0),[s,a]=et(null),l=it(""),c=it(null);nt((()=>(l.current=document.body.style.overflow,()=>{document.body.style.overflow=l.current})),[]),nt((()=>{document.body.style.overflow=i?l.current:"hidden"}),[i]),nt((()=>{const e=t.createEmitter();return e.subscribe("openNotebook",(t=>{r(!1),o((t=>t+1)),a(t)})),c.current=e,()=>{e.destroy()}}),[t]);const h=st((()=>{r(!0),c.current?.publish("closeNotebook")}),[]);return null===s?null:St(Rr,{closed:i,onClose:h,"data-testid":"notebook-outer","aria-label":"Hypothesis notebook",children:[St("div",{className:"absolute right-0 m-3",children:St(oe,{title:"Close notebook",onClick:h,
172
+ variant:"dark",classes:Tt("!bg-transparent enabled:hover:!bg-grey-3"),"data-testid":"close-button",children:St(It,{className:"w-4 h-4"})})}),St(Er,{config:e,groupId:s},n)]})}class Tr{constructor(t,e,n){this._container=new Pn("notebook",(()=>St(Pr,{eventBus:e,config:n}))),t.append(this._container.element),this._container.render()}destroy(){this._container.destroy()}}function Nr({eventBus:t,config:e}){const[n,o]=et(!0),i=it(null);nt((()=>{const e=t.createEmitter();return e.subscribe("openProfile",(()=>{o(!1)})),i.current=e,()=>{e.destroy()}}),[t]);const r=()=>{o(!0),i.current?.publish("closeProfile")};return n?null:St(Rr,{closed:n,onClose:r,"data-testid":"profile-outer","aria-label":"Hypothesis profile",children:[St("div",{className:"absolute right-0 m-3",children:St(oe,{title:"Close profile dialog",onClick:r,variant:"dark",classes:Tt("!bg-transparent enabled:hover:!bg-grey-3"),children:St(It,{className:"w-4 h-4"})})}),St("iframe",{title:"Hypothesis profile",className:"h-full w-full border-0",
173
+ src:e.profileAppUrl})]})}class Lr{constructor(t,e,n){this._container=new Pn("profile",(()=>St(Nr,{eventBus:e,config:n}))),t.append(this._container.element),this._container.render()}destroy(){this._container.destroy()}}function Or({above:t,below:e,buckets:n,onFocusAnnotations:o,onScrollToAnnotation:i,onSelectAnnotations:r}){const s=t.anchors.length>0,a=e.anchors.length>0,l=t=>t.anchors.map((t=>t.tag));return St("ul",{className:"relative",children:[s&&St("li",{className:"absolute right-0 pointer-events-auto mt-[-11px]",style:{top:t.position},children:St(ve,{"data-testid":"up-navigation-button",direction:"up",onClick:()=>{const e=[...t.anchors].sort(((t,e)=>t.bottom-e.bottom)),n=e[e.length-1];i(n.tag)},onBlur:()=>o([]),onFocus:()=>o(l(t)),onMouseEnter:()=>o(l(t)),onMouseOut:()=>o([]),title:`Go up to next annotations (${t.anchors.length})`,children:t.anchors.length})}),n.map(((t,e)=>St("li",{className:"absolute right-0 pointer-events-auto mt-[-8px]",style:{top:t.position},children:St(ve,{direction:"left",
174
+ onClick:e=>r(l(t),e.metaKey||e.ctrlKey),onBlur:()=>o([]),onFocus:()=>o(l(t)),onMouseEnter:()=>o(l(t)),onMouseOut:()=>o([]),title:`Select nearby annotations (${t.anchors.length})`,children:t.anchors.length})},e))),a&&St("li",{className:"absolute right-0 pointer-events-auto",style:{top:e.position},children:St(ve,{"data-testid":"down-navigation-button",direction:"down",onClick:()=>{const t=[...e.anchors].sort(((t,e)=>t.top-e.top)),n=t[0];i(n.tag)},onBlur:()=>o([]),onFocus:()=>o(l(e)),onMouseEnter:()=>o(l(e)),onMouseOut:()=>o([]),title:`Go up to next annotations (${e.anchors.length})`,children:e.anchors.length})})]})}class Ir{constructor(t,{onFocusAnnotations:e,onScrollToAnnotation:n,onSelectAnnotations:o}){this._positions=[],this._container=new Pn("bucket-bar",(()=>this._render())),Object.assign(this._container.element.style,{display:"block",flexGrow:"1",width:"100%"}),t.appendChild(this._container.element),this._onFocusAnnotations=e,this._onScrollToAnnotation=n,this._onSelectAnnotations=o,
175
+ this._container.render()}destroy(){this._container.destroy()}update(t){this._positions=t,this._container.render()}_render(){const t=function(t,e){const n=[],o=[],i=[];let r=null;function s(t){const{bottom:e,top:n}=t;return{bottom:e,position:n+(e-n)/2,anchors:[t],top:n}}const a=e.getBoundingClientRect(),l=t.map((t=>({tag:t.tag,top:t.top-a.top,bottom:t.bottom-a.top})));for(const t of l){const e=(t.top+t.bottom)/2;if(e<30){n.push(t);continue}if(e>a.height-30){o.push(t);continue}if(!r){r=s(t);continue}const l=t.top>r.top&&t.bottom<r.bottom;if(t.top-r.bottom>60&&!l)i.push(r),r=s(t);else{const e=t.bottom>r.bottom?t.bottom:r.bottom,n=e-r.top;r.anchors.push(t),r.bottom=e,r.position=r.top+n/2}}return r&&i.push(r),{above:{anchors:n,position:25},below:{anchors:o,position:a.height-30},buckets:i}}(this._positions,this._container.element);return St(Or,{above:t.above,below:t.below,buckets:t.buckets,onFocusAnnotations:t=>this._onFocusAnnotations(t),onScrollToAnnotation:t=>this._onScrollToAnnotation(t),
176
+ onSelectAnnotations:(t,e)=>this._onSelectAnnotations(t,e)})}}function Br({emitter:t}){const[e,n]=et([]),o=st((t=>n((e=>[...e,t]))),[]),i=st((t=>n((e=>e.filter((e=>e.id!==t))))),[]);return nt((()=>(t.subscribe("toastMessageAdded",o),t.subscribe("toastMessageDismissed",i),()=>{t.unsubscribe("toastMessageAdded",o),t.unsubscribe("toastMessageDismissed",i)})),[t,i,o]),St(ye,{messages:e,onMessageDismiss:i})}function Dr(t){return St("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",...t,children:[St("g",{"fill-rule":"evenodd",children:[St("path",{fill:"none",d:"M0 0h16v16H0z"}),St("path",{fill:"currentColor","clip-rule":"evenodd",
176
177
  d:"M2.5 0h-1A1.5 1.5 0 0 0 0 1.5v1 a1.5 1.5 0 0 0 1 1.415v8.17 A1.5 1.5 0 0 0 0 13.5v1 A1.5 1.5 0 0 0 1.5 16h1 a1.5 1.5 0 0 0 1.415-1h8.17 a1.5 1.5 0 0 0 1.415 1h1 a1.5 1.5 0 0 0 1.5-1.5v-1 a1.5 1.5 0 0 0-1-1.415v-8.17 A1.5 1.5 0 0 0 16 2.5v-1 A1.5 1.5 0 0 0 14.5 0h-1 a1.5 1.5 0 0 0-1.415 1h-8.17 A1.5 1.5 0 0 0 2.5 0 m9.585 13 c.151-.426.489-.764.915-.915v-8.17 A1.5 1.5 0 0 1 12.085 3h-8.17 c-.151.426-.489.764-.915.915v8.17 c.426.151.764.489.915.915z M1 1.5 a.5.5 0 0 1 .5-.5h1 a.5.5 0 0 1 .5.5v1 a.5.5 0 0 1-.5.5h-1 a.5.5 0 0 1-.5-.5z M1.5 13 a.5.5 0 0 0-.5.5v1 a.5.5 0 0 0 .5.5h1 a.5.5 0 0 0 .5-.5v-1 a.5.5 0 0 0-.5-.5z M13 1.5 a.5.5 0 0 1 .5-.5h1 a.5.5 0 0 1 .5.5v1 a.5.5 0 0 1-.5.5h-1 a.5.5 0 0 1-.5-.5z m.5 11.5 a.5.5 0 0 0-.5.5v1 a.5.5 0 0 0 .5.5h1 a.5.5 0 0 0 .5-.5v-1 a.5.5 0 0 0-.5-.5z"})]}),St("g",{transform:"translate(3 3) scale(0.0833)",stroke:"currentColor","stroke-width":"10","stroke-linecap":"round","stroke-linejoin":"round",fill:"none",children:[St("path",{d:"M60 15 L60 48"}),St("path",{
177
- d:"M45 30 L60 15 L75 30"}),St("path",{d:"M60 72 L60 105"}),St("path",{d:"M45 90 L60 105 L75 90"}),St("path",{d:"M15 60 L48 60"}),St("path",{d:"M30 45 L15 60 L30 75"}),St("path",{d:"M72 60 L105 60"}),St("path",{d:"M90 45 L105 60 L90 75"})]})]})}function Dr(t){return St("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",...t,children:[St("g",{"fill-rule":"evenodd",children:[St("path",{fill:"none",d:"M0 0h16v16H0z"}),St("path",{fill:"currentColor","clip-rule":"evenodd",
178
+ d:"M45 30 L60 15 L75 30"}),St("path",{d:"M60 72 L60 105"}),St("path",{d:"M45 90 L60 105 L75 90"}),St("path",{d:"M15 60 L48 60"}),St("path",{d:"M30 45 L15 60 L30 75"}),St("path",{d:"M72 60 L105 60"}),St("path",{d:"M90 45 L105 60 L90 75"})]})]})}function Fr(t){return St("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",...t,children:[St("g",{"fill-rule":"evenodd",children:[St("path",{fill:"none",d:"M0 0h16v16H0z"}),St("path",{fill:"currentColor","clip-rule":"evenodd",
178
179
  d:"M2.5 0h-1A1.5 1.5 0 0 0 0 1.5v1 a1.5 1.5 0 0 0 1 1.415v8.17 A1.5 1.5 0 0 0 0 13.5v1 A1.5 1.5 0 0 0 1.5 16h1 a1.5 1.5 0 0 0 1.415-1h8.17 a1.5 1.5 0 0 0 1.415 1h1 a1.5 1.5 0 0 0 1.5-1.5v-1 a1.5 1.5 0 0 0-1-1.415v-8.17 A1.5 1.5 0 0 0 16 2.5v-1 A1.5 1.5 0 0 0 14.5 0h-1 a1.5 1.5 0 0 0-1.415 1h-8.17 A1.5 1.5 0 0 0 2.5 0 m9.585 13 c.151-.426.489-.764.915-.915v-8.17 A1.5 1.5 0 0 1 12.085 3h-8.17 c-.151.426-.489.764-.915.915v8.17 c.426.151.764.489.915.915z M1 1.5 a.5.5 0 0 1 .5-.5h1 a.5.5 0 0 1 .5.5v1 a.5.5 0 0 1-.5.5h-1 a.5.5 0 0 1-.5-.5z M1.5 13 a.5.5 0 0 0-.5.5v1 a.5.5 0 0 0 .5.5h1 a.5.5 0 0 0 .5-.5v-1 a.5.5 0 0 0-.5-.5z M13 1.5 a.5.5 0 0 1 .5-.5h1 a.5.5 0 0 1 .5.5v1 a.5.5 0 0 1-.5.5h-1 a.5.5 0 0 1-.5-.5z m.5 11.5 a.5.5 0 0 0-.5.5v1 a.5.5 0 0 0 .5.5h1 a.5.5 0 0 0 .5-.5v-1 a.5.5 0 0 0-.5-.5z"})]}),St("g",{transform:"translate(3 3) scale(0.0833)",stroke:"currentColor","stroke-width":"18","stroke-linecap":"round","stroke-linejoin":"round",fill:"none",children:[St("path",{d:"M30 30 L55 55"}),St("path",{
179
- d:"M65 65 L90 90"}),St("path",{d:"M30 45 L30 30 L45 30"}),St("path",{d:"M75 90 L90 90 L90 75"})]})]})}function Fr(t,e,n){return t&&"rect"===e?"move"===n?"Move mode (Ctrl+Shift+Y) - Click to switch to Resize mode":"resize"===n?"Resize mode (Ctrl+Shift+J) - Click to switch to Rectangle mode":"Rectangle mode - Click to switch to Move mode":"Rectangle annotation"}function Hr(t,e){return n=>{"Enter"===n.key&&t&&!e&&(n.preventDefault(),n.stopPropagation(),t())}}function zr({mode:t}){return St("move"===t?Br:"resize"===t?Dr:Zt,{})}function Vr({icon:t,pressedBackground:e=!0,...n}){return St(ee,{classes:Tt("justify-center rounded","w-[30px] h-[30px] touch:h-[40px]","shadow border bg-white text-grey-6 hover:text-grey-9",e&&"aria-pressed:bg-grey-3"),...n,size:"custom",variant:"custom",children:St(t,{})})}function Ur({highlightsVisible:t}){return St("div",{className:"sr-only",role:"status","data-testid":"toolbar-status",children:t?"Highlights visible":"Highlights hidden"})}
180
- function $r({activeTool:t=null,closeSidebar:e,createAnnotation:n,isSidebarOpen:o,sidebarContainerId:i,newAnnotationType:r,showHighlights:s,supportedTools:a=["selection"],toggleHighlights:l,toggleSidebar:c,toggleSidebarRef:h,useMinimalControls:d=!1,keyboardMode:u=null,keyboardActive:f=!1,onModeClick:p,onActivateMoveMode:g,onActivatePointMoveMode:_}){return St("div",{className:Tt({"absolute right-full":d,"relative right-[11px]":!d},"w-[33px] z-2","text-px-base leading-none"),children:[d&&o&&St(ee,{classes:Tt("transition-colors focus-visible-ring ring-inset","w-[27px] h-[27px] mt-[140px] ml-[6px]","flex items-center justify-center bg-white border","text-grey-6 hover:text-grey-9 transition-colors","border-r-0","shadow-sidebar"),title:"Close annotation sidebar",onClick:e,unstyled:!0,children:St(It,{})}),!d&&St(y,{children:[St(ee,{classes:Tt("transition-colors focus-visible-ring ring-inset","h-[40px] w-[33px] pl-[6px] rounded-bl","bg-white text-grey-6 hover:text-grey-9","border-l border-b"),elementRef:h,
181
- title:"Annotation sidebar",expanded:o,"aria-controls":i,onClick:c,unstyled:!0,children:St(o?Ft:Dt,{})}),St("div",{className:"space-y-[6px] mt-[8px]",children:[St(Vr,{title:"Show highlights",icon:s?te:$t,pressed:s,pressedBackground:!1,onClick:l}),a.includes("selection")&&St(Vr,{"data-testid":"text-annotation",title:"note"===r?"New page note":"New annotation",icon:"note"===r?Kt:Ot,onClick:()=>n("selection")}),a.includes("rect")&&St(Vr,{"data-testid":"rect-annotation",pressed:"rect"===t,title:Fr(f,t,u??null),icon:f&&"rect"===t?()=>St(zr,{mode:u??"rect"}):Zt,onClick:()=>{f&&"rect"===t?p?.():n("rect"===t?null:"rect")},onKeyDown:Hr(g,f)}),a.includes("point")&&St(Vr,{"data-testid":"point-annotation",pressed:"point"===t,title:"Pin annotation",icon:Xt,onClick:()=>n("point"===t?null:"point"),onKeyDown:Hr(_,f)})]}),St(Ur,{highlightsVisible:s})]})]})}class qr{constructor(t,e){const{createAnnotation:n,setSidebarOpen:o,setHighlightsVisible:i}=e;this.container=t,this._activeTool=null,this._useMinimalControls=!1,
180
+ d:"M65 65 L90 90"}),St("path",{d:"M30 45 L30 30 L45 30"}),St("path",{d:"M75 90 L90 90 L90 75"})]})]})}function Hr(t,e,n){return t&&"rect"===e?"move"===n?"Move mode (Ctrl+Shift+Y) - Click to switch to Resize mode":"resize"===n?"Resize mode (Ctrl+Shift+J) - Click to switch to Rectangle mode":"Rectangle mode - Click to switch to Move mode":"Rectangle annotation"}function zr(t,e){return n=>{"Enter"===n.key&&t&&!e&&(n.preventDefault(),n.stopPropagation(),t())}}function Vr({mode:t}){return St("move"===t?Dr:"resize"===t?Fr:Zt,{})}function Ur({icon:t,pressedBackground:e=!0,...n}){return St(ee,{classes:Tt("justify-center rounded","w-[30px] h-[30px] touch:h-[40px]","shadow border bg-white text-grey-6 hover:text-grey-9",e&&"aria-pressed:bg-grey-3"),...n,size:"custom",variant:"custom",children:St(t,{})})}function $r({highlightsVisible:t}){return St("div",{className:"sr-only",role:"status","data-testid":"toolbar-status",children:t?"Highlights visible":"Highlights hidden"})}
181
+ function qr({activeTool:t=null,closeSidebar:e,createAnnotation:n,isSidebarOpen:o,sidebarContainerId:i,newAnnotationType:r,showHighlights:s,supportedTools:a=["selection"],toggleHighlights:l,toggleSidebar:c,toggleSidebarRef:h,useMinimalControls:d=!1,keyboardMode:u=null,keyboardActive:f=!1,onModeClick:p,onActivateMoveMode:g,onActivatePointMoveMode:_}){return St("div",{className:Tt({"absolute right-full":d,"relative right-[11px]":!d},"w-[33px] z-2","text-px-base leading-none"),children:[d&&o&&St(ee,{classes:Tt("transition-colors focus-visible-ring ring-inset","w-[27px] h-[27px] mt-[140px] ml-[6px]","flex items-center justify-center bg-white border","text-grey-6 hover:text-grey-9 transition-colors","border-r-0","shadow-sidebar"),title:"Close annotation sidebar",onClick:e,unstyled:!0,children:St(It,{})}),!d&&St(y,{children:[St(ee,{classes:Tt("transition-colors focus-visible-ring ring-inset","h-[40px] w-[33px] pl-[6px] rounded-bl","bg-white text-grey-6 hover:text-grey-9","border-l border-b"),elementRef:h,
182
+ title:"Annotation sidebar",expanded:o,"aria-controls":i,onClick:c,unstyled:!0,children:St(o?Ft:Dt,{})}),St("div",{className:"space-y-[6px] mt-[8px]",children:[St(Ur,{title:"Show highlights",icon:s?te:$t,pressed:s,pressedBackground:!1,onClick:l}),a.includes("selection")&&St(Ur,{"data-testid":"text-annotation",title:"note"===r?"New page note":"New annotation",icon:"note"===r?Kt:Ot,onClick:()=>n("selection")}),a.includes("rect")&&St(Ur,{"data-testid":"rect-annotation",pressed:"rect"===t,title:Hr(f,t,u??null),icon:f&&"rect"===t?()=>St(Vr,{mode:u??"rect"}):Zt,onClick:()=>{f&&"rect"===t?p?.():n("rect"===t?null:"rect")},onKeyDown:zr(g,f)}),a.includes("point")&&St(Ur,{"data-testid":"point-annotation",pressed:"point"===t,title:"Pin annotation",icon:Xt,onClick:()=>n("point"===t?null:"point"),onKeyDown:zr(_,f)})]}),St($r,{highlightsVisible:s})]})]})}class Wr{constructor(t,e){const{createAnnotation:n,setSidebarOpen:o,setHighlightsVisible:i}=e;this.container=t,this._activeTool=null,this._useMinimalControls=!1,
182
183
  this._newAnnotationType="note",this._highlightsVisible=!1,this._sidebarOpen=!1,this._sidebarContainerId=e.sidebarContainerId,this._supportedAnnotationTools=["selection"],this._keyboardMode=null,this._keyboardActive=!1,this._closeSidebar=()=>o(!1),this._toggleSidebar=()=>o(!this._sidebarOpen),this._toggleHighlights=()=>i(!this._highlightsVisible),this._createAnnotation=t=>{n(t),"selection"===t&&o(!0)},this._sidebarToggleButton={current:null},this.render()}getWidth(){return this.container.firstChild.getBoundingClientRect().width}set activeTool(t){this._activeTool=t,this.render()}get activeTool(){return this._activeTool}set useMinimalControls(t){this._useMinimalControls=t,this.render()}get useMinimalControls(){return this._useMinimalControls}set sidebarOpen(t){this._sidebarOpen=t,this.render()}get sidebarOpen(){return this._sidebarOpen}set newAnnotationType(t){this._newAnnotationType=t,this.render()}get newAnnotationType(){return this._newAnnotationType}set highlightsVisible(t){this._highlightsVisible=t,
183
- this.render()}get highlightsVisible(){return this._highlightsVisible}get sidebarToggleButton(){return this._sidebarToggleButton.current}set supportedAnnotationTools(t){this._supportedAnnotationTools=t,this.render()}get supportedAnnotationTools(){return this._supportedAnnotationTools}set keyboardModeState(t){this._keyboardActive=t.keyboardActive,this._keyboardMode=t.keyboardMode,this.render()}get keyboardModeState(){return{keyboardActive:this._keyboardActive,keyboardMode:this._keyboardMode}}set modeButtonCallbacks(t){this._onModeClick=t.onModeClick,this._onActivateMoveMode=t.onActivateMoveMode,this._onActivatePointMoveMode=t.onActivatePointMoveMode,this.render()}get modeButtonCallbacks(){return{onModeClick:this._onModeClick,onActivateMoveMode:this._onActivateMoveMode,onActivatePointMoveMode:this._onActivatePointMoveMode}}render(){H(St($r,{activeTool:this._activeTool,closeSidebar:this._closeSidebar,createAnnotation:this._createAnnotation,newAnnotationType:this._newAnnotationType,isSidebarOpen:this._sidebarOpen,
184
- sidebarContainerId:this._sidebarContainerId,showHighlights:this._highlightsVisible,supportedTools:this._supportedAnnotationTools,toggleHighlights:this._toggleHighlights,toggleSidebar:this._toggleSidebar,toggleSidebarRef:this._sidebarToggleButton,useMinimalControls:this.useMinimalControls,keyboardMode:this._keyboardMode,keyboardActive:this._keyboardActive,onModeClick:this._onModeClick,onActivateMoveMode:this._onActivateMoveMode,onActivatePointMoveMode:this._onActivatePointMoveMode}),this.container)}}class Wr{constructor({target:t,threshold:e=10,onDrag:n}){t.style.touchAction="none",this._listeners=new mt,this._startX=null,this._dragActive=!1,this._threshold=e,this._listeners.add(t,"pointerdown",(t=>{this._startX=t.clientX}));const o=t=>{if(null!==this._startX&&this._dragActive){const e=t.clientX-this._startX;n({type:"dragend",deltaX:e})}this._startX=null,this._dragActive=!1};this._listeners.add(window,"pointercancel",o),this._listeners.add(window,"pointerup",o),this._listeners.add(window,"pointermove",(t=>{
185
- if(null===this._startX)return;const e=t.clientX-this._startX;!this._dragActive&&Math.abs(e)>=this._threshold&&(this._dragActive=!0,n({type:"dragstart",deltaX:e})),this._dragActive&&n({type:"dragmove",deltaX:e})}))}destroy(){this._listeners.removeAll()}}const jr=280;class Kr{constructor(t,e,n){this._emitter=e.createEmitter(),this._guestWithSelection=null,this._guestRPC=[],this._sidebarRPC=new De,this.iframe=function(t){const e=t.sidebarAppUrl,n=Cr(e,Sr(e,t)),o=document.createElement("iframe");return o.src=n,o.title="Hypothesis annotation viewer",o.className="sidebar-frame",o.allow="fullscreen; clipboard-write",o}(n),this._config=n,this.bucketBar=null,this.features=new ko;const o="sidebar-container",i=document.createElement("div");if(i.setAttribute("data-testid","toolbar-container"),this.toolbar=new qr(i,{sidebarContainerId:o,createAnnotation:t=>{if(0===this._guestRPC.length)return;(this._guestWithSelection??this._guestRPC[0]).call("createAnnotation",{tool:t})},setSidebarOpen:t=>t?this.open():this.close(),
184
+ this.render()}get highlightsVisible(){return this._highlightsVisible}get sidebarToggleButton(){return this._sidebarToggleButton.current}set supportedAnnotationTools(t){this._supportedAnnotationTools=t,this.render()}get supportedAnnotationTools(){return this._supportedAnnotationTools}set keyboardModeState(t){this._keyboardActive=t.keyboardActive,this._keyboardMode=t.keyboardMode,this.render()}get keyboardModeState(){return{keyboardActive:this._keyboardActive,keyboardMode:this._keyboardMode}}set modeButtonCallbacks(t){this._onModeClick=t.onModeClick,this._onActivateMoveMode=t.onActivateMoveMode,this._onActivatePointMoveMode=t.onActivatePointMoveMode,this.render()}get modeButtonCallbacks(){return{onModeClick:this._onModeClick,onActivateMoveMode:this._onActivateMoveMode,onActivatePointMoveMode:this._onActivatePointMoveMode}}render(){H(St(qr,{activeTool:this._activeTool,closeSidebar:this._closeSidebar,createAnnotation:this._createAnnotation,newAnnotationType:this._newAnnotationType,isSidebarOpen:this._sidebarOpen,
185
+ sidebarContainerId:this._sidebarContainerId,showHighlights:this._highlightsVisible,supportedTools:this._supportedAnnotationTools,toggleHighlights:this._toggleHighlights,toggleSidebar:this._toggleSidebar,toggleSidebarRef:this._sidebarToggleButton,useMinimalControls:this.useMinimalControls,keyboardMode:this._keyboardMode,keyboardActive:this._keyboardActive,onModeClick:this._onModeClick,onActivateMoveMode:this._onActivateMoveMode,onActivatePointMoveMode:this._onActivatePointMoveMode}),this.container)}}class jr{constructor({target:t,threshold:e=10,onDrag:n}){t.style.touchAction="none",this._listeners=new mt,this._startX=null,this._dragActive=!1,this._threshold=e,this._listeners.add(t,"pointerdown",(t=>{this._startX=t.clientX}));const o=t=>{if(null!==this._startX&&this._dragActive){const e=t.clientX-this._startX;n({type:"dragend",deltaX:e})}this._startX=null,this._dragActive=!1};this._listeners.add(window,"pointercancel",o),this._listeners.add(window,"pointerup",o),this._listeners.add(window,"pointermove",(t=>{
186
+ if(null===this._startX)return;const e=t.clientX-this._startX;!this._dragActive&&Math.abs(e)>=this._threshold&&(this._dragActive=!0,n({type:"dragstart",deltaX:e})),this._dragActive&&n({type:"dragmove",deltaX:e})}))}destroy(){this._listeners.removeAll()}}const Kr=280;class Xr{constructor(t,e,n){this._emitter=e.createEmitter(),this._guestWithSelection=null,this._guestRPC=[],this._sidebarRPC=new De,this.iframe=function(t){const e=t.sidebarAppUrl,n=Sr(e,Ar(e,t)),o=document.createElement("iframe");return o.src=n,o.title="Hypothesis annotation viewer",o.className="sidebar-frame",o.allow="fullscreen; clipboard-write",o}(n),this._config=n,this.bucketBar=null,this.features=new Mo;const o="sidebar-container",i=document.createElement("div");if(i.setAttribute("data-testid","toolbar-container"),this.toolbar=new Wr(i,{sidebarContainerId:o,createAnnotation:t=>{if(0===this._guestRPC.length)return;(this._guestWithSelection??this._guestRPC[0]).call("createAnnotation",{tool:t})},setSidebarOpen:t=>t?this.open():this.close(),
186
187
  setHighlightsVisible:t=>this.setHighlightsVisible(t)}),this.toolbar.modeButtonCallbacks={onModeClick:()=>{const t=this._getGuestRPC();if(!t)return;const e=this.toolbar.keyboardModeState?.keyboardMode||"rect";let n;n="rect"===e?"move":"move"===e?"resize":"rect",t.call("setKeyboardMode",{mode:n})},onActivateMoveMode:()=>{const t=this._getGuestRPC();t&&t.call("activateMoveMode")},onActivatePointMoveMode:()=>{const t=this._getGuestRPC();t&&t.call("activatePointMoveMode")}},n.externalContainerSelector)this.externalFrame=document.querySelector(n.externalContainerSelector)??t,this.externalFrame.appendChild(this.iframe);else{if(this.iframeContainer=document.createElement("div"),this.iframeContainer.style.display="none",this.iframeContainer.className="sidebar-container",this.iframeContainer.id=o,"clean"===n.theme)this.iframeContainer.classList.add("theme-clean"),this.iframeContainer.append(i),this.toolbar.useMinimalControls=!0;else{let t;n.bucketContainerSelector&&(t=document.querySelector(n.bucketContainerSelector),
187
- t||console.warn(`Custom bucket container "${n.bucketContainerSelector}" not found`));const e=document.createElement("div");e.setAttribute("data-testid","sidebar-edge"),e.className=Tt("absolute top-0 bottom-0 w-[23px] left-[-22px]","flex flex-col pr-[5px]","bg-grey-2 sidebar-collapsed:bg-black/[.08]","pointer-events-none"),i.className="pointer-events-auto",e.append(i),this.iframeContainer.append(e),t||(t=e),this.bucketBar=new Or(t,{onFocusAnnotations:t=>this._guestRPC.forEach((e=>e.call("hoverAnnotations",t))),onScrollToAnnotation:t=>this._guestRPC.forEach((e=>e.call("scrollToAnnotation",t))),onSelectAnnotations:(t,e)=>this._guestRPC.forEach((n=>n.call("selectAnnotations",t,e)))})}this.iframeContainer.appendChild(this.iframe),this._hypothesisSidebar=document.createElement("hypothesis-sidebar");const{shadowRoot:e,stylesLoaded:r}=Rn(this._hypothesisSidebar);e.appendChild(this.iframeContainer),r.then((()=>this._onResize())),t.appendChild(this._hypothesisSidebar),
188
- this._messagesElement=document.createElement("div"),e.appendChild(this._messagesElement),H(St(Ir,{emitter:this._emitter}),this._messagesElement)}this.iframe.contentWindow&&Te(this.iframe.contentWindow),this._listeners=new mt,this.iframeContainer?this._toolbarWidth=this.toolbar.getWidth():this._toolbarWidth=0,this._listeners.add(window,"resize",(()=>this._onResize())),this._dragResizeState={initial:null,final:null};const r=this.toolbar.sidebarToggleButton;r&&(this._dragResizeHandler=new Wr({target:r,onDrag:t=>this._onDragSidebarToggleButton(t)})),this.close();const[s]=n.services||[];s&&(this.onLoginRequest=s.onLoginRequest,this.onLogoutRequest=s.onLogoutRequest,this.onSignupRequest=s.onSignupRequest,this.onProfileRequest=s.onProfileRequest,this.onHelpRequest=s.onHelpRequest),this.onLayoutChange=n.onLayoutChange,this._layoutState={expanded:!1,width:0,height:0,toolbarWidth:0},this._updateLayoutState(!1),this._setupSidebarEvents()}_getGuestRPC(){return this._guestRPC[0]??null}destroy(){
188
+ t||console.warn(`Custom bucket container "${n.bucketContainerSelector}" not found`));const e=document.createElement("div");e.setAttribute("data-testid","sidebar-edge"),e.className=Tt("absolute top-0 bottom-0 w-[23px] left-[-22px]","flex flex-col pr-[5px]","bg-grey-2 sidebar-collapsed:bg-black/[.08]","pointer-events-none"),i.className="pointer-events-auto",e.append(i),this.iframeContainer.append(e),t||(t=e),this.bucketBar=new Ir(t,{onFocusAnnotations:t=>this._guestRPC.forEach((e=>e.call("hoverAnnotations",t))),onScrollToAnnotation:t=>this._guestRPC.forEach((e=>e.call("scrollToAnnotation",t))),onSelectAnnotations:(t,e)=>this._guestRPC.forEach((n=>n.call("selectAnnotations",t,e)))})}this.iframeContainer.appendChild(this.iframe),this._hypothesisSidebar=document.createElement("hypothesis-sidebar");const{shadowRoot:e,stylesLoaded:r}=En(this._hypothesisSidebar);e.appendChild(this.iframeContainer),r.then((()=>this._onResize())),t.appendChild(this._hypothesisSidebar),
189
+ this._messagesElement=document.createElement("div"),e.appendChild(this._messagesElement),H(St(Br,{emitter:this._emitter}),this._messagesElement)}this.iframe.contentWindow&&Te(this.iframe.contentWindow),this._listeners=new mt,this.iframeContainer?this._toolbarWidth=this.toolbar.getWidth():this._toolbarWidth=0,this._listeners.add(window,"resize",(()=>this._onResize())),this._dragResizeState={initial:null,final:null};const r=this.toolbar.sidebarToggleButton;r&&(this._dragResizeHandler=new jr({target:r,onDrag:t=>this._onDragSidebarToggleButton(t)})),this.close();const[s]=n.services||[];s&&(this.onLoginRequest=s.onLoginRequest,this.onLogoutRequest=s.onLogoutRequest,this.onSignupRequest=s.onSignupRequest,this.onProfileRequest=s.onProfileRequest,this.onHelpRequest=s.onHelpRequest),this.onLayoutChange=n.onLayoutChange,this._layoutState={expanded:!1,width:0,height:0,toolbarWidth:0},this._updateLayoutState(!1),this._setupSidebarEvents()}_getGuestRPC(){return this._guestRPC[0]??null}destroy(){
189
190
  this._guestRPC.forEach((t=>t.destroy())),this._sidebarRPC.destroy(),this.bucketBar?.destroy(),this._listeners.removeAll(),this._dragResizeHandler?.destroy(),this._hypothesisSidebar?(H(null,this._messagesElement),this._hypothesisSidebar.remove()):this.iframe.remove(),this._emitter.destroy(),Te(null)}onFrameConnected(t,e){switch(t){case"guest":this._connectGuest(e);break;case"sidebar":this._sidebarRPC.connect(e)}}_connectGuest(t){const e=new De;e.on("textSelected",(()=>{this._guestWithSelection=e,this.toolbar.newAnnotationType="annotation",this._guestRPC.filter((t=>t!==e)).forEach((t=>t.call("clearSelection")))})),e.on("textUnselected",(()=>{this._guestWithSelection=null,this.toolbar.newAnnotationType="note",this._guestRPC.filter((t=>t!==e)).forEach((t=>t.call("clearSelection")))})),e.on("activeToolChanged",(t=>{this.toolbar.activeTool=t})),e.on("highlightsVisibleChanged",(t=>{this.setHighlightsVisible(t)}));const n=this.bucketBar;n&&e.on("anchorsChanged",(t=>{0===this._guestRPC.indexOf(e)&&n.update(t)})),
190
191
  e.on("close",(()=>{e.destroy(),e===this._guestWithSelection&&(this._guestWithSelection=null),this._guestRPC=this._guestRPC.filter((t=>t!==e))})),e.on("supportedToolsChanged",(t=>{this.toolbar.supportedAnnotationTools=t})),e.on("keyboardModeChanged",(t=>{this.toolbar.keyboardModeState=t})),e.connect(t),this._guestRPC.push(e),e.call("sidebarLayoutChanged",this._layoutState)}_setupSidebarEvents(){var t;t=document.body,this._sidebarRPC.on("publicAnnotationCountChanged",(function(e){const n=t.querySelectorAll("[data-hypothesis-annotation-count]");Array.from(n).forEach((t=>{t.textContent=e.toString()}))})),function(t,e){const n=t.querySelectorAll("[data-hypothesis-trigger]");Array.from(n).forEach((t=>{t.addEventListener("click",(t=>{e(),t.stopPropagation()}))}))}(document.body,(()=>this.open())),this._sidebarRPC.on("featureFlagsUpdated",(t=>this.features.update(t))),this._sidebarRPC.on("connect",(()=>{this.iframeContainer&&(this.iframeContainer.style.display="");const t="always"===this._config.showHighlights
191
192
  ;this.setHighlightsVisible(t),(this._config.openSidebar||this._config.annotations||this._config.query||this._config.group)&&this.open()})),this._sidebarRPC.on("showHighlights",(()=>this.setHighlightsVisible(!0))),this._sidebarRPC.on("openSidebar",(()=>this.open())),this._sidebarRPC.on("closeSidebar",(()=>this.close())),this._sidebarRPC.on("openNotebook",(t=>{this.hide(),this._emitter.publish("openNotebook",t)})),this._sidebarRPC.on("openProfile",(()=>{this.hide(),this._emitter.publish("openProfile")})),this._emitter.subscribe("closeProfile",(()=>{this.show()})),this._emitter.subscribe("closeNotebook",(()=>{this.show()})),this._sidebarRPC.on("toastMessageAdded",(t=>{this._emitter.publish("toastMessageAdded",t)})),this._sidebarRPC.on("toastMessageDismissed",(t=>{this._emitter.publish("toastMessageDismissed",t)}))
192
- ;[["loginRequested",this.onLoginRequest],["logoutRequested",this.onLogoutRequest],["signupRequested",this.onSignupRequest],["profileRequested",this.onProfileRequest],["helpRequested",this.onHelpRequest]].forEach((([t,e])=>{e&&this._sidebarRPC.on(t,(()=>e()))}))}_resetDragResizeState(){this._dragResizeState={initial:null,final:null}}_updateLayout(){this._renderFrame||(this._renderFrame=requestAnimationFrame((()=>{if(this._renderFrame=void 0,"number"==typeof this._dragResizeState.final&&this._dragResizeState.final!==this._dragResizeState.initial&&this.iframeContainer){const t=this._dragResizeState.final,e=-t;this.iframeContainer.style.marginLeft=`${t}px`,e>=jr&&(this.iframeContainer.style.width=`${e}px`),this._updateLayoutState()}})))}_updateLayoutState(t){const e=this.iframeContainer&&this.toolbar.getWidth()||0,n=this.iframeContainer??this.externalFrame,{height:o}=n.getBoundingClientRect(),i=window.getComputedStyle(n),r=parseInt(i.width),s=parseInt(i.marginLeft);let a=e
193
- ;"boolean"==typeof t?t&&(a+=r):(s<jr?a-=s:a+=r,t=a>e);const l={expanded:t,width:t?a:e,height:o,toolbarWidth:e};this._layoutState=l,this.onLayoutChange?.(l),this._guestRPC.forEach((t=>t.call("sidebarLayoutChanged",l)))}_onResize(){this.toolbar.sidebarOpen&&(window.innerWidth<jr?this.close():this.open())}isResizing(){return null!==this._dragResizeState.initial}_onDragSidebarToggleButton(t){const e=this.iframeContainer;if(e)switch(t.type){case"dragstart":this._resetDragResizeState(),e.classList.add("sidebar-no-transition"),this.toolbar.container.style.pointerEvents="none",this._dragResizeState.initial=parseInt(getComputedStyle(e).marginLeft);break;case"dragend":e.classList.remove("sidebar-no-transition"),this.toolbar.container.style.pointerEvents="",null===this._dragResizeState.final||this._dragResizeState.final<=-280?this.open():this.close(),this._resetDragResizeState();break;case"dragmove":{if("number"!=typeof this._dragResizeState.initial)return;const e=this._dragResizeState.initial,n=t.deltaX
194
- ;this._dragResizeState.final=Math.min(Math.round(e+n),0),this._updateLayout();break}}}open(){if(this._sidebarRPC.call("sidebarOpened"),this.iframeContainer){const t=this.iframeContainer.getBoundingClientRect().width;this.iframeContainer.style.marginLeft=-1*t+"px",this.iframeContainer.classList.remove("sidebar-collapsed")}this.toolbar.sidebarOpen=!0,"whenSidebarOpen"===this._config.showHighlights&&this.setHighlightsVisible(!0),this._updateLayoutState(!0)}close(){this._sidebarRPC.call("sidebarClosed"),this.iframeContainer&&(this.iframeContainer.style.marginLeft="",this.iframeContainer.classList.add("sidebar-collapsed")),this.toolbar.sidebarOpen=!1,"whenSidebarOpen"===this._config.showHighlights&&this.setHighlightsVisible(!1),this._updateLayoutState(!1)}setHighlightsVisible(t){this.toolbar.highlightsVisible=t,this._sidebarRPC.call("setHighlightsVisible",t)}show(){this.iframeContainer?.classList.remove("is-hidden")}hide(){this.iframeContainer?.classList.add("is-hidden")}}class Xr{constructor(t){this._emitter=t,
195
- this._subscriptions=[]}publish(t,...e){this._emitter.emit(t,...e)}subscribe(t,e){this._emitter.on(t,e),this._subscriptions.push([t,e])}unsubscribe(t,e){this._emitter.off(t,e),this._subscriptions=this._subscriptions.filter((([n,o])=>n!==t||o!==e))}destroy(){for(const[t,e]of this._subscriptions)this._emitter.off(t,e);this._subscriptions=[]}}class Yr{constructor(){this._emitter=new Me}createEmitter(){return new Xr(this._emitter)}}const Gr=document.querySelector('link[type="application/annotator+html"][rel="sidebar"]');new Promise((t=>{"loading"!==document.readyState&&t(),document.addEventListener("readystatechange",(()=>t()))})).then((function(){const t=hn("annotator");let e=()=>{};const n=new Promise((t=>{e=t}));Gr.addEventListener("destroy",e);const o=t.subFrameIdentifier?window.parent:window,i=[];if(o===window){if(function(){const t=document.querySelectorAll(["hypothesis-sidebar","hypothesis-notebook","hypothesis-profile"].join(","));return t.forEach((t=>t.remove())),t.length>0
196
- }())return void console.warn("Hypothesis did not load because it found an existing instance on the page.");const t=hn("sidebar"),e=new URL(t.sidebarAppUrl).origin,n=new Ne(e),o=new Yr,r=new Kr(document.body,o,t),s=new Pr(document.body,o,hn("notebook")),a=new Nr(document.body,o,hn("profile"));n.on("frameConnected",((t,e)=>r.onFrameConnected(t,e))),i.push(n,r,s,a)}if("container"===lr()){const e=new cr(t);i.push(e)}else{const n=new ir(document.body,t),r=new xr(document.body,t,o);r.on("hostDisconnected",e),i.push(n,r)}n.then((()=>{i.forEach((t=>t.destroy()));document.querySelectorAll("[data-hypothesis-asset]").forEach((t=>t.remove())),function(t=document){Array.from(t.querySelectorAll("script.js-hypothesis-config[data-remove-on-unload]")).forEach((t=>t.remove()))}()}))}))}();
193
+ ;[["loginRequested",this.onLoginRequest],["logoutRequested",this.onLogoutRequest],["signupRequested",this.onSignupRequest],["profileRequested",this.onProfileRequest],["helpRequested",this.onHelpRequest]].forEach((([t,e])=>{e&&this._sidebarRPC.on(t,(()=>e()))}))}_resetDragResizeState(){this._dragResizeState={initial:null,final:null}}_updateLayout(){this._renderFrame||(this._renderFrame=requestAnimationFrame((()=>{if(this._renderFrame=void 0,"number"==typeof this._dragResizeState.final&&this._dragResizeState.final!==this._dragResizeState.initial&&this.iframeContainer){const t=this._dragResizeState.final,e=-t;this.iframeContainer.style.marginLeft=`${t}px`,e>=Kr&&(this.iframeContainer.style.width=`${e}px`),this._updateLayoutState()}})))}_updateLayoutState(t){const e=this.iframeContainer&&this.toolbar.getWidth()||0,n=this.iframeContainer??this.externalFrame,{height:o}=n.getBoundingClientRect(),i=window.getComputedStyle(n),r=parseInt(i.width),s=parseInt(i.marginLeft);let a=e
194
+ ;"boolean"==typeof t?t&&(a+=r):(s<Kr?a-=s:a+=r,t=a>e);const l={expanded:t,width:t?a:e,height:o,toolbarWidth:e};this._layoutState=l,this.onLayoutChange?.(l),this._guestRPC.forEach((t=>t.call("sidebarLayoutChanged",l)))}_onResize(){this.toolbar.sidebarOpen&&(window.innerWidth<Kr?this.close():this.open())}isResizing(){return null!==this._dragResizeState.initial}_onDragSidebarToggleButton(t){const e=this.iframeContainer;if(e)switch(t.type){case"dragstart":this._resetDragResizeState(),e.classList.add("sidebar-no-transition"),this.toolbar.container.style.pointerEvents="none",this._dragResizeState.initial=parseInt(getComputedStyle(e).marginLeft);break;case"dragend":e.classList.remove("sidebar-no-transition"),this.toolbar.container.style.pointerEvents="",null===this._dragResizeState.final||this._dragResizeState.final<=-280?this.open():this.close(),this._resetDragResizeState();break;case"dragmove":{if("number"!=typeof this._dragResizeState.initial)return;const e=this._dragResizeState.initial,n=t.deltaX
195
+ ;this._dragResizeState.final=Math.min(Math.round(e+n),0),this._updateLayout();break}}}open(){if(this._sidebarRPC.call("sidebarOpened"),this.iframeContainer){const t=this.iframeContainer.getBoundingClientRect().width;this.iframeContainer.style.marginLeft=-1*t+"px",this.iframeContainer.classList.remove("sidebar-collapsed")}this.toolbar.sidebarOpen=!0,"whenSidebarOpen"===this._config.showHighlights&&this.setHighlightsVisible(!0),this._updateLayoutState(!0)}close(){this._sidebarRPC.call("sidebarClosed"),this.iframeContainer&&(this.iframeContainer.style.marginLeft="",this.iframeContainer.classList.add("sidebar-collapsed")),this.toolbar.sidebarOpen=!1,"whenSidebarOpen"===this._config.showHighlights&&this.setHighlightsVisible(!1),this._updateLayoutState(!1)}setHighlightsVisible(t){this.toolbar.highlightsVisible=t,this._sidebarRPC.call("setHighlightsVisible",t)}show(){this.iframeContainer?.classList.remove("is-hidden")}hide(){this.iframeContainer?.classList.add("is-hidden")}}class Yr{constructor(t){this._emitter=t,
196
+ this._subscriptions=[]}publish(t,...e){this._emitter.emit(t,...e)}subscribe(t,e){this._emitter.on(t,e),this._subscriptions.push([t,e])}unsubscribe(t,e){this._emitter.off(t,e),this._subscriptions=this._subscriptions.filter((([n,o])=>n!==t||o!==e))}destroy(){for(const[t,e]of this._subscriptions)this._emitter.off(t,e);this._subscriptions=[]}}class Gr{constructor(){this._emitter=new Me}createEmitter(){return new Yr(this._emitter)}}const Qr=document.querySelector('link[type="application/annotator+html"][rel="sidebar"]');new Promise((t=>{"loading"!==document.readyState&&t(),document.addEventListener("readystatechange",(()=>t()))})).then((function(){const t=hn("annotator");let e=()=>{};const n=new Promise((t=>{e=t}));Qr.addEventListener("destroy",e);const o=t.subFrameIdentifier?window.parent:window,i=[];if(o===window){if(function(){const t=document.querySelectorAll(["hypothesis-sidebar","hypothesis-notebook","hypothesis-profile"].join(","));return t.forEach((t=>t.remove())),t.length>0
197
+ }())return void console.warn("Hypothesis did not load because it found an existing instance on the page.");const t=hn("sidebar"),e=new URL(t.sidebarAppUrl).origin,n=new Ne(e),o=new Gr,r=new Xr(document.body,o,t),s=new Tr(document.body,o,hn("notebook")),a=new Lr(document.body,o,hn("profile"));n.on("frameConnected",((t,e)=>r.onFrameConnected(t,e))),i.push(n,r,s,a)}if("container"===cr()){const e=new hr(t);i.push(e)}else{const n=new rr(document.body,t),r=new Cr(document.body,t,o);r.on("hostDisconnected",e),i.push(n,r)}n.then((()=>{i.forEach((t=>t.destroy()));document.querySelectorAll("[data-hypothesis-asset]").forEach((t=>t.remove())),function(t=document){Array.from(t.querySelectorAll("script.js-hypothesis-config[data-remove-on-unload]")).forEach((t=>t.remove()))}()}))}))}();
197
198
  //# sourceMappingURL=annotator.bundle.js.map