Line data Source code
1 : <template>
2 1681 : <button
3 : :id="`tab-${props.value}`"
4 : role="tab"
5 : type="button"
6 : :aria-selected="isActive"
7 : :aria-controls="`tabpanel-${props.value}`"
8 : :data-state="isActive ? 'active' : 'inactive'"
9 : :tabindex="isActive ? 0 : -1"
10 : :class="
11 : cn(
12 : 'flex h-8 shrink-0 items-center justify-center',
13 : 'px-2.5',
14 : tabStateVariants({ active: isActive }),
15 : props.class
16 : )
17 : "
18 : @click="handleClick"
19 : @keydown="handleKeydown"
20 : >
21 : <slot />
22 : </button>
23 : </template>
24 :
25 : <script setup lang="ts" generic="T extends string = string">
26 : import type { HTMLAttributes } from 'vue'
27 :
28 : import { computed, inject } from 'vue'
29 :
30 : import { cn } from '@comfyorg/tailwind-utils'
31 :
32 : import { tabStateVariants } from './tab.variants'
33 : import { TAB_LIST_INJECTION_KEY } from './tabKeys'
34 :
35 984 : const props = defineProps<{
36 : value: T
37 : class?: HTMLAttributes['class']
38 : }>()
39 :
40 984 : const context = inject(TAB_LIST_INJECTION_KEY)
41 :
42 984 : const isActive = computed(() => context?.modelValue.value === props.value)
43 :
44 64 : function handleClick() {
45 64 : context?.select(props.value)
46 : }
47 :
48 0 : function handleKeydown(event: KeyboardEvent) {
49 0 : const tablist = (event.currentTarget as HTMLElement).parentElement
50 0 : if (!tablist) return
51 :
52 0 : const tabs = Array.from(tablist.querySelectorAll<HTMLElement>('[role="tab"]'))
53 0 : const currentIndex = tabs.indexOf(event.currentTarget as HTMLElement)
54 :
55 0 : let targetIndex = -1
56 :
57 0 : if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
58 0 : targetIndex = (currentIndex + 1) % tabs.length
59 0 : } else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
60 0 : targetIndex = (currentIndex - 1 + tabs.length) % tabs.length
61 0 : } else if (event.key === 'Home') {
62 0 : targetIndex = 0
63 0 : } else if (event.key === 'End') {
64 0 : targetIndex = tabs.length - 1
65 : }
66 :
67 0 : if (targetIndex !== -1) {
68 0 : event.preventDefault()
69 0 : tabs[targetIndex].focus()
70 : }
71 : }
72 : </script>
|