useFlatSelectOptions.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed, type Ref } from 'vue'
  3. import type { SelectValue } from '#shared/components/CommonSelect/types.ts'
  4. import type {
  5. FlatSelectOption,
  6. TreeSelectOption,
  7. } from '#shared/components/Form/fields/FieldTreeSelect/types.ts'
  8. const useFlatSelectOptions = (options?: Ref<TreeSelectOption[]>) => {
  9. const flattenOptions = (
  10. options: TreeSelectOption[],
  11. parents: SelectValue[] = [],
  12. ): FlatSelectOption[] =>
  13. options &&
  14. options.reduce(
  15. (flatOptions: FlatSelectOption[], { children, ...option }) => {
  16. flatOptions.push({
  17. ...option,
  18. parents,
  19. hasChildren: Boolean(children),
  20. })
  21. if (children)
  22. flatOptions.push(
  23. ...flattenOptions(children, [...parents, option.value]),
  24. )
  25. return flatOptions
  26. },
  27. [],
  28. )
  29. const flatOptions = computed(() => flattenOptions(options?.value || []))
  30. return {
  31. flatOptions,
  32. flattenOptions,
  33. }
  34. }
  35. export default useFlatSelectOptions