Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 71 additions & 24 deletions src/lib/viewers/image/ImageViewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import {
CLASS_INVISIBLE,
DISCOVERABILITY_ATTRIBUTE,
IMAGE_FTUX_CURSOR_SEEN_KEY,
STATUS_NONE,
STATUS_PENDING,
} from '../../constants';
import { LOAD_METRIC, FIRST_RENDER_METRIC, VIEWER_EVENT } from '../../events';
import Timer from '../../Timer';
Expand All @@ -24,7 +22,6 @@ const IMAGE_ZOOM_SCALE = 1.2;
const PLACEHOLDER_DISPLAY_SIZE = 920;
const PLACEHOLDER_FADE_MS = 500;
const PLACEHOLDER_REP = 'jpg_320x320';
const CONVERTING_STATES = [STATUS_NONE, STATUS_PENDING];

class ImageViewer extends ImageBaseViewer {
/** @inheritdoc */
Expand Down Expand Up @@ -134,10 +131,7 @@ class ImageViewer extends ImageBaseViewer {
this.bindDOMListeners();

const contentUrl = this.createContentUrlV2(template, viewer.ASSET);
if (
this.featureEnabled('imageConversionPlaceholder.enabled') &&
CONVERTING_STATES.includes(representation.status?.state)
) {
if (this.featureEnabled('imageConversionPlaceholder.enabled')) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return this.loadWithPlaceholder(contentUrl);
}

Expand Down Expand Up @@ -169,8 +163,8 @@ class ImageViewer extends ImageBaseViewer {
}

/**
* Shows the 320 thumbnail while the image rep converts, zoomed to PLACEHOLDER_DISPLAY_SIZE,
* then swaps in the image rep once it is ready. Falls back to waiting for the image rep, with
* Shows the 320 thumbnail first, zoomed to PLACEHOLDER_DISPLAY_SIZE, then swaps in the image
* rep once it is ready. Falls back to waiting for the image rep, with
* the host's loading indicator, when the 320 is not available either.
*
* @param {string} contentUrl - Content URL of the image rep
Expand All @@ -195,7 +189,7 @@ class ImageViewer extends ImageBaseViewer {
() => undefined,
);

return this.fetchDecodedImage(placeholderUrl)
return this.getPlaceholderImage(placeholderUrl)
.then(
placeholder => {
if (this.isDestroyed()) {
Expand Down Expand Up @@ -244,20 +238,73 @@ class ImageViewer extends ImageBaseViewer {
* @return {Promise<Object>} blobUrl, width and height of the decoded image
*/
fetchDecodedImage(url) {
return this.fetchContentAsBlobUrl(url).then(blobUrl => {
const decoder = new Image();
decoder.src = blobUrl;
return decoder
.decode()
.catch(() => undefined)
.then(() => {
if (!decoder.naturalWidth) {
URL.revokeObjectURL(blobUrl);
throw new Error('Response is not a decodable image');
}
return { blobUrl, height: decoder.naturalHeight, width: decoder.naturalWidth };
});
});
return this.fetchContentAsBlobUrl(url).then(blobUrl => this.decodeBlobUrl(blobUrl));
}

/**
* Whether the placeholder viewer option is for the file and version being previewed. Without
* a version, it is taken to be the current version's, so it is only used when no other
* version was requested.
*
* @param {Object} [hostPlaceholder] - fileId, optional fileVersionId, and url
* @return {boolean}
*/
isHostPlaceholderForFile(hostPlaceholder) {
const fileId = getProp(this.options, 'file.id');
if (!hostPlaceholder?.url || !fileId || String(hostPlaceholder.fileId) !== String(fileId)) {
return false;
}
if (hostPlaceholder.fileVersionId) {
return String(hostPlaceholder.fileVersionId) === String(getProp(this.options, 'file.file_version.id'));
}
return !getProp(this.options, ['fileOptions', fileId, 'fileVersionId']);
}

/**
* Gets the placeholder shown before the image rep. Uses the image the host passed in the
* placeholder viewer option, such as a thumbnail it already loaded, when it is for the file
* being previewed, and fetches the 320 otherwise.
*
* @param {string} placeholderUrl - Content URL of the 320
* @return {Promise<Object>} blobUrl, width and height of the decoded placeholder
*/
getPlaceholderImage(placeholderUrl) {
const hostPlaceholder = this.getViewerOption('placeholder');
if (!this.isHostPlaceholderForFile(hostPlaceholder)) {
return this.fetchDecodedImage(placeholderUrl);
}

// The host owns its URL and may revoke it, so decode a copy that this viewer can revoke.
return fetch(hostPlaceholder.url)
.then(response => {
if (!response.ok) {
throw new Error(`Host placeholder fetch failed: ${response.status}`);
}
return response.blob();
})
.then(blob => this.decodeBlobUrl(URL.createObjectURL(blob)))
.catch(() => this.fetchDecodedImage(placeholderUrl));
}

/**
* Decodes an image blob URL. Rejects, and revokes the URL, when it is not an image.
*
* @param {string} blobUrl - Blob URL of the image
* @return {Promise<Object>} blobUrl, width and height of the decoded image
*/
decodeBlobUrl(blobUrl) {
const decoder = new Image();
decoder.src = blobUrl;
return decoder
.decode()
.catch(() => undefined)
.then(() => {
if (!decoder.naturalWidth) {
URL.revokeObjectURL(blobUrl);
throw new Error('Response is not a decodable image');
}
return { blobUrl, height: decoder.naturalHeight, width: decoder.naturalWidth };
});
}

/**
Expand Down
72 changes: 67 additions & 5 deletions src/lib/viewers/image/__tests__/ImageViewer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,13 +208,14 @@ describe('lib/viewers/image/ImageViewer', () => {
expect(image.fetchDecodedImage).not.toHaveBeenCalled();
});

test.each(['success', 'error'])('should wait for the image rep as before when its state is %s', state => {
image.options.representation.status.state = state;
jest.spyOn(image, 'fetchDecodedImage');
test('should show the 320 first when the image rep is already ready', async () => {
image.options.representation.status.state = 'success';
jest.spyOn(image, 'fetchDecodedImage').mockResolvedValue({ blobUrl: 'blob:320', height: 240, width: 320 });

image.load();
await image.load();

expect(image.fetchDecodedImage).not.toHaveBeenCalled();
expect(image.fetchDecodedImage).toHaveBeenCalledWith(placeholderUrl);
expect(image.imageEl.src).toBe('blob:320');
});

test('should show the 320 without telling the host the rep is converting', async () => {
Expand Down Expand Up @@ -305,6 +306,67 @@ describe('lib/viewers/image/ImageViewer', () => {
});
});

describe('getPlaceholderImage()', () => {
const placeholderUrl = 'https://dl.example.com/representations/jpg_320x320/content/';
const decoded = { blobUrl: 'blob:copy', height: 768, width: 1024 };
let originalFetch;

beforeEach(() => {
originalFetch = global.fetch;
global.fetch = jest.fn().mockResolvedValue({ blob: () => Promise.resolve(new Blob(['img'])), ok: true });
jest.spyOn(URL, 'createObjectURL').mockReturnValue('blob:copy');
jest.spyOn(image, 'decodeBlobUrl').mockResolvedValue(decoded);
jest.spyOn(image, 'fetchDecodedImage').mockResolvedValue({ blobUrl: 'blob:320', height: 240, width: 320 });
});

afterEach(() => {
global.fetch = originalFetch;
});

test.each([
['the previewed version', { fileId: '1', fileVersionId: 1, url: 'blob:host' }],
['the file, with no version, while previewing the current version', { fileId: 1, url: 'blob:host' }],
])('should decode a copy of the host placeholder for %s', async (_, placeholder) => {
image.options.viewers = { Image: { placeholder } };

await expect(image.getPlaceholderImage(placeholderUrl)).resolves.toBe(decoded);
expect(global.fetch).toHaveBeenCalledWith('blob:host');
expect(image.decodeBlobUrl).toHaveBeenCalledWith('blob:copy');
expect(image.fetchDecodedImage).not.toHaveBeenCalled();
});

test.each([
['there is no host placeholder', undefined, undefined],
['the host placeholder is for another file', { fileId: '2', url: 'blob:host' }, undefined],
[
'the host placeholder is for another version',
{ fileId: '1', fileVersionId: '2', url: 'blob:host' },
undefined,
],
['another version is requested', { fileId: '1', url: 'blob:host' }, { 1: { fileVersionId: '3' } }],
])('should fetch the 320 when %s', async (_, placeholder, fileOptions) => {
image.options.viewers = { Image: { placeholder } };
image.options.fileOptions = fileOptions;

await image.getPlaceholderImage(placeholderUrl);

expect(global.fetch).not.toHaveBeenCalled();
expect(image.fetchDecodedImage).toHaveBeenCalledWith(placeholderUrl);
});

test.each([
['cannot be read', () => Promise.reject(new TypeError('Failed to fetch'))],
['returns an error status', () => Promise.resolve({ ok: false, status: 404 })],
])('should fetch the 320 when the host placeholder %s', async (_, fetchResult) => {
image.options.viewers = { Image: { placeholder: { fileId: '1', url: 'blob:revoked' } } };
global.fetch.mockImplementation(fetchResult);

await image.getPlaceholderImage(placeholderUrl);

expect(image.fetchDecodedImage).toHaveBeenCalledWith(placeholderUrl);
});
});

describe('waitForViewerLoad()', () => {
test('should resolve immediately if the viewer has loaded', async () => {
image.loaded = true;
Expand Down
Loading