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

Update default FilterSearch behavior #333

Merged
merged 4 commits into from
Nov 15, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
37 changes: 33 additions & 4 deletions src/components/FilterSearch.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AutocompleteResult, FieldValueStaticFilter, FilterSearchResponse, SearchParameterField, StaticFilter, useSearchActions, useSearchState } from '@yext/search-headless-react';
import { AutocompleteResult, FieldValueStaticFilter, FilterSearchResponse, SearchParameterField, SelectableStaticFilter, StaticFilter, useSearchActions, useSearchState } from '@yext/search-headless-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useComposedCssClasses } from '../hooks/useComposedCssClasses';
import { useSynchronizedRequest } from '../hooks/useSynchronizedRequest';
Expand Down Expand Up @@ -109,6 +109,11 @@ export function FilterSearch({
const [currentFilter, setCurrentFilter] = useState<StaticFilter>();
const [filterQuery, setFilterQuery] = useState<string>();
const staticFilters = useSearchState(state => state.filters.static);
const matchingFilters: SelectableStaticFilter[] = useMemo(() => {
return staticFilters?.filter(({ filter, selected }) =>
selected && filter.kind === 'fieldValue' && searchFields.some(s => s.fieldApiName === filter.fieldId)
) ?? [];
}, [staticFilters, searchFields]);

const [
filterSearchResponse,
Expand All @@ -123,14 +128,33 @@ export function FilterSearch({
);

useEffect(() => {
if (matchingFilters.length > 1 && !onSelect) {
Copy link
Contributor

Choose a reason for hiding this comment

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

I feel like it may be beneficial to warn user regardless if onSelect is provided here?

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 was a deliberate decision because the thinking is that if you provide your own onSelect prop, you might be fine with having multiple filters selected in state at once and you wouldn't want this warning to to be logged. it's only assumed to be a problem for the default component behavior. people shouldn't have to fork the component just to remove this warning if they don't want clobbering behavior

console.warn('More than one selected static filter found that matches the filter search fields.'
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: can we add to the message that we will use the first selected static filter found?

Copy link
Contributor Author

@nmanu1 nmanu1 Nov 15, 2022

Choose a reason for hiding this comment

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

what do you think about adding "Picking one filter to display in the input." instead? because technically, it will only pick the first filter it finds if the currentFilter is not selected in state anymore. or does that seem too vague?

Edit: updated to "Picking one filter to display in the input." and I also added the specific search fields to make it more clear in case there are multiple filter search components on the page

+ ' Please update the state to remove the extra filters.');
}

if (currentFilter && staticFilters?.find(f =>
isDuplicateStaticFilter(f.filter, currentFilter) && !f.selected
isDuplicateStaticFilter(f.filter, currentFilter) && f.selected
)) {
return;
}

if (matchingFilters.length === 0) {
clearFilterSearchResponse();
setCurrentFilter(undefined);
setFilterQuery('');
} else {
setCurrentFilter(matchingFilters[0].filter);
executeFilterSearch(matchingFilters[0].displayName);
}
}, [clearFilterSearchResponse, currentFilter, staticFilters]);
}, [
clearFilterSearchResponse,
currentFilter,
staticFilters,
executeFilterSearch,
onSelect,
matchingFilters
]);

const sections = useMemo(() => {
return filterSearchResponse?.sections.filter(section => section.results.length > 0) ?? [];
Expand Down Expand Up @@ -159,6 +183,11 @@ export function FilterSearch({
});
}

if (matchingFilters.length > 1) {
console.warn('More than one selected static filter found that matches the filter search fields.'
+ ' Unselecting all existing matching filters and selecting the new filter.');
}
matchingFilters.forEach(f => searchActions.setFilterOption({ filter: f.filter, selected: false }));
if (currentFilter) {
searchActions.setFilterOption({ filter: currentFilter, selected: false });
}
Expand All @@ -171,7 +200,7 @@ export function FilterSearch({
searchActions.resetFacets();
executeSearch(searchActions);
}
}, [currentFilter, searchActions, executeFilterSearch, onSelect, searchOnSelect]);
}, [currentFilter, searchActions, executeFilterSearch, onSelect, searchOnSelect, matchingFilters]);

const meetsSubmitCritera = useCallback(index => index >= 0, []);

Expand Down
157 changes: 155 additions & 2 deletions tests/components/FilterSearch.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,38 @@ const mockedState: Partial<State> = {
}
};

const mockedStateWithSingleFilter: Partial<State> = {
...mockedState,
filters: {
static: [{
filter: {
kind: 'fieldValue',
fieldId: 'name',
matcher: Matcher.Equals,
value: 'Real Person'
},
selected: true,
displayName: 'Real Person'
}]
}
};

const mockedStateWithMultipleFilters: Partial<State> = {
...mockedState,
filters: {
static: [...(mockedStateWithSingleFilter.filters?.static ?? []), {
filter: {
kind: 'fieldValue',
fieldId: 'name',
matcher: Matcher.Equals,
value: 'Fake Person'
},
selected: true,
displayName: 'Fake Person'
}]
}
};

describe('search with section labels', () => {
it('renders the filter search bar, "Filter" label, and default placeholder text', () => {
renderFilterSearch({ searchFields: searchFieldsProp, label: 'Filter' });
Expand Down Expand Up @@ -179,6 +211,124 @@ describe('search with section labels', () => {
});
});

it('updates input to show display name of matching filter in state when no current filter', async () => {
renderFilterSearch(undefined, mockedStateWithSingleFilter);
const searchBarElement = screen.getByRole('textbox');
expect(searchBarElement).toHaveValue('Real Person');
});

it('logs a warning when multiple matching filters in state and no current filter selected', async () => {
const consoleWarnSpy = jest.spyOn(global.console, 'warn').mockImplementation();
renderFilterSearch(undefined, mockedStateWithMultipleFilters);
const searchBarElement = screen.getByRole('textbox');
expect(searchBarElement).toHaveValue('Real Person');
expect(consoleWarnSpy).toBeCalledWith(
'More than one selected static filter found that matches the filter search fields.'
+ ' Please update the state to remove the extra filters.'
);
});

it('does not log a warning for multiple matching filters in state if onSelect is passed', async () => {
const consoleWarnSpy = jest.spyOn(global.console, 'warn').mockImplementation();
const mockedOnSelect = jest.fn();
renderFilterSearch(
{ searchFields: searchFieldsProp, onSelect: mockedOnSelect },
mockedStateWithMultipleFilters
);
const searchBarElement = screen.getByRole('textbox');
expect(searchBarElement).toHaveValue('Real Person');
expect(consoleWarnSpy).not.toHaveBeenCalled();
});

it('unselects single matching filter in state when a new filter is selected and doesn\'t log warning', async () => {
const consoleWarnSpy = jest.spyOn(global.console, 'warn').mockImplementation();
renderFilterSearch(undefined, mockedStateWithSingleFilter);
const executeFilterSearch = jest
.spyOn(SearchHeadless.prototype, 'executeFilterSearch')
.mockResolvedValue(labeledFilterSearchResponse);
const setFilterOption = jest.spyOn(SearchHeadless.prototype, 'setFilterOption');
const searchBarElement = screen.getByRole('textbox');

userEvent.clear(searchBarElement);
userEvent.type(searchBarElement, 'n');
await waitFor(() => expect(executeFilterSearch).toHaveBeenCalled());
await waitFor(() => screen.findByText('first name 1'));
userEvent.type(searchBarElement, '{enter}');
await waitFor(() => {
expect(setFilterOption).toBeCalledWith({
filter: {
kind: 'fieldValue',
fieldId: 'name',
matcher: Matcher.Equals,
value: 'Real Person'
},
selected: false
});
});
expect(setFilterOption).toBeCalledWith({
filter: {
kind: 'fieldValue',
fieldId: 'name',
matcher: Matcher.Equals,
value: 'first name 1'
},
displayName: 'first name 1',
selected: true
});

expect(consoleWarnSpy).not.toHaveBeenCalled();
});

it('unselects multiple matching filters in state when a new filter is selected and logs warning', async () => {
const consoleWarnSpy = jest.spyOn(global.console, 'warn').mockImplementation();
renderFilterSearch(undefined, mockedStateWithMultipleFilters);
const executeFilterSearch = jest
.spyOn(SearchHeadless.prototype, 'executeFilterSearch')
.mockResolvedValue(labeledFilterSearchResponse);
const setFilterOption = jest.spyOn(SearchHeadless.prototype, 'setFilterOption');
const searchBarElement = screen.getByRole('textbox');

userEvent.clear(searchBarElement);
userEvent.type(searchBarElement, 'n');
await waitFor(() => expect(executeFilterSearch).toHaveBeenCalled());
await waitFor(() => screen.findByText('first name 1'));
userEvent.type(searchBarElement, '{enter}');
await waitFor(() => {
expect(setFilterOption).toBeCalledWith({
filter: {
kind: 'fieldValue',
fieldId: 'name',
matcher: Matcher.Equals,
value: 'Real Person'
},
selected: false
});
});
expect(setFilterOption).toBeCalledWith({
filter: {
kind: 'fieldValue',
fieldId: 'name',
matcher: Matcher.Equals,
value: 'Fake Person'
},
selected: false
});
expect(setFilterOption).toBeCalledWith({
filter: {
kind: 'fieldValue',
fieldId: 'name',
matcher: Matcher.Equals,
value: 'first name 1'
},
displayName: 'first name 1',
selected: true
});
expect(consoleWarnSpy).toBeCalledWith(
'More than one selected static filter found that matches the filter search fields.'
+ ' Unselecting all existing matching filters and selecting the new filter.'
);
});

it('executes onSelect function when a filter is selected', async () => {
const mockedOnSelect = jest.fn();
const setFilterOption = jest.spyOn(SearchHeadless.prototype, 'setFilterOption');
Expand Down Expand Up @@ -460,8 +610,11 @@ describe('screen reader', () => {
});
});

function renderFilterSearch(props: FilterSearchProps = { searchFields: searchFieldsProp }): RenderResult {
return render(<SearchHeadlessContext.Provider value={generateMockedHeadless(mockedState)}>
function renderFilterSearch(
props: FilterSearchProps = { searchFields: searchFieldsProp },
state = mockedState
): RenderResult {
return render(<SearchHeadlessContext.Provider value={generateMockedHeadless(state)}>
<FilterSearch {...props} />
</SearchHeadlessContext.Provider>);
}
Expand Down