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.

Merge branch 'main' into 252-fonts-manager-and-fonts-selector

Oleg Isonenc54497b95f4b
diff --cc apps/designer/app/designer/features/style-panel/controls/font-family/font-family-control.tsx
index c64ce4a5a0,c2c2b9ac36..46deacc0fb
--- a/apps/designer/app/designer/features/style-panel/controls/font-family/font-family-control.tsx
+++ b/apps/designer/app/designer/features/style-panel/controls/font-family/font-family-control.tsx
@@@ -1,18 -1,26 +1,10 @@@
-import {
- TextField,
- Popover,
- PopoverTrigger,
- PopoverContent,
- PopoverHeader,
- PopoverPortal,
-} from "@webstudio-is/design-system";
+import { Grid, TextField } from "@webstudio-is/design-system";
+import { FontsManager } from "~/designer/shared/fonts-manager";
import type { ControlProps } from "../../style-sections";
import { getFinalValue } from "../../shared/get-final-value";
-import { PANEL_WIDTH } from "~/designer/shared/constants";
-import { MutableRefObject, useRef, useState } from "react";
-import { FontsManager } from "~/designer/shared/fonts-manager";
-
-const usePickerSideOffset = (
- isOpen: boolean
-): [MutableRefObject<HTMLInputElement | null>, number] => {
- const ref = useRef<HTMLInputElement | null>(null);
- const sideOffset =
- isOpen && ref.current !== null ? PANEL_WIDTH - ref.current.offsetWidth : 0;
- return [ref, sideOffset];
-};
+import { PropertyName } from "../../shared/property-name";
+import { ValuePickerPopover } from "../../shared/value-picker-popover";
- // @todo get rid of this custom styling, it should be part of the design system and/or reused across style panel
- const textFieldStyle = {
- paddingLeft: "calc($sizes$1 + $nudge$3)",
- textAlign: "left",
- height: "$6",
- fontWeight: "500",
- };
-
export const FontFamilyControl = ({
currentStyle,
inheritedStyle,
@@@ -28,25 -38,26 +20,15 @@@
if (value === undefined) return null;
- //const setValue = setProperty(styleConfig.property);
+ const setValue = setProperty(styleConfig.property);
return (
- <Grid columns={2}>
- <PropertyName property={styleConfig.property} label={styleConfig.label} />
- <ValuePickerPopover
- title="Fonts"
- content={
- <FontsManager value={String(value.value)} onChange={setValue} />
- }
- >
- {/* @todo this should be part of the design system, probably a varian="button" */}
- <Popover open={isOpen} onOpenChange={setIsOpen}>
- <PopoverTrigger asChild>
-- <TextField
- css={textFieldStyle}
- ref={textFieldRef}
-- spellCheck={false}
- readOnly
-- defaultValue={value.value}
- onClick={() => {
- setIsOpen(true);
- }}
-- />
- </ValuePickerPopover>
- </Grid>
- </PopoverTrigger>
- <PopoverPortal>
- <PopoverContent sideOffset={sideOffset} side="right" hideArrow>
- <PopoverHeader title="Fonts" />
- <FontsManager />
- </PopoverContent>
- </PopoverPortal>
- </Popover>
++ <ValuePickerPopover
++ title="Fonts"
++ content={<FontsManager value={String(value.value)} onChange={setValue} />}
++ >
++ {/* @todo this should be part of the design system, probably a varian="button" */}
++ <TextField defaultValue={value.value} />
++ </ValuePickerPopover>
);
};
diff --cc apps/designer/app/designer/features/style-panel/shared/configs.ts
index 7495d10cad,ce0cec3a23..ca8fcfa658
--- a/apps/designer/app/designer/features/style-panel/shared/configs.ts
+++ b/apps/designer/app/designer/features/style-panel/shared/configs.ts
@@@ -47,15 -47,7 +47,13 @@@ type BaseStyleConfig =
};
// @todo make it use actual list of controls
-export type Control = "Text" | "Color" | "Menu" | "Select" | "FontFamily";
+export type Control =
- | "Spacing"
+ | "Text"
+ | "Color"
+ | "Menu"
+ | "Select"
- | "Empty"
+ | "FontFamily"
+ | "Image";
export type StyleConfig = BaseStyleConfig & {
control: Control;
@@@ -68,35 -60,10 +66,13 @@@ const getControl = (property: StyleProp
if (property.toLocaleLowerCase().includes("color")) {
return "Color";
}
- // Spacing properties is more narrow than StyleProperty,
- // so we have to widen it to be able to run .includes.
- // @todo do better
- const spacing = categories.spacing
- .properties as unknown as Array<StyleProperty>;
- if (spacing.includes(property)) {
- return "Spacing";
- }
switch (property) {
- case "display": {
- return "Select";
- }
- case "flexDirection":
- case "flexWrap":
- case "alignItems":
- case "justifyItems":
- case "justifyContent":
- case "alignContent": {
- return "Menu";
- }
- case "placeContent": {
- return "Empty";
- }
case "fontFamily": {
- return isFeatureEnabled("assets") ? "FontFamily" : "Text";
+ return isFeatureEnabled("fonts") ? "FontFamily" : "Text";
+ }
+ case "backgroundImage": {
+ return isFeatureEnabled("assets") ? "Image" : "Text";
}
}
diff --cc apps/designer/app/designer/features/style-panel/style-sections.tsx
index c9643bc000,d2ea47e381..265a52184d
--- a/apps/designer/app/designer/features/style-panel/style-sections.tsx
+++ b/apps/designer/app/designer/features/style-panel/style-sections.tsx
@@@ -17,8 -16,8 +16,9 @@@ import
FontFamilyControl,
} from "./controls";
import { ShowMore } from "./shared/show-more";
- import { LayoutSection } from "./sections";
+ import { LayoutSection, SpacingSection } from "./sections";
+import { BackgroundImageControl } from "./controls/background-image/background-image-control";
+ import { PropertyName } from "./shared/property-name";
export type PropertyProps = {
property: StyleProperty;
@@@ -136,7 -145,5 +146,6 @@@ const controls:
Text: TextControl,
Color: ColorControl,
Select: SelectControl,
- Spacing: SpacingControl,
FontFamily: FontFamilyControl,
+ Image: BackgroundImageControl,
};
diff --cc apps/designer/app/designer/shared/fonts-manager/fonts-manager.tsx
index 258b08522c,b4586902e2..e170a9cf06
--- a/apps/designer/app/designer/shared/fonts-manager/fonts-manager.tsx
+++ b/apps/designer/app/designer/shared/fonts-manager/fonts-manager.tsx
@@@ -1,89 -1,10 +1,133 @@@
-import { Flex, Box } from "@webstudio-is/design-system";
-import { AssetUpload, useAssets } from "~/designer/shared/assets";
+import type { Asset } from "@webstudio-is/asset-uploader";
+import {
+ Flex,
+ Box,
+ Combobox,
+ ComboboxListboxItem,
+ TextField,
+ DropdownMenu,
+ DropdownMenuTrigger,
+ IconButton,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ Text,
+ DropdownMenuPortal,
++ useCombobox,
++ comboboxStateChangeTypes,
+} from "@webstudio-is/design-system";
+import { AssetUpload, PreviewAsset, useAssets } from "~/designer/shared/assets";
+import { SYSTEM_FONTS } from "@webstudio-is/fonts";
- import { DotsHorizontalIcon } from "@webstudio-is/icons";
++import { DotsHorizontalIcon, MagnifyingGlassIcon } from "@webstudio-is/icons";
++import { useCallback, useState } from "react";
+
+const getItems = (
+ assets: Array<Asset | PreviewAsset>
+): Array<{ label: string }> => {
+ const system = Array.from(SYSTEM_FONTS.keys()).map((label) => ({ label }));
+ // We can have 2+ assets with the same family name, so we use a map to dedupe.
+ const uploaded = new Map();
+ for (const asset of assets) {
+ // @todo need to teach ts the right type from useAssets
+ if ("meta" in asset && "family" in asset.meta) {
+ uploaded.set(asset.meta.family, { label: asset.meta.family });
+ }
+ }
+ return [...system, ...uploaded.values()];
+};
+
+const ItemMenu = ({ onDelete }: { onDelete: () => void }) => {
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton aria-label="Font menu button">
+ <DotsHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ onSelect={() => {
+ onDelete();
+ }}
+ >
+ <Text>Delete font</Text>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenu>
+ );
+};
+
+type FontsManagerProps = {
+ value: string;
+ onChange: (value: string) => void;
+};
+
+export const FontsManager = ({ value, onChange }: FontsManagerProps) => {
+ const { assets, onSubmitAssets, onActionData, onDelete } = useAssets("font");
- const items = getItems(assets);
+
+ const handleDelete = (family: string) => {
+ // One family may have multiple assets for different formats, so we need to delete them all.
+ const ids = assets
+ .filter(
+ (asset) =>
+ // @todo need to teach ts the right type from useAssets
+ "meta" in asset &&
+ "family" in asset.meta &&
+ asset.meta.family === family
+ )
+ .map((asset) => asset.id);
+ onDelete(ids);
+ };
+
++ const stateReducer = useCallback((state, actionAndChanges) => {
++ const { type, changes } = actionAndChanges;
++ switch (type) {
++ // on item selection.
++ case comboboxStateChangeTypes.ItemClick:
++ case comboboxStateChangeTypes.InputKeyDownEnter:
++ case comboboxStateChangeTypes.InputBlur:
++ case comboboxStateChangeTypes.ControlledPropUpdatedSelectedItem:
++ return {
++ ...changes,
++ // if we have a selected item.
++ ...(changes.selectedItem && {
++ // we will set the input value to "" (empty string).
++ inputValue: "",
++ }),
++ };
++
++ // Remove "reset" action
++ case comboboxStateChangeTypes.InputKeyDownEscape: {
++ return {
++ ...state,
++ };
++ }
++
++ default:
++ return changes; // otherwise business as usual.
++ }
++ }, []);
++
++ const { items, getComboboxProps, getMenuProps, getItemProps, getInputProps } =
++ useCombobox({
++ items: getItems(assets),
++ value: { label: value },
++ itemToString: (item) => item?.label ?? "",
++ stateReducer,
++ onItemSelect: (value) => {
++ if (value !== null) {
++ onChange(value.label);
++ }
++ },
++ });
+
-export const FontsManager = () => {
- const { assets, onSubmitAssets, onActionData } = useAssets("font");
return (
- <Flex gap="3" direction="column" css={{ padding: "$1", paddingTop: "$2" }}>
+ <Flex
+ gap="3"
+ direction="column"
+ css={{ padding: "$1", paddingTop: "$2", height: 460, overflow: "hidden" }}
+ >
<Box css={{ padding: "$2" }}>
<AssetUpload
onSubmit={onSubmitAssets}
@@@ -91,33 -12,7 +135,32 @@@
type="font"
/>
</Box>
- {assets.map((asset) => asset.name)}
+
- <Combobox
- open
- name="prop"
- items={items}
- selectedItem={{ label: value }}
- onItemSelect={(value) => {
- onChange(value.label);
- }}
- renderTextField={({ inputProps: { value, ...inputProps } }) => (
- <TextField {...inputProps} placeholder="Search" />
- )}
- renderPopperContent={(props) => <>{props.children}</>}
- renderItem={(props) => (
- // @ts-expect-error temp
- <ComboboxListboxItem
- {...props}
- suffix={
- <ItemMenu
- onDelete={() => {
- handleDelete(props.item.label);
- }}
- />
- }
- />
- )}
- />
++ <Flex
++ {...getComboboxProps()}
++ css={{ flexDirection: "column", gap: "$3" }}
++ >
++ <TextField
++ type="search"
++ prefix={<MagnifyingGlassIcon />}
++ {...getInputProps({})}
++ />
++ <fieldset>
++ <legend>Choose an item</legend>
++ <Flex {...getMenuProps()} css={{ flexDirection: "column" }}>
++ {items.map((item, index) => {
++ return (
++ <ComboboxListboxItem
++ key={index}
++ {...getItemProps({ item, index })}
++ >
++ {item.label}
++ </ComboboxListboxItem>
++ );
++ })}
++ </Flex>
++ </fieldset>
++ </Flex>
</Flex>
);
};
diff --cc apps/designer/app/routes/$.tsx
index 0000000000,c72ca92da0..75c31ac3d5
mode 000000,100644..100644
--- a/apps/designer/app/routes/$.tsx
+++ b/apps/designer/app/routes/$.tsx
@@@ -1,0 -1,94 +1,94 @@@
+ import {
+ type LoaderFunction,
+ redirect,
+ MetaFunction,
+ json,
+ } from "@remix-run/node";
+ import { useLoaderData } from "@remix-run/react";
+ import { InstanceRoot, Root } from "@webstudio-is/react-sdk";
+ import { loadCanvasData, type CanvasData } from "~/shared/db";
+ import config from "~/config";
+ import { db } from "@webstudio-is/project/index.server";
+ import env, { Env } from "~/env.server";
+ import { sentryException } from "~/shared/sentry";
+ import { Canvas } from "~/canvas";
+ import { ErrorMessage } from "~/shared/error";
+ import { type BuildMode, getBuildParams } from "~/shared/router-utils";
+
+ type Data =
+ | (CanvasData & { env: Env; mode: BuildMode })
+ | { errors: string; env: Env };
+
+ export const meta: MetaFunction = ({ data }: { data: Data }) => {
+ if ("errors" in data) {
+ return { title: "Error" };
+ }
+ const { page } = data;
+ return { title: page.title, ...page.meta };
+ };
+
+ export const loader: LoaderFunction = async ({
+ request,
+ }): Promise<Data | Response> => {
+ try {
+ const buildParams = getBuildParams(request);
+
+ if (buildParams === undefined) {
+ return redirect(config.dashboardPath);
+ }
+
+ const { mode, pathname } = buildParams;
+
+ const project =
+ "projectId" in buildParams
+ ? await db.project.loadById(buildParams.projectId)
+ : await db.project.loadByDomain(buildParams.projectDomain);
+
+ if (project === null) {
+ throw json("Project not found", { status: 404 });
+ }
+
+ const canvasData = await loadCanvasData(
- project.id,
++ project,
+ mode === "published" ? "prod" : "dev",
+ pathname
+ );
+
+ if (canvasData === undefined) {
+ throw json("Page not found", { status: 404 });
+ }
+
+ return { ...canvasData, env, mode };
+ } catch (error) {
+ // If a Response is thrown, we're rethrowing it for Remix to handle.
+ // https://remix.run/docs/en/v1/api/conventions#throwing-responses-in-loaders
+ if (error instanceof Response) {
+ throw error;
+ }
+
+ sentryException({ error });
+ return {
+ errors: error instanceof Error ? error.message : String(error),
+ env,
+ };
+ }
+ };
+
+ const Content = () => {
+ const data = useLoaderData<Data>();
+
+ if ("errors" in data) {
+ return <ErrorMessage message={data.errors} />;
+ }
+
+ const Outlet =
+ data.mode === "edit"
+ ? () => <Canvas data={data} />
+ : () => <InstanceRoot data={data} />;
+
+ // @todo This is non-standard for Remix, is there a better way?
+ // Maybe there is a way to tell remix to use the right outlet somehow and avoid passing it?
+ return <Root Outlet={Outlet} />;
+ };
+
+ export default Content;
diff --cc apps/designer/app/shared/db/canvas.server.ts
index 0728008564,35c344c045..d961368ff3
--- a/apps/designer/app/shared/db/canvas.server.ts
+++ b/apps/designer/app/shared/db/canvas.server.ts
@@@ -6,22 -6,23 +6,23 @@@ import { utils } from "@webstudio-is/pr
export type CanvasData = Data & { buildId: Build["id"]; page: Page };
export const loadCanvasData = async (
-- projectId: Project["id"],
- pageId?: Page["id"]
- ): Promise<CanvasData> => {
- const project = await db.project.loadById(projectId);
-
- if (project === null) throw new Error(`Project "${projectId}" not found`);
-
- const devBuild = await db.build.loadByProjectId(projectId, "dev");
++ project: Project,
+ env: "dev" | "prod",
+ pagePath = ""
+ ): Promise<CanvasData | undefined> => {
+ const build =
+ env === "dev"
- ? await db.build.loadByProjectId(projectId, "dev")
- : await db.build.loadByProjectId(projectId, "prod");
++ ? await db.build.loadByProjectId(project.id, "dev")
++ : await db.build.loadByProjectId(project.id, "prod");
+
+ if (build === undefined) {
+ throw new Error("The project is not published");
+ }
- const page =
- pageId === undefined
- ? devBuild.pages.homePage
- : utils.pages.findById(devBuild.pages, pageId);
+ const page = utils.pages.findByPath(build.pages, pagePath);
if (page === undefined) {
- throw new Error(`Page "${pageId}" not found`);
+ return;
}
const [tree, props, breakpoints] = await Promise.all([
@@@ -31,19 -32,18 +32,19 @@@
]);
if (tree === null) {
-- throw new Error(`Tree not found for project ${projectId}`);
++ throw new Error(`Tree not found for project ${project.id}`);
}
if (breakpoints === null) {
-- throw new Error(`Breakpoints not found for project ${projectId}`);
++ throw new Error(`Breakpoints not found for project ${project.id}`);
}
return {
tree,
props,
breakpoints: breakpoints.values,
- buildId: devBuild.id,
+ buildId: build.id,
page,
+ assets: project.assets ?? [],
};
};
diff --cc apps/designer/app/shared/feature-flags/flags.ts
index 12dd85ea82,32814f8cb7..cdbf11dacf
--- a/apps/designer/app/shared/feature-flags/flags.ts
+++ b/apps/designer/app/shared/feature-flags/flags.ts
@@@ -1,3 -1,3 +1,4 @@@
export const assets = false;
+export const fonts = false;
export const example = false;
+ export const pages = false;
diff --cc packages/react-sdk/src/css/schema.ts
index e8d1e8ae27,865e5c021f..4b9bc605ff
--- a/packages/react-sdk/src/css/schema.ts
+++ b/packages/react-sdk/src/css/schema.ts
@@@ -15,14 -15,9 +15,14 @@@ export const KeywordValueSchema = z.obj
value: z.string(),
});
+const FontFamilyValueSchema = z.object({
+ type: z.literal("fontFamily"),
+ value: z.array(z.string()),
+});
+
// We want to be able to render the invalid value
// and show it is invalid visually, without saving it to the db
- const InvalidValueSchema = z.object({
+ export const InvalidValueSchema = z.object({
type: z.literal("invalid"),
value: z.string(),
});
@@@ -31,7 -31,7 +36,8 @@@ export const StyleValueSchema = z.union
UnitValueSchema,
KeywordValueSchema,
InvalidValueSchema,
+ FontFamilyValueSchema,
+ UnsetValueSchema,
]);
export const StyleSchema = z.record(z.string(), StyleValueSchema);