useValue.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed, type Ref } from 'vue'
  3. import { type FormFieldContext } from '../types/field'
  4. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5. const useValue = <T = any>(
  6. context: Ref<FormFieldContext<{ multiple?: boolean }>>,
  7. ) => {
  8. const currentValue = computed(() => context.value._value as T)
  9. const hasValue = computed(() => {
  10. return context.value.fns.hasValue(currentValue.value)
  11. })
  12. const valueContainer = computed(() =>
  13. context.value.multiple ? currentValue.value : [currentValue.value],
  14. )
  15. const isCurrentValue = (value: T) => {
  16. if (!hasValue.value) return false
  17. return (valueContainer.value as unknown as T[]).includes(value)
  18. }
  19. const clearValue = (asyncSettling = true) => {
  20. if (!hasValue.value) return
  21. context.value.node.input(undefined, asyncSettling)
  22. }
  23. const localValue = computed({
  24. get: () => currentValue.value,
  25. set: (value) => {
  26. context.value.node.input(value)
  27. },
  28. })
  29. return {
  30. localValue,
  31. currentValue,
  32. hasValue,
  33. valueContainer,
  34. isCurrentValue,
  35. clearValue,
  36. }
  37. }
  38. export default useValue