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.

feat: add collection component to builder (#2657)

Bogdan Chadkind361c9ecee9a
diff --git a/apps/builder/app/builder/features/settings-panel/controls/json.tsx b/apps/builder/app/builder/features/settings-panel/controls/json.tsx
index 0c4d7ff71d..c50e368638 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/json.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/json.tsx
@@ -49,7 +49,7 @@ export const JsonControl = ({
<Box css={{ py: theme.spacing[2] }}>
<CodeEditor
// reset editor every time value is changed
- key={localValue.value}
+ key={valueString}
variables={emptyVariables}
defaultValue={localValue.value}
onChange={localValue.set}
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 4954f5bae4..4c7760dce1 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
@@ -249,9 +249,6 @@ export const PropsSectionContainer = ({
return prop;
}
const propValue = propValues?.get(prop.name);
- if (propValue === undefined) {
- return prop;
- }
return { ...prop, ...getPropTypeAndValue(propValue) };
}) ?? [],
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx b/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx
index 04ce615562..3902a2988f 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx
@@ -4,6 +4,7 @@ import { usePress } from "@react-aria/interactions";
import {
type WsComponentMeta,
componentCategories,
+ collectionComponent,
} from "@webstudio-is/react-sdk";
import {
theme,
@@ -27,6 +28,7 @@ import { MetaIcon } from "~/builder/shared/meta-icon";
import { registeredComponentMetasStore } from "~/shared/nano-states";
import { getMetaMaps } from "./get-meta-maps";
import { getInstanceLabel } from "~/shared/instance-utils";
+import { isFeatureEnabled } from "@webstudio-is/feature-flags";
type TabContentProps = {
onSetActiveTab: (tabName: TabName) => void;
@@ -82,7 +84,13 @@ export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {
(meta: WsComponentMeta, index) => {
const component = componentNamesByMeta.get(meta);
if (component === undefined) {
- return null;
+ return;
+ }
+ if (
+ component === collectionComponent &&
+ isFeatureEnabled("bindings") === false
+ ) {
+ return;
}
return (
<Tooltip
diff --git a/apps/builder/app/builder/shared/navigator-tree.tsx b/apps/builder/app/builder/shared/navigator-tree.tsx
index dcbd6faf58..9b22ab7c2d 100644
--- a/apps/builder/app/builder/shared/navigator-tree.tsx
+++ b/apps/builder/app/builder/shared/navigator-tree.tsx
@@ -2,6 +2,7 @@ import { useCallback, useMemo } from "react";
import { useStore } from "@nanostores/react";
import { shallowEqual } from "shallow-equal";
import { toast } from "@webstudio-is/design-system";
+import { collectionComponent } from "@webstudio-is/react-sdk";
import {
hoveredInstanceSelectorStore,
instancesStore,
@@ -70,8 +71,11 @@ export const NavigatorTree = () => {
const componentSelector: string[] = [];
for (const instanceId of instanceSelector) {
const component = instances.get(instanceId)?.component;
+ // collection produce fake instances
+ // and fragment does not have constraints
if (component === undefined) {
- return -1;
+ componentSelector.push("Fragment");
+ continue;
}
componentSelector.push(component);
}
@@ -85,10 +89,16 @@ export const NavigatorTree = () => {
);
const isItemHidden = useCallback(
- ([instanceId]: InstanceSelector) =>
- // fragment is internal component to group other instances
- // for example to support multiple children in slots
- instances.get(instanceId)?.component === "Fragment",
+ (instanceSelector: InstanceSelector) => {
+ const [instanceId, parentInstanceId] = instanceSelector;
+ return (
+ // fragment is internal component to group other instances
+ // for example to support multiple children in slots
+ instances.get(instanceId)?.component === "Fragment" ||
+ // hide collection items which are temporary generated
+ instances.get(parentInstanceId)?.component === collectionComponent
+ );
+ },
[instances]
);
diff --git a/apps/builder/app/builder/shared/tree/index.tsx b/apps/builder/app/builder/shared/tree/index.tsx
index 38dfaa1d55..deba946aaa 100644
--- a/apps/builder/app/builder/shared/tree/index.tsx
+++ b/apps/builder/app/builder/shared/tree/index.tsx
@@ -10,8 +10,11 @@ import {
theme,
} from "@webstudio-is/design-system";
import type { Instance } from "@webstudio-is/sdk";
+import { collectionComponent } from "@webstudio-is/react-sdk";
import {
+ $propValuesByInstanceSelector,
editingItemIdStore,
+ getIndexedInstanceId,
instancesStore,
registeredComponentMetasStore,
} from "~/shared/nano-states";
@@ -30,6 +33,7 @@ export const InstanceTree = (
const metas = useStore(registeredComponentMetasStore);
const instances = useStore(instancesStore);
const editingItemId = useStore(editingItemIdStore);
+ const propValues = useStore($propValuesByInstanceSelector);
const canLeaveParent = useCallback(
([instanceId]: InstanceSelector) => {
@@ -44,9 +48,37 @@ export const InstanceTree = (
);
const getItemChildren = useCallback(
- ([instanceId]: InstanceSelector) => {
- const instance = instances.get(instanceId);
+ (instanceSelector: InstanceSelector) => {
+ const [instanceId, parentId] = instanceSelector;
+ let instance = instances.get(instanceId);
const children: Instance[] = [];
+
+ // put fake collection item instances according to collection data
+ if (instance?.component === collectionComponent) {
+ const data = propValues
+ .get(JSON.stringify(instanceSelector))
+ ?.get("data");
+ // create items only when collection has content
+ if (Array.isArray(data) && instance.children.length > 0) {
+ data.forEach((_item, index) => {
+ children.push({
+ type: "instance",
+ id: getIndexedInstanceId(instanceId, index),
+ component: "ws:collection-item",
+ children: [],
+ });
+ });
+ }
+ return children;
+ }
+
+ // put parent children as own when parent is a collection
+ if (instance === undefined) {
+ const parentInstance = instances.get(parentId);
+ if (parentInstance?.component === collectionComponent) {
+ instance = parentInstance;
+ }
+ }
if (instance === undefined) {
return children;
}
@@ -63,7 +95,7 @@ export const InstanceTree = (
}
return children;
},
- [instances]
+ [instances, propValues]
);
const updateInstanceLabel = useCallback(
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index 42fdf673af..a4535ad3bc 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -5,6 +5,8 @@ import {
type Params,
type Components,
createElementsTree,
+ coreMetas,
+ corePropsMetas,
} from "@webstudio-is/react-sdk";
import * as baseComponents from "@webstudio-is/sdk-components-react";
import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";
@@ -123,6 +125,11 @@ export const Canvas = ({
const isPreviewMode = useStore($isPreviewMode);
useMount(() => {
+ registerComponentLibrary({
+ components: {},
+ metas: coreMetas,
+ propsMetas: corePropsMetas,
+ });
registerComponentLibrary({
components: baseComponents,
metas: baseComponentMetas,
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 2f20c6f3f7..d9e2b405d6 100644
--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
@@ -5,6 +5,8 @@ import {
useRef,
useLayoutEffect,
useMemo,
+ Fragment,
+ type ReactNode,
} from "react";
import { Suspense, lazy } from "react";
import { computed } from "nanostores";
@@ -21,9 +23,13 @@ import {
selectorIdAttribute,
indexAttribute,
getIndexesWithinAncestors,
+ createInstanceChildrenElements,
+ collectionComponent,
+ type AnyComponent,
} from "@webstudio-is/react-sdk";
import {
$propValuesByInstanceSelector,
+ getIndexedInstanceId,
instancesStore,
registeredComponentMetasStore,
selectedInstanceRenderStateStore,
@@ -92,6 +98,20 @@ const ContentEditable = ({
return renderComponentWithRef(ref);
};
+const StubComponent = forwardRef<HTMLDivElement, { children?: ReactNode }>(
+ (props, ref) => {
+ return (
+ <div
+ {...props}
+ ref={ref}
+ style={{ display: props.children ? "contents" : "block" }}
+ />
+ );
+ }
+);
+
+StubComponent.displayName = "StubComponent";
+
// this utility is temporary solution to compute instance selectors
// for rich text subtree which cannot have slots so its safe to traverse ancestors
// until editor instance is reached
@@ -224,7 +244,7 @@ const mergeProps = (
export const WebstudioComponentCanvas = forwardRef<
HTMLElement,
WebstudioComponentProps
->(({ instance, instanceSelector, children, components, ...restProps }, ref) => {
+>(({ instance, instanceSelector, components, ...restProps }, ref) => {
const rootRef = useRef<null | HTMLDivElement>(null);
const instanceId = instance.id;
const instanceStyles = useInstanceStyles(instanceId);
@@ -238,6 +258,13 @@ export const WebstudioComponentCanvas = forwardRef<
const { [showAttribute]: show = true, ...instanceProps } =
useInstanceProps(instanceSelector);
+ const children = createInstanceChildrenElements({
+ instances,
+ instanceSelector,
+ children: instance.children,
+ Component: WebstudioComponentCanvas,
+ components,
+ });
/**
* Prevents edited element from having a size of 0 on the first render.
* Directly using `children` in Text Edit
@@ -261,16 +288,41 @@ export const WebstudioComponentCanvas = forwardRef<
}
});
- const Component = components.get(instance.component);
-
if (show === false) {
return <></>;
}
- if (Component === undefined) {
- return <></>;
+ if (instance.component === collectionComponent) {
+ const data = instanceProps.data;
+ // render stub component when no data or children
+ if (
+ Array.isArray(data) &&
+ data.length > 0 &&
+ instance.children.length > 0
+ ) {
+ return data.map((_item, index) => {
+ return (
+ <Fragment key={index}>
+ {createInstanceChildrenElements({
+ instances,
+ // create fake indexed id to distinct items for select and hover
+ instanceSelector: [
+ getIndexedInstanceId(instance.id, index),
+ ...instanceSelector,
+ ],
+ children: instance.children,
+ Component: WebstudioComponentCanvas,
+ components,
+ })}
+ </Fragment>
+ );
+ });
+ }
}
+ const Component =
+ components.get(instance.component) ?? (StubComponent as AnyComponent);
+
const props: {
[componentAttribute]: string;
[idAttribute]: string;
@@ -348,7 +400,8 @@ export const WebstudioComponentCanvas = forwardRef<
export const WebstudioComponentPreview = forwardRef<
HTMLElement,
WebstudioComponentProps
->(({ instance, instanceSelector, children, components, ...restProps }, ref) => {
+>(({ instance, instanceSelector, components, ...restProps }, ref) => {
+ const instances = useStore(instancesStore);
const instanceStyles = useInstanceStyles(instance.id);
useCssRules({ instanceId: instance.id, instanceStyles });
const { [showAttribute]: show = true, ...instanceProps } =
@@ -361,13 +414,48 @@ export const WebstudioComponentPreview = forwardRef<
if (show === false) {
return <></>;
}
+
+ if (instance.component === collectionComponent) {
+ const data = instanceProps.data;
+ // render stub component when no data or children
+ if (
+ Array.isArray(data) &&
+ data.length > 0 &&
+ instance.children.length > 0
+ ) {
+ return data.map((_item, index) => {
+ return (
+ <Fragment key={index}>
+ {createInstanceChildrenElements({
+ instances,
+ // create fake indexed id to distinct items for select and hover
+ instanceSelector: [
+ getIndexedInstanceId(instance.id, index),
+ ...instanceSelector,
+ ],
+ children: instance.children,
+ Component: WebstudioComponentPreview,
+ components,
+ })}
+ </Fragment>
+ );
+ });
+ }
+ }
+
const Component = components.get(instance.component);
if (Component === undefined) {
return <></>;
}
return (
<Component {...props} ref={ref}>
- {children}
+ {createInstanceChildrenElements({
+ instances,
+ instanceSelector,
+ children: instance.children,
+ Component: WebstudioComponentPreview,
+ components,
+ })}
</Component>
);
});
diff --git a/apps/builder/app/canvas/shared/use-drag-drop.ts b/apps/builder/app/canvas/shared/use-drag-drop.ts
index 6df910b678..4b0e1f910c 100644
--- a/apps/builder/app/canvas/shared/use-drag-drop.ts
+++ b/apps/builder/app/canvas/shared/use-drag-drop.ts
@@ -96,8 +96,11 @@ const findClosestDroppableInstanceSelector = (
const componentSelector: string[] = [];
for (const instanceId of instanceSelector) {
const component = instances.get(instanceId)?.component;
+ // collection produce fake instances
+ // and fragment does not have constraints
if (component === undefined) {
- return;
+ componentSelector.push("Fragment");
+ continue;
}
componentSelector.push(component);
}
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts
index 74a21edec9..5fbdd4b265 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts
@@ -10,7 +10,11 @@ import type {
Page,
} from "@webstudio-is/sdk";
import type { Project } from "@webstudio-is/project";
-import { encodeDataSourceVariable } from "@webstudio-is/react-sdk";
+import {
+ collectionComponent,
+ encodeDataSourceVariable,
+ coreMetas,
+} from "@webstudio-is/react-sdk";
import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";
import { registerContainers } from "../sync";
import {
@@ -28,7 +32,9 @@ import { onCopy, onPaste } from "./plugin-instance";
enableMapSet();
registerContainers();
-registeredComponentMetasStore.set(new Map(Object.entries(baseComponentMetas)));
+registeredComponentMetasStore.set(
+ new Map(Object.entries({ ...baseComponentMetas, ...coreMetas }))
+);
projectStore.set({ id: "my-project" } as Project);
pagesStore.set({
meta: {},
@@ -359,4 +365,90 @@ describe("data sources", () => {
])
);
});
+
+ test("copy parameter prop with new data source", () => {
+ const instances: Instances = toMap([
+ createInstance("body", "Body", [{ type: "id", value: "list" }]),
+ createInstance("list", collectionComponent, []),
+ ] satisfies Instance[]);
+ const dataSources: DataSources = toMap([
+ {
+ id: "itemDataSource",
+ scopeInstanceId: "list",
+ type: "variable",
+ name: "item",
+ value: { type: "json", value: {} },
+ },
+ ] satisfies DataSource[]);
+ const props: Props = toMap([
+ {
+ id: "dataProp",
+ instanceId: "list",
+ name: "data",
+ type: "json",
+ value: [],
+ },
+ {
+ id: "itemProp",
+ instanceId: "list",
+ name: "item",
+ type: "parameter",
+ value: "itemDataSource",
+ },
+ ] satisfies Prop[]);
+ instancesStore.set(instances);
+ propsStore.set(props);
+ dataSourcesStore.set(dataSources);
+ selectedInstanceSelectorStore.set(["list", "body"]);
+ const clipboardData = onCopy() ?? "";
+ selectedInstanceSelectorStore.set(["body"]);
+ onPaste(clipboardData);
+
+ const instancesDifference = getMapDifference(
+ instances,
+ instancesStore.get()
+ );
+ const [collectionId] = instancesDifference.keys();
+
+ const dataSourcesDifference = getMapDifference(
+ dataSources,
+ dataSourcesStore.get()
+ );
+ const [itemDataSourceId] = dataSourcesDifference.keys();
+ expect(dataSourcesDifference).toEqual(
+ new Map([
+ [
+ itemDataSourceId,
+ {
+ id: itemDataSourceId,
+ scopeInstanceId: collectionId,
+ type: "variable",
+ name: "item",
+ value: { type: "json", value: {} },
+ },
+ ],
+ ])
+ );
+
+ const propsDifference = getMapDifference(props, propsStore.get());
+ const [dataPropId, itemPropId] = propsDifference.keys();
+ expect(propsDifference).toEqual(
+ toMap([
+ {
+ id: dataPropId,
+ instanceId: collectionId,
+ name: "data",
+ type: "json",
+ value: [],
+ },
+ {
+ id: itemPropId,
+ instanceId: collectionId,
+ name: "item",
+ type: "parameter",
+ value: itemDataSourceId,
+ },
+ ])
+ );
+ });
});
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.ts
index 0c4a8e43d9..44bab0e796 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts
@@ -290,6 +290,13 @@ export const onPaste = (clipboardData: string): boolean => {
return identifier;
};
+ if (prop.type === "parameter") {
+ return {
+ ...prop,
+ value: copiedDataSourceIds.get(prop.value) ?? prop.value,
+ };
+ }
+
if (prop.type === "expression") {
return {
...prop,
diff --git a/apps/builder/app/shared/instance-utils.test.ts b/apps/builder/app/shared/instance-utils.test.ts
index d2c8dd7be3..110ae23d58 100644
--- a/apps/builder/app/shared/instance-utils.test.ts
+++ b/apps/builder/app/shared/instance-utils.test.ts
@@ -3,6 +3,7 @@ import { describe, test, expect, beforeEach } from "@jest/globals";
import {
encodeDataSourceVariable,
portalComponent,
+ collectionComponent,
type WsComponentMeta,
} from "@webstudio-is/react-sdk";
import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";
@@ -25,6 +26,7 @@ import {
deleteInstance,
getInstancesSlice,
insertInstancesSliceCopy,
+ reparentInstance,
} from "./instance-utils";
import {
$assets,
@@ -382,14 +384,6 @@ describe("find closest droppable target", () => {
parentSelector: ["box", "body"],
position: "end",
});
- expect(
- findClosestDroppableTarget(
- defaultMetasMap,
- instances,
- ["not-existing", "body"],
- emptyInsertConstraints
- )
- ).toEqual(undefined);
});
test("puts in the end of root instance", () => {
@@ -520,49 +514,106 @@ test("insert template data with only new style sources", () => {
);
});
-test("delete instance with its children", () => {
- // body
- // box1
- // box11
- // box2
- instancesStore.set(
- new Map([
- createInstancePair("body", "Body", [
- { type: "id", value: "box1" },
- { type: "id", value: "box2" },
- ]),
- createInstancePair("box1", "Box", [{ type: "id", value: "box11" }]),
- createInstancePair("box11", "Box", []),
- createInstancePair("box2", "Box", []),
- ])
- );
- registeredComponentMetasStore.set(createFakeComponentMetas({}));
- deleteInstance(["box1", "body"]);
- expect(instancesStore.get()).toEqual(
- new Map([
- createInstancePair("body", "Body", [{ type: "id", value: "box2" }]),
- createInstancePair("box2", "Box", []),
- ])
- );
+describe("reparent instance", () => {
+ test("from collectioo item", () => {
+ // body
+ // list
+ // box
+ instancesStore.set(
+ new Map([
+ createInstancePair("body", "Body", [{ type: "id", value: "list" }]),
+ createInstancePair("list", collectionComponent, [
+ { type: "id", value: "box" },
+ ]),
+ createInstancePair("box", "Box", []),
+ ])
+ );
+ registeredComponentMetasStore.set(createFakeComponentMetas({}));
+ reparentInstance(["box", "list[0]", "list", "body"], {
+ parentSelector: ["body"],
+ position: 1,
+ });
+ expect(instancesStore.get()).toEqual(
+ new Map([
+ createInstancePair("body", "Body", [
+ { type: "id", value: "list" },
+ { type: "id", value: "box" },
+ ]),
+ createInstancePair("list", collectionComponent, []),
+ createInstancePair("box", "Box", []),
+ ])
+ );
+ });
});
-test("prevent deleting root instance", () => {
- // body
- // box1
- instancesStore.set(
- new Map([
- createInstancePair("body", "Body", [{ type: "id", value: "box1" }]),
- createInstancePair("box1", "Box", []),
- ])
- );
- registeredComponentMetasStore.set(createFakeComponentMetas({}));
- deleteInstance(["body"]);
- expect(instancesStore.get()).toEqual(
- new Map([
- createInstancePair("body", "Body", [{ type: "id", value: "box1" }]),
- createInstancePair("box1", "Box", []),
- ])
- );
+describe("delete instance", () => {
+ test("delete instance with its children", () => {
+ // body
+ // box1
+ // box11
+ // box2
+ instancesStore.set(
+ new Map([
+ createInstancePair("body", "Body", [
+ { type: "id", value: "box1" },
+ { type: "id", value: "box2" },
+ ]),
+ createInstancePair("box1", "Box", [{ type: "id", value: "box11" }]),
+ createInstancePair("box11", "Box", []),
+ createInstancePair("box2", "Box", []),
+ ])
+ );
+ registeredComponentMetasStore.set(createFakeComponentMetas({}));
+ deleteInstance(["box1", "body"]);
+ expect(instancesStore.get()).toEqual(
+ new Map([
+ createInstancePair("body", "Body", [{ type: "id", value: "box2" }]),
+ createInstancePair("box2", "Box", []),
+ ])
+ );
+ });
+
+ test("prevent deleting root instance", () => {
+ // body
+ // box1
+ instancesStore.set(
+ new Map([
+ createInstancePair("body", "Body", [{ type: "id", value: "box1" }]),
+ createInstancePair("box1", "Box", []),
+ ])
+ );
+ registeredComponentMetasStore.set(createFakeComponentMetas({}));
+ deleteInstance(["body"]);
+ expect(instancesStore.get()).toEqual(
+ new Map([
+ createInstancePair("body", "Body", [{ type: "id", value: "box1" }]),
+ createInstancePair("box1", "Box", []),
+ ])
+ );
+ });
+
+ test("delete instance from collection item", () => {
+ // body
+ // list
+ // box
+ instancesStore.set(
+ new Map([
+ createInstancePair("body", "Body", [{ type: "id", value: "list" }]),
+ createInstancePair("list", collectionComponent, [
+ { type: "id", value: "box" },
+ ]),
+ createInstancePair("box", "Box", []),
+ ])
+ );
+ registeredComponentMetasStore.set(createFakeComponentMetas({}));
+ deleteInstance(["box", "list[0]", "list", "body"]);
+ expect(instancesStore.get()).toEqual(
+ new Map([
+ createInstancePair("body", "Body", [{ type: "id", value: "list" }]),
+ createInstancePair("list", collectionComponent, []),
+ ])
+ );
+ });
});
describe("get instances slice", () => {
@@ -1327,6 +1378,13 @@ describe("insert instances slice copy", () => {
},
],
},
+ {
+ id: "parameterId",
+ instanceId: "body",
+ name: "myProp3",
+ type: "parameter",
+ value: "variableId",
+ },
],
},
availableDataSources: new Set(),
@@ -1363,6 +1421,13 @@ describe("insert instances slice copy", () => {
},
],
},
+ {
+ id: expect.not.stringMatching("parameterId"),
+ instanceId: expect.not.stringMatching("body"),
+ name: "myProp3",
+ type: "parameter",
+ value: newVariableId,
+ },
]);
});
@@ -1492,6 +1557,13 @@ describe("insert instances slice copy", () => {
},
],
},
+ {
+ id: "parameterId",
+ instanceId: "fragment",
+ name: "myProp3",
+ type: "parameter",
+ value: "variableId",
+ },
],
},
availableDataSources: new Set(),
@@ -1526,6 +1598,13 @@ describe("insert instances slice copy", () => {
},
],
},
+ {
+ id: "parameterId",
+ instanceId: "fragment",
+ name: "myProp3",
+ type: "parameter",
+ value: `variableId`,
+ },
]);
});
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index 4c36817556..7ca3e7cd1f 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -27,6 +27,7 @@ import {
validateExpression,
encodeDataSourceVariable,
portalComponent,
+ collectionComponent,
} from "@webstudio-is/react-sdk";
import {
propsStore,
@@ -264,8 +265,11 @@ export const findClosestDroppableTarget = (
const componentSelector: string[] = [];
for (const instanceId of instanceSelector) {
const component = instances.get(instanceId)?.component;
+ // collection produce fake instances
+ // and fragment does not have constraints
if (component === undefined) {
- return;
+ componentSelector.push("Fragment");
+ continue;
}
componentSelector.push(component);
}
@@ -446,11 +450,12 @@ export const deleteInstance = (instanceSelector: InstanceSelector) => {
) => {
let targetInstanceId = instanceSelector[0];
const parentInstanceId = instanceSelector[1];
- const grandparentInstanceId = instanceSelector[2];
let parentInstance =
parentInstanceId === undefined
? undefined
: instances.get(parentInstanceId);
+ const grandparentInstanceId = instanceSelector[2];
+ const grandparentInstance = instances.get(grandparentInstanceId);
// delete parent fragment too if its last child is going to be deleted
// use case for slots: slot became empty and remove display: contents
@@ -458,10 +463,15 @@ export const deleteInstance = (instanceSelector: InstanceSelector) => {
if (
parentInstance?.component === "Fragment" &&
parentInstance.children.length === 1 &&
- grandparentInstanceId !== undefined
+ grandparentInstance
) {
targetInstanceId = parentInstance.id;
- parentInstance = instances.get(grandparentInstanceId);
+ parentInstance = grandparentInstance;
+ }
+
+ // skip parent fake "item" instance and use grandparent collection as parent
+ if (grandparentInstance?.component === collectionComponent) {
+ parentInstance = grandparentInstance;
}
const instanceIds = findTreeInstanceIdsExcludingSlotDescendants(
@@ -1091,6 +1101,12 @@ export const insertInstancesSliceCopy = ({
}),
};
}
+ if (prop.type === "parameter") {
+ prop = {
+ ...prop,
+ value: newDataSourceIds.get(prop.value) ?? prop.value,
+ };
+ }
const newId = nanoid();
props.set(newId, {
...prop,
diff --git a/apps/builder/app/shared/nano-states/props.test.ts b/apps/builder/app/shared/nano-states/props.test.ts
index 44fe72d2e3..9b9e0a4f07 100644
--- a/apps/builder/app/shared/nano-states/props.test.ts
+++ b/apps/builder/app/shared/nano-states/props.test.ts
@@ -1,6 +1,7 @@
import { expect, test } from "@jest/globals";
import { cleanStores } from "nanostores";
import type { Instance, Page } from "@webstudio-is/sdk";
+import { collectionComponent } from "@webstudio-is/react-sdk";
import { $instances } from "./instances";
import { $propValuesByInstanceSelector } from "./props";
import { $pages, $selectedPageId } from "./pages";
@@ -252,3 +253,80 @@ test("resolve page prop values when params is provided", () => {
cleanStores($propValuesByInstanceSelector);
});
+
+test("compute expression from collection items", () => {
+ $instances.set(
+ toMap([
+ {
+ id: "list",
+ type: "instance",
+ component: collectionComponent,
+ children: [{ type: "id", value: "item" }],
+ },
+ {
+ id: "item",
+ type: "instance",
+ component: "Box",
+ children: [],
+ },
+ ])
+ );
+ selectPageRoot("list");
+ $dataSources.set(
+ toMap([
+ {
+ id: "itemId",
+ type: "variable",
+ name: "item",
+ value: { type: "json", value: {} },
+ },
+ ])
+ );
+ $props.set(
+ toMap([
+ {
+ id: "prop1",
+ name: "data",
+ instanceId: "list",
+ type: "json",
+ value: ["orange", "apple", "banana"],
+ },
+ {
+ id: "prop2",
+ name: "item",
+ instanceId: "list",
+ type: "parameter",
+ value: "itemId",
+ },
+ {
+ id: "prop3",
+ name: "ariaLabel",
+ instanceId: "item",
+ type: "expression",
+ value: `$ws$dataSource$itemId`,
+ },
+ ])
+ );
+ expect($propValuesByInstanceSelector.get()).toEqual(
+ new Map([
+ [
+ JSON.stringify(["list"]),
+ new Map<string, unknown>([["data", ["orange", "apple", "banana"]]]),
+ ],
+ [
+ JSON.stringify(["item", "list[0]", "list"]),
+ new Map<string, unknown>([["ariaLabel", "orange"]]),
+ ],
+ [
+ JSON.stringify(["item", "list[1]", "list"]),
+ new Map<string, unknown>([["ariaLabel", "apple"]]),
+ ],
+ [
+ JSON.stringify(["item", "list[2]", "list"]),
+ new Map<string, unknown>([["ariaLabel", "banana"]]),
+ ],
+ ])
+ );
+
+ cleanStores($propValuesByInstanceSelector);
+});
diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.ts
index c9ce5336c7..d6138790fa 100644
--- a/apps/builder/app/shared/nano-states/props.ts
+++ b/apps/builder/app/shared/nano-states/props.ts
@@ -7,6 +7,7 @@ import {
type Prop,
} from "@webstudio-is/sdk";
import {
+ collectionComponent,
encodeDataSourceVariable,
generateDataSources,
normalizeProps,
@@ -23,6 +24,11 @@ import { groupBy } from "../array-utils";
import type { InstanceSelector } from "../tree-utils";
import { $params } from "~/canvas/stores";
+export const getIndexedInstanceId = (
+ instanceId: Instance["id"],
+ index: number
+) => `${instanceId}[${index}]`;
+
// result of executing generated code
// includes variables, computed expressions and action callbacks
const $dataSourcesLogic = computed(
@@ -144,7 +150,6 @@ export const $propValuesByInstanceSelector = computed(
const propValues = new Map<Prop["name"], unknown>();
let props = propsByInstanceId.get(instanceId);
- // @todo store parameters to update with core components later
const parameters = new Map<Prop["name"], DataSource["id"]>();
if (props) {
// ignore asset and page props when params is not provided
@@ -189,6 +194,22 @@ export const $propValuesByInstanceSelector = computed(
JSON.stringify(instanceSelector),
propValues
);
+ if (instance.component === collectionComponent) {
+ const data = propValues.get("data");
+ const itemVariableId = parameters.get("item");
+ if (Array.isArray(data) && itemVariableId !== undefined) {
+ data.forEach((item, index) => {
+ values.set(itemVariableId, item);
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ const indexId = getIndexedInstanceId(instanceId, index);
+ traverseInstances([child.value, indexId, ...instanceSelector]);
+ }
+ }
+ });
+ }
+ return;
+ }
for (const child of instance.children) {
if (child.type === "id") {
traverseInstances([child.value, ...instanceSelector]);
diff --git a/apps/builder/app/shared/tree-utils.ts b/apps/builder/app/shared/tree-utils.ts
index e11c2a86b7..b1d033f09f 100644
--- a/apps/builder/app/shared/tree-utils.ts
+++ b/apps/builder/app/shared/tree-utils.ts
@@ -19,7 +19,10 @@ import {
findTreeInstanceIdsExcludingSlotDescendants,
} from "@webstudio-is/sdk";
import { equalMedia } from "@webstudio-is/css-engine";
-import type { WsComponentMeta } from "@webstudio-is/react-sdk";
+import {
+ collectionComponent,
+ type WsComponentMeta,
+} from "@webstudio-is/react-sdk";
// slots can have multiple parents so instance should be addressed
// with full rendered path to avoid double selections with slots
@@ -225,11 +228,22 @@ export const reparentInstanceMutable = (
instanceSelector: InstanceSelector,
dropTarget: DroppableTarget
) => {
- const [instanceId, parentInstanceId] = instanceSelector;
- const prevParent =
+ const [instanceId, parentInstanceId, grandparentInstanceId] =
+ instanceSelector;
+ const grandparentInstance =
+ grandparentInstanceId === undefined
+ ? undefined
+ : instances.get(grandparentInstanceId);
+
+ let prevParent =
parentInstanceId === undefined
? undefined
: instances.get(parentInstanceId);
+ // skip parent fake "item" instance and use grandparent collection as parent
+ if (grandparentInstance?.component === collectionComponent) {
+ prevParent = grandparentInstance;
+ }
+
dropTarget =
getInstanceOrCreateFragmentIfNecessary(instances, dropTarget) ?? dropTarget;
dropTarget =
diff --git a/packages/react-sdk/package.json b/packages/react-sdk/package.json
index 2f88c4d1da..92f7cc06c9 100644
--- a/packages/react-sdk/package.json
+++ b/packages/react-sdk/package.json
@@ -38,6 +38,7 @@
"@jsep-plugin/object": "^1.2.1",
"@webstudio-is/css-engine": "workspace:*",
"@webstudio-is/fonts": "workspace:*",
+ "@webstudio-is/icons": "workspace:^",
"@webstudio-is/image": "workspace:*",
"@webstudio-is/sdk": "workspace:*",
"change-case": "^5.0.2",
diff --git a/packages/react-sdk/src/core-components.ts b/packages/react-sdk/src/core-components.ts
index b1e00b33a0..0a1f90bd9b 100644
--- a/packages/react-sdk/src/core-components.ts
+++ b/packages/react-sdk/src/core-components.ts
@@ -1,3 +1,69 @@
+import { ListIcon } from "@webstudio-is/icons/svg";
+import type {
+ WsComponentMeta,
+ WsComponentPropsMeta,
+} from "./components/component-meta";
+
export const portalComponent = "Slot";
-export const collectionComponent = "ws:component";
+export const collectionComponent = "ws:collection";
+
+const collectionMeta: WsComponentMeta = {
+ category: "general",
+ order: 7,
+ type: "container",
+ label: "Collection",
+ icon: ListIcon,
+ template: [
+ {
+ type: "instance",
+ component: collectionComponent,
+ variables: {
+ collectionItem: { initialValue: "" },
+ },
+ props: [
+ {
+ name: "data",
+ type: "json",
+ value: ["apple", "orange", "banana"],
+ },
+ { name: "item", type: "parameter", variableName: "collectionItem" },
+ ],
+ children: [
+ {
+ type: "instance",
+ component: "Box",
+ children: [
+ {
+ type: "instance",
+ component: "HtmlEmbed",
+ props: [
+ { name: "code", type: "expression", code: "collectionItem" },
+ ],
+ children: [],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+};
+
+const collectionPropsMeta: WsComponentPropsMeta = {
+ props: {
+ data: {
+ required: true,
+ control: "json",
+ type: "json",
+ },
+ },
+ initialProps: ["data"],
+};
+
+export const coreMetas = {
+ [collectionComponent]: collectionMeta,
+};
+
+export const corePropsMetas = {
+ [collectionComponent]: collectionPropsMeta,
+};
diff --git a/packages/react-sdk/src/embed-template.test.ts b/packages/react-sdk/src/embed-template.test.ts
index b03fd46b43..8a23352f59 100644
--- a/packages/react-sdk/src/embed-template.test.ts
+++ b/packages/react-sdk/src/embed-template.test.ts
@@ -484,6 +484,64 @@ test("generate data for embedding from action props", () => {
});
});
+test("generate data for embedding from parameter props", () => {
+ const data = generateDataFromEmbedTemplate(
+ [
+ {
+ type: "instance",
+ component: "Box",
+ variables: {
+ parameterName: { initialValue: "" },
+ },
+ props: [
+ {
+ type: "parameter",
+ name: "myParameter",
+ variableName: "parameterName",
+ },
+ ],
+ children: [],
+ },
+ ],
+ new Map(),
+ defaultBreakpointId
+ );
+ const instanceId = data.instances[0].id;
+ const variableId = data.dataSources[0].id;
+ expect(data).toEqual({
+ children: [{ type: "id", value: instanceId }],
+ instances: [
+ {
+ type: "instance",
+ id: instanceId,
+ component: "Box",
+ children: [],
+ },
+ ],
+ props: [
+ {
+ id: expectString,
+ instanceId,
+ name: "myParameter",
+ type: "parameter",
+ value: variableId,
+ },
+ ],
+ dataSources: [
+ {
+ type: "variable",
+ id: variableId,
+ scopeInstanceId: instanceId,
+ name: "parameterName",
+ value: { type: "string", value: "" },
+ },
+ ],
+ styleSourceSelections: [],
+ styleSources: [],
+ styles: [],
+ });
+});
+
test("generate styles from tokens", () => {
const presetTokens: WsComponentMeta["presetTokens"] = {
box: {
diff --git a/packages/react-sdk/src/embed-template.ts b/packages/react-sdk/src/embed-template.ts
index 58f55867f3..68356cc3f9 100644
--- a/packages/react-sdk/src/embed-template.ts
+++ b/packages/react-sdk/src/embed-template.ts
@@ -24,12 +24,7 @@ const EmbedTemplateText = z.object({
type EmbedTemplateText = z.infer<typeof EmbedTemplateText>;
const EmbedTemplateVariable = z.object({
- initialValue: z.union([
- z.string(),
- z.number(),
- z.boolean(),
- z.array(z.string()),
- ]),
+ initialValue: z.unknown(),
});
type EmbedTemplateVariable = z.infer<typeof EmbedTemplateVariable>;
@@ -55,11 +50,21 @@ export const EmbedTemplateProp = z.union([
name: z.string(),
value: z.array(z.string()),
}),
+ z.object({
+ type: z.literal("json"),
+ name: z.string(),
+ value: z.unknown(),
+ }),
z.object({
type: z.literal("expression"),
name: z.string(),
code: z.string(),
}),
+ z.object({
+ type: z.literal("parameter"),
+ name: z.string(),
+ variableName: z.string(),
+ }),
z.object({
type: z.literal("action"),
name: z.string(),
@@ -137,8 +142,7 @@ const getVariablValue = (
if (Array.isArray(value)) {
return { type: "string[]", value };
}
- value satisfies never;
- throw Error("Impossible case");
+ return { type: "json", value };
};
const createInstancesFromTemplate = (
@@ -225,6 +229,22 @@ const createInstancesFromTemplate = (
continue;
}
+ if (prop.type === "parameter") {
+ const dataSourceId = dataSourceByRef.get(prop.variableName)?.id;
+ if (dataSourceId === undefined) {
+ continue;
+ }
+ props.push({
+ id: propId,
+ instanceId,
+ name: prop.name,
+ type: "parameter",
+ // replace variable reference with variable id
+ value: dataSourceId,
+ });
+ continue;
+ }
+
props.push({ id: propId, instanceId, ...prop });
}
}
diff --git a/packages/react-sdk/src/tree/create-elements-tree.tsx b/packages/react-sdk/src/tree/create-elements-tree.tsx
index cab2f30034..8ad5a630d7 100644
--- a/packages/react-sdk/src/tree/create-elements-tree.tsx
+++ b/packages/react-sdk/src/tree/create-elements-tree.tsx
@@ -14,7 +14,6 @@ type InstanceSelector = Instance["id"][];
export type WebstudioComponentProps = {
instance: Instance;
instanceSelector: Instance["id"][];
- children: ReactNode;
components: Components;
};
@@ -43,18 +42,10 @@ export const createElementsTree = ({
}
const rootInstanceSelector = [rootInstanceId];
- const children = createInstanceChildrenElements({
- instances,
- instanceSelector: rootInstanceSelector,
- Component,
- children: rootInstance.children,
- components,
- });
const root = createInstanceElement({
Component,
instance: rootInstance,
instanceSelector: rootInstanceSelector,
- children,
components,
});
return (
@@ -82,7 +73,7 @@ const renderText = (text: string): Array<JSX.Element> => {
));
};
-const createInstanceChildrenElements = ({
+export const createInstanceChildrenElements = ({
instances,
instanceSelector,
children,
@@ -108,18 +99,10 @@ const createInstanceChildrenElements = ({
continue;
}
const childInstanceSelector = [child.value, ...instanceSelector];
- const children = createInstanceChildrenElements({
- instances,
- instanceSelector: childInstanceSelector,
- children: childInstance.children,
- Component,
- components,
- });
const element = createInstanceElement({
instance: childInstance,
instanceSelector: childInstanceSelector,
Component,
- children,
components,
});
elements.push(element);
@@ -135,7 +118,6 @@ const createInstanceElement = ({
Component,
instance,
instanceSelector,
- children,
components,
}: {
instance: Instance;
@@ -143,7 +125,6 @@ const createInstanceElement = ({
Component: ForwardRefExoticComponent<
WebstudioComponentProps & RefAttributes<HTMLElement>
>;
- children?: ReactNode;
components: Components;
}) => {
return (
@@ -152,8 +133,6 @@ const createInstanceElement = ({
instance={instance}
instanceSelector={instanceSelector}
components={components}
- >
- {children}
- </Component>
+ />
);
};
diff --git a/packages/sdk-components-react/src/code-text.ws.tsx b/packages/sdk-components-react/src/code-text.ws.tsx
index cfeee34a1d..87f21fd7ce 100644
--- a/packages/sdk-components-react/src/code-text.ws.tsx
+++ b/packages/sdk-components-react/src/code-text.ws.tsx
@@ -45,7 +45,7 @@ export const meta: WsComponentMeta = {
invalidAncestors: ["CodeText"],
states: defaultStates,
presetStyle,
- order: 8,
+ order: 9,
};
export const propsMeta: WsComponentPropsMeta = {
diff --git a/packages/sdk-components-react/src/html-embed.ws.ts b/packages/sdk-components-react/src/html-embed.ws.ts
index ca1342c550..dd69081a72 100644
--- a/packages/sdk-components-react/src/html-embed.ws.ts
+++ b/packages/sdk-components-react/src/html-embed.ws.ts
@@ -12,7 +12,7 @@ export const meta: WsComponentMeta = {
description: "Used to add HTML code to the page, such as an SVG or script.",
icon: EmbedIcon,
stylable: false,
- order: 7,
+ order: 8,
};
export const propsMeta: WsComponentPropsMeta = {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 676e5e44f6..fbfeb9282b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1574,6 +1574,9 @@ importers:
'@webstudio-is/fonts':
specifier: workspace:*
version: link:../fonts
+ '@webstudio-is/icons':
+ specifier: workspace:^
+ version: link:../icons
'@webstudio-is/image':
specifier: workspace:*
version: link:../image