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: simplify stylesheet caching (#3275)

Bogdan Chadkin09491d7c0b56
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index b0ae6cf013..0b648da50c 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -117,7 +117,7 @@ const useElementsTree = (
};
const DesignMode = ({ params }: { params: Params }) => {
- useManageDesignModeStyles(params);
+ useManageDesignModeStyles();
useDragAndDrop();
// We need to initialize this in both canvas and builder,
// because the events will fire in either one, depending on where the focus is
diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts
index 1133960c6f..3e981ee615 100644
--- a/apps/builder/app/canvas/shared/styles.ts
+++ b/apps/builder/app/canvas/shared/styles.ts
@@ -1,7 +1,7 @@
import { useContext, useEffect, useLayoutEffect, useMemo } from "react";
import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
-import type { Assets, Instance, StyleDecl } from "@webstudio-is/sdk";
+import type { Instance, StyleDecl } from "@webstudio-is/sdk";
import {
collapsedAttribute,
idAttribute,
@@ -27,12 +27,11 @@ import {
} from "~/shared/nano-states";
import {
type StyleRule,
- type PlaintextRule,
createRegularStyleSheet,
toValue,
compareMedia,
} from "@webstudio-is/css-engine";
-import { $ephemeralStyles } from "../stores";
+import { $ephemeralStyles, $params } from "../stores";
import { resetInert, setInert } from "./inert";
const userSheet = createRegularStyleSheet({ name: "user-styles" });
@@ -114,7 +113,15 @@ const subscribePreviewMode = () => {
};
};
-const subscribeEphemeralStyle = (params: Params) => {
+// keep stable transformValue in store
+// to preserve cache in css engine
+const $transformValue = computed([$assets, $params], (assets, params) =>
+ createImageValueTransformer(assets, {
+ assetBaseUrl: params?.assetBaseUrl ?? "",
+ })
+);
+
+const subscribeEphemeralStyle = () => {
// track custom properties added on previous ephemeral styles change
const addedCustomProperties = new Set<string>();
@@ -128,10 +135,7 @@ const subscribeEphemeralStyle = (params: Params) => {
// track custom properties not set on this change
const deletedCustomProperties = new Set(addedCustomProperties);
- const assets = $assets.get();
- const transformer = createImageValueTransformer(assets, {
- assetBaseUrl: params.assetBaseUrl,
- });
+ const transformValue = $transformValue.get();
for (const styleDecl of ephemeralStyles) {
const {
@@ -148,7 +152,7 @@ const subscribeEphemeralStyle = (params: Params) => {
document.body.style.setProperty(
customProperty,
- toValue(value, transformer)
+ toValue(value, transformValue)
);
addedCustomProperties.add(customProperty);
deletedCustomProperties.delete(customProperty);
@@ -157,8 +161,6 @@ const subscribeEphemeralStyle = (params: Params) => {
instanceId,
breakpointId,
state,
- assets,
- params,
});
const propertyValue = rule.styleMap.get(property);
@@ -189,12 +191,13 @@ const subscribeEphemeralStyle = (params: Params) => {
}
// rerender style rules if new vars added
+ userSheet.setTransformer($transformValue.get());
userSheet.render();
});
};
-export const useManageDesignModeStyles = (params: Params) => {
- useEffect(() => subscribeEphemeralStyle(params), [params]);
+export const useManageDesignModeStyles = () => {
+ useEffect(() => subscribeEphemeralStyle(), []);
useEffect(subscribePreviewMode, []);
};
@@ -210,6 +213,7 @@ export const GlobalStyles = ({ params }: { params: Params }) => {
for (const breakpoint of sortedBreakpoints) {
userSheet.addMediaRule(breakpoint.id, breakpoint);
}
+ userSheet.setTransformer($transformValue.get());
userSheet.render();
}, [breakpoints]);
@@ -261,20 +265,16 @@ const toVarValue = (
}
};
-const wrappedRulesMap = new Map<string, StyleRule | PlaintextRule>();
+const wrappedRulesMap = new Map<string, StyleRule>();
const getOrCreateRule = ({
instanceId,
breakpointId,
state = "",
- assets,
- params,
}: {
instanceId: string;
breakpointId: string;
state: undefined | string;
- assets: Assets;
- params: Params;
}) => {
const key = `${instanceId}:${breakpointId}:${state}`;
let rule = wrappedRulesMap.get(key);
@@ -288,9 +288,6 @@ const getOrCreateRule = ({
);
wrappedRulesMap.set(key, rule);
}
- rule.styleMap.setTransformer(
- createImageValueTransformer(assets, { assetBaseUrl: params.assetBaseUrl })
- );
return rule;
};
@@ -322,15 +319,8 @@ export const useCssRules = ({
const selectedState = useSelectedState(instanceId);
useLayoutEffect(() => {
- // expect assets to be up to date by the time styles are changed
- // to avoid all styles rerendering when assets are changed
- const assets = $assets.get();
-
// find all instance rules and collect rendered properties
- const deletedPropertiesByRule = new Map<
- StyleRule | PlaintextRule,
- Set<StyleProperty>
- >();
+ const deletedPropertiesByRule = new Map<StyleRule, Set<StyleProperty>>();
for (const [key, rule] of wrappedRulesMap) {
if (key.startsWith(`${instanceId}:`)) {
deletedPropertiesByRule.set(rule, new Set(rule.styleMap.keys()));
@@ -355,8 +345,6 @@ export const useCssRules = ({
// render selected state as style without state
// to show user preview
state: selectedState === state ? undefined : state,
- assets,
- params,
});
// find existing declarations and exclude currently set properties
@@ -379,6 +367,7 @@ export const useCssRules = ({
}
}
+ userSheet.setTransformer($transformValue.get());
userSheet.render();
}, [instanceId, selectedState, instanceStyles, breakpoints, params]);
};
diff --git a/packages/css-engine/src/core/index.ts b/packages/css-engine/src/core/index.ts
index c1645515ef..c32c2ef973 100644
--- a/packages/css-engine/src/core/index.ts
+++ b/packages/css-engine/src/core/index.ts
@@ -1,6 +1,5 @@
export type {
NestingRule,
- AnyRule,
StyleRule,
MediaRule,
PlaintextRule,
diff --git a/packages/css-engine/src/core/rules.ts b/packages/css-engine/src/core/rules.ts
index fc9b2a8948..befde6932d 100644
--- a/packages/css-engine/src/core/rules.ts
+++ b/packages/css-engine/src/core/rules.ts
@@ -116,7 +116,7 @@ export class NestingRule {
}
return declarations.values();
}
- generateRules({
+ toString({
breakpoint,
indent = 0,
transformValue,
@@ -173,31 +173,19 @@ export class NestingRule {
}
export class StylePropertyMap {
+ #cached: undefined | string;
#styleMap: Map<StyleProperty, StyleValue | undefined> = new Map();
- #isDirty = true;
- #string = "";
#indent = 0;
#transformValue?: TransformValue;
- #onChange?: () => void;
- constructor(
- style: Style,
- transformValue?: TransformValue,
- onChange?: () => void
- ) {
- this.#transformValue = transformValue;
- this.#onChange = onChange;
+ constructor(style: Style) {
let property: StyleProperty;
for (property in style) {
this.#styleMap.set(property, style[property]);
}
}
- setTransformer(transformValue: TransformValue) {
- this.#transformValue = transformValue;
- }
set(property: StyleProperty, value?: StyleValue) {
this.#styleMap.set(property, value);
- this.#isDirty = true;
- this.#onChange?.();
+ this.#cached = undefined;
}
get(property: StyleProperty) {
return this.#styleMap.get(property);
@@ -213,19 +201,24 @@ export class StylePropertyMap {
}
delete(property: StyleProperty) {
this.#styleMap.delete(property);
- this.#isDirty = true;
- this.#onChange?.();
+ this.#cached = undefined;
}
clear() {
this.#styleMap.clear();
- this.#isDirty = true;
- this.#onChange?.();
+ this.#cached = undefined;
}
- toString({ indent = 0 } = {}) {
- if (this.#isDirty === false && indent === this.#indent) {
- return this.#string;
+ toString({
+ indent = 0,
+ transformValue,
+ }: { indent?: number; transformValue?: TransformValue } = {}) {
+ // invalidate cache when indent is changed
+ if (
+ this.#cached &&
+ indent === this.#indent &&
+ transformValue === this.#transformValue
+ ) {
+ return this.#cached;
}
- this.#indent = indent;
const block: Array<string> = [];
const spaces = " ".repeat(indent);
for (const [property, value] of this.#styleMap) {
@@ -233,41 +226,37 @@ export class StylePropertyMap {
continue;
}
block.push(
- `${spaces}${toProperty(property)}: ${toValue(
- value,
- this.#transformValue
- )}`
+ `${spaces}${toProperty(property)}: ${toValue(value, transformValue)}`
);
}
- this.#string = block.join(";\n");
- this.#isDirty = false;
- return this.#string;
+ this.#cached = block.join(";\n");
+ this.#indent = indent;
+ this.#transformValue = transformValue;
+ return this.#cached;
}
}
export class StyleRule {
styleMap;
selectorText;
- constructor(
- selectorText: string,
- style: StylePropertyMap | Style,
- transformValue?: TransformValue,
- onChange?: () => void
- ) {
+ constructor(selectorText: string, style: StylePropertyMap | Style) {
this.selectorText = selectorText;
this.styleMap =
- style instanceof StylePropertyMap
- ? style
- : new StylePropertyMap(style, transformValue, onChange);
+ style instanceof StylePropertyMap ? style : new StylePropertyMap(style);
}
get cssText() {
return this.toString();
}
- toString(options = { indent: 0 }) {
- const spaces = " ".repeat(options.indent);
- return `${spaces}${this.selectorText} {\n${this.styleMap.toString({
- indent: options.indent + 2,
- })}\n${spaces}}`;
+ toString({
+ indent = 0,
+ transformValue,
+ }: { indent?: number; transformValue?: TransformValue } = {}) {
+ const spaces = " ".repeat(indent);
+ const content = this.styleMap.toString({
+ indent: indent + 2,
+ transformValue,
+ });
+ return `${spaces}${this.selectorText} {\n${content}\n${spaces}}`;
}
}
@@ -313,10 +302,10 @@ export class MediaRule {
}
const rules = [];
for (const rule of this.rules.values()) {
- rules.push(rule.toString({ indent: 2 }));
+ rules.push(rule.toString({ indent: 2, transformValue }));
}
for (const rule of nestingRules) {
- const generatedRule = rule.generateRules({
+ const generatedRule = rule.toString({
breakpoint: this.#name,
indent: 2,
transformValue,
@@ -345,10 +334,8 @@ export class MediaRule {
export class PlaintextRule {
cssText;
- styleMap: StylePropertyMap;
constructor(cssText: string) {
this.cssText = cssText;
- this.styleMap = new StylePropertyMap({});
}
toString() {
return this.cssText;
@@ -364,17 +351,21 @@ export type FontFaceOptions = {
};
export class FontFaceRule {
- options: FontFaceOptions;
+ #cached: undefined | string;
+ #options: FontFaceOptions;
constructor(options: FontFaceOptions) {
- this.options = options;
+ this.#options = options;
}
get cssText() {
return this.toString();
}
toString() {
+ if (this.#cached) {
+ return this.#cached;
+ }
const decls = [];
const { fontFamily, fontStyle, fontWeight, fontDisplay, src } =
- this.options;
+ this.#options;
const value = toValue(
{ type: "fontFamily", value: [fontFamily] },
// Avoids adding a fallback automatically which needs to happen for font family in general but not for font face.
@@ -385,8 +376,7 @@ export class FontFaceRule {
decls.push(`font-weight: ${fontWeight}`);
decls.push(`font-display: ${fontDisplay}`);
decls.push(`src: ${src}`);
- return `@font-face {\n ${decls.join("; ")};\n}`;
+ this.#cached = `@font-face {\n ${decls.join("; ")};\n}`;
+ return this.#cached;
}
}
-
-export type AnyRule = StyleRule | MediaRule | PlaintextRule | FontFaceRule;
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 edfadbbcb2..9d35a26f13 100644
--- a/packages/css-engine/src/core/style-sheet-regular.test.ts
+++ b/packages/css-engine/src/core/style-sheet-regular.test.ts
@@ -53,13 +53,13 @@ describe("nesting rule", () => {
property: "color",
value: { type: "keyword", value: "transparent" },
});
- expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+ expect(rule.toString({ breakpoint: "base" })).toMatchInlineSnapshot(`
".instance {
width: auto;
height: auto
}"
`);
- expect(rule.generateRules({ breakpoint: "small" })).toMatchInlineSnapshot(`
+ expect(rule.toString({ breakpoint: "small" })).toMatchInlineSnapshot(`
".instance {
color: transparent
}"
@@ -87,7 +87,7 @@ describe("nesting rule", () => {
property: "color",
value: { type: "keyword", value: "transparent" },
});
- expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+ expect(rule.toString({ breakpoint: "base" })).toMatchInlineSnapshot(`
".instance {
width: auto;
height: auto
@@ -113,7 +113,7 @@ describe("nesting rule", () => {
property: "width",
value: { type: "keyword", value: "auto" },
});
- expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+ expect(rule.toString({ breakpoint: "base" })).toMatchInlineSnapshot(`
".instance {
width: auto
}
@@ -132,7 +132,7 @@ describe("nesting rule", () => {
property: "width",
value: { type: "keyword", value: "auto" },
});
- expect(rule.generateRules({ breakpoint: "base", indent: 4 }))
+ expect(rule.toString({ breakpoint: "base", indent: 4 }))
.toMatchInlineSnapshot(`
" .instance {
width: auto
@@ -149,7 +149,7 @@ describe("nesting rule", () => {
property: "width",
value: { type: "keyword", value: "auto" },
});
- expect(rule.generateRules({ breakpoint: "base", transformValue }))
+ expect(rule.toString({ breakpoint: "base", transformValue }))
.toMatchInlineSnapshot(`
".instance {
width: AUTO
@@ -166,7 +166,7 @@ describe("nesting rule", () => {
property: "width",
value: { type: "keyword", value: "auto" },
});
- expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+ expect(rule.toString({ breakpoint: "base" })).toMatchInlineSnapshot(`
".instance {
width: auto
}"
@@ -178,7 +178,7 @@ describe("nesting rule", () => {
property: "height",
value: { type: "keyword", value: "auto" },
});
- expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+ expect(rule.toString({ breakpoint: "base" })).toMatchInlineSnapshot(`
".instance {
width: auto;
height: auto
@@ -190,22 +190,21 @@ describe("nesting rule", () => {
selector: "",
property: "height",
});
- expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+ expect(rule.toString({ breakpoint: "base" })).toMatchInlineSnapshot(`
".instance {
width: auto
}"
`);
// invalidate by indent
- expect(rule.generateRules({ breakpoint: "base", indent: 2 }))
+ expect(rule.toString({ breakpoint: "base", indent: 2 }))
.toMatchInlineSnapshot(`
" .instance {
width: auto
}"
`);
// invalidate by transform value
- expect(
- rule.generateRules({ breakpoint: "base", indent: 2, transformValue })
- ).toMatchInlineSnapshot(`
+ expect(rule.toString({ breakpoint: "base", indent: 2, transformValue }))
+ .toMatchInlineSnapshot(`
" .instance {
width: AUTO
}"
@@ -215,7 +214,7 @@ describe("nesting rule", () => {
test("generate breakpoint without declarations", () => {
const sheet = createRegularStyleSheet();
const rule = sheet.addNestingRule(".instance");
- expect(rule.generateRules({ breakpoint: "base" })).toEqual("");
+ expect(rule.toString({ breakpoint: "base" })).toEqual("");
});
});
@@ -244,7 +243,7 @@ describe("mixin rule", () => {
property: "height",
value: { type: "keyword", value: "auto" },
});
- expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+ expect(rule.toString({ breakpoint: "base" })).toMatchInlineSnapshot(`
".instance {
width: fit-content;
height: auto
@@ -270,7 +269,7 @@ describe("mixin rule", () => {
property: "height",
value: { type: "keyword", value: "auto" },
});
- expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+ expect(rule.toString({ breakpoint: "base" })).toMatchInlineSnapshot(`
".instance:hover {
height: auto;
width: fit-content
@@ -288,11 +287,9 @@ describe("mixin rule", () => {
property: "width",
value: { type: "keyword", value: "auto" },
});
- expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(
- `""`
- );
+ expect(rule.toString({ breakpoint: "base" })).toMatchInlineSnapshot(`""`);
rule.applyMixins(["local"]);
- expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+ expect(rule.toString({ breakpoint: "base" })).toMatchInlineSnapshot(`
".instance {
width: auto
}"
@@ -304,16 +301,14 @@ describe("mixin rule", () => {
const rule = sheet.addNestingRule(".instance");
const localMixin = sheet.addMixinRule("local");
rule.applyMixins(["local"]);
- expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(
- `""`
- );
+ expect(rule.toString({ breakpoint: "base" })).toMatchInlineSnapshot(`""`);
localMixin.setDeclaration({
breakpoint: "base",
selector: "",
property: "width",
value: { type: "keyword", value: "auto" },
});
- expect(rule.generateRules({ breakpoint: "base" })).toMatchInlineSnapshot(`
+ expect(rule.toString({ breakpoint: "base" })).toMatchInlineSnapshot(`
".instance {
width: auto
}"
@@ -816,6 +811,21 @@ describe("Style Sheet Regular", () => {
const assets = new Map<string, { path: string }>([
["1234", { path: "foo.png" }],
]);
+ sheet.setTransformer((styleValue) => {
+ if (styleValue.type === "image" && styleValue.value.type === "asset") {
+ const asset = assets.get(styleValue.value.value);
+ if (asset === undefined) {
+ return { type: "keyword", value: "none" };
+ }
+ return {
+ type: "image",
+ value: {
+ type: "url",
+ url: asset.path,
+ },
+ };
+ }
+ });
const rule = sheet.addStyleRule(
{
style: {
@@ -829,22 +839,7 @@ describe("Style Sheet Regular", () => {
},
breakpoint: "0",
},
- ".c",
- (styleValue) => {
- if (styleValue.type === "image" && styleValue.value.type === "asset") {
- const asset = assets.get(styleValue.value.value);
- if (asset === undefined) {
- return { type: "keyword", value: "none" };
- }
- return {
- type: "image",
- value: {
- type: "url",
- url: asset.path,
- },
- };
- }
- }
+ ".c"
);
rule.styleMap.delete("display");
expect(sheet.cssText).toMatchInlineSnapshot(`
diff --git a/packages/css-engine/src/core/style-sheet-regular.ts b/packages/css-engine/src/core/style-sheet-regular.ts
index 54e6f7f487..24bf4ad381 100644
--- a/packages/css-engine/src/core/style-sheet-regular.ts
+++ b/packages/css-engine/src/core/style-sheet-regular.ts
@@ -1,29 +1,14 @@
import { StyleRule } from "./rules";
-import type { TransformValue } from "./to-value";
import { StyleSheet, type CssRule } from "./style-sheet";
const defaultMediaRuleId = "__default-media-rule__";
export class StyleSheetRegular extends StyleSheet {
- addStyleRule(
- rule: CssRule,
- selectorText: string,
- transformValue?: TransformValue
- ) {
+ addStyleRule(rule: CssRule, selectorText: string) {
const mediaRule = this.addMediaRule(rule.breakpoint || defaultMediaRuleId);
- this.markAsDirty();
- const styleRule = new StyleRule(
- selectorText,
- rule.style,
- transformValue,
- this.#onChangeRule
- );
+ const styleRule = new StyleRule(selectorText, rule.style);
mediaRule.insertRule(styleRule);
return styleRule;
}
-
- #onChangeRule = () => {
- this.markAsDirty();
- };
}
diff --git a/packages/css-engine/src/core/style-sheet.ts b/packages/css-engine/src/core/style-sheet.ts
index 9175326620..df3f3910c1 100644
--- a/packages/css-engine/src/core/style-sheet.ts
+++ b/packages/css-engine/src/core/style-sheet.ts
@@ -25,27 +25,23 @@ export class StyleSheet {
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(id, options);
this.#mediaRules.set(id, mediaRule);
- this.#isDirty = true;
return mediaRule;
}
if (options) {
mediaRule.options = options;
- this.#isDirty = true;
}
if (mediaRule === undefined) {
@@ -60,7 +56,6 @@ export class StyleSheet {
if (rule !== undefined) {
return rule;
}
- this.#isDirty = true;
return this.#plainRules.set(cssText, new PlaintextRule(cssText));
}
addMixinRule(name: string) {
@@ -68,7 +63,6 @@ export class StyleSheet {
if (rule === undefined) {
rule = new MixinRule();
this.#mixinRules.set(name, rule);
- this.#isDirty = true;
}
return rule;
}
@@ -77,17 +71,12 @@ export class StyleSheet {
if (rule === undefined) {
rule = new NestingRule(selector, this.#mixinRules);
this.nestingRules.set(selector, rule);
- this.#isDirty = true;
}
return rule;
}
addFontFaceRule(options: FontFaceOptions) {
- this.#isDirty = true;
return this.#fontFaceRules.push(new FontFaceRule(options));
}
- markAsDirty() {
- this.#isDirty = true;
- }
generateWith({
nestingRules,
transformValue,
@@ -95,10 +84,6 @@ export class StyleSheet {
nestingRules: NestingRule[];
transformValue?: TransformValue;
}) {
- if (this.#isDirty === false) {
- return this.#cssText;
- }
- this.#isDirty = false;
const css: Array<string> = [];
css.push(...this.#fontFaceRules.map((rule) => rule.cssText));
@@ -135,7 +120,6 @@ export class StyleSheet {
this.#mediaRules.clear();
this.#plainRules.clear();
this.#fontFaceRules = [];
- this.#isDirty = true;
}
render() {
this.#element.mount();