useConfirmation.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. closeCallback: () => void
  20. }
  21. const confirmationOptions = ref<ConfirmationOptions>()
  22. const showConfirmation = computed(() => !!confirmationOptions.value)
  23. export const useConfirmation = () => {
  24. const waitForConfirmation = (
  25. text: string,
  26. options: Except<
  27. ConfirmationOptions,
  28. 'text' | 'confirmCallback' | 'cancelCallback' | 'closeCallback'
  29. > = {},
  30. ) => {
  31. return new Promise<boolean | undefined>((resolve) => {
  32. confirmationOptions.value = {
  33. ...options,
  34. text,
  35. confirmCallback() {
  36. resolve(true)
  37. },
  38. cancelCallback() {
  39. resolve(false)
  40. },
  41. closeCallback() {
  42. resolve(undefined)
  43. },
  44. }
  45. })
  46. }
  47. const waitForVariantConfirmation = (
  48. variant: ConfirmationVariant = 'confirm',
  49. options: Except<
  50. ConfirmationOptions,
  51. 'text' | 'confirmCallback' | 'cancelCallback' | 'closeCallback'
  52. > = {},
  53. ) => {
  54. return waitForConfirmation('', {
  55. ...options,
  56. confirmationVariant: variant,
  57. })
  58. }
  59. return {
  60. showConfirmation,
  61. confirmationOptions,
  62. waitForConfirmation,
  63. waitForVariantConfirmation,
  64. }
  65. }