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
Update Combobox
Andrey Okonetchnikovf7268d648200
diff --git a/packages/design-system/src/components/combobox.stories.tsx b/packages/design-system/src/components/combobox.stories.tsxindex f4eccfd4f3..5c1abba546 100644--- a/packages/design-system/src/components/combobox.stories.tsx+++ b/packages/design-system/src/components/combobox.stories.tsx@@ -1,7 +1,10 @@-import { action } from "@storybook/addon-actions";import { ComponentStory } from "@storybook/react";-import React from "react";-import { Combobox, ComboboxTextField } from "./combobox";+import { MagnifyingGlassIcon } from "@webstudio-is/icons";+import { useCombobox as useDownshiftCombobox } from "downshift";+import React, { useCallback } from "react";+import { TextField } from "./text-field";+import { Combobox, ComboboxListboxItem, useCombobox } from "./combobox";+import { Flex } from "./flex";export default {component: Combobox,@@ -13,59 +16,90 @@ export const Simple: ComponentStory<typeof Combobox> = () => {{ label: "Banana" },{ label: "Orange" },] as const;- const [value, setValue] = React.useState<typeof items[number] | undefined>();+ const [value, setValue] = React.useState<typeof items[number] | null>(null);return (<Comboboxname="fruit"placeholder="Select a fruit"items={items}value={value}- onItemSelect={setValue}+ onItemSelect={(value) => {+ // If the value is cleared, we revert to previous state+ if (value !== null) {+ setValue(value);+ }+ }}+ itemToString={(item) => item?.label ?? ""}/>);};-export const CustomInput: ComponentStory<typeof Combobox> = () => {- const items = [- { label: "Apple", value: "apple", disabled: true },- { label: "Banana", value: "banana" },- { label: "Orange", value: "orange" },- ];- const [value, setValue] = React.useState<typeof items[0] | undefined>(- items[0]- );+export const Complex: ComponentStory<typeof Combobox> = () => {+ const [value, setValue] = React.useState<string | null>(null);++ const stateReducer = useCallback((state, actionAndChanges) => {+ const { type, changes } = actionAndChanges;+ switch (type) {+ // on item selection.+ case useDownshiftCombobox.stateChangeTypes.ItemClick:+ case useDownshiftCombobox.stateChangeTypes.InputKeyDownEnter:+ case useDownshiftCombobox.stateChangeTypes.InputBlur:+ case useDownshiftCombobox.stateChangeTypes+ .ControlledPropUpdatedSelectedItem:+ return {+ ...changes,+ // if we have a selected item.+ ...(changes.selectedItem && {+ // we will set the input value to "" (empty string).+ inputValue: "",+ }),+ };++ // Remove "reset" action+ case useDownshiftCombobox.stateChangeTypes.InputKeyDownEscape: {+ return {+ ...state,+ };+ }++ default:+ return changes; // otherwise business as usual.+ }+ }, []);++ const { items, getComboboxProps, getMenuProps, getItemProps, getInputProps } =+ useCombobox({+ items: ["Apple", "Banana", "Orange"],+ value,+ itemToString: (item) => item ?? "",+ stateReducer,+ onItemSelect: (value) => {+ setValue(value);+ },+ });return (- <Combobox- name="fruit"- placeholder="Select a fruit"- items={items}- value={value}- onItemSelect={setValue}- onItemHighlight={(item) => {- action("Highlight")(item);- }}- renderTextField={({ inputProps, toggleProps }) => (- <ComboboxTextField- toggleProps={toggleProps}- inputProps={{- ...inputProps,- onKeyDown: (event) => {- inputProps.onKeyDown?.(event);- switch (event.key) {- case "Enter": {- action("Enter")(inputProps.value);- break;- }- }- },- onBlur: (event) => {- inputProps.onBlur?.(event);- action("Blur")(inputProps.value);- },- }}- />- )}- />+ <Flex {...getComboboxProps()} css={{ flexDirection: "column", gap: "$3" }}>+ <TextField+ type="search"+ prefix={<MagnifyingGlassIcon />}+ {...getInputProps({})}+ />+ <fieldset>+ <legend>Choose an item</legend>+ <Flex {...getMenuProps()} css={{ flexDirection: "column" }}>+ {items.map((item, index) => {+ return (+ <ComboboxListboxItem+ key={index}+ {...getItemProps({ item, index })}+ >+ {item}+ </ComboboxListboxItem>+ );+ })}+ </Flex>+ </fieldset>+ </Flex>);};diff --git a/packages/design-system/src/components/combobox.tsx b/packages/design-system/src/components/combobox.tsxindex 2e0dc1c1f3..ae936d67d5 100644--- a/packages/design-system/src/components/combobox.tsx+++ b/packages/design-system/src/components/combobox.tsx@@ -4,10 +4,16 @@ import {useCallback,type ComponentProps,type ForwardRefRenderFunction,+ useEffect,+ useRef,} from "react";import { CheckIcon, ChevronDownIcon } from "@webstudio-is/icons";import { Popper, PopperContent, PopperAnchor } from "@radix-ui/react-popper";-import { useCombobox, type UseComboboxGetItemPropsOptions } from "downshift";+import {+ DownshiftState,+ UseComboboxStateChangeOptions,+ useCombobox as useDownshiftCombobox,+} from "downshift";import { matchSorter } from "match-sorter";import { styled } from "../stitches.config";import { IconButton } from "./icon-button";@@ -17,37 +23,6 @@ import { TextField } from "./text-field";import { Box } from "./box";import { Grid } from "./grid";-type Label = string;--type BaseItem = { label: Label; disabled?: boolean } | Label;--type ComboboxTextFieldProps<Item> = {- inputProps: ComponentProps<typeof TextField>;- toggleProps: ComponentProps<typeof IconButton>;- highlightedItem?: Item;-};--const ComboboxTextFieldBase: ForwardRefRenderFunction<- HTMLDivElement,- ComboboxTextFieldProps<BaseItem>-> = ({ inputProps, toggleProps }, ref) => {- return (- <TextField- ref={ref}- suffix={- <IconButton {...toggleProps}>- <ChevronDownIcon />- </IconButton>- }- {...inputProps}- />- );-};--export const ComboboxTextField = forwardRef(ComboboxTextFieldBase);--ComboboxTextField.displayName = "ComboboxTextField";-const Listbox = styled("ul", panelStyles, {padding: 0,margin: 0,@@ -62,195 +37,191 @@ const ListboxItem = styled("li", itemCss, {margin: 0,});-type ListProps<Item> = {- containerProps: ComponentProps<typeof Listbox>;+export const ListboxItemBase: ForwardRefRenderFunction<+ HTMLLIElement,+ ComponentProps<typeof ListboxItem> & {+ disabled?: boolean;+ selected?: boolean;+ highlighted?: boolean;+ }+> = (props, ref) => {+ const { disabled, selected, highlighted, children, ...rest } = props;+ return (+ <ListboxItem+ ref={ref}+ {...(disabled ? { "aria-disabled": true, disabled: true } : {})}+ {...(selected ? { "aria-current": true } : {})}+ {...rest}+ >+ <Grid align="center" css={{ gridTemplateColumns: "$4 1fr" }}>+ {selected && <CheckIcon />}+ <Box css={{ gridColumn: 2 }}>{children}</Box>+ </Grid>+ </ListboxItem>+ );+};++export const ComboboxListboxItem = forwardRef(ListboxItemBase);++export const ComboboxPopperContent = PopperContent;++type useComboboxProps<Item> = {items: ReadonlyArray<Item>;- getItemProps: (- options: UseComboboxGetItemPropsOptions<Item>- ) => ComponentProps<typeof ListboxItem>;- highlightedIndex: number;- selectedItem: Item | null;itemToString: (item: Item | null) => string;+ value: Item | null; // This is to prevent: "downshift: A component has changed the uncontrolled prop "selectedItem" to be controlled."+ onItemSelect?: (value: Item | null) => void;+ onItemHighlight?: (value: Item | null) => void;+ stateReducer?: (+ state: DownshiftState<Item>,+ changes: UseComboboxStateChangeOptions<Item>+ ) => Partial<UseComboboxStateChangeOptions<Item>>;};-export const List = <Item extends BaseItem>({- containerProps,+// eslint-disable-next-line func-style+export function useCombobox<Item>({items,- getItemProps,- highlightedIndex,- selectedItem,+ value,itemToString,-}: ListProps<Item>) => {- return (- <Listbox {...containerProps}>- {items.map((item, index) => {- const itemProps: Record<string, unknown> = getItemProps({- item,- index,- key: index,- ...(typeof item === "object" && item.disabled- ? { "data-disabled": true, disabled: true }- : {}),- ...(highlightedIndex === index ? { "data-found": true } : {}),- });+ onItemSelect,+ onItemHighlight,+ stateReducer,+}: useComboboxProps<Item>) {+ const [filteredItems, setFilteredItems] = useState(items);+ const cachedItems = useRef(items);++ const downshiftProps = useDownshiftCombobox({+ items: filteredItems as Item[],+ selectedItem: value, // Avoid downshift warning about switching controlled mode+ stateReducer,+ itemToString,+ onInputValueChange({ inputValue }) {+ const foundItems: ReadonlyArray<Item> = matchSorter(+ items,+ inputValue ?? "",+ {+ keys: [(item) => itemToString(item)],+ }+ );+ setFilteredItems(foundItems);+ },+ onSelectedItemChange({ selectedItem }) {+ onItemSelect?.(selectedItem ?? null);+ },+ onHighlightedIndexChange({ highlightedIndex }) {+ if (highlightedIndex !== undefined) {+ onItemHighlight?.(items[highlightedIndex]);+ }+ },+ });++ const { isOpen, getItemProps, highlightedIndex, selectedItem } =+ downshiftProps;- return (- // eslint-disable-next-line react/jsx-key- <ListboxItem {...itemProps}>- <Grid align="center" css={{ gridTemplateColumns: "$4 1fr" }}>- {selectedItem === item && <CheckIcon />}- <Box css={{ gridColumn: 2 }}>{itemToString(item)}</Box>- </Grid>- </ListboxItem>- );- })}- </Listbox>+ useEffect(() => {+ cachedItems.current = items;+ }, [items]);++ useEffect(() => {+ if (!isOpen) {+ setFilteredItems(cachedItems.current);+ }+ }, [isOpen]);++ const enhancedGetItemProps = useCallback(+ (options) => {+ return getItemProps({+ highlighted: highlightedIndex === options.index,+ // We need to either deep compare objects here or use itemToString to get primitive types+ selected: itemToString(selectedItem) === itemToString(options.item),+ key: options.id,+ ...options,+ });+ },+ [getItemProps, highlightedIndex, itemToString, selectedItem]);-};-export const ComboboxPopperContent = PopperContent;+ return {+ ...downshiftProps,+ items: filteredItems, // Return filtered items+ getItemProps: enhancedGetItemProps,+ };+}-type ComboboxProps<Item> = {+type ComboboxProps<Item> = useComboboxProps<Item> & {name: string;label?: string;placeholder?: string;- items: ReadonlyArray<Item>;- value?: Item;- onItemSelect?: (value?: Item) => void;- onItemHighlight?: (value?: Item) => void;- itemToString?: (item?: Item | null) => string;- renderTextField?: (- props: ComponentProps<typeof ComboboxTextField>- ) => JSX.Element;- renderList?: (props: ListProps<Item>) => JSX.Element;- renderPopperContent?: (- props: ComponentProps<typeof ComboboxPopperContent>- ) => JSX.Element;};-export const Combobox = <Item extends BaseItem>({+// eslint-disable-next-line func-style+export function Combobox<Item>({items,- value,+ value = null,name,placeholder,- itemToString = (item) =>- item != null && "label" in item ? item.label : item ?? "",+ itemToString,onItemSelect,onItemHighlight,- renderTextField = (props) => <ComboboxTextField {...props} />,- // IMPORTANT! Without Item passed to list <List<Item> typescript is 10x slower!- renderList = (props) => <List<Item> {...props} />,- renderPopperContent = (props) => <ComboboxPopperContent {...props} />,-}: ComboboxProps<Item>) => {- const [foundItems, setFoundItems] = useState(items);+}: ComboboxProps<Item>) {const stateReducer = useCallback((state, actionAndChanges) => {const { type, changes } = actionAndChanges;switch (type) {- // on item selection.- case useCombobox.stateChangeTypes.ItemClick:- case useCombobox.stateChangeTypes.InputKeyDownEnter:- case useCombobox.stateChangeTypes.InputBlur:- case useCombobox.stateChangeTypes.ControlledPropUpdatedSelectedItem:- return {- ...changes,- // if we had an item selected.- ...(changes.selectedItem && {- // we will set the input value to be empty since we display it using prefix- inputValue: "",- }),- };- // Clear input value on escape- case useCombobox.stateChangeTypes.InputKeyDownEscape:- return {- ...changes,- inputValue: "",- selectedItem: null,- };- // Reset selectedItem when there is selection and we type something- case useCombobox.stateChangeTypes.InputChange:- return {- ...changes,- selectedItem: null,- };default:return changes; // otherwise business as usual.}}, []);+const {- isOpen,- getToggleButtonProps,- // getLabelProps,- getMenuProps,+ items: foundItems,getInputProps,getComboboxProps,- highlightedIndex,+ getToggleButtonProps,+ getMenuProps,getItemProps,- selectedItem,+ isOpen,} = useCombobox({- items: foundItems as Item[],- selectedItem: value ?? null, // Avoid downshift warning about switching controlled mode- stateReducer,+ items,+ value,itemToString,- onInputValueChange({ inputValue }) {- const options =- typeof items[0] === "object" && "label" in items[0]- ? { keys: ["label"] }- : undefined;- const foundItems = matchSorter(items, inputValue ?? "", options);- setFoundItems(foundItems);- },- onSelectedItemChange({ selectedItem }) {- onItemSelect?.(selectedItem ?? undefined);- },- onHighlightedIndexChange({ highlightedIndex }) {- if (highlightedIndex !== undefined) {- onItemHighlight?.(items[highlightedIndex]);- }- },- });-- const inputProps: Record<string, unknown> = getInputProps({- name,- placeholder: selectedItem ? "" : placeholder, // Placeholder should not be visible when we have selected item- prefix: itemToString?.(selectedItem ?? undefined),- onKeyDown: (event) => {- // When we press Backspace and the input is empty,- // we should to clear the selection- // @todo: it would be much better to handle this in reducer but downshift doesn't handle this event- if (event.key === "Backspace" && selectedItem !== null) {- onItemSelect?.(undefined);- }- },+ onItemSelect,+ onItemHighlight,+ stateReducer,});- const toggleProps: Record<string, unknown> = getToggleButtonProps();- const comboboxProps: Record<string, unknown> = getComboboxProps();- const menuProps: Record<string, unknown> = getMenuProps();- const highlightedItem = foundItems[highlightedIndex];-return (<Popper>- <Box {...comboboxProps}>+ <Box {...getComboboxProps()}><PopperAnchor>- {renderTextField({- inputProps,- toggleProps,- highlightedItem,- })}+ <TextField+ {...getInputProps({+ name,+ placeholder,+ })}+ suffix={+ <IconButton {...getToggleButtonProps()}>+ <ChevronDownIcon />+ </IconButton>+ }+ /></PopperAnchor>- {renderPopperContent({- style: { zIndex: 1 },- children: renderList({- containerProps: menuProps,- items: isOpen ? foundItems : [],- getItemProps,- highlightedIndex,- selectedItem,- itemToString,- }),- })}+ <PopperContent>+ <Listbox {...getMenuProps()}>+ {isOpen &&+ foundItems.map((item, index) => {+ return (+ // eslint-disable-next-line react/jsx-key+ <ComboboxListboxItem+ key={index}+ {...getItemProps({ item, index })}+ >+ {itemToString(item)}+ </ComboboxListboxItem>+ );+ })}+ </Listbox>+ </PopperContent></Box></Popper>);-};+}Combobox.displayName = "Combobox";diff --git a/packages/design-system/src/components/menu.tsx b/packages/design-system/src/components/menu.tsxindex 903c3c77b4..cd0a2eea91 100644--- a/packages/design-system/src/components/menu.tsx+++ b/packages/design-system/src/components/menu.tsx@@ -24,12 +24,12 @@ export const baseItemCss = css({export const itemCss = css(baseItemCss, {position: "relative",color: "$hiContrast",- "&:focus, &[data-found]": {+ "&:focus, &[data-found], &[aria-selected=true]": {outline: "none",backgroundColor: "$blue9",color: "white",},- "&[data-disabled]": {+ "&[data-disabled], &[aria-disabled]": {color: "$slate9",},});