react-iiif-vault 0.9.4 → 0.9.7

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