useNotifications.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { ref } from 'vue'
  3. import getUuid from '#shared/utils/getUuid.ts'
  4. import { NotificationTypes } from './types.ts'
  5. import type { NewNotification, Notification } from './types.ts'
  6. const notifications = ref<Notification[]>([])
  7. const defaultNotificationDurationMS = 3000
  8. const removeNotification = (id: string) => {
  9. notifications.value = notifications.value.filter(
  10. (notification: Notification) => notification.id !== id,
  11. )
  12. }
  13. const clearAllNotifications = () => {
  14. notifications.value = []
  15. }
  16. const useNotifications = () => {
  17. const notify = (notification: NewNotification): string => {
  18. let { id } = notification
  19. const { unique = true } = notification
  20. if (!id) {
  21. id = getUuid()
  22. }
  23. const newNotification: Notification = { id, timeout: 0, ...notification }
  24. if (unique) {
  25. notifications.value = notifications.value.filter(
  26. (notification: Notification) => {
  27. const isSame = notification.id === id
  28. if (isSame) {
  29. window.clearTimeout(notification.timeout)
  30. }
  31. return !isSame
  32. },
  33. )
  34. }
  35. notifications.value.push(newNotification)
  36. if (!newNotification.persistent) {
  37. newNotification.timeout = window.setTimeout(() => {
  38. removeNotification(newNotification.id)
  39. }, newNotification.durationMS || defaultNotificationDurationMS)
  40. }
  41. return newNotification.id
  42. }
  43. const hasErrors = () => {
  44. return notifications.value.some((notification) => {
  45. return notification.type === NotificationTypes.Error
  46. })
  47. }
  48. return {
  49. notify,
  50. notifications,
  51. removeNotification,
  52. clearAllNotifications,
  53. hasErrors,
  54. }
  55. }
  56. export { useNotifications }