react-iiif-vault 0.9.11 → 0.9.12

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 (90) hide show
  1. package/.build/types/canvas-panel/Viewer.d.ts +13 -0
  2. package/.build/types/canvas-panel/index.d.ts +18 -0
  3. package/.build/types/canvas-panel/render/Annotation.d.ts +8 -0
  4. package/.build/types/canvas-panel/render/AnnotationPage.d.ts +6 -0
  5. package/.build/types/canvas-panel/render/Audio.d.ts +6 -0
  6. package/.build/types/canvas-panel/render/Canvas.d.ts +23 -0
  7. package/.build/types/canvas-panel/render/DefaultCanvasFallback.d.ts +5 -0
  8. package/.build/types/canvas-panel/render/Image.d.ts +13 -0
  9. package/.build/types/canvas-panel/render/Model.d.ts +3 -0
  10. package/.build/types/canvas-panel/render/Video.d.ts +6 -0
  11. package/.build/types/context/AnnotationContext.d.ts +5 -0
  12. package/.build/types/context/CanvasContext.d.ts +5 -0
  13. package/.build/types/context/CollectionContext.d.ts +5 -0
  14. package/.build/types/context/ContextBridge.d.ts +22 -0
  15. package/.build/types/context/ImageServiceLoaderContext.d.ts +4 -0
  16. package/.build/types/context/ManifestContext.d.ts +5 -0
  17. package/.build/types/context/MediaContext.d.ts +17 -0
  18. package/.build/types/context/PortalContext.d.ts +7 -0
  19. package/.build/types/context/RangeContext.d.ts +5 -0
  20. package/.build/types/context/ResourceContext.d.ts +14 -0
  21. package/.build/types/context/VaultContext.d.ts +14 -0
  22. package/.build/types/context/ViewerPresetContext.d.ts +3 -0
  23. package/.build/types/context/VisibleCanvasContext.d.ts +4 -0
  24. package/.build/types/demo/demo.d.ts +1 -0
  25. package/.build/types/demo/media-controls.d.ts +1 -0
  26. package/.build/types/demo/viewer-controls.d.ts +1 -0
  27. package/.build/types/features/rendering-strategy/3d-strategy.d.ts +13 -0
  28. package/.build/types/features/rendering-strategy/audio-strategy.d.ts +3 -0
  29. package/.build/types/features/rendering-strategy/choice-types.d.ts +15 -0
  30. package/.build/types/features/rendering-strategy/image-strategy.d.ts +13 -0
  31. package/.build/types/features/rendering-strategy/rendering-utils.d.ts +21 -0
  32. package/.build/types/features/rendering-strategy/resource-types.d.ts +42 -0
  33. package/.build/types/features/rendering-strategy/selector-extensions.d.ts +53 -0
  34. package/.build/types/features/rendering-strategy/strategies.d.ts +22 -0
  35. package/.build/types/features/rendering-strategy/video-strategy.d.ts +3 -0
  36. package/.build/types/hooks/useAnnotation.d.ts +8 -0
  37. package/.build/types/hooks/useAnnotationPageManager.d.ts +10 -0
  38. package/.build/types/hooks/useAnnotationsAtTime.d.ts +4 -0
  39. package/.build/types/hooks/useCanvas.d.ts +8 -0
  40. package/.build/types/hooks/useCanvasClock.d.ts +1 -0
  41. package/.build/types/hooks/useCanvasSelector.d.ts +0 -0
  42. package/.build/types/hooks/useCanvasTimeline.d.ts +0 -0
  43. package/.build/types/hooks/useCollection.d.ts +8 -0
  44. package/.build/types/hooks/useDispatch.d.ts +2 -0
  45. package/.build/types/hooks/useEnabledAnnotationPageIds.d.ts +1 -0
  46. package/.build/types/hooks/useEventListener.d.ts +4 -0
  47. package/.build/types/hooks/useExistingVault.d.ts +1 -0
  48. package/.build/types/hooks/useExternalCollection.d.ts +13 -0
  49. package/.build/types/hooks/useExternalManifest.d.ts +13 -0
  50. package/.build/types/hooks/useExternalResource.d.ts +16 -0
  51. package/.build/types/hooks/useImageService.d.ts +9 -0
  52. package/.build/types/hooks/useImageTile.d.ts +11 -0
  53. package/.build/types/hooks/useLoadImageService.d.ts +6 -0
  54. package/.build/types/hooks/useManifest.d.ts +8 -0
  55. package/.build/types/hooks/usePaintables.d.ts +8 -0
  56. package/.build/types/hooks/usePaintingAnnotations.d.ts +4 -0
  57. package/.build/types/hooks/useRange.d.ts +8 -0
  58. package/.build/types/hooks/useRenderingStrategy.d.ts +14 -0
  59. package/.build/types/hooks/useResourceEvents.d.ts +3 -0
  60. package/.build/types/hooks/useResources.d.ts +1 -0
  61. package/.build/types/hooks/useSearchService.d.ts +2 -0
  62. package/.build/types/hooks/useSimpleMediaPlayer.d.ts +32 -0
  63. package/.build/types/hooks/useStyleHelper.d.ts +1 -0
  64. package/.build/types/hooks/useStyles.d.ts +3 -0
  65. package/.build/types/hooks/useThumbnail.d.ts +5 -0
  66. package/.build/types/hooks/useVault.d.ts +2 -0
  67. package/.build/types/hooks/useVaultEffect.d.ts +2 -0
  68. package/.build/types/hooks/useVaultSelector.d.ts +2 -0
  69. package/.build/types/hooks/useVirtualAnnotationPage.d.ts +13 -0
  70. package/.build/types/hooks/useVirtualAnnotationPageContext.d.ts +9 -0
  71. package/.build/types/hooks/useVirtualCanvas.d.ts +0 -0
  72. package/.build/types/index.d.ts +56 -0
  73. package/.build/types/utility/expand-target.d.ts +19 -0
  74. package/.build/types/utility/flatten-annotation-page-ids.d.ts +7 -0
  75. package/.build/types/utility/parse-selector.d.ts +7 -0
  76. package/.build/types/viewers/SimpleViewerContext.d.ts +18 -0
  77. package/.build/types/viewers/SingleCanvasContext.d.ts +1 -0
  78. package/dist/bundle/cjs/index.js +36 -0
  79. package/dist/bundle/cjs/index.js.map +1 -0
  80. package/dist/{esm → bundle/esm}/index.mjs +720 -790
  81. package/dist/bundle/esm/index.mjs.map +1 -0
  82. package/dist/canvas-panel/cjs/canvas-panel.js +36 -0
  83. package/dist/canvas-panel/cjs/canvas-panel.js.map +1 -0
  84. package/dist/canvas-panel/esm/canvas-panel.mjs +2024 -0
  85. package/dist/canvas-panel/esm/canvas-panel.mjs.map +1 -0
  86. package/dist/index.umd.js +121 -31744
  87. package/dist/index.umd.js.map +1 -0
  88. package/package.json +38 -28
  89. package/dist/cjs/index.js +0 -2538
  90. package/dist/index.d.ts +0 -619
@@ -0,0 +1,2024 @@
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, createContext, useRef, useLayoutEffect, useCallback, Fragment as Fragment$1, useReducer } from "react";
34
+ import { AtlasAuto, mergeStyles, RegionHighlight, TileSet } from "@atlas-viewer/atlas";
35
+ import { globalVault, Vault } from "@iiif/vault";
36
+ import { createAction } from "typesafe-actions";
37
+ import require$$0 from "react-dom";
38
+ import { ImageServiceLoader, getImageServices, getFixedSizeFromImage } from "@atlas-viewer/iiif-image-api";
39
+ function _setPrototypeOf(o, p2) {
40
+ _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
41
+ o2.__proto__ = p3;
42
+ return o2;
43
+ };
44
+ return _setPrototypeOf(o, p2);
45
+ }
46
+ function _inheritsLoose(subClass, superClass) {
47
+ subClass.prototype = Object.create(superClass.prototype);
48
+ subClass.prototype.constructor = subClass;
49
+ _setPrototypeOf(subClass, superClass);
50
+ }
51
+ var changedArray = function changedArray2(a, b) {
52
+ if (a === void 0) {
53
+ a = [];
54
+ }
55
+ if (b === void 0) {
56
+ b = [];
57
+ }
58
+ return a.length !== b.length || a.some(function(item, index) {
59
+ return !Object.is(item, b[index]);
60
+ });
61
+ };
62
+ var initialState = {
63
+ error: null
64
+ };
65
+ var ErrorBoundary = /* @__PURE__ */ function(_React$Component) {
66
+ _inheritsLoose(ErrorBoundary2, _React$Component);
67
+ function ErrorBoundary2() {
68
+ var _this;
69
+ for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
70
+ _args[_key] = arguments[_key];
71
+ }
72
+ _this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;
73
+ _this.state = initialState;
74
+ _this.resetErrorBoundary = function() {
75
+ var _this$props;
76
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
77
+ args[_key2] = arguments[_key2];
78
+ }
79
+ _this.props.onReset == null ? void 0 : (_this$props = _this.props).onReset.apply(_this$props, args);
80
+ _this.reset();
81
+ };
82
+ return _this;
83
+ }
84
+ ErrorBoundary2.getDerivedStateFromError = function getDerivedStateFromError(error) {
85
+ return {
86
+ error
87
+ };
88
+ };
89
+ var _proto = ErrorBoundary2.prototype;
90
+ _proto.reset = function reset() {
91
+ this.setState(initialState);
92
+ };
93
+ _proto.componentDidCatch = function componentDidCatch(error, info) {
94
+ var _this$props$onError, _this$props2;
95
+ (_this$props$onError = (_this$props2 = this.props).onError) == null ? void 0 : _this$props$onError.call(_this$props2, error, info);
96
+ };
97
+ _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
98
+ var error = this.state.error;
99
+ var resetKeys = this.props.resetKeys;
100
+ if (error !== null && prevState.error !== null && changedArray(prevProps.resetKeys, resetKeys)) {
101
+ var _this$props$onResetKe, _this$props3;
102
+ (_this$props$onResetKe = (_this$props3 = this.props).onResetKeysChange) == null ? void 0 : _this$props$onResetKe.call(_this$props3, prevProps.resetKeys, resetKeys);
103
+ this.reset();
104
+ }
105
+ };
106
+ _proto.render = function render() {
107
+ var error = this.state.error;
108
+ var _this$props4 = this.props, fallbackRender = _this$props4.fallbackRender, FallbackComponent = _this$props4.FallbackComponent, fallback = _this$props4.fallback;
109
+ if (error !== null) {
110
+ var _props = {
111
+ error,
112
+ resetErrorBoundary: this.resetErrorBoundary
113
+ };
114
+ if (/* @__PURE__ */ React.isValidElement(fallback)) {
115
+ return fallback;
116
+ } else if (typeof fallbackRender === "function") {
117
+ return fallbackRender(_props);
118
+ } else if (FallbackComponent) {
119
+ return /* @__PURE__ */ React.createElement(FallbackComponent, _props);
120
+ } else {
121
+ throw new Error("react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop");
122
+ }
123
+ }
124
+ return this.props.children;
125
+ };
126
+ return ErrorBoundary2;
127
+ }(React.Component);
128
+ var jsxRuntime = { exports: {} };
129
+ var reactJsxRuntime_production_min = {};
130
+ /**
131
+ * @license React
132
+ * react-jsx-runtime.production.min.js
133
+ *
134
+ * Copyright (c) Facebook, Inc. and its affiliates.
135
+ *
136
+ * This source code is licensed under the MIT license found in the
137
+ * LICENSE file in the root directory of this source tree.
138
+ */
139
+ var f = React__default, k = Symbol.for("react.element"), l = Symbol.for("react.fragment"), m$1 = Object.prototype.hasOwnProperty, n = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, p = { key: true, ref: true, __self: true, __source: true };
140
+ function q(c, a, g) {
141
+ var b, d = {}, e = null, h = null;
142
+ g !== void 0 && (e = "" + g);
143
+ a.key !== void 0 && (e = "" + a.key);
144
+ a.ref !== void 0 && (h = a.ref);
145
+ for (b in a)
146
+ m$1.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]);
147
+ if (c && c.defaultProps)
148
+ for (b in a = c.defaultProps, a)
149
+ d[b] === void 0 && (d[b] = a[b]);
150
+ return { $$typeof: k, type: c, key: e, ref: h, props: d, _owner: n.current };
151
+ }
152
+ reactJsxRuntime_production_min.Fragment = l;
153
+ reactJsxRuntime_production_min.jsx = q;
154
+ reactJsxRuntime_production_min.jsxs = q;
155
+ {
156
+ jsxRuntime.exports = reactJsxRuntime_production_min;
157
+ }
158
+ const jsx = jsxRuntime.exports.jsx;
159
+ const jsxs = jsxRuntime.exports.jsxs;
160
+ const Fragment = jsxRuntime.exports.Fragment;
161
+ const defaultResourceContext = {
162
+ collection: void 0,
163
+ manifest: void 0,
164
+ range: void 0,
165
+ canvas: void 0,
166
+ annotation: void 0
167
+ };
168
+ const ResourceReactContext = React__default.createContext(defaultResourceContext);
169
+ const useResourceContext = () => {
170
+ return useContext(ResourceReactContext);
171
+ };
172
+ function ResourceProvider({
173
+ value,
174
+ children
175
+ }) {
176
+ const parentContext = useResourceContext();
177
+ const newContext = useMemo(() => {
178
+ return __spreadValues(__spreadValues({}, parentContext), value);
179
+ }, [value, parentContext]);
180
+ return /* @__PURE__ */ jsx(ResourceReactContext.Provider, {
181
+ value: newContext,
182
+ children
183
+ });
184
+ }
185
+ const ReactVaultContext = React__default.createContext({
186
+ vault: null,
187
+ setVaultInstance: (vault) => {
188
+ }
189
+ });
190
+ function VaultProvider({
191
+ vault,
192
+ vaultOptions,
193
+ useGlobal,
194
+ resources,
195
+ children
196
+ }) {
197
+ const [vaultInstance, setVaultInstance] = useState(() => {
198
+ if (vault) {
199
+ return vault;
200
+ }
201
+ if (useGlobal) {
202
+ return globalVault(vaultOptions);
203
+ }
204
+ if (vaultOptions) {
205
+ return new Vault(vaultOptions);
206
+ }
207
+ return new Vault();
208
+ });
209
+ return /* @__PURE__ */ jsx(ReactVaultContext.Provider, {
210
+ value: {
211
+ vault: vaultInstance,
212
+ setVaultInstance
213
+ },
214
+ children: /* @__PURE__ */ jsx(ResourceProvider, {
215
+ value: resources || {},
216
+ children
217
+ })
218
+ });
219
+ }
220
+ const useVault = () => {
221
+ const { vault } = useContext(ReactVaultContext);
222
+ if (vault === null) {
223
+ throw new Error("Vault not found. Ensure you have your provider set up correctly.");
224
+ }
225
+ return vault;
226
+ };
227
+ function CanvasContext({
228
+ canvas,
229
+ children
230
+ }) {
231
+ return /* @__PURE__ */ jsx(ResourceProvider, {
232
+ value: {
233
+ canvas
234
+ },
235
+ children
236
+ });
237
+ }
238
+ function useVaultSelector(selector, deps = []) {
239
+ const vault = useVault();
240
+ const [selectedState, setSelectedState] = useState(() => selector(vault.getState(), vault));
241
+ useEffect(() => {
242
+ return vault.subscribe((s) => selector(s, vault), (s) => {
243
+ setSelectedState(s);
244
+ }, false);
245
+ }, deps);
246
+ return selectedState;
247
+ }
248
+ const VisibleCanvasReactContext = React__default.createContext([]);
249
+ function useVisibleCanvases() {
250
+ const ids = useContext(VisibleCanvasReactContext);
251
+ return useVaultSelector((state) => {
252
+ return ids.map((id) => state.iiif.entities.Canvas[id]).filter(Boolean);
253
+ }, [ids]);
254
+ }
255
+ const noop = () => {
256
+ };
257
+ const SimpleViewerReactContext = createContext({
258
+ setCurrentCanvasId: noop,
259
+ setCurrentCanvasIndex: noop,
260
+ nextCanvas: noop,
261
+ previousCanvas: noop,
262
+ currentCanvasIndex: -1,
263
+ totalCanvases: 0,
264
+ pagingView: true
265
+ });
266
+ function useContextBridge() {
267
+ return {
268
+ VaultContext: useContext(ReactVaultContext),
269
+ ResourceContext: useContext(ResourceReactContext),
270
+ SimpleViewerReactContext: useContext(SimpleViewerReactContext),
271
+ VisibleCanvasReactContext: useContext(VisibleCanvasReactContext)
272
+ };
273
+ }
274
+ function ContextBridge(props) {
275
+ return /* @__PURE__ */ jsx(VaultProvider, {
276
+ vault: props.bridge.VaultContext.vault || void 0,
277
+ resources: props.bridge.ResourceContext,
278
+ children: /* @__PURE__ */ jsx(VisibleCanvasReactContext.Provider, {
279
+ value: props.bridge.VisibleCanvasReactContext,
280
+ children: /* @__PURE__ */ jsx(SimpleViewerReactContext.Provider, {
281
+ value: props.bridge.SimpleViewerReactContext,
282
+ children: props.children
283
+ })
284
+ })
285
+ });
286
+ }
287
+ const IMPORT_ENTITIES = "@iiif/IMPORT_ENTITIES";
288
+ const MODIFY_ENTITY_FIELD = "@iiif/MODIFY_ENTITY_FIELD";
289
+ const REORDER_ENTITY_FIELD = "@iiif/REORDER_ENTITY_FIELD";
290
+ const ADD_REFERENCE = "@iiif/ADD_REFERENCE";
291
+ const REMOVE_REFERENCE = "@iiif/REMOVE_REFERENCE";
292
+ const importEntities = createAction(IMPORT_ENTITIES)();
293
+ const modifyEntityField = createAction(MODIFY_ENTITY_FIELD)();
294
+ const reorderEntityField = createAction(REORDER_ENTITY_FIELD)();
295
+ const addReference = createAction(ADD_REFERENCE)();
296
+ const removeReference = createAction(REMOVE_REFERENCE)();
297
+ const entityActions = { importEntities, modifyEntityField, reorderEntityField, addReference, removeReference };
298
+ const ADD_MAPPING = "@iiif/ADD_MAPPING";
299
+ const ADD_MAPPINGS = "@iiif/ADD_MAPPINGS";
300
+ createAction(ADD_MAPPING)();
301
+ createAction(ADD_MAPPINGS)();
302
+ const SET_META_VALUE = "@iiif/SET_META_VALUE";
303
+ const SET_META_VALUE_DYNAMIC = "@iiif/SET_META_VALUE_DYNAMIC";
304
+ const UNSET_META_VALUE = "@iiif/UNSET_META_VALUE";
305
+ createAction(SET_META_VALUE)();
306
+ createAction(SET_META_VALUE_DYNAMIC)();
307
+ createAction(UNSET_META_VALUE)();
308
+ const REQUEST_RESOURCE = "@iiif/REQUEST_RESOURCE";
309
+ const REQUEST_ERROR = "@iiif/REQUEST_ERROR";
310
+ const REQUEST_MISMATCH = "@iiif/REQUEST_MISMATCH";
311
+ const REQUEST_COMPLETE = "@iiif/REQUEST_COMPLETE";
312
+ const REQUEST_OFFLINE_RESOURCE = "@iiif/REQUEST_OFFLINE_RESOURCE";
313
+ createAction(REQUEST_RESOURCE)();
314
+ createAction(REQUEST_ERROR)();
315
+ createAction(REQUEST_MISMATCH)();
316
+ createAction(REQUEST_COMPLETE)();
317
+ createAction(REQUEST_OFFLINE_RESOURCE)();
318
+ const BATCH_ACTIONS = "@iiif/BATCH";
319
+ const BATCH_IMPORT = "@iiif/BATCH_IMPORT";
320
+ createAction(BATCH_ACTIONS)();
321
+ createAction(BATCH_IMPORT)();
322
+ function useDispatch() {
323
+ const vault = useVault();
324
+ const store = vault.getStore();
325
+ return useMemo(() => {
326
+ return (action) => store.dispatch(action);
327
+ }, [store]);
328
+ }
329
+ function isVaultActivated(obj) {
330
+ return typeof obj !== "string" && obj && obj.bindToVault;
331
+ }
332
+ function useVirtualAnnotationPage() {
333
+ const vault = useVault();
334
+ const sources = useRef([]);
335
+ const dispatch = useDispatch();
336
+ const virtualId = useMemo(() => {
337
+ return `vault://annotation-page/${new Date().getTime()}/${Math.round(Math.random() * 1e9).toString(16)}`;
338
+ }, []);
339
+ useLayoutEffect(() => {
340
+ const page = {
341
+ id: virtualId,
342
+ type: "AnnotationPage",
343
+ behavior: [],
344
+ motivation: null,
345
+ label: null,
346
+ thumbnail: [],
347
+ summary: null,
348
+ requiredStatement: null,
349
+ metadata: [],
350
+ rights: null,
351
+ provider: [],
352
+ items: [],
353
+ seeAlso: [],
354
+ homepage: [],
355
+ logo: [],
356
+ rendering: [],
357
+ service: []
358
+ };
359
+ dispatch(entityActions.importEntities({
360
+ entities: {
361
+ AnnotationPage: {
362
+ [page.id]: page
363
+ }
364
+ }
365
+ }));
366
+ }, [virtualId]);
367
+ const fullPage = useVaultSelector((state) => virtualId ? state.iiif.entities.AnnotationPage[virtualId] : null, [virtualId]);
368
+ const addAnnotation = useCallback((id, atIndex) => {
369
+ if (virtualId) {
370
+ if (isVaultActivated(id)) {
371
+ const display = id;
372
+ if (!display.__vault) {
373
+ display.bindToVault(vault);
374
+ }
375
+ id = typeof display.source === "string" ? display.source : display.source.id;
376
+ sources.current[id] = display;
377
+ } else if (typeof id !== "string") {
378
+ id = id.id;
379
+ }
380
+ const full = vault.get({ id: virtualId, type: "AnnotationPage" });
381
+ const annotation = vault.get({ id, type: "Annotation" });
382
+ if (full && annotation) {
383
+ if (!full.items.find((r) => r.id === annotation.id)) {
384
+ dispatch(entityActions.addReference({
385
+ id: virtualId,
386
+ type: "AnnotationPage",
387
+ key: "items",
388
+ reference: {
389
+ id,
390
+ type: "Annotation"
391
+ },
392
+ index: atIndex
393
+ }));
394
+ }
395
+ }
396
+ }
397
+ }, [virtualId]);
398
+ const removeAnnotation = useCallback((id) => {
399
+ if (virtualId) {
400
+ if (isVaultActivated(id)) {
401
+ id = typeof id.source === "string" ? id.source : id.source.id;
402
+ } else if (typeof id !== "string") {
403
+ id = id.id;
404
+ }
405
+ if (sources.current[id]) {
406
+ sources.current[id].beforeRemove();
407
+ }
408
+ const full = vault.get({ id: virtualId, type: "AnnotationPage" });
409
+ if (full) {
410
+ dispatch(entityActions.removeReference({
411
+ id: virtualId,
412
+ type: "AnnotationPage",
413
+ key: "items",
414
+ reference: {
415
+ id,
416
+ type: "Annotation"
417
+ }
418
+ }));
419
+ }
420
+ }
421
+ }, [virtualId]);
422
+ return [
423
+ fullPage,
424
+ {
425
+ addAnnotation,
426
+ removeAnnotation
427
+ }
428
+ ];
429
+ }
430
+ const VirtualAnnotationPageContext = createContext(null);
431
+ function useVirtualAnnotationPageContext() {
432
+ const ctx = useContext(VirtualAnnotationPageContext);
433
+ return [ctx.fullPage, {
434
+ addAnnotation: ctx.addAnnotation,
435
+ removeAnnotation: ctx.removeAnnotation
436
+ }];
437
+ }
438
+ function VirtualAnnotationProvider({
439
+ children
440
+ }) {
441
+ const [fullPage, {
442
+ addAnnotation,
443
+ removeAnnotation
444
+ }] = useVirtualAnnotationPage();
445
+ return /* @__PURE__ */ jsx(VirtualAnnotationPageContext.Provider, {
446
+ value: useMemo(() => ({
447
+ fullPage,
448
+ addAnnotation,
449
+ removeAnnotation
450
+ }), [fullPage]),
451
+ children
452
+ });
453
+ }
454
+ function DefaultCanvasFallback({
455
+ width,
456
+ style,
457
+ height
458
+ }) {
459
+ return /* @__PURE__ */ jsx("div", {
460
+ style: __spreadProps(__spreadValues({
461
+ width,
462
+ height,
463
+ minHeight: 500
464
+ }, style || {}), {
465
+ background: "#f9f9f9"
466
+ }),
467
+ children: "Unknown error"
468
+ });
469
+ }
470
+ var createRoot;
471
+ var m = require$$0;
472
+ {
473
+ createRoot = m.createRoot;
474
+ }
475
+ const ViewerPresetContext = createContext(null);
476
+ function useViewerPreset() {
477
+ return useContext(ViewerPresetContext);
478
+ }
479
+ const PortalContext = React__default.createContext(null);
480
+ const OverlayPortalContext = React__default.createContext(null);
481
+ function CanvasPortal({
482
+ children,
483
+ overlay
484
+ }) {
485
+ const htmlElement = useContext(overlay ? OverlayPortalContext : PortalContext);
486
+ const rootRef = useRef(null);
487
+ const preset = useViewerPreset();
488
+ useLayoutEffect(() => {
489
+ if (!rootRef.current) {
490
+ rootRef.current = htmlElement ? createRoot(htmlElement) : null;
491
+ }
492
+ }, []);
493
+ useLayoutEffect(() => {
494
+ return () => {
495
+ var _a;
496
+ (_a = rootRef.current) == null ? void 0 : _a.unmount();
497
+ rootRef.current = null;
498
+ };
499
+ }, []);
500
+ useLayoutEffect(() => {
501
+ if (rootRef.current) {
502
+ rootRef.current.render(/* @__PURE__ */ jsx(ViewerPresetContext.Provider, {
503
+ value: preset,
504
+ children
505
+ }));
506
+ }
507
+ }, [children, preset]);
508
+ return null;
509
+ }
510
+ function Viewer(_a) {
511
+ var _b = _a, {
512
+ children,
513
+ errorFallback,
514
+ outerContainerProps = {}
515
+ } = _b, props = __objRest(_b, [
516
+ "children",
517
+ "errorFallback",
518
+ "outerContainerProps"
519
+ ]);
520
+ const portal = useRef(null);
521
+ const [portalElement, setPortalElement] = useState();
522
+ const [viewerPreset, setViewerPreset] = useState();
523
+ const overlayPortal = useRef(null);
524
+ const [overlayPortalElement, setOverlayPortalElement] = useState();
525
+ const bridge = useContextBridge();
526
+ const ErrorFallback = errorFallback || DefaultCanvasFallback;
527
+ useLayoutEffect(() => {
528
+ setPortalElement(portal.current);
529
+ setOverlayPortalElement(overlayPortal.current);
530
+ }, []);
531
+ return /* @__PURE__ */ jsxs(ErrorBoundary, {
532
+ fallbackRender: () => /* @__PURE__ */ jsx(ErrorFallback, __spreadValues({}, props)),
533
+ children: [/* @__PURE__ */ jsx(AtlasAuto, __spreadProps(__spreadValues({}, props), {
534
+ containerProps: __spreadValues({
535
+ style: {
536
+ position: "relative"
537
+ }
538
+ }, props.containerProps || {}),
539
+ htmlChildren: /* @__PURE__ */ jsx("div", {
540
+ ref: overlayPortal
541
+ }),
542
+ onCreated: (preset) => {
543
+ setViewerPreset(preset);
544
+ if (props.onCreated) {
545
+ props.onCreated(preset);
546
+ }
547
+ },
548
+ children: /* @__PURE__ */ jsx(ViewerPresetContext.Provider, {
549
+ value: viewerPreset,
550
+ children: /* @__PURE__ */ jsx(PortalContext.Provider, {
551
+ value: portalElement,
552
+ children: /* @__PURE__ */ jsx(OverlayPortalContext.Provider, {
553
+ value: overlayPortalElement,
554
+ children: /* @__PURE__ */ jsx(ContextBridge, {
555
+ bridge,
556
+ children: /* @__PURE__ */ jsx(VirtualAnnotationProvider, {
557
+ children
558
+ })
559
+ })
560
+ })
561
+ })
562
+ })
563
+ })), /* @__PURE__ */ jsx("div", {
564
+ ref: portal
565
+ })]
566
+ });
567
+ }
568
+ function createEventsHelper(vault) {
569
+ return {
570
+ addEventListener(resource, event, listener, scope) {
571
+ if (!resource) {
572
+ return;
573
+ }
574
+ vault.setMetaValue([resource.id, "eventManager", event], (registeredCallbacks) => {
575
+ const callbacks = registeredCallbacks || [];
576
+ for (const registered of callbacks) {
577
+ if (registered.callback === listener) {
578
+ return callbacks;
579
+ }
580
+ }
581
+ return [...callbacks, { callback: listener, scope }];
582
+ });
583
+ return listener;
584
+ },
585
+ removeEventListener(resource, event, listener) {
586
+ if (!resource) {
587
+ return;
588
+ }
589
+ vault.setMetaValue([resource.id, "eventManager", event], (registeredCallbacks) => {
590
+ return (registeredCallbacks || []).filter((registeredCallback) => registeredCallback.callback !== listener);
591
+ });
592
+ },
593
+ getListenersAsProps(resourceOrId, scope) {
594
+ const resource = typeof resourceOrId === "string" ? { id: resourceOrId } : resourceOrId;
595
+ if (!resource || !resource.id) {
596
+ return {};
597
+ }
598
+ const hooks = vault.getResourceMeta(resource.id, "eventManager");
599
+ const props = {};
600
+ if (hooks && resource) {
601
+ for (const hook of Object.keys(hooks)) {
602
+ props[hook] = (e) => {
603
+ const fullResource = vault.get(resource);
604
+ for (const { callback, scope: _scope } of hooks[hook] || []) {
605
+ if (!_scope || scope && _scope.indexOf(scope) !== -1) {
606
+ callback(e, fullResource);
607
+ }
608
+ }
609
+ };
610
+ }
611
+ }
612
+ return props;
613
+ }
614
+ };
615
+ }
616
+ function useResourceEvents(resource, scope) {
617
+ const vault = useVault();
618
+ const helper = useMemo(() => createEventsHelper(vault), [vault]);
619
+ const hooks = useVaultSelector(() => {
620
+ if (resource && resource.id) {
621
+ return vault.getResourceMeta(resource.id, "eventManager");
622
+ }
623
+ return null;
624
+ }, [resource]);
625
+ return useMemo(() => {
626
+ return resource ? helper.getListenersAsProps(resource, scope) : {};
627
+ }, [hooks, resource, vault, scope]);
628
+ }
629
+ function createStylesHelper(vault) {
630
+ return {
631
+ applyStyles(resource, scope, styles) {
632
+ const id = typeof resource === "string" ? resource : resource.id;
633
+ return vault.setMetaValue([id, "styles", scope], styles);
634
+ },
635
+ getAppliedStyles(resource) {
636
+ const id = typeof resource === "string" ? resource : resource.id;
637
+ return vault.getResourceMeta(id, "styles");
638
+ }
639
+ };
640
+ }
641
+ function useStyles(resource, scope) {
642
+ const vault = useVault();
643
+ const helper = useMemo(() => createStylesHelper(vault), [vault]);
644
+ return useVaultSelector(() => {
645
+ if (!resource) {
646
+ return null;
647
+ }
648
+ const styles = helper.getAppliedStyles(resource.id);
649
+ return styles ? scope ? styles[scope] : styles : void 0;
650
+ }, [resource, scope]);
651
+ }
652
+ const BOX_SELECTOR = /&?(xywh=)?(pixel:|percent:|pct:)?([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?)/;
653
+ const TEMPORAL_SELECTOR = /&?(t=)(npt:)?([0-9]+(.[0-9]+)?)?(,([0-9]+(.[0-9]+)?))?/;
654
+ function parseSelector(source) {
655
+ if (Array.isArray(source)) {
656
+ return source.reduce((data, nextSource) => {
657
+ const { selector, selectors } = parseSelector(nextSource);
658
+ if (selector) {
659
+ if (!data.selector) {
660
+ data.selector = selector;
661
+ }
662
+ data.selectors.push(...selectors);
663
+ }
664
+ return data;
665
+ }, {
666
+ selector: null,
667
+ selectors: []
668
+ });
669
+ }
670
+ if (!source) {
671
+ return {
672
+ selector: null,
673
+ selectors: []
674
+ };
675
+ }
676
+ if (typeof source === "string") {
677
+ const [id, fragment] = source.split("#");
678
+ if (!fragment) {
679
+ return {
680
+ selector: null,
681
+ selectors: []
682
+ };
683
+ }
684
+ return parseSelector({ type: "FragmentSelector", value: fragment });
685
+ }
686
+ if (source.type === "PointSelector" && (source.t || source.t === 0)) {
687
+ const selector = {
688
+ type: "TemporalSelector",
689
+ temporal: {
690
+ startTime: source.t
691
+ }
692
+ };
693
+ return {
694
+ selector,
695
+ selectors: [selector]
696
+ };
697
+ }
698
+ if (source.type === "FragmentSelector") {
699
+ const matchBoxSelector = BOX_SELECTOR.exec(source.value);
700
+ if (matchBoxSelector) {
701
+ const selector = {
702
+ type: "BoxSelector",
703
+ spatial: {
704
+ unit: matchBoxSelector[2] === "percent:" || matchBoxSelector[2] === "pct:" ? "percent" : "pixel",
705
+ x: parseFloat(matchBoxSelector[3]),
706
+ y: parseFloat(matchBoxSelector[4]),
707
+ width: parseFloat(matchBoxSelector[5]),
708
+ height: parseFloat(matchBoxSelector[6])
709
+ }
710
+ };
711
+ return {
712
+ selector,
713
+ selectors: [selector]
714
+ };
715
+ }
716
+ const matchTimeSelector = source.value.match(TEMPORAL_SELECTOR);
717
+ if (matchTimeSelector) {
718
+ const selector = {
719
+ type: "TemporalSelector",
720
+ temporal: {
721
+ startTime: matchTimeSelector[4] ? parseFloat(matchTimeSelector[4]) : 0,
722
+ endTime: matchTimeSelector[7] ? parseFloat(matchTimeSelector[7]) : void 0
723
+ }
724
+ };
725
+ return {
726
+ selector,
727
+ selectors: [selector]
728
+ };
729
+ }
730
+ return {
731
+ selector: null,
732
+ selectors: []
733
+ };
734
+ }
735
+ return {
736
+ selector: null,
737
+ selectors: []
738
+ };
739
+ }
740
+ function expandTarget(target, options = {}) {
741
+ if (Array.isArray(target)) {
742
+ return expandTarget(target[0]);
743
+ }
744
+ if (typeof target === "string") {
745
+ const [id, fragment] = target.split("#");
746
+ if (!fragment) {
747
+ return {
748
+ type: "SpecificResource",
749
+ source: { id, type: options.typeMap && options.typeMap[id] || "Unknown" },
750
+ selector: null,
751
+ selectors: []
752
+ };
753
+ }
754
+ return expandTarget({
755
+ type: "SpecificResource",
756
+ source: { id, type: "Unknown" },
757
+ selector: {
758
+ type: "FragmentSelector",
759
+ value: fragment
760
+ }
761
+ });
762
+ }
763
+ if (target.type === "Choice" || target.type === "List" || target.type === "Composite" || target.type === "Independents") {
764
+ return expandTarget(target.items[0]);
765
+ }
766
+ if (target.type === "SpecificResource") {
767
+ if (target.source.type === "Canvas" && target.source.partOf && typeof target.source.partOf === "string") {
768
+ target.source.partOf = [
769
+ {
770
+ id: target.source.partOf,
771
+ type: "Manifest"
772
+ }
773
+ ];
774
+ }
775
+ const { selector, selectors } = target.selector ? parseSelector(target.selector) : { selector: null, selectors: [] };
776
+ return {
777
+ type: "SpecificResource",
778
+ source: target.source,
779
+ selector,
780
+ selectors
781
+ };
782
+ }
783
+ if (target.id) {
784
+ if (target.type === "Canvas" && target.partOf && typeof target.partOf === "string") {
785
+ target.partOf = [
786
+ {
787
+ id: target.partOf,
788
+ type: "Manifest"
789
+ }
790
+ ];
791
+ }
792
+ const [id, fragment] = target.id.split("#");
793
+ if (!fragment) {
794
+ return {
795
+ type: "SpecificResource",
796
+ source: __spreadProps(__spreadValues({}, target), {
797
+ id
798
+ }),
799
+ selector: null,
800
+ selectors: []
801
+ };
802
+ }
803
+ return expandTarget({
804
+ type: "SpecificResource",
805
+ source: __spreadProps(__spreadValues({}, target), {
806
+ id
807
+ }),
808
+ selector: {
809
+ type: "FragmentSelector",
810
+ value: fragment
811
+ }
812
+ });
813
+ }
814
+ return {
815
+ type: "SpecificResource",
816
+ source: target,
817
+ selector: null,
818
+ selectors: []
819
+ };
820
+ }
821
+ function useAnnotation(options = {}, deps = []) {
822
+ const { id, selector } = options;
823
+ const ctx = useResourceContext();
824
+ const vault = useVault();
825
+ const annotationId = id ? id : ctx.annotation;
826
+ const annotation = useVaultSelector((s) => annotationId ? s.iiif.entities.Annotation[annotationId] : void 0, [annotationId]);
827
+ const body = useVaultSelector((s) => annotation && annotation.body ? annotation.body.map((singleBody) => singleBody ? s.iiif.entities[singleBody.type][singleBody.id] : null).filter(Boolean) : [], [annotation]);
828
+ return useMemo(() => {
829
+ if (!annotation) {
830
+ return void 0;
831
+ }
832
+ const newAnnotation = __spreadProps(__spreadValues({}, annotation), {
833
+ body,
834
+ target: expandTarget(annotation.target, { typeMap: vault.getState().iiif.mapping })
835
+ });
836
+ if (selector) {
837
+ return selector(newAnnotation);
838
+ }
839
+ return newAnnotation;
840
+ }, [annotation, selector, body, ...deps]);
841
+ }
842
+ function useCanvas(options = {}, deps = []) {
843
+ const { id, selector } = options;
844
+ const ctx = useResourceContext();
845
+ const canvasId = id ? id : ctx.canvas;
846
+ const canvas = useVaultSelector((s) => canvasId ? s.iiif.entities.Canvas[canvasId] : void 0, [canvasId]);
847
+ return useMemo(() => {
848
+ if (!canvas) {
849
+ return void 0;
850
+ }
851
+ if (selector) {
852
+ return selector(canvas);
853
+ }
854
+ return canvas;
855
+ }, [canvas, selector, ...deps]);
856
+ }
857
+ const RenderAnnotation = ({
858
+ id,
859
+ style: defaultStyle,
860
+ className,
861
+ interactive
862
+ }) => {
863
+ const annotation = useAnnotation({
864
+ id
865
+ });
866
+ const style = useStyles(annotation, "atlas");
867
+ const html = useStyles(annotation, "html");
868
+ const events = useResourceEvents(annotation, ["atlas"]);
869
+ const canvas = useCanvas();
870
+ const allStyles = useMemo(() => {
871
+ return mergeStyles(defaultStyle, style);
872
+ }, [defaultStyle, style]);
873
+ const isValid = canvas && annotation && annotation.target && annotation.target.selector && annotation.target.selector.type === "BoxSelector" && annotation.target.source && annotation.target.source.id === canvas.id;
874
+ if (!isValid) {
875
+ return null;
876
+ }
877
+ return /* @__PURE__ */ jsx(RegionHighlight, __spreadValues({
878
+ id: annotation.id,
879
+ isEditing: true,
880
+ region: annotation.target.selector.spatial,
881
+ style: allStyles,
882
+ className: (html == null ? void 0 : html.className) || className,
883
+ interactive: !!((html == null ? void 0 : html.href) || interactive),
884
+ href: (html == null ? void 0 : html.href) || null,
885
+ title: (html == null ? void 0 : html.title) || null,
886
+ hrefTarget: (html == null ? void 0 : html.target) || null
887
+ }, events));
888
+ };
889
+ const RenderAnnotationPage = ({
890
+ className,
891
+ page
892
+ }) => {
893
+ var _a;
894
+ const style = useStyles(page, "atlas");
895
+ const html = useStyles(page, "html");
896
+ useVaultSelector((state) => page.id ? state.iiif.entities.AnnotationPage[page.id] : null, []);
897
+ return /* @__PURE__ */ jsx(Fragment$1, {
898
+ children: (_a = page.items) == null ? void 0 : _a.map((annotation) => {
899
+ return /* @__PURE__ */ jsx(RenderAnnotation, {
900
+ id: annotation.id,
901
+ style,
902
+ className: (html == null ? void 0 : html.className) || className
903
+ }, annotation.id);
904
+ })
905
+ });
906
+ };
907
+ function RenderImage({
908
+ id,
909
+ image,
910
+ thumbnail,
911
+ isStatic,
912
+ x = 0,
913
+ y = 0,
914
+ annotations,
915
+ children
916
+ }) {
917
+ var _a, _b, _c, _d;
918
+ return /* @__PURE__ */ jsx(Fragment$1, {
919
+ children: !image.service ? /* @__PURE__ */ jsxs(Fragment$1, {
920
+ children: [/* @__PURE__ */ jsx("world-image", {
921
+ uri: image.id,
922
+ target: image.target.spatial,
923
+ display: image.width && image.height ? {
924
+ width: image.width,
925
+ height: image.height
926
+ } : void 0
927
+ }), annotations, children]
928
+ }, "no-service") : /* @__PURE__ */ jsxs(Fragment$1, {
929
+ children: [/* @__PURE__ */ jsx(TileSet, {
930
+ tiles: {
931
+ id: image.service.id || image.service["@id"] || "unknown",
932
+ height: image.height,
933
+ width: image.width,
934
+ imageService: image.service,
935
+ thumbnail: thumbnail && thumbnail.type === "fixed" ? thumbnail : void 0
936
+ },
937
+ x: ((_a = image.target) == null ? void 0 : _a.spatial.x) + x,
938
+ y: ((_b = image.target) == null ? void 0 : _b.spatial.y) + y,
939
+ width: (_c = image.target) == null ? void 0 : _c.spatial.width,
940
+ height: (_d = image.target) == null ? void 0 : _d.spatial.height
941
+ }), annotations, children]
942
+ }, "service")
943
+ }, id);
944
+ }
945
+ function parseSpecificResource(resource) {
946
+ if (resource.type === "SpecificResource") {
947
+ return [resource.source, { selector: resource.selector }];
948
+ }
949
+ return [resource, { selector: null }];
950
+ }
951
+ function getPaintables(vault, paintingAnnotations, enabledChoices) {
952
+ const types = [];
953
+ let choice = null;
954
+ const items = [];
955
+ for (const annotation of paintingAnnotations) {
956
+ const bodies = vault.get(annotation.body);
957
+ for (const unknownBody of bodies) {
958
+ const [body, { selector }] = parseSpecificResource(unknownBody);
959
+ const type = (body.type || "unknown").toLowerCase();
960
+ if (type === "choice") {
961
+ const nestedBodies = vault.get(body.items);
962
+ const selected = enabledChoices.length ? enabledChoices.map((cid) => nestedBodies.find((b) => b.id === cid)).filter(Boolean) : [nestedBodies[0]];
963
+ if (selected.length === 0) {
964
+ selected.push(nestedBodies[0]);
965
+ }
966
+ choice = {
967
+ type: "single-choice",
968
+ items: nestedBodies.map((b) => ({
969
+ id: b.id,
970
+ label: b.label,
971
+ selected: selected.indexOf(b) !== -1
972
+ })),
973
+ label: unknownBody.label
974
+ };
975
+ bodies.push(...selected);
976
+ continue;
977
+ }
978
+ if (types.indexOf(type) === -1) {
979
+ types.push(type);
980
+ }
981
+ items.push({
982
+ type,
983
+ resource: body,
984
+ target: annotation.target,
985
+ selector
986
+ });
987
+ }
988
+ }
989
+ return {
990
+ types,
991
+ items,
992
+ choice
993
+ };
994
+ }
995
+ const emptyActions = {
996
+ makeChoice: () => {
997
+ }
998
+ };
999
+ const unknownResponse = { type: "unknown" };
1000
+ const unsupportedStrategy = (reason) => {
1001
+ return { type: "unknown", reason, annotations: { pages: [] } };
1002
+ };
1003
+ function useManifest(options = {}, deps = []) {
1004
+ const { id, selector } = options;
1005
+ const ctx = useResourceContext();
1006
+ useVault();
1007
+ const manifestId = id ? id : ctx.manifest;
1008
+ const manifest = useVaultSelector((s) => manifestId ? s.iiif.entities.Manifest[manifestId] : void 0, [manifestId]);
1009
+ return useMemo(() => {
1010
+ if (!manifest) {
1011
+ return void 0;
1012
+ }
1013
+ if (selector) {
1014
+ return selector(manifest);
1015
+ }
1016
+ return manifest;
1017
+ }, [manifest, selector, ...deps]);
1018
+ }
1019
+ function getMeta$1(state, resourceId) {
1020
+ var _a;
1021
+ const resourceMeta = (_a = state == null ? void 0 : state.iiif) == null ? void 0 : _a.meta[resourceId];
1022
+ if (!resourceMeta) {
1023
+ return null;
1024
+ }
1025
+ return resourceMeta.annotationPageManager;
1026
+ }
1027
+ function useEnabledAnnotationPageIds(resourceId, availablePageIds) {
1028
+ return useVaultSelector((state) => {
1029
+ const pageIds = [];
1030
+ if (!resourceId) {
1031
+ return pageIds;
1032
+ }
1033
+ const allAnnotationListIds = Object.keys(state.iiif.entities.AnnotationPage);
1034
+ for (const annotationListId of allAnnotationListIds) {
1035
+ if (!availablePageIds || availablePageIds.indexOf(annotationListId) !== -1) {
1036
+ const annotationListMeta = getMeta$1(state, annotationListId);
1037
+ if (annotationListMeta && annotationListMeta.views && annotationListMeta.views[resourceId]) {
1038
+ pageIds.push(annotationListId);
1039
+ }
1040
+ }
1041
+ }
1042
+ return pageIds;
1043
+ }, [resourceId, availablePageIds]);
1044
+ }
1045
+ function flattenAnnotationPageIds({
1046
+ canvas,
1047
+ manifest,
1048
+ all,
1049
+ canvases
1050
+ }) {
1051
+ const foundIds = [];
1052
+ if (manifest) {
1053
+ for (const page of manifest.annotations) {
1054
+ if (foundIds.indexOf(page.id) === -1) {
1055
+ foundIds.push(page.id);
1056
+ }
1057
+ }
1058
+ }
1059
+ if (all) {
1060
+ if (canvases && canvases.length) {
1061
+ for (const canvas_ of canvases) {
1062
+ for (const page of canvas_.annotations) {
1063
+ if (foundIds.indexOf(page.id) === -1) {
1064
+ foundIds.push(page.id);
1065
+ }
1066
+ }
1067
+ }
1068
+ }
1069
+ } else if (canvas) {
1070
+ for (const page of canvas.annotations) {
1071
+ if (foundIds.indexOf(page.id) === -1) {
1072
+ foundIds.push(page.id);
1073
+ }
1074
+ }
1075
+ }
1076
+ return foundIds;
1077
+ }
1078
+ function getMeta(state, resourceId) {
1079
+ var _a;
1080
+ const resourceMeta = (_a = state == null ? void 0 : state.iiif) == null ? void 0 : _a.meta[resourceId];
1081
+ if (!resourceMeta) {
1082
+ return null;
1083
+ }
1084
+ return resourceMeta.annotationPageManager;
1085
+ }
1086
+ function useAnnotationPageManager(resourceId, options = {}) {
1087
+ const vault = useVault();
1088
+ const manifest = useManifest();
1089
+ const canvas = useCanvas();
1090
+ const canvases = useVisibleCanvases();
1091
+ const availablePageIds = useMemo(() => {
1092
+ return flattenAnnotationPageIds({
1093
+ all: options.all,
1094
+ manifest,
1095
+ canvas,
1096
+ canvases
1097
+ });
1098
+ }, [options.all, canvas, canvases, manifest]);
1099
+ const enabledPageIds = useEnabledAnnotationPageIds(resourceId, options.all ? void 0 : availablePageIds);
1100
+ const setPageDisabled = useCallback((deselectId) => {
1101
+ if (!resourceId) {
1102
+ return;
1103
+ }
1104
+ vault.setMetaValue([deselectId, "annotationPageManager", "views"], (existingResources) => {
1105
+ if (existingResources && !existingResources[resourceId]) {
1106
+ return existingResources;
1107
+ }
1108
+ return __spreadProps(__spreadValues({}, existingResources || {}), {
1109
+ [resourceId]: false
1110
+ });
1111
+ });
1112
+ }, [resourceId, vault]);
1113
+ const setPageEnabled = useCallback((id, opt = {}) => {
1114
+ if (!resourceId) {
1115
+ return;
1116
+ }
1117
+ const state = vault.getState();
1118
+ const toDeselect = [];
1119
+ if (opt == null ? void 0 : opt.deselectOthers) {
1120
+ const allAnnotationListIds = Object.keys(state.iiif.entities.AnnotationPage);
1121
+ for (const annotationPageId of allAnnotationListIds) {
1122
+ const annotationListMeta = getMeta(state, annotationPageId);
1123
+ if (annotationListMeta && annotationListMeta.views && annotationListMeta.views[resourceId]) {
1124
+ toDeselect.push(annotationPageId);
1125
+ }
1126
+ }
1127
+ }
1128
+ for (const deselectId of toDeselect) {
1129
+ setPageDisabled(deselectId);
1130
+ }
1131
+ vault.setMetaValue([id, "annotationPageManager", "views"], (existingResources) => {
1132
+ if (existingResources && existingResources[resourceId]) {
1133
+ return existingResources;
1134
+ }
1135
+ return __spreadProps(__spreadValues({}, existingResources || {}), {
1136
+ [resourceId]: true
1137
+ });
1138
+ });
1139
+ }, [resourceId, setPageDisabled, vault]);
1140
+ return {
1141
+ availablePageIds,
1142
+ enabledPageIds,
1143
+ setPageEnabled,
1144
+ setPageDisabled
1145
+ };
1146
+ }
1147
+ function useResources(ids, type) {
1148
+ return useVaultSelector((state, vault) => vault.get(ids.map((id) => ({ id, type }))), [ids, type]);
1149
+ }
1150
+ const ImageServiceLoaderContext = React__default.createContext(new ImageServiceLoader());
1151
+ function useImageServiceLoader() {
1152
+ return useContext(ImageServiceLoaderContext);
1153
+ }
1154
+ function useLoadImageService() {
1155
+ const loader = useImageServiceLoader();
1156
+ const [imageServiceStatus, setImageServiceStatus] = useState({});
1157
+ const didUnmount = useRef(false);
1158
+ useEffect(() => {
1159
+ return () => {
1160
+ didUnmount.current = true;
1161
+ };
1162
+ }, []);
1163
+ const loadImageService = useCallback((imageService, { height, width }) => {
1164
+ if (imageService) {
1165
+ const imageServiceId = imageService.id || imageService["@id"];
1166
+ const syncLoaded = loader.loadServiceSync({
1167
+ id: imageServiceId,
1168
+ width: imageService.width || width,
1169
+ height: imageService.height || height,
1170
+ source: imageService
1171
+ });
1172
+ if (syncLoaded) {
1173
+ imageService = syncLoaded;
1174
+ } else if (!imageServiceStatus[imageServiceId]) {
1175
+ if (!didUnmount.current) {
1176
+ setImageServiceStatus((r) => {
1177
+ return __spreadProps(__spreadValues({}, r), {
1178
+ [imageServiceId]: "loading"
1179
+ });
1180
+ });
1181
+ }
1182
+ loader.loadService({
1183
+ id: imageServiceId,
1184
+ width: imageService.width || width,
1185
+ height: imageService.height || height
1186
+ }).then(() => {
1187
+ if (!didUnmount.current) {
1188
+ setImageServiceStatus((r) => {
1189
+ return __spreadProps(__spreadValues({}, r), {
1190
+ [imageServiceId]: "done"
1191
+ });
1192
+ });
1193
+ }
1194
+ });
1195
+ }
1196
+ }
1197
+ return imageService;
1198
+ }, [loader, imageServiceStatus]);
1199
+ return [loadImageService, imageServiceStatus];
1200
+ }
1201
+ function usePaintingAnnotations(options = {}) {
1202
+ const canvas = useCanvas(options.canvasId ? { id: options.canvasId } : void 0);
1203
+ return useVaultSelector((state, vault) => {
1204
+ if (!canvas) {
1205
+ return [];
1206
+ }
1207
+ const annotationPages = vault.get(canvas.items);
1208
+ const flatAnnotations = [];
1209
+ for (const page of annotationPages) {
1210
+ flatAnnotations.push(...vault.get(page.items));
1211
+ }
1212
+ return flatAnnotations;
1213
+ }, [canvas]);
1214
+ }
1215
+ function usePaintables(options, deps = []) {
1216
+ const vault = useVault();
1217
+ const paintingAnnotations = usePaintingAnnotations();
1218
+ const [enabledChoices, setEnabledChoices] = useState((options == null ? void 0 : options.defaultChoices) || []);
1219
+ const paintables = useMemo(() => getPaintables(vault, paintingAnnotations, enabledChoices), [vault, paintingAnnotations, enabledChoices, ...deps]);
1220
+ const makeChoice = useCallback((id, { deselectOthers = true, deselect = false } = {}) => {
1221
+ if (paintables.choice) {
1222
+ if (paintables.choice.type !== "single-choice") {
1223
+ throw new Error("Complex choice not supported yet");
1224
+ }
1225
+ setEnabledChoices((prevChoices) => {
1226
+ if (deselect) {
1227
+ const without = prevChoices.filter((e) => e !== id);
1228
+ if (without.length === 0) {
1229
+ const defaultId = paintables.items[0].resource.id;
1230
+ if (defaultId) {
1231
+ return [defaultId];
1232
+ } else {
1233
+ return [];
1234
+ }
1235
+ }
1236
+ return without;
1237
+ }
1238
+ if (deselectOthers) {
1239
+ return [id];
1240
+ }
1241
+ const newChoices = [...prevChoices];
1242
+ if (newChoices.length === 0 && paintables.items.length) {
1243
+ const defaultId = paintables.items[0].resource.id;
1244
+ if (defaultId) {
1245
+ newChoices.push(defaultId);
1246
+ }
1247
+ }
1248
+ if (prevChoices.indexOf(id) !== -1) {
1249
+ return prevChoices;
1250
+ }
1251
+ return [...prevChoices, id];
1252
+ });
1253
+ }
1254
+ }, [paintables.choice]);
1255
+ const actions = { makeChoice };
1256
+ return [paintables, actions];
1257
+ }
1258
+ function getImageStrategy(canvas, paintables, loadImageService) {
1259
+ const imageTypes = [];
1260
+ for (const singleImage of paintables.items) {
1261
+ const resource = singleImage.resource && singleImage.resource.type === "SpecificResource" ? singleImage.resource.source : singleImage.resource;
1262
+ if (!resource.id) {
1263
+ return unsupportedStrategy("No resource Identifier");
1264
+ }
1265
+ let imageService = void 0;
1266
+ if (resource.service) {
1267
+ const imageServices = getImageServices(resource);
1268
+ if (imageServices[0]) {
1269
+ imageService = loadImageService(imageServices[0], canvas);
1270
+ }
1271
+ }
1272
+ const { selector: imageTarget, source } = expandTarget(singleImage.target);
1273
+ if (source.id !== canvas.id) {
1274
+ continue;
1275
+ }
1276
+ const defaultTarget = {
1277
+ type: "BoxSelector",
1278
+ spatial: {
1279
+ x: 0,
1280
+ y: 0,
1281
+ width: canvas.width,
1282
+ height: canvas.height
1283
+ }
1284
+ };
1285
+ const target = imageTarget ? imageTarget.type === "TemporalSelector" ? {
1286
+ type: "TemporalBoxSelector",
1287
+ temporal: imageTarget.temporal,
1288
+ spatial: defaultTarget.spatial
1289
+ } : imageTarget : null;
1290
+ const defaultImageSelector = {
1291
+ type: "BoxSelector",
1292
+ spatial: {
1293
+ x: 0,
1294
+ y: 0,
1295
+ width: canvas.width,
1296
+ height: canvas.height
1297
+ }
1298
+ };
1299
+ const imageSelector = singleImage.resource.type === "SpecificResource" ? expandTarget(singleImage.resource) : null;
1300
+ const selector = imageSelector && imageSelector.selector && (imageSelector.selector.type === "BoxSelector" || imageSelector.selector.type === "TemporalBoxSelector") ? {
1301
+ type: "BoxSelector",
1302
+ spatial: {
1303
+ x: imageSelector.selector.spatial.x,
1304
+ y: imageSelector.selector.spatial.y,
1305
+ width: imageSelector.selector.spatial.width,
1306
+ height: imageSelector.selector.spatial.height
1307
+ }
1308
+ } : defaultImageSelector;
1309
+ if (imageService && !imageService.id) {
1310
+ imageService.id = imageService["@id"];
1311
+ }
1312
+ const imageType = {
1313
+ id: resource.id,
1314
+ type: "Image",
1315
+ width: target ? resource.width : canvas.width,
1316
+ height: target ? resource.height : canvas.height,
1317
+ service: imageService,
1318
+ sizes: imageService && imageService.sizes ? imageService.sizes : resource.width && resource.height ? [{ width: resource.width, height: resource.height }] : [],
1319
+ target: target && target.type !== "PointSelector" ? target : defaultTarget,
1320
+ selector
1321
+ };
1322
+ imageTypes.push(imageType);
1323
+ }
1324
+ return {
1325
+ type: "images",
1326
+ image: imageTypes[0],
1327
+ images: imageTypes,
1328
+ choice: paintables.choice
1329
+ };
1330
+ }
1331
+ const supportedFormats = ["model/gltf-binary"];
1332
+ function get3dStrategy(canvas, paintables) {
1333
+ const first = paintables.items[0];
1334
+ const resource = first.resource;
1335
+ if (!resource.format) {
1336
+ return unsupportedStrategy("Unknown format");
1337
+ }
1338
+ if (supportedFormats.indexOf(resource.format) === -1) {
1339
+ return unsupportedStrategy(`3D format: ${resource.format} is unsupported`);
1340
+ }
1341
+ return {
1342
+ type: "3d-model",
1343
+ model: resource
1344
+ };
1345
+ }
1346
+ function getAudioStrategy(canvas, paintables) {
1347
+ var _a;
1348
+ if (!canvas.duration) {
1349
+ return unsupportedStrategy("No duration on canvas");
1350
+ }
1351
+ if (paintables.items.length > 1) {
1352
+ return unsupportedStrategy("Only one audio source supported");
1353
+ }
1354
+ const audioResource = (_a = paintables.items[0]) == null ? void 0 : _a.resource;
1355
+ if (!audioResource) {
1356
+ return unsupportedStrategy("Unknown audio");
1357
+ }
1358
+ if (!audioResource.format) {
1359
+ return unsupportedStrategy("Audio does not have format");
1360
+ }
1361
+ return {
1362
+ type: "media",
1363
+ media: {
1364
+ duration: canvas.duration,
1365
+ url: audioResource.id,
1366
+ type: "Sound",
1367
+ target: {
1368
+ type: "TemporalSelector",
1369
+ temporal: {
1370
+ startTime: 0,
1371
+ endTime: canvas.duration
1372
+ }
1373
+ },
1374
+ format: audioResource.format,
1375
+ selector: {
1376
+ type: "TemporalSelector",
1377
+ temporal: {
1378
+ startTime: 0,
1379
+ endTime: canvas.duration
1380
+ }
1381
+ }
1382
+ },
1383
+ annotations: {
1384
+ pages: []
1385
+ }
1386
+ };
1387
+ }
1388
+ function getVideoStrategy(canvas, paintables) {
1389
+ var _a;
1390
+ const videoPaintables = paintables.items.filter((t) => t.type === "video");
1391
+ if (!canvas.duration) {
1392
+ return unsupportedStrategy("No duration on canvas");
1393
+ }
1394
+ if (videoPaintables.length > 1) {
1395
+ return unsupportedStrategy("Only one video source supported");
1396
+ }
1397
+ const audioResource = (_a = videoPaintables[0]) == null ? void 0 : _a.resource;
1398
+ if (!audioResource) {
1399
+ return unsupportedStrategy("Unknown video");
1400
+ }
1401
+ if (!audioResource.format) {
1402
+ return unsupportedStrategy("Video does not have format");
1403
+ }
1404
+ return {
1405
+ type: "media",
1406
+ media: {
1407
+ duration: canvas.duration,
1408
+ url: audioResource.id,
1409
+ type: "Video",
1410
+ items: [],
1411
+ target: {
1412
+ type: "TemporalSelector",
1413
+ temporal: {
1414
+ startTime: 0,
1415
+ endTime: canvas.duration
1416
+ }
1417
+ },
1418
+ format: audioResource.format,
1419
+ selector: {
1420
+ type: "TemporalSelector",
1421
+ temporal: {
1422
+ startTime: 0,
1423
+ endTime: canvas.duration
1424
+ }
1425
+ }
1426
+ },
1427
+ annotations: {
1428
+ pages: []
1429
+ }
1430
+ };
1431
+ }
1432
+ function useRenderingStrategy(options) {
1433
+ const manifest = useManifest();
1434
+ const canvas = useCanvas();
1435
+ const vault = useVault();
1436
+ const [loadImageService, imageServiceStatus] = useLoadImageService();
1437
+ const { enabledPageIds } = useAnnotationPageManager((options == null ? void 0 : options.annotationPageManagerId) || (manifest == null ? void 0 : manifest.id) || (canvas == null ? void 0 : canvas.id), {
1438
+ all: false
1439
+ });
1440
+ const enabledPages = useResources(enabledPageIds, "AnnotationPage");
1441
+ const supports = (options == null ? void 0 : options.strategies) || ["images", "media", "complex-timeline"];
1442
+ const [paintables, actions] = usePaintables(options, [imageServiceStatus]);
1443
+ const strategy = useMemo(() => {
1444
+ if (!canvas || paintables.types.length === 0) {
1445
+ return unknownResponse;
1446
+ }
1447
+ if (paintables.types.length !== 1) {
1448
+ if (paintables.types.length === 2 && paintables.types.indexOf("text") !== -1) {
1449
+ paintables.types = paintables.types.filter((t) => t !== "text");
1450
+ } else {
1451
+ if (supports.indexOf("complex-timeline") === -1) {
1452
+ return unsupportedStrategy("Complex timeline not supported");
1453
+ }
1454
+ return unsupportedStrategy("ComplexTimelineStrategy not yet supported");
1455
+ }
1456
+ }
1457
+ const mainType = paintables.types[0];
1458
+ if (mainType === "image") {
1459
+ if (supports.indexOf("images") === -1) {
1460
+ return unsupportedStrategy("Image not supported");
1461
+ }
1462
+ return getImageStrategy(canvas, paintables, loadImageService);
1463
+ }
1464
+ if (mainType === "Model" || mainType === "model") {
1465
+ if (supports.indexOf("3d-model") === -1) {
1466
+ return unsupportedStrategy("3D not supported");
1467
+ }
1468
+ return get3dStrategy(canvas, paintables);
1469
+ }
1470
+ if (mainType === "sound" || mainType === "audio") {
1471
+ if (supports.indexOf("media") === -1) {
1472
+ return unsupportedStrategy("Media not supported");
1473
+ }
1474
+ return getAudioStrategy(canvas, paintables);
1475
+ }
1476
+ if (mainType === "video") {
1477
+ if (supports.indexOf("media") === -1) {
1478
+ return unsupportedStrategy("Media not supported");
1479
+ }
1480
+ return getVideoStrategy(canvas, paintables);
1481
+ }
1482
+ return unknownResponse;
1483
+ }, [canvas, paintables, vault, actions.makeChoice]);
1484
+ return useMemo(() => {
1485
+ if (strategy.type === "unknown") {
1486
+ return [strategy, emptyActions];
1487
+ }
1488
+ return [
1489
+ __spreadProps(__spreadValues({}, strategy), {
1490
+ annotations: { pages: enabledPages }
1491
+ }),
1492
+ actions
1493
+ ];
1494
+ }, [strategy, enabledPages]);
1495
+ }
1496
+ const useVaultEffect = (callback, deps = []) => {
1497
+ const vault = useVault();
1498
+ useEffect(() => {
1499
+ callback(vault);
1500
+ }, [vault, ...deps]);
1501
+ };
1502
+ function createThumbnailHelper(vault, dependencies = {}) {
1503
+ const imageServiceLoader = dependencies.imageServiceLoader || new ImageServiceLoader();
1504
+ async function getBestThumbnailAtSize(input, request, dereference, candidates = [], dimensions) {
1505
+ if (typeof input === "string") {
1506
+ return { best: getFixedSizeFromImage(input), fallback: [], log: [] };
1507
+ }
1508
+ const fullInput = vault.get(input);
1509
+ if (typeof fullInput === "string") {
1510
+ return { best: getFixedSizeFromImage(fullInput), fallback: [], log: [] };
1511
+ }
1512
+ switch (fullInput.type) {
1513
+ case "Annotation": {
1514
+ const contentResources = fullInput.body;
1515
+ const firstContentResources = vault.get(contentResources[0]);
1516
+ if (dimensions && !firstContentResources.width) {
1517
+ firstContentResources.width = dimensions.width;
1518
+ firstContentResources.height = dimensions.height;
1519
+ }
1520
+ return await imageServiceLoader.getThumbnailFromResource(firstContentResources, request, dereference, candidates);
1521
+ }
1522
+ case "Canvas": {
1523
+ const canvas = fullInput;
1524
+ if (canvas.thumbnail && canvas.thumbnail.length) {
1525
+ const thumbnail = vault.get(canvas.thumbnail[0]);
1526
+ const potentialThumbnails = await imageServiceLoader.getImageCandidates(thumbnail, dereference);
1527
+ if (potentialThumbnails && potentialThumbnails.length) {
1528
+ candidates.push(...potentialThumbnails);
1529
+ }
1530
+ }
1531
+ return getBestThumbnailAtSize(canvas.items[0], request, dereference, candidates, {
1532
+ width: canvas.width,
1533
+ height: canvas.height
1534
+ });
1535
+ }
1536
+ case "AnnotationPage": {
1537
+ const annotationPage = fullInput;
1538
+ return getBestThumbnailAtSize(annotationPage.items[0], request, dereference, candidates, dimensions);
1539
+ }
1540
+ case "Choice": {
1541
+ const choice = fullInput;
1542
+ return getBestThumbnailAtSize(choice.items[0], request, dereference, candidates, dimensions);
1543
+ }
1544
+ case "Collection": {
1545
+ const collection = fullInput;
1546
+ const firstManifest = collection.items[0];
1547
+ return getBestThumbnailAtSize(firstManifest, request, dereference, candidates, dimensions);
1548
+ }
1549
+ case "Manifest": {
1550
+ const manifest = fullInput;
1551
+ const firstCanvas = manifest.items[0];
1552
+ return getBestThumbnailAtSize(firstCanvas, request, dereference, candidates, dimensions);
1553
+ }
1554
+ case "SpecificResource":
1555
+ case "Image":
1556
+ case "Dataset":
1557
+ case "Sound":
1558
+ case "Text":
1559
+ case "TextualBody":
1560
+ case "Video":
1561
+ if (dimensions && !fullInput.width) {
1562
+ fullInput.width = dimensions.width;
1563
+ fullInput.height = dimensions.height;
1564
+ }
1565
+ return imageServiceLoader.getThumbnailFromResource(fullInput, request, dereference, candidates);
1566
+ case "Service":
1567
+ case "Range":
1568
+ case "AnnotationCollection":
1569
+ case "CanvasReference":
1570
+ case "ContentResource":
1571
+ return { best: void 0, fallback: [], log: [] };
1572
+ }
1573
+ return { best: void 0, fallback: [], log: [] };
1574
+ }
1575
+ return {
1576
+ getBestThumbnailAtSize
1577
+ };
1578
+ }
1579
+ function useThumbnail(request, dereference, { canvasId, manifestId } = {}) {
1580
+ const vault = useVault();
1581
+ const loader = useImageServiceLoader();
1582
+ const helper = useMemo(() => createThumbnailHelper(vault, { imageServiceLoader: loader }), [vault, loader]);
1583
+ const [thumbnail, setThumbnail] = useState();
1584
+ const manifest = useManifest(manifestId ? { id: manifestId } : void 0);
1585
+ const canvas = useCanvas(canvasId ? { id: canvasId } : void 0);
1586
+ const subject = canvas ? canvas : manifest;
1587
+ const didUnmount = useRef(false);
1588
+ useEffect(() => {
1589
+ return () => {
1590
+ didUnmount.current = true;
1591
+ };
1592
+ }, []);
1593
+ if (!subject) {
1594
+ throw new Error("Must be called under a manifest or canvas context.");
1595
+ }
1596
+ useVaultEffect((v) => {
1597
+ helper.getBestThumbnailAtSize(subject, request, dereference).then((thumb) => {
1598
+ if (thumb.best && !didUnmount.current) {
1599
+ setThumbnail(thumb.best);
1600
+ }
1601
+ });
1602
+ }, [subject]);
1603
+ return thumbnail;
1604
+ }
1605
+ function getDefaultState(duration) {
1606
+ return { isMuted: false, playRequested: false, isPlaying: false, isFinished: false, volume: 100, duration };
1607
+ }
1608
+ function reducer(state, action) {
1609
+ switch (action.type) {
1610
+ case "FINISHED":
1611
+ return __spreadProps(__spreadValues({}, state), { isFinished: true, isPlaying: false, playRequested: false });
1612
+ case "PLAY_PAUSE":
1613
+ return __spreadProps(__spreadValues({}, state), { isFinished: false, isPlaying: !state.isPlaying });
1614
+ case "PLAY_REQUESTED":
1615
+ return __spreadProps(__spreadValues({}, state), { isFinished: false, playRequested: true });
1616
+ case "PAUSE":
1617
+ return __spreadProps(__spreadValues({}, state), { isPlaying: false });
1618
+ case "PLAY":
1619
+ return __spreadProps(__spreadValues({}, state), { isFinished: false, playRequested: false, isPlaying: true });
1620
+ case "MUTE":
1621
+ return __spreadProps(__spreadValues({}, state), { isMuted: true });
1622
+ case "SET_VOLUME":
1623
+ return __spreadProps(__spreadValues({}, state), { volume: action.volume, isMuted: action.volume === 0 });
1624
+ case "TOGGLE_MUTE":
1625
+ return __spreadProps(__spreadValues({}, state), { isMuted: !state.isMuted });
1626
+ case "UNMUTE":
1627
+ return __spreadProps(__spreadValues({}, state), { isMuted: false });
1628
+ }
1629
+ return state;
1630
+ }
1631
+ function formatTime(time) {
1632
+ const seconds = Math.round(time);
1633
+ return `${Math.floor(seconds / 60)}:${`${seconds % 60}`.padStart(2, "0")}`;
1634
+ }
1635
+ function useSimpleMediaPlayer(props) {
1636
+ const [state, dispatch] = useReducer(reducer, getDefaultState(props.duration));
1637
+ const media = useRef(null);
1638
+ const currentTime = useRef(null);
1639
+ const progress = useRef(null);
1640
+ const _isMuted = useRef(false);
1641
+ const _updateCurrentTime = useCallback(() => {
1642
+ if (currentTime.current && media.current) {
1643
+ currentTime.current.innerHTML = formatTime(media.current.currentTime);
1644
+ if (progress.current) {
1645
+ progress.current.style.width = `${media.current.currentTime / props.duration * 100}%`;
1646
+ }
1647
+ if (_isMuted.current !== media.current.muted) {
1648
+ _isMuted.current = media.current.muted;
1649
+ dispatch(media.current.muted ? { type: "MUTE" } : { type: "UNMUTE" });
1650
+ }
1651
+ }
1652
+ }, [props.duration]);
1653
+ const play = useCallback(() => {
1654
+ if (media.current) {
1655
+ dispatch({ type: "PLAY_REQUESTED" });
1656
+ media.current.play().then(() => {
1657
+ dispatch({ type: "PLAY" });
1658
+ });
1659
+ _updateCurrentTime();
1660
+ }
1661
+ }, [_updateCurrentTime]);
1662
+ const playPause = useCallback(() => {
1663
+ if (media.current) {
1664
+ if (media.current.duration > 0 && media.current.paused) {
1665
+ play();
1666
+ } else {
1667
+ pause();
1668
+ }
1669
+ }
1670
+ }, [_updateCurrentTime]);
1671
+ const pause = useCallback(() => {
1672
+ if (media.current) {
1673
+ media.current.pause();
1674
+ dispatch({ type: "PAUSE" });
1675
+ _updateCurrentTime();
1676
+ }
1677
+ }, [_updateCurrentTime]);
1678
+ const toggleMute = useCallback(() => {
1679
+ if (media.current) {
1680
+ media.current.muted = !media.current.muted;
1681
+ dispatch(media.current.muted ? { type: "MUTE" } : { type: "UNMUTE" });
1682
+ }
1683
+ }, []);
1684
+ const mute = useCallback(() => {
1685
+ if (media.current) {
1686
+ media.current.muted = true;
1687
+ dispatch({ type: "MUTE" });
1688
+ }
1689
+ }, []);
1690
+ const unmute = useCallback(() => {
1691
+ if (media.current) {
1692
+ media.current.muted = false;
1693
+ dispatch({ type: "UNMUTE" });
1694
+ }
1695
+ }, []);
1696
+ const setVolume = useCallback((newVolume) => {
1697
+ if (media.current) {
1698
+ media.current.muted = false;
1699
+ media.current.volume = newVolume / 100;
1700
+ dispatch({ type: "SET_VOLUME", volume: newVolume });
1701
+ }
1702
+ }, []);
1703
+ const setDurationPercent = useCallback((percent) => {
1704
+ if (media.current) {
1705
+ media.current.currentTime = Math.max(0, Math.min(percent * props.duration, props.duration));
1706
+ _updateCurrentTime();
1707
+ }
1708
+ }, []);
1709
+ const setTime = useCallback((time) => {
1710
+ if (media.current) {
1711
+ media.current.currentTime = Math.max(0, Math.min(time, props.duration));
1712
+ _updateCurrentTime();
1713
+ }
1714
+ }, []);
1715
+ useEffect(() => {
1716
+ const interval = setInterval(() => {
1717
+ _updateCurrentTime();
1718
+ }, 350);
1719
+ return () => clearInterval(interval);
1720
+ }, [_updateCurrentTime, props.duration]);
1721
+ useEffect(() => {
1722
+ const ended = () => {
1723
+ dispatch({ type: "FINISHED" });
1724
+ };
1725
+ const _media = media.current;
1726
+ _media == null ? void 0 : _media.addEventListener("ended", ended);
1727
+ return () => _media == null ? void 0 : _media.removeEventListener("ended", ended);
1728
+ }, []);
1729
+ return [
1730
+ { element: media, currentTime, progress },
1731
+ state,
1732
+ {
1733
+ play,
1734
+ pause,
1735
+ playPause,
1736
+ mute,
1737
+ unmute,
1738
+ toggleMute,
1739
+ setVolume,
1740
+ setDurationPercent,
1741
+ setTime
1742
+ }
1743
+ ];
1744
+ }
1745
+ const MediaReactContextState = createContext(null);
1746
+ const MediaReactContextActions = createContext(null);
1747
+ const MediaReactContextElements = createContext(null);
1748
+ function MediaPlayerProvider({
1749
+ actions,
1750
+ state,
1751
+ children,
1752
+ currentTime,
1753
+ progress,
1754
+ element
1755
+ }) {
1756
+ return /* @__PURE__ */ jsx(MediaReactContextElements.Provider, {
1757
+ value: {
1758
+ currentTime,
1759
+ progress,
1760
+ element
1761
+ },
1762
+ children: /* @__PURE__ */ jsx(MediaReactContextActions.Provider, {
1763
+ value: actions,
1764
+ children: /* @__PURE__ */ jsx(MediaReactContextState.Provider, {
1765
+ value: state,
1766
+ children
1767
+ })
1768
+ })
1769
+ });
1770
+ }
1771
+ function Audio({
1772
+ media,
1773
+ children
1774
+ }) {
1775
+ const [{
1776
+ element,
1777
+ currentTime,
1778
+ progress
1779
+ }, state, actions] = useSimpleMediaPlayer({
1780
+ duration: media.duration
1781
+ });
1782
+ return /* @__PURE__ */ jsx(Fragment, {
1783
+ children: /* @__PURE__ */ jsx(CanvasPortal, {
1784
+ children: /* @__PURE__ */ jsxs(MediaPlayerProvider, {
1785
+ state,
1786
+ actions,
1787
+ currentTime,
1788
+ progress,
1789
+ element,
1790
+ children: [/* @__PURE__ */ jsx("audio", {
1791
+ ref: element,
1792
+ src: media.url
1793
+ }), children]
1794
+ })
1795
+ })
1796
+ });
1797
+ }
1798
+ function Video({
1799
+ media,
1800
+ children
1801
+ }) {
1802
+ const [{
1803
+ element,
1804
+ currentTime,
1805
+ progress
1806
+ }, state, actions] = useSimpleMediaPlayer({
1807
+ duration: media.duration
1808
+ });
1809
+ const Component = "div";
1810
+ return /* @__PURE__ */ jsxs(Fragment, {
1811
+ children: [/* @__PURE__ */ jsxs(CanvasPortal, {
1812
+ overlay: true,
1813
+ children: [/* @__PURE__ */ jsx("style", {
1814
+ children: `
1815
+ .video-container {
1816
+ position: absolute;
1817
+ top: 0;
1818
+ bottom: 0;
1819
+ left: 0;
1820
+ right: 0;
1821
+ background: #000;
1822
+ z-index: 13;
1823
+ display: flex;
1824
+ justify-content: center;
1825
+ pointer-events: visible;
1826
+ }
1827
+ `
1828
+ }), /* @__PURE__ */ jsx(Component, {
1829
+ className: "video-container",
1830
+ part: "video-container",
1831
+ onClick: () => actions.playPause(),
1832
+ children: /* @__PURE__ */ jsx("video", {
1833
+ ref: element,
1834
+ src: media.url,
1835
+ style: {
1836
+ width: "100%",
1837
+ objectFit: "contain"
1838
+ }
1839
+ })
1840
+ })]
1841
+ }), /* @__PURE__ */ jsx(CanvasPortal, {
1842
+ children: /* @__PURE__ */ jsx(MediaPlayerProvider, {
1843
+ state,
1844
+ actions,
1845
+ currentTime,
1846
+ progress,
1847
+ element,
1848
+ children
1849
+ })
1850
+ })]
1851
+ });
1852
+ }
1853
+ function Model({
1854
+ model
1855
+ }) {
1856
+ return /* @__PURE__ */ jsxs(CanvasPortal, {
1857
+ overlay: true,
1858
+ children: [/* @__PURE__ */ jsx("style", {
1859
+ children: `
1860
+ .model-container {
1861
+ position: absolute;
1862
+ top: 0;
1863
+ bottom: 0;
1864
+ left: 0;
1865
+ right: 0;
1866
+ background: #000;
1867
+ z-index: 13;
1868
+ display: flex;
1869
+ justify-content: center;
1870
+ pointer-events: visible;
1871
+ }
1872
+ `
1873
+ }), /* @__PURE__ */ jsx("div", {
1874
+ className: "model-container",
1875
+ children: /* @__PURE__ */ jsx("model-viewer", {
1876
+ "interaction-prompt": "none",
1877
+ style: {
1878
+ width: "100%",
1879
+ height: "100%"
1880
+ },
1881
+ "camera-controls": "",
1882
+ "ar-status": "not-presenting",
1883
+ src: model.id
1884
+ })
1885
+ })]
1886
+ });
1887
+ }
1888
+ function RenderCanvas({
1889
+ x,
1890
+ y,
1891
+ onChoiceChange,
1892
+ registerActions,
1893
+ defaultChoices,
1894
+ isStatic,
1895
+ renderViewerControls,
1896
+ renderMediaControls,
1897
+ strategies,
1898
+ children
1899
+ }) {
1900
+ const canvas = useCanvas();
1901
+ const elementProps = useResourceEvents(canvas, ["deep-zoom"]);
1902
+ const [virtualPage] = useVirtualAnnotationPageContext();
1903
+ const vault = useVault();
1904
+ const helper = useMemo(() => createStylesHelper(vault), [vault]);
1905
+ const [strategy, actions] = useRenderingStrategy({
1906
+ strategies: strategies || ["images"],
1907
+ defaultChoices: defaultChoices == null ? void 0 : defaultChoices.map(({
1908
+ id
1909
+ }) => id)
1910
+ });
1911
+ const choice = strategy.type === "images" ? strategy.choice : void 0;
1912
+ useEffect(() => {
1913
+ if (registerActions) {
1914
+ registerActions(actions);
1915
+ }
1916
+ }, [strategy.annotations]);
1917
+ useEffect(() => {
1918
+ if (defaultChoices) {
1919
+ for (const choice2 of defaultChoices) {
1920
+ if (typeof choice2.opacity !== "undefined") {
1921
+ helper.applyStyles({
1922
+ id: choice2.id
1923
+ }, "atlas", {
1924
+ opacity: choice2.opacity
1925
+ });
1926
+ }
1927
+ }
1928
+ }
1929
+ }, [defaultChoices]);
1930
+ useLayoutEffect(() => {
1931
+ if (onChoiceChange) {
1932
+ onChoiceChange(choice);
1933
+ }
1934
+ }, [choice]);
1935
+ const thumbnail = useThumbnail({
1936
+ maxWidth: 256,
1937
+ maxHeight: 256
1938
+ });
1939
+ if (!canvas) {
1940
+ return null;
1941
+ }
1942
+ const accompanyingCanvas = canvas.accompanyingCanvas;
1943
+ const thumbnailFallbackImage = thumbnail && thumbnail.type === "fixed" ? /* @__PURE__ */ jsx("world-object", {
1944
+ height: canvas.height,
1945
+ width: canvas.width,
1946
+ x,
1947
+ y,
1948
+ children: /* @__PURE__ */ jsx("world-image", {
1949
+ uri: thumbnail.id,
1950
+ target: {
1951
+ x: 0,
1952
+ y: 0,
1953
+ width: canvas.width,
1954
+ height: canvas.height
1955
+ },
1956
+ display: thumbnail.width && thumbnail.height ? {
1957
+ width: thumbnail.width,
1958
+ height: thumbnail.height
1959
+ } : void 0
1960
+ })
1961
+ }) : null;
1962
+ if (strategy.type === "unknown") {
1963
+ if (thumbnailFallbackImage) {
1964
+ return thumbnailFallbackImage;
1965
+ }
1966
+ throw new Error(strategy.reason || "Unknown image strategy");
1967
+ }
1968
+ const annotations = /* @__PURE__ */ jsxs(Fragment$1, {
1969
+ children: [virtualPage ? /* @__PURE__ */ jsx(RenderAnnotationPage, {
1970
+ page: virtualPage
1971
+ }) : null, strategy.annotations && strategy.annotations.pages ? strategy.annotations.pages.map((page) => {
1972
+ return /* @__PURE__ */ jsx(RenderAnnotationPage, {
1973
+ page
1974
+ }, page.id);
1975
+ }) : null, children]
1976
+ });
1977
+ return /* @__PURE__ */ jsxs(Fragment, {
1978
+ children: [/* @__PURE__ */ jsxs("world-object", __spreadProps(__spreadValues({
1979
+ height: canvas.height,
1980
+ width: canvas.width,
1981
+ x,
1982
+ y
1983
+ }, elementProps), {
1984
+ children: [strategy.type === "images" ? /* @__PURE__ */ jsxs(Fragment, {
1985
+ children: [strategy.images.map((image, idx) => {
1986
+ return /* @__PURE__ */ jsx(RenderImage, {
1987
+ isStatic,
1988
+ image,
1989
+ id: image.id,
1990
+ thumbnail: idx === 0 ? thumbnail : void 0,
1991
+ annotations
1992
+ }, image.id);
1993
+ }), renderViewerControls ? /* @__PURE__ */ jsx(CanvasPortal, {
1994
+ overlay: true,
1995
+ children: renderViewerControls(strategy)
1996
+ }) : null]
1997
+ }) : null, strategy.type === "3d-model" ? /* @__PURE__ */ jsx(Model, {
1998
+ model: strategy.model
1999
+ }) : null, strategy.type === "media" ? /* @__PURE__ */ jsx(Fragment, {
2000
+ children: strategy.media.type === "Sound" ? /* @__PURE__ */ jsxs(Audio, {
2001
+ media: strategy.media,
2002
+ children: [thumbnailFallbackImage, renderMediaControls ? renderMediaControls(strategy) : null]
2003
+ }) : strategy.media.type === "Video" ? /* @__PURE__ */ jsxs(Video, {
2004
+ media: strategy.media,
2005
+ children: [thumbnailFallbackImage, renderMediaControls ? renderMediaControls(strategy) : null]
2006
+ }) : null
2007
+ }) : null]
2008
+ }), strategy.type), strategy.type === "media" && strategy.media.type === "Sound" && accompanyingCanvas ? /* @__PURE__ */ jsx(CanvasContext, {
2009
+ canvas: accompanyingCanvas.id,
2010
+ children: /* @__PURE__ */ jsx(RenderCanvas, {
2011
+ renderViewerControls
2012
+ })
2013
+ }) : null]
2014
+ });
2015
+ }
2016
+ const CanvasPanel = {
2017
+ RenderImage,
2018
+ RenderCanvas,
2019
+ RenderAnnotationPage,
2020
+ RenderAnnotation,
2021
+ Viewer
2022
+ };
2023
+ export { CanvasPanel };
2024
+ //# sourceMappingURL=canvas-panel.mjs.map