@snack-uikit/tree 0.10.3 → 0.11.1-preview-c3fee040.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/CHANGELOG.md +11 -0
- package/README.md +121 -0
- package/dist/cjs/helpers/__tests__/collectEmptyNestedNodesInExpanded.spec.d.ts +1 -0
- package/dist/cjs/helpers/__tests__/collectEmptyNestedNodesInExpanded.spec.js +80 -0
- package/dist/cjs/helpers/__tests__/setChildrenOfTreeNode.spec.d.ts +1 -0
- package/dist/cjs/helpers/__tests__/setChildrenOfTreeNode.spec.js +102 -0
- package/dist/cjs/helpers/collectEmptyNestedNodesInExpanded.d.ts +2 -0
- package/dist/cjs/helpers/collectEmptyNestedNodesInExpanded.js +17 -0
- package/dist/cjs/helpers/index.d.ts +2 -0
- package/dist/cjs/helpers/index.js +3 -1
- package/dist/cjs/helpers/setChildrenOfTreeNode.d.ts +2 -0
- package/dist/cjs/helpers/setChildrenOfTreeNode.js +28 -0
- package/dist/cjs/helpers/sortTreeItemsByTitle.js +2 -2
- package/dist/cjs/helpers/traverse.d.ts +7 -1
- package/dist/cjs/helpers/traverse.js +38 -2
- package/dist/cjs/hooks/__tests__/useSearchableTree.spec.d.ts +1 -0
- package/dist/cjs/hooks/__tests__/useSearchableTree.spec.js +230 -0
- package/dist/cjs/hooks/__tests__/useTreeMultiSelection.spec.d.ts +1 -0
- package/dist/cjs/hooks/__tests__/useTreeMultiSelection.spec.js +225 -0
- package/dist/cjs/hooks/index.d.ts +2 -0
- package/dist/cjs/hooks/index.js +26 -0
- package/dist/cjs/hooks/useSearchableTree.d.ts +28 -0
- package/dist/cjs/hooks/useSearchableTree.js +147 -0
- package/dist/cjs/hooks/useTreeMultiSelection.d.ts +12 -0
- package/dist/cjs/hooks/useTreeMultiSelection.js +82 -0
- package/dist/cjs/index.d.ts +2 -1
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/types.d.ts +17 -0
- package/dist/esm/helpers/__tests__/collectEmptyNestedNodesInExpanded.spec.d.ts +1 -0
- package/dist/esm/helpers/__tests__/collectEmptyNestedNodesInExpanded.spec.js +64 -0
- package/dist/esm/helpers/__tests__/setChildrenOfTreeNode.spec.d.ts +1 -0
- package/dist/esm/helpers/__tests__/setChildrenOfTreeNode.spec.js +50 -0
- package/dist/esm/helpers/collectEmptyNestedNodesInExpanded.d.ts +2 -0
- package/dist/esm/helpers/collectEmptyNestedNodesInExpanded.js +11 -0
- package/dist/esm/helpers/index.d.ts +2 -0
- package/dist/esm/helpers/index.js +2 -0
- package/dist/esm/helpers/setChildrenOfTreeNode.d.ts +2 -0
- package/dist/esm/helpers/setChildrenOfTreeNode.js +20 -0
- package/dist/esm/helpers/sortTreeItemsByTitle.js +2 -2
- package/dist/esm/helpers/traverse.d.ts +7 -1
- package/dist/esm/helpers/traverse.js +24 -0
- package/dist/esm/hooks/__tests__/useSearchableTree.spec.d.ts +1 -0
- package/dist/esm/hooks/__tests__/useSearchableTree.spec.js +165 -0
- package/dist/esm/hooks/__tests__/useTreeMultiSelection.spec.d.ts +1 -0
- package/dist/esm/hooks/__tests__/useTreeMultiSelection.spec.js +130 -0
- package/dist/esm/hooks/index.d.ts +2 -0
- package/dist/esm/hooks/index.js +2 -0
- package/dist/esm/hooks/useSearchableTree.d.ts +28 -0
- package/dist/esm/hooks/useSearchableTree.js +108 -0
- package/dist/esm/hooks/useTreeMultiSelection.d.ts +12 -0
- package/dist/esm/hooks/useTreeMultiSelection.js +43 -0
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.js +1 -0
- package/dist/esm/types.d.ts +17 -0
- package/package.json +22 -4
- package/src/helpers/__tests__/collectEmptyNestedNodesInExpanded.spec.ts +88 -0
- package/src/helpers/__tests__/setChildrenOfTreeNode.spec.ts +68 -0
- package/src/helpers/collectEmptyNestedNodesInExpanded.ts +16 -0
- package/src/helpers/index.ts +2 -0
- package/src/helpers/setChildrenOfTreeNode.ts +30 -0
- package/src/helpers/sortTreeItemsByTitle.ts +2 -2
- package/src/helpers/traverse.ts +38 -1
- package/src/hooks/__tests__/useSearchableTree.spec.ts +200 -0
- package/src/hooks/__tests__/useTreeMultiSelection.spec.ts +165 -0
- package/src/hooks/index.ts +2 -0
- package/src/hooks/useSearchableTree.ts +163 -0
- package/src/hooks/useTreeMultiSelection.ts +61 -0
- package/src/index.ts +2 -1
- package/src/types.ts +15 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { SearchableTreeDataLoadResult, TreeNodeProps } from '../types';
|
|
2
|
+
export type SearchResult<TTreeNode extends TreeNodeProps> = {
|
|
3
|
+
tree: TTreeNode[];
|
|
4
|
+
needPreloadNodes: string[];
|
|
5
|
+
};
|
|
6
|
+
export type SearchParams = {
|
|
7
|
+
search: string;
|
|
8
|
+
};
|
|
9
|
+
type UseSearchableTreeParams<TRecordValue, TTreeNode extends TreeNodeProps> = {
|
|
10
|
+
initTree: TTreeNode[];
|
|
11
|
+
onPreloadNode: (node: TreeNodeProps) => Promise<TTreeNode[]>;
|
|
12
|
+
onPreloadNodes: (nodes: string[], signal?: AbortSignal) => Promise<Record<string, TTreeNode[]>>;
|
|
13
|
+
onSearch: (params: SearchParams, signal?: AbortSignal) => Promise<SearchResult<TTreeNode>>;
|
|
14
|
+
mapNodeToRecordItem: (node: TTreeNode) => TRecordValue;
|
|
15
|
+
};
|
|
16
|
+
export declare function useSearchableTree<TRecordValue, TTreeNode extends TreeNodeProps>({ initTree, onPreloadNode, onPreloadNodes, onSearch, mapNodeToRecordItem, }: UseSearchableTreeParams<TRecordValue, TTreeNode>): {
|
|
17
|
+
tree: import("@siberiacancode/reactuse").StateRef<TTreeNode[]>;
|
|
18
|
+
expandedNodes: import("@siberiacancode/reactuse").StateRef<string[]>;
|
|
19
|
+
loading: boolean;
|
|
20
|
+
treeItemsRecord: import("@siberiacancode/reactuse").StateRef<Record<string, TRecordValue>>;
|
|
21
|
+
search: {
|
|
22
|
+
value: string;
|
|
23
|
+
onChange: import("react").Dispatch<import("react").SetStateAction<string>>;
|
|
24
|
+
};
|
|
25
|
+
onExpand: (nodes: string[]) => void;
|
|
26
|
+
onDataLoad: (node: TreeNodeProps) => Promise<SearchableTreeDataLoadResult<TTreeNode, TRecordValue>>;
|
|
27
|
+
};
|
|
28
|
+
export {};
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { useDebounceValue, useDidUpdate, useRefState } from '@siberiacancode/reactuse';
|
|
11
|
+
import { cancelable } from 'cancelable-promise';
|
|
12
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
13
|
+
import { collectEmptyNestedNodesInExpanded, setChildrenOfTreeNode, traverse } from '../helpers';
|
|
14
|
+
export function useSearchableTree({ initTree, onPreloadNode, onPreloadNodes, onSearch, mapNodeToRecordItem, }) {
|
|
15
|
+
const tree = useRefState(initTree);
|
|
16
|
+
const treeItemsRecord = useRefState({});
|
|
17
|
+
const expandedNodes = useRefState([]);
|
|
18
|
+
const [search, setSearch] = useState('');
|
|
19
|
+
const debouncedSearch = useDebounceValue(search, 500);
|
|
20
|
+
const [loading, setLoading] = useState(false);
|
|
21
|
+
const searchPromiseRef = useRef(null);
|
|
22
|
+
const searchAbortControllerRef = useRef(null);
|
|
23
|
+
const buildTreeItemsRecord = useCallback((nodes) => {
|
|
24
|
+
const record = {};
|
|
25
|
+
traverse(nodes, node => {
|
|
26
|
+
record[node.id] = mapNodeToRecordItem(node);
|
|
27
|
+
});
|
|
28
|
+
return record;
|
|
29
|
+
}, [mapNodeToRecordItem]);
|
|
30
|
+
const onExpand = useCallback((nodes) => {
|
|
31
|
+
expandedNodes.current = nodes;
|
|
32
|
+
}, [expandedNodes]);
|
|
33
|
+
const onDataLoad = useCallback((node) => __awaiter(this, void 0, void 0, function* () {
|
|
34
|
+
const preloadedChildren = yield onPreloadNode(node);
|
|
35
|
+
const updatedTree = setChildrenOfTreeNode(tree.current, node.id, preloadedChildren);
|
|
36
|
+
tree.current = updatedTree;
|
|
37
|
+
const newTreeItemsRecord = Object.assign({}, treeItemsRecord.current);
|
|
38
|
+
traverse(preloadedChildren, child => {
|
|
39
|
+
newTreeItemsRecord[child.id] = mapNodeToRecordItem(child);
|
|
40
|
+
});
|
|
41
|
+
treeItemsRecord.current = newTreeItemsRecord;
|
|
42
|
+
return { preloadedChildren, updatedTree, newTreeItemsRecord };
|
|
43
|
+
}), [mapNodeToRecordItem, onPreloadNode, tree, treeItemsRecord]);
|
|
44
|
+
const handleSearch = useCallback((searchQuery) => __awaiter(this, void 0, void 0, function* () {
|
|
45
|
+
var _a, _b;
|
|
46
|
+
(_a = searchPromiseRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
|
|
47
|
+
(_b = searchAbortControllerRef.current) === null || _b === void 0 ? void 0 : _b.abort();
|
|
48
|
+
setLoading(true);
|
|
49
|
+
const abortController = new AbortController();
|
|
50
|
+
searchAbortControllerRef.current = abortController;
|
|
51
|
+
const searchPromise = cancelable(onSearch({ search: searchQuery }, abortController.signal));
|
|
52
|
+
searchPromiseRef.current = searchPromise;
|
|
53
|
+
try {
|
|
54
|
+
const { tree: searchedTree, needPreloadNodes } = yield searchPromise;
|
|
55
|
+
if (!searchPromise.isCanceled()) {
|
|
56
|
+
tree.current = searchedTree;
|
|
57
|
+
treeItemsRecord.current = buildTreeItemsRecord(searchedTree);
|
|
58
|
+
const expandedSet = new Set(expandedNodes.current);
|
|
59
|
+
const toPreloadExpandableNodes = collectEmptyNestedNodesInExpanded(searchedTree, expandedSet);
|
|
60
|
+
const collectedNodesForPreload = Array.from(new Set([...toPreloadExpandableNodes.map(node => node.id), ...needPreloadNodes]));
|
|
61
|
+
if (!collectedNodesForPreload.length) {
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const preloadedNodes = yield onPreloadNodes(collectedNodesForPreload, abortController.signal);
|
|
65
|
+
if (searchPromiseRef.current !== searchPromise) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
let tmpTree = [...searchedTree];
|
|
69
|
+
for (const [nodeId, children] of Object.entries(preloadedNodes)) {
|
|
70
|
+
tmpTree = setChildrenOfTreeNode(tmpTree, nodeId, children);
|
|
71
|
+
}
|
|
72
|
+
tree.current = tmpTree;
|
|
73
|
+
treeItemsRecord.current = buildTreeItemsRecord(tmpTree);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
if (searchPromiseRef.current === searchPromise) {
|
|
78
|
+
setLoading(false);
|
|
79
|
+
searchPromiseRef.current = null;
|
|
80
|
+
searchAbortControllerRef.current = null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}), [buildTreeItemsRecord, expandedNodes, onPreloadNodes, onSearch, tree, treeItemsRecord]);
|
|
84
|
+
useDidUpdate(() => {
|
|
85
|
+
handleSearch(debouncedSearch);
|
|
86
|
+
}, [debouncedSearch, handleSearch]);
|
|
87
|
+
useEffect(() => {
|
|
88
|
+
tree.current = initTree;
|
|
89
|
+
treeItemsRecord.current = buildTreeItemsRecord(initTree);
|
|
90
|
+
}, [buildTreeItemsRecord, initTree, tree, treeItemsRecord]);
|
|
91
|
+
useEffect(() => () => {
|
|
92
|
+
var _a, _b;
|
|
93
|
+
(_a = searchPromiseRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
|
|
94
|
+
(_b = searchAbortControllerRef.current) === null || _b === void 0 ? void 0 : _b.abort();
|
|
95
|
+
}, []);
|
|
96
|
+
return {
|
|
97
|
+
tree,
|
|
98
|
+
expandedNodes,
|
|
99
|
+
loading,
|
|
100
|
+
treeItemsRecord,
|
|
101
|
+
search: {
|
|
102
|
+
value: search,
|
|
103
|
+
onChange: setSearch,
|
|
104
|
+
},
|
|
105
|
+
onExpand,
|
|
106
|
+
onDataLoad,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { PreloadNodeHandler, SelectHandler, TreeNodeProps } from '../types';
|
|
2
|
+
type UseTreeMultiSelectionParams<TTreeNode extends TreeNodeProps> = {
|
|
3
|
+
onDataLoad: PreloadNodeHandler<TTreeNode>;
|
|
4
|
+
onSelect: SelectHandler;
|
|
5
|
+
selected?: string[];
|
|
6
|
+
onChangeSelected?: (newSelected: string[]) => void;
|
|
7
|
+
};
|
|
8
|
+
export declare function useTreeMultiSelection<TTreeNode extends TreeNodeProps>({ onDataLoad, onSelect: onSelectProp, selected, onChangeSelected, }: UseTreeMultiSelectionParams<TTreeNode>): {
|
|
9
|
+
selected: string[];
|
|
10
|
+
onSelect: (selectedKeys: string[], node: TreeNodeProps) => Promise<void>;
|
|
11
|
+
};
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { useCallback } from 'react';
|
|
11
|
+
import { useValueControl } from '@snack-uikit/utils';
|
|
12
|
+
const getNewSelectedIds = (selectedIds, added, removed) => {
|
|
13
|
+
const result = new Set(selectedIds);
|
|
14
|
+
added.forEach(id => {
|
|
15
|
+
result.add(id);
|
|
16
|
+
});
|
|
17
|
+
removed.forEach(id => {
|
|
18
|
+
result.delete(id);
|
|
19
|
+
});
|
|
20
|
+
return Array.from(result);
|
|
21
|
+
};
|
|
22
|
+
export function useTreeMultiSelection({ onDataLoad, onSelect: onSelectProp, selected, onChangeSelected, }) {
|
|
23
|
+
const [selectedIds = [], setSelectedIds] = useValueControl({
|
|
24
|
+
value: selected,
|
|
25
|
+
defaultValue: [],
|
|
26
|
+
onChange: onChangeSelected,
|
|
27
|
+
});
|
|
28
|
+
const onSelect = useCallback((selectedKeys, node) => __awaiter(this, void 0, void 0, function* () {
|
|
29
|
+
const isSelected = selectedKeys.includes(node.id);
|
|
30
|
+
const clonedNode = structuredClone(node);
|
|
31
|
+
if (node.nested && !node.nested.length) {
|
|
32
|
+
const { preloadedChildren } = yield onDataLoad(node);
|
|
33
|
+
clonedNode.nested = preloadedChildren;
|
|
34
|
+
}
|
|
35
|
+
const { added, removed } = onSelectProp({ selectedKeys, node: clonedNode, isSelected });
|
|
36
|
+
const updatedSelectedIds = getNewSelectedIds(selectedIds, added, removed);
|
|
37
|
+
setSelectedIds(updatedSelectedIds);
|
|
38
|
+
}), [onDataLoad, onSelectProp, selectedIds, setSelectedIds]);
|
|
39
|
+
return {
|
|
40
|
+
selected: selectedIds,
|
|
41
|
+
onSelect,
|
|
42
|
+
};
|
|
43
|
+
}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export * from './components';
|
|
2
|
-
export type { OnNodeClick, TreeNodeId, TreeNodeProps } from './types';
|
|
2
|
+
export type { OnNodeClick, TreeNodeId, TreeNodeProps, ExtendedTreeNodeProps } from './types';
|
|
3
3
|
export { setNonce } from '@snack-uikit/list';
|
|
4
|
+
export * from './helpers';
|
package/dist/esm/index.js
CHANGED
package/dist/esm/types.d.ts
CHANGED
|
@@ -103,3 +103,20 @@ export type TreeBaseProps = TreeView | TreeMultiSelect | TreeSingleSelect;
|
|
|
103
103
|
export type ExtendedTreeNodeProps = TreeNodeProps & {
|
|
104
104
|
getTitle?(): void;
|
|
105
105
|
};
|
|
106
|
+
export type PreloadNodeHandler<TTreeNode extends TreeNodeProps> = (node: TreeNodeProps) => Promise<{
|
|
107
|
+
preloadedChildren: TTreeNode[];
|
|
108
|
+
updatedTree: TTreeNode[];
|
|
109
|
+
}>;
|
|
110
|
+
export type SearchableTreeDataLoadResult<TTreeNode extends TreeNodeProps, TRecordValue> = {
|
|
111
|
+
preloadedChildren: TTreeNode[];
|
|
112
|
+
updatedTree: TTreeNode[];
|
|
113
|
+
newTreeItemsRecord: Record<string, TRecordValue>;
|
|
114
|
+
};
|
|
115
|
+
export type SelectHandler = (props: {
|
|
116
|
+
selectedKeys: string[];
|
|
117
|
+
node: TreeNodeProps;
|
|
118
|
+
isSelected: boolean;
|
|
119
|
+
}) => {
|
|
120
|
+
added: string[];
|
|
121
|
+
removed: string[];
|
|
122
|
+
};
|
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
6
|
"title": "Tree",
|
|
7
|
-
"version": "0.
|
|
7
|
+
"version": "0.11.1-preview-c3fee040.0",
|
|
8
8
|
"sideEffects": [
|
|
9
9
|
"*.css",
|
|
10
10
|
"*.woff",
|
|
@@ -12,9 +12,25 @@
|
|
|
12
12
|
],
|
|
13
13
|
"description": "",
|
|
14
14
|
"types": "./dist/esm/index.d.ts",
|
|
15
|
+
"typesVersions": {
|
|
16
|
+
"*": {
|
|
17
|
+
".": [
|
|
18
|
+
"./dist/esm/index.d.ts"
|
|
19
|
+
],
|
|
20
|
+
"hooks": [
|
|
21
|
+
"./dist/esm/hooks/index.d.ts"
|
|
22
|
+
]
|
|
23
|
+
}
|
|
24
|
+
},
|
|
15
25
|
"exports": {
|
|
16
|
-
"
|
|
17
|
-
|
|
26
|
+
".": {
|
|
27
|
+
"import": "./dist/esm/index.js",
|
|
28
|
+
"require": "./dist/cjs/index.js"
|
|
29
|
+
},
|
|
30
|
+
"./hooks": {
|
|
31
|
+
"import": "./dist/esm/hooks/index.js",
|
|
32
|
+
"require": "./dist/cjs/hooks/index.js"
|
|
33
|
+
}
|
|
18
34
|
},
|
|
19
35
|
"homepage": "https://github.com/cloud-ru-tech/snack-uikit/tree/master/packages/tree",
|
|
20
36
|
"repository": {
|
|
@@ -36,6 +52,7 @@
|
|
|
36
52
|
"license": "Apache-2.0",
|
|
37
53
|
"scripts": {},
|
|
38
54
|
"dependencies": {
|
|
55
|
+
"@siberiacancode/reactuse": "0.3.14",
|
|
39
56
|
"@snack-uikit/button": "0.19.17",
|
|
40
57
|
"@snack-uikit/icons": "0.27.7",
|
|
41
58
|
"@snack-uikit/list": "0.32.17",
|
|
@@ -43,10 +60,11 @@
|
|
|
43
60
|
"@snack-uikit/truncate-string": "0.7.11",
|
|
44
61
|
"@snack-uikit/typography": "0.8.12",
|
|
45
62
|
"@snack-uikit/utils": "4.0.1",
|
|
63
|
+
"cancelable-promise": "4.3.1",
|
|
46
64
|
"classnames": "2.5.1",
|
|
47
65
|
"queue-fifo": "0.2.6",
|
|
48
66
|
"react-transition-state": "2.1.1",
|
|
49
67
|
"uncontrollable": "8.0.4"
|
|
50
68
|
},
|
|
51
|
-
"gitHead": "
|
|
69
|
+
"gitHead": "4aa46f03f56e45a92f8d7cbf49d91bcc7ae130cb"
|
|
52
70
|
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import type { TreeNodeProps } from '../../types';
|
|
4
|
+
import { collectEmptyNestedNodesInExpanded } from '../collectEmptyNestedNodesInExpanded';
|
|
5
|
+
|
|
6
|
+
const node = (id: string, nested?: TreeNodeProps[]) => ({
|
|
7
|
+
id,
|
|
8
|
+
title: id,
|
|
9
|
+
...(nested !== undefined && { nested }),
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
describe('collectEmptyNestedNodesInExpanded', () => {
|
|
13
|
+
it('returns nodes with empty nested array that are in expandedIds', () => {
|
|
14
|
+
const tree = [node('a', []), node('b', [node('b1')])];
|
|
15
|
+
const expandedIds = new Set(['a']);
|
|
16
|
+
const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
|
|
17
|
+
|
|
18
|
+
expect(result).toHaveLength(1);
|
|
19
|
+
expect(result[0]).toMatchObject({ id: 'a', nested: [] });
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it('does not return nodes with empty nested if not in expandedIds', () => {
|
|
23
|
+
const tree = [node('a', []), node('b', [])];
|
|
24
|
+
const expandedIds = new Set(['b']);
|
|
25
|
+
const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
|
|
26
|
+
|
|
27
|
+
expect(result).toHaveLength(1);
|
|
28
|
+
expect(result[0].id).toBe('b');
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('does not return nodes that have non-empty nested', () => {
|
|
32
|
+
const tree = [node('a', [node('a1')]), node('b', [])];
|
|
33
|
+
const expandedIds = new Set(['a', 'b']);
|
|
34
|
+
const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
|
|
35
|
+
|
|
36
|
+
expect(result).toHaveLength(1);
|
|
37
|
+
expect(result[0].id).toBe('b');
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('does not return nodes without nested property (leaf)', () => {
|
|
41
|
+
const tree = [node('leaf'), node('empty', [])];
|
|
42
|
+
const expandedIds = new Set(['leaf', 'empty']);
|
|
43
|
+
const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
|
|
44
|
+
|
|
45
|
+
expect(result).toHaveLength(1);
|
|
46
|
+
expect(result[0].id).toBe('empty');
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('returns empty array for empty tree', () => {
|
|
50
|
+
const result = collectEmptyNestedNodesInExpanded([], new Set(['any']));
|
|
51
|
+
expect(result).toEqual([]);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('returns empty array when expandedIds is empty', () => {
|
|
55
|
+
const tree = [node('a', []), node('b', [])];
|
|
56
|
+
const result = collectEmptyNestedNodesInExpanded(tree, new Set());
|
|
57
|
+
|
|
58
|
+
expect(result).toEqual([]);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('collects from deeply nested nodes', () => {
|
|
62
|
+
const child = node('child', []);
|
|
63
|
+
const tree = [node('root', [node('mid', [child])])];
|
|
64
|
+
const expandedIds = new Set(['root', 'mid', 'child']);
|
|
65
|
+
const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
|
|
66
|
+
|
|
67
|
+
expect(result).toHaveLength(1);
|
|
68
|
+
expect(result[0]).toMatchObject({ id: 'child', nested: [] });
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('returns all matching nodes from different levels', () => {
|
|
72
|
+
const tree = [node('a', []), node('b', [node('b1', []), node('b2', [])])];
|
|
73
|
+
const expandedIds = new Set(['a', 'b', 'b1', 'b2']);
|
|
74
|
+
const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
|
|
75
|
+
|
|
76
|
+
expect(result).toHaveLength(3);
|
|
77
|
+
expect(result.map(n => n.id).sort()).toEqual(['a', 'b1', 'b2']);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('only includes node if both empty nested and expanded', () => {
|
|
81
|
+
const tree = [node('expanded', []), node('collapsed', [])];
|
|
82
|
+
const expandedIds = new Set(['expanded']);
|
|
83
|
+
const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
|
|
84
|
+
|
|
85
|
+
expect(result).toHaveLength(1);
|
|
86
|
+
expect(result[0].id).toBe('expanded');
|
|
87
|
+
});
|
|
88
|
+
});
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import type { TreeNodeProps } from '../../types';
|
|
4
|
+
import { setChildrenOfTreeNode } from '../setChildrenOfTreeNode';
|
|
5
|
+
|
|
6
|
+
const node = (id: string, nested?: { id: string; title: string }[]) => ({
|
|
7
|
+
id,
|
|
8
|
+
title: id,
|
|
9
|
+
...(nested !== undefined && { nested: nested.map(n => ({ ...n, title: n.id })) }),
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
describe('setChildrenOfTreeNode', () => {
|
|
13
|
+
it('replaces nested for root-level node', () => {
|
|
14
|
+
const tree = [node('a', [{ id: 'a1', title: 'a1' }]), node('b', [{ id: 'b1', title: 'b1' }])];
|
|
15
|
+
const children = [node('new1'), node('new2')];
|
|
16
|
+
const result = setChildrenOfTreeNode(tree, 'b', children);
|
|
17
|
+
|
|
18
|
+
expect(result).toHaveLength(2);
|
|
19
|
+
expect(result[0]).toMatchObject({ id: 'a', nested: [{ id: 'a1' }] });
|
|
20
|
+
expect(result[1]).toMatchObject({ id: 'b', nested: [{ id: 'new1' }, { id: 'new2' }] });
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('replaces nested for deeply nested node', () => {
|
|
24
|
+
const childWithNested = node('child');
|
|
25
|
+
(childWithNested as { nested: { id: string; title: string }[] }).nested = [{ id: 'grand', title: 'grand' }];
|
|
26
|
+
const tree = [node('root', [childWithNested])];
|
|
27
|
+
const children = [node('replacement')];
|
|
28
|
+
const result = setChildrenOfTreeNode(tree, 'child', children);
|
|
29
|
+
|
|
30
|
+
const root = result[0] as TreeNodeProps & { nested: (TreeNodeProps & { nested: TreeNodeProps[] })[] };
|
|
31
|
+
expect(root.nested).toHaveLength(1);
|
|
32
|
+
expect(root.nested[0]).toMatchObject({ id: 'child', nested: [{ id: 'replacement' }] });
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('returns cloned tree when node is not found', () => {
|
|
36
|
+
const tree = [node('a'), node('b')];
|
|
37
|
+
const result = setChildrenOfTreeNode(tree, 'missing', [node('x')]);
|
|
38
|
+
|
|
39
|
+
expect(result).toHaveLength(2);
|
|
40
|
+
expect(result[0]).toMatchObject({ id: 'a' });
|
|
41
|
+
expect(result[1]).toMatchObject({ id: 'b' });
|
|
42
|
+
expect(result).not.toBe(tree);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('returns empty array for empty tree', () => {
|
|
46
|
+
const result = setChildrenOfTreeNode([], 'any', [node('x')]);
|
|
47
|
+
expect(result).toEqual([]);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('sets children for target node that had no nested (leaf)', () => {
|
|
51
|
+
const tree = [node('leaf'), node('other')];
|
|
52
|
+
const children = [node('new1')];
|
|
53
|
+
const result = setChildrenOfTreeNode(tree, 'leaf', children);
|
|
54
|
+
|
|
55
|
+
expect(result[0]).toMatchObject({ id: 'leaf', nested: [{ id: 'new1' }] });
|
|
56
|
+
expect(result[1]).toMatchObject({ id: 'other' });
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('preserves order of root nodes when target is second', () => {
|
|
60
|
+
const tree = [node('first'), node('second', [{ id: 's1', title: 's1' }]), node('third')];
|
|
61
|
+
const children = [node('new1'), node('new2')];
|
|
62
|
+
const result = setChildrenOfTreeNode(tree, 'second', children);
|
|
63
|
+
|
|
64
|
+
expect(result.map(n => n.id)).toEqual(['first', 'second', 'third']);
|
|
65
|
+
expect((result[1] as TreeNodeProps & { nested: TreeNodeProps[] }).nested).toHaveLength(2);
|
|
66
|
+
expect((result[1] as { nested: { id: string }[] }).nested.map(n => n.id)).toEqual(['new1', 'new2']);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { TreeNodeProps } from '../types';
|
|
2
|
+
import { traverse } from './traverse';
|
|
3
|
+
|
|
4
|
+
export function collectEmptyNestedNodesInExpanded<TTreeNode extends TreeNodeProps>(
|
|
5
|
+
nodes: TTreeNode[],
|
|
6
|
+
expandedIds: Set<string>,
|
|
7
|
+
): TTreeNode[] {
|
|
8
|
+
const result: TTreeNode[] = [];
|
|
9
|
+
traverse(nodes, node => {
|
|
10
|
+
const hasEmptyNested = Array.isArray(node.nested) && node.nested.length === 0;
|
|
11
|
+
if (hasEmptyNested && expandedIds.has(node.id)) {
|
|
12
|
+
result.push(node);
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
return result;
|
|
16
|
+
}
|
package/src/helpers/index.ts
CHANGED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { TreeNodeProps } from '../types';
|
|
2
|
+
import { traverseWithTarget } from './traverse';
|
|
3
|
+
|
|
4
|
+
export const setChildrenOfTreeNode = <TTreeNode extends TreeNodeProps>(
|
|
5
|
+
tree: TTreeNode[],
|
|
6
|
+
nodeId: string,
|
|
7
|
+
children: TTreeNode[],
|
|
8
|
+
): TTreeNode[] => {
|
|
9
|
+
const result: TTreeNode[] = [];
|
|
10
|
+
|
|
11
|
+
traverseWithTarget(tree, result, (source, _depth, targetList) => {
|
|
12
|
+
const isTarget = source.id === nodeId;
|
|
13
|
+
const hasNested = Array.isArray(source.nested);
|
|
14
|
+
|
|
15
|
+
let newNested: TTreeNode[] | undefined;
|
|
16
|
+
if (isTarget) {
|
|
17
|
+
newNested = children;
|
|
18
|
+
} else if (hasNested) {
|
|
19
|
+
newNested = [];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const newNode = (newNested !== undefined ? { ...source, nested: newNested } : { ...source }) as TTreeNode;
|
|
23
|
+
|
|
24
|
+
targetList.push(newNode);
|
|
25
|
+
|
|
26
|
+
return !isTarget && hasNested && source.nested?.length ? newNested : undefined;
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
return result;
|
|
30
|
+
};
|
|
@@ -3,8 +3,8 @@ import { extractTreeNodeTitle } from './extractTreeNodeTitle';
|
|
|
3
3
|
|
|
4
4
|
export const sortTreeItemsByTitle = (items: ExtendedTreeNodeProps[]) =>
|
|
5
5
|
items?.toSorted((itemA, itemB) => {
|
|
6
|
-
const valueA = extractTreeNodeTitle(itemA);
|
|
7
|
-
const valueB = extractTreeNodeTitle(itemB);
|
|
6
|
+
const valueA = extractTreeNodeTitle(itemA).toLowerCase();
|
|
7
|
+
const valueB = extractTreeNodeTitle(itemB).toLowerCase();
|
|
8
8
|
|
|
9
9
|
return valueA.localeCompare(valueB);
|
|
10
10
|
});
|
package/src/helpers/traverse.ts
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
import Queue from 'queue-fifo';
|
|
2
2
|
|
|
3
|
-
import { TreeNodeProps } from '../';
|
|
3
|
+
import { TreeNodeProps } from '../types';
|
|
4
4
|
|
|
5
5
|
type NodeWithDepth<T extends TreeNodeProps> = { node: T; depth: number };
|
|
6
6
|
|
|
7
|
+
type NodeWithDepthAndTarget<T extends TreeNodeProps> = {
|
|
8
|
+
node: T;
|
|
9
|
+
depth: number;
|
|
10
|
+
targetList: T[];
|
|
11
|
+
};
|
|
12
|
+
|
|
7
13
|
export const traverse = <T extends TreeNodeProps>(nodes: T[], callback: (node: T, depth: number) => void) => {
|
|
8
14
|
const queue = new Queue<NodeWithDepth<T>>();
|
|
9
15
|
|
|
@@ -25,3 +31,34 @@ export const traverse = <T extends TreeNodeProps>(nodes: T[], callback: (node: T
|
|
|
25
31
|
}
|
|
26
32
|
}
|
|
27
33
|
};
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* BFS с указанием целевого списка для каждого узла.
|
|
37
|
+
* Очередь хранит (node, depth, targetList). Callback добавляет узел в targetList
|
|
38
|
+
* и возвращает массив для детей (или undefined, чтобы не обходить детей).
|
|
39
|
+
*/
|
|
40
|
+
export const traverseWithTarget = <T extends TreeNodeProps>(
|
|
41
|
+
nodes: T[],
|
|
42
|
+
rootTargetList: T[],
|
|
43
|
+
callback: (node: T, depth: number, targetList: T[]) => T[] | undefined,
|
|
44
|
+
) => {
|
|
45
|
+
const queue = new Queue<NodeWithDepthAndTarget<T>>();
|
|
46
|
+
|
|
47
|
+
for (const node of nodes) {
|
|
48
|
+
queue.enqueue({ node, depth: 0, targetList: rootTargetList });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
while (!queue.isEmpty()) {
|
|
52
|
+
const item = queue.dequeue();
|
|
53
|
+
if (!item) continue;
|
|
54
|
+
|
|
55
|
+
const { node, depth, targetList } = item;
|
|
56
|
+
const childTargetList = callback(node, depth, targetList);
|
|
57
|
+
|
|
58
|
+
if (childTargetList !== undefined && node.nested?.length) {
|
|
59
|
+
for (const child of node.nested) {
|
|
60
|
+
queue.enqueue({ node: child as T, depth: depth + 1, targetList: childTargetList });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
};
|