Skip to content

Commit 69eae85

Browse files
committed
feat(useTreeLoader): include .depth for TreeNodes
1 parent a27b066 commit 69eae85

File tree

3 files changed

+8
-3
lines changed

3 files changed

+8
-3
lines changed

src/Tree.stories.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ const ListItem: React.FC<IListItemProps> = React.memo(({ item }) => {
129129
? (item.isActive ? <strong>{item.label}</strong> : <em>{item.label}</em>)
130130
: item.label
131131
}
132+
{` (${item.depth})`}
132133
{subItems}
133134
</li>
134135
);

src/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ export type TreeNode<T> = TreeSourceNode<T> & {
2222
isExpanded: boolean;
2323
isActive: boolean;
2424
isActiveTrail: boolean;
25+
depth: number;
2526
children: Tree<T>;
2627
};
2728

src/use-tree-loader.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -125,10 +125,11 @@ export function useTreeLoader<T>(
125125
const activeTrailIdsIndex = Object.fromEntries(activeTrailIds.map((id) => [id, true]));
126126
const expandedIdsIndex = expandedIds || {};
127127

128-
function buildOutputNode(node: TreeSourceNode<T>): TreeNode<T> {
128+
function buildOutputNode(node: TreeSourceNode<T>, depth: number): TreeNode<T> {
129129
const nodeId = node.id;
130130
const current = statefulNodes.current[nodeId];
131-
const mappedChildren = (children[nodeId] ? children[nodeId].items : []).map(buildOutputNode);
131+
const mappedChildren = (children[nodeId] ? children[nodeId].items : [])
132+
.map((child) => buildOutputNode(child, depth + 1));
132133
const isActive = activeId === nodeId;
133134
const isActiveTrail = !!activeTrailIdsIndex[nodeId];
134135
const isExpanded = expandedIdsIndex[nodeId] === true
@@ -138,6 +139,7 @@ export function useTreeLoader<T>(
138139
&& current.isExpanded === isExpanded
139140
&& current.isActiveTrail === isActiveTrail
140141
&& current.isActive === isActive
142+
&& current.depth === depth
141143
&& current.children.isLoading === isLoadingChildren
142144
&& valuesEqual(current.children.items, mappedChildren)) {
143145
// Item is still up-to-date. Return the same instance to allow React.memo magic.
@@ -148,14 +150,15 @@ export function useTreeLoader<T>(
148150
isExpanded,
149151
isActive,
150152
isActiveTrail,
153+
depth,
151154
children: { isLoading: isLoadingChildren, items: mappedChildren },
152155
};
153156
statefulNodes.current[nodeId] = outputNode;
154157
return outputNode;
155158
}
156159

157160
return {
158-
items: rootNodes.items.map(buildOutputNode),
161+
items: rootNodes.items.map((item) => buildOutputNode(item, 0)),
159162
isLoading: rootNodes.isLoading,
160163
allNodes: statefulNodes.current,
161164
};

0 commit comments

Comments
 (0)