@recogito/text-annotator 3.0.0-rc.1 → 3.0.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- (function(O,k){typeof exports=="object"&&typeof module<"u"?k(exports):typeof define=="function"&&define.amd?define(["exports"],k):(O=typeof globalThis<"u"?globalThis:O||self,k(O.RecogitoJS={}))})(this,function(O){"use strict";const k={fill:"rgb(0, 128, 255",fillOpacity:.18},ft={fill:"rgb(0, 128, 255)",fillOpacity:.45},j={paint:(t,e,n,o,i,s)=>{const a=s?typeof s=="function"?s(t,i):s:i?ft:k;n.fillStyle=a.fill,n.globalAlpha=a.fillOpacity||1,e.forEach(({x:r,y:l,width:h,height:g})=>n.fillRect(r,l-2.5,h,g+5))}},gt=t=>{let e=new Set;return o=>{const i=o.map(s=>s.id);(e.size!==i.length||i.some(s=>!e.has(s)))&&t.set(i),e=new Set(i)}},he="",pt=(t,e=10)=>{let n;return(...o)=>{clearTimeout(n),n=setTimeout(()=>t.apply(void 0,o),e)}},et=(t,e)=>{const n=document.createElement("canvas");if(n.width=e?2*window.innerWidth:window.innerWidth,n.height=e?2*window.innerHeight:window.innerHeight,n.className=t,e){const o=n.getContext("2d");o.scale(2,2),o.translate(.5,.5)}return n},nt=(t,e)=>{if(t.width=e?2*window.innerWidth:window.innerWidth,t.height=e?2*window.innerHeight:window.innerHeight,e){const n=t.getContext("2d");n.scale(2,2),n.translate(.5,.5)}},ot=(t,e,n)=>{const{store:o,selection:i,hover:s}=e;let a,r=j;const l=gt(n);t.classList.add("r6o-annotatable");const h=et("r6o-highlight-layer bg"),g=et("r6o-highlight-layer fg",!0),d=h.getContext("2d"),p=g.getContext("2d");t.insertBefore(h,t.firstChild),t.appendChild(g),t.addEventListener("pointermove",m=>{const{x:T,y:b}=t.getBoundingClientRect(),C=o.getAt(m.clientX-T,m.clientY-b);C?s.current!==C.id&&(t.classList.add("hovered"),s.set(C.id)):s.current&&(t.classList.remove("hovered"),s.set(null))});const B=()=>{const{top:m,left:T}=t.getBoundingClientRect(),{innerWidth:b,innerHeight:C}=window,L=-T,f=-m,y=b-T,E=C-m;return{top:m,left:T,minX:L,minY:f,maxX:y,maxY:E}},A=()=>u();document.addEventListener("scroll",A,{capture:!0,passive:!0});const w=pt(()=>{nt(h),nt(g,!0),o.recalculatePositions(),u()});window.addEventListener("resize",w),new ResizeObserver(w).observe(t);const u=()=>requestAnimationFrame(()=>{const{top:m,left:T,minX:b,minY:C,maxX:L,maxY:f}=B(),y=o.getIntersectingRects(b,C,L,f),{width:E,height:v}=g,M=new Set(i.selected.map(({id:R})=>R));p.clearRect(-.5,-.5,E+1,v+1),d.clearRect(-.5,-.5,E+1,v+1),y.forEach(({annotation:R,rects:Y})=>{const tt=Y.map(({x:ae,y:ce,width:le,height:de})=>({x:ae+T,y:ce+m,width:le,height:de})),W=M.has(R.id);r.paint(R,tt,d,p,W,a)}),setTimeout(()=>l(y.map(({annotation:R})=>R)),1)});return o.observe(()=>u()),i.subscribe(()=>u()),{redraw:u,setDrawingStyle:m=>{a=m,u()},setPainter:m=>r=m}},I=(t,e)=>{const{quote:n,start:o,end:i}=t.selector,s=t.selector.offsetReference?t.selector.offsetReference:e;if(!s)return t;const a=document.createNodeIterator(e,NodeFilter.SHOW_TEXT);let r=0,l=document.createRange(),h=a.nextNode();h===null&&console.error("Could not revive annotation target. Content missing.");let g=!s;for(;h!==null;){const d=h.textContent.length;if(!g&&s&&(g=s.contains(h)),g){if(r+d>o){l.setStart(h,o-r);break}r+=d}h=a.nextNode()}for(;h!==null;){const d=h.textContent.length;if(r+d>i){l.setEnd(h,i-r);break}r+=d,h=a.nextNode()}return{...t,selector:{...t.selector,quote:n,start:o,end:i,range:l}}};var it=Object.prototype.hasOwnProperty;function _(t,e){var n,o;if(t===e)return!0;if(t&&e&&(n=t.constructor)===e.constructor){if(n===Date)return t.getTime()===e.getTime();if(n===RegExp)return t.toString()===e.toString();if(n===Array){if((o=t.length)===e.length)for(;o--&&_(t[o],e[o]););return o===-1}if(!n||typeof t=="object"){o=0;for(n in t)if(it.call(t,n)&&++o&&!it.call(e,n)||!(n in e)||!_(t[n],e[n]))return!1;return Object.keys(e).length===o}}return t!==t&&e!==e}function G(){}function mt(t,e){return t!=t?e==e:t!==e||t&&typeof t=="object"||typeof t=="function"}const D=[];function J(t,e=G){let n;const o=new Set;function i(r){if(mt(t,r)&&(t=r,n)){const l=!D.length;for(const h of o)h[1](),D.push(h,t);if(l){for(let h=0;h<D.length;h+=2)D[h][0](D[h+1]);D.length=0}}}function s(r){i(r(t))}function a(r,l=G){const h=[r,l];return o.add(h),o.size===1&&(n=e(i,s)||G),r(t),()=>{o.delete(h),o.size===0&&n&&(n(),n=null)}}return{set:i,update:s,subscribe:a}}const At=t=>{const{subscribe:e,set:n}=J(null);let o=null;return e(i=>o=i),t.observe(({changes:i})=>{if(o){i.deleted.some(r=>r.id===o)&&n(null);const a=i.updated.find(({oldValue:r})=>r.id===o);a&&n(a.newValue.id)}}),{get current(){return o},subscribe:e,set:n}},K={selected:[]},xt=(t,e="EDIT")=>{const{subscribe:n,set:o}=J(K);let i=K;n(d=>i=d);const s=()=>o(K),a=()=>{var d;return((d=i.selected)==null?void 0:d.length)===0},r=d=>{if(i.selected.length===0)return!1;const p=typeof d=="string"?d:d.id;return i.selected.some(B=>B.id===p)},l=(d,p)=>{const B=t.getAnnotation(d);if(B){const A=yt(B,e);o(A==="EDIT"?{selected:[{id:d,editable:!0}],pointerEvent:p}:A==="SELECT"?{selected:[{id:d}],pointerEvent:p}:{selected:[],pointerEvent:p})}else console.warn("Invalid selection: "+d)},h=(d,p=!0)=>{const B=Array.isArray(d)?d:[d],A=B.map(w=>t.getAnnotation(w)).filter(w=>w);o({selected:A.map(({id:w})=>({id:w,editable:p}))}),A.length!==B.length&&console.warn("Invalid selection",d)},g=d=>{if(i.selected.length===0)return!1;const{selected:p}=i;p.filter(({id:A})=>d.includes(A)).length>0&&o({selected:p.filter(({id:A})=>!d.includes(A))})};return t.observe(({changes:d})=>g(d.deleted.map(p=>p.id))),{clear:s,clickSelect:l,get selected(){return i?[...i.selected]:null},get pointerEvent(){return i?i.pointerEvent:null},isEmpty:a,isSelected:r,setSelected:h,subscribe:n}},yt=(t,e)=>typeof e=="function"?e(t)||"EDIT":e||"EDIT";let $;const Et=new Uint8Array(16);function wt(){if(!$&&($=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!$))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return $(Et)}const X=[];for(let t=0;t<256;++t)X.push((t+256).toString(16).slice(1));function bt(t,e=0){return X[t[e+0]]+X[t[e+1]]+X[t[e+2]]+X[t[e+3]]+"-"+X[t[e+4]]+X[t[e+5]]+"-"+X[t[e+6]]+X[t[e+7]]+"-"+X[t[e+8]]+X[t[e+9]]+"-"+X[t[e+10]]+X[t[e+11]]+X[t[e+12]]+X[t[e+13]]+X[t[e+14]]+X[t[e+15]]}const st={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Tt(t,e,n){if(st.randomUUID&&!e&&!t)return st.randomUUID();t=t||{};const o=t.random||(t.rng||wt)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){n=n||0;for(let i=0;i<16;++i)e[n+i]=o[i];return e}return bt(o)}const vt=(t,e)=>{const n=new Set(t.bodies.map(o=>o.id));return e.bodies.filter(o=>!n.has(o.id))},Ct=(t,e)=>{const n=new Set(e.bodies.map(o=>o.id));return t.bodies.filter(o=>!n.has(o.id))},Bt=(t,e)=>e.bodies.map(n=>{const o=t.bodies.find(i=>i.id===n.id);return{newBody:n,oldBody:o&&!_(o,n)?o:void 0}}).filter(({oldBody:n})=>n),Mt=(t,e)=>!_(t.target,e.target),St=(t,e)=>({oldValue:t,newValue:e,bodiesCreated:vt(t,e),bodiesDeleted:Ct(t,e),bodiesUpdated:Bt(t,e),targetUpdated:Mt(t,e)?{oldTarget:t.target,newTarget:e.target}:void 0});var S=(t=>(t.LOCAL="LOCAL",t.REMOTE="REMOTE",t))(S||{});const Rt=(t,e)=>{var s,a;const{changes:n,origin:o}=e;if(!(!t.options.origin||t.options.origin===o))return!1;if(t.options.ignore){const{ignore:r}=t.options,l=g=>(g==null?void 0:g.length)>0;if(!(l(n.created)||l(n.deleted))){const g=(s=n.updated)==null?void 0:s.some(p=>l(p.bodiesCreated)||l(p.bodiesDeleted)||l(p.bodiesUpdated)),d=(a=n.updated)==null?void 0:a.some(p=>p.targetUpdated);if(r==="BODY_ONLY"&&g&&!d||r==="TARGET_ONLY"&&d&&!g)return!1}}if(t.options.annotations){const r=new Set([...n.created.map(h=>h.id),...n.deleted.map(h=>h.id),...n.updated.map(({oldValue:h})=>h.id)]);return!!(Array.isArray(t.options.annotations)?t.options.annotations:[t.options.annotations]).find(h=>r.has(h))}else return!0},Lt=t=>t.id!==void 0,Ot=()=>{const t=new Map,e=new Map,n=[],o=(f,y={})=>n.push({onChange:f,options:y}),i=f=>{const y=n.findIndex(E=>E.onChange==f);y>-1&&n.splice(y,1)},s=(f,y)=>{const E={origin:f,changes:{created:y.created||[],updated:y.updated||[],deleted:y.deleted||[]},state:[...t.values()]};n.forEach(v=>{Rt(v,E)&&v.onChange(E)})},a=(f,y=S.LOCAL)=>{if(t.get(f.id))throw Error(`Cannot add annotation ${f.id} - exists already`);t.set(f.id,f),f.bodies.forEach(v=>e.set(v.id,f.id)),s(y,{created:[f]})},r=(f,y=S.LOCAL,E=S.LOCAL)=>{const v=Lt(y)?E:y,M=typeof f=="string"?y:f,R=typeof f=="string"?f:f.id,Y=t.get(R);if(Y){const tt=St(Y,M);R===M.id?t.set(R,M):(t.delete(R),t.set(M.id,M)),Y.bodies.forEach(W=>e.delete(W.id)),M.bodies.forEach(W=>e.set(W.id,M.id)),s(v,{updated:[tt]})}else throw Error(`Cannot update annotation ${R} - does not exist`)},l=(f,y=S.LOCAL)=>{const E=t.get(f.annotation);if(E){const v={...E,bodies:[...E.bodies,f]};t.set(E.id,v),e.set(f.id,v.id),s(y,{updated:[{oldValue:E,newValue:v,bodiesCreated:[f]}]})}else console.warn(`Attempt to add body to missing annotation: ${f.annotation}`)},h=()=>[...t.values()],g=(f=S.LOCAL)=>{const y=[...t.values()];t.clear(),e.clear(),s(f,{deleted:y})},d=(f,y=!0,E=S.LOCAL)=>{if(y){const v=[...t.values()];t.clear(),e.clear(),f.forEach(M=>{t.set(M.id,M),M.bodies.forEach(R=>e.set(R.id,M.id))}),s(E,{created:f,deleted:v})}else{const v=f.reduce((M,R)=>{const Y=t.get(R.id);return Y?[...M,Y]:M},[]);if(v.length>0)throw Error(`Bulk insert would overwrite the following annotations: ${v.map(M=>M.id).join(", ")}`);f.forEach(M=>{t.set(M.id,M),M.bodies.forEach(R=>e.set(R.id,M.id))}),s(E,{created:f})}},p=f=>{const y=typeof f=="string"?f:f.id,E=t.get(y);if(E)return t.delete(y),E.bodies.forEach(v=>e.delete(v.id)),E;console.warn(`Attempt to delete missing annotation: ${y}`)},B=(f,y=S.LOCAL)=>{const E=p(f);E&&s(y,{deleted:[E]})},A=(f,y=S.LOCAL)=>{const E=f.reduce((v,M)=>{const R=p(M);return R?[...v,R]:v},[]);E.length>0&&s(y,{deleted:E})},w=(f,y=S.LOCAL)=>{const E=t.get(f.annotation);if(E){const v=E.bodies.find(M=>M.id===f.id);if(v){e.delete(v.id);const M={...E,bodies:E.bodies.filter(Y=>Y.id!==f.id)};t.set(E.id,M),s(y,{updated:[{oldValue:E,newValue:M,bodiesDeleted:[v]}]})}else console.warn(`Attempt to delete missing body ${f.id} from annotation ${f.annotation}`)}else console.warn(`Attempt to delete body from missing annotation ${f.annotation}`)},x=f=>{const y=t.get(f);return y?{...y}:void 0},u=f=>{const y=e.get(f);if(y){const v=x(y).bodies.find(M=>M.id===f);if(v)return v;console.error(`Store integrity error: body ${f} in index, but not in annotation`)}else console.warn(`Attempt to retrieve missing body: ${f}`)},c=(f,y)=>{if(f.annotation!==y.annotation)throw"Annotation integrity violation: annotation ID must be the same when updating bodies";const E=t.get(f.annotation);if(E){const v=E.bodies.find(R=>R.id===f.id),M={...E,bodies:E.bodies.map(R=>R.id===v.id?y:R)};return t.set(E.id,M),v.id!==y.id&&(e.delete(v.id),e.set(y.id,M.id)),{oldValue:E,newValue:M,bodiesUpdated:[{oldBody:v,newBody:y}]}}else console.warn(`Attempt to add body to missing annotation ${f.annotation}`)},m=(f,y,E=S.LOCAL)=>{const v=c(f,y);s(E,{updated:[v]})},T=(f,y=S.LOCAL)=>{const E=f.map(v=>c({id:v.id,annotation:v.annotation},v));s(y,{updated:E})},b=f=>{const y=t.get(f.annotation);if(y){const E={...y,target:{...y.target,...f}};return t.set(y.id,E),{oldValue:y,newValue:E,targetUpdated:{oldTarget:y.target,newTarget:f}}}else console.warn(`Attempt to update target on missing annotation: ${f.annotation}`)};return{addAnnotation:a,addBody:l,all:h,bulkAddAnnotation:d,bulkDeleteAnnotation:A,bulkUpdateBodies:T,bulkUpdateTargets:(f,y=S.LOCAL)=>{const E=f.map(b).filter(v=>v);E.length>0&&s(y,{updated:E})},clear:g,deleteAnnotation:B,deleteBody:w,getAnnotation:x,getBody:u,observe:o,unobserve:i,updateAnnotation:r,updateBody:m,updateTarget:(f,y=S.LOCAL)=>{const E=b(f);E&&s(y,{updated:[E]})}}},Xt=()=>{const{subscribe:t,set:e}=J([]);return{subscribe:t,set:e}},Yt=(t,e,n,o,i,s)=>{const a=new Map;let r=[],l,h;const g=(A,w)=>{a.has(A)?a.get(A).push(w):a.set(A,[w])},d=(A,w)=>{const x=a.get(A);x&&x.indexOf(w)>0&&x.splice(x.indexOf(w),1)},p=(A,w,x)=>{a.has(A)&&setTimeout(()=>{a.get(A).forEach(u=>{if(i){const c=Array.isArray(w)?w.map(T=>i.serialize(T)):i.serialize(w),m=x?x instanceof PointerEvent?x:i.serialize(x):void 0;u(c,m)}else u(w,x)})},1)},B=()=>{const{selected:A}=e,w=A.map(({id:x})=>t.getAnnotation(x));w.forEach(x=>{const u=r.find(c=>c.id===x.id);(!u||!_(u,x))&&p("updateAnnotation",x,u)}),r=r.map(x=>{const u=w.find(({id:c})=>c===x.id);return u||x})};return e.subscribe(({selected:A})=>{if(!(r.length===0&&A.length===0)){if(r.length===0&&A.length>0)r=A.map(({id:w})=>t.getAnnotation(w));else if(r.length>0&&A.length===0)r.forEach(w=>{const x=t.getAnnotation(w.id);x&&!_(x,w)&&p("updateAnnotation",x,w)}),r=[];else{const w=new Set(r.map(c=>c.id)),x=new Set(A.map(({id:c})=>c));r.filter(c=>!x.has(c.id)).forEach(c=>{const m=t.getAnnotation(c.id);m&&!_(m,c)&&p("updateAnnotation",m,c)}),r=[...r.filter(c=>x.has(c.id)),...A.filter(({id:c})=>!w.has(c)).map(({id:c})=>t.getAnnotation(c))]}p("selectionChanged",r)}}),n.subscribe(A=>{!l&&A?p("mouseEnterAnnotation",t.getAnnotation(A)):l&&!A?p("mouseLeaveAnnotation",t.getAnnotation(l)):l&&A&&(p("mouseLeaveAnnotation",t.getAnnotation(l)),p("mouseEnterAnnotation",t.getAnnotation(A))),l=A}),o==null||o.subscribe(A=>p("viewportIntersect",A.map(t.getAnnotation))),t.observe(A=>{s&&(h&&clearTimeout(h),h=setTimeout(B,1e3));const{created:w,deleted:x}=A.changes;w.forEach(c=>p("createAnnotation",c)),x.forEach(c=>p("deleteAnnotation",c)),A.changes.updated.filter(c=>[...c.bodiesCreated||[],...c.bodiesDeleted||[],...c.bodiesUpdated||[]].length>0).forEach(({oldValue:c,newValue:m})=>{const T=r.find(b=>b.id===c.id)||c;r=r.map(b=>b.id===c.id?m:b),p("updateAnnotation",m,T)})},{origin:S.LOCAL}),t.observe(A=>{if(r){const w=new Set(r.map(u=>u.id)),x=A.changes.updated.filter(({newValue:u})=>w.has(u.id)).map(({newValue:u})=>u);x.length>0&&(r=r.map(u=>{const c=x.find(m=>m.id===u.id);return c||u}))}},{origin:S.REMOTE}),{on:g,off:d,emit:p}},_t=t=>e=>e.map(n=>t.serialize(n)),rt=t=>e=>e.reduce((n,o)=>{const{parsed:i,error:s}=t.parse(o);return s?{parsed:n.parsed,failed:[...n.failed,o]}:{parsed:[...n.parsed,i],failed:n.failed}},{parsed:[],failed:[]}),at=(t,e)=>{const n=g=>{if(e){const{parsed:d,error:p}=e.parse(g);d?t.addAnnotation(d,S.REMOTE):console.error(p)}else t.addAnnotation(g,S.REMOTE)},o=()=>t.clear(),i=g=>{const d=t.getAnnotation(g);return e&&d?e.serialize(d):d},s=()=>e?t.all().map(e.serialize):t.all(),a=g=>fetch(g).then(d=>d.json()).then(d=>(l(d),d)),r=g=>{if(typeof g=="string"){const d=t.getAnnotation(g);return t.deleteAnnotation(g),e?e.serialize(d):d}else{const d=e?e.parse(g).parsed:g;return t.deleteAnnotation(d),g}},l=g=>{if(e){const{parsed:d,failed:p}=rt(e)(g);p.length>0&&console.warn(`Discarded ${p.length} invalid annotations`,p),t.bulkAddAnnotation(d,!0,S.REMOTE)}else t.bulkAddAnnotation(g,!0,S.REMOTE)};return{addAnnotation:n,clearAnnotations:o,getAnnotationById:i,getAnnotations:s,loadAnnotations:a,removeAnnotation:r,setAnnotations:l,updateAnnotation:g=>{if(e){const d=e.parse(g).parsed,p=e.serialize(t.getAnnotation(d.id));return t.updateAnnotation(d),p}else{const d=t.getAnnotation(g.id);return t.updateAnnotation(g),d}}}};let It=t=>crypto.getRandomValues(new Uint8Array(t)),Dt=(t,e,n)=>{let o=(2<<Math.log(t.length-1)/Math.LN2)-1,i=-~(1.6*o*e/t.length);return(s=e)=>{let a="";for(;;){let r=n(i),l=i;for(;l--;)if(a+=t[r[l]&o]||"",a.length===s)return a}}},Ut=(t,e=21)=>Dt(t,e,It),Nt=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,n)=>(n&=63,n<36?e+=n.toString(36):n<62?e+=(n-26).toString(36).toUpperCase():n>62?e+="-":e+="_",e),"");const ct=()=>({isGuest:!0,id:Ut("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_",20)()}),kt=t=>{const e=JSON.stringify(t);let n=0;for(let o=0,i=e.length;o<i;o++){let s=e.charCodeAt(o);n=(n<<5)-n+s,n|=0}return`${n}`},zt=(t,e)=>(Array.isArray(t)?t:[t]).map(n=>{const{id:o,type:i,purpose:s,value:a,created:r,creator:l,...h}=n;return{id:o||`temp-${kt(n)}`,annotation:e,type:i,purpose:s,value:a,created:r,creator:l?typeof l=="object"?{...l}:l:void 0,...h}}),Pt=t=>t.map(e=>{var o;const n={...e};return delete n.annotation,(o=n.id)!=null&&o.startsWith("temp-")&&delete n.id,n});Nt();function Ht(t,e,n,o,i){lt(t,e,n||0,o||t.length-1,i||Wt)}function lt(t,e,n,o,i){for(;o>n;){if(o-n>600){var s=o-n+1,a=e-n+1,r=Math.log(s),l=.5*Math.exp(2*r/3),h=.5*Math.sqrt(r*l*(s-l)/s)*(a-s/2<0?-1:1),g=Math.max(n,Math.floor(e-a*l/s+h)),d=Math.min(o,Math.floor(e+(s-a)*l/s+h));lt(t,e,g,d,i)}var p=t[e],B=n,A=o;for(z(t,n,e),i(t[o],p)>0&&z(t,n,o);B<A;){for(z(t,B,A),B++,A--;i(t[B],p)<0;)B++;for(;i(t[A],p)>0;)A--}i(t[n],p)===0?z(t,n,A):(A++,z(t,A,o)),A<=e&&(n=A+1),e<=A&&(o=A-1)}}function z(t,e,n){var o=t[e];t[e]=t[n],t[n]=o}function Wt(t,e){return t<e?-1:t>e?1:0}class $t{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.4)),this.clear()}all(){return this._all(this.data,[])}search(e){let n=this.data;const o=[];if(!q(e,n))return o;const i=this.toBBox,s=[];for(;n;){for(let a=0;a<n.children.length;a++){const r=n.children[a],l=n.leaf?i(r):r;q(e,l)&&(n.leaf?o.push(r):Z(e,l)?this._all(r,o):s.push(r))}n=s.pop()}return o}collides(e){let n=this.data;if(!q(e,n))return!1;const o=[];for(;n;){for(let i=0;i<n.children.length;i++){const s=n.children[i],a=n.leaf?this.toBBox(s):s;if(q(e,a)){if(n.leaf||Z(e,a))return!0;o.push(s)}}n=o.pop()}return!1}load(e){if(!(e&&e.length))return this;if(e.length<this._minEntries){for(let o=0;o<e.length;o++)this.insert(e[o]);return this}let n=this._build(e.slice(),0,e.length-1,0);if(!this.data.children.length)this.data=n;else if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){const o=this.data;this.data=n,n=o}this._insert(n,this.data.height-n.height-1,!0)}return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=N([]),this}remove(e,n){if(!e)return this;let o=this.data;const i=this.toBBox(e),s=[],a=[];let r,l,h;for(;o||s.length;){if(o||(o=s.pop(),l=s[s.length-1],r=a.pop(),h=!0),o.leaf){const g=Vt(e,o.children,n);if(g!==-1)return o.children.splice(g,1),s.push(o),this._condense(s),this}!h&&!o.leaf&&Z(o,i)?(s.push(o),a.push(r),r=0,l=o,o=o.children[0]):l?(r++,o=l.children[r],h=!1):o=null}return this}toBBox(e){return e}compareMinX(e,n){return e.minX-n.minX}compareMinY(e,n){return e.minY-n.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,n){const o=[];for(;e;)e.leaf?n.push(...e.children):o.push(...e.children),e=o.pop();return n}_build(e,n,o,i){const s=o-n+1;let a=this._maxEntries,r;if(s<=a)return r=N(e.slice(n,o+1)),U(r,this.toBBox),r;i||(i=Math.ceil(Math.log(s)/Math.log(a)),a=Math.ceil(s/Math.pow(a,i-1))),r=N([]),r.leaf=!1,r.height=i;const l=Math.ceil(s/a),h=l*Math.ceil(Math.sqrt(a));dt(e,n,o,h,this.compareMinX);for(let g=n;g<=o;g+=h){const d=Math.min(g+h-1,o);dt(e,g,d,l,this.compareMinY);for(let p=g;p<=d;p+=l){const B=Math.min(p+l-1,d);r.children.push(this._build(e,p,B,i-1))}}return U(r,this.toBBox),r}_chooseSubtree(e,n,o,i){for(;i.push(n),!(n.leaf||i.length-1===o);){let s=1/0,a=1/0,r;for(let l=0;l<n.children.length;l++){const h=n.children[l],g=Q(h),d=jt(e,h)-g;d<a?(a=d,s=g<s?g:s,r=h):d===a&&g<s&&(s=g,r=h)}n=r||n.children[0]}return n}_insert(e,n,o){const i=o?e:this.toBBox(e),s=[],a=this._chooseSubtree(i,this.data,n,s);for(a.children.push(e),H(a,i);n>=0&&s[n].children.length>this._maxEntries;)this._split(s,n),n--;this._adjustParentBBoxes(i,s,n)}_split(e,n){const o=e[n],i=o.children.length,s=this._minEntries;this._chooseSplitAxis(o,s,i);const a=this._chooseSplitIndex(o,s,i),r=N(o.children.splice(a,o.children.length-a));r.height=o.height,r.leaf=o.leaf,U(o,this.toBBox),U(r,this.toBBox),n?e[n-1].children.push(r):this._splitRoot(o,r)}_splitRoot(e,n){this.data=N([e,n]),this.data.height=e.height+1,this.data.leaf=!1,U(this.data,this.toBBox)}_chooseSplitIndex(e,n,o){let i,s=1/0,a=1/0;for(let r=n;r<=o-n;r++){const l=P(e,0,r,this.toBBox),h=P(e,r,o,this.toBBox),g=Gt(l,h),d=Q(l)+Q(h);g<s?(s=g,i=r,a=d<a?d:a):g===s&&d<a&&(a=d,i=r)}return i||o-n}_chooseSplitAxis(e,n,o){const i=e.leaf?this.compareMinX:qt,s=e.leaf?this.compareMinY:Ft,a=this._allDistMargin(e,n,o,i),r=this._allDistMargin(e,n,o,s);a<r&&e.children.sort(i)}_allDistMargin(e,n,o,i){e.children.sort(i);const s=this.toBBox,a=P(e,0,n,s),r=P(e,o-n,o,s);let l=V(a)+V(r);for(let h=n;h<o-n;h++){const g=e.children[h];H(a,e.leaf?s(g):g),l+=V(a)}for(let h=o-n-1;h>=n;h--){const g=e.children[h];H(r,e.leaf?s(g):g),l+=V(r)}return l}_adjustParentBBoxes(e,n,o){for(let i=o;i>=0;i--)H(n[i],e)}_condense(e){for(let n=e.length-1,o;n>=0;n--)e[n].children.length===0?n>0?(o=e[n-1].children,o.splice(o.indexOf(e[n]),1)):this.clear():U(e[n],this.toBBox)}}function Vt(t,e,n){if(!n)return e.indexOf(t);for(let o=0;o<e.length;o++)if(n(t,e[o]))return o;return-1}function U(t,e){P(t,0,t.children.length,e,t)}function P(t,e,n,o,i){i||(i=N(null)),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let s=e;s<n;s++){const a=t.children[s];H(i,t.leaf?o(a):a)}return i}function H(t,e){return t.minX=Math.min(t.minX,e.minX),t.minY=Math.min(t.minY,e.minY),t.maxX=Math.max(t.maxX,e.maxX),t.maxY=Math.max(t.maxY,e.maxY),t}function qt(t,e){return t.minX-e.minX}function Ft(t,e){return t.minY-e.minY}function Q(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function V(t){return t.maxX-t.minX+(t.maxY-t.minY)}function jt(t,e){return(Math.max(e.maxX,t.maxX)-Math.min(e.minX,t.minX))*(Math.max(e.maxY,t.maxY)-Math.min(e.minY,t.minY))}function Gt(t,e){const n=Math.max(t.minX,e.minX),o=Math.max(t.minY,e.minY),i=Math.min(t.maxX,e.maxX),s=Math.min(t.maxY,e.maxY);return Math.max(0,i-n)*Math.max(0,s-o)}function Z(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function q(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function N(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function dt(t,e,n,o,i){const s=[e,n];for(;s.length;){if(n=s.pop(),e=s.pop(),n-e<=o)continue;const a=e+Math.ceil((n-e)/o/2)*o;Ht(t,a,e,n,i),s.push(e,a,a,n)}}const Jt=(t,e)=>{const n=s=>Math.round(s*10)/10,o={top:n(t.top),bottom:n(t.bottom),left:n(t.left),right:n(t.right)},i={top:n(e.top),bottom:n(e.bottom),left:n(e.left),right:n(e.right)};if(Math.abs(o.top-i.top)<.5&&Math.abs(o.bottom-i.bottom)<.5){if(Math.abs(o.left-i.right)<.5||Math.abs(o.right-i.left)<.5)return"inline-adjacent";if(o.left>=i.left&&o.right<=i.right)return"inline-is-contained";if(o.left<=i.left&&o.right>=i.right)return"inline-contains"}else if(o.top<=i.top&&o.bottom>=i.bottom){if(o.left<=i.left&&o.right>=i.right)return"block-contains"}else if(o.top>=i.top&&o.bottom<=i.bottom&&o.left>=i.left&&o.right<=i.right)return"block-is-contained"},Kt=(t,e)=>{const n=Math.min(t.left,e.left),o=Math.max(t.right,e.right),i=Math.min(t.top,e.top),s=Math.max(t.bottom,e.bottom);return new DOMRect(n,i,o-n,s-i)},Qt=t=>t.reduce((e,n)=>{if(n.width===0||n.height===0)return e;let o=[...e],i=!1;for(const s of e){const a=Jt(n,s);if(a==="inline-adjacent"){o=o.map(r=>r===s?Kt(n,s):r),i=!0;break}else if(a==="inline-contains"){o=o.map(r=>r===s?n:r),i=!0;break}else if(a==="inline-is-contained"){i=!0;break}else if(a==="block-contains"||a==="block-is-contained"){n.width<s.width&&(o=o.map(r=>r===s?n:r)),i=!0;break}}return i?o:[...o,n]},[]),Zt=t=>{const{startContainer:e,endContainer:n}=t;if(e.nodeType===Node.TEXT_NODE&&n.nodeType===Node.TEXT_NODE)return t;if(e.nodeType!==Node.TEXT_NODE){const i=e.nextSibling||e.parentNode,s=i.nodeType===Node.TEXT_NODE?i:Array.from(i.childNodes).filter(a=>a.nodeType===Node.TEXT_NODE).shift();t.setEnd(s,0)}if(n.nodeType!==Node.TEXT_NODE){const i=n.previousSibling||n.parentNode,s=i.nodeType===Node.TEXT_NODE?i:Array.from(i.childNodes).filter(a=>a.nodeType===Node.TEXT_NODE).pop();t.setEnd(s,s.textContent.length)}return t},te=(t,e)=>{const n=new $t,o=new Map,i=u=>{const c=e.getBoundingClientRect(),T=u.selector.range instanceof Range&&!u.selector.range.collapsed&&u.selector.range.startContainer.nodeType===Node.TEXT_NODE&&u.selector.range.endContainer.nodeType===Node.TEXT_NODE?u:I(u,e),b=Array.from(T.selector.range.getClientRects()),C=Qt(b);return C.map(L=>{const{x:f,y,width:E,height:v}=L;return{minX:f-c.x,minY:y-c.y,maxX:f-c.x+E,maxY:y-c.y+v,annotation:{id:u.annotation,rects:C}}})},s=()=>[...o.values()],a=()=>{n.clear(),o.clear()},r=u=>{const c=i(u);c.forEach(m=>n.insert(m)),o.set(u.annotation,c)},l=u=>{o.get(u.annotation).forEach(m=>n.remove(m)),o.delete(u.annotation)},h=u=>{l(u),r(u)},g=(u,c=!0)=>{c&&a();const m=u.map(b=>({target:b,rects:i(b)}));m.forEach(({target:b,rects:C})=>o.set(b.annotation,C));const T=m.reduce((b,{rects:C})=>[...b,...C],[]);n.load(T)},d=(u,c)=>{const m=n.search({minX:u,minY:c,maxX:u,maxY:c}),T=b=>b.annotation.rects.reduce((C,L)=>C+L.width*L.height,0);if(m.length>0)return m.sort((b,C)=>T(b)-T(C)),m[0].annotation.id},p=u=>{const c=B(u);if(c.length===0)return;let m=c[0].left,T=c[0].top,b=c[0].right,C=c[0].bottom;for(let L=1;L<c.length;L++){const f=c[L];m=Math.min(m,f.left),T=Math.min(T,f.top),b=Math.max(b,f.right),C=Math.max(C,f.bottom)}return new DOMRect(m,T,b-m,C-T)},B=u=>{const c=o.get(u);return c?c[0].annotation.rects:[]};return{all:s,clear:a,getAt:d,getBoundsForAnnotation:p,getDOMRectsForAnnotation:B,getIntersectingRects:(u,c,m,T)=>n.search({minX:u,minY:c,maxX:m,maxY:T}),insert:r,recalculate:()=>g(t.all().map(u=>u.target),!0),remove:l,set:g,size:()=>n.all().length,update:h}},F=t=>{const{range:e}=t.target.selector;return e instanceof Range&&!e.collapsed},ht=(t,e)=>{const n=Ot(),o=te(n,t),i=xt(n,e),s=At(n),a=Xt(),r=(x,u=S.LOCAL)=>{const c=x.target.selector.range instanceof Range?x:{...x,target:I(x.target,t)},{range:m}=c.target.selector,T=m&&!m.collapsed;return T&&n.addAnnotation(c,u),T},l=(x,u=!0,c=S.LOCAL)=>{const m=x.map(b=>F(b)?b:{...b,target:I(b.target,t)});if(m.some(b=>b.target.selector.range.collapsed)){const b=m.filter(C=>C.target.selector.range.collapsed);return console.warn("Could not revive all targets"),console.warn(b),n.bulkAddAnnotation(m,u,c),b}else return n.bulkAddAnnotation(m,u,c),[]},h=(x,u=S.LOCAL)=>{const c=x.selector.range instanceof Range?x:I(x,t);n.updateTarget(c,u)},g=(x,u=S.LOCAL)=>{const c=x.map(m=>m.selector.range instanceof Range?m:I(m,t));n.bulkUpdateTargets(c,u)},d=(x,u)=>{const c=o.getAt(x,u);return c?n.getAnnotation(c):void 0},p=(x,u,c,m)=>{const T=o.getIntersectingRects(x,u,c,m);return Array.from(new Set(T.map(C=>C.annotation.id))).map(C=>n.getAnnotation(C)).filter(C=>C)},B=(x,u,c,m=5)=>{const T=o.getDOMRectsForAnnotation(x);if(T.length>0){if(u&&c){const b=T.find(({top:C,right:L,bottom:f,left:y})=>u>=y-m&&u<=L+m&&c>=C-m&&c<=f+m);if(b)return b}return o.getBoundsForAnnotation(x)}},A=(x,u,c,m)=>{const b=o.getIntersectingRects(x,u,c,m).reduce((C,L)=>((C[L.annotation.id]=C[L.annotation.id]||[]).push(L),C),{});return Object.entries(b).map(([C,L])=>({annotation:n.getAnnotation(C),rects:L.map(({minX:f,minY:y,maxX:E,maxY:v})=>({x:f,y,width:E-f,height:v-y}))}))},w=()=>o.recalculate();return n.observe(({changes:x})=>{const u=(x.created||[]).filter(F),c=(x.deleted||[]).filter(F),m=(x.updated||[]).filter(T=>F(T.newValue));u.length>0&&o.set(u.map(T=>T.target),!1),(c==null?void 0:c.length)>0&&c.forEach(T=>o.remove(T.target)),(m==null?void 0:m.length)>0&&m.forEach(({newValue:T})=>o.update(T.target))}),{store:{...n,addAnnotation:r,bulkAddAnnotation:l,bulkUpdateTargets:g,getAnnotationBounds:B,getAt:d,getIntersecting:p,getIntersectingRects:A,recalculatePositions:w,updateTarget:h},selection:i,hover:s,viewport:a}},ee=(t,e={})=>{const n=new Map,o=s=>Array.from(n.entries()).filter(([a,r])=>r.presenceKey===s.presenceKey).map(([a,r])=>a);return t.on("selectionChange",(s,a)=>{o(s).forEach(l=>n.delete(l)),a&&a.forEach(l=>n.set(l,s))}),{paint:(s,a,r,l,h,g)=>{e.font&&(l.font=e.font);const d=n.get(s.id);if(d){const{x:p,y:B,height:A}=a[0];l.fillStyle=d.appearance.color,l.fillRect(p-2,B-2.5,2,A+5);const w=l.measureText(d.appearance.label),x=w.width+6,u=w.actualBoundingBoxAscent+w.actualBoundingBoxDescent+8,c=w.fontBoundingBoxAscent?8:6.5;l.fillRect(p-2,B-2.5-u,x,u),l.fillStyle="#fff",l.fillText(d.appearance.label,p+1,B-c),r.fillStyle=d.appearance.color,r.globalAlpha=h?.45:.18,a.forEach(({x:m,y:T,width:b,height:C})=>r.fillRect(m,T-2.5,b,C+5))}else j.paint(s,a,r,l,h,g)}}},ut=t=>t===null?null:t.scrollHeight>t.clientHeight?t:ut(t.parentElement),ne=(t,e)=>n=>{const o=ut(t);if(o){const i=e.getAnnotation(n.id),{range:s}=i.target.selector;if(!s||s.collapsed)return!1;const a=o.getBoundingClientRect(),r=o.clientHeight,l=o.clientWidth,h=i.target.selector.range.getBoundingClientRect(),{width:g,height:d}=e.getAnnotationBounds(n.id),p=h.top-a.top,B=h.left-a.left,A=o.parentElement?o.scrollTop:0,w=o.parentElement?o.scrollLeft:0,x=p+A-(r-d)/2,u=B+w-(l-g)/2;return o.scroll({top:x,left:u,behavior:"smooth"}),!0}},oe=(t,e,n)=>{const o=document.createRange(),i=n?t.startContainer.parentElement.closest(n):e;o.setStart(i,0),o.setEnd(t.startContainer,t.startOffset);const s=t.toString(),a=o.toString().length,r=a+s.length;return n?{quote:s,start:a,end:r,range:t,offsetReference:i}:{quote:s,start:a,end:r,range:t}},ie=(t,e,n)=>{const{store:o,selection:i}=e;let s,a=null;const r=p=>s=p;let l=!1,h;t.addEventListener("selectstart",p=>{if(!l)return;!p.target.parentElement.closest(".not-annotatable")?a={annotation:Tt(),selector:void 0,creator:s,created:new Date}:(a=null,h=void 0)});let g;document.addEventListener("selectionchange",p=>{g&&clearTimeout(g),g=setTimeout(()=>d(),50)});const d=()=>{var B,A;const p=document.getSelection();if(!p.isCollapsed&&l&&a){const w=Array.from(Array(p.rangeCount).keys()).map(c=>p.getRangeAt(c));Zt(w[0]).toString()!==((A=(B=a.selector)==null?void 0:B.range)==null?void 0:A.toString())&&(a={...a,selector:oe(w[0],t,n)},o.getAnnotation(a.annotation)?o.updateTarget(a,S.LOCAL):(o.addAnnotation({id:a.annotation,bodies:[],target:a}),i.clickSelect(a.annotation,h)))}};return t.addEventListener("pointerdown",p=>{h=p,l=p.button===0}),document.addEventListener("pointerup",p=>{var A;h=p,!((A=p.target.parentElement)!=null&&A.closest(".not-annotatable")||!l)&&setTimeout(()=>{if(a!=null&&a.selector)o.updateTarget(a,S.LOCAL),i.clickSelect(a.annotation,p),a=null,h=void 0;else{const{x:w,y:x}=t.getBoundingClientRect(),u=o.getAt(p.clientX-w,p.clientY-x);if(u){const{selected:c}=i;(c.length!==1||c[0].id!==u.id)&&(i.clickSelect(u.id,p),h=void 0)}else i.isEmpty()||i.clear()}},50)}),{setUser:r}},fe="",se=(t,e={})=>{const n=ht(t,e.pointerAction),{hover:o,selection:i,viewport:s}=n,a=n.store,r=Yt(a,i,o,s);let l=ct(),h=e.style;const g=ot(t,n,s),d=ie(t,n,e.offsetReferenceSelector);d.setUser(l);const p=at(a,e.adapter),B=m=>{h=m,g.setDrawingStyle(m)};return{...p,destroy:()=>{throw"Not implemented yet"},element:t,getUser:()=>l,setUser:m=>{l=m,d.setUser(m)},setSelected:m=>{m?i.setSelected(m):i.clear()},setPresenceProvider:m=>{m&&(g.setPainter(ee(m,e.presence)),m.on("selectionChange",()=>g.redraw()))},on:r.on,off:r.off,scrollIntoView:ne(t,a),state:n,get style(){return h},set style(m){B(m)}}},re=S;O.Origin=re,O.createAnonymousGuest=ct,O.createBaseAnnotator=at,O.createHighlightLayer=ot,O.createTextAnnotator=se,O.createTextAnnotatorState=ht,O.defaultPainter=j,O.parseAll=rt,O.parseW3CBodies=zt,O.reviveTarget=I,O.serializeAll=_t,O.serializeW3CBodies=Pt,Object.defineProperty(O,Symbol.toStringTag,{value:"Module"})});
1
+ (function(U,N){typeof exports=="object"&&typeof module<"u"?N(exports):typeof define=="function"&&define.amd?define(["exports"],N):(U=typeof globalThis<"u"?globalThis:U||self,N(U.RecogitoJS={}))})(this,function(U){"use strict";const N={fill:"rgb(0, 128, 255",fillOpacity:.18},wt={fill:"rgb(0, 128, 255)",fillOpacity:.45},K={paint:(t,e,n,o,i,s)=>{const r=s?typeof s=="function"?s(t,i):s:i?wt:N;n.fillStyle=r.fill,n.globalAlpha=r.fillOpacity||1,e.forEach(({x:a,y:l,width:d,height:w})=>n.fillRect(a,l-2.5,d,w+5))}},yt=t=>{let e=new Set;return o=>{const i=o.map(s=>s.id);(e.size!==i.length||i.some(s=>!e.has(s)))&&t.set(i),e=new Set(i)}},xt=(t,e=10)=>{let n;return(...o)=>{clearTimeout(n),n=setTimeout(()=>t.apply(void 0,o),e)}},it=(t,e)=>{const n=document.createElement("canvas");if(n.width=e?2*window.innerWidth:window.innerWidth,n.height=e?2*window.innerHeight:window.innerHeight,n.className=t,e){const o=n.getContext("2d");o.scale(2,2),o.translate(.5,.5)}return n},st=(t,e)=>{if(t.width=e?2*window.innerWidth:window.innerWidth,t.height=e?2*window.innerHeight:window.innerHeight,e){const n=t.getContext("2d");n.scale(2,2),n.translate(.5,.5)}},rt=(t,e,n)=>{const{store:o,selection:i,hover:s}=e;let r,a,l=K;const d=yt(n);t.classList.add("r6o-annotatable");const w=it("r6o-highlight-layer bg"),u=it("r6o-highlight-layer fg",!0),T=w.getContext("2d"),h=u.getContext("2d");t.insertBefore(w,t.firstChild),t.appendChild(u);const A=v=>{const{x:C,y:O}=t.getBoundingClientRect(),X=o.getAt(v.clientX-C,v.clientY-O);X&&(!a||a(X))?s.current!==X.id&&(t.classList.add("hovered"),s.set(X.id)):s.current&&(t.classList.remove("hovered"),s.set(null))};t.addEventListener("pointermove",A);const B=()=>{const{top:v,left:C}=t.getBoundingClientRect(),{innerWidth:O,innerHeight:X}=window,W=-C,J=-v,Q=O-C,G=X-v;return{top:v,left:C,minX:W,minY:J,maxX:Q,maxY:G}},b=()=>requestAnimationFrame(()=>{const{top:v,left:C,minX:O,minY:X,maxX:W,maxY:J}=B(),Q=a?o.getIntersectingRects(O,X,W,J).filter(({annotation:Y})=>a(Y)):o.getIntersectingRects(O,X,W,J),{width:G,height:At}=u,we=new Set(i.selected.map(({id:Y})=>Y));h.clearRect(-.5,-.5,G+1,At+1),T.clearRect(-.5,-.5,G+1,At+1),Q.forEach(({annotation:Y,rects:ye})=>{const xe=ye.map(({x:Ee,y:Se,width:Te,height:Be})=>({x:Ee+C,y:Se+v,width:Te,height:Be})),ve=we.has(Y.id);l.paint(Y,xe,T,h,ve,r)}),setTimeout(()=>d(Q.map(({annotation:Y})=>Y)),1)}),c=v=>{r=v,b()},f=v=>{a=v,b()},g=()=>b();o.observe(g);const m=i.subscribe(()=>b()),E=()=>b();document.addEventListener("scroll",E,{capture:!0,passive:!0});const S=xt(()=>{console.log("onresize!"),st(w),st(u,!0),o.recalculatePositions(),b()});window.addEventListener("resize",S);const M=new ResizeObserver(S);M.observe(t);const p={attributes:!0,childList:!0,subtree:!0},x=new MutationObserver(S);return x.observe(document.body,p),{destroy:()=>{t.removeEventListener("pointermove",A),t.removeChild(u),t.appendChild(w),o.unobserve(g),m(),document.removeEventListener("scroll",E),window.removeEventListener("resize",S),M.disconnect(),x.disconnect()},redraw:b,setDrawingStyle:c,setFilter:f,setPainter:v=>l=v}};let $;const vt=new Uint8Array(16);function Et(){if(!$&&($=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!$))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return $(vt)}const R=[];for(let t=0;t<256;++t)R.push((t+256).toString(16).slice(1));function St(t,e=0){return R[t[e+0]]+R[t[e+1]]+R[t[e+2]]+R[t[e+3]]+"-"+R[t[e+4]]+R[t[e+5]]+"-"+R[t[e+6]]+R[t[e+7]]+"-"+R[t[e+8]]+R[t[e+9]]+"-"+R[t[e+10]]+R[t[e+11]]+R[t[e+12]]+R[t[e+13]]+R[t[e+14]]+R[t[e+15]]}const at={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ct(t,e,n){if(at.randomUUID&&!e&&!t)return at.randomUUID();t=t||{};const o=t.random||(t.rng||Et)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){n=n||0;for(let i=0;i<16;++i)e[n+i]=o[i];return e}return St(o)}var lt=Object.prototype.hasOwnProperty;function I(t,e){var n,o;if(t===e)return!0;if(t&&e&&(n=t.constructor)===e.constructor){if(n===Date)return t.getTime()===e.getTime();if(n===RegExp)return t.toString()===e.toString();if(n===Array){if((o=t.length)===e.length)for(;o--&&I(t[o],e[o]););return o===-1}if(!n||typeof t=="object"){o=0;for(n in t)if(lt.call(t,n)&&++o&&!lt.call(e,n)||!(n in e)||!I(t[n],e[n]))return!1;return Object.keys(e).length===o}}return t!==t&&e!==e}function Z(){}function Tt(t,e){return t!=t?e==e:t!==e||t&&typeof t=="object"||typeof t=="function"}const V=[];function tt(t,e=Z){let n;const o=new Set;function i(a){if(Tt(t,a)&&(t=a,n)){const l=!V.length;for(const d of o)d[1](),V.push(d,t);if(l){for(let d=0;d<V.length;d+=2)V[d][0](V[d+1]);V.length=0}}}function s(a){i(a(t))}function r(a,l=Z){const d=[a,l];return o.add(d),o.size===1&&(n=e(i,s)||Z),a(t),()=>{o.delete(d),o.size===0&&n&&(n(),n=null)}}return{set:i,update:s,subscribe:r}}const Bt=t=>{const{subscribe:e,set:n}=tt();let o;return e(i=>o=i),t.observe(({changes:i})=>{if(o){(i.deleted||[]).some(r=>r.id===o)&&n(void 0);const s=(i.updated||[]).find(({oldValue:r})=>r.id===o);s&&n(s.newValue.id)}}),{get current(){return o},subscribe:e,set:n}},et={selected:[]},Ct=(t,e="EDIT")=>{const{subscribe:n,set:o}=tt(et);let i=et;n(u=>i=u);const s=()=>o(et),r=()=>{var u;return((u=i.selected)==null?void 0:u.length)===0},a=u=>{if(i.selected.length===0)return!1;const T=typeof u=="string"?u:u.id;return i.selected.some(h=>h.id===T)},l=(u,T)=>{const h=t.getAnnotation(u);if(h){const A=Mt(h,e);o(A==="EDIT"?{selected:[{id:u,editable:!0}],pointerEvent:T}:A==="SELECT"?{selected:[{id:u}],pointerEvent:T}:{selected:[],pointerEvent:T})}else console.warn("Invalid selection: "+u)},d=(u,T=!0)=>{const h=Array.isArray(u)?u:[u],A=h.map(B=>t.getAnnotation(B)).filter(Boolean);o({selected:A.map(({id:B})=>({id:B,editable:T}))}),A.length!==h.length&&console.warn("Invalid selection",u)},w=u=>{if(i.selected.length===0)return!1;const{selected:T}=i;T.filter(({id:h})=>u.includes(h)).length>0&&o({selected:T.filter(({id:h})=>!u.includes(h))})};return t.observe(({changes:u})=>w((u.deleted||[]).map(T=>T.id))),{clear:s,clickSelect:l,get selected(){return i?[...i.selected]:null},get pointerEvent(){return i?i.pointerEvent:null},isEmpty:r,isSelected:a,setSelected:d,subscribe:n}},Mt=(t,e)=>typeof e=="function"?e(t)||"EDIT":e||"EDIT",Lt=[];for(let t=0;t<256;++t)Lt.push((t+256).toString(16).slice(1));typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Ot=(t,e)=>{const n=new Set(t.bodies.map(o=>o.id));return e.bodies.filter(o=>!n.has(o.id))},Rt=(t,e)=>{const n=new Set(e.bodies.map(o=>o.id));return t.bodies.filter(o=>!n.has(o.id))},Xt=(t,e)=>e.bodies.map(n=>{const o=t.bodies.find(i=>i.id===n.id);return{newBody:n,oldBody:o&&!I(o,n)?o:void 0}}).filter(({oldBody:n})=>n).map(({oldBody:n,newBody:o})=>({oldBody:n,newBody:o})),Ut=(t,e)=>!I(t.target,e.target),dt=(t,e)=>{const n=Ot(t,e),o=Rt(t,e),i=Xt(t,e);return{oldValue:t,newValue:e,bodiesCreated:n.length>0?n:void 0,bodiesDeleted:o.length>0?o:void 0,bodiesUpdated:i.length>0?i:void 0,targetUpdated:Ut(t,e)?{oldTarget:t.target,newTarget:e.target}:void 0}};var L=(t=>(t.LOCAL="LOCAL",t.REMOTE="REMOTE",t))(L||{});const Dt=(t,e)=>{var n,o;const{changes:i,origin:s}=e;if(!(!t.options.origin||t.options.origin===s))return!1;if(t.options.ignore){const{ignore:r}=t.options,a=l=>l&&l.length>0;if(!(a(i.created)||a(i.deleted))){const l=(n=i.updated)==null?void 0:n.some(w=>a(w.bodiesCreated)||a(w.bodiesDeleted)||a(w.bodiesUpdated)),d=(o=i.updated)==null?void 0:o.some(w=>w.targetUpdated);if(r==="BODY_ONLY"&&l&&!d||r==="TARGET_ONLY"&&d&&!l)return!1}}if(t.options.annotations){const r=new Set([...(i.created||[]).map(a=>a.id),...(i.deleted||[]).map(a=>a.id),...(i.updated||[]).map(({oldValue:a})=>a.id)]);return!!(Array.isArray(t.options.annotations)?t.options.annotations:[t.options.annotations]).find(a=>r.has(a))}else return!0},Yt=(t,e)=>{const n=new Set((t.created||[]).map(u=>u.id)),o=new Set((t.updated||[]).map(({newValue:u})=>u.id)),i=new Set((e.created||[]).map(u=>u.id)),s=new Set((e.deleted||[]).map(u=>u.id)),r=new Set((e.updated||[]).map(({oldValue:u})=>u.id)),a=new Set((e.updated||[]).filter(({oldValue:u})=>n.has(u.id)||o.has(u.id)).map(({oldValue:u})=>u.id)),l=[...(t.created||[]).filter(u=>!s.has(u.id)).map(u=>r.has(u.id)?e.updated.find(({oldValue:T})=>T.id===u.id).newValue:u),...e.created||[]],d=[...(t.deleted||[]).filter(u=>!i.has(u.id)),...(e.deleted||[]).filter(u=>!n.has(u.id))],w=[...(t.updated||[]).filter(({newValue:u})=>!s.has(u.id)).map(u=>{const{oldValue:T,newValue:h}=u;if(r.has(h.id)){const A=e.updated.find(B=>B.oldValue.id===h.id).newValue;return dt(T,A)}else return u}),...(e.updated||[]).filter(({oldValue:u})=>!a.has(u.id))];return{created:l,deleted:d,updated:w}},It=t=>t.id!==void 0,Vt=()=>{const t=new Map,e=new Map,n=[],o=(p,x={})=>n.push({onChange:p,options:x}),i=p=>{const x=n.findIndex(y=>y.onChange==p);x>-1&&n.splice(x,1)},s=(p,x)=>{const y={origin:p,changes:{created:x.created||[],updated:x.updated||[],deleted:x.deleted||[]},state:[...t.values()]};n.forEach(v=>{Dt(v,y)&&v.onChange(y)})},r=(p,x=L.LOCAL)=>{if(t.get(p.id))throw Error(`Cannot add annotation ${p.id} - exists already`);t.set(p.id,p),p.bodies.forEach(y=>e.set(y.id,p.id)),s(x,{created:[p]})},a=(p,x)=>{const y=typeof p=="string"?x:p,v=typeof p=="string"?p:p.id,C=t.get(v);if(C){const O=dt(C,y);return v===y.id?t.set(v,y):(t.delete(v),t.set(y.id,y)),C.bodies.forEach(X=>e.delete(X.id)),y.bodies.forEach(X=>e.set(X.id,y.id)),O}else console.warn(`Cannot update annotation ${v} - does not exist`)},l=(p,x=L.LOCAL,y=L.LOCAL)=>{const v=It(x)?y:x,C=a(p,x);C&&s(v,{updated:[C]})},d=(p,x=L.LOCAL)=>{const y=p.reduce((v,C)=>{const O=a(C);return O?[...v,O]:v},[]);y.length>0&&s(x,{updated:y})},w=(p,x=L.LOCAL)=>{const y=t.get(p.annotation);if(y){const v={...y,bodies:[...y.bodies,p]};t.set(y.id,v),e.set(p.id,v.id),s(x,{updated:[{oldValue:y,newValue:v,bodiesCreated:[p]}]})}else console.warn(`Attempt to add body to missing annotation: ${p.annotation}`)},u=()=>[...t.values()],T=(p=L.LOCAL)=>{const x=[...t.values()];t.clear(),e.clear(),s(p,{deleted:x})},h=(p,x=!0,y=L.LOCAL)=>{if(x){const v=[...t.values()];t.clear(),e.clear(),p.forEach(C=>{t.set(C.id,C),C.bodies.forEach(O=>e.set(O.id,C.id))}),s(y,{created:p,deleted:v})}else{const v=p.reduce((C,O)=>{const X=t.get(O.id);return X?[...C,X]:C},[]);if(v.length>0)throw Error(`Bulk insert would overwrite the following annotations: ${v.map(C=>C.id).join(", ")}`);p.forEach(C=>{t.set(C.id,C),C.bodies.forEach(O=>e.set(O.id,C.id))}),s(y,{created:p})}},A=p=>{const x=typeof p=="string"?p:p.id,y=t.get(x);if(y)return t.delete(x),y.bodies.forEach(v=>e.delete(v.id)),y;console.warn(`Attempt to delete missing annotation: ${x}`)},B=(p,x=L.LOCAL)=>{const y=A(p);y&&s(x,{deleted:[y]})},b=(p,x=L.LOCAL)=>{const y=p.reduce((v,C)=>{const O=A(C);return O?[...v,O]:v},[]);y.length>0&&s(x,{deleted:y})},c=(p,x=L.LOCAL)=>{const y=t.get(p.annotation);if(y){const v=y.bodies.find(C=>C.id===p.id);if(v){e.delete(v.id);const C={...y,bodies:y.bodies.filter(O=>O.id!==p.id)};t.set(y.id,C),s(x,{updated:[{oldValue:y,newValue:C,bodiesDeleted:[v]}]})}else console.warn(`Attempt to delete missing body ${p.id} from annotation ${p.annotation}`)}else console.warn(`Attempt to delete body from missing annotation ${p.annotation}`)},f=p=>{const x=t.get(p);return x?{...x}:void 0},g=p=>{const x=e.get(p);if(x){const y=f(x).bodies.find(v=>v.id===p);if(y)return y;console.error(`Store integrity error: body ${p} in index, but not in annotation`)}else console.warn(`Attempt to retrieve missing body: ${p}`)},m=(p,x)=>{if(p.annotation!==x.annotation)throw"Annotation integrity violation: annotation ID must be the same when updating bodies";const y=t.get(p.annotation);if(y){const v=y.bodies.find(O=>O.id===p.id),C={...y,bodies:y.bodies.map(O=>O.id===v.id?x:O)};return t.set(y.id,C),v.id!==x.id&&(e.delete(v.id),e.set(x.id,C.id)),{oldValue:y,newValue:C,bodiesUpdated:[{oldBody:v,newBody:x}]}}else console.warn(`Attempt to add body to missing annotation ${p.annotation}`)},E=(p,x,y=L.LOCAL)=>{const v=m(p,x);v&&s(y,{updated:[v]})},S=(p,x=L.LOCAL)=>{const y=p.map(v=>m({id:v.id,annotation:v.annotation},v)).filter(Boolean);s(x,{updated:y})},M=p=>{const x=t.get(p.annotation);if(x){const y={...x,target:{...x.target,...p}};return t.set(x.id,y),{oldValue:x,newValue:y,targetUpdated:{oldTarget:x.target,newTarget:p}}}else console.warn(`Attempt to update target on missing annotation: ${p.annotation}`)};return{addAnnotation:r,addBody:w,all:u,bulkAddAnnotation:h,bulkDeleteAnnotation:b,bulkUpdateAnnotation:d,bulkUpdateBodies:S,bulkUpdateTargets:(p,x=L.LOCAL)=>{const y=p.map(v=>M(v)).filter(Boolean);y.length>0&&s(x,{updated:y})},clear:T,deleteAnnotation:B,deleteBody:c,getAnnotation:f,getBody:g,observe:o,unobserve:i,updateAnnotation:l,updateBody:E,updateTarget:(p,x=L.LOCAL)=>{const y=M(p);y&&s(x,{updated:[y]})}}};let _t=()=>({emit(t,...e){for(let n=0,o=this.events[t]||[],i=o.length;n<i;n++)o[n](...e)},events:{},on(t,e){var n;return((n=this.events)[t]||(n[t]=[])).push(e),()=>{var o;this.events[t]=(o=this.events[t])==null?void 0:o.filter(i=>e!==i)}}});const kt=250,Nt=t=>{const e=_t(),n=[];let o=-1,i=!1,s=0;const r=h=>{if(!i){const{changes:A}=h,B=performance.now();if(B-s>kt)n.splice(o+1),n.push(A),o=n.length-1;else{const b=n.length-1;n[b]=Yt(n[b],A)}s=B}i=!1};t.observe(r,{origin:L.LOCAL});const a=h=>h&&h.length>0&&t.bulkDeleteAnnotation(h),l=h=>h&&h.length>0&&t.bulkAddAnnotation(h,!1),d=h=>h&&h.length>0&&t.bulkUpdateAnnotation(h.map(({oldValue:A})=>A)),w=h=>h&&h.length>0&&t.bulkUpdateAnnotation(h.map(({newValue:A})=>A)),u=h=>h&&h.length>0&&t.bulkAddAnnotation(h,!1),T=h=>h&&h.length>0&&t.bulkDeleteAnnotation(h);return{canRedo:()=>n.length-1>o,canUndo:()=>o>-1,destroy:()=>t.unobserve(r),on:(h,A)=>e.on(h,A),redo:()=>{if(n.length-1>o){i=!0;const{created:h,updated:A,deleted:B}=n[o+1];l(h),w(A),T(B),e.emit("redo",n[o+1]),o+=1}},undo:()=>{if(o>-1){i=!0;const{created:h,updated:A,deleted:B}=n[o];a(h),d(A),u(B),e.emit("undo",n[o]),o-=1}}}},Pt=()=>{const{subscribe:t,set:e}=tt([]);return{subscribe:t,set:e}},zt=(t,e,n,o)=>{const{store:i,selection:s,hover:r,viewport:a}=t,l=new Map;let d=[],w,u;const T=(c,f)=>{l.has(c)?l.get(c).push(f):l.set(c,[f])},h=(c,f)=>{const g=l.get(c);g&&g.indexOf(f)>0&&g.splice(g.indexOf(f),1)},A=(c,f,g)=>{l.has(c)&&setTimeout(()=>{l.get(c).forEach(m=>{if(n){const E=Array.isArray(f)?f.map(M=>n.serialize(M)):n.serialize(f),S=g?g instanceof PointerEvent?g:n.serialize(g):void 0;m(E,S)}else m(f,g)})},1)},B=()=>{const{selected:c}=s,f=(c||[]).map(({id:g})=>i.getAnnotation(g));f.forEach(g=>{const m=d.find(E=>E.id===g.id);(!m||!I(m,g))&&A("updateAnnotation",g,m)}),d=d.map(g=>f.find(({id:E})=>E===g.id)||g)};s.subscribe(({selected:c})=>{if(!(d.length===0&&c.length===0)){if(d.length===0&&c.length>0)d=c.map(({id:f})=>i.getAnnotation(f));else if(d.length>0&&c.length===0)d.forEach(f=>{const g=i.getAnnotation(f.id);g&&!I(g,f)&&A("updateAnnotation",g,f)}),d=[];else{const f=new Set(d.map(m=>m.id)),g=new Set(c.map(({id:m})=>m));d.filter(m=>!g.has(m.id)).forEach(m=>{const E=i.getAnnotation(m.id);E&&!I(E,m)&&A("updateAnnotation",E,m)}),d=[...d.filter(m=>g.has(m.id)),...c.filter(({id:m})=>!f.has(m)).map(({id:m})=>i.getAnnotation(m))]}A("selectionChanged",d)}}),r.subscribe(c=>{!w&&c?A("mouseEnterAnnotation",i.getAnnotation(c)):w&&!c?A("mouseLeaveAnnotation",i.getAnnotation(w)):w&&c&&(A("mouseLeaveAnnotation",i.getAnnotation(w)),A("mouseEnterAnnotation",i.getAnnotation(c))),w=c}),a==null||a.subscribe(c=>A("viewportIntersect",c.map(f=>i.getAnnotation(f)))),i.observe(c=>{o&&(u&&clearTimeout(u),u=setTimeout(B,1e3));const{created:f,deleted:g}=c.changes;(f||[]).forEach(m=>A("createAnnotation",m)),(g||[]).forEach(m=>A("deleteAnnotation",m)),(c.changes.updated||[]).filter(m=>[...m.bodiesCreated||[],...m.bodiesDeleted||[],...m.bodiesUpdated||[]].length>0).forEach(({oldValue:m,newValue:E})=>{const S=d.find(M=>M.id===m.id)||m;d=d.map(M=>M.id===m.id?E:M),A("updateAnnotation",E,S)})},{origin:L.LOCAL}),i.observe(c=>{if(d){const f=new Set(d.map(m=>m.id)),g=(c.changes.updated||[]).filter(({newValue:m})=>f.has(m.id)).map(({newValue:m})=>m);g.length>0&&(d=d.map(m=>g.find(S=>S.id===m.id)||m))}},{origin:L.REMOTE});const b=c=>f=>{const{created:g,deleted:m,updated:E}=f;(g||[]).forEach(S=>A("createAnnotation",S)),(m||[]).forEach(S=>A("deleteAnnotation",S)),c?(E||[]).forEach(S=>A("updateAnnotation",S.oldValue,S.newValue)):(E||[]).forEach(S=>A("updateAnnotation",S.newValue,S.oldValue))};return e.on("undo",b(!0)),e.on("redo",b(!1)),{on:T,off:h,emit:A}},Ht=t=>e=>e.reduce((n,o)=>{const{parsed:i,error:s}=t.parse(o);return s?{parsed:n.parsed,failed:[...n.failed,o]}:i?{parsed:[...n.parsed,i],failed:n.failed}:{...n}},{parsed:[],failed:[]}),Wt=(t,e,n)=>{const{store:o,selection:i}=t,s=b=>{if(n){const{parsed:c,error:f}=n.parse(b);c?o.addAnnotation(c,L.REMOTE):console.error(f)}else o.addAnnotation(b,L.REMOTE)},r=()=>i.clear(),a=()=>o.clear(),l=b=>{const c=o.getAnnotation(b);return n&&c?n.serialize(c):c},d=()=>n?o.all().map(n.serialize):o.all(),w=()=>{var b;const c=(((b=i.selected)==null?void 0:b.map(f=>f.id))||[]).map(f=>o.getAnnotation(f)).filter(Boolean);return n?c.map(n.serialize):c},u=b=>fetch(b).then(c=>c.json()).then(c=>(h(c),c)),T=b=>{if(typeof b=="string"){const c=o.getAnnotation(b);if(o.deleteAnnotation(b),c)return n?n.serialize(c):c}else{const c=n?n.parse(b).parsed:b;if(c)return o.deleteAnnotation(c),b}},h=b=>{if(n){const{parsed:c,failed:f}=Ht(n)(b);f.length>0&&console.warn(`Discarded ${f.length} invalid annotations`,f),o.bulkAddAnnotation(c,!0,L.REMOTE)}else o.bulkAddAnnotation(b,!0,L.REMOTE)},A=b=>{b?i.setSelected(b):i.clear()},B=b=>{if(n){const c=n.parse(b).parsed,f=n.serialize(o.getAnnotation(c.id));return o.updateAnnotation(c),f}else{const c=o.getAnnotation(b.id);return o.updateAnnotation(b),c}};return{addAnnotation:s,cancelSelected:r,canRedo:e.canRedo,canUndo:e.canUndo,clearAnnotations:a,getAnnotationById:l,getAnnotations:d,getSelected:w,loadAnnotations:u,redo:e.redo,removeAnnotation:T,setAnnotations:h,setSelected:A,undo:e.undo,updateAnnotation:B}};let $t=t=>crypto.getRandomValues(new Uint8Array(t)),Ft=(t,e,n)=>{let o=(2<<Math.log(t.length-1)/Math.LN2)-1,i=-~(1.6*o*e/t.length);return(s=e)=>{let r="";for(;;){let a=n(i),l=i;for(;l--;)if(r+=t[a[l]&o]||"",r.length===s)return r}}},qt=(t,e=21)=>Ft(t,e,$t),jt=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,n)=>(n&=63,n<36?e+=n.toString(36):n<62?e+=(n-26).toString(36).toUpperCase():n>62?e+="-":e+="_",e),"");const Jt=()=>({isGuest:!0,id:qt("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_",20)()}),Qt=t=>{const e=JSON.stringify(t);let n=0;for(let o=0,i=e.length;o<i;o++){let s=e.charCodeAt(o);n=(n<<5)-n+s,n|=0}return`${n}`},ut=t=>t?typeof t=="object"?{...t}:t:void 0,Gt=(t,e)=>(Array.isArray(t)?t:[t]).map(n=>{const{id:o,type:i,purpose:s,value:r,created:a,creator:l,...d}=n;return{id:o||`temp-${Qt(n)}`,annotation:e,type:i,purpose:s,value:r,created:a?new Date(a):void 0,creator:ut(l),...d}}),Kt=t=>t.map(e=>{var n,o;const i={...e};return delete i.annotation,(n=i.id)!=null&&n.startsWith("temp-")&&delete i.id,{...i,created:(o=i.created)==null?void 0:o.toISOString()}});jt();const D=(t,e)=>{const{start:n,end:o}=t.selector,i=t.selector.offsetReference?t.selector.offsetReference:e;if(!i)return t;const s=document.createNodeIterator(e,NodeFilter.SHOW_TEXT);let r=0,a=document.createRange(),l=s.nextNode();l===null&&console.error("Could not revive annotation target. Content missing.");let d=!i;for(;l!==null;){const w=l.textContent.length;if(!d&&i&&(d=i.contains(l)),d){if(r+w>n){a.setStart(l,n-r);break}r+=w}l=s.nextNode()}for(;l!==null;){const w=l.textContent.length;if(r+w>o){a.setEnd(l,o-r);break}r+=w,l=s.nextNode()}return{...t,selector:{...t.selector,range:a}}};function Zt(t,e,n,o,i){ht(t,e,n||0,o||t.length-1,i||te)}function ht(t,e,n,o,i){for(;o>n;){if(o-n>600){var s=o-n+1,r=e-n+1,a=Math.log(s),l=.5*Math.exp(2*a/3),d=.5*Math.sqrt(a*l*(s-l)/s)*(r-s/2<0?-1:1),w=Math.max(n,Math.floor(e-r*l/s+d)),u=Math.min(o,Math.floor(e+(s-r)*l/s+d));ht(t,e,w,u,i)}var T=t[e],h=n,A=o;for(P(t,n,e),i(t[o],T)>0&&P(t,n,o);h<A;){for(P(t,h,A),h++,A--;i(t[h],T)<0;)h++;for(;i(t[A],T)>0;)A--}i(t[n],T)===0?P(t,n,A):(A++,P(t,A,o)),A<=e&&(n=A+1),e<=A&&(o=A-1)}}function P(t,e,n){var o=t[e];t[e]=t[n],t[n]=o}function te(t,e){return t<e?-1:t>e?1:0}class ee{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.4)),this.clear()}all(){return this._all(this.data,[])}search(e){let n=this.data;const o=[];if(!q(e,n))return o;const i=this.toBBox,s=[];for(;n;){for(let r=0;r<n.children.length;r++){const a=n.children[r],l=n.leaf?i(a):a;q(e,l)&&(n.leaf?o.push(a):ot(e,l)?this._all(a,o):s.push(a))}n=s.pop()}return o}collides(e){let n=this.data;if(!q(e,n))return!1;const o=[];for(;n;){for(let i=0;i<n.children.length;i++){const s=n.children[i],r=n.leaf?this.toBBox(s):s;if(q(e,r)){if(n.leaf||ot(e,r))return!0;o.push(s)}}n=o.pop()}return!1}load(e){if(!(e&&e.length))return this;if(e.length<this._minEntries){for(let o=0;o<e.length;o++)this.insert(e[o]);return this}let n=this._build(e.slice(),0,e.length-1,0);if(!this.data.children.length)this.data=n;else if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){const o=this.data;this.data=n,n=o}this._insert(n,this.data.height-n.height-1,!0)}return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=k([]),this}remove(e,n){if(!e)return this;let o=this.data;const i=this.toBBox(e),s=[],r=[];let a,l,d;for(;o||s.length;){if(o||(o=s.pop(),l=s[s.length-1],a=r.pop(),d=!0),o.leaf){const w=ne(e,o.children,n);if(w!==-1)return o.children.splice(w,1),s.push(o),this._condense(s),this}!d&&!o.leaf&&ot(o,i)?(s.push(o),r.push(a),a=0,l=o,o=o.children[0]):l?(a++,o=l.children[a],d=!1):o=null}return this}toBBox(e){return e}compareMinX(e,n){return e.minX-n.minX}compareMinY(e,n){return e.minY-n.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,n){const o=[];for(;e;)e.leaf?n.push(...e.children):o.push(...e.children),e=o.pop();return n}_build(e,n,o,i){const s=o-n+1;let r=this._maxEntries,a;if(s<=r)return a=k(e.slice(n,o+1)),_(a,this.toBBox),a;i||(i=Math.ceil(Math.log(s)/Math.log(r)),r=Math.ceil(s/Math.pow(r,i-1))),a=k([]),a.leaf=!1,a.height=i;const l=Math.ceil(s/r),d=l*Math.ceil(Math.sqrt(r));ft(e,n,o,d,this.compareMinX);for(let w=n;w<=o;w+=d){const u=Math.min(w+d-1,o);ft(e,w,u,l,this.compareMinY);for(let T=w;T<=u;T+=l){const h=Math.min(T+l-1,u);a.children.push(this._build(e,T,h,i-1))}}return _(a,this.toBBox),a}_chooseSubtree(e,n,o,i){for(;i.push(n),!(n.leaf||i.length-1===o);){let s=1/0,r=1/0,a;for(let l=0;l<n.children.length;l++){const d=n.children[l],w=nt(d),u=se(e,d)-w;u<r?(r=u,s=w<s?w:s,a=d):u===r&&w<s&&(s=w,a=d)}n=a||n.children[0]}return n}_insert(e,n,o){const i=o?e:this.toBBox(e),s=[],r=this._chooseSubtree(i,this.data,n,s);for(r.children.push(e),H(r,i);n>=0&&s[n].children.length>this._maxEntries;)this._split(s,n),n--;this._adjustParentBBoxes(i,s,n)}_split(e,n){const o=e[n],i=o.children.length,s=this._minEntries;this._chooseSplitAxis(o,s,i);const r=this._chooseSplitIndex(o,s,i),a=k(o.children.splice(r,o.children.length-r));a.height=o.height,a.leaf=o.leaf,_(o,this.toBBox),_(a,this.toBBox),n?e[n-1].children.push(a):this._splitRoot(o,a)}_splitRoot(e,n){this.data=k([e,n]),this.data.height=e.height+1,this.data.leaf=!1,_(this.data,this.toBBox)}_chooseSplitIndex(e,n,o){let i,s=1/0,r=1/0;for(let a=n;a<=o-n;a++){const l=z(e,0,a,this.toBBox),d=z(e,a,o,this.toBBox),w=re(l,d),u=nt(l)+nt(d);w<s?(s=w,i=a,r=u<r?u:r):w===s&&u<r&&(r=u,i=a)}return i||o-n}_chooseSplitAxis(e,n,o){const i=e.leaf?this.compareMinX:oe,s=e.leaf?this.compareMinY:ie,r=this._allDistMargin(e,n,o,i),a=this._allDistMargin(e,n,o,s);r<a&&e.children.sort(i)}_allDistMargin(e,n,o,i){e.children.sort(i);const s=this.toBBox,r=z(e,0,n,s),a=z(e,o-n,o,s);let l=F(r)+F(a);for(let d=n;d<o-n;d++){const w=e.children[d];H(r,e.leaf?s(w):w),l+=F(r)}for(let d=o-n-1;d>=n;d--){const w=e.children[d];H(a,e.leaf?s(w):w),l+=F(a)}return l}_adjustParentBBoxes(e,n,o){for(let i=o;i>=0;i--)H(n[i],e)}_condense(e){for(let n=e.length-1,o;n>=0;n--)e[n].children.length===0?n>0?(o=e[n-1].children,o.splice(o.indexOf(e[n]),1)):this.clear():_(e[n],this.toBBox)}}function ne(t,e,n){if(!n)return e.indexOf(t);for(let o=0;o<e.length;o++)if(n(t,e[o]))return o;return-1}function _(t,e){z(t,0,t.children.length,e,t)}function z(t,e,n,o,i){i||(i=k(null)),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let s=e;s<n;s++){const r=t.children[s];H(i,t.leaf?o(r):r)}return i}function H(t,e){return t.minX=Math.min(t.minX,e.minX),t.minY=Math.min(t.minY,e.minY),t.maxX=Math.max(t.maxX,e.maxX),t.maxY=Math.max(t.maxY,e.maxY),t}function oe(t,e){return t.minX-e.minX}function ie(t,e){return t.minY-e.minY}function nt(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function F(t){return t.maxX-t.minX+(t.maxY-t.minY)}function se(t,e){return(Math.max(e.maxX,t.maxX)-Math.min(e.minX,t.minX))*(Math.max(e.maxY,t.maxY)-Math.min(e.minY,t.minY))}function re(t,e){const n=Math.max(t.minX,e.minX),o=Math.max(t.minY,e.minY),i=Math.min(t.maxX,e.maxX),s=Math.min(t.maxY,e.maxY);return Math.max(0,i-n)*Math.max(0,s-o)}function ot(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function q(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function k(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function ft(t,e,n,o,i){const s=[e,n];for(;s.length;){if(n=s.pop(),e=s.pop(),n-e<=o)continue;const r=e+Math.ceil((n-e)/o/2)*o;Zt(t,r,e,n,i),s.push(e,r,r,n)}}const ae=(t,e,n=10,o)=>{const i=o?t.startContainer.parentElement.closest(o):e,s=document.createRange();s.setStart(i,0),s.setEnd(t.startContainer,t.startOffset);const r=s.toString(),a=document.createRange();a.setStart(t.endContainer,t.endOffset),i===document.body?a.setEnd(i,i.childNodes.length):a.setEndAfter(i);const l=a.toString();return{prefix:r.substring(r.length-n),suffix:l.substring(0,n)}},ce=(t,e)=>{const n=s=>Math.round(s*10)/10,o={top:n(t.top),bottom:n(t.bottom),left:n(t.left),right:n(t.right)},i={top:n(e.top),bottom:n(e.bottom),left:n(e.left),right:n(e.right)};if(Math.abs(o.top-i.top)<.5&&Math.abs(o.bottom-i.bottom)<.5){if(Math.abs(o.left-i.right)<.5||Math.abs(o.right-i.left)<.5)return"inline-adjacent";if(o.left>=i.left&&o.right<=i.right)return"inline-is-contained";if(o.left<=i.left&&o.right>=i.right)return"inline-contains"}else if(o.top<=i.top&&o.bottom>=i.bottom){if(o.left<=i.left&&o.right>=i.right)return"block-contains"}else if(o.top>=i.top&&o.bottom<=i.bottom&&o.left>=i.left&&o.right<=i.right)return"block-is-contained"},le=(t,e)=>{const n=Math.min(t.left,e.left),o=Math.max(t.right,e.right),i=Math.min(t.top,e.top),s=Math.max(t.bottom,e.bottom);return new DOMRect(n,i,o-n,s-i)},de=t=>t.reduce((e,n)=>{if(n.width===0||n.height===0)return e;let o=[...e],i=!1;for(const s of e){const r=ce(n,s);if(r==="inline-adjacent"){o=o.map(a=>a===s?le(n,s):a),i=!0;break}else if(r==="inline-contains"){o=o.map(a=>a===s?n:a),i=!0;break}else if(r==="inline-is-contained"){i=!0;break}else if(r==="block-contains"||r==="block-is-contained"){n.width<s.width&&(o=o.map(a=>a===s?n:a)),i=!0;break}}return i?o:[...o,n]},[]),ue=t=>{var i;const{startContainer:e,endContainer:n}=t;if(e.nodeType===Node.TEXT_NODE&&n.nodeType===Node.TEXT_NODE)return t;if(e.nodeType!==Node.TEXT_NODE){const s=e.nextSibling||e.parentNode,r=(s==null?void 0:s.nodeType)===Node.TEXT_NODE?s:Array.from(s.childNodes).filter(a=>a.nodeType===Node.TEXT_NODE).shift();t.setEnd(r,0)}if(n.nodeType!==Node.TEXT_NODE){const s=n.previousSibling||n.parentNode,r=(s==null?void 0:s.nodeType)===Node.TEXT_NODE?s:Array.from(s.childNodes).filter(a=>a.nodeType===Node.TEXT_NODE).pop();t.setEnd(r,((i=r==null?void 0:r.textContent)==null?void 0:i.length)||0)}return t},he=(t,e)=>{const n=new ee,o=new Map,i=c=>{const f=e.getBoundingClientRect(),m=c.selector.range instanceof Range&&!c.selector.range.collapsed&&c.selector.range.startContainer.nodeType===Node.TEXT_NODE&&c.selector.range.endContainer.nodeType===Node.TEXT_NODE?c:D(c,e),E=Array.from(m.selector.range.getClientRects()),S=de(E);return S.map(M=>{const{x:p,y:x,width:y,height:v}=M;return{minX:p-f.x,minY:x-f.y,maxX:p-f.x+y,maxY:x-f.y+v,annotation:{id:c.annotation,rects:S}}})},s=()=>[...o.values()],r=()=>{n.clear(),o.clear()},a=c=>{const f=i(c);f.forEach(g=>n.insert(g)),o.set(c.annotation,f)},l=c=>{o.get(c.annotation).forEach(g=>n.remove(g)),o.delete(c.annotation)},d=c=>{l(c),a(c)},w=(c,f=!0)=>{f&&r();const g=c.map(E=>({target:E,rects:i(E)}));g.forEach(({target:E,rects:S})=>o.set(E.annotation,S));const m=g.reduce((E,{rects:S})=>[...E,...S],[]);n.load(m)},u=(c,f)=>{const g=n.search({minX:c,minY:f,maxX:c,maxY:f}),m=E=>E.annotation.rects.reduce((S,M)=>S+M.width*M.height,0);if(g.length>0)return g.sort((E,S)=>m(E)-m(S)),g[0].annotation.id},T=c=>{const f=h(c);if(f.length===0)return;let g=f[0].left,m=f[0].top,E=f[0].right,S=f[0].bottom;for(let M=1;M<f.length;M++){const p=f[M];g=Math.min(g,p.left),m=Math.min(m,p.top),E=Math.max(E,p.right),S=Math.max(S,p.bottom)}return new DOMRect(g,m,E-g,S-m)},h=c=>{const f=o.get(c);return f?f[0].annotation.rects:[]};return{all:s,clear:r,getAt:u,getBoundsForAnnotation:T,getDOMRectsForAnnotation:h,getIntersectingRects:(c,f,g,m)=>n.search({minX:c,minY:f,maxX:g,maxY:m}),insert:a,recalculate:()=>w(t.all().map(c=>c.target),!0),remove:l,set:w,size:()=>n.all().length,update:d}},j=t=>{const{range:e}=t.target.selector;return e instanceof Range&&!e.collapsed},gt=(t,e)=>{const n=Vt(),o=he(n,t),i=Ct(n,e),s=Bt(n),r=Pt(),a=(b,c=L.LOCAL)=>{const f=b.target.selector.range instanceof Range?b:{...b,target:D(b.target,t)},{range:g}=f.target.selector,m=g&&!g.collapsed;return m&&n.addAnnotation(f,c),m},l=(b,c=!0,f=L.LOCAL)=>{const g=b.map(E=>j(E)?E:{...E,target:D(E.target,t)});if(g.some(E=>E.target.selector.range.collapsed)){const E=g.filter(S=>S.target.selector.range.collapsed);return console.warn("Could not revive all targets"),console.warn(E),n.bulkAddAnnotation(g,c,f),E}else return n.bulkAddAnnotation(g,c,f),[]},d=(b,c=L.LOCAL)=>{const f=b.selector.range instanceof Range?b:D(b,t);n.updateTarget(f,c)},w=(b,c=L.LOCAL)=>{const f=b.map(g=>g.selector.range instanceof Range?g:D(g,t));n.bulkUpdateTargets(f,c)},u=(b,c)=>{const f=o.getAt(b,c);return f?n.getAnnotation(f):void 0},T=(b,c,f,g)=>{const m=o.getIntersectingRects(b,c,f,g);return Array.from(new Set(m.map(S=>S.annotation.id))).map(S=>n.getAnnotation(S)).filter(S=>S)},h=(b,c,f,g=5)=>{const m=o.getDOMRectsForAnnotation(b);if(m.length>0){if(c&&f){const E=m.find(({top:S,right:M,bottom:p,left:x})=>c>=x-g&&c<=M+g&&f>=S-g&&f<=p+g);if(E)return E}return o.getBoundsForAnnotation(b)}},A=(b,c,f,g)=>{const E=o.getIntersectingRects(b,c,f,g).reduce((S,M)=>((S[M.annotation.id]=S[M.annotation.id]||[]).push(M),S),{});return Object.entries(E).map(([S,M])=>({annotation:n.getAnnotation(S),rects:M.map(({minX:p,minY:x,maxX:y,maxY:v})=>({x:p,y:x,width:y-p,height:v-x}))}))},B=()=>o.recalculate();return n.observe(({changes:b})=>{const c=(b.created||[]).filter(j),f=(b.deleted||[]).filter(j),g=(b.updated||[]).filter(m=>j(m.newValue));c.length>0&&o.set(c.map(m=>m.target),!1),(f==null?void 0:f.length)>0&&f.forEach(m=>o.remove(m.target)),(g==null?void 0:g.length)>0&&g.forEach(({newValue:m})=>o.update(m.target))}),{store:{...n,addAnnotation:a,bulkAddAnnotation:l,bulkUpdateTargets:w,getAnnotationBounds:h,getAt:u,getIntersecting:T,getIntersectingRects:A,recalculatePositions:B,updateTarget:d},selection:i,hover:s,viewport:r}},fe=(t,e)=>({parse:n=>pt(n,e),serialize:n=>mt(n,t,e)}),pt=(t,e)=>{const n=t.id||ct(),{creator:o,created:i,modified:s,body:r,...a}=t,l=Gt(r,n),d=Array.isArray(t.target)?t.target[0]:t.target,u=(Array.isArray(d.selector)?d.selector:[d.selector]).reduce((h,A)=>{switch(A.type){case"TextQuoteSelector":h.quote=A.exact;break;case"TextPositionSelector":h.start=A.start,h.end=A.end;break}return h},{});if((h=>h.quote!==void 0&&h.start!==void 0&&h.end!==void 0)(u))return{parsed:{...a,id:n,bodies:l,target:D({...a.target,created:i?new Date(i):void 0,creator:ut(o),updated:s?new Date(s):void 0,annotation:n,selector:u},e)}};{const h=[u.start?void 0:"TextPositionSelector",u.quote?void 0:"TextQuoteSelector"].filter(Boolean);return{error:Error(`Missing selector types: ${h.join(" and ")}`)}}},mt=(t,e,n)=>{const{bodies:o,target:i,...s}=t,{selector:r,creator:a,created:l,updated:d,...w}=i,{quote:u,start:T,end:h,range:A}=r,{prefix:B,suffix:b}=ae(A,n),c=[{type:"TextQuoteSelector",exact:u,prefix:B,suffix:b},{type:"TextPositionSelector",start:T,end:h}];return{...s,"@context":"http://www.w3.org/ns/anno.jsonld",id:t.id,type:"Annotation",body:Kt(t.bodies),creator:a,created:l==null?void 0:l.toISOString(),modified:d==null?void 0:d.toISOString(),target:{...w,source:e,selector:c}}},ge=(t,e={})=>{const n=new Map,o=s=>Array.from(n.entries()).filter(([r,a])=>a.presenceKey===s.presenceKey).map(([r,a])=>r);return t.on("selectionChange",(s,r)=>{o(s).forEach(l=>n.delete(l)),r&&r.forEach(l=>n.set(l,s))}),{paint:(s,r,a,l,d,w)=>{e.font&&(l.font=e.font);const u=n.get(s.id);if(u){const{x:T,y:h,height:A}=r[0];l.fillStyle=u.appearance.color,l.fillRect(T-2,h-2.5,2,A+5);const B=l.measureText(u.appearance.label),b=B.width+6,c=B.actualBoundingBoxAscent+B.actualBoundingBoxDescent+8,f=B.fontBoundingBoxAscent?8:6.5;l.fillRect(T-2,h-2.5-c,b,c),l.fillStyle="#fff",l.fillText(u.appearance.label,T+1,h-f),a.fillStyle=u.appearance.color,a.globalAlpha=d?.45:.18,r.forEach(({x:g,y:m,width:E,height:S})=>a.fillRect(g,m-2.5,E,S+5))}else K.paint(s,r,a,l,d,w)}}},bt=t=>{if(t===null)return document.scrollingElement;const{overflowY:e}=window.getComputedStyle(t);return e!=="visible"&&e!=="hidden"&&t.scrollHeight>t.clientHeight?t:bt(t.parentElement)},pe=(t,e)=>n=>{const o=s=>{const r=i.getBoundingClientRect(),a=i.clientHeight,l=i.clientWidth,d=s.selector.range.getBoundingClientRect(),{width:w,height:u}=e.getAnnotationBounds(n.id),T=d.top-r.top,h=d.left-r.left,A=i.parentElement?i.scrollTop:0,B=i.parentElement?i.scrollLeft:0,b=T+A-(a-u)/2,c=h+B-(l-w)/2;i.scroll({top:b,left:c,behavior:"smooth"})},i=bt(t);if(i){const s=e.getAnnotation(n.id),{range:r}=s.target.selector;if(r&&!r.collapsed)return o(s.target),!0;{const a=D(s.target,t);if(a.selector.range&&!a.selector.range.collapsed)return o(a),!0}}return!1},me=(t,e,n)=>{const o=document.createRange(),i=n?t.startContainer.parentElement.closest(n):e;o.setStart(i,0),o.setEnd(t.startContainer,t.startOffset);const s=t.toString(),r=o.toString().length,a=r+s.length;return n?{quote:s,start:r,end:a,range:t,offsetReference:i}:{quote:s,start:r,end:a,range:t}},be=(t,e,n)=>{const{store:o,selection:i}=e;let s,r;const a=h=>s=h;let l=!1,d;const w=h=>{var B;if(!l)return;!((B=h.target.parentElement)!=null&&B.closest(".not-annotatable"))?r={annotation:ct(),selector:void 0,creator:s,created:new Date}:r=void 0};t.addEventListener("selectstart",w);let u;const T=h=>{var B;const A=document.getSelection();if(h.timeStamp-d.timeStamp<1e3&&!r&&w(d),!A.isCollapsed&&l&&r){const b=Array.from(Array(A.rangeCount).keys()).map(g=>A.getRangeAt(g));ue(b[0]).toString()!==((B=r.selector)==null?void 0:B.quote)&&(r={...r,selector:me(b[0],t,n)},o.getAnnotation(r.annotation)?o.updateTarget(r,L.LOCAL):(o.addAnnotation({id:r.annotation,bodies:[],target:r}),i.clickSelect(r.annotation,d)))}};return document.addEventListener("selectionchange",h=>{u&&clearTimeout(u),u=setTimeout(()=>T(h),10)}),t.addEventListener("pointerdown",h=>{const{target:A,timeStamp:B,offsetX:b,offsetY:c,type:f}=h;d={...h,target:A,timeStamp:B,offsetX:b,offsetY:c,type:f},l=h.button===0}),document.addEventListener("pointerup",h=>{var c;if(!!((c=h.target.parentElement)!=null&&c.closest(".not-annotatable"))||!l)return;const B=()=>{const{x:f,y:g}=t.getBoundingClientRect(),m=o.getAt(h.clientX-f,h.clientY-g);if(m){const{selected:E}=i;(E.length!==1||E[0].id!==m.id)&&i.clickSelect(m.id,h)}else i.isEmpty()||i.clear()},b=h.timeStamp-d.timeStamp;document.getSelection().isCollapsed&&b<300?(r=void 0,B()):i.clickSelect(r.annotation,h)}),{setUser:a}},Ae=(t,e={})=>{t.addEventListener("click",g=>g.preventDefault());const n=gt(t,e.pointerAction),{selection:o,viewport:i}=n,s=n.store,r=Nt(s),a=zt(n,r,e.adapter);let l=Jt();const d=rt(t,n,i);e.style&&d.setDrawingStyle(e.style);const w=be(t,n,e.offsetReferenceSelector);return w.setUser(l),{...Wt(n,r,e.adapter),destroy:()=>{throw"Not implemented yet"},element:t,getUser:()=>l,setFilter:g=>d.setFilter(g),setStyle:g=>d.setDrawingStyle(g),setUser:g=>{l=g,w.setUser(g)},setSelected:g=>{g?o.setSelected(g):o.clear()},setPresenceProvider:g=>{g&&(d.setPainter(ge(g,e.presence)),g.on("selectionChange",()=>d.redraw()))},on:a.on,off:a.off,scrollIntoView:pe(t,s),state:n}};U.Origin=L,U.W3CTextFormat=fe,U.createHighlightLayer=rt,U.createTextAnnotator=Ae,U.createTextAnnotatorState=gt,U.defaultPainter=K,U.parseW3CTextAnnotation=pt,U.reviveTarget=D,U.serializeW3CTextAnnotation=mt,Object.defineProperty(U,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=text-annotator.umd.js.map