@atlaskit/media-viewer 54.11.28 → 54.12.0

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 +44 -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 +5 -5
  39. package/preload/package.json +10 -0
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `ImageViewer` asks for the image at media-client's maximum resolution so it stays
3
+ * sharp when zoomed in.
4
+ */
5
+ export const IMAGE_VIEWER_FETCH_MAX_RES = true;
6
+
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 const getImageViewerRequestParams = collectionName => ({
16
+ collection: collectionName,
17
+ mode: 'fit'
18
+ });
@@ -7,7 +7,9 @@ import { fg } from '@atlaskit/platform-feature-flags/fg';
7
7
  import { buildImgErrorDiagnostics } from '../../buildImgErrorDiagnostics';
8
8
  import { Outcome } from '../../domain/outcome';
9
9
  import { MediaViewerError } from '../../MediaViewerError';
10
+ import { getWarmedImageKey, hasWarmedImageForFile, takeWarmedImage } from '../../warmedImages';
10
11
  import { BaseViewer } from '../base-viewer';
12
+ import { getImageViewerRequestParams, IMAGE_VIEWER_FETCH_MAX_RES } from './imageRequestParams';
11
13
  import { InteractiveImg } from './interactive-img';
12
14
  function processedFileStateToMediaItem(file) {
13
15
  return {
@@ -20,6 +22,8 @@ function processedFileStateToMediaItem(file) {
20
22
  export class ImageViewer extends BaseViewer {
21
23
  constructor(...args) {
22
24
  super(...args);
25
+ /** Counts `init` calls, so an `init` that a reset has replaced can tell it is stale. */
26
+ _defineProperty(this, "initRuns", 0);
23
27
  _defineProperty(this, "onLoad", () => {
24
28
  this.props.onLoad();
25
29
  this.onMediaDisplayed();
@@ -40,6 +44,7 @@ export class ImageViewer extends BaseViewer {
40
44
  };
41
45
  }
42
46
  async init() {
47
+ const initRun = this.initRuns += 1;
43
48
  const {
44
49
  item: fileState,
45
50
  mediaClient,
@@ -82,13 +87,60 @@ export class ImageViewer extends BaseViewer {
82
87
  objectUrl = value;
83
88
  }
84
89
  } else if (isImageRepresentationReady(fileState)) {
85
- const item = processedFileStateToMediaItem(fileState);
86
- const response = mediaClient.getImage(item.details.id, {
87
- collection: collectionName,
88
- mode: 'fit'
89
- }, controller, true, traceContext);
90
- this.cancelImageFetch = () => controller === null || controller === void 0 ? void 0 : controller.abort();
91
- const blob = await response;
90
+ // A hover or focus may already have started this exact request. Taking it
91
+ // means the image downloads once, even while the warm-up is still in
92
+ // flight. The viewer owns the download from here, so closing it aborts the
93
+ // request. A taken request keeps the trace context of whoever started it.
94
+ // Warm-ups only exist in the treatment arm of the
95
+ // `platform_media_viewer_preload_on_hover` experiment, so there is no check
96
+ // here: in control nothing is found and the viewer makes its own request.
97
+ // The key carries the watermark version, so a warm-up made before a
98
+ // watermark config change is not taken. The version is only resolved when
99
+ // a warm-up for this file exists, so control makes the same requests as
100
+ // before.
101
+ let warmed;
102
+ if (hasWarmedImageForFile({
103
+ id: fileState.id,
104
+ collectionName
105
+ })) {
106
+ try {
107
+ const watermarkVersion = await mediaClient.getImageWatermarkVersion(collectionName);
108
+ // Closed or reset while the version resolved. Leave the warm-up in the
109
+ // store, which aborts it on expiry, rather than take it for nobody.
110
+ if (!this.mounted || initRun !== this.initRuns) {
111
+ return;
112
+ }
113
+ warmed = takeWarmedImage(getWarmedImageKey({
114
+ id: fileState.id,
115
+ collectionName,
116
+ watermarkVersion
117
+ }));
118
+ } catch {
119
+ // No version, so no warm-up can be matched. The viewer's own request below
120
+ // reports the auth failure.
121
+ }
122
+ }
123
+ let blob;
124
+ if (warmed) {
125
+ this.cancelImageFetch = () => warmed.controller.abort();
126
+ try {
127
+ blob = await warmed.image;
128
+ } catch {
129
+ // The warm-up failed. Fall through and request it again so the viewer
130
+ // reports its own error if that fails too.
131
+ }
132
+
133
+ // Released while the warm-up was downloading, so there is nothing to show.
134
+ if (warmed.controller.signal.aborted) {
135
+ return;
136
+ }
137
+ }
138
+ if (!blob) {
139
+ const item = processedFileStateToMediaItem(fileState);
140
+ const response = mediaClient.getImage(item.details.id, getImageViewerRequestParams(collectionName), controller, IMAGE_VIEWER_FETCH_MAX_RES, traceContext);
141
+ this.cancelImageFetch = () => controller === null || controller === void 0 ? void 0 : controller.abort();
142
+ blob = await response;
143
+ }
92
144
  renderedBlobMimeType = blob.type || undefined;
93
145
  objectUrl = URL.createObjectURL(blob);
94
146
  } else {
@@ -0,0 +1,157 @@
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
+
24
+ /**
25
+ * How many untaken warm-ups to hold at once. These are full resolution images and can
26
+ * be several megabytes each, so the ceiling is deliberately low: the point is the
27
+ * image the user is about to open, plus a little slack for hovering past one image on
28
+ * the way to another.
29
+ */
30
+ const MAX_WARMED_IMAGES = 2;
31
+
32
+ /** How long an untaken warm-up is held. Covers a hover followed by a click. */
33
+ export const WARMED_IMAGE_TTL_MS = 30_000;
34
+
35
+ /** How a warm-up left the store. */
36
+
37
+ // Versioned, so a later change to `Entry` never reads a store another version wrote.
38
+ const STORE_KEY = Symbol.for('@atlaskit/media-viewer/warmed-images/v1');
39
+ const getStore = () => {
40
+ const scope = globalThis;
41
+ let store = scope[STORE_KEY];
42
+ if (!store) {
43
+ store = new Map();
44
+ scope[STORE_KEY] = store;
45
+ }
46
+ return store;
47
+ };
48
+
49
+ /**
50
+ * Listeners report analytics. A throw from one must not break a take, which runs
51
+ * inside `ImageViewer`, or an eviction, which runs inside the next warm-up.
52
+ */
53
+ const notify = call => {
54
+ try {
55
+ call();
56
+ } catch {
57
+ // Ignored, see above.
58
+ }
59
+ };
60
+ export const getWarmedImageKey = ({
61
+ id,
62
+ collectionName,
63
+ watermarkVersion
64
+ }) =>
65
+ // Joined as JSON, because a watermark version can contain any separator character.
66
+ JSON.stringify([id, collectionName !== null && collectionName !== void 0 ? collectionName : '', watermarkVersion !== null && watermarkVersion !== void 0 ? watermarkVersion : '']);
67
+ export const hasWarmedImage = key => getStore().has(key);
68
+
69
+ /**
70
+ * Whether any warm-up is held for the file, whatever its watermark version. Lets
71
+ * `ImageViewer` skip resolving the version when there is nothing it could take.
72
+ */
73
+ export const hasWarmedImageForFile = ({
74
+ id,
75
+ collectionName
76
+ }) => {
77
+ // The file's keys all start with the JSON of its first two parts, minus the closing
78
+ // bracket. JSON quotes each part, so no other file's key can share the prefix.
79
+ const prefix = `${JSON.stringify([id, collectionName !== null && collectionName !== void 0 ? collectionName : '']).slice(0, -1)},`;
80
+ return [...getStore().keys()].some(key => key.startsWith(prefix));
81
+ };
82
+ const removeWarmedImage = (key, outcome) => {
83
+ const store = getStore();
84
+ const entry = store.get(key);
85
+ if (entry) {
86
+ var _entry$listener;
87
+ clearTimeout(entry.expiry);
88
+ store.delete(key);
89
+ const onEnd = (_entry$listener = entry.listener) === null || _entry$listener === void 0 ? void 0 : _entry$listener.onEnd;
90
+ if (outcome && onEnd) {
91
+ notify(() => onEnd(outcome, entry.blob));
92
+ }
93
+ }
94
+ return entry;
95
+ };
96
+ const discardWarmedImage = (key, outcome) => {
97
+ var _removeWarmedImage;
98
+ (_removeWarmedImage = removeWarmedImage(key, outcome)) === null || _removeWarmedImage === void 0 ? void 0 : _removeWarmedImage.controller.abort();
99
+ };
100
+ export const setWarmedImage = (key, {
101
+ image,
102
+ controller
103
+ }, listener) => {
104
+ const store = getStore();
105
+ discardWarmedImage(key, 'replaced');
106
+
107
+ // `Map` iterates in insertion order, so the first key is the oldest.
108
+ if (store.size >= MAX_WARMED_IMAGES) {
109
+ const oldest = store.keys().next().value;
110
+ if (oldest !== undefined) {
111
+ discardWarmedImage(oldest, 'evicted');
112
+ }
113
+ }
114
+ const entry = {
115
+ image,
116
+ controller,
117
+ listener,
118
+ expiry: setTimeout(() => discardWarmedImage(key, 'expired'), WARMED_IMAGE_TTL_MS)
119
+ };
120
+ store.set(key, entry);
121
+ image.then(blob => {
122
+ entry.blob = blob;
123
+ }, error => {
124
+ // Every removal except a take aborts the request, and so does closing the
125
+ // viewer after a take. None of those are failures.
126
+ if (controller.signal.aborted) {
127
+ return;
128
+ }
129
+ // Drop a failed warm-up so a later hover can try again. This handler also marks
130
+ // the rejection as handled when nobody takes the warm-up.
131
+ const wasTaken = getStore().get(key) !== entry;
132
+ if (!wasTaken) {
133
+ removeWarmedImage(key, 'failed');
134
+ }
135
+ const onError = listener === null || listener === void 0 ? void 0 : listener.onError;
136
+ if (onError) {
137
+ notify(() => onError(error, wasTaken));
138
+ }
139
+ });
140
+ };
141
+
142
+ /**
143
+ * Removes the warm-up for `key` and hands it over. The caller owns the request from
144
+ * here, including aborting it.
145
+ */
146
+ export const takeWarmedImage = key => {
147
+ const entry = removeWarmedImage(key, 'taken');
148
+ return entry && {
149
+ image: entry.image,
150
+ controller: entry.controller
151
+ };
152
+ };
153
+
154
+ /** Aborts and drops every warm-up without reporting an outcome. For tests. */
155
+ export const clearWarmedImages = () => {
156
+ [...getStore().keys()].forEach(key => discardWarmedImage(key));
157
+ };
@@ -16,6 +16,7 @@ import { createLoadSucceededEvent } from './analytics/events/operational/loadSuc
16
16
  import { fireAnalytics } from './analytics/fireAnalytics';
17
17
  import { getFileAttributes } from './analytics/getFileAttributes';
18
18
  import { startMediaFileUfoExperience, succeedMediaFileUfoExperience } from './analytics/ufoExperiences';
19
+ import { loadImageViewerChunk } from './chunkLoaders';
19
20
  import { Outcome } from './domain/outcome';
20
21
  import ErrorMessage from './errorMessageWithAnalytics';
21
22
  import { ErrorViewDownloadButton } from './ErrorViewDownloadButton';
@@ -26,9 +27,8 @@ import { MediaViewerError } from './MediaViewerError';
26
27
  import ArchiveViewerLoader from './viewers/archiveSidebar/archiveViewerLoader';
27
28
  import { CustomViewer } from './viewers/customViewer/customViewer';
28
29
  import { InteractiveImg } from './viewers/image/interactive-img';
29
- function loadImageViewer() {
30
- return import( /* webpackChunkName: "@atlaskit-internal_imageViewer" */'./viewers/image');
31
- }
30
+ // Shared with `./preload` so the warm-up and the render path load the same chunk.
31
+ var loadImageViewer = loadImageViewerChunk;
32
32
  var LoadableImageViewer = Loadable({
33
33
  loader: function loader() {
34
34
  return loadImageViewer().then(function (mod) {
@@ -0,0 +1,61 @@
1
+ import { getErrorDetail } from '../../../getErrorDetail';
2
+ import { getPrimaryErrorReason } from '../../../getPrimaryErrorReason';
3
+ import { getRequestMetadata } from '../../../getRequestMetadata';
4
+ import { getSecondaryErrorReason } from '../../../getSecondaryErrorReason';
5
+ import { MediaViewerError } from '../../../MediaViewerError';
6
+
7
+ /** Fired when a warm-up request fails for a reason other than an abort. Never sampled. */
8
+
9
+ /** Fired once per sampled warm-up, when it leaves the warmed image store. */
10
+
11
+ export var createPreloadFailedEventPayload = function createPreloadFailedEventPayload(_ref) {
12
+ var error = _ref.error,
13
+ wasTaken = _ref.wasTaken,
14
+ durationMs = _ref.durationMs,
15
+ fileAttributes = _ref.fileAttributes,
16
+ traceContext = _ref.traceContext;
17
+ var viewerError = new MediaViewerError('preload-image-fetch', error instanceof Error ? error : undefined);
18
+ var requestMetadata = getRequestMetadata(viewerError);
19
+ return {
20
+ eventType: 'operational',
21
+ actionSubject: 'mediaFile',
22
+ action: 'preloadFailed',
23
+ attributes: {
24
+ status: 'fail',
25
+ failReason: getPrimaryErrorReason(viewerError),
26
+ error: getSecondaryErrorReason(viewerError),
27
+ errorDetail: getErrorDetail(viewerError),
28
+ statusCode: requestMetadata === null || requestMetadata === void 0 ? void 0 : requestMetadata.statusCode,
29
+ request: requestMetadata,
30
+ fileMimetype: fileAttributes.fileMimetype,
31
+ fileMediatype: fileAttributes.fileMediatype,
32
+ fileAttributes: fileAttributes,
33
+ traceContext: traceContext,
34
+ wasTaken: wasTaken,
35
+ durationMs: durationMs
36
+ }
37
+ };
38
+ };
39
+ export var createPreloadEndedEventPayload = function createPreloadEndedEventPayload(_ref2) {
40
+ var outcome = _ref2.outcome,
41
+ blob = _ref2.blob,
42
+ durationMs = _ref2.durationMs,
43
+ fileAttributes = _ref2.fileAttributes,
44
+ traceContext = _ref2.traceContext,
45
+ samplingRate = _ref2.samplingRate;
46
+ return {
47
+ eventType: 'operational',
48
+ actionSubject: 'mediaFile',
49
+ action: 'preloadEnded',
50
+ attributes: {
51
+ outcome: outcome,
52
+ resolved: !!blob,
53
+ sizeBytes: blob === null || blob === void 0 ? void 0 : blob.size,
54
+ durationMs: durationMs,
55
+ fileAttributes: fileAttributes,
56
+ traceContext: traceContext,
57
+ isSamplingEnabled: samplingRate < 1,
58
+ samplingRate: samplingRate
59
+ }
60
+ };
61
+ };
@@ -7,7 +7,7 @@ import { fg } from '@atlaskit/platform-feature-flags/fg';
7
7
  import { UFOExperience } from '@atlaskit/ufo/experience';
8
8
  import { ExperiencePerformanceTypes, ExperienceTypes } from '@atlaskit/ufo/experience-types';
9
9
  var packageName = "@atlaskit/media-viewer";
10
- var packageVersion = "54.11.27";
10
+ var packageVersion = "54.11.28";
11
11
  var ufoExperience;
12
12
  var getExperience = function getExperience() {
13
13
  if (!ufoExperience) {
@@ -0,0 +1,15 @@
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
+
10
+ export var loadMediaViewerChunk = function loadMediaViewerChunk() {
11
+ return import( /* webpackChunkName: "@atlaskit-internal_media-viewer" */'./components/media-viewer-error-boundary');
12
+ };
13
+ export var loadImageViewerChunk = function loadImageViewerChunk() {
14
+ return import( /* webpackChunkName: "@atlaskit-internal_imageViewer" */'./viewers/image');
15
+ };
@@ -1,8 +1,9 @@
1
1
  import React, { lazy, Suspense } from 'react';
2
+ import { loadMediaViewerChunk } from '../chunkLoaders';
2
3
  import ModalSpinner from '../viewers/modalSpinner';
3
4
  import { MediaViewerPortal } from './portal';
4
5
  var MediaViewer = /*#__PURE__*/lazy(function () {
5
- return import( /* webpackChunkName: "@atlaskit-internal_media-viewer" */'./media-viewer-error-boundary').then(function (_ref) {
6
+ return loadMediaViewerChunk().then(function (_ref) {
6
7
  var MediaViewerWithErrorBoundary = _ref.MediaViewerWithErrorBoundary;
7
8
  return {
8
9
  default: MediaViewerWithErrorBoundary
@@ -0,0 +1,193 @@
1
+ import _defineProperty from "@babel/runtime/helpers/defineProperty";
2
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
3
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4
+ import { isErrorFileState } from '@atlaskit/media-client/is-error-file-state';
5
+ import { isFileIdentifier } from '@atlaskit/media-client/is-file-identifier';
6
+ import { isImageRepresentationReady } from '@atlaskit/media-client/is-image-representation-ready';
7
+ import { getMediaTypeFromMimeType } from '@atlaskit/media-common/mediaTypeUtils';
8
+ import { sanitiseAnalyticsPayload } from '@atlaskit/media-common/sanitisePayload';
9
+ import { isExperimentEnabled } from '@atlaskit/platform-feature-experiments/is-experiment-enabled';
10
+ import { createPreloadEndedEventPayload, createPreloadFailedEventPayload } from './analytics/events/operational/preload';
11
+ import { loadImageViewerChunk, loadMediaViewerChunk } from './chunkLoaders';
12
+ import { getImageViewerRequestParams, IMAGE_VIEWER_FETCH_MAX_RES } from './viewers/image/imageRequestParams';
13
+ import { getWarmedImageKey, hasWarmedImage, setWarmedImage } from './warmedImages';
14
+ /**
15
+ * Share of warm-ups that report `preloadEnded`, which measures how many warm-ups the
16
+ * viewer takes. `preloadFailed` is never sampled.
17
+ */
18
+ var PRELOAD_ENDED_SAMPLING_RATE = 0.1;
19
+
20
+ /**
21
+ * A warm-up is speculative, so it doesn't retry a failure with backoff. Retrying a
22
+ * 5xx would add load when the image endpoint is already struggling, and the viewer
23
+ * makes its own request on open anyway. media-client's Edge network-error fallback
24
+ * still applies. `fetchRetry` waits `startTimeoutInMs` even
25
+ * after the last attempt, so it is zero: a failed warm-up a viewer has taken then
26
+ * hands over to the viewer's own request without a pause.
27
+ */
28
+ var WARM_UP_CLIENT_OPTIONS = {
29
+ retryOptions: {
30
+ maxAttempts: 1,
31
+ startTimeoutInMs: 0
32
+ }
33
+ };
34
+
35
+ /** SVGs are rendered by `SvgViewer`, which does not go through the image endpoint. */
36
+ var SVG_MIME_TYPE = 'image/svg+xml';
37
+
38
+ /**
39
+ * Effective connection types where speculatively downloading a full resolution
40
+ * image costs the user more than the latency it saves.
41
+ */
42
+ var METERED_EFFECTIVE_TYPES = ['slow-2g', '2g', '3g'];
43
+ var isMeteredConnection = function isMeteredConnection() {
44
+ if (typeof navigator === 'undefined') {
45
+ return false;
46
+ }
47
+ var _ref = navigator,
48
+ connection = _ref.connection;
49
+ if (!connection) {
50
+ return false;
51
+ }
52
+ return !!connection.saveData || !!connection.effectiveType && METERED_EFFECTIVE_TYPES.includes(connection.effectiveType);
53
+ };
54
+ /**
55
+ * Speculatively warms what the media viewer needs to display `identifier`, so
56
+ * that opening it is closer to instant. Intended to be called from a hover or
57
+ * focus handler on whatever opens the viewer.
58
+ *
59
+ * Two things get warmed:
60
+ * - the lazily loaded viewer chunks, and
61
+ * - the full resolution image binary, whose in-flight request is kept in
62
+ * `./warmedImages` for `ImageViewer` to take instead of issuing its own.
63
+ *
64
+ * The image request starts once media-client has resolved the watermark version
65
+ * it carries, because the version is part of the warmed image's key.
66
+ *
67
+ * The image binary is only warmed when the file is known to be a non-SVG image,
68
+ * because `ImageViewer` is the only viewer that makes this request. Callers that
69
+ * know nothing about the file still get the chunk warm-up.
70
+ *
71
+ * Safe to call repeatedly and safe to call for files the user never opens: an
72
+ * image already being warmed is not requested again, a failed image request is not
73
+ * retried and its rejection is handled, and no image is fetched on metered or slow
74
+ * connections. Failures and outcomes go to `onAnalyticsEvent`.
75
+ *
76
+ * This is the exposure point for the `platform_media_viewer_preload_on_hover`
77
+ * experiment. Callers attach their handlers in both arms, and the exposure fires
78
+ * here before the arms differ, so both arms are exposed on the same hover or focus.
79
+ */
80
+ export var preloadMediaViewer = function preloadMediaViewer(_ref2) {
81
+ var getMediaClient = _ref2.getMediaClient,
82
+ identifier = _ref2.identifier,
83
+ mimeType = _ref2.mimeType,
84
+ mediaType = _ref2.mediaType,
85
+ fileState = _ref2.fileState,
86
+ traceContext = _ref2.traceContext,
87
+ onAnalyticsEvent = _ref2.onAnalyticsEvent;
88
+ // External images need no warm-up: the viewer renders the same `dataURI` the
89
+ // card is already displaying. Checked before the exposure, so neither arm is
90
+ // exposed for them.
91
+ if (!isFileIdentifier(identifier)) {
92
+ return;
93
+ }
94
+ if (!isExperimentEnabled('platform_media_viewer_preload_on_hover')) {
95
+ return;
96
+ }
97
+ void loadMediaViewerChunk().catch(function () {});
98
+ var resolvedMediaType = mediaType !== null && mediaType !== void 0 ? mediaType : mimeType ? getMediaTypeFromMimeType(mimeType) : undefined;
99
+ if (resolvedMediaType !== 'image' || mimeType === SVG_MIME_TYPE) {
100
+ return;
101
+ }
102
+ void loadImageViewerChunk().catch(function () {});
103
+ if (fileState) {
104
+ // `ImageViewer` renders `fileState.preview` directly when one exists
105
+ // (typically a local upload preview) without touching the image endpoint.
106
+ if (!isErrorFileState(fileState) && fileState.preview) {
107
+ return;
108
+ }
109
+
110
+ // Otherwise it waits for the backend image representation before fetching.
111
+ if (!isImageRepresentationReady(fileState)) {
112
+ return;
113
+ }
114
+ }
115
+ if (isMeteredConnection()) {
116
+ return;
117
+ }
118
+ var mediaClient = getMediaClient();
119
+ var id = identifier.id,
120
+ collectionName = identifier.collectionName;
121
+ var warmImage = function warmImage(watermarkVersion) {
122
+ var key = getWarmedImageKey({
123
+ id: id,
124
+ collectionName: collectionName,
125
+ watermarkVersion: watermarkVersion
126
+ });
127
+
128
+ // An existing entry is either still downloading or already resolved. Either way
129
+ // the viewer can take it, so there is nothing to do. Checked after the version
130
+ // resolves, so repeated hovers still make one request.
131
+ if (hasWarmedImage(key)) {
132
+ return;
133
+ }
134
+ var controller = new AbortController();
135
+ var startedAt = Date.now();
136
+ var fileSize = fileState && !isErrorFileState(fileState) ? fileState.size : undefined;
137
+ var fileAttributes = _objectSpread({
138
+ fileId: id,
139
+ fileMediatype: resolvedMediaType,
140
+ fileMimetype: mimeType
141
+ }, fileSize !== undefined && {
142
+ fileSize: fileSize
143
+ });
144
+ var report = function report(createPayload) {
145
+ try {
146
+ // Sanitised here, as every media channel event is, so each caller sends the
147
+ // same masked payload.
148
+ onAnalyticsEvent === null || onAnalyticsEvent === void 0 || onAnalyticsEvent(sanitiseAnalyticsPayload(createPayload()));
149
+ } catch (_unused) {
150
+ // Analytics must never break the warm-up.
151
+ }
152
+ };
153
+ var isSampled = !!onAnalyticsEvent && Math.random() < PRELOAD_ENDED_SAMPLING_RATE;
154
+ setWarmedImage(key, {
155
+ image: mediaClient.getImage(id, getImageViewerRequestParams(collectionName), controller, IMAGE_VIEWER_FETCH_MAX_RES, traceContext, WARM_UP_CLIENT_OPTIONS),
156
+ controller: controller
157
+ }, onAnalyticsEvent && {
158
+ onEnd: isSampled ? function (outcome, blob) {
159
+ return report(function () {
160
+ return createPreloadEndedEventPayload({
161
+ outcome: outcome,
162
+ blob: blob,
163
+ durationMs: Date.now() - startedAt,
164
+ fileAttributes: fileAttributes,
165
+ traceContext: traceContext,
166
+ samplingRate: PRELOAD_ENDED_SAMPLING_RATE
167
+ });
168
+ });
169
+ } : undefined,
170
+ onError: function onError(error, wasTaken) {
171
+ return report(function () {
172
+ return createPreloadFailedEventPayload({
173
+ error: error,
174
+ wasTaken: wasTaken,
175
+ durationMs: Date.now() - startedAt,
176
+ fileAttributes: fileAttributes,
177
+ traceContext: traceContext
178
+ });
179
+ });
180
+ }
181
+ });
182
+ };
183
+
184
+ // The key carries the watermark version the image request is made with, so a
185
+ // warm-up made before a watermark config change never reaches a viewer opened after
186
+ // it. If auth fails, the image request would fail too, so only the chunks are warmed
187
+ // and the viewer's own request reports the failure. Called inside a promise, so a
188
+ // throw (say, from an older media-client without the method) can't reach the hover
189
+ // handler that called this.
190
+ void Promise.resolve().then(function () {
191
+ return mediaClient.getImageWatermarkVersion(collectionName);
192
+ }).then(warmImage, function () {});
193
+ };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * `ImageViewer` asks for the image at media-client's maximum resolution so it stays
3
+ * sharp when zoomed in.
4
+ */
5
+ export var IMAGE_VIEWER_FETCH_MAX_RES = true;
6
+
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 var getImageViewerRequestParams = function getImageViewerRequestParams(collectionName) {
16
+ return {
17
+ collection: collectionName,
18
+ mode: 'fit'
19
+ };
20
+ };