-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathloadGoogleFont.ts
More file actions
77 lines (65 loc) · 1.77 KB
/
loadGoogleFont.ts
File metadata and controls
77 lines (65 loc) · 1.77 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
75
76
77
import type { FontStyle, FontWeight } from "satori";
export type FontOptions = {
name: string;
data: ArrayBuffer;
weight: FontWeight | undefined;
style: FontStyle | undefined;
};
async function loadGoogleFont(
font: string,
text: string
): Promise<ArrayBuffer> {
const API = `https://fonts.googleapis.com/css2?family=${font}&text=${encodeURIComponent(text)}`;
const css = await (
await fetch(API, {
headers: {
"User-Agent":
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1",
},
})
).text();
const resource = css.match(
/src: url\((.+)\) format\('(opentype|truetype)'\)/
);
if (!resource) throw new Error("Failed to download dynamic font");
const res = await fetch(resource[1]);
if (!res.ok) {
throw new Error("Failed to download dynamic font. Status: " + res.status);
}
const fonts: ArrayBuffer = await res.arrayBuffer();
return fonts;
}
async function loadGoogleFonts(
text: string
): Promise<
Array<{ name: string; data: ArrayBuffer; weight: number; style: string }>
> {
const fontsConfig = [
{
name: "Space Mono",
font: "Space+Mono",
weight: 400,
style: "normal",
},
// {
// name: "IBM Plex Mono",
// font: "IBM+Plex+Mono",
// weight: 400,
// style: "normal",
// },
// {
// name: "IBM Plex Mono",
// font: "IBM+Plex+Mono:wght@700",
// weight: 700,
// style: "bold",
// },
];
const fonts = await Promise.all(
fontsConfig.map(async ({ name, font, weight, style }) => {
const data = await loadGoogleFont(font, text);
return { name, data, weight, style };
})
);
return fonts;
}
export default loadGoogleFonts;