@wordpress/components
Version:
UI components for WordPress.
76 lines (59 loc) • 2.65 kB
JavaScript
import { cx as _cx } from "emotion";
/**
* WordPress dependencies
*/
import warn from '@wordpress/warning';
/**
* Internal dependencies
*/
import { useComponentsContext } from './context-system-provider';
import { getNamespace, getConnectedNamespace } from './utils';
import { getStyledClassNameFromKey } from './get-styled-class-name-from-key';
/* eslint-disable jsdoc/valid-types */
/**
* @template TProps
* @typedef {TProps & { className: string; children?: import('react').ReactNode }} ConnectedProps
*/
/* eslint-enable jsdoc/valid-types */
/**
* Custom hook that derives registered props from the Context system.
* These derived props are then consolidated with incoming component props.
*
* @template {{ className?: string }} P
* @param {P} props Incoming props from the component.
* @param {string} namespace The namespace to register and to derive context props from.
* @return {ConnectedProps<P>} The connected props.
*/
export function useContextSystem(props, namespace) {
const contextSystemProps = useComponentsContext();
if (typeof namespace === 'undefined') {
typeof process !== "undefined" && process.env && process.env.NODE_ENV !== "production" ? warn('useContextSystem: Please provide a namespace') : void 0;
}
const contextProps = (contextSystemProps === null || contextSystemProps === void 0 ? void 0 : contextSystemProps[namespace]) || {};
/* eslint-disable jsdoc/no-undefined-types */
/** @type {ConnectedProps<P>} */
// @ts-ignore We fill in the missing properties below
const finalComponentProps = { ...getConnectedNamespace(),
...getNamespace(namespace)
};
/* eslint-enable jsdoc/no-undefined-types */
const {
_overrides: overrideProps,
...otherContextProps
} = contextProps;
const initialMergedProps = Object.entries(otherContextProps).length ? Object.assign({}, otherContextProps, props) : props;
const classes = _cx(getStyledClassNameFromKey(namespace), props.className); // Provides the ability to customize the render of the component.
const rendered = typeof initialMergedProps.renderChildren === 'function' ? initialMergedProps.renderChildren(initialMergedProps) : initialMergedProps.children;
for (const key in initialMergedProps) {
// @ts-ignore filling in missing props
finalComponentProps[key] = initialMergedProps[key];
}
for (const key in overrideProps) {
// @ts-ignore filling in missing props
finalComponentProps[key] = overrideProps[key];
}
finalComponentProps.children = rendered;
finalComponentProps.className = classes;
return finalComponentProps;
}
//# sourceMappingURL=use-context-system.js.map