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: support bindings in page meta (#2859)

Bogdan Chadkin6fda5d7f6649
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.stories.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.stories.tsx
index bc8f12cdfc..cbbde4f8a1 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.stories.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.stories.tsx
@@ -14,11 +14,7 @@ export const Basic = () => {
return (
<Box css={{ width: 448, margin: 20 }}>
- <CustomMetadata
- variableValues={new Map()}
- customMetas={customMetas}
- onChange={setCustomMetas}
- />
+ <CustomMetadata customMetas={customMetas} onChange={setCustomMetas} />
</Box>
);
};
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.tsx
index 597cca91bf..58e5f67f47 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/custom-metadata.tsx
@@ -1,3 +1,5 @@
+import { useId } from "react";
+import { useStore } from "@nanostores/react";
import {
Button,
Grid,
@@ -9,8 +11,14 @@ import {
theme,
} from "@webstudio-is/design-system";
import { DeleteIcon, PlusIcon } from "@webstudio-is/icons";
-import { useId } from "react";
+import { isFeatureEnabled } from "@webstudio-is/feature-flags";
+import {
+ BindingControl,
+ BindingPopover,
+ isLiteralExpression,
+} from "~/builder/shared/binding-popover";
import { computeExpression } from "~/shared/nano-states";
+import { $pageRootScope } from "./page-utils";
type Meta = {
property: string;
@@ -18,13 +26,11 @@ type Meta = {
};
type CustomMetadataProps = {
- variableValues: Map<string, unknown>;
customMetas: Meta[];
onChange: (value: Meta[]) => void;
};
-const PropertyContent = (props: {
- variableValues: Map<string, unknown>;
+const MetadataItem = (props: {
property: string;
content: string;
onDelete: () => void;
@@ -32,8 +38,9 @@ const PropertyContent = (props: {
}) => {
const propertyId = useId();
const contentId = useId();
+ const { variableValues, scope, aliases } = useStore($pageRootScope);
- const content = computeExpression(props.content, props.variableValues);
+ const content = computeExpression(props.content, variableValues);
return (
<Grid
@@ -65,20 +72,41 @@ const PropertyContent = (props: {
<Label htmlFor={contentId} css={{ gridArea: "content" }}>
Content
</Label>
- <InputErrorsTooltip errors={undefined}>
- <InputField
- css={{
- gridArea: "content-input",
- }}
- tabIndex={1}
- id={contentId}
- property="path"
- value={content}
- onChange={(event) => {
- props.onChange(props.property, JSON.stringify(event.target.value));
- }}
- />
- </InputErrorsTooltip>
+ <BindingControl>
+ {isFeatureEnabled("cms") && (
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ variant={isLiteralExpression(props.content) ? "default" : "bound"}
+ value={props.content}
+ onChange={(value) => {
+ props.onChange(props.property, value);
+ }}
+ onRemove={(evaluatedValue) => {
+ props.onChange(props.property, JSON.stringify(evaluatedValue));
+ }}
+ />
+ )}
+ <InputErrorsTooltip errors={undefined}>
+ <InputField
+ css={{
+ gridArea: "content-input",
+ }}
+ disabled={isLiteralExpression(props.content) === false}
+ color={typeof content !== "string" ? "error" : undefined}
+ tabIndex={1}
+ id={contentId}
+ property="path"
+ value={content}
+ onChange={(event) => {
+ props.onChange(
+ props.property,
+ JSON.stringify(event.target.value)
+ );
+ }}
+ />
+ </InputErrorsTooltip>
+ </BindingControl>
<Grid
css={{
gridArea: "button",
@@ -140,9 +168,8 @@ export const CustomMetadata = (props: CustomMetadataProps) => {
<div />
<Grid gap={3}>
{props.customMetas.map((meta, index) => (
- <PropertyContent
+ <MetadataItem
key={index}
- variableValues={props.variableValues}
property={meta.property}
content={meta.content}
onChange={(property, content) => {
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
index 7be962947e..e5fe521998 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
@@ -1,11 +1,6 @@
+import { nanoid } from "nanoid";
import { z } from "zod";
-import {
- type FocusEventHandler,
- useState,
- useCallback,
- Fragment,
- useMemo,
-} from "react";
+import { type FocusEventHandler, useState, useCallback, Fragment } from "react";
import { useStore } from "@nanostores/react";
import { useDebouncedCallback } from "use-debounce";
import { useUnmount } from "react-use";
@@ -70,7 +65,11 @@ import {
$dataSourceVariables,
computeExpression,
} from "~/shared/nano-states";
-import { nanoid } from "nanoid";
+import {
+ BindingControl,
+ BindingPopover,
+ isLiteralExpression,
+} from "~/builder/shared/binding-popover";
import { serverSyncStore } from "~/shared/sync";
import { SearchPreview } from "./search-preview";
import { ImageControl } from "~/builder/features/seo/image-control";
@@ -84,7 +83,11 @@ import {
parsePathnamePattern,
validatePathnamePattern,
} from "./url-pattern";
-import { registerFolderChildMutable, deletePageMutable } from "./page-utils";
+import {
+ registerFolderChildMutable,
+ deletePageMutable,
+ $pageRootScope,
+} from "./page-utils";
import { Form } from "./form";
const fieldDefaultValues = {
@@ -141,18 +144,28 @@ const LegacyPagePath = z
"/build prefix is reserved for the system"
);
-const HomePageValues = z.object({
+const SharedPageValues = z.object({
name: PageName,
- path: HomePagePath,
title: PageTitle,
description: z.string().optional(),
+ excludePageFromSearch: z.boolean().optional(),
+ socialImageUrl: z.string().optional(),
+ customMetas: z
+ .array(
+ z.object({
+ property: z.string(),
+ content: z.string(),
+ })
+ )
+ .optional(),
});
-const PageValues = z.object({
- name: PageName,
+const HomePageValues = SharedPageValues.extend({
+ path: HomePagePath,
+});
+
+const PageValues = SharedPageValues.extend({
path: isFeatureEnabled("cms") ? PagePath : LegacyPagePath,
- title: PageTitle,
- description: z.string().optional(),
});
const isPathUnique = (
@@ -179,10 +192,26 @@ const validateValues = (
// undefined page id means new page
pageId: undefined | Page["id"],
values: Values,
- isHomePage: boolean
+ isHomePage: boolean,
+ variableValues: Map<string, unknown>
): Errors => {
+ const computedValues = {
+ name: values.name,
+ path: values.path,
+ title: computeExpression(values.title, variableValues),
+ description: computeExpression(values.description, variableValues),
+ excludePageFromSearch: computeExpression(
+ values.excludePageFromSearch,
+ variableValues
+ ),
+ socialImageUrl: computeExpression(values.socialImageUrl, variableValues),
+ customMetas: values.customMetas.map((item) => ({
+ property: item.property,
+ content: computeExpression(item.content, variableValues),
+ })),
+ };
const Validator = isHomePage ? HomePageValues : PageValues;
- const parsedResult = Validator.safeParse(values);
+ const parsedResult = Validator.safeParse(computedValues);
const errors: Errors = {};
if (parsedResult.success === false) {
return parsedResult.error.formErrors.fieldErrors;
@@ -303,7 +332,7 @@ const FormFields = ({
const assets = useStore($assets);
const pages = useStore($pages);
const dataSourceVariables = useStore($dataSourceVariables);
- const variableValues = useMemo(() => new Map(), []);
+ const { variableValues, scope, aliases } = useStore($pageRootScope);
if (pages === undefined) {
return;
@@ -548,62 +577,155 @@ const FormFields = ({
<Grid gap={1}>
<Label htmlFor={fieldIds.title}>Title</Label>
- <InputErrorsTooltip errors={errors.title}>
- <InputField
- tabIndex={1}
- color={errors.title && "error"}
- id={fieldIds.title}
- name="title"
- placeholder="My awesome project - About"
- disabled={disabled}
- value={title}
- onChange={(event) => {
- onChange({
- field: "title",
- value: JSON.stringify(event.target.value),
- });
- }}
- />
- </InputErrorsTooltip>
+ <BindingControl>
+ {isFeatureEnabled("cms") && (
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ variant={
+ isLiteralExpression(values.title) ? "default" : "bound"
+ }
+ value={values.title}
+ onChange={(value) => {
+ onChange({
+ field: "title",
+ value,
+ });
+ }}
+ onRemove={(evaluatedValue) => {
+ onChange({
+ field: "title",
+ value: JSON.stringify(evaluatedValue),
+ });
+ }}
+ />
+ )}
+ <InputErrorsTooltip errors={errors.title}>
+ <InputField
+ tabIndex={1}
+ color={errors.title && "error"}
+ id={fieldIds.title}
+ name="title"
+ placeholder="My awesome project - About"
+ disabled={
+ disabled || isLiteralExpression(values.title) === false
+ }
+ value={title}
+ onChange={(event) => {
+ onChange({
+ field: "title",
+ value: JSON.stringify(event.target.value),
+ });
+ }}
+ />
+ </InputErrorsTooltip>
+ </BindingControl>
</Grid>
<Grid gap={1}>
<Label htmlFor={fieldIds.description}>Description</Label>
- <InputErrorsTooltip errors={errors.description}>
- <TextArea
- tabIndex={1}
- state={errors.description && "invalid"}
- id={fieldIds.description}
- name="description"
- disabled={disabled}
- value={description}
- onChange={(value) => {
- onChange({
- field: "description",
- value: JSON.stringify(value),
- });
- }}
- autoGrow
- maxRows={10}
- />
- </InputErrorsTooltip>
- <Grid flow={"column"} gap={1} justify={"start"} align={"center"}>
- <Checkbox
- id={fieldIds.excludePageFromSearch}
- checked={excludePageFromSearch}
- onCheckedChange={() => {
- const newValue = !excludePageFromSearch;
- onChange({
- field: "excludePageFromSearch",
- value: newValue.toString(),
- });
- }}
- />
+ <BindingControl>
+ {isFeatureEnabled("cms") && (
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ variant={
+ isLiteralExpression(values.description)
+ ? "default"
+ : "bound"
+ }
+ value={values.description}
+ onChange={(value) => {
+ onChange({
+ field: "description",
+ value,
+ });
+ }}
+ onRemove={(evaluatedValue) => {
+ onChange({
+ field: "description",
+ value: JSON.stringify(evaluatedValue),
+ });
+ }}
+ />
+ )}
+ <InputErrorsTooltip errors={errors.description}>
+ <TextArea
+ tabIndex={1}
+ state={errors.description && "invalid"}
+ id={fieldIds.description}
+ name="description"
+ disabled={
+ disabled ||
+ isLiteralExpression(values.description) === false
+ }
+ value={description}
+ onChange={(value) => {
+ onChange({
+ field: "description",
+ value: JSON.stringify(value),
+ });
+ }}
+ autoGrow
+ maxRows={10}
+ />
+ </InputErrorsTooltip>
+ </BindingControl>
+ <BindingControl>
+ <Grid
+ flow={"column"}
+ gap={1}
+ justify={"start"}
+ align={"center"}
+ css={{ py: theme.spacing[2] }}
+ >
+ {isFeatureEnabled("cms") && (
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ variant={
+ isLiteralExpression(values.excludePageFromSearch)
+ ? "default"
+ : "bound"
+ }
+ value={values.excludePageFromSearch}
+ onChange={(value) => {
+ onChange({
+ field: "excludePageFromSearch",
+ value,
+ });
+ }}
+ onRemove={(evaluatedValue) => {
+ onChange({
+ field: "excludePageFromSearch",
+ value: JSON.stringify(evaluatedValue),
+ });
+ }}
+ />
+ )}
+ <Checkbox
+ id={fieldIds.excludePageFromSearch}
+ disabled={
+ disabled ||
+ isLiteralExpression(values.excludePageFromSearch) === false
+ }
+ checked={excludePageFromSearch}
+ onCheckedChange={() => {
+ const newValue = !excludePageFromSearch;
+ onChange({
+ field: "excludePageFromSearch",
+ value: newValue.toString(),
+ });
+ }}
+ />
- <Label htmlFor={fieldIds.excludePageFromSearch}>
- Exclude this page from search results
- </Label>
- </Grid>
+ <InputErrorsTooltip errors={errors.excludePageFromSearch}>
+ <Label htmlFor={fieldIds.excludePageFromSearch}>
+ Exclude this page from search results
+ </Label>
+ </InputErrorsTooltip>
+ </Grid>
+ </BindingControl>
</Grid>
</Grid>
@@ -623,17 +745,48 @@ const FormFields = ({
are 1200x630 px or larger with a 1.91:1 aspect ratio.
</Text>
{isFeatureEnabled("cms") && (
- <InputField
- placeholder="https://www.url.com"
- value={socialImageUrl}
- onChange={(event) => {
- onChange({
- field: "socialImageUrl",
- value: JSON.stringify(event.target.value),
- });
- onChange({ field: "socialImageAssetId", value: "" });
- }}
- />
+ <BindingControl>
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ variant={
+ isLiteralExpression(values.socialImageUrl)
+ ? "default"
+ : "bound"
+ }
+ value={values.socialImageUrl}
+ onChange={(value) => {
+ onChange({
+ field: "socialImageUrl",
+ value,
+ });
+ }}
+ onRemove={(evaluatedValue) => {
+ onChange({
+ field: "socialImageUrl",
+ value: JSON.stringify(evaluatedValue),
+ });
+ }}
+ />
+ <InputErrorsTooltip errors={errors.socialImageUrl}>
+ <InputField
+ placeholder="https://www.url.com"
+ disabled={
+ disabled ||
+ isLiteralExpression(values.socialImageUrl) === false
+ }
+ color={errors.socialImageUrl && "error"}
+ value={socialImageUrl}
+ onChange={(event) => {
+ onChange({
+ field: "socialImageUrl",
+ value: JSON.stringify(event.target.value),
+ });
+ onChange({ field: "socialImageAssetId", value: "" });
+ }}
+ />
+ </InputErrorsTooltip>
+ </BindingControl>
)}
<Grid gap={1} flow={"column"}>
<ImageControl
@@ -681,16 +834,19 @@ const FormFields = ({
<Separator />
- <CustomMetadata
- variableValues={variableValues}
- customMetas={values.customMetas}
- onChange={(customMetas) => {
- onChange({
- field: "customMetas",
- value: customMetas,
- });
- }}
- />
+ <InputErrorsTooltip errors={errors.customMetas}>
+ <div>
+ <CustomMetadata
+ customMetas={values.customMetas}
+ onChange={(customMetas) => {
+ onChange({
+ field: "customMetas",
+ value: customMetas,
+ });
+ }}
+ />
+ </div>
+ </InputErrorsTooltip>
<Box css={{ height: theme.spacing[10] }} />
</ScrollArea>
</Grid>
@@ -736,7 +892,14 @@ export const NewPageSettings = ({
...fieldDefaultValues,
path: nameToPath(pages, fieldDefaultValues.name),
});
- const errors = validateValues(pages, undefined, values, false);
+ const { variableValues } = useStore($pageRootScope);
+ const errors = validateValues(
+ pages,
+ undefined,
+ values,
+ false,
+ variableValues
+ );
const handleSubmit = () => {
if (Object.keys(errors).length === 0) {
@@ -1014,7 +1177,14 @@ export const PageSettings = ({
...unsavedValues,
};
- const errors = validateValues(pages, pageId, values, values.isHomePage);
+ const { variableValues } = useStore($pageRootScope);
+ const errors = validateValues(
+ pages,
+ pageId,
+ values,
+ values.isHomePage,
+ variableValues
+ );
const debouncedFn = useEffectEvent(() => {
if (
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.ts b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.ts
index a48c6d00a3..177da285a0 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.ts
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.ts
@@ -1,4 +1,6 @@
+import { computed } from "nanostores";
import { createRootFolder } from "@webstudio-is/project-build";
+import { encodeDataSourceVariable } from "@webstudio-is/react-sdk";
import {
type Page,
Pages,
@@ -12,8 +14,11 @@ import {
import { removeByMutable } from "~/shared/array-utils";
import { deleteInstanceMutable } from "~/shared/instance-utils";
import {
+ $dataSources,
$selectedInstanceSelector,
+ $selectedPage,
$selectedPageId,
+ $variableValuesByInstanceSelector,
} from "~/shared/nano-states";
type TreePage = {
@@ -278,3 +283,30 @@ export const getExistingRoutePaths = (pages?: Pages): Set<string> => {
}
return paths;
};
+
+export const $pageRootScope = computed(
+ [$selectedPage, $variableValuesByInstanceSelector, $dataSources],
+ (selectedPage, variableValuesByInstanceSelector, dataSources) => {
+ const scope: Record<string, unknown> = {};
+ const aliases = new Map<string, string>();
+ const variableValues = new Map<string, unknown>();
+ if (selectedPage === undefined) {
+ return { variableValues, scope, aliases };
+ }
+ const values = variableValuesByInstanceSelector.get(
+ JSON.stringify([selectedPage.rootInstanceId])
+ );
+ 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 { variableValues: values ?? variableValues, scope, aliases };
+ }
+);
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/settings-panel.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/settings-panel.tsx
index f732938679..e5dfa44ead 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/settings-panel.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/settings-panel.tsx
@@ -5,6 +5,8 @@ import {
Flex,
} from "@webstudio-is/design-system";
import { theme } from "@webstudio-is/design-system";
+import { useRef } from "react";
+import { BindingPopoverProvider } from "~/builder/shared/binding-popover";
const CollapsibleRoot = styled(Collapsible.Root, {
position: "absolute",
@@ -58,8 +60,9 @@ export const SettingsPanel = ({
children: React.ReactNode;
isOpen: boolean;
}) => {
+ const settingsRef = useRef<HTMLDivElement>(null);
return (
- <CollapsibleRoot open={isOpen}>
+ <CollapsibleRoot ref={settingsRef} open={isOpen}>
<CollapsibleContent>
<Flex
direction="column"
@@ -72,7 +75,11 @@ export const SettingsPanel = ({
borderRight: `1px solid ${theme.colors.slate7}`,
}}
>
- {children}
+ <BindingPopoverProvider
+ value={{ containerRef: settingsRef, side: "right" }}
+ >
+ {children}
+ </BindingPopoverProvider>
</Flex>
</CollapsibleContent>
</CollapsibleRoot>
diff --git a/apps/builder/app/builder/shared/binding-popover.tsx b/apps/builder/app/builder/shared/binding-popover.tsx
index 54e4f0d7ee..b00cc3194d 100644
--- a/apps/builder/app/builder/shared/binding-popover.tsx
+++ b/apps/builder/app/builder/shared/binding-popover.tsx
@@ -364,6 +364,7 @@ BindingButton.displayName = "BindingButton";
const BindingPopoverContext = createContext<{
containerRef?: RefObject<HTMLElement>;
+ side?: "left" | "right";
}>({});
export const BindingPopoverProvider = BindingPopoverContext.Provider;
@@ -385,9 +386,13 @@ export const BindingPopover = ({
onChange: (newValue: string) => void;
onRemove: (evaluatedValue: unknown) => void;
}) => {
- const { containerRef } = useContext(BindingPopoverContext);
+ const { side = "left", containerRef } = useContext(BindingPopoverContext);
const [isOpen, onOpenChange] = useState(false);
- const [triggerRef, sideOffset] = useSideOffset({ isOpen, containerRef });
+ const [triggerRef, sideOffset] = useSideOffset({
+ side,
+ isOpen,
+ containerRef,
+ });
const hasUnsavedChange = useRef<boolean>(false);
const preventedClosing = useRef<boolean>(false);
@@ -418,7 +423,7 @@ export const BindingPopover = ({
</FloatingPanelPopoverTrigger>
<FloatingPanelPopoverContent
sideOffset={sideOffset}
- side="left"
+ side={side}
align="start"
>
<BindingPanel
diff --git a/apps/builder/app/builder/shared/floating-panel.tsx b/apps/builder/app/builder/shared/floating-panel.tsx
index 04122537a2..510263e1a3 100644
--- a/apps/builder/app/builder/shared/floating-panel.tsx
+++ b/apps/builder/app/builder/shared/floating-panel.tsx
@@ -17,9 +17,11 @@ import {
} from "@webstudio-is/design-system";
export const useSideOffset = ({
+ side = "left",
isOpen,
containerRef,
}: {
+ side?: "left" | "right";
isOpen: boolean;
containerRef?: RefObject<HTMLElement>;
}): [MutableRefObject<HTMLButtonElement | null>, number] => {
@@ -39,8 +41,15 @@ export const useSideOffset = ({
}
const containerRect = containerRef.current.getBoundingClientRect();
const triggerRect = triggerRef.current.getBoundingClientRect();
- setSideOffset(triggerRect.left - containerRect.left);
- }, [isOpen, containerRef]);
+ if (side === "left") {
+ setSideOffset(triggerRect.left - containerRect.left);
+ }
+ if (side === "right") {
+ const containerRight = containerRect.left + containerRect.width;
+ const triggerRight = triggerRect.left + triggerRect.width;
+ setSideOffset(containerRight - triggerRight);
+ }
+ }, [side, isOpen, containerRef]);
return [triggerRef, sideOffset];
};