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/heal search debounce #1232

Merged
merged 20 commits into from
Mar 9, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
96426cc
feat(healSearchDebounce): Initial commit
jarvisraymond-uchicago Feb 8, 2023
43f0aed
feat(healSearchDebounce): Wrote unit test and organized code
jarvisraymond-uchicago Feb 9, 2023
c75f83a
feat(healSearchDebounce): Ran eslint on changed files
jarvisraymond-uchicago Feb 9, 2023
8ebc935
feat(healSearchDebounce): Changed import of DebounceSearch for Jest test
jarvisraymond-uchicago Feb 9, 2023
ac65aed
test(addReactTestingLibrary): Refactored and separated out code so te…
jarvisraymond-uchicago Feb 9, 2023
6cfb52f
feat(healSearchDebounce): Renamed function dbs to debounceSearch for …
jarvisraymond-uchicago Feb 10, 2023
c16dd59
feat(healSearchDebounce): Renamed organized functions only used for s…
jarvisraymond-uchicago Feb 10, 2023
7296e9f
feat(healSearchDebounce): Created test for doDebounceSearch.ts
jarvisraymond-uchicago Feb 10, 2023
9c32e4b
test(addReactTestingLibrary): Removed console.log
jarvisraymond-uchicago Feb 10, 2023
a620768
Merge branch 'master' into feat/healSearchDebounce
jarvisraymond-uchicago Feb 10, 2023
88f0aa4
Merge branch 'master' into feat/healSearchDebounce
jarvisraymond-uchicago Feb 23, 2023
b77a49e
feat(healSearchDebounce): Converted JS function to TS and changed arr…
jarvisraymond-uchicago Feb 23, 2023
d2e8790
feat(healSearchDebounce): Ran eslint on changed files
jarvisraymond-uchicago Feb 23, 2023
1b900cd
feat(healSearchDebounce): Fixed TS errors
jarvisraymond-uchicago Feb 23, 2023
38540b4
feat(healSearchDebounce): Formatted code
jarvisraymond-uchicago Feb 23, 2023
d98faa6
feat(healSearchDebounce): Removed old comment
jarvisraymond-uchicago Feb 23, 2023
df74c73
feat(healSearchDebounce): Refactored test to use a test object
jarvisraymond-uchicago Feb 23, 2023
1ab5a85
feat(healSearchDebounce): Removed duplicated code, added import for F…
jarvisraymond-uchicago Mar 9, 2023
1fad804
Merge branch 'master' into feat/healSearchDebounce
jarvisraymond-uchicago Mar 9, 2023
5940e63
feat(healSearchDebounce): ran eslint and fixed imports for doSearchFi…
jarvisraymond-uchicago Mar 9, 2023
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
240 changes: 78 additions & 162 deletions src/Discovery/Discovery.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import React, { useState, useEffect, ReactNode } from 'react';
import React, {
useState, useEffect, ReactNode, useMemo,
} from 'react';
import * as JsSearch from 'js-search';
import {
Tag, Popover, Space, Collapse, Button, Dropdown, Menu, Pagination, Tooltip,
Tag, Popover, Space, Collapse, Button, Dropdown, Pagination, Tooltip,
} from 'antd';
import {
LockOutlined,
Expand All @@ -18,9 +20,9 @@ import {
MinusCircleOutlined,
} from '@ant-design/icons';
import Checkbox from 'antd/lib/checkbox/Checkbox';
import MenuItem from 'antd/lib/menu/MenuItem';
import { debounce } from 'lodash';
import doDebounceSearch from './Utils/Search/doDebounceSearch';
import { DiscoveryConfig } from './DiscoveryConfig';
import './Discovery.css';
import DiscoverySummary from './DiscoverySummary';
import DiscoveryTagViewer from './DiscoveryTagViewer';
import DiscoveryDropdownTagViewer from './DiscoveryDropdownTagViewer';
Expand All @@ -29,7 +31,8 @@ import DiscoveryAdvancedSearchPanel from './DiscoveryAdvancedSearchPanel';
import { ReduxDiscoveryActionBar, ReduxDiscoveryDetails } from './reduxer';
import DiscoveryMDSSearch from './DiscoveryMDSSearch';
import DiscoveryAccessibilityLinks from './DiscoveryAccessibilityLinks';
import { JsxElement } from 'typescript';
import doSearchFilterSort from './Utils/Search/doSearchFilterSort';
import './Discovery.css';

export const accessibleFieldName = '__accessible';

Expand Down Expand Up @@ -106,54 +109,54 @@ const accessibleDataFilterToggle = () => {

export const renderFieldContent = (content: any, contentType: 'string' | 'paragraphs' | 'number' | 'link' | 'tags' = 'string', config: DiscoveryConfig): React.ReactNode => {
switch (contentType) {
case 'string':
if (Array.isArray(content)) {
return content.join(', ');
}
return content;
case 'number':
if (Array.isArray(content)) {
return content.join(', ');
}
return content.toLocaleString();
case 'paragraphs':
return content.split('\n').map((paragraph, i) => <p key={i}>{paragraph}</p>);
case 'link':
case 'string':
if (Array.isArray(content)) {
return content.join(', ');
}
return content;
case 'number':
if (Array.isArray(content)) {
return content.join(', ');
}
return content.toLocaleString();
case 'paragraphs':
return content.split('\n').map((paragraph, i) => <p key={i}>{paragraph}</p>);
case 'link':
return (
<a
onClick={(ev) => ev.stopPropagation()}
onKeyPress={(ev) => ev.stopPropagation()}
href={content}
target='_blank'
rel='noreferrer'
>
{content}
</a>
);
case 'tags':
if (!content || !content.map) {
return null;
}
return content.map(({ name, category }) => {
const color = getTagColor(category, config);
return (
<a
onClick={(ev) => ev.stopPropagation()}
onKeyPress={(ev) => ev.stopPropagation()}
href={content}
target='_blank'
rel='noreferrer'
<Tag
key={name}
role='button'
tabIndex={0}
className='discovery-header__tag-btn discovery-tag discovery-tag--selected'
aria-label={name}
style={{
backgroundColor: color,
borderColor: color,
}}
>
{content}
</a>
{name}
</Tag>
);
case 'tags':
if (!content || !content.map) {
return null;
}
return content.map(({ name, category }) => {
const color = getTagColor(category, config);
return (
<Tag
key={name}
role='button'
tabIndex={0}
className='discovery-header__tag-btn discovery-tag discovery-tag--selected'
aria-label={name}
style={{
backgroundColor: color,
borderColor: color,
}}
>
{name}
</Tag>
);
});
default:
throw new Error(`Unrecognized content type ${contentType}. Check the 'study_page_fields' section of the Discovery config.`);
});
default:
throw new Error(`Unrecognized content type ${contentType}. Check the 'study_page_fields' section of the Discovery config.`);
}
};

Expand All @@ -178,82 +181,17 @@ const highlightSearchTerm = (value: string, searchTerm: string, highlighClassNam
};
};

const filterByTags = (studies: any[], selectedTags: any, config: DiscoveryConfig): any[] => {
// if no tags selected, show all studies
if (Object.values(selectedTags).every((selected) => !selected)) {
return studies;
}
const tagField = config.minimalFieldMapping.tagsListFieldName;
return studies.filter((study) => study[tagField]?.some((tag) => selectedTags[tag.name]));
};

interface FilterState {
export interface FilterState {
[key: string]: { [value: string]: boolean }
}

const filterByAdvSearch = (studies: any[], advSearchFilterState: FilterState, config: DiscoveryConfig, filterMultiSelectionLogic: string): any[] => {
// if no filters active, show all studies
const noFiltersActive = Object.values(advSearchFilterState).every((selectedValues) => {
if (Object.values(selectedValues).length === 0) {
return true;
}
if (Object.values(selectedValues).every((selected) => !selected)) {
return true;
}
return false;
});
if (noFiltersActive) {
return studies;
}

// Combine within filters as AND
if (filterMultiSelectionLogic === 'AND') {
return studies.filter((study) => Object.keys(advSearchFilterState).every((filterName) => {
const filterValues = Object.keys(advSearchFilterState[filterName]);
// Handle the edge case where no values in this filter are selected
if (filterValues.length === 0) {
return true;
}
if (!config.features.advSearchFilters) {
return false;
}
const studyFilters = study[config.features.advSearchFilters.field];
if (!studyFilters || !studyFilters.length) {
return false;
}

const studyFilterValues = studyFilters.filter(({ key }) => key === filterName)
.map(({ value }) => value);
return filterValues.every((value) => studyFilterValues.includes(value));
}));
}

// Combine within filters as OR
return studies.filter((study) => Object.keys(advSearchFilterState).some((filterName) => {
const filterValues = Object.keys(advSearchFilterState[filterName]);
// Handle the edge case where no values in this filter are selected
if (filterValues.length === 0) {
return true;
}
if (!config.features.advSearchFilters) {
return false;
}
const studyFilters = study[config.features.advSearchFilters.field];
if (!studyFilters || !studyFilters.length) {
return false;
}

return studyFilters.some(({ key, value }) => key === filterName && filterValues.includes(value));
}));
};

export interface DiscoveryResource {
[accessibleFieldName]: AccessLevel,
[any: string]: any,
tags?: { name: string, category: string }[]
}

interface Props {
export interface Props {
config: DiscoveryConfig,
studies: DiscoveryResource[],
studyRegistrationValidationField: string,
Expand All @@ -276,8 +214,8 @@ interface Props {

const Discovery: React.FunctionComponent<Props> = (props: Props) => {
const { config } = props;

const [jsSearch, setJsSearch] = useState(null);
const [executedSearchesCount, setExecutedSearchesCount] = useState(0);
const [accessibilityFilterVisible, setAccessibilityFilterVisible] = useState(false);
const [modalVisible, setModalVisible] = useState(false);
const [filtersVisible, setFiltersVisible] = useState(false);
Expand All @@ -299,52 +237,30 @@ const Discovery: React.FunctionComponent<Props> = (props: Props) => {
props.onSearchChange(value);
};

const doSearchFilterSort = () => {
let filteredResources = props.studies;
if (jsSearch && props.searchTerm) {
filteredResources = jsSearch.search(props.searchTerm);
}
filteredResources = filterByTags(
filteredResources,
props.selectedTags,
config,
);

if (config.features.advSearchFilters && config.features.advSearchFilters.enabled) {
filteredResources = filterByAdvSearch(
filteredResources,
filterState,
config,
filterMultiSelectionLogic,
);
}

if (props.config.features.authorization.enabled) {
filteredResources = filteredResources.filter(
(resource) => props.accessFilters[resource[accessibleFieldName]],
);
}

filteredResources = filteredResources.sort(
(a, b) => {
if (props.accessSortDirection === AccessSortDirection.DESCENDING) {
return a[accessibleFieldName] - b[accessibleFieldName];
} if (props.accessSortDirection === AccessSortDirection.ASCENDING) {
return b[accessibleFieldName] - a[accessibleFieldName];
}
return 0;
},
);
setVisibleResources(filteredResources);
const debouncingDelayInMilliseconds = 500;
const memoizedDebouncedSearch = useMemo(
() => debounce(doSearchFilterSort, debouncingDelayInMilliseconds),
[],
);
const parametersForDoSearchFilterSort = {
props,
jsSearch,
config,
setVisibleResources,
filterState,
filterMultiSelectionLogic,
accessibleFieldName,
AccessSortDirection,
};

useEffect(doSearchFilterSort,
[props.searchTerm,
props.accessSortDirection,
props.studies,
props.pagination,
props.accessFilters,
props.selectedTags,
useEffect(
() => doDebounceSearch(parametersForDoSearchFilterSort, memoizedDebouncedSearch, executedSearchesCount, setExecutedSearchesCount), [
props.searchTerm,
props.accessSortDirection,
props.studies,
props.pagination,
props.accessFilters,
props.selectedTags,
filterMultiSelectionLogic,
filterState],
);
Expand Down
37 changes: 37 additions & 0 deletions src/Discovery/Utils/Search/doDebounceSearch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import doDebounceSearch from './doDebounceSearch';
import doSearchFilterSort from './doSearchFilterSort';

jest.mock('./doSearchFilterSort');

describe('doDebounceSearch', () => {
let memoizedDebouncedSearch;
let setExecutedSearchesCount;
beforeEach(() => {
memoizedDebouncedSearch = jest.fn(() => {});
setExecutedSearchesCount = jest.fn(() => {});
});

afterEach(() => {
jest.clearAllMocks();
});

it('should execute doSearchFilterSort initially without debouncing', () => {
doDebounceSearch([1, 2, 3], memoizedDebouncedSearch, 0, setExecutedSearchesCount);
expect(doSearchFilterSort).toHaveBeenCalledWith(1, 2, 3);
expect(memoizedDebouncedSearch).not.toHaveBeenCalled();
expect(setExecutedSearchesCount).toHaveBeenCalledWith(1);

jest.clearAllMocks();
doDebounceSearch([4, 5, 6], memoizedDebouncedSearch, 1, setExecutedSearchesCount);
expect(doSearchFilterSort).toHaveBeenCalledWith(4, 5, 6);
expect(memoizedDebouncedSearch).not.toHaveBeenCalled();
expect(setExecutedSearchesCount).toHaveBeenCalledWith(2);
});

it('should debounce the doSearchFilterSort call when executedSearchesCount >= 2', () => {
doDebounceSearch([1, 2, 3], memoizedDebouncedSearch, 2, setExecutedSearchesCount);
expect(doSearchFilterSort).not.toHaveBeenCalled();
expect(memoizedDebouncedSearch).toHaveBeenCalledWith(1, 2, 3);
expect(setExecutedSearchesCount).not.toHaveBeenCalled();
});
});
19 changes: 19 additions & 0 deletions src/Discovery/Utils/Search/doDebounceSearch.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import doSearchFilterSort from './doSearchFilterSort';

const doDebounceSearch = (
parametersForDoSearchFilterSort: {},
memoizedDebouncedSearch: (...args: any[]) => void,
executedSearchesCount: number,
setExecutedSearchesCount: (count: number) => void,
) => {
const initialSearchesWithoutDebounce = 2;
// Execute searches initially without debounce to decrease page load time
if (executedSearchesCount < initialSearchesWithoutDebounce) {
setExecutedSearchesCount(executedSearchesCount + 1);
return doSearchFilterSort(parametersForDoSearchFilterSort);
}
// Otherwise debounce the calls
// return debounce(doSearchFilterSort, debounceDelayInMilliseconds);
return memoizedDebouncedSearch(parametersForDoSearchFilterSort);
};
export default doDebounceSearch;
Loading