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.

[designer] Assets picker (#444)

Ivan Starkove08aa99c4323
diff --git a/apps/designer/app/designer/features/inspector/inspector.tsx b/apps/designer/app/designer/features/inspector/inspector.tsx
index beee2246c6..ff1d1397b6 100644
--- a/apps/designer/app/designer/features/inspector/inspector.tsx
+++ b/apps/designer/app/designer/features/inspector/inspector.tsx
@@ -39,7 +39,14 @@ export const Inspector = ({ publish }: InspectorProps) => {
return (
// @todo: Nit: I wonder if this width was supposed to be defined by the parent container layout
- <Tabs defaultValue="style" css={{ width: "100%" }}>
+ <Tabs
+ defaultValue="style"
+ css={{
+ width: "100%",
+ position:
+ "relative" /* Hack - value picker popover positioning depends on it */,
+ }}
+ >
<TabsList>
<TabsTrigger value="style">
<Text>Style</Text>
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 e08f38dfdb..a805d3ef7a 100644
--- a/apps/designer/app/designer/features/props-panel/control.stories.tsx
+++ b/apps/designer/app/designer/features/props-panel/control.stories.tsx
@@ -7,22 +7,22 @@ export default {
export const Primitive: ComponentStoryObj<typeof Control> = {
args: {
- type: "text",
+ component: "Image",
+ userProp: {
+ prop: "src",
+ id: "ddf20afe-65a8-478e-a52d-1be2d2f70830",
+ value: "",
+ },
},
};
export const Options: ComponentStoryObj<typeof Control> = {
args: {
- type: "radio",
- options: ["option1", "option2"],
- },
-};
-
-export const Range: ComponentStoryObj<typeof Control> = {
- args: {
- type: "range",
- min: 0,
- max: 100,
- step: 1,
+ component: "Image",
+ userProp: {
+ prop: "loading",
+ id: "ddf20afe-65a8-478e-a52d-1be2d2f70830",
+ value: "",
+ },
},
};
diff --git a/apps/designer/app/designer/features/props-panel/control.tsx b/apps/designer/app/designer/features/props-panel/control.tsx
index 184377cfec..dab2e52657 100644
--- a/apps/designer/app/designer/features/props-panel/control.tsx
+++ b/apps/designer/app/designer/features/props-panel/control.tsx
@@ -1,80 +1,102 @@
-import { UserProp } from "@webstudio-is/react-sdk";
-import type { ComponentProps } from "react";
+import {
+ componentsMeta,
+ type Instance,
+ type UserProp,
+} from "@webstudio-is/react-sdk";
+import warnOnce from "warn-once";
import {
Flex,
Label,
Radio,
RadioGroup,
Select,
- Slider,
Switch,
- Text,
TextField,
} from "@webstudio-is/design-system";
+import { isFeatureEnabled } from "~/shared/feature-flags";
+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";
-type BaseControlProps<T = UserProp["value"]> = {
- value?: T;
- defaultValue?: T;
- onChange: (value: T) => void;
- required?: boolean;
-};
-type TextControlProps = BaseControlProps & {
- type?: ComponentProps<typeof TextField>["type"];
- defaultValue?: UserProp["value"];
+const textControlTypes = [
+ "text",
+ "array",
+ "color",
+ "date",
+ "file",
+ "number",
+ "object",
+] as const;
+
+type TextControlProps = {
+ type: typeof textControlTypes[number];
+ value: string;
+ onChange: (value: string) => void;
};
-const TextControl = ({
- value,
- defaultValue,
- type,
- onChange,
-}: TextControlProps) => (
+
+const TextControl = ({ value, type, onChange }: TextControlProps) => (
<TextField
type={type}
placeholder="Value"
name="value"
- value={String(value || defaultValue || "")}
+ value={value}
onChange={(event) => {
onChange(event.target.value);
}}
/>
);
-type CheckboxControlProps = BaseControlProps & {
+
+const checkboxControlTypes = ["check", "inline-check", "multi-select"] as const;
+
+type CheckboxControlProps = {
+ value: string;
+ onChange: (value: string) => void;
options: Array<string>;
+ type: typeof checkboxControlTypes[number];
};
+
const CheckboxControl = ({
value,
options,
- defaultValue,
onChange,
}: CheckboxControlProps) => (
<RadioGroup
css={{ flexDirection: "column" }}
name="value"
- value={String(value || defaultValue || "")}
+ value={value}
onValueChange={onChange}
>
- {options.map((value) => (
- <Flex align="center" gap="1" key={value}>
- <Checkbox value={value} />
- <Label>{value}</Label>
+ {options.map((option) => (
+ <Flex align="center" gap="1" key={option}>
+ <Checkbox value={option} />
+ <Label>{option}</Label>
</Flex>
))}
</RadioGroup>
);
-type RadioControlProps = BaseControlProps & {
+
+const radioControlTypes = ["radio", "inline-radio"] as const;
+
+type RadioControlProps = {
+ value: string;
+ onChange: (value: string) => void;
+
options: Array<string>;
+ type: typeof radioControlTypes[number];
};
+
const RadioControl = ({
value,
options,
- defaultValue,
+
onChange,
}: RadioControlProps) => (
<RadioGroup
css={{ flexDirection: "column" }}
name="value"
- value={String(value || defaultValue || "")}
+ value={value}
onValueChange={onChange}
>
{options.map((value) => (
@@ -86,29 +108,35 @@ const RadioControl = ({
</RadioGroup>
);
-type SelectControlProps = BaseControlProps & {
+const selectControlTypes = ["select"] as const;
+type SelectControlProps = {
+ value: string;
+ onChange: (value: string) => void;
+
options: Array<string>;
+ type: typeof selectControlTypes[number];
};
const SelectControl = ({
value,
options,
- defaultValue,
+
onChange,
}: SelectControlProps) => (
- <Select
- name="value"
- value={String(value || defaultValue || "")}
- options={options}
- onChange={onChange}
- />
+ <Select name="value" value={value} options={options} onChange={onChange} />
);
+type BooleanControlProps = {
+ defaultValue?: boolean;
+ value: boolean;
+ onChange: (value: boolean) => void;
+};
+
const BooleanControl = ({
value,
defaultValue,
onChange,
-}: BaseControlProps) => (
+}: BooleanControlProps) => (
<Switch
name="value"
defaultChecked={Boolean(defaultValue)}
@@ -117,107 +145,161 @@ const BooleanControl = ({
/>
);
-const RangeControl = ({
- value,
- defaultValue,
- onChange,
- min,
- max,
- step,
-}: RangeControlProps) => (
- <Flex direction="column" gap={1}>
- <Slider
- value={value}
- defaultValue={defaultValue}
- onValueChange={(values) => {
- onChange(values[0]);
- }}
- min={min}
- max={max}
- step={step}
- />
- <Flex direction="row" justify="between">
- <Text>{min}</Text>
- <Text>{max}</Text>
- </Flex>
- </Flex>
-);
-
-type PrimitiveControlProps = BaseControlProps & {
- type: "array" | "boolean" | "date" | "number" | "object" | "text";
+type ImageControlProps = {
+ asset: Asset | null;
+ onChange: (asset: Asset) => void;
};
-type ColorControlProps = BaseControlProps & {
- type: "color";
- presetColors?: Array<string>;
+const ImageControl = ({ asset, onChange }: ImageControlProps) => {
+ return (
+ <ValuePickerPopover
+ title="Images"
+ content={<ImageManager onChange={onChange} />}
+ >
+ <TextField defaultValue={asset?.name ?? " - "} />
+ </ValuePickerPopover>
+ );
};
-type FileControlProps = BaseControlProps & {
- type: "file";
- accept: string;
-};
+const NotImplemented = () => <div />;
-type RangeControlProps = BaseControlProps<number> & {
- type: "range";
- min: number;
- max: number;
- step: number;
+const includes = <T extends string>(arr: readonly T[], v: string): v is T => {
+ return arr.includes(v as never);
};
-type OptionsControlProps = BaseControlProps & {
- type:
- | "radio"
- | "inline-radio"
- | "check"
- | "inline-check"
- | "select"
- | "multi-select";
- options: Array<string>;
+const assertUnreachable = (_arg: never, errorMessage: string) => {
+ throw new Error(errorMessage);
};
-export type ControlProps =
- | PrimitiveControlProps
- | OptionsControlProps
- | FileControlProps
- | ColorControlProps
- | RangeControlProps;
+type ControlProps = {
+ component: Instance["component"];
+ userProp: UserProp;
+ onChangePropValue: (value: string | boolean, asset?: Asset) => void;
+};
// eslint-disable-next-line func-style
-export function Control(props: ControlProps) {
- switch (props.type) {
- case "array":
- return <TextControl {...props} />;
- case "boolean":
- return <BooleanControl {...props} />;
- case "color":
- return <TextControl {...props} type="color" />;
- case "date":
- return <TextControl {...props} type="date" />;
- case "file":
- return <TextControl {...props} type="file" />;
- case "number":
- return <TextControl {...props} type="number" />;
- case "range":
- return <RangeControl {...props} />;
- case "object":
- return <TextControl {...props} />;
- case "radio":
- return <RadioControl {...props} />;
- case "inline-radio":
- return <RadioControl {...props} />;
- case "check":
- return <CheckboxControl {...props} />;
- case "inline-check":
- return <CheckboxControl {...props} />;
- case "select":
- return <SelectControl {...props} />;
- case "multi-select":
- return <CheckboxControl {...props} />;
- case "text":
- return <TextControl {...props} />;
- default: {
- const _exhaustivecheck: never = props;
- return _exhaustivecheck;
+export function Control({
+ component,
+ userProp,
+ onChangePropValue,
+}: ControlProps) {
+ const meta = componentsMeta[component];
+ const argType = meta[userProp.prop as keyof typeof meta];
+
+ const defaultValue = argType.defaultValue;
+ const type = argType.type;
+
+ if (type == null) {
+ warnOnce(
+ true,
+ `No control type for prop "${userProp.prop}" component "${component}" found`
+ );
+ return <NotImplemented />;
+ }
+
+ if (typeof type !== "string") {
+ warnOnce(
+ true,
+ `Control type "${typeof type}" for prop "${
+ userProp.prop
+ }" component "${component}" is not a string`
+ );
+
+ return <NotImplemented />;
+ }
+
+ if (isFeatureEnabled("assets")) {
+ if (component === "Image" && userProp.prop === "src") {
+ const asset = userProp.asset ?? null;
+
+ return (
+ <ImageControl
+ asset={asset}
+ onChange={(asset) => onChangePropValue(asset.path, asset)}
+ />
+ );
}
}
+
+ if (includes(textControlTypes, type)) {
+ const value = `${userProp.value}`;
+
+ return (
+ <TextControl value={value} onChange={onChangePropValue} type={type} />
+ );
+ }
+
+ if (type === "boolean") {
+ const value = Boolean(userProp.value);
+
+ return (
+ <BooleanControl
+ value={value}
+ onChange={onChangePropValue}
+ defaultValue={Boolean(defaultValue)}
+ />
+ );
+ }
+
+ if (
+ argType.type === "radio" ||
+ argType.type === "inline-radio" ||
+ argType.type === "check" ||
+ argType.type === "inline-check" ||
+ argType.type === "multi-select" ||
+ argType.type === "select"
+ ) {
+ const options = argType.options;
+
+ const value = `${userProp.value}`;
+
+ warnOnce(
+ options == null,
+ `options is not an array of strings for prop: ${userProp.prop} component: ${component}`
+ );
+
+ const DEFAULT_OPTIONS: string[] = [];
+
+ if (includes(radioControlTypes, type)) {
+ return (
+ <RadioControl
+ value={value}
+ onChange={onChangePropValue}
+ options={options ?? DEFAULT_OPTIONS}
+ type={type}
+ />
+ );
+ }
+
+ if (includes(checkboxControlTypes, type)) {
+ return (
+ <CheckboxControl
+ value={value}
+ onChange={onChangePropValue}
+ options={options ?? DEFAULT_OPTIONS}
+ type={type}
+ />
+ );
+ }
+
+ if (includes(selectControlTypes, type)) {
+ return (
+ <SelectControl
+ value={value}
+ onChange={onChangePropValue}
+ options={options ?? DEFAULT_OPTIONS}
+ type={type}
+ />
+ );
+ }
+
+ assertUnreachable(type, `Unknown control type ${type}`);
+ }
+
+ warnOnce(
+ true,
+ `Control type "${type}" is not implemented for prop: "${userProp.prop}" in component "${component}"`
+ );
+
+ return <NotImplemented />;
}
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 c7dfaf6a6f..892dcdcd78 100644
--- a/apps/designer/app/designer/features/props-panel/props-panel.tsx
+++ b/apps/designer/app/designer/features/props-panel/props-panel.tsx
@@ -3,6 +3,7 @@ import {
type Instance,
type UserProp,
} from "@webstudio-is/react-sdk";
+
import { type Publish } from "~/shared/pubsub";
import { Control } from "./control";
import { CollapsibleSection, ComponentInfo } from "~/designer/shared/inspector";
@@ -27,7 +28,8 @@ import {
ExclamationTriangleIcon,
ChevronDownIcon,
} from "@webstudio-is/icons";
-import { handleChangePropType, usePropsLogic } from "./use-props-logic";
+import { usePropsLogic } from "./use-props-logic";
+import type { Asset } from "@webstudio-is/asset-uploader";
type ComboboxProps = {
isReadonly: boolean;
@@ -104,79 +106,82 @@ const Combobox = ({
);
};
-type PropertyProps = UserProp & {
+type PropertyProps = {
+ userProp: UserProp;
component: Instance["component"];
- onChange: handleChangePropType;
+ onChangePropName: (name: string, defaultValue: string | boolean) => void;
+ onChangePropValue: (value: string | boolean, asset?: Asset) => void;
onDelete: (id: UserProp["id"]) => void;
};
const Property = ({
- id,
- prop,
- value,
- required = false,
+ userProp,
component,
- onChange,
+ onChangePropName,
+ onChangePropValue,
onDelete,
}: PropertyProps) => {
const meta = componentsMeta[component];
- const argType = meta[prop as keyof typeof meta];
+
+ const argType = meta[userProp.prop as keyof typeof meta];
const isInvalid =
- prop != null &&
- prop.length > 0 &&
+ userProp.prop != null &&
+ userProp.prop.length > 0 &&
typeof argType === "undefined" &&
- !prop.match(/^data-(.)+/);
- const type = argType?.type || "text";
- const defaultValue = argType?.defaultValue;
- const options = argType?.options;
+ !userProp.prop.match(/^data-(.)+/);
+
const allProps = Object.keys(meta);
return (
- <Grid
- gap={1}
- css={{ gridTemplateColumns: "1fr 1fr auto", alignItems: "center" }}
- >
+ <>
<Combobox
items={allProps}
- value={prop}
- onItemSelect={(value: PropertyProps["value"] | null) => {
- if (value !== null) {
- onChange(id, "prop", value);
+ value={userProp.prop}
+ onItemSelect={(name) => {
+ if (name != null) {
+ const argType = meta[name as keyof typeof meta];
+
+ const defaultValue =
+ argType?.defaultValue ?? argType?.type === "boolean" ? false : "";
+
+ onChangePropName(name, defaultValue);
}
}}
- onSubmit={(value) => {
- onChange(id, "prop", value);
+ onSubmit={(name) => {
+ const argType = meta[name as keyof typeof meta];
+
+ const defaultValue =
+ argType?.defaultValue ?? argType?.type === "boolean" ? false : "";
+
+ onChangePropName(name, defaultValue);
}}
isInvalid={isInvalid}
- isReadonly={required}
+ isReadonly={userProp.required ?? false}
/>
{isInvalid ? (
- <Tooltip content={`Invalid property name: ${prop}`}>
+ <Tooltip content={`Invalid property name: ${userProp.prop}`}>
<ExclamationTriangleIcon width={12} height={12} />
</Tooltip>
) : (
// requires matching complex union
// skip for now and fix types later
<Control
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- type={type as any}
- defaultValue={defaultValue ?? undefined}
- options={options ?? []}
- value={value}
- onChange={(value: UserProp["value"]) => onChange(id, "value", value)}
+ component={component}
+ userProp={userProp}
+ onChangePropValue={onChangePropValue}
/>
)}
- {required !== true && (
+ {userProp.required !== true && (
<Button
ghost
onClick={() => {
- onDelete(id);
+ onDelete(userProp.id);
}}
>
<TrashIcon />
</Button>
)}
- </Grid>
+ </>
);
};
@@ -189,8 +194,13 @@ export const PropsPanel = ({
selectedInstanceData,
publish,
}: PropsPanelProps) => {
- const { userProps, addEmptyProp, handleChangeProp, handleDeleteProp } =
- usePropsLogic({ selectedInstanceData, publish });
+ const {
+ userProps,
+ addEmptyProp,
+ handleChangePropName,
+ handleChangePropValue,
+ handleDeleteProp,
+ } = usePropsLogic({ selectedInstanceData, publish });
const addButton = (
<Button
@@ -203,8 +213,9 @@ export const PropsPanel = ({
<PlusIcon />
</Button>
);
+
return (
- <>
+ <Box>
<Box css={{ p: "$spacing$9" }}>
<ComponentInfo selectedInstanceData={selectedInstanceData} />
</Box>
@@ -213,21 +224,29 @@ export const PropsPanel = ({
rightSlot={addButton}
isOpenDefault
>
- <>
- {userProps.map(({ id, prop, value, required }) => (
+ <Grid
+ gap={1}
+ css={{
+ gridTemplateColumns: "1fr minmax(0, 1fr) auto",
+ alignItems: "center",
+ }}
+ >
+ {userProps.map((userProp) => (
<Property
- key={id}
- id={id}
- prop={prop}
- value={value}
- required={required}
+ key={userProp.id}
+ userProp={userProp}
component={selectedInstanceData.component}
- onChange={handleChangeProp}
+ onChangePropName={(name, defaultValue) =>
+ handleChangePropName(userProp.id, name, defaultValue)
+ }
+ onChangePropValue={(value, asset) =>
+ handleChangePropValue(userProp.id, value, asset)
+ }
onDelete={handleDeleteProp}
/>
))}
- </>
+ </Grid>
</CollapsibleSection>
- </>
+ </Box>
);
};
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 c8528a56ea..e9103b21c5 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
@@ -170,11 +170,11 @@ describe("usePropsLogic", () => {
);
act(() => {
- result.current.handleChangeProp("disabled", "prop", "disabled2");
+ result.current.handleChangePropName("disabled", "disabled2", false);
});
act(() => {
- result.current.handleChangeProp("disabled", "value", false);
+ result.current.handleChangePropValue("disabled", false);
});
expect(result.current.userProps).toMatchInlineSnapshot(`
@@ -262,7 +262,7 @@ describe("usePropsLogic", () => {
);
act(() => {
- result.current.handleChangeProp("2", "prop", "test-example");
+ result.current.handleChangePropName("2", "test-example", "");
});
expect(result.current.userProps).toMatchInlineSnapshot(`
@@ -305,7 +305,7 @@ describe("usePropsLogic", () => {
);
act(() => {
- result.current.handleChangeProp("2", "value", false);
+ result.current.handleChangePropValue("2", false);
});
expect(result.current.userProps).toMatchInlineSnapshot(`
@@ -325,4 +325,78 @@ describe("usePropsLogic", () => {
]
`);
});
+
+ test("should update value and asset", () => {
+ const { result } = renderHook(() =>
+ usePropsLogic({
+ selectedInstanceData: getSelectedInstanceData("Box", [
+ {
+ id: "1",
+ prop: "tag",
+ value: "div",
+ required: true,
+ },
+ ]),
+ publish: jest.fn(),
+ })
+ );
+
+ 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:00"),
+ meta: { width: 101, height: 202 },
+ path: "string",
+ status: "uploaded",
+ });
+ });
+
+ expect(result.current.userProps).toMatchInlineSnapshot(`
+ [
+ {
+ "asset": {
+ "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,
+ "status": "uploaded",
+ },
+ "id": "1",
+ "prop": "tag",
+ "required": true,
+ "value": "img",
+ },
+ ]
+ `);
+
+ act(() => {
+ result.current.handleChangePropValue("1", "img");
+ });
+
+ expect(result.current.userProps).toMatchInlineSnapshot(`
+ [
+ {
+ "id": "1",
+ "prop": "tag",
+ "required": true,
+ "value": "img",
+ },
+ ]
+ `);
+ });
});
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 9fea373267..4e2c76794d 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
@@ -8,9 +8,9 @@ import { componentsMeta } from "@webstudio-is/react-sdk";
import ObjectId from "bson-objectid";
import produce from "immer";
import uniqBy from "lodash/uniqBy";
-import debounce from "lodash/debounce";
-import { useRef, useState } from "react";
+import { useState } from "react";
import type { SelectedInstanceData } from "@webstudio-is/project";
+import type { Asset } from "@webstudio-is/asset-uploader";
declare module "~/shared/pubsub" {
export interface PubsubMap {
@@ -19,10 +19,18 @@ declare module "~/shared/pubsub" {
}
}
-export type handleChangePropType = (
+type UserPropValue = Extract<UserProp, { value: unknown }>["value"];
+
+type HandleChangePropName = (
id: UserProp["id"],
- field: "prop" | "value",
- value: UserProp["prop"] | UserProp["value"]
+ name: string,
+ defaultValue: string | boolean
+) => void;
+
+type HandleChangePropValue = (
+ id: UserProp["id"],
+ value: UserPropValue,
+ asset?: Asset
) => void;
const getRequiredProps = (
@@ -85,13 +93,8 @@ export const usePropsLogic = ({
);
const [userProps, setUserProps] = useState<Array<UserProp>>(initialState);
- const propsToPublishRef = useRef<{
- [id: UserProp["id"]]: true;
- }>({});
- // @todo this may call the last callback after unmount
- // @todo we don't need to debounce change events on select for instance, so debounce is only needed on text inputs
- const updateProps = debounce((updates: UserPropsUpdates["updates"]) => {
+ const updateProps = (updates: UserPropsUpdates["updates"]) => {
publish({
type: "updateProps",
payload: {
@@ -101,10 +104,7 @@ export const usePropsLogic = ({
updates,
},
});
- for (const update of updates) {
- delete propsToPublishRef.current[update.id];
- }
- }, 100);
+ };
const deleteProp = (id: UserProp["id"]) => {
publish({
@@ -116,30 +116,49 @@ export const usePropsLogic = ({
});
};
- const handleChangeProp: handleChangePropType = (id, field, value) => {
- const index = userProps.findIndex((item) => item.id === id);
+ const handleChangePropName: HandleChangePropName = (
+ id,
+ name,
+ defaultValue
+ ) => {
const nextUserProps = produce((draft: Array<UserProp>) => {
+ const index = draft.findIndex((item) => item.id === id);
+
const isPropRequired = draft[index].required;
- switch (field) {
- case "prop":
- if (isPropRequired !== true) {
- // 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;
+
+ if (isPropRequired !== true) {
+ draft[index].prop = name;
+ draft[index].value = defaultValue;
+ }
+ })(userProps);
+
+ // Optimistically update the state (what if publish fails?)
+ setUserProps(nextUserProps);
+
+ const updatedProps = nextUserProps.filter((item) => item.id === id);
+
+ updateProps(updatedProps);
+ };
+
+ const handleChangePropValue: HandleChangePropValue = (id, value, asset) => {
+ 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;
}
})(userProps);
+
+ // Optimistically update the state (what if publish fails?)
setUserProps(nextUserProps);
- propsToPublishRef.current[id] = true;
- const updates = Object.keys(propsToPublishRef.current)
- .map((id) => nextUserProps.find((prop) => prop.id === id))
- // Could be empty if you quickly remove props which have pending changes
- .filter(Boolean) as Array<UserProp>;
- updateProps(updates);
+ const updatedProps = nextUserProps.filter((item) => item.id === id);
+
+ updateProps(updatedProps);
};
const handleDeleteProp = (id: UserProp["id"]) => {
@@ -169,7 +188,8 @@ export const usePropsLogic = ({
return {
addEmptyProp,
userProps,
- handleChangeProp,
+ handleChangePropName,
+ handleChangePropValue,
handleDeleteProp,
};
};
diff --git a/apps/designer/app/designer/features/style-panel/style-panel.tsx b/apps/designer/app/designer/features/style-panel/style-panel.tsx
index d14044a532..98ea93d7e4 100644
--- a/apps/designer/app/designer/features/style-panel/style-panel.tsx
+++ b/apps/designer/app/designer/features/style-panel/style-panel.tsx
@@ -69,7 +69,6 @@ export const StylePanel = ({
<Box
css={{
overflow: "auto",
- position: "relative", // Hack - value picker popover positioning depends on it
}}
>
<StyleSettings
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 56191d76ec..d71b253577 100644
--- a/apps/designer/app/shared/props-utils/update-props.test.ts
+++ b/apps/designer/app/shared/props-utils/update-props.test.ts
@@ -1,3 +1,4 @@
+import { Asset } from "@webstudio-is/asset-uploader";
import {
type AllUserProps,
type UserPropsUpdates,
@@ -80,4 +81,48 @@ describe("Update props", () => {
updateAllUserPropsMutable(propsMap, update);
expect(propsMap).toMatchSnapshot();
});
+
+ test("with changed value to asset type", () => {
+ const propsMap: AllUserProps = {
+ instanceId: {
+ id: "id",
+ instanceId: "instanceId",
+ treeId: "treeId",
+ props: [{ id: "propId", prop: "a", value: "1" }],
+ },
+ };
+ const update: UserPropsUpdates = {
+ propsId: "id",
+ instanceId: "instanceId",
+ treeId: "treeId",
+ updates: [
+ {
+ id: "propId",
+ prop: "a",
+ value: "test",
+ asset: { id: "assetId" } as Asset,
+ },
+ ],
+ };
+ updateAllUserPropsMutable(propsMap, update);
+ expect(propsMap).toMatchInlineSnapshot(`
+ {
+ "instanceId": {
+ "id": "id",
+ "instanceId": "instanceId",
+ "props": [
+ {
+ "asset": {
+ "id": "assetId",
+ },
+ "id": "propId",
+ "prop": "a",
+ "value": "test",
+ },
+ ],
+ "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 4513d7776e..2bc2eb0d8e 100644
--- a/apps/designer/app/shared/props-utils/update-props.ts
+++ b/apps/designer/app/shared/props-utils/update-props.ts
@@ -17,12 +17,28 @@ export const updateAllUserPropsMutable = (
}
const instanceProps = allUserProps[instanceId];
for (const update of updates) {
- const prop = instanceProps.props.find(({ id }) => id === update.id);
- if (prop === undefined) {
+ const propIndex = instanceProps.props.findIndex(
+ ({ id }) => id === update.id
+ );
+
+ if (propIndex === -1) {
instanceProps.props.push(update);
} else {
+ const prop = instanceProps.props[propIndex];
prop.prop = update.prop;
+
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;
}
}
};
diff --git a/apps/designer/package.json b/apps/designer/package.json
index 26c0c75e8c..4669e53cf5 100644
--- a/apps/designer/package.json
+++ b/apps/designer/package.json
@@ -66,6 +66,7 @@
"remix-auth-google": "^1.1.0",
"remix-utils": "^4.1.0",
"slugify": "^1.6.5",
+ "warn-once": "^0.1.1",
"zod-form-data": "^1.2.1"
},
"devDependencies": {
diff --git a/packages/project/package.json b/packages/project/package.json
index db225a512e..1aa2c2067a 100644
--- a/packages/project/package.json
+++ b/packages/project/package.json
@@ -16,14 +16,15 @@
},
"dependencies": {
"@webstudio-is/asset-uploader": "*",
+ "@webstudio-is/css-data": "*",
"@webstudio-is/prisma-client": "*",
"@webstudio-is/react-sdk": "*",
- "@webstudio-is/css-data": "*",
"bson-objectid": "^2.0.2",
"immer": "^9.0.12",
"nanoid": "^3.2.0",
"slugify": "^1.6.5",
"uuid": "^9.0.0",
+ "warn-once": "^0.1.1",
"zod": "^3.19.1"
},
"devDependencies": {
diff --git a/packages/project/src/db/props.ts b/packages/project/src/db/props.ts
index 2e6180eb92..1a68a1c55e 100644
--- a/packages/project/src/db/props.ts
+++ b/packages/project/src/db/props.ts
@@ -1,22 +1,76 @@
+import warnOnce from "warn-once";
import {
type Tree,
type AllUserProps,
- UserProps,
+ type UserProp,
+ // @todo move zod schema into project package
+ UserUserProps,
+ 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";
export const loadByTreeId = async (treeId: Tree["id"]) => {
const instancePropsEntries = await prisma.instanceProps.findMany({
where: { treeId },
});
+ // Fin all assetId in all props
+ const assetIds: string[] = [];
+
+ for (const instanceProps of instancePropsEntries) {
+ const props = JSON.parse(instanceProps.props);
+ const dpProps = UserDbProps.parse(props);
+
+ for (const dbProp of dpProps) {
+ if (dbProp.assetId != null) {
+ assetIds.push(dbProp.assetId);
+ }
+ }
+ }
+ // Load all assets
+ const assets = await prisma.asset.findMany({
+ where: {
+ id: {
+ in: assetIds,
+ },
+ },
+ });
+
+ const assetsMap = new Map(
+ assets.map((asset) => [asset.id, formatAsset(asset)])
+ );
+
return instancePropsEntries.map((instanceProps) => {
const props = JSON.parse(instanceProps.props);
- UserProps.parse(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;
+ }
+
+ 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`);
+ }
+ }
+
return {
...instanceProps,
- props,
+ props: userProps,
};
});
};
@@ -70,8 +124,10 @@ export const patch = async (
await Promise.all(
Object.values(nextProps).map(({ id, instanceId, treeId, props }) => {
- UserProps.parse(props);
- const propsString = JSON.stringify(props);
+ const propsDb = UserUserProps.parse(props);
+
+ const propsString = JSON.stringify(propsDb);
+
return prisma.instanceProps.upsert({
where: { id: id },
create: { id: id, instanceId, treeId, props: propsString },
diff --git a/packages/react-sdk/src/component-utils/image.test.ts b/packages/react-sdk/src/component-utils/image.test.ts
deleted file mode 100644
index 8899ce200b..0000000000
--- a/packages/react-sdk/src/component-utils/image.test.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-import { getImageAttributes } from "./image";
-
-describe("Image optimizations applied", () => {
- test("width is number, create pixel density descriptor 'x'", () => {
- const imgAttr = getImageAttributes({
- optimize: true,
- width: 100,
- src: "https://webstudio.is/logo.webp",
- srcSet: undefined,
- sizes: undefined,
- quality: 100,
- });
-
- expect(imgAttr).toMatchInlineSnapshot(`
- {
- "sizes": undefined,
- "src": "/cdn-cgi/image/width=256,quality=100,format=auto/https://webstudio.is/logo.webp",
- "srcSet": "/cdn-cgi/image/width=128,quality=100,format=auto/https://webstudio.is/logo.webp 1x, /cdn-cgi/image/width=256,quality=100,format=auto/https://webstudio.is/logo.webp 2x",
- }
- `);
- });
-
- test("width is undefined, create 'w' descriptor and sizes prop", () => {
- const imgAttr = getImageAttributes({
- optimize: true,
- width: undefined,
- src: "https://webstudio.is/logo.webp",
- srcSet: undefined,
- sizes: undefined,
- quality: 90,
- });
-
- expect(imgAttr).toMatchInlineSnapshot(`
- {
- "sizes": "(min-width: 1280px) 50vw, 100vw",
- "src": "/cdn-cgi/image/width=3840,quality=90,format=auto/https://webstudio.is/logo.webp",
- "srcSet": "/cdn-cgi/image/width=384,quality=90,format=auto/https://webstudio.is/logo.webp 384w, /cdn-cgi/image/width=640,quality=90,format=auto/https://webstudio.is/logo.webp 640w, /cdn-cgi/image/width=750,quality=90,format=auto/https://webstudio.is/logo.webp 750w, /cdn-cgi/image/width=828,quality=90,format=auto/https://webstudio.is/logo.webp 828w, /cdn-cgi/image/width=1080,quality=90,format=auto/https://webstudio.is/logo.webp 1080w, /cdn-cgi/image/width=1200,quality=90,format=auto/https://webstudio.is/logo.webp 1200w, /cdn-cgi/image/width=1920,quality=90,format=auto/https://webstudio.is/logo.webp 1920w, /cdn-cgi/image/width=2048,quality=90,format=auto/https://webstudio.is/logo.webp 2048w, /cdn-cgi/image/width=3840,quality=90,format=auto/https://webstudio.is/logo.webp 3840w",
- }
- `);
- });
-
- test("width is undefined and size defined, creates 'w' descriptor and use input sizes props", () => {
- const imgAttr = getImageAttributes({
- optimize: true,
- width: undefined,
- src: "https://webstudio.is/logo.webp",
- srcSet: undefined,
- sizes: "100vw",
- quality: 70,
- });
-
- expect(imgAttr).toMatchInlineSnapshot(`
- {
- "sizes": "100vw",
- "src": "/cdn-cgi/image/width=3840,quality=70,format=auto/https://webstudio.is/logo.webp",
- "srcSet": "/cdn-cgi/image/width=640,quality=70,format=auto/https://webstudio.is/logo.webp 640w, /cdn-cgi/image/width=750,quality=70,format=auto/https://webstudio.is/logo.webp 750w, /cdn-cgi/image/width=828,quality=70,format=auto/https://webstudio.is/logo.webp 828w, /cdn-cgi/image/width=1080,quality=70,format=auto/https://webstudio.is/logo.webp 1080w, /cdn-cgi/image/width=1200,quality=70,format=auto/https://webstudio.is/logo.webp 1200w, /cdn-cgi/image/width=1920,quality=70,format=auto/https://webstudio.is/logo.webp 1920w, /cdn-cgi/image/width=2048,quality=70,format=auto/https://webstudio.is/logo.webp 2048w, /cdn-cgi/image/width=3840,quality=70,format=auto/https://webstudio.is/logo.webp 3840w",
- }
- `);
- });
-
- test("custom loader", () => {
- const imgAttr = getImageAttributes({
- optimize: true,
- width: undefined,
- src: "https://webstudio.is/logo.webp",
- srcSet: undefined,
- sizes: "100vw",
- quality: 70,
- loader: ({ width, src, quality }) =>
- `${new URL(src).pathname}?w=${width}&q=${quality}`,
- });
-
- expect(imgAttr).toMatchInlineSnapshot(`
- {
- "sizes": "100vw",
- "src": "/logo.webp?w=3840&q=70",
- "srcSet": "/logo.webp?w=640&q=70 640w, /logo.webp?w=750&q=70 750w, /logo.webp?w=828&q=70 828w, /logo.webp?w=1080&q=70 1080w, /logo.webp?w=1200&q=70 1200w, /logo.webp?w=1920&q=70 1920w, /logo.webp?w=2048&q=70 2048w, /logo.webp?w=3840&q=70 3840w",
- }
- `);
- });
-});
-
-describe("Image optimizations not applied", () => {
- test("optimize is false", () => {
- const imgAttr = getImageAttributes({
- optimize: false,
- width: 100,
- src: "https://webstudio.is/logo.webp",
- srcSet: undefined,
- sizes: undefined,
- quality: 100,
- });
-
- expect(imgAttr).toMatchInlineSnapshot(`
- {
- "sizes": undefined,
- "src": "https://webstudio.is/logo.webp",
- "srcSet": undefined,
- }
- `);
- });
-
- test("srcSet is defined", () => {
- const imgAttr = getImageAttributes({
- optimize: true,
- width: 100,
- src: "https://webstudio.is/logo.webp",
- srcSet: "user-defined-srcset",
- sizes: undefined,
- quality: 100,
- });
-
- expect(imgAttr).toMatchInlineSnapshot(`
- {
- "sizes": undefined,
- "src": "https://webstudio.is/logo.webp",
- "srcSet": "user-defined-srcset",
- }
- `);
- });
-
- test("src is empty", () => {
- const imgAttr = getImageAttributes({
- optimize: true,
- width: 100,
- src: "",
- srcSet: undefined,
- sizes: undefined,
- quality: 100,
- });
-
- expect(imgAttr).toMatchInlineSnapshot(`null`);
- });
-
- test("src is undefined", () => {
- const imgAttr = getImageAttributes({
- optimize: true,
- width: 100,
- src: undefined,
- srcSet: undefined,
- sizes: undefined,
- quality: 100,
- });
-
- expect(imgAttr).toMatchInlineSnapshot(`null`);
- });
-});
diff --git a/packages/react-sdk/src/component-utils/image.ts b/packages/react-sdk/src/component-utils/image.ts
deleted file mode 100644
index b3dd0f6314..0000000000
--- a/packages/react-sdk/src/component-utils/image.ts
+++ /dev/null
@@ -1,268 +0,0 @@
-/**
- * # Responsive Image component helpers.
- *
- * ## Quick summary about img srcset and sizes attributes:
- *
- * There are 2 ways to define what image will be loaded in the img property srcset.
- *
- * 1. via pixel density descriptor 'x', like `srcset="photo-small.jpg 1x, photo-medium.jpg 1.5x, photo-huge.jpg 2x"`
- * src will be selected depending on `device-pixel-ratio`.
- *
- * 2. via viewport width descriptor 'w' and sizes property containing source size descriptors, like
- * `srcset="photo-small.jpg 320w, photo-medium.jpg 640w, photo-huge.jpg 1280w"`
- * `sizes="(max-width: 600px) 400px, (max-width: 1200px) 70vw, 50vw"`
- *
- * The browser finds the first matching media query from source size descriptors,
- * then use source size value to generate internally srcset
- * with pixel density descriptors dividing width descriptor value by source size value.
- *
- * Using the example above for viewport width 800px.
- * The first matching media query is (max-width: 1200px)
- * source size value is 70vw equal to 800px * 0,7 = 560px
- *
- * browser internal srcset will be (we divide `w` descriptor by source size value):
- * photo-small.jpg 320/560x, photo-medium.jpg 640/560x, photo-huge.jpg 1280/560x =>
- * photo-small.jpg 0.57x, photo-medium.jpg 1.14x, photo-huge.jpg 2.28x
- *
- * Finally same rules as for pixel density descriptor 'x' are applied.
- *
- * ## Algorithm (without optimizations):
- *
- * We have a predefined array of all supported image sizes allSizes, this is the real width of an image in pixels.
- * This is good for caching, as we can cache image with specific width and then use it for different devices.
- *
- * > allSizes array is a tradeoff between cache and the best possible image size you deliver to the user.
- * > If allSizes.length is too small, you will deliver too big images to the user,
- * > if allSizes.length is too big, you will have many caches misses.
- *
- * If img has a defined width property.
- * 1. find the first value from allSizes which is greater or equal to the width property
- * 2. use found value to generate srcset with pixel density descriptor 'x'
- *
- *
- * If img has no defined width property.
- * 1. Generate srcset = allSizes.map((w) => `${getImageSrcAtWidth(w)} ${w}w`)
- * 2. Use sizes property, or if it is not defined use opinionated DEFAULT_SIZES = "(min-width: 1280px) 50vw, 100vw";
- *
- * Optimizations applied now:
- *
- * - If the sizes property is defined, we can exclude from `srcsets` all images
- * which are smaller than the `smallestRatio * smallesDeviceSize`
- *
- * Future (not implemented) optimizations and improvements:
- *
- * - Knowing image size on different viewport widths we can provide nondefault sizes property
- * - Knowledge of Image aspect-ratio would allow cropping images serverside.
- * - Early hints for high priority images https://blog.cloudflare.com/early-hints/
- * - Slow networks optimizations
- * - 404 etc processing with CSS - https://bitsofco.de/styling-broken-images/ (has some opinionated issues) or js solution with custom user fallback.
- *
- * # Attributions
- *
- * The MIT License (MIT)
- *
- * applies to:
- *
- * - https://github.com/vercel/next.js, Copyright (c) 2022 Vercel, Inc.
- *
- * The MIT License (MIT)
- *
- * Copyright (c) 2022 Vercel, Inc.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
- * and associated documentation files (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge, publish, distribute,
- * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
- * is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in all copies
- * or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
- * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- **/
-
-import warnOnce from "warn-once";
-
-export type ImageLoader = (props: {
- width: number;
- quality: number;
- src: string;
-}) => string;
-
-/**
- * max(...imageSizes) must be less then min(...deviceSizes)
- **/
-const imageSizes = [16, 32, 48, 64, 96, 128, 256, 384];
-const deviceSizes = [640, 750, 828, 1080, 1200, 1920, 2048, 3840];
-
-export const allSizes = [...imageSizes, ...deviceSizes];
-
-/**
- * https://github.com/vercel/next.js/blob/canary/packages/next/client/image.tsx
- **/
-const getWidths = (
- width: number | undefined,
- sizes: string | undefined
-): { widths: number[]; kind: "w" | "x" } => {
- if (sizes) {
- // Find all the "vw" percent sizes used in the sizes prop
- const viewportWidthRe = /(^|\s)(1?\d?\d)vw/g;
- const percentSizes = [];
- for (let match; (match = viewportWidthRe.exec(sizes)); match) {
- percentSizes.push(parseInt(match[2], 10));
- }
-
- if (percentSizes.length) {
- // we can exclude from srcSets all images which are smaller than the smallestRatio * smallesDeviceSize
- const smallestRatio = Math.min(...percentSizes) * 0.01;
- return {
- widths: allSizes.filter((s) => s >= deviceSizes[0] * smallestRatio),
- kind: "w",
- };
- }
- return { widths: allSizes, kind: "w" };
- }
-
- if (width == null) {
- return { widths: deviceSizes, kind: "w" };
- }
-
- const widths = [
- ...new Set(
- [width, width * 2].map(
- (w) => allSizes.find((p) => p >= w) || allSizes[allSizes.length - 1]
- )
- ),
- ];
- return { widths, kind: "x" };
-};
-
-const generateImgAttrs = ({
- src,
- width,
- quality,
- sizes,
- loader,
-}: {
- src: string;
- quality: number;
- width: number | undefined;
- sizes: string | undefined;
- loader: ImageLoader;
-}): {
- src: string;
- srcSet: string | undefined;
- sizes: string | undefined;
-} => {
- const { widths, kind } = getWidths(width, sizes);
-
- return {
- sizes: !sizes && kind === "w" ? "100vw" : sizes,
- srcSet: widths
- .map(
- (w, i) =>
- `${loader({ src, quality, width: w })} ${
- kind === "w" ? w : i + 1
- }${kind}`
- )
- .join(", "),
-
- // Must be last, to prevent Safari to load images twice
- src: loader({
- src,
- quality,
- width: widths[widths.length - 1],
- }),
- };
-};
-
-/**
- * Default image loader in case of no loader provided
- * https://developers.cloudflare.com/images/image-resizing/url-format/
- **/
-const cloudflareImageLoader: ImageLoader = ({ width, src, quality }) => {
- if (process.env.NODE_ENV !== "production") {
- warnOnce(
- !allSizes.includes(width),
- "Width must be only from allowed values"
- );
- }
-
- const options = `width=${width},quality=${quality},format=auto`;
- // Cloudflare docs say that we don't need to urlencode the path params
- const pathname = `/cdn-cgi/image/${options}/${src}`;
- return pathname;
-};
-
-const getInt = (value: unknown): number | undefined => {
- if (typeof value === "number") {
- return Math.round(value);
- }
-
- if (typeof value === "string") {
- const vNum = Number.parseFloat(value);
-
- if (!Number.isNaN(vNum)) {
- return Math.round(vNum);
- }
- }
-
- return undefined;
-};
-
-/**
- * DEFAULT_SIZES Just an assumption that most images (except hero and icons) are 100% wide on mobile and 50% on desktop.
- * For icons width are usually set explicitly so DEFAULT_SIZES is not applied.
- * For hero images, we can allow in UI to select sizes=100vw explicitly.
- * Anyway, the best would be to calculate this based on canvas data from different breakpoints.
- * See ../component-utils/image for detailed description
- **/
-const DEFAULT_SIZES = "(min-width: 1280px) 50vw, 100vw";
-
-const DEFAULT_QUALITY = 80;
-
-export const getImageAttributes = (props: {
- src: string | undefined;
- srcSet: string | undefined;
- sizes: string | undefined;
- width: string | number | undefined;
- quality: number | undefined;
- loader?: ImageLoader;
- optimize: boolean;
-}): {
- src: string;
- srcSet: string | undefined;
- sizes: string | undefined;
-} | null => {
- const width = getInt(props.width);
- const quality = Math.max(
- Math.min(getInt(props.quality) ?? DEFAULT_QUALITY, 100),
- 0
- );
-
- if (props.src != null && props.src != "") {
- if (props.srcSet == null && props.optimize) {
- const sizes =
- props.sizes ?? (props.width == null ? DEFAULT_SIZES : undefined);
-
- const loader = props.loader ?? cloudflareImageLoader;
-
- return generateImgAttrs({
- src: props.src,
- width,
- quality,
- sizes,
- loader,
- });
- }
-
- return { src: props.src, srcSet: props.srcSet, sizes: props.sizes };
- }
-
- return null;
-};
diff --git a/packages/react-sdk/src/components/image-dev.stories.tsx b/packages/react-sdk/src/components/image-dev.stories.tsx
deleted file mode 100644
index 0aa54a543e..0000000000
--- a/packages/react-sdk/src/components/image-dev.stories.tsx
+++ /dev/null
@@ -1,169 +0,0 @@
-// Story for image development, see https://github.com/webstudio-is/webstudio-designer/issues/387
-
-import React, { type ComponentProps, type HTMLAttributes } from "react";
-import type { ComponentMeta, ComponentStory } from "@storybook/react";
-import warnOnce from "warn-once";
-import { Image as ImagePrimitive } from "./image";
-import imageMeta from "./image.ws";
-import { type ImageLoader } from "../component-utils/image";
-
-// to not allow include local assets everywhere, just enable it for this file
-// eslint-disable-next-line @typescript-eslint/ban-ts-comment
-// @ts-ignore
-import localLogoImage from "../../storybook-assets/logo.webp";
-
-export default {
- title: "Components/ImageDev",
-} as ComponentMeta<typeof ImagePrimitive>;
-
-type ImageProps = ComponentProps<typeof ImagePrimitive>;
-
-/**
- * In case you need to test img with real cloudflare trasforms
- * set USE_CLOUDFLARE_IMAGE_TRANSFORM = true
- **/
-const USE_CLOUDFLARE_IMAGE_TRANSFORM = false;
-
-// For cloudflare image transform testing, logo should be the most consistent image on the site
-const REMOTE_SELF_DOMAIN_IMAGE = "https://webstudio.is/logo.webp";
-
-const imageSrc = USE_CLOUDFLARE_IMAGE_TRANSFORM
- ? REMOTE_SELF_DOMAIN_IMAGE
- : localLogoImage;
-
-// In case of REMOTE_DEBUG
-const cloudflareImageLoader: ImageLoader = ({ width, src, quality }) => {
- // No image transformation in development
- const resizeOrigin = "https://webstudio.is";
-
- const pathParams = [
- `width=${width}`,
- quality != null && `quality=${quality}`,
- "format=auto",
- ].filter(Boolean);
-
- const pathname = `/cdn-cgi/image/${pathParams.join(",")}/${src}`;
-
- const url = new URL(pathname, resizeOrigin);
- return url.href;
-};
-
-const localImageLoader: ImageLoader = ({ width, src, quality }) => {
- // Just emulate like we really resize the image
- const params = new URLSearchParams();
- params.set("width", `${width}`);
- params.set("quality", `${quality}`);
- return `${src}?${params.toString()}`;
-};
-
-const imageLoader = USE_CLOUDFLARE_IMAGE_TRANSFORM
- ? cloudflareImageLoader
- : localImageLoader;
-
-const ImageBase: ComponentStory<
- React.ForwardRefExoticComponent<
- ImageProps & { style?: HTMLAttributes<"img">["style"] }
- >
-> = (args) => {
- warnOnce(
- !(
- imageMeta.defaultStyle?.maxWidth?.value === 100 &&
- imageMeta.defaultStyle?.maxWidth?.unit === "%"
- ),
- "We expect that the image default style has maxWidth: 100%"
- );
-
- warnOnce(
- imageMeta.defaultStyle?.display?.value !== "block",
- "We expect that the image default style has display: block"
- );
-
- const style = {
- maxWidth: "100%",
- display: "block",
- ...args.style,
- };
-
- return (
- <ImagePrimitive
- {...args}
- optimize={true}
- loader={imageLoader}
- style={style}
- />
- );
-};
-
-/**
- * Load images depending on image width and device per pixel ratio.
- **/
-export const FixedWidthImage: ComponentStory<React.FunctionComponent> = () => (
- <ImageBase src={imageSrc} width="300" height="400" />
-);
-
-/**
- * Preserve ratio using object-fit: cover. Load images depending on image width and device per pixel ratio.
- **/
-export const FixedWidthImageCover: ComponentStory<
- React.FunctionComponent
-> = () => (
- <ImageBase
- src={imageSrc}
- width="300"
- height="400"
- style={{ objectFit: "cover" }}
- />
-);
-
-/**
- * Load images depending on the viewport width.
- **/
-export const UnknownWidthImage: ComponentStory<
- React.FunctionComponent
-> = () => <ImageBase src={imageSrc} />;
-
-/**
- * Fit width of the parent container, has own aspect-ratio and object-fit=cover.
- * Load images depending on the viewport width.
- **/
-export const AspectRatioImage: ComponentStory<React.FunctionComponent> = () => (
- <div style={{ width: "50%" }}>
- <ImageBase
- src={imageSrc}
- style={{ aspectRatio: "2/1", objectFit: "cover", width: "100%" }}
- />
- </div>
-);
-
-/**
- * Fill width and height of the relative parent container, object-fit=cover. Load images depending on the viewport width.
- **/
-export const FillParentImage: ComponentStory<React.FunctionComponent> = () => (
- <div style={{ width: "50%", aspectRatio: "2/1", position: "relative" }}>
- <ImageBase
- src={imageSrc}
- style={{
- objectFit: "cover",
- position: "absolute",
- width: "100%",
- height: "100%",
- }}
- />
- </div>
-);
-
-/**
- * "sizes" attribute explicitly equal to 100vw allowing to skip the default behavior.
- * See DEFAULT_SIZES in the Image component. Load images depending on the viewport width.
- **/
-export const HeroImage: ComponentStory<React.FunctionComponent> = () => (
- <ImageBase
- src={imageSrc}
- sizes="100vw"
- style={{
- aspectRatio: "3/1",
- objectFit: "cover",
- width: "100%",
- }}
- />
-);
diff --git a/packages/react-sdk/src/components/image.tsx b/packages/react-sdk/src/components/image.tsx
index f473c9a7a1..802853fed7 100644
--- a/packages/react-sdk/src/components/image.tsx
+++ b/packages/react-sdk/src/components/image.tsx
@@ -1,31 +1,20 @@
import { forwardRef, type ElementRef, type ComponentProps } from "react";
-import { getImageAttributes, type ImageLoader } from "../component-utils/image";
const defaultTag = "img";
-type ImageProps = ComponentProps<typeof defaultTag> & {
- quality?: number;
- loader?: ImageLoader;
- optimize?: boolean;
-};
+// quality and optimize can be overwritten and used by asset transform
+// Or we need and additional way to pass them upper level
+type ImageProps = ComponentProps<typeof defaultTag>;
export const Image = forwardRef<ElementRef<typeof defaultTag>, ImageProps>(
- ({ quality, loader, optimize, ...imageProps }, ref) => {
- // Temporary set to false, to support previous image behaviour
- const DEFAULT_OPTIMIZE = false;
-
- const imageAttributes = getImageAttributes({
- src: imageProps.src,
- srcSet: imageProps.srcSet,
- sizes: imageProps.sizes,
- width: imageProps.width,
- quality,
- loader,
- optimize: optimize ?? DEFAULT_OPTIMIZE,
- }) ?? { src: imagePlaceholderSvg };
-
+ (imageProps, ref) => {
return (
- <img {...imageProps} {...imageAttributes} decoding="async" ref={ref} />
+ <img
+ {...imageProps}
+ src={imageProps.src || imagePlaceholderSvg}
+ decoding="async"
+ ref={ref}
+ />
);
}
);
diff --git a/packages/react-sdk/src/components/meta.ts b/packages/react-sdk/src/components/meta.ts
index d360b0227b..3b1aeeae34 100644
--- a/packages/react-sdk/src/components/meta.ts
+++ b/packages/react-sdk/src/components/meta.ts
@@ -32,14 +32,32 @@ const meta = {
Image,
} as const;
-type MetaProps = Record<
- string,
- {
- type: string;
- required: boolean;
- defaultValue: null | string;
- options?: string[];
- }
->;
+type MetaProp =
+ | {
+ type: "text";
+ required: boolean;
+ defaultValue: null | string;
+ }
+ | {
+ type: "boolean";
+ required: boolean;
+ defaultValue: null | boolean;
+ }
+ | {
+ type:
+ | "radio"
+ | "inline-radio"
+ | "check"
+ | "inline-check"
+ | "multi-select"
+ | "select";
+ required: boolean;
+ defaultValue: null | string;
+ options: string[];
+ };
-export const componentsMeta: Record<keyof typeof meta, MetaProps> = meta;
+type MetaProps = Record<string, MetaProp>;
+
+// Probably better instead of JSON to generate ts with `as const`
+export const componentsMeta: Record<keyof typeof meta, MetaProps> =
+ meta as Record<keyof typeof meta, MetaProps>;
diff --git a/packages/react-sdk/src/user-props/schema.ts b/packages/react-sdk/src/user-props/schema.ts
index 8e3b66cf64..1fb83cf08e 100644
--- a/packages/react-sdk/src/user-props/schema.ts
+++ b/packages/react-sdk/src/user-props/schema.ts
@@ -1,12 +1,43 @@
import { z } from "zod";
+import type { Asset } from "@webstudio-is/asset-uploader";
-export const UserProp = z.object({
+const UserPropDb = z.object({
id: z.string(),
prop: z.string(),
value: z.union([z.string(), z.boolean()]),
+ assetId: z.optional(z.string()),
required: z.optional(z.boolean()),
});
-export type UserProp = z.infer<typeof UserProp>;
+export const UserDbProps = z.array(UserPropDb);
-export const UserProps = z.array(UserProp);
+const UserUserProp = z
+ .object({
+ id: z.string(),
+ prop: z.string(),
+ value: z.union([z.string(), z.boolean()]),
+ // We are not interested in Props data does any other props on asset exists
+ asset: z.optional(z.object({ id: z.string() })),
+ required: z.optional(z.boolean()),
+ })
+ .transform(({ id, prop, value, asset, required }) => {
+ // Check with infer that we are transforming to UserPropDb
+ const res: z.infer<typeof UserPropDb> = {
+ id,
+ prop,
+ value,
+ assetId: asset?.id,
+ required,
+ };
+ return res;
+ });
+
+export const UserUserProps = z.array(UserUserProp);
+
+export type UserProp = {
+ id: string;
+ prop: string;
+ value: string | boolean;
+ asset?: Asset;
+ required?: boolean | undefined;
+};
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 1a0389c5a5..6f9e33aca7 100644
--- a/packages/react-sdk/src/user-props/use-user-props.ts
+++ b/packages/react-sdk/src/user-props/use-user-props.ts
@@ -11,6 +11,7 @@ type UserProps = { [prop: UserProp["prop"]]: UserProp["value"] };
*/
export const useUserProps = (instanceId: Instance["id"]) => {
const [allUserProps] = useAllUserProps();
+
const propsData = allUserProps[instanceId];
const initialUserProps = useMemo(() => {
if (propsData === undefined) return {};