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.

ability to add a page (wip)

Roman Pominovd25e8d972a1a
diff --git a/apps/designer/app/designer/features/sidebar-left/lib/header.tsx b/apps/designer/app/designer/features/sidebar-left/lib/header.tsx
index 0b47b76754..ef19be5b9e 100644
--- a/apps/designer/app/designer/features/sidebar-left/lib/header.tsx
+++ b/apps/designer/app/designer/features/sidebar-left/lib/header.tsx
@@ -2,13 +2,12 @@ import { Flex, IconButton, Text } from "@webstudio-is/design-system";
import { Separator } from "@webstudio-is/design-system";
import { Cross1Icon } from "@webstudio-is/icons";
-type HeaderProps = {
+type BaseHeaderProps = {
title: string;
- isClosable?: boolean;
- onClose?: () => void;
+ actions: React.ReactNode;
};
-export const Header = ({ title, isClosable = true, onClose }: HeaderProps) => {
+export const BaseHeader = ({ title, actions }: BaseHeaderProps) => {
return (
<>
<Flex
@@ -17,18 +16,30 @@ export const Header = ({ title, isClosable = true, onClose }: HeaderProps) => {
justify="between"
>
<Text variant="title">{title}</Text>
- {isClosable && (
- <IconButton
- onClick={() => onClose?.()}
- size="1"
- css={{ marginRight: "$2" }}
- aria-label="Close"
- >
- <Cross1Icon />
- </IconButton>
- )}
+ {actions && <Flex css={{ marginRight: "$1" }}>{actions}</Flex>}
</Flex>
<Separator css={{ height: 2 }} />
</>
);
};
+
+type HeaderProps = {
+ title: string;
+ isClosable?: boolean;
+ onClose?: () => void;
+};
+
+export const Header = ({ title, isClosable = true, onClose }: HeaderProps) => {
+ return (
+ <BaseHeader
+ title={title}
+ actions={
+ isClosable ? (
+ <IconButton onClick={() => onClose?.()} size="2" aria-label="Close">
+ <Cross1Icon />
+ </IconButton>
+ ) : null
+ }
+ />
+ );
+};
diff --git a/apps/designer/app/designer/features/sidebar-left/panels/pages/pages.tsx b/apps/designer/app/designer/features/sidebar-left/panels/pages/pages.tsx
index 72ce1c953d..8801c574f3 100644
--- a/apps/designer/app/designer/features/sidebar-left/panels/pages/pages.tsx
+++ b/apps/designer/app/designer/features/sidebar-left/panels/pages/pages.tsx
@@ -1,10 +1,15 @@
-import { TreeNodeLabel, TreeNode } from "@webstudio-is/design-system";
+import { useFetcher } from "@remix-run/react";
+import {
+ TreeNodeLabel,
+ TreeNode,
+ IconButton,
+} from "@webstudio-is/design-system";
import { type Publish } from "~/shared/pubsub";
-import { PageIcon } from "@webstudio-is/icons";
+import { Cross1Icon, NewPageIcon, PageIcon } from "@webstudio-is/icons";
import type { TabName } from "../../types";
-import { Header } from "../../lib/header";
+import { BaseHeader } from "../../lib/header";
import { type Page, type Pages } from "@webstudio-is/project";
-import { useMemo } from "react";
+import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { type Config } from "~/config";
import {
@@ -12,6 +17,8 @@ import {
usePages,
useProject,
} from "~/designer/shared/nano-states";
+import { SettingsPanel } from "./settings-panel";
+import { NewPageSettings } from "./settings";
type TabContentProps = {
onSetActiveTab: (tabName: TabName) => void;
@@ -60,20 +67,24 @@ const staticTreeProps = {
}
return (
- <TreeNodeLabel
- isSelected={props.isSelected}
- text={props.data.data.name}
- />
+ <>
+ <TreeNodeLabel
+ isSelected={props.isSelected}
+ text={props.data.data.name}
+ />
+ </>
);
},
};
const Pages = ({
onClose,
+ onNewPage,
onSelect,
selectedPageId,
}: {
- onClose: () => void;
+ onClose?: () => void;
+ onNewPage?: () => void;
onSelect: (pageId: string) => void;
selectedPageId: string;
}) => {
@@ -86,7 +97,23 @@ const Pages = ({
return (
<>
- <Header title="Pages" onClose={onClose} />
+ <BaseHeader
+ title="Pages"
+ actions={
+ <>
+ {onNewPage && (
+ <IconButton size="2" onClick={onNewPage} aria-label="Close">
+ <NewPageIcon />
+ </IconButton>
+ )}
+ {onClose && (
+ <IconButton size="2" onClick={onClose} aria-label="Close">
+ <Cross1Icon />
+ </IconButton>
+ )}
+ </>
+ }
+ />
<TreeNode
hideRoot
selectedItemId={selectedPageId}
@@ -110,16 +137,33 @@ export const TabContent = (props: TabContentProps) => {
navigate(`${props.config.designerPath}/${project.id}?pageId=${pageId}`);
};
- if (currentPageId === undefined) {
+ const [newPageOpen, setNewPageOpen] = useState(false);
+ const newPageFetcher = useFetcher();
+
+ if (currentPageId === undefined || project === undefined) {
return null;
}
return (
- <Pages
- onClose={() => props.onSetActiveTab("none")}
- onSelect={handleSelect}
- selectedPageId={currentPageId}
- />
+ <>
+ <Pages
+ onClose={() => props.onSetActiveTab("none")}
+ onNewPage={() => setNewPageOpen((value) => !value)}
+ onSelect={handleSelect}
+ selectedPageId={currentPageId}
+ />
+ <SettingsPanel isOpen={newPageOpen}>
+ <NewPageSettings
+ fetcher={newPageFetcher}
+ projectId={project.id}
+ onClose={() => setNewPageOpen(false)}
+ onSuccess={(page) => {
+ setNewPageOpen(false);
+ handleSelect(page.id);
+ }}
+ />
+ </SettingsPanel>
+ </>
);
};
diff --git a/apps/designer/app/designer/features/sidebar-left/panels/pages/settings-panel.tsx b/apps/designer/app/designer/features/sidebar-left/panels/pages/settings-panel.tsx
new file mode 100644
index 0000000000..44b7f6aa1f
--- /dev/null
+++ b/apps/designer/app/designer/features/sidebar-left/panels/pages/settings-panel.tsx
@@ -0,0 +1,61 @@
+import {
+ styled,
+ keyframes,
+ Collapsible,
+ Box,
+} from "@webstudio-is/design-system";
+
+const CollapsibleRoot = styled(Collapsible.Root, {
+ position: "absolute",
+ left: "100%",
+ top: 0,
+ bottom: 0,
+ display: "flex",
+ flexDirection: "column",
+ marginLeft: 1,
+});
+
+const openKeyframes = keyframes({
+ from: { width: 0 },
+ to: { width: "var(--radix-collapsible-content-width)" },
+});
+
+const closeKeyframes = keyframes({
+ from: { width: "var(--radix-collapsible-content-width)" },
+ to: { width: 0 },
+});
+
+const CollapsibleContent = styled(Collapsible.Content, {
+ overflow: "hidden",
+ flexGrow: "1",
+ display: "flex",
+ flexDirection: "column",
+ '&[data-state="open"]': { animation: `${openKeyframes} 200ms ease-out` },
+ '&[data-state="closed"]': { animation: `${closeKeyframes} 200ms ease-out` },
+});
+
+export const SettingsPanel = ({
+ children,
+ isOpen,
+}: {
+ children: React.ReactNode;
+ isOpen: boolean;
+}) => {
+ return (
+ <CollapsibleRoot open={isOpen}>
+ <CollapsibleContent>
+ <Box
+ css={{
+ flexGrow: 1,
+ width: 424,
+ background: "$loContrast",
+ borderRight: "1px solid $slate7",
+ position: "relative",
+ }}
+ >
+ {children}
+ </Box>
+ </CollapsibleContent>
+ </CollapsibleRoot>
+ );
+};
diff --git a/apps/designer/app/designer/features/sidebar-left/panels/pages/settings.tsx b/apps/designer/app/designer/features/sidebar-left/panels/pages/settings.tsx
new file mode 100644
index 0000000000..d543df9a56
--- /dev/null
+++ b/apps/designer/app/designer/features/sidebar-left/panels/pages/settings.tsx
@@ -0,0 +1,121 @@
+import {
+ IconButton,
+ Button,
+ Box,
+ Label,
+ TextField,
+ useId,
+ styled,
+ Flex,
+} from "@webstudio-is/design-system";
+import { type FetcherWithComponents } from "@remix-run/react";
+import { ChevronDoubleLeftIcon } from "@webstudio-is/icons";
+import type { ZodError } from "zod";
+import { BaseHeader } from "../../lib/header";
+import { useEffect, useRef } from "react";
+import { type Page } from "@webstudio-is/project";
+
+const Group = styled(Flex, {
+ marginBottom: "$3",
+ gap: "$2",
+ defaultVariants: { direction: "column" },
+});
+
+export type PutPageData =
+ | { ok: true; page: Page }
+ | { errors: string | ZodError["formErrors"] };
+
+const getErrors = (
+ fetcher: FetcherWithComponents<PutPageData>
+): ZodError["formErrors"] | undefined => {
+ if (fetcher.data === undefined || !("errors" in fetcher.data)) {
+ return undefined;
+ }
+ if (typeof fetcher.data.errors === "string") {
+ return { formErrors: [fetcher.data.errors], fieldErrors: {} };
+ }
+ return fetcher.data.errors;
+};
+
+export const NewPageSettings = ({
+ onClose,
+ onSuccess,
+ fetcher,
+ projectId,
+}: {
+ onClose?: () => void;
+ onSuccess?: (page: Page) => void;
+ fetcher: FetcherWithComponents<PutPageData>;
+ projectId: string;
+}) => {
+ const nameFieldId = useId();
+ const pathFieldId = useId();
+
+ const errors = getErrors(fetcher);
+
+ const isSubmitting = fetcher.state !== "idle";
+
+ const prevFetcher = useRef(fetcher);
+ useEffect(() => {
+ if (
+ prevFetcher.current.state !== "idle" &&
+ fetcher.state === "idle" &&
+ fetcher.data !== undefined &&
+ "ok" in fetcher.data
+ ) {
+ onSuccess?.(fetcher.data.page);
+ }
+ prevFetcher.current = fetcher;
+ }, [fetcher, onSuccess]);
+
+ return (
+ <>
+ <BaseHeader
+ title="New Page Settings"
+ actions={
+ <>
+ {onClose && (
+ <IconButton size="2" onClick={onClose} aria-label="Close">
+ <ChevronDoubleLeftIcon />
+ </IconButton>
+ )}
+ </>
+ }
+ />
+ <Box css={{ overflow: "auto", padding: "$2 $3" }}>
+ <fetcher.Form method="put" action={`/rest/pages/${projectId}`}>
+ {/* @todo: banner? toast? */}
+ {errors !== undefined &&
+ errors.formErrors.length > 0 &&
+ JSON.stringify(errors.formErrors)}
+
+ <Group>
+ <Label htmlFor={nameFieldId} size={2}>
+ Page Name
+ </Label>
+ <TextField id={nameFieldId} name="name" disabled={isSubmitting} />
+ {/* @todo: tooltip */}
+ {errors !== undefined &&
+ errors.fieldErrors.name !== undefined &&
+ JSON.stringify(errors.fieldErrors.name)}
+ </Group>
+ <Group>
+ <Label htmlFor={pathFieldId} size={2}>
+ Path
+ </Label>
+ <TextField id={pathFieldId} name="path" disabled={isSubmitting} />
+ {/* @todo: tooltip */}
+ {errors !== undefined &&
+ errors.fieldErrors.path !== undefined &&
+ JSON.stringify(errors.fieldErrors.path)}
+ </Group>
+ <Group css={{ alignItems: "end" }}>
+ <Button type="submit" variant="green" disabled={isSubmitting}>
+ Create
+ </Button>
+ </Group>
+ </fetcher.Form>
+ </Box>
+ </>
+ );
+};
diff --git a/apps/designer/app/designer/features/sidebar-left/sidebar-left.tsx b/apps/designer/app/designer/features/sidebar-left/sidebar-left.tsx
index f82b138aaf..6ac4f4c596 100644
--- a/apps/designer/app/designer/features/sidebar-left/sidebar-left.tsx
+++ b/apps/designer/app/designer/features/sidebar-left/sidebar-left.tsx
@@ -77,7 +77,9 @@ export const SidebarLeft = ({ publish, config }: SidebarLeftProps) => {
dragAndDropState.isDragging && dragAndDropState.origin === "panel"
? "hidden"
: "visible",
- overflow: "auto",
+
+ // @todo: is it ok to remove? (need to fix the "components" panel at min)
+ // overflow: "auto",
}}
>
<TabContent
diff --git a/apps/designer/app/routes/rest/pages.$projectId.ts b/apps/designer/app/routes/rest/pages.$projectId.ts
index cfee94a249..196851ea84 100644
--- a/apps/designer/app/routes/rest/pages.$projectId.ts
+++ b/apps/designer/app/routes/rest/pages.$projectId.ts
@@ -1,6 +1,83 @@
-import type { LoaderFunction } from "@remix-run/node";
+import { LoaderFunction, ActionFunction } from "@remix-run/node";
import { db } from "@webstudio-is/project/index.server";
-import { Pages } from "@webstudio-is/project";
+import { type Pages, utils } from "@webstudio-is/project";
+import { zfd } from "zod-form-data";
+import { z } from "zod";
+import { PutPageData } from "~/designer/features/sidebar-left/panels/pages/settings";
+import { sentryException } from "~/shared/sentry";
+
+const nonEmptyString = (fieldName: string) => {
+ const message = `${fieldName} can't be empty`;
+ return z
+ .string({ invalid_type_error: message, required_error: message })
+ .transform((v) => v.trim())
+ .refine((val) => val !== "", message);
+};
+
+const CreatePageInput = zfd.formData({
+ name: nonEmptyString("Page Name"),
+ path: nonEmptyString("Path")
+ .refine((path) => path !== "/", "Path can't be /")
+ .transform((path) => (path.endsWith("/") ? path.slice(0, -1) : path))
+ .transform((path) => path.replace(/\/\//g, "/"))
+ .refine((path) => path.startsWith("/"), "Path must start with a /"),
+});
+
+const handlePUT = async (
+ projectId: string,
+ request: Request
+): Promise<PutPageData> => {
+ const result = CreatePageInput.safeParse(await request.formData());
+ if (result.success === false) {
+ return { errors: result.error.formErrors };
+ }
+ const data = result.data;
+
+ const devBuild = await db.build.loadByProjectId(projectId, "dev");
+
+ const existingPage = utils.pages.findByPath(devBuild.pages, data.path);
+ if (existingPage !== undefined) {
+ return {
+ errors: {
+ formErrors: [],
+ fieldErrors: {
+ path: [
+ `The path ${data.path} is already used for another page "${existingPage.name}"`,
+ ],
+ },
+ },
+ };
+ }
+
+ const updatedBuild = await db.build.addPage(devBuild.id, data);
+
+ const newPage = utils.pages.findByPath(updatedBuild.pages, data.path);
+
+ if (newPage === undefined) {
+ throw new Error("New page not found");
+ }
+
+ return { ok: true, page: newPage };
+};
+
+export const action: ActionFunction = async ({ request, params }) => {
+ try {
+ if (params.projectId === undefined) {
+ throw new Error(`Project ID required`);
+ }
+
+ if (request.method.toLowerCase() === "put") {
+ return handlePUT(params.projectId, request);
+ }
+
+ throw new Error(`Method ${request.method} is not supported`);
+ } catch (error) {
+ sentryException({ error });
+ return {
+ errors: error instanceof Error ? error.message : String(error),
+ };
+ }
+};
export type ErrorData = {
errors: string;
@@ -24,11 +101,9 @@ export const loader: LoaderFunction = async ({
return prodBuild.pages;
} catch (error) {
- if (error instanceof Error) {
- return {
- errors: error.message,
- };
- }
+ sentryException({ error });
+ return {
+ errors: error instanceof Error ? error.message : String(error),
+ };
}
- return { errors: "Unexpected error" };
};
diff --git a/packages/project/src/db/build.ts b/packages/project/src/db/build.ts
index 523b3a9359..6e339baaa3 100644
--- a/packages/project/src/db/build.ts
+++ b/packages/project/src/db/build.ts
@@ -61,10 +61,42 @@ export async function loadByProjectId(
return parseBuild(build);
}
+export const addPage = async (
+ buildId: Build["id"],
+ data: { name: string; path: string }
+) => {
+ const build = await loadById(buildId);
+
+ const breakpoints = await db.breakpoints.load(buildId);
+ const tree = await db.tree.create(
+ db.tree.createRootInstance(breakpoints.values)
+ );
+
+ const nextPages = PagesSchema.parse({
+ homePage: build.pages.homePage,
+ pages: [
+ ...build.pages.pages,
+ {
+ id: uuid(),
+ name: data.name,
+ path: data.path,
+ title: data.name,
+ meta: {},
+ treeId: tree.id,
+ },
+ ],
+ });
+
+ const newBuild = await prisma.build.update({
+ where: { id: buildId },
+ data: { pages: JSON.stringify(nextPages) },
+ });
+
+ return parseBuild(newBuild);
+};
+
const createPages = async (breakpoints: Array<Breakpoint>) => {
- // const breakpoints = db.breakpoints.getBreakpointsWithId();
const tree = await db.tree.create(db.tree.createRootInstance(breakpoints));
- // await db.breakpoints.create(tree.id, breakpoints);
return PagesSchema.parse({
homePage: {
id: uuid(),
diff --git a/packages/project/src/db/types.ts b/packages/project/src/db/types.ts
index 5183eead93..3983b91e4d 100644
--- a/packages/project/src/db/types.ts
+++ b/packages/project/src/db/types.ts
@@ -9,7 +9,7 @@ export type Project = Omit<BaseProject, "assets"> & {
assets?: Array<Asset>;
};
-const PageSchema = z.object({
+export const PageSchema = z.object({
id: z.string(),
name: z.string(),
path: z.string(),