Merge pull request #514 from acelaya-forks/feature/sticky-tags-header

Feature/sticky tags header
This commit is contained in:
Alejandro Celaya 2021-11-01 14:16:00 +01:00 committed by GitHub
commit af08b53002
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 199 additions and 158 deletions

View file

@ -10,6 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
* [#500](https://github.com/shlinkio/shlink-web-client/issues/500) Allowed to set the `forwardQuery` flag when creating/editing short URLs on a Shlink v2.9.0 server.
* [#508](https://github.com/shlinkio/shlink-web-client/issues/508) Added new servers management section.
* [#490](https://github.com/shlinkio/shlink-web-client/issues/490) Now a server can be marked as auto-connect, skipping home screen when that happens.
* [#492](https://github.com/shlinkio/shlink-web-client/issues/492) Improved tags table, by supporting sorting by column and making the header sticky.
### Changed
* Moved ci workflow to external repo and reused

View file

@ -1,3 +0,0 @@
.short-urls-list__header-icon {
margin-left: .4rem;
}

View file

@ -5,7 +5,7 @@ import { FC, useEffect, useState } from 'react';
import { RouteComponentProps } from 'react-router';
import { Card } from 'reactstrap';
import SortingDropdown from '../utils/SortingDropdown';
import { determineOrderDir, OrderDir } from '../utils/utils';
import { determineOrderDir, Order, OrderDir } from '../utils/helpers/ordering';
import { getServerId, SelectedServer } from '../servers/data';
import { boundToMercureHub } from '../mercure/helpers/boundToMercureHub';
import { parseQuery } from '../utils/helpers/query';
@ -14,7 +14,6 @@ import { ShortUrlsList as ShortUrlsListState } from './reducers/shortUrlsList';
import { OrderableFields, ShortUrlsListParams, SORTABLE_FIELDS } from './reducers/shortUrlsListParams';
import { ShortUrlsTableProps } from './ShortUrlsTable';
import Paginator from './Paginator';
import './ShortUrlsList.scss';
interface RouteParams {
page: string;
@ -29,6 +28,8 @@ export interface ShortUrlsListProps extends RouteComponentProps<RouteParams> {
resetShortUrlParams: () => void;
}
type ShortUrlsOrder = Order<OrderableFields>;
const ShortUrlsList = (ShortUrlsTable: FC<ShortUrlsTableProps>) => boundToMercureHub(({
listShortUrls,
resetShortUrlParams,
@ -39,34 +40,20 @@ const ShortUrlsList = (ShortUrlsTable: FC<ShortUrlsTableProps>) => boundToMercur
selectedServer,
}: ShortUrlsListProps) => {
const { orderBy } = shortUrlsListParams;
const [ order, setOrder ] = useState<{ orderField?: OrderableFields; orderDir?: OrderDir }>({
orderField: orderBy && (head(keys(orderBy)) as OrderableFields),
orderDir: orderBy && head(values(orderBy)),
const [ order, setOrder ] = useState<ShortUrlsOrder>({
field: orderBy && (head(keys(orderBy)) as OrderableFields),
dir: orderBy && head(values(orderBy)),
});
const { pagination } = shortUrlsList?.shortUrls ?? {};
const refreshList = (extraParams: ShortUrlsListParams) => listShortUrls({ ...shortUrlsListParams, ...extraParams });
const handleOrderBy = (orderField?: OrderableFields, orderDir?: OrderDir) => {
setOrder({ orderField, orderDir });
refreshList({ orderBy: orderField ? { [orderField]: orderDir } : undefined });
const handleOrderBy = (field?: OrderableFields, dir?: OrderDir) => {
setOrder({ field, dir });
refreshList({ orderBy: field ? { [field]: dir } : undefined });
};
const orderByColumn = (field: OrderableFields) => () =>
handleOrderBy(field, determineOrderDir(field, order.orderField, order.orderDir));
const renderOrderIcon = (field: OrderableFields) => {
if (order.orderField !== field) {
return null;
}
if (!order.orderDir) {
return null;
}
return (
<FontAwesomeIcon
icon={order.orderDir === 'ASC' ? caretUpIcon : caretDownIcon}
className="short-urls-list__header-icon"
/>
);
};
handleOrderBy(field, determineOrderDir(field, order.field, order.dir));
const renderOrderIcon = (field: OrderableFields) => order.dir && order.field === field &&
<FontAwesomeIcon icon={order.dir === 'ASC' ? caretUpIcon : caretDownIcon} className="ml-1" />;
useEffect(() => {
const { tag } = parseQuery<{ tag?: string }>(location.search);
@ -82,8 +69,8 @@ const ShortUrlsList = (ShortUrlsTable: FC<ShortUrlsTableProps>) => boundToMercur
<div className="d-block d-lg-none mb-3">
<SortingDropdown
items={SORTABLE_FIELDS}
orderField={order.orderField}
orderDir={order.orderDir}
orderField={order.field}
orderDir={order.dir}
onChange={handleOrderBy}
/>
</div>

View file

@ -63,34 +63,29 @@ export const ShortUrlsTable = (ShortUrlsRow: FC<ShortUrlsRowProps>) => ({
<thead className="responsive-table__header short-urls-table__header">
<tr>
<th className={orderableColumnsClasses} onClick={orderByColumn?.('dateCreated')}>
Created at
{renderOrderIcon?.('dateCreated')}
Created at {renderOrderIcon?.('dateCreated')}
</th>
<th className={orderableColumnsClasses} onClick={orderByColumn?.('shortCode')}>
Short URL
{renderOrderIcon?.('shortCode')}
Short URL {renderOrderIcon?.('shortCode')}
</th>
{!supportsTitle && (
<th className={orderableColumnsClasses} onClick={orderByColumn?.('longUrl')}>
Long URL
{renderOrderIcon?.('longUrl')}
Long URL {renderOrderIcon?.('longUrl')}
</th>
) || (
<th className="short-urls-table__header-cell">
<span className={actionableFieldClasses} onClick={orderByColumn?.('title')}>
Title
{renderOrderIcon?.('title')}
Title {renderOrderIcon?.('title')}
</span>
&nbsp;&nbsp;/&nbsp;&nbsp;
<span className={actionableFieldClasses} onClick={orderByColumn?.('longUrl')}>
<span className="indivisible">Long URL</span>
{renderOrderIcon?.('longUrl')}
<span className="indivisible">Long URL</span> {renderOrderIcon?.('longUrl')}
</span>
</th>
)}
<th className="short-urls-table__header-cell">Tags</th>
<th className={orderableColumnsClasses} onClick={orderByColumn?.('visits')}>
<span className="indivisible">Visits{renderOrderIcon?.('visits')}</span>
<span className="indivisible">Visits {renderOrderIcon?.('visits')}</span>
</th>
<th className="short-urls-table__header-cell">&nbsp;</th>
</tr>

View file

@ -1,5 +1,5 @@
import { buildActionCreator, buildReducer } from '../../utils/helpers/redux';
import { OrderDir } from '../../utils/utils';
import { OrderDir } from '../../utils/helpers/ordering';
import { LIST_SHORT_URLS, ListShortUrlsAction } from './shortUrlsList';
export const RESET_SHORT_URL_PARAMS = 'shlink/shortUrlsListParams/RESET_SHORT_URL_PARAMS';

10
src/tags/TagsTable.scss Normal file
View file

@ -0,0 +1,10 @@
@import '../utils/base';
@import '../utils/mixins/sticky-cell';
.tags-table__header-cell.tags-table__header-cell {
@include sticky-cell(false);
top: $headerHeight;
position: sticky;
cursor: pointer;
}

View file

@ -1,27 +1,50 @@
import { FC, useEffect, useRef } from 'react';
import { splitEvery } from 'ramda';
import { FC, useEffect, useMemo, useRef, useState } from 'react';
import { pipe, splitEvery } from 'ramda';
import { RouteChildrenProps } from 'react-router';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCaretDown as caretDownIcon, faCaretUp as caretUpIcon } from '@fortawesome/free-solid-svg-icons';
import { SimpleCard } from '../utils/SimpleCard';
import ColorGenerator from '../utils/services/ColorGenerator';
import SimplePaginator from '../common/SimplePaginator';
import { useQueryState } from '../utils/helpers/hooks';
import { parseQuery } from '../utils/helpers/query';
import { determineOrderDir, Order, sortList } from '../utils/helpers/ordering';
import { TagsListChildrenProps } from './data/TagsListChildrenProps';
import { TagsTableRowProps } from './TagsTableRow';
import { NormalizedTag } from './data';
import './TagsTable.scss';
const TAGS_PER_PAGE = 20; // TODO Allow customizing this value in settings
export const TagsTable = (colorGenerator: ColorGenerator, TagsTableRow: FC<TagsTableRowProps>) => (
type OrderableFields = 'tag' | 'shortUrls' | 'visits';
type TagsOrder = Order<OrderableFields>;
export const TagsTable = (TagsTableRow: FC<TagsTableRowProps>) => (
{ tagsList, selectedServer, location }: TagsListChildrenProps & RouteChildrenProps,
) => {
const isFirstLoad = useRef(true);
const { page: pageFromQuery = 1 } = parseQuery<{ page?: number | string }>(location.search);
const [ page, setPage ] = useQueryState<number>('page', Number(pageFromQuery));
const sortedTags = tagsList.filteredTags; // TODO Support sorting tags
const [ order, setOrder ] = useState<TagsOrder>({});
const sortedTags = useMemo(
pipe(
() => tagsList.filteredTags.map((tag): NormalizedTag => ({
tag,
shortUrls: tagsList.stats[tag]?.shortUrlsCount ?? 0,
visits: tagsList.stats[tag]?.visitsCount ?? 0,
})),
(normalizedTags) => sortList<NormalizedTag>(normalizedTags, order),
),
[ tagsList.filteredTags, order ],
);
const pages = splitEvery(TAGS_PER_PAGE, sortedTags);
const showPaginator = pages.length > 1;
const currentPage = pages[page - 1] ?? [];
const orderByColumn = (field: OrderableFields) =>
() => setOrder({ field, dir: determineOrderDir(field, order.field, order.dir) });
const renderOrderIcon = (field: OrderableFields) => order.dir && order.field === field &&
<FontAwesomeIcon icon={order.dir === 'ASC' ? caretUpIcon : caretDownIcon} className="ml-1" />;
useEffect(() => {
!isFirstLoad.current && setPage(1);
isFirstLoad.current = false;
@ -35,23 +58,20 @@ export const TagsTable = (colorGenerator: ColorGenerator, TagsTableRow: FC<TagsT
<table className="table table-hover mb-0">
<thead className="responsive-table__header">
<tr>
<th>Tag</th>
<th className="text-lg-right">Short URLs</th>
<th className="text-lg-right">Visits</th>
<th />
<th className="tags-table__header-cell" onClick={orderByColumn('tag')}>Tag {renderOrderIcon('tag')}</th>
<th className="tags-table__header-cell text-lg-right" onClick={orderByColumn('shortUrls')}>
Short URLs {renderOrderIcon('shortUrls')}
</th>
<th className="tags-table__header-cell text-lg-right" onClick={orderByColumn('visits')}>
Visits {renderOrderIcon('visits')}
</th>
<th className="tags-table__header-cell" />
</tr>
<tr><th colSpan={4} className="p-0 border-top-0" /></tr>
</thead>
<tbody>
{currentPage.length === 0 && <tr><td colSpan={4} className="text-center">No results found</td></tr>}
{currentPage.map((tag) => (
<TagsTableRow
key={tag}
tag={tag}
tagStats={tagsList.stats[tag]}
selectedServer={selectedServer}
colorGenerator={colorGenerator}
/>
))}
{currentPage.map((tag) => <TagsTableRow key={tag.tag} tag={tag} selectedServer={selectedServer} />)}
</tbody>
</table>

View file

@ -9,18 +9,18 @@ import { prettify } from '../utils/helpers/numbers';
import { useToggle } from '../utils/helpers/hooks';
import { DropdownBtnMenu } from '../utils/DropdownBtnMenu';
import TagBullet from './helpers/TagBullet';
import { TagModalProps, TagStats } from './data';
import { NormalizedTag, TagModalProps } from './data';
export interface TagsTableRowProps {
tag: string;
tagStats?: TagStats;
tag: NormalizedTag;
selectedServer: SelectedServer;
colorGenerator: ColorGenerator;
}
export const TagsTableRow = (DeleteTagConfirmModal: FC<TagModalProps>, EditTagModal: FC<TagModalProps>) => (
{ tag, tagStats, colorGenerator, selectedServer }: TagsTableRowProps,
) => {
export const TagsTableRow = (
DeleteTagConfirmModal: FC<TagModalProps>,
EditTagModal: FC<TagModalProps>,
colorGenerator: ColorGenerator,
) => ({ tag, selectedServer }: TagsTableRowProps) => {
const [ isDeleteModalOpen, toggleDelete ] = useToggle();
const [ isEditModalOpen, toggleEdit ] = useToggle();
const [ isDropdownOpen, toggleDropdown ] = useToggle();
@ -29,16 +29,16 @@ export const TagsTableRow = (DeleteTagConfirmModal: FC<TagModalProps>, EditTagMo
return (
<tr className="responsive-table__row">
<th className="responsive-table__cell" data-th="Tag">
<TagBullet tag={tag} colorGenerator={colorGenerator} /> {tag}
<TagBullet tag={tag.tag} colorGenerator={colorGenerator} /> {tag.tag}
</th>
<td className="responsive-table__cell text-lg-right" data-th="Short URLs">
<Link to={`/server/${serverId}/list-short-urls/1?tag=${encodeURIComponent(tag)}`}>
{prettify(tagStats?.shortUrlsCount ?? 0)}
<Link to={`/server/${serverId}/list-short-urls/1?tag=${encodeURIComponent(tag.tag)}`}>
{prettify(tag.shortUrls)}
</Link>
</td>
<td className="responsive-table__cell text-lg-right" data-th="Visits">
<Link to={`/server/${serverId}/tag/${tag}/visits`}>
{prettify(tagStats?.visitsCount ?? 0)}
<Link to={`/server/${serverId}/tag/${tag.tag}/visits`}>
{prettify(tag.visits)}
</Link>
</td>
<td className="responsive-table__cell text-lg-right">
@ -52,8 +52,8 @@ export const TagsTableRow = (DeleteTagConfirmModal: FC<TagModalProps>, EditTagMo
</DropdownBtnMenu>
</td>
<EditTagModal tag={tag} toggle={toggleEdit} isOpen={isEditModalOpen} />
<DeleteTagConfirmModal tag={tag} toggle={toggleDelete} isOpen={isDeleteModalOpen} />
<EditTagModal tag={tag.tag} toggle={toggleEdit} isOpen={isEditModalOpen} />
<DeleteTagConfirmModal tag={tag.tag} toggle={toggleDelete} isOpen={isDeleteModalOpen} />
</tr>
);
};

View file

@ -8,3 +8,9 @@ export interface TagModalProps {
isOpen: boolean;
toggle: () => void;
}
export interface NormalizedTag {
tag: string;
shortUrls: number;
visits: number;
}

View file

@ -27,9 +27,9 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
bottle.decorator('EditTagModal', connect([ 'tagEdit' ], [ 'editTag', 'tagEdited' ]));
bottle.serviceFactory('TagsCards', TagsCards, 'TagCard');
bottle.serviceFactory('TagsTableRow', TagsTableRow, 'DeleteTagConfirmModal', 'EditTagModal');
bottle.serviceFactory('TagsTableRow', TagsTableRow, 'DeleteTagConfirmModal', 'EditTagModal', 'ColorGenerator');
bottle.serviceFactory('TagsTable', TagsTable, 'ColorGenerator', 'TagsTableRow');
bottle.serviceFactory('TagsTable', TagsTable, 'TagsTableRow');
bottle.decorator('TagsTable', withRouter);
bottle.serviceFactory('TagsList', TagsList, 'TagsCards', 'TagsTable');

View file

@ -3,7 +3,7 @@ import { toPairs } from 'ramda';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSortAmountUp as sortAscIcon, faSortAmountDown as sortDescIcon } from '@fortawesome/free-solid-svg-icons';
import classNames from 'classnames';
import { determineOrderDir, OrderDir } from './utils';
import { determineOrderDir, OrderDir } from './helpers/ordering';
import './SortingDropdown.scss';
export interface SortingDropdownProps<T extends string = string> {

View file

@ -0,0 +1,32 @@
export type OrderDir = 'ASC' | 'DESC' | undefined;
export interface Order<Fields> {
field?: Fields;
dir?: OrderDir;
}
export const determineOrderDir = <T extends string = string>(
currentField: T,
newField?: T,
currentOrderDir?: OrderDir,
): OrderDir => {
if (currentField !== newField) {
return 'ASC';
}
const newOrderMap: Record<'ASC' | 'DESC', OrderDir> = {
ASC: 'DESC',
DESC: undefined,
};
return currentOrderDir ? newOrderMap[currentOrderDir] : 'ASC';
};
export const sortList = <List>(list: List[], { field, dir }: Order<Partial<keyof List>>) => !field || !dir
? list
: list.sort((a, b) => {
const greaterThan = dir === 'ASC' ? 1 : -1;
const smallerThan = dir === 'ASC' ? -1 : 1;
return a[field] > b[field] ? greaterThan : smallerThan;
});

View file

@ -1,6 +1,6 @@
@import '../base';
@mixin sticky-cell() {
@mixin sticky-cell($with-separators: true) {
z-index: 1;
border: none !important;
position: relative;
@ -11,20 +11,20 @@
top: -1px;
left: 0;
bottom: -1px;
right: -1px;
right: if($with-separators, -1px, 0);
background: var(--table-border-color);
z-index: -2;
}
&:first-child:before {
left: -1px;
left: if($with-separators, -1px, 0);
}
&:after {
content: '';
position: absolute;
top: 0;
left: 1px;
left: if($with-separators, 1px, 0);
bottom: 0;
right: 0;
background: var(--primary-color);

View file

@ -1,25 +1,6 @@
import { isEmpty, isNil, pipe, range } from 'ramda';
import { SyntheticEvent } from 'react';
export type OrderDir = 'ASC' | 'DESC' | undefined;
export const determineOrderDir = <T extends string = string>(
currentField: T,
newField?: T,
currentOrderDir?: OrderDir,
): OrderDir => {
if (currentField !== newField) {
return 'ASC';
}
const newOrderMap: Record<'ASC' | 'DESC', OrderDir> = {
ASC: 'DESC',
DESC: undefined,
};
return currentOrderDir ? newOrderMap[currentOrderDir] : 'ASC';
};
export const rangeOf = <T>(size: number, mappingFn: (value: number) => T, startAt = 1): T[] =>
range(startAt, size + 1).map(mappingFn);

View file

@ -15,6 +15,7 @@ import { ShlinkApiError } from '../api/ShlinkApiError';
import { Settings } from '../settings/reducers/settings';
import { SelectedServer } from '../servers/data';
import { supportsBotVisits } from '../utils/helpers/features';
import { prettify } from '../utils/helpers/numbers';
import LineChartCard from './charts/LineChartCard';
import VisitsTable from './VisitsTable';
import { NormalizedOrphanVisit, NormalizedVisit, VisitsFilter, VisitsInfo, VisitsParams } from './types';
@ -295,7 +296,7 @@ const VisitsStats: FC<VisitsStatsProps> = ({
className="btn-md-block mr-2"
onClick={() => setSelectedVisits([])}
>
Clear selection {highlightedVisits.length > 0 && <>({highlightedVisits.length})</>}
Clear selection {highlightedVisits.length > 0 && <>({prettify(highlightedVisits.length)})</>}
</Button>
<Button
outline
@ -303,7 +304,7 @@ const VisitsStats: FC<VisitsStatsProps> = ({
className="btn-md-block"
onClick={() => exportCsv(normalizedVisits)}
>
<FontAwesomeIcon icon={faFileDownload} /> Export ({normalizedVisits.length})
<FontAwesomeIcon icon={faFileDownload} /> Export ({prettify(normalizedVisits.length)})
</Button>
</div>
</div>

View file

@ -11,7 +11,7 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { UncontrolledTooltip } from 'reactstrap';
import SimplePaginator from '../common/SimplePaginator';
import SearchField from '../utils/SearchField';
import { determineOrderDir, OrderDir } from '../utils/utils';
import { determineOrderDir, Order, sortList } from '../utils/helpers/ordering';
import { prettify } from '../utils/helpers/numbers';
import { supportsBotVisits } from '../utils/helpers/features';
import { SelectedServer } from '../servers/data';
@ -29,11 +29,7 @@ export interface VisitsTableProps {
}
type OrderableFields = 'date' | 'country' | 'city' | 'browser' | 'os' | 'referer' | 'visitedUrl' | 'potentialBot';
interface Order {
field?: OrderableFields;
dir?: OrderDir;
}
type VisitsOrder = Order<OrderableFields>;
const PAGE_SIZE = 20;
const visitMatchesSearch = ({ browser, os, referer, country, city, ...rest }: NormalizedVisit, searchTerm: string) =>
@ -42,15 +38,8 @@ const visitMatchesSearch = ({ browser, os, referer, country, city, ...rest }: No
);
const searchVisits = (searchTerm: string, visits: NormalizedVisit[]) =>
visits.filter((visit) => visitMatchesSearch(visit, searchTerm));
const sortVisits = ({ field, dir }: Order, visits: NormalizedVisit[]) => !field || !dir ? visits : visits.sort(
(a, b) => {
const greaterThan = dir === 'ASC' ? 1 : -1;
const smallerThan = dir === 'ASC' ? -1 : 1;
return (a as NormalizedOrphanVisit)[field] > (b as NormalizedOrphanVisit)[field] ? greaterThan : smallerThan;
},
);
const calculateVisits = (allVisits: NormalizedVisit[], searchTerm: string | undefined, order: Order) => {
const sortVisits = (order: VisitsOrder, visits: NormalizedVisit[]) => sortList<NormalizedVisit>(visits, order as any);
const calculateVisits = (allVisits: NormalizedVisit[], searchTerm: string | undefined, order: VisitsOrder) => {
const filteredVisits = searchTerm ? searchVisits(searchTerm, allVisits) : [ ...allVisits ];
const sortedVisits = sortVisits(order, filteredVisits);
const total = sortedVisits.length;
@ -72,7 +61,7 @@ const VisitsTable = ({
const [ isMobileDevice, setIsMobileDevice ] = useState(matchMobile());
const [ searchTerm, setSearchTerm ] = useState<string | undefined>(undefined);
const [ order, setOrder ] = useState<Order>({ field: undefined, dir: undefined });
const [ order, setOrder ] = useState<VisitsOrder>({});
const resultSet = useMemo(() => calculateVisits(visits, searchTerm, order), [ searchTerm, order ]);
const isFirstLoad = useRef(true);
const [ page, setPage ] = useState(1);

View file

@ -1,6 +1,7 @@
import { FC, useState } from 'react';
import { fromPairs, pipe, reverse, sortBy, splitEvery, toLower, toPairs, type, zipObj } from 'ramda';
import { OrderDir, rangeOf } from '../../utils/utils';
import { rangeOf } from '../../utils/utils';
import { OrderDir } from '../../utils/helpers/ordering';
import SimplePaginator from '../../common/SimplePaginator';
import { roundTen } from '../../utils/helpers/numbers';
import SortingDropdown from '../../utils/SortingDropdown';

View file

@ -79,13 +79,13 @@ describe('<ShortUrlsList />', () => {
const renderIcon = (field: OrderableFields) =>
(wrapper.find(ShortUrlsTable).prop('renderOrderIcon') as (field: OrderableFields) => ReactElement | null)(field);
expect(renderIcon('visits')).toEqual(null);
expect(renderIcon('visits')).toEqual(undefined);
wrapper.find(SortingDropdown).simulate('change', 'visits');
expect(renderIcon('visits')).toEqual(null);
expect(renderIcon('visits')).toEqual(undefined);
wrapper.find(SortingDropdown).simulate('change', 'visits', 'ASC');
expect(renderIcon('visits')).not.toEqual(null);
expect(renderIcon('visits')).not.toEqual(undefined);
});
it('handles order by through table', () => {

View file

@ -2,17 +2,16 @@ import { Mock } from 'ts-mockery';
import { shallow, ShallowWrapper } from 'enzyme';
import { match } from 'react-router';
import { Location, History } from 'history';
import ColorGenerator from '../../src/utils/services/ColorGenerator';
import { TagsTable as createTagsTable } from '../../src/tags/TagsTable';
import { SelectedServer } from '../../src/servers/data';
import { TagsList } from '../../src/tags/reducers/tagsList';
import { rangeOf } from '../../src/utils/utils';
import SimplePaginator from '../../src/common/SimplePaginator';
import { NormalizedTag } from '../../src/tags/data';
describe('<TagsTable />', () => {
const colorGenerator = Mock.all<ColorGenerator>();
const TagsTableRow = () => null;
const TagsTable = createTagsTable(colorGenerator, TagsTableRow);
const TagsTable = createTagsTable(TagsTableRow);
const tags = (amount: number) => rangeOf(amount, (i) => `tag_${i}`);
let wrapper: ShallowWrapper;
const createWrapper = (filteredTags: string[] = [], search = '') => {
@ -86,7 +85,7 @@ describe('<TagsTable />', () => {
expect(tagRows).toHaveLength(expectedRows);
tagRows.forEach((row, index) => {
expect(row.prop('tag')).toEqual(`tag_${index + offset + 1}`);
expect(row.prop('tag')).toEqual(expect.objectContaining({ tag: `tag_${index + offset + 1}` }));
});
});
@ -97,4 +96,25 @@ describe('<TagsTable />', () => {
(wrapper.find(SimplePaginator).prop('setCurrentPage') as Function)(5);
expect(wrapper.find(SimplePaginator).prop('currentPage')).toEqual(5);
});
it('orders tags when column is clicked', () => {
const wrapper = createWrapper(tags(100));
const firstRowText = () => (wrapper.find('tbody').find(TagsTableRow).first().prop('tag') as NormalizedTag).tag;
expect(firstRowText()).toEqual('tag_1');
wrapper.find('thead').find('th').first().simulate('click'); // Tag column ASC
expect(firstRowText()).toEqual('tag_1');
wrapper.find('thead').find('th').first().simulate('click'); // Tag column DESC
expect(firstRowText()).toEqual('tag_99');
wrapper.find('thead').find('th').at(2).simulate('click'); // Visits column - ASC
expect(firstRowText()).toEqual('tag_100');
wrapper.find('thead').find('th').at(2).simulate('click'); // Visits column - DESC
expect(firstRowText()).toEqual('tag_1');
wrapper.find('thead').find('th').at(2).simulate('click'); // Visits column - reset
expect(firstRowText()).toEqual('tag_1');
wrapper.find('thead').find('th').at(1).simulate('click'); // Short URLs column - ASC
expect(firstRowText()).toEqual('tag_100');
wrapper.find('thead').find('th').at(1).simulate('click'); // Short URLs column - DESC
expect(firstRowText()).toEqual('tag_1');
});
});

View file

@ -5,21 +5,18 @@ import { DropdownItem } from 'reactstrap';
import { TagsTableRow as createTagsTableRow } from '../../src/tags/TagsTableRow';
import { ReachableServer } from '../../src/servers/data';
import ColorGenerator from '../../src/utils/services/ColorGenerator';
import { TagStats } from '../../src/tags/data';
import { DropdownBtnMenu } from '../../src/utils/DropdownBtnMenu';
describe('<TagsTableRow />', () => {
const DeleteTagConfirmModal = () => null;
const EditTagModal = () => null;
const TagsTableRow = createTagsTableRow(DeleteTagConfirmModal, EditTagModal);
const TagsTableRow = createTagsTableRow(DeleteTagConfirmModal, EditTagModal, Mock.all<ColorGenerator>());
let wrapper: ShallowWrapper;
const createWrapper = (tagStats?: TagStats) => {
const createWrapper = (tagStats?: { visits?: number; shortUrls?: number }) => {
wrapper = shallow(
<TagsTableRow
tag="foo&bar"
tagStats={tagStats}
tag={{ tag: 'foo&bar', visits: tagStats?.visits ?? 0, shortUrls: tagStats?.shortUrls ?? 0 }}
selectedServer={Mock.of<ReachableServer>({ id: 'abc123' })}
colorGenerator={Mock.all<ColorGenerator>()}
/>,
);
@ -30,7 +27,7 @@ describe('<TagsTableRow />', () => {
it.each([
[ undefined, '0', '0' ],
[ Mock.of<TagStats>({ shortUrlsCount: 10, visitsCount: 3480 }), '10', '3,480' ],
[{ shortUrls: 10, visits: 3480 }, '10', '3,480' ],
])('shows expected tag stats', (stats, expectedShortUrls, expectedVisits) => {
const wrapper = createWrapper(stats);
const links = wrapper.find(Link);

View file

@ -4,7 +4,7 @@ import { identity, values } from 'ramda';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSortAmountDown as caretDownIcon } from '@fortawesome/free-solid-svg-icons';
import SortingDropdown, { SortingDropdownProps } from '../../src/utils/SortingDropdown';
import { OrderDir } from '../../src/utils/utils';
import { OrderDir } from '../../src/utils/helpers/ordering';
describe('<SortingDropdown />', () => {
let wrapper: ShallowWrapper;

View file

@ -0,0 +1,25 @@
import { determineOrderDir } from '../../../src/utils/helpers/ordering';
describe('ordering', () => {
describe('determineOrderDir', () => {
it('returns ASC when current order field and selected field are different', () => {
expect(determineOrderDir('foo', 'bar')).toEqual('ASC');
expect(determineOrderDir('bar', 'foo')).toEqual('ASC');
});
it('returns ASC when no current order dir is provided', () => {
expect(determineOrderDir('foo', 'foo')).toEqual('ASC');
expect(determineOrderDir('bar', 'bar')).toEqual('ASC');
});
it('returns DESC when current order field and selected field are equal and current order dir is ASC', () => {
expect(determineOrderDir('foo', 'foo', 'ASC')).toEqual('DESC');
expect(determineOrderDir('bar', 'bar', 'ASC')).toEqual('DESC');
});
it('returns undefined when current order field and selected field are equal and current order dir is DESC', () => {
expect(determineOrderDir('foo', 'foo', 'DESC')).toBeUndefined();
expect(determineOrderDir('bar', 'bar', 'DESC')).toBeUndefined();
});
});
});

View file

@ -1,28 +1,6 @@
import { capitalize, determineOrderDir, nonEmptyValueOrNull, rangeOf } from '../../src/utils/utils';
import { capitalize, nonEmptyValueOrNull, rangeOf } from '../../src/utils/utils';
describe('utils', () => {
describe('determineOrderDir', () => {
it('returns ASC when current order field and selected field are different', () => {
expect(determineOrderDir('foo', 'bar')).toEqual('ASC');
expect(determineOrderDir('bar', 'foo')).toEqual('ASC');
});
it('returns ASC when no current order dir is provided', () => {
expect(determineOrderDir('foo', 'foo')).toEqual('ASC');
expect(determineOrderDir('bar', 'bar')).toEqual('ASC');
});
it('returns DESC when current order field and selected field are equal and current order dir is ASC', () => {
expect(determineOrderDir('foo', 'foo', 'ASC')).toEqual('DESC');
expect(determineOrderDir('bar', 'bar', 'ASC')).toEqual('DESC');
});
it('returns undefined when current order field and selected field are equal and current order dir is DESC', () => {
expect(determineOrderDir('foo', 'foo', 'DESC')).toBeUndefined();
expect(determineOrderDir('bar', 'bar', 'DESC')).toBeUndefined();
});
});
describe('rangeOf', () => {
const func = (i: number) => `result_${i}`;
const size = 5;

View file

@ -2,7 +2,8 @@ import { shallow, ShallowWrapper } from 'enzyme';
import { range } from 'ramda';
import SortingDropdown from '../../../src/utils/SortingDropdown';
import PaginationDropdown from '../../../src/utils/PaginationDropdown';
import { OrderDir, rangeOf } from '../../../src/utils/utils';
import { rangeOf } from '../../../src/utils/utils';
import { OrderDir } from '../../../src/utils/helpers/ordering';
import { Stats } from '../../../src/visits/types';
import { SortableBarChartCard } from '../../../src/visits/charts/SortableBarChartCard';
import { HorizontalBarChart } from '../../../src/visits/charts/HorizontalBarChart';