CommonSelect.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 {
  10. computed,
  11. type ConcreteComponent,
  12. nextTick,
  13. onUnmounted,
  14. ref,
  15. type Ref,
  16. toRef,
  17. } from 'vue'
  18. import CommonLabel from '#shared/components/CommonLabel/CommonLabel.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 { useTransitionCollapse } from '#desktop/composables/useTransitionCollapse.ts'
  33. import CommonSelectItem from './CommonSelectItem.vue'
  34. import { useCommonSelect } from './useCommonSelect.ts'
  35. import type {
  36. CommonSelectInternalInstance,
  37. DropdownOptionsAction,
  38. } from './types.ts'
  39. export interface Props {
  40. modelValue?:
  41. | SelectValue
  42. | SelectValue[]
  43. | { value: SelectValue; label: string }
  44. | null
  45. options: AutoCompleteOption[] | SelectOption[]
  46. /**
  47. * Do not modify local value
  48. */
  49. passive?: boolean
  50. multiple?: boolean
  51. noClose?: boolean
  52. noRefocus?: boolean
  53. owner?: string
  54. noOptionsLabelTranslation?: boolean
  55. filter?: string
  56. optionIconComponent?: ConcreteComponent
  57. initiallyEmpty?: boolean
  58. emptyInitialLabelText?: string
  59. actions?: DropdownOptionsAction[]
  60. isChildPage?: boolean
  61. }
  62. const props = withDefaults(defineProps<Props>(), {
  63. emptyInitialLabelText: __('Start typing to search…'),
  64. })
  65. const emit = defineEmits<{
  66. 'update:modelValue': [option: string | number | (string | number)[]]
  67. select: [option: SelectOption]
  68. push: [option: AutoCompleteOption]
  69. pop: []
  70. close: []
  71. focusFilterInput: []
  72. }>()
  73. const dropdownElement = ref<HTMLElement>()
  74. const localValue = useVModel(props, 'modelValue', emit)
  75. // TODO: do we really want this initial transforming of the value, when it's null?
  76. if (localValue.value == null && props.multiple) {
  77. localValue.value = []
  78. }
  79. const getFocusableOptions = () => {
  80. return Array.from<HTMLElement>(
  81. dropdownElement.value?.querySelectorAll('[tabindex="0"]') || [],
  82. )
  83. }
  84. const showDropdown = ref(false)
  85. let inputElementBounds: UseElementBoundingReturn
  86. let windowHeight: Ref<number>
  87. const hasDirectionUp = computed(() => {
  88. if (!inputElementBounds || !windowHeight) return false
  89. return inputElementBounds.y.value > windowHeight.value / 2
  90. })
  91. const dropdownStyle = computed(() => {
  92. if (!inputElementBounds) return { top: 0, left: 0, width: 0, maxHeight: 0 }
  93. const style: Record<string, string> = {
  94. left: `${inputElementBounds.left.value}px`,
  95. width: `${inputElementBounds.width.value}px`,
  96. maxHeight: `calc(50vh - ${inputElementBounds.height.value}px)`,
  97. }
  98. if (hasDirectionUp.value) {
  99. style.bottom = `${windowHeight.value - inputElementBounds.top.value}px`
  100. } else {
  101. style.top = `${
  102. inputElementBounds.top.value + inputElementBounds.height.value
  103. }px`
  104. }
  105. return style
  106. })
  107. const { activateTabTrap, deactivateTabTrap } = useTrapTab(dropdownElement)
  108. let lastFocusableOutsideElement: HTMLElement | null = null
  109. const getActiveElement = () => {
  110. if (props.owner) {
  111. return document.getElementById(props.owner)
  112. }
  113. return document.activeElement as HTMLElement
  114. }
  115. const { instances } = useCommonSelect()
  116. const closeDropdown = () => {
  117. deactivateTabTrap()
  118. showDropdown.value = false
  119. emit('close')
  120. // TODO: move to existing nextTick.
  121. if (!props.noRefocus) {
  122. nextTick(() => lastFocusableOutsideElement?.focus())
  123. }
  124. nextTick(() => {
  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()
  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('focusFilterInput')
  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="dropdownElement"
  342. class="fixed z-10 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-white 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 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"
  360. :aria-label="$t('Back to previous page')"
  361. :prefix-icon="
  362. locale.localeData?.dir === 'rtl'
  363. ? 'chevron-right'
  364. : 'chevron-left'
  365. "
  366. role="button"
  367. tabindex="0"
  368. @click.stop="goToParentPage(true)"
  369. @keypress.enter.prevent.stop="goToParentPage()"
  370. @keypress.space.prevent.stop="goToParentPage()"
  371. >
  372. {{ $t('Back') }}
  373. </CommonLabel>
  374. <div
  375. v-if="dropdownActions.length"
  376. class="flex grow justify-end gap-2"
  377. >
  378. <CommonLabel
  379. v-for="action of dropdownActions"
  380. :key="action.key"
  381. :prefix-icon="action.icon"
  382. class="text-blue-800 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"
  383. role="button"
  384. tabindex="0"
  385. @click.stop="action.onClick(true)"
  386. @keypress.enter.prevent.stop="action.onClick"
  387. @keypress.space.prevent.stop="action.onClick"
  388. >
  389. {{ $t(action.label) }}
  390. </CommonLabel>
  391. </div>
  392. </div>
  393. <div
  394. :aria-label="$t('Select…')"
  395. role="listbox"
  396. :aria-multiselectable="multiple"
  397. tabindex="-1"
  398. class="w-full overflow-y-auto"
  399. >
  400. <CommonSelectItem
  401. v-for="option in filter ? highlightedOptions : options"
  402. :key="String(option.value)"
  403. :class="{
  404. 'first:rounded-t-lg':
  405. hasDirectionUp &&
  406. !isChildPage &&
  407. (!multiple || !hasMoreSelectableOptions),
  408. 'last:rounded-b-lg': !hasDirectionUp,
  409. }"
  410. :selected="isCurrentValue(option.value)"
  411. :multiple="multiple"
  412. :option="option"
  413. :no-label-translate="noOptionsLabelTranslation"
  414. :filter="filter"
  415. :option-icon-component="optionIconComponent"
  416. @select="select($event)"
  417. @next="goToChildPage($event)"
  418. />
  419. <CommonSelectItem
  420. v-if="!options.length"
  421. :option="{
  422. label: emptyLabelText,
  423. value: '',
  424. disabled: true,
  425. }"
  426. no-selection-indicator
  427. />
  428. <slot name="footer" />
  429. </div>
  430. </div>
  431. </div>
  432. </div>
  433. </Transition>
  434. </Teleport>
  435. </template>