Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: support image source objects #1470

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
59 changes: 41 additions & 18 deletions packages/react-native-web/src/exports/Image/ImageUriCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,57 +7,80 @@
* @flow
*/

const dataUriPattern = /^data:/;
import ImageLoader from '../../modules/ImageLoader';

type ImageSource =
| string
| number
| {
method: ?string,
uri: ?string,
headers: ?Object,
body: ?string
};

export default class ImageUriCache {
static _maximumEntries: number = 256;
static _entries = {};

static has(uri: string) {
static createCacheId(source: ImageSource) {
return JSON.stringify(ImageLoader.resolveSource(source));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a little concerned about using JSON.stringify here. We could use a Map instead

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I don't like it either but I could not find a smart way. The advantage of this approach is that you will always get the cached content for a combination of method, uri, headers and body. If we use a Map instead and use the source as a key then we somehow first need to get the reference to the source which leads to the same issue again. Or did you have something else in mind?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A Map can use objects as keys

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it allows object as keys but the reference is stored as a key and not the content of the object:

const map = new Map()
const key = { a: 1 }
map.set(key, true)

map.get(key) !== map.get({ a: 1 }) // true

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah that's a problem given how image sources are defined. I guess we're stuck with stringifying for now

}

static has(source: ImageSource) {
const entries = ImageUriCache._entries;
const cacheId = ImageUriCache.createCacheId(source);
return Boolean(entries[cacheId]);
}

static get(source: ImageSource) {
const entries = ImageUriCache._entries;
const isDataUri = dataUriPattern.test(uri);
return isDataUri || Boolean(entries[uri]);
const cacheId = ImageUriCache.createCacheId(source);
return entries[cacheId];
}

static add(uri: string) {
static add(source: ImageSource, displayImageUri: ?string) {
const entries = ImageUriCache._entries;
const lastUsedTimestamp = Date.now();
if (entries[uri]) {
entries[uri].lastUsedTimestamp = lastUsedTimestamp;
entries[uri].refCount += 1;
const cacheId = ImageUriCache.createCacheId(source);
if (entries[cacheId]) {
entries[cacheId].lastUsedTimestamp = lastUsedTimestamp;
entries[cacheId].refCount += 1;
} else {
entries[uri] = {
entries[cacheId] = {
lastUsedTimestamp,
refCount: 1
refCount: 1,
displayImageUri: displayImageUri || ImageLoader.resolveSource(source).uri
};
}
}

static remove(uri: string) {
static remove(source: ImageSource) {
const entries = ImageUriCache._entries;
if (entries[uri]) {
entries[uri].refCount -= 1;
const cacheId = ImageUriCache.createCacheId(source);
if (entries[cacheId]) {
entries[cacheId].refCount -= 1;
}
// Free up entries when the cache is "full"
ImageUriCache._cleanUpIfNeeded();
}

static _cleanUpIfNeeded() {
const entries = ImageUriCache._entries;
const imageUris = Object.keys(entries);
const cacheIds = Object.keys(entries);

if (imageUris.length + 1 > ImageUriCache._maximumEntries) {
if (cacheIds.length + 1 > ImageUriCache._maximumEntries) {
let leastRecentlyUsedKey;
let leastRecentlyUsedEntry;

imageUris.forEach(uri => {
const entry = entries[uri];
cacheIds.forEach(cacheId => {
const entry = entries[cacheId];
if (
(!leastRecentlyUsedEntry ||
entry.lastUsedTimestamp < leastRecentlyUsedEntry.lastUsedTimestamp) &&
entry.refCount === 0
) {
leastRecentlyUsedKey = uri;
leastRecentlyUsedKey = cacheId;
leastRecentlyUsedEntry = entry;
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import React from 'react';
import { shallow } from 'enzyme';
import StyleSheet from '../../StyleSheet';

const originalImage = window.Image;
const OriginalImage = window.Image;

const findImageSurfaceStyle = wrapper => StyleSheet.flatten(wrapper.childAt(0).prop('style'));

Expand All @@ -19,7 +19,7 @@ describe('components/Image', () => {
});

afterEach(() => {
window.Image = originalImage;
window.Image = OriginalImage;
});

test('prop "accessibilityLabel"', () => {
Expand Down Expand Up @@ -95,23 +95,24 @@ describe('components/Image', () => {
describe('prop "onLoad"', () => {
test('is called after image is loaded from network', () => {
jest.useFakeTimers();
const uri = 'https://test.com/img.jpg';
ImageLoader.load = jest.fn().mockImplementation((_, onLoad, onError) => {
onLoad();
onLoad(uri);
});
const onLoadStub = jest.fn();
shallow(<Image onLoad={onLoadStub} source="https://test.com/img.jpg" />);
shallow(<Image onLoad={onLoadStub} source={uri} />);
jest.runOnlyPendingTimers();
expect(ImageLoader.load).toBeCalled();
expect(onLoadStub).toBeCalled();
});

test('is called after image is loaded from cache', () => {
jest.useFakeTimers();
const uri = 'https://test.com/img.jpg';
ImageLoader.load = jest.fn().mockImplementation((_, onLoad, onError) => {
onLoad();
onLoad(uri);
});
const onLoadStub = jest.fn();
const uri = 'https://test.com/img.jpg';
ImageUriCache.add(uri);
shallow(<Image onLoad={onLoadStub} source={uri} />);
jest.runOnlyPendingTimers();
Expand Down Expand Up @@ -164,7 +165,7 @@ describe('components/Image', () => {
test('is set immediately if the image was preloaded', () => {
const uri = 'https://yahoo.com/favicon.ico';
ImageLoader.load = jest.fn().mockImplementationOnce((_, onLoad, onError) => {
onLoad();
onLoad(uri);
});
return Image.prefetch(uri).then(() => {
const source = { uri };
Expand Down Expand Up @@ -222,7 +223,7 @@ describe('components/Image', () => {
});
const component = shallow(<Image defaultSource={{ uri: defaultUri }} source={{ uri }} />);
expect(component.find('img').prop('src')).toBe(defaultUri);
loadCallback();
loadCallback(uri);
expect(component.find('img').prop('src')).toBe(uri);
});
});
Expand Down
Loading