CommonSelect.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. <!-- Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/ -->
  2. <script setup lang="ts">
  3. import {
  4. type UseElementBoundingReturn,
  5. onClickOutside,
  6. onKeyDown,
  7. useVModel,
  8. } from '@vueuse/core'
  9. import { useTemplateRef } from 'vue'
  10. import {
  11. computed,
  12. type ConcreteComponent,
  13. nextTick,
  14. onUnmounted,
  15. ref,
  16. type Ref,
  17. toRef,
  18. } from 'vue'
  19. import type {
  20. MatchedSelectOption,
  21. SelectOption,
  22. SelectValue,
  23. } from '#shared/components/CommonSelect/types.ts'
  24. import type { AutoCompleteOption } from '#shared/components/Form/fields/FieldAutocomplete/types.ts'
  25. import { useFocusWhenTyping } from '#shared/composables/useFocusWhenTyping.ts'
  26. import { useTrapTab } from '#shared/composables/useTrapTab.ts'
  27. import { useTraverseOptions } from '#shared/composables/useTraverseOptions.ts'
  28. import { i18n } from '#shared/i18n.ts'
  29. import { useLocaleStore } from '#shared/stores/locale.ts'
  30. import stopEvent from '#shared/utils/events.ts'
  31. import testFlags from '#shared/utils/testFlags.ts'
  32. import CommonLoader from '#desktop/components/CommonLoader/CommonLoader.vue'
  33. import { useTransitionCollapse } from '#desktop/composables/useTransitionCollapse.ts'
  34. import CommonSelectItem from './CommonSelectItem.vue'
  35. import { useCommonSelect } from './useCommonSelect.ts'
  36. import type {
  37. CommonSelectInternalInstance,
  38. DropdownOptionsAction,
  39. } from './types.ts'
  40. export interface Props {
  41. modelValue?:
  42. | SelectValue
  43. | SelectValue[]
  44. | { value: SelectValue; label: string }
  45. | null
  46. options: AutoCompleteOption[] | SelectOption[]
  47. /**
  48. * Do not modify local value
  49. */
  50. passive?: boolean
  51. multiple?: boolean
  52. noClose?: boolean
  53. noRefocus?: boolean
  54. owner?: string
  55. noOptionsLabelTranslation?: boolean
  56. filter?: string
  57. optionIconComponent?: ConcreteComponent
  58. initiallyEmpty?: boolean
  59. emptyInitialLabelText?: string
  60. actions?: DropdownOptionsAction[]
  61. isChildPage?: boolean
  62. isLoading?: boolean
  63. }
  64. const props = withDefaults(defineProps<Props>(), {
  65. emptyInitialLabelText: __('Start typing to search…'),
  66. })
  67. const emit = defineEmits<{
  68. 'update:modelValue': [option: string | number | (string | number)[]]
  69. select: [option: SelectOption]
  70. push: [option: AutoCompleteOption]
  71. pop: []
  72. close: []
  73. 'focus-filter-input': []
  74. }>()
  75. const dropdownElement = useTemplateRef('dropdown')
  76. const localValue = useVModel(props, 'modelValue', emit)
  77. // TODO: do we really want this initial transforming of the value, when it's null?
  78. if (localValue.value == null && props.multiple) {
  79. localValue.value = []
  80. }
  81. const getFocusableOptions = () => {
  82. return Array.from<HTMLElement>(
  83. dropdownElement.value?.querySelectorAll('[tabindex="0"]') || [],
  84. )
  85. }
  86. const showDropdown = ref(false)
  87. let inputElementBounds: UseElementBoundingReturn
  88. let windowHeight: Ref<number>
  89. const hasDirectionUp = computed(() => {
  90. if (!inputElementBounds || !windowHeight) return false
  91. return inputElementBounds.y.value > windowHeight.value / 2
  92. })
  93. const dropdownStyle = computed(() => {
  94. if (!inputElementBounds) return { top: 0, left: 0, width: 0, maxHeight: 0 }
  95. const style: Record<string, string> = {
  96. left: `${inputElementBounds.left.value}px`,
  97. width: `${inputElementBounds.width.value}px`,
  98. maxHeight: `calc(50vh - ${inputElementBounds.height.value}px)`,
  99. }
  100. if (hasDirectionUp.value) {
  101. style.bottom = `${windowHeight.value - inputElementBounds.top.value}px`
  102. } else {
  103. style.top = `${
  104. inputElementBounds.top.value + inputElementBounds.height.value
  105. }px`
  106. }
  107. return style
  108. })
  109. const { activateTabTrap, deactivateTabTrap } = useTrapTab(dropdownElement)
  110. let lastFocusableOutsideElement: HTMLElement | null = null
  111. const getActiveElement = () => {
  112. if (props.owner) {
  113. return document.getElementById(props.owner)
  114. }
  115. return document.activeElement as HTMLElement
  116. }
  117. const { instances } = useCommonSelect()
  118. const closeDropdown = (refocusOnEscape?: boolean) => {
  119. deactivateTabTrap()
  120. showDropdown.value = false
  121. emit('close')
  122. nextTick(() => {
  123. if (!props.noRefocus || refocusOnEscape)
  124. lastFocusableOutsideElement?.focus()
  125. testFlags.set('common-select.closed')
  126. })
  127. }
  128. const openDropdown = (
  129. bounds: UseElementBoundingReturn,
  130. height: Ref<number>,
  131. ) => {
  132. inputElementBounds = bounds
  133. windowHeight = toRef(height)
  134. instances.value.forEach((instance) => {
  135. if (instance.isOpen.value) instance.closeDropdown()
  136. })
  137. showDropdown.value = true
  138. lastFocusableOutsideElement = getActiveElement()
  139. onClickOutside(dropdownElement, () => closeDropdown(), {
  140. ignore: [lastFocusableOutsideElement as unknown as HTMLElement],
  141. })
  142. requestAnimationFrame(() => {
  143. nextTick(() => {
  144. testFlags.set('common-select.opened')
  145. })
  146. })
  147. }
  148. const moveFocusToDropdown = (lastOption = false) => {
  149. // Focus selected or first available option.
  150. // https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role#keyboard_interactions
  151. const focusableElements = getFocusableOptions()
  152. if (!focusableElements?.length) return
  153. let focusElement = focusableElements[0]
  154. if (lastOption) {
  155. focusElement = focusableElements[focusableElements.length - 1]
  156. } else {
  157. const selected = focusableElements.find(
  158. (el) => el.getAttribute('aria-selected') === 'true',
  159. )
  160. if (selected) focusElement = selected
  161. }
  162. focusElement?.focus()
  163. activateTabTrap()
  164. }
  165. const exposedInstance: CommonSelectInternalInstance = {
  166. isOpen: computed(() => showDropdown.value),
  167. openDropdown,
  168. closeDropdown,
  169. getFocusableOptions,
  170. moveFocusToDropdown,
  171. }
  172. instances.value.add(exposedInstance)
  173. onUnmounted(() => {
  174. instances.value.delete(exposedInstance)
  175. })
  176. defineExpose(exposedInstance)
  177. // https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role#keyboard_interactions
  178. useTraverseOptions(dropdownElement, { direction: 'vertical' })
  179. // - Type-ahead is recommended for all listboxes, especially those with more than seven options
  180. useFocusWhenTyping(dropdownElement)
  181. onKeyDown(
  182. 'Escape',
  183. (event) => {
  184. stopEvent(event)
  185. closeDropdown(true)
  186. },
  187. { target: dropdownElement as Ref<EventTarget> },
  188. )
  189. const isCurrentValue = (value: string | number | boolean) => {
  190. if (props.multiple && Array.isArray(localValue.value)) {
  191. return localValue.value.includes(value)
  192. }
  193. return localValue.value === value
  194. }
  195. const select = (option: SelectOption) => {
  196. if (option.disabled) return
  197. emit('select', option)
  198. if (props.passive) {
  199. if (!props.multiple) {
  200. closeDropdown()
  201. }
  202. return
  203. }
  204. if (props.multiple && Array.isArray(localValue.value)) {
  205. if (localValue.value.includes(option.value)) {
  206. localValue.value = localValue.value.filter((v) => v !== option.value)
  207. } else {
  208. localValue.value.push(option.value)
  209. }
  210. return
  211. }
  212. if (props.modelValue === option.value) {
  213. localValue.value = undefined
  214. } else {
  215. localValue.value = option.value
  216. }
  217. if (!props.multiple && !props.noClose) {
  218. closeDropdown()
  219. }
  220. }
  221. const hasMoreSelectableOptions = computed(
  222. () =>
  223. props.options.filter(
  224. (option) => !option.disabled && !isCurrentValue(option.value),
  225. ).length > 0,
  226. )
  227. const focusFirstOption = () => {
  228. const focusableElements = getFocusableOptions()
  229. if (!focusableElements?.length) return
  230. const focusElement = focusableElements[0]
  231. focusElement?.focus()
  232. }
  233. const selectAll = (focusInput = false) => {
  234. props.options
  235. .filter((option) => !option.disabled && !isCurrentValue(option.value))
  236. .forEach((option) => select(option))
  237. if (focusInput === true) {
  238. emit('focus-filter-input')
  239. return
  240. }
  241. focusFirstOption()
  242. }
  243. const highlightedOptions = computed(() =>
  244. props.options.map((option) => {
  245. let label = option.label || i18n.t('%s (unknown)', option.value.toString())
  246. // Highlight the matched text within the option label by re-using passed regex match object.
  247. // This approach has several benefits:
  248. // - no repeated regex matching in order to identify matched text
  249. // - support for matched text with accents, in case the search keyword didn't contain them (and vice-versa)
  250. if (option.match && option.match[0]) {
  251. const labelBeforeMatch = label.slice(0, option.match.index)
  252. // Do not use the matched text here, instead use part of the original label in the same length.
  253. // This is because the original match does not include accented characters.
  254. const labelMatchedText = label.slice(
  255. option.match.index,
  256. option.match.index + option.match[0].length,
  257. )
  258. const labelAfterMatch = label.slice(
  259. option.match.index + option.match[0].length,
  260. )
  261. const highlightClasses = option.disabled
  262. ? 'bg-blue-200 dark:bg-gray-300'
  263. : 'bg-blue-600 dark:bg-blue-900 group-hover:bg-blue-800 group-hover:group-focus:bg-blue-600 dark:group-hover:group-focus:bg-blue-900 group-hover:text-white group-focus:text-black dark:group-focus:text-white group-hover:group-focus:text-black dark:group-hover:group-focus:text-white'
  264. label = `${labelBeforeMatch}<span class="${highlightClasses}">${labelMatchedText}</span>${labelAfterMatch}`
  265. }
  266. return {
  267. ...option,
  268. matchedLabel: label,
  269. } as MatchedSelectOption
  270. }),
  271. )
  272. const emptyLabelText = computed(() => {
  273. if (!props.initiallyEmpty) return __('No results found')
  274. return props.filter ? __('No results found') : props.emptyInitialLabelText
  275. })
  276. const { collapseDuration, collapseEnter, collapseAfterEnter, collapseLeave } =
  277. useTransitionCollapse()
  278. const dropdownActions = computed(() => {
  279. return [
  280. ...(props.actions || []),
  281. ...(props.multiple && hasMoreSelectableOptions.value
  282. ? [
  283. {
  284. key: 'selectAll',
  285. label: __('select all options'),
  286. icon: 'check-all',
  287. onClick: selectAll,
  288. },
  289. ]
  290. : []),
  291. ]
  292. })
  293. const locale = useLocaleStore()
  294. const parentPageCallback = (noFocus?: boolean) => {
  295. emit('pop')
  296. if (noFocus) return
  297. nextTick(() => {
  298. focusFirstOption()
  299. })
  300. }
  301. const goToParentPage = (noFocus?: boolean) => {
  302. parentPageCallback(noFocus)
  303. }
  304. const childPageCallback = (option?: AutoCompleteOption, noFocus?: boolean) => {
  305. if (option?.children) {
  306. emit('push', option)
  307. if (noFocus) return
  308. nextTick(() => {
  309. focusFirstOption()
  310. })
  311. }
  312. }
  313. const goToChildPage = ({
  314. option,
  315. noFocus,
  316. }: {
  317. option: AutoCompleteOption
  318. noFocus?: boolean
  319. }) => {
  320. childPageCallback(option, noFocus)
  321. }
  322. </script>
  323. <template>
  324. <slot
  325. :state="showDropdown"
  326. :open="openDropdown"
  327. :close="closeDropdown"
  328. :focus="moveFocusToDropdown"
  329. />
  330. <Teleport to="body">
  331. <Transition
  332. name="collapse"
  333. :duration="collapseDuration"
  334. @enter="collapseEnter"
  335. @after-enter="collapseAfterEnter"
  336. @leave="collapseLeave"
  337. >
  338. <div
  339. v-if="showDropdown"
  340. id="common-select"
  341. ref="dropdown"
  342. class="fixed z-50 flex min-h-9 antialiased"
  343. :style="dropdownStyle"
  344. >
  345. <div class="w-full" role="menu">
  346. <div
  347. class="flex h-full flex-col items-start border-x border-neutral-100 bg-neutral-50 dark:border-gray-900 dark:bg-gray-500"
  348. :class="{
  349. 'rounded-t-lg border-t': hasDirectionUp,
  350. 'rounded-b-lg border-b': !hasDirectionUp,
  351. }"
  352. >
  353. <div
  354. v-if="isChildPage || dropdownActions.length"
  355. class="flex w-full justify-between gap-2 px-2.5 py-1.5"
  356. >
  357. <CommonLabel
  358. v-if="isChildPage"
  359. class="text-blue-800 hover:text-black focus-visible:rounded-sm focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-1 focus-visible:outline-blue-800 dark:text-blue-800 dark:hover:text-white"
  360. :aria-label="$t('Back to previous page')"
  361. :prefix-icon="
  362. locale.localeData?.dir === 'rtl'
  363. ? 'chevron-right'
  364. : 'chevron-left'
  365. "
  366. size="small"
  367. role="button"
  368. tabindex="0"
  369. @click.stop="goToParentPage(true)"
  370. @keypress.enter.prevent.stop="goToParentPage()"
  371. @keypress.space.prevent.stop="goToParentPage()"
  372. >
  373. {{ $t('Back') }}
  374. </CommonLabel>
  375. <div
  376. v-if="dropdownActions.length"
  377. class="flex grow justify-end gap-2"
  378. >
  379. <CommonLabel
  380. v-for="action of dropdownActions"
  381. :key="action.key"
  382. :prefix-icon="action.icon"
  383. class="text-blue-800 hover:text-black focus-visible:rounded-sm focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-1 focus-visible:outline-blue-800 dark:text-blue-800 dark:hover:text-white"
  384. size="small"
  385. role="button"
  386. tabindex="0"
  387. @click.stop="action.onClick(true)"
  388. @keypress.enter.prevent.stop="action.onClick"
  389. @keypress.space.prevent.stop="action.onClick"
  390. >
  391. {{ $t(action.label) }}
  392. </CommonLabel>
  393. </div>
  394. </div>
  395. <div
  396. :aria-label="$t('Select…')"
  397. role="listbox"
  398. :aria-multiselectable="multiple"
  399. tabindex="-1"
  400. class="w-full overflow-y-auto"
  401. >
  402. <Transition name="none" mode="out-in">
  403. <div v-if="options.length">
  404. <CommonSelectItem
  405. v-for="option in filter ? highlightedOptions : options"
  406. :key="String(option.value)"
  407. :class="{
  408. 'first:rounded-t-lg':
  409. hasDirectionUp &&
  410. !isChildPage &&
  411. (!multiple || !hasMoreSelectableOptions),
  412. 'last:rounded-b-lg': !hasDirectionUp,
  413. }"
  414. :selected="isCurrentValue(option.value)"
  415. :multiple="multiple"
  416. :option="option"
  417. :no-label-translate="noOptionsLabelTranslation"
  418. :filter="filter"
  419. :option-icon-component="optionIconComponent"
  420. @select="select($event)"
  421. @next="goToChildPage($event)"
  422. />
  423. </div>
  424. <div v-else-if="isLoading" class="flex items-center">
  425. <CommonLoader
  426. v-if="!options.length"
  427. class="ltr:ml-2 rtl:mr-2"
  428. size="small"
  429. loading
  430. />
  431. <CommonSelectItem
  432. :option="{
  433. label: __('Loading…'),
  434. value: '',
  435. disabled: true,
  436. }"
  437. no-selection-indicator
  438. />
  439. </div>
  440. <CommonSelectItem
  441. v-else-if="!options.length"
  442. :option="{
  443. label: emptyLabelText,
  444. value: '',
  445. disabled: true,
  446. }"
  447. no-selection-indicator
  448. />
  449. </Transition>
  450. <slot name="footer" />
  451. </div>
  452. </div>
  453. </div>
  454. </div>
  455. </Transition>
  456. </Teleport>
  457. </template>