Skip to content

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

Add multi select dropdown support

dominik-zeglen555a726885c0
diff --git a/saleor/static/dashboard-next/components/SingleAutocompleteSelectField/SingleAutocompleteSelectField.tsx b/saleor/static/dashboard-next/components/SingleAutocompleteSelectField/SingleAutocompleteSelectField.tsx
index 94fe160a50..c7ee5d954c 100644
--- a/saleor/static/dashboard-next/components/SingleAutocompleteSelectField/SingleAutocompleteSelectField.tsx
+++ b/saleor/static/dashboard-next/components/SingleAutocompleteSelectField/SingleAutocompleteSelectField.tsx
@@ -14,10 +14,10 @@ import Downshift from "downshift";
import React from "react";
import { compareTwoStrings } from "string-similarity";
+import useStateFromProps from "@saleor/hooks/useStateFromProps";
import i18n from "../../i18n";
import ArrowDropdownIcon from "../../icons/ArrowDropdown";
import Debounce, { DebounceProps } from "../Debounce";
-import useStateFromProps from "@saleor/hooks/useStateFromProps";
const styles = (theme: Theme) =>
createStyles({
diff --git a/saleor/static/dashboard-next/hooks/useForm.ts b/saleor/static/dashboard-next/hooks/useForm.ts
index 9dfb0a6d1a..9d793a295a 100644
--- a/saleor/static/dashboard-next/hooks/useForm.ts
+++ b/saleor/static/dashboard-next/hooks/useForm.ts
@@ -5,17 +5,17 @@ import { UserError } from "@saleor/types";
import { toggle } from "@saleor/utils/lists";
import useStateFromProps from "./useStateFromProps";
-export interface ChangeEvent<TName = string, TData = any> {
+export interface ChangeEvent<TData = any> {
target: {
- name: keyof TName | string;
+ name: string;
value: TData;
};
}
-export type FormChange<T> = (event: ChangeEvent<T>, cb?: () => void) => void;
+export type FormChange = (event: ChangeEvent, cb?: () => void) => void;
export interface UseFormResult<T> {
- change: FormChange<T>;
+ change: FormChange;
data: T;
errors: Record<string, string>;
hasChanged: boolean;
@@ -23,7 +23,7 @@ export interface UseFormResult<T> {
set: (data: T) => void;
submit: () => void;
triggerChange: () => void;
- toggleValue: (event: ChangeEvent<T>) => void;
+ toggleValue: FormChange;
}
function parseErrors(errors: UserError[]): Record<string, string> {
@@ -71,19 +71,26 @@ function useForm<T extends FormData>(
onRefresh: newData => handleRefresh(data, newData, setChanged)
});
- function toggleValue(event: ChangeEvent<T>) {
+ function toggleValue(event: ChangeEvent, cb?: () => void) {
const { name, value } = event.target;
const field = data[name as keyof T];
if (Array.isArray(field)) {
+ if (!hasChanged) {
+ setChanged(true);
+ }
setData({
...data,
[name]: toggle(value, field, isEqual)
});
}
+
+ if (typeof cb === "function") {
+ cb();
+ }
}
- function change(event: ChangeEvent<T>) {
+ function change(event: ChangeEvent) {
const { name, value } = event.target;
if (!(name in data)) {
diff --git a/saleor/static/dashboard-next/hooks/useFormset.ts b/saleor/static/dashboard-next/hooks/useFormset.ts
index c8dcadf606..ae83499c0c 100644
--- a/saleor/static/dashboard-next/hooks/useFormset.ts
+++ b/saleor/static/dashboard-next/hooks/useFormset.ts
@@ -1,26 +1,27 @@
-import { useEffect, useState } from "react";
+import isEqual from "lodash-es/isEqual";
-export type FormsetChange = (id: string, value: string) => void;
+import { toggle } from "@saleor/utils/lists";
+import useStateFromProps from "./useStateFromProps";
+
+export type FormsetChange = (id: string, value: any) => void;
export interface FormsetAtomicData<TData = object> {
data: TData;
id: string;
label: string;
- value: string;
+ value: any;
}
export type FormsetData<TData = object> = Array<FormsetAtomicData<TData>>;
export interface UseFormsetOutput<TData = object> {
change: FormsetChange;
data: FormsetData<TData>;
+ toggleItemValue: FormsetChange;
}
function useFormset<TData = object>(
initial: FormsetData<TData>
): UseFormsetOutput<TData> {
- const [data, setData] = useState<FormsetData<TData>>(initial || []);
-
- // Reload formset after fetching new initial data
- useEffect(() => setData(initial), [JSON.stringify(initial)]);
+ const [data, setData] = useStateFromProps<FormsetData<TData>>(initial || []);
- function setItemValue(id: string, value: string) {
+ function setItemValue(id: string, value: any) {
const itemIndex = data.findIndex(item => item.id === id);
setData([
...data.slice(0, itemIndex),
@@ -32,9 +33,19 @@ function useFormset<TData = object>(
]);
}
+ function toggleItemValue(id: string, value: any) {
+ const itemIndex = data.findIndex(item => item.id === id);
+ const field = data[itemIndex];
+
+ if (Array.isArray(field)) {
+ setItemValue(id, toggle(value, field, isEqual));
+ }
+ }
+
return {
change: setItemValue,
- data
+ data,
+ toggleItemValue
};
}
diff --git a/saleor/static/dashboard-next/products/components/ProductAttributes/ProductAttributes.tsx b/saleor/static/dashboard-next/products/components/ProductAttributes/ProductAttributes.tsx
index 3033fc6401..7013af181e 100644
--- a/saleor/static/dashboard-next/products/components/ProductAttributes/ProductAttributes.tsx
+++ b/saleor/static/dashboard-next/products/components/ProductAttributes/ProductAttributes.tsx
@@ -17,7 +17,7 @@ import MultiAutocompleteSelectField, {
import SingleAutocompleteSelectField, {
SingleAutocompleteChoiceType
} from "@saleor/components/SingleAutocompleteSelectField";
-import { FormsetAtomicData } from "@saleor/hooks/useFormset";
+import { FormsetAtomicData, FormsetChange } from "@saleor/hooks/useFormset";
import i18n from "@saleor/i18n";
import { maybe } from "@saleor/misc";
import { ProductDetails_product_attributes_attribute_values } from "@saleor/products/types/ProductDetails";
@@ -33,7 +33,8 @@ export type ProductAttributeInput = FormsetAtomicData<
export interface ProductAttributesProps {
attributes: ProductAttributeInput[];
disabled: boolean;
- onChange: (id: string, value: string) => void;
+ onChange: FormsetChange;
+ onMultiChange: FormsetChange;
}
const useStyles = makeStyles((theme: Theme) => ({
@@ -94,7 +95,8 @@ function getSingleChoices(
const ProductAttributes: React.FC<ProductAttributesProps> = ({
attributes,
disabled,
- onChange
+ onChange,
+ onMultiChange
}) => {
const classes = useStyles({});
const [expanded, setExpansionStatus] = React.useState(true);
@@ -155,10 +157,19 @@ const ProductAttributes: React.FC<ProductAttributesProps> = ({
) : (
<MultiAutocompleteSelectField
choices={getMultiChoices(attribute.data.values)}
+ displayValues={maybe(
+ () =>
+ attribute.data.values.map(value => ({
+ label: value.name,
+ value: value.id
+ })),
+ []
+ )}
label={i18n.t("Values")}
+ name={`attribute:${attribute.label}`}
value={attribute.value}
onChange={event =>
- onChange(attribute.id, event.target.value)
+ onMultiChange(attribute.id, event.target.value)
}
/>
)}
diff --git a/saleor/static/dashboard-next/products/components/ProductOrganization/ProductOrganization.tsx b/saleor/static/dashboard-next/products/components/ProductOrganization/ProductOrganization.tsx
index b6fd090faa..31e010bbad 100644
--- a/saleor/static/dashboard-next/products/components/ProductOrganization/ProductOrganization.tsx
+++ b/saleor/static/dashboard-next/products/components/ProductOrganization/ProductOrganization.tsx
@@ -16,16 +16,14 @@ import Hr from "@saleor/components/Hr";
import MultiAutocompleteSelectField, {
MultiAutocompleteChoiceType
} from "@saleor/components/MultiAutocompleteSelectField";
-import SingleAutocompleteSelectField from "@saleor/components/SingleAutocompleteSelectField";
+import SingleAutocompleteSelectField, {
+ SingleAutocompleteChoiceType
+} from "@saleor/components/SingleAutocompleteSelectField";
import { ChangeEvent } from "@saleor/hooks/useForm";
import i18n from "@saleor/i18n";
import { maybe } from "@saleor/misc";
import { FormErrors } from "@saleor/types";
-interface ChoiceType {
- label: string;
- value: string;
-}
interface ProductType {
hasVariants: boolean;
id: string;
@@ -48,19 +46,20 @@ const styles = (theme: Theme) =>
interface ProductOrganizationProps extends WithStyles<typeof styles> {
canChangeType: boolean;
- categories?: ChoiceType[];
+ categories?: SingleAutocompleteChoiceType[];
categoryInputDisplayValue: string;
- collections?: ChoiceType[];
+ collections?: MultiAutocompleteChoiceType[];
+ collectionsInputDisplayValue: MultiAutocompleteChoiceType[];
data: {
category: string;
+ collections: string[];
productType?: string;
};
disabled: boolean;
errors: FormErrors<"productType" | "category">;
- selectedCollections: MultiAutocompleteChoiceType[];
productType?: ProductType;
productTypeInputDisplayValue?: string;
- productTypes?: ChoiceType[];
+ productTypes?: SingleAutocompleteChoiceType[];
fetchCategories: (query: string) => void;
fetchCollections: (query: string) => void;
onCategoryChange: (event: ChangeEvent) => void;
@@ -75,12 +74,12 @@ const ProductOrganization = withStyles(styles, { name: "ProductOrganization" })(
categoryInputDisplayValue,
classes,
collections,
+ collectionsInputDisplayValue,
data,
disabled,
errors,
fetchCategories,
fetchCollections,
- selectedCollections,
productType,
productTypeInputDisplayValue,
productTypes,
@@ -143,11 +142,11 @@ const ProductOrganization = withStyles(styles, { name: "ProductOrganization" })(
<Hr />
<FormSpacer />
<MultiAutocompleteSelectField
- displayValues={selectedCollections}
+ displayValues={collectionsInputDisplayValue}
label={i18n.t("Collections")}
choices={disabled ? [] : collections}
name="collections"
- value={selectedCollections.map(collection => collection.value)}
+ value={data.collections}
helperText={i18n.t(
"*Optional. Adding product to collection helps users find it."
)}
diff --git a/saleor/static/dashboard-next/products/components/ProductUpdatePage/ProductUpdatePage.tsx b/saleor/static/dashboard-next/products/components/ProductUpdatePage/ProductUpdatePage.tsx
index 72e98991be..dea9281a01 100644
--- a/saleor/static/dashboard-next/products/components/ProductUpdatePage/ProductUpdatePage.tsx
+++ b/saleor/static/dashboard-next/products/components/ProductUpdatePage/ProductUpdatePage.tsx
@@ -14,14 +14,12 @@ 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 useStateFromProps from "@saleor/hooks/useStateFromProps";
import i18n from "@saleor/i18n";
import { maybe } from "@saleor/misc";
import { ListActions, UserError } from "@saleor/types";
import {
ProductDetails_product,
- ProductDetails_product_collections,
ProductDetails_product_images,
ProductDetails_product_variants
} from "../../types/ProductDetails";
@@ -43,6 +41,8 @@ import ProductOrganization from "../ProductOrganization";
import ProductPricing from "../ProductPricing";
import ProductStock from "../ProductStock";
import ProductVariants from "../ProductVariants";
+import createMultiAutocompleteSelectHandler from "@saleor/utils/handlers/multiAutocompleteSelectChangeHandler";
+import createSingleAutocompleteSelectHandler from "@saleor/utils/handlers/singleAutocompleteSelectChangeHandler";
interface ProductUpdatePageProps extends ListActions {
errors: UserError[];
@@ -50,7 +50,6 @@ interface ProductUpdatePageProps extends ListActions {
collections: SearchCollections_collections_edges_node[];
categories: SearchCategories_categories_edges_node[];
disabled: boolean;
- productCollections: ProductDetails_product_collections[];
variants: ProductDetails_product_variants[];
images: ProductDetails_product_images[];
product: ProductDetails_product;
@@ -88,7 +87,6 @@ export const ProductUpdatePage: React.FC<ProductUpdatePageProps> = ({
header,
placeholderImage,
product,
- productCollections,
saveButtonBarState,
variants,
onAttributesEdit,
@@ -112,13 +110,12 @@ export const ProductUpdatePage: React.FC<ProductUpdatePageProps> = ({
getAttributeInputFromProduct(product)
);
const [selectedCategory, setSelectedCategory] = useStateFromProps(
- maybe(() => product.category.name)
+ maybe(() => product.category.name, "")
);
- const {
- change: selectCollection,
- data: selectedCollections
- } = useMultiAutocomplete(getChoices(productCollections));
+ const [selectedCollections, setSelectedCollections] = useStateFromProps(
+ getChoices(maybe(() => product.collections, []))
+ );
const initialData = getProductUpdatePageFormData(product, variants);
const initialDescription = maybe<RawDraftContentState>(() =>
@@ -133,7 +130,6 @@ export const ProductUpdatePage: React.FC<ProductUpdatePageProps> = ({
const handleSubmit = (data: ProductUpdatePageFormData) =>
onSubmit({
attributes,
- collections: selectedCollections.map(({ value }) => value),
...data
});
@@ -144,15 +140,25 @@ export const ProductUpdatePage: React.FC<ProductUpdatePageProps> = ({
initial={initialData}
confirmLeave
>
- {({ change, data, errors, hasChanged, submit, triggerChange }) => {
- const handleCollectionSelect = createCollectionSelectHandler(
- event => selectCollection(event, collections),
- triggerChange
+ {({
+ change,
+ data,
+ errors,
+ hasChanged,
+ submit,
+ triggerChange,
+ toggleValue
+ }) => {
+ const handleCollectionSelect = createMultiAutocompleteSelectHandler(
+ toggleValue,
+ setSelectedCollections,
+ selectedCollections,
+ collections
);
- const handleCategorySelect = createCategorySelectHandler(
- categoryChoiceList,
+ const handleCategorySelect = createSingleAutocompleteSelectHandler(
+ change,
setSelectedCategory,
- change
+ categories
);
const handleAttributeChange = createAttributeChangeHandler(
changeAttributeData,
@@ -240,13 +246,13 @@ export const ProductUpdatePage: React.FC<ProductUpdatePageProps> = ({
categories={categories}
categoryInputDisplayValue={selectedCategory}
collections={collections}
+ collectionsInputDisplayValue={selectedCollections}
data={data}
disabled={disabled}
errors={errors}
fetchCategories={fetchCategories}
fetchCollections={fetchCollections}
productType={maybe(() => product.productType)}
- selectedCollections={selectedCollections}
onCategoryChange={handleCategorySelect}
onCollectionChange={handleCollectionSelect}
/>
diff --git a/saleor/static/dashboard-next/products/utils/data.ts b/saleor/static/dashboard-next/products/utils/data.ts
index f473a13e10..f03bead1ea 100644
--- a/saleor/static/dashboard-next/products/utils/data.ts
+++ b/saleor/static/dashboard-next/products/utils/data.ts
@@ -87,6 +87,7 @@ export function getChoices(nodes: Node[]): SingleAutocompleteChoiceType[] {
export interface ProductUpdatePageFormData {
basePrice: number;
category: string | null;
+ collections: string[];
chargeTaxes: boolean;
description: RawDraftContentState;
isPublished: boolean;
@@ -106,6 +107,9 @@ export function getProductUpdatePageFormData(
basePrice: maybe(() => product.basePrice.amount),
category: maybe(() => product.category.id),
chargeTaxes: maybe(() => product.chargeTaxes, false),
+ collections: maybe(() =>
+ product.collections.map(collection => collection.id)
+ ),
description: maybe(() => JSON.parse(product.descriptionJson)),
isPublished: maybe(() => product.isPublished, false),
name: maybe(() => product.name),
diff --git a/saleor/static/dashboard-next/products/utils/handlers.ts b/saleor/static/dashboard-next/products/utils/handlers.ts
index 2abbb3fa39..964928e303 100644
--- a/saleor/static/dashboard-next/products/utils/handlers.ts
+++ b/saleor/static/dashboard-next/products/utils/handlers.ts
@@ -1,32 +1,7 @@
-import { FormChange } from "@saleor/components/Form";
-import { SearchCategories_categories_edges_node } from "@saleor/containers/SearchCategories/types/SearchCategories";
+import { FormChange } from "@saleor/hooks/useForm";
import { FormsetChange } from "@saleor/hooks/useFormset";
import { ProductType } from "./data";
-export function createCollectionSelectHandler(
- change: FormChange,
- triggerChange: () => void
-): FormChange {
- return (event: React.ChangeEvent<any>) => {
- change(event);
- triggerChange();
- };
-}
-
-export function createCategorySelectHandler(
- categoryChoiceList: SearchCategories_categories_edges_node[],
- setSelectedCategory: (id: string) => void,
- change: FormChange
-): FormChange {
- return (event: React.ChangeEvent<any>) => {
- const id = event.target.value;
- setSelectedCategory(
- categoryChoiceList.find(category => category.id === id).name
- );
- change(event);
- };
-}
-
export function createAttributeChangeHandler(
changeAttributeData: FormsetChange,
triggerChange: () => void
diff --git a/saleor/static/dashboard-next/utils/handlers/multiAutocompleteSelectChangeHandler.ts b/saleor/static/dashboard-next/utils/handlers/multiAutocompleteSelectChangeHandler.ts
new file mode 100644
index 0000000000..72f7927404
--- /dev/null
+++ b/saleor/static/dashboard-next/utils/handlers/multiAutocompleteSelectChangeHandler.ts
@@ -0,0 +1,21 @@
+import { MultiAutocompleteChoiceType } from "@saleor/components/MultiAutocompleteSelectField";
+import { ChangeEvent, FormChange } from "@saleor/hooks/useForm";
+import { toggle } from "../lists";
+
+function createMultiAutocompleteSelectHandler(
+ change: FormChange,
+ setSelected: (choices: MultiAutocompleteChoiceType[]) => void,
+ selected: MultiAutocompleteChoiceType[],
+ choices: MultiAutocompleteChoiceType[]
+): FormChange {
+ return (event: ChangeEvent) => {
+ change(event);
+
+ const id = event.target.value;
+ const choice = choices.find(choice => choice.value === id);
+
+ setSelected(toggle(choice, selected, (a, b) => a.value === b.value));
+ };
+}
+
+export default createMultiAutocompleteSelectHandler;
diff --git a/saleor/static/dashboard-next/utils/handlers/singleAutocompleteSelectChangeHandler.ts b/saleor/static/dashboard-next/utils/handlers/singleAutocompleteSelectChangeHandler.ts
new file mode 100644
index 0000000000..ee22651850
--- /dev/null
+++ b/saleor/static/dashboard-next/utils/handlers/singleAutocompleteSelectChangeHandler.ts
@@ -0,0 +1,17 @@
+import { SingleAutocompleteChoiceType } from "@saleor/components/SingleAutocompleteSelectField";
+import { FormChange } from "@saleor/hooks/useForm";
+
+function createSingleAutocompleteSelectHandler(
+ change: FormChange,
+ setSelected: (value: string) => void,
+ choices: SingleAutocompleteChoiceType[]
+): FormChange {
+ return (event: React.ChangeEvent<any>) => {
+ change(event);
+
+ const value = event.target.value;
+ setSelected(choices.find(category => category.value === value).label);
+ };
+}
+
+export default createSingleAutocompleteSelectHandler;