|
| 1 | +import { |
| 2 | + PropFunction, |
| 3 | + component$, |
| 4 | + useContext, |
| 5 | + useId, |
| 6 | + Slot, |
| 7 | + useComputed$, |
| 8 | + useTask$, |
| 9 | + $, |
| 10 | + useVisibleTask$, |
| 11 | + useSignal, |
| 12 | +} from '@builder.io/qwik'; |
| 13 | +import { tabsContextId } from './tabs-context-id'; |
| 14 | + |
| 15 | +export interface TabProps { |
| 16 | + onClick?: PropFunction<() => void>; |
| 17 | + class?: string; |
| 18 | + selectedClassName?: string; |
| 19 | +} |
| 20 | + |
| 21 | +// Tab button inside of a tab list |
| 22 | +export const Tab = component$( |
| 23 | + ({ selectedClassName, onClick, class: classString }: TabProps) => { |
| 24 | + const contextService = useContext(tabsContextId); |
| 25 | + |
| 26 | + const uniqueId = useId(); |
| 27 | + |
| 28 | + const currentTabIndex = useSignal(0); |
| 29 | + |
| 30 | + const isSelectedSignal = useSignal(false); |
| 31 | + |
| 32 | + useTask$(({ cleanup }) => { |
| 33 | + contextService.tabsChanged$(); |
| 34 | + |
| 35 | + cleanup(() => { |
| 36 | + contextService.tabsChanged$(); |
| 37 | + }); |
| 38 | + }); |
| 39 | + |
| 40 | + useTask$(({ track }) => { |
| 41 | + track(contextService.indexByTabId); |
| 42 | + console.log('contextService.indexByTabId', contextService.indexByTabId); |
| 43 | + currentTabIndex.value = contextService.indexByTabId[uniqueId]; |
| 44 | + }); |
| 45 | + |
| 46 | + useVisibleTask$(() => { |
| 47 | + console.log( |
| 48 | + 'contextService.selectedIndex.value', |
| 49 | + contextService.selectedIndex.value |
| 50 | + ); |
| 51 | + console.log('currentTabIndex.value', currentTabIndex.value); |
| 52 | + isSelectedSignal.value = |
| 53 | + contextService.selectedIndex.value === currentTabIndex.value; |
| 54 | + }); |
| 55 | + |
| 56 | + const selectTab$ = $(() => { |
| 57 | + contextService.selectedIndex.value = currentTabIndex.value; |
| 58 | + }); |
| 59 | + |
| 60 | + const selectIfAutomatic$ = $(() => { |
| 61 | + if (contextService.behavior === 'automatic') { |
| 62 | + selectTab$(); |
| 63 | + } |
| 64 | + }); |
| 65 | + |
| 66 | + return ( |
| 67 | + <button |
| 68 | + data-tab-id={uniqueId} |
| 69 | + type="button" |
| 70 | + role="tab" |
| 71 | + onFocus$={selectIfAutomatic$} |
| 72 | + onMouseEnter$={selectIfAutomatic$} |
| 73 | + aria-selected={isSelectedSignal.value} |
| 74 | + aria-controls={'tabpanel-' + currentTabIndex.value} |
| 75 | + class={`${isSelectedSignal ? `selected ${selectedClassName}` : ''}${ |
| 76 | + classString ? ` ${classString}` : '' |
| 77 | + }`} |
| 78 | + onClick$={async () => { |
| 79 | + await selectTab$(); |
| 80 | + if (onClick) { |
| 81 | + onClick(); |
| 82 | + } |
| 83 | + }} |
| 84 | + > |
| 85 | + <Slot /> |
| 86 | + </button> |
| 87 | + ); |
| 88 | + } |
| 89 | +); |
0 commit comments