UNPKG

@mui/x-tree-view

Version:

The community edition of the MUI X Tree View components.

102 lines (101 loc) 3.06 kB
import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import { useRefWithInit } from '@base-ui/utils/useRefWithInit'; import { Store } from '@mui/x-internals/store'; import { useMergedRefs } from '@base-ui/utils/useMergedRefs'; import { TREE_VIEW_CORE_PLUGINS } from "../corePlugins/index.js"; import { useExtractPluginParamsFromProps } from "./useExtractPluginParamsFromProps.js"; import { useTreeViewBuildContext } from "./useTreeViewBuildContext.js"; function initializeInputApiRef(inputApiRef) { if (inputApiRef.current == null) { inputApiRef.current = {}; } return inputApiRef; } export function useTreeViewApiInitialization(inputApiRef) { const fallbackPublicApiRef = React.useRef({}); if (inputApiRef) { return initializeInputApiRef(inputApiRef); } return fallbackPublicApiRef; } /** * This is the main hook that sets the plugin system up for the tree-view. * * It manages the data used to create the tree-view. * * @param plugins All the plugins that will be used in the tree-view. * @param props The props passed to the tree-view. * @param rootRef The ref of the root element. */ export const useTreeView = ({ plugins: inPlugins, rootRef, props }) => { const plugins = React.useMemo(() => [...TREE_VIEW_CORE_PLUGINS, ...inPlugins], [inPlugins]); const { pluginParams, forwardedProps, apiRef } = useExtractPluginParamsFromProps({ plugins, props }); const instance = useRefWithInit(() => ({})).current; const publicAPI = useTreeViewApiInitialization(apiRef); const innerRootRef = React.useRef(null); const handleRootRef = useMergedRefs(innerRootRef, rootRef); const store = useRefWithInit(() => { const initialState = {}; for (const plugin of plugins) { if (plugin.getInitialState) { Object.assign(initialState, plugin.getInitialState(pluginParams)); } } return new Store(initialState); }).current; const contextValue = useTreeViewBuildContext({ plugins, instance, publicAPI: publicAPI.current, store, rootRef: innerRootRef }); const rootPropsGetters = []; const runPlugin = plugin => { const pluginResponse = plugin({ instance, params: pluginParams, rootRef: innerRootRef, plugins, store }); if (pluginResponse.getRootProps) { rootPropsGetters.push(pluginResponse.getRootProps); } if (pluginResponse.publicAPI) { Object.assign(publicAPI.current, pluginResponse.publicAPI); } if (pluginResponse.instance) { Object.assign(instance, pluginResponse.instance); } }; plugins.forEach(runPlugin); const getRootProps = (otherHandlers = {}) => { const rootProps = _extends({ role: 'tree' }, forwardedProps, otherHandlers, { ref: handleRootRef }); rootPropsGetters.forEach(rootPropsGetter => { Object.assign(rootProps, rootPropsGetter(otherHandlers)); }); return rootProps; }; return { getRootProps, rootRef: handleRootRef, contextValue }; };