useValue.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed, type Ref } from 'vue'
  3. import { type FormFieldContext } from '../types/field.ts'
  4. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5. const useValue = <T = any>(
  6. context: Ref<FormFieldContext<{ multiple?: boolean; clearValue?: unknown }>>,
  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<T[]>(() =>
  13. context.value.multiple ? (currentValue.value as T[]) : [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. // if value is undefined, it is not sent to the backend
  22. // we want to clear the value, so we set it to null
  23. const clearValue =
  24. context.value.clearValue !== undefined ? context.value.clearValue : null
  25. context.value.node.input(clearValue, asyncSettling)
  26. }
  27. const localValue = computed({
  28. get: () => currentValue.value,
  29. set: (value) => {
  30. context.value.node.input(value)
  31. },
  32. })
  33. return {
  34. localValue,
  35. currentValue,
  36. hasValue,
  37. valueContainer,
  38. isCurrentValue,
  39. clearValue,
  40. }
  41. }
  42. export default useValue