grafana/public/app/core/copy/appNotification.ts

91 lines
2.3 KiB
TypeScript
Raw Normal View History

import { useMemo } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { getMessageFromError } from 'app/core/utils/errors';
import { AppNotification, AppNotificationSeverity, useDispatch } from 'app/types';
import { notifyApp } from '../actions';
2018-10-24 07:33:53 -05:00
const defaultSuccessNotification = {
2018-10-24 07:33:53 -05:00
title: '',
text: '',
severity: AppNotificationSeverity.Success,
icon: 'check',
2018-10-24 07:33:53 -05:00
};
const defaultWarningNotification = {
2018-10-24 07:33:53 -05:00
title: '',
text: '',
severity: AppNotificationSeverity.Warning,
icon: 'exclamation-triangle',
2018-10-24 07:33:53 -05:00
};
const defaultErrorNotification = {
2018-10-24 07:33:53 -05:00
title: '',
text: '',
severity: AppNotificationSeverity.Error,
icon: 'exclamation-triangle',
2018-10-24 07:33:53 -05:00
};
export const createSuccessNotification = (title: string, text = '', traceId?: string): AppNotification => ({
2018-10-24 07:33:53 -05:00
...defaultSuccessNotification,
title,
text,
id: uuidv4(),
timestamp: Date.now(),
showing: true,
2018-10-24 07:33:53 -05:00
});
export const createErrorNotification = (
title: string,
text: string | Error = '',
traceId?: string,
component?: React.ReactElement
): AppNotification => {
2019-02-05 07:42:29 -06:00
return {
...defaultErrorNotification,
text: getMessageFromError(text),
title,
id: uuidv4(),
traceId,
component,
timestamp: Date.now(),
showing: true,
2019-02-05 07:42:29 -06:00
};
};
2018-10-24 07:33:53 -05:00
export const createWarningNotification = (title: string, text = '', traceId?: string): AppNotification => ({
2018-10-24 07:33:53 -05:00
...defaultWarningNotification,
title,
text,
traceId,
id: uuidv4(),
timestamp: Date.now(),
showing: true,
2018-10-24 07:33:53 -05:00
});
/** Hook for showing toast notifications with varying severity (success, warning error).
* @example
* const notifyApp = useAppNotification();
* notifyApp.success('Success!', 'Some additional text');
* notifyApp.warning('Warning!');
* notifyApp.error('Error!');
*/
export function useAppNotification() {
const dispatch = useDispatch();
return useMemo(
() => ({
success: (title: string, text = '') => {
dispatch(notifyApp(createSuccessNotification(title, text)));
},
warning: (title: string, text = '', traceId?: string) => {
dispatch(notifyApp(createWarningNotification(title, text, traceId)));
},
error: (title: string, text = '', traceId?: string) => {
dispatch(notifyApp(createErrorNotification(title, text, traceId)));
},
}),
[dispatch]
);
}