Skip to content

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

Move form logic to a typed Form component (#1978)

Patryk Zawadzkibb007e15096d
diff --git a/saleor/static/dashboard-next/category/components/BaseForm.tsx b/saleor/static/dashboard-next/category/components/BaseForm.tsx
index 33f6e0e638..a76446a9fc 100644
--- a/saleor/static/dashboard-next/category/components/BaseForm.tsx
+++ b/saleor/static/dashboard-next/category/components/BaseForm.tsx
@@ -19,98 +19,48 @@ const decorate = withStyles(theme => ({
}));
interface BaseCategoryFormProps {
- confirmButtonLabel: string;
description: string;
errors: Array<{
field: string;
message: string;
}>;
name: string;
- handleConfirm(data);
+ onChange?(event: React.ChangeEvent<any>);
}
-interface BaseCategoryFormState {
- formData: {
- description: string;
- name: string;
- };
-}
-
-export const BaseCategoryForm = decorate(
- class InnerBaseCategoryForm extends Component<
- BaseCategoryFormProps & WithStyles<"cardActions" | "textField">,
- BaseCategoryFormState
- > {
- state = {
- formData: {
- description: this.props.description,
- name: this.props.name
- }
- };
-
- handleInputChange = event => {
- const { target } = event;
- this.setState(prevState => ({
- formData: { ...prevState.formData, [target.name]: target.value }
- }));
- };
-
- render() {
- const {
- classes,
- confirmButtonLabel,
- description,
- handleConfirm,
- name,
- errors
- } = this.props;
- const errorList: { [key: string]: string } = errors.reduce(
- (acc, curr) => {
- acc[curr.field] = curr.message;
- return acc;
- },
- {}
- );
- return (
- <>
- <CardContent>
- <TextField
- autoFocus
- fullWidth
- className={classes.textField}
- defaultValue={name}
- error={!!errorList.name}
- helperText={errorList.name}
- label={i18n.t("Name", { context: "category" })}
- name="name"
- onChange={this.handleInputChange}
- />
- <TextField
- fullWidth
- multiline
- defaultValue={description}
- error={!!errorList.description}
- helperText={
- errorList.description ||
- i18n.t("Optional", { context: "field" })
- }
- label={i18n.t("Description")}
- name="description"
- onChange={this.handleInputChange}
- />
- </CardContent>
- <Toolbar className={classes.cardActions}>
- <Button
- variant="raised"
- color="primary"
- onClick={() => handleConfirm(this.state.formData)}
- >
- {confirmButtonLabel}
- </Button>
- </Toolbar>
- </>
- );
- }
+export const BaseCategoryForm = decorate<BaseCategoryFormProps>(
+ ({ classes, description, errors, name, onChange }) => {
+ const errorList: { [key: string]: string } = errors.reduce((acc, curr) => {
+ acc[curr.field] = curr.message;
+ return acc;
+ }, {});
+ return (
+ <CardContent>
+ <TextField
+ autoFocus
+ fullWidth
+ className={classes.textField}
+ value={name}
+ error={!!errorList.name}
+ helperText={errorList.name}
+ label={i18n.t("Name", { context: "category" })}
+ name="name"
+ onChange={onChange}
+ />
+ <TextField
+ fullWidth
+ multiline
+ value={description}
+ error={!!errorList.description}
+ helperText={
+ errorList.description || i18n.t("Optional", { context: "field" })
+ }
+ label={i18n.t("Description")}
+ name="description"
+ onChange={onChange}
+ />
+ </CardContent>
+ );
}
);
diff --git a/saleor/static/dashboard-next/category/components/CategoryDeleteDialog.tsx b/saleor/static/dashboard-next/category/components/CategoryDeleteDialog.tsx
index b7e5c61983..e59c54d136 100644
--- a/saleor/static/dashboard-next/category/components/CategoryDeleteDialog.tsx
+++ b/saleor/static/dashboard-next/category/components/CategoryDeleteDialog.tsx
@@ -53,17 +53,18 @@ const CategoryDeleteDialog = decorate<CategoryDeleteDialogProps>(props => {
)
}}
/>
- {productCount &&
- productCount > 0 && (
- <DialogContentText>
- {i18n.t(
- "There are {{count}} product(s) in this category that will also be removed.",
- {
- count: productCount
- }
- )}
- </DialogContentText>
- )}
+ {productCount && productCount > 0 ? (
+ <DialogContentText>
+ {i18n.t(
+ "There are {{count}} product(s) in this category that will also be removed.",
+ {
+ count: productCount
+ }
+ )}
+ </DialogContentText>
+ ) : (
+ undefined
+ )}
</DialogContent>
<DialogActions>
<Button onClick={onClose}>
diff --git a/saleor/static/dashboard-next/category/views/CategoryCreateForm.tsx b/saleor/static/dashboard-next/category/views/CategoryCreateForm.tsx
index 4eafe5d1b0..2b5bd6e741 100644
--- a/saleor/static/dashboard-next/category/views/CategoryCreateForm.tsx
+++ b/saleor/static/dashboard-next/category/views/CategoryCreateForm.tsx
@@ -2,8 +2,10 @@ import Card from "material-ui/Card";
import * as React from "react";
import { Redirect } from "react-router-dom";
+import Form, { FormActions, FormProps } from "../../components/Form";
import { NavigatorLink } from "../../components/Navigator";
import PageHeader from "../../components/PageHeader";
+import { CategoryCreateMutationVariables } from "../../gql-types";
import i18n from "../../i18n";
import BaseCategoryForm from "../components/BaseForm";
import { categoryShowUrl } from "../index";
@@ -12,6 +14,10 @@ import {
TypedCategoryCreateMutation
} from "../mutations";
+const CategoryForm: React.ComponentType<
+ FormProps<CategoryCreateMutationVariables>
+> = Form;
+
interface CategoryCreateFormProps {
parentId: string;
}
@@ -20,38 +26,58 @@ export const CategoryCreateForm: React.StatelessComponent<
CategoryCreateFormProps
> = ({ parentId }) => (
<TypedCategoryCreateMutation mutation={categoryCreateMutation}>
- {(mutate, { called, data, loading }) => {
- if (called && !loading && data.categoryCreate.errors.length === 0) {
+ {(mutate, { called, data: createResult, loading: createInProgress }) => {
+ if (
+ called &&
+ !createInProgress &&
+ createResult.categoryCreate.errors.length === 0
+ ) {
return (
<Redirect
- to={categoryShowUrl(data.categoryCreate.category.id)}
+ to={categoryShowUrl(createResult.categoryCreate.category.id)}
push={false}
/>
);
}
+ const errors =
+ called && !createInProgress ? createResult.categoryCreate.errors : [];
return (
<NavigatorLink to={categoryShowUrl(parentId)}>
{handleCancel => (
- <Card style={{ maxWidth: 750 }}>
- <PageHeader
- onCancel={handleCancel}
- title={i18n.t("Add category", { context: "title" })}
- />
- <BaseCategoryForm
- confirmButtonLabel={i18n.t("Add", { context: "button" })}
- description=""
- handleConfirm={formData =>
- mutate({
- variables: {
- ...formData,
- parentId
- }
- })
- }
- name=""
- errors={called && !loading ? data.categoryCreate.errors : []}
- />
- </Card>
+ <CategoryForm
+ initial={{
+ description: "",
+ name: "",
+ parentId
+ }}
+ onSubmit={data =>
+ mutate({
+ variables: data
+ })
+ }
+ >
+ {({ change, data, submit: handleSubmit }) => (
+ <Card style={{ maxWidth: 750 }}>
+ <PageHeader
+ onBack={handleCancel}
+ title={i18n.t("Add category", { context: "title" })}
+ />
+ <BaseCategoryForm
+ description={data.description}
+ errors={errors}
+ name={data.name}
+ onChange={change}
+ />
+ <FormActions
+ onCancel={handleCancel}
+ onSubmit={handleSubmit}
+ submitLabel={i18n.t("Save", {
+ context: "button"
+ })}
+ />
+ </Card>
+ )}
+ </CategoryForm>
)}
</NavigatorLink>
);
diff --git a/saleor/static/dashboard-next/category/views/CategoryUpdateForm.tsx b/saleor/static/dashboard-next/category/views/CategoryUpdateForm.tsx
index 025d0723e6..59a293a14f 100644
--- a/saleor/static/dashboard-next/category/views/CategoryUpdateForm.tsx
+++ b/saleor/static/dashboard-next/category/views/CategoryUpdateForm.tsx
@@ -1,11 +1,14 @@
import Card from "material-ui/Card";
import { CircularProgress } from "material-ui/Progress";
+import { withStyles } from "material-ui/styles";
import * as React from "react";
import { Redirect } from "react-router-dom";
import ErrorMessageCard from "../../components/ErrorMessageCard";
+import Form, { FormActions, FormProps } from "../../components/Form";
import { NavigatorLink } from "../../components/Navigator";
import PageHeader from "../../components/PageHeader";
+import { CategoryUpdateMutationVariables } from "../../gql-types";
import i18n from "../../i18n";
import BaseCategoryForm from "../components/BaseForm";
import { categoryShowUrl } from "../index";
@@ -15,68 +18,108 @@ import {
} from "../mutations";
import { categoryDetailsQuery, TypedCategoryDetailsQuery } from "../queries";
+const CategoryForm: React.ComponentType<
+ FormProps<CategoryUpdateMutationVariables>
+> = Form;
+
+const decorate = withStyles(theme => ({
+ root: {
+ marginBottom: theme.spacing.unit * 2,
+ [theme.breakpoints.up("sm")]: {
+ marginLeft: "auto",
+ marginRight: "auto",
+ maxWidth: theme.breakpoints.width("sm")
+ }
+ }
+}));
+
interface CategoryUpdateFormProps {
id: string;
}
-export const CategoryUpdateForm: React.StatelessComponent<
- CategoryUpdateFormProps
-> = ({ id }) => (
- <TypedCategoryDetailsQuery query={categoryDetailsQuery} variables={{ id }}>
- {({ data, loading, error }) => {
- if (error) {
- console.error(error.message);
- return <ErrorMessageCard message={error.message} />;
- }
- const { category } = data;
+export const CategoryUpdateForm = decorate<CategoryUpdateFormProps>(
+ ({ classes, id }) => (
+ <TypedCategoryDetailsQuery query={categoryDetailsQuery} variables={{ id }}>
+ {({ data, loading, error }) => {
+ if (error) {
+ console.error(error.message);
+ return <ErrorMessageCard message={error.message} />;
+ }
+ const { category } = data;
- return (
- <TypedCategoryUpdateMutation mutation={categoryUpdateMutation}>
- {(mutate, { called, data, loading }) => {
- if (called && !loading && data.categoryUpdate.errors.length === 0) {
+ return (
+ <TypedCategoryUpdateMutation mutation={categoryUpdateMutation}>
+ {(
+ mutate,
+ { called, data: updateResult, loading: updateInProgress }
+ ) => {
+ if (
+ called &&
+ !updateInProgress &&
+ updateResult.categoryUpdate.errors.length === 0
+ ) {
+ return (
+ <Redirect
+ to={categoryShowUrl(
+ updateResult.categoryUpdate.category.id
+ )}
+ />
+ );
+ }
+ const errors =
+ called && !updateInProgress
+ ? updateResult.categoryUpdate.errors
+ : [];
return (
- <Redirect
- to={categoryShowUrl(data.categoryUpdate.category.id)}
- />
- );
- }
- return (
- <NavigatorLink to={categoryShowUrl(id)}>
- {handleCancel => (
- <Card style={{ maxWidth: 750 }}>
- <PageHeader
- onCancel={handleCancel}
- title={i18n.t("Edit category", { context: "title" })}
- />
- {loading ? (
+ <NavigatorLink to={categoryShowUrl(id)}>
+ {handleCancel =>
+ loading ? (
<CircularProgress />
) : (
- <BaseCategoryForm
- name={category.name}
- description={category.description}
- handleConfirm={formData =>
+ <CategoryForm
+ initial={{
+ description: category.description,
+ id: category.id,
+ name: category.name
+ }}
+ onSubmit={data =>
mutate({
- variables: {
- ...formData,
- id
- }
+ variables: data
})
}
- confirmButtonLabel={i18n.t("Save", {
- context: "button"
- })}
- errors={
- called && !loading ? data.categoryUpdate.errors : []
- }
- />
- )}
- </Card>
- )}
- </NavigatorLink>
- );
- }}
- </TypedCategoryUpdateMutation>
- );
- }}
- </TypedCategoryDetailsQuery>
+ >
+ {({ change, data, submit: handleSubmit }) => (
+ <Card className={classes.root}>
+ <PageHeader
+ onBack={handleCancel}
+ title={i18n.t("Category details", {
+ context: "title"
+ })}
+ />
+ <BaseCategoryForm
+ description={data.description}
+ errors={errors}
+ name={data.name}
+ onChange={change}
+ />
+ <FormActions
+ onCancel={handleCancel}
+ onSubmit={handleSubmit}
+ submitLabel={i18n.t("Save", {
+ context: "button"
+ })}
+ />
+ </Card>
+ )}
+ </CategoryForm>
+ )
+ }
+ </NavigatorLink>
+ );
+ }}
+ </TypedCategoryUpdateMutation>
+ );
+ }}
+ </TypedCategoryDetailsQuery>
+ )
);
diff --git a/saleor/static/dashboard-next/components/Form/Form.tsx b/saleor/static/dashboard-next/components/Form/Form.tsx
new file mode 100644
index 0000000000..ba2cfa3fe7
--- /dev/null
+++ b/saleor/static/dashboard-next/components/Form/Form.tsx
@@ -0,0 +1,50 @@
+import * as React from "react";
+
+export interface FormProps<T extends {}> {
+ children:
+ | ((
+ props: {
+ data: T;
+ change(event: React.ChangeEvent<any>);
+ submit(event: React.FormEvent<any>);
+ }
+ ) => React.ReactElement<any>)
+ | React.ReactNode;
+ initial?: T;
+ onSubmit?(data: T);
+}
+
+class Form<T extends {} = {}> extends React.Component<FormProps<T>, T> {
+ state: T = this.props.initial;
+
+ handleChange = (event: React.ChangeEvent<any>) => {
+ const { target } = event;
+ this.setState({ [target.name]: target.value });
+ };
+
+ handleSubmit = (event: React.FormEvent<any>) => {
+ const { onSubmit } = this.props;
+ event.preventDefault();
+ if (onSubmit !== undefined) {
+ onSubmit(this.state);
+ }
+ };
+
+ render() {
+ const { children } = this.props;
+
+ let contents = children;
+
+ if (typeof children === "function") {
+ contents = children({
+ change: this.handleChange,
+ data: this.state,
+ submit: this.handleSubmit
+ });
+ }
+
+ return <form onSubmit={this.handleSubmit}>{contents}</form>;
+ }
+}
+
+export default Form;
diff --git a/saleor/static/dashboard-next/components/Form/FormActions.tsx b/saleor/static/dashboard-next/components/Form/FormActions.tsx
new file mode 100644
index 0000000000..eef483e4f2
--- /dev/null
+++ b/saleor/static/dashboard-next/components/Form/FormActions.tsx
@@ -0,0 +1,35 @@
+import Button from "material-ui/Button";
+import { withStyles } from "material-ui/styles";
+import Toolbar from "material-ui/Toolbar";
+import * as React from "react";
+
+import i18n from "../../i18n";
+
+const decorate = withStyles(theme => ({
+ cardActions: {
+ flexDirection: "row-reverse" as "row-reverse"
+ }
+}));
+
+interface FormActionsProps {
+ submitLabel: string;
+ onCancel?();
+ onSubmit?(event: React.FormEvent<any>);
+}
+
+const FormActions = decorate<FormActionsProps>(
+ ({ children, classes, onCancel, onSubmit, submitLabel }) => (
+ <Toolbar className={classes.cardActions}>
+ <Button variant="raised" color="primary" onClick={onSubmit} type="submit">
+ {submitLabel}
+ </Button>
+ {onCancel && (
+ <Button onClick={onCancel}>
+ {i18n.t("Cancel", { context: "button" })}
+ </Button>
+ )}
+ </Toolbar>
+ )
+);
+
+export default FormActions;
diff --git a/saleor/static/dashboard-next/components/Form/index.ts b/saleor/static/dashboard-next/components/Form/index.ts
new file mode 100644
index 0000000000..dd177d39a4
--- /dev/null
+++ b/saleor/static/dashboard-next/components/Form/index.ts
@@ -0,0 +1,4 @@
+export { default } from "./Form";
+export * from "./Form";
+export { default as FormActions } from "./FormActions";
+export * from "./FormActions";
diff --git a/saleor/static/dashboard-next/components/PageHeader.tsx b/saleor/static/dashboard-next/components/PageHeader.tsx
index 2b5a75f10e..39f0498231 100644
--- a/saleor/static/dashboard-next/components/PageHeader.tsx
+++ b/saleor/static/dashboard-next/components/PageHeader.tsx
@@ -38,11 +38,10 @@ const decorate = withStyles(theme => ({
interface PageHeaderProps {
title: string;
onBack?();
- onCancel?();
}
const PageHeader = decorate<PageHeaderProps>(
- ({ children, classes, onBack, onCancel, title }) => (
+ ({ children, classes, onBack, title }) => (
<div className={classes.root}>
{onBack && (
<IconButton
@@ -53,15 +52,6 @@ const PageHeader = decorate<PageHeaderProps>(
<ArrowBackIcon />
</IconButton>
)}
- {onCancel && (
- <IconButton
- color="inherit"
- className={classes.menuButton}
- onClick={onCancel}
- >
- <CloseIcon />
- </IconButton>
- )}
<Typography className={classes.title} variant="title">
{title !== undefined ? title : <Skeleton style={{ width: "10em" }} />}
</Typography>
diff --git a/saleor/static/dashboard-next/page/views/PageCreateForm.tsx b/saleor/static/dashboard-next/page/views/PageCreateForm.tsx
index fb0bbbf19a..555800f64b 100644
--- a/saleor/static/dashboard-next/page/views/PageCreateForm.tsx
+++ b/saleor/static/dashboard-next/page/views/PageCreateForm.tsx
@@ -29,7 +29,7 @@ export const PageCreateForm: React.StatelessComponent<PageCreateFormProps> = ({
{handleCancel => (
<Card>
<PageHeader
- onCancel={handleCancel}
+ onBack={handleCancel}
title={i18n.t("Add page", { context: "title" })}
/>
<PageBaseForm
diff --git a/saleor/static/dashboard-next/page/views/PageUpdateForm.tsx b/saleor/static/dashboard-next/page/views/PageUpdateForm.tsx
index 554cfb406b..8e4e3bc0b3 100644
--- a/saleor/static/dashboard-next/page/views/PageUpdateForm.tsx
+++ b/saleor/static/dashboard-next/page/views/PageUpdateForm.tsx
@@ -67,105 +67,101 @@ export class PageUpdateForm extends React.Component<
title: page.title
};
return (
- <Card>
- <TypedPageDeleteMutation mutation={pageDeleteMutation}>
- {(
- deletePage,
- { called, data, error, loading: deleteInProgress }
- ) => {
- if (called && !deleteInProgress) {
- if (error) {
- console.error(error);
- return;
- }
- if (data && data.pageDelete.errors.length) {
- return;
- }
- // FIXME: component is loaded with previous state (meaning that delete d page will still be there until table reload)
- this.handleRemoveButtonClick();
- return <Redirect to="/pages/" />;
+ <TypedPageDeleteMutation mutation={pageDeleteMutation}>
+ {(
+ deletePage,
+ { called, data, error, loading: deleteInProgress }
+ ) => {
+ if (called && !deleteInProgress) {
+ if (error) {
+ console.error(error);
+ return;
}
- return (
- <TypedPageUpdateMutation mutation={pageUpdateMutation}>
- {(
- updatePage,
- { called, data, error, loading: updateInProgress }
- ) => {
- if (
- called &&
- !updateInProgress &&
- !data.pageUpdate.errors.length
- ) {
- if (error) {
- console.error(error);
- return;
- }
- return <Redirect to="/pages/" />;
+ if (data && data.pageDelete.errors.length) {
+ return;
+ }
+ // FIXME: component is loaded with previous state (meaning that delete d page will still be there until table reload)
+ this.handleRemoveButtonClick();
+ return <Redirect to="/pages/" />;
+ }
+ return (
+ <TypedPageUpdateMutation mutation={pageUpdateMutation}>
+ {(
+ updatePage,
+ { called, data, error, loading: updateInProgress }
+ ) => {
+ if (
+ called &&
+ !updateInProgress &&
+ !data.pageUpdate.errors.length
+ ) {
+ if (error) {
+ console.error(error);
+ return;
}
- return (
- <NavigatorLink to={"/pages/"}>
- {handleCancel => (
- <>
- <PageHeader
- onCancel={handleCancel}
- title={i18n.t("Edit page", {
- context: "title"
- })}
+ return <Redirect to="/pages/" />;
+ }
+ return (
+ <NavigatorLink to={"/pages/"}>
+ {handleCancel => (
+ <Card>
+ <PageHeader
+ onBack={handleCancel}
+ title={i18n.t("Page details", {
+ context: "title"
+ })}
+ >
+ <IconButton
+ onClick={this.handleRemoveButtonClick}
>
- <IconButton
- onClick={this.handleRemoveButtonClick}
- >
- <DeleteIcon />
- </IconButton>
- </PageHeader>
- {loading ? (
- <CircularProgress />
- ) : (
- <>
- <PageBaseForm
- handleSubmit={data =>
- updatePage({
- variables: { id, ...data }
- })
- }
- formInitialValues={formInitialValues}
- created={page.created}
- errors={
- data
- ? data.pageUpdate.errors
- : undefined
+ <DeleteIcon />
+ </IconButton>
+ </PageHeader>
+ {loading ? (
+ <CircularProgress />
+ ) : (
+ <>
+ <PageBaseForm
+ handleSubmit={data =>
+ updatePage({
+ variables: { id, ...data }
+ })
+ }
+ formInitialValues={formInitialValues}
+ created={page.created}
+ errors={
+ data ? data.pageUpdate.errors : undefined
+ }
+ />
+ {!loading ? (
+ <PageDeleteDialog
+ onClose={this.handleRemoveButtonClick}
+ onConfirm={() =>
+ deletePage({ variables: { id } })
}
- />
- {!loading ? (
- <PageDeleteDialog
- onClose={this.handleRemoveButtonClick}
- onConfirm={() =>
- deletePage({ variables: { id } })
- }
- opened={this.state.opened}
- >
- <DialogContentText
- dangerouslySetInnerHTML={{
- __html: i18n.t(
- "Are you sure you want to remove <strong>{{name}}</strong>?",
- { name: page.title }
- )
- }}
- />
- </PageDeleteDialog>
- ) : null}
- </>
- )}
- </>
- )}
- </NavigatorLink>
- );
- }}
- </TypedPageUpdateMutation>
- );
- }}
- </TypedPageDeleteMutation>
- </Card>
+ opened={this.state.opened}
+ >
+ <DialogContentText
+ dangerouslySetInnerHTML={{
+ __html: i18n.t(
+ "Are you sure you want to remove <strong>{{name}}</strong>?",
+ { name: page.title }
+ )
+ }}
+ />
+ </PageDeleteDialog>
+ ) : null}
+ </>
+ )}
+ </Card>
+ )}
+ </NavigatorLink>
+ );
+ }}
+ </TypedPageUpdateMutation>
+ );
+ }}
+ </TypedPageDeleteMutation>
);
}}
</TypedPageDetailsQuery>