useSelectPreselect.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import type { SelectOption } from '#shared/components/CommonSelect/types.ts'
  3. import useValue from '#shared/components/Form/composables/useValue.ts'
  4. import type { FlatSelectOption } from '#shared/components/Form/fields/FieldTreeSelect/types.ts'
  5. import type { FormFieldContext } from '#shared/components/Form/types/field.ts'
  6. import { type Ref, onMounted, watch } from 'vue'
  7. const useSelectPreselect = (
  8. options: Ref<SelectOption[] | FlatSelectOption[]>,
  9. context: Ref<
  10. FormFieldContext<{
  11. clearable?: boolean
  12. multiple?: boolean
  13. }>
  14. >,
  15. ) => {
  16. const { hasValue } = useValue(context)
  17. // Consider only enabled options.
  18. const getPreselectValue = () =>
  19. options.value?.find((option) => !option.disabled)?.value
  20. // Remember function to use it during the next value check.
  21. context.value.getPreselectValue = getPreselectValue
  22. // Pre-select the first option of a single select when and only when the field is not clearable nor disabled.
  23. // This mimics the behavior of the native select field.
  24. const preselectOption = () => {
  25. if (
  26. !hasValue.value &&
  27. !context.value.disabled &&
  28. !context.value.multiple &&
  29. !context.value.clearable &&
  30. options.value &&
  31. options.value.length > 0
  32. ) {
  33. context.value.node.input(getPreselectValue(), false)
  34. }
  35. }
  36. onMounted(() => {
  37. preselectOption()
  38. watch(
  39. () =>
  40. !hasValue.value &&
  41. !context.value.disabled &&
  42. !context.value.multiple &&
  43. !context.value.clearable &&
  44. options.value,
  45. preselectOption,
  46. )
  47. })
  48. }
  49. export default useSelectPreselect