Skip to content

Commit

Permalink
feat: add collapse all tree nodes functionality (#159)
Browse files Browse the repository at this point in the history
  • Loading branch information
SSHari committed May 24, 2023
1 parent 8a7175a commit 2b7062b
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions app/hooks/useVirtualTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ type BlurAction = {
type: "BLUR";
};

type CollapseAllNodesAction = {
type: "COLLAPSE_ALL_NODES"
};

type TreeAction =
| ToggleNodeAction
| MoveNodeAction
Expand All @@ -111,7 +115,8 @@ type TreeAction =
| MoveLeftAction
| RestoreStateAction
| ExpandAllOnPathAction
| BlurAction;
| BlurAction
| CollapseAllNodesAction;

function expandNode<T extends { id: string; children?: T[] }>(
state: TreeState<T>,
Expand Down Expand Up @@ -225,6 +230,14 @@ export function useVirtualTree<T extends { id: string; children?: T[] }, R>(
}
}
}
case "COLLAPSE_ALL_NODES": {
// Reduce from the right, so that the
// focusedNodeId is set to the top-level node.
return state.items.reduceRight(
(nextState, item) => collapseNode<T>(nextState, item.id),
state
);
}
case "FOCUS_NODE": {
const itemIndex = state.items.findIndex(({ id }) => id === action.id);

Expand Down Expand Up @@ -653,10 +666,14 @@ function createTreeProps<T extends { id: string; children?: T[] }>(
}
case "Left":
case "ArrowLeft": {
dispatch({
type: "MOVE_LEFT",
source: e.nativeEvent,
});
if (e.altKey) {
dispatch({ type: "COLLAPSE_ALL_NODES" });
} else {
dispatch({
type: "MOVE_LEFT",
source: e.nativeEvent,
});
}
e.preventDefault();

break;
Expand Down

0 comments on commit 2b7062b

Please sign in to comment.