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 resource variables support in builder (#2711)
Bogdan Chadkin1a904b00b406
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex ecbc4e7196..d25dc13ac2 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -37,6 +37,7 @@ import {styleSourcesStore,stylesStore,$domains,+ $resources,} from "~/shared/nano-states";import { type Settings, useClientSettings } from "./shared/client-settings";import { getBuildUrl } from "~/shared/router-utils";@@ -249,6 +250,7 @@ export const Builder = ({assetsStore.set(new Map(assets));instancesStore.set(new Map(build.instances));dataSourcesStore.set(new Map(build.dataSources));+ $resources.set(new Map(build.resources));// props should be after data sources to compute logicpropsStore.set(new Map(build.props));pagesStore.set(build.pages);diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsxnew file mode 100644index 0000000000..3c5ed5c60d--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx@@ -0,0 +1,340 @@+import { nanoid } from "nanoid";+import { useId, useMemo, useState } from "react";+import { useStore } from "@nanostores/react";+import type { DataSource, Resource } from "@webstudio-is/sdk";+import {+ Box,+ Button,+ Flex,+ Grid,+ InputField,+ Label,+ Select,+ SmallIconButton,+ theme,+} from "@webstudio-is/design-system";+import { DeleteIcon, PlusIcon } from "@webstudio-is/icons";+import { humanizeString } from "~/shared/string-utils";+import { serverSyncStore } from "~/shared/sync";+import {+ $dataSources,+ $resources,+ $selectedInstanceSelector,+ $selectedPage,+ $variableValuesByInstanceSelector,+} from "~/shared/nano-states";+import { ExpressionEditor } from "~/builder/shared/expression-editor";+import { encodeDataSourceVariable } from "@webstudio-is/react-sdk";+import { computed } from "nanostores";++const HeaderPair = (props: {+ editorAliases: Map<string, string>;+ editorScope: Record<string, unknown>;+ name: string;+ value: string;+ onChange: (name: string, value: string) => void;+ onDelete: () => void;+}) => {+ const nameId = useId();++ return (+ <Grid+ gap={2}+ align={"center"}+ css={{+ gridTemplateColumns: `${theme.spacing[18]} 1fr 19px`,+ gridTemplateAreas: `+ "name name-input button"+ "value value-input button"+ `,+ }}+ >+ <Label htmlFor={nameId} css={{ gridArea: "name" }}>+ Name+ </Label>+ <InputField+ css={{ gridArea: "name-input" }}+ id={nameId}+ value={props.name}+ onChange={(event) => {+ props.onChange(event.target.value, props.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)}+ />+ </Box>++ <Grid+ css={{+ gridArea: "button",+ justifyItems: "center",+ gap: "2px",+ color: theme.colors.foregroundIconSecondary,+ }}+ >+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="19"+ height="11"+ viewBox="0 0 19 11"+ fill="currentColor"+ >+ <path d="M10 10.05V6.05005C10 2.73634 7.31371 0.0500488 4 0.0500488H0V1.05005H4C6.76142 1.05005 9 3.28863 9 6.05005V10.05H10Z" />+ </svg>+ <SmallIconButton+ variant="destructive"+ icon={<DeleteIcon />}+ onClick={props.onDelete}+ />+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="19"+ height="11"+ viewBox="0 0 19 11"+ fill="currentColor"+ >+ <path d="M-4.37114e-07 10.05L4 10.05C7.31371 10.05 10 7.36376 10 4.05005L10 0.0500488L9 0.0500488L9 4.05005C9 6.81147 6.76142 9.05005 4 9.05005L-3.93402e-07 9.05005L-4.37114e-07 10.05Z" />+ </svg>+ </Grid>+ </Grid>+ );+};++const Headers = ({+ editorScope,+ editorAliases,+ headers,+ onChange,+}: {+ editorAliases: Map<string, string>;+ editorScope: Record<string, unknown>;+ headers: Resource["headers"];+ onChange: (headers: Resource["headers"]) => void;+}) => {+ return (+ <Grid gap={3}>+ {headers.map((header, index) => (+ <HeaderPair+ key={index}+ editorScope={editorScope}+ editorAliases={editorAliases}+ name={header.name}+ value={header.value}+ onChange={(name, value) => {+ const newHeaders = [...headers];+ newHeaders[index] = { name, value };+ onChange(newHeaders);+ }}+ onDelete={() => {+ const newHeaders = [...headers];+ newHeaders.splice(index, 1);+ onChange(newHeaders);+ }}+ />+ ))}+ <Button+ type="button"+ color="neutral"+ css={{ justifySelf: "center" }}+ prefix={<PlusIcon />}+ onClick={() => {+ const newHeaders = [...headers, { name: "", value: "" }];+ onChange(newHeaders);+ }}+ >+ Add another header pair+ </Button>+ </Grid>+ );+};++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[] = [];+ if (instanceSelector === undefined) {+ return matchedVariables;+ }+ 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);+ }+ }+ return matchedVariables;+ }+);++export const ResourcePanel = ({+ variable,+ onCancel,+}: {+ variable?: DataSource;+ onCancel: () => 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 [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 ?? "");++ const matchedVariables = useStore($selectedInstanceVariables);+ const variableValues = useStore($selectedInstanceVariableValues);+ 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);+ }+ return aliases;+ }, [matchedVariables]);++ 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>URL (Expression)</Label>+ <ExpressionEditor+ scope={editorScope}+ aliases={editorAliases}+ value={url}+ onChange={setUrl}+ />+ </Flex>+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>+ <Label>Method</Label>+ <Select<Resource["method"]>+ options={["get", "post", "put", "delete"]}+ getLabel={humanizeString}+ value={method}+ onChange={(newValue) => setMethod(newValue)}+ />+ </Flex>+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>+ <Label>Headers</Label>+ <Headers+ editorScope={editorScope}+ editorAliases={editorAliases}+ headers={headers}+ onChange={setHeaders}+ />+ </Flex>+ {method !== "get" && (+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>+ <Label>Body (Expression)</Label>+ <ExpressionEditor+ scope={editorScope}+ aliases={editorAliases}+ value={body}+ onChange={setBody}+ />+ </Flex>+ )}++ <Flex justify="end" css={{ gap: theme.spacing[5] }}>+ <Button color="neutral" onClick={onCancel}>+ 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);+ }+ );+ onCancel();+ }}+ >+ Save+ </Button>+ </Flex>+ </Flex>+ );+};diff --git a/apps/builder/app/builder/features/settings-panel/variables.tsx b/apps/builder/app/builder/features/settings-panel/variables.tsxindex d4055ddc41..b843a38fa0 100644--- a/apps/builder/app/builder/features/settings-panel/variables.tsx+++ b/apps/builder/app/builder/features/settings-panel/variables.tsx@@ -16,6 +16,10 @@ import {InputErrorsTooltip,InputField,Label,+ PanelTabs,+ PanelTabsContent,+ PanelTabsList,+ PanelTabsTrigger,ScrollArea,Separator,SmallIconButton,@@ -42,6 +46,7 @@ import {$dataSources,$instances,$props,+ $resources,$selectedInstanceSelector,$variableValuesByInstanceSelector,} from "~/shared/nano-states";@@ -53,6 +58,7 @@ import {formatValue,formatValuePreview,} from "~/builder/shared/expression-editor";+import { ResourcePanel } from "./resource-panel";/*** convert value expression to js value@@ -94,10 +100,11 @@ const renameVariable = (variable: DataSource, name: string) => {};const saveVariable = (- dataSourceId: string = nanoid(),+ 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 };@@ -108,38 +115,46 @@ const saveVariable = (return;}const [instanceId] = instanceSelector;- serverSyncStore.createTransaction([$dataSources], (dataSources) => {- 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);+ }++ 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 };+ }+ dataSources.set(dataSourceId, {+ id: dataSourceId,+ // preserve existing instance scope when edit+ scopeInstanceId:+ dataSources.get(dataSourceId)?.scopeInstanceId ?? instanceId,+ name,+ type: "variable",+ value: variableValue,+ });}- dataSources.set(dataSourceId, {- id: dataSourceId,- // preserve existing instance scope when edit- scopeInstanceId:- dataSources.get(dataSourceId)?.scopeInstanceId ?? instanceId,- name,- type: "variable",- value: variableValue,- });- });+ );};-const VariablePanel = ({+const VariableValuePanel = ({variable,- onBack,+ onCancel,}: {variable?: DataSource;- onBack: () => void;+ onCancel: () => void;}) => {// variable value cannot have an access to other variablesconst nameId = useId();@@ -152,6 +167,78 @@ const VariablePanel = ({);const [valueErrors, setValueErrors] = useState<undefined | string[]>();+ 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={onCancel}>+ Cancel+ </Button>+ <Button+ onClick={() => {+ if (name.length === 0) {+ setNameErrors([`Variable name is required`]);+ return;+ }+ if (variable?.type === "parameter") {+ renameVariable(variable, name);+ onCancel();+ }+ // save value variable and convert from resource variable if necessary+ const result = saveVariable(variable, name, value);+ if (result?.error !== undefined) {+ setValueErrors([result.error]);+ return;+ }+ onCancel();+ }}+ >+ Save+ </Button>+ </Flex>+ </Flex>+ );+};++const VariablePanel = ({+ variable,+ onBack,+}: {+ variable?: DataSource;+ onBack: () => void;+}) => {+ const [tab, setTab] = useState(+ variable?.type === "resource" ? "resource" : "value"+ );useEffect(() => {const handleKeyDown = (event: KeyboardEvent) => {if (event.key === "Escape") {@@ -167,72 +254,32 @@ const VariablePanel = ({}, [onBack]);return (- <ScrollArea- css={{- display: "flex",- flexDirection: "column",- width: theme.spacing[30],- }}- >- <Flex- direction="column"- css={{- overflow: "hidden",- p: theme.spacing[9],- gap: theme.spacing[5],- }}- >- <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>- {/* only value variables (new and existing) can have value field */}- {(variable === undefined || variable.type === "variable") && (- <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={onBack}>- Cancel- </Button>- <Button- onClick={() => {- if (name.length === 0) {- setNameErrors([`Variable name is required`]);- return;- }- if (variable === undefined || variable.type === "variable") {- const result = saveVariable(variable?.id, name, value);- if (result?.error !== undefined) {- setValueErrors([result.error]);- return;- }- onBack();- return;- }-- // only rename any other type of variable- renameVariable(variable, name);- onBack();- }}- >- Save- </Button>- </Flex>+ <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} onCancel={onBack} />+ </PanelTabsContent>+ <PanelTabsContent value="resource">+ <ResourcePanel variable={variable} onCancel={onBack} />+ </PanelTabsContent>+ </ScrollArea></Flex>- </ScrollArea>+ </PanelTabs>);};diff --git a/apps/builder/app/shared/nano-states/nano-states.ts b/apps/builder/app/shared/nano-states/nano-states.tsindex aba127a5f3..968cf99f85 100644--- a/apps/builder/app/shared/nano-states/nano-states.ts+++ b/apps/builder/app/shared/nano-states/nano-states.ts@@ -11,6 +11,7 @@ import type {Instance,Prop,Props,+ Resource,StyleDecl,Styles,StyleSource,@@ -49,6 +50,8 @@ export const dataSourceVariablesStore = atom<Map<DataSource["id"], unknown>>();export const $dataSourceVariables = dataSourceVariablesStore;+export const $resources = atom(new Map<Resource["id"], Resource>());+export const propsStore = atom<Props>(new Map());export const $props = propsStore;export const propsIndexStore = computed(propsStore, (props) => {diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex 312c4fb5f5..a51e76a671 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -32,6 +32,7 @@ import {dataSourceVariablesStore,$dragAndDropState,$selectedInstanceStates,+ $resources,} from "~/shared/nano-states";import { $ephemeralStyles } from "~/canvas/stores";@@ -79,6 +80,7 @@ export const registerContainers = () => {serverSyncStore.register("styleSourceSelections", styleSourceSelectionsStore);serverSyncStore.register("props", propsStore);serverSyncStore.register("dataSources", dataSourcesStore);+ serverSyncStore.register("resources", $resources);serverSyncStore.register("assets", assetsStore);// synchronize whole statesclientStores.set("project", projectStore);