2020-03-03 10:26:02 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2020-03-10 13:39:21 +00:00
|
|
|
import { useStoreNoticesContext } from '@woocommerce/base-context';
|
2020-05-10 23:41:10 +00:00
|
|
|
import { useMemo, useRef, useEffect } from '@wordpress/element';
|
2020-03-03 10:26:02 +00:00
|
|
|
|
|
|
|
export const useStoreNotices = () => {
|
2020-03-16 20:57:12 +00:00
|
|
|
const {
|
|
|
|
notices,
|
|
|
|
createNotice,
|
|
|
|
removeNotice,
|
|
|
|
createSnackbarNotice,
|
2020-05-14 23:55:22 +00:00
|
|
|
setIsSuppressed,
|
2020-03-16 20:57:12 +00:00
|
|
|
} = useStoreNoticesContext();
|
2020-05-10 23:41:10 +00:00
|
|
|
// Added to a ref so the surface for notices doesn't change frequently
|
|
|
|
// and thus can be used as dependencies on effects.
|
|
|
|
const currentNotices = useRef( notices );
|
|
|
|
|
|
|
|
// Update notices ref whenever they change
|
|
|
|
useEffect( () => {
|
|
|
|
currentNotices.current = notices;
|
|
|
|
}, [ notices ] );
|
2020-03-03 10:26:02 +00:00
|
|
|
|
2020-03-30 14:32:23 +00:00
|
|
|
const noticesApi = useMemo(
|
2020-05-10 23:41:10 +00:00
|
|
|
() => ( {
|
|
|
|
hasNoticesOfType: ( type ) => {
|
|
|
|
return currentNotices.current.some(
|
|
|
|
( notice ) => notice.type === type
|
|
|
|
);
|
|
|
|
},
|
|
|
|
removeNotices: ( status = null ) => {
|
2020-09-18 18:50:45 +00:00
|
|
|
currentNotices.current.forEach( ( notice ) => {
|
2020-05-10 23:41:10 +00:00
|
|
|
if ( status === null || notice.status === status ) {
|
|
|
|
removeNotice( notice.id );
|
|
|
|
}
|
|
|
|
} );
|
|
|
|
},
|
|
|
|
removeNotice,
|
|
|
|
} ),
|
|
|
|
[ removeNotice ]
|
|
|
|
);
|
|
|
|
|
|
|
|
const noticeCreators = useMemo(
|
2020-03-30 14:32:23 +00:00
|
|
|
() => ( {
|
|
|
|
addDefaultNotice: ( text, noticeProps = {} ) =>
|
|
|
|
void createNotice( 'default', text, {
|
|
|
|
...noticeProps,
|
|
|
|
} ),
|
|
|
|
addErrorNotice: ( text, noticeProps = {} ) =>
|
|
|
|
void createNotice( 'error', text, {
|
|
|
|
...noticeProps,
|
|
|
|
} ),
|
|
|
|
addWarningNotice: ( text, noticeProps = {} ) =>
|
|
|
|
void createNotice( 'warning', text, {
|
|
|
|
...noticeProps,
|
|
|
|
} ),
|
|
|
|
addInfoNotice: ( text, noticeProps = {} ) =>
|
|
|
|
void createNotice( 'info', text, {
|
|
|
|
...noticeProps,
|
|
|
|
} ),
|
|
|
|
addSuccessNotice: ( text, noticeProps = {} ) =>
|
|
|
|
void createNotice( 'success', text, {
|
|
|
|
...noticeProps,
|
|
|
|
} ),
|
|
|
|
addSnackbarNotice: ( text, noticeProps = {} ) => {
|
|
|
|
createSnackbarNotice( text, noticeProps );
|
|
|
|
},
|
|
|
|
} ),
|
2020-05-10 23:41:10 +00:00
|
|
|
[ createNotice, createSnackbarNotice ]
|
2020-03-30 14:32:23 +00:00
|
|
|
);
|
2020-03-03 10:26:02 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
notices,
|
|
|
|
...noticesApi,
|
2020-05-10 23:41:10 +00:00
|
|
|
...noticeCreators,
|
2020-05-14 23:55:22 +00:00
|
|
|
setIsSuppressed,
|
2020-03-03 10:26:02 +00:00
|
|
|
};
|
|
|
|
};
|