@recogito/text-annotator 3.0.0-rc.2 → 3.0.0-rc.4

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