UNPKG

@mui/x-tree-view

Version:

The community edition of the MUI X Tree View components.

86 lines (84 loc) 2.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useApplyPropagationToSelectedItemsOnMount = useApplyPropagationToSelectedItemsOnMount; var _useRefWithInit = require("@base-ui/utils/useRefWithInit"); var _TreeViewSelectionPlugin = require("../internals/plugins/selection/TreeViewSelectionPlugin"); const defaultGetItemId = item => item.id; const defaultGetItemChildren = item => item.children; /** * Applies the selection propagation rules to the selected items. * The value is only computed during the first render, any update of the parameters will be ignored. * * Uncontrolled example: * ```tsx * const defaultSelectedItems = useApplyPropagationToSelectedItemsOnMount({ * items: props.items, * selectionPropagation: props.selectionPropagation, * selectedItems: ['10', '11', '13', '14'], * }); * * return ( * <RichTreeView * items={props.items} * selectionPropagation={props.selectionPropagation} * defaultSelectedItems={defaultSelectedItems} * /> * ); * ``` * * Controlled example: * ```tsx * const initialSelectedItems = useApplyPropagationToSelectedItemsOnMount({ * items: props.items, * selectionPropagation: props.selectionPropagation, * selectedItems: ['10', '11', '13', '14'], * }); * * const [selectedItems, setSelectedItems] = React.useState(initialSelectedItems); * * return ( * <RichTreeView * items={props.items} * selectionPropagation={props.selectionPropagation} * selectedItems={selectedItems} * onSelectedItemsChange={setSelectedItems} * /> * ); * ``` */ function useApplyPropagationToSelectedItemsOnMount(parameters) { const { items: itemsParam, getItemId = defaultGetItemId, getItemChildren = defaultGetItemChildren, selectedItems, selectionPropagation } = parameters; return (0, _useRefWithInit.useRefWithInit)(() => { const lookup = (0, _TreeViewSelectionPlugin.getLookupFromArray)(selectedItems); function walk(items, isParentSelected) { for (const item of items) { const itemId = getItemId(item); let isSelected = lookup[itemId]; if (!isSelected && selectionPropagation.descendants && isParentSelected) { lookup[itemId] = true; isSelected = true; } const children = getItemChildren(item) ?? []; if (children.length > 0) { walk(children, isSelected); if (!isSelected && selectionPropagation.parents) { const areAllChildrenSelected = children.every(childId => lookup[getItemId(childId)]); if (areAllChildrenSelected) { lookup[itemId] = true; } } } } } walk(itemsParam, false); return Object.keys(lookup); }).current; }