CommonSelect.vue 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. <!-- Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/ -->
  2. <script setup lang="ts">
  3. import { onClickOutside, onKeyDown, useVModel } from '@vueuse/core'
  4. import { useTemplateRef, onUnmounted, computed, nextTick, ref } from 'vue'
  5. import type { SelectOption } from '#shared/components/CommonSelect/types.ts'
  6. import { useFocusWhenTyping } from '#shared/composables/useFocusWhenTyping.ts'
  7. import { useTrapTab } from '#shared/composables/useTrapTab.ts'
  8. import { useTraverseOptions } from '#shared/composables/useTraverseOptions.ts'
  9. import stopEvent from '#shared/utils/events.ts'
  10. import testFlags from '#shared/utils/testFlags.ts'
  11. import CommonSelectItem from './CommonSelectItem.vue'
  12. import { useCommonSelect } from './useCommonSelect.ts'
  13. import type { CommonSelectInternalInstance } from './types.ts'
  14. import type { Ref } from 'vue'
  15. export interface Props {
  16. // we cannot move types into separate file, because Vue would not be able to
  17. // transform these into runtime types
  18. modelValue?: string | number | boolean | (string | number | boolean)[] | null
  19. options: SelectOption[]
  20. /**
  21. * Do not modify local value
  22. */
  23. passive?: boolean
  24. multiple?: boolean
  25. noClose?: boolean
  26. noRefocus?: boolean
  27. owner?: string
  28. noOptionsLabelTranslation?: boolean
  29. }
  30. const props = defineProps<Props>()
  31. const emit = defineEmits<{
  32. 'update:modelValue': [option: string | number | (string | number)[]]
  33. select: [option: SelectOption]
  34. close: []
  35. }>()
  36. const dialogElement = useTemplateRef('dialog')
  37. const localValue = useVModel(props, 'modelValue', emit)
  38. // TODO: do we really want this initial transfomring of the value, when it's null?
  39. if (localValue.value == null && props.multiple) {
  40. localValue.value = []
  41. }
  42. const getFocusableOptions = () => {
  43. return Array.from<HTMLElement>(
  44. dialogElement.value?.querySelectorAll('[tabindex="0"]') || [],
  45. )
  46. }
  47. const showDialog = ref(false)
  48. let lastFocusableOutsideElement: HTMLElement | null = null
  49. const getActiveElement = () => {
  50. if (props.owner) {
  51. return document.getElementById(props.owner)
  52. }
  53. return document.activeElement as HTMLElement
  54. }
  55. const openDialog = () => {
  56. showDialog.value = true
  57. lastFocusableOutsideElement = getActiveElement()
  58. requestAnimationFrame(() => {
  59. // https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role#keyboard_interactions
  60. // focus selected or first available option
  61. const focusableElements = getFocusableOptions()
  62. const selected = focusableElements.find(
  63. (el) => el.getAttribute('aria-selected') === 'true',
  64. )
  65. const focusElement = selected || focusableElements[0]
  66. focusElement?.focus()
  67. nextTick(() => {
  68. testFlags.set('common-select.opened')
  69. })
  70. })
  71. }
  72. const closeDialog = () => {
  73. showDialog.value = false
  74. emit('close')
  75. if (!props.noRefocus) {
  76. nextTick(() => lastFocusableOutsideElement?.focus())
  77. }
  78. nextTick(() => {
  79. testFlags.set('common-select.closed')
  80. })
  81. }
  82. const exposedInstance: CommonSelectInternalInstance = {
  83. isOpen: computed(() => showDialog.value),
  84. openDialog,
  85. closeDialog,
  86. getFocusableOptions,
  87. }
  88. const { instances } = useCommonSelect()
  89. instances.value.add(exposedInstance)
  90. onUnmounted(() => {
  91. instances.value.delete(exposedInstance)
  92. })
  93. defineExpose(exposedInstance)
  94. // https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role#keyboard_interactions
  95. useTraverseOptions(dialogElement, { direction: 'vertical' })
  96. // - Type-ahead is recommended for all listboxes, especially those with more than seven options
  97. useFocusWhenTyping(dialogElement)
  98. onClickOutside(dialogElement, closeDialog)
  99. useTrapTab(dialogElement)
  100. onKeyDown(
  101. 'Escape',
  102. (event) => {
  103. stopEvent(event)
  104. closeDialog()
  105. },
  106. { target: dialogElement as Ref<EventTarget> },
  107. )
  108. const isCurrentValue = (value: string | number | boolean) => {
  109. if (props.multiple && Array.isArray(localValue.value)) {
  110. return localValue.value.includes(value)
  111. }
  112. return localValue.value === value
  113. }
  114. const select = (option: SelectOption) => {
  115. if (option.disabled) return
  116. emit('select', option)
  117. if (props.passive) {
  118. if (!props.multiple) {
  119. closeDialog()
  120. }
  121. return
  122. }
  123. if (props.multiple && Array.isArray(localValue.value)) {
  124. if (localValue.value.includes(option.value)) {
  125. localValue.value = localValue.value.filter((v) => v !== option.value)
  126. } else {
  127. localValue.value.push(option.value)
  128. }
  129. return
  130. }
  131. if (props.modelValue === option.value) {
  132. localValue.value = undefined
  133. } else {
  134. localValue.value = option.value
  135. }
  136. if (!props.multiple && !props.noClose) {
  137. closeDialog()
  138. }
  139. }
  140. const duration = VITE_TEST_MODE ? undefined : { enter: 300, leave: 200 }
  141. </script>
  142. <template>
  143. <slot :state="showDialog" :open="openDialog" :close="closeDialog" />
  144. <Teleport to="body">
  145. <Transition :duration="duration">
  146. <div
  147. v-if="showDialog"
  148. id="common-select"
  149. class="fixed inset-0 z-10 flex overflow-y-auto"
  150. :aria-label="$t('Dialog window with selections')"
  151. role="dialog"
  152. >
  153. <!-- empty @click is needed for https://stackoverflow.com/a/39712411 -->
  154. <div
  155. class="select-overlay fixed inset-0 flex h-full w-full bg-gray-500 opacity-60"
  156. data-test-id="dialog-overlay"
  157. role="presentation"
  158. @click="void 0"
  159. ></div>
  160. <div class="select-dialog relative m-auto">
  161. <div
  162. class="flex min-w-[294px] max-w-[90vw] flex-col items-start rounded-xl bg-gray-400/80 backdrop-blur-[15px]"
  163. >
  164. <div
  165. ref="dialog"
  166. :aria-label="$t('Select…')"
  167. role="listbox"
  168. :aria-multiselectable="multiple"
  169. class="max-h-[50vh] w-full divide-y divide-solid divide-white/10 overflow-y-auto"
  170. >
  171. <CommonSelectItem
  172. v-for="option in options"
  173. :key="String(option.value)"
  174. :selected="isCurrentValue(option.value)"
  175. :multiple="multiple"
  176. :option="option"
  177. :no-label-translate="noOptionsLabelTranslation"
  178. @select="select($event)"
  179. />
  180. <slot name="footer" />
  181. </div>
  182. </div>
  183. </div>
  184. </div>
  185. </Transition>
  186. </Teleport>
  187. </template>
  188. <style scoped>
  189. .v-enter-active {
  190. .select-overlay,
  191. .select-dialog {
  192. @apply duration-300 ease-out;
  193. }
  194. }
  195. .v-leave-active {
  196. .select-overlay,
  197. .select-dialog {
  198. @apply duration-200 ease-in;
  199. }
  200. }
  201. .v-enter-to,
  202. .v-leave-from {
  203. .select-dialog {
  204. @apply scale-100 opacity-100;
  205. }
  206. .select-overlay {
  207. @apply opacity-60;
  208. }
  209. }
  210. .v-enter-from,
  211. .v-leave-to {
  212. .select-dialog {
  213. @apply scale-95 opacity-0;
  214. }
  215. .select-overlay {
  216. @apply opacity-0;
  217. }
  218. }
  219. </style>