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.

render fonts using css engine

Oleg Isonen80a30a2b201b
diff --git a/apps/designer/app/canvas/canvas.tsx b/apps/designer/app/canvas/canvas.tsx
index b6b37946dc..77aa7e67b2 100644
--- a/apps/designer/app/canvas/canvas.tsx
+++ b/apps/designer/app/canvas/canvas.tsx
@@ -3,10 +3,9 @@ import store from "immerhin";
import type { Build } from "@webstudio-is/project";
import {
createElementsTree,
- useGlobalStyles,
+ useAllUserProps,
type OnChangeChildren,
type Tree,
- useAllUserProps,
} from "@webstudio-is/react-sdk";
import { useSubscribe } from "~/shared/pubsub";
import { useShortcuts } from "./shared/use-shortcuts";
@@ -24,7 +23,7 @@ import {
useUnselectInstance,
useUpdateSelectedInstance,
} from "./shared/instance";
-import { useManageStyles } from "./shared/styles";
+import { useManageDesignModeStyles, useGlobalStyles } from "./shared/styles";
import { useTrackSelectedElement } from "./shared/use-track-selected-element";
import { WrapperComponentDev } from "./features/wrapper-component";
import { useSync } from "./shared/sync";
@@ -91,7 +90,7 @@ type DesignModeProps = {
const DesignMode = ({ treeId, buildId }: DesignModeProps) => {
useManageBreakpoints();
- useManageStyles();
+ useManageDesignModeStyles();
useManageProps();
usePublishSelectedInstanceData(treeId);
useInsertInstance();
@@ -123,7 +122,7 @@ export const Canvas = ({ data }: CanvasProps): JSX.Element | null => {
const isDesignerReady = useSubscribeDesignerReady();
useInitializeBreakpoints(data.breakpoints);
const assets = useAssets(data.assets);
- useGlobalStyles({ assets });
+ useGlobalStyles(assets);
useAllUserProps(data.props);
usePopulateRootInstance(data.tree);
// e.g. toggling preview is still needed in both modes
diff --git a/apps/designer/app/canvas/shared/breakpoints.ts b/apps/designer/app/canvas/shared/breakpoints.ts
index 15a2bacef0..6d2a960d65 100644
--- a/apps/designer/app/canvas/shared/breakpoints.ts
+++ b/apps/designer/app/canvas/shared/breakpoints.ts
@@ -1,6 +1,6 @@
import { useEffect, useRef } from "react";
import store from "immerhin";
-import { type Breakpoint, setBreakpoints } from "@webstudio-is/react-sdk";
+import type { Breakpoint } from "@webstudio-is/react-sdk";
import { useSubscribe } from "~/shared/pubsub";
import { deleteCssRulesByBreakpoint } from "~/shared/css-utils";
import {
@@ -17,7 +17,6 @@ export const useInitializeBreakpoints = (breakpoints: Array<Breakpoint>) => {
const ref = useRef(false);
if (ref.current === false) {
ref.current = true;
- setBreakpoints(breakpoints);
setCurrentBreakpoints(breakpoints);
addMediaRules(breakpoints);
}
@@ -45,7 +44,7 @@ const useBreakpointChange = () => {
breakpoints.push(breakpoint);
}
- setBreakpoints(breakpoints);
+ addMediaRules(breakpoints);
});
});
};
diff --git a/apps/designer/app/canvas/shared/styles.ts b/apps/designer/app/canvas/shared/styles.ts
index 03f6e3eb22..23da6a9d4c 100644
--- a/apps/designer/app/canvas/shared/styles.ts
+++ b/apps/designer/app/canvas/shared/styles.ts
@@ -16,9 +16,15 @@ import {
type Style,
} from "@webstudio-is/react-sdk";
import { useEffect } from "react";
-import { createCssEngine, type StyleRule } from "@webstudio-is/css-engine";
+import {
+ createCssEngine,
+ type CssEngine,
+ type StyleRule,
+ type PlaintextRule,
+} from "@webstudio-is/css-engine";
import { useIsomorphicLayoutEffect } from "react-use";
-import { PlaintextRule } from "@webstudio-is/css-engine/src/core/rules";
+import { Asset, FontAsset } from "@webstudio-is/asset-uploader";
+import { FontFormat, FONT_FORMATS, getFontFaces } from "@webstudio-is/fonts";
const cssEngine = createCssEngine();
@@ -26,7 +32,7 @@ const voidElements =
"area, base, br, col, embed, hr, img, input, link, meta, source, track, wbr";
// Helper styles on for canvas in design mode
-const styles = [
+const helperStyles = [
// When double clicking into an element to edit text, it should not select the word.
`[${idAttribute}] {
user-select: none;
@@ -48,14 +54,47 @@ const styles = [
margin: 0
}`,
];
-for (const style of styles) cssEngine.addPlaintextRule(style);
-export const useManageStyles = () => {
+export const useManageDesignModeStyles = () => {
useUpdateStyle();
usePreviewStyle();
useRemoveSsrStyles();
};
+export const addGlobalRules = (
+ engine: CssEngine,
+ { assets = [] }: { assets?: Array<Asset> }
+) => {
+ // @todo we need to figure out all global resets while keeping
+ // the engine aware of all of them.
+ // Ideally, the user is somehow aware and in control of the reset
+ engine.addPlaintextRule("html {margin: 0; height: 100%}");
+
+ const fontAssets = assets.filter((asset) =>
+ FONT_FORMATS.has(asset.format as FontFormat)
+ ) as Array<FontAsset>;
+ const fontFaces = getFontFaces(fontAssets);
+ for (const fontFace of fontFaces) {
+ engine.addFontFaceRule(fontFace);
+ }
+};
+
+const globalStylesCssEngine = createCssEngine();
+
+export const useGlobalStyles = (assets: Array<Asset>) => {
+ globalStylesCssEngine.clear();
+
+ addGlobalRules(globalStylesCssEngine, { assets });
+
+ for (const style of helperStyles) {
+ globalStylesCssEngine.addPlaintextRule(style);
+ }
+
+ if (typeof document !== "undefined") {
+ globalStylesCssEngine.render();
+ }
+};
+
// Wrapps a normal StyleValue into a VarStyleValue that uses the previous style value as a fallback and allows
// to quickly pass the values over CSS variable witout rerendering the components tree.
// Results in values like this: `var(--namespace, staticValue)`
diff --git a/apps/designer/app/routes/s/css.ts b/apps/designer/app/routes/s/css.ts
index 5165138e46..97d7a57feb 100644
--- a/apps/designer/app/routes/s/css.ts
+++ b/apps/designer/app/routes/s/css.ts
@@ -7,6 +7,7 @@ import { sentryException } from "~/shared/sentry";
import { createCssEngine } from "@webstudio-is/css-engine";
import { getCssRules } from "~/shared/tree-utils";
import { idAttribute } from "@webstudio-is/react-sdk";
+import { addGlobalRules } from "~/canvas/shared/styles";
export const loader: ActionFunction = async ({ request }) => {
try {
@@ -34,6 +35,8 @@ export const loader: ActionFunction = async ({ request }) => {
const engine = createCssEngine();
+ addGlobalRules(engine, canvasData);
+
for (const breakpoint of canvasData.breakpoints) {
engine.addMediaRule(breakpoint.id, breakpoint);
}
diff --git a/packages/css-engine/src/core/css-engine.test.ts b/packages/css-engine/src/core/css-engine.test.ts
index ddf3ba3f33..6ba8452d5f 100644
--- a/packages/css-engine/src/core/css-engine.test.ts
+++ b/packages/css-engine/src/core/css-engine.test.ts
@@ -167,10 +167,40 @@ describe("CssEngine", () => {
test("plaintext rule", () => {
engine.addPlaintextRule(".c { color: red }");
+ expect(engine.cssText).toMatchInlineSnapshot(`".c { color: red }"`);
+ });
+
+ test("plaintext - no duplicates", () => {
+ engine.addPlaintextRule(".c { color: red }");
+ engine.addPlaintextRule(".c { color: red }");
+ engine.addPlaintextRule(".c { color: green }");
expect(engine.cssText).toMatchInlineSnapshot(`
- "@media all {
- .c { color: red }
+ ".c { color: red }
+ .c { color: green }"
+ `);
+ });
+
+ test("font family rule", () => {
+ engine.addFontFaceRule({
+ fontFamily: "Roboto",
+ fontStyle: "normal",
+ fontWeight: 400,
+ fontDisplay: "swap",
+ src: "url(/src)",
+ });
+ expect(engine.cssText).toMatchInlineSnapshot(`
+ "@font-face {
+ font-family: Roboto; font-style: normal; font-weight: 400; font-display: swap; src: url(/src);
}"
`);
});
+
+ test("clear", () => {
+ engine.addStyleRule(".c", {
+ style: style0,
+ breakpoint: "0",
+ });
+ engine.clear();
+ expect(engine.cssText).toMatchInlineSnapshot(`""`);
+ });
});
diff --git a/packages/css-engine/src/core/css-engine.ts b/packages/css-engine/src/core/css-engine.ts
index fd4cf420eb..f043972709 100644
--- a/packages/css-engine/src/core/css-engine.ts
+++ b/packages/css-engine/src/core/css-engine.ts
@@ -1,8 +1,10 @@
import { CssRule } from "@webstudio-is/react-sdk";
import {
+ FontFaceRule,
MediaRule,
PlaintextRule,
StyleRule,
+ type FontFaceOptions,
type MediaRuleOptions,
} from "./rules";
import { StyleElement } from "./style-element";
@@ -13,6 +15,8 @@ const defaultMediaRuleId = "__default-media-rule__";
export class CssEngine {
#element;
#mediaRules: Map<string, MediaRule> = new Map();
+ #plainRules: Map<string, PlaintextRule> = new Map();
+ #fontFaceRules: Array<FontFaceRule> = [];
#sheet: StyleSheet;
#isDirty = false;
#cssText = "";
@@ -44,12 +48,18 @@ export class CssEngine {
return mediaRule.insertRule(styleRule);
}
addPlaintextRule(cssText: string) {
- const mediaRule = this.#mediaRules.get(defaultMediaRuleId);
- if (mediaRule === undefined) {
- // Should be impossible to reach.
- throw new Error("No media rule found");
- }
- return mediaRule.insertRule(new PlaintextRule(cssText));
+ const rule = this.#plainRules.get(cssText);
+ if (rule !== undefined) return rule;
+ return this.#plainRules.set(cssText, new PlaintextRule(cssText));
+ }
+ addFontFaceRule(options: FontFaceOptions) {
+ return this.#fontFaceRules.push(new FontFaceRule(options));
+ }
+ clear() {
+ this.#mediaRules.clear();
+ this.#plainRules.clear();
+ this.#fontFaceRules = [];
+ this.#isDirty = true;
}
render() {
this.#element.mount();
@@ -62,6 +72,11 @@ export class CssEngine {
}
this.#isDirty = false;
const css: Array<string> = [];
+
+ css.push(...this.#fontFaceRules.map((rule) => rule.cssText));
+ for (const plaintextRule of this.#plainRules.values()) {
+ css.push(plaintextRule.cssText);
+ }
for (const mediaRule of this.#mediaRules.values()) {
const { cssText } = mediaRule;
if (cssText !== "") css.push(cssText);
diff --git a/packages/css-engine/src/core/index.ts b/packages/css-engine/src/core/index.ts
index 1b9ef7391f..7edd74db29 100644
--- a/packages/css-engine/src/core/index.ts
+++ b/packages/css-engine/src/core/index.ts
@@ -1,3 +1,9 @@
export { CssEngine } from "./css-engine";
-export type { AnyRule, StyleRule, MediaRule } from "./rules";
+export type {
+ AnyRule,
+ StyleRule,
+ MediaRule,
+ PlaintextRule,
+ FontFaceRule,
+} from "./rules";
export * from "./create-css-engine";
diff --git a/packages/css-engine/src/core/rules.ts b/packages/css-engine/src/core/rules.ts
index a2a9d78f68..fa8639c720 100644
--- a/packages/css-engine/src/core/rules.ts
+++ b/packages/css-engine/src/core/rules.ts
@@ -95,4 +95,24 @@ export class PlaintextRule {
}
}
-export type AnyRule = StyleRule | MediaRule | PlaintextRule;
+export type FontFaceOptions = {
+ fontFamily: string;
+ fontStyle: "normal" | "italic" | "oblique";
+ fontWeight: number;
+ fontDisplay: "swap" | "auto" | "block" | "fallback" | "optional";
+ src: string;
+};
+
+export class FontFaceRule {
+ #options: FontFaceOptions;
+ constructor(options: FontFaceOptions) {
+ this.#options = options;
+ }
+ get cssText() {
+ 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}`;
+ }
+}
+
+export type AnyRule = StyleRule | MediaRule | PlaintextRule | FontFaceRule;
diff --git a/packages/react-sdk/src/stitches/stitches.ts b/packages/react-sdk/src/stitches/stitches.ts
index e724c3db2e..ba3f755fbc 100644
--- a/packages/react-sdk/src/stitches/stitches.ts
+++ b/packages/react-sdk/src/stitches/stitches.ts
@@ -1,5 +1,4 @@
import { createStitches, type CSS } from "@stitches/core";
-import type { FontFace } from "@webstudio-is/fonts";
import type { Breakpoint } from "../css";
let media = {};
@@ -47,35 +46,3 @@ export const setBreakpoints = (breakpoints: Array<Breakpoint>) => {
media = nextMedia;
stitches = undefined;
};
-
-let styleElement: HTMLStyleElement | undefined;
-
-/**
- * Stitches doesn't update fonts over globalCss
- */
-export const renderFontFaces = (fontFaces: Array<FontFace>) => {
- fontsCss = fontFaces
- .map(
- (fontFace) =>
- `
-@font-face {
- font-family: ${fontFace.fontFamily};
- font-style: ${fontFace.fontStyle};
- font-weight: ${fontFace.fontWeight};
- font-display: ${fontFace.fontDisplay};
- src: ${fontFace.src};
-}`
- )
- .join("");
-
- if (
- typeof document !== "undefined" &&
- typeof document.createElement === "function"
- ) {
- if (styleElement === undefined) {
- styleElement = document.createElement("style");
- document.head.appendChild(styleElement);
- }
- styleElement.textContent = fontsCss;
- }
-};
diff --git a/packages/react-sdk/src/tree/root.ts b/packages/react-sdk/src/tree/root.ts
index 784beadab7..797382133c 100644
--- a/packages/react-sdk/src/tree/root.ts
+++ b/packages/react-sdk/src/tree/root.ts
@@ -1,16 +1,11 @@
import { useAllUserProps } from "../user-props/";
import type { Tree, InstanceProps } from "../db";
import type { Breakpoint } from "../css";
-import { globalCss, setBreakpoints, renderFontFaces } from "../stitches";
+import { setBreakpoints } from "../stitches";
import { createElementsTree } from "./create-elements-tree";
import { WrapperComponent } from "./wrapper-component";
-import {
- type FontFormat,
- FONT_FORMATS,
- getFontFaces,
-} from "@webstudio-is/fonts";
-import type { Asset, FontAsset } from "@webstudio-is/asset-uploader";
-import { type ComponentProps, useRef } from "react";
+import type { Asset } from "@webstudio-is/asset-uploader";
+import { type ComponentProps } from "react";
export type Data = {
tree: Tree | null;
@@ -19,27 +14,6 @@ export type Data = {
assets: Array<Asset>;
};
-export const useGlobalStyles = ({ assets }: { assets: Array<Asset> }) => {
- const ref = useRef<Array<Asset>>();
-
- // This may look weird, but globalCss API doesn't allow us creating global styles with data,
- // so we have to manually ensure calling it only once
- if (ref.current === assets) return;
-
- const fontAssets = assets.filter((asset) =>
- FONT_FORMATS.has(asset.format as FontFormat)
- ) as Array<FontAsset>;
-
- renderFontFaces(getFontFaces(fontAssets));
- globalCss({
- html: {
- height: "100%",
- },
- })();
-
- ref.current = assets;
-};
-
type RootProps = {
data: Data;
Component?: (props: ComponentProps<typeof WrapperComponent>) => JSX.Element;
@@ -53,7 +27,6 @@ export const InstanceRoot = ({
throw new Error("Tree is null");
}
setBreakpoints(data.breakpoints);
- useGlobalStyles({ assets: data.assets });
useAllUserProps(data.props);
return createElementsTree({
instance: data.tree.root,