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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: add binding popover (#2719)
Bogdan Chadkina5bc12ed2c9d
diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsxindex 3c5ed5c60d..7ab3149043 100644--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx@@ -1,7 +1,9 @@+import { computed } from "nanostores";import { nanoid } from "nanoid";import { useId, useMemo, useState } from "react";import { useStore } from "@nanostores/react";import type { DataSource, Resource } from "@webstudio-is/sdk";+import { encodeDataSourceVariable } from "@webstudio-is/react-sdk";import {Box,Button,@@ -11,6 +13,7 @@ import {Label,Select,SmallIconButton,+ TextArea,theme,} from "@webstudio-is/design-system";import { DeleteIcon, PlusIcon } from "@webstudio-is/icons";@@ -23,11 +26,20 @@ import {$selectedPage,$variableValuesByInstanceSelector,} from "~/shared/nano-states";-import { ExpressionEditor } from "~/builder/shared/expression-editor";-import { encodeDataSourceVariable } from "@webstudio-is/react-sdk";-import { computed } from "nanostores";+import {+ BindingPopover,+ evaluateExpressionWithinScope,+ isLiteralExpression,+} from "~/builder/shared/binding-popover";-const HeaderPair = (props: {+const HeaderPair = ({+ editorAliases,+ editorScope,+ name,+ value,+ onChange,+ onDelete,+}: {editorAliases: Map<string, string>;editorScope: Record<string, unknown>;name: string;@@ -36,6 +48,7 @@ const HeaderPair = (props: {onDelete: () => void;}) => {const nameId = useId();+ const valueId = useId();return (<Grid@@ -55,18 +68,30 @@ const HeaderPair = (props: {<InputFieldcss={{ gridArea: "name-input" }}id={nameId}- value={props.name}+ value={name}onChange={(event) => {- props.onChange(event.target.value, props.value);+ onChange(event.target.value, value);}}/>- <Label css={{ gridArea: "value" }}>Value (Expression)</Label>- <Box css={{ gridArea: "value-input" }}>- <ExpressionEditor- scope={props.editorScope}- aliases={props.editorAliases}- value={props.value}- onChange={(newValue) => props.onChange(props.name, newValue)}+ <Label htmlFor={valueId} css={{ gridArea: "value" }}>+ Value+ </Label>+ <Box css={{ gridArea: "value-input", position: "relative" }}>+ <BindingPopover+ scope={editorScope}+ aliases={editorAliases}+ value={value}+ onChange={(newValue) => onChange(name, newValue)}+ />+ <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))+ }/></Box>@@ -90,7 +115,7 @@ const HeaderPair = (props: {<SmallIconButtonvariant="destructive"icon={<DeleteIcon />}- onClick={props.onDelete}+ onClick={onDelete}/><svgxmlns="http://www.w3.org/2000/svg"@@ -144,7 +169,8 @@ const Headers = ({css={{ justifySelf: "center" }}prefix={<PlusIcon />}onClick={() => {- const newHeaders = [...headers, { name: "", value: "" }];+ // use empty string expression as default+ const newHeaders = [...headers, { name: "", value: `""` }];onChange(newHeaders);}}>@@ -206,14 +232,17 @@ export const ResourcePanel = ({const nameId = useId();const [name, setName] = useState(variable?.name ?? "");- const [url, setUrl] = useState(resource?.url ?? "");+ 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 ?? []);- const [body, setBody] = useState(resource?.body ?? "");+ // empty string as default+ const [body, setBody] = useState(resource?.body ?? `""`);const matchedVariables = useStore($selectedInstanceVariables);const variableValues = useStore($selectedInstanceVariableValues);@@ -257,13 +286,23 @@ export const ResourcePanel = ({/></Flex><Flex direction="column" css={{ gap: theme.spacing[3] }}>- <Label>URL (Expression)</Label>- <ExpressionEditor- scope={editorScope}- aliases={editorAliases}- value={url}- onChange={setUrl}- />+ <Label htmlFor={urlId}>URL</Label>+ <Box css={{ position: "relative" }}>+ <BindingPopover+ scope={editorScope}+ aliases={editorAliases}+ value={url}+ onChange={setUrl}+ />+ <InputField+ id={urlId}+ // expressions with variables cannot be edited+ disabled={isLiteralExpression(url) === false}+ value={String(evaluateExpressionWithinScope(url, editorScope))}+ // update text value as string literal+ onChange={(event) => setUrl(JSON.stringify(event.target.value))}+ />+ </Box></Flex><Flex direction="column" css={{ gap: theme.spacing[3] }}><Label>Method</Label>@@ -285,13 +324,24 @@ export const ResourcePanel = ({</Flex>{method !== "get" && (<Flex direction="column" css={{ gap: theme.spacing[3] }}>- <Label>Body (Expression)</Label>- <ExpressionEditor- scope={editorScope}- aliases={editorAliases}- value={body}- onChange={setBody}- />+ <Label>Body</Label>+ <Box css={{ position: "relative" }}>+ <BindingPopover+ scope={editorScope}+ aliases={editorAliases}+ value={body}+ onChange={setBody}+ />+ <TextArea+ autoGrow={true}+ maxRows={10}+ // expressions with variables cannot be edited+ disabled={isLiteralExpression(body) === false}+ value={String(evaluateExpressionWithinScope(body, editorScope))}+ // update text value as string literal+ onChange={(newValue) => setBody(JSON.stringify(newValue))}+ />+ </Box></Flex>)}diff --git a/apps/builder/app/builder/features/settings-panel/variables.stories.tsx b/apps/builder/app/builder/features/settings-panel/variables.stories.tsxindex a5c9e4464b..141f2050a2 100644--- a/apps/builder/app/builder/features/settings-panel/variables.stories.tsx+++ b/apps/builder/app/builder/features/settings-panel/variables.stories.tsx@@ -8,10 +8,14 @@ import {} from "@webstudio-is/design-system";import { VariablesPanel } from "./variables";import {- propsStore,- selectedInstanceSelectorStore,+ $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",@@ -19,7 +23,17 @@ export default {} satisfies Meta;registerContainers();-selectedInstanceSelectorStore.set(["root"]);+$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",@@ -28,7 +42,7 @@ const initialProp = {type: "string",value: "initial",} as const;-propsStore.set(new Map([[initialProp.id, initialProp]]));+$props.set(new Map([[initialProp.id, initialProp]]));const VariablesPopover = () => {const [isOpen, setIsOpen] = useState(true);diff --git a/apps/builder/app/builder/shared/binding-popover.tsx b/apps/builder/app/builder/shared/binding-popover.tsxnew file mode 100644index 0000000000..1598fc729f--- /dev/null+++ b/apps/builder/app/builder/shared/binding-popover.tsx@@ -0,0 +1,296 @@+import { forwardRef, useMemo, useRef, useState } from "react";+import { isFeatureEnabled } from "@webstudio-is/feature-flags";+import { DotIcon, PlusIcon, TrashIcon } from "@webstudio-is/icons";+import {+ Box,+ Button,+ CssValueListArrowFocus,+ CssValueListItem,+ FloatingPanelPopover,+ FloatingPanelPopoverClose,+ FloatingPanelPopoverContent,+ FloatingPanelPopoverTitle,+ FloatingPanelPopoverTrigger,+ InputErrorsTooltip,+ Label,+ ScrollArea,+ SmallIconButton,+ Tooltip,+ theme,+} from "@webstudio-is/design-system";+import { validateExpression } from "@webstudio-is/react-sdk";+import { ExpressionEditor, formatValuePreview } from "./expression-editor";++export const evaluateExpressionWithinScope = (+ expression: string,+ scope: Record<string, unknown>+) => {+ let expressionWithScope = "";+ for (const [name, value] of Object.entries(scope)) {+ expressionWithScope += `const ${name} = ${JSON.stringify(value)};\n`;+ }+ expressionWithScope += `return (${expression})`;+ try {+ const fn = new Function(expressionWithScope);+ return fn();+ } catch {+ //+ }+};++/**+ * execute valid expression without scope+ * to check any variable usage+ */+export const isLiteralExpression = (expression: string) => {+ try {+ const fn = new Function(`return (${expression})`);+ fn();+ return true;+ } catch {+ return false;+ }+};++const getUsedIdentifiers = (expression: string) => {+ const identifiers = new Set<string>();+ // prevent parsing empty expression+ if (expression === "") {+ return identifiers;+ }+ // avoid parsing error+ try {+ validateExpression(expression, {+ transformIdentifier: (identifier) => {+ identifiers.add(identifier);+ return identifier;+ },+ });+ } catch {+ //+ }+ return identifiers;+};++const BindingPanel = ({+ scope,+ aliases,+ error,+ value,+ onChange,+ onPotentialErrorChange,+ onValidate,+}: {+ scope: Record<string, unknown>;+ aliases: Map<string, string>;+ error: undefined | string;+ value: string;+ onChange: (newValue: string) => void;+ onPotentialErrorChange: (error: string) => void;+ onValidate: () => void;+}) => {+ const [expression, setExpression] = useState(value);+ const usedIdentifiers = useMemo(() => getUsedIdentifiers(value), [value]);++ const updateExpression = (newExpression: string) => {+ setExpression(newExpression);+ try {+ if (newExpression.trim().length === 0) {+ throw Error("Cannot use empty expression");+ }+ // update value only when expression is valid+ validateExpression(newExpression, {+ transformIdentifier: (identifier) => {+ if (aliases.has(identifier) === false) {+ throw Error(`Unknown variable "${identifier}"`);+ }+ return identifier;+ },+ });+ onChange(newExpression);+ } catch (error) {+ onPotentialErrorChange((error as Error).message);+ }+ };++ return (+ <ScrollArea+ css={{+ display: "flex",+ flexDirection: "column",+ width: theme.spacing[30],+ }}+ >+ <Box css={{ padding: `${theme.spacing[5]} 0` }}>+ <CssValueListArrowFocus>+ {Object.entries(scope).map(([identifier, value], index) => {+ const name = aliases.get(identifier);+ const label =+ value === undefined+ ? name+ : `${name}: ${formatValuePreview(value)}`;+ return (+ <CssValueListItem+ key={identifier}+ id={identifier}+ index={index}+ label={<Label truncate>{label}</Label>}+ // mark all variables used in expression as selected+ active={usedIdentifiers.has(identifier)}+ // convert variable to expression+ onClick={() => {+ setExpression(identifier);+ onChange(identifier);+ }}+ />+ );+ })}+ </CssValueListArrowFocus>+ </Box>+ <Box css={{ padding: `0 ${theme.spacing[9]} ${theme.spacing[9]}` }}>+ <InputErrorsTooltip errors={error ? [error] : undefined}>+ <div>+ <ExpressionEditor+ scope={scope}+ aliases={aliases}+ autoFocus={true}+ value={expression}+ onChange={updateExpression}+ onBlur={onValidate}+ />+ </div>+ </InputErrorsTooltip>+ </Box>+ </ScrollArea>+ );+};++const BindingButton = forwardRef<HTMLButtonElement>((props, ref) => (+ <SmallIconButton+ ref={ref}+ css={{+ position: "absolute",+ top: 0,+ left: 0,+ width: 14,+ height: 14,+ borderRadius: "50%",+ backgroundColor: "#834DF4",+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ transform: "translate(-50%, -50%) scale(1)",+ transition: "transform 60ms",+ "--dot-display": "block",+ "--plus-display": "none",+ "&:hover, &[aria-expanded=true]": {+ transform: `translate(-50%, -50%) scale(1.5)`,+ "--dot-display": "none",+ "--plus-display": "block",+ },+ }}+ {...props}+ icon={+ <>+ <DotIcon+ size={14}+ fill="white"+ style={{ display: `var(--dot-display)` }}+ />+ <PlusIcon+ size={10}+ fill="white"+ style={{ display: `var(--plus-display)` }}+ />+ </>+ }+ />+));+BindingButton.displayName = "BindingButton";++export const BindingPopover = ({+ scope,+ aliases,+ value,+ onChange,+}: {+ scope: Record<string, unknown>;+ aliases: Map<string, string>;+ acceptableType?: "text" | "any";+ value: string;+ onChange: (newValue: string) => void;+}) => {+ const [open, onOpenChange] = useState(false);+ const [error, setError] = useState<undefined | string>();+ const potentialError = useRef<undefined | string>();++ if (isFeatureEnabled("bindings") === false) {+ return;+ }+ return (+ <FloatingPanelPopover+ modal+ open={open}+ onOpenChange={(newOpen) => {+ if (potentialError.current) {+ setError(potentialError.current);+ } else {+ onOpenChange(newOpen);+ }+ }}+ >+ <FloatingPanelPopoverTrigger asChild>+ <BindingButton />+ </FloatingPanelPopoverTrigger>+ <FloatingPanelPopoverContent side="top" align="start">+ <BindingPanel+ scope={scope}+ aliases={aliases}+ error={error}+ value={value}+ onChange={(newValue) => {+ potentialError.current = undefined;+ setError(undefined);+ onChange(newValue);+ }}+ onPotentialErrorChange={(error) => {+ potentialError.current = error;+ }}+ onValidate={() => {+ if (potentialError.current) {+ setError(potentialError.current);+ }+ }}+ />+ {/* put after content to avoid auto focusing heading buttons */}+ <FloatingPanelPopoverTitle+ actions={+ <Tooltip content="Reset binding" side="bottom">+ {/* automatically close popover when remove expression */}+ <FloatingPanelPopoverClose asChild>+ <Button+ aria-label="Reset binding"+ prefix={<TrashIcon />}+ color="ghost"+ onClick={() => {+ // reset error, inline variables and close dialog+ potentialError.current = undefined;+ setError(undefined);+ const evaluatedValue = evaluateExpressionWithinScope(+ value,+ scope+ );+ onChange(JSON.stringify(evaluatedValue));+ onOpenChange(false);+ }}+ />+ </FloatingPanelPopoverClose>+ </Tooltip>+ }+ >+ Binding+ </FloatingPanelPopoverTitle>+ </FloatingPanelPopoverContent>+ </FloatingPanelPopover>+ );+};diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsxindex b3d6957fec..5dd121c22d 100644--- a/apps/builder/app/builder/shared/expression-editor.tsx+++ b/apps/builder/app/builder/shared/expression-editor.tsx@@ -242,6 +242,7 @@ const emptyAliases: Aliases = new Map();export const ExpressionEditor = ({scope = emptyScope,aliases = emptyAliases,+ autoFocus = false,readOnly = false,value,onChange,@@ -255,6 +256,7 @@ export const ExpressionEditor = ({* variable aliases to show instead of $ws$dataSource$id*/aliases?: Aliases;+ autoFocus?: boolean;readOnly?: boolean;value: string;onChange: (newValue: string) => void;@@ -278,11 +280,14 @@ export const ExpressionEditor = ({doc: "",parent: editorRef.current,});+ if (autoFocus) {+ view.focus();+ }viewRef.current = view;return () => {view.destroy();};- }, []);+ }, [autoFocus]);// update extensions whenever variables data is changed