Created
January 28, 2022 02:16
-
-
Save FredKSchott/3d656427d53a3609ae337c60cc6e3002 to your computer and use it in GitHub Desktop.
A font component for Astro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
import {writeFile} from 'node:fs/promises'; | |
export interface Props { | |
font: string; | |
weight?: string[]; | |
} | |
const {font, weight} = Astro.props as Props; | |
let familyValue = font; | |
if (weight) { | |
familyValue += ':wght@' + weight.join(';'); | |
} | |
// can we literallhy download the font files here! | |
const response = await fetch(`https://google-webfonts-helper.herokuapp.com/api/fonts/${font.toLowerCase()}?subsets=latin,latin-ext`); | |
const data = await response.json(); | |
console.log(data); | |
let num = 0; | |
const fontFamilies = []; | |
for (const variant of data.variants) { | |
console.log(variant.woff2, variant.fontWeight); | |
fontFamilies.push(`@font-face { | |
font-family: '${font}'; | |
font-style: ${variant.fontStyle}; | |
font-weight: ${variant.fontWeight}; | |
src: local(''), | |
url('${variant.woff2}') format('woff2'); /* Chrome 26+, Opera 23+, Firefox 39+ */ | |
}`) | |
// TODO: | |
// Load the font file using fetch() | |
// write it to public/ | |
// create the absolute URL to public | |
} | |
console.log(fontFamilies); | |
--- | |
<!-- WARNING: Hack! --> | |
{`<style> | |
${fontFamilies.join('\n')} | |
</style>`} | |
{`<style> body {font-family: '${font}', cursive;} </style>`} | |
<!-- | |
The fully remote approach: | |
<link rel="preconnect" href="https://fonts.googleapis.com"> | |
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
<link href={`https://fonts.googleapis.com/css2?family=${familyValue}&display=swap`} rel="stylesheet"> | |
The local approach: | |
{`<style> | |
/* comforter-regular - latin *//* comforter-regular - latin */ | |
@font-face { | |
font-family: '${font}'; | |
font-style: normal; | |
font-weight: 400; | |
src: local(''), | |
url('/fonts/${font}-v3-latin-regular.woff2') format('woff2'); /* Chrome 26+, Opera 23+, Firefox 39+ */ | |
} | |
body { | |
font-family: '${font}', cursive; | |
} | |
</style>`} --> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment