FieldSelectInput.vue 11 KB

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