datatable-tree 0.0.0-stage → 0.1.0
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 +240 -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 +137 -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
package/src/TreeList.tsx
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
import React, { createContext, useMemo, useRef } from 'react';
|
|
2
|
+
|
|
3
|
+
import { useTableConfig } from './config.js';
|
|
4
|
+
import { useStatefulObjectIfNotGivenBy } from './hooks.js';
|
|
5
|
+
import { ISet } from './interfaces.js';
|
|
6
|
+
import {
|
|
7
|
+
defaultRenderItem as defaultRenderItem_, ListCore, ListCoreProps, ListItemProps,
|
|
8
|
+
ModifiedListItemProps, useListCoreStyles
|
|
9
|
+
} from './ListBox.js';
|
|
10
|
+
import { asAction, getReactivityAdapter, reactive, useWatched } from './reactivity.js';
|
|
11
|
+
import { classAndStyle, Styles } from './styles.js';
|
|
12
|
+
import { TableTheme, useThemeProps } from './theme.js';
|
|
13
|
+
import { cx, mapMap, nully, toggleSetMembership } from './util.js';
|
|
14
|
+
|
|
15
|
+
/** Each item in a TreeList or DataTable is wrapped in one of these objects.
|
|
16
|
+
* They are transient: new TreeItems are created during each render.
|
|
17
|
+
* The second type parameter is used by DataTable. */
|
|
18
|
+
export interface TreeItem<T,TRow=T> {
|
|
19
|
+
readonly item: TRow;
|
|
20
|
+
readonly children?: readonly TreeItem<T>[];
|
|
21
|
+
readonly parent?: TreeItem<T>;
|
|
22
|
+
readonly depth: number;
|
|
23
|
+
}
|
|
24
|
+
export interface TreeItemM<T> extends TreeItem<T> {
|
|
25
|
+
children?: TreeItemM<T>[];
|
|
26
|
+
// These need to be updated if the item is in cache
|
|
27
|
+
item: T;
|
|
28
|
+
parent?: TreeItem<T>;
|
|
29
|
+
depth: number;
|
|
30
|
+
version?: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type DefaultTreeItemProps = Styles & {
|
|
34
|
+
highlightChildrenOfSelectedParents?: boolean;
|
|
35
|
+
noPadding?: boolean|nully;
|
|
36
|
+
ref?: React.Ref<HTMLDivElement>;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** Describes the items to display including parent-child relationships. You can either provide
|
|
40
|
+
* a `tree` directly, or a list with `getChildren` / `getParents` functions to describe these
|
|
41
|
+
* relationships. */
|
|
42
|
+
export type TreeListMainProps<T> =
|
|
43
|
+
{
|
|
44
|
+
/** Provides a tree in the "native" format of `TreeListCore`/`TreeList`/`DataTable`.
|
|
45
|
+
*
|
|
46
|
+
* Note: `TreeListCore` assumes that all `parent` and `children` props are consistent with
|
|
47
|
+
* each other, e.g. that `tree[i].children[j].parent === tree[i]`. It will malfunction
|
|
48
|
+
* otherwise.
|
|
49
|
+
*
|
|
50
|
+
* Note: This is `TreeItemM` rather than `TreeItem` because `TreeListCore` (via
|
|
51
|
+
* `flattenToList`) will sort sublists mutably when there is no filter applied. */
|
|
52
|
+
tree: TreeItemM<T>[];
|
|
53
|
+
list?: undefined;
|
|
54
|
+
getChildren?: undefined;
|
|
55
|
+
getParents?: undefined;
|
|
56
|
+
isParent?: undefined;
|
|
57
|
+
} |
|
|
58
|
+
{
|
|
59
|
+
tree?: undefined;
|
|
60
|
+
list: T[];
|
|
61
|
+
/** Gets the children of an item. It is useless to provide both a
|
|
62
|
+
* `getParents` and `getChildren` prop, as only one will be called. */
|
|
63
|
+
getChildren(item: T): T[] | undefined;
|
|
64
|
+
getParents?: undefined;
|
|
65
|
+
isParent?: undefined;
|
|
66
|
+
} |
|
|
67
|
+
{
|
|
68
|
+
tree?: undefined;
|
|
69
|
+
/** List of items to display. If `getParents` is provided, then items with parents
|
|
70
|
+
* are not displayed at the root level (they are nested inside their parents);
|
|
71
|
+
* otherwise, all items in this list are displayed at the root level and there
|
|
72
|
+
* may be additional items (not in this list) nested inside them if `getChildren`
|
|
73
|
+
* returns items. */
|
|
74
|
+
list: T[];
|
|
75
|
+
getChildren?: undefined;
|
|
76
|
+
/** Gets the parents of an item (that is, the path to reach the item). The parents must
|
|
77
|
+
* be listed in order from root to child. This function is only called for items in the
|
|
78
|
+
* `list`, not for items returned by `getParents` itself.
|
|
79
|
+
*
|
|
80
|
+
* Example: `getParents={filename => getParentPathsOf(filename, '/', false)}`
|
|
81
|
+
**/
|
|
82
|
+
getParents?(item: T): T[] | undefined;
|
|
83
|
+
/** `getParents` by itself gives you no way to indicate that an item is a parent
|
|
84
|
+
* without children (e.g. an empty folder). If this function returns true, an item's
|
|
85
|
+
* expansion icon is displayed even when it has no children. This property is unused
|
|
86
|
+
* if you don't provide `getParents`. TODO: if `isParent` and `getChildren` are both
|
|
87
|
+
* provided, we shouldn't call `getChildren()` for unexpanded nodes. In fact, right
|
|
88
|
+
* now all unexpanded nodes are retrieved recursively which is wasteful. */
|
|
89
|
+
isParent?(item: T): boolean;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/** The rest of `TreeListCoreProps`. */
|
|
93
|
+
export interface TreeListAuxProps<T, K=T, ItemProps=DefaultTreeItemProps> extends
|
|
94
|
+
Omit<ListCoreProps<T, K, ItemProps>, 'renderItem' | 'RenderItem' | 'onClickItem' | 'filter' | 'itemProps' | 'list'>, Styles
|
|
95
|
+
{
|
|
96
|
+
/** The set of nodes that are currently expanded. If provided, this should be a
|
|
97
|
+
* MobX `observable.set` rather than a plain Set<K>. */
|
|
98
|
+
expandedParents?: ISet<K>;
|
|
99
|
+
/** Called to render a T value. */
|
|
100
|
+
renderItem?(item: TreeItem<T>, props: ListItemProps<TreeItem<T>, K, ItemProps>): React.ReactNode;
|
|
101
|
+
/** Component type used to render the entire row (including an outer `div` or `tr`). */
|
|
102
|
+
RenderItem?: React.ComponentType<TreeItemProps<T, K, ItemProps>>;
|
|
103
|
+
/** Called to render the indentation and tree expander button. It will return an
|
|
104
|
+
* element with `display: inline-block` and with a width that varies according to the
|
|
105
|
+
* appropriate amount of indentation. Note: this should usually be placed inside
|
|
106
|
+
* a flex row (`display: flex`) so that word-wrapping of the label after the indent
|
|
107
|
+
* looks right. */
|
|
108
|
+
renderTreeIndent?(this: TreeItemProps<T, K, ItemProps>): React.ReactNode;
|
|
109
|
+
/** This is called immediately when an item is clicked, and if it returns
|
|
110
|
+
'abort' the click on the item will be ignored (rather than selecting the item) */
|
|
111
|
+
onClickItem?(this: ModifiedTreeItemProps<T, K, ItemProps>, item: TreeItem<T>): void|'abort' | Promise<void|'abort'>;
|
|
112
|
+
/** This is called for each item, if you provide it. Items for which this function
|
|
113
|
+
* returns false are hidden. */
|
|
114
|
+
filter?(item: TreeItem<T>, index: number): boolean;
|
|
115
|
+
/** This prop is ignored if `sort` is provided. Otherwise, if provided, this is used
|
|
116
|
+
* after filtering to sort only the visible items.
|
|
117
|
+
*
|
|
118
|
+
* Note: rows are sorted level-by-level. For example, given this tree of items:
|
|
119
|
+
*
|
|
120
|
+
* Clothes
|
|
121
|
+
* Shirt
|
|
122
|
+
* Pants
|
|
123
|
+
* Shorts
|
|
124
|
+
* Toys
|
|
125
|
+
* Dolls
|
|
126
|
+
* Cars
|
|
127
|
+
*
|
|
128
|
+
* The three sublists [Clothes, Toys], [Shirt, Pants, Shorts], and [Dolls, Cars] are
|
|
129
|
+
* sorted separately, as one would expect.
|
|
130
|
+
**/
|
|
131
|
+
sortComparer?(a: TreeItem<T>, b: TreeItem<T>): number;
|
|
132
|
+
/** If provided, this is called after filtering to sort visible items at each level of
|
|
133
|
+
* the tree.
|
|
134
|
+
*
|
|
135
|
+
* Note: when `sort` or `sortComparer` is used in `DataTable` or `DataTableCore`, they
|
|
136
|
+
* stop being used to sort if the user sorts by clicking a column header, or if the
|
|
137
|
+
* `DataTableCoreProps.columnsToSortBy` prop is provided. However, these props still
|
|
138
|
+
* control the default sort order. When a table has a default sort order, the user can
|
|
139
|
+
* click the same column header three times to cancel user-defined sorting and return
|
|
140
|
+
* to the default sort order.
|
|
141
|
+
**/
|
|
142
|
+
sort?(list: TreeItemM<T>[]): void;
|
|
143
|
+
/** props that should apply to each item (usually Styles: `className` and `style`).
|
|
144
|
+
* If `RenderItem` is provided, these props are forwarded to it. In a `<DataTable>`,
|
|
145
|
+
* any styles in this object are applied to the row as a whole, not to each cell. */
|
|
146
|
+
itemProps?: ItemProps | ((item: TreeItem<T>) => ItemProps | undefined);
|
|
147
|
+
/** Number of pixels to indent per level of nesting (default: the theme's `treeIndent`,
|
|
148
|
+
* i.e. the --dtbl-indent CSS variable, which itself defaults to 20) */
|
|
149
|
+
indentPerLevel?: number;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Main properties of a `<TreeList>` or `<TreeListCore>`. The only required prop is `list`
|
|
153
|
+
* (or `tree`), but it's recommended to also provide `getKey` to identify items to React. */
|
|
154
|
+
export type TreeListCoreProps<T, K=T, ItemProps=DefaultTreeItemProps> =
|
|
155
|
+
TreeListMainProps<T> & TreeListAuxProps<T, K, ItemProps>;
|
|
156
|
+
|
|
157
|
+
/** Omit/modify certain prop(s) so that `<DataTable>` type checks when it uses `renderTreeIndent`
|
|
158
|
+
* and so that `TreeListCore` type checks when it passes `onClickItem` to `ListCore`. */
|
|
159
|
+
export type ModifiedTreeItemProps<T, K, ItemProps>
|
|
160
|
+
= Omit<ListItemProps<TreeItem<T>, K, ItemProps>, 'renderItem'>
|
|
161
|
+
& Partial<TreeItemProps<T, K, ItemProps>>;
|
|
162
|
+
|
|
163
|
+
/** Props passed to renderers (`TreeListProps<...>.renderItem` and `RenderItem`). */
|
|
164
|
+
export interface TreeItemProps<T, K=T, ItemProps=Styles>
|
|
165
|
+
extends ListItemProps<TreeItem<T>, K, ItemProps>
|
|
166
|
+
{
|
|
167
|
+
/** The set of nodes that are currently expanded. If provided, this should be a
|
|
168
|
+
* MobX `observable.set` rather than a plain Set<K>. */
|
|
169
|
+
expandedParents: ISet<K>;
|
|
170
|
+
/** Whether `expandedParents` includes `selKey` */
|
|
171
|
+
isExpanded: boolean;
|
|
172
|
+
/** Renders the indentation and tree expander button. */
|
|
173
|
+
renderTreeIndent(this: ModifiedTreeItemProps<T, K, ItemProps>): React.ReactNode;
|
|
174
|
+
/** Expands or collapses this item. */
|
|
175
|
+
toggleExpanded(this: ModifiedTreeItemProps<T, K, ItemProps>): void;
|
|
176
|
+
/** Props that were passed to the parent `TreeListCore` or `DataTableCore` */
|
|
177
|
+
parentProps: TreeListCoreProps<T, K, ItemProps>;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** A combined list and tree component that allows items to be nested inside each other,
|
|
181
|
+
* and allows parent nodes to be expanded or collapsed. Inherits selection and
|
|
182
|
+
* multiselect functionality from ListCore. It is the same as `TreeList` except that
|
|
183
|
+
* the list contents are not wrapped in any parent element.
|
|
184
|
+
*
|
|
185
|
+
* Example: In this tree, the child of each number is the square of the number.
|
|
186
|
+
* Note that `1` cannot be in the list, because all children are recursively enumerated
|
|
187
|
+
* when the list is displayed, so if 1 is in the list, the `TreeListCore` will crash.
|
|
188
|
+
* Also note that selecting `4` at the root level will also implicitly select the child
|
|
189
|
+
* of `2` because it is also `4`; the component is not designed for duplicate items and
|
|
190
|
+
* so there may be glitches.
|
|
191
|
+
*
|
|
192
|
+
* <TreeListCore
|
|
193
|
+
* list={[ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]}
|
|
194
|
+
* getChildren={x => x < 10 ? [x * x] : []}
|
|
195
|
+
* renderItem={node => `The number ${node.item}`}
|
|
196
|
+
* />
|
|
197
|
+
**/
|
|
198
|
+
export const TreeListCore = reactive(function TreeListCore<T, K=T, ItemProps extends Styles=DefaultTreeItemProps>(
|
|
199
|
+
p: TreeListCoreProps<T, K, ItemProps>
|
|
200
|
+
) {
|
|
201
|
+
const expandedParents = useWatched(
|
|
202
|
+
useStatefulObjectIfNotGivenBy(p.expandedParents, () => getReactivityAdapter().observableSet<K>()));
|
|
203
|
+
const RenderItem = p.RenderItem ?? DefaultRenderItem as NonNullable<(typeof p)['RenderItem']>;
|
|
204
|
+
const renderTreeIndent_ = p.renderTreeIndent ?? renderTreeIndent;
|
|
205
|
+
const getSelKey = p.getSelKey
|
|
206
|
+
? ((item: TreeItem<T>) => p.getSelKey!(item.item))
|
|
207
|
+
: ((item: TreeItem<T>) => item.item as unknown as K);
|
|
208
|
+
|
|
209
|
+
// TODO: React components are not supposed to contain nested components because they
|
|
210
|
+
// are recreated on every render, which confuses React into unmounting and remounting
|
|
211
|
+
// them, which causes the state of not just the nested component, but all other
|
|
212
|
+
// components it contains, to be forgotten and reset. By using `useMemo` we can avoid
|
|
213
|
+
// this problem in most cases, but ideally we should solve it in all cases.
|
|
214
|
+
const RenderBaseItem = useMemo(() =>
|
|
215
|
+
// `observer` is needed so the arrow re-renders when `expandedParents`
|
|
216
|
+
// changes. It's a closure variable, not a prop, so React.memo can't detect the change.
|
|
217
|
+
getReactivityAdapter().observer(function RenderBaseItem(
|
|
218
|
+
props: ListItemProps<TreeItem<T>, K, ItemProps>
|
|
219
|
+
) {
|
|
220
|
+
return (<RenderItem {...props}
|
|
221
|
+
expandedParents={expandedParents}
|
|
222
|
+
renderTreeIndent={renderTreeIndent_}
|
|
223
|
+
isExpanded={expandedParents.has(props.selKey)}
|
|
224
|
+
toggleExpanded={asAction(toggleExpanded)}
|
|
225
|
+
parentProps={p}/>);
|
|
226
|
+
}),
|
|
227
|
+
[expandedParents, renderTreeIndent_, RenderItem]);
|
|
228
|
+
|
|
229
|
+
let tree: TreeItemM<T>[];
|
|
230
|
+
if (p.getParents) {
|
|
231
|
+
tree = getDataAsTree1(p.list, p.getParents, p.getSelKey, p.isParent);
|
|
232
|
+
} else if (p.list) {
|
|
233
|
+
const getChildren = p.getChildren ?? ((item: T) => undefined);
|
|
234
|
+
tree = getDataAsTree2(p.list, getChildren);
|
|
235
|
+
} else {
|
|
236
|
+
tree = p.tree ?? [];
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// We want to avoid re-rendering rows that haven't changed. To convince React to do that,
|
|
240
|
+
// we need to use the same wrapper `TreeItem` for each item that hasn't changed.
|
|
241
|
+
// To accomplish that, use a cache.
|
|
242
|
+
useCachedItems(tree, getSelKey);
|
|
243
|
+
|
|
244
|
+
let list = flattenToList<T,K>(tree, expandedParents, p);
|
|
245
|
+
const listVirtualize = p.virtualize && {
|
|
246
|
+
...p.virtualize,
|
|
247
|
+
height: typeof p.virtualize.height === 'function'
|
|
248
|
+
? (item: TreeItem<T>) => (p.virtualize!.height as (item: T) => number|false)(item.item)
|
|
249
|
+
: p.virtualize.height,
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
return (
|
|
253
|
+
<ListCore<TreeItem<T>, K, ItemProps>
|
|
254
|
+
list={list}
|
|
255
|
+
selection={p.selection}
|
|
256
|
+
selMode={p.selMode}
|
|
257
|
+
renderItem={p.renderItem ?? defaultRenderItem}
|
|
258
|
+
RenderItem={RenderBaseItem}
|
|
259
|
+
onClickItem={p.onClickItem}
|
|
260
|
+
getKey={p.getKey
|
|
261
|
+
? (item => p.getKey!(item.item))
|
|
262
|
+
: undefined}
|
|
263
|
+
getSelKey={getSelKey}
|
|
264
|
+
lastClicked={p.lastClicked}
|
|
265
|
+
itemProps={p.itemProps}
|
|
266
|
+
readOnly={p.readOnly}
|
|
267
|
+
virtualize={listVirtualize}
|
|
268
|
+
virtualGapRenderer={p.virtualGapRenderer}
|
|
269
|
+
placeholder={p.placeholder}
|
|
270
|
+
/>
|
|
271
|
+
);
|
|
272
|
+
|
|
273
|
+
function toggleExpanded(this: TreeItemProps<T, K, ItemProps>) {
|
|
274
|
+
toggleSetMembership(this.expandedParents, this.selKey);
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
/** Replaces items in `tree` with previously cached items from a cache, while storing new items
|
|
279
|
+
* in the cache and removing stale items. */
|
|
280
|
+
function useCachedItems<T, K>(
|
|
281
|
+
tree: TreeItemM<T>[],
|
|
282
|
+
getSelKey: (item: TreeItem<T>) => K,
|
|
283
|
+
) {
|
|
284
|
+
const nodeCache = useRef<Map<K, TreeItemM<T>>>(new Map());
|
|
285
|
+
const version = ++useRef(0).current;
|
|
286
|
+
|
|
287
|
+
recursivelyUseCachedItems(tree, getSelKey, nodeCache.current, version);
|
|
288
|
+
|
|
289
|
+
// prune stale cache entries
|
|
290
|
+
for (const [key, node] of nodeCache.current) {
|
|
291
|
+
if (node.version !== version)
|
|
292
|
+
nodeCache.current.delete(key);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function recursivelyUseCachedItems<T, K>(
|
|
297
|
+
tree: TreeItemM<T>[],
|
|
298
|
+
getSelKey: (item: TreeItem<T>) => K,
|
|
299
|
+
cache: Map<K, TreeItemM<T>>,
|
|
300
|
+
version: number,
|
|
301
|
+
parent?: TreeItemM<T>, // cached parent object (or original parent if parent is new)
|
|
302
|
+
): TreeItemM<T>[] {
|
|
303
|
+
for (let i = 0; i < tree.length; i++) {
|
|
304
|
+
const node = tree[i];
|
|
305
|
+
const key = getSelKey(node);
|
|
306
|
+
|
|
307
|
+
let cachedNode = cache.get(key);
|
|
308
|
+
// Avoid sharing the same wrapper for duplicate keys in a single render
|
|
309
|
+
if (cachedNode && cachedNode.version !== version) {
|
|
310
|
+
cachedNode.item = node.item;
|
|
311
|
+
cachedNode.parent = parent;
|
|
312
|
+
cachedNode.depth = node.depth;
|
|
313
|
+
cachedNode.children = node.children &&
|
|
314
|
+
recursivelyUseCachedItems(node.children, getSelKey, cache, version, cachedNode);
|
|
315
|
+
cachedNode.version = version;
|
|
316
|
+
tree[i] = cachedNode;
|
|
317
|
+
} else {
|
|
318
|
+
node.version = version;
|
|
319
|
+
cache.set(key, node);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
return tree;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export type TreeListProps<T, K=T, ItemProps=Styles> = TreeListCoreProps<T, K, ItemProps> & Styles & {
|
|
327
|
+
/** Theme for this tree; overrides the ambient `TableConfig` theme. */
|
|
328
|
+
theme?: TableTheme | string | nully;
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
/** A combined list and tree component that allows items to be nested inside each other,
|
|
332
|
+
* and allows parent nodes to be expanded or collapsed. Inherits selection and
|
|
333
|
+
* multiselect functionality from ListCore. This is the same as `TreeListCore` except
|
|
334
|
+
* that the list contents are wrapped in a scrollable div (and thus, only TreeList
|
|
335
|
+
* supports `style` and `className`.) */
|
|
336
|
+
export function TreeList<T, K=T, ItemProps extends Styles=DefaultTreeItemProps>(
|
|
337
|
+
p: TreeListProps<T, K, ItemProps>
|
|
338
|
+
) {
|
|
339
|
+
const theme = useThemeProps(p.theme);
|
|
340
|
+
return (
|
|
341
|
+
<div tabIndex={0} {...classAndStyle(p, theme.className, { overflowY: 'scroll', ...theme.style })}>
|
|
342
|
+
<TreeListCore {...p}/>
|
|
343
|
+
</div>);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function renderTreeIndent<T>(this: TreeItemProps<T,any,any>) {
|
|
347
|
+
// The indent comes from the `indentPerLevel` prop, or else the theme (see TableMetrics)
|
|
348
|
+
const ipl = this.parentProps.indentPerLevel;
|
|
349
|
+
const indent = ipl != null ? `${ipl}px` : 'var(--dtbl-indent, 20px)';
|
|
350
|
+
const expanderWidth = `calc(12px + ${indent})`;
|
|
351
|
+
return (
|
|
352
|
+
<div style={{ display: 'inline-block',
|
|
353
|
+
marginLeft: this.item.depth === 0 ? 0 : `calc(${indent} * ${this.item.depth})`,
|
|
354
|
+
minWidth: expanderWidth }}>
|
|
355
|
+
{this.item.children == null ? undefined :
|
|
356
|
+
<TreeExpanderButton width={expanderWidth} isExpanded={this.isExpanded}
|
|
357
|
+
toggleExpanded={() => this.toggleExpanded()}/>
|
|
358
|
+
}
|
|
359
|
+
</div>);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** The expand/collapse button in tree cells. The button itself comes from
|
|
363
|
+
* `TableConfig.renderIconButton` and the icons from `TableConfig.icons`. */
|
|
364
|
+
function TreeExpanderButton(p: { width: number|string, isExpanded: boolean, toggleExpanded: () => void }) {
|
|
365
|
+
const { icons, renderIconButton } = useTableConfig();
|
|
366
|
+
return renderIconButton({
|
|
367
|
+
onClick: e => { p.toggleExpanded(); e.stopPropagation(); },
|
|
368
|
+
style: { width: p.width },
|
|
369
|
+
'aria-label': p.isExpanded ? 'Collapse' : 'Expand',
|
|
370
|
+
children: p.isExpanded ? icons.expanded : icons.collapsed,
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function defaultRenderItem(node: TreeItem<any>, props?: { isSelected: boolean|null }) {
|
|
375
|
+
return defaultRenderItem_(node.item);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export function DefaultRenderItem<T, K, ItemProps extends DefaultTreeItemProps>(
|
|
379
|
+
p: TreeItemProps<T, K, ItemProps>
|
|
380
|
+
) {
|
|
381
|
+
const styles = useListCoreStyles();
|
|
382
|
+
let treeIndent = p.renderTreeIndent();
|
|
383
|
+
|
|
384
|
+
let className = styles[getSelectionClass(p)];
|
|
385
|
+
if (!p.itemProps?.noPadding)
|
|
386
|
+
className = cx(className, styles.padding);
|
|
387
|
+
let styling = classAndStyle(p.itemProps, className, { display: 'flex', alignItems: 'center' });
|
|
388
|
+
const { ref: itemRef } = (p.itemProps ?? {}) as DefaultTreeItemProps;
|
|
389
|
+
|
|
390
|
+
let rendered = (p.renderItem ?? defaultRenderItem)(p.item, p);
|
|
391
|
+
|
|
392
|
+
let wrapped = (
|
|
393
|
+
<div ref={itemRef} onClick={e => p.onClick(p.item, e)} {...styling}>
|
|
394
|
+
{treeIndent}{rendered}
|
|
395
|
+
</div>);
|
|
396
|
+
|
|
397
|
+
if (p.readOnly) {
|
|
398
|
+
// Put a filter on top that grays out the contents of the row
|
|
399
|
+
wrapped = <div style={{ position: 'relative' }}>
|
|
400
|
+
{wrapped}
|
|
401
|
+
<div className={styles.readOnlyWrapper}/>
|
|
402
|
+
</div>;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// Add `p.item` to `selectedParents` where applicable. This relies on parents being
|
|
406
|
+
// rendered before their children. (An alternate way we could've done this is to
|
|
407
|
+
// precompute an “hasSelectedAncestor” flag during flatten, stored in each tree item.
|
|
408
|
+
// that could avoid the need for ListCore to know about `selectedParents`.)
|
|
409
|
+
if (p.item.children?.length) {
|
|
410
|
+
if (p.isSelected || p.tempState.selectedParents?.has(p.item.parent!)) {
|
|
411
|
+
// Use WeakSet so that selected items removed from the tree can be GC'd
|
|
412
|
+
(p.tempState.selectedParents ??= new WeakSet<TreeItem<T>>()).add(p.item);
|
|
413
|
+
} else {
|
|
414
|
+
// `selectedParents` is preserved between renders; delete stale items
|
|
415
|
+
p.tempState.selectedParents?.delete(p.item);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
return wrapped;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
export function getSelectionClass<T, K, ItemProps>(
|
|
423
|
+
p: Pick<TreeItemProps<T, K, ItemProps>, 'item' | 'isSelected' | 'tempState' | 'itemProps'>
|
|
424
|
+
): 'selected' | 'unselected' | 'parentSelected' {
|
|
425
|
+
if (p.item.children?.length &&
|
|
426
|
+
(p.isSelected || p.tempState.selectedParents?.has(p.item.parent!))
|
|
427
|
+
) {
|
|
428
|
+
p.tempState.selectedParents ??= new Set<TreeItem<T>>();
|
|
429
|
+
p.tempState.selectedParents.add(p.item);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
if (p.isSelected)
|
|
433
|
+
return 'selected';
|
|
434
|
+
else if (((p.itemProps as any)?.highlightChildrenOfSelectedParents ?? true)
|
|
435
|
+
&& p.tempState.selectedParents?.has(p.item.parent!))
|
|
436
|
+
return 'parentSelected';
|
|
437
|
+
else
|
|
438
|
+
return 'unselected';
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
interface TempTree<T, K> {
|
|
442
|
+
// There can be just an item, just children, or both
|
|
443
|
+
item: T;
|
|
444
|
+
children?: Map<K, TempTree<T, K>>;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Converts a list of items to a tree using a user-defined `getParents` function. */
|
|
448
|
+
export function getDataAsTree1<T,K=T>(
|
|
449
|
+
items: Iterable<T>,
|
|
450
|
+
getParents: (item: T) => T[] | undefined,
|
|
451
|
+
getSelKey = (item: T) => item as unknown as K,
|
|
452
|
+
isParent?: (item: T) => boolean
|
|
453
|
+
): TreeItemM<T>[] {
|
|
454
|
+
const map = new Map<K, TempTree<T, K>>();
|
|
455
|
+
|
|
456
|
+
// Convert the items array into a tree structure in `map`
|
|
457
|
+
for (let item of items) {
|
|
458
|
+
// Get the parents of the item
|
|
459
|
+
let key = getSelKey(item);
|
|
460
|
+
let parents = getParents(item);
|
|
461
|
+
let submap = map;
|
|
462
|
+
if (parents) {
|
|
463
|
+
let subtree: TempTree<T, K> | undefined;
|
|
464
|
+
for (let i = 0; i < parents.length; i++) {
|
|
465
|
+
subtree = getOrMakeSubmap(submap, parents[i], getSelKey);
|
|
466
|
+
submap = subtree.children!;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
if (!submap.has(key)) {
|
|
470
|
+
submap.set(key, { item });
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
return convertTreeToArrayForm(map, isParent);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function getOrMakeSubmap<T,K>(map: Map<K, TempTree<T, K>>, item: T, getSelKey?: (item: T) => K) {
|
|
478
|
+
let key = getSelKey ? getSelKey(item) : item as unknown as K;
|
|
479
|
+
|
|
480
|
+
let subtree = map.get(key);
|
|
481
|
+
if (!subtree) map.set(key, subtree = { item });
|
|
482
|
+
|
|
483
|
+
subtree.children ??= new Map<K, TempTree<T, K>>();
|
|
484
|
+
return subtree;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function convertTreeToArrayForm<T, K>(map: Map<K, TempTree<T, K>>, isParent?: (item: T) => boolean, parent?: TreeItem<T>, depth = 0): TreeItemM<T>[] {
|
|
488
|
+
return mapMap(map, (key, treeItem) => {
|
|
489
|
+
let item: TreeItemM<T> = {
|
|
490
|
+
item: treeItem.item,
|
|
491
|
+
parent,
|
|
492
|
+
depth,
|
|
493
|
+
};
|
|
494
|
+
if (treeItem.children?.size) {
|
|
495
|
+
item.children = convertTreeToArrayForm(treeItem.children, isParent, item, depth + 1);
|
|
496
|
+
} else if (isParent && isParent(treeItem.item)) {
|
|
497
|
+
item.children = [];
|
|
498
|
+
}
|
|
499
|
+
return item;
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** Converts a list of items to a tree using a user-defined `getChildren` function.
|
|
504
|
+
*
|
|
505
|
+
* TODO: optimize the design so that it is not necessary to call getChildren() on
|
|
506
|
+
* non-expanded nodes. */
|
|
507
|
+
export function getDataAsTree2<T>(
|
|
508
|
+
items: Iterable<T>,
|
|
509
|
+
getChildren: (item: T) => T[] | undefined,
|
|
510
|
+
parent?: TreeItem<T>,
|
|
511
|
+
depth = 0,
|
|
512
|
+
): TreeItemM<T>[] {
|
|
513
|
+
const result: TreeItemM<T>[] = [];
|
|
514
|
+
|
|
515
|
+
for (let item of items) {
|
|
516
|
+
let treeItem: TreeItemM<T> = {
|
|
517
|
+
item,
|
|
518
|
+
parent,
|
|
519
|
+
depth,
|
|
520
|
+
};
|
|
521
|
+
let children = getChildren(item);
|
|
522
|
+
if (children) {
|
|
523
|
+
treeItem.children = getDataAsTree2(children, getChildren, treeItem, depth + 1);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
result.push(treeItem);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
return result;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function flattenToList<T, K=T>(
|
|
533
|
+
tree_: TreeItemM<T>[],
|
|
534
|
+
expandedParents: ISet<K>,
|
|
535
|
+
p: {
|
|
536
|
+
filter?: ((item: TreeItem<T>, index: number) => boolean),
|
|
537
|
+
getSelKey?: ((item: T) => K),
|
|
538
|
+
sortComparer?: (a: TreeItem<T>, b: TreeItem<T>) => number,
|
|
539
|
+
sort?: (list: TreeItemM<T>[]) => void,
|
|
540
|
+
},
|
|
541
|
+
results: TreeItem<T>[] = []
|
|
542
|
+
) {
|
|
543
|
+
let { filter, getSelKey, sort } = p;
|
|
544
|
+
// Apply filtering before sorting
|
|
545
|
+
let tree = tree_;
|
|
546
|
+
if (filter) {
|
|
547
|
+
tree = [];
|
|
548
|
+
for (let i = 0; i < tree_.length; i++) {
|
|
549
|
+
if (filter(tree_[i], i))
|
|
550
|
+
tree.push(tree_[i]);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
if (sort) {
|
|
555
|
+
sort(tree);
|
|
556
|
+
} else if (p.sortComparer) {
|
|
557
|
+
tree.sort(p.sortComparer);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// Copy items and expanded children to results list
|
|
561
|
+
for (let i = 0; i < tree.length; i++) {
|
|
562
|
+
const item = tree[i];
|
|
563
|
+
results.push(item);
|
|
564
|
+
|
|
565
|
+
const key = getSelKey ? getSelKey(item.item) : item.item as unknown as K;
|
|
566
|
+
if (item.children && expandedParents.has(key)) {
|
|
567
|
+
flattenToList(item.children, expandedParents, p, results);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
return results;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/** This helper function returns a list of parent paths of a path. For example,
|
|
574
|
+
* `getParentPathsOf('C:\\Windows\\System')` returns `['C:', 'C:\\Windows']`.
|
|
575
|
+
* Note: `getParentPathsOf('')` returns [] even if `includeSelf` is true. **/
|
|
576
|
+
export function getParentPathsOf(path: string|nully, separator = '\\', includeSelf = false): string[] {
|
|
577
|
+
let parents = [];
|
|
578
|
+
if (path) {
|
|
579
|
+
for (let i = 1; i < path.length; i++) {
|
|
580
|
+
if (path[i] === separator) {
|
|
581
|
+
parents.push(path.slice(0, i));
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
if (includeSelf) {
|
|
585
|
+
parents.push(path);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
return parents;
|
|
590
|
+
}
|
package/src/config.tsx
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import React, { createContext, CSSProperties, ReactNode, useContext, useMemo } from 'react';
|
|
2
|
+
|
|
3
|
+
import type { TableTheme } from './theme.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* TableConfig
|
|
7
|
+
* -----------
|
|
8
|
+
*
|
|
9
|
+
* App-wide (or subtree-wide) defaults for the components in this package, so that
|
|
10
|
+
* individual call sites don't need to configure icons or themes. Provide it once near the
|
|
11
|
+
* root of your app:
|
|
12
|
+
*
|
|
13
|
+
* <TableConfig theme={darkTheme}
|
|
14
|
+
* icons={{ expanded: <MyChevronDown/>, collapsed: <MyChevronRight/> }}>
|
|
15
|
+
* <App/>
|
|
16
|
+
* </TableConfig>
|
|
17
|
+
*
|
|
18
|
+
* Providers nest: an inner `TableConfig` overrides only the fields it specifies. Anything
|
|
19
|
+
* not configured falls back to built-in defaults (unicode glyph icons, light theme).
|
|
20
|
+
*/
|
|
21
|
+
export interface TableIcons {
|
|
22
|
+
/** Sort indicator on a column header sorted ascending (default: ▲). */
|
|
23
|
+
sortAscending?: ReactNode;
|
|
24
|
+
/** Sort indicator on a column header sorted descending (default: ▼). */
|
|
25
|
+
sortDescending?: ReactNode;
|
|
26
|
+
/** Icon on the expander button of an expanded tree item (default: ▾). */
|
|
27
|
+
expanded?: ReactNode;
|
|
28
|
+
/** Icon on the expander button of a collapsed tree item (default: ▸). */
|
|
29
|
+
collapsed?: ReactNode;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Props passed to `TableConfigValue.renderIconButton`. */
|
|
33
|
+
export interface TableIconButtonProps {
|
|
34
|
+
onClick: React.MouseEventHandler<HTMLElement>;
|
|
35
|
+
style?: CSSProperties;
|
|
36
|
+
'aria-label'?: string;
|
|
37
|
+
children?: ReactNode;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface TableConfigValue {
|
|
41
|
+
icons?: TableIcons;
|
|
42
|
+
/** Renders the tree-expander button. The default renders a plain `<button
|
|
43
|
+
* className="dtbl-expander">`; override this to use your design system's icon button
|
|
44
|
+
* (e.g. MUI's `<IconButton size="large">`). */
|
|
45
|
+
renderIconButton?: (props: TableIconButtonProps) => React.ReactElement;
|
|
46
|
+
/** Default theme for tables/lists in this subtree (see `theme.ts`). A component's own
|
|
47
|
+
* `theme` prop takes precedence. */
|
|
48
|
+
theme?: TableTheme | string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const TableConfigContext = createContext<TableConfigValue>({});
|
|
52
|
+
|
|
53
|
+
/** Provides defaults (icons, theme, ...) to all list/tree/table components in a subtree.
|
|
54
|
+
* Nesting is supported; unspecified fields are inherited from the outer provider. */
|
|
55
|
+
export function TableConfig(p: TableConfigValue & { children: ReactNode }) {
|
|
56
|
+
const outer = useContext(TableConfigContext);
|
|
57
|
+
const merged = useMemo<TableConfigValue>(() => ({
|
|
58
|
+
...outer,
|
|
59
|
+
...(p.theme !== undefined && { theme: p.theme }),
|
|
60
|
+
...(p.renderIconButton !== undefined && { renderIconButton: p.renderIconButton }),
|
|
61
|
+
...((p.icons || outer.icons) && { icons: { ...outer.icons, ...p.icons } }),
|
|
62
|
+
}), [outer, p.icons, p.renderIconButton, p.theme]);
|
|
63
|
+
|
|
64
|
+
return <TableConfigContext.Provider value={merged}>{p.children}</TableConfigContext.Provider>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A chevron similar to typical icon-font arrows, but with no icon-font dependency. */
|
|
68
|
+
function chevron(points: string) {
|
|
69
|
+
return (
|
|
70
|
+
<svg className="dtbl-glyph-svg" viewBox="0 0 24 24" width="1.25em" height="1.25em"
|
|
71
|
+
aria-hidden="true" fill="none" stroke="currentColor" strokeWidth="2.2"
|
|
72
|
+
strokeLinecap="round" strokeLinejoin="round">
|
|
73
|
+
<polyline points={points}/>
|
|
74
|
+
</svg>);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const defaultIcons: Required<TableIcons> = {
|
|
78
|
+
sortAscending: chevron('6.5 14.5 12 9 17.5 14.5'),
|
|
79
|
+
sortDescending: chevron('6.5 9.5 12 15 17.5 9.5'),
|
|
80
|
+
expanded: chevron('6.5 9.5 12 15 17.5 9.5'),
|
|
81
|
+
collapsed: chevron('9.5 6.5 15 12 9.5 17.5'),
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
function defaultRenderIconButton(props: TableIconButtonProps) {
|
|
85
|
+
return <button type="button" className="dtbl-expander" {...props}/>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Returns the ambient `TableConfig` with all defaults filled in. */
|
|
89
|
+
export function useTableConfig(): { icons: Required<TableIcons> } & Required<Pick<TableConfigValue, 'renderIconButton'>> & Pick<TableConfigValue, 'theme'> {
|
|
90
|
+
const config = useContext(TableConfigContext);
|
|
91
|
+
return {
|
|
92
|
+
icons: { ...defaultIcons, ...config.icons },
|
|
93
|
+
renderIconButton: config.renderIconButton ?? defaultRenderIconButton,
|
|
94
|
+
theme: config.theme,
|
|
95
|
+
};
|
|
96
|
+
}
|
package/src/css.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
declare module '*.css';
|