-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex.js
367 lines (321 loc) · 10.3 KB
/
index.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { requireNativeComponent, NativeModules, Platform, Image, View } from 'react-native';
const LINKING_ERROR =
`The package 'react-native-blasted-image' doesn't seem to be linked. Make sure: \n\n` +
Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) +
'- You rebuilt the app after installing the package';
const NativeBlastedImage = NativeModules.BlastedImage
? NativeModules.BlastedImage
: new Proxy(
{},
{
get() {
throw new Error(LINKING_ERROR);
},
}
);
const BlastedImageView = requireNativeComponent('BlastedImageView');
const requestsCache = {};
export const loadImage = (imageUrl, skipMemoryCache = false, hybridAssets = false, cloudUrl = null, retries = 3) => {
if (typeof retries !== 'number' || retries <= 0) {
retries = 1;
}
if (hybridAssets && cloudUrl === null) {
console.error("When using hybridAssets, you must specify a cloudUrl prop. This is the base URL where the local assets are hosted.");
hybridAssets = false;
}
const cacheKey = `${imageUrl}::${!!skipMemoryCache}::${!!hybridAssets}::${cloudUrl || ''}`;
if (!requestsCache[cacheKey]) {
requestsCache[cacheKey] = new Promise(async (resolve, reject) => {
let wasRetried = false;
for (let attempt = 1; attempt <= retries; attempt++) {
// sleep for 1 second before retrying if attempt > 1
if (attempt > 1) {
wasRetried = true;
// await new Promise(resolve => setTimeout(resolve, 5000)); Keep for testing purposes
}
try {
await NativeBlastedImage.loadImage(imageUrl, skipMemoryCache, hybridAssets, cloudUrl);
resolve({ wasRetried });
return;
} catch (error) {
console.warn(`[BlastedImage] Attempt ${attempt} failed for ${imageUrl}`);
if (attempt === retries) {
delete requestsCache[cacheKey]; // Clear failed cache entry
reject(error);
}
}
}
});
}
return requestsCache[cacheKey];
};
const BlastedImage = ({
resizeMode = "cover",
isBackground = false,
returnSize = false,
fallbackSource = null,
tintColor = null,
retries = 3,
source,
width,
onLoad,
onError,
height,
style,
children
}) => {
const [error, setError] = useState(false);
const errorRef = useRef({});
const [renderKey, setRenderKey] = useState(null);
const isDoneRef = useRef(false);
if (typeof source === 'object') {
source = {
uri: '',
hybridAssets: false,
cloudUrl: null,
...source
};
if (source.hybridAssets && source.cloudUrl === null) {
console.error("When using hybridAssets, you must specify a cloudUrl prop. This is the base URL where the local assets are hosted.");
source.hybridAssets = false;
}
}
if (!source || (!source.uri && typeof source !== 'number')) {
if (!source) {
console.error("Source not specified for BlastedImage.");
} else {
console.error("Source should be either a URI <BlastedImage source={{ uri: 'https://example.com/image.jpg' }} /> or a local image using <BlastedImage source={ require('https://example.com/image.jpg') } />");
}
return null;
}
useEffect(() => {
if (typeof source === 'number' || (typeof source === 'object' && source.uri && source.uri.startsWith('file://'))) {
return;
}
// Check if this image URI already failed
if (errorRef.current[source.uri]) {
setError(true);
return;
}
if (isDoneRef.current) {
return;
}
fetchImage();
}, [source]);
// Callback for fetching image to not cause re-renders
const fetchImage = useCallback(async () => {
if (!source?.uri) {
console.error("Invalid source URI.");
return;
}
/*
try {
setError(false);
await loadImage(source.uri, false, source.hybridAssets, source.cloudUrl, retries);
onLoad?.();
} catch (err) {
setError(true);
errorRef.current[source.uri] = true;
console.error(`Failed to load image: ${source.uri}`, err);
onError?.(err);
}
*/
loadImage(source.uri, false, source.hybridAssets, source.cloudUrl, retries)
.then(({wasRetried}) => {
// Finally succeeded
isDoneRef.current = true;
if (wasRetried) {
const key = Math.random().toString(36).substring(2, 8);
setRenderKey(key);
}
setError(false);
//onLoad?.();
if (returnSize) {
Image.getSize(source.uri, (width, height) => {
onLoad?.({ width, height });
}, (error) => {
console.warn('[BlastedImage] Failed to get image size:', error);
onLoad?.(null);
});
} else {
onLoad?.();
}
})
.catch((err) => {
isDoneRef.current = true;
setError(true);
errorRef.current[source.uri] = true;
console.error(`Failed to load image: ${source.uri}`, err);
onError?.(err);
});
}, [source, retries]);
// Flatten styles if provided as an array, otherwise use style as-is
const flattenedStyle = Array.isArray(style) ? Object.assign({}, ...style) : style;
const defaultStyle = { overflow: 'hidden', position: 'relative', backgroundColor: style?.borderColor || 'transparent' }; // Use border color as background
const {
width: styleWidth, // Get width from style
height: styleHeight, // Get height from style
...remainingStyle // All other styles excluding above
} = flattenedStyle || {};
// Override width and height if they exist in style
width = width || styleWidth || 100; // First check the direct prop, then style, then default to 100
height = height || styleHeight || 100; // First check the direct prop, then style, then default to 100
const {
borderWidth = 0,
borderTopWidth = borderWidth,
borderBottomWidth = borderWidth,
borderLeftWidth = borderWidth,
borderRightWidth = borderWidth,
} = remainingStyle;
if (typeof width === 'string' && width.includes('%')) {
console.log("[BlastedImage] For maximum performance, BlastedImage does not support width defined as a percentage");
return;
}
if (typeof height === 'string' && height.includes('%')) {
console.log("[BlastedImage] For maximum performance, BlastedImage does not support height defined as a percentage");
return;
}
// Calculate the adjusted width and height
const adjustedWidth = width - (borderLeftWidth + borderRightWidth);
const adjustedHeight = height - (borderTopWidth + borderBottomWidth);
const viewStyle = {
...defaultStyle,
...remainingStyle,
width,
height,
};
const childrenStyle = {
position: 'absolute',
top: 0,
left: 0,
justifyContent:'center',
alignItems:'center',
width: adjustedWidth,
height: adjustedHeight,
};
return (
<View style={!isBackground ? viewStyle : null}>
{isBackground ? (
<View style={viewStyle}>
{renderImageContent(error, source, fallbackSource, tintColor, adjustedHeight, adjustedWidth, resizeMode, renderKey)}
</View>
) : (
renderImageContent(error, source, fallbackSource, tintColor, adjustedHeight, adjustedWidth, resizeMode, renderKey)
)}
{isBackground && <View style={childrenStyle}>{children}</View>}
</View>
);
};
function renderImageContent(error, source, fallbackSource, tintColor, adjustedHeight, adjustedWidth, resizeMode, renderKey) {
if (error) {
if (fallbackSource) { // Error - Fallback specified, use native component
return (
<Image
source={fallbackSource}
style={{ width: adjustedHeight, height: adjustedHeight }}
resizeMode={resizeMode}
tintColor={tintColor}
/>
);
} else { // Error - No fallback, use native component with static asset
return (
<Image
source={require('./assets/image-error.png')}
style={{ width: adjustedHeight, height: adjustedHeight }}
resizeMode={resizeMode}
tintColor={tintColor}
/>
);
}
} else if (typeof source === 'number') { // Success - with local asset (require), no need to use cache
return (
<Image
source={source}
style={{ width: adjustedWidth, height: adjustedHeight }}
resizeMode={resizeMode}
tintColor={tintColor}
/>
);
} else if (typeof source === 'object' && source.uri && source.uri.startsWith('file://')) { // Success - with local asset (file://android_asset), no need to use cache
return (
<Image
source={{ uri: source.uri }}
style={{ width: adjustedWidth, height: adjustedHeight }}
resizeMode={resizeMode}
tintColor={tintColor}
/>
);
} else { // Success - with remote asset (http/https), use native component with full cache support
return renderKey != null ? (
<BlastedImageView
key={renderKey} // Force re-render when image is retried
source={source}
width={adjustedWidth}
height={adjustedHeight}
resizeMode={resizeMode}
tintColor={tintColor}
/>
) : (
<BlastedImageView
source={source}
width={adjustedWidth}
height={adjustedHeight}
resizeMode={resizeMode}
tintColor={tintColor}
/>
);
}
}
// clear memory cache
BlastedImage.clearMemoryCache = () => {
return NativeBlastedImage.clearMemoryCache();
};
// clear disk cache
BlastedImage.clearDiskCache = () => {
return NativeBlastedImage.clearDiskCache();
};
// clear disk and memory cache
BlastedImage.clearAllCaches = () => {
return NativeBlastedImage.clearAllCaches();
};
BlastedImage.preload = (input, retries = 3) => {
return new Promise((resolve) => {
// single object
if (typeof input === 'object' && input !== null && !Array.isArray(input)) {
loadImage(input.uri, input.skipMemoryCache, input.hybridAssets, input.cloudUrl, retries)
.then(() => {
resolve();
})
.catch((err) => {
console.error(`Error preloading single image: ${input.uri}`, err);
resolve(); // Count as handled even if failed to continue processing
});
}
// array
else if (Array.isArray(input)) {
let loadedCount = 0;
if (input.length === 0) {
resolve();
return;
}
input.forEach(image => {
loadImage(image.uri, image.skipMemoryCache, image.hybridAssets, image.cloudUrl, retries)
.then(() => {
loadedCount++;
if (loadedCount === input.length) {
resolve();
}
})
.catch((err) => {
console.error(`Error preloading one of the array images: ${image.uri}`, err);
loadedCount++; // Count as handled even if failed to continue processing
if (loadedCount === input.length) {
resolve();
}
});
});
}
});
};
export default BlastedImage;