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: render ephemeral styles with synced store (#2512)

Bogdan Chadkin45f311150cf9
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index 7d0db950fd..a99e4891f6 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -332,7 +332,7 @@ export const Builder = ({
isPreviewMode={isPreviewMode}
css={{ overflow: "hidden" }}
>
- <Inspector publish={publish} navigatorLayout={navigatorLayout} />
+ <Inspector navigatorLayout={navigatorLayout} />
</SidePanel>
{isPreviewMode === false && <Footer />}
<BlockingAlerts />
diff --git a/apps/builder/app/builder/features/inspector/inspector.tsx b/apps/builder/app/builder/features/inspector/inspector.tsx
index 5165d3605e..3914af46a7 100644
--- a/apps/builder/app/builder/features/inspector/inspector.tsx
+++ b/apps/builder/app/builder/features/inspector/inspector.tsx
@@ -15,7 +15,6 @@ import {
Flex,
ScrollArea,
} from "@webstudio-is/design-system";
-import type { Publish } from "~/shared/pubsub";
import { StylePanel } from "~/builder/features/style-panel";
import { SettingsPanelContainer } from "~/builder/features/settings-panel";
import { FloatingPanelProvider } from "~/builder/shared/floating-panel";
@@ -56,7 +55,6 @@ const InstanceInfo = ({ instance }: { instance: Instance }) => {
};
type InspectorProps = {
- publish: Publish;
navigatorLayout: Settings["navigatorLayout"];
};
@@ -68,7 +66,7 @@ const contentStyle = {
const $isDragging = computed([$dragAndDropState], (state) => state.isDragging);
-export const Inspector = ({ publish, navigatorLayout }: InspectorProps) => {
+export const Inspector = ({ navigatorLayout }: InspectorProps) => {
const selectedInstance = useStore(selectedInstanceStore);
const tabsRef = useRef<HTMLDivElement>(null);
const [tab, setTab] = useState("style");
@@ -122,16 +120,12 @@ export const Inspector = ({ publish, navigatorLayout }: InspectorProps) => {
</PanelTabsList>
<PanelTabsContent value="style" css={contentStyle} tabIndex={-1}>
<InstanceInfo instance={selectedInstance} />
- <StylePanel
- publish={publish}
- selectedInstance={selectedInstance}
- />
+ <StylePanel selectedInstance={selectedInstance} />
</PanelTabsContent>
<PanelTabsContent value="settings" css={contentStyle} tabIndex={-1}>
<ScrollArea>
<InstanceInfo instance={selectedInstance} />
<SettingsPanelContainer
- publish={publish}
key={
selectedInstance.id /* Re-render when instance changes */
}
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx
index 897ac3e9d4..1ffe28c961 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx
+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx
@@ -14,7 +14,6 @@ import {
InputField,
NestedInputButton,
} from "@webstudio-is/design-system";
-import type { Publish } from "~/shared/pubsub";
import {
dataSourceVariablesStore,
propsIndexStore,
@@ -198,14 +197,11 @@ export const PropsSection = (props: PropsSectionProps) => {
export const PropsSectionContainer = ({
selectedInstance: instance,
- publish,
}: {
- publish: Publish;
selectedInstance: Instance;
}) => {
const { setProperty: setCssProperty } = useStyleData({
selectedInstance: instance,
- publish,
});
const { propsByInstanceId } = useStore(propsIndexStore);
diff --git a/apps/builder/app/builder/features/settings-panel/settings-panel.tsx b/apps/builder/app/builder/features/settings-panel/settings-panel.tsx
index fde57c2bef..0e915af669 100644
--- a/apps/builder/app/builder/features/settings-panel/settings-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/settings-panel.tsx
@@ -1,22 +1,16 @@
import type { Instance } from "@webstudio-is/sdk";
-import type { Publish } from "~/shared/pubsub";
import { SettingsSection } from "./settings-section/settings-section";
import { PropsSectionContainer } from "./props-section/props-section";
export const SettingsPanelContainer = ({
selectedInstance,
- publish,
}: {
- publish: Publish;
selectedInstance: Instance;
}) => {
return (
<>
<SettingsSection />
- <PropsSectionContainer
- publish={publish}
- selectedInstance={selectedInstance}
- />
+ <PropsSectionContainer selectedInstance={selectedInstance} />
</>
);
};
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 2a5b3ef950..55edc74112 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
@@ -6,7 +6,6 @@ import {
getStyleDeclKey,
} from "@webstudio-is/sdk";
import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";
-import type { Publish } from "~/shared/pubsub";
import {
selectedBreakpointStore,
selectedOrLastStyleSourceSelectorStore,
@@ -17,6 +16,7 @@ import {
} from "~/shared/nano-states";
import { useStyleInfo } from "./style-info";
import { serverSyncStore } from "~/shared/sync";
+import { $ephemeralStyles } from "~/canvas/stores";
export type StyleUpdate =
| {
@@ -29,22 +29,14 @@ export type StyleUpdate =
value: StyleValue;
};
-export type StyleUpdates = {
+type StyleUpdates = {
id: Instance["id"];
updates: Array<StyleUpdate>;
breakpoint: Breakpoint;
state: undefined | string;
};
-declare module "~/shared/pubsub" {
- export interface PubsubMap {
- updateStyle: StyleUpdates;
- previewStyle: StyleUpdates;
- }
-}
-
type UseStyleData = {
- publish: Publish;
selectedInstance: Instance;
};
@@ -68,7 +60,7 @@ export type CreateBatchUpdate = () => {
publish: (options?: StyleUpdateOptions) => void;
};
-export const useStyleData = ({ selectedInstance, publish }: UseStyleData) => {
+export const useStyleData = ({ selectedInstance }: UseStyleData) => {
const selectedBreakpoint = useStore(selectedBreakpointStore);
const currentStyle = useStyleInfo();
@@ -86,20 +78,25 @@ export const useStyleData = ({ selectedInstance, publish }: UseStyleData) => {
) {
return;
}
- publish({
- type: type === "update" ? "updateStyle" : "previewStyle",
- payload: {
- id: selectedInstance.id,
- updates,
- breakpoint: selectedBreakpoint,
- state: styleSourceSelector.state,
- },
- });
-
- if (type !== "update") {
+
+ if (type === "preview") {
+ const ephemeralStyles: ReturnType<typeof $ephemeralStyles.get> = [];
+ for (const update of updates) {
+ if (update.operation === "set") {
+ ephemeralStyles.push({
+ instanceId: selectedInstance.id,
+ breakpointId: selectedBreakpoint.id,
+ state: styleSourceSelector.state,
+ property: update.property,
+ value: update.value,
+ });
+ }
+ }
+ $ephemeralStyles.set(ephemeralStyles);
return;
}
+ $ephemeralStyles.set([]);
serverSyncStore.createTransaction(
[styleSourceSelectionsStore, styleSourcesStore, stylesStore],
(styleSourceSelections, styleSources, styles) => {
@@ -145,7 +142,7 @@ export const useStyleData = ({ selectedInstance, publish }: UseStyleData) => {
}
);
},
- [publish, selectedBreakpoint, selectedInstance]
+ [selectedBreakpoint, selectedInstance]
);
const setProperty = useCallback<SetProperty>(
diff --git a/apps/builder/app/builder/features/style-panel/style-panel.tsx b/apps/builder/app/builder/features/style-panel/style-panel.tsx
index fbd290fc1f..9edc9ea6bd 100644
--- a/apps/builder/app/builder/features/style-panel/style-panel.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-panel.tsx
@@ -7,7 +7,6 @@ import {
ScrollArea,
} from "@webstudio-is/design-system";
import type { Instance } from "@webstudio-is/sdk";
-import type { Publish } from "~/shared/pubsub";
import { useStyleData } from "./shared/use-style-data";
import { StyleSettings } from "./style-settings";
@@ -17,15 +16,13 @@ import { selectedInstanceRenderStateStore } from "~/shared/nano-states";
import { useStore } from "@nanostores/react";
type StylePanelProps = {
- publish: Publish;
selectedInstance: Instance;
};
-export const StylePanel = ({ selectedInstance, publish }: StylePanelProps) => {
+export const StylePanel = ({ selectedInstance }: StylePanelProps) => {
const { currentStyle, setProperty, deleteProperty, createBatchUpdate } =
useStyleData({
selectedInstance,
- publish,
});
const selectedInstanceRenderState = useStore(
diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts
index 407a5644cc..9968ac427e 100644
--- a/apps/builder/app/canvas/shared/styles.ts
+++ b/apps/builder/app/canvas/shared/styles.ts
@@ -32,7 +32,7 @@ import {
toValue,
compareMedia,
} from "@webstudio-is/css-engine";
-import { useSubscribe } from "~/shared/pubsub";
+import { $ephemeralStyles } from "../stores";
const userCssEngine = createCssEngine({ name: "user-styles" });
const helpersCssEngine = createCssEngine({ name: "helpers" });
@@ -113,9 +113,56 @@ const subscribePreviewMode = () => {
};
};
+const subscribeEphemeralStyle = (params: Params) => {
+ // track custom properties added on previous ephemeral styles change
+ const addedCustomProperties = new Set<string>();
+ return $ephemeralStyles.subscribe((ephemeralStyles) => {
+ // track custom properties not set on this change
+ const deletedCustomProperties = new Set(addedCustomProperties);
+
+ const assets = assetsStore.get();
+ const transformer = createImageValueTransformer(assets, {
+ assetBaseUrl: params.assetBaseUrl,
+ });
+ for (const styleDecl of ephemeralStyles) {
+ const { instanceId, breakpointId, state, property, value } = styleDecl;
+ const customProperty = `--${toVarNamespace(instanceId, property)}`;
+ document.body.style.setProperty(
+ customProperty,
+ toValue(value, transformer)
+ );
+ addedCustomProperties.add(customProperty);
+ deletedCustomProperties.delete(customProperty);
+
+ const rule = getOrCreateRule({
+ instanceId,
+ breakpointId,
+ state,
+ assets,
+ params,
+ });
+ // this is possible on newly created instances,
+ // properties are not yet defined in the style.
+ if (rule.styleMap.has(property) === false) {
+ const varValue = toVarValue(instanceId, property, value);
+ if (varValue) {
+ rule.styleMap.set(property, varValue);
+ }
+ }
+ }
+
+ for (const property of deletedCustomProperties) {
+ document.body.style.removeProperty(property);
+ addedCustomProperties.delete(property);
+ }
+
+ // rerender style rules if new vars added
+ userCssEngine.render();
+ });
+};
+
export const useManageDesignModeStyles = (params: Params) => {
- useUpdateStyle(params);
- usePreviewStyle(params);
+ useEffect(() => subscribeEphemeralStyle(params), [params]);
useEffect(subscribePreviewMode, []);
};
@@ -314,71 +361,3 @@ export const useCssRules = ({
const toVarNamespace = (id: string, property: string) => {
return `${property}-${id}`;
};
-
-const setCssVar = (
- params: Params,
- id: string,
- property: string,
- value?: StyleValue
-) => {
- const customProperty = `--${toVarNamespace(id, property)}`;
- if (value === undefined) {
- document.body.style.removeProperty(customProperty);
- return;
- }
-
- const assets = assetsStore.get();
- const transformer = createImageValueTransformer(assets, {
- assetBaseUrl: params.assetBaseUrl,
- });
-
- document.body.style.setProperty(customProperty, toValue(value, transformer));
-};
-
-const useUpdateStyle = (params: Params) => {
- useSubscribe("updateStyle", ({ id, updates }) => {
- const selectedInstanceSelector = selectedInstanceSelectorStore.get();
- const selectedInstanceId = selectedInstanceSelector?.[0];
- // Only update styles if they match the selected instance
- // It can potentially happen that we selected a difference instance right after we changed the style in style panel.
- if (id !== selectedInstanceId) {
- return;
- }
-
- for (const update of updates) {
- setCssVar(params, id, update.property, undefined);
- }
- });
-};
-
-const usePreviewStyle = (params: Params) => {
- useSubscribe("previewStyle", ({ id, updates, breakpoint, state }) => {
- const rule = getOrCreateRule({
- instanceId: id,
- breakpointId: breakpoint.id,
- state,
- assets: assetsStore.get(),
- params,
- });
-
- 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 varValue = toVarValue(id, update.property, update.value);
- if (varValue) {
- rule.styleMap.set(update.property, varValue);
- }
- }
-
- setCssVar(params, id, update.property, update.value);
- }
-
- if (update.operation === "delete") {
- setCssVar(params, id, update.property, undefined);
- }
- }
-
- userCssEngine.render();
- });
-};
diff --git a/apps/builder/app/canvas/stores.ts b/apps/builder/app/canvas/stores.ts
new file mode 100644
index 0000000000..0d1ee11d2b
--- /dev/null
+++ b/apps/builder/app/canvas/stores.ts
@@ -0,0 +1,12 @@
+import { atom } from "nanostores";
+import type { Instance, StyleDecl } from "@webstudio-is/sdk";
+
+export const $ephemeralStyles = atom<
+ Array<{
+ instanceId: Instance["id"];
+ breakpointId: StyleDecl["breakpointId"];
+ state: StyleDecl["state"];
+ property: StyleDecl["property"];
+ value: StyleDecl["value"];
+ }>
+>([]);
diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts
index 02be6e3e55..80ad8d5a3f 100644
--- a/apps/builder/app/shared/sync/sync-stores.ts
+++ b/apps/builder/app/shared/sync/sync-stores.ts
@@ -32,6 +32,7 @@ import {
dataSourceVariablesStore,
$dragAndDropState,
} from "~/shared/nano-states";
+import { $ephemeralStyles } from "~/canvas/stores";
enableMapSet();
@@ -107,6 +108,7 @@ export const registerContainers = () => {
selectedStyleSourceSelectorStore
);
clientStores.set("dragAndDropState", $dragAndDropState);
+ clientStores.set("ephemeralStyles", $ephemeralStyles);
for (const [name, store] of synchronizedBreakpointsStores) {
clientStores.set(name, store);
}