FieldTreeSelectInput.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. <!-- Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/ -->
  2. <script setup lang="ts">
  3. import { useElementBounding, useWindowSize } from '@vueuse/core'
  4. import { escapeRegExp } from 'lodash-es'
  5. import { computed, nextTick, ref, toRef, watch } from 'vue'
  6. import useValue from '#shared/components/Form/composables/useValue.ts'
  7. import type {
  8. FlatSelectOption,
  9. TreeSelectContext,
  10. } from '#shared/components/Form/fields/FieldTreeSelect/types.ts'
  11. import useSelectOptions from '#shared/composables/useSelectOptions.ts'
  12. import useSelectPreselect from '#shared/composables/useSelectPreselect.ts'
  13. import { useTrapTab } from '#shared/composables/useTrapTab.ts'
  14. import { useFormBlock } from '#shared/form/useFormBlock.ts'
  15. import { i18n } from '#shared/i18n.ts'
  16. import CommonInputSearch from '#desktop/components/CommonInputSearch/CommonInputSearch.vue'
  17. import type { CommonSelectInstance } from '#desktop/components/CommonSelect/types.ts'
  18. import FieldTreeSelectInputDropdown from './FieldTreeSelectInputDropdown.vue'
  19. import useFlatSelectOptions from './useFlatSelectOptions.ts'
  20. interface Props {
  21. context: TreeSelectContext & {
  22. alternativeBackground?: boolean
  23. }
  24. }
  25. const props = defineProps<Props>()
  26. const contextReactive = toRef(props, 'context')
  27. const {
  28. hasValue,
  29. valueContainer,
  30. currentValue,
  31. clearValue: clearInternalValue,
  32. } = useValue(contextReactive)
  33. const { flatOptions } = useFlatSelectOptions(toRef(props.context, 'options'))
  34. const {
  35. sortedOptions,
  36. optionValueLookup,
  37. selectOption,
  38. getSelectedOption,
  39. getSelectedOptionIcon,
  40. getSelectedOptionLabel,
  41. getSelectedOptionFullPath,
  42. setupMissingOrDisabledOptionHandling,
  43. } = useSelectOptions<FlatSelectOption[]>(flatOptions, toRef(props, 'context'))
  44. const currentPath = ref<FlatSelectOption[]>([])
  45. const clearPath = () => {
  46. currentPath.value = []
  47. }
  48. const currentParent = computed<FlatSelectOption>(
  49. () => currentPath.value[currentPath.value.length - 1] ?? null,
  50. )
  51. const input = ref<HTMLDivElement>()
  52. const outputElement = ref<HTMLOutputElement>()
  53. const filter = ref('')
  54. const filterInput = ref<HTMLInputElement>()
  55. const select = ref<CommonSelectInstance>()
  56. const { activateTabTrap, deactivateTabTrap } = useTrapTab(input, true)
  57. const clearFilter = () => {
  58. filter.value = ''
  59. }
  60. watch(() => contextReactive.value.noFiltering, clearFilter)
  61. const deaccent = (s: string) =>
  62. s.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
  63. const filteredOptions = computed(() => {
  64. // In case we are not currently filtering for a parent, search across all options.
  65. let options = sortedOptions.value
  66. // Otherwise, search across options which are children of the current parent.
  67. if (currentParent.value)
  68. options = sortedOptions.value.filter((option) =>
  69. option.parents.includes(currentParent.value?.value),
  70. )
  71. // Trim and de-accent search keywords and compile them as a case-insensitive regex.
  72. // Make sure to escape special regex characters!
  73. const filterRegex = new RegExp(
  74. escapeRegExp(deaccent(filter.value.trim())),
  75. 'i',
  76. )
  77. return options
  78. .map(
  79. (option) =>
  80. ({
  81. ...option,
  82. // Match options via their de-accented labels.
  83. match: filterRegex.exec(
  84. deaccent(option.label || String(option.value)),
  85. ),
  86. }) as FlatSelectOption,
  87. )
  88. .filter((option) => option.match)
  89. })
  90. const suggestedOptionLabel = computed(() => {
  91. if (!filter.value || !filteredOptions.value.length) return undefined
  92. const exactMatches = filteredOptions.value.filter(
  93. (option) =>
  94. (getSelectedOptionLabel(option.value) || option.value.toString())
  95. .toLowerCase()
  96. .indexOf(filter.value.toLowerCase()) === 0 &&
  97. (getSelectedOptionLabel(option.value) || option.value.toString()).length >
  98. filter.value.length,
  99. )
  100. if (!exactMatches.length) return undefined
  101. return getSelectedOptionLabel(exactMatches[0].value)
  102. })
  103. const currentOptions = computed(() => {
  104. // In case we are not currently filtering for a parent, return only top-level options.
  105. if (!currentParent.value)
  106. return sortedOptions.value.filter((option) => !option.parents?.length)
  107. // Otherwise, return all options which are children of the current parent.
  108. return sortedOptions.value.filter(
  109. (option) =>
  110. option.parents.length &&
  111. option.parents[option.parents.length - 1] === currentParent.value?.value,
  112. )
  113. })
  114. const focusOutputElement = () => {
  115. if (!props.context.disabled) {
  116. outputElement.value?.focus()
  117. }
  118. }
  119. const clearValue = () => {
  120. if (props.context.disabled) return
  121. clearInternalValue()
  122. focusOutputElement()
  123. }
  124. const inputElementBounds = useElementBounding(input)
  125. const windowSize = useWindowSize()
  126. const isBelowHalfScreen = computed(() => {
  127. return inputElementBounds.y.value > windowSize.height.value / 2
  128. })
  129. const openSelectDropdown = () => {
  130. if (select.value?.isOpen || props.context.disabled) return
  131. select.value?.openDropdown(inputElementBounds, windowSize.height)
  132. requestAnimationFrame(() => {
  133. activateTabTrap()
  134. if (props.context.noFiltering) outputElement.value?.focus()
  135. else filterInput.value?.focus()
  136. })
  137. }
  138. const openOrMoveFocusToDropdown = (lastOption = false) => {
  139. if (!select.value?.isOpen) {
  140. openSelectDropdown()
  141. return
  142. }
  143. deactivateTabTrap()
  144. nextTick(() => {
  145. requestAnimationFrame(() => {
  146. select.value?.moveFocusToDropdown(lastOption)
  147. })
  148. })
  149. }
  150. const onCloseDropdown = () => {
  151. clearFilter()
  152. clearPath()
  153. deactivateTabTrap()
  154. }
  155. const onPathPush = (option: FlatSelectOption) => {
  156. currentPath.value.push(option)
  157. }
  158. const onPathPop = () => {
  159. currentPath.value.pop()
  160. }
  161. useFormBlock(contextReactive, openSelectDropdown)
  162. useSelectPreselect(flatOptions, contextReactive)
  163. setupMissingOrDisabledOptionHandling()
  164. </script>
  165. <template>
  166. <div
  167. ref="input"
  168. class="flex h-auto min-h-10 hover:outline hover:outline-1 hover:outline-offset-1 hover:outline-blue-600 has-[output:focus,input:focus]:outline has-[output:focus,input:focus]:outline-1 has-[output:focus,input:focus]:outline-offset-1 has-[output:focus,input:focus]:outline-blue-800 dark:hover:outline-blue-900 dark:has-[output:focus,input:focus]:outline-blue-800"
  169. :class="[
  170. context.classes.input,
  171. {
  172. 'rounded-lg': !select?.isOpen,
  173. 'rounded-t-lg': select?.isOpen && !isBelowHalfScreen,
  174. 'rounded-b-lg': select?.isOpen && isBelowHalfScreen,
  175. 'bg-blue-200 dark:bg-gray-700': !context.alternativeBackground,
  176. 'bg-white dark:bg-gray-500': context.alternativeBackground,
  177. },
  178. ]"
  179. data-test-id="field-treeselect"
  180. >
  181. <FieldTreeSelectInputDropdown
  182. ref="select"
  183. #default="{ state: expanded, close: closeDropdown }"
  184. :model-value="currentValue"
  185. :options="filteredOptions"
  186. :multiple="context.multiple"
  187. :owner="context.id"
  188. :current-path="currentPath"
  189. :filter="filter"
  190. :flat-options="flatOptions"
  191. :current-options="currentOptions"
  192. :option-value-lookup="optionValueLookup"
  193. no-options-label-translation
  194. no-close
  195. passive
  196. @clear-filter="clearFilter"
  197. @close="onCloseDropdown"
  198. @push="onPathPush"
  199. @pop="onPathPop"
  200. @select="selectOption"
  201. >
  202. <!-- https://www.w3.org/WAI/ARIA/apg/patterns/combobox/ -->
  203. <output
  204. :id="context.id"
  205. ref="outputElement"
  206. role="combobox"
  207. :name="context.node.name"
  208. class="flex grow items-center gap-2.5 px-2.5 py-2 text-black focus:outline-none dark:text-white"
  209. tabindex="0"
  210. :aria-labelledby="`label-${context.id}`"
  211. :aria-disabled="context.disabled ? 'true' : undefined"
  212. v-bind="context.attrs"
  213. :data-multiple="context.multiple"
  214. aria-autocomplete="none"
  215. aria-controls="field-tree-select-input-dropdown"
  216. aria-owns="field-tree-select-input-dropdown"
  217. aria-haspopup="menu"
  218. :aria-expanded="expanded"
  219. :aria-describedby="context.describedBy"
  220. @keydown.escape.prevent="closeDropdown()"
  221. @keypress.enter.prevent="openSelectDropdown()"
  222. @keydown.down.prevent="openOrMoveFocusToDropdown()"
  223. @keydown.up.prevent="openOrMoveFocusToDropdown(true)"
  224. @keypress.space.prevent="openSelectDropdown()"
  225. @blur="context.handlers.blur"
  226. >
  227. <div
  228. v-if="hasValue && context.multiple"
  229. class="flex flex-wrap gap-1.5"
  230. role="list"
  231. >
  232. <div
  233. v-for="selectedValue in valueContainer"
  234. :key="selectedValue"
  235. class="flex items-center gap-1.5"
  236. role="listitem"
  237. >
  238. <div
  239. class="inline-flex cursor-default items-center gap-1 rounded px-1.5 py-0.5 text-xs text-black dark:text-white"
  240. :class="{
  241. 'bg-white dark:bg-gray-200': !context.alternativeBackground,
  242. 'bg-neutral-100 dark:bg-gray-200':
  243. context.alternativeBackground,
  244. }"
  245. >
  246. <CommonIcon
  247. v-if="getSelectedOptionIcon(selectedValue)"
  248. :name="getSelectedOptionIcon(selectedValue)"
  249. class="shrink-0 fill-gray-100 dark:fill-neutral-400"
  250. size="xs"
  251. decorative
  252. />
  253. <span
  254. class="line-clamp-3 whitespace-pre-wrap break-words"
  255. :title="getSelectedOptionFullPath(selectedValue)"
  256. >
  257. {{ getSelectedOptionFullPath(selectedValue) }}
  258. </span>
  259. <CommonIcon
  260. :aria-label="i18n.t('Unselect Option')"
  261. class="shrink-0 fill-stone-200 hover:fill-black focus:outline-none focus-visible:rounded-sm focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-1 focus-visible:outline-blue-800 dark:fill-neutral-500 dark:hover:fill-white"
  262. name="x-lg"
  263. size="xs"
  264. role="button"
  265. tabindex="0"
  266. @click.stop="selectOption(getSelectedOption(selectedValue))"
  267. @keypress.enter.prevent.stop="
  268. selectOption(getSelectedOption(selectedValue))
  269. "
  270. @keypress.space.prevent.stop="
  271. selectOption(getSelectedOption(selectedValue))
  272. "
  273. />
  274. </div>
  275. </div>
  276. </div>
  277. <CommonInputSearch
  278. v-if="expanded && !context.noFiltering"
  279. ref="filterInput"
  280. v-model="filter"
  281. :suggestion="suggestedOptionLabel"
  282. :alternative-background="context.alternativeBackground"
  283. @keypress.space.stop
  284. />
  285. <div v-else class="flex grow flex-wrap gap-1" role="list">
  286. <div
  287. v-if="hasValue && !context.multiple"
  288. class="flex items-center gap-1.5 text-sm"
  289. role="listitem"
  290. >
  291. <CommonIcon
  292. v-if="getSelectedOptionIcon(currentValue)"
  293. :name="getSelectedOptionIcon(currentValue)"
  294. class="shrink-0 fill-gray-100 dark:fill-neutral-400"
  295. size="tiny"
  296. decorative
  297. />
  298. <span
  299. class="line-clamp-3 whitespace-pre-wrap break-words"
  300. :title="getSelectedOptionFullPath(currentValue)"
  301. >
  302. {{ getSelectedOptionFullPath(currentValue) }}
  303. </span>
  304. </div>
  305. </div>
  306. <CommonIcon
  307. v-if="context.clearable && hasValue && !context.disabled"
  308. :aria-label="i18n.t('Clear Selection')"
  309. class="shrink-0 fill-stone-200 hover:fill-black focus:outline-none focus-visible:rounded-sm focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-1 focus-visible:outline-blue-800 dark:fill-neutral-500 dark:hover:fill-white"
  310. name="x-lg"
  311. size="xs"
  312. role="button"
  313. tabindex="0"
  314. @click.stop="clearValue()"
  315. @keypress.enter.prevent.stop="clearValue()"
  316. @keypress.space.prevent.stop="clearValue()"
  317. />
  318. <CommonIcon
  319. class="shrink-0 fill-stone-200 dark:fill-neutral-500"
  320. name="chevron-down"
  321. size="xs"
  322. decorative
  323. />
  324. </output>
  325. </FieldTreeSelectInputDropdown>
  326. </div>
  327. </template>