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.

new catch-all route for canvas/preview/published

Roman Pominov02434049b37b
diff --git a/apps/designer/app/config.ts b/apps/designer/app/config.ts
index 7bc8840d93..7bcd5c7519 100644
--- a/apps/designer/app/config.ts
+++ b/apps/designer/app/config.ts
@@ -1,6 +1,4 @@
const config = {
- previewPath: "/preview",
- canvasPath: "/canvas",
designerPath: "/designer",
dashboardPath: "/dashboard",
loginPath: "/login",
diff --git a/apps/designer/app/designer/designer.tsx b/apps/designer/app/designer/designer.tsx
index 0518f7cad9..72cf5459a3 100644
--- a/apps/designer/app/designer/designer.tsx
+++ b/apps/designer/app/designer/designer.tsx
@@ -321,7 +321,7 @@ export const Designer = ({ config, project, pages, pageId }: DesignerProps) => {
<Workspace onTransitionEnd={onTransitionEnd} publish={publish}>
<CanvasIframe
ref={iframeRefCallback}
- src={`${config.canvasPath}/${project.id}?pageId=${page.id}`}
+ src={`${page.path || "/"}?projectId=${project.id}&mode=edit`}
pointerEvents={
dragAndDropState.isDragging && dragAndDropState.origin === "panel"
? "none"
diff --git a/apps/designer/app/designer/features/topbar/share.tsx b/apps/designer/app/designer/features/topbar/share.tsx
index 900e494e08..6b4ddb4a1f 100644
--- a/apps/designer/app/designer/features/topbar/share.tsx
+++ b/apps/designer/app/designer/features/topbar/share.tsx
@@ -9,21 +9,22 @@ import {
TextField,
} from "@webstudio-is/design-system";
import { Share1Icon } from "@webstudio-is/icons";
-import type { Project, Page } from "@webstudio-is/project";
+import type { Project } from "@webstudio-is/project";
import { useIsShareDialogOpen } from "../../shared/nano-states";
type ShareButtonProps = {
- path: string;
projectId: Project["id"];
- pageId: Page["id"];
+ pagePath: string;
};
-const Content = ({ path, projectId, pageId }: ShareButtonProps) => {
+const Content = ({ projectId, pagePath }: ShareButtonProps) => {
if (typeof location === "undefined") {
return null;
}
const url = new URL(
- `${location.protocol}//${location.host}${path}/${projectId}?pageId=${pageId}`
+ `${location.protocol}//${location.host}${
+ pagePath || "/"
+ }?projectId=${projectId}&mode=preview`
);
return (
<PopoverContent
diff --git a/apps/designer/app/designer/features/topbar/topbar.tsx b/apps/designer/app/designer/features/topbar/topbar.tsx
index 5dfeb9b003..5d6c6e9a56 100644
--- a/apps/designer/app/designer/features/topbar/topbar.tsx
+++ b/apps/designer/app/designer/features/topbar/topbar.tsx
@@ -62,11 +62,7 @@ export const Topbar = ({
>
<SyncStatus />
<PreviewButton publish={publish} />
- <ShareButton
- path={config.previewPath}
- projectId={project.id}
- pageId={page.id}
- />
+ <ShareButton projectId={project.id} pagePath={page.path} />
<PublishButton project={project} />
</Flex>
</Flex>
diff --git a/apps/designer/app/entry.server.tsx b/apps/designer/app/entry.server.tsx
index 2d217876da..969eed6c8e 100644
--- a/apps/designer/app/entry.server.tsx
+++ b/apps/designer/app/entry.server.tsx
@@ -4,7 +4,7 @@ import { initSentry } from "./shared/sentry";
import { prisma } from "@webstudio-is/prisma-client";
import { handleRequest as handleRequestDesigner } from "./shared/remix";
import { handleRequest as handleRequestCanvas } from "@webstudio-is/react-sdk";
-import config from "./config";
+import { isCanvasRequest } from "./routes/$";
initSentry({
integrations: [new Sentry.Integrations.Prisma({ client: prisma })],
@@ -16,13 +16,9 @@ export default function handleRequest(
responseHeaders: Headers,
remixContext: EntryContext
) {
- const { pathname } = new URL(request.url);
let handle = handleRequestDesigner;
- if (
- pathname.indexOf(config.previewPath) === 0 ||
- pathname.indexOf(config.canvasPath) === 0
- ) {
+ if (isCanvasRequest(request)) {
handle = handleRequestCanvas;
}
diff --git a/apps/designer/app/routes/$.tsx b/apps/designer/app/routes/$.tsx
new file mode 100644
index 0000000000..2547d31f35
--- /dev/null
+++ b/apps/designer/app/routes/$.tsx
@@ -0,0 +1,130 @@
+import { type LoaderFunction, redirect, MetaFunction } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { InstanceRoot, Root } from "@webstudio-is/react-sdk";
+import { loadCanvasData, type CanvasData } from "~/shared/db";
+import config from "~/config";
+import { db } from "@webstudio-is/project/index.server";
+import env, { Env } from "~/env.server";
+import { sentryException } from "~/shared/sentry";
+import { Canvas } from "~/canvas";
+
+type Mode = "edit" | "preview" | "published";
+
+type Data =
+ | (CanvasData & { env: Env; mode: Mode })
+ | { errors: string; env: Env };
+
+type ProjectIdentifier = { type: "id" | "domain"; value: string };
+
+export const isCanvasRequest = (
+ request: Request
+): false | { projectId: ProjectIdentifier; mode: Mode; pathname: string } => {
+ const url = new URL(request.url);
+
+ const pathname = url.pathname;
+
+ if (Object.values(config).some((path) => pathname.startsWith(path))) {
+ return false;
+ }
+
+ let projectId: ProjectIdentifier | undefined = undefined;
+
+ // @todo all this subdomain logic is very hacky
+ const host =
+ request.headers.get("x-forwarded-host") ||
+ request.headers.get("host") ||
+ "";
+ const [userDomain, wstdDomain] = host.split(".");
+ if (wstdDomain === "wstd" || wstdDomain?.includes("localhost")) {
+ projectId = { type: "domain", value: userDomain };
+ }
+
+ if (projectId === undefined) {
+ const projectIdParam = url.searchParams.get("projectId");
+ if (projectIdParam !== null) {
+ projectId = { type: "id", value: projectIdParam };
+ }
+ }
+
+ if (projectId === undefined) {
+ return false;
+ }
+
+ const modeParam = url.searchParams.get("mode");
+
+ if (modeParam === "edit") {
+ return { projectId, mode: "edit", pathname };
+ }
+
+ if (modeParam === "preview") {
+ return { projectId, mode: "preview", pathname };
+ }
+
+ return { projectId, mode: "published", pathname };
+};
+
+export const meta: MetaFunction = ({ data }: { data: Data }) => {
+ if ("errors" in data) {
+ return { title: "Error" };
+ }
+ const { page } = data;
+ return { title: page.title, ...page.meta };
+};
+
+export const loader: LoaderFunction = async ({
+ request,
+}): Promise<Data | Response> => {
+ try {
+ const canvasRequest = isCanvasRequest(request);
+
+ if (canvasRequest === false) {
+ return redirect(config.dashboardPath);
+ }
+
+ const { projectId, mode, pathname } = canvasRequest;
+
+ const project =
+ projectId.type === "id"
+ ? await db.project.loadById(projectId.value)
+ : await db.project.loadByDomain(projectId.value);
+
+ if (project === null) {
+ throw new Error("Project not found");
+ }
+
+ const canvasData = await loadCanvasData(
+ project.id,
+ mode === "published" ? "prod" : "dev",
+ pathname
+ );
+
+ return { ...canvasData, env, mode };
+ } catch (error) {
+ sentryException({ error });
+ return {
+ errors: error instanceof Error ? error.message : String(error),
+ env,
+ };
+ }
+};
+
+const Content = () => {
+ const data = useLoaderData<Data>();
+
+ if ("errors" in data) {
+ return <p>{data.errors}</p>;
+ }
+
+ const Outlet =
+ data.mode === "edit"
+ ? () => <Canvas data={data} />
+ : () => <InstanceRoot data={data} />;
+
+ // @todo This is non-standard for Remix, is there a better way?
+ // We need to render essentially the preview route but from the index,
+ // so we have to know the layout and the outlet from here.
+ // Maybe there is a way to tell remix to use the right outlet somehow and avoid passing it?
+ return <Root Outlet={Outlet} />;
+};
+
+export default Content;
diff --git a/apps/designer/app/routes/canvas/$projectId.tsx b/apps/designer/app/routes/canvas/$projectId.tsx
deleted file mode 100644
index b10818c1de..0000000000
--- a/apps/designer/app/routes/canvas/$projectId.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import { useLoaderData } from "@remix-run/react";
-import type { LoaderFunction, MetaFunction } from "@remix-run/node";
-import { Canvas } from "~/canvas";
-import { loadCanvasData, type CanvasData } from "~/shared/db";
-import { ErrorMessage } from "~/shared/error";
-import { sentryException } from "~/shared/sentry";
-import { Root } from "@webstudio-is/react-sdk";
-
-type Data = CanvasData | { errors: string };
-
-export const meta: MetaFunction = ({ data }: { data: Data }) => {
- if ("errors" in data) {
- return { title: "Error" };
- }
- const { page } = data;
- return { title: page.title, ...page.meta };
-};
-
-export const loader: LoaderFunction = async ({
- params,
- request,
-}): Promise<Data> => {
- try {
- if (params.projectId === undefined) {
- throw new Error("Missing projectId");
- }
-
- const url = new URL(request.url);
- const pageIdParam = url.searchParams.get("pageId");
-
- return loadCanvasData(params.projectId, pageIdParam || undefined);
- } catch (error) {
- sentryException({ error });
- return { errors: error instanceof Error ? error.message : String(error) };
- }
-};
-
-const Outlet = () => {
- const data = useLoaderData<CanvasData>();
- return <Canvas data={data} />;
-};
-
-const CanvasRoute = () => {
- const data = useLoaderData<Data>();
- if ("errors" in data) {
- return <ErrorMessage message={data.errors} />;
- }
- return <Root Outlet={Outlet} />;
-};
-
-export default CanvasRoute;
diff --git a/apps/designer/app/routes/index.tsx b/apps/designer/app/routes/index.tsx
index 7ef1149563..476a48fc1f 100644
--- a/apps/designer/app/routes/index.tsx
+++ b/apps/designer/app/routes/index.tsx
@@ -1,87 +1,18 @@
-import { type LoaderFunction, redirect } from "@remix-run/node";
-import { useLoaderData } from "@remix-run/react";
-import { type Data, InstanceRoot, Root } from "@webstudio-is/react-sdk";
-import config from "~/config";
-import { db } from "@webstudio-is/project/index.server";
-import env, { Env } from "~/env.server";
-
-// @todo all this subdomain logic is very hacky
-
-type Error = { errors: string };
-type LoaderReturnProps = Promise<
- (Data & { env: Env }) | (Error & { env: Env }) | Response
->;
-
-export const loader: LoaderFunction = async ({
- request,
-}): LoaderReturnProps => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const [userDomain, wstdDomain] = host.split(".");
- // We render the site from a subdomain
- if (
- typeof userDomain === "string" &&
- (wstdDomain === "wstd" || wstdDomain?.includes("localhost"))
- ) {
- try {
- const project = await db.project.loadByDomain(userDomain);
- if (project === null) {
- throw new Error(`Unknown domain "${userDomain}"`);
- }
-
- const prodBuild = await db.build.loadByProjectId(project.id, "prod");
-
- if (prodBuild === undefined) {
- throw new Error(`Site is not published`);
- }
-
- // @todo: use a correct page rather than homePage
-
- const [tree, props, breakpoints] = await Promise.all([
- db.tree.loadById(prodBuild.pages.homePage.treeId),
- db.props.loadByTreeId(prodBuild.pages.homePage.treeId),
- db.breakpoints.load(prodBuild.id),
- ]);
- if (tree === null) {
- throw new Error(`Tree ${prodBuild.pages.homePage.treeId} not found`);
- }
- if (breakpoints === null) {
- throw new Error(
- `Breakpoints for tree ${prodBuild.pages.homePage.treeId} not found`
- );
- }
- return { tree, props, breakpoints: breakpoints.values, env };
- } catch (error) {
- if (error instanceof Error) {
- return { errors: error.message, env };
- }
- }
- }
-
- return redirect(config.dashboardPath);
-};
-
-const Index = () => {
- const data = useLoaderData<Data | Error>();
- if ("errors" in data) {
- return <p>{data.errors}</p>;
- }
-
- // We render the site from a subdomain
- if (data.tree && data.props) {
- const Outlet = () => <InstanceRoot data={data} />;
-
- // @todo This is non-standard for Remix, is there a better way?
- // We need to render essentially the preview route but from the index,
- // so we have to know the layout and the outlet from here.
- // Maybe there is a way to tell remix to use the right outlet somehow and avoid passing it?
- return <Root Outlet={Outlet} />;
- }
-
- return null;
-};
-
-export default Index;
+// We want our catch-all route to also handle `/`.
+// Unfortunately, Remix doesn't do this by default,
+// see https://github.com/remix-run/remix/issues/2098#issuecomment-1049262218 .
+// To solve this, we're re-exporting the $.tsx route API in index.tsx
+
+import { LoaderFunction, MetaFunction } from "@remix-run/node";
+import CatchAllContnet, {
+ loader as catchAllloader,
+ meta as catchAllmeta,
+} from "./$";
+
+// We're wrapping functions in order for them to be distinct from the ones in $.tsx.
+// If they are the same, Remix may get confused, and don't load data on page transitions.
+
+export const meta: MetaFunction = (args) => catchAllmeta(args);
+export const loader: LoaderFunction = (args) => catchAllloader(args);
+const Content = () => <CatchAllContnet />;
+export default Content;
diff --git a/apps/designer/app/routes/preview/$projectId.tsx b/apps/designer/app/routes/preview/$projectId.tsx
deleted file mode 100644
index 6c5166ab27..0000000000
--- a/apps/designer/app/routes/preview/$projectId.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { useLoaderData } from "@remix-run/react";
-import type { LoaderFunction, MetaFunction } from "@remix-run/node";
-import { loadCanvasData, type CanvasData } from "~/shared/db";
-import { InstanceRoot, Root } from "@webstudio-is/react-sdk";
-import { sentryException } from "~/shared/sentry";
-
-type Data = CanvasData | { errors: string };
-
-export const meta: MetaFunction = ({ data }: { data: Data }) => {
- if ("errors" in data) {
- return { title: "Error" };
- }
- const { page } = data;
- return { title: page.title, ...page.meta };
-};
-
-export const loader: LoaderFunction = async ({
- params,
- request,
-}): Promise<Data> => {
- try {
- if (params.projectId === undefined) {
- throw new Error("Missing projectId");
- }
-
- const url = new URL(request.url);
- const pageIdParam = url.searchParams.get("pageId");
-
- return loadCanvasData(params.projectId, pageIdParam || undefined);
- } catch (error) {
- sentryException({ error });
- return { errors: error instanceof Error ? error.message : String(error) };
- }
-};
-
-const Outlet = () => {
- const data = useLoaderData<CanvasData>();
- return <InstanceRoot data={data} />;
-};
-
-const PreviewRoute = () => {
- const data = useLoaderData<Data>();
- if ("errors" in data) {
- return <p>{data.errors}</p>;
- }
- return <Root Outlet={Outlet} />;
-};
-
-export default PreviewRoute;
diff --git a/apps/designer/app/shared/db/canvas.server.ts b/apps/designer/app/shared/db/canvas.server.ts
index 1b05f12c13..9ed4fe0fa5 100644
--- a/apps/designer/app/shared/db/canvas.server.ts
+++ b/apps/designer/app/shared/db/canvas.server.ts
@@ -7,27 +7,28 @@ export type CanvasData = Data & { buildId: Build["id"]; page: Page };
export const loadCanvasData = async (
projectId: Project["id"],
- pageId?: Page["id"]
+ env: "dev" | "prod",
+ pagePath = ""
): Promise<CanvasData> => {
- const project = await db.project.loadById(projectId);
+ const build =
+ env === "dev"
+ ? await db.build.loadByProjectId(projectId, "dev")
+ : await db.build.loadByProjectId(projectId, "prod");
- if (project === null) throw new Error(`Project "${projectId}" not found`);
-
- const devBuild = await db.build.loadByProjectId(projectId, "dev");
+ if (build === undefined) {
+ throw new Error("The project is not published");
+ }
- const page =
- pageId === undefined
- ? devBuild.pages.homePage
- : utils.pages.findById(devBuild.pages, pageId);
+ const page = utils.pages.findByPath(build.pages, pagePath);
if (page === undefined) {
- throw new Error(`Page "${pageId}" not found`);
+ throw new Error(`Page "${pagePath}" not found`);
}
const [tree, props, breakpoints] = await Promise.all([
db.tree.loadById(page.treeId),
db.props.loadByTreeId(page.treeId),
- db.breakpoints.load(devBuild.id),
+ db.breakpoints.load(build.id),
]);
if (tree === null) {
@@ -42,7 +43,7 @@ export const loadCanvasData = async (
tree,
props,
breakpoints: breakpoints.values,
- buildId: devBuild.id,
+ buildId: build.id,
page,
};
};
diff --git a/packages/project/src/shared/pages/find-by-path.ts b/packages/project/src/shared/pages/find-by-path.ts
new file mode 100644
index 0000000000..a286071248
--- /dev/null
+++ b/packages/project/src/shared/pages/find-by-path.ts
@@ -0,0 +1,11 @@
+import { type Pages, type Page } from "../../db/types";
+
+export const findByPath = (
+ pages: Pages,
+ pagePath: string
+): Page | undefined => {
+ if (pagePath === "" || pagePath === "/") {
+ return pages.homePage;
+ }
+ return pages.pages.find((page) => page.path === pagePath);
+};
diff --git a/packages/project/src/shared/pages/index.ts b/packages/project/src/shared/pages/index.ts
index 41138b8354..d4526db190 100644
--- a/packages/project/src/shared/pages/index.ts
+++ b/packages/project/src/shared/pages/index.ts
@@ -1 +1,2 @@
export * from "./find-by-id";
+export * from "./find-by-path";