react-iiif-vault 0.9.14 → 0.9.17

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