Skip to content

Commit ed0e45b

Browse files
committed
WIP: refactor: add image mimeType cache
1 parent 615e37a commit ed0e45b

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

src/main/resources/META-INF/resources/frontend/src/image-crop.tsx

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ import { type Crop, ReactCrop, PixelCrop, PercentCrop, makeAspectCrop, centerCro
2525

2626
class ImageCropElement extends ReactAdapterElement {
2727

28+
// Cache detected MIME per source URL to avoid repeated network calls
29+
#mimeTypeCache = new Map<string, string | null>();
30+
2831
protected render(hooks: RenderHooks): ReactElement<any, string | JSXElementConstructor<any>> | null {
2932

3033
const [crop, setCrop] = hooks.useState<Crop>("crop");
@@ -180,29 +183,43 @@ class ImageCropElement extends ReactAdapterElement {
180183
return null;
181184
}
182185

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+
183193
// Case 1: data URL (e.g., data:image/png;base64,...)
184194
if (img.src.startsWith("data:")) {
185195
const semiIndex = img.src.indexOf(";");
186196
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;
188200
}
201+
this.#mimeTypeCache?.set(cacheKey, null);
189202
return null;
190203
}
191204

192205
try {
193206
// Case 2: try a HEAD request (fast, no body)
194207
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;
198212
}
199213

200214
// Case 3: fallback — fetch full blob
201215
const blobRes = await fetch(img.src);
202216
const blob = await blobRes.blob();
203-
return blob.type || null;
217+
mimeType = blob.type || null;
218+
this.#mimeTypeCache?.set(cacheKey, mimeType);
219+
return mimeType;
204220
} catch (err) {
205221
console.error("Error fetching image MIME type:", err);
222+
this.#mimeTypeCache?.set(cacheKey, null);
206223
return null;
207224
}
208225
}

0 commit comments

Comments
 (0)