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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: Publish uploaded fonts used through CSS variables (#6604)
Oleg Isonen59e0e1111f7a
diff --git a/.github/workflows/fixtures-test.yml b/.github/workflows/fixtures-test.ymlindex 1c4282524a..95c30afb21 100644--- a/.github/workflows/fixtures-test.yml+++ b/.github/workflows/fixtures-test.yml@@ -76,12 +76,16 @@ jobs:find . -type f -path "./fixtures/*/.webstudio/data.json" -exec sed -i 's|"origin": ".*"|"origin": "https://main.development.webstudio.is"|g' {} +- name: Test git diff- # This command will fail if there are uncommitted changes, i.e something has broken- run: git diff --name-only HEAD --exit-code+ # Submodule checkout can move the pinned commit to its current branch.+ run: |+ git diff --name-only HEAD --exit-code -- . ':(exclude)packages/sdk-components-animation/private-src'+ git -C packages/sdk-components-animation/private-src diff --name-only HEAD --exit-code- name: Show changed files and diffif: ${{ failure() }}run: |echo "Changed files are:"- git diff --name-only HEAD- git diff HEAD | head -n 1000+ git diff --name-only HEAD -- . ':(exclude)packages/sdk-components-animation/private-src'+ git -C packages/sdk-components-animation/private-src diff --name-only HEAD+ git diff HEAD -- . ':(exclude)packages/sdk-components-animation/private-src' | head -n 1000+ git -C packages/sdk-components-animation/private-src diff HEAD | head -n 1000diff --git a/apps/builder/app/shared/db/canvas.server.test.ts b/apps/builder/app/shared/db/canvas.server.test.tsindex 1457295f21..a674cf3f6d 100644--- a/apps/builder/app/shared/db/canvas.server.test.ts+++ b/apps/builder/app/shared/db/canvas.server.test.ts@@ -117,6 +117,69 @@ test("keeps font assets referenced from nested style values", () => {expect(bundle.assets).toEqual([fontAsset]);});+test.each([+ ["double", '"Playfair Display", serif'],+ ["single", "'Playfair Display', serif"],+])(+ "keeps fonts referenced through CSS variables with %s quotes",+ (_quote, headingValue) => {+ const build = createBundleBuild({+ styles: [+ {+ styleSourceId: "root",+ breakpointId: "base",+ property: "--font-body",+ value: { type: "unparsed", value: "Inter, system-ui, sans-serif" },+ },+ {+ styleSourceId: "root",+ breakpointId: "base",+ property: "--font-heading",+ value: { type: "unparsed", value: headingValue },+ },+ {+ styleSourceId: "root",+ breakpointId: "base",+ property: "--font-unused",+ value: { type: "unparsed", value: '"Unused Font", serif' },+ },+ {+ styleSourceId: "body",+ breakpointId: "base",+ property: "fontFamily",+ value: { type: "var", value: "font-body" },+ },+ {+ styleSourceId: "heading-token",+ breakpointId: "base",+ property: "fontFamily",+ value: { type: "var", value: "font-heading" },+ },+ ],+ });+ const fontAsset = (id: string, family: string): Asset => ({+ id,+ projectId: build.projectId,+ name: `${id}.woff2`,+ type: "font",+ createdAt: "2024-01-01T00:00:00.000Z",+ format: "woff2",+ size: 100,+ meta: { family, style: "normal", weight: 400 },+ });+ const inter = fontAsset("inter", "Inter");+ const playfair = fontAsset("playfair", "Playfair Display");+ const unused = fontAsset("unused", "Unused Font");++ const bundle = serializeProjectBundle({+ build,+ assets: [inter, playfair, unused],+ });++ expect(bundle.assets).toEqual([inter, playfair]);+ }+);+test("validates collections when publication does not need a content index", async () => {const build = createBundleBuild({styles: [diff --git a/packages/project-build/src/runtime/assets.test.ts b/packages/project-build/src/runtime/assets.test.tsindex 03534c1618..1a2b4d8b59 100644--- a/packages/project-build/src/runtime/assets.test.ts+++ b/packages/project-build/src/runtime/assets.test.ts@@ -908,6 +908,79 @@ describe("asset-info", () => {]);});+ test.each(['"Rajdhani", sans-serif', "'Rajdhani', sans-serif"])(+ "protects fonts used through a CSS variable: %s",+ (fontStack) => {+ const styles: Styles = new Map([+ [+ "root:base:--font-heading",+ {+ breakpointId: "base",+ styleSourceId: "root",+ property: "--font-heading",+ value: { type: "unparsed", value: fontStack },+ },+ ],+ [+ "heading:base:fontFamily",+ {+ breakpointId: "base",+ styleSourceId: "heading",+ property: "fontFamily",+ value: { type: "var", value: "font-heading" },+ },+ ],+ [+ "heading-2:base:fontFamily",+ {+ breakpointId: "base",+ styleSourceId: "heading-2",+ property: "fontFamily",+ value: { type: "var", value: "font-heading" },+ },+ ],+ ]);+ const assets = new Map([+ ["font", fontAsset("font")],+ ["font-bold", fontAsset("font-bold")],+ ]);+ const fontState = { ...state, styles, assets };++ expect(calculateUsagesByAssetId(fontState).get("font")).toEqual([+ { type: "style", styleDeclKey: "heading:base:fontFamily" },+ { type: "style", styleDeclKey: "heading-2:base:fontFamily" },+ ]);+ expect(calculateUsagesByAssetId(fontState).get("font-bold")).toEqual([+ { type: "style", styleDeclKey: "heading:base:fontFamily" },+ { type: "style", styleDeclKey: "heading-2:base:fontFamily" },+ ]);+ expect(() => deleteAssets(fontState, { assetIds: ["font"] })).toThrow(+ "Assets are still referenced: font"+ );+ expect(() =>+ deleteAssets(fontState, { assetIds: ["font-bold"] })+ ).toThrow("Assets are still referenced: font-bold");+ const replacementFont = {+ ...fontAsset("replacement"),+ meta: { family: "Replacement", style: "normal", weight: 600 },+ } as Asset;+ expect(() =>+ replaceAsset(+ {+ ...fontState,+ assets: new Map<Asset["id"], Asset>([+ ...fontState.assets,+ ["replacement", replacementFont],+ ]),+ },+ { fromAssetId: "font", toAssetId: "replacement" }+ )+ ).toThrow(+ "Asset is referenced in resources or variables. Update those references before replacing the asset."+ );+ }+ );+test("tracks font asset usage in nested style values", () => {const pages = createPages();const props: Props = new Map();diff --git a/packages/project-build/src/runtime/assets.ts b/packages/project-build/src/runtime/assets.tsindex 96ff39e4f0..1d63bd1220 100644--- a/packages/project-build/src/runtime/assets.ts+++ b/packages/project-build/src/runtime/assets.ts@@ -49,7 +49,7 @@ import { createRuntimeMutation } from "./mutation";import { createCopyName } from "./copy-name";import type { BuilderRuntimeContext } from "./context";import {- collectFontFamiliesFromStyleValue,+ collectFontFamiliesFromStyleDecls,traverseStyleValue,} from "./style-utils";@@ -324,10 +324,12 @@ export const calculateUsagesByAssetId = ({usagesByAsset.set(assetId, usages);};- const fontFamilyToAssetId = new Map<string, Asset["id"]>();+ const fontFamilyToAssetIds = new Map<string, Asset["id"][]>();for (const asset of assets.values()) {if (asset.type === "font") {- fontFamilyToAssetId.set(asset.meta.family, asset.id);+ const assetIds = fontFamilyToAssetIds.get(asset.meta.family) ?? [];+ assetIds.push(asset.id);+ fontFamilyToAssetIds.set(asset.meta.family, assetIds);}}@@ -369,18 +371,22 @@ export const calculateUsagesByAssetId = ({});}});- for (const fontFamily of collectFontFamiliesFromStyleValue(- styleDecl.value- )) {- const assetId = fontFamilyToAssetId.get(fontFamily);- if (assetId !== undefined) {- addUsage(assetId, {- type: "style",- styleDeclKey,- });+ }+ const styleDeclKeys = new Map(+ Array.from(styles, ([styleDeclKey, styleDecl]) => [styleDecl, styleDeclKey])+ );+ collectFontFamiliesFromStyleDecls(+ styles.values(),+ (fontFamily, styleDecl) => {+ const styleDeclKey = styleDeclKeys.get(styleDecl);+ if (styleDeclKey === undefined) {+ return;+ }+ for (const assetId of fontFamilyToAssetIds.get(fontFamily) ?? []) {+ addUsage(assetId, { type: "style", styleDeclKey });}}- }+ );return usagesByAsset;};@@ -1112,6 +1118,17 @@ export const replaceAsset = (return throwBuilderRuntimeError("NOT_FOUND", "Asset not found");}const build = getRequiredAssetReferenceBuild(state);+ let hasFontVariableUsage = false;+ if (fromAsset.type === "font") {+ collectFontFamiliesFromStyleDecls(+ build.styles,+ (family, _styleDecl, fromVariable) => {+ if (fromVariable && family === fromAsset.meta.family) {+ hasFontVariableUsage = true;+ }+ }+ );+ }const unrewritableUsages = createAssetUsageList({asset: fromAsset,assets,@@ -1120,7 +1137,7 @@ export const replaceAsset = ((usage) =>usage.namespace === "resources" || usage.namespace === "dataSources");- if (unrewritableUsages.length > 0) {+ if (unrewritableUsages.length > 0 || hasFontVariableUsage) {return throwBuilderRuntimeError("BAD_REQUEST","Asset is referenced in resources or variables. Update those references before replacing the asset."diff --git a/packages/project-build/src/runtime/style-utils.test.ts b/packages/project-build/src/runtime/style-utils.test.tsindex 09d2d7b4c0..fc85f9525b 100644--- a/packages/project-build/src/runtime/style-utils.test.ts+++ b/packages/project-build/src/runtime/style-utils.test.ts@@ -305,6 +305,41 @@ test("collects font families from style declarations", () => {).toEqual(new Set(["Inter"]));});+test("collects font families through nested variables and cyclic definitions", () => {+ expect(+ collectFontFamiliesFromStyleDecls([+ {+ property: "--font-name",+ value: { type: "unparsed", value: "'Playfair Display', serif" },+ },+ {+ property: "--font-heading",+ value: { type: "var", value: "font-name" },+ },+ {+ property: "--font-cycle-a",+ value: { type: "var", value: "font-cycle-b" },+ },+ {+ property: "--font-cycle-b",+ value: { type: "var", value: "font-cycle-a" },+ },+ {+ property: "fontFamily",+ value: { type: "var", value: "font-heading" },+ },+ {+ property: "fontFamily",+ value: {+ type: "var",+ value: "font-cycle-a",+ fallback: { type: "unparsed", value: "Inter, sans-serif" },+ },+ },+ ])+ ).toEqual(new Set(["Playfair Display", "serif", "Inter", "sans-serif"]));+});+const createGridStyleDecl = (styleSourceId: string,breakpointId: string,diff --git a/packages/project-build/src/runtime/style-utils.ts b/packages/project-build/src/runtime/style-utils.tsindex 27ec3fdac6..9c8b54d3a9 100644--- a/packages/project-build/src/runtime/style-utils.ts+++ b/packages/project-build/src/runtime/style-utils.ts@@ -1,4 +1,5 @@import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";+import { parseCssValue } from "@webstudio-is/css-data";import type {Instance,Styles,@@ -99,15 +100,72 @@ export const collectFontFamiliesFromStyleValue = (value: StyleValue) => {return fontFamilies;};-export const collectFontFamiliesFromStyleDecls = (- styles: Iterable<Pick<StyleDecl, "value">>+export const collectFontFamiliesFromStyleDecls = <+ Declaration extends Pick<StyleDecl, "value"> &+ Partial<Pick<StyleDecl, "property">>,+>(+ styles: Iterable<Declaration>,+ onFamily?: (+ family: string,+ styleDecl: Declaration,+ fromVariable: boolean+ ) => void) => {const fontFamilies = new Set<string>();- for (const styleDecl of styles) {- for (const fontFamily of collectFontFamiliesFromStyleValue(- styleDecl.value- )) {- fontFamilies.add(fontFamily);+ const customProperties = new Map<string, StyleValue[]>();+ const declarations = Array.from(styles);+ for (const styleDecl of declarations) {+ if (styleDecl.property?.startsWith("--")) {+ const values = customProperties.get(styleDecl.property) ?? [];+ values.push(styleDecl.value);+ customProperties.set(styleDecl.property, values);+ }+ }++ for (const styleDecl of declarations) {+ const families = new Map<string, boolean>();+ const addFamily = (family: string, fromVariable: boolean) => {+ families.set(family, fromVariable || families.get(family) === true);+ };+ if (styleDecl.property === "fontFamily") {+ const visitedVariables = new Set<string>();+ const collectFromVariable = (+ value: StyleValue,+ fromVariable: boolean+ ) => {+ traverseStyleValue(value, (item) => {+ if (item.type === "fontFamily") {+ for (const family of item.value) {+ addFamily(family, fromVariable);+ }+ }+ if (item.type === "unparsed") {+ const parsed = parseCssValue("font-family", item.value);+ if (parsed.type !== "unparsed") {+ collectFromVariable(parsed, fromVariable);+ }+ }+ if (item.type === "var") {+ const name = `--${item.value}`;+ if (visitedVariables.has(name)) {+ return;+ }+ visitedVariables.add(name);+ for (const definition of customProperties.get(name) ?? []) {+ collectFromVariable(definition, true);+ }+ }+ });+ };+ collectFromVariable(styleDecl.value, false);+ } else {+ for (const family of collectFontFamiliesFromStyleValue(styleDecl.value)) {+ addFamily(family, false);+ }+ }+ for (const [family, fromVariable] of families) {+ fontFamilies.add(family);+ onFamily?.(family, styleDecl, fromVariable);}}return fontFamilies;