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: Dashboard thumbnails (#2836)

Oleg Isonen64940433c16b
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.stories.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.stories.tsx
index 87a356c17d..799039eb0c 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.stories.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.stories.tsx
@@ -61,6 +61,10 @@ $project.set({
isDeleted: false,
userId: "userId",
domain: "new-2x9tcd",
+ previewImageAsset: {
+ id: "0",
+ name: "0",
+ },
});
export const PageSettingsEdit = () => {
diff --git a/apps/builder/app/dashboard/dashboard.stories.tsx b/apps/builder/app/dashboard/dashboard.stories.tsx
index cb152e26a2..cc2b0ab215 100644
--- a/apps/builder/app/dashboard/dashboard.stories.tsx
+++ b/apps/builder/app/dashboard/dashboard.stories.tsx
@@ -57,6 +57,7 @@ export const WithProjects: ComponentStory<typeof Dashboard> = () => {
isDeleted: false,
isPublished: false,
latestBuild: null,
+ previewImageAsset: null,
},
];
const router = createRouter(
diff --git a/apps/builder/app/dashboard/projects/project-card.tsx b/apps/builder/app/dashboard/projects/project-card.tsx
index 4e6c4efa0a..d40f9cc628 100644
--- a/apps/builder/app/dashboard/projects/project-card.tsx
+++ b/apps/builder/app/dashboard/projects/project-card.tsx
@@ -26,7 +26,12 @@ import {
ShareProjectDialog,
DuplicateProjectDialog,
} from "./project-dialogs";
-import { Thumbnail, ThumbnailLink } from "./thumbnail-link";
+import {
+ ThumbnailLinkWithAbbr,
+ ThumbnailLinkWithImage,
+ ThumbnailWithAbbr,
+ ThumbnailWithImage,
+} from "./thumbnail";
import { useNavigation } from "@remix-run/react";
import { Spinner } from "../spinner";
import type { DashboardProject } from "@webstudio-is/dashboard";
@@ -51,6 +56,7 @@ const thumbnailStyle = css({
position: "relative",
overflow: "hidden",
minWidth: "100%",
+ height: "100%",
});
const footerStyle = css({
@@ -197,6 +203,7 @@ export const ProjectCard = ({
hasProPlan,
createdAt,
latestBuild,
+ previewImageAsset,
}: ProjectCardProps) => {
const [isRenameDialogOpen, setIsRenameDialogOpen] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
@@ -219,7 +226,19 @@ export const ProjectCard = ({
onKeyDown={handleKeyDown}
>
<Grid className={thumbnailStyle()}>
- <ThumbnailLink title={title} to={linkPath} ref={thumbnailRef} />
+ {previewImageAsset ? (
+ <ThumbnailLinkWithImage
+ to={linkPath}
+ name={previewImageAsset.name}
+ ref={thumbnailRef}
+ />
+ ) : (
+ <ThumbnailLinkWithAbbr
+ title={title}
+ to={linkPath}
+ ref={thumbnailRef}
+ />
+ )}
{isTransitioning && <Spinner delay={0} />}
</Grid>
@@ -304,6 +323,7 @@ export const ProjectTemplateCard = ({
id,
title,
domain,
+ previewImageAsset,
isPublished,
}: Omit<ProjectCardProps, "hasProPlan">) => {
const { thumbnailRef, handleKeyDown } = useProjectCard();
@@ -320,13 +340,23 @@ export const ProjectTemplateCard = ({
onKeyDown={handleKeyDown}
>
<Grid className={thumbnailStyle()}>
- <Thumbnail
- title={title}
- ref={thumbnailRef}
- onClick={() => {
- setIsDuplicateDialogOpen(true);
- }}
- />
+ {previewImageAsset ? (
+ <ThumbnailWithImage
+ name={previewImageAsset.name}
+ ref={thumbnailRef}
+ onClick={() => {
+ setIsDuplicateDialogOpen(true);
+ }}
+ />
+ ) : (
+ <ThumbnailWithAbbr
+ title={title}
+ ref={thumbnailRef}
+ onClick={() => {
+ setIsDuplicateDialogOpen(true);
+ }}
+ />
+ )}
</Grid>
<Flex
diff --git a/apps/builder/app/dashboard/projects/thumbnail-link.tsx b/apps/builder/app/dashboard/projects/thumbnail-link.tsx
deleted file mode 100644
index 21f334e4e0..0000000000
--- a/apps/builder/app/dashboard/projects/thumbnail-link.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { css, theme, textVariants } from "@webstudio-is/design-system";
-import { forwardRef } from "react";
-import { Link } from "@remix-run/react";
-
-const thumbnailStyle = css(textVariants.brandThumbnailLargeDefault, {
- display: "flex",
- alignItems: "center",
- alignSelf: "center",
- minHeight: 0,
- background: theme.colors.brandBackgroundProjectCardFront,
- WebkitBackgroundClip: "text",
- backgroundClip: "text",
- color: "transparent",
- outline: "none",
- "&:hover, &:focus": {
- ...textVariants.brandThumbnailLargeHover,
- transition: "100ms",
- },
-});
-
-// My Next Project > MN
-const getThumbnailAbbreviation = (title: string) =>
- title
- .split(/\s+/)
- .slice(0, 2)
- .map((word) => word.charAt(0).toUpperCase())
- .join("");
-
-export const ThumbnailLink = forwardRef<
- HTMLAnchorElement,
- { title: string; to: string }
->(({ title, to }, ref) => {
- return (
- <Link ref={ref} to={to} className={thumbnailStyle()} tabIndex={-1}>
- {getThumbnailAbbreviation(title)}
- </Link>
- );
-});
-
-export const Thumbnail = forwardRef<
- HTMLDivElement,
- { title: string; onClick: React.MouseEventHandler<HTMLDivElement> }
->(({ title, onClick }, ref) => {
- return (
- <div ref={ref} onClick={onClick} className={thumbnailStyle()} tabIndex={-1}>
- {getThumbnailAbbreviation(title)}
- </div>
- );
-});
-
-Thumbnail.displayName = "Thumbnail";
-ThumbnailLink.displayName = "ThumbnailLink";
diff --git a/apps/builder/app/dashboard/projects/thumbnail.tsx b/apps/builder/app/dashboard/projects/thumbnail.tsx
new file mode 100644
index 0000000000..186eea7657
--- /dev/null
+++ b/apps/builder/app/dashboard/projects/thumbnail.tsx
@@ -0,0 +1,107 @@
+import { forwardRef } from "react";
+import { Link } from "@remix-run/react";
+import { Image, createImageLoader } from "@webstudio-is/image";
+import { css, theme, textVariants } from "@webstudio-is/design-system";
+import env from "~/shared/env";
+
+const abbrStyle = css(textVariants.brandThumbnailLargeDefault, {
+ display: "flex",
+ alignItems: "center",
+ alignSelf: "center",
+ minHeight: 0,
+ background: theme.colors.brandBackgroundProjectCardFront,
+ WebkitBackgroundClip: "text",
+ backgroundClip: "text",
+ color: "transparent",
+ outline: "none",
+ "&:hover, &:focus": {
+ ...textVariants.brandThumbnailLargeHover,
+ transition: "100ms",
+ },
+});
+
+// My Next Project > MN
+const getThumbnailAbbreviation = (title: string) =>
+ title
+ .split(/\s+/)
+ .slice(0, 2)
+ .map((word) => word.charAt(0).toUpperCase())
+ .join("");
+
+export const ThumbnailLinkWithAbbr = forwardRef<
+ HTMLAnchorElement,
+ { title: string; to: string }
+>(({ title, to }, ref) => {
+ return (
+ <Link ref={ref} to={to} className={abbrStyle()} tabIndex={-1}>
+ {getThumbnailAbbreviation(title)}
+ </Link>
+ );
+});
+ThumbnailLinkWithAbbr.displayName = "ThumbnailLinkWithAbbr";
+
+export const ThumbnailWithAbbr = forwardRef<
+ HTMLDivElement,
+ { title: string; onClick: React.MouseEventHandler<HTMLDivElement> }
+>(({ title, onClick }, ref) => {
+ return (
+ <div ref={ref} onClick={onClick} className={abbrStyle()} tabIndex={-1}>
+ {getThumbnailAbbreviation(title)}
+ </div>
+ );
+});
+
+ThumbnailWithAbbr.displayName = "ThumbnailWithAbbr";
+
+const imageLoader = createImageLoader({
+ imageBaseUrl: env.IMAGE_BASE_URL,
+});
+
+const imageContainerStyle = css({
+ position: "relative",
+ background: theme.colors.brandBackgroundProjectCardFront,
+ outline: "none",
+ overflow: "hidden",
+ transition: "transform 100ms",
+ "&:hover, &:focus": {
+ transform: "scale(1.1)",
+ },
+});
+
+const imageStyle = css({
+ position: "absolute",
+ top: 0,
+ width: "100%",
+ height: "100%",
+ objectFit: "cover",
+});
+
+export const ThumbnailLinkWithImage = forwardRef<
+ HTMLAnchorElement,
+ { name: string; to: string }
+>(({ name, to }, ref) => {
+ return (
+ <Link ref={ref} to={to} className={imageContainerStyle()} tabIndex={-1}>
+ <Image src={name} loader={imageLoader} className={imageStyle()} />
+ </Link>
+ );
+});
+ThumbnailLinkWithImage.displayName = "ThumbnailLinkWithImage";
+
+export const ThumbnailWithImage = forwardRef<
+ HTMLDivElement,
+ { name: string; onClick: React.MouseEventHandler<HTMLDivElement> }
+>(({ name, onClick }, ref) => {
+ return (
+ <div
+ ref={ref}
+ onClick={onClick}
+ className={imageContainerStyle()}
+ tabIndex={-1}
+ >
+ <Image src={name} loader={imageLoader} className={imageStyle()} />
+ </div>
+ );
+});
+
+ThumbnailWithImage.displayName = "ThumbnailWithImage";
diff --git a/apps/builder/app/routes/dashboard._index.tsx b/apps/builder/app/routes/dashboard._index.tsx
index f119979db0..9beb1ff2f5 100644
--- a/apps/builder/app/routes/dashboard._index.tsx
+++ b/apps/builder/app/routes/dashboard._index.tsx
@@ -10,7 +10,6 @@ import { sentryException } from "~/shared/sentry";
import { ErrorMessage } from "~/shared/error";
import { createContext } from "~/shared/context.server";
import env from "~/env/env.server";
-
export const loader = async ({
request,
}: LoaderArgs): Promise<ComponentProps<typeof Dashboard>> => {
@@ -32,13 +31,9 @@ export const loader = async ({
.createCaller(context)
.findMany({ userId: user.id });
- const projectIds = env.PROJECT_TEMPLATES;
-
const projectTemplates = await dashboardProjectRouter
.createCaller(context)
- .findManyByIds({
- projectIds,
- });
+ .findManyByIds({ projectIds: env.PROJECT_TEMPLATES });
const { userPlanFeatures } = context;
diff --git a/apps/builder/app/routes/rest.patch.ts b/apps/builder/app/routes/rest.patch.ts
index db1584739b..5fd9636688 100644
--- a/apps/builder/app/routes/rest.patch.ts
+++ b/apps/builder/app/routes/rest.patch.ts
@@ -34,6 +34,7 @@ import { patchAssets } from "@webstudio-is/asset-uploader/index.server";
import type { Project } from "@webstudio-is/project";
import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";
import { createContext } from "~/shared/context.server";
+import { db } from "@webstudio-is/project/index.server";
type PatchData = {
transactions: Array<SyncItem>;
@@ -107,6 +108,8 @@ export const action = async ({ request }: ActionArgs) => {
styles?: Styles;
} = {};
+ let previewImageAssetId: string | null | undefined = undefined;
+
// Used to optimize by validating only changed styles, as they accounted for 99% of validation time
const patchedStyleDeclKeysSet = new Set<string>();
@@ -120,7 +123,14 @@ export const action = async ({ request }: ActionArgs) => {
if (namespace === "pages") {
// lazily parse build data before patching
const pages = buildData.pages ?? parsePages(build.pages);
+ const currentSocialImageAssetId =
+ pages.homePage.meta.socialImageAssetId;
buildData.pages = applyPatches(pages, patches);
+ const newSocialImageAssetId =
+ buildData.pages.homePage.meta.socialImageAssetId;
+ if (currentSocialImageAssetId !== newSocialImageAssetId) {
+ previewImageAssetId = newSocialImageAssetId || null;
+ }
continue;
}
@@ -288,6 +298,13 @@ export const action = async ({ request }: ActionArgs) => {
};
}
+ if (previewImageAssetId !== undefined) {
+ await db.project.updatePreviewImage(
+ { assetId: previewImageAssetId, projectId },
+ context
+ );
+ }
+
return { status: "ok" };
} catch (e) {
return { errors: e instanceof Error ? e.message : JSON.stringify(e) };
diff --git a/packages/dashboard/src/db/projects.ts b/packages/dashboard/src/db/projects.ts
index d23a735d50..e347666360 100644
--- a/packages/dashboard/src/db/projects.ts
+++ b/packages/dashboard/src/db/projects.ts
@@ -8,6 +8,9 @@ export const findMany = async (userId: string, context: AppContext) => {
userId,
isDeleted: false,
},
+ include: {
+ previewImageAsset: true,
+ },
orderBy: [
{
createdAt: "desc",
@@ -36,6 +39,9 @@ export const findManyByIds = async (
},
isDeleted: false,
},
+ include: {
+ previewImageAsset: true,
+ },
orderBy: [
{
createdAt: "desc",
diff --git a/packages/prisma-client/prisma/migrations/20240127230238_project-preview/migration.sql b/packages/prisma-client/prisma/migrations/20240127230238_project-preview/migration.sql
new file mode 100644
index 0000000000..0f2d850198
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20240127230238_project-preview/migration.sql
@@ -0,0 +1,29 @@
+ALTER TABLE
+ "public"."Project"
+ADD
+ COLUMN "previewImageAssetId" text;
+
+-- AddForeignKey
+ALTER TABLE
+ "Project"
+ADD
+ CONSTRAINT "Project_previewImageAssetId_id_fkey" FOREIGN KEY ("previewImageAssetId", "id") REFERENCES "Asset"("id", "projectId") ON DELETE
+SET
+ NULL;
+
+-- Update DashboardProject View
+CREATE
+OR REPLACE VIEW "DashboardProject" AS
+SELECT
+ *,
+ EXISTS (
+ SELECT
+ 1
+ from
+ "Build"
+ WHERE
+ "Build"."projectId" = "Project".id
+ AND "Build"."deployment" IS NOT NULL
+ ) AS "isPublished"
+FROM
+ "Project";
\ No newline at end of file
diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prisma
index 877735e688..6dcb0acb33 100644
--- a/packages/prisma-client/prisma/schema.prisma
+++ b/packages/prisma-client/prisma/schema.prisma
@@ -42,10 +42,12 @@ model File {
}
model Asset {
- id String @default(uuid()) // not unique!
- projectId String
- file File @relation(fields: [name], references: [name])
- name String
+ id String @default(uuid()) // not unique!
+ projectId String
+ file File @relation(fields: [name], references: [name])
+ name String
+ Project Project[]
+ DashboardProject DashboardProject[]
@@id([id, projectId])
}
@@ -135,18 +137,20 @@ view UserProduct {
}
model Project {
- id String @id @default(uuid())
- createdAt DateTime @default(now())
- title String
- domain String @unique
- user User? @relation(fields: [userId], references: [id])
- userId String?
- build Build[]
- isDeleted Boolean @default(false)
- files File[]
- projectDomain ProjectDomain[]
- latestBuild LatestBuildPerProject?
- authorizationToken AuthorizationToken[]
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ title String
+ domain String @unique
+ user User? @relation(fields: [userId], references: [id])
+ userId String?
+ build Build[]
+ isDeleted Boolean @default(false)
+ files File[]
+ projectDomain ProjectDomain[]
+ latestBuild LatestBuildPerProject?
+ authorizationToken AuthorizationToken[]
+ previewImageAsset Asset? @relation(fields: [previewImageAssetId, id], references: [id, projectId])
+ previewImageAssetId String?
@@unique([id, isDeleted])
@@unique([domain, isDeleted])
@@ -298,11 +302,13 @@ view LatestBuildPerProject {
// Dashboard
view DashboardProject {
- id String @id @default(uuid())
- createdAt DateTime @default(now())
- title String
- domain String
- userId String?
- isDeleted Boolean @default(false)
- isPublished Boolean
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ title String
+ domain String
+ userId String?
+ previewImageAsset Asset? @relation(fields: [previewImageAssetId, id], references: [id, projectId])
+ previewImageAssetId String?
+ isDeleted Boolean @default(false)
+ isPublished Boolean
}
diff --git a/packages/project/src/db/project.ts b/packages/project/src/db/project.ts
index 7105538857..b3b749a259 100644
--- a/packages/project/src/db/project.ts
+++ b/packages/project/src/db/project.ts
@@ -30,6 +30,7 @@ export const loadById = async (
where: { id_isDeleted: { id: projectId, isDeleted: false } },
include: {
latestBuild: true,
+ previewImageAsset: true,
},
});
@@ -62,6 +63,7 @@ export const create = async (
userId,
title,
domain: generateDomain(title),
+ previewImageAssetId: "",
},
});
@@ -92,6 +94,19 @@ export const markAsDeleted = async (
});
};
+const assertEditPermission = async (projectId: string, context: AppContext) => {
+ const canEdit = await authorizeProject.hasProjectPermit(
+ { projectId, permit: "edit" },
+ context
+ );
+
+ if (canEdit === false) {
+ throw new Error(
+ "Only a token or user with edit permission can edit the project."
+ );
+ }
+};
+
export const rename = async (
{
projectId,
@@ -104,16 +119,7 @@ export const rename = async (
) => {
Title.parse(title);
- const canEdit = await authorizeProject.hasProjectPermit(
- { projectId, permit: "edit" },
- context
- );
-
- if (canEdit === false) {
- throw new Error(
- "Only a token or user with edit permission can edit the project."
- );
- }
+ await assertEditPermission(projectId, context);
return await prisma.project.update({
where: { id: projectId },
@@ -121,6 +127,24 @@ export const rename = async (
});
};
+export const updatePreviewImage = async (
+ {
+ projectId,
+ assetId,
+ }: {
+ projectId: Project["id"];
+ assetId: string | null;
+ },
+ context: AppContext
+) => {
+ await assertEditPermission(projectId, context);
+
+ return await prisma.project.update({
+ where: { id: projectId },
+ data: { previewImageAssetId: assetId },
+ });
+};
+
const clone = async (
{
project,
@@ -152,6 +176,7 @@ const clone = async (
userId: userId,
title: title ?? project.title,
domain: generateDomain(project.title),
+ previewImageAssetId: project.previewImageAsset?.id,
},
});
@@ -221,16 +246,7 @@ export const updateDomain = async (
const { domain } = domainValidation;
- const canEdit = await authorizeProject.hasProjectPermit(
- { projectId: input.id, permit: "edit" },
- context
- );
-
- if (canEdit === false) {
- throw new Error(
- "Only a token or user with edit permission can edit the project."
- );
- }
+ await assertEditPermission(input.id, context);
try {
const project = await prisma.project.update({
diff --git a/packages/project/src/shared/schema.ts b/packages/project/src/shared/schema.ts
index 04b52b1870..8a986583df 100644
--- a/packages/project/src/shared/schema.ts
+++ b/packages/project/src/shared/schema.ts
@@ -16,6 +16,12 @@ export const Project = z.object({
userId: z.string().nullable(),
isDeleted: z.boolean(),
domain: z.string(),
+ previewImageAsset: z
+ .object({
+ id: z.string(),
+ name: z.string(),
+ })
+ .nullable(),
latestBuild: z.optional(
z
.object({