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.

feat: auto-detect font weight based on selected font family (#4134)

Oleg Isonen052fe9e55c3b
diff --git a/apps/builder/app/builder/features/style-panel/controls/font-weight/font-weight-control.tsx b/apps/builder/app/builder/features/style-panel/controls/font-weight/font-weight-control.tsx
index 03690beec6..f8f66853fd 100644
--- a/apps/builder/app/builder/features/style-panel/controls/font-weight/font-weight-control.tsx
+++ b/apps/builder/app/builder/features/style-panel/controls/font-weight/font-weight-control.tsx
@@ -1,78 +1,25 @@
-import { Select } from "@webstudio-is/design-system";
-import { type FontWeight, fontWeights } from "@webstudio-is/fonts";
+import { Select, Text } from "@webstudio-is/design-system";
+import {
+ type FontWeight,
+ fontWeightNames,
+ fontWeights,
+} from "@webstudio-is/fonts";
import { toValue } from "@webstudio-is/css-engine";
-import { useMemo } from "react";
-import { useAssets } from "~/builder/shared/assets";
-import { isSupportedFontWeight } from "./is-supported-font-weight";
+import { useEffect } from "react";
import { useComputedStyles } from "../../shared/model";
import { setProperty } from "../../shared/use-style-data";
+import { canvasApi } from "~/shared/canvas-api";
+import { useStore } from "@nanostores/react";
+import { $detectedFontsWeights } from "~/shared/nano-states";
-type FontWeightItem = {
- label: string;
- weight: FontWeight;
-};
-
-const allFontWeights: Array<FontWeightItem> = (
- Object.keys(fontWeights) as Array<FontWeight>
-).map((weight) => ({
- label: `${weight} - ${fontWeights[weight].label}`,
- weight,
-}));
-
-// All font weights for the current family
-const useAvailableFontWeights = (
- currentFamily: string
-): Array<FontWeightItem> => {
- const { assetContainers } = useAssets("font");
-
- // Find all font weights that are available for the current font family.
- return useMemo(() => {
- const found = allFontWeights.filter((option) => {
- return assetContainers.find((assetContainer) => {
- if (
- assetContainer.status !== "uploaded" ||
- assetContainer.asset.type !== "font"
- ) {
- return false;
- }
- return isSupportedFontWeight(
- assetContainer.asset,
- option.weight,
- currentFamily
- );
- });
- });
- return found.length === 0 ? allFontWeights : found;
- }, [currentFamily, assetContainers]);
-};
-
-const useLabels = (
- availableFontWeights: Array<FontWeightItem>,
- currentWeight: string
-) => {
- // support named aliases
- if (currentWeight === "normal") {
- currentWeight = "400";
- }
- if (currentWeight === "bold") {
- currentWeight = "700";
- }
- const labels = useMemo(
- () => availableFontWeights.map((option) => option.label),
- [availableFontWeights]
- );
-
- const selectedLabel = useMemo(() => {
- const selectedOption =
- availableFontWeights.find((option) => option.weight === currentWeight) ??
- // In case available weights a custom font supports does not include the current weight,
- // we show the first available weight.
- availableFontWeights[0];
- return selectedOption?.label;
- }, [currentWeight, availableFontWeights]);
+const allFontWeights = Object.keys(fontWeights) as Array<FontWeight>;
- return { labels, selectedLabel };
-};
+const labels = new Map(
+ allFontWeights.map((weight) => [
+ weight,
+ `${weight} - ${fontWeights[weight as FontWeight].label}`,
+ ])
+);
export const FontWeightControl = () => {
// We need the font family to determine which font weights are available
@@ -80,32 +27,25 @@ export const FontWeightControl = () => {
"fontWeight",
"fontFamily",
]);
+ const detectedFontsWeights = useStore($detectedFontsWeights);
+ const fontFamilyCss = toValue(fontFamily.usedValue);
+ const fontWeightCss = toValue(fontWeight.cascadedValue);
+ const supportedFontWeights = detectedFontsWeights.get(fontFamilyCss) ?? [];
- const availableFontWeights = useAvailableFontWeights(
- toValue(fontFamily.cascadedValue, (styleValue) => {
- // override default fallback with rendering only first font family
- if (styleValue.type === "fontFamily") {
- return {
- type: "fontFamily",
- value: [styleValue.value[0]],
- };
- }
- })
- );
- const { labels, selectedLabel } = useLabels(
- availableFontWeights,
- toValue(fontWeight.cascadedValue)
- );
+ useEffect(() => {
+ canvasApi.detectSupportedFontWeights(fontFamilyCss);
+ }, [fontFamilyCss]);
+
+ const selectedWeight =
+ fontWeightNames.get(fontWeightCss) ?? (fontWeightCss as FontWeight);
const setValue = setProperty("fontWeight");
- const setFontWeight = (label: string, options?: { isEphemeral: boolean }) => {
- const selected = availableFontWeights.find(
- (option) => option.label === label
- );
- if (selected) {
- setValue({ type: "keyword", value: selected.weight }, options);
- }
+ const setFontWeight = (
+ nextWeight: FontWeight,
+ options?: { isEphemeral: boolean }
+ ) => {
+ setValue({ type: "keyword", value: nextWeight }, options);
};
return (
@@ -113,20 +53,29 @@ export const FontWeightControl = () => {
// show empty field instead of radix placeholder
// like css value input does
placeholder=""
- options={labels}
+ options={allFontWeights}
+ getLabel={(weight: FontWeight) => {
+ return (
+ <Text
+ color={supportedFontWeights.includes(weight) ? "main" : "subtle"}
+ >
+ {labels.get(weight)}
+ </Text>
+ );
+ }}
// We use a weight as a value, because there are only 9 weights and they are unique.
- value={selectedLabel}
+ value={selectedWeight}
onChange={setFontWeight}
- onItemHighlight={(label) => {
+ onItemHighlight={(nextWeight) => {
// Remove preview when mouse leaves the item.
- if (label === undefined) {
+ if (nextWeight === undefined) {
if (fontWeight !== undefined) {
setValue(fontWeight.cascadedValue, { isEphemeral: true });
}
return;
}
// Preview on mouse enter or focus.
- setFontWeight(label, { isEphemeral: true });
+ setFontWeight(nextWeight, { isEphemeral: true });
}}
onOpenChange={(isOpen) => {
// Remove ephemeral changes when closing the menu.
diff --git a/apps/builder/app/builder/features/style-panel/controls/font-weight/is-supported-font-weight.test.ts b/apps/builder/app/builder/features/style-panel/controls/font-weight/is-supported-font-weight.test.ts
deleted file mode 100644
index 8354c3e4f1..0000000000
--- a/apps/builder/app/builder/features/style-panel/controls/font-weight/is-supported-font-weight.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { describe, test, expect } from "@jest/globals";
-import type { FontAsset } from "@webstudio-is/sdk";
-import { isSupportedFontWeight } from "./is-supported-font-weight";
-
-const createServerAsset = (meta: FontAsset["meta"]): FontAsset => ({
- id: "111",
- type: "font",
- name: "test",
- projectId: "id",
- size: 2135,
- format: "ttf",
- createdAt: "",
- description: "",
- meta,
-});
-
-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/builder/app/builder/features/style-panel/controls/font-weight/is-supported-font-weight.ts b/apps/builder/app/builder/features/style-panel/controls/font-weight/is-supported-font-weight.ts
deleted file mode 100644
index 8935f80c4f..0000000000
--- a/apps/builder/app/builder/features/style-panel/controls/font-weight/is-supported-font-weight.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import type { FontAsset } from "@webstudio-is/sdk";
-
-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/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index 85e2c72577..d7d17c9fdc 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -64,6 +64,7 @@ import { $params } from "./stores";
import { useScrollNewInstanceIntoView } from "./shared/use-scroll-new-instance-into-view";
import { subscribeInspectorEdits } from "./inspector-edits";
import { initCanvasApi } from "~/shared/canvas-api";
+import { subscribeFontLoadingDone } from "./shared/font-weight-support";
registerContainers();
@@ -143,6 +144,7 @@ const DesignMode = () => {
useEffect(subscribeInstanceSelection, []);
useEffect(subscribeInstanceHovering, []);
useEffect(subscribeInspectorEdits, []);
+ useEffect(subscribeFontLoadingDone, []);
return null;
};
diff --git a/apps/builder/app/canvas/shared/font-weight-support.ts b/apps/builder/app/canvas/shared/font-weight-support.ts
new file mode 100644
index 0000000000..b98a2d6a99
--- /dev/null
+++ b/apps/builder/app/canvas/shared/font-weight-support.ts
@@ -0,0 +1,117 @@
+import type { FontWeight } from "@webstudio-is/fonts";
+import { $detectedFontsWeights } from "~/shared/nano-states";
+
+const fontWeights: Array<FontWeight> = [
+ "100",
+ "200",
+ "300",
+ "400",
+ "500",
+ "600",
+ "700",
+ "800",
+ "900",
+];
+
+// Render a font on canvas in each width and compare the amount of inked pixels.
+const testFontWeights = (fontFamily: string) => {
+ const canvas = document.createElement("canvas");
+ canvas.width = 200;
+ canvas.height = 20;
+ const context = canvas.getContext("2d");
+ const supportedWeights: Array<FontWeight> = ["400"];
+
+ if (context === null) {
+ return supportedWeights;
+ }
+
+ const weightWidthMap: Map<FontWeight, number> = new Map();
+
+ // Function to render text with a given font weight and measure "inked" pixels
+ // We can't just compare the text width using `context.measureText(..).width api` because many monospace
+ // fonts have the same width for all weights.
+ const measureInkCoverage = (fontWeight: string) => {
+ context.clearRect(0, 0, canvas.width, canvas.height);
+ context.font = `${fontWeight} 16px ${fontFamily}`;
+ context.fillText("abcdefgsw1234567890", 0, 16);
+
+ const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
+ const pixels = imageData.data;
+
+ let inkedPixels = 0;
+ // Loop through all pixel data and count non-transparent pixels.
+ for (let index = 3; index < pixels.length; index += 4) {
+ if (pixels[index] > 0) {
+ inkedPixels++;
+ }
+ }
+
+ return inkedPixels;
+ };
+
+ for (const testWeight of fontWeights) {
+ weightWidthMap.set(
+ testWeight as FontWeight,
+ measureInkCoverage(testWeight)
+ );
+ }
+
+ const compare = (weights: Array<FontWeight>) => {
+ const supported: Array<FontWeight> = [];
+ for (let index = 0; index < weights.length; index++) {
+ const referenceWeight = weights[index];
+ const testWeight = weights[index + 1];
+ const referenceWidth = weightWidthMap.get(referenceWeight);
+ const testWidth = weightWidthMap.get(testWeight);
+ // If next width is the same as the previous one, it means the weight is not supported
+ if (testWeight && testWidth !== referenceWidth) {
+ supported.push(testWeight);
+ }
+ }
+ return supported;
+ };
+
+ // 400 is the baseline that's always supported, from there we test in both directions
+ // each step must result in a different width to be considered supported
+ // if for e.g. 400-300 is compared and has not change in width, it means 300 is not supported
+ // then we can then compare 300-200 and so on.
+ supportedWeights.push(...compare(["400", "300", "200", "100"]));
+ supportedWeights.push(...compare(["400", "500", "600", "700", "800", "900"]));
+
+ return supportedWeights.sort();
+};
+
+export const subscribeFontLoadingDone = () => {
+ // @todo move it to the call-site
+ const abortController = new AbortController();
+ document.fonts.addEventListener(
+ "loadingdone",
+ () => {
+ const cache = new Map($detectedFontsWeights.get());
+ // We need to re-detect all fonts because we don't know which fonts were loaded.
+ for (const [stack] of cache) {
+ const supportedWeights = testFontWeights(stack);
+ cache.set(stack, supportedWeights);
+ }
+ $detectedFontsWeights.set(cache);
+ },
+ { signal: abortController.signal }
+ );
+
+ return () => {
+ abortController.abort();
+ };
+};
+
+export const detectSupportedFontWeights = (stack: string) => {
+ // Delaying it to potentially have less work done in the previous frame.
+ requestAnimationFrame(() => {
+ const cache = new Map($detectedFontsWeights.get());
+ // Detecting immediately in case its a font that is already loaded, otheriwese
+ // it will be detected correctly when the font is loaded and in the meantime the detected
+ // value may be incorrect due to the fallback font.
+ const supportedWeights = testFontWeights(stack);
+ cache.set(stack, supportedWeights);
+ $detectedFontsWeights.set(cache);
+ });
+};
diff --git a/apps/builder/app/shared/canvas-api.ts b/apps/builder/app/shared/canvas-api.ts
index 4bf1c7f7cf..cf73faa838 100644
--- a/apps/builder/app/shared/canvas-api.ts
+++ b/apps/builder/app/shared/canvas-api.ts
@@ -5,6 +5,7 @@ import { createRecursiveProxy } from "@trpc/server/shared";
import invariant from "tiny-invariant";
import { $canvasIframeState } from "./nano-states";
import { getElementAndAncestorInstanceTags } from "~/canvas/instance-selected";
+import { detectSupportedFontWeights } from "~/canvas/shared/font-weight-support";
const apiWindowNamespace = "__webstudio__$__canvasApi";
@@ -15,6 +16,7 @@ const _canvasApi = {
preventUnhandled,
monitorForExternal,
getElementAndAncestorInstanceTags,
+ detectSupportedFontWeights,
};
declare global {
diff --git a/apps/builder/app/shared/nano-states/canvas.ts b/apps/builder/app/shared/nano-states/canvas.ts
index 164842b18a..ffecc3c38c 100644
--- a/apps/builder/app/shared/nano-states/canvas.ts
+++ b/apps/builder/app/shared/nano-states/canvas.ts
@@ -1,5 +1,6 @@
import { atom, computed } from "nanostores";
import type { Instance, Instances } from "@webstudio-is/sdk";
+import type { FontWeight } from "@webstudio-is/fonts";
import { $instances } from "./instances";
import type { InstanceSelector } from "../tree-utils";
@@ -71,3 +72,7 @@ export const synchronizedCanvasStores = [
] as const;
export const $canvasIframeState = atom<"idle" | "ready">("idle");
+
+export const $detectedFontsWeights = atom<Map<string, Array<FontWeight>>>(
+ new Map()
+);
diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts
index 3806af1c60..9a35a02a93 100644
--- a/apps/builder/app/shared/sync/sync-stores.ts
+++ b/apps/builder/app/shared/sync/sync-stores.ts
@@ -41,6 +41,7 @@ import {
$canvasIframeState,
$uploadingFilesDataStore,
$memoryProps,
+ $detectedFontsWeights,
} from "~/shared/nano-states";
import { $ephemeralStyles } from "~/canvas/stores";
@@ -126,6 +127,7 @@ export const registerContainers = () => {
clientStores.set("canvasIframeState", $canvasIframeState);
clientStores.set("uploadingFilesDataStore", $uploadingFilesDataStore);
clientStores.set("memoryProps", $memoryProps);
+ clientStores.set("detectedFontsWeights", $detectedFontsWeights);
for (const [name, store] of $synchronizedBreakpoints) {
clientStores.set(name, store);
diff --git a/packages/fonts/src/font-weights.ts b/packages/fonts/src/font-weights.ts
index 06ceacb85b..20b66fdf2c 100644
--- a/packages/fonts/src/font-weights.ts
+++ b/packages/fonts/src/font-weights.ts
@@ -37,4 +37,13 @@ export const fontWeights = {
},
} as const;
+export const fontWeightNames = new Map<string, FontWeight>(
+ Object.keys(fontWeights)
+ .map((weight) => {
+ const weightData = fontWeights[weight as FontWeight];
+ return weightData.names.map((name) => [name, weight]);
+ })
+ .flat() as Array<[string, FontWeight]>
+);
+
export type FontWeight = keyof typeof fontWeights;