UNPKG

@mui/x-tree-view

Version:

The community edition of the MUI X Tree View components.

51 lines (45 loc) 1.8 kB
import { lruMemoize, createSelectorCreator } from 'reselect'; const reselectCreateSelector = createSelectorCreator({ memoize: lruMemoize, memoizeOptions: { maxSize: 1, equalityCheck: Object.is } }); const cache = new WeakMap(); /** * Type of a selector that take the whole tree view state as input and returns a value based on a required plugin. * @param {TreeViewState} state The state of the Tree View. * @returns {any | undefined} The value of the plugin state. */ /** * Type of a selector that take the whole tree view state as input and returns a value based on an optional plugin. * * @param {TreeViewState} state The state of the Tree View. * @returns {any | undefined} The value of the plugin state or undefined if the plugin is not registered. */ /** * Method wrapping reselect's createSelector to provide caching for tree view instances. * */ export const createSelector = (...createSelectorArgs) => { const selector = (state, selectorArgs) => { const cacheKey = state.cacheKey; // If there is no cache for the current tree view instance, create one. let cacheForCurrentTreeViewInstance = cache.get(cacheKey); if (!cacheForCurrentTreeViewInstance) { cacheForCurrentTreeViewInstance = new Map(); cache.set(cacheKey, cacheForCurrentTreeViewInstance); } // If there is a cached selector, execute it. const cachedSelector = cacheForCurrentTreeViewInstance.get(createSelectorArgs); if (cachedSelector) { return cachedSelector(state, selectorArgs); } // Otherwise, create a new selector and cache it and execute it. const fn = reselectCreateSelector(...createSelectorArgs); cacheForCurrentTreeViewInstance.set(createSelectorArgs, fn); return fn(state, selectorArgs); }; return selector; };