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: switch props to binding popover (#2727)

Bogdan Chadkine810ea9b8999
diff --git a/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx b/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx
index 46c7c153ac..d26af2278f 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx
@@ -1,22 +1,29 @@
+import { useStore } from "@nanostores/react";
import { Box, Grid, Switch, theme, useId } from "@webstudio-is/design-system";
+import { BindingPopover } from "~/builder/shared/binding-popover";
import {
type ControlProps,
getLabel,
Label,
RemovePropButton,
+ $selectedInstanceScope,
+ updateExpressionValue,
} from "../shared";
-import { VariablesButton } from "../variables";
export const BooleanControl = ({
meta,
prop,
propName,
+ computedValue,
deletable,
readOnly,
onChange,
onDelete,
-}: ControlProps<"boolean", "boolean">) => {
+}: ControlProps<"boolean", "boolean" | "expression">) => {
const id = useId();
+ const { scope, aliases } = useStore($selectedInstanceScope);
+ const expression =
+ prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
return (
<Grid
@@ -30,22 +37,34 @@ export const BooleanControl = ({
align="center"
gap="2"
>
+ <Label htmlFor={id} description={meta.description} readOnly={readOnly}>
+ {getLabel(meta, propName)}
+ </Label>
<Box css={{ position: "relative" }}>
- <Label htmlFor={id} description={meta.description} readOnly={readOnly}>
- {getLabel(meta, propName)}
- </Label>
- <VariablesButton
- propId={prop?.id}
- propName={propName}
- propMeta={meta}
+ <Switch
+ id={id}
+ disabled={readOnly}
+ checked={Boolean(computedValue ?? false)}
+ onCheckedChange={(value) => {
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, value);
+ } else {
+ onChange({ type: "boolean", value });
+ }
+ }}
+ />
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ value={expression}
+ onChange={(newExpression) =>
+ onChange({ type: "expression", value: newExpression })
+ }
+ onRemove={(evaluatedValue) =>
+ onChange({ type: "boolean", value: Boolean(evaluatedValue) })
+ }
/>
</Box>
- <Switch
- id={id}
- disabled={readOnly}
- checked={prop?.value ?? false}
- onCheckedChange={(value) => onChange({ type: "boolean", value })}
- />
{deletable && <RemovePropButton onClick={onDelete} />}
</Grid>
);
diff --git a/apps/builder/app/builder/features/settings-panel/controls/check.tsx b/apps/builder/app/builder/features/settings-panel/controls/check.tsx
index c329352c2c..85a523dd13 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/check.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/check.tsx
@@ -1,3 +1,4 @@
+import { useStore } from "@nanostores/react";
import {
Box,
Checkbox,
@@ -6,8 +7,15 @@ import {
theme,
} from "@webstudio-is/design-system";
import { humanizeString } from "~/shared/string-utils";
-import { type ControlProps, getLabel, VerticalLayout, Label } from "../shared";
-import { VariablesButton } from "../variables";
+import { BindingPopover } from "~/builder/shared/binding-popover";
+import {
+ type ControlProps,
+ getLabel,
+ VerticalLayout,
+ Label,
+ $selectedInstanceScope,
+ updateExpressionValue,
+} from "../shared";
const add = (array: string[], item: string) => {
if (array.includes(item)) {
@@ -27,59 +35,78 @@ export const CheckControl = ({
meta,
prop,
propName,
+ computedValue,
deletable,
readOnly,
onChange,
onDelete,
-}: ControlProps<"check" | "inline-check" | "multi-select", "string[]">) => {
- const value = prop?.value ?? [];
+}: ControlProps<
+ "check" | "inline-check" | "multi-select",
+ "string[]" | "expression"
+>) => {
+ const value = Array.isArray(computedValue)
+ ? computedValue.map((item) => String(item))
+ : [];
// making sure that the current value is in the list of options
- const options = value.reduce(
- (result, item) => (result.includes(item) ? result : [item, ...result]),
- meta.options
- );
+ const options = Array.from(new Set([...meta.options, ...value]));
const id = useId();
+ const { scope, aliases } = useStore($selectedInstanceScope);
+ const expression =
+ prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
return (
<VerticalLayout
label={
- <Box css={{ position: "relative" }}>
- <Label
- htmlFor={`${id}:${options[0]}`}
- description={meta.description}
- readOnly={readOnly}
- >
- {getLabel(meta, propName)}
- </Label>
- <VariablesButton
- propId={prop?.id}
- propName={propName}
- propMeta={meta}
- />
- </Box>
+ <Label
+ htmlFor={`${id}:${options[0]}`}
+ description={meta.description}
+ readOnly={readOnly}
+ >
+ {getLabel(meta, propName)}
+ </Label>
}
deletable={deletable}
onDelete={onDelete}
>
- <Box css={{ paddingTop: theme.spacing[2] }}>
+ <Box css={{ position: "relative", paddingTop: theme.spacing[2] }}>
{options.map((option) => (
<CheckboxAndLabel key={option}>
<Checkbox
disabled={readOnly}
checked={value.includes(option)}
onCheckedChange={(checked) => {
- onChange({
- type: "string[]",
- value: checked ? add(value, option) : remove(value, option),
- });
+ const newValue = checked
+ ? add(value, option)
+ : remove(value, option);
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, newValue);
+ } else {
+ onChange({ type: "string[]", value: newValue });
+ }
}}
id={`${id}:${option}`}
/>
<Label htmlFor={`${id}:${option}`}>{humanizeString(option)}</Label>
</CheckboxAndLabel>
))}
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ value={expression}
+ onChange={(newExpression) =>
+ onChange({ type: "expression", value: newExpression })
+ }
+ onRemove={(evaluatedValue) =>
+ onChange({
+ type: "string[]",
+ value: Array.isArray(evaluatedValue)
+ ? evaluatedValue.map((item) => String(item))
+ : [],
+ })
+ }
+ />
</Box>
</VerticalLayout>
);
diff --git a/apps/builder/app/builder/features/settings-panel/controls/code.tsx b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
index 6716f54185..ad25477d11 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/code.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
@@ -1,3 +1,4 @@
+import { useStore } from "@nanostores/react";
import { Box, theme } from "@webstudio-is/design-system";
import {
useLocalValue,
@@ -5,58 +6,73 @@ import {
getLabel,
VerticalLayout,
Label,
+ updateExpressionValue,
+ $selectedInstanceScope,
} from "../shared";
-import { VariablesButton } from "../variables";
import { HtmlEditor } from "~/builder/shared/html-editor";
+import { BindingPopover } from "~/builder/shared/binding-popover";
export const CodeControl = ({
meta,
prop,
propName,
+ computedValue,
deletable,
readOnly,
onChange,
onDelete,
-}: ControlProps<"code", "string">) => {
+}: ControlProps<"code", "string" | "expression">) => {
const metaOverride = {
...meta,
control: "text" as const,
};
- const localValue = useLocalValue(prop?.value ?? "", (value) => {
+ const localValue = useLocalValue(String(computedValue ?? ""), (value) => {
// sanitize html before saving
// this is basically what browser does when innerHTML is set
// but isolated within temporary element
// so the result is correct markup
const div = document.createElement("div");
div.innerHTML = value;
- onChange({ type: "string", value: div.innerHTML });
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, div.innerHTML);
+ } else {
+ onChange({ type: "string", value: div.innerHTML });
+ }
});
const label = getLabel(metaOverride, propName);
+ const { scope, aliases } = useStore($selectedInstanceScope);
+ const expression =
+ prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
+
return (
<VerticalLayout
label={
- <Box css={{ position: "relative" }}>
- <Label description={metaOverride.description} readOnly={readOnly}>
- {label}
- </Label>
- <VariablesButton
- propId={prop?.id}
- propName={propName}
- propMeta={metaOverride}
- />
- </Box>
+ <Label description={metaOverride.description} readOnly={readOnly}>
+ {label}
+ </Label>
}
deletable={deletable}
onDelete={onDelete}
>
- <Box css={{ py: theme.spacing[2] }}>
+ <Box css={{ position: "relative", py: theme.spacing[2] }}>
<HtmlEditor
readOnly={readOnly}
value={localValue.value}
onChange={localValue.set}
onBlur={localValue.save}
/>
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ value={expression}
+ onChange={(newExpression) =>
+ onChange({ type: "expression", value: newExpression })
+ }
+ onRemove={(evaluatedValue) =>
+ onChange({ type: "string", value: String(evaluatedValue) })
+ }
+ />
</Box>
</VerticalLayout>
);
diff --git a/apps/builder/app/builder/features/settings-panel/controls/color.tsx b/apps/builder/app/builder/features/settings-panel/controls/color.tsx
deleted file mode 100644
index eda703ff4a..0000000000
--- a/apps/builder/app/builder/features/settings-panel/controls/color.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import { Box, InputField, useId } from "@webstudio-is/design-system";
-import {
- type ControlProps,
- getLabel,
- useLocalValue,
- ResponsiveLayout,
- Label,
-} from "../shared";
-import { VariablesButton } from "../variables";
-
-// @todo:
-// use ColorPicker (need to refactor it first,
-// as it's currently tailored to work with styles only)
-
-export const ColorControl = ({
- meta,
- prop,
- propName,
- deletable,
- readOnly,
- onChange,
- onDelete,
-}: ControlProps<"color", "string">) => {
- const id = useId();
-
- const localValue = useLocalValue(prop?.value ?? "", (value) =>
- onChange({ type: "string", value })
- );
-
- return (
- <ResponsiveLayout
- label={
- <Box css={{ position: "relative" }}>
- <Label
- htmlFor={id}
- description={meta.description}
- readOnly={readOnly}
- >
- {getLabel(meta, propName)}
- </Label>
- <VariablesButton
- propId={prop?.id}
- propName={propName}
- propMeta={meta}
- />
- </Box>
- }
- deletable={deletable}
- onDelete={onDelete}
- >
- <InputField
- id={id}
- disabled={readOnly}
- value={localValue.value}
- onChange={(event) => localValue.set(event.target.value)}
- onBlur={localValue.save}
- onKeyDown={(event) => {
- if (event.key === "Enter") {
- localValue.save();
- }
- }}
- />
- </ResponsiveLayout>
- );
-};
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 aa961cff91..d72699fd67 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
@@ -1,6 +1,5 @@
import { TextControl } from "./text";
import { CodeControl } from "./code";
-import { ColorControl } from "./color";
import { NumberControl } from "./number";
import { CheckControl } from "./check";
import { RadioControl } from "./radio";
@@ -16,9 +15,7 @@ export const renderControl = ({
prop,
...rest
}: ControlProps<string, string> & { key?: string }) => {
- if (prop?.type === "expression") {
- throw Error("Expression is not resolved");
- }
+ const computed = rest.computedValue;
// never render parameter props
if (prop?.type === "parameter") {
@@ -30,20 +27,29 @@ export const renderControl = ({
return;
}
- if (meta.control === "json" && (prop === undefined || prop.type === "json")) {
+ if (
+ meta.control === "json" &&
+ (prop === undefined ||
+ prop.type === "json" ||
+ (prop.type === "expression" && typeof computed === "object"))
+ ) {
return <JsonControl meta={meta} prop={prop} {...rest} />;
}
if (
meta.control === "text" &&
- (prop === undefined || prop.type === "string")
+ (prop === undefined ||
+ prop.type === "string" ||
+ (prop.type === "expression" && typeof computed === "string"))
) {
return <TextControl meta={meta} prop={prop} {...rest} />;
}
if (
meta.control === "code" &&
- (prop === undefined || prop.type === "string")
+ (prop === undefined ||
+ prop.type === "string" ||
+ (prop.type === "expression" && typeof computed === "string"))
) {
return <CodeControl meta={meta} prop={prop} {...rest} />;
}
@@ -52,19 +58,25 @@ export const renderControl = ({
meta.control === "color" &&
(prop === undefined || prop.type === "string")
) {
- return <ColorControl meta={meta} prop={prop} {...rest} />;
+ return (
+ <TextControl meta={{ ...meta, control: "text" }} prop={prop} {...rest} />
+ );
}
if (
meta.control === "number" &&
- (prop === undefined || prop.type === "number")
+ (prop === undefined ||
+ prop.type === "number" ||
+ (prop.type === "expression" && typeof computed === "number"))
) {
return <NumberControl meta={meta} prop={prop} {...rest} />;
}
if (
meta.control === "boolean" &&
- (prop === undefined || prop.type === "boolean")
+ (prop === undefined ||
+ prop.type === "boolean" ||
+ (prop.type === "expression" && typeof computed === "boolean"))
) {
return <BooleanControl meta={meta} prop={prop} {...rest} />;
}
@@ -73,28 +85,37 @@ export const renderControl = ({
(meta.control === "check" ||
meta.control === "inline-check" ||
meta.control === "multi-select") &&
- (prop === undefined || prop.type === "string[]")
+ (prop === undefined ||
+ prop.type === "string[]" ||
+ (prop.type === "expression" && typeof computed === "object"))
) {
return <CheckControl meta={meta} prop={prop} {...rest} />;
}
if (
(meta.control === "radio" || meta.control === "inline-radio") &&
- (prop === undefined || prop.type === "string")
+ (prop === undefined ||
+ prop.type === "string" ||
+ (prop.type === "expression" && typeof computed === "string"))
) {
return <RadioControl meta={meta} prop={prop} {...rest} />;
}
if (
meta.control === "select" &&
- (prop === undefined || prop.type === "string")
+ (prop === undefined ||
+ prop.type === "string" ||
+ (prop.type === "expression" && typeof computed === "string"))
) {
return <SelectControl meta={meta} prop={prop} {...rest} />;
}
if (
meta.control === "file" &&
- (prop === undefined || prop.type === "asset" || prop.type === "string")
+ (prop === undefined ||
+ prop.type === "asset" ||
+ prop.type === "string" ||
+ (prop.type === "expression" && typeof computed === "string"))
) {
return <FileControl meta={meta} prop={prop} {...rest} />;
}
@@ -104,7 +125,8 @@ export const renderControl = ({
(prop === undefined ||
prop.type === "string" ||
prop.type === "page" ||
- prop.type === "asset")
+ prop.type === "asset" ||
+ (prop.type === "expression" && typeof computed === "string"))
) {
return <UrlControl meta={meta} prop={prop} {...rest} />;
}
@@ -112,13 +134,13 @@ export const renderControl = ({
// Type in meta can be changed at some point without updating props in DB that are still using the old type
// In this case meta and prop will mismatch, but we try to guess a matching control based just on the prop type
if (prop) {
- if (prop.type === "string") {
+ if (prop.type === "asset") {
return (
- <TextControl
+ <FileControl
meta={{
...meta,
defaultValue: undefined,
- control: "text",
+ control: "file",
type: "string",
}}
prop={prop}
@@ -127,14 +149,14 @@ export const renderControl = ({
);
}
- if (prop.type === "number") {
+ if (prop.type === "page") {
return (
- <NumberControl
+ <UrlControl
meta={{
...meta,
defaultValue: undefined,
- control: "number",
- type: "number",
+ control: "url",
+ type: "string",
}}
prop={prop}
{...rest}
@@ -142,14 +164,17 @@ export const renderControl = ({
);
}
- if (prop.type === "boolean") {
+ if (
+ prop.type === "string" ||
+ (prop.type === "expression" && typeof computed === "string")
+ ) {
return (
- <BooleanControl
+ <TextControl
meta={{
...meta,
defaultValue: undefined,
- control: "boolean",
- type: "boolean",
+ control: "text",
+ type: "string",
}}
prop={prop}
{...rest}
@@ -157,14 +182,17 @@ export const renderControl = ({
);
}
- if (prop.type === "json") {
+ if (
+ prop.type === "number" ||
+ (prop.type === "expression" && typeof computed === "number")
+ ) {
return (
- <JsonControl
+ <NumberControl
meta={{
...meta,
defaultValue: undefined,
- control: "json",
- type: "json",
+ control: "number",
+ type: "number",
}}
prop={prop}
{...rest}
@@ -172,14 +200,17 @@ export const renderControl = ({
);
}
- if (prop.type === "asset") {
+ if (
+ prop.type === "boolean" ||
+ (prop.type === "expression" && typeof computed === "boolean")
+ ) {
return (
- <FileControl
+ <BooleanControl
meta={{
...meta,
defaultValue: undefined,
- control: "file",
- type: "string",
+ control: "boolean",
+ type: "boolean",
}}
prop={prop}
{...rest}
@@ -187,14 +218,14 @@ export const renderControl = ({
);
}
- if (prop.type === "page") {
+ if (prop.type === "json" || prop.type === "expression") {
return (
- <UrlControl
+ <JsonControl
meta={{
...meta,
defaultValue: undefined,
- control: "url",
- type: "string",
+ control: "json",
+ type: "json",
}}
prop={prop}
{...rest}
diff --git a/apps/builder/app/builder/features/settings-panel/controls/file.tsx b/apps/builder/app/builder/features/settings-panel/controls/file.tsx
index 8473f36ae7..3902cbe431 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/file.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/file.tsx
@@ -1,32 +1,30 @@
-import { type ReactNode } from "react";
-import {
- Box,
- Flex,
- InputField,
- theme,
- useId,
-} from "@webstudio-is/design-system";
+import { useStore } from "@nanostores/react";
+import { useId, type ReactNode } from "react";
+import { Flex, InputField, theme } from "@webstudio-is/design-system";
+import { BindingPopover } from "~/builder/shared/binding-popover";
import {
type ControlProps,
getLabel,
VerticalLayout,
useLocalValue,
Label,
+ updateExpressionValue,
+ $selectedInstanceScope,
} from "../shared";
import { SelectAsset } from "./select-asset";
-import { VariablesButton } from "../variables";
-
-type FileControlProps = ControlProps<"file", "asset" | "string">;
const UrlInput = ({
id,
+ readOnly,
localValue,
}: {
id: string;
+ readOnly: boolean;
localValue: ReturnType<typeof useLocalValue<undefined | string>>;
}) => (
<InputField
id={id}
+ disabled={readOnly}
value={localValue.value ?? ""}
placeholder="http://www.url.com"
onChange={(event) => localValue.set(event.target.value)}
@@ -41,7 +39,10 @@ const UrlInput = ({
);
const Row = ({ children }: { children: ReactNode }) => (
- <Flex css={{ height: theme.spacing[13] }} align="center">
+ <Flex
+ css={{ height: theme.spacing[13], position: "relative" }}
+ align="center"
+ >
{children}
</Flex>
);
@@ -50,46 +51,60 @@ export const FileControl = ({
meta,
prop,
propName,
+ computedValue,
+ readOnly,
deletable,
onChange,
onDelete,
-}: FileControlProps) => {
+}: ControlProps<"file", "asset" | "string" | "expression">) => {
const id = useId();
const localStringValue = useLocalValue(
// use undefined for asset type to not delete
// when url is reset by asset selector
- prop?.type === "string" ? prop.value : undefined,
+ prop?.type === "string" || prop?.type === "expression"
+ ? String(computedValue)
+ : undefined,
(value) => {
if (value === undefined) {
return;
} else if (value === "") {
onDelete();
+ } else if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, value);
} else {
onChange({ type: "string", value });
}
}
);
+ const { scope, aliases } = useStore($selectedInstanceScope);
+ const expression =
+ prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
+
return (
<VerticalLayout
label={
- <Box css={{ position: "relative" }}>
- <Label htmlFor={id} description={meta.description}>
- {getLabel(meta, propName)}
- </Label>
- <VariablesButton
- propId={prop?.id}
- propName={propName}
- propMeta={meta}
- />
- </Box>
+ <Label htmlFor={id} description={meta.description}>
+ {getLabel(meta, propName)}
+ </Label>
}
deletable={deletable}
onDelete={onDelete}
>
<Row>
- <UrlInput id={id} localValue={localStringValue} />
+ <UrlInput id={id} readOnly={readOnly} localValue={localStringValue} />
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ value={expression}
+ onChange={(newExpression) =>
+ onChange({ type: "expression", value: newExpression })
+ }
+ onRemove={(evaluatedValue) =>
+ onChange({ type: "string", value: String(evaluatedValue) })
+ }
+ />
</Row>
<Row>
<SelectAsset
diff --git a/apps/builder/app/builder/features/settings-panel/controls/json.tsx b/apps/builder/app/builder/features/settings-panel/controls/json.tsx
index 3aa1d91978..7407f231d0 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/json.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/json.tsx
@@ -1,3 +1,4 @@
+import { useStore } from "@nanostores/react";
import { theme, Box } from "@webstudio-is/design-system";
import {
type ControlProps,
@@ -5,58 +6,72 @@ import {
useLocalValue,
VerticalLayout,
Label,
+ updateExpressionValue,
+ $selectedInstanceScope,
} from "../shared";
-import { VariablesButton } from "../variables";
import {
ExpressionEditor,
formatValue,
} from "~/builder/shared/expression-editor";
+import { BindingPopover } from "~/builder/shared/binding-popover";
export const JsonControl = ({
meta,
prop,
propName,
+ computedValue,
deletable,
readOnly,
onChange,
onDelete,
-}: ControlProps<"json", "json">) => {
- const valueString = formatValue(prop?.value ?? "");
+}: ControlProps<"json", "json" | "expression">) => {
+ const valueString = formatValue(computedValue ?? "");
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 });
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, parsedValue);
+ } else {
+ onChange({ type: "json", value: parsedValue });
+ }
} catch {
// empty block
}
});
const label = getLabel(meta, propName);
+ const { scope, aliases } = useStore($selectedInstanceScope);
+ const expression = prop?.type === "expression" ? prop.value : valueString;
+
return (
<VerticalLayout
label={
- <Box css={{ position: "relative" }}>
- <Label description={meta.description} readOnly={readOnly}>
- {label}
- </Label>
- <VariablesButton
- propId={prop?.id}
- propName={propName}
- propMeta={meta}
- />
- </Box>
+ <Label description={meta.description} readOnly={readOnly}>
+ {label}
+ </Label>
}
deletable={deletable}
onDelete={onDelete}
>
- <Box css={{ py: theme.spacing[2] }}>
+ <Box css={{ position: "relative", py: theme.spacing[2] }}>
<ExpressionEditor
readOnly={readOnly}
value={localValue.value}
onChange={localValue.set}
onBlur={localValue.save}
/>
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ value={expression}
+ onChange={(newExpression) =>
+ onChange({ type: "expression", value: newExpression })
+ }
+ onRemove={(evaluatedValue) =>
+ onChange({ type: "json", value: evaluatedValue })
+ }
+ />
</Box>
</VerticalLayout>
);
diff --git a/apps/builder/app/builder/features/settings-panel/controls/number.tsx b/apps/builder/app/builder/features/settings-panel/controls/number.tsx
index 24c9337870..de5ae6d79a 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/number.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/number.tsx
@@ -1,73 +1,95 @@
-import { Box, InputField, useId } from "@webstudio-is/design-system";
+import { useId, useState } from "react";
+import { useStore } from "@nanostores/react";
+import { Box, InputField } from "@webstudio-is/design-system";
+import { BindingPopover } from "~/builder/shared/binding-popover";
import {
type ControlProps,
getLabel,
useLocalValue,
ResponsiveLayout,
Label,
+ updateExpressionValue,
+ $selectedInstanceScope,
} from "../shared";
-import { useState } from "react";
-import { VariablesButton } from "../variables";
export const NumberControl = ({
meta,
prop,
propName,
+ computedValue,
onChange,
deletable,
readOnly,
onDelete,
-}: ControlProps<"number", "number">) => {
+}: ControlProps<"number", "number" | "expression">) => {
const id = useId();
const [isInvalid, setIsInvalid] = useState(false);
- const localValue = useLocalValue(prop ? prop.value : "", (value) => {
- if (typeof value === "number") {
- onChange({ type: "number", value });
- }
- if (value === "") {
- setIsInvalid(true);
+ const number = Number(computedValue);
+ const localValue = useLocalValue(
+ Number.isNaN(number) ? "" : number,
+ (value) => {
+ if (typeof value === "number") {
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, value);
+ } else {
+ onChange({ type: "number", value });
+ }
+ }
+ if (value === "") {
+ setIsInvalid(true);
+ }
}
- });
+ );
+
+ const { scope, aliases } = useStore($selectedInstanceScope);
+ const expression =
+ prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
return (
<ResponsiveLayout
label={
- <Box css={{ position: "relative" }}>
- <Label
- htmlFor={id}
- description={meta.description}
- readOnly={readOnly}
- >
- {getLabel(meta, propName)}
- </Label>
- <VariablesButton
- propId={prop?.id}
- propName={propName}
- propMeta={meta}
- />
- </Box>
+ <Label htmlFor={id} description={meta.description} readOnly={readOnly}>
+ {getLabel(meta, propName)}
+ </Label>
}
deletable={deletable}
onDelete={onDelete}
>
- <InputField
- id={id}
- disabled={readOnly}
- type="number"
- value={localValue.value}
- color={isInvalid ? "error" : undefined}
- onChange={({ target: { valueAsNumber, value } }) => {
- localValue.set(Number.isNaN(valueAsNumber) ? value : valueAsNumber);
- setIsInvalid(false);
- }}
- onBlur={localValue.save}
- onKeyDown={(event) => {
- if (event.key === "Enter") {
- localValue.save();
+ <Box css={{ position: "relative" }}>
+ <InputField
+ id={id}
+ disabled={readOnly}
+ type="number"
+ value={localValue.value}
+ color={isInvalid ? "error" : undefined}
+ onChange={({ target: { valueAsNumber, value } }) => {
+ localValue.set(Number.isNaN(valueAsNumber) ? value : valueAsNumber);
+ setIsInvalid(false);
+ }}
+ onBlur={localValue.save}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ localValue.save();
+ }
+ }}
+ />
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ value={expression}
+ onChange={(newExpression) =>
+ onChange({ type: "expression", value: newExpression })
}
- }}
- />
+ onRemove={(evaluatedValue) => {
+ const number = Number(evaluatedValue);
+ onChange({
+ type: "number",
+ value: Number.isNaN(number) ? 0 : number,
+ });
+ }}
+ />
+ </Box>
</ResponsiveLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/radio.tsx b/apps/builder/app/builder/features/settings-panel/controls/radio.tsx
index 097a404d3b..b07ba8a65b 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/radio.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/radio.tsx
@@ -1,59 +1,67 @@
+import { useId } from "react";
+import { useStore } from "@nanostores/react";
import {
Box,
RadioGroup,
Radio,
RadioAndLabel,
- useId,
theme,
} from "@webstudio-is/design-system";
import { humanizeString } from "~/shared/string-utils";
-import { type ControlProps, getLabel, VerticalLayout, Label } from "../shared";
-import { VariablesButton } from "../variables";
+import { BindingPopover } from "~/builder/shared/binding-popover";
+import {
+ type ControlProps,
+ getLabel,
+ VerticalLayout,
+ Label,
+ $selectedInstanceScope,
+ updateExpressionValue,
+} from "../shared";
export const RadioControl = ({
meta,
prop,
propName,
+ computedValue,
deletable,
readOnly,
onChange,
onDelete,
-}: ControlProps<"radio" | "inline-radio", "string">) => {
+}: ControlProps<"radio" | "inline-radio", "string" | "expression">) => {
+ const value = computedValue === undefined ? undefined : String(computedValue);
// making sure that the current value is in the list of options
const options =
- prop === undefined || meta.options.includes(prop.value)
+ value === undefined || meta.options.includes(value)
? meta.options
- : [prop.value, ...meta.options];
+ : [value, ...meta.options];
const id = useId();
+ const { scope, aliases } = useStore($selectedInstanceScope);
+ const expression =
+ prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
return (
<VerticalLayout
label={
- <Box css={{ position: "relative" }}>
- <Label
- htmlFor={id}
- description={meta.description}
- readOnly={readOnly}
- >
- {getLabel(meta, propName)}
- </Label>
- <VariablesButton
- propId={prop?.id}
- propName={propName}
- propMeta={meta}
- />
- </Box>
+ <Label htmlFor={id} description={meta.description} readOnly={readOnly}>
+ {getLabel(meta, propName)}
+ </Label>
}
deletable={deletable}
onDelete={onDelete}
>
- <Box css={{ paddingTop: theme.spacing[2] }}>
+ <Box css={{ position: "relative", paddingTop: theme.spacing[2] }}>
<RadioGroup
disabled={readOnly}
name="value"
- value={prop?.value}
- onValueChange={(value) => onChange({ type: "string", value })}
+ value={value}
+ onValueChange={(value) => {
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, value);
+ } else {
+ onChange({ type: "string", value });
+ }
+ }}
>
{options.map((value) => (
<RadioAndLabel key={value}>
@@ -62,6 +70,17 @@ export const RadioControl = ({
</RadioAndLabel>
))}
</RadioGroup>
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ value={expression}
+ onChange={(newExpression) =>
+ onChange({ type: "expression", value: newExpression })
+ }
+ onRemove={(evaluatedValue) =>
+ onChange({ type: "string", value: String(evaluatedValue) })
+ }
+ />
</Box>
</VerticalLayout>
);
diff --git a/apps/builder/app/builder/features/settings-panel/controls/select.tsx b/apps/builder/app/builder/features/settings-panel/controls/select.tsx
index 9a11aff889..ad6306176a 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/select.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/select.tsx
@@ -1,55 +1,76 @@
-import { Flex, theme, useId, Select, Box } from "@webstudio-is/design-system";
+import { useId } from "react";
+import { useStore } from "@nanostores/react";
+import { Flex, theme, Select } from "@webstudio-is/design-system";
import { humanizeString } from "~/shared/string-utils";
-import { type ControlProps, getLabel, VerticalLayout, Label } from "../shared";
-import { VariablesButton } from "../variables";
+import { BindingPopover } from "~/builder/shared/binding-popover";
+import {
+ type ControlProps,
+ getLabel,
+ VerticalLayout,
+ Label,
+ $selectedInstanceScope,
+ updateExpressionValue,
+} from "../shared";
export const SelectControl = ({
meta,
prop,
propName,
+ computedValue,
deletable,
readOnly,
onChange,
onDelete,
-}: ControlProps<"select", "string">) => {
+}: ControlProps<"select", "string" | "expression">) => {
const id = useId();
+ const value = computedValue === undefined ? undefined : String(computedValue);
// making sure that the current value is in the list of options
const options =
- prop === undefined || meta.options.includes(prop.value) || prop.value === ""
+ value === undefined || value.length === 0 || meta.options.includes(value)
? meta.options
- : [prop.value, ...meta.options];
+ : [value, ...meta.options];
+
+ const { scope, aliases } = useStore($selectedInstanceScope);
+ const expression =
+ prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
return (
<VerticalLayout
label={
- <Box css={{ position: "relative" }}>
- <Label
- htmlFor={id}
- description={meta.description}
- readOnly={readOnly}
- >
- {getLabel(meta, propName)}
- </Label>
- <VariablesButton
- propId={prop?.id}
- propName={propName}
- propMeta={meta}
- />
- </Box>
+ <Label htmlFor={id} description={meta.description} readOnly={readOnly}>
+ {getLabel(meta, propName)}
+ </Label>
}
deletable={deletable}
onDelete={onDelete}
>
- <Flex css={{ py: theme.spacing[2] }}>
+ <Flex css={{ position: "relative", py: theme.spacing[2] }}>
<Select
+ fullWidth
id={id}
disabled={readOnly}
- value={prop?.value}
+ value={value}
options={options}
getLabel={humanizeString}
- onChange={(value) => onChange({ type: "string", value })}
- fullWidth
+ onChange={(value) => {
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, value);
+ } else {
+ onChange({ type: "string", value });
+ }
+ }}
+ />
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ value={expression}
+ onChange={(newExpression) =>
+ onChange({ type: "expression", value: newExpression })
+ }
+ onRemove={(evaluatedValue) =>
+ onChange({ type: "string", value: String(evaluatedValue) })
+ }
/>
</Flex>
</VerticalLayout>
diff --git a/apps/builder/app/builder/features/settings-panel/controls/text.tsx b/apps/builder/app/builder/features/settings-panel/controls/text.tsx
index ceb64f5ea7..71968c3cf7 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/text.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/text.tsx
@@ -1,4 +1,5 @@
-import { Flex, theme, useId, TextArea, Box } from "@webstudio-is/design-system";
+import { useStore } from "@nanostores/react";
+import { Flex, theme, useId, TextArea } from "@webstudio-is/design-system";
import {
type ControlProps,
getLabel,
@@ -6,48 +7,69 @@ import {
VerticalLayout,
ResponsiveLayout,
Label,
+ updateExpressionValue,
+ $selectedInstanceScope,
} from "../shared";
-import { VariablesButton } from "../variables";
+import { BindingPopover } from "~/builder/shared/binding-popover";
export const TextControl = ({
meta,
prop,
propName,
deletable,
+ computedValue,
readOnly,
onChange,
onDelete,
-}: ControlProps<"text", "string">) => {
- const localValue = useLocalValue(prop?.value ?? "", (value) => {
- onChange({ type: "string", value });
+}: ControlProps<"text", "string" | "expression">) => {
+ const localValue = useLocalValue(String(computedValue ?? ""), (value) => {
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, value);
+ } else {
+ onChange({ type: "string", value });
+ }
});
const id = useId();
const label = getLabel(meta, propName);
const rows = meta.rows ?? 1;
const isTwoColumnLayout = rows < 2;
+ const { scope, aliases } = useStore($selectedInstanceScope);
+ const expression =
+ prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
+
const input = (
- <TextArea
- id={id}
- disabled={readOnly}
- autoGrow
- value={localValue.value}
- rows={meta.rows ?? 1}
- // Set maxRows to 3 when meta.rows is undefined or equal to 1, otherwise set it to rows * 2
- maxRows={Math.max(2 * (meta.rows ?? 1), 3)}
- onChange={localValue.set}
- onBlur={localValue.save}
- onSubmit={localValue.save}
- />
+ <>
+ <TextArea
+ id={id}
+ disabled={readOnly}
+ autoGrow
+ value={localValue.value}
+ rows={meta.rows ?? 1}
+ // Set maxRows to 3 when meta.rows is undefined or equal to 1, otherwise set it to rows * 2
+ maxRows={Math.max(2 * (meta.rows ?? 1), 3)}
+ onChange={localValue.set}
+ onBlur={localValue.save}
+ onSubmit={localValue.save}
+ />
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ value={expression}
+ onChange={(newExpression) =>
+ onChange({ type: "expression", value: newExpression })
+ }
+ onRemove={(evaluatedValue) =>
+ onChange({ type: "string", value: String(evaluatedValue) })
+ }
+ />
+ </>
);
const labelElement = (
- <Box css={{ position: "relative" }}>
- <Label htmlFor={id} description={meta.description} readOnly={readOnly}>
- {label}
- </Label>
- <VariablesButton propId={prop?.id} propName={propName} propMeta={meta} />
- </Box>
+ <Label htmlFor={id} description={meta.description} readOnly={readOnly}>
+ {label}
+ </Label>
);
if (isTwoColumnLayout) {
@@ -57,7 +79,7 @@ export const TextControl = ({
deletable={deletable}
onDelete={onDelete}
>
- <Flex>{input}</Flex>
+ <Flex css={{ position: "relative" }}>{input}</Flex>
</ResponsiveLayout>
);
}
@@ -68,7 +90,7 @@ export const TextControl = ({
deletable={deletable}
onDelete={onDelete}
>
- <Flex css={{ py: theme.spacing[2] }}>{input}</Flex>
+ <Flex css={{ py: theme.spacing[2], position: "relative" }}>{input}</Flex>
</VerticalLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/controls/url.tsx b/apps/builder/app/builder/features/settings-panel/controls/url.tsx
index d967db8106..c6d823fab2 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/url.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/url.tsx
@@ -1,4 +1,4 @@
-import { type ReactNode, useState, useEffect } from "react";
+import { type ReactNode, useEffect } from "react";
import { useStore } from "@nanostores/react";
import { computed } from "nanostores";
import {
@@ -22,22 +22,29 @@ import {
import type { Instance, Page } from "@webstudio-is/sdk";
import { findTreeInstanceIds } from "@webstudio-is/sdk";
import { instancesStore, pagesStore, propsStore } from "~/shared/nano-states";
+import { BindingPopover } from "~/builder/shared/binding-popover";
import {
type ControlProps,
getLabel,
useLocalValue,
VerticalLayout,
Label,
+ updateExpressionValue,
+ $selectedInstanceScope,
} from "../shared";
import { SelectAsset } from "./select-asset";
-import { VariablesButton } from "../variables";
-type UrlControlProps = ControlProps<"url", "string" | "page" | "asset">;
+type UrlControlProps = ControlProps<
+ "url",
+ "string" | "page" | "asset" | "expression"
+>;
type BaseControlProps = {
id: string;
instanceId: string;
+ readOnly: boolean;
prop: UrlControlProps["prop"];
+ value: string;
onChange: UrlControlProps["onChange"];
onDelete: UrlControlProps["onDelete"];
};
@@ -79,11 +86,14 @@ const addHttpsIfMissing = (url: string) => {
return url;
};
-const BaseUrl = ({ prop, onChange, id }: BaseControlProps) => {
- const localValue = useLocalValue(
- prop?.type === "string" ? prop.value : "",
- (value) => onChange({ type: "string", value })
- );
+const BaseUrl = ({ readOnly, prop, value, onChange, id }: BaseControlProps) => {
+ const localValue = useLocalValue(value, (value) => {
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, value);
+ } else {
+ onChange({ type: "string", value });
+ }
+ });
useEffect(() => {
return () => localValue.set(addHttpsIfMissing(localValue.value));
@@ -93,6 +103,7 @@ const BaseUrl = ({ prop, onChange, id }: BaseControlProps) => {
return (
<Row>
<InputField
+ disabled={readOnly}
id={id}
value={localValue.value}
placeholder="http://www.url.com"
@@ -113,18 +124,29 @@ const BaseUrl = ({ prop, onChange, id }: BaseControlProps) => {
);
};
-const BasePhone = ({ prop, onChange, id }: BaseControlProps) => {
+const BasePhone = ({
+ readOnly,
+ prop,
+ value,
+ onChange,
+ id,
+}: BaseControlProps) => {
const localValue = useLocalValue(
- prop?.type === "string" && prop.value.startsWith("tel:")
- ? prop.value.slice(4)
- : "",
- (value) => onChange({ type: "string", value: `tel:${value}` })
+ value.startsWith("tel:") ? value.slice(4) : "",
+ (value) => {
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, `tel:${value}`);
+ } else {
+ onChange({ type: "string", value: `tel:${value}` });
+ }
+ }
);
return (
<Row>
<InputField
id={id}
+ disabled={readOnly}
value={localValue.value}
type="tel"
placeholder="+15555555555"
@@ -141,16 +163,13 @@ const BasePhone = ({ prop, onChange, id }: BaseControlProps) => {
);
};
-const propToEmail = (prop?: UrlControlProps["prop"]) => {
- if (prop?.type !== "string") {
- return { email: "", subject: "" };
- }
-
+const propToEmail = (value: string) => {
let url;
try {
- url = new URL(prop.value);
- // eslint-disable-next-line no-empty
- } catch {}
+ url = new URL(value);
+ } catch {
+ // empty block
+ }
if (url === undefined || url.protocol !== "mailto:") {
return { email: "", subject: "" };
@@ -162,23 +181,39 @@ const propToEmail = (prop?: UrlControlProps["prop"]) => {
};
};
-const BaseEmail = ({ prop, onChange, id }: BaseControlProps) => {
- const localValue = useLocalValue(propToEmail(prop), ({ email, subject }) => {
+const BaseEmail = ({
+ readOnly,
+ prop,
+ value,
+ onChange,
+ id,
+}: BaseControlProps) => {
+ const localValue = useLocalValue(propToEmail(value), ({ email, subject }) => {
if (email === "") {
- onChange({ type: "string", value: "" });
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, "");
+ } else {
+ onChange({ type: "string", value: "" });
+ }
return;
}
const url = new URL(`mailto:${email}`);
if (subject !== "") {
url.searchParams.set("subject", subject);
}
- onChange({ type: "string", value: url.toString() });
+ const value = url.toString();
+ if (prop?.type === "expression") {
+ updateExpressionValue(prop.value, value);
+ } else {
+ onChange({ type: "string", value });
+ }
});
return (
<>
<Row>
<InputField
+ disabled={readOnly}
id={id}
value={localValue.value.email}
type="email"
@@ -198,6 +233,7 @@ const BaseEmail = ({ prop, onChange, id }: BaseControlProps) => {
<Row>
<Label htmlFor={`${id}-subject`}>Subject</Label>
<InputField
+ disabled={readOnly}
id={`${id}-subject`}
value={localValue.value.subject}
placeholder="You've got mail!"
@@ -360,7 +396,10 @@ const modes = {
type Mode = keyof typeof modes;
-const propToMode = (prop?: UrlControlProps["prop"]): Mode => {
+const propToMode = (
+ prop: undefined | UrlControlProps["prop"],
+ value: string
+): Mode => {
if (prop === undefined) {
return "url";
}
@@ -373,11 +412,11 @@ const propToMode = (prop?: UrlControlProps["prop"]): Mode => {
return "attachment";
}
- if (prop.value.startsWith("tel:")) {
+ if (value.startsWith("tel:")) {
return "phone";
}
- if (prop.value.startsWith("mailto:")) {
+ if (value.startsWith("mailto:")) {
return "email";
}
@@ -389,29 +428,32 @@ export const UrlControl = ({
meta,
prop,
propName,
+ computedValue,
+ readOnly,
deletable,
onChange,
onDelete,
}: UrlControlProps) => {
- const [mode, setMode] = useState<Mode>(propToMode(prop));
+ const value = String(computedValue ?? "");
+ const { value: mode, set: setMode } = useLocalValue<Mode>(
+ propToMode(prop, value),
+ () => {}
+ );
const id = useId();
const BaseControl = modes[mode].control;
+ const { scope, aliases } = useStore($selectedInstanceScope);
+ const expression =
+ prop?.type === "expression" ? prop.value : JSON.stringify(computedValue);
+
return (
<VerticalLayout
label={
- <Box css={{ position: "relative" }}>
- <Label htmlFor={id} description={meta.description}>
- {getLabel(meta, propName)}
- </Label>
- <VariablesButton
- propId={prop?.id}
- propName={propName}
- propMeta={meta}
- />
- </Box>
+ <Label htmlFor={id} description={meta.description}>
+ {getLabel(meta, propName)}
+ </Label>
}
deletable={deletable}
onDelete={onDelete}
@@ -427,6 +469,7 @@ export const UrlControl = ({
>
<ToggleGroup
type="single"
+ disabled={readOnly}
value={mode}
onValueChange={(value) => {
// too tricky to prove to TS that value is a Mode
@@ -442,13 +485,28 @@ export const UrlControl = ({
</ToggleGroup>
</Flex>
- <BaseControl
- id={id}
- instanceId={instanceId}
- prop={prop}
- onChange={onChange}
- onDelete={onDelete}
- />
+ <Box css={{ position: "relative" }}>
+ <BaseControl
+ id={id}
+ instanceId={instanceId}
+ readOnly={readOnly}
+ prop={prop}
+ value={value}
+ onChange={onChange}
+ onDelete={onDelete}
+ />
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ value={expression}
+ onChange={(newExpression) =>
+ onChange({ type: "expression", value: newExpression })
+ }
+ onRemove={(evaluatedValue) =>
+ onChange({ type: "string", value: String(evaluatedValue) })
+ }
+ />
+ </Box>
</VerticalLayout>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.stories.tsx b/apps/builder/app/builder/features/settings-panel/props-section/props-section.stories.tsx
index 3d0d532d2b..125585bd90 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/props-section.stories.tsx
+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.stories.tsx
@@ -400,6 +400,7 @@ export const Story = () => {
<PropsSection
instanceId={instanceId}
propsLogic={logic}
+ propValues={new Map()}
component="Button"
setCssProperty={() => () => undefined}
/>
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 a70632ae05..3545325631 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
@@ -14,11 +14,8 @@ import {
InputField,
NestedInputButton,
} from "@webstudio-is/design-system";
-import { decodeDataSourceVariable } from "@webstudio-is/react-sdk";
import {
$propValuesByInstanceSelector,
- dataSourceVariablesStore,
- dataSourcesStore,
propsIndexStore,
propsStore,
selectedInstanceSelectorStore,
@@ -94,6 +91,7 @@ const PropsCombobox = ({
const renderProperty = (
{
propsLogic: logic,
+ propValues,
setCssProperty,
component,
instanceId,
@@ -103,13 +101,15 @@ const renderProperty = (
) => (
// 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
+ // when unmount to reproduce try to edit body id prop
+ // and then bind json variable to it
<Fragment key={(prop?.type ?? "") + propName}>
{renderControl({
key: propName,
instanceId,
meta,
prop,
+ computedValue: propValues.get(propName),
propName,
readOnly,
deletable: deletable ?? false,
@@ -165,6 +165,7 @@ const AddPropertyForm = ({
type PropsSectionProps = {
propsLogic: ReturnType<typeof usePropsLogic>;
+ propValues: Map<string, unknown>;
component: Instance["component"];
instanceId: string;
setCssProperty: SetCssProperty;
@@ -228,44 +229,21 @@ export const PropsSectionContainer = ({
const logic = usePropsLogic({
instance,
props: propsByInstanceId.get(instance.id) ?? [],
- propValues,
updateProp: (update) => {
- const props = propsStore.get();
- const prop = props.get(update.id);
- // update the variable when real prop has expression type
- // update the prop when new expression is added
- if (prop?.type === "expression" && update.type !== "expression") {
- const dataSources = dataSourcesStore.get();
- // when expression contains only reference to variable update that variable
- // extract id without parsing expression
- const potentialVariableId = decodeDataSourceVariable(prop.value);
- if (
- potentialVariableId !== undefined &&
- dataSources.has(potentialVariableId)
- ) {
- const dataSourceId = potentialVariableId;
- const dataSourceVariables = new Map(dataSourceVariablesStore.get());
- dataSourceVariables.set(dataSourceId, update.value);
- dataSourceVariablesStore.set(dataSourceVariables);
+ const { propsByInstanceId } = propsIndexStore.get();
+ 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 = instanceProps
+ .filter((prop) => prop.id !== update.id)
+ .filter((prop) => prop.name === update.name);
+ serverSyncStore.createTransaction([propsStore], (props) => {
+ for (const prop of duplicateProps) {
+ props.delete(prop.id);
}
- } else {
- const { propsByInstanceId } = propsIndexStore.get();
- serverSyncStore.createTransaction([propsStore], (props) => {
- 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 = instanceProps
- .filter((prop) => prop.id !== update.id)
- .filter((prop) => prop.name === update.name);
-
- for (const prop of duplicateProps) {
- props.delete(prop.id);
- }
-
- props.set(update.id, update);
- });
- }
+ props.set(update.id, update);
+ });
},
deleteProp: (propId) => {
@@ -284,6 +262,7 @@ export const PropsSectionContainer = ({
return (
<PropsSection
propsLogic={logic}
+ propValues={propValues ?? new Map()}
component={instance.component}
instanceId={instance.id}
setCssProperty={setCssProperty}
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 ab5c8bb778..803529676e 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
@@ -116,7 +116,6 @@ const getDefaultMetaForType = (type: Prop["type"]): PropMeta => {
type UsePropsLogicInput = {
instance: Instance;
props: Prop[];
- propValues?: Map<Prop["name"], unknown>;
updateProp: (update: Prop) => void;
deleteProp: (id: Prop["id"]) => void;
};
@@ -140,25 +139,10 @@ const systemPropsMeta: { name: string; meta: PropMeta }[] = [
},
];
-const getPropTypeAndValue = (value: unknown) => {
- if (typeof value === "boolean") {
- return { type: "boolean", value } as const;
- }
- if (typeof value === "number") {
- return { type: "number", value } as const;
- }
- if (typeof value === "string") {
- 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 */
export const usePropsLogic = ({
instance,
props,
- propValues,
updateProp,
deleteProp,
}: UsePropsLogicInput) => {
@@ -181,14 +165,6 @@ export const usePropsLogic = ({
const initialPropsNames = new Set(meta.initialProps ?? []);
- const resolvePropExpression = (prop?: Prop) => {
- if (prop?.type !== "expression") {
- return prop;
- }
- const propValue = propValues?.get(prop.name);
- return { ...prop, ...getPropTypeAndValue(propValue) };
- };
-
/**
* make sure expression can be edited if consists only of single variable
*/
@@ -211,7 +187,7 @@ export const usePropsLogic = ({
getAndDelete(unprocessedKnown, name);
initialPropsNames.delete(name);
return {
- prop: resolvePropExpression(saved),
+ prop: saved,
propName: name,
meta,
readOnly: isReadOnly(saved),
@@ -247,7 +223,7 @@ export const usePropsLogic = ({
}
initialProps.push({
- prop: resolvePropExpression(prop),
+ prop,
propName: name,
meta: known,
readOnly: isReadOnly(prop),
@@ -272,7 +248,7 @@ export const usePropsLogic = ({
}
addedProps.push({
- prop: resolvePropExpression(prop),
+ prop,
propName: prop.name,
meta: known,
readOnly: isReadOnly(prop),
diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
index 57143662c2..c74397967a 100644
--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
@@ -23,7 +23,6 @@ import {
$dataSources,
$resources,
$selectedInstanceSelector,
- $selectedPage,
$variableValuesByInstanceSelector,
} from "~/shared/nano-states";
import {
@@ -82,6 +81,9 @@ const HeaderPair = ({
aliases={editorAliases}
value={value}
onChange={(newValue) => onChange(name, newValue)}
+ onRemove={(evaluatedValue) =>
+ onChange(name, JSON.stringify(evaluatedValue))
+ }
/>
<InputField
id={valueId}
@@ -180,40 +182,30 @@ const Headers = ({
);
};
-const $selectedInstanceVariableValues = computed(
- [$selectedInstanceSelector, $variableValuesByInstanceSelector],
- (instanceSelector, variableValuesByInstanceSelector) => {
- const key = JSON.stringify(instanceSelector);
- return variableValuesByInstanceSelector.get(key) ?? new Map();
- }
-);
-
-const $selectedInstanceVariables = computed(
- [$selectedInstanceSelector, $dataSources, $selectedPage],
- (instanceSelector, dataSources, page) => {
- const matchedVariables: DataSource[] = [];
+const $selectedInstanceScope = computed(
+ [$selectedInstanceSelector, $variableValuesByInstanceSelector, $dataSources],
+ (instanceSelector, variableValuesByInstanceSelector, dataSources) => {
+ const scope: Record<string, unknown> = {};
+ const aliases = new Map<string, string>();
if (instanceSelector === undefined) {
- return matchedVariables;
+ return { scope, aliases };
}
- for (const dataSource of dataSources.values()) {
- if (
- dataSource.scopeInstanceId === undefined ||
- instanceSelector.includes(dataSource.scopeInstanceId) === false
- ) {
- continue;
- }
- // support only value variables and page page params parameter
- if (
- dataSource.type === "parameter" &&
- dataSource.id === page?.pathVariableId
- ) {
- matchedVariables.push(dataSource);
- }
- if (dataSource.type === "variable") {
- matchedVariables.push(dataSource);
+ const values = variableValuesByInstanceSelector.get(
+ JSON.stringify(instanceSelector)
+ );
+ if (values) {
+ for (const [dataSourceId, value] of values) {
+ const dataSource = dataSources.get(dataSourceId);
+ // prevent resources using data of other resources
+ if (dataSource === undefined || dataSource.type === "resource") {
+ continue;
+ }
+ const name = encodeDataSourceVariable(dataSourceId);
+ scope[name] = value;
+ aliases.set(name, dataSource.name);
}
}
- return matchedVariables;
+ return { scope, aliases };
}
);
@@ -244,28 +236,20 @@ export const ResourcePanel = ({
// empty string as default
const [body, setBody] = useState(resource?.body ?? `""`);
- const matchedVariables = useStore($selectedInstanceVariables);
- const variableValues = useStore($selectedInstanceVariableValues);
+ const { scope: scopeWithCurrentVariable, aliases } = useStore(
+ $selectedInstanceScope
+ );
const currentVariableId = variable?.id;
- const editorScope = useMemo(() => {
- const scope: Record<string, unknown> = {};
- for (const [variableId, variableValue] of variableValues) {
- // prevent showing currently edited variable in suggestions
- // to avoid cirular dependeny
- if (currentVariableId === variableId) {
- continue;
- }
- scope[encodeDataSourceVariable(variableId)] = variableValue;
- }
- return scope;
- }, [variableValues, currentVariableId]);
- const editorAliases = useMemo(() => {
- const aliases = new Map<string, string>();
- for (const variable of matchedVariables) {
- aliases.set(encodeDataSourceVariable(variable.id), variable.name);
+ // prevent showing currently edited variable in suggestions
+ // to avoid cirular dependeny
+ const scope = useMemo(() => {
+ if (currentVariableId === undefined) {
+ return scopeWithCurrentVariable;
}
- return aliases;
- }, [matchedVariables]);
+ const newScope: Record<string, unknown> = { ...scopeWithCurrentVariable };
+ delete newScope[encodeDataSourceVariable(currentVariableId)];
+ return newScope;
+ }, [scopeWithCurrentVariable, currentVariableId]);
return (
<Flex
@@ -289,16 +273,19 @@ export const ResourcePanel = ({
<Label htmlFor={urlId}>URL</Label>
<Box css={{ position: "relative" }}>
<BindingPopover
- scope={editorScope}
- aliases={editorAliases}
+ scope={scope}
+ aliases={aliases}
value={url}
onChange={setUrl}
+ onRemove={(evaluatedValue) =>
+ setUrl(JSON.stringify(evaluatedValue))
+ }
/>
<InputField
id={urlId}
// expressions with variables cannot be edited
disabled={isLiteralExpression(url) === false}
- value={String(evaluateExpressionWithinScope(url, editorScope))}
+ value={String(evaluateExpressionWithinScope(url, scope))}
// update text value as string literal
onChange={(event) => setUrl(JSON.stringify(event.target.value))}
/>
@@ -316,8 +303,8 @@ export const ResourcePanel = ({
<Flex direction="column" css={{ gap: theme.spacing[3] }}>
<Label>Headers</Label>
<Headers
- editorScope={editorScope}
- editorAliases={editorAliases}
+ editorScope={scope}
+ editorAliases={aliases}
headers={headers}
onChange={setHeaders}
/>
@@ -327,17 +314,20 @@ export const ResourcePanel = ({
<Label>Body</Label>
<Box css={{ position: "relative" }}>
<BindingPopover
- scope={editorScope}
- aliases={editorAliases}
+ scope={scope}
+ aliases={aliases}
value={body}
onChange={setBody}
+ onRemove={(evaluatedValue) =>
+ setBody(JSON.stringify(evaluatedValue))
+ }
/>
<TextArea
autoGrow={true}
maxRows={10}
// expressions with variables cannot be edited
disabled={isLiteralExpression(body) === false}
- value={String(evaluateExpressionWithinScope(body, editorScope))}
+ value={String(evaluateExpressionWithinScope(body, scope))}
// update text value as string literal
onChange={(newValue) => setBody(JSON.stringify(newValue))}
/>
diff --git a/apps/builder/app/builder/features/settings-panel/shared.tsx b/apps/builder/app/builder/features/settings-panel/shared.tsx
index a3101d1e3a..372c85d0fc 100644
--- a/apps/builder/app/builder/features/settings-panel/shared.tsx
+++ b/apps/builder/app/builder/features/settings-panel/shared.tsx
@@ -1,3 +1,4 @@
+import { computed } from "nanostores";
import {
type ComponentPropsWithoutRef,
type ReactNode,
@@ -6,7 +7,11 @@ import {
useEffect,
} from "react";
import equal from "fast-deep-equal";
-import type { PropMeta } from "@webstudio-is/react-sdk";
+import {
+ decodeDataSourceVariable,
+ encodeDataSourceVariable,
+ type PropMeta,
+} from "@webstudio-is/react-sdk";
import type { Prop, Asset } from "@webstudio-is/sdk";
import { HelpIcon, SubtractIcon } from "@webstudio-is/icons";
import {
@@ -23,6 +28,12 @@ import {
rawTheme,
} from "@webstudio-is/design-system";
import { humanizeString } from "~/shared/string-utils";
+import {
+ $dataSourceVariables,
+ $dataSources,
+ $selectedInstanceSelector,
+ $variableValuesByInstanceSelector,
+} from "~/shared/nano-states";
export type PropValue =
| { type: "number"; value: number }
@@ -52,6 +63,7 @@ export type ControlProps<Control, PropType> = {
// and we don't want to show user something like a 0 for number when it's in fact not set to any value
prop: PropByType<PropType> | undefined;
propName: string;
+ computedValue: unknown;
deletable: boolean;
readOnly: boolean;
onChange: (value: PropValue, asset?: Asset) => void;
@@ -283,3 +295,45 @@ export const Row = ({ children, css }: { children: ReactNode; css?: CSS }) => (
{children}
</Flex>
);
+
+export const $selectedInstanceScope = computed(
+ [$selectedInstanceSelector, $variableValuesByInstanceSelector, $dataSources],
+ (instanceSelector, variableValuesByInstanceSelector, dataSources) => {
+ const scope: Record<string, unknown> = {};
+ const aliases = new Map<string, string>();
+ if (instanceSelector === undefined) {
+ return { scope, aliases };
+ }
+ const values = variableValuesByInstanceSelector.get(
+ JSON.stringify(instanceSelector)
+ );
+ if (values) {
+ for (const [dataSourceId, value] of values) {
+ const dataSource = dataSources.get(dataSourceId);
+ if (dataSource === undefined) {
+ continue;
+ }
+ const name = encodeDataSourceVariable(dataSourceId);
+ scope[name] = value;
+ aliases.set(name, dataSource.name);
+ }
+ }
+ return { scope, aliases };
+ }
+);
+
+export const updateExpressionValue = (expression: string, value: unknown) => {
+ const dataSources = $dataSources.get();
+ // when expression contains only reference to variable update that variable
+ // extract id without parsing expression
+ const potentialVariableId = decodeDataSourceVariable(expression);
+ if (
+ potentialVariableId !== undefined &&
+ dataSources.has(potentialVariableId)
+ ) {
+ const dataSourceId = potentialVariableId;
+ const dataSourceVariables = new Map($dataSourceVariables.get());
+ dataSourceVariables.set(dataSourceId, value);
+ $dataSourceVariables.set(dataSourceVariables);
+ }
+};
diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.tsx
index c7cab85ba7..c1df300b4a 100644
--- a/apps/builder/app/builder/features/settings-panel/variables-section.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variables-section.tsx
@@ -214,7 +214,10 @@ export const VariablesSection = () => {
</SectionTitle>
}
>
- <VariablesList />
+ {/* prevent applyig gap to list items */}
+ <div>
+ <VariablesList />
+ </div>
</CollapsibleSectionBase>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/variables.stories.tsx b/apps/builder/app/builder/features/settings-panel/variables.stories.tsx
deleted file mode 100644
index 141f2050a2..0000000000
--- a/apps/builder/app/builder/features/settings-panel/variables.stories.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import type { Meta, StoryObj } from "@storybook/react";
-import { useState } from "react";
-import {
- Button,
- FloatingPanelPopover,
- FloatingPanelPopoverContent,
- FloatingPanelPopoverTrigger,
-} from "@webstudio-is/design-system";
-import { VariablesPanel } from "./variables";
-import {
- $pages,
- $selectedInstanceSelector,
- $selectedPageId,
- $props,
- $instances,
-} from "~/shared/nano-states";
-import { registerContainers } from "~/shared/sync";
-import type { Page } from "@webstudio-is/sdk";
-
-export default {
- title: "Builder/Variables",
- component: VariablesPanel,
-} satisfies Meta;
-
-registerContainers();
-$selectedInstanceSelector.set(["root"]);
-$instances.set(
- new Map([
- ["root", { id: "root", type: "instance", component: "Box", children: [] }],
- ])
-);
-$selectedPageId.set("home");
-$pages.set({
- homePage: { id: "home", rootInstanceId: "root" } as Page,
- pages: [],
-});
-
-const initialProp = {
- id: "my-prop",
- instanceId: "#",
- name: "my-prop",
- type: "string",
- value: "initial",
-} as const;
-$props.set(new Map([[initialProp.id, initialProp]]));
-
-const VariablesPopover = () => {
- const [isOpen, setIsOpen] = useState(true);
- return (
- <FloatingPanelPopover open={isOpen} onOpenChange={setIsOpen}>
- <FloatingPanelPopoverTrigger asChild>
- <Button>Open variables panel</Button>
- </FloatingPanelPopoverTrigger>
- <FloatingPanelPopoverContent align="start">
- <VariablesPanel
- propId="my-prop"
- propName="my-prop"
- propMeta={{
- required: false,
- control: "text",
- type: "string",
- defaultValue: "initial",
- }}
- />
- </FloatingPanelPopoverContent>
- </FloatingPanelPopover>
- );
-};
-
-export const Variables: StoryObj = {
- render: () => <VariablesPopover />,
-};
diff --git a/apps/builder/app/builder/features/settings-panel/variables.tsx b/apps/builder/app/builder/features/settings-panel/variables.tsx
deleted file mode 100644
index 8f795955cc..0000000000
--- a/apps/builder/app/builder/features/settings-panel/variables.tsx
+++ /dev/null
@@ -1,492 +0,0 @@
-import { useMemo, useState } from "react";
-import { nanoid } from "nanoid";
-import { computed } from "nanostores";
-import { useStore } from "@nanostores/react";
-import { isFeatureEnabled } from "@webstudio-is/feature-flags";
-import {
- Button,
- CssValueListArrowFocus,
- CssValueListItem,
- Flex,
- FloatingPanelPopover,
- FloatingPanelPopoverClose,
- FloatingPanelPopoverContent,
- FloatingPanelPopoverTitle,
- FloatingPanelPopoverTrigger,
- Label,
- ScrollArea,
- Separator,
- SmallIconButton,
- Text,
- Tooltip,
- theme,
-} from "@webstudio-is/design-system";
-import {
- DotIcon,
- MenuIcon,
- MinusIcon,
- PlusIcon,
- TrashIcon,
-} from "@webstudio-is/icons";
-import type { DataSource, Prop } from "@webstudio-is/sdk";
-import {
- PropMeta,
- collectionComponent,
- decodeDataSourceVariable,
- encodeDataSourceVariable,
- validateExpression,
-} from "@webstudio-is/react-sdk";
-import {
- $dataSources,
- $instances,
- $props,
- $selectedInstanceSelector,
- $variableValuesByInstanceSelector,
-} from "~/shared/nano-states";
-import { serverSyncStore } from "~/shared/sync";
-import type { PropValue } from "./shared";
-import { getStartingValue } from "./props-section/use-props-logic";
-import {
- ExpressionEditor,
- formatValuePreview,
-} from "~/builder/shared/expression-editor";
-import { VariablePopoverTrigger } from "./variable-popover";
-
-const $selectedInstanceVariables = computed(
- [$selectedInstanceSelector, $dataSources, $instances],
- (instanceSelector, dataSources, instances) => {
- const matchedVariables: DataSource[] = [];
- if (instanceSelector === undefined) {
- return matchedVariables;
- }
- for (const dataSource of dataSources.values()) {
- const [instanceId] = instanceSelector;
- // prevent showing "item" parameter on collection component
- // to avoid circular undefined variable runtime error
- if (
- dataSource.type === "parameter" &&
- instanceId === dataSource.scopeInstanceId &&
- instances.get(instanceId)?.component === collectionComponent
- ) {
- continue;
- }
- if (
- dataSource.scopeInstanceId !== undefined &&
- instanceSelector.includes(dataSource.scopeInstanceId)
- ) {
- matchedVariables.push(dataSource);
- }
- }
- return matchedVariables;
- }
-);
-
-const $selectedInstanceVariableValues = computed(
- [$selectedInstanceSelector, $variableValuesByInstanceSelector],
- (instanceSelector, variableValuesByInstanceSelector) => {
- const key = JSON.stringify(instanceSelector);
- return variableValuesByInstanceSelector.get(key) ?? new Map();
- }
-);
-
-const EmptyList = () => {
- return (
- <Flex direction="column" css={{ gap: theme.spacing[5] }}>
- <Flex justify="center" align="center" css={{ height: theme.spacing[13] }}>
- <Text variant="labelsSentenceCase">No variables yet</Text>
- </Flex>
- <Flex justify="center" align="center" css={{ height: theme.spacing[13] }}>
- <VariablePopoverTrigger>
- <Button prefix={<PlusIcon />}>Create variable</Button>
- </VariablePopoverTrigger>
- </Flex>
- </Flex>
- );
-};
-
-const $usedVariables = computed([$props], (props) => {
- const usedVariables = new Set<DataSource["id"]>();
- for (const prop of props.values()) {
- if (prop.type === "expression") {
- try {
- validateExpression(prop.value, {
- transformIdentifier: (identifier) => {
- const id = decodeDataSourceVariable(identifier);
- if (id !== undefined) {
- usedVariables.add(id);
- }
- return identifier;
- },
- });
- } catch {
- // empty block
- }
- }
- if (prop.type === "action") {
- for (const value of prop.value) {
- try {
- validateExpression(value.code, {
- effectful: true,
- transformIdentifier: (identifier) => {
- const id = decodeDataSourceVariable(identifier);
- if (id !== undefined) {
- usedVariables.add(id);
- }
- return identifier;
- },
- });
- } catch {
- // empty block
- }
- }
- }
- }
- return usedVariables;
-});
-
-const deleteVariable = (variable: DataSource) => {
- serverSyncStore.createTransaction([$dataSources], (dataSources) => {
- dataSources.delete(variable.id);
- });
-};
-
-const ListItem = ({
- index,
- selected,
- deletable,
- variable,
- value,
- onSelect,
-}: {
- index: number;
- selected: boolean;
- deletable: boolean;
- variable: DataSource;
- value: unknown;
- onSelect: (variableId: DataSource["id"]) => void;
-}) => {
- return (
- <CssValueListItem
- label={
- <Label truncate>
- {value === undefined
- ? variable.name
- : `${variable.name}: ${formatValuePreview(value)}`}
- </Label>
- }
- id={variable.id}
- index={index}
- active={selected}
- buttons={
- <>
- <Tooltip content="Edit variable" side="bottom" asChild>
- <VariablePopoverTrigger variable={variable}>
- <SmallIconButton
- tabIndex={-1}
- aria-label="Edit variable"
- icon={<MenuIcon />}
- />
- </VariablePopoverTrigger>
- </Tooltip>
- <Tooltip content="Delete variable" side="bottom">
- <SmallIconButton
- tabIndex={-1}
- disabled={deletable === false}
- aria-label="Delete variable"
- variant="destructive"
- icon={<MinusIcon />}
- onClick={() => deleteVariable(variable)}
- />
- </Tooltip>
- </>
- }
- onClick={() => onSelect(variable.id)}
- />
- );
-};
-
-const getExpressionVariables = (expression: string) => {
- const variableIds = new Set<DataSource["id"]>();
- if (expression === "") {
- return variableIds;
- }
- validateExpression(expression, {
- transformIdentifier: (identifier) => {
- const id = decodeDataSourceVariable(identifier);
- if (id !== undefined) {
- variableIds.add(id);
- }
- return identifier;
- },
- });
- return variableIds;
-};
-
-const setPropValue = ({
- propId,
- propName,
- propValue,
-}: {
- propId: undefined | Prop["id"];
- propName: Prop["name"];
- propValue: PropValue;
-}) => {
- const instanceSelector = $selectedInstanceSelector.get();
- if (instanceSelector === undefined) {
- return;
- }
- const [instanceId] = instanceSelector;
-
- serverSyncStore.createTransaction([$props], (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 {
- prop = { ...prop, ...propValue };
- }
- props.set(prop.id, prop);
- });
-};
-
-const ListPanel = ({
- prop,
- onChange,
-}: {
- prop: undefined | Prop;
- onChange: (value: undefined | PropValue) => void;
-}) => {
- const matchedVariables = useStore($selectedInstanceVariables);
- const propExpression = prop?.type === "expression" ? prop?.value ?? "" : "";
- const exoressionVariables = useMemo(
- () => getExpressionVariables(propExpression),
- [propExpression]
- );
- const usedVariables = useStore($usedVariables);
- const [expression, setExpression] = useState<undefined | string>();
-
- const variableValues = useStore($selectedInstanceVariableValues);
- const editorScope = useMemo(() => {
- const scope: Record<string, unknown> = {};
- for (const [variableId, variableValue] of variableValues) {
- scope[encodeDataSourceVariable(variableId)] = variableValue;
- }
- return scope;
- }, [variableValues]);
- const editorAliases = useMemo(() => {
- const aliases = new Map<string, string>();
- for (const variable of matchedVariables) {
- aliases.set(encodeDataSourceVariable(variable.id), variable.name);
- }
- return aliases;
- }, [matchedVariables]);
-
- return (
- <ScrollArea
- css={{
- display: "flex",
- flexDirection: "column",
- width: theme.spacing[30],
- padding: `${theme.spacing[5]} 0 ${theme.spacing[9]}`,
- }}
- >
- {matchedVariables.length === 0 ? (
- <EmptyList />
- ) : (
- <>
- <CssValueListArrowFocus>
- {matchedVariables.map((variable, index) => (
- <ListItem
- key={variable.id}
- index={index}
- variable={variable}
- value={variableValues.get(variable.id)}
- // mark all variables used in expression as selected
- selected={exoressionVariables.has(variable.id)}
- deletable={
- variable.type === "variable" &&
- usedVariables.has(variable.id) === false
- }
- onSelect={() =>
- // convert variable to expression
- onChange({
- type: "expression",
- value: encodeDataSourceVariable(variable.id),
- })
- }
- />
- ))}
- </CssValueListArrowFocus>
- <Separator />
- <Flex
- direction="column"
- css={{
- padding: `${theme.spacing[5]} ${theme.spacing[9]} ${theme.spacing[9]}`,
- gap: theme.spacing[3],
- }}
- >
- <Label>Expression</Label>
- <ExpressionEditor
- scope={editorScope}
- aliases={editorAliases}
- value={expression ?? propExpression}
- onChange={setExpression}
- onBlur={() => {
- // skip when expression is not changed
- if (expression === undefined) {
- return;
- }
-
- if (expression.trim() === "") {
- onChange(undefined);
- setExpression(undefined);
- return;
- }
-
- try {
- validateExpression(expression, {
- transformIdentifier: (id) => {
- if (editorAliases.has(id) === false) {
- throw Error(`Unknown variable "${id}"`);
- }
- return id;
- },
- });
- } catch (error) {
- // @todo show errors
- (error as Error).message;
- return;
- }
-
- onChange({ type: "expression", value: expression });
- setExpression(undefined);
- }}
- />
- </Flex>
- </>
- )}
- </ScrollArea>
- );
-};
-
-export const VariablesPanel = ({
- propId,
- propName,
- propMeta,
-}: {
- propId: undefined | Prop["id"];
- propName: Prop["id"];
- propMeta: PropMeta;
-}) => {
- // compute prop instead of using passed one
- // because data source props are converted into values
- const prop = useStore(
- useMemo(
- () =>
- computed($props, (props) => {
- if (propId) {
- return props.get(propId);
- }
- }),
- [propId]
- )
- );
-
- const removeExpression = () => {
- // reset prop with initial value from meta
- 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([$props], (props) => {
- props.delete(propId);
- });
- }
- };
-
- return (
- <>
- <ListPanel
- prop={prop}
- onChange={(propValue) => {
- if (propValue === undefined) {
- removeExpression();
- } else {
- setPropValue({ propId, propName, propValue });
- }
- }}
- />
- {/* put after content to avoid auto focusing "New variable" button */}
- <FloatingPanelPopoverTitle
- actions={
- <>
- {prop?.type === "expression" && (
- <Tooltip content="Remove expression" side="bottom">
- {/* automatically close popover when remove expression */}
- <FloatingPanelPopoverClose asChild>
- <Button
- aria-label="Remove expression"
- prefix={<TrashIcon />}
- color="ghost"
- onClick={removeExpression}
- />
- </FloatingPanelPopoverClose>
- </Tooltip>
- )}
- <Tooltip content="New variable" side="bottom" asChild>
- <VariablePopoverTrigger>
- <Button
- aria-label="New variable"
- prefix={<PlusIcon />}
- color="ghost"
- />
- </VariablePopoverTrigger>
- </Tooltip>
- </>
- }
- >
- Variables
- </FloatingPanelPopoverTitle>
- </>
- );
-};
-
-export const VariablesButton = ({
- propId,
- propName,
- propMeta,
-}: {
- propId: undefined | Prop["id"];
- propName: Prop["name"];
- propMeta: PropMeta;
-}) => {
- if (isFeatureEnabled("bindings") === false) {
- return;
- }
- return (
- <FloatingPanelPopover modal>
- <FloatingPanelPopoverTrigger asChild>
- <SmallIconButton
- css={{
- position: "absolute",
- top: -10,
- left: -10,
- }}
- icon={<DotIcon />}
- />
- </FloatingPanelPopoverTrigger>
- <FloatingPanelPopoverContent side="left" align="start">
- <VariablesPanel
- propId={propId}
- propName={propName}
- propMeta={propMeta}
- />
- </FloatingPanelPopoverContent>
- </FloatingPanelPopover>
- );
-};
diff --git a/apps/builder/app/builder/shared/binding-popover.tsx b/apps/builder/app/builder/shared/binding-popover.tsx
index 1598fc729f..9952091172 100644
--- a/apps/builder/app/builder/shared/binding-popover.tsx
+++ b/apps/builder/app/builder/shared/binding-popover.tsx
@@ -172,13 +172,8 @@ const BindingButton = forwardRef<HTMLButtonElement>((props, ref) => (
position: "absolute",
top: 0,
left: 0,
- width: 14,
- height: 14,
- borderRadius: "50%",
- backgroundColor: "#834DF4",
- display: "flex",
- justifyContent: "center",
- alignItems: "center",
+ boxSizing: "border-box",
+ padding: 2,
transform: "translate(-50%, -50%) scale(1)",
transition: "transform 60ms",
"--dot-display": "block",
@@ -191,7 +186,17 @@ const BindingButton = forwardRef<HTMLButtonElement>((props, ref) => (
}}
{...props}
icon={
- <>
+ <Box
+ css={{
+ width: 12,
+ height: 12,
+ borderRadius: "50%",
+ backgroundColor: "#834DF4",
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ }}
+ >
<DotIcon
size={14}
fill="white"
@@ -202,7 +207,7 @@ const BindingButton = forwardRef<HTMLButtonElement>((props, ref) => (
fill="white"
style={{ display: `var(--plus-display)` }}
/>
- </>
+ </Box>
}
/>
));
@@ -213,12 +218,14 @@ export const BindingPopover = ({
aliases,
value,
onChange,
+ onRemove,
}: {
scope: Record<string, unknown>;
aliases: Map<string, string>;
acceptableType?: "text" | "any";
value: string;
onChange: (newValue: string) => void;
+ onRemove: (evaluatedValue: unknown) => void;
}) => {
const [open, onOpenChange] = useState(false);
const [error, setError] = useState<undefined | string>();
@@ -280,7 +287,7 @@ export const BindingPopover = ({
value,
scope
);
- onChange(JSON.stringify(evaluatedValue));
+ onRemove(evaluatedValue);
onOpenChange(false);
}}
/>