useTaskbarTabStateUpdates.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { ref, type Ref } from 'vue'
  3. import type { FormRef } from '#shared/components/Form/types.ts'
  4. import SubscriptionHandler from '#shared/server/apollo/handler/SubscriptionHandler.ts'
  5. import type { FormUpdaterOptions } from '#shared/types/form.ts'
  6. import { useUserCurrentTaskbarItemStateUpdatesSubscription } from '../graphql/subscriptions/userCurrentTaskbarItemStateUpdates.api.ts'
  7. export const useTaskbarTabStateUpdates = (
  8. currentTaskbarTabId: Ref<string | undefined>,
  9. form: Ref<FormRef | undefined>,
  10. autoSaveTriggerFormUpdater: (options?: FormUpdaterOptions) => void,
  11. ) => {
  12. const skipNextStateUpdate = ref(false)
  13. const applyTaskbarState = ref(false)
  14. const setSkipNextStateUpdate = (skip: boolean) => {
  15. // When it's after a applay taskbar state it was not a manual change in the current tab.
  16. if (skip && applyTaskbarState.value) {
  17. skipNextStateUpdate.value = false
  18. return
  19. }
  20. skipNextStateUpdate.value = skip
  21. }
  22. const stateUpdatesSubscription = new SubscriptionHandler(
  23. useUserCurrentTaskbarItemStateUpdatesSubscription(
  24. () => ({
  25. taskbarItemId: currentTaskbarTabId.value!,
  26. }),
  27. () => ({
  28. enabled: !!currentTaskbarTabId.value,
  29. }),
  30. ),
  31. )
  32. stateUpdatesSubscription.onSubscribed().then(() => {
  33. stateUpdatesSubscription.onResult((result) => {
  34. let listenFormUpdaterProcessing: string | undefined
  35. if (
  36. currentTaskbarTabId.value &&
  37. !skipNextStateUpdate.value &&
  38. result.data?.userCurrentTaskbarItemStateUpdates.stateChanged
  39. ) {
  40. listenFormUpdaterProcessing = form.value?.formNode.on(
  41. 'message-removed',
  42. ({ payload }) => {
  43. if (
  44. !listenFormUpdaterProcessing ||
  45. payload.key !== 'formUpdaterProcessing'
  46. ) {
  47. return
  48. }
  49. applyTaskbarState.value = false
  50. form.value?.formNode.off(listenFormUpdaterProcessing)
  51. },
  52. )
  53. applyTaskbarState.value = true
  54. autoSaveTriggerFormUpdater({
  55. includeDirtyFields: true,
  56. additionalParams: {
  57. taskbarId: currentTaskbarTabId.value,
  58. applyTaskbarState: true,
  59. },
  60. })
  61. }
  62. setSkipNextStateUpdate(false)
  63. })
  64. })
  65. return { setSkipNextStateUpdate }
  66. }