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: Clonable project (#2871)

Oleg Isonend1dba475c59f
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index 33a5419d9a..276efbb0ac 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -50,8 +50,9 @@ import { subscribeCommands } from "~/builder/shared/commands";
import { AiCommandBar } from "./features/ai/ai-command-bar";
import { ProjectSettings } from "./features/project-settings";
import type { UserPlanFeatures } from "~/shared/db/user-plan-features.server";
-import { $userPlanFeatures } from "./shared/nano-states";
+import { $isCloneDialogOpen, $userPlanFeatures } from "./shared/nano-states";
import { useNavigatorLayout } from "./features/sidebar-left/navigator";
+import { CloneProjectDialog } from "~/shared/clone-project";
registerContainers();
@@ -279,7 +280,7 @@ export const Builder = ({
authPermit,
version: build.version,
});
-
+ const isCloneDialogOpen = useStore($isCloneDialogOpen);
const isPreviewMode = useStore($isPreviewMode);
const { onRef: onRefReadCanvas, onTransitionEnd } = useReadCanvasRect();
// We need to initialize this in both canvas and builder,
@@ -343,6 +344,11 @@ export const Builder = ({
</SidePanel>
{isPreviewMode === false && <Footer />}
<BlockingAlerts />
+ <CloneProjectDialog
+ isOpen={isCloneDialogOpen}
+ onOpenChange={$isCloneDialogOpen.set}
+ project={project}
+ />
</ChromeWrapper>
</TooltipProvider>
);
diff --git a/apps/builder/app/builder/features/project-settings/compiler-section.tsx b/apps/builder/app/builder/features/project-settings/compiler-section.tsx
new file mode 100644
index 0000000000..e9cc264830
--- /dev/null
+++ b/apps/builder/app/builder/features/project-settings/compiler-section.tsx
@@ -0,0 +1,55 @@
+import {
+ Grid,
+ Label,
+ theme,
+ Text,
+ CheckboxAndLabel,
+ Checkbox,
+} from "@webstudio-is/design-system";
+import { useIds } from "~/shared/form-utils";
+import type { CompilerSettings } from "@webstudio-is/sdk";
+import { serverSyncStore } from "~/shared/sync";
+import { $pages } from "~/shared/nano-states";
+import { useState } from "react";
+
+const defaultSettings: CompilerSettings = {
+ atomicStyles: true,
+};
+
+export const CompilerSection = () => {
+ const ids = useIds(["atomicStyles"]);
+ const [settings, setSettings] = useState(
+ () => $pages.get()?.compiler ?? defaultSettings
+ );
+
+ const handleSave = (settings: CompilerSettings) => {
+ serverSyncStore.createTransaction([$pages], (pages) => {
+ if (pages === undefined) {
+ return;
+ }
+ pages.compiler = settings;
+ });
+ };
+
+ return (
+ <Grid gap={2} css={{ mx: theme.spacing[5], px: theme.spacing[5] }}>
+ <Text variant="titles">Compiler</Text>
+ <CheckboxAndLabel>
+ <Checkbox
+ checked={settings.atomicStyles ?? true}
+ id={ids.atomicStyles}
+ onCheckedChange={(atomicStyles) => {
+ if (typeof atomicStyles === "boolean") {
+ const nextSettings = { ...settings, atomicStyles };
+ setSettings(nextSettings);
+ handleSave(nextSettings);
+ }
+ }}
+ />
+ <Label htmlFor={ids.atomicStyles}>
+ Generate atomic CSS when publishing
+ </Label>
+ </CheckboxAndLabel>
+ </Grid>
+ );
+};
diff --git a/apps/builder/app/builder/features/project-settings/meta-section.tsx b/apps/builder/app/builder/features/project-settings/meta-section.tsx
index 3fd0973833..6aa67737bb 100644
--- a/apps/builder/app/builder/features/project-settings/meta-section.tsx
+++ b/apps/builder/app/builder/features/project-settings/meta-section.tsx
@@ -11,11 +11,13 @@ import {
css,
} from "@webstudio-is/design-system";
import { ImageControl } from "./image-control";
-import { $assets } from "~/shared/nano-states";
+import { $assets, $pages } from "~/shared/nano-states";
import env from "~/shared/env";
import { Image, createImageLoader } from "@webstudio-is/image";
import { useIds } from "~/shared/form-utils";
import type { ProjectMeta } from "@webstudio-is/sdk";
+import { useState } from "react";
+import { serverSyncStore } from "~/shared/sync";
const imgStyle = css({
width: 72,
@@ -26,29 +28,43 @@ const imgStyle = css({
borderColor: theme.colors.borderMain,
});
-export const MetaSection = (props: {
- meta: ProjectMeta;
- onMetaChange: (value: ProjectMeta) => void;
-}) => {
- const ids = useIds(["siteName", "favicon", "code"]);
- const handleChange =
- <Name extends keyof ProjectMeta>(name: Name) =>
- (value: ProjectMeta[Name]) => {
- props.onMetaChange({
- ...props.meta,
- [name]: value,
- });
- };
+const defaultMetaSettings: ProjectMeta = {
+ siteName: "",
+ faviconAssetId: "",
+ code: "",
+};
+export const MetaSection = () => {
+ const [meta, setMeta] = useState(
+ () => $pages.get()?.meta ?? defaultMetaSettings
+ );
+ const ids = useIds(["siteName", "favicon", "code"]);
const assets = useStore($assets);
- const asset = assets.get(props.meta.faviconAssetId ?? "");
-
+ const asset = assets.get(meta.faviconAssetId ?? "");
const favIconUrl = asset ? `${asset.name}` : undefined;
const imageLoader = createImageLoader({
imageBaseUrl: env.IMAGE_BASE_URL,
});
+ const handleSave = <Setting extends keyof ProjectMeta>(setting: Setting) => {
+ return (value: ProjectMeta[Setting]) => {
+ setMeta({
+ ...meta,
+ [setting]: value,
+ });
+ serverSyncStore.createTransaction([$pages], (pages) => {
+ if (pages === undefined) {
+ return;
+ }
+ if (pages.meta === undefined) {
+ pages.meta = {};
+ }
+ pages.meta[setting] = value;
+ });
+ };
+ };
+
return (
<>
<Grid
@@ -58,13 +74,14 @@ export const MetaSection = (props: {
px: theme.spacing[5],
}}
>
- <Label htmlFor={ids.siteName}>Project Name</Label>
+ <Label htmlFor={ids.siteName}>Site Name</Label>
<InputField
id={ids.siteName}
- value={props.meta.siteName ?? ""}
- onChange={(event) => handleChange("siteName")(event.target.value)}
- placeholder="Current Project Name"
- name="Name"
+ value={meta.siteName ?? ""}
+ onChange={(event) => {
+ handleSave("siteName")(event.target.value);
+ }}
+ placeholder="Current Site Name"
autoFocus
/>
</Grid>
@@ -86,7 +103,7 @@ export const MetaSection = (props: {
<Text color="subtle">
Upload a 32 x 32 px image to display in browser tabs.
</Text>
- <ImageControl onAssetIdChange={handleChange("faviconAssetId")}>
+ <ImageControl onAssetIdChange={handleSave("faviconAssetId")}>
<Button id={ids.favicon} css={{ justifySelf: "start" }}>
Upload
</Button>
@@ -108,8 +125,8 @@ export const MetaSection = (props: {
rows={5}
autoGrow
maxRows={10}
- value={props.meta.code ?? ""}
- onChange={handleChange("code")}
+ value={meta.code ?? ""}
+ onChange={handleSave("code")}
/>
</Grid>
</>
diff --git a/apps/builder/app/builder/features/project-settings/project-settings.stories.tsx b/apps/builder/app/builder/features/project-settings/project-settings.stories.tsx
index 5971b937e0..e0f0b5425c 100644
--- a/apps/builder/app/builder/features/project-settings/project-settings.stories.tsx
+++ b/apps/builder/app/builder/features/project-settings/project-settings.stories.tsx
@@ -1,3 +1,4 @@
+import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { $isProjectSettingsOpen } from "~/shared/nano-states/seo";
import { ProjectSettings } from "./project-settings";
@@ -6,7 +7,16 @@ export default {
};
$isProjectSettingsOpen.set(true);
+const createRouter = (element: JSX.Element) =>
+ createBrowserRouter([
+ {
+ path: "*",
+ element,
+ loader: () => null,
+ },
+ ]);
export const ProjectSettingsExample = () => {
- return <ProjectSettings />;
+ const router = createRouter(<ProjectSettings />);
+ return <RouterProvider router={router} />;
};
diff --git a/apps/builder/app/builder/features/project-settings/project-settings.tsx b/apps/builder/app/builder/features/project-settings/project-settings.tsx
index 2414555337..8640b82af8 100644
--- a/apps/builder/app/builder/features/project-settings/project-settings.tsx
+++ b/apps/builder/app/builder/features/project-settings/project-settings.tsx
@@ -8,81 +8,37 @@ import {
Separator,
ScrollArea,
} from "@webstudio-is/design-system";
-import { useEffect, useState } from "react";
-import { $isProjectSettingsOpen } from "~/shared/nano-states/seo";
-import { $pages } from "~/shared/nano-states";
-import { serverSyncStore } from "~/shared/sync";
-import { useEffectEvent } from "../ai/hooks/effect-event";
-import type { Pages } from "@webstudio-is/sdk";
import { isFeatureEnabled } from "@webstudio-is/feature-flags";
+import { $isProjectSettingsOpen } from "~/shared/nano-states/seo";
import { MetaSection } from "./meta-section";
-import { PublishSection } from "./publish-section";
-import { RedirectSection } from "./redirect-settings";
-
-export type ProjectSettings = NonNullable<Pages["settings"]>;
-
-const ProjectSettingsView = () => {
- const [meta, setMeta] = useState(
- $pages.get()?.meta ?? {
- siteName: "",
- faviconAssetId: "",
- code: "",
- }
- );
-
- const [settings, setSettings] = useState(
- $pages.get()?.settings ?? {
- atomicStyles: true,
- }
- );
-
- const isOpen = useStore($isProjectSettingsOpen);
-
- const handleSave = useEffectEvent(() => {
- serverSyncStore.createTransaction([$pages], (pages) => {
- if (pages === undefined) {
- return;
- }
-
- pages.meta = meta;
- pages.settings = settings;
- });
- });
-
+import { CompilerSection } from "./compiler-section";
+import { RedirectSection } from "./redirect-section";
+
+const ProjectSettingsView = ({
+ isOpen,
+ onOpenChange,
+}: {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+}) => {
return (
- <Dialog
- open={isOpen}
- onOpenChange={(isOpen) => {
- handleSave();
- $isProjectSettingsOpen.set(isOpen);
- }}
- >
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
<DialogContent
- onBlur={handleSave}
// Left Aside panels (e.g., Pages, Components) use zIndex: theme.zIndices[1].
// For a dialog to appear above these panels, both overlay and content should also have zIndex: theme.zIndices[1].
css={{
width: theme.spacing[34],
zIndex: theme.zIndices[1],
}}
- overlayCss={{
- zIndex: theme.zIndices[1],
- }}
+ overlayCss={{ zIndex: theme.zIndices[1] }}
>
<ScrollArea>
<Grid gap={2} css={{ my: theme.spacing[5] }}>
- <MetaSection meta={meta} onMetaChange={setMeta} />
+ <MetaSection />
+ <Separator />
+ <CompilerSection />
<Separator />
- <PublishSection
- settings={settings}
- onSettingsChange={setSettings}
- />
- {isFeatureEnabled("redirects") ? (
- <RedirectSection
- settings={settings}
- onSettingsChange={setSettings}
- />
- ) : null}
+ {isFeatureEnabled("redirects") && <RedirectSection />}
<div />
</Grid>
</ScrollArea>
@@ -96,19 +52,12 @@ const ProjectSettingsView = () => {
};
export const ProjectSettings = () => {
- const [settingDialogLazyOpen, setSettingDialogLazyOpen] = useState(false);
-
- useEffect(() => {
- return $isProjectSettingsOpen.subscribe((isOpen) => {
- if (isOpen) {
- setSettingDialogLazyOpen(true);
- }
- });
- }, []);
-
- if (settingDialogLazyOpen === false) {
- return null;
- }
+ const isOpen = useStore($isProjectSettingsOpen);
- return <ProjectSettingsView />;
+ return (
+ <ProjectSettingsView
+ isOpen={isOpen}
+ onOpenChange={$isProjectSettingsOpen.set}
+ />
+ );
};
diff --git a/apps/builder/app/builder/features/project-settings/publish-section.tsx b/apps/builder/app/builder/features/project-settings/publish-section.tsx
deleted file mode 100644
index a28af5dcad..0000000000
--- a/apps/builder/app/builder/features/project-settings/publish-section.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import {
- Grid,
- Label,
- theme,
- Text,
- CheckboxAndLabel,
- Checkbox,
-} from "@webstudio-is/design-system";
-import { useIds } from "~/shared/form-utils";
-import type { ProjectSettings } from "./project-settings";
-
-export const PublishSection = (props: {
- settings: ProjectSettings;
- onSettingsChange: (settings: ProjectSettings) => void;
-}) => {
- const ids = useIds(["atomicStyles"]);
-
- const handleChange =
- <Name extends keyof ProjectSettings>(name: Name) =>
- (value: ProjectSettings[Name]) => {
- props.onSettingsChange({
- ...props.settings,
- [name]: value,
- });
- };
-
- return (
- <Grid gap={2} css={{ mx: theme.spacing[5], px: theme.spacing[5] }}>
- <Text variant="titles">Publish Settings</Text>
- <CheckboxAndLabel>
- <Checkbox
- checked={props.settings.atomicStyles ?? true}
- id={ids.atomicStyles}
- onCheckedChange={(checked) => {
- if (typeof checked === "boolean") {
- handleChange("atomicStyles")(checked);
- }
- }}
- />
- <Label htmlFor={ids.atomicStyles}>
- Generate atomic CSS when publishing
- </Label>
- </CheckboxAndLabel>
- </Grid>
- );
-};
diff --git a/apps/builder/app/builder/features/project-settings/redirect-settings.tsx b/apps/builder/app/builder/features/project-settings/redirect-section.tsx
similarity index 89%
rename from apps/builder/app/builder/features/project-settings/redirect-settings.tsx
rename to apps/builder/app/builder/features/project-settings/redirect-section.tsx
index 7167f18b33..ba1951acd8 100644
--- a/apps/builder/app/builder/features/project-settings/redirect-settings.tsx
+++ b/apps/builder/app/builder/features/project-settings/redirect-section.tsx
@@ -13,16 +13,20 @@ import {
} from "@webstudio-is/design-system";
import { ArrowRightIcon, TrashIcon } from "@webstudio-is/icons";
import { useState, type ChangeEvent } from "react";
-import type { ProjectSettings } from "./project-settings";
-import { PagePath, ProjectNewRedirectPathSchema } from "@webstudio-is/sdk";
+import {
+ PagePath,
+ PageRedirect,
+ ProjectNewRedirectPath,
+} from "@webstudio-is/sdk";
import { useStore } from "@nanostores/react";
import { getExistingRoutePaths } from "../sidebar-left/panels/pages/page-utils";
import { $pages } from "~/shared/nano-states";
+import { serverSyncStore } from "~/shared/sync";
-export const RedirectSection = (props: {
- settings: ProjectSettings;
- onSettingsChange: (settings: ProjectSettings) => void;
-}) => {
+export const RedirectSection = () => {
+ const [redirects, setRedirects] = useState(
+ () => $pages.get()?.redirects ?? []
+ );
const [oldPath, setOldPath] = useState<string>("");
const [newPath, setNewPath] = useState<string>("");
const [oldPathErrors, setOldPathErrors] = useState<string[]>([]);
@@ -30,7 +34,6 @@ export const RedirectSection = (props: {
const pages = useStore($pages);
const existingPaths = getExistingRoutePaths(pages);
- const redirects = props.settings?.redirects ?? [];
const redirectKeys = Object.keys(redirects);
const isValidRedirects =
oldPathErrors.length === 0 && newPathErrors.length === 0;
@@ -69,8 +72,7 @@ export const RedirectSection = (props: {
};
const validateNewPath = (newPath: string): string[] => {
- const newPathValidationResult =
- ProjectNewRedirectPathSchema.safeParse(newPath);
+ const newPathValidationResult = ProjectNewRedirectPath.safeParse(newPath);
if (newPathValidationResult.success === true) {
/*
@@ -96,6 +98,16 @@ export const RedirectSection = (props: {
}
};
+ const handleSave = (redirects: Array<PageRedirect>) => {
+ setRedirects(redirects);
+ serverSyncStore.createTransaction([$pages], (pages) => {
+ if (pages === undefined) {
+ return;
+ }
+ pages.redirects = redirects;
+ });
+ };
+
const handleAddRedirect = () => {
const validOldPath = validateOldPath(oldPath);
const validNewPath = validateNewPath(newPath);
@@ -104,10 +116,7 @@ export const RedirectSection = (props: {
return;
}
- props.onSettingsChange({
- ...props.settings,
- redirects: [{ old: oldPath, new: newPath }, ...redirects],
- });
+ handleSave([{ old: oldPath, new: newPath }, ...redirects]);
setOldPath("");
setNewPath("");
};
@@ -115,10 +124,7 @@ export const RedirectSection = (props: {
const handleDeleteRedirect = (index: number) => {
const newRedirects = [...redirects];
newRedirects.splice(index, 1);
- props.onSettingsChange({
- ...props.settings,
- redirects: newRedirects,
- });
+ handleSave(newRedirects);
};
return (
@@ -192,6 +198,7 @@ export const RedirectSection = (props: {
gap="2"
css={{
p: theme.spacing[3],
+ overflow: "hidden",
}}
>
<Flex gap="2">
diff --git a/apps/builder/app/builder/features/topbar/menu/menu.tsx b/apps/builder/app/builder/features/topbar/menu/menu.tsx
index 083e1111a0..c873abf54f 100644
--- a/apps/builder/app/builder/features/topbar/menu/menu.tsx
+++ b/apps/builder/app/builder/features/topbar/menu/menu.tsx
@@ -20,6 +20,7 @@ import {
useIsShareDialogOpen,
useIsPublishDialogOpen,
$userPlanFeatures,
+ $isCloneDialogOpen,
} from "~/builder/shared/nano-states";
import {
getThemeSetting,
@@ -100,15 +101,15 @@ export const Menu = () => {
const isPublishEnabled = authPermit === "own" || authPermit === "admin";
- const isShareDisabled = authPermit !== "own";
+ const isShareEnabled = authPermit === "own";
const disabledPublishTooltipContent = isPublishEnabled
? undefined
: "Only owner or admin can publish projects";
- const disabledShareTooltipContent = isShareDisabled
- ? "Only owner can share projects"
- : undefined;
+ const disabledShareTooltipContent = isShareEnabled
+ ? undefined
+ : "Only owner can share projects";
return (
<DropdownMenu>
@@ -196,7 +197,7 @@ export const Menu = () => {
onSelect={() => {
setIsShareOpen(true);
}}
- disabled={isShareDisabled}
+ disabled={isShareEnabled === false}
>
Share
</DropdownMenuItem>
@@ -212,6 +213,13 @@ export const Menu = () => {
Publish
</DropdownMenuItem>
</Tooltip>
+ <DropdownMenuItem
+ onSelect={() => {
+ $isCloneDialogOpen.set(true);
+ }}
+ >
+ Clone
+ </DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={() => {
diff --git a/apps/builder/app/builder/shared/nano-states/index.ts b/apps/builder/app/builder/shared/nano-states/index.ts
index cbd920a5bb..a214ff4401 100644
--- a/apps/builder/app/builder/shared/nano-states/index.ts
+++ b/apps/builder/app/builder/shared/nano-states/index.ts
@@ -17,6 +17,8 @@ export const useIsPublishDialogOpen = () => useValue($isPublishDialogOpen);
export const $canvasWidth = atom<number | undefined>();
export const useCanvasWidth = () => useValue($canvasWidth);
+export const $isCloneDialogOpen = atom<boolean>(false);
+
export const $canvasRect = atom<DOMRect | undefined>();
export const $workspaceRect = atom<DOMRect | undefined>();
diff --git a/apps/builder/app/dashboard/projects/dialog.tsx b/apps/builder/app/dashboard/projects/dialog.tsx
deleted file mode 100644
index 9d35b5ea14..0000000000
--- a/apps/builder/app/dashboard/projects/dialog.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import {
- Flex,
- Dialog as BaseDialog,
- DialogTrigger,
- DialogContent,
- DialogTitle,
- DialogClose,
- DialogDescription,
- theme,
-} from "@webstudio-is/design-system";
-
-type DialogProps = {
- title: string;
- children: JSX.Element | Array<JSX.Element>;
- trigger?: JSX.Element;
- onOpenChange?: (open: boolean) => void;
- isOpen?: boolean;
-};
-
-export const Dialog = ({
- title,
- children,
- trigger,
- onOpenChange,
- isOpen,
-}: DialogProps) => {
- return (
- <BaseDialog open={isOpen} onOpenChange={onOpenChange}>
- {trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>}
- <DialogContent>
- {children}
- <DialogTitle>{title}</DialogTitle>
- </DialogContent>
- </BaseDialog>
- );
-};
-
-export const DialogActions = ({
- children,
-}: {
- children: Array<JSX.Element>;
-}) => {
- return (
- <Flex
- gap="1"
- css={{
- padding: theme.spacing["9"],
- paddingTop: theme.spacing["5"],
- // Making sure the tab order is the last item first.
- flexFlow: "row-reverse",
- }}
- >
- {children}
- </Flex>
- );
-};
-
-export { DialogClose, DialogDescription };
diff --git a/apps/builder/app/dashboard/projects/project-card.tsx b/apps/builder/app/dashboard/projects/project-card.tsx
index e1d1737d65..7dc7ab6109 100644
--- a/apps/builder/app/dashboard/projects/project-card.tsx
+++ b/apps/builder/app/dashboard/projects/project-card.tsx
@@ -20,9 +20,8 @@ import { builderPath, getPublishedUrl } from "~/shared/router-utils";
import {
RenameProjectDialog,
DeleteProjectDialog,
- useDuplicate,
+ useCloneProject,
ShareProjectDialog,
- DuplicateProjectDialog,
} from "./project-dialogs";
import {
ThumbnailLinkWithAbbr,
@@ -34,6 +33,7 @@ import { useNavigation } from "@remix-run/react";
import { Spinner } from "../shared/spinner";
import type { DashboardProject } from "@webstudio-is/dashboard";
import { Card, CardContent, CardFooter } from "../shared/card";
+import { CloneProjectDialog } from "~/shared/clone-project";
const titleStyle = css({
userSelect: "auto",
@@ -162,24 +162,26 @@ const formatDate = (date: string) => {
});
};
-type ProjectCardProps = DashboardProject & { hasProPlan: boolean };
+type ProjectCardProps = { project: DashboardProject; hasProPlan: boolean };
export const ProjectCard = ({
- id,
- title,
- domain,
- isPublished,
+ project: {
+ id,
+ title,
+ domain,
+ isPublished,
+ createdAt,
+ latestBuild,
+ previewImageAsset,
+ },
hasProPlan,
- createdAt,
- latestBuild,
- previewImageAsset,
}: ProjectCardProps) => {
const [isRenameDialogOpen, setIsRenameDialogOpen] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const [isShareDialogOpen, setIsShareDialogOpen] = useState(false);
const [isHidden, setIsHidden] = useState(false);
const { thumbnailRef, handleKeyDown } = useProjectCard();
- const handleDuplicate = useDuplicate(id);
+ const handleCloneProject = useCloneProject(id);
const { state, location } = useNavigation();
const linkPath = builderPath({ projectId: id });
// Transition to the project has started, we may need to show a spinner
@@ -248,7 +250,7 @@ export const ProjectCard = ({
onShare={() => {
setIsShareDialogOpen(true);
}}
- onDuplicate={handleDuplicate}
+ onDuplicate={handleCloneProject}
/>
</CardFooter>
<RenameProjectDialog
@@ -275,15 +277,11 @@ export const ProjectCard = ({
};
export const ProjectTemplateCard = ({
- id,
- title,
- domain,
- previewImageAsset,
- isPublished,
+ project,
}: Omit<ProjectCardProps, "hasProPlan">) => {
const { thumbnailRef, handleKeyDown } = useProjectCard();
const [isDuplicateDialogOpen, setIsDuplicateDialogOpen] = useState(false);
-
+ const { title, domain, previewImageAsset, isPublished } = project;
return (
<Card tabIndex={0} onKeyDown={handleKeyDown}>
<CardContent
@@ -319,11 +317,10 @@ export const ProjectTemplateCard = ({
)}
</Flex>
</CardFooter>
- <DuplicateProjectDialog
+ <CloneProjectDialog
isOpen={isDuplicateDialogOpen}
onOpenChange={setIsDuplicateDialogOpen}
- title={title}
- projectId={id}
+ project={project}
/>
</Card>
);
diff --git a/apps/builder/app/dashboard/projects/project-dialogs.tsx b/apps/builder/app/dashboard/projects/project-dialogs.tsx
index c1e685efb6..627c6547a1 100644
--- a/apps/builder/app/dashboard/projects/project-dialogs.tsx
+++ b/apps/builder/app/dashboard/projects/project-dialogs.tsx
@@ -1,3 +1,5 @@
+import { useEffect, useState } from "react";
+import { useNavigate } from "@remix-run/react";
import type { DashboardProjectRouter } from "@webstudio-is/dashboard";
import {
Box,
@@ -6,22 +8,47 @@ import {
Label,
Text,
DeprecatedTextField,
- theme,
-} from "@webstudio-is/design-system";
-import { PlusIcon } from "@webstudio-is/icons";
-import { useEffect, useState } from "react";
-import { useNavigate } from "@remix-run/react";
-import { dashboardProjectPath, builderPath } from "~/shared/router-utils";
-import { createTrpcRemixProxy } from "~/shared/remix/trpc-remix-proxy";
-import {
DialogActions,
+ Dialog as BaseDialog,
+ DialogTrigger,
+ DialogContent as DialogContentBase,
+ DialogTitle,
DialogClose,
- Dialog,
DialogDescription,
-} from "./dialog";
+ theme,
+} from "@webstudio-is/design-system";
+import { PlusIcon } from "@webstudio-is/icons";
import type { DashboardProject } from "@webstudio-is/prisma-client";
-import { ShareProjectContainer } from "~/shared/share-project";
import { Title } from "@webstudio-is/project";
+import { dashboardProjectsPath, builderPath } from "~/shared/router-utils";
+import { createTrpcRemixProxy } from "~/shared/remix/trpc-remix-proxy";
+import { ShareProjectContainer } from "~/shared/share-project";
+
+type DialogProps = {
+ title: string;
+ children: JSX.Element | Array<JSX.Element>;
+ trigger?: JSX.Element;
+ onOpenChange?: (open: boolean) => void;
+ isOpen?: boolean;
+};
+
+const Dialog = ({
+ title,
+ children,
+ trigger,
+ onOpenChange,
+ isOpen,
+}: DialogProps) => {
+ return (
+ <BaseDialog open={isOpen} onOpenChange={onOpenChange}>
+ {trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>}
+ <DialogContentBase>
+ {children}
+ <DialogTitle>{title}</DialogTitle>
+ </DialogContentBase>
+ </BaseDialog>
+ );
+};
const DialogContent = ({
onSubmit,
@@ -91,7 +118,9 @@ const DialogContent = ({
);
};
-const trpc = createTrpcRemixProxy<DashboardProjectRouter>(dashboardProjectPath);
+const trpc = createTrpcRemixProxy<DashboardProjectRouter>(
+ dashboardProjectsPath
+);
const useCreateProject = () => {
const navigate = useNavigate();
@@ -222,79 +251,6 @@ export const RenameProjectDialog = ({
);
};
-const useDuplicateProject = ({
- projectId,
- onOpenChange,
-}: {
- projectId: DashboardProject["id"];
- onOpenChange: (isOpen: boolean) => void;
-}) => {
- const navigate = useNavigate();
- const { send, state } = trpc.duplicate.useMutation();
-
- const [errors, setErrors] = useState<string>();
-
- const handleSubmit = ({ title }: { title: string }) => {
- const parsed = Title.safeParse(title);
- const errors =
- "error" in parsed
- ? parsed.error.issues.map((issue) => issue.message).join("\n")
- : undefined;
-
- setErrors(errors);
-
- if (parsed.success) {
- send({ projectId, title }, (data) => {
- if (data?.id) {
- navigate(builderPath({ projectId: data.id }));
- onOpenChange(false);
- }
- });
- }
- };
-
- return {
- handleSubmit,
- errors,
- state,
- };
-};
-
-export const DuplicateProjectDialog = ({
- isOpen,
- title,
- projectId,
- onOpenChange,
-}: {
- isOpen: boolean;
- title: string;
- projectId: DashboardProject["id"];
- onOpenChange: (isOpen: boolean) => void;
-}) => {
- const { handleSubmit, errors, state } = useDuplicateProject({
- projectId,
- onOpenChange,
- });
- return (
- <Dialog title="Create" isOpen={isOpen} onOpenChange={onOpenChange}>
- <DialogContent
- onSubmit={handleSubmit}
- errors={errors}
- title={title}
- label="Project Title"
- primaryButton={
- <Button
- type="submit"
- state={state === "idle" ? undefined : "pending"}
- >
- Create Project
- </Button>
- }
- />
- </Dialog>
- );
-};
-
const useDeleteProject = ({
projectId,
title,
@@ -397,8 +353,8 @@ export const DeleteProjectDialog = ({
);
};
-export const useDuplicate = (projectId: DashboardProject["id"]) => {
- const { send } = trpc.duplicate.useMutation();
+export const useCloneProject = (projectId: DashboardProject["id"]) => {
+ const { send } = trpc.clone.useMutation();
return () => {
send({ projectId });
};
diff --git a/apps/builder/app/dashboard/projects/projects.tsx b/apps/builder/app/dashboard/projects/projects.tsx
index ed6da5dd7e..5421a67ac7 100644
--- a/apps/builder/app/dashboard/projects/projects.tsx
+++ b/apps/builder/app/dashboard/projects/projects.tsx
@@ -35,7 +35,7 @@ export const Projects = ({
{projects.map((project) => {
return (
<ProjectCard
- {...project}
+ project={project}
key={project.id}
hasProPlan={hasProPlan}
/>
@@ -58,7 +58,7 @@ export const Projects = ({
}}
>
{projectTemplates.map((project) => {
- return <ProjectTemplateCard {...project} key={project.id} />;
+ return <ProjectTemplateCard project={project} key={project.id} />;
})}
</Grid>
</Flex>
diff --git a/apps/builder/app/routes/rest.projects.$method.ts b/apps/builder/app/routes/rest.projects.$method.ts
new file mode 100644
index 0000000000..d44483af50
--- /dev/null
+++ b/apps/builder/app/routes/rest.projects.$method.ts
@@ -0,0 +1,21 @@
+import type { ActionArgs } from "@remix-run/node";
+import { projectRouter } from "@webstudio-is/project/index.server";
+import { findAuthenticatedUser } from "~/services/auth.server";
+import { createContext } from "~/shared/context.server";
+import { handleTrpcRemixAction } from "~/shared/remix/trpc-remix-request.server";
+
+export const action = async ({ request, params }: ActionArgs) => {
+ const authenticatedUser = await findAuthenticatedUser(request);
+ if (authenticatedUser === null) {
+ throw new Error("Not authenticated");
+ }
+
+ const context = await createContext(request);
+
+ return await handleTrpcRemixAction({
+ request,
+ params,
+ router: projectRouter,
+ context,
+ });
+};
diff --git a/apps/builder/app/shared/clone-project.tsx b/apps/builder/app/shared/clone-project.tsx
new file mode 100644
index 0000000000..afa2086782
--- /dev/null
+++ b/apps/builder/app/shared/clone-project.tsx
@@ -0,0 +1,148 @@
+import { useState } from "react";
+import { useNavigate } from "@remix-run/react";
+import {
+ Box,
+ Button,
+ Flex,
+ Label,
+ Text,
+ theme,
+ InputField,
+ DialogContent,
+ DialogTitle,
+ DialogClose,
+ Dialog,
+ DialogActions,
+} from "@webstudio-is/design-system";
+import { Title, type ProjectRouter, Project } from "@webstudio-is/project";
+import { projectsPath, builderPath } from "~/shared/router-utils";
+import { createTrpcRemixProxy } from "~/shared/remix/trpc-remix-proxy";
+
+const trpc = createTrpcRemixProxy<ProjectRouter>(projectsPath);
+
+const useCloneProject = ({
+ projectId,
+ onOpenChange,
+}: {
+ projectId: Project["id"];
+ onOpenChange: (isOpen: boolean) => void;
+}) => {
+ const navigate = useNavigate();
+ const { send, state } = trpc.clone.useMutation();
+ const [errors, setErrors] = useState<string>();
+
+ const handleSubmit = ({ title }: { title: string }) => {
+ const parsed = Title.safeParse(title);
+ const errors =
+ "error" in parsed
+ ? parsed.error.issues.map((issue) => issue.message).join("\n")
+ : undefined;
+
+ setErrors(errors);
+
+ if (parsed.success) {
+ send({ projectId, title }, (data) => {
+ if (data?.id) {
+ navigate(builderPath({ projectId: data.id }));
+ onOpenChange(false);
+ }
+ });
+ }
+ };
+
+ return {
+ handleSubmit,
+ errors,
+ state,
+ };
+};
+
+const CloneProjectView = ({
+ isOpen,
+ title,
+ errors,
+ state,
+ onOpenChange,
+ onSubmit,
+}: {
+ isOpen: boolean;
+ title: string;
+ errors?: string;
+ state: "idle" | "loading" | "submitting";
+ onOpenChange: (isOpen: boolean) => void;
+ onSubmit: ({ title }: { title: string }) => void;
+}) => {
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent css={{ zIndex: theme.zIndices[1] }}>
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ const formData = new FormData(
+ event.currentTarget as HTMLFormElement
+ );
+ const title = String(formData.get("title") ?? "");
+ onSubmit({ title });
+ }}
+ >
+ <Flex
+ direction="column"
+ css={{
+ px: theme.spacing["9"],
+ paddingTop: theme.spacing["5"],
+ }}
+ gap="1"
+ >
+ <Label>Project Title</Label>
+ <InputField
+ name="title"
+ defaultValue={title}
+ color={errors ? "error" : undefined}
+ />
+ <Box css={{ minHeight: theme.spacing["10"] }}>
+ {errors && <Text color="destructive">{errors}</Text>}
+ </Box>
+ </Flex>
+ <DialogActions>
+ <Button
+ type="submit"
+ state={state === "idle" ? undefined : "pending"}
+ >
+ Clone
+ </Button>
+ <DialogClose asChild>
+ <Button color="ghost">Cancel</Button>
+ </DialogClose>
+ </DialogActions>
+ </form>
+ <DialogTitle>Clone Project</DialogTitle>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export const CloneProjectDialog = ({
+ isOpen,
+ project: { id, title },
+ onOpenChange,
+}: {
+ isOpen: boolean;
+ project: Project;
+ onOpenChange: (isOpen: boolean) => void;
+}) => {
+ const { handleSubmit, errors, state } = useCloneProject({
+ projectId: id,
+ onOpenChange,
+ });
+
+ return (
+ <CloneProjectView
+ title={title}
+ onSubmit={handleSubmit}
+ errors={errors}
+ state={state}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ />
+ );
+};
diff --git a/apps/builder/app/shared/router-utils/path-utils.ts b/apps/builder/app/shared/router-utils/path-utils.ts
index 1810bbb940..20046a9ace 100644
--- a/apps/builder/app/shared/router-utils/path-utils.ts
+++ b/apps/builder/app/shared/router-utils/path-utils.ts
@@ -73,8 +73,10 @@ export const builderDomainsPath = (method: string) => {
}`;
};
-export const dashboardProjectPath = (method: string) =>
- `/dashboard/projects/${method}`;
+export const projectsPath = (method: string) => `/rest/projects/${method}`;
+
+export const dashboardProjectsPath = (method: string) =>
+ `${dashboardPath()}/projects/${method}`;
export const authorizationTokenPath = (method: string) =>
`/rest/authorization-token/${method}`;
diff --git a/fixtures/webstudio-remix-netlify-edge-functions/app/__generated__/_index.tsx b/fixtures/webstudio-remix-netlify-edge-functions/app/__generated__/_index.tsx
index c1deaf577a..74da5fb503 100644
--- a/fixtures/webstudio-remix-netlify-edge-functions/app/__generated__/_index.tsx
+++ b/fixtures/webstudio-remix-netlify-edge-functions/app/__generated__/_index.tsx
@@ -38,7 +38,11 @@ export const getPageMeta = ({}: {
const Page = ({ params: PageParams }: { params: any }) => {
return (
- <Body data-ws-id="MMimeobf_zi4ZkRGXapju" data-ws-component="Body">
+ <Body
+ data-ws-id="MMimeobf_zi4ZkRGXapju"
+ data-ws-component="Body"
+ className="c9ryj1f c1e3go07 cmhckny cr0vgwe"
+ >
<Heading data-ws-id="MYDt0guk1-vzc7yzqyN6A" data-ws-component="Heading">
{"Simple Project to test CLI"}
</Heading>
diff --git a/fixtures/webstudio-remix-netlify-edge-functions/app/__generated__/index.css b/fixtures/webstudio-remix-netlify-edge-functions/app/__generated__/index.css
index 5fb7b76bb1..6ea394ea0b 100644
--- a/fixtures/webstudio-remix-netlify-edge-functions/app/__generated__/index.css
+++ b/fixtures/webstudio-remix-netlify-edge-functions/app/__generated__/index.css
@@ -79,10 +79,16 @@ html {
}
}
@media all {
- [data-ws-id="MMimeobf_zi4ZkRGXapju"] {
+ .c9ryj1f {
display: flex;
+ }
+ .c1e3go07 {
align-items: center;
+ }
+ .cmhckny {
justify-content: center;
+ }
+ .cr0vgwe {
flex-direction: column;
}
}
diff --git a/fixtures/webstudio-remix-netlify-functions/app/__generated__/_index.tsx b/fixtures/webstudio-remix-netlify-functions/app/__generated__/_index.tsx
index c1deaf577a..74da5fb503 100644
--- a/fixtures/webstudio-remix-netlify-functions/app/__generated__/_index.tsx
+++ b/fixtures/webstudio-remix-netlify-functions/app/__generated__/_index.tsx
@@ -38,7 +38,11 @@ export const getPageMeta = ({}: {
const Page = ({ params: PageParams }: { params: any }) => {
return (
- <Body data-ws-id="MMimeobf_zi4ZkRGXapju" data-ws-component="Body">
+ <Body
+ data-ws-id="MMimeobf_zi4ZkRGXapju"
+ data-ws-component="Body"
+ className="c9ryj1f c1e3go07 cmhckny cr0vgwe"
+ >
<Heading data-ws-id="MYDt0guk1-vzc7yzqyN6A" data-ws-component="Heading">
{"Simple Project to test CLI"}
</Heading>
diff --git a/fixtures/webstudio-remix-netlify-functions/app/__generated__/index.css b/fixtures/webstudio-remix-netlify-functions/app/__generated__/index.css
index 5fb7b76bb1..6ea394ea0b 100644
--- a/fixtures/webstudio-remix-netlify-functions/app/__generated__/index.css
+++ b/fixtures/webstudio-remix-netlify-functions/app/__generated__/index.css
@@ -79,10 +79,16 @@ html {
}
}
@media all {
- [data-ws-id="MMimeobf_zi4ZkRGXapju"] {
+ .c9ryj1f {
display: flex;
+ }
+ .c1e3go07 {
align-items: center;
+ }
+ .cmhckny {
justify-content: center;
+ }
+ .cr0vgwe {
flex-direction: column;
}
}
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index 240a0f70f0..645bc0ccf5 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -424,7 +424,7 @@ export const prebuild = async (options: {
},
{
assetBaseUrl,
- atomic: siteData.build.pages.settings?.atomicStyles ?? true,
+ atomic: siteData.build.pages.compiler?.atomicStyles ?? true,
}
);
diff --git a/packages/design-system/src/components/dialog.tsx b/packages/design-system/src/components/dialog.tsx
index 40bd97c593..56a041b60a 100644
--- a/packages/design-system/src/components/dialog.tsx
+++ b/packages/design-system/src/components/dialog.tsx
@@ -8,6 +8,7 @@ import * as Primitive from "@radix-ui/react-dialog";
import { css, theme, keyframes, type CSS } from "../stitches.config";
import { PanelTitle } from "./panel-title";
import { floatingPanelStyle, CloseButton, TitleSlot } from "./floating-panel";
+import { Flex } from "./flex";
export const Dialog = Primitive.Root;
export const DialogTrigger = Primitive.Trigger;
@@ -74,6 +75,22 @@ export const DialogTitle = ({
</TitleSlot>
);
+export const DialogActions = ({ children }: { children: ReactNode }) => {
+ return (
+ <Flex
+ gap="1"
+ css={{
+ padding: theme.spacing["9"],
+ paddingTop: theme.spacing["5"],
+ // Making sure the tab order is the last item first.
+ flexFlow: "row-reverse",
+ }}
+ >
+ {children}
+ </Flex>
+ );
+};
+
// Styles specific to dialog
// (as opposed to be common for all floating panels)
diff --git a/packages/prisma-client/prisma/migrations/20240131200102_page_meta_expressions/migration.ts b/packages/prisma-client/prisma/migrations/20240131200102_page_meta_expressions/migration.ts
index ca8001885e..067ae7a08b 100644
--- a/packages/prisma-client/prisma/migrations/20240131200102_page_meta_expressions/migration.ts
+++ b/packages/prisma-client/prisma/migrations/20240131200102_page_meta_expressions/migration.ts
@@ -34,14 +34,14 @@ type ProjectMeta = {
code?: string;
};
-type PageRedirectSchema = {
+type PageRedirect = {
old: string;
new: string;
};
type ProjectSettings = {
atomicStyles?: boolean;
- redirects?: PageRedirectSchema[];
+ redirects?: PageRedirect[];
};
type Pages = {
diff --git a/packages/project/src/db/project.ts b/packages/project/src/db/project.ts
index be522a6a64..2539855125 100644
--- a/packages/project/src/db/project.ts
+++ b/packages/project/src/db/project.ts
@@ -144,19 +144,22 @@ export const updatePreviewImage = async (
});
};
-const clone = async (
+export const clone = async (
{
- project,
+ projectId,
title,
- env = "dev",
}: {
- project: Project;
- title?: string;
- env?: "dev" | "prod";
+ projectId: string;
+ title?: string | undefined;
},
context: AppContext
) => {
- const userId = context.authorization.userId;
+ const project = await loadById(projectId, context);
+ if (project === null) {
+ throw new Error(`Not found project "${projectId}"`);
+ }
+
+ const { userId } = context.authorization;
if (userId === undefined) {
throw new Error("The user must be authenticated to clone the project");
@@ -173,7 +176,7 @@ const clone = async (
data: {
id: newProjectId,
userId: userId,
- title: title ?? project.title,
+ title: title ?? `${project.title} (copy)`,
domain: generateDomain(project.title),
previewImageAssetId: project.previewImageAsset?.id,
},
@@ -210,29 +213,6 @@ const clone = async (
return Project.parse(clonedProject);
};
-export const duplicate = async (
- {
- projectId,
- title,
- }: {
- projectId: string;
- title?: string | undefined;
- },
- context: AppContext
-) => {
- const project = await loadById(projectId, context);
- if (project === null) {
- throw new Error(`Not found project "${projectId}"`);
- }
- return await clone(
- {
- project,
- title: title ?? `${project.title} (copy)`,
- },
- context
- );
-};
-
export const updateDomain = async (
input: {
id: string;
diff --git a/packages/project/src/shared/schema.ts b/packages/project/src/shared/schema.ts
index 8a986583df..cde10b5fd0 100644
--- a/packages/project/src/shared/schema.ts
+++ b/packages/project/src/shared/schema.ts
@@ -33,6 +33,7 @@ export const Project = z.object({
.nullable()
),
});
+
export type Project = z.infer<typeof Project>;
export const Projects = z.array(Project);
diff --git a/packages/project/src/trpc/project-router.ts b/packages/project/src/trpc/project-router.ts
index 2eee625179..7e8a632e57 100644
--- a/packages/project/src/trpc/project-router.ts
+++ b/packages/project/src/trpc/project-router.ts
@@ -21,10 +21,10 @@ export const projectRouter = router({
// @todo pass ctx for authorization
return await db.project.markAsDeleted(input.projectId, ctx);
}),
- duplicate: procedure
+ clone: procedure
.input(z.object({ projectId: z.string(), title: z.optional(z.string()) }))
.mutation(async ({ input, ctx }) => {
- return await db.project.duplicate(
+ return await db.project.clone(
{
projectId: input.projectId,
title: input.title,
diff --git a/packages/sdk/src/schema/pages.ts b/packages/sdk/src/schema/pages.ts
index 092d71c095..e1d764a367 100644
--- a/packages/sdk/src/schema/pages.ts
+++ b/packages/sdk/src/schema/pages.ts
@@ -102,8 +102,9 @@ const ProjectMeta = z.object({
faviconAssetId: z.string().optional(),
code: z.string().optional(),
});
+export type ProjectMeta = z.infer<typeof ProjectMeta>;
-export const ProjectNewRedirectPathSchema = PagePath.or(
+export const ProjectNewRedirectPath = PagePath.or(
z.string().refine((data) => {
try {
new URL(data);
@@ -114,26 +115,24 @@ export const ProjectNewRedirectPathSchema = PagePath.or(
}, "Must be a valid URL")
);
-export const PageRedirectSchema = z.object({
+export const PageRedirect = z.object({
old: PagePath,
- new: ProjectNewRedirectPathSchema,
+ new: ProjectNewRedirectPath,
});
+export type PageRedirect = z.infer<typeof PageRedirect>;
-const ProjectSettings = z.object({
+export const CompilerSettings = z.object({
// All fields are optional to ensure consistency and allow for the addition of new fields without requiring migration
atomicStyles: z.boolean().optional(),
- redirects: z.array(PageRedirectSchema).optional(),
});
-
-export type PageRedirect = z.infer<typeof PageRedirectSchema>;
-
-export type ProjectMeta = z.infer<typeof ProjectMeta>;
+export type CompilerSettings = z.infer<typeof CompilerSettings>;
export type Page = z.infer<typeof Page>;
export const Pages = z.object({
meta: ProjectMeta.optional(),
- settings: ProjectSettings.optional(),
+ compiler: CompilerSettings.optional(),
+ redirects: z.array(PageRedirect).optional(),
homePage: HomePage,
pages: z
.array(Page)
diff --git a/packages/trpc-interface/src/authorize/project.server.ts b/packages/trpc-interface/src/authorize/project.server.ts
index d34bc2c9f2..9ce3358217 100644
--- a/packages/trpc-interface/src/authorize/project.server.ts
+++ b/packages/trpc-interface/src/authorize/project.server.ts
@@ -51,24 +51,6 @@ export const hasProjectPermit = async (
return true;
}
- // Allow load webstudiois for clone
- // @todo Rethink permissions for this use-case
- // The plan is to make new permission for projects which are allowed to be publicly clonable by anyone
- // https://github.com/webstudio-is/webstudio/issues/1038
- if (
- props.permit === "view" &&
- props.projectId === "62154aaef0cb0860ccf85d6e"
- ) {
- return true;
- }
-
- if (
- props.permit === "view" &&
- context.authorization.projectTemplates.includes(props.projectId)
- ) {
- return true;
- }
-
// Check if the user is allowed to access the project
if (authorization.userId !== undefined) {
checks.push(