Skip to content

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

Use hooks in form component

dominik-zeglen96f8b0e4f47f
diff --git a/saleor/static/dashboard-next/components/ConfirmFormLeaveDialog.tsx b/saleor/static/dashboard-next/components/ConfirmFormLeaveDialog.tsx
deleted file mode 100644
index 4c5334a26f..0000000000
--- a/saleor/static/dashboard-next/components/ConfirmFormLeaveDialog.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import Button from "@material-ui/core/Button";
-import Dialog from "@material-ui/core/Dialog";
-import DialogActions from "@material-ui/core/DialogActions";
-import DialogContent from "@material-ui/core/DialogContent";
-import DialogContentText from "@material-ui/core/DialogContentText";
-import DialogTitle from "@material-ui/core/DialogTitle";
-import {
- createStyles,
- Theme,
- withStyles,
- WithStyles
-} from "@material-ui/core/styles";
-import React from "react";
-import NavigationPrompt from "react-router-navigation-prompt";
-
-import i18n from "../i18n";
-import { FormContext } from "./Form";
-
-const styles = (theme: Theme) =>
- createStyles({
- deleteButton: {
- "&:hover": {
- backgroundColor: theme.palette.error.main
- },
- backgroundColor: theme.palette.error.main,
- color: theme.palette.error.contrastText
- }
- });
-
-export const ConfirmFormLeaveDialog = withStyles(styles, {
- name: "ConfirmFormLeaveDialog"
-})(({ classes }: WithStyles<typeof styles>) => (
- <FormContext.Consumer>
- {({ hasChanged: hasFormChanged }) => (
- <NavigationPrompt renderIfNotActive={true} when={hasFormChanged}>
- {({ isActive, onCancel, onConfirm }) => (
- <Dialog onClose={onCancel} open={isActive}>
- <DialogTitle>{i18n.t("Unsaved changes")}</DialogTitle>
- <DialogContent>
- <DialogContentText>
- {i18n.t(
- "If you leave this page, unsaved changes will be lost. Are you sure you want to leave?",
- {
- context: "form leave confirmation"
- }
- )}
- </DialogContentText>
- </DialogContent>
- <DialogActions>
- <Button onClick={onCancel}>
- {i18n.t("Cancel", { context: "button" })}
- </Button>
- <Button onClick={onConfirm} className={classes.deleteButton}>
- {i18n.t("Leave page", { context: "button" })}
- </Button>
- </DialogActions>
- </Dialog>
- )}
- </NavigationPrompt>
- )}
- </FormContext.Consumer>
-));
diff --git a/saleor/static/dashboard-next/components/EditableTableCell/EditableTableCell.tsx b/saleor/static/dashboard-next/components/EditableTableCell/EditableTableCell.tsx
index 363d8ea49b..594c244cad 100644
--- a/saleor/static/dashboard-next/components/EditableTableCell/EditableTableCell.tsx
+++ b/saleor/static/dashboard-next/components/EditableTableCell/EditableTableCell.tsx
@@ -12,7 +12,7 @@ import Typography from "@material-ui/core/Typography";
import classNames from "classnames";
import React from "react";
-import Form from "@saleor/components/Form";
+import useForm from "@saleor/hooks/useForm";
const styles = (theme: Theme) =>
createStyles({
@@ -66,48 +66,39 @@ export const EditableTableCell = withStyles(styles, {
value,
onConfirm
}: EditableTableCellProps) => {
- const [opened, setOpenStatus] = React.useState(focused);
- const enable = () => setOpenStatus(true);
- const disable = () => setOpenStatus(false);
-
const handleConfirm = (data: { value: string }) => {
disable();
onConfirm(data.value);
};
+ const [opened, setOpenStatus] = React.useState(focused);
+ const { change, data } = useForm({ value }, [], handleConfirm);
+ const enable = () => setOpenStatus(true);
+ const disable = () => setOpenStatus(false);
+
return (
<TableCell className={classNames(classes.container, className)}>
{opened && <div className={classes.overlay} onClick={disable} />}
- <Form initial={{ value }} onSubmit={handleConfirm} useForm={false}>
- {({ change, data }) => (
- <>
- <Typography
- variant="caption"
- onClick={enable}
- className={classes.text}
- >
- {value || defaultValue}
- </Typography>
- {opened && (
- <div className={classes.root}>
- <Card className={classes.card}>
- <CardContent>
- <TextField
- name="value"
- autoFocus
- fullWidth
- onChange={change}
- value={data.value}
- variant="standard"
- {...InputProps}
- />
- </CardContent>
- </Card>
- </div>
- )}
- </>
- )}
- </Form>
+ <Typography variant="caption" onClick={enable} className={classes.text}>
+ {value || defaultValue}
+ </Typography>
+ {opened && (
+ <div className={classes.root}>
+ <Card className={classes.card}>
+ <CardContent>
+ <TextField
+ name="value"
+ autoFocus
+ fullWidth
+ onChange={change}
+ value={data.value}
+ variant="standard"
+ {...InputProps}
+ />
+ </CardContent>
+ </Card>
+ </div>
+ )}
</TableCell>
);
}
diff --git a/saleor/static/dashboard-next/components/Form/Form.tsx b/saleor/static/dashboard-next/components/Form/Form.tsx
index 306348168a..c44613cc31 100644
--- a/saleor/static/dashboard-next/components/Form/Form.tsx
+++ b/saleor/static/dashboard-next/components/Form/Form.tsx
@@ -1,170 +1,212 @@
+// import React from "react";
+// import { UserError } from "../../types";
+
+// export interface FormProps<T extends {}> {
+// children: (props: {
+// data: T;
+// hasChanged: boolean;
+// errors: { [key: string]: string };
+// change(event: React.ChangeEvent<any>, cb?: () => void);
+// reset();
+// submit(event?: React.FormEvent<any>);
+// }) => React.ReactElement<any>;
+// errors?: UserError[];
+// initial?: T;
+// confirmLeave?: boolean;
+// useForm?: boolean;
+// resetOnSubmit?: boolean;
+// onSubmit?(data: T);
+// }
+
+// interface FormComponentProps<T extends {}> extends FormProps<T> {
+// hasChanged: boolean;
+// toggleFormChangeState: () => void;
+// }
+
+// interface FormState<T extends {}> {
+// initial: T;
+// fields: T;
+// hasChanged: boolean;
+// }
+
+// class FormComponent<T extends {} = {}> extends React.Component<
+// FormComponentProps<T>,
+// FormState<T>
+// > {
+// static getDerivedStateFromProps<T extends {} = {}>(
+// nextProps: FormComponentProps<T>,
+// prevState: FormState<T>
+// ): FormState<T> {
+// const changedFields = Object.keys(nextProps.initial).filter(
+// nextFieldName =>
+// JSON.stringify(nextProps.initial[nextFieldName]) !==
+// JSON.stringify(prevState.initial[nextFieldName])
+// );
+// if (changedFields.length > 0) {
+// const swapFields = changedFields.reduce((prev, curr) => {
+// prev[curr] = nextProps.initial[curr];
+// return prev;
+// }, {});
+
+// return {
+// fields: {
+// ...(prevState.fields as any),
+// ...swapFields
+// },
+// hasChanged: false,
+// initial: {
+// ...(prevState.initial as any),
+// ...swapFields
+// }
+// };
+// }
+// return null;
+// }
+
+// state: FormState<T> = {
+// fields: this.props.initial,
+// hasChanged: false,
+// initial: this.props.initial
+// };
+
+// componentDidUpdate() {
+// const { hasChanged, confirmLeave, toggleFormChangeState } = this.props;
+// if (this.state.hasChanged !== hasChanged && confirmLeave) {
+// toggleFormChangeState();
+// }
+// }
+
+// componentDidMount() {
+// const { hasChanged, confirmLeave, toggleFormChangeState } = this.props;
+// if (this.state.hasChanged !== hasChanged && confirmLeave) {
+// toggleFormChangeState();
+// }
+// }
+
+// componentWillUnmount() {
+// const { hasChanged, confirmLeave, toggleFormChangeState } = this.props;
+// if (hasChanged && confirmLeave) {
+// toggleFormChangeState();
+// }
+// }
+
+// handleChange = (event: React.ChangeEvent<any>, cb?: () => void) => {
+// const { target } = event;
+// if (!(target.name in this.state.fields)) {
+// console.error(`Unknown form field: ${target.name}`);
+// return;
+// }
+
+// this.setState(
+// {
+// fields: {
+// ...(this.state.fields as any),
+// [target.name]: target.value
+// },
+// hasChanged: true
+// },
+// typeof cb === "function" ? cb : undefined
+// );
+// };
+
+// handleKeyDown = (event: React.KeyboardEvent<any>) => {
+// switch (event.keyCode) {
+// // Enter
+// case 13:
+// this.props.onSubmit(this.state.fields);
+// break;
+// }
+// };
+
+// handleSubmit = (event?: React.FormEvent<any>, cb?: () => void) => {
+// const { resetOnSubmit, onSubmit } = this.props;
+// if (event) {
+// event.stopPropagation();
+// event.preventDefault();
+// }
+// if (onSubmit !== undefined) {
+// onSubmit(this.state.fields);
+// }
+// if (cb) {
+// cb();
+// }
+// if (resetOnSubmit) {
+// this.setState({
+// fields: this.state.initial
+// });
+// }
+// };
+
+// render() {
+// const { children, errors, useForm = true } = this.props;
+
+// const contents = children({
+// change: this.handleChange,
+// data: this.state.fields,
+// errors: errors
+// ? errors.reduce(
+// (prev, curr) => ({
+// ...prev,
+// [curr.field.split(":")[0]]: curr.message
+// }),
+// {}
+// )
+// : {},
+// hasChanged: this.state.hasChanged,
+// reset: () =>
+// this.setState({
+// fields: this.state.initial
+// }),
+// submit: this.handleSubmit
+// });
+
+// return useForm ? (
+// <form onSubmit={this.handleSubmit}>{contents}</form>
+// ) : (
+// <div onKeyDown={this.handleKeyDown}>{contents}</div>
+// );
+// }
+// }
+// export default FormComponent;
+
import React from "react";
-import { UserError } from "../../types";
-
-export interface FormProps<T extends {}> {
- children: (props: {
- data: T;
- hasChanged: boolean;
- errors: { [key: string]: string };
- change(event: React.ChangeEvent<any>, cb?: () => void);
- reset();
- submit(event?: React.FormEvent<any>);
- }) => React.ReactElement<any>;
+
+import useForm, { UseFormResult } from "@saleor/hooks/useForm";
+import { UserError } from "@saleor/types";
+
+export interface FormProps<T> {
+ children: (props: UseFormResult<T>) => React.ReactNode;
+ confirmLeave?: boolean;
errors?: UserError[];
initial?: T;
- confirmLeave?: boolean;
- useForm?: boolean;
resetOnSubmit?: boolean;
- onSubmit?(data: T);
-}
-
-interface FormComponentProps<T extends {}> extends FormProps<T> {
- hasChanged: boolean;
- toggleFormChangeState: () => void;
-}
-
-interface FormState<T extends {}> {
- initial: T;
- fields: T;
- hasChanged: boolean;
+ useForm?: boolean;
+ onSubmit?: (data: T) => void;
}
-class FormComponent<T extends {} = {}> extends React.Component<
- FormComponentProps<T>,
- FormState<T>
-> {
- static getDerivedStateFromProps<T extends {} = {}>(
- nextProps: FormComponentProps<T>,
- prevState: FormState<T>
- ): FormState<T> {
- const changedFields = Object.keys(nextProps.initial).filter(
- nextFieldName =>
- JSON.stringify(nextProps.initial[nextFieldName]) !==
- JSON.stringify(prevState.initial[nextFieldName])
- );
- if (changedFields.length > 0) {
- const swapFields = changedFields.reduce((prev, curr) => {
- prev[curr] = nextProps.initial[curr];
- return prev;
- }, {});
-
- return {
- fields: {
- ...(prevState.fields as any),
- ...swapFields
- },
- hasChanged: false,
- initial: {
- ...(prevState.initial as any),
- ...swapFields
- }
- };
- }
- return null;
- }
-
- state: FormState<T> = {
- fields: this.props.initial,
- hasChanged: false,
- initial: this.props.initial
- };
+function Form<T>(props: FormProps<T>) {
+ const { children, errors, initial, resetOnSubmit, onSubmit } = props;
+ const renderProps = useForm(initial, errors, onSubmit);
- componentDidUpdate() {
- const { hasChanged, confirmLeave, toggleFormChangeState } = this.props;
- if (this.state.hasChanged !== hasChanged && confirmLeave) {
- toggleFormChangeState();
- }
- }
+ function handleSubmit(event?: React.FormEvent<any>, cb?: () => void) {
+ const { reset } = renderProps;
- componentDidMount() {
- const { hasChanged, confirmLeave, toggleFormChangeState } = this.props;
- if (this.state.hasChanged !== hasChanged && confirmLeave) {
- toggleFormChangeState();
- }
- }
-
- componentWillUnmount() {
- const { hasChanged, confirmLeave, toggleFormChangeState } = this.props;
- if (hasChanged && confirmLeave) {
- toggleFormChangeState();
- }
- }
-
- handleChange = (event: React.ChangeEvent<any>, cb?: () => void) => {
- const { target } = event;
- if (!(target.name in this.state.fields)) {
- console.error(`Unknown form field: ${target.name}`);
- return;
- }
-
- this.setState(
- {
- fields: {
- ...(this.state.fields as any),
- [target.name]: target.value
- },
- hasChanged: true
- },
- typeof cb === "function" ? cb : undefined
- );
- };
-
- handleKeyDown = (event: React.KeyboardEvent<any>) => {
- switch (event.keyCode) {
- // Enter
- case 13:
- this.props.onSubmit(this.state.fields);
- break;
- }
- };
-
- handleSubmit = (event?: React.FormEvent<any>, cb?: () => void) => {
- const { resetOnSubmit, onSubmit } = this.props;
if (event) {
event.stopPropagation();
event.preventDefault();
}
- if (onSubmit !== undefined) {
- onSubmit(this.state.fields);
- }
+
if (cb) {
cb();
}
+
if (resetOnSubmit) {
- this.setState({
- fields: this.state.initial
- });
+ reset();
}
- };
-
- render() {
- const { children, errors, useForm = true } = this.props;
-
- const contents = children({
- change: this.handleChange,
- data: this.state.fields,
- errors: errors
- ? errors.reduce(
- (prev, curr) => ({
- ...prev,
- [curr.field.split(":")[0]]: curr.message
- }),
- {}
- )
- : {},
- hasChanged: this.state.hasChanged,
- reset: () =>
- this.setState({
- fields: this.state.initial
- }),
- submit: this.handleSubmit
- });
-
- return useForm ? (
- <form onSubmit={this.handleSubmit}>{contents}</form>
- ) : (
- <div onKeyDown={this.handleKeyDown}>{contents}</div>
- );
}
+
+ return <form onSubmit={handleSubmit}>{children(renderProps)}</form>;
}
-export default FormComponent;
+Form.displayName = "Form";
+
+export default Form;
diff --git a/saleor/static/dashboard-next/components/Form/FormContext.tsx b/saleor/static/dashboard-next/components/Form/FormContext.tsx
deleted file mode 100644
index 4ef3b81016..0000000000
--- a/saleor/static/dashboard-next/components/Form/FormContext.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import React from "react";
-
-import FormComponent, { FormProps } from "./Form";
-
-interface IFormContext {
- hasChanged: boolean;
- toggle: () => void;
-}
-
-export const FormContext = React.createContext<IFormContext>(undefined);
-
-interface FormProviderState {
- hasChanged: boolean;
-}
-
-export class FormProvider extends React.Component<{}, FormProviderState> {
- state: FormProviderState = {
- hasChanged: false
- };
-
- toggle = () =>
- this.setState(prevState => ({
- hasChanged: !prevState.hasChanged
- }));
-
- render() {
- return (
- <FormContext.Provider
- value={{
- hasChanged: this.state.hasChanged,
- toggle: this.toggle
- }}
- >
- {this.props.children}
- </FormContext.Provider>
- );
- }
-}
-
-export function Form<T>(props: FormProps<T>) {
- return (
- <FormContext.Consumer>
- {({ hasChanged, toggle }) => (
- <FormComponent
- {...props}
- toggleFormChangeState={toggle}
- hasChanged={hasChanged}
- />
- )}
- </FormContext.Consumer>
- );
-}
-
-export default Form;
diff --git a/saleor/static/dashboard-next/components/Form/index.ts b/saleor/static/dashboard-next/components/Form/index.ts
index 1f0b7dda49..98ebc8cc61 100644
--- a/saleor/static/dashboard-next/components/Form/index.ts
+++ b/saleor/static/dashboard-next/components/Form/index.ts
@@ -1,5 +1,4 @@
export * from "./Form";
+export { default } from "./Form";
export { default as FormActions } from "./FormActions";
export * from "./FormActions";
-export * from "./FormContext";
-export { default } from "./FormContext";
diff --git a/saleor/static/dashboard-next/hooks/useForm.ts b/saleor/static/dashboard-next/hooks/useForm.ts
new file mode 100644
index 0000000000..fd8d6904dc
--- /dev/null
+++ b/saleor/static/dashboard-next/hooks/useForm.ts
@@ -0,0 +1,96 @@
+import isEqual from "lodash-es/isEqual";
+import { useState } from "react";
+
+import { UserError } from "@saleor/types";
+import { toggle } from "@saleor/utils/lists";
+import useStateFromProps from "./useStateFromProps";
+
+interface ChangeEvent<T> {
+ target: {
+ name: keyof T | string;
+ value: any;
+ };
+}
+
+export interface UseFormResult<T> {
+ change: (event: ChangeEvent<T>, cb?: () => void) => void;
+ data: T;
+ errors: Record<string, string>;
+ hasChanged: boolean;
+ reset: () => void;
+ submit: () => void;
+ toggleValue: (event: ChangeEvent<T>) => void;
+}
+
+function parseErrors(errors: UserError[]): Record<string, string> {
+ return errors
+ ? errors.reduce(
+ (prev, curr) => ({
+ ...prev,
+ [curr.field.split(":")[0]]: curr.message
+ }),
+ {}
+ )
+ : {};
+}
+
+function useForm<T extends Record<keyof T, any | any[]>>(
+ initial: T,
+ errors: UserError[],
+ onSubmit: (data: T) => void
+): UseFormResult<T> {
+ const [data, setData] = useStateFromProps(initial);
+ const [hasChanged, setChanged] = useState(false);
+
+ function toggleValue(event: ChangeEvent<T>) {
+ const { name, value } = event.target;
+ const field = data[name as keyof T];
+
+ if (Array.isArray(field)) {
+ setData({
+ ...data,
+ [name]: toggle(value, field, isEqual)
+ });
+ }
+ }
+
+ function change(event: ChangeEvent<T>, cb?: () => void) {
+ const { name, value } = event.target;
+
+ if (!(name in data)) {
+ console.error(`Unknown form field: ${name}`);
+ return;
+ }
+
+ if (!hasChanged) {
+ setChanged(true);
+ }
+ setData({
+ ...data,
+ [name]: value
+ });
+ if (typeof cb === "function") {
+ cb();
+ }
+ }
+
+ function reset() {
+ setData(initial);
+ }
+
+ function submit() {
+ return onSubmit(data);
+ }
+
+ return {
+ change,
+ data,
+ errors: parseErrors(errors),
+ hasChanged,
+ reset,
+ submit,
+ toggleValue
+ };
+}
+
+export default useForm;
diff --git a/saleor/static/dashboard-next/hooks/useStateFromProps.ts b/saleor/static/dashboard-next/hooks/useStateFromProps.ts
new file mode 100644
index 0000000000..b5abc44355
--- /dev/null
+++ b/saleor/static/dashboard-next/hooks/useStateFromProps.ts
@@ -0,0 +1,16 @@
+import isEqual from "lodash-es/isEqual";
+import { Dispatch, SetStateAction, useEffect, useState } from "react";
+
+function useStateFromProps<T>(data: T): [T, Dispatch<SetStateAction<T>>] {
+ const [state, setState] = useState(data);
+ const [prevState, setPrevState] = useState(data);
+
+ useEffect(() => {
+ setState(data);
+ setPrevState(data);
+ }, [!isEqual(prevState, data)]);
+
+ return [state, setState];
+}
+
+export default useStateFromProps;
diff --git a/saleor/static/dashboard-next/index.tsx b/saleor/static/dashboard-next/index.tsx
index 0364dbcaf1..9df25ff671 100644
--- a/saleor/static/dashboard-next/index.tsx
+++ b/saleor/static/dashboard-next/index.tsx
@@ -20,9 +20,7 @@ import Login from "./auth/views/Login";
import CategorySection from "./categories";
import CollectionSection from "./collections";
import { AppProgressProvider } from "./components/AppProgress";
-// import { ConfirmFormLeaveDialog } from "./components/ConfirmFormLeaveDialog";
import { DateProvider } from "./components/Date";
-import { FormProvider } from "./components/Form";
import { LocaleProvider } from "./components/Locale";
import { MessageManager } from "./components/messages";
import { ShopProvider } from "./components/Shop";
@@ -108,134 +106,124 @@ const App: React.FC = () => {
const isDark = localStorage.getItem("theme") === "true";
return (
- <FormProvider>
- <ApolloProvider client={apolloClient}>
- <BrowserRouter basename={APP_MOUNT_URI}>
- <ThemeProvider isDefaultDark={isDark}>
- <DateProvider>
- <LocaleProvider>
- <MessageManager>
- <AppProgressProvider>
- <ShopProvider>
- <WindowTitle title={i18n.t("Dashboard")} />
- {/* FIXME: #3424 */}
- {/* <ConfirmFormLeaveDialog /> */}
- <AuthProvider>
- {({
- hasToken,
- isAuthenticated,
- tokenAuthLoading,
- tokenVerifyLoading,
- user
- }) => {
- return isAuthenticated &&
- !tokenAuthLoading &&
- !tokenVerifyLoading ? (
- <Switch>
+ <ApolloProvider client={apolloClient}>
+ <BrowserRouter basename={APP_MOUNT_URI}>
+ <ThemeProvider isDefaultDark={isDark}>
+ <DateProvider>
+ <LocaleProvider>
+ <MessageManager>
+ <AppProgressProvider>
+ <ShopProvider>
+ <WindowTitle title={i18n.t("Dashboard")} />
+ <AuthProvider>
+ {({
+ hasToken,
+ isAuthenticated,
+ tokenAuthLoading,
+ tokenVerifyLoading,
+ user
+ }) => {
+ return isAuthenticated &&
+ !tokenAuthLoading &&
+ !tokenVerifyLoading ? (
+ <Switch>
+ <SectionRoute exact path="/" component={HomePage} />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_PRODUCTS]}
+ path="/categories"
+ component={CategorySection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_PRODUCTS]}
+ path="/collections"
+ component={CollectionSection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_USERS]}
+ path="/customers"
+ component={CustomerSection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_DISCOUNTS]}
+ path="/discounts"
+ component={DiscountSection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_PAGES]}
+ path="/pages"
+ component={PageSection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_ORDERS]}
+ path="/orders"
+ component={OrdersSection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_PRODUCTS]}
+ path="/products"
+ component={ProductSection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_PRODUCTS]}
+ path="/product-types"
+ component={ProductTypesSection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_STAFF]}
+ path="/staff"
+ component={StaffSection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_SETTINGS]}
+ path="/site-settings"
+ component={SiteSettingsSection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_SETTINGS]}
+ path="/taxes"
+ component={TaxesSection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_SHIPPING]}
+ path="/shipping"
+ component={ShippingSection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_TRANSLATIONS]}
+ path="/translations"
+ component={TranslationsSection}
+ />
+ <SectionRoute
+ permissions={[PermissionEnum.MANAGE_MENUS]}
+ path={navigationSection}
+ component={NavigationSection}
+ />
+ {configurationMenu.filter(menuItem =>
+ hasPermission(menuItem.permission, user)
+ ).length > 0 && (
<SectionRoute
exact
- path="/"
- component={HomePage}
+ path="/configuration"
+ component={ConfigurationSection}
/>
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_PRODUCTS]}
- path="/categories"
- component={CategorySection}
- />
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_PRODUCTS]}
- path="/collections"
- component={CollectionSection}
- />
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_USERS]}
- path="/customers"
- component={CustomerSection}
- />
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_DISCOUNTS]}
- path="/discounts"
- component={DiscountSection}
- />
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_PAGES]}
- path="/pages"
- component={PageSection}
- />
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_ORDERS]}
- path="/orders"
- component={OrdersSection}
- />
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_PRODUCTS]}
- path="/products"
- component={ProductSection}
- />
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_PRODUCTS]}
- path="/product-types"
- component={ProductTypesSection}
- />
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_STAFF]}
- path="/staff"
- component={StaffSection}
- />
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_SETTINGS]}
- path="/site-settings"
- component={SiteSettingsSection}
- />
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_SETTINGS]}
- path="/taxes"
- component={TaxesSection}
- />
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_SHIPPING]}
- path="/shipping"
- component={ShippingSection}
- />
- <SectionRoute
- permissions={[
- PermissionEnum.MANAGE_TRANSLATIONS
- ]}
- path="/translations"
- component={TranslationsSection}
- />
- <SectionRoute
- permissions={[PermissionEnum.MANAGE_MENUS]}
- path={navigationSection}
- component={NavigationSection}
- />
- {configurationMenu.filter(menuItem =>
- hasPermission(menuItem.permission, user)
- ).length > 0 && (
- <SectionRoute
- exact
- path="/configuration"
- component={ConfigurationSection}
- />
- )}
- <Route component={NotFound} />
- </Switch>
- ) : hasToken && tokenVerifyLoading ? (
- <LoginLoading />
- ) : (
- <Login loading={tokenAuthLoading} />
- );
- }}
- </AuthProvider>
- </ShopProvider>
- </AppProgressProvider>
- </MessageManager>
- </LocaleProvider>
- </DateProvider>
- </ThemeProvider>
- </BrowserRouter>
- </ApolloProvider>
- </FormProvider>
+ )}
+ <Route component={NotFound} />
+ </Switch>
+ ) : hasToken && tokenVerifyLoading ? (
+ <LoginLoading />
+ ) : (
+ <Login loading={tokenAuthLoading} />
+ );
+ }}
+ </AuthProvider>
+ </ShopProvider>
+ </AppProgressProvider>
+ </MessageManager>
+ </LocaleProvider>
+ </DateProvider>
+ </ThemeProvider>
+ </BrowserRouter>
+ </ApolloProvider>
);
};
diff --git a/saleor/static/dashboard-next/storybook/Decorator.tsx b/saleor/static/dashboard-next/storybook/Decorator.tsx
index fc1b0497e0..573cde8b13 100644
--- a/saleor/static/dashboard-next/storybook/Decorator.tsx
+++ b/saleor/static/dashboard-next/storybook/Decorator.tsx
@@ -1,28 +1,25 @@
import React from "react";
import { Provider as DateProvider } from "../components/Date/DateContext";
-import { FormProvider } from "../components/Form";
import { MessageManager } from "../components/messages";
import ThemeProvider from "../components/Theme";
import { TimezoneProvider } from "../components/Timezone";
export const Decorator = storyFn => (
- <FormProvider>
- <DateProvider value={+new Date("2018-08-07T14:30:44+00:00")}>
- <TimezoneProvider value="America/New_York">
- <ThemeProvider isDefaultDark={false}>
- <MessageManager>
- <div
- style={{
- padding: 24
- }}
- >
- {storyFn()}
- </div>
- </MessageManager>
- </ThemeProvider>
- </TimezoneProvider>
- </DateProvider>
- </FormProvider>
+ <DateProvider value={+new Date("2018-08-07T14:30:44+00:00")}>
+ <TimezoneProvider value="America/New_York">
+ <ThemeProvider isDefaultDark={false}>
+ <MessageManager>
+ <div
+ style={{
+ padding: 24
+ }}
+ >
+ {storyFn()}
+ </div>
+ </MessageManager>
+ </ThemeProvider>
+ </TimezoneProvider>
+ </DateProvider>
);
export default Decorator;
diff --git a/saleor/static/dashboard-next/utils/lists/__snapshots__/lists.test.ts.snap b/saleor/static/dashboard-next/utils/lists/__snapshots__/lists.test.ts.snap
new file mode 100644
index 0000000000..93c5d4c066
--- /dev/null
+++ b/saleor/static/dashboard-next/utils/lists/__snapshots__/lists.test.ts.snap
@@ -0,0 +1,33 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Properly calculates output arrays Adds 1`] = `
+Array [
+ "lorem",
+ "ipsum",
+ "dolor",
+ "sit",
+]
+`;
+
+exports[`Properly calculates output arrays Removes 1`] = `
+Array [
+ "lorem",
+ "dolor",
+]
+`;
+
+exports[`Properly calculates output arrays Toggles 1`] = `
+Array [
+ "ipsum",
+ "dolor",
+]
+`;
+
+exports[`Properly calculates output arrays Toggles 2`] = `
+Array [
+ "lorem",
+ "ipsum",
+ "dolor",
+ "sit",
+]
+`;
diff --git a/saleor/static/dashboard-next/utils/lists/index.ts b/saleor/static/dashboard-next/utils/lists/index.ts
new file mode 100644
index 0000000000..fc00ec8632
--- /dev/null
+++ b/saleor/static/dashboard-next/utils/lists/index.ts
@@ -0,0 +1 @@
+export * from "./lists";
diff --git a/saleor/static/dashboard-next/utils/lists/lists.test.ts b/saleor/static/dashboard-next/utils/lists/lists.test.ts
new file mode 100644
index 0000000000..32caf71319
--- /dev/null
+++ b/saleor/static/dashboard-next/utils/lists/lists.test.ts
@@ -0,0 +1,23 @@
+import { add, isSelected, remove, toggle } from "./lists";
+
+const initialArray = ["lorem", "ipsum", "dolor"];
+
+describe("Properly calculates output arrays", () => {
+ it("Adds", () => {
+ expect(add("sit", initialArray)).toMatchSnapshot();
+ });
+
+ it("Removes", () => {
+ expect(remove("ipsum", initialArray, (a, b) => a === b)).toMatchSnapshot();
+ });
+
+ it("Matches", () => {
+ expect(isSelected("lorem", initialArray, (a, b) => a === b)).toBe(true);
+ expect(isSelected("sit", initialArray, (a, b) => a === b)).toBe(false);
+ });
+
+ it("Toggles", () => {
+ expect(toggle("lorem", initialArray, (a, b) => a === b)).toMatchSnapshot();
+ expect(toggle("sit", initialArray, (a, b) => a === b)).toMatchSnapshot();
+ });
+});
diff --git a/saleor/static/dashboard-next/utils/lists/lists.ts b/saleor/static/dashboard-next/utils/lists/lists.ts
new file mode 100644
index 0000000000..b1c2517932
--- /dev/null
+++ b/saleor/static/dashboard-next/utils/lists/lists.ts
@@ -0,0 +1,32 @@
+type List<TData> = TData[];
+type Compare<TData> = (a: TData, b: TData) => boolean;
+
+export function isSelected<TData>(
+ data: TData,
+ list: List<TData>,
+ compare: Compare<TData>
+) {
+ return !!list.find(listElement => compare(listElement, data));
+}
+
+export function add<TData>(data: TData, list: List<TData>) {
+ return [...list, data];
+}
+
+export function remove<TData>(
+ data: TData,
+ list: List<TData>,
+ compare: Compare<TData>
+) {
+ return list.filter(listElement => !compare(listElement, data));
+}
+
+export function toggle<TData>(
+ data: TData,
+ list: List<TData>,
+ compare: Compare<TData>
+) {
+ return isSelected(data, list, compare)
+ ? remove(data, list, compare)
+ : add(data, list);
+}