UNPKG

2.74 kBJavaScriptView Raw
1/*
2 * Copyright (c) Jupyter Development Team.
3 * Distributed under the terms of the Modified BSD License.
4 */
5import React, { useState } from 'react';
6import { caretDownIcon, caretUpIcon } from '../icon';
7export const TABLE_CLASS = 'jp-sortable-table';
8/**
9 * Sortable table component for small datasets.
10 *
11 * For large datasets use `DataGrid` from `@lumino/datagrid`.
12 */
13export function Table(props) {
14 const [sortState, setSortState] = useState({
15 sortKey: props.sortKey,
16 sortDirection: props.sortDirection || 1
17 });
18 const sort = (key) => {
19 if (key === sortState.sortKey) {
20 setSortState({
21 sortKey: key,
22 sortDirection: (sortState.sortDirection * -1)
23 });
24 }
25 else {
26 setSortState({ sortKey: key, sortDirection: 1 });
27 }
28 };
29 let rows = props.rows;
30 const sortedColumn = props.columns.filter(column => column.id === sortState.sortKey)[0];
31 if (sortedColumn) {
32 const sorter = sortedColumn.sort.bind(sortedColumn);
33 rows = props.rows.sort((a, b) => sorter(a.data, b.data) * sortState.sortDirection);
34 }
35 const visibleColumns = props.columns.filter(column => (column.isAvailable ? column.isAvailable() : true) && !column.isHidden);
36 const elements = rows.map(row => {
37 const cells = visibleColumns.map(column => (React.createElement("td", { key: column.id + '-' + row.key }, column.renderCell(row.data))));
38 return (React.createElement("tr", { key: row.key, "data-key": row.key, onClick: props.onRowClick, className: 'jp-sortable-table-tr' }, cells));
39 });
40 const columnsHeaders = visibleColumns.map(column => (React.createElement(SortableTH, { label: column.label, id: column.id, state: sortState, key: column.id, onSort: () => {
41 sort(column.id);
42 } })));
43 return (React.createElement("table", { className: TABLE_CLASS },
44 React.createElement("thead", null,
45 React.createElement("tr", { className: 'jp-sortable-table-tr' }, columnsHeaders)),
46 React.createElement("tbody", null, elements)));
47}
48function SortableTH(props) {
49 const isSortKey = props.id === props.state.sortKey;
50 const sortIcon = !isSortKey || props.state.sortDirection === 1 ? caretUpIcon : caretDownIcon;
51 return (React.createElement("th", { key: props.id, onClick: () => props.onSort(), className: isSortKey ? 'jp-sorted-header' : undefined, "data-id": props.id },
52 React.createElement("div", { className: "jp-sortable-table-th-wrapper" },
53 React.createElement("label", null, props.label),
54 React.createElement(sortIcon.react, { tag: "span", className: "jp-sort-icon" }))));
55}
56//# sourceMappingURL=table.js.map
\No newline at end of file