@wordpress/components
Version:
UI components for WordPress.
118 lines (101 loc) • 3.2 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _element = require("@wordpress/element");
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _uuid = require("uuid");
var _compose = require("@wordpress/compose");
var _list = _interopRequireDefault(require("../../notice/list"));
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Override the default edit UI to include notices if supported.
*
* Wrapping the original component with `withNotices` encapsulates the component
* with the additional props `noticeOperations` and `noticeUI`.
*
* ```jsx
* import { withNotices, Button } from '@wordpress/components';
*
* const MyComponentWithNotices = withNotices(
* ( { noticeOperations, noticeUI } ) => {
* const addError = () =>
* noticeOperations.createErrorNotice( 'Error message' );
* return (
* <div>
* { noticeUI }
* <Button variant="secondary" onClick={ addError }>
* Add error
* </Button>
* </div>
* );
* }
* );
* ```
*
* @param OriginalComponent Original component.
*
* @return Wrapped component.
*/
var _default = (0, _compose.createHigherOrderComponent)(OriginalComponent => {
function Component(props, ref) {
const [noticeList, setNoticeList] = (0, _element.useState)([]);
const noticeOperations = (0, _element.useMemo)(() => {
const createNotice = notice => {
const noticeToAdd = notice.id ? notice : { ...notice,
id: (0, _uuid.v4)()
};
setNoticeList(current => [...current, noticeToAdd]);
};
return {
createNotice,
createErrorNotice: msg => {
// @ts-expect-error TODO: Missing `id`, potentially a bug
createNotice({
status: 'error',
content: msg
});
},
removeNotice: id => {
setNoticeList(current => current.filter(notice => notice.id !== id));
},
removeAllNotices: () => {
setNoticeList([]);
}
};
}, []);
const propsOut = { ...props,
noticeList,
noticeOperations,
noticeUI: noticeList.length > 0 && (0, _element.createElement)(_list.default, {
className: "components-with-notices-ui",
notices: noticeList,
onRemove: noticeOperations.removeNotice
})
};
return isForwardRef ? (0, _element.createElement)(OriginalComponent, (0, _extends2.default)({}, propsOut, {
ref: ref
})) : (0, _element.createElement)(OriginalComponent, propsOut);
}
let isForwardRef; // @ts-expect-error - `render` will only be present when OriginalComponent was wrapped with forwardRef().
const {
render
} = OriginalComponent; // Returns a forwardRef if OriginalComponent appears to be a forwardRef.
if (typeof render === 'function') {
isForwardRef = true;
return (0, _element.forwardRef)(Component);
}
return Component;
}, 'withNotices');
exports.default = _default;
//# sourceMappingURL=index.js.map