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.

experimental: Marketplace settings (#2949)

Oleg Isonenf66a6bee31a5
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index cd76acd41d..4fe6cfb3a1 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -10,7 +10,11 @@ import { theme, Box, type CSS, Flex, Grid } from "@webstudio-is/design-system";
import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";
import { registerContainers, useBuilderStore } from "~/shared/sync";
import { useSyncServer } from "./shared/sync/sync-server";
-import { SidebarLeft, Navigator } from "./features/sidebar-left";
+import {
+ SidebarLeft,
+ NavigatorContent,
+ useNavigatorLayout,
+} from "./features/sidebar-left";
import { Inspector } from "./features/inspector";
import { Topbar } from "./features/topbar";
import builderStyles from "./builder.css";
@@ -39,6 +43,7 @@ import {
$domains,
$resources,
subscribeResources,
+ $marketplaceProduct,
} from "~/shared/nano-states";
import { type Settings } from "./shared/client-settings";
import { getBuildUrl } from "~/shared/router-utils";
@@ -51,7 +56,6 @@ import { AiCommandBar } from "./features/ai/ai-command-bar";
import { ProjectSettings } from "./features/project-settings";
import type { UserPlanFeatures } from "~/shared/db/user-plan-features.server";
import { $isCloneDialogOpen, $userPlanFeatures } from "./shared/nano-states";
-import { useNavigatorLayout } from "./features/sidebar-left/navigator";
import { CloneProjectDialog } from "~/shared/clone-project";
registerContainers();
@@ -211,7 +215,7 @@ const NavigatorPanel = ({
height: "100%",
}}
>
- <Navigator isClosable={false} />
+ <NavigatorContent isClosable={false} />
</Box>
</SidePanel>
);
@@ -256,6 +260,7 @@ export const Builder = ({
$styleSourceSelections.set(new Map(build.styleSourceSelections));
$breakpoints.set(new Map(build.breakpoints));
$styles.set(new Map(build.styles));
+ $marketplaceProduct.set(build.marketplaceProduct);
});
useEffect(subscribeCommands, []);
diff --git a/apps/builder/app/builder/features/project-settings/compiler-section.tsx b/apps/builder/app/builder/features/project-settings/compiler-section.tsx
deleted file mode 100644
index e9cc264830..0000000000
--- a/apps/builder/app/builder/features/project-settings/compiler-section.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import {
- Grid,
- Label,
- theme,
- Text,
- CheckboxAndLabel,
- Checkbox,
-} from "@webstudio-is/design-system";
-import { useIds } from "~/shared/form-utils";
-import type { CompilerSettings } from "@webstudio-is/sdk";
-import { serverSyncStore } from "~/shared/sync";
-import { $pages } from "~/shared/nano-states";
-import { useState } from "react";
-
-const defaultSettings: CompilerSettings = {
- atomicStyles: true,
-};
-
-export const CompilerSection = () => {
- const ids = useIds(["atomicStyles"]);
- const [settings, setSettings] = useState(
- () => $pages.get()?.compiler ?? defaultSettings
- );
-
- const handleSave = (settings: CompilerSettings) => {
- serverSyncStore.createTransaction([$pages], (pages) => {
- if (pages === undefined) {
- return;
- }
- pages.compiler = settings;
- });
- };
-
- return (
- <Grid gap={2} css={{ mx: theme.spacing[5], px: theme.spacing[5] }}>
- <Text variant="titles">Compiler</Text>
- <CheckboxAndLabel>
- <Checkbox
- checked={settings.atomicStyles ?? true}
- id={ids.atomicStyles}
- onCheckedChange={(atomicStyles) => {
- if (typeof atomicStyles === "boolean") {
- const nextSettings = { ...settings, atomicStyles };
- setSettings(nextSettings);
- handleSave(nextSettings);
- }
- }}
- />
- <Label htmlFor={ids.atomicStyles}>
- Generate atomic CSS when publishing
- </Label>
- </CheckboxAndLabel>
- </Grid>
- );
-};
diff --git a/apps/builder/app/builder/features/project-settings/project-settings.tsx b/apps/builder/app/builder/features/project-settings/project-settings.tsx
index 30dd8e783c..d66da3dfef 100644
--- a/apps/builder/app/builder/features/project-settings/project-settings.tsx
+++ b/apps/builder/app/builder/features/project-settings/project-settings.tsx
@@ -5,13 +5,30 @@ import {
DialogTitle,
Grid,
theme,
- Separator,
ScrollArea,
+ Flex,
+ List,
+ ListItem,
+ focusRingStyle,
+ Text,
} from "@webstudio-is/design-system";
import { $isProjectSettingsOpen } from "~/shared/nano-states/seo";
-import { MetaSection } from "./meta-section";
-import { CompilerSection } from "./compiler-section";
-import { RedirectSection } from "./redirect-section";
+import { SectionGeneral } from "./section-general";
+import { SectionRedirects } from "./section-redirects";
+import { useState } from "react";
+import { isFeatureEnabled } from "@webstudio-is/feature-flags";
+import { SectionMarketplace } from "./section-marketplace";
+
+const focusOutline = focusRingStyle();
+
+const settingNames = ["General", "Redirects"];
+
+if (isFeatureEnabled("marketplace")) {
+ settingNames.push("Marketplace");
+}
+
+const leftPanelWidth = theme.spacing[26];
+const rightPanelWidth = theme.spacing[34];
const ProjectSettingsView = ({
isOpen,
@@ -20,27 +37,78 @@ const ProjectSettingsView = ({
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
}) => {
+ const [selectedSetting, setSelectedSetting] = useState<
+ (typeof settingNames)[number]
+ >(settingNames[0]);
+
return (
<Dialog open={isOpen} onOpenChange={onOpenChange}>
<DialogContent
// Left Aside panels (e.g., Pages, Components) use zIndex: theme.zIndices[1].
// For a dialog to appear above these panels, both overlay and content should also have zIndex: theme.zIndices[1].
css={{
- width: theme.spacing[34],
+ width: `calc(${leftPanelWidth} + ${rightPanelWidth})`,
+ maxWidth: "none",
+ height: theme.spacing[35],
zIndex: theme.zIndices[1],
}}
overlayCss={{ zIndex: theme.zIndices[1] }}
>
- <ScrollArea>
- <Grid gap={2} css={{ my: theme.spacing[5] }}>
- <MetaSection />
- <Separator />
- <CompilerSection />
- <Separator />
- <RedirectSection />
- <div />
- </Grid>
- </ScrollArea>
+ <Flex grow>
+ <List asChild>
+ <Flex
+ direction="column"
+ shrink={false}
+ css={{
+ width: leftPanelWidth,
+ borderRight: `1px solid ${theme.colors.borderMain}`,
+ }}
+ >
+ {settingNames.map((name, index) => {
+ return (
+ <ListItem
+ current={selectedSetting === name}
+ asChild
+ index={index}
+ key={name}
+ onSelect={() => {
+ setSelectedSetting(name);
+ }}
+ >
+ <Flex
+ css={{
+ position: "relative",
+ height: theme.spacing[13],
+ px: theme.spacing[9],
+ outline: "none",
+ "&:focus-visible": focusOutline,
+ "&:hover": focusOutline,
+ "&[aria-current=true]": {
+ background: theme.colors.backgroundItemCurrent,
+ color: theme.colors.foregroundContrastMain,
+ },
+ }}
+ align="center"
+ >
+ <Text variant="labelsSentenceCase" truncate>
+ {name}
+ </Text>
+ </Flex>
+ </ListItem>
+ );
+ })}
+ </Flex>
+ </List>
+ <ScrollArea>
+ <Grid gap={2} css={{ my: theme.spacing[5] }}>
+ {selectedSetting === "General" && <SectionGeneral />}
+ {selectedSetting === "Redirects" && <SectionRedirects />}
+ {selectedSetting === "Marketplace" &&
+ isFeatureEnabled("marketplace") && <SectionMarketplace />}
+ <div />
+ </Grid>
+ </ScrollArea>
+ </Flex>
{/* Title is at the end intentionally,
* to make the close button last in the tab order
*/}
diff --git a/apps/builder/app/builder/features/project-settings/meta-section.tsx b/apps/builder/app/builder/features/project-settings/section-general.tsx
similarity index 66%
rename from apps/builder/app/builder/features/project-settings/meta-section.tsx
rename to apps/builder/app/builder/features/project-settings/section-general.tsx
index 6aa67737bb..df3b4c6f5a 100644
--- a/apps/builder/app/builder/features/project-settings/meta-section.tsx
+++ b/apps/builder/app/builder/features/project-settings/section-general.tsx
@@ -8,6 +8,8 @@ import {
TextArea,
Separator,
Button,
+ CheckboxAndLabel,
+ Checkbox,
css,
} from "@webstudio-is/design-system";
import { ImageControl } from "./image-control";
@@ -15,7 +17,7 @@ import { $assets, $pages } from "~/shared/nano-states";
import env from "~/shared/env";
import { Image, createImageLoader } from "@webstudio-is/image";
import { useIds } from "~/shared/form-utils";
-import type { ProjectMeta } from "@webstudio-is/sdk";
+import type { ProjectMeta, CompilerSettings } from "@webstudio-is/sdk";
import { useState } from "react";
import { serverSyncStore } from "~/shared/sync";
@@ -34,11 +36,11 @@ const defaultMetaSettings: ProjectMeta = {
code: "",
};
-export const MetaSection = () => {
+export const SectionGeneral = () => {
const [meta, setMeta] = useState(
() => $pages.get()?.meta ?? defaultMetaSettings
);
- const ids = useIds(["siteName", "favicon", "code"]);
+ const ids = useIds(["siteName", "code"]);
const assets = useStore($assets);
const asset = assets.get(meta.faviconAssetId ?? "");
const favIconUrl = asset ? `${asset.name}` : undefined;
@@ -74,6 +76,7 @@ export const MetaSection = () => {
px: theme.spacing[5],
}}
>
+ <Text variant="titles">General</Text>
<Label htmlFor={ids.siteName}>Site Name</Label>
<InputField
id={ids.siteName}
@@ -89,7 +92,7 @@ export const MetaSection = () => {
<Separator />
<Grid gap={2} css={{ mx: theme.spacing[5], px: theme.spacing[5] }}>
- <Text variant="titles">Favicon</Text>
+ <Label>Favicon</Label>
<Grid flow="column" gap={3}>
<Image
width={72}
@@ -104,9 +107,7 @@ export const MetaSection = () => {
Upload a 32 x 32 px image to display in browser tabs.
</Text>
<ImageControl onAssetIdChange={handleSave("faviconAssetId")}>
- <Button id={ids.favicon} css={{ justifySelf: "start" }}>
- Upload
- </Button>
+ <Button css={{ justifySelf: "start" }}>Upload</Button>
</ImageControl>
</Grid>
</Grid>
@@ -115,7 +116,7 @@ export const MetaSection = () => {
<Separator />
<Grid gap={2} css={{ mx: theme.spacing[5], px: theme.spacing[5] }}>
- <Text variant="titles">Custom Code</Text>
+ <Label htmlFor={ids.code}>Custom Code</Label>
<Text color="subtle">
Custom code and scripts will be added at the end of the &lt;head&gt;
tag to every page across the published project.
@@ -129,6 +130,52 @@ export const MetaSection = () => {
onChange={handleSave("code")}
/>
</Grid>
+
+ <Separator />
+
+ <CompilerSection />
</>
);
};
+
+const defaultCompilerSettings: CompilerSettings = {
+ atomicStyles: true,
+};
+
+const CompilerSection = () => {
+ const ids = useIds(["atomicStyles"]);
+ const [settings, setSettings] = useState(
+ () => $pages.get()?.compiler ?? defaultCompilerSettings
+ );
+
+ const handleSave = (settings: CompilerSettings) => {
+ serverSyncStore.createTransaction([$pages], (pages) => {
+ if (pages === undefined) {
+ return;
+ }
+ pages.compiler = settings;
+ });
+ };
+
+ return (
+ <Grid gap={2} css={{ mx: theme.spacing[5], px: theme.spacing[5] }}>
+ <Label htmlFor={ids.atomicStyles}>Compiler</Label>
+ <CheckboxAndLabel>
+ <Checkbox
+ checked={settings.atomicStyles ?? true}
+ id={ids.atomicStyles}
+ onCheckedChange={(atomicStyles) => {
+ if (typeof atomicStyles === "boolean") {
+ const nextSettings = { ...settings, atomicStyles };
+ setSettings(nextSettings);
+ handleSave(nextSettings);
+ }
+ }}
+ />
+ <Label htmlFor={ids.atomicStyles}>
+ Generate atomic CSS when publishing
+ </Label>
+ </CheckboxAndLabel>
+ </Grid>
+ );
+};
diff --git a/apps/builder/app/builder/features/project-settings/section-marketplace.tsx b/apps/builder/app/builder/features/project-settings/section-marketplace.tsx
new file mode 100644
index 0000000000..c9385ab86c
--- /dev/null
+++ b/apps/builder/app/builder/features/project-settings/section-marketplace.tsx
@@ -0,0 +1,335 @@
+import { useStore } from "@nanostores/react";
+import {
+ Grid,
+ InputField,
+ Label,
+ theme,
+ Text,
+ TextArea,
+ Button,
+ css,
+ Flex,
+ CheckboxAndLabel,
+ Checkbox,
+ InputErrorsTooltip,
+ PanelBanner,
+} from "@webstudio-is/design-system";
+import { ImageControl } from "./image-control";
+import {
+ $assets,
+ $authToken,
+ $marketplaceProduct,
+ $project,
+} from "~/shared/nano-states";
+import env from "~/shared/env";
+import { Image, createImageLoader } from "@webstudio-is/image";
+import { useIds } from "~/shared/form-utils";
+import { useState } from "react";
+import { MarketplaceProduct } from "@webstudio-is/project-build";
+import { serverSyncStore } from "~/shared/sync";
+import { createTrpcRemixProxy } from "~/shared/remix/trpc-remix-proxy";
+import {
+ MarketplaceApprovalStatus,
+ type ProjectRouter,
+} from "@webstudio-is/project";
+import { projectsPath } from "~/shared/router-utils";
+
+const imgStyle = css({
+ width: 72,
+ height: 72,
+ borderRadius: theme.borderRadius[4],
+ borderWidth: 1,
+ borderStyle: "solid",
+ borderColor: theme.colors.borderMain,
+});
+
+const defaultMarketplaceProduct: Partial<MarketplaceProduct> = {
+ category: "sectionTemplates",
+};
+
+const imageLoader = createImageLoader({
+ imageBaseUrl: env.IMAGE_BASE_URL,
+});
+
+const trpc = createTrpcRemixProxy<ProjectRouter>((method) =>
+ projectsPath(method, { authToken: $authToken.get() })
+);
+
+const validate = (data: MarketplaceProduct) => {
+ const parsedResult = MarketplaceProduct.safeParse(data);
+ if (parsedResult.success === false) {
+ return parsedResult.error.formErrors.fieldErrors;
+ }
+};
+
+const useMarketplaceApprovalStatus = () => {
+ const { send, data, state } = trpc.setMarketplaceApprovalStatus.useMutation();
+ const project = useStore($project);
+
+ const status =
+ data?.marketplaceApprovalStatus ??
+ project?.marketplaceApprovalStatus ??
+ "UNLISTED";
+
+ const handleSuccess = ({
+ marketplaceApprovalStatus,
+ }: {
+ marketplaceApprovalStatus: MarketplaceApprovalStatus;
+ }) => {
+ const project = $project.get();
+ if (project) {
+ $project.set({
+ ...project,
+ marketplaceApprovalStatus,
+ });
+ }
+ };
+
+ return {
+ status,
+ state,
+ submit() {
+ if (project) {
+ send(
+ {
+ projectId: project.id,
+ marketplaceApprovalStatus: "PENDING",
+ },
+ handleSuccess
+ );
+ }
+ },
+ unlist() {
+ if (project) {
+ send(
+ {
+ projectId: project.id,
+ marketplaceApprovalStatus: "UNLISTED",
+ },
+ handleSuccess
+ );
+ }
+ },
+ };
+};
+
+export const SectionMarketplace = () => {
+ const project = useStore($project);
+ const approval = useMarketplaceApprovalStatus();
+ const [data, setData] = useState(() => $marketplaceProduct.get());
+ const ids = useIds([
+ "name",
+ "thumbnailAssetId",
+ "author",
+ "email",
+ "website",
+ "issues",
+ "description",
+ "isConfirmed",
+ ]);
+ const assets = useStore($assets);
+ const [isConfirmed, setIsConfirmed] = useState<boolean>(false);
+ const [errors, setErrors] = useState<ReturnType<typeof validate>>();
+
+ if (data === undefined || project === undefined) {
+ return;
+ }
+ const asset = assets.get(data.thumbnailAssetId ?? "");
+ const thumbnailUrl = asset ? `${asset.name}` : undefined;
+
+ const handleSave = <Setting extends keyof MarketplaceProduct>(
+ setting: Setting
+ ) => {
+ return (value: MarketplaceProduct[Setting]) => {
+ const nextData = {
+ ...defaultMarketplaceProduct,
+ ...data,
+ [setting]: value,
+ };
+ const errors = validate(nextData);
+ setErrors(errors);
+ setData(nextData);
+ if (errors) {
+ return;
+ }
+ serverSyncStore.createTransaction(
+ [$marketplaceProduct],
+ (marketplaceProduct) => {
+ if (marketplaceProduct === undefined) {
+ return;
+ }
+ Object.assign(marketplaceProduct, nextData);
+ }
+ );
+ };
+ };
+ const sectionSpacing = { mx: theme.spacing[5], px: theme.spacing[5] };
+
+ return (
+ <>
+ <Grid gap={1} css={sectionSpacing}>
+ <Text variant="titles">Marketplace</Text>
+ <Label htmlFor={ids.name}>Product Name</Label>
+ <InputErrorsTooltip errors={errors?.name}>
+ <InputField
+ id={ids.name}
+ value={data.name ?? ""}
+ autoFocus
+ color={errors?.name && "error"}
+ onChange={(event) => {
+ handleSave("name")(event.target.value);
+ }}
+ />
+ </InputErrorsTooltip>
+ </Grid>
+
+ <Grid gap={2} css={sectionSpacing}>
+ <Label>Thumbnail</Label>
+ <Grid flow="column" gap={3}>
+ <Image
+ width={72}
+ height={72}
+ className={imgStyle()}
+ src={thumbnailUrl}
+ loader={imageLoader}
+ />
+
+ <Grid gap={2}>
+ <Text color="subtle">
+ Upload a 32 x 32 px image to display in the marketplace overview.
+ </Text>
+ <ImageControl onAssetIdChange={handleSave("thumbnailAssetId")}>
+ <Button css={{ justifySelf: "start" }}>Upload</Button>
+ </ImageControl>
+ </Grid>
+ </Grid>
+ </Grid>
+
+ <Grid gap={1} css={sectionSpacing}>
+ <Label htmlFor={ids.author}>Author</Label>
+ <InputErrorsTooltip errors={errors?.author}>
+ <InputField
+ id={ids.author}
+ value={data.author ?? ""}
+ color={errors?.author && "error"}
+ onChange={(event) => {
+ handleSave("author")(event.target.value);
+ }}
+ />
+ </InputErrorsTooltip>
+ </Grid>
+
+ <Grid gap={1} css={sectionSpacing}>
+ <Label htmlFor={ids.email}>Email</Label>
+ <InputErrorsTooltip errors={errors?.email}>
+ <InputField
+ id={ids.email}
+ value={data.email ?? ""}
+ color={errors?.email && "error"}
+ onChange={(event) => {
+ handleSave("email")(event.target.value);
+ }}
+ />
+ </InputErrorsTooltip>
+ </Grid>
+
+ <Grid gap={1} css={sectionSpacing}>
+ <Label htmlFor={ids.website}>Website</Label>
+ <InputErrorsTooltip errors={errors?.website}>
+ <InputField
+ id={ids.website}
+ value={data.website ?? ""}
+ color={errors?.website && "error"}
+ onChange={(event) => {
+ handleSave("website")(event.target.value);
+ }}
+ />
+ </InputErrorsTooltip>
+ </Grid>
+
+ <Grid gap={1} css={sectionSpacing}>
+ <Label htmlFor={ids.issues}>Issues Tracker</Label>
+ <InputErrorsTooltip errors={errors?.issues}>
+ <InputField
+ id={ids.issues}
+ value={data.issues ?? ""}
+ color={errors?.issues && "error"}
+ onChange={(event) => {
+ handleSave("issues")(event.target.value);
+ }}
+ />
+ </InputErrorsTooltip>
+ </Grid>
+
+ <Grid gap={2} css={sectionSpacing}>
+ <Label htmlFor={ids.description}>Description</Label>
+ <InputErrorsTooltip errors={errors?.description}>
+ <TextArea
+ id={ids.description}
+ rows={5}
+ autoGrow
+ maxRows={10}
+ value={data.description ?? ""}
+ onChange={handleSave("description")}
+ />
+ </InputErrorsTooltip>
+ </Grid>
+
+ <Grid gap={2} css={sectionSpacing}>
+ <PanelBanner>
+ <Text>
+ {`For a page to show up in the marketplace, you will need to add a "ws:category"
+ meta tag in the page settings. Optionally, you can also define
+ "ws:title"; otherwise, the page title will be used.`}
+ </Text>
+ <Text color="destructive">
+ {`Don't forget to publish your project after every change to make your
+ changes available in the marketplace!`}
+ </Text>
+ </PanelBanner>
+ </Grid>
+
+ {approval.status === "UNLISTED" && (
+ <Grid gap={2} css={sectionSpacing}>
+ <CheckboxAndLabel>
+ <Checkbox
+ checked={isConfirmed}
+ id={ids.isConfirmed}
+ onCheckedChange={(value) => {
+ if (typeof value === "boolean") {
+ setIsConfirmed(value);
+ }
+ }}
+ />
+ <Label htmlFor={ids.isConfirmed} css={{ flexBasis: "fit-content" }}>
+ I understand that by submitting, this project will become
+ available in a public marketplace.
+ </Label>
+ </CheckboxAndLabel>
+ </Grid>
+ )}
+
+ <Flex align="center" justify="between" gap={2} css={sectionSpacing}>
+ <Text>Status: {approval.status.toLocaleLowerCase()}</Text>
+ {approval.status === "UNLISTED" ? (
+ <Button
+ color="primary"
+ disabled={isConfirmed === false}
+ state={approval.state === "idle" ? undefined : "pending"}
+ onClick={approval.submit}
+ >
+ Submit
+ </Button>
+ ) : (
+ <Button
+ state={approval.state === "idle" ? undefined : "pending"}
+ color="destructive"
+ onClick={approval.unlist}
+ >
+ Unlist from Marketplace
+ </Button>
+ )}
+ </Flex>
+ </>
+ );
+};
diff --git a/apps/builder/app/builder/features/project-settings/redirect-section.tsx b/apps/builder/app/builder/features/project-settings/section-redirects.tsx
similarity index 92%
rename from apps/builder/app/builder/features/project-settings/redirect-section.tsx
rename to apps/builder/app/builder/features/project-settings/section-redirects.tsx
index e2cd612312..e7d640ada2 100644
--- a/apps/builder/app/builder/features/project-settings/redirect-section.tsx
+++ b/apps/builder/app/builder/features/project-settings/section-redirects.tsx
@@ -12,7 +12,7 @@ import {
Select,
} from "@webstudio-is/design-system";
import { ArrowRightIcon, TrashIcon } from "@webstudio-is/icons";
-import { useState, type ChangeEvent } from "react";
+import { useState, type ChangeEvent, useRef } from "react";
import {
PagePath,
PageRedirect,
@@ -22,8 +22,9 @@ import { useStore } from "@nanostores/react";
import { getExistingRoutePaths } from "../sidebar-left/panels/pages/page-utils";
import { $pages } from "~/shared/nano-states";
import { serverSyncStore } from "~/shared/sync";
+import { flushSync } from "react-dom";
-export const RedirectSection = () => {
+export const SectionRedirects = () => {
const [redirects, setRedirects] = useState(
() => $pages.get()?.redirects ?? []
);
@@ -35,6 +36,7 @@ export const RedirectSection = () => {
const [newPathErrors, setNewPathErrors] = useState<string[]>([]);
const pages = useStore($pages);
const existingPaths = getExistingRoutePaths(pages);
+ const oldPathRef = useRef<HTMLInputElement>(null);
const redirectKeys = Object.keys(redirects);
const isValidRedirects =
@@ -118,16 +120,20 @@ export const RedirectSection = () => {
return;
}
- handleSave([
- {
- old: oldPath,
- new: newPath,
- status: httpStatus ?? "301",
- },
- ...redirects,
- ]);
- setOldPath("");
- setNewPath("");
+ // Needs to apply state before setting focus.
+ flushSync(() => {
+ handleSave([
+ {
+ old: oldPath,
+ new: newPath,
+ status: httpStatus ?? "301",
+ },
+ ...redirects,
+ ]);
+ setOldPath("");
+ setNewPath("");
+ });
+ oldPathRef.current?.focus();
};
const handleDeleteRedirect = (index: number) => {
@@ -152,6 +158,8 @@ export const RedirectSection = () => {
css={{ zIndex: theme.zIndices["1"] }}
>
<InputField
+ ref={oldPathRef}
+ autoFocus
type="text"
placeholder="/old-path"
value={oldPath}
diff --git a/apps/builder/app/builder/features/sidebar-left/index.tsx b/apps/builder/app/builder/features/sidebar-left/index.tsx
index e996490006..8964ebd8b2 100644
--- a/apps/builder/app/builder/features/sidebar-left/index.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/index.tsx
@@ -1,2 +1,2 @@
export { SidebarLeft } from "./sidebar-left";
-export { Navigator } from "./navigator";
+export { NavigatorContent, useNavigatorLayout } from "./panels/navigator";
diff --git a/apps/builder/app/builder/features/sidebar-left/navigator/index.ts b/apps/builder/app/builder/features/sidebar-left/navigator/index.ts
deleted file mode 100644
index e17e01b012..0000000000
--- a/apps/builder/app/builder/features/sidebar-left/navigator/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./navigator";
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/assets/assets.tsx b/apps/builder/app/builder/features/sidebar-left/panels/assets/assets.tsx
index 5b71f3f015..03bb4e9605 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/assets/assets.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/assets/assets.tsx
@@ -1,18 +1,17 @@
import { ImageIcon } from "@webstudio-is/icons";
-import { Flex } from "@webstudio-is/design-system";
import { ImageManager } from "~/builder/shared/image-manager";
import type { TabContentProps } from "../../types";
-import { Header, CloseButton } from "../../header";
+import { Header, CloseButton, Root } from "../../shared/panel";
export const TabContent = ({ onSetActiveTab }: TabContentProps) => {
return (
- <Flex direction="column" css={{ height: "100%" }}>
+ <Root>
<Header
title="Assets"
suffix={<CloseButton onClick={() => onSetActiveTab("none")} />}
/>
<ImageManager />
- </Flex>
+ </Root>
);
};
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx b/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx
index ca9104b777..6252bc757a 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx
@@ -16,7 +16,7 @@ import {
import { PlusIcon } from "@webstudio-is/icons";
import { CollapsibleSection } from "~/builder/shared/collapsible-section";
import type { TabContentProps } from "../../types";
-import { Header, CloseButton } from "../../header";
+import { Header, CloseButton, Root } from "../../shared/panel";
import {
dragItemAttribute,
elementToComponentName,
@@ -26,7 +26,6 @@ import { MetaIcon } from "~/builder/shared/meta-icon";
import { $registeredComponentMetas } from "~/shared/nano-states";
import { getMetaMaps } from "./get-meta-maps";
import { getInstanceLabel } from "~/shared/instance-utils";
-import { isFeatureEnabled } from "@webstudio-is/feature-flags";
export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {
const metaByComponentName = useStore($registeredComponentMetas);
@@ -52,10 +51,7 @@ export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {
});
return (
- <Flex
- css={{ height: "100%", flexDirection: "column" }}
- ref={draggableContainerRef}
- >
+ <Root ref={draggableContainerRef}>
<Header
title="Components"
suffix={<CloseButton onClick={() => onSetActiveTab("none")} />}
@@ -66,14 +62,6 @@ export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {
if (category === "hidden") {
return false;
}
-
- if (
- category === "utilities" &&
- isFeatureEnabled("marketplace") === false
- ) {
- return false;
- }
-
return true;
})
.map((category) => (
@@ -116,7 +104,7 @@ export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {
</CollapsibleSection>
))}
</ScrollArea>
- </Flex>
+ </Root>
);
};
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/about.tsx b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/about.tsx
new file mode 100644
index 0000000000..c87dcf68a8
--- /dev/null
+++ b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/about.tsx
@@ -0,0 +1,75 @@
+import {
+ Button,
+ Flex,
+ Link,
+ Text,
+ Tooltip,
+ theme,
+} from "@webstudio-is/design-system";
+import type { MarketplaceOverviewItem } from "~/shared/marketplace/types";
+import { Header } from "../../shared/panel";
+import { ChevronDoubleLeftIcon } from "@webstudio-is/icons";
+
+export const About = ({
+ item,
+ onClose,
+}: {
+ item?: MarketplaceOverviewItem;
+ onClose: () => void;
+}) => {
+ if (item === undefined) {
+ return;
+ }
+ return (
+ <>
+ <Header
+ title={item.name}
+ suffix={
+ <Tooltip content="Close" side="bottom">
+ <Button
+ onClick={onClose}
+ aria-label="Close"
+ prefix={<ChevronDoubleLeftIcon />}
+ color="ghost"
+ // Tab should go:
+ // trought form fields -> create button -> cancel button
+ tabIndex={3}
+ />
+ </Tooltip>
+ }
+ />
+ <Flex
+ direction="column"
+ css={{ my: theme.spacing[5], mx: theme.spacing[8] }}
+ gap="2"
+ >
+ <Text>{item.description}</Text>
+ <Flex direction="column">
+ <Flex gap="1">
+ <Text>Author: {item.author}</Text>
+ </Flex>
+ {item.website && (
+ <Flex gap="1">
+ <Text>Website:</Text>
+ <Link href={item.website} target="_blank">
+ {item.website}
+ </Link>
+ </Flex>
+ )}
+ <Flex gap="1">
+ <Text>Email:</Text>
+ <Link href={`mailto:${item.email}`}>{item.email}</Link>
+ </Flex>
+ {item.issues && (
+ <Flex gap="1">
+ <Text>Issues Tracker:</Text>
+ <Link href={item.issues} target="_blank">
+ {item.issues}
+ </Link>
+ </Flex>
+ )}
+ </Flex>
+ </Flex>
+ </>
+ );
+};
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/index.ts b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/index.ts
index 8b8e96a783..21a5b78694 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/index.ts
+++ b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/index.ts
@@ -1 +1 @@
-export * from "./tab";
+export * from "./marketplace";
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/marketplace.tsx b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/marketplace.tsx
index 7bdcb6a8da..a36e057aea 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/marketplace.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/marketplace.tsx
@@ -1,127 +1,85 @@
-import { useMemo } from "react";
-import { useStore } from "@nanostores/react";
-import {
- Flex,
- List,
- ListItem,
- ScrollArea,
- Text,
- focusRingStyle,
- rawTheme,
- theme,
-} from "@webstudio-is/design-system";
-import { CollapsibleSection } from "~/builder/shared/collapsible-section";
-import { $products, categories } from "./utils";
-import type { MarketplaceProduct } from "./schema";
-import { LoadingDotsIcon } from "@webstudio-is/icons";
+import { ExtensionIcon, SpinnerIcon } from "@webstudio-is/icons";
+import { Flex, rawTheme } from "@webstudio-is/design-system";
+import type { TabContentProps } from "../../types";
+import { Header, CloseButton, Root } from "../../shared/panel";
+import { Overview } from "./overview";
+import { SectionTemplates } from "./section-templates";
+import { marketplacePath } from "~/shared/router-utils";
+import { useEffect, useState } from "react";
+import { toWebstudioData } from "./utils";
+import type { MarketplaceOverviewItem } from "~/shared/marketplace/types";
+import type { MarketplaceRouter } from "~/shared/marketplace/router";
+import { createTrpcFetchProxy } from "~/shared/remix/trpc-remix-proxy";
+import type { Project } from "@webstudio-is/project";
+import { ExtendedPanel } from "../../shared/extended-panel";
+import { About } from "./about";
-const getProductsByCategory = (products: Array<MarketplaceProduct>) => {
- const productsByCategory = new Map<
- MarketplaceProduct["category"],
- Array<MarketplaceProduct>
- >();
+const trpc = createTrpcFetchProxy<MarketplaceRouter>(marketplacePath);
- for (const product of products) {
- if (
- categories.some((category) => category.category === product.category) ===
- false
- ) {
- throw new Error(`Unknown category: ${product.category}`);
- }
- let categoryItems = productsByCategory.get(product.category);
- if (categoryItems === undefined) {
- categoryItems = [];
- productsByCategory.set(product.category, categoryItems);
- }
- categoryItems.push(product);
- }
- return productsByCategory;
-};
+export const TabContent = ({ onSetActiveTab }: TabContentProps) => {
+ const [activeOverviewItem, setAciveOverviewItem] =
+ useState<MarketplaceOverviewItem>();
+ const [openAbout, setopenAbout] = useState<Project["id"]>();
+
+ const {
+ load: getItems,
+ data: items,
+ state: itemsLoadingState,
+ } = trpc.getItems.useQuery();
+
+ const { load: getBuildData, data: buildData } = trpc.getBuildData.useQuery();
-const focusOutline = focusRingStyle();
+ useEffect(() => {
+ getItems();
+ }, [getItems]);
+
+ const openAboutItem = items?.find((item) => item.projectId === openAbout);
-const Product = ({
- product,
- isLoading,
- ...props
-}: {
- product: MarketplaceProduct;
- isLoading: boolean;
-}) => {
return (
- <Flex
- {...props}
- css={{
- position: "relative",
- height: theme.spacing[13],
- px: theme.spacing[9],
- outline: "none",
- "&:focus-visible": focusOutline,
- "&:hover": focusOutline,
- }}
- align="center"
- justify="between"
- >
- <Flex align="center" gap="2">
- <img
- src={`${new URL(product.publishedUrl).origin}/favicon.ico`}
- style={{ width: rawTheme.spacing[11], height: rawTheme.spacing[11] }}
- aria-disabled
+ <>
+ <Root>
+ <Header
+ title="Marketplace"
+ suffix={<CloseButton onClick={() => onSetActiveTab("none")} />}
+ />
+ {itemsLoadingState !== "idle" && (
+ <Flex justify="center" css={{ mt: "20%" }}>
+ <SpinnerIcon size={rawTheme.spacing[15]} />
+ </Flex>
+ )}
+ {activeOverviewItem && buildData ? (
+ <SectionTemplates
+ name={activeOverviewItem.name}
+ data={toWebstudioData(buildData)}
+ onOpenChange={(isOpen: boolean) => {
+ if (isOpen === false) {
+ setAciveOverviewItem(undefined);
+ }
+ }}
+ />
+ ) : (
+ <Overview
+ items={items}
+ activeProjectId={activeOverviewItem?.projectId}
+ onSelect={(activeOverviewItem) => {
+ setAciveOverviewItem(activeOverviewItem);
+ getBuildData({ projectId: activeOverviewItem.projectId });
+ }}
+ openAbout={openAbout}
+ onOpenAbout={setopenAbout}
+ />
+ )}
+ </Root>
+ <ExtendedPanel isOpen={openAboutItem !== undefined}>
+ <About
+ item={openAboutItem}
+ onClose={() => {
+ setopenAbout(undefined);
+ }}
/>
- <Text variant="labelsSentenceCase" truncate>
- {product.label}
- </Text>
- </Flex>
- {isLoading && <LoadingDotsIcon style={{ flexShrink: 0 }} />}
- </Flex>
+ </ExtendedPanel>
+ </>
);
};
-export const Marketplace = ({
- activeProduct,
- onSelect,
-}: {
- activeProduct?: MarketplaceProduct;
- onSelect: (product: MarketplaceProduct) => void;
-}) => {
- const products = useStore($products);
- const productsByCategory = useMemo(
- () => new Map(getProductsByCategory(products)),
- [products]
- );
- return (
- <ScrollArea>
- {categories.map(({ category, label }) => {
- const products = productsByCategory.get(category);
- if (products === undefined || products.length === 0) {
- return;
- }
- return (
- <CollapsibleSection label={label} key={category} fullWidth>
- <List asChild>
- <Flex direction="column">
- {products.map((product: MarketplaceProduct, index) => {
- return (
- <ListItem
- asChild
- key={product.id}
- index={index}
- onSelect={() => {
- onSelect(product);
- }}
- >
- <Product
- product={product}
- isLoading={product.id === activeProduct?.id}
- />
- </ListItem>
- );
- })}
- </Flex>
- </List>
- </CollapsibleSection>
- );
- })}
- </ScrollArea>
- );
-};
+export const Icon = ExtensionIcon;
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/overview.tsx b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/overview.tsx
new file mode 100644
index 0000000000..713113fe84
--- /dev/null
+++ b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/overview.tsx
@@ -0,0 +1,168 @@
+import { useMemo } from "react";
+import {
+ Flex,
+ List,
+ ListItem,
+ ScrollArea,
+ SmallIconButton,
+ Text,
+ focusRingStyle,
+ rawTheme,
+ theme,
+} from "@webstudio-is/design-system";
+import { CollapsibleSection } from "~/builder/shared/collapsible-section";
+import { categories } from "./utils";
+import {
+ ChevronRightIcon,
+ EllipsesIcon,
+ SpinnerIcon,
+} from "@webstudio-is/icons";
+import env from "~/shared/env";
+import { Image, createImageLoader } from "@webstudio-is/image";
+import type { MarketplaceOverviewItem } from "~/shared/marketplace/types";
+import type { Project } from "@webstudio-is/project";
+import { usePress } from "@react-aria/interactions";
+
+const getItemsByCategory = (items: Array<MarketplaceOverviewItem> = []) => {
+ const itemsByCategory = new Map<
+ MarketplaceOverviewItem["category"],
+ Array<MarketplaceOverviewItem>
+ >();
+
+ for (const OverviewItem of items) {
+ if (
+ categories.some(
+ (category) => category.category === OverviewItem.category
+ ) === false
+ ) {
+ throw new Error(`Unknown category: ${OverviewItem.category}`);
+ }
+ let categoryItems = itemsByCategory.get(OverviewItem.category);
+ if (categoryItems === undefined) {
+ categoryItems = [];
+ itemsByCategory.set(OverviewItem.category, categoryItems);
+ }
+ categoryItems.push(OverviewItem);
+ }
+ return itemsByCategory;
+};
+
+const focusOutline = focusRingStyle();
+
+const imageLoader = createImageLoader({
+ imageBaseUrl: env.IMAGE_BASE_URL,
+});
+
+const OverviewItem = ({
+ item,
+ isLoading,
+ isOpen,
+ onOpenStateChange,
+ ...props
+}: {
+ item: MarketplaceOverviewItem;
+ isLoading: boolean;
+ isOpen: boolean;
+ onOpenStateChange: (isOpen: boolean) => void;
+}) => {
+ const { pressProps } = usePress({
+ onPress() {
+ onOpenStateChange(isOpen ? false : true);
+ },
+ });
+
+ return (
+ <Flex
+ {...props}
+ css={{
+ position: "relative",
+ height: theme.spacing[13],
+ px: theme.spacing[9],
+ outline: "none",
+ "&:focus-visible": focusOutline,
+ "&:hover": focusOutline,
+ }}
+ align="center"
+ justify="between"
+ >
+ <Flex align="center" gap="2">
+ <Image
+ src={item.thumbnailAssetName}
+ loader={imageLoader}
+ width={rawTheme.spacing[11]}
+ height={rawTheme.spacing[11]}
+ aria-disabled
+ />
+ <Text variant="labelsSentenceCase" truncate>
+ {item.name}
+ </Text>
+ </Flex>
+ <Flex shrink={false} align="center">
+ {isLoading ? (
+ <SpinnerIcon />
+ ) : (
+ <SmallIconButton
+ icon={isOpen ? <ChevronRightIcon /> : <EllipsesIcon />}
+ {...pressProps}
+ />
+ )}
+ </Flex>
+ </Flex>
+ );
+};
+
+export const Overview = ({
+ activeProjectId,
+ items,
+ onSelect,
+ openAbout,
+ onOpenAbout,
+}: {
+ activeProjectId?: Project["id"];
+ items?: Array<MarketplaceOverviewItem>;
+ onSelect: (item: MarketplaceOverviewItem) => void;
+ openAbout?: Project["id"];
+ onOpenAbout: (projectId?: string) => void;
+}) => {
+ const itemsByCategory = useMemo(() => getItemsByCategory(items), [items]);
+
+ return (
+ <ScrollArea>
+ {categories.map(({ category, label }) => {
+ const items = itemsByCategory.get(category);
+ if (items === undefined || items.length === 0) {
+ return;
+ }
+ return (
+ <CollapsibleSection label={label} key={category} fullWidth>
+ <List asChild>
+ <Flex direction="column">
+ {items.map((item, index) => {
+ return (
+ <ListItem
+ asChild
+ key={item.projectId}
+ index={index}
+ onSelect={() => {
+ onSelect(item);
+ }}
+ >
+ <OverviewItem
+ item={item}
+ isLoading={item.projectId === activeProjectId}
+ isOpen={openAbout === item.projectId}
+ onOpenStateChange={(isOpen) => {
+ onOpenAbout(isOpen ? item.projectId : undefined);
+ }}
+ />
+ </ListItem>
+ );
+ })}
+ </Flex>
+ </List>
+ </CollapsibleSection>
+ );
+ })}
+ </ScrollArea>
+ );
+};
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/products.json b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/products.json
deleted file mode 100644
index de69545120..0000000000
--- a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/products.json
+++ /dev/null
@@ -1,9 +0,0 @@
-[
- {
- "category": "templates",
- "label": "CIQ Library Lite",
- "publishedUrl": "https://launchpads-style-guide-c4i72.wstd.io",
- "authToken": "e41a0452-a468-416c-a4da-13590db1821a",
- "projectId": "bc5f0c98-a6b0-4544-9b3f-9ae06664c036"
- }
-]
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/schema.ts b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/schema.ts
deleted file mode 100644
index afbe451e67..0000000000
--- a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/schema.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { z } from "zod";
-
-const Base = z.object({
- id: z.string(),
- label: z.string(),
- publishedUrl: z.string(),
- authToken: z.string(),
- projectId: z.string(),
-});
-
-const TemplatesProduct = Base.extend({
- category: z.literal("templates"),
-});
-
-// Will add an AppProduct later.
-export const MarketplaceProduct = TemplatesProduct;
-export type MarketplaceProduct = z.infer<typeof MarketplaceProduct>;
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/template.tsx b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/section-templates.tsx
similarity index 89%
rename from apps/builder/app/builder/features/sidebar-left/panels/marketplace/template.tsx
rename to apps/builder/app/builder/features/sidebar-left/panels/marketplace/section-templates.tsx
index 414d8fc157..a7ae779759 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/template.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/section-templates.tsx
@@ -18,7 +18,6 @@ import type { Asset, WebstudioData } from "@webstudio-is/sdk";
import { useMemo } from "react";
import env from "~/shared/env";
import { Image, createImageLoader } from "@webstudio-is/image";
-import type { MarketplaceProduct } from "./schema";
const focusOutline = focusRingStyle();
@@ -68,7 +67,7 @@ type TemplateData = {
rootInstanceId: string;
};
-const Template = ({
+const SectionTemplate = ({
data: { socialImageAsset, socialImageUrl, title },
...listItemProps
}: {
@@ -84,8 +83,13 @@ const Template = ({
position: "relative",
overflow: "hidden",
outline: "none",
- "&:hover": focusOutline,
- "&:focus-visible": focusOutline,
+ "&:hover": {
+ background: theme.colors.backgroundPresetMain,
+ },
+ "&:focus-visible": {
+ ...focusOutline,
+ background: theme.colors.backgroundPresetMain,
+ },
}}
gap="1"
>
@@ -110,8 +114,9 @@ const getTemplatesDataByCategory = (data?: WebstudioData) => {
// In the future we could support bindings in the store as well.
const variableValues = new Map();
+ const pages = [data.pages.homePage, ...data.pages.pages];
- for (const page of data.pages.pages) {
+ for (const page of pages) {
let category = page.meta.custom?.find(
({ property }) => property === marketplaceMeta.category
)?.content;
@@ -153,12 +158,12 @@ const getTemplatesDataByCategory = (data?: WebstudioData) => {
return templatesByCategory;
};
-export const Templates = ({
- product,
+export const SectionTemplates = ({
+ name,
data,
onOpenChange,
}: {
- product: MarketplaceProduct;
+ name: string;
data: WebstudioData;
onOpenChange: (isOpen: boolean) => void;
}) => {
@@ -173,7 +178,11 @@ export const Templates = ({
return (
<Flex direction="column" css={{ height: "100%" }}>
- <Flex align="center" css={{ px: theme.spacing[9], py: theme.spacing[5] }}>
+ <Flex
+ align="center"
+ shrink="false"
+ css={{ px: theme.spacing[9], py: theme.spacing[5] }}
+ >
<Button
prefix={<ChevronLeftIcon />}
onClick={() => {
@@ -181,7 +190,7 @@ export const Templates = ({
}}
color="neutral"
>
- {product.label}
+ {name}
</Button>
</Flex>
<Separator />
@@ -206,7 +215,7 @@ export const Templates = ({
});
}}
>
- <Template data={templateData} />
+ <SectionTemplate data={templateData} />
</ListItem>
);
})}
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/tab.tsx b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/tab.tsx
deleted file mode 100644
index a863c29e5c..0000000000
--- a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/tab.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { ExtensionIcon } from "@webstudio-is/icons";
-import { Flex } from "@webstudio-is/design-system";
-import type { TabContentProps } from "../../types";
-import { Header, CloseButton } from "../../header";
-import { Marketplace } from "./marketplace";
-import { Templates } from "./template";
-import { builderPath } from "~/shared/router-utils";
-import { useFetcher } from "@remix-run/react";
-import { useState } from "react";
-import type { MarketplaceProduct } from "./schema";
-import { toWebstudioData } from "./utils";
-
-export const TabContent = ({ onSetActiveTab }: TabContentProps) => {
- const [activeProduct, setActiveProduct] = useState<MarketplaceProduct>();
- const { load, data } = useFetcher();
-
- const handleOpenChange = (isOpen: boolean) => {
- if (isOpen === false) {
- setActiveProduct(undefined);
- }
- };
-
- return (
- <Flex direction="column" css={{ height: "100%" }}>
- <Header
- title="Marketplace"
- suffix={<CloseButton onClick={() => onSetActiveTab("none")} />}
- />
- {activeProduct && data ? (
- <Templates
- product={activeProduct}
- data={toWebstudioData(data)}
- onOpenChange={handleOpenChange}
- />
- ) : (
- <Marketplace
- activeProduct={activeProduct}
- onSelect={(product) => {
- setActiveProduct(product);
- load(
- builderPath({
- projectId: product.projectId,
- authToken: product.authToken,
- })
- );
- }}
- />
- )}
- </Flex>
- );
-};
-
-export const Icon = ExtensionIcon;
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/utils.ts b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/utils.ts
index 248c51ca5b..e366d28768 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/marketplace/utils.ts
+++ b/apps/builder/app/builder/features/sidebar-left/panels/marketplace/utils.ts
@@ -4,24 +4,17 @@ import {
findTargetAndInsertFragment,
} from "~/shared/instance-utils";
import type { WebstudioData } from "@webstudio-is/sdk";
-import productsData from "./products.json";
-import { MarketplaceProduct } from "./schema";
-import type { BuilderProps } from "~/builder";
+import { MarketplaceProduct } from "@webstudio-is/project-build";
+import type { BuildData } from "~/shared/marketplace/types";
export const $activeProductData = atom<WebstudioData | undefined>();
-export const $products = atom(
- productsData.map((product, index) =>
- MarketplaceProduct.parse({ ...product, id: String(index) })
- )
-);
-
export const categories: Array<{
category: MarketplaceProduct["category"];
label: string;
-}> = [{ category: "templates", label: "Templates" }];
+}> = [{ category: "sectionTemplates", label: "Section Templates" }];
-export const toWebstudioData = (data: BuilderProps): WebstudioData => ({
+export const toWebstudioData = (data: BuildData): WebstudioData => ({
pages: data.build.pages,
assets: new Map(data.assets),
instances: new Map(data.build.instances),
diff --git a/apps/builder/app/builder/features/sidebar-left/navigator/css-preview.tsx b/apps/builder/app/builder/features/sidebar-left/panels/navigator/css-preview.tsx
similarity index 98%
rename from apps/builder/app/builder/features/sidebar-left/navigator/css-preview.tsx
rename to apps/builder/app/builder/features/sidebar-left/panels/navigator/css-preview.tsx
index 8eb319fe90..2754cd150b 100644
--- a/apps/builder/app/builder/features/sidebar-left/navigator/css-preview.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/navigator/css-preview.tsx
@@ -8,7 +8,7 @@ import {
type StyleInfo,
useStyleInfo,
type StyleValueInfo,
-} from "../../style-panel/shared/style-info";
+} from "../../../style-panel/shared/style-info";
import { createRegularStyleSheet } from "@webstudio-is/css-engine";
import { CollapsibleSection } from "~/builder/shared/collapsible-section";
import { useMemo } from "react";
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/navigator/index.ts b/apps/builder/app/builder/features/sidebar-left/panels/navigator/index.ts
index e17e01b012..c54ad3aaf7 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/navigator/index.ts
+++ b/apps/builder/app/builder/features/sidebar-left/panels/navigator/index.ts
@@ -1 +1,2 @@
export * from "./navigator";
+export * from "./navigator-content";
diff --git a/apps/builder/app/builder/features/sidebar-left/navigator/navigator.tsx b/apps/builder/app/builder/features/sidebar-left/panels/navigator/navigator-content.tsx
similarity index 86%
rename from apps/builder/app/builder/features/sidebar-left/navigator/navigator.tsx
rename to apps/builder/app/builder/features/sidebar-left/panels/navigator/navigator-content.tsx
index 0cb6822bcb..848b8cc2de 100644
--- a/apps/builder/app/builder/features/sidebar-left/navigator/navigator.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/navigator/navigator-content.tsx
@@ -1,6 +1,6 @@
import { Flex, Separator } from "@webstudio-is/design-system";
import { NavigatorTree } from "~/builder/shared/navigator-tree";
-import { Header, CloseButton } from "../header";
+import { Header, CloseButton, Root } from "../../shared/panel";
import { CssPreview } from "./css-preview";
import { useHotkeys } from "react-hotkeys-hook";
import { emitCommand } from "~/builder/shared/commands";
@@ -27,7 +27,10 @@ type NavigatorProps = {
onClose?: () => void;
};
-export const Navigator = ({ isClosable = true, onClose }: NavigatorProps) => {
+export const NavigatorContent = ({
+ isClosable = true,
+ onClose,
+}: NavigatorProps) => {
const shortcutRef = useHotkeys<HTMLDivElement>(
"enter",
() => emitCommand("editInstanceText"),
@@ -35,7 +38,7 @@ export const Navigator = ({ isClosable = true, onClose }: NavigatorProps) => {
);
return (
- <Flex ref={shortcutRef} css={{ height: "100%", flexDirection: "column" }}>
+ <Root ref={shortcutRef}>
<Header
title="Navigator"
suffix={isClosable && <CloseButton onClick={() => onClose?.()} />}
@@ -45,6 +48,6 @@ export const Navigator = ({ isClosable = true, onClose }: NavigatorProps) => {
<Separator />
<CssPreview />
</Flex>
- </Flex>
+ </Root>
);
};
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/navigator/navigator.tsx b/apps/builder/app/builder/features/sidebar-left/panels/navigator/navigator.tsx
index 8ffbbad6cc..aaed6fb667 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/navigator/navigator.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/navigator/navigator.tsx
@@ -1,10 +1,10 @@
import { NavigatorIcon } from "@webstudio-is/icons";
-import { Navigator } from "../../navigator";
+import { NavigatorContent } from "./navigator-content";
import type { TabContentProps } from "../../types";
export const TabContent = ({ onSetActiveTab }: TabContentProps) => {
return (
- <Navigator
+ <NavigatorContent
onClose={() => {
onSetActiveTab("none");
}}
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/folder-settings.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/folder-settings.tsx
index 95f59dce30..2041817c65 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/folder-settings.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/folder-settings.tsx
@@ -34,7 +34,7 @@ import {
HelpIcon,
} from "@webstudio-is/icons";
import { useIds } from "~/shared/form-utils";
-import { Header, HeaderSuffixSpacer } from "../../header";
+import { Header, HeaderSuffixSpacer } from "../../shared/panel";
import { $pages } from "~/shared/nano-states";
import { nanoid } from "nanoid";
import { serverSyncStore } from "~/shared/sync";
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 8d1f97c8eb..eab6d67735 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
@@ -71,6 +71,7 @@ $project.set({
id: "0",
name: "0",
},
+ marketplaceApprovalStatus: "UNLISTED",
});
export const PageSettingsEdit = () => {
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
index c985a9306a..f16c8dce17 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
@@ -53,7 +53,7 @@ import {
} from "@webstudio-is/icons";
import { isLiteralExpression } from "@webstudio-is/react-sdk";
import { useIds } from "~/shared/form-utils";
-import { Header, HeaderSuffixSpacer } from "../../header";
+import { Header, HeaderSuffixSpacer } from "../../shared/panel";
import { updateWebstudioData } from "~/shared/instance-utils";
import {
$assets,
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/pages.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/pages.tsx
index 7d52015249..23f6e5d010 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/pages.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/pages.tsx
@@ -8,7 +8,6 @@ import {
type TreeItemRenderProps,
type ItemSelector,
styled,
- Flex,
Tooltip,
Box,
Button,
@@ -25,8 +24,8 @@ import {
DynamicPageIcon,
} from "@webstudio-is/icons";
import type { TabContentProps } from "../../types";
-import { CloseButton, Header } from "../../header";
-import { SettingsPanel } from "./settings-panel";
+import { CloseButton, Header, Root } from "../../shared/panel";
+import { ExtendedPanel } from "../../shared/extended-panel";
import { NewPageSettings, PageSettings } from "./page-settings";
import { $pages, $selectedPageId } from "~/shared/nano-states";
import { switchPage } from "~/shared/pages";
@@ -233,17 +232,7 @@ const PagesPanel = ({
}
return (
- <Flex
- css={{
- position: "relative",
- height: "100%",
- // z-index needed for page settings animation
- zIndex: 1,
- flexGrow: 1,
- background: theme.colors.backgroundPanel,
- }}
- direction="column"
- >
+ <Root>
<Header
title="Pages"
suffix={
@@ -308,7 +297,7 @@ const PagesPanel = ({
}}
/>
</Box>
- </Flex>
+ </Root>
);
};
@@ -420,21 +409,23 @@ export const TabContent = ({ onSetActiveTab }: TabContentProps) => {
editingItemId={editingItemId}
/>
- {editingItemId && (
- <SettingsPanel isOpen>
- {isFolder(editingItemId, pages.folders) ? (
- <FolderEditor
- editingFolderId={editingItemId}
- setEditingFolderId={$editingPagesItemId.set}
- />
- ) : (
- <PageEditor
- editingPageId={editingItemId}
- setEditingPageId={$editingPagesItemId.set}
- />
- )}
- </SettingsPanel>
- )}
+ <ExtendedPanel isOpen={editingItemId !== undefined}>
+ {editingItemId !== undefined && (
+ <>
+ {isFolder(editingItemId, pages.folders) ? (
+ <FolderEditor
+ editingFolderId={editingItemId}
+ setEditingFolderId={$editingPagesItemId.set}
+ />
+ ) : (
+ <PageEditor
+ editingPageId={editingItemId}
+ setEditingPageId={$editingPagesItemId.set}
+ />
+ )}
+ </>
+ )}
+ </ExtendedPanel>
</>
);
};
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/settings-panel.tsx b/apps/builder/app/builder/features/sidebar-left/shared/extended-panel.tsx
similarity index 97%
rename from apps/builder/app/builder/features/sidebar-left/panels/pages/settings-panel.tsx
rename to apps/builder/app/builder/features/sidebar-left/shared/extended-panel.tsx
index e5dfa44ead..3a29eda70c 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/settings-panel.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/shared/extended-panel.tsx
@@ -16,6 +16,7 @@ const CollapsibleRoot = styled(Collapsible.Root, {
display: "flex",
flexDirection: "column",
marginLeft: 1,
+ zIndex: -1,
});
const openKeyframes = keyframes({
@@ -53,7 +54,7 @@ const CollapsibleContent = styled(Collapsible.Content, {
},
});
-export const SettingsPanel = ({
+export const ExtendedPanel = ({
children,
isOpen,
}: {
diff --git a/apps/builder/app/builder/features/sidebar-left/header.tsx b/apps/builder/app/builder/features/sidebar-left/shared/panel.tsx
similarity index 61%
rename from apps/builder/app/builder/features/sidebar-left/header.tsx
rename to apps/builder/app/builder/features/sidebar-left/shared/panel.tsx
index d70f47954f..668067b25f 100644
--- a/apps/builder/app/builder/features/sidebar-left/header.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/shared/panel.tsx
@@ -4,8 +4,11 @@ import {
Separator,
PanelTitle,
TitleSuffixSpacer,
+ Flex,
+ theme,
} from "@webstudio-is/design-system";
import { CrossIcon } from "@webstudio-is/icons";
+import { forwardRef, type ComponentProps } from "react";
type HeaderProps = {
title: string;
@@ -39,3 +42,23 @@ export const CloseButton = ({
/>
</Tooltip>
);
+
+export const Root = forwardRef<HTMLDivElement, ComponentProps<typeof Flex>>(
+ (props, ref) => {
+ return (
+ <Flex
+ css={{
+ position: "relative",
+ height: "100%",
+ flexGrow: 1,
+ background: theme.colors.backgroundPanel,
+ }}
+ direction="column"
+ ref={ref}
+ {...props}
+ />
+ );
+ }
+);
+
+Root.displayName = "Root";
diff --git a/apps/builder/app/builder/shared/html-editor.tsx b/apps/builder/app/builder/shared/html-editor.tsx
index 69fdd9cd87..def46fc4e3 100644
--- a/apps/builder/app/builder/shared/html-editor.tsx
+++ b/apps/builder/app/builder/shared/html-editor.tsx
@@ -74,9 +74,6 @@ const wrapperStyle = css({
minHeight: 160,
maxHeight: 320,
},
- "&:hover": {
- "--ws-code-editor-dialog-maximize-icon-display": "block",
- },
});
export const HtmlEditor = forwardRef<
@@ -126,6 +123,7 @@ export const HtmlEditor = forwardRef<
return (
<div className={wrapperStyle()} ref={ref}>
<CodeEditor
+ title={title}
extensions={extensions}
readOnly={readOnly}
invalid={invalid}
diff --git a/apps/builder/app/dashboard/dashboard.stories.tsx b/apps/builder/app/dashboard/dashboard.stories.tsx
index 14bd8c16ce..d55349a063 100644
--- a/apps/builder/app/dashboard/dashboard.stories.tsx
+++ b/apps/builder/app/dashboard/dashboard.stories.tsx
@@ -58,6 +58,7 @@ export const WithProjects: ComponentStory<typeof Dashboard> = () => {
isPublished: false,
latestBuild: null,
previewImageAsset: null,
+ marketplaceApprovalStatus: "UNLISTED" as const,
},
];
const router = createRouter(
diff --git a/apps/builder/app/routes/builder.marketplace.$method.tsx b/apps/builder/app/routes/builder.marketplace.$method.tsx
new file mode 100644
index 0000000000..9f1e65bb34
--- /dev/null
+++ b/apps/builder/app/routes/builder.marketplace.$method.tsx
@@ -0,0 +1,22 @@
+import type { ActionArgs } from "@remix-run/node";
+import { findAuthenticatedUser } from "~/services/auth.server";
+import { createContext } from "~/shared/context.server";
+import { marketplaceRouter } from "~/shared/marketplace/router";
+import { handleTrpcRemixAction } from "~/shared/remix/trpc-remix-request.server";
+
+export const action = async ({ request, params }: ActionArgs) => {
+ const authenticatedUser = await findAuthenticatedUser(request);
+ if (authenticatedUser === null) {
+ throw new Error("Not authenticated");
+ }
+ const context = await createContext(request);
+
+ return await handleTrpcRemixAction({
+ request,
+ params,
+ router: marketplaceRouter,
+ context,
+ });
+};
+
+export const loader = action;
diff --git a/apps/builder/app/routes/rest.patch.ts b/apps/builder/app/routes/rest.patch.ts
index 5fd9636688..e1e2e1771d 100644
--- a/apps/builder/app/routes/rest.patch.ts
+++ b/apps/builder/app/routes/rest.patch.ts
@@ -19,7 +19,7 @@ import {
Resources,
Resource,
} from "@webstudio-is/sdk";
-import type { Build } from "@webstudio-is/project-build";
+import { type Build, MarketplaceProduct } from "@webstudio-is/project-build";
import {
parsePages,
parseStyleSourceSelections,
@@ -29,6 +29,8 @@ import {
serializeStyles,
parseData,
serializeData,
+ parseConfig,
+ serializeConfig,
} from "@webstudio-is/project-build/index.server";
import { patchAssets } from "@webstudio-is/asset-uploader/index.server";
import type { Project } from "@webstudio-is/project";
@@ -106,6 +108,7 @@ export const action = async ({ request }: ActionArgs) => {
styleSources?: StyleSources;
styleSourceSelections?: StyleSourceSelections;
styles?: Styles;
+ marketplaceProduct?: MarketplaceProduct;
} = {};
let previewImageAssetId: string | null | undefined = undefined;
@@ -207,6 +210,19 @@ export const action = async ({ request }: ActionArgs) => {
continue;
}
+ if (namespace === "marketplaceProduct") {
+ const marketplaceProduct =
+ buildData.marketplaceProduct ??
+ parseConfig<MarketplaceProduct>(build.marketplaceProduct);
+
+ buildData.marketplaceProduct = applyPatches(
+ marketplaceProduct,
+ patches
+ );
+
+ continue;
+ }
+
return { errors: `Unknown namespace "${namespace}"` };
}
}
@@ -279,6 +295,12 @@ export const action = async ({ request }: ActionArgs) => {
dbBuildData.styles = serializeStyles(buildData.styles);
}
+ if (buildData.marketplaceProduct) {
+ dbBuildData.marketplaceProduct = serializeConfig<MarketplaceProduct>(
+ MarketplaceProduct.parse(buildData.marketplaceProduct)
+ );
+ }
+
const { count } = await prisma.build.updateMany({
data: dbBuildData,
where: {
diff --git a/apps/builder/app/shared/marketplace/db.server.ts b/apps/builder/app/shared/marketplace/db.server.ts
new file mode 100644
index 0000000000..826d6f98e7
--- /dev/null
+++ b/apps/builder/app/shared/marketplace/db.server.ts
@@ -0,0 +1,92 @@
+import { prisma } from "@webstudio-is/prisma-client";
+import { MarketplaceProduct } from "@webstudio-is/project-build";
+import type { BuildData, MarketplaceOverviewItem } from "./types";
+import {
+ loadProdBuildByProjectId,
+ parseConfig,
+} from "@webstudio-is/project-build/index.server";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { Project } from "@webstudio-is/project";
+import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";
+
+export const getBuildProdData = async (
+ { projectId }: { projectId: Project["id"] },
+ context: AppContext
+): Promise<BuildData> => {
+ const build = await loadProdBuildByProjectId(projectId, {
+ marketplaceApprovalStatus: "APPROVED",
+ });
+
+ const assets = await loadAssetsByProject(projectId, context);
+
+ return {
+ assets: assets.map((asset) => [asset.id, asset]),
+ build,
+ };
+};
+
+export const getItems = async (): Promise<Array<MarketplaceOverviewItem>> => {
+ const projects = await prisma.project.findMany({
+ where: {
+ isDeleted: false,
+ marketplaceApprovalStatus: "APPROVED",
+ NOT: {
+ latestBuild: null,
+ },
+ },
+ select: {
+ id: true,
+ latestBuild: {
+ select: {
+ build: {
+ select: { id: true, marketplaceProduct: true },
+ },
+ },
+ },
+ },
+ });
+ const items = [];
+
+ for (const project of projects) {
+ if (project.latestBuild === null) {
+ continue;
+ }
+
+ const parsedProduct = MarketplaceProduct.safeParse(
+ parseConfig(project.latestBuild.build.marketplaceProduct)
+ );
+
+ if (parsedProduct.success === false) {
+ console.error(parsedProduct.error.formErrors.fieldErrors);
+ continue;
+ }
+
+ items.push({
+ projectId: project.id,
+ ...parsedProduct.data,
+ });
+ }
+ const assetIds = items
+ .map((item) => item.thumbnailAssetId)
+ .filter((value): value is string => value != null);
+
+ const assets =
+ assetIds.length > 0
+ ? await prisma.asset.findMany({
+ where: {
+ id: {
+ in: assetIds,
+ },
+ },
+ })
+ : [];
+
+ return items.map((item) => {
+ return {
+ ...item,
+ thumbnailAssetName: assets.find(
+ (asset) => asset.id === item.thumbnailAssetId
+ )?.name,
+ };
+ });
+};
diff --git a/apps/builder/app/shared/marketplace/router.ts b/apps/builder/app/shared/marketplace/router.ts
new file mode 100644
index 0000000000..18f8844b3f
--- /dev/null
+++ b/apps/builder/app/shared/marketplace/router.ts
@@ -0,0 +1,20 @@
+import { z } from "zod";
+import { procedure, router } from "../trpc";
+import { getItems, getBuildProdData } from "./db.server";
+
+export const marketplaceRouter = router({
+ getItems: procedure.query(async () => {
+ return await getItems();
+ }),
+ getBuildData: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ })
+ )
+ .query(async ({ input, ctx }) => {
+ return await getBuildProdData(input, ctx);
+ }),
+});
+
+export type MarketplaceRouter = typeof marketplaceRouter;
diff --git a/apps/builder/app/shared/marketplace/types.ts b/apps/builder/app/shared/marketplace/types.ts
new file mode 100644
index 0000000000..19536d6466
--- /dev/null
+++ b/apps/builder/app/shared/marketplace/types.ts
@@ -0,0 +1,13 @@
+import type { Project } from "@webstudio-is/prisma-client";
+import type { Build, MarketplaceProduct } from "@webstudio-is/project-build";
+import type { Asset } from "@webstudio-is/sdk";
+
+export type MarketplaceOverviewItem = MarketplaceProduct & {
+ projectId: Project["id"];
+ thumbnailAssetName?: Asset["name"];
+};
+
+export type BuildData = {
+ build: Build;
+ assets: Array<[Asset["id"], Asset]>;
+};
diff --git a/apps/builder/app/shared/nano-states/nano-states.ts b/apps/builder/app/shared/nano-states/nano-states.ts
index 32dc70393e..92ce3565c0 100644
--- a/apps/builder/app/shared/nano-states/nano-states.ts
+++ b/apps/builder/app/shared/nano-states/nano-states.ts
@@ -27,6 +27,7 @@ import { $instances, $selectedInstanceSelector } from "./instances";
import { $selectedPage } from "./pages";
import type { UnitSizes } from "~/builder/features/style-panel/shared/css-value-input/convert-units";
import type { Project } from "@webstudio-is/project";
+import type { MarketplaceProduct } from "@webstudio-is/project-build";
export const $project = atom<Project | undefined>();
@@ -313,3 +314,5 @@ export type DragAndDropState = {
export const $dragAndDropState = atom<DragAndDropState>({
isDragging: false,
});
+
+export const $marketplaceProduct = atom<undefined | MarketplaceProduct>();
diff --git a/apps/builder/app/shared/router-utils/path-utils.ts b/apps/builder/app/shared/router-utils/path-utils.ts
index 8b8635c197..851fabfbb6 100644
--- a/apps/builder/app/shared/router-utils/path-utils.ts
+++ b/apps/builder/app/shared/router-utils/path-utils.ts
@@ -176,3 +176,6 @@ export const restAi = (subEndpoint?: "detect" | "audio/transcriptions") =>
typeof subEndpoint === "string" ? `/rest/ai/${subEndpoint}` : "/rest/ai";
export const restResourcesLoader = () => `/rest/resources-loader`;
+
+export const marketplacePath = (method: string) =>
+ `/builder/marketplace/${method}`;
diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts
index 186a12a0c7..eacf65e55f 100644
--- a/apps/builder/app/shared/sync/sync-stores.ts
+++ b/apps/builder/app/shared/sync/sync-stores.ts
@@ -35,6 +35,7 @@ import {
$selectedInstanceStates,
$resources,
$resourceValues,
+ $marketplaceProduct,
} from "~/shared/nano-states";
import { $ephemeralStyles } from "~/canvas/stores";
@@ -84,6 +85,7 @@ export const registerContainers = () => {
serverSyncStore.register("dataSources", $dataSources);
serverSyncStore.register("resources", $resources);
serverSyncStore.register("assets", $assets);
+ serverSyncStore.register("marketplaceProduct", $marketplaceProduct);
// synchronize whole states
clientStores.set("project", $project);
clientStores.set("dataSourceVariables", $dataSourceVariables);
diff --git a/apps/builder/app/shared/trpc.ts b/apps/builder/app/shared/trpc.ts
new file mode 100644
index 0000000000..570d5022d9
--- /dev/null
+++ b/apps/builder/app/shared/trpc.ts
@@ -0,0 +1,6 @@
+import { initTRPC } from "@trpc/server";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+
+export const { router, procedure, middleware, mergeRouters } = initTRPC
+ .context<AppContext>()
+ .create();
diff --git a/packages/design-system/src/components/checkbox.tsx b/packages/design-system/src/components/checkbox.tsx
index af44774ddf..159aa5edd4 100644
--- a/packages/design-system/src/components/checkbox.tsx
+++ b/packages/design-system/src/components/checkbox.tsx
@@ -98,6 +98,7 @@ export const Checkbox = forwardRef(
Checkbox.displayName = "Checkbox";
export const CheckboxAndLabel = styled("div", {
+ boxSizing: "border-box",
display: "flex",
alignItems: "center",
gap: theme.spacing[3],
diff --git a/packages/design-system/src/components/primitives/list.tsx b/packages/design-system/src/components/primitives/list.tsx
index fddb9a06a5..ec4e0a2fb4 100644
--- a/packages/design-system/src/components/primitives/list.tsx
+++ b/packages/design-system/src/components/primitives/list.tsx
@@ -1,4 +1,4 @@
-import { usePress } from "@react-aria/interactions";
+import { usePress, type PressEvent } from "@react-aria/interactions";
import { Slot, type SlotProps } from "@radix-ui/react-slot";
import { ArrowFocus } from "./arrow-focus";
@@ -24,7 +24,7 @@ type ListItemProps = SlotProps & {
state?: "disabled" | "selected";
current?: boolean;
index?: number;
- onSelect?: () => void;
+ onSelect?: (event: PressEvent) => void;
asChild?: boolean;
};
@@ -43,8 +43,8 @@ export const ListItem = ({
? { "data-state": "selected" }
: undefined;
const { pressProps } = usePress({
- onPress() {
- onSelect?.();
+ onPress(event) {
+ onSelect?.(event);
},
});
const Component = asChild ? Slot : "li";
diff --git a/packages/design-system/src/components/text-area.tsx b/packages/design-system/src/components/text-area.tsx
index 806113b440..45366c193f 100644
--- a/packages/design-system/src/components/text-area.tsx
+++ b/packages/design-system/src/components/text-area.tsx
@@ -122,13 +122,14 @@ export const TextArea = forwardRef(
grow,
autoGrow,
variant = "regular",
+ defaultValue,
...props
}: Props,
ref: Ref<HTMLTextAreaElement>
) => {
const [textValue, setTextValue] = useControllableState({
prop: value,
- defaultProp: props.defaultValue,
+ defaultProp: defaultValue,
onChange,
});
diff --git a/packages/prisma-client/prisma/migrations/20240227150630_marketplace/migration.sql b/packages/prisma-client/prisma/migrations/20240227150630_marketplace/migration.sql
new file mode 100644
index 0000000000..626ed80588
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20240227150630_marketplace/migration.sql
@@ -0,0 +1,14 @@
+-- CreateEnum
+CREATE TYPE "MarketplaceApprovalStatus" AS ENUM ('UNLISTED', 'PENDING', 'APPROVED', 'REJECTED');
+
+-- AlterTable
+ALTER TABLE
+ "Build"
+ADD
+ COLUMN "marketplaceProduct" TEXT NOT NULL DEFAULT '{}';
+
+-- AlterTable
+ALTER TABLE
+ "Project"
+ADD
+ COLUMN "marketplaceApprovalStatus" "MarketplaceApprovalStatus" NOT NULL DEFAULT 'UNLISTED';
\ No newline at end of file
diff --git a/packages/prisma-client/prisma/migrations/20240229133316_add-approval-status/migration.sql b/packages/prisma-client/prisma/migrations/20240229133316_add-approval-status/migration.sql
new file mode 100644
index 0000000000..9461ef9ffe
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20240229133316_add-approval-status/migration.sql
@@ -0,0 +1,18 @@
+-- Drop DashboardProject View
+DROP VIEW IF EXISTS "DashboardProject";
+
+-- Update DashboardProject View
+CREATE VIEW "DashboardProject" AS
+SELECT
+ *,
+ EXISTS (
+ SELECT
+ 1
+ from
+ "Build"
+ WHERE
+ "Build"."projectId" = "Project".id
+ AND "Build"."deployment" IS NOT NULL
+ ) AS "isPublished"
+FROM
+ "Project";
diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prisma
index 6dcb0acb33..8637fdda53 100644
--- a/packages/prisma-client/prisma/schema.prisma
+++ b/packages/prisma-client/prisma/schema.prisma
@@ -137,20 +137,21 @@ 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[]
- previewImageAsset Asset? @relation(fields: [previewImageAssetId, id], references: [id, projectId])
- previewImageAssetId String?
+ 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?
+ marketplaceApprovalStatus MarketplaceApprovalStatus @default(UNLISTED)
@@unique([id, isDeleted])
@@unique([domain, isDeleted])
@@ -163,6 +164,13 @@ enum PublishStatus {
FAILED
}
+enum MarketplaceApprovalStatus {
+ UNLISTED
+ PENDING
+ APPROVED
+ REJECTED
+}
+
model Build {
id String @unique @default(uuid())
version Int @default(0)
@@ -182,10 +190,13 @@ model Build {
dataSources String @default("[]")
resources String @default("[]")
instances String @default("[]")
+ marketplaceProduct String @default("{}")
deployment String?
publishStatus PublishStatus @default(PENDING)
+ latestBuildPerProject LatestBuildPerProject?
+
@@id([id, projectId])
}
@@ -288,6 +299,7 @@ view LatestBuildPerProjectDomain {
view LatestBuildPerProject {
buildId String
+ build Build @relation(fields: [buildId, projectId], references: [id, projectId])
projectId String
domain String
@@ -298,17 +310,19 @@ view LatestBuildPerProject {
updatedAt DateTime
@@id([projectId, domain])
+ @@unique([buildId, projectId])
}
// Dashboard
view DashboardProject {
- 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
+ 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
+ marketplaceApprovalStatus MarketplaceApprovalStatus @default(UNLISTED)
}
diff --git a/packages/project-build/src/db/build.ts b/packages/project-build/src/db/build.ts
index 23f10e8fd2..d3c317007d 100644
--- a/packages/project-build/src/db/build.ts
+++ b/packages/project-build/src/db/build.ts
@@ -3,6 +3,7 @@
import { nanoid } from "nanoid";
import {
type Build as DbBuild,
+ type $Enums,
prisma,
Prisma,
} from "@webstudio-is/prisma-client";
@@ -29,6 +30,7 @@ import { parseStyleSourceSelections } from "./style-source-selections";
import { parseDeployment, serializeDeployment } from "./deployment";
import { parsePages, serializePages } from "./pages";
import { createDefaultPages } from "../shared/pages-utils";
+import type { MarketplaceProduct } from "..";
export const parseData = <Type extends { id: string }>(
string: string
@@ -44,6 +46,14 @@ export const serializeData = <Type extends { id: string }>(
return JSON.stringify(dataSourcesList);
};
+export const parseConfig = <Type>(string: string): Type => {
+ return JSON.parse(string);
+};
+
+export const serializeConfig = <Type>(data: Type) => {
+ return JSON.stringify(data);
+};
+
const parseBuild = async (build: DbBuild): Promise<Build> => {
// eslint-disable-next-line no-console
console.time("parseBuild");
@@ -71,8 +81,10 @@ const parseBuild = async (build: DbBuild): Promise<Build> => {
resources: Array.from(parseData<Resource>(build.resources)),
instances: Array.from(parseData<Instance>(build.instances)),
deployment,
- } satisfies Data["build"];
-
+ marketplaceProduct: parseConfig<MarketplaceProduct>(
+ build.marketplaceProduct
+ ),
+ } satisfies Data["build"] & { marketplaceProduct: MarketplaceProduct };
return result;
} finally {
// eslint-disable-next-line no-console
@@ -108,6 +120,34 @@ export const loadBuildByProjectId = async (
return parseBuild(build);
};
+export const loadProdBuildByProjectId = async (
+ projectId: Build["projectId"],
+ where: {
+ marketplaceApprovalStatus?: $Enums.MarketplaceApprovalStatus;
+ }
+): Promise<Build> => {
+ const projectData = await prisma.project.findUnique({
+ where: {
+ ...where,
+ id_isDeleted: { id: projectId, isDeleted: false },
+ },
+ select: {
+ latestBuild: {
+ select: {
+ build: true,
+ },
+ },
+ },
+ });
+
+ const build = projectData?.latestBuild?.build;
+ if (build === undefined) {
+ throw new Error("Prod build not found");
+ }
+
+ return parseBuild(build);
+};
+
const createNewPageInstances = (): Build["instances"] => {
const instanceId = nanoid();
return [
diff --git a/packages/project-build/src/index.ts b/packages/project-build/src/index.ts
index 6cc51677ee..3a7df2eeef 100644
--- a/packages/project-build/src/index.ts
+++ b/packages/project-build/src/index.ts
@@ -1,2 +1,3 @@
export * from "./types";
export * from "./shared/pages-utils";
+export * from "./shared/marketplace";
diff --git a/packages/project-build/src/shared/marketplace.ts b/packages/project-build/src/shared/marketplace.ts
new file mode 100644
index 0000000000..f6735689c0
--- /dev/null
+++ b/packages/project-build/src/shared/marketplace.ts
@@ -0,0 +1,19 @@
+import { z } from "zod";
+
+const Base = z.object({
+ name: z.string().min(2).trim(),
+ thumbnailAssetId: z.string(),
+ author: z.string().min(2).trim(),
+ email: z.string().email().trim(),
+ website: z.union([z.string().url().trim().optional(), z.literal("")]),
+ issues: z.union([z.string().url().trim().optional(), z.literal("")]),
+ description: z.string().trim().min(10),
+});
+
+const TemplatesProduct = Base.extend({
+ category: z.literal("sectionTemplates"),
+});
+
+// Will add an AppProduct later.
+export const MarketplaceProduct = TemplatesProduct;
+export type MarketplaceProduct = z.infer<typeof MarketplaceProduct>;
diff --git a/packages/project-build/src/types.ts b/packages/project-build/src/types.ts
index 4aed25390a..d22e4cbb2a 100644
--- a/packages/project-build/src/types.ts
+++ b/packages/project-build/src/types.ts
@@ -11,6 +11,7 @@ import type {
DataSource,
Resource,
} from "@webstudio-is/sdk";
+import type { MarketplaceProduct } from "./shared/marketplace";
export type Build = {
id: string;
@@ -28,4 +29,5 @@ export type Build = {
dataSources: [DataSource["id"], DataSource][];
resources: [Resource["id"], Resource][];
deployment?: Deployment | undefined;
+ marketplaceProduct: MarketplaceProduct;
};
diff --git a/packages/project/src/db/project.ts b/packages/project/src/db/project.ts
index f828471fe5..40d327c0cb 100644
--- a/packages/project/src/db/project.ts
+++ b/packages/project/src/db/project.ts
@@ -10,7 +10,7 @@ import {
createBuild,
cloneBuild,
} from "@webstudio-is/project-build/index.server";
-import { Project, Title } from "../shared/schema";
+import { MarketplaceApprovalStatus, Project, Title } from "../shared/schema";
import { generateDomain, validateProjectDomain } from "./project-domain";
export const loadById = async (
@@ -246,3 +246,27 @@ export const updateDomain = async (
throw error;
}
};
+
+export const setMarketplaceApprovalStatus = async (
+ {
+ projectId,
+ marketplaceApprovalStatus,
+ }: {
+ projectId: Project["id"];
+ marketplaceApprovalStatus: MarketplaceApprovalStatus;
+ },
+ context: AppContext
+) => {
+ if (
+ marketplaceApprovalStatus === "APPROVED" ||
+ marketplaceApprovalStatus === "REJECTED"
+ ) {
+ throw new Error("User can't approve or reject");
+ }
+ await assertEditPermission(projectId, context);
+
+ return await prisma.project.update({
+ where: { id: projectId },
+ data: { marketplaceApprovalStatus },
+ });
+};
diff --git a/packages/project/src/shared/schema.ts b/packages/project/src/shared/schema.ts
index cde10b5fd0..860ef37eaf 100644
--- a/packages/project/src/shared/schema.ts
+++ b/packages/project/src/shared/schema.ts
@@ -9,6 +9,17 @@ export const Title = z
`Minimum ${MIN_TITLE_LENGTH} characters required`
);
+export const MarketplaceApprovalStatus = z.enum([
+ "UNLISTED",
+ "PENDING",
+ "APPROVED",
+ "REJECTED",
+]);
+
+export type MarketplaceApprovalStatus = z.infer<
+ typeof MarketplaceApprovalStatus
+>;
+
export const Project = z.object({
id: z.string(),
title: Title,
@@ -32,6 +43,7 @@ export const Project = z.object({
})
.nullable()
),
+ marketplaceApprovalStatus: MarketplaceApprovalStatus,
});
export type Project = z.infer<typeof Project>;
diff --git a/packages/project/src/trpc/project-router.ts b/packages/project/src/trpc/project-router.ts
index 7e8a632e57..5d5706204b 100644
--- a/packages/project/src/trpc/project-router.ts
+++ b/packages/project/src/trpc/project-router.ts
@@ -1,7 +1,7 @@
import * as db from "../db";
import { z } from "zod";
import { router, procedure } from "./trpc";
-import { Title } from "../shared/schema";
+import { MarketplaceApprovalStatus, Title } from "../shared/schema";
export const projectRouter = router({
rename: procedure
@@ -24,19 +24,23 @@ export const projectRouter = router({
clone: procedure
.input(z.object({ projectId: z.string(), title: z.optional(z.string()) }))
.mutation(async ({ input, ctx }) => {
- return await db.project.clone(
- {
- projectId: input.projectId,
- title: input.title,
- },
- ctx
- );
+ return await db.project.clone(input, ctx);
}),
create: procedure
.input(z.object({ title: Title }))
.mutation(async ({ input, ctx }) => {
return await db.project.create(input, ctx);
}),
+ setMarketplaceApprovalStatus: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ marketplaceApprovalStatus: MarketplaceApprovalStatus,
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ return await db.project.setMarketplaceApprovalStatus(input, ctx);
+ }),
});
export type ProjectRouter = typeof projectRouter;
diff --git a/packages/react-sdk/src/components/component-meta.ts b/packages/react-sdk/src/components/component-meta.ts
index 67d6ceaeb0..e049d087bf 100644
--- a/packages/react-sdk/src/components/component-meta.ts
+++ b/packages/react-sdk/src/components/component-meta.ts
@@ -25,7 +25,6 @@ export const componentCategories = [
"forms",
"radix",
"hidden",
- "utilities",
] as const;
export const stateCategories = ["states", "component-states"] as const;