forked from xerdnu/react-native-blasted-image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
220 lines (192 loc) · 6.56 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
import React, { useState, useEffect } 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\n' +
'- You are not using Expo Go\n';
const NativeBlastedImage = NativeModules.BlastedImage
? NativeModules.BlastedImage
: new Proxy(
{},
{
get() {
throw new Error(LINKING_ERROR);
},
}
);
export const loadImage = (imageUrl, headers = {}, skipMemoryCache = false) => {
return NativeBlastedImage.loadImage(imageUrl, headers, skipMemoryCache)
.catch((error) => {
console.error("Error loading image:", error);
throw error;
});
};
const BlastedImageView = requireNativeComponent('BlastedImageView');
const BlastedImage = ({ source, width, onLoad, onError, fallbackSource, height, style, resizeMode, isBackground, children }) => {
const [error, setError] = useState(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') {
return;
}
const fetchImage = async () => {
try {
await loadImage(source.uri, source.headers);
onLoad?.();
} catch (err) {
setError(true);
console.error(err);
onError?.(err);
}
};
fetchImage();
}, [source]);
// 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("For maximum performance, BlastedImage does not support width defined as a percentage");
return;
}
if (typeof height === 'string' && height.includes('%')) {
console.log("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, adjustedHeight, adjustedWidth, resizeMode)}
</View>
) : (
renderImageContent(error, source, fallbackSource, adjustedHeight, adjustedWidth, resizeMode)
)}
{isBackground && <View style={childrenStyle}>{children}</View>}
</View>
);
};
function renderImageContent(error, source, fallbackSource, adjustedHeight, adjustedWidth, resizeMode) {
if (error) {
if (fallbackSource) {
return (
<Image
source={fallbackSource}
style={{ width: adjustedHeight, height: adjustedHeight }}
resizeMode={resizeMode}
/>
);
} else {
return null;
}
} else if (typeof source === 'number') {
return (
<Image
source={source}
style={{ width: adjustedWidth, height: adjustedHeight }}
resizeMode={resizeMode}
/>
);
} else {
return (
<BlastedImageView
sourceUri={source.uri}
width={adjustedWidth}
height={adjustedHeight}
resizeMode={resizeMode}
/>
);
}
}
BlastedImage.defaultProps = {
resizeMode: "cover",
isBackground: false
};
// 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) => {
return new Promise((resolve) => {
// single object
if (typeof input === 'object' && input !== null && !Array.isArray(input)) {
loadImage(input.uri, input.headers, input.skipMemoryCache)
.then(() => {
resolve();
})
.catch((err) => {
console.error("Error preloading single image:", err);
resolve(); // Count as handled even if failed to continue processing
});
}
// array
else if (Array.isArray(input)) {
let loadedCount = 0;
input.forEach(image => {
loadImage(image.uri, image.headers, image.skipMemoryCache)
.then(() => {
loadedCount++;
if (loadedCount === input.length) {
resolve();
}
})
.catch((err) => {
console.error("Error preloading one of the array images:", err);
loadedCount++; // Count as handled even if failed to continue processing
if (loadedCount === input.length) {
resolve();
}
});
});
}
});
};
export default BlastedImage;