Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: add json prop control (#2608)

Bogdan Chadkinc776356b5332
diff --git a/apps/builder/app/builder/features/settings-panel/controls/combined.tsx b/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
index f0b39c888a..89e517a015 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
@@ -9,6 +9,7 @@ import { BooleanControl } from "./boolean";
import { FileControl } from "./file";
import { UrlControl } from "./url";
import type { ControlProps } from "../shared";
+import { JsonControl } from "./json";
export const renderControl = ({
meta,
@@ -147,6 +148,21 @@ export const renderControl = ({
);
}
+ if (prop.type === "json") {
+ return (
+ <JsonControl
+ meta={{
+ ...meta,
+ defaultValue: undefined,
+ control: "json",
+ type: "json",
+ }}
+ prop={prop}
+ {...rest}
+ />
+ );
+ }
+
if (prop.type === "asset") {
return (
<FileControl
@@ -183,12 +199,6 @@ export const renderControl = ({
);
}
- if (prop.type === "json") {
- throw new Error(
- `Cannot render a fallback control for prop "${rest.propName}" with type json, because we don't know the available options for a multiselect control`
- );
- }
-
prop satisfies never;
}
diff --git a/apps/builder/app/builder/features/settings-panel/controls/json.tsx b/apps/builder/app/builder/features/settings-panel/controls/json.tsx
new file mode 100644
index 0000000000..0c4d7ff71d
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/controls/json.tsx
@@ -0,0 +1,61 @@
+import { theme, Box } from "@webstudio-is/design-system";
+import {
+ type ControlProps,
+ getLabel,
+ useLocalValue,
+ VerticalLayout,
+ Label,
+} from "../shared";
+import { VariablesButton } from "../variables";
+import { CodeEditor } from "../code-editor";
+
+const emptyVariables = new Map();
+
+export const JsonControl = ({
+ meta,
+ prop,
+ propName,
+ deletable,
+ onChange,
+ onDelete,
+}: ControlProps<"json", "json">) => {
+ const valueString = JSON.stringify(prop?.value ?? "");
+ const localValue = useLocalValue(valueString, (value) => {
+ try {
+ // wrap into parens to treat object expression as value instead of block
+ const parsedValue = eval(`(${value})`);
+ onChange({ type: "json", value: parsedValue });
+ } catch {
+ // empty block
+ }
+ });
+ const label = getLabel(meta, propName);
+
+ return (
+ <VerticalLayout
+ label={
+ <Box css={{ position: "relative" }}>
+ <Label description={meta.description}>{label}</Label>
+ <VariablesButton
+ propId={prop?.id}
+ propName={propName}
+ propMeta={meta}
+ />
+ </Box>
+ }
+ deletable={deletable}
+ onDelete={onDelete}
+ >
+ <Box css={{ py: theme.spacing[2] }}>
+ <CodeEditor
+ // reset editor every time value is changed
+ key={localValue.value}
+ variables={emptyVariables}
+ defaultValue={localValue.value}
+ onChange={localValue.set}
+ onBlur={localValue.save}
+ />
+ </Box>
+ </VerticalLayout>
+ );
+};
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx
index f15e899801..aacd8635df 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx
+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { Fragment, useState } from "react";
import { useStore } from "@nanostores/react";
import type { Instance } from "@webstudio-is/sdk";
import {
@@ -98,46 +98,52 @@ const renderProperty = (
}: PropsSectionProps,
{ prop, propName, meta }: PropAndMeta,
deletable?: boolean
-) =>
- renderControl({
- key: propName,
- instanceId,
- meta,
- prop,
- propName,
- deletable: deletable ?? false,
- onDelete: () => {
- if (prop) {
- logic.handleDelete(prop);
- }
- },
- onChange: (propValue, asset) => {
- logic.handleChange({ prop, propName }, propValue);
+) => (
+ // fix the issue with changing type while binding expression
+ // old prop value is getting preserved in useLocalValue and saved into variable
+ // to reproduce try to edit body id prop and then bind json variable to it
+ <Fragment key={prop?.type ?? ""}>
+ {renderControl({
+ key: propName,
+ instanceId,
+ meta,
+ prop,
+ propName,
+ deletable: deletable ?? false,
+ onDelete: () => {
+ if (prop) {
+ logic.handleDelete(prop);
+ }
+ },
+ onChange: (propValue, asset) => {
+ logic.handleChange({ prop, propName }, propValue);
- // @todo: better way to do this?
- if (
- component === "Image" &&
- propName === "src" &&
- asset &&
- "width" in asset.meta &&
- "height" in asset.meta
- ) {
- logic.handleChangeByPropName("width", {
- value: asset.meta.width,
- type: "number",
- });
- logic.handleChangeByPropName("height", {
- value: asset.meta.height,
- type: "number",
- });
+ // @todo: better way to do this?
+ if (
+ component === "Image" &&
+ propName === "src" &&
+ asset &&
+ "width" in asset.meta &&
+ "height" in asset.meta
+ ) {
+ logic.handleChangeByPropName("width", {
+ value: asset.meta.width,
+ type: "number",
+ });
+ logic.handleChangeByPropName("height", {
+ value: asset.meta.height,
+ type: "number",
+ });
- setCssProperty("height")({
- type: "keyword",
- value: "fit-content",
- });
- }
- },
- });
+ setCssProperty("height")({
+ type: "keyword",
+ value: "fit-content",
+ });
+ }
+ },
+ })}
+ </Fragment>
+);
const AddPropertyForm = ({
availableProps,
@@ -234,11 +240,12 @@ export const PropsSectionContainer = ({
dataSourceVariablesStore.set(dataSourceVariables);
}
} else {
+ const { propsByInstanceId } = propsIndexStore.get();
serverSyncStore.createTransaction([propsStore], (props) => {
- const istanceProps = propsByInstanceId.get(instance.id) ?? [];
+ const instanceProps = propsByInstanceId.get(instance.id) ?? [];
// Fixing a bug that caused some props to be duplicated on unmount by removing duplicates.
// see for details https://github.com/webstudio-is/webstudio/pull/2170
- const duplicateProps = istanceProps
+ const duplicateProps = instanceProps
.filter((prop) => prop.id !== update.id)
.filter((prop) => prop.name === update.name);
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts
index e246aa3943..ef41db1dbd 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts
+++ b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts
@@ -137,11 +137,8 @@ const getPropTypeAndValue = (value: unknown) => {
if (typeof value === "string") {
return { type: "string", value } as const;
}
- if (Array.isArray(value)) {
- return { type: "string[]", value } as const;
- }
- // fallback to empty string to not break UI
- return { type: "string", value: "" } as const;
+ // fallback to json
+ return { type: "json", value } as const;
};
/** usePropsLogic expects that key={instanceId} is used on the ancestor component */
@@ -160,7 +157,7 @@ export const usePropsLogic = ({
throw new Error(`Could not get meta for component "${instance.component}"`);
}
- const savedProps = props.flatMap((prop) => {
+ const savedProps = props.flatMap((prop): Prop[] => {
if (prop.type === "expression") {
// convert expression prop to value prop
const dataSourceValue = computeExpression(prop.value, dataSourcesLogic);
@@ -172,7 +169,7 @@ export const usePropsLogic = ({
required: prop.required,
// infer type from value
...getPropTypeAndValue(dataSourceValue),
- } satisfies Prop,
+ },
];
}
return [prop];
diff --git a/apps/builder/app/builder/features/settings-panel/shared.tsx b/apps/builder/app/builder/features/settings-panel/shared.tsx
index d309ff90e5..451479dc81 100644
--- a/apps/builder/app/builder/features/settings-panel/shared.tsx
+++ b/apps/builder/app/builder/features/settings-panel/shared.tsx
@@ -23,11 +23,16 @@ import {
} from "@webstudio-is/design-system";
import { humanizeString } from "~/shared/string-utils";
-export type PropValue = Prop extends infer T
- ? T extends { value: unknown; type: unknown }
- ? { value: T["value"]; type: T["type"] }
- : never
- : never;
+export type PropValue =
+ | { type: "number"; value: number }
+ | { type: "string"; value: string }
+ | { type: "boolean"; value: boolean }
+ | { type: "json"; value: unknown }
+ | { type: "string[]"; value: string[] }
+ | { type: "expression"; value: string }
+ | { type: "asset"; value: Asset["id"] }
+ | { type: "page"; value: Extract<Prop, { type: "page" }>["value"] }
+ | { type: "action"; value: Extract<Prop, { type: "action" }>["value"] };
// Weird code is to make type distributive
// https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
diff --git a/apps/builder/app/builder/features/settings-panel/variables.tsx b/apps/builder/app/builder/features/settings-panel/variables.tsx
index bff7953548..3d7f6dad47 100644
--- a/apps/builder/app/builder/features/settings-panel/variables.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variables.tsx
@@ -45,6 +45,7 @@ import {
import { serverSyncStore } from "~/shared/sync";
import { CodeEditor } from "./code-editor";
import type { PropValue } from "./shared";
+import { getStartingValue } from "./props-section/use-props-logic";
type VariableDataSource = Extract<DataSource, { type: "variable" }>;
@@ -379,9 +380,9 @@ const setPropValue = ({
}
const [instanceId] = instanceSelector;
- // create new prop or update existing one
serverSyncStore.createTransaction([propsStore], (props) => {
let prop = propId === undefined ? undefined : props.get(propId);
+ // create new prop or update existing one
if (prop === undefined) {
prop = { id: nanoid(), instanceId, name: propName, ...propValue };
} else {
@@ -550,14 +551,19 @@ export const VariablesPanel = ({
const removeExpression = () => {
// reset prop with initial value from meta
- setPropValue({
- propId,
- propName,
- propValue: {
- type: propMeta.type,
- value: propMeta.defaultValue,
- } as PropValue,
- });
+ const propValue = getStartingValue(propMeta);
+ if (propValue) {
+ setPropValue({
+ propId,
+ propName,
+ propValue,
+ });
+ } else if (propId !== undefined) {
+ // delete prop when not possible to infer default value from meta
+ serverSyncStore.createTransaction([propsStore], (props) => {
+ props.delete(propId);
+ });
+ }
};
return (
diff --git a/packages/react-sdk/src/prop-meta.ts b/packages/react-sdk/src/prop-meta.ts
index fa1f4363bb..72bec1e607 100644
--- a/packages/react-sdk/src/prop-meta.ts
+++ b/packages/react-sdk/src/prop-meta.ts
@@ -132,16 +132,11 @@ const Url = z.object({
defaultValue: z.string().optional(),
});
-// we neither generate object nor support it in props panel, listed here for completeness
-// can't use name "Object" for the variable because it causes bugs when Object.assign() is used in compiled output
-const ObjectType = z.object({
+const Json = z.object({
...common,
- control: z.literal("object"),
-
- // @todo not sure what type should be here
- // (we don't support Object yet, added for completeness)
- type: z.literal("Record<string, string>"),
- defaultValue: z.record(z.string()).optional(),
+ control: z.literal("json"),
+ type: z.literal("json"),
+ defaultValue: z.unknown().optional(),
});
// we neither generate date nor support it in props panel, listed here for completeness
@@ -177,7 +172,7 @@ export const PropMeta = z.union([
InlineCheck,
File,
Url,
- ObjectType,
+ Json,
Date,
Action,
]);