UNPKG

@wordpress/components

Version:
108 lines (107 loc) 3.17 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _uuid = require("uuid"); var _element = require("@wordpress/element"); var _compose = require("@wordpress/compose"); var _list = _interopRequireDefault(require("../../notice/list")); var _jsxRuntime = require("react/jsx-runtime"); /** * 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 = exports.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 && /*#__PURE__*/(0, _jsxRuntime.jsx)(_list.default, { className: "components-with-notices-ui", notices: noticeList, onRemove: noticeOperations.removeNotice }) }; return isForwardRef ? /*#__PURE__*/(0, _jsxRuntime.jsx)(OriginalComponent, { ...propsOut, ref: ref }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(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'); //# sourceMappingURL=index.js.map