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] Fix option grouping #19121

Merged
merged 1 commit into from
Jan 8, 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
27 changes: 27 additions & 0 deletions packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -955,4 +955,31 @@ describe('<Autocomplete />', () => {
expect(options).to.have.length(3);
});
});

describe('prop: groupBy', () => {
it('correctly groups options and preserves option order in each group', () => {
const data = [
{ group: 1, value: 'A' },
{ group: 2, value: 'D' },
{ group: 2, value: 'E' },
{ group: 1, value: 'B' },
{ group: 3, value: 'G' },
{ group: 2, value: 'F' },
{ group: 1, value: 'C' },
];
const { getAllByRole } = render(
<Autocomplete
options={data}
getOptionLabel={option => option.value}
renderInput={params => <TextField {...params} autoFocus />}
open
groupBy={option => option.group}
/>,
);

const options = getAllByRole('option').map(el => el.textContent);
expect(options).to.have.length(7);
expect(options).to.deep.equal(['A', 'B', 'C', 'D', 'E', 'F', 'G']);
});
});
});
32 changes: 22 additions & 10 deletions packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -782,21 +782,33 @@ export default function useAutocomplete(props) {

let groupedOptions = filteredOptions;
if (groupBy) {
groupedOptions = filteredOptions.reduce((acc, option, index) => {
const key = groupBy(option);
const result = [];

if (acc.length > 0 && acc[acc.length - 1].key === key) {
acc[acc.length - 1].options.push(option);
} else {
acc.push({
// used to keep track of key and indexes in the result array
const indexByKey = new Map();
let currentResultIndex = 0;

filteredOptions.forEach(option => {
const key = groupBy(option);
if (indexByKey.get(key) === undefined) {
indexByKey.set(key, currentResultIndex);
result.push({
key,
index,
options: [option],
options: [],
});
currentResultIndex += 1;
}
result[indexByKey.get(key)].options.push(option);
});

// now we can add the `index` property based on the options length
let indexCounter = 0;
result.forEach(option => {
option.index = indexCounter;
indexCounter += option.options.length;
});

return acc;
}, []);
groupedOptions = result;
}

return {
Expand Down