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

[RFR] Convert CheckboxGroupInput to use useInput #3502

Merged
merged 1 commit into from
Aug 12, 2019
Merged
Show file tree
Hide file tree
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
242 changes: 95 additions & 147 deletions packages/ra-ui-materialui/src/input/CheckboxGroupInput.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,25 @@
import React, { Component } from 'react';
import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import get from 'lodash/get';
import FormLabel from '@material-ui/core/FormLabel';
import FormControl from '@material-ui/core/FormControl';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormHelperText from '@material-ui/core/FormHelperText';
import Checkbox from '@material-ui/core/Checkbox';
import { withStyles, createStyles } from '@material-ui/core/styles';
import compose from 'recompose/compose';
import { addField, translate, FieldTitle } from 'ra-core';
import { makeStyles } from '@material-ui/core/styles';
import { FieldTitle, useInput } from 'ra-core';

import defaultSanitizeRestProps from './sanitizeRestProps';
import CheckboxGroupInputItem from './CheckboxGroupInputItem';

const sanitizeRestProps = ({ setFilter, setPagination, setSort, ...rest }) =>
defaultSanitizeRestProps(rest);

const styles = theme =>
createStyles({
root: {},
label: {
transform: 'translate(0, 1.5px) scale(0.75)',
transformOrigin: `top ${
theme.direction === 'ltr' ? 'left' : 'right'
}`,
},
checkbox: {
height: 32,
},
});
const useStyles = makeStyles(theme => ({
root: {},
label: {
transform: 'translate(0, 1.5px) scale(0.75)',
transformOrigin: `top ${theme.direction === 'ltr' ? 'left' : 'right'}`,
},
}));

/**
* An Input component for a checkbox group, using an array of objects for the options
Expand Down Expand Up @@ -91,160 +83,116 @@ const styles = theme =>
*
* The object passed as `options` props is passed to the material-ui <Checkbox> components
*/
export class CheckboxGroupInput extends Component {
handleCheck = (event, isChecked) => {
const {
input: { value, onChange },
} = this.props;
let newValue;
try {
// try to convert string value to number, e.g. '123'
newValue = JSON.parse(event.target.value);
} catch (e) {
// impossible to convert value, e.g. 'abc'
newValue = event.target.value;
}
if (isChecked) {
onChange([...(value || []), ...[newValue]]);
} else {
onChange(value.filter(v => v != newValue)); // eslint-disable-line eqeqeq
}
};

renderCheckbox = choice => {
const {
id,
input: { value },
optionText,
optionValue,
options,
translate,
translateChoice,
classes,
} = this.props;

const choiceName = React.isValidElement(optionText)
? React.cloneElement(optionText, { record: choice })
: typeof optionText === 'function'
? optionText(choice)
: get(choice, optionText);

return (
<FormControlLabel
htmlFor={`${id}_${get(choice, optionValue)}`}
key={get(choice, optionValue)}
checked={
value
? value.find(v => v == get(choice, optionValue)) !== // eslint-disable-line eqeqeq
undefined
: false
}
onChange={this.handleCheck}
value={String(get(choice, optionValue))}
control={
<Checkbox
id={`${id}_${get(choice, optionValue)}`}
color="primary"
className={classes.checkbox}
{...options}
/>
}
label={
translateChoice
? translate(choiceName, { _: choiceName })
: choiceName
}
/>
);
};
const CheckboxGroupInput = ({
choices,
helperText,
label,
onBlur,
onChange,
onFocus,
optionText,
optionValue,
options,
resource,
source,
translate,
translateChoice,
validate,
...rest
}) => {
const classes = useStyles();

render() {
const {
choices,
className,
classes = {},
isRequired,
label,
meta,
resource,
source,
input,
...rest
} = this.props;
if (typeof meta === 'undefined') {
throw new Error(
"The CheckboxGroupInput component wasn't called within a react-final-form <Field>. Did you decorate it and forget to add the addField prop to your component? See https://marmelab.com/react-admin/Inputs.html#writing-your-own-input-component for details."
);
}
const {
id,
input: { onChange: finalFormOnChange, onBlur: finalFormOnBlur, value },
isRequired,
meta: { error, touched },
} = useInput({
onBlur,
onChange,
onFocus,
resource,
source,
validate,
});

const { touched, error, helperText = false } = meta;
const handleCheck = useCallback(
(event, isChecked) => {
let newValue;
try {
// try to convert string value to number, e.g. '123'
newValue = JSON.parse(event.target.value);
} catch (e) {
// impossible to convert value, e.g. 'abc'
newValue = event.target.value;
}
if (isChecked) {
finalFormOnChange([...(value || []), ...[newValue]]);
} else {
finalFormOnChange(value.filter(v => v != newValue)); // eslint-disable-line eqeqeq
Kmaschta marked this conversation as resolved.
Show resolved Hide resolved
}
finalFormOnBlur(); // HACK: See https://github.com/final-form/react-final-form/issues/365#issuecomment-515045503
},
[finalFormOnChange, finalFormOnBlur, value]
);

return (
<FormControl
className={className}
component="fieldset"
margin="normal"
{...sanitizeRestProps(rest)}
>
<FormLabel component="legend" className={classes.label}>
<FieldTitle
label={label}
source={source}
resource={resource}
isRequired={isRequired}
return (
<FormControl
component="fieldset"
margin="normal"
{...sanitizeRestProps(rest)}
>
<FormLabel component="legend" className={classes.label}>
<FieldTitle
label={label}
source={source}
resource={resource}
isRequired={isRequired}
/>
</FormLabel>
<FormGroup row>
{choices.map(choice => (
<CheckboxGroupInputItem
choice={choice}
id={id}
onChange={handleCheck}
options={options}
optionText={optionText}
optionValue={optionValue}
translateChoice={translateChoice}
value={value}
/>
</FormLabel>
<FormGroup row>{choices.map(this.renderCheckbox)}</FormGroup>
{touched && error && (
<FormHelperText error>{error}</FormHelperText>
)}
{helperText && <FormHelperText>{helperText}</FormHelperText>}
</FormControl>
);
}
}
))}
</FormGroup>
{touched && error && <FormHelperText error>{error}</FormHelperText>}
{helperText && <FormHelperText>{helperText}</FormHelperText>}
</FormControl>
);
};

CheckboxGroupInput.propTypes = {
choices: PropTypes.arrayOf(PropTypes.object),
classes: PropTypes.object,
className: PropTypes.string,
label: PropTypes.string,
source: PropTypes.string,
options: PropTypes.object,
id: PropTypes.string,
input: PropTypes.shape({
onChange: PropTypes.func.isRequired,
Kmaschta marked this conversation as resolved.
Show resolved Hide resolved
}),
isRequired: PropTypes.bool,
optionText: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
PropTypes.element,
]).isRequired,
optionValue: PropTypes.string.isRequired,
resource: PropTypes.string,
translate: PropTypes.func.isRequired,
translateChoice: PropTypes.bool.isRequired,
meta: PropTypes.object,
};

CheckboxGroupInput.defaultProps = {
choices: [],
classes: {},
options: {},
optionText: 'name',
optionValue: 'id',
translateChoice: true,
};

const EnhancedCheckboxGroupInput = compose(
addField,
translate,
withStyles(styles)
)(CheckboxGroupInput);

EnhancedCheckboxGroupInput.defaultProps = {
fullWidth: true,
};

export default EnhancedCheckboxGroupInput;
export default CheckboxGroupInput;
Loading