usePopoverMenu.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { inject, computed, provide } from 'vue'
  3. import { useSessionStore } from '#shared/stores/session.ts'
  4. import type { ObjectLike } from '#shared/types/utils.ts'
  5. import type { MenuItem } from '#desktop/components/CommonPopover/types.ts'
  6. import type { ComputedRef, Ref } from 'vue'
  7. const POPOVER_MENU_SYMBOL = Symbol('popover-menu')
  8. interface UsePopoverMenuReturn {
  9. filteredMenuItems: ComputedRef<MenuItem[] | undefined>
  10. singleMenuItemPresent: ComputedRef<boolean>
  11. singleMenuItem: ComputedRef<MenuItem | undefined>
  12. }
  13. export const usePopoverMenu = (
  14. items: Ref<MenuItem[] | undefined>,
  15. entity: Ref<ObjectLike | undefined>,
  16. options: { provides?: boolean } = {},
  17. ) => {
  18. const injectPopoverMenu = inject<Maybe<UsePopoverMenuReturn>>(
  19. POPOVER_MENU_SYMBOL,
  20. null,
  21. )
  22. if (injectPopoverMenu) return injectPopoverMenu
  23. const { provides = false } = options
  24. const session = useSessionStore()
  25. const filteredMenuItems = computed(() => {
  26. if (!items.value || !items.value.length) return
  27. return items.value.filter((item) => {
  28. if (item.permission) {
  29. return session.hasPermission(item.permission)
  30. }
  31. if (item.show) {
  32. return item.show(entity?.value)
  33. }
  34. return true
  35. })
  36. })
  37. const singleMenuItemPresent = computed(() => {
  38. return filteredMenuItems.value?.length === 1
  39. })
  40. const singleMenuItem = computed(() => {
  41. if (!singleMenuItemPresent.value) return
  42. return filteredMenuItems.value?.[0]
  43. })
  44. const providePopoverMenu = {
  45. filteredMenuItems,
  46. singleMenuItemPresent,
  47. singleMenuItem,
  48. }
  49. if (provides) provide(POPOVER_MENU_SYMBOL, providePopoverMenu)
  50. return providePopoverMenu
  51. }