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
experimental: add tabbable command actions (#4407)
Bogdan Chadkinb8a341c4fdde
diff --git a/apps/builder/app/builder/features/command-panel/command-panel.tsx b/apps/builder/app/builder/features/command-panel/command-panel.tsxindex dbe915bb57..f0511171a5 100644--- a/apps/builder/app/builder/features/command-panel/command-panel.tsx+++ b/apps/builder/app/builder/features/command-panel/command-panel.tsx@@ -1,5 +1,7 @@import { atom, computed } from "nanostores";import { useStore } from "@nanostores/react";+import { useState } from "react";+import { matchSorter } from "match-sorter";import {collectionComponent,componentCategories,@@ -15,15 +17,19 @@ import {CommandGroupHeading,CommandItem,CommandIcon,+ useSelectedAction,ScrollArea,Flex,Kbd,Text,+ CommandFooter,+ Separator,} from "@webstudio-is/design-system";import { compareMedia } from "@webstudio-is/css-engine";import type { Breakpoint, Page } from "@webstudio-is/sdk";import {$breakpoints,+ $editingPageId,$pages,$registeredComponentMetas,$selectedBreakpoint,@@ -34,9 +40,8 @@ import { humanizeString } from "~/shared/string-utils";import { setCanvasWidth } from "~/builder/features/breakpoints";import { insert as insertComponent } from "~/builder/features/components/insert";import { $selectedPage, selectPage } from "~/shared/awareness";-import { useState } from "react";-import { matchSorter } from "match-sorter";import { mapGroupBy } from "~/shared/shim";+import { setActiveSidebarPanel } from "~/builder/shared/nano-states";const $commandPanel = atom<| undefined@@ -124,30 +129,35 @@ const $componentOptions = computed(});-const ComponentsGroup = ({ options }: { options: ComponentOption[] }) => {+const ComponentGroup = ({ options }: { options: ComponentOption[] }) => {return (<CommandGroup+ name="component"heading={<CommandGroupHeading>Components</CommandGroupHeading>}+ actions={["add"]}>{options.map(({ component, label, meta }) => {return (<CommandItemkey={component}- keywords={["Components"]}+ // preserve selected state when rerender+ value={component}onSelect={() => {closeCommandPanel();insertComponent(component);}}>- <CommandIcon- dangerouslySetInnerHTML={{ __html: meta.icon }}- ></CommandIcon>- <Text variant="labelsTitleCase">- {label}{" "}- <Text as="span" color="moreSubtle">- {humanizeString(meta.category ?? "")}+ <Flex gap={2}>+ <CommandIcon+ dangerouslySetInnerHTML={{ __html: meta.icon }}+ ></CommandIcon>+ <Text variant="labelsTitleCase">+ {label}{" "}+ <Text as="span" color="moreSubtle">+ {humanizeString(meta.category ?? "")}+ </Text></Text>- </Text>+ </Flex></CommandItem>);})}@@ -198,21 +208,24 @@ const getBreakpointLabel = (breakpoint: Breakpoint) => {return `${breakpoint.label}: ${label}`;};-const BreakpointsGroup = ({ options }: { options: BreakpointOption[] }) => {+const BreakpointGroup = ({ options }: { options: BreakpointOption[] }) => {return (<CommandGroup+ name="breakpoint"heading={<CommandGroupHeading>Breakpoints</CommandGroupHeading>}+ actions={["select"]}>{options.map(({ breakpoint, shortcut }) => (<CommandItemkey={breakpoint.id}+ // preserve selected state when rerender+ value={breakpoint.id}onSelect={() => {closeCommandPanel({ restoreFocus: true });$selectedBreakpointId.set(breakpoint.id);setCanvasWidth(breakpoint.id);}}>- <CommandIcon></CommandIcon><Text variant="labelsTitleCase">{getBreakpointLabel(breakpoint)}</Text>@@ -249,18 +262,33 @@ const $pageOptions = computed(});-const PagesGroup = ({ options }: { options: PageOption[] }) => {+const PageGroup = ({ options }: { options: PageOption[] }) => {+ const action = useSelectedAction();return (- <CommandGroup heading={<CommandGroupHeading>Pages</CommandGroupHeading>}>+ <CommandGroup+ name="page"+ heading={<CommandGroupHeading>Pages</CommandGroupHeading>}+ actions={["select", "settings"]}+ >{options.map(({ page }) => (<CommandItemkey={page.id}+ // preserve selected state when rerender+ value={page.id}onSelect={() => {closeCommandPanel();- selectPage(page.id);+ if (action === "select") {+ selectPage(page.id);+ setActiveSidebarPanel("auto");+ $editingPageId.set(undefined);+ }+ if (action === "settings") {+ selectPage(page.id);+ setActiveSidebarPanel("pages");+ $editingPageId.set(page.id);+ }}}>- <CommandIcon></CommandIcon><Text variant="labelsTitleCase">{page.name}</Text></CommandItem>))}@@ -288,7 +316,7 @@ const CommandDialogContent = () => {}const groups = mapGroupBy(matches, (match) => match.type);return (- <Command shouldFilter={false}>+ <><CommandInput value={search} onValueChange={setSearch} /><Flex direction="column" css={{ maxHeight: 300 }}><ScrollArea>@@ -296,7 +324,7 @@ const CommandDialogContent = () => {{Array.from(groups).map(([group, matches]) => {if (group === "component") {return (- <ComponentsGroup+ <ComponentGroupkey={group}options={matches as ComponentOption[]}/>@@ -304,7 +332,7 @@ const CommandDialogContent = () => {}if (group === "breakpoint") {return (- <BreakpointsGroup+ <BreakpointGroupkey={group}options={matches as BreakpointOption[]}/>@@ -312,14 +340,17 @@ const CommandDialogContent = () => {}if (group === "page") {return (- <PagesGroup key={group} options={matches as PageOption[]} />+ <PageGroup key={group} options={matches as PageOption[]} />);}+ group satisfies never;})}</CommandList></ScrollArea></Flex>- </Command>+ <Separator />+ <CommandFooter />+ </>);};@@ -330,7 +361,9 @@ export const CommandPanel = () => {open={isOpen}onOpenChange={() => closeCommandPanel({ restoreFocus: true })}>- <CommandDialogContent />+ <Command shouldFilter={false}>+ <CommandDialogContent />+ </Command></CommandDialog>);};diff --git a/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.tsx b/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.tsxindex c77c4ab4a4..5d7ef00047 100644--- a/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/shared/input-popover.tsx@@ -139,7 +139,6 @@ export const InputPopover = ({<Trigger /></PopoverTrigger><PopoverContentStyled- hideArrowsideOffset={-24}// prevent propagating click on input or combobox menu// and closing popover before applying changesdiff --git a/apps/builder/app/builder/features/topbar/menu/menu.tsx b/apps/builder/app/builder/features/topbar/menu/menu.tsxindex 1f2210b390..2b406c4226 100644--- a/apps/builder/app/builder/features/topbar/menu/menu.tsx+++ b/apps/builder/app/builder/features/topbar/menu/menu.tsx@@ -219,6 +219,13 @@ export const Menu = () => {<DropdownMenuSeparator />+ <DropdownMenuItem onSelect={() => emitCommand("openCommandPanel")}>+ Search & Commands+ <DropdownMenuItemRightSlot>+ <Kbd value={["cmd", "k"]} />+ </DropdownMenuItemRightSlot>+ </DropdownMenuItem>+<DropdownMenuItemonSelect={() => {window.open(diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex 3084a8accf..4f01134f32 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -349,7 +349,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({},{- name: "search",+ name: "openCommandPanel",defaultHotkeys: ["meta+k", "ctrl+k"],handler: openCommandPanel,},diff --git a/packages/design-system/src/components/command.stories.tsx b/packages/design-system/src/components/command.stories.tsxindex 244546ff0b..70847f8edd 100644--- a/packages/design-system/src/components/command.stories.tsx+++ b/packages/design-system/src/components/command.stories.tsx@@ -1,6 +1,7 @@import type { Meta, StoryFn } from "@storybook/react";import {Command as CommandComponent,+ CommandFooter,CommandGroup,CommandGroupHeading,CommandIcon,@@ -11,65 +12,93 @@ import {import { Text } from "./text";import { InfoCircleIcon } from "@webstudio-is/icons";import { Kbd } from "./kbd";+import { Flex } from "./flex";+import { Separator } from "./separator";const meta: Meta = {title: "Library/Command",};export default meta;-export const Command: StoryFn = () => {+const CommandContent = () => {return (- <CommandComponent>+ <><CommandInput /><CommandList><CommandGroupheading={<CommandGroupHeading>Suggestions</CommandGroupHeading>}+ name="suggestions"+ actions={["select", "edit", "delete"]}><CommandItem>- <CommandIcon>- <InfoCircleIcon />- </CommandIcon>- <Text variant="labelsTitleCase">Calendar</Text>+ <Flex gap={2}>+ <CommandIcon>+ <InfoCircleIcon />+ </CommandIcon>+ <Text variant="labelsTitleCase">Calendar</Text>+ </Flex></CommandItem><CommandItem>- <CommandIcon>- <InfoCircleIcon />- </CommandIcon>- <Text variant="labelsTitleCase">Search Emoji</Text>+ <Flex gap={2}>+ <CommandIcon>+ <InfoCircleIcon />+ </CommandIcon>+ <Text variant="labelsTitleCase">Search Emoji</Text>+ </Flex></CommandItem><CommandItem>- <CommandIcon>- <InfoCircleIcon />- </CommandIcon>- <Text variant="labelsTitleCase">Calculator</Text>+ <Flex gap={2}>+ <CommandIcon>+ <InfoCircleIcon />+ </CommandIcon>+ <Text variant="labelsTitleCase">Calculator</Text>+ </Flex></CommandItem></CommandGroup><CommandGroupheading={<CommandGroupHeading>Settings</CommandGroupHeading>}+ name="settings"+ actions={["open"]}><CommandItem>- <CommandIcon>- <InfoCircleIcon />- </CommandIcon>- <Text variant="labelsTitleCase">Profile</Text>+ <Flex gap={2}>+ <CommandIcon>+ <InfoCircleIcon />+ </CommandIcon>+ <Text variant="labelsTitleCase">Profile</Text>+ </Flex><Kbd value={["cmd", "p"]} /></CommandItem><CommandItem>- <CommandIcon>- <InfoCircleIcon />- </CommandIcon>- <Text variant="labelsTitleCase">Billing</Text>+ <Flex gap={2}>+ <CommandIcon>+ <InfoCircleIcon />+ </CommandIcon>+ <Text variant="labelsTitleCase">Billing</Text>+ </Flex><Kbd value={["cmd", "b"]} /></CommandItem><CommandItem>- <CommandIcon>- <InfoCircleIcon />- </CommandIcon>- <Text variant="labelsTitleCase">Settings</Text>+ <Flex gap={2}>+ <CommandIcon>+ <InfoCircleIcon />+ </CommandIcon>+ <Text variant="labelsTitleCase">Settings</Text>+ </Flex><Kbd value={["cmd", "s"]} /></CommandItem></CommandGroup></CommandList>+ <Separator />+ <CommandFooter />+ </>+ );+};++export const Command: StoryFn = () => {+ return (+ <CommandComponent>+ <CommandContent /></CommandComponent>);};diff --git a/packages/design-system/src/components/command.tsx b/packages/design-system/src/components/command.tsxindex 35b2677062..f302e661ea 100644--- a/packages/design-system/src/components/command.tsx+++ b/packages/design-system/src/components/command.tsx@@ -1,5 +1,19 @@-import type { ComponentPropsWithoutRef } from "react";-import { Command as CommandPrimitive, defaultFilter } from "cmdk";+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useRef,+ useState,+ type ComponentPropsWithoutRef,+ type Dispatch,+ type SetStateAction,+} from "react";+import {+ Command as CommandPrimitive,+ defaultFilter,+ useCommandState,+} from "cmdk";import { VisuallyHidden } from "@radix-ui/react-visually-hidden";import {DialogTitle,@@ -10,7 +24,11 @@ import {} from "@radix-ui/react-dialog";import { MagnifyingGlassIcon } from "@webstudio-is/icons";import { styled, theme } from "../stitches.config";-import { textVariants } from "./text";+import { Text, textVariants } from "./text";+import { Flex } from "./flex";+import { Button } from "./button";+import { Popover, PopoverContent, PopoverTrigger } from "./popover";+import { Kbd } from "./kbd";const panelWidth = "400px";const itemHeight = "32px";@@ -46,8 +64,39 @@ const lowerCasedFilter: CommandProps["filter"] = (aliases);+type CommandState = {+ highlightedGroup: string;+ actions: string[];+ actionIndex: number;+};++const CommandContext = createContext<+ [CommandState, Dispatch<SetStateAction<CommandState>>]+>([+ {+ highlightedGroup: "",+ actions: [],+ actionIndex: 0,+ },+ () => {},+]);++export const useSelectedAction = () => {+ const [state] = useContext(CommandContext);+ return state.actions[state.actionIndex];+};+export const Command = (props: CommandProps) => {- return <StyledCommand loop={true} filter={lowerCasedFilter} {...props} />;+ const state = useState<CommandState>({+ highlightedGroup: "",+ actions: [],+ actionIndex: 0,+ });+ return (+ <CommandContext.Provider value={state}>+ <StyledCommand loop={true} filter={lowerCasedFilter} {...props} />+ </CommandContext.Provider>+ );};const CommandDialogContent = styled(DialogContent, {@@ -79,7 +128,7 @@ export const CommandDialog = ({const CommandInputContainer = styled("div", {display: "grid",- gridTemplateColumns: `${itemHeight} 1fr`,+ gridTemplateColumns: `${itemHeight} 1fr max-content`,height: itemHeight,borderBottom: `var(${inputBorderBottomSize}) solid ${theme.colors.borderMain}`,});@@ -108,6 +157,7 @@ const CommandInputField = styled(CommandPrimitive.Input, {export const CommandInput = (props: ComponentPropsWithoutRef<typeof CommandPrimitive.Input>) => {+ const action = useSelectedAction();return (<CommandInputContainer><CommandInputIcon />@@ -116,18 +166,166 @@ export const CommandInput = (placeholder="Type a command or search..."{...props}/>+ <Text+ variant="labelsTitleCase"+ color="moreSubtle"+ css={{ alignSelf: "center", paddingInline: 8 }}+ >+ {action} <Kbd value={["enter"]} color="moreSubtle" />+ </Text></CommandInputContainer>);};+const ActionsCommand = styled(CommandPrimitive, {});++const useDebounceEffect = () => {+ const [updateCallback, setUpdateCallback] = useState(() => () => {+ /* empty */+ });+ useEffect(() => {+ // Because of how our styles works we need to update after React render to be sure that+ // all styles are applied+ updateCallback();+ }, [updateCallback]);+ return useCallback((callback: () => void) => {+ setUpdateCallback(() => callback);+ }, []);+};++export const CommandFooter = () => {+ const [isActionOpen, setIsActionOpen] = useState(false);+ const scheduleEffect = useDebounceEffect();++ const actionsRef = useRef<HTMLDivElement>(null);++ // store group actions whenever highlighted item is changed+ const [state, setState] = useContext(CommandContext);+ const highlightedValue = useCommandState((state) => state.value);+ useEffect(() => {+ const actionsElement = actionsRef.current?.closest("[cmdk-root]");+ const selectedGroup = actionsElement?.querySelector(+ "[cmdk-group]:has([aria-selected=true])"+ );+ const highlightedGroup = selectedGroup?.getAttribute("data-value") ?? "";+ const actions =+ selectedGroup?.getAttribute("data-actions")?.split(",") ?? [];+ setState((prev) => {+ // reset index only when group is changed+ if (prev.highlightedGroup === highlightedGroup) {+ return prev;+ }+ return { highlightedGroup, actions, actionIndex: 0 };+ });+ }, [highlightedValue, setState]);++ // open action popover with Tab+ useEffect(() => {+ const controller = new AbortController();+ const actionsElement = actionsRef.current?.closest("[cmdk-root]");+ if (actionsElement instanceof HTMLElement) {+ actionsElement.addEventListener(+ "keydown",+ (event) => {+ if (event.key === "Tab") {+ event.preventDefault();+ setIsActionOpen(true);+ }+ },+ { signal: controller.signal }+ );+ }+ return () => controller.abort();+ }, [setState]);++ return (+ <Flex+ justify="end"+ align="center"+ css={{ height: itemHeight, paddingInline: 4 }}+ ref={actionsRef}+ >+ <Popover open={isActionOpen} onOpenChange={setIsActionOpen}>+ <PopoverTrigger asChild>+ <Button tabIndex={-1} color="ghost" data-action-trigger>+ Actions <Kbd value={["tab"]} />+ </Button>+ </PopoverTrigger>+ <PopoverContent+ side="top"+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ // restore focus to the input instead of button+ const root = actionsRef.current?.closest("[cmdk-root]");+ const input = root?.querySelector("[cmdk-input]");+ if (input instanceof HTMLElement) {+ input.focus();+ }+ }}+ >+ <ActionsCommand>+ <CommandInputContainer>+ <CommandInputField placeholder="Choose action..." />+ </CommandInputContainer>+ <CommandList data-action-list>+ {state.actions.map((action, actionIndex) => (+ <CommandItem+ key={action}+ onSelect={() => {+ setState((prev) => ({ ...prev, actionIndex }));+ setIsActionOpen(false);+ const root = actionsRef.current?.closest("[cmdk-root]");+ const item = root?.querySelector(+ "[cmdk-group] [aria-selected=true]"+ );+ // execute after action state is applied+ scheduleEffect(() => {+ if (item instanceof HTMLElement) {+ item.click();+ }+ });+ }}+ >+ <Text variant="labelsTitleCase">{action}</Text>+ </CommandItem>+ ))}+ </CommandList>+ </ActionsCommand>+ </PopoverContent>+ </Popover>+ </Flex>+ );+};+export const CommandList = CommandPrimitive.List;-export const CommandGroup = CommandPrimitive.Group;+type CommandGroupProps = Omit<+ ComponentPropsWithoutRef<typeof CommandPrimitive.Group>,+ "value"+> & {+ name: string;+ actions: string[];+};++export const CommandGroup = ({+ name,+ actions,+ ...props+}: CommandGroupProps) => {+ return (+ <CommandPrimitive.Group+ {...props}+ value={name}+ data-actions={actions.join()}+ />+ );+};export const CommandGroupHeading = styled("div", {...textVariants.titles,color: theme.colors.foregroundMoreSubtle,display: "flex",+ gap: 8,alignItems: "center",paddingInline: 8,height: itemHeight,@@ -135,10 +333,10 @@ export const CommandGroupHeading = styled("div", {export const CommandItem = styled(CommandPrimitive.Item, {display: "grid",- gridTemplateColumns: `${itemHeight} 1fr max-content`,+ gridTemplateColumns: `1fr max-content`,alignItems: "center",minHeight: itemHeight,- paddingRight: 16,+ paddingInline: 16,"&[aria-selected=true]": {backgroundColor: theme.colors.backgroundHover,},diff --git a/packages/design-system/src/components/kbd.tsx b/packages/design-system/src/components/kbd.tsxindex 830adffca3..3ab7561a35 100644--- a/packages/design-system/src/components/kbd.tsx+++ b/packages/design-system/src/components/kbd.tsx@@ -9,6 +9,8 @@ const shortcutSymbolMap: Record<string, string> = {shift: "⇧",option: "⌥",backspace: "⌫",+ enter: "↵",+ tab: "tab",click: "+click",};diff --git a/packages/design-system/src/components/popover.tsx b/packages/design-system/src/components/popover.tsxindex 47798726d4..07b1db9106 100644--- a/packages/design-system/src/components/popover.tsx+++ b/packages/design-system/src/components/popover.tsx@@ -21,31 +21,15 @@ const contentStyle = css({},});-const ArrowBackground = styled("path", { fill: theme.colors.backgroundMenu });-const ArrowInnerBorder = styled("path", { fill: theme.colors.borderMenuInner });-const ArrowOuterBorder = styled("path", { fill: theme.colors.borderMain });-const ArrowSgv = styled("svg", { transform: "translateY(-3px)" });-const Arrow = () => (- <Primitive.Arrow width={16} height={11} asChild>- <ArrowSgv xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 11">- <ArrowOuterBorder d="M8.73 9.76a1 1 0 0 1-1.46 0L.5 2.54h15L8.73 9.76Z" />- <ArrowInnerBorder d="M8.146 8.909a.2.2 0 0 1-.292 0L.5 1.065h15L8.146 8.909Z" />- <ArrowBackground d="M8.073 7.52a.1.1 0 0 1-.146 0L.877 0h14.246l-7.05 7.52Z" />- </ArrowSgv>- </Primitive.Arrow>-);-export const PopoverContent = forwardRef(({children,className,css,- hideArrow,sideOffset,...props}: ComponentProps<typeof Primitive.Content> & {- hideArrow?: boolean;css?: CSS;},ref: Ref<HTMLDivElement>@@ -59,7 +43,6 @@ export const PopoverContent = forwardRef(ref={ref}>{children}- {hideArrow !== true && <Arrow />}</Primitive.Content></Primitive.Portal>)