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.

Render style states (#1420)

Bogdan Chadkina148507e4861
diff --git a/apps/builder/app/builder/features/footer/breadcrumbs.tsx b/apps/builder/app/builder/features/footer/breadcrumbs.tsx
index 2804de9651..63de7829fd 100644
--- a/apps/builder/app/builder/features/footer/breadcrumbs.tsx
+++ b/apps/builder/app/builder/features/footer/breadcrumbs.tsx
@@ -9,6 +9,7 @@ import {
import {
instancesStore,
selectedInstanceSelectorStore,
+ selectedStyleSourceSelectorStore,
} from "~/shared/nano-states";
import { getAncestorInstanceSelector } from "~/shared/tree-utils";
import { textEditingInstanceSelectorStore } from "~/shared/nano-states";
@@ -69,6 +70,7 @@ export const Breadcrumbs = () => {
)
);
textEditingInstanceSelectorStore.set(undefined);
+ selectedStyleSourceSelectorStore.set(undefined);
}}
>
{instance.label || instance.component}
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 03ce8c099e..ce84b4d0c7 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
@@ -36,6 +36,7 @@ export type StyleUpdates = {
id: Instance["id"];
updates: Array<StyleUpdate>;
breakpoint: Breakpoint;
+ state: undefined | string;
};
declare module "~/shared/pubsub" {
@@ -97,6 +98,7 @@ export const useStyleData = ({ selectedInstance, publish }: UseStyleData) => {
id: selectedInstance.id,
updates,
breakpoint: selectedBreakpoint,
+ state: styleSourceSelector.state,
},
});
diff --git a/apps/builder/app/builder/features/style-panel/style-source-section.tsx b/apps/builder/app/builder/features/style-panel/style-source-section.tsx
index d5b2d86bac..4cd13208d5 100644
--- a/apps/builder/app/builder/features/style-panel/style-source-section.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-source-section.tsx
@@ -39,6 +39,35 @@ const getOrCreateStyleSourceSelectionMutable = (
return styleSourceSelection;
};
+const createLocalStyleSourceIfNotExists = (
+ styleSourceId: StyleSource["id"]
+) => {
+ const selectedInstanceSelector = selectedInstanceSelectorStore.get();
+ if (selectedInstanceSelector === undefined) {
+ return;
+ }
+ const [selectedInstanceId] = selectedInstanceSelector;
+ store.createTransaction(
+ [styleSourceSelectionsStore, styleSourcesStore],
+ (styleSourceSelections, styleSources) => {
+ const styleSourceSelection = getOrCreateStyleSourceSelectionMutable(
+ styleSourceSelections,
+ selectedInstanceId
+ );
+ if (styleSourceSelection.values.includes(styleSourceId) === false) {
+ // local should be put first by default
+ styleSourceSelection.values.unshift(styleSourceId);
+ }
+ if (styleSources.has(styleSourceId) === false) {
+ styleSources.set(styleSourceId, {
+ type: "local",
+ id: styleSourceId,
+ });
+ }
+ }
+ );
+};
+
const createStyleSource = (name: string) => {
const selectedInstanceSelector = selectedInstanceSelectorStore.get();
if (selectedInstanceSelector === undefined) {
@@ -105,6 +134,12 @@ const removeStyleSourceFromInstance = (styleSourceId: StyleSource["id"]) => {
);
}
);
+ // reset selected style source if necessary
+ const selectedStyleSourceId =
+ selectedStyleSourceSelectorStore.get()?.styleSourceId;
+ if (selectedStyleSourceId === styleSourceId) {
+ selectedStyleSourceSelectorStore.set(undefined);
+ }
};
const deleteStyleSource = (styleSourceId: StyleSource["id"]) => {
@@ -127,6 +162,12 @@ const deleteStyleSource = (styleSourceId: StyleSource["id"]) => {
}
}
);
+ // reset selected style source if necessary
+ const selectedStyleSourceId =
+ selectedStyleSourceSelectorStore.get()?.styleSourceId;
+ if (selectedStyleSourceId === styleSourceId) {
+ selectedStyleSourceSelectorStore.set(undefined);
+ }
};
const duplicateStyleSource = (styleSourceId: StyleSource["id"]) => {
@@ -321,6 +362,7 @@ export const StyleSourcesSection = () => {
reorderStyleSources(items.map((item) => item.id));
}}
onSelectItem={(styleSourceSelector) => {
+ createLocalStyleSourceIfNotExists(styleSourceSelector.styleSourceId);
selectedStyleSourceSelectorStore.set(styleSourceSelector);
}}
// style source renaming
diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx
index a2b1296e11..37e12e7ea2 100644
--- a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx
@@ -80,7 +80,7 @@ type TextFieldBaseWrapperProps<Item extends IntermediateItem> = Omit<
renderStyleSourceMenuItems: (item: Item) => ReactNode;
onChangeItem?: (item: Item) => void;
onSort?: (items: Array<Item>) => void;
- onSelectItem?: (itemSelector?: ItemSelector) => void;
+ onSelectItem?: (itemSelector: ItemSelector) => void;
onEditItem?: (id?: Item["id"]) => void;
editingItemId?: Item["id"];
};
@@ -193,7 +193,7 @@ type StyleSourceInputProps<Item extends IntermediateItem> = {
onConvertToToken?: (id: Item["id"]) => void;
onCreateItem?: (label: string) => void;
onChangeItem?: (item: Item) => void;
- onSelectItem?: (item: undefined | ItemSelector) => void;
+ onSelectItem?: (item: ItemSelector) => void;
onEditItem?: (id?: Item["id"]) => void;
onDisableItem?: (id: Item["id"]) => void;
onEnableItem?: (id: Item["id"]) => void;
@@ -251,7 +251,7 @@ const userActionStates = [
const renderMenuItems = (props: {
selectedItemSelector: undefined | ItemSelector;
item: IntermediateItem;
- onSelect?: (itemSelector: undefined | ItemSelector) => void;
+ onSelect?: (itemSelector: ItemSelector) => void;
onEdit?: (itemId: IntermediateItem["id"]) => void;
onDuplicate?: (itemId: IntermediateItem["id"]) => void;
onConvertToToken?: (itemId: IntermediateItem["id"]) => void;
diff --git a/apps/builder/app/builder/features/workspace/workspace.tsx b/apps/builder/app/builder/features/workspace/workspace.tsx
index 723cda8530..f65916ee1d 100644
--- a/apps/builder/app/builder/features/workspace/workspace.tsx
+++ b/apps/builder/app/builder/features/workspace/workspace.tsx
@@ -6,7 +6,10 @@ import {
workspaceRectStore,
} from "~/builder/shared/nano-states";
import type { Publish } from "~/shared/pubsub";
-import { selectedInstanceSelectorStore } from "~/shared/nano-states";
+import {
+ selectedInstanceSelectorStore,
+ selectedStyleSourceSelectorStore,
+} from "~/shared/nano-states";
import { textEditingInstanceSelectorStore } from "~/shared/nano-states";
import { CanvasTools } from "./canvas-tools";
import { useMeasure } from "react-use";
@@ -87,6 +90,7 @@ export const Workspace = ({
const handleWorkspaceClick = () => {
selectedInstanceSelectorStore.set(undefined);
textEditingInstanceSelectorStore.set(undefined);
+ selectedStyleSourceSelectorStore.set(undefined);
};
return (
diff --git a/apps/builder/app/builder/shared/navigator-tree.tsx b/apps/builder/app/builder/shared/navigator-tree.tsx
index 8e0c97af9f..b5c7ade882 100644
--- a/apps/builder/app/builder/shared/navigator-tree.tsx
+++ b/apps/builder/app/builder/shared/navigator-tree.tsx
@@ -8,6 +8,7 @@ import {
selectedInstanceSelectorStore,
useDragAndDropState,
textEditingInstanceSelectorStore,
+ selectedStyleSourceSelectorStore,
} from "~/shared/nano-states";
import type { InstanceSelector } from "~/shared/tree-utils";
import { reparentInstance } from "~/shared/instance-utils";
@@ -57,6 +58,7 @@ export const NavigatorTree = () => {
) {
selectedInstanceSelectorStore.set(instanceSelector);
textEditingInstanceSelectorStore.set(undefined);
+ selectedStyleSourceSelectorStore.set(undefined);
}
}, []);
diff --git a/apps/builder/app/canvas/canvas-shortcuts.ts b/apps/builder/app/canvas/canvas-shortcuts.ts
index 80e0423142..20a1814709 100644
--- a/apps/builder/app/canvas/canvas-shortcuts.ts
+++ b/apps/builder/app/canvas/canvas-shortcuts.ts
@@ -2,7 +2,8 @@ import { useHotkeys } from "react-hotkeys-hook";
import { shortcuts, instanceTreeShortcuts, options } from "~/shared/shortcuts";
import { publish, useSubscribe } from "~/shared/pubsub";
import { isPreviewModeStore } from "~/shared/nano-states";
-import { enterEditingMode, escapeSelection } from "~/shared/nano-states";
+import { enterEditingMode } from "~/shared/nano-states";
+import { escapeSelection } from "~/shared/instance-utils";
declare module "~/shared/pubsub" {
export interface PubsubMap {
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 1b95fa60c5..312b8d7bb4 100644
--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
@@ -18,6 +18,7 @@ import type { GetComponent } from "@webstudio-is/react-sdk";
import {
instancesStore,
selectedInstanceSelectorStore,
+ selectedStyleSourceSelectorStore,
useInstanceProps,
useInstanceStyles,
} from "~/shared/nano-states";
@@ -224,6 +225,7 @@ export const WebstudioComponentDev = ({
);
textEditingInstanceSelectorStore.set(undefined);
selectedInstanceSelectorStore.set(newSelectedSelector);
+ selectedStyleSourceSelectorStore.set(undefined);
}}
/>
</Suspense>
diff --git a/apps/builder/app/canvas/instance-selection.ts b/apps/builder/app/canvas/instance-selection.ts
index 7f8a8fba84..fc9a499cb6 100644
--- a/apps/builder/app/canvas/instance-selection.ts
+++ b/apps/builder/app/canvas/instance-selection.ts
@@ -3,6 +3,7 @@ import { getInstanceSelectorFromElement } from "~/shared/dom-utils";
import {
instancesStore,
selectedInstanceSelectorStore,
+ selectedStyleSourceSelectorStore,
} from "~/shared/nano-states";
import { textEditingInstanceSelectorStore } from "~/shared/nano-states";
import { publish } from "~/shared/pubsub";
@@ -70,6 +71,7 @@ export const subscribeInstanceSelection = () => {
selectedInstanceSelectorStore.set(instanceSelector);
// reset text editor when another instance is selected
textEditingInstanceSelectorStore.set(undefined);
+ selectedStyleSourceSelectorStore.set(undefined);
}
// the second click in a double click.
@@ -81,6 +83,7 @@ export const subscribeInstanceSelection = () => {
if (richTextInstanceSelector) {
selectedInstanceSelectorStore.set(richTextInstanceSelector);
textEditingInstanceSelectorStore.set(richTextInstanceSelector);
+ selectedStyleSourceSelectorStore.set(undefined);
}
}
};
diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts
index c70f7ff429..5e377a6b19 100644
--- a/apps/builder/app/canvas/shared/styles.ts
+++ b/apps/builder/app/canvas/shared/styles.ts
@@ -1,5 +1,6 @@
-import { useEffect } from "react";
+import { useEffect, useMemo } from "react";
import { useIsomorphicLayoutEffect } from "react-use";
+import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
import type { Assets } from "@webstudio-is/asset-uploader";
import {
@@ -12,20 +13,18 @@ import {
createImageValueTransformer,
getParams,
} from "@webstudio-is/react-sdk";
-import type { StyleDecl } from "@webstudio-is/project-build";
+import type { Instance, StyleDecl } from "@webstudio-is/project-build";
import {
- validStaticValueTypes,
- type ValidStaticStyleValue,
type StyleValue,
- type CssRule,
type StyleProperty,
- type Style,
+ isValidStaticStyleValue,
} from "@webstudio-is/css-data";
import {
assetsStore,
breakpointsStore,
isPreviewModeStore,
selectedInstanceSelectorStore,
+ selectedStyleSourceSelectorStore,
} from "~/shared/nano-states";
import {
createCssEngine,
@@ -158,63 +157,70 @@ export const GlobalStyles = () => {
// 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 toVarStyleWithFallback = (instanceId: string, style: Style): Style => {
- const dynamicStyle: Style = {};
- let property: StyleProperty;
- for (property in style) {
- const value = style[property];
- if (value === undefined) {
- continue;
- }
- if (value.type === "var") {
- dynamicStyle[property] = value;
- continue;
- }
- if (
- validStaticValueTypes.includes(
- value.type as (typeof validStaticValueTypes)[number]
- )
- ) {
- // We don't want to wrap backgroundClip into a var, because it's not supported by CSS variables
- // It's fine because we don't need to update it dynamically via CSS variables during preview changes
- // we renrender it anyway when CSS update happens
- if (property === "backgroundClip") {
- dynamicStyle[property] = value;
- continue;
- }
- dynamicStyle[property] = {
- type: "var",
- value: toVarNamespace(instanceId, property),
- fallbacks: [value as ValidStaticStyleValue],
- };
- }
+const toVarValue = (
+ instanceId: Instance["id"],
+ styleProperty: StyleProperty,
+ styleValue: StyleValue
+): undefined | StyleValue => {
+ if (styleValue.type === "var") {
+ return styleValue;
+ }
+ // Values like InvalidValue, UnsetValue, VarValue don't need to be wrapped
+ if (isValidStaticStyleValue(styleValue)) {
+ return {
+ type: "var",
+ value: toVarNamespace(instanceId, styleProperty),
+ fallbacks: [styleValue],
+ };
}
- return dynamicStyle;
};
const wrappedRulesMap = new Map<string, StyleRule | PlaintextRule>();
-const addRule = (id: string, cssRule: CssRule, assets: Assets) => {
- const key = id + cssRule.breakpoint;
- const selectorText = `[${idAttribute}="${id}"]`;
- const params = getParams();
- const rule = cssEngine.addStyleRule(
- selectorText,
- {
- ...cssRule,
- style: toVarStyleWithFallback(id, cssRule.style),
- },
- createImageValueTransformer(assets, {
- assetBaseUrl: params.assetBaseUrl,
- })
- );
- wrappedRulesMap.set(key, rule);
+const getOrCreateRule = ({
+ instanceId,
+ breakpointId,
+ state = "",
+ assets,
+}: {
+ instanceId: string;
+ breakpointId: string;
+ state: undefined | string;
+ assets: Assets;
+}) => {
+ const key = `${instanceId}:${breakpointId}:${state}`;
+ let rule = wrappedRulesMap.get(key);
+ if (rule === undefined) {
+ const params = getParams();
+ rule = cssEngine.addStyleRule(
+ `[${idAttribute}="${instanceId}"]${state}`,
+ {
+ breakpoint: breakpointId,
+ style: {},
+ },
+ createImageValueTransformer(assets, {
+ assetBaseUrl: params.assetBaseUrl,
+ })
+ );
+ wrappedRulesMap.set(key, rule);
+ }
return rule;
};
-const getRule = (id: string, breakpoint?: string) => {
- const key = id + breakpoint;
- return wrappedRulesMap.get(key);
+const useSelectedState = (instanceId: Instance["id"]) => {
+ const selectedStateStore = useMemo(() => {
+ return computed(
+ [selectedInstanceSelectorStore, selectedStyleSourceSelectorStore],
+ (selectedInstanceSelector, selectedStyleSourceSelector) => {
+ if (selectedInstanceSelector?.[0] !== instanceId) {
+ return;
+ }
+ return selectedStyleSourceSelector?.state;
+ }
+ );
+ }, [instanceId]);
+ const selectedState = useStore(selectedStateStore);
+ return selectedState;
};
export const useCssRules = ({
@@ -225,45 +231,74 @@ export const useCssRules = ({
instanceStyles: StyleDecl[];
}) => {
const breakpoints = useStore(breakpointsStore);
+ const selectedState = useSelectedState(instanceId);
useIsomorphicLayoutEffect(() => {
- const stylePerBreakpoint = new Map<string, Style>();
// expect assets to be up to date by the time styles are changed
// to avoid all styles rerendering when assets are changed
const assets = assetsStore.get();
- for (const item of instanceStyles) {
- let style = stylePerBreakpoint.get(item.breakpointId);
- if (style === undefined) {
- style = {};
- stylePerBreakpoint.set(item.breakpointId, style);
+ // find all instance rules and collect rendered properties
+ const deletedPropertiesByRule = new Map<
+ StyleRule | PlaintextRule,
+ Set<StyleProperty>
+ >();
+ for (const [key, rule] of wrappedRulesMap) {
+ if (key.startsWith(`${instanceId}:`)) {
+ deletedPropertiesByRule.set(rule, new Set(rule.styleMap.keys()));
}
- style[item.property] = item.value;
}
- for (const breakpointId of breakpoints.keys()) {
- const style = stylePerBreakpoint.get(breakpointId) ?? {};
- const rule = getRule(instanceId, breakpointId);
- // It's the first time the rule is being used
- if (rule === undefined) {
- addRule(instanceId, { breakpoint: breakpointId, style }, assets);
- continue;
- }
- // It's an update to an existing rule
- const dynamicStyle = toVarStyleWithFallback(instanceId, style);
- let property: StyleProperty;
- for (property in dynamicStyle) {
- rule.styleMap.set(property, dynamicStyle[property]);
+ // 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 } = 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,
+ assets,
+ });
+
+ // find existing declarations and exclude currently set properties
+ // to delete the rest later
+ const deletedProperties = deletedPropertiesByRule.get(rule);
+ if (deletedProperties) {
+ deletedProperties.delete(property);
}
- // delete previously rendered properties when reset
- for (const property of rule.styleMap.keys()) {
- if (dynamicStyle[property] === undefined) {
- rule.styleMap.delete(property);
+
+ // We don't want to wrap backgroundClip into a var, because it's not supported by CSS variables
+ // It's fine because we don't need to update it dynamically via CSS variables during preview changes
+ // we renrender it anyway when CSS update happens
+ if (property === "backgroundClip") {
+ rule.styleMap.set(property, value);
+ } else {
+ const varValue = toVarValue(instanceId, property, value);
+ if (varValue) {
+ rule.styleMap.set(property, varValue);
}
}
}
+
+ // delete previously rendered properties when reset
+ for (const [styleRule, deletedProperties] of deletedPropertiesByRule) {
+ for (const property of deletedProperties) {
+ styleRule.styleMap.delete(property);
+ }
+ }
+
cssEngine.render();
- }, [instanceId, instanceStyles, breakpoints]);
+ }, [instanceId, selectedState, instanceStyles, breakpoints]);
};
const toVarNamespace = (id: string, property: string) => {
@@ -296,23 +331,22 @@ const useUpdateStyle = () => {
};
const usePreviewStyle = () => {
- useSubscribe("previewStyle", ({ id, updates, breakpoint }) => {
- let rule = getRule(id, breakpoint.id);
-
- if (rule === undefined) {
- const assets = assetsStore.get();
- rule = addRule(id, { breakpoint: breakpoint.id, style: {} }, assets);
- }
+ useSubscribe("previewStyle", ({ id, updates, breakpoint, state }) => {
+ const rule = getOrCreateRule({
+ instanceId: id,
+ breakpointId: breakpoint.id,
+ state,
+ assets: assetsStore.get(),
+ });
for (const update of updates) {
if (update.operation === "set") {
// This is possible on newly created instances, properties are not yet defined in the style.
if (rule.styleMap.has(update.property) === false) {
- const dynamicStyle = toVarStyleWithFallback(id, {
- [update.property]: update.value,
- });
-
- rule.styleMap.set(update.property, dynamicStyle[update.property]);
+ const varValue = toVarValue(id, update.property, update.value);
+ if (varValue) {
+ rule.styleMap.set(update.property, varValue);
+ }
}
setCssVar(id, update.property, update.value);
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.ts
index 8a4a209938..ca24c4bbd5 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts
@@ -19,6 +19,7 @@ import {
instancesStore,
selectedPageStore,
breakpointsStore,
+ selectedStyleSourceSelectorStore,
} from "../nano-states";
import {
type InstanceSelector,
@@ -218,6 +219,7 @@ export const onPaste = (clipboardData: string) => {
copiedRootInstanceId,
...instanceSelector,
]);
+ selectedStyleSourceSelectorStore.set(undefined);
}
);
};
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index 16ebc16cee..3808950990 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -7,6 +7,8 @@ import {
styleSourceSelectionsStore,
styleSourcesStore,
instancesStore,
+ selectedStyleSourceSelectorStore,
+ textEditingInstanceSelectorStore,
} from "./nano-states";
import {
type DroppableTarget,
@@ -34,6 +36,7 @@ export const insertNewComponentInstance = (
instance.id,
...dropTarget.parentSelector,
]);
+ selectedStyleSourceSelectorStore.set(undefined);
});
};
@@ -46,6 +49,7 @@ export const reparentInstance = (
reparentInstanceMutable(instances, targetInstanceSelector, dropTarget);
});
selectedInstanceSelectorStore.set(targetInstanceSelector);
+ selectedStyleSourceSelectorStore.set(undefined);
});
};
@@ -123,6 +127,7 @@ export const deleteInstance = (instanceSelector: InstanceSelector) => {
selectedInstanceSelectorStore.set(
getAncestorInstanceSelector(instanceSelector, parentInstance.id)
);
+ selectedStyleSourceSelectorStore.set(undefined);
}
}
);
@@ -142,3 +147,18 @@ export const deleteSelectedInstance = () => {
deleteInstance(selectedInstanceSelector);
});
};
+
+export const escapeSelection = () => {
+ const selectedInstanceSelector = selectedInstanceSelectorStore.get();
+ const textEditingInstanceSelector = textEditingInstanceSelectorStore.get();
+ if (selectedInstanceSelector === undefined) {
+ return;
+ }
+ // exit text editing mode first without unselecting instance
+ if (textEditingInstanceSelector) {
+ textEditingInstanceSelectorStore.set(undefined);
+ return;
+ }
+ selectedInstanceSelectorStore.set(undefined);
+ selectedStyleSourceSelectorStore.set(undefined);
+};
diff --git a/apps/builder/app/shared/nano-states/instances.ts b/apps/builder/app/shared/nano-states/instances.ts
index 53b9331106..354bab3385 100644
--- a/apps/builder/app/shared/nano-states/instances.ts
+++ b/apps/builder/app/shared/nano-states/instances.ts
@@ -45,20 +45,6 @@ export const enterEditingMode = (event?: KeyboardEvent) => {
textEditingInstanceSelectorStore.set(selectedInstanceSelector);
};
-export const escapeSelection = () => {
- const selectedInstanceSelector = selectedInstanceSelectorStore.get();
- const textEditingInstanceSelector = textEditingInstanceSelectorStore.get();
- if (selectedInstanceSelector === undefined) {
- return;
- }
- // exit text editing mode first without unselecting instance
- if (textEditingInstanceSelector) {
- textEditingInstanceSelectorStore.set(undefined);
- return;
- }
- selectedInstanceSelectorStore.set(undefined);
-};
-
export const instancesStore = atom<Instances>(new Map());
export const useSetInstances = (instances: [Instance["id"], Instance][]) => {
useSyncInitializeOnce(() => {
diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts
index 01521532fe..6a8603ae3c 100644
--- a/apps/builder/app/shared/sync/sync-stores.ts
+++ b/apps/builder/app/shared/sync/sync-stores.ts
@@ -22,6 +22,7 @@ import {
synchronizedCanvasStores,
synchronizedInstancesStores,
synchronizedBreakpointsStores,
+ selectedStyleSourceSelectorStore,
} from "~/shared/nano-states";
enableMapSet();
@@ -76,9 +77,12 @@ export const registerContainers = () => {
"selectedInstanceUnitSizesStore",
selectedInstanceUnitSizesStore
);
-
clientStores.set("hoveredInstanceSelector", hoveredInstanceSelectorStore);
clientStores.set("isPreviewMode", isPreviewModeStore);
+ clientStores.set(
+ "selectedStyleSourceSelector",
+ selectedStyleSourceSelectorStore
+ );
for (const [name, store] of synchronizedBreakpointsStores) {
clientStores.set(name, store);
}
diff --git a/packages/css-data/src/schema.ts b/packages/css-data/src/schema.ts
index 5bbe711090..b89b404a6e 100644
--- a/packages/css-data/src/schema.ts
+++ b/packages/css-data/src/schema.ts
@@ -128,22 +128,6 @@ export const LayersValue = z.object({
export type LayersValue = z.infer<typeof LayersValue>;
-/**
- * All StyleValue types that going to need wrapping into a CSS variable when rendered
- * on canvas inside builder.
- * Values like InvalidValue, UnsetValue, VarValue don't need to be wrapped
- */
-export const validStaticValueTypes = [
- "unit",
- "keyword",
- "fontFamily",
- "rgb",
- "image",
- "unparsed",
- "layers",
- "tuple",
-] as const;
-
const ValidStaticStyleValue = z.union([
ImageValue,
LayersValue,
@@ -157,6 +141,28 @@ const ValidStaticStyleValue = z.union([
export type ValidStaticStyleValue = z.infer<typeof ValidStaticStyleValue>;
+/**
+ * All StyleValue types that going to need wrapping into a CSS variable when rendered
+ * on canvas inside builder.
+ * Values like InvalidValue, UnsetValue, VarValue don't need to be wrapped
+ */
+export const isValidStaticStyleValue = (
+ styleValue: StyleValue
+): styleValue is ValidStaticStyleValue => {
+ // guard against invalid checks
+ const staticStyleValue = styleValue as ValidStaticStyleValue;
+ return (
+ staticStyleValue.type === "image" ||
+ staticStyleValue.type === "layers" ||
+ staticStyleValue.type === "unit" ||
+ staticStyleValue.type === "keyword" ||
+ staticStyleValue.type === "fontFamily" ||
+ staticStyleValue.type === "rgb" ||
+ staticStyleValue.type === "unparsed" ||
+ staticStyleValue.type === "tuple"
+ );
+};
+
const VarValue = z.object({
type: z.literal("var"),
value: z.string(),
@@ -178,10 +184,3 @@ const Style = z.record(z.string(), StyleValue);
export type Style = {
[property in StyleProperty]?: StyleValue;
} & { [property: CustomProperty]: StyleValue };
-
-export const CssRule = z.object({
- style: Style,
- breakpoint: z.optional(z.string()),
-});
-
-export type CssRule = z.infer<typeof CssRule>;
diff --git a/packages/css-engine/src/core/css-engine.stories.tsx b/packages/css-engine/src/core/css-engine.stories.tsx
index ae14a60aee..996c71f7fb 100644
--- a/packages/css-engine/src/core/css-engine.stories.tsx
+++ b/packages/css-engine/src/core/css-engine.stories.tsx
@@ -34,7 +34,7 @@ export const Basic = () => {
onClick={() => {
engine.addStyleRule(".test", {
style: {
- background: { type: "keyword", value: "yellow" },
+ backgroundColor: { type: "keyword", value: "yellow" },
},
breakpoint: "0",
});
diff --git a/packages/css-engine/src/core/css-engine.ts b/packages/css-engine/src/core/css-engine.ts
index fbc7eeebe1..f47c18cd87 100644
--- a/packages/css-engine/src/core/css-engine.ts
+++ b/packages/css-engine/src/core/css-engine.ts
@@ -1,4 +1,4 @@
-import type { CssRule } from "@webstudio-is/css-data";
+import type { Style } from "@webstudio-is/css-data";
import {
FontFaceRule,
MediaRule,
@@ -14,6 +14,11 @@ import type { TransformValue } from "./to-value";
const defaultMediaRuleId = "__default-media-rule__";
+type CssRule = {
+ style: Style;
+ breakpoint?: string;
+};
+
export type CssEngineOptions = { name?: string };
export class CssEngine {
diff --git a/packages/react-sdk/src/css/css.ts b/packages/react-sdk/src/css/css.ts
index 3d5e0bcccf..6d5a70d1f1 100644
--- a/packages/react-sdk/src/css/css.ts
+++ b/packages/react-sdk/src/css/css.ts
@@ -77,9 +77,9 @@ export const generateCssText = (data: Data, options: CssOptions) => {
}
const styleRules = getStyleRules(styles, styleSourceSelections);
- for (const { breakpointId, instanceId, style } of styleRules) {
+ for (const { breakpointId, instanceId, state, style } of styleRules) {
engine.addStyleRule(
- `[${idAttribute}="${instanceId}"]`,
+ `[${idAttribute}="${instanceId}"]${state ?? ""}`,
{
breakpoint: breakpointId,
style,
diff --git a/packages/react-sdk/src/css/style-rules.test.ts b/packages/react-sdk/src/css/style-rules.test.ts
index 47e5ec116f..9443d27d37 100644
--- a/packages/react-sdk/src/css/style-rules.test.ts
+++ b/packages/react-sdk/src/css/style-rules.test.ts
@@ -55,6 +55,13 @@ test("compute styles from different style sources", () => {
property: "color",
value: { type: "keyword", value: "blue" },
}),
+ createStyleDeclPair({
+ breakpointId: "a",
+ styleSourceId: "styleSource6",
+ state: ":hover",
+ property: "color",
+ value: { type: "keyword", value: "blue" },
+ }),
]);
const styleSourceSelections: StyleSourceSelections = new Map([
[
@@ -85,6 +92,7 @@ test("compute styles from different style sources", () => {
{
"breakpointId": "a",
"instanceId": "instance1",
+ "state": undefined,
"style": {
"width": {
"type": "unit",
@@ -96,6 +104,7 @@ test("compute styles from different style sources", () => {
{
"breakpointId": "a",
"instanceId": "instance2",
+ "state": undefined,
"style": {
"color": {
"type": "keyword",
@@ -110,6 +119,7 @@ test("compute styles from different style sources", () => {
{
"breakpointId": "b",
"instanceId": "instance2",
+ "state": undefined,
"style": {
"color": {
"type": "keyword",
@@ -120,6 +130,18 @@ test("compute styles from different style sources", () => {
{
"breakpointId": "a",
"instanceId": "instance3",
+ "state": undefined,
+ "style": {
+ "color": {
+ "type": "keyword",
+ "value": "blue",
+ },
+ },
+ },
+ {
+ "breakpointId": "a",
+ "instanceId": "instance3",
+ "state": ":hover",
"style": {
"color": {
"type": "keyword",
diff --git a/packages/react-sdk/src/css/style-rules.ts b/packages/react-sdk/src/css/style-rules.ts
index 7872ae0bd8..ac541253f9 100644
--- a/packages/react-sdk/src/css/style-rules.ts
+++ b/packages/react-sdk/src/css/style-rules.ts
@@ -10,6 +10,7 @@ import type {
type StyleRule = {
instanceId: string;
breakpointId: string;
+ state: undefined | string;
style: Style;
};
@@ -38,7 +39,10 @@ export const getStyleRules = (
const styleRules: StyleRule[] = [];
for (const { instanceId, values } of styleSourceSelections.values()) {
- const styleRuleByBreakpointId = new Map<Breakpoint["id"], StyleRule>();
+ const styleRuleByBreakpointId = new Map<
+ `${Breakpoint["id"]}:${string}`,
+ StyleRule
+ >();
for (const styleSourceId of values) {
const styleSourceStyles = stylesByStyleSourceId.get(styleSourceId);
@@ -46,15 +50,22 @@ export const getStyleRules = (
if (styleSourceStyles === undefined) {
continue;
}
- for (const { breakpointId, property, value } of styleSourceStyles) {
- let styleRule = styleRuleByBreakpointId.get(breakpointId);
+ for (const {
+ breakpointId,
+ state,
+ property,
+ value,
+ } of styleSourceStyles) {
+ const key = `${breakpointId}:${state ?? ""}` as const;
+ let styleRule = styleRuleByBreakpointId.get(key);
if (styleRule === undefined) {
styleRule = {
instanceId,
breakpointId,
+ state,
style: {},
};
- styleRuleByBreakpointId.set(breakpointId, styleRule);
+ styleRuleByBreakpointId.set(key, styleRule);
}
styleRule.style[property] = value;
}