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

[WIP] Common Table component (part 2) #2382

Draft
wants to merge 17 commits into
base: develop
Choose a base branch
from
Draft
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
56 changes: 56 additions & 0 deletions client/common/Table/StandardTable.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { omit } from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import TableBase from './TableBase';

/**
* Extends TableBase, but renders each row based on the columns.
* Can provide a `Dropdown` column which gets the `row` as a prop.
*/
function StandardTable({ Dropdown, columns, ...props }) {
const renderRow = (item) => (
<tr key={item.id}>
{columns.map((column, i) => {
const value = item[column.field];
const formatted = column.formatValue
? column.formatValue(value)
: value;
if (i === 0) {
return (
<th scope="row" key={column.field}>
{formatted}
</th>
);
}
return <td key={column.field}>{formatted}</td>;
})}
{
// TODO: styled-component
Dropdown && (
<td className="sketch-list__dropdown-column">
<Dropdown row={item} />
</td>
)
}
</tr>
);
return (
<TableBase
{...props}
columns={columns}
renderRow={renderRow}
addDropdownColumn={Boolean(Dropdown)}
/>
);
}

StandardTable.propTypes = {
...omit(TableBase.propTypes, ['renderRow', 'addDropdownColumn']),
Dropdown: PropTypes.elementType
};

StandardTable.defaultProps = {
Dropdown: null
};

export default StandardTable;
104 changes: 104 additions & 0 deletions client/common/Table/TableBase.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import classNames from 'classnames';
import { orderBy } from 'lodash';
import PropTypes from 'prop-types';
import React, { useState, useMemo } from 'react';
import Loader from '../../modules/App/components/loader';
import { DIRECTION } from '../../modules/IDE/actions/sorting';
import { TableEmpty } from './TableElements';
import TableHeaderCell, { StyledHeaderCell } from './TableHeaderCell';

const toAscDesc = (direction) => (direction === DIRECTION.ASC ? 'asc' : 'desc');

/**
* Renders the headers, loading spinner, empty message.
* Applies sorting to the items.
* Expects a `renderRow` prop to render each row.
*/
function TableBase({
initialSort,
columns,
items = [],
isLoading,
emptyMessage,
caption,
addDropdownColumn,
renderRow,
className
}) {
const [sorting, setSorting] = useState(initialSort);

const sortedItems = useMemo(
() => orderBy(items, sorting.field, toAscDesc(sorting.direction)),
[sorting.field, sorting.direction, items]
);

if (isLoading) {
return <Loader />;
}

if (items.length === 0) {
return <TableEmpty>{emptyMessage}</TableEmpty>;
}

return (
<table
className={classNames('sketches-table', className)}
// TODO: summary is deprecated. Use a hidden <caption>.
summary={caption}
>
<thead>
<tr>
{columns.map((column) => (
<TableHeaderCell
key={column.field}
sorting={sorting}
onSort={setSorting}
field={column.field}
defaultOrder={column.defaultOrder}
title={column.title}
/>
))}
{addDropdownColumn && <StyledHeaderCell scope="col" />}
</tr>
</thead>
<tbody>{sortedItems.map((item) => renderRow(item, columns))}</tbody>
</table>
);
}

TableBase.propTypes = {
initialSort: PropTypes.shape({
field: PropTypes.string.isRequired,
direction: PropTypes.string.isRequired
}).isRequired,
columns: PropTypes.arrayOf(
PropTypes.shape({
field: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
defaultOrder: PropTypes.oneOf([DIRECTION.ASC, DIRECTION.DESC]),
formatValue: PropTypes.func
})
).isRequired,
items: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired
// Will have other properties, depending on the type.
})
),
renderRow: PropTypes.func.isRequired,
addDropdownColumn: PropTypes.bool,
isLoading: PropTypes.bool,
emptyMessage: PropTypes.string.isRequired,
caption: PropTypes.string,
className: PropTypes.string
};

TableBase.defaultProps = {
items: [],
isLoading: false,
caption: '',
addDropdownColumn: false,
className: ''
};

export default TableBase;
63 changes: 63 additions & 0 deletions client/common/Table/TableBase.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import React from 'react';
import { DIRECTION } from '../../modules/IDE/actions/sorting';
import { render, screen } from '../../test-utils';
import TableBase from './TableBase';

describe('<TableBase/>', () => {
const items = [
{ id: '1', name: 'abc', count: 3 },
{ id: '2', name: 'def', count: 10 }
];

const props = {
items,
initialSort: { field: 'count', direction: DIRECTION.DESC },
emptyMessage: 'No items found',
renderRow: (item) => <tr key={item.id} />,
columns: []
};

const subject = (overrideProps) =>
render(<TableBase {...props} {...overrideProps} />);

jest.spyOn(props, 'renderRow');

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

it('shows a spinner when loading', () => {
subject({ isLoading: true });

expect(document.querySelector('.loader')).toBeInTheDocument();
});

it('show the `emptyMessage` when there are no items', () => {
subject({ items: [] });

expect(screen.getByText(props.emptyMessage)).toBeVisible();
});

it('calls `renderRow` function for each row', () => {
subject();

expect(props.renderRow).toHaveBeenCalledTimes(2);
});

it('sorts the items', () => {
subject();

expect(props.renderRow).toHaveBeenNthCalledWith(1, items[1]);
expect(props.renderRow).toHaveBeenNthCalledWith(2, items[0]);
});

it('does not add an extra header if `addDropdownColumn` is false', () => {
subject({ addDropdownColumn: false });
expect(screen.queryByRole('columnheader')).not.toBeInTheDocument();
});

it('adds an extra header if `addDropdownColumn` is true', () => {
subject({ addDropdownColumn: true });
expect(screen.getByRole('columnheader')).toBeInTheDocument();
});
});
10 changes: 10 additions & 0 deletions client/common/Table/TableElements.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import React from 'react';
import styled from 'styled-components';
import { remSize } from '../../theme';

// eslint-disable-next-line import/prefer-default-export
export const TableEmpty = styled.p`
text-align: center;
font-size: ${remSize(16)};
padding: ${remSize(42)} 0;
`;
100 changes: 100 additions & 0 deletions client/common/Table/TableHeaderCell.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import PropTypes from 'prop-types';
import React from 'react';
import { useTranslation } from 'react-i18next';
import styled from 'styled-components';
import { DIRECTION } from '../../modules/IDE/actions/sorting';
import { prop, remSize } from '../../theme';
import { SortArrowDownIcon, SortArrowUpIcon } from '../icons';

const opposite = (direction) =>
direction === DIRECTION.ASC ? DIRECTION.DESC : DIRECTION.ASC;

const ariaSort = (direction) =>
direction === DIRECTION.ASC ? 'ascending' : 'descending';

const TableHeaderTitle = styled.span`
border-bottom: 2px dashed transparent;
padding: ${remSize(3)} 0;
color: ${prop('inactiveTextColor')};
${(props) => props.selected && `border-color: ${prop('accentColor')(props)}`}
`;

export const StyledHeaderCell = styled.th`
height: ${remSize(32)};
position: sticky;
top: 0;
z-index: 1;
background-color: ${prop('backgroundColor')};
font-weight: normal;
&:nth-child(1) {
padding-left: ${remSize(12)};
}
button {
display: flex;
align-items: center;
height: ${remSize(35)};
svg {
margin-left: ${remSize(8)};
fill: ${prop('inactiveTextColor')};
}
}
`;

const TableHeaderCell = ({ sorting, field, title, defaultOrder, onSort }) => {
const isSelected = sorting.field === field;
const { direction } = sorting;
const { t } = useTranslation();
const directionWhenClicked = isSelected ? opposite(direction) : defaultOrder;
// TODO: more generic translation properties
const translationKey =
directionWhenClicked === DIRECTION.ASC
? 'SketchList.ButtonLabelAscendingARIA'
: 'SketchList.ButtonLabelDescendingARIA';
const buttonLabel = t(translationKey, {
displayName: title
});

return (
<StyledHeaderCell
scope="col"
aria-sort={isSelected ? ariaSort(direction) : null}
>
<button
onClick={() => onSort({ field, direction: directionWhenClicked })}
aria-label={buttonLabel}
aria-pressed={isSelected}
>
<TableHeaderTitle selected={isSelected}>{title}</TableHeaderTitle>
{/* TODO: show icons on hover of cell */}
{isSelected && direction === DIRECTION.ASC && (
<SortArrowUpIcon
aria-label={t('SketchList.DirectionAscendingARIA')}
/>
)}
{isSelected && direction === DIRECTION.DESC && (
<SortArrowDownIcon
aria-label={t('SketchList.DirectionDescendingARIA')}
/>
)}
</button>
</StyledHeaderCell>
);
};

TableHeaderCell.propTypes = {
sorting: PropTypes.shape({
field: PropTypes.string.isRequired,
direction: PropTypes.string.isRequired
}).isRequired,
field: PropTypes.string.isRequired,
title: PropTypes.string,
defaultOrder: PropTypes.oneOf([DIRECTION.ASC, DIRECTION.DESC]),
onSort: PropTypes.func.isRequired
};

TableHeaderCell.defaultProps = {
title: '',
defaultOrder: DIRECTION.ASC
};

export default TableHeaderCell;
Loading
Loading