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

Table Widget: core functionality #154

Merged
merged 20 commits into from
Jan 3, 2022
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
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Not released

- Fix: DrawingToolLayer disables interactivity of the layers behind it [#263](https://github.com/CartoDB/carto-react/pull/263)
- Add TableWidget [#154](https://github.com/CartoDB/carto-react/pull/154)

## 1.2.0-alpha.0 (2021-12-30)

Expand All @@ -24,7 +25,7 @@
- Refactor useViewportFeatures [#238](https://github.com/CartoDB/carto-react/pull/238)
- Add clear button for TimeSeriesWidget widget and enable the speed button even though the animation has not started [#239](https://github.com/CartoDB/carto-react/pull/239)
- Improve timeseries animation performance [#243](https://github.com/CartoDB/carto-react/pull/243)
- Fix TS type declarations for BasemapName and CartoSlice [#248](https://github.com/CartoDB/carto-react/pull/248)
- Fix TS type declarations for BasemapName and CartoSlice [#248](https://github.com/CartoDB/carto-react/pull/248)

## 1.1.3 (2021-12-04)

Expand Down
78 changes: 78 additions & 0 deletions packages/react-ui/__tests__/widgets/TableWidgetUI.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import TableWidgetUI from '../../src/widgets/TableWidgetUI/TableWidgetUI';
import { getMaterialUIContext } from './testUtils';
import { columns, rows } from '../../src/widgets/TableWidgetUI/mockData';

describe('TableWidgetUI', () => {
const Widget = (props) =>
getMaterialUIContext(<TableWidgetUI columns={columns} rows={rows} {...props} />);

test('renders with default props', () => {
render(<Widget />);
expect(screen.queryByText('State / Province')).toBeInTheDocument();
});

test('renders only specified columns', () => {
const keptFields = ['address', 'city'];
const filteredColumns = columns.filter((col) => keptFields.includes(col.field));
render(<Widget columns={filteredColumns} />);
columns.forEach((col) => {
if (keptFields.includes(col.field)) {
expect(screen.queryByText(col.headerName)).toBeInTheDocument();
} else {
expect(screen.queryByText(col.headerName)).not.toBeInTheDocument();
}
});
});

test('calls callback when clicking on a row', () => {
const mockOnRowClick = jest.fn();

render(<Widget onRowClick={mockOnRowClick} />);

const row = rows[1];
fireEvent.click(screen.getByText(row.address));
expect(mockOnRowClick).toHaveBeenCalledWith(row);
});

describe('sorting', () => {
test('clicking on a column name triggers a sort on this field', () => {
const mockOnSetSortBy = jest.fn();
const mockOnSetSortDirection = jest.fn();

render(
<Widget
sorting
onSetSortBy={mockOnSetSortBy}
onSetSortDirection={mockOnSetSortDirection}
/>
);

fireEvent.click(screen.getByText('Address'));
expect(mockOnSetSortBy).toHaveBeenCalledWith('address');
});

test('clicking a second time reverse the sort direction', () => {
const mockOnSetSortBy = jest.fn();
const mockOnSetSortDirection = jest.fn();

const props = {
sorting: true,
onSetSortBy: mockOnSetSortBy,
onSetSortDirection: mockOnSetSortDirection
};

const { rerender } = render(<Widget {...props} />);

fireEvent.click(screen.getByText('Address'));
expect(mockOnSetSortBy).toHaveBeenCalledWith('address');
expect(mockOnSetSortDirection).toHaveBeenCalledWith('asc');

// the component is fully controlled so we need to simulate the change of sort props
rerender(<Widget {...props} sortBy='address' sortDirection='asc' />);
fireEvent.click(screen.getByText('Address'));
expect(mockOnSetSortDirection).toHaveBeenCalledWith('desc');
});
});
});
3 changes: 3 additions & 0 deletions packages/react-ui/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
} from './widgets/TimeSeriesWidgetUI/hooks/TimeSeriesContext';
import useTimeSeriesInteractivity from './widgets/TimeSeriesWidgetUI/hooks/useTimeSeriesInteractivity';
import { CHART_TYPES } from './widgets/utils/constants';
import TableWidgetUI from './widgets/TableWidgetUI/TableWidgetUI';
import NoDataAlert from './widgets/NoDataAlert';
import FeatureSelectionWidgetUI from './widgets/FeatureSelectionWidgetUI';

Expand All @@ -30,7 +31,9 @@ export {
TimeSeriesProvider,
CHART_TYPES as TIME_SERIES_CHART_TYPES,
FeatureSelectionWidgetUI,
TableWidgetUI,
LegendWidgetUI,
LEGEND_TYPES,
NoDataAlert
};

2 changes: 2 additions & 0 deletions packages/react-ui/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import ScatterPlotWidgetUI from './widgets/ScatterPlotWidgetUI';
import TimeSeriesWidgetUI from './widgets/TimeSeriesWidgetUI/TimeSeriesWidgetUI';
import DrawingToolWidgetUI from './widgets/DrawingToolWidgetUI';
import { CHART_TYPES } from './widgets/TimeSeriesWidgetUI/utils/constants';
import TableWidgetUI from './widgets/TableWidgetUI/TableWidgetUI';
import NoDataAlert from './widgets/NoDataAlert';
import CursorIcon from './assets/CursorIcon';
import PolygonIcon from './assets/PolygonIcon';
Expand All @@ -35,6 +36,7 @@ export {
TimeSeriesWidgetUI,
DrawingToolWidgetUI,
CHART_TYPES as TIME_SERIES_CHART_TYPES,
TableWidgetUI,
LegendWidgetUI,
LEGEND_TYPES,
NoDataAlert,
Expand Down
209 changes: 209 additions & 0 deletions packages/react-ui/src/widgets/TableWidgetUI/TableWidgetUI.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import React from 'react';
import PropTypes from 'prop-types';
import {
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
makeStyles,
TableSortLabel,
TablePagination
} from '@material-ui/core';

const useStyles = makeStyles((theme) => ({
tableHead: {
backgroundColor: theme.palette.common.white,
'& .MuiTableCell-head': {
border: 'none'
},
'& .MuiTableCell-head, & .MuiTableCell-head span': {
...theme.typography.caption,
color: theme.palette.text.secondary
}
},
tableRow: {
maxHeight: theme.spacing(6.5),
transition: 'background-color 0.25s ease',
'&.MuiTableRow-hover:hover': {
cursor: 'pointer',
backgroundColor: theme.palette.background.default
}
},
tableCell: {
overflow: 'hidden',
'& p': {
maxWidth: '100%',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis'
}
},
pagination: {
'& .MuiTablePagination-caption': {
...theme.typography.caption
},
'& .MuiTablePagination-caption:first-of-type': {
color: theme.palette.text.secondary
},
'& .MuiTablePagination-input': {
minHeight: theme.spacing(4.5),
border: `2px solid ${theme.palette.divider}`,
borderRadius: theme.spacing(0.5)
}
}
}));

function TableWidgetUI({
columns,
rows,
sorting,
sortBy,
sortDirection,
onSetSortBy,
onSetSortDirection,
pagination,
totalCount,
page,
onSetPage,
rowsPerPage,
rowsPerPageOptions,
onSetRowsPerPage,
onRowClick
}) {
const classes = useStyles();

const handleSort = (sortField) => {
const isAsc = sortBy === sortField && sortDirection === 'asc';
onSetSortDirection(isAsc ? 'desc' : 'asc');
onSetSortBy(sortField);
};

const handleChangePage = (_event, newPage) => {
onSetPage(newPage + 1);
};

const handleChangeRowsPerPage = (event) => {
onSetRowsPerPage(parseInt(event.target.value, 10));
onSetPage(1);
};

return (
<>
<TableContainer>
<Table>
<TableHeaderComponent
columns={columns}
sorting={sorting}
sortBy={sortBy}
sortDirection={sortDirection}
onSort={handleSort}
/>
<TableBodyComponent columns={columns} rows={rows} onRowClick={onRowClick} />
</Table>
</TableContainer>
{pagination && (
<TablePagination
className={classes.pagination}
rowsPerPageOptions={rowsPerPageOptions}
component='div'
count={totalCount}
rowsPerPage={rowsPerPage}
page={page - 1}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to make this adjustment because TablePagination from MUI is zero-based whereas our pagination API is 1-based (see https://github.com/CartoDB/carto-react/blob/master/packages/react-workers/src/workers/features.worker.js#L166)

Or maybe we could change our own implementation to start at page 0 too? Would it be possible @Clebal?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bbecquet totally agree, it's a mistake that page is 1-based. Sorry for my late response, I didn't saw this. Can you open a PR with that change?

onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
)}
</>
);
}

function TableHeaderComponent({ columns, sorting, sortBy, sortDirection, onSort }) {
const classes = useStyles();

return (
<TableHead className={classes.tableHead}>
<TableRow>
{columns.map(({ field, headerName, align }) => (
<TableCell key={field} align={align || 'left'}>
{sorting ? (
<TableSortLabel
active={sortBy === field}
direction={sortBy === field ? sortDirection : 'asc'}
onClick={() => onSort(field)}
>
{headerName}
</TableSortLabel>
) : (
headerName
)}
</TableCell>
))}
</TableRow>
</TableHead>
);
}

function TableBodyComponent({ columns, rows, onRowClick }) {
const classes = useStyles();

return (
<TableBody>
{rows.map((row, i) => {
const rowKey = row.cartodb_id || row.id || i;

return (
<TableRow
key={rowKey}
className={classes.tableRow}
hover={!!onRowClick}
onClick={() => onRowClick && onRowClick(row)}
>
{columns.map(
({ field, headerName, align, component }) =>
headerName && (
<TableCell
key={`${rowKey}_${field}`}
scope='row'
align={align || 'left'}
className={classes.tableCell}
>
{component ? component(row[field]) : row[field]}
</TableCell>
)
)}
</TableRow>
);
})}
</TableBody>
);
}

TableWidgetUI.defaultProps = {
sorting: false,
sortDirection: 'asc',
pagination: false,
rowsPerPage: 10,
rowsPerPageOptions: [5, 10, 25]
};

TableWidgetUI.propTypes = {
columns: PropTypes.array.isRequired,
rows: PropTypes.array.isRequired,
sorting: PropTypes.bool,
sortBy: PropTypes.string,
sortDirection: PropTypes.string,
onSetSortBy: PropTypes.func,
onSetSortDirection: PropTypes.func,
pagination: PropTypes.bool,
totalCount: PropTypes.number,
page: PropTypes.number,
onSetPage: PropTypes.func,
rowsPerPage: PropTypes.number,
rowsPerPageOptions: PropTypes.array,
onSetRowsPerPage: PropTypes.func,
onRowClick: PropTypes.func
};

export default TableWidgetUI;
Loading