Skip to content

🎥 Make videos programmatically with React

get rid of postcss

Jonny Burgerfb953fde00ea
diff --git a/packages/google-fonts/scripts/extract-info-from-css.ts b/packages/google-fonts/scripts/extract-info-from-css.ts
new file mode 100644
index 0000000000..f9587c54bd
--- /dev/null
+++ b/packages/google-fonts/scripts/extract-info-from-css.ts
@@ -0,0 +1,101 @@
+import { unquote } from "./utils";
+
+const getValue = (line: string) => {
+ const name = line.match(/\:(.*)\;/)?.[1].trim();
+ return unquote(name as string);
+};
+
+const getUrl = (line: string) => {
+ const name = line.match(/url\((.*?)\)/)?.[1].trim();
+ return name;
+};
+
+const parseFontFace = (block: string) => {
+ const lines = block.split("\n");
+
+ const subset = (lines.find((line) => line.trim().startsWith("/*")) as string)
+ .match(/\/\*(.*)\*\//)![1]
+ .trim();
+ const fontFamily = getValue(
+ lines.find((line) => line.trim().startsWith("font-family")) as string
+ );
+ const src = getUrl(
+ lines.find((line) => line.trim().startsWith("src")) as string
+ );
+ const unicodeRange = getValue(
+ lines.find((line) => line.trim().startsWith("unicode-range")) as string
+ );
+ const weight = getValue(
+ lines.find((line) => line.trim().startsWith("font-weight")) as string
+ );
+ const style = getValue(
+ lines.find((line) => line.trim().startsWith("font-style")) as string
+ );
+
+ if (!weight) throw Error("no weight");
+ if (!subset) throw Error("no subset");
+ if (!unicodeRange) throw Error("no unicodeRange");
+ if (!src) throw Error("no src");
+
+ return { fontFamily, src, unicodeRange, weight, style, subset };
+};
+
+export type FontInfo = {
+ fontFamily: string;
+ importName: string;
+ version: string;
+ url: string;
+ unicodeRanges: Record<string, string>;
+ fonts: Record<string, Record<string, Record<string, string>>>;
+};
+
+export const extractInfoFromCss = ({
+ contents,
+ fontFamily,
+ importName,
+ url,
+ version,
+}: {
+ contents: string;
+ fontFamily: string;
+ importName: string;
+ url: string;
+ version: string;
+}): FontInfo => {
+ let remainingContents = contents;
+
+ let unicodeRanges: Record<string, string> = {};
+ let fonts: Record<string, Record<string, Record<string, string>>> = {};
+
+ while (remainingContents.match(/\/\*(.*)/)) {
+ const startIndex = remainingContents.indexOf("/*");
+ const endIndex = remainingContents.substring(startIndex + 2).indexOf("/*");
+ const extractedContents = remainingContents.substring(
+ startIndex,
+ endIndex === -1 ? Infinity : endIndex + 2
+ );
+ remainingContents = remainingContents.substring(endIndex + 2);
+ const { subset, unicodeRange, style, src, weight } =
+ parseFontFace(extractedContents);
+
+ unicodeRanges[subset] = unicodeRange;
+ fonts[style] ??= {};
+ fonts[style][weight] ??= {};
+ fonts[style][weight][subset] = src;
+
+ if (endIndex === -1) {
+ break;
+ }
+ }
+
+ // Prepare info data
+ const info: FontInfo = {
+ fontFamily,
+ importName,
+ version,
+ url,
+ unicodeRanges,
+ fonts,
+ };
+ return info;
+};
diff --git a/packages/google-fonts/scripts/generate.ts b/packages/google-fonts/scripts/generate.ts
index 37f5a168a2..49bee5edfb 100644
--- a/packages/google-fonts/scripts/generate.ts
+++ b/packages/google-fonts/scripts/generate.ts
@@ -1,15 +1,5 @@
import fs, { mkdirSync } from "node:fs";
import path from "path";
-import postcss from "postcss";
-
-type FontInfo = {
- fontFamily: string;
- importName: string;
- version: string;
- url: string;
- unicodeRanges: Record<string, string>;
- fonts: Record<string, Record<string, Record<string, string>>>;
-};
import {
getCssLink,
@@ -20,6 +10,7 @@ import {
} from "./utils";
import { Font } from "./google-fonts";
import { filteredFonts } from "./filtered-fonts";
+import { FontInfo, extractInfoFromCss } from "./extract-info-from-css";
const OUTDIR = "./src";
const CSS_CACHE_DIR = "./.cache-css";
@@ -36,7 +27,6 @@ const generate = async (font: Font) => {
font.version
}.css`;
-
// Get css link
const url = getCssLink(font);
@@ -54,9 +44,9 @@ const generate = async (font: Font) => {
});
// Save to cache
- const body = await res.text()
+ const body = await res.text();
await fs.promises.writeFile(cssFile, body);
- console.log("Generated", cssFile)
+ console.log("Generated", cssFile);
css = body;
} else {
@@ -64,86 +54,18 @@ const generate = async (font: Font) => {
css = await fs.promises.readFile(cssFile, "utf-8");
}
-
-
if (!css) {
throw new Error("no css");
}
- // Parse CSS
- let ast = postcss.parse(css);
- let unicodeRanges: Record<string, string> = {};
- let fonts: Record<string, Record<string, Record<string, string>>> = {};
- for (const node of ast.nodes) {
- // Only process @font-face
- if (node.type !== "atrule" || node.name !== "font-face") continue;
-
- // Check subset info before @font-face block
- let prev = node.prev();
- if (!prev || prev.type != "comment") continue;
-
- let style: null | string = null;
- let weight: null | string = null;
- let src: null | string = null;
- let unicodeRange: null | string = null;
- let subset: null | string = prev.text;
-
- // Parse fontFamily
- node.walkDecls("font-fontFamily", (decl, _) => {
- if (font.family != unquote(decl.value)) {
- throw new Error(
- `Font fontFamily value mismatch: ${font.family} with ${unquote(
- decl.value
- )}`
- );
- }
-
- fontFamily = decl.value;
- });
-
- // Parse style
- node.walkDecls("font-style", (decl, _) => {
- style = decl.value;
- });
-
- // Parse weight
- node.walkDecls("font-weight", (decl, _) => {
- weight = decl.value;
- });
-
- // Parse url to font file
- node.walkDecls("src", (decl, _) => {
- src = decl.value.match(/url\((.+?)\)/)?.[1] as string;
- });
-
- // Parse unicode-range
- node.walkDecls("unicode-range", (decl, _) => {
- unicodeRange = decl.value;
- });
-
- if (!style) throw Error("no style");
- if (!weight) throw Error("no weight");
- if (!subset) throw Error("no subset");
- if (!unicodeRange) throw Error("no unicodeRange" + font.family);
- if (!src) throw Error("no src");
-
- // Set unicode range data
- unicodeRanges[subset] = unicodeRange;
-
- // Set font url
- fonts[style] ??= {};
- fonts[style][weight] ??= {};
- fonts[style][weight][subset] = src;
- }
// Prepare info data
- const info: FontInfo = {
- fontFamily,
- importName,
+ const info: FontInfo = extractInfoFromCss({
+ contents: css,
+ fontFamily: fontFamily,
+ importName: importName,
+ url: url,
version: font.version,
- url,
- unicodeRanges,
- fonts,
- };
+ });
let output = `import { loadFonts } from "./base";
@@ -153,7 +75,7 @@ export const fontFamily = "${fontFamily}" as const;
type Variants = {\n`;
- for (const [style, val] of Object.entries(fonts)) {
+ for (const [style, val] of Object.entries(info.fonts)) {
output += ` ${style}: {\n`;
output += ` weights: ${Object.keys(val).map(quote).join(" | ")},\n`;
output += ` subsets: ${font.subsets.map(quote).join(" | ")},\n`;
@@ -178,7 +100,7 @@ export const loadFont = <T extends keyof Variants>(
mkdirSync(OUTDIR, { recursive: true });
// Save
await fs.promises.writeFile(tsFile, output);
- console.log('Wrote', tsFile)
+ console.log("Wrote", tsFile);
};
const run = async () => {
diff --git a/packages/google-fonts/scripts/utils.ts b/packages/google-fonts/scripts/utils.ts
index 30d65a2757..cea134ac6b 100644
--- a/packages/google-fonts/scripts/utils.ts
+++ b/packages/google-fonts/scripts/utils.ts
@@ -1,4 +1,4 @@
-import { Font } from "./google-fonts";
+import type { Font } from "./google-fonts";
export const unquote = (str: string) =>
str.replace(/^['"]/g, "").replace(/['"]$/g, "");
diff --git a/packages/google-fonts/test/generate-info.test.ts b/packages/google-fonts/test/generate-info.test.ts
new file mode 100644
index 0000000000..82a23c37c5
--- /dev/null
+++ b/packages/google-fonts/test/generate-info.test.ts
@@ -0,0 +1,77 @@
+import { test, expect } from "bun:test";
+import { extractInfoFromCss } from "../scripts/extract-info-from-css";
+
+const testFile = `
+/* latin-ext */
+@font-face {
+ font-family: 'ABeeZee';
+ font-style: italic;
+ font-weight: 400;
+ src: url(https://fonts.gstatic.com/s/abeezee/v22/esDT31xSG-6AGleN2tCUnJ8DKpE.woff2) format('woff2');
+ unicode-range: U+0100-02AF, U+0304, U+0308, U+0329, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
+}
+/* latin */
+@font-face {
+ font-family: 'ABeeZee';
+ font-style: italic;
+ font-weight: 400;
+ src: url(https://fonts.gstatic.com/s/abeezee/v22/esDT31xSG-6AGleN2tCUkp8D.woff2) format('woff2');
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
+}
+/* latin-ext */
+@font-face {
+ font-family: 'ABeeZee';
+ font-style: normal;
+ font-weight: 400;
+ src: url(https://fonts.gstatic.com/s/abeezee/v22/esDR31xSG-6AGleN2tukkIcH.woff2) format('woff2');
+ unicode-range: U+0100-02AF, U+0304, U+0308, U+0329, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
+}
+/* latin */
+@font-face {
+ font-family: 'ABeeZee';
+ font-style: normal;
+ font-weight: 400;
+ src: url(https://fonts.gstatic.com/s/abeezee/v22/esDR31xSG-6AGleN2tWkkA.woff2) format('woff2');
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
+}
+`;
+
+test("Should extract correctly", () => {
+ const data = extractInfoFromCss({
+ contents: testFile,
+ fontFamily: "ABeeZee",
+ importName: "ABeeZee",
+ url: "https://fonts.googleapis.com/css2?family=ABeeZee:ital,wght@0,400;1,400",
+ version: "v22",
+ });
+ expect(data).toEqual({
+ fontFamily: "ABeeZee",
+ importName: "ABeeZee",
+ version: "v22",
+ url: "https://fonts.googleapis.com/css2?family=ABeeZee:ital,wght@0,400;1,400",
+ unicodeRanges: {
+ "latin-ext":
+ "U+0100-02AF, U+0304, U+0308, U+0329, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF",
+ latin:
+ "U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD",
+ },
+ fonts: {
+ italic: {
+ "400": {
+ "latin-ext":
+ "https://fonts.gstatic.com/s/abeezee/v22/esDT31xSG-6AGleN2tCUnJ8DKpE.woff2",
+ latin:
+ "https://fonts.gstatic.com/s/abeezee/v22/esDT31xSG-6AGleN2tCUkp8D.woff2",
+ },
+ },
+ normal: {
+ "400": {
+ "latin-ext":
+ "https://fonts.gstatic.com/s/abeezee/v22/esDR31xSG-6AGleN2tukkIcH.woff2",
+ latin:
+ "https://fonts.gstatic.com/s/abeezee/v22/esDR31xSG-6AGleN2tWkkA.woff2",
+ },
+ },
+ },
+ });
+});