UNPKG

@mui/x-tree-view

Version:

The community edition of the MUI X Tree View components.

56 lines (54 loc) 2.53 kB
'use client'; import * as React from 'react'; import PropTypes from 'prop-types'; import { useTreeViewContext } from "./TreeViewContext.js"; import { escapeOperandAttributeSelector } from "../utils/utils.js"; import { itemsSelectors } from "../plugins/items/selectors.js"; import { jsx as _jsx } from "react/jsx-runtime"; export const TreeViewChildrenItemContext = /*#__PURE__*/React.createContext(null); if (process.env.NODE_ENV !== "production") TreeViewChildrenItemContext.displayName = "TreeViewChildrenItemContext"; export function TreeViewChildrenItemProvider(props) { const { children, itemId = null, idAttribute } = props; const { store, rootRef } = useTreeViewContext(); const childrenIdAttrToIdRef = React.useRef(new Map()); React.useEffect(() => { if (!rootRef.current) { return; } const previousChildrenIds = itemsSelectors.itemOrderedChildrenIds(store.state, itemId ?? null) ?? []; const escapedIdAttr = escapeOperandAttributeSelector(idAttribute ?? rootRef.current.id); // If collapsed, skip childrenIds update prevents clearing the parent's indeterminate state after opening a sibling. if (itemId != null) { const itemRoot = rootRef.current.querySelector(`*[id="${escapedIdAttr}"][role="treeitem"]`); if (itemRoot && itemRoot.getAttribute('aria-expanded') === 'false') { return; } } const childrenElements = rootRef.current.querySelectorAll(`${itemId == null ? '' : `*[id="${escapedIdAttr}"] `}[role="treeitem"]:not(*[id="${escapedIdAttr}"] [role="treeitem"] [role="treeitem"])`); const childrenIds = Array.from(childrenElements).map(child => childrenIdAttrToIdRef.current.get(child.id)); const hasChanged = childrenIds.length !== previousChildrenIds.length || childrenIds.some((childId, index) => childId !== previousChildrenIds[index]); if (hasChanged) { store.jsxItems.setJSXItemsOrderedChildrenIds(itemId ?? null, childrenIds); } }); const value = React.useMemo(() => ({ registerChild: (childIdAttribute, childItemId) => childrenIdAttrToIdRef.current.set(childIdAttribute, childItemId), unregisterChild: childIdAttribute => childrenIdAttrToIdRef.current.delete(childIdAttribute), parentId: itemId }), [itemId]); return /*#__PURE__*/_jsx(TreeViewChildrenItemContext.Provider, { value: value, children: children }); } process.env.NODE_ENV !== "production" ? TreeViewChildrenItemProvider.propTypes = { children: PropTypes.node, id: PropTypes.string } : void 0;