@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
package/AGENTS.md CHANGED
@@ -55,7 +55,27 @@ first, edit, then `kg.py edit <path> --message "<reason>"`.
55
55
 
56
56
  - React Compiler is enabled for this package
57
57
  - Peer dependencies: `@emotion/react`, `react`, `react-dom`, `react-intl`
58
- - Export subpaths: `.`, `./classnames`, `./media-viewer-loader`, `./types`, `./viewer-options`
58
+ - Export subpaths: `.`, `./classnames`, `./media-viewer-loader`, `./preload`, `./types`,
59
+ `./viewer-options`
60
+ - `./preload` exports `preloadMediaViewer`, called from hover/focus handlers in
61
+ `@atlaskit/media-card` and `@atlaskit/editor-plugin-media` to warm the viewer chunks and the full
62
+ resolution image ahead of the click. The in-flight request and its `AbortController` are held in
63
+ `src/warmedImages.ts` (at most 2 entries, 30 s each). `ImageViewer` takes the entry and awaits the
64
+ same request instead of issuing its own, so the image downloads once even when the click lands
65
+ mid-download. Once taken, the viewer owns the download and closing it aborts the request. Entries
66
+ nobody takes are aborted on eviction or expiry. Don't rely on the browser HTTP cache for this: the
67
+ warm-up is usually still downloading when the user clicks. Behind the
68
+ `platform_media_viewer_preload_on_hover` experiment. `preloadMediaViewer` is the only exposure
69
+ point and fires in both arms on hover or focus. `ImageViewer` has no check of its own: warm-ups
70
+ only exist in treatment. The store is on `globalThis` under
71
+ `Symbol.for('@atlaskit/media-viewer/warmed-images/v1')`, because a bundler can copy the module
72
+ into the card's bundle and the image viewer chunk separately. Bump the key if `Entry` changes.
73
+ Entries are keyed by file, collection and the `wmv` from `MediaClient.getImageWatermarkVersion`,
74
+ so a warm-up made before a watermark config change is never taken by a viewer opened after it. The
75
+ warm-up resolves the version before it touches the store. `ImageViewer` resolves it only when the
76
+ store holds a warm-up for the file, so control makes no extra auth call. The warm-up makes one
77
+ attempt (`retryOptions.maxAttempts: 1`) and reports `mediaFile` `preloadFailed` and a sampled
78
+ `preloadEnded` through the caller's `onAnalyticsEvent`. Aborts are not failures.
59
79
  - Supports custom viewer via `CustomRendererConfig`
60
80
  - Inset presentation: when `extensions.useInsetViewer` is set and the
61
81
  `cc_comments_inset_media_viewer` gate is on, `media-viewer.tsx` computes `isInsetViewer` once and
package/CHANGELOG.md CHANGED
@@ -1,5 +1,55 @@
1
1
  # @atlaskit/media-viewer
2
2
 
3
+ ## 54.12.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies
8
+
9
+ ## 54.12.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [`c570c6f9b75f7`](https://bitbucket.org/atlassian/atlassian-frontend-monorepo/commits/c570c6f9b75f7) -
14
+ Add a new `@atlaskit/media-viewer/preload` entry point exporting `preloadMediaViewer`, which warms
15
+ what the viewer needs for a file before the user opens it: the lazily loaded viewer chunks, and
16
+ the full resolution image binary.
17
+
18
+ The image request is fetched with the exact params `ImageViewer` uses and is held with its
19
+ `AbortController`. `ImageViewer` takes that request and awaits it rather than issuing a second
20
+ one. This holds whether the warm-up has finished or is still downloading, which matters because a
21
+ multi-megabyte image is usually still in flight when the user clicks. Once taken, the viewer owns
22
+ the download, so closing the viewer aborts it.
23
+
24
+ At most two untaken warm-ups are held, for up to 30 seconds each. Warm-ups that are evicted or
25
+ expire are aborted. An image already being warmed is not requested again. The image is only warmed
26
+ for non-SVG images. When the caller passes the file state, it is also skipped until the backend
27
+ image representation exists, and skipped when the viewer would render a local preview. The image
28
+ warm-up is skipped when the connection reports data saver or an effective type of 3g or slower.
29
+ The chunks are still loaded.
30
+
31
+ The warm-up makes one attempt with no retries, so a failing image endpoint gets no extra load from
32
+ backoff. Pass `onAnalyticsEvent` to receive its operational events: `mediaFile` `preloadFailed` on
33
+ any failure other than an abort, never sampled, and `mediaFile` `preloadEnded` for 10% of
34
+ warm-ups, with whether the viewer took it or it expired, was evicted or failed.
35
+
36
+ The warmed image store lives on `globalThis` under a versioned `Symbol.for` key, so copies of the
37
+ module in different bundles share it. Warm-ups are keyed by the watermark version (`wmv`) of their
38
+ request as well as the file, so a viewer opened after a watermark config change never takes a
39
+ warm-up made before it.
40
+
41
+ The `import()` calls for the lazily loaded media viewer and image viewer chunks are consolidated
42
+ into a single call site each, so the warm-up cannot request a different chunk than the render
43
+ path.
44
+
45
+ Behind the `platform_media_viewer_preload_on_hover` experiment. `preloadMediaViewer` fires the
46
+ exposure on hover or focus in both arms, before they differ, and takes a lazy `getMediaClient` so
47
+ the control arm creates no client.
48
+
49
+ ### Patch Changes
50
+
51
+ - Updated dependencies
52
+
3
53
  ## 54.11.28
4
54
 
5
55
  ### Patch Changes
@@ -24,6 +24,7 @@ var _loadSucceeded = require("./analytics/events/operational/loadSucceeded");
24
24
  var _fireAnalytics = require("./analytics/fireAnalytics");
25
25
  var _getFileAttributes = require("./analytics/getFileAttributes");
26
26
  var _ufoExperiences = require("./analytics/ufoExperiences");
27
+ var _chunkLoaders = require("./chunkLoaders");
27
28
  var _outcome = require("./domain/outcome");
28
29
  var _errorMessageWithAnalytics = _interopRequireDefault(require("./errorMessageWithAnalytics"));
29
30
  var _ErrorViewDownloadButton = require("./ErrorViewDownloadButton");
@@ -35,11 +36,8 @@ var _archiveViewerLoader = _interopRequireDefault(require("./viewers/archiveSide
35
36
  var _customViewer = require("./viewers/customViewer/customViewer");
36
37
  var _interactiveImg = require("./viewers/image/interactive-img");
37
38
  function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != (0, _typeof2.default)(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
38
- function loadImageViewer() {
39
- return Promise.resolve().then(function () {
40
- return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_imageViewer" */'./viewers/image'));
41
- });
42
- }
39
+ // Shared with `./preload` so the warm-up and the render path load the same chunk.
40
+ var loadImageViewer = _chunkLoaders.loadImageViewerChunk;
43
41
  var LoadableImageViewer = (0, _reactLoadable.default)({
44
42
  loader: function loader() {
45
43
  return loadImageViewer().then(function (mod) {
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createPreloadFailedEventPayload = exports.createPreloadEndedEventPayload = void 0;
7
+ var _getErrorDetail = require("../../../getErrorDetail");
8
+ var _getPrimaryErrorReason = require("../../../getPrimaryErrorReason");
9
+ var _getRequestMetadata = require("../../../getRequestMetadata");
10
+ var _getSecondaryErrorReason = require("../../../getSecondaryErrorReason");
11
+ var _MediaViewerError = require("../../../MediaViewerError");
12
+ /** Fired when a warm-up request fails for a reason other than an abort. Never sampled. */
13
+
14
+ /** Fired once per sampled warm-up, when it leaves the warmed image store. */
15
+
16
+ var createPreloadFailedEventPayload = exports.createPreloadFailedEventPayload = function createPreloadFailedEventPayload(_ref) {
17
+ var error = _ref.error,
18
+ wasTaken = _ref.wasTaken,
19
+ durationMs = _ref.durationMs,
20
+ fileAttributes = _ref.fileAttributes,
21
+ traceContext = _ref.traceContext;
22
+ var viewerError = new _MediaViewerError.MediaViewerError('preload-image-fetch', error instanceof Error ? error : undefined);
23
+ var requestMetadata = (0, _getRequestMetadata.getRequestMetadata)(viewerError);
24
+ return {
25
+ eventType: 'operational',
26
+ actionSubject: 'mediaFile',
27
+ action: 'preloadFailed',
28
+ attributes: {
29
+ status: 'fail',
30
+ failReason: (0, _getPrimaryErrorReason.getPrimaryErrorReason)(viewerError),
31
+ error: (0, _getSecondaryErrorReason.getSecondaryErrorReason)(viewerError),
32
+ errorDetail: (0, _getErrorDetail.getErrorDetail)(viewerError),
33
+ statusCode: requestMetadata === null || requestMetadata === void 0 ? void 0 : requestMetadata.statusCode,
34
+ request: requestMetadata,
35
+ fileMimetype: fileAttributes.fileMimetype,
36
+ fileMediatype: fileAttributes.fileMediatype,
37
+ fileAttributes: fileAttributes,
38
+ traceContext: traceContext,
39
+ wasTaken: wasTaken,
40
+ durationMs: durationMs
41
+ }
42
+ };
43
+ };
44
+ var createPreloadEndedEventPayload = exports.createPreloadEndedEventPayload = function createPreloadEndedEventPayload(_ref2) {
45
+ var outcome = _ref2.outcome,
46
+ blob = _ref2.blob,
47
+ durationMs = _ref2.durationMs,
48
+ fileAttributes = _ref2.fileAttributes,
49
+ traceContext = _ref2.traceContext,
50
+ samplingRate = _ref2.samplingRate;
51
+ return {
52
+ eventType: 'operational',
53
+ actionSubject: 'mediaFile',
54
+ action: 'preloadEnded',
55
+ attributes: {
56
+ outcome: outcome,
57
+ resolved: !!blob,
58
+ sizeBytes: blob === null || blob === void 0 ? void 0 : blob.size,
59
+ durationMs: durationMs,
60
+ fileAttributes: fileAttributes,
61
+ traceContext: traceContext,
62
+ isSamplingEnabled: samplingRate < 1,
63
+ samplingRate: samplingRate
64
+ }
65
+ };
66
+ };
@@ -14,7 +14,7 @@ var _experienceTypes = require("@atlaskit/ufo/experience-types");
14
14
  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; }
15
15
  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) { (0, _defineProperty2.default)(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; }
16
16
  var packageName = "@atlaskit/media-viewer";
17
- var packageVersion = "54.11.27";
17
+ var packageVersion = "54.12.0";
18
18
  var ufoExperience;
19
19
  var getExperience = function getExperience() {
20
20
  if (!ufoExperience) {
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.loadMediaViewerChunk = exports.loadImageViewerChunk = void 0;
8
+ var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
9
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != (0, _typeof2.default)(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
10
+ /**
11
+ * The single call site for each lazily loaded chunk that `./preload` warms.
12
+ *
13
+ * Both the render path and the warm-up path must go through these. Repeating an
14
+ * `import()` with the same `webpackChunkName` in two files relies on the two
15
+ * comments staying identical forever; if they drift, the warm-up fetches a
16
+ * different chunk than the one the viewer loads and silently does nothing.
17
+ */
18
+
19
+ var loadMediaViewerChunk = exports.loadMediaViewerChunk = function loadMediaViewerChunk() {
20
+ return Promise.resolve().then(function () {
21
+ return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_media-viewer" */'./components/media-viewer-error-boundary'));
22
+ });
23
+ };
24
+ var loadImageViewerChunk = exports.loadImageViewerChunk = function loadImageViewerChunk() {
25
+ return Promise.resolve().then(function () {
26
+ return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_imageViewer" */'./viewers/image'));
27
+ });
28
+ };
@@ -1,19 +1,18 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ var _typeof = require("@babel/runtime/helpers/typeof");
4
5
  Object.defineProperty(exports, "__esModule", {
5
6
  value: true
6
7
  });
7
8
  exports.default = AsyncMediaViewer;
8
- var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
9
9
  var _react = _interopRequireWildcard(require("react"));
10
+ var _chunkLoaders = require("../chunkLoaders");
10
11
  var _modalSpinner = _interopRequireDefault(require("../viewers/modalSpinner"));
11
12
  var _portal = require("./portal");
12
- function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != (0, _typeof2.default)(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
13
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
13
14
  var MediaViewer = /*#__PURE__*/(0, _react.lazy)(function () {
14
- return Promise.resolve().then(function () {
15
- return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_media-viewer" */'./media-viewer-error-boundary'));
16
- }).then(function (_ref) {
15
+ return (0, _chunkLoaders.loadMediaViewerChunk)().then(function (_ref) {
17
16
  var MediaViewerWithErrorBoundary = _ref.MediaViewerWithErrorBoundary;
18
17
  return {
19
18
  default: MediaViewerWithErrorBoundary
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.preloadMediaViewer = void 0;
8
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
9
+ var _isErrorFileState = require("@atlaskit/media-client/is-error-file-state");
10
+ var _isFileIdentifier = require("@atlaskit/media-client/is-file-identifier");
11
+ var _isImageRepresentationReady = require("@atlaskit/media-client/is-image-representation-ready");
12
+ var _mediaTypeUtils = require("@atlaskit/media-common/mediaTypeUtils");
13
+ var _sanitisePayload = require("@atlaskit/media-common/sanitisePayload");
14
+ var _isExperimentEnabled = require("@atlaskit/platform-feature-experiments/is-experiment-enabled");
15
+ var _preload = require("./analytics/events/operational/preload");
16
+ var _chunkLoaders = require("./chunkLoaders");
17
+ var _imageRequestParams = require("./viewers/image/imageRequestParams");
18
+ var _warmedImages = require("./warmedImages");
19
+ 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; }
20
+ 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) { (0, _defineProperty2.default)(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; }
21
+ /**
22
+ * Share of warm-ups that report `preloadEnded`, which measures how many warm-ups the
23
+ * viewer takes. `preloadFailed` is never sampled.
24
+ */
25
+ var PRELOAD_ENDED_SAMPLING_RATE = 0.1;
26
+
27
+ /**
28
+ * A warm-up is speculative, so it doesn't retry a failure with backoff. Retrying a
29
+ * 5xx would add load when the image endpoint is already struggling, and the viewer
30
+ * makes its own request on open anyway. media-client's Edge network-error fallback
31
+ * still applies. `fetchRetry` waits `startTimeoutInMs` even
32
+ * after the last attempt, so it is zero: a failed warm-up a viewer has taken then
33
+ * hands over to the viewer's own request without a pause.
34
+ */
35
+ var WARM_UP_CLIENT_OPTIONS = {
36
+ retryOptions: {
37
+ maxAttempts: 1,
38
+ startTimeoutInMs: 0
39
+ }
40
+ };
41
+
42
+ /** SVGs are rendered by `SvgViewer`, which does not go through the image endpoint. */
43
+ var SVG_MIME_TYPE = 'image/svg+xml';
44
+
45
+ /**
46
+ * Effective connection types where speculatively downloading a full resolution
47
+ * image costs the user more than the latency it saves.
48
+ */
49
+ var METERED_EFFECTIVE_TYPES = ['slow-2g', '2g', '3g'];
50
+ var isMeteredConnection = function isMeteredConnection() {
51
+ if (typeof navigator === 'undefined') {
52
+ return false;
53
+ }
54
+ var _ref = navigator,
55
+ connection = _ref.connection;
56
+ if (!connection) {
57
+ return false;
58
+ }
59
+ return !!connection.saveData || !!connection.effectiveType && METERED_EFFECTIVE_TYPES.includes(connection.effectiveType);
60
+ };
61
+ /**
62
+ * Speculatively warms what the media viewer needs to display `identifier`, so
63
+ * that opening it is closer to instant. Intended to be called from a hover or
64
+ * focus handler on whatever opens the viewer.
65
+ *
66
+ * Two things get warmed:
67
+ * - the lazily loaded viewer chunks, and
68
+ * - the full resolution image binary, whose in-flight request is kept in
69
+ * `./warmedImages` for `ImageViewer` to take instead of issuing its own.
70
+ *
71
+ * The image request starts once media-client has resolved the watermark version
72
+ * it carries, because the version is part of the warmed image's key.
73
+ *
74
+ * The image binary is only warmed when the file is known to be a non-SVG image,
75
+ * because `ImageViewer` is the only viewer that makes this request. Callers that
76
+ * know nothing about the file still get the chunk warm-up.
77
+ *
78
+ * Safe to call repeatedly and safe to call for files the user never opens: an
79
+ * image already being warmed is not requested again, a failed image request is not
80
+ * retried and its rejection is handled, and no image is fetched on metered or slow
81
+ * connections. Failures and outcomes go to `onAnalyticsEvent`.
82
+ *
83
+ * This is the exposure point for the `platform_media_viewer_preload_on_hover`
84
+ * experiment. Callers attach their handlers in both arms, and the exposure fires
85
+ * here before the arms differ, so both arms are exposed on the same hover or focus.
86
+ */
87
+ var preloadMediaViewer = exports.preloadMediaViewer = function preloadMediaViewer(_ref2) {
88
+ var getMediaClient = _ref2.getMediaClient,
89
+ identifier = _ref2.identifier,
90
+ mimeType = _ref2.mimeType,
91
+ mediaType = _ref2.mediaType,
92
+ fileState = _ref2.fileState,
93
+ traceContext = _ref2.traceContext,
94
+ onAnalyticsEvent = _ref2.onAnalyticsEvent;
95
+ // External images need no warm-up: the viewer renders the same `dataURI` the
96
+ // card is already displaying. Checked before the exposure, so neither arm is
97
+ // exposed for them.
98
+ if (!(0, _isFileIdentifier.isFileIdentifier)(identifier)) {
99
+ return;
100
+ }
101
+ if (!(0, _isExperimentEnabled.isExperimentEnabled)('platform_media_viewer_preload_on_hover')) {
102
+ return;
103
+ }
104
+ void (0, _chunkLoaders.loadMediaViewerChunk)().catch(function () {});
105
+ var resolvedMediaType = mediaType !== null && mediaType !== void 0 ? mediaType : mimeType ? (0, _mediaTypeUtils.getMediaTypeFromMimeType)(mimeType) : undefined;
106
+ if (resolvedMediaType !== 'image' || mimeType === SVG_MIME_TYPE) {
107
+ return;
108
+ }
109
+ void (0, _chunkLoaders.loadImageViewerChunk)().catch(function () {});
110
+ if (fileState) {
111
+ // `ImageViewer` renders `fileState.preview` directly when one exists
112
+ // (typically a local upload preview) without touching the image endpoint.
113
+ if (!(0, _isErrorFileState.isErrorFileState)(fileState) && fileState.preview) {
114
+ return;
115
+ }
116
+
117
+ // Otherwise it waits for the backend image representation before fetching.
118
+ if (!(0, _isImageRepresentationReady.isImageRepresentationReady)(fileState)) {
119
+ return;
120
+ }
121
+ }
122
+ if (isMeteredConnection()) {
123
+ return;
124
+ }
125
+ var mediaClient = getMediaClient();
126
+ var id = identifier.id,
127
+ collectionName = identifier.collectionName;
128
+ var warmImage = function warmImage(watermarkVersion) {
129
+ var key = (0, _warmedImages.getWarmedImageKey)({
130
+ id: id,
131
+ collectionName: collectionName,
132
+ watermarkVersion: watermarkVersion
133
+ });
134
+
135
+ // An existing entry is either still downloading or already resolved. Either way
136
+ // the viewer can take it, so there is nothing to do. Checked after the version
137
+ // resolves, so repeated hovers still make one request.
138
+ if ((0, _warmedImages.hasWarmedImage)(key)) {
139
+ return;
140
+ }
141
+ var controller = new AbortController();
142
+ var startedAt = Date.now();
143
+ var fileSize = fileState && !(0, _isErrorFileState.isErrorFileState)(fileState) ? fileState.size : undefined;
144
+ var fileAttributes = _objectSpread({
145
+ fileId: id,
146
+ fileMediatype: resolvedMediaType,
147
+ fileMimetype: mimeType
148
+ }, fileSize !== undefined && {
149
+ fileSize: fileSize
150
+ });
151
+ var report = function report(createPayload) {
152
+ try {
153
+ // Sanitised here, as every media channel event is, so each caller sends the
154
+ // same masked payload.
155
+ onAnalyticsEvent === null || onAnalyticsEvent === void 0 || onAnalyticsEvent((0, _sanitisePayload.sanitiseAnalyticsPayload)(createPayload()));
156
+ } catch (_unused) {
157
+ // Analytics must never break the warm-up.
158
+ }
159
+ };
160
+ var isSampled = !!onAnalyticsEvent && Math.random() < PRELOAD_ENDED_SAMPLING_RATE;
161
+ (0, _warmedImages.setWarmedImage)(key, {
162
+ image: mediaClient.getImage(id, (0, _imageRequestParams.getImageViewerRequestParams)(collectionName), controller, _imageRequestParams.IMAGE_VIEWER_FETCH_MAX_RES, traceContext, WARM_UP_CLIENT_OPTIONS),
163
+ controller: controller
164
+ }, onAnalyticsEvent && {
165
+ onEnd: isSampled ? function (outcome, blob) {
166
+ return report(function () {
167
+ return (0, _preload.createPreloadEndedEventPayload)({
168
+ outcome: outcome,
169
+ blob: blob,
170
+ durationMs: Date.now() - startedAt,
171
+ fileAttributes: fileAttributes,
172
+ traceContext: traceContext,
173
+ samplingRate: PRELOAD_ENDED_SAMPLING_RATE
174
+ });
175
+ });
176
+ } : undefined,
177
+ onError: function onError(error, wasTaken) {
178
+ return report(function () {
179
+ return (0, _preload.createPreloadFailedEventPayload)({
180
+ error: error,
181
+ wasTaken: wasTaken,
182
+ durationMs: Date.now() - startedAt,
183
+ fileAttributes: fileAttributes,
184
+ traceContext: traceContext
185
+ });
186
+ });
187
+ }
188
+ });
189
+ };
190
+
191
+ // The key carries the watermark version the image request is made with, so a
192
+ // warm-up made before a watermark config change never reaches a viewer opened after
193
+ // it. If auth fails, the image request would fail too, so only the chunks are warmed
194
+ // and the viewer's own request reports the failure. Called inside a promise, so a
195
+ // throw (say, from an older media-client without the method) can't reach the hover
196
+ // handler that called this.
197
+ void Promise.resolve().then(function () {
198
+ return mediaClient.getImageWatermarkVersion(collectionName);
199
+ }).then(warmImage, function () {});
200
+ };
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getImageViewerRequestParams = exports.IMAGE_VIEWER_FETCH_MAX_RES = void 0;
7
+ /**
8
+ * `ImageViewer` asks for the image at media-client's maximum resolution so it stays
9
+ * sharp when zoomed in.
10
+ */
11
+ var IMAGE_VIEWER_FETCH_MAX_RES = exports.IMAGE_VIEWER_FETCH_MAX_RES = true;
12
+
13
+ /**
14
+ * Params `ImageViewer` uses to fetch the image it renders.
15
+ *
16
+ * Shared with `preloadMediaViewer` so a warm-up fetches exactly the bytes the
17
+ * viewer will render, and the resulting blob can be handed straight to it. Media
18
+ * cards request the image at their own rendered size, usually with a different
19
+ * `mode`, so a card's image is never a substitute for this one.
20
+ */
21
+ var getImageViewerRequestParams = exports.getImageViewerRequestParams = function getImageViewerRequestParams(collectionName) {
22
+ return {
23
+ collection: collectionName,
24
+ mode: 'fit'
25
+ };
26
+ };