Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

Keyboard support in spacing control (#723)

Roman Pominovbf75cbb664ab
diff --git a/apps/designer/app/designer/features/style-panel/sections/spacing/keyboard.ts b/apps/designer/app/designer/features/style-panel/sections/spacing/keyboard.ts
new file mode 100644
index 0000000000..5d7818dc36
--- /dev/null
+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/keyboard.ts
@@ -0,0 +1,102 @@
+import { useState } from "react";
+import type { FocusEvent, KeyboardEvent, MouseEvent } from "react";
+import type { SpacingStyleProperty } from "./types";
+
+const movementKeys = [
+ "ArrowUp",
+ "ArrowRight",
+ "ArrowDown",
+ "ArrowLeft",
+] as const;
+
+const movementMap = {
+ marginTop: ["marginBottom", "marginRight", "paddingTop", "marginLeft"],
+ marginRight: ["marginTop", "marginLeft", "marginBottom", "paddingRight"],
+ marginBottom: ["paddingBottom", "marginRight", "marginTop", "marginLeft"],
+ marginLeft: ["marginTop", "paddingLeft", "marginBottom", "marginRight"],
+ paddingTop: ["marginTop", "paddingRight", "paddingBottom", "paddingLeft"],
+ paddingRight: ["paddingTop", "marginRight", "paddingBottom", "paddingBottom"],
+ paddingBottom: ["paddingTop", "paddingRight", "marginBottom", "paddingLeft"],
+ paddingLeft: ["paddingTop", "paddingTop", "paddingBottom", "marginLeft"],
+} as const;
+
+export const useKeyboardNavigation = ({
+ onOpen,
+}: {
+ onOpen: (property: SpacingStyleProperty) => void;
+}) => {
+ const [activeProperty, setActiveProperty] =
+ useState<SpacingStyleProperty>("marginTop");
+
+ const [isActive, setIsActive] = useState(false);
+
+ const hadnleFocus = (event: FocusEvent<HTMLElement>) => {
+ if (event.currentTarget.matches(":focus-visible")) {
+ setIsActive(true);
+ }
+ };
+
+ const handleBlur = () => {
+ setIsActive(false);
+ };
+
+ const handleHover = (property: SpacingStyleProperty | undefined) => {
+ // switch to mouse navigation if user starts to use mouse
+ setIsActive(false);
+
+ // keep active property in sync with hover (makes UX more intuitive)
+ if (property) {
+ setActiveProperty(property);
+ }
+ };
+
+ // switch back to keyboard navigation on mouse leave
+ const handleMouseLeave = (event: MouseEvent<HTMLElement>) => {
+ if (event.currentTarget.matches(":focus-visible")) {
+ setIsActive(true);
+ }
+ };
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLElement>) => {
+ // ignore events originating from popover input or something
+ if (event.target !== event.currentTarget) {
+ return;
+ }
+
+ // 1. handle transition from :focus to :focus-visible
+ // 2. switch from mouse navigation back to keyboard navigation if user starts to use keyboard
+ if (event.currentTarget.matches(":focus-visible")) {
+ setIsActive(true);
+ }
+
+ if (
+ event.key === "ArrowUp" ||
+ event.key === "ArrowRight" ||
+ event.key === "ArrowDown" ||
+ event.key === "ArrowLeft"
+ ) {
+ event.preventDefault(); // prevent scrolling
+ const key = event.key;
+ setActiveProperty(
+ (property) => movementMap[property][movementKeys.indexOf(key)]
+ );
+ }
+
+ if (event.key === "Enter") {
+ event.preventDefault(); // not sure we need this, but just in case
+ onOpen(activeProperty);
+ }
+ };
+
+ return {
+ activeProperty,
+ isActive,
+ handleHover,
+
+ // these are supposed to be put on the root element of the control
+ hadnleFocus,
+ handleBlur,
+ handleKeyDown,
+ handleMouseLeave,
+ };
+};
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.tsx
index bd935d6f73..389417f950 100644
--- a/apps/designer/app/designer/features/style-panel/sections/spacing/layout.tsx
+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/layout.tsx
@@ -1,5 +1,6 @@
import { styled, useId } from "@webstudio-is/design-system";
-import type { ComponentProps } from "react";
+import { forwardRef } from "react";
+import type { ComponentProps, Ref } from "react";
import type { HoverTagret, SpacingStyleProperty } from "./types";
import { spacingPropertiesNames } from "./types";
@@ -121,13 +122,6 @@ const MostInnerRect = styled(
{ 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",
@@ -144,6 +138,21 @@ const Grid = styled("div", {
pointerEvents: "none",
});
+const Container = styled("div", {
+ userSelect: "none",
+ position: "relative",
+ width: TOTAL_WIDTH,
+ height: TOTAL_HEIGHT,
+ "&:focus-visible": { outline: "none" },
+
+ // Grid happens to be positioned perfectly for the focus outline
+ // (both in z-order and in top/left)
+ [`&:focus-visible > ${Grid}`]: {
+ borderRadius: "$borderRadius$3",
+ outline: "2px solid $colors$blue10",
+ },
+});
+
const Cell = styled("div", {
position: "relative",
display: "flex",
@@ -221,81 +230,103 @@ const getPath = (property: SpacingStyleProperty) => {
};
type LayoutProps = {
- onClick: () => void;
+ onFocus?: ComponentProps<"div">["onFocus"];
+ onBlur?: ComponentProps<"div">["onBlur"];
+ onKeyDown?: ComponentProps<"div">["onKeyDown"];
+ onClick?: ComponentProps<"div">["onClick"];
+ onMouseLeave?: ComponentProps<"div">["onMouseLeave"];
onHover: (hoverTarget: HoverTagret | undefined) => void;
activeProperties?: ReadonlyArray<SpacingStyleProperty>;
renderCell: (args: { property: SpacingStyleProperty }) => React.ReactNode;
};
-export const SpacingLayout = ({
- onClick,
- onHover,
- activeProperties,
- renderCell,
-}: LayoutProps) => {
- const outerClipId = useId();
- const innerClipId = useId();
+export const SpacingLayout = forwardRef(
+ (
+ {
+ onFocus,
+ onBlur,
+ onKeyDown,
+ onClick,
+ onHover,
+ onMouseLeave,
+ activeProperties,
+ renderCell,
+ }: LayoutProps,
+ ref: Ref<HTMLDivElement>
+ ) => {
+ 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={activeProperties?.includes(property)}
- />
- );
+ const renderValueArea = (property: SpacingStyleProperty) => (
+ <ValueArea
+ side={getSide(property)}
+ d={getPath(property)}
+ onMouseEnter={(event) =>
+ onHover({ element: event.currentTarget, property })
+ }
+ onMouseLeave={() => onHover(undefined)}
+ isActive={activeProperties?.includes(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"
+ return (
+ <Container
+ onClick={onClick}
+ onFocus={onFocus}
+ onBlur={onBlur}
+ onKeyDown={onKeyDown}
+ onMouseLeave={onMouseLeave}
+ tabIndex={0}
+ ref={ref}
>
- <g clipPath={`url(#${outerClipId})`}>
- {renderValueArea("marginTop")}
- {renderValueArea("marginRight")}
- {renderValueArea("marginBottom")}
- {renderValueArea("marginLeft")}
- </g>
+ <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 />
+ <OuterRect />
+ <InnerOuterRect />
- <g clipPath={`url(#${innerClipId})`}>
- {renderValueArea("paddingTop")}
- {renderValueArea("paddingRight")}
- {renderValueArea("paddingBottom")}
- {renderValueArea("paddingLeft")}
- </g>
+ <g clipPath={`url(#${innerClipId})`}>
+ {renderValueArea("paddingTop")}
+ {renderValueArea("paddingRight")}
+ {renderValueArea("paddingBottom")}
+ {renderValueArea("paddingLeft")}
+ </g>
- <InnerRect />
- <MostInnerRect />
+ <InnerRect />
+ <MostInnerRect />
- <defs>
- <clipPath id={outerClipId}>
- <OuterRect />
- </clipPath>
- <clipPath id={innerClipId}>
- <InnerRect />
- </clipPath>
- </defs>
- </svg>
- <Grid>
- <Label>Margin</Label>
- <Label inner>Padding</Label>
+ <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>
- );
-};
+ {spacingPropertiesNames.map((property) => (
+ <Cell property={property} key={property}>
+ {renderCell({ property })}
+ </Cell>
+ ))}
+ </Grid>
+ </Container>
+ );
+ }
+);
+SpacingLayout.displayName = "SpacingLayout";
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.tsx
index 734dd78d9c..d1eba052a0 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,4 +1,4 @@
-import { type ComponentProps, useState } from "react";
+import { type ComponentProps, useState, useRef } from "react";
import type { RenderCategoryProps } from "../../style-sections";
import { SpacingLayout } from "./layout";
import { ValueText } from "./value-text";
@@ -8,6 +8,7 @@ import type { SpacingStyleProperty, HoverTagret } from "./types";
import { InputPopover } from "./input-popover";
import { SpacingTooltip } from "./tooltip";
import { getStyleSource } from "../../shared/style-info";
+import { useKeyboardNavigation } from "./keyboard";
const Cell = ({
isPopoverOpen,
@@ -109,13 +110,39 @@ export const SpacingSection = ({
const [openProperty, setOpenProperty] = useState<SpacingStyleProperty>();
- const activeProperties =
- openProperty === undefined ? scrubStatus.properties : [openProperty];
+ const layoutRef = useRef<HTMLDivElement>(null);
+
+ const keyboardNavigation = useKeyboardNavigation({
+ onOpen: setOpenProperty,
+ });
+
+ // 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: HoverTagret | undefined) => {
+ setHoverTarget(target);
+ keyboardNavigation.handleHover(target?.property);
+ };
return (
<SpacingLayout
+ ref={layoutRef}
onClick={() => setOpenProperty(hoverTarget?.property)}
- onHover={setHoverTarget}
+ onHover={handleHover}
+ onFocus={keyboardNavigation.hadnleFocus}
+ onBlur={keyboardNavigation.handleBlur}
+ onKeyDown={keyboardNavigation.handleKeyDown}
+ onMouseLeave={keyboardNavigation.handleMouseLeave}
activeProperties={activeProperties}
renderCell={({ property }) => (
<Cell
@@ -123,6 +150,7 @@ export const SpacingSection = ({
onPopoverClose={() => {
if (openProperty === property) {
setOpenProperty(undefined);
+ layoutRef.current?.focus();
}
}}
onChange={(update, options) => {
@@ -132,7 +160,7 @@ export const SpacingSection = ({
deleteProperty(update.property, options);
}
}}
- onHover={setHoverTarget}
+ onHover={handleHover}
property={property}
scrubStatus={scrubStatus}
isActive={activeProperties.includes(property)}