UNPKG

@mui/x-tree-view

Version:

The community edition of the MUI X Tree View components.

109 lines (108 loc) 3.19 kB
import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import useForkRef from '@mui/utils/useForkRef'; import { TREE_VIEW_CORE_PLUGINS } from "../corePlugins/index.js"; import { useExtractPluginParamsFromProps } from "./useExtractPluginParamsFromProps.js"; import { useTreeViewBuildContext } from "./useTreeViewBuildContext.js"; import { TreeViewStore } from "../utils/TreeViewStore.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; } let globalId = 0; /** * 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 instanceRef = React.useRef({}); const instance = instanceRef.current; const publicAPI = useTreeViewApiInitialization(apiRef); const innerRootRef = React.useRef(null); const handleRootRef = useForkRef(innerRootRef, rootRef); const storeRef = React.useRef(null); if (storeRef.current == null) { globalId += 1; const initialState = { cacheKey: { id: globalId } }; plugins.forEach(plugin => { if (plugin.getInitialState) { Object.assign(initialState, plugin.getInitialState(pluginParams)); } }); storeRef.current = new TreeViewStore(initialState); } const contextValue = useTreeViewBuildContext({ plugins, instance, publicAPI: publicAPI.current, store: storeRef.current, rootRef: innerRootRef }); const rootPropsGetters = []; const runPlugin = plugin => { const pluginResponse = plugin({ instance, params: pluginParams, rootRef: innerRootRef, plugins, store: storeRef.current }); 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 }; };