-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
99 lines (81 loc) · 2.76 KB
/
index.ts
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { getPlaiceholder } from 'plaiceholder';
import { Node as UnistNode } from 'unist-util-visit/lib';
import { visit } from 'unist-util-visit';
type Node = UnistNode & { value: any; children?: Node[] };
type RehypeNode = Node & {
tagName?: string;
properties: Record<string, any>;
};
const DefaultOptions = {
srcAsAlt: true,
blurDataURLPropertyName: 'blurDataURL',
placeholderPropertyName: 'placeholder',
srcTransform: (src: string) => src,
} as const;
export type RehypeImageProcessOption = Partial<typeof DefaultOptions>;
// TODO: support possible images in mdxElement
function isImageNode(node: RehypeNode) {
const img = node;
return (
img.type === 'element' &&
img.tagName === 'img' &&
img.properties &&
typeof img.properties.src === 'string'
);
}
function rehypeImageProcess(options: RehypeImageProcessOption) {
options = Object.assign({}, DefaultOptions, options);
// Returns the props of given `src` to use for blurred images
async function returnProps(src: string) {
const { base64: blurDataURL, img } = await getPlaiceholder(src);
const { width, height } = img;
return {
...img,
width,
height,
blurDataURL,
};
}
async function addProps(node: RehypeNode, options: RehypeImageProcessOption) {
const transformedSrc: string = options.srcTransform?.(node.properties.src) || node.properties.src;
try {
if (!node.properties) {
node.properties = {};
return;
}
// return the new props we'll need for our image
const { width, height, blurDataURL } = await returnProps(transformedSrc);
// add the props in the properties object of the node
// the properties object later gets transformed as props
node.properties.width = width;
node.properties.height = height;
node.properties.src = transformedSrc;
node.properties.sizes = `(max-width: ${width}px) 100vw, ${height}px`;
if (options.srcAsAlt) {
node.properties.alt ||= transformedSrc;
}
node.properties[options.blurDataURLPropertyName || 'blurDataURL'] = blurDataURL;
node.properties[options.placeholderPropertyName || 'placeholder'] = 'blur';
} catch (e) {
// @ts-ignore
throw Error(`Invalid image with src: "${transformedSrc}"`, {
cause: e,
});
}
}
return async (root: RehypeNode) => {
// Create an array to hold all of the images from the markdown file
const images: RehypeNode[] = [];
visit<any>(root, (node: RehypeNode, i, p) => {
if (isImageNode(node)) {
images.push(node);
}
});
for (const image of images) {
// Loop through all of the images and add their props
await addProps(image, options);
}
return root;
};
}
export default rehypeImageProcess;