CommonSelect.vue 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. <!-- Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/ -->
  2. <script setup lang="ts">
  3. import { useFocusWhenTyping } from '#shared/composables/useFocusWhenTyping.ts'
  4. import { useTrapTab } from '#shared/composables/useTrapTab.ts'
  5. import { useTraverseOptions } from '#shared/composables/useTraverseOptions.ts'
  6. import stopEvent from '#shared/utils/events.ts'
  7. import { onClickOutside, onKeyDown, useVModel } from '@vueuse/core'
  8. import type { Ref } from 'vue'
  9. import { onUnmounted, computed, nextTick, ref } from 'vue'
  10. import type { SelectOption } from '#shared/components/CommonSelect/types.ts'
  11. import testFlags from '#shared/utils/testFlags.ts'
  12. import CommonSelectItem from './CommonSelectItem.vue'
  13. import { useCommonSelect } from './useCommonSelect.ts'
  14. import type { CommonSelectInternalInstance } from './types.ts'
  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. (e: 'update:modelValue', option: string | number | (string | number)[]): void
  33. (e: 'select', option: SelectOption): void
  34. (e: 'close'): void
  35. }>()
  36. const dialogElement = ref<HTMLElement>()
  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. @click="void 0"
  158. ></div>
  159. <div class="select-dialog relative m-auto">
  160. <div
  161. class="flex min-w-[294px] max-w-[90vw] flex-col items-start rounded-xl bg-gray-400/80 backdrop-blur-[15px]"
  162. >
  163. <div
  164. ref="dialogElement"
  165. :aria-label="$t('Select…')"
  166. role="listbox"
  167. :aria-multiselectable="multiple"
  168. class="max-h-[50vh] w-full divide-y divide-solid divide-white/10 overflow-y-auto"
  169. >
  170. <CommonSelectItem
  171. v-for="option in options"
  172. :key="String(option.value)"
  173. :selected="isCurrentValue(option.value)"
  174. :multiple="multiple"
  175. :option="option"
  176. :no-label-translate="noOptionsLabelTranslation"
  177. @select="select($event)"
  178. />
  179. <slot name="footer" />
  180. </div>
  181. </div>
  182. </div>
  183. </div>
  184. </Transition>
  185. </Teleport>
  186. </template>
  187. <style scoped>
  188. .v-enter-active {
  189. .select-overlay,
  190. .select-dialog {
  191. @apply duration-300 ease-out;
  192. }
  193. }
  194. .v-leave-active {
  195. .select-overlay,
  196. .select-dialog {
  197. @apply duration-200 ease-in;
  198. }
  199. }
  200. .v-enter-to,
  201. .v-leave-from {
  202. .select-dialog {
  203. @apply scale-100 opacity-100;
  204. }
  205. .select-overlay {
  206. @apply opacity-60;
  207. }
  208. }
  209. .v-enter-from,
  210. .v-leave-to {
  211. .select-dialog {
  212. @apply scale-95 opacity-0;
  213. }
  214. .select-overlay {
  215. @apply opacity-0;
  216. }
  217. }
  218. </style>