Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor tree module
dominik-zeglenc4eddcb57997
diff --git a/saleor/static/dashboard-next/components/AutocompleteSelectMenu/AutocompleteSelectMenu.tsx b/saleor/static/dashboard-next/components/AutocompleteSelectMenu/AutocompleteSelectMenu.tsxindex 5024c47019..d00ca186ff 100644--- a/saleor/static/dashboard-next/components/AutocompleteSelectMenu/AutocompleteSelectMenu.tsx+++ b/saleor/static/dashboard-next/components/AutocompleteSelectMenu/AutocompleteSelectMenu.tsx@@ -13,7 +13,11 @@ import Downshift from "downshift";import * as React from "react";import i18n from "../../i18n";-import { getMenu, IMenu, validateMenuOptions } from "../../utils/menu";+import {+ getMenuItemByPath,+ IMenu,+ validateMenuOptions+} from "../../utils/menu";import Debounce, { DebounceProps } from "../Debounce";export interface AutocompleteSelectMenuProps {@@ -24,7 +28,7 @@ export interface AutocompleteSelectMenuProps {label: string;loading: boolean;name: string;- options: IMenu[];+ options: IMenu;placeholder: string;onChange: (event: React.ChangeEvent<any>) => void;onInputChange?: (value: string) => void;@@ -78,14 +82,13 @@ const AutocompleteSelectMenu = withStyles(styles, {const [inputValue, setInputValue] = React.useState(displayValue || "");const [menuPath, setMenuPath] = React.useState<number[]>([]);- const handleChange = (value: string) => {+ const handleChange = (value: string) =>onChange({target: {name,value}} as any);- };// Validate if option values are duplicatedReact.useEffect(() => {@@ -153,22 +156,23 @@ const AutocompleteSelectMenu = withStyles(styles, {{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>- )- )}+ {(menuPath.length+ ? getMenuItemByPath(options, menuPath).children+ : options+ ).map((suggestion, index) => (+ <MenuItem+ key={suggestion.value}+ component="div"+ {...getItemProps({ item: suggestion })}+ onClick={() =>+ suggestion.value+ ? selectItem(suggestion.value)+ : setMenuPath([...menuPath, index])+ }+ >+ {suggestion.label}+ </MenuItem>+ ))}</>) : (<MenuItem disabled component="div">diff --git a/saleor/static/dashboard-next/storybook/stories/components/AutocompleteSelectMenu.tsx b/saleor/static/dashboard-next/storybook/stories/components/AutocompleteSelectMenu.tsxindex c1f28ee94e..a8aa7e2613 100644--- a/saleor/static/dashboard-next/storybook/stories/components/AutocompleteSelectMenu.tsx+++ b/saleor/static/dashboard-next/storybook/stories/components/AutocompleteSelectMenu.tsx@@ -4,48 +4,65 @@ import { storiesOf } from "@storybook/react";import * as React from "react";import AutocompleteSelectMenu, {- AutocompleteSelectMenuProps,- SelectMenuItem+ AutocompleteSelectMenuProps} from "../../../components/AutocompleteSelectMenu";+import Form from "../../../components/Form";+import { getMenuItemByValue, IMenu } from "../../../utils/menu";import Decorator from "../../Decorator";-const menu: SelectMenuItem[] = [+const menu: IMenu = [{+ children: [],+ data: null,label: "Item 1",value: "item1"},{children: [{+ children: [],+ data: null,label: "Item 1.1",value: "item1.1"},{+ children: [],+ data: null,label: "Item 1.2",value: "item1.2"}],+ data: null,label: "Menu 1"},{+ children: [],+ data: null,label: "Item 3",value: "item3"},{+ children: [],+ data: null,label: "Item 4",value: "item4"},{children: [{+ children: [],+ data: null,label: "Item 5.1",value: "item5.1"},{+ children: [],+ data: null,label: "Item 5.2",value: "item5.2"}],+ data: null,label: "Menu 5"}];@@ -84,4 +101,15 @@ storiesOf("Generics / Autocomplete Menu", module)error={true}helperText="Generic form error"/>+ ))+ .add("interactive", () => (+ <Form initial={{ menu: menu[1].children[1].value }}>+ {({ change, data }) => (+ <AutocompleteSelectMenu+ {...props}+ displayValue={getMenuItemByValue(menu, data.menu).label.toString()}+ onChange={change}+ />+ )}+ </Form>));diff --git a/saleor/static/dashboard-next/utils/menu/__snapshots__/menu.test.ts.snap b/saleor/static/dashboard-next/utils/menu/__snapshots__/menu.test.ts.snapnew file mode 100644index 0000000000..39d9892479--- /dev/null+++ b/saleor/static/dashboard-next/utils/menu/__snapshots__/menu.test.ts.snap@@ -0,0 +1,80 @@+// Jest Snapshot v1, https://goo.gl/fbAQLP++exports[`Converting to different representations Properly converts to flat structure 1`] = `+Array [+ Object {+ "data": null,+ "id": "0",+ "label": "1",+ "parent": null,+ "sort": 0,+ "value": "1",+ },+ Object {+ "data": null,+ "id": "1",+ "label": "2",+ "parent": null,+ "sort": 1,+ "value": "2",+ },+ Object {+ "data": null,+ "id": "2",+ "label": "3",+ "parent": null,+ "sort": 2,+ "value": "3",+ },+ Object {+ "data": null,+ "id": "3",+ "label": "4",+ "parent": null,+ "sort": 3,+ "value": "4",+ },+ Object {+ "data": null,+ "id": "3:0",+ "label": "4.1",+ "parent": "3",+ "sort": 0,+ "value": "4.1",+ },+ Object {+ "data": null,+ "id": "3:1",+ "label": "4.2",+ "parent": "3",+ "sort": 1,+ "value": "4.2",+ },+]+`;++exports[`Walk through menu Properly returns all nodes on the path 1`] = `+Array [+ Object {+ "children": Array [+ Object {+ "children": Array [],+ "data": null,+ "label": "4.1",+ "value": "4.1",+ },+ Object {+ "children": Array [],+ "data": null,+ "label": "4.2",+ "value": "4.2",+ },+ ],+ "data": null,+ "label": "4",+ "value": "4",+ },+ undefined,+ undefined,+]+`;diff --git a/saleor/static/dashboard-next/utils/menu/menu.test.ts b/saleor/static/dashboard-next/utils/menu/menu.test.tsindex 68a69dc346..205fe25194 100644--- a/saleor/static/dashboard-next/utils/menu/menu.test.ts+++ b/saleor/static/dashboard-next/utils/menu/menu.test.ts@@ -1,17 +1,71 @@-import { IMenu, validateMenuOptions } from "./menu";+import {+ fromFlat,+ getMenuItemByPath,+ getMenuItemByValue,+ IMenu,+ toFlat,+ validateMenuOptions,+ walkToMenuItem+} from "./menu";++const validMenu: IMenu = [+ {+ children: [],+ data: null,+ label: "1",+ value: "1"+ },+ {+ children: [],+ data: null,+ label: "2",+ value: "2"+ },+ {+ children: [],+ data: null,+ label: "3",+ value: "3"+ },+ {+ children: [+ {+ children: [],+ data: null,+ label: "4.1",+ value: "4.1"+ },+ {+ children: [],+ data: null,+ label: "4.2",+ value: "4.2"+ }+ ],+ data: null,+ label: "4",+ value: "4"+ }+];describe("Validate menu data structure", () => {it("Properly catches same level duplicated value", () => {- const menu: IMenu[] = [+ const menu: IMenu = [{+ children: [],+ data: null,label: "1",value: "1"},{+ children: [],+ data: null,label: "2",value: "2"},{+ children: [],+ data: null,label: "1",value: "1"}@@ -21,31 +75,43 @@ describe("Validate menu data structure", () => {});it("Properly catches multi level duplicated value", () => {- const menu: IMenu[] = [+ const menu: IMenu = [{+ children: [],+ data: null,label: "1",value: "1"},{+ children: [],+ data: null,label: "2",value: "2"},{+ children: [],+ data: null,label: "3",value: "3"},{children: [{+ children: [],+ data: null,label: "4.1",value: "4.1"},{+ children: [],+ data: null,label: "1",value: "1"}],- label: "4"+ data: null,+ label: "4",+ value: "4"}];@@ -53,34 +119,46 @@ describe("Validate menu data structure", () => {});it("Properly passes valid structure", () => {- const menu: IMenu[] = [- {- 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(validateMenuOptions(validMenu)).toBeTruthy();+ });+});++describe("Converting to different representations", () => {+ it("Properly converts to flat structure", () => {+ expect(toFlat(validMenu)).toMatchSnapshot();+ });++ it("Properly converts to nested structure", () => {+ expect(fromFlat(toFlat(validMenu))).toMatchObject(validMenu);+ });+});++describe("Getting items", () => {+ it("Properly returns an item from root by path", () => {+ expect(getMenuItemByPath(validMenu, [1])).toMatchObject(validMenu[1]);+ });++ it("Properly returns an nested item by path", () => {+ expect(getMenuItemByPath(validMenu, [3, 0])).toMatchObject(+ validMenu[3].children[0]+ );+ });++ it("Properly returns an item from root by value", () => {+ expect(getMenuItemByValue(validMenu, validMenu[1].value)).toMatchObject(+ validMenu[1]+ );+ });++ it("Properly returns an nested item by value", () => {+ expect(+ getMenuItemByValue(validMenu, validMenu[3].children[0].value)+ ).toMatchObject(validMenu[3].children[0]);+ });+});- expect(validateMenuOptions(menu)).toBeTruthy();+describe("Walk through menu", () => {+ it("Properly returns all nodes on the path", () => {+ expect(walkToMenuItem(validMenu, [3, 0])).toMatchSnapshot();});});diff --git a/saleor/static/dashboard-next/utils/menu/menu.ts b/saleor/static/dashboard-next/utils/menu/menu.tsindex 3973626e68..406c68498e 100644--- a/saleor/static/dashboard-next/utils/menu/menu.ts+++ b/saleor/static/dashboard-next/utils/menu/menu.ts@@ -1,31 +1,128 @@-export interface IMenu<TData = {}> {- children?: Array<IMenu<TData>>;- data?: TData;+interface IBaseMenuItem<TMenuData = {}> {label: React.ReactNode;value?: string;+ data: TMenuData | null;}+export type IFlatMenuItem<TMenuData = {}> = IBaseMenuItem<TMenuData> & {+ id: string;+ parent: string | null;+ sort: number;+};+export type IMenuItem<TMenuData = {}> = IBaseMenuItem<TMenuData> & {+ children: Array<IMenuItem<TMenuData>>;+};+export type IMenu<TMenuData = {}> = Array<IMenuItem<TMenuData>>;+export type IFlatMenu<TMenuData = {}> = Array<IFlatMenuItem<TMenuData>>;-function getMenuOptionValues(menuOption: IMenu): string[] {- return menuOption.value- ? [menuOption.value]- : menuOption.children.reduce(- (acc, menuOption) => [...acc, ...getMenuOptionValues(menuOption)],- []- );-}--export function validateMenuOptions(menuOptions: IMenu[]): boolean {- const values: string[] = menuOptions.reduce(- (acc, menuOption) => [...acc, ...getMenuOptionValues(menuOption)],- []- );+export function validateMenuOptions<TMenuData = {}>(+ menu: IMenu<TMenuData>+): boolean {+ const values: string[] = toFlat(menu)+ .map(menuItem => menuItem.value)+ .filter(value => value !== undefined);const uniqueValues = Array.from(new Set(values));return uniqueValues.length === values.length;}-export function getMenu(menuOptions: IMenu[], path: number[]): IMenu[] {+function _getMenuItemByPath<TMenuData = {}>(+ menuItem: IMenuItem<TMenuData>,+ path: number[]+): IMenuItem<TMenuData> {if (path.length === 0) {- return menuOptions;+ return menuItem;}- return getMenu(menuOptions[path[0]].children, path.slice(1));+ return _getMenuItemByPath(menuItem.children[path[0]], path.slice(1));+}++export function getMenuItemByPath<TMenuData = {}>(+ menu: IMenu<TMenuData>,+ path: number[]+): IMenuItem<TMenuData> {+ return _getMenuItemByPath(menu[path[0]], path.slice(1));+}++export function getMenuItemByValue<TMenuData = {}>(+ menu: IMenu<TMenuData>,+ value: string+): IMenuItem<TMenuData> {+ const flatMenu = toFlat(menu);+ const flatMenuItem: IFlatMenuItem<TMenuData> = flatMenu.find(+ menuItem => menuItem.value === value+ );++ return _fromFlat(flatMenu, flatMenuItem.id);+}++function _walkToMenuItem<TMenuData = {}>(+ menuItem: IMenuItem<TMenuData>,+ path: number[]+): IMenu<TMenuData> {+ const node = menuItem.children[path[0]];++ if (path.length === 1) {+ return [node];+ }++ return [node, ..._walkToMenuItem(node, path.slice(1))];+}++export function walkToMenuItem<TMenuData = {}>(+ menu: IMenu<TMenuData>,+ path: number[]+): IMenu<TMenuData> {+ const walkByNode = menu[path[0]];+ return [walkByNode, ..._walkToMenuItem(walkByNode, path.slice(1))];+}++function _toFlat<TMenuData = {}>(+ menuItem: IMenuItem<TMenuData>,+ sort: number,+ parent: string+): IFlatMenu<TMenuData> {+ const id = parent ? [parent, sort].join(":") : sort.toString();+ const flatMenuItem: IFlatMenuItem<TMenuData> = {+ data: menuItem.data,+ id,+ label: menuItem.label,+ parent,+ sort,+ value: menuItem.value+ };+ return [+ flatMenuItem,+ ...menuItem.children+ .map((child, childIndex) => _toFlat(child, childIndex, id))+ .reduce((acc, curr) => [...acc, ...curr], [] as IFlatMenu<TMenuData>)+ ];+}+export function toFlat<TMenuData = {}>(+ menu: IMenu<TMenuData>+): IFlatMenu<TMenuData> {+ return menu+ .map((menuItem, menuItemIndex) => _toFlat(menuItem, menuItemIndex, null))+ .reduce((acc, curr) => [...acc, ...curr], [] as IFlatMenu<TMenuData>);+}++function _fromFlat<TMenuData = {}>(+ menu: IFlatMenu<TMenuData>,+ id: string+): IMenuItem<TMenuData> {+ const flatMenuItem = menu.find(menuItem => menuItem.id === id);+ const children: Array<IMenuItem<TMenuData>> = menu+ .filter(menuItem => menuItem.parent === flatMenuItem.id)+ .map(menuItem => _fromFlat(menu, menuItem.id));++ return {+ children,+ data: flatMenuItem.data,+ label: flatMenuItem.label,+ value: flatMenuItem.value+ };+}+export function fromFlat<TMenuData = {}>(+ menu: IFlatMenu<TMenuData>+): IMenu<TMenuData> {+ return menu+ .filter(menuItem => menuItem.parent === null)+ .map(menuItem => _fromFlat(menu, menuItem.id));}