datatable-tree 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +251 -2
- package/dist/DataTable.d.ts +583 -0
- package/dist/DataTable.js +620 -0
- package/dist/Draggable.d.ts +35 -0
- package/dist/Draggable.js +91 -0
- package/dist/ListBox.d.ts +132 -0
- package/dist/ListBox.js +243 -0
- package/dist/ListVirtualizer.d.ts +59 -0
- package/dist/ListVirtualizer.js +180 -0
- package/dist/TreeList.d.ts +196 -0
- package/dist/TreeList.js +300 -0
- package/dist/config.d.ts +55 -0
- package/dist/config.js +33 -0
- package/dist/datatable.css +161 -0
- package/dist/hooks.d.ts +27 -0
- package/dist/hooks.js +115 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +15 -0
- package/dist/interfaces.d.ts +269 -0
- package/dist/interfaces.js +3 -0
- package/dist/mobx-adapter.d.ts +12 -0
- package/dist/mobx-adapter.js +21 -0
- package/dist/reactivity.d.ts +112 -0
- package/dist/reactivity.js +155 -0
- package/dist/styles.d.ts +64 -0
- package/dist/styles.js +86 -0
- package/dist/theme.d.ts +160 -0
- package/dist/theme.js +239 -0
- package/dist/util.d.ts +28 -0
- package/dist/util.js +45 -0
- package/package.json +143 -4
- package/src/DataTable.tsx +1332 -0
- package/src/Draggable.tsx +133 -0
- package/src/ListBox.tsx +423 -0
- package/src/ListVirtualizer.ts +234 -0
- package/src/TreeList.tsx +590 -0
- package/src/config.tsx +96 -0
- package/src/css.d.ts +1 -0
- package/src/datatable.css +161 -0
- package/src/hooks.ts +138 -0
- package/src/index.ts +15 -0
- package/src/interfaces.ts +309 -0
- package/src/mobx-adapter.ts +24 -0
- package/src/reactivity.ts +222 -0
- package/src/styles.tsx +102 -0
- package/src/theme.ts +346 -0
- package/src/util.ts +60 -0
|
@@ -0,0 +1,1332 @@
|
|
|
1
|
+
import { createContext, CSSProperties, ReactNode, Ref, RefObject, useContext, useRef, useState } from 'react';
|
|
2
|
+
|
|
3
|
+
import { Holder } from 'holders';
|
|
4
|
+
|
|
5
|
+
import { useTableConfig } from './config.js';
|
|
6
|
+
import { Draggable } from './Draggable.js';
|
|
7
|
+
import { coalesce, useForceUpdate } from './hooks.js';
|
|
8
|
+
import { IMapSource } from './interfaces.js';
|
|
9
|
+
import { useListCoreStyles } from './ListBox.js';
|
|
10
|
+
import { VirtualizationSettings } from './ListVirtualizer.js';
|
|
11
|
+
import {
|
|
12
|
+
getReactivityAdapter, reactive, useComputed, useWatched, WatchableArrayLike
|
|
13
|
+
} from './reactivity.js';
|
|
14
|
+
import { classAndStyle, Styles } from './styles.js';
|
|
15
|
+
import { TableTheme, useThemeProps } from './theme.js';
|
|
16
|
+
import {
|
|
17
|
+
getSelectionClass, TreeItem, TreeItemM, TreeItemProps, TreeListAuxProps, TreeListCore,
|
|
18
|
+
TreeListMainProps
|
|
19
|
+
} from './TreeList.js';
|
|
20
|
+
import { cx, newObjectWithPrototype, nully, Optionalize } from './util.js';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* `DataTable` overview
|
|
24
|
+
* --------------------
|
|
25
|
+
*
|
|
26
|
+
* `DataTable` and `DataTableCore` are based on `TreeListCore`, so please have a look at
|
|
27
|
+
* the simpler `TreeList`/`TreeListCore` components first. The difference is that while
|
|
28
|
+
* `TreeList` is a tree of "items", `DataTable` is a tree of "rows" and therefore adds
|
|
29
|
+
* a set of columns and column headers. If you want a plain table rather than a tree,
|
|
30
|
+
* simply don't provide properties that would make it a tree.
|
|
31
|
+
*
|
|
32
|
+
* - The only required props are `columns` and `list` (or `tree`). `list` is an array of any
|
|
33
|
+
* type `T`, while `columns` is typically an array of `DataTableColumn<T>`.
|
|
34
|
+
* - `DataTable` is the usual choice. `DataTableCore` is the same, but omits the outer
|
|
35
|
+
* `<div>` and `<table>` elements (which is useful if you want to change the rendering
|
|
36
|
+
* method, e.g. to avoid `table` in favor of flexbox).
|
|
37
|
+
* - The table uses `table-layout: fixed`, so the widths of the columns are determined by
|
|
38
|
+
* the header row alone. If you provide a numeric/Holder `width` for a column, the user
|
|
39
|
+
* can resize it by dragging the right edge of the column header.
|
|
40
|
+
* - To make a tree, provide a `getChildren` or `getParents` prop and set `isTreeCol: true`
|
|
41
|
+
* on exactly one of the columns.
|
|
42
|
+
* - If you want to mix different kinds of rows on a single table (often parents and
|
|
43
|
+
* children are different things, for example), the `getRowConfig` prop lets you
|
|
44
|
+
* configure behavior for each row type individually (see example below).
|
|
45
|
+
*
|
|
46
|
+
* Most important types
|
|
47
|
+
* --------------------
|
|
48
|
+
*
|
|
49
|
+
* - `DataTableProps`: props of `DataTable`. Inherits `DataTableCoreProps`, `TreeListMainProps`
|
|
50
|
+
* `TreeListAuxProps` and most of `ListCoreProps`.
|
|
51
|
+
* - `DataTableColumn<T,...>`: settings for a single column. Inherits from
|
|
52
|
+
* `DataTableCellConfig<T,T,...>`.
|
|
53
|
+
*
|
|
54
|
+
* Support for multiple row types
|
|
55
|
+
* ------------------------------
|
|
56
|
+
*
|
|
57
|
+
* A table has a single set of columns, but the way values are chosen for a column can be
|
|
58
|
+
* specified separately for each row type. Here is a simple example of a "file browser" to
|
|
59
|
+
* explain the principle:
|
|
60
|
+
*
|
|
61
|
+
* class FileInfo {
|
|
62
|
+
* constructor(public name: string, public folderPath: string, public size: number, public modified: Date) {}
|
|
63
|
+
* }
|
|
64
|
+
*
|
|
65
|
+
* const files = [
|
|
66
|
+
* new FileInfo('README.md', '', 1345, new Date(2024,0,2)),
|
|
67
|
+
* new FileInfo('index.html', 'Documents', 1345, new Date(2024,0,2)),
|
|
68
|
+
* new FileInfo('Life 3.0.pdf', 'Documents/Books/Nonfiction', 5235091, new Date(2022,2,3)),
|
|
69
|
+
* new FileInfo('Rules for Radicals.pdf', 'Documents/Books/Nonfiction', 583020, new Date(2022,0,1)),
|
|
70
|
+
* new FileInfo('IMG_20240106_101958_861.jpg', 'Documents/Photos', 5830220, new Date(2024,0,6)),
|
|
71
|
+
* new FileInfo('IMG_20240107_141614_680.jpg', 'Documents/Photos', 5731990, new Date(2024,0,7)),
|
|
72
|
+
* new FileInfo('test.pdf', 'Books/Nonfiction', 5235091, new Date(2022,2,3)),
|
|
73
|
+
* ];
|
|
74
|
+
*
|
|
75
|
+
* export function FileTree() {
|
|
76
|
+
* // You don't have to memoize the column configuration, but hey, why not?
|
|
77
|
+
* const { columns, folderConfig } = useMemo(getColumnsAndRowConfigs, []);
|
|
78
|
+
*
|
|
79
|
+
* return (
|
|
80
|
+
* // TypeScript can infer the type argument(s), but in case of a type error, the
|
|
81
|
+
* // error message tends to be easier to understand if the type argument is explicit.
|
|
82
|
+
* <DataTable<FileInfo|string>
|
|
83
|
+
* columns={columns}
|
|
84
|
+
* list={files}
|
|
85
|
+
* // `getParents` is only called for items in `list`, all of which are `FileInfo`.
|
|
86
|
+
* getParents={item => getParentPathsOf((item as FileInfo).folderPath, '/', true)}
|
|
87
|
+
* getRowConfig={item => {
|
|
88
|
+
* if (typeof item.item === 'string') {
|
|
89
|
+
* return folderConfig;
|
|
90
|
+
* }
|
|
91
|
+
* }}
|
|
92
|
+
* // Note: if your folders close, or the selection is lost, whenever the outer
|
|
93
|
+
* // component is re-rendered, it means you need to add a `getSelKey` prop.
|
|
94
|
+
* // But in this example the folders are just strings, which serve as
|
|
95
|
+
* // their own keys.
|
|
96
|
+
* />);
|
|
97
|
+
*
|
|
98
|
+
* function getColumnsAndRowConfigs() {
|
|
99
|
+
* // Basic column configuration
|
|
100
|
+
* let columns: DataTableColumn<string|FileInfo>[] = [
|
|
101
|
+
* {
|
|
102
|
+
* name: 'name',
|
|
103
|
+
* heading: 'Name',
|
|
104
|
+
* width: 300,
|
|
105
|
+
* isTreeCol: true,
|
|
106
|
+
* },
|
|
107
|
+
* {
|
|
108
|
+
* name: 'size',
|
|
109
|
+
* heading: 'Size',
|
|
110
|
+
* width: 100,
|
|
111
|
+
* renderCell(node, props) {
|
|
112
|
+
* let size = props.value as number;
|
|
113
|
+
* if (size > 1024 * 1024) {
|
|
114
|
+
* return `${(size / (1 << 20)).toFixed(1)} MiB`;
|
|
115
|
+
* } else {
|
|
116
|
+
* return size > 1024 ? `${(size / 1024).toFixed(1)} KiB` : `${size} bytes`;
|
|
117
|
+
* }
|
|
118
|
+
* }
|
|
119
|
+
* },
|
|
120
|
+
* {
|
|
121
|
+
* name: 'modified',
|
|
122
|
+
* heading: 'Modified',
|
|
123
|
+
* width: 220,
|
|
124
|
+
* renderCell(node, props) {
|
|
125
|
+
* return (props.value as unknown as Date).toLocaleString();
|
|
126
|
+
* }
|
|
127
|
+
* },
|
|
128
|
+
* ];
|
|
129
|
+
*
|
|
130
|
+
* // Configures "folder" (parent) rows
|
|
131
|
+
* let folder = new Map<string, DataTableCellConfig<string|FileInfo, string>>([
|
|
132
|
+
* ['name', {
|
|
133
|
+
* getValue: path => path.substring(path.lastIndexOf('/') + 1),
|
|
134
|
+
* getColSpan: _ => 3,
|
|
135
|
+
* }],
|
|
136
|
+
* ]);
|
|
137
|
+
*
|
|
138
|
+
* return { columns, folderConfig: { columns: folder } };
|
|
139
|
+
* }
|
|
140
|
+
* }
|
|
141
|
+
*
|
|
142
|
+
* In this example, files are `FileInfo` while folders are simply strings. The main `columns`
|
|
143
|
+
* list contains default settings, and configuration for a specific row type is specified with
|
|
144
|
+
* an object of type `ItemAndColumns` (`{ columns: Map<string, DataTableCellConfig<...>>, ... }`).
|
|
145
|
+
* In this example we only need a single `Map<string, DataTableCellConfig>` for folders, but
|
|
146
|
+
* often it's more convenient to define one for every row type.
|
|
147
|
+
*
|
|
148
|
+
* Note that the folders are derived on-the-fly from the files using `getParentPathsOf`
|
|
149
|
+
* (e.g. 'Books/Nonfiction' => ['Books', 'Books/Nonfiction']). You cannot simply use
|
|
150
|
+
* `folderPath.split('/')` because if a folder such as 'Nonfiction' appears as part of multiple
|
|
151
|
+
* paths, as it does in this example, `DataTable` will treat it like the "same" item, which can
|
|
152
|
+
* cause problems, e.g. if you click one of the 'Nonfiction' folders, the other one will be
|
|
153
|
+
* selected too. `getParentPathsOf` ensures that the two 'Nonfiction' folders are different
|
|
154
|
+
* strings, and a `getValue` method is also required so that 'Books/Nonfiction' shows up as
|
|
155
|
+
* 'Nonfiction'.
|
|
156
|
+
**/
|
|
157
|
+
|
|
158
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
159
|
+
//#region Column, heading, row and cell props
|
|
160
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
161
|
+
|
|
162
|
+
export type DefaultRowProps =
|
|
163
|
+
React.ComponentProps<'td'> &
|
|
164
|
+
React.ComponentProps<'tr'> & {
|
|
165
|
+
highlightChildrenOfSelectedParents?: boolean;
|
|
166
|
+
noPadding?: boolean|nully;
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
/** Settings for rendering cells in a specific column, either for a specific type of row (if
|
|
170
|
+
* this object is in the map returned by the table's `getRowConfig` prop), or for all rows.
|
|
171
|
+
* This type is a subset of `DataTableColumn`. The most important properties are `getValue`
|
|
172
|
+
* and `renderCell`.
|
|
173
|
+
*
|
|
174
|
+
* @template T is the union type of all rows in the DataTable or DataTableCore.
|
|
175
|
+
* @template TRow is the type of row that the the current object is designed for.
|
|
176
|
+
* @template ColName is the type of `name` and of `ColName` in the `this` passed to some functions
|
|
177
|
+
* @template ItemProps is the type of the `cellProps` property.
|
|
178
|
+
*/
|
|
179
|
+
export interface DataTableCellConfig<
|
|
180
|
+
T,
|
|
181
|
+
TRow=T,
|
|
182
|
+
ColName=string,
|
|
183
|
+
ItemProps=DefaultRowProps>
|
|
184
|
+
{
|
|
185
|
+
/** Contains props to apply to each cell in this column (except to the standard header cell),
|
|
186
|
+
* or a function to get a set of props that depends on the current row. */
|
|
187
|
+
cellProps?: ItemProps | ((item: TreeItem<T, TRow>) => ItemProps);
|
|
188
|
+
|
|
189
|
+
/** Provide this to customize the way that the value of this column is obtained
|
|
190
|
+
* from a row. If this is not provided, `node.item[this.name.toString()]` is used. The
|
|
191
|
+
* value obtained from this function is passed to the renderer via `TableCellProps`.
|
|
192
|
+
*
|
|
193
|
+
* The return type should be `ReactNode` if you don't provide `renderCell` or `RenderCell`,
|
|
194
|
+
* and `string|number|boolean` if you don't provide sorting properties such as
|
|
195
|
+
* `getSortableValue` or `compare`.
|
|
196
|
+
*
|
|
197
|
+
* If the table has a `getRowConfig` prop, it is called before `getValue`, both to
|
|
198
|
+
* determine what value of `item` will be passed to `getValue`, and also _which `getValue`
|
|
199
|
+
* function_ will be called, in case you provide different `getValue` functions for
|
|
200
|
+
* different row types.
|
|
201
|
+
*
|
|
202
|
+
* As a case study, let's consider `Date`. Here are the main ways you might handle
|
|
203
|
+
* rendering and sorting for them:
|
|
204
|
+
*
|
|
205
|
+
* 1. Convert the `Date` to a string in `getValue`, then provide a separate
|
|
206
|
+
* `getSortableValue` function that just returns the `Date` so that the column can be
|
|
207
|
+
* sorted correctly. In this case, you don't need to provide `renderCell`.
|
|
208
|
+
* 2. Return the `Date` from `getValue`, then check in `renderCell` whether `props.value`
|
|
209
|
+
* is actually a `Date` and, if so, format it as a string or JSX there.
|
|
210
|
+
* 3. Don't provide a `getValue` function at all, only a `renderCell`. In this case,
|
|
211
|
+
* `name` must refer to the property that contains the `Date`, and `renderCell` must
|
|
212
|
+
* convert the `Date` to a string or JSX.
|
|
213
|
+
**/
|
|
214
|
+
getValue?(this: DataTableColumn<T, TRow, ColName, ItemProps>, item: TRow, node: TreeItem<T>): any;
|
|
215
|
+
|
|
216
|
+
/** This function is called to render a column value to a ReactNode, not including the
|
|
217
|
+
* outer `<td>` element. If not provided, `defaultRenderCell` is used.
|
|
218
|
+
*
|
|
219
|
+
* You must provide `renderCell` or `RenderCell` if the cell's value (determined by `name`
|
|
220
|
+
* or `getValue`) is not always a `ReactNode` (string, number, boolean or JSX).
|
|
221
|
+
*
|
|
222
|
+
* You can think of rendering customizations as a three-level hierarchy:
|
|
223
|
+
*
|
|
224
|
+
* 1. `getValue` prop: in charge of selecting low-level cell content, such as a
|
|
225
|
+
* string, number, boolean or `<span>`. `DefaultDataTableRow` calls this function
|
|
226
|
+
* and stores the result in `TableCellProps.value`.
|
|
227
|
+
* 2. `renderCell` prop: in charge of selecting the "main" cell content, such as a
|
|
228
|
+
* `<div>` element to control padding.
|
|
229
|
+
* 3. `RenderCell` prop: the top level, in charge of rendering the entire cell
|
|
230
|
+
* including `<td>` and the tree indent (if any).
|
|
231
|
+
*
|
|
232
|
+
* In the simplest cases (e.g. string or boolean columns) you may not need to
|
|
233
|
+
* customize any of these, and in simple cases you only need to provide `getValue`.
|
|
234
|
+
* On the other end of the scale, you can provide `RenderCell` for maximum control.
|
|
235
|
+
* It is recommended that each level use the output of the previous level, i.e.
|
|
236
|
+
* `RenderCell` should get the "main" cell content by calling the function
|
|
237
|
+
* `column.renderCell ?? defaultRenderCell`, while `renderCell` should include
|
|
238
|
+
* `props.value` in its output.
|
|
239
|
+
***/
|
|
240
|
+
renderCell?(node: TreeItem<T, TRow>, props: DataTableCellProps<T, TRow, ColName, ItemProps>): React.ReactNode;
|
|
241
|
+
|
|
242
|
+
/** This component is used to render a data cell. Usually it should be left undefined
|
|
243
|
+
* so that the `DefaultDataTableCell` component will be used. If you just want to add
|
|
244
|
+
* attributes to the `<td>` element, you can set `cellProps` instead.
|
|
245
|
+
*
|
|
246
|
+
* If you provide this prop, you are responsible for rendering the outer `<td>` element,
|
|
247
|
+
* and for using other relevant attributes of the column and the cell to produce output,
|
|
248
|
+
* such as:
|
|
249
|
+
* - Including `cellProps` and `colSpan` in your output, if applicable
|
|
250
|
+
* - Including the value of the cell (`props.value`) into the output
|
|
251
|
+
* - Rendering the tree indent if `isTreeCol` may be true, e.g. by calling
|
|
252
|
+
* `props.renderTreeIndent?.()` and including its output at the left edge of the cell.
|
|
253
|
+
**/
|
|
254
|
+
RenderCell?: React.ComponentType<DataTableCellProps<T, TRow, ColName, ItemProps>>;
|
|
255
|
+
|
|
256
|
+
/** This function allows you to cause this column to span multiple columns sometimes.
|
|
257
|
+
* If this function returns a value greater than one, the default row rendering code
|
|
258
|
+
* will skip rendering the spanned columns after this column (e.g. if it returns 3,
|
|
259
|
+
* the row renderer skips rendering two columns afterward) and the default cell
|
|
260
|
+
* renderer will set the `colSpan` prop on the `td`. If this function returns a value
|
|
261
|
+
* less than one, it's treated the same as one. */
|
|
262
|
+
getColSpan?(node: TreeItem<T, TRow>, props: DataTableCellProps<T, TRow, ColName, ItemProps>): number|undefined;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Properties of a single column of a `<DataTable>`. The most important properties are
|
|
266
|
+
* `name`, `heading`, `getValue`, `width` and `renderCell`.
|
|
267
|
+
*
|
|
268
|
+
* @template T is the union type of all row types in the DataTable or DataTableCore.
|
|
269
|
+
* @template TRow is normally just `T`, but when the table has a `getRowConfig` prop, the
|
|
270
|
+
* configuration returned by that prop is combined with the information in the
|
|
271
|
+
* original `DataTableColumn<T,T>` objects to produce a set of objects of type
|
|
272
|
+
* `DataTableColumn<T,TRow>`.
|
|
273
|
+
* @template ColName is the type of the `name` property.
|
|
274
|
+
* @template ItemProps is the type of the `headingProps` and `cellProps` properties.
|
|
275
|
+
*/
|
|
276
|
+
export interface DataTableColumn<T, TRow=T, ColName=string, ItemProps=DefaultRowProps>
|
|
277
|
+
extends DataTableCellConfig<T, TRow, ColName, ItemProps>
|
|
278
|
+
{
|
|
279
|
+
/** The `name` property is used in the following ways.
|
|
280
|
+
* - If no `heading` or `RenderHeading` is provided, it is shown as the column heading
|
|
281
|
+
* - If no `getValue` is provided, `name.toString()` is treated as a property name
|
|
282
|
+
* and used to get the value for this column on each data row.
|
|
283
|
+
* - `name.toString()` is also used as the React `key` on the column heading
|
|
284
|
+
*
|
|
285
|
+
* IMPORTANT: `name` (if given) must be unique among columns in a table, because it is
|
|
286
|
+
* used as a React key. If it isn't unique, columns with that name may glitch out by, for
|
|
287
|
+
* example, being duplicated by React.
|
|
288
|
+
**/
|
|
289
|
+
name: ColName;
|
|
290
|
+
/** The label to show on the table heater. If this is missing, `name` is displayed. */
|
|
291
|
+
heading?: ReactNode;
|
|
292
|
+
/** True if this column is the "tree column" which is indented and has buttons to expand
|
|
293
|
+
* and collapse items that have children. If and only if this property is truthy, a prop
|
|
294
|
+
* called `renderTreeIndent` is provided to the cell renderer. */
|
|
295
|
+
isTreeCol?: boolean;
|
|
296
|
+
/** Default or current column width. Columns require a numeric `width` to allow users to
|
|
297
|
+
* resize (see also: `noResize`), but this prop is optional since the browser can choose a
|
|
298
|
+
* width based on the headings row of the table. Providing a `Holder` allows you to get
|
|
299
|
+
* the current width (in case the user resized it) or set the width dynamically. */
|
|
300
|
+
width?: number | Holder<number>;
|
|
301
|
+
|
|
302
|
+
/** When a user sorts a column by clicking it, normally the column is sorted by "value" of
|
|
303
|
+
* the column (based on `getValue` or `name`). If you need sorting to be based on something
|
|
304
|
+
* else, this property is the most convenient way to do it. See also: `getComparer`.
|
|
305
|
+
*
|
|
306
|
+
* Note: this prop doesn't have a row-type-specific version, so if you provide it,
|
|
307
|
+
* `getRowConfig` is not called as part of the sorting process.
|
|
308
|
+
**/
|
|
309
|
+
getSortableValue?(this: DataTableColumn<T, T, ColName, ItemProps>, node: TreeItem<T>): any;
|
|
310
|
+
|
|
311
|
+
/** A function to compare two values that were selected based on two rows of the table. The
|
|
312
|
+
* `a` and `b` values passed to the comparer are the values returned by `getSortableValue`,
|
|
313
|
+
* or by `getValue` if `getSortableValue` is not provided, or by using `name` to look up
|
|
314
|
+
* the value of the column. If no `compare` function is provided, `DataTableCore` will
|
|
315
|
+
* compare values using `>` and `<` operators instead.
|
|
316
|
+
*
|
|
317
|
+
* For text columns, you should typically use `compare: compareByLocale`.
|
|
318
|
+
**/
|
|
319
|
+
compare?: (a: any, b: any) => number;
|
|
320
|
+
|
|
321
|
+
/** This rarely-used prop provides full control over comparisons between items when sorting
|
|
322
|
+
* this column. If you provide this, then `getValue`, `getSortableValue` and `getComparer`
|
|
323
|
+
* are not called during the sorting process for this column. */
|
|
324
|
+
getNodeComparer?(this: DataTableColumn<T, T, ColName, ItemProps>, descending: boolean):
|
|
325
|
+
(a: TreeItem<T, T>, b: TreeItem<T, T>) => number;
|
|
326
|
+
|
|
327
|
+
/** Contains a `style` and/or `className` to apply to the heading cell.
|
|
328
|
+
* See also `DataTableCoreProps.headingRowProps`.
|
|
329
|
+
*
|
|
330
|
+
* Note: if you provide your own `RenderHeading` then this prop is only used if
|
|
331
|
+
* your custom renderer uses it. */
|
|
332
|
+
headingProps?: ItemProps;
|
|
333
|
+
|
|
334
|
+
/** This function is called to render a column header to a ReactNode. Your custom
|
|
335
|
+
* component must include the outer `<th>` element, and is recommended to use
|
|
336
|
+
* `headingProps`. **/
|
|
337
|
+
RenderHeading?: React.ComponentType<DataTableHeadingProps<T,ColName,ItemProps>>;
|
|
338
|
+
|
|
339
|
+
/** If true, users cannot sort the column by clicking on the column heading and the
|
|
340
|
+
* sort-direction icon (if any) is hidden. Sorting based on `sortComparer` and
|
|
341
|
+
* `columnsToSortBy` still works. */
|
|
342
|
+
noSort?: boolean;
|
|
343
|
+
/** If true, the resize cursor is not shown and the user cannot resize the column.
|
|
344
|
+
* Note: columns also cannot be resized if they don't have a `width` value. */
|
|
345
|
+
noResize?: boolean;
|
|
346
|
+
/** Maximum width when user is resizing (default: unlimited) */
|
|
347
|
+
maxWidth?: number;
|
|
348
|
+
/** A function to modify a proposed column width when user is resizing. If this is
|
|
349
|
+
* not provided, a default minimum column width of 30 (or `width`, if less than 30) is
|
|
350
|
+
* enforced. This function is called before enforcing `maxWidth`. */
|
|
351
|
+
clampWidth?(proposedWidth: number, column: DataTableColumn<T, T, ColName, ItemProps>): number;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Props passed to the renderer for the heading row of a `<DataTable>`.
|
|
355
|
+
* Note: if you need access to other props that were passed to `DataTable`,
|
|
356
|
+
* use `const tableProps = useContext(DataTableContext);`. */
|
|
357
|
+
export interface DataTableHeadingRowProps<ColName=string, ItemProps=DefaultRowProps> {
|
|
358
|
+
headingRowProps?: ItemProps;
|
|
359
|
+
/** A function to get which sort icon (ascending or descending) to show */
|
|
360
|
+
getColumnSortIndicator(colName: ColName): SortDirection|undefined;
|
|
361
|
+
/** A function to gets the current width of column width, if set. */
|
|
362
|
+
getColumnWidth(colName: ColName): number|undefined;
|
|
363
|
+
/** A function to save a column width. Called as the resize handle is dragged by the user. */
|
|
364
|
+
setColumnWidth(colName: ColName, width: number): void;
|
|
365
|
+
/** A function to change the table's sort order. */
|
|
366
|
+
onHeadingClick(colName: ColName): void;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Props passed to the renderer for an entire row of data in a DataTable. */
|
|
370
|
+
export interface DataTableRowProps<T, K=T, ItemProps=DefaultRowProps>
|
|
371
|
+
extends Omit<TreeItemProps<T, K, ItemProps>, 'renderItem'> {}
|
|
372
|
+
|
|
373
|
+
/** Props passed when rendering a single heading in a DataTable. */
|
|
374
|
+
export interface DataTableHeadingProps<T, ColName=string, ItemProps=DefaultRowProps>
|
|
375
|
+
extends DataTableHeadingRowProps<ColName, ItemProps>
|
|
376
|
+
{
|
|
377
|
+
/** Information about the column being rendered */
|
|
378
|
+
column: DataTableColumn<T, T, ColName, ItemProps>;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Props passed when rendering one cell of a DataTable. */
|
|
382
|
+
export interface DataTableCellProps<T, TRow=T, ColName=string, ItemProps=DefaultRowProps>
|
|
383
|
+
extends Optionalize<Omit<DataTableRowProps<T, unknown, ItemProps>, 'item'>, 'renderTreeIndent'>
|
|
384
|
+
{
|
|
385
|
+
/** Settings of the column being rendered. If the table has a `getRowConfig` prop, the
|
|
386
|
+
* settings it returns are included in this object. */
|
|
387
|
+
column: DataTableColumn<T, TRow, ColName, ItemProps>;
|
|
388
|
+
/** The current row (overridden by `getRowConfig(...).item`, if applicable). */
|
|
389
|
+
item: TreeItem<T, TRow>;
|
|
390
|
+
/** Value of the cell (obtained from `this.column.getValue(this.item)` or
|
|
391
|
+
* `this.item[this.column.name]`.) */
|
|
392
|
+
value: React.ReactNode;
|
|
393
|
+
/** Whether the current row is selected. */
|
|
394
|
+
isSelected: boolean|null;
|
|
395
|
+
/** Number of columns spanned by cell, if provided by `DataTableColumn.getColSpan()`. */
|
|
396
|
+
colSpan?: number;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** Sort order of the column, used in `DataTableCoreProps.columnsToSortBy` */
|
|
400
|
+
export enum SortDirection {
|
|
401
|
+
Ascending = 1,
|
|
402
|
+
Descending = -1
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Tells `DataTableCoreProps.getRowConfig` what section of the row is being rendered. */
|
|
406
|
+
export enum RowType {
|
|
407
|
+
Header = -1, Normal = 0, Footer = 1,
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
//#endregion
|
|
411
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
412
|
+
//#region DataTableCore and its props
|
|
413
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
414
|
+
|
|
415
|
+
/** Main properties of a `DataTable` or `DataTableCore`. The only required properties are
|
|
416
|
+
* `list` (or `tree`) and `columns`, but if you are showing a tree, it is recommended to
|
|
417
|
+
* also provide `getKey` to identify rows to React. */
|
|
418
|
+
export type DataTableCoreProps<T, K=T, ColName=string, ItemProps=DefaultRowProps> =
|
|
419
|
+
Omit<TreeListAuxProps<T, K, ItemProps>, 'RenderItem'|'renderItem'> &
|
|
420
|
+
TreeListMainProps<T> &
|
|
421
|
+
{
|
|
422
|
+
/** Describes each of the columns in this data table. */
|
|
423
|
+
columns: DataTableColumn<T, T, ColName, ItemProps>[];
|
|
424
|
+
/** Component type used to render the heading cells (including `<th>` element).
|
|
425
|
+
* If not provided, headers are rendered with `DefaultDataTableHeading`.
|
|
426
|
+
* This property can be overridden for specific columns in `DataTableColumn`. */
|
|
427
|
+
RenderHeading?: React.ComponentType<DataTableHeadingProps<T, ColName, ItemProps>>;
|
|
428
|
+
/** Component type used to render the data cells (including `<td>` element).
|
|
429
|
+
* It is recommended to leave this undefined in order to use `DefaultDataTableCell`.
|
|
430
|
+
* This property can be overridden for specific columns in `DataTableColumn`.
|
|
431
|
+
* If you're using any tree columns, be sure to render the tree indent
|
|
432
|
+
* using `props.renderTreeIndent?.()` and include its output.
|
|
433
|
+
**/
|
|
434
|
+
RenderCell?: React.ComponentType<DataTableCellProps<T, T, ColName, ItemProps>>;
|
|
435
|
+
/** Component type used to render the header row. The result must include the outer
|
|
436
|
+
* `tr` or `div` but the `<thead>` is added by `DataTableCore` unless `noTHeadBody`.
|
|
437
|
+
* If not provided, the headings are rendered with `DefaultDataTableHeadingRow`. */
|
|
438
|
+
RenderHeadingRow?: React.ComponentType<DataTableHeadingRowProps<ColName, ItemProps>>;
|
|
439
|
+
/** Component type used to render an entire row. The result must include the outer
|
|
440
|
+
* `tr` or `div`. If not provided, rows are rendered with `DefaultDataTableRow`. */
|
|
441
|
+
RenderDataRow?: React.ComponentType<DataTableRowProps<T, K, ItemProps>>;
|
|
442
|
+
/** Optional props to send to the renderer for the heading row (if there is one).
|
|
443
|
+
* BTW: the inherited `itemProps` prop specifies props to use for each data row. */
|
|
444
|
+
headingRowProps?: ItemProps;
|
|
445
|
+
/** Optional props to add to `<thead>` element. Ignored if `noStructureWrap` is true. */
|
|
446
|
+
theadProps?: React.HTMLProps<HTMLTableSectionElement>;
|
|
447
|
+
/** Optional props to add to `<thead>` element. Ignored if `noStructureWrap` is true. */
|
|
448
|
+
tbodyProps?: React.HTMLProps<HTMLTableSectionElement>;
|
|
449
|
+
/** Optional props to add to `<tfoot>` element. Ignored if `noStructureWrap` is true. */
|
|
450
|
+
tfootProps?: React.HTMLProps<HTMLTableSectionElement>;
|
|
451
|
+
/** If this is true, then no header row is included in the output. This allows you
|
|
452
|
+
* either to make a table without a header, or to provide a header manually, e.g.
|
|
453
|
+
*
|
|
454
|
+
* <table>
|
|
455
|
+
* <tr>
|
|
456
|
+
* <th colSpan={2}>Custom</th>
|
|
457
|
+
* <th colSpan={2}>Headings</th>
|
|
458
|
+
* </tr>
|
|
459
|
+
* <DataTableCore noHeader noTHeadBody list={L} columns={C}/>
|
|
460
|
+
* </table>
|
|
461
|
+
*
|
|
462
|
+
* NOTE: Column widths are controller by the header row, and don't work when using
|
|
463
|
+
* `noHeader` mode.
|
|
464
|
+
*/
|
|
465
|
+
noHeader?: boolean;
|
|
466
|
+
/** If this is true, the rows are not wrapped in `<thead>`, `<tbody>`, or `<tfoot>` elements. */
|
|
467
|
+
noStructureWrap?: boolean;
|
|
468
|
+
|
|
469
|
+
/** Optional list of columns to sort by, where the first item of the list is the primary
|
|
470
|
+
* sort key. This is treated as mutable by `DataTableCore`, so by providing an observable
|
|
471
|
+
* array here, you can find out (as well as change) what sort order the user has chosen.
|
|
472
|
+
* So that changes (including the user clicking headings) cause a re-render of the table,
|
|
473
|
+
* this should be an array the reactivity adapter can track: a `WatchableArray` (from
|
|
474
|
+
* this package) with the default adapter, or a MobX `observable.array` with the MobX
|
|
475
|
+
* adapter.
|
|
476
|
+
*
|
|
477
|
+
* Example in function-style component:
|
|
478
|
+
*
|
|
479
|
+
* const [columnsToSortBy] = useState(() => WatchableArray.from(
|
|
480
|
+
* [['myColumn', SortDirection.Descending]]) as WatchableArray<[string, SortDirection]>);
|
|
481
|
+
*
|
|
482
|
+
* return <DataTable list={...} columns={...} columnsToSortBy={columnsToSortBy}/>
|
|
483
|
+
**/
|
|
484
|
+
columnsToSortBy?: WatchableArrayLike<[ColName, SortDirection]>;
|
|
485
|
+
|
|
486
|
+
/** If provided, this is called on each row to find out how that row should be rendered.
|
|
487
|
+
* @param item Row being rendered.
|
|
488
|
+
* @param rowType Section of the table that is being rendered
|
|
489
|
+
* @returns The item to render (normally `item.item`) and the configuration of each column
|
|
490
|
+
* whose behavior you want to customize, or null/undefined to use the default
|
|
491
|
+
* configuration specified by `columns`. *The return type is incorrect.* The return type
|
|
492
|
+
* should actually be `ItemAndColumns<T,TRow,ColName,ItemProps> | nully` for some specific
|
|
493
|
+
* type `TRow`, but we could not find any way to express this in TypeScript.
|
|
494
|
+
**/
|
|
495
|
+
getRowConfig?(item: TreeItem<T>, rowType: RowType): ItemAndColumns<T,any,ColName,ItemProps> | nully;
|
|
496
|
+
|
|
497
|
+
/** Optional additional header rows that will be rendered underneath the normal header row. */
|
|
498
|
+
headerRows?: T[];
|
|
499
|
+
/** Optional footer rows that will be rendered underneath all other rows. */
|
|
500
|
+
footerRows?: T[];
|
|
501
|
+
/** These settings enable virtualization, which speeds up table rendering by not rendering
|
|
502
|
+
* off-screen items. */
|
|
503
|
+
virtualize?: VirtualizationSettings<T>;
|
|
504
|
+
};
|
|
505
|
+
|
|
506
|
+
/** Return type of `DataTableCoreProps.getRowConfig` */
|
|
507
|
+
export interface ItemAndColumns<T, TRow=T, ColName=string, ItemProps=DefaultRowProps> {
|
|
508
|
+
readonly columns: IMapSource<ColName, DataTableCellConfig<T, TRow, ColName, ItemProps>>;
|
|
509
|
+
/** If provided, `DefaultDataTableRow` renders this item instead of the original row
|
|
510
|
+
* value. If the original item has type `TRow`, you can omit this prop to render
|
|
511
|
+
* the original item. If the original item is not a `TRow`, this prop is required
|
|
512
|
+
* to avoid runtime type errors. */
|
|
513
|
+
item?: TRow;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** A table of data with columns and rows rendered based on user-specified objects. This
|
|
517
|
+
* is the core functionality of a `<DataTable>`, without the actual `<table>` element.
|
|
518
|
+
* It can be used the same way as `<DataTable>` except that you wrap it in a `<table>`.
|
|
519
|
+
* See `<DataTable>` for a usage example. By not including `<table>`, this component
|
|
520
|
+
* gives you additional ways to format the table, e.g. you can use `<caption>`, `<tfoot>`
|
|
521
|
+
* or an extra header row. Also, it is possible to construct a non-table grid (e.g. CSS
|
|
522
|
+
* grid) using this component and custom renderers. */
|
|
523
|
+
export const DataTableCore = reactive(function DataTableCore<T, K=T, ColName extends { toString(): string } = string, ItemProps extends Styles=DefaultRowProps>(
|
|
524
|
+
p: DataTableCoreProps<T, K, ColName, ItemProps>
|
|
525
|
+
) {
|
|
526
|
+
const RenderDataRow = (p.RenderDataRow ?? DefaultDataTableRow) as React.ComponentType<TreeItemProps<T, K, ItemProps>>;
|
|
527
|
+
const RenderHeadingRow = (p.RenderHeadingRow ?? DefaultDataTableHeadingRow);
|
|
528
|
+
const forceUpdate = useForceUpdate();
|
|
529
|
+
type ColState = { width?: number | Holder<number>, column: DataTableColumn<T, T, ColName, ItemProps> };
|
|
530
|
+
const [ columnState ] = useState(() => new Map<ColName, ColState>());
|
|
531
|
+
|
|
532
|
+
const colsToSortBy = useWatched(coalesce(p.columnsToSortBy,
|
|
533
|
+
useState(() => getReactivityAdapter().observableArray<[ColName, SortDirection]>())[0]));
|
|
534
|
+
|
|
535
|
+
// We want to wrap the table in the same context object if props used in child components
|
|
536
|
+
// haven't changed, so that all rows don't have to re-render. But if those props have changed,
|
|
537
|
+
// create a new context object to cause a re-render.
|
|
538
|
+
const tableContextInit = { rowConfigCache: new Map(), tableProps: p };
|
|
539
|
+
const tableContextRef = useRef<DataTableContext<T, K, ColName, ItemProps>>(tableContextInit);
|
|
540
|
+
tableContextRef.current.rowConfigCache.clear();
|
|
541
|
+
const prevProps = tableContextRef.current.tableProps;
|
|
542
|
+
if (prevProps.columns !== p.columns
|
|
543
|
+
|| prevProps.getRowConfig !== p.getRowConfig
|
|
544
|
+
|| prevProps.RenderHeading !== p.RenderHeading
|
|
545
|
+
|| prevProps.RenderCell !== p.RenderCell
|
|
546
|
+
|| prevProps.indentPerLevel !== p.indentPerLevel
|
|
547
|
+
) {
|
|
548
|
+
tableContextRef.current = tableContextInit;
|
|
549
|
+
}
|
|
550
|
+
tableContextRef.current.tableProps = p;
|
|
551
|
+
|
|
552
|
+
const sort = useComputed(
|
|
553
|
+
() => getSorter(colsToSortBy, tableContextRef.current),
|
|
554
|
+
[colsToSortBy, p.sortComparer, p.columns]).get();
|
|
555
|
+
|
|
556
|
+
// Update column state based on the column information provided
|
|
557
|
+
for (let column of p.columns) {
|
|
558
|
+
let state = columnState.get(column.name);
|
|
559
|
+
if (state == null) {
|
|
560
|
+
columnState.set(column.name, { column, width: column.width });
|
|
561
|
+
} else {
|
|
562
|
+
state.column = column;
|
|
563
|
+
if (typeof column.width === 'object') {
|
|
564
|
+
state.width = column.width;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
let headings = p.noHeader ? undefined :
|
|
570
|
+
<RenderHeadingRow
|
|
571
|
+
headingRowProps={p.headingRowProps}
|
|
572
|
+
getColumnWidth={name => {
|
|
573
|
+
const state = columnState.get(name);
|
|
574
|
+
if (state) {
|
|
575
|
+
return typeof state.width === 'object' ? state.width.get() : state.width;
|
|
576
|
+
}
|
|
577
|
+
}}
|
|
578
|
+
setColumnWidth={(name, width) => {
|
|
579
|
+
let state = columnState.get(name);
|
|
580
|
+
if (state) {
|
|
581
|
+
if (typeof state.width === 'object') {
|
|
582
|
+
state.width.set(width);
|
|
583
|
+
} else {
|
|
584
|
+
state.width = width;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}}
|
|
588
|
+
getColumnSortIndicator={(name) => {
|
|
589
|
+
if (colsToSortBy.length && colsToSortBy[0][0] === name)
|
|
590
|
+
return colsToSortBy[0][1];
|
|
591
|
+
}}
|
|
592
|
+
onHeadingClick={(name) => {
|
|
593
|
+
getReactivityAdapter().runInAction(() => {
|
|
594
|
+
let columnIndex = findSortTupleIndexByName(name);
|
|
595
|
+
if (columnIndex === 0) {
|
|
596
|
+
let column = colsToSortBy[columnIndex];
|
|
597
|
+
|
|
598
|
+
if (column[1] === SortDirection.Ascending)
|
|
599
|
+
column[1] = SortDirection.Descending;
|
|
600
|
+
else if (!p.sortComparer && !p.sort)
|
|
601
|
+
column[1] = SortDirection.Ascending;
|
|
602
|
+
else
|
|
603
|
+
colsToSortBy.clear(); // restore default sort order
|
|
604
|
+
} else {
|
|
605
|
+
if (columnIndex > 0) {
|
|
606
|
+
colsToSortBy.splice(columnIndex, 1);
|
|
607
|
+
}
|
|
608
|
+
colsToSortBy.unshift([name, SortDirection.Ascending]);
|
|
609
|
+
colsToSortBy.splice(4); // for efficiency, don't sort by too many columns
|
|
610
|
+
}
|
|
611
|
+
});
|
|
612
|
+
// With the default (non-MobX) adapter, flipping the sort direction mutates a
|
|
613
|
+
// tuple element in place, which even a WatchableArray can't detect. (With the
|
|
614
|
+
// MobX adapter this render is scheduled anyway, and React merges the two.)
|
|
615
|
+
forceUpdate();
|
|
616
|
+
}}/>;
|
|
617
|
+
|
|
618
|
+
if (p.headerRows != null) {
|
|
619
|
+
headings = <>
|
|
620
|
+
{headings}
|
|
621
|
+
<DataTableSection<T, K, ColName, ItemProps>
|
|
622
|
+
{...p} rowType={RowType.Header} list={p.headerRows} tree={undefined}
|
|
623
|
+
RenderItem={RenderDataRow} />
|
|
624
|
+
</>;
|
|
625
|
+
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
let rows =
|
|
629
|
+
<TreeListCore<T, K, ItemProps>
|
|
630
|
+
{...p}
|
|
631
|
+
sort={sort}
|
|
632
|
+
RenderItem={RenderDataRow}
|
|
633
|
+
virtualGapRenderer={p.virtualGapRenderer ?? renderVirtualGap}
|
|
634
|
+
/>;
|
|
635
|
+
|
|
636
|
+
let footer;
|
|
637
|
+
if (p.footerRows != null) {
|
|
638
|
+
footer = <DataTableSection<T, K, ColName, ItemProps>
|
|
639
|
+
{...p} rowType={RowType.Footer} list={p.footerRows} tree={undefined}
|
|
640
|
+
RenderItem={RenderDataRow} />;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
return (
|
|
644
|
+
<DataTableContext.Provider value={tableContextRef.current}>
|
|
645
|
+
{p.noStructureWrap
|
|
646
|
+
? headings
|
|
647
|
+
: <thead {...p.theadProps}>{headings}</thead>}
|
|
648
|
+
{p.noStructureWrap
|
|
649
|
+
? rows
|
|
650
|
+
: <tbody {...p.tbodyProps}>{rows}</tbody>}
|
|
651
|
+
{p.noStructureWrap || p.footerRows == null
|
|
652
|
+
? footer
|
|
653
|
+
: <tfoot {...p.tfootProps}>{footer}</tfoot>}
|
|
654
|
+
</DataTableContext.Provider>
|
|
655
|
+
);
|
|
656
|
+
|
|
657
|
+
function findSortTupleIndexByName(colName: ColName) {
|
|
658
|
+
return colsToSortBy.findIndex((([name]) => name === colName));
|
|
659
|
+
}
|
|
660
|
+
});
|
|
661
|
+
|
|
662
|
+
function renderVirtualGap(height: number, ref?: Ref<Element>) {
|
|
663
|
+
return <tr ref={ref as Ref<HTMLTableRowElement>} style={{ height }}/>;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function DataTableSection<T, K, ColName=string, ItemProps extends Styles=Styles>(p: {
|
|
667
|
+
RenderItem: React.ComponentType<TreeItemProps<T, K, ItemProps>>,
|
|
668
|
+
rowType: RowType,
|
|
669
|
+
} & DataTableCoreProps<T, K, ColName, ItemProps>
|
|
670
|
+
) {
|
|
671
|
+
return (
|
|
672
|
+
<DataTableSectionContext.Provider value={p.rowType}>
|
|
673
|
+
<TreeListCore<T, K, ItemProps>
|
|
674
|
+
{...p}
|
|
675
|
+
sortComparer={undefined}
|
|
676
|
+
filter={undefined}
|
|
677
|
+
virtualize={undefined}
|
|
678
|
+
virtualGapRenderer={undefined} />
|
|
679
|
+
</DataTableSectionContext.Provider>
|
|
680
|
+
);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
export interface DataTableContext<T,K=T,ColName=string,ItemProps=DefaultRowProps> {
|
|
684
|
+
rowConfigCache: Map<DataTableCellConfig<T,any,ColName,ItemProps>, DataTableColumn<T,any,ColName,ItemProps>>,
|
|
685
|
+
tableProps: DataTableCoreProps<T,K,ColName,ItemProps>;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/** This context can be used in a custom component used inside DataTable (e.g.
|
|
689
|
+
* a custom `RenderCell` component) to get the props that were passed to the
|
|
690
|
+
* data table. */
|
|
691
|
+
export const DataTableContext = createContext<DataTableContext<any,any,any,any>>({
|
|
692
|
+
rowConfigCache: new Map(),
|
|
693
|
+
tableProps: { list: [], columns: [] },
|
|
694
|
+
});
|
|
695
|
+
|
|
696
|
+
export const DataTableSectionContext = createContext<RowType>(RowType.Normal);
|
|
697
|
+
|
|
698
|
+
//#endregion
|
|
699
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
700
|
+
//#region DataTable and its props
|
|
701
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
702
|
+
|
|
703
|
+
/** Properties of a `DataTable`. The only required properties are `columns` and `list` (or
|
|
704
|
+
* `tree`), which are defined in the base interfaces `DataTableCoreProps` and `TreeListMainProps`.
|
|
705
|
+
* If you are using a tree view, it is recommended to also provide `getKey` (from the base
|
|
706
|
+
* interface `ListCoreProps`) to identify rows to React. */
|
|
707
|
+
export type DataTableProps<T, K=T, ColName=string, ItemProps=DefaultRowProps> =
|
|
708
|
+
DataTableCoreProps<T,K,ColName,ItemProps> & Styles &
|
|
709
|
+
{
|
|
710
|
+
/** Styles on the `<table>` element (the `style` and `className` on `DataTableProps`
|
|
711
|
+
* itelf are applied to an outer scrollable `<div>` that contains the `<table>`.) */
|
|
712
|
+
tableProps?: Styles & React.ComponentProps<'table'>;
|
|
713
|
+
/** Attributes to add to the outer `<div>` element that contains the `<table>` */
|
|
714
|
+
outerProps?: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
|
|
715
|
+
/** Theme for this table; overrides the ambient `TableConfig` theme. */
|
|
716
|
+
theme?: TableTheme | string | nully;
|
|
717
|
+
};
|
|
718
|
+
|
|
719
|
+
/** A table of data with columns and rows rendered based on user-specified objects.
|
|
720
|
+
* Also supports tree grids via the `getChildren` or `getParents` prop.
|
|
721
|
+
*
|
|
722
|
+
* By default, DataTable is rendered as a `<table>` element (with style `width: 100%`)
|
|
723
|
+
* wrapped in a `<div>` whose class includes `overflow: auto` so that a scroll bar
|
|
724
|
+
* appears automatically when appropriate. Other than that, the table size is not
|
|
725
|
+
* constrained and will automatically choose its own size. One simple way to limit
|
|
726
|
+
* min/max table size is to add `style={{ minHeight: N, maxHeight: M }}`. If the table
|
|
727
|
+
* is within a container that has its own min/max height, it might be better to set
|
|
728
|
+
* `display: flex; flex-direction: column` on that container and also set
|
|
729
|
+
* `style={{ flex: 1 }}` on the DataTable. This way, the table fills available space
|
|
730
|
+
* while also allowing space for other widgets.
|
|
731
|
+
*
|
|
732
|
+
* The table class includes `table-layout: fixed` and each `<th>` has an inline width
|
|
733
|
+
* controlled by the `DataTableColumn.width` value if you provided one. This is a
|
|
734
|
+
* minimum width; if the table is wider than the total widths of all columns, your
|
|
735
|
+
* browser will distribute excess available space among the columns automatically. If
|
|
736
|
+
* the table is less wide than the total widths of all columns, a horizontal scroll bar
|
|
737
|
+
* will appear. Drag handles appear by default so the user can change column widths (but
|
|
738
|
+
* the user's custom widths are forgotten when the component is unmounted.)
|
|
739
|
+
*
|
|
740
|
+
* Here's an example that shows a bunch of columns based on some simple `{ n: number }`
|
|
741
|
+
* objects, and shows certain items in tree form. In this example, `getParents`
|
|
742
|
+
* regenerates a parent object every time it is called, and the result is that the user
|
|
743
|
+
* can't expand parent rows unless a `getSelKey` prop is provided. This is because when
|
|
744
|
+
* the user expands a parent, the table is re-rendered and the originally-expanded
|
|
745
|
+
* parent object is no longer in the table! `getSelKey` fixes the problem causing the sets
|
|
746
|
+
* of selected and expanded items to be sets of numbers rather than objects. However,
|
|
747
|
+
* TypeScript can't infer that the type returned by `getSelKey` is correct, so type
|
|
748
|
+
* parameters are needed on `DataTable<{n: number}, number>`.
|
|
749
|
+
*
|
|
750
|
+
* <DataTable<{n: number}, number>
|
|
751
|
+
* list={[ { n:1 }, { n:3 }, { n:5 }, { n:36 }, { n:100 } ]}
|
|
752
|
+
* selMode="multi"
|
|
753
|
+
* columns={[
|
|
754
|
+
* {
|
|
755
|
+
* name: 'n',
|
|
756
|
+
* heading: 'Number',
|
|
757
|
+
* isTreeCol: true,
|
|
758
|
+
* },
|
|
759
|
+
* {
|
|
760
|
+
* name: 'Square', // Shown as the heading because `heading` is missing
|
|
761
|
+
* getValue(item: {n: number}) { return item.n * item.n; }
|
|
762
|
+
* },
|
|
763
|
+
* {
|
|
764
|
+
* name: 'Square root',
|
|
765
|
+
* getValue(item: {n: number}) { return Math.sqrt(item.n); }
|
|
766
|
+
* },
|
|
767
|
+
* {
|
|
768
|
+
* name: 'Odd?',
|
|
769
|
+
* getValue(item: {n: number}) { return (item.n & 1) !== 0; }
|
|
770
|
+
* },
|
|
771
|
+
* ]}
|
|
772
|
+
* getParents={item => {
|
|
773
|
+
* let root = Math.sqrt(item.n);
|
|
774
|
+
* return root === Math.round(root) ? [ { n: root } ] : undefined;
|
|
775
|
+
* }}
|
|
776
|
+
* getSelKey={item => item.n}
|
|
777
|
+
* />
|
|
778
|
+
*/
|
|
779
|
+
export function DataTable<T, K=T, ColName extends { toString(): string } = string, ItemProps extends Styles=DefaultRowProps>(
|
|
780
|
+
p: DataTableProps<T, K, ColName, ItemProps>
|
|
781
|
+
) {
|
|
782
|
+
const styles = useDataTableStyles();
|
|
783
|
+
const theme = useThemeProps(p.theme);
|
|
784
|
+
|
|
785
|
+
const containerRef = useRef(null);
|
|
786
|
+
let { virtualize } = p;
|
|
787
|
+
if (virtualize && virtualize.containerRef == null)
|
|
788
|
+
virtualize.containerRef = containerRef;
|
|
789
|
+
|
|
790
|
+
return (
|
|
791
|
+
<div ref={containerRef} tabIndex={0} {...p.outerProps}
|
|
792
|
+
{...classAndStyle(p, cx(styles.outerDiv, theme.className), theme.style)}>
|
|
793
|
+
<table {...p.tableProps} {...classAndStyle(p.tableProps, styles.table)}>
|
|
794
|
+
<DataTableCore {...p}/>
|
|
795
|
+
</table>
|
|
796
|
+
</div>);
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
//#endregion
|
|
800
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
801
|
+
//#region Rendering of header row
|
|
802
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
803
|
+
|
|
804
|
+
export function DefaultDataTableHeadingRow(p: DataTableHeadingRowProps<any, any>) {
|
|
805
|
+
const { tableProps } = useContext(DataTableContext);
|
|
806
|
+
const RenderHeading = tableProps.RenderHeading ?? DefaultDataTableHeading;
|
|
807
|
+
const styles = useDataTableStyles();
|
|
808
|
+
|
|
809
|
+
let className = styles[(p.headingRowProps as DefaultRowProps)?.noPadding ? 'row' : 'rowPadded'];
|
|
810
|
+
return (
|
|
811
|
+
<tr {...p.headingRowProps} {...classAndStyle(p.headingRowProps, className)}>
|
|
812
|
+
{tableProps.columns.map((col, i) => {
|
|
813
|
+
let RenderHeading2 = col.RenderHeading ?? RenderHeading;
|
|
814
|
+
return <RenderHeading2 key={col.name?.toString()} {...p} column={col}/>;
|
|
815
|
+
})}
|
|
816
|
+
</tr>
|
|
817
|
+
);
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
export let defaultClampWidth = {
|
|
821
|
+
current(w: number, c: DataTableColumn<any, any, any, any>) {
|
|
822
|
+
let baseWidth = typeof c.width === 'number' ? c.width : c.width?.get();
|
|
823
|
+
return Math.max(Math.min(30, baseWidth ?? 30), w);
|
|
824
|
+
}
|
|
825
|
+
};
|
|
826
|
+
|
|
827
|
+
export function DefaultDataTableHeading(p: DataTableHeadingProps<any,any,any>) {
|
|
828
|
+
const styles = useDataTableStyles();
|
|
829
|
+
const { icons } = useTableConfig();
|
|
830
|
+
const refresh = useForceUpdate();
|
|
831
|
+
const width = p.getColumnWidth(p.column.name);
|
|
832
|
+
const extraProps = p.column.headingProps;
|
|
833
|
+
const content = p.column.heading !== undefined ? p.column.heading : p.column.name;
|
|
834
|
+
// If the user drags the column resizer, a click event still occurs. This is used
|
|
835
|
+
// to prevent that event from doing anything.
|
|
836
|
+
const isDragging = useRef(false);
|
|
837
|
+
|
|
838
|
+
let widthH, style, draggableStyle;
|
|
839
|
+
if (width != null) {
|
|
840
|
+
style = { width };
|
|
841
|
+
if (!p.column.noResize) {
|
|
842
|
+
widthH = {
|
|
843
|
+
get() { return width; },
|
|
844
|
+
set(w: number) {
|
|
845
|
+
w = (p.column.clampWidth ?? defaultClampWidth.current)(w, p.column);
|
|
846
|
+
if (p.column.maxWidth != null && w > p.column.maxWidth) {
|
|
847
|
+
w = p.column.maxWidth;
|
|
848
|
+
}
|
|
849
|
+
if (w >= 0 && !Number.isNaN(w)) {
|
|
850
|
+
p.setColumnWidth(p.column.name, w);
|
|
851
|
+
refresh();
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
let sortIcon;
|
|
859
|
+
if (!p.column.noSort) {
|
|
860
|
+
const sortIndicator = p.getColumnSortIndicator(p.column.name);
|
|
861
|
+
style = { ...style, paddingRight: 16, cursor: 'pointer' } as CSSProperties;
|
|
862
|
+
draggableStyle = { right: -10 };
|
|
863
|
+
|
|
864
|
+
if (sortIndicator != null) {
|
|
865
|
+
sortIcon = (
|
|
866
|
+
<span className={styles.sortIcon}>
|
|
867
|
+
{sortIndicator === SortDirection.Ascending ? icons.sortAscending : icons.sortDescending}
|
|
868
|
+
</span>);
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
return (
|
|
873
|
+
<th {...extraProps} {...classAndStyle(extraProps, undefined, style)}
|
|
874
|
+
onClick={p.column.noSort ? undefined : onClick}>
|
|
875
|
+
{widthH
|
|
876
|
+
? <ResizableColumn
|
|
877
|
+
width={widthH}
|
|
878
|
+
forDraggable={{ style: draggableStyle || { right: -4 }}}
|
|
879
|
+
onStartDrag={() => isDragging.current = true}
|
|
880
|
+
onStopDrag={() => setTimeout(() => isDragging.current = false)}>
|
|
881
|
+
{content}
|
|
882
|
+
</ResizableColumn>
|
|
883
|
+
: content}
|
|
884
|
+
{sortIcon}
|
|
885
|
+
</th>);
|
|
886
|
+
|
|
887
|
+
function onClick(e: MouseEvent) {
|
|
888
|
+
if (!isDragging.current) {
|
|
889
|
+
p.onHeadingClick(p.column.name);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
export function ResizableColumn(p: {
|
|
895
|
+
children: React.ReactNode,
|
|
896
|
+
width: Holder<number>,
|
|
897
|
+
forDraggable?: Styles,
|
|
898
|
+
onStartDrag: () => void,
|
|
899
|
+
onStopDrag: () => void
|
|
900
|
+
}) {
|
|
901
|
+
const styles = useDataTableStyles();
|
|
902
|
+
return (
|
|
903
|
+
<div style={{ width: '100%', position: 'relative', minHeight: 8 }}>
|
|
904
|
+
<Draggable
|
|
905
|
+
// The resize cursor comes from the stylesheet (--dtbl-resize-cursor)
|
|
906
|
+
{...classAndStyle(p.forDraggable, styles.draggableColumn)}
|
|
907
|
+
tabIndex={0}
|
|
908
|
+
xValue={p.width}
|
|
909
|
+
onStartDrag={p.onStartDrag}
|
|
910
|
+
onStopDrag={p.onStopDrag}
|
|
911
|
+
/>
|
|
912
|
+
{p.children}
|
|
913
|
+
</div>
|
|
914
|
+
);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
//#endregion
|
|
918
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
919
|
+
//#region Rendering of data rows
|
|
920
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
921
|
+
|
|
922
|
+
export const DefaultDataTableRow = reactive(function DefaultDataTableRow(p: DataTableRowProps<any,any,any>) {
|
|
923
|
+
const styles = useDataTableStyles();
|
|
924
|
+
const shared = useListCoreStyles();
|
|
925
|
+
const rowType = useContext(DataTableSectionContext);
|
|
926
|
+
const { tableProps, rowConfigCache } = useContext(DataTableContext);
|
|
927
|
+
|
|
928
|
+
const RenderCell = tableProps.RenderCell ?? DefaultDataTableCell;
|
|
929
|
+
const columns = tableProps.columns;
|
|
930
|
+
|
|
931
|
+
let className = styles[p.itemProps?.noPadding ? 'row' : 'rowPadded'];
|
|
932
|
+
className = cx(shared[getSelectionClass(p)], className);
|
|
933
|
+
|
|
934
|
+
let node = p.item;
|
|
935
|
+
let item = node.item;
|
|
936
|
+
let rowConfig, cellConfigs;
|
|
937
|
+
|
|
938
|
+
if (tableProps.getRowConfig != null) {
|
|
939
|
+
rowConfig = tableProps.getRowConfig(node, rowType);
|
|
940
|
+
if (rowConfig != null) {
|
|
941
|
+
if (rowConfig.item !== undefined) {
|
|
942
|
+
item = rowConfig.item;
|
|
943
|
+
node = { ...node, item };
|
|
944
|
+
}
|
|
945
|
+
cellConfigs = rowConfig.columns;
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
let cells = [];
|
|
950
|
+
for (let i = 0; i < columns.length; i++) {
|
|
951
|
+
let column = columns[i];
|
|
952
|
+
let specialized = tryGetColumnConfig(column, cellConfigs, rowConfigCache);
|
|
953
|
+
let value = getValue(node, columns[i], rowConfig, rowConfigCache, specialized);
|
|
954
|
+
|
|
955
|
+
let col = specialized ?? column;
|
|
956
|
+
let colSpan = col.getColSpan?.(node, col.cellProps);
|
|
957
|
+
if (colSpan && colSpan > 1 && Number.isFinite(colSpan)) {
|
|
958
|
+
i += (colSpan - 1) | 0;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
let RenderCell2 = col.RenderCell ?? RenderCell;
|
|
962
|
+
cells.push(
|
|
963
|
+
<RenderCell2 key={col.name?.toString() ?? i}
|
|
964
|
+
reactKey={p.reactKey}
|
|
965
|
+
selKey={p.selKey}
|
|
966
|
+
item={node}
|
|
967
|
+
value={value}
|
|
968
|
+
isSelected={p.isSelected}
|
|
969
|
+
column={col}
|
|
970
|
+
readOnly={p.readOnly}
|
|
971
|
+
expandedParents={p.expandedParents}
|
|
972
|
+
onClick={p.onClick}
|
|
973
|
+
renderTreeIndent={col.isTreeCol ? p.renderTreeIndent : undefined}
|
|
974
|
+
toggleExpanded={p.toggleExpanded}
|
|
975
|
+
isExpanded={p.isExpanded}
|
|
976
|
+
colSpan={colSpan}
|
|
977
|
+
tempState={p.tempState}
|
|
978
|
+
parentProps={tableProps}
|
|
979
|
+
/>);
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
const { ref: rowRef, ...rowProps } = (p.itemProps ?? {}) as DefaultRowProps & {
|
|
983
|
+
ref?: Ref<HTMLTableRowElement>;
|
|
984
|
+
};
|
|
985
|
+
const rowClassAndStyle = classAndStyle(p.itemProps, className);
|
|
986
|
+
return (
|
|
987
|
+
<tr ref={rowRef} {...rowProps} {...rowClassAndStyle}>
|
|
988
|
+
{cells}
|
|
989
|
+
</tr>
|
|
990
|
+
);
|
|
991
|
+
});
|
|
992
|
+
|
|
993
|
+
// export function getValue(item: any, originalNode: TreeItem<any>, originalCol: DataTableColumn<any,any,any,any>, trowCol: DataTableColumn<any,any,any,any>) {
|
|
994
|
+
// if (trowCol.getValue !== undefined) {
|
|
995
|
+
// return trowCol.getValue(item, originalNode);
|
|
996
|
+
// } else if (originalCol.getValue !== undefined) {
|
|
997
|
+
// return originalCol.getValue(originalNode.item, originalNode);
|
|
998
|
+
// } else {
|
|
999
|
+
// return (item as any)?.[trowCol.name.toString()];
|
|
1000
|
+
// }
|
|
1001
|
+
// }
|
|
1002
|
+
|
|
1003
|
+
export function DefaultDataTableCell(p: DataTableCellProps<any,any,any,any>) {
|
|
1004
|
+
const styles = useListCoreStyles();
|
|
1005
|
+
let treeIndent = p.renderTreeIndent?.();
|
|
1006
|
+
|
|
1007
|
+
let rendered = (p.column.renderCell ?? defaultRenderCell)(p.item, p);
|
|
1008
|
+
if (p.readOnly) {
|
|
1009
|
+
rendered =
|
|
1010
|
+
<div style={{ position: 'relative' }}>
|
|
1011
|
+
{rendered}
|
|
1012
|
+
<div className={styles.readOnlyWrapper}/>
|
|
1013
|
+
</div>;
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
let cellProps = p.column.cellProps;
|
|
1017
|
+
cellProps = cellProps instanceof Function ? cellProps(p.item) : cellProps;
|
|
1018
|
+
return (
|
|
1019
|
+
<td {...cellProps}
|
|
1020
|
+
colSpan={p.colSpan}
|
|
1021
|
+
onClick={e => {
|
|
1022
|
+
p.onClick(p.item, e);
|
|
1023
|
+
cellProps?.onClick?.(e);
|
|
1024
|
+
}}>
|
|
1025
|
+
{!treeIndent ? rendered :
|
|
1026
|
+
<div style={{ display: 'flex', alignItems: 'center' }}>
|
|
1027
|
+
{treeIndent}
|
|
1028
|
+
<div style={{ flex: 1 }}>{rendered}</div>
|
|
1029
|
+
</div>}
|
|
1030
|
+
</td>);
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
export function defaultRenderCell(node: TreeItem<any>, props: DataTableCellProps<any,any,any>): React.ReactNode {
|
|
1034
|
+
const value = props.value;
|
|
1035
|
+
if (value === true)
|
|
1036
|
+
return '✅';
|
|
1037
|
+
if (value === false)
|
|
1038
|
+
return '❌';
|
|
1039
|
+
else
|
|
1040
|
+
return value;
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
//#endregion
|
|
1044
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
1045
|
+
|
|
1046
|
+
/** The class names used to render tables (defined in datatable.css). These are stable, but
|
|
1047
|
+
* exposed as an object so that code written against the earlier makeStyles-based API keeps
|
|
1048
|
+
* working. Colors and spacing come from CSS variables; see `TableTheme`. */
|
|
1049
|
+
export const dataTableClasses: Record<'outerDiv'|'table'|'rowPadded'|'row'|'sortIcon'|'draggableColumn', string> = {
|
|
1050
|
+
outerDiv: 'dtbl-outer',
|
|
1051
|
+
table: 'dtbl-table',
|
|
1052
|
+
rowPadded: 'dtbl-row-padded',
|
|
1053
|
+
row: 'dtbl-row',
|
|
1054
|
+
sortIcon: 'dtbl-sort-icon',
|
|
1055
|
+
draggableColumn: 'dtbl-resize-handle',
|
|
1056
|
+
};
|
|
1057
|
+
|
|
1058
|
+
export function useDataTableStyles() {
|
|
1059
|
+
return dataTableClasses;
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
|
|
1063
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
1064
|
+
//#region Helper Functions
|
|
1065
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|
|
1066
|
+
|
|
1067
|
+
type SortableNode<T, ColName, ItemProps> = TreeItem<T> & { rowConfig?: nully | ItemAndColumns<T, any, ColName, ItemProps>, [n: number]: any; };
|
|
1068
|
+
|
|
1069
|
+
/** Obtains a function to sort a list of items in a `DataTable`. DataTable provides flexible
|
|
1070
|
+
* control over sorting, and the sort process is a bit complicated in order to provide
|
|
1071
|
+
* flexibility without losing efficiency; review its code for details.
|
|
1072
|
+
*
|
|
1073
|
+
* @param colsToSortBy The columns to sort by, where colsToSortBy[0] is the primary sort column
|
|
1074
|
+
* and sort direction.
|
|
1075
|
+
* @param tableContext The table's context object (corresponding to a React `DataTableContext`).
|
|
1076
|
+
*/
|
|
1077
|
+
function getSorter<T, K=T, ColName extends { toString(): string } = string, ItemProps extends Styles=Styles>(
|
|
1078
|
+
colsToSortBy: Array<[ColName, SortDirection]>,
|
|
1079
|
+
tableContext: DataTableContext<T, K, ColName, ItemProps>
|
|
1080
|
+
): undefined | ((list: TreeItemM<T>[]) => void) {
|
|
1081
|
+
const { tableProps, rowConfigCache } = tableContext;
|
|
1082
|
+
|
|
1083
|
+
// `colsToSortBy` holds column names, but we need column objects.
|
|
1084
|
+
var sortBy = colsToSortBy.map(([colName, direction]) => {
|
|
1085
|
+
return { column: tableProps.columns.find((col) => col.name === colName)!, direction };
|
|
1086
|
+
}).filter(x => x.column);
|
|
1087
|
+
|
|
1088
|
+
if (sortBy.length <= 0)
|
|
1089
|
+
return tableProps.sort;
|
|
1090
|
+
|
|
1091
|
+
// For efficiency, rows are not compared directly to each other. Instead, the general
|
|
1092
|
+
// sort operation is broken into three steps: preparation, projection, and sort.
|
|
1093
|
+
//
|
|
1094
|
+
// 1. The preparation step prepares the final comparer function that compares `SortableNode`s.
|
|
1095
|
+
// This can and should be done in advance: the table may be showing a tree with many
|
|
1096
|
+
// sublists that will be sorted separately, and the same comparer can be used for them all.
|
|
1097
|
+
// 2. The projection step creates a `SortableNode<T,...>` from each `TreeItem<T>`.
|
|
1098
|
+
// 3. The sort step uses the comparer function to sort the `SortableNode`s.
|
|
1099
|
+
//
|
|
1100
|
+
// This is faster than the simpler approach of doing projection inside the comparer function,
|
|
1101
|
+
// especially if `getRowConfig` needs to be called during projection, because projection
|
|
1102
|
+
// needs O(N) steps while sorting needs O(N log N) steps.
|
|
1103
|
+
//
|
|
1104
|
+
// For example, suppose we are sorting by two string columns, "country" and "city". The
|
|
1105
|
+
// preparation step creates a comparer function that compares objects `a` and `b` by comparing
|
|
1106
|
+
// `a[0]` to `b[0]` and then, if those are equal, comparing `a[1]` to `b[1]`. The projection
|
|
1107
|
+
// step maps `list` to a second list of equal length that contains the original nodes as
|
|
1108
|
+
// prototypes, plus additional properties [0] and [1], and also `rowConfig` if necessary.
|
|
1109
|
+
// Finally, the sort step sorts the second list using the comparer function.
|
|
1110
|
+
|
|
1111
|
+
// Preparation: compute the `comparer` and decide whether we'll need to call `getRowConfig`.
|
|
1112
|
+
type Comparer = (a: SortableNode<T, ColName, ItemProps>, b: SortableNode<T, ColName, ItemProps>) => number;
|
|
1113
|
+
const comparers: Comparer[] = [];
|
|
1114
|
+
let getRowConfig: DataTableCoreProps<T, K, ColName, ItemProps>['getRowConfig'] | undefined;
|
|
1115
|
+
for (let iCol = 0; iCol < sortBy.length; iCol++) {
|
|
1116
|
+
const { column, direction } = sortBy[iCol];
|
|
1117
|
+
|
|
1118
|
+
// Prefer to use the `getNodeComparer` function, in the rare case it is provided.
|
|
1119
|
+
const nodeComparer = column.getNodeComparer?.(direction === SortDirection.Descending);
|
|
1120
|
+
if (nodeComparer) {
|
|
1121
|
+
comparers[iCol] = nodeComparer;
|
|
1122
|
+
} else {
|
|
1123
|
+
if (!column.getSortableValue)
|
|
1124
|
+
getRowConfig = tableProps.getRowConfig;
|
|
1125
|
+
|
|
1126
|
+
if (column.compare) {
|
|
1127
|
+
let comparer = column.compare;
|
|
1128
|
+
if (direction === SortDirection.Ascending) {
|
|
1129
|
+
comparers[iCol] = (a, b) => comparer(a[iCol], b[iCol]);
|
|
1130
|
+
} else {
|
|
1131
|
+
comparers[iCol] = (a, b) => comparer(b[iCol], a[iCol]);
|
|
1132
|
+
}
|
|
1133
|
+
} else {
|
|
1134
|
+
if (direction === SortDirection.Ascending) {
|
|
1135
|
+
// `let` actually has very strange behavior, at least within for loops!
|
|
1136
|
+
// Even though it seems like there is only one `iCol` variable, there
|
|
1137
|
+
// is actually a separate `iCol` for each iteration of the `for` loop
|
|
1138
|
+
// (because `let` was used rather than `var`). Therefore, `iCol` has the
|
|
1139
|
+
// "correct" value here.
|
|
1140
|
+
comparers[iCol] = (a, b) => {
|
|
1141
|
+
if (a[iCol] > b[iCol]) return 1;
|
|
1142
|
+
if (a[iCol] < b[iCol]) return -1;
|
|
1143
|
+
return 0;
|
|
1144
|
+
};
|
|
1145
|
+
} else {
|
|
1146
|
+
comparers[iCol] = (a, b) => {
|
|
1147
|
+
if (a[iCol] > b[iCol]) return -1;
|
|
1148
|
+
if (a[iCol] < b[iCol]) return 1;
|
|
1149
|
+
return 0;
|
|
1150
|
+
};
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
let comparer = combineComparers<SortableNode<T, ColName, ItemProps>>(comparers.shift()!, ...comparers);
|
|
1157
|
+
|
|
1158
|
+
return function sort(list: TreeItemM<T>[]) {
|
|
1159
|
+
// Projection: convert `list` to `listEx` by adding properties `rowConfig`, [0], [1], etc.
|
|
1160
|
+
const listEx = list.map(node => newObjectWithPrototype(node) as SortableNode<T, ColName, ItemProps>);
|
|
1161
|
+
|
|
1162
|
+
if (getRowConfig) {
|
|
1163
|
+
for (let iRow = 0; iRow < list.length; iRow++) {
|
|
1164
|
+
listEx[iRow].rowConfig = getRowConfig(list[iRow], RowType.Normal);
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
for (let iCol = 0; iCol < sortBy.length; iCol++) {
|
|
1169
|
+
const { column } = sortBy[iCol];
|
|
1170
|
+
|
|
1171
|
+
// In the simple case, `getSortableValue` is provided. Otherwise, use one of the two
|
|
1172
|
+
// `getValue` or `name` props (`rowConfig` may specify an override for these).
|
|
1173
|
+
if (column.getSortableValue != null) {
|
|
1174
|
+
for (let iRow = 0; iRow < listEx.length; iRow++) {
|
|
1175
|
+
listEx[iRow][iCol] = column.getSortableValue(listEx[iRow]);
|
|
1176
|
+
}
|
|
1177
|
+
} else {
|
|
1178
|
+
for (let iRow = 0; iRow < listEx.length; iRow++) {
|
|
1179
|
+
const node = listEx[iRow];
|
|
1180
|
+
|
|
1181
|
+
node[iCol] = getValue(node, column, node.rowConfig, rowConfigCache);
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
// Sort
|
|
1187
|
+
listEx.sort(comparer);
|
|
1188
|
+
for (let i = 0; i < list.length; i++) {
|
|
1189
|
+
list[i] = Object.getPrototypeOf(listEx[i]);
|
|
1190
|
+
}
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
/** Gets the `value` of a cell, which may become the value of `DataTableCellProps<...>.value`,
|
|
1195
|
+
* or may be used for sorting if the column doesn't have a `getSortableValue` function.
|
|
1196
|
+
*
|
|
1197
|
+
* The value is obtained from one of the following sources (highest priority listed first):
|
|
1198
|
+
*
|
|
1199
|
+
* 1. The `specialized.getValue(TRow)` function, if a `specialized` configuration object was
|
|
1200
|
+
* obtained from the user's `getRowConfig(...).columns` collection and it defines `getValue`.
|
|
1201
|
+
* 2. `node.item[specialized.name.toString()]`, if `specialized?.name` is not `undefined`.
|
|
1202
|
+
* 3. `column.getValue(node.item)`, if `getValue` is not `undefined`.
|
|
1203
|
+
* 4. `node.item[column.name.toString()]`, if `column.name` is not `undefined`.
|
|
1204
|
+
*/
|
|
1205
|
+
function getValue<T,ColName,ItemProps>(
|
|
1206
|
+
node: TreeItem<T>,
|
|
1207
|
+
column: DataTableColumn<T, T, any, any>,
|
|
1208
|
+
rowConfig: nully | ItemAndColumns<T, any, ColName, ItemProps>,
|
|
1209
|
+
rowConfigCache: Map<DataTableCellConfig<T, any, ColName, ItemProps>, DataTableColumn<T, any, ColName, ItemProps>>,
|
|
1210
|
+
specialized?: DataTableColumn<T, any, ColName, ItemProps>
|
|
1211
|
+
) {
|
|
1212
|
+
// The *original* `column.getValue` expects type T (the "original" row value), while the
|
|
1213
|
+
// `getValue` buried in `rowConfig` expects type TRow, so distinguish which one applies.
|
|
1214
|
+
if (rowConfig != null) {
|
|
1215
|
+
specialized ??= tryGetColumnConfig(column, rowConfig.columns, rowConfigCache);
|
|
1216
|
+
if (specialized !== undefined) {
|
|
1217
|
+
if (specialized.getValue !== undefined) {
|
|
1218
|
+
return specialized.getValue(rowConfig.item !== undefined ? rowConfig.item : node.item, node);
|
|
1219
|
+
} else if (specialized.name !== undefined) {
|
|
1220
|
+
return (node.item as any)?.[specialized.name!.toString()];
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
if (column.getValue !== undefined) {
|
|
1226
|
+
return column.getValue(node.item, node);
|
|
1227
|
+
} else if (column.name !== undefined) {
|
|
1228
|
+
return (node.item as any)?.[column.name.toString()];
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
/** Obtains the "combined" column configuration for a combination of column and row type, which
|
|
1233
|
+
* is derived from both the column configuration (`columns[i]` prop of `DataTableCore` for some
|
|
1234
|
+
* index `i`) and the row type configuration (obtained from by calling the `getRowConfig` prop
|
|
1235
|
+
* of `DataTableCore`).
|
|
1236
|
+
*
|
|
1237
|
+
* @param column column info from the `columns[i]` prop of `DataTableCore`.
|
|
1238
|
+
* @param cellConfigs the `Map` returned from the `getRowConfig(...).columns` provided by the user.
|
|
1239
|
+
* @param rowConfigCache the cache in `useContext(DataTableContext).rowConfigCache`, which
|
|
1240
|
+
* stores a merged column configurations indexed by objects returned by `rowConfigCache`.
|
|
1241
|
+
* Thanks to the cache, a merge operation is not necessary for every cell, provided that
|
|
1242
|
+
* the `getRowConfig` prop does not return unique objects on every call.
|
|
1243
|
+
*/
|
|
1244
|
+
function tryGetColumnConfig(
|
|
1245
|
+
column: DataTableColumn<any, any, any, any>,
|
|
1246
|
+
cellConfigs: IMapSource<any, DataTableCellConfig<any, any, any, any>> | undefined,
|
|
1247
|
+
rowConfigCache: Map<DataTableCellConfig<any, any, any, any>, DataTableColumn<any, any, any, any>>
|
|
1248
|
+
): DataTableColumn<any, any, any, any> | undefined {
|
|
1249
|
+
let cellConfig;
|
|
1250
|
+
|
|
1251
|
+
// If there is a custom configuration for this type of row, set `column` to be the
|
|
1252
|
+
// merger of the original column config in `columns[i]` and the specialized config
|
|
1253
|
+
// in `cellConfigs.get(col.name)`. In case the same row type appears many times,
|
|
1254
|
+
// we use `rowConfigCache` to avoid repeating the merge operation for every cell.
|
|
1255
|
+
if (cellConfigs != null && (cellConfig = cellConfigs.get(column.name)) != null) {
|
|
1256
|
+
let cachedCol = rowConfigCache.get(cellConfig);
|
|
1257
|
+
if (cachedCol !== undefined) {
|
|
1258
|
+
return cachedCol;
|
|
1259
|
+
|
|
1260
|
+
} else {
|
|
1261
|
+
column = { ...column, ...cellConfig, getValue: cellConfig.getValue };
|
|
1262
|
+
rowConfigCache.set(cellConfig, column);
|
|
1263
|
+
return column;
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
/** Returns a function that sorts with two or more comparison functions for the same type T.
|
|
1269
|
+
* For example, if T is `{ x: number, y: string }` and you have two comparers `cmpX` and `cmpY`
|
|
1270
|
+
* that projects and compares the two fields, then `combineComparers(cmpX, cmpY)` returns a
|
|
1271
|
+
* function that compares by field X, and when those are equal (so `cmpX` returns 0), compares
|
|
1272
|
+
* by field Y. */
|
|
1273
|
+
export function combineComparers<T>(comparator: (a: T, b: T) => number, ...comparators: Array<(a: T, b: T) => number>) {
|
|
1274
|
+
if (!comparators?.length)
|
|
1275
|
+
return comparator;
|
|
1276
|
+
|
|
1277
|
+
return function combinedComparisons(a: T, b: T): number {
|
|
1278
|
+
let result = comparator(a, b);
|
|
1279
|
+
if (result === 0)
|
|
1280
|
+
for (let comparator of comparators) {
|
|
1281
|
+
result = comparator(a, b);
|
|
1282
|
+
if (result !== 0)
|
|
1283
|
+
break;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
return result;
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
export function compareByLocale<T>(a: nully | { toString(): string }, b: nully | { toString(): string }): number {
|
|
1291
|
+
let strA = a?.toString();
|
|
1292
|
+
let strB = b?.toString();
|
|
1293
|
+
|
|
1294
|
+
if (strA == null) {
|
|
1295
|
+
if (strB == null) return 0;
|
|
1296
|
+
return -1;
|
|
1297
|
+
} else if (strB == null) {
|
|
1298
|
+
return 1;
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
return strA.localeCompare(strB);
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
/** Compares any pair of numbers, strings, booleans, Dates, or (to the extent supported by the
|
|
1305
|
+
* `>` and `<` operators) arrays. String comparisons are case-sensitive. */
|
|
1306
|
+
export function heterogeneousCompare(a: any, b: any) {
|
|
1307
|
+
if (typeof a !== typeof b || a == null || b == null) {
|
|
1308
|
+
return getTypeOrder(a) - getTypeOrder(b);
|
|
1309
|
+
} else {
|
|
1310
|
+
return a > b ? 1 : a < b ? -1 : 0;
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
// An arbitrary order between different custom field types to enable cross-type sorting
|
|
1315
|
+
function getTypeOrder(x: any) {
|
|
1316
|
+
if (x == null) {
|
|
1317
|
+
return 0;
|
|
1318
|
+
} else if (typeof x === 'number') {
|
|
1319
|
+
return 1;
|
|
1320
|
+
} else if (typeof x === 'string') {
|
|
1321
|
+
return 2;
|
|
1322
|
+
} else if (typeof x === 'boolean') {
|
|
1323
|
+
return 3;
|
|
1324
|
+
} else if (x instanceof Date) {
|
|
1325
|
+
return 4;
|
|
1326
|
+
} else {
|
|
1327
|
+
return 5;
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
//#endregion
|
|
1332
|
+
/////////////////////////////////////////////////////////////////////////////////////////
|