-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathImageWithAlt.astro
More file actions
74 lines (65 loc) · 1.97 KB
/
ImageWithAlt.astro
File metadata and controls
74 lines (65 loc) · 1.97 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
62
63
64
65
66
67
68
69
70
71
72
73
74
---
import { Image } from "astro:assets";
import { getImage } from "astro:assets";
import path from "node:path";
type ImageProps = Parameters<typeof Image>[0];
type Props = ImageProps & {
alt?: ImageProps["alt"];
};
// TODO: this causes all the assets to be moved to the assets folder, see
// if we can avoid it.
const imageModules = import.meta.glob("/src/assets/*.{png,jpg,jpeg,webp}", {
eager: true,
import: "default",
});
const altTextModules = import.meta.glob("/src/assets/*.alt.txt", {
query: "?raw",
import: "default",
eager: true,
});
const getAltTextPathForImage = (imagePath: string) => {
const parsedPath = path.parse(imagePath);
return path.join(parsedPath.dir, parsedPath.name + ".alt.txt");
};
const getPathToAltTextMap = (
imageModules: {
[originalPath: string]: {
src: string; // Compiled path
};
},
altTextModules: {
[originalPath: string]: string;
},
) => {
const pathToAltTextMap = new Map<string, string>();
for (const [originalPath, module] of Object.entries(imageModules)) {
const finalPath = module.src;
const altTextPath = getAltTextPathForImage(originalPath);
if (altTextModules[altTextPath]) {
pathToAltTextMap.set(finalPath, altTextModules[altTextPath]);
}
}
return pathToAltTextMap;
};
const getFinalSrc = async (image: typeof Astro.props.src) => {
const imageOptions = await getImage({
src: Astro.props.src,
});
// Loads the final src of this image no matter what the image passed in looks like
return typeof imageOptions.rawOptions.src == "string"
? imageOptions.rawOptions.src
: imageOptions.rawOptions.src.src;
};
const finalPathToAltTextMap = getPathToAltTextMap(
imageModules as any,
altTextModules as any,
);
const alt =
Astro.props.alt === "file://"
? finalPathToAltTextMap.get(await getFinalSrc(Astro.props.src))
: Astro.props.alt;
if (!alt) {
console.error("You need an alt text for your image");
}
---
<Image {...Astro.props} alt={alt ?? "Shame on you"} />