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

[Autocomplete] Add new feature onHighlightChange #20691

Merged
merged 3 commits into from
Apr 22, 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
1 change: 1 addition & 0 deletions docs/pages/api-docs/autocomplete.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ The `MuiAutocomplete` name can be used for providing [default props](/customizat
| <span class="prop-name">noOptionsText</span> | <span class="prop-type">node</span> | <span class="prop-default">'No options'</span> | Text to display when there are no options.<br>For localization purposes, you can use the provided [translations](/guides/localization/). |
| <span class="prop-name">onChange</span> | <span class="prop-type">func</span> | | Callback fired when the value changes.<br><br>**Signature:**<br>`function(event: object, value: T, reason: string) => void`<br>*event:* The event source of the callback.<br>*value:* The new value of the component.<br>*reason:* One of "create-option", "select-option", "remove-option", "blur" or "clear". |
| <span class="prop-name">onClose</span> | <span class="prop-type">func</span> | | Callback fired when the popup requests to be closed. Use in controlled mode (see open).<br><br>**Signature:**<br>`function(event: object, reason: string) => void`<br>*event:* The event source of the callback.<br>*reason:* Can be: `"toggleInput"`, `"escape"`, `"select-option"`, `"blur"`. |
| <span class="prop-name">onHighlightChange</span> | <span class="prop-type">func</span> | | Callback fired when the highlight option changes.<br><br>**Signature:**<br>`function(event: object, option: T, reason: string) => void`<br>*event:* The event source of the callback.<br>*option:* The highlighted option.<br>*reason:* Can be: `"keyboard"`, `"auto"`, `"mouse"`. |
| <span class="prop-name">onInputChange</span> | <span class="prop-type">func</span> | | Callback fired when the input value changes.<br><br>**Signature:**<br>`function(event: object, value: string, reason: string) => void`<br>*event:* The event source of the callback.<br>*value:* The new value of the text input.<br>*reason:* Can be: `"input"` (user input), `"reset"` (programmatic change), `"clear"`. |
| <span class="prop-name">onOpen</span> | <span class="prop-type">func</span> | | Callback fired when the popup requests to be opened. Use in controlled mode (see open).<br><br>**Signature:**<br>`function(event: object) => void`<br>*event:* The event source of the callback. |
| <span class="prop-name">open</span> | <span class="prop-type">bool</span> | | Control the popup` open state. |
Expand Down
9 changes: 9 additions & 0 deletions packages/material-ui-lab/src/Autocomplete/Autocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ const Autocomplete = React.forwardRef(function Autocomplete(props, ref) {
noOptionsText = 'No options',
onChange,
onClose,
onHighlightChange,
onInputChange,
onOpen,
open,
Expand Down Expand Up @@ -729,6 +730,14 @@ Autocomplete.propTypes = {
* @param {string} reason Can be: `"toggleInput"`, `"escape"`, `"select-option"`, `"blur"`.
*/
onClose: PropTypes.func,
/**
* Callback fired when the highlight option changes.
*
* @param {object} event The event source of the callback.
* @param {T} option The highlighted option.
* @param {string} reason Can be: `"keyboard"`, `"auto"`, `"mouse"`.
*/
onHighlightChange: PropTypes.func,
/**
* Callback fired when the input value changes.
*
Expand Down
62 changes: 62 additions & 0 deletions packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1549,4 +1549,66 @@ describe('<Autocomplete />', () => {
expect(container.querySelector(`.${classes.root}`)).to.have.class(classes.fullWidth);
});
});

describe('prop: onHighlightChange', () => {
it('should trigger event when default value is passed', () => {
const handleChange = spy();
const options = ['one', 'two', 'three'];
render(
<Autocomplete
defaultValue={options[0]}
onHighlightChange={handleChange}
options={options}
open
renderInput={(params) => <TextField autoFocus {...params} />}
/>,
);
expect(handleChange.callCount).to.equal(1);
expect(handleChange.args[0][0]).to.equal(undefined);
expect(handleChange.args[0][1]).to.equal(options[0]);
expect(handleChange.args[0][2]).to.equal('auto');
});

it('should support keyboard event', () => {
const handleChange = spy();
const options = ['one', 'two', 'three'];
render(
<Autocomplete
onHighlightChange={handleChange}
options={options}
open
renderInput={(params) => <TextField autoFocus {...params} />}
/>,
);
fireEvent.keyDown(document.activeElement, { key: 'ArrowDown' });
expect(handleChange.callCount).to.equal(2);
expect(handleChange.args[1][0]).to.not.equal(undefined);
expect(handleChange.args[1][1]).to.equal(options[0]);
expect(handleChange.args[1][2]).to.equal('keyboard');
fireEvent.keyDown(document.activeElement, { key: 'ArrowDown' });
expect(handleChange.callCount).to.equal(3);
expect(handleChange.args[2][0]).to.not.equal(undefined);
expect(handleChange.args[2][1]).to.equal(options[1]);
expect(handleChange.args[2][2]).to.equal('keyboard');
});

it('should support mouse event', () => {
const handleChange = spy();
const options = ['one', 'two', 'three'];
const { getAllByRole } = render(
<Autocomplete
onHighlightChange={handleChange}
options={options}
open
renderInput={(params) => <TextField autoFocus {...params} />}
/>,
);
const firstOption = getAllByRole('option')[0];
fireEvent.mouseOver(firstOption);
expect(handleChange.callCount).to.equal(2);
expect(handleChange.args[1][0]).to.not.equal(undefined);
expect(handleChange.args[1][1]).to.equal(options[0]);
expect(handleChange.args[1][2]).to.equal('mouse');
});
});
});
14 changes: 14 additions & 0 deletions packages/material-ui-lab/src/useAutocomplete/useAutocomplete.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,18 @@ export interface UseAutocompleteCommonProps<T> {
* @param {object} event The event source of the callback.
*/
onOpen?: (event: React.ChangeEvent<{}>) => void;
/**
* Callback fired when the highlight option changes.
*
* @param {object} event The event source of the callback.
* @param {T} option The highlighted option.
* @param {string} reason Can be: `"keyboard"`, `"auto"`, `"mouse"`.
*/
onHighlightChange?: (
event: React.ChangeEvent<{}>,
option: T | null,
reason: AutocompleteHighlightChangeReason
) => void;
/**
* Control the popup` open state.
*/
Expand All @@ -189,6 +201,8 @@ export interface UseAutocompleteCommonProps<T> {
selectOnFocus?: boolean;
}

export type AutocompleteHighlightChangeReason = 'keyboard' | 'mouse' | 'auto';

export type AutocompleteChangeReason =
| 'create-option'
| 'select-option'
Expand Down
27 changes: 16 additions & 11 deletions packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ export default function useAutocomplete(props) {
multiple = false,
onChange,
onClose,
onHighlightChange,
onInputChange,
onOpen,
open: openProp,
Expand All @@ -120,7 +121,7 @@ export default function useAutocomplete(props) {
const defaultHighlighted = autoHighlight ? 0 : -1;
const highlightedIndexRef = React.useRef(defaultHighlighted);

const setHighlightedIndex = useEventCallback((index, mouse = false) => {
const setHighlightedIndex = useEventCallback((index, reason = 'auto', event) => {
highlightedIndexRef.current = index;
// does the index exist?
if (index === -1) {
Expand All @@ -145,6 +146,10 @@ export default function useAutocomplete(props) {
return;
}

if (onHighlightChange) {
onHighlightChange(event, options[index], reason);
}

if (index === -1) {
listboxNode.scrollTop = 0;
return;
Expand All @@ -163,7 +168,7 @@ export default function useAutocomplete(props) {
//
// Consider this API instead once it has a better browser support:
// .scrollIntoView({ scrollMode: 'if-needed', block: 'nearest' });
if (listboxNode.scrollHeight > listboxNode.clientHeight && !mouse) {
if (listboxNode.scrollHeight > listboxNode.clientHeight && reason !== 'mouse') {
const element = option;

const scrollBottom = listboxNode.clientHeight + listboxNode.scrollTop;
Expand Down Expand Up @@ -332,7 +337,7 @@ export default function useAutocomplete(props) {
}
}

const changeHighlightedIndex = useEventCallback((diff, direction) => {
const changeHighlightedIndex = useEventCallback((diff, direction, reason = 'auto', event) => {
if (!popupOpen) {
return;
}
Expand Down Expand Up @@ -382,7 +387,7 @@ export default function useAutocomplete(props) {
};

const nextIndex = validOptionIndex(getNextIndex(), direction);
setHighlightedIndex(nextIndex);
setHighlightedIndex(nextIndex, reason, event);

if (autoComplete && diff !== 'reset') {
if (nextIndex === -1) {
Expand Down Expand Up @@ -627,38 +632,38 @@ export default function useAutocomplete(props) {
if (popupOpen) {
// Prevent scroll of the page
event.preventDefault();
changeHighlightedIndex('start', 'next');
changeHighlightedIndex('start', 'next', 'keyboard', event);
}
break;
case 'End':
if (popupOpen) {
// Prevent scroll of the page
event.preventDefault();
changeHighlightedIndex('end', 'previous');
changeHighlightedIndex('end', 'previous', 'keyboard', event);
}
break;
case 'PageUp':
// Prevent scroll of the page
event.preventDefault();
changeHighlightedIndex(-pageSize, 'previous');
changeHighlightedIndex(-pageSize, 'previous', 'keyboard', event);
handleOpen(event);
break;
case 'PageDown':
// Prevent scroll of the page
event.preventDefault();
changeHighlightedIndex(pageSize, 'next');
changeHighlightedIndex(pageSize, 'next', 'keyboard', event);
handleOpen(event);
break;
case 'ArrowDown':
// Prevent cursor move
event.preventDefault();
changeHighlightedIndex(1, 'next');
changeHighlightedIndex(1, 'next', 'keyboard', event);
handleOpen(event);
break;
case 'ArrowUp':
// Prevent cursor move
event.preventDefault();
changeHighlightedIndex(-1, 'previous');
changeHighlightedIndex(-1, 'previous', 'keyboard', event);
handleOpen(event);
break;
case 'ArrowLeft':
Expand Down Expand Up @@ -791,7 +796,7 @@ export default function useAutocomplete(props) {

const handleOptionMouseOver = (event) => {
const index = Number(event.currentTarget.getAttribute('data-option-index'));
setHighlightedIndex(index, 'mouse');
setHighlightedIndex(index, 'mouse', event);
};

const handleOptionTouchStart = () => {
Expand Down