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.

Validate pages on client (#1221)

Bogdan Chadkin9a7b61a49129
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx
index 7afd903562..2f84efc794 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx
@@ -1,4 +1,4 @@
-import type { ZodError } from "zod";
+import { z } from "zod";
import { useState, useCallback, ComponentProps } from "react";
import { useDebouncedCallback } from "use-debounce";
import { useUnmount } from "react-use";
@@ -8,6 +8,10 @@ import {
type Page,
type Pages,
findPageByIdOrPath,
+ PageName,
+ HomePagePath,
+ PageTitle,
+ PagePath,
} from "@webstudio-is/project-build";
import {
theme,
@@ -28,7 +32,6 @@ import {
normalizeErrors,
toastUnknownFieldErrors,
useIds,
- useFetcherErrors,
} from "~/shared/form-utils";
import type {
DeletePageData,
@@ -47,16 +50,42 @@ const Group = styled(Flex, {
const fieldNames = ["name", "path", "title", "description"] as const;
type FieldName = (typeof fieldNames)[number];
-type FormPage = Pick<Page, "name" | "path" | "title"> & {
- description: string;
+type Values = {
+ [fieldName in FieldName]: string;
};
+type Errors = {
+ [fieldName in FieldName]?: string[];
+};
+
+const HomePageValues = z.object({
+ name: PageName,
+ path: HomePagePath,
+ title: PageTitle,
+ description: z.string().optional(),
+});
+
+const PageValues = z.object({
+ name: PageName,
+ path: PagePath,
+ title: PageTitle,
+ description: z.string().optional(),
+});
-const toFormPage = (page: Page): FormPage => {
+const getErrors = (values: Values, isHomePage: boolean): Errors => {
+ const Validator = isHomePage ? HomePageValues : PageValues;
+ const parsedResult = Validator.safeParse(values);
+ if (parsedResult.success) {
+ return {};
+ }
+ return parsedResult.error.formErrors.fieldErrors;
+};
+
+const toFormPage = (page?: Page): Values => {
return {
- name: page.name,
- path: page.path,
- title: page.title,
- description: page.meta.description ?? "",
+ name: page?.name ?? "",
+ path: page?.path ?? "",
+ title: page?.title ?? "",
+ description: page?.meta.description ?? "",
};
};
@@ -67,19 +96,19 @@ const FormFields = ({
disabled,
autoSelect,
isHomePage,
+ errors,
values,
onChange,
- fieldErrors,
}: {
disabled?: boolean;
autoSelect?: boolean;
isHomePage?: boolean;
- values: FormPage;
+ errors: Errors;
+ values: Values;
onChange: <Name extends FieldName>(event: {
field: Name;
- value: FormPage[Name];
+ value: Values[Name];
}) => void;
- fieldErrors: ZodError["formErrors"]["fieldErrors"];
}) => {
const fieldIds = useIds(fieldNames);
@@ -87,10 +116,10 @@ const FormFields = ({
<>
<Group>
<DeprecatedLabel htmlFor={fieldIds.name}>Page Name</DeprecatedLabel>
- <InputErrorsTooltip errors={fieldErrors.name}>
+ <InputErrorsTooltip errors={errors.name}>
<TextField
tabIndex={1}
- state={fieldErrors.name && "invalid"}
+ state={errors.name && "invalid"}
id={fieldIds.name}
autoFocus
onFocus={autoSelect ? autoSelectHandler : undefined}
@@ -107,10 +136,10 @@ const FormFields = ({
{isHomePage !== true && (
<Group>
<DeprecatedLabel htmlFor={fieldIds.path}>Path</DeprecatedLabel>
- <InputErrorsTooltip errors={fieldErrors.path}>
+ <InputErrorsTooltip errors={errors.path}>
<TextField
tabIndex={1}
- state={fieldErrors.path && "invalid"}
+ state={errors.path && "invalid"}
id={fieldIds.path}
name="path"
placeholder="/about"
@@ -125,10 +154,10 @@ const FormFields = ({
)}
<Group>
<DeprecatedLabel htmlFor={fieldIds.title}>Title</DeprecatedLabel>
- <InputErrorsTooltip errors={fieldErrors.title}>
+ <InputErrorsTooltip errors={errors.title}>
<TextField
tabIndex={1}
- state={fieldErrors.title && "invalid"}
+ state={errors.title && "invalid"}
id={fieldIds.title}
name="title"
placeholder="My awesome site - About"
@@ -144,10 +173,10 @@ const FormFields = ({
<DeprecatedLabel htmlFor={fieldIds.description}>
Description
</DeprecatedLabel>
- <InputErrorsTooltip errors={fieldErrors.description}>
+ <InputErrorsTooltip errors={errors.description}>
<TextArea
tabIndex={1}
- state={fieldErrors.description && "invalid"}
+ state={errors.description && "invalid"}
id={fieldIds.description}
name="description"
disabled={disabled}
@@ -209,23 +238,21 @@ export const NewPageSettings = ({
const isSubmitting = fetcher.state !== "idle";
- const { fieldErrors, resetFieldError } = useFetcherErrors({
- fetcher,
- fieldNames,
- });
-
- const [values, setValues] = useState<FormPage>({
+ const [values, setValues] = useState<Values>({
name: "Untitled",
path: nameToPath(pages, "Untitled"),
title: "Untitled",
description: "",
});
+ const errors = getErrors(values, false);
const handleSubmit = () => {
- fetcher.submit(values, {
- method: "put",
- action: restPagesPath({ projectId }),
- });
+ if (Object.keys(errors).length === 0) {
+ fetcher.submit(values, {
+ method: "put",
+ action: restPagesPath({ projectId }),
+ });
+ }
};
return (
@@ -233,14 +260,12 @@ export const NewPageSettings = ({
onSubmit={handleSubmit}
onClose={onClose}
isSubmitting={isSubmitting}
- fieldErrors={fieldErrors}
+ errors={errors}
disabled={isSubmitting}
values={values}
onChange={({ field, value }) => {
- resetFieldError(field);
setValues((values) => {
const changes = { [field]: value };
-
if (field === "name") {
if (values.path === nameToPath(pages, values.name)) {
changes.path = nameToPath(pages, value);
@@ -249,7 +274,6 @@ export const NewPageSettings = ({
changes.title = value;
}
}
-
return { ...values, ...changes };
});
}}
@@ -317,7 +341,7 @@ const NewPageSettingsView = ({
);
};
-const toFormData = (page: Partial<FormPage> & { id: string }): FormData => {
+const toFormData = (page: Partial<Values> & { id: string }): FormData => {
const formData = new FormData();
for (const [key, value] of Object.entries(page)) {
// @todo: handle "meta"
@@ -377,18 +401,21 @@ export const PageSettings = ({
const isHomePage = page?.id === pages?.homePage.id;
- const [unsavedValues, setUnsavedValues] = useState<Partial<FormPage>>({});
- const [submittedValues, setSubmittedValues] = useState<Partial<FormPage>>({});
+ const [unsavedValues, setUnsavedValues] = useState<Partial<Values>>({});
+ const [submittedValues, setSubmittedValues] = useState<Partial<Values>>({});
- const { fieldErrors, resetFieldError } = useFetcherErrors({
- fetcher,
- fieldNames: isHomePage
- ? fieldNames.filter((name) => name !== "path")
- : fieldNames,
- });
+ const values: Values = {
+ ...toFormPage(page),
+ ...submittedValues,
+ ...unsavedValues,
+ };
+ const errors = getErrors(values, isHomePage);
const handleSubmitDebounced = useDebouncedCallback(() => {
- if (Object.keys(unsavedValues).length === 0) {
+ if (
+ Object.keys(unsavedValues).length === 0 ||
+ Object.keys(errors).length !== 0
+ ) {
return;
}
@@ -406,12 +433,14 @@ export const PageSettings = ({
}, 1000);
const handleChange = useCallback(
- <Name extends FieldName>(event: { field: Name; value: FormPage[Name] }) => {
- resetFieldError(event.field);
- setUnsavedValues((values) => ({ ...values, [event.field]: event.value }));
+ <Name extends FieldName>(event: { field: Name; value: Values[Name] }) => {
+ setUnsavedValues((values) => ({
+ ...values,
+ [event.field]: event.value,
+ }));
handleSubmitDebounced();
},
- [handleSubmitDebounced, resetFieldError]
+ [handleSubmitDebounced]
);
useUnmount(() => {
@@ -468,8 +497,8 @@ export const PageSettings = ({
isHomePage={isHomePage}
onClose={onClose}
onDelete={hanldeDelete}
- fieldErrors={fieldErrors}
- values={{ ...toFormPage(page), ...submittedValues, ...unsavedValues }}
+ errors={errors}
+ values={values}
onChange={handleChange}
/>
);
diff --git a/apps/builder/app/shared/form-utils/validation.ts b/apps/builder/app/shared/form-utils/validation.ts
index e3883e4197..6330a3245f 100644
--- a/apps/builder/app/shared/form-utils/validation.ts
+++ b/apps/builder/app/shared/form-utils/validation.ts
@@ -1,8 +1,5 @@
-import type { Fetcher } from "@remix-run/react";
import { toast } from "@webstudio-is/design-system";
-import { useCallback, useState } from "react";
import type { ZodError } from "zod";
-import { useOnFetchEnd } from "~/shared/fetcher";
export type FetcherData<Payload> =
| ({ status: "ok" } & Payload)
@@ -15,35 +12,6 @@ export const normalizeErrors = (
? { formErrors: [errors], fieldErrors: {} }
: errors;
-export const useFetcherErrors = <FieldName extends string>({
- fetcher,
- fieldNames,
-}: {
- fetcher: Fetcher<FetcherData<unknown>>;
- fieldNames?: readonly FieldName[];
-}): {
- fieldErrors: ZodError["formErrors"]["fieldErrors"];
- resetFieldError: (fieldName: FieldName) => void;
-} => {
- const [fieldErrors, setFieldErrors] = useState<
- ZodError["formErrors"]["fieldErrors"]
- >({});
-
- useOnFetchEnd(fetcher, (data) => {
- if (data.status === "error") {
- const errors = normalizeErrors(data.errors);
- toastUnknownFieldErrors(errors, fieldNames);
- setFieldErrors(errors.fieldErrors);
- }
- });
-
- const resetFieldError = useCallback((fieldName: FieldName) => {
- setFieldErrors(({ [fieldName]: _, ...rest }) => rest);
- }, []);
-
- return { fieldErrors, resetFieldError };
-};
-
// Show a toast for each of formErrors
// as well as fieldErrors which we cannot display near a corresponding field
export const toastUnknownFieldErrors = (
diff --git a/packages/project-build/src/schema/pages.ts b/packages/project-build/src/schema/pages.ts
index 3d6e866cd8..d03deb02c4 100644
--- a/packages/project-build/src/schema/pages.ts
+++ b/packages/project-build/src/schema/pages.ts
@@ -2,7 +2,11 @@ import { z, type ZodType } from "zod";
const MIN_TITLE_LENGTH = 2;
-const Title = z
+export const PageName = z
+ .string()
+ .refine((value) => value.trim() !== "", "Can't be empty");
+
+export const PageTitle = z
.string()
.refine(
(val) => val.length >= MIN_TITLE_LENGTH,
@@ -11,17 +15,19 @@ const Title = z
const commonPageFields = {
id: z.string(),
- name: z.string().refine((val) => val !== "", "Can't be empty"),
- title: Title,
+ name: PageName,
+ title: PageTitle,
meta: z.record(z.string(), z.string()),
rootInstanceId: z.string(),
} as const;
+export const HomePagePath = z
+ .string()
+ .refine((path) => path === "", "Home page path must be empty");
+
const HomePage = z.object({
...commonPageFields,
- path: z
- .string()
- .refine((path) => path === "", "Home page path must be empty"),
+ path: HomePagePath,
});
export const pathValidators = (
@@ -55,9 +61,11 @@ export const pathValidators = (
"/build prefix is reserved for the system"
);
+export const PagePath = pathValidators(z.string());
+
const Page = z.object({
...commonPageFields,
- path: pathValidators(z.string()),
+ path: PagePath,
});
export type Page = z.infer<typeof Page>;