Skip to content

Commit 2b7062b

Browse files
authored
feat: add collapse all tree nodes functionality (#159)
1 parent 8a7175a commit 2b7062b

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

app/hooks/useVirtualTree.ts

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,10 @@ type BlurAction = {
102102
type: "BLUR";
103103
};
104104

105+
type CollapseAllNodesAction = {
106+
type: "COLLAPSE_ALL_NODES"
107+
};
108+
105109
type TreeAction =
106110
| ToggleNodeAction
107111
| MoveNodeAction
@@ -111,7 +115,8 @@ type TreeAction =
111115
| MoveLeftAction
112116
| RestoreStateAction
113117
| ExpandAllOnPathAction
114-
| BlurAction;
118+
| BlurAction
119+
| CollapseAllNodesAction;
115120

116121
function expandNode<T extends { id: string; children?: T[] }>(
117122
state: TreeState<T>,
@@ -225,6 +230,14 @@ export function useVirtualTree<T extends { id: string; children?: T[] }, R>(
225230
}
226231
}
227232
}
233+
case "COLLAPSE_ALL_NODES": {
234+
// Reduce from the right, so that the
235+
// focusedNodeId is set to the top-level node.
236+
return state.items.reduceRight(
237+
(nextState, item) => collapseNode<T>(nextState, item.id),
238+
state
239+
);
240+
}
228241
case "FOCUS_NODE": {
229242
const itemIndex = state.items.findIndex(({ id }) => id === action.id);
230243

@@ -653,10 +666,14 @@ function createTreeProps<T extends { id: string; children?: T[] }>(
653666
}
654667
case "Left":
655668
case "ArrowLeft": {
656-
dispatch({
657-
type: "MOVE_LEFT",
658-
source: e.nativeEvent,
659-
});
669+
if (e.altKey) {
670+
dispatch({ type: "COLLAPSE_ALL_NODES" });
671+
} else {
672+
dispatch({
673+
type: "MOVE_LEFT",
674+
source: e.nativeEvent,
675+
});
676+
}
660677
e.preventDefault();
661678

662679
break;

0 commit comments

Comments
 (0)