Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Make autocomplete multi select work
dominik-zeglen2b73daa0d659
diff --git a/saleor/static/dashboard-next/components/MultiAutocompleteSelectField/MultiAutocompleteSelectField.tsx b/saleor/static/dashboard-next/components/MultiAutocompleteSelectField/MultiAutocompleteSelectField.tsxindex 8faa438768..5edc763714 100644--- a/saleor/static/dashboard-next/components/MultiAutocompleteSelectField/MultiAutocompleteSelectField.tsx+++ b/saleor/static/dashboard-next/components/MultiAutocompleteSelectField/MultiAutocompleteSelectField.tsx@@ -1,4 +1,5 @@import CircularProgress from "@material-ui/core/CircularProgress";+import IconButton from "@material-ui/core/IconButton";import MenuItem from "@material-ui/core/MenuItem";import Paper from "@material-ui/core/Paper";import {@@ -8,14 +9,18 @@ import {WithStyles} from "@material-ui/core/styles";import TextField from "@material-ui/core/TextField";+import Typography from "@material-ui/core/Typography";+import CloseIcon from "@material-ui/icons/Close";import Downshift, { ControllerStateAndHelpers } from "downshift";import React from "react";import { compareTwoStrings } from "string-similarity";+import { fade } from "@material-ui/core/styles/colorManipulator";import Checkbox from "@saleor/components/Checkbox";import Debounce, { DebounceProps } from "@saleor/components/Debounce";import i18n from "@saleor/i18n";import ArrowDropdownIcon from "@saleor/icons/ArrowDropdown";+import Hr from "../Hr";export interface MultiAutocompleteChoiceType {label: string;@@ -25,12 +30,42 @@ export interface MultiAutocompleteChoiceType {const styles = (theme: Theme) =>createStyles({chip: {- margin: `${theme.spacing.unit / 2}px ${theme.spacing.unit / 2}px`+ width: "100%"+ },+ chipClose: {+ height: 32,+ padding: 0,+ width: 32+ },+ chipContainer: {+ display: "flex",+ flexDirection: "column",+ marginTop: theme.spacing.unit+ },+ chipInner: {+ "& svg": {+ color: theme.palette.primary.contrastText+ },+ alignItems: "center",+ background: fade(theme.palette.primary.main, 0.6),+ borderRadius: 24,+ color: theme.palette.primary.contrastText,+ display: "flex",+ justifyContent: "space-between",+ margin: `${theme.spacing.unit}px 0`,+ paddingLeft: theme.spacing.unit * 2,+ paddingRight: theme.spacing.unit+ },+ chipLabel: {+ color: theme.palette.primary.contrastText},container: {flexGrow: 1,position: "relative"},+ hr: {+ margin: `${theme.spacing.unit}px 0`+ },paper: {left: 0,marginTop: theme.spacing.unit,@@ -42,7 +77,8 @@ const styles = (theme: Theme) =>});export interface MultiAutocompleteSelectFieldProps {- displayValue: string;+ allowCustomValues?: boolean;+ displayValues: MultiAutocompleteChoiceType[];name: string;choices: MultiAutocompleteChoiceType[];value: string[];@@ -50,8 +86,8 @@ export interface MultiAutocompleteSelectFieldProps {placeholder?: string;helperText?: string;label?: string;- fetchChoices?(value: string);- onChange(event);+ fetchChoices?: (value: string) => void;+ onChange: (event: React.ChangeEvent<any>) => void;}const DebounceAutocomplete: React.ComponentType<@@ -62,9 +98,10 @@ export const MultiAutocompleteSelectFieldComponent = withStyles(styles, {name: "MultiAutocompleteSelectField"})(({+ allowCustomValues,choices,classes,- displayValue,+ displayValues,helperText,label,loading,@@ -74,38 +111,39 @@ export const MultiAutocompleteSelectFieldComponent = withStyles(styles, {fetchChoices,onChange}: MultiAutocompleteSelectFieldProps & WithStyles<typeof styles>) => {- const [focused, setFocus] = React.useState(false);const handleSelect = (- item: MultiAutocompleteChoiceType,- { reset }: ControllerStateAndHelpers+ item: string,+ downshiftOpts?: ControllerStateAndHelpers) => {- reset({ inputValue: "" });- onChange({ target: { name, value: item } });+ if (downshiftOpts) {+ downshiftOpts.reset({ inputValue: "" });+ }+ onChange({+ target: { name, value: item }+ } as any);};+ const suggestions = choices.filter(choice => !value.includes(choice.value));return (- <Downshift- selectedItem={value}- itemToString={item => (item ? item.label : "")}- onSelect={handleSelect}- onInputValueChange={fetchChoices}- >- {({- getInputProps,- getItemProps,- isOpen,- toggleMenu,- openMenu,- highlightedIndex,- inputValue- }) => {- return (+ <>+ <Downshift+ onInputValueChange={fetchChoices}+ onSelect={handleSelect}+ itemToString={() => ""}+ >+ {({+ getInputProps,+ getItemProps,+ isOpen,+ toggleMenu,+ highlightedIndex,+ inputValue+ }) => (<div className={classes.container}><TextFieldInputProps={{...getInputProps({- placeholder,- value: focused ? inputValue : displayValue+ placeholder}),endAdornment: (<div>@@ -117,23 +155,38 @@ export const MultiAutocompleteSelectFieldComponent = withStyles(styles, {</div>),id: undefined,- onBlur: () => setFocus(false),- onFocus: () => {- openMenu();- setFocus(true);- }+ onClick: toggleMenu}}helperText={helperText}label={label}fullWidth={true}/>- {isOpen && (+ {isOpen && (!!inputValue || !!choices.length) && (<Paper className={classes.paper} square>- {!loading && choices.length > 0- ? choices.map((suggestion, index) => (+ {choices.length > 0 ||+ displayValues.length > 0 ||+ allowCustomValues ? (+ <>+ {displayValues.map(value => (+ <MenuItem+ key={value.value}+ selected={true}+ component="div"+ {...getItemProps({+ item: value.value+ })}+ >+ <Checkbox checked={true} disableRipple />+ {value.label}+ </MenuItem>+ ))}+ {displayValues.length > 0 && suggestions.length > 0 && (+ <Hr className={classes.hr} />+ )}+ {suggestions.map((suggestion, index) => (<MenuItemkey={suggestion.value}- selected={highlightedIndex === index}+ selected={highlightedIndex === index + value.length}component="div"{...getItemProps({item: suggestion.value@@ -145,18 +198,58 @@ export const MultiAutocompleteSelectFieldComponent = withStyles(styles, {/>{suggestion.label}</MenuItem>- ))- : !loading && (- <MenuItem disabled={true} component="div">- {i18n.t("No results found")}- </MenuItem>- )}+ ))}+ {allowCustomValues &&+ inputValue &&+ !choices.find(+ choice =>+ choice.label.toLowerCase() ===+ inputValue.toLowerCase()+ ) && (+ <MenuItem+ key={"customValue"}+ component="div"+ {...getItemProps({+ item: inputValue+ })}+ >+ {i18n.t("Add new value: {{ value }}", {+ context: "add custom option",+ value: inputValue+ })}+ </MenuItem>+ )}+ </>+ ) : (+ !loading && (+ <MenuItem disabled={true} component="div">+ {i18n.t("No results found")}+ </MenuItem>+ )+ )}</Paper>)}</div>- );- }}- </Downshift>+ )}+ </Downshift>+ <div className={classes.chipContainer}>+ {displayValues.map(value => (+ <div className={classes.chip}>+ <div className={classes.chipInner}>+ <Typography className={classes.chipLabel} variant="caption">+ {value.label}+ </Typography>+ <IconButton+ className={classes.chipClose}+ onClick={() => handleSelect(value.value)}+ >+ <CloseIcon fontSize="small" />+ </IconButton>+ </div>+ </div>+ ))}+ </div>+ </>);});diff --git a/saleor/static/dashboard-next/hooks/useBulkActions.ts b/saleor/static/dashboard-next/hooks/useBulkActions.tsindex 9863087822..b4c86fe61b 100644--- a/saleor/static/dashboard-next/hooks/useBulkActions.ts+++ b/saleor/static/dashboard-next/hooks/useBulkActions.ts@@ -1,34 +1,22 @@-import { useState } from "react";import { Node } from "../types";+import useListActions from "./useListActions";function useBulkActions(initial: string[] = []) {- const [listElements, setListElements] = useState(initial);-- function isSelected(id: string) {- return !!listElements.find(listElement => listElement === id);- }-- function add(id: string) {- setListElements([...listElements, id]);- }-- function remove(id: string) {- setListElements(listElements.filter(listElement => listElement !== id));- }-- function reset() {- setListElements([]);- }-- function toggle(id: string) {- isSelected(id) ? remove(id) : add(id);- }+ const {+ add,+ isSelected,+ listElements,+ remove,+ reset,+ set,+ toggle+ } = useListActions<string>(initial);function toggleAll(items: Node[], selected: number) {const allItems = items.map(item => item.id);reset();if (selected !== allItems.length) {- setListElements(allItems);+ set(allItems);}}diff --git a/saleor/static/dashboard-next/hooks/useListActions.ts b/saleor/static/dashboard-next/hooks/useListActions.tsnew file mode 100644index 0000000000..43f38b88ca--- /dev/null+++ b/saleor/static/dashboard-next/hooks/useListActions.ts@@ -0,0 +1,47 @@+import { useEffect, useState } from "react";++function useListActions<TData>(+ initial: TData[] = [],+ compareFunc: (a: TData, b: TData) => boolean = (a, b) => a === b+) {+ const [listElements, setListElements] = useState(initial);++ useEffect(() => setListElements(initial), [JSON.stringify(initial)]);++ function isSelected(data: TData) {+ return !!listElements.find(listElement => compareFunc(listElement, data));+ }++ function add(data: TData) {+ setListElements([...listElements, data]);+ }++ function remove(data: TData) {+ setListElements(+ listElements.filter(listElement => !compareFunc(listElement, data))+ );+ }++ function reset() {+ setListElements([]);+ }++ function toggle(data: TData) {+ isSelected(data) ? remove(data) : add(data);+ }++ function set(data: TData[]) {+ setListElements(data);+ }++ return {+ add,+ isSelected,+ listElements,+ remove,+ reset,+ set,+ toggle+ };+}+export default useListActions;diff --git a/saleor/static/dashboard-next/hooks/useMultiAutocomplete.ts b/saleor/static/dashboard-next/hooks/useMultiAutocomplete.tsnew file mode 100644index 0000000000..af3a375a23--- /dev/null+++ b/saleor/static/dashboard-next/hooks/useMultiAutocomplete.ts@@ -0,0 +1,28 @@+import { MultiAutocompleteChoiceType } from "@saleor/components/MultiAutocompleteSelectField";+import { maybe } from "@saleor/misc";+import useListActions from "./useListActions";++function useMultiAutocomplete(initial: MultiAutocompleteChoiceType[] = []) {+ const { listElements, toggle } = useListActions<MultiAutocompleteChoiceType>(+ initial,+ (a, b) => a.value === b.value+ );+ const handleSelect = (+ event: React.ChangeEvent<any>,+ choices: MultiAutocompleteChoiceType[]+ ) => {+ const value: string = event.target.value;+ const match = choices.find(choice => choice.value === value);+ toggle({+ label: maybe(() => match.label, value),+ value+ });+ };++ return {+ change: handleSelect,+ data: listElements+ };+}++export default useMultiAutocomplete;diff --git a/saleor/static/dashboard-next/products/components/ProductCreatePage/ProductCreatePage.tsx b/saleor/static/dashboard-next/products/components/ProductCreatePage/ProductCreatePage.tsxindex 449b167168..86e84f1c3a 100644--- a/saleor/static/dashboard-next/products/components/ProductCreatePage/ProductCreatePage.tsx+++ b/saleor/static/dashboard-next/products/components/ProductCreatePage/ProductCreatePage.tsx@@ -14,8 +14,8 @@ import VisibilityCard from "@saleor/components/VisibilityCard";import { SearchCategories_categories_edges_node } from "@saleor/containers/SearchCategories/types/SearchCategories";import { SearchCollections_collections_edges_node } from "@saleor/containers/SearchCollections/types/SearchCollections";import useFormset from "@saleor/hooks/useFormset";+import useMultiAutocomplete from "@saleor/hooks/useMultiAutocomplete";import {- Collection,getAttributeInputFromProductType,getChoices,ProductType@@ -100,9 +100,10 @@ export const ProductCreatePage: React.StatelessComponent<name: "",productAttributes: [] as ProductCreateData_productTypes_edges_node_productAttributes[]});- const [selectedCollections, setSelectedCollections] = React.useState<- Collection[]- >([]);+ const {+ change: selectCollection,+ data: selectedCollections+ } = useMultiAutocomplete();const { change: changeAttributeData, data: attributes } = useFormset(getAttributeInputFromProductType(productType));@@ -141,11 +142,8 @@ export const ProductCreatePage: React.StatelessComponent<>{({ change, data, errors, hasChanged, submit, triggerChange }) => {const handleCollectionSelect = createCollectionSelectHandler(- data,- collections,- selectedCollections,- setSelectedCollections,- change+ event => selectCollection(event, collections),+ triggerChange);const handleCategorySelect = createCategorySelectHandler(categoryChoiceList,@@ -219,18 +217,16 @@ export const ProductCreatePage: React.StatelessComponent<canChangeType={true}categories={categories}categoryInputDisplayValue={selectedCategory}+ collections={collections}+ data={data}+ disabled={disabled}errors={errors}fetchCategories={fetchCategories}fetchCollections={fetchCollections}- collections={collections}+ productType={productType}productTypeInputDisplayValue={productType.name}productTypes={productTypes}- data={data}- productType={productType}- disabled={disabled}- collectionInputDisplayValue={selectedCollections- .map(collection => collection.label)- .join(", ")}+ selectedCollections={selectedCollections}onCategoryChange={handleCategorySelect}onCollectionChange={handleCollectionSelect}onProductTypeChange={handleProductTypeSelect}diff --git a/saleor/static/dashboard-next/products/components/ProductOrganization/ProductOrganization.tsx b/saleor/static/dashboard-next/products/components/ProductOrganization/ProductOrganization.tsxindex 8000656b7c..7cdf419bff 100644--- a/saleor/static/dashboard-next/products/components/ProductOrganization/ProductOrganization.tsx+++ b/saleor/static/dashboard-next/products/components/ProductOrganization/ProductOrganization.tsx@@ -13,7 +13,9 @@ import CardSpacer from "@saleor/components/CardSpacer";import CardTitle from "@saleor/components/CardTitle";import { FormSpacer } from "@saleor/components/FormSpacer";import Hr from "@saleor/components/Hr";-import MultiAutocompleteSelectField from "@saleor/components/MultiAutocompleteSelectField";+import MultiAutocompleteSelectField, {+ MultiAutocompleteChoiceType+} from "@saleor/components/MultiAutocompleteSelectField";import SingleAutocompleteSelectField from "@saleor/components/SingleAutocompleteSelectField";import { ChangeEvent } from "@saleor/hooks/useForm";import i18n from "@saleor/i18n";@@ -49,7 +51,6 @@ interface ProductOrganizationProps extends WithStyles<typeof styles> {categories?: ChoiceType[];categoryInputDisplayValue: string;collections?: ChoiceType[];- collectionInputDisplayValue: string;data: {category: string;collections: string[];@@ -57,6 +58,7 @@ interface ProductOrganizationProps extends WithStyles<typeof styles> {};disabled: boolean;errors: FormErrors<"productType" | "category">;+ selectedCollections: MultiAutocompleteChoiceType[];productType?: ProductType;productTypeInputDisplayValue?: string;productTypes?: ChoiceType[];@@ -74,12 +76,12 @@ const ProductOrganization = withStyles(styles, { name: "ProductOrganization" })(categoryInputDisplayValue,classes,collections,- collectionInputDisplayValue,data,disabled,errors,fetchCategories,fetchCollections,+ selectedCollections,productType,productTypeInputDisplayValue,productTypes,@@ -142,11 +144,11 @@ const ProductOrganization = withStyles(styles, { name: "ProductOrganization" })(<Hr /><FormSpacer /><MultiAutocompleteSelectField- displayValue={collectionInputDisplayValue}+ displayValues={selectedCollections}label={i18n.t("Collections")}choices={disabled ? [] : collections}name="collections"- value={data.collections}+ value={selectedCollections.map(collection => collection.value)}helperText={i18n.t("*Optional. Adding product to collection helps users find it.")}diff --git a/saleor/static/dashboard-next/products/utils/handlers.ts b/saleor/static/dashboard-next/products/utils/handlers.tsindex 6a0680551a..2abbb3fa39 100644--- a/saleor/static/dashboard-next/products/utils/handlers.ts+++ b/saleor/static/dashboard-next/products/utils/handlers.ts@@ -1,42 +1,15 @@import { FormChange } from "@saleor/components/Form";-import { SingleAutocompleteChoiceType } from "@saleor/components/SingleAutocompleteSelectField";import { SearchCategories_categories_edges_node } from "@saleor/containers/SearchCategories/types/SearchCategories";import { FormsetChange } from "@saleor/hooks/useFormset";-import { ProductCreateData_productTypes_edges_node } from "@saleor/products/types/ProductCreateData";-import { Collection, ProductType, ProductUpdatePageFormData } from "./data";+import { ProductType } from "./data";export function createCollectionSelectHandler(- data: ProductUpdatePageFormData,- collections: SingleAutocompleteChoiceType[],- selectedCollections: Collection[],- setSelectedCollections: (collections: Collection[]) => void,- change: FormChange+ change: FormChange,+ triggerChange: () => void): FormChange {return (event: React.ChangeEvent<any>) => {- const id = event.target.value;- const collectionIndex = data.collections.indexOf(id);- const collectionList =- collectionIndex === -1- ? [- ...selectedCollections,- {- id,- label: collections.find(collection => collection.value === id)- .label- }- ]- : [- ...selectedCollections.slice(0, collectionIndex),- ...selectedCollections.slice(collectionIndex + 1)- ];-- setSelectedCollections(collectionList);- change({- target: {- name: "collections",- value: collectionList.map(collection => collection.id)- }- } as any);+ change(event);+ triggerChange();};}diff --git a/saleor/static/dashboard-next/storybook/stories/components/MultiAutocompleteSelectField.tsx b/saleor/static/dashboard-next/storybook/stories/components/MultiAutocompleteSelectField.tsxindex 3aa63f0d43..0582992cc9 100644--- a/saleor/static/dashboard-next/storybook/stories/components/MultiAutocompleteSelectField.tsx+++ b/saleor/static/dashboard-next/storybook/stories/components/MultiAutocompleteSelectField.tsx@@ -1,13 +1,10 @@-import IconButton from "@material-ui/core/IconButton";-import Typography from "@material-ui/core/Typography";-import DeleteIcon from "@material-ui/icons/Close";import { storiesOf } from "@storybook/react";import React from "react";-import Form from "@saleor/components/Form";import MultiAutocompleteSelectField, {- MultiAutocompleteSelectFieldChildrenFunc+ MultiAutocompleteSelectFieldProps} from "@saleor/components/MultiAutocompleteSelectField";+import useMultiAutocomplete from "@saleor/hooks/useMultiAutocomplete";import CardDecorator from "../../CardDecorator";import Decorator from "../../Decorator";import { ChoiceProvider } from "../../mock";@@ -27,80 +24,46 @@ const suggestions = ["Zimbabwe"].map(c => ({ label: c, value: c.toLocaleLowerCase().replace(/\s+/, "_") }));-const Choices: React.FC<MultiAutocompleteSelectFieldChildrenFunc> = ({- deleteItem,- items-}) => (- <div style={{ marginTop: 16 }}>- {items.map(item => (- <div- style={{- alignItems: "center",- display: "flex",- justifyContent: "space-between"- }}- key={item.value}- >- <Typography>{item.label}</Typography>- <div- style={{- flex: 1- }}+const props: MultiAutocompleteSelectFieldProps = {+ choices: undefined,+ displayValues: [],+ label: "Country",+ loading: false,+ name: "country",+ onChange: () => undefined,+ placeholder: "Select country",+ value: undefined+};++const Story: React.FC<+ Partial<MultiAutocompleteSelectFieldProps>+> = storyProps => {+ const { change, data: countries } = useMultiAutocomplete([suggestions[0]]);++ return (+ <ChoiceProvider choices={suggestions}>+ {({ choices, loading, fetchChoices }) => (+ <MultiAutocompleteSelectField+ {...props}+ displayValues={countries}+ choices={choices}+ fetchChoices={fetchChoices}+ helperText={`Value: ${countries+ .map(country => country.label)+ .join(", ")}`}+ onChange={event => change(event, choices)}+ value={countries.map(country => country.value)}+ loading={loading}+ {...storyProps}/>- <IconButton onClick={() => deleteItem(item)}>- <DeleteIcon style={{ fontSize: 16 }} />- </IconButton>- </div>- ))}- </div>-);+ )}+ </ChoiceProvider>+ );+};storiesOf("Generics / MultiAutocompleteSelectField", module).addDecorator(CardDecorator).addDecorator(Decorator)- .add("with loading data", () => (- <Form initial={{ countries: [suggestions[0]] }}>- {({ change, data }) => (- <ChoiceProvider choices={suggestions}>- {({ choices, fetchChoices }) => (- <MultiAutocompleteSelectField- choices={choices}- fetchChoices={fetchChoices}- helperText={`Value: ${data.countries.map(c => c.value)}`}- label="Countries"- loading={true}- name="countries"- onChange={change}- placeholder="Select country"- value={data.countries}- >- {selectInput => <Choices {...selectInput} />}- </MultiAutocompleteSelectField>- )}- </ChoiceProvider>- )}- </Form>- ))- .add("with loaded data", () => (- <Form initial={{ countries: [suggestions[0]] }}>- {({ change, data }) => (- <ChoiceProvider choices={suggestions}>- {({ choices, fetchChoices }) => (- <MultiAutocompleteSelectField- choices={choices}- fetchChoices={fetchChoices}- helperText={`Value: ${data.countries.map(c => c.value)}`}- label="Countries"- loading={false}- name="countries"- onChange={change}- placeholder="Select country"- value={data.countries}- >- {selectInput => <Choices {...selectInput} />}- </MultiAutocompleteSelectField>- )}- </ChoiceProvider>- )}- </Form>- ));+ .add("with loaded data", () => <Story />)+ .add("with loading data", () => <Story loading={true} />)+ .add("with custom option", () => <Story allowCustomValues={true} />);diff --git a/saleor/static/dashboard-next/storybook/stories/products/ProductCreatePage.tsx b/saleor/static/dashboard-next/storybook/stories/products/ProductCreatePage.tsxindex 63b5fcdd2a..f7706fb9bb 100644--- a/saleor/static/dashboard-next/storybook/stories/products/ProductCreatePage.tsx+++ b/saleor/static/dashboard-next/storybook/stories/products/ProductCreatePage.tsx@@ -2,7 +2,7 @@ import { storiesOf } from "@storybook/react";import React from "react";import ProductCreatePage, {- FormData+ ProductCreatePageSubmitData} from "../../../products/components/ProductCreatePage";import { formError } from "../../misc";@@ -54,8 +54,8 @@ storiesOf("Views / Products / Create product", module)currency="USD"disabled={false}errors={(["name", "productType", "category", "sku"] as Array<- keyof FormData- >).map(field => formError(field))}+ keyof ProductCreatePageSubmitData+ >).map(formError)}header="Add product"collections={product.collections}fetchCategories={() => undefined}