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
refactor: add nesting rule to css engine (#3227)
Bogdan Chadkin0cdcfc562cd6
diff --git a/packages/css-engine/src/core/rules.ts b/packages/css-engine/src/core/rules.tsindex a5f3ff1b1b..a804f3fddd 100644--- a/packages/css-engine/src/core/rules.ts+++ b/packages/css-engine/src/core/rules.ts@@ -2,6 +2,107 @@ import type { Style, StyleProperty, StyleValue } from "../schema";import { toValue, type TransformValue } from "./to-value";import { toProperty } from "./to-property";+type Declaration = {+ breakpoint: string;+ selector: string;+ property: StyleProperty;+ value: StyleValue;+};++type DeclarationKey = Omit<Declaration, "value">;++const getDeclarationKey = (declaraionKey: DeclarationKey) => {+ const { breakpoint, selector, property } = declaraionKey;+ return `${breakpoint}:${selector}:${property}`;+};++/**+ * Universal style rule with nested selectors and media queries support+ * Rules are generated by each media query+ * and heavily cached to avoid complex computation+ *+ * selector {+ * \@media breakpoint {+ * &selector {+ * property: value+ * }+ * }+ * }+ */+export class NestingRule {+ #selector: string;+ // use map to avoid duplicated properties+ #declarations = new Map<string, Declaration>();+ // cached generated rule by breakpoint+ #cache = new Map<+ string,+ { generated: string; indent: number; transformValue?: TransformValue }+ >();+ constructor(selector: string) {+ this.#selector = selector;+ }+ getSelector() {+ return this.#selector;+ }+ setDeclaration(declaration: Declaration) {+ this.#declarations.set(getDeclarationKey(declaration), declaration);+ this.#cache.delete(declaration.breakpoint);+ }+ deleteDeclaration(declaration: DeclarationKey) {+ this.#declarations.delete(getDeclarationKey(declaration));+ this.#cache.delete(declaration.breakpoint);+ }+ getDeclarations() {+ return this.#declarations.values();+ }+ generateRules({+ breakpoint,+ indent = 0,+ transformValue,+ }: {+ breakpoint: string;+ indent?: number;+ transformValue?: TransformValue;+ }) {+ const cached = this.#cache.get(breakpoint);+ // invalidate cache when indent and value transformer are changed+ if (+ cached &&+ cached.indent === indent &&+ cached.transformValue === transformValue+ ) {+ return cached.generated;+ }+ const spaces = " ".repeat(indent);+ const linesBySelector = new Map<string, string>();+ for (const declaration of this.#declarations.values()) {+ // generate declarations only for specified breakpoint+ if (declaration.breakpoint !== breakpoint) {+ continue;+ }+ const { selector: nestedSelector, property, value } = declaration;+ const selector = `${this.#selector}${nestedSelector}`;+ const lines = linesBySelector.get(selector) ?? "";+ const propertyString = toProperty(property);+ const valueString = toValue(value, transformValue);+ const line = `${spaces} ${propertyString}: ${valueString}`;+ linesBySelector.set(selector, lines === "" ? line : `${lines};\n${line}`);+ }+ // sort by selector to put values without nested selector first+ const generated = Array.from(linesBySelector)+ .sort(([leftSelector], [rightSelector]) =>+ leftSelector.localeCompare(rightSelector)+ )+ .map(+ ([selector, lines]) => `${spaces}${selector} {\n${lines}\n${spaces}}\n`+ )+ .join("")+ .trimEnd();+ this.#cache.set(breakpoint, { generated, indent, transformValue });+ return generated;+ }+}+export class StylePropertyMap {#styleMap: Map<StyleProperty, StyleValue | undefined> = new Map();#isDirty = true;@@ -108,17 +209,19 @@ export type MediaRuleOptions = {};export class MediaRule {+ #name: string;options: MediaRuleOptions;rules: Map<string, StyleRule | PlaintextRule>;#mediaType;- constructor(options: MediaRuleOptions = {}) {+ constructor(name: string, options: MediaRuleOptions = {}) {+ this.#name = name;this.options = options;this.rules = new Map();this.#mediaType = options.mediaType ?? "all";}insertRule(rule: StyleRule | PlaintextRule) {this.rules.set(- "selectorText" in rule ? rule.selectorText : rule.cssText,+ rule instanceof StyleRule ? rule.selectorText : rule.cssText,rule);return rule;@@ -127,13 +230,32 @@ export class MediaRule {return this.toString();}toString() {- if (this.rules.size === 0) {+ return this.generateRule({ nestingRules: [] });+ }+ generateRule({+ nestingRules,+ transformValue,+ }: {+ nestingRules: NestingRule[];+ transformValue?: TransformValue;+ }) {+ if (this.rules.size === 0 && nestingRules.length === 0) {return "";}const rules = [];for (const rule of this.rules.values()) {rules.push(rule.toString({ indent: 2 }));}+ for (const rule of nestingRules) {+ const generatedRule = rule.generateRules({+ breakpoint: this.#name,+ indent: 2,+ transformValue,+ });+ if (generatedRule !== "") {+ rules.push(generatedRule);+ }+ }let conditionText = "";const { minWidth, maxWidth } = this.options;if (minWidth !== undefined) {diff --git a/packages/css-engine/src/core/style-sheet-regular.test.ts b/packages/css-engine/src/core/style-sheet-regular.test.tsindex 5b6a522160..bd4102adb7 100644--- a/packages/css-engine/src/core/style-sheet-regular.test.ts+++ b/packages/css-engine/src/core/style-sheet-regular.test.ts@@ -1,6 +1,7 @@import { describe, beforeEach, test, expect } from "@jest/globals";import type { StyleSheetRegular } from "./style-sheet-regular";import { createRegularStyleSheet } from "./create-style-sheet";+import type { TransformValue } from "./to-value";const style0 = {display: { type: "keyword", value: "block" },@@ -21,6 +22,203 @@ const style2 = {const mediaRuleOptions1 = { minWidth: 300 } as const;const mediaId1 = "1";+describe("nesting rule", () => {+ const transformValue: TransformValue = (styleValue) => {+ if (styleValue.type === "keyword") {+ return {+ type: "keyword",+ value: styleValue.value.toUpperCase(),+ };+ }+ };++ test("generate rules for breakpoint", () => {+ const sheet = createRegularStyleSheet();+ const rule = sheet.addNestingRule(".instance");+ rule.setDeclaration({+ breakpoint: "base",+ selector: "",+ property: "width",+ value: { type: "keyword", value: "auto" },+ });+ rule.setDeclaration({+ breakpoint: "base",+ selector: "",+ property: "height",+ value: { type: "keyword", value: "auto" },+ });+ rule.setDeclaration({+ breakpoint: "small",+ selector: "",+ property: "color",+ value: { type: "keyword", value: "transparent" },+ });+ expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`+".instance {+ width: auto;+ height: auto+}"+`);+ expect(rule.generateRules({ breakpoint: "small" })).toMatchInlineSnapshot(`+".instance {+ color: transparent+}"+`);+ });++ test("generated nested rules", () => {+ const sheet = createRegularStyleSheet();+ const rule = sheet.addNestingRule(".instance");+ rule.setDeclaration({+ breakpoint: "base",+ selector: "",+ property: "width",+ value: { type: "keyword", value: "auto" },+ });+ rule.setDeclaration({+ breakpoint: "base",+ selector: "",+ property: "height",+ value: { type: "keyword", value: "auto" },+ });+ rule.setDeclaration({+ breakpoint: "base",+ selector: ":hover",+ property: "color",+ value: { type: "keyword", value: "transparent" },+ });+ expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`+".instance {+ width: auto;+ height: auto+}+.instance:hover {+ color: transparent+}"+`);+ });++ test("sort nested rules without state first", () => {+ const sheet = createRegularStyleSheet();+ const rule = sheet.addNestingRule(".instance");+ rule.setDeclaration({+ breakpoint: "base",+ selector: ":hover",+ property: "color",+ value: { type: "keyword", value: "transparent" },+ });+ rule.setDeclaration({+ breakpoint: "base",+ selector: "",+ property: "width",+ value: { type: "keyword", value: "auto" },+ });+ expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`+".instance {+ width: auto+}+.instance:hover {+ color: transparent+}"+`);+ });++ test("customize indentation", () => {+ const sheet = createRegularStyleSheet();+ const rule = sheet.addNestingRule(".instance");+ rule.setDeclaration({+ breakpoint: "base",+ selector: "",+ property: "width",+ value: { type: "keyword", value: "auto" },+ });+ expect(rule.generateRules({ breakpoint: "base", indent: 4 }))+ .toMatchInlineSnapshot(`+" .instance {+ width: auto+ }"+`);+ });++ test("customize value transformer", () => {+ const sheet = createRegularStyleSheet();+ const rule = sheet.addNestingRule(".instance");+ rule.setDeclaration({+ breakpoint: "base",+ selector: "",+ property: "width",+ value: { type: "keyword", value: "auto" },+ });+ expect(rule.generateRules({ breakpoint: "base", transformValue }))+ .toMatchInlineSnapshot(`+".instance {+ width: AUTO+}"+`);+ });++ test("invalidate cache", () => {+ const sheet = createRegularStyleSheet();+ const rule = sheet.addNestingRule(".instance");+ rule.setDeclaration({+ breakpoint: "base",+ selector: "",+ property: "width",+ value: { type: "keyword", value: "auto" },+ });+ expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`+".instance {+ width: auto+}"+`);+ // invalidate by set declaration+ rule.setDeclaration({+ breakpoint: "base",+ selector: "",+ property: "height",+ value: { type: "keyword", value: "auto" },+ });+ expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`+".instance {+ width: auto;+ height: auto+}"+`);+ // invalidate by delete declaration+ rule.deleteDeclaration({+ breakpoint: "base",+ selector: "",+ property: "height",+ });+ expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`+".instance {+ width: auto+}"+`);+ // invalidate by indent+ expect(rule.generateRules({ breakpoint: "base", indent: 2 }))+ .toMatchInlineSnapshot(`+" .instance {+ width: auto+ }"+`);+ // invalidate by transform value+ expect(+ rule.generateRules({ breakpoint: "base", indent: 2, transformValue })+ ).toMatchInlineSnapshot(`+" .instance {+ width: AUTO+ }"+`);+ });++ test("generate breakpoint without declarations", () => {+ const sheet = createRegularStyleSheet();+ const rule = sheet.addNestingRule(".instance");+ expect(rule.generateRules({ breakpoint: "base" })).toEqual("");+ });+});+describe("Style Sheet Regular", () => {let sheet: StyleSheetRegular;@@ -555,4 +753,35 @@ describe("Style Sheet Regular", () => {}"`);});++ test("render nesting rules", () => {+ const sheet = createRegularStyleSheet();+ sheet.addMediaRule("base", {});+ sheet.addMediaRule("small", { minWidth: 768 });+ const rule = sheet.addNestingRule(".instance");+ rule.setDeclaration({+ breakpoint: "small",+ selector: "",+ property: "color",+ value: { type: "keyword", value: "blue" },+ });+ rule.setDeclaration({+ breakpoint: "base",+ selector: "",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ 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.tsindex 5f9439e887..71bba2b781 100644--- a/packages/css-engine/src/core/style-sheet.ts+++ b/packages/css-engine/src/core/style-sheet.ts@@ -2,12 +2,14 @@ import type { Style } from "../schema";import {FontFaceRule,MediaRule,+ NestingRule,PlaintextRule,type FontFaceOptions,type MediaRuleOptions,} from "./rules";import { compareMedia } from "./compare-media";import { StyleElement } from "./style-element";+import type { TransformValue } from "./to-value";export type CssRule = {style: Style;@@ -18,16 +20,22 @@ export class StyleSheet {#cssText = "";#mediaRules: Map<string, MediaRule> = new Map();#plainRules: Map<string, PlaintextRule> = new Map();+ #nestingRules: Map<string, NestingRule> = new Map();#fontFaceRules: Array<FontFaceRule> = [];+ #transformValue?: TransformValue;#isDirty = false;#element: StyleElement;constructor(element: StyleElement) {this.#element = element;}+ setTransformer(transformValue: TransformValue) {+ this.#transformValue = transformValue;+ this.#isDirty = true;+ }addMediaRule(id: string, options?: MediaRuleOptions) {let mediaRule = this.#mediaRules.get(id);if (mediaRule === undefined) {- mediaRule = new MediaRule(options);+ mediaRule = new MediaRule(id, options);this.#mediaRules.set(id, mediaRule);this.#isDirty = true;return mediaRule;@@ -53,6 +61,15 @@ export class StyleSheet {this.#isDirty = true;return this.#plainRules.set(cssText, new PlaintextRule(cssText));}+ addNestingRule(selector: string) {+ let rule = this.#nestingRules.get(selector);+ if (rule === undefined) {+ rule = new NestingRule(selector);+ this.#nestingRules.set(selector, rule);+ this.#isDirty = true;+ }+ return rule;+ }addFontFaceRule(options: FontFaceOptions) {this.#isDirty = true;return this.#fontFaceRules.push(new FontFaceRule(options));@@ -76,7 +93,10 @@ export class StyleSheet {(ruleA, ruleB) => compareMedia(ruleA.options, ruleB.options));for (const mediaRule of sortedMediaRules) {- const { cssText } = mediaRule;+ const cssText = mediaRule.generateRule({+ nestingRules: Array.from(this.#nestingRules.values()),+ transformValue: this.#transformValue,+ });if (cssText !== "") {css.push(cssText);}diff --git a/packages/react-sdk/src/css/css.ts b/packages/react-sdk/src/css/css.tsindex cca66521df..b85ab433a6 100644--- a/packages/react-sdk/src/css/css.ts+++ b/packages/react-sdk/src/css/css.ts@@ -6,6 +6,8 @@ import {import type {Assets,Breakpoints,+ StyleDecl,+ StyleSource,StyleSourceSelections,Styles,} from "@webstudio-is/sdk";@@ -88,9 +90,11 @@ export const generateCss = ({const imageValueTransformer = createImageValueTransformer(assets, {assetBaseUrl,});+ regularSheet.setTransformer(imageValueTransformer);+ atomicSheet?.setTransformer(imageValueTransformer);- for (const { breakpointId, instanceId, state, style } of styleRules) {- if (atomicSheet) {+ if (atomicSheet) {+ for (const { breakpointId, instanceId, state, style } of styleRules) {const { classes } = atomicSheet.addStyleRule({ breakpoint: breakpointId, style },state,@@ -100,17 +104,48 @@ export const generateCss = ({...(classesMap.get(instanceId) ?? []),...classes,]);- continue;}- regularSheet.addStyleRule(- { breakpoint: breakpointId, style },- `[${idAttribute}="${instanceId}"]${state ?? ""}`,- imageValueTransformer++ return {+ cssText: regularSheet.cssText + (atomicSheet?.cssText ?? ""),+ classesMap,+ };+ }++ // @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);+ }++ 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,+ });+ }+ }}return {- cssText: regularSheet.cssText + (atomicSheet?.cssText ?? ""),+ cssText: regularSheet.cssText,classesMap,};};