composable.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. import { ref } from 'vue'
  3. import getUuid from '@shared/utils/getUuid'
  4. import { NotificationTypes } from './types'
  5. import type { NewNotification, Notification } from './types'
  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. if (!id) {
  20. id = getUuid()
  21. }
  22. const newNotification: Notification = { id, timeout: 0, ...notification }
  23. if (notification.unique) {
  24. notifications.value = notifications.value.filter(
  25. (notification: Notification) => {
  26. const isSame = notification.id === id
  27. if (isSame) {
  28. window.clearTimeout(notification.timeout)
  29. }
  30. return !isSame
  31. },
  32. )
  33. }
  34. notifications.value.push(newNotification)
  35. if (!newNotification.persistent) {
  36. newNotification.timeout = window.setTimeout(() => {
  37. removeNotification(newNotification.id)
  38. }, newNotification.durationMS || defaultNotificationDurationMS)
  39. }
  40. return newNotification.id
  41. }
  42. const hasErrors = () => {
  43. return notifications.value.some((notification) => {
  44. return notification.type === NotificationTypes.Error
  45. })
  46. }
  47. return {
  48. notify,
  49. notifications,
  50. removeNotification,
  51. clearAllNotifications,
  52. hasErrors,
  53. }
  54. }
  55. export default useNotifications