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.

Implement clonable projects and user identification over a cookie

Oleg Isonen008926883ccf
diff --git a/app/routes/dashboard/index.tsx b/app/routes/dashboard/index.tsx
index 95fa540e4f..0c60cc8659 100644
--- a/app/routes/dashboard/index.tsx
+++ b/app/routes/dashboard/index.tsx
@@ -3,31 +3,35 @@ import {
redirect,
type LoaderFunction,
type ActionFunction,
+ json,
} from "remix";
import { Dashboard, links } from "~/dashboard";
import * as db from "~/shared/db";
import config from "~/config";
+import { ensureUserCookie } from "~/shared/session";
export { links };
export const action: ActionFunction = async ({ request }) => {
const formData = await request.formData();
- const title = formData.get("project") as string | null;
- const data = {} as { errors?: string };
+ const title = formData.get("project");
+ if (typeof title !== "string") return { errors: "Title required" };
+ const { userId, headers } = await ensureUserCookie(request);
try {
- const project = await db.project.create({ title });
- return redirect(`${config.designerPath}/${project.id}`);
+ const project = await db.project.create({ title, userId });
+ return redirect(`${config.designerPath}/${project.id}`, { headers });
} catch (error) {
if (error instanceof Error) {
- data.errors = error.message;
+ return { errors: error.message };
}
}
- return data;
+ return { errors: "Unexpected error" };
};
-export const loader: LoaderFunction = async () => {
- const projects = await db.project.loadAll();
- return { config, projects };
+export const loader: LoaderFunction = async ({ request }) => {
+ const { userId, headers } = await ensureUserCookie(request);
+ const projects = await db.project.loadManyByUserId(userId);
+ return json({ config, projects }, headers);
};
const DashboardRoute = () => {
diff --git a/app/routes/rest/project/clone.$domain.ts b/app/routes/rest/project/clone.$domain.ts
new file mode 100644
index 0000000000..a55f04e7f7
--- /dev/null
+++ b/app/routes/rest/project/clone.$domain.ts
@@ -0,0 +1,39 @@
+import { type LoaderFunction, redirect } from "remix";
+import type { Project, User } from "@webstudio-is/sdk";
+import * as db from "~/shared/db";
+import { ensureUserCookie } from "~/shared/session";
+import config from "~/config";
+
+const ensureProject = async ({
+ userId,
+ domain,
+}: {
+ userId: User["id"];
+ domain: string;
+}): Promise<Project> => {
+ const projects = await db.project.loadManyByUserId(userId);
+ if (projects.length !== 0) return projects[0];
+ return await db.project.clone(domain);
+};
+
+/**
+ * Currently this is used to demo the designer from landing page without
+ * having to sign up.
+ *
+ * 1. Set cookie with a random user id if not already set
+ * 2. Clone the project by domain if user doesn't have any projects yet
+ * 3. Redirect user to the designer with the cloned project
+ */
+export const loader: LoaderFunction = async ({ request, params }) => {
+ if (params.domain === undefined) return { errors: "Domain required" };
+ const { headers, userId } = await ensureUserCookie(request);
+ try {
+ const project = await ensureProject({ userId, domain: params.domain });
+ return redirect(`${config.designerPath}/${project.id}`, { headers });
+ } catch (error: unknown) {
+ if (error instanceof Error) {
+ return { errors: error.message };
+ }
+ }
+ return { errors: "Unexpected error" };
+};
diff --git a/app/shared/db/misc.server.ts b/app/shared/db/misc.server.ts
index 180421a31e..97e2d59764 100644
--- a/app/shared/db/misc.server.ts
+++ b/app/shared/db/misc.server.ts
@@ -24,7 +24,7 @@ export const publish = async ({
}
const tree = await db.tree.clone(project.devTreeId);
- await db.props.publish({
+ await db.props.clone({
previousTreeId: project.devTreeId,
nextTreeId: tree.id,
});
diff --git a/app/shared/db/project.server.ts b/app/shared/db/project.server.ts
index 053d1bb5b6..003ec6575f 100644
--- a/app/shared/db/project.server.ts
+++ b/app/shared/db/project.server.ts
@@ -1,10 +1,12 @@
import slugify from "slugify";
import { nanoid } from "nanoid";
-import type { Project } from "@webstudio-is/sdk";
+import type { Project, User } from "@webstudio-is/sdk";
import { prisma, Prisma } from "./prisma.server";
import * as db from ".";
-export const loadById = async (projectId?: string): Promise<Project | null> => {
+export const loadById = async (
+ projectId?: Project["id"]
+): Promise<Project | null> => {
if (typeof projectId !== "string") {
throw new Error("Project ID required");
}
@@ -14,8 +16,14 @@ export const loadById = async (projectId?: string): Promise<Project | null> => {
});
};
-export const loadAll = async (): Promise<Array<Project>> => {
- return await prisma.project.findMany();
+export const loadByDomain = async (domain: string): Promise<Project | null> => {
+ return await prisma.project.findUnique({ where: { domain } });
+};
+
+export const loadManyByUserId = async (
+ userId: User["id"]
+): Promise<Array<Project>> => {
+ return await prisma.project.findMany({ where: { userId } });
};
const slugifyOptions = { lower: true, strict: true };
@@ -23,25 +31,32 @@ const slugifyOptions = { lower: true, strict: true };
const MIN_DOMAIN_LENGTH = 10;
const MIN_TITLE_LENGTH = 2;
-export const create = async ({
- title,
-}: {
- title: string | null;
-}): Promise<Project> => {
- if (title === null || title.length < MIN_TITLE_LENGTH) {
- throw new Error(`Minimum ${MIN_TITLE_LENGTH} characters required`);
- }
+const generateDomain = (title: string) => {
const slugifiedTitle = slugify(title, slugifyOptions);
const domain = `${slugifiedTitle}-${nanoid(
// If user entered a long title already, we just add 5 chars generated id
// Otherwise we add the amount of chars to satisfy min length
Math.max(MIN_DOMAIN_LENGTH - slugifiedTitle.length - 1, 5)
)}`;
+ return domain;
+};
- const tree = await db.tree.create();
+export const create = async ({
+ userId,
+ title,
+}: {
+ userId: string;
+ title: string;
+}): Promise<Project> => {
+ if (title.length < MIN_TITLE_LENGTH) {
+ throw new Error(`Minimum ${MIN_TITLE_LENGTH} characters required`);
+ }
+ const domain = generateDomain(title);
+ const tree = await db.tree.create();
return await prisma.project.create({
data: {
+ userId,
title,
domain,
devTreeId: tree.id,
@@ -49,6 +64,35 @@ export const create = async ({
});
};
+export const clone = async (clonableDomain: string): Promise<Project> => {
+ const clonableProject = await loadByDomain(clonableDomain);
+ if (clonableProject === null) {
+ throw new Error(`Not found project "${clonableDomain}"`);
+ }
+ if (clonableProject.prodTreeId === null) {
+ throw new Error("Expected project to be published first");
+ }
+
+ const tree = await db.tree.clone(clonableProject.prodTreeId);
+ const domain = generateDomain(clonableProject.title);
+
+ const [project] = await Promise.all([
+ prisma.project.create({
+ data: {
+ userId: clonableProject.userId,
+ title: clonableProject.title,
+ domain,
+ devTreeId: tree.id,
+ },
+ }),
+ db.props.clone({
+ previousTreeId: clonableProject.prodTreeId,
+ nextTreeId: tree.id,
+ }),
+ ]);
+ return project;
+};
+
export const update = async ({
id,
...data
diff --git a/app/shared/db/props.server.ts b/app/shared/db/props.server.ts
index 33b4ab1883..2cc28e857b 100644
--- a/app/shared/db/props.server.ts
+++ b/app/shared/db/props.server.ts
@@ -107,7 +107,7 @@ export const deleteProps = async ({
}
};
-export const publish = async ({
+export const clone = async ({
previousTreeId,
nextTreeId,
}: {
diff --git a/app/shared/session/index.ts b/app/shared/session/index.ts
new file mode 100644
index 0000000000..9d23682347
--- /dev/null
+++ b/app/shared/session/index.ts
@@ -0,0 +1 @@
+export * from "./user.server";
diff --git a/app/shared/session/user.server.ts b/app/shared/session/user.server.ts
new file mode 100644
index 0000000000..b6d58a29c6
--- /dev/null
+++ b/app/shared/session/user.server.ts
@@ -0,0 +1,23 @@
+import ObjectId from "bson-objectid";
+import { createCookie } from "remix";
+
+const userIdParser = createCookie("user-id", {
+ maxAge: 604_800, // one week
+});
+
+export const ensureUserCookie = async (
+ request: Request
+): Promise<{ userId: string; headers?: { [key: string]: string } }> => {
+ const cookieString = request.headers.get("Cookie");
+ const userId = await userIdParser.parse(cookieString);
+ if (userId !== null) return { userId };
+ // We use a generated id temporarily as a way to demonstrate the designer
+ // to a new user without a signup.
+ const generatedUserId = ObjectId().toString();
+ return {
+ headers: {
+ "Set-Cookie": await userIdParser.serialize(generatedUserId),
+ },
+ userId,
+ };
+};
diff --git a/package.json b/package.json
index 21bc1ec73c..e2cdfe773b 100644
--- a/package.json
+++ b/package.json
@@ -42,7 +42,7 @@
"@remix-run/vercel": "^1.2.3",
"@stitches/react": "^1.2.6",
"@stitches/stringify": "^1.2.6",
- "@webstudio-is/sdk": "0.1.6",
+ "@webstudio-is/sdk": "^0.1.14",
"bson-objectid": "^2.0.2",
"camelcase": "^6.3.0",
"hyphenate-style-name": "^1.0.4",
diff --git a/yarn.lock b/yarn.lock
index eba447a0bb..be97082a72 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1820,10 +1820,10 @@
dependencies:
web-streams-polyfill "^3.1.1"
-"@webstudio-is/[email protected]":
- version "0.1.6"
- resolved "https://registry.yarnpkg.com/@webstudio-is/sdk/-/sdk-0.1.6.tgz#88f4eb1ba6268308aac5708da335f023a9131603"
- integrity sha512-jTvHk51+F7cwf3m3cDS4CM+2qFHui3XIo0MU5URnYZM3gmIwZI8+YMOi37XoDV2/0gb7xrao2eT/uFO+rmKJIA==
+"@webstudio-is/sdk@^0.1.14":
+ version "0.1.14"
+ resolved "https://registry.yarnpkg.com/@webstudio-is/sdk/-/sdk-0.1.14.tgz#7ce584c105a05fe94425b6cd99bbc46f5bd9ac2d"
+ integrity sha512-HBJziqBT532eonaCfeI2AV7CCXGY/xukyjWUkCkaj/ZN7Cg7+BoRpMLPtVtnEqJVS/o7lwsUEkOz8oGkkQKf8g==
dependencies:
"@prisma/client" "^3.10.0"
"@stitches/react" "^1.2.7"