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: add project tags in dashboard (#5399)

Bogdan Chadkin801181c8b69a
diff --git a/apps/builder/app/builder/features/pages/page-settings.stories.tsx b/apps/builder/app/builder/features/pages/page-settings.stories.tsx
index b354f13190..cd66290aec 100644
--- a/apps/builder/app/builder/features/pages/page-settings.stories.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings.stories.tsx
@@ -63,6 +63,7 @@ $project.set({
isDeleted: false,
userId: "userId",
domain: "new-2x9tcd",
+ tags: [],
marketplaceApprovalStatus: "UNLISTED",
diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
index 3e8b598bc7..a8f5ca2ac4 100644
--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
@@ -214,7 +214,7 @@ const InvalidCollectionDataStub = forwardRef<
<a
style={{ color: "inherit" }}
target="_blank"
- href="https://docs.webstudio.is/university/core-components/collection.md#whats-an-array"
+ href="https://docs.webstudio.is/university/core-components/collection#whats-an-array"
// avoid preventing click by events interceptor
onClickCapture={(event) => event.stopPropagation()}
>
diff --git a/apps/builder/app/dashboard/dashboard.stories.tsx b/apps/builder/app/dashboard/dashboard.stories.tsx
index e6c93a3809..6de8d838a6 100644
--- a/apps/builder/app/dashboard/dashboard.stories.tsx
+++ b/apps/builder/app/dashboard/dashboard.stories.tsx
@@ -18,6 +18,7 @@ const user = {
username: "Taylor",
teamId: null,
provider: "github",
+ projectsTags: [],
};
const createRouter = (element: JSX.Element, path: string, current?: string) =>
@@ -49,6 +50,7 @@ const projects = [
previewImageAssetId: "",
latestBuildVirtual: null,
marketplaceApprovalStatus: "UNLISTED" as const,
+ tags: [],
} as DashboardProject,
];
diff --git a/apps/builder/app/dashboard/dashboard.tsx b/apps/builder/app/dashboard/dashboard.tsx
index a96c6bbe52..28ab6aaffc 100644
--- a/apps/builder/app/dashboard/dashboard.tsx
+++ b/apps/builder/app/dashboard/dashboard.tsx
@@ -256,6 +256,7 @@ export const Dashboard = () => {
projects={projects}
hasProPlan={userPlanFeatures.hasProPlan}
publisherHost={publisherHost}
+ projectsTags={user.projectsTags}
/>
)}
{view === "templates" && <Templates projects={templates} />}
diff --git a/apps/builder/app/dashboard/projects/colors.ts b/apps/builder/app/dashboard/projects/colors.ts
new file mode 100644
index 0000000000..9b05f55fd9
--- /dev/null
+++ b/apps/builder/app/dashboard/projects/colors.ts
@@ -0,0 +1,6 @@
+export const colors = Array.from({ length: 50 }, (_, i) => {
+ const l = 55 + (i % 3) * 3; // Reduced variation in lightness (55-61%) to lower contrast
+ const c = 0.14 + (i % 2) * 0.02; // Reduced variation in chroma (0.14-0.16) for balance
+ const h = (i * 137.5) % 360; // Golden angle for pleasing hue distribution
+ return `oklch(${l}% ${c.toFixed(2)} ${h.toFixed(1)})`;
+});
diff --git a/apps/builder/app/dashboard/projects/project-card.tsx b/apps/builder/app/dashboard/projects/project-card.tsx
index 8318b44840..82d796cf9c 100644
--- a/apps/builder/app/dashboard/projects/project-card.tsx
+++ b/apps/builder/app/dashboard/projects/project-card.tsx
@@ -30,6 +30,8 @@ import {
} from "../shared/thumbnail";
import { Spinner } from "../shared/spinner";
import { Card, CardContent, CardFooter } from "../shared/card";
+import type { User } from "~/shared/db/user.server";
+import { TagsDialog } from "./tags";
const infoIconStyle = css({ flexShrink: 0 });
@@ -64,12 +66,14 @@ const Menu = ({
onRename,
onDuplicate,
onShare,
+ onUpdateTags,
}: {
tabIndex: number;
onDelete: () => void;
onRename: () => void;
onDuplicate: () => void;
onShare: () => void;
+ onUpdateTags: () => void;
}) => {
const [isOpen, setIsOpen] = useState(false);
return (
@@ -87,6 +91,7 @@ const Menu = ({
<DropdownMenuItem onSelect={onDuplicate}>Duplicate</DropdownMenuItem>
<DropdownMenuItem onSelect={onRename}>Rename</DropdownMenuItem>
<DropdownMenuItem onSelect={onShare}>Share</DropdownMenuItem>
+ <DropdownMenuItem onSelect={onUpdateTags}>Tags</DropdownMenuItem>
<DropdownMenuItem onSelect={onDelete}>Delete</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -105,6 +110,7 @@ type ProjectCardProps = {
project: DashboardProject;
hasProPlan: boolean;
publisherHost: string;
+ projectsTags: User["projectsTags"];
};
export const ProjectCard = ({
@@ -116,18 +122,30 @@ export const ProjectCard = ({
createdAt,
latestBuildVirtual,
previewImageAsset,
+ tags,
},
hasProPlan,
publisherHost,
+ projectsTags,
...props
}: ProjectCardProps) => {
const [isRenameDialogOpen, setIsRenameDialogOpen] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const [isShareDialogOpen, setIsShareDialogOpen] = useState(false);
+ const [isTagsDialogOpen, setIsTagsDialogOpen] = useState(false);
const [isHidden, setIsHidden] = useState(false);
const handleCloneProject = useCloneProject(id);
const [isTransitioning, setIsTransitioning] = useState(false);
+ // Makes sure there are no project tags that reference deleted User tags.
+ // We are not deleting project tag from project.tags when deleting User tags.
+ const projectTagsIds = (tags || [])
+ .map((tagId) => {
+ const tag = projectsTags.find((tag) => tag.id === tagId);
+ return tag ? tag.id : undefined;
+ })
+ .filter(Boolean) as string[];
+
useEffect(() => {
const linkPath = builderUrl({ origin: window.origin, projectId: id });
@@ -173,7 +191,33 @@ export const ProjectCard = ({
opacity: 0,
}}
/>
-
+ <Flex
+ wrap="wrap"
+ gap={1}
+ css={{
+ position: "absolute",
+ padding: theme.panel.padding,
+ bottom: 0,
+ zIndex: 1,
+ }}
+ >
+ {projectsTags.map((tag) => {
+ const isApplied = projectTagsIds.includes(tag.id);
+ if (isApplied) {
+ return (
+ <Text
+ color="contrast"
+ key={tag.id}
+ css={{
+ background: "oklch(0 0 0 / 0.3)",
+ borderRadius: theme.borderRadius[3],
+ paddingInline: theme.spacing[3],
+ }}
+ >{`#${tag.label}`}</Text>
+ );
+ }
+ })}
+ </Flex>
{previewImageAsset ? (
<ThumbnailLinkWithImage to={linkPath} name={previewImageAsset.name} />
) : (
@@ -225,16 +269,11 @@ export const ProjectCard = ({
</Flex>
<Menu
tabIndex={-1}
- onDelete={() => {
- setIsDeleteDialogOpen(true);
- }}
- onRename={() => {
- setIsRenameDialogOpen(true);
- }}
- onShare={() => {
- setIsShareDialogOpen(true);
- }}
+ onDelete={() => setIsDeleteDialogOpen(true)}
+ onRename={() => setIsRenameDialogOpen(true)}
+ onShare={() => setIsShareDialogOpen(true)}
onDuplicate={handleCloneProject}
+ onUpdateTags={() => setIsTagsDialogOpen(true)}
/>
</CardFooter>
<RenameProjectDialog
@@ -256,6 +295,13 @@ export const ProjectCard = ({
projectId={id}
hasProPlan={hasProPlan}
/>
+ <TagsDialog
+ projectId={id}
+ projectsTags={projectsTags}
+ projectTagsIds={projectTagsIds}
+ isOpen={isTagsDialogOpen}
+ onOpenChange={setIsTagsDialogOpen}
+ />
</Card>
);
};
diff --git a/apps/builder/app/dashboard/projects/projects.tsx b/apps/builder/app/dashboard/projects/projects.tsx
index 2f22cbf5ff..8325660836 100644
--- a/apps/builder/app/dashboard/projects/projects.tsx
+++ b/apps/builder/app/dashboard/projects/projects.tsx
@@ -1,4 +1,5 @@
import {
+ Box,
Flex,
Grid,
List,
@@ -11,11 +12,16 @@ import type { DashboardProject } from "@webstudio-is/dashboard";
import { ProjectCard } from "./project-card";
import { CreateProject } from "./project-dialogs";
import { Header, Main } from "../shared/layout";
+import { useSearchParams } from "react-router-dom";
+import { setIsSubsetOf } from "~/shared/shim";
+import type { User } from "~/shared/db/user.server";
+import { Tag } from "./tags";
export const ProjectsGrid = ({
projects,
hasProPlan,
publisherHost,
+ projectsTags,
}: ProjectsProps) => {
return (
<List asChild>
@@ -33,6 +39,7 @@ export const ProjectsGrid = ({
project={project}
hasProPlan={hasProPlan}
publisherHost={publisherHost}
+ projectsTags={projectsTags}
/>
</ListItem>
);
@@ -46,9 +53,19 @@ type ProjectsProps = {
projects: Array<DashboardProject>;
hasProPlan: boolean;
publisherHost: string;
+ projectsTags: User["projectsTags"];
};
export const Projects = (props: ProjectsProps) => {
+ const [searchParams] = useSearchParams();
+ const selectedTags = searchParams.getAll("tag");
+ let projects = props.projects;
+ if (selectedTags.length > 0) {
+ projects = projects.filter((project) =>
+ setIsSubsetOf(new Set(selectedTags), new Set(project.tags))
+ );
+ }
+
return (
<Main>
<Header variant="main">
@@ -60,12 +77,43 @@ export const Projects = (props: ProjectsProps) => {
</Flex>
</Header>
<Flex
- direction="column"
- gap="3"
- css={{ paddingInline: theme.spacing[13] }}
+ gap="2"
+ wrap="wrap"
+ css={{
+ display: "none",
+ flexShrink: 0,
+ paddingInline: theme.spacing[13],
+ paddingBlockStart: theme.spacing[2],
+ paddingBlockEnd: theme.spacing[10],
+ "&:has(*:first-child)": {
+ display: "flex",
+ },
+ }}
>
- <ProjectsGrid {...props} />
+ {props.projectsTags.map((tag, index) => {
+ return (
+ <Tag
+ tag={tag}
+ key={tag.id}
+ index={index}
+ state={selectedTags.includes(tag.id) ? "pressed" : "auto"}
+ >
+ {tag.label}
+ </Tag>
+ );
+ })}
</Flex>
+ <Box css={{ paddingInline: theme.spacing[13] }}>
+ {projects.length === 0 && (
+ <Text
+ variant="brandRegular"
+ css={{ padding: theme.spacing[13], textAlign: "center" }}
+ >
+ No projects found
+ </Text>
+ )}
+ <ProjectsGrid {...props} projects={projects} />
+ </Box>
</Main>
);
};
diff --git a/apps/builder/app/dashboard/projects/tags.tsx b/apps/builder/app/dashboard/projects/tags.tsx
new file mode 100644
index 0000000000..360ce8d362
--- /dev/null
+++ b/apps/builder/app/dashboard/projects/tags.tsx
@@ -0,0 +1,372 @@
+import { useRevalidator, useSearchParams } from "react-router-dom";
+import { useState, type ComponentProps } from "react";
+import {
+ Text,
+ theme,
+ Dialog,
+ DialogContent,
+ DialogTitle,
+ Button,
+ DialogActions,
+ DialogClose,
+ Checkbox,
+ CheckboxAndLabel,
+ Label,
+ InputField,
+ DialogTitleActions,
+ Grid,
+ List,
+ ListItem,
+ Flex,
+ DropdownMenu,
+ DropdownMenuTrigger,
+ SmallIconButton,
+ DropdownMenuContent,
+ DropdownMenuItem,
+} from "@webstudio-is/design-system";
+import { nativeClient } from "~/shared/trpc/trpc-client";
+import type { User } from "~/shared/db/user.server";
+import { nanoid } from "nanoid";
+import { EllipsesIcon, SpinnerIcon } from "@webstudio-is/icons";
+import { colors } from "./colors";
+
+type DeleteConfirmationDialogProps = {
+ onClose: () => void;
+ onConfirm: () => void;
+ question: string;
+};
+
+const DeleteConfirmationDialog = ({
+ onClose,
+ onConfirm,
+ question,
+}: DeleteConfirmationDialogProps) => {
+ return (
+ <Dialog
+ open
+ onOpenChange={(isOpen) => {
+ if (isOpen === false) {
+ onClose();
+ }
+ }}
+ >
+ <DialogContent>
+ <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>
+ <Text>{question}</Text>
+ <Flex direction="rowReverse" gap="2">
+ <DialogClose>
+ <Button
+ color="destructive"
+ onClick={() => {
+ onConfirm();
+ }}
+ >
+ Delete
+ </Button>
+ </DialogClose>
+ <DialogClose>
+ <Button color="ghost">Cancel</Button>
+ </DialogClose>
+ </Flex>
+ </Flex>
+ <DialogTitle>Delete confirmation</DialogTitle>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+const TagsList = ({
+ projectId,
+ projectsTags,
+ projectTagsIds,
+ onEdit,
+}: {
+ projectId: string;
+ projectsTags: User["projectsTags"];
+ projectTagsIds: string[];
+ onEdit: (tagId: string) => void;
+}) => {
+ const revalidator = useRevalidator();
+ const [deleteConfirmationTagId, setDeleteConfirmationTagId] =
+ useState<string>();
+
+ return (
+ <form
+ onChange={async (event) => {
+ event.preventDefault();
+ const formData = new FormData(event.currentTarget);
+ const tagsIds = formData.getAll("tagId") as string[];
+ await nativeClient.project.updateTags.mutate({
+ projectId,
+ tags: tagsIds,
+ });
+ revalidator.revalidate();
+ }}
+ >
+ <List asChild>
+ <Grid
+ gap={1}
+ css={{
+ paddingBlock: theme.panel.paddingBlock,
+ maxHeight: theme.spacing[30],
+ overflow: "auto",
+ }}
+ >
+ {projectsTags
+ .sort((a, b) => a.label.localeCompare(b.label))
+ .map((tag, index) => (
+ <ListItem asChild onSelect={() => {}} index={index} key={tag.id}>
+ <Flex
+ justify="between"
+ align="center"
+ gap="2"
+ css={{
+ paddingInline: theme.panel.paddingInline,
+ outlineColor: theme.colors.borderFocus,
+ outlineOffset: -2,
+ paddingBlock: theme.spacing[2],
+ }}
+ >
+ <CheckboxAndLabel
+ key={tag.id}
+ css={{ overflow: "hidden", flexGrow: 1 }}
+ >
+ <Checkbox
+ id={tag.id}
+ name="tagId"
+ value={tag.id}
+ tabIndex={-1}
+ defaultChecked={projectTagsIds.includes(tag.id)}
+ />
+ <Label truncate htmlFor={tag.id}>
+ {tag.label}
+ </Label>
+ </CheckboxAndLabel>
+ <DropdownMenu modal>
+ <DropdownMenuTrigger asChild>
+ {/* a11y is completely broken here
+ focus is not restored to button invoker
+ @todo fix it eventually and consider restoring from closed value preview dialog
+ */}
+ <SmallIconButton
+ tabIndex={-1}
+ aria-label="Open variable menu"
+ icon={<EllipsesIcon />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ css={{ width: theme.spacing[24] }}
+ onCloseAutoFocus={(event) => event.preventDefault()}
+ align="end"
+ >
+ <DropdownMenuItem
+ onSelect={() => {
+ onEdit(tag.id);
+ }}
+ >
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={() => {
+ setDeleteConfirmationTagId(tag.id);
+ }}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </Flex>
+ </ListItem>
+ ))}
+ {projectsTags.length === 0 && (
+ <Text align="center">No tags found</Text>
+ )}
+ {deleteConfirmationTagId && (
+ <DeleteConfirmationDialog
+ question="Are you sure you want to delete this tag? It will be removed from all projects."
+ onClose={() => setDeleteConfirmationTagId(undefined)}
+ onConfirm={async () => {
+ setDeleteConfirmationTagId(undefined);
+ const updatedTags = projectsTags.filter(
+ (tag) => tag.id !== deleteConfirmationTagId
+ );
+ await nativeClient.user.updateProjectsTags.mutate({
+ tags: updatedTags,
+ });
+ revalidator.revalidate();
+ }}
+ />
+ )}
+ </Grid>
+ </List>
+ </form>
+ );
+};
+
+const TagEdit = ({
+ projectsTags,
+ tag,
+ onComplete,
+}: {
+ projectsTags: User["projectsTags"];
+ tag: User["projectsTags"][number];
+ onComplete: () => void;
+}) => {
+ const revalidator = useRevalidator();
+ const isExisting = projectsTags.some(({ id }) => id === tag.id);
+
+ return (
+ <form
+ onSubmit={async (event) => {
+ event.preventDefault();
+ const formData = new FormData(event.currentTarget);
+ const label = ((formData.get("tag") as string) || "").trim();
+ if (tag.label === label || !label) {
+ return;
+ }
+ let updatedTags = [];
+ if (isExisting) {
+ updatedTags = projectsTags.map((availableTag) => {
+ if (availableTag.id === tag.id) {
+ return { ...availableTag, label };
+ }
+ return availableTag;
+ });
+ } else {
+ updatedTags = [...projectsTags, { id: tag.id, label }];
+ }
+
+ await nativeClient.user.updateProjectsTags.mutate({
+ tags: updatedTags,
+ });
+ revalidator.revalidate();
+ onComplete();
+ }}
+ >
+ <Grid css={{ padding: theme.panel.padding }}>
+ <InputField
+ autoFocus
+ defaultValue={tag.label}
+ name="tag"
+ placeholder="My tag"
+ minLength={1}
+ />
+ </Grid>
+ <DialogActions>
+ <Button type="submit">
+ {isExisting ? "Update tag" : "Create tag"}
+ </Button>
+ <Button
+ color="ghost"
+ type="button"
+ onClick={() => {
+ onComplete();
+ }}
+ >
+ Cancel
+ </Button>
+ </DialogActions>
+ </form>
+ );
+};
+
+export const TagsDialog = ({
+ projectId,
+ projectsTags,
+ projectTagsIds,
+ isOpen,
+ onOpenChange,
+}: {
+ projectId: string;
+ projectsTags: User["projectsTags"];
+ projectTagsIds: string[];
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+}) => {
+ const [editingTag, setEditingTag] = useState<
+ User["projectsTags"][number] | undefined
+ >();
+ const revalidator = useRevalidator();
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent aria-describedby={undefined}>
+ <DialogTitle
+ suffix={
+ <DialogTitleActions>
+ {revalidator.state === "loading" && <SpinnerIcon />}
+ <DialogClose />
+ </DialogTitleActions>
+ }
+ >
+ Project tags
+ </DialogTitle>
+ {!editingTag && (
+ <>
+ <TagsList
+ projectId={projectId}
+ projectsTags={projectsTags}
+ projectTagsIds={projectTagsIds}
+ onEdit={(tagId) => {
+ setEditingTag(projectsTags.find((tag) => tag.id === tagId));
+ }}
+ />
+ <DialogActions>
+ <Button
+ onClick={() => setEditingTag({ id: nanoid(5), label: "" })}
+ >
+ Create tag
+ </Button>
+ </DialogActions>
+ </>
+ )}
+ {editingTag && (
+ <TagEdit
+ projectsTags={projectsTags}
+ tag={editingTag}
+ onComplete={() => setEditingTag(undefined)}
+ />
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export const Tag = ({
+ index,
+ tag,
+ ...props
+}: { index: number; tag: User["projectsTags"][number] } & ComponentProps<
+ typeof Button
+>) => {
+ const [searchParams, setSearchParams] = useSearchParams();
+ const selectedTagsIds = searchParams.getAll("tag");
+ const color = colors[index] ?? theme.colors.backgroundNeutralDark;
+ return (
+ <Button
+ color="neutral"
+ css={{
+ "&:hover[data-state='auto'], &[data-state='pressed']": {
+ backgroundColor: color,
+ color: theme.colors.white,
+ },
+ "&[data-state='pressed']:hover": {
+ backgroundColor: `oklch(from ${color} l c h / 0.8)`,
+ },
+ }}
+ onClick={() => {
+ const newSearchParams = new URLSearchParams(searchParams);
+ newSearchParams.delete("tag");
+ if (!selectedTagsIds.includes(tag.id)) {
+ newSearchParams.append("tag", tag.id);
+ }
+ for (const item of selectedTagsIds) {
+ if (item !== tag.id) {
+ newSearchParams.append("tag", item);
+ }
+ }
+ setSearchParams(newSearchParams);
+ }}
+ {...props}
+ />
+ );
+};
diff --git a/apps/builder/app/dashboard/search/search-results.tsx b/apps/builder/app/dashboard/search/search-results.tsx
index f2a0761774..d1d5e500eb 100644
--- a/apps/builder/app/dashboard/search/search-results.tsx
+++ b/apps/builder/app/dashboard/search/search-results.tsx
@@ -63,6 +63,7 @@ export const SearchResults = (props: DashboardData) => {
projects={results.projects}
hasProPlan={userPlanFeatures.hasProPlan}
publisherHost={publisherHost}
+ projectsTags={props.user.projectsTags}
/>
</>
)}
diff --git a/apps/builder/app/dashboard/shared/card.tsx b/apps/builder/app/dashboard/shared/card.tsx
index 9986ccfa10..31a4401b82 100644
--- a/apps/builder/app/dashboard/shared/card.tsx
+++ b/apps/builder/app/dashboard/shared/card.tsx
@@ -14,6 +14,7 @@ const borderColorVar = "--ws-dashboard-card-border-color";
const cardStyle = css({
position: "relative",
+ isolation: "isolate",
display: "flex",
padding: 0,
height: "100%",
diff --git a/apps/builder/app/routes/_ui.(builder).tsx b/apps/builder/app/routes/_ui.(builder).tsx
index cfcd28ed6a..365d23f9be 100644
--- a/apps/builder/app/routes/_ui.(builder).tsx
+++ b/apps/builder/app/routes/_ui.(builder).tsx
@@ -13,7 +13,7 @@ import {
} from "@remix-run/server-runtime";
import { loadBuildIdAndVersionByProjectId } from "@webstudio-is/project-build/index.server";
-import { db } from "@webstudio-is/project/index.server";
+import * as projectApi from "@webstudio-is/project/index.server";
import { db as authDb } from "@webstudio-is/authorization-token/index.server";
import {
@@ -120,7 +120,7 @@ export const loader = async (loaderArgs: LoaderFunctionArgs) => {
}
const start = Date.now();
- const project = await db.project.loadById(projectId, context);
+ const project = await projectApi.loadById(projectId, context);
if (project === null) {
throw new Response(`Project "${projectId}" not found`, {
diff --git a/apps/builder/app/routes/_ui.dashboard.tsx b/apps/builder/app/routes/_ui.dashboard.tsx
index 0ded4d84df..00d973b8bb 100644
--- a/apps/builder/app/routes/_ui.dashboard.tsx
+++ b/apps/builder/app/routes/_ui.dashboard.tsx
@@ -13,7 +13,7 @@ import {
type AppContext,
} from "@webstudio-is/trpc-interface/index.server";
import { db as authDb } from "@webstudio-is/authorization-token/index.server";
-import { db } from "@webstudio-is/project/index.server";
+import * as projectApi from "@webstudio-is/project/index.server";
import { parseBuilderUrl } from "@webstudio-is/http-client";
import { dashboardProjectRouter } from "@webstudio-is/dashboard/index.server";
import { builderUrl, isDashboard, loginPath } from "~/shared/router-utils";
@@ -121,7 +121,7 @@ const getProjectToClone = async (request: Request, context: AppContext) => {
throw new AuthorizationError("You don't have access to clone this project");
}
- const project = await db.project.loadById(
+ const project = await projectApi.loadById(
token.projectId,
await context.createTokenContext(projectToCloneAuthToken)
);
diff --git a/apps/builder/app/routes/rest.build.$buildId.tsx b/apps/builder/app/routes/rest.build.$buildId.tsx
index afbb76a428..d419cec4e1 100644
--- a/apps/builder/app/routes/rest.build.$buildId.tsx
+++ b/apps/builder/app/routes/rest.build.$buildId.tsx
@@ -4,7 +4,7 @@ import {
type TypedResponse,
} from "@remix-run/server-runtime";
import type { Data } from "@webstudio-is/http-client";
-import { db as projectDb } from "@webstudio-is/project/index.server";
+import * as projectApi from "@webstudio-is/project/index.server";
import { loadProductionCanvasData } from "~/shared/db";
import { createContext } from "~/shared/context.server";
import { getUserById, type User } from "~/shared/db/user.server";
@@ -46,7 +46,7 @@ export const loader = async ({
const pagesCanvasData = await loadProductionCanvasData(buildId, context);
- const project = await projectDb.project.loadById(
+ const project = await projectApi.loadById(
pagesCanvasData.build.projectId,
context
);
diff --git a/apps/builder/app/routes/rest.buildId.$projectId.tsx b/apps/builder/app/routes/rest.buildId.$projectId.tsx
index a6d43b6efe..30b012826e 100644
--- a/apps/builder/app/routes/rest.buildId.$projectId.tsx
+++ b/apps/builder/app/routes/rest.buildId.$projectId.tsx
@@ -3,7 +3,7 @@ import {
type LoaderFunctionArgs,
type TypedResponse,
} from "@remix-run/server-runtime";
-import { db as projectDb } from "@webstudio-is/project/index.server";
+import * as projectApi from "@webstudio-is/project/index.server";
import { allowedDestinations } from "~/services/destinations.server";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
import { createContext } from "~/shared/context.server";
@@ -40,7 +40,7 @@ export const loader = async ({
// @todo Create a context without user authentication information.
const context = await createContext(request);
- const project = await projectDb.project.loadById(projectId, context);
+ const project = await projectApi.loadById(projectId, context);
const buildId = project.latestBuildVirtual?.buildId ?? null;
return {
diff --git a/apps/builder/app/routes/rest.data.$projectId.ts b/apps/builder/app/routes/rest.data.$projectId.ts
index cc90ec0a82..a0ce881bb9 100644
--- a/apps/builder/app/routes/rest.data.$projectId.ts
+++ b/apps/builder/app/routes/rest.data.$projectId.ts
@@ -1,5 +1,5 @@
import type { LoaderFunctionArgs } from "@remix-run/server-runtime";
-import { db } from "@webstudio-is/project/index.server";
+import * as projectApi from "@webstudio-is/project/index.server";
import { loadDevBuildByProjectId } from "@webstudio-is/project-build/index.server";
import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";
import { createContext } from "~/shared/context.server";
@@ -16,7 +16,7 @@ export const loader = async ({ params, request }: LoaderFunctionArgs) => {
throw new Error("Project id undefined");
}
const context = await createContext(request);
- const project = await db.project.loadById(params.projectId, context);
+ const project = await projectApi.loadById(params.projectId, context);
if (project === null) {
throw new Error(`Project "${params.projectId}" not found`);
}
diff --git a/apps/builder/app/routes/rest.patch.ts b/apps/builder/app/routes/rest.patch.ts
index 162ca34c4b..ba4765a4c3 100644
--- a/apps/builder/app/routes/rest.patch.ts
+++ b/apps/builder/app/routes/rest.patch.ts
@@ -43,7 +43,7 @@ import {
authorizeProject,
} from "@webstudio-is/trpc-interface/index.server";
import { createContext } from "~/shared/context.server";
-import { db } from "@webstudio-is/project/index.server";
+import * as projectApi from "@webstudio-is/project/index.server";
import type { Database } from "@webstudio-is/postrest/index.server";
import { publicStaticEnv } from "~/env/env.static";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
@@ -421,7 +421,7 @@ export const action = async ({
}
if (previewImageAssetId !== undefined) {
- await db.project.updatePreviewImage(
+ await projectApi.updatePreviewImage(
{ assetId: previewImageAssetId, projectId },
context
);
diff --git a/apps/builder/app/services/trcp-router.server.ts b/apps/builder/app/services/trcp-router.server.ts
index f40b874159..177b386ecf 100644
--- a/apps/builder/app/services/trcp-router.server.ts
+++ b/apps/builder/app/services/trcp-router.server.ts
@@ -3,10 +3,12 @@ import { domainRouter } from "@webstudio-is/domain/index.server";
import { projectRouter } from "@webstudio-is/project/index.server";
import { authorizationTokenRouter } from "@webstudio-is/authorization-token/index.server";
import { dashboardProjectRouter } from "@webstudio-is/dashboard/index.server";
-import { marketplaceRouter } from "../shared/marketplace/router.server";
+import { marketplaceRouter } from "~/shared/marketplace/router.server";
+import { userRouter } from "./user-router.server";
import { logoutRouter } from "./logout-router.server";
export const appRouter = router({
+ user: userRouter,
marketplace: marketplaceRouter,
domain: domainRouter,
project: projectRouter,
diff --git a/apps/builder/app/services/user-router.server.ts b/apps/builder/app/services/user-router.server.ts
new file mode 100644
index 0000000000..2fca6e99c2
--- /dev/null
+++ b/apps/builder/app/services/user-router.server.ts
@@ -0,0 +1,14 @@
+import { z } from "zod";
+import { procedure, router } from "@webstudio-is/trpc-interface/index.server";
+import {
+ updateUserProjectsTags,
+ userProjectTagSchema,
+} from "../shared/db/user.server";
+
+export const userRouter = router({
+ updateProjectsTags: procedure
+ .input(z.object({ tags: z.array(userProjectTagSchema) }))
+ .mutation(async ({ input, ctx }) => {
+ return await updateUserProjectsTags(input, ctx);
+ }),
+});
diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx
index e62d7a6f9a..c481af2a9d 100644
--- a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx
+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx
@@ -105,6 +105,7 @@ beforeEach(() => {
domainsVirtual: [],
latestBuildVirtual: null,
previewImageAssetId: null,
+ tags: [],
});
$breakpoints.set(
diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.ts
index 8345c1563c..b6e6165314 100644
--- a/apps/builder/app/shared/db/canvas.server.ts
+++ b/apps/builder/app/shared/db/canvas.server.ts
@@ -3,7 +3,7 @@ import { loadBuildById } from "@webstudio-is/project-build/index.server";
import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import { findPageByIdOrPath, getStyleDeclKey } from "@webstudio-is/sdk";
-import { db as projectDb } from "@webstudio-is/project/index.server";
+import * as projectApi from "@webstudio-is/project/index.server";
const getPair = <Item extends { id: string }>(item: Item): [string, Item] => [
item.id,
@@ -26,7 +26,7 @@ export const loadProductionCanvasData = async (
throw new Error("The project is not published");
}
- const project = await projectDb.project.loadById(build.projectId, context);
+ const project = await projectApi.loadById(build.projectId, context);
const currentProjectDomains = project.domainsVirtual;
diff --git a/apps/builder/app/shared/db/user.server.ts b/apps/builder/app/shared/db/user.server.ts
index fb74d02d07..e25cc79ede 100644
--- a/apps/builder/app/shared/db/user.server.ts
+++ b/apps/builder/app/shared/db/user.server.ts
@@ -1,9 +1,25 @@
import type { Database } from "@webstudio-is/postrest/index.server";
-import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import {
+ AuthorizationError,
+ type AppContext,
+} from "@webstudio-is/trpc-interface/index.server";
import type { GitHubProfile } from "remix-auth-github";
import type { GoogleProfile } from "remix-auth-google";
+import { z } from "zod";
-export type User = Database["public"]["Tables"]["User"]["Row"];
+export type User = Omit<
+ Database["public"]["Tables"]["User"]["Row"],
+ "projectsTags"
+> & {
+ projectsTags: Array<ProjectTag>;
+};
+
+const formatUser = (user: Database["public"]["Tables"]["User"]["Row"]) => {
+ return {
+ ...user,
+ projectsTags: (user.projectsTags || []) as User["projectsTags"],
+ };
+};
export const getUserById = async (context: AppContext, id: User["id"]) => {
const dbUser = await context.postgrest.client
@@ -17,7 +33,7 @@ export const getUserById = async (context: AppContext, id: User["id"]) => {
throw new Error("User not found");
}
- return dbUser.data;
+ return formatUser(dbUser.data);
};
const genericCreateAccount = async (
@@ -36,7 +52,7 @@ const genericCreateAccount = async (
.single();
if (dbUser.error == null) {
- return dbUser.data;
+ return formatUser(dbUser.data);
}
// https://github.com/PostgREST/postgrest/blob/bfbd033c6e9f38cfbc8b1cfe19ee009a9379e3dd/docs/references/errors.rst#L234
@@ -59,7 +75,7 @@ const genericCreateAccount = async (
throw new Error("Failed to create user");
}
- return newUser.data;
+ return formatUser(newUser.data);
};
export const createOrLoginWithOAuth = async (
@@ -90,3 +106,32 @@ export const createOrLoginWithDev = async (
const newUser = await genericCreateAccount(context, userData);
return newUser;
};
+
+export const userProjectTagSchema = z.object({
+ id: z.string(),
+ label: z.string().min(1).max(100),
+});
+
+export type ProjectTag = z.infer<typeof userProjectTagSchema>;
+
+export const updateUserProjectsTags = async (
+ { tags }: { tags: ProjectTag[] },
+ context: AppContext
+) => {
+ if (context.authorization.type !== "user") {
+ throw new AuthorizationError(
+ "Only logged in users can update project tags"
+ );
+ }
+ const result = await context.postgrest.client
+ .from("User")
+ .update({ projectsTags: tags })
+ .eq("id", context.authorization.userId)
+ .select()
+ .single();
+
+ if (result.error) {
+ throw result.error;
+ }
+ return result.data.projectsTags as ProjectTag[];
+};
diff --git a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
index 850db6a72a..69b30748c6 100644
--- a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/react-router-cloudflare/app/routes/_index.tsx b/fixtures/react-router-cloudflare/app/routes/_index.tsx
index a0f0da7ba6..386b9b584c 100644
--- a/fixtures/react-router-cloudflare/app/routes/_index.tsx
+++ b/fixtures/react-router-cloudflare/app/routes/_index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
index 850db6a72a..69b30748c6 100644
--- a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/react-router-docker/app/routes/_index.tsx b/fixtures/react-router-docker/app/routes/_index.tsx
index a0f0da7ba6..386b9b584c 100644
--- a/fixtures/react-router-docker/app/routes/_index.tsx
+++ b/fixtures/react-router-docker/app/routes/_index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
index 850db6a72a..69b30748c6 100644
--- a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/react-router-netlify/app/routes/_index.tsx b/fixtures/react-router-netlify/app/routes/_index.tsx
index a0f0da7ba6..386b9b584c 100644
--- a/fixtures/react-router-netlify/app/routes/_index.tsx
+++ b/fixtures/react-router-netlify/app/routes/_index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
index 850db6a72a..69b30748c6 100644
--- a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/react-router-vercel/app/routes/_index.tsx b/fixtures/react-router-vercel/app/routes/_index.tsx
index a0f0da7ba6..386b9b584c 100644
--- a/fixtures/react-router-vercel/app/routes/_index.tsx
+++ b/fixtures/react-router-vercel/app/routes/_index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts b/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts
index 57293c637e..4afdd988d3 100644
--- a/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts
+++ b/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts
@@ -1,11 +1,37 @@
import type { PageContextServer } from "vike/types";
import { redirect } from "vike/abort";
-import { loadResources } from "@webstudio-is/sdk/runtime";
+import { isLocalResource, loadResources } from "@webstudio-is/sdk/runtime";
import {
getPageMeta,
getResources,
} from "../../app/__generated__/_index.server";
+const customFetch: typeof fetch = (input, init) => {
+ if (typeof input !== "string") {
+ return fetch(input, init);
+ }
+
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
+ return fetch(input, init);
+};
+
export const data = async (pageContext: PageContextServer) => {
const url = new URL(pageContext.urlOriginal, "http://url");
const headers = new Headers(pageContext.headers ?? {});
@@ -21,7 +47,10 @@ export const data = async (pageContext: PageContextServer) => {
pathname: url.pathname,
};
- const resources = await loadResources(fetch, getResources({ system }).data);
+ const resources = await loadResources(
+ customFetch,
+ getResources({ system }).data
+ );
const pageMeta = getPageMeta({ system, resources });
if (pageMeta.redirect) {
diff --git a/fixtures/ssg/pages/another-page/+data.ts b/fixtures/ssg/pages/another-page/+data.ts
index 3b424fa264..482b02a31b 100644
--- a/fixtures/ssg/pages/another-page/+data.ts
+++ b/fixtures/ssg/pages/another-page/+data.ts
@@ -1,11 +1,37 @@
import type { PageContextServer } from "vike/types";
import { redirect } from "vike/abort";
-import { loadResources } from "@webstudio-is/sdk/runtime";
+import { isLocalResource, loadResources } from "@webstudio-is/sdk/runtime";
import {
getPageMeta,
getResources,
} from "../../app/__generated__/[another-page]._index.server";
+const customFetch: typeof fetch = (input, init) => {
+ if (typeof input !== "string") {
+ return fetch(input, init);
+ }
+
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
+ return fetch(input, init);
+};
+
export const data = async (pageContext: PageContextServer) => {
const url = new URL(pageContext.urlOriginal, "http://url");
const headers = new Headers(pageContext.headers ?? {});
@@ -21,7 +47,10 @@ export const data = async (pageContext: PageContextServer) => {
pathname: url.pathname,
};
- const resources = await loadResources(fetch, getResources({ system }).data);
+ const resources = await loadResources(
+ customFetch,
+ getResources({ system }).data
+ );
const pageMeta = getPageMeta({ system, resources });
if (pageMeta.redirect) {
diff --git a/fixtures/ssg/pages/index/+data.ts b/fixtures/ssg/pages/index/+data.ts
index 57293c637e..4afdd988d3 100644
--- a/fixtures/ssg/pages/index/+data.ts
+++ b/fixtures/ssg/pages/index/+data.ts
@@ -1,11 +1,37 @@
import type { PageContextServer } from "vike/types";
import { redirect } from "vike/abort";
-import { loadResources } from "@webstudio-is/sdk/runtime";
+import { isLocalResource, loadResources } from "@webstudio-is/sdk/runtime";
import {
getPageMeta,
getResources,
} from "../../app/__generated__/_index.server";
+const customFetch: typeof fetch = (input, init) => {
+ if (typeof input !== "string") {
+ return fetch(input, init);
+ }
+
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
+ return fetch(input, init);
+};
+
export const data = async (pageContext: PageContextServer) => {
const url = new URL(pageContext.urlOriginal, "http://url");
const headers = new Headers(pageContext.headers ?? {});
@@ -21,7 +47,10 @@ export const data = async (pageContext: PageContextServer) => {
pathname: url.pathname,
};
- const resources = await loadResources(fetch, getResources({ system }).data);
+ const resources = await loadResources(
+ customFetch,
+ getResources({ system }).data
+ );
const pageMeta = getPageMeta({ system, resources });
if (pageMeta.redirect) {
diff --git a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx
index b2559fed1d..76a3d8b7b1 100644
--- a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx
@@ -54,6 +54,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
index 9993c144f1..e6b4fd8a9b 100644
--- a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
@@ -54,6 +54,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
index a128a99cb1..e2fd5fd585 100644
--- a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[animations]._index.tsx b/fixtures/webstudio-features/app/routes/[animations]._index.tsx
index 59d4dcd8b5..012dd6b682 100644
--- a/fixtures/webstudio-features/app/routes/[animations]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[animations]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
index c870d7b2fe..d848e9b17d 100644
--- a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
index 143d660b39..2818d10680 100644
--- a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[duration]._index.tsx b/fixtures/webstudio-features/app/routes/[duration]._index.tsx
index e6305aa6f3..b6cde3979c 100644
--- a/fixtures/webstudio-features/app/routes/[duration]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[duration]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
index 33df4e59e2..a1a6e50f47 100644
--- a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[form]._index.tsx b/fixtures/webstudio-features/app/routes/[form]._index.tsx
index ca398fb216..51260d77c9 100644
--- a/fixtures/webstudio-features/app/routes/[form]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[form]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
index ef659d7fa2..3b7de02fa0 100644
--- a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
index 100a05c4d4..ea3af3468f 100644
--- a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
index 1c26997475..2d5fc593dc 100644
--- a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[radix]._index.tsx b/fixtures/webstudio-features/app/routes/[radix]._index.tsx
index ab9d807901..f6345b1de4 100644
--- a/fixtures/webstudio-features/app/routes/[radix]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[radix]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[resources]._index.tsx b/fixtures/webstudio-features/app/routes/[resources]._index.tsx
index 9442e39b91..6186419d6c 100644
--- a/fixtures/webstudio-features/app/routes/[resources]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[resources]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx b/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx
index f79dd39e93..f2df2340d3 100644
--- a/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx
@@ -26,6 +26,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return fetch(input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
index ad38da0eac..3555f5eb4b 100644
--- a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/fixtures/webstudio-features/app/routes/_index.tsx b/fixtures/webstudio-features/app/routes/_index.tsx
index a0f0da7ba6..386b9b584c 100644
--- a/fixtures/webstudio-features/app/routes/_index.tsx
+++ b/fixtures/webstudio-features/app/routes/_index.tsx
@@ -53,6 +53,24 @@ const customFetch: typeof fetch = (input, init) => {
return Promise.resolve(response);
}
+ if (isLocalResource(input, "current-date")) {
+ const now = new Date();
+ // Normalize to midnight UTC to prevent hydration mismatches
+ const startOfDay = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ const data = {
+ iso: startOfDay.toISOString(),
+ year: startOfDay.getUTCFullYear(),
+ month: startOfDay.getUTCMonth() + 1, // 1-12 instead of 0-11
+ day: startOfDay.getUTCDate(),
+ timestamp: startOfDay.getTime(),
+ };
+ const response = new Response(JSON.stringify(data));
+ response.headers.set("content-type", "application/json; charset=utf-8");
+ return Promise.resolve(response);
+ }
+
return cachedFetch(projectId, input, init);
};
diff --git a/packages/design-system/src/components/dialog.tsx b/packages/design-system/src/components/dialog.tsx
index 0231fb1bfa..fca4a6c26b 100644
--- a/packages/design-system/src/components/dialog.tsx
+++ b/packages/design-system/src/components/dialog.tsx
@@ -420,7 +420,11 @@ export const DialogTitle = ({
};
export const DialogTitleActions = ({ children }: { children: ReactNode }) => {
- return <Flex gap="1">{children}</Flex>;
+ return (
+ <Flex gap="1" align="center">
+ {children}
+ </Flex>
+ );
};
export const DialogActions = ({ children }: { children: ReactNode }) => {
diff --git a/packages/domain/src/db/domain.ts b/packages/domain/src/db/domain.ts
index 76cae0e073..c59f5a67f2 100644
--- a/packages/domain/src/db/domain.ts
+++ b/packages/domain/src/db/domain.ts
@@ -3,7 +3,7 @@ import {
type AppContext,
AuthorizationError,
} from "@webstudio-is/trpc-interface/index.server";
-import { db as projectDb } from "@webstudio-is/project/index.server";
+import * as projectApi from "@webstudio-is/project/index.server";
import { validateDomain } from "./validate";
import { cnameFromUserId } from "./cname-from-user-id";
import type { Project } from "@webstudio-is/project";
@@ -35,7 +35,7 @@ export const create = async (
);
}
- const project = await projectDb.project.loadById(props.projectId, context);
+ const project = await projectApi.loadById(props.projectId, context);
const { userId: ownerId } = project;
diff --git a/packages/domain/src/trpc/domain.ts b/packages/domain/src/trpc/domain.ts
index 2b140ea1d9..2d1f59068c 100644
--- a/packages/domain/src/trpc/domain.ts
+++ b/packages/domain/src/trpc/domain.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
import { nanoid } from "nanoid";
-import { db as projectDb } from "@webstudio-is/project/index.server";
+import * as projectApi from "@webstudio-is/project/index.server";
import { createProductionBuild } from "@webstudio-is/project-build/index.server";
import { router, procedure } from "@webstudio-is/trpc-interface/index.server";
import { Templates } from "@webstudio-is/sdk";
@@ -41,7 +41,7 @@ export const domainRouter = router({
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
try {
- const project = await projectDb.project.loadById(input.projectId, ctx);
+ const project = await projectApi.loadById(input.projectId, ctx);
return {
success: true,
@@ -71,7 +71,7 @@ export const domainRouter = router({
)
.mutation(async ({ input, ctx }) => {
try {
- const project = await projectDb.project.loadById(input.projectId, ctx);
+ const project = await projectApi.loadById(input.projectId, ctx);
const name = `${project.id}-${nanoid()}.zip`;
@@ -169,7 +169,7 @@ export const domainRouter = router({
)
.mutation(async ({ input, ctx }) => {
try {
- await projectDb.project.updateDomain(
+ await projectApi.updateDomain(
{
id: input.projectId,
domain: input.domain,
diff --git a/packages/postgrest/package.json b/packages/postgrest/package.json
index 629d224e61..1e5813755d 100644
--- a/packages/postgrest/package.json
+++ b/packages/postgrest/package.json
@@ -16,7 +16,7 @@
"sideEffects": false,
"scripts": {
"typecheck": "tsc",
- "generate-types": "pnpx supabase gen types --lang=typescript --db-url postgresql://postgres:pass@localhost/webstudio > ./src/__generated__/db-types.ts",
+ "generate-types": "pnpx supabase gen types --lang=typescript --db-url postgresql://postgres:pass@localhost/webstudio > ./src/__generated__/db-types.ts && prettier --write ./src/__generated__/db-types.ts",
"playground": "pnpm tsx --env-file ../../apps/builder/.env",
"db-test": "docker run --rm --network host -v ./supabase/tests:/tests -e PGOPTIONS='--search_path=pgtap,public' supabase/pg_prove:3.36 pg_prove -d ${DIRECT_URL:-postgresql://postgres:pass@localhost/webstudio} --ext .sql /tests"
},
diff --git a/packages/postgrest/src/__generated__/db-types.ts b/packages/postgrest/src/__generated__/db-types.ts
index 24f69967cc..2db3243fc9 100644
--- a/packages/postgrest/src/__generated__/db-types.ts
+++ b/packages/postgrest/src/__generated__/db-types.ts
@@ -516,6 +516,7 @@ export type Database = {
isDeleted: boolean;
marketplaceApprovalStatus: Database["public"]["Enums"]["MarketplaceApprovalStatus"];
previewImageAssetId: string | null;
+ tags: string[] | null;
title: string;
userId: string | null;
};
@@ -526,6 +527,7 @@ export type Database = {
isDeleted?: boolean;
marketplaceApprovalStatus?: Database["public"]["Enums"]["MarketplaceApprovalStatus"];
previewImageAssetId?: string | null;
+ tags?: string[] | null;
title: string;
userId?: string | null;
};
@@ -536,6 +538,7 @@ export type Database = {
isDeleted?: boolean;
marketplaceApprovalStatus?: Database["public"]["Enums"]["MarketplaceApprovalStatus"];
previewImageAssetId?: string | null;
+ tags?: string[] | null;
title?: string;
userId?: string | null;
};
@@ -680,6 +683,7 @@ export type Database = {
email: string | null;
id: string;
image: string | null;
+ projectsTags: Json;
provider: string | null;
teamId: string | null;
username: string | null;
@@ -689,6 +693,7 @@ export type Database = {
email?: string | null;
id: string;
image?: string | null;
+ projectsTags?: Json;
provider?: string | null;
teamId?: string | null;
username?: string | null;
@@ -698,6 +703,7 @@ export type Database = {
email?: string | null;
id?: string;
image?: string | null;
+ projectsTags?: Json;
provider?: string | null;
teamId?: string | null;
username?: string | null;
@@ -748,6 +754,7 @@ export type Database = {
| Database["public"]["Enums"]["MarketplaceApprovalStatus"]
| null;
previewImageAssetId: string | null;
+ tags: string[] | null;
title: string | null;
userId: string | null;
};
@@ -761,6 +768,7 @@ export type Database = {
| Database["public"]["Enums"]["MarketplaceApprovalStatus"]
| null;
previewImageAssetId?: string | null;
+ tags?: string[] | null;
title?: string | null;
userId?: string | null;
};
@@ -774,6 +782,7 @@ export type Database = {
| Database["public"]["Enums"]["MarketplaceApprovalStatus"]
| null;
previewImageAssetId?: string | null;
+ tags?: string[] | null;
title?: string | null;
userId?: string | null;
};
@@ -895,9 +904,16 @@ export type Database = {
isDeleted: boolean;
marketplaceApprovalStatus: Database["public"]["Enums"]["MarketplaceApprovalStatus"];
previewImageAssetId: string | null;
+ tags: string[] | null;
title: string;
userId: string | null;
};
+ SetofOptions: {
+ from: "*";
+ to: "Project";
+ isOneToOne: true;
+ isSetofReturn: false;
+ };
};
create_production_build: {
Args: { deployment: string; project_id: string };
@@ -923,20 +939,48 @@ export type Database = {
updatedAt: string;
verified: boolean;
}[];
+ SetofOptions: {
+ from: '"Project"';
+ to: "domainsVirtual";
+ isOneToOne: false;
+ isSetofReturn: true;
+ };
};
- latestBuildVirtual: {
- Args:
- | { "": Database["public"]["Tables"]["Project"]["Row"] }
- | { "": Database["public"]["Tables"]["domainsVirtual"]["Row"] };
- Returns: {
- buildId: string;
- createdAt: string;
- domain: string;
- domainsVirtualId: string;
- projectId: string;
- publishStatus: Database["public"]["Enums"]["PublishStatus"];
- }[];
- };
+ latestBuildVirtual:
+ | {
+ Args: { "": Database["public"]["Tables"]["Project"]["Row"] };
+ Returns: {
+ buildId: string;
+ createdAt: string;
+ domain: string;
+ domainsVirtualId: string;
+ projectId: string;
+ publishStatus: Database["public"]["Enums"]["PublishStatus"];
+ };
+ SetofOptions: {
+ from: '"Project"';
+ to: "latestBuildVirtual";
+ isOneToOne: true;
+ isSetofReturn: true;
+ };
+ }
+ | {
+ Args: { "": Database["public"]["Tables"]["domainsVirtual"]["Row"] };
+ Returns: {
+ buildId: string;
+ createdAt: string;
+ domain: string;
+ domainsVirtualId: string;
+ projectId: string;
+ publishStatus: Database["public"]["Enums"]["PublishStatus"];
+ };
+ SetofOptions: {
+ from: '"domainsVirtual"';
+ to: "latestBuildVirtual";
+ isOneToOne: true;
+ isSetofReturn: true;
+ };
+ };
latestProjectDomainBuildVirtual: {
Args: { "": Database["public"]["Tables"]["Project"]["Row"] };
Returns: {
@@ -946,7 +990,13 @@ export type Database = {
domainsVirtualId: string;
projectId: string;
publishStatus: Database["public"]["Enums"]["PublishStatus"];
- }[];
+ };
+ SetofOptions: {
+ from: '"Project"';
+ to: "latestBuildVirtual";
+ isOneToOne: true;
+ isSetofReturn: true;
+ };
};
restore_development_build: {
Args: { from_build_id: string; project_id: string };
diff --git a/packages/prisma-client/prisma/migrations/20250913204036_project_tags/migration.sql b/packages/prisma-client/prisma/migrations/20250913204036_project_tags/migration.sql
new file mode 100644
index 0000000000..ade7798e53
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20250913204036_project_tags/migration.sql
@@ -0,0 +1,36 @@
+ALTER TABLE
+ "Project"
+ADD
+ COLUMN IF NOT EXISTS "tags" TEXT [];
+
+ALTER TABLE
+ "User"
+ADD
+ COLUMN IF NOT EXISTS "projectsTags" JSONB NOT NULL DEFAULT '[]';
+
+DROP VIEW IF EXISTS "DashboardProject";
+
+CREATE VIEW "DashboardProject" AS
+SELECT
+ id,
+ title,
+ tags,
+ domain,
+ "userId",
+ "isDeleted",
+ "createdAt",
+ "previewImageAssetId",
+ "marketplaceApprovalStatus",
+ (
+ 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 0748f0c784..a8b6eb9bbe 100644
--- a/packages/prisma-client/prisma/schema.prisma
+++ b/packages/prisma-client/prisma/schema.prisma
@@ -66,6 +66,7 @@ model User {
team Team? @relation(fields: [teamId], references: [id])
teamId String?
projects Project[]
+ projectsTags Json @default("[]")
clientReferences ClientReferences[]
checkout TransactionLog[]
products UserProduct[]
@@ -144,6 +145,8 @@ model Project {
id String @id @default(uuid())
createdAt DateTime @default(now()) @db.Timestamptz(3)
title String
+ // Tag ids used in User.projectTags
+ tags String[]
domain String @unique
user User? @relation(fields: [userId], references: [id])
userId String?
diff --git a/packages/project/src/db/index.ts b/packages/project/src/db/index.ts
deleted file mode 100644
index fd0f04972d..0000000000
--- a/packages/project/src/db/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-import * as project from "./project";
-export { project };
diff --git a/packages/project/src/db/project.ts b/packages/project/src/db/project.ts
index 70ef6bebf8..1bd7333842 100644
--- a/packages/project/src/db/project.ts
+++ b/packages/project/src/db/project.ts
@@ -310,3 +310,20 @@ export const setMarketplaceApprovalStatus = async (
}
return updatedProject.data;
};
+
+export const updateProjectTags = async (
+ { projectId, tags }: { projectId: Project["id"]; tags: string[] },
+ context: AppContext
+) => {
+ await assertEditPermission(projectId, context);
+ const updatedProject = await context.postgrest.client
+ .from("Project")
+ .update({ tags })
+ .eq("id", projectId)
+ .select()
+ .single();
+ if (updatedProject.error) {
+ throw updatedProject.error;
+ }
+ return updatedProject.data;
+};
diff --git a/packages/project/src/index.server.ts b/packages/project/src/index.server.ts
index 8dca4d08ed..ca744393c1 100644
--- a/packages/project/src/index.server.ts
+++ b/packages/project/src/index.server.ts
@@ -1,3 +1,2 @@
-import * as dbFunctions from "./db";
-export const db = dbFunctions;
-export * from "./trpc";
+export * from "./db/project";
+export * from "./trpc/project-router";
diff --git a/packages/project/src/index.ts b/packages/project/src/index.ts
index c924fefcdc..55da3b9106 100644
--- a/packages/project/src/index.ts
+++ b/packages/project/src/index.ts
@@ -1,4 +1,4 @@
export * from "./shared/schema";
export type { Project } from "./db/project";
-export type { ProjectRouter } from "./trpc";
+export type { ProjectRouter } from "./trpc/project-router";
export { validateProjectDomain } from "./db/project-domain";
diff --git a/packages/project/src/trpc/index.ts b/packages/project/src/trpc/index.ts
deleted file mode 100644
index 1f54bc1362..0000000000
--- a/packages/project/src/trpc/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./project-router";
diff --git a/packages/project/src/trpc/project-router.ts b/packages/project/src/trpc/project-router.ts
index d1ffead21b..ae373890a1 100644
--- a/packages/project/src/trpc/project-router.ts
+++ b/packages/project/src/trpc/project-router.ts
@@ -1,4 +1,4 @@
-import * as db from "../db";
+import * as projectApi from "../db/project";
import { z } from "zod";
import {
router,
@@ -18,14 +18,16 @@ export const projectRouter = router({
)
.mutation(async ({ input, ctx }) => {
// @todo pass ctx for authorization
- return await db.project.rename(input, ctx);
+ return await projectApi.rename(input, ctx);
}),
+
delete: procedure
.input(z.object({ projectId: z.string() }))
.mutation(async ({ input, ctx }) => {
// @todo pass ctx for authorization
- return await db.project.markAsDeleted(input.projectId, ctx);
+ return await projectApi.markAsDeleted(input.projectId, ctx);
}),
+
clone: procedure
.input(
z.object({
@@ -38,14 +40,15 @@ export const projectRouter = router({
const sourceContext = input.authToken
? await ctx.createTokenContext(input.authToken)
: ctx;
-
- return await db.project.clone(input, ctx, sourceContext);
+ return await projectApi.clone(input, ctx, sourceContext);
}),
+
create: procedure
.input(z.object({ title: Title }))
.mutation(async ({ input, ctx }) => {
- return await db.project.create(input, ctx);
+ return await projectApi.create(input, ctx);
}),
+
setMarketplaceApprovalStatus: procedure
.input(
z.object({
@@ -54,18 +57,28 @@ export const projectRouter = router({
})
)
.mutation(async ({ input, ctx }) => {
- return await db.project.setMarketplaceApprovalStatus(input, ctx);
+ return await projectApi.setMarketplaceApprovalStatus(input, ctx);
+ }),
+
+ updateTags: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ tags: z.array(z.string()),
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ await projectApi.updateProjectTags(input, ctx);
}),
+
findCurrentUserProjectIds: procedure.query(async ({ ctx }) => {
if (ctx.authorization.type !== "user") {
return [];
}
-
- const projectIds = await db.project.findProjectIdsByUserId(
+ const projectIds = await projectApi.findProjectIdsByUserId(
ctx.authorization.userId,
ctx
);
-
return projectIds.map((project) => project.id);
}),