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.

experimental: improve address bar UI (#2919)

Bogdan Chadkin51e26938726c
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/address-bar.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/address-bar.tsx
index 89a6689a69..242fd3f9b3 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/address-bar.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/address-bar.tsx
@@ -1,18 +1,26 @@
import { computed } from "nanostores";
import { useStore } from "@nanostores/react";
-import { Fragment, useEffect, useId, useState } from "react";
+import { useEffect, useId, useState } from "react";
import {
Button,
+ Flex,
Grid,
InputField,
Label,
Tooltip,
+ theme,
+ textVariants,
+ InputErrorsTooltip,
} from "@webstudio-is/design-system";
import { CheckMarkIcon, CopyIcon, LinkIcon } from "@webstudio-is/icons";
import type { DataSource } from "@webstudio-is/sdk";
import { $dataSourceVariables, $domains, $project } from "~/shared/nano-states";
import env from "~/shared/env";
-import { compilePathnamePattern, parsePathnamePattern } from "./url-pattern";
+import {
+ compilePathnamePattern,
+ parsePathnamePattern,
+ tokenizePathnamePattern,
+} from "./url-pattern";
import { $userPlanFeatures } from "~/builder/shared/nano-states";
const $publishedOrigin = computed([$project, $domains], (project, domains) => {
@@ -28,7 +36,7 @@ const $publishedOrigin = computed([$project, $domains], (project, domains) => {
type PathParams = Record<string, string>;
export type AddressBarApi = {
- pathParamNames: string[];
+ path: string;
pathParams: PathParams;
pageUrl: string;
updatePathParam: (name: string, value: string) => void;
@@ -61,7 +69,8 @@ export const useAddressBar = ({
const pathParams = storedParams ?? localParams;
const publishedOrigin = useStore($publishedOrigin);
- const compiledPath = compilePathnamePattern(path, pathParams);
+ const tokens = tokenizePathnamePattern(path);
+ const compiledPath = compilePathnamePattern(tokens, pathParams);
const pageUrl = `${publishedOrigin}${compiledPath}`;
const updatePathParam: AddressBarApi["updatePathParam"] = (name, value) => {
@@ -88,7 +97,7 @@ export const useAddressBar = ({
};
return {
- pathParamNames,
+ path,
pathParams,
pageUrl,
updatePathParam,
@@ -164,27 +173,78 @@ const CopyPageUrl = ({
};
export const AddressBar = ({ addressBar }: { addressBar: AddressBarApi }) => {
- const { pathParamNames, pathParams, pageUrl, updatePathParam } = addressBar;
+ const { path, pathParams, pageUrl, updatePathParam } = addressBar;
const id = useId();
const { allowDynamicData } = useStore($userPlanFeatures);
+ const tokens = tokenizePathnamePattern(path);
+ const hasParams = tokens.length > 1;
+
+ const errors = new Map<string, string>();
+ for (const token of tokens) {
+ if (token.type === "param") {
+ const value = (pathParams[token.name] ?? "").trim();
+ if (value === "" && token.optional === false) {
+ errors.set(token.name, `"${token.name}" is required`);
+ }
+ if (value.includes("/") && token.splat === false) {
+ errors.set(
+ token.name,
+ `"${token.name}" should be splat parameter to contain slashes`
+ );
+ }
+ }
+ }
+
return (
<Grid gap={1}>
- {allowDynamicData &&
- pathParamNames.map((name) => (
- <Fragment key={name}>
- <Label htmlFor={`${id}-${name}`}>{name}</Label>
- <InputField
- tabIndex={1}
- id={`${id}-${name}`}
- value={pathParams[name] ?? ""}
- onChange={(event) => updatePathParam(name, event.target.value)}
- />
- </Fragment>
- ))}
+ {allowDynamicData && hasParams && (
+ <>
+ <Label htmlFor={id}>Address Bar</Label>
+ <InputErrorsTooltip errors={Array.from(errors.values())}>
+ <Flex
+ align="center"
+ css={{
+ padding: theme.spacing[5],
+ // background: theme.colors.white,
+ borderRadius: theme.borderRadius[4],
+ border: `1px solid ${theme.colors.borderMain}`,
+ ...textVariants.mono,
+ }}
+ >
+ {tokens.map((token, index) => {
+ if (token.type === "fragment") {
+ return token.value;
+ }
+ if (token.type === "param") {
+ return (
+ <InputField
+ key={index}
+ fieldSizing="content"
+ css={{
+ margin: `0 ${theme.spacing[3]}`,
+ minWidth: theme.spacing[15],
+ }}
+ color={errors.has(token.name) ? "error" : undefined}
+ id={`${id}-${token.name}`}
+ placeholder={token.name}
+ value={pathParams[token.name] ?? ""}
+ onChange={(event) =>
+ updatePathParam(token.name, event.target.value)
+ }
+ />
+ );
+ }
+ token satisfies never;
+ })}
+ </Flex>
+ </InputErrorsTooltip>
+ </>
+ )}
+
<CopyPageUrl
pageUrl={pageUrl}
- disabled={allowDynamicData === false && pathParamNames.length > 0}
+ disabled={errors.size > 0 || (allowDynamicData === false && hasParams)}
/>
</Grid>
);
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.test.ts b/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.test.ts
index 798ced8c99..be378378ad 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.test.ts
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.test.ts
@@ -2,6 +2,7 @@ import { expect, test } from "@jest/globals";
import {
compilePathnamePattern,
parsePathnamePattern,
+ tokenizePathnamePattern,
validatePathnamePattern,
} from "./url-pattern";
@@ -13,15 +14,60 @@ test("parse wildcard and named wildcard from pathname pattern", () => {
expect(parsePathnamePattern("/blog/*/:slug*/*")).toEqual(["0", "1", "slug"]);
});
+test("tokenize named params in pathname pattern", () => {
+ expect(tokenizePathnamePattern("/blog/:id")).toEqual([
+ { type: "fragment", value: "/blog/" },
+ { type: "param", name: "id", optional: false, splat: false },
+ ]);
+ expect(tokenizePathnamePattern("/blog/:slug*")).toEqual([
+ { type: "fragment", value: "/blog/" },
+ { type: "param", name: "slug", optional: false, splat: true },
+ ]);
+ expect(tokenizePathnamePattern("/blog/:name?")).toEqual([
+ { type: "fragment", value: "/blog/" },
+ { type: "param", name: "name", optional: true, splat: false },
+ ]);
+ expect(tokenizePathnamePattern("/blog/*")).toEqual([
+ { type: "fragment", value: "/blog/" },
+ { type: "param", name: "0", optional: false, splat: true },
+ ]);
+});
+
+test("tokenize complex pathname pattern", () => {
+ expect(tokenizePathnamePattern("/blog/:date/:slug*")).toEqual([
+ { type: "fragment", value: "/blog/" },
+ { type: "param", name: "date", optional: false, splat: false },
+ { type: "fragment", value: "/" },
+ { type: "param", name: "slug", optional: false, splat: true },
+ ]);
+});
+
+test("tokenize trailing fragment", () => {
+ expect(tokenizePathnamePattern("/blog/:name/profile")).toEqual([
+ { type: "fragment", value: "/blog/" },
+ { type: "param", name: "name", optional: false, splat: false },
+ { type: "fragment", value: "/profile" },
+ ]);
+});
+
+test("tokenize pathname without params", () => {
+ expect(tokenizePathnamePattern("/blog/post")).toEqual([
+ { type: "fragment", value: "/blog/post" },
+ ]);
+});
+
test("compile pathname pattern with named values", () => {
expect(
- compilePathnamePattern("/blog/:id/:date", { id: "my-id", date: "my-date" })
+ compilePathnamePattern(tokenizePathnamePattern("/blog/:id/:date"), {
+ id: "my-id",
+ date: "my-date",
+ })
).toEqual("/blog/my-id/my-date");
});
test("compile pathname pattern with named wildcard", () => {
expect(
- compilePathnamePattern("/blog/:slug*/:date*", {
+ compilePathnamePattern(tokenizePathnamePattern("/blog/:slug*/:date*"), {
slug: "my-slug",
date: "my-date",
})
@@ -30,7 +76,7 @@ test("compile pathname pattern with named wildcard", () => {
test("compile pathname pattern with indexed wildcard", () => {
expect(
- compilePathnamePattern("/blog/*/:slug*/*", {
+ compilePathnamePattern(tokenizePathnamePattern("/blog/*/:slug*/*"), {
// use random order
1: "one",
slug: "my-slug",
@@ -41,34 +87,45 @@ test("compile pathname pattern with indexed wildcard", () => {
test("compile pathname pattern with many indexed wildcards (more than 10)", () => {
expect(
- compilePathnamePattern("/blog/*/*/*/*/*/*/*/*/*/*/*/*", {
- // use random order
- 11: "eleven",
- 10: "ten",
- 9: "nine",
- 8: "eight",
- 7: "seven",
- 6: "six",
- 5: "five",
- 4: "four",
- 3: "three",
- 2: "two",
- 1: "one",
- 0: "zero",
- })
+ compilePathnamePattern(
+ tokenizePathnamePattern("/blog/*/*/*/*/*/*/*/*/*/*/*/*"),
+ {
+ // use random order
+ 11: "eleven",
+ 10: "ten",
+ 9: "nine",
+ 8: "eight",
+ 7: "seven",
+ 6: "six",
+ 5: "five",
+ 4: "four",
+ 3: "three",
+ 2: "two",
+ 1: "one",
+ 0: "zero",
+ }
+ )
).toEqual(
"/blog/zero/one/two/three/four/five/six/seven/eight/nine/ten/eleven"
);
});
-test("ignore compiling empty values", () => {
+test("collapse empty values", () => {
expect(
- compilePathnamePattern("/blog/*/:slug", {
+ compilePathnamePattern(tokenizePathnamePattern("/blog/*/:slug"), {
// use random order
slug: "",
0: "",
})
- ).toEqual("/blog/*/:slug");
+ ).toEqual("/blog//");
+});
+
+test("collapse optional values with preceding slash", () => {
+ expect(
+ compilePathnamePattern(tokenizePathnamePattern("/blog/:slug?/:name?"), {
+ slug: "",
+ })
+ ).toEqual("/blog");
});
test("validate invalid pattern", () => {
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.ts b/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.ts
index 593fa8f3f3..3750a26e67 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.ts
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/url-pattern.ts
@@ -1,5 +1,11 @@
import { URLPattern } from "urlpattern-polyfill";
+// allowed syntax
+// :name - group without modifiers
+// :name? - group with optional modifier
+// :name* - group with zero or more modifier in the end
+// * - wildcard group in the end
+
const baseUrl = "http://url";
export const parsePathnamePattern = (pathname: string) => {
@@ -13,29 +19,74 @@ export const parsePathnamePattern = (pathname: string) => {
}
};
-const indexRegex = /^\d+$/;
+type Token =
+ | { type: "fragment"; value: string }
+ | { type: "param"; name: string; optional: boolean; splat: boolean };
+
+// /:slug -> { name: "slug", modifier: "" }
+// /:slug* -> { name: "slug", modifier: "*" }
+// /:slug? -> { name: "slug", modifier: "?" }
+// /* -> { wildcard: "*" }
+const tokenRegex = /:(?<name>\w+)(?<modifier>[?*]?)|(?<wildcard>(?<!:\w+)\*)/g;
+
+export const tokenizePathnamePattern = (pathname: string) => {
+ const tokens: Token[] = [];
+ let lastCursor = 0;
+ let lastWildcard = -1;
+
+ for (const match of pathname.matchAll(tokenRegex)) {
+ const cursor = match.index ?? 0;
+ if (lastCursor < cursor) {
+ tokens.push({
+ type: "fragment",
+ value: pathname.slice(lastCursor, cursor),
+ });
+ }
+ lastCursor = cursor + match[0].length;
+ if (match.groups?.name) {
+ const optional = match.groups.modifier === "?";
+ const splat = match.groups.modifier === "*";
+
+ tokens.push({ type: "param", name: match.groups.name, optional, splat });
+ }
+ if (match.groups?.wildcard) {
+ lastWildcard += 1;
+ tokens.push({
+ type: "param",
+ name: lastWildcard.toString(),
+ splat: true,
+ optional: false,
+ });
+ }
+ }
+ if (lastCursor < pathname.length) {
+ tokens.push({
+ type: "fragment",
+ value: pathname.slice(lastCursor),
+ });
+ }
+ return tokens;
+};
export const compilePathnamePattern = (
- pathname: string,
+ tokens: Token[],
values: Record<string, string>
) => {
- const entries = Object.entries(values)
- .sort(
- // sort only indexes, names order is not important
- ([leftName], [rightName]) => Number(leftName) - Number(rightName)
- )
- .filter(([_name, value]) => value.length > 0);
- for (const [name, value] of entries) {
- pathname = pathname.replaceAll(`:${name}*`, value);
- pathname = pathname.replaceAll(`:${name}`, value);
- }
- for (const [name, value] of entries) {
- if (indexRegex.test(name)) {
- // replace only first occurence
- pathname = pathname.replace(`*`, value);
+ let compiledPathname = "";
+ for (const token of tokens) {
+ if (token.type === "fragment") {
+ compiledPathname += token.value;
+ }
+ if (token.type === "param") {
+ const value = values[token.name] ?? "";
+ // remove preceding slash
+ if (token.optional && value.length === 0) {
+ compiledPathname = compiledPathname.slice(0, -1);
+ }
+ compiledPathname += value;
}
}
- return pathname;
+ return compiledPathname;
};
export const validatePathnamePattern = (pathname: string) => {
@@ -47,12 +98,6 @@ export const validatePathnamePattern = (pathname: string) => {
const messages: string[] = [];
- // allowed syntax
- // :name - group without modifiers
- // :name? - group with optional modifier
- // :name* - group with zero or more modifier in the end
- // * - wildcard group in the end
-
// fobid :name+ everywhere
const namedGroupsWithPlus = Array.from(pathname.matchAll(/:\w+\+/g)).flat();
if (namedGroupsWithPlus.length > 0) {
diff --git a/apps/builder/remix.config.js b/apps/builder/remix.config.js
index ae380fcac1..aa019dba27 100644
--- a/apps/builder/remix.config.js
+++ b/apps/builder/remix.config.js
@@ -38,6 +38,7 @@ module.exports = {
"strip-indent",
"change-case",
"title-case",
+ "react-field-sizing-content",
],
// appDirectory: "app",
// assetsBuildDirectory: "public/build",
diff --git a/packages/design-system/package.json b/packages/design-system/package.json
index fc2ae81d97..b88e74f72f 100644
--- a/packages/design-system/package.json
+++ b/packages/design-system/package.json
@@ -70,6 +70,7 @@
"downshift": "^6.1.7",
"immer": "^10.0.3",
"match-sorter": "^6.3.1",
+ "react-field-sizing-content": "^1.0.0",
"react-hot-toast": "^2.4.1",
"token-transformer": "^0.0.28",
"use-debounce": "^9.0.4",
diff --git a/packages/design-system/src/components/input-field.tsx b/packages/design-system/src/components/input-field.tsx
index 5161c25f5f..424281ed95 100644
--- a/packages/design-system/src/components/input-field.tsx
+++ b/packages/design-system/src/components/input-field.tsx
@@ -15,6 +15,10 @@ import { css, theme, type CSS } from "../stitches.config";
import { ArrowFocus } from "./primitives/arrow-focus";
import { mergeRefs } from "@react-aria/utils";
import { useFocusWithin } from "@react-aria/interactions";
+import {
+ type InputProps as InputWithFieldSizingProps,
+ Input as InputWithFieldSizing,
+} from "react-field-sizing-content";
// we only support types that behave more or less like a regular text input
export const inputFieldTypes = [
@@ -163,7 +167,7 @@ type InputProps = {
color?: (typeof inputFieldColors)[number];
css?: CSS;
variant?: "regular" | "mono";
-} & Omit<ComponentProps<"input">, "prefix" | "onFocus" | "onBlur">;
+} & Omit<InputWithFieldSizingProps, "prefix" | "onFocus" | "onBlur">;
const Input = forwardRef(
(
@@ -171,7 +175,7 @@ const Input = forwardRef(
ref: Ref<HTMLInputElement>
) => {
return (
- <input
+ <InputWithFieldSizing
{...props}
spellCheck={false}
data-input-field-input // to distinguish from potential other inputs in prefix/suffix
diff --git a/packages/design-system/src/components/tooltip.tsx b/packages/design-system/src/components/tooltip.tsx
index 00114407b7..7d355bd319 100644
--- a/packages/design-system/src/components/tooltip.tsx
+++ b/packages/design-system/src/components/tooltip.tsx
@@ -1,5 +1,5 @@
import type { Ref, ComponentProps, ReactNode, ReactElement } from "react";
-import { Fragment, forwardRef, useEffect } from "react";
+import { forwardRef, useEffect } from "react";
import { styled } from "../stitches.config";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { useControllableState } from "@radix-ui/react-use-controllable-state";
@@ -136,10 +136,7 @@ export const InputErrorsTooltip = ({
side?: ComponentProps<typeof Tooltip>["side"];
}) => {
const content = errors?.map((error, index) => (
- <Fragment key={index}>
- {index > 0 && <br />}
- <Text>{error}</Text>
- </Fragment>
+ <Text key={index}>{error}</Text>
));
return (
// We intentionally always pass non empty content to avoid optimization inside Tooltip
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 746d117348..cdaf5acb4f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1147,6 +1147,9 @@ importers:
match-sorter:
specifier: ^6.3.1
version: 6.3.1
+ react-field-sizing-content:
+ specifier: ^1.0.0
+ version: 1.0.0([email protected])
react-hot-toast:
specifier: ^2.4.1
@@ -15245,6 +15248,14 @@ packages:
react: 18.2.0
dev: false
+ resolution: {integrity: sha512-Wu9kaurnMn4AZ4kVxcR0rmbLKdCetqOSszB8KuauwU91cAKv1YPjhOLsbUyBB+11+yYpdFPoDSuasuQ5ruz0pg==}
+ peerDependencies:
+ react: ^17.0.0 || ^18.0.0
+ dependencies:
+ react: 18.2.0
+ dev: false
+
resolution: {integrity: sha512-j8z+cQbWIM5LY37pR6uZR6D4LfseplqnuAO4co4u8917hBUvXlEqyP1ZzqVLcqoyUesZZv/ImreoCeHVDpE5pQ==}
engines: {node: '>=10'}