@hitachivantara/uikit-react-core
Version:
Core React components for the NEXT Design System.
67 lines (66 loc) • 2.01 kB
JavaScript
import * as React from "react";
import { useEventCallback } from "@mui/material/utils";
import { populateInstance } from "../utils.js";
const useTreeViewExpansion = ({ instance, params, models }) => {
const isNodeExpanded = React.useCallback(
(nodeId) => {
return Array.isArray(models.expanded.value) ? models.expanded.value.indexOf(nodeId) !== -1 : false;
},
[models.expanded.value]
);
const isNodeExpandable = React.useCallback(
(nodeId) => !!instance.getNode(nodeId)?.expandable,
[instance]
);
const toggleNodeExpansion = useEventCallback(
(event, nodeId) => {
if (nodeId == null) {
return;
}
let newExpanded;
if (models.expanded.value.indexOf(nodeId) !== -1) {
newExpanded = models.expanded.value.filter((id) => id !== nodeId);
} else {
newExpanded = [nodeId].concat(models.expanded.value);
}
if (params.onNodeToggle) {
params.onNodeToggle(event, newExpanded);
}
models.expanded.setValue(newExpanded);
}
);
const expandAllSiblings = (event, nodeId) => {
const node = instance.getNode(nodeId);
const siblings = instance.getChildrenIds(node.parentId);
const diff = siblings.filter(
(child) => instance.isNodeExpandable(child) && !instance.isNodeExpanded(child)
);
const newExpanded = models.expanded.value.concat(diff);
if (diff.length > 0) {
models.expanded.setValue(newExpanded);
if (params.onNodeToggle) {
params.onNodeToggle(event, newExpanded);
}
}
};
populateInstance(instance, {
isNodeExpanded,
isNodeExpandable,
toggleNodeExpansion,
expandAllSiblings
});
};
useTreeViewExpansion.models = {
expanded: {
controlledProp: "expanded",
defaultProp: "defaultExpanded"
}
};
const DEFAULT_EXPANDED = [];
useTreeViewExpansion.getDefaultizedParams = (params) => ({
...params,
defaultExpanded: params.defaultExpanded ?? DEFAULT_EXPANDED
});
export {
useTreeViewExpansion
};