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

Fix SelectInput / SelectArrayInput onChange handler #7519

Merged
merged 4 commits into from
Apr 27, 2022
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
73 changes: 73 additions & 0 deletions packages/ra-ui-materialui/src/input/SelectArrayInput.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -502,4 +502,77 @@ describe('<SelectArrayInput />', () => {
// 2 because there is both the chip for the new selected item and the option (event if hidden)
expect(screen.queryAllByText(newChoice.name).length).toEqual(2);
});

it('should recive an event object on change', async () => {
const choices = [...defaultProps.choices];
const onChange = jest.fn();

render(
<AdminContext dataProvider={testDataProvider()}>
<SimpleForm>
<SelectArrayInput
{...defaultProps}
choices={choices}
onChange={onChange}
/>
</SimpleForm>
</AdminContext>
);

const input = screen.getByLabelText(
'resources.posts.fields.categories'
) as HTMLInputElement;
fireEvent.mouseDown(input);

fireEvent.click(screen.getByText('Lifestyle'));

await waitFor(() => {
expect(onChange).toHaveBeenCalledWith(
expect.objectContaining({ isTrusted: false })
);
});
});

it('should recive a value on change when creating a new choice', async () => {
jest.spyOn(console, 'warn').mockImplementation(() => {});
const choices = [...defaultProps.choices];
const newChoice = { id: 'js_fatigue', name: 'New Kid On The Block' };
const onChange = jest.fn();

const Create = () => {
const context = useCreateSuggestionContext();
const handleClick = () => {
choices.push(newChoice);
context.onCreate(newChoice);
};

return <button onClick={handleClick}>Get the kid</button>;
};

render(
<AdminContext dataProvider={testDataProvider()}>
<SimpleForm onSubmit={jest.fn()}>
<SelectArrayInput
{...defaultProps}
choices={choices}
create={<Create />}
onChange={onChange}
/>
</SimpleForm>
</AdminContext>
);

const input = screen.getByLabelText(
'resources.posts.fields.categories'
) as HTMLInputElement;
fireEvent.mouseDown(input);

fireEvent.click(screen.getByText('ra.action.create'));
fireEvent.click(screen.getByText('Get the kid'));
input.blur();

await waitFor(() => {
expect(onChange).toHaveBeenCalledWith(['js_fatigue']);
});
});
});
11 changes: 6 additions & 5 deletions packages/ra-ui-materialui/src/input/SelectArrayInput.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import { styled } from '@mui/material/styles';
import { useCallback, useRef } from 'react';
import { useCallback, useRef, ChangeEvent } from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import {
Expand All @@ -17,6 +17,7 @@ import {
useInput,
useChoicesContext,
useChoices,
RaRecord,
} from 'ra-core';
import { InputHelperText } from './InputHelperText';
import { FormControlProps } from '@mui/material/FormControl';
Expand Down Expand Up @@ -143,12 +144,11 @@ export const SelectArrayInput = (props: SelectArrayInputProps) => {
});

const handleChange = useCallback(
(eventOrChoice: any) => {
(eventOrChoice: ChangeEvent<HTMLInputElement> | RaRecord) => {
// We might receive an event from the mui component
// In this case, it will be the choice id
// eslint-disable-next-line eqeqeq
if (eventOrChoice?.target?.value != undefined) {
field.onChange(eventOrChoice.target.value);
if (eventOrChoice?.target) {
field.onChange(eventOrChoice);
} else {
// Or we might receive a choice directly, for instance a newly created one
field.onChange([
Expand Down Expand Up @@ -295,6 +295,7 @@ export type SelectArrayInputProps = ChoicesProps &
Omit<FormControlProps, 'defaultValue' | 'onBlur' | 'onChange'> & {
disableValue?: string;
source?: string;
onChange?: (event: ChangeEvent<HTMLInputElement> | RaRecord) => void;
};

SelectArrayInput.propTypes = {
Expand Down
77 changes: 77 additions & 0 deletions packages/ra-ui-materialui/src/input/SelectInput.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -589,4 +589,81 @@ describe('<SelectInput />', () => {
expect(screen.queryByText(newChoice.name)).not.toBeNull();
});
});

it('should recive an event object on change', async () => {
const choices = [...defaultProps.choices];
const onChange = jest.fn();

render(
<AdminContext dataProvider={testDataProvider()}>
<SimpleForm>
<SelectInput
{...defaultProps}
choices={choices}
defaultValue="ang"
inputProps={{ 'data-testid': 'content-input' }}
onChange={onChange}
/>
</SimpleForm>
</AdminContext>
);

const input = screen.getByTestId('content-input');
fireEvent.change(input, {
target: { value: 'rea' },
});

await waitFor(() => {
expect(onChange).toHaveBeenCalledWith(
expect.objectContaining({
bubbles: true,
cancelable: false,
currentTarget: null,
eventPhase: 3,
isTrusted: false,
type: 'change',
})
);
});
});

it('should recive a value on change when creating a new choice', async () => {
jest.spyOn(console, 'warn').mockImplementation(() => {});
const choices = [...defaultProps.choices];
const newChoice = { id: 'js_fatigue', name: 'New Kid On The Block' };
const onChange = jest.fn();

const Create = () => {
const context = useCreateSuggestionContext();
const handleClick = () => {
choices.push(newChoice);
context.onCreate(newChoice);
};

return <button onClick={handleClick}>Get the kid</button>;
};

render(
<AdminContext dataProvider={testDataProvider()}>
<SimpleForm onSubmit={jest.fn()}>
<SelectInput
{...defaultProps}
choices={choices}
create={<Create />}
onChange={onChange}
/>
</SimpleForm>
</AdminContext>
);

const input = screen.getByLabelText('resources.posts.fields.language');
fireEvent.mouseDown(input);

fireEvent.click(screen.getByText('ra.action.create'));
fireEvent.click(screen.getByText('Get the kid'));

await waitFor(() => {
expect(onChange).toHaveBeenCalledWith('js_fatigue');
});
});
});
13 changes: 7 additions & 6 deletions packages/ra-ui-materialui/src/input/SelectInput.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { ReactElement, useCallback } from 'react';
import { ReactElement, useCallback, ChangeEvent } from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import MenuItem from '@mui/material/MenuItem';
Expand All @@ -12,6 +12,7 @@ import {
useTranslate,
ChoicesProps,
useChoices,
RaRecord,
} from 'ra-core';

import { CommonInputProps } from './CommonInputProps';
Expand Down Expand Up @@ -183,12 +184,11 @@ export const SelectInput = (props: SelectInputProps) => {
]);

const handleChange = useCallback(
async (eventOrChoice: any) => {
async (eventOrChoice: ChangeEvent<HTMLInputElement> | RaRecord) => {
// We might receive an event from the mui component
// In this case, it will be the choice id
// eslint-disable-next-line eqeqeq
if (eventOrChoice?.target?.value != undefined) {
field.onChange(eventOrChoice.target.value);
if (eventOrChoice?.target) {
field.onChange(eventOrChoice);
} else {
// Or we might receive a choice directly, for instance a newly created one
field.onChange(getChoiceValue(eventOrChoice));
Expand Down Expand Up @@ -373,10 +373,11 @@ const StyledResettableTextField = styled(ResettableTextField, {
export type SelectInputProps = Omit<CommonInputProps, 'source'> &
ChoicesProps &
Omit<SupportCreateSuggestionOptions, 'handleChange'> &
Omit<TextFieldProps, 'label' | 'helperText' | 'classes'> & {
Omit<TextFieldProps, 'label' | 'helperText' | 'classes' | 'onChange'> & {
disableValue?: string;
emptyText?: string | ReactElement;
emptyValue?: any;
// Source is optional as AutocompleteInput can be used inside a ReferenceInput that already defines the source
source?: string;
onChange?: (event: ChangeEvent<HTMLInputElement> | RaRecord) => void;
};