FieldSelectInput.vue 11 KB

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