1import { imageManifests } from "../image-manifest";
2
3export interface ImageProps {
4 size?: number;
5 class?: string;
6 id?: string;
7 [key: string]: unknown;
8}
9
10export function Image(
11 imageKey: keyof typeof imageManifests,
12 props?: ImageProps,
13): string {
14 const { size, class: className, id, ...additionalAttributes } = props || {};
15 const imageManifest = imageManifests[imageKey];
16
17 if (!imageManifest) {
18 console.warn(`image manifest not found for key: ${imageKey}`);
19 return ""; // todo: add placeholder image
20 }
21
22 type Size = (typeof imageManifests)[typeof imageKey]["sizes"][number];
23 let bestSize: Size = imageManifest.sizes[0];
24 if (size) {
25 bestSize = imageManifest.sizes.reduce((prev: Size, curr: Size) => {
26 return Math.abs(curr.width - size) < Math.abs(prev.width - size)
27 ? curr
28 : prev;
29 });
30 }
31
32 const attributes: { [key: string]: string } = {
33 src: bestSize.path,
34 alt: imageManifest.altText,
35 };
36
37 if (className) attributes.class = className as string;
38 if (id) attributes.id = id as string;
39
40 for (const key in additionalAttributes) {
41 if (key !== "children" && additionalAttributes[key] != null) {
42 attributes[key] = String(additionalAttributes[key]);
43 }
44 }
45
46 const attributesString = Object.entries(attributes)
47 .map(([key, value]) => `${key}="${value}"`)
48 .join(" ");
49 return `<img ${attributesString} />`;
50}