forked from frappe/builder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimageUtils.ts
More file actions
61 lines (51 loc) · 1.56 KB
/
imageUtils.ts
File metadata and controls
61 lines (51 loc) · 1.56 KB
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
import { createResource } from "frappe-ui";
import { toast } from "vue-sonner";
export interface ImageOptimizationOptions {
imageUrl: string;
onSuccess: (newUrl: string) => void;
}
export const isExternalImage = (imageUrl: string): boolean => {
return imageUrl.startsWith("http://") || imageUrl.startsWith("https://");
};
export const isConvertibleToWebP = (imageUrl: string): boolean => {
return [".jpg", ".jpeg", ".png"].some((ext) => imageUrl.toLowerCase().endsWith(ext));
};
export const shouldShowOptimizeButton = (imageUrl: string | null): boolean => {
if (!imageUrl) {
return false;
}
return isExternalImage(imageUrl) || isConvertibleToWebP(imageUrl);
};
export const getOptimizeButtonText = (imageUrl: string | null): string => {
if (!imageUrl) {
return "";
}
if (isExternalImage(imageUrl)) {
return "Serve Locally";
} else if (isConvertibleToWebP(imageUrl)) {
return "Convert to WebP";
}
return "";
};
export const optimizeImage = ({ imageUrl, onSuccess }: ImageOptimizationOptions) => {
if (!imageUrl) {
return;
}
const convertToWebP = createResource({
url: "/api/method/builder.api.convert_to_webp",
params: {
image_url: imageUrl,
},
});
const isExternal = isExternalImage(imageUrl);
return toast.promise(
convertToWebP.fetch().then((res: string) => {
onSuccess(res);
}),
{
loading: isExternal ? "Pulling..." : "Converting...",
success: () => (isExternal ? "Image pulled to local" : "Image converted to WebP"),
error: () => (isExternal ? "Failed to pull image to local" : "Failed to convert image to WebP"),
},
);
};