|
| 1 | +/** |
| 2 | + * Copyright (c) Facebook, Inc. and its affiliates. |
| 3 | + */ |
| 4 | + |
| 5 | +import * as React from 'react'; |
| 6 | +import {useState, useEffect, useCallback} from 'react'; |
| 7 | +import TerminalBlock from './TerminalBlock'; |
| 8 | +import {IconTerminal} from '../Icon/IconTerminal'; |
| 9 | + |
| 10 | +type TabOption = { |
| 11 | + label: string; |
| 12 | + value: string; |
| 13 | + content: string; |
| 14 | +}; |
| 15 | + |
| 16 | +// Define this outside of any conditionals for SSR compatibility |
| 17 | +const STORAGE_KEY = 'react-terminal-tabs'; |
| 18 | + |
| 19 | +// Map key for active tab preferences - only used on client |
| 20 | +let activeTabsByKey: Record<string, string> = {}; |
| 21 | +let subscribersByKey: Record<string, Set<(tab: string) => void>> = {}; |
| 22 | + |
| 23 | +function saveToLocalStorage() { |
| 24 | + if (typeof window !== 'undefined') { |
| 25 | + try { |
| 26 | + localStorage.setItem(STORAGE_KEY, JSON.stringify(activeTabsByKey)); |
| 27 | + } catch (e) { |
| 28 | + // Ignore errors |
| 29 | + } |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +function getSubscribers(key: string): Set<(tab: string) => void> { |
| 34 | + if (!subscribersByKey[key]) { |
| 35 | + subscribersByKey[key] = new Set(); |
| 36 | + } |
| 37 | + return subscribersByKey[key]; |
| 38 | +} |
| 39 | + |
| 40 | +function setActiveTab(key: string, tab: string) { |
| 41 | + activeTabsByKey[key] = tab; |
| 42 | + saveToLocalStorage(); |
| 43 | + |
| 44 | + const subscribers = getSubscribers(key); |
| 45 | + subscribers.forEach((callback) => callback(tab)); |
| 46 | +} |
| 47 | + |
| 48 | +function useTabState( |
| 49 | + key: string, |
| 50 | + defaultTab: string |
| 51 | +): [string, (tab: string) => void] { |
| 52 | + // Start with the default tab for SSR |
| 53 | + const [activeTab, setLocalActiveTab] = useState(defaultTab); |
| 54 | + const [initialized, setInitialized] = useState(false); |
| 55 | + |
| 56 | + // Initialize from localStorage after mount |
| 57 | + useEffect(() => { |
| 58 | + // Read from localStorage |
| 59 | + try { |
| 60 | + const savedState = localStorage.getItem(STORAGE_KEY); |
| 61 | + if (savedState) { |
| 62 | + const parsed = JSON.parse(savedState); |
| 63 | + if (parsed && typeof parsed === 'object') { |
| 64 | + Object.assign(activeTabsByKey, parsed); |
| 65 | + } |
| 66 | + } |
| 67 | + } catch (e) { |
| 68 | + // Ignore errors |
| 69 | + } |
| 70 | + |
| 71 | + // Set up storage event listener |
| 72 | + const handleStorageChange = (e: StorageEvent) => { |
| 73 | + if (e.key === STORAGE_KEY && e.newValue) { |
| 74 | + try { |
| 75 | + const parsed = JSON.parse(e.newValue); |
| 76 | + if (parsed && typeof parsed === 'object') { |
| 77 | + Object.assign(activeTabsByKey, parsed); |
| 78 | + |
| 79 | + Object.entries(parsed).forEach(([k, value]) => { |
| 80 | + const subscribers = subscribersByKey[k]; |
| 81 | + if (subscribers) { |
| 82 | + subscribers.forEach((callback) => callback(value as string)); |
| 83 | + } |
| 84 | + }); |
| 85 | + } |
| 86 | + } catch (e) { |
| 87 | + // Ignore errors |
| 88 | + } |
| 89 | + } |
| 90 | + }; |
| 91 | + |
| 92 | + window.addEventListener('storage', handleStorageChange); |
| 93 | + |
| 94 | + // Now get the value from localStorage or keep using default |
| 95 | + const storedValue = activeTabsByKey[key] || defaultTab; |
| 96 | + setLocalActiveTab(storedValue); |
| 97 | + setInitialized(true); |
| 98 | + |
| 99 | + // Make sure this key is in our global store |
| 100 | + if (!activeTabsByKey[key]) { |
| 101 | + activeTabsByKey[key] = defaultTab; |
| 102 | + saveToLocalStorage(); |
| 103 | + } |
| 104 | + |
| 105 | + return () => { |
| 106 | + window.removeEventListener('storage', handleStorageChange); |
| 107 | + }; |
| 108 | + }, [key, defaultTab]); |
| 109 | + |
| 110 | + // Set up subscription effect |
| 111 | + useEffect(() => { |
| 112 | + // Skip if not yet initialized |
| 113 | + if (!initialized) return; |
| 114 | + |
| 115 | + const onTabChange = (newTab: string) => { |
| 116 | + setLocalActiveTab(newTab); |
| 117 | + }; |
| 118 | + |
| 119 | + const subscribers = getSubscribers(key); |
| 120 | + subscribers.add(onTabChange); |
| 121 | + |
| 122 | + return () => { |
| 123 | + subscribers.delete(onTabChange); |
| 124 | + |
| 125 | + if (subscribers.size === 0) { |
| 126 | + delete subscribersByKey[key]; |
| 127 | + } |
| 128 | + }; |
| 129 | + }, [key, initialized]); |
| 130 | + |
| 131 | + // Create a stable setter function |
| 132 | + const setTab = useCallback( |
| 133 | + (newTab: string) => { |
| 134 | + setActiveTab(key, newTab); |
| 135 | + }, |
| 136 | + [key] |
| 137 | + ); |
| 138 | + |
| 139 | + return [activeTab, setTab]; |
| 140 | +} |
| 141 | + |
| 142 | +interface TabTerminalBlockProps { |
| 143 | + /** Terminal's message level: info, warning, or error */ |
| 144 | + level?: 'info' | 'warning' | 'error'; |
| 145 | + |
| 146 | + /** |
| 147 | + * Tab options, each with a label, value, and content. |
| 148 | + * Example: [ |
| 149 | + * { label: 'npm', value: 'npm', content: 'npm install react' }, |
| 150 | + * { label: 'Bun', value: 'bun', content: 'bun install react' } |
| 151 | + * ] |
| 152 | + */ |
| 153 | + tabs?: Array<TabOption>; |
| 154 | + |
| 155 | + /** Optional initial active tab value */ |
| 156 | + defaultTab?: string; |
| 157 | + |
| 158 | + /** |
| 159 | + * Optional storage key for tab state. |
| 160 | + * All TabTerminalBlocks with the same key will share tab selection. |
| 161 | + */ |
| 162 | + storageKey?: string; |
| 163 | +} |
| 164 | + |
| 165 | +/** |
| 166 | + * TabTerminalBlock displays a terminal block with tabs. |
| 167 | + * Tabs sync across instances with the same storageKey. |
| 168 | + * |
| 169 | + * @example |
| 170 | + * <TabTerminalBlock |
| 171 | + * tabs={[ |
| 172 | + * { label: 'npm', value: 'npm', content: 'npm install react' }, |
| 173 | + * { label: 'Bun', value: 'bun', content: 'bun install react' } |
| 174 | + * ]} |
| 175 | + * /> |
| 176 | + */ |
| 177 | +function TabTerminalBlock({ |
| 178 | + level = 'info', |
| 179 | + tabs = [], |
| 180 | + defaultTab, |
| 181 | + storageKey = 'package-manager', |
| 182 | +}: TabTerminalBlockProps) { |
| 183 | + // Create a fallback tab if none provided |
| 184 | + const safeTabsList = |
| 185 | + tabs && tabs.length > 0 |
| 186 | + ? tabs |
| 187 | + : [{label: 'Terminal', value: 'default', content: 'No content provided'}]; |
| 188 | + |
| 189 | + // Always use the first tab as initial defaultTab for SSR consistency |
| 190 | + // This ensures server and client render the same content initially |
| 191 | + const initialDefaultTab = defaultTab || safeTabsList[0].value; |
| 192 | + |
| 193 | + // Set up tab state |
| 194 | + const [activeTab, setTabValue] = useTabState(storageKey, initialDefaultTab); |
| 195 | + |
| 196 | + const handleTabClick = useCallback( |
| 197 | + (tabValue: string) => { |
| 198 | + return () => setTabValue(tabValue); |
| 199 | + }, |
| 200 | + [setTabValue] |
| 201 | + ); |
| 202 | + |
| 203 | + // Handle the case with no content - after hooks have been called |
| 204 | + if ( |
| 205 | + safeTabsList.length === 0 || |
| 206 | + safeTabsList[0].content === 'No content provided' |
| 207 | + ) { |
| 208 | + return ( |
| 209 | + <TerminalBlock level="error"> |
| 210 | + Error: No tab content provided |
| 211 | + </TerminalBlock> |
| 212 | + ); |
| 213 | + } |
| 214 | + |
| 215 | + const activeTabOption = |
| 216 | + safeTabsList.find((tab) => tab.value === activeTab) || safeTabsList[0]; |
| 217 | + |
| 218 | + const customHeader = ( |
| 219 | + <div className="flex items-center"> |
| 220 | + <IconTerminal className="mr-3" /> |
| 221 | + <div className="flex items-center"> |
| 222 | + {safeTabsList.map((tab) => ( |
| 223 | + <button |
| 224 | + key={tab.value} |
| 225 | + className={`text-sm font-medium px-3 py-1 h-7 mx-0.5 inline-flex items-center justify-center rounded-sm transition-colors ${ |
| 226 | + activeTab === tab.value |
| 227 | + ? 'bg-gray-50/50 text-primary dark:bg-gray-800/30 dark:text-primary-dark' |
| 228 | + : 'text-primary dark:text-primary-dark hover:bg-gray-50/30 dark:hover:bg-gray-800/20' |
| 229 | + }`} |
| 230 | + onClick={handleTabClick(tab.value)}> |
| 231 | + {tab.label} |
| 232 | + </button> |
| 233 | + ))} |
| 234 | + </div> |
| 235 | + </div> |
| 236 | + ); |
| 237 | + |
| 238 | + return ( |
| 239 | + <TerminalBlock level={level} customHeader={customHeader}> |
| 240 | + {activeTabOption.content} |
| 241 | + </TerminalBlock> |
| 242 | + ); |
| 243 | +} |
| 244 | + |
| 245 | +export default TabTerminalBlock; |
0 commit comments