Updated Short URLs list so that it allows setting default orderBy from settings

This commit is contained in:
Alejandro Celaya 2021-12-24 13:14:13 +01:00
parent d8442e435d
commit 57075c581d
12 changed files with 69 additions and 69 deletions

View file

@ -24,12 +24,11 @@ const buildShlinkBaseUrl = (url: string, apiVersion: number) => url ? `${url}/re
const rejectNilProps = reject(isNil); const rejectNilProps = reject(isNil);
const normalizeOrderByInParams = (params: ShlinkShortUrlsListParams): ShlinkShortUrlsListNormalizedParams => { const normalizeOrderByInParams = (params: ShlinkShortUrlsListParams): ShlinkShortUrlsListNormalizedParams => {
const { orderBy = {}, ...rest } = params; const { orderBy = {}, ...rest } = params;
const [ firstKey ] = Object.keys(orderBy); const { field, dir } = orderBy;
const [ firstValue ] = Object.values(orderBy);
return !firstValue ? rest : { return !dir ? rest : {
...rest, ...rest,
orderBy: `${firstKey}-${firstValue}`, orderBy: `${field}-${dir}`,
}; };
}; };

View file

@ -1,7 +1,7 @@
import { Visit } from '../../visits/types'; import { Visit } from '../../visits/types';
import { OptionalString } from '../../utils/utils'; import { OptionalString } from '../../utils/utils';
import { ShortUrl, ShortUrlMeta } from '../../short-urls/data'; import { ShortUrl, ShortUrlMeta } from '../../short-urls/data';
import { OrderBy } from '../../short-urls/reducers/shortUrlsListParams'; import { ShortUrlsOrder } from '../../short-urls/reducers/shortUrlsListParams';
export interface ShlinkShortUrlsResponse { export interface ShlinkShortUrlsResponse {
data: ShortUrl[]; data: ShortUrl[];
@ -94,7 +94,7 @@ export interface ShlinkShortUrlsListParams {
searchTerm?: string; searchTerm?: string;
startDate?: string; startDate?: string;
endDate?: string; endDate?: string;
orderBy?: OrderBy; orderBy?: ShortUrlsOrder;
} }
export interface ShlinkShortUrlsListNormalizedParams extends Omit<ShlinkShortUrlsListParams, 'orderBy'> { export interface ShlinkShortUrlsListNormalizedParams extends Omit<ShlinkShortUrlsListParams, 'orderBy'> {

View file

@ -44,7 +44,7 @@ export const Overview = (
const history = useHistory(); const history = useHistory();
useEffect(() => { useEffect(() => {
listShortUrls({ itemsPerPage: 5, orderBy: { dateCreated: 'DESC' } }); listShortUrls({ itemsPerPage: 5, orderBy: { field: 'dateCreated', dir: 'DESC' } });
listTags(); listTags();
loadVisitsOverview(); loadVisitsOverview();
}, []); }, []);

View file

@ -9,6 +9,11 @@ import { ShortUrlsOrder } from '../../short-urls/reducers/shortUrlsListParams';
export const SET_SETTINGS = 'shlink/realTimeUpdates/SET_SETTINGS'; export const SET_SETTINGS = 'shlink/realTimeUpdates/SET_SETTINGS';
export const DEFAULT_SHORT_URLS_ORDERING: ShortUrlsOrder = {
field: 'dateCreated',
dir: 'DESC',
};
/** /**
* Important! When adding new props in the main Settings interface or any of the nested props, they have to be set as * Important! When adding new props in the main Settings interface or any of the nested props, they have to be set as
* optional, as old instances of the app will load partial objects from local storage until it is saved again. * optional, as old instances of the app will load partial objects from local storage until it is saved again.
@ -68,6 +73,9 @@ const initialState: Settings = {
visits: { visits: {
defaultInterval: 'last30Days', defaultInterval: 'last30Days',
}, },
shortUrlList: {
defaultOrdering: DEFAULT_SHORT_URLS_ORDERING,
},
}; };
type SettingsAction = Action & Settings; type SettingsAction = Action & Settings;

View file

@ -1,4 +1,4 @@
import { head, keys, pipe, values } from 'ramda'; import { pipe } from 'ramda';
import { FC, useEffect, useMemo, useState } from 'react'; import { FC, useEffect, useMemo, useState } from 'react';
import { RouteComponentProps } from 'react-router'; import { RouteComponentProps } from 'react-router';
import { Card } from 'reactstrap'; import { Card } from 'reactstrap';
@ -9,6 +9,7 @@ import { boundToMercureHub } from '../mercure/helpers/boundToMercureHub';
import { Topics } from '../mercure/helpers/Topics'; import { Topics } from '../mercure/helpers/Topics';
import { TableOrderIcon } from '../utils/table/TableOrderIcon'; import { TableOrderIcon } from '../utils/table/TableOrderIcon';
import { ShlinkShortUrlsListParams } from '../api/types'; import { ShlinkShortUrlsListParams } from '../api/types';
import { DEFAULT_SHORT_URLS_ORDERING, Settings } from '../settings/reducers/settings';
import { ShortUrlsList as ShortUrlsListState } from './reducers/shortUrlsList'; import { ShortUrlsList as ShortUrlsListState } from './reducers/shortUrlsList';
import { OrderableFields, ShortUrlsListParams, ShortUrlsOrder, SORTABLE_FIELDS } from './reducers/shortUrlsListParams'; import { OrderableFields, ShortUrlsListParams, ShortUrlsOrder, SORTABLE_FIELDS } from './reducers/shortUrlsListParams';
import { ShortUrlsTableProps } from './ShortUrlsTable'; import { ShortUrlsTableProps } from './ShortUrlsTable';
@ -18,9 +19,10 @@ import { ShortUrlListRouteParams, useShortUrlsQuery } from './helpers/hooks';
interface ShortUrlsListProps extends RouteComponentProps<ShortUrlListRouteParams> { interface ShortUrlsListProps extends RouteComponentProps<ShortUrlListRouteParams> {
selectedServer: SelectedServer; selectedServer: SelectedServer;
shortUrlsList: ShortUrlsListState; shortUrlsList: ShortUrlsListState;
listShortUrls: (params: ShortUrlsListParams) => void; listShortUrls: (params: ShlinkShortUrlsListParams) => void;
shortUrlsListParams: ShortUrlsListParams; shortUrlsListParams: ShortUrlsListParams;
resetShortUrlParams: () => void; resetShortUrlParams: () => void;
settings: Settings;
} }
const ShortUrlsList = (ShortUrlsTable: FC<ShortUrlsTableProps>, SearchBar: FC) => boundToMercureHub(({ const ShortUrlsList = (ShortUrlsTable: FC<ShortUrlsTableProps>, SearchBar: FC) => boundToMercureHub(({
@ -32,24 +34,17 @@ const ShortUrlsList = (ShortUrlsTable: FC<ShortUrlsTableProps>, SearchBar: FC) =
history, history,
shortUrlsList, shortUrlsList,
selectedServer, selectedServer,
settings,
}: ShortUrlsListProps) => { }: ShortUrlsListProps) => {
const serverId = getServerId(selectedServer); const serverId = getServerId(selectedServer);
const { orderBy } = shortUrlsListParams; const { orderBy } = shortUrlsListParams;
const [ order, setOrder ] = useState<ShortUrlsOrder>({ const initialOrderBy = orderBy ?? settings.shortUrlList?.defaultOrdering ?? DEFAULT_SHORT_URLS_ORDERING;
field: orderBy && (head(keys(orderBy)) as OrderableFields), const [ order, setOrder ] = useState<ShortUrlsOrder>(initialOrderBy);
dir: orderBy && head(values(orderBy)),
});
const [{ tags, search, startDate, endDate }, toFirstPage ] = useShortUrlsQuery({ history, match, location }); const [{ tags, search, startDate, endDate }, toFirstPage ] = useShortUrlsQuery({ history, match, location });
const selectedTags = useMemo(() => tags?.split(',') ?? [], [ tags ]); const selectedTags = useMemo(() => tags?.split(',') ?? [], [ tags ]);
const { pagination } = shortUrlsList?.shortUrls ?? {}; const { pagination } = shortUrlsList?.shortUrls ?? {};
const refreshList = (extraParams: ShlinkShortUrlsListParams) => listShortUrls( const handleOrderBy = (field?: OrderableFields, dir?: OrderDir) => setOrder({ field, dir });
{ ...shortUrlsListParams, ...extraParams },
);
const handleOrderBy = (field?: OrderableFields, dir?: OrderDir) => {
setOrder({ field, dir });
refreshList({ orderBy: field ? { [field]: dir } : undefined });
};
const orderByColumn = (field: OrderableFields) => () => const orderByColumn = (field: OrderableFields) => () =>
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} />;
@ -60,10 +55,16 @@ const ShortUrlsList = (ShortUrlsTable: FC<ShortUrlsTableProps>, SearchBar: FC) =
useEffect(() => resetShortUrlParams, []); useEffect(() => resetShortUrlParams, []);
useEffect(() => { useEffect(() => {
refreshList( listShortUrls({
{ page: match.params.page, searchTerm: search, tags: selectedTags, itemsPerPage: undefined, startDate, endDate }, page: match.params.page,
); searchTerm: search,
}, [ match.params.page, search, selectedTags, startDate, endDate ]); tags: selectedTags,
itemsPerPage: undefined,
startDate,
endDate,
orderBy: order,
});
}, [ match.params.page, search, selectedTags, startDate, endDate, order ]);
return ( return (
<> <>

View file

@ -7,7 +7,6 @@ import { GetState } from '../../container/types';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder'; import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { ShlinkShortUrlsListParams, ShlinkShortUrlsResponse } from '../../api/types'; import { ShlinkShortUrlsListParams, ShlinkShortUrlsResponse } from '../../api/types';
import { DeleteShortUrlAction, SHORT_URL_DELETED } from './shortUrlDeletion'; import { DeleteShortUrlAction, SHORT_URL_DELETED } from './shortUrlDeletion';
import { ShortUrlsListParams } from './shortUrlsListParams';
import { CREATE_SHORT_URL, CreateShortUrlAction } from './shortUrlCreation'; import { CREATE_SHORT_URL, CreateShortUrlAction } from './shortUrlCreation';
import { SHORT_URL_EDITED, ShortUrlEditedAction } from './shortUrlEdition'; import { SHORT_URL_EDITED, ShortUrlEditedAction } from './shortUrlEdition';
@ -25,7 +24,7 @@ export interface ShortUrlsList {
export interface ListShortUrlsAction extends Action<string> { export interface ListShortUrlsAction extends Action<string> {
shortUrls: ShlinkShortUrlsResponse; shortUrls: ShlinkShortUrlsResponse;
params: ShortUrlsListParams; params: ShlinkShortUrlsListParams;
} }
export type ListShortUrlsCombinedAction = ( export type ListShortUrlsCombinedAction = (

View file

@ -1,5 +1,5 @@
import { buildActionCreator, buildReducer } from '../../utils/helpers/redux'; import { buildActionCreator, buildReducer } from '../../utils/helpers/redux';
import { Order, OrderDir } from '../../utils/helpers/ordering'; import { Order } from '../../utils/helpers/ordering';
import { LIST_SHORT_URLS, ListShortUrlsAction } from './shortUrlsList'; import { LIST_SHORT_URLS, ListShortUrlsAction } from './shortUrlsList';
export const RESET_SHORT_URL_PARAMS = 'shlink/shortUrlsListParams/RESET_SHORT_URL_PARAMS'; export const RESET_SHORT_URL_PARAMS = 'shlink/shortUrlsListParams/RESET_SHORT_URL_PARAMS';
@ -16,17 +16,14 @@ export type OrderableFields = keyof typeof SORTABLE_FIELDS;
export type ShortUrlsOrder = Order<OrderableFields>; export type ShortUrlsOrder = Order<OrderableFields>;
export type OrderBy = Partial<Record<OrderableFields, OrderDir>>;
export interface ShortUrlsListParams { export interface ShortUrlsListParams {
page?: string; page?: string;
itemsPerPage?: number; itemsPerPage?: number;
orderBy?: OrderBy; orderBy?: ShortUrlsOrder;
} }
const initialState: ShortUrlsListParams = { const initialState: ShortUrlsListParams = {
page: '1', page: '1',
orderBy: { dateCreated: 'DESC' },
}; };
export default buildReducer<ShortUrlsListParams, ListShortUrlsAction>({ export default buildReducer<ShortUrlsListParams, ListShortUrlsAction>({

View file

@ -22,7 +22,7 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator, withRouter:
// Components // Components
bottle.serviceFactory('ShortUrlsList', ShortUrlsList, 'ShortUrlsTable', 'SearchBar'); bottle.serviceFactory('ShortUrlsList', ShortUrlsList, 'ShortUrlsTable', 'SearchBar');
bottle.decorator('ShortUrlsList', connect( bottle.decorator('ShortUrlsList', connect(
[ 'selectedServer', 'shortUrlsListParams', 'mercureInfo', 'shortUrlsList' ], [ 'selectedServer', 'shortUrlsListParams', 'mercureInfo', 'shortUrlsList', 'settings' ],
[ 'listShortUrls', 'resetShortUrlParams', 'createNewVisits', 'loadMercureInfo' ], [ 'listShortUrls', 'resetShortUrlParams', 'createNewVisits', 'loadMercureInfo' ],
)); ));

View file

@ -5,7 +5,7 @@ import { OptionalString } from '../../../src/utils/utils';
import { ShlinkDomain, ShlinkVisitsOverview } from '../../../src/api/types'; import { ShlinkDomain, ShlinkVisitsOverview } from '../../../src/api/types';
import { ShortUrl } from '../../../src/short-urls/data'; import { ShortUrl } from '../../../src/short-urls/data';
import { Visit } from '../../../src/visits/types'; import { Visit } from '../../../src/visits/types';
import { OrderDir } from '../../../src/utils/helpers/ordering'; import { ShortUrlsOrder } from '../../../src/short-urls/reducers/shortUrlsListParams';
describe('ShlinkApiClient', () => { describe('ShlinkApiClient', () => {
const createAxios = (data: AxiosRequestConfig) => (async () => Promise.resolve(data)) as unknown as AxiosInstance; const createAxios = (data: AxiosRequestConfig) => (async () => Promise.resolve(data)) as unknown as AxiosInstance;
@ -33,9 +33,9 @@ describe('ShlinkApiClient', () => {
}); });
it.each([ it.each([
[{ visits: 'DESC' as OrderDir }, 'visits-DESC' ], [ { field: 'visits', dir: 'DESC' } as ShortUrlsOrder, 'visits-DESC' ],
[{ longUrl: 'ASC' as OrderDir }, 'longUrl-ASC' ], [ { field: 'longUrl', dir: 'ASC' } as ShortUrlsOrder, 'longUrl-ASC' ],
[{ longUrl: undefined as OrderDir }, undefined ], [ { field: 'longUrl', dir: undefined } as ShortUrlsOrder, undefined ],
])('parses orderBy in params', async (orderBy, expectedOrderBy) => { ])('parses orderBy in params', async (orderBy, expectedOrderBy) => {
const axiosSpy = createAxiosMock({ const axiosSpy = createAxiosMock({
data: expectedList, data: expectedList,

View file

@ -1,10 +1,12 @@
import reducer, { import reducer, {
SET_SETTINGS, SET_SETTINGS,
DEFAULT_SHORT_URLS_ORDERING,
toggleRealTimeUpdates, toggleRealTimeUpdates,
setRealTimeUpdatesInterval, setRealTimeUpdatesInterval,
setShortUrlCreationSettings, setShortUrlCreationSettings,
setUiSettings, setUiSettings,
setVisitsSettings, setVisitsSettings,
setTagsSettings,
} from '../../../src/settings/reducers/settings'; } from '../../../src/settings/reducers/settings';
describe('settingsReducer', () => { describe('settingsReducer', () => {
@ -12,7 +14,8 @@ describe('settingsReducer', () => {
const shortUrlCreation = { validateUrls: false }; const shortUrlCreation = { validateUrls: false };
const ui = { theme: 'light' }; const ui = { theme: 'light' };
const visits = { defaultInterval: 'last30Days' }; const visits = { defaultInterval: 'last30Days' };
const settings = { realTimeUpdates, shortUrlCreation, ui, visits }; const shortUrlList = { defaultOrdering: DEFAULT_SHORT_URLS_ORDERING };
const settings = { realTimeUpdates, shortUrlCreation, ui, visits, shortUrlList };
describe('reducer', () => { describe('reducer', () => {
it('returns realTimeUpdates when action is SET_SETTINGS', () => { it('returns realTimeUpdates when action is SET_SETTINGS', () => {
@ -59,4 +62,12 @@ describe('settingsReducer', () => {
expect(result).toEqual({ type: SET_SETTINGS, visits: { defaultInterval: 'last180Days' } }); expect(result).toEqual({ type: SET_SETTINGS, visits: { defaultInterval: 'last180Days' } });
}); });
}); });
describe('setTagsSettings', () => {
it('creates action to set tags settings', () => {
const result = setTagsSettings({ defaultMode: 'list' });
expect(result).toEqual({ type: SET_SETTINGS, tags: { defaultMode: 'list' } });
});
});
}); });

View file

@ -8,10 +8,11 @@ import { ShortUrl } from '../../src/short-urls/data';
import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub'; import { MercureBoundProps } from '../../src/mercure/helpers/boundToMercureHub';
import { ShortUrlsList as ShortUrlsListModel } from '../../src/short-urls/reducers/shortUrlsList'; import { ShortUrlsList as ShortUrlsListModel } from '../../src/short-urls/reducers/shortUrlsList';
import SortingDropdown from '../../src/utils/SortingDropdown'; import SortingDropdown from '../../src/utils/SortingDropdown';
import { OrderableFields, OrderBy } from '../../src/short-urls/reducers/shortUrlsListParams'; import { OrderableFields, ShortUrlsOrder } from '../../src/short-urls/reducers/shortUrlsListParams';
import Paginator from '../../src/short-urls/Paginator'; import Paginator from '../../src/short-urls/Paginator';
import { ReachableServer } from '../../src/servers/data'; import { ReachableServer } from '../../src/servers/data';
import { ShortUrlListRouteParams } from '../../src/short-urls/helpers/hooks'; import { ShortUrlListRouteParams } from '../../src/short-urls/helpers/hooks';
import { Settings } from '../../src/settings/reducers/settings';
describe('<ShortUrlsList />', () => { describe('<ShortUrlsList />', () => {
let wrapper: ShallowWrapper; let wrapper: ShallowWrapper;
@ -32,7 +33,7 @@ describe('<ShortUrlsList />', () => {
}, },
}); });
const ShortUrlsList = shortUrlsListCreator(ShortUrlsTable, SearchBar); const ShortUrlsList = shortUrlsListCreator(ShortUrlsTable, SearchBar);
const createWrapper = (orderBy: OrderBy = {}) => shallow( const createWrapper = (orderBy: ShortUrlsOrder = {}) => shallow(
<ShortUrlsList <ShortUrlsList
{...Mock.of<MercureBoundProps>({ mercureInfo: { loading: true } })} {...Mock.of<MercureBoundProps>({ mercureInfo: { loading: true } })}
listShortUrls={listShortUrlsMock} listShortUrls={listShortUrlsMock}
@ -43,6 +44,7 @@ describe('<ShortUrlsList />', () => {
shortUrlsList={shortUrlsList} shortUrlsList={shortUrlsList}
history={Mock.of<History>({ push })} history={Mock.of<History>({ push })}
selectedServer={Mock.of<ReachableServer>({ id: '1' })} selectedServer={Mock.of<ReachableServer>({ id: '1' })}
settings={Mock.all<Settings>()}
/>, />,
).dive(); // Dive is needed as this component is wrapped in a HOC ).dive(); // Dive is needed as this component is wrapped in a HOC
@ -91,20 +93,16 @@ describe('<ShortUrlsList />', () => {
it('handles order through table', () => { it('handles order through table', () => {
const orderByColumn: (field: OrderableFields) => Function = wrapper.find(ShortUrlsTable).prop('orderByColumn'); const orderByColumn: (field: OrderableFields) => Function = wrapper.find(ShortUrlsTable).prop('orderByColumn');
orderByColumn('visits')(); expect(wrapper.find(SortingDropdown).prop('order')).toEqual({});
orderByColumn('title')();
orderByColumn('shortCode')();
expect(listShortUrlsMock).toHaveBeenCalledTimes(3); orderByColumn('visits')();
expect(listShortUrlsMock).toHaveBeenNthCalledWith(1, expect.objectContaining({ expect(wrapper.find(SortingDropdown).prop('order')).toEqual({ field: 'visits', dir: 'ASC' });
orderBy: { visits: 'ASC' },
})); orderByColumn('title')();
expect(listShortUrlsMock).toHaveBeenNthCalledWith(2, expect.objectContaining({ expect(wrapper.find(SortingDropdown).prop('order')).toEqual({ field: 'title', dir: 'ASC' });
orderBy: { title: 'ASC' },
})); orderByColumn('shortCode')();
expect(listShortUrlsMock).toHaveBeenNthCalledWith(3, expect.objectContaining({ expect(wrapper.find(SortingDropdown).prop('order')).toEqual({ field: 'shortCode', dir: 'ASC' });
orderBy: { shortCode: 'ASC' },
}));
}); });
it('handles order through dropdown', () => { it('handles order through dropdown', () => {
@ -118,21 +116,12 @@ describe('<ShortUrlsList />', () => {
wrapper.find(SortingDropdown).simulate('change', undefined, undefined); wrapper.find(SortingDropdown).simulate('change', undefined, undefined);
expect(wrapper.find(SortingDropdown).prop('order')).toEqual({}); expect(wrapper.find(SortingDropdown).prop('order')).toEqual({});
expect(listShortUrlsMock).toHaveBeenCalledTimes(3);
expect(listShortUrlsMock).toHaveBeenNthCalledWith(1, expect.objectContaining({
orderBy: { visits: 'ASC' },
}));
expect(listShortUrlsMock).toHaveBeenNthCalledWith(2, expect.objectContaining({
orderBy: { shortCode: 'DESC' },
}));
expect(listShortUrlsMock).toHaveBeenNthCalledWith(3, expect.objectContaining({ orderBy: undefined }));
}); });
it.each([ it.each([
[ Mock.of<OrderBy>({ visits: 'ASC' }), 'visits', 'ASC' ], [ Mock.of<ShortUrlsOrder>({ field: 'visits', dir: 'ASC' }), 'visits', 'ASC' ],
[ Mock.of<OrderBy>({ title: 'DESC' }), 'title', 'DESC' ], [ Mock.of<ShortUrlsOrder>({ field: 'title', dir: 'DESC' }), 'title', 'DESC' ],
[ Mock.of<OrderBy>(), undefined, undefined ], [ Mock.of<ShortUrlsOrder>(), undefined, undefined ],
])('has expected initial ordering', (initialOrderBy, field, dir) => { ])('has expected initial ordering', (initialOrderBy, field, dir) => {
const wrapper = createWrapper(initialOrderBy); const wrapper = createWrapper(initialOrderBy);

View file

@ -10,14 +10,10 @@ describe('shortUrlsListParamsReducer', () => {
expect(reducer(undefined, { type: LIST_SHORT_URLS, params: { searchTerm: 'foo', page: '2' } } as any)).toEqual({ expect(reducer(undefined, { type: LIST_SHORT_URLS, params: { searchTerm: 'foo', page: '2' } } as any)).toEqual({
page: '2', page: '2',
searchTerm: 'foo', searchTerm: 'foo',
orderBy: { dateCreated: 'DESC' },
})); }));
it('returns default value when action is RESET_SHORT_URL_PARAMS', () => it('returns default value when action is RESET_SHORT_URL_PARAMS', () =>
expect(reducer(undefined, { type: RESET_SHORT_URL_PARAMS } as any)).toEqual({ expect(reducer(undefined, { type: RESET_SHORT_URL_PARAMS } as any)).toEqual({ page: '1' }));
page: '1',
orderBy: { dateCreated: 'DESC' },
}));
}); });
describe('resetShortUrlParams', () => { describe('resetShortUrlParams', () => {