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: reimplement canvas style renderer (#3253)

Bogdan Chadkin9f897f5d4172
diff --git a/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.tsx b/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.tsx
index bc612cab6b..b34e2df7ee 100644
--- a/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.tsx
+++ b/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.tsx
@@ -37,6 +37,7 @@ const initialPropertyNames = new Set<StyleProperty>([
const usePropertyNames = (currentStyle: StyleInfo) => {
const selectedInstanceSelector = useStore($selectedInstanceSelector);
+ // @todo switch to style object model to show also inherited styles
const styles = useInstanceStyles(selectedInstanceSelector?.[0]);
// Ordererd recent properties for sorting.
const recent = useRef<Set<StyleProperty>>(new Set());
diff --git a/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts b/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts
index e6e51af130..375b9e1577 100644
--- a/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts
+++ b/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts
@@ -85,7 +85,6 @@ export const useStyleData = (selectedInstance: Instance) => {
for (const update of updates) {
if (update.operation === "set") {
ephemeralStyles.push({
- instanceId: selectedInstance.id,
breakpointId: selectedBreakpoint.id,
styleSourceId: styleSourceSelector.styleSourceId,
state: styleSourceSelector.state,
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index 0b648da50c..10ad87a5bf 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useEffect, useState } from "react";
+import { useMemo, useEffect, useState, useLayoutEffect } from "react";
import { ErrorBoundary, type FallbackProps } from "react-error-boundary";
import { useStore } from "@nanostores/react";
import type { Instances } from "@webstudio-is/sdk";
@@ -26,7 +26,12 @@ import {
serverSyncStore,
useCanvasStore,
} from "~/shared/sync";
-import { useManageDesignModeStyles, GlobalStyles } from "./shared/styles";
+import {
+ useManageDesignModeStyles,
+ GlobalStyles,
+ subscribeStyles,
+ mountStyles,
+} from "./shared/styles";
import {
WebstudioComponentCanvas,
WebstudioComponentPreview,
@@ -116,7 +121,7 @@ const useElementsTree = (
]);
};
-const DesignMode = ({ params }: { params: Params }) => {
+const DesignMode = () => {
useManageDesignModeStyles();
useDragAndDrop();
// We need to initialize this in both canvas and builder,
@@ -173,6 +178,12 @@ export const Canvas = ({ params, imageLoader }: CanvasProps) => {
$params.set(params);
});
+ useLayoutEffect(() => {
+ mountStyles();
+ }, []);
+
+ useEffect(subscribeStyles, []);
+
useEffect(subscribeComponentHooks, []);
useEffect(subscribeCommands, []);
@@ -227,9 +238,7 @@ export const Canvas = ({ params, imageLoader }: CanvasProps) => {
// Call hooks after render to ensure effects are last.
// Helps improve outline calculations as all styles are then applied.
}
- {isPreviewMode === false && isInitialized && (
- <DesignMode params={params} />
- )}
+ {isPreviewMode === false && isInitialized && <DesignMode />}
</>
);
};
diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
index f3f25e862e..659b2c4d8e 100644
--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
@@ -36,10 +36,8 @@ import {
$selectedInstanceRenderState,
$selectedInstanceSelector,
$selectedPage,
- useInstanceStyles,
} from "~/shared/nano-states";
import { $textEditingInstanceSelector } from "~/shared/nano-states";
-import { useCssRules } from "~/canvas/shared/styles";
import {
type InstanceSelector,
areInstanceSelectorsEqual,
@@ -259,8 +257,6 @@ export const WebstudioComponentCanvas = forwardRef<
>(({ instance, instanceSelector, components, ...restProps }, ref) => {
const rootRef = useRef<null | HTMLDivElement>(null);
const instanceId = instance.id;
- const instanceStyles = useInstanceStyles(instanceId);
- useCssRules({ instanceId: instance.id, instanceStyles });
const instances = useStore($instances);
const textEditingInstanceSelector = useStore($textEditingInstanceSelector);
@@ -413,8 +409,6 @@ export const WebstudioComponentPreview = forwardRef<
WebstudioComponentProps
>(({ instance, instanceSelector, components, ...restProps }, ref) => {
const instances = useStore($instances);
- const instanceStyles = useInstanceStyles(instance.id);
- useCssRules({ instanceId: instance.id, instanceStyles });
const { [showAttribute]: show = true, ...instanceProps } =
useInstanceProps(instanceSelector);
const props = {
diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts
index 3e981ee615..bafdda4542 100644
--- a/apps/builder/app/canvas/shared/styles.ts
+++ b/apps/builder/app/canvas/shared/styles.ts
@@ -1,7 +1,11 @@
-import { useContext, useEffect, useLayoutEffect, useMemo } from "react";
+import { useEffect, useLayoutEffect } from "react";
import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
-import type { Instance, StyleDecl } from "@webstudio-is/sdk";
+import {
+ getStyleDeclKey,
+ type StyleDecl,
+ type StyleSourceSelection,
+} from "@webstudio-is/sdk";
import {
collapsedAttribute,
idAttribute,
@@ -9,13 +13,12 @@ import {
createImageValueTransformer,
getPresetStyleRules,
type Params,
- ReactSdkContext,
} from "@webstudio-is/react-sdk";
import {
- type StyleValue,
- type StyleProperty,
- isValidStaticStyleValue,
type VarValue,
+ createRegularStyleSheet,
+ isValidStaticStyleValue,
+ toValue,
} from "@webstudio-is/css-engine";
import {
$assets,
@@ -24,23 +27,33 @@ import {
$registeredComponentMetas,
$selectedInstanceSelector,
$selectedStyleState,
+ $styleSourceSelections,
+ $styles,
} from "~/shared/nano-states";
-import {
- type StyleRule,
- createRegularStyleSheet,
- toValue,
- compareMedia,
-} from "@webstudio-is/css-engine";
+import { setDifference } from "~/shared/shim";
import { $ephemeralStyles, $params } from "../stores";
import { resetInert, setInert } from "./inert";
const userSheet = createRegularStyleSheet({ name: "user-styles" });
+const stateSheet = createRegularStyleSheet({ name: "state-styles" });
const helpersSheet = createRegularStyleSheet({ name: "helpers" });
const fontsAndDefaultsSheet = createRegularStyleSheet({
name: "fonts-and-defaults",
});
const presetSheet = createRegularStyleSheet({ name: "preset-styles" });
+/**
+ * maintain order of rendered stylesheets
+ * should be invoked before any subscription
+ */
+export const mountStyles = () => {
+ fontsAndDefaultsSheet.render();
+ presetSheet.render();
+ userSheet.render();
+ stateSheet.render();
+ helpersSheet.render();
+};
+
// Helper styles on for canvas in design mode
// - Only instances that would collapse without helper should receive helper
// - Helper is removed when any CSS property is changed on that instance that would prevent collapsing, so that helper is not needed
@@ -121,102 +134,119 @@ const $transformValue = computed([$assets, $params], (assets, params) =>
})
);
-const subscribeEphemeralStyle = () => {
- // track custom properties added on previous ephemeral styles change
- const addedCustomProperties = new Set<string>();
-
- return $ephemeralStyles.subscribe((ephemeralStyles) => {
- if (ephemeralStyles.length > 0) {
- setInert();
- } else {
- resetInert();
- }
+const getEphemeralProperty = (styleDecl: StyleDecl) => {
+ const { styleSourceId, state = "", property } = styleDecl;
+ return `--${styleSourceId}-${state}-${property}`;
+};
- // track custom properties not set on this change
- const deletedCustomProperties = new Set(addedCustomProperties);
+// wrap normal style value with var(--namespace, value) to support ephemeral styles updates
+// between all token usages
+const toVarValue = (styleDecl: StyleDecl): undefined | VarValue => {
+ const { value } = styleDecl;
+ if (value.type === "var") {
+ return value;
+ }
+ // Values like InvalidValue, UnsetValue, VarValue don't need to be wrapped
+ if (isValidStaticStyleValue(value)) {
+ return {
+ type: "var",
+ // var style value is relying on name without leading "--"
+ // escape complex selectors in state like ":hover"
+ // setProperty and removeProperty escape automatically
+ value: CSS.escape(getEphemeralProperty(styleDecl).slice(2)),
+ fallbacks: [value],
+ };
+ }
+};
- const transformValue = $transformValue.get();
+/**
+ * track new or deleted styles and style source selections items
+ * and update style sheet accordingly
+ */
+export const subscribeStyles = () => {
+ let animationFrameId: undefined | number;
- for (const styleDecl of ephemeralStyles) {
- const {
- instanceId,
- breakpointId,
- state,
- property,
- value,
- styleSourceId,
- } = styleDecl;
- const customProperty = `--${
- toVarValue(styleSourceId, property, value)?.value ?? "invalid-property"
- }`;
+ const renderUserSheetInTheNextFrame = () => {
+ if (animationFrameId) {
+ cancelAnimationFrame(animationFrameId);
+ }
+ animationFrameId = requestAnimationFrame(() => {
+ userSheet.setTransformer($transformValue.get());
+ userSheet.render();
+ });
+ };
- document.body.style.setProperty(
- customProperty,
- toValue(value, transformValue)
- );
- addedCustomProperties.add(customProperty);
- deletedCustomProperties.delete(customProperty);
+ const unsubscribeBreakpoints = $breakpoints.subscribe((breakpoints) => {
+ for (const breakpoint of breakpoints.values()) {
+ userSheet.addMediaRule(breakpoint.id, breakpoint);
+ }
+ renderUserSheetInTheNextFrame();
+ });
- const rule = getOrCreateRule({
- instanceId,
- breakpointId,
- state,
+ // add/delete declarations in mixins
+ let prevStylesSet = new Set<StyleDecl>();
+ const unsubscribeStyles = $styles.subscribe((styles) => {
+ const stylesSet = new Set(styles.values());
+ const addedStyles = setDifference(stylesSet, prevStylesSet);
+ const deletedStyles = setDifference(prevStylesSet, stylesSet);
+ prevStylesSet = stylesSet;
+ // delete before adding declaraions by the same key
+ for (const styleDecl of deletedStyles) {
+ const rule = userSheet.addMixinRule(styleDecl.styleSourceId);
+ rule.deleteDeclaration({
+ breakpoint: styleDecl.breakpointId,
+ selector: styleDecl.state ?? "",
+ property: styleDecl.property,
});
+ }
+ for (const styleDecl of addedStyles) {
+ const rule = userSheet.addMixinRule(styleDecl.styleSourceId);
+ rule.setDeclaration({
+ breakpoint: styleDecl.breakpointId,
+ selector: styleDecl.state ?? "",
+ property: styleDecl.property,
+ value: toVarValue(styleDecl) ?? styleDecl.value,
+ });
+ }
+ renderUserSheetInTheNextFrame();
+ });
- const propertyValue = rule.styleMap.get(property);
-
- const varValue = toVarValue(styleSourceId, property, value);
-
- if (varValue === undefined) {
- continue;
- }
-
- // Variable names are equal, no need to update
- if (
- propertyValue?.type === "var" &&
- propertyValue.value === varValue.value
- ) {
- continue;
+ // apply mixins to nesting rules
+ let prevSelectionsSet = new Set<StyleSourceSelection>();
+ const unsubscribeStyleSourceSelections = $styleSourceSelections.subscribe(
+ (styleSourceSelections) => {
+ const selectionsSet = new Set(styleSourceSelections.values());
+ const addedSelections = setDifference(selectionsSet, prevSelectionsSet);
+ prevSelectionsSet = selectionsSet;
+ for (const { instanceId, values } of addedSelections) {
+ const selector = `[${idAttribute}="${instanceId}"]`;
+ const rule = userSheet.addNestingRule(selector);
+ rule.applyMixins(values);
}
-
- // this is possible on newly created instances, or
- // in case of property variable defined on the other style source
- // or properties are not yet defined in the style.
- rule.styleMap.set(property, varValue);
+ renderUserSheetInTheNextFrame();
}
+ );
- for (const property of deletedCustomProperties) {
- document.body.style.removeProperty(property);
- addedCustomProperties.delete(property);
+ return () => {
+ unsubscribeBreakpoints();
+ unsubscribeStyles();
+ unsubscribeStyleSourceSelections();
+ if (animationFrameId) {
+ cancelAnimationFrame(animationFrameId);
}
-
- // rerender style rules if new vars added
- userSheet.setTransformer($transformValue.get());
- userSheet.render();
- });
+ };
};
export const useManageDesignModeStyles = () => {
- useEffect(() => subscribeEphemeralStyle(), []);
+ useEffect(subscribeStateStyles, []);
+ useEffect(subscribeEphemeralStyle, []);
useEffect(subscribePreviewMode, []);
};
export const GlobalStyles = ({ params }: { params: Params }) => {
- const breakpoints = useStore($breakpoints);
const assets = useStore($assets);
const metas = useStore($registeredComponentMetas);
- useLayoutEffect(() => {
- const sortedBreakpoints = Array.from(breakpoints.values()).sort(
- compareMedia
- );
- for (const breakpoint of sortedBreakpoints) {
- userSheet.addMediaRule(breakpoint.id, breakpoint);
- }
- userSheet.setTransformer($transformValue.get());
- userSheet.render();
- }, [breakpoints]);
-
useLayoutEffect(() => {
fontsAndDefaultsSheet.clear();
addGlobalRules(fontsAndDefaultsSheet, {
@@ -244,130 +274,159 @@ export const GlobalStyles = ({ params }: { params: Params }) => {
return null;
};
-// Wrapps a normal StyleValue into a VarStyleValue that uses the previous style value as a fallback and allows
-// to quickly pass the values over CSS variable witout rerendering the components tree.
-// Results in values like this: `var(--namespace, staticValue)`
-const toVarValue = (
- styleSourceId: StyleDecl["styleSourceId"],
- styleProperty: StyleProperty,
- styleValue: StyleValue
-): undefined | VarValue => {
- if (styleValue.type === "var") {
- return styleValue;
- }
- // Values like InvalidValue, UnsetValue, VarValue don't need to be wrapped
- if (isValidStaticStyleValue(styleValue)) {
+const $instanceStyles = computed(
+ [
+ $selectedInstanceSelector,
+ $selectedStyleState,
+ $breakpoints,
+ $styleSourceSelections,
+ $styles,
+ ],
+ (
+ selectedInstanceSelector,
+ selectedStyleState,
+ breakpoints,
+ styleSourceSelections,
+ styles
+ ) => {
+ if (
+ selectedInstanceSelector === undefined ||
+ selectedStyleState === undefined
+ ) {
+ return;
+ }
+ const [instanceId] = selectedInstanceSelector;
+ const styleSources = new Set(styleSourceSelections.get(instanceId)?.values);
+ const instanceStyles: StyleDecl[] = [];
+ for (const styleDecl of styles.values()) {
+ if (
+ styleDecl.state === selectedStyleState &&
+ styleSources.has(styleDecl.styleSourceId)
+ ) {
+ instanceStyles.push(styleDecl);
+ }
+ }
return {
- type: "var",
- value: `${styleProperty}-${styleSourceId}`,
- fallbacks: [styleValue],
+ instanceId,
+ breakpoints: Array.from(breakpoints.values()),
+ styles: instanceStyles,
};
}
-};
-
-const wrappedRulesMap = new Map<string, StyleRule>();
-
-const getOrCreateRule = ({
- instanceId,
- breakpointId,
- state = "",
-}: {
- instanceId: string;
- breakpointId: string;
- state: undefined | string;
-}) => {
- const key = `${instanceId}:${breakpointId}:${state}`;
- let rule = wrappedRulesMap.get(key);
- if (rule === undefined) {
- rule = userSheet.addStyleRule(
- {
- breakpoint: breakpointId,
- style: {},
- },
- `[${idAttribute}="${instanceId}"]${state}`
- );
- wrappedRulesMap.set(key, rule);
- }
- return rule;
-};
+);
-const useSelectedState = (instanceId: Instance["id"]) => {
- const $selectedState = useMemo(() => {
- return computed(
- [$selectedInstanceSelector, $selectedStyleState],
- (selectedInstanceSelector, selectedStyleState) => {
- if (selectedInstanceSelector?.[0] !== instanceId) {
- return;
- }
- return selectedStyleState;
- }
- );
- }, [instanceId]);
- const selectedState = useStore($selectedState);
- return selectedState;
+/**
+ * render currently selected state styles as stateless
+ * in separate sheet and clear when state is not selected
+ */
+const subscribeStateStyles = () => {
+ return $instanceStyles.subscribe((instanceStyles) => {
+ if (instanceStyles === undefined) {
+ stateSheet.clear();
+ stateSheet.render();
+ return;
+ }
+ // reset state sheet on every update to avoid stale styles
+ stateSheet.clear();
+ const { instanceId, breakpoints, styles } = instanceStyles;
+ for (const breakpoint of breakpoints.values()) {
+ stateSheet.addMediaRule(breakpoint.id, breakpoint);
+ }
+ const selector = `[${idAttribute}="${instanceId}"]`;
+ const rule = stateSheet.addNestingRule(selector);
+ for (const styleDecl of styles) {
+ rule.setDeclaration({
+ breakpoint: styleDecl.breakpointId,
+ // render without state
+ selector: "",
+ property: styleDecl.property,
+ value: toVarValue(styleDecl) ?? styleDecl.value,
+ });
+ }
+ stateSheet.setTransformer($transformValue.get());
+ stateSheet.render();
+ });
};
-export const useCssRules = ({
- instanceId,
- instanceStyles,
-}: {
- instanceId: string;
- instanceStyles: StyleDecl[];
-}) => {
- const params = useContext(ReactSdkContext);
- const breakpoints = useStore($breakpoints);
- const selectedState = useSelectedState(instanceId);
+const subscribeEphemeralStyle = () => {
+ // track custom properties added on previous ephemeral update
+ const appliedEphemeralDeclarations = new Map<string, StyleDecl>();
- useLayoutEffect(() => {
- // find all instance rules and collect rendered properties
- 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()));
- }
+ return $ephemeralStyles.subscribe((ephemeralStyles) => {
+ const instanceSelector = $selectedInstanceSelector.get();
+ if (instanceSelector === undefined) {
+ return;
}
+ const [instanceId] = instanceSelector;
- // render styles without state first so state styles in preview
- // could override them
- const orderedStyles = instanceStyles.slice().sort((left, right) => {
- const leftDirection = left.state === undefined ? -1 : 1;
- const rightDirection = right.state === undefined ? -1 : 1;
- return leftDirection - rightDirection;
- });
-
- for (const styleDecl of orderedStyles) {
- const { breakpointId, state, property, value, styleSourceId } = styleDecl;
-
- // create new rule or use cached one
- const rule = getOrCreateRule({
- instanceId,
- breakpointId,
- // render selected state as style without state
- // to show user preview
- state: selectedState === state ? undefined : state,
- });
-
- // find existing declarations and exclude currently set properties
- // to delete the rest later
- const deletedProperties = deletedPropertiesByRule.get(rule);
- if (deletedProperties) {
- deletedProperties.delete(property);
- }
-
- const varValue = toVarValue(styleSourceId, property, value);
- if (varValue) {
- rule.styleMap.set(property, varValue);
+ // reset ephemeral styles
+ if (ephemeralStyles.length === 0) {
+ resetInert();
+ for (const styleDecl of appliedEphemeralDeclarations.values()) {
+ // prematurely apply last known ephemeral update to user stylesheet
+ // to avoid lag because of delay between deleting ephemeral style
+ // and sending style patch (and rendering)
+ const mixinRule = userSheet.addMixinRule(styleDecl.styleSourceId);
+ mixinRule.setDeclaration({
+ breakpoint: styleDecl.breakpointId,
+ selector: styleDecl.state ?? "",
+ property: styleDecl.property,
+ value: toVarValue(styleDecl) ?? styleDecl.value,
+ });
+ document.body.style.removeProperty(getEphemeralProperty(styleDecl));
}
+ userSheet.setTransformer($transformValue.get());
+ userSheet.render();
+ appliedEphemeralDeclarations.clear();
}
- // delete previously rendered properties when reset
- for (const [styleRule, deletedProperties] of deletedPropertiesByRule) {
- for (const property of deletedProperties) {
- styleRule.styleMap.delete(property);
+ // add ephemeral styles
+ if (ephemeralStyles.length > 0) {
+ setInert();
+ const selector = `[${idAttribute}="${instanceId}"]`;
+ const rule = userSheet.addNestingRule(selector);
+ let ephemetalSheetUpdated = false;
+ for (const styleDecl of ephemeralStyles) {
+ // update custom property
+ document.body.style.setProperty(
+ getEphemeralProperty(styleDecl),
+ toValue(styleDecl.value, $transformValue.get())
+ );
+ // render temporary rule for instance with var()
+ // rendered with "all" breakpoint and without state
+ // to reflect changes in canvas without user interaction
+ const styleDeclKey = getStyleDeclKey(styleDecl);
+ if (appliedEphemeralDeclarations.has(styleDeclKey) === false) {
+ ephemetalSheetUpdated = true;
+ const mixinRule = userSheet.addMixinRule(styleDecl.styleSourceId);
+ mixinRule.setDeclaration({
+ breakpoint: styleDecl.breakpointId,
+ selector: styleDecl.state ?? "",
+ property: styleDecl.property,
+ value: toVarValue(styleDecl) ?? styleDecl.value,
+ });
+ // add local style source when missing to support
+ // ephemeral styles on newly created instances
+ rule.addMixin(styleDecl.styleSourceId);
+
+ // temporary render var() in state sheet as well
+ if (styleDecl.state !== undefined) {
+ const stateRule = stateSheet.addNestingRule(selector);
+ stateRule.setDeclaration({
+ breakpoint: styleDecl.breakpointId,
+ // render without state
+ selector: "",
+ property: styleDecl.property,
+ value: toVarValue(styleDecl) ?? styleDecl.value,
+ });
+ }
+ }
+ appliedEphemeralDeclarations.set(styleDeclKey, styleDecl);
+ }
+ // avoid stylesheet rerendering on every ephemeral update
+ if (ephemetalSheetUpdated) {
+ userSheet.render();
+ stateSheet.render();
}
}
-
- userSheet.setTransformer($transformValue.get());
- userSheet.render();
- }, [instanceId, selectedState, instanceStyles, breakpoints, params]);
+ });
};
diff --git a/apps/builder/app/canvas/stores.ts b/apps/builder/app/canvas/stores.ts
index 3f8d8053c5..0fdea29e3b 100644
--- a/apps/builder/app/canvas/stores.ts
+++ b/apps/builder/app/canvas/stores.ts
@@ -1,9 +1,7 @@
import { atom } from "nanostores";
-import type { Instance, StyleDecl } from "@webstudio-is/sdk";
+import type { StyleDecl } from "@webstudio-is/sdk";
import type { Params } from "@webstudio-is/react-sdk";
-export const $ephemeralStyles = atom<
- Array<StyleDecl & { instanceId: Instance["id"] }>
->([]);
+export const $ephemeralStyles = atom<Array<StyleDecl>>([]);
export const $params = atom<undefined | Params>();
diff --git a/apps/builder/app/shared/nano-states/nano-states.ts b/apps/builder/app/shared/nano-states/nano-states.ts
index 9233355d58..2005ade9c7 100644
--- a/apps/builder/app/shared/nano-states/nano-states.ts
+++ b/apps/builder/app/shared/nano-states/nano-states.ts
@@ -101,6 +101,9 @@ export const $propsIndex = computed($props, (props) => {
export const $styles = atom<Styles>(new Map());
+/**
+ * @deprecated
+ */
export const useInstanceStyles = (instanceId: undefined | Instance["id"]) => {
const instance$styles = useMemo(() => {
return shallowComputed([$stylesIndex], (stylesIndex) => {
diff --git a/apps/builder/app/shared/shim.test.ts b/apps/builder/app/shared/shim.test.ts
new file mode 100644
index 0000000000..0bb05f60e7
--- /dev/null
+++ b/apps/builder/app/shared/shim.test.ts
@@ -0,0 +1,13 @@
+import { expect, test } from "@jest/globals";
+import { setDifference } from "./shim";
+
+test("set difference", () => {
+ // this set is bigger than other
+ expect(setDifference(new Set([1, 2, 3, 4]), new Set([3, 4, 5]))).toEqual(
+ new Set([1, 2])
+ );
+ // this set is smaller than other
+ expect(setDifference(new Set([1, 2, 3]), new Set([2, 3, 4, 5]))).toEqual(
+ new Set([1])
+ );
+});
diff --git a/apps/builder/app/shared/shim.ts b/apps/builder/app/shared/shim.ts
new file mode 100644
index 0000000000..c633184146
--- /dev/null
+++ b/apps/builder/app/shared/shim.ts
@@ -0,0 +1,17 @@
+export const setDifference = <Item>(current: Set<Item>, other: Set<Item>) => {
+ const result = new Set<Item>(current);
+ if (current.size <= other.size) {
+ for (const item of current) {
+ if (other.has(item)) {
+ result.delete(item);
+ }
+ }
+ } else {
+ for (const item of other) {
+ if (current.has(item)) {
+ result.delete(item);
+ }
+ }
+ }
+ return result;
+};
diff --git a/packages/css-data/src/parse-css-value.ts b/packages/css-data/src/parse-css-value.ts
index 9baa69192e..0c5523755d 100644
--- a/packages/css-data/src/parse-css-value.ts
+++ b/packages/css-data/src/parse-css-value.ts
@@ -36,11 +36,6 @@ export const isValidDeclaration = (
CSSStyleValue.parse(cssPropertyName, value);
return true;
} catch {
- warnOnce(
- true,
- `Css property "${property}" with value "${value}" is invalid according to CSSStyleValue.parse
- but valid according to csstree.lexer.matchProperty.`
- );
return false;
}
}
diff --git a/packages/css-engine/src/core/rules.ts b/packages/css-engine/src/core/rules.ts
index befde6932d..e11930df6b 100644
--- a/packages/css-engine/src/core/rules.ts
+++ b/packages/css-engine/src/core/rules.ts
@@ -72,7 +72,7 @@ export class MixinRule {
export class NestingRule {
#selector: string;
#mixinRules = new Map<string, MixinRule>();
- #mixins: string[] = [];
+ #mixins = new Set<string>();
// use map to avoid duplicated properties
#declarations = new Map<string, Declaration>();
// cached generated rule by breakpoint
@@ -87,8 +87,12 @@ export class NestingRule {
getSelector() {
return this.#selector;
}
+ addMixin(mixin: string) {
+ this.#mixins.add(mixin);
+ this.#cache.clear();
+ }
applyMixins(mixins: string[]) {
- this.#mixins = mixins;
+ this.#mixins = new Set(mixins);
this.#cache.clear();
}
setDeclaration(declaration: Declaration) {
diff --git a/packages/css-engine/src/core/style-sheet.ts b/packages/css-engine/src/core/style-sheet.ts
index df3f3910c1..5a95f57762 100644
--- a/packages/css-engine/src/core/style-sheet.ts
+++ b/packages/css-engine/src/core/style-sheet.ts
@@ -118,6 +118,8 @@ export class StyleSheet {
}
clear() {
this.#mediaRules.clear();
+ this.#mixinRules.clear();
+ this.nestingRules.clear();
this.#plainRules.clear();
this.#fontFaceRules = [];
}