@wordpress/components
Version:
UI components for WordPress.
64 lines (58 loc) • 1.71 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useCx = void 0;
var _react = require("@emotion/react");
var _utils = require("@emotion/utils");
var _css = require("@emotion/css");
var _element = require("@wordpress/element");
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
const isSerializedStyles = o => typeof o !== 'undefined' && o !== null && ['name', 'styles'].every(p => typeof o[p] !== 'undefined');
/**
* Retrieve a `cx` function that knows how to handle `SerializedStyles`
* returned by the `@emotion/react` `css` function in addition to what
* `cx` normally knows how to handle. It also hooks into the Emotion
* Cache, allowing `css` calls to work inside iframes.
*
* ```jsx
* import { css } from '@emotion/react';
*
* const styles = css`
* color: red
* `;
*
* function RedText( { className, ...props } ) {
* const cx = useCx();
*
* const classes = cx(styles, className);
*
* return <span className={classes} {...props} />;
* }
* ```
*/
const useCx = () => {
const cache = (0, _react.__unsafe_useEmotionCache)();
const cx = (0, _element.useCallback)((...classNames) => {
if (cache === null) {
throw new Error('The `useCx` hook should be only used within a valid Emotion Cache Context');
}
return (0, _css.cx)(...classNames.map(arg => {
if (isSerializedStyles(arg)) {
(0, _utils.insertStyles)(cache, arg, false);
return `${cache.key}-${arg.name}`;
}
return arg;
}));
}, [cache]);
return cx;
};
exports.useCx = useCx;
//# sourceMappingURL=use-cx.js.map