@wordpress/components
Version:
UI components for WordPress.
88 lines (87 loc) • 2.45 kB
JavaScript
import { v4 } from "uuid";
import { forwardRef, useMemo, useState } from "@wordpress/element";
import { createHigherOrderComponent } from "@wordpress/compose";
import NoticeList from "../../notice/list.mjs";
import { jsx } from "react/jsx-runtime";
// packages/components/src/higher-order/with-notices/index.tsx
/**
* 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 with_notices_default = createHigherOrderComponent((OriginalComponent) => {
function Component(props, ref) {
const [noticeList, setNoticeList] = useState([]);
const noticeOperations = useMemo(() => {
const createNotice = (notice) => {
const noticeToAdd = notice.id ? notice : {
...notice,
id: v4()
};
setNoticeList((current) => [...current, noticeToAdd]);
};
return {
createNotice,
createErrorNotice: (msg) => {
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__ */ jsx(NoticeList, {
className: "components-with-notices-ui",
notices: noticeList,
onRemove: noticeOperations.removeNotice
})
};
return isForwardRef ? /* @__PURE__ */ jsx(OriginalComponent, {
...propsOut,
ref
}) : /* @__PURE__ */ jsx(OriginalComponent, { ...propsOut });
}
let isForwardRef;
const { render } = OriginalComponent;
if (typeof render === "function") {
isForwardRef = true;
return forwardRef(Component);
}
return Component;
}, "withNotices");
export { with_notices_default as default };
//# sourceMappingURL=index.mjs.map