Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | 'use client'; /** * Tabs Compound Component * * A flexible, accessible tabs component using the compound component pattern. * Supports keyboard navigation, ARIA attributes, and custom styling. * * @example * ```tsx * <Tabs defaultTab="details" onChange={handleTabChange}> * <Tabs.List> * <Tabs.Tab value="details">Details</Tabs.Tab> * <Tabs.Tab value="reviews">Reviews</Tabs.Tab> * <Tabs.Tab value="shipping">Shipping</Tabs.Tab> * </Tabs.List> * <Tabs.Panel value="details"> * <ProductDetails product={product} /> * </Tabs.Panel> * <Tabs.Panel value="reviews"> * <ProductReviews reviews={reviews} /> * </Tabs.Panel> * <Tabs.Panel value="shipping"> * <ShippingInfo /> * </Tabs.Panel> * </Tabs> * ``` */ import { createContext, useContext, useState, useCallback, useMemo, ReactNode, memo, KeyboardEvent, useRef, useId, } from 'react'; import { cn } from '@/lib/core'; // ============================================================================ // CONTEXT // ============================================================================ interface TabsContextValue { activeTab: string; setActiveTab: (tab: string) => void; baseId: string; } const TabsContext = createContext<TabsContextValue | null>(null); function useTabs(): TabsContextValue { const context = useContext(TabsContext); if (!context) { throw new Error('Tabs compound components must be used within a Tabs root'); } return context; } // ============================================================================ // ROOT COMPONENT // ============================================================================ interface TabsRootProps { /** The default active tab value */ defaultTab: string; /** Tab content */ children: ReactNode; /** Additional CSS classes */ className?: string; /** Callback when active tab changes */ onChange?: (tab: string) => void; /** Controlled active tab value */ value?: string; } function TabsRoot({ defaultTab, children, className, onChange, value, }: TabsRootProps) { const [internalTab, setInternalTab] = useState(defaultTab); const baseId = useId(); // Support both controlled and uncontrolled modes const activeTab = value ?? internalTab; const setActiveTab = useCallback( (tab: string) => { if (value === undefined) { setInternalTab(tab); } onChange?.(tab); }, [onChange, value] ); const contextValue = useMemo( () => ({ activeTab, setActiveTab, baseId }), [activeTab, setActiveTab, baseId] ); return ( <TabsContext.Provider value={contextValue}> <div className={cn('tabs', className)}>{children}</div> </TabsContext.Provider> ); } // ============================================================================ // TAB LIST COMPONENT // ============================================================================ interface TabListProps { /** Tab buttons */ children: ReactNode; /** Additional CSS classes */ className?: string; /** Visual variant */ variant?: 'underline' | 'pills' | 'bordered'; } const TabList = memo(function TabList({ children, className, variant = 'underline', }: TabListProps) { const tabListRef = useRef<HTMLDivElement>(null); const variantStyles = { underline: 'border-b border-gray-200 dark:border-gray-700', pills: 'bg-gray-100 dark:bg-gray-800 p-1 rounded-lg gap-1', bordered: 'border border-gray-200 dark:border-gray-700 rounded-lg p-1 gap-1', }; const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => { const tabs = tabListRef.current?.querySelectorAll('[role="tab"]:not([disabled])'); if (!tabs?.length) return; const tabsArray = Array.from(tabs) as HTMLButtonElement[]; const currentIndex = tabsArray.findIndex( (tab) => tab === document.activeElement ); let nextIndex: number; switch (event.key) { case 'ArrowLeft': nextIndex = currentIndex > 0 ? currentIndex - 1 : tabsArray.length - 1; tabsArray[nextIndex]?.focus(); event.preventDefault(); break; case 'ArrowRight': nextIndex = currentIndex < tabsArray.length - 1 ? currentIndex + 1 : 0; tabsArray[nextIndex]?.focus(); event.preventDefault(); break; case 'Home': tabsArray[0]?.focus(); event.preventDefault(); break; case 'End': tabsArray[tabsArray.length - 1]?.focus(); event.preventDefault(); break; } }; return ( <div ref={tabListRef} role="tablist" aria-orientation="horizontal" onKeyDown={handleKeyDown} className={cn('flex', variantStyles[variant], className)} > {children} </div> ); }); // ============================================================================ // TAB COMPONENT // ============================================================================ interface TabProps { /** Unique value for this tab */ value: string; /** Tab label content */ children: ReactNode; /** Additional CSS classes */ className?: string; /** Whether the tab is disabled */ disabled?: boolean; /** Icon to display before the label */ icon?: ReactNode; } const Tab = memo(function Tab({ value, children, className, disabled = false, icon, }: TabProps) { const { activeTab, setActiveTab, baseId } = useTabs(); const isActive = activeTab === value; const handleClick = () => { if (!disabled) { setActiveTab(value); } }; return ( <button role="tab" type="button" aria-selected={isActive} aria-controls={`${baseId}-panel-${value}`} id={`${baseId}-tab-${value}`} tabIndex={isActive ? 0 : -1} disabled={disabled} onClick={handleClick} className={cn( 'px-4 py-2 font-medium text-sm transition-colors whitespace-nowrap', 'focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2', 'dark:focus-visible:ring-offset-gray-900', isActive ? 'border-b-2 border-blue-500 text-blue-600 dark:text-blue-400 -mb-px' : 'text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200', disabled && 'opacity-50 cursor-not-allowed', className )} > {icon && <span className="mr-2">{icon}</span>} {children} </button> ); }); // ============================================================================ // TAB PANEL COMPONENT // ============================================================================ interface TabPanelProps { /** Value matching the corresponding Tab */ value: string; /** Panel content */ children: ReactNode; /** Additional CSS classes */ className?: string; /** Whether to keep panel in DOM when inactive (for preserving state) */ keepMounted?: boolean; } const TabPanel = memo(function TabPanel({ value, children, className, keepMounted = false, }: TabPanelProps) { const { activeTab, baseId } = useTabs(); const isActive = activeTab === value; // If keepMounted is false and panel is not active, don't render if (!keepMounted && !isActive) { return null; } return ( <div role="tabpanel" id={`${baseId}-panel-${value}`} aria-labelledby={`${baseId}-tab-${value}`} hidden={!isActive} tabIndex={0} className={cn( 'py-4 focus:outline-none', !isActive && 'hidden', className )} > {children} </div> ); }); // ============================================================================ // COMPOUND EXPORT // ============================================================================ export const Tabs = Object.assign(TabsRoot, { List: TabList, Tab, Panel: TabPanel, }); export default Tabs; |