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

Add ability to reset an AutocompleteInput #5396

Merged
merged 2 commits into from
Oct 14, 2020
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
20 changes: 11 additions & 9 deletions docs/Inputs.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,15 +184,17 @@ import { AutocompleteInput } from 'react-admin';

| Prop | Required | Type | Default | Description |
| ------------------------- | -------- | --------------------------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `allowEmpty` | Optional | `boolean` | `false` | If `false` and the searchText typed did not match any suggestion, the searchText will revert to the current value when the field is blurred. If `true` and the `searchText` is set to `''` then the field will set the input value to `null`. |
| `choices` | Required | `Object[]` | `-` | List of items to autosuggest |
| `emptyValue` | Optional | `any` | `''` | The value to use for the empty element |
| `emptyText` | Optional | `string` | `''` | The text to use for the empty element |
| `matchSuggestion` | Optional | `Function` | `-` | Required if `optionText` is a React element. Function returning a boolean indicating whether a choice matches the filter. `(filter, choice) => boolean` |
| `optionText` | Optional | `string` | `Function` | `Component` | `name` | Fieldname of record to display in the suggestion item or function which accepts the correct record as argument (`(record)=> {string}`) |
| `optionValue` | Optional | `string` | `id` | Fieldname of record containing the value to use as input value |
| `inputText` | Optional | `Function` | `-` | If `optionText` is a custom Component, this function is needed to determine the text displayed for the current selection. |
| `setFilter` | Optional | `Function` | `null` | A callback to inform the `searchText` has changed and new `choices` can be retrieved based on this `searchText`. Signature `searchText => void`. This function is automatically setup when using `ReferenceInput`. |
| `allowEmpty` | Optional | `boolean` | `false` | If `false` and the searchText typed did not match any suggestion, the searchText will revert to the current value when the field is blurred. If `true` and the `searchText` is set to `''` then the field will set the input value to `null`. |
| `clearAlwaysVisible` | Optional | `boolean` | `false` | When `resettable` is true, set this prop to `true` to have the Reset button visible even when the field is empty |
| `choices` | Required | `Object[]` | `-` | List of items to autosuggest |
| `emptyValue` | Optional | `any` | `''` | The value to use for the empty element |
| `emptyText` | Optional | `string` | `''` | The text to use for the empty element |
| `matchSuggestion` | Optional | `Function` | `-` | Required if `optionText` is a React element. Function returning a boolean indicating whether a choice matches the filter. `(filter, choice) => boolean` |
| `optionText` | Optional | `string` | `Function` | `Component` | `name` | Fieldname of record to display in the suggestion item or function which accepts the correct record as argument (`(record)=> {string}`) |
| `optionValue` | Optional | `string` | `id` | Fieldname of record containing the value to use as input value |
| `inputText` | Optional | `Function` | `-` | If `optionText` is a custom Component, this function is needed to determine the text displayed for the current selection. |
| `resettable` | Optional | `boolean` | `false` | Display a button to reset the text filter. Useful when using `<AutocompleteInput>` inside `<Filter>` |
| `setFilter` | Optional | `Function` | `null` | A callback to inform the `searchText` has changed and new `choices` can be retrieved based on this `searchText`. Signature `searchText => void`. This function is automatically setup when using `ReferenceInput`. |
| `shouldRenderSuggestions` | Optional | Function | `() => true` | A function that returns a `boolean` to determine whether or not suggestions are rendered. Use this when working with large collections of data to improve performance and user experience. This function is passed into the underlying react-autosuggest component. Ex.`(value) => value.trim() > 2` |

`<AutocompleteInput>` also accepts the [common input props](./Inputs.md#common-input-props).
Expand Down
13 changes: 7 additions & 6 deletions packages/ra-core/src/form/useInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,18 @@ export interface InputProps<T = any>
FieldProps<any, FieldRenderProps<any, HTMLElement>, HTMLElement>,
'validate' | 'children'
> {
source: string;
name?: string;
id?: string;
defaultValue?: any;
validate?: Validator | Validator[];
id?: string;
input?: FieldInputProps<any, HTMLElement>;
meta?: any;
name?: string;
onBlur?: (event: FocusEvent<T>) => void;
onChange?: (event: ChangeEvent | any) => void;
onFocus?: (event: FocusEvent<T>) => void;
options?: T;
input?: FieldInputProps<any, HTMLElement>;
meta?: any;
resource?: string;
source: string;
validate?: Validator | Validator[];
}

interface ComputedInputProps extends FieldRenderProps<any, HTMLElement> {
Expand Down
126 changes: 117 additions & 9 deletions packages/ra-ui-materialui/src/input/AutocompleteInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@ import React, {
} from 'react';
import Downshift, { DownshiftProps } from 'downshift';
import get from 'lodash/get';
import { TextField } from '@material-ui/core';
import classNames from 'classnames';
import { TextField, InputAdornment, IconButton } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import ClearIcon from '@material-ui/icons/Clear';
import { TextFieldProps } from '@material-ui/core/TextField';
import {
useInput,
FieldTitle,
ChoicesInputProps,
useSuggestions,
useTranslate,
warning,
} from 'ra-core';

Expand Down Expand Up @@ -91,14 +94,12 @@ interface Options {
* @example
* <AutocompleteInput source="author_id" options={{ color: 'secondary', InputLabelProps: { shrink: true } }} />
*/
const AutocompleteInput: FunctionComponent<
ChoicesInputProps<TextFieldProps & Options> &
Omit<DownshiftProps<any>, 'onChange'>
> = props => {
const AutocompleteInput: FunctionComponent<AutocompleteInputProps> = props => {
const {
allowEmpty,
className,
classes: classesOverride,
clearAlwaysVisible,
choices = [],
disabled,
emptyText,
Expand Down Expand Up @@ -131,6 +132,7 @@ const AutocompleteInput: FunctionComponent<
inputText,
optionValue = 'id',
parse,
resettable,
resource,
setFilter,
shouldRenderSuggestions: shouldRenderSuggestionsOverride,
Expand Down Expand Up @@ -173,6 +175,8 @@ const AutocompleteInput: FunctionComponent<
let inputEl = useRef<HTMLInputElement>();
let anchorEl = useRef<any>();

const translate = useTranslate();

const {
id,
input,
Expand Down Expand Up @@ -336,6 +340,82 @@ const AutocompleteInput: FunctionComponent<
return true;
};

const { endAdornment, ...InputPropsWithoutEndAdornment } = InputProps || {};

const handleClickClearButton = useCallback(
openMenu => event => {
event.stopPropagation();
setFilterValue('');
input.onChange('');
openMenu(event);
input.onFocus(event);
},
[input]
);

const getEndAdornment = openMenu => {
if (!resettable) {
return endAdornment;
} else if (!filterValue) {
const label = translate('ra.action.clear_input_value');
if (clearAlwaysVisible) {
// show clear button, inactive
return (
<InputAdornment position="end">
<IconButton
className={classes.clearButton}
aria-label={label}
title={label}
disableRipple
disabled={true}
>
<ClearIcon
className={classNames(
classes.clearIcon,
classes.visibleClearIcon
)}
/>
</IconButton>
</InputAdornment>
);
} else {
if (endAdornment) {
return endAdornment;
} else {
// show spacer
return (
<InputAdornment position="end">
<span className={classes.clearButton}>&nbsp;</span>
</InputAdornment>
);
}
}
} else {
// show clear
const label = translate('ra.action.clear_input_value');
return (
<InputAdornment position="end">
<IconButton
className={classes.clearButton}
aria-label={label}
title={label}
disableRipple
onClick={handleClickClearButton(openMenu)}
onMouseDown={handleMouseDownClearButton}
disabled={disabled}
>
<ClearIcon
className={classNames(classes.clearIcon, {
[classes.visibleClearIcon]:
clearAlwaysVisible || filterValue,
})}
/>
</IconButton>
</InputAdornment>
);
}
};

return (
<Downshift
inputValue={filterValue}
Expand Down Expand Up @@ -379,6 +459,7 @@ const AutocompleteInput: FunctionComponent<
name={input.name}
InputProps={{
inputRef: storeInputRef,
endAdornment: getEndAdornment(openMenu),
onBlur,
onChange: event => {
handleFilterChange(event);
Expand All @@ -390,6 +471,7 @@ const AutocompleteInput: FunctionComponent<
);
},
onFocus,
...InputPropsWithoutEndAdornment,
}}
error={!!(touched && error)}
label={
Expand Down Expand Up @@ -464,18 +546,44 @@ const AutocompleteInput: FunctionComponent<
);
};

const handleMouseDownClearButton = event => {
event.preventDefault();
};

const useStyles = makeStyles(
{
root: {
flexGrow: 1,
height: 250,
},
container: {
flexGrow: 1,
position: 'relative',
},
clearIcon: {
height: 16,
width: 0,
},
visibleClearIcon: {
width: 16,
},
clearButton: {
height: 24,
width: 24,
padding: 0,
},
selectAdornment: {
position: 'absolute',
right: 24,
},
inputAdornedEnd: {
paddingRight: 0,
},
},
{ name: 'RaAutocompleteInput' }
);

export interface AutocompleteInputProps
extends ChoicesInputProps<TextFieldProps & Options>,
Omit<DownshiftProps<any>, 'onChange'> {
clearAlwaysVisible?: boolean;
resettable?: boolean;
}

export default AutocompleteInput;
4 changes: 3 additions & 1 deletion packages/ra-ui-materialui/src/input/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ArrayInput from './ArrayInput';
import AutocompleteArrayInput from './AutocompleteArrayInput';
import AutocompleteInput from './AutocompleteInput';
import AutocompleteInput, { AutocompleteInputProps } from './AutocompleteInput';
import BooleanInput from './BooleanInput';
import CheckboxGroupInput from './CheckboxGroupInput';
import DateInput from './DateInput';
Expand Down Expand Up @@ -47,3 +47,5 @@ export {
SelectInput,
TextInput,
};

export type { AutocompleteInputProps };