Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
Object Fit & object position (#1180)
Oleg Isonen11edeeb1c18a
diff --git a/apps/builder/app/builder/features/style-panel/controls/index.ts b/apps/builder/app/builder/features/style-panel/controls/index.tsindex 8d0e75c464..7c32157a66 100644--- a/apps/builder/app/builder/features/style-panel/controls/index.ts+++ b/apps/builder/app/builder/features/style-panel/controls/index.ts@@ -5,3 +5,5 @@ export * from "./menu/menu-control";export * from "./font-family/font-family-control";export * from "./font-weight/font-weight-control";export * from "./image/image-control";+export * from "./object-position/object-position-control";+export * from "./position/position-control";diff --git a/apps/builder/app/builder/features/style-panel/controls/object-position/object-position-control.tsx b/apps/builder/app/builder/features/style-panel/controls/object-position/object-position-control.tsxnew file mode 100644index 0000000000..64eb2c83c9--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/controls/object-position/object-position-control.tsx@@ -0,0 +1,32 @@+import { Flex, IconButton } from "@webstudio-is/design-system";+import type { ControlProps } from "../../style-sections";+import { FloatingPanel } from "~/builder/shared/floating-panel";+import { MenuIcon } from "@webstudio-is/icons";+import { PositionControl } from "../position/position-control";++export const ObjectPositionControl = ({+ property,+ currentStyle,+ setProperty,+ deleteProperty,+}: ControlProps) => {+ return (+ <Flex justify="end">+ <FloatingPanel+ title="Object Position"+ content={+ <PositionControl+ property={property}+ currentStyle={currentStyle}+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ />+ }+ >+ <IconButton>+ <MenuIcon />+ </IconButton>+ </FloatingPanel>+ </Flex>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/controls/position/css-value-input-container.tsx b/apps/builder/app/builder/features/style-panel/controls/position/css-value-input-container.tsxnew file mode 100644index 0000000000..be29c59e0f--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/controls/position/css-value-input-container.tsx@@ -0,0 +1,73 @@+import { ComponentProps, useState } from "react";+import type { StyleValue, StyleProperty } from "@webstudio-is/css-data";+import { Box, EnhancedTooltip } from "@webstudio-is/design-system";+import {+ CssValueInput,+ type IntermediateStyleValue,+} from "../../shared/css-value-input";+import type { StyleSource } from "../../shared/style-info";+import type { DeleteProperty, SetValue } from "../../shared/use-style-data";++type CssValueInputContainerProps = {+ property: StyleProperty;+ keywords: ComponentProps<typeof CssValueInput>["keywords"];+ label: string;+ styleSource: StyleSource;+ value?: StyleValue;+ setValue: SetValue;+ deleteProperty: DeleteProperty;+};++export const CssValueInputContainer = ({+ property,+ keywords,+ label,+ styleSource,+ value,+ setValue,+ deleteProperty,+}: CssValueInputContainerProps) => {+ const [intermediateValue, setIntermediateValue] = useState<+ StyleValue | IntermediateStyleValue+ >();++ return (+ <EnhancedTooltip content={label}>+ <Box>+ <CssValueInput+ styleSource={styleSource}+ property={property}+ value={value}+ intermediateValue={intermediateValue}+ keywords={keywords}+ onChange={(styleValue) => {+ setIntermediateValue(styleValue);++ if (styleValue === undefined) {+ deleteProperty(property, { isEphemeral: true });+ return;+ }++ if (styleValue.type !== "intermediate") {+ setValue(styleValue, { isEphemeral: true });+ }+ }}+ onHighlight={(styleValue) => {+ if (styleValue !== undefined) {+ setValue(styleValue, { isEphemeral: true });+ } else {+ deleteProperty(property, { isEphemeral: true });+ }+ }}+ onChangeComplete={({ value }) => {+ setValue(value);+ setIntermediateValue(undefined);+ }}+ onAbort={() => {+ deleteProperty(property, { isEphemeral: true });+ }}+ />+ </Box>+ </EnhancedTooltip>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/controls/position/position-control.tsx b/apps/builder/app/builder/features/style-panel/controls/position/position-control.tsxnew file mode 100644index 0000000000..ebc51446e1--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/controls/position/position-control.tsx@@ -0,0 +1,117 @@+import {+ TupleValue,+ type StyleValue,+ TupleValueItem,+} from "@webstudio-is/css-data";+import { Flex, Label, PositionGrid, theme } from "@webstudio-is/design-system";+import type { ControlProps } from "../../style-sections";+import { styleConfigByName } from "../../shared/configs";+import { getStyleSource } from "../../shared/style-info";+import { CssValueInputContainer } from "./css-value-input-container";+import type { SetValue } from "../../shared/use-style-data";++const toPosition = (value: TupleValue) => {+ return {+ x: value.value[0].value,+ y: value.value[1].value,+ };+};++// @todo SetValue has legacy string value support, that needs to be removed+const toTuple = (+ valueX?: StyleValue | string,+ valueY?: StyleValue | string+) => {+ const parsedValue = TupleValue.safeParse(valueX);+ if (parsedValue.success) {+ return parsedValue.data;+ }++ const parsedValueX = valueX+ ? TupleValueItem.parse(valueX)+ : ({ type: "unit", value: 0, unit: "px" } as const);+ const parsedValueY = valueY ? TupleValueItem.parse(valueY) : parsedValueX;++ return {+ type: "tuple" as const,+ value: [parsedValueX, parsedValueY],+ };+};++export const PositionControl = ({+ currentStyle,+ property,+ setProperty,+ deleteProperty,+}: ControlProps) => {+ const { label, items } = styleConfigByName[property];+ const styleInfo = currentStyle[property];+ const value = toTuple(styleInfo?.value);+ const styleSource = getStyleSource(styleInfo);+ const keywords = items.map((item) => ({+ type: "keyword" as const,+ value: item.name,+ }));++ const setValue = setProperty(property);++ const setValueX: SetValue = (valueX, options) => {+ const nextValue = toTuple(valueX, value.value[1]);+ setValue(nextValue, options);+ };++ const setValueY: SetValue = (valueY, options) => {+ const nextValue = toTuple(value.value[0], valueY);+ setValue(nextValue, options);+ };++ return (+ <Flex+ direction="column"+ gap="1"+ css={{ px: theme.spacing[9], py: theme.spacing[5] }}+ >+ <Label>Position</Label>+ <Flex gap="6">+ <PositionGrid+ selectedPosition={toPosition(value)}+ onSelect={({ x, y }) => {+ setValue({+ type: "tuple",+ value: [+ { type: "unit", value: x, unit: "%" },+ { type: "unit", value: y, unit: "%" },+ ],+ });+ }}+ />+ <Flex direction="column" justify="between">+ <Flex align="center" gap="2">+ <Label>Left</Label>+ <CssValueInputContainer+ label={label}+ property={property}+ styleSource={styleSource}+ keywords={keywords}+ value={value.value[0]}+ setValue={setValueX}+ deleteProperty={deleteProperty}+ />+ </Flex>+ <Flex align="center" gap="2">+ <Label>Top</Label>+ <CssValueInputContainer+ label={label}+ property={property}+ styleSource={styleSource}+ keywords={keywords}+ value={value.value[1]}+ setValue={setValueY}+ deleteProperty={deleteProperty}+ />+ </Flex>+ </Flex>+ </Flex>+ </Flex>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/controls/toggle/toggle-control.tsx b/apps/builder/app/builder/features/style-panel/controls/toggle/toggle-control.tsxindex c251e91c92..2c9dadd4d3 100644--- a/apps/builder/app/builder/features/style-panel/controls/toggle/toggle-control.tsx+++ b/apps/builder/app/builder/features/style-panel/controls/toggle/toggle-control.tsx@@ -15,6 +15,7 @@ export type ToggleGroupControlProps = {onValueChange?: (value: string) => void;};+// @todo refactor this control to follow the standard interface we otherwise have for all controlsexport const ToggleGroupControl = ({styleSource,value = "",diff --git a/apps/builder/app/builder/features/style-panel/sections/size/size.tsx b/apps/builder/app/builder/features/style-panel/sections/size/size.tsxindex 7be413f4b8..0208fbe95b 100644--- a/apps/builder/app/builder/features/style-panel/sections/size/size.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/size/size.tsx@@ -4,8 +4,11 @@ import { Grid } from "@webstudio-is/design-system";import { styleConfigByName } from "../../shared/configs";import type { RenderCategoryProps } from "../../style-sections";import { PropertyName } from "../../shared/property-name";-import { TextControl } from "../../controls";-import { ToggleGroupControl } from "../../controls/toggle/toggle-control";+import {+ SelectControl,+ TextControl,+ ObjectPositionControl,+} from "../../controls";import {EyeconOpenIcon,EyeconClosedIcon,@@ -14,6 +17,7 @@ import {} from "@webstudio-is/icons";import { getStyleSource } from "../../shared/style-info";import { theme } from "@webstudio-is/design-system";+import { ToggleGroupControl } from "../../controls/toggle/toggle-control";const SizeField = ({property,@@ -138,6 +142,30 @@ export const SizeSection = ({setProperty("overflow")({ type: "keyword", value })}/>+ <PropertyName+ label={styleConfigByName.objectFit.label}+ property="objectFit"+ style={style}+ onReset={() => deleteProperty("objectFit")}+ />+ <SelectControl+ property="objectFit"+ currentStyle={style}+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ />+ <PropertyName+ label={styleConfigByName.objectPosition.label}+ property="objectPosition"+ style={style}+ onReset={() => deleteProperty("objectPosition")}+ />+ <ObjectPositionControl+ property="objectPosition"+ currentStyle={style}+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ /></Grid>);};diff --git a/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts b/apps/builder/app/builder/features/style-panel/shared/use-style-data.tsindex c86d9a1ff4..3188992c07 100644--- a/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts+++ b/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts@@ -31,10 +31,13 @@ type UseStyleData = {export type StyleUpdateOptions = { isEphemeral: boolean };-// @todo: style must have StyleValue type always-export type SetProperty = (- property: StyleProperty-) => (style: string | StyleValue, options?: StyleUpdateOptions) => void;+// @todo: style must have StyleValue type always, get rid of string.+export type SetValue = (+ style: string | StyleValue,+ options?: StyleUpdateOptions+) => void;++export type SetProperty = (property: StyleProperty) => SetValue;export type DeleteProperty = (property: StyleProperty,diff --git a/packages/css-data/src/schema.ts b/packages/css-data/src/schema.tsindex 617a746d78..f0dcda8be0 100644--- a/packages/css-data/src/schema.ts+++ b/packages/css-data/src/schema.ts@@ -97,6 +97,20 @@ const ArrayValue = z.object({});export type ArrayValue = z.infer<typeof ArrayValue>;+export const TupleValueItem = z.union([UnitValue, KeywordValue, UnparsedValue]);+export type TupleValueItem = z.infer<typeof TupleValueItem>;++export const TupleValue = z.object({+ type: z.literal("tuple"),+ value: z.array(TupleValueItem),+});+export type TupleValue = z.infer<typeof TupleValue>;++/**+ * All StyleValue types that going to need wrapping into a CSS variable when rendered+ * on canvas inside builder.+ * Values like InvalidValue, UnsetValue, VarValue don't need to be wrapped+ */export const validStaticValueTypes = ["unit","keyword",@@ -105,6 +119,7 @@ export const validStaticValueTypes = ["image","unparsed","array",+ "tuple",] as const;/**@@ -118,6 +133,7 @@ const SharedStaticStyleValue = z.union([RgbValue,UnparsedValue,ArrayValue,+ TupleValue,]);const ValidStaticStyleValue = z.union([ImageValue, SharedStaticStyleValue]);diff --git a/packages/css-engine/src/core/to-value.test.ts b/packages/css-engine/src/core/to-value.test.tsindex abe388a906..88e4cb05e9 100644--- a/packages/css-engine/src/core/to-value.test.ts+++ b/packages/css-engine/src/core/to-value.test.ts@@ -100,4 +100,17 @@ describe("Convert WS CSS Values to native CSS strings", () => {expect(value).toBe("auto,10px,calc(10px),url(foo.png) /* id=1234567890 */");});++ test("tuple", () => {+ const value = toValue({+ type: "tuple",+ value: [+ { type: "unit", value: 10, unit: "px" },+ { type: "unit", value: 20, unit: "px" },+ { type: "unit", value: 30, unit: "px" },+ { type: "unit", value: 40, unit: "px" },+ ],+ });+ expect(value).toBe("10px 20px 30px 40px");+ });});diff --git a/packages/css-engine/src/core/to-value.ts b/packages/css-engine/src/core/to-value.tsindex 29566f757c..c4108c036c 100644--- a/packages/css-engine/src/core/to-value.ts+++ b/packages/css-engine/src/core/to-value.ts@@ -71,7 +71,11 @@ export const toValue = (}if (value.type === "layers") {- return value.value.map((v) => toValue(v, options)).join(",");+ return value.value.map((value) => toValue(value, options)).join(",");+ }++ if (value.type === "tuple") {+ return value.value.map((value) => toValue(value, options)).join(" ");}// Will give ts error in case of missing typediff --git a/packages/design-system/src/components/icon-button.tsx b/packages/design-system/src/components/icon-button.tsxindex 890a323fbe..e880a128ee 100644--- a/packages/design-system/src/components/icon-button.tsx+++ b/packages/design-system/src/components/icon-button.tsx@@ -26,6 +26,10 @@ export const IconButton = styled("button", {borderColor: "transparent",pointerEvents: "none",},+ "&[data-state=open]": {+ backgroundColor: theme.colors.blue10,+ color: theme.colors.foregroundContrastMain,+ },variants: {variant: {@@ -73,7 +77,7 @@ export const IconButton = styled("button", {},active: {backgroundColor: theme.colors.blue10,- color: "White",+ color: theme.colors.foregroundContrastMain,// non-interactive state because usually covered with overlay},},diff --git a/packages/design-system/src/components/position-grid.stories.tsx b/packages/design-system/src/components/position-grid.stories.tsxindex b52be3e7cb..238d69e47a 100644--- a/packages/design-system/src/components/position-grid.stories.tsx+++ b/packages/design-system/src/components/position-grid.stories.tsx@@ -9,8 +9,8 @@ export default {export const PositionGrid = () => {const [selectedPosition, setSelectedPosition] = useState({- top: 50,- left: 50,+ y: 50,+ x: 50,});return (<Flex gap="3">@@ -42,7 +42,7 @@ export const PositionGrid = () => {setSelectedPosition(position);action("onSelect")(position);}}- focusedPosition={{ top: 0, left: 0 }}+ focusedPosition={{ y: 0, x: 0 }}/></Flex>);diff --git a/packages/design-system/src/components/position-grid.tsx b/packages/design-system/src/components/position-grid.tsxindex dad55b1483..e86c93f9ce 100644--- a/packages/design-system/src/components/position-grid.tsx+++ b/packages/design-system/src/components/position-grid.tsx@@ -10,7 +10,29 @@ const positions = [[0, 100], [50, 100], [100, 100],];+type Position = { y: number; x: number };+type MixedPosition = { y: number | string; x: number | string };++const keywordNumberMap: Record<string, number> = {+ x: 0,+ y: 0,+ center: 50,+ right: 100,+ bottom: 100,+};++const toNumericPosition = (position?: MixedPosition) => {+ if (position === undefined) {+ return;+ }+ return {+ x: keywordNumberMap[position.x] ?? position.x,+ y: keywordNumberMap[position.y] ?? position.y,+ };+};+const containerStyle = css({+ background: theme.colors.backgroundControls,padding: theme.spacing[4],width: "fit-content",borderRadius: theme.borderRadius[4],@@ -51,8 +73,6 @@ const dotStyle = css({},});-type Position = { top: number; left: number };-const useKeyboard = ({onSelect,focusedPosition,@@ -61,48 +81,48 @@ const useKeyboard = ({onSelect: (position: Position) => void;}) => {// -50 is to prevent the focus to be on the first item when the grid is not focused- const [top, setTop] = useState(focusedPosition?.top ?? -50);- const [left, setLeft] = useState(focusedPosition?.left ?? 0);+ const [y, setTop] = useState(focusedPosition?.y ?? -50);+ const [x, setLeft] = useState(focusedPosition?.x ?? 0);const handleKeyDown: KeyboardEventHandler = (event) => {switch (event.key) {case "ArrowUp": {- setTop(top <= 0 ? 100 : top - 50);+ setTop(y <= 0 ? 100 : y - 50);break;}case "ArrowDown": {- setTop(top >= 100 ? 0 : top + 50);+ setTop(y >= 100 ? 0 : y + 50);break;}case "ArrowLeft": {- setLeft(left <= 0 ? 100 : left - 50);+ setLeft(x <= 0 ? 100 : x - 50);break;}case "ArrowRight": {- setLeft(left >= 100 ? 0 : left + 50);+ setLeft(x >= 100 ? 0 : x + 50);break;}case "Enter": {- if (top >= 0 && left >= 0) {- onSelect({ top, left });+ if (y >= 0 && x >= 0) {+ onSelect({ y, x });}break;}}};- return { handleKeyDown, focusedKey: `${left}-${top}` };+ return { handleKeyDown, focusedKey: `${x}-${y}` };};type PositionGridProps = {focusedPosition?: Position;- selectedPosition?: Position;+ selectedPosition?: MixedPosition;focused?: boolean;onSelect: (position: Position) => void;};/**- * It will render selected item when the top/left values in `selectedPosition` are 0, 50 or 100.+ * It will render selected item when the y/x values in `selectedPosition` are 0, 50 or 100.* All other values will be ignored.* Props `focused` and `focusedPosition` are for testing only, because they shold be set by interactions.*/@@ -116,6 +136,7 @@ export const PositionGrid = ({onSelect,focusedPosition,});+ const numericSelectedPosition = toNumericPosition(selectedPosition);return (<GridtabIndex={0}@@ -123,9 +144,9 @@ export const PositionGrid = ({data-focused={focused}className={containerStyle()}>- {positions.map(([left, top]) => {- const selectedKey = `${selectedPosition?.left}-${selectedPosition?.top}`;- const positionKey = `${left}-${top}`;+ {positions.map(([x, y]) => {+ const selectedKey = `${numericSelectedPosition?.x}-${numericSelectedPosition?.y}`;+ const positionKey = `${x}-${y}`;return (<Boxkey={positionKey}@@ -133,7 +154,7 @@ export const PositionGrid = ({data-focused={focusedKey === positionKey}className={dotStyle()}onClick={() => {- onSelect({ left, top });+ onSelect({ x, y });}}/>);