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: add mixin rule to css engine (#3233)

Bogdan Chadkin20a2a1ec5596
diff --git a/packages/css-engine/src/core/rules.ts b/packages/css-engine/src/core/rules.ts
index a804f3fddd..5ba661b2ac 100644
--- a/packages/css-engine/src/core/rules.ts
+++ b/packages/css-engine/src/core/rules.ts
@@ -16,6 +16,46 @@ const getDeclarationKey = (declaraionKey: DeclarationKey) => {
return `${breakpoint}:${selector}:${property}`;
};
+/**
+ * Reusable style rule in any nesting rule
+ *
+ * @mixin name {
+ * \@media breakpoint {
+ * &selector {
+ * property: value
+ * }
+ * }
+ * }
+ */
+export class MixinRule {
+ // use map to avoid duplicated properties
+ #declarations = new Map<string, Declaration>();
+ #dirtyBreakpoints = new Set<string>();
+ /*
+ * check if breakpoint was updated
+ */
+ isDirtyBreakpoint(breakpoint: string) {
+ return this.#dirtyBreakpoints.has(breakpoint);
+ }
+ /**
+ * reset breakpoints invalidation
+ */
+ clearBreakpoints() {
+ this.#dirtyBreakpoints.clear();
+ }
+ setDeclaration(declaration: Declaration) {
+ this.#declarations.set(getDeclarationKey(declaration), declaration);
+ this.#dirtyBreakpoints.add(declaration.breakpoint);
+ }
+ deleteDeclaration(declaration: DeclarationKey) {
+ this.#declarations.delete(getDeclarationKey(declaration));
+ this.#dirtyBreakpoints.add(declaration.breakpoint);
+ }
+ getDeclarations() {
+ return this.#declarations.values();
+ }
+}
+
/**
* Universal style rule with nested selectors and media queries support
* Rules are generated by each media query
@@ -31,6 +71,8 @@ const getDeclarationKey = (declaraionKey: DeclarationKey) => {
*/
export class NestingRule {
#selector: string;
+ #mixinRules = new Map<string, MixinRule>();
+ #mixins: string[] = [];
// use map to avoid duplicated properties
#declarations = new Map<string, Declaration>();
// cached generated rule by breakpoint
@@ -38,12 +80,17 @@ export class NestingRule {
string,
{ generated: string; indent: number; transformValue?: TransformValue }
>();
- constructor(selector: string) {
+ constructor(selector: string, mixinRules: Map<string, MixinRule>) {
this.#selector = selector;
+ this.#mixinRules = mixinRules;
}
getSelector() {
return this.#selector;
}
+ applyMixins(mixins: string[]) {
+ this.#mixins = mixins;
+ this.#cache.clear();
+ }
setDeclaration(declaration: Declaration) {
this.#declarations.set(getDeclarationKey(declaration), declaration);
this.#cache.delete(declaration.breakpoint);
@@ -52,9 +99,6 @@ export class NestingRule {
this.#declarations.delete(getDeclarationKey(declaration));
this.#cache.delete(declaration.breakpoint);
}
- getDeclarations() {
- return this.#declarations.values();
- }
generateRules({
breakpoint,
indent = 0,
@@ -64,6 +108,18 @@ export class NestingRule {
indent?: number;
transformValue?: TransformValue;
}) {
+ const mixinRules: MixinRule[] = [];
+ for (const mixin of this.#mixins) {
+ const rule = this.#mixinRules.get(mixin);
+ // invalidate cache when mixin is changed
+ if (rule?.isDirtyBreakpoint(breakpoint)) {
+ this.#cache.delete(breakpoint);
+ }
+ if (rule) {
+ mixinRules.push(rule);
+ }
+ }
+
const cached = this.#cache.get(breakpoint);
// invalidate cache when indent and value transformer are changed
if (
@@ -75,7 +131,17 @@ export class NestingRule {
}
const spaces = " ".repeat(indent);
const linesBySelector = new Map<string, string>();
+ // apply mixins first and then merge added declarations
+ const declarations = new Map<string, Declaration>();
+ for (const rule of mixinRules) {
+ for (const declaration of rule.getDeclarations()) {
+ declarations.set(getDeclarationKey(declaration), declaration);
+ }
+ }
for (const declaration of this.#declarations.values()) {
+ declarations.set(getDeclarationKey(declaration), declaration);
+ }
+ for (const declaration of declarations.values()) {
// generate declarations only for specified breakpoint
if (declaration.breakpoint !== breakpoint) {
continue;
diff --git a/packages/css-engine/src/core/style-sheet-regular.test.ts b/packages/css-engine/src/core/style-sheet-regular.test.ts
index bd4102adb7..5ae13d9455 100644
--- a/packages/css-engine/src/core/style-sheet-regular.test.ts
+++ b/packages/css-engine/src/core/style-sheet-regular.test.ts
@@ -219,6 +219,108 @@ describe("nesting rule", () => {
});
});
+describe("mixin rule", () => {
+ test("compose rules from multiple mixins", () => {
+ const sheet = createRegularStyleSheet();
+ const rule = sheet.addNestingRule(".instance");
+ const localMixin = sheet.addMixinRule("local");
+ const tokenMixin = sheet.addMixinRule("token");
+ rule.applyMixins(["token", "local"]);
+ localMixin.setDeclaration({
+ breakpoint: "base",
+ selector: "",
+ property: "width",
+ value: { type: "keyword", value: "fit-content" },
+ });
+ tokenMixin.setDeclaration({
+ breakpoint: "base",
+ selector: "",
+ property: "width",
+ value: { type: "keyword", value: "auto" },
+ });
+ tokenMixin.setDeclaration({
+ breakpoint: "base",
+ selector: "",
+ property: "height",
+ value: { type: "keyword", value: "auto" },
+ });
+ expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+".instance {
+ width: fit-content;
+ height: auto
+}"
+`);
+ });
+
+ test("generate nested selector", () => {
+ const sheet = createRegularStyleSheet();
+ const rule = sheet.addNestingRule(".instance");
+ const localMixin = sheet.addMixinRule("local");
+ const tokenMixin = sheet.addMixinRule("token");
+ rule.applyMixins(["token", "local"]);
+ localMixin.setDeclaration({
+ breakpoint: "base",
+ selector: ":hover",
+ property: "width",
+ value: { type: "keyword", value: "fit-content" },
+ });
+ tokenMixin.setDeclaration({
+ breakpoint: "base",
+ selector: ":hover",
+ property: "height",
+ value: { type: "keyword", value: "auto" },
+ });
+ expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+".instance:hover {
+ height: auto;
+ width: fit-content
+}"
+`);
+ });
+
+ test("invalidate cache after applying mixins", () => {
+ const sheet = createRegularStyleSheet();
+ const rule = sheet.addNestingRule(".instance");
+ const localMixin = sheet.addMixinRule("local");
+ localMixin.setDeclaration({
+ breakpoint: "base",
+ selector: "",
+ property: "width",
+ value: { type: "keyword", value: "auto" },
+ });
+ expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(
+ `""`
+ );
+ rule.applyMixins(["local"]);
+ expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+".instance {
+ width: auto
+}"
+`);
+ });
+
+ test("invalidate cache after updating mixin declaration", () => {
+ const sheet = createRegularStyleSheet();
+ const rule = sheet.addNestingRule(".instance");
+ const localMixin = sheet.addMixinRule("local");
+ rule.applyMixins(["local"]);
+ expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(
+ `""`
+ );
+ localMixin.setDeclaration({
+ breakpoint: "base",
+ selector: "",
+ property: "width",
+ value: { type: "keyword", value: "auto" },
+ });
+ expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+".instance {
+ width: auto
+}"
+`);
+ });
+});
+
describe("Style Sheet Regular", () => {
let sheet: StyleSheetRegular;
@@ -782,6 +884,39 @@ describe("Style Sheet Regular", () => {
color: blue
}
}"
+`);
+ });
+
+ test("render mixin rules", () => {
+ const sheet = createRegularStyleSheet();
+ sheet.addMediaRule("base", {});
+ sheet.addMediaRule("small", { minWidth: 768 });
+ const mixin = sheet.addMixinRule("local");
+ mixin.setDeclaration({
+ breakpoint: "small",
+ selector: "",
+ property: "color",
+ value: { type: "keyword", value: "blue" },
+ });
+ mixin.setDeclaration({
+ breakpoint: "base",
+ selector: "",
+ property: "color",
+ value: { type: "keyword", value: "red" },
+ });
+ const rule = sheet.addNestingRule(".instance");
+ rule.applyMixins(["local"]);
+ expect(sheet.cssText).toMatchInlineSnapshot(`
+"@media all {
+ .instance {
+ color: red
+ }
+}
+@media all and (min-width: 768px) {
+ .instance {
+ color: blue
+ }
+}"
`);
});
});
diff --git a/packages/css-engine/src/core/style-sheet.ts b/packages/css-engine/src/core/style-sheet.ts
index 71bba2b781..a14515f83b 100644
--- a/packages/css-engine/src/core/style-sheet.ts
+++ b/packages/css-engine/src/core/style-sheet.ts
@@ -2,6 +2,7 @@ import type { Style } from "../schema";
import {
FontFaceRule,
MediaRule,
+ MixinRule,
NestingRule,
PlaintextRule,
type FontFaceOptions,
@@ -20,6 +21,7 @@ export class StyleSheet {
#cssText = "";
#mediaRules: Map<string, MediaRule> = new Map();
#plainRules: Map<string, PlaintextRule> = new Map();
+ #mixinRules: Map<string, MixinRule> = new Map();
#nestingRules: Map<string, NestingRule> = new Map();
#fontFaceRules: Array<FontFaceRule> = [];
#transformValue?: TransformValue;
@@ -61,10 +63,19 @@ export class StyleSheet {
this.#isDirty = true;
return this.#plainRules.set(cssText, new PlaintextRule(cssText));
}
+ addMixinRule(name: string) {
+ let rule = this.#mixinRules.get(name);
+ if (rule === undefined) {
+ rule = new MixinRule();
+ this.#mixinRules.set(name, rule);
+ this.#isDirty = true;
+ }
+ return rule;
+ }
addNestingRule(selector: string) {
let rule = this.#nestingRules.get(selector);
if (rule === undefined) {
- rule = new NestingRule(selector);
+ rule = new NestingRule(selector, this.#mixinRules);
this.#nestingRules.set(selector, rule);
this.#isDirty = true;
}
@@ -101,6 +112,10 @@ export class StyleSheet {
css.push(cssText);
}
}
+ // reset invalidation from mixins after rendering
+ for (const rule of this.#mixinRules.values()) {
+ rule.clearBreakpoints();
+ }
this.#cssText = css.join("\n");
return this.#cssText;
}
diff --git a/packages/react-sdk/src/css/css.ts b/packages/react-sdk/src/css/css.ts
index b85ab433a6..d20bf6af58 100644
--- a/packages/react-sdk/src/css/css.ts
+++ b/packages/react-sdk/src/css/css.ts
@@ -6,8 +6,6 @@ import {
import type {
Assets,
Breakpoints,
- StyleDecl,
- StyleSource,
StyleSourceSelections,
Styles,
} from "@webstudio-is/sdk";
@@ -112,36 +110,21 @@ export const generateCss = ({
};
}
- // @todo write declarations into mixins instead of map
- const stylesByStyleSourceId = new Map<StyleSource["id"], StyleDecl[]>();
for (const styleDecl of styles.values()) {
- const { styleSourceId } = styleDecl;
- let styleSourceStyles = stylesByStyleSourceId.get(styleSourceId);
- if (styleSourceStyles === undefined) {
- styleSourceStyles = [];
- stylesByStyleSourceId.set(styleSourceId, styleSourceStyles);
- }
- styleSourceStyles.push(styleDecl);
+ const rule = regularSheet.addMixinRule(styleDecl.styleSourceId);
+ rule.setDeclaration({
+ breakpoint: styleDecl.breakpointId,
+ selector: styleDecl.state ?? "",
+ property: styleDecl.property,
+ value: styleDecl.value,
+ });
}
for (const { instanceId, values } of styleSourceSelections.values()) {
const rule = regularSheet.addNestingRule(
`[${idAttribute}="${instanceId}"]`
);
- for (const styleSourceId of values) {
- const styles = stylesByStyleSourceId.get(styleSourceId);
- if (styles === undefined) {
- continue;
- }
- for (const { breakpointId, state, property, value } of styles) {
- rule.setDeclaration({
- breakpoint: breakpointId,
- selector: state ?? "",
- property,
- value,
- });
- }
- }
+ rule.applyMixins(values);
}
return {