| 17 | const remote_base = "https://cdn.jsdelivr.net/gh/JacobLinCool/nano-font@json/"; |
| 18 | |
| 19 | export async function FontExtension(generator: Generator): Promise<Extension> { |
| 20 | const config = generator.config; |
| 21 | let names: string[] = []; |
| 22 | if (Array.isArray(config.fonts)) { |
| 23 | names = config.fonts.filter((font) => !supported[font.toLowerCase()]); |
| 24 | } else if (typeof config.font === "string" && !supported[config.font.toLowerCase()]) { |
| 25 | names = [config.font]; |
| 26 | } |
| 27 | |
| 28 | await Promise.all( |
| 29 | names.map(async (name) => { |
| 30 | try { |
| 31 | const url = `${remote_base}${name.replace(/\s+/g, "_")}.json`; |
| 32 | const cached = await generator.cache?.match(url); |
| 33 | if (cached) { |
| 34 | supported[name.toLowerCase()] = await cached.json(); |
| 35 | generator.log(`Loaded cached font ${name}`); |
| 36 | } else { |
| 37 | const res = await fetch(url); |
| 38 | if (res.ok) { |
| 39 | const data = (await res.clone().json()) as { name: string; base64: string }; |
| 40 | supported[name.toLowerCase()] = { name, base64: data.base64 }; |
| 41 | generator.log(`loaded remote font "${name}"`); |
| 42 | generator.cache?.put(url, res); |
| 43 | } else { |
| 44 | return; |
| 45 | } |
| 46 | } |
| 47 | } catch { |
| 48 | // do nothing |
| 49 | } |
| 50 | }), |
| 51 | ); |
| 52 | |
| 53 | return async function Font(generator, data, body, styles) { |
| 54 | if (Array.isArray(config.fonts)) { |
| 55 | const list = config.fonts.map((font: string) => { |
| 56 | if (supported[font.toLowerCase()]) { |
| 57 | return supported[font.toLowerCase()]; |
| 58 | } else { |
| 59 | return { name: font }; |
| 60 | } |
| 61 | }); |
| 62 | styles.push(css(list)); |
| 63 | } else if (typeof config.font === "string") { |
| 64 | const font = supported[config.font.toLowerCase()]; |
| 65 | |
| 66 | if (font) { |
| 67 | styles.push(css([font])); |
| 68 | } else { |
| 69 | styles.push(css([{ name: config.font }])); |
| 70 | } |
| 71 | } |
| 72 | }; |
| 73 | } |
| 74 | |
| 75 | function css(fonts: { name: string; base64?: string | null }[]): string { |
| 76 | let css = ""; |