useConfirmation.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. cancelLabel?: string
  15. // TODO: should maybe also be implemented for mobile, so that we have a better alignment for the code
  16. confirmationVariant?: ConfirmationVariant
  17. confirmCallback: () => void
  18. cancelCallback: () => void
  19. }
  20. const confirmationOptions = ref<ConfirmationOptions>()
  21. const showConfirmation = computed(() => !!confirmationOptions.value)
  22. export const useConfirmation = () => {
  23. const waitForConfirmation = (
  24. text: string,
  25. options: Except<
  26. ConfirmationOptions,
  27. 'text' | 'confirmCallback' | 'cancelCallback'
  28. > = {},
  29. ) => {
  30. return new Promise<boolean>((resolve) => {
  31. confirmationOptions.value = {
  32. ...options,
  33. text,
  34. confirmCallback() {
  35. resolve(true)
  36. },
  37. cancelCallback() {
  38. resolve(false)
  39. },
  40. }
  41. })
  42. }
  43. const waitForVariantConfirmation = (
  44. variant: ConfirmationVariant = 'confirm',
  45. options: Except<
  46. ConfirmationOptions,
  47. 'text' | 'confirmCallback' | 'cancelCallback'
  48. > = {},
  49. ) => {
  50. return waitForConfirmation('', {
  51. ...options,
  52. confirmationVariant: variant,
  53. })
  54. }
  55. return {
  56. showConfirmation,
  57. confirmationOptions,
  58. waitForConfirmation,
  59. waitForVariantConfirmation,
  60. }
  61. }