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

feat(atomic, headless): add support for sort criteria alphanumericNatural #4493

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
11 changes: 11 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/atomic/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@
"lit-html": "3.1.4",
"local-web-server": "5.4.0",
"lodash": "4.17.21",
"natural-orderby": "4.0.0",
"ncp": "2.0.0",
"postcss-focus-visible": "9.0.1",
"postcss-import": "16.1.0",
Expand Down
4 changes: 2 additions & 2 deletions packages/atomic/src/components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -888,7 +888,7 @@ export namespace Components {
*/
"resultsMustMatch": FacetResultsMustMatch;
/**
* The sort criterion to apply to the returned facet values. Possible values are 'score', 'alphanumeric', 'alphanumericDescending', 'occurrences', and 'automatic'.
* The sort criterion to apply to the returned facet values. Possible values are 'score', 'alphanumeric', 'alphanumericDescending', 'occurrences', alphanumericNatural', 'alphanumericNaturalDescending' and 'automatic'.
*/
"sortCriteria": FacetSortCriterion;
/**
Expand Down Expand Up @@ -7031,7 +7031,7 @@ declare namespace LocalJSX {
*/
"resultsMustMatch"?: FacetResultsMustMatch;
/**
* The sort criterion to apply to the returned facet values. Possible values are 'score', 'alphanumeric', 'alphanumericDescending', 'occurrences', and 'automatic'.
* The sort criterion to apply to the returned facet values. Possible values are 'score', 'alphanumeric', 'alphanumericDescending', 'occurrences', alphanumericNatural', 'alphanumericNaturalDescending' and 'automatic'.
*/
"sortCriteria"?: FacetSortCriterion;
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ const meta: Meta = {
name: 'number-of-values',
control: {type: 'number', min: 1},
},
'attributes-sort-criteria': {
name: 'sort-criteria',
type: 'string',
},
},
args: {
'attributes-number-of-values': 8,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ export class AtomicFacet implements InitializableComponent {
@Prop({reflect: true}) public withSearch = true;
/**
* The sort criterion to apply to the returned facet values.
* Possible values are 'score', 'alphanumeric', 'alphanumericDescending', 'occurrences', and 'automatic'.
* Possible values are 'score', 'alphanumeric', 'alphanumericDescending', 'occurrences', alphanumericNatural', 'alphanumericNaturalDescending' and 'automatic'.
*/
@Prop({reflect: true}) public sortCriteria: FacetSortCriterion = 'automatic';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The interface FacetSortCriterion does not contain alphanumericNatural' & alphanumericNaturalDescending.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR adds them!

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import {FacetSortCriterion} from '@coveo/headless';
import {orderBy} from 'natural-orderby';
Comment on lines +1 to +2
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think adding a dependency is necessary for tests. Is there other ways you can test this ? Or at least put it in devDependencies ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep def should be in dev deps. Extracting the sorting logic from natural-orderby would be too much work.

I tried with natural-compare-lite and javascript-natural-sort, which are already in our deps, but they don't sort in the same way as the index...

import {test, expect} from './fixture';

test.describe('when selecting the facet search "More matches for" button', () => {
Expand Down Expand Up @@ -151,3 +153,81 @@ test.describe('when the "Show more" button has been selected', () => {
});
});
});

const sortCriteriaTests: {
criteria: FacetSortCriterion;
sortFunction: (values: string[]) => string[];
}[] = [
{
criteria: 'alphanumeric',
sortFunction: (values: string[]) => [...values].sort(),
},
{
criteria: 'alphanumericDescending',
sortFunction: (values: string[]) => [...values].sort().reverse(),
},
{
criteria: 'alphanumericNatural',
sortFunction: (values: string[]) =>
orderBy([...values], [(value) => value], 'asc'),
},
{
criteria: 'alphanumericNaturalDescending',
sortFunction: (values: string[]) =>
orderBy([...values], [(value) => value], ['desc']),
},
];

test.describe('Sort Criteria', () => {
sortCriteriaTests.forEach(({criteria, sortFunction}) => {
test.describe(`when sort criteria is set to "${criteria}"`, () => {
test.beforeEach(async ({facet}) => {
await facet.load({
args: {
sortCriteria: criteria,
field: 'cat_available_sizes',
label: 'Size',
numberOfValues: 30,
},
});
await facet.hydrated.waitFor();
await expect.poll(async () => await facet.facetValue.count()).toBe(30);
});

test(`should have facet values sorted by ${criteria}`, async ({
facet,
}) => {
const values = await facet.facetValueLabel.allTextContents();
const sortedValues = sortFunction(values);
expect(values).toEqual(sortedValues);
});
});
});

test.describe('when sort criteria is set to "occurrences"', () => {
test.beforeEach(async ({facet}) => {
await facet.load({
args: {
sortCriteria: 'occurrences',
field: 'cat_available_sizes',
label: 'Size',
numberOfValues: 30,
},
});
await facet.hydrated.waitFor();
await expect.poll(async () => await facet.facetValue.count()).toBe(30);
});

test('should have facet values sorted by occurrences', async ({facet}) => {
const values = await facet.facetValueOccurrences.allTextContents();
const sortedValues = [...values]
.sort((a, b) => {
const numA = parseInt(a.replace(/[^\d]/g, ''), 10);
const numB = parseInt(b.replace(/[^\d]/g, ''), 10);
return numA - numB;
})
.reverse();
expect(values).toEqual(sortedValues);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ export class AtomicFacetPageObject extends BasePageObject<'atomic-facet'> {
return this.page.locator('ul[part="values"] > li');
}

get facetValueLabel() {
return this.page.locator('ul[part="values"] > li span[part="value-label"]');
}

get facetValueOccurrences() {
return this.page.locator('ul[part="values"] > li span[part="value-count"]');
}

get facetSearchMoreMatchesFor() {
return this.page.getByRole('button', {name: 'More matches for p'});
}
Expand Down
2 changes: 2 additions & 0 deletions packages/headless/src/features/facets/facet-api/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ export interface SortCriteria<
| 'score'
| 'alphanumeric'
| 'alphanumericDescending'
| 'alphanumericNatural'
| 'alphanumericNaturalDescending'
| 'ascending'
| 'descending'
| 'occurrences'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,18 @@ export const facetSortCriteria: FacetSortCriterion[] = [
'alphanumericDescending',
'occurrences',
'automatic',
'alphanumericNatural',
'alphanumericNaturalDescending',
];

export type FacetSortCriterion =
| 'score'
| 'alphanumeric'
| 'alphanumericDescending'
| 'occurrences'
| 'automatic';
| 'automatic'
| 'alphanumericNatural'
| 'alphanumericNaturalDescending';

export type FacetSortOrder = 'ascending' | 'descending';

Expand Down
15 changes: 15 additions & 0 deletions packages/headless/src/features/search/search-request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,21 @@ describe('search request', () => {
type: 'alphanumeric',
});
});
it('#searchRequest returns the facet state alphanumericNaturalDescending #sortCriteria', async () => {
const request = buildMockFacetRequest({
field: 'objecttype',
sortCriteria: 'alphanumericNaturalDescending',
});
state.facetSet[1] = buildMockFacetSlice({request});
const {facets} = (
await buildSearchRequest(state, buildMockNavigatorContextProvider()())
).request;

expect(facets?.map((f) => f.sortCriteria)).toContainEqual({
order: 'descending',
type: 'alphanumericNatural',
});
});

it('#searchRequest returns the facets in the state #numericFacetSet', async () => {
const request = buildMockNumericFacetRequest({
Expand Down
23 changes: 17 additions & 6 deletions packages/headless/src/features/search/search-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ import {mapSearchRequest} from './search-mappings.js';
type StateNeededBySearchRequest = ConfigurationSection &
Partial<SearchAppState>;

type SortCriteria = {
type: string;
order: string;
};

export const buildSearchRequest = async (
state: StateNeededBySearchRequest,
navigatorContext: NavigatorContext,
Expand Down Expand Up @@ -147,20 +152,26 @@ function getAllFacets(state: StateNeededBySearchRequest) {
];
}

const sortCriteriaMap: Record<string, SortCriteria> = {
alphanumericDescending: {type: 'alphanumeric', order: 'descending'},
alphanumericNaturalDescending: {
type: 'alphanumericNatural',
order: 'descending',
},
};

function getSpecificFacetRequests<T extends FacetSetState>(state: T) {
return getFacetRequests(state).map((request) => {
/* The Search API does not support 'alphanumericDescending' as a string value and instead relies on a new sort mechanism to specify sort order.
At the moment, this is only supported for alphanumeric sorting, but will likely transition to this pattern for other types in the future. */
if (request.sortCriteria === 'alphanumericDescending') {
const sortCriteria =
sortCriteriaMap[request.sortCriteria as keyof typeof sortCriteriaMap];
if (sortCriteria) {
return {
...request,
sortCriteria: {
type: 'alphanumeric',
order: 'descending',
},
sortCriteria,
};
}

return request;
});
}
Expand Down
23 changes: 17 additions & 6 deletions packages/headless/src/utils/facet-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import {ConfigurationSection} from '../state/state-sections.js';
type StateNeededBySearchRequest = ConfigurationSection &
Partial<SearchAppState>;

type SortCriteria = {
type: string;
order: string;
};

export function sortFacets<T extends {facetId: string}>(
facets: T[],
sortOrder: string[]
Expand Down Expand Up @@ -40,20 +45,26 @@ function getRangeFacetRequests<T extends RangeFacetSetState>(state: T) {
});
}

const sortCriteriaMap: Record<string, SortCriteria> = {
alphanumericDescending: {type: 'alphanumeric', order: 'descending'},
alphanumericNaturalDescending: {
type: 'alphanumericNatural',
order: 'descending',
},
};

function getSpecificFacetRequests<T extends FacetSetState>(state: T) {
return getFacetRequests(state).map((request) => {
/* The Search API does not support 'alphanumericDescending' as a string value and instead relies on a new sort mechanism to specify sort order.
At the moment, this is only supported for alphanumeric sorting, but will likely transition to this pattern for other types in the future. */
if (request.sortCriteria === 'alphanumericDescending') {
const sortCriteria =
sortCriteriaMap[request.sortCriteria as keyof typeof sortCriteriaMap];
if (sortCriteria) {
return {
...request,
sortCriteria: {
type: 'alphanumeric',
order: 'descending',
},
sortCriteria,
};
}

return request;
});
}
Expand Down
Loading