-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanaged-image.tsx
More file actions
61 lines (52 loc) · 1.38 KB
/
managed-image.tsx
File metadata and controls
61 lines (52 loc) · 1.38 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 Image, { type ImageProps } from "next/image";
import { normalizeLocalUploadUrl } from "@/lib/local-upload";
type ManagedImageProps = Omit<ImageProps, "alt"> & { alt: string };
function getImageSrc(src: ManagedImageProps["src"]) {
if (typeof src === "string") {
return src;
}
if ("src" in src && typeof src.src === "string") {
return src.src;
}
if ("default" in src && typeof src.default?.src === "string") {
return src.default.src;
}
return "";
}
function shouldBypassOptimization(src: string) {
return (
src.startsWith("/api/uploads/") ||
src.startsWith("/uploads/") ||
src.startsWith("data:") ||
src.startsWith("blob:") ||
src.endsWith(".svg") ||
src.includes(".svg?")
);
}
function isRenderableSrc(src: string) {
return (
src.startsWith("/") ||
src.startsWith("http://") ||
src.startsWith("https://") ||
src.startsWith("data:") ||
src.startsWith("blob:")
);
}
export function ManagedImage({ alt, ...props }: ManagedImageProps) {
const normalizedSrc =
typeof props.src === "string"
? normalizeLocalUploadUrl(props.src)
: props.src;
const src = getImageSrc(normalizedSrc);
if (!src || !isRenderableSrc(src)) {
return null;
}
return (
<Image
{...props}
src={normalizedSrc}
alt={alt}
unoptimized={props.unoptimized || shouldBypassOptimization(src)}
/>
);
}