-
Notifications
You must be signed in to change notification settings - Fork 591
/
imageCache.js
284 lines (235 loc) · 7.32 KB
/
imageCache.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import EVENTS, { events } from './events.js';
import triggerEvent from './triggerEvent.js';
/**
* This module deals with caching images
* @module ImageCache
*/
let maximumSizeInBytes = 1024 * 1024 * 1024; // 1 GB
let cacheSizeInBytes = 0;
// Dictionary of imageId to cachedImage objects
const imageCacheDict = {};
// Array of cachedImage objects
export const cachedImages = [];
/** Sets the maximum size of cache and purges cache contents if necessary.
*
* @param {number} numBytes The maximun size that the cache should occupy.
* @returns {void}
*/
export function setMaximumSizeBytes (numBytes) {
if (numBytes === undefined) {
throw new Error('setMaximumSizeBytes: parameter numBytes must not be undefined');
}
if (numBytes.toFixed === undefined) {
throw new Error('setMaximumSizeBytes: parameter numBytes must be a number');
}
maximumSizeInBytes = numBytes;
triggerEvent(events, EVENTS.IMAGE_CACHE_MAXIMUM_SIZE_CHANGED);
purgeCacheIfNecessary();
}
/**
* Purges the cache if size exceeds maximum
* @returns {void}
*/
function purgeCacheIfNecessary () {
// If max cache size has not been exceeded, do nothing
if (cacheSizeInBytes <= maximumSizeInBytes) {
return;
}
// Cache size has been exceeded, create list of images sorted by timeStamp
// So we can purge the least recently used image
function compare (a, b) {
if (a.timeStamp > b.timeStamp) {
return -1;
}
if (a.timeStamp < b.timeStamp) {
return 1;
}
return 0;
}
cachedImages.sort(compare);
// Remove images as necessary)
while (cacheSizeInBytes > maximumSizeInBytes) {
const lastCachedImage = cachedImages[cachedImages.length - 1];
const imageId = lastCachedImage.imageId;
removeImageLoadObject(imageId);
triggerEvent(events, EVENTS.IMAGE_CACHE_PROMISE_REMOVED, { imageId });
}
const cacheInfo = getCacheInfo();
triggerEvent(events, EVENTS.IMAGE_CACHE_FULL, cacheInfo);
}
/**
* Puts a new image loader into the cache
*
* @param {string} imageId ImageId of the image loader
* @param {Object} imageLoadObject The object that is loading or loaded the image
*/
export function putImageLoadObject (imageId, imageLoadObject) {
if (imageId === undefined) {
throw new Error('putImageLoadObject: imageId must not be undefined');
}
if (imageLoadObject.promise === undefined) {
throw new Error('putImageLoadObject: imageLoadObject.promise must not be undefined');
}
if (imageCacheDict.hasOwnProperty(imageId) === true) {
throw new Error('putImageLoadObject: imageId already in cache');
}
if (imageLoadObject.cancelFn && typeof imageLoadObject.cancelFn !== 'function') {
throw new Error('putImageLoadObject: imageLoadObject.cancelFn must be a function');
}
const cachedImage = {
loaded: false,
imageId,
sharedCacheKey: undefined, // The sharedCacheKey for this imageId. undefined by default
imageLoadObject,
timeStamp: Date.now(),
sizeInBytes: 0
};
imageCacheDict[imageId] = cachedImage;
cachedImages.push(cachedImage);
imageLoadObject.promise.then(function (image) {
if (cachedImages.indexOf(cachedImage) === -1) {
// If the image has been purged before being loaded, we stop here.
return;
}
cachedImage.loaded = true;
cachedImage.image = image;
if (image.sizeInBytes === undefined) {
throw new Error('putImageLoadObject: image.sizeInBytes must not be undefined');
}
if (image.sizeInBytes.toFixed === undefined) {
throw new Error('putImageLoadObject: image.sizeInBytes is not a number');
}
cachedImage.sizeInBytes = image.sizeInBytes;
cacheSizeInBytes += cachedImage.sizeInBytes;
const eventDetails = {
action: 'addImage',
image: cachedImage
};
triggerEvent(events, EVENTS.IMAGE_CACHE_CHANGED, eventDetails);
cachedImage.sharedCacheKey = image.sharedCacheKey;
purgeCacheIfNecessary();
}, () => {
const cachedImage = imageCacheDict[imageId];
cachedImages.splice(cachedImages.indexOf(cachedImage), 1);
delete imageCacheDict[imageId];
});
}
/**
* Retuns the object that is loading a given imageId
*
* @param {string} imageId
*/
export function getImageLoadObject (imageId) {
if (imageId === undefined) {
throw new Error('getImageLoadObject: imageId must not be undefined');
}
const cachedImage = imageCacheDict[imageId];
if (cachedImage === undefined) {
return;
}
// Bump time stamp for cached image
cachedImage.timeStamp = Date.now();
return cachedImage.imageLoadObject;
}
/**
* Removes the image loader associated with a given Id from the cache
*
* @param {string} imageId
*/
export function removeImageLoadObject (imageId) {
if (imageId === undefined) {
throw new Error('removeImageLoadObject: imageId must not be undefined');
}
const cachedImage = imageCacheDict[imageId];
if (cachedImage === undefined) {
throw new Error('removeImageLoadObject: imageId was not present in imageCache');
}
cachedImages.splice(cachedImages.indexOf(cachedImage), 1);
cacheSizeInBytes -= cachedImage.sizeInBytes;
const eventDetails = {
action: 'deleteImage',
image: cachedImage
};
triggerEvent(events, EVENTS.IMAGE_CACHE_CHANGED, eventDetails);
decache(cachedImage.imageLoadObject);
delete imageCacheDict[imageId];
}
/**
* @typedef {Object} CacheInformation
* @property {number} maximumSizeInBytes The maximum size of the cache in bytes
* @property {number} cacheSizeInBytes Currently occupied space in the cache in bytes
* @property {number} numberOfImagesCached Number of ImageLoaders in the cache
*/
/**
* Gets the current state of the cache
*/
export function getCacheInfo () {
return {
maximumSizeInBytes,
cacheSizeInBytes,
numberOfImagesCached: cachedImages.length
};
}
// This method should only be called by `removeImageLoadObject` because it's
// The one that knows how to deal with shared cache keys and cache size.
/**
* INTERNAL: Removes and ImageLoader from the cache
*
* @param {Object} imageLoadObject
*/
function decache (imageLoadObject) {
imageLoadObject.promise.then(
function () {
if (imageLoadObject.decache) {
imageLoadObject.decache();
}
},
function () {
if (imageLoadObject.decache) {
imageLoadObject.decache();
}
}
);
}
/**
* Removes all images from cache
*/
export function purgeCache () {
while (cachedImages.length > 0) {
const removedCachedImage = cachedImages[0];
removeImageLoadObject(removedCachedImage.imageId);
}
}
/**
* Updates the space than an image is using in the cache
*
* @param {string} imageId
* @param {number} newCacheSize
*/
export function changeImageIdCacheSize (imageId, newCacheSize) {
const cacheEntry = imageCacheDict[imageId];
if (cacheEntry) {
cacheEntry.imageLoadObject.promise.then(function (image) {
const cacheSizeDifference = newCacheSize - image.sizeInBytes;
image.sizeInBytes = newCacheSize;
cacheEntry.sizeInBytes = newCacheSize;
cacheSizeInBytes += cacheSizeDifference;
const eventDetails = {
action: 'changeImageSize',
image
};
triggerEvent(events, EVENTS.IMAGE_CACHE_CHANGED, eventDetails);
});
}
}
export default {
imageCache: imageCacheDict,
cachedImages,
setMaximumSizeBytes,
putImageLoadObject,
getImageLoadObject,
removeImageLoadObject,
getCacheInfo,
purgeCache,
changeImageIdCacheSize
};