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.

Props panel: basic URL control (#1280)

Roman Pominov3279d6fc7828
diff --git a/apps/builder/app/builder/features/props-panel/controls/color.tsx b/apps/builder/app/builder/features/props-panel/controls/color.tsx
index 41489dca55..39f39818c6 100644
--- a/apps/builder/app/builder/features/props-panel/controls/color.tsx
+++ b/apps/builder/app/builder/features/props-panel/controls/color.tsx
@@ -1,4 +1,4 @@
-import { TextField, theme, useId } from "@webstudio-is/design-system";
+import { Flex, TextField, theme, useId } from "@webstudio-is/design-system";
import {
type ControlProps,
getLabel,
@@ -29,18 +29,24 @@ export const ColorControl = ({
id={id}
onDelete={onDelete}
>
- <TextField
- id={id}
- value={localValue.value}
- onChange={(event) => localValue.set(event.target.value)}
- onBlur={localValue.save}
- onKeyDown={(event) => {
- if (event.key === "Enter") {
- localValue.save();
- }
+ <Flex
+ css={{
+ // can't set width on TextField because it adds padding
+ width: theme.spacing[22],
}}
- css={{ width: theme.spacing[22] }}
- />
+ >
+ <TextField
+ id={id}
+ value={localValue.value}
+ onChange={(event) => localValue.set(event.target.value)}
+ onBlur={localValue.save}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ localValue.save();
+ }
+ }}
+ />
+ </Flex>
</HorizontalLayout>
);
};
diff --git a/apps/builder/app/builder/features/props-panel/controls/combined.tsx b/apps/builder/app/builder/features/props-panel/controls/combined.tsx
index a3c8a37ef7..3d163290e7 100644
--- a/apps/builder/app/builder/features/props-panel/controls/combined.tsx
+++ b/apps/builder/app/builder/features/props-panel/controls/combined.tsx
@@ -6,6 +6,7 @@ import { RadioControl } from "./radio";
import { SelectControl } from "./select";
import { BooleanControl } from "./boolean";
import { FileImageControl } from "./file-image";
+import { UrlControl } from "./url";
import type { ControlProps } from "../shared";
export const renderControl = ({
@@ -71,6 +72,13 @@ export const renderControl = ({
return <FileImageControl meta={meta} prop={prop} {...rest} />;
}
+ if (
+ meta.control === "url" &&
+ (prop === undefined || prop.type === "string" || prop.type === "page")
+ ) {
+ return <UrlControl meta={meta} prop={prop} {...rest} />;
+ }
+
// 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) {
@@ -133,6 +141,21 @@ export const renderControl = ({
/>
);
}
+
+ if (prop.type === "page") {
+ return (
+ <UrlControl
+ meta={{
+ ...meta,
+ defaultValue: undefined,
+ control: "url",
+ type: "string",
+ }}
+ prop={prop}
+ {...rest}
+ />
+ );
+ }
}
throw new Error(
diff --git a/apps/builder/app/builder/features/props-panel/controls/number.tsx b/apps/builder/app/builder/features/props-panel/controls/number.tsx
index 8e2db3200d..a6504f5a2d 100644
--- a/apps/builder/app/builder/features/props-panel/controls/number.tsx
+++ b/apps/builder/app/builder/features/props-panel/controls/number.tsx
@@ -1,4 +1,4 @@
-import { TextField, theme, useId } from "@webstudio-is/design-system";
+import { Flex, TextField, theme, useId } from "@webstudio-is/design-system";
import {
type ControlProps,
getLabel,
@@ -31,25 +31,27 @@ export const NumberControl = ({
label={getLabel(meta, propName)}
onDelete={onDelete}
>
- <TextField
- id={id}
- type="number"
- value={localValue.value}
- onChange={(event) => {
- const asNumber = parseFloat(event.target.value);
- localValue.set(
- // just in case type="number" doesn't guarantee a number
- Number.isNaN(asNumber) ? event.target.value : asNumber
- );
+ <Flex
+ css={{
+ // can't set width on TextField because it adds padding
+ width: theme.spacing[21],
}}
- onBlur={localValue.save}
- onKeyDown={(event) => {
- if (event.key === "Enter") {
- localValue.save();
+ >
+ <TextField
+ id={id}
+ type="number"
+ value={localValue.value}
+ onChange={({ target: { valueAsNumber, value } }) =>
+ localValue.set(Number.isNaN(valueAsNumber) ? value : valueAsNumber)
}
- }}
- css={{ width: theme.spacing[21] }}
- />
+ onBlur={localValue.save}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ localValue.save();
+ }
+ }}
+ />
+ </Flex>
</HorizontalLayout>
);
};
diff --git a/apps/builder/app/builder/features/props-panel/controls/text.tsx b/apps/builder/app/builder/features/props-panel/controls/text.tsx
index f4ed46c1f0..e60aa9af28 100644
--- a/apps/builder/app/builder/features/props-panel/controls/text.tsx
+++ b/apps/builder/app/builder/features/props-panel/controls/text.tsx
@@ -32,18 +32,24 @@ const AsInput = ({
return (
<HorizontalLayout label={label} id={id} onDelete={onDelete}>
- <TextField
- id={id}
- value={localValue.value}
- onChange={(event) => localValue.set(event.target.value)}
- onBlur={localValue.save}
- onKeyDown={(event) => {
- if (event.key === "Enter") {
- localValue.save();
- }
+ <Flex
+ css={{
+ // can't set width on TextField because it adds padding
+ width: theme.spacing[22],
}}
- css={{ width: theme.spacing[22] }}
- />
+ >
+ <TextField
+ id={id}
+ value={localValue.value}
+ onChange={(event) => localValue.set(event.target.value)}
+ onBlur={localValue.save}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ localValue.save();
+ }
+ }}
+ />
+ </Flex>
</HorizontalLayout>
);
};
diff --git a/apps/builder/app/builder/features/props-panel/controls/url.tsx b/apps/builder/app/builder/features/props-panel/controls/url.tsx
new file mode 100644
index 0000000000..4100eb8b5d
--- /dev/null
+++ b/apps/builder/app/builder/features/props-panel/controls/url.tsx
@@ -0,0 +1,145 @@
+import { useStore } from "@nanostores/react";
+import { pagesStore } from "~/shared/nano-states";
+import {
+ TextField,
+ Flex,
+ theme,
+ useId,
+ ToggleGroup,
+ ToggleGroupItem,
+ Select,
+ Tooltip,
+} from "@webstudio-is/design-system";
+import { Link2Icon, PageIcon } from "@webstudio-is/icons";
+import { useState } from "react";
+import {
+ type ControlProps,
+ getLabel,
+ useLocalValue,
+ VerticalLayout,
+} from "../shared";
+import type { Page } from "@webstudio-is/project-build";
+
+type UrlControlProps = ControlProps<"url", "string" | "page">;
+
+type BaseControlProps = {
+ id: string;
+ prop: UrlControlProps["prop"];
+ onChange: UrlControlProps["onChange"];
+};
+
+const BaseUrl = ({ prop, onChange, id }: BaseControlProps) => {
+ const localValue = useLocalValue(
+ prop?.type === "string" ? prop.value : "",
+ (value) => onChange({ type: "string", value })
+ );
+
+ return (
+ <Flex css={{ py: theme.spacing[2] }} direction="column" align="stretch">
+ <TextField
+ id={id}
+ value={localValue.value}
+ placeholder="https://example.com/"
+ onChange={(event) => localValue.set(event.target.value)}
+ onBlur={localValue.save}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ localValue.save();
+ }
+ }}
+ />
+ </Flex>
+ );
+};
+
+const getPageId = (page: Page) => page.id;
+const getPageName = (page: Page) => page.name;
+
+const BasePage = ({ prop, onChange, id }: BaseControlProps) => {
+ const pages = useStore(pagesStore);
+ const options = pages === undefined ? [] : [pages.homePage, ...pages.pages];
+ const value =
+ prop?.type === "page"
+ ? options.find((page) => page.id === prop.value)
+ : undefined;
+
+ return (
+ <Flex css={{ py: theme.spacing[2] }}>
+ <Select
+ id={id}
+ value={value}
+ options={options}
+ getLabel={getPageName}
+ getValue={getPageId}
+ onChange={(page) => onChange({ type: "page", value: page.id })}
+ fullWidth
+ />
+ </Flex>
+ );
+};
+
+// @todo: Section, Email, Phone, Attachment
+const modes = ["url", "page"] as const;
+type Mode = (typeof modes)[number];
+const baseControls = {
+ url: BaseUrl,
+ page: BasePage,
+} satisfies Record<Mode, unknown>;
+
+export const UrlControl = ({
+ meta,
+ prop,
+ propName,
+ onChange,
+ onDelete,
+}: UrlControlProps) => {
+ const initialMode = prop?.type === "page" ? "page" : "url";
+
+ const [mode, setMode] = useState<Mode>(initialMode);
+
+ const id = useId();
+
+ const BaseControl = baseControls[mode];
+
+ return (
+ <VerticalLayout
+ label={getLabel(meta, propName)}
+ onDelete={onDelete}
+ id={id}
+ >
+ <Flex
+ css={{
+ py: theme.spacing[2],
+
+ // temporary fix for ToggleGroup
+ // which borders protrude outside of the container
+ px: theme.spacing[1],
+ }}
+ >
+ <ToggleGroup
+ type="single"
+ value={mode}
+ onValueChange={(value) => {
+ const asMode = modes.find((mode) => mode === value);
+ if (asMode) {
+ setMode(asMode);
+ }
+ }}
+ >
+ <ToggleGroupItem value={"url" satisfies Mode}>
+ <Tooltip content="URL">
+ <Link2Icon />
+ </Tooltip>
+ </ToggleGroupItem>
+ <ToggleGroupItem value={"page" satisfies Mode}>
+ <Tooltip content="Page">
+ <PageIcon />
+ </Tooltip>
+ </ToggleGroupItem>
+ </ToggleGroup>
+ </Flex>
+
+ <BaseControl id={id} prop={prop} onChange={onChange} />
+ </VerticalLayout>
+ );
+};
diff --git a/apps/builder/app/builder/features/props-panel/props-panel.stories.tsx b/apps/builder/app/builder/features/props-panel/props-panel.stories.tsx
index 97a5e6569d..36eec48eaa 100644
--- a/apps/builder/app/builder/features/props-panel/props-panel.stories.tsx
+++ b/apps/builder/app/builder/features/props-panel/props-panel.stories.tsx
@@ -2,12 +2,31 @@ import { useState } from "react";
import { ButtonIcon } from "@webstudio-is/icons";
import { PropsPanel } from "./props-panel";
import { usePropsLogic } from "./use-props-logic";
+import { pagesStore } from "~/shared/nano-states";
import type { Prop } from "@webstudio-is/project-build";
import type {
WsComponentMeta,
WsComponentPropsMeta,
} from "@webstudio-is/react-sdk";
+const page = (name: string, path: string) => ({
+ id: Math.random().toString(),
+ name,
+ title: name,
+ path,
+ meta: {},
+ rootInstanceId: "1",
+});
+
+pagesStore.set({
+ homePage: page("Home", "/"),
+ pages: [
+ page("About", "/about"),
+ page("Pricing", "/pricing"),
+ page("Contacts", "/contacts"),
+ ],
+});
+
type PropMeta = WsComponentPropsMeta["props"][string];
const textProp = (label?: string): PropMeta => ({
@@ -46,22 +65,18 @@ const colorProp = (label?: string): PropMeta => ({
label,
});
-const defaultOptions = ["one", "two", "three-the-very-long-one-so-much-long"];
-
-const radioProp = (options = defaultOptions, label?: string): PropMeta => ({
+const urlProp = (label?: string): PropMeta => ({
type: "string",
- control: "radio",
- options,
+ control: "url",
required: false,
label,
});
-const inlineRadioProp = (
- options = defaultOptions,
- label?: string
-): PropMeta => ({
+const defaultOptions = ["one", "two", "three-the-very-long-one-so-much-long"];
+
+const radioProp = (options = defaultOptions, label?: string): PropMeta => ({
type: "string",
- control: "inline-radio",
+ control: "radio",
options,
required: false,
label,
@@ -83,28 +98,6 @@ const checkProp = (options = defaultOptions, label?: string): PropMeta => ({
label,
});
-const inlineCheckProp = (
- options = defaultOptions,
- label?: string
-): PropMeta => ({
- type: "string[]",
- control: "inline-check",
- options,
- required: false,
- label,
-});
-
-const multiSelectProp = (
- options = defaultOptions,
- label?: string
-): PropMeta => ({
- type: "string[]",
- control: "multi-select",
- options,
- required: false,
- label,
-});
-
const instanceId = "0";
const componentMeta: WsComponentMeta = {
@@ -122,33 +115,28 @@ const componentPropsMeta: WsComponentPropsMeta = {
initialBoolean: booleanProp(),
initialColor: colorProp(),
initialRadio: radioProp(),
- initialInlineRadio: inlineRadioProp(),
initialSelect: selectProp(),
initialCheck: checkProp(),
- initialInlineCheck: inlineCheckProp(),
- initialMultiSelect: multiSelectProp(),
+ initialUrl: urlProp(),
addedText: textProp(),
addedShortText: shortTextProp(),
addedNumber: numberProp(),
addedBoolean: booleanProp(),
addedColor: colorProp(),
addedRadio: radioProp(),
- addedInlineRadio: inlineRadioProp(),
addedSelect: selectProp(),
addedCheck: checkProp(),
- addedInlineCheck: inlineCheckProp(),
- addedMultiSelect: multiSelectProp(),
+ addedUrlUrl: urlProp("Added URL (URL)"),
+ addedUrlPage: urlProp("Added URL (Page)"),
availableText: textProp(),
availableShortText: shortTextProp(),
availableNumber: numberProp(),
availableBoolean: booleanProp(),
availableColor: colorProp(),
availableRadio: radioProp(),
- availableInlineRadio: inlineRadioProp(),
availableSelect: selectProp(),
availableCheck: checkProp(),
- availableInlineCheck: inlineCheckProp(),
- availableMultiSelect: multiSelectProp(),
+ availableUrl: urlProp(),
},
initialProps: [
"initialText",
@@ -157,11 +145,9 @@ const componentPropsMeta: WsComponentPropsMeta = {
"initialBoolean",
"initialColor",
"initialRadio",
- "initialInlineRadio",
"initialSelect",
"initialCheck",
- "initialInlineCheck",
- "initialMultiSelect",
+ "initialUrl",
],
};
@@ -208,13 +194,6 @@ const startingProps: Prop[] = [
type: "string",
value: "two",
},
- {
- id: "6",
- instanceId,
- name: "addedInlineRadio",
- type: "string",
- value: "two",
- },
{
id: "7",
instanceId,
@@ -232,16 +211,16 @@ const startingProps: Prop[] = [
{
id: "9",
instanceId,
- name: "addedInlineCheck",
- type: "string[]",
- value: ["one", "two"],
+ name: "addedUrlUrl",
+ type: "string",
+ value: "https://example.com",
},
{
id: "10",
instanceId,
- name: "addedMultiSelect",
- type: "string[]",
- value: ["one", "two"],
+ name: "addedUrlPage",
+ type: "page",
+ value: pagesStore.get()?.pages[0].id ?? "",
},
];
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index ab6daf224b..2a028ffde1 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -2,7 +2,7 @@ import { useMemo, Fragment, useEffect } from "react";
import { useStore } from "@nanostores/react";
import { computed } from "nanostores";
import type { CanvasData } from "@webstudio-is/project";
-import type { Instance } from "@webstudio-is/project-build";
+import type { Instance, Page } from "@webstudio-is/project-build";
import {
createElementsTree,
registerComponents,
@@ -23,6 +23,7 @@ import { WebstudioComponentDev } from "./features/webstudio-component";
import {
propsIndexStore,
assetsStore,
+ pagesStore,
useRootInstance,
useSubscribeScrollState,
useIsPreviewMode,
@@ -54,6 +55,19 @@ const temporaryRootInstance: Instance = {
const useElementsTree = (getComponent: GetComponent) => {
const [rootInstance] = useRootInstance();
+ const pagesMapStore = useMemo(
+ () =>
+ computed(pagesStore, (pages): Map<string, Page> => {
+ if (pages === undefined) {
+ return new Map();
+ }
+ return new Map(
+ [pages.homePage, ...pages.pages].map((page) => [page.id, page])
+ );
+ }),
+ []
+ );
+
return useMemo(() => {
return createElementsTree({
sandbox: true,
@@ -62,10 +76,11 @@ const useElementsTree = (getComponent: GetComponent) => {
instance: rootInstance ?? temporaryRootInstance,
propsByInstanceIdStore,
assetsStore,
+ pagesStore: pagesMapStore,
Component: WebstudioComponentDev,
getComponent,
});
- }, [rootInstance, getComponent]);
+ }, [rootInstance, getComponent, pagesMapStore]);
};
const DesignMode = () => {
diff --git a/packages/design-system/src/components/select.tsx b/packages/design-system/src/components/select.tsx
index ecf49c08a2..e58125e06d 100644
--- a/packages/design-system/src/components/select.tsx
+++ b/packages/design-system/src/components/select.tsx
@@ -1,5 +1,5 @@
import * as Primitive from "@radix-ui/react-select";
-import React, { ReactNode, Ref, type ComponentProps } from "react";
+import React, { ReactNode, Ref, useMemo, type ComponentProps } from "react";
import {
menuCss,
itemCss,
@@ -69,9 +69,9 @@ type TriggerPassThroughProps = Omit<
ComponentProps<typeof Primitive.Trigger>,
"onChange" | "value" | "defaultValue" | "asChild" | "prefix"
> &
- Omit<ComponentProps<typeof SelectButton>, "onChange">;
+ Omit<ComponentProps<typeof SelectButton>, "onChange" | "value">;
-export type SelectProps<Option = SelectOption> = TriggerPassThroughProps & {
+export type SelectProps<Option = SelectOption> = {
options: Option[];
defaultValue?: Option;
value?: Option;
@@ -79,12 +79,28 @@ export type SelectProps<Option = SelectOption> = TriggerPassThroughProps & {
open?: boolean;
onOpenChange?: (open: boolean) => void;
placeholder?: string;
- getLabel?: (option: Option) => string | undefined;
- getValue?: (option: Option) => string | undefined;
children?: ReactNode;
+} & (Option extends string
+ ? {
+ getLabel?: (option: Option) => string | undefined;
+ getValue?: (option: Option) => string | undefined;
+ }
+ : {
+ getLabel: (option: Option) => string | undefined;
+ getValue: (option: Option) => string | undefined;
+ }) &
+ TriggerPassThroughProps;
+
+const defaultGetValue = (option: unknown) => {
+ if (typeof option === "string") {
+ return option;
+ }
+ throw new Error(
+ `Cannot automatically convert ${typeof option} to string. Provide a getValue/getLabel`
+ );
};
-const SelectBase = (
+const SelectBase = <Option,>(
{
options,
value,
@@ -93,21 +109,36 @@ const SelectBase = (
onChange,
onOpenChange,
open,
- getLabel = (option) => option,
- getValue = (option) => option,
+ getLabel = defaultGetValue,
+ getValue = defaultGetValue,
name,
children,
prefix,
...props
- }: SelectProps,
+ }: SelectProps<Option>,
forwardedRef: Ref<HTMLButtonElement>
) => {
+ const valueToOption = useMemo(() => {
+ const map = new Map<string, Option>();
+ for (const option of options) {
+ map.set(getValue(option) ?? "", option);
+ }
+ return map;
+ }, [options, getValue]);
+
return (
<Primitive.Root
name={name}
- value={value}
- defaultValue={defaultValue}
- onValueChange={onChange}
+ value={value === undefined ? undefined : getValue(value)}
+ defaultValue={
+ defaultValue === undefined ? undefined : getValue(defaultValue)
+ }
+ onValueChange={(value) => {
+ const option = valueToOption.get(value);
+ if (option !== undefined) {
+ onChange?.(option);
+ }
+ }}
open={open}
onOpenChange={onOpenChange}
>
@@ -142,5 +173,6 @@ const SelectBase = (
);
};
-export const Select = React.forwardRef(SelectBase);
-Select.displayName = "Select";
+export const Select = React.forwardRef(SelectBase) as <Option>(
+ props: SelectProps<Option> & { ref?: Ref<HTMLButtonElement> }
+) => JSX.Element | null;
diff --git a/packages/generate-arg-types/src/types.ts b/packages/generate-arg-types/src/types.ts
index f21bb46efe..5d69c73b35 100644
--- a/packages/generate-arg-types/src/types.ts
+++ b/packages/generate-arg-types/src/types.ts
@@ -114,6 +114,13 @@ const FileImage = z.object({
defaultValue: z.string().optional(),
});
+const Url = z.object({
+ ...common,
+ control: z.literal("url"),
+ type: z.literal("string"),
+ defaultValue: z.string().optional(),
+});
+
// we neither generate object nor support it in props panel, listed here for completeness
// can't use name "Object" for the variable because it causes bugs when Object.assign() is used in compiled output
const ObjectType = z.object({
@@ -150,6 +157,7 @@ export const PropMeta = z.union([
Check,
InlineCheck,
FileImage,
+ Url,
ObjectType,
Date,
]);
diff --git a/packages/project-build/src/schema/props.ts b/packages/project-build/src/schema/props.ts
index 7707c31088..a7755726b8 100644
--- a/packages/project-build/src/schema/props.ts
+++ b/packages/project-build/src/schema/props.ts
@@ -28,7 +28,12 @@ export const Prop = z.union([
z.object({
...baseProp,
type: z.literal("asset"),
- value: z.string(),
+ value: z.string(), // asset id
+ }),
+ z.object({
+ ...baseProp,
+ type: z.literal("page"),
+ value: z.string(), // page id
}),
z.object({
...baseProp,
diff --git a/packages/project/src/shared/schema.ts b/packages/project/src/shared/schema.ts
index 0954b9c1b6..d9f70e350c 100644
--- a/packages/project/src/shared/schema.ts
+++ b/packages/project/src/shared/schema.ts
@@ -23,4 +23,4 @@ export type Project = z.infer<typeof Project>;
export const Projects = z.array(Project);
export type Projects = z.infer<typeof Projects>;
-export type CanvasData = Data & { pages: Data["page"][] };
+export type CanvasData = Data;
diff --git a/packages/react-sdk/src/app/custom-components/image.tsx b/packages/react-sdk/src/app/custom-components/image.tsx
index 90f8f36958..0ddd92d7d1 100644
--- a/packages/react-sdk/src/app/custom-components/image.tsx
+++ b/packages/react-sdk/src/app/custom-components/image.tsx
@@ -1,24 +1,21 @@
import {
forwardRef,
useMemo,
- type ComponentProps,
+ type ComponentPropsWithoutRef,
type ElementRef,
} from "react";
import { Image as WebstudioImage, loaders } from "@webstudio-is/image";
import { Image as SdkImage } from "../../components/image";
-import { usePropAsset } from "../../props";
-import { idAttribute } from "../../tree/webstudio-component";
+import { usePropAsset, getInstanceIdFromComponentProps } from "../../props";
import { getParams } from "../params";
const defaultTag = "img";
-type Props = ComponentProps<typeof WebstudioImage> & { [idAttribute]: string };
+type Props = ComponentPropsWithoutRef<typeof WebstudioImage>;
export const Image = forwardRef<ElementRef<typeof defaultTag>, Props>(
(props, ref) => {
- const componentId = props[idAttribute] as string;
-
- const asset = usePropAsset(componentId, "src");
+ const asset = usePropAsset(getInstanceIdFromComponentProps(props), "src");
const params = getParams();
const loader = useMemo(() => {
diff --git a/packages/react-sdk/src/app/custom-components/shared/remix-link.tsx b/packages/react-sdk/src/app/custom-components/shared/remix-link.tsx
index 95fb4d2f3e..e6c15f21e3 100644
--- a/packages/react-sdk/src/app/custom-components/shared/remix-link.tsx
+++ b/packages/react-sdk/src/app/custom-components/shared/remix-link.tsx
@@ -1,59 +1,23 @@
-import { Link } from "@remix-run/react";
-import type {
- ElementRef,
- ComponentProps,
- RefAttributes,
- ForwardRefExoticComponent,
-} from "react";
+import { Link as RemixLink } from "@remix-run/react";
+import type { ComponentPropsWithoutRef } from "react";
import { forwardRef } from "react";
-import type { Link as BaseLink } from "../../../components/link";
+import type { Link } from "../../../components/link";
+import { usePropUrl, getInstanceIdFromComponentProps } from "../../../props";
-const isAbsoluteUrl = (href: string) => {
- try {
- new URL(href);
- return true;
- } catch {
- return false;
- }
-};
-
-// Remix's check for absolute URL copied from here:
-// https://github.com/remix-run/react-router/blob/react-router-dom%406.8.0/packages/react-router-dom/index.tsx#L423-L424
-const isAbsoluteUrlRemix = (href: string) =>
- /^[a-z+]+:\/\//i.test(href) || href.startsWith("//");
-
-type Props = ComponentProps<typeof BaseLink>;
-
-type Ref = ElementRef<"a">;
-
-export const wrapLinkComponent = (
- BaseLink: ForwardRefExoticComponent<Props & RefAttributes<Ref>>
-) => {
- // We're not actually wrapping BaseLink (no way to wrap with Remix's Link),
- // but this is still useful because we're making sure that props/ref types are compatible
- const Component = forwardRef<Ref, Props>(({ href = "", ...props }, ref) => {
- const isAbsolute = isAbsoluteUrl(href);
+type LinkComponent = typeof Link;
+type LinkProps = ComponentPropsWithoutRef<LinkComponent>;
- // This is a workaround for a bug in Remix: https://github.com/remix-run/remix/issues/5440
- // It has a buggy absolute URL detection, which gives false positives on value like "//" or "http://"
- // and causes entire app to crash
- const willRemixTryToTreatAsAbsoluteAndCrash =
- isAbsolute === false && isAbsoluteUrlRemix(href);
+export const wrapLinkComponent = (BaseLink: LinkComponent) => {
+ const Component: LinkComponent = forwardRef((props: LinkProps, ref) => {
+ const href = usePropUrl(getInstanceIdFromComponentProps(props), "href");
- if (isAbsolute || willRemixTryToTreatAsAbsoluteAndCrash) {
- return (
- <BaseLink
- {...props}
- href={willRemixTryToTreatAsAbsoluteAndCrash ? "" : href}
- ref={ref}
- />
- );
+ if (typeof href === "string" || href === undefined) {
+ return <BaseLink {...props} ref={ref} />;
}
- return <Link {...props} to={href} ref={ref} />;
+ return <RemixLink {...props} to={href.path} ref={ref} />;
});
- // This is the only part that we use from BaseLink at runtime
Component.displayName = BaseLink.displayName;
return Component;
diff --git a/packages/react-sdk/src/components/__generated__/link-block.props.ts b/packages/react-sdk/src/components/__generated__/link-block.props.ts
index 52ca7c56be..a265aab0fc 100644
--- a/packages/react-sdk/src/components/__generated__/link-block.props.ts
+++ b/packages/react-sdk/src/components/__generated__/link-block.props.ts
@@ -4,18 +4,18 @@ export const props: Record<string, PropMeta> = {
slot: { required: false, control: "text", type: "string" },
style: { required: false, control: "text", type: "string" },
title: { required: false, control: "text", type: "string" },
- download: { required: false, control: "text", type: "string" },
href: { required: false, control: "text", type: "string" },
- hrefLang: { required: false, control: "text", type: "string" },
- media: { required: false, control: "text", type: "string" },
- ping: { required: false, control: "text", type: "string" },
- rel: { required: false, control: "text", type: "string" },
target: {
required: false,
control: "select",
type: "string",
options: ["_self", "_blank", "_parent", "_top"],
},
+ download: { required: false, control: "text", type: "string" },
+ hrefLang: { required: false, control: "text", type: "string" },
+ media: { required: false, control: "text", type: "string" },
+ ping: { required: false, control: "text", type: "string" },
+ rel: { required: false, control: "text", type: "string" },
type: { required: false, control: "text", type: "string" },
referrerPolicy: {
required: false,
diff --git a/packages/react-sdk/src/components/__generated__/link.props.ts b/packages/react-sdk/src/components/__generated__/link.props.ts
index cdb81d3111..a265aab0fc 100644
--- a/packages/react-sdk/src/components/__generated__/link.props.ts
+++ b/packages/react-sdk/src/components/__generated__/link.props.ts
@@ -4,18 +4,18 @@ export const props: Record<string, PropMeta> = {
slot: { required: false, control: "text", type: "string" },
style: { required: false, control: "text", type: "string" },
title: { required: false, control: "text", type: "string" },
- download: { required: false, control: "text", type: "string" },
- href: { required: false, control: "text", type: "string", defaultValue: "" },
- hrefLang: { required: false, control: "text", type: "string" },
- media: { required: false, control: "text", type: "string" },
- ping: { required: false, control: "text", type: "string" },
- rel: { required: false, control: "text", type: "string" },
+ href: { required: false, control: "text", type: "string" },
target: {
required: false,
control: "select",
type: "string",
options: ["_self", "_blank", "_parent", "_top"],
},
+ download: { required: false, control: "text", type: "string" },
+ hrefLang: { required: false, control: "text", type: "string" },
+ media: { required: false, control: "text", type: "string" },
+ ping: { required: false, control: "text", type: "string" },
+ rel: { required: false, control: "text", type: "string" },
type: { required: false, control: "text", type: "string" },
referrerPolicy: {
required: false,
diff --git a/packages/react-sdk/src/components/__generated__/rich-text-link.props.ts b/packages/react-sdk/src/components/__generated__/rich-text-link.props.ts
index 52ca7c56be..a265aab0fc 100644
--- a/packages/react-sdk/src/components/__generated__/rich-text-link.props.ts
+++ b/packages/react-sdk/src/components/__generated__/rich-text-link.props.ts
@@ -4,18 +4,18 @@ export const props: Record<string, PropMeta> = {
slot: { required: false, control: "text", type: "string" },
style: { required: false, control: "text", type: "string" },
title: { required: false, control: "text", type: "string" },
- download: { required: false, control: "text", type: "string" },
href: { required: false, control: "text", type: "string" },
- hrefLang: { required: false, control: "text", type: "string" },
- media: { required: false, control: "text", type: "string" },
- ping: { required: false, control: "text", type: "string" },
- rel: { required: false, control: "text", type: "string" },
target: {
required: false,
control: "select",
type: "string",
options: ["_self", "_blank", "_parent", "_top"],
},
+ download: { required: false, control: "text", type: "string" },
+ hrefLang: { required: false, control: "text", type: "string" },
+ media: { required: false, control: "text", type: "string" },
+ ping: { required: false, control: "text", type: "string" },
+ rel: { required: false, control: "text", type: "string" },
type: { required: false, control: "text", type: "string" },
referrerPolicy: {
required: false,
diff --git a/packages/react-sdk/src/components/link-block.ws.tsx b/packages/react-sdk/src/components/link-block.ws.tsx
index 7cbc77ae32..c940962a5e 100644
--- a/packages/react-sdk/src/components/link-block.ws.tsx
+++ b/packages/react-sdk/src/components/link-block.ws.tsx
@@ -1,6 +1,7 @@
import { BoxLinkIcon } from "@webstudio-is/icons";
import type { WsComponentMeta, WsComponentPropsMeta } from "./component-meta";
import { props } from "./__generated__/link-block.props";
+import { propsMeta as linkPropsMeta } from "./link.ws";
const presetStyle = {
boxSizing: {
@@ -22,6 +23,9 @@ export const meta: WsComponentMeta = {
};
export const propsMeta: WsComponentPropsMeta = {
- props,
- initialProps: ["href", "target", "prefetch"],
+ props: {
+ ...props,
+ href: linkPropsMeta.props.href,
+ },
+ initialProps: linkPropsMeta.initialProps,
};
diff --git a/packages/react-sdk/src/components/link.tsx b/packages/react-sdk/src/components/link.tsx
index 33923f1b36..0bafa36506 100644
--- a/packages/react-sdk/src/components/link.tsx
+++ b/packages/react-sdk/src/components/link.tsx
@@ -1,4 +1,5 @@
-import { forwardRef, type ElementRef, type ComponentProps } from "react";
+import { forwardRef, type ComponentProps } from "react";
+import { usePropUrl, getInstanceIdFromComponentProps } from "../props";
// @todo props that come from remix link, shouldn't be here at all
// - prefetch should be only on remix component and it already is
@@ -10,10 +11,15 @@ type Props = Omit<ComponentProps<"a">, "href" | "target"> & {
prefetch?: "none" | "intent" | "render";
};
-export const Link = forwardRef<ElementRef<"a">, Props>(
- ({ href = "", ...props }, ref) => {
- return <a {...props} href={href} ref={ref} />;
- }
-);
+export const Link = forwardRef<HTMLAnchorElement, Props>((props, ref) => {
+ const href = usePropUrl(getInstanceIdFromComponentProps(props), "href");
+ return (
+ <a
+ {...props}
+ href={typeof href === "string" ? href : href?.path}
+ ref={ref}
+ />
+ );
+});
Link.displayName = "Link";
diff --git a/packages/react-sdk/src/components/link.ws.tsx b/packages/react-sdk/src/components/link.ws.tsx
index 732c0e04a4..3277e94971 100644
--- a/packages/react-sdk/src/components/link.ws.tsx
+++ b/packages/react-sdk/src/components/link.ws.tsx
@@ -24,6 +24,13 @@ export const meta: WsComponentMeta = {
};
export const propsMeta: WsComponentPropsMeta = {
- props,
+ props: {
+ ...props,
+ href: {
+ type: "string",
+ control: "url",
+ required: false,
+ },
+ },
initialProps: ["href", "target", "prefetch"],
};
diff --git a/packages/react-sdk/src/components/rich-text-link.ws.tsx b/packages/react-sdk/src/components/rich-text-link.ws.tsx
index f30660f302..5a1378ce0b 100644
--- a/packages/react-sdk/src/components/rich-text-link.ws.tsx
+++ b/packages/react-sdk/src/components/rich-text-link.ws.tsx
@@ -1,6 +1,6 @@
import type { WsComponentMeta, WsComponentPropsMeta } from "./component-meta";
import { props } from "./__generated__/rich-text-link.props";
-import { meta as linkMeta, propsMeta as propsLinkMeta } from "./link.ws";
+import { meta as linkMeta, propsMeta as linkPropsMeta } from "./link.ws";
const { category, ...linkMetaRest } = linkMeta;
@@ -11,6 +11,9 @@ export const meta: WsComponentMeta = {
};
export const propsMeta: WsComponentPropsMeta = {
- ...propsLinkMeta,
- props,
+ initialProps: linkPropsMeta.initialProps,
+ props: {
+ ...props,
+ href: linkPropsMeta.props.href,
+ },
};
diff --git a/packages/react-sdk/src/context.tsx b/packages/react-sdk/src/context.tsx
index 2b1e62b81d..b4c43fc9ad 100644
--- a/packages/react-sdk/src/context.tsx
+++ b/packages/react-sdk/src/context.tsx
@@ -1,11 +1,13 @@
import { type ReadableAtom, atom } from "nanostores";
import { createContext } from "react";
-import type { Assets, PropsByInstanceId } from "./props";
+import type { Assets, Pages, PropsByInstanceId } from "./props";
export const ReactSdkContext = createContext<{
propsByInstanceIdStore: ReadableAtom<PropsByInstanceId>;
assetsStore: ReadableAtom<Assets>;
+ pagesStore: ReadableAtom<Pages>;
}>({
propsByInstanceIdStore: atom(new Map()),
assetsStore: atom(new Map()),
+ pagesStore: atom(new Map()),
});
diff --git a/packages/react-sdk/src/props.test.ts b/packages/react-sdk/src/props.test.ts
new file mode 100644
index 0000000000..edcd976803
--- /dev/null
+++ b/packages/react-sdk/src/props.test.ts
@@ -0,0 +1,95 @@
+import { describe, test, expect } from "@jest/globals";
+import { resolveUrlProp, type Pages, type PropsByInstanceId } from "./props";
+import type { Page, Prop } from "@webstudio-is/project-build";
+
+const unique = () => Math.random().toString();
+
+describe("resolveUrlProp", () => {
+ const instanceId = unique();
+
+ const page1: Page = {
+ id: unique(),
+ path: `/${unique()}`,
+ name: "",
+ title: "",
+ meta: {},
+ rootInstanceId: "0",
+ };
+
+ const page2: Page = {
+ id: unique(),
+ path: `/${unique()}`,
+ name: "",
+ title: "",
+ meta: {},
+ rootInstanceId: "0",
+ };
+
+ const pageByIdProp: Prop = {
+ type: "page",
+ id: unique(),
+ instanceId,
+ name: unique(),
+ value: page1.id,
+ };
+
+ const pageByPathProp: Prop = {
+ type: "string",
+ id: unique(),
+ instanceId,
+ name: unique(),
+ value: page2.path,
+ };
+
+ const arbitraryUrlProp: Prop = {
+ type: "string",
+ id: unique(),
+ instanceId,
+ name: unique(),
+ value: unique(),
+ };
+
+ const propsByInstanceId: PropsByInstanceId = new Map([
+ [instanceId, [pageByIdProp, pageByPathProp, arbitraryUrlProp]],
+ ]);
+
+ const pages: Pages = new Map([
+ [page1.id, page1],
+ [page2.id, page2],
+ ]);
+
+ test("if instanceId is unknown returns undefined", () => {
+ expect(
+ resolveUrlProp("unknown", pageByIdProp.name, propsByInstanceId, pages)
+ ).toBeUndefined();
+ });
+
+ test("if prop name is unknown returns undefined", () => {
+ expect(
+ resolveUrlProp(instanceId, "unknown", propsByInstanceId, pages)
+ ).toBeUndefined();
+ });
+
+ test("page by id", () => {
+ expect(
+ resolveUrlProp(instanceId, pageByIdProp.name, propsByInstanceId, pages)
+ ).toBe(page1);
+ });
+
+ test("page by path", () => {
+ expect(
+ resolveUrlProp(instanceId, pageByPathProp.name, propsByInstanceId, pages)
+ ).toBe(page2);
+ });
+
+ test("arbitrary url", () => {
+ expect(
+ resolveUrlProp(
+ instanceId,
+ arbitraryUrlProp.name,
+ propsByInstanceId,
+ pages
+ )
+ ).toBe(arbitraryUrlProp.value);
+ });
+});
diff --git a/packages/react-sdk/src/props.ts b/packages/react-sdk/src/props.ts
index 00342f74ed..9b82bdf137 100644
--- a/packages/react-sdk/src/props.ts
+++ b/packages/react-sdk/src/props.ts
@@ -1,13 +1,15 @@
import { useContext, useMemo } from "react";
import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
-import type { Instance, Prop, Props } from "@webstudio-is/project-build";
+import type { Instance, Page, Prop, Props } from "@webstudio-is/project-build";
import type { Asset } from "@webstudio-is/asset-uploader";
import { ReactSdkContext } from "./context";
+import { idAttribute } from "./tree/webstudio-component";
export type PropsByInstanceId = Map<Instance["id"], Prop[]>;
export type Assets = Map<Asset["id"], Asset>;
+export type Pages = Map<Page["id"], Page>;
export const getPropsByInstanceId = (props: Props) => {
const propsByInstanceId: PropsByInstanceId = new Map();
@@ -39,7 +41,7 @@ export const useInstanceProps = (instanceId: Instance["id"]) => {
return instancePropsObject;
};
-// this utility is be used for image component in both builder and preview
+// this utility is used for image component in both builder and preview
// so need to optimize rerenders with computed
export const usePropAsset = (instanceId: Instance["id"], name: string) => {
const { propsByInstanceIdStore, assetsStore } = useContext(ReactSdkContext);
@@ -49,7 +51,7 @@ export const usePropAsset = (instanceId: Instance["id"], name: string) => {
(propsByInstanceId, assets) => {
const instanceProps = propsByInstanceId.get(instanceId);
if (instanceProps === undefined) {
- return undefined;
+ return;
}
for (const prop of instanceProps) {
if (prop.type === "asset" && prop.name === name) {
@@ -63,3 +65,57 @@ export const usePropAsset = (instanceId: Instance["id"], name: string) => {
const asset = useStore(assetStore);
return asset;
};
+
+export const resolveUrlProp = (
+ instanceId: Instance["id"],
+ name: string,
+ propsByInstanceId: PropsByInstanceId,
+ pages: Pages
+): Page | string | undefined => {
+ const instanceProps = propsByInstanceId.get(instanceId);
+ if (instanceProps === undefined) {
+ return;
+ }
+ for (const prop of instanceProps) {
+ if (prop.name !== name) {
+ continue;
+ }
+
+ if (prop.type === "page") {
+ return pages.get(prop.value);
+ }
+
+ if (prop.type === "string") {
+ for (const page of pages.values()) {
+ if (page.path === prop.value) {
+ return page;
+ }
+ }
+ return prop.value;
+ }
+
+ return;
+ }
+};
+
+// this utility is used for link component in both builder and preview
+// so need to optimize rerenders with computed
+export const usePropUrl = (instanceId: Instance["id"], name: string) => {
+ const { propsByInstanceIdStore, pagesStore } = useContext(ReactSdkContext);
+ const pageStore = useMemo(
+ () =>
+ computed(
+ [propsByInstanceIdStore, pagesStore],
+ (propsByInstanceId, pages) =>
+ resolveUrlProp(instanceId, name, propsByInstanceId, pages)
+ ),
+ [propsByInstanceIdStore, pagesStore, instanceId, name]
+ );
+ return useStore(pageStore);
+};
+
+export const getInstanceIdFromComponentProps = (
+ props: Record<string, unknown>
+) => {
+ return props[idAttribute] as string;
+};
diff --git a/packages/react-sdk/src/tree/create-elements-tree.tsx b/packages/react-sdk/src/tree/create-elements-tree.tsx
index 382b0d4ba9..52254ca0ef 100644
--- a/packages/react-sdk/src/tree/create-elements-tree.tsx
+++ b/packages/react-sdk/src/tree/create-elements-tree.tsx
@@ -4,7 +4,7 @@ import { Scripts, ScrollRestoration } from "@remix-run/react";
import type { Instance } from "@webstudio-is/project-build";
import type { GetComponent } from "../components/components-utils";
import { ReactSdkContext } from "../context";
-import type { Assets, PropsByInstanceId } from "../props";
+import type { Assets, Pages, PropsByInstanceId } from "../props";
import type { WebstudioComponent } from "./webstudio-component";
import { SessionStoragePolyfill } from "./session-storage-polyfill";
@@ -15,6 +15,7 @@ export const createElementsTree = ({
instance,
propsByInstanceIdStore,
assetsStore,
+ pagesStore,
Component,
getComponent,
}: {
@@ -22,6 +23,7 @@ export const createElementsTree = ({
instance: Instance;
propsByInstanceIdStore: ReadableAtom<PropsByInstanceId>;
assetsStore: ReadableAtom<Assets>;
+ pagesStore: ReadableAtom<Pages>;
Component: (props: ComponentProps<typeof WebstudioComponent>) => JSX.Element;
getComponent: GetComponent;
}) => {
@@ -47,7 +49,9 @@ export const createElementsTree = ({
getComponent,
});
return (
- <ReactSdkContext.Provider value={{ propsByInstanceIdStore, assetsStore }}>
+ <ReactSdkContext.Provider
+ value={{ propsByInstanceIdStore, assetsStore, pagesStore }}
+ >
{root}
</ReactSdkContext.Provider>
);
diff --git a/packages/react-sdk/src/tree/root.ts b/packages/react-sdk/src/tree/root.ts
index 89c4c4da72..fd151a1d17 100644
--- a/packages/react-sdk/src/tree/root.ts
+++ b/packages/react-sdk/src/tree/root.ts
@@ -18,6 +18,7 @@ import type { GetComponent } from "../components/components-utils";
export type Data = {
page: Page;
+ pages: Array<Page>;
build: Build;
assets: Array<Asset>;
params?: Params;
@@ -86,6 +87,7 @@ export const InstanceRoot = ({
getPropsByInstanceId(new Map(data.build.props))
),
assetsStore: atom(new Map(data.assets.map((asset) => [asset.id, asset]))),
+ pagesStore: atom(new Map(data.pages.map((page) => [page.id, page]))),
Component: Component ?? WebstudioComponent,
getComponent,
});