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

[Rating] Clear value if selected value is clicked #18999

Merged
merged 3 commits into from
Dec 30, 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
1 change: 1 addition & 0 deletions docs/pages/api/rating.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ You can learn more about the difference by [reading this guide](/guides/minimizi
| <span class="prop-name">classes</span> | <span class="prop-type">object</span> | | Override or extend the styles applied to the component. See [CSS API](#css) below for more details. |
| <span class="prop-name">disabled</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | If `true`, the rating will be disabled. |
| <span class="prop-name">emptyIcon</span> | <span class="prop-type">node</span> | | The icon to display when empty. |
| <span class="prop-name">emptyLabelText</span> | <span class="prop-type">node</span> | <span class="prop-default">'Empty'</span> | The label read when the rating input is empty. |
| <span class="prop-name">getLabelText</span> | <span class="prop-type">func</span> | <span class="prop-default">function defaultLabelText(value) { return `${value} Star${value !== 1 ? 's' : ''}`;}</span> | Accepts a function which returns a string value that provides a user-friendly name for the current value of the rating.<br>For localization purposes, you can use the provided [translations](/guides/localization/).<br><br>**Signature:**<br>`function(value: number) => string`<br>*value:* The rating label's value to format. |
| <span class="prop-name">icon</span> | <span class="prop-type">node</span> | <span class="prop-default">&lt;Star fontSize="inherit" /></span> | The icon to display. |
| <span class="prop-name">IconContainerComponent</span> | <span class="prop-type">elementType</span> | <span class="prop-default">function IconContainer(props) { const { value, ...other } = props; return &lt;span {...other} />;}</span> | The component containing the icon. |
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/components/rating/SimpleRating.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';

export default function SimpleRating() {
const [value, setValue] = React.useState(2);
const [value, setValue] = React.useState<number | null>(2);

return (
<div>
Expand Down
2 changes: 1 addition & 1 deletion packages/material-ui-lab/src/Rating/Rating.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export interface RatingProps
IconContainerComponent?: React.ElementType<IconContainerProps>;
max?: number;
name?: string;
onChange?: (event: React.ChangeEvent<{}>, value: number) => void;
onChange?: (event: React.ChangeEvent<{}>, value: number | null) => void;
onChangeActive?: (event: React.ChangeEvent<{}>, value: number) => void;
precision?: number;
readOnly?: boolean;
Expand Down
49 changes: 38 additions & 11 deletions packages/material-ui-lab/src/Rating/Rating.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ function getDecimalPrecision(num) {
}

function roundValueToPrecision(value, precision) {
if (value == null) {
return value;
}

const nearest = Math.round(value / precision) * precision;
return Number(nearest.toFixed(getDecimalPrecision(precision)));
}
Expand Down Expand Up @@ -134,6 +138,7 @@ const Rating = React.forwardRef(function Rating(props, ref) {
className,
disabled = false,
emptyIcon,
emptyLabelText = 'Empty',
getLabelText = defaultLabelText,
icon = defaultIcon,
IconContainerComponent = IconContainer,
Expand All @@ -146,7 +151,7 @@ const Rating = React.forwardRef(function Rating(props, ref) {
precision = 1,
readOnly = false,
size = 'medium',
value: valueProp2 = null,
value: valueProp = null,
...other
} = props;

Expand All @@ -159,14 +164,14 @@ const Rating = React.forwardRef(function Rating(props, ref) {
setDefaultName(`mui-rating-${Math.round(Math.random() * 1e5)}`);
}, []);

const valueProp = roundValueToPrecision(valueProp2, precision);
const valueRounded = roundValueToPrecision(valueProp, precision);
const theme = useTheme();
const [{ hover, focus }, setState] = React.useState({
hover: -1,
focus: -1,
});

let value = valueProp;
let value = valueRounded;
if (hover !== -1) {
value = hover;
}
Expand All @@ -188,7 +193,7 @@ const Rating = React.forwardRef(function Rating(props, ref) {

const rootNode = rootRef.current;
const { right, left } = rootNode.getBoundingClientRect();
const { width } = rootNode.firstChild.getBoundingClientRect();
const { width } = rootNode.querySelector(`.${classes.label}`).getBoundingClientRect();
let percent;

if (theme.direction === 'rtl') {
Expand Down Expand Up @@ -238,6 +243,23 @@ const Rating = React.forwardRef(function Rating(props, ref) {
}
};

const handleClear = event => {
// Ignore keyboard events
// https://github.com/facebook/react/issues/7407
if (event.clientX === 0 && event.clientY === 0) {
return;
}

setState({
hover: -1,
focus: -1,
});

if (onChange && parseFloat(event.target.value) === valueRounded) {
onChange(event, null);
}
};

const handleFocus = event => {
if (isFocusVisible(event)) {
setFocusVisible(true);
Expand Down Expand Up @@ -306,6 +328,7 @@ const Rating = React.forwardRef(function Rating(props, ref) {
onFocus={handleFocus}
onBlur={handleBlur}
onChange={handleChange}
onClick={handleClear}
value={propsItem.value}
id={id}
type="radio"
Expand Down Expand Up @@ -336,18 +359,18 @@ const Rating = React.forwardRef(function Rating(props, ref) {
aria-label={readOnly ? getLabelText(value) : null}
{...other}
>
{!readOnly && !disabled && value == null && (
{!readOnly && !disabled && valueRounded == null && (
<React.Fragment>
<input
value="0"
id={`${name}-0`}
value=""
id={`${name}-empty`}
type="radio"
name={name}
defaultChecked
className={classes.visuallyhidden}
/>
<label htmlFor={`${name}-0`} className={classes.pristine}>
<span className={classes.visuallyhidden}>{getLabelText(0)}</span>
<label className={classes.pristine} htmlFor={`${name}-empty`}>
<span className={classes.visuallyhidden}>{emptyLabelText}</span>
</label>
</React.Fragment>
)}
Expand Down Expand Up @@ -390,7 +413,7 @@ const Rating = React.forwardRef(function Rating(props, ref) {
filled: itemDecimalValue <= value,
hover: itemDecimalValue <= hover,
focus: itemDecimalValue <= focus,
checked: itemDecimalValue === valueProp,
checked: itemDecimalValue === valueRounded,
},
);
})}
Expand All @@ -407,7 +430,7 @@ const Rating = React.forwardRef(function Rating(props, ref) {
filled: itemValue <= value,
hover: itemValue <= hover,
focus: itemValue <= focus,
checked: itemValue === valueProp,
checked: itemValue === valueRounded,
},
);
})}
Expand All @@ -433,6 +456,10 @@ Rating.propTypes = {
* The icon to display when empty.
*/
emptyIcon: PropTypes.node,
/**
* The label read when the rating input is empty.
Copy link
Member

@mbrookes mbrookes Dec 28, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* The label read when the rating input is empty.
* The label read by a screen reader when the rating input is empty.

?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"You do not have permission to push to this repository."

*/
emptyLabelText: PropTypes.node,
/**
* Accepts a function which returns a string value that provides a user-friendly name for the current value of the rating.
*
Expand Down
34 changes: 33 additions & 1 deletion packages/material-ui-lab/src/Rating/Rating.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import { expect } from 'chai';
import { stub } from 'sinon';
import { stub, spy } from 'sinon';
import { createMount, getClasses } from '@material-ui/core/test-utils';
import describeConformance from '@material-ui/core/test-utils/describeConformance';
import { createClientRender, fireEvent } from 'test/utils/createClientRender';
Expand Down Expand Up @@ -66,4 +66,36 @@ describe('<Rating />', () => {
});
expect(container.querySelectorAll(`.${classes.iconHover}`).length).to.equal(2);
});

it('should clear the rating', () => {
const handleChange = spy();
const { getByLabelText } = render(<Rating {...defaultProps} onChange={handleChange} />);

const input = getByLabelText('2 Stars');
fireEvent.click(input, {
clientX: 1,
});

expect(handleChange.callCount).to.equal(1);
expect(handleChange.args[0][1]).to.deep.equal(null);
});

it('should select the rating', () => {
const handleChange = spy();
const { getByLabelText } = render(<Rating {...defaultProps} onChange={handleChange} />);

const input = getByLabelText('3 Stars');
fireEvent.click(input);

expect(handleChange.callCount).to.equal(1);
expect(handleChange.args[0][1]).to.deep.equal(3);
});

it('should select the empty input if value is null', () => {
const { container, getByLabelText } = render(<Rating {...defaultProps} value={null} />);
const input = getByLabelText('Empty');
const checked = container.querySelector('input[name="rating-test"]:checked');
expect(input).to.equal(checked);
expect(input.value).to.equal('');
});
});
22 changes: 22 additions & 0 deletions packages/material-ui/src/locale/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const azAZ = {

return `${value} ${pluralForm}`;
},
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Silmək',
Expand Down Expand Up @@ -46,6 +47,7 @@ export const csCZ = {
}
return `${value} hvězdiček`;
},
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Vymazat',
Expand All @@ -67,6 +69,7 @@ export const deDE = {
},
MuiRating: {
getLabelText: value => `${value} ${value !== 1 ? 'Sterne' : 'Stern'}`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Leeren',
Expand All @@ -91,6 +94,7 @@ export const enUS = {};
},
MuiRating: {
getLabelText: value => `${value} Star${value !== 1 ? 's' : ''}`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Clear',
Expand All @@ -112,6 +116,7 @@ export const esES = {
},
MuiRating: {
getLabelText: value => `${value} Estrella${value !== 1 ? 's' : ''}`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Limpiar',
Expand All @@ -133,6 +138,7 @@ export const faIR = {
},
MuiRating: {
getLabelText: value => `${value} ستاره`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'پاک‌کردن',
Expand All @@ -154,6 +160,7 @@ export const frFR = {
},
MuiRating: {
getLabelText: value => `${value} Etoile${value !== 1 ? 's' : ''}`,
emptyLabelText: 'Vide',
},
MuiAutocomplete: {
clearText: 'Vider',
Expand All @@ -176,6 +183,7 @@ export const idID = {
},
MuiRating: {
getLabelText: value => `${value} Bintang`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Hapus',
Expand All @@ -197,6 +205,7 @@ export const itIT = {
},
MuiRating: {
getLabelText: value => `${value} Stell${value !== 1 ? 'a' : 'e'}`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Svuota',
Expand All @@ -218,6 +227,7 @@ export const jaJP = {
},
MuiRating: {
getLabelText: value => `${value} ${value !== 1 ? '出演者' : '星'}`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'クリア',
Expand All @@ -239,6 +249,7 @@ export const koKR = {
},
MuiRating: {
getLabelText: value => `${value} 점`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: '지우기',
Expand All @@ -260,6 +271,7 @@ export const nlNL = {
},
MuiRating: {
getLabelText: value => `${value} Ster${value !== 1 ? 'ren' : ''}`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Wissen',
Expand Down Expand Up @@ -292,6 +304,7 @@ export const plPL = {

return `${value} ${pluralForm}`;
},
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Wyczyść',
Expand All @@ -313,6 +326,7 @@ export const ptBR = {
},
MuiRating: {
getLabelText: value => `${value} Estrela${value !== 1 ? 's' : ''}`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Limpar',
Expand All @@ -334,6 +348,7 @@ export const ptPT = {
},
MuiRating: {
getLabelText: value => `${value} Estrela${value !== 1 ? 's' : ''}`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Limpar',
Expand All @@ -355,6 +370,7 @@ export const roRO = {
},
MuiRating: {
getLabelText: value => `${value} St${value !== 1 ? 'ele' : 'ea'}`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Șterge',
Expand Down Expand Up @@ -387,6 +403,7 @@ export const ruRU = {

return `${value} ${pluralForm}`;
},
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Очистить',
Expand Down Expand Up @@ -416,6 +433,7 @@ export const skSK = {
}
return `${value} hviezdičiek`;
},
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Vymazať',
Expand All @@ -437,6 +455,7 @@ export const svSE = {
},
MuiRating: {
getLabelText: value => `${value} ${value !== 1 ? 'Stjärnor' : 'Stjärna'}`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Rensa',
Expand All @@ -459,6 +478,7 @@ export const trTR = {
},
MuiRating: {
getLabelText: value => `${value} Yıldız`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Temizle',
Expand Down Expand Up @@ -491,6 +511,7 @@ export const ukUA = {

return `${value} ${pluralForm}`;
},
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: 'Очистити',
Expand All @@ -512,6 +533,7 @@ export const zhCN = {
},
MuiRating: {
getLabelText: value => `${value} 星${value !== 1 ? '星' : ''}`,
emptyLabelText: 'Empty',
},
MuiAutocomplete: {
clearText: '明确',
Expand Down