!function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n;n||(n=1,function(){function e(e){var t=!0,n=!1,o=null,i={text:!0,search:!0,url:!0,tel:!0,email:!0,password:!0,number:!0,date:!0,month:!0,week:!0,time:!0,datetime:!0,"datetime-local":!0};function r(e){return!!(e&&e!==document&&"HTML"!==e.nodeName&&"BODY"!==e.nodeName&&"classList"in e&&"contains"in e.classList)}function s(e){var t=e.type,n=e.tagName;return!("INPUT"!==n||!i[t]||e.readOnly)||"TEXTAREA"===n&&!e.readOnly||!!e.isContentEditable}function a(e){e.classList.contains("focus-visible")||(e.classList.add("focus-visible"),e.setAttribute("data-focus-visible-added",""))}function l(e){e.hasAttribute("data-focus-visible-added")&&(e.classList.remove("focus-visible"),e.removeAttribute("data-focus-visible-added"))}function c(n){ n.metaKey||n.altKey||n.ctrlKey||(r(e.activeElement)&&a(e.activeElement),t=!0)}function d(e){t=!1}function u(e){r(e.target)&&(t||s(e.target))&&a(e.target)}function h(e){r(e.target)&&(e.target.classList.contains("focus-visible")||e.target.hasAttribute("data-focus-visible-added"))&&(n=!0,window.clearTimeout(o),o=window.setTimeout((function(){n=!1}),100),l(e.target))}function f(e){"hidden"===document.visibilityState&&(n&&(t=!0),m())}function m(){document.addEventListener("mousemove",p),document.addEventListener("mousedown",p),document.addEventListener("mouseup",p),document.addEventListener("pointermove",p),document.addEventListener("pointerdown",p),document.addEventListener("pointerup",p),document.addEventListener("touchmove",p),document.addEventListener("touchstart",p),document.addEventListener("touchend",p)}function g(){document.removeEventListener("mousemove",p),document.removeEventListener("mousedown",p),document.removeEventListener("mouseup",p),document.removeEventListener("pointermove",p), document.removeEventListener("pointerdown",p),document.removeEventListener("pointerup",p),document.removeEventListener("touchmove",p),document.removeEventListener("touchstart",p),document.removeEventListener("touchend",p)}function p(e){e.target.nodeName&&"html"===e.target.nodeName.toLowerCase()||(t=!1,g())}document.addEventListener("keydown",c,!0),document.addEventListener("mousedown",d,!0),document.addEventListener("pointerdown",d,!0),document.addEventListener("touchstart",d,!0),document.addEventListener("visibilitychange",f,!0),m(),e.addEventListener("focus",u,!0),e.addEventListener("blur",h,!0),e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&e.host?e.host.setAttribute("data-js-focus-visible",""):e.nodeType===Node.DOCUMENT_NODE&&(document.documentElement.classList.add("js-focus-visible"),document.documentElement.setAttribute("data-js-focus-visible",""))}if("undefined"!=typeof window&&"undefined"!=typeof document){var t;window.applyFocusVisiblePolyfill=e;try{t=new CustomEvent("focus-visible-polyfill-ready") }catch(e){(t=document.createEvent("CustomEvent")).initCustomEvent("focus-visible-polyfill-ready",!1,!1,{})}window.dispatchEvent(t)}"undefined"!=typeof document&&e(document)}());var o,i,r,s,a,l,c,d,u,h,f,m,g={},p=[],_=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,b=Array.isArray;function v(e,t){for(var n in t)e[n]=t[n];return e}function w(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function y(e,t,n,o,s){var a={type:e,props:t,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==s?++r:s,__i:-1,__u:0};return null==s&&null!=i.vnode&&i.vnode(a),a}function x(e){return e.children}function N(e,t){this.props=e,this.context=t}function C(e,t){if(null==t)return e.__?C(e.__,e.__i+1):null;for(var n;tt&&s.sort(c));A.__r=0}function R(e,t,n,o,i,r,s,a,l,c,d){var u,h,f,m,_,v,w=o&&o.__k||p,N=t.length;for(l=function(e,t,n,o,i){var r,s,a,l,c,d=n.length,u=d,h=0;for(e.__k=new Array(i),r=0;r0?y(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=e,s.__b=e.__b+1,a=null,-1!==(c=s.__i=P(s,n,l,u))&&(u--, (a=n[c])&&(a.__u|=2)),null==a||null===a.__v?(-1==c&&h--,"function"!=typeof s.type&&(s.__u|=4)):c!=l&&(c==l-1?h--:c==l+1?h++:(c>l?h--:h++,s.__u|=4))):e.__k[r]=null;if(u)for(r=0;r(null!=l&&0==(2&l.__u)?1:0))for(i=n-1, r=n+1;i>=0||r=0){if((l=t[i])&&0==(2&l.__u)&&s==l.key&&a===l.type)return i;i--}if(r2&&(a.children=arguments.length>3?o.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===a[s]&&(a[s]=e.defaultProps[s]);return y(e,a,i,r,null)}(x,null,[e]),r||g,g,t.namespaceURI,r?null:t.firstChild?o.call(t.childNodes):null,s,r?r.__e:t.firstChild,false,a),I(s,e,a)}function U(e,t){var n={__c:t="__cC"+m++,__:e,Consumer:function(e,t){return e.children(t)},Provider:function(e){var n,o;return this.getChildContext||(n=new Set,(o={})[t]=this,this.getChildContext=function(){return o},this.componentWillUnmount=function(){n=null},this.shouldComponentUpdate=function(e){this.props.value!==e.value&&n.forEach((function(e){e.__e=!0,E(e)}))},this.sub=function(e){n.add(e);var t=e.componentWillUnmount;e.componentWillUnmount=function(){n&&n.delete(e),t&&t.call(e)}}),e.children}} ;return n.Provider.__=n.Consumer.contextType=n}o=p.slice,i={__e:function(e,t,n,o){for(var i,r,s;t=t.__;)if((i=t.__c)&&!i.__)try{if((r=i.constructor)&&null!=r.getDerivedStateFromError&&(i.setState(r.getDerivedStateFromError(e)),s=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(e,o||{}),s=i.__d),s)return i.__E=i}catch(t){e=t}throw e}},r=0,N.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=v({},this.state),"function"==typeof e&&(e=e(v({},n),this.props)),e&&v(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),E(this))},N.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),E(this))},N.prototype.render=x,s=[],l="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,c=function(e,t){return e.__v.__b-t.__v.__b},A.__r=0,d=/(PointerCapture)$|Capture$/i,u=0,h=L(!1),f=L(!0),m=0;var q,$,z,W,j=0,X=[],K=i,G=K.__b,Y=K.__r,Q=K.diffed,J=K.__c,Z=K.unmount,ee=K.__;function te(e,t){K.__h&&K.__h($,e,j||t),j=0 ;var n=$.__H||($.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function ne(e){return j=1,function(e,t,n){var o=te(q++,2);if(o.t=e,!o.__c&&(o.__=[pe(void 0,t),function(e){var t=o.__N?o.__N[0]:o.__[0],n=o.t(t,e);t!==n&&(o.__N=[n,o.__[1]],o.__c.setState({}))}],o.__c=$,!$.u)){var i=function(e,t,n){if(!o.__c.__H)return!0;var i=o.__c.__H.__.filter((function(e){return!!e.__c}));if(i.every((function(e){return!e.__N})))return!r||r.call(this,e,t,n);var s=o.__c.props!==e;return i.forEach((function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(s=!0)}})),r&&r.call(this,e,t,n)||s};$.u=!0;var r=$.shouldComponentUpdate,s=$.componentWillUpdate;$.componentWillUpdate=function(e,t,n){if(this.__e){var o=r;r=void 0,i(e,t,n),r=o}s&&s.call(this,e,t,n)},$.shouldComponentUpdate=i}return o.__N||o.__}(pe,e)}function oe(e,t){var n=te(q++,3);!K.__s&&ge(n.__H,t)&&(n.__=e,n.i=t,$.__H.__h.push(n))}function ie(e,t){var n=te(q++,4);!K.__s&&ge(n.__H,t)&&(n.__=e,n.i=t,$.__h.push(n))}function re(e){ return j=5,se((function(){return{current:e}}),[])}function se(e,t){var n=te(q++,7);return ge(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function ae(e,t){return j=8,se((function(){return e}),t)}function le(e){var t=$.context[e.__c],n=te(q++,9);return n.c=e,t?(null==n.__&&(n.__=!0,t.sub($)),t.props.value):e.__}function ce(){var e=te(q++,11);if(!e.__){for(var t=$.__v;null!==t&&!t.__m&&null!==t.__;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function de(){for(var e;e=X.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(fe),e.__H.__h.forEach(me),e.__H.__h=[]}catch(t){e.__H.__h=[],K.__e(t,e.__v)}}K.__b=function(e){$=null,G&&G(e)},K.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),ee&&ee(e,t)},K.__r=function(e){Y&&Y(e),q=0;var t=($=e.__c).__H;t&&(z===$?(t.__h=[],$.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.i=e.__N=void 0}))):(t.__h.forEach(fe),t.__h.forEach(me),t.__h=[],q=0)),z=$},K.diffed=function(e){Q&&Q(e);var t=e.__c ;t&&t.__H&&(t.__H.__h.length&&(1!==X.push(t)&&W===K.requestAnimationFrame||((W=K.requestAnimationFrame)||he)(de)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.i=void 0}))),z=$=null},K.__c=function(e,t){t.some((function(e){try{e.__h.forEach(fe),e.__h=e.__h.filter((function(e){return!e.__||me(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],K.__e(n,e.__v)}})),J&&J(e,t)},K.unmount=function(e){Z&&Z(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{fe(e)}catch(e){t=e}})),n.__H=void 0,t&&K.__e(t,n.__v))};var ue="function"==typeof requestAnimationFrame;function he(e){var t,n=function(){clearTimeout(o),ue&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,100);ue&&(t=requestAnimationFrame(n))}function fe(e){var t=$,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),$=t}function me(e){var t=$;e.__c=e.__(),$=t}function ge(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function pe(e,t){return"function"==typeof t?t(e):t}function _e(e,t,n){return(t=function(e){ var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t);if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class be{constructor(){_e(this,"_listeners",void 0),this._listeners=new Map}add(e,t,n,o){e.addEventListener(t,n,o);const i=Symbol();return this._listeners.set(i,{eventTarget:e,eventType:t,listener:n,options:o}),i}remove(e){const t=this._listeners.get(e);if(t){const{eventTarget:n,eventType:o,listener:i,options:r}=t;n.removeEventListener(o,i,r),this._listeners.delete(e)}}removeAll(){this._listeners.forEach((({eventTarget:e,eventType:t,listener:n,options:o})=>{e.removeEventListener(t,n,o)})),this._listeners.clear()}}function ve(e){e.focus()} function we(e,{autofocus:t=!1,loop:n=!0,horizontal:o=!0,vertical:i=!0,selector:r="a,button",containerVisible:s=!0,focusElement:a=ve}={}){const l=re(null),c=function(e){const t=re({callback:e,call:(...e)=>t.current.callback(...e)});return t.current.callback=e,t.current.call}(a);oe((()=>{if(!s)return()=>{};if(!e.current)throw new Error("Container ref not set");const a=e.current,d=()=>{const e=Array.from(a.querySelectorAll(r)).filter((e=>null!==e.offsetParent&&!function(e){return"boolean"==typeof e.disabled&&e.disabled}(e)));return document.activeElement===a&&e.unshift(a),e},u=(e=d(),t=-1,n=!1,o)=>{t<0&&(t=e.findIndex((e=>0===e.tabIndex)))<0&&(t=0);for(const[i,r]of e.entries())r.tabIndex=i===t?0:-1,i===t&&n&&(l.current=r,c(r,o))},h=d(),f=l.current?h.indexOf(l.current):0;u(h,f,t);const m=new be;m.add(a,"focusin",(e=>{if(e.target===a&&l.current)return void c(l.current);const n=d(),o=n.indexOf(e.target);o>=0&&u(n,o,t)})),m.add(a,"keydown",(e=>{const t=d();let r=t.findIndex((e=>0===e.tabIndex)),s=!1 ;o&&"ArrowLeft"===e.key||i&&"ArrowUp"===e.key?(0===r?r=n?t.length-1:r:--r,s=!0):o&&"ArrowRight"===e.key||i&&"ArrowDown"===e.key?(r===t.length-1?r=n?0:r:++r,s=!0):"Home"===e.key?(r=0,s=!0):"End"===e.key&&(r=t.length-1,s=!0),s&&(u(t,r,!0,e),e.preventDefault(),e.stopPropagation())}));const g=new MutationObserver((()=>{u()}));return g.observe(a,{subtree:!0,attributes:!0,attributeFilter:["disabled"],childList:!0}),()=>{m.removeAll(),g.disconnect()}}),[t,e,c,o,n,r,i,s])}function ye(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t);if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class xe{constructor(e){ye(this,"_target",void 0),ye(this,"_value",void 0),this._target=e,this._value=null} get current(){return this._value}set current(e){this._value=e,this._updateTarget()}get target(){return this._target}set target(e){e!==this._target&&(this._target=e,this._updateTarget())}_updateTarget(){const e=this._value;"function"==typeof this._target?this._target(e):this._target&&(this._target.current=e)}}function Ne(e){const t=re(new xe(e));return t.current.target=e,t.current}var Ce,Se={exports:{}};var Ee,Ae=(Ce||(Ce=1,Ee=Se,function(){var e={}.hasOwnProperty;function t(){for(var e="",t=0;ta(e),onKeyDown:s?void 0:t=>{["Enter"," "].includes(t.key)&&(t.preventDefault(),a(e))},tabIndex:-1,children:[Pe("div",{className:"flex items-center gap-x-1.5",children:[l?Pe(pt,{},void 0,0,{fileName:kt,lineNumber:68,columnNumber:23},this):Pe(mt,{},void 0,0,{fileName:kt,lineNumber:68,columnNumber:46},this),t]},void 0,0,{fileName:kt,lineNumber:67,columnNumber:7},this),n&&Pe("div",{className:Re("pl-4 ml-1.5 mt-1 text-sm",{"text-grey-7":l,"text-grey-6 group-hover:text-grey-7":!l&&!s}),children:n},void 0,0,{fileName:kt,lineNumber:72,columnNumber:9},this)]},void 0,0,{fileName:kt,lineNumber:40,columnNumber:5},this)}Pt.displayName="RadioGroup.Radio",Object.assign((function({direction:e="horizontal",children:t,selected:n,onChange:o,disabled:i,"aria-label":r,"aria-labelledby":s,name:a}){const l=re(null);return we(l,{loop:!1, selector:'[role="radio"]:not([aria-disabled="true"])',focusElement:e=>{o(e.dataset.value),e.focus()}}),Pe(Rt.Provider,{value:{selected:n,disabled:i,onChange:o},children:[Pe("div",{"aria-label":r,"aria-labelledby":s,ref:l,role:"radiogroup",className:Re("w-full flex gap-1.5",{"flex-col":"vertical"===e}),children:t},void 0,0,{fileName:kt,lineNumber:134,columnNumber:7},this),a&&Pe("input",{type:"hidden","data-testid":"hidden-input",name:a,value:n,disabled:i},void 0,0,{fileName:kt,lineNumber:146,columnNumber:9},this)]},void 0,0,{fileName:kt,lineNumber:131,columnNumber:5},this)}),{Radio:Pt,displayName:"RadioGroup"});var Tt="/home/runner/work/frontend-shared/frontend-shared/src/components/feedback/Popover.tsx";const Mt=".15rem",Lt=8;function Ot(e,t,n,o,i){oe((()=>{if(!i)return()=>{};const t=e.current,o=e=>{"open"===e.oldState&&"closed"===e.newState&&n()};return t.addEventListener("toggle",o),()=>t.removeEventListener("toggle",o)}),[i,n,e]);const r=o&&!i;!function(e,t,{enabled:n=!0}={}){oe((()=>{if(!n)return()=>{} ;const o=document.body,i=new be,r=n=>{e.current&&!n.composedPath().includes(e.current)&&t(n)};return i.add(o,"mousedown",r),i.add(o,"click",r),()=>{i.removeAll()}}),[e,n,t])}(e,(e=>{e.composedPath().includes(t.current)||n()}),{enabled:r}),function(e,t,{enabled:n=!0}={}){oe((()=>{if(!n)return()=>{};const o=document.body,i=new be;return i.add(o,"keydown",(n=>{e.includes(n.key)&&t(n)})),()=>{i.removeAll()}}),[n,t,e])}(["Escape"],n,{enabled:r})}function It({anchorElementRef:e,children:t,open:n,onClose:o,align:i="left",classes:r,variant:s="panel",restoreFocusOnClose:a=!0,onScroll:l,asNativePopover:c=HTMLElement.prototype.hasOwnProperty("popover")}){const d=re(null);return function(e,t,n,o,i){const r=ae((()=>{const n=t.current,r=e.current,s=e=>{Object.assign(n.style,e);const t=Object.keys(e);return()=>t.map((e=>n.style[e]=""))},a=window.innerHeight,{top:l,bottom:c,left:d,height:u,width:h}=r.getBoundingClientRect(),f=a-c,{height:m,width:g}=n.getBoundingClientRect(),p=ff;if(!o)return s(p?{bottom:"100%", marginBottom:Mt}:{top:"100%",marginTop:Mt});const{top:_,width:b}=document.body.getBoundingClientRect(),v=Math.abs(_),w=(i?d+h:b-d)-Lt;let y=d;return g>w?y=i?Lt:y-(g-w):i&&g>h&&(y-=g-h),s({minWidth:`${h}px`,top:p?`calc(${v+l-m}px - ${Mt})`:`calc(${v+l+u}px + ${Mt})`,left:`${Math.max(Lt,y)}px`})}),[o,e,t,i]);ie((()=>{if(!n)return()=>{};const e=t.current;o&&e.togglePopover(!0);const i=r();if(!o)return i;const s=new be;s.add(document.body,"scroll",r,{capture:!0});const a=new ResizeObserver(r);return a.observe(e),()=>{o&&(null==e||e.togglePopover(!1)),i(),s.removeAll(),a.disconnect()}}),[r,o,n,t])}(e,d,n,c,"right"===i),Ot(d,e,o,n,c),ie((()=>{const e=n?document.activeElement:null;return()=>{a&&e&&e.focus()}}),[n,a]),Pe("div",{className:Re("absolute z-5","panel"===s&&["max-h-80 overflow-y-auto overflow-x-hidden","rounded border bg-white shadow hover:shadow-md focus-within:shadow-md"],c&&["max-w-[calc(100%-16px)]","p-0 m-0"],!c&&{hidden:!n,"right-0":"right"===i,"min-w-full":!0},r),ref:d,popover:c&&"auto",onScroll:l, "data-testid":"popover","data-component":"Popover",children:n&&t},void 0,0,{fileName:Tt,lineNumber:302,columnNumber:5},this)}const Bt=U(null);var Ht="/home/runner/work/frontend-shared/frontend-shared/src/components/input/Select.tsx";function Ft(e,t){return"function"==typeof e?e(t):e}function Dt({value:e,children:t,disabled:n=!1,classes:o,elementRef:i,title:r}){const s=re(null),a=re(null),l=Ne(i),c=e=>e.target===s.current||e.target===a.current,d=le(Bt);if(!d)throw new Error("Select.Option can only be used as Select or MultiSelect child");const{selectValue:u,value:h,multiple:f}=d,m=se((()=>!n&&(f?h.includes(e)||0===h.length&&void 0===e:h===e)),[h,n,f,e]),g=ae((()=>{const t={closeListbox:!0};u(f?void 0!==e?[e]:[]:e,t)}),[f,u,e]),p=ae((()=>{if(!f)return;const t={closeListbox:void 0===e};if(void 0===e)return void u([],t);const n=h.indexOf(e);if(-1===n)u([...h,e],t);else{const e=[...h];e.splice(n,1),u(e,t)}}),[h,f,u,e]);return Pe("li",{ className:Re("w-full ring-inset outline-none rounded-none select-none","px-1 mb-1 first:mt-1 whitespace-nowrap group",{"text-grey-4":n,"cursor-pointer":!n},o),onClick:e=>{n||c(e)||g()},onKeyDown:e=>{n||(["Enter"," "].includes(e.key)&&!c(e)?(e.preventDefault(),g()):s.current&&"ArrowRight"===e.key&&(e.preventDefault(),s.current.focus()))},role:"option","aria-disabled":n,"aria-selected":m,tabIndex:m?0:-1,ref:l,title:r,children:Pe("div",{className:Re("flex justify-between items-center","w-full rounded",{"hover:bg-grey-1 group-focus-visible:ring":!n,"bg-grey-1 hover:bg-grey-2":m}),children:[Pe("div",{className:Re("py-2 pl-3",{truncate:"truncate"===d.listboxOverflow,"whitespace-normal":"wrap"===d.listboxOverflow}),children:Ft(t,{selected:m,disabled:n})},void 0,0,{fileName:Ht,lineNumber:203,columnNumber:9},this),!f&&Pe("div",{className:"px-3",children:Pe(Ke,{className:Re("text-grey-6 scale-125",{"opacity-0":!m})},void 0,0,{fileName:Ht,lineNumber:213,columnNumber:13},this)},void 0,0,{fileName:Ht,lineNumber:212, columnNumber:11},this),f&&Pe(At,{containerClasses:Re("self-stretch px-3","text-lg",{"text-grey-6":m,"text-grey-3 hover:text-grey-6":!m}),checked:m,checkedIcon:Je,elementRef:s,containerRef:a,onChange:p,onKeyDown:e=>{var t;"ArrowLeft"===e.key&&(e.preventDefault(),null===(t=l.current)||void 0===t||t.focus())}},void 0,0,{fileName:Ht,lineNumber:224,columnNumber:11},this)]},void 0,0,{fileName:Ht,lineNumber:193,columnNumber:7},this)},void 0,0,{fileName:Ht,lineNumber:146,columnNumber:5},this)}function Vt({buttonContent:e,value:t,onChange:n,children:o,disabled:i,elementRef:r,buttonId:s,buttonClasses:a,popoverClasses:l,containerClasses:c,onPopoverScroll:d,alignListbox:u="left",multiple:h,listboxOverflow:f="truncate","aria-label":m,"aria-labelledby":g,listboxAsPopover:p}){const _=re(null),b=re(null),[v,w]=ne(!1),y=ae((()=>w(!1)),[w]),x=ce(),N=Ne(r),C=ce(),S=ae(((e,t)=>{n(e),t.closeListbox&&y()}),[n,y]);return function(e,t,{enabled:n=!0}={}){oe((()=>{if(!n||!e.current)return()=>{};const o=new be ;return o.add(e.current,"focusout",(n=>{const o=n;e.current&&!e.current.contains(o.relatedTarget)&&t(o)})),()=>{o.removeAll()}}),[e,n,t])}(_,y),we(b,{horizontal:!1,loop:!1,autofocus:!0,containerVisible:v,selector:'[role="option"]:not([aria-disabled="true"])'}),Pe("div",{className:Re("relative w-full border rounded",{"border-grey-5":v},yt,c),ref:_,children:[Pe("button",{id:null!=s?s:C,className:Re("focus-visible-ring transition-colors whitespace-nowrap","w-full flex items-center justify-between gap-x-2","bg-grey-0 disabled:bg-grey-1 disabled:text-grey-6","text-left","rounded-[inherit]",a),type:"button",role:"combobox",disabled:i,"aria-expanded":v,"aria-haspopup":"listbox","aria-controls":x,"aria-label":m,"aria-labelledby":g,ref:N,onClick:()=>w((e=>!e)),onKeyDown:e=>{"ArrowDown"!==e.key||v||(e.preventDefault(),w(!0))},"data-testid":"select-toggle-button",children:[Pe("div",{className:"pl-2 py-2 truncate grow",children:e},void 0,0,{fileName:Ht,lineNumber:429,columnNumber:9},this),Pe("div",{ className:"pr-2 py-2 text-grey-6",children:v?Pe(it,{},void 0,0,{fileName:Ht,lineNumber:431,columnNumber:26},this):Pe(st,{},void 0,0,{fileName:Ht,lineNumber:431,columnNumber:49},this)},void 0,0,{fileName:Ht,lineNumber:430,columnNumber:9},this)]},void 0,0,{fileName:Ht,lineNumber:396,columnNumber:7},this),Pe(Bt.Provider,{value:{value:t,selectValue:S,multiple:h,listboxOverflow:f},children:Pe(It,{anchorElementRef:_,open:v,onClose:y,asNativePopover:p,align:u,classes:l,onScroll:d,children:Pe("ul",{role:"listbox",id:x,ref:b,"aria-multiselectable":h,"aria-labelledby":null!=s?s:C,"aria-orientation":"vertical",children:o},void 0,0,{fileName:Ht,lineNumber:453,columnNumber:11},this)},void 0,0,{fileName:Ht,lineNumber:444,columnNumber:9},this)},void 0,0,{fileName:Ht,lineNumber:435,columnNumber:7},this)]},void 0,0,{fileName:Ht,lineNumber:387,columnNumber:5},this)}Dt.displayName="Select.Option",Object.assign((function(e){return Vt({...e,multiple:!1})}),{Option:Dt,displayName:"Select"}),Object.assign((function(e){return Vt({ ...e,multiple:!0})}),{Option:Dt,displayName:"MultiSelect"}),U({}),U(null);var Ut="/home/runner/work/frontend-shared/frontend-shared/src/components/feedback/Callout.tsx";function qt({children:e,classes:t,elementRef:n,icon:o,status:i="notice",size:r="md",variant:s="outlined",unstyled:a=!1,...l}){const c=!a,d=c&&"custom"!==s,u=c&&"custom"!==r;let h=o;if(!h)switch(i){case"success":h=Ke;break;case"error":h=Fe;break;default:h=je}const f=d&&u;return Pe("div",{"data-component":"Callout",...l,ref:n,className:Re(c&&"flex items-center border",d&&{"rounded border":!0,"shadow hover:shadow-md cursor-pointer":"raised"===s,"border-yellow-notice":"notice"===i,"border-green-success":"success"===i,"border-red-error":"error"===i},d&&{"bg-yellow-notice":"notice"===i&&f,"bg-green-success":"success"===i&&f,"bg-red-error":"error"===i&&f,"bg-white":!f},t),children:[f&&Pe("div",{className:Re({"p-2":"md"===r,"p-1.5":"sm"===r,"p-3":"lg"===r}),children:Pe(h,{"data-testid":"callout-icon",className:Re("text-white",{ "w-[1.25em] h-[1.25em]":"md"===r,"w-[0.85em] h-[0.85em]":"sm"===r,"w-[1.5em] h-[1.5em]":"lg"===r})},void 0,0,{fileName:Ut,lineNumber:95,columnNumber:11},this)},void 0,0,{fileName:Ut,lineNumber:88,columnNumber:9},this),Pe("div",{className:Re(u&&{"p-2":"md"===r,"py-1.5 px-2":"sm"===r,"p-3":"lg"===r},c&&"grow",d&&"bg-white rounded-r"),children:e},void 0,0,{fileName:Ut,lineNumber:105,columnNumber:7},this)]},void 0,0,{fileName:Ut,lineNumber:64,columnNumber:5},this)}var $t="/home/runner/work/frontend-shared/frontend-shared/src/components/feedback/ToastMessages.tsx";function zt({message:e,onDismiss:t}){return Pe(qt,{classes:Re({"sr-only":e.visuallyHidden}),status:e.type,onClick:()=>t(e.id),variant:"raised",children:e.message},void 0,0,{fileName:$t,lineNumber:55,columnNumber:5},this)}const Wt=({direction:e,onTransitionEnd:t,children:n,transitionClasses:o={}})=>{const i="out"===e,r=re(null),s=se((()=>{const{transitionIn:e="animate-fade-in",transitionOut:t="animate-fade-out"}=o;return{[e]:!i,[t]:i}}),[i,o]) ;return Pe("div",{"data-testid":"animation-container",onAnimationEnd:n=>{n.target===r.current&&(null==t||t(null!=e?e:"in"))},ref:r,className:Re("relative w-full container",s),children:n},void 0,0,{fileName:$t,lineNumber:103,columnNumber:5},void 0)};function jt({messages:e,onMessageDismiss:t,transitionClasses:n,setTimeout_:o=setTimeout}){const[i,r]=ne([]),s=re(new Map),a=ae((e=>r((t=>[...t,e]))),[]),l=ae((e=>{const t=o((()=>{a(e),s.current.delete(e)}),5e3);s.current.set(e,t)}),[a,o]),c=ae(((e,n)=>{var o;const i=null===(o=n.autoDismiss)||void 0===o||o;"in"===e&&i&&l(n.id),"out"===e&&(t(n.id),r((e=>e.filter((e=>e!==n.id)))))}),[l,t]);return ie((()=>{const e=s.current;return()=>{e.forEach((e=>clearTimeout(e)))}}),[]),Pe("ul",{"aria-live":"polite","aria-relevant":"additions",className:"w-full space-y-2","data-component":"ToastMessages",children:e.map((e=>{const t=i.includes(e.id);return Pe("li",{className:Re({"mb-2":!e.visuallyHidden}),children:Pe(Wt,{direction:t?"out":"in",onTransitionEnd:t=>c(t,e), transitionClasses:n,children:Pe(zt,{message:e,onDismiss:a},void 0,0,{fileName:$t,lineNumber:206,columnNumber:15},this)},void 0,0,{fileName:$t,lineNumber:201,columnNumber:13},this)},e.id,0,{fileName:$t,lineNumber:189,columnNumber:11},this)}))},void 0,0,{fileName:$t,lineNumber:180,columnNumber:5},this)}var Xt="/home/runner/work/frontend-shared/frontend-shared/src/components/navigation/Link.tsx";function Kt({children:e,classes:t,elementRef:n,underline:o="none",unstyled:i=!1,variant:r="brand",...s}){const a=!i;return Pe("a",{"data-component":"Link",rel:"noopener noreferrer",...s,className:Re(a&&{"focus-visible-ring rounded":!0,"no-underline hover:no-underline":"none"===o,"underline hover:underline":"always"===o,"no-underline hover:underline":"hover"===o},a&&"custom"!==r&&{"text-brand hover:text-brand-dark":"brand"===r,"text-color-text-light hover:text-brand":"text-light"===r,"text-color-text hover:text-brand-dark":"text"===r},t),ref:n,children:e},void 0,0,{fileName:Xt,lineNumber:37,columnNumber:5},this)} var Gt="/home/runner/work/frontend-shared/frontend-shared/src/components/navigation/PointerButton.tsx";function Yt({children:e,classes:t,elementRef:n,expanded:o,pressed:i,title:r,direction:s,...a}){return Pe(wt,{"data-component":"PointerButton",...a,elementRef:n,classes:Re("relative w-[26px] h-[16px]","flex items-center justify-center","bg-white rounded-[4px] border","before:absolute before:border-transparent","after:absolute after:border-transparent","text-[10px] text-color-text-light leading-none font-semibold",{"shadow-[1px_1px_1px_rgba(0,0,0,0.1)]":"down"!==s,"shadow-[1px_0px_1px_rgba(0,0,0,0.1)]":"down"===s},{"rounded-r-[4px] rounded-l-[2px]":"left"===s,"before:right-full before:top-1/2 after:right-full after:top-1/2":"left"===s,"before:mt-[-8px] before:border-8 before:border-r-[5px] before:border-r-grey-3":"left"===s,"after:mt-[-7px] after:border-[7px] after:border-r-[4px] after:border-r-white":"left"===s},{"z-1 rounded-t-px-sm rounded-b-px":"up"===s, "before:top-auto before:left-1/2 before:bottom-full after:top-auto after:left-1/2 after:bottom-full":"up"===s,"before:ml-[-13px] before:border-[13px] before:border-b-[6px] before:border-b-grey-3":"up"===s,"after:ml-[-12px] after:border-[12px] after:border-b-[5px] after:border-b-white":"up"===s},{"z-1 rounded-t-px rounded-b-px-sm":"down"===s,"before:top-full before:left-1/2 after:top-full after:left-1/2":"down"===s,"before:ml-[-13px] before:border-[13px] before:border-t-[6px] before:border-t-grey-3":"down"===s,"after:ml-[-12px] after:border-[12px] after:border-t-[5px] after:border-t-white":"down"===s},t),expanded:o,pressed:i,title:r,variant:"custom",size:"custom",children:e},void 0,0,{fileName:Gt,lineNumber:48,columnNumber:5},this)}function Qt(e){const t=e.toString(16);return 1===t.length?"0"+t:t}function Jt(e){const t=new Uint8Array(e/2);return window.crypto.getRandomValues(t),Array.from(t).map(Qt).join("")}function Zt(e){if(null===e||"object"!=typeof e)return!1 ;for(const t of["frame1","frame2","type","requestId"])if("string"!=typeof e[t])return!1;return!0}class en extends Error{constructor(e){super(e)}}class tn{constructor({hostFrame:e,source:t,sourceId:n}){this._hostFrame=e,this._source=t,this._sourceId=n,this._listeners=new be}destroy(){this._listeners.removeAll()}async discover(e){const t=Jt(6);return new Promise(((n,o)=>{const i=()=>{this._hostFrame.postMessage({frame1:this._source,frame2:e,type:"request",requestId:t,sourceId:this._sourceId},"*")},r=setInterval(i,250),s=setTimeout((()=>{clearInterval(r),o(new en(`Unable to establish ${this._source}-${e} communication channel`))}),2e4),a=this._listeners.add(window,"message",(i=>{const{data:l,ports:c}=i;Zt(l)&&l.requestId===t&&"request"!==l.type&&(clearInterval(r),clearTimeout(s),this._listeners.remove(a),"string"==typeof l.error?o(new en(l.error)):c.length>0?n(c[0]):o(new en(`${this._source}-${e} port request failed`)))}));i()}))}}var nn,on={exports:{}};var rn=function(){if(nn)return on.exports;function e(){} return nn=1,e.prototype={on:function(e,t,n){var o=this.e||(this.e={});return(o[e]||(o[e]=[])).push({fn:t,ctx:n}),this},once:function(e,t,n){var o=this;function i(){o.off(e,i),t.apply(n,arguments)}return i._=t,this.on(e,i,n)},emit:function(e){for(var t=[].slice.call(arguments,1),n=((this.e||(this.e={}))[e]||[]).slice(),o=0,i=n.length;o{t.has(n)||(t.add(n),ln(new Error(n),e))};var o,i;this._listeners.add(window,"message",(o=e=>{const{data:t,origin:o,source:i}=e;if(!i)return;if(!Zt(t)||"request"!==t.type)return;const{frame1:r,frame2:s,requestId:a,sourceId:l}=t,c=`${r}-${s}`;if(!function(e){ return!(null===e||e instanceof MessagePort||window.ServiceWorker&&e instanceof ServiceWorker)}(i))return void n(`Ignored port request for channel ${c} from non-Window source`);if(void 0===this._allowedMessages.find((({allowedOrigin:e,...n})=>this._messageMatches({allowedMessage:n,allowedOrigin:e,data:t,origin:o}))))return void n(`Ignored invalid port request for channel ${c} from ${o}`);if(this._handledRequests.has(a))return;this._handledRequests.add(a);const d="null"===o?"*":o,u="sidebar-host"===c?this._sidebarHostChannel:new MessageChannel,h={frame1:r,frame2:s,type:"offer",requestId:a,sourceId:l};if(u===this._sidebarHostChannel){if(this._sidebarConnected)return console.warn("Ignoring second request from Hypothesis sidebar to connect to host frame"),h.error="Received duplicate port request",void i.postMessage(h,d);this._sidebarConnected=!0}i.postMessage(h,d,[u.port1]),"sidebar"===s?this._sidebarHostChannel.port2.postMessage(h,[u.port2]):"host"===s&&this._emitter.emit("frameConnected",r,u.port2)},i=e, (...e)=>{try{return o(...e)}catch(e){throw ln(e,i),e}}))}_messageMatches({allowedMessage:e,allowedOrigin:t,data:n,origin:o}){return("*"===t||o===t)&&function(e,t){return!!Zt(e)&&JSON.stringify(e,Object.keys(t).sort())===JSON.stringify(t,Object.keys(t).sort())}(n,e)}on(e,t){this._emitter.on(e,t)}destroy(){this._listeners.removeAll()}}const un="1.0.0",hn="frame-rpc";function fn(e,t=[],n=-1){return{protocol:hn,version:un,arguments:t,method:e,sequence:n}}function mn(e,t,n=[],o=-1){e.postMessage(fn(t,n,o))}function gn(e){const t=e.match(/\bAppleWebKit\/([0-9]+)\b/);if(!t)return!1;if(parseInt(t[1])<=537)return!1;const n=e.match(/\bVersion\/([0-9]+)\b/);if(!n)return!1;return!(parseInt(n[1])>=16)}class pn{constructor({userAgent:e=navigator.userAgent,currentWindow:t=window,forceUnloadListener:n=!1}={}){this._port=null,this._methods=new Map,this._sequence=1,this._callbacks=new Map,this._listeners=new be,"onclose"in MessagePort.prototype&&!n||this._listeners.add(t,"unload",(n=>{ n instanceof CustomEvent||this._port&&(mn(this._port,"close"),t!==t.parent&&gn(e)&&t.parent.postMessage({type:"hypothesisPortClosed"},"*",[this._port]))})),this._pendingCalls=[],this._destroyed=!1,this._receivedCloseEvent=!1}on(e,t){if(this._port)throw new Error("Cannot add a method handler after a port is connected");this._methods.set(e,t)}connect(e){this._port=e,this._listeners.add(e,"message",(e=>this._handle(e))),this._listeners.add(e,"close",(()=>{e.dispatchEvent(new MessageEvent("message",{data:fn("close")}))})),e.start(),mn(e,"connect");for(const[e,t]of this._pendingCalls)this.call(e,...t);this._pendingCalls=[]}destroy(){this._port&&(mn(this._port,"close"),this._port.close()),this._destroyed=!0,this._listeners.removeAll()}call(e,...t){if(this._port||this._pendingCalls.push([e,t]),!this._port||this._destroyed)return;const n=this._sequence++,o=t[t.length-1];"function"==typeof o&&(this._callbacks.set(n,o),t=t.slice(0,-1)),mn(this._port,e,t,n)}_parseMessage({data:e}){ return e&&"object"==typeof e?e.protocol!==hn||e.version!==un?null:Array.isArray(e.arguments)?e:null:null}_handle(e){const t=this._parseMessage(e),n=this._port;if(t&&n)if("method"in t){if("close"===t.method){if(this._receivedCloseEvent)return;this._receivedCloseEvent=!0}const e=this._methods.get(t.method);if(!e)return;const o=(...e)=>{const o={arguments:e,protocol:hn,response:t.sequence,version:un};n.postMessage(o)};e(...t.arguments,o)}else if("response"in t){const e=this._callbacks.get(t.response);this._callbacks.delete(t.response),e&&e(...t.arguments)}}}function _n(e){if("string"==typeof e&&"false"===e.trim().toLocaleLowerCase())return!1;const t=Number(e);return isNaN(t)?"string"==typeof e:Boolean(t)}function bn(e){for(var t={},n=e.querySelectorAll("script.js-hypothesis-config"),o=0;o!function(e){switch(getComputedStyle(e).position){case"fixed":case"sticky":return!0;default:return!1}}(e);e:for(const s of Ln(e,t,o)){let e=0;for(const o of s.data.split(/\b/)){if(/\S/.test(o)){const a=e,l=e+o.length,c=Tn(s,a,l);if(r=c,!wn(i=t)&&!wn(r)&&r.left>=i.left&&r.right<=i.right&&r.top>=i.top&&r.bottom<=i.bottom){n=document.createRange(),n.setStart(s,a),n.setEnd(s,l);break e}}e+=o.length}}var i,r;return n}function In(e,t=document.documentElement,n=new DOMRect(0,0,window.innerWidth,window.innerHeight)){const o=On(t,n);if(!o)return e(),0;const i=o.getBoundingClientRect().top;e();const r=o.getBoundingClientRect().top-i;return t.scrollTop+=r,r}function Bn(e,t,n){ const o=e.document.querySelector(`link[type="application/annotator+${n}"][rel="${t}"]`);if(!o)throw new Error(`No application/annotator+${n} (rel="${t}") link in the document`);if(!o.href)throw new Error(`application/annotator+${n} (rel="${t}") link has no href`);return o.href}function Hn(e){return"string"==typeof e?e:null}function Fn(e){const t=function(e){if(!vn(e,"hypothesisConfig"))return{};if("function"!=typeof e.hypothesisConfig){const e="https://h.readthedocs.io/projects/client/en/latest/publishers/config/#window.hypothesisConfig";return console.warn("hypothesisConfig must be a function, see: "+e),{}}return e.hypothesisConfig()}(e),n=_n(t.ignoreOtherConfiguration)?{}:bn(e.document);function o(e){return vn(t,e)?t[e]:vn(n,e)?n[e]:void 0}return{get annotations(){return Hn(n.annotations)||function(){const t=e.location.href.match(/#annotations:([A-Za-z0-9_-]+)$/);return t?t[1]:null}()},get clientUrl(){return Bn(e,"hypothesis-client","javascript")},get group(){return Hn(n.group)||function(){ const t=e.location.href.match(/#annotations:group:([A-Za-z0-9_-]+)$/);return t?t[1]:null}()},get notebookAppUrl(){return Bn(e,"notebook","html")},get profileAppUrl(){return Bn(e,"profile","html")},get showHighlights(){return function(){const e=o("showHighlights");switch(e){case"always":case"never":case"whenSidebarOpen":return e;case!0:return"always";case!1:return"never";default:return"always"}}()},get sidebarAppUrl(){return Bn(e,"sidebar","html")},get query(){return Hn(n.query)||function(){const t=e.location.href.match(/#annotations:(query|q):(.+)$/i);if(t)try{return decodeURIComponent(t[2])}catch{}return null}()},get sideBySide(){return function(){const e=o("sideBySide");if(!function(e){return null!==e&&"object"==typeof e}(e))return{mode:"auto"};const t="mode"in e&&function(e){return"string"==typeof e&&["auto","manual"].includes(e)}(e.mode)?e.mode:"auto";return"auto"===t?{mode:t}:{mode:t,isActive:"isActive"in e&&"function"==typeof e.isActive?e.isActive:void 0}}()},hostPageSetting:o}} const Dn=(e,t)=>e.hostPageSetting(t),Vn={annotations:{allowInBrowserExt:!0,defaultValue:null,getValue:e=>e.annotations},appType:{allowInBrowserExt:!0,defaultValue:null,getValue:Dn},branding:{defaultValue:null,allowInBrowserExt:!1,getValue:Dn},bucketContainerSelector:{defaultValue:null,allowInBrowserExt:!1,getValue:Dn},clientUrl:{allowInBrowserExt:!0,defaultValue:null,getValue:e=>e.clientUrl},contentInfoBanner:{allowInBrowserExt:!1,defaultValue:null,getValue:Dn},contentReady:{allowInBrowserExt:!0,defaultValue:null,getValue:Dn},enableExperimentalNewNoteButton:{allowInBrowserExt:!1,defaultValue:null,getValue:Dn},group:{allowInBrowserExt:!0,defaultValue:null,getValue:e=>e.group},focus:{allowInBrowserExt:!1,defaultValue:null,getValue:Dn},theme:{allowInBrowserExt:!1,defaultValue:null,getValue:Dn},usernameUrl:{allowInBrowserExt:!1,defaultValue:null,getValue:Dn},onLayoutChange:{allowInBrowserExt:!1,defaultValue:null,getValue:Dn},openSidebar:{allowInBrowserExt:!0,defaultValue:!1,coerce:_n,getValue:Dn},query:{ allowInBrowserExt:!0,defaultValue:null,getValue:e=>e.query},requestConfigFromFrame:{allowInBrowserExt:!1,defaultValue:null,getValue:Dn},services:{allowInBrowserExt:!1,defaultValue:null,getValue:Dn},showHighlights:{allowInBrowserExt:!1,defaultValue:"always",getValue:e=>e.showHighlights},notebookAppUrl:{allowInBrowserExt:!0,defaultValue:null,getValue:e=>e.notebookAppUrl},profileAppUrl:{allowInBrowserExt:!0,defaultValue:null,getValue:e=>e.profileAppUrl},sidebarAppUrl:{allowInBrowserExt:!0,defaultValue:null,getValue:e=>e.sidebarAppUrl},subFrameIdentifier:{allowInBrowserExt:!0,defaultValue:null,getValue:Dn},externalContainerSelector:{allowInBrowserExt:!1,defaultValue:null,getValue:Dn},sideBySide:{allowInBrowserExt:!0,getValue:e=>e.sideBySide}};function Un(e,t=window){const n=Fn(t),o={};for(const r of function(e){const t={annotator:["clientUrl","contentInfoBanner","contentReady","subFrameIdentifier","sideBySide"], sidebar:["appType","annotations","branding","bucketContainerSelector","enableExperimentalNewNoteButton","externalContainerSelector","focus","group","onLayoutChange","openSidebar","query","requestConfigFromFrame","services","showHighlights","sidebarAppUrl","theme","usernameUrl"],notebook:["branding","group","notebookAppUrl","requestConfigFromFrame","services","theme","usernameUrl"],profile:["profileAppUrl"]};return"all"===e?Object.values(t).flat():t[e]}(e)){const e=Vn[r],s=void 0!==e.defaultValue,a=!((i=Bn(t,"sidebar","html")).startsWith("http://")||i.startsWith("https://"));if(!e.allowInBrowserExt&&a){s&&(o[r]=e.defaultValue);continue}const l=e.getValue(n,r);void 0!==l?o[r]=e.coerce?e.coerce(l):l:s&&(o[r]=e.defaultValue)}var i;return o}const qn={alt:1,ctrl:2,meta:4,shift:8};function $n(e,t){if(!(e instanceof KeyboardEvent))return!1;const n=t.split("+").map((e=>e.toLowerCase()));let o=0,i=null;for(const e of n){const t=qn[e];if(t)o|=t;else{if(null!==i)throw new Error("Multiple non-modifier keys specified");i=e }}if(!i)throw new Error(`Invalid shortcut: ${t}`);return((e.ctrlKey?qn.ctrl:0)|(e.metaKey?qn.meta:0)|(e.altKey?qn.alt:0)|(e.shiftKey?qn.shift:0))===o&&e.key.toLowerCase()===i}function zn(e,t,{rootElement:n}={}){oe((()=>{if(e)return function(e,t,{rootElement:n=document.documentElement??void 0}={}){const o=n=>{$n(n,e)&&t(n)};return n?(n.addEventListener("keydown",o),()=>n.removeEventListener("keydown",o)):()=>{}}(e,t,{rootElement:n})}),[e,t,n])}const Wn=(e=window)=>e.matchMedia("(pointer: coarse)").matches;function jn({badgeCount:e}){return Pe("span",{className:Re("rounded px-1 py-0.5","bg-current"),children:Pe("span",{className:"font-bold text-color-text-inverted",children:e})})}function Xn({arrowDirection:e}){return Pe("div",{className:Re("absolute left-1/2 -translate-x-1/2 z-2","fill-white text-grey-3",{"top-0 -translate-y-full":"up"===e}),children:Pe("up"===e?ht:dt,{})})}function Kn({badgeCount:e,icon:t,label:n,onClick:o,shortcut:i}){zn(i,o);const r=i?`${n} (${i})`:n;return Pe(wt,{ classes:Re("text-grey-7","group-hover:text-grey-5","hover:group-hover:text-grey-9"),onClick:o,title:r,size:"custom",variant:"custom",children:Pe("div",{className:Re("flex flex-col items-center gap-y-1 py-2.5 px-2","text-annotator-sm leading-none"),children:[t&&Pe(t,{className:"text-annotator-lg",title:r}),"number"==typeof e&&Pe(jn,{badgeCount:e}),Pe("span",{"data-testid":"adder-button-label",children:n})]})})}function Gn({annotationCount:e,isVisible:t}){return Pe("div",{className:"sr-only",children:[Pe("span",{"aria-live":"polite","aria-atomic":"true",role:"status","data-testid":"annotation-count-announce",children:e>0&&Pe("span",{children:[e," ",1===e?"annotation":"annotations"," for this selection."]})}),Pe("ul",{"aria-live":"polite","data-testid":"annotate-shortcuts-announce",children:t&&Pe(x,{children:[e>0&&Pe("li",{children:["Press ","'S'"," to show annotations."]}),Pe("li",{children:["Press ","'A'"," to annotate."]}),Pe("li",{children:["Press ","'H'"," to highlight."]})]})})]})} function Yn({arrowDirection:e,isVisible:t,onCommand:n,annotationCount:o=0}){const i=t?"a":null,r=t?"h":null,s=t?"s":null;return zn(t?"Escape":null,(()=>n("hide"))),Pe("div",{className:Re("all-initial","border border-solid border-grey-3","absolute select-none bg-white rounded shadow-intense","opacity-5",{"animate-adder-pop-up":"up"===e&&t,"animate-adder-pop-down":"down"===e&&t}),"data-component":"AdderToolbar",dir:"ltr",style:{visibility:t?"visible":"hidden"},children:[Pe("div",{className:Re("flex group"),children:[Pe(Kn,{icon:Be,onClick:()=>n("annotate"),label:"Annotate",shortcut:i}),Pe(Kn,{icon:nt,onClick:()=>n("highlight"),label:"Highlight",shortcut:r}),o>0&&Pe(x,{children:[Pe("div",{className:Re("m-1.5 border-r border-grey-4 border-solid")}),Pe(Kn,{badgeCount:o,onClick:()=>n("show"),label:"Show",shortcut:s})]})]}),Pe(Xn,{arrowDirection:e}),Pe(Gn,{annotationCount:o,isVisible:t})]})}function Qn(e){const t=e.attachShadow({mode:"open"});!function(e){ const t=document.querySelector('link[rel="preload"][href*="/build/styles/annotator.css"]')?.href;if(!t)return;const n=document.createElement("link");n.rel="stylesheet",n.href=t,e.appendChild(n)}(t);const n=window.applyFocusVisiblePolyfill;return n&&n(t),t}class Jn{constructor(e,t){const n=`hypothesis-${e}`;this._element=document.createElement(n),this._shadowRoot=Qn(this._element),this._render=t}destroy(){V(null,this._shadowRoot),this._element.remove()}get element(){return this._element}render(){V(this._render(),this._shadowRoot)}}let Zn=function(e){return e[e.DOWN=1]="DOWN",e[e.UP=2]="UP",e}({});function eo(e){return e.toString()+"px"}class to{constructor(e,t){this._view=e.ownerDocument.defaultView,this._isVisible=!1,this._arrowDirection="up",this._annotationsForSelection=[],this._onAnnotate=t.onAnnotate,this._onHighlight=t.onHighlight,this._onShowAnnotations=t.onShowAnnotations,this._container=new Jn("adder",(()=>this._render())),e.appendChild(this._container.element), Object.assign(this._container.element.style,{position:"absolute",top:0,left:0}),this._container.render()}get annotationsForSelection(){return this._annotationsForSelection}set annotationsForSelection(e){this._annotationsForSelection=e,this._container.render()}hide(){this._isVisible=!1,this._container.render(),Object.assign(this._container.element.style,{top:0,left:0})}destroy(){this._container.destroy()}show(e,t){const{left:n,top:o,arrowDirection:i}=this._calculateTarget(e,t);this._showAt(n,o),this._isVisible=!0,this._arrowDirection=i===Zn.UP?"up":"down",this._container.render()}_firstChild(){return this._container.element.shadowRoot.firstChild}_width(){return this._firstChild().getBoundingClientRect().width}_height(){return this._firstChild().getBoundingClientRect().height}_calculateTarget(e,t){let n,o,i;n=t&&!Wn()?Zn.DOWN:Zn.UP;const r=Math.min(20,e.width),s=this._width(),a=Wn()?10:0,l=this._height();return i=t?e.left-s/2+r:e.left+e.width-s/2-r, e.top-l<0&&n===Zn.DOWN?n=Zn.UP:e.top+l>this._view.innerHeight&&(n=Zn.DOWN),o=n===Zn.UP?e.top+e.height+10+a:e.top-l-10,i=Math.max(i,0),i=Math.min(i,this._view.innerWidth-s),o=Math.max(o,0),o=Math.min(o,this._view.innerHeight-l),{top:o,left:i,arrowDirection:n}}_findZindex(e,t){if(void 0===document.elementsFromPoint)return 32768;const n=this._width(),o=this._height(),i=[...new Set([...document.elementsFromPoint(e,t),...document.elementsFromPoint(e,t+o),...document.elementsFromPoint(e+n/2,t+o/2),...document.elementsFromPoint(e+n,t),...document.elementsFromPoint(e+n,t+o)])].map((e=>+getComputedStyle(e).zIndex)).filter(Number.isInteger);return i.push(0),Math.max(...i)+1}_showAt(e,t){const n=function(e){let t=e.parentElement;for(;t.parentElement&&"static"===getComputedStyle(t).position;)t=t.parentElement;return t}(this._container.element).getBoundingClientRect(),o=this._findZindex(e,t);Object.assign(this._container.element.style,{left:eo(e-n.left),top:eo(t-n.top),zIndex:o})}_render(){return Pe(Yn,{ isVisible:this._isVisible,arrowDirection:this._arrowDirection,onCommand:e=>{switch(e){case"annotate":this._onAnnotate(),this.hide();break;case"highlight":this._onHighlight(),this.hide();break;case"show":this._onShowAnnotations(this.annotationsForSelection);break;case"hide":this.hide()}},annotationCount:this.annotationsForSelection.length})}}var no=function(e){return e[e.Forwards=1]="Forwards",e[e.Backwards=2]="Backwards",e}(no||{});function oo(e,t,n){const o=n===no.Forwards?t:t-1;if(""!==e.charAt(o).trim())return t;let i,r;if(n===no.Backwards?(i=e.substring(0,t),r=i.trimEnd()):(i=e.substring(t),r=i.trimStart()),!r.length)return-1;const s=i.length-r.length;return n===no.Backwards?t-s:t+s}function io(e,t){const n=e.commonAncestorContainer.ownerDocument.createNodeIterator(e.commonAncestorContainer,NodeFilter.SHOW_TEXT),o=t===no.Forwards?e.startContainer:e.endContainer,i=t===no.Forwards?e.endContainer:e.startContainer;let r=n.nextNode();for(;r&&r!==o;)r=n.nextNode();t===no.Backwards&&(r=n.previousNode());let s=-1 ;const a=()=>{if(r=t===no.Forwards?n.nextNode():n.previousNode(),r){const e=r.textContent,n=t===no.Forwards?0:e.length;s=oo(e,n,t)}};for(;r&&-1===s&&r!==i;)a();if(r&&s>=0)return{node:r,offset:s};throw new RangeError("No text nodes with non-whitespace text found in range")}function ro(e){switch(e.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return e.textContent?.length??0;default:return 0}}function so(e){let t=e.previousSibling,n=0;for(;t;)n+=ro(t),t=t.previousSibling;return n}function ao(e,...t){let n=t.shift();const o=e.ownerDocument.createNodeIterator(e,NodeFilter.SHOW_TEXT),i=[];let r,s=o.nextNode(),a=0;for(;void 0!==n&&s;)r=s,a+r.data.length>n?(i.push({node:r,offset:n-a}),n=t.shift()):(s=o.nextNode(),a+=r.data.length);for(;void 0!==n&&r&&a===n;)i.push({node:r,offset:r.data.length}),n=t.shift();if(void 0!==n)throw new RangeError("Offset exceeds text length");return i}let lo=function(e){return e[e.FORWARDS=1]="FORWARDS",e[e.BACKWARDS=2]="BACKWARDS",e}({});class co{constructor(e,t){ if(t<0)throw new Error("Offset is invalid");this.element=e,this.offset=t}relativeTo(e){if(!e.contains(this.element))throw new Error("Parent is not an ancestor of current element");let t=this.element,n=this.offset;for(;t!==e;)n+=so(t),t=t.parentElement;return new co(t,n)}resolve(e={}){try{return ao(this.element,this.offset)[0]}catch(t){if(0===this.offset&&void 0!==e.direction){const n=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);n.currentNode=this.element;const o=e.direction===lo.FORWARDS,i=o?n.nextNode():n.previousNode();if(!i)throw t;return{node:i,offset:o?0:i.data.length}}throw t}}static fromCharOffset(e,t){switch(e.nodeType){case Node.TEXT_NODE:return co.fromPoint(e,t);case Node.ELEMENT_NODE:return new co(e,t);default:throw new Error("Node is not an element or text node")}}static fromPoint(e,t){switch(e.nodeType){case Node.TEXT_NODE:{if(t<0||t>e.data.length)throw new Error("Text node offset is out of range");if(!e.parentElement)throw new Error("Text node has no parent") ;const n=so(e)+t;return new co(e.parentElement,n)}case Node.ELEMENT_NODE:{if(t<0||t>e.childNodes.length)throw new Error("Child node offset is out of range");let n=0;for(let o=0;o=0&&(t.setStart(e.startContainer,i.start),n=!0),i.end>0&&(t.setEnd(e.endContainer,i.end),o=!0),n&&o)return t;if(!n){const{node:e,offset:n}=io(t,no.Forwards);e&&n>=0&&t.setStart(e,n)}if(!o){const{node:e,offset:n}=io(t,no.Backwards);e&&n>0&&t.setEnd(e,n)}return t}(uo.fromRange(e).toRange())}}const ho=".annotator-placeholder";function fo(e){return!!e.parentElement&&null!==e.parentElement.closest(ho)}function mo(e,t){const n=new Range ;return e.compareBoundaryPoints(Range.START_TO_START,t)<=0?n.setStart(e.startContainer,e.startOffset):n.setStart(t.startContainer,t.startOffset),e.compareBoundaryPoints(Range.END_TO_END,t)>=0?n.setEnd(e.endContainer,e.endOffset):n.setEnd(t.endContainer,t.endOffset),n}function go(e=document.getSelection()){if(!e||0===e.rangeCount)return null;let t=e.getRangeAt(0);for(let n=1;n=0}catch{return!1}}function bo(e,t){const n=e.commonAncestorContainer,o=n.ownerDocument.createNodeIterator(n,NodeFilter.SHOW_ALL);let i;for(;i=o.nextNode();)_o(e,i)&&t(i)}function vo(e){const t=go(e);if(!t)return null;const n=function(e){const t=[];return bo(e,(e=>{Rn(e)&&!e.textContent.match(/^\s*$/)&&t.push(e)})),t.flatMap((t=>{ const n=t.ownerDocument.createRange();if(n.selectNodeContents(t),t===e.startContainer&&n.setStart(t,e.startOffset),t===e.endContainer&&n.setEnd(t,e.endOffset),n.collapsed)return[];const o=Array.from(n.getClientRects());return n.detach(),o}))}(t);return 0===n.length?null:po(e)?n[0]:n[n.length-1]}const wo="http://www.w3.org/2000/svg",yo=["user-annotations","user-highlights","other-content"];function xo(e,t){const n=function(e){if(e.collapsed)return[];let t=e.commonAncestorContainer;if(t&&t.nodeType!==Node.ELEMENT_NODE&&(t=t.parentElement),!t)return[];const n=[],o=t.ownerDocument.createNodeIterator(t,NodeFilter.SHOW_TEXT);let i;for(;i=o.nextNode();){if(!_o(e,i))continue;const t=i;t===e.startContainer&&e.startOffset>0?t.splitText(e.startOffset):(t===e.endContainer&&e.endOffset0&&fo(n[0]);let i=[],r=null,s=null;n.forEach((e=>{r&&r.nextSibling===e?s.push(e):(s=[e],i.push(s)),r=e}));const a=/^\s*$/;i=i.filter((e=>{const t=e[0].parentElement ;return 1===t?.childNodes.length&&"SPAN"===t?.tagName||e.some((e=>!a.test(e.data)))}));const l=[];return i.forEach((e=>{const n=document.createElement("hypothesis-highlight");n.className=Re("hypothesis-highlight",t);e[0].parentNode.replaceChild(n,e[0]),e.forEach((e=>n.appendChild(e))),l.push(n)})),o||function(e,t){if(0===e.length)return;const n=function(e){const t=e.closest(".page");if(!t)return null;return t.querySelector(".canvasWrapper > canvas")||null}(e[0]);if(!n||!n.parentElement)return;let o=n.parentElement.querySelector(".hypothesis-highlight-layer");if(!o){o=document.createElementNS(wo,"svg"),o.setAttribute("class","hypothesis-highlight-layer"),n.parentElement.appendChild(o),n.parentElement.style.position="relative";const e=o.style;e.position="absolute",e.left="0",e.top="0",e.width="100%",e.height="100%",e.mixBlendMode="multiply"}const i=n.getBoundingClientRect(),r=e.map((e=>{const n=e.getBoundingClientRect(),o=document.createElementNS(wo,"rect");return o.setAttribute("x",(n.left-i.left).toString()), o.setAttribute("y",(n.top-i.top).toString()),o.setAttribute("width",n.width.toString()),o.setAttribute("height",n.height.toString()),o.setAttribute("class",Re("hypothesis-svg-highlight",t)),e.classList.add("is-transparent"),e.svgHighlight=o,o}));o.append(...r)}(l,t),l}function No(e,t){const n=e.parentNode;t.forEach((t=>n.insertBefore(t,e))),e.remove()}function Co(e){So(e,!1);for(const t of e){if(t.parentNode){No(t,Array.from(t.childNodes))}t.svgHighlight&&t.svgHighlight.remove()}}function So(e,t){e.forEach((e=>{e.svgHighlight?function(e,t){const n=e.parentNode,o=e.getAttribute("data-focused-id");if(Boolean(o)!==t)if(t){e.setAttribute("data-focused-id",Jt(8));const t=e.cloneNode();t.setAttribute("data-is-focused","data-is-focused"),n.append(t)}else{const t=n.querySelector(`[data-focused-id="${o}"][data-is-focused]`);t?.remove(),e.removeAttribute("data-focused-id")}}(e.svgHighlight,t):e.classList.toggle("hypothesis-highlight-focused",t)}))}function Eo(e){ko(Ro(e)),function(e){for(const[t,n]of function(e){ const t=new Map;for(const n of(e??document).getElementsByClassName("hypothesis-highlight-layer"))t.set(n,Array.from(n.querySelectorAll(".hypothesis-svg-highlight")));return t}(e)){n.every(((e,t,n)=>0===t||Po(e)>=Po(n[t-1])))||(n.sort(((e,t)=>Po(e)-Po(t))),t.replaceChildren(...n))}}(e)}const Ao=e=>"hypothesis-highlight"===e.tagName.toLowerCase();function Ro(e){let t;return t=Ao(e)?Array.from(e.children).filter(Ao):Array.from(e.getElementsByTagName("hypothesis-highlight")).filter((e=>!e.parentElement||!Ao(e.parentElement))),t}function ko(e,t="",n=0,o=0){for(const i of e){const e=yo.find((e=>i.classList.contains(e)))??"other-content",r=t&&e===t?o+1:0;i.setAttribute("data-nesting-level",`${n}`),i.setAttribute("data-cluster-level",`${r}`),i.svgHighlight&&(i.svgHighlight.setAttribute("data-nesting-level",`${n}`),i.svgHighlight.setAttribute("data-cluster-level",`${r}`)),ko(Ro(i),e,n+1,r)}}function Po(e){ return e.getAttribute("data-is-focused")?Number.MAX_SAFE_INTEGER:parseInt(e.getAttribute("data-nesting-level")??"0",10)}function To(e){const t=[];return e.forEach((({annotation:e,highlights:n})=>{if(!n?.length)return;const{top:o,bottom:i}=function(e){const t=e.map((e=>e.getBoundingClientRect()));return t.reduce(((e,t)=>({top:Math.min(e.top,t.top),left:Math.min(e.left,t.left),bottom:Math.max(e.bottom,t.bottom),right:Math.max(e.right,t.right)})))}(n);o>=i||t.push({tag:e.$tag,top:o,bottom:i})})),t.sort(((e,t)=>e.top-t.top)),t}class Mo{constructor({contentContainer:e,hostRPC:t}){this._hostRPC=t,this._updatePending=!1,this._anchors=[],this._listeners=new be,this._listeners.add(window,"resize",(()=>this.update())),this._listeners.add(window,"scroll",(()=>this.update())),this._listeners.add(e,"scroll",(()=>this.update()),{capture:!0})}destroy(){this._listeners.removeAll()}update(e){e&&(this._anchors=e),this._updatePending||(this._updatePending=!0,requestAnimationFrame((()=>{const e=To(this._anchors) ;this._hostRPC.call("anchorsChanged",e),this._updatePending=!1})))}}class Lo extends CustomEvent{constructor(e){super("hypothesis:layoutchange",{bubbles:!0,cancelable:!1,detail:e})}}const Oo=new Set;function Io(...e){const t=e.join();Oo.has(t)||(console.warn(...e),Oo.add(t))}Io.reset=()=>{Oo.clear()};const Bo=["styled_highlight_clusters"];class Ho extends rn.TinyEmitter{constructor(e=Bo){super(),this._flags=new Map,this._knownFlags=e}update(e){this._flags.clear();for(const[t,n]of Object.entries(e))this._flags.set(t,n);this.emit("flagsChanged")}flagEnabled(e){return this._knownFlags.includes(e)?this._flags.get(e)??!1:(Io("Looked up unknown feature",e),!1)}allFlags(){return Object.fromEntries(this._flags)}}function Fo({cluster:e,label:t,onChange:n,currentStyles:o,highlightStyles:i}){const r=o[e],s="transparent"===r;return Pe("div",{className:"space-y-2",children:[Pe("div",{className:"flex items-center gap-x-2 text-annotator-base",children:Pe("div",{className:"grow text-color-text px-2 py-1 rounded",style:{ backgroundColor:i[r].color},children:t})}),Pe("div",{className:"flex items-center gap-x-2",children:Object.keys(i).map((t=>Pe("div",{className:"relative",children:[Pe("input",{className:Re("absolute w-6 h-6","opacity-[.00001]","cursor-pointer"),name:e,id:`hypothesis-${e}-${t}`,checked:r===t,onChange:n,type:"radio",value:t}),Pe("label",{className:"block",htmlFor:`${e}-${t}`,children:[Pe("div",{style:{backgroundColor:i[t].color},className:Re("block w-6 h-6 rounded-full flex items-center justify-center",{"border-2 border-slate-0":r!==t,"border-2 border-slate-3":r===t}),children:"transparent"===t&&Pe(et,{className:Re("w-3 h-3",{"text-slate-3":!s,"text-slate-7":s})})}),Pe("span",{className:"sr-only",children:t})]})]},`${e}-${t}`)))})]})}function Do({active:e,availableStyles:t,currentStyles:n,onStyleChange:o}){const i=ae((e=>{const t=e.target,n=t.name,i=t.value;o(n,i)}),[o]),[r,s]=ne(!1);return e?Pe(Me,{classes:"overflow-hidden",children:Pe("div",{className:"flex flex-col text-annotator-base text-color-text", children:[Pe(wt,{classes:"rounded-none","data-testid":"control-toggle-button",onClick:()=>s(!r),title:r?"Hide highlight settings":"Show highlight settings",children:Pe(x,r?{children:[Pe(Ve,{}),Pe("span",{children:"Highlight Appearance"})]}:{children:[Pe(ze,{}),Pe(nt,{})]})}),r&&Pe(Oe,{"data-testid":"cluster-style-controls",size:"sm",children:[Pe(Fo,{highlightStyles:t,label:"My annotations",cluster:"user-annotations",onChange:i,currentStyles:n}),Pe(Fo,{highlightStyles:t,label:"My highlights",cluster:"user-highlights",onChange:i,currentStyles:n}),Pe(Fo,{highlightStyles:t,label:"Everybody's content",cluster:"other-content",onChange:i,currentStyles:n})]})]})}):null}const Vo={transparent:{color:"transparent",secondColor:"transparent",thirdColor:"transparent"},pink:{color:"var(--hypothesis-color-pink)",secondColor:"var(--hypothesis-color-pink-1)",thirdColor:"var(--hypothesis-color-pink-2)"},orange:{color:"var(--hypothesis-color-orange)",secondColor:"var(--hypothesis-color-orange-1)", thirdColor:"var(--hypothesis-color-orange-2)"},yellow:{color:"var(--hypothesis-color-yellow)",secondColor:"var(--hypothesis-color-yellow-1)",thirdColor:"var(--hypothesis-color-yellow-2)"},green:{color:"var(--hypothesis-color-green)",secondColor:"var(--hypothesis-color-green-1)",thirdColor:"var(--hypothesis-color-green-2)"},purple:{color:"var(--hypothesis-color-purple)",secondColor:"var(--hypothesis-color-purple-1)",thirdColor:"var(--hypothesis-color-purple-2)"},grey:{color:"var(--hypothesis-color-grey)",secondColor:"var(--hypothesis-color-grey-1)",thirdColor:"var(--hypothesis-color-grey-2)"}},Uo={"other-content":"yellow","user-annotations":"orange","user-highlights":"purple"};class qo{constructor(e,t){this._element=e,this._features=t.features,this._container=new Jn("highlight-cluster-toolbar",(()=>this._render())),this._element.appendChild(this._container.element),Object.assign(this._container.element.style,{position:"fixed",top:`${this._element.offsetTop+4}px`,left:"4px"}),this.appliedStyles=Uo,this._init(), this._features.on("flagsChanged",(()=>{this._activate(this._isActive())})),this._container.render()}destroy(){clearTimeout(this._updateTimeout),this._activate(!1),this._container.destroy()}scheduleClusterUpdates(){clearTimeout(this._updateTimeout),this._updateTimeout=setTimeout((()=>this._updateClusters()),100)}_init(){for(const e of Object.keys(this.appliedStyles))this._setClusterStyles(e,this.appliedStyles[e]);this._activate(this._isActive())}_updateClusters(){this._isActive()&&Eo(this._element)}_isActive(){return this._features.flagEnabled("styled_highlight_clusters")}_activate(e){this._element.classList.toggle("hypothesis-highlights-clustered",e),this._container.render()}_setClusterStyle(e,t){document.documentElement.style.setProperty(e,t)}_setClusterStyles(e,t){const n=Vo[t];for(const t of Object.keys(n))this._setClusterStyle(`--hypothesis-${e}-${t}`,n[t])}_onChangeClusterStyle(e,t){this.appliedStyles[e]=t,this._setClusterStyles(e,t),this._container.render()}_render(){return Pe(Do,{ active:this._isActive(),availableStyles:Vo,currentStyles:this.appliedStyles,onStyleChange:(e,t)=>this._onChangeClusterStyle(e,t)})}}function $o(e){return e.split("").reverse().join("")}function zo(e){return(e|-e)>>31&1}function Wo(e,t,n,o){let i=e.P[n],r=e.M[n];const s=o>>>31,a=t[n]|s,l=a|r,c=(a&i)+i^i|a;let d=r|~(c|i),u=i&c;const h=zo(d&e.lastRowMask[n])-zo(u&e.lastRowMask[n]);return d<<=1,u<<=1,u|=s,d|=zo(o)-s,i=u|~(l|d),r=d&l,e.P[n]=i,e.M[n]=r,h}function jo(e,t,n){if(0===t.length)return[];n=Math.min(n,t.length);const o=[],i=32,r=Math.ceil(t.length/i)-1,s={P:new Uint32Array(r+1),M:new Uint32Array(r+1),lastRowMask:new Uint32Array(r+1)};s.lastRowMask.fill(1<<31),s.lastRowMask[r]=1<<(t.length-1)%i;const a=new Uint32Array(r+1),l=new Map,c=[];for(let e=0;e<256;e++)c.push(a);for(let e=0;e=t.length)continue ;t.charCodeAt(s)===n&&(o[e]|=1<0&&u[d]>=n+i;)d-=1;d===r&&u[d]<=n&&(u[d]{const i=Math.max(0,n.end-t.length-n.errors);return{start:jo($o(e.slice(i,n.end)),o,n.errors).reduce(((e,t)=>n.end-t.end0?i:Xo(e,t,n)}function Go(e,t){if(0===t.length||0===e.length)return 0;return 1-Ko(e,t,t.length)[0].errors/t.length}function Yo(e,t,n={}){if(0===t.length)return null;const o=Math.min(256,t.length/2),i=Ko(e,t,o);if(0===i.length)return null;const r=o=>{const i=1-o.errors/t.length,r=n.prefix?Go(e.slice(Math.max(0,o.start-n.prefix.length),o.start),n.prefix):1,s=n.suffix?Go(e.slice(o.end,o.end+n.suffix.length),n.suffix):1;let a=1;if("number"==typeof n.hint){a=1-Math.abs(o.start-n.hint)/e.length}return(50*i+20*r+20*s+2*a)/92},s=i.map((e=>({start:e.start,end:e.end,score:r(e)})));return s.sort(((e,t)=>t.score-e.score)),s[0]}function Qo(e){const t=function(e){const t=e.nodeName.toLowerCase();return"#text"===t?"text()":t}(e),n=function(e){let t=0,n=e;for(;n;)n.nodeName===e.nodeName&&(t+=1),n=n.previousSibling;return t}(e);return`${t}[${n}]`}function Jo(e,t){let n="",o=e;for(;o!==t;){if(!o)throw new Error("Node is not a descendant of root");n=Qo(o)+"/"+n,o=o.parentNode}return n="/"+n, n=n.replace(/\/$/,""),n}function Zo(e,t,n){t=t.toUpperCase();let o=-1;for(let i=0;i{const t=si(e);if(!t)return null;const[n,o]=t;return{element:e,start:n,end:o}})).filter((e=>null!==e));e.sort(((e,t)=>e.start-t.start));const t=function(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}(e,(e=>e.start<=this.start&&e.end>=this.start));if(-1===t)throw new Error("Start segment not found");const n=t+e.slice(t).findIndex((e=>e.start<=this.end&&e.end>=this.end));if(-1===n)throw new Error("End segment not found");const o=new Range;o.setStart(e[t].element,0);const i=e[n].element;return o.setEnd(i,i.childNodes.length),o}static fromSelector(e,t){const{start:n,end:o}=t;return new ai(e,n,o)}toSelector(){return{type:"MediaTimeSelector",start:this.start,end:this.end}}}async function li(e,t){return e.toRange(t)}function ci(e,t,n){const o=e[t];if("function"!=typeof o)throw new Error("Can only intercept functions");return e[t]=(...t)=>{const i=o.call(e,...t);return n(...t),i},()=>{ e[t]=o}}function di(e){return e.replace(/#.*/,"")}class ui{constructor(e,t=(()=>location.href)){this._listeners=new be;let n=t();const o=(o=t())=>{di(n)!==di(o)&&(n=o,e(o))},i=function(){const e=window.navigation;return"function"==typeof Navigation&&e instanceof Navigation?e:null}();if(i)this._listeners.add(i,"navigatesuccess",(()=>o()));else{const e=[ci(window.history,"pushState",(()=>o())),ci(window.history,"replaceState",(()=>o()))];this._unpatchHistory=()=>e.forEach((e=>e())),this._listeners.add(window,"popstate",(()=>o()))}}disconnect(){this._unpatchHistory?.(),this._listeners.removeAll()}}var hi,fi;var mi=function(){if(fi)return hi;fi=1;var e="complete",t="canceled";function n(e,t,n){e.self===e?e.scrollTo(t,n):(e.scrollLeft=t,e.scrollTop=n)}function o(t){var i=t._scrollSettings;if(i){var r=i.maxSynchronousAlignments,s=function(e,t){ var n,o,i,r,s,a,l,c=e.align,d=e.target.getBoundingClientRect(),u=c&&null!=c.left?c.left:.5,h=c&&null!=c.top?c.top:.5,f=c&&null!=c.leftOffset?c.leftOffset:0,m=c&&null!=c.topOffset?c.topOffset:0,g=u,p=h;if(e.isWindow(t))a=Math.min(d.width,t.innerWidth),l=Math.min(d.height,t.innerHeight),o=d.left+t.pageXOffset-t.innerWidth*g+a*g,i=d.top+t.pageYOffset-t.innerHeight*p+l*p,o-=f,i-=m,o=e.align.lockX?t.pageXOffset:o,i=e.align.lockY?t.pageYOffset:i,r=o-t.pageXOffset,s=i-t.pageYOffset;else{a=d.width,l=d.height,n=t.getBoundingClientRect();var _=d.left-(n.left-t.scrollLeft),b=d.top-(n.top-t.scrollTop);o=_+a*g-t.clientWidth*g,i=b+l*p-t.clientHeight*p,o-=f,i-=m,o=Math.max(Math.min(o,t.scrollWidth-t.clientWidth),0),i=Math.max(Math.min(i,t.scrollHeight-t.clientHeight),0),o=e.align.lockX?t.scrollLeft:o,i=e.align.lockY?t.scrollTop:i,r=o-t.scrollLeft,s=i-t.scrollTop}return{x:o,y:i,differenceX:r,differenceY:s}}(i,t),a=Date.now()-i.startTime,l=Math.min(1/i.time*a,1);if(i.endIterations>=r)return n(t,s.x,s.y), t._scrollSettings=null,i.end(e);var c=1-i.ease(l);if(n(t,s.x-s.differenceX*c,s.y-s.differenceY*c),a>=i.time)return i.endIterations++,i.scrollAncestor&&o(i.scrollAncestor),void o(t);!function(e){if("requestAnimationFrame"in window)return window.requestAnimationFrame(e);setTimeout(e,16)}(o.bind(null,t))}}function i(e){return e.self===e}function r(e){return"pageXOffset"in e||(e.scrollHeight!==e.clientHeight||e.scrollWidth!==e.clientWidth)&&"hidden"!==getComputedStyle(e).overflow}function s(){return!0}function a(e){if(e.assignedSlot)return a(e.assignedSlot);if(e.parentElement)return"body"===e.parentElement.tagName.toLowerCase()?e.parentElement.ownerDocument.defaultView||e.parentElement.ownerDocument.ownerWindow:e.parentElement;if(e.getRootNode){var t=e.getRootNode();if(11===t.nodeType)return t.host}}return hi=function(n,l,c){if(n){"function"==typeof l&&(c=l,l=null),l||(l={}),l.time=isNaN(l.time)?1e3:l.time,l.ease=l.ease||function(e){return 1-Math.pow(1-e,e/2)},l.align=l.align||{} ;var d=a(n),u=1,h=l.validTarget||s,f=l.isScrollable;l.debug&&(console.log("About to scroll to",n),d||console.error("Target did not have a parent, is it mounted in the DOM?"));for(var m=[];d;)if(l.debug&&console.log("Scrolling parent node",d),h(d,u)&&(f?f(d,r):r(d))&&(u++,m.push(d)),!(d=a(d))){g(e);break}return m.reduce(((e,r,s)=>function(e,n,r,s,a){var l,c=!n._scrollSettings,d=n._scrollSettings,u=Date.now(),h={passive:!0};function f(e){n._scrollSettings=null,n.parentElement&&n.parentElement._scrollSettings&&n.parentElement._scrollSettings.end(e),r.debug&&console.log("Scrolling ended with type",e,"for",n),a(e),l&&(n.removeEventListener("touchstart",l,h),n.removeEventListener("wheel",l,h))}d&&d.end(t);var m=r.maxSynchronousAlignments;return null==m&&(m=3),n._scrollSettings={startTime:u,endIterations:0,target:e,time:r.time,ease:r.ease,align:r.align,isWindow:r.isWindow||i,maxSynchronousAlignments:m,end:f,scrollAncestor:s},"cancellable"in r&&!r.cancellable||(l=f.bind(null,t),n.addEventListener("touchstart",l,h), n.addEventListener("wheel",l,h)),c&&o(n),l}(n,r,l,m[s+1],g)),null)}function g(e){--u||c&&c(e)}},hi}(),gi=t(mi);function pi(e,t,n){return e+n*(t-e)}async function _i(e,t,{maxDuration:n=500}={}){const o=e.scrollTop,i=t,r=Date.now(),s=Math.min(Math.abs(i-o)/3,n);let a=0;for(;a<1;)await new Promise((e=>{requestAnimationFrame(e)})),a=Math.min(1,(Date.now()-r)/s),e.scrollTop=pi(o,i,a)}function bi(e,t=document.baseURI){return new URL(e,t).href.toString().replace(/#.*/,"")}class vi{constructor(e={}){this.document=e.document||document}uri(){let e=this._getDocumentHref();try{e=decodeURIComponent(e)}catch(e){console.error("Error decoding URI:",e)}const t=this._getLinks();for(const n of t)"canonical"===n.rel&&(e=n.href);return e}getDocumentMetadata(){const e={title:document.title,link:[],dc:this._getMetaTags("name","dc."),eprints:this._getMetaTags("name","eprints."),facebook:this._getMetaTags("property","og:"),highwire:this._getMetaTags("name","citation_"),prism:this._getMetaTags("name","prism."), twitter:this._getMetaTags("name","twitter:")},t=this._getFavicon();t&&(e.favicon=t),e.title=this._getTitle(e),e.link=this._getLinks(e);const n=e.link.find((e=>e.href.startsWith("urn:x-dc")));return n&&(e.documentFingerprint=n.href),e}_getMetaTags(e,t){const n={};for(const o of Array.from(this.document.querySelectorAll("meta"))){const i=o.getAttribute(e),{content:r}=o;if(i&&r){const e=i.match(RegExp(`^${t}(.+)$`,"i"));if(e){const t=e[1].toLowerCase();n[t]?n[t].push(r):n[t]=[r]}}}return n}_getTitle(e){return e.highwire.title?e.highwire.title[0]:e.eprints.title?e.eprints.title[0]:e.prism.title?e.prism.title[0]:e.facebook.title?e.facebook.title[0]:e.twitter.title?e.twitter.title[0]:e.dc.title?e.dc.title[0]:this.document.title}_getLinks(e={dc:{},highwire:{}}){const t=[{href:this._getDocumentHref()}],n=Array.from(this.document.querySelectorAll("link"));for(const e of n)if(["alternate","canonical","bookmark","shortlink"].includes(e.rel)){if("alternate"===e.rel){ if(e.type&&e.type.match(/^application\/(rss|atom)\+xml/))continue;if(e.hreflang)continue}try{const n=this._absoluteUrl(e.href);t.push({href:n,rel:e.rel,type:e.type})}catch{}}for(const n of Object.keys(e.highwire)){const o=e.highwire[n];if("pdf_url"===n)for(const e of o)try{t.push({href:this._absoluteUrl(e),type:"application/pdf"})}catch{}if("doi"===n)for(let e of o)"doi:"!==e.slice(0,4)&&(e=`doi:${e}`),t.push({href:e})}for(const n of Object.keys(e.dc)){const o=e.dc[n];if("identifier"===n)for(const e of o)"doi:"===e.slice(0,4)&&t.push({href:e})}const o=e.dc["relation.ispartof"],i=e.dc.identifier;if(o&&i){const e=o[o.length-1],n=i[i.length-1],r="urn:x-dc:"+encodeURIComponent(e)+"/"+encodeURIComponent(n);t.push({href:r})}return t}_getFavicon(){let e=null;for(const t of Array.from(this.document.querySelectorAll("link")))if(["shortcut icon","icon"].includes(t.rel))try{e=this._absoluteUrl(t.href)}catch{}return e}_absoluteUrl(e){return bi(e,this.document.baseURI)}_getDocumentHref(){ const{href:e}=this.document.location,t=["http:","https:","file:"],n=new URL(e).protocol;return t.includes(n)?e:this.document.baseURI&&t.includes(new URL(this.document.baseURI).protocol)?this.document.baseURI:e}}class wi extends rn.TinyEmitter{constructor({features:e,container:t=document.body,sideBySideOptions:n}){super(),this.features=e,this.container=t,this._htmlMeta=new vi,this._prevURI=this._htmlMeta.uri(),this._sideBySideEnabled=!0,this._sideBySideOptions=n??{mode:"auto"},this._sideBySideActive=!1,this._lastLayout=null,this._navObserver=new ui((()=>this._checkForURIChange())),this._metaObserver=new MutationObserver((()=>this._checkForURIChange())),this._metaObserver.observe(document.head,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["rel","href","name","content"]}),this._flagsChanged=()=>{},this.features.on("flagsChanged",this._flagsChanged)}anchor(e,t){return function(e,t,n={}){let o=null,i=null,r=null,s=null;for(const e of t)switch(e.type){case"TextPositionSelector":i=e,n.hint=i.start;break ;case"TextQuoteSelector":r=e;break;case"RangeSelector":s=e;break;case"MediaTimeSelector":o=e}const a=e=>{if(r?.exact&&e.toString()!==r.exact)throw new Error("quote mismatch");return e};let l=Promise.reject("unable to anchor");if(s){const t=s;l=l.catch((()=>li(ti.fromSelector(e,t),n).then(a)))}if(i){const t=i;l=l.catch((()=>li(ni.fromSelector(e,t),n).then(a)))}if(r){const t=r;l=l.catch((()=>li(oi.fromSelector(e,t),n)))}if(o){const t=o;l=l.catch((()=>ai.fromSelector(e,t).toRange()))}return l}(e,t)}describe(e,t){return function(e,t){const n=[ai,ti,ni,oi],o=[];for(const i of n)try{const n=i.fromRange(e,t);n&&o.push(n.toSelector())}catch{}return o}(e,t)}_checkForURIChange(){const e=this._htmlMeta.uri();e!==this._prevURI&&(this._prevURI=e,this.emit("uriChanged",e))}getAnnotatableRange(e){try{return uo.trimmedRange(e)}catch(e){if(e instanceof RangeError)return null;throw e}}canStyleClusteredHighlights(){return!0}destroy(){this._deactivateSideBySide(),this._navObserver.disconnect(),this._metaObserver.disconnect(), this.features.off("flagsChanged",this._flagsChanged)}contentContainer(){return this.container}fitSideBySide(e){this._lastLayout=e;const t=window.innerWidth-e.width,n=this._sideBySideEnabled&&"auto"===this._sideBySideOptions.mode&&e.expanded&&t>=480;return n?this._activateSideBySide(e.width):this._sideBySideActive&&this._deactivateSideBySide(),this._sideBySideActive=n,this.container.classList.toggle("hypothesis-sidebyside-active",this._sideBySideActive),n}sideBySideActive(){return this._sideBySideActive}_activateSideBySide(e){const t=e+12,n=e=>parseInt(window.getComputedStyle(e).marginLeft,10);In((()=>{document.body.style.marginLeft="",document.body.style.marginRight="";const e=n(document.body);document.body.style.marginRight=`${t}px`;const o=function(e){const t=new Map,n=new Map,o=kn.join(","),i=Array.from(e.querySelectorAll(o)).map((e=>({rect:e.getBoundingClientRect(),textLength:e.textContent.length}))).filter((({rect:e})=>e.width>0&&e.height>0)).sort(((e,t)=>t.textLength-e.textLength)).slice(0,15) ;if(i.forEach((({rect:e})=>{let o=t.get(e.left)??0;o+=1,t.set(e.left,o);let i=n.get(e.right)??0;i+=1,n.set(e.right,i)})),0===t.size||0===n.size)return null;const r=[...t.entries()].sort(((e,t)=>t[1]-e[1])),s=[...n.entries()].sort(((e,t)=>t[1]-e[1])),[a]=r[0],[l]=s[0];return{left:a,right:l}}(document.body);if(o){const i=Math.max(0,window.innerWidth-t-o.right);if(i>0){const e=Math.max(0,t-i);document.body.style.marginRight=`${e}px`}n(document.body)>e&&(document.body.style.marginLeft=`${e}px`),o.left<12&&(document.body.style.marginLeft="12px")}else document.body.style.marginLeft="",document.body.style.marginRight=""}))}_deactivateSideBySide(){In((()=>{document.body.style.marginLeft="",document.body.style.marginRight=""}))}async getMetadata(){return this._htmlMeta.getDocumentMetadata()}async uri(){return this._htmlMeta.uri()}async scrollToAnchor(e){const t=e.highlights?.[0];t&&await async function(e,{maxDuration:t=500}={}){const n=e.closest("body");n&&"BODY"!==n.tagName&&Object.defineProperty(n,"tagName",{ value:"BODY",configurable:!0});const o=e.closest("details");o&&!o.hasAttribute("open")&&(o.open=!0),await new Promise((n=>gi(e,{time:t},n)))}(t)}}var yi,xi;var Ni=function(){if(xi)return yi;xi=1;var t=NaN,n="[object Symbol]",o=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,r=/^0b[01]+$/i,s=/^0o[0-7]+$/i,a=parseInt,l="object"==typeof e&&e&&e.Object===Object&&e,c="object"==typeof self&&self&&self.Object===Object&&self,d=l||c||Function("return this")(),u=Object.prototype.toString,h=Math.max,f=Math.min,m=function(){return d.Date.now()};function g(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function p(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&u.call(e)==n}(e))return t;if(g(e)){var l="function"==typeof e.valueOf?e.valueOf():e;e=g(l)?l+"":l}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(o,"");var c=r.test(e);return c||s.test(e)?a(e.slice(2),c?2:8):i.test(e)?t:+e}return yi=function(e,t,n){var o,i,r,s,a,l,c=0,d=!1,u=!1,_=!0 ;if("function"!=typeof e)throw new TypeError("Expected a function");function b(t){var n=o,r=i;return o=i=void 0,c=t,s=e.apply(r,n)}function v(e){var n=e-l;return void 0===l||n>=t||n<0||u&&e-c>=r}function w(){var e=m();if(v(e))return y(e);a=setTimeout(w,function(e){var n=t-(e-l);return u?f(n,r-(e-c)):n}(e))}function y(e){return a=void 0,_&&o?b(e):(o=i=void 0,s)}function x(){var e=m(),n=v(e);if(o=arguments,i=this,l=e,n){if(void 0===a)return function(e){return c=e,a=setTimeout(w,t),d?b(e):s}(l);if(u)return a=setTimeout(w,t),b(l)}return void 0===a&&(a=setTimeout(w,t)),s}return t=p(t)||0,g(n)&&(d=!!n.leading,r=(u="maxWait"in n)?h(p(n.maxWait)||0,t):r,_="trailing"in n?!!n.trailing:_),x.cancel=function(){void 0!==a&&clearTimeout(a),c=0,o=l=i=a=void 0},x.flush=function(){return void 0===a?s:y(m())},x},yi}(),Ci=t(Ni);function Si(e,t,n,o=0){let i=o;for(;i0;)n(e[i])&&--t,++i;return i}function Ei(e,t,n,o){let i=0;for(let r=n;r{const o=()=>{t.eventBus?t.eventBus.off("pagesloaded",o):document.removeEventListener("pagesloaded",o),n(t.getPageView(e))};t.eventBus?t.eventBus.on("pagesloaded",o):document.addEventListener("pagesloaded",o)}))),n}function Ii(e){const t=ki.get(e);if(t)return t;const n=(async()=>{const t=await Oi(e);return(await t.pdfPage.getTextContent({normalizeWhitespace:!0})).items.map((e=>e.str)).join("")})();return ki.set(e,n),n}async function Bi(e){const t=Li();let n=0,o=0,i="";for(let r=0;r=e)return{index:r,offset:n,text:i};return{ index:t.pagesCount-1,offset:n,text:i}}function Hi(e){switch(e){case" ":case"\f":case"\n":case"\r":case"\t":case"\v":case" ":return!0;default:return!1}}const Fi=e=>!Hi(e);function Di(e){return void 0!==e.renderingDone?e.renderingDone:!!e.div&&null!==e.div.querySelector(".endOfContent")}async function Vi(e,t,n){const[o,i]=await Promise.all([Oi(e),Ii(e)]);if(o.renderingState===Ri.FINISHED&&o.textLayer&&Di(o.textLayer)){const e=o.textLayer.textLayerDiv??o.textLayer.div;if(!e)throw new Error("Unable to find PDF.js text layer root");const r=e.textContent,[s,a]=Ai(i,r,t,n,Fi);Ui(r.slice(s,a))!==Ui(i.slice(t,n))&&Io("Text layer text does not match page text. Highlights will be mis-aligned.");const l=new co(e,s),c=new co(e,a);return new uo(l,c).toRange()}const r=function(e){let t=e.querySelector(ho);return t||(t=document.createElement("span"),t.classList.add("annotator-placeholder"),t.textContent="Loading annotations...",e.appendChild(t),t)}(o.div),s=document.createRange();return s.setStartBefore(r),s.setEndAfter(r),s }function Ui(e){let t="";for(let n=0;n"TextQuoteSelector"===e.type));if(!n)throw new Error("No quote selector found");const o=t.find((e=>"TextPositionSelector"===e.type));if(o){try{const{index:e,offset:t,text:i}=await Bi(o.start),r=o.start-t,s=o.end-t,a=i.substring(r,s);if(n.exact!==a)throw new Error("quote mismatch");return await Vi(e,r,s)}catch{}try{const e=Ti(n.exact,o.start),t=Pi.get(e);if(t){const{pageIndex:e,anchor:n}=t;return await Vi(e,n.start,n.end)}}catch{}}return async function(e,t){const n=Li().pagesCount,o=Array(n).fill(0).map(((e,t)=>t));let i,r;if(t){const{index:e,offset:n}=await Bi(t);i=e,r=t-n,o.sort(((t,n)=>Math.abs(t-e)-Math.abs(n-e)))}const s=void 0!==e.prefix?Ui(e.prefix):void 0,a=void 0!==e.suffix?Ui(e.suffix):void 0,l=Ui(e.exact);let c;for(const e of o){const t=await Ii(e),n=Ui(t);let o;void 0!==i&&void 0!==r&&(ec.match.score)){const[o,i]=Ai(n,t,d.start,d.end,Fi);c={page:e,match:{start:o,end:i,score:d.score}};const r=n.slice(d.start,d.end)===l,u=void 0!==s&&n.slice(Math.max(0,d.start-s.length),d.start)===s,h=void 0!==a&&n.slice(d.end,a.length)===a;if(r&&(u||h||void 0===s&&void 0===a))break}}if(c){const{page:n,match:o}=c;if(t){const i=Ti(e.exact,t);Pi.set(i,{pageIndex:n,anchor:o})}return Vi(n,o.start,o.end)}throw new Error("Quote not found")}(n,o?.start)}function $i(e){try{e=uo.fromRange(e).toRange()}catch{throw new Error("Selection does not contain text")}const t=Mi(e.startContainer),n=Mi(e.endContainer);if(!t||!n)throw new Error("Selection is outside page text");if(t!==n)throw new Error("Selecting across page breaks is not supported");return[e,t]}async function zi(e,t){const[n,o]=$i(t),i=co.fromPoint(n.startContainer,n.startOffset).relativeTo(o),r=co.fromPoint(n.endContainer,n.endOffset).relativeTo(o),s=function(e){let t=0;for(;e.previousSibling;)++t,e=e.previousSibling;return t }(o.parentNode),a=s+1,l=await async function(e){if(e>=Li().pagesCount)throw new Error("Invalid page index");let t=0;for(let n=0;n{const n=setInterval((()=>{e.initialized&&(clearTimeout(n),t())}),5)}))}(e).then((async()=>{const t=await async function(e){return void 0!==e.downloadComplete?e.downloadComplete:(await e.pdfDocument.getDownloadInfo(),!0)}(e);return t?e:new Promise((t=>{const n=()=>{e.eventBus?(e.eventBus.off("documentload",n),e.eventBus.off("documentloaded",n)):window.removeEventListener("documentload",n),t(e)};e.eventBus?(e.eventBus.on("documentloaded",n),e.eventBus.on("documentload",n)):window.addEventListener("documentload",n)}))}))}getUri(){return this._loaded.then((e=>{let t=Qi(e);return t||(t=Yi(Gi(e))),t}))}async getMetadata(){const e=await this._loaded,{info:t,contentDispositionFilename:n,metadata:o}=await e.pdfDocument.getMetadata(),i=Gi(e),r=Qi(e);let s;s=o?.has("dc:title")&&"Untitled"!==o.get("dc:title")?o.get("dc:title"):t?.Title?t.Title:n||(r?function(e){const t=new URL(e),n=t.pathname.split("/");return n[n.length-1] }(r):"");const a=[{href:Yi(i)}];return r&&a.push({href:r}),{title:s,link:a,documentFingerprint:i}}}function Gi(e){return Array.isArray(e.pdfDocument.fingerprints)?e.pdfDocument.fingerprints[0]:e.pdfDocument.fingerprint}function Yi(e){return`urn:x-pdf:${e}`}function Qi(e){if(!e.url)return null;const t=bi(e.url);return 0!==t.indexOf("file://")?t:null}function Ji(e){const t=e.highlights?.[0];return t&&fo(t)}function Zi(e){return new Promise((t=>setTimeout(t,e)))}class er{constructor(){this._pdfjsContainer=document.querySelector("#outerContainer"),this._contentInfo=null,this._noTextWarning=!1,this._container=null}setContentInfo(e){this._contentInfo=e,this._update()}showNoTextWarning(e){this._noTextWarning=e,this._update()}destroy(){this._container?.destroy()}_update(){if(!(this._noTextWarning||this._contentInfo))return this._container?.destroy(),this._container=null,void(this._pdfjsContainer.style.height="");this._container||(this._container=new Jn("banner",(()=>this._render())), document.body.prepend(this._container.element)),this._container.render();const e=this._container.element.getBoundingClientRect().height;this._pdfjsContainer.style.height=`calc(100% - ${e}px)`}_render(){return Pe(Wi,{children:[this._contentInfo&&Pe(ji,{info:this._contentInfo}),this._noTextWarning&&Pe(Xi,{})]})}}class tr extends rn.TinyEmitter{constructor(e,t={}){super(),this._annotator=e;const n=window,o=n.PDFViewerApplication;this._pdfViewer=o.pdfViewer,this._pdfViewer.viewer.classList.add("has-transparent-text-layer"),this._pdfContainer=o.appConfig?.appContainer??document.body,this._pdfMetadata=new Ki(o),this._observer=new MutationObserver(Ci((()=>this._update()),100)),this._observer.observe(this._pdfViewer.viewer,{attributes:!0,attributeFilter:["data-loaded"],childList:!0,subtree:!0}),this._reanchoringMaxWait=t.reanchoringMaxWait??3e3,this._banner=new er,this._checkForSelectableText(),this._sideBySideActive=!1,this._updateAnnotationLayerVisibility=()=>{const e=n.getSelection() ;this._pdfViewer.viewer.classList.toggle("is-selecting",!e.isCollapsed)},this._listeners=new be,this._listeners.add(document,"selectionchange",this._updateAnnotationLayerVisibility),this._destroyed=!1}destroy(){this.fitSideBySide({expanded:!1,width:0,toolbarWidth:0,height:window.innerHeight}),this._listeners.removeAll(),this._pdfViewer.viewer.classList.remove("has-transparent-text-layer"),this._observer.disconnect(),this._banner.destroy(),this._destroyed=!0}uri(){return this._pdfMetadata.getUri()}getMetadata(){return this._pdfMetadata.getMetadata()}showContentInfo(e){this._banner.setContentInfo(e)}anchor(e,t){return qi(0,t)}getAnnotatableRange(e){try{const t=uo.trimmedRange(e);if(function(e){try{return $i(e),!0}catch{return!1}}(t))return t}catch(e){if(!(e instanceof RangeError))throw e}return null}canStyleClusteredHighlights(){return!0}describe(e,t){return zi(e,t)}async _checkForSelectableText(){try{await this.uri()}catch{return}if(!this._destroyed)try{const e=await async function(){const e=Li();let t=!1 ;for(let n=0;n0){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;ethis._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}async scrollToAnchor(e){const t=e.annotation,n=Ji(e),o=this._anchorOffset(e);if(null!==o&&(await _i(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 _i(this.contentContainer(),n)}}async _waitForAnnotationToBeAnchored(e,t){const n=Date.now();let o;do{o=this._annotator.anchors.find((t=>t.annotation===e)),o&&!Ji(o)||(o=null,await Zi(20))}while(!o&&Date.now()-n{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 rr(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 rr(e){return new Promise(((t,n)=>{const o=sr(e,((e,i)=>{o(),i?t(i):n(e)}))}))}function sr(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)){"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 ar{constructor(e,t){this._config=t, this._frameObserver=new ir(e,(e=>lr(e,t)),(()=>{}))}destroy(){this._frameObserver.disconnect()}}async function lr(e,t,n){if(null!==e.contentDocument.querySelector("script.js-hypothesis-config"))return;await rr(e);const{assetRoot:o,notebookAppUrl:i,profileAppUrl:r,sidebarAppUrl:s}=bn(document),a={...t,assetRoot:o,notebookAppUrl:i,profileAppUrl:r,sidebarAppUrl:s,subFrameIdentifier:n??Jt(10)},l=document.createElement("script");l.className="js-hypothesis-config",l.setAttribute("data-remove-on-unload",""),l.type="application/json",l.innerText=JSON.stringify(a);const c=document.createElement("script");c.async=!0,c.src=t.clientUrl;const d=e.contentDocument;d.body.appendChild(l),d.body.appendChild(c)}class cr{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&&!Nn(o.rect,r)&&i(),o.rect=Sn(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;(!Nn(t.rect,e.rect)||o<0)&&a()}s.words.push(e),s.rect=Sn(s.rect,e.rect)}a();const l=[];let c={lines:[],rect:new DOMRect};const d=()=>{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;(!Cn(t.rect,e.rect)||Nn(t.rect,e.rect)||o<0||o>4*e.rect.height)&&d()}c.lines.push(e),c.rect=Sn(c.rect,e.rect)}return d(),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),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=Ci(c,{maxWait:50}),this._listeners=new be,"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 dr(e=document){return e.querySelector("mosaic-book")}function ur(e=window){if(dr(e.document))return"container" ;const t=e.frameElement?.ownerDocument;return t&&dr(t)?"content":null}class hr{constructor(e){const t=dr();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),sr(t,((n,o)=>{if(n)return;const i=o.body;i&&!i.querySelector("#page-content")&&lr(t,e,"vitalsource-content")})))};i(),this._frameObserver=new MutationObserver(i),this._frameObserver.observe(o,{childList:!0,subtree:!0})}destroy(){this._frameObserver.disconnect()}}function fr(){return document.querySelector("img#pbk-page")}class mr extends rn.TinyEmitter{constructor(e=document.body,t={}){super();const n=t.bookElement??dr(window.parent.document);if(!n)throw new Error("Failed to find element in container frame");this._bookElement=n;const o=new Ho;this._htmlIntegration=new wi({container:e,features:o}),this._listeners=new be;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=fr(),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 cr(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()}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=fr();if(t&&this._textLayer){const n=t.parentElement,o=this._textLayer,i=window.innerWidth-e.width;return this._sideBySideActive=!1,In((()=>{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()}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"];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=or(n.cfi),t=o.data?.find((t=>or(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=nr(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){return this._htmlIntegration.scrollToAnchor(e)}}function gr(e){if(void 0!==window.PDFViewerApplication)return new tr(e);return"content"===ur()?new mr(document.body):new wi({features:e.features,sideBySideOptions:e.sideBySide})}function pr(){return Pe(qt,{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 _r{constructor(e){this._visible=!1,this._container=new Jn("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(pr,{}):null}}class br{constructor(e,t=document){let n=!1;this._pendingCallback=null;const o=(n=10)=>{this._pendingCallback=setTimeout((()=>{e(go(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 be,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 vr(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 wr(){return function(e,t){const n=new Set,o=new Set;return bo(e,(e=>{for(;e&&!n.has(e);){n.add(e);const i=t(e);null!=i&&o.add(i),e=e.parentNode}})),[...o]}(go()??new Range,(e=>e._annotation?.$tag))}function yr(e){const t=function(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;const n=[];for(;t;)t.classList.contains("hypothesis-highlight")&&n.push(t),t=t.parentElement;return n}(e).map((e=>e._annotation)).filter((e=>void 0!==e)).map((e=>e?.$tag));return t}function xr(e){if(!e.range)return null;try{return e.range.toRange()}catch{return null}}function Nr(){document.getSelection()?.removeAllRanges()}class Cr 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 Sr extends rn.TinyEmitter{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._adder=new to(this.element,{onAnnotate:()=>this.createAnnotation(),onHighlight:()=>this.createAnnotation({highlight:!0}),onShowAnnotations:e=>this.selectAnnotations(e,{focusInSidebar:!0})}),this._selectionObserver=new br((e=>{e?this._onSelection(e):this._onClearSelection()})),this.anchors=[],this._annotations=new Set,this._frameIdentifier=t.subFrameIdentifier||null,this._portFinder=new tn({hostFrame:this._hostFrame,source:"guest",sourceId:this._frameIdentifier??void 0}),this.features=new Ho,this._featureFlagsReceived=new Promise((e=>{this.features.on("flagsChanged",e)})),this.sideBySide=t.sideBySide,this._integration=gr(this),this._integration.on("uriChanged",(()=>this._sendDocumentInfo())),t.contentInfoBanner&&this._integration.showContentInfo?.(t.contentInfoBanner), this._integration.canStyleClusteredHighlights?.()&&(this._clusterToolbar=new qo(this._integration.contentContainer(),{features:this.features})),this._hostRPC=new pn,this._connectHost(n),this._sidebarRPC=new pn,this._sidebarLayout=null,this._connectSidebar(),this._bucketBarClient=new Mo({contentContainer:this._integration.contentContainer(),hostRPC:this._hostRPC}),this._listeners=new be,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=>{const{target:t,metaKey:n,ctrlKey:o}=e,i=yr(t);if(i.length&&this._highlightsVisible){const e=n||o;this.selectAnnotations(i,{toggle:e})}})),this._listeners.add(this.element,"pointerdown",(e=>{ this._sideBySideActive()||e.composedPath().some((e=>e instanceof Element&&e.localName.startsWith("hypothesis-")))||yr(e.target).length||vr(window,this._hostFrame)&&this._sidebarLayout?.expanded&&window.innerWidth-e.clientX{const t=yr(e);t.length&&this._highlightsVisible&&this._sidebarRPC.call("hoverAnnotations",t)})),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:bi(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=go();e&&this._onSelection(e)}async _connectHost(e){this._hostRPC.on("clearSelection",(()=>{go()&&(this._informHostOnNextSelectionClear=!1,Nr())})),this._hostRPC.on("createAnnotation",(()=>this.createAnnotation())),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=>{vr(window,e)&&this.fitSideBySide(t),this.element.dispatchEvent(new Lo({sidebarLayout:t,sideBySideActive:this._sideBySideActive()}))})),this._hostRPC.on("close",(()=>this.emit("hostDisconnected")));const t=await this._portFinder.discover("host");this._hostRPC.connect(t)}async _scrollToAnchor(e){const t=xr(e) ;if(!t)return;const n=new Cr(t);this.element.dispatchEvent(n)&&(await n.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)})), this._sidebarRPC.on("navigateToSegment",(e=>this._integration.navigateToSegment?.(e))),this._portFinder.discover("sidebar").then((e=>{this._sidebarRPC.connect(e)})),this._sendDocumentInfo()}destroy(){var e;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(),e=this.element,Co(Array.from(e.querySelectorAll("hypothesis-highlight"))),this._integration.destroy()}async anchor(e){this._contentReady&&(await this._contentReady,this._contentReady=void 0);const t=e=>{const t=xr(e);if(!t)return;const n=xo(t,e.annotation?.$cluster);n.forEach((t=>{t._annotation=e.annotation})),e.highlights=n,this._hoveredAnnotations.has(e.annotation.$tag)&&So(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)))return{annotation:e,target:t};let n;try{const o=await this._integration.anchor(this.element,t.selector),i=uo.fromRange(o);n={annotation:e,target:t,range:i}}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.range)),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&&Co(t.highlights);this._updateAnchors(n,t)}_updateAnchors(e,t){this.anchors=e,this._clusterToolbar?.scheduleClusterUpdates(),t&&this._bucketBarClient.update(this.anchors)}async createAnnotation({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:"+Jt(8)};return this._sidebarRPC.call("createAnnotation",r),this.anchor(r),Nr(),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);So(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=po(n),i=vo(n);i?(this.selectedRanges=[t],this._hostRPC.call("textSelected"),this._adder.annotationsForSelection=wr(),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){!function(e,t){e.classList.toggle("hypothesis-highlights-always-on",t)}(this.element,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){$n(e,"Ctrl+Shift+H")&&this.setHighlightsVisible(!this._highlightsVisible)}_setOutsideAssignmentNoticeVisible(e){this._outsideAssignmentNotice||(this._outsideAssignmentNotice=new _r(this.element)),this._outsideAssignmentNotice.setVisible(e)}}function Er(e,t){const n=new URL(e),o=new URLSearchParams;return o.append("config",JSON.stringify(t)),n.hash=o.toString(),n.toString()}function Ar(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.1574.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 Rr({closed:e,onClose:t,children:n,"data-testid":o,"aria-label":i}){const r=re(null);return oe((()=>{e?r.current?.close():r.current?.showModal()}),[e]),oe((()=>{const e=r.current;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 kr({closed:e,children:t,...n}){return Pe("div",{...n, className:Re("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 Pr({document_:e=document,...t}){return Pe(se((()=>function(e){return"function"==typeof e.createElement("dialog").showModal}(e)?Rr:kr),[e]),{...t})}function Tr({config:e,groupId:t}){return Pe("iframe",{title:"Hypothesis annotation notebook",className:"h-full w-full border-0",allow:"fullscreen; clipboard-write",src:Er(e.notebookAppUrl,{...Ar(e.notebookAppUrl,e),group:t})})}function Mr({eventBus:e,config:t}){const[n,o]=ne(0),[i,r]=ne(!0),[s,a]=ne(null),l=re(""),c=re(null);oe((()=>(l.current=document.body.style.overflow,()=>{document.body.style.overflow=l.current})),[]),oe((()=>{document.body.style.overflow=i?l.current:"hidden"}),[i]),oe((()=>{const t=e.createEmitter();return t.subscribe("openNotebook",(e=>{r(!1),o((e=>e+1)),a(e)})),c.current=t,()=>{t.destroy()}}),[e]);const d=ae((()=>{r(!0),c.current?.publish("closeNotebook")}),[]) ;return null===s?null:Pe(Pr,{closed:i,onClose:d,"data-testid":"notebook-outer","aria-label":"Hypothesis notebook",children:[Pe("div",{className:"absolute right-0 m-3",children:Pe(Nt,{title:"Close notebook",onClick:d,variant:"dark",classes:Re("!bg-transparent enabled:hover:!bg-grey-3"),"data-testid":"close-button",children:Pe(Fe,{className:"w-4 h-4"})})}),Pe(Tr,{config:t,groupId:s},n)]})}class Lr{constructor(e,t,n){this._container=new Jn("notebook",(()=>Pe(Mr,{eventBus:t,config:n}))),e.append(this._container.element),this._container.render()}destroy(){this._container.destroy()}}function Or({eventBus:e,config:t}){const[n,o]=ne(!0),i=re(null);oe((()=>{const t=e.createEmitter();return t.subscribe("openProfile",(()=>{o(!1)})),i.current=t,()=>{t.destroy()}}),[e]);const r=()=>{o(!0),i.current?.publish("closeProfile")};return n?null:Pe(Pr,{closed:n,onClose:r,"data-testid":"profile-outer","aria-label":"Hypothesis profile",children:[Pe("div",{className:"absolute right-0 m-3",children:Pe(Nt,{ title:"Close profile dialog",onClick:r,variant:"dark",classes:Re("!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 Ir{constructor(e,t,n){this._container=new Jn("profile",(()=>Pe(Or,{eventBus:t,config:n}))),e.append(this._container.element),this._container.render()}destroy(){this._container.destroy()}}function Br({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(Yt,{"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(Yt,{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(Yt,{"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})})]})}class Hr{constructor(e,{onFocusAnnotations:t,onScrollToAnnotation:n,onSelectAnnotations:o}){this._positions=[],this._container=new Jn("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.bottom60&&!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:30},below:{anchors:o,position:a.height-30},buckets:i} }(this._positions,this._container.element);return Pe(Br,{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 Fr({emitter:e}){const[t,n]=ne([]),o=ae((e=>n((t=>[...t,e]))),[]),i=ae((e=>n((t=>t.filter((t=>t.id!==e))))),[]);return oe((()=>(e.subscribe("toastMessageAdded",o),e.subscribe("toastMessageDismissed",i),()=>{e.unsubscribe("toastMessageAdded",o),e.unsubscribe("toastMessageDismissed",i)})),[e,i,o]),Pe(jt,{messages:t,onMessageDismiss:i})}function Dr({icon:e,...t}){return Pe(wt,{classes:Re("justify-center rounded","w-[30px] h-[30px]","shadow border bg-white text-grey-6 hover:text-grey-9"),...t,size:"custom",variant:"custom",children:Pe(e,{})})}function Vr({highlightsVisible:e}){return Pe("div",{className:"sr-only",role:"status","data-testid":"toolbar-status",children:e?"Highlights visible":"Highlights hidden"})} function Ur({closeSidebar:e,createAnnotation:t,isSidebarOpen:n,sidebarContainerId:o,newAnnotationType:i,showHighlights:r,toggleHighlights:s,toggleSidebar:a,toggleSidebarRef:l,useMinimalControls:c=!1}){return Pe("div",{className:Re("absolute left-[-33px] w-[33px] z-2","text-px-base leading-none"),children:[c&&n&&Pe(wt,{classes:Re("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:e,unstyled:!0,children:Pe(Fe,{})}),!c&&Pe(x,{children:[Pe(wt,{classes:Re("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:l,title:"Annotation sidebar",expanded:n,"aria-controls":o,onClick:a,unstyled:!0,children:Pe(n?ze:qe,{})}),Pe("div",{className:"space-y-px-1.5 mt-px-2",children:[Pe(Dr,{title:"Show highlights", icon:r?bt:et,pressed:r,onClick:s}),Pe(Dr,{title:"note"===i?"New page note":"New annotation",icon:"note"===i?lt:Be,onClick:t})]}),Pe(Vr,{highlightsVisible:r})]})]})}class qr{constructor(e,t){const{createAnnotation:n,setSidebarOpen:o,setHighlightsVisible:i}=t;this._container=e,this._useMinimalControls=!1,this._newAnnotationType="note",this._highlightsVisible=!1,this._sidebarOpen=!1,this._sidebarContainerId=t.sidebarContainerId,this._closeSidebar=()=>o(!1),this._toggleSidebar=()=>o(!this._sidebarOpen),this._toggleHighlights=()=>i(!this._highlightsVisible),this._createAnnotation=()=>{n(),o(!0)},this._sidebarToggleButton={current:null},this.render()}getWidth(){return this._container.firstChild.getBoundingClientRect().width}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(){return this._newAnnotationType}set highlightsVisible(e){this._highlightsVisible=e,this.render()}get highlightsVisible(){return this._highlightsVisible}get sidebarToggleButton(){return this._sidebarToggleButton.current}render(){V(Pe(Ur,{closeSidebar:this._closeSidebar,createAnnotation:this._createAnnotation,newAnnotationType:this._newAnnotationType,isSidebarOpen:this._sidebarOpen,sidebarContainerId:this._sidebarContainerId,showHighlights:this._highlightsVisible,toggleHighlights:this._toggleHighlights,toggleSidebar:this._toggleSidebar,toggleSidebarRef:this._sidebarToggleButton,useMinimalControls:this.useMinimalControls}),this._container)}}class $r{constructor({target:e,threshold:t=10,onDrag:n}){e.style.touchAction="none",this._listeners=new be,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 zr{constructor(e,t,n){if(this._emitter=t.createEmitter(),this._guestWithSelection=null,this._guestRPC=[],this._sidebarRPC=new pn,this.iframe=function(e){const t=e.sidebarAppUrl,n=Er(t,Ar(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,this.features=new Ho,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="sidebar-container","clean"===n.theme)this.iframeContainer.classList.add("theme-clean");else{let e;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=Re("absolute top-0 bottom-0 w-[23px] left-[-22px]","flex flex-col pt-[110px] pr-[5px]","bg-grey-2 sidebar-collapsed:bg-black/[.08]","pointer-events-none"),this.iframeContainer.append(t),e||(e=t),this.bucketBar=new Hr(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=Qn(this._hypothesisSidebar);t.appendChild(this.iframeContainer),e.appendChild(this._hypothesisSidebar),this._messagesElement=document.createElement("div"),t.appendChild(this._messagesElement),V(Pe(Fr,{emitter:this._emitter}),this._messagesElement)}this.iframe.contentWindow&&cn(this.iframe.contentWindow),this._listeners=new be;const o=document.createElement("div");this.toolbar=new qr(o,{sidebarContainerId:this.iframeContainer?.id,createAnnotation:()=>{if(0===this._guestRPC.length)return;(this._guestWithSelection??this._guestRPC[0]).call("createAnnotation")},setSidebarOpen:e=>e?this.open():this.close(),setHighlightsVisible:e=>this.setHighlightsVisible(e)}),"clean"===n.theme?this.toolbar.useMinimalControls=!0:this.toolbar.useMinimalControls=!1,this.iframeContainer?(this.iframeContainer.prepend(o),this._toolbarWidth=this.toolbar.getWidth()):this._toolbarWidth=0, this._listeners.add(window,"resize",(()=>this._onResize())),this._dragResizeState={initial:null,final:null};const i=this.toolbar.sidebarToggleButton;i&&(this._dragResizeHandler=new $r({target:i,onDrag:e=>this._onDragSidebarToggleButton(e)})),this.close();const[r]=n.services||[];r&&(this.onLoginRequest=r.onLoginRequest,this.onLogoutRequest=r.onLogoutRequest,this.onSignupRequest=r.onSignupRequest,this.onProfileRequest=r.onProfileRequest,this.onHelpRequest=r.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(),this._hypothesisSidebar?(V(null,this._messagesElement),this._hypothesisSidebar.remove()):this.iframe.remove(),this._emitter.destroy(),cn(null)}onFrameConnected(e,t){switch(e){case"guest":this._connectGuest(t);break ;case"sidebar":this._sidebarRPC.connect(t)}}_connectGuest(e){const t=new pn;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("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))})),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))),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(){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}_onDragSidebarToggleButton(e){const t=this.iframeContainer;if(t)switch(e.type){case"dragstart":this._resetDragResizeState(),t.classList.add("sidebar-no-transition"),t.style.pointerEvents="none",this._dragResizeState.initial=parseInt(getComputedStyle(t).marginLeft);break;case"dragend":t.classList.remove("sidebar-no-transition"),t.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,"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 Wr{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 jr{constructor(){this._emitter=new rn.TinyEmitter}createEmitter(){return new Wr(this._emitter)}}const Xr=document.querySelector('link[type="application/annotator+html"][rel="sidebar"]');new Promise((e=>{"loading"!==document.readyState&&e(),document.addEventListener("readystatechange",(()=>e()))})).then((function(){const e=Un("annotator");let t=()=>{};const n=new Promise((e=>{t=e})) ;Xr.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(!gn(e))return()=>{};const t=e=>{if("hypothesisPortClosed"===e.data?.type&&e.ports[0]){const t=e.ports[0];mn(t,"close"),t.close()}};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}();i.push({destroy:e});const t=Un("sidebar"),n=new URL(t.sidebarAppUrl).origin,o=new dn(n),r=new jr,s=new zr(document.body,r,t),a=new Lr(document.body,r,Un("notebook")),l=new Ir(document.body,r,Un("profile"));o.on("frameConnected",((e,t)=>s.onFrameConnected(e,t))),i.push(o,s,a,l)}if("container"===ur()){const t=new hr(e);i.push(t)}else{ const n=new ar(document.body,e),r=new Sr(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()))}()}))}))}(); //# sourceMappingURL=annotator.bundle.js.map