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.

Use props state instead of local one (#786)

Bogdan Chadkinb40c967ee262
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 d5cb6616aa..82ea7f3ac6 100644
--- a/apps/designer/app/designer/features/props-panel/props-panel.tsx
+++ b/apps/designer/app/designer/features/props-panel/props-panel.tsx
@@ -127,7 +127,7 @@ type PropertyProps = {
component: Instance["component"];
onChangePropName: (name: string) => void;
onChangePropValue: (value: UserPropValue) => void;
- onDelete: (id: UserProp["id"]) => void;
+ onDelete: () => void;
setCssProperty: SetProperty;
required: boolean;
existingProps: string[];
@@ -210,13 +210,7 @@ const Property = ({
{required ? (
<Box />
) : (
- <Button
- variant="ghost"
- onClick={() => {
- onDelete(userProp.id);
- }}
- prefix={<TrashIcon />}
- />
+ <Button variant="ghost" onClick={onDelete} prefix={<TrashIcon />} />
)}
</>
);
@@ -231,8 +225,9 @@ export const PropsPanel = ({
selectedInstanceData,
publish,
}: PropsPanelProps) => {
+ const instanceId = selectedInstanceData.id;
const allUserProps = useAllUserProps();
- const props = allUserProps[selectedInstanceData.id] ?? [];
+ const props = allUserProps[instanceId] ?? [];
const {
userProps,
@@ -245,27 +240,24 @@ export const PropsPanel = ({
props,
selectedInstanceData,
- updateProps: (updates) => {
+ updateProps: (update) => {
store.createTransaction([allUserPropsContainer], (allUserProps) => {
- const instanceId = selectedInstanceData.id;
let props = allUserProps[instanceId];
if (props === undefined) {
props = [];
allUserProps[instanceId] = props;
}
- for (const update of updates) {
- replaceByOrAppendMutable(
- props,
- update,
- (item) => item.id === update.id
- );
- }
+ replaceByOrAppendMutable(
+ props,
+ update,
+ (item) => item.id === update.id
+ );
});
},
deleteProp: (id) => {
store.createTransaction([allUserPropsContainer], (allUserProps) => {
- const props = allUserProps[selectedInstanceData.id];
+ const props = allUserProps[instanceId];
if (props) {
removeByMutable(props, (prop) => prop.id === id);
}
@@ -313,14 +305,12 @@ export const PropsPanel = ({
key={userProp.id}
userProp={userProp}
component={selectedInstanceData.component}
- onChangePropName={(name) =>
- handleChangePropName(userProp.id, name)
- }
+ onChangePropName={(name) => handleChangePropName(userProp, name)}
onChangePropValue={(value) =>
- handleChangePropValue(userProp.id, value)
+ handleChangePropValue(userProp, value)
}
setCssProperty={setCssProperty}
- onDelete={handleDeleteProp}
+ onDelete={() => handleDeleteProp(userProp)}
required={isRequired(userProp)}
existingProps={existingProps}
/>
diff --git a/apps/designer/app/designer/features/props-panel/use-props-logic.test.ts b/apps/designer/app/designer/features/props-panel/use-props-logic.test.ts
index e393393f28..9c96f37c97 100644
--- a/apps/designer/app/designer/features/props-panel/use-props-logic.test.ts
+++ b/apps/designer/app/designer/features/props-panel/use-props-logic.test.ts
@@ -118,358 +118,6 @@ describe("usePropsLogic", () => {
expect(result.current.userProps[1]).toMatchObject({ prop: "", value: "" });
});
- test("should remove a prop", () => {
- const { result } = renderHook(() =>
- usePropsLogic({
- props: [
- {
- id: "1",
- prop: "tag",
- type: "string",
- value: "div",
- required: true,
- },
- {
- id: "disabled",
- prop: "disabled",
- type: "boolean",
- value: true,
- },
- ],
- selectedInstanceData: getSelectedInstanceData("Box"),
- updateProps: jest.fn(),
- deleteProp: jest.fn(),
- })
- );
-
- act(() => {
- result.current.handleDeleteProp("disabled");
- });
-
- expect(result.current.userProps.length).toEqual(1);
- expect(result.current.userProps).toMatchInlineSnapshot(`
- [
- {
- "id": "1",
- "prop": "tag",
- "required": true,
- "type": "string",
- "value": "div",
- },
- ]
- `);
- });
-
- test("should update a prop", () => {
- const { result } = renderHook(() =>
- usePropsLogic({
- props: [
- {
- id: "1",
- prop: "tag",
- type: "string",
- value: "div",
- required: true,
- },
- {
- id: "disabled",
- prop: "disabled",
- type: "boolean",
- value: true,
- },
- ],
- selectedInstanceData: getSelectedInstanceData("Box"),
- updateProps: jest.fn(),
- deleteProp: jest.fn(),
- })
- );
-
- act(() => {
- result.current.handleChangePropName("disabled", "disabled2");
- });
-
- act(() => {
- result.current.handleChangePropValue("disabled", {
- type: "boolean",
- value: false,
- });
- });
-
- expect(result.current.userProps).toMatchInlineSnapshot(`
- [
- {
- "id": "1",
- "prop": "tag",
- "required": true,
- "type": "string",
- "value": "div",
- },
- {
- "id": "disabled",
- "prop": "disabled2",
- "type": "boolean",
- "value": false,
- },
- ]
- `);
- });
-
- test("should not remove a required prop", () => {
- const { result } = renderHook(() =>
- usePropsLogic({
- props: [
- {
- id: "1",
- prop: "tag",
- type: "string",
- value: "div",
- required: true,
- },
- {
- id: "disabled",
- prop: "disabled",
- type: "boolean",
- value: true,
- required: true,
- },
- ],
- selectedInstanceData: getSelectedInstanceData("Box"),
- updateProps: jest.fn(),
- deleteProp: jest.fn(),
- })
- );
-
- expect(result.current.userProps.length).toEqual(2);
-
- act(() => {
- result.current.handleDeleteProp("disabled");
- });
-
- expect(result.current.userProps.length).toEqual(2);
- expect(result.current.userProps).toMatchInlineSnapshot(`
- [
- {
- "id": "1",
- "prop": "tag",
- "required": true,
- "type": "string",
- "value": "div",
- },
- {
- "id": "disabled",
- "prop": "disabled",
- "required": true,
- "type": "boolean",
- "value": true,
- },
- ]
- `);
- });
-
- test("should not update a required prop name", () => {
- const { result } = renderHook(() =>
- usePropsLogic({
- props: [
- {
- id: "1",
- prop: "tag",
- type: "string",
- value: "div",
- required: true,
- },
- {
- id: "2",
- prop: "test",
- type: "string",
- value: "test",
- required: true,
- },
- ],
- selectedInstanceData: getSelectedInstanceData("Box"),
- updateProps: jest.fn(),
- deleteProp: jest.fn(),
- })
- );
-
- act(() => {
- result.current.handleChangePropName("2", "test-example");
- });
-
- expect(result.current.userProps).toMatchInlineSnapshot(`
- [
- {
- "id": "1",
- "prop": "tag",
- "required": true,
- "type": "string",
- "value": "div",
- },
- {
- "id": "2",
- "prop": "test",
- "required": true,
- "type": "string",
- "value": "test",
- },
- ]
- `);
- });
-
- test("should update a required prop value", () => {
- const { result } = renderHook(() =>
- usePropsLogic({
- props: [
- {
- id: "1",
- prop: "tag",
- type: "string",
- value: "div",
- required: true,
- },
- {
- id: "2",
- prop: "test",
- type: "boolean",
- value: true,
- required: true,
- },
- ],
- selectedInstanceData: getSelectedInstanceData("Box"),
- updateProps: jest.fn(),
- deleteProp: jest.fn(),
- })
- );
-
- act(() => {
- result.current.handleChangePropValue("2", {
- type: "boolean",
- value: false,
- });
- });
-
- expect(result.current.userProps).toMatchInlineSnapshot(`
- [
- {
- "id": "1",
- "prop": "tag",
- "required": true,
- "type": "string",
- "value": "div",
- },
- {
- "id": "2",
- "prop": "test",
- "required": true,
- "type": "boolean",
- "value": false,
- },
- ]
- `);
- });
-
- test("should update value and asset", () => {
- const { result } = renderHook(() =>
- usePropsLogic({
- props: [
- {
- id: "1",
- prop: "tag",
- type: "string",
- value: "div",
- required: true,
- },
- ],
- selectedInstanceData: getSelectedInstanceData("Box"),
- updateProps: jest.fn(),
- deleteProp: jest.fn(),
- })
- );
-
- act(() => {
- result.current.handleChangePropValue("1", {
- type: "string",
- value: "img",
- });
- });
-
- expect(result.current.userProps).toMatchInlineSnapshot(`
- [
- {
- "id": "1",
- "prop": "tag",
- "required": true,
- "type": "string",
- "value": "img",
- },
- ]
- `);
-
- act(() => {
- result.current.handleChangePropValue("1", {
- type: "asset",
- value: {
- type: "image",
- id: "string",
- projectId: "string",
- format: "string",
- size: 1111,
- name: "string",
- description: "string",
- location: "REMOTE",
- createdAt: new Date("1995-12-17T03:24:00Z").toISOString(),
- meta: { width: 101, height: 202 },
- path: "string",
- },
- });
- });
-
- expect(result.current.userProps).toMatchInlineSnapshot(`
- [
- {
- "id": "1",
- "prop": "tag",
- "required": true,
- "type": "asset",
- "value": {
- "createdAt": "1995-12-17T03:24:00.000Z",
- "description": "string",
- "format": "string",
- "id": "string",
- "location": "REMOTE",
- "meta": {
- "height": 202,
- "width": 101,
- },
- "name": "string",
- "path": "string",
- "projectId": "string",
- "size": 1111,
- "type": "image",
- },
- },
- ]
- `);
-
- act(() => {
- result.current.handleChangePropValue("1", {
- type: "string",
- value: "img-3",
- });
- });
-
- expect(result.current.userProps).toMatchInlineSnapshot(`
- [
- {
- "id": "1",
- "prop": "tag",
- "required": true,
- "type": "string",
- "value": "img-3",
- },
- ]
- `);
- });
-
test("should respect initialProps ordering", () => {
const { result } = renderHook(() =>
usePropsLogic({
diff --git a/apps/designer/app/designer/features/props-panel/use-props-logic.ts b/apps/designer/app/designer/features/props-panel/use-props-logic.ts
index fb8d761b0f..dddfa34cb4 100644
--- a/apps/designer/app/designer/features/props-panel/use-props-logic.ts
+++ b/apps/designer/app/designer/features/props-panel/use-props-logic.ts
@@ -1,15 +1,16 @@
-import type { UserProp, MetaProps } from "@webstudio-is/react-sdk";
+import { useMemo, useState } from "react";
+import ObjectId from "bson-objectid";
+import warnOnce from "warn-once";
+import type {
+ UserProp,
+ MetaProps,
+ ComponentName,
+} from "@webstudio-is/react-sdk";
import {
getComponentMeta,
getComponentMetaProps,
} from "@webstudio-is/react-sdk";
-import ObjectId from "bson-objectid";
-import produce from "immer";
-// @todo: importing normally doesn't work in Jest for some reason
-import uniqBy from "lodash/uniqBy"; // eslint-disable-line
-import { useState } from "react";
import type { SelectedInstanceData } from "@webstudio-is/project";
-import warnOnce from "warn-once";
export type UserPropValue = UserProp extends infer T
? T extends { value: unknown; type: unknown }
@@ -17,11 +18,7 @@ export type UserPropValue = UserProp extends infer T
: never
: never;
-type HandleChangePropName = (id: UserProp["id"], name: string) => void;
-
-type HandleChangePropValue = (id: UserProp["id"], value: UserPropValue) => void;
-
-export const getValueFromPropMeta = (propValue: MetaProps[string]) => {
+export const getValueFromPropMeta = (propValue?: MetaProps[string]) => {
let typedValue: UserPropValue = {
type: "string",
value: `${propValue?.defaultValue ?? ""}`,
@@ -44,108 +41,56 @@ export const getValueFromPropMeta = (propValue: MetaProps[string]) => {
return typedValue;
};
-const getRequiredProps = (
- selectedInstanceData: SelectedInstanceData,
- props: UserProp[]
-): UserProp[] => {
- const { component } = selectedInstanceData;
- const meta = getComponentMetaProps(component);
-
- return Object.entries(meta)
- .filter(([_, value]) => value?.required)
- .map(([requiredProp, requiredPropValue]) => {
- warnOnce(
- requiredPropValue?.defaultValue == null,
- `Default value for required "${requiredProp}" is required`
- );
- const userProp = props.find((prop) => prop.prop === requiredProp);
-
- if (userProp !== undefined) {
- return userProp;
- }
-
- const typedValue = getValueFromPropMeta(requiredPropValue);
-
- return {
- id: ObjectId().toString(),
- prop: requiredProp,
- ...typedValue,
- required: true,
- };
- });
-};
-
-// @todo: This returns same props for all instances.
-// See the failing test in use-props-logic.test.ts
-const getPropsWithDefaultValue = (
- selectedInstanceData: SelectedInstanceData,
- props: UserProp[]
-): UserProp[] => {
- const { component } = selectedInstanceData;
- const meta = getComponentMetaProps(component);
-
- return Object.entries(meta)
- .filter(([_, value]) => value?.defaultValue != null)
- .map(([defaultProp, defaultPropValue]) => {
- const userProp = props.find((prop) => prop.prop === defaultProp);
-
- if (userProp !== undefined) {
- return userProp;
- }
-
- const typedValue = getValueFromPropMeta(defaultPropValue);
-
- return {
- id: ObjectId().toString(),
- prop: defaultProp,
- ...typedValue,
- };
- });
-};
-
-const getInitialProps = (
- selectedInstanceData: SelectedInstanceData,
- props: UserProp[]
-): UserProp[] => {
- const { component } = selectedInstanceData;
+const getRequiredPropsList = (component: ComponentName) => {
const meta = getComponentMeta(component);
const metaProps = getComponentMetaProps(component);
const initialProps = meta.initialProps ?? [];
+ const requiredProps = [];
+ const propsWithDefaultValue = [];
- const userProps: UserProp[] = [];
-
- // Preserve ordering from `initialProps` getting values from DB props or default values
- for (const initialProp of initialProps) {
- const userProp = props.find((prop) => prop.prop === initialProp);
- if (userProp !== undefined) {
- userProps.push(userProp);
- continue;
+ for (const [prop, value] of Object.entries(metaProps)) {
+ if (value?.required) {
+ warnOnce(
+ value.defaultValue == null,
+ `Default value for required "${prop}" is required`
+ );
+ requiredProps.push(prop);
}
-
- const metaPropValue = metaProps[initialProp];
- if (metaPropValue !== undefined) {
- const typedValue = getValueFromPropMeta(metaPropValue);
-
- userProps.push({
- id: ObjectId().toString(),
- prop: initialProp,
- ...typedValue,
- });
-
- continue;
+ if (value?.defaultValue != null) {
+ propsWithDefaultValue.push(prop);
}
}
- return userProps;
+
+ // deduplicate required props
+ return Array.from(
+ new Set<string>([
+ ...initialProps,
+ ...requiredProps,
+ ...propsWithDefaultValue,
+ ])
+ );
};
type UsePropsLogic = {
props: UserProp[];
selectedInstanceData: SelectedInstanceData;
- updateProps: (updates: Array<UserProp>) => void;
+ updateProps: (update: UserProp) => void;
deleteProp: (id: UserProp["id"]) => void;
};
+const getPropsItemFromMetaProps = (metaProps: MetaProps, name: string) => {
+ const metaPropValue = metaProps[name];
+ if (metaPropValue === undefined) {
+ return undefined;
+ }
+ return {
+ id: ObjectId().toString(),
+ prop: name,
+ ...getValueFromPropMeta(metaPropValue),
+ };
+};
+
/**
* usePropsLogic expects that key={selectedInstanceData.id} is used on the ancestor component
*/
@@ -155,89 +100,77 @@ export const usePropsLogic = ({
updateProps,
deleteProp,
}: UsePropsLogic) => {
- const [requiredProps] = useState<Array<UserProp>>(() =>
- uniqBy(
- [
- ...getInitialProps(selectedInstanceData, props),
- ...getRequiredProps(selectedInstanceData, props),
- ...getPropsWithDefaultValue(selectedInstanceData, props),
- ],
- "prop"
- )
+ const { component } = selectedInstanceData;
+
+ const metaProps = useMemo(
+ () => getComponentMetaProps(component),
+ [component]
);
- // Prefer ordering from `initialProps`
- const [userProps, setUserProps] = useState<Array<UserProp>>(() =>
- uniqBy([...requiredProps, ...props], "prop")
+ const requiredPropsList = useMemo(
+ () => getRequiredPropsList(component),
+ [component]
);
+ const requiredPropsByName = new Map<string, UserProp>();
+ for (const name of requiredPropsList) {
+ const propsItem = getPropsItemFromMetaProps(metaProps, name);
+ if (propsItem) {
+ requiredPropsByName.set(name, propsItem);
+ }
+ }
- const handleChangePropName: HandleChangePropName = (id, name) => {
- const nextUserProps = produce((draft: Array<UserProp>) => {
- const index = draft.findIndex((item) => item.id === id);
-
- const isPropRequired = draft[index].required;
-
- if (isPropRequired !== true) {
- const { component } = selectedInstanceData;
- const meta = getComponentMetaProps(component);
-
- let typedValue: UserPropValue = { type: "string", value: "" };
- if (name in meta) {
- typedValue = getValueFromPropMeta(meta[name]);
- }
-
- // @todo we need to not allow changing non required on required prop too
- draft[index] = {
- id: draft[index].id,
- prop: name,
- ...typedValue,
- };
- }
- })(userProps);
-
- // Optimistically update the state (what if publish fails?)
- setUserProps(nextUserProps);
+ const [addedProps, setAddedProps] = useState<UserProp[]>([]);
+ const addedPropsById = new Map<string, UserProp>();
+ for (const propsItem of addedProps) {
+ addedPropsById.set(propsItem.id, propsItem);
+ }
- const updatedProps = nextUserProps.filter((item) => item.id === id);
+ const propsById = new Map<string, UserProp>();
+ for (const propsItem of props) {
+ if (requiredPropsByName.has(propsItem.prop)) {
+ requiredPropsByName.set(propsItem.prop, propsItem);
+ continue;
+ }
+ if (addedPropsById.has(propsItem.id)) {
+ addedPropsById.set(propsItem.id, propsItem);
+ continue;
+ }
+ propsById.set(propsItem.id, propsItem);
+ }
- updateProps(updatedProps);
+ // maintain added props order until panel is closed
+ // to prevent inputs jumping while user typing
+ const userProps = [
+ ...requiredPropsByName.values(),
+ ...propsById.values(),
+ ...addedPropsById.values(),
+ ];
+
+ const handleChangePropName = (propsItem: UserProp, name: string) => {
+ // prevent changing name of required props
+ if (isRequired(propsItem)) {
+ return;
+ }
+ const typedValue = getValueFromPropMeta(metaProps[name]);
+ updateProps({ id: propsItem.id, prop: name, ...typedValue });
};
- const handleChangePropValue: HandleChangePropValue = (id, value) => {
- const nextUserProps = produce((draft: Array<UserProp>) => {
- const index = draft.findIndex((item) => item.id === id);
-
- draft[index] = {
- ...draft[index],
- ...value,
- };
- })(userProps);
-
- // Optimistically update the state (what if publish fails?)
- setUserProps(nextUserProps);
-
- const updatedProps = nextUserProps.filter((item) => item.id === id);
-
- updateProps(updatedProps);
+ const handleChangePropValue = (propsItem: UserProp, value: UserPropValue) => {
+ updateProps({ ...propsItem, ...value });
};
- const handleDeleteProp = (id: UserProp["id"]) => {
- const nextUserProps = [...userProps];
- const prop = userProps.find((prop) => prop.id === id);
-
- // Required prop should never be deleted
- if (prop === undefined || prop.required) {
+ const handleDeleteProp = (propsItem: UserProp) => {
+ // required prop should never be deleted
+ if (isRequired(propsItem)) {
return;
}
-
- const index = nextUserProps.indexOf(prop);
- nextUserProps.splice(index, 1);
- setUserProps(nextUserProps);
+ const id = propsItem.id;
deleteProp(id);
+ setAddedProps((prev) => prev.filter((propsItem) => propsItem.id !== id));
};
const addEmptyProp = () => {
- setUserProps([
- ...userProps,
+ setAddedProps((prev) => [
+ ...prev,
{
id: ObjectId().toString(),
prop: "",
@@ -247,22 +180,16 @@ export const usePropsLogic = ({
]);
};
- const isRequired = (prop: UserProp) => {
- if (prop.required) {
- return true;
- }
-
- return requiredProps.some(
- (requiredProp) => requiredProp.prop === prop.prop
- );
+ const isRequired = (propsItem: UserProp) => {
+ return propsItem.required || requiredPropsList.includes(propsItem.prop);
};
return {
- addEmptyProp,
userProps,
handleChangePropName,
handleChangePropValue,
handleDeleteProp,
+ addEmptyProp,
isRequired,
};
};