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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +251 -2
  3. package/dist/DataTable.d.ts +583 -0
  4. package/dist/DataTable.js +620 -0
  5. package/dist/Draggable.d.ts +35 -0
  6. package/dist/Draggable.js +91 -0
  7. package/dist/ListBox.d.ts +132 -0
  8. package/dist/ListBox.js +243 -0
  9. package/dist/ListVirtualizer.d.ts +59 -0
  10. package/dist/ListVirtualizer.js +180 -0
  11. package/dist/TreeList.d.ts +196 -0
  12. package/dist/TreeList.js +300 -0
  13. package/dist/config.d.ts +55 -0
  14. package/dist/config.js +33 -0
  15. package/dist/datatable.css +161 -0
  16. package/dist/hooks.d.ts +27 -0
  17. package/dist/hooks.js +115 -0
  18. package/dist/index.d.ts +12 -0
  19. package/dist/index.js +15 -0
  20. package/dist/interfaces.d.ts +269 -0
  21. package/dist/interfaces.js +3 -0
  22. package/dist/mobx-adapter.d.ts +12 -0
  23. package/dist/mobx-adapter.js +21 -0
  24. package/dist/reactivity.d.ts +112 -0
  25. package/dist/reactivity.js +155 -0
  26. package/dist/styles.d.ts +64 -0
  27. package/dist/styles.js +86 -0
  28. package/dist/theme.d.ts +160 -0
  29. package/dist/theme.js +239 -0
  30. package/dist/util.d.ts +28 -0
  31. package/dist/util.js +45 -0
  32. package/package.json +143 -4
  33. package/src/DataTable.tsx +1332 -0
  34. package/src/Draggable.tsx +133 -0
  35. package/src/ListBox.tsx +423 -0
  36. package/src/ListVirtualizer.ts +234 -0
  37. package/src/TreeList.tsx +590 -0
  38. package/src/config.tsx +96 -0
  39. package/src/css.d.ts +1 -0
  40. package/src/datatable.css +161 -0
  41. package/src/hooks.ts +138 -0
  42. package/src/index.ts +15 -0
  43. package/src/interfaces.ts +309 -0
  44. package/src/mobx-adapter.ts +24 -0
  45. package/src/reactivity.ts +222 -0
  46. package/src/styles.tsx +102 -0
  47. package/src/theme.ts +346 -0
  48. package/src/util.ts +60 -0
@@ -0,0 +1,620 @@
1
+ var __rest = (this && this.__rest) || function (s, e) {
2
+ var t = {};
3
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
+ t[p] = s[p];
5
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
+ t[p[i]] = s[p[i]];
9
+ }
10
+ return t;
11
+ };
12
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
13
+ import { createContext, useContext, useRef, useState } from 'react';
14
+ import { useTableConfig } from './config.js';
15
+ import { Draggable } from './Draggable.js';
16
+ import { coalesce, useForceUpdate } from './hooks.js';
17
+ import { useListCoreStyles } from './ListBox.js';
18
+ import { getReactivityAdapter, reactive, useComputed, useWatched } from './reactivity.js';
19
+ import { classAndStyle } from './styles.js';
20
+ import { useThemeProps } from './theme.js';
21
+ import { getSelectionClass, TreeListCore } from './TreeList.js';
22
+ import { cx, newObjectWithPrototype } from './util.js';
23
+ /** Sort order of the column, used in `DataTableCoreProps.columnsToSortBy` */
24
+ export var SortDirection;
25
+ (function (SortDirection) {
26
+ SortDirection[SortDirection["Ascending"] = 1] = "Ascending";
27
+ SortDirection[SortDirection["Descending"] = -1] = "Descending";
28
+ })(SortDirection || (SortDirection = {}));
29
+ /** Tells `DataTableCoreProps.getRowConfig` what section of the row is being rendered. */
30
+ export var RowType;
31
+ (function (RowType) {
32
+ RowType[RowType["Header"] = -1] = "Header";
33
+ RowType[RowType["Normal"] = 0] = "Normal";
34
+ RowType[RowType["Footer"] = 1] = "Footer";
35
+ })(RowType || (RowType = {}));
36
+ /** A table of data with columns and rows rendered based on user-specified objects. This
37
+ * is the core functionality of a `<DataTable>`, without the actual `<table>` element.
38
+ * It can be used the same way as `<DataTable>` except that you wrap it in a `<table>`.
39
+ * See `<DataTable>` for a usage example. By not including `<table>`, this component
40
+ * gives you additional ways to format the table, e.g. you can use `<caption>`, `<tfoot>`
41
+ * or an extra header row. Also, it is possible to construct a non-table grid (e.g. CSS
42
+ * grid) using this component and custom renderers. */
43
+ export const DataTableCore = reactive(function DataTableCore(p) {
44
+ var _a, _b, _c;
45
+ const RenderDataRow = ((_a = p.RenderDataRow) !== null && _a !== void 0 ? _a : DefaultDataTableRow);
46
+ const RenderHeadingRow = ((_b = p.RenderHeadingRow) !== null && _b !== void 0 ? _b : DefaultDataTableHeadingRow);
47
+ const forceUpdate = useForceUpdate();
48
+ const [columnState] = useState(() => new Map());
49
+ const colsToSortBy = useWatched(coalesce(p.columnsToSortBy, useState(() => getReactivityAdapter().observableArray())[0]));
50
+ // We want to wrap the table in the same context object if props used in child components
51
+ // haven't changed, so that all rows don't have to re-render. But if those props have changed,
52
+ // create a new context object to cause a re-render.
53
+ const tableContextInit = { rowConfigCache: new Map(), tableProps: p };
54
+ const tableContextRef = useRef(tableContextInit);
55
+ tableContextRef.current.rowConfigCache.clear();
56
+ const prevProps = tableContextRef.current.tableProps;
57
+ if (prevProps.columns !== p.columns
58
+ || prevProps.getRowConfig !== p.getRowConfig
59
+ || prevProps.RenderHeading !== p.RenderHeading
60
+ || prevProps.RenderCell !== p.RenderCell
61
+ || prevProps.indentPerLevel !== p.indentPerLevel) {
62
+ tableContextRef.current = tableContextInit;
63
+ }
64
+ tableContextRef.current.tableProps = p;
65
+ const sort = useComputed(() => getSorter(colsToSortBy, tableContextRef.current), [colsToSortBy, p.sortComparer, p.columns]).get();
66
+ // Update column state based on the column information provided
67
+ for (let column of p.columns) {
68
+ let state = columnState.get(column.name);
69
+ if (state == null) {
70
+ columnState.set(column.name, { column, width: column.width });
71
+ }
72
+ else {
73
+ state.column = column;
74
+ if (typeof column.width === 'object') {
75
+ state.width = column.width;
76
+ }
77
+ }
78
+ }
79
+ let headings = p.noHeader ? undefined :
80
+ _jsx(RenderHeadingRow, { headingRowProps: p.headingRowProps, getColumnWidth: name => {
81
+ const state = columnState.get(name);
82
+ if (state) {
83
+ return typeof state.width === 'object' ? state.width.get() : state.width;
84
+ }
85
+ }, setColumnWidth: (name, width) => {
86
+ let state = columnState.get(name);
87
+ if (state) {
88
+ if (typeof state.width === 'object') {
89
+ state.width.set(width);
90
+ }
91
+ else {
92
+ state.width = width;
93
+ }
94
+ }
95
+ }, getColumnSortIndicator: (name) => {
96
+ if (colsToSortBy.length && colsToSortBy[0][0] === name)
97
+ return colsToSortBy[0][1];
98
+ }, onHeadingClick: (name) => {
99
+ getReactivityAdapter().runInAction(() => {
100
+ let columnIndex = findSortTupleIndexByName(name);
101
+ if (columnIndex === 0) {
102
+ let column = colsToSortBy[columnIndex];
103
+ if (column[1] === SortDirection.Ascending)
104
+ column[1] = SortDirection.Descending;
105
+ else if (!p.sortComparer && !p.sort)
106
+ column[1] = SortDirection.Ascending;
107
+ else
108
+ colsToSortBy.clear(); // restore default sort order
109
+ }
110
+ else {
111
+ if (columnIndex > 0) {
112
+ colsToSortBy.splice(columnIndex, 1);
113
+ }
114
+ colsToSortBy.unshift([name, SortDirection.Ascending]);
115
+ colsToSortBy.splice(4); // for efficiency, don't sort by too many columns
116
+ }
117
+ });
118
+ // With the default (non-MobX) adapter, flipping the sort direction mutates a
119
+ // tuple element in place, which even a WatchableArray can't detect. (With the
120
+ // MobX adapter this render is scheduled anyway, and React merges the two.)
121
+ forceUpdate();
122
+ } });
123
+ if (p.headerRows != null) {
124
+ headings = _jsxs(_Fragment, { children: [headings, _jsx(DataTableSection, Object.assign({}, p, { rowType: RowType.Header, list: p.headerRows, tree: undefined, RenderItem: RenderDataRow }))] });
125
+ }
126
+ let rows = _jsx(TreeListCore, Object.assign({}, p, { sort: sort, RenderItem: RenderDataRow, virtualGapRenderer: (_c = p.virtualGapRenderer) !== null && _c !== void 0 ? _c : renderVirtualGap }));
127
+ let footer;
128
+ if (p.footerRows != null) {
129
+ footer = _jsx(DataTableSection, Object.assign({}, p, { rowType: RowType.Footer, list: p.footerRows, tree: undefined, RenderItem: RenderDataRow }));
130
+ }
131
+ return (_jsxs(DataTableContext.Provider, { value: tableContextRef.current, children: [p.noStructureWrap
132
+ ? headings
133
+ : _jsx("thead", Object.assign({}, p.theadProps, { children: headings })), p.noStructureWrap
134
+ ? rows
135
+ : _jsx("tbody", Object.assign({}, p.tbodyProps, { children: rows })), p.noStructureWrap || p.footerRows == null
136
+ ? footer
137
+ : _jsx("tfoot", Object.assign({}, p.tfootProps, { children: footer }))] }));
138
+ function findSortTupleIndexByName(colName) {
139
+ return colsToSortBy.findIndex((([name]) => name === colName));
140
+ }
141
+ });
142
+ function renderVirtualGap(height, ref) {
143
+ return _jsx("tr", { ref: ref, style: { height } });
144
+ }
145
+ function DataTableSection(p) {
146
+ return (_jsx(DataTableSectionContext.Provider, { value: p.rowType, children: _jsx(TreeListCore, Object.assign({}, p, { sortComparer: undefined, filter: undefined, virtualize: undefined, virtualGapRenderer: undefined })) }));
147
+ }
148
+ /** This context can be used in a custom component used inside DataTable (e.g.
149
+ * a custom `RenderCell` component) to get the props that were passed to the
150
+ * data table. */
151
+ export const DataTableContext = createContext({
152
+ rowConfigCache: new Map(),
153
+ tableProps: { list: [], columns: [] },
154
+ });
155
+ export const DataTableSectionContext = createContext(RowType.Normal);
156
+ /** A table of data with columns and rows rendered based on user-specified objects.
157
+ * Also supports tree grids via the `getChildren` or `getParents` prop.
158
+ *
159
+ * By default, DataTable is rendered as a `<table>` element (with style `width: 100%`)
160
+ * wrapped in a `<div>` whose class includes `overflow: auto` so that a scroll bar
161
+ * appears automatically when appropriate. Other than that, the table size is not
162
+ * constrained and will automatically choose its own size. One simple way to limit
163
+ * min/max table size is to add `style={{ minHeight: N, maxHeight: M }}`. If the table
164
+ * is within a container that has its own min/max height, it might be better to set
165
+ * `display: flex; flex-direction: column` on that container and also set
166
+ * `style={{ flex: 1 }}` on the DataTable. This way, the table fills available space
167
+ * while also allowing space for other widgets.
168
+ *
169
+ * The table class includes `table-layout: fixed` and each `<th>` has an inline width
170
+ * controlled by the `DataTableColumn.width` value if you provided one. This is a
171
+ * minimum width; if the table is wider than the total widths of all columns, your
172
+ * browser will distribute excess available space among the columns automatically. If
173
+ * the table is less wide than the total widths of all columns, a horizontal scroll bar
174
+ * will appear. Drag handles appear by default so the user can change column widths (but
175
+ * the user's custom widths are forgotten when the component is unmounted.)
176
+ *
177
+ * Here's an example that shows a bunch of columns based on some simple `{ n: number }`
178
+ * objects, and shows certain items in tree form. In this example, `getParents`
179
+ * regenerates a parent object every time it is called, and the result is that the user
180
+ * can't expand parent rows unless a `getSelKey` prop is provided. This is because when
181
+ * the user expands a parent, the table is re-rendered and the originally-expanded
182
+ * parent object is no longer in the table! `getSelKey` fixes the problem causing the sets
183
+ * of selected and expanded items to be sets of numbers rather than objects. However,
184
+ * TypeScript can't infer that the type returned by `getSelKey` is correct, so type
185
+ * parameters are needed on `DataTable<{n: number}, number>`.
186
+ *
187
+ * <DataTable<{n: number}, number>
188
+ * list={[ { n:1 }, { n:3 }, { n:5 }, { n:36 }, { n:100 } ]}
189
+ * selMode="multi"
190
+ * columns={[
191
+ * {
192
+ * name: 'n',
193
+ * heading: 'Number',
194
+ * isTreeCol: true,
195
+ * },
196
+ * {
197
+ * name: 'Square', // Shown as the heading because `heading` is missing
198
+ * getValue(item: {n: number}) { return item.n * item.n; }
199
+ * },
200
+ * {
201
+ * name: 'Square root',
202
+ * getValue(item: {n: number}) { return Math.sqrt(item.n); }
203
+ * },
204
+ * {
205
+ * name: 'Odd?',
206
+ * getValue(item: {n: number}) { return (item.n & 1) !== 0; }
207
+ * },
208
+ * ]}
209
+ * getParents={item => {
210
+ * let root = Math.sqrt(item.n);
211
+ * return root === Math.round(root) ? [ { n: root } ] : undefined;
212
+ * }}
213
+ * getSelKey={item => item.n}
214
+ * />
215
+ */
216
+ export function DataTable(p) {
217
+ const styles = useDataTableStyles();
218
+ const theme = useThemeProps(p.theme);
219
+ const containerRef = useRef(null);
220
+ let { virtualize } = p;
221
+ if (virtualize && virtualize.containerRef == null)
222
+ virtualize.containerRef = containerRef;
223
+ return (_jsx("div", Object.assign({ ref: containerRef, tabIndex: 0 }, p.outerProps, classAndStyle(p, cx(styles.outerDiv, theme.className), theme.style), { children: _jsx("table", Object.assign({}, p.tableProps, classAndStyle(p.tableProps, styles.table), { children: _jsx(DataTableCore, Object.assign({}, p)) })) })));
224
+ }
225
+ //#endregion
226
+ /////////////////////////////////////////////////////////////////////////////////////////
227
+ //#region Rendering of header row
228
+ /////////////////////////////////////////////////////////////////////////////////////////
229
+ export function DefaultDataTableHeadingRow(p) {
230
+ var _a, _b;
231
+ const { tableProps } = useContext(DataTableContext);
232
+ const RenderHeading = (_a = tableProps.RenderHeading) !== null && _a !== void 0 ? _a : DefaultDataTableHeading;
233
+ const styles = useDataTableStyles();
234
+ let className = styles[((_b = p.headingRowProps) === null || _b === void 0 ? void 0 : _b.noPadding) ? 'row' : 'rowPadded'];
235
+ return (_jsx("tr", Object.assign({}, p.headingRowProps, classAndStyle(p.headingRowProps, className), { children: tableProps.columns.map((col, i) => {
236
+ var _a, _b;
237
+ let RenderHeading2 = (_a = col.RenderHeading) !== null && _a !== void 0 ? _a : RenderHeading;
238
+ return _jsx(RenderHeading2, Object.assign({}, p, { column: col }), (_b = col.name) === null || _b === void 0 ? void 0 : _b.toString());
239
+ }) })));
240
+ }
241
+ export let defaultClampWidth = {
242
+ current(w, c) {
243
+ var _a;
244
+ let baseWidth = typeof c.width === 'number' ? c.width : (_a = c.width) === null || _a === void 0 ? void 0 : _a.get();
245
+ return Math.max(Math.min(30, baseWidth !== null && baseWidth !== void 0 ? baseWidth : 30), w);
246
+ }
247
+ };
248
+ export function DefaultDataTableHeading(p) {
249
+ const styles = useDataTableStyles();
250
+ const { icons } = useTableConfig();
251
+ const refresh = useForceUpdate();
252
+ const width = p.getColumnWidth(p.column.name);
253
+ const extraProps = p.column.headingProps;
254
+ const content = p.column.heading !== undefined ? p.column.heading : p.column.name;
255
+ // If the user drags the column resizer, a click event still occurs. This is used
256
+ // to prevent that event from doing anything.
257
+ const isDragging = useRef(false);
258
+ let widthH, style, draggableStyle;
259
+ if (width != null) {
260
+ style = { width };
261
+ if (!p.column.noResize) {
262
+ widthH = {
263
+ get() { return width; },
264
+ set(w) {
265
+ var _a;
266
+ w = ((_a = p.column.clampWidth) !== null && _a !== void 0 ? _a : defaultClampWidth.current)(w, p.column);
267
+ if (p.column.maxWidth != null && w > p.column.maxWidth) {
268
+ w = p.column.maxWidth;
269
+ }
270
+ if (w >= 0 && !Number.isNaN(w)) {
271
+ p.setColumnWidth(p.column.name, w);
272
+ refresh();
273
+ }
274
+ }
275
+ };
276
+ }
277
+ }
278
+ let sortIcon;
279
+ if (!p.column.noSort) {
280
+ const sortIndicator = p.getColumnSortIndicator(p.column.name);
281
+ style = Object.assign(Object.assign({}, style), { paddingRight: 16, cursor: 'pointer' });
282
+ draggableStyle = { right: -10 };
283
+ if (sortIndicator != null) {
284
+ sortIcon = (_jsx("span", { className: styles.sortIcon, children: sortIndicator === SortDirection.Ascending ? icons.sortAscending : icons.sortDescending }));
285
+ }
286
+ }
287
+ return (_jsxs("th", Object.assign({}, extraProps, classAndStyle(extraProps, undefined, style), { onClick: p.column.noSort ? undefined : onClick, children: [widthH
288
+ ? _jsx(ResizableColumn, { width: widthH, forDraggable: { style: draggableStyle || { right: -4 } }, onStartDrag: () => isDragging.current = true, onStopDrag: () => setTimeout(() => isDragging.current = false), children: content })
289
+ : content, sortIcon] })));
290
+ function onClick(e) {
291
+ if (!isDragging.current) {
292
+ p.onHeadingClick(p.column.name);
293
+ }
294
+ }
295
+ }
296
+ export function ResizableColumn(p) {
297
+ const styles = useDataTableStyles();
298
+ return (_jsxs("div", { style: { width: '100%', position: 'relative', minHeight: 8 }, children: [_jsx(Draggable
299
+ // The resize cursor comes from the stylesheet (--dtbl-resize-cursor)
300
+ , Object.assign({}, classAndStyle(p.forDraggable, styles.draggableColumn), { tabIndex: 0, xValue: p.width, onStartDrag: p.onStartDrag, onStopDrag: p.onStopDrag })), p.children] }));
301
+ }
302
+ //#endregion
303
+ /////////////////////////////////////////////////////////////////////////////////////////
304
+ //#region Rendering of data rows
305
+ /////////////////////////////////////////////////////////////////////////////////////////
306
+ export const DefaultDataTableRow = reactive(function DefaultDataTableRow(p) {
307
+ var _a, _b, _c, _d, _e, _f, _g;
308
+ const styles = useDataTableStyles();
309
+ const shared = useListCoreStyles();
310
+ const rowType = useContext(DataTableSectionContext);
311
+ const { tableProps, rowConfigCache } = useContext(DataTableContext);
312
+ const RenderCell = (_a = tableProps.RenderCell) !== null && _a !== void 0 ? _a : DefaultDataTableCell;
313
+ const columns = tableProps.columns;
314
+ let className = styles[((_b = p.itemProps) === null || _b === void 0 ? void 0 : _b.noPadding) ? 'row' : 'rowPadded'];
315
+ className = cx(shared[getSelectionClass(p)], className);
316
+ let node = p.item;
317
+ let item = node.item;
318
+ let rowConfig, cellConfigs;
319
+ if (tableProps.getRowConfig != null) {
320
+ rowConfig = tableProps.getRowConfig(node, rowType);
321
+ if (rowConfig != null) {
322
+ if (rowConfig.item !== undefined) {
323
+ item = rowConfig.item;
324
+ node = Object.assign(Object.assign({}, node), { item });
325
+ }
326
+ cellConfigs = rowConfig.columns;
327
+ }
328
+ }
329
+ let cells = [];
330
+ for (let i = 0; i < columns.length; i++) {
331
+ let column = columns[i];
332
+ let specialized = tryGetColumnConfig(column, cellConfigs, rowConfigCache);
333
+ let value = getValue(node, columns[i], rowConfig, rowConfigCache, specialized);
334
+ let col = specialized !== null && specialized !== void 0 ? specialized : column;
335
+ let colSpan = (_c = col.getColSpan) === null || _c === void 0 ? void 0 : _c.call(col, node, col.cellProps);
336
+ if (colSpan && colSpan > 1 && Number.isFinite(colSpan)) {
337
+ i += (colSpan - 1) | 0;
338
+ }
339
+ let RenderCell2 = (_d = col.RenderCell) !== null && _d !== void 0 ? _d : RenderCell;
340
+ cells.push(_jsx(RenderCell2, { reactKey: p.reactKey, selKey: p.selKey, item: node, value: value, isSelected: p.isSelected, column: col, readOnly: p.readOnly, expandedParents: p.expandedParents, onClick: p.onClick, renderTreeIndent: col.isTreeCol ? p.renderTreeIndent : undefined, toggleExpanded: p.toggleExpanded, isExpanded: p.isExpanded, colSpan: colSpan, tempState: p.tempState, parentProps: tableProps }, (_f = (_e = col.name) === null || _e === void 0 ? void 0 : _e.toString()) !== null && _f !== void 0 ? _f : i));
341
+ }
342
+ const _h = ((_g = p.itemProps) !== null && _g !== void 0 ? _g : {}), { ref: rowRef } = _h, rowProps = __rest(_h, ["ref"]);
343
+ const rowClassAndStyle = classAndStyle(p.itemProps, className);
344
+ return (_jsx("tr", Object.assign({ ref: rowRef }, rowProps, rowClassAndStyle, { children: cells })));
345
+ });
346
+ // export function getValue(item: any, originalNode: TreeItem<any>, originalCol: DataTableColumn<any,any,any,any>, trowCol: DataTableColumn<any,any,any,any>) {
347
+ // if (trowCol.getValue !== undefined) {
348
+ // return trowCol.getValue(item, originalNode);
349
+ // } else if (originalCol.getValue !== undefined) {
350
+ // return originalCol.getValue(originalNode.item, originalNode);
351
+ // } else {
352
+ // return (item as any)?.[trowCol.name.toString()];
353
+ // }
354
+ // }
355
+ export function DefaultDataTableCell(p) {
356
+ var _a, _b;
357
+ const styles = useListCoreStyles();
358
+ let treeIndent = (_a = p.renderTreeIndent) === null || _a === void 0 ? void 0 : _a.call(p);
359
+ let rendered = ((_b = p.column.renderCell) !== null && _b !== void 0 ? _b : defaultRenderCell)(p.item, p);
360
+ if (p.readOnly) {
361
+ rendered =
362
+ _jsxs("div", { style: { position: 'relative' }, children: [rendered, _jsx("div", { className: styles.readOnlyWrapper })] });
363
+ }
364
+ let cellProps = p.column.cellProps;
365
+ cellProps = cellProps instanceof Function ? cellProps(p.item) : cellProps;
366
+ return (_jsx("td", Object.assign({}, cellProps, { colSpan: p.colSpan, onClick: e => {
367
+ var _a;
368
+ p.onClick(p.item, e);
369
+ (_a = cellProps === null || cellProps === void 0 ? void 0 : cellProps.onClick) === null || _a === void 0 ? void 0 : _a.call(cellProps, e);
370
+ }, children: !treeIndent ? rendered :
371
+ _jsxs("div", { style: { display: 'flex', alignItems: 'center' }, children: [treeIndent, _jsx("div", { style: { flex: 1 }, children: rendered })] }) })));
372
+ }
373
+ export function defaultRenderCell(node, props) {
374
+ const value = props.value;
375
+ if (value === true)
376
+ return '✅';
377
+ if (value === false)
378
+ return '❌';
379
+ else
380
+ return value;
381
+ }
382
+ //#endregion
383
+ /////////////////////////////////////////////////////////////////////////////////////////
384
+ /** The class names used to render tables (defined in datatable.css). These are stable, but
385
+ * exposed as an object so that code written against the earlier makeStyles-based API keeps
386
+ * working. Colors and spacing come from CSS variables; see `TableTheme`. */
387
+ export const dataTableClasses = {
388
+ outerDiv: 'dtbl-outer',
389
+ table: 'dtbl-table',
390
+ rowPadded: 'dtbl-row-padded',
391
+ row: 'dtbl-row',
392
+ sortIcon: 'dtbl-sort-icon',
393
+ draggableColumn: 'dtbl-resize-handle',
394
+ };
395
+ export function useDataTableStyles() {
396
+ return dataTableClasses;
397
+ }
398
+ /** Obtains a function to sort a list of items in a `DataTable`. DataTable provides flexible
399
+ * control over sorting, and the sort process is a bit complicated in order to provide
400
+ * flexibility without losing efficiency; review its code for details.
401
+ *
402
+ * @param colsToSortBy The columns to sort by, where colsToSortBy[0] is the primary sort column
403
+ * and sort direction.
404
+ * @param tableContext The table's context object (corresponding to a React `DataTableContext`).
405
+ */
406
+ function getSorter(colsToSortBy, tableContext) {
407
+ var _a;
408
+ const { tableProps, rowConfigCache } = tableContext;
409
+ // `colsToSortBy` holds column names, but we need column objects.
410
+ var sortBy = colsToSortBy.map(([colName, direction]) => {
411
+ return { column: tableProps.columns.find((col) => col.name === colName), direction };
412
+ }).filter(x => x.column);
413
+ if (sortBy.length <= 0)
414
+ return tableProps.sort;
415
+ const comparers = [];
416
+ let getRowConfig;
417
+ for (let iCol = 0; iCol < sortBy.length; iCol++) {
418
+ const { column, direction } = sortBy[iCol];
419
+ // Prefer to use the `getNodeComparer` function, in the rare case it is provided.
420
+ const nodeComparer = (_a = column.getNodeComparer) === null || _a === void 0 ? void 0 : _a.call(column, direction === SortDirection.Descending);
421
+ if (nodeComparer) {
422
+ comparers[iCol] = nodeComparer;
423
+ }
424
+ else {
425
+ if (!column.getSortableValue)
426
+ getRowConfig = tableProps.getRowConfig;
427
+ if (column.compare) {
428
+ let comparer = column.compare;
429
+ if (direction === SortDirection.Ascending) {
430
+ comparers[iCol] = (a, b) => comparer(a[iCol], b[iCol]);
431
+ }
432
+ else {
433
+ comparers[iCol] = (a, b) => comparer(b[iCol], a[iCol]);
434
+ }
435
+ }
436
+ else {
437
+ if (direction === SortDirection.Ascending) {
438
+ // `let` actually has very strange behavior, at least within for loops!
439
+ // Even though it seems like there is only one `iCol` variable, there
440
+ // is actually a separate `iCol` for each iteration of the `for` loop
441
+ // (because `let` was used rather than `var`). Therefore, `iCol` has the
442
+ // "correct" value here.
443
+ comparers[iCol] = (a, b) => {
444
+ if (a[iCol] > b[iCol])
445
+ return 1;
446
+ if (a[iCol] < b[iCol])
447
+ return -1;
448
+ return 0;
449
+ };
450
+ }
451
+ else {
452
+ comparers[iCol] = (a, b) => {
453
+ if (a[iCol] > b[iCol])
454
+ return -1;
455
+ if (a[iCol] < b[iCol])
456
+ return 1;
457
+ return 0;
458
+ };
459
+ }
460
+ }
461
+ }
462
+ }
463
+ let comparer = combineComparers(comparers.shift(), ...comparers);
464
+ return function sort(list) {
465
+ // Projection: convert `list` to `listEx` by adding properties `rowConfig`, [0], [1], etc.
466
+ const listEx = list.map(node => newObjectWithPrototype(node));
467
+ if (getRowConfig) {
468
+ for (let iRow = 0; iRow < list.length; iRow++) {
469
+ listEx[iRow].rowConfig = getRowConfig(list[iRow], RowType.Normal);
470
+ }
471
+ }
472
+ for (let iCol = 0; iCol < sortBy.length; iCol++) {
473
+ const { column } = sortBy[iCol];
474
+ // In the simple case, `getSortableValue` is provided. Otherwise, use one of the two
475
+ // `getValue` or `name` props (`rowConfig` may specify an override for these).
476
+ if (column.getSortableValue != null) {
477
+ for (let iRow = 0; iRow < listEx.length; iRow++) {
478
+ listEx[iRow][iCol] = column.getSortableValue(listEx[iRow]);
479
+ }
480
+ }
481
+ else {
482
+ for (let iRow = 0; iRow < listEx.length; iRow++) {
483
+ const node = listEx[iRow];
484
+ node[iCol] = getValue(node, column, node.rowConfig, rowConfigCache);
485
+ }
486
+ }
487
+ }
488
+ // Sort
489
+ listEx.sort(comparer);
490
+ for (let i = 0; i < list.length; i++) {
491
+ list[i] = Object.getPrototypeOf(listEx[i]);
492
+ }
493
+ };
494
+ }
495
+ /** Gets the `value` of a cell, which may become the value of `DataTableCellProps<...>.value`,
496
+ * or may be used for sorting if the column doesn't have a `getSortableValue` function.
497
+ *
498
+ * The value is obtained from one of the following sources (highest priority listed first):
499
+ *
500
+ * 1. The `specialized.getValue(TRow)` function, if a `specialized` configuration object was
501
+ * obtained from the user's `getRowConfig(...).columns` collection and it defines `getValue`.
502
+ * 2. `node.item[specialized.name.toString()]`, if `specialized?.name` is not `undefined`.
503
+ * 3. `column.getValue(node.item)`, if `getValue` is not `undefined`.
504
+ * 4. `node.item[column.name.toString()]`, if `column.name` is not `undefined`.
505
+ */
506
+ function getValue(node, column, rowConfig, rowConfigCache, specialized) {
507
+ var _a, _b;
508
+ // The *original* `column.getValue` expects type T (the "original" row value), while the
509
+ // `getValue` buried in `rowConfig` expects type TRow, so distinguish which one applies.
510
+ if (rowConfig != null) {
511
+ specialized !== null && specialized !== void 0 ? specialized : (specialized = tryGetColumnConfig(column, rowConfig.columns, rowConfigCache));
512
+ if (specialized !== undefined) {
513
+ if (specialized.getValue !== undefined) {
514
+ return specialized.getValue(rowConfig.item !== undefined ? rowConfig.item : node.item, node);
515
+ }
516
+ else if (specialized.name !== undefined) {
517
+ return (_a = node.item) === null || _a === void 0 ? void 0 : _a[specialized.name.toString()];
518
+ }
519
+ }
520
+ }
521
+ if (column.getValue !== undefined) {
522
+ return column.getValue(node.item, node);
523
+ }
524
+ else if (column.name !== undefined) {
525
+ return (_b = node.item) === null || _b === void 0 ? void 0 : _b[column.name.toString()];
526
+ }
527
+ }
528
+ /** Obtains the "combined" column configuration for a combination of column and row type, which
529
+ * is derived from both the column configuration (`columns[i]` prop of `DataTableCore` for some
530
+ * index `i`) and the row type configuration (obtained from by calling the `getRowConfig` prop
531
+ * of `DataTableCore`).
532
+ *
533
+ * @param column column info from the `columns[i]` prop of `DataTableCore`.
534
+ * @param cellConfigs the `Map` returned from the `getRowConfig(...).columns` provided by the user.
535
+ * @param rowConfigCache the cache in `useContext(DataTableContext).rowConfigCache`, which
536
+ * stores a merged column configurations indexed by objects returned by `rowConfigCache`.
537
+ * Thanks to the cache, a merge operation is not necessary for every cell, provided that
538
+ * the `getRowConfig` prop does not return unique objects on every call.
539
+ */
540
+ function tryGetColumnConfig(column, cellConfigs, rowConfigCache) {
541
+ let cellConfig;
542
+ // If there is a custom configuration for this type of row, set `column` to be the
543
+ // merger of the original column config in `columns[i]` and the specialized config
544
+ // in `cellConfigs.get(col.name)`. In case the same row type appears many times,
545
+ // we use `rowConfigCache` to avoid repeating the merge operation for every cell.
546
+ if (cellConfigs != null && (cellConfig = cellConfigs.get(column.name)) != null) {
547
+ let cachedCol = rowConfigCache.get(cellConfig);
548
+ if (cachedCol !== undefined) {
549
+ return cachedCol;
550
+ }
551
+ else {
552
+ column = Object.assign(Object.assign(Object.assign({}, column), cellConfig), { getValue: cellConfig.getValue });
553
+ rowConfigCache.set(cellConfig, column);
554
+ return column;
555
+ }
556
+ }
557
+ }
558
+ /** Returns a function that sorts with two or more comparison functions for the same type T.
559
+ * For example, if T is `{ x: number, y: string }` and you have two comparers `cmpX` and `cmpY`
560
+ * that projects and compares the two fields, then `combineComparers(cmpX, cmpY)` returns a
561
+ * function that compares by field X, and when those are equal (so `cmpX` returns 0), compares
562
+ * by field Y. */
563
+ export function combineComparers(comparator, ...comparators) {
564
+ if (!(comparators === null || comparators === void 0 ? void 0 : comparators.length))
565
+ return comparator;
566
+ return function combinedComparisons(a, b) {
567
+ let result = comparator(a, b);
568
+ if (result === 0)
569
+ for (let comparator of comparators) {
570
+ result = comparator(a, b);
571
+ if (result !== 0)
572
+ break;
573
+ }
574
+ return result;
575
+ };
576
+ }
577
+ export function compareByLocale(a, b) {
578
+ let strA = a === null || a === void 0 ? void 0 : a.toString();
579
+ let strB = b === null || b === void 0 ? void 0 : b.toString();
580
+ if (strA == null) {
581
+ if (strB == null)
582
+ return 0;
583
+ return -1;
584
+ }
585
+ else if (strB == null) {
586
+ return 1;
587
+ }
588
+ return strA.localeCompare(strB);
589
+ }
590
+ /** Compares any pair of numbers, strings, booleans, Dates, or (to the extent supported by the
591
+ * `>` and `<` operators) arrays. String comparisons are case-sensitive. */
592
+ export function heterogeneousCompare(a, b) {
593
+ if (typeof a !== typeof b || a == null || b == null) {
594
+ return getTypeOrder(a) - getTypeOrder(b);
595
+ }
596
+ else {
597
+ return a > b ? 1 : a < b ? -1 : 0;
598
+ }
599
+ }
600
+ // An arbitrary order between different custom field types to enable cross-type sorting
601
+ function getTypeOrder(x) {
602
+ if (x == null) {
603
+ return 0;
604
+ }
605
+ else if (typeof x === 'number') {
606
+ return 1;
607
+ }
608
+ else if (typeof x === 'string') {
609
+ return 2;
610
+ }
611
+ else if (typeof x === 'boolean') {
612
+ return 3;
613
+ }
614
+ else if (x instanceof Date) {
615
+ return 4;
616
+ }
617
+ else {
618
+ return 5;
619
+ }
620
+ }
@@ -0,0 +1,35 @@
1
+ import { Holder } from 'holders';
2
+ export type DraggableProps = React.HTMLAttributes<HTMLDivElement> & {
3
+ xValue?: Holder<number>;
4
+ yValue?: Holder<number>;
5
+ /** Amount by which to change xValue for each pixel the mouse moves horizontally (default 1) */
6
+ xPerPixel?: number | (() => number);
7
+ /** Amount by which to change yValue for each pixel the mouse moves vertically (default 1) */
8
+ yPerPixel?: number | (() => number);
9
+ /** If provided, xValue / yValue are not modified until this function returns true. */
10
+ hasMovedEnough?(deltaX: number, deltaY: number): boolean;
11
+ /** Called after the left mouse button is clicked */
12
+ onDragButtonDown?(event: React.PointerEvent<HTMLDivElement>): void;
13
+ /** Called when dragging stops (and the mouse pointer moved enough to detect that dragging
14
+ * started), either because the left mouse button is released or the user pressed Escape
15
+ * or mouse capture was lost. */
16
+ onStopDrag?(event?: PointerEvent | KeyboardEvent): void;
17
+ /** Called when dragging starts (and the mouse pointer moved enough to detect that dragging
18
+ * started). */
19
+ onStartDrag?(): void;
20
+ /** Called when the left mouse button is released without sufficient movement to initiate a drag. */
21
+ onClick?(event: PointerEvent): void;
22
+ };
23
+ /** An unstyled div that can be clicked and dragged to change an "X" or "Y" value,
24
+ * e.g. representing a priority on PrioritiesDiagram, or the size of a modal.
25
+ *
26
+ * Draggable does not know or care about the meaning of the x and y values it changes.
27
+ * One example usage can be found in `SplitPane`, where it is used to alter the size
28
+ * of a different element.
29
+ *
30
+ * Typically one should set a cursor, e.g. with `style={{ cursor: 'col-resize' }}`,
31
+ * and also `tabIndex={0}` so that the drag handle can get the keyboard focus,
32
+ * which allows the escape key to cancel the drag by setting the x/y value back to
33
+ * what it was when the drag started.
34
+ */
35
+ export declare const Draggable: (p: DraggableProps) => import("react").JSX.Element;