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: move selected instance store into awareness (#4388)

Bogdan Chadkina1c05ba7687f
diff --git a/apps/builder/app/builder/features/ai/ai-fetch-result.ts b/apps/builder/app/builder/features/ai/ai-fetch-result.ts
index adc78c12c0..2b2d6076cf 100644
--- a/apps/builder/app/builder/features/ai/ai-fetch-result.ts
+++ b/apps/builder/app/builder/features/ai/ai-fetch-result.ts
@@ -22,7 +22,6 @@ import {
$project,
$props,
$registeredComponentMetas,
- $selectedInstanceSelector,
$styleSourceSelections,
$styles,
} from "~/shared/nano-states";
@@ -37,6 +36,7 @@ import {
} from "./api-exceptions";
import { isFeatureEnabled } from "@webstudio-is/feature-flags";
import { fetch } from "~/shared/fetch.client";
+import { $selectedInstance } from "~/shared/awareness";
const unknownArray = z.array(z.unknown());
@@ -253,7 +253,7 @@ const restoreComponentsNamespace = (operations: operations.WsOperations) => {
const $jsx = computed(
[
- $selectedInstanceSelector,
+ $selectedInstance,
$instances,
$props,
$dataSources,
@@ -262,7 +262,7 @@ const $jsx = computed(
$styleSourceSelections,
],
(
- selectedInstanceSelector,
+ instance,
instances,
props,
dataSources,
@@ -270,17 +270,12 @@ const $jsx = computed(
styles,
styleSourceSelections
) => {
- if (selectedInstanceSelector === undefined) {
- return;
- }
-
- const [rootInstanceId] = selectedInstanceSelector;
- const instance = instances.get(rootInstanceId);
if (instance === undefined) {
return;
}
+
const indexesWithinAncestors = getIndexesWithinAncestors(metas, instances, [
- rootInstanceId,
+ instance.id,
]);
const scope = createScope();
@@ -303,7 +298,7 @@ const $jsx = computed(
}),
});
- const treeInstanceIds = findTreeInstanceIds(instances, rootInstanceId);
+ const treeInstanceIds = findTreeInstanceIds(instances, instance.id);
const sheet = createRegularStyleSheet({ name: "ssr" });
for (const styleDecl of styles.values()) {
diff --git a/apps/builder/app/builder/features/ai/apply-operations.ts b/apps/builder/app/builder/features/ai/apply-operations.ts
index b15e2ddd62..40839b7db0 100644
--- a/apps/builder/app/builder/features/ai/apply-operations.ts
+++ b/apps/builder/app/builder/features/ai/apply-operations.ts
@@ -1,6 +1,8 @@
-import { serverSyncStore } from "~/shared/sync";
+import { nanoid } from "nanoid";
+import { getStyleDeclKey, Instance, type StyleSource } from "@webstudio-is/sdk";
import { generateDataFromEmbedTemplate } from "@webstudio-is/react-sdk";
import type { copywriter, operations } from "@webstudio-is/ai";
+import { serverSyncStore } from "~/shared/sync";
import { isBaseBreakpoint } from "~/shared/breakpoints";
import {
deleteInstanceMutable,
@@ -12,14 +14,12 @@ import {
$instances,
$registeredComponentMetas,
$selectedInstanceSelector,
- $selectedInstance,
$styleSourceSelections,
$styleSources,
$styles,
} from "~/shared/nano-states";
import type { DroppableTarget, InstanceSelector } from "~/shared/tree-utils";
-import { getStyleDeclKey, Instance, type StyleSource } from "@webstudio-is/sdk";
-import { nanoid } from "nanoid";
+import { $selectedInstance } from "~/shared/awareness";
export const applyOperations = (operations: operations.WsOperations) => {
for (const operation of operations) {
diff --git a/apps/builder/app/builder/features/inspector/inspector.tsx b/apps/builder/app/builder/features/inspector/inspector.tsx
index f30164460c..fbbaebf117 100644
--- a/apps/builder/app/builder/features/inspector/inspector.tsx
+++ b/apps/builder/app/builder/features/inspector/inspector.tsx
@@ -22,7 +22,6 @@ import { StylePanel } from "~/builder/features/style-panel";
import { SettingsPanelContainer } from "~/builder/features/settings-panel";
import { FloatingPanelProvider } from "~/builder/shared/floating-panel";
import {
- $selectedInstance,
$registeredComponentMetas,
$dragAndDropState,
} from "~/shared/nano-states";
@@ -32,7 +31,7 @@ import { MetaIcon } from "~/builder/shared/meta-icon";
import { getInstanceLabel } from "~/shared/instance-utils";
import { BindingPopoverProvider } from "~/builder/shared/binding-popover";
import { $activeInspectorPanel } from "~/builder/shared/nano-states";
-import { $selectedPage } from "~/shared/awareness";
+import { $selectedInstance, $selectedPage } from "~/shared/awareness";
const InstanceInfo = ({ instance }: { instance: Instance }) => {
const metas = useStore($registeredComponentMetas);
diff --git a/apps/builder/app/builder/features/navigator/css-preview.tsx b/apps/builder/app/builder/features/navigator/css-preview.tsx
index 68961f831b..18ab928af5 100644
--- a/apps/builder/app/builder/features/navigator/css-preview.tsx
+++ b/apps/builder/app/builder/features/navigator/css-preview.tsx
@@ -15,8 +15,8 @@ import type { StyleMap, StyleProperty } from "@webstudio-is/css-engine";
import { CollapsibleSection } from "~/builder/shared/collapsible-section";
import { highlightCss } from "~/builder/shared/code-highlight";
import type { ComputedStyleDecl } from "~/shared/style-object-model";
-import { $selectedInstanceSelector } from "~/shared/nano-states";
import { $definedComputedStyles } from "~/builder/features/style-panel/shared/model";
+import { $selectedInstance } from "~/shared/awareness";
const preStyle = css(textVariants.mono, {
margin: 0,
@@ -80,13 +80,12 @@ const getCssText = (
};
const $highlightedCss = computed(
- [$selectedInstanceSelector, $definedComputedStyles],
- (instanceSelector, computedStyles) => {
- if (instanceSelector === undefined) {
+ [$selectedInstance, $definedComputedStyles],
+ (instance, computedStyles) => {
+ if (instance === undefined) {
return;
}
- const [instanceId] = instanceSelector;
- const cssText = getCssText(computedStyles, instanceId);
+ const cssText = getCssText(computedStyles, instance.id);
return highlightCss(cssText);
}
);
diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
index 17cd6e5b05..8afa30bd29 100644
--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
@@ -55,7 +55,7 @@ import {
EditorDialogControl,
} from "~/builder/shared/code-editor-base";
import { parseCurl, type CurlRequest } from "./curl";
-import { $selectedPage } from "~/shared/awareness";
+import { $selectedInstance, $selectedPage } from "~/shared/awareness";
const validateUrl = (value: string, scope: Record<string, unknown>) => {
const evaluatedValue = evaluateExpressionWithinScope(value, scope);
@@ -581,12 +581,11 @@ export const ResourceForm = forwardRef<
useImperativeHandle(ref, () => ({
save: (formData) => {
- const instanceSelector = $selectedInstanceSelector.get();
- if (instanceSelector === undefined) {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
return;
}
const name = z.string().parse(formData.get("name"));
- const [instanceId] = instanceSelector;
const newResource: Resource = {
id: resource?.id ?? nanoid(),
name,
@@ -715,12 +714,11 @@ export const SystemResourceForm = forwardRef<
useImperativeHandle(ref, () => ({
save: (formData) => {
- const instanceSelector = $selectedInstanceSelector.get();
- if (instanceSelector === undefined) {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
return;
}
const name = z.string().parse(formData.get("name"));
- const [instanceId] = instanceSelector;
const newResource: Resource = {
id: resource?.id ?? nanoid(),
name,
@@ -826,8 +824,8 @@ export const GraphqlResourceForm = forwardRef<
useImperativeHandle(ref, () => ({
save: (formData) => {
- const instanceSelector = $selectedInstanceSelector.get();
- if (instanceSelector === undefined) {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
return;
}
const name = z.string().parse(formData.get("name"));
@@ -837,7 +835,6 @@ export const GraphqlResourceForm = forwardRef<
["variables", variables],
])
);
- const [instanceId] = instanceSelector;
const newResource: Resource = {
id: resource?.id ?? nanoid(),
name,
diff --git a/apps/builder/app/builder/features/settings-panel/settings-section.tsx b/apps/builder/app/builder/features/settings-panel/settings-section.tsx
index 622cd16eaf..3b4d6f0703 100644
--- a/apps/builder/app/builder/features/settings-panel/settings-section.tsx
+++ b/apps/builder/app/builder/features/settings-panel/settings-section.tsx
@@ -1,14 +1,11 @@
import { useStore } from "@nanostores/react";
+import type { Instance } from "@webstudio-is/sdk";
import { InputField, useId } from "@webstudio-is/design-system";
-import {
- $instances,
- $registeredComponentMetas,
- $selectedInstance,
-} from "~/shared/nano-states";
+import { $instances, $registeredComponentMetas } from "~/shared/nano-states";
import { HorizontalLayout, Label, Row, useLocalValue } from "./shared";
import { getInstanceLabel } from "~/shared/instance-utils";
import { serverSyncStore } from "~/shared/sync";
-import type { Instance } from "@webstudio-is/sdk";
+import { $selectedInstance } from "~/shared/awareness";
const saveLabel = (label: string, selectedInstance: Instance) => {
serverSyncStore.createTransaction([$instances], (instances) => {
diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
index 244d7ceda7..4947718249 100644
--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
@@ -52,7 +52,6 @@ import {
$dataSources,
$resources,
$areResourcesLoading,
- $selectedInstanceSelector,
invalidateResource,
getComputedResource,
} from "~/shared/nano-states";
@@ -71,6 +70,7 @@ import {
SystemResourceForm,
} from "./resource-panel";
import { generateCurl } from "./curl";
+import { $selectedInstance } from "~/shared/awareness";
const validateName = (value: string) =>
value.trim().length === 0 ? "Name is required" : "";
@@ -241,11 +241,10 @@ const useValuePanelRef = ({
}) => {
useImperativeHandle(ref, () => ({
save: (formData) => {
- const instanceSelector = $selectedInstanceSelector.get();
- if (instanceSelector === undefined) {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
return;
}
- const [instanceId] = instanceSelector;
const dataSourceId = variable?.id ?? nanoid();
// preserve existing instance scope when edit
const scopeInstanceId = variable?.scopeInstanceId ?? instanceId;
diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.tsx
index 9e8597202d..0a0841e921 100644
--- a/apps/builder/app/builder/features/settings-panel/variables-section.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variables-section.tsx
@@ -46,21 +46,20 @@ import {
VariablePopoverProvider,
VariablePopoverTrigger,
} from "./variable-popover";
-import { $selectedPage } from "~/shared/awareness";
+import { $selectedInstance, $selectedPage } from "~/shared/awareness";
/**
* find variables defined specifically on this selected instance
*/
const $instanceVariables = computed(
- [$selectedInstanceSelector, $dataSources],
- (instanceSelector, dataSources) => {
+ [$selectedInstance, $dataSources],
+ (instance, dataSources) => {
const matchedVariables: DataSource[] = [];
- if (instanceSelector === undefined) {
+ if (instance === undefined) {
return matchedVariables;
}
- const [instanceId] = instanceSelector;
for (const dataSource of dataSources.values()) {
- if (instanceId === dataSource.scopeInstanceId) {
+ if (instance.id === dataSource.scopeInstanceId) {
matchedVariables.push(dataSource);
}
}
diff --git a/apps/builder/app/builder/features/style-panel/property-label.tsx b/apps/builder/app/builder/features/style-panel/property-label.tsx
index 7d43394647..26f58ca920 100644
--- a/apps/builder/app/builder/features/style-panel/property-label.tsx
+++ b/apps/builder/app/builder/features/style-panel/property-label.tsx
@@ -24,7 +24,6 @@ import {
$instances,
$registeredComponentMetas,
$styleSources,
- $virtualInstances,
} from "~/shared/nano-states";
import { getInstanceLabel } from "~/shared/instance-utils";
import type {
@@ -34,6 +33,7 @@ import type {
import { useComputedStyles } from "./shared/model";
import { StyleSourceBadge } from "./style-source";
import { createBatchUpdate } from "./shared/use-style-data";
+import { $virtualInstances } from "~/shared/awareness";
const $isAltPressed = atom(false);
if (typeof window !== "undefined") {
diff --git a/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.stories.tsx
index 0d220e4637..5d9fceabdf 100644
--- a/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.stories.tsx
+++ b/apps/builder/app/builder/features/style-panel/sections/advanced/advanced.stories.tsx
@@ -3,6 +3,7 @@ import { registerContainers } from "~/shared/sync";
import { Section } from "./advanced";
import {
$breakpoints,
+ $instances,
$selectedBreakpointId,
$styles,
$styleSourceSelections,
@@ -27,6 +28,11 @@ $styles.set(new Map([[getStyleDeclKey(backgroundImage), backgroundImage]]));
$styleSourceSelections.set(
new Map([["box", { instanceId: "box", values: ["local"] }]])
);
+$instances.set(
+ new Map([
+ ["box", { type: "instance", id: "box", component: "Box", children: [] }],
+ ])
+);
$awareness.set({
pageId: "",
instanceSelector: ["box"],
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx
index c896495943..495371b97e 100644
--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx
@@ -3,6 +3,7 @@ import { styled, theme } from "@webstudio-is/design-system";
import { registerContainers } from "~/shared/sync";
import {
$breakpoints,
+ $instances,
$selectedBreakpointId,
$styles,
$styleSourceSelections,
@@ -40,6 +41,11 @@ $styles.set(new Map([[getStyleDeclKey(backgroundImage), backgroundImage]]));
$styleSourceSelections.set(
new Map([["box", { instanceId: "box", values: ["local"] }]])
);
+$instances.set(
+ new Map([
+ ["box", { type: "instance", id: "box", component: "Box", children: [] }],
+ ])
+);
$awareness.set({
pageId: "",
instanceSelector: ["box"],
diff --git a/apps/builder/app/builder/features/style-panel/shared/instances-kv.ts b/apps/builder/app/builder/features/style-panel/shared/instances-kv.ts
index af0106238e..0353631cdf 100644
--- a/apps/builder/app/builder/features/style-panel/shared/instances-kv.ts
+++ b/apps/builder/app/builder/features/style-panel/shared/instances-kv.ts
@@ -1,7 +1,7 @@
import { useStore } from "@nanostores/react";
import { map } from "nanostores";
import { useCallback } from "react";
-import { $selectedInstanceSelector } from "~/shared/nano-states";
+import { $selectedInstance } from "~/shared/awareness";
const instancesKv = map<Record<string, unknown>>({});
@@ -11,24 +11,19 @@ const instancesKv = map<Record<string, unknown>>({});
* allowing the default UI behavior to be used until the user modifies the state.
*/
export const useSelectedInstanceKv = <T>(key: string, defaultValue: T) => {
- const instanceSelector = useStore($selectedInstanceSelector);
- const keyInstanceSelector = instanceSelector
- ? `${instanceSelector.join(",")}-${key}`
- : `undefined-${key}`;
+ const instance = useStore($selectedInstance);
+ const instanceKey = `${instance?.id}-${key}`;
const mapStore = useStore(instancesKv, {
- keys: [keyInstanceSelector],
+ keys: [instanceKey],
});
const setValue = useCallback(
(value: T) => {
- instancesKv.setKey(keyInstanceSelector, value);
+ instancesKv.setKey(instanceKey, value);
},
- [keyInstanceSelector]
+ [instanceKey]
);
- return [
- (mapStore[keyInstanceSelector] as T) ?? defaultValue,
- setValue,
- ] as const;
+ return [(mapStore[instanceKey] as T) ?? defaultValue, setValue] as const;
};
diff --git a/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts b/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts
index 7dad39b4b3..b499147aa7 100644
--- a/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts
+++ b/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts
@@ -19,6 +19,7 @@ import { createComputedStyleDeclStore } from "./model";
import { parseCssFragment } from "./css-fragment";
import {
$breakpoints,
+ $instances,
$selectedBreakpointId,
$styles,
$styleSources,
@@ -39,6 +40,11 @@ beforeEach(() => {
pageId: "",
instanceSelector: ["box"],
});
+ $instances.set(
+ new Map([
+ ["box", { type: "instance", id: "box", component: "Box", children: [] }],
+ ])
+ );
$styleSourceSelections.set(new Map());
$styleSources.set(new Map());
$styles.set(new Map());
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 daa041ae73..545b16530f 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
@@ -7,7 +7,6 @@ import {
import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";
import {
$selectedBreakpoint,
- $selectedInstanceSelector,
$selectedOrLastStyleSourceSelector,
$selectedStyleSource,
$styleSourceSelections,
@@ -16,6 +15,7 @@ import {
} from "~/shared/nano-states";
import { serverSyncStore } from "~/shared/sync";
import { $ephemeralStyles } from "~/canvas/stores";
+import { $selectedInstance } from "~/shared/awareness";
export type StyleUpdate =
| {
@@ -64,14 +64,13 @@ const publishUpdates = (
return;
}
- const selectedInstanceSelector = $selectedInstanceSelector.get();
- const selectedInstanceId = selectedInstanceSelector?.[0];
+ const selectedInstance = $selectedInstance.get();
const selectedBreakpoint = $selectedBreakpoint.get();
const selectedStyleSource = $selectedStyleSource.get();
const styleSourceSelector = $selectedOrLastStyleSourceSelector.get();
if (
- selectedInstanceId === undefined ||
+ selectedInstance === undefined ||
selectedBreakpoint === undefined ||
selectedStyleSource === undefined ||
styleSourceSelector === undefined
@@ -101,7 +100,7 @@ const publishUpdates = (
serverSyncStore.createTransaction(
[$styleSourceSelections, $styleSources, $styles],
(styleSourceSelections, styleSources, styles) => {
- const instanceId = selectedInstanceId;
+ const instanceId = selectedInstance.id;
const breakpointId = selectedBreakpoint.id;
// set only selected style source and update selection with it
// generated local style source will not be written if not selected
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 224dc7186c..34cd6365b2 100644
--- a/apps/builder/app/builder/features/style-panel/style-panel.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-panel.tsx
@@ -10,21 +10,19 @@ import { useStore } from "@nanostores/react";
import { computed } from "nanostores";
import { StyleSourcesSection } from "./style-source-section";
import { $selectedInstanceRenderState } from "~/shared/nano-states";
-import {
- $selectedInstanceIntanceToTag,
- $selectedInstanceSelector,
-} from "~/shared/nano-states";
+import { $selectedInstanceIntanceToTag } from "~/shared/nano-states";
import { sections } from "./sections";
import { toValue } from "@webstudio-is/css-engine";
import { useParentComputedStyleDecl } from "./shared/model";
+import { $selectedInstance } from "~/shared/awareness";
const $selectedInstanceTag = computed(
- [$selectedInstanceSelector, $selectedInstanceIntanceToTag],
- (instanceSelector, instanceToTag) => {
- if (instanceSelector === undefined || instanceToTag === undefined) {
+ [$selectedInstance, $selectedInstanceIntanceToTag],
+ (selectedInstance, instanceToTag) => {
+ if (selectedInstance === undefined || instanceToTag === undefined) {
return;
}
- return instanceToTag.get(instanceSelector[0]);
+ return instanceToTag.get(selectedInstance.id);
}
);
diff --git a/apps/builder/app/builder/features/style-panel/style-source-section.test.ts b/apps/builder/app/builder/features/style-panel/style-source-section.test.ts
index f6b065d5bd..047d81f909 100644
--- a/apps/builder/app/builder/features/style-panel/style-source-section.test.ts
+++ b/apps/builder/app/builder/features/style-panel/style-source-section.test.ts
@@ -5,6 +5,7 @@ import type { WsComponentMeta } from "@webstudio-is/react-sdk";
import { registerContainers } from "~/shared/sync";
import {
$breakpoints,
+ $instances,
$registeredComponentMetas,
$selectedStyleSources,
$styleSourceSelections,
@@ -108,6 +109,14 @@ test("generate styles from preset tokens", () => {
});
test("add style source to instance", () => {
+ $instances.set(
+ new Map([
+ [
+ "body",
+ { type: "instance", id: "body", component: "Body", children: [] },
+ ],
+ ])
+ );
$awareness.set({
pageId: "",
instanceSelector: ["body"],
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 c95eccc5b6..c68a27d9e1 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
@@ -28,11 +28,8 @@ import {
} from "./style-source";
import {
$breakpoints,
- $instances,
$registeredComponentMetas,
- $selectedInstanceSelector,
$selectedInstanceStatesByStyleSourceId,
- $selectedInstance,
$selectedInstanceStyleSources,
$selectedOrLastStyleSourceSelector,
$selectedStyleSources,
@@ -47,16 +44,16 @@ import { humanizeString } from "~/shared/string-utils";
import { isBaseBreakpoint } from "~/shared/breakpoints";
import { shallowComputed } from "~/shared/store-utils";
import { serverSyncStore } from "~/shared/sync";
+import { $selectedInstance } from "~/shared/awareness";
const selectStyleSource = (
styleSourceId: StyleSource["id"],
state?: StyleDecl["state"]
) => {
- const selectedInstanceSelector = $selectedInstanceSelector.get();
- if (selectedInstanceSelector === undefined) {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
return;
}
- const [instanceId] = selectedInstanceSelector;
const selectedStyleSources = new Map($selectedStyleSources.get());
selectedStyleSources.set(instanceId, styleSourceId);
$selectedStyleSources.set(selectedStyleSources);
@@ -64,11 +61,10 @@ const selectStyleSource = (
};
const deselectMatchingStyleSource = (styleSourceId: StyleSource["id"]) => {
- const selectedInstanceSelector = $selectedInstanceSelector.get();
- if (selectedInstanceSelector === undefined) {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
return;
}
- const [instanceId] = selectedInstanceSelector;
const selectedStyleSources = new Map($selectedStyleSources.get());
if (selectedStyleSources.get(instanceId) === styleSourceId) {
selectedStyleSources.delete(instanceId);
@@ -171,11 +167,10 @@ const addStyleSourceToInstaceMutable = (
};
const createStyleSource = (id: StyleSource["id"], name: string) => {
- const selectedInstanceSelector = $selectedInstanceSelector.get();
- if (selectedInstanceSelector === undefined) {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
return;
}
- const [selectedInstanceId] = selectedInstanceSelector;
const newStyleSource: StyleSource = {
type: "token",
id,
@@ -189,7 +184,7 @@ const createStyleSource = (id: StyleSource["id"], name: string) => {
addStyleSourceToInstaceMutable(
styleSourceSelections,
styleSources,
- selectedInstanceId,
+ instanceId,
newStyleSource.id
);
// populate preset token styles
@@ -207,18 +202,17 @@ const createStyleSource = (id: StyleSource["id"], name: string) => {
export const addStyleSourceToInstance = (
newStyleSourceId: StyleSource["id"]
) => {
- const selectedInstanceSelector = $selectedInstanceSelector.get();
- if (selectedInstanceSelector === undefined) {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
return;
}
- const [selectedInstanceId] = selectedInstanceSelector;
serverSyncStore.createTransaction(
[$styleSourceSelections, $styleSources],
(styleSourceSelections, styleSources) => {
addStyleSourceToInstaceMutable(
styleSourceSelections,
styleSources,
- selectedInstanceId,
+ instanceId,
newStyleSourceId
);
}
@@ -227,16 +221,14 @@ export const addStyleSourceToInstance = (
};
const removeStyleSourceFromInstance = (styleSourceId: StyleSource["id"]) => {
- const selectedInstanceSelector = $selectedInstanceSelector.get();
- if (selectedInstanceSelector === undefined) {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
return;
}
- const [selectedInstanceId] = selectedInstanceSelector;
serverSyncStore.createTransaction(
[$styleSourceSelections],
(styleSourceSelections) => {
- const styleSourceSelection =
- styleSourceSelections.get(selectedInstanceId);
+ const styleSourceSelection = styleSourceSelections.get(instanceId);
if (styleSourceSelection === undefined) {
return;
}
@@ -275,11 +267,10 @@ const deleteStyleSource = (styleSourceId: StyleSource["id"]) => {
};
const duplicateStyleSource = (styleSourceId: StyleSource["id"]) => {
- const selectedInstanceSelector = $selectedInstanceSelector.get();
- if (selectedInstanceSelector === undefined) {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
return;
}
- const [selectedInstanceId] = selectedInstanceSelector;
const styleSources = $styleSources.get();
// style source may not exist in store which means
// temporary generated local stye source was not applied yet
@@ -300,8 +291,7 @@ const duplicateStyleSource = (styleSourceId: StyleSource["id"]) => {
serverSyncStore.createTransaction(
[$styleSources, $styles, $styleSourceSelections],
(styleSources, styles, styleSourceSelections) => {
- const styleSourceSelection =
- styleSourceSelections.get(selectedInstanceId);
+ const styleSourceSelection = styleSourceSelections.get(instanceId);
if (styleSourceSelection === undefined) {
return;
}
@@ -321,11 +311,10 @@ const duplicateStyleSource = (styleSourceId: StyleSource["id"]) => {
};
const convertLocalStyleSourceToToken = (styleSourceId: StyleSource["id"]) => {
- const selectedInstanceSelector = $selectedInstanceSelector.get();
- if (selectedInstanceSelector === undefined) {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
return;
}
- const [selectedInstanceId] = selectedInstanceSelector;
const newStyleSource: StyleSource = {
type: "token",
id: styleSourceId,
@@ -336,7 +325,7 @@ const convertLocalStyleSourceToToken = (styleSourceId: StyleSource["id"]) => {
(styleSources, styleSourceSelections) => {
const styleSourceSelection = getOrCreateStyleSourceSelectionMutable(
styleSourceSelections,
- selectedInstanceId
+ instanceId
);
// generated local style source was not applied so put last
if (styleSourceSelection.values.includes(newStyleSource.id) === false) {
@@ -349,16 +338,14 @@ const convertLocalStyleSourceToToken = (styleSourceId: StyleSource["id"]) => {
};
const reorderStyleSources = (styleSourceIds: StyleSource["id"][]) => {
- const selectedInstanceSelector = $selectedInstanceSelector.get();
- if (selectedInstanceSelector === undefined) {
+ const instanceId = $selectedInstance.get()?.id;
+ if (instanceId === undefined) {
return;
}
- const [selectedInstanceId] = selectedInstanceSelector;
serverSyncStore.createTransaction(
[$styleSourceSelections],
(styleSourceSelections) => {
- const styleSourceSelection =
- styleSourceSelections.get(selectedInstanceId);
+ const styleSourceSelection = styleSourceSelections.get(instanceId);
if (styleSourceSelection === undefined) {
return;
}
@@ -434,19 +421,14 @@ const convertToInputItem = (
};
const $selectedInstancePresetTokens = shallowComputed(
- [$selectedInstanceSelector, $instances, $presetTokens],
- (selectedInstanceSelector, instances, presetTokens) => {
+ [$selectedInstance, $presetTokens],
+ (selectedInstance, presetTokens) => {
const selectedInstancePresetTokens: StyleSourceToken[] = [];
- if (selectedInstanceSelector === undefined) {
- return selectedInstancePresetTokens;
- }
- const [instanceId] = selectedInstanceSelector;
- const instance = instances.get(instanceId);
- if (instance === undefined) {
+ if (selectedInstance === undefined) {
return selectedInstancePresetTokens;
}
for (const presetToken of presetTokens.values()) {
- if (presetToken.component === instance.component) {
+ if (presetToken.component === selectedInstance.component) {
selectedInstancePresetTokens.push(presetToken.styleSource);
}
}
diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts
index 26d838aab3..78c398f387 100644
--- a/apps/builder/app/canvas/shared/styles.ts
+++ b/apps/builder/app/canvas/shared/styles.ts
@@ -31,7 +31,6 @@ import {
$isPreviewMode,
$props,
$registeredComponentMetas,
- $selectedInstanceSelector,
$selectedStyleState,
$styleSourceSelections,
$styles,
@@ -39,6 +38,7 @@ import {
import { setDifference } from "~/shared/shim";
import { $ephemeralStyles, $params } from "../stores";
import { canvasApi } from "~/shared/canvas-api";
+import { $selectedInstance } from "~/shared/awareness";
const userSheet = createRegularStyleSheet({ name: "user-styles" });
const stateSheet = createRegularStyleSheet({ name: "state-styles" });
@@ -367,27 +367,25 @@ export const GlobalStyles = ({ params }: { params: Params }) => {
const $instanceStyles = computed(
[
- $selectedInstanceSelector,
+ $selectedInstance,
$selectedStyleState,
$breakpoints,
$styleSourceSelections,
$styles,
],
(
- selectedInstanceSelector,
+ selectedInstance,
selectedStyleState,
breakpoints,
styleSourceSelections,
styles
) => {
- if (
- selectedInstanceSelector === undefined ||
- selectedStyleState === undefined
- ) {
+ if (selectedInstance === undefined || selectedStyleState === undefined) {
return;
}
- const [instanceId] = selectedInstanceSelector;
- const styleSources = new Set(styleSourceSelections.get(instanceId)?.values);
+ const styleSources = new Set(
+ styleSourceSelections.get(selectedInstance.id)?.values
+ );
const instanceStyles: StyleDecl[] = [];
for (const styleDecl of styles.values()) {
if (
@@ -398,7 +396,7 @@ const $instanceStyles = computed(
}
}
return {
- instanceId,
+ instanceId: selectedInstance.id,
breakpoints: Array.from(breakpoints.values()),
styles: instanceStyles,
};
@@ -443,11 +441,10 @@ const subscribeEphemeralStyle = () => {
const appliedEphemeralDeclarations = new Map<string, StyleDecl>();
return $ephemeralStyles.subscribe((ephemeralStyles) => {
- const instanceSelector = $selectedInstanceSelector.get();
- if (instanceSelector === undefined) {
+ const instance = $selectedInstance.get();
+ if (instance === undefined) {
return;
}
- const [instanceId] = instanceSelector;
// reset ephemeral styles
if (ephemeralStyles.length === 0) {
@@ -476,7 +473,7 @@ const subscribeEphemeralStyle = () => {
// add ephemeral styles
if (ephemeralStyles.length > 0) {
canvasApi.setInert();
- const selector = `[${idAttribute}="${instanceId}"]`;
+ const selector = `[${idAttribute}="${instance.id}"]`;
const rule = userSheet.addNestingRule(selector);
let ephemetalSheetUpdated = false;
for (const styleDecl of ephemeralStyles) {
diff --git a/apps/builder/app/shared/awareness.ts b/apps/builder/app/shared/awareness.ts
index 633b452c95..a340095584 100644
--- a/apps/builder/app/shared/awareness.ts
+++ b/apps/builder/app/shared/awareness.ts
@@ -1,7 +1,14 @@
import { atom, computed, onSet } from "nanostores";
-import { findPageByIdOrPath, Instance, type Page } from "@webstudio-is/sdk";
+import {
+ findPageByIdOrPath,
+ Instance,
+ Instances,
+ ROOT_INSTANCE_ID,
+ type Page,
+} from "@webstudio-is/sdk";
+import { rootComponent } from "@webstudio-is/react-sdk";
import { $pages } from "./nano-states/pages";
-import { $selectedInstanceSelector } from "./nano-states/instances";
+import { $instances, $selectedInstanceSelector } from "./nano-states/instances";
type Awareness = {
pageId: Page["id"];
@@ -24,6 +31,33 @@ export const $selectedPage = computed(
}
);
+export const $virtualInstances = computed($selectedPage, (selectedPage) => {
+ const virtualInstances: Instances = new Map();
+ if (selectedPage) {
+ virtualInstances.set(ROOT_INSTANCE_ID, {
+ type: "instance",
+ id: ROOT_INSTANCE_ID,
+ component: rootComponent,
+ children: [{ type: "id", value: selectedPage.rootInstanceId }],
+ });
+ }
+ return virtualInstances;
+});
+
+export const $selectedInstance = computed(
+ [$instances, $virtualInstances, $awareness],
+ (instances, virtualInstances, awareness) => {
+ if (awareness?.instanceSelector === undefined) {
+ return;
+ }
+ const [selectedInstanceId] = awareness.instanceSelector;
+ return (
+ instances.get(selectedInstanceId) ??
+ virtualInstances.get(selectedInstanceId)
+ );
+ }
+);
+
export const selectPage = (pageId: Page["id"]) => {
const pages = $pages.get();
if (pages === undefined) {
diff --git a/apps/builder/app/shared/nano-states/instances.ts b/apps/builder/app/shared/nano-states/instances.ts
index b2b1ea9cbb..9e867d7ce7 100644
--- a/apps/builder/app/shared/nano-states/instances.ts
+++ b/apps/builder/app/shared/nano-states/instances.ts
@@ -1,8 +1,6 @@
-import { atom, computed } from "nanostores";
-import { ROOT_INSTANCE_ID, type Instances } from "@webstudio-is/sdk";
-import { rootComponent } from "@webstudio-is/react-sdk";
+import { atom } from "nanostores";
+import type { Instances } from "@webstudio-is/sdk";
import type { InstanceSelector } from "../tree-utils";
-import { $selectedPage } from "../awareness";
export const $isResizingCanvas = atom(false);
@@ -35,33 +33,6 @@ export const $textEditingInstanceSelector = atom<
export const $instances = atom<Instances>(new Map());
-export const $virtualInstances = computed($selectedPage, (selectedPage) => {
- const virtualInstances: Instances = new Map();
- if (selectedPage) {
- virtualInstances.set(ROOT_INSTANCE_ID, {
- type: "instance",
- id: ROOT_INSTANCE_ID,
- component: rootComponent,
- children: [{ type: "id", value: selectedPage.rootInstanceId }],
- });
- }
- return virtualInstances;
-});
-
-export const $selectedInstance = computed(
- [$instances, $virtualInstances, $selectedInstanceSelector],
- (instances, virtualInstances, selectedInstanceSelector) => {
- if (selectedInstanceSelector === undefined) {
- return;
- }
- const [selectedInstanceId] = selectedInstanceSelector;
- return (
- instances.get(selectedInstanceId) ??
- virtualInstances.get(selectedInstanceId)
- );
- }
-);
-
export const $synchronizedInstances = [
["textEditingInstanceSelector", $textEditingInstanceSelector],
["isResizingCanvas", $isResizingCanvas],
diff --git a/apps/builder/app/shared/nano-states/misc.ts b/apps/builder/app/shared/nano-states/misc.ts
index cce7d53685..0c6e66c154 100644
--- a/apps/builder/app/shared/nano-states/misc.ts
+++ b/apps/builder/app/shared/nano-states/misc.ts
@@ -28,6 +28,7 @@ import type { UnitSizes } from "~/builder/features/style-panel/shared/css-value-
import type { Simplify } from "type-fest";
import type { AssetType } from "@webstudio-is/asset-uploader";
import type { ChildrenOrientation } from "node_modules/@webstudio-is/design-system/src/components/primitives/dnd/geometry-utils";
+import { $selectedInstance } from "../awareness";
export const $project = atom<Project | undefined>();
@@ -178,14 +179,14 @@ export const $selectedInstanceRenderState = atom<
>("notMounted");
export const $selectedInstanceStatesByStyleSourceId = computed(
- [$styles, $styleSourceSelections, $selectedInstanceSelector],
- (styles, styleSourceSelections, selectedInstanceSelector) => {
+ [$styles, $styleSourceSelections, $selectedInstance],
+ (styles, styleSourceSelections, selectedInstance) => {
const statesByStyleSourceId = new Map<StyleSource["id"], string[]>();
- if (selectedInstanceSelector === undefined) {
+ if (selectedInstance === undefined) {
return statesByStyleSourceId;
}
const styleSourceIds = new Set(
- styleSourceSelections.get(selectedInstanceSelector[0])?.values
+ styleSourceSelections.get(selectedInstance.id)?.values
);
for (const styleDecl of styles.values()) {
if (
@@ -208,15 +209,14 @@ export const $selectedInstanceStatesByStyleSourceId = computed(
);
export const $selectedInstanceStyleSources = computed(
- [$styleSourceSelections, $styleSources, $selectedInstanceSelector],
- (styleSourceSelections, styleSources, selectedInstanceSelector) => {
+ [$styleSourceSelections, $styleSources, $selectedInstance],
+ (styleSourceSelections, styleSources, selectedInstance) => {
const selectedInstanceStyleSources: StyleSource[] = [];
- if (selectedInstanceSelector === undefined) {
+ if (selectedInstance === undefined) {
return selectedInstanceStyleSources;
}
- const [selectedInstanceId] = selectedInstanceSelector;
const styleSourceIds =
- styleSourceSelections.get(selectedInstanceId)?.values ?? [];
+ styleSourceSelections.get(selectedInstance.id)?.values ?? [];
let hasLocal = false;
for (const styleSourceId of styleSourceIds) {
const styleSource = styleSources.get(styleSourceId);
@@ -244,20 +244,19 @@ export const $selectedOrLastStyleSourceSelector = computed(
[
$selectedInstanceStyleSources,
$selectedStyleSources,
- $selectedInstanceSelector,
+ $selectedInstance,
$selectedStyleState,
],
(
styleSources,
selectedStyleSources,
- selectedInstanceSelector,
+ selectedInstance,
selectedStyleState
) => {
- if (selectedInstanceSelector === undefined) {
+ if (selectedInstance === undefined) {
return;
}
- const [instanceId] = selectedInstanceSelector;
- const styleSourceId = selectedStyleSources.get(instanceId);
+ const styleSourceId = selectedStyleSources.get(selectedInstance.id);
// always fallback to local (the last one) style source
const lastStyleSource = styleSources.at(-1);
const matchedStyleSource = styleSources.find(
@@ -275,17 +274,12 @@ export const $selectedOrLastStyleSourceSelector = computed(
* to the last style source of selected instance
*/
export const $selectedStyleSource = computed(
- [
- $selectedInstanceStyleSources,
- $selectedStyleSources,
- $selectedInstanceSelector,
- ],
- (styleSources, selectedStyleSources, selectedInstanceSelector) => {
- if (selectedInstanceSelector === undefined) {
+ [$selectedInstanceStyleSources, $selectedStyleSources, $selectedInstance],
+ (styleSources, selectedStyleSources, selectedInstance) => {
+ if (selectedInstance === undefined) {
return;
}
- const [instanceId] = selectedInstanceSelector;
- const selectedStyleSourceId = selectedStyleSources.get(instanceId);
+ const selectedStyleSourceId = selectedStyleSources.get(selectedInstance.id);
return (
styleSources.find((item) => item.id === selectedStyleSourceId) ??
styleSources.at(-1)