useNotifications.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright (C) 2012-2021 Zammad Foundation, https://zammad-foundation.org/
  2. import { v4 as uuid } from 'uuid'
  3. import { ref } from 'vue'
  4. import type {
  5. NewNotificationInterface,
  6. NotificationInterface,
  7. } from '@common/types/notification'
  8. const notifications = ref<NotificationInterface[]>([])
  9. const defaultNotificationDuration = 5000
  10. function removeNotification(id: string) {
  11. notifications.value = notifications.value.filter(
  12. (notification: NotificationInterface) => notification.id !== id,
  13. )
  14. }
  15. function clearAllNotifications() {
  16. notifications.value = []
  17. }
  18. export default function useNotifications() {
  19. function notify(notification: NewNotificationInterface): string {
  20. // TODO: Check different solution for the optional id in the interface, but required field in the removeNotification function.
  21. let { id } = notification
  22. if (!id) {
  23. id = uuid()
  24. }
  25. const newNotification: NotificationInterface = { id, ...notification }
  26. notifications.value.push(newNotification)
  27. setTimeout(() => {
  28. removeNotification(newNotification.id)
  29. }, newNotification.duration || defaultNotificationDuration)
  30. return newNotification.id
  31. }
  32. return {
  33. notify,
  34. notifications,
  35. clearAllNotifications,
  36. }
  37. }