Moved dates handling in short URLs list to query

This commit is contained in:
Alejandro Celaya 2021-11-10 22:25:56 +01:00
parent ed038b9799
commit 21b8e05e35
6 changed files with 37 additions and 35 deletions

View file

@ -14,23 +14,20 @@ import { ShortUrlListRouteParams, useShortUrlsQuery } from './helpers/hooks';
import './SearchBar.scss'; import './SearchBar.scss';
export interface SearchBarProps extends RouteChildrenProps<ShortUrlListRouteParams> { export interface SearchBarProps extends RouteChildrenProps<ShortUrlListRouteParams> {
listShortUrls: (params: ShortUrlsListParams) => void;
shortUrlsListParams: ShortUrlsListParams; shortUrlsListParams: ShortUrlsListParams;
} }
const dateOrNull = (date?: string) => date ? parseISO(date) : null; const dateOrNull = (date?: string) => date ? parseISO(date) : null;
const SearchBar = (colorGenerator: ColorGenerator) => ( const SearchBar = (colorGenerator: ColorGenerator) => ({ shortUrlsListParams, ...rest }: SearchBarProps) => {
{ listShortUrls, shortUrlsListParams, ...rest }: SearchBarProps, const [{ search, tags, startDate, endDate }, toFirstPage ] = useShortUrlsQuery(rest);
) => { const selectedTags = tags?.split(',') ?? [];
const [{ search, tags }, toFirstPage ] = useShortUrlsQuery(rest);
const selectedTags = tags?.split(',').map(decodeURIComponent) ?? [];
const setDates = pipe( const setDates = pipe(
({ startDate, endDate }: DateRange) => ({ ({ startDate, endDate }: DateRange) => ({
startDate: formatIsoDate(startDate) ?? undefined, startDate: formatIsoDate(startDate) ?? undefined,
endDate: formatIsoDate(endDate) ?? undefined, endDate: formatIsoDate(endDate) ?? undefined,
}), }),
(dates) => listShortUrls({ ...shortUrlsListParams, ...dates }), toFirstPage,
); );
const setSearch = pipe( const setSearch = pipe(
(searchTerm: string) => isEmpty(searchTerm) ? undefined : searchTerm, (searchTerm: string) => isEmpty(searchTerm) ? undefined : searchTerm,
@ -52,8 +49,8 @@ const SearchBar = (colorGenerator: ColorGenerator) => (
<DateRangeSelector <DateRangeSelector
defaultText="All short URLs" defaultText="All short URLs"
initialDateRange={{ initialDateRange={{
startDate: dateOrNull(shortUrlsListParams.startDate), startDate: dateOrNull(startDate),
endDate: dateOrNull(shortUrlsListParams.endDate), endDate: dateOrNull(endDate),
}} }}
onDatesChange={setDates} onDatesChange={setDates}
/> />

View file

@ -40,8 +40,8 @@ const ShortUrlsList = (ShortUrlsTable: FC<ShortUrlsTableProps>, SearchBar: FC) =
field: orderBy && (head(keys(orderBy)) as OrderableFields), field: orderBy && (head(keys(orderBy)) as OrderableFields),
dir: orderBy && head(values(orderBy)), dir: orderBy && head(values(orderBy)),
}); });
const [{ tags, search }, toFirstPage ] = useShortUrlsQuery({ history, match, location }); const [{ tags, search, startDate, endDate }, toFirstPage ] = useShortUrlsQuery({ history, match, location });
const decodedTags = useMemo(() => tags?.split(',').map(decodeURIComponent) ?? [], [ tags ]); const selectedTags = useMemo(() => tags?.split(',') ?? [], [ tags ]);
const { pagination } = shortUrlsList?.shortUrls ?? {}; const { pagination } = shortUrlsList?.shortUrls ?? {};
const refreshList = (extraParams: ShortUrlsListParams) => listShortUrls({ ...shortUrlsListParams, ...extraParams }); const refreshList = (extraParams: ShortUrlsListParams) => listShortUrls({ ...shortUrlsListParams, ...extraParams });
@ -53,14 +53,16 @@ const ShortUrlsList = (ShortUrlsTable: FC<ShortUrlsTableProps>, SearchBar: FC) =
handleOrderBy(field, determineOrderDir(field, order.field, order.dir)); handleOrderBy(field, determineOrderDir(field, order.field, order.dir));
const renderOrderIcon = (field: OrderableFields) => <TableOrderIcon currentOrder={order} field={field} />; const renderOrderIcon = (field: OrderableFields) => <TableOrderIcon currentOrder={order} field={field} />;
const addTag = pipe( const addTag = pipe(
(newTag: string) => [ ...new Set([ ...decodedTags, newTag ]) ].join(','), (newTag: string) => [ ...new Set([ ...selectedTags, newTag ]) ].join(','),
(tags) => toFirstPage({ tags }), (tags) => toFirstPage({ tags }),
); );
useEffect(() => resetShortUrlParams, []); useEffect(() => resetShortUrlParams, []);
useEffect(() => { useEffect(() => {
refreshList({ page: match.params.page, searchTerm: search, tags: decodedTags, itemsPerPage: undefined }); refreshList(
}, [ match.params.page, search, decodedTags ]); { page: match.params.page, searchTerm: search, tags: selectedTags, itemsPerPage: undefined, startDate, endDate },
);
}, [ match.params.page, search, selectedTags, startDate, endDate ]);
return ( return (
<> <>

View file

@ -14,6 +14,8 @@ export interface ShortUrlListRouteParams {
interface ShortUrlsQuery { interface ShortUrlsQuery {
tags?: string; tags?: string;
search?: string; search?: string;
startDate?: string;
endDate?: string;
} }
export const useShortUrlsQuery = ({ history, location, match }: ServerIdRouteProps): [ShortUrlsQuery, ToFirstPage] => { export const useShortUrlsQuery = ({ history, location, match }: ServerIdRouteProps): [ShortUrlsQuery, ToFirstPage] => {

View file

@ -52,7 +52,7 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator, withRouter:
// Services // Services
bottle.serviceFactory('SearchBar', SearchBar, 'ColorGenerator'); bottle.serviceFactory('SearchBar', SearchBar, 'ColorGenerator');
bottle.decorator('SearchBar', connect([ 'shortUrlsListParams' ], [ 'listShortUrls' ])); bottle.decorator('SearchBar', connect([ 'shortUrlsListParams' ]));
bottle.decorator('SearchBar', withRouter); bottle.decorator('SearchBar', withRouter);
// Actions // Actions

View file

@ -22,18 +22,16 @@ export interface DateRangeSelectorProps {
export const DateRangeSelector = ( export const DateRangeSelector = (
{ onDatesChange, initialDateRange, defaultText, disabled }: DateRangeSelectorProps, { onDatesChange, initialDateRange, defaultText, disabled }: DateRangeSelectorProps,
) => { ) => {
const [ activeInterval, setActiveInterval ] = useState( const initialIntervalIsRange = rangeIsInterval(initialDateRange);
rangeIsInterval(initialDateRange) ? initialDateRange : undefined, const [ activeInterval, setActiveInterval ] = useState(initialIntervalIsRange ? initialDateRange : undefined);
); const [ activeDateRange, setActiveDateRange ] = useState(initialIntervalIsRange ? undefined : initialDateRange);
const [ activeDateRange, setActiveDateRange ] = useState(
!rangeIsInterval(initialDateRange) ? initialDateRange : undefined,
);
const updateDateRange = (dateRange: DateRange) => { const updateDateRange = (dateRange: DateRange) => {
setActiveInterval(dateRangeIsEmpty(dateRange) ? 'all' : undefined); setActiveInterval(dateRangeIsEmpty(dateRange) ? 'all' : undefined);
setActiveDateRange(dateRange); setActiveDateRange(dateRange);
onDatesChange(dateRange); onDatesChange(dateRange);
}; };
const updateInterval = (dateInterval: DateInterval) => () => { const updateInterval = (dateInterval: DateInterval) => {
setActiveInterval(dateInterval); setActiveInterval(dateInterval);
setActiveDateRange(undefined); setActiveDateRange(undefined);
onDatesChange(intervalToDateRange(dateInterval)); onDatesChange(intervalToDateRange(dateInterval));
@ -41,11 +39,7 @@ export const DateRangeSelector = (
return ( return (
<DropdownBtn disabled={disabled} text={rangeOrIntervalToString(activeInterval ?? activeDateRange) ?? defaultText}> <DropdownBtn disabled={disabled} text={rangeOrIntervalToString(activeInterval ?? activeDateRange) ?? defaultText}>
<DateIntervalDropdownItems <DateIntervalDropdownItems allText={defaultText} active={activeInterval} onChange={updateInterval} />
allText={defaultText}
active={activeInterval}
onChange={(interval) => updateInterval(interval)()}
/>
<DropdownItem divider /> <DropdownItem divider />
<DropdownItem header>Custom:</DropdownItem> <DropdownItem header>Custom:</DropdownItem>
<DropdownItem text> <DropdownItem text>

View file

@ -2,6 +2,7 @@ import { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { History, Location } from 'history'; import { History, Location } from 'history';
import { match } from 'react-router'; import { match } from 'react-router';
import { formatISO } from 'date-fns';
import searchBarCreator, { SearchBarProps } from '../../src/short-urls/SearchBar'; import searchBarCreator, { SearchBarProps } from '../../src/short-urls/SearchBar';
import SearchField from '../../src/utils/SearchField'; import SearchField from '../../src/utils/SearchField';
import Tag from '../../src/tags/helpers/Tag'; import Tag from '../../src/tags/helpers/Tag';
@ -11,13 +12,12 @@ import { ShortUrlListRouteParams } from '../../src/short-urls/helpers/hooks';
describe('<SearchBar />', () => { describe('<SearchBar />', () => {
let wrapper: ShallowWrapper; let wrapper: ShallowWrapper;
const listShortUrlsMock = jest.fn();
const SearchBar = searchBarCreator(Mock.all<ColorGenerator>()); const SearchBar = searchBarCreator(Mock.all<ColorGenerator>());
const push = jest.fn(); const push = jest.fn();
const now = new Date();
const createWrapper = (props: Partial<SearchBarProps> = {}) => { const createWrapper = (props: Partial<SearchBarProps> = {}) => {
wrapper = shallow( wrapper = shallow(
<SearchBar <SearchBar
listShortUrls={listShortUrlsMock}
shortUrlsListParams={{}} shortUrlsListParams={{}}
history={Mock.of<History>({ push })} history={Mock.of<History>({ push })}
location={Mock.of<Location>({ search: '' })} location={Mock.of<Location>({ search: '' })}
@ -50,7 +50,7 @@ describe('<SearchBar />', () => {
expect(wrapper.find(Tag)).toHaveLength(expectedTagComps); expect(wrapper.find(Tag)).toHaveLength(expectedTagComps);
}); });
it('updates short URLs list when search field changes', () => { it('redirects to first page when search field changes', () => {
const wrapper = createWrapper(); const wrapper = createWrapper();
const searchField = wrapper.find(SearchField); const searchField = wrapper.find(SearchField);
@ -59,7 +59,7 @@ describe('<SearchBar />', () => {
expect(push).toHaveBeenCalledWith('/server/1/list-short-urls/1?search=search-term'); expect(push).toHaveBeenCalledWith('/server/1/list-short-urls/1?search=search-term');
}); });
it('updates short URLs list when a tag is removed', () => { it('redirects to first page when a tag is removed', () => {
const wrapper = createWrapper({ location: Mock.of<Location>({ search: 'tags=foo,bar' }) }); const wrapper = createWrapper({ location: Mock.of<Location>({ search: 'tags=foo,bar' }) });
const tag = wrapper.find(Tag).first(); const tag = wrapper.find(Tag).first();
@ -68,12 +68,19 @@ describe('<SearchBar />', () => {
expect(push).toHaveBeenCalledWith('/server/1/list-short-urls/1?tags=bar'); expect(push).toHaveBeenCalledWith('/server/1/list-short-urls/1?tags=bar');
}); });
it('updates short URLs list when date range changes', () => { it.each([
[{ startDate: now }, `startDate=${encodeURIComponent(formatISO(now))}` ],
[{ endDate: now }, `endDate=${encodeURIComponent(formatISO(now))}` ],
[
{ startDate: now, endDate: now },
`startDate=${encodeURIComponent(formatISO(now))}&endDate=${encodeURIComponent(formatISO(now))}`,
],
])('redirects to first page when date range changes', (dates, expectedQuery) => {
const wrapper = createWrapper(); const wrapper = createWrapper();
const dateRange = wrapper.find(DateRangeSelector); const dateRange = wrapper.find(DateRangeSelector);
expect(listShortUrlsMock).not.toHaveBeenCalled(); expect(push).not.toHaveBeenCalled();
dateRange.simulate('datesChange', {}); dateRange.simulate('datesChange', dates);
expect(listShortUrlsMock).toHaveBeenCalledTimes(1); expect(push).toHaveBeenCalledWith(`/server/1/list-short-urls/1?${expectedQuery}`);
}); });
}); });