@recogito/text-annotator 3.1.2 → 3.1.3

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,3 +1,3 @@
1
- (function(S,D){typeof exports=="object"&&typeof module<"u"?D(exports,require("colord"),require("dequal/lite"),require("uuid"),require("@annotorious/core"),require("rbush"),require("hotkeys-js")):typeof define=="function"&&define.amd?define(["exports","colord","dequal/lite","uuid","@annotorious/core","rbush","hotkeys-js"],D):(S=typeof globalThis<"u"?globalThis:S||self,D(S.RecogitoJS={},S.Colord,S.DequalLite,S.UUID,S.AnnotoriousCore,S.RBush,S.HotkeysJs))})(this,(function(S,D,Oe,ee,x,ke,z){"use strict";const Q="not-annotatable",M=`.${Q}`,K=(e,n)=>{var o;return e.contains(n)?!!(n instanceof HTMLElement?n.closest(M):(o=n.parentElement)==null?void 0:o.closest(M)):!0},te=(e,n)=>{const t=n.commonAncestorContainer;return!K(e,t)},ne=e=>e.addEventListener("click",n=>{!n.target.closest(M)&&!n.target.closest("a")&&n.preventDefault()}),X=e=>({...e,type:e.type,x:e.x,y:e.y,clientX:e.clientX,clientY:e.clientY,offsetX:e.offsetX,offsetY:e.offsetY,screenX:e.screenX,screenY:e.screenY,isPrimary:e.isPrimary,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,shiftKey:e.shiftKey,button:e.button,buttons:e.buttons,currentTarget:e.currentTarget,target:e.target,defaultPrevented:e.defaultPrevented,detail:e.detail,eventPhase:e.eventPhase,pointerId:e.pointerId,pointerType:e.pointerType,timeStamp:e.timeStamp}),$=e=>({...e,type:e.type,key:e.key,code:e.code,location:e.location,repeat:e.repeat,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,shiftKey:e.shiftKey,currentTarget:e.currentTarget,target:e.target,defaultPrevented:e.defaultPrevented,detail:e.detail,timeStamp:e.timeStamp}),oe=typeof navigator<"u"&&/mac/i.test(navigator.userAgentData?navigator.userAgentData.platform:navigator.platform),se=e=>{!e.hasAttribute("tabindex")&&e.tabIndex<0&&e.setAttribute("tabindex","-1"),e.classList.add("no-focus-outline")},W=(e,n=10)=>{let t;return((...o)=>{clearTimeout(t),t=setTimeout(()=>e.apply(void 0,o),n)})},Ne=function*(e){const n=document.createNodeIterator(e.commonAncestorContainer,NodeFilter.SHOW_ELEMENT,o=>o instanceof HTMLElement&&o.classList.contains(Q)&&!o.parentElement.closest(M)&&e.intersectsNode(o)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);let t;for(;t=n.nextNode();)t instanceof HTMLElement&&(yield t)},re=(e,n)=>{if(!te(e,n))return[];const t=[];let o=null;for(const s of Ne(n)){let r;o?(r=document.createRange(),r.setStartAfter(o),r.setEndBefore(s)):(r=n.cloneRange(),r.setEndBefore(s)),r.collapsed||t.push(r),o=s}if(o){const s=n.cloneRange();s.setStartAfter(o),s.collapsed||t.push(s)}return t.length>0?t:[n]},j=e=>{const n=e.cloneContents();return n.querySelectorAll(M).forEach(t=>t.remove()),n},ie=(e,n,t=10,o)=>{const s=o?e.startContainer.parentElement.closest(o):n,r=document.createRange();r.setStart(s,0),r.setEnd(e.startContainer,e.startOffset);const l=j(r).textContent,u=document.createRange();u.setStart(e.endContainer,e.endOffset),s===document.body?u.setEnd(s,s.childNodes.length):u.setEndAfter(s);const m=j(u).textContent;return{prefix:l.substring(l.length-t),suffix:m.substring(0,t)}},P=e=>e.every(n=>n.range instanceof Range&&!n.range.collapsed),ae=/^\s*$/,ce=e=>ae.test(e.toString()),Be=(e,n)=>{const t=r=>Math.round(r*10)/10,o={top:t(e.top),bottom:t(e.bottom),left:t(e.left),right:t(e.right)},s={top:t(n.top),bottom:t(n.bottom),left:t(n.left),right:t(n.right)};if(Math.abs(o.top-s.top)<.5&&Math.abs(o.bottom-s.bottom)<.5){if(Math.abs(o.left-s.right)<.5||Math.abs(o.right-s.left)<.5)return"inline-adjacent";if(o.left>=s.left&&o.right<=s.right)return"inline-is-contained";if(o.left<=s.left&&o.right>=s.right)return"inline-contains"}else if(o.top<=s.top&&o.bottom>=s.bottom){if(o.left<=s.left&&o.right>=s.right)return"block-contains"}else if(o.top>=s.top&&o.bottom<=s.bottom&&o.left>=s.left&&o.right<=s.right)return"block-is-contained"},Ie=(e,n)=>{const t=Math.min(e.left,n.left),o=Math.max(e.right,n.right),s=Math.min(e.top,n.top),r=Math.max(e.bottom,n.bottom);return new DOMRect(t,s,o-t,r-s)},le=e=>e.reduce((n,t)=>{if(t.width===0||t.height===0)return n;let o=[...n],s=!1;for(const r of n){const l=Be(t,r);if(l==="inline-adjacent"){o=o.map(u=>u===r?Ie(t,r):u),s=!0;break}else if(l==="inline-contains"){o=o.map(u=>u===r?t:u),s=!0;break}else if(l==="inline-is-contained"){s=!0;break}else if(l==="block-contains"||l==="block-is-contained"){t.width<r.width&&(o=o.map(u=>u===r?t:u)),s=!0;break}}return s?o:[...o,t]},[]),Pe=e=>({length:e.length,item:n=>e[n],[Symbol.iterator]:function*(){for(let n=0;n<this.length;n++)yield this.item(n)}}),de=(e,n,t)=>{const o=document.createRange(),s=t?e.startContainer.parentElement.closest(t):n;o.setStart(s,0),o.setEnd(e.startContainer,e.startOffset);const r=j(o).textContent,l=e.toString(),u=r.length||0,m=u+l.length;return t?{quote:l,start:u,end:m,range:e,offsetReference:s}:{quote:l,start:u,end:m,range:e}},J=(e,n)=>{var p,d;const{start:t,end:o}=e,s=e.offsetReference||n,r=document.createNodeIterator(n,NodeFilter.SHOW_TEXT,i=>{var T;return(T=i.parentElement)!=null&&T.closest(M)?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT});let l=0;const u=document.createRange();let m=r.nextNode();m===null&&console.error("Could not revive annotation target. Content missing.");let C=!s;for(;m!==null;){if(C||(C=typeof(s==null?void 0:s.contains)=="function"?s.contains(m):!1),C){const i=((p=m.textContent)==null?void 0:p.length)||0;if(l+i>t){u.setStart(m,t-l);break}l+=i}m=r.nextNode()}for(;m!==null;){const i=((d=m.textContent)==null?void 0:d.length)||0;if(l+i>=o){u.setEnd(m,o-l);break}l+=i,m=r.nextNode()}return{...e,range:u}},V=(e,n)=>P(e.selector)?e:{...e,selector:e.selector.map(t=>t.range instanceof Range&&!t.range.collapsed?t:J(t,n))},G=(e,n)=>P(e.target.selector)?e:{...e,target:V(e.target,n)},ue=(e,n)=>{const t=e.cloneRange();return n.contains(t.startContainer)||t.setStart(n,0),n.contains(t.endContainer)||t.setEnd(n,n.childNodes.length),t},fe=e=>{if(e===null)return document.scrollingElement;const{overflowY:n}=window.getComputedStyle(e);return n!=="visible"&&n!=="hidden"&&e.scrollHeight>e.clientHeight?e:fe(e.parentElement)},ge=(e,n)=>t=>{const o=typeof t=="string"?t:t.id,s=p=>{const d=r.getBoundingClientRect(),i=r.clientHeight,T=r.clientWidth,E=p.selector[0].range.getBoundingClientRect(),{width:w,height:v}=n.getAnnotationBounds(o),a=E.top-d.top,c=E.left-d.left,y=r.parentElement?r.scrollTop:0,b=r.parentElement?r.scrollLeft:0,h=a+y-(i-v)/2,f=c+b-(T-w)/2;r.scroll({top:h,left:f,behavior:"smooth"})},r=fe(e);if(!r)return console.warn(`The scroll parent is missing for the annotation: ${o}`,{container:e}),!1;const l=n.getAnnotation(o);if(!l)return console.warn(`The annotation is missing in the store: ${o}`),!1;const{range:u}=l.target.selector[0];if(u&&!u.collapsed)return s(l.target),!0;const m=V(l.target,e),{range:C}=m.selector[0];return C&&!C.collapsed?(s(m),!0):!1},H={fill:"rgb(0, 128, 255)",fillOpacity:.18},Y={fill:"rgb(0, 128, 255)",fillOpacity:.45},me=(e,n,t,o,s)=>{var l,u;const r=t?typeof t=="function"?t(e.annotation,e.state,s)||((l=e.state)!=null&&l.selected?Y:H):t:(u=e.state)!=null&&u.selected?Y:H;return o&&o.paint(e,n)||r},He=e=>{const{top:n,left:t}=e.getBoundingClientRect(),{innerWidth:o,innerHeight:s}=window,r=-t,l=-n,u=o-t,m=s-n;return{top:n,left:t,minX:r,minY:l,maxX:u,maxY:m}},Me=e=>{let n=new Set;return o=>{const s=o.map(r=>r.id);(n.size!==s.length||s.some(r=>!n.has(r)))&&e.set(s),n=new Set(s)}},Z=(e,n,t,o)=>{const{store:s,selection:r,hover:l}=n;let u,m,C;const p=Me(t),d=g=>{const{x:R,y:k}=e.getBoundingClientRect(),N=s.getAt(g.clientX-R,g.clientY-k,!1,m);N?l.current!==N.id&&(e.classList.add("hovered"),l.set(N.id)):l.current&&(e.classList.remove("hovered"),l.set(null))};e.addEventListener("pointermove",d);const i=(g=!1)=>{C&&C.clear();const R=He(e),{minX:k,minY:N,maxX:_,maxY:I}=R,q=m?s.getIntersecting(k,N,_,I).filter(({annotation:B})=>m(B)):s.getIntersecting(k,N,_,I),O=r.selected.map(({id:B})=>B),U=q.map(({annotation:B,rects:F})=>{const Ge=O.includes(B.id),Qe=B.id===l.current;return{annotation:B,rects:F,state:{selected:Ge,hovered:Qe}}});o.redraw(U,R,u,C,g),setTimeout(()=>p(q.map(({annotation:B})=>B)),1)},T=g=>{C=g,i()},E=g=>{u=g,i()},w=g=>{m=g,i(!1)},v=()=>i();s.observe(v);const a=r.subscribe(()=>i()),c=l.subscribe(()=>i()),y=()=>i(!0);document.addEventListener("scroll",y,{capture:!0,passive:!0});const b=W(()=>{s.recalculatePositions(),C&&C.reset(),i()});window.addEventListener("resize",b);const h=new ResizeObserver(b);h.observe(e);const f={attributes:!0,childList:!0,subtree:!0},A=new MutationObserver(W(g=>{g.every(k=>k.target===e||e.contains(k.target))||i(!0)},150));return A.observe(document.body,f),{destroy:()=>{e.removeEventListener("pointermove",d),o.destroy(),s.unobserve(v),a(),c(),document.removeEventListener("scroll",y),window.removeEventListener("resize",b),h.disconnect(),A.disconnect()},redraw:i,setStyle:E,setFilter:w,setPainter:T,setVisible:o.setVisible}},_e=()=>{const e=document.createElement("canvas");return e.width=window.innerWidth,e.height=window.innerHeight,e.className="r6o-canvas-highlight-layer bg",e},Ue=(e,n)=>{e.width=window.innerWidth,e.height=window.innerHeight},Fe=e=>{e.classList.add("r6o-annotatable");const n=_e(),t=n.getContext("2d");document.body.appendChild(n);const o=(u,m,C,p)=>requestAnimationFrame(()=>{const{width:d,height:i}=n;t.clearRect(-.5,-.5,d+1,i+1),p&&p.clear();const{top:T,left:E}=m;[...u].sort((v,a)=>{const{annotation:{target:{created:c}}}=v,{annotation:{target:{created:y}}}=a;return c.getTime()-y.getTime()}).forEach(v=>{var b;const a=C?typeof C=="function"?C(v.annotation,v.state):C:(b=v.state)!=null&&b.selected?Y:H,c=p&&p.paint(v,m)||a,y=v.rects.map(({x:h,y:f,width:A,height:L})=>({x:h+E,y:f+T,width:A,height:L}));if(t.fillStyle=c.fill,t.globalAlpha=c.fillOpacity||1,y.forEach(({x:h,y:f,width:A,height:L})=>t.fillRect(h,f,A,L)),c.underlineColor){t.globalAlpha=1,t.strokeStyle=c.underlineColor,t.lineWidth=c.underlineThickness??1;const h=c.underlineOffset??0;y.forEach(({x:f,y:A,width:L,height:g})=>{t.beginPath(),t.moveTo(f,A+g+h),t.lineTo(f+L,A+g+h),t.stroke()})}})}),s=W(()=>{Ue(n)});return window.addEventListener("resize",s),{destroy:()=>{n.remove(),window.removeEventListener("resize",s)},setVisible:u=>{console.log("setVisible not implemented on Canvas renderer")},redraw:o}},he=(e,n,t)=>Z(e,n,t,Fe(e)),De=e=>[`background-color:${D.colord((e==null?void 0:e.fill)||H.fill).alpha((e==null?void 0:e.fillOpacity)===void 0?H.fillOpacity:e.fillOpacity).toHex()}`,e!=null&&e.underlineThickness?"text-decoration:underline":void 0,e!=null&&e.underlineColor?`text-decoration-color:${e.underlineColor}`:void 0,e!=null&&e.underlineOffset?`text-underline-offset:${e.underlineOffset}px`:void 0,e!=null&&e.underlineThickness?`text-decoration-thickness:${e.underlineThickness}px`:void 0].filter(Boolean).join(";"),pe=()=>{const e=document.createElement("style");document.getElementsByTagName("head")[0].appendChild(e);let n=new Set;return{destroy:()=>{CSS.highlights.clear(),e.remove()},setVisible:r=>{console.log("setVisible not implemented on CSS Custom Highlights renderer")},redraw:(r,l,u,m)=>{m&&m.clear();const C=new Set(r.map(d=>d.annotation.id));Array.from(n).filter(d=>!C.has(d));const p=r.map(d=>{var E;const i=u?typeof u=="function"?u(d.annotation,d.state):u:(E=d.state)!=null&&E.selected?Y:H,T=m&&m.paint(d,l)||i;return`::highlight(_${d.annotation.id}) { ${De(T)} }`});e.innerHTML=p.join(`
2
- `),CSS.highlights.clear(),r.forEach(({annotation:d})=>{const i=d.target.selector.map(E=>E.range),T=new Highlight(...i);CSS.highlights.set(`_${d.id}`,T)}),n=C}}},ye=(e,n,t)=>Z(e,n,t,pe()),Ke=(e,n)=>{const t=(r,l)=>r.x<=l.x+l.width&&r.x+r.width>=l.x&&r.y<=l.y+l.height&&r.y+r.height>=l.y,o=r=>r.rects.reduce((l,u)=>l+u.width,0),s=n.filter(({rects:r})=>r.some(l=>t(e,l)));return s.sort((r,l)=>o(l)-o(r)),s.findIndex(r=>r.rects.includes(e))},$e=e=>{e.classList.add("r6o-annotatable");const n=document.createElement("div");n.className="r6o-span-highlight-layer",e.insertBefore(n,e.firstChild);let t=[];return{destroy:()=>{n.remove()},redraw:(l,u,m,C,p)=>{const i=!(Oe.dequal(t,l)&&p);if(!C&&!i)return;i&&(n.innerHTML=""),[...l].sort((E,w)=>{const{annotation:{target:{created:v}}}=E,{annotation:{target:{created:a}}}=w;return v&&a?v.getTime()-a.getTime():0}).forEach(E=>{E.rects.map(w=>{const v=Ke(w,l),a=me(E,u,m,C,v);if(i){const c=document.createElement("span");c.className="r6o-annotation",c.dataset.annotation=E.annotation.id,c.style.left=`${w.x}px`,c.style.top=`${w.y}px`,c.style.width=`${w.width}px`,c.style.height=`${w.height}px`,c.style.backgroundColor=D.colord((a==null?void 0:a.fill)||H.fill).alpha((a==null?void 0:a.fillOpacity)===void 0?H.fillOpacity:a.fillOpacity).toHex(),a.underlineStyle&&(c.style.borderStyle=a.underlineStyle),a.underlineColor&&(c.style.borderColor=a.underlineColor),a.underlineThickness&&(c.style.borderBottomWidth=`${a.underlineThickness}px`),a.underlineOffset&&(c.style.paddingBottom=`${a.underlineOffset}px`),n.appendChild(c)}})}),t=l},setVisible:l=>{l?n.classList.remove("hidden"):n.classList.add("hidden")}}},be=(e,n,t)=>Z(e,n,t,$e(e)),We=(e,n)=>({parse:t=>Se(t),serialize:t=>Ce(t,e,n)}),Ve=e=>e.quote!==void 0&&e.start!==void 0&&e.end!==void 0,Ye=e=>{const{id:n,creator:t,created:o,modified:s,target:r}=e,l=Array.isArray(r)?r:[r];if(l.length===0)return{error:Error(`No targets found for annotation: ${e.id}`)};const u={creator:x.parseW3CUser(t),created:o?new Date(o):void 0,updated:s?new Date(s):void 0,annotation:n,selector:[],styleClass:"styleClass"in l[0]?l[0].styleClass:void 0};for(const m of l){const p=(Array.isArray(m.selector)?m.selector:[m.selector]).reduce((d,i)=>{switch(i.type){case"TextQuoteSelector":d.quote=i.exact;break;case"TextPositionSelector":d.start=i.start,d.end=i.end;break}return d},{});if(Ve(p))u.selector.push({...p,id:m.id,scope:m.scope});else{const d=[p.start?void 0:"TextPositionSelector",p.quote?void 0:"TextQuoteSelector"].filter(Boolean);return{error:Error(`Missing selector types: ${d.join(" and ")} for annotation: ${e.id}`)}}}return{parsed:u}},Se=e=>{const n=e.id||ee.v4(),{creator:t,created:o,modified:s,body:r,...l}=e,u=x.parseW3CBodies(r,n),m=Ye(e);return"error"in m?{error:m.error}:{parsed:{...l,id:n,bodies:u,target:m.parsed}}},Ce=(e,n,t)=>{const{bodies:o,target:s,...r}=e,{selector:l,creator:u,created:m,updated:C,...p}=s,d=l.map(i=>{const{id:T,quote:E,start:w,end:v,range:a}=i,c={type:"TextQuoteSelector",exact:E};if(t){const{prefix:b,suffix:h}=ie(a,t);c.prefix=b,c.suffix=h}const y={type:"TextPositionSelector",start:w,end:v};return{...p,id:T,scope:"scope"in i?i.scope:void 0,source:n,selector:[c,y]}});return{...r,"@context":"http://www.w3.org/ns/anno.jsonld",id:e.id,type:"Annotation",body:x.serializeW3CBodies(e.bodies),creator:u,created:m==null?void 0:m.toISOString(),modified:C==null?void 0:C.toISOString(),target:d}},qe=(e,n)=>{const t=new ke,o=new Map,s=(a,c)=>{const y=a.selector.flatMap(h=>{const f=P([h])?h.range:J(h,n).range;return Array.from(f.getClientRects())}),b=le(y).map(({left:h,top:f,right:A,bottom:L})=>new DOMRect(h-c.left,f-c.top,A-h,L-f));return b.map(h=>{const{x:f,y:A,width:L,height:g}=h;return{minX:f,minY:A,maxX:f+L,maxY:A+g,annotation:{id:a.annotation,rects:b}}})},r=()=>[...o.values()],l=()=>{t.clear(),o.clear()},u=a=>{const c=s(a,n.getBoundingClientRect());c.length!==0&&(c.forEach(y=>t.insert(y)),o.set(a.annotation,c))},m=a=>{const c=o.get(a.annotation);c&&(c.forEach(y=>t.remove(y)),o.delete(a.annotation))},C=a=>{m(a),u(a)},p=(a,c=!0)=>{c&&l();const y=n.getBoundingClientRect(),b=a.map(f=>({target:f,rects:s(f,y)}));b.forEach(({target:f,rects:A})=>{A.length>0&&o.set(f.annotation,A)});const h=b.flatMap(({rects:f})=>f);t.load(h)},d=(a,c,y=!1)=>{const b=t.search({minX:a,minY:c,maxX:a,maxY:c}),h=f=>f.annotation.rects.reduce((A,L)=>A+L.width*L.height,0);return b.length>0?(b.sort((f,A)=>h(f)-h(A)),y?b.map(f=>f.annotation.id):[b[0].annotation.id]):[]},i=a=>{const c=T(a);if(c.length===0)return;let y=c[0].left,b=c[0].top,h=c[0].right,f=c[0].bottom;for(let A=1;A<c.length;A++){const L=c[A];y=Math.min(y,L.left),b=Math.min(b,L.top),h=Math.max(h,L.right),f=Math.max(f,L.bottom)}return new DOMRect(y,b,h-y,f-b)},T=a=>{const c=o.get(a);return c?c[0].annotation.rects:[]};return{all:r,clear:l,getAt:d,getAnnotationBounds:i,getAnnotationRects:T,getIntersecting:(a,c,y,b)=>{const h=t.search({minX:a,minY:c,maxX:y,maxY:b}),f=new Set(h.map(A=>A.annotation.id));return Array.from(f).map(A=>({annotation:e.getAnnotation(A),rects:T(A)})).filter(A=>!!A.annotation)},insert:u,recalculate:()=>p(e.all().map(a=>a.target),!0),remove:m,set:p,size:()=>t.all().length,update:C}},Ae=(e,n)=>{const t=x.createStore(),o=qe(t,e),s=x.createSelectionState(t,n.userSelectAction,n.adapter),r=x.createHoverState(t),l=x.createViewportState(),u=(a,c=x.Origin.LOCAL)=>{const y=G(a,e),b=P(y.target.selector);return b&&t.addAnnotation(y,c),b},m=(a,c=!0,y=x.Origin.LOCAL)=>{const b=a.map(f=>G(f,e)),h=b.filter(f=>!P(f.target.selector));return t.bulkAddAnnotations(b,c,y),h},C=(a,c=x.Origin.LOCAL)=>{const y=a.map(h=>G(h,e)),b=y.filter(h=>!P(h.target.selector));return y.forEach(h=>{t.getAnnotation(h.id)?t.updateAnnotation(h,c):t.addAnnotation(h,c)}),b},p=(a,c=x.Origin.LOCAL)=>{const y=V(a,e);t.updateTarget(y,c)},d=(a,c=x.Origin.LOCAL)=>{const y=a.map(b=>V(b,e));t.bulkUpdateTargets(y,c)};function i(a,c,y,b){const h=y||!!b,f=o.getAt(a,c,h).map(L=>t.getAnnotation(L)),A=b?f.filter(b):f;if(A.length!==0)return y?A:A[0]}const T=a=>{if(o.getAnnotationRects(a).length!==0)return o.getAnnotationBounds(a)},E=(a,c,y,b)=>o.getIntersecting(a,c,y,b),w=a=>o.getAnnotationRects(a),v=()=>o.recalculate();return t.observe(({changes:a})=>{const c=(a.deleted||[]).filter(h=>P(h.target.selector)),y=(a.created||[]).filter(h=>P(h.target.selector)),b=(a.updated||[]).filter(h=>P(h.newValue.target.selector));(c==null?void 0:c.length)>0&&c.forEach(h=>o.remove(h.target)),y.length>0&&o.set(y.map(h=>h.target),!1),(b==null?void 0:b.length)>0&&b.forEach(({newValue:h})=>o.update(h.target))}),{store:{...t,addAnnotation:u,bulkAddAnnotations:m,bulkUpdateTargets:d,bulkUpsertAnnotations:C,getAnnotationBounds:T,getAnnotationRects:w,getIntersecting:E,getAt:i,recalculatePositions:v,updateTarget:p},selection:s,hover:r,viewport:l}},ze=()=>{const e=document.createElement("canvas");e.width=2*window.innerWidth,e.height=2*window.innerHeight,e.className="r6o-presence-layer";const n=e.getContext("2d");return n.scale(2,2),n.translate(.5,.5),e},Ee=(e,n={})=>{const t=ze(),o=t.getContext("2d");document.body.appendChild(t);const s=new Map,r=p=>Array.from(s.entries()).filter(([d,i])=>i.presenceKey===p.presenceKey).map(([d,i])=>d);return e.on("selectionChange",(p,d)=>{r(p).forEach(T=>s.delete(T)),d&&d.forEach(T=>s.set(T,p))}),{clear:()=>{const{width:p,height:d}=t;o.clearRect(-.5,-.5,p+1,d+1)},destroy:()=>{t.remove()},paint:(p,d,i)=>{n.font&&(o.font=n.font);const T=s.get(p.annotation.id);if(T){const{height:E}=p.rects[0],w=p.rects[0].x+d.left,v=p.rects[0].y+d.top;o.fillStyle=T.appearance.color,o.fillRect(w-2,v-2.5,2,E+5);const a=o.measureText(T.appearance.label),c=a.width+6,y=a.actualBoundingBoxAscent+a.actualBoundingBoxDescent+8,b=a.fontBoundingBoxAscent?8:6.5;return o.fillRect(w-2,v-2.5-y,c,y),o.fillStyle="#fff",o.fillText(T.appearance.label,w+1,v-b),{fill:T.appearance.color,fillOpacity:i?.45:.18}}},reset:()=>{t.width=2*window.innerWidth,t.height=2*window.innerHeight;const p=t.getContext("2d");p.scale(2,2),p.translate(.5,.5)}}},Te=300,ve=["up","down","left","right"],we=oe?"⌘+a":"ctrl+a",Xe=[...ve.map(e=>`shift+${e}`),we],Re=(e,n,t)=>{let o;const{annotatingEnabled:s,offsetReferenceSelector:r,selectionMode:l}=t,u=g=>o=g;let m;const C=g=>m=g,{store:p,selection:d}=n;let i,T,E;const w=g=>{T!==!1&&(i=K(e,g.target)?void 0:{annotation:ee.v4(),selector:[],creator:o,created:new Date})},v=W(g=>{const R=document.getSelection();if(!(R!=null&&R.anchorNode))return;if(K(e,R.anchorNode)){i=void 0;return}const k=g.timeStamp-((E==null?void 0:E.timeStamp)||g.timeStamp);if((E==null?void 0:E.type)==="pointerdown"&&(k<1e3&&!i||R.isCollapsed&&k<Te)&&w(E||g),!i)return;if(R.isCollapsed){p.getAnnotation(i.annotation)&&(d.clear(),p.deleteAnnotation(i.annotation));return}const _=Array.from(Array(R.rangeCount).keys()).map(O=>R.getRangeAt(O)).map(O=>ue(O,e));if(_.every(O=>ce(O)))return;const I=_.flatMap(O=>re(e,O.cloneRange()));(I.length!==i.selector.length||I.some((O,U)=>{var B;return O.toString()!==((B=i.selector[U])==null?void 0:B.quote)}))&&(i={...i,selector:I.map(O=>de(O,e,r)),updated:new Date},p.getAnnotation(i.annotation)?p.updateTarget(i,x.Origin.LOCAL):d.clear())}),a=g=>{K(e,g.target)||(E=X(g),T=E.button===0)},c=g=>{if(!T)return;if(K(e,g.target)){t.dismissOnClickOutside&&d.clear();return}const R=()=>{const{x:N,y:_}=e.getBoundingClientRect(),I=g.target instanceof Node&&e.contains(g.target)&&p.getAt(g.clientX-N,g.clientY-_,l==="all",m);if(I){const{selected:q}=d,O=new Set(q.map(F=>F.id)),U=Array.isArray(I)?I.map(F=>F.id):[I.id];(O.size!==U.length||!U.every(F=>O.has(F)))&&d.userSelect(U,g)}else d.clear()},k=g.timeStamp-E.timeStamp;setTimeout(()=>{const N=document.getSelection();N!=null&&N.isCollapsed&&k<Te?(i=void 0,R()):i&&i.selector.length>0&&(A(),d.userSelect(i.annotation,X(g)))})},y=g=>{const R=document.getSelection();R!=null&&R.isCollapsed||((!i||i.selector.length===0)&&v(g),i&&(A(),d.userSelect(i.annotation,X(g))))},b=g=>{g.key==="Shift"&&i&&(document.getSelection().isCollapsed||(A(),d.userSelect(i.annotation,$(g))))},h=g=>{const R=()=>setTimeout(()=>{(i==null?void 0:i.selector.length)>0&&(d.clear(),p.addAnnotation({id:i.annotation,bodies:[],target:i}),d.userSelect(i.annotation,$(g))),document.removeEventListener("selectionchange",R)},100);document.addEventListener("selectionchange",R),w(g)};z(Xe.join(","),{element:e,keydown:!0,keyup:!1},g=>{g.repeat||(E=$(g))}),z(we,{keydown:!0,keyup:!1},g=>{E=$(g),h(g)});const f=g=>{g.repeat||g.target!==e&&g.target!==document.body||(i=void 0,d.clear())};z(ve.join(","),{keydown:!0,keyup:!1},f);const A=()=>{const g=p.getAnnotation(i.annotation);if(!g){p.addAnnotation({id:i.annotation,bodies:[],target:i});return}const{target:{updated:R}}=g,{updated:k}=i;(!R||!k||R<k)&&p.updateTarget(i)};return e.addEventListener("pointerdown",a),document.addEventListener("pointerup",c),document.addEventListener("contextmenu",y),s&&(e.addEventListener("keyup",b),e.addEventListener("selectstart",w),document.addEventListener("selectionchange",v)),{destroy:()=>{e.removeEventListener("pointerdown",a),document.removeEventListener("pointerup",c),document.removeEventListener("contextmenu",y),e.removeEventListener("keyup",b),e.removeEventListener("selectstart",w),document.removeEventListener("selectionchange",v),z.unbind()},setFilter:C,setUser:u}},Le=(e,n)=>({...e,annotatingEnabled:e.annotatingEnabled??n.annotatingEnabled,user:e.user||n.user}),xe="SPANS",je=(e,n={})=>{ne(e),se(e);const t=Le(n,{annotatingEnabled:!0,user:x.createAnonymousGuest()}),o=Ae(e,t),{selection:s,viewport:r}=o,l=o.store,u=x.createUndoStack(l),m=x.createLifecycleObserver(o,u,t.adapter);let C=t.user;const p=t.renderer==="CSS_HIGHLIGHTS"?CSS.highlights?"CSS_HIGHLIGHTS":xe:t.renderer||xe,d=p==="SPANS"?be(e,o,r):p==="CSS_HIGHLIGHTS"?ye(e,o,r):p==="CANVAS"?he(e,o,r):void 0;if(!d)throw`Unknown renderer implementation: ${p}`;console.debug(`Using ${p} renderer`),t.style&&d.setStyle(t.style);const i=Re(e,o,t);return i.setUser(C),{...x.createBaseAnnotator(o,u,t.adapter),destroy:()=>{d.destroy(),i.destroy(),u.destroy()},element:e,getUser:()=>C,setFilter:f=>{d.setFilter(f),i.setFilter(f)},setStyle:f=>d.setStyle(f),setUser:f=>{C=f,i.setUser(f)},setSelected:f=>{f?s.setSelected(f):s.clear()},setPresenceProvider:f=>{f&&(d.setPainter(Ee(f,t.presence)),f.on("selectionChange",()=>d.redraw()))},setVisible:f=>d.setVisible(f),on:m.on,off:m.off,scrollIntoView:ge(e,l),state:o}};Object.defineProperty(S,"Origin",{enumerable:!0,get:()=>x.Origin}),Object.defineProperty(S,"UserSelectAction",{enumerable:!0,get:()=>x.UserSelectAction}),Object.defineProperty(S,"createBody",{enumerable:!0,get:()=>x.createBody}),S.DEFAULT_SELECTED_STYLE=Y,S.DEFAULT_STYLE=H,S.NOT_ANNOTATABLE_CLASS=Q,S.NOT_ANNOTATABLE_SELECTOR=M,S.SelectionHandler=Re,S.W3CTextFormat=We,S.cancelSingleClickEvents=ne,S.cloneKeyboardEvent=$,S.clonePointerEvent=X,S.createCanvasRenderer=he,S.createHighlightsRenderer=ye,S.createPresencePainter=Ee,S.createRenderer=pe,S.createSpansRenderer=be,S.createTextAnnotator=je,S.createTextAnnotatorState=Ae,S.debounce=W,S.fillDefaults=Le,S.getQuoteContext=ie,S.getRangeAnnotatableContents=j,S.isMac=oe,S.isNotAnnotatable=K,S.isRangeAnnotatable=te,S.isRevived=P,S.isWhitespaceOrEmpty=ce,S.mergeClientRects=le,S.paint=me,S.parseW3CTextAnnotation=Se,S.programmaticallyFocusable=se,S.rangeToSelector=de,S.reviveAnnotation=G,S.reviveSelector=J,S.reviveTarget=V,S.scrollIntoView=ge,S.serializeW3CTextAnnotation=Ce,S.splitAnnotatableRanges=re,S.toDomRectList=Pe,S.trimRangeToContainer=ue,S.whitespaceOrEmptyRegex=ae,Object.defineProperty(S,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(b,F){typeof exports=="object"&&typeof module<"u"?F(exports,require("colord"),require("dequal/lite"),require("uuid"),require("@annotorious/core"),require("rbush"),require("hotkeys-js"),require("poll")):typeof define=="function"&&define.amd?define(["exports","colord","dequal/lite","uuid","@annotorious/core","rbush","hotkeys-js","poll"],F):(b=typeof globalThis<"u"?globalThis:b||self,F(b.RecogitoJS={},b.Colord,b.DequalLite,b.UUID,b.AnnotoriousCore,b.RBush,b.HotkeysJs,b.poll))})(this,(function(b,F,ke,te,x,Ne,z,Ie){"use strict";const J="not-annotatable",U=`.${J}`,K=(e,n)=>{var o;return e.contains(n)?!!(n instanceof HTMLElement?n.closest(U):(o=n.parentElement)==null?void 0:o.closest(U)):!0},ne=(e,n)=>{const t=n.commonAncestorContainer;return!K(e,t)},oe=e=>e.addEventListener("click",n=>{!n.target.closest(U)&&!n.target.closest("a")&&n.preventDefault()}),X=e=>({...e,type:e.type,x:e.x,y:e.y,clientX:e.clientX,clientY:e.clientY,offsetX:e.offsetX,offsetY:e.offsetY,screenX:e.screenX,screenY:e.screenY,isPrimary:e.isPrimary,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,shiftKey:e.shiftKey,button:e.button,buttons:e.buttons,currentTarget:e.currentTarget,target:e.target,defaultPrevented:e.defaultPrevented,detail:e.detail,eventPhase:e.eventPhase,pointerId:e.pointerId,pointerType:e.pointerType,timeStamp:e.timeStamp}),$=e=>({...e,type:e.type,key:e.key,code:e.code,location:e.location,repeat:e.repeat,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,shiftKey:e.shiftKey,currentTarget:e.currentTarget,target:e.target,defaultPrevented:e.defaultPrevented,detail:e.detail,timeStamp:e.timeStamp}),se=typeof navigator<"u"&&/mac/i.test(navigator.userAgentData?navigator.userAgentData.platform:navigator.platform),re=e=>{!e.hasAttribute("tabindex")&&e.tabIndex<0&&e.setAttribute("tabindex","-1"),e.classList.add("no-focus-outline")},W=(e,n=10)=>{let t;return((...o)=>{clearTimeout(t),t=setTimeout(()=>e.apply(void 0,o),n)})},Be=function*(e){const n=document.createNodeIterator(e.commonAncestorContainer,NodeFilter.SHOW_ELEMENT,o=>o instanceof HTMLElement&&o.classList.contains(J)&&!o.parentElement.closest(U)&&e.intersectsNode(o)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);let t;for(;t=n.nextNode();)t instanceof HTMLElement&&(yield t)},ie=(e,n)=>{if(!ne(e,n))return[];const t=[];let o=null;for(const s of Be(n)){let r;o?(r=document.createRange(),r.setStartAfter(o),r.setEndBefore(s)):(r=n.cloneRange(),r.setEndBefore(s)),r.collapsed||t.push(r),o=s}if(o){const s=n.cloneRange();s.setStartAfter(o),s.collapsed||t.push(s)}return t.length>0?t:[n]},j=e=>{const n=e.cloneContents();return n.querySelectorAll(U).forEach(t=>t.remove()),n},ae=(e,n,t=10,o)=>{const s=o?e.startContainer.parentElement.closest(o):n,r=document.createRange();r.setStart(s,0),r.setEnd(e.startContainer,e.startOffset);const l=j(r).textContent,u=document.createRange();u.setStart(e.endContainer,e.endOffset),s===document.body?u.setEnd(s,s.childNodes.length):u.setEndAfter(s);const g=j(u).textContent;return{prefix:l.substring(l.length-t),suffix:g.substring(0,t)}},M=e=>e.every(n=>n.range instanceof Range&&!n.range.collapsed),ce=/^\s*$/,le=e=>ce.test(e.toString()),Pe=(e,n)=>{const t=r=>Math.round(r*10)/10,o={top:t(e.top),bottom:t(e.bottom),left:t(e.left),right:t(e.right)},s={top:t(n.top),bottom:t(n.bottom),left:t(n.left),right:t(n.right)};if(Math.abs(o.top-s.top)<.5&&Math.abs(o.bottom-s.bottom)<.5){if(Math.abs(o.left-s.right)<.5||Math.abs(o.right-s.left)<.5)return"inline-adjacent";if(o.left>=s.left&&o.right<=s.right)return"inline-is-contained";if(o.left<=s.left&&o.right>=s.right)return"inline-contains"}else if(o.top<=s.top&&o.bottom>=s.bottom){if(o.left<=s.left&&o.right>=s.right)return"block-contains"}else if(o.top>=s.top&&o.bottom<=s.bottom&&o.left>=s.left&&o.right<=s.right)return"block-is-contained"},Me=(e,n)=>{const t=Math.min(e.left,n.left),o=Math.max(e.right,n.right),s=Math.min(e.top,n.top),r=Math.max(e.bottom,n.bottom);return new DOMRect(t,s,o-t,r-s)},de=e=>e.reduce((n,t)=>{if(t.width===0||t.height===0)return n;let o=[...n],s=!1;for(const r of n){const l=Pe(t,r);if(l==="inline-adjacent"){o=o.map(u=>u===r?Me(t,r):u),s=!0;break}else if(l==="inline-contains"){o=o.map(u=>u===r?t:u),s=!0;break}else if(l==="inline-is-contained"){s=!0;break}else if(l==="block-contains"||l==="block-is-contained"){t.width<r.width&&(o=o.map(u=>u===r?t:u)),s=!0;break}}return s?o:[...o,t]},[]),He=e=>({length:e.length,item:n=>e[n],[Symbol.iterator]:function*(){for(let n=0;n<this.length;n++)yield this.item(n)}}),ue=(e,n,t)=>{const o=document.createRange(),s=t?e.startContainer.parentElement.closest(t):n;o.setStart(s,0),o.setEnd(e.startContainer,e.startOffset);const r=j(o).textContent,l=e.toString(),u=r.length||0,g=u+l.length;return t?{quote:l,start:u,end:g,range:e,offsetReference:s}:{quote:l,start:u,end:g,range:e}},Z=(e,n)=>{var h,d;const{start:t,end:o}=e,s=e.offsetReference||n,r=document.createNodeIterator(n,NodeFilter.SHOW_TEXT,i=>{var T;return(T=i.parentElement)!=null&&T.closest(U)?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT});let l=0;const u=document.createRange();let g=r.nextNode();g===null&&console.error("Could not revive annotation target. Content missing.");let C=!s;for(;g!==null;){if(C||(C=typeof(s==null?void 0:s.contains)=="function"?s.contains(g):!1),C){const i=((h=g.textContent)==null?void 0:h.length)||0;if(l+i>t){u.setStart(g,t-l);break}l+=i}g=r.nextNode()}for(;g!==null;){const i=((d=g.textContent)==null?void 0:d.length)||0;if(l+i>=o){u.setEnd(g,o-l);break}l+=i,g=r.nextNode()}return{...e,range:u}},V=(e,n)=>M(e.selector)?e:{...e,selector:e.selector.map(t=>t.range instanceof Range&&!t.range.collapsed?t:Z(t,n))},G=(e,n)=>M(e.target.selector)?e:{...e,target:V(e.target,n)},fe=(e,n)=>{const t=e.cloneRange();return n.contains(t.startContainer)||t.setStart(n,0),n.contains(t.endContainer)||t.setEnd(n,n.childNodes.length),t},ge=e=>{if(e===null)return document.scrollingElement;const{overflowY:n}=window.getComputedStyle(e);return n!=="visible"&&n!=="hidden"&&e.scrollHeight>e.clientHeight?e:ge(e.parentElement)},me=(e,n)=>t=>{const o=typeof t=="string"?t:t.id,s=h=>{const d=r.getBoundingClientRect(),i=r.clientHeight,T=r.clientWidth,A=h.selector[0].range.getBoundingClientRect(),{width:R,height:v}=n.getAnnotationBounds(o),a=A.top-d.top,c=A.left-d.left,S=r.parentElement?r.scrollTop:0,y=r.parentElement?r.scrollLeft:0,m=a+S-(i-v)/2,f=c+y-(T-R)/2;r.scroll({top:m,left:f,behavior:"smooth"})},r=ge(e);if(!r)return console.warn(`The scroll parent is missing for the annotation: ${o}`,{container:e}),!1;const l=n.getAnnotation(o);if(!l)return console.warn(`The annotation is missing in the store: ${o}`),!1;const{range:u}=l.target.selector[0];if(u&&!u.collapsed)return s(l.target),!0;const g=V(l.target,e),{range:C}=g.selector[0];return C&&!C.collapsed?(s(g),!0):!1},H={fill:"rgb(0, 128, 255)",fillOpacity:.18},Y={fill:"rgb(0, 128, 255)",fillOpacity:.45},he=(e,n,t,o,s)=>{var l,u;const r=t?typeof t=="function"?t(e.annotation,e.state,s)||((l=e.state)!=null&&l.selected?Y:H):t:(u=e.state)!=null&&u.selected?Y:H;return o&&o.paint(e,n)||r},_e=e=>{const{top:n,left:t}=e.getBoundingClientRect(),{innerWidth:o,innerHeight:s}=window,r=-t,l=-n,u=o-t,g=s-n;return{top:n,left:t,minX:r,minY:l,maxX:u,maxY:g}},Ue=e=>{let n=new Set;return o=>{const s=o.map(r=>r.id);(n.size!==s.length||s.some(r=>!n.has(r)))&&e.set(s),n=new Set(s)}},ee=(e,n,t,o)=>{const{store:s,selection:r,hover:l}=n;let u,g,C;const h=Ue(t),d=O=>{const{x:p,y:w}=e.getBoundingClientRect(),k=s.getAt(O.clientX-p,O.clientY-w,!1,g);k?l.current!==k.id&&(e.classList.add("hovered"),l.set(k.id)):l.current&&(e.classList.remove("hovered"),l.set(null))};e.addEventListener("pointermove",d);const i=(O=!1)=>{C&&C.clear();const p=_e(e),{minX:w,minY:k,maxX:P,maxY:_}=p,B=g?s.getIntersecting(w,k,P,_).filter(({annotation:I})=>g(I)):s.getIntersecting(w,k,P,_),Q=r.selected.map(({id:I})=>I),N=B.map(({annotation:I,rects:q})=>{const D=Q.includes(I.id),Je=I.id===l.current;return{annotation:I,rects:q,state:{selected:D,hovered:Je}}});o.redraw(N,p,u,C,O),setTimeout(()=>h(B.map(({annotation:I})=>I)),1)},T=O=>{C=O,i()},A=O=>{u=O,i()},R=O=>{g=O,i(!1)},v=()=>i();s.observe(v);const a=r.subscribe(()=>i()),c=l.subscribe(()=>i()),S=()=>i(!0);document.addEventListener("scroll",S,{capture:!0,passive:!0});const y=W(()=>{s.recalculatePositions(),C&&C.reset(),i()});window.addEventListener("resize",y);const m=new ResizeObserver(y);m.observe(e);const f={attributes:!0,childList:!0,subtree:!0},E=new MutationObserver(W(O=>{O.every(w=>w.target===e||e.contains(w.target))||i(!0)},150));return E.observe(document.body,f),{destroy:()=>{e.removeEventListener("pointermove",d),o.destroy(),s.unobserve(v),a(),c(),document.removeEventListener("scroll",S),window.removeEventListener("resize",y),m.disconnect(),E.disconnect()},redraw:i,setStyle:A,setFilter:R,setPainter:T,setVisible:o.setVisible}},De=()=>{const e=document.createElement("canvas");return e.width=window.innerWidth,e.height=window.innerHeight,e.className="r6o-canvas-highlight-layer bg",e},Fe=(e,n)=>{e.width=window.innerWidth,e.height=window.innerHeight},Ke=e=>{e.classList.add("r6o-annotatable");const n=De(),t=n.getContext("2d");document.body.appendChild(n);const o=(u,g,C,h)=>requestAnimationFrame(()=>{const{width:d,height:i}=n;t.clearRect(-.5,-.5,d+1,i+1),h&&h.clear();const{top:T,left:A}=g;[...u].sort((v,a)=>{const{annotation:{target:{created:c}}}=v,{annotation:{target:{created:S}}}=a;return c.getTime()-S.getTime()}).forEach(v=>{var y;const a=C?typeof C=="function"?C(v.annotation,v.state):C:(y=v.state)!=null&&y.selected?Y:H,c=h&&h.paint(v,g)||a,S=v.rects.map(({x:m,y:f,width:E,height:L})=>({x:m+A,y:f+T,width:E,height:L}));if(t.fillStyle=c.fill,t.globalAlpha=c.fillOpacity||1,S.forEach(({x:m,y:f,width:E,height:L})=>t.fillRect(m,f,E,L)),c.underlineColor){t.globalAlpha=1,t.strokeStyle=c.underlineColor,t.lineWidth=c.underlineThickness??1;const m=c.underlineOffset??0;S.forEach(({x:f,y:E,width:L,height:O})=>{t.beginPath(),t.moveTo(f,E+O+m),t.lineTo(f+L,E+O+m),t.stroke()})}})}),s=W(()=>{Fe(n)});return window.addEventListener("resize",s),{destroy:()=>{n.remove(),window.removeEventListener("resize",s)},setVisible:u=>{console.log("setVisible not implemented on Canvas renderer")},redraw:o}},pe=(e,n,t)=>ee(e,n,t,Ke(e)),$e=e=>[`background-color:${F.colord((e==null?void 0:e.fill)||H.fill).alpha((e==null?void 0:e.fillOpacity)===void 0?H.fillOpacity:e.fillOpacity).toHex()}`,e!=null&&e.underlineThickness?"text-decoration:underline":void 0,e!=null&&e.underlineColor?`text-decoration-color:${e.underlineColor}`:void 0,e!=null&&e.underlineOffset?`text-underline-offset:${e.underlineOffset}px`:void 0,e!=null&&e.underlineThickness?`text-decoration-thickness:${e.underlineThickness}px`:void 0].filter(Boolean).join(";"),ye=()=>{const e=document.createElement("style");document.getElementsByTagName("head")[0].appendChild(e);let n=new Set;return{destroy:()=>{CSS.highlights.clear(),e.remove()},setVisible:r=>{console.log("setVisible not implemented on CSS Custom Highlights renderer")},redraw:(r,l,u,g)=>{g&&g.clear();const C=new Set(r.map(d=>d.annotation.id));Array.from(n).filter(d=>!C.has(d));const h=r.map(d=>{var A;const i=u?typeof u=="function"?u(d.annotation,d.state):u:(A=d.state)!=null&&A.selected?Y:H,T=g&&g.paint(d,l)||i;return`::highlight(_${d.annotation.id}) { ${$e(T)} }`});e.innerHTML=h.join(`
2
+ `),CSS.highlights.clear(),r.forEach(({annotation:d})=>{const i=d.target.selector.map(A=>A.range),T=new Highlight(...i);CSS.highlights.set(`_${d.id}`,T)}),n=C}}},be=(e,n,t)=>ee(e,n,t,ye()),We=(e,n)=>{const t=(r,l)=>r.x<=l.x+l.width&&r.x+r.width>=l.x&&r.y<=l.y+l.height&&r.y+r.height>=l.y,o=r=>r.rects.reduce((l,u)=>l+u.width,0),s=n.filter(({rects:r})=>r.some(l=>t(e,l)));return s.sort((r,l)=>o(l)-o(r)),s.findIndex(r=>r.rects.includes(e))},Ve=e=>{e.classList.add("r6o-annotatable");const n=document.createElement("div");n.className="r6o-span-highlight-layer",e.insertBefore(n,e.firstChild);let t=[];return{destroy:()=>{n.remove()},redraw:(l,u,g,C,h)=>{const i=!(ke.dequal(t,l)&&h);if(!C&&!i)return;i&&(n.innerHTML=""),[...l].sort((A,R)=>{const{annotation:{target:{created:v}}}=A,{annotation:{target:{created:a}}}=R;return v&&a?v.getTime()-a.getTime():0}).forEach(A=>{A.rects.map(R=>{const v=We(R,l),a=he(A,u,g,C,v);if(i){const c=document.createElement("span");c.className="r6o-annotation",c.dataset.annotation=A.annotation.id,c.style.left=`${R.x}px`,c.style.top=`${R.y}px`,c.style.width=`${R.width}px`,c.style.height=`${R.height}px`,c.style.backgroundColor=F.colord((a==null?void 0:a.fill)||H.fill).alpha((a==null?void 0:a.fillOpacity)===void 0?H.fillOpacity:a.fillOpacity).toHex(),a.underlineStyle&&(c.style.borderStyle=a.underlineStyle),a.underlineColor&&(c.style.borderColor=a.underlineColor),a.underlineThickness&&(c.style.borderBottomWidth=`${a.underlineThickness}px`),a.underlineOffset&&(c.style.paddingBottom=`${a.underlineOffset}px`),n.appendChild(c)}})}),t=l},setVisible:l=>{l?n.classList.remove("hidden"):n.classList.add("hidden")}}},Se=(e,n,t)=>ee(e,n,t,Ve(e)),Ye=(e,n)=>({parse:t=>Ce(t),serialize:t=>Ae(t,e,n)}),qe=e=>e.quote!==void 0&&e.start!==void 0&&e.end!==void 0,ze=e=>{const{id:n,creator:t,created:o,modified:s,target:r}=e,l=Array.isArray(r)?r:[r];if(l.length===0)return{error:Error(`No targets found for annotation: ${e.id}`)};const u={creator:x.parseW3CUser(t),created:o?new Date(o):void 0,updated:s?new Date(s):void 0,annotation:n,selector:[],styleClass:"styleClass"in l[0]?l[0].styleClass:void 0};for(const g of l){const h=(Array.isArray(g.selector)?g.selector:[g.selector]).reduce((d,i)=>{switch(i.type){case"TextQuoteSelector":d.quote=i.exact;break;case"TextPositionSelector":d.start=i.start,d.end=i.end;break}return d},{});if(qe(h))u.selector.push({...h,id:g.id,scope:g.scope});else{const d=[h.start?void 0:"TextPositionSelector",h.quote?void 0:"TextQuoteSelector"].filter(Boolean);return{error:Error(`Missing selector types: ${d.join(" and ")} for annotation: ${e.id}`)}}}return{parsed:u}},Ce=e=>{const n=e.id||te.v4(),{creator:t,created:o,modified:s,body:r,...l}=e,u=x.parseW3CBodies(r,n),g=ze(e);return"error"in g?{error:g.error}:{parsed:{...l,id:n,bodies:u,target:g.parsed}}},Ae=(e,n,t)=>{const{bodies:o,target:s,...r}=e,{selector:l,creator:u,created:g,updated:C,...h}=s,d=l.map(i=>{const{id:T,quote:A,start:R,end:v,range:a}=i,c={type:"TextQuoteSelector",exact:A};if(t){const{prefix:y,suffix:m}=ae(a,t);c.prefix=y,c.suffix=m}const S={type:"TextPositionSelector",start:R,end:v};return{...h,id:T,scope:"scope"in i?i.scope:void 0,source:n,selector:[c,S]}});return{...r,"@context":"http://www.w3.org/ns/anno.jsonld",id:e.id,type:"Annotation",body:x.serializeW3CBodies(e.bodies),creator:u,created:g==null?void 0:g.toISOString(),modified:C==null?void 0:C.toISOString(),target:d}},Xe=(e,n)=>{const t=new Ne,o=new Map,s=(a,c)=>{const S=a.selector.flatMap(m=>{const f=M([m])?m.range:Z(m,n).range;return Array.from(f.getClientRects())}),y=de(S).map(({left:m,top:f,right:E,bottom:L})=>new DOMRect(m-c.left,f-c.top,E-m,L-f));return y.map(m=>{const{x:f,y:E,width:L,height:O}=m;return{minX:f,minY:E,maxX:f+L,maxY:E+O,annotation:{id:a.annotation,rects:y}}})},r=()=>[...o.values()],l=()=>{t.clear(),o.clear()},u=a=>{const c=s(a,n.getBoundingClientRect());c.length!==0&&(c.forEach(S=>t.insert(S)),o.set(a.annotation,c))},g=a=>{const c=o.get(a.annotation);c&&(c.forEach(S=>t.remove(S)),o.delete(a.annotation))},C=a=>{g(a),u(a)},h=(a,c=!0)=>{c&&l();const S=n.getBoundingClientRect(),y=a.map(f=>({target:f,rects:s(f,S)}));y.forEach(({target:f,rects:E})=>{E.length>0&&o.set(f.annotation,E)});const m=y.flatMap(({rects:f})=>f);t.load(m)},d=(a,c,S=!1)=>{const y=t.search({minX:a,minY:c,maxX:a,maxY:c}),m=f=>f.annotation.rects.reduce((E,L)=>E+L.width*L.height,0);return y.length>0?(y.sort((f,E)=>m(f)-m(E)),S?y.map(f=>f.annotation.id):[y[0].annotation.id]):[]},i=a=>{const c=T(a);if(c.length===0)return;let S=c[0].left,y=c[0].top,m=c[0].right,f=c[0].bottom;for(let E=1;E<c.length;E++){const L=c[E];S=Math.min(S,L.left),y=Math.min(y,L.top),m=Math.max(m,L.right),f=Math.max(f,L.bottom)}return new DOMRect(S,y,m-S,f-y)},T=a=>{const c=o.get(a);return c?c[0].annotation.rects:[]};return{all:r,clear:l,getAt:d,getAnnotationBounds:i,getAnnotationRects:T,getIntersecting:(a,c,S,y)=>{const m=t.search({minX:a,minY:c,maxX:S,maxY:y}),f=new Set(m.map(E=>E.annotation.id));return Array.from(f).map(E=>({annotation:e.getAnnotation(E),rects:T(E)})).filter(E=>!!E.annotation)},insert:u,recalculate:()=>h(e.all().map(a=>a.target),!0),remove:g,set:h,size:()=>t.all().length,update:C}},Ee=(e,n)=>{const t=x.createStore(),o=Xe(t,e),s=x.createSelectionState(t,n.userSelectAction,n.adapter),r=x.createHoverState(t),l=x.createViewportState(),u=(a,c=x.Origin.LOCAL)=>{const S=G(a,e),y=M(S.target.selector);return y&&t.addAnnotation(S,c),y},g=(a,c=!0,S=x.Origin.LOCAL)=>{const y=a.map(f=>G(f,e)),m=y.filter(f=>!M(f.target.selector));return t.bulkAddAnnotations(y,c,S),m},C=(a,c=x.Origin.LOCAL)=>{const S=a.map(m=>G(m,e)),y=S.filter(m=>!M(m.target.selector));return S.forEach(m=>{t.getAnnotation(m.id)?t.updateAnnotation(m,c):t.addAnnotation(m,c)}),y},h=(a,c=x.Origin.LOCAL)=>{const S=V(a,e);t.updateTarget(S,c)},d=(a,c=x.Origin.LOCAL)=>{const S=a.map(y=>V(y,e));t.bulkUpdateTargets(S,c)};function i(a,c,S,y){const m=S||!!y,f=o.getAt(a,c,m).map(L=>t.getAnnotation(L)),E=y?f.filter(y):f;if(E.length!==0)return S?E:E[0]}const T=a=>{if(o.getAnnotationRects(a).length!==0)return o.getAnnotationBounds(a)},A=(a,c,S,y)=>o.getIntersecting(a,c,S,y),R=a=>o.getAnnotationRects(a),v=()=>o.recalculate();return t.observe(({changes:a})=>{const c=(a.deleted||[]).filter(m=>M(m.target.selector)),S=(a.created||[]).filter(m=>M(m.target.selector)),y=(a.updated||[]).filter(m=>M(m.newValue.target.selector));(c==null?void 0:c.length)>0&&c.forEach(m=>o.remove(m.target)),S.length>0&&o.set(S.map(m=>m.target),!1),(y==null?void 0:y.length)>0&&y.forEach(({newValue:m})=>o.update(m.target))}),{store:{...t,addAnnotation:u,bulkAddAnnotations:g,bulkUpdateTargets:d,bulkUpsertAnnotations:C,getAnnotationBounds:T,getAnnotationRects:R,getIntersecting:A,getAt:i,recalculatePositions:v,updateTarget:h},selection:s,hover:r,viewport:l}},je=()=>{const e=document.createElement("canvas");e.width=2*window.innerWidth,e.height=2*window.innerHeight,e.className="r6o-presence-layer";const n=e.getContext("2d");return n.scale(2,2),n.translate(.5,.5),e},Te=(e,n={})=>{const t=je(),o=t.getContext("2d");document.body.appendChild(t);const s=new Map,r=h=>Array.from(s.entries()).filter(([d,i])=>i.presenceKey===h.presenceKey).map(([d,i])=>d);return e.on("selectionChange",(h,d)=>{r(h).forEach(T=>s.delete(T)),d&&d.forEach(T=>s.set(T,h))}),{clear:()=>{const{width:h,height:d}=t;o.clearRect(-.5,-.5,h+1,d+1)},destroy:()=>{t.remove()},paint:(h,d,i)=>{n.font&&(o.font=n.font);const T=s.get(h.annotation.id);if(T){const{height:A}=h.rects[0],R=h.rects[0].x+d.left,v=h.rects[0].y+d.top;o.fillStyle=T.appearance.color,o.fillRect(R-2,v-2.5,2,A+5);const a=o.measureText(T.appearance.label),c=a.width+6,S=a.actualBoundingBoxAscent+a.actualBoundingBoxDescent+8,y=a.fontBoundingBoxAscent?8:6.5;return o.fillRect(R-2,v-2.5-S,c,S),o.fillStyle="#fff",o.fillText(T.appearance.label,R+1,v-y),{fill:T.appearance.color,fillOpacity:i?.45:.18}}},reset:()=>{t.width=2*window.innerWidth,t.height=2*window.innerHeight;const h=t.getContext("2d");h.scale(2,2),h.translate(.5,.5)}}},we=300,ve=["up","down","left","right"],Re=se?"⌘+a":"ctrl+a",Ge=[...ve.map(e=>`shift+${e}`),Re],Le=(e,n,t)=>{let o;const{annotatingEnabled:s,offsetReferenceSelector:r,selectionMode:l}=t,u=p=>o=p;let g;const C=p=>g=p,{store:h,selection:d}=n;let i,T,A;const R=p=>{T!==!1&&(i=K(e,p.target)?void 0:{annotation:te.v4(),selector:[],creator:o,created:new Date})},v=W(p=>{const w=document.getSelection();if(!(w!=null&&w.anchorNode))return;if(K(e,w.anchorNode)){i=void 0;return}const k=p.timeStamp-((A==null?void 0:A.timeStamp)||p.timeStamp);if((A==null?void 0:A.type)==="pointerdown"&&(k<1e3&&!i||w.isCollapsed&&k<we)&&R(A||p),!i)return;if(w.isCollapsed){h.getAnnotation(i.annotation)&&(d.clear(),h.deleteAnnotation(i.annotation));return}const _=Array.from(Array(w.rangeCount).keys()).map(N=>w.getRangeAt(N)).map(N=>fe(N,e));if(_.every(N=>le(N)))return;const B=_.flatMap(N=>ie(e,N.cloneRange()));(B.length!==i.selector.length||B.some((N,I)=>{var q;return N.toString()!==((q=i.selector[I])==null?void 0:q.quote)}))&&(i={...i,selector:B.map(N=>ue(N,e,r)),updated:new Date},h.getAnnotation(i.annotation)?h.updateTarget(i,x.Origin.LOCAL):d.clear())}),a=p=>{K(e,p.target)||(A=X(p),T=A.button===0)},c=async p=>{if(!T)return;if(K(e,p.target)){t.dismissOnClickOutside&&d.clear();return}const w=()=>{const{x:P,y:_}=e.getBoundingClientRect(),B=p.target instanceof Node&&e.contains(p.target)&&h.getAt(p.clientX-P,p.clientY-_,l==="all",g);if(B){const{selected:Q}=d,N=new Set(Q.map(D=>D.id)),I=Array.isArray(B)?B.map(D=>D.id):[B.id];(N.size!==I.length||!I.every(D=>N.has(D)))&&d.userSelect(I,p)}else d.clear()};if(p.timeStamp-A.timeStamp<we){await S();const P=document.getSelection();if(P!=null&&P.isCollapsed){i=void 0,w();return}}i&&i.selector.length>0&&(L(),d.userSelect(i.annotation,X(p)))},S=async()=>{const p=document.getSelection();let w=!1,k=p==null?void 0:p.isCollapsed;const P=()=>k||w,_=1;return setTimeout(()=>w=!0,50),Ie.poll(()=>k=p==null?void 0:p.isCollapsed,_,P)},y=p=>{const w=document.getSelection();w!=null&&w.isCollapsed||((!i||i.selector.length===0)&&v(p),i&&(L(),d.userSelect(i.annotation,X(p))))},m=p=>{p.key==="Shift"&&i&&(document.getSelection().isCollapsed||(L(),d.userSelect(i.annotation,$(p))))},f=p=>{const w=()=>setTimeout(()=>{(i==null?void 0:i.selector.length)>0&&(d.clear(),h.addAnnotation({id:i.annotation,bodies:[],target:i}),d.userSelect(i.annotation,$(p))),document.removeEventListener("selectionchange",w)},100);document.addEventListener("selectionchange",w),R(p)};z(Ge.join(","),{element:e,keydown:!0,keyup:!1},p=>{p.repeat||(A=$(p))}),z(Re,{keydown:!0,keyup:!1},p=>{A=$(p),f(p)});const E=p=>{p.repeat||p.target!==e&&p.target!==document.body||(i=void 0,d.clear())};z(ve.join(","),{keydown:!0,keyup:!1},E);const L=()=>{const p=h.getAnnotation(i.annotation);if(!p){h.addAnnotation({id:i.annotation,bodies:[],target:i});return}const{target:{updated:w}}=p,{updated:k}=i;(!w||!k||w<k)&&h.updateTarget(i)};return e.addEventListener("pointerdown",a),document.addEventListener("pointerup",c),document.addEventListener("contextmenu",y),s&&(e.addEventListener("keyup",m),e.addEventListener("selectstart",R),document.addEventListener("selectionchange",v)),{destroy:()=>{e.removeEventListener("pointerdown",a),document.removeEventListener("pointerup",c),document.removeEventListener("contextmenu",y),e.removeEventListener("keyup",m),e.removeEventListener("selectstart",R),document.removeEventListener("selectionchange",v),z.unbind()},setFilter:C,setUser:u}},xe=(e,n)=>({...e,annotatingEnabled:e.annotatingEnabled??n.annotatingEnabled,user:e.user||n.user}),Oe="SPANS",Qe=(e,n={})=>{oe(e),re(e);const t=xe(n,{annotatingEnabled:!0,user:x.createAnonymousGuest()}),o=Ee(e,t),{selection:s,viewport:r}=o,l=o.store,u=x.createUndoStack(l),g=x.createLifecycleObserver(o,u,t.adapter);let C=t.user;const h=t.renderer==="CSS_HIGHLIGHTS"?CSS.highlights?"CSS_HIGHLIGHTS":Oe:t.renderer||Oe,d=h==="SPANS"?Se(e,o,r):h==="CSS_HIGHLIGHTS"?be(e,o,r):h==="CANVAS"?pe(e,o,r):void 0;if(!d)throw`Unknown renderer implementation: ${h}`;console.debug(`Using ${h} renderer`),t.style&&d.setStyle(t.style);const i=Le(e,o,t);return i.setUser(C),{...x.createBaseAnnotator(o,u,t.adapter),destroy:()=>{d.destroy(),i.destroy(),u.destroy()},element:e,getUser:()=>C,setFilter:f=>{d.setFilter(f),i.setFilter(f)},setStyle:f=>d.setStyle(f),setUser:f=>{C=f,i.setUser(f)},setSelected:f=>{f?s.setSelected(f):s.clear()},setPresenceProvider:f=>{f&&(d.setPainter(Te(f,t.presence)),f.on("selectionChange",()=>d.redraw()))},setVisible:f=>d.setVisible(f),on:g.on,off:g.off,scrollIntoView:me(e,l),state:o}};Object.defineProperty(b,"Origin",{enumerable:!0,get:()=>x.Origin}),Object.defineProperty(b,"UserSelectAction",{enumerable:!0,get:()=>x.UserSelectAction}),Object.defineProperty(b,"createBody",{enumerable:!0,get:()=>x.createBody}),b.DEFAULT_SELECTED_STYLE=Y,b.DEFAULT_STYLE=H,b.NOT_ANNOTATABLE_CLASS=J,b.NOT_ANNOTATABLE_SELECTOR=U,b.SelectionHandler=Le,b.W3CTextFormat=Ye,b.cancelSingleClickEvents=oe,b.cloneKeyboardEvent=$,b.clonePointerEvent=X,b.createCanvasRenderer=pe,b.createHighlightsRenderer=be,b.createPresencePainter=Te,b.createRenderer=ye,b.createSpansRenderer=Se,b.createTextAnnotator=Qe,b.createTextAnnotatorState=Ee,b.debounce=W,b.fillDefaults=xe,b.getQuoteContext=ae,b.getRangeAnnotatableContents=j,b.isMac=se,b.isNotAnnotatable=K,b.isRangeAnnotatable=ne,b.isRevived=M,b.isWhitespaceOrEmpty=le,b.mergeClientRects=de,b.paint=he,b.parseW3CTextAnnotation=Ce,b.programmaticallyFocusable=re,b.rangeToSelector=ue,b.reviveAnnotation=G,b.reviveSelector=Z,b.reviveTarget=V,b.scrollIntoView=me,b.serializeW3CTextAnnotation=Ae,b.splitAnnotatableRanges=ie,b.toDomRectList=He,b.trimRangeToContainer=fe,b.whitespaceOrEmptyRegex=ce,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})}));
3
3
  //# sourceMappingURL=text-annotator.umd.js.map