notification.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import dayjs from 'dayjs'
  2. import NotificationWorker from 'worker-loader!../workers/notification.js'
  3. import { createRandom } from '@/helpers/uuidv4'
  4. const clickEvents = {}
  5. const showEvents = {}
  6. const errorEvents = {}
  7. const closeEvents = {}
  8. const noop = () => {}
  9. export const notificationWorker = new NotificationWorker()
  10. const notificationClicked = data => {
  11. const activeFn = clickEvents[data.callback_key]
  12. if (typeof activeFn === 'function') {
  13. activeFn(data)
  14. }
  15. delete clickEvents[data.callback_key]
  16. }
  17. const notificationShowed = data => {
  18. const activeFn = showEvents[data.callback_key]
  19. if (typeof activeFn === 'function') {
  20. activeFn(data)
  21. }
  22. delete showEvents[data.callback_key]
  23. }
  24. const notificationErrored = data => {
  25. const activeFn = errorEvents[data.callback_key]
  26. if (typeof activeFn === 'function') {
  27. activeFn(data)
  28. }
  29. delete errorEvents[data.callback_key]
  30. }
  31. const notificationClosed = data => {
  32. const activeFn = closeEvents[data.callback_key]
  33. if (typeof activeFn === 'function') {
  34. activeFn(data)
  35. }
  36. delete closeEvents[data.callback_key]
  37. }
  38. notificationWorker.addEventListener('message', evt => {
  39. if (evt.data.type === 'NotificationClicked') {
  40. notificationClicked(evt.data.data || {})
  41. } else if (evt.data.type === 'NotificationShowed') {
  42. notificationShowed(evt.data.data || {})
  43. } else if (evt.data.type === 'NotificationErrored') {
  44. notificationErrored(evt.data.data || {})
  45. } else if (evt.data.type === 'NotificationClosed') {
  46. notificationClosed(evt.data.data || {})
  47. }
  48. })
  49. export const createNotification = data => {
  50. /**
  51. *
  52. * @param { Object } 会原样在onClick返回
  53. *
  54. */
  55. const { onClick = noop, onShow = noop, onError = noop, onClose = noop, ...rest } = data
  56. const timemap = dayjs().valueOf()
  57. const callback_key = `${timemap}_${createRandom()}`
  58. clickEvents[callback_key] = onClick
  59. clickEvents[callback_key] = onShow
  60. clickEvents[callback_key] = onError
  61. clickEvents[callback_key] = onClose
  62. notificationWorker.postMessage({
  63. ...rest,
  64. timemap,
  65. callback_key,
  66. type: 'create'
  67. })
  68. }