Skip to content

Commit

Permalink
[@mantine/core] NumberInput: Fix incorrect allowNegative handling w…
Browse files Browse the repository at this point in the history
…ith up/down arrows (#6170)
  • Loading branch information
AustinWildgrube committed May 8, 2024
1 parent eb755c5 commit 3c8ca0d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ const defaultProps: NumberInputProps = {
const clickIncrement = (container: HTMLElement) =>
userEvent.click(container.querySelector('.mantine-NumberInput-control[data-direction="up"]')!);

const clickDecrement = (container: HTMLElement) =>
userEvent.click(container.querySelector('.mantine-NumberInput-control[data-direction="down"]')!);

const getInput = () => screen.getByRole('textbox');
const enterText = (text: string) => userEvent.type(getInput(), text);
const expectValue = (value: string) => expect(getInput()).toHaveValue(value);
Expand Down Expand Up @@ -176,4 +179,14 @@ describe('@mantine/core/NumberInput', () => {

expect(spy).toHaveBeenLastCalledWith(0);
});

it('does not allow negative numbers if the allowNegative prop is false', async () => {
const spy = jest.fn();
const { container } = render(<NumberInput onChange={spy} value={0} allowNegative={false} />);

await clickDecrement(container);

expectValue('0');
expect(spy).toHaveBeenLastCalledWith(0);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -290,16 +290,17 @@ export const NumberInput = factory<NumberInputFactory>((_props, ref) => {
const decrementRef = useRef<() => void>();
decrementRef.current = () => {
let val: number;
const minValue = min !== undefined ? min : !allowNegative ? 0 : Number.MIN_SAFE_INTEGER;
const currentValuePrecision = getDecimalPlaces(_value);
const stepPrecision = getDecimalPlaces(step!);
const maxPrecision = Math.max(currentValuePrecision, stepPrecision);
const factor = 10 ** maxPrecision;

if (typeof _value !== 'number' || Number.isNaN(_value)) {
val = clamp(startValue!, min, max);
val = clamp(startValue!, minValue, max);
} else {
const decrementedValue = (Math.round(_value * factor) - Math.round(step! * factor)) / factor;
val = min !== undefined && decrementedValue < min ? min : decrementedValue;
val = minValue !== undefined && decrementedValue < minValue ? minValue : decrementedValue;
}

const formattedValue = val.toFixed(maxPrecision);
Expand Down

0 comments on commit 3c8ca0d

Please sign in to comment.