import { useCallback } from '@wordpress/element'; import { useDispatch, dispatch } from '@wordpress/data'; import { store as noticesStore } from '@wordpress/notices'; type NoticeType = 'default' | 'success' | 'warning' | 'error' | 'info'; interface NoticeOptions { id?: string; isDismissible?: boolean; type?: 'default' | 'snackbar'; actions?: Array< { label: string; onClick: () => void; variant?: 'primary' | 'secondary' | 'tertiary' | 'link'; } >; icon?: JSX.Element; explicitDismiss?: boolean; } // Standalone functions that don't require a hook export const showNotice = ( type: NoticeType, message: string, options?: NoticeOptions ) => { const defaultOptions: NoticeOptions = { type: 'snackbar', isDismissible: true, ...options, }; // @ts-ignore - WordPress notices store types return dispatch( noticesStore ).createNotice( type, message, defaultOptions ); }; export const showSuccess = ( message: string, options?: NoticeOptions ) => showNotice( 'success', message, options ); export const showError = ( message: string, options?: NoticeOptions ) => showNotice( 'error', message, options ); export const showWarning = ( message: string, options?: NoticeOptions ) => showNotice( 'warning', message, options ); export const showInfo = ( message: string, options?: NoticeOptions ) => showNotice( 'info', message, options ); export const removeNotice = ( id: string ) => { // @ts-ignore - WordPress notices store types return dispatch( noticesStore ).removeNotice( id ); }; // Hook version for components that need stable references export default function useNotice() { const { createNotice: wpCreateNotice, removeNotice: wpRemoveNotice } = useDispatch( noticesStore ); const hookShowNotice = useCallback( ( type: NoticeType, message: string, options?: NoticeOptions ) => { const defaultOptions: NoticeOptions = { type: 'snackbar', isDismissible: true, ...options, }; // @ts-ignore - WordPress notices store types return wpCreateNotice( type, message, defaultOptions ); }, [ wpCreateNotice ] ); const hookShowSuccess = useCallback( ( message: string, options?: NoticeOptions ) => hookShowNotice( 'success', message, options ), [ hookShowNotice ] ); const hookShowError = useCallback( ( message: string, options?: NoticeOptions ) => hookShowNotice( 'error', message, options ), [ hookShowNotice ] ); const hookShowWarning = useCallback( ( message: string, options?: NoticeOptions ) => hookShowNotice( 'warning', message, options ), [ hookShowNotice ] ); const hookShowInfo = useCallback( ( message: string, options?: NoticeOptions ) => hookShowNotice( 'info', message, options ), [ hookShowNotice ] ); return { showNotice: hookShowNotice, showSuccess: hookShowSuccess, showError: hookShowError, showWarning: hookShowWarning, showInfo: hookShowInfo, removeNotice: wpRemoveNotice, }; }