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.

Fix that images with asset had value inside db (#549)

Ivan Starkovb6c6f57f2cc1
diff --git a/apps/designer/app/designer/features/props-panel/control.stories.tsx b/apps/designer/app/designer/features/props-panel/control.stories.tsx
index a805d3ef7a..847eed1c35 100644
--- a/apps/designer/app/designer/features/props-panel/control.stories.tsx
+++ b/apps/designer/app/designer/features/props-panel/control.stories.tsx
@@ -11,6 +11,7 @@ export const Primitive: ComponentStoryObj<typeof Control> = {
userProp: {
prop: "src",
id: "ddf20afe-65a8-478e-a52d-1be2d2f70830",
+ type: "string",
value: "",
},
},
@@ -22,6 +23,7 @@ export const Options: ComponentStoryObj<typeof Control> = {
userProp: {
prop: "loading",
id: "ddf20afe-65a8-478e-a52d-1be2d2f70830",
+ type: "string",
value: "",
},
},
diff --git a/apps/designer/app/designer/features/props-panel/control.tsx b/apps/designer/app/designer/features/props-panel/control.tsx
index 7fe07995a4..4bd0497bb1 100644
--- a/apps/designer/app/designer/features/props-panel/control.tsx
+++ b/apps/designer/app/designer/features/props-panel/control.tsx
@@ -15,9 +15,9 @@ import {
} from "@webstudio-is/design-system";
import { ValuePickerPopover } from "../style-panel/shared/value-picker-popover";
import { ImageManager } from "~/designer/shared/image-manager";
-
import { Checkbox } from "@webstudio-is/design-system";
import { Asset } from "@webstudio-is/asset-uploader";
+import type { UserPropValue } from "./use-props-logic";
const textControlTypes = [
"text",
@@ -173,7 +173,7 @@ const assertUnreachable = (_arg: never, errorMessage: string) => {
type ControlProps = {
component: Instance["component"];
userProp: UserProp;
- onChangePropValue: (value: string | boolean, asset?: Asset) => void;
+ onChangePropValue: (value: UserPropValue) => void;
};
// eslint-disable-next-line func-style
@@ -210,21 +210,36 @@ export function Control({
}
if (component === "Image" && userProp.prop === "src") {
- const asset = userProp.asset ?? null;
+ const asset = userProp.type === "asset" ? userProp.value : null;
return (
<ImageControl
asset={asset}
- onChange={(asset) => onChangePropValue(asset.path, asset)}
+ onChange={(value) => onChangePropValue({ type: "asset", value })}
/>
);
}
+ if (userProp.type === "asset") {
+ throw new Error(
+ `userProp with id "${userProp.value.id}" has asset but no control exists to process it`
+ );
+ }
+
if (includes(textControlTypes, type)) {
const value = `${userProp.value}`;
return (
- <TextControl value={value} onChange={onChangePropValue} type={type} />
+ <TextControl
+ value={value}
+ onChange={(value) =>
+ onChangePropValue({
+ type: "string",
+ value,
+ })
+ }
+ type={type}
+ />
);
}
@@ -234,7 +249,12 @@ export function Control({
return (
<BooleanControl
value={value}
- onChange={onChangePropValue}
+ onChange={(value) =>
+ onChangePropValue({
+ type: "boolean",
+ value,
+ })
+ }
defaultValue={Boolean(defaultValue)}
/>
);
@@ -263,7 +283,12 @@ export function Control({
return (
<RadioControl
value={value}
- onChange={onChangePropValue}
+ onChange={(value) =>
+ onChangePropValue({
+ type: "string",
+ value,
+ })
+ }
options={options ?? DEFAULT_OPTIONS}
type={type}
/>
@@ -274,7 +299,12 @@ export function Control({
return (
<CheckboxControl
value={value}
- onChange={onChangePropValue}
+ onChange={(value) =>
+ onChangePropValue({
+ type: "string",
+ value,
+ })
+ }
options={options ?? DEFAULT_OPTIONS}
type={type}
/>
@@ -285,7 +315,12 @@ export function Control({
return (
<SelectControl
value={value}
- onChange={onChangePropValue}
+ onChange={(value) =>
+ onChangePropValue({
+ type: "string",
+ value,
+ })
+ }
options={options ?? DEFAULT_OPTIONS}
type={type}
/>
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 8e76e5fc89..30f73e6cc9 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
@@ -20,6 +20,7 @@ export const NoProps: ComponentStoryObj<typeof PropsPanel> = {
{
id: "disabled",
prop: "disabled",
+ type: "boolean",
value: true,
},
],
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 a5cf5ec65e..036b6d66a3 100644
--- a/apps/designer/app/designer/features/props-panel/props-panel.tsx
+++ b/apps/designer/app/designer/features/props-panel/props-panel.tsx
@@ -28,8 +28,7 @@ import {
ExclamationTriangleIcon,
ChevronDownIcon,
} from "@webstudio-is/icons";
-import { usePropsLogic } from "./use-props-logic";
-import type { Asset } from "@webstudio-is/asset-uploader";
+import { usePropsLogic, type UserPropValue } from "./use-props-logic";
type ComboboxProps = {
isReadonly: boolean;
@@ -109,11 +108,8 @@ const Combobox = ({
type PropertyProps = {
userProp: UserProp;
component: Instance["component"];
- onChangePropName: (
- name: string,
- defaultValue: string | boolean | number
- ) => void;
- onChangePropValue: (value: string | boolean | number, asset?: Asset) => void;
+ onChangePropName: (name: string) => void;
+ onChangePropValue: (value: UserPropValue) => void;
onDelete: (id: UserProp["id"]) => void;
};
@@ -142,32 +138,10 @@ const Property = ({
value={userProp.prop}
onItemSelect={(name) => {
if (name != null) {
- const argType = meta[name as keyof typeof meta];
-
- const defaultValue =
- argType?.defaultValue ??
- (argType?.type === "boolean"
- ? false
- : argType?.type === "number"
- ? 0
- : "");
-
- onChangePropName(name, defaultValue);
+ onChangePropName(name);
}
}}
- onSubmit={(name) => {
- const argType = meta[name as keyof typeof meta];
-
- const defaultValue =
- argType?.defaultValue ??
- (argType?.type === "boolean"
- ? false
- : argType?.type === "number"
- ? 0
- : "");
-
- onChangePropName(name, defaultValue);
- }}
+ onSubmit={onChangePropName}
isInvalid={isInvalid}
isReadonly={userProp.required ?? false}
/>
@@ -249,11 +223,11 @@ export const PropsPanel = ({
key={userProp.id}
userProp={userProp}
component={selectedInstanceData.component}
- onChangePropName={(name, defaultValue) =>
- handleChangePropName(userProp.id, name, defaultValue)
+ onChangePropName={(name) =>
+ handleChangePropName(userProp.id, name)
}
- onChangePropValue={(value, asset) =>
- handleChangePropValue(userProp.id, value, asset)
+ onChangePropValue={(value) =>
+ handleChangePropValue(userProp.id, value)
}
onDelete={handleDeleteProp}
/>
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 4a06a753ab..7b41c59c6f 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
@@ -82,6 +82,7 @@ describe("usePropsLogic", () => {
{
id: "default",
prop: "type",
+ type: "string",
value: "submit",
},
]),
@@ -120,13 +121,15 @@ describe("usePropsLogic", () => {
{
id: "1",
prop: "tag",
+ type: "string",
value: "div",
required: true,
},
{
id: "disabled",
prop: "disabled",
- value: "true",
+ type: "boolean",
+ value: true,
},
]),
publish: jest.fn(),
@@ -144,6 +147,7 @@ describe("usePropsLogic", () => {
"id": "1",
"prop": "tag",
"required": true,
+ "type": "string",
"value": "div",
},
]
@@ -157,13 +161,15 @@ describe("usePropsLogic", () => {
{
id: "1",
prop: "tag",
+ type: "string",
value: "div",
required: true,
},
{
id: "disabled",
prop: "disabled",
- value: "true",
+ type: "boolean",
+ value: true,
},
]),
publish: jest.fn(),
@@ -171,11 +177,14 @@ describe("usePropsLogic", () => {
);
act(() => {
- result.current.handleChangePropName("disabled", "disabled2", false);
+ result.current.handleChangePropName("disabled", "disabled2");
});
act(() => {
- result.current.handleChangePropValue("disabled", false);
+ result.current.handleChangePropValue("disabled", {
+ type: "boolean",
+ value: false,
+ });
});
expect(result.current.userProps).toMatchInlineSnapshot(`
@@ -184,11 +193,13 @@ describe("usePropsLogic", () => {
"id": "1",
"prop": "tag",
"required": true,
+ "type": "string",
"value": "div",
},
{
"id": "disabled",
"prop": "disabled2",
+ "type": "boolean",
"value": false,
},
]
@@ -202,13 +213,15 @@ describe("usePropsLogic", () => {
{
id: "1",
prop: "tag",
+ type: "string",
value: "div",
required: true,
},
{
id: "disabled",
prop: "disabled",
- value: "true",
+ type: "boolean",
+ value: true,
required: true,
},
]),
@@ -229,13 +242,15 @@ describe("usePropsLogic", () => {
"id": "1",
"prop": "tag",
"required": true,
+ "type": "string",
"value": "div",
},
{
"id": "disabled",
"prop": "disabled",
"required": true,
- "value": "true",
+ "type": "boolean",
+ "value": true,
},
]
`);
@@ -248,12 +263,14 @@ describe("usePropsLogic", () => {
{
id: "1",
prop: "tag",
+ type: "string",
value: "div",
required: true,
},
{
id: "2",
prop: "test",
+ type: "string",
value: "test",
required: true,
},
@@ -263,7 +280,7 @@ describe("usePropsLogic", () => {
);
act(() => {
- result.current.handleChangePropName("2", "test-example", "");
+ result.current.handleChangePropName("2", "test-example");
});
expect(result.current.userProps).toMatchInlineSnapshot(`
@@ -272,12 +289,14 @@ describe("usePropsLogic", () => {
"id": "1",
"prop": "tag",
"required": true,
+ "type": "string",
"value": "div",
},
{
"id": "2",
"prop": "test",
"required": true,
+ "type": "string",
"value": "test",
},
]
@@ -291,12 +310,14 @@ describe("usePropsLogic", () => {
{
id: "1",
prop: "tag",
+ type: "string",
value: "div",
required: true,
},
{
id: "2",
prop: "test",
+ type: "boolean",
value: true,
required: true,
},
@@ -306,7 +327,10 @@ describe("usePropsLogic", () => {
);
act(() => {
- result.current.handleChangePropValue("2", false);
+ result.current.handleChangePropValue("2", {
+ type: "boolean",
+ value: false,
+ });
});
expect(result.current.userProps).toMatchInlineSnapshot(`
@@ -315,12 +339,14 @@ describe("usePropsLogic", () => {
"id": "1",
"prop": "tag",
"required": true,
+ "type": "string",
"value": "div",
},
{
"id": "2",
"prop": "test",
"required": true,
+ "type": "boolean",
"value": false,
},
]
@@ -334,6 +360,7 @@ describe("usePropsLogic", () => {
{
id: "1",
prop: "tag",
+ type: "string",
value: "div",
required: true,
},
@@ -343,25 +370,51 @@ describe("usePropsLogic", () => {
);
act(() => {
- result.current.handleChangePropValue("1", "img", {
- 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",
- status: "uploaded",
+ 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: {
+ 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",
+ status: "uploaded",
+ },
});
});
expect(result.current.userProps).toMatchInlineSnapshot(`
[
{
- "asset": {
+ "id": "1",
+ "prop": "tag",
+ "required": true,
+ "type": "asset",
+ "value": {
"createdAt": "1995-12-17T03:24:00.000Z",
"description": "string",
"format": "string",
@@ -377,16 +430,15 @@ describe("usePropsLogic", () => {
"size": 1111,
"status": "uploaded",
},
- "id": "1",
- "prop": "tag",
- "required": true,
- "value": "img",
},
]
`);
act(() => {
- result.current.handleChangePropValue("1", "img");
+ result.current.handleChangePropValue("1", {
+ type: "string",
+ value: "img-3",
+ });
});
expect(result.current.userProps).toMatchInlineSnapshot(`
@@ -395,7 +447,8 @@ describe("usePropsLogic", () => {
"id": "1",
"prop": "tag",
"required": true,
- "value": "img",
+ "type": "string",
+ "value": "img-3",
},
]
`);
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 6a60056817..653f118812 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
@@ -2,6 +2,7 @@ import type {
DeleteProp,
UserProp,
UserPropsUpdates,
+ MetaProps,
} from "@webstudio-is/react-sdk";
import { type Publish } from "~/shared/pubsub";
import { getComponentMetaProps } from "@webstudio-is/react-sdk";
@@ -10,7 +11,7 @@ import produce from "immer";
import uniqBy from "lodash/uniqBy";
import { useState } from "react";
import type { SelectedInstanceData } from "@webstudio-is/project";
-import type { Asset } from "@webstudio-is/asset-uploader";
+import warnOnce from "warn-once";
declare module "~/shared/pubsub" {
export interface PubsubMap {
@@ -19,33 +20,62 @@ declare module "~/shared/pubsub" {
}
}
-type UserPropValue = Extract<UserProp, { value: unknown }>["value"];
+export type UserPropValue = UserProp extends infer T
+ ? T extends { value: unknown; type: unknown }
+ ? { value: T["value"]; type: T["type"] }
+ : never
+ : never;
-type HandleChangePropName = (
- id: UserProp["id"],
- name: string,
- defaultValue: string | boolean | number
-) => void;
+type HandleChangePropName = (id: UserProp["id"], name: string) => void;
-type HandleChangePropValue = (
- id: UserProp["id"],
- value: UserPropValue,
- asset?: Asset
-) => void;
+type HandleChangePropValue = (id: UserProp["id"], value: UserPropValue) => void;
+
+export const getValueFromPropMeta = (propValue: MetaProps[string]) => {
+ let typedValue: UserPropValue = {
+ type: "string",
+ value: `${propValue?.defaultValue ?? ""}`,
+ };
+
+ if (propValue?.type === "boolean") {
+ typedValue = {
+ type: "boolean",
+ value: propValue.defaultValue ?? false,
+ };
+ }
+
+ if (propValue?.type === "number") {
+ typedValue = {
+ type: "number",
+ value: propValue.defaultValue ?? 0,
+ };
+ }
+
+ return typedValue;
+};
const getRequiredProps = (
selectedInstanceData: SelectedInstanceData
): UserProp[] => {
const { component } = selectedInstanceData;
const meta = getComponentMetaProps(component);
+
return Object.entries(meta)
.filter(([_, value]) => value?.required)
- .map(([prop, _]) => ({
- id: ObjectId().toString(),
- prop,
- value: "",
- required: true,
- }));
+ .map(([prop, propValue]) => {
+ warnOnce(
+ propValue?.defaultValue == null,
+ `Default value for required "${prop}" is required`
+ );
+
+ const typedValue = getValueFromPropMeta(propValue);
+
+ return {
+ id: ObjectId().toString(),
+ prop,
+ ...typedValue,
+ required: true,
+ };
+ });
};
// @todo: This returns same props for all instances.
@@ -58,12 +88,13 @@ const getPropsWithDefaultValue = (
return Object.entries(meta)
.filter(([_, value]) => value?.defaultValue != null)
- .map(([prop, propObj]) => {
- const value = propObj?.defaultValue ?? "";
+ .map(([prop, propValue]) => {
+ const typedValue = getValueFromPropMeta(propValue);
+
return {
id: ObjectId().toString(),
prop,
- value,
+ ...typedValue,
};
});
};
@@ -116,19 +147,27 @@ export const usePropsLogic = ({
});
};
- const handleChangePropName: HandleChangePropName = (
- id,
- name,
- defaultValue
- ) => {
+ 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) {
- draft[index].prop = name;
- draft[index].value = defaultValue;
+ 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);
@@ -140,17 +179,14 @@ export const usePropsLogic = ({
updateProps(updatedProps);
};
- const handleChangePropValue: HandleChangePropValue = (id, value, asset) => {
+ const handleChangePropValue: HandleChangePropValue = (id, value) => {
const nextUserProps = produce((draft: Array<UserProp>) => {
const index = draft.findIndex((item) => item.id === id);
- const val = draft[index];
- val.value = value;
- if (asset) {
- val.asset = asset;
- } else if (val.asset != null) {
- delete val.asset;
- }
+ draft[index] = {
+ ...draft[index],
+ ...value,
+ };
})(userProps);
// Optimistically update the state (what if publish fails?)
@@ -180,6 +216,7 @@ export const usePropsLogic = ({
{
id: ObjectId().toString(),
prop: "",
+ type: "string",
value: "",
},
]);
diff --git a/apps/designer/app/shared/props-utils/__snapshots__/delete-prop.test.ts.snap b/apps/designer/app/shared/props-utils/__snapshots__/delete-prop.test.ts.snap
deleted file mode 100644
index d8105b6881..0000000000
--- a/apps/designer/app/shared/props-utils/__snapshots__/delete-prop.test.ts.snap
+++ /dev/null
@@ -1,40 +0,0 @@
-// Jest Snapshot v1, https://goo.gl/fbAQLP
-
-exports[`Delete prop found and deleted 1`] = `
-{
- "instanceId": {
- "id": "id",
- "instanceId": "instanceId",
- "props": [
- {
- "id": "propId1",
- "prop": "a",
- "value": "1",
- },
- ],
- "treeId": "treeId",
- },
-}
-`;
-
-exports[`Delete prop not found and not deleted 1`] = `
-{
- "instanceId": {
- "id": "id",
- "instanceId": "instanceId",
- "props": [
- {
- "id": "propId",
- "prop": "b",
- "value": "1",
- },
- {
- "id": "propId1",
- "prop": "a",
- "value": "1",
- },
- ],
- "treeId": "treeId",
- },
-}
-`;
diff --git a/apps/designer/app/shared/props-utils/__snapshots__/update-props.test.ts.snap b/apps/designer/app/shared/props-utils/__snapshots__/update-props.test.ts.snap
index 70d470cafe..11272d16ab 100644
--- a/apps/designer/app/shared/props-utils/__snapshots__/update-props.test.ts.snap
+++ b/apps/designer/app/shared/props-utils/__snapshots__/update-props.test.ts.snap
@@ -9,6 +9,7 @@ exports[`Update props with added prop 1`] = `
{
"id": "propId",
"prop": "a",
+ "type": "string",
"value": "1",
},
],
@@ -37,6 +38,8 @@ exports[`Update props with renamed prop name 1`] = `
{
"id": "propId",
"prop": "b",
+ "required": undefined,
+ "type": "string",
"value": "1",
},
],
@@ -54,6 +57,8 @@ exports[`Update props with updated prop value 1`] = `
{
"id": "propId",
"prop": "a",
+ "required": undefined,
+ "type": "string",
"value": "2",
},
],
diff --git a/apps/designer/app/shared/props-utils/delete-prop.test.ts b/apps/designer/app/shared/props-utils/delete-prop.test.ts
index 9fb33cd998..4f71b23eaf 100644
--- a/apps/designer/app/shared/props-utils/delete-prop.test.ts
+++ b/apps/designer/app/shared/props-utils/delete-prop.test.ts
@@ -9,8 +9,8 @@ describe("Delete prop", () => {
instanceId: "instanceId",
treeId: "treeId",
props: [
- { id: "propId", prop: "b", value: "1" },
- { id: "propId1", prop: "a", value: "1" },
+ { id: "propId", prop: "b", value: "1", type: "string" },
+ { id: "propId1", prop: "a", value: "1", type: "string" },
],
},
};
@@ -19,7 +19,23 @@ describe("Delete prop", () => {
instanceId: "instanceId",
propId: "propId",
});
- expect(propsMap).toMatchSnapshot();
+ expect(propsMap).toMatchInlineSnapshot(`
+ {
+ "instanceId": {
+ "id": "id",
+ "instanceId": "instanceId",
+ "props": [
+ {
+ "id": "propId1",
+ "prop": "a",
+ "type": "string",
+ "value": "1",
+ },
+ ],
+ "treeId": "treeId",
+ },
+ }
+ `);
expect(isDeleted).toBeTruthy();
});
@@ -30,8 +46,8 @@ describe("Delete prop", () => {
instanceId: "instanceId",
treeId: "treeId",
props: [
- { id: "propId", prop: "b", value: "1" },
- { id: "propId1", prop: "a", value: "1" },
+ { id: "propId", prop: "b", value: "1", type: "string" },
+ { id: "propId1", prop: "a", value: "1", type: "string" },
],
},
};
@@ -40,7 +56,29 @@ describe("Delete prop", () => {
instanceId: "instanceId",
propId: "notFound",
});
- expect(propsMap).toMatchSnapshot();
+ expect(propsMap).toMatchInlineSnapshot(`
+ {
+ "instanceId": {
+ "id": "id",
+ "instanceId": "instanceId",
+ "props": [
+ {
+ "id": "propId",
+ "prop": "b",
+ "type": "string",
+ "value": "1",
+ },
+ {
+ "id": "propId1",
+ "prop": "a",
+ "type": "string",
+ "value": "1",
+ },
+ ],
+ "treeId": "treeId",
+ },
+ }
+ `);
expect(isDeleted).toBeFalsy();
});
});
diff --git a/apps/designer/app/shared/props-utils/update-props.test.ts b/apps/designer/app/shared/props-utils/update-props.test.ts
index d71b253577..309d6ebc59 100644
--- a/apps/designer/app/shared/props-utils/update-props.test.ts
+++ b/apps/designer/app/shared/props-utils/update-props.test.ts
@@ -38,7 +38,7 @@ describe("Update props", () => {
propsId: "id",
instanceId: "instanceId",
treeId: "treeId",
- updates: [{ id: "propId", prop: "a", value: "1" }],
+ updates: [{ id: "propId", prop: "a", value: "1", type: "string" }],
};
updateAllUserPropsMutable(propsMap, update);
expect(propsMap).toMatchSnapshot();
@@ -50,14 +50,14 @@ describe("Update props", () => {
id: "id",
instanceId: "instanceId",
treeId: "treeId",
- props: [{ id: "propId", prop: "a", value: "1" }],
+ props: [{ id: "propId", prop: "a", value: "1", type: "string" }],
},
};
const update: UserPropsUpdates = {
propsId: "id",
instanceId: "instanceId",
treeId: "treeId",
- updates: [{ id: "propId", prop: "a", value: "2" }],
+ updates: [{ id: "propId", prop: "a", value: "2", type: "string" }],
};
updateAllUserPropsMutable(propsMap, update);
expect(propsMap).toMatchSnapshot();
@@ -69,14 +69,14 @@ describe("Update props", () => {
id: "id",
instanceId: "instanceId",
treeId: "treeId",
- props: [{ id: "propId", prop: "a", value: "1" }],
+ props: [{ id: "propId", prop: "a", value: "1", type: "string" }],
},
};
const update: UserPropsUpdates = {
propsId: "id",
instanceId: "instanceId",
treeId: "treeId",
- updates: [{ id: "propId", prop: "b", value: "1" }],
+ updates: [{ id: "propId", prop: "b", value: "1", type: "string" }],
};
updateAllUserPropsMutable(propsMap, update);
expect(propsMap).toMatchSnapshot();
@@ -88,7 +88,7 @@ describe("Update props", () => {
id: "id",
instanceId: "instanceId",
treeId: "treeId",
- props: [{ id: "propId", prop: "a", value: "1" }],
+ props: [{ id: "propId", prop: "a", value: "1", type: "string" }],
},
};
const update: UserPropsUpdates = {
@@ -99,8 +99,8 @@ describe("Update props", () => {
{
id: "propId",
prop: "a",
- value: "test",
- asset: { id: "assetId" } as Asset,
+ type: "asset",
+ value: { id: "assetId" } as Asset,
},
],
};
@@ -112,12 +112,13 @@ describe("Update props", () => {
"instanceId": "instanceId",
"props": [
{
- "asset": {
- "id": "assetId",
- },
"id": "propId",
"prop": "a",
- "value": "test",
+ "required": undefined,
+ "type": "asset",
+ "value": {
+ "id": "assetId",
+ },
},
],
"treeId": "treeId",
diff --git a/apps/designer/app/shared/props-utils/update-props.ts b/apps/designer/app/shared/props-utils/update-props.ts
index 2bc2eb0d8e..cdf458c7b4 100644
--- a/apps/designer/app/shared/props-utils/update-props.ts
+++ b/apps/designer/app/shared/props-utils/update-props.ts
@@ -25,20 +25,11 @@ export const updateAllUserPropsMutable = (
instanceProps.props.push(update);
} else {
const prop = instanceProps.props[propIndex];
- prop.prop = update.prop;
+ prop.prop = update.prop;
+ prop.type = update.type;
prop.value = update.value;
-
- if (update.asset != null) {
- prop.asset = update.asset;
- } else {
- if (prop.asset != null) {
- delete prop.asset;
- }
- }
-
- // Prop changed type from value to asset or vice versa
- instanceProps.props[propIndex] = update;
+ prop.required = update.required;
}
}
};
diff --git a/packages/generate-arg-types/src/index.ts b/packages/generate-arg-types/src/index.ts
index f8e9dcce00..28986f6479 100755
--- a/packages/generate-arg-types/src/index.ts
+++ b/packages/generate-arg-types/src/index.ts
@@ -44,7 +44,7 @@ const ArgTypes = z.record(
z.object({
type: z.string(),
required: z.boolean(),
- defaultValue: z.union([z.null(), z.string()]),
+ defaultValue: z.union([z.null(), z.string(), z.number(), z.boolean()]),
options: z.array(z.string()).optional(),
})
);
diff --git a/packages/image/src/__generated__/image.props.json b/packages/image/src/__generated__/image.props.json
index cf5310d413..5a8918c7c2 100644
--- a/packages/image/src/__generated__/image.props.json
+++ b/packages/image/src/__generated__/image.props.json
@@ -568,7 +568,7 @@
"type": "text"
},
"optimize": {
- "defaultValue": null,
+ "defaultValue": true,
"required": false,
"type": "boolean"
}
diff --git a/packages/image/src/image.tsx b/packages/image/src/image.tsx
index df4a522134..1aea0addda 100644
--- a/packages/image/src/image.tsx
+++ b/packages/image/src/image.tsx
@@ -14,16 +14,13 @@ export const Image = forwardRef<ElementRef<typeof defaultTag>, ImageProps>(
{
quality,
loader,
- optimize,
+ optimize = true,
loading = "lazy",
decoding = "async",
...imageProps
},
ref
) => {
- // Temporary set to false, to support previous image behaviour
- const DEFAULT_OPTIMIZE = false;
-
const imageAttributes = getImageAttributes({
src: imageProps.src,
srcSet: imageProps.srcSet,
@@ -31,7 +28,7 @@ export const Image = forwardRef<ElementRef<typeof defaultTag>, ImageProps>(
width: imageProps.width,
quality,
loader,
- optimize: optimize ?? DEFAULT_OPTIMIZE,
+ optimize,
}) ?? { src: imagePlaceholderSvg };
return (
diff --git a/packages/prisma-client/prisma/migrations/20221201075120_user-props/migration.ts b/packages/prisma-client/prisma/migrations/20221201075120_user-props/migration.ts
new file mode 100644
index 0000000000..c6d8f0ee4d
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20221201075120_user-props/migration.ts
@@ -0,0 +1,153 @@
+import { z } from "zod";
+import { PrismaClient } from "./client";
+
+const baseUserProps = {
+ id: z.string(),
+ prop: z.string(),
+ required: z.optional(z.boolean()),
+};
+
+export const UserDbProp = z.discriminatedUnion("type", [
+ z.object({
+ ...baseUserProps,
+ type: z.literal("number"),
+ value: z.number(),
+ }),
+ z.object({
+ ...baseUserProps,
+ type: z.literal("string"),
+ value: z.string(),
+ }),
+ z.object({
+ ...baseUserProps,
+ type: z.literal("boolean"),
+ value: z.boolean(),
+ }),
+ z.object({
+ ...baseUserProps,
+ type: z.literal("asset"),
+ // In database we hold asset.id
+ value: z.string(),
+ }),
+]);
+
+const UserDbProps = z.array(UserDbProp);
+type UserDbProp = z.infer<typeof UserDbProp>;
+
+const OutdatedProp = z.object({
+ ...baseUserProps,
+ value: z.optional(z.union([z.string(), z.number(), z.boolean()])),
+ asset_id: z.optional(z.string()),
+ assetId: z.optional(z.string()),
+ type: z.optional(z.string()),
+});
+
+const OutdatedProps = z.array(OutdatedProp);
+
+export default () => {
+ const client = new PrismaClient({
+ // Uncomment to see the queries in console as the migration runs
+ // log: ["query", "info", "warn", "error"],
+ });
+ return client.$transaction(
+ async (prisma) => {
+ const allInstanceProps = await prisma.instanceProps.findMany({
+ where: {
+ props: {
+ not: {
+ equals: "[]",
+ },
+ },
+ },
+ });
+
+ for (const instanceProps of allInstanceProps) {
+ const rawProps = JSON.parse(instanceProps.props);
+ const props = OutdatedProps.parse(rawProps);
+
+ const newProps: UserDbProp[] = [];
+
+ let need_update = false;
+
+ for (const prop of props) {
+ if (prop.type != null) {
+ const dbProp = UserDbProp.parse(prop);
+ newProps.push(dbProp);
+ continue;
+ }
+
+ need_update = true;
+
+ if (prop.assetId != null) {
+ newProps.push({
+ id: prop.id,
+ prop: prop.prop,
+ required: prop.required,
+ type: "asset",
+ value: prop.assetId,
+ });
+ continue;
+ }
+
+ if (prop.asset_id != null) {
+ newProps.push({
+ id: prop.id,
+ prop: prop.prop,
+ required: prop.required,
+ type: "asset",
+ value: prop.asset_id,
+ });
+ continue;
+ }
+
+ if (prop.value == null) {
+ continue;
+ }
+
+ if (typeof prop.value === "string") {
+ newProps.push({
+ id: prop.id,
+ prop: prop.prop,
+ required: prop.required,
+ type: "string",
+ value: prop.value,
+ });
+ continue;
+ }
+
+ if (typeof prop.value === "boolean") {
+ newProps.push({
+ id: prop.id,
+ prop: prop.prop,
+ required: prop.required,
+ type: "boolean",
+ value: prop.value,
+ });
+ continue;
+ }
+
+ if (typeof prop.value === "number") {
+ newProps.push({
+ id: prop.id,
+ prop: prop.prop,
+ required: prop.required,
+ type: "number",
+ value: prop.value,
+ });
+ continue;
+ }
+
+ throw new Error(`Unexpected prop type ${typeof prop.value}`);
+ }
+
+ if (need_update) {
+ await prisma.instanceProps.update({
+ where: { id: instanceProps.id },
+ data: { props: JSON.stringify(UserDbProps.parse(newProps)) },
+ });
+ }
+ }
+ },
+ { timeout: 1000 * 60 }
+ );
+};
diff --git a/packages/prisma-client/prisma/migrations/20221201075120_user-props/schema.prisma b/packages/prisma-client/prisma/migrations/20221201075120_user-props/schema.prisma
new file mode 100644
index 0000000000..6b01a80b0a
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20221201075120_user-props/schema.prisma
@@ -0,0 +1,95 @@
+// DO NOT EDIT THIS FILE!
+// This is a copy of your schema.prisma that corresponds to the state of the database
+// when all migrations up until this one are applied.
+// It's used to generate a Prisma Client for the migration.
+
+// This is your Prisma schema file,
+// learn more about it in the docs: https://pris.ly/d/prisma-schema
+
+generator client {
+ provider = "prisma-client-js"
+ previewFeatures = ["interactiveTransactions"]
+ output = "client"
+}
+
+datasource db {
+ provider = "postgres"
+ url = env("DATABASE_URL")
+}
+
+model Team {
+ id String @id @default(uuid())
+ users User[]
+}
+
+enum Location {
+ FS
+ REMOTE
+}
+
+model Asset {
+ id String @id @default(uuid())
+ project Project @relation(fields: [projectId], references: [id])
+ projectId String
+ format String
+ size Int
+ name String
+ description String?
+ location Location
+ createdAt DateTime @default(now())
+ meta String @default("{}")
+}
+
+model User {
+ id String @id @default(uuid())
+ email String? @unique
+ provider String?
+ image String?
+ username String?
+ createdAt DateTime @default(now())
+ team Team? @relation(fields: [teamId], references: [id])
+ teamId String?
+ projects Project[]
+}
+
+model Project {
+ id String @id @default(uuid())
+ title String
+ domain String @unique
+ user User? @relation(fields: [userId], references: [id])
+ userId String?
+ assets Asset[]
+ build Build[]
+}
+
+model Build {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ pages String
+
+ project Project @relation(fields: [projectId], references: [id])
+ projectId String
+
+ isDev Boolean // exctly one is true per project
+ isProd Boolean // at most one is true per project (none if not published)
+
+ breakpoints Breakpoints?
+}
+
+model Tree {
+ id String @id @default(uuid())
+ root String
+}
+
+model InstanceProps {
+ id String @id @default(uuid())
+ instanceId String
+ treeId String
+ props String @default("[]")
+}
+
+model Breakpoints {
+ build Build @relation(fields: [buildId], references: [id])
+ buildId String @id
+ values String @default("[]")
+}
diff --git a/packages/project/src/db/props.ts b/packages/project/src/db/props.ts
index ccf6c03fc4..6f37d840b0 100644
--- a/packages/project/src/db/props.ts
+++ b/packages/project/src/db/props.ts
@@ -1,16 +1,50 @@
+import { z } from "zod";
+
import warnOnce from "warn-once";
import {
type Tree,
type AllUserProps,
type UserProp,
UserProps,
- // @todo move zod schema into project package
- UserDbProps,
} from "@webstudio-is/react-sdk";
import { applyPatches, type Patch } from "immer";
import { prisma } from "@webstudio-is/prisma-client";
import { formatAsset } from "@webstudio-is/asset-uploader/server";
+const baseUserProps = {
+ id: z.string(),
+ prop: z.string(),
+ required: z.optional(z.boolean()),
+};
+
+export const UserDbProp = z.discriminatedUnion("type", [
+ z.object({
+ ...baseUserProps,
+ type: z.literal("number"),
+ value: z.number(),
+ }),
+ z.object({
+ ...baseUserProps,
+ type: z.literal("string"),
+ value: z.string(),
+ }),
+ z.object({
+ ...baseUserProps,
+ type: z.literal("boolean"),
+ value: z.boolean(),
+ }),
+ z.object({
+ ...baseUserProps,
+ type: z.literal("asset"),
+ // In database we hold asset.id
+ value: z.string(),
+ }),
+]);
+
+const UserDbProps = z.array(UserDbProp);
+
+type UserDbProp = z.infer<typeof UserDbProp>;
+
export const loadByTreeId = async (treeId: Tree["id"]) => {
const instancePropsEntries = await prisma.instanceProps.findMany({
where: { treeId },
@@ -21,11 +55,11 @@ export const loadByTreeId = async (treeId: Tree["id"]) => {
for (const instanceProps of instancePropsEntries) {
const props = JSON.parse(instanceProps.props);
- const dpProps = UserDbProps.parse(props);
+ const dbProps = UserDbProps.parse(props);
- for (const dbProp of dpProps) {
- if (dbProp.assetId != null) {
- assetIds.push(dbProp.assetId);
+ for (const dbProp of dbProps) {
+ if (dbProp.type === "asset") {
+ assetIds.push(dbProp.value);
}
}
}
@@ -45,27 +79,28 @@ export const loadByTreeId = async (treeId: Tree["id"]) => {
return instancePropsEntries.map((instanceProps) => {
const props = JSON.parse(instanceProps.props);
const userProps: UserProp[] = [];
+
// Can be changed onto `props as ` having that above is already checked, no optmizations now
const dpProps = UserDbProps.parse(props);
for (const dbProp of dpProps) {
- if (dbProp.assetId == null) {
- userProps.push(dbProp);
- continue;
- }
+ if (dbProp.type === "asset") {
+ const assetId = dbProp.value;
+ const asset = assetsMap.get(assetId);
+
+ if (asset) {
+ userProps.push({
+ ...dbProp,
+ value: asset,
+ });
+ continue;
+ }
- const { assetId, ...userProp } = dbProp;
- const asset = assetsMap.get(assetId);
-
- if (asset) {
- userProps.push({
- ...userProp,
- asset,
- });
- } else {
- userProps.push(userProp);
warnOnce(true, `Asset with assetId "${assetId}" not found`);
+ continue;
}
+
+ userProps.push(dbProp);
}
return {
@@ -124,9 +159,15 @@ export const patch = async (
await Promise.all(
Object.values(nextProps).map(({ id, instanceId, treeId, props }) => {
- const propsDb: UserDbProps = UserProps.parse(props).map((prop) => {
- const { asset, ...rest } = prop;
- return { ...rest, assetId: asset?.id };
+ const propsDb: UserDbProp[] = UserProps.parse(props).map((prop) => {
+ if (prop.type === "asset") {
+ return {
+ ...prop,
+ value: prop.value.id,
+ };
+ }
+
+ return prop;
});
const propsString = JSON.stringify(propsDb);
diff --git a/packages/react-sdk/src/app/custom-components/image.tsx b/packages/react-sdk/src/app/custom-components/image.tsx
index 26164fe624..6d00288462 100644
--- a/packages/react-sdk/src/app/custom-components/image.tsx
+++ b/packages/react-sdk/src/app/custom-components/image.tsx
@@ -28,12 +28,17 @@ export const Image = forwardRef<ElementRef<typeof defaultTag>, Props>(
return loaders.localImageLoader();
}, [asset, params]);
- if (asset === null || loader == null)
- return <SdkImage {...props} ref={ref} />;
+ let src = props.src;
- return (
- <WebstudioImage {...props} loader={loader} optimize={true} ref={ref} />
- );
+ if (asset != null) {
+ src = asset.path;
+ }
+
+ if (asset == null || loader == null) {
+ return <SdkImage {...props} src={src} ref={ref} />;
+ }
+
+ return <WebstudioImage {...props} loader={loader} src={src} ref={ref} />;
}
);
diff --git a/packages/react-sdk/src/index.ts b/packages/react-sdk/src/index.ts
index c030f6ec31..d1d49a6a93 100644
--- a/packages/react-sdk/src/index.ts
+++ b/packages/react-sdk/src/index.ts
@@ -9,3 +9,4 @@ export {
customComponents,
customComponentsMeta,
} from "./app/custom-components";
+export type { MetaProps } from "./components/component-type";
diff --git a/packages/react-sdk/src/user-props/schema.ts b/packages/react-sdk/src/user-props/schema.ts
index 1b8b2f91f1..af29ce6bde 100644
--- a/packages/react-sdk/src/user-props/schema.ts
+++ b/packages/react-sdk/src/user-props/schema.ts
@@ -1,26 +1,35 @@
import { z } from "zod";
import { Asset } from "@webstudio-is/asset-uploader";
-const UserPropDb = z.object({
+const baseUserProps = {
id: z.string(),
prop: z.string(),
- value: z.union([z.string(), z.boolean(), z.number()]),
- assetId: z.optional(z.string()),
required: z.optional(z.boolean()),
-});
-export type UserPropDb = z.infer<typeof UserPropDb>;
+};
-export const UserDbProps = z.array(UserPropDb);
-export type UserDbProps = z.infer<typeof UserDbProps>;
-
-export const UserProp = z.object({
- id: z.string(),
- prop: z.string(),
- value: z.union([z.string(), z.boolean(), z.number()]),
- asset: Asset.optional(),
- required: z.optional(z.boolean()),
-});
-export type UserProp = z.infer<typeof UserProp>;
+export const UserProp = z.discriminatedUnion("type", [
+ z.object({
+ ...baseUserProps,
+ type: z.literal("number"),
+ value: z.number(),
+ }),
+ z.object({
+ ...baseUserProps,
+ type: z.literal("string"),
+ value: z.string(),
+ }),
+ z.object({
+ ...baseUserProps,
+ type: z.literal("boolean"),
+ value: z.boolean(),
+ }),
+ z.object({
+ ...baseUserProps,
+ type: z.literal("asset"),
+ value: Asset,
+ }),
+]);
export const UserProps = z.array(UserProp);
-export type UserProps = z.infer<typeof UserProps>;
+
+export type UserProp = z.infer<typeof UserProp>;
diff --git a/packages/react-sdk/src/user-props/use-user-props-asset.ts b/packages/react-sdk/src/user-props/use-user-props-asset.ts
index a537db5559..307c100889 100644
--- a/packages/react-sdk/src/user-props/use-user-props-asset.ts
+++ b/packages/react-sdk/src/user-props/use-user-props-asset.ts
@@ -10,16 +10,21 @@ import type { Asset } from "@webstudio-is/asset-uploader";
export const useUserPropsAsset = (
instanceId: Instance["id"],
propName: UserProp["prop"]
-): Asset | null => {
+): Asset | undefined => {
const [allUserProps] = useAllUserProps();
const propsData = allUserProps[instanceId];
const asset = useMemo(() => {
- if (propsData == null) return null;
+ if (propsData == null) return undefined;
const prop = propsData.props.find((prop) => prop.prop === propName);
- if (prop == null) return null;
- return prop.asset ?? null;
+ if (prop == null) return undefined;
+
+ if (prop.type === "asset") {
+ return prop.value;
+ }
+
+ return undefined;
}, [propName, propsData]);
return asset;
diff --git a/packages/react-sdk/src/user-props/use-user-props.ts b/packages/react-sdk/src/user-props/use-user-props.ts
index fe0a193d20..bfd6a2100b 100644
--- a/packages/react-sdk/src/user-props/use-user-props.ts
+++ b/packages/react-sdk/src/user-props/use-user-props.ts
@@ -3,7 +3,7 @@ import { type Instance } from "../db";
import { type UserProp } from "./schema";
import { useAllUserProps } from "./all-user-props";
-type UserProps = { [prop: UserProp["prop"]]: UserProp["value"] };
+type UserProps = { [prop: UserProp["prop"]]: string | number | boolean };
/**
* User props mapped in prop:value format,
@@ -15,10 +15,15 @@ export const useUserProps = (instanceId: Instance["id"]) => {
const propsData = allUserProps[instanceId];
const props = useMemo(() => {
if (propsData == null) return {};
- return propsData.props.reduce((props, { prop, value }) => {
- props[prop] = value;
- return props;
- }, {} as UserProps);
+ const result: UserProps = {};
+
+ for (const userProp of propsData.props) {
+ if (userProp.type !== "asset") {
+ result[userProp.prop] = userProp.value;
+ }
+ }
+
+ return result;
}, [propsData]);
return props;