react-iiif-vault 0.9.11 → 0.9.14

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