CreateImageWizard: Sort packages alphabetically

Search results are now converted to lower case before sorting. This
ensures that results appear in alphabetical order in a case insensitive
fashion.
This commit is contained in:
lucasgarfield 2022-02-22 18:30:44 +01:00 committed by Lucas Garfield
parent e8e7329bf6
commit 1630f30448
2 changed files with 55 additions and 6 deletions

View file

@ -43,31 +43,34 @@ const Packages = ({ defaultArch, ...props }) => {
const searchResultsComparator = useCallback((searchTerm) => {
return (a, b) => {
a = a.name.toLowerCase();
b = b.name.toLowerCase();
// check exact match first
if (a.name === searchTerm) {
if (a === searchTerm) {
return -1;
}
if (b.name === searchTerm) {
if (b === searchTerm) {
return 1;
}
// check for packages that start with the search term
if (a.name.startsWith(searchTerm) && !b.name.startsWith(searchTerm)) {
if (a.startsWith(searchTerm) && !b.startsWith(searchTerm)) {
return -1;
}
if (b.name.startsWith(searchTerm) && !a.name.startsWith(searchTerm)) {
if (b.startsWith(searchTerm) && !a.startsWith(searchTerm)) {
return 1;
}
// if both (or neither) start with the search term
// sort alphabetically
if (a.name < b.name) {
if (a < b) {
return -1;
}
if (b.name < a.name) {
if (b < a) {
return 1;
}

View file

@ -49,6 +49,28 @@ const mockPkgResult = {
]
};
const mockPkgResultAlpha = {
meta: { count: 3 },
links: { first: '', last: '' },
data: [
{
name: 'lib-test',
summary: 'lib-test package summary',
version: '1.0',
},
{
name: 'Z-test',
summary: 'Z-test package summary',
version: '1.0',
},
{
name: 'test',
summary: 'summary for test package',
version: '1.0',
}
]
};
const mockPkgResultPartial = {
meta: { count: 132 },
links: { first: '', last: '' },
@ -768,6 +790,30 @@ describe('Step Packages', () => {
const availablePackagesItems = within(availablePackagesList).getAllByRole('option');
expect(availablePackagesItems).toHaveLength(132);
});
test('search results should be sorted alphabetically', async () => {
await setUp();
const searchbox = screen.getAllByRole('textbox')[0]; // searching by id doesn't update the input ref
searchbox.click();
const getPackages = jest
.spyOn(api, 'getPackages')
.mockImplementation(() => Promise.resolve(mockPkgResultAlpha));
await searchForAvailablePackages(searchbox, 'test');
expect(getPackages).toHaveBeenCalledTimes(1);
const availablePackagesList = screen.getByTestId('available-pkgs-list');
const availablePackagesItems = within(availablePackagesList).getAllByRole('option');
expect(availablePackagesItems).toHaveLength(3);
const [ firstItem, secondItem, thirdItem ] = availablePackagesItems;
expect(firstItem).toHaveTextContent('testsummary for test package');
expect(secondItem).toHaveTextContent('lib-testlib-test package summary');
expect(thirdItem).toHaveTextContent('Z-testZ-test package summary');
});
});
describe('Step Review', () => {