hypothesis 1.1641.0 → 1.1643.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.
package/build/boot.js CHANGED
@@ -1 +1 @@
1
- !function(){"use strict";var s={"scripts/annotator.bundle.js":"scripts/annotator.bundle.js?653ce8","styles/annotator.css":"styles/annotator.css?d21fb5","styles/annotator.css.map":"styles/annotator.css.map?ba6735","styles/highlights.css":"styles/highlights.css?24baca","styles/highlights.css.map":"styles/highlights.css.map?377599","styles/katex.min.css":"styles/katex.min.css?921c28","styles/katex.min.css.map":"styles/katex.min.css.map?e7e03f","styles/pdfjs-overrides.css":"styles/pdfjs-overrides.css?c95edf","styles/pdfjs-overrides.css.map":"styles/pdfjs-overrides.css.map?1d8ac6","styles/sidebar.css":"styles/sidebar.css?c949f4","styles/sidebar.css.map":"styles/sidebar.css.map?c4cba4","styles/ui-playground.css":"styles/ui-playground.css?6778a6","styles/ui-playground.css.map":"styles/ui-playground.css.map?0e6471","scripts/annotator.bundle.js.map":"scripts/annotator.bundle.js.map?85353d","scripts/sidebar.bundle.js":"scripts/sidebar.bundle.js?b81126","scripts/ui-playground.bundle.js":"scripts/ui-playground.bundle.js?7f00d1","scripts/sidebar.bundle.js.map":"scripts/sidebar.bundle.js.map?8a33c7","scripts/ui-playground.bundle.js.map":"scripts/ui-playground.bundle.js.map?f8f9bd"};function t(s){s.setAttribute("data-hypothesis-asset","")}function e(s,e){var o=s.createElement("link");o.rel="stylesheet",o.type="text/css",o.href=e,t(o),s.head.appendChild(o)}function o(s,e){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=o.esModule,n=void 0===r||r,i=o.forceReload,a=void 0!==i&&i,l=s.createElement("script");n&&(l.type="module"),a&&(e+="#ts=".concat(Date.now())),l.src=e,l.async=!1,t(l),s.head.appendChild(l)}function r(s,e,o,r){var n=s.createElement("link");n.rel=e,n.href=r,n.type="application/annotator+".concat(o),t(n),s.head.appendChild(n)}function n(s,e,o){var r=s.createElement("link");r.rel="preload",r.as=e,r.href=o,"fetch"===e&&(r.crossOrigin="anonymous"),t(r),s.head.appendChild(r)}function i(s,t){return s.assetRoot+"build/"+s.manifest[t]}function a(s){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;if(-1===s.indexOf("{"))return s;var e=function(){var s,t,e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:document).currentScript;return e?(s=e.src,(t=s.match(/(https?):\/\/([^:/]+)/))?{protocol:t[1],hostname:t[2]}:null):null}(t);if(!e)throw new Error("Could not process URL template because script origin is unknown");return s=(s=s.replace("{current_host}",e.hostname)).replace("{current_scheme}",e.protocol)}if(function(){var s=[()=>Object.fromEntries([]),()=>new URL(document.location.href),()=>new Request("https://hypothes.is"),()=>Element.prototype.attachShadow,()=>CSS.supports("display: grid"),()=>(document.evaluate("/html/body",document,null,XPathResult.ANY_TYPE,null),!0)];try{return s.every((s=>s()))}catch(s){return!1}}()){var l=function(s){for(var t={},e=s.querySelectorAll("script.js-hypothesis-config"),o=0;o<e.length;o++){var r=void 0;try{r=JSON.parse(e[o].textContent||"")}catch(s){console.warn("Could not parse settings from js-hypothesis-config tags",s),r={}}Object.assign(t,r)}return t}(document),p=a(l.assetRoot||"https://cdn.hypothes.is/hypothesis/1.1641.0/");if(document.querySelector("hypothesis-app")){!function(s,t){n(s,"fetch",t.apiUrl),n(s,"fetch",t.apiUrl+"links");for(var r=0,a=["scripts/sidebar.bundle.js"];r<a.length;r++)o(s,i(t,a[r]),{esModule:!0});for(var l=0,p=["styles/katex.min.css","styles/sidebar.css"];l<p.length;l++)e(s,i(t,p[l]))}(document,{assetRoot:p,manifest:s,apiUrl:l.apiUrl})}else{var c=function(){var s;return null===(s=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:window).chrome)||void 0===s||null===(s=s.runtime)||void 0===s?void 0:s.id}();if(c&&!function(s){return!!(arguments.length>1&&void 0!==arguments[1]?arguments[1]:document).querySelector("script.js-hypothesis-config[data-extension-id=".concat(s,"]"))}(c))throw new Error("Could not start Hypothesis extension as configuration is missing");var d=l,h=a(d.notebookAppUrl||"https://hypothes.is/notebook"),u=a(d.profileAppUrl||"https://hypothes.is/user-profile"),y=a(d.sidebarAppUrl||"https://hypothes.is/app.html");!function(s,t){if(!s.querySelector('link[type="application/annotator+html"]')){r(s,"sidebar","html",t.sidebarAppUrl),r(s,"notebook","html",t.notebookAppUrl),r(s,"profile","html",t.profileAppUrl),n(s,"style",i(t,"styles/annotator.css")),r(s,"hypothesis-client","javascript",t.assetRoot+"build/boot.js");for(var a=0,l=["scripts/annotator.bundle.js"];a<l.length;a++)o(s,i(t,l[a]),{esModule:!1});var p=[];void 0!==window.PDFViewerApplication&&p.push("styles/pdfjs-overrides.css"),p.push("styles/highlights.css");for(var c=0,d=p;c<d.length;c++)e(s,i(t,d[c]))}}(document,{assetRoot:p,manifest:s,notebookAppUrl:h,profileAppUrl:u,sidebarAppUrl:y})}}else console.warn("The Hypothesis annotation tool is not supported in this browser. See https://web.hypothes.is/help/which-browsers-are-supported-by-hypothesis/.")}();
1
+ !function(){"use strict";var s={"scripts/annotator.bundle.js":"scripts/annotator.bundle.js?17e171","styles/annotator.css.map":"styles/annotator.css.map?ba6735","styles/annotator.css":"styles/annotator.css?d21fb5","styles/highlights.css":"styles/highlights.css?24baca","styles/highlights.css.map":"styles/highlights.css.map?377599","styles/katex.min.css.map":"styles/katex.min.css.map?e7e03f","styles/katex.min.css":"styles/katex.min.css?921c28","styles/pdfjs-overrides.css.map":"styles/pdfjs-overrides.css.map?1d8ac6","styles/pdfjs-overrides.css":"styles/pdfjs-overrides.css?c95edf","styles/sidebar.css":"styles/sidebar.css?c949f4","styles/sidebar.css.map":"styles/sidebar.css.map?c4cba4","styles/ui-playground.css.map":"styles/ui-playground.css.map?0e6471","styles/ui-playground.css":"styles/ui-playground.css?6778a6","scripts/annotator.bundle.js.map":"scripts/annotator.bundle.js.map?3764ae","scripts/sidebar.bundle.js":"scripts/sidebar.bundle.js?a5c914","scripts/ui-playground.bundle.js":"scripts/ui-playground.bundle.js?7f00d1","scripts/ui-playground.bundle.js.map":"scripts/ui-playground.bundle.js.map?f8f9bd","scripts/sidebar.bundle.js.map":"scripts/sidebar.bundle.js.map?3f90f1"};function t(s){s.setAttribute("data-hypothesis-asset","")}function e(s,e){var o=s.createElement("link");o.rel="stylesheet",o.type="text/css",o.href=e,t(o),s.head.appendChild(o)}function o(s,e){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=o.esModule,n=void 0===r||r,i=o.forceReload,a=void 0!==i&&i,l=s.createElement("script");n&&(l.type="module"),a&&(e+="#ts=".concat(Date.now())),l.src=e,l.async=!1,t(l),s.head.appendChild(l)}function r(s,e,o,r){var n=s.createElement("link");n.rel=e,n.href=r,n.type="application/annotator+".concat(o),t(n),s.head.appendChild(n)}function n(s,e,o){var r=s.createElement("link");r.rel="preload",r.as=e,r.href=o,"fetch"===e&&(r.crossOrigin="anonymous"),t(r),s.head.appendChild(r)}function i(s,t){return s.assetRoot+"build/"+s.manifest[t]}function a(s){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;if(-1===s.indexOf("{"))return s;var e=function(){var s,t,e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:document).currentScript;return e?(s=e.src,(t=s.match(/(https?):\/\/([^:/]+)/))?{protocol:t[1],hostname:t[2]}:null):null}(t);if(!e)throw new Error("Could not process URL template because script origin is unknown");return s=(s=s.replace("{current_host}",e.hostname)).replace("{current_scheme}",e.protocol)}if(function(){var s=[()=>Object.fromEntries([]),()=>new URL(document.location.href),()=>new Request("https://hypothes.is"),()=>Element.prototype.attachShadow,()=>CSS.supports("display: grid"),()=>(document.evaluate("/html/body",document,null,XPathResult.ANY_TYPE,null),!0)];try{return s.every((s=>s()))}catch(s){return!1}}()){var l=function(s){for(var t={},e=s.querySelectorAll("script.js-hypothesis-config"),o=0;o<e.length;o++){var r=void 0;try{r=JSON.parse(e[o].textContent||"")}catch(s){console.warn("Could not parse settings from js-hypothesis-config tags",s),r={}}Object.assign(t,r)}return t}(document),p=a(l.assetRoot||"https://cdn.hypothes.is/hypothesis/1.1643.0/");if(document.querySelector("hypothesis-app")){!function(s,t){n(s,"fetch",t.apiUrl),n(s,"fetch",t.apiUrl+"links");for(var r=0,a=["scripts/sidebar.bundle.js"];r<a.length;r++)o(s,i(t,a[r]),{esModule:!0});for(var l=0,p=["styles/katex.min.css","styles/sidebar.css"];l<p.length;l++)e(s,i(t,p[l]))}(document,{assetRoot:p,manifest:s,apiUrl:l.apiUrl})}else{var c=function(){var s;return null===(s=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:window).chrome)||void 0===s||null===(s=s.runtime)||void 0===s?void 0:s.id}();if(c&&!function(s){return!!(arguments.length>1&&void 0!==arguments[1]?arguments[1]:document).querySelector("script.js-hypothesis-config[data-extension-id=".concat(s,"]"))}(c))throw new Error("Could not start Hypothesis extension as configuration is missing");var d=l,h=a(d.notebookAppUrl||"https://hypothes.is/notebook"),u=a(d.profileAppUrl||"https://hypothes.is/user-profile"),y=a(d.sidebarAppUrl||"https://hypothes.is/app.html");!function(s,t){if(!s.querySelector('link[type="application/annotator+html"]')){r(s,"sidebar","html",t.sidebarAppUrl),r(s,"notebook","html",t.notebookAppUrl),r(s,"profile","html",t.profileAppUrl),n(s,"style",i(t,"styles/annotator.css")),r(s,"hypothesis-client","javascript",t.assetRoot+"build/boot.js");for(var a=0,l=["scripts/annotator.bundle.js"];a<l.length;a++)o(s,i(t,l[a]),{esModule:!1});var p=[];void 0!==window.PDFViewerApplication&&p.push("styles/pdfjs-overrides.css"),p.push("styles/highlights.css");for(var c=0,d=p;c<d.length;c++)e(s,i(t,d[c]))}}(document,{assetRoot:p,manifest:s,notebookAppUrl:h,profileAppUrl:u,sidebarAppUrl:y})}}else console.warn("The Hypothesis annotation tool is not supported in this browser. See https://web.hypothes.is/help/which-browsers-are-supported-by-hypothesis/.")}();
@@ -1,20 +1,20 @@
1
1
  {
2
- "scripts/annotator.bundle.js": "scripts/annotator.bundle.js?653ce8",
3
- "styles/annotator.css": "styles/annotator.css?d21fb5",
2
+ "scripts/annotator.bundle.js": "scripts/annotator.bundle.js?17e171",
4
3
  "styles/annotator.css.map": "styles/annotator.css.map?ba6735",
4
+ "styles/annotator.css": "styles/annotator.css?d21fb5",
5
5
  "styles/highlights.css": "styles/highlights.css?24baca",
6
6
  "styles/highlights.css.map": "styles/highlights.css.map?377599",
7
- "styles/katex.min.css": "styles/katex.min.css?921c28",
8
7
  "styles/katex.min.css.map": "styles/katex.min.css.map?e7e03f",
9
- "styles/pdfjs-overrides.css": "styles/pdfjs-overrides.css?c95edf",
8
+ "styles/katex.min.css": "styles/katex.min.css?921c28",
10
9
  "styles/pdfjs-overrides.css.map": "styles/pdfjs-overrides.css.map?1d8ac6",
10
+ "styles/pdfjs-overrides.css": "styles/pdfjs-overrides.css?c95edf",
11
11
  "styles/sidebar.css": "styles/sidebar.css?c949f4",
12
12
  "styles/sidebar.css.map": "styles/sidebar.css.map?c4cba4",
13
- "styles/ui-playground.css": "styles/ui-playground.css?6778a6",
14
13
  "styles/ui-playground.css.map": "styles/ui-playground.css.map?0e6471",
15
- "scripts/annotator.bundle.js.map": "scripts/annotator.bundle.js.map?85353d",
16
- "scripts/sidebar.bundle.js": "scripts/sidebar.bundle.js?b81126",
14
+ "styles/ui-playground.css": "styles/ui-playground.css?6778a6",
15
+ "scripts/annotator.bundle.js.map": "scripts/annotator.bundle.js.map?3764ae",
16
+ "scripts/sidebar.bundle.js": "scripts/sidebar.bundle.js?a5c914",
17
17
  "scripts/ui-playground.bundle.js": "scripts/ui-playground.bundle.js?7f00d1",
18
- "scripts/sidebar.bundle.js.map": "scripts/sidebar.bundle.js.map?8a33c7",
19
- "scripts/ui-playground.bundle.js.map": "scripts/ui-playground.bundle.js.map?f8f9bd"
18
+ "scripts/ui-playground.bundle.js.map": "scripts/ui-playground.bundle.js.map?f8f9bd",
19
+ "scripts/sidebar.bundle.js.map": "scripts/sidebar.bundle.js.map?3f90f1"
20
20
  }
@@ -132,52 +132,52 @@ function cr(e){return new Promise((t=>setTimeout(t,e)))}class hr{constructor(){t
132
132
  ;if(!o)throw new Error("Bottom-right point is not in a page");if(n.pageIndex!==o.pageIndex)throw new Error("Shape must start and end on same page");const i=await Vi(n.pageIndex);return[er(i,n.pageIndex),{type:"ShapeSelector",anchor:"page",shape:{type:"rect",left:n.x,top:n.y,right:o.x,bottom:o.y},view:t(i.pdfPage)}]}case"point":{const n=await Zi(e.x,e.y);if(!n)throw new Error("Point is not in a page");const o=await Vi(n.pageIndex);return[er(o,n.pageIndex),{type:"ShapeSelector",anchor:"page",shape:{type:"point",x:n.x,y:n.y},view:t(o.pdfPage)}]}default:throw new Error("Unsupported shape")}}(t)}async _checkForSelectableText(){try{await this.uri()}catch{return}if(!this._destroyed)try{const e=await async function(){const e=Di();let t=!1;for(let n=0;n<e.pagesCount;n++)if((await Ui(n)).trim().length>0){t=!0;break}return t}();this._banner.showNoTextWarning(!e)}catch(e){console.warn("Unable to check for text in PDF:",e)}}_update(){const e=[],t=this._pdfViewer.pagesCount;for(let e=0;e<t;e++){
133
133
  const t=this._pdfViewer.getPageView(e);if(t?.textLayer&&Wi(t.textLayer))switch(t.renderingState){case Ii.INITIAL:t.textLayer=null;break;case Ii.FINISHED:n=t.div,n.querySelector(mo)?.remove()}}var n;for(const t of this._annotator.anchors)if(t.highlights){if(e.includes(t.annotation))continue;for(let n=0;n<t.highlights.length;n++){const o=t.highlights[n];if(!document.body.contains(o)){t.highlights.splice(n,1),delete t.region,e.push(t.annotation);break}}}e.map((e=>this._annotator.anchor(e)))}contentContainer(){return document.querySelector("#viewerContainer")}fitSideBySide(e){const t=window.innerWidth-e.width,n=e.expanded&&t>=680,o=n?e.width:e.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 e=this._features?.flagEnabled("pdf_image_annotation")
134
134
  ;return e?["selection","rect","point"]:["selection"]}async scrollToAnchor(e){const t=e.annotation,n=lr(e),o=this._anchorOffset(e);if(null!==o&&(await Ni(this.contentContainer(),o),n)){const e=await this._waitForAnnotationToBeAnchored(t,this._reanchoringMaxWait);if(!e)return;const n=this._anchorOffset(e);if(null===n)return;await Ni(this.contentContainer(),n)}}async _waitForAnnotationToBeAnchored(e,t){const n=Date.now();let o;do{o=this._annotator.anchors.find((t=>t.annotation===e)),o&&!lr(o)||(o=null,await cr(20))}while(!o&&Date.now()-n<t);return o??null}_anchorOffset(e){if(!e.highlights)return null;const t=e.highlights[0];return function(e,t,n={}){let o=0,i=t;for(;i!==e&&e.contains(i);)o+=i.offsetTop,i=i.offsetParent;if("center"===n.position){const n=e.getBoundingClientRect(),i=t.getBoundingClientRect();o-=n.height/2-i.height/2}return o}(this.contentContainer(),t,{position:"center"})}async renderToBitmap(e,t){
135
- const n=e.target.selector?.find((e=>"ShapeSelector"===e.type)),o=e.target.selector?.find((e=>"PageSelector"===e.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:e,y:t}=n.shape,[o,,c]=i.pdfPage.view,h=.1*Math.abs(c-o);r=e-h,a=t+h,s=e+h,l=t-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=96/72,h=t.devicePixelRatio??1,d=(s-r)*c*h,u=(s-r)/(a-l),f="number"==typeof t.maxWidth?Math.min(t.maxWidth,d):d,m=f/u,p=i.pdfPage.getViewport({scale:1}),g=f/d*c*h,_=new(0,p.constructor)({rotation:0,scale:g,userUnit:p.userUnit,viewBox:[r,l,s,a]}),b=Math.max(f,1),w=Math.max(m,1),v=new OffscreenCanvas(b,w),y=v.getContext("2d"),x=i.pdfPage.render({canvasContext:y,viewport:_});if(await x.promise,
136
- "point"===n.shape.type){y.save(),y.scale(g,g);const e=n.shape.x-r,t=n.shape.y-l,o=5;y.strokeStyle="black",y.fillStyle="yellow",y.beginPath(),y.arc(e,t,o,0,2*Math.PI),y.fill(),y.stroke(),y.restore()}return v.transferToImageBitmap()}}function ur(e){if(!e.includes("["))return e;let t="",n=!1,o=!1;for(const i of e)n||"^"!==i?(n||"["!==i?!n&&o&&"]"===i?o=!1:o||(t+=i):o=!0,n=!1):n=!0;return t}function fr(e){const t=ur(e),n=t.indexOf("!");return-1===n?t:t.slice(0,n)}class mr{constructor(e,t,n){this._element=e,this._onFrameAdded=t,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,subtree:!0,attributeFilter:["enable-annotation"]})}disconnect(){this._isDisconnected=!0,this._mutationObserver.disconnect()}async _addFrame(e){this._annotatableFrames.add(e);try{if(await pr(e),this._isDisconnected)return
137
- ;e.contentWindow.addEventListener("unload",(()=>{this._removeFrame(e)})),this._onFrameAdded(e)}catch{console.warn(`Unable to inject the Hypothesis client (from '${document.location.href}' into a cross-origin frame '${e.src}')`)}}_removeFrame(e){this._annotatableFrames.delete(e),this._onFrameRemoved(e)}_discoverFrames(){const e=new Set(this._element.querySelectorAll("iframe[enable-annotation]"));for(const t of e)this._annotatableFrames.has(t)||this._addFrame(t);for(const t of this._annotatableFrames)e.has(t)||this._removeFrame(t)}}function pr(e){return new Promise(((t,n)=>{const o=gr(e,((e,i)=>{o(),i?t(i):n(e)}))}))}function gr(e,t,{pollInterval:n=10}={}){let o,i;const r=new WeakSet,s=()=>{clearTimeout(o),o=void 0},a=()=>{const n=e.contentDocument;if(n){if(!r.has(n)){if(r.add(n),s(),!function(e){return"about:blank"===e.contentDocument?.location.href&&e.hasAttribute("src")&&"about:blank"!==e.src}(e)){
138
- "interactive"===n.readyState||"complete"===n.readyState?t(null,n):n.addEventListener("DOMContentLoaded",(()=>t(null,n)))}e.contentDocument&&e.contentWindow?.addEventListener("unload",i)}}else{s();const n=e.isConnected?"Frame is cross-origin":"Frame is disconnected";t(new Error(n))}};let l=!1;i=()=>{s(),l||(o=setInterval(a,n))},e.addEventListener("load",a);const c=setTimeout(a,0);return()=>{l=!0,clearTimeout(c),s(),e.removeEventListener("load",a)}}class _r{constructor(e,t){this._config=t,this._frameObserver=new mr(e,(e=>br(e,t)),(()=>{}))}destroy(){this._frameObserver.disconnect()}}async function br(e,t,n){if(null!==e.contentDocument.querySelector("script.js-hypothesis-config"))return;await pr(e);const{assetRoot:o,notebookAppUrl:i,profileAppUrl:r,sidebarAppUrl:s}=vn(document),a={...t,assetRoot:o,notebookAppUrl:i,profileAppUrl:r,sidebarAppUrl:s,subFrameIdentifier:n??nn(10)},l=document.createElement("script");l.className="js-hypothesis-config",l.setAttribute("data-remove-on-unload",""),l.type="application/json",
139
- l.innerText=JSON.stringify(a);const c=document.createElement("script");c.async=!0,c.src=t.clientUrl;const h=e.contentDocument;h.body.appendChild(l),h.body.appendChild(c)}class wr{constructor(e,t,n){if(t.length!==n.length)throw new Error("Char boxes length does not match text length");const o=e.parentNode,i=document.createElement("hypothesis-text-layer");o.insertBefore(i,e.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=(e,t,n="px")=>`calc(var(--${e}-scale) * ${t}${n})`,l=function(e,t){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 e.entries()){const e=t[n],s=/\s/.test(e);o.text.length>0&&!Sn(o.rect,r)&&i(),o.rect=kn(o.rect,r),
140
- o.text+=s?" ":e,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 e of n){const t=s.words[s.words.length-1];if(t){const n=En(t.rect),o=En(e.rect).x-n.x;(!Sn(t.rect,e.rect)||o<0)&&a()}s.words.push(e),s.rect=kn(s.rect,e.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 e of r){const t=c.lines[c.lines.length-1];if(t){const n=En(t.rect),o=En(e.rect).y-n.y;(!An(t.rect,e.rect)||Sn(t.rect,e.rect)||o<0||o>4*e.rect.height)&&h()}c.lines.push(e),c.rect=kn(c.rect,e.rect)}return h(),l}(t,n);for(const e of l){const t=document.createElement("hypothesis-text-column");t.style.display="block",t.style.position="absolute",t.style.left=a("x",e.rect.left),t.style.top=a("y",e.rect.top);let n=null;for(const o of e.lines){const i=document.createElement("hypothesis-text-line");i.style.display="block",i.style.marginLeft=a("x",o.rect.left-e.rect.left),
141
- 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 e of o.words){const t=document.createElement("hypothesis-text-word");t.style.display="inline-block",t.style.transformOrigin="top left",t.textContent=e.text,r&&(t.style.marginLeft=a("x",e.rect.left-r.rect.right)),r=e,t.style.width=a("x",e.rect.width),t.style.height=a("y",e.rect.height),t.style.whiteSpace="pre";const n=s.measureText(e.text),o=a("x",e.rect.width/n.width,""),l=a("y",e.rect.height/16,"");t.style.transform=`scale(${o}, ${l})`,i.append(t)}t.append(i)}i.append(t)}const c=()=>{const{width:t,height:n}=e.getBoundingClientRect();i.style.width=t+"px",i.style.height=n+"px",i.style.setProperty("--x-scale",`${t}`),i.style.setProperty("--y-scale",`${n}`)};c(),this.container=i,this._updateTextLayerSize=Pi(c,{maxWait:50}),this._listeners=new ge,"undefined"!=typeof ResizeObserver&&(this._imageSizeObserver=new ResizeObserver((()=>{this._updateTextLayerSize()})),
142
- this._imageSizeObserver.observe(e)),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 vr(e=document){return e.querySelector("mosaic-book")}function yr(e=window){if(vr(e.document))return"container";const t=e.frameElement?.ownerDocument;return t&&vr(t)?"content":null}class xr{constructor(e){const t=vr();if(!t)throw new Error("Book container element not found");const n=new WeakSet,o=t.shadowRoot,i=()=>{const t=o.querySelector("iframe");t&&!n.has(t)&&(n.add(t),gr(t,((n,o)=>{if(n)return;const i=o.body;i&&!i.querySelector("#page-content")&&br(t,e,"vitalsource-content")})))};i(),this._frameObserver=new MutationObserver(i),this._frameObserver.observe(o,{childList:!0,subtree:!0})}destroy(){this._frameObserver.disconnect()}}function Nr(){return document.querySelector("img#pbk-page")}
143
- class Cr extends an{constructor(e=document.body,t={}){super();const n=t.bookElement??vr(window.parent.document);if(!n)throw new Error("Failed to find <mosaic-book> element in container frame");this._bookElement=n;const o=new $o;this._htmlIntegration=new Ai({container:e,features:o}),this._listeners=new ge;const i=["mouseup","mousedown","mouseout"];for(const e of i)this._listeners.add(document.documentElement,e,(e=>{e.stopPropagation()}));const r=window.frameElement;r&&function(e){if("no"!==e.getAttribute("scrolling"))return;const t=document.createElement("style");t.textContent="iframe { height: 100% !important; }",e.insertAdjacentElement("beforebegin",t);const n=()=>e.removeAttribute("scrolling");n(),new MutationObserver(n).observe(e,{attributes:!0})}(r);const s=Nr(),a=window.innerPageData;if(s&&a){const e=a.glyphs.glyphs.map((e=>{const t=e.l/100,n=e.r/100,o=e.t/100,i=e.b/100;return new DOMRect(t,o,n-t,i-o)}));this._textLayer=new wr(s,e,a.words),this._textLayer.container.style.zIndex="100",
144
- this._sideBySideActive=!1}}getAnnotatableRange(e){return this._htmlIntegration.getAnnotatableRange(e)}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(e,t){return this._htmlIntegration.anchor(e,t)}async describe(e,t){const n=this._htmlIntegration.describe(e,t),{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 e={type:"PageSelector",index:i,label:r};l.push(e)}return n.push(...l),n}contentContainer(){return this._htmlIntegration.contentContainer()}fitSideBySide(e){const t=Nr();if(t&&this._textLayer){const n=t.parentElement,o=this._textLayer,i=window.innerWidth-e.width;return this._sideBySideActive=!1,Hn((()=>{e.expanded&&i>480?(n.style.textAlign="left",t.style.width=`${i}px`,
145
- this._sideBySideActive=!0):(n.style.textAlign="",t.style.width=""),o.updateSync()})),this._sideBySideActive}return this._htmlIntegration.fitSideBySide(e)}sideBySideActive(){return"boolean"==typeof this._sideBySideActive?this._sideBySideActive:this._htmlIntegration.sideBySideActive()}supportedTools(){return["selection"]}async getMetadata(){return{title:this._bookElement.getBookInfo().title,link:[]}}navigateToSegment(e){const t=e.target[0].selector?.find((e=>"EPUBContentSelector"===e.type));if(t?.cfi)this._bookElement.goToCfi(t.cfi);else{if(!t?.url)throw new Error("No segment information available");this._bookElement.goToURL(function(e){const t=new URL(e,document.baseURI);return t.pathname+t.search}(t.url))}}persistFrame(){return!0}async _getPageInfo({includeTitle:e=!1,includePageIndex:t=!1}={}){const[n,o,i]=await Promise.all([this._bookElement.getCurrentPage(),e?this._bookElement.getTOC():void 0,t?this._bookElement.getPages():void 0]),r=["absoluteURL","cfi"]
146
- ;for(const e of r)if(!(e in n))throw new Error(`Page metadata field "${e}" is missing`);let s;if(o){s=n.chapterTitle;const e=fr(n.cfi),t=o.data?.find((t=>fr(t.cfi)===e));t&&(s=t.title)}let a=n.index;if(void 0===a&&i){const e=i.data?.findIndex((e=>e.cfi===n.cfi));-1!==e&&(a=e)}return{cfi:n.cfi,index:a,page:n.page,title:s,url:new URL(n.absoluteURL,document.baseURI).toString()}}async _getPageRange(e){let t=[];try{const e=await this._bookElement.getPageBreaks();e.ok&&e.data&&(t=e.data)}catch(e){console.error("Failed to get page breaks",e)}const n=ur(e),o=t.filter((e=>e.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:e,url:t}=await this._getPageInfo();return{cfi:e,pages:await this._getPageRange(e),url:t}}async uri(){const e=this._bookElement.getBookInfo().isbn;if(!e)throw new Error("Unable to get book ID from VitalSource");return`https://bookshelf.vitalsource.com/reader/books/${e}`}async scrollToAnchor(e){
147
- return this._htmlIntegration.scrollToAnchor(e)}}function Sr(e){if(void 0!==window.PDFViewerApplication)return new dr({annotator:e,features:e.features});return"content"===yr()?new Cr(document.body):new Ai({features:e.features,sideBySideOptions:e.sideBySide})}function Ar(){return Pe(jt,{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 kr{constructor(e){this._visible=!1,this._container=new eo("notice",(()=>this._render())),e.appendChild(this._container.element)}destroy(){this._container.destroy()}setVisible(e){this._visible=e,this._container.render()}_render(){return this._visible?Pe(Ar,{}):null}}class Er{constructor(e,t=document){let n=!1;this._pendingCallback=null;const o=(n=10)=>{this._pendingCallback=setTimeout((()=>{e(_o(t.getSelection()))}),n)},i=e=>{if("mousedown"===e.type&&(n=!0),"mouseup"===e.type&&(n=!1),n)return
148
- ;this._cancelPendingCallback();const t="mouseup"===e.type?10:100;o(t)};this._document=t,this._listeners=new ge,this._listeners.add(t,"selectionchange",i),this._listeners.add(t.body,"mousedown",i),this._listeners.add(t.body,"mouseup",i),o(1)}disconnect(){this._listeners.removeAll(),this._cancelPendingCallback()}_cancelPendingCallback(){this._pendingCallback&&(clearTimeout(this._pendingCallback),this._pendingCallback=null)}}function Rr(e,t){if(e===t)return!0;if(e.parent!==t)return!1;if(!e.frameElement)return!1;return e.frameElement.getBoundingClientRect().width/e.parent.innerWidth>=.8}function Pr(){return function(e,t){const n=new Set,o=new Set;return vo(e,(e=>{for(;e&&!n.has(e);){n.add(e);const i=t(e);null!=i&&o.add(i),e=e.parentNode}})),[...o]}(_o()??new Range,(e=>e._annotation?.$tag))}function Tr(e,t,n){return e.getHighlightsFromPoint(t,n).map((e=>e._annotation?.$tag)).filter((e=>void 0!==e))}function Mr(e){if(!e.region)return null;if(!function(e){
149
- return void 0!==e&&"toRange"in e&&"function"==typeof e.toRange}(e.region))return e.region;try{return e.region.toRange()}catch{return null}}function Or(){document.getSelection()?.removeAllRanges()}class Ir extends CustomEvent{constructor(e){super("scrolltorange",{bubbles:!0,cancelable:!0,detail:e}),this._ready=null}get ready(){return this._ready}waitUntil(e){this._ready=e}}class Lr extends an{constructor(e,t={},n=window){super(),this.element=e,this._contentReady=t.contentReady,this._hostFrame=n,this._highlightsVisible=!1,this._isAdderVisible=!1,this._informHostOnNextSelectionClear=!0,this.selectedRanges=[],this._outsideAssignmentNotice=null,this._highlighter=new Co(this.element),this._adder=new oo(this.element,{onAnnotate:()=>this.createAnnotationFromSelection(),onHighlight:()=>this.createAnnotationFromSelection({highlight:!0}),onShowAnnotations:e=>this.selectAnnotations(e,{focusInSidebar:!0})}),this._drawTool=new Fo(this.element),this._selectionObserver=new Er((e=>{
150
- e?this._onSelection(e):this._onClearSelection()})),this.anchors=[],this._annotations=new Set,this._frameIdentifier=t.subFrameIdentifier||null,this._portFinder=new sn({hostFrame:this._hostFrame,source:"guest",sourceId:this._frameIdentifier??void 0}),this.features=new $o,this._featureFlagsReceived=new Promise((e=>{this.features.on("flagsChanged",e)})),this.sideBySide=t.sideBySide,this._integration=Sr(this),this._integration.on("uriChanged",(()=>this._sendDocumentInfo())),t.contentInfoBanner&&this._integration.showContentInfo?.(t.contentInfoBanner),this._integration.canStyleClusteredHighlights?.()&&(this._clusterToolbar=new Yo(this._integration.contentContainer(),{features:this.features})),this._integration.on("supportedToolsChanged",(()=>this._notifySupportedToolsChanged())),this._hostRPC=new bn,this._connectHost(n),this._sidebarRPC=new bn,this._sidebarLayout=null,this._connectSidebar(),this._bucketBarClient=new Lo({contentContainer:this._integration.contentContainer(),hostRPC:this._hostRPC}),
151
- this._listeners=new ge,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",(e=>{if(!document.getSelection()?.isCollapsed)return;const{clientX:t,clientY:n,metaKey:o,ctrlKey:i}=e,r=Tr(this._highlighter,t,n);if(r.length){const e=o||i;this.selectAnnotations(r,{toggle:e})}})),this._listeners.add(this.element,"pointerdown",(e=>{this._sideBySideActive()||e.composedPath().some((e=>e instanceof Element&&e.localName.startsWith("hypothesis-")))||Tr(this._highlighter,e.clientX,e.clientY).length||Rr(window,this._hostFrame)&&this._sidebarLayout?.expanded&&window.innerWidth-e.clientX<this._sidebarLayout.width||this._sidebarRPC.call("closeSidebar")})),this._listeners.add(this.element,"mouseover",(({clientX:e,clientY:t})=>{const n=Tr(this._highlighter,e,t)
152
- ;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",(e=>{this._handleShortcut(e)})),this._listeners.add(window,"resize",(()=>this._repositionAdder()))}async getDocumentInfo(){const[e,t,n]=await Promise.all([this._integration.uri(),this._integration.getMetadata(),this._integration.segmentInfo?.()]);return{uri:Ci(e),metadata:t,segmentInfo:n,persistent:this._integration.persistFrame?.()??!1}}async _sendDocumentInfo(){this._integration.waitForFeatureFlags?.()&&await this._featureFlagsReceived;const e=await this.getDocumentInfo();this._sidebarRPC.call("documentInfoChanged",e)}_repositionAdder(){if(!this._isAdderVisible)return;const e=_o();e&&this._onSelection(e)}async _connectHost(e){this._hostRPC.on("clearSelection",(()=>{_o()&&(this._informHostOnNextSelectionClear=!1,Or())})),
153
- this._hostRPC.on("createAnnotation",(({tool:e})=>e?this.createAnnotation(e):(this._drawTool.cancel(),null))),this._hostRPC.on("hoverAnnotations",(e=>this._hoverAnnotations(e))),this._hostRPC.on("scrollToAnnotation",(e=>{this._scrollToAnnotation(e)})),this._hostRPC.on("selectAnnotations",((e,t)=>this.selectAnnotations(e,{toggle:t}))),this._hostRPC.on("sidebarLayoutChanged",(t=>{Rr(window,e)&&this.fitSideBySide(t),this.element.dispatchEvent(new Do({sidebarLayout:t,sideBySideActive:this._sideBySideActive()}))})),this._hostRPC.on("close",(()=>this.emit("hostDisconnected"))),this._notifySupportedToolsChanged();const t=await this._portFinder.discover("host");this._hostRPC.connect(t)}_notifySupportedToolsChanged(){this._hostRPC.call("supportedToolsChanged",this._integration.supportedTools())}async _scrollToAnchor(e){const t=Mr(e);if(!t)return;let n;t instanceof Range?n=t:(n=new Range,n.selectNodeContents(t.anchor));const o=new Ir(n);this.element.dispatchEvent(o)&&(await o.ready,
154
- await this._integration.scrollToAnchor(e))}async _scrollToAnnotation(e){const t=this.anchors.find((t=>t.annotation.$tag===e));t?.highlights&&await this._scrollToAnchor(t)}async _connectSidebar(){this._sidebarRPC.on("featureFlagsUpdated",(e=>this.features.update(e))),this._sidebarRPC.on("hoverAnnotations",(e=>this._hoverAnnotations(e))),this._sidebarRPC.on("scrollToAnnotation",(e=>{this._scrollToAnnotation(e)})),this._sidebarRPC.on("setHighlightsVisible",(e=>{this.setHighlightsVisible(e,!1)})),this._sidebarRPC.on("deleteAnnotation",(e=>this.detach(e))),this._sidebarRPC.on("loadAnnotations",(async e=>{try{await Promise.all(e.map((e=>this.anchor(e))))}catch(e){console.warn("Failed to anchor annotations:",e)}})),this._sidebarRPC.on("showContentInfo",(e=>this._integration.showContentInfo?.(e))),this._sidebarRPC.on("setOutsideAssignmentNoticeVisible",(e=>{this._setOutsideAssignmentNoticeVisible(e)})),this._sidebarRPC.on("navigateToSegment",(e=>this._integration.navigateToSegment?.(e))),
155
- this._sidebarRPC.on("renderThumbnail",((e,t,n)=>{(async()=>{if(!this._integration.renderToBitmap)throw new Error("Thumbnail rendering not supported for document type");const n=this.anchors.find((t=>t.annotation.$tag===e));if(!n)throw new Error("Annotation not anchored in guest");return this._integration.renderToBitmap(n,t)})().then((e=>n({ok:!0,value:e}))).catch((e=>n({ok:!1,error:e.message})))})),this._portFinder.discover("sidebar").then((e=>{this._sidebarRPC.connect(e)})),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(),super.destroy()}async anchor(e){this._contentReady&&(await this._contentReady,this._contentReady=void 0);const t=e=>{const t=Mr(e);if(!t)return
156
- ;let n;n=t instanceof Range?this._highlighter.highlightRange(t,e.annotation?.$cluster):this._highlighter.highlightShape(t),n.forEach((t=>{t._annotation=e.annotation})),e.highlights=n,this._hoveredAnnotations.has(e.annotation.$tag)&&this._highlighter.setHighlightsFocused(n,!0)};this.detach(e.$tag,!1),this._annotations.add(e.$tag),e.target||(e.target=[]);const n=await Promise.all(e.target.map((async t=>{if(!t.selector||!t.selector.some((e=>"TextQuoteSelector"===e.type||"ShapeSelector"===e.type)))return{annotation:e,target:t};let n;try{const o=await this._integration.anchor(this.element,t.selector);if(o instanceof Range){const i=fo.fromRange(o);n={annotation:e,target:t,region:i}}else n={annotation:e,target:t,region:o}}catch{n={annotation:e,target:t}}return n})));if(!this._annotations.has(e.$tag))return[];for(const e of n)t(e);return e.$orphan=n.length>0&&n.every((e=>e.target.selector&&!e.region)),this._updateAnchors(this.anchors.concat(n),!0),this._sidebarRPC.call("syncAnchoringStatus",e),n}detach(e,t=!0){
157
- this._annotations.delete(e);const n=[];for(const t of this.anchors)t.annotation.$tag!==e?n.push(t):t.highlights&&this._highlighter.removeHighlights(t.highlights);this._updateAnchors(n,t)}_updateAnchors(e,t){this.anchors=e,this._clusterToolbar?.scheduleClusterUpdates(),t&&this._bucketBarClient.update(this.anchors)}async createAnnotation(e){if("selection"===e)return this.createAnnotationFromSelection();if(!["rect","point"].includes(e))throw new Error("Unsupported annotation tool");{let t=!1;try{this._hostRPC.call("activeToolChanged",e);const t=await this._drawTool.draw(e),n=await this.getDocumentInfo(),o=[{source:n.uri,selector:await this._integration.describe(this.element,t)}],i={uri:n.uri,document:n.metadata,target:o,$tag:"a:"+nn(8)};return this._sidebarRPC.call("createAnnotation",i),this.anchor(i),i}catch(e){if(e instanceof Ho&&["canceled","restarted"].includes(e.kind))return t="restarted"===e.kind,null;throw e}finally{t||this._hostRPC.call("activeToolChanged",null)}}}
158
- async createAnnotationFromSelection({highlight:e=!1}={}){const t=this.selectedRanges;this.selectedRanges=[];const n=await this.getDocumentInfo(),o=this.element,i=(await Promise.all(t.map((e=>this._integration.describe(o,e))))).map((e=>({source:n.uri,selector:e}))),r={uri:n.uri,document:n.metadata,target:i,$highlight:e,$cluster:e?"user-highlights":"user-annotations",$tag:"a:"+nn(8)};return this._sidebarRPC.call("createAnnotation",r),this.anchor(r),Or(),r}_hoverAnnotations(e){this._hoveredAnnotations.clear(),e.forEach((e=>this._hoveredAnnotations.add(e)));for(const t of this.anchors)if(t.highlights){const n=e.includes(t.annotation.$tag);this._highlighter.setHighlightsFocused(t.highlights,n)}this._sidebarRPC.call("hoverAnnotations",e)}_onSelection(e){const t=this._integration.getAnnotatableRange(e);if(!t)return void this._onClearSelection();const n=document.getSelection(),o=bo(n),i=yo(n);i?(this.selectedRanges=[t],this._hostRPC.call("textSelected"),this._adder.annotationsForSelection=Pr(),
159
- 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(e,{toggle:t=!1,focusInSidebar:n=!1}={}){t?this._sidebarRPC.call("toggleAnnotationSelection",e):this._sidebarRPC.call("showAnnotations",e,n),this._sidebarRPC.call("openSidebar")}setHighlightsVisible(e,t=!0){this._highlighter.setHighlightsVisible(e),this._highlightsVisible=e,t&&this._hostRPC.call("highlightsVisibleChanged",e)}get highlightsVisible(){return this._highlightsVisible}fitSideBySide(e){this._sidebarLayout=e,this._integration.fitSideBySide(e)}get hoveredAnnotationTags(){return this._hoveredAnnotations}_handleShortcut(e){Wn(e,"Ctrl+Shift+H")&&this.setHighlightsVisible(!this._highlightsVisible)}_setOutsideAssignmentNoticeVisible(e){this._outsideAssignmentNotice||(this._outsideAssignmentNotice=new kr(this.element)),
160
- this._outsideAssignmentNotice.setVisible(e)}}function Br(e,t){const n=new URL(e),o=new URLSearchParams;return o.append("config",JSON.stringify(t)),n.hash=o.toString(),n.toString()}function Hr(e,t){const n={};for(const[e,o]of Object.entries(t))"notebookAppUrl"!==e&&"sidebarAppUrl"!==e&&null!=o&&(n[e]=o);n.origin=new URL(e).origin,n.version="1.1641.0";const o=new URL(window.location.href);if(o.hash="",n.hostURL=o.toString(),Array.isArray(n.services)&&n.services?.length>0){const e=n.services[0];e.onLoginRequest&&(e.onLoginRequestProvided=!0),e.onLogoutRequest&&(e.onLogoutRequestProvided=!0),e.onSignupRequest&&(e.onSignupRequestProvided=!0),e.onProfileRequest&&(e.onProfileRequestProvided=!0),e.onHelpRequest&&(e.onHelpRequestProvided=!0)}return n}function Fr({closed:e,onClose:t,children:n,"data-testid":o,"aria-label":i}){const r=oe(null);return te((()=>{e?r.current?.close():r.current?.showModal()}),[e]),te((()=>{const e=r.current;return e?.addEventListener("cancel",t),()=>{e?.removeEventListener("cancel",t)}
161
- }),[t]),Pe("dialog",{ref:r,className:"relative w-full h-full backdrop:bg-black/50","data-testid":o,"aria-label":i,children:n})}function Dr({closed:e,children:t,...n}){return Pe("div",{...n,className:Ee("fixed z-max top-0 left-0 right-0 bottom-0 p-3 bg-black/50",{hidden:e}),children:Pe("div",{className:"relative w-full h-full",children:t})})}function Vr({document_:e=document,...t}){return Pe(ie((()=>function(e){return"function"==typeof e.createElement("dialog").showModal}(e)?Fr:Dr),[e]),{...t})}function Ur({config:e,groupId:t}){return Pe("iframe",{title:"Hypothesis annotation notebook",className:"h-full w-full border-0",allow:"fullscreen; clipboard-write",src:Br(e.notebookAppUrl,{...Hr(e.notebookAppUrl,e),group:t})})}function qr({eventBus:e,config:t}){const[n,o]=ee(0),[i,r]=ee(!0),[s,a]=ee(null),l=oe(""),c=oe(null);te((()=>(l.current=document.body.style.overflow,()=>{document.body.style.overflow=l.current})),[]),te((()=>{document.body.style.overflow=i?l.current:"hidden"}),[i]),te((()=>{
162
- const t=e.createEmitter();return t.subscribe("openNotebook",(e=>{r(!1),o((e=>e+1)),a(e)})),c.current=t,()=>{t.destroy()}}),[e]);const h=re((()=>{r(!0),c.current?.publish("closeNotebook")}),[]);return null===s?null:Pe(Vr,{closed:i,onClose:h,"data-testid":"notebook-outer","aria-label":"Hypothesis notebook",children:[Pe("div",{className:"absolute right-0 m-3",children:Pe(kt,{title:"Close notebook",onClick:h,variant:"dark",classes:Ee("!bg-transparent enabled:hover:!bg-grey-3"),"data-testid":"close-button",children:Pe(Fe,{className:"w-4 h-4"})})}),Pe(Ur,{config:t,groupId:s},n)]})}class $r{constructor(e,t,n){this._container=new eo("notebook",(()=>Pe(qr,{eventBus:t,config:n}))),e.append(this._container.element),this._container.render()}destroy(){this._container.destroy()}}function zr({eventBus:e,config:t}){const[n,o]=ee(!0),i=oe(null);te((()=>{const t=e.createEmitter();return t.subscribe("openProfile",(()=>{o(!1)})),i.current=t,()=>{t.destroy()}}),[e]);const r=()=>{o(!0),i.current?.publish("closeProfile")}
163
- ;return n?null:Pe(Vr,{closed:n,onClose:r,"data-testid":"profile-outer","aria-label":"Hypothesis profile",children:[Pe("div",{className:"absolute right-0 m-3",children:Pe(kt,{title:"Close profile dialog",onClick:r,variant:"dark",classes:Ee("!bg-transparent enabled:hover:!bg-grey-3"),children:Pe(Fe,{className:"w-4 h-4"})})}),Pe("iframe",{title:"Hypothesis profile",className:"h-full w-full border-0",src:t.profileAppUrl})]})}class Wr{constructor(e,t,n){this._container=new eo("profile",(()=>Pe(zr,{eventBus:t,config:n}))),e.append(this._container.element),this._container.render()}destroy(){this._container.destroy()}}function jr({above:e,below:t,buckets:n,onFocusAnnotations:o,onScrollToAnnotation:i,onSelectAnnotations:r}){const s=e.anchors.length>0,a=t.anchors.length>0,l=e=>e.anchors.map((e=>e.tag));return Pe("ul",{className:"relative",children:[s&&Pe("li",{className:"absolute right-0 pointer-events-auto mt-[-11px]",style:{top:e.position},children:Pe(en,{"data-testid":"up-navigation-button",direction:"up",
164
- onClick:()=>{const t=[...e.anchors].sort(((e,t)=>e.bottom-t.bottom)),n=t[t.length-1];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})}),n.map(((e,t)=>Pe("li",{className:"absolute right-0 pointer-events-auto mt-[-8px]",style:{top:e.position},children:Pe(en,{direction:"left",onClick:t=>r(l(e),t.metaKey||t.ctrlKey),onBlur:()=>o([]),onFocus:()=>o(l(e)),onMouseEnter:()=>o(l(e)),onMouseOut:()=>o([]),title:`Select nearby annotations (${e.anchors.length})`,children:e.anchors.length})},t))),a&&Pe("li",{className:"absolute right-0 pointer-events-auto",style:{top:t.position},children:Pe(en,{"data-testid":"down-navigation-button",direction:"down",onClick:()=>{const e=[...t.anchors].sort(((e,t)=>e.top-t.top)),n=e[0];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})})]})}
165
- class Xr{constructor(e,{onFocusAnnotations:t,onScrollToAnnotation:n,onSelectAnnotations:o}){this._positions=[],this._container=new eo("bucket-bar",(()=>this._render())),Object.assign(this._container.element.style,{display:"block",flexGrow:"1",width:"100%"}),e.appendChild(this._container.element),this._onFocusAnnotations=t,this._onScrollToAnnotation=n,this._onSelectAnnotations=o,this._container.render()}destroy(){this._container.destroy()}update(e){this._positions=e,this._container.render()}_render(){const e=function(e,t){const n=[],o=[],i=[];let r=null;function s(e){const{bottom:t,top:n}=e;return{bottom:t,position:n+(t-n)/2,anchors:[e],top:n}}const a=t.getBoundingClientRect(),l=e.map((e=>({tag:e.tag,top:e.top-a.top,bottom:e.bottom-a.top})));for(const e of l){const t=(e.top+e.bottom)/2;if(t<30){n.push(e);continue}if(t>a.height-30){o.push(e);continue}if(!r){r=s(e);continue}const l=e.top>r.top&&e.bottom<r.bottom;if(e.top-r.bottom>60&&!l)i.push(r),r=s(e);else{const t=e.bottom>r.bottom?e.bottom:r.bottom,n=t-r.top
166
- ;r.anchors.push(e),r.bottom=t,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 Pe(jr,{above:e.above,below:e.below,buckets:e.buckets,onFocusAnnotations:e=>this._onFocusAnnotations(e),onScrollToAnnotation:e=>this._onScrollToAnnotation(e),onSelectAnnotations:(e,t)=>this._onSelectAnnotations(e,t)})}}function Yr({emitter:e}){const[t,n]=ee([]),o=re((e=>n((t=>[...t,e]))),[]),i=re((e=>n((t=>t.filter((t=>t.id!==e))))),[]);return te((()=>(e.subscribe("toastMessageAdded",o),e.subscribe("toastMessageDismissed",i),()=>{e.unsubscribe("toastMessageAdded",o),e.unsubscribe("toastMessageDismissed",i)})),[e,i,o]),Pe(Gt,{messages:t,onMessageDismiss:i})}function Kr({icon:e,pressedBackground:t=!0,...n}){return Pe(Ct,{classes:Ee("justify-center rounded","w-[30px] h-[30px] touch:h-[40px]","shadow border bg-white text-grey-6 hover:text-grey-9",t&&"aria-pressed:bg-grey-3"),...n,size:"custom",variant:"custom",
167
- children:Pe(e,{})})}function Gr({highlightsVisible:e}){return Pe("div",{className:"sr-only",role:"status","data-testid":"toolbar-status",children:e?"Highlights visible":"Highlights hidden"})}function Qr({activeTool:e=null,closeSidebar:t,createAnnotation:n,isSidebarOpen:o,sidebarContainerId:i,newAnnotationType:r,showHighlights:s,supportedTools:a=["selection"],toggleHighlights:l,toggleSidebar:c,toggleSidebarRef:h,useMinimalControls:d=!1}){return Pe("div",{className:Ee({"absolute right-full":d,"relative right-[11px]":!d},"w-[33px] z-2","text-px-base leading-none"),children:[d&&o&&Pe(Ct,{classes:Ee("transition-colors focus-visible-ring ring-inset","w-[27px] h-[27px] mt-[140px] ml-px-1.5","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:t,unstyled:!0,children:Pe(Fe,{})}),!d&&Pe(w,{children:[Pe(Ct,{
168
- classes:Ee("transition-colors focus-visible-ring ring-inset","h-[40px] w-[33px] pl-[6px] rounded-bl","bg-white text-grey-5 hover:text-grey-9","border-l border-b"),elementRef:h,title:"Annotation sidebar",expanded:o,"aria-controls":i,onClick:c,unstyled:!0,children:Pe(o?ze:qe,{})}),Pe("div",{className:"space-y-px-1.5 mt-px-2",children:[Pe(Kr,{title:"Show highlights",icon:s?xt:et,pressed:s,pressedBackground:!1,onClick:l}),a.includes("selection")&&Pe(Kr,{"data-testid":"text-annotation",title:"note"===r?"New page note":"New annotation",icon:"note"===r?lt:Be,onClick:()=>n("selection")}),a.includes("rect")&&Pe(Kr,{"data-testid":"rect-annotation",pressed:"rect"===e,title:"Rectangle annotation",icon:vt,onClick:()=>n("rect"===e?null:"rect")}),a.includes("point")&&Pe(Kr,{"data-testid":"point-annotation",pressed:"point"===e,title:"Pin annotation",icon:ht,onClick:()=>n("point"===e?null:"point")})]}),Pe(Gr,{highlightsVisible:s})]})]})}class Jr{constructor(e,t){
169
- const{createAnnotation:n,setSidebarOpen:o,setHighlightsVisible:i}=t;this.container=e,this._activeTool=null,this._useMinimalControls=!1,this._newAnnotationType="note",this._highlightsVisible=!1,this._sidebarOpen=!1,this._sidebarContainerId=t.sidebarContainerId,this._supportedAnnotationTools=["selection"],this._closeSidebar=()=>o(!1),this._toggleSidebar=()=>o(!this._sidebarOpen),this._toggleHighlights=()=>i(!this._highlightsVisible),this._createAnnotation=e=>{n(e),"selection"===e&&o(!0)},this._sidebarToggleButton={current:null},this.render()}getWidth(){return this.container.firstChild.getBoundingClientRect().width}set activeTool(e){this._activeTool=e,this.render()}get activeTool(){return this._activeTool}set useMinimalControls(e){this._useMinimalControls=e,this.render()}get useMinimalControls(){return this._useMinimalControls}set sidebarOpen(e){this._sidebarOpen=e,this.render()}get sidebarOpen(){return this._sidebarOpen}set newAnnotationType(e){this._newAnnotationType=e,this.render()}get newAnnotationType(){
170
- return this._newAnnotationType}set highlightsVisible(e){this._highlightsVisible=e,this.render()}get highlightsVisible(){return this._highlightsVisible}get sidebarToggleButton(){return this._sidebarToggleButton.current}set supportedAnnotationTools(e){this._supportedAnnotationTools=e,this.render()}get supportedAnnotationTools(){return this._supportedAnnotationTools}render(){F(Pe(Qr,{activeTool:this._activeTool,closeSidebar:this._closeSidebar,createAnnotation:this._createAnnotation,newAnnotationType:this._newAnnotationType,isSidebarOpen:this._sidebarOpen,sidebarContainerId:this._sidebarContainerId,showHighlights:this._highlightsVisible,supportedTools:this._supportedAnnotationTools,toggleHighlights:this._toggleHighlights,toggleSidebar:this._toggleSidebar,toggleSidebarRef:this._sidebarToggleButton,useMinimalControls:this.useMinimalControls}),this.container)}}class Zr{constructor({target:e,threshold:t=10,onDrag:n}){e.style.touchAction="none",this._listeners=new ge,this._startX=null,this._dragActive=!1,
171
- this._threshold=t,this._listeners.add(e,"pointerdown",(e=>{this._startX=e.clientX}));const o=e=>{if(null!==this._startX&&this._dragActive){const t=e.clientX-this._startX;n({type:"dragend",deltaX:t})}this._startX=null,this._dragActive=!1};this._listeners.add(window,"pointercancel",o),this._listeners.add(window,"pointerup",o),this._listeners.add(window,"pointermove",(e=>{if(null===this._startX)return;const t=e.clientX-this._startX;!this._dragActive&&Math.abs(t)>=this._threshold&&(this._dragActive=!0,n({type:"dragstart",deltaX:t})),this._dragActive&&n({type:"dragmove",deltaX:t})}))}destroy(){this._listeners.removeAll()}}class es{constructor(e,t,n){this._emitter=t.createEmitter(),this._guestWithSelection=null,this._guestRPC=[],this._sidebarRPC=new bn,this.iframe=function(e){const t=e.sidebarAppUrl,n=Br(t,Hr(t,e)),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,
172
- this.features=new $o;const o="sidebar-container",i=document.createElement("div");if(i.setAttribute("data-testid","toolbar-container"),this.toolbar=new Jr(i,{sidebarContainerId:o,createAnnotation:e=>{if(0===this._guestRPC.length)return;(this._guestWithSelection??this._guestRPC[0]).call("createAnnotation",{tool:e})},setSidebarOpen:e=>e?this.open():this.close(),setHighlightsVisible:e=>this.setHighlightsVisible(e)}),n.externalContainerSelector)this.externalFrame=document.querySelector(n.externalContainerSelector)??e,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 e;n.bucketContainerSelector&&(e=document.querySelector(n.bucketContainerSelector),
173
- e||console.warn(`Custom bucket container "${n.bucketContainerSelector}" not found`));const t=document.createElement("div");t.setAttribute("data-testid","sidebar-edge"),t.className=Ee("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",t.append(i),this.iframeContainer.append(t),e||(e=t),this.bucketBar=new Xr(e,{onFocusAnnotations:e=>this._guestRPC.forEach((t=>t.call("hoverAnnotations",e))),onScrollToAnnotation:e=>this._guestRPC.forEach((t=>t.call("scrollToAnnotation",e))),onSelectAnnotations:(e,t)=>this._guestRPC.forEach((n=>n.call("selectAnnotations",e,t)))})}this.iframeContainer.appendChild(this.iframe),this._hypothesisSidebar=document.createElement("hypothesis-sidebar");const t=Zn(this._hypothesisSidebar);t.appendChild(this.iframeContainer),e.appendChild(this._hypothesisSidebar),this._messagesElement=document.createElement("div"),t.appendChild(this._messagesElement),F(Pe(Yr,{
174
- emitter:this._emitter}),this._messagesElement)}this.iframe.contentWindow&&dn(this.iframe.contentWindow),this._listeners=new ge,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 Zr({target:r,onDrag:e=>this._onDragSidebarToggleButton(e)})),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()}destroy(){this._guestRPC.forEach((e=>e.destroy())),this._sidebarRPC.destroy(),this.bucketBar?.destroy(),this._listeners.removeAll(),this._dragResizeHandler?.destroy(),
175
- this._hypothesisSidebar?(F(null,this._messagesElement),this._hypothesisSidebar.remove()):this.iframe.remove(),this._emitter.destroy(),dn(null)}onFrameConnected(e,t){switch(e){case"guest":this._connectGuest(t);break;case"sidebar":this._sidebarRPC.connect(t)}}_connectGuest(e){const t=new bn;t.on("textSelected",(()=>{this._guestWithSelection=t,this.toolbar.newAnnotationType="annotation",this._guestRPC.filter((e=>e!==t)).forEach((e=>e.call("clearSelection")))})),t.on("textUnselected",(()=>{this._guestWithSelection=null,this.toolbar.newAnnotationType="note",this._guestRPC.filter((e=>e!==t)).forEach((e=>e.call("clearSelection")))})),t.on("activeToolChanged",(e=>{this.toolbar.activeTool=e})),t.on("highlightsVisibleChanged",(e=>{this.setHighlightsVisible(e)}));const n=this.bucketBar;n&&t.on("anchorsChanged",(e=>{0===this._guestRPC.indexOf(t)&&n.update(e)})),t.on("close",(()=>{t.destroy(),t===this._guestWithSelection&&(this._guestWithSelection=null),this._guestRPC=this._guestRPC.filter((e=>e!==t))})),
176
- t.on("supportedToolsChanged",(e=>{this.toolbar.supportedAnnotationTools=e})),t.connect(e),this._guestRPC.push(t),t.call("sidebarLayoutChanged",this._layoutState)}_setupSidebarEvents(){var e;e=document.body,this._sidebarRPC.on("publicAnnotationCountChanged",(function(t){const n=e.querySelectorAll("[data-hypothesis-annotation-count]");Array.from(n).forEach((e=>{e.textContent=t.toString()}))})),function(e,t){const n=e.querySelectorAll("[data-hypothesis-trigger]");Array.from(n).forEach((e=>{e.addEventListener("click",(e=>{t(),e.stopPropagation()}))}))}(document.body,(()=>this.open())),this._sidebarRPC.on("featureFlagsUpdated",(e=>this.features.update(e))),this._sidebarRPC.on("connect",(()=>{this.iframeContainer&&(this.iframeContainer.style.display="");const e="always"===this._config.showHighlights;this.setHighlightsVisible(e),(this._config.openSidebar||this._config.annotations||this._config.query||this._config.group)&&this.open()})),this._sidebarRPC.on("showHighlights",(()=>this.setHighlightsVisible(!0))),
177
- this._sidebarRPC.on("openSidebar",(()=>this.open())),this._sidebarRPC.on("closeSidebar",(()=>this.close())),this._sidebarRPC.on("openNotebook",(e=>{this.hide(),this._emitter.publish("openNotebook",e)})),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",(e=>{this._emitter.publish("toastMessageAdded",e)})),this._sidebarRPC.on("toastMessageDismissed",(e=>{this._emitter.publish("toastMessageDismissed",e)}));[["loginRequested",this.onLoginRequest],["logoutRequested",this.onLogoutRequest],["signupRequested",this.onSignupRequest],["profileRequested",this.onProfileRequest],["helpRequested",this.onHelpRequest]].forEach((([e,t])=>{t&&this._sidebarRPC.on(e,(()=>t()))}))}_resetDragResizeState(){this._dragResizeState={initial:null,final:null}}_updateLayout(){
178
- this._renderFrame||(this._renderFrame=requestAnimationFrame((()=>{if(this._renderFrame=void 0,"number"==typeof this._dragResizeState.final&&this._dragResizeState.final!==this._dragResizeState.initial&&this.iframeContainer){const e=this._dragResizeState.final,t=-e;this.iframeContainer.style.marginLeft=`${e}px`,t>=280&&(this.iframeContainer.style.width=`${t}px`),this._updateLayoutState()}})))}_updateLayoutState(e){const t=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=t;"boolean"==typeof e?e&&(a+=r):(s<280?a-=s:a+=r,e=a>t);const l={expanded:e,width:e?a:t,height:o,toolbarWidth:t};this._layoutState=l,this.onLayoutChange?.(l),this._guestRPC.forEach((e=>e.call("sidebarLayoutChanged",l)))}_onResize(){!0===this.toolbar.sidebarOpen&&(window.innerWidth<280?this.close():this.open())}isResizing(){return null!==this._dragResizeState.initial}
179
- _onDragSidebarToggleButton(e){const t=this.iframeContainer;if(t)switch(e.type){case"dragstart":this._resetDragResizeState(),t.classList.add("sidebar-no-transition"),this.toolbar.container.style.pointerEvents="none",this._dragResizeState.initial=parseInt(getComputedStyle(t).marginLeft);break;case"dragend":t.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 t=this._dragResizeState.initial,n=e.deltaX;this._dragResizeState.final=Math.min(Math.round(t+n),0),this._updateLayout();break}}}open(){if(this._sidebarRPC.call("sidebarOpened"),this.iframeContainer){const e=this.iframeContainer.getBoundingClientRect().width;this.iframeContainer.style.marginLeft=-1*e+"px",this.iframeContainer.classList.remove("sidebar-collapsed")}this.toolbar.sidebarOpen=!0,
180
- "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(e){this.toolbar.highlightsVisible=e,this._sidebarRPC.call("setHighlightsVisible",e)}show(){this.iframeContainer?.classList.remove("is-hidden")}hide(){this.iframeContainer?.classList.add("is-hidden")}}class ts{constructor(e){this._emitter=e,this._subscriptions=[]}publish(e,...t){this._emitter.emit(e,...t)}subscribe(e,t){this._emitter.on(e,t),this._subscriptions.push([e,t])}unsubscribe(e,t){this._emitter.off(e,t),this._subscriptions=this._subscriptions.filter((([n,o])=>n!==e||o!==t))}destroy(){for(const[e,t]of this._subscriptions)this._emitter.off(e,t);this._subscriptions=[]}}class ns{
181
- constructor(){this._emitter=new an}createEmitter(){return new ts(this._emitter)}}const os=document.querySelector('link[type="application/annotator+html"][rel="sidebar"]');new Promise((e=>{"loading"!==document.readyState&&e(),document.addEventListener("readystatechange",(()=>e()))})).then((function(){const e=$n("annotator");let t=()=>{};const n=new Promise((e=>{t=e}));os.addEventListener("destroy",t);const o=e.subFrameIdentifier?window.parent:window,i=[];if(o===window){if(function(){const e=document.querySelectorAll(["hypothesis-sidebar","hypothesis-notebook","hypothesis-profile"].join(","));return e.forEach((e=>e.remove())),e.length>0}())return void console.warn("Hypothesis did not load because it found an existing instance on the page.");const e=function(e=navigator.userAgent){if(!_n(e))return()=>{};const t=e=>{if("hypothesisPortClosed"===e.data?.type&&e.ports[0]){const t=e.ports[0];gn(t,"close"),t.close()}};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}();i.push({
182
- destroy:e});const t=$n("sidebar"),n=new URL(t.sidebarAppUrl).origin,o=new un(n),r=new ns,s=new es(document.body,r,t),a=new $r(document.body,r,$n("notebook")),l=new Wr(document.body,r,$n("profile"));o.on("frameConnected",((e,t)=>s.onFrameConnected(e,t))),i.push(o,s,a,l)}if("container"===yr()){const t=new xr(e);i.push(t)}else{const n=new _r(document.body,e),r=new Lr(document.body,e,o);r.on("hostDisconnected",t),i.push(n,r)}n.then((()=>{i.forEach((e=>e.destroy()));document.querySelectorAll("[data-hypothesis-asset]").forEach((e=>e.remove())),function(e=document){Array.from(e.querySelectorAll("script.js-hypothesis-config[data-remove-on-unload]")).forEach((e=>e.remove()))}()}))}))}();
135
+ const n=e.target.selector?.find((e=>"ShapeSelector"===e.type)),o=e.target.selector?.find((e=>"PageSelector"===e.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:e,y:t}=n.shape,[o,,c]=i.pdfPage.view,h=.1*Math.abs(c-o);r=e-h,a=t+h,s=e+h,l=t-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=t.devicePixelRatio??1,m=h*u*f,p=h/d,g="number"==typeof t.maxWidth?Math.min(t.maxWidth,m):m,_=g/p,b=i.pdfPage.getViewport({scale:1}),w=g/m*u*f,v=new(0,b.constructor)({rotation:c,scale:w,
136
+ userUnit:b.userUnit,viewBox:[r,l,s,a]}),y=Math.max(g,1),x=Math.max(_,1),N=new OffscreenCanvas(y,x),C=N.getContext("2d"),S=i.pdfPage.render({canvasContext:C,viewport:v});if(await S.promise,"point"===n.shape.type){C.save(),C.scale(w,w);const e=n.shape.x-r,t=n.shape.y-l,o=5;C.strokeStyle="black",C.fillStyle="yellow",C.beginPath(),C.arc(e,t,o,0,2*Math.PI),C.fill(),C.stroke(),C.restore()}return N.transferToImageBitmap()}}function ur(e){if(!e.includes("["))return e;let t="",n=!1,o=!1;for(const i of e)n||"^"!==i?(n||"["!==i?!n&&o&&"]"===i?o=!1:o||(t+=i):o=!0,n=!1):n=!0;return t}function fr(e){const t=ur(e),n=t.indexOf("!");return-1===n?t:t.slice(0,n)}class mr{constructor(e,t,n){this._element=e,this._onFrameAdded=t,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,subtree:!0,attributeFilter:["enable-annotation"]})}
137
+ disconnect(){this._isDisconnected=!0,this._mutationObserver.disconnect()}async _addFrame(e){this._annotatableFrames.add(e);try{if(await pr(e),this._isDisconnected)return;e.contentWindow.addEventListener("unload",(()=>{this._removeFrame(e)})),this._onFrameAdded(e)}catch{console.warn(`Unable to inject the Hypothesis client (from '${document.location.href}' into a cross-origin frame '${e.src}')`)}}_removeFrame(e){this._annotatableFrames.delete(e),this._onFrameRemoved(e)}_discoverFrames(){const e=new Set(this._element.querySelectorAll("iframe[enable-annotation]"));for(const t of e)this._annotatableFrames.has(t)||this._addFrame(t);for(const t of this._annotatableFrames)e.has(t)||this._removeFrame(t)}}function pr(e){return new Promise(((t,n)=>{const o=gr(e,((e,i)=>{o(),i?t(i):n(e)}))}))}function gr(e,t,{pollInterval:n=10}={}){let o,i;const r=new WeakSet,s=()=>{clearTimeout(o),o=void 0},a=()=>{const n=e.contentDocument;if(n){if(!r.has(n)){if(r.add(n),s(),!function(e){
138
+ return"about:blank"===e.contentDocument?.location.href&&e.hasAttribute("src")&&"about:blank"!==e.src}(e)){"interactive"===n.readyState||"complete"===n.readyState?t(null,n):n.addEventListener("DOMContentLoaded",(()=>t(null,n)))}e.contentDocument&&e.contentWindow?.addEventListener("unload",i)}}else{s();const n=e.isConnected?"Frame is cross-origin":"Frame is disconnected";t(new Error(n))}};let l=!1;i=()=>{s(),l||(o=setInterval(a,n))},e.addEventListener("load",a);const c=setTimeout(a,0);return()=>{l=!0,clearTimeout(c),s(),e.removeEventListener("load",a)}}class _r{constructor(e,t){this._config=t,this._frameObserver=new mr(e,(e=>br(e,t)),(()=>{}))}destroy(){this._frameObserver.disconnect()}}async function br(e,t,n){if(null!==e.contentDocument.querySelector("script.js-hypothesis-config"))return;await pr(e);const{assetRoot:o,notebookAppUrl:i,profileAppUrl:r,sidebarAppUrl:s}=vn(document),a={...t,assetRoot:o,notebookAppUrl:i,profileAppUrl:r,sidebarAppUrl:s,subFrameIdentifier:n??nn(10)
139
+ },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=t.clientUrl;const h=e.contentDocument;h.body.appendChild(l),h.body.appendChild(c)}class wr{constructor(e,t,n){if(t.length!==n.length)throw new Error("Char boxes length does not match text length");const o=e.parentNode,i=document.createElement("hypothesis-text-layer");o.insertBefore(i,e.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=(e,t,n="px")=>`calc(var(--${e}-scale) * ${t}${n})`,l=function(e,t){const n=[];let o={text:"",rect:new DOMRect};const i=()=>{o.text.length>0&&(n.push(o),o={text:"",
140
+ rect:new DOMRect})};for(const[n,r]of e.entries()){const e=t[n],s=/\s/.test(e);o.text.length>0&&!Sn(o.rect,r)&&i(),o.rect=kn(o.rect,r),o.text+=s?" ":e,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 e of n){const t=s.words[s.words.length-1];if(t){const n=En(t.rect),o=En(e.rect).x-n.x;(!Sn(t.rect,e.rect)||o<0)&&a()}s.words.push(e),s.rect=kn(s.rect,e.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 e of r){const t=c.lines[c.lines.length-1];if(t){const n=En(t.rect),o=En(e.rect).y-n.y;(!An(t.rect,e.rect)||Sn(t.rect,e.rect)||o<0||o>4*e.rect.height)&&h()}c.lines.push(e),c.rect=kn(c.rect,e.rect)}return h(),l}(t,n);for(const e of l){const t=document.createElement("hypothesis-text-column");t.style.display="block",t.style.position="absolute",t.style.left=a("x",e.rect.left),t.style.top=a("y",e.rect.top);let n=null;for(const o of e.lines){
141
+ const i=document.createElement("hypothesis-text-line");i.style.display="block",i.style.marginLeft=a("x",o.rect.left-e.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 e of o.words){const t=document.createElement("hypothesis-text-word");t.style.display="inline-block",t.style.transformOrigin="top left",t.textContent=e.text,r&&(t.style.marginLeft=a("x",e.rect.left-r.rect.right)),r=e,t.style.width=a("x",e.rect.width),t.style.height=a("y",e.rect.height),t.style.whiteSpace="pre";const n=s.measureText(e.text),o=a("x",e.rect.width/n.width,""),l=a("y",e.rect.height/16,"");t.style.transform=`scale(${o}, ${l})`,i.append(t)}t.append(i)}i.append(t)}const c=()=>{const{width:t,height:n}=e.getBoundingClientRect();i.style.width=t+"px",i.style.height=n+"px",i.style.setProperty("--x-scale",`${t}`),i.style.setProperty("--y-scale",`${n}`)};c(),this.container=i,this._updateTextLayerSize=Pi(c,{maxWait:50}),
142
+ this._listeners=new ge,"undefined"!=typeof ResizeObserver&&(this._imageSizeObserver=new ResizeObserver((()=>{this._updateTextLayerSize()})),this._imageSizeObserver.observe(e)),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 vr(e=document){return e.querySelector("mosaic-book")}function yr(e=window){if(vr(e.document))return"container";const t=e.frameElement?.ownerDocument;return t&&vr(t)?"content":null}class xr{constructor(e){const t=vr();if(!t)throw new Error("Book container element not found");const n=new WeakSet,o=t.shadowRoot,i=()=>{const t=o.querySelector("iframe");t&&!n.has(t)&&(n.add(t),gr(t,((n,o)=>{if(n)return;const i=o.body;i&&!i.querySelector("#page-content")&&br(t,e,"vitalsource-content")})))};i(),this._frameObserver=new MutationObserver(i),
143
+ this._frameObserver.observe(o,{childList:!0,subtree:!0})}destroy(){this._frameObserver.disconnect()}}function Nr(){return document.querySelector("img#pbk-page")}class Cr extends an{constructor(e=document.body,t={}){super();const n=t.bookElement??vr(window.parent.document);if(!n)throw new Error("Failed to find <mosaic-book> element in container frame");this._bookElement=n;const o=new $o;this._htmlIntegration=new Ai({container:e,features:o}),this._listeners=new ge;const i=["mouseup","mousedown","mouseout"];for(const e of i)this._listeners.add(document.documentElement,e,(e=>{e.stopPropagation()}));const r=window.frameElement;r&&function(e){if("no"!==e.getAttribute("scrolling"))return;const t=document.createElement("style");t.textContent="iframe { height: 100% !important; }",e.insertAdjacentElement("beforebegin",t);const n=()=>e.removeAttribute("scrolling");n(),new MutationObserver(n).observe(e,{attributes:!0})}(r);const s=Nr(),a=window.innerPageData;if(s&&a){const e=a.glyphs.glyphs.map((e=>{
144
+ const t=e.l/100,n=e.r/100,o=e.t/100,i=e.b/100;return new DOMRect(t,o,n-t,i-o)}));this._textLayer=new wr(s,e,a.words),this._textLayer.container.style.zIndex="100",this._sideBySideActive=!1}}getAnnotatableRange(e){return this._htmlIntegration.getAnnotatableRange(e)}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(e,t){return this._htmlIntegration.anchor(e,t)}async describe(e,t){const n=this._htmlIntegration.describe(e,t),{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 e={type:"PageSelector",index:i,label:r};l.push(e)}return n.push(...l),n}contentContainer(){return this._htmlIntegration.contentContainer()}fitSideBySide(e){const t=Nr();if(t&&this._textLayer){
145
+ const n=t.parentElement,o=this._textLayer,i=window.innerWidth-e.width;return this._sideBySideActive=!1,Hn((()=>{e.expanded&&i>480?(n.style.textAlign="left",t.style.width=`${i}px`,this._sideBySideActive=!0):(n.style.textAlign="",t.style.width=""),o.updateSync()})),this._sideBySideActive}return this._htmlIntegration.fitSideBySide(e)}sideBySideActive(){return"boolean"==typeof this._sideBySideActive?this._sideBySideActive:this._htmlIntegration.sideBySideActive()}supportedTools(){return["selection"]}async getMetadata(){return{title:this._bookElement.getBookInfo().title,link:[]}}navigateToSegment(e){const t=e.target[0].selector?.find((e=>"EPUBContentSelector"===e.type));if(t?.cfi)this._bookElement.goToCfi(t.cfi);else{if(!t?.url)throw new Error("No segment information available");this._bookElement.goToURL(function(e){const t=new URL(e,document.baseURI);return t.pathname+t.search}(t.url))}}persistFrame(){return!0}async _getPageInfo({includeTitle:e=!1,includePageIndex:t=!1}={}){
146
+ const[n,o,i]=await Promise.all([this._bookElement.getCurrentPage(),e?this._bookElement.getTOC():void 0,t?this._bookElement.getPages():void 0]),r=["absoluteURL","cfi"];for(const e of r)if(!(e in n))throw new Error(`Page metadata field "${e}" is missing`);let s;if(o){s=n.chapterTitle;const e=fr(n.cfi),t=o.data?.find((t=>fr(t.cfi)===e));t&&(s=t.title)}let a=n.index;if(void 0===a&&i){const e=i.data?.findIndex((e=>e.cfi===n.cfi));-1!==e&&(a=e)}return{cfi:n.cfi,index:a,page:n.page,title:s,url:new URL(n.absoluteURL,document.baseURI).toString()}}async _getPageRange(e){let t=[];try{const e=await this._bookElement.getPageBreaks();e.ok&&e.data&&(t=e.data)}catch(e){console.error("Failed to get page breaks",e)}const n=ur(e),o=t.filter((e=>e.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:e,url:t}=await this._getPageInfo();return{cfi:e,pages:await this._getPageRange(e),url:t}}async uri(){
147
+ const e=this._bookElement.getBookInfo().isbn;if(!e)throw new Error("Unable to get book ID from VitalSource");return`https://bookshelf.vitalsource.com/reader/books/${e}`}async scrollToAnchor(e){return this._htmlIntegration.scrollToAnchor(e)}}function Sr(e){if(void 0!==window.PDFViewerApplication)return new dr({annotator:e,features:e.features});return"content"===yr()?new Cr(document.body):new Ai({features:e.features,sideBySideOptions:e.sideBySide})}function Ar(){return Pe(jt,{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 kr{constructor(e){this._visible=!1,this._container=new eo("notice",(()=>this._render())),e.appendChild(this._container.element)}destroy(){this._container.destroy()}setVisible(e){this._visible=e,this._container.render()}_render(){return this._visible?Pe(Ar,{}):null}}class Er{constructor(e,t=document){let n=!1
148
+ ;this._pendingCallback=null;const o=(n=10)=>{this._pendingCallback=setTimeout((()=>{e(_o(t.getSelection()))}),n)},i=e=>{if("mousedown"===e.type&&(n=!0),"mouseup"===e.type&&(n=!1),n)return;this._cancelPendingCallback();const t="mouseup"===e.type?10:100;o(t)};this._document=t,this._listeners=new ge,this._listeners.add(t,"selectionchange",i),this._listeners.add(t.body,"mousedown",i),this._listeners.add(t.body,"mouseup",i),o(1)}disconnect(){this._listeners.removeAll(),this._cancelPendingCallback()}_cancelPendingCallback(){this._pendingCallback&&(clearTimeout(this._pendingCallback),this._pendingCallback=null)}}function Rr(e,t){if(e===t)return!0;if(e.parent!==t)return!1;if(!e.frameElement)return!1;return e.frameElement.getBoundingClientRect().width/e.parent.innerWidth>=.8}function Pr(){return function(e,t){const n=new Set,o=new Set;return vo(e,(e=>{for(;e&&!n.has(e);){n.add(e);const i=t(e);null!=i&&o.add(i),e=e.parentNode}})),[...o]}(_o()??new Range,(e=>e._annotation?.$tag))}function Tr(e,t,n){
149
+ return e.getHighlightsFromPoint(t,n).map((e=>e._annotation?.$tag)).filter((e=>void 0!==e))}function Mr(e){if(!e.region)return null;if(!function(e){return void 0!==e&&"toRange"in e&&"function"==typeof e.toRange}(e.region))return e.region;try{return e.region.toRange()}catch{return null}}function Or(){document.getSelection()?.removeAllRanges()}class Ir extends CustomEvent{constructor(e){super("scrolltorange",{bubbles:!0,cancelable:!0,detail:e}),this._ready=null}get ready(){return this._ready}waitUntil(e){this._ready=e}}class Lr extends an{constructor(e,t={},n=window){super(),this.element=e,this._contentReady=t.contentReady,this._hostFrame=n,this._highlightsVisible=!1,this._isAdderVisible=!1,this._informHostOnNextSelectionClear=!0,this.selectedRanges=[],this._outsideAssignmentNotice=null,this._highlighter=new Co(this.element),this._adder=new oo(this.element,{onAnnotate:()=>this.createAnnotationFromSelection(),onHighlight:()=>this.createAnnotationFromSelection({highlight:!0}),
150
+ onShowAnnotations:e=>this.selectAnnotations(e,{focusInSidebar:!0})}),this._drawTool=new Fo(this.element),this._selectionObserver=new Er((e=>{e?this._onSelection(e):this._onClearSelection()})),this.anchors=[],this._annotations=new Set,this._frameIdentifier=t.subFrameIdentifier||null,this._portFinder=new sn({hostFrame:this._hostFrame,source:"guest",sourceId:this._frameIdentifier??void 0}),this.features=new $o,this._featureFlagsReceived=new Promise((e=>{this.features.on("flagsChanged",e)})),this.sideBySide=t.sideBySide,this._integration=Sr(this),this._integration.on("uriChanged",(()=>this._sendDocumentInfo())),t.contentInfoBanner&&this._integration.showContentInfo?.(t.contentInfoBanner),this._integration.canStyleClusteredHighlights?.()&&(this._clusterToolbar=new Yo(this._integration.contentContainer(),{features:this.features})),this._integration.on("supportedToolsChanged",(()=>this._notifySupportedToolsChanged())),this._hostRPC=new bn,this._connectHost(n),this._sidebarRPC=new bn,this._sidebarLayout=null,
151
+ this._connectSidebar(),this._bucketBarClient=new Lo({contentContainer:this._integration.contentContainer(),hostRPC:this._hostRPC}),this._listeners=new ge,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",(e=>{if(!document.getSelection()?.isCollapsed)return;const{clientX:t,clientY:n,metaKey:o,ctrlKey:i}=e,r=Tr(this._highlighter,t,n);if(r.length){const e=o||i;this.selectAnnotations(r,{toggle:e})}})),this._listeners.add(this.element,"pointerdown",(e=>{this._sideBySideActive()||e.composedPath().some((e=>e instanceof Element&&e.localName.startsWith("hypothesis-")))||Tr(this._highlighter,e.clientX,e.clientY).length||Rr(window,this._hostFrame)&&this._sidebarLayout?.expanded&&window.innerWidth-e.clientX<this._sidebarLayout.width||this._sidebarRPC.call("closeSidebar")})),
152
+ this._listeners.add(this.element,"mouseover",(({clientX:e,clientY:t})=>{const n=Tr(this._highlighter,e,t);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",(e=>{this._handleShortcut(e)})),this._listeners.add(window,"resize",(()=>this._repositionAdder()))}async getDocumentInfo(){const[e,t,n]=await Promise.all([this._integration.uri(),this._integration.getMetadata(),this._integration.segmentInfo?.()]);return{uri:Ci(e),metadata:t,segmentInfo:n,persistent:this._integration.persistFrame?.()??!1}}async _sendDocumentInfo(){this._integration.waitForFeatureFlags?.()&&await this._featureFlagsReceived;const e=await this.getDocumentInfo();this._sidebarRPC.call("documentInfoChanged",e)}_repositionAdder(){if(!this._isAdderVisible)return;const e=_o();e&&this._onSelection(e)}async _connectHost(e){this._hostRPC.on("clearSelection",(()=>{
153
+ _o()&&(this._informHostOnNextSelectionClear=!1,Or())})),this._hostRPC.on("createAnnotation",(({tool:e})=>e?this.createAnnotation(e):(this._drawTool.cancel(),null))),this._hostRPC.on("hoverAnnotations",(e=>this._hoverAnnotations(e))),this._hostRPC.on("scrollToAnnotation",(e=>{this._scrollToAnnotation(e)})),this._hostRPC.on("selectAnnotations",((e,t)=>this.selectAnnotations(e,{toggle:t}))),this._hostRPC.on("sidebarLayoutChanged",(t=>{Rr(window,e)&&this.fitSideBySide(t),this.element.dispatchEvent(new Do({sidebarLayout:t,sideBySideActive:this._sideBySideActive()}))})),this._hostRPC.on("close",(()=>this.emit("hostDisconnected"))),this._notifySupportedToolsChanged();const t=await this._portFinder.discover("host");this._hostRPC.connect(t)}_notifySupportedToolsChanged(){this._hostRPC.call("supportedToolsChanged",this._integration.supportedTools())}async _scrollToAnchor(e){const t=Mr(e);if(!t)return;let n;t instanceof Range?n=t:(n=new Range,n.selectNodeContents(t.anchor));const o=new Ir(n)
154
+ ;this.element.dispatchEvent(o)&&(await o.ready,await this._integration.scrollToAnchor(e))}async _scrollToAnnotation(e){const t=this.anchors.find((t=>t.annotation.$tag===e));t?.highlights&&await this._scrollToAnchor(t)}async _connectSidebar(){this._sidebarRPC.on("featureFlagsUpdated",(e=>this.features.update(e))),this._sidebarRPC.on("hoverAnnotations",(e=>this._hoverAnnotations(e))),this._sidebarRPC.on("scrollToAnnotation",(e=>{this._scrollToAnnotation(e)})),this._sidebarRPC.on("setHighlightsVisible",(e=>{this.setHighlightsVisible(e,!1)})),this._sidebarRPC.on("deleteAnnotation",(e=>this.detach(e))),this._sidebarRPC.on("loadAnnotations",(async e=>{try{await Promise.all(e.map((e=>this.anchor(e))))}catch(e){console.warn("Failed to anchor annotations:",e)}})),this._sidebarRPC.on("showContentInfo",(e=>this._integration.showContentInfo?.(e))),this._sidebarRPC.on("setOutsideAssignmentNoticeVisible",(e=>{this._setOutsideAssignmentNoticeVisible(e)})),
155
+ this._sidebarRPC.on("navigateToSegment",(e=>this._integration.navigateToSegment?.(e))),this._sidebarRPC.on("renderThumbnail",((e,t,n)=>{(async()=>{if(!this._integration.renderToBitmap)throw new Error("Thumbnail rendering not supported for document type");const n=this.anchors.find((t=>t.annotation.$tag===e));if(!n)throw new Error("Annotation not anchored in guest");return this._integration.renderToBitmap(n,t)})().then((e=>n({ok:!0,value:e}))).catch((e=>n({ok:!1,error:e.message})))})),this._portFinder.discover("sidebar").then((e=>{this._sidebarRPC.connect(e)})),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(),super.destroy()}async anchor(e){
156
+ this._contentReady&&(await this._contentReady,this._contentReady=void 0);const t=e=>{const t=Mr(e);if(!t)return;let n;n=t instanceof Range?this._highlighter.highlightRange(t,e.annotation?.$cluster):this._highlighter.highlightShape(t),n.forEach((t=>{t._annotation=e.annotation})),e.highlights=n,this._hoveredAnnotations.has(e.annotation.$tag)&&this._highlighter.setHighlightsFocused(n,!0)};this.detach(e.$tag,!1),this._annotations.add(e.$tag),e.target||(e.target=[]);const n=await Promise.all(e.target.map((async t=>{if(!t.selector||!t.selector.some((e=>"TextQuoteSelector"===e.type||"ShapeSelector"===e.type)))return{annotation:e,target:t};let n;try{const o=await this._integration.anchor(this.element,t.selector);if(o instanceof Range){const i=fo.fromRange(o);n={annotation:e,target:t,region:i}}else n={annotation:e,target:t,region:o}}catch{n={annotation:e,target:t}}return n})));if(!this._annotations.has(e.$tag))return[];for(const e of n)t(e);return e.$orphan=n.length>0&&n.every((e=>e.target.selector&&!e.region)),
157
+ this._updateAnchors(this.anchors.concat(n),!0),this._sidebarRPC.call("syncAnchoringStatus",e),n}detach(e,t=!0){this._annotations.delete(e);const n=[];for(const t of this.anchors)t.annotation.$tag!==e?n.push(t):t.highlights&&this._highlighter.removeHighlights(t.highlights);this._updateAnchors(n,t)}_updateAnchors(e,t){this.anchors=e,this._clusterToolbar?.scheduleClusterUpdates(),t&&this._bucketBarClient.update(this.anchors)}async createAnnotation(e){if("selection"===e)return this.createAnnotationFromSelection();if(!["rect","point"].includes(e))throw new Error("Unsupported annotation tool");{let t=!1;try{this._hostRPC.call("activeToolChanged",e);const t=await this._drawTool.draw(e),n=await this.getDocumentInfo(),o=[{source:n.uri,selector:await this._integration.describe(this.element,t)}],i={uri:n.uri,document:n.metadata,target:o,$tag:"a:"+nn(8)};return this._sidebarRPC.call("createAnnotation",i),this.anchor(i),i}catch(e){if(e instanceof Ho&&["canceled","restarted"].includes(e.kind))return t="restarted"===e.kind,
158
+ null;throw e}finally{t||this._hostRPC.call("activeToolChanged",null)}}}async createAnnotationFromSelection({highlight:e=!1}={}){const t=this.selectedRanges;this.selectedRanges=[];const n=await this.getDocumentInfo(),o=this.element,i=(await Promise.all(t.map((e=>this._integration.describe(o,e))))).map((e=>({source:n.uri,selector:e}))),r={uri:n.uri,document:n.metadata,target:i,$highlight:e,$cluster:e?"user-highlights":"user-annotations",$tag:"a:"+nn(8)};return this._sidebarRPC.call("createAnnotation",r),this.anchor(r),Or(),r}_hoverAnnotations(e){this._hoveredAnnotations.clear(),e.forEach((e=>this._hoveredAnnotations.add(e)));for(const t of this.anchors)if(t.highlights){const n=e.includes(t.annotation.$tag);this._highlighter.setHighlightsFocused(t.highlights,n)}this._sidebarRPC.call("hoverAnnotations",e)}_onSelection(e){const t=this._integration.getAnnotatableRange(e);if(!t)return void this._onClearSelection();const n=document.getSelection(),o=bo(n),i=yo(n);i?(this.selectedRanges=[t],
159
+ this._hostRPC.call("textSelected"),this._adder.annotationsForSelection=Pr(),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(e,{toggle:t=!1,focusInSidebar:n=!1}={}){t?this._sidebarRPC.call("toggleAnnotationSelection",e):this._sidebarRPC.call("showAnnotations",e,n),this._sidebarRPC.call("openSidebar")}setHighlightsVisible(e,t=!0){this._highlighter.setHighlightsVisible(e),this._highlightsVisible=e,t&&this._hostRPC.call("highlightsVisibleChanged",e)}get highlightsVisible(){return this._highlightsVisible}fitSideBySide(e){this._sidebarLayout=e,this._integration.fitSideBySide(e)}get hoveredAnnotationTags(){return this._hoveredAnnotations}_handleShortcut(e){Wn(e,"Ctrl+Shift+H")&&this.setHighlightsVisible(!this._highlightsVisible)}_setOutsideAssignmentNoticeVisible(e){
160
+ this._outsideAssignmentNotice||(this._outsideAssignmentNotice=new kr(this.element)),this._outsideAssignmentNotice.setVisible(e)}}function Br(e,t){const n=new URL(e),o=new URLSearchParams;return o.append("config",JSON.stringify(t)),n.hash=o.toString(),n.toString()}function Hr(e,t){const n={};for(const[e,o]of Object.entries(t))"notebookAppUrl"!==e&&"sidebarAppUrl"!==e&&null!=o&&(n[e]=o);n.origin=new URL(e).origin,n.version="1.1643.0";const o=new URL(window.location.href);if(o.hash="",n.hostURL=o.toString(),Array.isArray(n.services)&&n.services?.length>0){const e=n.services[0];e.onLoginRequest&&(e.onLoginRequestProvided=!0),e.onLogoutRequest&&(e.onLogoutRequestProvided=!0),e.onSignupRequest&&(e.onSignupRequestProvided=!0),e.onProfileRequest&&(e.onProfileRequestProvided=!0),e.onHelpRequest&&(e.onHelpRequestProvided=!0)}return n}function Fr({closed:e,onClose:t,children:n,"data-testid":o,"aria-label":i}){const r=oe(null);return te((()=>{e?r.current?.close():r.current?.showModal()}),[e]),te((()=>{const e=r.current
161
+ ;return e?.addEventListener("cancel",t),()=>{e?.removeEventListener("cancel",t)}}),[t]),Pe("dialog",{ref:r,className:"relative w-full h-full backdrop:bg-black/50","data-testid":o,"aria-label":i,children:n})}function Dr({closed:e,children:t,...n}){return Pe("div",{...n,className:Ee("fixed z-max top-0 left-0 right-0 bottom-0 p-3 bg-black/50",{hidden:e}),children:Pe("div",{className:"relative w-full h-full",children:t})})}function Vr({document_:e=document,...t}){return Pe(ie((()=>function(e){return"function"==typeof e.createElement("dialog").showModal}(e)?Fr:Dr),[e]),{...t})}function Ur({config:e,groupId:t}){return Pe("iframe",{title:"Hypothesis annotation notebook",className:"h-full w-full border-0",allow:"fullscreen; clipboard-write",src:Br(e.notebookAppUrl,{...Hr(e.notebookAppUrl,e),group:t})})}function qr({eventBus:e,config:t}){const[n,o]=ee(0),[i,r]=ee(!0),[s,a]=ee(null),l=oe(""),c=oe(null);te((()=>(l.current=document.body.style.overflow,()=>{document.body.style.overflow=l.current})),[]),te((()=>{
162
+ document.body.style.overflow=i?l.current:"hidden"}),[i]),te((()=>{const t=e.createEmitter();return t.subscribe("openNotebook",(e=>{r(!1),o((e=>e+1)),a(e)})),c.current=t,()=>{t.destroy()}}),[e]);const h=re((()=>{r(!0),c.current?.publish("closeNotebook")}),[]);return null===s?null:Pe(Vr,{closed:i,onClose:h,"data-testid":"notebook-outer","aria-label":"Hypothesis notebook",children:[Pe("div",{className:"absolute right-0 m-3",children:Pe(kt,{title:"Close notebook",onClick:h,variant:"dark",classes:Ee("!bg-transparent enabled:hover:!bg-grey-3"),"data-testid":"close-button",children:Pe(Fe,{className:"w-4 h-4"})})}),Pe(Ur,{config:t,groupId:s},n)]})}class $r{constructor(e,t,n){this._container=new eo("notebook",(()=>Pe(qr,{eventBus:t,config:n}))),e.append(this._container.element),this._container.render()}destroy(){this._container.destroy()}}function zr({eventBus:e,config:t}){const[n,o]=ee(!0),i=oe(null);te((()=>{const t=e.createEmitter();return t.subscribe("openProfile",(()=>{o(!1)})),i.current=t,()=>{t.destroy()}
163
+ }),[e]);const r=()=>{o(!0),i.current?.publish("closeProfile")};return n?null:Pe(Vr,{closed:n,onClose:r,"data-testid":"profile-outer","aria-label":"Hypothesis profile",children:[Pe("div",{className:"absolute right-0 m-3",children:Pe(kt,{title:"Close profile dialog",onClick:r,variant:"dark",classes:Ee("!bg-transparent enabled:hover:!bg-grey-3"),children:Pe(Fe,{className:"w-4 h-4"})})}),Pe("iframe",{title:"Hypothesis profile",className:"h-full w-full border-0",src:t.profileAppUrl})]})}class Wr{constructor(e,t,n){this._container=new eo("profile",(()=>Pe(zr,{eventBus:t,config:n}))),e.append(this._container.element),this._container.render()}destroy(){this._container.destroy()}}function jr({above:e,below:t,buckets:n,onFocusAnnotations:o,onScrollToAnnotation:i,onSelectAnnotations:r}){const s=e.anchors.length>0,a=t.anchors.length>0,l=e=>e.anchors.map((e=>e.tag));return Pe("ul",{className:"relative",children:[s&&Pe("li",{className:"absolute right-0 pointer-events-auto mt-[-11px]",style:{top:e.position},children:Pe(en,{
164
+ "data-testid":"up-navigation-button",direction:"up",onClick:()=>{const t=[...e.anchors].sort(((e,t)=>e.bottom-t.bottom)),n=t[t.length-1];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})}),n.map(((e,t)=>Pe("li",{className:"absolute right-0 pointer-events-auto mt-[-8px]",style:{top:e.position},children:Pe(en,{direction:"left",onClick:t=>r(l(e),t.metaKey||t.ctrlKey),onBlur:()=>o([]),onFocus:()=>o(l(e)),onMouseEnter:()=>o(l(e)),onMouseOut:()=>o([]),title:`Select nearby annotations (${e.anchors.length})`,children:e.anchors.length})},t))),a&&Pe("li",{className:"absolute right-0 pointer-events-auto",style:{top:t.position},children:Pe(en,{"data-testid":"down-navigation-button",direction:"down",onClick:()=>{const e=[...t.anchors].sort(((e,t)=>e.top-t.top)),n=e[0];i(n.tag)},onBlur:()=>o([]),onFocus:()=>o(l(t)),onMouseEnter:()=>o(l(t)),onMouseOut:()=>o([]),
165
+ title:`Go up to next annotations (${t.anchors.length})`,children:t.anchors.length})})]})}class Xr{constructor(e,{onFocusAnnotations:t,onScrollToAnnotation:n,onSelectAnnotations:o}){this._positions=[],this._container=new eo("bucket-bar",(()=>this._render())),Object.assign(this._container.element.style,{display:"block",flexGrow:"1",width:"100%"}),e.appendChild(this._container.element),this._onFocusAnnotations=t,this._onScrollToAnnotation=n,this._onSelectAnnotations=o,this._container.render()}destroy(){this._container.destroy()}update(e){this._positions=e,this._container.render()}_render(){const e=function(e,t){const n=[],o=[],i=[];let r=null;function s(e){const{bottom:t,top:n}=e;return{bottom:t,position:n+(t-n)/2,anchors:[e],top:n}}const a=t.getBoundingClientRect(),l=e.map((e=>({tag:e.tag,top:e.top-a.top,bottom:e.bottom-a.top})));for(const e of l){const t=(e.top+e.bottom)/2;if(t<30){n.push(e);continue}if(t>a.height-30){o.push(e);continue}if(!r){r=s(e);continue}const l=e.top>r.top&&e.bottom<r.bottom
166
+ ;if(e.top-r.bottom>60&&!l)i.push(r),r=s(e);else{const t=e.bottom>r.bottom?e.bottom:r.bottom,n=t-r.top;r.anchors.push(e),r.bottom=t,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 Pe(jr,{above:e.above,below:e.below,buckets:e.buckets,onFocusAnnotations:e=>this._onFocusAnnotations(e),onScrollToAnnotation:e=>this._onScrollToAnnotation(e),onSelectAnnotations:(e,t)=>this._onSelectAnnotations(e,t)})}}function Yr({emitter:e}){const[t,n]=ee([]),o=re((e=>n((t=>[...t,e]))),[]),i=re((e=>n((t=>t.filter((t=>t.id!==e))))),[]);return te((()=>(e.subscribe("toastMessageAdded",o),e.subscribe("toastMessageDismissed",i),()=>{e.unsubscribe("toastMessageAdded",o),e.unsubscribe("toastMessageDismissed",i)})),[e,i,o]),Pe(Gt,{messages:t,onMessageDismiss:i})}function Kr({icon:e,pressedBackground:t=!0,...n}){return Pe(Ct,{
167
+ classes:Ee("justify-center rounded","w-[30px] h-[30px] touch:h-[40px]","shadow border bg-white text-grey-6 hover:text-grey-9",t&&"aria-pressed:bg-grey-3"),...n,size:"custom",variant:"custom",children:Pe(e,{})})}function Gr({highlightsVisible:e}){return Pe("div",{className:"sr-only",role:"status","data-testid":"toolbar-status",children:e?"Highlights visible":"Highlights hidden"})}function Qr({activeTool:e=null,closeSidebar:t,createAnnotation:n,isSidebarOpen:o,sidebarContainerId:i,newAnnotationType:r,showHighlights:s,supportedTools:a=["selection"],toggleHighlights:l,toggleSidebar:c,toggleSidebarRef:h,useMinimalControls:d=!1}){return Pe("div",{className:Ee({"absolute right-full":d,"relative right-[11px]":!d},"w-[33px] z-2","text-px-base leading-none"),children:[d&&o&&Pe(Ct,{classes:Ee("transition-colors focus-visible-ring ring-inset","w-[27px] h-[27px] mt-[140px] ml-px-1.5","flex items-center justify-center bg-white border","text-grey-6 hover:text-grey-9 transition-colors","border-r-0","shadow-sidebar"),
168
+ title:"Close annotation sidebar",onClick:t,unstyled:!0,children:Pe(Fe,{})}),!d&&Pe(w,{children:[Pe(Ct,{classes:Ee("transition-colors focus-visible-ring ring-inset","h-[40px] w-[33px] pl-[6px] rounded-bl","bg-white text-grey-5 hover:text-grey-9","border-l border-b"),elementRef:h,title:"Annotation sidebar",expanded:o,"aria-controls":i,onClick:c,unstyled:!0,children:Pe(o?ze:qe,{})}),Pe("div",{className:"space-y-px-1.5 mt-px-2",children:[Pe(Kr,{title:"Show highlights",icon:s?xt:et,pressed:s,pressedBackground:!1,onClick:l}),a.includes("selection")&&Pe(Kr,{"data-testid":"text-annotation",title:"note"===r?"New page note":"New annotation",icon:"note"===r?lt:Be,onClick:()=>n("selection")}),a.includes("rect")&&Pe(Kr,{"data-testid":"rect-annotation",pressed:"rect"===e,title:"Rectangle annotation",icon:vt,onClick:()=>n("rect"===e?null:"rect")}),a.includes("point")&&Pe(Kr,{"data-testid":"point-annotation",pressed:"point"===e,title:"Pin annotation",icon:ht,onClick:()=>n("point"===e?null:"point")})]}),Pe(Gr,{
169
+ highlightsVisible:s})]})]})}class Jr{constructor(e,t){const{createAnnotation:n,setSidebarOpen:o,setHighlightsVisible:i}=t;this.container=e,this._activeTool=null,this._useMinimalControls=!1,this._newAnnotationType="note",this._highlightsVisible=!1,this._sidebarOpen=!1,this._sidebarContainerId=t.sidebarContainerId,this._supportedAnnotationTools=["selection"],this._closeSidebar=()=>o(!1),this._toggleSidebar=()=>o(!this._sidebarOpen),this._toggleHighlights=()=>i(!this._highlightsVisible),this._createAnnotation=e=>{n(e),"selection"===e&&o(!0)},this._sidebarToggleButton={current:null},this.render()}getWidth(){return this.container.firstChild.getBoundingClientRect().width}set activeTool(e){this._activeTool=e,this.render()}get activeTool(){return this._activeTool}set useMinimalControls(e){this._useMinimalControls=e,this.render()}get useMinimalControls(){return this._useMinimalControls}set sidebarOpen(e){this._sidebarOpen=e,this.render()}get sidebarOpen(){return this._sidebarOpen}set newAnnotationType(e){
170
+ this._newAnnotationType=e,this.render()}get newAnnotationType(){return this._newAnnotationType}set highlightsVisible(e){this._highlightsVisible=e,this.render()}get highlightsVisible(){return this._highlightsVisible}get sidebarToggleButton(){return this._sidebarToggleButton.current}set supportedAnnotationTools(e){this._supportedAnnotationTools=e,this.render()}get supportedAnnotationTools(){return this._supportedAnnotationTools}render(){F(Pe(Qr,{activeTool:this._activeTool,closeSidebar:this._closeSidebar,createAnnotation:this._createAnnotation,newAnnotationType:this._newAnnotationType,isSidebarOpen:this._sidebarOpen,sidebarContainerId:this._sidebarContainerId,showHighlights:this._highlightsVisible,supportedTools:this._supportedAnnotationTools,toggleHighlights:this._toggleHighlights,toggleSidebar:this._toggleSidebar,toggleSidebarRef:this._sidebarToggleButton,useMinimalControls:this.useMinimalControls}),this.container)}}class Zr{constructor({target:e,threshold:t=10,onDrag:n}){e.style.touchAction="none",
171
+ this._listeners=new ge,this._startX=null,this._dragActive=!1,this._threshold=t,this._listeners.add(e,"pointerdown",(e=>{this._startX=e.clientX}));const o=e=>{if(null!==this._startX&&this._dragActive){const t=e.clientX-this._startX;n({type:"dragend",deltaX:t})}this._startX=null,this._dragActive=!1};this._listeners.add(window,"pointercancel",o),this._listeners.add(window,"pointerup",o),this._listeners.add(window,"pointermove",(e=>{if(null===this._startX)return;const t=e.clientX-this._startX;!this._dragActive&&Math.abs(t)>=this._threshold&&(this._dragActive=!0,n({type:"dragstart",deltaX:t})),this._dragActive&&n({type:"dragmove",deltaX:t})}))}destroy(){this._listeners.removeAll()}}class es{constructor(e,t,n){this._emitter=t.createEmitter(),this._guestWithSelection=null,this._guestRPC=[],this._sidebarRPC=new bn,this.iframe=function(e){const t=e.sidebarAppUrl,n=Br(t,Hr(t,e)),o=document.createElement("iframe");return o.src=n,o.title="Hypothesis annotation viewer",o.className="sidebar-frame",
172
+ o.allow="fullscreen; clipboard-write",o}(n),this._config=n,this.bucketBar=null,this.features=new $o;const o="sidebar-container",i=document.createElement("div");if(i.setAttribute("data-testid","toolbar-container"),this.toolbar=new Jr(i,{sidebarContainerId:o,createAnnotation:e=>{if(0===this._guestRPC.length)return;(this._guestWithSelection??this._guestRPC[0]).call("createAnnotation",{tool:e})},setSidebarOpen:e=>e?this.open():this.close(),setHighlightsVisible:e=>this.setHighlightsVisible(e)}),n.externalContainerSelector)this.externalFrame=document.querySelector(n.externalContainerSelector)??e,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 e
173
+ ;n.bucketContainerSelector&&(e=document.querySelector(n.bucketContainerSelector),e||console.warn(`Custom bucket container "${n.bucketContainerSelector}" not found`));const t=document.createElement("div");t.setAttribute("data-testid","sidebar-edge"),t.className=Ee("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",t.append(i),this.iframeContainer.append(t),e||(e=t),this.bucketBar=new Xr(e,{onFocusAnnotations:e=>this._guestRPC.forEach((t=>t.call("hoverAnnotations",e))),onScrollToAnnotation:e=>this._guestRPC.forEach((t=>t.call("scrollToAnnotation",e))),onSelectAnnotations:(e,t)=>this._guestRPC.forEach((n=>n.call("selectAnnotations",e,t)))})}this.iframeContainer.appendChild(this.iframe),this._hypothesisSidebar=document.createElement("hypothesis-sidebar");const t=Zn(this._hypothesisSidebar);t.appendChild(this.iframeContainer),e.appendChild(this._hypothesisSidebar),
174
+ this._messagesElement=document.createElement("div"),t.appendChild(this._messagesElement),F(Pe(Yr,{emitter:this._emitter}),this._messagesElement)}this.iframe.contentWindow&&dn(this.iframe.contentWindow),this._listeners=new ge,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 Zr({target:r,onDrag:e=>this._onDragSidebarToggleButton(e)})),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()}destroy(){this._guestRPC.forEach((e=>e.destroy())),this._sidebarRPC.destroy(),
175
+ this.bucketBar?.destroy(),this._listeners.removeAll(),this._dragResizeHandler?.destroy(),this._hypothesisSidebar?(F(null,this._messagesElement),this._hypothesisSidebar.remove()):this.iframe.remove(),this._emitter.destroy(),dn(null)}onFrameConnected(e,t){switch(e){case"guest":this._connectGuest(t);break;case"sidebar":this._sidebarRPC.connect(t)}}_connectGuest(e){const t=new bn;t.on("textSelected",(()=>{this._guestWithSelection=t,this.toolbar.newAnnotationType="annotation",this._guestRPC.filter((e=>e!==t)).forEach((e=>e.call("clearSelection")))})),t.on("textUnselected",(()=>{this._guestWithSelection=null,this.toolbar.newAnnotationType="note",this._guestRPC.filter((e=>e!==t)).forEach((e=>e.call("clearSelection")))})),t.on("activeToolChanged",(e=>{this.toolbar.activeTool=e})),t.on("highlightsVisibleChanged",(e=>{this.setHighlightsVisible(e)}));const n=this.bucketBar;n&&t.on("anchorsChanged",(e=>{0===this._guestRPC.indexOf(t)&&n.update(e)})),t.on("close",(()=>{t.destroy(),
176
+ t===this._guestWithSelection&&(this._guestWithSelection=null),this._guestRPC=this._guestRPC.filter((e=>e!==t))})),t.on("supportedToolsChanged",(e=>{this.toolbar.supportedAnnotationTools=e})),t.connect(e),this._guestRPC.push(t),t.call("sidebarLayoutChanged",this._layoutState)}_setupSidebarEvents(){var e;e=document.body,this._sidebarRPC.on("publicAnnotationCountChanged",(function(t){const n=e.querySelectorAll("[data-hypothesis-annotation-count]");Array.from(n).forEach((e=>{e.textContent=t.toString()}))})),function(e,t){const n=e.querySelectorAll("[data-hypothesis-trigger]");Array.from(n).forEach((e=>{e.addEventListener("click",(e=>{t(),e.stopPropagation()}))}))}(document.body,(()=>this.open())),this._sidebarRPC.on("featureFlagsUpdated",(e=>this.features.update(e))),this._sidebarRPC.on("connect",(()=>{this.iframeContainer&&(this.iframeContainer.style.display="");const e="always"===this._config.showHighlights;this.setHighlightsVisible(e),
177
+ (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",(e=>{this.hide(),this._emitter.publish("openNotebook",e)})),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",(e=>{this._emitter.publish("toastMessageAdded",e)})),this._sidebarRPC.on("toastMessageDismissed",(e=>{this._emitter.publish("toastMessageDismissed",e)}));[["loginRequested",this.onLoginRequest],["logoutRequested",this.onLogoutRequest],["signupRequested",this.onSignupRequest],["profileRequested",this.onProfileRequest],["helpRequested",this.onHelpRequest]].forEach((([e,t])=>{
178
+ t&&this._sidebarRPC.on(e,(()=>t()))}))}_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 e=this._dragResizeState.final,t=-e;this.iframeContainer.style.marginLeft=`${e}px`,t>=280&&(this.iframeContainer.style.width=`${t}px`),this._updateLayoutState()}})))}_updateLayoutState(e){const t=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=t;"boolean"==typeof e?e&&(a+=r):(s<280?a-=s:a+=r,e=a>t);const l={expanded:e,width:e?a:t,height:o,toolbarWidth:t};this._layoutState=l,this.onLayoutChange?.(l),this._guestRPC.forEach((e=>e.call("sidebarLayoutChanged",l)))}_onResize(){
179
+ !0===this.toolbar.sidebarOpen&&(window.innerWidth<280?this.close():this.open())}isResizing(){return null!==this._dragResizeState.initial}_onDragSidebarToggleButton(e){const t=this.iframeContainer;if(t)switch(e.type){case"dragstart":this._resetDragResizeState(),t.classList.add("sidebar-no-transition"),this.toolbar.container.style.pointerEvents="none",this._dragResizeState.initial=parseInt(getComputedStyle(t).marginLeft);break;case"dragend":t.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 t=this._dragResizeState.initial,n=e.deltaX;this._dragResizeState.final=Math.min(Math.round(t+n),0),this._updateLayout();break}}}open(){if(this._sidebarRPC.call("sidebarOpened"),this.iframeContainer){const e=this.iframeContainer.getBoundingClientRect().width
180
+ ;this.iframeContainer.style.marginLeft=-1*e+"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(e){this.toolbar.highlightsVisible=e,this._sidebarRPC.call("setHighlightsVisible",e)}show(){this.iframeContainer?.classList.remove("is-hidden")}hide(){this.iframeContainer?.classList.add("is-hidden")}}class ts{constructor(e){this._emitter=e,this._subscriptions=[]}publish(e,...t){this._emitter.emit(e,...t)}subscribe(e,t){this._emitter.on(e,t),this._subscriptions.push([e,t])}unsubscribe(e,t){this._emitter.off(e,t),
181
+ this._subscriptions=this._subscriptions.filter((([n,o])=>n!==e||o!==t))}destroy(){for(const[e,t]of this._subscriptions)this._emitter.off(e,t);this._subscriptions=[]}}class ns{constructor(){this._emitter=new an}createEmitter(){return new ts(this._emitter)}}const os=document.querySelector('link[type="application/annotator+html"][rel="sidebar"]');new Promise((e=>{"loading"!==document.readyState&&e(),document.addEventListener("readystatechange",(()=>e()))})).then((function(){const e=$n("annotator");let t=()=>{};const n=new Promise((e=>{t=e}));os.addEventListener("destroy",t);const o=e.subFrameIdentifier?window.parent:window,i=[];if(o===window){if(function(){const e=document.querySelectorAll(["hypothesis-sidebar","hypothesis-notebook","hypothesis-profile"].join(","));return e.forEach((e=>e.remove())),e.length>0}())return void console.warn("Hypothesis did not load because it found an existing instance on the page.");const e=function(e=navigator.userAgent){if(!_n(e))return()=>{};const t=e=>{
182
+ if("hypothesisPortClosed"===e.data?.type&&e.ports[0]){const t=e.ports[0];gn(t,"close"),t.close()}};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}();i.push({destroy:e});const t=$n("sidebar"),n=new URL(t.sidebarAppUrl).origin,o=new un(n),r=new ns,s=new es(document.body,r,t),a=new $r(document.body,r,$n("notebook")),l=new Wr(document.body,r,$n("profile"));o.on("frameConnected",((e,t)=>s.onFrameConnected(e,t))),i.push(o,s,a,l)}if("container"===yr()){const t=new xr(e);i.push(t)}else{const n=new _r(document.body,e),r=new Lr(document.body,e,o);r.on("hostDisconnected",t),i.push(n,r)}n.then((()=>{i.forEach((e=>e.destroy()));document.querySelectorAll("[data-hypothesis-asset]").forEach((e=>e.remove())),function(e=document){Array.from(e.querySelectorAll("script.js-hypothesis-config[data-remove-on-unload]")).forEach((e=>e.remove()))}()}))}))}();
183
183
  //# sourceMappingURL=annotator.bundle.js.map