useSelectPreselect.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. import { type Ref, onMounted, watch } from 'vue'
  3. import type { FormFieldContext } from '../types/field'
  4. import type { SelectOption } from '../fields/FieldSelect'
  5. import type { FlatSelectOption } from '../fields/FieldTreeSelect'
  6. import useValue from './useValue'
  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. // Pre-select the first option of a single select when and only when the field is not clearable nor disabled.
  18. // This mimics the behavior of the native select field.
  19. const preselectOption = () => {
  20. if (
  21. !hasValue.value &&
  22. !context.value.disabled &&
  23. !context.value.multiple &&
  24. !context.value.clearable &&
  25. options.value &&
  26. options.value.length > 0
  27. ) {
  28. context.value.node.input(options.value[0].value, false)
  29. }
  30. }
  31. onMounted(() => {
  32. preselectOption()
  33. watch(
  34. () =>
  35. !hasValue.value &&
  36. !context.value.disabled &&
  37. !context.value.multiple &&
  38. !context.value.clearable &&
  39. options.value,
  40. preselectOption,
  41. )
  42. })
  43. }
  44. export default useSelectPreselect