@@ -25,6 +25,9 @@ import { type Crop, ReactCrop, PixelCrop, PercentCrop, makeAspectCrop, centerCro
25
25
26
26
class ImageCropElement extends ReactAdapterElement {
27
27
28
+ // Cache detected MIME per source URL to avoid repeated network calls
29
+ #mimeTypeCache = new Map < string , string | null > ( ) ;
30
+
28
31
protected render ( hooks : RenderHooks ) : ReactElement < any , string | JSXElementConstructor < any > > | null {
29
32
30
33
const [ crop , setCrop ] = hooks . useState < Crop > ( "crop" ) ;
@@ -180,29 +183,43 @@ class ImageCropElement extends ReactAdapterElement {
180
183
return null ;
181
184
}
182
185
186
+ // Return cached result if available
187
+ const cacheKey = img . src ;
188
+ const cached = this . #mimeTypeCache?. get ( cacheKey ) ;
189
+ if ( cached !== undefined ) {
190
+ return cached ;
191
+ }
192
+
183
193
// Case 1: data URL (e.g., data:image/png;base64,...)
184
194
if ( img . src . startsWith ( "data:" ) ) {
185
195
const semiIndex = img . src . indexOf ( ";" ) ;
186
196
if ( semiIndex > 5 ) {
187
- return img . src . substring ( 5 , semiIndex ) ;
197
+ const mimeType = img . src . substring ( 5 , semiIndex ) ;
198
+ this . #mimeTypeCache?. set ( cacheKey , mimeType ) ;
199
+ return mimeType ;
188
200
}
201
+ this . #mimeTypeCache?. set ( cacheKey , null ) ;
189
202
return null ;
190
203
}
191
204
192
205
try {
193
206
// Case 2: try a HEAD request (fast, no body)
194
207
const headRes = await fetch ( img . src , { method : "HEAD" } ) ;
195
- const mime = headRes . headers . get ( "Content-Type" ) ;
196
- if ( mime ) {
197
- return mime ;
208
+ let mimeType = headRes . headers . get ( "Content-Type" ) ;
209
+ if ( mimeType ) {
210
+ this . #mimeTypeCache?. set ( cacheKey , mimeType ) ;
211
+ return mimeType ;
198
212
}
199
213
200
214
// Case 3: fallback — fetch full blob
201
215
const blobRes = await fetch ( img . src ) ;
202
216
const blob = await blobRes . blob ( ) ;
203
- return blob . type || null ;
217
+ mimeType = blob . type || null ;
218
+ this . #mimeTypeCache?. set ( cacheKey , mimeType ) ;
219
+ return mimeType ;
204
220
} catch ( err ) {
205
221
console . error ( "Error fetching image MIME type:" , err ) ;
222
+ this . #mimeTypeCache?. set ( cacheKey , null ) ;
206
223
return null ;
207
224
}
208
225
}
0 commit comments