react-iiif-vault 0.9.15 → 0.9.16

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.
Files changed (34) hide show
  1. package/.build/types/canvas-panel/Viewer.d.ts +1 -1
  2. package/.build/types/canvas-panel/index.d.ts +2 -0
  3. package/.build/types/canvas-panel/render/Canvas.d.ts +8 -3
  4. package/.build/types/canvas-panel/render/CanvasBackground.d.ts +4 -0
  5. package/.build/types/canvas-panel/render/Image.d.ts +2 -2
  6. package/.build/types/context/ContextBridge.d.ts +1 -9
  7. package/.build/types/context/PortalContext.d.ts +3 -2
  8. package/.build/types/features/rendering-strategy/3d-strategy.d.ts +1 -1
  9. package/.build/types/features/rendering-strategy/rendering-utils.d.ts +5 -1
  10. package/.build/types/features/rendering-strategy/resource-types.d.ts +3 -0
  11. package/.build/types/features/rendering-strategy/strategies.d.ts +10 -1
  12. package/.build/types/features/rendering-strategy/textual-content-strategy.d.ts +17 -0
  13. package/.build/types/future-helpers/ranges.d.ts +6 -0
  14. package/.build/types/future-helpers/sequences.d.ts +6 -0
  15. package/.build/types/hooks/useCanvasSubset.d.ts +2 -0
  16. package/.build/types/index.d.ts +5 -0
  17. package/.build/types/viewers/SimpleViewerContext.d.ts +4 -16
  18. package/.build/types/viewers/SimpleViewerContext.hooks.d.ts +14 -0
  19. package/.build/types/viewers/SimpleViewerContext.types.d.ts +42 -0
  20. package/dist/bundle/cjs/index.js +5 -3
  21. package/dist/bundle/cjs/index.js.map +1 -1
  22. package/dist/bundle/esm/index.mjs +1020 -214
  23. package/dist/bundle/esm/index.mjs.map +1 -1
  24. package/dist/canvas-panel/cjs/canvas-panel.js +5 -3
  25. package/dist/canvas-panel/cjs/canvas-panel.js.map +1 -1
  26. package/dist/canvas-panel/esm/canvas-panel.mjs +729 -94
  27. package/dist/canvas-panel/esm/canvas-panel.mjs.map +1 -1
  28. package/dist/index.umd.js +22 -20
  29. package/dist/index.umd.js.map +1 -1
  30. package/dist/react17/cjs/index.js +30 -0
  31. package/dist/react17/cjs/index.js.map +1 -0
  32. package/dist/react17/esm/index.mjs +3186 -0
  33. package/dist/react17/esm/index.mjs.map +1 -0
  34. package/package.json +13 -8
@@ -0,0 +1,3186 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
30
+ return target;
31
+ };
32
+ import * as React from "react";
33
+ import React__default, { useContext, useMemo, useState, useEffect, useCallback, createContext, useRef, useLayoutEffect, Fragment, useReducer } from "react";
34
+ import { AtlasAuto, mergeStyles, RegionHighlight, TileSet, HTMLPortal } from "@atlas-viewer/atlas";
35
+ import { jsx, jsxs, Fragment as Fragment$1 } from "react/jsx-runtime";
36
+ import { globalVault, Vault } from "@iiif/vault";
37
+ import { createAction } from "typesafe-actions";
38
+ import require$$0 from "react-dom";
39
+ import { expandTarget as expandTarget$1 } from "@iiif/vault-helpers";
40
+ import { ImageServiceLoader, getImageServices, getFixedSizeFromImage } from "@atlas-viewer/iiif-image-api";
41
+ function _setPrototypeOf(o, p) {
42
+ _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) {
43
+ o2.__proto__ = p2;
44
+ return o2;
45
+ };
46
+ return _setPrototypeOf(o, p);
47
+ }
48
+ function _inheritsLoose(subClass, superClass) {
49
+ subClass.prototype = Object.create(superClass.prototype);
50
+ subClass.prototype.constructor = subClass;
51
+ _setPrototypeOf(subClass, superClass);
52
+ }
53
+ var changedArray = function changedArray2(a, b) {
54
+ if (a === void 0) {
55
+ a = [];
56
+ }
57
+ if (b === void 0) {
58
+ b = [];
59
+ }
60
+ return a.length !== b.length || a.some(function(item, index) {
61
+ return !Object.is(item, b[index]);
62
+ });
63
+ };
64
+ var initialState = {
65
+ error: null
66
+ };
67
+ var ErrorBoundary = /* @__PURE__ */ function(_React$Component) {
68
+ _inheritsLoose(ErrorBoundary2, _React$Component);
69
+ function ErrorBoundary2() {
70
+ var _this;
71
+ for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
72
+ _args[_key] = arguments[_key];
73
+ }
74
+ _this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;
75
+ _this.state = initialState;
76
+ _this.resetErrorBoundary = function() {
77
+ var _this$props;
78
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
79
+ args[_key2] = arguments[_key2];
80
+ }
81
+ _this.props.onReset == null ? void 0 : (_this$props = _this.props).onReset.apply(_this$props, args);
82
+ _this.reset();
83
+ };
84
+ return _this;
85
+ }
86
+ ErrorBoundary2.getDerivedStateFromError = function getDerivedStateFromError(error) {
87
+ return {
88
+ error
89
+ };
90
+ };
91
+ var _proto = ErrorBoundary2.prototype;
92
+ _proto.reset = function reset() {
93
+ this.setState(initialState);
94
+ };
95
+ _proto.componentDidCatch = function componentDidCatch(error, info) {
96
+ var _this$props$onError, _this$props2;
97
+ (_this$props$onError = (_this$props2 = this.props).onError) == null ? void 0 : _this$props$onError.call(_this$props2, error, info);
98
+ };
99
+ _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
100
+ var error = this.state.error;
101
+ var resetKeys = this.props.resetKeys;
102
+ if (error !== null && prevState.error !== null && changedArray(prevProps.resetKeys, resetKeys)) {
103
+ var _this$props$onResetKe, _this$props3;
104
+ (_this$props$onResetKe = (_this$props3 = this.props).onResetKeysChange) == null ? void 0 : _this$props$onResetKe.call(_this$props3, prevProps.resetKeys, resetKeys);
105
+ this.reset();
106
+ }
107
+ };
108
+ _proto.render = function render() {
109
+ var error = this.state.error;
110
+ var _this$props4 = this.props, fallbackRender = _this$props4.fallbackRender, FallbackComponent = _this$props4.FallbackComponent, fallback = _this$props4.fallback;
111
+ if (error !== null) {
112
+ var _props = {
113
+ error,
114
+ resetErrorBoundary: this.resetErrorBoundary
115
+ };
116
+ if (/* @__PURE__ */ React.isValidElement(fallback)) {
117
+ return fallback;
118
+ } else if (typeof fallbackRender === "function") {
119
+ return fallbackRender(_props);
120
+ } else if (FallbackComponent) {
121
+ return /* @__PURE__ */ React.createElement(FallbackComponent, _props);
122
+ } else {
123
+ throw new Error("react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop");
124
+ }
125
+ }
126
+ return this.props.children;
127
+ };
128
+ return ErrorBoundary2;
129
+ }(React.Component);
130
+ const defaultResourceContext = {
131
+ collection: void 0,
132
+ manifest: void 0,
133
+ range: void 0,
134
+ canvas: void 0,
135
+ annotation: void 0
136
+ };
137
+ const ResourceReactContext = React__default.createContext(defaultResourceContext);
138
+ const useResourceContext = () => {
139
+ return useContext(ResourceReactContext);
140
+ };
141
+ function ResourceProvider({
142
+ value,
143
+ children
144
+ }) {
145
+ const parentContext = useResourceContext();
146
+ const newContext = useMemo(() => {
147
+ return __spreadValues(__spreadValues({}, parentContext), value);
148
+ }, [value, parentContext]);
149
+ return /* @__PURE__ */ jsx(ResourceReactContext.Provider, {
150
+ value: newContext,
151
+ children
152
+ });
153
+ }
154
+ const ReactVaultContext = React__default.createContext({
155
+ vault: null,
156
+ setVaultInstance: (vault) => {
157
+ }
158
+ });
159
+ function VaultProvider({
160
+ vault,
161
+ vaultOptions,
162
+ useGlobal,
163
+ resources,
164
+ children
165
+ }) {
166
+ const [vaultInstance, setVaultInstance] = useState(() => {
167
+ if (vault) {
168
+ return vault;
169
+ }
170
+ if (useGlobal) {
171
+ return globalVault(vaultOptions);
172
+ }
173
+ if (vaultOptions) {
174
+ return new Vault(vaultOptions);
175
+ }
176
+ return new Vault();
177
+ });
178
+ return /* @__PURE__ */ jsx(ReactVaultContext.Provider, {
179
+ value: {
180
+ vault: vaultInstance,
181
+ setVaultInstance
182
+ },
183
+ children: /* @__PURE__ */ jsx(ResourceProvider, {
184
+ value: resources || {},
185
+ children
186
+ })
187
+ });
188
+ }
189
+ const useVault = () => {
190
+ const { vault } = useContext(ReactVaultContext);
191
+ if (vault === null) {
192
+ throw new Error("Vault not found. Ensure you have your provider set up correctly.");
193
+ }
194
+ return vault;
195
+ };
196
+ function useExternalResource(idOrRef, { noCache = false } = {}) {
197
+ const id = typeof idOrRef === "string" ? idOrRef : idOrRef.id;
198
+ const vault = useVault();
199
+ const [realId, setRealId] = useState(id);
200
+ const [error, setError] = useState(void 0);
201
+ const initialData = useMemo(() => {
202
+ return vault.get(id, { skipSelfReturn: true }) || void 0;
203
+ }, [id, vault]);
204
+ const [resource, setResource] = useState(initialData);
205
+ useEffect(() => {
206
+ (async () => {
207
+ try {
208
+ const fetchedResource = initialData && !noCache ? initialData : await vault.load(id);
209
+ const _realId = fetchedResource ? fetchedResource.id || fetchedResource["@id"] : null;
210
+ if (fetchedResource && realId !== _realId) {
211
+ setRealId(_realId);
212
+ }
213
+ setResource(fetchedResource);
214
+ } catch (err) {
215
+ setError(err);
216
+ }
217
+ })();
218
+ }, [id, noCache]);
219
+ return {
220
+ isLoaded: !!resource,
221
+ id: realId,
222
+ requestId: id,
223
+ error,
224
+ resource,
225
+ cached: !!(resource && resource === initialData)
226
+ };
227
+ }
228
+ function useExternalManifest(idOrRef, options) {
229
+ const { id, isLoaded, error, resource, requestId, cached } = useExternalResource(idOrRef, options);
230
+ return { id, isLoaded, error, manifest: resource, requestId, cached };
231
+ }
232
+ function ManifestContext({
233
+ manifest,
234
+ children
235
+ }) {
236
+ return /* @__PURE__ */ jsx(ResourceProvider, {
237
+ value: {
238
+ manifest
239
+ },
240
+ children
241
+ });
242
+ }
243
+ function CanvasContext({
244
+ canvas,
245
+ children
246
+ }) {
247
+ return /* @__PURE__ */ jsx(ResourceProvider, {
248
+ value: {
249
+ canvas
250
+ },
251
+ children
252
+ });
253
+ }
254
+ function useVaultSelector(selector, deps = []) {
255
+ const vault = useVault();
256
+ const [selectedState, setSelectedState] = useState(() => selector(vault.getState(), vault));
257
+ useEffect(() => {
258
+ return vault.subscribe((s) => selector(s, vault), (s) => {
259
+ setSelectedState(s);
260
+ }, false);
261
+ }, deps);
262
+ return selectedState;
263
+ }
264
+ const VisibleCanvasReactContext = React__default.createContext([]);
265
+ function useVisibleCanvases() {
266
+ const ids = useContext(VisibleCanvasReactContext);
267
+ return useVaultSelector((state) => {
268
+ return ids.map((id) => state.iiif.entities.Canvas[id]).filter(Boolean);
269
+ }, [ids]);
270
+ }
271
+ function useManifest(options = {}, deps = []) {
272
+ const { id, selector } = options;
273
+ const ctx = useResourceContext();
274
+ useVault();
275
+ const manifestId = id ? id : ctx.manifest;
276
+ const manifest = useVaultSelector((s) => manifestId ? s.iiif.entities.Manifest[manifestId] : void 0, [manifestId]);
277
+ return useMemo(() => {
278
+ if (!manifest) {
279
+ return void 0;
280
+ }
281
+ if (selector) {
282
+ return selector(manifest);
283
+ }
284
+ return manifest;
285
+ }, [manifest, selector, ...deps]);
286
+ }
287
+ function RangeContext({
288
+ range,
289
+ children
290
+ }) {
291
+ return /* @__PURE__ */ jsx(ResourceProvider, {
292
+ value: {
293
+ range
294
+ },
295
+ children
296
+ });
297
+ }
298
+ function findFirstCanvasFromRange(vault, range) {
299
+ for (const inner of range.items) {
300
+ if (inner.type === "Canvas") {
301
+ return inner;
302
+ }
303
+ if (inner.type === "Range") {
304
+ const found = findFirstCanvasFromRange(vault, vault.get(inner));
305
+ if (found) {
306
+ return found;
307
+ }
308
+ }
309
+ }
310
+ return null;
311
+ }
312
+ function findAllCanvasesInRange(vault, range) {
313
+ const found = [];
314
+ for (const inner of range.items) {
315
+ if (inner.type === "Canvas") {
316
+ if (inner.id.indexOf("#") !== -1) {
317
+ found.push({ id: inner.id.split("#")[0], type: "Canvas" });
318
+ } else {
319
+ found.push(inner);
320
+ }
321
+ }
322
+ if (inner.type === "Range") {
323
+ found.push(...findAllCanvasesInRange(vault, vault.get(inner)));
324
+ }
325
+ if (inner.type === "SpecificResource") {
326
+ const sourceId = typeof inner.source === "string" ? inner.source : inner.source.id;
327
+ found.push({ id: sourceId, type: "Canvas" });
328
+ }
329
+ }
330
+ return found;
331
+ }
332
+ function findManifestSelectedRange(vault, manifest, canvasId) {
333
+ for (const range of manifest.structures) {
334
+ const found = findSelectedRange(vault, vault.get(range), canvasId);
335
+ if (found) {
336
+ return found;
337
+ }
338
+ }
339
+ return null;
340
+ }
341
+ function findSelectedRange(vault, range, canvasId) {
342
+ var _a;
343
+ for (const inner of range.items) {
344
+ const parsedId = (_a = inner.id) == null ? void 0 : _a.split("#")[0];
345
+ if (inner.type === "SpecificResource" && inner.source === canvasId) {
346
+ return range;
347
+ }
348
+ if (inner.type === "Canvas" && canvasId === parsedId) {
349
+ return range;
350
+ }
351
+ if (inner.type === "Range") {
352
+ const found = findSelectedRange(vault, vault.get(inner), canvasId);
353
+ if (found) {
354
+ return found;
355
+ }
356
+ }
357
+ }
358
+ return null;
359
+ }
360
+ function getVisibleCanvasesFromCanvasId(vault, manifestOrRange, canvasId, preventPaged = false) {
361
+ const behavior = manifestOrRange.behavior;
362
+ const fullCanvas = canvasId ? vault.get(canvasId) : null;
363
+ if (!fullCanvas) {
364
+ return [];
365
+ }
366
+ const canvasBehavior = fullCanvas.behavior;
367
+ const isPaged = preventPaged ? false : behavior.includes("paged");
368
+ const isContinuous = isPaged ? false : behavior.includes("continuous");
369
+ const isIndividuals = isPaged || isContinuous ? false : behavior.includes("individuals");
370
+ const isCanvasFacingPages = canvasBehavior.includes("facing-pages");
371
+ const isCanvasNonPaged = canvasBehavior.includes("non-paged");
372
+ if (isCanvasFacingPages || isCanvasNonPaged || isIndividuals || preventPaged) {
373
+ return [{ id: fullCanvas.id, type: "Canvas" }];
374
+ }
375
+ const [manifestItems, ordering] = getManifestSequence(vault, manifestOrRange);
376
+ if (isContinuous) {
377
+ return manifestItems;
378
+ }
379
+ const canvasIndex = manifestItems.findIndex((r) => r.id === canvasId);
380
+ if (canvasIndex === -1) {
381
+ return [];
382
+ }
383
+ for (const indexes of ordering) {
384
+ if (indexes.includes(canvasIndex)) {
385
+ return indexes.map((index) => manifestItems[index]);
386
+ }
387
+ }
388
+ return [{ id: fullCanvas.id, type: "Canvas" }];
389
+ }
390
+ function getManifestSequence(vault, manifestOrRange, { disablePaging } = {}) {
391
+ const behavior = manifestOrRange.behavior;
392
+ const isPaged = behavior.includes("paged");
393
+ const isContinuous = isPaged ? false : behavior.includes("continuous");
394
+ const isIndividuals = isPaged || isContinuous ? false : behavior.includes("individuals");
395
+ const manifestItems = manifestOrRange.type === "Manifest" ? manifestOrRange.items : findAllCanvasesInRange(vault, manifestOrRange);
396
+ if (isContinuous) {
397
+ return [manifestItems, [manifestItems.map((_, index) => index)]];
398
+ }
399
+ if (isIndividuals || !isPaged || disablePaging) {
400
+ return [manifestItems, manifestItems.map((_, index) => [index])];
401
+ }
402
+ const ordering = [];
403
+ let currentOrdering = [];
404
+ const flush = () => {
405
+ if (currentOrdering.length) {
406
+ ordering.push([...currentOrdering]);
407
+ currentOrdering = [];
408
+ }
409
+ };
410
+ for (let i = 0; i < manifestItems.length; i++) {
411
+ const canvas = vault.get(manifestItems[i]);
412
+ if (i === 0 || canvas.behavior.includes("facing-pages")) {
413
+ flush();
414
+ ordering.push([i]);
415
+ continue;
416
+ }
417
+ if (canvas.behavior.includes("non-paged")) {
418
+ continue;
419
+ }
420
+ currentOrdering.push(i);
421
+ if (currentOrdering.length > 1) {
422
+ flush();
423
+ }
424
+ }
425
+ if (currentOrdering.length) {
426
+ flush();
427
+ }
428
+ return [manifestItems, ordering];
429
+ }
430
+ function useRange(options = {}, deps = []) {
431
+ const { id, selector } = options;
432
+ const ctx = useResourceContext();
433
+ const rangeId = id ? id : ctx.range;
434
+ const range = useVaultSelector((s) => rangeId ? s.iiif.entities.Range[rangeId] : void 0, [rangeId]);
435
+ return useMemo(() => {
436
+ if (!range) {
437
+ return void 0;
438
+ }
439
+ if (selector) {
440
+ return selector(range);
441
+ }
442
+ return range;
443
+ }, [range, selector, ...deps]);
444
+ }
445
+ function useCanvasSequence({ startCanvas, disablePaging }) {
446
+ var _a;
447
+ const vault = useVault();
448
+ const manifest = useManifest();
449
+ const range = useRange();
450
+ const [cursor, setCursor] = useState(void 0);
451
+ const rangeOrManifest = range ? range : manifest;
452
+ if (!rangeOrManifest) {
453
+ throw new Error("Nothing selected");
454
+ }
455
+ const [items, initialSequence] = useMemo(() => getManifestSequence(vault, rangeOrManifest, { disablePaging }), [vault, rangeOrManifest]);
456
+ const setCanvasIndex = useCallback((index) => {
457
+ const foundSequence = initialSequence.findIndex((i) => i.includes(index));
458
+ setCursor(foundSequence === -1 ? 0 : foundSequence);
459
+ }, [items, initialSequence]);
460
+ const setCanvasId = useCallback((id) => {
461
+ const foundIndex = items.findIndex((i) => i.id === id);
462
+ if (foundIndex !== -1) {
463
+ setCanvasIndex(foundIndex);
464
+ } else {
465
+ setCursor(0);
466
+ }
467
+ }, [items, initialSequence]);
468
+ const next = useCallback(() => {
469
+ setCursor((i) => {
470
+ if (i >= initialSequence.length) {
471
+ return i;
472
+ }
473
+ return i + 1;
474
+ });
475
+ }, [initialSequence]);
476
+ const previous = useCallback(() => {
477
+ setCursor((i) => {
478
+ if (i <= 0) {
479
+ return 0;
480
+ }
481
+ return i - 1;
482
+ });
483
+ }, [initialSequence]);
484
+ if (typeof cursor === "undefined") {
485
+ if (startCanvas) {
486
+ setCanvasId(startCanvas);
487
+ } else {
488
+ setCursor(0);
489
+ }
490
+ }
491
+ return {
492
+ visibleItems: ((_a = initialSequence[cursor]) == null ? void 0 : _a.map((idx) => items[idx].id)) || [],
493
+ cursor,
494
+ items,
495
+ sequence: initialSequence,
496
+ setSequenceIndex: setCursor,
497
+ setCanvasIndex,
498
+ setCanvasId,
499
+ next,
500
+ previous
501
+ };
502
+ }
503
+ const noop = () => {
504
+ };
505
+ const SimpleViewerReactContext = createContext({
506
+ setCurrentCanvasId: noop,
507
+ setCurrentCanvasIndex: noop,
508
+ nextCanvas: noop,
509
+ previousCanvas: noop,
510
+ items: [],
511
+ sequence: [],
512
+ setSequenceIndex: noop,
513
+ currentSequenceIndex: 0
514
+ });
515
+ function InnerViewerProvider(props) {
516
+ const manifest = useManifest();
517
+ const {
518
+ cursor,
519
+ visibleItems,
520
+ next,
521
+ sequence,
522
+ items,
523
+ setCanvasIndex,
524
+ setCanvasId,
525
+ previous,
526
+ setSequenceIndex
527
+ } = useCanvasSequence({
528
+ startCanvas: props.startCanvas,
529
+ disablePaging: props.pagingEnabled === false
530
+ });
531
+ const ctx = useMemo(() => ({
532
+ sequence,
533
+ items,
534
+ setCurrentCanvasId: setCanvasId,
535
+ nextCanvas: next,
536
+ previousCanvas: previous,
537
+ totalCanvases: items.length,
538
+ setCurrentCanvasIndex: setCanvasIndex,
539
+ setSequenceIndex,
540
+ currentSequenceIndex: cursor
541
+ }), [sequence, items, setCanvasId, next, previous, items, setCanvasIndex, setSequenceIndex, cursor]);
542
+ if (!manifest) {
543
+ console.warn("The manifest passed to the provider is not a valid IIIF manifest.");
544
+ return /* @__PURE__ */ jsx("div", {
545
+ children: "Sorry, something went wrong."
546
+ });
547
+ }
548
+ return /* @__PURE__ */ jsx(SimpleViewerReactContext.Provider, {
549
+ value: ctx,
550
+ children: /* @__PURE__ */ jsx(VisibleCanvasReactContext.Provider, {
551
+ value: visibleItems,
552
+ children: /* @__PURE__ */ jsx(CanvasContext, {
553
+ canvas: visibleItems[0],
554
+ children: props.children
555
+ })
556
+ })
557
+ });
558
+ }
559
+ function SimpleViewerProvider(props) {
560
+ const manifest = useExternalManifest(props.manifest);
561
+ if (!manifest) {
562
+ console.warn("The manifest passed to the provider is not a valid IIIF manifest.");
563
+ return /* @__PURE__ */ jsx("div", {
564
+ children: "Sorry, something went wrong."
565
+ });
566
+ }
567
+ if (!manifest.isLoaded) {
568
+ return /* @__PURE__ */ jsx("div", {
569
+ children: "Loading..."
570
+ });
571
+ }
572
+ const inner = /* @__PURE__ */ jsx(InnerViewerProvider, __spreadProps(__spreadValues({}, props), {
573
+ children: props.children
574
+ }));
575
+ return /* @__PURE__ */ jsx(ManifestContext, {
576
+ manifest: manifest.id,
577
+ children: props.rangeId ? /* @__PURE__ */ jsx(RangeContext, {
578
+ range: props.rangeId,
579
+ children: inner
580
+ }) : inner
581
+ });
582
+ }
583
+ function useSimpleViewer() {
584
+ return useContext(SimpleViewerReactContext);
585
+ }
586
+ function useContextBridge() {
587
+ return {
588
+ VaultContext: useContext(ReactVaultContext),
589
+ ResourceContext: useContext(ResourceReactContext),
590
+ SimpleViewerReactContext: useContext(SimpleViewerReactContext),
591
+ VisibleCanvasReactContext: useContext(VisibleCanvasReactContext)
592
+ };
593
+ }
594
+ function ContextBridge(props) {
595
+ return /* @__PURE__ */ jsx(VaultProvider, {
596
+ vault: props.bridge.VaultContext.vault || void 0,
597
+ resources: props.bridge.ResourceContext,
598
+ children: /* @__PURE__ */ jsx(VisibleCanvasReactContext.Provider, {
599
+ value: props.bridge.VisibleCanvasReactContext,
600
+ children: /* @__PURE__ */ jsx(SimpleViewerReactContext.Provider, {
601
+ value: props.bridge.SimpleViewerReactContext,
602
+ children: props.children
603
+ })
604
+ })
605
+ });
606
+ }
607
+ const IMPORT_ENTITIES = "@iiif/IMPORT_ENTITIES";
608
+ const MODIFY_ENTITY_FIELD = "@iiif/MODIFY_ENTITY_FIELD";
609
+ const REORDER_ENTITY_FIELD = "@iiif/REORDER_ENTITY_FIELD";
610
+ const ADD_REFERENCE = "@iiif/ADD_REFERENCE";
611
+ const REMOVE_REFERENCE = "@iiif/REMOVE_REFERENCE";
612
+ const importEntities = createAction(IMPORT_ENTITIES)();
613
+ const modifyEntityField = createAction(MODIFY_ENTITY_FIELD)();
614
+ const reorderEntityField = createAction(REORDER_ENTITY_FIELD)();
615
+ const addReference = createAction(ADD_REFERENCE)();
616
+ const removeReference = createAction(REMOVE_REFERENCE)();
617
+ const entityActions = { importEntities, modifyEntityField, reorderEntityField, addReference, removeReference };
618
+ const ADD_MAPPING = "@iiif/ADD_MAPPING";
619
+ const ADD_MAPPINGS = "@iiif/ADD_MAPPINGS";
620
+ createAction(ADD_MAPPING)();
621
+ createAction(ADD_MAPPINGS)();
622
+ const SET_META_VALUE = "@iiif/SET_META_VALUE";
623
+ const SET_META_VALUE_DYNAMIC = "@iiif/SET_META_VALUE_DYNAMIC";
624
+ const UNSET_META_VALUE = "@iiif/UNSET_META_VALUE";
625
+ createAction(SET_META_VALUE)();
626
+ createAction(SET_META_VALUE_DYNAMIC)();
627
+ createAction(UNSET_META_VALUE)();
628
+ const REQUEST_RESOURCE = "@iiif/REQUEST_RESOURCE";
629
+ const REQUEST_ERROR = "@iiif/REQUEST_ERROR";
630
+ const REQUEST_MISMATCH = "@iiif/REQUEST_MISMATCH";
631
+ const REQUEST_COMPLETE = "@iiif/REQUEST_COMPLETE";
632
+ const REQUEST_OFFLINE_RESOURCE = "@iiif/REQUEST_OFFLINE_RESOURCE";
633
+ createAction(REQUEST_RESOURCE)();
634
+ createAction(REQUEST_ERROR)();
635
+ createAction(REQUEST_MISMATCH)();
636
+ createAction(REQUEST_COMPLETE)();
637
+ createAction(REQUEST_OFFLINE_RESOURCE)();
638
+ const BATCH_ACTIONS = "@iiif/BATCH";
639
+ const BATCH_IMPORT = "@iiif/BATCH_IMPORT";
640
+ createAction(BATCH_ACTIONS)();
641
+ createAction(BATCH_IMPORT)();
642
+ function useDispatch() {
643
+ const vault = useVault();
644
+ const store = vault.getStore();
645
+ return useMemo(() => {
646
+ return (action) => store.dispatch(action);
647
+ }, [store]);
648
+ }
649
+ function isVaultActivated(obj) {
650
+ return typeof obj !== "string" && obj && obj.bindToVault;
651
+ }
652
+ function useVirtualAnnotationPage() {
653
+ const vault = useVault();
654
+ const sources = useRef([]);
655
+ const dispatch = useDispatch();
656
+ const virtualId = useMemo(() => {
657
+ return `vault://annotation-page/${new Date().getTime()}/${Math.round(Math.random() * 1e9).toString(16)}`;
658
+ }, []);
659
+ useLayoutEffect(() => {
660
+ const page = {
661
+ id: virtualId,
662
+ type: "AnnotationPage",
663
+ behavior: [],
664
+ motivation: null,
665
+ label: null,
666
+ thumbnail: [],
667
+ summary: null,
668
+ requiredStatement: null,
669
+ metadata: [],
670
+ rights: null,
671
+ provider: [],
672
+ items: [],
673
+ seeAlso: [],
674
+ homepage: [],
675
+ logo: [],
676
+ rendering: [],
677
+ service: []
678
+ };
679
+ dispatch(entityActions.importEntities({
680
+ entities: {
681
+ AnnotationPage: {
682
+ [page.id]: page
683
+ }
684
+ }
685
+ }));
686
+ }, [virtualId]);
687
+ const fullPage = useVaultSelector((state) => virtualId ? state.iiif.entities.AnnotationPage[virtualId] : null, [virtualId]);
688
+ const addAnnotation = useCallback((id, atIndex) => {
689
+ if (virtualId) {
690
+ if (isVaultActivated(id)) {
691
+ const display = id;
692
+ if (!display.__vault) {
693
+ display.bindToVault(vault);
694
+ }
695
+ id = typeof display.source === "string" ? display.source : display.source.id;
696
+ sources.current[id] = display;
697
+ } else if (typeof id !== "string") {
698
+ id = id.id;
699
+ }
700
+ const full = vault.get({ id: virtualId, type: "AnnotationPage" });
701
+ const annotation = vault.get({ id, type: "Annotation" });
702
+ if (full && annotation) {
703
+ if (!full.items.find((r) => r.id === annotation.id)) {
704
+ dispatch(entityActions.addReference({
705
+ id: virtualId,
706
+ type: "AnnotationPage",
707
+ key: "items",
708
+ reference: {
709
+ id,
710
+ type: "Annotation"
711
+ },
712
+ index: atIndex
713
+ }));
714
+ }
715
+ }
716
+ }
717
+ }, [virtualId]);
718
+ const removeAnnotation = useCallback((id) => {
719
+ if (virtualId) {
720
+ if (isVaultActivated(id)) {
721
+ id = typeof id.source === "string" ? id.source : id.source.id;
722
+ } else if (typeof id !== "string") {
723
+ id = id.id;
724
+ }
725
+ if (sources.current[id]) {
726
+ sources.current[id].beforeRemove();
727
+ }
728
+ const full = vault.get({ id: virtualId, type: "AnnotationPage" });
729
+ if (full) {
730
+ dispatch(entityActions.removeReference({
731
+ id: virtualId,
732
+ type: "AnnotationPage",
733
+ key: "items",
734
+ reference: {
735
+ id,
736
+ type: "Annotation"
737
+ }
738
+ }));
739
+ }
740
+ }
741
+ }, [virtualId]);
742
+ return [
743
+ fullPage,
744
+ {
745
+ addAnnotation,
746
+ removeAnnotation
747
+ }
748
+ ];
749
+ }
750
+ const VirtualAnnotationPageContext = createContext(null);
751
+ function useVirtualAnnotationPageContext() {
752
+ const ctx = useContext(VirtualAnnotationPageContext);
753
+ return [ctx.fullPage, {
754
+ addAnnotation: ctx.addAnnotation,
755
+ removeAnnotation: ctx.removeAnnotation
756
+ }];
757
+ }
758
+ function VirtualAnnotationProvider({
759
+ children
760
+ }) {
761
+ const [fullPage, {
762
+ addAnnotation,
763
+ removeAnnotation
764
+ }] = useVirtualAnnotationPage();
765
+ return /* @__PURE__ */ jsx(VirtualAnnotationPageContext.Provider, {
766
+ value: useMemo(() => ({
767
+ fullPage,
768
+ addAnnotation,
769
+ removeAnnotation
770
+ }), [fullPage]),
771
+ children
772
+ });
773
+ }
774
+ function DefaultCanvasFallback({
775
+ width,
776
+ style,
777
+ height
778
+ }) {
779
+ return /* @__PURE__ */ jsx("div", {
780
+ style: __spreadProps(__spreadValues({
781
+ width,
782
+ height,
783
+ minHeight: 500
784
+ }, style || {}), {
785
+ background: "#f9f9f9"
786
+ }),
787
+ children: "Unknown error"
788
+ });
789
+ }
790
+ const ViewerPresetContext = createContext(null);
791
+ function useViewerPreset() {
792
+ return useContext(ViewerPresetContext);
793
+ }
794
+ const PortalContext = React__default.createContext(null);
795
+ const OverlayPortalContext = React__default.createContext(null);
796
+ function CanvasPortal({
797
+ children,
798
+ overlay
799
+ }) {
800
+ const htmlElement = useContext(overlay ? OverlayPortalContext : PortalContext);
801
+ const preset = useViewerPreset();
802
+ useLayoutEffect(() => {
803
+ if (htmlElement) {
804
+ try {
805
+ htmlElement.render(/* @__PURE__ */ jsx(ViewerPresetContext.Provider, {
806
+ value: preset,
807
+ children
808
+ }));
809
+ } catch (e) {
810
+ }
811
+ }
812
+ }, [children, preset]);
813
+ return null;
814
+ }
815
+ var createRoot;
816
+ var m = require$$0;
817
+ {
818
+ createRoot = m.createRoot;
819
+ }
820
+ function Viewer(_a) {
821
+ var _b = _a, {
822
+ children,
823
+ errorFallback,
824
+ outerContainerProps = {}
825
+ } = _b, props = __objRest(_b, [
826
+ "children",
827
+ "errorFallback",
828
+ "outerContainerProps"
829
+ ]);
830
+ const portal = useRef(null);
831
+ const [portalElement, setPortalElement] = useState();
832
+ const [viewerPreset, setViewerPreset] = useState();
833
+ const overlayPortal = useRef(null);
834
+ const [overlayPortalElement, setOverlayPortalElement] = useState();
835
+ const bridge = useContextBridge();
836
+ const ErrorFallback = errorFallback || DefaultCanvasFallback;
837
+ useLayoutEffect(() => {
838
+ const roots = {};
839
+ if (portal.current) {
840
+ const $el = document.createElement("div");
841
+ portal.current.appendChild($el);
842
+ roots.portal = createRoot($el);
843
+ setPortalElement(roots.portal);
844
+ }
845
+ if (overlayPortal.current) {
846
+ const $el = document.createElement("div");
847
+ overlayPortal.current.appendChild($el);
848
+ roots.overlayPortal = createRoot($el);
849
+ setOverlayPortalElement(roots.overlayPortal);
850
+ }
851
+ return () => {
852
+ setPortalElement(null);
853
+ setOverlayPortalElement(null);
854
+ setTimeout(() => {
855
+ if (roots.portal) {
856
+ roots.portal.unmount();
857
+ }
858
+ if (roots.overlayPortal) {
859
+ roots.overlayPortal.unmount();
860
+ }
861
+ }, 0);
862
+ };
863
+ }, []);
864
+ return /* @__PURE__ */ jsxs(ErrorBoundary, {
865
+ fallbackRender: () => /* @__PURE__ */ jsx(ErrorFallback, __spreadValues({}, props)),
866
+ children: [/* @__PURE__ */ jsx(AtlasAuto, __spreadProps(__spreadValues({}, props), {
867
+ containerProps: __spreadValues({
868
+ style: {
869
+ position: "relative"
870
+ }
871
+ }, props.containerProps || {}),
872
+ htmlChildren: /* @__PURE__ */ jsx("div", {
873
+ ref: overlayPortal
874
+ }),
875
+ onCreated: (preset) => {
876
+ setViewerPreset(preset);
877
+ if (props.onCreated) {
878
+ props.onCreated(preset);
879
+ }
880
+ },
881
+ children: /* @__PURE__ */ jsx(ViewerPresetContext.Provider, {
882
+ value: viewerPreset,
883
+ children: /* @__PURE__ */ jsx(PortalContext.Provider, {
884
+ value: portalElement,
885
+ children: /* @__PURE__ */ jsx(OverlayPortalContext.Provider, {
886
+ value: overlayPortalElement,
887
+ children: /* @__PURE__ */ jsx(ContextBridge, {
888
+ bridge,
889
+ children: /* @__PURE__ */ jsx(VirtualAnnotationProvider, {
890
+ children
891
+ })
892
+ })
893
+ })
894
+ })
895
+ })
896
+ })), /* @__PURE__ */ jsx("div", {
897
+ ref: portal
898
+ })]
899
+ });
900
+ }
901
+ function createEventsHelper(vault) {
902
+ return {
903
+ addEventListener(resource, event, listener, scope) {
904
+ if (!resource) {
905
+ return;
906
+ }
907
+ vault.setMetaValue([resource.id, "eventManager", event], (registeredCallbacks) => {
908
+ const callbacks = registeredCallbacks || [];
909
+ for (const registered of callbacks) {
910
+ if (registered.callback === listener) {
911
+ return callbacks;
912
+ }
913
+ }
914
+ return [...callbacks, { callback: listener, scope }];
915
+ });
916
+ return listener;
917
+ },
918
+ removeEventListener(resource, event, listener) {
919
+ if (!resource) {
920
+ return;
921
+ }
922
+ vault.setMetaValue([resource.id, "eventManager", event], (registeredCallbacks) => {
923
+ return (registeredCallbacks || []).filter((registeredCallback) => registeredCallback.callback !== listener);
924
+ });
925
+ },
926
+ getListenersAsProps(resourceOrId, scope) {
927
+ const resource = typeof resourceOrId === "string" ? { id: resourceOrId } : resourceOrId;
928
+ if (!resource || !resource.id) {
929
+ return {};
930
+ }
931
+ const hooks = vault.getResourceMeta(resource.id, "eventManager");
932
+ const props = {};
933
+ if (hooks && resource) {
934
+ for (const hook of Object.keys(hooks)) {
935
+ props[hook] = (e) => {
936
+ const fullResource = vault.get(resource);
937
+ for (const { callback, scope: _scope } of hooks[hook] || []) {
938
+ if (!_scope || scope && _scope.indexOf(scope) !== -1) {
939
+ callback(e, fullResource);
940
+ }
941
+ }
942
+ };
943
+ }
944
+ }
945
+ return props;
946
+ }
947
+ };
948
+ }
949
+ function useResourceEvents(resource, scope) {
950
+ const vault = useVault();
951
+ const helper = useMemo(() => createEventsHelper(vault), [vault]);
952
+ const hooks = useVaultSelector(() => {
953
+ if (resource && resource.id) {
954
+ return vault.getResourceMeta(resource.id, "eventManager");
955
+ }
956
+ return null;
957
+ }, [resource]);
958
+ return useMemo(() => {
959
+ return resource ? helper.getListenersAsProps(resource, scope) : {};
960
+ }, [hooks, resource, vault, scope]);
961
+ }
962
+ function createStylesHelper(vault) {
963
+ return {
964
+ applyStyles(resource, scope, styles) {
965
+ const id = typeof resource === "string" ? resource : resource.id;
966
+ return vault.setMetaValue([id, "styles", scope], styles);
967
+ },
968
+ getAppliedStyles(resource) {
969
+ const id = typeof resource === "string" ? resource : resource.id;
970
+ return vault.getResourceMeta(id, "styles");
971
+ }
972
+ };
973
+ }
974
+ function useStyles(resource, scope) {
975
+ const vault = useVault();
976
+ const helper = useMemo(() => createStylesHelper(vault), [vault]);
977
+ return useVaultSelector(() => {
978
+ if (!resource) {
979
+ return null;
980
+ }
981
+ const styles = helper.getAppliedStyles(resource.id);
982
+ return styles ? scope ? styles[scope] : styles : void 0;
983
+ }, [resource, scope]);
984
+ }
985
+ var __defProp$1 = Object.defineProperty;
986
+ var __defProps$1 = Object.defineProperties;
987
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
988
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
989
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
990
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
991
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
992
+ var __spreadValues$1 = (a, b) => {
993
+ for (var prop in b || (b = {}))
994
+ if (__hasOwnProp$1.call(b, prop))
995
+ __defNormalProp$1(a, prop, b[prop]);
996
+ if (__getOwnPropSymbols$1)
997
+ for (var prop of __getOwnPropSymbols$1(b)) {
998
+ if (__propIsEnum$1.call(b, prop))
999
+ __defNormalProp$1(a, prop, b[prop]);
1000
+ }
1001
+ return a;
1002
+ };
1003
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
1004
+ const BOX_SELECTOR = /&?(xywh=)?(pixel:|percent:|pct:)?([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?)/;
1005
+ const TEMPORAL_SELECTOR = /&?(t=)(npt:)?([0-9]+(.[0-9]+)?)?(,([0-9]+(.[0-9]+)?))?/;
1006
+ function parseSelector(source) {
1007
+ if (Array.isArray(source)) {
1008
+ return source.reduce((data, nextSource) => {
1009
+ const { selector, selectors } = parseSelector(nextSource);
1010
+ if (selector) {
1011
+ if (!data.selector) {
1012
+ data.selector = selector;
1013
+ }
1014
+ data.selectors.push(...selectors);
1015
+ }
1016
+ return data;
1017
+ }, {
1018
+ selector: null,
1019
+ selectors: []
1020
+ });
1021
+ }
1022
+ if (!source) {
1023
+ return {
1024
+ selector: null,
1025
+ selectors: []
1026
+ };
1027
+ }
1028
+ if (typeof source === "string") {
1029
+ const [id, fragment] = source.split("#");
1030
+ if (!fragment) {
1031
+ return {
1032
+ selector: null,
1033
+ selectors: []
1034
+ };
1035
+ }
1036
+ return parseSelector({ type: "FragmentSelector", value: fragment });
1037
+ }
1038
+ if (source.type === "PointSelector" && (source.t || source.t === 0)) {
1039
+ const selector = {
1040
+ type: "TemporalSelector",
1041
+ temporal: {
1042
+ startTime: source.t
1043
+ }
1044
+ };
1045
+ return {
1046
+ selector,
1047
+ selectors: [selector]
1048
+ };
1049
+ }
1050
+ if (source.type === "FragmentSelector") {
1051
+ const matchBoxSelector = BOX_SELECTOR.exec(source.value);
1052
+ if (matchBoxSelector) {
1053
+ const selector = {
1054
+ type: "BoxSelector",
1055
+ spatial: {
1056
+ unit: matchBoxSelector[2] === "percent:" || matchBoxSelector[2] === "pct:" ? "percent" : "pixel",
1057
+ x: parseFloat(matchBoxSelector[3]),
1058
+ y: parseFloat(matchBoxSelector[4]),
1059
+ width: parseFloat(matchBoxSelector[5]),
1060
+ height: parseFloat(matchBoxSelector[6])
1061
+ }
1062
+ };
1063
+ return {
1064
+ selector,
1065
+ selectors: [selector]
1066
+ };
1067
+ }
1068
+ const matchTimeSelector = source.value.match(TEMPORAL_SELECTOR);
1069
+ if (matchTimeSelector) {
1070
+ const selector = {
1071
+ type: "TemporalSelector",
1072
+ temporal: {
1073
+ startTime: matchTimeSelector[4] ? parseFloat(matchTimeSelector[4]) : 0,
1074
+ endTime: matchTimeSelector[7] ? parseFloat(matchTimeSelector[7]) : void 0
1075
+ }
1076
+ };
1077
+ return {
1078
+ selector,
1079
+ selectors: [selector]
1080
+ };
1081
+ }
1082
+ return {
1083
+ selector: null,
1084
+ selectors: []
1085
+ };
1086
+ }
1087
+ return {
1088
+ selector: null,
1089
+ selectors: []
1090
+ };
1091
+ }
1092
+ function expandTarget(target, options = {}) {
1093
+ if (Array.isArray(target)) {
1094
+ return expandTarget(target[0]);
1095
+ }
1096
+ if (typeof target === "string") {
1097
+ const [id, fragment] = target.split("#");
1098
+ if (!fragment) {
1099
+ return {
1100
+ type: "SpecificResource",
1101
+ source: { id, type: options.typeMap && options.typeMap[id] || "Unknown" },
1102
+ selector: null,
1103
+ selectors: []
1104
+ };
1105
+ }
1106
+ return expandTarget({
1107
+ type: "SpecificResource",
1108
+ source: { id, type: "Unknown" },
1109
+ selector: {
1110
+ type: "FragmentSelector",
1111
+ value: fragment
1112
+ }
1113
+ });
1114
+ }
1115
+ if (target.type === "Choice" || target.type === "List" || target.type === "Composite" || target.type === "Independents") {
1116
+ return expandTarget(target.items[0]);
1117
+ }
1118
+ if (target.type === "SpecificResource") {
1119
+ if (target.source.type === "Canvas" && target.source.partOf && typeof target.source.partOf === "string") {
1120
+ target.source.partOf = [
1121
+ {
1122
+ id: target.source.partOf,
1123
+ type: "Manifest"
1124
+ }
1125
+ ];
1126
+ }
1127
+ const { selector, selectors } = target.selector ? parseSelector(target.selector) : { selector: null, selectors: [] };
1128
+ return {
1129
+ type: "SpecificResource",
1130
+ source: target.source,
1131
+ selector,
1132
+ selectors
1133
+ };
1134
+ }
1135
+ if (target.id) {
1136
+ if (target.type === "Canvas" && target.partOf && typeof target.partOf === "string") {
1137
+ target.partOf = [
1138
+ {
1139
+ id: target.partOf,
1140
+ type: "Manifest"
1141
+ }
1142
+ ];
1143
+ }
1144
+ const [id, fragment] = target.id.split("#");
1145
+ if (!fragment) {
1146
+ return {
1147
+ type: "SpecificResource",
1148
+ source: __spreadProps$1(__spreadValues$1({}, target), {
1149
+ id
1150
+ }),
1151
+ selector: null,
1152
+ selectors: []
1153
+ };
1154
+ }
1155
+ return expandTarget({
1156
+ type: "SpecificResource",
1157
+ source: __spreadProps$1(__spreadValues$1({}, target), {
1158
+ id
1159
+ }),
1160
+ selector: {
1161
+ type: "FragmentSelector",
1162
+ value: fragment
1163
+ }
1164
+ });
1165
+ }
1166
+ return {
1167
+ type: "SpecificResource",
1168
+ source: target,
1169
+ selector: null,
1170
+ selectors: []
1171
+ };
1172
+ }
1173
+ function useAnnotation(options = {}, deps = []) {
1174
+ const { id, selector } = options;
1175
+ const ctx = useResourceContext();
1176
+ const vault = useVault();
1177
+ const annotationId = id ? id : ctx.annotation;
1178
+ const annotation = useVaultSelector((s) => annotationId ? s.iiif.entities.Annotation[annotationId] : void 0, [annotationId]);
1179
+ const body = useVaultSelector((s) => annotation && annotation.body ? annotation.body.map((singleBody) => singleBody ? s.iiif.entities[singleBody.type][singleBody.id] : null).filter(Boolean) : [], [annotation]);
1180
+ return useMemo(() => {
1181
+ if (!annotation) {
1182
+ return void 0;
1183
+ }
1184
+ const newAnnotation = __spreadProps(__spreadValues({}, annotation), {
1185
+ body,
1186
+ target: expandTarget(annotation.target, { typeMap: vault.getState().iiif.mapping })
1187
+ });
1188
+ if (selector) {
1189
+ return selector(newAnnotation);
1190
+ }
1191
+ return newAnnotation;
1192
+ }, [annotation, selector, body, ...deps]);
1193
+ }
1194
+ function useCanvas(options = {}, deps = []) {
1195
+ const { id, selector } = options;
1196
+ const ctx = useResourceContext();
1197
+ const canvasId = id ? id : ctx.canvas;
1198
+ const canvas = useVaultSelector((s) => canvasId ? s.iiif.entities.Canvas[canvasId] : void 0, [canvasId]);
1199
+ return useMemo(() => {
1200
+ if (!canvas) {
1201
+ return void 0;
1202
+ }
1203
+ if (selector) {
1204
+ return selector(canvas);
1205
+ }
1206
+ return canvas;
1207
+ }, [canvas, selector, ...deps]);
1208
+ }
1209
+ const RenderAnnotation = ({
1210
+ id,
1211
+ style: defaultStyle,
1212
+ className,
1213
+ interactive
1214
+ }) => {
1215
+ const annotation = useAnnotation({
1216
+ id
1217
+ });
1218
+ const style = useStyles(annotation, "atlas");
1219
+ const html = useStyles(annotation, "html");
1220
+ const events = useResourceEvents(annotation, ["atlas"]);
1221
+ const canvas = useCanvas();
1222
+ const allStyles = useMemo(() => {
1223
+ return mergeStyles(defaultStyle, style);
1224
+ }, [defaultStyle, style]);
1225
+ const isValid = canvas && annotation && annotation.target && annotation.target.selector && annotation.target.selector.type === "BoxSelector" && annotation.target.source && annotation.target.source.id === canvas.id;
1226
+ if (!isValid) {
1227
+ return null;
1228
+ }
1229
+ return /* @__PURE__ */ jsx(RegionHighlight, __spreadValues({
1230
+ id: annotation.id,
1231
+ isEditing: true,
1232
+ region: annotation.target.selector.spatial,
1233
+ style: allStyles,
1234
+ className: (html == null ? void 0 : html.className) || className,
1235
+ interactive: !!((html == null ? void 0 : html.href) || interactive),
1236
+ href: (html == null ? void 0 : html.href) || null,
1237
+ title: (html == null ? void 0 : html.title) || null,
1238
+ hrefTarget: (html == null ? void 0 : html.target) || null
1239
+ }, events));
1240
+ };
1241
+ const RenderAnnotationPage = ({
1242
+ className,
1243
+ page
1244
+ }) => {
1245
+ var _a;
1246
+ const style = useStyles(page, "atlas");
1247
+ const html = useStyles(page, "html");
1248
+ useVaultSelector((state) => page.id ? state.iiif.entities.AnnotationPage[page.id] : null, []);
1249
+ return /* @__PURE__ */ jsx(Fragment, {
1250
+ children: (_a = page.items) == null ? void 0 : _a.map((annotation) => {
1251
+ return /* @__PURE__ */ jsx(RenderAnnotation, {
1252
+ id: annotation.id,
1253
+ style,
1254
+ className: (html == null ? void 0 : html.className) || className
1255
+ }, annotation.id);
1256
+ })
1257
+ });
1258
+ };
1259
+ function RenderImage({
1260
+ id,
1261
+ image,
1262
+ thumbnail,
1263
+ isStatic,
1264
+ x = 0,
1265
+ y = 0,
1266
+ children,
1267
+ onClick
1268
+ }) {
1269
+ var _a, _b, _c, _d;
1270
+ return /* @__PURE__ */ jsx(Fragment, {
1271
+ children: !image.service ? /* @__PURE__ */ jsxs(Fragment, {
1272
+ children: [/* @__PURE__ */ jsx("world-image", {
1273
+ onClick,
1274
+ uri: image.id,
1275
+ target: image.target.spatial,
1276
+ display: image.width && image.height ? {
1277
+ width: image.width,
1278
+ height: image.height
1279
+ } : void 0
1280
+ }), children]
1281
+ }, "no-service") : /* @__PURE__ */ jsxs(Fragment, {
1282
+ children: [/* @__PURE__ */ jsx(TileSet, {
1283
+ tiles: {
1284
+ id: image.service.id || image.service["@id"] || "unknown",
1285
+ height: image.height,
1286
+ width: image.width,
1287
+ imageService: image.service,
1288
+ thumbnail: thumbnail && thumbnail.type === "fixed" ? thumbnail : void 0
1289
+ },
1290
+ x: ((_a = image.target) == null ? void 0 : _a.spatial.x) + x,
1291
+ y: ((_b = image.target) == null ? void 0 : _b.spatial.y) + y,
1292
+ width: (_c = image.target) == null ? void 0 : _c.spatial.width,
1293
+ height: (_d = image.target) == null ? void 0 : _d.spatial.height,
1294
+ onClick
1295
+ }), children]
1296
+ }, "service")
1297
+ }, id);
1298
+ }
1299
+ function parseSpecificResource(resource) {
1300
+ if (resource.type === "SpecificResource") {
1301
+ return [resource.source, { selector: resource.selector }];
1302
+ }
1303
+ return [resource, { selector: null }];
1304
+ }
1305
+ function getPaintables(vault, paintingAnnotations, enabledChoices) {
1306
+ const types = [];
1307
+ let choice = null;
1308
+ const items = [];
1309
+ for (const annotation of paintingAnnotations) {
1310
+ const bodies = vault.get(annotation.body);
1311
+ for (const unknownBody of bodies) {
1312
+ const [body, { selector }] = parseSpecificResource(unknownBody);
1313
+ const type = (body.type || "unknown").toLowerCase();
1314
+ if (type === "choice") {
1315
+ const nestedBodies = vault.get(body.items);
1316
+ const selected = enabledChoices.length ? enabledChoices.map((cid) => nestedBodies.find((b) => b.id === cid)).filter(Boolean) : [nestedBodies[0]];
1317
+ if (selected.length === 0) {
1318
+ selected.push(nestedBodies[0]);
1319
+ }
1320
+ choice = {
1321
+ type: "single-choice",
1322
+ items: nestedBodies.map((b) => ({
1323
+ id: b.id,
1324
+ label: b.label,
1325
+ selected: selected.indexOf(b) !== -1
1326
+ })),
1327
+ label: unknownBody.label
1328
+ };
1329
+ bodies.push(...selected);
1330
+ continue;
1331
+ }
1332
+ if (types.indexOf(type) === -1) {
1333
+ types.push(type);
1334
+ }
1335
+ items.push({
1336
+ annotationId: annotation.id,
1337
+ type,
1338
+ resource: body,
1339
+ target: annotation.target,
1340
+ selector
1341
+ });
1342
+ }
1343
+ }
1344
+ return {
1345
+ types,
1346
+ items,
1347
+ choice
1348
+ };
1349
+ }
1350
+ function getParsedTargetSelector(canvas, target) {
1351
+ const { selector: imageTarget, source } = expandTarget$1(target);
1352
+ if (source.id !== canvas.id) {
1353
+ return [null, source];
1354
+ }
1355
+ const defaultTarget = {
1356
+ type: "BoxSelector",
1357
+ spatial: {
1358
+ x: 0,
1359
+ y: 0,
1360
+ width: canvas.width,
1361
+ height: canvas.height
1362
+ }
1363
+ };
1364
+ return [
1365
+ imageTarget ? imageTarget.type === "TemporalSelector" ? {
1366
+ type: "TemporalBoxSelector",
1367
+ temporal: imageTarget.temporal,
1368
+ spatial: defaultTarget.spatial
1369
+ } : imageTarget : null,
1370
+ source
1371
+ ];
1372
+ }
1373
+ const emptyActions = {
1374
+ makeChoice: () => {
1375
+ }
1376
+ };
1377
+ const unknownResponse = { type: "unknown" };
1378
+ const unsupportedStrategy = (reason) => {
1379
+ return { type: "unknown", reason, annotations: { pages: [] } };
1380
+ };
1381
+ const emptyStrategy = (width, height) => {
1382
+ return { type: "empty", width, height, annotations: { pages: [] }, image: null, images: [] };
1383
+ };
1384
+ function getMeta$1(state, resourceId) {
1385
+ var _a;
1386
+ const resourceMeta = (_a = state == null ? void 0 : state.iiif) == null ? void 0 : _a.meta[resourceId];
1387
+ if (!resourceMeta) {
1388
+ return null;
1389
+ }
1390
+ return resourceMeta.annotationPageManager;
1391
+ }
1392
+ function useEnabledAnnotationPageIds(resourceId, availablePageIds) {
1393
+ return useVaultSelector((state) => {
1394
+ const pageIds = [];
1395
+ if (!resourceId) {
1396
+ return pageIds;
1397
+ }
1398
+ const allAnnotationListIds = Object.keys(state.iiif.entities.AnnotationPage);
1399
+ for (const annotationListId of allAnnotationListIds) {
1400
+ if (!availablePageIds || availablePageIds.indexOf(annotationListId) !== -1) {
1401
+ const annotationListMeta = getMeta$1(state, annotationListId);
1402
+ if (annotationListMeta && annotationListMeta.views && annotationListMeta.views[resourceId]) {
1403
+ pageIds.push(annotationListId);
1404
+ }
1405
+ }
1406
+ }
1407
+ return pageIds;
1408
+ }, [resourceId, availablePageIds]);
1409
+ }
1410
+ function flattenAnnotationPageIds({
1411
+ canvas,
1412
+ manifest,
1413
+ all,
1414
+ canvases
1415
+ }) {
1416
+ const foundIds = [];
1417
+ if (manifest) {
1418
+ for (const page of manifest.annotations) {
1419
+ if (foundIds.indexOf(page.id) === -1) {
1420
+ foundIds.push(page.id);
1421
+ }
1422
+ }
1423
+ }
1424
+ if (all) {
1425
+ if (canvases && canvases.length) {
1426
+ for (const canvas_ of canvases) {
1427
+ for (const page of canvas_.annotations) {
1428
+ if (foundIds.indexOf(page.id) === -1) {
1429
+ foundIds.push(page.id);
1430
+ }
1431
+ }
1432
+ }
1433
+ }
1434
+ } else if (canvas) {
1435
+ for (const page of canvas.annotations) {
1436
+ if (foundIds.indexOf(page.id) === -1) {
1437
+ foundIds.push(page.id);
1438
+ }
1439
+ }
1440
+ }
1441
+ return foundIds;
1442
+ }
1443
+ function getMeta(state, resourceId) {
1444
+ var _a;
1445
+ const resourceMeta = (_a = state == null ? void 0 : state.iiif) == null ? void 0 : _a.meta[resourceId];
1446
+ if (!resourceMeta) {
1447
+ return null;
1448
+ }
1449
+ return resourceMeta.annotationPageManager;
1450
+ }
1451
+ function useAnnotationPageManager(resourceId, options = {}) {
1452
+ const vault = useVault();
1453
+ const manifest = useManifest();
1454
+ const canvas = useCanvas();
1455
+ const canvases = useVisibleCanvases();
1456
+ const availablePageIds = useMemo(() => {
1457
+ return flattenAnnotationPageIds({
1458
+ all: options.all,
1459
+ manifest,
1460
+ canvas,
1461
+ canvases
1462
+ });
1463
+ }, [options.all, canvas, canvases, manifest]);
1464
+ const enabledPageIds = useEnabledAnnotationPageIds(resourceId, options.all ? void 0 : availablePageIds);
1465
+ const setPageDisabled = useCallback((deselectId) => {
1466
+ if (!resourceId) {
1467
+ return;
1468
+ }
1469
+ vault.setMetaValue([deselectId, "annotationPageManager", "views"], (existingResources) => {
1470
+ if (existingResources && !existingResources[resourceId]) {
1471
+ return existingResources;
1472
+ }
1473
+ return __spreadProps(__spreadValues({}, existingResources || {}), {
1474
+ [resourceId]: false
1475
+ });
1476
+ });
1477
+ }, [resourceId, vault]);
1478
+ const setPageEnabled = useCallback((id, opt = {}) => {
1479
+ if (!resourceId) {
1480
+ return;
1481
+ }
1482
+ const state = vault.getState();
1483
+ const toDeselect = [];
1484
+ if (opt == null ? void 0 : opt.deselectOthers) {
1485
+ const allAnnotationListIds = Object.keys(state.iiif.entities.AnnotationPage);
1486
+ for (const annotationPageId of allAnnotationListIds) {
1487
+ const annotationListMeta = getMeta(state, annotationPageId);
1488
+ if (annotationListMeta && annotationListMeta.views && annotationListMeta.views[resourceId]) {
1489
+ toDeselect.push(annotationPageId);
1490
+ }
1491
+ }
1492
+ }
1493
+ for (const deselectId of toDeselect) {
1494
+ setPageDisabled(deselectId);
1495
+ }
1496
+ vault.setMetaValue([id, "annotationPageManager", "views"], (existingResources) => {
1497
+ if (existingResources && existingResources[resourceId]) {
1498
+ return existingResources;
1499
+ }
1500
+ return __spreadProps(__spreadValues({}, existingResources || {}), {
1501
+ [resourceId]: true
1502
+ });
1503
+ });
1504
+ }, [resourceId, setPageDisabled, vault]);
1505
+ return {
1506
+ availablePageIds,
1507
+ enabledPageIds,
1508
+ setPageEnabled,
1509
+ setPageDisabled
1510
+ };
1511
+ }
1512
+ function useResources(ids, type) {
1513
+ return useVaultSelector((state, vault) => vault.get(ids.map((id) => ({ id, type }))), [ids, type]);
1514
+ }
1515
+ const ImageServiceLoaderContext = React__default.createContext(new ImageServiceLoader());
1516
+ function useImageServiceLoader() {
1517
+ return useContext(ImageServiceLoaderContext);
1518
+ }
1519
+ function useLoadImageService() {
1520
+ const loader = useImageServiceLoader();
1521
+ const [imageServiceStatus, setImageServiceStatus] = useState({});
1522
+ const didUnmount = useRef(false);
1523
+ useEffect(() => {
1524
+ return () => {
1525
+ didUnmount.current = true;
1526
+ };
1527
+ }, []);
1528
+ const loadImageService = useCallback((imageService, { height, width }) => {
1529
+ if (imageService) {
1530
+ const imageServiceId = imageService.id || imageService["@id"];
1531
+ const syncLoaded = loader.loadServiceSync({
1532
+ id: imageServiceId,
1533
+ width: imageService.width || width,
1534
+ height: imageService.height || height,
1535
+ source: imageService
1536
+ });
1537
+ if (syncLoaded) {
1538
+ imageService = syncLoaded;
1539
+ } else if (!imageServiceStatus[imageServiceId]) {
1540
+ if (!didUnmount.current) {
1541
+ setImageServiceStatus((r) => {
1542
+ return __spreadProps(__spreadValues({}, r), {
1543
+ [imageServiceId]: "loading"
1544
+ });
1545
+ });
1546
+ }
1547
+ loader.loadService({
1548
+ id: imageServiceId,
1549
+ width: imageService.width || width,
1550
+ height: imageService.height || height
1551
+ }).then(() => {
1552
+ if (!didUnmount.current) {
1553
+ setImageServiceStatus((r) => {
1554
+ return __spreadProps(__spreadValues({}, r), {
1555
+ [imageServiceId]: "done"
1556
+ });
1557
+ });
1558
+ }
1559
+ });
1560
+ }
1561
+ }
1562
+ return imageService;
1563
+ }, [loader, imageServiceStatus]);
1564
+ return [loadImageService, imageServiceStatus];
1565
+ }
1566
+ function usePaintingAnnotations(options = {}) {
1567
+ const canvas = useCanvas(options.canvasId ? { id: options.canvasId } : void 0);
1568
+ return useVaultSelector((state, vault) => {
1569
+ if (!canvas) {
1570
+ return [];
1571
+ }
1572
+ const annotationPages = vault.get(canvas.items);
1573
+ const flatAnnotations = [];
1574
+ for (const page of annotationPages) {
1575
+ flatAnnotations.push(...vault.get(page.items));
1576
+ }
1577
+ return flatAnnotations;
1578
+ }, [canvas]);
1579
+ }
1580
+ function usePaintables(options, deps = []) {
1581
+ const vault = useVault();
1582
+ const paintingAnnotations = usePaintingAnnotations();
1583
+ const [enabledChoices, setEnabledChoices] = useState((options == null ? void 0 : options.defaultChoices) || []);
1584
+ const paintables = useMemo(() => getPaintables(vault, paintingAnnotations, enabledChoices), [vault, paintingAnnotations, enabledChoices, ...deps]);
1585
+ const makeChoice = useCallback((id, { deselectOthers = true, deselect = false } = {}) => {
1586
+ if (paintables.choice) {
1587
+ if (paintables.choice.type !== "single-choice") {
1588
+ throw new Error("Complex choice not supported yet");
1589
+ }
1590
+ setEnabledChoices((prevChoices) => {
1591
+ if (deselect) {
1592
+ const without = prevChoices.filter((e) => e !== id);
1593
+ if (without.length === 0) {
1594
+ const defaultId = paintables.items[0].resource.id;
1595
+ if (defaultId) {
1596
+ return [defaultId];
1597
+ } else {
1598
+ return [];
1599
+ }
1600
+ }
1601
+ return without;
1602
+ }
1603
+ if (deselectOthers) {
1604
+ return [id];
1605
+ }
1606
+ const newChoices = [...prevChoices];
1607
+ if (newChoices.length === 0 && paintables.items.length) {
1608
+ const defaultId = paintables.items[0].resource.id;
1609
+ if (defaultId) {
1610
+ newChoices.push(defaultId);
1611
+ }
1612
+ }
1613
+ if (prevChoices.indexOf(id) !== -1) {
1614
+ return prevChoices;
1615
+ }
1616
+ return [...prevChoices, id];
1617
+ });
1618
+ }
1619
+ }, [paintables.choice]);
1620
+ const actions = { makeChoice };
1621
+ return [paintables, actions];
1622
+ }
1623
+ function getImageStrategy(canvas, paintables, loadImageService) {
1624
+ const imageTypes = [];
1625
+ for (const singleImage of paintables.items) {
1626
+ const resource = singleImage.resource && singleImage.resource.type === "SpecificResource" ? singleImage.resource.source : singleImage.resource;
1627
+ if (!resource.id) {
1628
+ return unsupportedStrategy("No resource Identifier");
1629
+ }
1630
+ let imageService = void 0;
1631
+ if (resource.service) {
1632
+ const imageServices = getImageServices(resource);
1633
+ if (imageServices[0]) {
1634
+ imageService = loadImageService(imageServices[0], canvas);
1635
+ }
1636
+ }
1637
+ const defaultTarget = {
1638
+ type: "BoxSelector",
1639
+ spatial: {
1640
+ x: 0,
1641
+ y: 0,
1642
+ width: canvas.width,
1643
+ height: canvas.height
1644
+ }
1645
+ };
1646
+ const [target, source] = getParsedTargetSelector(canvas, singleImage.target);
1647
+ if (source.id !== canvas.id) {
1648
+ continue;
1649
+ }
1650
+ const defaultImageSelector = {
1651
+ type: "BoxSelector",
1652
+ spatial: {
1653
+ x: 0,
1654
+ y: 0,
1655
+ width: canvas.width,
1656
+ height: canvas.height
1657
+ }
1658
+ };
1659
+ const imageSelector = singleImage.resource.type === "SpecificResource" ? expandTarget(singleImage.resource) : null;
1660
+ const selector = imageSelector && imageSelector.selector && (imageSelector.selector.type === "BoxSelector" || imageSelector.selector.type === "TemporalBoxSelector") ? {
1661
+ type: "BoxSelector",
1662
+ spatial: {
1663
+ x: imageSelector.selector.spatial.x,
1664
+ y: imageSelector.selector.spatial.y,
1665
+ width: imageSelector.selector.spatial.width,
1666
+ height: imageSelector.selector.spatial.height
1667
+ }
1668
+ } : defaultImageSelector;
1669
+ if (imageService && !imageService.id) {
1670
+ imageService.id = imageService["@id"];
1671
+ }
1672
+ const imageType = {
1673
+ id: resource.id,
1674
+ type: "Image",
1675
+ annotationId: singleImage.annotationId,
1676
+ width: target ? resource.width : canvas.width,
1677
+ height: target ? resource.height : canvas.height,
1678
+ service: imageService,
1679
+ sizes: imageService && imageService.sizes ? imageService.sizes : resource.width && resource.height ? [{ width: resource.width, height: resource.height }] : [],
1680
+ target: target && target.type !== "PointSelector" ? target : defaultTarget,
1681
+ selector
1682
+ };
1683
+ imageTypes.push(imageType);
1684
+ }
1685
+ return {
1686
+ type: "images",
1687
+ image: imageTypes[0],
1688
+ images: imageTypes,
1689
+ choice: paintables.choice
1690
+ };
1691
+ }
1692
+ const supportedFormats = ["model/gltf-binary"];
1693
+ function get3dStrategy(canvas, paintables) {
1694
+ const first = paintables.items[0];
1695
+ const resource = first.resource;
1696
+ if (!resource.format) {
1697
+ return unsupportedStrategy("Unknown format");
1698
+ }
1699
+ if (supportedFormats.indexOf(resource.format) === -1) {
1700
+ return unsupportedStrategy(`3D format: ${resource.format} is unsupported`);
1701
+ }
1702
+ return {
1703
+ type: "3d-model",
1704
+ model: resource
1705
+ };
1706
+ }
1707
+ function getAudioStrategy(canvas, paintables) {
1708
+ var _a;
1709
+ if (!canvas.duration) {
1710
+ return unsupportedStrategy("No duration on canvas");
1711
+ }
1712
+ if (paintables.items.length > 1) {
1713
+ return unsupportedStrategy("Only one audio source supported");
1714
+ }
1715
+ const audioResource = (_a = paintables.items[0]) == null ? void 0 : _a.resource;
1716
+ if (!audioResource) {
1717
+ return unsupportedStrategy("Unknown audio");
1718
+ }
1719
+ if (!audioResource.format) {
1720
+ return unsupportedStrategy("Audio does not have format");
1721
+ }
1722
+ return {
1723
+ type: "media",
1724
+ media: {
1725
+ annotationId: paintables.items[0].annotationId,
1726
+ duration: canvas.duration,
1727
+ url: audioResource.id,
1728
+ type: "Sound",
1729
+ target: {
1730
+ type: "TemporalSelector",
1731
+ temporal: {
1732
+ startTime: 0,
1733
+ endTime: canvas.duration
1734
+ }
1735
+ },
1736
+ format: audioResource.format,
1737
+ selector: {
1738
+ type: "TemporalSelector",
1739
+ temporal: {
1740
+ startTime: 0,
1741
+ endTime: canvas.duration
1742
+ }
1743
+ }
1744
+ },
1745
+ annotations: {
1746
+ pages: []
1747
+ }
1748
+ };
1749
+ }
1750
+ function getVideoStrategy(canvas, paintables) {
1751
+ var _a;
1752
+ const videoPaintables = paintables.items.filter((t) => t.type === "video");
1753
+ if (!canvas.duration) {
1754
+ return unsupportedStrategy("No duration on canvas");
1755
+ }
1756
+ if (videoPaintables.length > 1) {
1757
+ return unsupportedStrategy("Only one video source supported");
1758
+ }
1759
+ const audioResource = (_a = videoPaintables[0]) == null ? void 0 : _a.resource;
1760
+ if (!audioResource) {
1761
+ return unsupportedStrategy("Unknown video");
1762
+ }
1763
+ if (!audioResource.format) {
1764
+ return unsupportedStrategy("Video does not have format");
1765
+ }
1766
+ return {
1767
+ type: "media",
1768
+ media: {
1769
+ annotationId: paintables.items[0].annotationId,
1770
+ duration: canvas.duration,
1771
+ url: audioResource.id,
1772
+ type: "Video",
1773
+ items: [],
1774
+ target: {
1775
+ type: "TemporalSelector",
1776
+ temporal: {
1777
+ startTime: 0,
1778
+ endTime: canvas.duration
1779
+ }
1780
+ },
1781
+ format: audioResource.format,
1782
+ selector: {
1783
+ type: "TemporalSelector",
1784
+ temporal: {
1785
+ startTime: 0,
1786
+ endTime: canvas.duration
1787
+ }
1788
+ }
1789
+ },
1790
+ annotations: {
1791
+ pages: []
1792
+ }
1793
+ };
1794
+ }
1795
+ function parseType(item, languageMap = {}, lang) {
1796
+ const language = item.language || lang || "none";
1797
+ switch (item.type) {
1798
+ case "TextualBody": {
1799
+ if (typeof item.value !== "undefined") {
1800
+ languageMap[language] = item.value;
1801
+ }
1802
+ break;
1803
+ }
1804
+ case "List":
1805
+ case "Composite":
1806
+ case "Choice": {
1807
+ if (item.items) {
1808
+ item.items.forEach((inner) => parseType(inner, languageMap, language));
1809
+ }
1810
+ }
1811
+ }
1812
+ return languageMap;
1813
+ }
1814
+ function getTextualContentStrategy(canvas, paintables) {
1815
+ const items = [];
1816
+ paintables.items.forEach((item) => {
1817
+ if (item.resource) {
1818
+ const [target] = getParsedTargetSelector(canvas, item.target);
1819
+ items.push({ annotationId: item.annotationId, text: parseType(item.resource), target });
1820
+ }
1821
+ });
1822
+ return {
1823
+ type: "textual-content",
1824
+ items
1825
+ };
1826
+ }
1827
+ function useRenderingStrategy(options) {
1828
+ const manifest = useManifest();
1829
+ const canvas = useCanvas();
1830
+ const vault = useVault();
1831
+ const [loadImageService, imageServiceStatus] = useLoadImageService();
1832
+ const { enabledPageIds } = useAnnotationPageManager((options == null ? void 0 : options.annotationPageManagerId) || (manifest == null ? void 0 : manifest.id) || (canvas == null ? void 0 : canvas.id), {
1833
+ all: false
1834
+ });
1835
+ const enabledPages = useResources(enabledPageIds, "AnnotationPage");
1836
+ const supports = (options == null ? void 0 : options.strategies) || [
1837
+ "empty",
1838
+ "images",
1839
+ "media",
1840
+ "textual-content",
1841
+ "complex-timeline"
1842
+ ];
1843
+ const [paintables, actions] = usePaintables(options, [imageServiceStatus]);
1844
+ const strategy = useMemo(() => {
1845
+ if (!canvas) {
1846
+ return unknownResponse;
1847
+ }
1848
+ if (paintables.types.length === 0) {
1849
+ if (supports.indexOf("empty") !== -1) {
1850
+ return emptyStrategy(canvas.width, canvas.height);
1851
+ }
1852
+ return unknownResponse;
1853
+ }
1854
+ if (paintables.types.length !== 1) {
1855
+ if (paintables.types.length === 2 && paintables.types.indexOf("text") !== -1) {
1856
+ paintables.types = paintables.types.filter((t) => t !== "text");
1857
+ } else {
1858
+ if (supports.indexOf("complex-timeline") === -1) {
1859
+ return unsupportedStrategy("Complex timeline not supported");
1860
+ }
1861
+ return unsupportedStrategy("ComplexTimelineStrategy not yet supported");
1862
+ }
1863
+ }
1864
+ const mainType = paintables.types[0];
1865
+ if (mainType === "image") {
1866
+ if (supports.indexOf("images") === -1) {
1867
+ return unsupportedStrategy("Image not supported");
1868
+ }
1869
+ return getImageStrategy(canvas, paintables, loadImageService);
1870
+ }
1871
+ if (mainType === "Model" || mainType === "model") {
1872
+ if (supports.indexOf("3d-model") === -1) {
1873
+ return unsupportedStrategy("3D not supported");
1874
+ }
1875
+ return get3dStrategy(canvas, paintables);
1876
+ }
1877
+ if (mainType === "textualbody") {
1878
+ if (supports.indexOf("textual-content") === -1) {
1879
+ return unsupportedStrategy("Textual content not supported");
1880
+ }
1881
+ return getTextualContentStrategy(canvas, paintables);
1882
+ }
1883
+ if (mainType === "sound" || mainType === "audio") {
1884
+ if (supports.indexOf("media") === -1) {
1885
+ return unsupportedStrategy("Media not supported");
1886
+ }
1887
+ return getAudioStrategy(canvas, paintables);
1888
+ }
1889
+ if (mainType === "video") {
1890
+ if (supports.indexOf("media") === -1) {
1891
+ return unsupportedStrategy("Media not supported");
1892
+ }
1893
+ return getVideoStrategy(canvas, paintables);
1894
+ }
1895
+ return unknownResponse;
1896
+ }, [canvas, paintables, vault, actions.makeChoice]);
1897
+ return useMemo(() => {
1898
+ if (strategy.type === "unknown") {
1899
+ return [strategy, emptyActions];
1900
+ }
1901
+ return [
1902
+ __spreadProps(__spreadValues({}, strategy), {
1903
+ annotations: { pages: enabledPages }
1904
+ }),
1905
+ actions
1906
+ ];
1907
+ }, [strategy, enabledPages]);
1908
+ }
1909
+ const useVaultEffect = (callback, deps = []) => {
1910
+ const vault = useVault();
1911
+ useEffect(() => {
1912
+ callback(vault);
1913
+ }, [vault, ...deps]);
1914
+ };
1915
+ function createThumbnailHelper(vault, dependencies = {}) {
1916
+ const imageServiceLoader = dependencies.imageServiceLoader || new ImageServiceLoader();
1917
+ async function getBestThumbnailAtSize(input, request, dereference, candidates = [], dimensions) {
1918
+ if (typeof input === "string") {
1919
+ return { best: getFixedSizeFromImage(input), fallback: [], log: [] };
1920
+ }
1921
+ const fullInput = vault.get(input);
1922
+ if (typeof fullInput === "string") {
1923
+ return { best: getFixedSizeFromImage(fullInput), fallback: [], log: [] };
1924
+ }
1925
+ switch (fullInput.type) {
1926
+ case "Annotation": {
1927
+ const contentResources = fullInput.body;
1928
+ const firstContentResources = vault.get(contentResources[0]);
1929
+ if (dimensions && !firstContentResources.width) {
1930
+ firstContentResources.width = dimensions.width;
1931
+ firstContentResources.height = dimensions.height;
1932
+ }
1933
+ return await imageServiceLoader.getThumbnailFromResource(firstContentResources, request, dereference, candidates);
1934
+ }
1935
+ case "Canvas": {
1936
+ const canvas = fullInput;
1937
+ if (canvas.thumbnail && canvas.thumbnail.length) {
1938
+ const thumbnail = vault.get(canvas.thumbnail[0]);
1939
+ const potentialThumbnails = await imageServiceLoader.getImageCandidates(thumbnail, dereference);
1940
+ if (potentialThumbnails && potentialThumbnails.length) {
1941
+ candidates.push(...potentialThumbnails);
1942
+ }
1943
+ }
1944
+ return getBestThumbnailAtSize(canvas.items[0], request, dereference, candidates, {
1945
+ width: canvas.width,
1946
+ height: canvas.height
1947
+ });
1948
+ }
1949
+ case "AnnotationPage": {
1950
+ const annotationPage = fullInput;
1951
+ return getBestThumbnailAtSize(annotationPage.items[0], request, dereference, candidates, dimensions);
1952
+ }
1953
+ case "Choice": {
1954
+ const choice = fullInput;
1955
+ return getBestThumbnailAtSize(choice.items[0], request, dereference, candidates, dimensions);
1956
+ }
1957
+ case "Collection": {
1958
+ const collection = fullInput;
1959
+ const firstManifest = collection.items[0];
1960
+ return getBestThumbnailAtSize(firstManifest, request, dereference, candidates, dimensions);
1961
+ }
1962
+ case "Manifest": {
1963
+ const manifest = fullInput;
1964
+ const firstCanvas = manifest.items[0];
1965
+ return getBestThumbnailAtSize(firstCanvas, request, dereference, candidates, dimensions);
1966
+ }
1967
+ case "SpecificResource":
1968
+ case "Image":
1969
+ case "Dataset":
1970
+ case "Sound":
1971
+ case "Text":
1972
+ case "TextualBody":
1973
+ case "Video":
1974
+ if (dimensions && !fullInput.width) {
1975
+ fullInput.width = dimensions.width;
1976
+ fullInput.height = dimensions.height;
1977
+ }
1978
+ return imageServiceLoader.getThumbnailFromResource(fullInput, request, dereference, candidates);
1979
+ case "Service":
1980
+ case "Range":
1981
+ case "AnnotationCollection":
1982
+ case "CanvasReference":
1983
+ case "ContentResource":
1984
+ return { best: void 0, fallback: [], log: [] };
1985
+ }
1986
+ return { best: void 0, fallback: [], log: [] };
1987
+ }
1988
+ return {
1989
+ getBestThumbnailAtSize
1990
+ };
1991
+ }
1992
+ function useThumbnail(request, dereference, { canvasId, manifestId } = {}) {
1993
+ const vault = useVault();
1994
+ const loader = useImageServiceLoader();
1995
+ const helper = useMemo(() => createThumbnailHelper(vault, { imageServiceLoader: loader }), [vault, loader]);
1996
+ const [thumbnail, setThumbnail] = useState();
1997
+ const manifest = useManifest(manifestId ? { id: manifestId } : void 0);
1998
+ const canvas = useCanvas(canvasId ? { id: canvasId } : void 0);
1999
+ const subject = canvas ? canvas : manifest;
2000
+ const didUnmount = useRef(false);
2001
+ useEffect(() => {
2002
+ didUnmount.current = false;
2003
+ return () => {
2004
+ didUnmount.current = true;
2005
+ };
2006
+ }, []);
2007
+ if (!subject) {
2008
+ throw new Error("Must be called under a manifest or canvas context.");
2009
+ }
2010
+ useVaultEffect((v) => {
2011
+ helper.getBestThumbnailAtSize(subject, request, dereference).then((thumb) => {
2012
+ if (thumb.best && !didUnmount.current) {
2013
+ setThumbnail(thumb.best);
2014
+ }
2015
+ });
2016
+ }, [subject]);
2017
+ return thumbnail;
2018
+ }
2019
+ function getDefaultState(duration) {
2020
+ return { isMuted: false, playRequested: false, isPlaying: false, isFinished: false, volume: 100, duration };
2021
+ }
2022
+ function reducer(state, action) {
2023
+ switch (action.type) {
2024
+ case "FINISHED":
2025
+ return __spreadProps(__spreadValues({}, state), { isFinished: true, isPlaying: false, playRequested: false });
2026
+ case "PLAY_PAUSE":
2027
+ return __spreadProps(__spreadValues({}, state), { isFinished: false, isPlaying: !state.isPlaying });
2028
+ case "PLAY_REQUESTED":
2029
+ return __spreadProps(__spreadValues({}, state), { isFinished: false, playRequested: true });
2030
+ case "PAUSE":
2031
+ return __spreadProps(__spreadValues({}, state), { isPlaying: false });
2032
+ case "PLAY":
2033
+ return __spreadProps(__spreadValues({}, state), { isFinished: false, playRequested: false, isPlaying: true });
2034
+ case "MUTE":
2035
+ return __spreadProps(__spreadValues({}, state), { isMuted: true });
2036
+ case "SET_VOLUME":
2037
+ return __spreadProps(__spreadValues({}, state), { volume: action.volume, isMuted: action.volume === 0 });
2038
+ case "TOGGLE_MUTE":
2039
+ return __spreadProps(__spreadValues({}, state), { isMuted: !state.isMuted });
2040
+ case "UNMUTE":
2041
+ return __spreadProps(__spreadValues({}, state), { isMuted: false });
2042
+ }
2043
+ return state;
2044
+ }
2045
+ function formatTime(time) {
2046
+ const seconds = Math.round(time);
2047
+ return `${Math.floor(seconds / 60)}:${`${seconds % 60}`.padStart(2, "0")}`;
2048
+ }
2049
+ function useSimpleMediaPlayer(props) {
2050
+ const [state, dispatch] = useReducer(reducer, getDefaultState(props.duration));
2051
+ const media = useRef(null);
2052
+ const currentTime = useRef(null);
2053
+ const progress = useRef(null);
2054
+ const _isMuted = useRef(false);
2055
+ const _updateCurrentTime = useCallback(() => {
2056
+ if (currentTime.current && media.current) {
2057
+ currentTime.current.innerHTML = formatTime(media.current.currentTime);
2058
+ if (progress.current) {
2059
+ progress.current.style.width = `${media.current.currentTime / props.duration * 100}%`;
2060
+ }
2061
+ if (_isMuted.current !== media.current.muted) {
2062
+ _isMuted.current = media.current.muted;
2063
+ dispatch(media.current.muted ? { type: "MUTE" } : { type: "UNMUTE" });
2064
+ }
2065
+ }
2066
+ }, [props.duration]);
2067
+ const play = useCallback(() => {
2068
+ if (media.current) {
2069
+ dispatch({ type: "PLAY_REQUESTED" });
2070
+ media.current.play().then(() => {
2071
+ dispatch({ type: "PLAY" });
2072
+ });
2073
+ _updateCurrentTime();
2074
+ }
2075
+ }, [_updateCurrentTime]);
2076
+ const playPause = useCallback(() => {
2077
+ if (media.current) {
2078
+ if (media.current.duration > 0 && media.current.paused) {
2079
+ play();
2080
+ } else {
2081
+ pause();
2082
+ }
2083
+ }
2084
+ }, [_updateCurrentTime]);
2085
+ const pause = useCallback(() => {
2086
+ if (media.current) {
2087
+ media.current.pause();
2088
+ dispatch({ type: "PAUSE" });
2089
+ _updateCurrentTime();
2090
+ }
2091
+ }, [_updateCurrentTime]);
2092
+ const toggleMute = useCallback(() => {
2093
+ if (media.current) {
2094
+ media.current.muted = !media.current.muted;
2095
+ dispatch(media.current.muted ? { type: "MUTE" } : { type: "UNMUTE" });
2096
+ }
2097
+ }, []);
2098
+ const mute = useCallback(() => {
2099
+ if (media.current) {
2100
+ media.current.muted = true;
2101
+ dispatch({ type: "MUTE" });
2102
+ }
2103
+ }, []);
2104
+ const unmute = useCallback(() => {
2105
+ if (media.current) {
2106
+ media.current.muted = false;
2107
+ dispatch({ type: "UNMUTE" });
2108
+ }
2109
+ }, []);
2110
+ const setVolume = useCallback((newVolume) => {
2111
+ if (media.current) {
2112
+ media.current.muted = false;
2113
+ media.current.volume = newVolume / 100;
2114
+ dispatch({ type: "SET_VOLUME", volume: newVolume });
2115
+ }
2116
+ }, []);
2117
+ const setDurationPercent = useCallback((percent) => {
2118
+ if (media.current) {
2119
+ media.current.currentTime = Math.max(0, Math.min(percent * props.duration, props.duration));
2120
+ _updateCurrentTime();
2121
+ }
2122
+ }, []);
2123
+ const setTime = useCallback((time) => {
2124
+ if (media.current) {
2125
+ media.current.currentTime = Math.max(0, Math.min(time, props.duration));
2126
+ _updateCurrentTime();
2127
+ }
2128
+ }, []);
2129
+ useEffect(() => {
2130
+ const interval = setInterval(() => {
2131
+ _updateCurrentTime();
2132
+ }, 350);
2133
+ return () => clearInterval(interval);
2134
+ }, [_updateCurrentTime, props.duration]);
2135
+ useEffect(() => {
2136
+ const ended = () => {
2137
+ dispatch({ type: "FINISHED" });
2138
+ };
2139
+ const _media = media.current;
2140
+ _media == null ? void 0 : _media.addEventListener("ended", ended);
2141
+ return () => _media == null ? void 0 : _media.removeEventListener("ended", ended);
2142
+ }, []);
2143
+ return [
2144
+ { element: media, currentTime, progress },
2145
+ state,
2146
+ {
2147
+ play,
2148
+ pause,
2149
+ playPause,
2150
+ mute,
2151
+ unmute,
2152
+ toggleMute,
2153
+ setVolume,
2154
+ setDurationPercent,
2155
+ setTime
2156
+ }
2157
+ ];
2158
+ }
2159
+ const MediaReactContextState = createContext(null);
2160
+ const MediaReactContextActions = createContext(null);
2161
+ const MediaReactContextElements = createContext(null);
2162
+ function useMediaState() {
2163
+ const ctx = useContext(MediaReactContextState);
2164
+ if (!ctx) {
2165
+ throw new Error("Ctx not found");
2166
+ }
2167
+ return ctx;
2168
+ }
2169
+ function useMediaActions() {
2170
+ const ctx = useContext(MediaReactContextActions);
2171
+ if (!ctx) {
2172
+ throw new Error("Ctx not found");
2173
+ }
2174
+ return ctx;
2175
+ }
2176
+ function useMediaElements() {
2177
+ const ctx = useContext(MediaReactContextElements);
2178
+ if (!ctx) {
2179
+ throw new Error("Ctx not found");
2180
+ }
2181
+ return ctx;
2182
+ }
2183
+ function MediaPlayerProvider({
2184
+ actions,
2185
+ state,
2186
+ children,
2187
+ currentTime,
2188
+ progress,
2189
+ element
2190
+ }) {
2191
+ return /* @__PURE__ */ jsx(MediaReactContextElements.Provider, {
2192
+ value: {
2193
+ currentTime,
2194
+ progress,
2195
+ element
2196
+ },
2197
+ children: /* @__PURE__ */ jsx(MediaReactContextActions.Provider, {
2198
+ value: actions,
2199
+ children: /* @__PURE__ */ jsx(MediaReactContextState.Provider, {
2200
+ value: state,
2201
+ children
2202
+ })
2203
+ })
2204
+ });
2205
+ }
2206
+ function Audio({
2207
+ media,
2208
+ children
2209
+ }) {
2210
+ const [{
2211
+ element,
2212
+ currentTime,
2213
+ progress
2214
+ }, state, actions] = useSimpleMediaPlayer({
2215
+ duration: media.duration
2216
+ });
2217
+ return /* @__PURE__ */ jsx(Fragment$1, {
2218
+ children: /* @__PURE__ */ jsx(CanvasPortal, {
2219
+ children: /* @__PURE__ */ jsxs(MediaPlayerProvider, {
2220
+ state,
2221
+ actions,
2222
+ currentTime,
2223
+ progress,
2224
+ element,
2225
+ children: [/* @__PURE__ */ jsx("audio", {
2226
+ ref: element,
2227
+ src: media.url
2228
+ }), children]
2229
+ })
2230
+ })
2231
+ });
2232
+ }
2233
+ function Video({
2234
+ media,
2235
+ children
2236
+ }) {
2237
+ const [{
2238
+ element,
2239
+ currentTime,
2240
+ progress
2241
+ }, state, actions] = useSimpleMediaPlayer({
2242
+ duration: media.duration
2243
+ });
2244
+ const Component = "div";
2245
+ return /* @__PURE__ */ jsxs(Fragment$1, {
2246
+ children: [/* @__PURE__ */ jsxs(CanvasPortal, {
2247
+ overlay: true,
2248
+ children: [/* @__PURE__ */ jsx("style", {
2249
+ children: `
2250
+ .video-container {
2251
+ position: absolute;
2252
+ top: 0;
2253
+ bottom: 0;
2254
+ left: 0;
2255
+ right: 0;
2256
+ background: #000;
2257
+ z-index: 13;
2258
+ display: flex;
2259
+ justify-content: center;
2260
+ pointer-events: visible;
2261
+ }
2262
+ `
2263
+ }), /* @__PURE__ */ jsx(Component, {
2264
+ className: "video-container",
2265
+ part: "video-container",
2266
+ onClick: () => actions.playPause(),
2267
+ children: /* @__PURE__ */ jsx("video", {
2268
+ ref: element,
2269
+ src: media.url,
2270
+ style: {
2271
+ width: "100%",
2272
+ objectFit: "contain"
2273
+ }
2274
+ })
2275
+ })]
2276
+ }), /* @__PURE__ */ jsx(CanvasPortal, {
2277
+ children: /* @__PURE__ */ jsx(MediaPlayerProvider, {
2278
+ state,
2279
+ actions,
2280
+ currentTime,
2281
+ progress,
2282
+ element,
2283
+ children
2284
+ })
2285
+ })]
2286
+ });
2287
+ }
2288
+ function Model({
2289
+ model
2290
+ }) {
2291
+ return /* @__PURE__ */ jsxs(CanvasPortal, {
2292
+ overlay: true,
2293
+ children: [/* @__PURE__ */ jsx("style", {
2294
+ children: `
2295
+ .model-container {
2296
+ position: absolute;
2297
+ top: 0;
2298
+ bottom: 0;
2299
+ left: 0;
2300
+ right: 0;
2301
+ background: #000;
2302
+ z-index: 13;
2303
+ display: flex;
2304
+ justify-content: center;
2305
+ pointer-events: visible;
2306
+ }
2307
+ `
2308
+ }), /* @__PURE__ */ jsx("div", {
2309
+ className: "model-container",
2310
+ children: /* @__PURE__ */ jsx("model-viewer", {
2311
+ "interaction-prompt": "none",
2312
+ style: {
2313
+ width: "100%",
2314
+ height: "100%"
2315
+ },
2316
+ "camera-controls": "",
2317
+ "ar-status": "not-presenting",
2318
+ src: model.id
2319
+ })
2320
+ })]
2321
+ });
2322
+ }
2323
+ function CanvasBackground({
2324
+ style
2325
+ }) {
2326
+ const canvas = useCanvas();
2327
+ if (!canvas || !canvas.height || !canvas.width) {
2328
+ return null;
2329
+ }
2330
+ return /* @__PURE__ */ jsx("box", {
2331
+ interactive: false,
2332
+ target: {
2333
+ x: 0,
2334
+ y: 0,
2335
+ width: canvas.width,
2336
+ height: canvas.height
2337
+ },
2338
+ style
2339
+ });
2340
+ }
2341
+ var __defProp2 = Object.defineProperty;
2342
+ var __defProps2 = Object.defineProperties;
2343
+ var __getOwnPropDescs2 = Object.getOwnPropertyDescriptors;
2344
+ var __getOwnPropSymbols2 = Object.getOwnPropertySymbols;
2345
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2346
+ var __propIsEnum2 = Object.prototype.propertyIsEnumerable;
2347
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, {
2348
+ enumerable: true,
2349
+ configurable: true,
2350
+ writable: true,
2351
+ value
2352
+ }) : obj[key] = value;
2353
+ var __spreadValues2 = (a, b) => {
2354
+ for (var prop in b || (b = {}))
2355
+ if (__hasOwnProp2.call(b, prop))
2356
+ __defNormalProp2(a, prop, b[prop]);
2357
+ if (__getOwnPropSymbols2)
2358
+ for (var prop of __getOwnPropSymbols2(b)) {
2359
+ if (__propIsEnum2.call(b, prop))
2360
+ __defNormalProp2(a, prop, b[prop]);
2361
+ }
2362
+ return a;
2363
+ };
2364
+ var __spreadProps2 = (a, b) => __defProps2(a, __getOwnPropDescs2(b));
2365
+ var __objRest2 = (source, exclude) => {
2366
+ var target = {};
2367
+ for (var prop in source)
2368
+ if (__hasOwnProp2.call(source, prop) && exclude.indexOf(prop) < 0)
2369
+ target[prop] = source[prop];
2370
+ if (source != null && __getOwnPropSymbols2)
2371
+ for (var prop of __getOwnPropSymbols2(source)) {
2372
+ if (exclude.indexOf(prop) < 0 && __propIsEnum2.call(source, prop))
2373
+ target[prop] = source[prop];
2374
+ }
2375
+ return target;
2376
+ };
2377
+ function _defineProperty(obj, key, value) {
2378
+ if (key in obj) {
2379
+ Object.defineProperty(obj, key, {
2380
+ value,
2381
+ enumerable: true,
2382
+ configurable: true,
2383
+ writable: true
2384
+ });
2385
+ } else {
2386
+ obj[key] = value;
2387
+ }
2388
+ return obj;
2389
+ }
2390
+ function _classCallCheck(instance, Constructor) {
2391
+ if (!(instance instanceof Constructor)) {
2392
+ throw new TypeError("Cannot call a class as a function");
2393
+ }
2394
+ }
2395
+ function _defineProperties(target, props) {
2396
+ for (var i = 0; i < props.length; i++) {
2397
+ var descriptor = props[i];
2398
+ descriptor.enumerable = descriptor.enumerable || false;
2399
+ descriptor.configurable = true;
2400
+ if ("value" in descriptor)
2401
+ descriptor.writable = true;
2402
+ Object.defineProperty(target, descriptor.key, descriptor);
2403
+ }
2404
+ }
2405
+ function _createClass(Constructor, protoProps, staticProps) {
2406
+ if (protoProps)
2407
+ _defineProperties(Constructor.prototype, protoProps);
2408
+ if (staticProps)
2409
+ _defineProperties(Constructor, staticProps);
2410
+ Object.defineProperty(Constructor, "prototype", {
2411
+ writable: false
2412
+ });
2413
+ return Constructor;
2414
+ }
2415
+ var defaultOptions = {
2416
+ bindI18n: "languageChanged",
2417
+ bindI18nStore: "",
2418
+ transEmptyNodeValue: "",
2419
+ transSupportBasicHtmlNodes: true,
2420
+ transWrapTextNodes: "",
2421
+ transKeepBasicHtmlNodesFor: ["br", "strong", "i", "p"],
2422
+ useSuspense: true
2423
+ };
2424
+ var i18nInstance;
2425
+ var I18nContext = React__default.createContext();
2426
+ function getDefaults() {
2427
+ return defaultOptions;
2428
+ }
2429
+ var ReportNamespaces = function() {
2430
+ function ReportNamespaces2() {
2431
+ _classCallCheck(this, ReportNamespaces2);
2432
+ this.usedNamespaces = {};
2433
+ }
2434
+ _createClass(ReportNamespaces2, [{
2435
+ key: "addUsedNamespaces",
2436
+ value: function addUsedNamespaces(namespaces) {
2437
+ var _this = this;
2438
+ namespaces.forEach(function(ns) {
2439
+ if (!_this.usedNamespaces[ns])
2440
+ _this.usedNamespaces[ns] = true;
2441
+ });
2442
+ }
2443
+ }, {
2444
+ key: "getUsedNamespaces",
2445
+ value: function getUsedNamespaces() {
2446
+ return Object.keys(this.usedNamespaces);
2447
+ }
2448
+ }]);
2449
+ return ReportNamespaces2;
2450
+ }();
2451
+ function getI18n() {
2452
+ return i18nInstance;
2453
+ }
2454
+ function warn() {
2455
+ if (console && console.warn) {
2456
+ var _console;
2457
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2458
+ args[_key] = arguments[_key];
2459
+ }
2460
+ if (typeof args[0] === "string")
2461
+ args[0] = "react-i18next:: ".concat(args[0]);
2462
+ (_console = console).warn.apply(_console, args);
2463
+ }
2464
+ }
2465
+ var alreadyWarned = {};
2466
+ function warnOnce() {
2467
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
2468
+ args[_key2] = arguments[_key2];
2469
+ }
2470
+ if (typeof args[0] === "string" && alreadyWarned[args[0]])
2471
+ return;
2472
+ if (typeof args[0] === "string")
2473
+ alreadyWarned[args[0]] = new Date();
2474
+ warn.apply(void 0, args);
2475
+ }
2476
+ function loadNamespaces(i18n, ns, cb) {
2477
+ i18n.loadNamespaces(ns, function() {
2478
+ if (i18n.isInitialized) {
2479
+ cb();
2480
+ } else {
2481
+ var initialized = function initialized2() {
2482
+ setTimeout(function() {
2483
+ i18n.off("initialized", initialized2);
2484
+ }, 0);
2485
+ cb();
2486
+ };
2487
+ i18n.on("initialized", initialized);
2488
+ }
2489
+ });
2490
+ }
2491
+ function hasLoadedNamespace(ns, i18n) {
2492
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
2493
+ if (!i18n.languages || !i18n.languages.length) {
2494
+ warnOnce("i18n.languages were undefined or empty", i18n.languages);
2495
+ return true;
2496
+ }
2497
+ var lng = i18n.languages[0];
2498
+ var fallbackLng = i18n.options ? i18n.options.fallbackLng : false;
2499
+ var lastLng = i18n.languages[i18n.languages.length - 1];
2500
+ if (lng.toLowerCase() === "cimode")
2501
+ return true;
2502
+ var loadNotPending = function loadNotPending2(l, n) {
2503
+ var loadState = i18n.services.backendConnector.state["".concat(l, "|").concat(n)];
2504
+ return loadState === -1 || loadState === 2;
2505
+ };
2506
+ if (options.bindI18n && options.bindI18n.indexOf("languageChanging") > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns))
2507
+ return false;
2508
+ if (i18n.hasResourceBundle(lng, ns))
2509
+ return true;
2510
+ if (!i18n.services.backendConnector.backend)
2511
+ return true;
2512
+ if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns)))
2513
+ return true;
2514
+ return false;
2515
+ }
2516
+ function _arrayWithHoles(arr) {
2517
+ if (Array.isArray(arr))
2518
+ return arr;
2519
+ }
2520
+ function _iterableToArrayLimit(arr, i) {
2521
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
2522
+ if (_i == null)
2523
+ return;
2524
+ var _arr = [];
2525
+ var _n = true;
2526
+ var _d = false;
2527
+ var _s, _e;
2528
+ try {
2529
+ for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
2530
+ _arr.push(_s.value);
2531
+ if (i && _arr.length === i)
2532
+ break;
2533
+ }
2534
+ } catch (err) {
2535
+ _d = true;
2536
+ _e = err;
2537
+ } finally {
2538
+ try {
2539
+ if (!_n && _i["return"] != null)
2540
+ _i["return"]();
2541
+ } finally {
2542
+ if (_d)
2543
+ throw _e;
2544
+ }
2545
+ }
2546
+ return _arr;
2547
+ }
2548
+ function _arrayLikeToArray(arr, len) {
2549
+ if (len == null || len > arr.length)
2550
+ len = arr.length;
2551
+ for (var i = 0, arr2 = new Array(len); i < len; i++) {
2552
+ arr2[i] = arr[i];
2553
+ }
2554
+ return arr2;
2555
+ }
2556
+ function _unsupportedIterableToArray(o, minLen) {
2557
+ if (!o)
2558
+ return;
2559
+ if (typeof o === "string")
2560
+ return _arrayLikeToArray(o, minLen);
2561
+ var n = Object.prototype.toString.call(o).slice(8, -1);
2562
+ if (n === "Object" && o.constructor)
2563
+ n = o.constructor.name;
2564
+ if (n === "Map" || n === "Set")
2565
+ return Array.from(o);
2566
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
2567
+ return _arrayLikeToArray(o, minLen);
2568
+ }
2569
+ function _nonIterableRest() {
2570
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2571
+ }
2572
+ function _slicedToArray(arr, i) {
2573
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
2574
+ }
2575
+ function ownKeys(object, enumerableOnly) {
2576
+ var keys = Object.keys(object);
2577
+ if (Object.getOwnPropertySymbols) {
2578
+ var symbols = Object.getOwnPropertySymbols(object);
2579
+ if (enumerableOnly) {
2580
+ symbols = symbols.filter(function(sym) {
2581
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
2582
+ });
2583
+ }
2584
+ keys.push.apply(keys, symbols);
2585
+ }
2586
+ return keys;
2587
+ }
2588
+ function _objectSpread(target) {
2589
+ for (var i = 1; i < arguments.length; i++) {
2590
+ var source = arguments[i] != null ? arguments[i] : {};
2591
+ if (i % 2) {
2592
+ ownKeys(Object(source), true).forEach(function(key) {
2593
+ _defineProperty(target, key, source[key]);
2594
+ });
2595
+ } else if (Object.getOwnPropertyDescriptors) {
2596
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
2597
+ } else {
2598
+ ownKeys(Object(source)).forEach(function(key) {
2599
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
2600
+ });
2601
+ }
2602
+ }
2603
+ return target;
2604
+ }
2605
+ function useTranslation(ns) {
2606
+ var props = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
2607
+ var i18nFromProps = props.i18n;
2608
+ var _ref = useContext(I18nContext) || {}, i18nFromContext = _ref.i18n, defaultNSFromContext = _ref.defaultNS;
2609
+ var i18n = i18nFromProps || i18nFromContext || getI18n();
2610
+ if (i18n && !i18n.reportNamespaces)
2611
+ i18n.reportNamespaces = new ReportNamespaces();
2612
+ if (!i18n) {
2613
+ warnOnce("You will need to pass in an i18next instance by using initReactI18next");
2614
+ var notReadyT = function notReadyT2(k) {
2615
+ return Array.isArray(k) ? k[k.length - 1] : k;
2616
+ };
2617
+ var retNotReady = [notReadyT, {}, false];
2618
+ retNotReady.t = notReadyT;
2619
+ retNotReady.i18n = {};
2620
+ retNotReady.ready = false;
2621
+ return retNotReady;
2622
+ }
2623
+ if (i18n.options.react && i18n.options.react.wait !== void 0)
2624
+ warnOnce("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");
2625
+ var i18nOptions = _objectSpread(_objectSpread(_objectSpread({}, getDefaults()), i18n.options.react), props);
2626
+ var useSuspense = i18nOptions.useSuspense, keyPrefix = i18nOptions.keyPrefix;
2627
+ var namespaces = ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;
2628
+ namespaces = typeof namespaces === "string" ? [namespaces] : namespaces || ["translation"];
2629
+ if (i18n.reportNamespaces.addUsedNamespaces)
2630
+ i18n.reportNamespaces.addUsedNamespaces(namespaces);
2631
+ var ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(function(n) {
2632
+ return hasLoadedNamespace(n, i18n, i18nOptions);
2633
+ });
2634
+ function getT() {
2635
+ return i18n.getFixedT(null, i18nOptions.nsMode === "fallback" ? namespaces : namespaces[0], keyPrefix);
2636
+ }
2637
+ var _useState = useState(getT), _useState2 = _slicedToArray(_useState, 2), t = _useState2[0], setT = _useState2[1];
2638
+ var isMounted = useRef(true);
2639
+ useEffect(function() {
2640
+ var bindI18n = i18nOptions.bindI18n, bindI18nStore = i18nOptions.bindI18nStore;
2641
+ isMounted.current = true;
2642
+ if (!ready && !useSuspense) {
2643
+ loadNamespaces(i18n, namespaces, function() {
2644
+ if (isMounted.current)
2645
+ setT(getT);
2646
+ });
2647
+ }
2648
+ function boundReset() {
2649
+ if (isMounted.current)
2650
+ setT(getT);
2651
+ }
2652
+ if (bindI18n && i18n)
2653
+ i18n.on(bindI18n, boundReset);
2654
+ if (bindI18nStore && i18n)
2655
+ i18n.store.on(bindI18nStore, boundReset);
2656
+ return function() {
2657
+ isMounted.current = false;
2658
+ if (bindI18n && i18n)
2659
+ bindI18n.split(" ").forEach(function(e) {
2660
+ return i18n.off(e, boundReset);
2661
+ });
2662
+ if (bindI18nStore && i18n)
2663
+ bindI18nStore.split(" ").forEach(function(e) {
2664
+ return i18n.store.off(e, boundReset);
2665
+ });
2666
+ };
2667
+ }, [i18n, namespaces.join()]);
2668
+ var isInitial = useRef(true);
2669
+ useEffect(function() {
2670
+ if (isMounted.current && !isInitial.current) {
2671
+ setT(getT);
2672
+ }
2673
+ isInitial.current = false;
2674
+ }, [i18n]);
2675
+ var ret = [t, i18n, ready];
2676
+ ret.t = t;
2677
+ ret.i18n = i18n;
2678
+ ret.ready = ready;
2679
+ if (ready)
2680
+ return ret;
2681
+ if (!ready && !useSuspense)
2682
+ return ret;
2683
+ throw new Promise(function(resolve) {
2684
+ loadNamespaces(i18n, namespaces, function() {
2685
+ resolve();
2686
+ });
2687
+ });
2688
+ }
2689
+ function LanguageString(_a) {
2690
+ var _b = _a, {
2691
+ as: Component,
2692
+ language,
2693
+ children
2694
+ } = _b, props = __objRest2(_b, ["as", "language", "children"]);
2695
+ const {
2696
+ i18n
2697
+ } = useTranslation();
2698
+ const viewingDirection = useMemo(() => i18n.dir ? i18n.dir(language) : "ltr", [language]);
2699
+ const isSame = useMemo(() => {
2700
+ if (!i18n.services) {
2701
+ return false;
2702
+ }
2703
+ return i18n.services.languageUtils.getLanguagePartFromCode(i18n.language) === i18n.services.languageUtils.getLanguagePartFromCode(language);
2704
+ }, [i18n.language, language]);
2705
+ if (isSame) {
2706
+ if (Component) {
2707
+ return /* @__PURE__ */ jsx(Component, __spreadProps(__spreadValues({}, __spreadValues2({}, props)), {
2708
+ children
2709
+ }));
2710
+ }
2711
+ return /* @__PURE__ */ jsx("span", __spreadProps(__spreadValues({}, __spreadValues2({}, props)), {
2712
+ children
2713
+ }));
2714
+ }
2715
+ if (Component) {
2716
+ return /* @__PURE__ */ jsx(Component, __spreadProps(__spreadValues({}, __spreadProps2(__spreadValues2({}, props), {
2717
+ lang: language,
2718
+ dir: viewingDirection
2719
+ })), {
2720
+ children
2721
+ }));
2722
+ }
2723
+ return /* @__PURE__ */ jsx("span", __spreadProps(__spreadValues({}, __spreadProps2(__spreadValues2({}, props), {
2724
+ lang: language,
2725
+ dir: viewingDirection
2726
+ })), {
2727
+ children
2728
+ }));
2729
+ }
2730
+ function getClosestLanguage(i18nLanguage, languages, i18nLanguages = [], strictFallback = false) {
2731
+ if (!i18nLanguage || !languages || languages.length === 0) {
2732
+ return void 0;
2733
+ }
2734
+ if (languages.length === 1) {
2735
+ return languages[0];
2736
+ }
2737
+ if (languages.indexOf(i18nLanguage) !== -1) {
2738
+ return i18nLanguage;
2739
+ }
2740
+ const root = i18nLanguage.indexOf("-") !== -1 ? i18nLanguage.slice(0, i18nLanguage.indexOf("-")) : null;
2741
+ if (root && languages.indexOf(root) !== -1) {
2742
+ return root;
2743
+ }
2744
+ for (const lang of i18nLanguages) {
2745
+ if (languages.indexOf(lang) !== -1) {
2746
+ return lang;
2747
+ }
2748
+ }
2749
+ if (!strictFallback) {
2750
+ const inverseRoot = languages.map((l) => l.indexOf("-") !== -1 ? l.slice(0, l.indexOf("-")) : null);
2751
+ const inverseIdx = inverseRoot.indexOf(i18nLanguage);
2752
+ if (inverseIdx !== -1) {
2753
+ return languages[inverseIdx];
2754
+ }
2755
+ for (const lang of i18nLanguages) {
2756
+ const root2 = lang.indexOf("-") !== -1 ? lang.slice(0, lang.indexOf("-")) : null;
2757
+ const inverseIdx2 = root2 ? languages.indexOf(root2) : -1;
2758
+ if (inverseIdx2 !== -1) {
2759
+ return languages[inverseIdx2];
2760
+ }
2761
+ }
2762
+ }
2763
+ if (languages.indexOf("none") !== -1) {
2764
+ return "none";
2765
+ }
2766
+ if (languages.indexOf("@none") !== -1) {
2767
+ return "@none";
2768
+ }
2769
+ return languages[0];
2770
+ }
2771
+ function buildLocaleString(inputText, i18nLanguage, options = {}) {
2772
+ const {
2773
+ strictFallback = false,
2774
+ defaultText = "",
2775
+ separator = "\n",
2776
+ fallbackLanguages = [],
2777
+ closest
2778
+ } = options;
2779
+ const languages = Object.keys(inputText || {});
2780
+ const language = closest ? i18nLanguage : getClosestLanguage(i18nLanguage, languages, fallbackLanguages, strictFallback);
2781
+ if (!inputText) {
2782
+ return defaultText;
2783
+ }
2784
+ if (typeof inputText === "string") {
2785
+ return inputText;
2786
+ }
2787
+ const candidateText = language ? inputText[language] : void 0;
2788
+ if (candidateText) {
2789
+ if (typeof candidateText === "string") {
2790
+ return candidateText;
2791
+ }
2792
+ return candidateText.join(separator);
2793
+ }
2794
+ return "";
2795
+ }
2796
+ function useClosestLanguage(getLanguages, deps = []) {
2797
+ const {
2798
+ i18n
2799
+ } = useTranslation();
2800
+ const i18nLanguages = i18n && i18n.languages ? i18n.languages : [];
2801
+ const i18nLanguage = i18n && i18n.language ? i18n.language : "en";
2802
+ return useMemo(() => {
2803
+ const languages = getLanguages();
2804
+ return getClosestLanguage(i18nLanguage, languages, i18nLanguages);
2805
+ }, [i18nLanguages, i18nLanguage, ...deps]);
2806
+ }
2807
+ function useLocaleString(inputText, defaultText) {
2808
+ const language = useClosestLanguage(() => Object.keys(inputText || {}), [inputText]);
2809
+ return [useMemo(() => {
2810
+ return buildLocaleString(inputText, language, {
2811
+ defaultText,
2812
+ closest: true
2813
+ });
2814
+ }, [language, defaultText, inputText]), language];
2815
+ }
2816
+ const LocaleString = (_c) => {
2817
+ var _d = _c, {
2818
+ as: Component,
2819
+ defaultText,
2820
+ enableDangerouslySetInnerHTML,
2821
+ children
2822
+ } = _d, props = __objRest2(_d, ["as", "defaultText", "enableDangerouslySetInnerHTML", "children"]);
2823
+ const [text, language] = useLocaleString(children, defaultText);
2824
+ if (language) {
2825
+ return /* @__PURE__ */ jsx(LanguageString, __spreadProps(__spreadValues({}, __spreadProps2(__spreadValues2({}, props), {
2826
+ as: Component,
2827
+ language,
2828
+ title: enableDangerouslySetInnerHTML ? void 0 : text,
2829
+ dangerouslySetInnerHTML: enableDangerouslySetInnerHTML ? {
2830
+ __html: text
2831
+ } : void 0
2832
+ })), {
2833
+ children: enableDangerouslySetInnerHTML ? void 0 : text
2834
+ }));
2835
+ }
2836
+ if (Component) {
2837
+ return /* @__PURE__ */ jsx(Component, __spreadProps(__spreadValues({}, __spreadValues2({}, props)), {
2838
+ children: text
2839
+ }));
2840
+ }
2841
+ return /* @__PURE__ */ jsx("span", __spreadProps(__spreadValues({}, __spreadProps2(__spreadValues2({}, props), {
2842
+ title: enableDangerouslySetInnerHTML ? void 0 : text,
2843
+ dangerouslySetInnerHTML: enableDangerouslySetInnerHTML ? {
2844
+ __html: text
2845
+ } : void 0
2846
+ })), {
2847
+ children: enableDangerouslySetInnerHTML ? void 0 : text
2848
+ }));
2849
+ };
2850
+ function RenderCanvas({
2851
+ x,
2852
+ y,
2853
+ onChoiceChange,
2854
+ registerActions,
2855
+ defaultChoices,
2856
+ isStatic,
2857
+ renderViewerControls,
2858
+ renderMediaControls,
2859
+ strategies,
2860
+ backgroundStyle,
2861
+ alwaysShowBackground,
2862
+ onClickPaintingAnnotation,
2863
+ children
2864
+ }) {
2865
+ const canvas = useCanvas();
2866
+ const elementProps = useResourceEvents(canvas, ["deep-zoom"]);
2867
+ const [virtualPage] = useVirtualAnnotationPageContext();
2868
+ const vault = useVault();
2869
+ const helper = useMemo(() => createStylesHelper(vault), [vault]);
2870
+ const [strategy, actions] = useRenderingStrategy({
2871
+ strategies: strategies || ["images"],
2872
+ defaultChoices: defaultChoices == null ? void 0 : defaultChoices.map(({
2873
+ id
2874
+ }) => id)
2875
+ });
2876
+ const choice = strategy.type === "images" ? strategy.choice : void 0;
2877
+ useEffect(() => {
2878
+ if (registerActions) {
2879
+ registerActions(actions);
2880
+ }
2881
+ }, [strategy.annotations]);
2882
+ useEffect(() => {
2883
+ if (defaultChoices) {
2884
+ for (const choice2 of defaultChoices) {
2885
+ if (typeof choice2.opacity !== "undefined") {
2886
+ helper.applyStyles({
2887
+ id: choice2.id
2888
+ }, "atlas", {
2889
+ opacity: choice2.opacity
2890
+ });
2891
+ }
2892
+ }
2893
+ }
2894
+ }, [defaultChoices]);
2895
+ useLayoutEffect(() => {
2896
+ if (onChoiceChange) {
2897
+ onChoiceChange(choice);
2898
+ }
2899
+ }, [choice]);
2900
+ const thumbnail = useThumbnail({
2901
+ maxWidth: 256,
2902
+ maxHeight: 256
2903
+ });
2904
+ if (!canvas) {
2905
+ return null;
2906
+ }
2907
+ const accompanyingCanvas = canvas.accompanyingCanvas;
2908
+ const thumbnailFallbackImage = thumbnail && thumbnail.type === "fixed" ? /* @__PURE__ */ jsx("world-object", {
2909
+ height: canvas.height,
2910
+ width: canvas.width,
2911
+ x,
2912
+ y,
2913
+ children: /* @__PURE__ */ jsx("world-image", {
2914
+ uri: thumbnail.id,
2915
+ target: {
2916
+ x: 0,
2917
+ y: 0,
2918
+ width: canvas.width,
2919
+ height: canvas.height
2920
+ },
2921
+ display: thumbnail.width && thumbnail.height ? {
2922
+ width: thumbnail.width,
2923
+ height: thumbnail.height
2924
+ } : void 0
2925
+ })
2926
+ }) : null;
2927
+ if (strategy.type === "unknown") {
2928
+ if (thumbnailFallbackImage) {
2929
+ return thumbnailFallbackImage;
2930
+ }
2931
+ throw new Error(strategy.reason || "Unknown image strategy");
2932
+ }
2933
+ const annotations = /* @__PURE__ */ jsxs(Fragment, {
2934
+ children: [virtualPage ? /* @__PURE__ */ jsx(RenderAnnotationPage, {
2935
+ page: virtualPage
2936
+ }) : null, strategy.annotations && strategy.annotations.pages ? strategy.annotations.pages.map((page) => {
2937
+ return /* @__PURE__ */ jsx(RenderAnnotationPage, {
2938
+ page
2939
+ }, page.id);
2940
+ }) : null, children]
2941
+ });
2942
+ return /* @__PURE__ */ jsxs(Fragment$1, {
2943
+ children: [/* @__PURE__ */ jsxs("world-object", __spreadProps(__spreadValues({
2944
+ height: canvas.height,
2945
+ width: canvas.width,
2946
+ x,
2947
+ y
2948
+ }, elementProps), {
2949
+ children: [strategy.type === "empty" || alwaysShowBackground ? /* @__PURE__ */ jsx(CanvasBackground, {
2950
+ style: backgroundStyle
2951
+ }) : null, strategy.type === "textual-content" ? strategy.items.map((item, n) => {
2952
+ return /* @__PURE__ */ jsxs(Fragment$1, {
2953
+ children: [/* @__PURE__ */ jsx(HTMLPortal, {
2954
+ onClick: onClickPaintingAnnotation ? (e) => {
2955
+ e.stopPropagation();
2956
+ onClickPaintingAnnotation(item.annotationId, item, e);
2957
+ } : void 0,
2958
+ target: item.target.spatial || void 0,
2959
+ children: /* @__PURE__ */ jsx(LocaleString, {
2960
+ children: item.text
2961
+ })
2962
+ }, n), annotations]
2963
+ });
2964
+ }) : null, strategy.type === "images" ? /* @__PURE__ */ jsxs(Fragment$1, {
2965
+ children: [strategy.images.map((image, idx) => /* @__PURE__ */ jsx(RenderImage, {
2966
+ isStatic,
2967
+ image,
2968
+ id: image.id,
2969
+ thumbnail: idx === 0 ? thumbnail : void 0,
2970
+ onClick: onClickPaintingAnnotation ? (e) => {
2971
+ e.stopPropagation();
2972
+ onClickPaintingAnnotation(image.annotationId, image, e);
2973
+ } : void 0
2974
+ }, image.id)), annotations]
2975
+ }) : null, (strategy.type === "images" || strategy.type === "empty" || strategy.type === "textual-content") && renderViewerControls ? /* @__PURE__ */ jsx(CanvasPortal, {
2976
+ overlay: true,
2977
+ children: renderViewerControls(strategy)
2978
+ }) : null, strategy.type === "3d-model" ? /* @__PURE__ */ jsx(Model, {
2979
+ model: strategy.model
2980
+ }) : null, strategy.type === "media" ? /* @__PURE__ */ jsx(Fragment$1, {
2981
+ children: strategy.media.type === "Sound" ? /* @__PURE__ */ jsxs(Audio, {
2982
+ media: strategy.media,
2983
+ children: [thumbnailFallbackImage, renderMediaControls ? renderMediaControls(strategy) : null]
2984
+ }) : strategy.media.type === "Video" ? /* @__PURE__ */ jsxs(Video, {
2985
+ media: strategy.media,
2986
+ children: [thumbnailFallbackImage, renderMediaControls ? renderMediaControls(strategy) : null]
2987
+ }) : null
2988
+ }) : null]
2989
+ }), `${canvas.id}/${strategy.type}`), strategy.type === "media" && strategy.media.type === "Sound" && accompanyingCanvas ? /* @__PURE__ */ jsx(CanvasContext, {
2990
+ canvas: accompanyingCanvas.id,
2991
+ children: /* @__PURE__ */ jsx(RenderCanvas, {
2992
+ renderViewerControls
2993
+ })
2994
+ }) : null]
2995
+ });
2996
+ }
2997
+ const CanvasPanel = {
2998
+ RenderImage,
2999
+ RenderCanvas,
3000
+ RenderAnnotationPage,
3001
+ RenderAnnotation,
3002
+ Viewer,
3003
+ CanvasBackground
3004
+ };
3005
+ function AnnotationContext({
3006
+ annotation,
3007
+ children
3008
+ }) {
3009
+ return /* @__PURE__ */ jsx(ResourceProvider, {
3010
+ value: {
3011
+ annotation
3012
+ },
3013
+ children
3014
+ });
3015
+ }
3016
+ function CollectionContext({
3017
+ collection,
3018
+ children
3019
+ }) {
3020
+ return /* @__PURE__ */ jsx(ResourceProvider, {
3021
+ value: {
3022
+ collection
3023
+ },
3024
+ children
3025
+ });
3026
+ }
3027
+ function useAnnotationsAtTime(time, options = {}) {
3028
+ const allAnnotations = usePaintingAnnotations(options);
3029
+ return allAnnotations;
3030
+ }
3031
+ function useCanvasClock(canvasId, autoplay = false) {
3032
+ }
3033
+ function useCanvasSubset(idsOrRefs) {
3034
+ const ctx = useResourceContext();
3035
+ const manifestId = ctx.manifest;
3036
+ const refs = idsOrRefs ? idsOrRefs.map((item) => typeof item === "string" ? item : item == null ? void 0 : item.id) : [];
3037
+ return useVaultSelector((s) => {
3038
+ const manifest = manifestId ? s.iiif.entities.Manifest[manifestId] : void 0;
3039
+ const items = (manifest == null ? void 0 : manifest.items) || [];
3040
+ if (typeof idsOrRefs === "undefined") {
3041
+ return items;
3042
+ }
3043
+ const newItems = [];
3044
+ for (const item of (manifest == null ? void 0 : manifest.items) || []) {
3045
+ if (refs.indexOf(item.id) !== -1) {
3046
+ newItems.push(item);
3047
+ }
3048
+ }
3049
+ return newItems;
3050
+ }, [refs.join("/")]);
3051
+ }
3052
+ function useCollection(options, deps = []) {
3053
+ const { id, selector } = options;
3054
+ const ctx = useResourceContext();
3055
+ const collectionId = id ? id : ctx.collection;
3056
+ const collection = useVaultSelector((s) => collectionId ? s.iiif.entities.Collection[collectionId] : void 0, [collectionId]);
3057
+ return useMemo(() => {
3058
+ if (!collection) {
3059
+ return void 0;
3060
+ }
3061
+ if (selector) {
3062
+ return selector(collection);
3063
+ }
3064
+ return collection;
3065
+ }, [collection, selector, ...deps]);
3066
+ }
3067
+ function useEventListener(resource, name, listener, scope, deps = []) {
3068
+ const vault = useVault();
3069
+ const helper = useMemo(() => createEventsHelper(vault), [vault]);
3070
+ useEffect(() => {
3071
+ const currentResource = resource;
3072
+ if (!currentResource) {
3073
+ return () => {
3074
+ };
3075
+ }
3076
+ helper.addEventListener(currentResource, name, listener, scope);
3077
+ return () => {
3078
+ helper.removeEventListener(currentResource, name, listener);
3079
+ };
3080
+ }, [helper, resource, name, ...deps]);
3081
+ }
3082
+ function useExistingVault() {
3083
+ const oldContext = useContext(ReactVaultContext);
3084
+ return oldContext && oldContext.vault ? oldContext.vault : globalVault();
3085
+ }
3086
+ function useExternalCollection(idOrRef, options) {
3087
+ const { id, isLoaded, error, resource, requestId, cached } = useExternalResource(idOrRef, options);
3088
+ return { id, isLoaded, error, manifest: resource, requestId, cached };
3089
+ }
3090
+ function useImageService({ cacheKey } = {}) {
3091
+ const canvas = useCanvas();
3092
+ const annotations = usePaintingAnnotations();
3093
+ const vault = useVault();
3094
+ const imageService = useImageServiceLoader();
3095
+ const [_data, setData] = useState(void 0);
3096
+ const [isFetching, setIsFetching] = useState(false);
3097
+ const [status, setStatus] = useState("idle");
3098
+ const [error, setError] = useState(void 0);
3099
+ const key = canvas ? canvas.id : "undefined";
3100
+ const initialData = useMemo(() => {
3101
+ try {
3102
+ if (canvas && annotations.length) {
3103
+ const annotation = annotations[0];
3104
+ const resource = vault.get(annotation.body[0]);
3105
+ const imageServices = getImageServices(resource);
3106
+ const firstImageService = imageServices[0];
3107
+ if (!firstImageService) {
3108
+ return void 0;
3109
+ }
3110
+ return imageService.loadServiceSync({
3111
+ id: firstImageService.id || firstImageService["@id"],
3112
+ width: firstImageService.width || canvas.width,
3113
+ height: firstImageService.height || canvas.height
3114
+ }) || void 0;
3115
+ }
3116
+ } catch (e) {
3117
+ console.error(e);
3118
+ }
3119
+ return void 0;
3120
+ }, [key, cacheKey, canvas]);
3121
+ const data = status === "success" && _data ? _data : initialData;
3122
+ useEffect(() => {
3123
+ (async () => {
3124
+ try {
3125
+ if (canvas && annotations.length) {
3126
+ const annotation = annotations[0];
3127
+ const resource = vault.get(annotation.body[0]);
3128
+ const imageServices = getImageServices(resource);
3129
+ const firstImageService = imageServices[0];
3130
+ if (!firstImageService) {
3131
+ return;
3132
+ }
3133
+ setIsFetching(true);
3134
+ setStatus("loading");
3135
+ try {
3136
+ const loadedService = await imageService.loadService({
3137
+ id: firstImageService.id || firstImageService["@id"],
3138
+ width: firstImageService.width || canvas.width,
3139
+ height: firstImageService.height || canvas.height
3140
+ }) || void 0;
3141
+ setData(loadedService);
3142
+ setStatus("success");
3143
+ setIsFetching(false);
3144
+ } catch (err) {
3145
+ setStatus("error");
3146
+ setError(err);
3147
+ }
3148
+ }
3149
+ } catch (err) {
3150
+ setStatus("error");
3151
+ setError(err);
3152
+ }
3153
+ })();
3154
+ }, [key, cacheKey]);
3155
+ return useMemo(() => {
3156
+ return {
3157
+ data,
3158
+ isFetching,
3159
+ status,
3160
+ error
3161
+ };
3162
+ }, [data, isFetching, status, error]);
3163
+ }
3164
+ function useImageTile() {
3165
+ const imageService = useImageService();
3166
+ return {
3167
+ isLoading: imageService.isFetching,
3168
+ tile: imageService.data ? {
3169
+ id: imageService.data.id || imageService.data["@id"],
3170
+ width: imageService.data.width,
3171
+ height: imageService.data.height,
3172
+ imageService: imageService.data,
3173
+ thumbnail: void 0
3174
+ } : null
3175
+ };
3176
+ }
3177
+ function useSearchService() {
3178
+ const manifest = useManifest();
3179
+ return manifest ? manifest.service.find((service) => service.profile === "SearchService1" || service.profile === "http://iiif.io/api/search/1/search") : void 0;
3180
+ }
3181
+ function useStyleHelper() {
3182
+ const vault = useVault();
3183
+ return useMemo(() => createStylesHelper(vault), [vault]);
3184
+ }
3185
+ export { AnnotationContext, CanvasContext, CanvasPanel, CanvasPortal, CollectionContext, ContextBridge, ImageServiceLoaderContext, InnerViewerProvider, ManifestContext, MediaPlayerProvider, OverlayPortalContext, PortalContext, RangeContext, ReactVaultContext, ResourceProvider, ResourceReactContext, SimpleViewerProvider, SimpleViewerReactContext, VaultProvider, ViewerPresetContext, VirtualAnnotationProvider, VisibleCanvasReactContext, emptyActions, emptyStrategy, expandTarget, findAllCanvasesInRange, findFirstCanvasFromRange, findManifestSelectedRange, findSelectedRange, flattenAnnotationPageIds, formatTime, getImageStrategy, getManifestSequence, getPaintables, getParsedTargetSelector, getVisibleCanvasesFromCanvasId, parseSelector, parseSpecificResource, unknownResponse, unsupportedStrategy, useAnnotation, useAnnotationPageManager, useAnnotationsAtTime, useCanvas, useCanvasClock, useCanvasSequence, useCanvasSubset, useCollection, useContextBridge, useDispatch, useEventListener, useExistingVault, useExternalCollection, useExternalManifest, useExternalResource, useImageService, useImageServiceLoader, useImageTile, useLoadImageService, useManifest, useMediaActions, useMediaElements, useMediaState, usePaintables, usePaintingAnnotations, useRange, useRenderingStrategy, useResourceContext, useResourceEvents, useResources, useSearchService, useSimpleMediaPlayer, useSimpleViewer, useStyleHelper, useStyles, useThumbnail, useVault, useVaultEffect, useVaultSelector, useViewerPreset, useVirtualAnnotationPage, useVirtualAnnotationPageContext, useVisibleCanvases };
3186
+ //# sourceMappingURL=index.mjs.map