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.

Support required props

Andrey Okonetchnikov2def4a61c93e
diff --git a/app/designer/features/props-panel/control.tsx b/app/designer/features/props-panel/control.tsx
index d0f11e4c40..3642597088 100644
--- a/app/designer/features/props-panel/control.tsx
+++ b/app/designer/features/props-panel/control.tsx
@@ -15,6 +15,7 @@ type BaseControlProps = {
value?: UserProp["value"];
defaultValue?: UserProp["value"];
onChange: (value: UserProp["value"]) => void;
+ required?: boolean;
};
type TextControlProps = BaseControlProps & {
type?: ComponentProps<typeof TextField>["type"];
diff --git a/app/designer/features/props-panel/props-panel.stories.tsx b/app/designer/features/props-panel/props-panel.stories.tsx
index 39ff9e08cc..e211ca8c0e 100644
--- a/app/designer/features/props-panel/props-panel.stories.tsx
+++ b/app/designer/features/props-panel/props-panel.stories.tsx
@@ -30,11 +30,11 @@ export const NoProps: ComponentStoryObj<typeof PropsPanel> = {
},
};
-export const DefaultProps: ComponentStoryObj<typeof PropsPanel> = {
+export const RequiredProps: ComponentStoryObj<typeof PropsPanel> = {
args: {
selectedInstanceData: {
id: "1",
- component: "Button",
+ component: "Link",
cssRules: [],
browserStyle: {},
props: {
diff --git a/app/designer/features/props-panel/props-panel.tsx b/app/designer/features/props-panel/props-panel.tsx
index 3d5a39ae57..58b7d7d48e 100644
--- a/app/designer/features/props-panel/props-panel.tsx
+++ b/app/designer/features/props-panel/props-panel.tsx
@@ -9,18 +9,11 @@ import { CollapsibleSection, ComponentInfo } from "~/designer/shared/inspector";
import type { SelectedInstanceData } from "~/shared/canvas-components";
import { Box, Button, Grid, TextField } from "~/shared/design-system";
import { PlusIcon, TrashIcon } from "~/shared/icons";
-import { usePropsLogic } from "./use-props-logic";
+import { handleChangePropType, usePropsLogic } from "./use-props-logic";
-type PropertyProps = {
- id: UserProp["id"];
- prop: UserProp["prop"];
- value: UserProp["value"];
+type PropertyProps = UserProp & {
component: Instance["component"];
- onChange: (
- id: UserProp["id"],
- field: keyof UserProp,
- value: UserProp["prop"] | UserProp["value"]
- ) => void;
+ onChange: handleChangePropType;
onDelete: (id: UserProp["id"]) => void;
};
@@ -28,6 +21,7 @@ const Property = ({
id,
prop,
value,
+ required,
component,
onChange,
onDelete,
@@ -40,8 +34,9 @@ const Property = ({
// TODO: We need to sync defaultValue with value if value is not set and publish this change
// const realValue = value || defaultValue;
return (
- <Grid gap="1" css={{ gridTemplateColumns: "auto auto 1fr auto" }}>
+ <Grid gap="1" css={{ gridTemplateColumns: "auto 1fr auto" }}>
<TextField
+ readOnly={required}
variant="ghost"
placeholder="Property"
name="prop"
@@ -50,9 +45,9 @@ const Property = ({
onChange(id, "prop", event.target.value);
}}
/>
- :
<Control
type={type}
+ required={required}
defaultValue={defaultValue}
options={options}
value={value}
@@ -60,6 +55,7 @@ const Property = ({
/>
<Button
ghost
+ disabled={required}
onClick={() => {
onDelete(id);
}}
@@ -104,12 +100,13 @@ export const PropsPanel = ({
isOpenDefault
>
<>
- {userProps.map(({ id, prop, value }) => (
+ {userProps.map(({ id, prop, value, required }) => (
<Property
key={id}
id={id}
prop={prop}
value={value}
+ required={required}
component={selectedInstanceData.component}
onChange={handleChangeProp}
onDelete={handleDeleteProp}
diff --git a/app/designer/features/props-panel/use-props-logic.test.ts b/app/designer/features/props-panel/use-props-logic.test.ts
index a64591fcf4..c8aafddc27 100644
--- a/app/designer/features/props-panel/use-props-logic.test.ts
+++ b/app/designer/features/props-panel/use-props-logic.test.ts
@@ -1,67 +1,70 @@
import { renderHook, act } from "@testing-library/react-hooks";
+import { components, UserProp } from "@webstudio-is/sdk";
import { SelectedInstanceData } from "~/shared/canvas-components";
import { usePropsLogic } from "./use-props-logic";
-const selectedInstanceData = {
- id: "2",
- component: "Button",
- cssRules: [],
- browserStyle: {},
- props: {
- id: "1",
- props: [
- {
- id: "disabled",
- prop: "disabled",
- value: true,
- },
- ],
- instanceId: "2",
- treeId: "1",
- },
-} as SelectedInstanceData;
+const getSelectedInstanceData = (
+ componentName: keyof typeof components,
+ props: UserProp[]
+): SelectedInstanceData => {
+ return {
+ id: "2",
+ component: componentName,
+ cssRules: [],
+ browserStyle: {},
+ props: {
+ id: "1",
+ props,
+ instanceId: "2",
+ treeId: "1",
+ },
+ };
+};
describe("usePropsLogic", () => {
test("should return initial props for a given instance", () => {
const { result } = renderHook(() =>
usePropsLogic({
- selectedInstanceData,
+ selectedInstanceData: getSelectedInstanceData("Link", []),
publish: jest.fn(),
})
);
- expect(result.current.userProps).toMatchInlineSnapshot(`
- Array [
- Object {
- "id": "disabled",
- "prop": "disabled",
- "value": true,
- },
- ]
- `);
+ expect(result.current.userProps.length).toEqual(1);
+ expect(result.current.userProps[0]).toMatchObject({
+ prop: "href",
+ required: true,
+ value: "",
+ });
});
test("should add an empty prop", () => {
const { result } = renderHook(() =>
usePropsLogic({
- selectedInstanceData,
+ selectedInstanceData: getSelectedInstanceData("Box", []),
publish: jest.fn(),
})
);
- expect(result.current.userProps.length).toEqual(1);
+ expect(result.current.userProps.length).toEqual(0);
act(() => {
result.current.addEmptyProp();
});
- expect(result.current.userProps.length).toEqual(2);
- expect(result.current.userProps[1]).toMatchObject({ prop: "", value: "" });
+ expect(result.current.userProps.length).toEqual(1);
+ expect(result.current.userProps[0]).toMatchObject({ prop: "", value: "" });
});
test("should remove a prop", () => {
const { result } = renderHook(() =>
usePropsLogic({
- selectedInstanceData,
+ selectedInstanceData: getSelectedInstanceData("Button", [
+ {
+ id: "disabled",
+ prop: "disabled",
+ value: "true",
+ },
+ ]),
publish: jest.fn(),
})
);
@@ -74,10 +77,16 @@ describe("usePropsLogic", () => {
expect(result.current.userProps).toMatchInlineSnapshot(`Array []`);
});
- test("should add update a prop", () => {
+ test("should update a prop", () => {
const { result } = renderHook(() =>
usePropsLogic({
- selectedInstanceData,
+ selectedInstanceData: getSelectedInstanceData("Button", [
+ {
+ id: "disabled",
+ prop: "disabled",
+ value: "true",
+ },
+ ]),
publish: jest.fn(),
})
);
@@ -100,4 +109,104 @@ describe("usePropsLogic", () => {
]
`);
});
+
+ test("should not remove a required prop", () => {
+ const { result } = renderHook(() =>
+ usePropsLogic({
+ selectedInstanceData: getSelectedInstanceData("Button", [
+ {
+ id: "disabled",
+ prop: "disabled",
+ value: "true",
+ required: true,
+ },
+ ]),
+ publish: jest.fn(),
+ })
+ );
+
+ expect(result.current.userProps.length).toEqual(1);
+
+ act(() => {
+ result.current.handleDeleteProp("disabled");
+ });
+
+ expect(result.current.userProps.length).toEqual(1);
+ expect(result.current.userProps).toMatchInlineSnapshot(`
+ Array [
+ Object {
+ "id": "disabled",
+ "prop": "disabled",
+ "required": true,
+ "value": "true",
+ },
+ ]
+ `);
+ });
+
+ test("should not update a required prop name", () => {
+ const { result } = renderHook(() =>
+ usePropsLogic({
+ selectedInstanceData: getSelectedInstanceData("Button", [
+ {
+ id: "test",
+ prop: "test",
+ value: "test",
+ required: true,
+ },
+ ]),
+ publish: jest.fn(),
+ })
+ );
+
+ act(() => {
+ result.current.handleChangeProp("test", "prop", "test-example");
+ });
+
+ // act(() => {
+ // result.current.handleChangeProp("test", "value", false);
+ // });
+
+ expect(result.current.userProps).toMatchInlineSnapshot(`
+ Array [
+ Object {
+ "id": "test",
+ "prop": "test",
+ "required": true,
+ "value": "test",
+ },
+ ]
+ `);
+ });
+
+ test("should update a required prop value", () => {
+ const { result } = renderHook(() =>
+ usePropsLogic({
+ selectedInstanceData: getSelectedInstanceData("Button", [
+ {
+ id: "test",
+ prop: "test",
+ value: true,
+ required: true,
+ },
+ ]),
+ publish: jest.fn(),
+ })
+ );
+
+ act(() => {
+ result.current.handleChangeProp("test", "value", false);
+ });
+
+ expect(result.current.userProps).toMatchInlineSnapshot(`
+ Array [
+ Object {
+ "id": "test",
+ "prop": "test",
+ "required": true,
+ "value": false,
+ },
+ ]
+ `);
+ });
});
diff --git a/app/designer/features/props-panel/use-props-logic.ts b/app/designer/features/props-panel/use-props-logic.ts
index 0f1aff0fa4..555291a8e8 100644
--- a/app/designer/features/props-panel/use-props-logic.ts
+++ b/app/designer/features/props-panel/use-props-logic.ts
@@ -4,19 +4,34 @@ import type {
UserProp,
UserPropsUpdates,
} from "@webstudio-is/sdk";
+import { componentsMeta } from "@webstudio-is/sdk";
import ObjectId from "bson-objectid";
import produce from "immer";
import debounce from "lodash.debounce";
import { useRef, useState } from "react";
import type { SelectedInstanceData } from "~/shared/canvas-components";
-const getInitialProp = () => ({
- id: ObjectId().toString(),
- prop: "",
- value: "",
-});
+export type handleChangePropType = (
+ id: UserProp["id"],
+ field: "prop" | "value",
+ value: UserProp["prop"] | UserProp["value"]
+) => void;
-const initialUserProps = [getInitialProp()];
+const getRequiredProps = (
+ selectedInstanceData: SelectedInstanceData
+): UserProp[] => {
+ const { component } = selectedInstanceData;
+ const meta = componentsMeta[component];
+ const argTypes = meta?.argTypes || {};
+ return Object.entries(argTypes)
+ .filter(([_, value]) => value.required)
+ .map(([prop, _]) => ({
+ id: ObjectId().toString(),
+ prop,
+ value: "",
+ required: true,
+ }));
+};
type UsePropsLogic = {
publish: Publish;
@@ -30,9 +45,13 @@ export const usePropsLogic = ({
const props =
selectedInstanceData.props === undefined ||
selectedInstanceData.props.props.length === 0
- ? initialUserProps
+ ? []
: selectedInstanceData.props.props;
- const [userProps, setUserProps] = useState<Array<UserProp>>(props);
+
+ const [userProps, setUserProps] = useState<Array<UserProp>>([
+ ...getRequiredProps(selectedInstanceData),
+ ...props,
+ ]);
const propsToPublishRef = useRef<{
[id: UserProp["id"]]: true;
}>({});
@@ -63,16 +82,21 @@ export const usePropsLogic = ({
});
};
- const handleChangeProp = (
- id: UserProp["id"],
- field: keyof UserProp,
- value: UserProp["prop"] | UserProp["value"]
- ) => {
+ const handleChangeProp: handleChangePropType = (id, field, value) => {
const index = userProps.findIndex((item) => item.id === id);
const nextUserProps = produce((draft: Array<UserProp>) => {
- if (field === "prop" && typeof value === "string") {
- draft[index].prop = value;
- } else draft[index].value = value;
+ const isPropRequired = draft[index].required;
+ switch (field) {
+ case "prop":
+ if (!isPropRequired) {
+ // TODO: Use discriminant type to make this more clear or separate into 2 functions
+ draft[index].prop = value as UserProp["prop"];
+ }
+ break;
+ case "value":
+ draft[index].value = value;
+ break;
+ }
})(userProps);
setUserProps(nextUserProps);
@@ -86,14 +110,26 @@ export const usePropsLogic = ({
const handleDeleteProp = (id: UserProp["id"]) => {
const nextUserProps = [...userProps];
- const index = nextUserProps.findIndex((item) => item.id === id);
+ const prop = userProps.find((prop) => prop.id === id);
+
+ // Required prop should never be deleted
+ if (prop === undefined || prop.required) return;
+
+ const index = nextUserProps.indexOf(prop);
nextUserProps.splice(index, 1);
setUserProps(nextUserProps);
deleteProp(id);
};
const addEmptyProp = () => {
- setUserProps([...userProps, getInitialProp()]);
+ setUserProps([
+ ...userProps,
+ {
+ id: ObjectId().toString(),
+ prop: "",
+ value: "",
+ },
+ ]);
};
return {