-
Notifications
You must be signed in to change notification settings - Fork 7.7k
/
Copy pathTabTerminalBlock.tsx
245 lines (209 loc) · 6.54 KB
/
TabTerminalBlock.tsx
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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*/
import * as React from 'react';
import {useState, useEffect, useCallback} from 'react';
import TerminalBlock from './TerminalBlock';
import {IconTerminal} from '../Icon/IconTerminal';
type TabOption = {
label: string;
value: string;
content: string;
};
// Define this outside of any conditionals for SSR compatibility
const STORAGE_KEY = 'react-terminal-tabs';
// Map key for active tab preferences - only used on client
let activeTabsByKey: Record<string, string> = {};
let subscribersByKey: Record<string, Set<(tab: string) => void>> = {};
function saveToLocalStorage() {
if (typeof window !== 'undefined') {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(activeTabsByKey));
} catch (e) {
// Ignore errors
}
}
}
function getSubscribers(key: string): Set<(tab: string) => void> {
if (!subscribersByKey[key]) {
subscribersByKey[key] = new Set();
}
return subscribersByKey[key];
}
function setActiveTab(key: string, tab: string) {
activeTabsByKey[key] = tab;
saveToLocalStorage();
const subscribers = getSubscribers(key);
subscribers.forEach((callback) => callback(tab));
}
function useTabState(
key: string,
defaultTab: string
): [string, (tab: string) => void] {
// Start with the default tab for SSR
const [activeTab, setLocalActiveTab] = useState(defaultTab);
const [initialized, setInitialized] = useState(false);
// Initialize from localStorage after mount
useEffect(() => {
// Read from localStorage
try {
const savedState = localStorage.getItem(STORAGE_KEY);
if (savedState) {
const parsed = JSON.parse(savedState);
if (parsed && typeof parsed === 'object') {
Object.assign(activeTabsByKey, parsed);
}
}
} catch (e) {
// Ignore errors
}
// Set up storage event listener
const handleStorageChange = (e: StorageEvent) => {
if (e.key === STORAGE_KEY && e.newValue) {
try {
const parsed = JSON.parse(e.newValue);
if (parsed && typeof parsed === 'object') {
Object.assign(activeTabsByKey, parsed);
Object.entries(parsed).forEach(([k, value]) => {
const subscribers = subscribersByKey[k];
if (subscribers) {
subscribers.forEach((callback) => callback(value as string));
}
});
}
} catch (e) {
// Ignore errors
}
}
};
window.addEventListener('storage', handleStorageChange);
// Now get the value from localStorage or keep using default
const storedValue = activeTabsByKey[key] || defaultTab;
setLocalActiveTab(storedValue);
setInitialized(true);
// Make sure this key is in our global store
if (!activeTabsByKey[key]) {
activeTabsByKey[key] = defaultTab;
saveToLocalStorage();
}
return () => {
window.removeEventListener('storage', handleStorageChange);
};
}, [key, defaultTab]);
// Set up subscription effect
useEffect(() => {
// Skip if not yet initialized
if (!initialized) return;
const onTabChange = (newTab: string) => {
setLocalActiveTab(newTab);
};
const subscribers = getSubscribers(key);
subscribers.add(onTabChange);
return () => {
subscribers.delete(onTabChange);
if (subscribers.size === 0) {
delete subscribersByKey[key];
}
};
}, [key, initialized]);
// Create a stable setter function
const setTab = useCallback(
(newTab: string) => {
setActiveTab(key, newTab);
},
[key]
);
return [activeTab, setTab];
}
interface TabTerminalBlockProps {
/** Terminal's message level: info, warning, or error */
level?: 'info' | 'warning' | 'error';
/**
* Tab options, each with a label, value, and content.
* Example: [
* { label: 'npm', value: 'npm', content: 'npm install react' },
* { label: 'Bun', value: 'bun', content: 'bun install react' }
* ]
*/
tabs?: Array<TabOption>;
/** Optional initial active tab value */
defaultTab?: string;
/**
* Optional storage key for tab state.
* All TabTerminalBlocks with the same key will share tab selection.
*/
storageKey?: string;
}
/**
* TabTerminalBlock displays a terminal block with tabs.
* Tabs sync across instances with the same storageKey.
*
* @example
* <TabTerminalBlock
* tabs={[
* { label: 'npm', value: 'npm', content: 'npm install react' },
* { label: 'Bun', value: 'bun', content: 'bun install react' }
* ]}
* />
*/
function TabTerminalBlock({
level = 'info',
tabs = [],
defaultTab,
storageKey = 'package-manager',
}: TabTerminalBlockProps) {
// Create a fallback tab if none provided
const safeTabsList =
tabs && tabs.length > 0
? tabs
: [{label: 'Terminal', value: 'default', content: 'No content provided'}];
// Always use the first tab as initial defaultTab for SSR consistency
// This ensures server and client render the same content initially
const initialDefaultTab = defaultTab || safeTabsList[0].value;
// Set up tab state
const [activeTab, setTabValue] = useTabState(storageKey, initialDefaultTab);
const handleTabClick = useCallback(
(tabValue: string) => {
return () => setTabValue(tabValue);
},
[setTabValue]
);
// Handle the case with no content - after hooks have been called
if (
safeTabsList.length === 0 ||
safeTabsList[0].content === 'No content provided'
) {
return (
<TerminalBlock level="error">
Error: No tab content provided
</TerminalBlock>
);
}
const activeTabOption =
safeTabsList.find((tab) => tab.value === activeTab) || safeTabsList[0];
const customHeader = (
<div className="flex items-center">
<IconTerminal className="mr-3" />
<div className="flex items-center">
{safeTabsList.map((tab) => (
<button
key={tab.value}
className={`text-sm font-medium px-3 py-1 h-7 mx-0.5 inline-flex items-center justify-center rounded-sm transition-colors ${
activeTab === tab.value
? 'bg-gray-50/50 text-primary dark:bg-gray-800/30 dark:text-primary-dark'
: 'text-primary dark:text-primary-dark hover:bg-gray-50/30 dark:hover:bg-gray-800/20'
}`}
onClick={handleTabClick(tab.value)}>
{tab.label}
</button>
))}
</div>
</div>
);
return (
<TerminalBlock level={level} customHeader={customHeader}>
{activeTabOption.content}
</TerminalBlock>
);
}
export default TabTerminalBlock;