useAddUnknownValueAction.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { email as emailValidation } from '@formkit/rules'
  3. import { ref, type Ref } from 'vue'
  4. import type { DropdownOptionsAction } from '#desktop/components/CommonSelect/types.ts'
  5. import type {
  6. AutoCompleteOptionValueDictionary,
  7. SelectOptionFunction,
  8. } from '#desktop/components/Form/fields/FieldAutoComplete/types.ts'
  9. import type { FormKitNode } from '@formkit/core'
  10. export const emailFilterValueValidator = (filter: string) =>
  11. emailValidation({ value: filter } as FormKitNode)
  12. export const phoneFilterValueValidator = (filter: string) =>
  13. /^\+?[1-9]\d+$/.test(filter)
  14. export const useAddUnknownValueAction = (
  15. label?: Ref<string>,
  16. filterValueValidator?: (filter: string) => boolean | Promise<boolean>,
  17. ) => {
  18. const actions = ref<DropdownOptionsAction[]>([])
  19. const actionLabel = label ?? ref(__('add new email address'))
  20. const validFilterValue = filterValueValidator ?? emailFilterValueValidator
  21. const onSearchInteractionUpdate = (
  22. filter: string,
  23. optionValues: AutoCompleteOptionValueDictionary,
  24. selectOption: SelectOptionFunction,
  25. ) => {
  26. if (optionValues[filter] || !validFilterValue(filter)) {
  27. actions.value = []
  28. return
  29. }
  30. const newOption = {
  31. value: filter,
  32. label: filter,
  33. }
  34. actions.value = [
  35. {
  36. key: 'addUnknownValue',
  37. label: actionLabel.value,
  38. icon: 'plus-square-fill',
  39. onClick: (focus) => {
  40. selectOption(newOption, focus)
  41. // Reset actions after current filter was added.
  42. actions.value = []
  43. },
  44. },
  45. ]
  46. }
  47. return {
  48. actions,
  49. onSearchInteractionUpdate,
  50. }
  51. }