Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add autocomplete select menu component

dominik-zeglen022d3ad70e2e
diff --git a/saleor/static/dashboard-next/components/AutocompleteSelectMenu/AutocompleteSelectMenu.test.ts b/saleor/static/dashboard-next/components/AutocompleteSelectMenu/AutocompleteSelectMenu.test.ts
new file mode 100644
index 0000000000..7c78d08eb9
--- /dev/null
+++ b/saleor/static/dashboard-next/components/AutocompleteSelectMenu/AutocompleteSelectMenu.test.ts
@@ -0,0 +1,86 @@
+import { SelectMenuItem, validateOptions } from "./AutocompleteSelectMenu";
+
+describe("Validate Autocomplete Menu data structure", () => {
+ it("Properly catches same level duplicated value", () => {
+ const menu: SelectMenuItem[] = [
+ {
+ label: "1",
+ value: "1"
+ },
+ {
+ label: "2",
+ value: "2"
+ },
+ {
+ label: "1",
+ value: "1"
+ }
+ ];
+
+ expect(validateOptions(menu)).toBeFalsy();
+ });
+
+ it("Properly catches multi level duplicated value", () => {
+ const menu: SelectMenuItem[] = [
+ {
+ label: "1",
+ value: "1"
+ },
+ {
+ label: "2",
+ value: "2"
+ },
+ {
+ label: "3",
+ value: "3"
+ },
+ {
+ children: [
+ {
+ label: "4.1",
+ value: "4.1"
+ },
+ {
+ label: "1",
+ value: "1"
+ }
+ ],
+ label: "4"
+ }
+ ];
+
+ expect(validateOptions(menu)).toBeFalsy();
+ });
+
+ it("Properly passes valid structure", () => {
+ const menu: SelectMenuItem[] = [
+ {
+ label: "1",
+ value: "1"
+ },
+ {
+ label: "2",
+ value: "2"
+ },
+ {
+ label: "3",
+ value: "3"
+ },
+ {
+ children: [
+ {
+ label: "4.1",
+ value: "4.1"
+ },
+ {
+ label: "4.2",
+ value: "4.2"
+ }
+ ],
+ label: "4"
+ }
+ ];
+
+ expect(validateOptions(menu)).toBeTruthy();
+ });
+});
diff --git a/saleor/static/dashboard-next/components/AutocompleteSelectMenu/AutocompleteSelectMenu.tsx b/saleor/static/dashboard-next/components/AutocompleteSelectMenu/AutocompleteSelectMenu.tsx
new file mode 100644
index 0000000000..1bb56866f3
--- /dev/null
+++ b/saleor/static/dashboard-next/components/AutocompleteSelectMenu/AutocompleteSelectMenu.tsx
@@ -0,0 +1,199 @@
+import CircularProgress from "@material-ui/core/CircularProgress";
+import MenuItem from "@material-ui/core/MenuItem";
+import Paper from "@material-ui/core/Paper";
+import {
+ createStyles,
+ Theme,
+ withStyles,
+ WithStyles
+} from "@material-ui/core/styles";
+import TextField from "@material-ui/core/TextField";
+import ArrowBack from "@material-ui/icons/ArrowBack";
+import Downshift from "downshift";
+import * as React from "react";
+
+import i18n from "../../i18n";
+import Debounce, { DebounceProps } from "../Debounce";
+
+export interface SelectMenuItem {
+ children?: SelectMenuItem[];
+ label: React.ReactNode;
+ value?: string;
+}
+
+export interface AutocompleteSelectMenuProps {
+ disabled: boolean;
+ displayValue: string;
+ error: boolean;
+ helperText: string;
+ label: string;
+ loading: boolean;
+ name: string;
+ options: SelectMenuItem[];
+ placeholder: string;
+ onChange: (event: React.ChangeEvent<any>) => void;
+}
+
+function getOptionValues(option: SelectMenuItem): string[] {
+ return option.value
+ ? [option.value]
+ : option.children.reduce(
+ (acc, option) => [...acc, ...getOptionValues(option)],
+ []
+ );
+}
+
+export function validateOptions(options: SelectMenuItem[]): boolean {
+ const values: string[] = options.reduce(
+ (acc, option) => [...acc, ...getOptionValues(option)],
+ []
+ );
+ const uniqueValues = Array.from(new Set(values));
+ return uniqueValues.length === values.length;
+}
+
+const validationError: Error = new Error(
+ "Values supplied to AutocompleteSelectMenu should be unique"
+);
+
+function getMenu(options: SelectMenuItem[], path: number[]): SelectMenuItem[] {
+ if (path.length === 0) {
+ return options;
+ }
+ return getMenu(options[path[0]].children, path.slice(1));
+}
+
+const DebounceAutocomplete: React.ComponentType<
+ DebounceProps<string>
+> = Debounce;
+
+const styles = (theme: Theme) =>
+ createStyles({
+ container: {
+ flexGrow: 1,
+ position: "relative"
+ },
+ menuBack: {
+ marginLeft: -theme.spacing.unit / 2,
+ marginRight: theme.spacing.unit
+ },
+ paper: {
+ left: 0,
+ marginTop: theme.spacing.unit,
+ position: "absolute",
+ right: 0,
+ zIndex: 1
+ },
+ root: {}
+ });
+const AutocompleteSelectMenu = withStyles(styles, {
+ name: "AutocompleteSelectMenu"
+})(
+ ({
+ classes,
+ disabled,
+ displayValue,
+ error,
+ helperText,
+ label,
+ loading,
+ name,
+ options,
+ placeholder,
+ onChange
+ }: AutocompleteSelectMenuProps & WithStyles<typeof styles>) => {
+ const [inputValue, setInputValue] = React.useState(displayValue || "");
+ const [menuPath, setMenuPath] = React.useState<number[]>([]);
+
+ const handleChange = (value: string) => {
+ onChange({
+ target: {
+ name,
+ value
+ }
+ } as any);
+ };
+
+ // Validate if option values are duplicated
+ React.useEffect(() => {
+ if (!validateOptions(options)) {
+ throw validationError;
+ }
+ }, []);
+
+ // Navigate back to main menu after input field change
+ React.useEffect(() => setMenuPath([]), [JSON.stringify(options)]);
+
+ return (
+ <DebounceAutocomplete debounceFn={undefined}>
+ {debounceFn => (
+ <Downshift
+ itemToString={item => (item ? item.label : "")}
+ onSelect={handleChange}
+ onInputValueChange={value => debounceFn(value)}
+ >
+ {({ getItemProps, isOpen, openMenu, closeMenu, selectItem }) => {
+ return (
+ <div className={classes.container}>
+ <TextField
+ InputProps={{
+ endAdornment: loading && <CircularProgress size={16} />,
+ id: undefined,
+ onBlur: () => {
+ closeMenu();
+ setMenuPath([]);
+ },
+ onChange: event => setInputValue(event.target.value),
+ onFocus: () => openMenu(),
+ placeholder
+ }}
+ disabled={disabled}
+ error={error}
+ helperText={helperText}
+ label={label}
+ fullWidth={true}
+ value={inputValue}
+ />
+ {isOpen && (
+ <Paper className={classes.paper} square>
+ {menuPath.length > 0 && (
+ <MenuItem
+ component="div"
+ {...getItemProps({
+ item: null
+ })}
+ onClick={() =>
+ setMenuPath(menuPath.slice(0, menuPath.length - 2))
+ }
+ >
+ <ArrowBack className={classes.menuBack} />
+ {i18n.t("Back")}
+ </MenuItem>
+ )}
+ {getMenu(options, menuPath).map((suggestion, index) => (
+ <MenuItem
+ key={suggestion.value}
+ component="div"
+ {...getItemProps({ item: suggestion })}
+ onClick={() =>
+ suggestion.value
+ ? selectItem(suggestion.value)
+ : setMenuPath([...menuPath, index])
+ }
+ >
+ {suggestion.label}
+ </MenuItem>
+ ))}
+ </Paper>
+ )}
+ </div>
+ );
+ }}
+ </Downshift>
+ )}
+ </DebounceAutocomplete>
+ );
+ }
+);
+AutocompleteSelectMenu.displayName = "AutocompleteSelectMenu";
+export default AutocompleteSelectMenu;
diff --git a/saleor/static/dashboard-next/components/AutocompleteSelectMenu/index.ts b/saleor/static/dashboard-next/components/AutocompleteSelectMenu/index.ts
new file mode 100644
index 0000000000..3a0e4e0d25
--- /dev/null
+++ b/saleor/static/dashboard-next/components/AutocompleteSelectMenu/index.ts
@@ -0,0 +1,2 @@
+export { default } from './AutocompleteSelectMenu';
+export * from './AutocompleteSelectMenu';
\ No newline at end of file
diff --git a/saleor/static/dashboard-next/storybook/config.js b/saleor/static/dashboard-next/storybook/config.js
index 22ca6a515e..bbb5a1e9b4 100644
--- a/saleor/static/dashboard-next/storybook/config.js
+++ b/saleor/static/dashboard-next/storybook/config.js
@@ -6,6 +6,7 @@ function loadStories() {
require("./stories/components/ActionDialog");
require("./stories/components/AddressEdit");
require("./stories/components/AddressFormatter");
+ require("./stories/components/AutocompleteSelectMenu");
require("./stories/components/CardMenu");
require("./stories/components/Checkbox");
require("./stories/components/Chip");
diff --git a/saleor/static/dashboard-next/storybook/stories/components/AutocompleteSelectMenu.tsx b/saleor/static/dashboard-next/storybook/stories/components/AutocompleteSelectMenu.tsx
new file mode 100644
index 0000000000..c1f28ee94e
--- /dev/null
+++ b/saleor/static/dashboard-next/storybook/stories/components/AutocompleteSelectMenu.tsx
@@ -0,0 +1,87 @@
+import Card from "@material-ui/core/Card";
+import CardContent from "@material-ui/core/CardContent";
+import { storiesOf } from "@storybook/react";
+import * as React from "react";
+
+import AutocompleteSelectMenu, {
+ AutocompleteSelectMenuProps,
+ SelectMenuItem
+} from "../../../components/AutocompleteSelectMenu";
+import Decorator from "../../Decorator";
+
+const menu: SelectMenuItem[] = [
+ {
+ label: "Item 1",
+ value: "item1"
+ },
+ {
+ children: [
+ {
+ label: "Item 1.1",
+ value: "item1.1"
+ },
+ {
+ label: "Item 1.2",
+ value: "item1.2"
+ }
+ ],
+ label: "Menu 1"
+ },
+ {
+ label: "Item 3",
+ value: "item3"
+ },
+ {
+ label: "Item 4",
+ value: "item4"
+ },
+ {
+ children: [
+ {
+ label: "Item 5.1",
+ value: "item5.1"
+ },
+ {
+ label: "Item 5.2",
+ value: "item5.2"
+ }
+ ],
+ label: "Menu 5"
+ }
+];
+
+const props: AutocompleteSelectMenuProps = {
+ disabled: false,
+ displayValue: menu[1].children[1].label.toString(),
+ error: false,
+ helperText: undefined,
+ label: "Autocomplete Menu",
+ loading: false,
+ name: "menu",
+ onChange: () => undefined,
+ options: menu,
+ placeholder: "Start typing to search ..."
+};
+
+storiesOf("Generics / Autocomplete Menu", module)
+ .addDecorator(storyFn => (
+ <Card
+ style={{
+ margin: "auto",
+ overflow: "visible",
+ width: 400
+ }}
+ >
+ <CardContent>{storyFn()}</CardContent>
+ </Card>
+ ))
+ .addDecorator(Decorator)
+ .add("default", () => <AutocompleteSelectMenu {...props} />)
+ .add("loading", () => <AutocompleteSelectMenu {...props} loading={true} />)
+ .add("error", () => (
+ <AutocompleteSelectMenu
+ {...props}
+ error={true}
+ helperText="Generic form error"
+ />
+ ));