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
Spacing UI (#550)
Roman Pominovdd331815464f
diff --git a/apps/designer/app/designer/features/style-panel/sections/spacing/input-popover.tsx b/apps/designer/app/designer/features/style-panel/sections/spacing/input-popover.tsxnew file mode 100644index 0000000000..eea9bd96c8--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/input-popover.tsx@@ -0,0 +1,124 @@+import { useState } from "react";+import {+ keyframes,+ Popover,+ PopoverTrigger,+ PopoverContent,+ PopoverPortal,+ styled,+} from "@webstudio-is/design-system";+import {+ CssValueInput,+ type IntermediateStyleValue,+} from "../../shared/css-value-input";+import type { StyleProperty, StyleValue } from "@webstudio-is/css-data";+import type { StyleChangeHandler } from "./types";++const slideUpAndFade = keyframes({+ "0%": { opacity: 0, transform: "scale(0.8)" },+ "100%": { opacity: 1, transform: "scale(1)" },+});++const Input = ({+ value,+ property,+ onChange,+ onClosePopover,+}: {+ property: StyleProperty;+ value: StyleValue;+ onChange: StyleChangeHandler;+ onClosePopover: () => void;+}) => {+ const [intermediateValue, setIntermediateValue] = useState<+ StyleValue | IntermediateStyleValue+ >();++ return (+ <CssValueInput+ property={property}+ value={value}+ intermediateValue={intermediateValue}+ onChange={(styleValue) => {+ setIntermediateValue(styleValue);+ if (styleValue.type !== "intermediate") {+ onChange(+ { operation: "set", property, value: styleValue },+ { isEphemeral: true }+ );+ }+ }}+ onHighlight={(styleValue) => {+ onChange(+ { operation: "set", property, value: styleValue },+ { isEphemeral: true }+ );+ }}+ onChangeComplete={({ value, reason }) => {+ setIntermediateValue(undefined);+ onChange({ operation: "set", property, value }, { isEphemeral: false });++ // @todo: handle Esc+ if (reason === "blur" || reason === "enter") {+ onClosePopover();+ }+ }}+ />+ );+};++// trigger is used only for positioning+const Trigger = styled("div", { position: "absolute", width: 0, height: 0 });++const PopoverContentStyled = styled(PopoverContent, {+ minWidth: 0,+ minHeight: 0,+ width: "$spacing$20",+ border: "1px solid $colors$slate8",+ borderRadius: "$borderRadius$7",+ background: "$colors$gray2",+ padding: "$spacing$5",+ boxShadow: "0px 2px 7px rgba(0, 0, 0, 0.1), 0px 5px 17px rgba(0, 0, 0, 0.15)",+ animationDuration: "200ms",+ animationTimingFunction: "$easing$easeOut",+ '&[data-state="open"]': { animationName: slideUpAndFade },+});++export const InputPopover = ({+ value,+ property,+ onChange,+ isOpen,+ onClose,+}: {+ property: StyleProperty;+ value: StyleValue;+ onChange: StyleChangeHandler;+ isOpen: boolean;+ onClose: () => void;+}) => {+ return (+ <Popover+ open={isOpen}+ onOpenChange={(nextOpen) => {+ if (nextOpen === false) {+ onClose();+ }+ }}+ >+ <PopoverTrigger asChild>+ <Trigger />+ </PopoverTrigger>+ <PopoverPortal>+ <PopoverContentStyled hideArrow sideOffset={-24}>+ <Input+ value={value}+ property={property}+ onChange={onChange}+ onClosePopover={onClose}+ />+ </PopoverContentStyled>+ </PopoverPortal>+ </Popover>+ );+};diff --git a/apps/designer/app/designer/features/style-panel/sections/spacing/layout.stories.tsx b/apps/designer/app/designer/features/style-panel/sections/spacing/layout.stories.tsxnew file mode 100644index 0000000000..ac460511f8--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/layout.stories.tsx@@ -0,0 +1,17 @@+import type { ComponentMeta } from "@storybook/react";+import React from "react";+import { SpacingLayout } from "./layout";++export const Layout = (+ args: Omit<React.ComponentProps<typeof SpacingLayout>, "renderCell">+) => (+ <SpacingLayout+ renderCell={() => <div style={{ color: "red" }}>·</div>}+ {...args}+ />+);++export default {+ title: "Spacing/Layout",+ component: Layout,+} as ComponentMeta<typeof Layout>;diff --git a/apps/designer/app/designer/features/style-panel/sections/spacing/layout.tsx b/apps/designer/app/designer/features/style-panel/sections/spacing/layout.tsxnew file mode 100644index 0000000000..15ae423e08--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/layout.tsx@@ -0,0 +1,301 @@+import { styled, useId } from "@webstudio-is/design-system";+import type { ComponentProps } from "react";+import type { HoverTagret, SpacingStyleProperty } from "./types";+import { spacingPropertiesNames } from "./types";++const VALUE_WIDTH = 34;+const VALUE_HEIGHT = 24;++const BORDER = 1;+const INNER_MARGIN = 3;++const MOST_INNER_WIDTH = 62;+const MOST_INNER_HEIGHT = 6;++const INNER_WIDTH = MOST_INNER_WIDTH + (VALUE_WIDTH + BORDER) * 2;+const INNER_HEIGHT = MOST_INNER_HEIGHT + (VALUE_HEIGHT + BORDER) * 2;++const TOTAL_WIDTH = INNER_WIDTH + (INNER_MARGIN + VALUE_WIDTH + BORDER) * 2;+const TOTAL_HEIGHT = INNER_HEIGHT + (INNER_MARGIN + VALUE_HEIGHT + BORDER) * 2;++// in SVG stroke is always in the middle of the line+const emulateInnerStroke = ({+ width,+ height,+ x,+ y,+ strokeWidth = 1,+}: {+ width: number; // total desired size including border+ height: number;+ x: number;+ y: number;+ strokeWidth?: number;+}) => ({+ x: x + strokeWidth / 2,+ y: y + strokeWidth / 2,+ width: width - strokeWidth,+ height: height - strokeWidth,+});++const ValueArea = styled("path", {+ fill: "$slate2",+ variants: {+ side: {+ top: { cursor: "n-resize" },+ bottom: { cursor: "s-resize" },+ right: { cursor: "e-resize", fill: "$slate3" },+ left: { cursor: "w-resize", fill: "$slate3" },+ },+ isActive: { true: { fill: "$slate5" } },+ },+});++const OuterRect = styled(+ (props: ComponentProps<"rect">) => (+ <rect+ rx="2.5"+ {...emulateInnerStroke({+ width: TOTAL_WIDTH,+ height: TOTAL_HEIGHT,+ x: 0,+ y: 0,+ })}+ {...props}+ />+ ),+ { stroke: "$slate8" }+);++const InnerOuterRect = styled(+ (props: ComponentProps<"rect">) => {+ const width = INNER_WIDTH + INNER_MARGIN * 2;+ const height = INNER_HEIGHT + INNER_MARGIN * 2;+ return (+ <rect+ rx="2.5"+ {...emulateInnerStroke({+ width,+ height,+ x: (TOTAL_WIDTH - width) / 2,+ y: (TOTAL_HEIGHT - height) / 2,+ })}+ {...props}+ />+ );+ },+ { stroke: "$slate8", fill: "$loContrast" }+);++const InnerRect = styled(+ (props: ComponentProps<"rect">) => (+ <rect+ rx=".5"+ {...emulateInnerStroke({+ width: INNER_WIDTH,+ height: INNER_HEIGHT,+ x: (TOTAL_WIDTH - INNER_WIDTH) / 2,+ y: (TOTAL_HEIGHT - INNER_HEIGHT) / 2,+ })}+ {...props}+ />+ ),+ { stroke: "$slate8" }+);++const MostInnerRect = styled(+ (props: ComponentProps<"rect">) => {+ return (+ <rect+ rx=".5"+ {...emulateInnerStroke({+ width: MOST_INNER_WIDTH,+ height: MOST_INNER_HEIGHT,+ x: (TOTAL_WIDTH - MOST_INNER_WIDTH) / 2,+ y: (TOTAL_HEIGHT - MOST_INNER_HEIGHT) / 2,+ })}+ {...props}+ />+ );+ },+ { stroke: "$slate8", fill: "$loContrast" }+);++const Container = styled("div", {+ userSelect: "none",+ position: "relative",+ width: TOTAL_WIDTH,+ height: TOTAL_HEIGHT,+});++const gap = `${INNER_MARGIN + BORDER}px`;+const Grid = styled("div", {+ position: "absolute",+ top: 1,+ left: 1,+ right: 1,+ bottom: 1,+ display: "grid",+ columnGap: gap,+ // minmax here is a hack: https://css-tricks.com/preventing-a-grid-blowout/+ gridTemplateColumns: `${VALUE_WIDTH}px ${VALUE_WIDTH}px minmax(0, 1fr) ${VALUE_WIDTH}px ${VALUE_WIDTH}px`,+ // gap is inserted manually because we don't want it around the "auto" row+ gridTemplateRows: `${VALUE_HEIGHT}px ${gap} ${VALUE_HEIGHT}px auto ${VALUE_HEIGHT}px ${gap} ${VALUE_HEIGHT}px`,+ pointerEvents: "none",+});++const Cell = styled("div", {+ position: "relative",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ maxWidth: "100%",+ variants: {+ property: {+ marginTop: { gridColumn: "2 / 5", gridRow: "1" },+ marginRight: { gridColumn: "5", gridRow: "1 / 8" },+ marginBottom: { gridColumn: "2 / 5", gridRow: "7" },+ marginLeft: { gridColumn: "1", gridRow: "1 / 8" },+ paddingTop: { gridColumn: "3 / 4", gridRow: "3" },+ paddingRight: { gridColumn: "4", gridRow: "3 / 6" },+ paddingBottom: { gridColumn: "3 / 4", gridRow: "5" },+ paddingLeft: { gridColumn: "2", gridRow: "3 / 6" },+ },+ },+});++const Label = styled("div", {+ color: "$colors$slate11",+ textTransform: "uppercase",+ fontSize: "$fontSize$1",+ lineHeight: 1,+ marginTop: 3,+ marginLeft: 4,+ gridColumn: "1 / 6",+ gridRow: "1",+ variants: {+ inner: { true: { gridColumn: "2 / 5", gridRow: "3" } },+ },+});++const getSide = (property: SpacingStyleProperty) => {+ switch (property) {+ case "marginTop":+ case "paddingTop":+ return "top";+ case "marginRight":+ case "paddingRight":+ return "right";+ case "marginBottom":+ case "paddingBottom":+ return "bottom";+ case "marginLeft":+ case "paddingLeft":+ return "left";+ }+};++const getPath = (property: SpacingStyleProperty) => {+ const width = TOTAL_WIDTH;+ const height = TOTAL_HEIGHT;+ // distance between LeftValueArea's and RightValueArea's tips in the middle+ const tips =+ MOST_INNER_WIDTH - MOST_INNER_HEIGHT * (VALUE_WIDTH / VALUE_HEIGHT);++ switch (getSide(property)) {+ case "top":+ return `M${width} 0H0L${(width - tips) / 2} ${height / 2}H${+ (width + tips) / 2+ }L${width} 0Z`;+ case "right":+ return `M${width} ${height}L${(width + tips) / 2} ${+ height / 2+ }L${width} 0V${height}Z`;+ case "bottom":+ return `M${width} ${height}H0L${(width - tips) / 2} ${height / 2}H${+ (width + tips) / 2+ }L${width} ${height}Z`;+ case "left":+ return `M0 0L${(width - tips) / 2} ${height / 2}L0 ${height}V0Z`;+ }+};++type LayoutProps = {+ onClick: () => void;+ onHover: (hoverTarget: HoverTagret | undefined) => void;+ activeProperty?: SpacingStyleProperty;+ renderCell: (args: { property: SpacingStyleProperty }) => React.ReactNode;+};++export const SpacingLayout = ({+ onClick,+ onHover,+ activeProperty,+ renderCell,+}: LayoutProps) => {+ const outerClipId = useId();+ const innerClipId = useId();++ const renderValueArea = (property: SpacingStyleProperty) => (+ <ValueArea+ side={getSide(property)}+ d={getPath(property)}+ onMouseEnter={(event) =>+ onHover({ element: event.currentTarget, property })+ }+ onMouseLeave={() => onHover(undefined)}+ isActive={activeProperty === property}+ />+ );++ return (+ <Container onClick={onClick}>+ <svg+ width={TOTAL_WIDTH}+ height={TOTAL_HEIGHT}+ viewBox={`0 0 ${TOTAL_WIDTH} ${TOTAL_HEIGHT}`}+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <g clipPath={`url(#${outerClipId})`}>+ {renderValueArea("marginTop")}+ {renderValueArea("marginRight")}+ {renderValueArea("marginBottom")}+ {renderValueArea("marginLeft")}+ </g>++ <OuterRect />+ <InnerOuterRect />++ <g clipPath={`url(#${innerClipId})`}>+ {renderValueArea("paddingTop")}+ {renderValueArea("paddingRight")}+ {renderValueArea("paddingBottom")}+ {renderValueArea("paddingLeft")}+ </g>++ <InnerRect />+ <MostInnerRect />++ <defs>+ <clipPath id={outerClipId}>+ <OuterRect />+ </clipPath>+ <clipPath id={innerClipId}>+ <InnerRect />+ </clipPath>+ </defs>+ </svg>+ <Grid>+ <Label>Margin</Label>+ <Label inner>Padding</Label>++ {spacingPropertiesNames.map((property) => (+ <Cell property={property} key={property}>+ {renderCell({ property })}+ </Cell>+ ))}+ </Grid>+ </Container>+ );+};diff --git a/apps/designer/app/designer/features/style-panel/sections/spacing/scrub.tsx b/apps/designer/app/designer/features/style-panel/sections/spacing/scrub.tsxnew file mode 100644index 0000000000..5a5d893840--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/scrub.tsx@@ -0,0 +1,106 @@+import type { UnitValue } from "@webstudio-is/css-data";+import { numericScrubControl } from "@webstudio-is/design-system";+import { useState, useEffect, useRef } from "react";+import { getFinalValue } from "../../shared/get-final-value";+import type { RenderCategoryProps } from "../../style-sections";+import type {+ StyleChangeHandler,+ SpacingStyleProperty,+ HoverTagret,+} from "./types";++type ScrubStatus =+ | { isActive: false }+ | { isActive: true; property: SpacingStyleProperty; value: UnitValue };++export const useScrub = (+ props: {+ target: HoverTagret | undefined;+ onChange: StyleChangeHandler;+ } & Pick<RenderCategoryProps, "currentStyle" | "inheritedStyle">+): ScrubStatus => {+ // we want to hold on to the target while scrub is active even if hover changes+ const [activeTarget, setActiveTarget] = useState<HoverTagret>();+ const finalTarget = activeTarget ?? props.target;++ const [value, setValue] = useState<UnitValue>();++ // we need this in useEffect, but don't want it as a dependency+ const latestProps = useRef(props);+ latestProps.current = props;++ const unitRef = useRef<UnitValue["unit"]>();++ useEffect(() => {+ if (finalTarget === undefined) {+ return;+ }++ const property = finalTarget.property;++ const scrub = numericScrubControl(finalTarget.element, {+ direction:+ property.endsWith("Left") || property.endsWith("Right")+ ? "horizontal"+ : "vertical",+ getValue() {+ const { currentStyle, inheritedStyle } = latestProps.current;+ const value = getFinalValue({+ property: property,+ currentStyle,+ inheritedStyle,+ });+ if (value?.type === "unit") {+ unitRef.current = value.unit;+ return value.value;+ }+ },+ onValueInput(event) {+ // for TypeScript+ if (unitRef.current === undefined) {+ return;+ }++ const value = {+ type: "unit",+ value: event.value,+ unit: unitRef.current,+ } as const;++ setValue(value);+ latestProps.current.onChange(+ { operation: "set", property, value },+ { isEphemeral: true }+ );+ },+ onValueChange(event) {+ // for TypeScript+ if (unitRef.current === undefined) {+ return;+ }++ const value = {+ type: "unit",+ value: event.value,+ unit: unitRef.current,+ } as const;++ latestProps.current.onChange(+ { operation: "set", property, value },+ { isEphemeral: false }+ );+ },+ onStatusChange(status) {+ setActiveTarget(+ status === "scrubbing" ? latestProps.current.target : undefined+ );+ },+ });++ return scrub.disconnectedCallback;+ }, [finalTarget]);++ return activeTarget === undefined || value === undefined+ ? { isActive: false }+ : { isActive: true, property: activeTarget.property, value };+};diff --git a/apps/designer/app/designer/features/style-panel/sections/spacing/spacing.tsx b/apps/designer/app/designer/features/style-panel/sections/spacing/spacing.tsxindex a67489c5b6..33ba219aba 100644--- a/apps/designer/app/designer/features/style-panel/sections/spacing/spacing.tsx+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/spacing.tsx@@ -1,274 +1,144 @@-import { useEffect, useState } from "react";-import { categories } from "@webstudio-is/react-sdk";-import type { StyleProperty, StyleValue } from "@webstudio-is/css-data";-import { Box } from "@webstudio-is/design-system";-import { toValue } from "@webstudio-is/css-engine";-import { SetProperty } from "../../shared/use-style-data";-import { useIsFromCurrentBreakpoint } from "../../shared/use-is-from-current-breakpoint";-import { propertyNameColorForSelectedBreakpoint } from "../../shared/constants";+import { useState } from "react";import { getFinalValue } from "../../shared/get-final-value";+import { useIsFromCurrentBreakpoint } from "../../shared/use-is-from-current-breakpoint";import type { RenderCategoryProps } from "../../style-sections";--type SpacingSingularStyle = { [property in SpacingProperty]?: StyleValue };--type SpacingStyles = {- paddings: SpacingSingularStyle;- margins: SpacingSingularStyle;-};--type SpacingProperty = Margin | Padding;--type Margin = "marginTop" | "marginRight" | "marginBottom" | "marginLeft";--type Padding = "paddingTop" | "paddingRight" | "paddingBottom" | "paddingLeft";--const grid = {- margin: {- marginTop: "1 / 2 / 2 / 3",- marginRight: "2 / 3 / 3 / 4",- marginBottom: "3 / 2 / 4 / 3",- marginLeft: "2 / 1 / 3 / 2",- },- padding: {- paddingTop: "1 / 2 / 2 / 3",- paddingRight: "2 / 3 / 3 / 4",- paddingBottom: "3 / 2 / 4 / 3",- paddingLeft: "2 / 1 / 3 / 2",- },-};--const styles = {- spacingEdit: {- fontSize: "$fontSize$3",- // @todo use a color from design system- color: "rgb(217, 217, 217)",- display: "flex",- alignItems: "center",- justifyContent: "center",- },- wrapper: {- display: "grid",- height: 130,- gridTemplateColumns:- "$spacing$11 $spacing$3 $spacing$11 1fr $spacing$11 $spacing$3 $spacing$11",- gridTemplateRows:- "$spacing$11 $spacing$3 $spacing$11 1fr $spacing$11 $spacing$3 $spacing$11",- },- input: {- fontSize: "$fontSize$2",- fontWeight: 400,- fontFamily: "inherit",- display: "block",- background: "transparent",- color: "$hiContrast",- margin: "auto",- // @todo need to fit more chars- width: 40,- border: "none",- textAlign: "center",- outline: "none",- // No idea why it's hidden otherwise- zIndex: 0,- },- inputFromCurrentBreakpoint: {- color: propertyNameColorForSelectedBreakpoint,- },- emptySpace: {- gridArea: "2 / 2 / 3 / 2",- background: "$loContrast",- width: "$spacing$13",- margin: "auto",- height: "100%",- borderRadius: "$borderRadius$4",- },- marginGrid: {- gridArea: "1 / 1 / -1 / -1",- display: "grid",- gridTemplateColumns: "$spacing$11 1fr $spacing$11",- gridTemplateRows: "$spacing$11 minmax($spacing$9, 1fr) $spacing$11",- height: 130,- backgroundColor: "$gray6",- borderRadius: "$borderRadius$4",- px: 2,- },- text: {- fontWeight: "bold",- color: "$gray12",- fontSize: "$fontSize$1",- margin: "$spacing$3",- },- paddingGrid: {- gridArea: "3 / 3 / span 3 / span 3",- display: "grid",- gridTemplateColumns: "$spacing$11 1fr $spacing$11",- gridTemplateRows: "$spacing$11 minmax($spacing$9, 1fr) $spacing$11",- border: "2px solid",- borderColor: "$loContrast",- borderRadius: "$borderRadius$4",- },-};--type TextFieldProps = {- property: StyleProperty;- value: string | undefined;- onEnter: (value: string) => void;-};--const TextField = ({ property, value, onEnter }: TextFieldProps) => {- const [currentValue, setCurrentValue] = useState<string>(value ?? "");+import { SpacingLayout } from "./layout";+import { ValueText } from "./value-text";+import { useScrub } from "./scrub";+import type {+ StyleChangeHandler,+ SpacingStyleProperty,+ HoverTagret,+} from "./types";+import { InputPopover } from "./input-popover";+import { SpacingTooltip } from "./tooltip";++const Cell = ({+ isPopoverOpen,+ onPopoverClose,+ onChange,+ onHover,+ property,+ isActive,+ scrubStatus,+ currentStyle,+ inheritedStyle,+}: {+ isPopoverOpen: boolean;+ onPopoverClose: () => void;+ onChange: StyleChangeHandler;+ onHover: (target: HoverTagret | undefined) => void;+ property: SpacingStyleProperty;+ isActive: boolean;+ scrubStatus: ReturnType<typeof useScrub>;+} & Pick<RenderCategoryProps, "currentStyle" | "inheritedStyle">) => {const isFromCurrentBreakpoint = useIsFromCurrentBreakpoint(property);- useEffect(() => {- setCurrentValue(value ?? "");- }, [value]);+ const styleValue = getFinalValue({+ property,+ currentStyle,+ inheritedStyle,+ });- return (- <Box- as="input"- name={property}- aria-label={`${property} edit`}- value={currentValue}- onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {- if (event.key === "Enter") {- onEnter(currentValue);- }- }}- onChange={(event: React.ChangeEvent<HTMLInputElement>) => {- setCurrentValue(event.target.value);- }}- css={- isFromCurrentBreakpoint- ? { ...styles.input, ...styles.inputFromCurrentBreakpoint }- : styles.input- }- />- );-};+ const finalValue = scrubStatus.isActive ? scrubStatus.value : styleValue;-const toCss = (style: SpacingSingularStyle) => {- const css: Record<string, string> = {};- let property: SpacingProperty;- for (property in style) {- const value = style[property];- if (value === undefined) {- continue;- }- css[property] = toValue(value);+ // for TypeScript+ if (finalValue === undefined) {+ return null;}- return css;-};--type SpacingWidgetProps = {- setProperty: SetProperty;- values: SpacingStyles;-};--const SpacingWidget = ({ setProperty, values }: SpacingWidgetProps) => {- const margins = toCss(values.margins);- const paddings = toCss(values.paddings);-- const updateSpacing = ({- value,- property,- }: {- value: string;- property: StyleProperty;- }) => {- setProperty(property)(value);- };return (- <Box css={styles.wrapper}>- <Box css={styles.marginGrid}>- {(Object.keys(margins) as Array<Margin>).map((property: Margin) => (- <Box- key={property}- css={{- ...styles.spacingEdit,- gridArea: grid.margin[property],- }}- >- <TextField- property={property}- value={margins[property]}- onEnter={(value: string) => {- updateSpacing({- value,- property,- });- }}- />- </Box>- ))}- </Box>- <Box css={styles.paddingGrid}>- {(Object.keys(paddings) as Array<Padding>).map((property: Padding) => (- <Box- key={property}- css={{- ...styles.spacingEdit,- gridArea: grid.padding[property],- }}- >- <TextField- property={property}- value={paddings[property]}- onEnter={(value: string) => {- updateSpacing({- value,- property,- });- }}- />- </Box>- ))}- <Box css={styles.emptySpace} />- </Box>- <Box- css={{- ...styles.text,- gridArea: "3 / 3 / span 3 / span 3",- }}- >- PADDING- </Box>-- <Box+ <>+ <InputPopover+ value={finalValue}+ isOpen={isPopoverOpen}+ property={property}+ onChange={onChange}+ onClose={onPopoverClose}+ />+ <SpacingTooltip+ property={property}+ isOpen={+ isActive && isPopoverOpen === false && scrubStatus.isActive === false+ }+ />+ <ValueTextcss={{- ...styles.text,- gridArea: "1 / 1 / -1 / -1",+ // 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 SpacingLayout sets it to "none" for cells' content.+ pointerEvents: "all",}}- >- MARGIN- </Box>- </Box>+ value={finalValue}+ isActive={isActive}+ origin={isFromCurrentBreakpoint ? "set" : "unset"}+ onMouseEnter={(event) =>+ onHover({ property, element: event.currentTarget })+ }+ onMouseLeave={() => onHover(undefined)}+ />+ </>);};export const SpacingSection = ({+ setProperty,+ deleteProperty,currentStyle,inheritedStyle,- setProperty,}: RenderCategoryProps) => {- const styles = categories.spacing.properties.reduce(- (acc: SpacingStyles, property: SpacingProperty): SpacingStyles => {- const value = getFinalValue({- currentStyle,- inheritedStyle,- property,- });- if (value !== undefined) {- if (property.includes("margin")) {- acc.margins[property] = value;- } else {- acc.paddings[property] = value;- }- }+ const [hoverTarget, setHoverTarget] = useState<HoverTagret>();- return acc;- },- { margins: {}, paddings: {} } as SpacingStyles- );+ const handleChange: StyleChangeHandler = (update, options) => {+ if (update.operation === "set") {+ setProperty(update.property)(update.value, options);+ } else {+ deleteProperty(update.property);+ }+ };- return <SpacingWidget setProperty={setProperty} values={styles} />;+ const scrubStatus = useScrub({+ target: hoverTarget,+ onChange: handleChange,+ currentStyle,+ inheritedStyle,+ });++ const [openProperty, setOpenProperty] = useState<SpacingStyleProperty>();++ const activeProperty = scrubStatus.isActive+ ? scrubStatus.property+ : openProperty ?? hoverTarget?.property;++ return (+ <SpacingLayout+ onClick={() => setOpenProperty(hoverTarget?.property)}+ onHover={setHoverTarget}+ activeProperty={activeProperty}+ renderCell={({ property }) => (+ <Cell+ isPopoverOpen={openProperty === property}+ onPopoverClose={() => {+ if (openProperty === property) {+ setOpenProperty(undefined);+ }+ }}+ onChange={handleChange}+ onHover={setHoverTarget}+ property={property}+ scrubStatus={+ scrubStatus.isActive && scrubStatus.property === property+ ? scrubStatus+ : { isActive: false }+ }+ isActive={activeProperty === property}+ currentStyle={currentStyle}+ inheritedStyle={inheritedStyle}+ />+ )}+ />+ );};diff --git a/apps/designer/app/designer/features/style-panel/sections/spacing/tooltip.tsx b/apps/designer/app/designer/features/style-panel/sections/spacing/tooltip.tsxnew file mode 100644index 0000000000..59a772c11b--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/tooltip.tsx@@ -0,0 +1,51 @@+import { styled, Tooltip } from "@webstudio-is/design-system";+import { SpacingStyleProperty } from "./types";++// trigger is used only for positioning+const Trigger = styled("div", {+ position: "absolute",+ width: "100%",+ height: "100%",+ pointerEvents: "none",+ top: 0,+ left: 0,+});++const labels = {+ paddingTop: "Padding Top",+ paddingRight: "Padding Right",+ paddingBottom: "Padding Bottom",+ paddingLeft: "Padding Left",+ marginTop: "Margin Top",+ marginRight: "Margin Right",+ marginBottom: "Margin Bottom",+ marginLeft: "Margin Left",+};++const sides = {+ paddingTop: "top",+ paddingRight: "left",+ paddingBottom: "top",+ paddingLeft: "right",+ marginTop: "top",+ marginRight: "left",+ marginBottom: "top",+ marginLeft: "right",+} as const;++export const SpacingTooltip = ({+ property,+ isOpen,+}: {+ property: SpacingStyleProperty;+ isOpen: boolean;+}) => (+ <Tooltip+ open={isOpen}+ content={labels[property]}+ side={sides[property]}+ disableHoverableContent+ >+ <Trigger />+ </Tooltip>+);diff --git a/apps/designer/app/designer/features/style-panel/sections/spacing/types.ts b/apps/designer/app/designer/features/style-panel/sections/spacing/types.tsnew file mode 100644index 0000000000..7988ad6918--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/types.ts@@ -0,0 +1,17 @@+import { StyleUpdate } from "@webstudio-is/project";+import { categories } from "@webstudio-is/react-sdk";+import { StyleUpdateOptions } from "../../shared/use-style-data";++export const spacingPropertiesNames = categories.spacing.properties;++export type SpacingStyleProperty = typeof spacingPropertiesNames[number];++export type HoverTagret = {+ property: SpacingStyleProperty;+ element: SVGElement | HTMLElement;+};++export type StyleChangeHandler = (+ update: StyleUpdate,+ options: StyleUpdateOptions+) => void;diff --git a/apps/designer/app/designer/features/style-panel/sections/spacing/value-text.stories.tsx b/apps/designer/app/designer/features/style-panel/sections/spacing/value-text.stories.tsxnew file mode 100644index 0000000000..46bbb370b4--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/value-text.stories.tsx@@ -0,0 +1,58 @@+import type { ComponentMeta } from "@storybook/react";+import React from "react";+import { parseCssValue } from "../../shared/parse-css-value";+import { SpacingLayout } from "./layout";+import { ValueText as ValueTextComponent } from "./value-text";++export const ValueText = (+ args: Pick<+ React.ComponentProps<typeof ValueTextComponent>,+ "origin" | "value"+ >+) => {+ const [hovered, setHovered] = React.useState<{ property: string }>();+ return (+ <SpacingLayout+ onHover={setHovered}+ onClick={() => null}+ renderCell={({ property }) => (+ <ValueTextComponent+ isActive={property === hovered?.property}+ {...args}+ />+ )}+ />+ );+};++ValueText.args = {+ origin: "set",+ value: { type: "unit", value: 100, unit: "px" },+};++export default {+ title: "Spacing/ValueText",+ component: ValueText,+ argTypes: {+ origin: {+ control: "select",+ options: ["set", "preset", "unset", "inherited"],+ },+ value: {+ control: "select",+ options: Object.fromEntries(+ [+ "0",+ "10rem",+ "100rem",+ "100px",+ "1000px",+ "10000px",+ "100000px",+ "auto",+ "revert-layer",+ ].map((value) => [value, parseCssValue("marginTop", value)])+ ),+ },+ },+} as ComponentMeta<typeof ValueText>;diff --git a/apps/designer/app/designer/features/style-panel/sections/spacing/value-text.tsx b/apps/designer/app/designer/features/style-panel/sections/spacing/value-text.tsxnew file mode 100644index 0000000000..f41d590c55--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/value-text.tsx@@ -0,0 +1,125 @@+import { styled } from "@webstudio-is/design-system";+import type { StyleValue } from "@webstudio-is/css-data";+import { useLayoutEffect, useMemo, useRef, type ComponentProps } from "react";++const Container = styled("span", {+ boxSizing: "border-box",+ maxWidth: "100%",+ display: "flex",+ flexWrap: "wrap",+ alignItems: "end",+ justifyContent: "center",+ border: "1px solid transparent",+ borderRadius: "$borderRadius$3",+ padding: "0 $spacing$1",+ variants: {+ origin: {+ unset: { color: "$colors$slate11" },+ set: {+ color: "$colors$blue11",+ backgroundColor: "$colors$blue4",+ borderColor: "$colors$blue6",+ },+ preset: {+ // as I'm adding this Figma already uses new colors system,+ // so I don't know which tokens to use from our legacy system+ color: "#11181C", // foreground/main+ backgroundColor: "#DFE3E6", // background/preset/main+ borderColor: "#C1C8CD", // border/main+ },+ inherited: {+ color: "$colors$orange11",+ backgroundColor: "$colors$orange4",+ borderColor: "$colors$orange6",+ },+ },+ isActive: { true: {} },+ },+ compoundVariants: [+ { origin: "unset", isActive: true, css: { color: "$colors$slate12" } },+ ],+});++const Span = styled("span", {+ display: "block",+ fontSize: "$fontSize$2",+ lineHeight: 1,+ overflow: "hidden",+ maxWidth: "100%",+ whiteSpace: "nowrap",+ textOverflow: "ellipsis",+ variants: {+ keyword: { true: { fontSize: "$fontSize$1", textTransform: "uppercase" } },+ },+});++export const ValueText = ({+ value,+ origin,+ ...rest+}: { value: StyleValue } & ComponentProps<typeof Container>) => {+ const children = useMemo(() => {+ if (value.type === "unit") {+ // we want to show "0" rather than "0px" for unset values for cleaner UI+ if (origin === "unset" && 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, origin]);++ 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 origin={origin} {...rest} ref={ref}>+ {children}+ </Container>+ );+};diff --git a/apps/designer/app/designer/features/style-panel/shared/use-style-data.ts b/apps/designer/app/designer/features/style-panel/shared/use-style-data.tsindex 5964b6e6dc..e07e2f333c 100644--- a/apps/designer/app/designer/features/style-panel/shared/use-style-data.ts+++ b/apps/designer/app/designer/features/style-panel/shared/use-style-data.ts@@ -22,7 +22,7 @@ type UseStyleData = {selectedInstanceData?: SelectedInstanceData;};-type StyleUpdateOptions = { isEphemeral: boolean };+export type StyleUpdateOptions = { isEphemeral: boolean };// @todo: style must have StyleValue type alwaysexport type SetProperty = (diff --git a/packages/design-system/src/components/primitives/numeric-gesture-control.ts b/packages/design-system/src/components/primitives/numeric-gesture-control.tsindex b2fe43fc41..ca1cde95cb 100644--- a/packages/design-system/src/components/primitives/numeric-gesture-control.ts+++ b/packages/design-system/src/components/primitives/numeric-gesture-control.ts@@ -19,7 +19,7 @@ export type NumericScrubDirection = "horizontal" | "vertical";export type NumericScrubValue = number;export type NumericScrubCallback = (event: {- target: HTMLElement;+ target: HTMLElement | SVGElement;value: NumericScrubValue;preventDefault: () => void;}) => void;@@ -31,6 +31,7 @@ export type NumericScrubOptions = {direction?: NumericScrubDirection;onValueInput?: NumericScrubCallback;onValueChange?: NumericScrubCallback;+ onStatusChange?: (status: "idle" | "scrubbing") => void;shouldHandleEvent?: (node: EventTarget) => boolean;};@@ -42,7 +43,7 @@ type NumericScrubState = {};export const numericScrubControl = (- targetNode: HTMLElement,+ targetNode: HTMLElement | SVGElement,{minValue = Number.MIN_SAFE_INTEGER,maxValue = Number.MAX_SAFE_INTEGER,@@ -50,6 +51,7 @@ export const numericScrubControl = (direction = "horizontal",onValueInput,onValueChange,+ onStatusChange,shouldHandleEvent,}: NumericScrubOptions) => {@@ -64,7 +66,15 @@ export const numericScrubControl = (let exitPointerLock: (() => void) | undefined = undefined;- const handleEvent = (event: PointerEvent) => {+ // Cannot define `event:` as PointerEvent,+ // because (HTMLElement | SVGElement).addEventListener("pointermove", ...)+ // takes (Event => void) as a callback+ const handleEvent = (event: Event) => {+ // For TypeScript+ if (!(event instanceof PointerEvent)) {+ return;+ }+const { type, movementY, movementX } = event;const movement = direction === "horizontal" ? movementX : -movementY;@@ -72,6 +82,7 @@ export const numericScrubControl = (case "pointerup": {const shouldComponentUpdate = Boolean(state.cursor);targetNode.removeEventListener("pointermove", handleEvent);+ onStatusChange?.("idle");clearTimeout(state.timerId);exitPointerLock?.();@@ -111,6 +122,7 @@ export const numericScrubControl = (exitPointerLock = requestPointerLock(state, event, targetNode);}, 150);+ onStatusChange?.("scrubbing");targetNode.addEventListener("pointermove", handleEvent);break;}@@ -165,6 +177,7 @@ export const numericScrubControl = (clearTimeout(state.timerId);targetNode.removeEventListener("pointermove", handleEvent);+ onStatusChange?.("idle");exitPointerLock?.();exitPointerLock = undefined;@@ -175,7 +188,7 @@ export const numericScrubControl = (const requestPointerLock = (state: NumericScrubState,event: PointerEvent,- targetNode: HTMLElement+ targetNode: HTMLElement | SVGElement) => {// The pointer lock api nukes the cursor on requestng a pointer lock,// creating and managing the visual que of the cursor is thus left to the authordiff --git a/packages/design-system/src/stitches.config.ts b/packages/design-system/src/stitches.config.tsindex a01eb725c2..d9b4fee496 100644--- a/packages/design-system/src/stitches.config.ts+++ b/packages/design-system/src/stitches.config.ts@@ -294,6 +294,7 @@ const {},easing: {easeOutQuart: "cubic-bezier(0.25, 1, 0.5, 1)",+ easeOut: "cubic-bezier(0.16, 1, 0.3, 1)",},},media: {diff --git a/packages/project/src/shared/canvas-components/instance-data.ts b/packages/project/src/shared/canvas-components/instance-data.tsindex 755c8f5bf5..ddf6e43bc8 100644--- a/packages/project/src/shared/canvas-components/instance-data.ts+++ b/packages/project/src/shared/canvas-components/instance-data.ts@@ -20,7 +20,7 @@ export type HoveredInstanceData = {component: Instance["component"];};-type StyleUpdate =+export type StyleUpdate =| {operation: "delete";property: StyleProperty;