@atlaskit/media-viewer 54.11.28 → 54.12.1

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 (39) hide show
  1. package/AGENTS.md +21 -1
  2. package/CHANGELOG.md +50 -0
  3. package/dist/cjs/ItemViewerBase.js +3 -5
  4. package/dist/cjs/analytics/events/operational/preload.js +66 -0
  5. package/dist/cjs/analytics/ufoExperiences.js +1 -1
  6. package/dist/cjs/chunkLoaders.js +28 -0
  7. package/dist/cjs/components/media-viewer-loader.js +4 -5
  8. package/dist/cjs/preload.js +200 -0
  9. package/dist/cjs/viewers/image/imageRequestParams.js +26 -0
  10. package/dist/cjs/viewers/image/index.js +87 -27
  11. package/dist/cjs/warmedImages.js +177 -0
  12. package/dist/es2019/ItemViewerBase.js +3 -3
  13. package/dist/es2019/analytics/events/operational/preload.js +61 -0
  14. package/dist/es2019/analytics/ufoExperiences.js +1 -1
  15. package/dist/es2019/chunkLoaders.js +11 -0
  16. package/dist/es2019/components/media-viewer-loader.js +2 -1
  17. package/dist/es2019/preload.js +185 -0
  18. package/dist/es2019/viewers/image/imageRequestParams.js +18 -0
  19. package/dist/es2019/viewers/image/index.js +59 -7
  20. package/dist/es2019/warmedImages.js +157 -0
  21. package/dist/esm/ItemViewerBase.js +3 -3
  22. package/dist/esm/analytics/events/operational/preload.js +61 -0
  23. package/dist/esm/analytics/ufoExperiences.js +1 -1
  24. package/dist/esm/chunkLoaders.js +15 -0
  25. package/dist/esm/components/media-viewer-loader.js +2 -1
  26. package/dist/esm/preload.js +193 -0
  27. package/dist/esm/viewers/image/imageRequestParams.js +20 -0
  28. package/dist/esm/viewers/image/index.js +87 -27
  29. package/dist/esm/warmedImages.js +170 -0
  30. package/dist/types/MediaViewerError.d.ts +1 -1
  31. package/dist/types/analytics/events/operational/_mediaFile.d.ts +1 -1
  32. package/dist/types/analytics/events/operational/preload.d.ts +36 -0
  33. package/dist/types/chunkLoaders.d.ts +10 -0
  34. package/dist/types/preload.d.ts +58 -0
  35. package/dist/types/viewers/image/imageRequestParams.d.ts +15 -0
  36. package/dist/types/viewers/image/index.d.ts +2 -0
  37. package/dist/types/warmedImages.d.ts +60 -0
  38. package/package.json +6 -6
  39. package/preload/package.json +10 -0
@@ -16,7 +16,9 @@ import { fg } from '@atlaskit/platform-feature-flags/fg';
16
16
  import { buildImgErrorDiagnostics } from '../../buildImgErrorDiagnostics';
17
17
  import { Outcome } from '../../domain/outcome';
18
18
  import { MediaViewerError } from '../../MediaViewerError';
19
+ import { getWarmedImageKey, hasWarmedImageForFile, takeWarmedImage } from '../../warmedImages';
19
20
  import { BaseViewer } from '../base-viewer';
21
+ import { getImageViewerRequestParams, IMAGE_VIEWER_FETCH_MAX_RES } from './imageRequestParams';
20
22
  import { InteractiveImg } from './interactive-img';
21
23
  function processedFileStateToMediaItem(file) {
22
24
  return {
@@ -34,6 +36,8 @@ export var ImageViewer = /*#__PURE__*/function (_BaseViewer) {
34
36
  args[_key] = arguments[_key];
35
37
  }
36
38
  _this = _callSuper(this, ImageViewer, [].concat(args));
39
+ /** Counts `init` calls, so an `init` that a reset has replaced can tell it is stale. */
40
+ _defineProperty(_this, "initRuns", 0);
37
41
  _defineProperty(_this, "onLoad", function () {
38
42
  _this.props.onLoad();
39
43
  _this.onMediaDisplayed();
@@ -61,10 +65,11 @@ export var ImageViewer = /*#__PURE__*/function (_BaseViewer) {
61
65
  key: "init",
62
66
  value: function () {
63
67
  var _init = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
64
- var _this$props, fileState, mediaClient, collectionName, traceContext, controller, orientation, objectUrl, originalBinaryImageUrl, isLocalFileReference, clientId, renderedBlobMimeType, preview, _yield$preview, value, origin, item, response, blob, effectiveMimeType, unsupportedError, imgError, _t, _t2;
68
+ var initRun, _this$props, fileState, mediaClient, collectionName, traceContext, controller, orientation, objectUrl, originalBinaryImageUrl, isLocalFileReference, clientId, renderedBlobMimeType, preview, _yield$preview, value, origin, warmed, watermarkVersion, blob, item, response, effectiveMimeType, unsupportedError, imgError, _t, _t2, _t3, _t4;
65
69
  return _regeneratorRuntime.wrap(function (_context) {
66
70
  while (1) switch (_context.prev = _context.next) {
67
71
  case 0:
72
+ initRun = this.initRuns += 1;
68
73
  _this$props = this.props, fileState = _this$props.item, mediaClient = _this$props.mediaClient, collectionName = _this$props.collectionName, traceContext = _this$props.traceContext;
69
74
  if (!isErrorFileState(fileState)) {
70
75
  _context.next = 1;
@@ -114,56 +119,111 @@ export var ImageViewer = /*#__PURE__*/function (_BaseViewer) {
114
119
  case 9:
115
120
  objectUrl = value;
116
121
  case 10:
117
- _context.next = 14;
122
+ _context.next = 25;
118
123
  break;
119
124
  case 11:
120
125
  if (!isImageRepresentationReady(fileState)) {
121
- _context.next = 13;
126
+ _context.next = 24;
127
+ break;
128
+ }
129
+ if (!hasWarmedImageForFile({
130
+ id: fileState.id,
131
+ collectionName: collectionName
132
+ })) {
133
+ _context.next = 16;
134
+ break;
135
+ }
136
+ _context.prev = 12;
137
+ _context.next = 13;
138
+ return mediaClient.getImageWatermarkVersion(collectionName);
139
+ case 13:
140
+ watermarkVersion = _context.sent;
141
+ if (!(!this.mounted || initRun !== this.initRuns)) {
142
+ _context.next = 14;
143
+ break;
144
+ }
145
+ return _context.abrupt("return");
146
+ case 14:
147
+ warmed = takeWarmedImage(getWarmedImageKey({
148
+ id: fileState.id,
149
+ collectionName: collectionName,
150
+ watermarkVersion: watermarkVersion
151
+ }));
152
+ _context.next = 16;
153
+ break;
154
+ case 15:
155
+ _context.prev = 15;
156
+ _t2 = _context["catch"](12);
157
+ case 16:
158
+ if (!warmed) {
159
+ _context.next = 21;
160
+ break;
161
+ }
162
+ this.cancelImageFetch = function () {
163
+ return warmed.controller.abort();
164
+ };
165
+ _context.prev = 17;
166
+ _context.next = 18;
167
+ return warmed.image;
168
+ case 18:
169
+ blob = _context.sent;
170
+ _context.next = 20;
171
+ break;
172
+ case 19:
173
+ _context.prev = 19;
174
+ _t3 = _context["catch"](17);
175
+ case 20:
176
+ if (!warmed.controller.signal.aborted) {
177
+ _context.next = 21;
178
+ break;
179
+ }
180
+ return _context.abrupt("return");
181
+ case 21:
182
+ if (blob) {
183
+ _context.next = 23;
122
184
  break;
123
185
  }
124
186
  item = processedFileStateToMediaItem(fileState);
125
- response = mediaClient.getImage(item.details.id, {
126
- collection: collectionName,
127
- mode: 'fit'
128
- }, controller, true, traceContext);
187
+ response = mediaClient.getImage(item.details.id, getImageViewerRequestParams(collectionName), controller, IMAGE_VIEWER_FETCH_MAX_RES, traceContext);
129
188
  this.cancelImageFetch = function () {
130
189
  return controller === null || controller === void 0 ? void 0 : controller.abort();
131
190
  };
132
- _context.next = 12;
191
+ _context.next = 22;
133
192
  return response;
134
- case 12:
193
+ case 22:
135
194
  blob = _context.sent;
195
+ case 23:
136
196
  renderedBlobMimeType = blob.type || undefined;
137
197
  objectUrl = URL.createObjectURL(blob);
138
- _context.next = 14;
198
+ _context.next = 25;
139
199
  break;
140
- case 13:
200
+ case 24:
141
201
  this.setState({
142
202
  content: Outcome.pending()
143
203
  });
144
204
  return _context.abrupt("return");
145
- case 14:
205
+ case 25:
146
206
  if (!(!isLocalFileReference &&
147
207
  // objectUrl at this point is binary file already
148
208
  !isErrorFileState(fileState) && fileState.status !== 'uploading' && fileState.mediaType === 'image')) {
149
- _context.next = 17;
209
+ _context.next = 28;
150
210
  break;
151
211
  }
152
212
  // Prefer the MIME type of the actual fetched bytes over the declared one.
153
213
  effectiveMimeType = fg('platform_media_unsupported_mime_routing') ? renderedBlobMimeType !== null && renderedBlobMimeType !== void 0 ? renderedBlobMimeType : fileState.mimeType : fileState.mimeType;
154
214
  if (!isImageMimeTypeSupportedByBrowser(effectiveMimeType)) {
155
- _context.next = 16;
215
+ _context.next = 27;
156
216
  break;
157
217
  }
158
- _context.next = 15;
218
+ _context.next = 26;
159
219
  return mediaClient.file.getFileBinaryURL(fileState.id, collectionName);
160
- case 15:
220
+ case 26:
161
221
  originalBinaryImageUrl = _context.sent;
162
- _context.next = 17;
222
+ _context.next = 28;
163
223
  break;
164
- case 16:
224
+ case 27:
165
225
  if (!fg('platform_media_unsupported_mime_routing')) {
166
- _context.next = 17;
226
+ _context.next = 28;
167
227
  break;
168
228
  }
169
229
  // Route unsupported MIME types browser can't natively decode straight to the
@@ -177,7 +237,7 @@ export var ImageViewer = /*#__PURE__*/function (_BaseViewer) {
177
237
  });
178
238
  this.props.onError(unsupportedError);
179
239
  return _context.abrupt("return");
180
- case 17:
240
+ case 28:
181
241
  this.setState({
182
242
  content: Outcome.successful({
183
243
  objectUrl: objectUrl,
@@ -186,24 +246,24 @@ export var ImageViewer = /*#__PURE__*/function (_BaseViewer) {
186
246
  clientId: clientId
187
247
  })
188
248
  });
189
- _context.next = 19;
249
+ _context.next = 30;
190
250
  break;
191
- case 18:
192
- _context.prev = 18;
193
- _t2 = _context["catch"](2);
251
+ case 29:
252
+ _context.prev = 29;
253
+ _t4 = _context["catch"](2);
194
254
  // TODO : properly handle aborted requests (MS-2843)
195
255
  if (!(controller !== null && controller !== void 0 && controller.signal.aborted)) {
196
- imgError = new MediaViewerError('imageviewer-fetch-url', _t2 instanceof Error ? _t2 : undefined);
256
+ imgError = new MediaViewerError('imageviewer-fetch-url', _t4 instanceof Error ? _t4 : undefined);
197
257
  this.setState({
198
258
  content: Outcome.failed(imgError)
199
259
  });
200
260
  this.props.onError(imgError);
201
261
  }
202
- case 19:
262
+ case 30:
203
263
  case "end":
204
264
  return _context.stop();
205
265
  }
206
- }, _callee, this, [[2, 18], [3, 5]]);
266
+ }, _callee, this, [[2, 29], [3, 5], [12, 15], [17, 19]]);
207
267
  }));
208
268
  function init() {
209
269
  return _init.apply(this, arguments);
@@ -0,0 +1,170 @@
1
+ import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
2
+ /**
3
+ * Full resolution image fetches started before the viewer opens.
4
+ *
5
+ * `ImageViewer` takes the entry for the file it opens and awaits the same request, so
6
+ * the image downloads once even when the click lands while the warm-up is still
7
+ * downloading.
8
+ *
9
+ * Taking an entry hands over its `AbortController` too. The viewer then owns the
10
+ * download, and closing the viewer aborts it as it aborts the viewer's own request.
11
+ * Entries nobody takes are aborted when they are evicted or expire.
12
+ *
13
+ * Whoever takes the blob creates and revokes its own object URL.
14
+ *
15
+ * Entries are keyed by file, collection and watermark version. The watermark is
16
+ * applied server-side, so a warm-up made before a watermark config change carries
17
+ * the old watermark, and a viewer opened after the change must not take it.
18
+ *
19
+ * The store lives on `globalThis`, not in this module. A bundler can copy a small
20
+ * module into several bundles, each with its own module state, and the warm-up and
21
+ * `ImageViewer` load from different bundles. The shared key gives every copy of this
22
+ * file the same store.
23
+ */
24
+
25
+ /**
26
+ * How many untaken warm-ups to hold at once. These are full resolution images and can
27
+ * be several megabytes each, so the ceiling is deliberately low: the point is the
28
+ * image the user is about to open, plus a little slack for hovering past one image on
29
+ * the way to another.
30
+ */
31
+ var MAX_WARMED_IMAGES = 2;
32
+
33
+ /** How long an untaken warm-up is held. Covers a hover followed by a click. */
34
+ export var WARMED_IMAGE_TTL_MS = 30000;
35
+
36
+ /** How a warm-up left the store. */
37
+
38
+ // Versioned, so a later change to `Entry` never reads a store another version wrote.
39
+ var STORE_KEY = Symbol.for('@atlaskit/media-viewer/warmed-images/v1');
40
+ var getStore = function getStore() {
41
+ var scope = globalThis;
42
+ var store = scope[STORE_KEY];
43
+ if (!store) {
44
+ store = new Map();
45
+ scope[STORE_KEY] = store;
46
+ }
47
+ return store;
48
+ };
49
+
50
+ /**
51
+ * Listeners report analytics. A throw from one must not break a take, which runs
52
+ * inside `ImageViewer`, or an eviction, which runs inside the next warm-up.
53
+ */
54
+ var notify = function notify(call) {
55
+ try {
56
+ call();
57
+ } catch (_unused) {
58
+ // Ignored, see above.
59
+ }
60
+ };
61
+ export var getWarmedImageKey = function getWarmedImageKey(_ref) {
62
+ var id = _ref.id,
63
+ collectionName = _ref.collectionName,
64
+ watermarkVersion = _ref.watermarkVersion;
65
+ return (
66
+ // Joined as JSON, because a watermark version can contain any separator character.
67
+ JSON.stringify([id, collectionName !== null && collectionName !== void 0 ? collectionName : '', watermarkVersion !== null && watermarkVersion !== void 0 ? watermarkVersion : ''])
68
+ );
69
+ };
70
+ export var hasWarmedImage = function hasWarmedImage(key) {
71
+ return getStore().has(key);
72
+ };
73
+
74
+ /**
75
+ * Whether any warm-up is held for the file, whatever its watermark version. Lets
76
+ * `ImageViewer` skip resolving the version when there is nothing it could take.
77
+ */
78
+ export var hasWarmedImageForFile = function hasWarmedImageForFile(_ref2) {
79
+ var id = _ref2.id,
80
+ collectionName = _ref2.collectionName;
81
+ // The file's keys all start with the JSON of its first two parts, minus the closing
82
+ // bracket. JSON quotes each part, so no other file's key can share the prefix.
83
+ var prefix = "".concat(JSON.stringify([id, collectionName !== null && collectionName !== void 0 ? collectionName : '']).slice(0, -1), ",");
84
+ return _toConsumableArray(getStore().keys()).some(function (key) {
85
+ return key.startsWith(prefix);
86
+ });
87
+ };
88
+ var removeWarmedImage = function removeWarmedImage(key, outcome) {
89
+ var store = getStore();
90
+ var entry = store.get(key);
91
+ if (entry) {
92
+ var _entry$listener;
93
+ clearTimeout(entry.expiry);
94
+ store.delete(key);
95
+ var onEnd = (_entry$listener = entry.listener) === null || _entry$listener === void 0 ? void 0 : _entry$listener.onEnd;
96
+ if (outcome && onEnd) {
97
+ notify(function () {
98
+ return onEnd(outcome, entry.blob);
99
+ });
100
+ }
101
+ }
102
+ return entry;
103
+ };
104
+ var discardWarmedImage = function discardWarmedImage(key, outcome) {
105
+ var _removeWarmedImage;
106
+ (_removeWarmedImage = removeWarmedImage(key, outcome)) === null || _removeWarmedImage === void 0 || _removeWarmedImage.controller.abort();
107
+ };
108
+ export var setWarmedImage = function setWarmedImage(key, _ref3, listener) {
109
+ var image = _ref3.image,
110
+ controller = _ref3.controller;
111
+ var store = getStore();
112
+ discardWarmedImage(key, 'replaced');
113
+
114
+ // `Map` iterates in insertion order, so the first key is the oldest.
115
+ if (store.size >= MAX_WARMED_IMAGES) {
116
+ var oldest = store.keys().next().value;
117
+ if (oldest !== undefined) {
118
+ discardWarmedImage(oldest, 'evicted');
119
+ }
120
+ }
121
+ var entry = {
122
+ image: image,
123
+ controller: controller,
124
+ listener: listener,
125
+ expiry: setTimeout(function () {
126
+ return discardWarmedImage(key, 'expired');
127
+ }, WARMED_IMAGE_TTL_MS)
128
+ };
129
+ store.set(key, entry);
130
+ image.then(function (blob) {
131
+ entry.blob = blob;
132
+ }, function (error) {
133
+ // Every removal except a take aborts the request, and so does closing the
134
+ // viewer after a take. None of those are failures.
135
+ if (controller.signal.aborted) {
136
+ return;
137
+ }
138
+ // Drop a failed warm-up so a later hover can try again. This handler also marks
139
+ // the rejection as handled when nobody takes the warm-up.
140
+ var wasTaken = getStore().get(key) !== entry;
141
+ if (!wasTaken) {
142
+ removeWarmedImage(key, 'failed');
143
+ }
144
+ var onError = listener === null || listener === void 0 ? void 0 : listener.onError;
145
+ if (onError) {
146
+ notify(function () {
147
+ return onError(error, wasTaken);
148
+ });
149
+ }
150
+ });
151
+ };
152
+
153
+ /**
154
+ * Removes the warm-up for `key` and hands it over. The caller owns the request from
155
+ * here, including aborting it.
156
+ */
157
+ export var takeWarmedImage = function takeWarmedImage(key) {
158
+ var entry = removeWarmedImage(key, 'taken');
159
+ return entry && {
160
+ image: entry.image,
161
+ controller: entry.controller
162
+ };
163
+ };
164
+
165
+ /** Aborts and drops every warm-up without reporting an outcome. For tests. */
166
+ export var clearWarmedImages = function clearWarmedImages() {
167
+ _toConsumableArray(getStore().keys()).forEach(function (key) {
168
+ return discardWarmedImage(key);
169
+ });
170
+ };
@@ -4,4 +4,4 @@ export declare class MediaViewerError extends Error {
4
4
  readonly secondaryError?: Error | undefined;
5
5
  constructor(primaryReason: MediaViewerErrorReason | ArchiveViewerErrorReason, secondaryError?: Error | undefined);
6
6
  }
7
- export type MediaViewerErrorReason = 'collection-fetch-metadata' | 'header-fetch-metadata' | 'itemviewer-onerror' | 'itemviewer-fetch-metadata' | 'itemviewer-file-error-status' | 'itemviewer-file-failed-processing-status' | 'imageviewer-external-onerror' | 'imageviewer-fetch-url' | 'imageviewer-src-onerror' | 'imageviewer-unsupported-mime' | 'audioviewer-fetch-url' | 'audioviewer-missing-artefact' | 'audioviewer-playback' | 'videoviewer-fetch-url' | 'videoviewer-missing-artefact' | 'videoviewer-playback' | 'docviewer-fetch-url' | 'docviewer-content-fetch-failed' | 'docviewer-fetch-pdf' | 'codeviewer-fetch-src' | 'codeviewer-load-src' | 'codeviewer-file-size-exceeds' | 'codeviewer-parse-email' | 'svg-img-error' | 'svg-binary-fetch' | 'svg-unknown-error' | 'svg-blob-to-datauri' | 'unsupported' | 'custom-viewer-error' | 'download';
7
+ export type MediaViewerErrorReason = 'collection-fetch-metadata' | 'header-fetch-metadata' | 'itemviewer-onerror' | 'itemviewer-fetch-metadata' | 'itemviewer-file-error-status' | 'itemviewer-file-failed-processing-status' | 'imageviewer-external-onerror' | 'imageviewer-fetch-url' | 'imageviewer-src-onerror' | 'imageviewer-unsupported-mime' | 'audioviewer-fetch-url' | 'audioviewer-missing-artefact' | 'audioviewer-playback' | 'videoviewer-fetch-url' | 'videoviewer-missing-artefact' | 'videoviewer-playback' | 'docviewer-fetch-url' | 'docviewer-content-fetch-failed' | 'docviewer-fetch-pdf' | 'codeviewer-fetch-src' | 'codeviewer-load-src' | 'codeviewer-file-size-exceeds' | 'codeviewer-parse-email' | 'svg-img-error' | 'svg-binary-fetch' | 'svg-unknown-error' | 'svg-blob-to-datauri' | 'unsupported' | 'custom-viewer-error' | 'download' | 'preload-image-fetch';
@@ -1,3 +1,3 @@
1
1
  import type { OperationalEventPayload, OperationalAttributes } from '@atlaskit/media-common/analytics/types';
2
2
  /** common definition used by other mediaFile events */
3
- export type MediaFileEventPayload<Attributes extends OperationalAttributes, Action extends 'commenced' | 'loadSucceeded' | 'loadFailed' | 'previewUnsupported' | 'previewTooLarge' | 'zipEntryLoadSucceeded' | 'zipEntryLoadFailed' | 'downloadSucceeded' | 'downloadFailed'> = OperationalEventPayload<Attributes, Action, 'mediaFile'>;
3
+ export type MediaFileEventPayload<Attributes extends OperationalAttributes, Action extends 'commenced' | 'loadSucceeded' | 'loadFailed' | 'previewUnsupported' | 'previewTooLarge' | 'zipEntryLoadSucceeded' | 'zipEntryLoadFailed' | 'downloadSucceeded' | 'downloadFailed' | 'preloadEnded' | 'preloadFailed'> = OperationalEventPayload<Attributes, Action, 'mediaFile'>;
@@ -0,0 +1,36 @@
1
+ import type { FileAttributes, MediaTraceContext, WithFileAttributes, WithTraceContext } from '@atlaskit/media-common/analytics/types';
2
+ import { type MediaViewerFailureAttributes } from '../..';
3
+ import type { WarmUpOutcome } from '../../../warmedImages';
4
+ import { type MediaFileEventPayload } from './_mediaFile';
5
+ /** Fired when a warm-up request fails for a reason other than an abort. Never sampled. */
6
+ export type PreloadFailedEventPayload = MediaFileEventPayload<MediaViewerFailureAttributes & {
7
+ /** Whether `ImageViewer` had already taken the warm-up when it failed. */
8
+ wasTaken: boolean;
9
+ durationMs: number;
10
+ }, 'preloadFailed'>;
11
+ /** Fired once per sampled warm-up, when it leaves the warmed image store. */
12
+ export type PreloadEndedEventPayload = MediaFileEventPayload<WithFileAttributes & WithTraceContext & {
13
+ outcome: WarmUpOutcome;
14
+ /** Whether the image had finished downloading by then. */
15
+ resolved: boolean;
16
+ sizeBytes?: number;
17
+ durationMs: number;
18
+ isSamplingEnabled: boolean;
19
+ samplingRate: number;
20
+ }, 'preloadEnded'>;
21
+ export type MediaViewerPreloadEventPayload = PreloadFailedEventPayload | PreloadEndedEventPayload;
22
+ export declare const createPreloadFailedEventPayload: ({ error, wasTaken, durationMs, fileAttributes, traceContext, }: {
23
+ error: unknown;
24
+ wasTaken: boolean;
25
+ durationMs: number;
26
+ fileAttributes: FileAttributes;
27
+ traceContext?: MediaTraceContext;
28
+ }) => PreloadFailedEventPayload;
29
+ export declare const createPreloadEndedEventPayload: ({ outcome, blob, durationMs, fileAttributes, traceContext, samplingRate, }: {
30
+ outcome: WarmUpOutcome;
31
+ blob: Blob | undefined;
32
+ durationMs: number;
33
+ fileAttributes: FileAttributes;
34
+ traceContext?: MediaTraceContext;
35
+ samplingRate: number;
36
+ }) => PreloadEndedEventPayload;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The single call site for each lazily loaded chunk that `./preload` warms.
3
+ *
4
+ * Both the render path and the warm-up path must go through these. Repeating an
5
+ * `import()` with the same `webpackChunkName` in two files relies on the two
6
+ * comments staying identical forever; if they drift, the warm-up fetches a
7
+ * different chunk than the one the viewer loads and silently does nothing.
8
+ */
9
+ export declare const loadMediaViewerChunk: () => Promise<typeof import('./components/media-viewer-error-boundary')>;
10
+ export declare const loadImageViewerChunk: () => Promise<typeof import('./viewers/image')>;
@@ -0,0 +1,58 @@
1
+ import type { Identifier } from '@atlaskit/media-client/identifier';
2
+ import type { MediaClient } from '@atlaskit/media-client/media-client';
3
+ import type { MediaTraceContext } from '@atlaskit/media-common/analytics/types';
4
+ import type { MediaType } from '@atlaskit/media-common/main-types';
5
+ import type { FileState } from '@atlaskit/media-state/file-state';
6
+ import { type MediaViewerPreloadEventPayload } from './analytics/events/operational/preload';
7
+ export type { MediaViewerPreloadEventPayload, PreloadEndedEventPayload, PreloadFailedEventPayload, } from './analytics/events/operational/preload';
8
+ export type PreloadMediaViewerOptions = {
9
+ /**
10
+ * Returns the media client for the image request. Only called when an image is
11
+ * actually warmed, so the control arm never creates a client.
12
+ */
13
+ getMediaClient: () => MediaClient;
14
+ identifier: Identifier;
15
+ /** Mime type of the target file, when the caller knows it. */
16
+ mimeType?: string;
17
+ /** Media type of the target file. Derived from `mimeType` when omitted. */
18
+ mediaType?: MediaType;
19
+ /**
20
+ * File state for the target file, when the caller already has it. Used to
21
+ * skip the image warm-up in the cases where `ImageViewer` would not request
22
+ * the image endpoint anyway.
23
+ */
24
+ fileState?: FileState;
25
+ traceContext?: MediaTraceContext;
26
+ /**
27
+ * Receives the warm-up's operational events, for the caller to fire on the media
28
+ * channel with its own analytics. Errors it throws are ignored.
29
+ */
30
+ onAnalyticsEvent?: (payload: MediaViewerPreloadEventPayload) => void;
31
+ };
32
+ /**
33
+ * Speculatively warms what the media viewer needs to display `identifier`, so
34
+ * that opening it is closer to instant. Intended to be called from a hover or
35
+ * focus handler on whatever opens the viewer.
36
+ *
37
+ * Two things get warmed:
38
+ * - the lazily loaded viewer chunks, and
39
+ * - the full resolution image binary, whose in-flight request is kept in
40
+ * `./warmedImages` for `ImageViewer` to take instead of issuing its own.
41
+ *
42
+ * The image request starts once media-client has resolved the watermark version
43
+ * it carries, because the version is part of the warmed image's key.
44
+ *
45
+ * The image binary is only warmed when the file is known to be a non-SVG image,
46
+ * because `ImageViewer` is the only viewer that makes this request. Callers that
47
+ * know nothing about the file still get the chunk warm-up.
48
+ *
49
+ * Safe to call repeatedly and safe to call for files the user never opens: an
50
+ * image already being warmed is not requested again, a failed image request is not
51
+ * retried and its rejection is handled, and no image is fetched on metered or slow
52
+ * connections. Failures and outcomes go to `onAnalyticsEvent`.
53
+ *
54
+ * This is the exposure point for the `platform_media_viewer_preload_on_hover`
55
+ * experiment. Callers attach their handlers in both arms, and the exposure fires
56
+ * here before the arms differ, so both arms are exposed on the same hover or focus.
57
+ */
58
+ export declare const preloadMediaViewer: ({ getMediaClient, identifier, mimeType, mediaType, fileState, traceContext, onAnalyticsEvent, }: PreloadMediaViewerOptions) => void;
@@ -0,0 +1,15 @@
1
+ import type { MediaStoreGetFileImageParams } from '@atlaskit/media-client/media-store/types';
2
+ /**
3
+ * `ImageViewer` asks for the image at media-client's maximum resolution so it stays
4
+ * sharp when zoomed in.
5
+ */
6
+ export declare const IMAGE_VIEWER_FETCH_MAX_RES = true;
7
+ /**
8
+ * Params `ImageViewer` uses to fetch the image it renders.
9
+ *
10
+ * Shared with `preloadMediaViewer` so a warm-up fetches exactly the bytes the
11
+ * viewer will render, and the resulting blob can be handed straight to it. Media
12
+ * cards request the image at their own rendered size, usually with a different
13
+ * `mode`, so a card's image is never a substitute for this one.
14
+ */
15
+ export declare const getImageViewerRequestParams: (collectionName?: string) => MediaStoreGetFileImageParams;
@@ -27,6 +27,8 @@ export declare class ImageViewer extends BaseViewer<ImageViewerContent, ImageVie
27
27
  content: Outcome<ImageViewerContent, MediaViewerError>;
28
28
  };
29
29
  private cancelImageFetch?;
30
+ /** Counts `init` calls, so an `init` that a reset has replaced can tell it is stale. */
31
+ private initRuns;
30
32
  protected init(): Promise<void>;
31
33
  protected release(): void;
32
34
  revokeObjectUrl(objectUrl: string): void;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Full resolution image fetches started before the viewer opens.
3
+ *
4
+ * `ImageViewer` takes the entry for the file it opens and awaits the same request, so
5
+ * the image downloads once even when the click lands while the warm-up is still
6
+ * downloading.
7
+ *
8
+ * Taking an entry hands over its `AbortController` too. The viewer then owns the
9
+ * download, and closing the viewer aborts it as it aborts the viewer's own request.
10
+ * Entries nobody takes are aborted when they are evicted or expire.
11
+ *
12
+ * Whoever takes the blob creates and revokes its own object URL.
13
+ *
14
+ * Entries are keyed by file, collection and watermark version. The watermark is
15
+ * applied server-side, so a warm-up made before a watermark config change carries
16
+ * the old watermark, and a viewer opened after the change must not take it.
17
+ *
18
+ * The store lives on `globalThis`, not in this module. A bundler can copy a small
19
+ * module into several bundles, each with its own module state, and the warm-up and
20
+ * `ImageViewer` load from different bundles. The shared key gives every copy of this
21
+ * file the same store.
22
+ */
23
+ /** How long an untaken warm-up is held. Covers a hover followed by a click. */
24
+ export declare const WARMED_IMAGE_TTL_MS = 30000;
25
+ export type WarmedImage = {
26
+ image: Promise<Blob>;
27
+ controller: AbortController;
28
+ };
29
+ /** How a warm-up left the store. */
30
+ export type WarmUpOutcome = 'taken' | 'expired' | 'evicted' | 'replaced' | 'failed';
31
+ export type WarmUpListener = {
32
+ /** Called once, when the warm-up leaves the store. `blob` is set if it had downloaded. */
33
+ onEnd?: (outcome: WarmUpOutcome, blob: Blob | undefined) => void;
34
+ /** Called when the request fails for a reason other than an abort. */
35
+ onError?: (error: unknown, wasTaken: boolean) => void;
36
+ };
37
+ export type WarmedImageKeyParts = {
38
+ id: string;
39
+ collectionName?: string;
40
+ /**
41
+ * The `wmv` the image request carries, from `MediaClient.getImageWatermarkVersion`.
42
+ * Required, so no caller can leave it out.
43
+ */
44
+ watermarkVersion: string | undefined;
45
+ };
46
+ export declare const getWarmedImageKey: ({ id, collectionName, watermarkVersion, }: WarmedImageKeyParts) => string;
47
+ export declare const hasWarmedImage: (key: string) => boolean;
48
+ /**
49
+ * Whether any warm-up is held for the file, whatever its watermark version. Lets
50
+ * `ImageViewer` skip resolving the version when there is nothing it could take.
51
+ */
52
+ export declare const hasWarmedImageForFile: ({ id, collectionName, }: Omit<WarmedImageKeyParts, 'watermarkVersion'>) => boolean;
53
+ export declare const setWarmedImage: (key: string, { image, controller }: WarmedImage, listener?: WarmUpListener) => void;
54
+ /**
55
+ * Removes the warm-up for `key` and hands it over. The caller owns the request from
56
+ * here, including aborting it.
57
+ */
58
+ export declare const takeWarmedImage: (key: string) => WarmedImage | undefined;
59
+ /** Aborts and drops every warm-up without reporting an outcome. For tests. */
60
+ export declare const clearWarmedImages: () => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atlaskit/media-viewer",
3
- "version": "54.11.28",
3
+ "version": "54.12.1",
4
4
  "description": "MediaViewer is Atlassian's powerful solution for viewing files on the web. It's both powerful and extendable yet easy-to-integrate",
5
5
  "publishConfig": {
6
6
  "registry": "https://registry.npmjs.org/"
@@ -37,12 +37,12 @@
37
37
  "@atlaskit/button": "^25.6.0",
38
38
  "@atlaskit/code": "^20.0.0",
39
39
  "@atlaskit/css": "^1.1.0",
40
- "@atlaskit/form": "^18.2.0",
40
+ "@atlaskit/form": "^18.3.0",
41
41
  "@atlaskit/heading": "^8.0.0",
42
42
  "@atlaskit/icon": "^38.0.0",
43
43
  "@atlaskit/icon-file-type": "^8.3.0",
44
44
  "@atlaskit/icon-lab": "^7.11.0",
45
- "@atlaskit/media-client": "^39.2.0",
45
+ "@atlaskit/media-client": "^39.3.0",
46
46
  "@atlaskit/media-client-react": "^7.0.0",
47
47
  "@atlaskit/media-common": "^14.7.0",
48
48
  "@atlaskit/media-document-viewer": "^2.2.0",
@@ -50,7 +50,7 @@
50
50
  "@atlaskit/media-svg": "^4.0.0",
51
51
  "@atlaskit/media-ui": "^31.5.0",
52
52
  "@atlaskit/menu": "^11.0.0",
53
- "@atlaskit/motion": "^9.4.0",
53
+ "@atlaskit/motion": "^9.5.0",
54
54
  "@atlaskit/platform-feature-experiments": "^0.3.0",
55
55
  "@atlaskit/platform-feature-flags": "^2.2.0",
56
56
  "@atlaskit/portal": "^7.1.0",
@@ -60,8 +60,8 @@
60
60
  "@atlaskit/spinner": "^20.4.0",
61
61
  "@atlaskit/textfield": "^10.2.0",
62
62
  "@atlaskit/theme": "^28.2.0",
63
- "@atlaskit/tmp-editor-statsig": "^246.0.0",
64
- "@atlaskit/tokens": "^20.7.0",
63
+ "@atlaskit/tmp-editor-statsig": "^247.0.0",
64
+ "@atlaskit/tokens": "^20.8.0",
65
65
  "@atlaskit/tooltip": "^24.4.0",
66
66
  "@atlaskit/ufo": "^2.0.0",
67
67
  "@babel/runtime": "^7.0.0",
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "@atlaskit/media-viewer/preload",
3
+ "main": "../dist/cjs/preload.js",
4
+ "module": "../dist/esm/preload.js",
5
+ "module:es2019": "../dist/es2019/preload.js",
6
+ "sideEffects": [
7
+ "*.compiled.css"
8
+ ],
9
+ "types": "../dist/types/preload.d.ts"
10
+ }