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
Position section (#1879)
Ivan Starkov5e072c7242d1
diff --git a/apps/builder/app/builder/features/style-panel/sections/position/position-control.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/position/position-control.stories.tsxnew file mode 100644index 0000000000..d490f8c19a--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/position/position-control.stories.tsx@@ -0,0 +1,122 @@+import type { Meta } from "@storybook/react";+import type * as React from "react";+import { PositionControl } from "./position-control";+import type {+ CreateBatchUpdate,+ DeleteProperty,+ SetProperty,+} from "../../shared/use-style-data";+import { useState, useRef } from "react";+import type { StyleInfo } from "../../shared/style-info";+import { Box } from "@webstudio-is/design-system";++const useStyleInfo = (styleInfoInitial: StyleInfo) => {+ const [styleInfo, setStyleInfo] = useState(() => styleInfoInitial);++ const setProperty: SetProperty = (name) => (value, options) => {+ if (options?.isEphemeral) {+ return;+ }++ setStyleInfo((styleInfo) => ({+ ...styleInfo,+ [name]: {+ ...styleInfo[name],+ value: value,+ local: value,+ },+ }));+ };++ const deleteProperty: DeleteProperty = (name, options) => {+ if (options?.isEphemeral) {+ return;+ }++ setStyleInfo((styleInfo) => {+ const styleInfoCopy = { ...styleInfo };++ styleInfoCopy[name] = structuredClone(defaultValue);++ return styleInfoCopy;+ });+ };++ const execCommands = useRef<(() => void)[]>([]);++ const createBatchUpdate: CreateBatchUpdate = () => ({+ deleteProperty: (property) => {+ execCommands.current.push(() => {+ deleteProperty(property);+ });+ },+ setProperty: (property) => (style) => {+ execCommands.current.push(() => {+ setProperty(property)(style);+ });+ },+ publish: (options) => {+ if (options?.isEphemeral) {+ execCommands.current = [];+ return;+ }++ for (const command of execCommands.current) {+ command();+ }++ execCommands.current = [];+ },+ });++ return { styleInfo, setProperty, deleteProperty, createBatchUpdate };+};++const defaultValue = {+ value: {+ type: "keyword",+ value: "auto",+ },+} as const;++const bigValue = {+ value: {+ type: "unit",+ value: 123.27,+ unit: "rem",+ },++ local: {+ type: "unit",+ value: 123.27,+ unit: "rem",+ },+} as const;++export const PositionControlComponent = (+ args: Omit<React.ComponentProps<typeof PositionControl>, "renderCell">+) => {+ const { styleInfo, setProperty, deleteProperty, createBatchUpdate } =+ useStyleInfo({+ left: defaultValue,+ right: bigValue,+ top: defaultValue,+ bottom: defaultValue,+ });++ return (+ <Box css={{ marginLeft: 100 }}>+ <PositionControl+ createBatchUpdate={createBatchUpdate}+ currentStyle={styleInfo}+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ />+ </Box>+ );+};++export default {+ title: "Position/Control",+ component: PositionControlComponent,+} as Meta<typeof PositionControlComponent>;diff --git a/apps/builder/app/builder/features/style-panel/sections/position/position-control.tsx b/apps/builder/app/builder/features/style-panel/sections/position/position-control.tsxnew file mode 100644index 0000000000..96744f6e8e--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/position/position-control.tsx@@ -0,0 +1,209 @@+import { Grid, theme } from "@webstudio-is/design-system";+import { PositionLayout, type PositionProperty } from "./position-layout";+import { movementMapPosition, useKeyboardNavigation } from "../shared/keyboard";+import { useRef, useState, type ComponentProps } from "react";+import type {+ CreateBatchUpdate,+ DeleteProperty,+ SetProperty,+} from "../../shared/use-style-data";+import { getStyleSource, type StyleInfo } from "../../shared/style-info";+import { getPositionModifiersGroup, useScrub } from "../shared/scrub";+import { ValueText } from "../shared/value-text";+import type { StyleValue } from "@webstudio-is/css-data";+import { InputPopover } from "../shared/input-popover";+import { PositionTooltip } from "./position-tooltip";++const Cell = ({+ scrubStatus,+ currentStyle,+ property,+ onHover,+ isPopoverOpen,+ onPopoverClose,+ onChange,+ createBatchUpdate,+}: {+ isPopoverOpen: boolean;+ onPopoverClose: () => void;+ onChange: ComponentProps<typeof InputPopover>["onChange"];+ scrubStatus: ReturnType<typeof useScrub>;+ currentStyle: StyleInfo;+ property: PositionProperty;+ onHover: (target: HoverTarget | undefined) => void;+ createBatchUpdate: CreateBatchUpdate;+}) => {+ const styleInfo = currentStyle[property];+ const finalValue: StyleValue | undefined = scrubStatus.isActive+ ? scrubStatus.values[property] ?? styleInfo?.value+ : styleInfo?.value;+ const styleSource = getStyleSource(styleInfo);++ if (finalValue === undefined) {+ return null;+ }++ return (+ <>+ <InputPopover+ styleSource={styleSource}+ value={finalValue}+ isOpen={isPopoverOpen}+ property={property}+ onChange={onChange}+ onClose={onPopoverClose}+ />+ <PositionTooltip+ property={property}+ style={currentStyle}+ createBatchUpdate={createBatchUpdate}+ preventOpen={scrubStatus.isActive}+ >+ <ValueText+ css={{+ // We want value to have `default` cursor to indicate that it's clickable,+ // unlike the rest of the value area that has cursor that indicates scrubbing.+ // Click and scrub works everywhere anyway, but we want cursors to be different.+ //+ // In order to have control over cursor we're setting pointerEvents to "all" here+ // because SpaceLayout sets it to "none" for cells' content.+ pointerEvents: "all",+ }}+ value={finalValue}+ source={styleSource}+ onMouseEnter={(event) =>+ onHover({ property, element: event.currentTarget })+ }+ onMouseLeave={() => onHover(undefined)}+ />+ </PositionTooltip>+ </>+ );+};++type HoverTarget = {+ element: HTMLElement;+ property: PositionProperty;+};++type PositionControlProps = {+ setProperty: SetProperty;+ deleteProperty: DeleteProperty;+ createBatchUpdate: CreateBatchUpdate;+ currentStyle: StyleInfo;+};++export const PositionControl = ({+ createBatchUpdate,+ currentStyle,+ deleteProperty,+ setProperty,+}: PositionControlProps) => {+ const [hoverTarget, setHoverTarget] = useState<HoverTarget>();++ const scrubStatus = useScrub({+ value:+ hoverTarget === undefined+ ? undefined+ : currentStyle[hoverTarget.property]?.value,+ target: hoverTarget,+ getModifiersGroup: getPositionModifiersGroup,+ onChange: (values, options) => {+ const batch = createBatchUpdate();+ for (const property of ["top", "right", "bottom", "left"] as const) {+ const value = values[property];+ if (value !== undefined) {+ batch.setProperty(property)(value);+ }+ }+ batch.publish(options);+ },+ });++ const [openProperty, setOpenProperty] = useState<PositionProperty>();++ const layoutRef = useRef<HTMLDivElement>(null);++ const keyboardNavigation = useKeyboardNavigation({+ onOpen: setOpenProperty,+ movementMap: movementMapPosition,+ });++ // by deafult highlight hovered or scrubbed properties+ let activeProperties = scrubStatus.properties;++ // if keyboard navigation is active, highlight its active property+ if (keyboardNavigation.isActive) {+ activeProperties = [keyboardNavigation.activeProperty];+ }++ // if popover is open, highlight its property and hovered properties+ if (openProperty !== undefined) {+ activeProperties = [openProperty, ...scrubStatus.properties];+ }++ const handleHover = (target: HoverTarget | undefined) => {+ setHoverTarget(target);+ keyboardNavigation.handleHover(target?.property);+ };++ return (+ <Grid+ ref={layoutRef}+ tabIndex={0}+ css={{+ // Create stacking context to prevent z-index issues with internal z-indexes+ zIndex: 0,+ // InputPopover is not working properly without position relative+ position: "relative",+ width: theme.spacing[22],+ height: theme.spacing[18],+ "&:focus-visible": {+ borderRadius: theme.borderRadius[3],+ outline: `2px solid ${theme.colors.blue10}`,+ },+ }}+ onFocus={keyboardNavigation.handleFocus}+ onBlur={keyboardNavigation.handleBlur}+ onKeyDown={keyboardNavigation.handleKeyDown}+ onMouseMove={keyboardNavigation.handleMouseMove}+ onMouseLeave={keyboardNavigation.handleMouseLeave}+ onClick={(event) => {+ const property = hoverTarget?.property;+ if (event.altKey && property) {+ deleteProperty(property);+ return;+ }+ setOpenProperty(property);+ }}+ >+ <PositionLayout+ activeProperties={activeProperties}+ renderCell={(property) => (+ <Cell+ scrubStatus={scrubStatus}+ currentStyle={currentStyle}+ property={property}+ onHover={handleHover}+ isPopoverOpen={openProperty === property}+ onPopoverClose={() => {+ if (openProperty === property) {+ setOpenProperty(undefined);+ layoutRef.current?.focus();+ }+ }}+ onChange={(update, options) => {+ if (update.operation === "set") {+ setProperty(update.property)(update.value, options);+ } else {+ deleteProperty(update.property, options);+ }+ }}+ createBatchUpdate={createBatchUpdate}+ />+ )}+ onHover={handleHover}+ />+ </Grid>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/position/position-layout.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/position/position-layout.stories.tsxnew file mode 100644index 0000000000..54bbac5283--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/position/position-layout.stories.tsx@@ -0,0 +1,35 @@+import type { Meta } from "@storybook/react";+import type * as React from "react";+import { PositionLayout } from "./position-layout";+import { Grid, theme, Text } from "@webstudio-is/design-system";++const Cell = () => (+ <Text variant={"spaceSectionValueText"}>Auto{/*1.275​rem*/}</Text>+);++export const PositionLayoutComponent = (+ args: Omit<React.ComponentProps<typeof PositionLayout>, "renderCell">+) => (+ <Grid css={{ width: theme.spacing[22], height: theme.spacing[18] }}>+ <PositionLayout+ renderCell={() => <Cell />}+ activeProperties={args.activeProperties}+ onHover={(hoverProps) => {+ // eslint-disable-next-line no-console+ console.log(hoverProps);+ }}+ />+ </Grid>+);++export default {+ title: "Position/Layout",+ component: PositionLayoutComponent,++ argTypes: {+ activeProperties: {+ options: ["left", "right", "top", "bottom"],+ control: { type: "check" },+ },+ },+} as Meta<typeof PositionLayoutComponent>;diff --git a/apps/builder/app/builder/features/style-panel/sections/position/position-layout.tsx b/apps/builder/app/builder/features/style-panel/sections/position/position-layout.tsxnew file mode 100644index 0000000000..f7ee184069--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/position/position-layout.tsx@@ -0,0 +1,194 @@+import { Grid, Box, theme, styled } from "@webstudio-is/design-system";+import type { MouseEvent } from "react";++const RECT_HEIGHT = 6;+const RECT_WIDTH = 42;+const RECT_BORDER_RADIUS = 1;+const OUTER_BORDER_RADIUS = 3;++const Trapezoid = styled("div", {+ borderRadius: OUTER_BORDER_RADIUS,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",++ "&:hover": {+ backgroundColor: theme.colors.backgroundSpacingHover,+ },+ variants: {+ isActive: {+ true: {+ backgroundColor: theme.colors.backgroundSpacingHover,+ },+ },+ },+});++const TopBottom = styled(Trapezoid, {+ zIndex: 0,+ backgroundColor: theme.colors.backgroundPanel,+});++const LeftRight = styled(Trapezoid, {+ zIndex: 1,+ backgroundColor: theme.colors.backgroundSpacingLeftRight,+});++export type PositionProperty = "top" | "right" | "bottom" | "left";++type PositionLayoutProps = {+ renderCell: (property: PositionProperty) => React.ReactNode;+ onHover: (+ args: { element: HTMLElement; property: PositionProperty } | undefined+ ) => void;+ activeProperties: readonly PositionProperty[];+};+/**+ * Grid schema for graphical layout+ * ```+ * 1 23 45 6+ * 1 -------------------+ * | || || |+ * 2 -------------------+ * 3 -------------------+ * | || || |+ * 4 -------------------+ * ```+ *+ **/+export const PositionLayout = ({+ renderCell,+ onHover,+ activeProperties,+}: PositionLayoutProps) => {+ const createHandleHover = (property: PositionProperty) => ({+ onMouseEnter: (e: MouseEvent<HTMLDivElement>) => {+ onHover({+ element: e.currentTarget,+ property,+ });+ },+ onMouseLeave: (e: MouseEvent<HTMLDivElement>) => {+ onHover(undefined);+ },+ });++ return (+ <Grid+ css={{+ borderRadius: OUTER_BORDER_RADIUS,++ borderColor: theme.colors.borderMain,+ borderWidth: 1,+ borderStyle: "solid",++ userSelect: "none",++ gridTemplateColumns: `1fr ${RECT_BORDER_RADIUS / 2}px ${+ RECT_WIDTH - RECT_BORDER_RADIUS+ }px ${RECT_BORDER_RADIUS / 2}px 1fr`,++ gridTemplateRows: `1fr ${RECT_HEIGHT}px 1fr`,+ }}+ >+ <Box+ css={{+ borderRadius: RECT_BORDER_RADIUS,+ gridArea: "2/2/3/5",+ backgroundColor: theme.colors.backgroundControls,+ borderWidth: 1,+ borderStyle: "solid",+ borderColor: theme.colors.borderMain,+ zIndex: 2,+ }}+ />+ <LeftRight+ css={{+ gridArea: "1/1/4/3",+ clipPath: `polygon(0 0, 100% calc(50% - ${+ RECT_HEIGHT / 2 - RECT_BORDER_RADIUS / 2+ }px), 100% calc(50% + ${+ RECT_HEIGHT / 2 - RECT_BORDER_RADIUS / 2+ }px), 0% 100%)`,+ cursor: "w-resize",+ }}+ isActive={activeProperties?.includes("left")}+ {...createHandleHover("left")}+ />++ <LeftRight+ css={{+ gridArea: "1/1/4/3",+ zIndex: 2,+ visibility: "hidden",+ }}+ >+ <Box+ css={{+ visibility: "visible",+ margin: theme.spacing[2],+ display: "flex",+ justifyContent: "center",+ }}+ >+ {renderCell("left")}+ </Box>+ </LeftRight>++ <LeftRight+ css={{+ gridArea: "1/4/4/6",+ clipPath: `polygon(0 calc(50% - ${+ RECT_HEIGHT / 2 - RECT_BORDER_RADIUS / 2+ }px), 100% 0, 100% 100%, 0 calc(50% + ${+ RECT_HEIGHT / 2 - RECT_BORDER_RADIUS / 2+ }px))`,+ cursor: "e-resize",+ }}+ isActive={activeProperties?.includes("right")}+ {...createHandleHover("right")}+ />++ <LeftRight+ css={{+ gridArea: "1/4/4/6",+ zIndex: 2,+ visibility: "hidden",+ }}+ >+ <Box+ css={{+ visibility: "visible",+ margin: theme.spacing[2],+ display: "flex",+ justifyContent: "center",+ }}+ >+ {renderCell("right")}+ </Box>+ </LeftRight>++ <TopBottom+ css={{+ gridArea: "1/1/2/6",+ cursor: "n-resize",+ }}+ isActive={activeProperties?.includes("top")}+ {...createHandleHover("top")}+ >+ {renderCell("top")}+ </TopBottom>++ <TopBottom+ css={{+ gridArea: "3/1/4/6",+ cursor: "s-resize",+ }}+ isActive={activeProperties?.includes("bottom")}+ {...createHandleHover("bottom")}+ >+ {renderCell("bottom")}+ </TopBottom>+ </Grid>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/position/position-tooltip.tsx b/apps/builder/app/builder/features/style-panel/sections/position/position-tooltip.tsxnew file mode 100644index 0000000000..8d9c6fbafd--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/position/position-tooltip.tsx@@ -0,0 +1,105 @@+import { PropertyTooltip } from "../../shared/property-name";+import type { StyleInfo } from "../../shared/style-info";+import { useState, type ReactElement } from "react";+import { useModifierKeys } from "../../shared/modifier-keys";+import { getPositionModifiersGroup } from "../shared/scrub";+import type { CreateBatchUpdate } from "../../shared/use-style-data";+import type { PositionProperty } from "./position-layout";++const sides = {+ top: "top",+ right: "left",+ bottom: "bottom",+ left: "left",+} as const;++const propertyContents: {+ properties: PositionProperty[];+ label: string;+ description: string;+}[] = [+ {+ properties: ["top", "bottom"],+ label: "Vertical position",+ description:+ "Sets the top and bottom position of an element relative to its nearest positioned ancestor.",+ },++ {+ properties: ["left", "right"],+ label: "Horizontal position",+ description:+ "Sets the left and right position of an element relative to its nearest positioned ancestor.",+ },++ {+ properties: ["top", "right", "bottom", "left"],+ label: "Padding",+ description:+ "Sets the top, right, bottom and left position of an element relative to its nearest positioned ancestor.",+ },+];++const isSameUnorderedArrays = (+ arrA: readonly string[],+ arrB: readonly string[]+) => {+ if (arrA.length !== arrB.length) {+ return false;+ }++ const union = new Set([...arrA, ...arrB]);+ return union.size === arrA.length;+};++export const PositionTooltip = ({+ property,+ style,+ children,+ createBatchUpdate,+ preventOpen,+}: {+ property: PositionProperty;+ style: StyleInfo;+ children: ReactElement;+ createBatchUpdate: CreateBatchUpdate;+ preventOpen: boolean;+}) => {+ const [open, setOpen] = useState(false);++ const modifiers = useModifierKeys();++ const properties = [...getPositionModifiersGroup(property, modifiers)];++ const propertyContent = propertyContents.find((propertyContent) =>+ isSameUnorderedArrays(propertyContent.properties, properties)+ );++ const handleOpenChange = (value: boolean) => {+ if (preventOpen && value === true) {+ return;+ }+ setOpen(value);+ };++ return (+ <PropertyTooltip+ open={open}+ onOpenChange={handleOpenChange}+ properties={properties}+ style={style}+ title={propertyContent?.label}+ description={propertyContent?.description}+ side={sides[property]}+ onReset={() => {+ const batch = createBatchUpdate();+ for (const property of properties) {+ batch.deleteProperty(property);+ }+ batch.publish();+ }}+ >+ <div>{children}</div>+ </PropertyTooltip>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/position/position.tsx b/apps/builder/app/builder/features/style-panel/sections/position/position.tsxindex 5aa56daeb1..449da3a998 100644--- a/apps/builder/app/builder/features/style-panel/sections/position/position.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/position/position.tsx@@ -1,25 +1,134 @@import type { StyleProperty } from "@webstudio-is/css-data";import type { RenderCategoryProps } from "../../style-sections";-import { renderProperty } from "../../style-sections";import { CollapsibleSection } from "../../shared/collapsible-section";+import { Grid, theme } from "@webstudio-is/design-system";+import { SelectControl, TextControl } from "../../controls";+import { PropertyName } from "../../shared/property-name";+import { styleConfigByName } from "../../shared/configs";+import { PositionControl } from "./position-control";+import { useStyleInfoByInstanceId } from "../../shared/style-info";+import { selectedInstanceSelectorStore } from "~/shared/nano-states";+import { useStore } from "@nanostores/react";-const properties: StyleProperty[] = [- "position",- "top",- "right",- "bottom",- "left",- "zIndex",- "float",- "clear",-];--export const PositionSection = (props: RenderCategoryProps) => (- <CollapsibleSection- label="Position"- currentStyle={props.currentStyle}- properties={properties}- >- {properties.map((property) => renderProperty({ ...props, property }))}- </CollapsibleSection>-);+const properties: StyleProperty[] = ["position"];++const useParentStyle = () => {+ const selectedInstanceSelector = useStore(selectedInstanceSelectorStore);+ const parentInstanceSelector =+ // root does not have parent+ selectedInstanceSelector?.length === 1+ ? undefined+ : selectedInstanceSelector?.slice(1);+ const parentStyleInfo = useStyleInfoByInstanceId(parentInstanceSelector);++ return parentStyleInfo;+};++const positionControlVisibleProperties = [+ "relative",+ "absolute",+ "fixed",+ "sticky",+] as const;++const zIndexParents = ["flex", "grid", "inline-flex", "inline-grid"] as const;++export const PositionSection = ({+ setProperty,+ deleteProperty,+ currentStyle,+ createBatchUpdate,+}: RenderCategoryProps) => {+ const parentStyle = useParentStyle();++ const positionValue = currentStyle.position?.value;++ const showPositionControls =+ positionValue?.type === "keyword" &&+ positionControlVisibleProperties.includes(positionValue.value as never);++ const showZindexControl =+ showPositionControls ||+ (parentStyle?.display?.value.type === "keyword" &&+ zIndexParents.includes(parentStyle?.display?.value.value as never));++ const { items: unfilteredPositionItems } = styleConfigByName("position");++ // Filter out "inherit" as we have no a good way to handle it+ // @todo remove after https://github.com/webstudio-is/webstudio-builder/issues/1536+ const positionItems = unfilteredPositionItems.filter(+ (item) => item.name !== "inherit"+ );++ return (+ <CollapsibleSection+ label="Position"+ currentStyle={currentStyle}+ properties={properties}+ >+ <Grid gap={2}>+ <Grid+ gap={2}+ css={{+ gridTemplateColumns: `1fr ${theme.spacing[23]}`,+ }}+ >+ <PropertyName+ label={styleConfigByName("position").label}+ properties={["position"]}+ style={currentStyle}+ onReset={() => deleteProperty("position")}+ />+ <SelectControl+ property={"position"}+ currentStyle={currentStyle}+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ items={positionItems}+ />+ {showZindexControl && showPositionControls === false && (+ <>+ <PropertyName+ label={styleConfigByName("zIndex").label}+ properties={["zIndex"]}+ style={currentStyle}+ onReset={() => deleteProperty("zIndex")}+ />+ <TextControl+ property={"zIndex"}+ currentStyle={currentStyle}+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ />+ </>+ )}+ </Grid>++ {showPositionControls && (+ <Grid gap={3} columns={2}>+ <PositionControl+ currentStyle={currentStyle}+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ createBatchUpdate={createBatchUpdate}+ />+ <Grid gap={1}>+ <PropertyName+ label={styleConfigByName("zIndex").label}+ properties={["zIndex"]}+ style={currentStyle}+ onReset={() => deleteProperty("zIndex")}+ />+ <TextControl+ property={"zIndex"}+ currentStyle={currentStyle}+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ />+ </Grid>+ </Grid>+ )}+ </Grid>+ </CollapsibleSection>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/space/input-popover.tsx b/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.tsxsimilarity index 100%rename from apps/builder/app/builder/features/style-panel/sections/space/input-popover.tsxrename to apps/builder/app/builder/features/style-panel/sections/shared/input-popover.tsxdiff --git a/apps/builder/app/builder/features/style-panel/sections/space/keyboard.ts b/apps/builder/app/builder/features/style-panel/sections/shared/keyboard.tssimilarity index 54%rename from apps/builder/app/builder/features/style-panel/sections/space/keyboard.tsrename to apps/builder/app/builder/features/style-panel/sections/shared/keyboard.tsindex 90bd3c57e6..c902676a79 100644--- a/apps/builder/app/builder/features/style-panel/sections/space/keyboard.ts+++ b/apps/builder/app/builder/features/style-panel/sections/shared/keyboard.ts@@ -1,6 +1,6 @@import { useState, useRef } from "react";-import type { FocusEvent, KeyboardEvent } from "react";-import type { SpaceStyleProperty } from "./types";+import type { FocusEvent, FocusEventHandler, KeyboardEvent } from "react";+import { useDebouncedCallback } from "use-debounce";const movementKeys = ["ArrowUp",@@ -9,7 +9,7 @@ const movementKeys = ["ArrowLeft",] as const;-const movementMap = {+export const movementMapSpace = {marginTop: ["marginBottom", "marginRight", "paddingTop", "marginLeft"],marginRight: ["marginTop", "marginLeft", "marginBottom", "paddingRight"],marginBottom: ["paddingBottom", "marginRight", "marginTop", "marginLeft"],@@ -20,16 +20,79 @@ const movementMap = {paddingLeft: ["paddingTop", "paddingTop", "paddingBottom", "marginLeft"],} as const;-export const useKeyboardNavigation = ({+export const movementMapPosition = {+ top: ["bottom", "right", "bottom", "left"],+ right: ["top", "left", "bottom", "left"],+ bottom: ["top", "right", "top", "left"],+ left: ["top", "right", "bottom", "right"],+} as const;++/**+ * useFocusWithin does't work with popovers, implement it using debounce+ */+const useFocusWithinDebounce = (+ props: {+ onFocusWithin: FocusEventHandler<Element>;+ onBlurWithin: FocusEventHandler<Element>;+ },+ timeout: number+) => {+ const isFocusedRef = useRef(false);++ const handleFocusBlur = useDebouncedCallback(+ (isFocus: boolean, event: FocusEvent<Element>) => {+ if (isFocus && isFocusedRef.current === false) {+ isFocusedRef.current = true;+ props.onFocusWithin(event);+ return;+ }+ if (isFocus === false && isFocusedRef.current === true) {+ isFocusedRef.current = false;+ props.onBlurWithin(event);+ }+ },+ timeout+ );++ const handleFocus = (event: FocusEvent<Element>) => {+ // ...event because we debounce handleFocusBlur, and react reuses events+ handleFocusBlur(true, { ...event });+ };++ const handleBlur = (event: FocusEvent<Element>) => {+ handleFocusBlur(false, event);+ };++ return {+ onFocus: handleFocus,+ onBlur: handleBlur,+ };+};++export const useKeyboardNavigation = <+ P extends string,+ T extends {+ readonly [key in P]: readonly [+ ArrowUp: P,+ ArrowRight: P,+ ArrowDown: P,+ ArrowLeft: P+ ];+ }+>({onOpen,+ movementMap,}: {- onOpen: (property: SpaceStyleProperty) => void;+ onOpen: (property: keyof T) => void;+ movementMap: T;}) => {- const [activeProperty, setActiveProperty] =- useState<SpaceStyleProperty>("marginTop");+ const [activeProperty, setActiveProperty] = useState<keyof T>(+ Object.keys(movementMap)[0] as P+ );- const [hoverActiveProperty, setHoverActiveProperty] =- useState<SpaceStyleProperty>("marginTop");+ const [hoverActiveProperty, setHoverActiveProperty] = useState<keyof T>(+ Object.keys(movementMap)[0] as P+ );const [isActive, setIsActive] = useState(false);@@ -43,17 +106,25 @@ export const useKeyboardNavigation = ({}};- const handleFocus = (event: FocusEvent<Element>) => {+ const handleFocusInternal = (event: FocusEvent<Element>) => {if (event.currentTarget.matches(":focus-visible")) {handleActiveChange(true);}};- const handleBlur = () => {+ const handleBlurInternal = () => {handleActiveChange(false);};- const handleHover = (property: SpaceStyleProperty | undefined) => {+ const { onFocus: handleFocus, onBlur: handleBlur } = useFocusWithinDebounce(+ {+ onFocusWithin: handleFocusInternal,+ onBlurWithin: handleBlurInternal,+ },+ 100+ );++ const handleHover = (property: keyof T | undefined) => {// keep active property in sync with hover (makes UX more intuitive)if (property) {setHoverActiveProperty(property);diff --git a/apps/builder/app/builder/features/style-panel/sections/space/scrub.tsx b/apps/builder/app/builder/features/style-panel/sections/shared/scrub.tsxsimilarity index 69%rename from apps/builder/app/builder/features/style-panel/sections/space/scrub.tsxrename to apps/builder/app/builder/features/style-panel/sections/shared/scrub.tsxindex 09b51de2bb..0e9dc148f9 100644--- a/apps/builder/app/builder/features/style-panel/sections/space/scrub.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/shared/scrub.tsx@@ -1,38 +1,53 @@-import type { StyleValue, UnitValue } from "@webstudio-is/css-data";+import type {+ StyleProperty,+ StyleValue,+ UnitValue,+} from "@webstudio-is/css-data";import { numericScrubControl } from "@webstudio-is/design-system";import { useState, useEffect, useRef } from "react";import { useModifierKeys } from "../../shared/modifier-keys";import type { StyleUpdateOptions } from "../../shared/use-style-data";-import type { SpaceStyleProperty, HoverTagret } from "./types";+import type { SpaceStyleProperty } from "../space/types";import { isValidDeclaration } from "@webstudio-is/css-data";import { parseIntermediateOrInvalidValue } from "../../shared/css-value-input/parse-intermediate-or-invalid-value";import { toValue } from "@webstudio-is/css-engine";import type { CssValueInputValue } from "../../shared/css-value-input/css-value-input";+import type { PositionProperty } from "../position/position-layout";-type Values = Partial<Record<SpaceStyleProperty, StyleValue>>;--type ScrubStatus = {+type ScrubStatus<P extends string> = {isActive: boolean;// Properties that should be affected on the next pointer move.// We keep track of these properties even when scrub is not active.- properties: ReadonlyArray<SpaceStyleProperty>;+ properties: ReadonlyArray<P>;// When scrub is active, this contains ephemeral values for all properties// that have been affected during current scrub.//// Note that Object.keys(values) != properties above,// because user can press and release modifier keys multiple times during scrub.- values: Values;+ values: Partial<Record<P, StyleValue>>;+};++type HoverTarget<P> = {+ property: P;+ element: HTMLElement | SVGElement;};-export const useScrub = (props: {+export const useScrub = <P extends StyleProperty>(props: {value?: StyleValue;- target: HoverTagret | undefined;- onChange: (values: Values, options: StyleUpdateOptions) => void;-}): ScrubStatus => {+ target: HoverTarget<P> | undefined;+ getModifiersGroup: (+ property: P,+ modifiers: { shiftKey: boolean; altKey: boolean }+ ) => ReadonlyArray<P>;+ onChange: (+ values: Partial<Record<P, StyleValue>>,+ options: StyleUpdateOptions+ ) => void;+}): ScrubStatus<P> => {// we want to hold on to the target while scrub is active even if hover changes- const [activeTarget, setActiveTarget] = useState<HoverTagret>();+ const [activeTarget, setActiveTarget] = useState<HoverTarget<P>>();const finalTarget = activeTarget ?? props.target;const modifiers = useModifierKeys();@@ -40,9 +55,9 @@ export const useScrub = (props: {const properties =finalTarget === undefined? []- : getModifiersGroup(finalTarget.property, modifiers);+ : props.getModifiersGroup(finalTarget.property, modifiers);- const [values, setValues] = useState<Values>({});+ const [values, setValues] = useState<Partial<Record<P, StyleValue>>>({});// we need these in useEffect, but don't want as dependenciesconst nonDependencies = useRef({ props, values, properties });@@ -103,7 +118,8 @@ export const useScrub = (props: {return numericScrubControl(finalTarget.element, {direction:- property.endsWith("Left") || property.endsWith("Right")+ property.toLowerCase().endsWith("left") ||+ property.toLowerCase().endsWith("right")? "horizontal": "vertical",getInitialValue() {@@ -112,6 +128,9 @@ export const useScrub = (props: {unitRef.current = value.unit;return value.value;}+ // In case of Auto value+ unitRef.current = "px";+ return 0;},onValueInput(event) {handleChange(event, true);@@ -136,28 +155,50 @@ export const useScrub = (props: {};};-const opposingGroups = [+const opposingSpaceGroups = [["paddingTop", "paddingBottom"],["paddingRight", "paddingLeft"],["marginTop", "marginBottom"],["marginRight", "marginLeft"],] as const;-const circleGroups = [+const circleSpaceGroups = [["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"],["marginTop", "marginRight", "marginBottom", "marginLeft"],] as const;-export const getModifiersGroup = (+export const getSpaceModifiersGroup = (property: SpaceStyleProperty,modifiers: { shiftKey: boolean; altKey: boolean }) => {let groups: ReadonlyArray<ReadonlyArray<SpaceStyleProperty>> = [];if (modifiers.shiftKey) {- groups = circleGroups;+ groups = circleSpaceGroups;+ } else if (modifiers.altKey) {+ groups = opposingSpaceGroups;+ }++ return groups.find((group) => group.includes(property)) ?? [property];+};++const opposingPositionGroups = [+ ["top", "bottom"],+ ["left", "right"],+] as const;++const circlePositionGroups = [["top", "right", "bottom", "left"]] as const;++export const getPositionModifiersGroup = (+ property: PositionProperty,+ modifiers: { shiftKey: boolean; altKey: boolean }+) => {+ let groups: ReadonlyArray<ReadonlyArray<PositionProperty>> = [];++ if (modifiers.shiftKey) {+ groups = circlePositionGroups;} else if (modifiers.altKey) {- groups = opposingGroups;+ groups = opposingPositionGroups;}return groups.find((group) => group.includes(property)) ?? [property];diff --git a/apps/builder/app/builder/features/style-panel/sections/space/value-text.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/shared/value-text.stories.tsxsimilarity index 80%rename from apps/builder/app/builder/features/style-panel/sections/space/value-text.stories.tsxrename to apps/builder/app/builder/features/style-panel/sections/shared/value-text.stories.tsxindex aa64e7a0c7..74428a7e47 100644--- a/apps/builder/app/builder/features/style-panel/sections/space/value-text.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/shared/value-text.stories.tsx@@ -1,23 +1,18 @@import type { ComponentMeta } from "@storybook/react";import { type ComponentProps, useState } from "react";import { parseCssValue } from "@webstudio-is/css-data";-import { SpaceLayout } from "./layout";+import { SpaceLayout } from "../space/layout";import { ValueText as ValueTextComponent } from "./value-text";export const ValueText = (args: Pick<ComponentProps<typeof ValueTextComponent>, "source" | "value">) => {- const [hovered, setHovered] = useState<{ property: string }>();+ const [_hovered, setHovered] = useState<{ property: string }>();return (<SpaceLayoutonHover={setHovered}onClick={() => null}- renderCell={({ property }) => (- <ValueTextComponent- isActive={property === hovered?.property}- {...args}- />- )}+ renderCell={({ property }) => <ValueTextComponent {...args} />}/>);};diff --git a/apps/builder/app/builder/features/style-panel/sections/shared/value-text.tsx b/apps/builder/app/builder/features/style-panel/sections/shared/value-text.tsxnew file mode 100644index 0000000000..33f959e897--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/shared/value-text.tsx@@ -0,0 +1,108 @@+import { styled, Text } from "@webstudio-is/design-system";+import type { StyleValue } from "@webstudio-is/css-data";+import { useMemo, type ComponentProps } from "react";+import { theme } from "@webstudio-is/design-system";+import { toValue } from "@webstudio-is/css-engine";+import { toPascalCase } from "../../shared/keyword-utils";++const Container = styled("button", {+ // fit-content is not needed for the "button" element,+ // leave it here in case of tag change+ width: "fit-content",+ display: "flex",+ flexWrap: "wrap",+ alignItems: "baseline",+ justifyContent: "center",+ border: "1px solid transparent",+ borderRadius: theme.borderRadius[3],+ padding: `${theme.spacing[2]}`,++ "&:focus-visible": {+ outline: "none",+ },++ variants: {+ source: {+ default: {+ color: theme.colors.foregroundMain,+ backgroundColor: "transparent",+ },+ local: {+ color: theme.colors.foregroundLocalMain,+ backgroundColor: theme.colors.backgroundLocalMain,+ borderColor: theme.colors.borderLocalMain,+ },+ overwritten: {+ color: theme.colors.foregroundOverwrittenMain,+ backgroundColor: theme.colors.backgroundOverwrittenMain,+ borderColor: theme.colors.borderOverwrittenMain,+ },+ preset: {+ color: theme.colors.foregroundMain,+ backgroundColor: theme.colors.backgroundPresetMain,+ borderColor: theme.colors.borderMain,+ },+ remote: {+ color: theme.colors.foregroundRemoteMain,+ backgroundColor: theme.colors.backgroundRemoteMain,+ borderColor: theme.colors.borderRemoteMain,+ },+ },+ },+ compoundVariants: [+ { source: "default", css: { color: theme.colors.slate12 } },+ ],+});++export const ValueText = ({+ value,+ source,+ ...rest+}: { value: StyleValue } & Omit<ComponentProps<typeof Container>, "value">) => {+ const children = useMemo(() => {+ if (value.type === "unit") {+ // we want to show "0" rather than "0px" for default values for cleaner UI+ if (source === "default" && value.unit === "px" && value.value === 0) {+ return <Text variant="spaceSectionValueText">{value.value}</Text>;+ }++ /**+ * To prevent span width to change replace all numbers with wide characters. "3" looks like the wides with current font+ **/+ const wideValue = `${value.value}`.replace(/\d/g, "3");++ return (+ <>+ <Text variant="spaceSectionValueText">+ {value.value}+ <Text+ variant="spaceSectionValueText"+ css={{ height: 0, visibility: "hidden" }}+ >+ {wideValue}+ </Text>+ </Text>+ {value.unit !== "number" && (+ <Text variant="spaceSectionUnitText">{value.unit}</Text>+ )}+ </>+ );+ }++ if (value.type === "var") {+ return <Text variant="spaceSectionValueText">--{value.value}</Text>;+ }++ return (+ <Text css={{}} variant="spaceSectionValueText">+ {toPascalCase(toValue(value))}+ </Text>+ );+ }, [value, source]);++ return (+ <Container source={source} {...rest} tabIndex={-1}>+ {children}+ </Container>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/space/layout.tsx b/apps/builder/app/builder/features/style-panel/sections/space/layout.tsxindex 9c00aee87c..9ca6c14905 100644--- a/apps/builder/app/builder/features/style-panel/sections/space/layout.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/space/layout.tsx@@ -1,7 +1,7 @@import { styled, useId } from "@webstudio-is/design-system";import { forwardRef } from "react";import type { ComponentProps, Ref } from "react";-import type { HoverTagret, SpaceStyleProperty } from "./types";+import type { HoverTarget, SpaceStyleProperty } from "./types";import { spacePropertiesNames } from "./types";import { theme } from "@webstudio-is/design-system";@@ -160,6 +160,7 @@ const Cell = styled("div", {alignItems: "center",justifyContent: "center",maxWidth: "100%",+ padding: theme.spacing[2],variants: {property: {marginTop: { gridColumn: "2 / 5", gridRow: "1" },@@ -237,7 +238,7 @@ type LayoutProps = {onClick?: ComponentProps<"div">["onClick"];onMouseLeave?: ComponentProps<"div">["onMouseLeave"];onMouseMove?: ComponentProps<"div">["onMouseMove"];- onHover: (hoverTarget: HoverTagret | undefined) => void;+ onHover: (hoverTarget: HoverTarget | undefined) => void;activeProperties?: ReadonlyArray<SpaceStyleProperty>;renderCell: (args: { property: SpaceStyleProperty }) => React.ReactNode;};diff --git a/apps/builder/app/builder/features/style-panel/sections/space/space.tsx b/apps/builder/app/builder/features/style-panel/sections/space/space.tsxindex 1a8578d3c4..6edb689662 100644--- a/apps/builder/app/builder/features/style-panel/sections/space/space.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/space/space.tsx@@ -1,22 +1,16 @@-import {- type ComponentProps,- type FocusEvent,- useState,- useRef,- type FocusEventHandler,-} from "react";+import { type ComponentProps, useState, useRef } from "react";import type { RenderCategoryProps } from "../../style-sections";import { SpaceLayout } from "./layout";-import { ValueText } from "./value-text";-import { useScrub } from "./scrub";+import { ValueText } from "../shared/value-text";+import { getSpaceModifiersGroup, useScrub } from "../shared/scrub";import { spacePropertiesNames } from "./types";-import type { SpaceStyleProperty, HoverTagret } from "./types";-import { InputPopover } from "./input-popover";+import type { SpaceStyleProperty, HoverTarget } from "./types";+import { InputPopover } from "../shared/input-popover";import { SpaceTooltip } from "./tooltip";import { getStyleSource } from "../../shared/style-info";import { CollapsibleSection } from "../../shared/collapsible-section";-import { useKeyboardNavigation } from "./keyboard";-import { useDebouncedCallback } from "use-debounce";+import { movementMapSpace, useKeyboardNavigation } from "../shared/keyboard";+import type { CreateBatchUpdate } from "../../shared/use-style-data";const Cell = ({@@ -25,7 +19,6 @@ const Cell = ({onChange,onHover,property,- isActive,scrubStatus,currentStyle,createBatchUpdate,@@ -33,9 +26,8 @@ const Cell = ({isPopoverOpen: boolean;onPopoverClose: () => void;onChange: ComponentProps<typeof InputPopover>["onChange"];- onHover: (target: HoverTagret | undefined) => void;+ onHover: (target: HoverTarget | undefined) => void;property: SpaceStyleProperty;- isActive: boolean;scrubStatus: ReturnType<typeof useScrub>;currentStyle: RenderCategoryProps["currentStyle"];createBatchUpdate: CreateBatchUpdate;@@ -77,7 +69,6 @@ const Cell = ({pointerEvents: "all",}}value={finalValue}- isActive={isActive}source={styleSource}onMouseEnter={(event) =>onHover({ property, element: event.currentTarget })@@ -89,55 +80,13 @@ const Cell = ({);};-/**- * useFocusWithin does't work with popovers, implement it using debounce- */-const useFocusWithinDebounce = (- props: {- onFocusWithin: FocusEventHandler<Element>;- onBlurWithin: FocusEventHandler<Element>;- },- timeout: number-) => {- const isFocusedRef = useRef(false);-- const handleFocusBlur = useDebouncedCallback(- (isFocus: boolean, event: FocusEvent<Element>) => {- if (isFocus && isFocusedRef.current === false) {- isFocusedRef.current = true;- props.onFocusWithin(event);- return;- }- if (isFocus === false && isFocusedRef.current === true) {- isFocusedRef.current = false;- props.onBlurWithin(event);- }- },- timeout- );-- const handleFocus = (event: FocusEvent<Element>) => {- // ...event because we debounce handleFocusBlur, and react reuses events- handleFocusBlur(true, { ...event });- };-- const handleBlur = (event: FocusEvent<Element>) => {- handleFocusBlur(false, event);- };-- return {- onFocus: handleFocus,- onBlur: handleBlur,- };-};-export const SpaceSection = ({setProperty,deleteProperty,createBatchUpdate,currentStyle,}: RenderCategoryProps) => {- const [hoverTarget, setHoverTarget] = useState<HoverTagret>();+ const [hoverTarget, setHoverTarget] = useState<HoverTarget>();const scrubStatus = useScrub({value:@@ -145,6 +94,7 @@ export const SpaceSection = ({? undefined: currentStyle[hoverTarget.property]?.value,target: hoverTarget,+ getModifiersGroup: getSpaceModifiersGroup,onChange: (values, options) => {const batch = createBatchUpdate();for (const property of spacePropertiesNames) {@@ -163,16 +113,9 @@ export const SpaceSection = ({const keyboardNavigation = useKeyboardNavigation({onOpen: setOpenProperty,+ movementMap: movementMapSpace,});- const focusProps = useFocusWithinDebounce(- {- onFocusWithin: keyboardNavigation.handleFocus,- onBlurWithin: keyboardNavigation.handleBlur,- },- 100- );-// by deafult highlight hovered or scrubbed propertieslet activeProperties = scrubStatus.properties;@@ -186,28 +129,11 @@ export const SpaceSection = ({activeProperties = [openProperty, ...scrubStatus.properties];}- const handleHoverUndefined = useDebouncedCallback(() => {- setHoverTarget(undefined);- keyboardNavigation.handleHover(undefined);- }, 100);-- const handleHover = (target: HoverTagret | undefined) => {- if (target === undefined) {- // Debounce the mouseleave event to prevent delays when moving between cells.- // This resolves the issue where the tooltip content changes when repositioned (e.g., when alt/shift clicked),- // causing rapid mouseleave and mouseenter events in the space section.- handleHoverUndefined();- return;- }- handleHoverUndefined.cancel();+ const handleHover = (target: HoverTarget | undefined) => {setHoverTarget(target);keyboardNavigation.handleHover(target?.property);};- const activeProperty = keyboardNavigation.isActive- ? keyboardNavigation.activeProperty- : hoverTarget?.property;-return (<CollapsibleSectionlabel="Space"@@ -225,8 +151,8 @@ export const SpaceSection = ({setOpenProperty(property);}}onHover={handleHover}- onFocus={focusProps.onFocus}- onBlur={focusProps.onBlur}+ onFocus={keyboardNavigation.handleFocus}+ onBlur={keyboardNavigation.handleBlur}activeProperties={activeProperties}onKeyDown={keyboardNavigation.handleKeyDown}onMouseMove={keyboardNavigation.handleMouseMove}@@ -250,7 +176,6 @@ export const SpaceSection = ({onHover={handleHover}property={property}scrubStatus={scrubStatus}- isActive={activeProperty === property}currentStyle={currentStyle}createBatchUpdate={createBatchUpdate}/>diff --git a/apps/builder/app/builder/features/style-panel/sections/space/tooltip.tsx b/apps/builder/app/builder/features/style-panel/sections/space/tooltip.tsxindex b14abf34c9..42c844b9bd 100644--- a/apps/builder/app/builder/features/style-panel/sections/space/tooltip.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/space/tooltip.tsx@@ -3,7 +3,7 @@ import { PropertyTooltip } from "../../shared/property-name";import type { StyleInfo } from "../../shared/style-info";import { useState, type ReactElement } from "react";import { useModifierKeys } from "../../shared/modifier-keys";-import { getModifiersGroup } from "./scrub";+import { getSpaceModifiersGroup } from "../shared/scrub";import type { CreateBatchUpdate } from "../../shared/use-style-data";const sides = {@@ -92,7 +92,7 @@ export const SpaceTooltip = ({const modifiers = useModifierKeys();- const properties = [...getModifiersGroup(property, modifiers)];+ const properties = [...getSpaceModifiersGroup(property, modifiers)];const propertyContent = propertyContents.find((propertyContent) =>isSameUnorderedArrays(propertyContent.properties, properties)diff --git a/apps/builder/app/builder/features/style-panel/sections/space/types.ts b/apps/builder/app/builder/features/style-panel/sections/space/types.tsindex 15699d7fb8..5287891999 100644--- a/apps/builder/app/builder/features/style-panel/sections/space/types.ts+++ b/apps/builder/app/builder/features/style-panel/sections/space/types.ts@@ -13,7 +13,7 @@ export const spacePropertiesNames = [export type SpaceStyleProperty = (typeof spacePropertiesNames)[number];-export type HoverTagret = {+export type HoverTarget = {property: SpaceStyleProperty;element: SVGElement | HTMLElement;};diff --git a/apps/builder/app/builder/features/style-panel/sections/space/value-text.tsx b/apps/builder/app/builder/features/style-panel/sections/space/value-text.tsxdeleted file mode 100644index 2ffac59a7a..0000000000--- a/apps/builder/app/builder/features/style-panel/sections/space/value-text.tsx+++ /dev/null@@ -1,136 +0,0 @@-import { styled } from "@webstudio-is/design-system";-import type { StyleValue } from "@webstudio-is/css-data";-import { useLayoutEffect, useMemo, useRef, type ComponentProps } from "react";-import { theme } from "@webstudio-is/design-system";--const Container = styled("span", {- boxSizing: "border-box",- maxWidth: "100%",- display: "flex",- flexWrap: "wrap",- alignItems: "end",- justifyContent: "center",- border: "1px solid transparent",- borderRadius: theme.borderRadius[3],- padding: `0 ${theme.spacing[1]}`,- variants: {- source: {- default: {- color: theme.colors.foregroundMain,- },- local: {- color: theme.colors.foregroundLocalMain,- backgroundColor: theme.colors.backgroundLocalMain,- borderColor: theme.colors.borderLocalMain,- },- overwritten: {- color: theme.colors.foregroundOverwrittenMain,- backgroundColor: theme.colors.backgroundOverwrittenMain,- borderColor: theme.colors.borderOverwrittenMain,- },- preset: {- color: theme.colors.foregroundMain,- backgroundColor: theme.colors.backgroundPresetMain,- borderColor: theme.colors.borderMain,- },- remote: {- color: theme.colors.foregroundRemoteMain,- backgroundColor: theme.colors.backgroundRemoteMain,- borderColor: theme.colors.borderRemoteMain,- },- },- isActive: { true: {} },- },- compoundVariants: [- { source: "default", isActive: true, css: { color: theme.colors.slate12 } },- ],-});--const Span = styled("span", {- display: "block",- fontSize: theme.deprecatedFontSize[2],- lineHeight: 1,- overflow: "hidden",- maxWidth: "100%",- whiteSpace: "nowrap",- textOverflow: "ellipsis",- variants: {- keyword: {- true: {- fontSize: theme.deprecatedFontSize[1],- textTransform: "uppercase",- },- },- },-});--export const ValueText = ({- value,- source,- ...rest-}: { value: StyleValue } & ComponentProps<typeof Container>) => {- const children = useMemo(() => {- if (value.type === "unit") {- // we want to show "0" rather than "0px" for default values for cleaner UI- if (source === "default" && value.unit === "px" && value.value === 0) {- return <Span>{value.value}</Span>;- }-- return (- <>- <Span>{value.value}</Span>- {value.unit !== "number" && <Span keyword>{value.unit}</Span>}- </>- );- }-- if (value.type === "var") {- return <Span keyword>--{value.value}</Span>;- }-- // @todo: not sure this is the best way to handle "invalid"- if (value.type === "keyword" || value.type === "invalid") {- return <Span keyword>{value.value}</Span>;- }-- // @todo: not sure this is the best way to handle "unset"- if (value.type === "unset") {- return <Span keyword>unset</Span>;- }-- throw new Error(`Unexpected StyleValue type ${value.type}`);- }, [value, source]);-- const ref = useRef<HTMLSpanElement>(null);-- useLayoutEffect(() => {- const element = ref.current;- if (element === null) {- return;- }-- // When content wraps, browser sets width of Container to the value of max-width,- // but we want it to "hug" content.- // width:max-content sounds like it would do the trick, but has no effect in this case.- // width:min-content works, but it causes content to wrap even when there is enough space.- //- // So we solve this with JavaScript by using min-content,- // but only if it doesn't cause wrapping.-- element.style.width = "auto";- const heightWithAuto = element.getBoundingClientRect().height;-- element.style.width = "min-content";- const heightWithMinContent = element.getBoundingClientRect().height;-- if (heightWithAuto !== heightWithMinContent) {- element.style.width = "auto";- }- }, [children]);-- return (- <Container source={source} {...rest} ref={ref}>- {children}- </Container>- );-};diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx b/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsxindex 5e0337a778..170e99e353 100644--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx@@ -68,7 +68,7 @@ const useScrub = ({valueRef.current = value;- const type = valueRef.current.type;+ // const type = valueRef.current.type;// Since scrub is going to call onChange and onChangeComplete callbacks, it will result in a new value and potentially new callback refs.// We need this effect to ONLY run when type or unit changes, but not when callbacks or value.value changes.@@ -76,8 +76,12 @@ const useScrub = ({const inputRefCurrent = inputRef.current;const scrubRefCurrent = scrubRef.current;+ const { current } = valueRef;++ // Support only auto keyword to be scrubbableif (- type !== "unit" ||+ (current.type !== "unit" &&+ !(current.type === "keyword" && current.value === "auto")) ||inputRefCurrent === null ||scrubRefCurrent === null) {@@ -88,7 +92,7 @@ const useScrub = ({const validateValue = (numericValue: number) => {let value: CssValueInputValue = {- type,+ type: "unit",unit,value: numericValue,};@@ -141,12 +145,20 @@ const useScrub = ({if (valueRef.current.type === "unit") {return valueRef.current.value;}++ if (+ valueRef.current.type === "keyword" &&+ valueRef.current.value === "auto"+ ) {+ return 0;+ }},onStart() {// for TSif (valueRef.current.type !== "unit") {return;}+unit = valueRef.current.unit;},onValueInput(event) {@@ -173,7 +185,7 @@ const useScrub = ({},shouldHandleEvent: shouldHandleEvent,});- }, [type, shouldHandleEvent, property]);+ }, [shouldHandleEvent, property]);return [scrubRef, inputRef];};