useConfirmation.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed, ref } from 'vue'
  3. import type { ButtonVariant } from '#shared/types/button.ts'
  4. import type { Except } from 'type-fest'
  5. export type ConfirmationVariant = 'delete' | 'unsaved' | 'confirm'
  6. export interface ConfirmationOptions {
  7. headerTitle?: string
  8. headerTitlePlaceholder?: string[]
  9. headerIcon?: string
  10. text?: string
  11. textPlaceholder?: string[]
  12. buttonLabel?: string
  13. buttonVariant?: ButtonVariant
  14. // TODO: should maybe also be implemented for mobile, so that we have a better alignment for the code
  15. confirmationVariant?: ConfirmationVariant
  16. confirmCallback: () => void
  17. cancelCallback: () => void
  18. }
  19. const confirmationOptions = ref<ConfirmationOptions>()
  20. const showConfirmation = computed(() => !!confirmationOptions.value)
  21. export const useConfirmation = () => {
  22. const waitForConfirmation = (
  23. text: string,
  24. options: Except<
  25. ConfirmationOptions,
  26. 'text' | 'confirmCallback' | 'cancelCallback'
  27. > = {},
  28. ) => {
  29. return new Promise<boolean>((resolve) => {
  30. confirmationOptions.value = {
  31. ...options,
  32. text,
  33. confirmCallback() {
  34. resolve(true)
  35. },
  36. cancelCallback() {
  37. resolve(false)
  38. },
  39. }
  40. })
  41. }
  42. const waitForVariantConfirmation = (
  43. variant: ConfirmationVariant = 'confirm',
  44. options: Except<
  45. ConfirmationOptions,
  46. 'text' | 'confirmCallback' | 'cancelCallback'
  47. > = {},
  48. ) => {
  49. return waitForConfirmation('', {
  50. ...options,
  51. confirmationVariant: variant,
  52. })
  53. }
  54. return {
  55. showConfirmation,
  56. confirmationOptions,
  57. waitForConfirmation,
  58. waitForVariantConfirmation,
  59. }
  60. }