@snack-uikit/tree 0.10.1 → 0.10.2-preview-13f87e77.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.
Files changed (58) hide show
  1. package/README.md +17 -0
  2. package/dist/cjs/helpers/__tests__/collectEmptyNestedNodesInExpanded.spec.d.ts +1 -0
  3. package/dist/cjs/helpers/__tests__/collectEmptyNestedNodesInExpanded.spec.js +80 -0
  4. package/dist/cjs/helpers/__tests__/setChildrenOfTreeNode.spec.d.ts +1 -0
  5. package/dist/cjs/helpers/__tests__/setChildrenOfTreeNode.spec.js +102 -0
  6. package/dist/cjs/helpers/collectEmptyNestedNodesInExpanded.d.ts +2 -0
  7. package/dist/cjs/helpers/collectEmptyNestedNodesInExpanded.js +17 -0
  8. package/dist/cjs/helpers/index.d.ts +2 -0
  9. package/dist/cjs/helpers/index.js +3 -1
  10. package/dist/cjs/helpers/setChildrenOfTreeNode.d.ts +2 -0
  11. package/dist/cjs/helpers/setChildrenOfTreeNode.js +28 -0
  12. package/dist/cjs/helpers/sortTreeItemsByTitle.js +2 -2
  13. package/dist/cjs/helpers/traverse.d.ts +6 -0
  14. package/dist/cjs/helpers/traverse.js +38 -2
  15. package/dist/cjs/hooks/index.d.ts +2 -0
  16. package/dist/cjs/hooks/index.js +26 -0
  17. package/dist/cjs/hooks/useTreeMultiSelection.d.ts +12 -0
  18. package/dist/cjs/hooks/useTreeMultiSelection.js +82 -0
  19. package/dist/cjs/hooks/useTreeWithPreload.d.ts +33 -0
  20. package/dist/cjs/hooks/useTreeWithPreload.js +138 -0
  21. package/dist/cjs/index.d.ts +1 -0
  22. package/dist/cjs/index.js +2 -1
  23. package/dist/cjs/types.d.ts +12 -0
  24. package/dist/esm/helpers/__tests__/collectEmptyNestedNodesInExpanded.spec.d.ts +1 -0
  25. package/dist/esm/helpers/__tests__/collectEmptyNestedNodesInExpanded.spec.js +64 -0
  26. package/dist/esm/helpers/__tests__/setChildrenOfTreeNode.spec.d.ts +1 -0
  27. package/dist/esm/helpers/__tests__/setChildrenOfTreeNode.spec.js +50 -0
  28. package/dist/esm/helpers/collectEmptyNestedNodesInExpanded.d.ts +2 -0
  29. package/dist/esm/helpers/collectEmptyNestedNodesInExpanded.js +11 -0
  30. package/dist/esm/helpers/index.d.ts +2 -0
  31. package/dist/esm/helpers/index.js +2 -0
  32. package/dist/esm/helpers/setChildrenOfTreeNode.d.ts +2 -0
  33. package/dist/esm/helpers/setChildrenOfTreeNode.js +20 -0
  34. package/dist/esm/helpers/sortTreeItemsByTitle.js +2 -2
  35. package/dist/esm/helpers/traverse.d.ts +6 -0
  36. package/dist/esm/helpers/traverse.js +24 -0
  37. package/dist/esm/hooks/index.d.ts +2 -0
  38. package/dist/esm/hooks/index.js +2 -0
  39. package/dist/esm/hooks/useTreeMultiSelection.d.ts +12 -0
  40. package/dist/esm/hooks/useTreeMultiSelection.js +43 -0
  41. package/dist/esm/hooks/useTreeWithPreload.d.ts +33 -0
  42. package/dist/esm/hooks/useTreeWithPreload.js +98 -0
  43. package/dist/esm/index.d.ts +1 -0
  44. package/dist/esm/index.js +1 -0
  45. package/dist/esm/types.d.ts +12 -0
  46. package/package.json +4 -2
  47. package/src/helpers/__tests__/collectEmptyNestedNodesInExpanded.spec.ts +88 -0
  48. package/src/helpers/__tests__/setChildrenOfTreeNode.spec.ts +68 -0
  49. package/src/helpers/collectEmptyNestedNodesInExpanded.ts +16 -0
  50. package/src/helpers/index.ts +2 -0
  51. package/src/helpers/setChildrenOfTreeNode.ts +30 -0
  52. package/src/helpers/sortTreeItemsByTitle.ts +2 -2
  53. package/src/helpers/traverse.ts +37 -0
  54. package/src/hooks/index.ts +2 -0
  55. package/src/hooks/useTreeMultiSelection.ts +61 -0
  56. package/src/hooks/useTreeWithPreload.ts +150 -0
  57. package/src/index.ts +1 -0
  58. package/src/types.ts +9 -0
package/dist/cjs/index.js CHANGED
@@ -30,4 +30,5 @@ Object.defineProperty(exports, "setNonce", {
30
30
  get: function () {
31
31
  return list_1.setNonce;
32
32
  }
33
- });
33
+ });
34
+ __exportStar(require("./hooks"), exports);
@@ -103,3 +103,15 @@ 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 SelectHandler = (props: {
111
+ selectedKeys: string[];
112
+ node: TreeNodeProps;
113
+ isSelected: boolean;
114
+ }) => {
115
+ added: string[];
116
+ removed: string[];
117
+ };
@@ -0,0 +1,64 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { collectEmptyNestedNodesInExpanded } from '../collectEmptyNestedNodesInExpanded';
3
+ const node = (id, nested) => (Object.assign({ id, title: id }, (nested !== undefined && { nested })));
4
+ describe('collectEmptyNestedNodesInExpanded', () => {
5
+ it('returns nodes with empty nested array that are in expandedIds', () => {
6
+ const tree = [node('a', []), node('b', [node('b1')])];
7
+ const expandedIds = new Set(['a']);
8
+ const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
9
+ expect(result).toHaveLength(1);
10
+ expect(result[0]).toMatchObject({ id: 'a', nested: [] });
11
+ });
12
+ it('does not return nodes with empty nested if not in expandedIds', () => {
13
+ const tree = [node('a', []), node('b', [])];
14
+ const expandedIds = new Set(['b']);
15
+ const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
16
+ expect(result).toHaveLength(1);
17
+ expect(result[0].id).toBe('b');
18
+ });
19
+ it('does not return nodes that have non-empty nested', () => {
20
+ const tree = [node('a', [node('a1')]), node('b', [])];
21
+ const expandedIds = new Set(['a', 'b']);
22
+ const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
23
+ expect(result).toHaveLength(1);
24
+ expect(result[0].id).toBe('b');
25
+ });
26
+ it('does not return nodes without nested property (leaf)', () => {
27
+ const tree = [node('leaf'), node('empty', [])];
28
+ const expandedIds = new Set(['leaf', 'empty']);
29
+ const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
30
+ expect(result).toHaveLength(1);
31
+ expect(result[0].id).toBe('empty');
32
+ });
33
+ it('returns empty array for empty tree', () => {
34
+ const result = collectEmptyNestedNodesInExpanded([], new Set(['any']));
35
+ expect(result).toEqual([]);
36
+ });
37
+ it('returns empty array when expandedIds is empty', () => {
38
+ const tree = [node('a', []), node('b', [])];
39
+ const result = collectEmptyNestedNodesInExpanded(tree, new Set());
40
+ expect(result).toEqual([]);
41
+ });
42
+ it('collects from deeply nested nodes', () => {
43
+ const child = node('child', []);
44
+ const tree = [node('root', [node('mid', [child])])];
45
+ const expandedIds = new Set(['root', 'mid', 'child']);
46
+ const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
47
+ expect(result).toHaveLength(1);
48
+ expect(result[0]).toMatchObject({ id: 'child', nested: [] });
49
+ });
50
+ it('returns all matching nodes from different levels', () => {
51
+ const tree = [node('a', []), node('b', [node('b1', []), node('b2', [])])];
52
+ const expandedIds = new Set(['a', 'b', 'b1', 'b2']);
53
+ const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
54
+ expect(result).toHaveLength(3);
55
+ expect(result.map(n => n.id).sort()).toEqual(['a', 'b1', 'b2']);
56
+ });
57
+ it('only includes node if both empty nested and expanded', () => {
58
+ const tree = [node('expanded', []), node('collapsed', [])];
59
+ const expandedIds = new Set(['expanded']);
60
+ const result = collectEmptyNestedNodesInExpanded(tree, expandedIds);
61
+ expect(result).toHaveLength(1);
62
+ expect(result[0].id).toBe('expanded');
63
+ });
64
+ });
@@ -0,0 +1,50 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { setChildrenOfTreeNode } from '../setChildrenOfTreeNode';
3
+ const node = (id, nested) => (Object.assign({ id, title: id }, (nested !== undefined && { nested: nested.map(n => (Object.assign(Object.assign({}, n), { title: n.id }))) })));
4
+ describe('setChildrenOfTreeNode', () => {
5
+ it('replaces nested for root-level node', () => {
6
+ const tree = [node('a', [{ id: 'a1', title: 'a1' }]), node('b', [{ id: 'b1', title: 'b1' }])];
7
+ const children = [node('new1'), node('new2')];
8
+ const result = setChildrenOfTreeNode(tree, 'b', children);
9
+ expect(result).toHaveLength(2);
10
+ expect(result[0]).toMatchObject({ id: 'a', nested: [{ id: 'a1' }] });
11
+ expect(result[1]).toMatchObject({ id: 'b', nested: [{ id: 'new1' }, { id: 'new2' }] });
12
+ });
13
+ it('replaces nested for deeply nested node', () => {
14
+ const childWithNested = node('child');
15
+ childWithNested.nested = [{ id: 'grand', title: 'grand' }];
16
+ const tree = [node('root', [childWithNested])];
17
+ const children = [node('replacement')];
18
+ const result = setChildrenOfTreeNode(tree, 'child', children);
19
+ const root = result[0];
20
+ expect(root.nested).toHaveLength(1);
21
+ expect(root.nested[0]).toMatchObject({ id: 'child', nested: [{ id: 'replacement' }] });
22
+ });
23
+ it('returns cloned tree when node is not found', () => {
24
+ const tree = [node('a'), node('b')];
25
+ const result = setChildrenOfTreeNode(tree, 'missing', [node('x')]);
26
+ expect(result).toHaveLength(2);
27
+ expect(result[0]).toMatchObject({ id: 'a' });
28
+ expect(result[1]).toMatchObject({ id: 'b' });
29
+ expect(result).not.toBe(tree);
30
+ });
31
+ it('returns empty array for empty tree', () => {
32
+ const result = setChildrenOfTreeNode([], 'any', [node('x')]);
33
+ expect(result).toEqual([]);
34
+ });
35
+ it('sets children for target node that had no nested (leaf)', () => {
36
+ const tree = [node('leaf'), node('other')];
37
+ const children = [node('new1')];
38
+ const result = setChildrenOfTreeNode(tree, 'leaf', children);
39
+ expect(result[0]).toMatchObject({ id: 'leaf', nested: [{ id: 'new1' }] });
40
+ expect(result[1]).toMatchObject({ id: 'other' });
41
+ });
42
+ it('preserves order of root nodes when target is second', () => {
43
+ const tree = [node('first'), node('second', [{ id: 's1', title: 's1' }]), node('third')];
44
+ const children = [node('new1'), node('new2')];
45
+ const result = setChildrenOfTreeNode(tree, 'second', children);
46
+ expect(result.map(n => n.id)).toEqual(['first', 'second', 'third']);
47
+ expect(result[1].nested).toHaveLength(2);
48
+ expect(result[1].nested.map(n => n.id)).toEqual(['new1', 'new2']);
49
+ });
50
+ });
@@ -0,0 +1,2 @@
1
+ import { TreeNodeProps } from '../types';
2
+ export declare function collectEmptyNestedNodesInExpanded<TTreeNode extends TreeNodeProps>(nodes: TTreeNode[], expandedIds: Set<string>): TTreeNode[];
@@ -0,0 +1,11 @@
1
+ import { traverse } from './traverse';
2
+ export function collectEmptyNestedNodesInExpanded(nodes, expandedIds) {
3
+ const result = [];
4
+ traverse(nodes, node => {
5
+ const hasEmptyNested = Array.isArray(node.nested) && node.nested.length === 0;
6
+ if (hasEmptyNested && expandedIds.has(node.id)) {
7
+ result.push(node);
8
+ }
9
+ });
10
+ return result;
11
+ }
@@ -6,3 +6,5 @@ export * from './getSearchedTreeNodeById';
6
6
  export * from './lookupTreeForSelectedNodes';
7
7
  export * from './sortTreeItemsByTitle';
8
8
  export * from './traverse';
9
+ export * from './setChildrenOfTreeNode';
10
+ export * from './collectEmptyNestedNodesInExpanded';
@@ -6,3 +6,5 @@ export * from './getSearchedTreeNodeById';
6
6
  export * from './lookupTreeForSelectedNodes';
7
7
  export * from './sortTreeItemsByTitle';
8
8
  export * from './traverse';
9
+ export * from './setChildrenOfTreeNode';
10
+ export * from './collectEmptyNestedNodesInExpanded';
@@ -0,0 +1,2 @@
1
+ import { TreeNodeProps } from '../types';
2
+ export declare const setChildrenOfTreeNode: <TTreeNode extends TreeNodeProps>(tree: TTreeNode[], nodeId: string, children: TTreeNode[]) => TTreeNode[];
@@ -0,0 +1,20 @@
1
+ import { traverseWithTarget } from './traverse';
2
+ export const setChildrenOfTreeNode = (tree, nodeId, children) => {
3
+ const result = [];
4
+ traverseWithTarget(tree, result, (source, _depth, targetList) => {
5
+ var _a;
6
+ const isTarget = source.id === nodeId;
7
+ const hasNested = Array.isArray(source.nested);
8
+ let newNested;
9
+ if (isTarget) {
10
+ newNested = children;
11
+ }
12
+ else if (hasNested) {
13
+ newNested = [];
14
+ }
15
+ const newNode = (newNested !== undefined ? Object.assign(Object.assign({}, source), { nested: newNested }) : Object.assign({}, source));
16
+ targetList.push(newNode);
17
+ return !isTarget && hasNested && ((_a = source.nested) === null || _a === void 0 ? void 0 : _a.length) ? newNested : undefined;
18
+ });
19
+ return result;
20
+ };
@@ -1,6 +1,6 @@
1
1
  import { extractTreeNodeTitle } from './extractTreeNodeTitle';
2
2
  export const sortTreeItemsByTitle = (items) => items === null || items === void 0 ? void 0 : items.toSorted((itemA, itemB) => {
3
- const valueA = extractTreeNodeTitle(itemA);
4
- const valueB = extractTreeNodeTitle(itemB);
3
+ const valueA = extractTreeNodeTitle(itemA).toLowerCase();
4
+ const valueB = extractTreeNodeTitle(itemB).toLowerCase();
5
5
  return valueA.localeCompare(valueB);
6
6
  });
@@ -1,2 +1,8 @@
1
1
  import { TreeNodeProps } from '../';
2
2
  export declare const traverse: <T extends TreeNodeProps>(nodes: T[], callback: (node: T, depth: number) => void) => void;
3
+ /**
4
+ * BFS с указанием целевого списка для каждого узла.
5
+ * Очередь хранит (node, depth, targetList). Callback добавляет узел в targetList
6
+ * и возвращает массив для детей (или undefined, чтобы не обходить детей).
7
+ */
8
+ export declare const traverseWithTarget: <T extends TreeNodeProps>(nodes: T[], rootTargetList: T[], callback: (node: T, depth: number, targetList: T[]) => T[] | undefined) => void;
@@ -17,3 +17,27 @@ export const traverse = (nodes, callback) => {
17
17
  }
18
18
  }
19
19
  };
20
+ /**
21
+ * BFS с указанием целевого списка для каждого узла.
22
+ * Очередь хранит (node, depth, targetList). Callback добавляет узел в targetList
23
+ * и возвращает массив для детей (или undefined, чтобы не обходить детей).
24
+ */
25
+ export const traverseWithTarget = (nodes, rootTargetList, callback) => {
26
+ var _a;
27
+ const queue = new Queue();
28
+ for (const node of nodes) {
29
+ queue.enqueue({ node, depth: 0, targetList: rootTargetList });
30
+ }
31
+ while (!queue.isEmpty()) {
32
+ const item = queue.dequeue();
33
+ if (!item)
34
+ continue;
35
+ const { node, depth, targetList } = item;
36
+ const childTargetList = callback(node, depth, targetList);
37
+ if (childTargetList !== undefined && ((_a = node.nested) === null || _a === void 0 ? void 0 : _a.length)) {
38
+ for (const child of node.nested) {
39
+ queue.enqueue({ node: child, depth: depth + 1, targetList: childTargetList });
40
+ }
41
+ }
42
+ }
43
+ };
@@ -0,0 +1,2 @@
1
+ export * from './useTreeWithPreload';
2
+ export * from './useTreeMultiSelection';
@@ -0,0 +1,2 @@
1
+ export * from './useTreeWithPreload';
2
+ export * from './useTreeMultiSelection';
@@ -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
+ }
@@ -0,0 +1,33 @@
1
+ import { 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
+ expandedNodes: string[];
9
+ };
10
+ type UseTreeWithPreloadParams<TRecordValue, TTreeNode extends TreeNodeProps> = {
11
+ initTree: TTreeNode[];
12
+ onPreloadNode: (node: TreeNodeProps) => Promise<TTreeNode[]>;
13
+ onPreloadNodes: (nodes: string[]) => Promise<Record<string, TTreeNode[]>>;
14
+ onSearch: (params: SearchParams) => Promise<SearchResult<TTreeNode>>;
15
+ mapNodeToRecordItem: (node: TTreeNode) => TRecordValue;
16
+ };
17
+ export declare function useTreeWithPreload<TRecordValue, TTreeNode extends TreeNodeProps>({ initTree, onPreloadNode, onPreloadNodes, onSearch, mapNodeToRecordItem, }: UseTreeWithPreloadParams<TRecordValue, TTreeNode>): {
18
+ tree: import("@siberiacancode/reactuse").StateRef<TTreeNode[]>;
19
+ expandedNodes: import("@siberiacancode/reactuse").StateRef<string[]>;
20
+ loading: boolean;
21
+ treeItemsRecord: import("@siberiacancode/reactuse").StateRef<Record<string, TRecordValue>>;
22
+ search: {
23
+ value: string;
24
+ onChange: import("react").Dispatch<import("react").SetStateAction<string>>;
25
+ };
26
+ onExpand: (nodes: string[]) => void;
27
+ onDataLoad: (node: TreeNodeProps) => Promise<{
28
+ preloadedChildren: TTreeNode[];
29
+ updatedTree: TTreeNode[];
30
+ newTreeItemsRecord: Record<string, TRecordValue>;
31
+ }>;
32
+ };
33
+ export {};
@@ -0,0 +1,98 @@
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 useTreeWithPreload({ 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 buildTreeItemsRecord = useCallback((nodes) => {
23
+ const record = {};
24
+ traverse(nodes, node => {
25
+ record[node.id] = mapNodeToRecordItem(node);
26
+ });
27
+ return record;
28
+ }, [mapNodeToRecordItem]);
29
+ const onExpand = useCallback((nodes) => {
30
+ expandedNodes.current = nodes;
31
+ }, [expandedNodes]);
32
+ const onDataLoad = useCallback((node) => __awaiter(this, void 0, void 0, function* () {
33
+ const preloadedChildren = yield onPreloadNode(node);
34
+ const updatedTree = setChildrenOfTreeNode(tree.current, node.id, preloadedChildren);
35
+ tree.current = updatedTree;
36
+ const newTreeItemsRecord = Object.assign({}, treeItemsRecord.current);
37
+ traverse(preloadedChildren, child => {
38
+ newTreeItemsRecord[child.id] = mapNodeToRecordItem(child);
39
+ });
40
+ treeItemsRecord.current = newTreeItemsRecord;
41
+ return { preloadedChildren, updatedTree, newTreeItemsRecord };
42
+ }), [mapNodeToRecordItem, onPreloadNode, tree, treeItemsRecord]);
43
+ const handleSearch = useCallback((searchQuery) => __awaiter(this, void 0, void 0, function* () {
44
+ var _a;
45
+ (_a = searchPromiseRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
46
+ setLoading(true);
47
+ const searchPromise = cancelable(onSearch({ search: searchQuery, expandedNodes: expandedNodes.current }));
48
+ searchPromiseRef.current = searchPromise;
49
+ try {
50
+ const { tree: searchedTree, needPreloadNodes } = yield searchPromise;
51
+ if (!searchPromise.isCanceled()) {
52
+ tree.current = searchedTree;
53
+ treeItemsRecord.current = buildTreeItemsRecord(searchedTree);
54
+ const expandedSet = new Set(expandedNodes.current);
55
+ const toPreloadExpandableNodes = collectEmptyNestedNodesInExpanded(searchedTree, expandedSet);
56
+ const collectedNodesForPreload = Array.from(new Set([...toPreloadExpandableNodes.map(node => node.id), ...needPreloadNodes]));
57
+ if (!collectedNodesForPreload.length) {
58
+ return;
59
+ }
60
+ const preloadedNodes = yield onPreloadNodes(collectedNodesForPreload);
61
+ if (searchPromiseRef.current !== searchPromise) {
62
+ return;
63
+ }
64
+ let tmpTree = [...searchedTree];
65
+ for (const [nodeId, children] of Object.entries(preloadedNodes)) {
66
+ tmpTree = setChildrenOfTreeNode(tmpTree, nodeId, children);
67
+ }
68
+ tree.current = tmpTree;
69
+ treeItemsRecord.current = buildTreeItemsRecord(tmpTree);
70
+ }
71
+ }
72
+ finally {
73
+ if (searchPromiseRef.current === searchPromise) {
74
+ setLoading(false);
75
+ searchPromiseRef.current = null;
76
+ }
77
+ }
78
+ }), [buildTreeItemsRecord, expandedNodes, onPreloadNodes, onSearch, tree, treeItemsRecord]);
79
+ useDidUpdate(() => {
80
+ handleSearch(debouncedSearch);
81
+ }, [debouncedSearch, handleSearch]);
82
+ useEffect(() => {
83
+ tree.current = initTree;
84
+ treeItemsRecord.current = buildTreeItemsRecord(initTree);
85
+ }, [buildTreeItemsRecord, initTree, tree, treeItemsRecord]);
86
+ return {
87
+ tree,
88
+ expandedNodes,
89
+ loading,
90
+ treeItemsRecord,
91
+ search: {
92
+ value: search,
93
+ onChange: setSearch,
94
+ },
95
+ onExpand,
96
+ onDataLoad,
97
+ };
98
+ }
@@ -1,3 +1,4 @@
1
1
  export * from './components';
2
2
  export type { OnNodeClick, TreeNodeId, TreeNodeProps } from './types';
3
3
  export { setNonce } from '@snack-uikit/list';
4
+ export * from './hooks';
package/dist/esm/index.js CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './components';
2
2
  export { setNonce } from '@snack-uikit/list';
3
+ export * from './hooks';
@@ -103,3 +103,15 @@ 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 SelectHandler = (props: {
111
+ selectedKeys: string[];
112
+ node: TreeNodeProps;
113
+ isSelected: boolean;
114
+ }) => {
115
+ added: string[];
116
+ removed: string[];
117
+ };
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "access": "public"
5
5
  },
6
6
  "title": "Tree",
7
- "version": "0.10.1",
7
+ "version": "0.10.2-preview-13f87e77.0",
8
8
  "sideEffects": [
9
9
  "*.css",
10
10
  "*.woff",
@@ -36,6 +36,7 @@
36
36
  "license": "Apache-2.0",
37
37
  "scripts": {},
38
38
  "dependencies": {
39
+ "@siberiacancode/reactuse": "0.3.14",
39
40
  "@snack-uikit/button": "0.19.17",
40
41
  "@snack-uikit/icons": "0.27.7",
41
42
  "@snack-uikit/list": "0.32.15",
@@ -43,10 +44,11 @@
43
44
  "@snack-uikit/truncate-string": "0.7.9",
44
45
  "@snack-uikit/typography": "0.8.12",
45
46
  "@snack-uikit/utils": "4.0.1",
47
+ "cancelable-promise": "4.3.1",
46
48
  "classnames": "2.5.1",
47
49
  "queue-fifo": "0.2.6",
48
50
  "react-transition-state": "2.1.1",
49
51
  "uncontrollable": "8.0.4"
50
52
  },
51
- "gitHead": "08bc11a562baec889f73cfb3af56946ab5e668fb"
53
+ "gitHead": "244db9228818f24f34f9d5a4dafdf6f7f2182c6d"
52
54
  }
@@ -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
+ });