Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert SimpleFormIterator to function component #4450

Merged
merged 8 commits into from
Mar 4, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
317 changes: 151 additions & 166 deletions packages/ra-ui-materialui/src/form/SimpleFormIterator.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,20 @@
import React, {
Children,
cloneElement,
Component,
isValidElement,
} from 'react';
import React, { Children, cloneElement, isValidElement, useRef } from 'react';
import PropTypes from 'prop-types';
import compose from 'recompose/compose';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import get from 'lodash/get';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import FormHelperText from '@material-ui/core/FormHelperText';
import { withStyles, createStyles } from '@material-ui/core/styles';
import { makeStyles } from '@material-ui/core/styles';
import CloseIcon from '@material-ui/icons/RemoveCircleOutline';
import AddIcon from '@material-ui/icons/AddCircleOutline';
import { translate, ValidationError } from 'ra-core';
import { useTranslate, ValidationError } from 'ra-core';
import classNames from 'classnames';

import FormInput from '../form/FormInput';

const styles = theme =>
createStyles({
const useStyles = makeStyles(
theme => ({
root: {
padding: 0,
marginBottom: 0,
Expand Down Expand Up @@ -64,177 +58,171 @@ const styles = theme =>
leftIcon: {
marginRight: theme.spacing(1),
},
});
}),
{ name: 'RaSimpleFormIterator' }
);

export class SimpleFormIterator extends Component {
constructor(props) {
super(props);
// we need a unique id for each field for a proper enter/exit animation
// but redux-form doesn't provide one (cf https://github.com/erikras/redux-form/issues/2735)
// so we keep an internal map between the field position and an auto-increment id
this.nextId = props.fields.length
? props.fields.length
: props.defaultValue
? props.defaultValue.length
: 0;
const SimpleFormIterator = ({
basePath,
classes: classesOverride,
children,
fields,
meta: { error, submitFailed },
record,
resource,
source,
disableAdd,
disableRemove,
variant,
margin,
TransitionProps,
defaultValue,
}) => {
const translate = useTranslate();
const classes = useStyles({ classes: classesOverride });

// We check whether we have a defaultValue (which must be an array) before checking
// the fields prop which will always be empty for a new record.
// Without it, our ids wouldn't match the default value and we would get key warnings
// on the CssTransition element inside our render method
this.ids = this.nextId > 0 ? Array.from(Array(this.nextId).keys()) : [];
}
// We need a unique id for each field for a proper enter/exit animation
// so we keep an internal map between the field position and an auto-increment id
const nextId = useRef(
fields && fields.length
? fields.length
: defaultValue
? defaultValue.length
: 0
);

removeField = index => () => {
const { fields } = this.props;
this.ids.splice(index, 1);
// We check whether we have a defaultValue (which must be an array) before checking
// the fields prop which will always be empty for a new record.
// Without it, our ids wouldn't match the default value and we would get key warnings
// on the CssTransition element inside our render method
const ids = useRef(nextId > 0 ? Array.from(Array(nextId).keys()) : []);

const removeField = index => () => {
ids.current.splice(index, 1);
fields.remove(index);
};

// Returns a boolean to indicate whether to disable the remove button for certain fields.
// If disableRemove is a function, then call the function with the current record to
// determining if the button should be disabled. Otherwise, use a boolean property that
// enables or disables the button for all of the fields.
disableRemoveField = (record, disableRemove) => {
const disableRemoveField = (record, disableRemove) => {
if (typeof disableRemove === 'boolean') {
return disableRemove;
}
return disableRemove && disableRemove(record);
};

addField = () => {
const { fields } = this.props;
this.ids.push(this.nextId++);
const addField = () => {
ids.current.push(nextId.current++);
fields.push({});
};

render() {
const {
basePath,
classes = {},
children,
fields,
meta: { error, submitFailed },
record,
resource,
source,
translate,
disableAdd,
disableRemove,
variant,
margin,
TransitionProps,
} = this.props;
const records = get(record, source);
return fields ? (
<ul className={classes.root}>
{submitFailed && typeof error !== 'object' && error && (
<FormHelperText error>
<ValidationError error={error} />
</FormHelperText>
)}
<TransitionGroup component={null}>
{fields.map((member, index) => (
<CSSTransition
key={this.ids[index]}
timeout={500}
classNames="fade"
{...TransitionProps}
>
<li className={classes.line}>
<Typography
variant="body1"
className={classes.index}
>
{index + 1}
</Typography>
<section className={classes.form}>
{Children.map(children, (input, index2) =>
isValidElement(input) ? (
<FormInput
basePath={
input.props.basePath ||
basePath
}
input={cloneElement(input, {
source: input.props.source
? `${member}.${
input.props.source
}`
: member,
index: input.props.source
? undefined
: index2,
label:
typeof input.props
.label ===
'undefined'
? input.props.source
? `resources.${resource}.fields.${
input
.props
.source
}`
: undefined
: input.props.label,
})}
record={
(records &&
records[index]) ||
{}
}
resource={resource}
variant={variant}
margin={margin}
/>
) : null
)}
</section>
{!this.disableRemoveField(
(records && records[index]) || {},
disableRemove
) && (
<span className={classes.action}>
<Button
className={classNames(
'button-remove',
`button-remove-${source}-${index}`
)}
size="small"
onClick={this.removeField(index)}
>
<CloseIcon
className={classes.leftIcon}
/>
{translate('ra.action.remove')}
</Button>
</span>
)}
</li>
</CSSTransition>
))}
</TransitionGroup>
{!disableAdd && (
<li className={classes.line}>
<span className={classes.action}>
<Button
className={classNames(
'button-add',
`button-add-${source}`
)}
size="small"
onClick={this.addField}
const records = get(record, source);
return fields ? (
<ul className={classes.root}>
{submitFailed && typeof error !== 'object' && error && (
<FormHelperText error>
<ValidationError error={error} />
</FormHelperText>
)}
<TransitionGroup component={null}>
{fields.map((member, index) => (
<CSSTransition
key={ids.current[index]}
timeout={500}
classNames="fade"
{...TransitionProps}
>
<li className={classes.line}>
<Typography
variant="body1"
className={classes.index}
>
<AddIcon className={classes.leftIcon} />
{translate('ra.action.add')}
</Button>
</span>
</li>
)}
</ul>
) : null;
}
}
{index + 1}
</Typography>
<section className={classes.form}>
{Children.map(children, (input, index2) =>
isValidElement(input) ? (
<FormInput
basePath={
input.props.basePath || basePath
}
input={cloneElement(input, {
source: input.props.source
? `${member}.${
input.props.source
}`
: member,
index: input.props.source
? undefined
: index2,
label:
typeof input.props.label ===
'undefined'
? input.props.source
? `resources.${resource}.fields.${
input.props
.source
}`
: undefined
: input.props.label,
})}
record={
(records && records[index]) ||
{}
}
resource={resource}
variant={variant}
margin={margin}
/>
) : null
)}
</section>
{!disableRemoveField(
(records && records[index]) || {},
disableRemove
) && (
<span className={classes.action}>
<Button
className={classNames(
'button-remove',
`button-remove-${source}-${index}`
)}
size="small"
onClick={removeField(index)}
>
<CloseIcon
className={classes.leftIcon}
/>
{translate('ra.action.remove')}
</Button>
</span>
)}
</li>
</CSSTransition>
))}
</TransitionGroup>
{!disableAdd && (
<li className={classes.line}>
<span className={classes.action}>
<Button
className={classNames(
'button-add',
`button-add-${source}`
)}
size="small"
onClick={addField}
>
<AddIcon className={classes.leftIcon} />
{translate('ra.action.add')}
</Button>
</span>
</li>
)}
</ul>
) : null;
};

SimpleFormIterator.defaultProps = {
disableAdd: false,
Expand All @@ -258,7 +246,4 @@ SimpleFormIterator.propTypes = {
TransitionProps: PropTypes.shape({}),
};

export default compose(
translate,
withStyles(styles)
)(SimpleFormIterator);
export default SimpleFormIterator;