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: improve variable popover (#2737)

Bogdan Chadkin4f64676db784
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 c74397967a..86887992a4 100644
--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
@@ -1,6 +1,12 @@
import { computed } from "nanostores";
import { nanoid } from "nanoid";
-import { useId, useMemo, useState } from "react";
+import {
+ forwardRef,
+ useId,
+ useImperativeHandle,
+ useMemo,
+ useState,
+} from "react";
import { useStore } from "@nanostores/react";
import type { DataSource, Resource } from "@webstudio-is/sdk";
import { encodeDataSourceVariable } from "@webstudio-is/react-sdk";
@@ -9,6 +15,7 @@ import {
Button,
Flex,
Grid,
+ InputErrorsTooltip,
InputField,
Label,
Select,
@@ -30,6 +37,25 @@ import {
evaluateExpressionWithinScope,
isLiteralExpression,
} from "~/builder/shared/binding-popover";
+import {
+ type Field,
+ type ComposedFields,
+ useField,
+ composeFields,
+} from "~/shared/form-utils";
+
+const validateHeaderName = (value: string) =>
+ value.trim().length === 0 ? "Header name is required" : undefined;
+
+const validateHeaderValue = (value: string, scope: Record<string, unknown>) => {
+ const evaluatedValue = evaluateExpressionWithinScope(value, scope);
+ if (typeof evaluatedValue !== "string") {
+ return "Header value expects a string";
+ }
+ if (evaluatedValue.length === 0) {
+ return "Header value is required";
+ }
+};
const HeaderPair = ({
editorAliases,
@@ -49,6 +75,17 @@ const HeaderPair = ({
const nameId = useId();
const valueId = useId();
+ // temporary fields to validate name and value only onBlur
+ // invalid headers will be removed on save
+ const nameField = useField({
+ initialValue: name,
+ validate: validateHeaderName,
+ });
+ const valueField = useField({
+ initialValue: value,
+ validate: (value) => validateHeaderValue(value, editorScope),
+ });
+
return (
<Grid
gap={2}
@@ -64,14 +101,21 @@ const HeaderPair = ({
<Label htmlFor={nameId} css={{ gridArea: "name" }}>
Name
</Label>
- <InputField
- css={{ gridArea: "name-input" }}
- id={nameId}
- value={name}
- onChange={(event) => {
- onChange(event.target.value, value);
- }}
- />
+ <InputErrorsTooltip
+ errors={nameField.error ? [nameField.error] : undefined}
+ >
+ <InputField
+ css={{ gridArea: "name-input" }}
+ id={nameId}
+ color={nameField.error ? "error" : undefined}
+ value={name}
+ onChange={(event) => {
+ nameField.onChange(event.target.value);
+ onChange(event.target.value, value);
+ }}
+ onBlur={nameField.onBlur}
+ />
+ </InputErrorsTooltip>
<Label htmlFor={valueId} css={{ gridArea: "value" }}>
Value
</Label>
@@ -80,21 +124,34 @@ const HeaderPair = ({
scope={editorScope}
aliases={editorAliases}
value={value}
- onChange={(newValue) => onChange(name, newValue)}
- onRemove={(evaluatedValue) =>
- onChange(name, JSON.stringify(evaluatedValue))
- }
- />
- <InputField
- id={valueId}
- // expressions with variables cannot be edited
- disabled={isLiteralExpression(value) === false}
- value={String(evaluateExpressionWithinScope(value, editorScope))}
- // update text value as string literal
- onChange={(event) =>
- onChange(name, JSON.stringify(event.target.value))
- }
+ onChange={(newValue) => {
+ valueField.onChange(newValue);
+ valueField.onBlur();
+ onChange(name, newValue);
+ }}
+ onRemove={(evaluatedValue) => {
+ valueField.onChange(JSON.stringify(evaluatedValue));
+ valueField.onBlur();
+ onChange(name, JSON.stringify(evaluatedValue));
+ }}
/>
+ <InputErrorsTooltip
+ errors={valueField.error ? [valueField.error] : undefined}
+ >
+ <InputField
+ id={valueId}
+ // expressions with variables cannot be edited
+ disabled={isLiteralExpression(value) === false}
+ color={valueField.error ? "error" : undefined}
+ value={String(evaluateExpressionWithinScope(value, editorScope))}
+ // update text value as string literal
+ onChange={(event) => {
+ valueField.onChange(JSON.stringify(event.target.value));
+ onChange(name, JSON.stringify(event.target.value));
+ }}
+ onBlur={valueField.onBlur}
+ />
+ </InputErrorsTooltip>
</Box>
<Grid
@@ -209,33 +266,14 @@ const $selectedInstanceScope = computed(
}
);
-export const ResourcePanel = ({
- variable,
- onClose,
-}: {
- variable?: DataSource;
- onClose: () => void;
-}) => {
- const resources = useStore($resources);
- const resource =
- variable?.type === "resource"
- ? resources.get(variable.resourceId)
- : undefined;
-
- const nameId = useId();
- const [name, setName] = useState(variable?.name ?? "");
- const urlId = useId();
- // empty string as default
- const [url, setUrl] = useState(resource?.url ?? `""`);
- const [method, setMethod] = useState<Resource["method"]>(
- resource?.method ?? "get"
- );
- const [headers, setHeaders] = useState<Resource["headers"]>(
- resource?.headers ?? []
- );
- // empty string as default
- const [body, setBody] = useState(resource?.body ?? `""`);
+type PanelApi = ComposedFields & {
+ save: () => void;
+};
+export const ResourceForm = forwardRef<
+ undefined | PanelApi,
+ { variable?: DataSource; nameField: Field<string> }
+>(({ variable, nameField }, ref) => {
const { scope: scopeWithCurrentVariable, aliases } = useStore(
$selectedInstanceScope
);
@@ -251,44 +289,126 @@ export const ResourcePanel = ({
return newScope;
}, [scopeWithCurrentVariable, currentVariableId]);
+ const resources = useStore($resources);
+ const resource =
+ variable?.type === "resource"
+ ? resources.get(variable.resourceId)
+ : undefined;
+
+ const urlField = useField<string>({
+ initialValue: resource?.url ?? `""`,
+ validate: (value) => {
+ const evaluatedValue = evaluateExpressionWithinScope(value, scope);
+ if (typeof evaluatedValue !== "string") {
+ return "URL expects a string";
+ }
+ if (evaluatedValue.length === 0) {
+ return "URL is required";
+ }
+ },
+ });
+ const [method, setMethod] = useState<Resource["method"]>(
+ resource?.method ?? "get"
+ );
+ const headersField = useField<Resource["headers"]>({
+ initialValue: resource?.headers ?? [],
+ validate: (_value) => undefined,
+ });
+ const bodyField = useField<string>({
+ initialValue: resource?.body ?? `""`,
+ validate: (value) => {
+ const evaluatedValue = evaluateExpressionWithinScope(value, scope);
+ if (typeof evaluatedValue !== "string") {
+ return "Body expects a string";
+ }
+ },
+ });
+
+ const form = composeFields(nameField, urlField, headersField, bodyField);
+ useImperativeHandle(ref, () => ({
+ ...form,
+ save: () => {
+ const instanceSelector = $selectedInstanceSelector.get();
+ if (instanceSelector === undefined) {
+ return;
+ }
+ const [instanceId] = instanceSelector;
+ const newHeaders = headersField.value.flatMap((header) => {
+ // exclude invalid headers
+ if (
+ validateHeaderName(header.name) !== undefined ||
+ validateHeaderValue(header.value, scope) !== undefined
+ ) {
+ return [];
+ }
+ return [header];
+ });
+ // clear invalid headers on save
+ headersField.onChange(newHeaders);
+ const newResource: Resource = {
+ id: resource?.id ?? nanoid(),
+ name: nameField.value,
+ url: urlField.value,
+ method,
+ headers: newHeaders,
+ body: bodyField.value,
+ };
+ const newVariable: DataSource = {
+ id: variable?.id ?? nanoid(),
+ // preserve existing instance scope when edit
+ scopeInstanceId: variable?.scopeInstanceId ?? instanceId,
+ name: nameField.value,
+ type: "resource",
+ resourceId: newResource.id,
+ };
+ serverSyncStore.createTransaction(
+ [$dataSources, $resources],
+ (dataSources, resources) => {
+ dataSources.set(newVariable.id, newVariable);
+ resources.set(newResource.id, newResource);
+ }
+ );
+ },
+ }));
+
+ const urlId = useId();
+
return (
- <Flex
- direction="column"
- css={{
- overflow: "hidden",
- gap: theme.spacing[9],
- px: theme.spacing[9],
- pb: theme.spacing[9],
- }}
- >
- <Flex direction="column" css={{ gap: theme.spacing[3] }}>
- <Label htmlFor={nameId}>Name</Label>
- <InputField
- id={nameId}
- value={name}
- onChange={(event) => setName(event.target.value)}
- />
- </Flex>
+ <>
<Flex direction="column" css={{ gap: theme.spacing[3] }}>
<Label htmlFor={urlId}>URL</Label>
<Box css={{ position: "relative" }}>
<BindingPopover
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, scope))}
- // update text value as string literal
- onChange={(event) => setUrl(JSON.stringify(event.target.value))}
+ value={urlField.value}
+ onChange={(value) => {
+ urlField.onChange(value);
+ urlField.onBlur();
+ }}
+ onRemove={(evaluatedValue) => {
+ urlField.onChange(JSON.stringify(evaluatedValue));
+ urlField.onBlur();
+ }}
/>
+ <InputErrorsTooltip
+ errors={urlField.error ? [urlField.error] : undefined}
+ >
+ <InputField
+ id={urlId}
+ // expressions with variables cannot be edited
+ disabled={isLiteralExpression(urlField.value) === false}
+ color={urlField.error ? "error" : undefined}
+ value={String(
+ evaluateExpressionWithinScope(urlField.value, scope)
+ )}
+ // update text value as string literal
+ onChange={(event) =>
+ urlField.onChange(JSON.stringify(event.target.value))
+ }
+ onBlur={urlField.onBlur}
+ />
+ </InputErrorsTooltip>
</Box>
</Flex>
<Flex direction="column" css={{ gap: theme.spacing[3] }}>
@@ -305,8 +425,8 @@ export const ResourcePanel = ({
<Headers
editorScope={scope}
editorAliases={aliases}
- headers={headers}
- onChange={setHeaders}
+ headers={headersField.value}
+ onChange={headersField.onChange}
/>
</Flex>
{method !== "get" && (
@@ -316,65 +436,39 @@ export const ResourcePanel = ({
<BindingPopover
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, scope))}
- // update text value as string literal
- onChange={(newValue) => setBody(JSON.stringify(newValue))}
+ value={bodyField.value}
+ onChange={(value) => {
+ bodyField.onChange(value);
+ bodyField.onBlur();
+ }}
+ onRemove={(evaluatedValue) => {
+ bodyField.onChange(JSON.stringify(evaluatedValue));
+ bodyField.onBlur();
+ }}
/>
+ <InputErrorsTooltip
+ errors={bodyField.error ? [bodyField.error] : undefined}
+ >
+ <TextArea
+ autoGrow={true}
+ maxRows={10}
+ // expressions with variables cannot be edited
+ disabled={isLiteralExpression(bodyField.value) === false}
+ state={bodyField.error ? "invalid" : undefined}
+ value={String(
+ evaluateExpressionWithinScope(bodyField.value, scope)
+ )}
+ // update text value as string literal
+ onChange={(newValue) =>
+ bodyField.onChange(JSON.stringify(newValue))
+ }
+ onBlur={bodyField.onBlur}
+ />
+ </InputErrorsTooltip>
</Box>
</Flex>
)}
-
- <Flex justify="end" css={{ gap: theme.spacing[5] }}>
- <Button color="neutral" onClick={onClose}>
- Cancel
- </Button>
- <Button
- onClick={() => {
- const instanceSelector = $selectedInstanceSelector.get();
- if (instanceSelector === undefined) {
- return;
- }
- const [instanceId] = instanceSelector;
- const newResource: Resource = {
- id: resource?.id ?? nanoid(),
- name,
- url,
- method,
- headers,
- body,
- };
- const newVariable: DataSource = {
- id: variable?.id ?? nanoid(),
- // preserve existing instance scope when edit
- scopeInstanceId: variable?.scopeInstanceId ?? instanceId,
- name,
- type: "resource",
- resourceId: newResource.id,
- };
- serverSyncStore.createTransaction(
- [$dataSources, $resources],
- (dataSources, resources) => {
- dataSources.set(newVariable.id, newVariable);
- resources.set(newResource.id, newResource);
- }
- );
- onClose();
- }}
- >
- Save
- </Button>
- </Flex>
- </Flex>
+ </>
);
-};
+});
+ResourceForm.displayName = "ResourceForm";
diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
index d0b638af04..cec06ab005 100644
--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
@@ -1,7 +1,14 @@
import { nanoid } from "nanoid";
-import { forwardRef, useId, useState, type ReactNode } from "react";
import {
- Button,
+ forwardRef,
+ useId,
+ useState,
+ type ReactNode,
+ useImperativeHandle,
+ type Ref,
+ useRef,
+} from "react";
+import {
Flex,
FloatingPanelPopover,
FloatingPanelPopoverContent,
@@ -10,11 +17,9 @@ import {
InputErrorsTooltip,
InputField,
Label,
- PanelTabs,
- PanelTabsContent,
- PanelTabsList,
- PanelTabsTrigger,
ScrollArea,
+ Select,
+ Switch,
theme,
} from "@webstudio-is/design-system";
import { validateExpression } from "@webstudio-is/react-sdk";
@@ -29,15 +34,26 @@ import {
$selectedInstanceSelector,
} from "~/shared/nano-states";
import { serverSyncStore } from "~/shared/sync";
-import { ResourcePanel } from "./resource-panel";
+import { humanizeString } from "~/shared/string-utils";
+import {
+ useField,
+ type Field,
+ composeFields,
+ type ComposedFields,
+} from "~/shared/form-utils";
+import { ResourceForm } from "./resource-panel";
/**
* convert value expression to js value
* validating out accessing any identifier
*/
-const parseVariableValue = (code: string) => {
+const parseJsonValue = (code: string) => {
const result: { value?: unknown; error?: string } = {};
const ids = new Set<string>();
+ if (code.trim().length === 0) {
+ result.error = "Value is required";
+ return result;
+ }
try {
code = validateExpression(code, {
optional: true,
@@ -64,193 +80,414 @@ const parseVariableValue = (code: string) => {
return result;
};
-const renameVariable = (variable: DataSource, name: string) => {
- serverSyncStore.createTransaction([$dataSources], (dataSources) => {
- dataSources.set(variable.id, { ...variable, name });
- });
+type VariableType =
+ | "string"
+ | "number"
+ | "boolean"
+ | "json"
+ | "resource"
+ | "parameter";
+
+type PanelApi = ComposedFields & {
+ save: () => void;
};
-const saveVariable = (
- dataSource: undefined | DataSource,
- name: string,
- valueString: string
-): undefined | { error?: string } => {
- const dataSourceId = dataSource?.id ?? nanoid();
- const { value, error } = parseVariableValue(valueString);
- if (error !== undefined) {
- return { error };
- }
- const instanceSelector = $selectedInstanceSelector.get();
- if (instanceSelector === undefined) {
- return;
- }
- const [instanceId] = instanceSelector;
- let variableValue: Extract<DataSource, { type: "variable" }>["value"] = {
- type: "json",
- value,
- };
- if (typeof value === "string") {
- variableValue = { type: "string", value };
- }
- if (typeof value === "number") {
- variableValue = { type: "number", value };
- }
- if (typeof value === "boolean") {
- variableValue = { type: "boolean", value };
- }
- serverSyncStore.createTransaction(
- [$dataSources, $resources],
- (dataSources, resources) => {
- // cleanup resource when value variable is set
- if (dataSource?.type === "resource") {
- resources.delete(dataSource.resourceId);
+const ParameterForm = forwardRef<
+ undefined | PanelApi,
+ { variable?: DataSource; nameField: Field<string> }
+>(({ variable, nameField }, ref) => {
+ const form = composeFields(nameField);
+ useImperativeHandle(ref, () => ({
+ ...form,
+ save: () => {
+ // only existing parameter variables can be renamed
+ if (variable === undefined) {
+ return;
}
- dataSources.set(dataSourceId, {
- id: dataSourceId,
- // preserve existing instance scope when edit
- scopeInstanceId:
- dataSources.get(dataSourceId)?.scopeInstanceId ?? instanceId,
- name,
- type: "variable",
- value: variableValue,
+ const name = nameField.value;
+ serverSyncStore.createTransaction([$dataSources], (dataSources) => {
+ dataSources.set(variable.id, { ...variable, name });
});
- }
- );
-};
+ },
+ }));
+ return <></>;
+});
+ParameterForm.displayName = "ParameterForm";
-const VariableValuePanel = ({
+const useValuePanelRef = ({
+ ref,
variable,
- onClose,
+ form,
+ name,
+ variableValue,
}: {
+ ref: Ref<undefined | PanelApi>;
variable?: DataSource;
- onClose: () => void;
+ form: ComposedFields;
+ name: string;
+ variableValue: Extract<DataSource, { type: "variable" }>["value"];
}) => {
- // variable value cannot have an access to other variables
- const nameId = useId();
- const [name, setName] = useState(variable?.name ?? "");
- const [nameErrors, setNameErrors] = useState<undefined | string[]>();
+ useImperativeHandle(ref, () => ({
+ ...form,
+ save: () => {
+ const instanceSelector = $selectedInstanceSelector.get();
+ if (instanceSelector === undefined) {
+ return;
+ }
+ const [instanceId] = instanceSelector;
+ const dataSourceId = variable?.id ?? nanoid();
+ // preserve existing instance scope when edit
+ const scopeInstanceId = variable?.scopeInstanceId ?? instanceId;
+ serverSyncStore.createTransaction(
+ [$dataSources, $resources],
+ (dataSources, resources) => {
+ // cleanup resource when value variable is set
+ if (variable?.type === "resource") {
+ resources.delete(variable.resourceId);
+ }
+ dataSources.set(dataSourceId, {
+ id: dataSourceId,
+ scopeInstanceId,
+ name,
+ type: "variable",
+ value: variableValue,
+ });
+ }
+ );
+ },
+ }));
+};
+
+const StringForm = forwardRef<
+ undefined | PanelApi,
+ { variable?: DataSource; nameField: Field<string> }
+>(({ variable, nameField }, ref) => {
const [value, setValue] = useState(
- formatValue(
- variable?.type === "variable" ? variable?.value.value ?? "" : ""
- )
+ variable?.type === "variable" && variable.value.type === "string"
+ ? variable.value.value
+ : ""
+ );
+ const form = composeFields(nameField);
+ useValuePanelRef({
+ ref,
+ variable,
+ form,
+ name: nameField.value,
+ variableValue: { type: "string", value },
+ });
+ const valueId = useId();
+ return (
+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>
+ <Label htmlFor={valueId}>Value</Label>
+ <InputField
+ id={valueId}
+ value={value}
+ onChange={(event) => setValue(event.target.value)}
+ />
+ </Flex>
);
- const [valueErrors, setValueErrors] = useState<undefined | string[]>();
+});
+StringForm.displayName = "StringForm";
+const NumberForm = forwardRef<
+ undefined | PanelApi,
+ { variable?: DataSource; nameField: Field<string> }
+>(({ variable, nameField }, ref) => {
+ const valueField = useField<number | string>({
+ initialValue:
+ variable?.type === "variable" && variable.value.type === "number"
+ ? variable.value.value
+ : "",
+ validate: (value) => {
+ if (typeof value === "string" && value.length === 0) {
+ return "Value expects a number";
+ }
+ const number = Number(value);
+ return Number.isNaN(number) ? "Invalid number" : undefined;
+ },
+ });
+ const form = composeFields(nameField, valueField);
+ useValuePanelRef({
+ ref,
+ variable,
+ form,
+ name: nameField.value,
+ variableValue: { type: "number", value: Number(valueField.value) },
+ });
+ const valueId = useId();
return (
- <Flex
- direction="column"
- css={{
- overflow: "hidden",
- gap: theme.spacing[9],
- px: theme.spacing[9],
- pb: theme.spacing[9],
- }}
- >
- <Flex direction="column" css={{ gap: theme.spacing[3] }}>
- <Label htmlFor={nameId}>Name</Label>
- <InputErrorsTooltip errors={nameErrors}>
- <InputField
- id={nameId}
- value={name}
- onChange={(event) => setName(event.target.value)}
- />
- </InputErrorsTooltip>
- </Flex>
- {/* resource variable can be replaced with value variable
- parameters can change only name */}
- {variable?.type !== "parameter" && (
- <Flex direction="column" css={{ gap: theme.spacing[3] }}>
- <Label>Value</Label>
- <InputErrorsTooltip errors={valueErrors}>
- <div>
- <ExpressionEditor value={value} onChange={setValue} />
- </div>
- </InputErrorsTooltip>
- </Flex>
- )}
- <Flex justify="end" css={{ gap: theme.spacing[5] }}>
- <Button color="neutral" onClick={onClose}>
- Cancel
- </Button>
- <Button
- onClick={() => {
- if (name.length === 0) {
- setNameErrors([`Variable name is required`]);
- return;
- }
- if (variable?.type === "parameter") {
- renameVariable(variable, name);
- onClose();
- }
- // save value variable and convert from resource variable if necessary
- const result = saveVariable(variable, name, value);
- if (result?.error !== undefined) {
- setValueErrors([result.error]);
- return;
- }
- onClose();
+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>
+ <Label htmlFor={valueId}>Value</Label>
+ <InputErrorsTooltip
+ errors={valueField.error ? [valueField.error] : undefined}
+ >
+ <InputField
+ id={valueId}
+ type="number"
+ color={valueField.error ? "error" : undefined}
+ value={valueField.value}
+ onChange={(event) => {
+ valueField.onChange(
+ Number.isNaN(event.target.valueAsNumber)
+ ? event.target.value
+ : event.target.valueAsNumber
+ );
}}
- >
- Save
- </Button>
- </Flex>
+ onBlur={valueField.onBlur}
+ />
+ </InputErrorsTooltip>
</Flex>
);
-};
+});
+NumberForm.displayName = "NumberForm";
-const VariablePanel = ({
- variable,
- onClose,
-}: {
- variable?: DataSource;
- onClose: () => void;
-}) => {
- const [tab, setTab] = useState(
- variable?.type === "resource" ? "resource" : "value"
+const BooleanForm = forwardRef<
+ undefined | PanelApi,
+ { variable?: DataSource; nameField: Field<string> }
+>(({ variable, nameField }, ref) => {
+ const [value, setValue] = useState(
+ variable?.type === "variable" && variable.value.type === "boolean"
+ ? variable.value.value
+ : false
+ );
+ const form = composeFields(nameField);
+ useValuePanelRef({
+ ref,
+ variable,
+ form,
+ name: nameField.value,
+ variableValue: { type: "boolean", value },
+ });
+ const valueId = useId();
+ return (
+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>
+ <Label htmlFor={valueId}>Value</Label>
+ <Switch id={valueId} checked={value} onCheckedChange={setValue} />
+ </Flex>
);
+});
+BooleanForm.displayName = "BooleanForm";
+const JsonForm = forwardRef<
+ undefined | PanelApi,
+ { variable?: DataSource; nameField: Field<string> }
+>(({ variable, nameField }, ref) => {
+ const valueField = useField<string>({
+ initialValue:
+ variable?.type === "variable" &&
+ (variable.value.type === "json" || variable.value.type === "string[]")
+ ? formatValue(variable.value.value)
+ : ``,
+ validate: (value) => parseJsonValue(value).error,
+ });
+ const form = composeFields(nameField, valueField);
+ useValuePanelRef({
+ ref,
+ variable,
+ form,
+ name: nameField.value,
+ variableValue: {
+ type: "json",
+ value: parseJsonValue(valueField.value).value,
+ },
+ });
return (
- <PanelTabs value={tab} onValueChange={setTab} asChild>
- <Flex direction="column">
- <ScrollArea
- css={{
- // flex fixes content overflowing artificial scroll area
- display: "flex",
- flexDirection: "column",
- width: theme.spacing[30],
- }}
- >
- {/* user can change only parameter name */}
- {variable?.type !== "parameter" && (
- <PanelTabsList>
- <PanelTabsTrigger value="value">Value</PanelTabsTrigger>
- <PanelTabsTrigger value="resource">Resource</PanelTabsTrigger>
- </PanelTabsList>
- )}
- <PanelTabsContent value="value">
- <VariableValuePanel variable={variable} onClose={onClose} />
- </PanelTabsContent>
- <PanelTabsContent value="resource">
- <ResourcePanel variable={variable} onClose={onClose} />
- </PanelTabsContent>
- </ScrollArea>
- </Flex>
- </PanelTabs>
+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>
+ <Label>Value</Label>
+ <InputErrorsTooltip
+ errors={valueField.error ? [valueField.error] : undefined}
+ >
+ {/* use div to position tooltip */}
+ <div>
+ <ExpressionEditor
+ color={valueField.error ? "error" : undefined}
+ value={valueField.value}
+ onChange={valueField.onChange}
+ onBlur={valueField.onBlur}
+ />
+ </div>
+ </InputErrorsTooltip>
+ </Flex>
+ );
+});
+JsonForm.displayName = "JsonForm";
+
+const VariablePanel = forwardRef<
+ undefined | PanelApi,
+ {
+ variable?: DataSource;
+ }
+>(({ variable }, ref) => {
+ const nameField = useField({
+ initialValue: variable?.name ?? "",
+ validate: (value) =>
+ value.trim().length === 0 ? "Name is required" : undefined,
+ });
+ const nameId = useId();
+ const nameFieldElement = (
+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>
+ <Label htmlFor={nameId}>Name</Label>
+ <InputErrorsTooltip
+ errors={nameField.error ? [nameField.error] : undefined}
+ >
+ <InputField
+ id={nameId}
+ color={nameField.error ? "error" : undefined}
+ value={nameField.value}
+ onChange={(event) => nameField.onChange(event.target.value)}
+ onBlur={nameField.onBlur}
+ />
+ </InputErrorsTooltip>
+ </Flex>
+ );
+
+ const [type, setType] = useState<VariableType>(() => {
+ if (variable?.type === "parameter" || variable?.type === "resource") {
+ return variable.type;
+ }
+ if (variable?.type === "variable") {
+ const type = variable.value.type;
+ if (type === "string" || type === "number" || type === "boolean") {
+ return type;
+ }
+ return "json";
+ }
+ return "string";
+ });
+ const typeFieldElement = (
+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>
+ <Label>Type</Label>
+ <Select<VariableType>
+ options={["string", "number", "boolean", "json", "resource"]}
+ getLabel={(value: VariableType) =>
+ value === "json" ? "JSON" : humanizeString(value)
+ }
+ value={type}
+ onChange={setType}
+ />
+ </Flex>
);
-};
+
+ if (type === "parameter") {
+ return (
+ <>
+ {nameFieldElement}
+ <ParameterForm ref={ref} variable={variable} nameField={nameField} />
+ </>
+ );
+ }
+ if (type === "string") {
+ return (
+ <>
+ {nameFieldElement}
+ {typeFieldElement}
+ <StringForm ref={ref} variable={variable} nameField={nameField} />
+ </>
+ );
+ }
+ if (type === "number") {
+ return (
+ <>
+ {nameFieldElement}
+ {typeFieldElement}
+ <NumberForm ref={ref} variable={variable} nameField={nameField} />
+ </>
+ );
+ }
+ if (type === "boolean") {
+ return (
+ <>
+ {nameFieldElement}
+ {typeFieldElement}
+ <BooleanForm ref={ref} variable={variable} nameField={nameField} />
+ </>
+ );
+ }
+ if (type === "json") {
+ return (
+ <>
+ {nameFieldElement}
+ {typeFieldElement}
+ <JsonForm ref={ref} variable={variable} nameField={nameField} />
+ </>
+ );
+ }
+ if (type === "resource") {
+ return (
+ <>
+ {nameFieldElement}
+ {typeFieldElement}
+ <ResourceForm ref={ref} variable={variable} nameField={nameField} />
+ </>
+ );
+ }
+});
+VariablePanel.displayName = "VariablePanel";
export const VariablePopoverTrigger = forwardRef<
HTMLButtonElement,
{ variable?: DataSource; children: ReactNode }
>(({ variable, children }, ref) => {
const [open, setOpen] = useState(false);
+ const panelRef = useRef<undefined | PanelApi>();
+ const saveAndClose = () => {
+ if (panelRef.current) {
+ if (panelRef.current.allErrorsVisible === false) {
+ panelRef.current.showAllErrors();
+ return;
+ }
+ if (panelRef.current.valid) {
+ panelRef.current.save();
+ }
+ }
+ setOpen(false);
+ };
return (
- <FloatingPanelPopover modal open={open} onOpenChange={setOpen}>
+ <FloatingPanelPopover
+ modal
+ open={open}
+ onOpenChange={(newOpen) => {
+ if (newOpen === false) {
+ saveAndClose();
+ return;
+ }
+ setOpen(newOpen);
+ }}
+ >
<FloatingPanelPopoverTrigger ref={ref} asChild>
{children}
</FloatingPanelPopoverTrigger>
<FloatingPanelPopoverContent side="left" align="start">
- <VariablePanel variable={variable} onClose={() => setOpen(false)} />
+ <ScrollArea
+ css={{
+ // flex fixes content overflowing artificial scroll area
+ display: "flex",
+ flexDirection: "column",
+ width: theme.spacing[30],
+ }}
+ >
+ <Flex
+ direction="column"
+ css={{
+ overflow: "hidden",
+ gap: theme.spacing[9],
+ pt: theme.spacing[5],
+ px: theme.spacing[9],
+ pb: theme.spacing[9],
+ }}
+ >
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ saveAndClose();
+ }}
+ >
+ {/* submit is not triggered when press enter on input without submit button */}
+ <button style={{ display: "none" }}>submit</button>
+ <VariablePanel ref={panelRef} variable={variable} />
+ </form>
+ </Flex>
+ </ScrollArea>
{/* put after content to avoid auto focusing "Close" button */}
{variable === undefined ? (
<FloatingPanelPopoverTitle>New Variable</FloatingPanelPopoverTitle>
diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsx
index 1c5643b265..3e36b884eb 100644
--- a/apps/builder/app/builder/shared/expression-editor.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.tsx
@@ -53,9 +53,6 @@ export const formatValuePreview = (value: unknown) => {
if (Number.isNaN(value)) {
return "nan";
}
- if (Array.isArray(value)) {
- return "array";
- }
if (typeof value === "number") {
return value.toString();
}
@@ -68,7 +65,7 @@ export const formatValuePreview = (value: unknown) => {
if (value === null) {
return "null";
}
- return typeof value;
+ return "JSON";
};
type Scope = Record<string, unknown>;
diff --git a/apps/builder/app/shared/form-utils/form-utils.ts b/apps/builder/app/shared/form-utils/form-utils.ts
new file mode 100644
index 0000000000..8c83d325eb
--- /dev/null
+++ b/apps/builder/app/shared/form-utils/form-utils.ts
@@ -0,0 +1,61 @@
+import { useState } from "react";
+
+export type Field<Type> = {
+ value: Type;
+ error: undefined | string;
+ isErrorVisible: boolean;
+ valid: boolean;
+ onChange: (value: Type) => void;
+ onBlur: () => void;
+};
+
+export const useField = <Type>({
+ initialValue,
+ validate,
+}: {
+ initialValue: Type;
+ validate: (value: Type) => undefined | string;
+}): Field<Type> => {
+ const [value, setValue] = useState(initialValue);
+ const [touched, setTouched] = useState(false);
+ const error = validate?.(value);
+ return {
+ value,
+ // show error only when user stop interactinig with control
+ error: touched ? error : undefined,
+ // inform when user see the error and not need to trigger it
+ isErrorVisible: error === undefined || touched,
+ valid: error === undefined,
+ // hide error when user is typing
+ onChange: (value) => {
+ setValue(value);
+ setTouched(false);
+ },
+ // show error when user focus on another control
+ onBlur: () => {
+ setTouched(true);
+ },
+ };
+};
+
+export type ComposedFields = {
+ valid: boolean;
+ allErrorsVisible: boolean;
+ showAllErrors: () => void;
+};
+
+export const composeFields = (
+ // allow passing fields with more tight types
+ // by ensuring their onChange will not refine
+ ...fields: Omit<Field<unknown>, "onChange">[]
+): ComposedFields => {
+ return {
+ valid: fields.every((field) => field.valid),
+ allErrorsVisible: fields.every((field) => field.isErrorVisible),
+ showAllErrors: () => {
+ for (const field of fields) {
+ field.onBlur();
+ }
+ },
+ };
+};
diff --git a/apps/builder/app/shared/form-utils/index.ts b/apps/builder/app/shared/form-utils/index.ts
index 1851921d4f..cd24cd8dd8 100644
--- a/apps/builder/app/shared/form-utils/index.ts
+++ b/apps/builder/app/shared/form-utils/index.ts
@@ -1 +1,2 @@
export * from "./use-ids";
+export * from "./form-utils";