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,180 @@
1
+ export class ListVirtualizer {
2
+ static isSupportedByBrowser() {
3
+ return typeof window !== 'undefined' && !!window.IntersectionObserver;
4
+ }
5
+ constructor(options) {
6
+ var _a, _b, _c;
7
+ this.visible = new Set();
8
+ this.nodeToKeys = new Map();
9
+ this.onIntersect = (entries) => {
10
+ let changed = false;
11
+ for (const entry of entries) {
12
+ if (!entry.isIntersecting) {
13
+ continue;
14
+ }
15
+ const keys = this.nodeToKeys.get(entry.target);
16
+ if (!keys) {
17
+ continue;
18
+ }
19
+ const maxToAdd = keys.length === 1 ? 1 : this.getChunkSize(entry);
20
+ let added = 0;
21
+ for (const key of keys) {
22
+ if (!this.visible.has(key)) {
23
+ this.visible.add(key);
24
+ changed = true;
25
+ added++;
26
+ if (added >= maxToAdd) {
27
+ break;
28
+ }
29
+ }
30
+ }
31
+ if (keys.length > 1 && added > 0) {
32
+ if (added >= keys.length) {
33
+ this.unobserve(entry.target);
34
+ }
35
+ else {
36
+ keys.splice(0, added);
37
+ }
38
+ }
39
+ }
40
+ if (changed) {
41
+ this.onVisibilityChange();
42
+ }
43
+ };
44
+ this.itemHeight = options.height;
45
+ this.containerRef = options.containerRef;
46
+ this.margin = (_a = options.margin) !== null && _a !== void 0 ? _a : 400;
47
+ this.onVisibilityChange = options.onVisibilityChange;
48
+ if (ListVirtualizer.isSupportedByBrowser()) {
49
+ this.observer = new IntersectionObserver(this.onIntersect, {
50
+ root: (_c = (_b = options.containerRef) === null || _b === void 0 ? void 0 : _b.current) !== null && _c !== void 0 ? _c : undefined,
51
+ rootMargin: this.margin + 'px 0px',
52
+ });
53
+ }
54
+ }
55
+ disconnect() {
56
+ var _a;
57
+ (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
58
+ this.nodeToKeys.clear();
59
+ }
60
+ createObserverRef(keys) {
61
+ if (!this.observer) {
62
+ return undefined;
63
+ }
64
+ const keyList = Array.isArray(keys) ? keys : [keys];
65
+ let lastElement = null;
66
+ return (element) => {
67
+ if (!this.observer) {
68
+ return;
69
+ }
70
+ if (lastElement) {
71
+ this.unobserve(lastElement);
72
+ }
73
+ if (element) {
74
+ this.observe(keyList, element);
75
+ }
76
+ lastElement = element;
77
+ };
78
+ }
79
+ buildPlan(items) {
80
+ const slots = [];
81
+ if (this.visible.size > items.length) {
82
+ const currentKeys = new Set(items.map(item => item.key));
83
+ for (const key of this.visible) {
84
+ if (!currentKeys.has(key)) {
85
+ this.visible.delete(key);
86
+ }
87
+ }
88
+ }
89
+ const fixedHeight = this.getDefaultRowHeight();
90
+ if (fixedHeight) {
91
+ this.markVisibleRange(items, fixedHeight);
92
+ }
93
+ let gapKeys = [];
94
+ let gapHeight = 0;
95
+ for (const item of items) {
96
+ const height = this.getItemHeight(item.item);
97
+ const canVirtualize = height != null && height > 0;
98
+ if (!canVirtualize || this.visible.has(item.key)) {
99
+ if (gapHeight > 0) {
100
+ slots.push(this.buildGap(gapKeys, gapHeight));
101
+ gapKeys = [];
102
+ gapHeight = 0;
103
+ }
104
+ slots.push({
105
+ real: true,
106
+ item: item.item,
107
+ key: item.key,
108
+ index: item.index,
109
+ reactKey: item.reactKey,
110
+ });
111
+ continue;
112
+ }
113
+ gapKeys.push(item.key);
114
+ gapHeight += height;
115
+ }
116
+ if (gapHeight > 0) {
117
+ slots.push(this.buildGap(gapKeys, gapHeight));
118
+ }
119
+ return slots;
120
+ }
121
+ buildGap(keys, height) {
122
+ const firstKey = keys[0];
123
+ const gapKey = `gap-${String(firstKey)}-${keys.length}`;
124
+ return { real: false, height, key: gapKey, keys };
125
+ }
126
+ getItemHeight(item) {
127
+ const height = typeof this.itemHeight === 'function'
128
+ ? this.itemHeight(item)
129
+ : this.itemHeight;
130
+ if (height === false) {
131
+ return undefined;
132
+ }
133
+ if (typeof height !== 'number' || !Number.isFinite(height) || height <= 0) {
134
+ return undefined;
135
+ }
136
+ return height;
137
+ }
138
+ observe(keys, element) {
139
+ if (!this.observer) {
140
+ return;
141
+ }
142
+ this.nodeToKeys.set(element, keys);
143
+ this.observer.observe(element);
144
+ }
145
+ unobserve(element) {
146
+ if (!this.observer) {
147
+ return;
148
+ }
149
+ this.nodeToKeys.delete(element);
150
+ this.observer.unobserve(element);
151
+ }
152
+ getChunkSize(entry) {
153
+ var _a, _b, _c, _d, _e, _f;
154
+ const rowHeight = (_a = this.getDefaultRowHeight()) !== null && _a !== void 0 ? _a : 50;
155
+ const rootHeight = (_f = (_c = (_b = entry.rootBounds) === null || _b === void 0 ? void 0 : _b.height) !== null && _c !== void 0 ? _c : (_e = (_d = this.containerRef) === null || _d === void 0 ? void 0 : _d.current) === null || _e === void 0 ? void 0 : _e.clientHeight) !== null && _f !== void 0 ? _f : 600;
156
+ const targetHeight = rootHeight + this.margin * 2;
157
+ return Math.max(1, Math.ceil(targetHeight / rowHeight));
158
+ }
159
+ getDefaultRowHeight() {
160
+ if (typeof this.itemHeight === 'number' && Number.isFinite(this.itemHeight) && this.itemHeight > 0) {
161
+ return this.itemHeight;
162
+ }
163
+ return undefined;
164
+ }
165
+ markVisibleRange(items, rowHeight) {
166
+ var _a, _b, _c;
167
+ const container = (_a = this.containerRef) === null || _a === void 0 ? void 0 : _a.current;
168
+ if (!container) {
169
+ return;
170
+ }
171
+ const margin = this.margin;
172
+ const scrollTop = (_b = container.scrollTop) !== null && _b !== void 0 ? _b : 0;
173
+ const viewportHeight = (_c = container.clientHeight) !== null && _c !== void 0 ? _c : 0;
174
+ const start = Math.max(0, Math.floor((scrollTop - margin) / rowHeight));
175
+ const end = Math.min(items.length, Math.ceil((scrollTop + viewportHeight + margin) / rowHeight));
176
+ for (let i = start; i < end; i++) {
177
+ this.visible.add(items[i].key);
178
+ }
179
+ }
180
+ }
@@ -0,0 +1,196 @@
1
+ import React from 'react';
2
+ import { ISet } from './interfaces.js';
3
+ import { ListCoreProps, ListItemProps } from './ListBox.js';
4
+ import { Styles } from './styles.js';
5
+ import { TableTheme } from './theme.js';
6
+ import { nully } from './util.js';
7
+ /** Each item in a TreeList or DataTable is wrapped in one of these objects.
8
+ * They are transient: new TreeItems are created during each render.
9
+ * The second type parameter is used by DataTable. */
10
+ export interface TreeItem<T, TRow = T> {
11
+ readonly item: TRow;
12
+ readonly children?: readonly TreeItem<T>[];
13
+ readonly parent?: TreeItem<T>;
14
+ readonly depth: number;
15
+ }
16
+ export interface TreeItemM<T> extends TreeItem<T> {
17
+ children?: TreeItemM<T>[];
18
+ item: T;
19
+ parent?: TreeItem<T>;
20
+ depth: number;
21
+ version?: number;
22
+ }
23
+ export type DefaultTreeItemProps = Styles & {
24
+ highlightChildrenOfSelectedParents?: boolean;
25
+ noPadding?: boolean | nully;
26
+ ref?: React.Ref<HTMLDivElement>;
27
+ };
28
+ /** Describes the items to display including parent-child relationships. You can either provide
29
+ * a `tree` directly, or a list with `getChildren` / `getParents` functions to describe these
30
+ * relationships. */
31
+ export type TreeListMainProps<T> = {
32
+ /** Provides a tree in the "native" format of `TreeListCore`/`TreeList`/`DataTable`.
33
+ *
34
+ * Note: `TreeListCore` assumes that all `parent` and `children` props are consistent with
35
+ * each other, e.g. that `tree[i].children[j].parent === tree[i]`. It will malfunction
36
+ * otherwise.
37
+ *
38
+ * Note: This is `TreeItemM` rather than `TreeItem` because `TreeListCore` (via
39
+ * `flattenToList`) will sort sublists mutably when there is no filter applied. */
40
+ tree: TreeItemM<T>[];
41
+ list?: undefined;
42
+ getChildren?: undefined;
43
+ getParents?: undefined;
44
+ isParent?: undefined;
45
+ } | {
46
+ tree?: undefined;
47
+ list: T[];
48
+ /** Gets the children of an item. It is useless to provide both a
49
+ * `getParents` and `getChildren` prop, as only one will be called. */
50
+ getChildren(item: T): T[] | undefined;
51
+ getParents?: undefined;
52
+ isParent?: undefined;
53
+ } | {
54
+ tree?: undefined;
55
+ /** List of items to display. If `getParents` is provided, then items with parents
56
+ * are not displayed at the root level (they are nested inside their parents);
57
+ * otherwise, all items in this list are displayed at the root level and there
58
+ * may be additional items (not in this list) nested inside them if `getChildren`
59
+ * returns items. */
60
+ list: T[];
61
+ getChildren?: undefined;
62
+ /** Gets the parents of an item (that is, the path to reach the item). The parents must
63
+ * be listed in order from root to child. This function is only called for items in the
64
+ * `list`, not for items returned by `getParents` itself.
65
+ *
66
+ * Example: `getParents={filename => getParentPathsOf(filename, '/', false)}`
67
+ **/
68
+ getParents?(item: T): T[] | undefined;
69
+ /** `getParents` by itself gives you no way to indicate that an item is a parent
70
+ * without children (e.g. an empty folder). If this function returns true, an item's
71
+ * expansion icon is displayed even when it has no children. This property is unused
72
+ * if you don't provide `getParents`. TODO: if `isParent` and `getChildren` are both
73
+ * provided, we shouldn't call `getChildren()` for unexpanded nodes. In fact, right
74
+ * now all unexpanded nodes are retrieved recursively which is wasteful. */
75
+ isParent?(item: T): boolean;
76
+ };
77
+ /** The rest of `TreeListCoreProps`. */
78
+ export interface TreeListAuxProps<T, K = T, ItemProps = DefaultTreeItemProps> extends Omit<ListCoreProps<T, K, ItemProps>, 'renderItem' | 'RenderItem' | 'onClickItem' | 'filter' | 'itemProps' | 'list'>, Styles {
79
+ /** The set of nodes that are currently expanded. If provided, this should be a
80
+ * MobX `observable.set` rather than a plain Set<K>. */
81
+ expandedParents?: ISet<K>;
82
+ /** Called to render a T value. */
83
+ renderItem?(item: TreeItem<T>, props: ListItemProps<TreeItem<T>, K, ItemProps>): React.ReactNode;
84
+ /** Component type used to render the entire row (including an outer `div` or `tr`). */
85
+ RenderItem?: React.ComponentType<TreeItemProps<T, K, ItemProps>>;
86
+ /** Called to render the indentation and tree expander button. It will return an
87
+ * element with `display: inline-block` and with a width that varies according to the
88
+ * appropriate amount of indentation. Note: this should usually be placed inside
89
+ * a flex row (`display: flex`) so that word-wrapping of the label after the indent
90
+ * looks right. */
91
+ renderTreeIndent?(this: TreeItemProps<T, K, ItemProps>): React.ReactNode;
92
+ /** This is called immediately when an item is clicked, and if it returns
93
+ 'abort' the click on the item will be ignored (rather than selecting the item) */
94
+ onClickItem?(this: ModifiedTreeItemProps<T, K, ItemProps>, item: TreeItem<T>): void | 'abort' | Promise<void | 'abort'>;
95
+ /** This is called for each item, if you provide it. Items for which this function
96
+ * returns false are hidden. */
97
+ filter?(item: TreeItem<T>, index: number): boolean;
98
+ /** This prop is ignored if `sort` is provided. Otherwise, if provided, this is used
99
+ * after filtering to sort only the visible items.
100
+ *
101
+ * Note: rows are sorted level-by-level. For example, given this tree of items:
102
+ *
103
+ * Clothes
104
+ * Shirt
105
+ * Pants
106
+ * Shorts
107
+ * Toys
108
+ * Dolls
109
+ * Cars
110
+ *
111
+ * The three sublists [Clothes, Toys], [Shirt, Pants, Shorts], and [Dolls, Cars] are
112
+ * sorted separately, as one would expect.
113
+ **/
114
+ sortComparer?(a: TreeItem<T>, b: TreeItem<T>): number;
115
+ /** If provided, this is called after filtering to sort visible items at each level of
116
+ * the tree.
117
+ *
118
+ * Note: when `sort` or `sortComparer` is used in `DataTable` or `DataTableCore`, they
119
+ * stop being used to sort if the user sorts by clicking a column header, or if the
120
+ * `DataTableCoreProps.columnsToSortBy` prop is provided. However, these props still
121
+ * control the default sort order. When a table has a default sort order, the user can
122
+ * click the same column header three times to cancel user-defined sorting and return
123
+ * to the default sort order.
124
+ **/
125
+ sort?(list: TreeItemM<T>[]): void;
126
+ /** props that should apply to each item (usually Styles: `className` and `style`).
127
+ * If `RenderItem` is provided, these props are forwarded to it. In a `<DataTable>`,
128
+ * any styles in this object are applied to the row as a whole, not to each cell. */
129
+ itemProps?: ItemProps | ((item: TreeItem<T>) => ItemProps | undefined);
130
+ /** Number of pixels to indent per level of nesting (default: the theme's `treeIndent`,
131
+ * i.e. the --dtbl-indent CSS variable, which itself defaults to 20) */
132
+ indentPerLevel?: number;
133
+ }
134
+ /** Main properties of a `<TreeList>` or `<TreeListCore>`. The only required prop is `list`
135
+ * (or `tree`), but it's recommended to also provide `getKey` to identify items to React. */
136
+ export type TreeListCoreProps<T, K = T, ItemProps = DefaultTreeItemProps> = TreeListMainProps<T> & TreeListAuxProps<T, K, ItemProps>;
137
+ /** Omit/modify certain prop(s) so that `<DataTable>` type checks when it uses `renderTreeIndent`
138
+ * and so that `TreeListCore` type checks when it passes `onClickItem` to `ListCore`. */
139
+ export type ModifiedTreeItemProps<T, K, ItemProps> = Omit<ListItemProps<TreeItem<T>, K, ItemProps>, 'renderItem'> & Partial<TreeItemProps<T, K, ItemProps>>;
140
+ /** Props passed to renderers (`TreeListProps<...>.renderItem` and `RenderItem`). */
141
+ export interface TreeItemProps<T, K = T, ItemProps = Styles> extends ListItemProps<TreeItem<T>, K, ItemProps> {
142
+ /** The set of nodes that are currently expanded. If provided, this should be a
143
+ * MobX `observable.set` rather than a plain Set<K>. */
144
+ expandedParents: ISet<K>;
145
+ /** Whether `expandedParents` includes `selKey` */
146
+ isExpanded: boolean;
147
+ /** Renders the indentation and tree expander button. */
148
+ renderTreeIndent(this: ModifiedTreeItemProps<T, K, ItemProps>): React.ReactNode;
149
+ /** Expands or collapses this item. */
150
+ toggleExpanded(this: ModifiedTreeItemProps<T, K, ItemProps>): void;
151
+ /** Props that were passed to the parent `TreeListCore` or `DataTableCore` */
152
+ parentProps: TreeListCoreProps<T, K, ItemProps>;
153
+ }
154
+ /** A combined list and tree component that allows items to be nested inside each other,
155
+ * and allows parent nodes to be expanded or collapsed. Inherits selection and
156
+ * multiselect functionality from ListCore. It is the same as `TreeList` except that
157
+ * the list contents are not wrapped in any parent element.
158
+ *
159
+ * Example: In this tree, the child of each number is the square of the number.
160
+ * Note that `1` cannot be in the list, because all children are recursively enumerated
161
+ * when the list is displayed, so if 1 is in the list, the `TreeListCore` will crash.
162
+ * Also note that selecting `4` at the root level will also implicitly select the child
163
+ * of `2` because it is also `4`; the component is not designed for duplicate items and
164
+ * so there may be glitches.
165
+ *
166
+ * <TreeListCore
167
+ * list={[ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]}
168
+ * getChildren={x => x < 10 ? [x * x] : []}
169
+ * renderItem={node => `The number ${node.item}`}
170
+ * />
171
+ **/
172
+ export declare const TreeListCore: <T, K = T, ItemProps extends Styles = DefaultTreeItemProps>(p: TreeListCoreProps<T, K, ItemProps>) => React.JSX.Element;
173
+ export type TreeListProps<T, K = T, ItemProps = Styles> = TreeListCoreProps<T, K, ItemProps> & Styles & {
174
+ /** Theme for this tree; overrides the ambient `TableConfig` theme. */
175
+ theme?: TableTheme | string | nully;
176
+ };
177
+ /** A combined list and tree component that allows items to be nested inside each other,
178
+ * and allows parent nodes to be expanded or collapsed. Inherits selection and
179
+ * multiselect functionality from ListCore. This is the same as `TreeListCore` except
180
+ * that the list contents are wrapped in a scrollable div (and thus, only TreeList
181
+ * supports `style` and `className`.) */
182
+ export declare function TreeList<T, K = T, ItemProps extends Styles = DefaultTreeItemProps>(p: TreeListProps<T, K, ItemProps>): React.JSX.Element;
183
+ export declare function renderTreeIndent<T>(this: TreeItemProps<T, any, any>): React.JSX.Element;
184
+ export declare function DefaultRenderItem<T, K, ItemProps extends DefaultTreeItemProps>(p: TreeItemProps<T, K, ItemProps>): React.JSX.Element;
185
+ export declare function getSelectionClass<T, K, ItemProps>(p: Pick<TreeItemProps<T, K, ItemProps>, 'item' | 'isSelected' | 'tempState' | 'itemProps'>): 'selected' | 'unselected' | 'parentSelected';
186
+ /** Converts a list of items to a tree using a user-defined `getParents` function. */
187
+ export declare function getDataAsTree1<T, K = T>(items: Iterable<T>, getParents: (item: T) => T[] | undefined, getSelKey?: (item: T) => K, isParent?: (item: T) => boolean): TreeItemM<T>[];
188
+ /** Converts a list of items to a tree using a user-defined `getChildren` function.
189
+ *
190
+ * TODO: optimize the design so that it is not necessary to call getChildren() on
191
+ * non-expanded nodes. */
192
+ export declare function getDataAsTree2<T>(items: Iterable<T>, getChildren: (item: T) => T[] | undefined, parent?: TreeItem<T>, depth?: number): TreeItemM<T>[];
193
+ /** This helper function returns a list of parent paths of a path. For example,
194
+ * `getParentPathsOf('C:\\Windows\\System')` returns `['C:', 'C:\\Windows']`.
195
+ * Note: `getParentPathsOf('')` returns [] even if `includeSelf` is true. **/
196
+ export declare function getParentPathsOf(path: string | nully, separator?: string, includeSelf?: boolean): string[];
@@ -0,0 +1,300 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useMemo, useRef } from 'react';
3
+ import { useTableConfig } from './config.js';
4
+ import { useStatefulObjectIfNotGivenBy } from './hooks.js';
5
+ import { defaultRenderItem as defaultRenderItem_, ListCore, useListCoreStyles } from './ListBox.js';
6
+ import { asAction, getReactivityAdapter, reactive, useWatched } from './reactivity.js';
7
+ import { classAndStyle } from './styles.js';
8
+ import { useThemeProps } from './theme.js';
9
+ import { cx, mapMap, toggleSetMembership } from './util.js';
10
+ /** A combined list and tree component that allows items to be nested inside each other,
11
+ * and allows parent nodes to be expanded or collapsed. Inherits selection and
12
+ * multiselect functionality from ListCore. It is the same as `TreeList` except that
13
+ * the list contents are not wrapped in any parent element.
14
+ *
15
+ * Example: In this tree, the child of each number is the square of the number.
16
+ * Note that `1` cannot be in the list, because all children are recursively enumerated
17
+ * when the list is displayed, so if 1 is in the list, the `TreeListCore` will crash.
18
+ * Also note that selecting `4` at the root level will also implicitly select the child
19
+ * of `2` because it is also `4`; the component is not designed for duplicate items and
20
+ * so there may be glitches.
21
+ *
22
+ * <TreeListCore
23
+ * list={[ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]}
24
+ * getChildren={x => x < 10 ? [x * x] : []}
25
+ * renderItem={node => `The number ${node.item}`}
26
+ * />
27
+ **/
28
+ export const TreeListCore = reactive(function TreeListCore(p) {
29
+ var _a, _b, _c, _d, _e;
30
+ const expandedParents = useWatched(useStatefulObjectIfNotGivenBy(p.expandedParents, () => getReactivityAdapter().observableSet()));
31
+ const RenderItem = (_a = p.RenderItem) !== null && _a !== void 0 ? _a : DefaultRenderItem;
32
+ const renderTreeIndent_ = (_b = p.renderTreeIndent) !== null && _b !== void 0 ? _b : renderTreeIndent;
33
+ const getSelKey = p.getSelKey
34
+ ? ((item) => p.getSelKey(item.item))
35
+ : ((item) => item.item);
36
+ // TODO: React components are not supposed to contain nested components because they
37
+ // are recreated on every render, which confuses React into unmounting and remounting
38
+ // them, which causes the state of not just the nested component, but all other
39
+ // components it contains, to be forgotten and reset. By using `useMemo` we can avoid
40
+ // this problem in most cases, but ideally we should solve it in all cases.
41
+ const RenderBaseItem = useMemo(() =>
42
+ // `observer` is needed so the arrow re-renders when `expandedParents`
43
+ // changes. It's a closure variable, not a prop, so React.memo can't detect the change.
44
+ getReactivityAdapter().observer(function RenderBaseItem(props) {
45
+ return (_jsx(RenderItem, Object.assign({}, props, { expandedParents: expandedParents, renderTreeIndent: renderTreeIndent_, isExpanded: expandedParents.has(props.selKey), toggleExpanded: asAction(toggleExpanded), parentProps: p })));
46
+ }), [expandedParents, renderTreeIndent_, RenderItem]);
47
+ let tree;
48
+ if (p.getParents) {
49
+ tree = getDataAsTree1(p.list, p.getParents, p.getSelKey, p.isParent);
50
+ }
51
+ else if (p.list) {
52
+ const getChildren = (_c = p.getChildren) !== null && _c !== void 0 ? _c : ((item) => undefined);
53
+ tree = getDataAsTree2(p.list, getChildren);
54
+ }
55
+ else {
56
+ tree = (_d = p.tree) !== null && _d !== void 0 ? _d : [];
57
+ }
58
+ // We want to avoid re-rendering rows that haven't changed. To convince React to do that,
59
+ // we need to use the same wrapper `TreeItem` for each item that hasn't changed.
60
+ // To accomplish that, use a cache.
61
+ useCachedItems(tree, getSelKey);
62
+ let list = flattenToList(tree, expandedParents, p);
63
+ const listVirtualize = p.virtualize && Object.assign(Object.assign({}, p.virtualize), { height: typeof p.virtualize.height === 'function'
64
+ ? (item) => p.virtualize.height(item.item)
65
+ : p.virtualize.height });
66
+ return (_jsx(ListCore, { list: list, selection: p.selection, selMode: p.selMode, renderItem: (_e = p.renderItem) !== null && _e !== void 0 ? _e : defaultRenderItem, RenderItem: RenderBaseItem, onClickItem: p.onClickItem, getKey: p.getKey
67
+ ? (item => p.getKey(item.item))
68
+ : undefined, getSelKey: getSelKey, lastClicked: p.lastClicked, itemProps: p.itemProps, readOnly: p.readOnly, virtualize: listVirtualize, virtualGapRenderer: p.virtualGapRenderer, placeholder: p.placeholder }));
69
+ function toggleExpanded() {
70
+ toggleSetMembership(this.expandedParents, this.selKey);
71
+ }
72
+ });
73
+ /** Replaces items in `tree` with previously cached items from a cache, while storing new items
74
+ * in the cache and removing stale items. */
75
+ function useCachedItems(tree, getSelKey) {
76
+ const nodeCache = useRef(new Map());
77
+ const version = ++useRef(0).current;
78
+ recursivelyUseCachedItems(tree, getSelKey, nodeCache.current, version);
79
+ // prune stale cache entries
80
+ for (const [key, node] of nodeCache.current) {
81
+ if (node.version !== version)
82
+ nodeCache.current.delete(key);
83
+ }
84
+ }
85
+ function recursivelyUseCachedItems(tree, getSelKey, cache, version, parent) {
86
+ for (let i = 0; i < tree.length; i++) {
87
+ const node = tree[i];
88
+ const key = getSelKey(node);
89
+ let cachedNode = cache.get(key);
90
+ // Avoid sharing the same wrapper for duplicate keys in a single render
91
+ if (cachedNode && cachedNode.version !== version) {
92
+ cachedNode.item = node.item;
93
+ cachedNode.parent = parent;
94
+ cachedNode.depth = node.depth;
95
+ cachedNode.children = node.children &&
96
+ recursivelyUseCachedItems(node.children, getSelKey, cache, version, cachedNode);
97
+ cachedNode.version = version;
98
+ tree[i] = cachedNode;
99
+ }
100
+ else {
101
+ node.version = version;
102
+ cache.set(key, node);
103
+ }
104
+ }
105
+ return tree;
106
+ }
107
+ /** A combined list and tree component that allows items to be nested inside each other,
108
+ * and allows parent nodes to be expanded or collapsed. Inherits selection and
109
+ * multiselect functionality from ListCore. This is the same as `TreeListCore` except
110
+ * that the list contents are wrapped in a scrollable div (and thus, only TreeList
111
+ * supports `style` and `className`.) */
112
+ export function TreeList(p) {
113
+ const theme = useThemeProps(p.theme);
114
+ return (_jsx("div", Object.assign({ tabIndex: 0 }, classAndStyle(p, theme.className, Object.assign({ overflowY: 'scroll' }, theme.style)), { children: _jsx(TreeListCore, Object.assign({}, p)) })));
115
+ }
116
+ export function renderTreeIndent() {
117
+ // The indent comes from the `indentPerLevel` prop, or else the theme (see TableMetrics)
118
+ const ipl = this.parentProps.indentPerLevel;
119
+ const indent = ipl != null ? `${ipl}px` : 'var(--dtbl-indent, 20px)';
120
+ const expanderWidth = `calc(12px + ${indent})`;
121
+ return (_jsx("div", { style: { display: 'inline-block',
122
+ marginLeft: this.item.depth === 0 ? 0 : `calc(${indent} * ${this.item.depth})`,
123
+ minWidth: expanderWidth }, children: this.item.children == null ? undefined :
124
+ _jsx(TreeExpanderButton, { width: expanderWidth, isExpanded: this.isExpanded, toggleExpanded: () => this.toggleExpanded() }) }));
125
+ }
126
+ /** The expand/collapse button in tree cells. The button itself comes from
127
+ * `TableConfig.renderIconButton` and the icons from `TableConfig.icons`. */
128
+ function TreeExpanderButton(p) {
129
+ const { icons, renderIconButton } = useTableConfig();
130
+ return renderIconButton({
131
+ onClick: e => { p.toggleExpanded(); e.stopPropagation(); },
132
+ style: { width: p.width },
133
+ 'aria-label': p.isExpanded ? 'Collapse' : 'Expand',
134
+ children: p.isExpanded ? icons.expanded : icons.collapsed,
135
+ });
136
+ }
137
+ function defaultRenderItem(node, props) {
138
+ return defaultRenderItem_(node.item);
139
+ }
140
+ export function DefaultRenderItem(p) {
141
+ var _a, _b, _c, _d, _e, _f, _g;
142
+ var _h;
143
+ const styles = useListCoreStyles();
144
+ let treeIndent = p.renderTreeIndent();
145
+ let className = styles[getSelectionClass(p)];
146
+ if (!((_a = p.itemProps) === null || _a === void 0 ? void 0 : _a.noPadding))
147
+ className = cx(className, styles.padding);
148
+ let styling = classAndStyle(p.itemProps, className, { display: 'flex', alignItems: 'center' });
149
+ const { ref: itemRef } = ((_b = p.itemProps) !== null && _b !== void 0 ? _b : {});
150
+ let rendered = ((_c = p.renderItem) !== null && _c !== void 0 ? _c : defaultRenderItem)(p.item, p);
151
+ let wrapped = (_jsxs("div", Object.assign({ ref: itemRef, onClick: e => p.onClick(p.item, e) }, styling, { children: [treeIndent, rendered] })));
152
+ if (p.readOnly) {
153
+ // Put a filter on top that grays out the contents of the row
154
+ wrapped = _jsxs("div", { style: { position: 'relative' }, children: [wrapped, _jsx("div", { className: styles.readOnlyWrapper })] });
155
+ }
156
+ // Add `p.item` to `selectedParents` where applicable. This relies on parents being
157
+ // rendered before their children. (An alternate way we could've done this is to
158
+ // precompute an “hasSelectedAncestor” flag during flatten, stored in each tree item.
159
+ // that could avoid the need for ListCore to know about `selectedParents`.)
160
+ if ((_d = p.item.children) === null || _d === void 0 ? void 0 : _d.length) {
161
+ if (p.isSelected || ((_e = p.tempState.selectedParents) === null || _e === void 0 ? void 0 : _e.has(p.item.parent))) {
162
+ // Use WeakSet so that selected items removed from the tree can be GC'd
163
+ ((_f = (_h = p.tempState).selectedParents) !== null && _f !== void 0 ? _f : (_h.selectedParents = new WeakSet())).add(p.item);
164
+ }
165
+ else {
166
+ // `selectedParents` is preserved between renders; delete stale items
167
+ (_g = p.tempState.selectedParents) === null || _g === void 0 ? void 0 : _g.delete(p.item);
168
+ }
169
+ }
170
+ return wrapped;
171
+ }
172
+ export function getSelectionClass(p) {
173
+ var _a, _b, _c, _d, _e, _f;
174
+ var _g;
175
+ if (((_a = p.item.children) === null || _a === void 0 ? void 0 : _a.length) &&
176
+ (p.isSelected || ((_b = p.tempState.selectedParents) === null || _b === void 0 ? void 0 : _b.has(p.item.parent)))) {
177
+ (_c = (_g = p.tempState).selectedParents) !== null && _c !== void 0 ? _c : (_g.selectedParents = new Set());
178
+ p.tempState.selectedParents.add(p.item);
179
+ }
180
+ if (p.isSelected)
181
+ return 'selected';
182
+ else if (((_e = (_d = p.itemProps) === null || _d === void 0 ? void 0 : _d.highlightChildrenOfSelectedParents) !== null && _e !== void 0 ? _e : true)
183
+ && ((_f = p.tempState.selectedParents) === null || _f === void 0 ? void 0 : _f.has(p.item.parent)))
184
+ return 'parentSelected';
185
+ else
186
+ return 'unselected';
187
+ }
188
+ /** Converts a list of items to a tree using a user-defined `getParents` function. */
189
+ export function getDataAsTree1(items, getParents, getSelKey = (item) => item, isParent) {
190
+ const map = new Map();
191
+ // Convert the items array into a tree structure in `map`
192
+ for (let item of items) {
193
+ // Get the parents of the item
194
+ let key = getSelKey(item);
195
+ let parents = getParents(item);
196
+ let submap = map;
197
+ if (parents) {
198
+ let subtree;
199
+ for (let i = 0; i < parents.length; i++) {
200
+ subtree = getOrMakeSubmap(submap, parents[i], getSelKey);
201
+ submap = subtree.children;
202
+ }
203
+ }
204
+ if (!submap.has(key)) {
205
+ submap.set(key, { item });
206
+ }
207
+ }
208
+ return convertTreeToArrayForm(map, isParent);
209
+ }
210
+ function getOrMakeSubmap(map, item, getSelKey) {
211
+ var _a;
212
+ let key = getSelKey ? getSelKey(item) : item;
213
+ let subtree = map.get(key);
214
+ if (!subtree)
215
+ map.set(key, subtree = { item });
216
+ (_a = subtree.children) !== null && _a !== void 0 ? _a : (subtree.children = new Map());
217
+ return subtree;
218
+ }
219
+ function convertTreeToArrayForm(map, isParent, parent, depth = 0) {
220
+ return mapMap(map, (key, treeItem) => {
221
+ var _a;
222
+ let item = {
223
+ item: treeItem.item,
224
+ parent,
225
+ depth,
226
+ };
227
+ if ((_a = treeItem.children) === null || _a === void 0 ? void 0 : _a.size) {
228
+ item.children = convertTreeToArrayForm(treeItem.children, isParent, item, depth + 1);
229
+ }
230
+ else if (isParent && isParent(treeItem.item)) {
231
+ item.children = [];
232
+ }
233
+ return item;
234
+ });
235
+ }
236
+ /** Converts a list of items to a tree using a user-defined `getChildren` function.
237
+ *
238
+ * TODO: optimize the design so that it is not necessary to call getChildren() on
239
+ * non-expanded nodes. */
240
+ export function getDataAsTree2(items, getChildren, parent, depth = 0) {
241
+ const result = [];
242
+ for (let item of items) {
243
+ let treeItem = {
244
+ item,
245
+ parent,
246
+ depth,
247
+ };
248
+ let children = getChildren(item);
249
+ if (children) {
250
+ treeItem.children = getDataAsTree2(children, getChildren, treeItem, depth + 1);
251
+ }
252
+ result.push(treeItem);
253
+ }
254
+ return result;
255
+ }
256
+ function flattenToList(tree_, expandedParents, p, results = []) {
257
+ let { filter, getSelKey, sort } = p;
258
+ // Apply filtering before sorting
259
+ let tree = tree_;
260
+ if (filter) {
261
+ tree = [];
262
+ for (let i = 0; i < tree_.length; i++) {
263
+ if (filter(tree_[i], i))
264
+ tree.push(tree_[i]);
265
+ }
266
+ }
267
+ if (sort) {
268
+ sort(tree);
269
+ }
270
+ else if (p.sortComparer) {
271
+ tree.sort(p.sortComparer);
272
+ }
273
+ // Copy items and expanded children to results list
274
+ for (let i = 0; i < tree.length; i++) {
275
+ const item = tree[i];
276
+ results.push(item);
277
+ const key = getSelKey ? getSelKey(item.item) : item.item;
278
+ if (item.children && expandedParents.has(key)) {
279
+ flattenToList(item.children, expandedParents, p, results);
280
+ }
281
+ }
282
+ return results;
283
+ }
284
+ /** This helper function returns a list of parent paths of a path. For example,
285
+ * `getParentPathsOf('C:\\Windows\\System')` returns `['C:', 'C:\\Windows']`.
286
+ * Note: `getParentPathsOf('')` returns [] even if `includeSelf` is true. **/
287
+ export function getParentPathsOf(path, separator = '\\', includeSelf = false) {
288
+ let parents = [];
289
+ if (path) {
290
+ for (let i = 1; i < path.length; i++) {
291
+ if (path[i] === separator) {
292
+ parents.push(path.slice(0, i));
293
+ }
294
+ }
295
+ if (includeSelf) {
296
+ parents.push(path);
297
+ }
298
+ }
299
+ return parents;
300
+ }