UNPKG

dreamstate

Version:

Store management library based on react context and observers

55 lines (52 loc) 2.87 kB
import { DreamstateError } from '../error/DreamstateError.js'; import { ContextManager } from '../management/ContextManager.js'; import { createCombinedProvider } from './combined/createCombinedProvider.js'; import { createScopedProvider } from './scoped/createScopedProvider.js'; import { EDreamstateErrorCode } from '../../types/error.js'; /** * Method for creation of a component that provides React contexts and observes context changes. * * This function generates a React provider component that listens to changes in context state, * using the provided context managers and their corresponding configurations. The created provider * component can be used to wrap parts of the React component tree, making data from the context managers * available to all components within the tree via hooks like `useManager` and `useContext`. * * @param {Array<IContextManagerConstructor>} sources - An array of context manager class references * that should be provided as context in the React tree when the returned provider component renders. * @param {ICreateProviderProps} config - Configuration options for the store provider. * @param {boolean} config.isCombined - A flag that determines whether to observe the context changes * in one large React node or as smaller scoped nodes for better performance. * @returns {FunctionComponent} A React function component that acts as a provider for the specified * context manager classes, making their data accessible to the React tree. * * @throws {TypeError} If the `sources` parameter is not an array. * @throws {TypeError} If any object in the `sources` array is not a class that extends `ContextManager`. */ function createProvider(sources, config) { if (config === void 0) { config = {}; } /* * Validate provision sources parameter. * Supplied 'sources' should contain array of context manager class references. */ if (!Array.isArray(sources) || !sources.length) { throw new DreamstateError(EDreamstateErrorCode.INCORRECT_PARAMETER, "Only array of context managers is acceptable."); } /* * Validate provision sources on creation stage before actual component rendering. * All classes should be valid context managers with correct metadata and core methods. */ for (var it_1 = 0; it_1 < sources.length; it_1++) { if (!sources[it_1] || !(sources[it_1].prototype instanceof ContextManager)) { throw new DreamstateError(EDreamstateErrorCode.TARGET_CONTEXT_MANAGER_EXPECTED, "'".concat(String(sources[it_1]), "' is in sources array.")); } } /* * Supply two different versions of provision creation. * Combined - pre v4 variant with single observer. * Scoped - new v4 variant with separated react nodes. */ return config.isCombined ? createCombinedProvider(sources) : createScopedProvider(sources); } export { createProvider };