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

Add optional sort function to columns #12

Merged
merged 1 commit into from
Aug 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
12 changes: 12 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,11 @@
"devDependencies": {
"@testing-library/jest-dom": "^5.11.3",
"@testing-library/react": "^10.4.8",
"@types/faker": "^4.1.12",
"@types/react": "^16.9.46",
"@types/react-dom": "^16.9.8",
"codecov": "^3.7.2",
"faker": "^4.1.0",
"husky": "^4.2.5",
"react": "^16.13.1",
"react-dom": "^16.13.1",
Expand Down
28 changes: 20 additions & 8 deletions src/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
DataType,
UseTableReturnType,
UseTableOptionsType,
RowType,
} from './types';
import { byTextAscending, byTextDescending } from './utils';

Expand All @@ -24,9 +25,22 @@ const createReducer = <T extends DataType>() => (

let isAscending = null;

let sortedRows: RowType<T>[] = [];

const columnCopy = state.columns.map(column => {
if (action.columnName === column.name) {
isAscending = column.sorted.asc;
if (column.sort) {
sortedRows = isAscending
? state.rows.sort(column.sort)
: state.rows.sort(column.sort).reverse();
} else {
sortedRows = state.rows.sort(
isAscending
? byTextAscending(object => object.original[action.columnName])
: byTextDescending(object => object.original[action.columnName])
);
}
return {
...column,
sorted: {
Expand All @@ -47,11 +61,7 @@ const createReducer = <T extends DataType>() => (
return {
...state,
columns: columnCopy,
rows: state.rows.sort(
isAscending
? byTextAscending(object => object.original[action.columnName])
: byTextDescending(object => object.original[action.columnName])
),
rows: sortedRows,
columnsById: getColumnsById(columnCopy),
};
case 'GLOBAL_FILTER':
Expand Down Expand Up @@ -154,7 +164,7 @@ const createReducer = <T extends DataType>() => (
};

export const useTable = <T extends DataType>(
columns: ColumnType[],
columns: ColumnType<T>[],
data: T[],
options?: UseTableOptionsType<T>
): UseTableReturnType<T> => {
Expand Down Expand Up @@ -245,7 +255,7 @@ const makeRender = <T extends DataType>(

const sortDataInOrder = <T extends DataType>(
data: T[],
columns: ColumnType[]
columns: ColumnType<T>[]
): T[] => {
return data.map((row: any) => {
const newRow: any = {};
Expand All @@ -259,7 +269,9 @@ const sortDataInOrder = <T extends DataType>(
});
};

const getColumnsById = (columns: ColumnType[]): ColumnByIdsType => {
const getColumnsById = <T extends DataType>(
columns: ColumnType<T>[]
): ColumnByIdsType => {
const columnsById: ColumnByIdsType = {};
columns.forEach(column => {
const col: any = {
Expand Down
47 changes: 44 additions & 3 deletions src/test/makeData.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ColumnType } from 'types';
import { ColumnType, DataType } from 'types';
import { date } from 'faker';

// from json-generator.com
const randomData = [
Expand Down Expand Up @@ -275,11 +276,51 @@ export type UserType = {
address: string;
};

export const makeData = (
export const makeData = <T extends {}>(
rowNum: number
): { columns: ColumnType[]; data: UserType[] } => {
): { columns: ColumnType<T>[]; data: UserType[] } => {
return {
columns,
data: randomData.slice(0, rowNum),
};
};

export const makeSimpleData = <T extends DataType>() => {
const columns: ColumnType<T>[] = [
{
name: 'firstName',
label: 'First Name',
},
{
name: 'lastName',
label: 'Last Name',
},
{
name: 'birthDate',
label: 'Birth Date',
},
];

const recentDate = date.recent();
const pastDate = date.past(undefined, recentDate);
const oldestDate = date.past(100, pastDate);

const data = [
{
firstName: 'Samwise',
lastName: 'Gamgee',
birthDate: pastDate.toISOString(),
},
{
firstName: 'Frodo',
lastName: 'Baggins',
birthDate: recentDate.toISOString(), // must be youngest for tests
},
{
firstName: 'Bilbo',
lastName: 'Baggins',
birthDate: oldestDate.toISOString(),
},
];
return { columns, data };
};
31 changes: 13 additions & 18 deletions src/test/selectionGlobalFiltering.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import React, { useCallback, useState } from 'react';
import { render, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import { useTable } from '../hooks';
import { ColumnType, RowType } from '../types';
import { makeData, UserType } from './makeData';
import { ColumnType, RowType, DataType } from '../types';
import { makeData } from './makeData';

const columns = [
{
Expand All @@ -27,17 +27,12 @@ const data = [
},
];

type TestDataType = {
firstName: string;
lastName: string;
};

const TableWithSelection = ({
const TableWithSelection = <T extends DataType>({
columns,
data,
}: {
columns: ColumnType[];
data: Object[];
columns: ColumnType<T>[];
data: T[];
}) => {
const { headers, rows, selectRow, selectedRows, toggleAll } = useTable(
columns,
Expand Down Expand Up @@ -122,14 +117,14 @@ test('Should be able to select rows', async () => {
expect(rtl.queryAllByTestId('selected-row')).toHaveLength(0);
});

const TableWithFilter = ({
const TableWithFilter = <T extends DataType>({
columns,
data,
filter,
}: {
columns: ColumnType[];
data: TestDataType[];
filter: (row: RowType<TestDataType>[]) => RowType<TestDataType>[];
columns: ColumnType<T>[];
data: T[];
filter: (row: RowType<T>[]) => RowType<T>[];
}) => {
const { headers, rows } = useTable(columns, data, {
filter,
Expand Down Expand Up @@ -171,20 +166,20 @@ test('Should be able to filter rows', () => {
expect(rtl.getAllByTestId('table-row')).toHaveLength(1);
});

const TableWithSelectionAndFiltering = ({
const TableWithSelectionAndFiltering = <T extends DataType>({
columns,
data,
}: {
columns: ColumnType[];
data: UserType[];
columns: ColumnType<T>[];
data: T[];
}) => {
const [searchString, setSearchString] = useState('');
const [filterOn, setFilterOn] = useState(false);

const { headers, rows, selectRow, selectedRows } = useTable(columns, data, {
selectable: true,
filter: useCallback(
(rows: RowType<UserType>[]) => {
(rows: RowType<T>[]) => {
return rows.filter(row => {
return (
row.cells.filter(cell => {
Expand Down
53 changes: 49 additions & 4 deletions src/test/sorting.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import '@testing-library/jest-dom/extend-expect';

import { useTable } from '../hooks';
import { ColumnType } from '../types';
import { makeData } from './makeData';
import { makeData, makeSimpleData } from './makeData';

const Table = ({
const Table = <T extends {}>({
columns,
data,
}: {
columns: ColumnType[];
data: Object[];
columns: ColumnType<T>[];
data: T[];
}) => {
const { headers, rows, toggleSort } = useTable(columns, data, {
sortable: true,
Expand Down Expand Up @@ -75,3 +75,48 @@ test('Should render a table with sorting enabled', () => {
({ getByText } = within(firstRow));
expect(getByText('Yesenia')).toBeInTheDocument();
});

test('Should sort by dates correctly', () => {
const { columns, data } = makeSimpleData<{
firstName: string;
lastName: string;
birthDate: string;
}>();
columns[2] = {
name: 'birthDate',
label: 'Birth Date',
sort: (objectA, objectB) => {
return (
Number(new Date(objectA.original.birthDate)) -
Number(new Date(objectB.original.birthDate))
);
},
};
const rtl = render(<Table columns={columns} data={data} />);

const dateColumn = rtl.getByTestId('column-birthDate');

// should be sorted in ascending order
fireEvent.click(dateColumn);

expect(rtl.queryByTestId('sorted-birthDate')).toBeInTheDocument();

let firstRow = rtl.getByTestId('row-0');
let lastRow = rtl.getByTestId('row-2');

let { getByText } = within(firstRow);
expect(getByText('Bilbo')).toBeInTheDocument();
({ getByText } = within(lastRow));
expect(getByText('Frodo')).toBeInTheDocument();

// should be sorted in descending order
fireEvent.click(dateColumn);

firstRow = rtl.getByTestId('row-0');
lastRow = rtl.getByTestId('row-2');

({ getByText } = within(firstRow));
expect(getByText('Frodo')).toBeInTheDocument();
({ getByText } = within(lastRow));
expect(getByText('Bilbo')).toBeInTheDocument();
});
4 changes: 2 additions & 2 deletions src/test/table.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const Table = ({
columns,
data,
}: {
columns: ColumnType[];
columns: any[];
data: { firstName: string; lastName: string }[];
}) => {
const { headers, rows } = useTable<{ firstName: string; lastName: string }>(
Expand Down Expand Up @@ -87,7 +87,7 @@ test('Should be equal regardless of field order in data', () => {
expect(normalTl.asFragment()).toEqual(reverseTl.asFragment());
});

const columnsWithRender: ColumnType[] = [
const columnsWithRender: ColumnType<any>[] = [
{
name: 'firstName',
label: 'First Name',
Expand Down
15 changes: 9 additions & 6 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
export type ColumnType = {
export type ColumnType<T> = {
name: string;
label?: string;
hidden?: boolean;
sort?: ((a: RowType<T>, b: RowType<T>) => number) | undefined;
render?: (value: any) => React.ReactNode;
};

export type HeaderType = {
// this is the type saved as state and returned
export type HeaderType<T> = {
name: string;
label?: string;
hidden?: boolean;
sorted: {
on: boolean;
asc: boolean;
};
sort?: ((a: RowType<T>, b: RowType<T>) => number) | undefined;
render?: (value: any) => React.ReactNode;
};

Expand Down Expand Up @@ -52,7 +55,7 @@ export type CellType = {
};

export interface UseTableTypeParams<T extends DataType> {
columns: ColumnType[];
columns: ColumnType<T>[];
data: T[];
options?: {
sortable?: boolean;
Expand All @@ -63,7 +66,7 @@ export interface UseTableTypeParams<T extends DataType> {
}

export interface UseTablePropsType<T> {
columns: ColumnType[];
columns: ColumnType<T>[];
data: T[];
options?: {
sortable?: boolean;
Expand All @@ -79,7 +82,7 @@ export interface UseTableOptionsType<T> {
}

export interface UseTableReturnType<T> {
headers: HeaderType[];
headers: HeaderType<T>[];
originalRows: RowType<T>[];
rows: RowType<T>[];
selectedRows: RowType<T>[];
Expand All @@ -91,7 +94,7 @@ export interface UseTableReturnType<T> {

export type TableState<T extends DataType> = {
columnsById: ColumnByIdsType;
columns: HeaderType[];
columns: HeaderType<T>[];
rows: RowType<T>[];
originalRows: RowType<T>[];
selectedRows: RowType<T>[];
Expand Down