@mui/x-tree-view
Version:
The community edition of the MUI X Tree View components.
88 lines (86 loc) • 3.04 kB
JavaScript
'use client';
import * as React from 'react';
import { useStore } from '@mui/x-internals/store';
import { useMergedRefs } from '@base-ui/utils/useMergedRefs';
import { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';
import { useTreeViewContext } from "../../TreeViewProvider/index.js";
import { TreeViewChildrenItemContext, TreeViewChildrenItemProvider } from "../../TreeViewProvider/TreeViewChildrenItemProvider.js";
import { TreeViewItemDepthContext } from "../../TreeViewItemDepthContext/index.js";
import { itemHasChildren } from "../../../hooks/useTreeItemUtils/useTreeItemUtils.js";
import { idSelectors } from "../id/index.js";
import { jsx as _jsx } from "react/jsx-runtime";
export const useJSXItemsItemPlugin = ({
props,
rootRef,
contentRef
}) => {
const {
store
} = useTreeViewContext();
const {
children,
disabled = false,
disableSelection = false,
label,
itemId,
id
} = props;
const parentContext = React.useContext(TreeViewChildrenItemContext);
if (parentContext == null) {
throw new Error(['MUI X: Could not find the Tree View Children Item context.', 'It looks like you rendered your component outside of a SimpleTreeView parent component.', 'This can also happen if you are bundling multiple versions of the Tree View.'].join('\n'));
}
const {
registerChild,
unregisterChild,
parentId
} = parentContext;
const expandable = itemHasChildren(children);
const pluginContentRef = React.useRef(null);
const handleContentRef = useMergedRefs(pluginContentRef, contentRef);
const idAttribute = useStore(store, idSelectors.treeItemIdAttribute, itemId, id);
// Prevent any flashing
useIsoLayoutEffect(() => {
registerChild(idAttribute, itemId);
return () => {
unregisterChild(idAttribute);
unregisterChild(idAttribute);
};
}, [store, registerChild, unregisterChild, idAttribute, itemId]);
useIsoLayoutEffect(() => {
return store.jsxItems.insertJSXItem({
id: itemId,
idAttribute: id,
parentId,
expandable,
disabled,
selectable: !disableSelection
});
}, [store, parentId, itemId, expandable, disabled, disableSelection, id]);
React.useEffect(() => {
if (label) {
return store.jsxItems.mapLabelFromJSX(itemId, (pluginContentRef.current?.textContent ?? '').toLowerCase());
}
return undefined;
}, [store, itemId, label]);
return {
contentRef: handleContentRef,
rootRef
};
};
export const jsxItemsitemWrapper = ({
children,
itemId,
idAttribute
}) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const depthContext = React.useContext(TreeViewItemDepthContext);
return /*#__PURE__*/_jsx(TreeViewChildrenItemProvider, {
itemId: itemId,
idAttribute: idAttribute,
children: /*#__PURE__*/_jsx(TreeViewItemDepthContext.Provider, {
value: depthContext + 1,
children: children
})
});
};
if (process.env.NODE_ENV !== "production") jsxItemsitemWrapper.displayName = "jsxItemsitemWrapper";