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.

Add style sources stores (#913)

Bogdan Chadkin174b7124f209
diff --git a/apps/designer/app/canvas/canvas.tsx b/apps/designer/app/canvas/canvas.tsx
index 985286a8cb..951ce6cd71 100644
--- a/apps/designer/app/canvas/canvas.tsx
+++ b/apps/designer/app/canvas/canvas.tsx
@@ -32,6 +32,8 @@ import {
useSetProps,
useSetRootInstance,
useSetStyles,
+ useSetStyleSources,
+ useSetStyleSourceSelections,
useSubscribeScrollState,
useIsPreviewMode,
} from "~/shared/nano-states";
@@ -117,6 +119,9 @@ const propsByInstanceIdStore = computed(
);
export const Canvas = ({ data }: CanvasProps): JSX.Element | null => {
+ if (data.build === null) {
+ throw new Error("Build is null");
+ }
if (data.tree === null) {
throw new Error("Tree is null");
}
@@ -127,6 +132,8 @@ export const Canvas = ({ data }: CanvasProps): JSX.Element | null => {
// inject props store to sdk
setPropsByInstanceIdStore(propsByInstanceIdStore);
useSetStyles(data.tree.styles);
+ useSetStyleSources(data.build.styleSources);
+ useSetStyleSourceSelections(data.tree.styleSourceSelections);
useSetRootInstance(data.tree.root);
setParams(data.params ?? null);
useCanvasStore(publish);
diff --git a/apps/designer/app/designer/designer.tsx b/apps/designer/app/designer/designer.tsx
index e0f95b936a..b5b2df0404 100644
--- a/apps/designer/app/designer/designer.tsx
+++ b/apps/designer/app/designer/designer.tsx
@@ -344,7 +344,7 @@ export const Designer = ({
{dragAndDropState.isDragging ? (
<TreePrevew />
) : (
- <Inspector publish={publish} />
+ <Inspector treeId={treeId} publish={publish} />
)}
</SidePanel>
<Footer />
diff --git a/apps/designer/app/designer/features/inspector/inspector.tsx b/apps/designer/app/designer/features/inspector/inspector.tsx
index fa705a3a8b..888b8c1a94 100644
--- a/apps/designer/app/designer/features/inspector/inspector.tsx
+++ b/apps/designer/app/designer/features/inspector/inspector.tsx
@@ -1,5 +1,6 @@
import { useRef } from "react";
import { useStore } from "@nanostores/react";
+import { Tree } from "@webstudio-is/project-build";
import type { Publish } from "~/shared/pubsub";
import {
DeprecatedText2,
@@ -20,6 +21,7 @@ import { theme } from "@webstudio-is/design-system";
import { selectedInstanceStore } from "~/shared/nano-states";
type InspectorProps = {
+ treeId: Tree["id"];
publish: Publish;
};
@@ -29,7 +31,7 @@ const contentStyle = {
overflow: "auto",
};
-export const Inspector = ({ publish }: InspectorProps) => {
+export const Inspector = ({ treeId, publish }: InspectorProps) => {
const selectedInstance = useStore(selectedInstanceStore);
const tabsRef = useRef<HTMLDivElement>(null);
@@ -69,10 +71,15 @@ export const Inspector = ({ publish }: InspectorProps) => {
</TabsTrigger>
</TabsList>
<TabsContent value="style" css={contentStyle}>
- <StylePanel publish={publish} selectedInstance={selectedInstance} />
+ <StylePanel
+ treeId={treeId}
+ publish={publish}
+ selectedInstance={selectedInstance}
+ />
</TabsContent>
<TabsContent value="props" css={contentStyle}>
<PropsPanel
+ treeId={treeId}
publish={publish}
key={selectedInstance.id /* Re-render when instance changes */}
selectedInstance={selectedInstance}
diff --git a/apps/designer/app/designer/features/props-panel/props-panel.stories.tsx b/apps/designer/app/designer/features/props-panel/props-panel.stories.tsx
index 978751412a..0a6eb07a19 100644
--- a/apps/designer/app/designer/features/props-panel/props-panel.stories.tsx
+++ b/apps/designer/app/designer/features/props-panel/props-panel.stories.tsx
@@ -21,6 +21,7 @@ export const NoProps: ComponentStory<typeof PropsPanel> = () => {
]);
return (
<PropsPanel
+ treeId="treeId"
selectedInstance={{
type: "instance",
id: "1",
@@ -37,6 +38,7 @@ export const RequiredProps: ComponentStory<typeof PropsPanel> = () => {
propsStore.set([]);
return (
<PropsPanel
+ treeId="treeId"
selectedInstance={{
type: "instance",
id: "1",
@@ -53,6 +55,7 @@ export const DefaultProps: ComponentStory<typeof PropsPanel> = () => {
propsStore.set([]);
return (
<PropsPanel
+ treeId="treeId"
selectedInstance={{
type: "instance",
id: "1",
@@ -80,6 +83,7 @@ export const AllProps: ComponentStory<typeof PropsPanel> = () => {
);
return (
<PropsPanel
+ treeId="treeId"
selectedInstance={{
type: "instance",
id: "3",
diff --git a/apps/designer/app/designer/features/props-panel/props-panel.tsx b/apps/designer/app/designer/features/props-panel/props-panel.tsx
index f8fd1050c6..a6cff879d7 100644
--- a/apps/designer/app/designer/features/props-panel/props-panel.tsx
+++ b/apps/designer/app/designer/features/props-panel/props-panel.tsx
@@ -1,6 +1,6 @@
import { useState } from "react";
import store from "immerhin";
-import type { Instance, PropsItem } from "@webstudio-is/project-build";
+import type { Instance, PropsItem, Tree } from "@webstudio-is/project-build";
import { getComponentMetaProps } from "@webstudio-is/react-sdk";
import {
theme,
@@ -213,11 +213,16 @@ const Property = ({
};
type PropsPanelProps = {
+ treeId: Tree["id"];
publish: Publish;
selectedInstance: Instance;
};
-export const PropsPanel = ({ selectedInstance, publish }: PropsPanelProps) => {
+export const PropsPanel = ({
+ treeId,
+ selectedInstance,
+ publish,
+}: PropsPanelProps) => {
const instanceId = selectedInstance.id;
const instanceProps = useInstanceProps(instanceId);
@@ -250,6 +255,7 @@ export const PropsPanel = ({ selectedInstance, publish }: PropsPanelProps) => {
});
const { setProperty: setCssProperty } = useStyleData({
+ treeId,
selectedInstance,
publish,
});
diff --git a/apps/designer/app/designer/features/style-panel/shared/use-style-data.ts b/apps/designer/app/designer/features/style-panel/shared/use-style-data.ts
index 0150124fae..3214887aca 100644
--- a/apps/designer/app/designer/features/style-panel/shared/use-style-data.ts
+++ b/apps/designer/app/designer/features/style-panel/shared/use-style-data.ts
@@ -1,19 +1,24 @@
import { useCallback } from "react";
+import ObjectID from "bson-objectid";
import store from "immerhin";
import warnOnce from "warn-once";
-import type { Instance } from "@webstudio-is/project-build";
+import type { Instance, Tree } from "@webstudio-is/project-build";
import type { StyleUpdates } from "@webstudio-is/project";
import type { StyleProperty, StyleValue } from "@webstudio-is/css-data";
import { type Publish } from "~/shared/pubsub";
-import { stylesStore } from "~/shared/nano-states";
+import {
+ styleSourceSelectionsStore,
+ styleSourcesStore,
+ stylesStore,
+} from "~/shared/nano-states";
import { useSelectedBreakpoint } from "~/designer/shared/nano-states";
-// @todo: must be removed, now it's only for compatibility with existing code
-import { parseCssValue } from "./parse-css-value";
-import { useStyleInfo } from "./style-info";
import {
removeByMutable,
replaceByOrAppendMutable,
} from "~/shared/array-utils";
+// @todo: must be removed, now it's only for compatibility with existing code
+import { parseCssValue } from "./parse-css-value";
+import { useStyleInfo } from "./style-info";
declare module "~/shared/pubsub" {
export interface PubsubMap {
@@ -23,6 +28,7 @@ declare module "~/shared/pubsub" {
}
type UseStyleData = {
+ treeId: Tree["id"];
publish: Publish;
selectedInstance: Instance;
};
@@ -47,7 +53,11 @@ export type CreateBatchUpdate = () => {
publish: (options?: StyleUpdateOptions) => void;
};
-export const useStyleData = ({ selectedInstance, publish }: UseStyleData) => {
+export const useStyleData = ({
+ treeId,
+ selectedInstance,
+ publish,
+}: UseStyleData) => {
const [selectedBreakpoint] = useSelectedBreakpoint();
const currentStyle = useStyleInfo();
@@ -70,40 +80,61 @@ export const useStyleData = ({ selectedInstance, publish }: UseStyleData) => {
return;
}
- store.createTransaction([stylesStore], (styles) => {
- const instanceId = selectedInstance.id;
- const breakpointId = selectedBreakpoint.id;
-
- for (const update of updates) {
- if (update.operation === "set") {
- replaceByOrAppendMutable(
- styles,
- {
- breakpointId,
- instanceId,
- property: update.property,
- value: update.value,
- },
- (item) =>
- item.instanceId === instanceId &&
- item.breakpointId === breakpointId &&
- item.property === update.property
- );
+ store.createTransaction(
+ [styleSourceSelectionsStore, styleSourcesStore, stylesStore],
+ (styleSourceSelections, styleSources, styles) => {
+ const instanceId = selectedInstance.id;
+ const breakpointId = selectedBreakpoint.id;
+
+ // crate style source and its selection on currently selected instance
+ const matchedStyleSourceSelection = styleSourceSelections.find(
+ (styleSourceSelection) =>
+ styleSourceSelection.instanceId === instanceId
+ );
+ if (matchedStyleSourceSelection === undefined) {
+ const styleSourceId = ObjectID.toString();
+ styleSources.push({
+ type: "local",
+ id: styleSourceId,
+ treeId,
+ });
+ styleSourceSelections.push({
+ instanceId,
+ values: [styleSourceId],
+ });
}
- if (update.operation === "delete") {
- removeByMutable(
- styles,
- (item) =>
- item.instanceId === instanceId &&
- item.breakpointId === breakpointId &&
- item.property === update.property
- );
+ for (const update of updates) {
+ if (update.operation === "set") {
+ replaceByOrAppendMutable(
+ styles,
+ {
+ breakpointId,
+ instanceId,
+ property: update.property,
+ value: update.value,
+ },
+ (item) =>
+ item.instanceId === instanceId &&
+ item.breakpointId === breakpointId &&
+ item.property === update.property
+ );
+ }
+
+ if (update.operation === "delete") {
+ removeByMutable(
+ styles,
+ (item) =>
+ item.instanceId === instanceId &&
+ item.breakpointId === breakpointId &&
+ item.property === update.property
+ );
+ }
}
}
- });
+ );
},
- [publish, selectedBreakpoint, selectedInstance]
+ [publish, selectedBreakpoint, selectedInstance, treeId]
);
// @deprecated should not be called
diff --git a/apps/designer/app/designer/features/style-panel/style-panel.tsx b/apps/designer/app/designer/features/style-panel/style-panel.tsx
index c4fd5c7121..2c7e78af79 100644
--- a/apps/designer/app/designer/features/style-panel/style-panel.tsx
+++ b/apps/designer/app/designer/features/style-panel/style-panel.tsx
@@ -6,7 +6,7 @@ import {
DeprecatedParagraph,
SearchField,
} from "@webstudio-is/design-system";
-import type { Instance } from "@webstudio-is/project-build";
+import type { Instance, Tree } from "@webstudio-is/project-build";
import { useStyleData } from "./shared/use-style-data";
import { StyleSettings } from "./style-settings";
import { useState } from "react";
@@ -17,13 +17,19 @@ import {
import { theme } from "@webstudio-is/design-system";
type StylePanelProps = {
+ treeId: Tree["id"];
publish: Publish;
selectedInstance: Instance;
};
-export const StylePanel = ({ selectedInstance, publish }: StylePanelProps) => {
+export const StylePanel = ({
+ treeId,
+ selectedInstance,
+ publish,
+}: StylePanelProps) => {
const { currentStyle, setProperty, deleteProperty, createBatchUpdate } =
useStyleData({
+ treeId,
selectedInstance,
publish,
});
diff --git a/apps/designer/app/routes/rest/patch.ts b/apps/designer/app/routes/rest/patch.ts
index 41a7a4b36e..995d94b570 100644
--- a/apps/designer/app/routes/rest/patch.ts
+++ b/apps/designer/app/routes/rest/patch.ts
@@ -36,6 +36,12 @@ export const action = async ({ request }: ActionArgs) => {
if (namespace === "root") {
await projectDb.tree.patch({ treeId, projectId }, patches, context);
+ } else if (namespace === "styleSourceSelections") {
+ // @todo enable when styles migrated to style sources
+ continue;
+ } else if (namespace === "styleSources") {
+ // @todo enable when styles migrated to style sources
+ continue;
} else if (namespace === "styles") {
await projectDb.styles.patch({ treeId, projectId }, patches, context);
} else if (namespace === "props") {
diff --git a/apps/designer/app/shared/copy-paste/copy-paste-instance.ts b/apps/designer/app/shared/copy-paste/copy-paste-instance.ts
index c1ebba01d5..c7392bc73c 100644
--- a/apps/designer/app/shared/copy-paste/copy-paste-instance.ts
+++ b/apps/designer/app/shared/copy-paste/copy-paste-instance.ts
@@ -1,8 +1,13 @@
-import ObjectId from "bson-objectid";
import store from "immerhin";
import { z } from "zod";
import { useEffect } from "react";
-import { Instance, Props, Styles } from "@webstudio-is/project-build";
+import {
+ Instance,
+ Props,
+ Styles,
+ StyleSources,
+ StyleSourceSelections,
+} from "@webstudio-is/project-build";
import { utils } from "@webstudio-is/project";
import { findInsertLocation } from "~/canvas/shared/instance";
import {
@@ -10,23 +15,33 @@ import {
propsStore,
stylesStore,
selectedInstanceIdStore,
+ styleSourceSelectionsStore,
+ styleSourcesStore,
} from "../nano-states";
-import { cloneInstance, findSubtree } from "../tree-utils";
+import {
+ cloneInstance,
+ cloneProps,
+ cloneStyles,
+ cloneStyleSources,
+ cloneStyleSourceSelections,
+ findSubtree,
+ findSubtreeLocalStyleSources,
+} from "../tree-utils";
import { deleteInstance } from "../instance-utils";
import { startCopyPaste } from "./copy-paste";
-const InstanceCopyData = z.object({
+const InstanceData = z.object({
instance: Instance,
props: Props,
+ styleSourceSelections: StyleSourceSelections,
+ styleSources: StyleSources,
styles: Styles,
});
-type InstanceCopyData = z.infer<typeof InstanceCopyData>;
+type InstanceData = z.infer<typeof InstanceData>;
const copyInstanceData = (targetInstanceId: string) => {
const rootInstance = rootInstanceContainer.get();
- const props = propsStore.get();
- const styles = stylesStore.get();
if (rootInstance === undefined) {
return;
}
@@ -35,51 +50,56 @@ const copyInstanceData = (targetInstanceId: string) => {
return;
}
- const { targetInstance } = findSubtree(rootInstance, targetInstanceId);
+ const { targetInstance, subtreeIds } = findSubtree(
+ rootInstance,
+ targetInstanceId
+ );
+ const styleSources = styleSourcesStore.get();
+ const styleSourceSelections = styleSourceSelectionsStore.get();
+ const subtreeLocalStyleSourceIds = findSubtreeLocalStyleSources(
+ subtreeIds,
+ styleSources,
+ styleSourceSelections
+ );
if (targetInstance === undefined) {
return;
}
- const { clonedInstance, clonedIds } = cloneInstance(targetInstance);
- // clone props with new ids and link to new cloned instances
- const clonedProps: Props = [];
- for (const prop of props) {
- const instanceId = clonedIds.get(prop.instanceId);
- if (instanceId === undefined) {
- continue;
- }
- clonedProps.push({
- ...prop,
- id: ObjectId().toString(),
- instanceId,
- });
- }
-
- // clone styles and link to new cloned instances
- const clonedStyles: Styles = [];
- for (const styleDecl of styles) {
- const instanceId = clonedIds.get(styleDecl.instanceId);
- if (instanceId === undefined) {
- continue;
- }
- clonedStyles.push({
- ...styleDecl,
- instanceId,
- });
- }
+ // clone all instance related data and link it with new ids
+ const { clonedInstance, clonedInstanceIds } = cloneInstance(targetInstance);
+ const clonedProps = cloneProps(propsStore.get(), clonedInstanceIds);
+ const { clonedStyleSources, clonedStyleSourceIds } = cloneStyleSources(
+ styleSources,
+ subtreeLocalStyleSourceIds
+ );
+ const clonedStyleSourceSelections = cloneStyleSourceSelections(
+ styleSourceSelections,
+ clonedInstanceIds,
+ clonedStyleSourceIds
+ );
+ // @todo migrate to style source variant
+ const clonedStyles = cloneStyles(stylesStore.get(), clonedInstanceIds);
return {
instance: clonedInstance,
props: clonedProps,
+ styleSourceSelections: clonedStyleSourceSelections,
+ styleSources: clonedStyleSources,
styles: clonedStyles,
};
};
-const pasteInstance = (data: InstanceCopyData) => {
+const pasteInstance = (data: InstanceData) => {
const selectedInstanceId = selectedInstanceIdStore.get();
store.createTransaction(
- [rootInstanceContainer, propsStore, stylesStore],
- (rootInstance, props, styles) => {
+ [
+ rootInstanceContainer,
+ propsStore,
+ styleSourceSelectionsStore,
+ styleSourcesStore,
+ stylesStore,
+ ],
+ (rootInstance, props, styleSourceSelections, styleSources, styles) => {
if (rootInstance === undefined) {
return;
}
@@ -91,17 +111,21 @@ const pasteInstance = (data: InstanceCopyData) => {
if (hasInserted === false) {
return;
}
+ // append without checking existing
+ // because all data already cloned with new ids
props.push(...data.props);
+ styleSourceSelections.push(...data.styleSourceSelections);
+ styleSources.push(...data.styleSources);
styles.push(...data.styles);
- selectedInstanceIdStore.set(data.instance.id);
}
);
+ selectedInstanceIdStore.set(data.instance.id);
};
const startCopyPasteInstance = () => {
return startCopyPaste({
version: "@webstudio/instance/v0.1",
- type: InstanceCopyData,
+ type: InstanceData,
allowAnyTarget: true,
onCopy: () => {
@@ -129,7 +153,7 @@ const startCopyPasteInstance = () => {
});
};
-export const useCopyPasteInstance = (): void => {
+export const useCopyPasteInstance = () => {
useEffect(() => {
return startCopyPasteInstance();
}, []);
diff --git a/apps/designer/app/shared/instance-utils.ts b/apps/designer/app/shared/instance-utils.ts
index 89a866f7c3..f4adfa30c4 100644
--- a/apps/designer/app/shared/instance-utils.ts
+++ b/apps/designer/app/shared/instance-utils.ts
@@ -5,14 +5,22 @@ import {
propsStore,
stylesStore,
selectedInstanceIdStore,
+ styleSourceSelectionsStore,
+ styleSourcesStore,
} from "./nano-states";
-import { findSubtree } from "./tree-utils";
+import { findSubtree, findSubtreeLocalStyleSources } from "./tree-utils";
import { removeByMutable } from "./array-utils";
export const deleteInstance = (targetInstanceId: Instance["id"]) => {
store.createTransaction(
- [rootInstanceContainer, propsStore, stylesStore],
- (rootInstance, props, styles) => {
+ [
+ rootInstanceContainer,
+ propsStore,
+ styleSourceSelectionsStore,
+ styleSourcesStore,
+ stylesStore,
+ ],
+ (rootInstance, props, styleSourceSelections, styleSources, styles) => {
if (rootInstance === undefined) {
return;
}
@@ -24,6 +32,11 @@ export const deleteInstance = (targetInstanceId: Instance["id"]) => {
rootInstance,
targetInstanceId
);
+ const subtreeLocalStyleSourceIds = findSubtreeLocalStyleSources(
+ subtreeIds,
+ styleSources,
+ styleSourceSelections
+ );
if (parentInstance === undefined) {
return;
}
@@ -34,6 +47,13 @@ export const deleteInstance = (targetInstanceId: Instance["id"]) => {
);
// delete props and styles of deleted instance and its descendants
removeByMutable(props, (prop) => subtreeIds.has(prop.instanceId));
+ removeByMutable(styleSourceSelections, (styleSourceSelection) =>
+ subtreeIds.has(styleSourceSelection.instanceId)
+ );
+ removeByMutable(styleSources, (styleSource) =>
+ subtreeLocalStyleSourceIds.has(styleSource.id)
+ );
+ // @todo migrate to style source variant
removeByMutable(styles, (styleDecl) =>
subtreeIds.has(styleDecl.instanceId)
);
diff --git a/apps/designer/app/shared/nano-states/nano-states.ts b/apps/designer/app/shared/nano-states/nano-states.ts
index 6f8c32ea33..4c260962ec 100644
--- a/apps/designer/app/shared/nano-states/nano-states.ts
+++ b/apps/designer/app/shared/nano-states/nano-states.ts
@@ -1,12 +1,18 @@
import { useMemo } from "react";
import { atom, computed, type WritableAtom } from "nanostores";
import { useStore } from "@nanostores/react";
-import type { Instance, Props, Styles } from "@webstudio-is/project-build";
+import type {
+ Instance,
+ Props,
+ Styles,
+ StyleSources,
+ StyleSourceSelections,
+} from "@webstudio-is/project-build";
+import type { Breakpoint, Style } from "@webstudio-is/css-data";
import type {
DropTargetChangePayload,
DragStartPayload,
} from "~/canvas/shared/use-drag-drop";
-import type { Breakpoint, Style } from "@webstudio-is/css-data";
import { useSyncInitializeOnce } from "../hook-utils";
import { shallowComputed } from "../store-utils";
@@ -121,6 +127,22 @@ export const useInstanceStyles = (instanceId: undefined | Instance["id"]) => {
return instanceStyles;
};
+export const styleSourcesStore = atom<StyleSources>([]);
+export const useSetStyleSources = (styleSources: StyleSources) => {
+ useSyncInitializeOnce(() => {
+ styleSourcesStore.set(styleSources);
+ });
+};
+
+export const styleSourceSelectionsStore = atom<StyleSourceSelections>([]);
+export const useSetStyleSourceSelections = (
+ styleSourceSelections: StyleSourceSelections
+) => {
+ useSyncInitializeOnce(() => {
+ styleSourceSelectionsStore.set(styleSourceSelections);
+ });
+};
+
export const breakpointsContainer = atom<Breakpoint[]>([]);
export const useBreakpoints = () => useValue(breakpointsContainer);
export const useSetBreakpoints = (breakpoints: Breakpoint[]) => {
diff --git a/apps/designer/app/shared/sync/sync-stores.ts b/apps/designer/app/shared/sync/sync-stores.ts
index 072997c70e..64859e3a12 100644
--- a/apps/designer/app/shared/sync/sync-stores.ts
+++ b/apps/designer/app/shared/sync/sync-stores.ts
@@ -7,6 +7,8 @@ import {
propsStore,
breakpointsContainer,
stylesStore,
+ styleSourcesStore,
+ styleSourceSelectionsStore,
selectedInstanceIdStore,
selectedInstanceBrowserStyleStore,
hoveredInstanceIdStore,
@@ -43,6 +45,8 @@ export const registerContainers = () => {
store.register("breakpoints", breakpointsContainer);
store.register("root", rootInstanceContainer);
store.register("styles", stylesStore);
+ store.register("styleSources", styleSourcesStore);
+ store.register("styleSourceSelections", styleSourceSelectionsStore);
store.register("props", propsStore);
// synchronize whole states
clientStores.set("selectedInstanceId", selectedInstanceIdStore);
diff --git a/apps/designer/app/shared/tree-utils.test.ts b/apps/designer/app/shared/tree-utils.test.ts
index a55a44cc98..cd3223cc71 100644
--- a/apps/designer/app/shared/tree-utils.test.ts
+++ b/apps/designer/app/shared/tree-utils.test.ts
@@ -1,8 +1,24 @@
import { test, expect } from "@jest/globals";
-import type { Instance } from "@webstudio-is/project-build";
-import { cloneInstance, findSubtree } from "./tree-utils";
+import type {
+ Instance,
+ PropsItem,
+ StylesItem,
+ StyleSource,
+ StyleSourceSelection,
+} from "@webstudio-is/project-build";
+import {
+ cloneInstance,
+ cloneProps,
+ cloneStyles,
+ cloneStyleSources,
+ cloneStyleSourceSelections,
+ findSubtree,
+ findSubtreeLocalStyleSources,
+} from "./tree-utils";
-const createInstance = (id: string, children: Instance[]): Instance => {
+const expectString = expect.any(String) as unknown as string;
+
+const createInstance = (id: Instance["id"], children: Instance[]): Instance => {
return {
type: "instance",
id,
@@ -11,6 +27,56 @@ const createInstance = (id: string, children: Instance[]): Instance => {
};
};
+const createProp = (id: string, instanceId: string): PropsItem => {
+ return {
+ id,
+ instanceId,
+ type: "string",
+ name: "prop",
+ value: "value",
+ };
+};
+
+const createStyleSource = (
+ type: StyleSource["type"],
+ id: StyleSource["id"]
+): StyleSource => {
+ if (type === "token") {
+ return {
+ type,
+ id,
+ name: id,
+ };
+ }
+ return {
+ type,
+ id,
+ treeId: "",
+ };
+};
+
+const createStyleSourceSelection = (
+ instanceId: Instance["id"],
+ values: StyleSource["id"][]
+): StyleSourceSelection => {
+ return {
+ instanceId,
+ values,
+ };
+};
+
+const createStyleDecl = (instanceId: string): StylesItem => {
+ return {
+ instanceId,
+ breakpointId: "breakpointId",
+ property: "width",
+ value: {
+ type: "keyword",
+ value: "value",
+ },
+ };
+};
+
test("find subtree with all descendants and parent instance", () => {
const rootInstance: Instance = createInstance("root", [
createInstance("box1", []),
@@ -55,17 +121,131 @@ test("clone instance tree and provide cloned ids map", () => {
createInstance("child2", [createInstance("descendant", [])]),
createInstance("child3", []),
]);
- const { clonedInstance, clonedIds } = cloneInstance(instance);
- const string = expect.any(String) as unknown as string;
+ const { clonedInstance, clonedInstanceIds } = cloneInstance(instance);
expect(clonedInstance).toEqual(
- createInstance(string, [
- createInstance(string, []),
- createInstance(string, [createInstance(string, [])]),
- createInstance(string, []),
+ createInstance(expectString, [
+ createInstance(expectString, []),
+ createInstance(expectString, [createInstance(expectString, [])]),
+ createInstance(expectString, []),
])
);
- expect(clonedIds.get(instance.id)).toEqual(clonedInstance.id);
- expect(clonedIds.get((instance.children[0] as Instance).id)).toEqual(
+ expect(clonedInstanceIds.get(instance.id)).toEqual(clonedInstance.id);
+ expect(clonedInstanceIds.get((instance.children[0] as Instance).id)).toEqual(
(clonedInstance.children[0] as Instance).id
);
});
+
+test("clone props with new ids and apply new instance ids", () => {
+ const props = [
+ createProp("prop1", "instance1"),
+ createProp("prop2", "instance2"),
+ createProp("prop3", "instance1"),
+ createProp("prop4", "instance3"),
+ createProp("prop5", "instance1"),
+ createProp("prop6", "instance3"),
+ ];
+ const clonedInstanceIds = new Map<Instance["id"], Instance["id"]>();
+ clonedInstanceIds.set("instance2", "newInstance2");
+ clonedInstanceIds.set("instance3", "newInstance3");
+ expect(cloneProps(props, clonedInstanceIds)).toEqual([
+ createProp(expectString, "newInstance2"),
+ createProp(expectString, "newInstance3"),
+ createProp(expectString, "newInstance3"),
+ ]);
+});
+
+test("clone style sources with new ids within provided subset", () => {
+ const styleSources = [
+ createStyleSource("local", "local1"),
+ createStyleSource("local", "local2"),
+ createStyleSource("token", "token3"),
+ createStyleSource("local", "local4"),
+ ];
+ const subsetIds = new Set<StyleSource["id"]>(["local2", "token3"]);
+ expect(cloneStyleSources(styleSources, subsetIds)).toEqual({
+ clonedStyleSources: [
+ createStyleSource("local", expectString),
+ createStyleSource("token", expectString),
+ ],
+ clonedStyleSourceIds: new Map([
+ ["local2", expectString],
+ ["token3", expectString],
+ ]),
+ });
+});
+
+test("clone style source selections with applied instance ids and style source ids", () => {
+ const styleSourceSelections = [
+ createStyleSourceSelection("instance1", ["local1", "token2"]),
+ createStyleSourceSelection("instance2", ["token3", "local4", "token5"]),
+ createStyleSourceSelection("instance3", ["local6"]),
+ ];
+ const clonedStyleSourceIds = new Map<StyleSource["id"], StyleSource["id"]>([
+ ["local1", "newLocal1"],
+ ["local4", "newLocal4"],
+ ]);
+ const clonedInstanceIds = new Map<Instance["id"], Instance["id"]>([
+ ["instance1", "newInstance1"],
+ ["instance2", "newInstance2"],
+ ]);
+ expect(
+ cloneStyleSourceSelections(
+ styleSourceSelections,
+ clonedInstanceIds,
+ clonedStyleSourceIds
+ )
+ ).toEqual([
+ createStyleSourceSelection("newInstance1", ["newLocal1", "token2"]),
+ createStyleSourceSelection("newInstance2", [
+ "token3",
+ "newLocal4",
+ "token5",
+ ]),
+ ]);
+});
+
+test("clone styles with appled new instance ids", () => {
+ const styles = [
+ createStyleDecl("instance1"),
+ createStyleDecl("instance2"),
+ createStyleDecl("instance1"),
+ createStyleDecl("instance3"),
+ createStyleDecl("instance1"),
+ createStyleDecl("instance3"),
+ ];
+ const clonedInstanceIds = new Map<Instance["id"], Instance["id"]>();
+ clonedInstanceIds.set("instance2", "newInstance2");
+ clonedInstanceIds.set("instance3", "newInstance3");
+ expect(cloneStyles(styles, clonedInstanceIds)).toEqual([
+ createStyleDecl("newInstance2"),
+ createStyleDecl("newInstance3"),
+ createStyleDecl("newInstance3"),
+ ]);
+});
+
+test("find subtree local style sources", () => {
+ const subtreeIds = new Set(["instance2", "instance4"]);
+ const styleSources = [
+ createStyleSource("local", "local1"),
+ createStyleSource("local", "local2"),
+ createStyleSource("token", "token3"),
+ createStyleSource("local", "local4"),
+ createStyleSource("token", "token5"),
+ createStyleSource("local", "local6"),
+ ];
+ const styleSourceSelections = [
+ createStyleSourceSelection("instance1", ["local1"]),
+ createStyleSourceSelection("instance2", ["local2"]),
+ createStyleSourceSelection("instance3", ["token3"]),
+ createStyleSourceSelection("instance4", ["local4", "token5"]),
+ createStyleSourceSelection("instance5", ["local6"]),
+ ];
+
+ expect(
+ findSubtreeLocalStyleSources(
+ subtreeIds,
+ styleSources,
+ styleSourceSelections
+ )
+ ).toEqual(new Set(["local2", "local4"]));
+});
diff --git a/apps/designer/app/shared/tree-utils.ts b/apps/designer/app/shared/tree-utils.ts
index b39f5708fe..3f0ff30645 100644
--- a/apps/designer/app/shared/tree-utils.ts
+++ b/apps/designer/app/shared/tree-utils.ts
@@ -1,6 +1,13 @@
import ObjectId from "bson-objectid";
import produce from "immer";
-import type { Instance } from "@webstudio-is/project-build";
+import type {
+ Instance,
+ Props,
+ Styles,
+ StyleSource,
+ StyleSources,
+ StyleSourceSelections,
+} from "@webstudio-is/project-build";
const traverseInstances = (
instance: Instance,
@@ -46,19 +53,131 @@ export const findSubtree = (
};
export const cloneInstance = (targetInstance: Instance) => {
- const clonedIds = new Map<Instance["id"], Instance["id"]>();
+ const clonedInstanceIds = new Map<Instance["id"], Instance["id"]>();
const clonedInstance = produce((targetInstance) => {
const newId = ObjectId().toString();
- clonedIds.set(targetInstance.id, newId);
+ clonedInstanceIds.set(targetInstance.id, newId);
targetInstance.id = newId;
traverseInstances(targetInstance, (instance) => {
const newId = ObjectId().toString();
- clonedIds.set(instance.id, newId);
+ clonedInstanceIds.set(instance.id, newId);
instance.id = newId;
});
})(targetInstance);
return {
- clonedIds,
+ clonedInstanceIds,
clonedInstance,
};
};
+
+export const cloneProps = (
+ props: Props,
+ clonedInstanceIds: Map<Instance["id"], Instance["id"]>
+) => {
+ const clonedProps: Props = [];
+ for (const prop of props) {
+ const instanceId = clonedInstanceIds.get(prop.instanceId);
+ if (instanceId === undefined) {
+ continue;
+ }
+ clonedProps.push({
+ ...prop,
+ id: ObjectId().toString(),
+ instanceId,
+ });
+ }
+ return clonedProps;
+};
+
+export const cloneStyleSources = (
+ styleSources: StyleSources,
+ subsetIds: Set<StyleSource["id"]>
+) => {
+ const clonedStyleSourceIds = new Map<Instance["id"], Instance["id"]>();
+ const clonedStyleSources: StyleSources = [];
+ for (const styleSource of styleSources) {
+ if (subsetIds.has(styleSource.id) === false) {
+ continue;
+ }
+ const newId = ObjectId().toString();
+ clonedStyleSourceIds.set(styleSource.id, newId);
+ clonedStyleSources.push({
+ ...styleSource,
+ id: newId,
+ });
+ }
+ return { clonedStyleSources, clonedStyleSourceIds };
+};
+
+export const cloneStyleSourceSelections = (
+ styleSourceSelections: StyleSourceSelections,
+ clonedInstanceIds: Map<Instance["id"], Instance["id"]>,
+ clonedStyleSourceIds: Map<Instance["id"], Instance["id"]>
+) => {
+ const clonedStyleSourceSelections: StyleSourceSelections = [];
+ for (const styleSourceSelection of styleSourceSelections) {
+ const instanceId = clonedInstanceIds.get(styleSourceSelection.instanceId);
+ if (instanceId === undefined) {
+ continue;
+ }
+ // preserve style source id when not cloned
+ // which means it is non-local style source
+ const values = styleSourceSelection.values.map(
+ (styleSourceId) =>
+ clonedStyleSourceIds.get(styleSourceId) ?? styleSourceId
+ );
+ clonedStyleSourceSelections.push({
+ values,
+ instanceId,
+ });
+ }
+ return clonedStyleSourceSelections;
+};
+
+// @todo migrate to style source variant
+export const cloneStyles = (
+ styles: Styles,
+ clonedInstanceIds: Map<Instance["id"], Instance["id"]>
+) => {
+ const clonedStyles: Styles = [];
+ for (const styleDecl of styles) {
+ const instanceId = clonedInstanceIds.get(styleDecl.instanceId);
+ if (instanceId === undefined) {
+ continue;
+ }
+ clonedStyles.push({
+ ...styleDecl,
+ instanceId,
+ });
+ }
+ return clonedStyles;
+};
+
+export const findSubtreeLocalStyleSources = (
+ subtreeIds: Set<Instance["id"]>,
+ styleSources: StyleSources,
+ styleSourceSelections: StyleSourceSelections
+) => {
+ const localStyleSourceIds = new Set<StyleSource["id"]>();
+ for (const styleSource of styleSources) {
+ if (styleSource.type === "local") {
+ localStyleSourceIds.add(styleSource.id);
+ }
+ }
+
+ const subtreeLocalStyleSourceIds = new Set<StyleSource["id"]>();
+ for (const { instanceId, values } of styleSourceSelections) {
+ // skip selections outside of subtree
+ if (subtreeIds.has(instanceId) === false) {
+ continue;
+ }
+ // find only local style sources on selections
+ for (const styleSourceId of values) {
+ if (localStyleSourceIds.has(styleSourceId)) {
+ subtreeLocalStyleSourceIds.add(styleSourceId);
+ }
+ }
+ }
+
+ return subtreeLocalStyleSourceIds;
+};
diff --git a/packages/project/src/db/index.ts b/packages/project/src/db/index.ts
index e40697ef97..8d3b64956b 100644
--- a/packages/project/src/db/index.ts
+++ b/packages/project/src/db/index.ts
@@ -1,7 +1,18 @@
import * as project from "./project";
import * as tree from "./tree";
import * as styles from "./styles";
+import * as styleSources from "./style-sources";
+import * as styleSourceSelections from "./style-source-selections";
import * as props from "./props";
import * as breakpoints from "./breakpoints";
import * as build from "./build";
-export { project, tree, breakpoints, styles, props, build };
+export {
+ project,
+ tree,
+ breakpoints,
+ styles,
+ styleSources,
+ styleSourceSelections,
+ props,
+ build,
+};
diff --git a/packages/project/src/db/style-source-selections.ts b/packages/project/src/db/style-source-selections.ts
new file mode 100644
index 0000000000..13b1f71415
--- /dev/null
+++ b/packages/project/src/db/style-source-selections.ts
@@ -0,0 +1,45 @@
+import { type Patch, applyPatches } from "immer";
+import { prisma } from "@webstudio-is/prisma-client";
+import {
+ authorizeProject,
+ type AppContext,
+} from "@webstudio-is/trpc-interface/server";
+import { StyleSources, type Tree } from "@webstudio-is/project-build";
+import type { Project } from "./schema";
+
+export const patch = async (
+ { treeId, projectId }: { treeId: Tree["id"]; projectId: Project["id"] },
+ patches: Array<Patch>,
+ context: AppContext
+) => {
+ const canEdit = await authorizeProject.hasProjectPermit(
+ { projectId, permit: "edit" },
+ context
+ );
+
+ if (canEdit === false) {
+ throw new Error("You don't have edit access to this project");
+ }
+
+ const tree = await prisma.tree.findUnique({
+ where: { id: treeId },
+ });
+ if (tree === null) {
+ return;
+ }
+
+ const styleSourceSelections = StyleSources.parse(
+ JSON.parse(tree.styleSelections)
+ );
+
+ const patchedStyleSourceSelections = StyleSources.parse(
+ applyPatches(styleSourceSelections, patches)
+ );
+
+ await prisma.tree.update({
+ data: {
+ styleSelections: JSON.stringify(patchedStyleSourceSelections),
+ },
+ where: { id: treeId },
+ });
+};
diff --git a/packages/project/src/db/style-sources.ts b/packages/project/src/db/style-sources.ts
new file mode 100644
index 0000000000..fb8b4b18db
--- /dev/null
+++ b/packages/project/src/db/style-sources.ts
@@ -0,0 +1,43 @@
+import { type Patch, applyPatches } from "immer";
+import { prisma } from "@webstudio-is/prisma-client";
+import {
+ authorizeProject,
+ type AppContext,
+} from "@webstudio-is/trpc-interface/server";
+import { StyleSources } from "@webstudio-is/project-build";
+import type { Build, Project } from "./schema";
+
+export const patch = async (
+ { buildId, projectId }: { buildId: Build["id"]; projectId: Project["id"] },
+ patches: Array<Patch>,
+ context: AppContext
+) => {
+ const canEdit = await authorizeProject.hasProjectPermit(
+ { projectId, permit: "edit" },
+ context
+ );
+
+ if (canEdit === false) {
+ throw new Error("You don't have edit access to this project");
+ }
+
+ const build = await prisma.build.findUnique({
+ where: { id: buildId },
+ });
+ if (build === null) {
+ return;
+ }
+
+ const styleSources = StyleSources.parse(JSON.parse(build.styleSources));
+
+ const patchedStyleSources = StyleSources.parse(
+ applyPatches(styleSources, patches)
+ );
+
+ await prisma.build.update({
+ data: {
+ styleSources: JSON.stringify(patchedStyleSources),
+ },
+ where: { id: buildId },
+ });
+};