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.

refactor: generalize css api and add test (#3081)

Bogdan Chadkin201ffd5fb820
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index 1182dad734..1afc93c1dc 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -476,20 +476,16 @@ export const prebuild = async (options: {
spinner.text = "Generating css file";
- const { cssText, classesMap } = generateCss(
- {
- assets: siteData.assets,
- breakpoints: siteData.build?.breakpoints,
- styles: siteData.build?.styles,
- styleSourceSelections: siteData.build?.styleSourceSelections,
- // pass only used metas to not generate unused preset styles
- componentMetas: projectMetas,
- },
- {
- assetBaseUrl,
- atomic: siteData.build.pages.compiler?.atomicStyles ?? true,
- }
- );
+ const { cssText, classesMap } = generateCss({
+ assets,
+ breakpoints: new Map(siteData.build?.breakpoints),
+ styles: new Map(siteData.build?.styles),
+ styleSourceSelections: new Map(siteData.build?.styleSourceSelections),
+ // pass only used metas to not generate unused preset styles
+ componentMetas: projectMetas,
+ assetBaseUrl,
+ atomic: siteData.build.pages.compiler?.atomicStyles ?? true,
+ });
await ensureFileInPath(join(generatedDir, "index.css"), cssText);
diff --git a/packages/react-sdk/src/css/css.test.ts b/packages/react-sdk/src/css/css.test.ts
new file mode 100644
index 0000000000..2c5101c8ed
--- /dev/null
+++ b/packages/react-sdk/src/css/css.test.ts
@@ -0,0 +1,73 @@
+import { expect, test } from "@jest/globals";
+import type { Breakpoint } from "@webstudio-is/sdk";
+import { generateCss, type CssConfig } from "./css";
+
+const toMap = <T extends { id: string }>(list: T[]) =>
+ new Map(list.map((item) => [item.id, item] as const));
+
+const generateAllCss = (config: Omit<CssConfig, "atomic">) => {
+ const { cssText } = generateCss({
+ ...config,
+ atomic: false,
+ });
+ const { cssText: atomicCssText, classesMap } = generateCss({
+ ...config,
+ atomic: true,
+ });
+ return { cssText, atomicCssText, classesMap };
+};
+
+test("generate css for one instance with two tokens", () => {
+ const { cssText, atomicCssText, classesMap } = generateAllCss({
+ assets: new Map(),
+ breakpoints: toMap<Breakpoint>([{ id: "base", label: "" }]),
+ styleSourceSelections: new Map([
+ ["box", { instanceId: "box", values: ["token", "local"] }],
+ ]),
+ styles: new Map([
+ [
+ "token:base:color",
+ {
+ styleSourceId: "local",
+ breakpointId: "base",
+ property: "color",
+ value: { type: "keyword", value: "red" },
+ },
+ ],
+
+ [
+ "local:base:color",
+ {
+ styleSourceId: "token",
+ breakpointId: "base",
+ property: "color",
+ value: { type: "keyword", value: "blue" },
+ },
+ ],
+ ]),
+ componentMetas: new Map(),
+ assetBaseUrl: "",
+ });
+ expect(cssText).toMatchInlineSnapshot(`
+"html {margin: 0; display: grid; min-height: 100%}
+@media all {
+ [data-ws-id="box"] {
+ color: red
+ }
+}"
+`);
+ expect(atomicCssText).toMatchInlineSnapshot(`
+"html {margin: 0; display: grid; min-height: 100%}@media all {
+ .c10nxgm2 {
+ color: red
+ }
+}"
+`);
+ expect(classesMap).toMatchInlineSnapshot(`
+Map {
+ "box" => [
+ "c10nxgm2",
+ ],
+}
+`);
+});
diff --git a/packages/react-sdk/src/css/css.ts b/packages/react-sdk/src/css/css.ts
index 004c2a323a..cca66521df 100644
--- a/packages/react-sdk/src/css/css.ts
+++ b/packages/react-sdk/src/css/css.ts
@@ -4,28 +4,22 @@ import {
type TransformValue,
} from "@webstudio-is/css-engine";
import type {
- Asset,
Assets,
- Breakpoint,
- Instance,
- StyleDecl,
- StyleDeclKey,
- StyleSourceSelection,
+ Breakpoints,
+ StyleSourceSelections,
+ Styles,
} from "@webstudio-is/sdk";
import type { WsComponentMeta } from "../components/component-meta";
import { idAttribute } from "../props";
import { addGlobalRules } from "./global-rules";
import { getPresetStyleRules, getStyleRules } from "./style-rules";
-type Data = {
- assets: Asset[];
- breakpoints: [Breakpoint["id"], Breakpoint][];
- styles: [StyleDeclKey, StyleDecl][];
- styleSourceSelections: [Instance["id"], StyleSourceSelection][];
+export type CssConfig = {
+ assets: Assets;
+ breakpoints: Breakpoints;
+ styles: Styles;
+ styleSourceSelections: StyleSourceSelections;
componentMetas: Map<string, WsComponentMeta>;
-};
-
-type CssOptions = {
assetBaseUrl: string;
atomic: boolean;
};
@@ -56,14 +50,15 @@ export const createImageValueTransformer =
}
};
-export const generateCss = (
- data: Data,
- { assetBaseUrl, atomic = false }: CssOptions
-) => {
- const assets: Assets = new Map(data.assets.map((asset) => [asset.id, asset]));
- const breakpoints = new Map(data.breakpoints);
- const styles = new Map(data.styles);
- const styleSourceSelections = new Map(data.styleSourceSelections);
+export const generateCss = ({
+ assets,
+ breakpoints,
+ styles,
+ styleSourceSelections,
+ componentMetas,
+ assetBaseUrl,
+ atomic,
+}: CssConfig) => {
const classesMap = new Map<string, Array<string>>();
const regularSheet = createRegularStyleSheet({ name: "ssr-regular" });
@@ -77,7 +72,7 @@ export const generateCss = (
(atomicSheet ?? regularSheet).addMediaRule(breakpoint.id, breakpoint);
}
- for (const [component, meta] of data.componentMetas) {
+ for (const [component, meta] of componentMetas) {
const presetStyle = meta.presetStyle;
if (presetStyle === undefined) {
continue;
diff --git a/packages/sdk-cli/src/generate-stories.ts b/packages/sdk-cli/src/generate-stories.ts
index 27173d2519..3368d90c0a 100644
--- a/packages/sdk-cli/src/generate-stories.ts
+++ b/packages/sdk-cli/src/generate-stories.ts
@@ -145,21 +145,19 @@ export const generateStories = async () => {
usedMetas.set(instance.component, meta);
}
}
- const { cssText, classesMap } = generateCss(
- {
- assets: [],
- breakpoints: [
- [baseBreakpointId, { id: baseBreakpointId, label: "base" }],
- ],
- styles: data.styles.map((item) => [getStyleDeclKey(item), item]),
- styleSourceSelections: data.styleSourceSelections.map((item) => [
- item.instanceId,
- item,
- ]),
- componentMetas: usedMetas,
- },
- { assetBaseUrl: "/", atomic: true }
- );
+ const { cssText, classesMap } = generateCss({
+ assets: new Map(),
+ breakpoints: new Map([
+ [baseBreakpointId, { id: baseBreakpointId, label: "base" }],
+ ]),
+ styles: new Map(data.styles.map((item) => [getStyleDeclKey(item), item])),
+ styleSourceSelections: new Map(
+ data.styleSourceSelections.map((item) => [item.instanceId, item])
+ ),
+ componentMetas: usedMetas,
+ assetBaseUrl: "/",
+ atomic: true,
+ });
const scope = createScope(["Component", "Story", "props", "useState"]);
let content = "";
content += getStoriesImports({