react-iiif-vault 0.9.5 → 0.9.8

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 +1,1752 @@
1
- import g,{useContext as O,useMemo as m,useState as w,useEffect as b,createContext as je,useCallback as C,useRef as Q,useLayoutEffect as Fe}from"react";import{globalVault as X,Vault as J}from"@iiif/vault";import{ImageServiceLoader as Ne,getImageServices as q}from"@atlas-viewer/iiif-image-api";import{createEventsHelper as W,createStylesHelper as Z,createThumbnailHelper as Be}from"@iiif/vault-helpers";import{createAction as y}from"typesafe-actions";var Ue=Object.defineProperty,K=Object.getOwnPropertySymbols,ke=Object.prototype.hasOwnProperty,He=Object.prototype.propertyIsEnumerable,ee=(e,t,n)=>t in e?Ue(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,te=(e,t)=>{for(var n in t||(t={}))ke.call(t,n)&&ee(e,n,t[n]);if(K)for(var n of K(t))He.call(t,n)&&ee(e,n,t[n]);return e};const Qe={collection:void 0,manifest:void 0,range:void 0,canvas:void 0,annotation:void 0},N=g.createContext(Qe),T=()=>O(N),$=({value:e,children:t})=>{const n=T(),r=m(()=>te(te({},n),e),[e,n]);return g.createElement(N.Provider,{value:r},t)},qe=({annotation:e,children:t})=>g.createElement($,{value:{annotation:e}},t),ne=({canvas:e,children:t})=>g.createElement($,{value:{canvas:e}},t),ze=({collection:e,children:t})=>g.createElement($,{value:{collection:e}},t),re=({manifest:e,children:t})=>g.createElement($,{value:{manifest:e}},t),Ye=({range:e,children:t})=>g.createElement($,{value:{range:e}},t),L=g.createContext({vault:null,setVaultInstance:e=>{}}),oe=({vault:e,vaultOptions:t,useGlobal:n,resources:r,children:a})=>{const[i,s]=w(()=>e||(n?X(t):t?new J(t):new J));return g.createElement(L.Provider,{value:{vault:i,setVaultInstance:s}},g.createElement($,{value:r||{}},a))},_=()=>{const{vault:e}=O(L);if(e===null)throw new Error("Vault not found. Ensure you have your provider set up correctly.");return e};var Ge=(e,t,n)=>new Promise((r,a)=>{var i=c=>{try{o(n.next(c))}catch(l){a(l)}},s=c=>{try{o(n.throw(c))}catch(l){a(l)}},o=c=>c.done?r(c.value):Promise.resolve(c.value).then(i,s);o((n=n.apply(e,t)).next())});function z(e,{noCache:t=!1}={}){const n=typeof e=="string"?e:e.id,r=_(),[a,i]=w(n),[s,o]=w(void 0),c=m(()=>r.get(n,{skipSelfReturn:!0})||void 0,[n,r]),[l,d]=w(c);return b(()=>{Ge(this,null,function*(){try{const u=c&&!t?c:yield r.load(n),p=u?u.id||u["@id"]:null;u&&a!==p&&i(p),d(u)}catch(u){o(u)}})},[n,t]),{isLoaded:!!l,id:a,requestId:n,error:s,resource:l,cached:!!(l&&l===c)}}function ie(e,t){const{id:n,isLoaded:r,error:a,resource:i,requestId:s,cached:o}=z(e,t);return{id:n,isLoaded:r,error:a,manifest:i,requestId:s,cached:o}}function E(e,t=[]){const n=_(),[r,a]=w(()=>e(n.getState(),n));return b(()=>n.subscribe(i=>e(i,n),i=>{a(i)},!1),t),r}const D=g.createContext([]);function se(){const e=O(D);return E(t=>e.map(n=>t.iiif.entities.Canvas[n]).filter(Boolean),[e])}const B=()=>{},j=je({setCurrentCanvasId:B,setCurrentCanvasIndex:B,nextCanvas:B,previousCanvas:B,currentCanvasIndex:-1,totalCanvases:0,pagingView:!0}),Xe=e=>{const t=ie(e.manifest),[n,r]=w(""),[a,i]=w([]),s=(typeof e.pagingEnabled>"u"||e.pagingEnabled)&&t.manifest&&t.manifest.behavior&&t.manifest.behavior.includes("paged");b(()=>{var f,v;t.manifest&&(r((f=t.manifest.items[0])==null?void 0:f.id),i([(v=t.manifest.items[0])==null?void 0:v.id]))},[t.manifest,e.manifest]);const o=m(()=>{var f;return((f=t.manifest)==null?void 0:f.items.map(v=>v.id))||[]},[t.manifest,e.manifest]),c=m(()=>o.indexOf(n),[o,n]),l=C(()=>{if(o.length&&n){if(c===-1||(o[c+2]?c+2===o.length:c===o.length))return;const f=s&&c!==0?o[c+2]:o[c+1],v=s?c!==0?o[c+3]:o[c+2]:null;f&&(r(f),i(v?[f,v]:[f]))}},[s,o,n,c]),d=C(()=>{if(o.length&&n){if(c===0||c===-1)return;const f=s&&c!==1?o[c-2]:o[c-1],v=s&&c!==1?o[c-1]:null;f&&(r(f),i(v?[f,v]:[f]))}},[s,o,n,c]),u=C(f=>{const v=s&&f%2===1?f-1:f,P=o[v],M=s&&v!==0?o[v+1]:null;P&&(r(P),i(A=>{const S=M?[P,M]:[P];if(A.length===A.length){for(let I=0;I<A.length;I++)if(A[I]!==S[I])return S;return A}return S}))},[s,o]),p=C(f=>{const v=o.indexOf(f);v!==-1&&u(v)},[o,u]),h=m(()=>({setCurrentCanvasId:p,nextCanvas:l,previousCanvas:d,currentCanvasIndex:c,totalCanvases:o.length,setCurrentCanvasIndex:u,pagingView:!0}),[l,d,c,o,u,p]);return t.manifest?t.isLoaded?g.createElement(j.Provider,{value:h},g.createElement(D.Provider,{value:a},g.createElement(re,{manifest:t.manifest.id},g.createElement(ne,{canvas:n},e.children)))):g.createElement("div",null,"Loading..."):(console.warn("The manifest passed to the provider is not a valid IIIF manifest."),g.createElement("div",null,"Sorry, something went wrong."))};function Je(){return O(j)}function We(){return{VaultContext:O(L),ResourceContext:O(N),SimpleViewerReactContext:O(j),VisibleCanvasReactContext:O(D)}}const Ze=e=>g.createElement(oe,{vault:e.bridge.VaultContext.vault||void 0,resources:e.bridge.ResourceContext},g.createElement(D.Provider,{value:e.bridge.VisibleCanvasReactContext},g.createElement(j.Provider,{value:e.bridge.SimpleViewerReactContext},e.children))),ae=g.createContext(new Ne);function U(){return O(ae)}const Ke=/&?(xywh=)?(pixel:|percent:)?([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?)/,et=/&?(t=)(npt:)?([0-9]+(.[0-9]+)?)?(,([0-9]+(.[0-9]+)?))?/;function k(e){if(Array.isArray(e))return e.reduce((t,n)=>{const{selector:r,selectors:a}=k(n);return r&&(t.selector||(t.selector=r),t.selectors.push(...a)),t},{selector:null,selectors:[]});if(!e)return{selector:null,selectors:[]};if(typeof e=="string"){const[t,n]=e.split("#");return n?k({type:"FragmentSelector",value:n}):{selector:null,selectors:[]}}if(e.type==="PointSelector"&&(e.t||e.t===0)){const t={type:"TemporalSelector",temporal:{startTime:e.t}};return{selector:t,selectors:[t]}}if(e.type==="FragmentSelector"){const t=Ke.exec(e.value);if(t){const r={type:"BoxSelector",spatial:{unit:t[2]==="percent:"?"percent":"pixel",x:parseFloat(t[3]),y:parseFloat(t[4]),width:parseFloat(t[5]),height:parseFloat(t[6])}};return{selector:r,selectors:[r]}}const n=e.value.match(et);if(n){const r={type:"TemporalSelector",temporal:{startTime:n[4]?parseFloat(n[4]):0,endTime:n[7]?parseFloat(n[7]):void 0}};return{selector:r,selectors:[r]}}return{selector:null,selectors:[]}}return{selector:null,selectors:[]}}var tt=Object.defineProperty,nt=Object.defineProperties,rt=Object.getOwnPropertyDescriptors,ce=Object.getOwnPropertySymbols,ot=Object.prototype.hasOwnProperty,it=Object.prototype.propertyIsEnumerable,le=(e,t,n)=>t in e?tt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ue=(e,t)=>{for(var n in t||(t={}))ot.call(t,n)&&le(e,n,t[n]);if(ce)for(var n of ce(t))it.call(t,n)&&le(e,n,t[n]);return e},fe=(e,t)=>nt(e,rt(t));function R(e,t={}){if(Array.isArray(e))return R(e[0]);if(typeof e=="string"){const[n,r]=e.split("#");return r?R({type:"SpecificResource",source:{id:n,type:"Unknown"},selector:{type:"FragmentSelector",value:r}}):{type:"SpecificResource",source:{id:n,type:t.typeMap&&t.typeMap[n]||"Unknown"},selector:null,selectors:[]}}if(e.type==="Choice"||e.type==="List"||e.type==="Composite"||e.type==="Independents")return R(e.items[0]);if(e.type==="SpecificResource"){e.source.type==="Canvas"&&e.source.partOf&&typeof e.source.partOf=="string"&&(e.source.partOf=[{id:e.source.partOf,type:"Manifest"}]);const{selector:n,selectors:r}=e.selector?k(e.selector):{selector:null,selectors:[]};return{type:"SpecificResource",source:e.source,selector:n,selectors:r}}if(e.id){e.type==="Canvas"&&e.partOf&&typeof e.partOf=="string"&&(e.partOf=[{id:e.partOf,type:"Manifest"}]);const[n,r]=e.id.split("#");return r?R({type:"SpecificResource",source:fe(ue({},e),{id:n}),selector:{type:"FragmentSelector",value:r}}):{type:"SpecificResource",source:fe(ue({},e),{id:n}),selector:null,selectors:[]}}return{type:"SpecificResource",source:e,selector:null,selectors:[]}}function de(e){return e.type==="SpecificResource"?[e.source,{selector:e.selector}]:[e,{selector:null}]}function pe(e,t,n){const r=[];let a=null;const i=[];for(const s of t){const o=e.get(s.body);for(const c of o){const[l,{selector:d}]=de(c),u=(l.type||"unknown").toLowerCase();if(u==="choice"){const p=e.get(l.items),h=n.length?n.map(f=>p.find(v=>v.id===f)).filter(Boolean):[p[0]];h.length===0&&h.push(p[0]),a={type:"single-choice",items:p.map(f=>({id:f.id,label:f.label,selected:h.indexOf(f)!==-1})),label:c.label},o.push(...h);continue}r.indexOf(u)===-1&&r.push(u),i.push({type:u,resource:l,target:s.target,selector:d})}}return{types:r,items:i,choice:a}}const ve={makeChoice:()=>{}},Y={type:"unknown"},x=e=>({type:"unknown",reason:e,annotations:{pages:[]}});function me(e,t,n){const r=[];for(const a of t.items){const i=a.resource&&a.resource.type==="SpecificResource"?a.resource.source:a.resource;if(!i.id)return x("No resource Identifier");let s;if(i.service){const v=q(i);v[0]&&(s=n(v[0],e))}const{selector:o,source:c}=R(a.target);if(c.id!==e.id)continue;const l={type:"BoxSelector",spatial:{x:0,y:0,width:e.width,height:e.height}},d=o?o.type==="TemporalSelector"?{type:"TemporalBoxSelector",temporal:o.temporal,spatial:l.spatial}:o:null,u={type:"BoxSelector",spatial:{x:0,y:0,width:e.width,height:e.height}},p=a.resource.type==="SpecificResource"?R(a.resource):null,h=p&&p.selector&&(p.selector.type==="BoxSelector"||p.selector.type==="TemporalBoxSelector")?{type:"BoxSelector",spatial:{x:p.selector.spatial.x,y:p.selector.spatial.y,width:p.selector.spatial.width,height:p.selector.spatial.height}}:u,f={id:i.id,type:"Image",width:d?i.width:e.width,height:d?i.height:e.height,service:s,sizes:s&&s.sizes?s.sizes:i.width&&i.height?[{width:i.width,height:i.height}]:[],target:d&&d.type!=="PointSelector"?d:l,selector:h};r.push(f)}return{type:"images",image:r[0],images:r,choice:t.choice}}var st=Object.defineProperty,at=Object.defineProperties,ct=Object.getOwnPropertyDescriptors,ge=Object.getOwnPropertySymbols,lt=Object.prototype.hasOwnProperty,ut=Object.prototype.propertyIsEnumerable,he=(e,t,n)=>t in e?st(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ft=(e,t)=>{for(var n in t||(t={}))lt.call(t,n)&&he(e,n,t[n]);if(ge)for(var n of ge(t))ut.call(t,n)&&he(e,n,t[n]);return e},dt=(e,t)=>at(e,ct(t));function pt(e={},t=[]){const{id:n,selector:r}=e,a=T(),i=_(),s=n||a.annotation,o=E(l=>s?l.iiif.entities.Annotation[s]:void 0,[s]),c=E(l=>o&&o.body?o.body.map(d=>d?l.iiif.entities[d.type][d.id]:null).filter(Boolean):[],[o]);return m(()=>{if(!o)return;const l=dt(ft({},o),{body:c,target:R(o.target,{typeMap:i.getState().iiif.mapping})});return r?r(l):l},[o,r,c,...t])}function F(e={},t=[]){const{id:n,selector:r}=e,a=T();_();const i=n||a.manifest,s=E(o=>i?o.iiif.entities.Manifest[i]:void 0,[i]);return m(()=>{if(!!s)return r?r(s):s},[s,r,...t])}function V(e={},t=[]){const{id:n,selector:r}=e,a=T(),i=n||a.canvas,s=E(o=>i?o.iiif.entities.Canvas[i]:void 0,[i]);return m(()=>{if(!!s)return r?r(s):s},[s,r,...t])}function vt(e,t){var n;const r=(n=e==null?void 0:e.iiif)==null?void 0:n.meta[t];return r?r.annotationPageManager:null}function mt(e,t){return E(n=>{const r=[];if(!e)return r;const a=Object.keys(n.iiif.entities.AnnotationPage);for(const i of a)if(!t||t.indexOf(i)!==-1){const s=vt(n,i);s&&s.views&&s.views[e]&&r.push(i)}return r},[e,t])}function ye({canvas:e,manifest:t,all:n,canvases:r}){const a=[];if(t)for(const i of t.annotations)a.indexOf(i.id)===-1&&a.push(i.id);if(n){if(r&&r.length)for(const i of r)for(const s of i.annotations)a.indexOf(s.id)===-1&&a.push(s.id)}else if(e)for(const i of e.annotations)a.indexOf(i.id)===-1&&a.push(i.id);return a}var gt=Object.defineProperty,ht=Object.defineProperties,yt=Object.getOwnPropertyDescriptors,_e=Object.getOwnPropertySymbols,_t=Object.prototype.hasOwnProperty,Pt=Object.prototype.propertyIsEnumerable,Pe=(e,t,n)=>t in e?gt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Se=(e,t)=>{for(var n in t||(t={}))_t.call(t,n)&&Pe(e,n,t[n]);if(_e)for(var n of _e(t))Pt.call(t,n)&&Pe(e,n,t[n]);return e},we=(e,t)=>ht(e,yt(t));function St(e,t){var n;const r=(n=e==null?void 0:e.iiif)==null?void 0:n.meta[t];return r?r.annotationPageManager:null}function Ee(e,t={}){const n=_(),r=F(),a=V(),i=se(),s=m(()=>ye({all:t.all,manifest:r,canvas:a,canvases:i}),[t.all,a,i,r]),o=mt(e,t.all?void 0:s),c=C(d=>{!e||n.setMetaValue([d,"annotationPageManager","views"],u=>u&&!u[e]?u:we(Se({},u||{}),{[e]:!1}))},[e,n]),l=C((d,u={})=>{if(!e)return;const p=n.getState(),h=[];if(u==null?void 0:u.deselectOthers){const f=Object.keys(p.iiif.entities.AnnotationPage);for(const v of f){const P=St(p,v);P&&P.views&&P.views[e]&&h.push(v)}}for(const f of h)c(f);n.setMetaValue([d,"annotationPageManager","views"],f=>f&&f[e]?f:we(Se({},f||{}),{[e]:!0}))},[e,c,n]);return{availablePageIds:s,enabledPageIds:o,setPageEnabled:l,setPageDisabled:c}}function H(e={}){const t=V(e.canvasId?{id:e.canvasId}:void 0);return E((n,r)=>{if(!t)return[];const a=r.get(t.items),i=[];for(const s of a)i.push(...r.get(s.items));return i},[t])}function wt(e,t={}){return H(t)}function Et(e,t=!1){}function Ot(e,t=[]){const{id:n,selector:r}=e,a=T(),i=n||a.collection,s=E(o=>i?o.iiif.entities.Collection[i]:void 0,[i]);return m(()=>{if(!!s)return r?r(s):s},[s,r,...t])}function Oe(){const t=_().getStore();return m(()=>n=>t.dispatch(n),[t])}function Ct(e,t,n,r,a=[]){const i=_(),s=m(()=>W(i),[i]);b(()=>{const o=e;return o?(s.addEventListener(o,t,n,r),()=>{s.removeEventListener(o,t,n)}):()=>{}},[s,e,t,...a])}function xt(){const e=O(L);return e&&e.vault?e.vault:X()}function It(e,t){const{id:n,isLoaded:r,error:a,resource:i,requestId:s,cached:o}=z(e,t);return{id:n,isLoaded:r,error:a,manifest:i,requestId:s,cached:o}}var bt=(e,t,n)=>new Promise((r,a)=>{var i=c=>{try{o(n.next(c))}catch(l){a(l)}},s=c=>{try{o(n.throw(c))}catch(l){a(l)}},o=c=>c.done?r(c.value):Promise.resolve(c.value).then(i,s);o((n=n.apply(e,t)).next())});function Ce({cacheKey:e}={}){const t=V(),n=H(),r=_(),a=U(),[i,s]=w(void 0),[o,c]=w(!1),[l,d]=w("idle"),[u,p]=w(void 0),h=t?t.id:"undefined",f=m(()=>{try{if(t&&n.length){const P=n[0],M=r.get(P.body[0]),S=q(M)[0];return S&&a.loadServiceSync({id:S.id||S["@id"],width:S.width||t.width,height:S.height||t.height})||void 0}}catch(P){console.error(P)}},[h,e,t]),v=l==="success"&&i?i:f;return b(()=>{bt(this,null,function*(){try{if(t&&n.length){const P=n[0],M=r.get(P.body[0]),S=q(M)[0];if(!S)return;c(!0),d("loading");try{const I=(yield a.loadService({id:S.id||S["@id"],width:S.width||t.width,height:S.height||t.height}))||void 0;s(I),d("success"),c(!1)}catch(I){d("error"),p(I)}}}catch(P){d("error"),p(P)}})},[h,e]),m(()=>({data:v,isFetching:o,status:l,error:u}),[v,o,l,u])}function Rt(){const e=Ce();return{isLoading:e.isFetching,tile:e.data?{id:e.data.id||e.data["@id"],width:e.data.width,height:e.data.height,imageService:e.data,thumbnail:void 0}:null}}function xe(e,t=[]){const n=_(),r=H(),[a,i]=w((e==null?void 0:e.defaultChoices)||[]),s=m(()=>pe(n,r,a),[n,r,a,...t]),c={makeChoice:C((l,{deselectOthers:d=!0,deselect:u=!1}={})=>{if(s.choice){if(s.choice.type!=="single-choice")throw new Error("Complex choice not supported yet");i(p=>{if(u){const f=p.filter(v=>v!==l);if(f.length===0){const v=s.items[0].resource.id;return v?[v]:[]}return f}if(d)return[l];const h=[...p];if(h.length===0&&s.items.length){const f=s.items[0].resource.id;f&&h.push(f)}return p.indexOf(l)!==-1?p:[...p,l]})}},[s.choice])};return[s,c]}function At(e={},t=[]){const{id:n,selector:r}=e,a=T(),i=n||a.range,s=E(o=>i?o.iiif.entities.Range[i]:void 0,[i]);return m(()=>{if(!!s)return r?r(s):s},[s,r,...t])}function Tt(e,t){const n=_(),r=m(()=>W(n),[n]),a=E(()=>e&&e.id?n.getResourceMeta(e.id,"eventManager"):null,[e]);return m(()=>e?r.getListenersAsProps(e,t):{},[a,e,n,t])}function Ie(e,t){return E((n,r)=>r.get(e.map(a=>({id:a,type:t}))),[e,t])}function $t(){const e=F();return e?e.service.find(t=>t.profile==="SearchService1"||t.profile==="http://iiif.io/api/search/1/search"):void 0}function Mt(){const e=_();return m(()=>Z(e),[e])}function Vt(e,t){const n=_(),r=m(()=>Z(n),[n]);return E(()=>{if(!e)return null;const a=r.getAppliedStyles(e.id);return a?t?a[t]:a:void 0},[e,t])}const be=(e,t=[])=>{const n=_();b(()=>{e(n)},[n,...t])};function Lt(e,t,{canvasId:n,manifestId:r}={}){const a=_(),i=U(),s=m(()=>Be(a,{imageServiceLoader:i}),[a,i]),[o,c]=w(),l=F(r?{id:r}:void 0),d=V(n?{id:n}:void 0),u=d||l,p=Q(!1);if(b(()=>()=>{p.current=!0},[]),!u)throw new Error("Must be called under a manifest or canvas context.");return be(h=>{s.getBestThumbnailAtSize(u,e,t).then(f=>{f.best&&!p.current&&c(f.best)})},[u]),o}var Dt=Object.defineProperty,jt=Object.defineProperties,Ft=Object.getOwnPropertyDescriptors,Re=Object.getOwnPropertySymbols,Nt=Object.prototype.hasOwnProperty,Bt=Object.prototype.propertyIsEnumerable,Ae=(e,t,n)=>t in e?Dt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Te=(e,t)=>{for(var n in t||(t={}))Nt.call(t,n)&&Ae(e,n,t[n]);if(Re)for(var n of Re(t))Bt.call(t,n)&&Ae(e,n,t[n]);return e},$e=(e,t)=>jt(e,Ft(t));function Me(){const e=U(),[t,n]=w({}),r=Q(!1);return b(()=>()=>{r.current=!0},[]),[C((i,{height:s,width:o})=>{if(i){const c=i.id||i["@id"],l=e.loadServiceSync({id:c,width:i.width||o,height:i.height||s});l?i=l:t[c]||(r.current||n(d=>$e(Te({},d),{[c]:"loading"})),e.loadService({id:c,width:i.width||o,height:i.height||s}).then(()=>{r.current||n(d=>$e(Te({},d),{[c]:"done"}))}))}return i},[e,t]),t]}const Ut="@iiif/IMPORT_ENTITIES",kt="@iiif/MODIFY_ENTITY_FIELD",Ht="@iiif/REORDER_ENTITY_FIELD",Qt="@iiif/ADD_REFERENCE",qt="@iiif/REMOVE_REFERENCE",zt=y(Ut)(),Yt=y(kt)(),Gt=y(Ht)(),Xt=y(Qt)(),Jt=y(qt)(),G={importEntities:zt,modifyEntityField:Yt,reorderEntityField:Gt,addReference:Xt,removeReference:Jt},Wt="@iiif/ADD_MAPPING",Zt="@iiif/ADD_MAPPINGS";y(Wt)(),y(Zt)();const Kt="@iiif/SET_META_VALUE",en="@iiif/SET_META_VALUE_DYNAMIC",tn="@iiif/UNSET_META_VALUE";y(Kt)(),y(en)(),y(tn)();const nn="@iiif/REQUEST_RESOURCE",rn="@iiif/REQUEST_ERROR",on="@iiif/REQUEST_MISMATCH",sn="@iiif/REQUEST_COMPLETE",an="@iiif/REQUEST_OFFLINE_RESOURCE";y(nn)(),y(rn)(),y(on)(),y(sn)(),y(an)();const cn="@iiif/BATCH",ln="@iiif/BATCH_IMPORT";y(cn)(),y(ln)();function Ve(e){return typeof e!="string"&&e&&e.bindToVault}function un(){const e=_(),t=Q([]),n=Oe(),r=m(()=>`vault://annotation-page/${new Date().getTime()}/${Math.round(Math.random()*1e9).toString(16)}`,[]);Fe(()=>{const o={id:r,type:"AnnotationPage",behavior:[],motivation:null,label:null,thumbnail:[],summary:null,requiredStatement:null,metadata:[],rights:null,provider:[],items:[],seeAlso:[],homepage:[],logo:[],rendering:[],service:[]};n(G.importEntities({entities:{AnnotationPage:{[o.id]:o}}}))},[r]);const a=E(o=>r?o.iiif.entities.AnnotationPage[r]:null,[r]),i=C((o,c)=>{if(r){if(Ve(o)){const u=o;u.__vault||u.bindToVault(e),o=typeof u.source=="string"?u.source:u.source.id,t.current[o]=u}else typeof o!="string"&&(o=o.id);const l=e.get({id:r,type:"AnnotationPage"}),d=e.get({id:o,type:"Annotation"});l&&d&&(l.items.find(u=>u.id===d.id)||n(G.addReference({id:r,type:"AnnotationPage",key:"items",reference:{id:o,type:"Annotation"},index:c})))}},[r]),s=C(o=>{r&&(Ve(o)?o=typeof o.source=="string"?o.source:o.source.id:typeof o!="string"&&(o=o.id),t.current[o]&&t.current[o].beforeRemove(),e.get({id:r,type:"AnnotationPage"})&&n(G.removeReference({id:r,type:"AnnotationPage",key:"items",reference:{id:o,type:"Annotation"}})))},[r]);return[a,{addAnnotation:i,removeAnnotation:s}]}var fn=Object.defineProperty,dn=Object.defineProperties,pn=Object.getOwnPropertyDescriptors,Le=Object.getOwnPropertySymbols,vn=Object.prototype.hasOwnProperty,mn=Object.prototype.propertyIsEnumerable,De=(e,t,n)=>t in e?fn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,gn=(e,t)=>{for(var n in t||(t={}))vn.call(t,n)&&De(e,n,t[n]);if(Le)for(var n of Le(t))mn.call(t,n)&&De(e,n,t[n]);return e},hn=(e,t)=>dn(e,pn(t));function yn(e){const t=F(),n=V(),r=_(),[a,i]=Me(),{enabledPageIds:s}=Ee((e==null?void 0:e.annotationPageManagerId)||(t==null?void 0:t.id)||(n==null?void 0:n.id),{all:!1}),o=Ie(s,"AnnotationPage"),c=(e==null?void 0:e.strategies)||["images","media","complex-timeline"],[l,d]=xe(e,[i]),u=m(()=>{if(!n||l.types.length===0)return Y;if(l.types.length!==1)return c.indexOf("complex-timeline")===-1?x("Complex timeline not supported"):x("ComplexTimelineStrategy not yet supported");const p=l.types[0];return p==="image"?c.indexOf("images")===-1?x("Image not supported"):me(n,l,a):p==="audio"?c.indexOf("media")===-1?x("Media not supported"):x("Audio strategy not yet supported"):p==="video"?c.indexOf("media")===-1?x("Media not supported"):x("Video strategy not yet supported"):Y},[n,l,r,d.makeChoice]);return m(()=>u.type==="unknown"?[u,ve]:[hn(gn({},u),{annotations:{pages:o}}),d],[u,o])}export{qe as AnnotationContext,ne as CanvasContext,ze as CollectionContext,Ze as ContextBridge,ae as ImageServiceLoaderContext,re as ManifestContext,Ye as RangeContext,L as ReactVaultContext,$ as ResourceProvider,N as ResourceReactContext,Xe as SimpleViewerProvider,j as SimpleViewerReactContext,oe as VaultProvider,D as VisibleCanvasReactContext,ve as emptyActions,R as expandTarget,ye as flattenAnnotationPageIds,me as getImageStrategy,pe as getPaintables,k as parseSelector,de as parseSpecificResource,Y as unknownResponse,x as unsupportedStrategy,pt as useAnnotation,Ee as useAnnotationPageManager,wt as useAnnotationsAtTime,V as useCanvas,Et as useCanvasClock,Ot as useCollection,We as useContextBridge,Oe as useDispatch,Ct as useEventListener,xt as useExistingVault,It as useExternalCollection,ie as useExternalManifest,z as useExternalResource,Ce as useImageService,U as useImageServiceLoader,Rt as useImageTile,Me as useLoadImageService,F as useManifest,xe as usePaintables,H as usePaintingAnnotations,At as useRange,yn as useRenderingStrategy,T as useResourceContext,Tt as useResourceEvents,Ie as useResources,$t as useSearchService,Je as useSimpleViewer,Mt as useStyleHelper,Vt as useStyles,Lt as useThumbnail,_ as useVault,be as useVaultEffect,E as useVaultSelector,un as useVirtualAnnotationPage,se as useVisibleCanvases};
1
+ import React, { useContext, useMemo, useState, useEffect, createContext, useCallback, useRef, useLayoutEffect, Fragment } from 'react';
2
+ import { globalVault, Vault } from '@iiif/vault';
3
+ import { AtlasAuto, mergeStyles, RegionHighlight, TileSet as TileSet$1 } from '@atlas-viewer/atlas';
4
+ import { createAction } from 'typesafe-actions';
5
+ import { createEventsHelper, createStylesHelper, createThumbnailHelper } from '@iiif/vault-helpers';
6
+ import { ImageServiceLoader, getImageServices } from '@atlas-viewer/iiif-image-api';
7
+
8
+ var __defProp$8 = Object.defineProperty;
9
+ var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
10
+ var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues$8 = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp$8.call(b, prop))
16
+ __defNormalProp$8(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols$8)
18
+ for (var prop of __getOwnPropSymbols$8(b)) {
19
+ if (__propIsEnum$8.call(b, prop))
20
+ __defNormalProp$8(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ const defaultResourceContext = {
25
+ collection: void 0,
26
+ manifest: void 0,
27
+ range: void 0,
28
+ canvas: void 0,
29
+ annotation: void 0
30
+ };
31
+ const ResourceReactContext = React.createContext(defaultResourceContext);
32
+ const useResourceContext = () => {
33
+ return useContext(ResourceReactContext);
34
+ };
35
+ const ResourceProvider = ({ value, children }) => {
36
+ const parentContext = useResourceContext();
37
+ const newContext = useMemo(() => {
38
+ return __spreadValues$8(__spreadValues$8({}, parentContext), value);
39
+ }, [value, parentContext]);
40
+ return /* @__PURE__ */ React.createElement(ResourceReactContext.Provider, {
41
+ value: newContext
42
+ }, children);
43
+ };
44
+
45
+ const ReactVaultContext = React.createContext({
46
+ vault: null,
47
+ setVaultInstance: (vault) => {
48
+ }
49
+ });
50
+ const VaultProvider = ({ vault, vaultOptions, useGlobal, resources, children }) => {
51
+ const [vaultInstance, setVaultInstance] = useState(() => {
52
+ if (vault) {
53
+ return vault;
54
+ }
55
+ if (useGlobal) {
56
+ return globalVault(vaultOptions);
57
+ }
58
+ if (vaultOptions) {
59
+ return new Vault(vaultOptions);
60
+ }
61
+ return new Vault();
62
+ });
63
+ return /* @__PURE__ */ React.createElement(ReactVaultContext.Provider, {
64
+ value: { vault: vaultInstance, setVaultInstance }
65
+ }, /* @__PURE__ */ React.createElement(ResourceProvider, {
66
+ value: resources || {}
67
+ }, children));
68
+ };
69
+
70
+ const useVault = () => {
71
+ const { vault } = useContext(ReactVaultContext);
72
+ if (vault === null) {
73
+ throw new Error("Vault not found. Ensure you have your provider set up correctly.");
74
+ }
75
+ return vault;
76
+ };
77
+
78
+ var __async$1 = (__this, __arguments, generator) => {
79
+ return new Promise((resolve, reject) => {
80
+ var fulfilled = (value) => {
81
+ try {
82
+ step(generator.next(value));
83
+ } catch (e) {
84
+ reject(e);
85
+ }
86
+ };
87
+ var rejected = (value) => {
88
+ try {
89
+ step(generator.throw(value));
90
+ } catch (e) {
91
+ reject(e);
92
+ }
93
+ };
94
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
95
+ step((generator = generator.apply(__this, __arguments)).next());
96
+ });
97
+ };
98
+ function useExternalResource(idOrRef, { noCache = false } = {}) {
99
+ const id = typeof idOrRef === "string" ? idOrRef : idOrRef.id;
100
+ const vault = useVault();
101
+ const [realId, setRealId] = useState(id);
102
+ const [error, setError] = useState(void 0);
103
+ const initialData = useMemo(() => {
104
+ return vault.get(id, { skipSelfReturn: true }) || void 0;
105
+ }, [id, vault]);
106
+ const [resource, setResource] = useState(initialData);
107
+ useEffect(() => {
108
+ (() => __async$1(this, null, function* () {
109
+ try {
110
+ const fetchedResource = initialData && !noCache ? initialData : yield vault.load(id);
111
+ const _realId = fetchedResource ? fetchedResource.id || fetchedResource["@id"] : null;
112
+ if (fetchedResource && realId !== _realId) {
113
+ setRealId(_realId);
114
+ }
115
+ setResource(fetchedResource);
116
+ } catch (err) {
117
+ setError(err);
118
+ }
119
+ }))();
120
+ }, [id, noCache]);
121
+ return {
122
+ isLoaded: !!resource,
123
+ id: realId,
124
+ requestId: id,
125
+ error,
126
+ resource,
127
+ cached: !!(resource && resource === initialData)
128
+ };
129
+ }
130
+
131
+ function useExternalManifest(idOrRef, options) {
132
+ const { id, isLoaded, error, resource, requestId, cached } = useExternalResource(idOrRef, options);
133
+ return { id, isLoaded, error, manifest: resource, requestId, cached };
134
+ }
135
+
136
+ const ManifestContext = ({ manifest, children }) => {
137
+ return /* @__PURE__ */ React.createElement(ResourceProvider, {
138
+ value: { manifest }
139
+ }, children);
140
+ };
141
+
142
+ const CanvasContext = ({ canvas, children }) => {
143
+ return /* @__PURE__ */ React.createElement(ResourceProvider, {
144
+ value: { canvas }
145
+ }, children);
146
+ };
147
+
148
+ function useVaultSelector(selector, deps = []) {
149
+ const vault = useVault();
150
+ const [selectedState, setSelectedState] = useState(() => selector(vault.getState(), vault));
151
+ useEffect(() => {
152
+ return vault.subscribe((s) => selector(s, vault), setSelectedState, false);
153
+ }, deps);
154
+ return selectedState;
155
+ }
156
+
157
+ const VisibleCanvasReactContext = React.createContext([]);
158
+ function useVisibleCanvases() {
159
+ const ids = useContext(VisibleCanvasReactContext);
160
+ return useVaultSelector((state) => {
161
+ return ids.map((id) => state.iiif.entities.Canvas[id]).filter(Boolean);
162
+ }, [ids]);
163
+ }
164
+
165
+ const noop = () => {
166
+ };
167
+ const SimpleViewerReactContext = createContext({
168
+ setCurrentCanvasId: noop,
169
+ setCurrentCanvasIndex: noop,
170
+ nextCanvas: noop,
171
+ previousCanvas: noop,
172
+ currentCanvasIndex: -1,
173
+ totalCanvases: 0,
174
+ pagingView: true
175
+ });
176
+ const SimpleViewerProvider = (props) => {
177
+ const manifest = useExternalManifest(props.manifest);
178
+ const [currentCanvasId, setCurrentCanvasId] = useState("");
179
+ const [visible, setVisible] = useState([]);
180
+ const pagingView = (typeof props.pagingEnabled === "undefined" || props.pagingEnabled) && manifest.manifest && manifest.manifest.behavior && manifest.manifest.behavior.includes("paged");
181
+ useEffect(() => {
182
+ var _a, _b;
183
+ if (manifest.manifest) {
184
+ setCurrentCanvasId((_a = manifest.manifest.items[0]) == null ? void 0 : _a.id);
185
+ setVisible([(_b = manifest.manifest.items[0]) == null ? void 0 : _b.id]);
186
+ }
187
+ }, [manifest.manifest, props.manifest]);
188
+ const canvasList = useMemo(() => {
189
+ var _a;
190
+ return ((_a = manifest.manifest) == null ? void 0 : _a.items.map((c) => c.id)) || [];
191
+ }, [manifest.manifest, props.manifest]);
192
+ const currentCanvasIndex = useMemo(() => canvasList.indexOf(currentCanvasId), [canvasList, currentCanvasId]);
193
+ const nextCanvas = useCallback(() => {
194
+ if (canvasList.length && currentCanvasId) {
195
+ if (currentCanvasIndex === -1) {
196
+ return;
197
+ }
198
+ if (canvasList[currentCanvasIndex + 2] ? currentCanvasIndex + 2 === canvasList.length : currentCanvasIndex === canvasList.length) {
199
+ return;
200
+ }
201
+ const newCanvas = pagingView && currentCanvasIndex !== 0 ? canvasList[currentCanvasIndex + 2] : canvasList[currentCanvasIndex + 1];
202
+ const pageCanvas = pagingView ? currentCanvasIndex !== 0 ? canvasList[currentCanvasIndex + 3] : canvasList[currentCanvasIndex + 2] : null;
203
+ if (newCanvas) {
204
+ setCurrentCanvasId(newCanvas);
205
+ setVisible(pageCanvas ? [newCanvas, pageCanvas] : [newCanvas]);
206
+ }
207
+ }
208
+ }, [pagingView, canvasList, currentCanvasId, currentCanvasIndex]);
209
+ const previousCanvas = useCallback(() => {
210
+ if (canvasList.length && currentCanvasId) {
211
+ if (currentCanvasIndex === 0 || currentCanvasIndex === -1) {
212
+ return;
213
+ }
214
+ const newCanvas = pagingView && currentCanvasIndex !== 1 ? canvasList[currentCanvasIndex - 2] : canvasList[currentCanvasIndex - 1];
215
+ const pageCanvas = pagingView && currentCanvasIndex !== 1 ? canvasList[currentCanvasIndex - 1] : null;
216
+ if (newCanvas) {
217
+ setCurrentCanvasId(newCanvas);
218
+ setVisible(pageCanvas ? [newCanvas, pageCanvas] : [newCanvas]);
219
+ }
220
+ }
221
+ }, [pagingView, canvasList, currentCanvasId, currentCanvasIndex]);
222
+ const setCurrentCanvasIndex = useCallback((idx) => {
223
+ const realIdx = pagingView && idx % 2 === 1 ? idx - 1 : idx;
224
+ const newId = canvasList[realIdx];
225
+ const newNextId = pagingView && realIdx !== 0 ? canvasList[realIdx + 1] : null;
226
+ if (newId) {
227
+ setCurrentCanvasId(newId);
228
+ setVisible((prevValue) => {
229
+ const newValue = newNextId ? [newId, newNextId] : [newId];
230
+ if (prevValue.length === prevValue.length) {
231
+ for (let i = 0; i < prevValue.length; i++) {
232
+ if (prevValue[i] !== newValue[i]) {
233
+ return newValue;
234
+ }
235
+ }
236
+ return prevValue;
237
+ }
238
+ return newValue;
239
+ });
240
+ }
241
+ }, [pagingView, canvasList]);
242
+ const internalSetCurrentCanvasId = useCallback((nextId) => {
243
+ const idx = canvasList.indexOf(nextId);
244
+ if (idx !== -1) {
245
+ setCurrentCanvasIndex(idx);
246
+ }
247
+ }, [canvasList, setCurrentCanvasIndex]);
248
+ const ctx = useMemo(() => ({
249
+ setCurrentCanvasId: internalSetCurrentCanvasId,
250
+ nextCanvas,
251
+ previousCanvas,
252
+ currentCanvasIndex,
253
+ totalCanvases: canvasList.length,
254
+ setCurrentCanvasIndex,
255
+ pagingView: true
256
+ }), [nextCanvas, previousCanvas, currentCanvasIndex, canvasList, setCurrentCanvasIndex, internalSetCurrentCanvasId]);
257
+ if (!manifest.manifest) {
258
+ console.warn("The manifest passed to the provider is not a valid IIIF manifest.");
259
+ return /* @__PURE__ */ React.createElement("div", null, "Sorry, something went wrong.");
260
+ }
261
+ if (!manifest.isLoaded) {
262
+ return /* @__PURE__ */ React.createElement("div", null, "Loading...");
263
+ }
264
+ return /* @__PURE__ */ React.createElement(SimpleViewerReactContext.Provider, {
265
+ value: ctx
266
+ }, /* @__PURE__ */ React.createElement(VisibleCanvasReactContext.Provider, {
267
+ value: visible
268
+ }, /* @__PURE__ */ React.createElement(ManifestContext, {
269
+ manifest: manifest.manifest.id
270
+ }, /* @__PURE__ */ React.createElement(CanvasContext, {
271
+ canvas: currentCanvasId
272
+ }, props.children))));
273
+ };
274
+ function useSimpleViewer() {
275
+ return useContext(SimpleViewerReactContext);
276
+ }
277
+
278
+ function useContextBridge() {
279
+ return {
280
+ VaultContext: useContext(ReactVaultContext),
281
+ ResourceContext: useContext(ResourceReactContext),
282
+ SimpleViewerReactContext: useContext(SimpleViewerReactContext),
283
+ VisibleCanvasReactContext: useContext(VisibleCanvasReactContext)
284
+ };
285
+ }
286
+ const ContextBridge = (props) => {
287
+ return /* @__PURE__ */ React.createElement(VaultProvider, {
288
+ vault: props.bridge.VaultContext.vault || void 0,
289
+ resources: props.bridge.ResourceContext
290
+ }, /* @__PURE__ */ React.createElement(VisibleCanvasReactContext.Provider, {
291
+ value: props.bridge.VisibleCanvasReactContext
292
+ }, /* @__PURE__ */ React.createElement(SimpleViewerReactContext.Provider, {
293
+ value: props.bridge.SimpleViewerReactContext
294
+ }, props.children)));
295
+ };
296
+
297
+ const IMPORT_ENTITIES = "@iiif/IMPORT_ENTITIES";
298
+ const MODIFY_ENTITY_FIELD = "@iiif/MODIFY_ENTITY_FIELD";
299
+ const REORDER_ENTITY_FIELD = "@iiif/REORDER_ENTITY_FIELD";
300
+ const ADD_REFERENCE = "@iiif/ADD_REFERENCE";
301
+ const REMOVE_REFERENCE = "@iiif/REMOVE_REFERENCE";
302
+ const importEntities = createAction(IMPORT_ENTITIES)();
303
+ const modifyEntityField = createAction(MODIFY_ENTITY_FIELD)();
304
+ const reorderEntityField = createAction(REORDER_ENTITY_FIELD)();
305
+ const addReference = createAction(ADD_REFERENCE)();
306
+ const removeReference = createAction(REMOVE_REFERENCE)();
307
+ const entityActions = { importEntities, modifyEntityField, reorderEntityField, addReference, removeReference };
308
+
309
+ const ADD_MAPPING = "@iiif/ADD_MAPPING";
310
+ const ADD_MAPPINGS = "@iiif/ADD_MAPPINGS";
311
+ createAction(ADD_MAPPING)();
312
+ createAction(ADD_MAPPINGS)();
313
+
314
+ const SET_META_VALUE = "@iiif/SET_META_VALUE";
315
+ const SET_META_VALUE_DYNAMIC = "@iiif/SET_META_VALUE_DYNAMIC";
316
+ const UNSET_META_VALUE = "@iiif/UNSET_META_VALUE";
317
+ createAction(SET_META_VALUE)();
318
+ createAction(SET_META_VALUE_DYNAMIC)();
319
+ createAction(UNSET_META_VALUE)();
320
+ const REQUEST_RESOURCE = "@iiif/REQUEST_RESOURCE";
321
+ const REQUEST_ERROR = "@iiif/REQUEST_ERROR";
322
+ const REQUEST_MISMATCH = "@iiif/REQUEST_MISMATCH";
323
+ const REQUEST_COMPLETE = "@iiif/REQUEST_COMPLETE";
324
+ const REQUEST_OFFLINE_RESOURCE = "@iiif/REQUEST_OFFLINE_RESOURCE";
325
+ createAction(REQUEST_RESOURCE)();
326
+ createAction(REQUEST_ERROR)();
327
+ createAction(REQUEST_MISMATCH)();
328
+ createAction(REQUEST_COMPLETE)();
329
+ createAction(REQUEST_OFFLINE_RESOURCE)();
330
+
331
+ const BATCH_ACTIONS = "@iiif/BATCH";
332
+ const BATCH_IMPORT = "@iiif/BATCH_IMPORT";
333
+ createAction(BATCH_ACTIONS)();
334
+ createAction(BATCH_IMPORT)();
335
+
336
+ function useDispatch() {
337
+ const vault = useVault();
338
+ const store = vault.getStore();
339
+ return useMemo(() => {
340
+ return (action) => store.dispatch(action);
341
+ }, [store]);
342
+ }
343
+
344
+ function isVaultActivated(obj) {
345
+ return typeof obj !== "string" && obj && obj.bindToVault;
346
+ }
347
+ function useVirtualAnnotationPage() {
348
+ const vault = useVault();
349
+ const sources = useRef([]);
350
+ const dispatch = useDispatch();
351
+ const virtualId = useMemo(() => {
352
+ return `vault://annotation-page/${new Date().getTime()}/${Math.round(Math.random() * 1e9).toString(16)}`;
353
+ }, []);
354
+ useLayoutEffect(() => {
355
+ const page = {
356
+ id: virtualId,
357
+ type: "AnnotationPage",
358
+ behavior: [],
359
+ motivation: null,
360
+ label: null,
361
+ thumbnail: [],
362
+ summary: null,
363
+ requiredStatement: null,
364
+ metadata: [],
365
+ rights: null,
366
+ provider: [],
367
+ items: [],
368
+ seeAlso: [],
369
+ homepage: [],
370
+ logo: [],
371
+ rendering: [],
372
+ service: []
373
+ };
374
+ dispatch(entityActions.importEntities({
375
+ entities: {
376
+ AnnotationPage: {
377
+ [page.id]: page
378
+ }
379
+ }
380
+ }));
381
+ }, [virtualId]);
382
+ const fullPage = useVaultSelector((state) => virtualId ? state.iiif.entities.AnnotationPage[virtualId] : null, [virtualId]);
383
+ const addAnnotation = useCallback((id, atIndex) => {
384
+ if (virtualId) {
385
+ if (isVaultActivated(id)) {
386
+ const display = id;
387
+ if (!display.__vault) {
388
+ display.bindToVault(vault);
389
+ }
390
+ id = typeof display.source === "string" ? display.source : display.source.id;
391
+ sources.current[id] = display;
392
+ } else if (typeof id !== "string") {
393
+ id = id.id;
394
+ }
395
+ const full = vault.get({ id: virtualId, type: "AnnotationPage" });
396
+ const annotation = vault.get({ id, type: "Annotation" });
397
+ if (full && annotation) {
398
+ if (!full.items.find((r) => r.id === annotation.id)) {
399
+ dispatch(entityActions.addReference({
400
+ id: virtualId,
401
+ type: "AnnotationPage",
402
+ key: "items",
403
+ reference: {
404
+ id,
405
+ type: "Annotation"
406
+ },
407
+ index: atIndex
408
+ }));
409
+ }
410
+ }
411
+ }
412
+ }, [virtualId]);
413
+ const removeAnnotation = useCallback((id) => {
414
+ if (virtualId) {
415
+ if (isVaultActivated(id)) {
416
+ id = typeof id.source === "string" ? id.source : id.source.id;
417
+ } else if (typeof id !== "string") {
418
+ id = id.id;
419
+ }
420
+ if (sources.current[id]) {
421
+ sources.current[id].beforeRemove();
422
+ }
423
+ const full = vault.get({ id: virtualId, type: "AnnotationPage" });
424
+ if (full) {
425
+ dispatch(entityActions.removeReference({
426
+ id: virtualId,
427
+ type: "AnnotationPage",
428
+ key: "items",
429
+ reference: {
430
+ id,
431
+ type: "Annotation"
432
+ }
433
+ }));
434
+ }
435
+ }
436
+ }, [virtualId]);
437
+ return [
438
+ fullPage,
439
+ {
440
+ addAnnotation,
441
+ removeAnnotation
442
+ }
443
+ ];
444
+ }
445
+
446
+ const VirtualAnnotationPageContext = createContext(null);
447
+ function useVirtualAnnotationPageContext() {
448
+ const ctx = useContext(VirtualAnnotationPageContext);
449
+ return [
450
+ ctx.fullPage,
451
+ {
452
+ addAnnotation: ctx.addAnnotation,
453
+ removeAnnotation: ctx.removeAnnotation
454
+ }
455
+ ];
456
+ }
457
+ function VirtualAnnotationProvider({ children }) {
458
+ const [fullPage, { addAnnotation, removeAnnotation }] = useVirtualAnnotationPage();
459
+ return /* @__PURE__ */ React.createElement(VirtualAnnotationPageContext.Provider, {
460
+ value: useMemo(() => ({ fullPage, addAnnotation, removeAnnotation }), [fullPage])
461
+ }, children);
462
+ }
463
+
464
+ var __defProp$7 = Object.defineProperty;
465
+ var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
466
+ var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
467
+ var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
468
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
469
+ var __spreadValues$7 = (a, b) => {
470
+ for (var prop in b || (b = {}))
471
+ if (__hasOwnProp$7.call(b, prop))
472
+ __defNormalProp$7(a, prop, b[prop]);
473
+ if (__getOwnPropSymbols$7)
474
+ for (var prop of __getOwnPropSymbols$7(b)) {
475
+ if (__propIsEnum$7.call(b, prop))
476
+ __defNormalProp$7(a, prop, b[prop]);
477
+ }
478
+ return a;
479
+ };
480
+ var __objRest = (source, exclude) => {
481
+ var target = {};
482
+ for (var prop in source)
483
+ if (__hasOwnProp$7.call(source, prop) && exclude.indexOf(prop) < 0)
484
+ target[prop] = source[prop];
485
+ if (source != null && __getOwnPropSymbols$7)
486
+ for (var prop of __getOwnPropSymbols$7(source)) {
487
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$7.call(source, prop))
488
+ target[prop] = source[prop];
489
+ }
490
+ return target;
491
+ };
492
+ function Viewer(_a) {
493
+ var _b = _a, {
494
+ children
495
+ } = _b, props = __objRest(_b, [
496
+ "children"
497
+ ]);
498
+ const bridge = useContextBridge();
499
+ return /* @__PURE__ */ React.createElement(AtlasAuto, __spreadValues$7({}, props), /* @__PURE__ */ React.createElement(ContextBridge, {
500
+ bridge
501
+ }, /* @__PURE__ */ React.createElement(VirtualAnnotationProvider, null, children)));
502
+ }
503
+
504
+ function useResourceEvents(resource, scope) {
505
+ const vault = useVault();
506
+ const helper = useMemo(() => createEventsHelper(vault), [vault]);
507
+ const hooks = useVaultSelector(() => {
508
+ if (resource && resource.id) {
509
+ return vault.getResourceMeta(resource.id, "eventManager");
510
+ }
511
+ return null;
512
+ }, [resource]);
513
+ return useMemo(() => {
514
+ return resource ? helper.getListenersAsProps(resource, scope) : {};
515
+ }, [hooks, resource, vault, scope]);
516
+ }
517
+
518
+ function useStyles(resource, scope) {
519
+ const vault = useVault();
520
+ const helper = useMemo(() => createStylesHelper(vault), [vault]);
521
+ return useVaultSelector(() => {
522
+ if (!resource) {
523
+ return null;
524
+ }
525
+ const styles = helper.getAppliedStyles(resource.id);
526
+ return styles ? scope ? styles[scope] : styles : void 0;
527
+ }, [resource, scope]);
528
+ }
529
+
530
+ const BOX_SELECTOR = /&?(xywh=)?(pixel:|percent:)?([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?)/;
531
+ const TEMPORAL_SELECTOR = /&?(t=)(npt:)?([0-9]+(.[0-9]+)?)?(,([0-9]+(.[0-9]+)?))?/;
532
+ function parseSelector(source) {
533
+ if (Array.isArray(source)) {
534
+ return source.reduce((data, nextSource) => {
535
+ const { selector, selectors } = parseSelector(nextSource);
536
+ if (selector) {
537
+ if (!data.selector) {
538
+ data.selector = selector;
539
+ }
540
+ data.selectors.push(...selectors);
541
+ }
542
+ return data;
543
+ }, {
544
+ selector: null,
545
+ selectors: []
546
+ });
547
+ }
548
+ if (!source) {
549
+ return {
550
+ selector: null,
551
+ selectors: []
552
+ };
553
+ }
554
+ if (typeof source === "string") {
555
+ const [id, fragment] = source.split("#");
556
+ if (!fragment) {
557
+ return {
558
+ selector: null,
559
+ selectors: []
560
+ };
561
+ }
562
+ return parseSelector({ type: "FragmentSelector", value: fragment });
563
+ }
564
+ if (source.type === "PointSelector" && (source.t || source.t === 0)) {
565
+ const selector = {
566
+ type: "TemporalSelector",
567
+ temporal: {
568
+ startTime: source.t
569
+ }
570
+ };
571
+ return {
572
+ selector,
573
+ selectors: [selector]
574
+ };
575
+ }
576
+ if (source.type === "FragmentSelector") {
577
+ const matchBoxSelector = BOX_SELECTOR.exec(source.value);
578
+ if (matchBoxSelector) {
579
+ const selector = {
580
+ type: "BoxSelector",
581
+ spatial: {
582
+ unit: matchBoxSelector[2] === "percent:" ? "percent" : "pixel",
583
+ x: parseFloat(matchBoxSelector[3]),
584
+ y: parseFloat(matchBoxSelector[4]),
585
+ width: parseFloat(matchBoxSelector[5]),
586
+ height: parseFloat(matchBoxSelector[6])
587
+ }
588
+ };
589
+ return {
590
+ selector,
591
+ selectors: [selector]
592
+ };
593
+ }
594
+ const matchTimeSelector = source.value.match(TEMPORAL_SELECTOR);
595
+ if (matchTimeSelector) {
596
+ const selector = {
597
+ type: "TemporalSelector",
598
+ temporal: {
599
+ startTime: matchTimeSelector[4] ? parseFloat(matchTimeSelector[4]) : 0,
600
+ endTime: matchTimeSelector[7] ? parseFloat(matchTimeSelector[7]) : void 0
601
+ }
602
+ };
603
+ return {
604
+ selector,
605
+ selectors: [selector]
606
+ };
607
+ }
608
+ return {
609
+ selector: null,
610
+ selectors: []
611
+ };
612
+ }
613
+ return {
614
+ selector: null,
615
+ selectors: []
616
+ };
617
+ }
618
+
619
+ var __defProp$6 = Object.defineProperty;
620
+ var __defProps$4 = Object.defineProperties;
621
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
622
+ var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
623
+ var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
624
+ var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
625
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
626
+ var __spreadValues$6 = (a, b) => {
627
+ for (var prop in b || (b = {}))
628
+ if (__hasOwnProp$6.call(b, prop))
629
+ __defNormalProp$6(a, prop, b[prop]);
630
+ if (__getOwnPropSymbols$6)
631
+ for (var prop of __getOwnPropSymbols$6(b)) {
632
+ if (__propIsEnum$6.call(b, prop))
633
+ __defNormalProp$6(a, prop, b[prop]);
634
+ }
635
+ return a;
636
+ };
637
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
638
+ function expandTarget(target, options = {}) {
639
+ if (Array.isArray(target)) {
640
+ return expandTarget(target[0]);
641
+ }
642
+ if (typeof target === "string") {
643
+ const [id, fragment] = target.split("#");
644
+ if (!fragment) {
645
+ return {
646
+ type: "SpecificResource",
647
+ source: { id, type: options.typeMap && options.typeMap[id] || "Unknown" },
648
+ selector: null,
649
+ selectors: []
650
+ };
651
+ }
652
+ return expandTarget({
653
+ type: "SpecificResource",
654
+ source: { id, type: "Unknown" },
655
+ selector: {
656
+ type: "FragmentSelector",
657
+ value: fragment
658
+ }
659
+ });
660
+ }
661
+ if (target.type === "Choice" || target.type === "List" || target.type === "Composite" || target.type === "Independents") {
662
+ return expandTarget(target.items[0]);
663
+ }
664
+ if (target.type === "SpecificResource") {
665
+ if (target.source.type === "Canvas" && target.source.partOf && typeof target.source.partOf === "string") {
666
+ target.source.partOf = [
667
+ {
668
+ id: target.source.partOf,
669
+ type: "Manifest"
670
+ }
671
+ ];
672
+ }
673
+ const { selector, selectors } = target.selector ? parseSelector(target.selector) : { selector: null, selectors: [] };
674
+ return {
675
+ type: "SpecificResource",
676
+ source: target.source,
677
+ selector,
678
+ selectors
679
+ };
680
+ }
681
+ if (target.id) {
682
+ if (target.type === "Canvas" && target.partOf && typeof target.partOf === "string") {
683
+ target.partOf = [
684
+ {
685
+ id: target.partOf,
686
+ type: "Manifest"
687
+ }
688
+ ];
689
+ }
690
+ const [id, fragment] = target.id.split("#");
691
+ if (!fragment) {
692
+ return {
693
+ type: "SpecificResource",
694
+ source: __spreadProps$4(__spreadValues$6({}, target), {
695
+ id
696
+ }),
697
+ selector: null,
698
+ selectors: []
699
+ };
700
+ }
701
+ return expandTarget({
702
+ type: "SpecificResource",
703
+ source: __spreadProps$4(__spreadValues$6({}, target), {
704
+ id
705
+ }),
706
+ selector: {
707
+ type: "FragmentSelector",
708
+ value: fragment
709
+ }
710
+ });
711
+ }
712
+ return {
713
+ type: "SpecificResource",
714
+ source: target,
715
+ selector: null,
716
+ selectors: []
717
+ };
718
+ }
719
+
720
+ var __defProp$5 = Object.defineProperty;
721
+ var __defProps$3 = Object.defineProperties;
722
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
723
+ var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
724
+ var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
725
+ var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
726
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
727
+ var __spreadValues$5 = (a, b) => {
728
+ for (var prop in b || (b = {}))
729
+ if (__hasOwnProp$5.call(b, prop))
730
+ __defNormalProp$5(a, prop, b[prop]);
731
+ if (__getOwnPropSymbols$5)
732
+ for (var prop of __getOwnPropSymbols$5(b)) {
733
+ if (__propIsEnum$5.call(b, prop))
734
+ __defNormalProp$5(a, prop, b[prop]);
735
+ }
736
+ return a;
737
+ };
738
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
739
+ function useAnnotation(options = {}, deps = []) {
740
+ const { id, selector } = options;
741
+ const ctx = useResourceContext();
742
+ const vault = useVault();
743
+ const annotationId = id ? id : ctx.annotation;
744
+ const annotation = useVaultSelector((s) => annotationId ? s.iiif.entities.Annotation[annotationId] : void 0, [annotationId]);
745
+ const body = useVaultSelector((s) => annotation && annotation.body ? annotation.body.map((singleBody) => singleBody ? s.iiif.entities[singleBody.type][singleBody.id] : null).filter(Boolean) : [], [annotation]);
746
+ return useMemo(() => {
747
+ if (!annotation) {
748
+ return void 0;
749
+ }
750
+ const newAnnotation = __spreadProps$3(__spreadValues$5({}, annotation), {
751
+ body,
752
+ target: expandTarget(annotation.target, { typeMap: vault.getState().iiif.mapping })
753
+ });
754
+ if (selector) {
755
+ return selector(newAnnotation);
756
+ }
757
+ return newAnnotation;
758
+ }, [annotation, selector, body, ...deps]);
759
+ }
760
+
761
+ function useCanvas(options = {}, deps = []) {
762
+ const { id, selector } = options;
763
+ const ctx = useResourceContext();
764
+ const canvasId = id ? id : ctx.canvas;
765
+ const canvas = useVaultSelector((s) => canvasId ? s.iiif.entities.Canvas[canvasId] : void 0, [canvasId]);
766
+ return useMemo(() => {
767
+ if (!canvas) {
768
+ return void 0;
769
+ }
770
+ if (selector) {
771
+ return selector(canvas);
772
+ }
773
+ return canvas;
774
+ }, [canvas, selector, ...deps]);
775
+ }
776
+
777
+ var __defProp$4 = Object.defineProperty;
778
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
779
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
780
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
781
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
782
+ var __spreadValues$4 = (a, b) => {
783
+ for (var prop in b || (b = {}))
784
+ if (__hasOwnProp$4.call(b, prop))
785
+ __defNormalProp$4(a, prop, b[prop]);
786
+ if (__getOwnPropSymbols$4)
787
+ for (var prop of __getOwnPropSymbols$4(b)) {
788
+ if (__propIsEnum$4.call(b, prop))
789
+ __defNormalProp$4(a, prop, b[prop]);
790
+ }
791
+ return a;
792
+ };
793
+ const RenderAnnotation = ({
794
+ id,
795
+ style: defaultStyle,
796
+ className,
797
+ interactive
798
+ }) => {
799
+ const annotation = useAnnotation({ id });
800
+ const style = useStyles(annotation, "atlas");
801
+ const html = useStyles(annotation, "html");
802
+ const events = useResourceEvents(annotation, ["atlas"]);
803
+ const canvas = useCanvas();
804
+ const allStyles = useMemo(() => {
805
+ return mergeStyles(defaultStyle, style);
806
+ }, [defaultStyle, style]);
807
+ const isValid = canvas && annotation && annotation.target && annotation.target.selector && annotation.target.selector.type === "BoxSelector" && annotation.target.source && annotation.target.source.id === canvas.id;
808
+ if (!isValid) {
809
+ return null;
810
+ }
811
+ return /* @__PURE__ */ React.createElement(RegionHighlight, __spreadValues$4({
812
+ id: annotation.id,
813
+ isEditing: true,
814
+ region: annotation.target.selector.spatial,
815
+ style: allStyles,
816
+ className: (html == null ? void 0 : html.className) || className,
817
+ interactive: !!((html == null ? void 0 : html.href) || interactive),
818
+ href: (html == null ? void 0 : html.href) || null,
819
+ title: (html == null ? void 0 : html.title) || null,
820
+ hrefTarget: (html == null ? void 0 : html.target) || null
821
+ }, events));
822
+ };
823
+
824
+ const RenderAnnotationPage = ({
825
+ className,
826
+ page
827
+ }) => {
828
+ var _a;
829
+ const style = useStyles(page, "atlas");
830
+ const html = useStyles(page, "html");
831
+ useVaultSelector((state) => page.id ? state.iiif.entities.AnnotationPage[page.id] : null, []);
832
+ return /* @__PURE__ */ React.createElement(Fragment, null, (_a = page.items) == null ? void 0 : _a.map((annotation) => {
833
+ return /* @__PURE__ */ React.createElement(RenderAnnotation, {
834
+ key: annotation.id,
835
+ id: annotation.id,
836
+ style,
837
+ className: (html == null ? void 0 : html.className) || className
838
+ });
839
+ }));
840
+ };
841
+
842
+ const TileSet = TileSet$1;
843
+ function RenderImage({
844
+ id,
845
+ image,
846
+ thumbnail,
847
+ isStatic,
848
+ x = 0,
849
+ y = 0,
850
+ annotations
851
+ }) {
852
+ var _a, _b, _c, _d;
853
+ return /* @__PURE__ */ React.createElement(Fragment, {
854
+ key: id
855
+ }, !image.service ? /* @__PURE__ */ React.createElement(Fragment, {
856
+ key: "no-service"
857
+ }, /* @__PURE__ */ React.createElement("world-image", {
858
+ uri: image.id,
859
+ target: image.target.spatial,
860
+ display: image.width && image.height ? {
861
+ width: image.width,
862
+ height: image.height
863
+ } : void 0
864
+ }), annotations) : /* @__PURE__ */ React.createElement(Fragment, {
865
+ key: "service"
866
+ }, /* @__PURE__ */ React.createElement(TileSet, {
867
+ viewport: isStatic,
868
+ tiles: {
869
+ id: image.service.id || image.service["@id"],
870
+ height: image.height,
871
+ width: image.width,
872
+ imageService: image.service,
873
+ thumbnail: thumbnail && thumbnail.type === "fixed" ? thumbnail : void 0
874
+ },
875
+ x: ((_a = image.target) == null ? void 0 : _a.spatial.x) + x,
876
+ y: ((_b = image.target) == null ? void 0 : _b.spatial.y) + y,
877
+ width: (_c = image.target) == null ? void 0 : _c.spatial.width,
878
+ height: (_d = image.target) == null ? void 0 : _d.spatial.height
879
+ }), annotations));
880
+ }
881
+
882
+ function parseSpecificResource(resource) {
883
+ if (resource.type === "SpecificResource") {
884
+ return [resource.source, { selector: resource.selector }];
885
+ }
886
+ return [resource, { selector: null }];
887
+ }
888
+ function getPaintables(vault, paintingAnnotations, enabledChoices) {
889
+ const types = [];
890
+ let choice = null;
891
+ const items = [];
892
+ for (const annotation of paintingAnnotations) {
893
+ const bodies = vault.get(annotation.body);
894
+ for (const unknownBody of bodies) {
895
+ const [body, { selector }] = parseSpecificResource(unknownBody);
896
+ const type = (body.type || "unknown").toLowerCase();
897
+ if (type === "choice") {
898
+ const nestedBodies = vault.get(body.items);
899
+ const selected = enabledChoices.length ? enabledChoices.map((cid) => nestedBodies.find((b) => b.id === cid)).filter(Boolean) : [nestedBodies[0]];
900
+ if (selected.length === 0) {
901
+ selected.push(nestedBodies[0]);
902
+ }
903
+ choice = {
904
+ type: "single-choice",
905
+ items: nestedBodies.map((b) => ({
906
+ id: b.id,
907
+ label: b.label,
908
+ selected: selected.indexOf(b) !== -1
909
+ })),
910
+ label: unknownBody.label
911
+ };
912
+ bodies.push(...selected);
913
+ continue;
914
+ }
915
+ if (types.indexOf(type) === -1) {
916
+ types.push(type);
917
+ }
918
+ items.push({
919
+ type,
920
+ resource: body,
921
+ target: annotation.target,
922
+ selector
923
+ });
924
+ }
925
+ }
926
+ return {
927
+ types,
928
+ items,
929
+ choice
930
+ };
931
+ }
932
+ const emptyActions = {
933
+ makeChoice: () => {
934
+ }
935
+ };
936
+ const unknownResponse = { type: "unknown" };
937
+ const unsupportedStrategy = (reason) => {
938
+ return { type: "unknown", reason, annotations: { pages: [] } };
939
+ };
940
+
941
+ function useManifest(options = {}, deps = []) {
942
+ const { id, selector } = options;
943
+ const ctx = useResourceContext();
944
+ useVault();
945
+ const manifestId = id ? id : ctx.manifest;
946
+ const manifest = useVaultSelector((s) => manifestId ? s.iiif.entities.Manifest[manifestId] : void 0, [manifestId]);
947
+ return useMemo(() => {
948
+ if (!manifest) {
949
+ return void 0;
950
+ }
951
+ if (selector) {
952
+ return selector(manifest);
953
+ }
954
+ return manifest;
955
+ }, [manifest, selector, ...deps]);
956
+ }
957
+
958
+ function getMeta$1(state, resourceId) {
959
+ var _a;
960
+ const resourceMeta = (_a = state == null ? void 0 : state.iiif) == null ? void 0 : _a.meta[resourceId];
961
+ if (!resourceMeta) {
962
+ return null;
963
+ }
964
+ return resourceMeta.annotationPageManager;
965
+ }
966
+ function useEnabledAnnotationPageIds(resourceId, availablePageIds) {
967
+ return useVaultSelector((state) => {
968
+ const pageIds = [];
969
+ if (!resourceId) {
970
+ return pageIds;
971
+ }
972
+ const allAnnotationListIds = Object.keys(state.iiif.entities.AnnotationPage);
973
+ for (const annotationListId of allAnnotationListIds) {
974
+ if (!availablePageIds || availablePageIds.indexOf(annotationListId) !== -1) {
975
+ const annotationListMeta = getMeta$1(state, annotationListId);
976
+ if (annotationListMeta && annotationListMeta.views && annotationListMeta.views[resourceId]) {
977
+ pageIds.push(annotationListId);
978
+ }
979
+ }
980
+ }
981
+ return pageIds;
982
+ }, [resourceId, availablePageIds]);
983
+ }
984
+
985
+ function flattenAnnotationPageIds({
986
+ canvas,
987
+ manifest,
988
+ all,
989
+ canvases
990
+ }) {
991
+ const foundIds = [];
992
+ if (manifest) {
993
+ for (const page of manifest.annotations) {
994
+ if (foundIds.indexOf(page.id) === -1) {
995
+ foundIds.push(page.id);
996
+ }
997
+ }
998
+ }
999
+ if (all) {
1000
+ if (canvases && canvases.length) {
1001
+ for (const canvas_ of canvases) {
1002
+ for (const page of canvas_.annotations) {
1003
+ if (foundIds.indexOf(page.id) === -1) {
1004
+ foundIds.push(page.id);
1005
+ }
1006
+ }
1007
+ }
1008
+ }
1009
+ } else if (canvas) {
1010
+ for (const page of canvas.annotations) {
1011
+ if (foundIds.indexOf(page.id) === -1) {
1012
+ foundIds.push(page.id);
1013
+ }
1014
+ }
1015
+ }
1016
+ return foundIds;
1017
+ }
1018
+
1019
+ var __defProp$3 = Object.defineProperty;
1020
+ var __defProps$2 = Object.defineProperties;
1021
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
1022
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
1023
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
1024
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
1025
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1026
+ var __spreadValues$3 = (a, b) => {
1027
+ for (var prop in b || (b = {}))
1028
+ if (__hasOwnProp$3.call(b, prop))
1029
+ __defNormalProp$3(a, prop, b[prop]);
1030
+ if (__getOwnPropSymbols$3)
1031
+ for (var prop of __getOwnPropSymbols$3(b)) {
1032
+ if (__propIsEnum$3.call(b, prop))
1033
+ __defNormalProp$3(a, prop, b[prop]);
1034
+ }
1035
+ return a;
1036
+ };
1037
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
1038
+ function getMeta(state, resourceId) {
1039
+ var _a;
1040
+ const resourceMeta = (_a = state == null ? void 0 : state.iiif) == null ? void 0 : _a.meta[resourceId];
1041
+ if (!resourceMeta) {
1042
+ return null;
1043
+ }
1044
+ return resourceMeta.annotationPageManager;
1045
+ }
1046
+ function useAnnotationPageManager(resourceId, options = {}) {
1047
+ const vault = useVault();
1048
+ const manifest = useManifest();
1049
+ const canvas = useCanvas();
1050
+ const canvases = useVisibleCanvases();
1051
+ const availablePageIds = useMemo(() => {
1052
+ return flattenAnnotationPageIds({
1053
+ all: options.all,
1054
+ manifest,
1055
+ canvas,
1056
+ canvases
1057
+ });
1058
+ }, [options.all, canvas, canvases, manifest]);
1059
+ const enabledPageIds = useEnabledAnnotationPageIds(resourceId, options.all ? void 0 : availablePageIds);
1060
+ const setPageDisabled = useCallback((deselectId) => {
1061
+ if (!resourceId) {
1062
+ return;
1063
+ }
1064
+ vault.setMetaValue([deselectId, "annotationPageManager", "views"], (existingResources) => {
1065
+ if (existingResources && !existingResources[resourceId]) {
1066
+ return existingResources;
1067
+ }
1068
+ return __spreadProps$2(__spreadValues$3({}, existingResources || {}), {
1069
+ [resourceId]: false
1070
+ });
1071
+ });
1072
+ }, [resourceId, vault]);
1073
+ const setPageEnabled = useCallback((id, opt = {}) => {
1074
+ if (!resourceId) {
1075
+ return;
1076
+ }
1077
+ const state = vault.getState();
1078
+ const toDeselect = [];
1079
+ if (opt == null ? void 0 : opt.deselectOthers) {
1080
+ const allAnnotationListIds = Object.keys(state.iiif.entities.AnnotationPage);
1081
+ for (const annotationPageId of allAnnotationListIds) {
1082
+ const annotationListMeta = getMeta(state, annotationPageId);
1083
+ if (annotationListMeta && annotationListMeta.views && annotationListMeta.views[resourceId]) {
1084
+ toDeselect.push(annotationPageId);
1085
+ }
1086
+ }
1087
+ }
1088
+ for (const deselectId of toDeselect) {
1089
+ setPageDisabled(deselectId);
1090
+ }
1091
+ vault.setMetaValue([id, "annotationPageManager", "views"], (existingResources) => {
1092
+ if (existingResources && existingResources[resourceId]) {
1093
+ return existingResources;
1094
+ }
1095
+ return __spreadProps$2(__spreadValues$3({}, existingResources || {}), {
1096
+ [resourceId]: true
1097
+ });
1098
+ });
1099
+ }, [resourceId, setPageDisabled, vault]);
1100
+ return {
1101
+ availablePageIds,
1102
+ enabledPageIds,
1103
+ setPageEnabled,
1104
+ setPageDisabled
1105
+ };
1106
+ }
1107
+
1108
+ function useResources(ids, type) {
1109
+ return useVaultSelector((state, vault) => vault.get(ids.map((id) => ({ id, type }))), [ids, type]);
1110
+ }
1111
+
1112
+ const ImageServiceLoaderContext = React.createContext(new ImageServiceLoader());
1113
+ function useImageServiceLoader() {
1114
+ return useContext(ImageServiceLoaderContext);
1115
+ }
1116
+
1117
+ var __defProp$2 = Object.defineProperty;
1118
+ var __defProps$1 = Object.defineProperties;
1119
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
1120
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
1121
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
1122
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
1123
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1124
+ var __spreadValues$2 = (a, b) => {
1125
+ for (var prop in b || (b = {}))
1126
+ if (__hasOwnProp$2.call(b, prop))
1127
+ __defNormalProp$2(a, prop, b[prop]);
1128
+ if (__getOwnPropSymbols$2)
1129
+ for (var prop of __getOwnPropSymbols$2(b)) {
1130
+ if (__propIsEnum$2.call(b, prop))
1131
+ __defNormalProp$2(a, prop, b[prop]);
1132
+ }
1133
+ return a;
1134
+ };
1135
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
1136
+ function useLoadImageService() {
1137
+ const loader = useImageServiceLoader();
1138
+ const [imageServiceStatus, setImageServiceStatus] = useState({});
1139
+ const didUnmount = useRef(false);
1140
+ useEffect(() => {
1141
+ return () => {
1142
+ didUnmount.current = true;
1143
+ };
1144
+ }, []);
1145
+ const loadImageService = useCallback((imageService, { height, width }) => {
1146
+ if (imageService) {
1147
+ const imageServiceId = imageService.id || imageService["@id"];
1148
+ const syncLoaded = loader.loadServiceSync({
1149
+ id: imageServiceId,
1150
+ width: imageService.width || width,
1151
+ height: imageService.height || height
1152
+ });
1153
+ if (syncLoaded) {
1154
+ imageService = syncLoaded;
1155
+ } else if (!imageServiceStatus[imageServiceId]) {
1156
+ if (!didUnmount.current) {
1157
+ setImageServiceStatus((r) => {
1158
+ return __spreadProps$1(__spreadValues$2({}, r), {
1159
+ [imageServiceId]: "loading"
1160
+ });
1161
+ });
1162
+ }
1163
+ loader.loadService({
1164
+ id: imageServiceId,
1165
+ width: imageService.width || width,
1166
+ height: imageService.height || height
1167
+ }).then(() => {
1168
+ if (!didUnmount.current) {
1169
+ setImageServiceStatus((r) => {
1170
+ return __spreadProps$1(__spreadValues$2({}, r), {
1171
+ [imageServiceId]: "done"
1172
+ });
1173
+ });
1174
+ }
1175
+ });
1176
+ }
1177
+ }
1178
+ return imageService;
1179
+ }, [loader, imageServiceStatus]);
1180
+ return [loadImageService, imageServiceStatus];
1181
+ }
1182
+
1183
+ function usePaintingAnnotations(options = {}) {
1184
+ const canvas = useCanvas(options.canvasId ? { id: options.canvasId } : void 0);
1185
+ return useVaultSelector((state, vault) => {
1186
+ if (!canvas) {
1187
+ return [];
1188
+ }
1189
+ const annotationPages = vault.get(canvas.items);
1190
+ const flatAnnotations = [];
1191
+ for (const page of annotationPages) {
1192
+ flatAnnotations.push(...vault.get(page.items));
1193
+ }
1194
+ return flatAnnotations;
1195
+ }, [canvas]);
1196
+ }
1197
+
1198
+ function usePaintables(options, deps = []) {
1199
+ const vault = useVault();
1200
+ const paintingAnnotations = usePaintingAnnotations();
1201
+ const [enabledChoices, setEnabledChoices] = useState((options == null ? void 0 : options.defaultChoices) || []);
1202
+ const paintables = useMemo(() => getPaintables(vault, paintingAnnotations, enabledChoices), [vault, paintingAnnotations, enabledChoices, ...deps]);
1203
+ const makeChoice = useCallback((id, { deselectOthers = true, deselect = false } = {}) => {
1204
+ if (paintables.choice) {
1205
+ if (paintables.choice.type !== "single-choice") {
1206
+ throw new Error("Complex choice not supported yet");
1207
+ }
1208
+ setEnabledChoices((prevChoices) => {
1209
+ if (deselect) {
1210
+ const without = prevChoices.filter((e) => e !== id);
1211
+ if (without.length === 0) {
1212
+ const defaultId = paintables.items[0].resource.id;
1213
+ if (defaultId) {
1214
+ return [defaultId];
1215
+ } else {
1216
+ return [];
1217
+ }
1218
+ }
1219
+ return without;
1220
+ }
1221
+ if (deselectOthers) {
1222
+ return [id];
1223
+ }
1224
+ const newChoices = [...prevChoices];
1225
+ if (newChoices.length === 0 && paintables.items.length) {
1226
+ const defaultId = paintables.items[0].resource.id;
1227
+ if (defaultId) {
1228
+ newChoices.push(defaultId);
1229
+ }
1230
+ }
1231
+ if (prevChoices.indexOf(id) !== -1) {
1232
+ return prevChoices;
1233
+ }
1234
+ return [...prevChoices, id];
1235
+ });
1236
+ }
1237
+ }, [paintables.choice]);
1238
+ const actions = { makeChoice };
1239
+ return [paintables, actions];
1240
+ }
1241
+
1242
+ function getImageStrategy(canvas, paintables, loadImageService) {
1243
+ const imageTypes = [];
1244
+ for (const singleImage of paintables.items) {
1245
+ const resource = singleImage.resource && singleImage.resource.type === "SpecificResource" ? singleImage.resource.source : singleImage.resource;
1246
+ if (!resource.id) {
1247
+ return unsupportedStrategy("No resource Identifier");
1248
+ }
1249
+ let imageService = void 0;
1250
+ if (resource.service) {
1251
+ const imageServices = getImageServices(resource);
1252
+ if (imageServices[0]) {
1253
+ imageService = loadImageService(imageServices[0], canvas);
1254
+ }
1255
+ }
1256
+ const { selector: imageTarget, source } = expandTarget(singleImage.target);
1257
+ if (source.id !== canvas.id) {
1258
+ continue;
1259
+ }
1260
+ const defaultTarget = {
1261
+ type: "BoxSelector",
1262
+ spatial: {
1263
+ x: 0,
1264
+ y: 0,
1265
+ width: canvas.width,
1266
+ height: canvas.height
1267
+ }
1268
+ };
1269
+ const target = imageTarget ? imageTarget.type === "TemporalSelector" ? {
1270
+ type: "TemporalBoxSelector",
1271
+ temporal: imageTarget.temporal,
1272
+ spatial: defaultTarget.spatial
1273
+ } : imageTarget : null;
1274
+ const defaultImageSelector = {
1275
+ type: "BoxSelector",
1276
+ spatial: {
1277
+ x: 0,
1278
+ y: 0,
1279
+ width: canvas.width,
1280
+ height: canvas.height
1281
+ }
1282
+ };
1283
+ const imageSelector = singleImage.resource.type === "SpecificResource" ? expandTarget(singleImage.resource) : null;
1284
+ const selector = imageSelector && imageSelector.selector && (imageSelector.selector.type === "BoxSelector" || imageSelector.selector.type === "TemporalBoxSelector") ? {
1285
+ type: "BoxSelector",
1286
+ spatial: {
1287
+ x: imageSelector.selector.spatial.x,
1288
+ y: imageSelector.selector.spatial.y,
1289
+ width: imageSelector.selector.spatial.width,
1290
+ height: imageSelector.selector.spatial.height
1291
+ }
1292
+ } : defaultImageSelector;
1293
+ if (imageService && !imageService.id) {
1294
+ imageService.id = imageService["@id"];
1295
+ }
1296
+ const imageType = {
1297
+ id: resource.id,
1298
+ type: "Image",
1299
+ width: target ? resource.width : canvas.width,
1300
+ height: target ? resource.height : canvas.height,
1301
+ service: imageService,
1302
+ sizes: imageService && imageService.sizes ? imageService.sizes : resource.width && resource.height ? [{ width: resource.width, height: resource.height }] : [],
1303
+ target: target && target.type !== "PointSelector" ? target : defaultTarget,
1304
+ selector
1305
+ };
1306
+ imageTypes.push(imageType);
1307
+ }
1308
+ return {
1309
+ type: "images",
1310
+ image: imageTypes[0],
1311
+ images: imageTypes,
1312
+ choice: paintables.choice
1313
+ };
1314
+ }
1315
+
1316
+ const supportedFormats = ["model/gltf-binary"];
1317
+ function get3dStrategy(canvas, paintables) {
1318
+ const first = paintables.items[0];
1319
+ if (!first.format) {
1320
+ return unsupportedStrategy("Unknown format");
1321
+ }
1322
+ if (supportedFormats.indexOf(first.format) === -1) {
1323
+ return unsupportedStrategy(`3D format: ${first.format} is unsupported`);
1324
+ }
1325
+ return {
1326
+ type: "3d-model",
1327
+ model: first
1328
+ };
1329
+ }
1330
+
1331
+ var __defProp$1 = Object.defineProperty;
1332
+ var __defProps = Object.defineProperties;
1333
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1334
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
1335
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
1336
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
1337
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1338
+ var __spreadValues$1 = (a, b) => {
1339
+ for (var prop in b || (b = {}))
1340
+ if (__hasOwnProp$1.call(b, prop))
1341
+ __defNormalProp$1(a, prop, b[prop]);
1342
+ if (__getOwnPropSymbols$1)
1343
+ for (var prop of __getOwnPropSymbols$1(b)) {
1344
+ if (__propIsEnum$1.call(b, prop))
1345
+ __defNormalProp$1(a, prop, b[prop]);
1346
+ }
1347
+ return a;
1348
+ };
1349
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1350
+ function useRenderingStrategy(options) {
1351
+ const manifest = useManifest();
1352
+ const canvas = useCanvas();
1353
+ const vault = useVault();
1354
+ const [loadImageService, imageServiceStatus] = useLoadImageService();
1355
+ const { enabledPageIds } = useAnnotationPageManager((options == null ? void 0 : options.annotationPageManagerId) || (manifest == null ? void 0 : manifest.id) || (canvas == null ? void 0 : canvas.id), {
1356
+ all: false
1357
+ });
1358
+ const enabledPages = useResources(enabledPageIds, "AnnotationPage");
1359
+ const supports = (options == null ? void 0 : options.strategies) || ["images", "media", "complex-timeline"];
1360
+ const [paintables, actions] = usePaintables(options, [imageServiceStatus]);
1361
+ const strategy = useMemo(() => {
1362
+ if (!canvas || paintables.types.length === 0) {
1363
+ return unknownResponse;
1364
+ }
1365
+ if (paintables.types.length !== 1) {
1366
+ if (supports.indexOf("complex-timeline") === -1) {
1367
+ return unsupportedStrategy("Complex timeline not supported");
1368
+ }
1369
+ return unsupportedStrategy("ComplexTimelineStrategy not yet supported");
1370
+ }
1371
+ const mainType = paintables.types[0];
1372
+ if (mainType === "image") {
1373
+ if (supports.indexOf("images") === -1) {
1374
+ return unsupportedStrategy("Image not supported");
1375
+ }
1376
+ return getImageStrategy(canvas, paintables, loadImageService);
1377
+ }
1378
+ if (mainType === "Model") {
1379
+ if (supports.indexOf("3d-model") === -1) {
1380
+ return unsupportedStrategy("3D not supported");
1381
+ }
1382
+ return get3dStrategy(canvas, paintables);
1383
+ }
1384
+ if (mainType === "audio") {
1385
+ if (supports.indexOf("media") === -1) {
1386
+ return unsupportedStrategy("Media not supported");
1387
+ }
1388
+ return unsupportedStrategy("Audio strategy not yet supported");
1389
+ }
1390
+ if (mainType === "video") {
1391
+ if (supports.indexOf("media") === -1) {
1392
+ return unsupportedStrategy("Media not supported");
1393
+ }
1394
+ return unsupportedStrategy("Video strategy not yet supported");
1395
+ }
1396
+ return unknownResponse;
1397
+ }, [canvas, paintables, vault, actions.makeChoice]);
1398
+ return useMemo(() => {
1399
+ if (strategy.type === "unknown") {
1400
+ return [strategy, emptyActions];
1401
+ }
1402
+ return [
1403
+ __spreadProps(__spreadValues$1({}, strategy), {
1404
+ annotations: { pages: enabledPages }
1405
+ }),
1406
+ actions
1407
+ ];
1408
+ }, [strategy, enabledPages]);
1409
+ }
1410
+
1411
+ const useVaultEffect = (callback, deps = []) => {
1412
+ const vault = useVault();
1413
+ useEffect(() => {
1414
+ callback(vault);
1415
+ }, [vault, ...deps]);
1416
+ };
1417
+
1418
+ function useThumbnail(request, dereference, { canvasId, manifestId } = {}) {
1419
+ const vault = useVault();
1420
+ const loader = useImageServiceLoader();
1421
+ const helper = useMemo(() => createThumbnailHelper(vault, { imageServiceLoader: loader }), [vault, loader]);
1422
+ const [thumbnail, setThumbnail] = useState();
1423
+ const manifest = useManifest(manifestId ? { id: manifestId } : void 0);
1424
+ const canvas = useCanvas(canvasId ? { id: canvasId } : void 0);
1425
+ const subject = canvas ? canvas : manifest;
1426
+ const didUnmount = useRef(false);
1427
+ useEffect(() => {
1428
+ return () => {
1429
+ didUnmount.current = true;
1430
+ };
1431
+ }, []);
1432
+ if (!subject) {
1433
+ throw new Error("Must be called under a manifest or canvas context.");
1434
+ }
1435
+ useVaultEffect((v) => {
1436
+ helper.getBestThumbnailAtSize(subject, request, dereference).then((thumb) => {
1437
+ if (thumb.best && !didUnmount.current) {
1438
+ setThumbnail(thumb.best);
1439
+ }
1440
+ });
1441
+ }, [subject]);
1442
+ return thumbnail;
1443
+ }
1444
+
1445
+ var __defProp = Object.defineProperty;
1446
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1447
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1448
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
1449
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1450
+ var __spreadValues = (a, b) => {
1451
+ for (var prop in b || (b = {}))
1452
+ if (__hasOwnProp.call(b, prop))
1453
+ __defNormalProp(a, prop, b[prop]);
1454
+ if (__getOwnPropSymbols)
1455
+ for (var prop of __getOwnPropSymbols(b)) {
1456
+ if (__propIsEnum.call(b, prop))
1457
+ __defNormalProp(a, prop, b[prop]);
1458
+ }
1459
+ return a;
1460
+ };
1461
+ function RenderCanvas({ x, y, onChoiceChange, registerActions, defaultChoices, isStatic }) {
1462
+ const canvas = useCanvas();
1463
+ const elementProps = useResourceEvents(canvas, ["deep-zoom"]);
1464
+ const [virtualPage] = useVirtualAnnotationPageContext();
1465
+ const vault = useVault();
1466
+ const helper = useMemo(() => createStylesHelper(vault), [vault]);
1467
+ const [strategy, actions] = useRenderingStrategy({
1468
+ strategies: ["images"],
1469
+ defaultChoices: defaultChoices == null ? void 0 : defaultChoices.map(({ id }) => id)
1470
+ });
1471
+ const choice = strategy.type === "images" ? strategy.choice : void 0;
1472
+ useEffect(() => {
1473
+ if (registerActions) {
1474
+ registerActions(actions);
1475
+ }
1476
+ }, [strategy.annotations]);
1477
+ useEffect(() => {
1478
+ if (defaultChoices) {
1479
+ for (const choice2 of defaultChoices) {
1480
+ if (typeof choice2.opacity !== "undefined") {
1481
+ helper.applyStyles({ id: choice2.id }, "atlas", {
1482
+ opacity: choice2.opacity
1483
+ });
1484
+ }
1485
+ }
1486
+ }
1487
+ }, [defaultChoices]);
1488
+ useLayoutEffect(() => {
1489
+ if (onChoiceChange) {
1490
+ onChoiceChange(choice);
1491
+ }
1492
+ }, [choice]);
1493
+ const thumbnail = useThumbnail({ maxWidth: 256, maxHeight: 256 });
1494
+ if (!canvas) {
1495
+ return null;
1496
+ }
1497
+ if (strategy.type === "unknown") {
1498
+ if (thumbnail && thumbnail.type === "fixed") {
1499
+ return /* @__PURE__ */ React.createElement("world-object", {
1500
+ height: canvas.height,
1501
+ width: canvas.width,
1502
+ x,
1503
+ y
1504
+ }, /* @__PURE__ */ React.createElement("world-image", {
1505
+ uri: thumbnail.id,
1506
+ target: { x: 0, y: 0, width: canvas.width, height: canvas.height },
1507
+ display: thumbnail.width && thumbnail.height ? {
1508
+ width: thumbnail.width,
1509
+ height: thumbnail.height
1510
+ } : void 0
1511
+ }));
1512
+ }
1513
+ throw new Error("Unknown image strategy");
1514
+ }
1515
+ const annotations = /* @__PURE__ */ React.createElement(Fragment, null, virtualPage ? /* @__PURE__ */ React.createElement(RenderAnnotationPage, {
1516
+ page: virtualPage
1517
+ }) : null, strategy.annotations && strategy.annotations.pages ? strategy.annotations.pages.map((page) => {
1518
+ return /* @__PURE__ */ React.createElement(RenderAnnotationPage, {
1519
+ key: page.id,
1520
+ page
1521
+ });
1522
+ }) : null);
1523
+ return /* @__PURE__ */ React.createElement("world-object", __spreadValues({
1524
+ key: strategy.type,
1525
+ height: canvas.height,
1526
+ width: canvas.width,
1527
+ x,
1528
+ y
1529
+ }, elementProps), strategy.type === "images" ? strategy.images.map((image, idx) => {
1530
+ return /* @__PURE__ */ React.createElement(RenderImage, {
1531
+ isStatic,
1532
+ key: image.id,
1533
+ image,
1534
+ id: image.id,
1535
+ thumbnail: idx === 0 ? thumbnail : void 0,
1536
+ annotations
1537
+ });
1538
+ }) : null);
1539
+ }
1540
+
1541
+ const CanvasPanel = {
1542
+ RenderImage,
1543
+ RenderCanvas,
1544
+ RenderAnnotationPage,
1545
+ RenderAnnotation,
1546
+ Viewer
1547
+ };
1548
+
1549
+ const AnnotationContext = ({ annotation, children }) => {
1550
+ return /* @__PURE__ */ React.createElement(ResourceProvider, {
1551
+ value: { annotation }
1552
+ }, children);
1553
+ };
1554
+
1555
+ const CollectionContext = ({ collection, children }) => {
1556
+ return /* @__PURE__ */ React.createElement(ResourceProvider, {
1557
+ value: { collection }
1558
+ }, children);
1559
+ };
1560
+
1561
+ const RangeContext = ({ range, children }) => {
1562
+ return /* @__PURE__ */ React.createElement(ResourceProvider, {
1563
+ value: { range }
1564
+ }, children);
1565
+ };
1566
+
1567
+ function useAnnotationsAtTime(time, options = {}) {
1568
+ const allAnnotations = usePaintingAnnotations(options);
1569
+ return allAnnotations;
1570
+ }
1571
+
1572
+ function useCanvasClock(canvasId, autoplay = false) {
1573
+ }
1574
+
1575
+ function useCollection(options, deps = []) {
1576
+ const { id, selector } = options;
1577
+ const ctx = useResourceContext();
1578
+ const collectionId = id ? id : ctx.collection;
1579
+ const collection = useVaultSelector((s) => collectionId ? s.iiif.entities.Collection[collectionId] : void 0, [collectionId]);
1580
+ return useMemo(() => {
1581
+ if (!collection) {
1582
+ return void 0;
1583
+ }
1584
+ if (selector) {
1585
+ return selector(collection);
1586
+ }
1587
+ return collection;
1588
+ }, [collection, selector, ...deps]);
1589
+ }
1590
+
1591
+ function useEventListener(resource, name, listener, scope, deps = []) {
1592
+ const vault = useVault();
1593
+ const helper = useMemo(() => createEventsHelper(vault), [vault]);
1594
+ useEffect(() => {
1595
+ const currentResource = resource;
1596
+ if (!currentResource) {
1597
+ return () => {
1598
+ };
1599
+ }
1600
+ helper.addEventListener(currentResource, name, listener, scope);
1601
+ return () => {
1602
+ helper.removeEventListener(currentResource, name, listener);
1603
+ };
1604
+ }, [helper, resource, name, ...deps]);
1605
+ }
1606
+
1607
+ function useExistingVault() {
1608
+ const oldContext = useContext(ReactVaultContext);
1609
+ return oldContext && oldContext.vault ? oldContext.vault : globalVault();
1610
+ }
1611
+
1612
+ function useExternalCollection(idOrRef, options) {
1613
+ const { id, isLoaded, error, resource, requestId, cached } = useExternalResource(idOrRef, options);
1614
+ return { id, isLoaded, error, manifest: resource, requestId, cached };
1615
+ }
1616
+
1617
+ var __async = (__this, __arguments, generator) => {
1618
+ return new Promise((resolve, reject) => {
1619
+ var fulfilled = (value) => {
1620
+ try {
1621
+ step(generator.next(value));
1622
+ } catch (e) {
1623
+ reject(e);
1624
+ }
1625
+ };
1626
+ var rejected = (value) => {
1627
+ try {
1628
+ step(generator.throw(value));
1629
+ } catch (e) {
1630
+ reject(e);
1631
+ }
1632
+ };
1633
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1634
+ step((generator = generator.apply(__this, __arguments)).next());
1635
+ });
1636
+ };
1637
+ function useImageService({ cacheKey } = {}) {
1638
+ const canvas = useCanvas();
1639
+ const annotations = usePaintingAnnotations();
1640
+ const vault = useVault();
1641
+ const imageService = useImageServiceLoader();
1642
+ const [_data, setData] = useState(void 0);
1643
+ const [isFetching, setIsFetching] = useState(false);
1644
+ const [status, setStatus] = useState("idle");
1645
+ const [error, setError] = useState(void 0);
1646
+ const key = canvas ? canvas.id : "undefined";
1647
+ const initialData = useMemo(() => {
1648
+ try {
1649
+ if (canvas && annotations.length) {
1650
+ const annotation = annotations[0];
1651
+ const resource = vault.get(annotation.body[0]);
1652
+ const imageServices = getImageServices(resource);
1653
+ const firstImageService = imageServices[0];
1654
+ if (!firstImageService) {
1655
+ return void 0;
1656
+ }
1657
+ return imageService.loadServiceSync({
1658
+ id: firstImageService.id || firstImageService["@id"],
1659
+ width: firstImageService.width || canvas.width,
1660
+ height: firstImageService.height || canvas.height
1661
+ }) || void 0;
1662
+ }
1663
+ } catch (e) {
1664
+ console.error(e);
1665
+ }
1666
+ return void 0;
1667
+ }, [key, cacheKey, canvas]);
1668
+ const data = status === "success" && _data ? _data : initialData;
1669
+ useEffect(() => {
1670
+ (() => __async(this, null, function* () {
1671
+ try {
1672
+ if (canvas && annotations.length) {
1673
+ const annotation = annotations[0];
1674
+ const resource = vault.get(annotation.body[0]);
1675
+ const imageServices = getImageServices(resource);
1676
+ const firstImageService = imageServices[0];
1677
+ if (!firstImageService) {
1678
+ return;
1679
+ }
1680
+ setIsFetching(true);
1681
+ setStatus("loading");
1682
+ try {
1683
+ const loadedService = (yield imageService.loadService({
1684
+ id: firstImageService.id || firstImageService["@id"],
1685
+ width: firstImageService.width || canvas.width,
1686
+ height: firstImageService.height || canvas.height
1687
+ })) || void 0;
1688
+ setData(loadedService);
1689
+ setStatus("success");
1690
+ setIsFetching(false);
1691
+ } catch (err) {
1692
+ setStatus("error");
1693
+ setError(err);
1694
+ }
1695
+ }
1696
+ } catch (err) {
1697
+ setStatus("error");
1698
+ setError(err);
1699
+ }
1700
+ }))();
1701
+ }, [key, cacheKey]);
1702
+ return useMemo(() => {
1703
+ return {
1704
+ data,
1705
+ isFetching,
1706
+ status,
1707
+ error
1708
+ };
1709
+ }, [data, isFetching, status, error]);
1710
+ }
1711
+
1712
+ function useImageTile() {
1713
+ const imageService = useImageService();
1714
+ return {
1715
+ isLoading: imageService.isFetching,
1716
+ tile: imageService.data ? {
1717
+ id: imageService.data.id || imageService.data["@id"],
1718
+ width: imageService.data.width,
1719
+ height: imageService.data.height,
1720
+ imageService: imageService.data,
1721
+ thumbnail: void 0
1722
+ } : null
1723
+ };
1724
+ }
1725
+
1726
+ function useRange(options = {}, deps = []) {
1727
+ const { id, selector } = options;
1728
+ const ctx = useResourceContext();
1729
+ const rangeId = id ? id : ctx.range;
1730
+ const range = useVaultSelector((s) => rangeId ? s.iiif.entities.Range[rangeId] : void 0, [rangeId]);
1731
+ return useMemo(() => {
1732
+ if (!range) {
1733
+ return void 0;
1734
+ }
1735
+ if (selector) {
1736
+ return selector(range);
1737
+ }
1738
+ return range;
1739
+ }, [range, selector, ...deps]);
1740
+ }
1741
+
1742
+ function useSearchService() {
1743
+ const manifest = useManifest();
1744
+ return manifest ? manifest.service.find((service) => service.profile === "SearchService1" || service.profile === "http://iiif.io/api/search/1/search") : void 0;
1745
+ }
1746
+
1747
+ function useStyleHelper() {
1748
+ const vault = useVault();
1749
+ return useMemo(() => createStylesHelper(vault), [vault]);
1750
+ }
1751
+
1752
+ export { AnnotationContext, CanvasContext, CanvasPanel, CollectionContext, ContextBridge, ImageServiceLoaderContext, ManifestContext, RangeContext, ReactVaultContext, ResourceProvider, ResourceReactContext, SimpleViewerProvider, SimpleViewerReactContext, VaultProvider, VirtualAnnotationProvider, VisibleCanvasReactContext, emptyActions, expandTarget, flattenAnnotationPageIds, getImageStrategy, getPaintables, parseSelector, parseSpecificResource, unknownResponse, unsupportedStrategy, useAnnotation, useAnnotationPageManager, useAnnotationsAtTime, useCanvas, useCanvasClock, useCollection, useContextBridge, useDispatch, useEventListener, useExistingVault, useExternalCollection, useExternalManifest, useExternalResource, useImageService, useImageServiceLoader, useImageTile, useLoadImageService, useManifest, usePaintables, usePaintingAnnotations, useRange, useRenderingStrategy, useResourceContext, useResourceEvents, useResources, useSearchService, useSimpleViewer, useStyleHelper, useStyles, useThumbnail, useVault, useVaultEffect, useVaultSelector, useVirtualAnnotationPage, useVirtualAnnotationPageContext, useVisibleCanvases };