Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

Support for variable fonts (#1007)

Oleg Isonen525e6e384db0
diff --git a/apps/designer/app/designer/features/style-panel/controls/font-weight/font-weight-control.tsx b/apps/designer/app/designer/features/style-panel/controls/font-weight/font-weight-control.tsx
index 1f9c3e05b8..edc4416f5a 100644
--- a/apps/designer/app/designer/features/style-panel/controls/font-weight/font-weight-control.tsx
+++ b/apps/designer/app/designer/features/style-panel/controls/font-weight/font-weight-control.tsx
@@ -5,6 +5,7 @@ import { useMemo } from "react";
import { useAssets } from "~/designer/shared/assets";
import type { ControlProps } from "../../style-sections";
import { theme } from "@webstudio-is/design-system";
+import { isSupportedFontWeight } from "./is-supported-font-weight";
type FontWeightItem = {
label: string;
@@ -28,17 +29,16 @@ const useAvailableFontWeights = (
return useMemo(() => {
const found = allFontWeights.filter((option) => {
return assetContainers.find((assetContainer) => {
- if (assetContainer.status !== "uploaded") {
+ if (
+ assetContainer.status !== "uploaded" ||
+ assetContainer.asset.type !== "font"
+ ) {
return false;
}
-
- const { asset } = assetContainer;
-
- return (
- "meta" in asset &&
- "family" in asset.meta &&
- asset.meta.family === currentFamily &&
- String(asset.meta.weight) === option.weight
+ return isSupportedFontWeight(
+ assetContainer.asset,
+ option.weight,
+ currentFamily
);
});
});
diff --git a/apps/designer/app/designer/features/style-panel/controls/font-weight/is-supported-font-weight.test.ts b/apps/designer/app/designer/features/style-panel/controls/font-weight/is-supported-font-weight.test.ts
new file mode 100644
index 0000000000..525c6c4fed
--- /dev/null
+++ b/apps/designer/app/designer/features/style-panel/controls/font-weight/is-supported-font-weight.test.ts
@@ -0,0 +1,47 @@
+import { describe, test } from "@jest/globals";
+import { FontAsset } from "@webstudio-is/asset-uploader";
+import { isSupportedFontWeight } from "./is-supported-font-weight";
+
+const createServerAsset = (meta: FontAsset["meta"]): FontAsset => ({
+ id: "111",
+ type: "font",
+ name: "test",
+ location: "FS",
+ projectId: "id",
+ size: 2135,
+ format: "ttf",
+ createdAt: "",
+ description: "",
+ meta,
+ path: "",
+});
+
+describe("isSupportedFontWeight", () => {
+ test("static", () => {
+ const meta = {
+ family: "Acumin Pro",
+ style: "italic",
+ weight: 900,
+ } as const;
+ const asset = createServerAsset(meta);
+ expect(isSupportedFontWeight(asset, "400", "Roboto")).toBe(false);
+ expect(isSupportedFontWeight(asset, "400", "Acumin Pro")).toBe(false);
+ expect(isSupportedFontWeight(asset, "900", "Roboto")).toBe(false);
+ expect(isSupportedFontWeight(asset, "900", "Acumin Pro")).toBe(true);
+ });
+
+ test("variable", () => {
+ const meta = {
+ family: "Roboto Flex",
+ variationAxes: {
+ wght: { name: "wght", min: 100, default: 400, max: 1000 },
+ },
+ } as const;
+ const asset = createServerAsset(meta);
+ expect(isSupportedFontWeight(asset, "1", meta.family)).toBe(false);
+ expect(isSupportedFontWeight(asset, "100", meta.family)).toBe(true);
+ expect(isSupportedFontWeight(asset, "500", meta.family)).toBe(true);
+ expect(isSupportedFontWeight(asset, "1000", meta.family)).toBe(true);
+ expect(isSupportedFontWeight(asset, "1001", meta.family)).toBe(false);
+ });
+});
diff --git a/apps/designer/app/designer/features/style-panel/controls/font-weight/is-supported-font-weight.ts b/apps/designer/app/designer/features/style-panel/controls/font-weight/is-supported-font-weight.ts
new file mode 100644
index 0000000000..29e610e297
--- /dev/null
+++ b/apps/designer/app/designer/features/style-panel/controls/font-weight/is-supported-font-weight.ts
@@ -0,0 +1,25 @@
+import type { FontAsset } from "@webstudio-is/asset-uploader";
+
+export const isSupportedFontWeight = (
+ asset: FontAsset,
+ weight: string,
+ currentFamily: string
+) => {
+ if (asset?.meta?.family !== currentFamily) {
+ return false;
+ }
+
+ const { meta } = asset;
+ const weightNumber = Number(weight);
+
+ if ("variationAxes" in meta) {
+ const { variationAxes } = meta;
+ return (
+ variationAxes.wght !== undefined &&
+ variationAxes.wght.min <= weightNumber &&
+ variationAxes.wght.max >= weightNumber
+ );
+ }
+
+ return meta.weight === weightNumber;
+};
diff --git a/packages/css-engine/src/core/rules.ts b/packages/css-engine/src/core/rules.ts
index 06a0cb2835..05ee39c477 100644
--- a/packages/css-engine/src/core/rules.ts
+++ b/packages/css-engine/src/core/rules.ts
@@ -130,8 +130,8 @@ export class PlaintextRule {
export type FontFaceOptions = {
fontFamily: string;
- fontStyle: "normal" | "italic" | "oblique";
- fontWeight: number;
+ fontStyle?: "normal" | "italic" | "oblique";
+ fontWeight?: number | string;
fontDisplay: "swap" | "auto" | "block" | "fallback" | "optional";
src: string;
};
@@ -142,9 +142,17 @@ export class FontFaceRule {
this.options = options;
}
get cssText() {
+ const decls = [];
const { fontFamily, fontStyle, fontWeight, fontDisplay, src } =
this.options;
- return `@font-face {\n font-family: ${fontFamily}; font-style: ${fontStyle}; font-weight: ${fontWeight}; font-display: ${fontDisplay}; src: ${src};\n}`;
+ decls.push(
+ `font-family: ${/\s/.test(fontFamily) ? `"${fontFamily}"` : fontFamily}`
+ );
+ decls.push(`font-style: ${fontStyle}`);
+ decls.push(`font-weight: ${fontWeight}`);
+ decls.push(`font-display: ${fontDisplay}`);
+ decls.push(`src: ${src}`);
+ return `@font-face {\n ${decls.join("; ")};\n}`;
}
}
diff --git a/packages/fonts/package.json b/packages/fonts/package.json
index 551a7c2ce4..71ee526838 100644
--- a/packages/fonts/package.json
+++ b/packages/fonts/package.json
@@ -18,7 +18,7 @@
},
"devDependencies": {
"@jest/globals": "^29.3.1",
- "@types/fontkit": "^2.0.0",
+ "@types/fontkit": "^2.0.1",
"@webstudio-is/design-system": "workspace:^",
"@webstudio-is/jest-config": "workspace:^",
"@webstudio-is/scripts": "workspace:^",
diff --git a/packages/fonts/src/__snapshots__/get-font-faces.test.ts.snap b/packages/fonts/src/__snapshots__/get-font-faces.test.ts.snap
index 9c6f3d6164..f814ece782 100644
--- a/packages/fonts/src/__snapshots__/get-font-faces.test.ts.snap
+++ b/packages/fonts/src/__snapshots__/get-font-faces.test.ts.snap
@@ -49,3 +49,16 @@ exports[`getFontFaces() different weight 1`] = `
},
]
`;
+
+exports[`getFontFaces() variable font 1`] = `
+[
+ {
+ "fontDisplay": "swap",
+ "fontFamily": "Inter",
+ "fontStretch": "25% 151%",
+ "fontStyle": "normal",
+ "fontWeight": "100 1000",
+ "src": "url('/fonts/inter.ttf') format('truetype')",
+ },
+]
+`;
diff --git a/packages/fonts/src/font-data.ts b/packages/fonts/src/font-data.ts
index 0b7345a91a..e6758ee6a2 100644
--- a/packages/fonts/src/font-data.ts
+++ b/packages/fonts/src/font-data.ts
@@ -1,4 +1,4 @@
-import type { FontFormat } from "./schema";
+import type { FontFormat, VariationAxes } from "./schema";
import { create as createFontKit } from "fontkit";
import { FontWeight, fontWeights } from "./font-weights";
@@ -7,6 +7,7 @@ declare module "fontkit" {
export interface Font {
type: string;
getName: (name: string) => string;
+ variationAxes: VariationAxes;
}
}
@@ -22,7 +23,6 @@ export const parseSubfamily = (subfamily: string) => {
break;
}
}
-
let weight: FontWeight = "400";
for (weight in fontWeights) {
const { name } = fontWeights[weight];
@@ -51,12 +51,18 @@ export const normalizeFamily = (family: string, subfamily: string) => {
return familyPartsNormalized.join(" ");
};
-type FontData = {
+type FontDataStatic = {
format: FontFormat;
family: string;
style: Style;
weight: number;
};
+type FontDataVariable = {
+ format: FontFormat;
+ family: string;
+ variationAxes: VariationAxes;
+};
+type FontData = FontDataStatic | FontDataVariable;
export const getFontData = (data: Uint8Array): FontData => {
const font = createFontKit(data as Buffer);
@@ -64,11 +70,20 @@ export const getFontData = (data: Uint8Array): FontData => {
const originalFamily = font.getName("fontFamily");
const subfamily =
font.getName("preferredSubfamily") ?? font.getName("fontSubfamily");
- const parsedSubfamily = parseSubfamily(subfamily);
const family = normalizeFamily(originalFamily, subfamily);
+ const isVariable = Object.keys(font.variationAxes).length !== 0;
+
+ if (isVariable) {
+ return {
+ format,
+ family,
+ variationAxes: font.variationAxes,
+ };
+ }
+
return {
format,
family,
- ...parsedSubfamily,
+ ...parseSubfamily(subfamily),
};
};
diff --git a/packages/fonts/src/get-font-faces.test.ts b/packages/fonts/src/get-font-faces.test.ts
index 6edc265ba2..72b1fe5ffe 100644
--- a/packages/fonts/src/get-font-faces.test.ts
+++ b/packages/fonts/src/get-font-faces.test.ts
@@ -73,4 +73,32 @@ describe("getFontFaces()", () => {
];
expect(getFontFaces(assets)).toMatchSnapshot();
});
+
+ test("variable font", () => {
+ const assets: Array<PartialFontAsset> = [
+ {
+ format: "ttf",
+ meta: {
+ family: "Inter",
+ variationAxes: {
+ wght: { name: "wght", min: 100, default: 400, max: 1000 },
+ wdth: { name: "wdth", min: 25, default: 100, max: 151 },
+ opsz: { name: "opsz", min: 8, default: 14, max: 144 },
+ GRAD: { name: "GRAD", min: -200, default: 0, max: 150 },
+ slnt: { name: "slnt", min: -10, default: 0, max: 0 },
+ XTRA: { name: "XTRA", min: 323, default: 468, max: 603 },
+ XOPQ: { name: "XOPQ", min: 27, default: 96, max: 175 },
+ YOPQ: { name: "YOPQ", min: 25, default: 79, max: 135 },
+ YTLC: { name: "YTLC", min: 416, default: 514, max: 570 },
+ YTUC: { name: "YTUC", min: 528, default: 712, max: 760 },
+ YTAS: { name: "YTAS", min: 649, default: 750, max: 854 },
+ YTDE: { name: "YTDE", min: -305, default: -203, max: -98 },
+ YTFI: { name: "YTFI", min: 560, default: 738, max: 788 },
+ },
+ },
+ path: "/fonts/inter.ttf",
+ },
+ ];
+ expect(getFontFaces(assets)).toMatchSnapshot();
+ });
});
diff --git a/packages/fonts/src/get-font-faces.ts b/packages/fonts/src/get-font-faces.ts
index 9948239ce3..cf9298a6f7 100644
--- a/packages/fonts/src/get-font-faces.ts
+++ b/packages/fonts/src/get-font-faces.ts
@@ -1,5 +1,5 @@
import { FONT_FORMATS } from "./constants";
-import type { FontMeta, FontFormat } from "./schema";
+import type { FontMeta, FontFormat, FontMetaStatic } from "./schema";
export type PartialFontAsset = {
format: FontFormat;
@@ -9,13 +9,25 @@ export type PartialFontAsset = {
export type FontFace = {
fontFamily: string;
- fontStyle: FontMeta["style"];
- fontWeight: number;
fontDisplay: "swap" | "auto" | "block" | "fallback" | "optional";
src: string;
+ fontStyle?: FontMetaStatic["style"];
+ fontWeight?: number | string;
+ fontStretch?: string;
};
-const formatFace = (asset: PartialFontAsset, format: string) => {
+const formatFace = (asset: PartialFontAsset, format: string): FontFace => {
+ if ("variationAxes" in asset.meta) {
+ const { wght, wdth } = asset.meta?.variationAxes ?? {};
+ return {
+ fontFamily: asset.meta.family,
+ fontStyle: "normal",
+ fontDisplay: "swap",
+ src: `url('${asset.path}') format('${format}')`,
+ fontStretch: wdth ? `${wdth.min}% ${wdth.max}%` : undefined,
+ fontWeight: wght ? `${wght.min} ${wght.max}` : undefined,
+ };
+ }
return {
fontFamily: asset.meta.family,
fontStyle: asset.meta.style,
@@ -25,15 +37,20 @@ const formatFace = (asset: PartialFontAsset, format: string) => {
};
};
-const getKey = (asset: PartialFontAsset) =>
- asset.meta.family + asset.meta.style + asset.meta.weight;
+const getKey = (asset: PartialFontAsset) => {
+ if ("variationAxes" in asset.meta) {
+ return asset.meta.family + Object.values(asset.meta.variationAxes).join("");
+ }
+ return asset.meta.family + asset.meta.style + asset.meta.weight;
+};
export const getFontFaces = (
assets: Array<PartialFontAsset>
): Array<FontFace> => {
const faces = new Map();
for (const asset of assets) {
- const face = faces.get(getKey(asset));
+ const assetKey = getKey(asset);
+ const face = faces.get(assetKey);
const format = FONT_FORMATS.get(asset.format);
if (format === undefined) {
// Should never happen since we allow only uploading formats we support
@@ -42,7 +59,7 @@ export const getFontFaces = (
if (face === undefined) {
const face = formatFace(asset, format);
- faces.set(getKey(asset), face);
+ faces.set(assetKey, face);
continue;
}
diff --git a/packages/fonts/src/schema.ts b/packages/fonts/src/schema.ts
index 00cb4e98c6..3d49a03f3e 100644
--- a/packages/fonts/src/schema.ts
+++ b/packages/fonts/src/schema.ts
@@ -9,9 +9,48 @@ export const FontFormat = z.union([
]);
export type FontFormat = z.infer<typeof FontFormat>;
-export const FontMeta = z.object({
+const AxisName = z.enum([
+ "wght",
+ "wdth",
+ "slnt",
+ "opsz",
+ "ital",
+ "GRAD",
+ "XTRA",
+ "XOPQ",
+ "YOPQ",
+ "YTLC",
+ "YTUC",
+ "YTAS",
+ "YTDE",
+ "YTFI",
+]);
+
+const VariationAxes = z.record(
+ AxisName,
+ z.object({
+ name: z.string(),
+ min: z.number(),
+ default: z.number(),
+ max: z.number(),
+ })
+);
+
+export type VariationAxes = z.infer<typeof VariationAxes>;
+
+export const FontMetaStatic = z.object({
family: z.string(),
style: z.enum(styles),
weight: z.number(),
});
+
+export type FontMetaStatic = z.infer<typeof FontMetaStatic>;
+
+const FontMetaVariable = z.object({
+ family: z.string(),
+ variationAxes: VariationAxes,
+});
+
+export const FontMeta = z.union([FontMetaStatic, FontMetaVariable]);
+
export type FontMeta = z.infer<typeof FontMeta>;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2cb889ef8a..70a0775bd5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -591,7 +591,7 @@ importers:
packages/fonts:
specifiers:
'@jest/globals': ^29.3.1
- '@types/fontkit': ^2.0.0
+ '@types/fontkit': ^2.0.1
'@webstudio-is/design-system': workspace:^
'@webstudio-is/jest-config': workspace:^
'@webstudio-is/scripts': workspace:^
@@ -604,7 +604,7 @@ importers:
fontkit: 2.0.2
devDependencies:
'@jest/globals': 29.3.1
- '@types/fontkit': 2.0.0
+ '@types/fontkit': 2.0.1
'@webstudio-is/design-system': link:../design-system
'@webstudio-is/jest-config': link:../jest-config
'@webstudio-is/scripts': link:../scripts
@@ -10978,10 +10978,10 @@ packages:
resolution: {integrity: sha512-WulqXMDUTYAXCjZnk6JtIHPigp55cVtDgDrO2gHRwhyJto21+1zbVCtOYB2L1F9w4qCQ0rOGWBnBe0FNTiEJIQ==}
dev: true
- /@types/fontkit/2.0.0:
- resolution: {integrity: sha512-Qe+6szpPLTNsqkDFs2MScJyB51d5Hpobyg/T0QoUWO53WuNOTNLsV8fkE4QQPOJbhOMN5wlwmNeDdsh/e6Uqdg==}
+ /@types/fontkit/2.0.1:
+ resolution: {integrity: sha512-B5Jk560iAlWJ56yV1yBUH8Ek9LykCzb3N0FwJHtbH/Vmd/E1QN/Isen4SAtBb2UEWpZid4GjLm1Fih1xM0MbXA==}
dependencies:
- '@types/node': 18.11.9
+ '@types/node': 18.11.18
dev: true
/@types/fs-extra/9.0.13: