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.

css-engine wip

Oleg Isonenc4273162918c
diff --git a/packages/css-engine/package.json b/packages/css-engine/package.json
index 2df5dfc844..4808a26dfa 100644
--- a/packages/css-engine/package.json
+++ b/packages/css-engine/package.json
@@ -15,7 +15,8 @@
"storybook:build": "build-storybook"
},
"dependencies": {
- "@webstudio-is/react-sdk": "*"
+ "@webstudio-is/react-sdk": "*",
+ "hyphenate-style-name": "^1.0.4"
},
"devDependencies": {
"@storybook/addon-actions": "^6.5.6",
diff --git a/packages/css-engine/src/css-engine.stories.tsx b/packages/css-engine/src/css-engine.stories.tsx
index 97de4faf5f..0a5eb8985c 100644
--- a/packages/css-engine/src/css-engine.stories.tsx
+++ b/packages/css-engine/src/css-engine.stories.tsx
@@ -14,10 +14,35 @@ const breakpoint0 = { minWidth: 0, id: "0", label: "0" } as const;
export const Basic = () => {
const engine = new CssEngine();
engine.addBreakpoint(breakpoint0);
- const rule = engine.addRule({
+ const rule = engine.addRule(".test", {
style: style0,
breakpoint: "0",
});
engine.render();
- return <div className={rule.className}>Should be red</div>;
+ return (
+ <>
+ <div className="test">Should be red</div>
+ <button
+ onClick={() => {
+ rule.styleMap.set("color", { type: "keyword", value: "green" });
+ engine.render();
+ }}
+ >
+ Make it green
+ </button>
+ <button
+ onClick={() => {
+ engine.addRule(".test", {
+ style: {
+ background: { type: "keyword", value: "yellow" },
+ },
+ breakpoint: "0",
+ });
+ engine.render();
+ }}
+ >
+ Add rule with yellow background
+ </button>
+ </>
+ );
};
diff --git a/packages/css-engine/src/css-engine.test.ts b/packages/css-engine/src/css-engine.test.ts
index c49b29d663..870b51ab07 100644
--- a/packages/css-engine/src/css-engine.test.ts
+++ b/packages/css-engine/src/css-engine.test.ts
@@ -15,7 +15,7 @@ describe("CssEngine", () => {
test("throw when breakpoint is not registered", () => {
expect(() => {
- engine.addRule({
+ engine.addRule(".c", {
style: style0,
breakpoint: "0",
});
@@ -24,7 +24,7 @@ describe("CssEngine", () => {
test("rule with multiple properties", () => {
engine.addBreakpoint(breakpoint0);
- engine.addRule({
+ engine.addRule(".c", {
style: {
...style0,
color: { type: "keyword", value: "red" },
@@ -33,14 +33,29 @@ describe("CssEngine", () => {
});
expect(engine.cssText).toMatchInlineSnapshot(`
"@media (min-width: 0px) {
- .c0 { display: block; color: red }
+ .c { display: block; color: red }
}"
`);
});
- test("add one rule", () => {
+ test("hyphenate property", () => {
engine.addBreakpoint(breakpoint0);
- const rule = engine.addRule({
+ engine.addRule(".c", {
+ style: {
+ backgroundColor: { type: "keyword", value: "red" },
+ },
+ breakpoint: "0",
+ });
+ expect(engine.cssText).toMatchInlineSnapshot(`
+ "@media (min-width: 0px) {
+ .c { background-color: red }
+ }"
+ `);
+ });
+
+ test("add rule", () => {
+ engine.addBreakpoint(breakpoint0);
+ const rule1 = engine.addRule(".c", {
style: {
...style0,
color: { type: "keyword", value: "red" },
@@ -49,31 +64,73 @@ describe("CssEngine", () => {
});
expect(engine.cssText).toMatchInlineSnapshot(`
"@media (min-width: 0px) {
- .c0 { display: block; color: red }
+ .c { display: block; color: red }
}"
`);
- expect(rule.cssText).toMatchInlineSnapshot(
- `".c0 { display: block; color: red }"`
+ expect(rule1.cssText).toMatchInlineSnapshot(
+ `".c { display: block; color: red }"`
);
+ engine.addRule(".c2", {
+ style: {
+ ...style0,
+ color: { type: "keyword", value: "green" },
+ },
+ breakpoint: "0",
+ });
+ expect(engine.cssText).toMatchInlineSnapshot(`
+ "@media (min-width: 0px) {
+ .c { display: block; color: red }
+ .c2 { display: block; color: green }
+ }"
+ `);
});
- test("multiple breakpoints", () => {
+ test("update rule", () => {
engine.addBreakpoint(breakpoint0);
- engine.addBreakpoint({ minWidth: 100, id: "1", label: "1" });
- engine.addRule({
- style: style0,
+ const rule = engine.addRule(".c", {
+ style: {
+ ...style0,
+ color: { type: "keyword", value: "red" },
+ },
breakpoint: "0",
});
- engine.addRule({
+ expect(engine.cssText).toMatchInlineSnapshot(`
+ "@media (min-width: 0px) {
+ .c { display: block; color: red }
+ }"
+ `);
+ expect(rule.cssText).toMatchInlineSnapshot(
+ `".c { display: block; color: red }"`
+ );
+
+ rule.styleMap.set("color", { type: "keyword", value: "green" });
+
+ expect(rule.cssText).toMatchInlineSnapshot(
+ `".c { display: block; color: green }"`
+ );
+
+ expect(engine.cssText).toMatchInlineSnapshot(`
+ "@media (min-width: 0px) {
+ .c { display: block; color: green }
+ }"
+ `);
+ });
+
+ test("don't override breakpoints", () => {
+ engine.addBreakpoint(breakpoint0);
+ engine.addRule(".c", {
style: style0,
- breakpoint: "1",
+ breakpoint: "0",
});
expect(engine.cssText).toMatchInlineSnapshot(`
"@media (min-width: 0px) {
- .c0 { display: block }
- }
- @media (min-width: 100px) {
- .c1 { display: block }
+ .c { display: block }
+ }"
+ `);
+ engine.addBreakpoint(breakpoint0);
+ expect(engine.cssText).toMatchInlineSnapshot(`
+ "@media (min-width: 0px) {
+ .c { display: block }
}"
`);
});
diff --git a/packages/css-engine/src/css-engine.ts b/packages/css-engine/src/css-engine.ts
index 0e3dd3fafd..697c7b2a51 100644
--- a/packages/css-engine/src/css-engine.ts
+++ b/packages/css-engine/src/css-engine.ts
@@ -1,36 +1,57 @@
import { Breakpoint, CssRule } from "@webstudio-is/react-sdk";
import { MediaRule, StyleRule } from "./rules";
+import { StyleElement } from "./style-element";
import { StyleSheet } from "./style-sheet";
export class CssEngine {
- rulesCounter = -1;
- mediaRules: Map<Breakpoint["id"], MediaRule> = new Map();
- sheet: StyleSheet;
+ #element;
+ #mediaRules: Map<Breakpoint["id"], MediaRule> = new Map();
+ #sheet: StyleSheet;
+ #isDirty = false;
+ #cssText = "";
constructor() {
- this.sheet = new StyleSheet();
+ this.#element = new StyleElement();
+ this.#sheet = new StyleSheet(this.#element);
}
addBreakpoint(breakpoint: Breakpoint) {
- const mediaRule = new MediaRule(breakpoint);
- this.mediaRules.set(breakpoint.id, mediaRule);
+ let mediaRule = this.#mediaRules.get(breakpoint.id);
+ if (mediaRule === undefined) {
+ mediaRule = new MediaRule(breakpoint);
+ this.#mediaRules.set(breakpoint.id, mediaRule);
+ this.#isDirty = true;
+ }
+ return mediaRule;
}
- addRule(rule: CssRule) {
- const mediaRule = this.mediaRules.get(rule.breakpoint);
+ addRule(selectorText: string, rule: CssRule) {
+ const mediaRule = this.#mediaRules.get(rule.breakpoint);
if (mediaRule === undefined) {
throw new Error(`Unknown breakpoint: ${rule.breakpoint}`);
}
- const styleRule = new StyleRule(rule.style, ++this.rulesCounter);
+ this.#isDirty = true;
+ const styleRule = new StyleRule(selectorText, rule.style);
+ styleRule.onChange = this.#onChangeRule;
return mediaRule.insertRule(styleRule);
}
render() {
- this.sheet.mount();
- this.sheet.replaceSync(this.cssText);
+ this.#element.mount();
+ // This isn't going to do anything if the `cssText` hasn't changed.
+ this.#sheet.replaceSync(this.cssText);
}
get cssText() {
+ if (this.#isDirty === false) {
+ return this.#cssText;
+ }
+ this.#isDirty = false;
const css: Array<string> = [];
- for (const mediaRule of this.mediaRules.values()) {
+ for (const mediaRule of this.#mediaRules.values()) {
const { cssText } = mediaRule;
if (cssText !== "") css.push(cssText);
}
- return css.join("\n");
+ this.#cssText = css.join("\n");
+ return this.#cssText;
}
+
+ #onChangeRule = () => {
+ this.#isDirty = true;
+ };
}
diff --git a/packages/css-engine/src/index.ts b/packages/css-engine/src/index.ts
index 867abe6a5d..1639686447 100644
--- a/packages/css-engine/src/index.ts
+++ b/packages/css-engine/src/index.ts
@@ -1 +1,2 @@
export { CssEngine } from "./css-engine";
+export type { AnyRule, StyleRule, MediaRule } from "./rules";
diff --git a/packages/css-engine/src/rules.ts b/packages/css-engine/src/rules.ts
index 88d9527b36..488d8850ab 100644
--- a/packages/css-engine/src/rules.ts
+++ b/packages/css-engine/src/rules.ts
@@ -1,45 +1,77 @@
-import { Breakpoint, Style, toValue } from "@webstudio-is/react-sdk";
+import {
+ Breakpoint,
+ Style,
+ toValue,
+ StyleProperty,
+ StyleValue,
+} from "@webstudio-is/react-sdk";
+import hyphenate from "hyphenate-style-name";
-export class StyleRule {
- id = -1;
- style: Style;
- // @todo name can be composition token name or component name
- name = "c";
- get className() {
- return `${this.name}${this.id}`;
- }
- constructor(style: Style, id: number) {
- this.style = style;
- this.id = id;
+class StylePropertyMap {
+ #styleMap: Map<StyleProperty, StyleValue | undefined> = new Map();
+ #isDirty = false;
+ #string = "";
+ onChange?: () => void;
+ set(property: StyleProperty, value?: StyleValue) {
+ this.#styleMap.set(property, value);
+ this.#isDirty = true;
+ this.onChange?.();
}
- get cssText() {
+ toString() {
+ if (this.#isDirty === false) {
+ return this.#string;
+ }
const block: Array<string> = [];
- let property: keyof Style;
- for (property in this.style) {
- const value = this.style[property];
+ for (const [property, value] of this.#styleMap) {
if (value === undefined) continue;
- block.push(`${property}: ${toValue(value)}`);
+ block.push(`${hyphenate(property)}: ${toValue(value)}`);
+ }
+ this.#string = block.join("; ");
+ this.#isDirty = false;
+ return this.#string;
+ }
+}
+
+export class StyleRule {
+ styleMap;
+ selectorText;
+ onChange?: () => void;
+ constructor(selectorText: string, style: Style) {
+ this.styleMap = new StylePropertyMap();
+ this.selectorText = selectorText;
+ let property: StyleProperty;
+ for (property in style) {
+ this.styleMap.set(property, style[property]);
}
- return `.${this.className} { ${block.join("; ")} }`;
+ this.styleMap.onChange = this.#onChange;
+ }
+ #onChange = () => {
+ this.onChange?.();
+ };
+ get cssText() {
+ return `${this.selectorText} { ${this.styleMap} }`;
}
}
export class MediaRule {
- #id = "";
#breakpoint: Breakpoint;
rules: Array<StyleRule> = [];
constructor(breakpoint: Breakpoint) {
this.#breakpoint = breakpoint;
- this.#id = breakpoint.id;
}
insertRule(rule: StyleRule) {
this.rules.push(rule);
return rule;
}
get cssText() {
- const rules = this.rules.map((rule) => ` ${rule.cssText}`).join("\n");
- return `@media (min-width: ${this.#breakpoint.minWidth}px) {\n${rules}\n}`;
+ const rules = [];
+ for (const rule of this.rules) {
+ rules.push(` ${rule.cssText}`);
+ }
+ return `@media (min-width: ${this.#breakpoint.minWidth}px) {\n${rules.join(
+ "\n"
+ )}\n}`;
}
}
-export type Rule = StyleRule | MediaRule;
+export type AnyRule = StyleRule | MediaRule;
diff --git a/packages/css-engine/src/style-element.ts b/packages/css-engine/src/style-element.ts
new file mode 100644
index 0000000000..db100e58e7
--- /dev/null
+++ b/packages/css-engine/src/style-element.ts
@@ -0,0 +1,24 @@
+export class StyleElement {
+ #element?: HTMLStyleElement;
+ get isMounted() {
+ return this.#element?.parentElement != null;
+ }
+ mount() {
+ if (this.isMounted === false) {
+ this.#element = document.createElement("style");
+ this.#element.setAttribute("data-webstudio", "");
+ document.head.appendChild(this.#element);
+ }
+ }
+ unmount() {
+ if (this.isMounted) {
+ this.#element?.parentElement?.removeChild(this.#element);
+ this.#element = undefined;
+ }
+ }
+ render(cssText: string) {
+ if (this.#element) {
+ this.#element.textContent = cssText;
+ }
+ }
+}
diff --git a/packages/css-engine/src/style-sheet.ts b/packages/css-engine/src/style-sheet.ts
index 3dd834ad3a..74c1eb5e5b 100644
--- a/packages/css-engine/src/style-sheet.ts
+++ b/packages/css-engine/src/style-sheet.ts
@@ -1,21 +1,15 @@
+import { StyleElement } from "./style-element";
+
export class StyleSheet {
- #style?: HTMLStyleElement;
- mount() {
- //if (typeof document === "object" && "adoptedStyleSheets" in document) {
- // // @ts-expect-error TS2339: Property 'adoptedStyleSheets' does not exist on type 'Document'.
- // document.adoptedStyleSheets = [this.sheet];
- // return;
- //}
- if (this.#style === undefined) {
- this.#style = document.createElement("style");
- this.#style.setAttribute("data-webstudio", "");
- document.head.appendChild(this.#style);
- }
+ #cssText = "";
+ #element;
+ constructor(element: StyleElement) {
+ this.#element = element;
}
replaceSync(cssText: string) {
- if (this.#style === undefined) {
- throw new Error("StyleSheet not mounted");
+ if (cssText !== this.#cssText) {
+ this.#cssText = cssText;
+ this.#element.render(cssText);
}
- this.#style.textContent = cssText;
}
}