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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
Switch on link and generate css for all pages on server (#1041)
Ivan Starkovd76c59809052
diff --git a/apps/builder/app/routes/$.tsx b/apps/builder/app/routes/$.tsxindex c2c9310c15..8aedefb12a 100644--- a/apps/builder/app/routes/$.tsx+++ b/apps/builder/app/routes/$.tsx@@ -1,9 +1,8 @@-import { redirect, json, LoaderArgs } from "@remix-run/node";+import { redirect, json, LoaderArgs, LinksFunction } from "@remix-run/node";import type { MetaFunction, ErrorBoundaryComponent } from "@remix-run/node";import { useLoaderData } from "@remix-run/react";-import djb2a from "djb2a";import { InstanceRoot, Root } from "@webstudio-is/react-sdk";-import { loadCanvasData } from "~/shared/db";+import { loadCanvasData, loadProductionCanvasData } from "~/shared/db";import env, { type PublicEnv } from "~/env/env.public.server";import { sentryException } from "~/shared/sentry";import { Canvas } from "~/canvas";@@ -14,35 +13,22 @@ import {dashboardPath,} from "~/shared/router-utils";import { db } from "@webstudio-is/project/server";-import type { DynamicLinksFunction } from "remix-utils";import type { CanvasData } from "@webstudio-is/project";import { customComponents } from "~/canvas/custom-components";import { createContext } from "~/shared/context.server";type Data = CanvasData & { env: PublicEnv; mode: BuildMode };-export const dynamicLinks: DynamicLinksFunction<CanvasData> = ({- data,- location,-}) => {- const searchParams = new URLSearchParams(location.search);- searchParams.set("pageId", data.page.id);-- // Break cache in case of css has changed- const cssHash = djb2a(JSON.stringify(data.tree));- searchParams.set("css-hash", `${cssHash}`);-+export const links: LinksFunction = () => {return [{rel: "stylesheet",- href: `/s/css/?${searchParams}`,+ href: `/s/css`,"data-webstudio": "ssr",},];};-export const handle = { dynamicLinks };-export const meta: MetaFunction = ({ data }: { data: Data }) => {const { page } = data;return { title: page.title, ...page.meta };@@ -58,32 +44,62 @@ export const loader = async ({ request }: LoaderArgs): Promise<Data> => {throw redirect(dashboardPath());}- const { mode } = buildParams;-const project = await db.project.loadByParams(buildParams, context);if (project === null) {throw json("Project not found", { status: 404 });}- const canvasData = await loadCanvasData(- {- project,- env: buildEnv,- pageIdOrPath:- "pageId" in buildParams ? buildParams.pageId : buildParams.pagePath,- },+ const { mode } = buildParams;++ const params: CanvasData["params"] = {};++ if (env.RESIZE_ORIGIN != null) {+ params.resizeOrigin = env.RESIZE_ORIGIN;+ }++ if (buildEnv === "dev") {+ const canvasData = await loadCanvasData(+ {+ project,+ env: buildEnv,+ pageIdOrPath:+ "pageId" in buildParams ? buildParams.pageId : buildParams.pagePath,+ },+ context+ );++ if (canvasData === undefined) {+ throw json("Page not found", { status: 404 });+ }++ return { ...canvasData, env, mode, params };+ }++ // For "prod" builds we emulate the published site behaviour, reusing the same data production site uses.+ // https://github.com/webstudio-is/webstudio-builder/issues/929+ // The code below only used on localhost "publish".+ const pagesCanvasData = await loadProductionCanvasData(+ { projectId: project.id },context);- if (canvasData === undefined) {- throw json("Page not found", { status: 404 });+ if (!("pagePath" in buildParams)) {+ throw json("pagePath must exists in buildParams in production mode", {+ status: 404,+ });}- const params: CanvasData["params"] = {};+ const pagePath = buildParams.pagePath === "/" ? "" : buildParams.pagePath;- if (env.RESIZE_ORIGIN != null) {- params.resizeOrigin = env.RESIZE_ORIGIN;+ const canvasData = pagesCanvasData.find(+ (data) => data.page.path === pagePath+ );++ if (canvasData === undefined) {+ throw json("Page not found", {+ status: 404,+ });}return { ...canvasData, env, mode, params };diff --git a/apps/builder/app/routes/index.tsx b/apps/builder/app/routes/index.tsxindex 31bd6ff760..c8ca97fa39 100644--- a/apps/builder/app/routes/index.tsx+++ b/apps/builder/app/routes/index.tsx@@ -11,16 +11,16 @@ import type {import CatchAllContnet, {loader as catchAllloader,meta as catchAllmeta,- handle as catchAllHandle,ErrorBoundary as CatchAllErrorBoundary,+ links as catchAllLinks,} 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 links = catchAllLinks;export const meta: MetaFunction = (args) => catchAllmeta(args);export const loader = (args: LoaderArgs) => catchAllloader(args);-export const handle = catchAllHandle;export const ErrorBoundary: ErrorBoundaryComponent = ({ error }) => (<CatchAllErrorBoundary error={error} />);diff --git a/apps/builder/app/routes/rest/project.$projectId.tsx b/apps/builder/app/routes/rest/project.$projectId.tsxindex 109f423d0f..fb2ff75487 100644--- a/apps/builder/app/routes/rest/project.$projectId.tsx+++ b/apps/builder/app/routes/rest/project.$projectId.tsx@@ -1,7 +1,6 @@import { json, type LoaderArgs } from "@remix-run/node";-import { db } from "@webstudio-is/project/server";import { sentryException } from "~/shared/sentry";-import { loadCanvasData } from "~/shared/db";+import { loadProductionCanvasData } from "~/shared/db";import type { CanvasData } from "@webstudio-is/project";import { createContext } from "~/shared/context.server";@@ -13,7 +12,6 @@ export const loader = async ({}: LoaderArgs): Promise<PagesDetails> => {try {const projectId = params.projectId ?? undefined;- const pages: PagesDetails = [];if (projectId === undefined) {throw json("Required project id", { status: 400 });@@ -21,42 +19,12 @@ export const loader = async ({const context = await createContext(request, "prod");- const prodBuild = await db.build.loadByProjectId(projectId, "prod");- if (prodBuild === undefined) {- throw json(- `Project ${projectId} not found or not published yet. Please contact us to get help.`,- { status: 500 }- );- }- const {- pages: { homePage, pages: otherPages },- } = prodBuild;- const project = await db.project.loadByParams({ projectId }, context);- if (project === null) {- throw json("Project not found", { status: 404 });- }- const canvasData = await loadCanvasData(- {- project,- env: "prod",- pageIdOrPath: homePage.path,- },+ const pagesCanvasData = await loadProductionCanvasData(+ { projectId },context);- pages.push(canvasData);-- if (otherPages.length > 0) {- for (const page of otherPages) {- const canvasData = await loadCanvasData(- { project, env: "prod", pageIdOrPath: page.path },- context- );- pages.push(canvasData);- }- }-- return pages;+ return pagesCanvasData;} catch (error) {// If a Response is thrown, we're rethrowing it for Remix to handle.// https://remix.run/docs/en/v1/api/conventions#throwing-responses-in-loadersdiff --git a/apps/builder/app/routes/s/css.ts b/apps/builder/app/routes/s/css.tsindex ac6b838eb3..2c94a0ccf3 100644--- a/apps/builder/app/routes/s/css.ts+++ b/apps/builder/app/routes/s/css.ts@@ -5,46 +5,102 @@ import env from "~/env/env.public.server";import { getBuildParams } from "~/shared/router-utils";import { sentryException } from "~/shared/sentry";import { createContext } from "~/shared/context.server";-import { loadCanvasData } from "~/shared/db";+import { loadCanvasData, loadProductionCanvasData } from "~/shared/db";+import type { Tree } from "@webstudio-is/project-build";export const loader = async ({ request }: ActionArgs) => {try {const buildParams = getBuildParams(request);- const context = await createContext(request);++ const buildEnv = buildParams?.mode === "published" ? "prod" : "dev";++ const context = await createContext(request, buildEnv);if (buildParams === undefined) {throw json("Required project info", { status: 400 });}const project = await db.project.loadByParams(buildParams, context);+if (project === null) {throw json("Project not found", { status: 404 });}- const canvasData = await loadCanvasData(- {- project,- env: buildParams.mode === "published" ? "prod" : "dev",- pageIdOrPath:- "pageId" in buildParams ? buildParams.pageId : buildParams.pagePath,- },+ if (buildEnv === "dev") {+ const canvasData = await loadCanvasData(+ {+ project,+ env: buildParams.mode === "published" ? "prod" : "dev",+ pageIdOrPath:+ "pageId" in buildParams ? buildParams.pageId : buildParams.pagePath,+ },+ context+ );++ if (canvasData === undefined) {+ throw json("Page not found", { status: 404 });+ }++ const cssText = generateCssText({+ assets: canvasData.assets,+ breakpoints: canvasData.build?.breakpoints,+ styles: canvasData.build?.styles,+ styleSourceSelections: canvasData.tree?.styleSourceSelections,+ });++ return new Response(cssText, {+ headers: {+ "Content-Type": "text/css",+ // We have no way with Remix links to know if CSS has changed (no ?cache-breaker in url)+ // We can add Last-Modified and change Cache-Control: no-cache, but this is only used to publish on localhost.+ // And can be completely omitted for Designer Canvas see https://github.com/webstudio-is/webstudio-builder/issues/1044+ // This is not a problem on the published site, since we know the data at build time.+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control+ "Cache-Control": "no-store",+ },+ });+ }++ // For "prod" builds we emulate the published site behaviour, reusing the same data production site uses.+ // https://github.com/webstudio-is/webstudio-builder/issues/929+ // The code below only used on localhost "publish".+ const pagesCanvasData = await loadProductionCanvasData(+ { projectId: project.id },context);- if (canvasData === undefined) {- throw json("Page not found", { status: 404 });++ if (pagesCanvasData.length === 0) {+ throw json("Project not found or not published yet", { status: 404 });+ }++ const canvasData = pagesCanvasData[0];++ const styleSourceSelections: Tree["styleSourceSelections"] = [];++ for (const pageCanvasData of pagesCanvasData) {+ if (pageCanvasData.tree?.styleSourceSelections) {+ styleSourceSelections.push(+ ...pageCanvasData.tree.styleSourceSelections+ );+ }}const cssText = generateCssText({assets: canvasData.assets,- build: canvasData.build ?? undefined,- tree: canvasData.tree ?? undefined,+ breakpoints: canvasData.build?.breakpoints,+ styles: canvasData.build?.styles,+ styleSourceSelections,});return new Response(cssText, {headers: {"Content-Type": "text/css",+ // We have no way with Remix links to know if CSS has changed (no ?cache-breaker in url)+ // We can add Last-Modified and change Cache-Control: no-cache, but this is only used to publish on localhost.+ // And can be completely omitted for Designer Canvas see https://github.com/webstudio-is/webstudio-builder/issues/1044+ // This is not a problem on the published site, since we know the data at build time.// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control- "Cache-Control": "public, max-age=31536000, immutable",+ "Cache-Control": "no-store",},});} catch (error) {diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.tsindex ae432d1e5b..9ec639ada1 100644--- a/apps/builder/app/shared/db/canvas.server.ts+++ b/apps/builder/app/shared/db/canvas.server.ts@@ -4,6 +4,57 @@ import { utils } from "@webstudio-is/project";import { loadByProject } from "@webstudio-is/asset-uploader/server";import type { AppContext } from "@webstudio-is/trpc-interface/server";+export const loadProductionCanvasData = async (+ props: {+ projectId: Project["id"];+ },+ context: AppContext+): Promise<CanvasData[]> => {+ const pagesCanvasData: CanvasData[] = [];++ const prodBuild = await projectDb.build.loadByProjectId(+ props.projectId,+ "prod"+ );+ if (prodBuild === undefined) {+ throw new Error(+ `Project ${props.projectId} not found or not published yet. Please contact us to get help.`+ );+ }+ const {+ pages: { homePage, pages: otherPages },+ } = prodBuild;+ const project = await projectDb.project.loadByParams(+ { projectId: props.projectId },+ context+ );+ if (project === null) {+ throw new Error("Project not found");+ }+ const canvasData = await loadCanvasData(+ {+ project,+ env: "prod",+ pageIdOrPath: homePage.path,+ },+ context+ );++ pagesCanvasData.push(canvasData);++ if (otherPages.length > 0) {+ for (const page of otherPages) {+ const canvasData = await loadCanvasData(+ { project, env: "prod", pageIdOrPath: page.path },+ context+ );+ pagesCanvasData.push(canvasData);+ }+ }++ return pagesCanvasData;+};+export const loadCanvasData = async (props: {project: Project;diff --git a/apps/builder/app/shared/router-utils/build-params.ts b/apps/builder/app/shared/router-utils/build-params.tsindex 4d65f286ce..e323e6b1c4 100644--- a/apps/builder/app/shared/router-utils/build-params.ts+++ b/apps/builder/app/shared/router-utils/build-params.ts@@ -92,6 +92,25 @@ export const getBuildParams = (): BuildParams | undefined => {const url = new URL(request.url);+ // Having that we use Remix `export const links` and have no way to pass+ // projectId and other params here, we need to get them from referer.+ if (url.pathname === "/s/css") {+ const referer = request.headers.get("referer");+ if (referer !== null) {+ // Try to get projectId from referrer+ const refererUrl = new URL(referer);+ const projectId = refererUrl.searchParams.get("projectId");+ const mode = getMode(refererUrl);+ const pageId = url.searchParams.get("pageId") ?? undefined;++ if (mode === "edit" && projectId !== null) {+ return pageId === undefined+ ? { projectId, mode, pagePath: refererUrl.pathname }+ : { projectId, mode, pageId };+ }+ }+ }+const requestHost = getRequestHost(request);const buildHost = new URL(getBuildOrigin(request, env)).host;const pageId = url.searchParams.get("pageId") ?? undefined;diff --git a/apps/builder/package.json b/apps/builder/package.jsonindex f7480b8df8..76922287dc 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -88,7 +88,6 @@"remix-auth-form": "^1.1.2","remix-auth-github": "^1.1.1","remix-auth-google": "^1.1.0",- "remix-utils": "^4.1.0","shallow-equal": "^3.0.0","slugify": "^1.6.5","use-debounce": "^9.0.2",diff --git a/packages/project/src/shared/styles/css.ts b/packages/project/src/shared/styles/css.tsindex 54681d665a..74d52beff5 100644--- a/packages/project/src/shared/styles/css.ts+++ b/packages/project/src/shared/styles/css.ts@@ -11,17 +11,18 @@ import { getStyleRules } from "./style-rules";type Data = {assets: Asset[];- build?: Build;- tree?: Tree;+ breakpoints?: Build["breakpoints"];+ styles?: Build["styles"];+ styleSourceSelections?: Tree["styleSourceSelections"];};export const generateCssText = (data: Data) => {const assets = new Map<Asset["id"], Asset>(data.assets.map((asset) => [asset.id, asset]));- const breakpoints = new Map(data.build?.breakpoints);- const styles = new Map(data.build?.styles);- const styleSourceSelections = new Map(data.tree?.styleSourceSelections);+ const breakpoints = new Map(data.breakpoints);+ const styles = new Map(data.styles);+ const styleSourceSelections = new Map(data.styleSourceSelections);const engine = createCssEngine({ name: "ssr" });diff --git a/packages/react-sdk/src/app/root.tsx b/packages/react-sdk/src/app/root.tsxindex 3dc43f8d81..984d5a1cfb 100644--- a/packages/react-sdk/src/app/root.tsx+++ b/packages/react-sdk/src/app/root.tsx@@ -1,5 +1,4 @@import { Links, Meta, Outlet as DefaultOutlet } from "@remix-run/react";-import { DynamicLinks } from "remix-utils";/*** We are using Outlet prop from index layout when user renders site from a subdomain.@@ -17,7 +16,6 @@ export const Root = ({<link rel="icon" href="/favicon.ico" type="image/x-icon" /><link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /><Meta />- <DynamicLinks /><Links /></head>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c58ccd4ee6..becbcd6143 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -147,7 +147,6 @@ importers:remix-auth-form: ^1.1.2remix-auth-github: ^1.1.1remix-auth-google: ^1.1.0- remix-utils: ^4.1.0shallow-equal: ^3.0.0slugify: ^1.6.5typescript: 4.9.5@@ -227,7 +226,6 @@ importers:remix-auth-form: 1.1.2_@[email protected]remix-auth-github: 1.1.1_yc3vs22pubtmhv3yghgusrq624remix-auth-google: 1.1.0_7hezgflccoug2cpzfocojatbf4- remix-utils: 4.1.0_p52ca3tf56qhkz35kdbkqzg2b4shallow-equal: 3.0.0slugify: 1.6.5use-debounce: [email protected]@@ -15659,6 +15657,7 @@ packages:/intl-parse-accept-language/1.0.0:resolution: {integrity: sha512-YFMSV91JNBOSjw1cOfw2tup6hDP7mkz+2AUV7W1L1AM6ntgI75qC1ZeFpjPGMrWp+upmBRTX2fJWQ8c7jsUWpA==}engines: {node: '>=14'}+ dev: true/invariant/2.2.4:resolution: {integrity: sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==}@@ -15669,6 +15668,7 @@ packages:/ip-regex/4.3.0:resolution: {integrity: sha512-B9ZWJxHHOHUhUjCPrMpLD4xEq35bUTClHM1S6CBU5ixQnkZmwipwgc96vAd7AAGM9TGHvJR+Uss+/Ak6UphK+Q==}engines: {node: '>=8'}+ dev: true/ip/1.1.8:resolution: {integrity: sha512-PuExPYUiu6qMBQb4l06ecm6T6ujzhmh+MeJcW9wa89PoAz5pvd4zPgN5WJV104mb6S2T1AwNIAaB70JNrLQWhg==}@@ -15927,6 +15927,7 @@ packages:engines: {node: '>=8'}dependencies:ip-regex: 4.3.0+ dev: true/is-map/2.0.2:resolution: {integrity: sha512-cOZFQQozTha1f4MxLFzlgKYPTyj26picdZTx82hbc/Xf4K/tZOOXSCkMvU4pKioRXGDLJRn0GM7Upe7kR721yg==}@@ -19974,27 +19975,6 @@ packages:uuid: 8.3.2dev: false- /remix-utils/4.1.0_p52ca3tf56qhkz35kdbkqzg2b4:- resolution: {integrity: sha512-Ii/+6bd56t2D3ADeXD4RGc3Ym7Yn/rA/n7GZ9naTjF+fire7vqsDhBPwhZV0gIJBLIbw8ZRUlIAg+Ia95+CLBA==}- engines: {node: '>=14'}- peerDependencies:- '@remix-run/react': ^1.1.1- '@remix-run/server-runtime': ^1.1.1- react: ^16.8.0 || ^17.0.0 || ^18.0.0- zod: ^3.19.1- dependencies:- '@remix-run/react': 1.12.0_sfoxds7t5ydpegc3knd667wn6m- intl-parse-accept-language: 1.0.0- is-ip: 3.1.0- react: 17.0.2- schema-dts: [email protected]- type-fest: 2.19.0- uuid: 8.3.2- zod: 3.19.1- transitivePeerDependencies:- - typescript- dev: false-/remix-utils/4.1.0_sxlvzljqaugd26575xxyuqvtmm:resolution: {integrity: sha512-Ii/+6bd56t2D3ADeXD4RGc3Ym7Yn/rA/n7GZ9naTjF+fire7vqsDhBPwhZV0gIJBLIbw8ZRUlIAg+Ia95+CLBA==}engines: {node: '>=14'}@@ -20294,6 +20274,7 @@ packages:typescript: '>=4.1.0'dependencies:typescript: 4.9.5+ dev: true/schema-utils/1.0.0:resolution: {integrity: sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==}