@mhjuma/traverse 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +46 -0
  3. package/src/bootstrap.spec.tsx +290 -0
  4. package/src/bootstrap.tsx +195 -0
  5. package/src/colors.ts +23 -0
  6. package/src/components/ChartPanel/ChartPanel.logic.spec.ts +358 -0
  7. package/src/components/ChartPanel/ChartPanel.logic.ts +318 -0
  8. package/src/components/ChartPanel/ChartPanel.spec.tsx +331 -0
  9. package/src/components/ChartPanel/ChartPanel.styles.ts +14 -0
  10. package/src/components/ChartPanel/ChartPanel.tsx +151 -0
  11. package/src/components/ConnectionDialog/ConnectionDialog.spec.tsx +767 -0
  12. package/src/components/ConnectionDialog/ConnectionDialog.tsx +652 -0
  13. package/src/components/ConnectionDialog/ConnectionRow.spec.tsx +104 -0
  14. package/src/components/ConnectionDialog/ConnectionRow.tsx +177 -0
  15. package/src/components/EditorToolbar/EditorToolbar.spec.tsx +599 -0
  16. package/src/components/EditorToolbar/EditorToolbar.tsx +259 -0
  17. package/src/components/Explorer/Explorer.spec.tsx +615 -0
  18. package/src/components/Explorer/Explorer.tsx +49 -0
  19. package/src/components/ExplorerWorkspace/ExplorerWorkspace.logic.spec.ts +715 -0
  20. package/src/components/ExplorerWorkspace/ExplorerWorkspace.logic.ts +324 -0
  21. package/src/components/ExplorerWorkspace/ExplorerWorkspace.spec.tsx +450 -0
  22. package/src/components/ExplorerWorkspace/ExplorerWorkspace.styles.ts +478 -0
  23. package/src/components/ExplorerWorkspace/ExplorerWorkspace.tsx +648 -0
  24. package/src/components/ExplorerWorkspace/kqlLanguage.spec.ts +321 -0
  25. package/src/components/ExplorerWorkspace/kqlLanguage.ts +155 -0
  26. package/src/components/ResultsPanel/ElapsedTimer.spec.tsx +51 -0
  27. package/src/components/ResultsPanel/ElapsedTimer.tsx +15 -0
  28. package/src/components/ResultsPanel/HistoryItem.spec.tsx +123 -0
  29. package/src/components/ResultsPanel/HistoryItem.tsx +56 -0
  30. package/src/components/ResultsPanel/ResultSetTab.tsx +18 -0
  31. package/src/components/ResultsPanel/ResultsPanel.spec.tsx +1194 -0
  32. package/src/components/ResultsPanel/ResultsPanel.tsx +321 -0
  33. package/src/components/ResultsPanel/TabButton.tsx +11 -0
  34. package/src/components/ResultsTable/ColumnHeader.tsx +42 -0
  35. package/src/components/ResultsTable/ColumnPickerItem.tsx +16 -0
  36. package/src/components/ResultsTable/FilterCell.tsx +24 -0
  37. package/src/components/ResultsTable/ResultsTable.logic.spec.ts +655 -0
  38. package/src/components/ResultsTable/ResultsTable.logic.ts +264 -0
  39. package/src/components/ResultsTable/ResultsTable.spec.tsx +930 -0
  40. package/src/components/ResultsTable/ResultsTable.styles.ts +108 -0
  41. package/src/components/ResultsTable/ResultsTable.tsx +501 -0
  42. package/src/components/ResultsTable/VirtualCell.spec.tsx +55 -0
  43. package/src/components/ResultsTable/VirtualCell.tsx +32 -0
  44. package/src/components/ResultsTable/VirtualRow.tsx +55 -0
  45. package/src/components/SchemaSidebar/FolderRow.tsx +35 -0
  46. package/src/components/SchemaSidebar/SchemaColumnItem.tsx +41 -0
  47. package/src/components/SchemaSidebar/SchemaContextMenu.spec.tsx +148 -0
  48. package/src/components/SchemaSidebar/SchemaContextMenu.tsx +49 -0
  49. package/src/components/SchemaSidebar/SchemaSidebar.logic.spec.ts +230 -0
  50. package/src/components/SchemaSidebar/SchemaSidebar.logic.ts +74 -0
  51. package/src/components/SchemaSidebar/SchemaSidebar.spec.tsx +1111 -0
  52. package/src/components/SchemaSidebar/SchemaSidebar.tsx +244 -0
  53. package/src/components/SchemaSidebar/SchemaTableItem.tsx +77 -0
  54. package/src/components/TabBar/TabBar.logic.spec.ts +127 -0
  55. package/src/components/TabBar/TabBar.logic.ts +35 -0
  56. package/src/components/TabBar/TabBar.spec.tsx +929 -0
  57. package/src/components/TabBar/TabBar.tsx +284 -0
  58. package/src/components/TabBar/TabItem.tsx +166 -0
  59. package/src/components/VegaChart/VegaChart.spec.tsx +126 -0
  60. package/src/components/VegaChart/VegaChart.tsx +224 -0
  61. package/src/config.spec.ts +44 -0
  62. package/src/config.ts +47 -0
  63. package/src/context/ExplorerColorContext.ts +14 -0
  64. package/src/context/ExplorerStateContext.ts +49 -0
  65. package/src/context/KustoClientContext.ts +12 -0
  66. package/src/context/context.spec.tsx +183 -0
  67. package/src/index.ts +14 -0
  68. package/src/services/cache.spec.ts +31 -0
  69. package/src/services/cache.ts +16 -0
  70. package/src/services/concurrency.spec.ts +139 -0
  71. package/src/services/concurrency.ts +46 -0
  72. package/src/services/kusto.spec.ts +919 -0
  73. package/src/services/kusto.ts +472 -0
  74. package/src/services/queryHistory.spec.ts +287 -0
  75. package/src/services/queryHistory.ts +146 -0
  76. package/src/services/schema.spec.ts +618 -0
  77. package/src/services/schema.ts +294 -0
  78. package/src/services/state-service.spec.ts +670 -0
  79. package/src/services/state-service.ts +602 -0
  80. package/src/services/useKustoQuery.spec.ts +234 -0
  81. package/src/services/useKustoQuery.ts +124 -0
  82. package/src/state/actions.ts +50 -0
  83. package/src/state/index.ts +3 -0
  84. package/src/state/reducer.spec.ts +644 -0
  85. package/src/state/reducer.ts +207 -0
  86. package/src/state/types.ts +54 -0
  87. package/tsconfig.json +7 -0
  88. package/tsconfig.lint.json +4 -0
  89. package/tsconfig.spec.json +7 -0
  90. package/vitest.config.ts +34 -0
@@ -0,0 +1,652 @@
1
+ import { Button, tokens, Textarea, Spinner, Menu, MenuList, MenuItem, MenuPopover, MenuTrigger, MenuSplitGroup } from '@fluentui/react-components';
2
+ import { DismissRegular, AddRegular, ArrowExportRegular, ChevronDownRegular } from '@fluentui/react-icons';
3
+ import React, { useCallback, useMemo, useRef, useState } from 'react';
4
+
5
+ import { listDatabases, getPersistedDatabases, persistDatabases, reloadSchema, getSchema } from '../../services/schema';
6
+ import { useExplorerState, useExplorerDispatch } from '../../context/ExplorerStateContext';
7
+ import { useKustoClient } from '../../context/KustoClientContext';
8
+ import { useExplorerColors } from '../../context/ExplorerColorContext';
9
+
10
+ const emptyDbs: string[] = [];
11
+ import type { KustoConnection } from '../ExplorerWorkspace/ExplorerWorkspace.logic';
12
+ import { saveConnections, shortenClusterUrl } from '../ExplorerWorkspace/ExplorerWorkspace.logic';
13
+ import { CONNECTION_COLORS } from '../../config';
14
+ import { ConnectionRow } from './ConnectionRow';
15
+ import type { ValidationStatus } from './ConnectionRow';
16
+
17
+ const stopPropagation = (e: React.MouseEvent) => e.stopPropagation();
18
+ const stopPropagationKeyDown = (e: React.KeyboardEvent) => e.stopPropagation();
19
+
20
+ const dismissIcon = <DismissRegular />;
21
+ const addIcon = <AddRegular />;
22
+ const exportIcon = <ArrowExportRegular />;
23
+ const footerStyle = { display: 'flex', justifyContent: 'space-between', gap: '8px', paddingTop: '12px', borderTop: `1px solid ${tokens.colorNeutralStroke2}`, flexShrink: 0 } as const;
24
+ const footerLeftStyle = { display: 'flex', gap: '8px' } as const;
25
+ const footerRightStyle = { display: 'flex', gap: '8px' } as const;
26
+ const importAreaStyle = { padding: '12px 0', borderTop: `1px solid ${tokens.colorNeutralStroke2}`, marginTop: '8px' } as const;
27
+ const importHintStyle = { fontSize: '12px', color: tokens.colorNeutralForeground3, marginBottom: '8px' } as const;
28
+ const saveSummaryStyle = { fontSize: '12px', color: tokens.colorPaletteRedForeground1, marginTop: '8px', flexShrink: 0 } as const;
29
+
30
+ const headerStyle = { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px', flexShrink: 0 } as const;
31
+ const titleStyle = { fontSize: '16px', fontWeight: 600, color: tokens.colorNeutralForeground1 } as const;
32
+ const listStyle = { flex: 1, overflow: 'auto', minHeight: 0 } as const;
33
+
34
+ const hiddenInputStyle = { display: 'none' } as const;
35
+ const importTextareaStyle = { width: '100%', minHeight: '80px' } as const;
36
+ const importResultsContainerStyle = { marginTop: '8px', fontSize: '12px' } as const;
37
+ const importResultSuccessStyle = { padding: '2px 0', color: tokens.colorPaletteGreenForeground1 } as const;
38
+ const importResultErrorStyle = { padding: '2px 0', color: tokens.colorPaletteRedForeground1 } as const;
39
+ const importActionsStyle = { display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: '8px', marginTop: '8px' } as const;
40
+ const chevronDownIcon = <ChevronDownRegular />;
41
+ const menuTriggerButtonStyle = { minWidth: 'auto', padding: '0 4px' } as const;
42
+
43
+ export interface ConnectionDialogProps {
44
+ onClose: () => void;
45
+ }
46
+
47
+ export function ConnectionDialog({ onClose }: ConnectionDialogProps) {
48
+ const { connections } = useExplorerState();
49
+ const dispatch = useExplorerDispatch();
50
+ const client = useKustoClient();
51
+ const { semantic } = useExplorerColors();
52
+
53
+ const backdropStyle = useMemo(() => ({ position: 'fixed' as const, top: 0, left: 0, right: 0, bottom: 0, backgroundColor: semantic.backdrop, zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }) as const, [semantic.backdrop]);
54
+ const modalStyle = useMemo(() => ({ backgroundColor: tokens.colorNeutralBackground1, borderRadius: '8px', padding: '20px 24px', width: '740px', maxHeight: '80vh', display: 'flex', flexDirection: 'column' as const, boxShadow: `0 8px 32px ${semantic.shadowMedium}` }) as const, [semantic.shadowMedium]);
55
+
56
+ const originalIds = useMemo(() => new Set(connections.map((c) => c.id)), [connections]);
57
+ const originalMap = useMemo(() => {
58
+ const map: Record<string, KustoConnection> = {};
59
+ for (const c of connections) {
60
+ map[c.id] = c;
61
+ }
62
+ return map;
63
+ }, [connections]);
64
+
65
+ const [draft, setDraft] = useState<KustoConnection[]>([...connections]);
66
+ const [dbCache, setDbCache] = useState<Record<string, string[]>>(() => {
67
+ const initial: Record<string, string[]> = {};
68
+ for (const conn of connections) {
69
+ const cached = getPersistedDatabases(conn.clusterUrl);
70
+ if (cached) {
71
+ initial[conn.clusterUrl] = cached;
72
+ }
73
+ }
74
+ return initial;
75
+ });
76
+ const [dbLoading, setDbLoading] = useState<Set<string>>(new Set());
77
+ const [validationStatus, setValidationStatus] = useState<Record<string, ValidationStatus>>({});
78
+ const [saving, setSaving] = useState(false);
79
+ const [saveSummary, setSaveSummary] = useState('');
80
+ const dragIdx = useRef<number | null>(null);
81
+ const [dragOverIdx, setDragOverIdx] = useState<number | null>(null);
82
+ const fileInputRef = useRef<HTMLInputElement>(null);
83
+
84
+ const isNewConnection = useCallback((conn: KustoConnection) => !originalIds.has(conn.id), [originalIds]);
85
+ const isModifiedConnection = useCallback((conn: KustoConnection) => {
86
+ const orig = originalMap[conn.id];
87
+ if (!orig) {
88
+ return false;
89
+ }
90
+ return orig.clusterUrl !== conn.clusterUrl || orig.database !== conn.database;
91
+ }, [originalMap]);
92
+
93
+ const [dbLoadFailed, setDbLoadFailed] = useState<Set<string>>(new Set());
94
+
95
+ // Lazy-load databases for a single cluster URL (triggered by user clicking the db dropdown)
96
+ const loadDatabases = useCallback((clusterUrl: string) => {
97
+ if (dbLoading.has(clusterUrl) || !clusterUrl.startsWith('https://')) {
98
+ return;
99
+ }
100
+ // Check if already cached in local state
101
+ const cached = dbCache[clusterUrl];
102
+ if (cached && cached.length > 0) {
103
+ // Already have it — just ensure the draft row has a database set
104
+ setDraft((prev) => prev.map((c) => {
105
+ if (c.clusterUrl !== clusterUrl) {
106
+ return c;
107
+ }
108
+ const updates: Partial<KustoConnection> = {};
109
+ if (!c.database) {
110
+ updates.database = cached[0];
111
+ }
112
+ if (!c.name) {
113
+ updates.name = shortenClusterUrl(clusterUrl);
114
+ }
115
+ return Object.keys(updates).length > 0 ? { ...c, ...updates } : c;
116
+ }));
117
+ return;
118
+ }
119
+ // Check persistent cache
120
+ const persisted = getPersistedDatabases(clusterUrl);
121
+ if (persisted && persisted.length > 0) {
122
+ setDbCache((prev) => ({ ...prev, [clusterUrl]: persisted }));
123
+ setDraft((prev) => prev.map((c) => {
124
+ if (c.clusterUrl !== clusterUrl) {
125
+ return c;
126
+ }
127
+ const updates: Partial<KustoConnection> = {};
128
+ if (!c.database) {
129
+ updates.database = persisted[0];
130
+ }
131
+ if (!c.name) {
132
+ updates.name = shortenClusterUrl(clusterUrl);
133
+ }
134
+ return Object.keys(updates).length > 0 ? { ...c, ...updates } : c;
135
+ }));
136
+ return;
137
+ }
138
+ // Fetch from network
139
+ setDbLoadFailed((prev) => { const next = new Set(prev); next.delete(clusterUrl); return next; });
140
+ setDbLoading((prev) => new Set([...prev, clusterUrl]));
141
+ void listDatabases(client, clusterUrl, true).then((dbs) => {
142
+ setDbCache((prev) => ({ ...prev, [clusterUrl]: dbs }));
143
+ setDbLoading((prev) => {
144
+ const next = new Set(prev);
145
+ next.delete(clusterUrl);
146
+ return next;
147
+ });
148
+ if (dbs.length > 0) {
149
+ setDbLoadFailed((prev) => { const next = new Set(prev); next.delete(clusterUrl); return next; });
150
+ setDraft((prev) => prev.map((c) => {
151
+ if (c.clusterUrl !== clusterUrl) {
152
+ return c;
153
+ }
154
+ const updates: Partial<KustoConnection> = {};
155
+ if (!c.database) {
156
+ updates.database = dbs[0];
157
+ }
158
+ if (!c.name) {
159
+ updates.name = shortenClusterUrl(clusterUrl);
160
+ }
161
+ return Object.keys(updates).length > 0 ? { ...c, ...updates } : c;
162
+ }));
163
+ } else {
164
+ console.error('[conn] listDatabases returned empty for:', clusterUrl);
165
+ setDbLoadFailed((prev) => new Set([...prev, clusterUrl]));
166
+ }
167
+ }).catch((err) => {
168
+ console.error('[conn] listDatabases error for:', clusterUrl, err);
169
+ setDbLoading((prev) => {
170
+ const next = new Set(prev);
171
+ next.delete(clusterUrl);
172
+ return next;
173
+ });
174
+ setDbLoadFailed((prev) => new Set([...prev, clusterUrl]));
175
+ });
176
+ }, [client, dbCache, dbLoading]);
177
+
178
+ const handleRefreshSchema = useCallback(async (clusterUrl: string, database: string) => {
179
+ if (!clusterUrl || !database) {
180
+ return;
181
+ }
182
+ const target = { clusterUrl, database };
183
+ await reloadSchema(client, target);
184
+ dispatch({ type: 'SET_SCHEMA', schema: getSchema(target) });
185
+ // Also refresh the database list
186
+ setDbLoading((prev) => new Set([...prev, clusterUrl]));
187
+ void listDatabases(client, clusterUrl, true).then((dbs) => {
188
+ setDbCache((prev) => ({ ...prev, [clusterUrl]: dbs }));
189
+ setDbLoading((prev) => {
190
+ const next = new Set(prev);
191
+ next.delete(clusterUrl);
192
+ return next;
193
+ });
194
+ });
195
+ }, [client, dispatch]);
196
+
197
+ const handleBackdropClick = useCallback(() => onClose(), [onClose]);
198
+ const handleBackdropKeyDown = useCallback((e: React.KeyboardEvent) => {
199
+ if (e.key === 'Escape') {
200
+ onClose();
201
+ }
202
+ }, [onClose]);
203
+
204
+ const updateField = useCallback((id: string, field: keyof KustoConnection, value: string) => {
205
+ setDraft((prev) => {
206
+ if (field === 'clusterUrl') {
207
+ return prev.map((c) => c.id === id ? { ...c, clusterUrl: value, database: '' } : c);
208
+ }
209
+ return prev.map((c) => c.id === id ? { ...c, [field]: value } : c);
210
+ });
211
+ // Clear validation status and cached dbs when user edits a field
212
+ if (field === 'clusterUrl') {
213
+ setDbCache((prev) => {
214
+ const conn = draft.find((c) => c.id === id);
215
+ if (conn && prev[conn.clusterUrl]) {
216
+ const next = { ...prev };
217
+ delete next[conn.clusterUrl];
218
+ return next;
219
+ }
220
+ return prev;
221
+ });
222
+ }
223
+ setValidationStatus((prev) => {
224
+ if (prev[id]) {
225
+ const next = { ...prev };
226
+ delete next[id];
227
+ return next;
228
+ }
229
+ return prev;
230
+ });
231
+ }, [draft]);
232
+
233
+ const removeConnection = useCallback((id: string) => {
234
+ setDraft((prev) => prev.filter((c) => c.id !== id));
235
+ setValidationStatus((prev) => {
236
+ if (prev[id]) {
237
+ const next = { ...prev };
238
+ delete next[id];
239
+ return next;
240
+ }
241
+ return prev;
242
+ });
243
+ }, []);
244
+
245
+ const handleDragStart = useCallback((idx: number) => { dragIdx.current = idx; }, []);
246
+ const handleDragOver = useCallback((idx: number) => { setDragOverIdx(idx); }, []);
247
+ const handleDragEnd = useCallback(() => {
248
+ if (dragIdx.current !== null && dragOverIdx !== null && dragIdx.current !== dragOverIdx) {
249
+ setDraft((prev) => {
250
+ const next = [...prev];
251
+ const [moved] = next.splice(dragIdx.current!, 1);
252
+ next.splice(dragOverIdx, 0, moved);
253
+ return next;
254
+ });
255
+ }
256
+ dragIdx.current = null;
257
+ setDragOverIdx(null);
258
+ }, [dragOverIdx]);
259
+
260
+ // --- Add split button ---
261
+ const handleAddEmpty = useCallback(() => {
262
+ const colorIdx = draft.length;
263
+ const newConn: KustoConnection = {
264
+ id: `conn-${Date.now()}-${colorIdx}`,
265
+ name: '',
266
+ clusterUrl: 'https://',
267
+ database: '',
268
+ color: CONNECTION_COLORS[colorIdx % CONNECTION_COLORS.length],
269
+ };
270
+ setDraft((prev) => [...prev, newConn]);
271
+ }, [draft.length]);
272
+
273
+ const hasDuplicateUrls = useMemo(() => {
274
+ const urls = draft.map((c) => c.clusterUrl.toLowerCase()).filter((u) => u !== 'https://');
275
+ return new Set(urls).size !== urls.length;
276
+ }, [draft]);
277
+
278
+ // --- Import from text ---
279
+ const [showImportText, setShowImportText] = useState(false);
280
+ const [importText, setImportText] = useState('');
281
+ const [importLoading, setImportLoading] = useState(false);
282
+ const [importResults, setImportResults] = useState<{ url: string; status: 'success' | 'error'; dbs: string[] }[]>([]);
283
+
284
+ const handleImportFromTextOpen = useCallback(() => {
285
+ setShowImportText(true);
286
+ setImportText('');
287
+ setImportResults([]);
288
+ }, []);
289
+
290
+ const handleImportTextClose = useCallback(() => {
291
+ setShowImportText(false);
292
+ setImportText('');
293
+ setImportResults([]);
294
+ }, []);
295
+
296
+ const handleImportTextChange = useCallback((_: unknown, data: { value: string }) => {
297
+ setImportText(data.value);
298
+ }, []);
299
+
300
+ const handleImportTextConfirm = useCallback(async () => {
301
+ const lines = importText
302
+ .split('\n')
303
+ .map((l) => l.trim())
304
+ .filter((l) => l && l.startsWith('https://'));
305
+
306
+ if (lines.length === 0) {
307
+ return;
308
+ }
309
+
310
+ const existingUrls = new Set(draft.map((c) => c.clusterUrl.toLowerCase()));
311
+ const uniqueLines = lines.filter((url) => !existingUrls.has(url.toLowerCase()));
312
+
313
+ if (uniqueLines.length === 0) {
314
+ return;
315
+ }
316
+
317
+ setImportLoading(true);
318
+ setImportResults([]);
319
+
320
+ const results = await Promise.all(
321
+ uniqueLines.map(async (url) => {
322
+ const dbs = await listDatabases(client, url);
323
+ return { url, status: (dbs.length > 0 ? 'success' : 'error') as 'success' | 'error', dbs };
324
+ }),
325
+ );
326
+
327
+ setImportResults(results);
328
+ setImportLoading(false);
329
+
330
+ const valid = results.filter((r) => r.status === 'success');
331
+ if (valid.length > 0) {
332
+ let colorIdx = draft.length;
333
+ const newConns: KustoConnection[] = valid.map((r) => {
334
+ const conn: KustoConnection = {
335
+ id: `conn-${Date.now()}-${colorIdx}`,
336
+ name: shortenClusterUrl(r.url),
337
+ clusterUrl: r.url,
338
+ database: r.dbs[0] ?? '',
339
+ color: CONNECTION_COLORS[colorIdx % CONNECTION_COLORS.length],
340
+ };
341
+ colorIdx++;
342
+ setDbCache((prev) => ({ ...prev, [r.url]: r.dbs }));
343
+ return conn;
344
+ });
345
+ setDraft((prev) => [...prev, ...newConns]);
346
+ }
347
+
348
+ if (results.every((r) => r.status === 'success')) {
349
+ setShowImportText(false);
350
+ setImportText('');
351
+ setImportResults([]);
352
+ }
353
+ }, [importText, draft, client]);
354
+
355
+ // --- Import from file ---
356
+ const handleImportFromFile = useCallback(() => {
357
+ fileInputRef.current?.click();
358
+ }, []);
359
+
360
+ const handleFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
361
+ const file = e.target.files?.[0];
362
+ if (!file) {
363
+ return;
364
+ }
365
+ const reader = new FileReader();
366
+ reader.onload = () => {
367
+ try {
368
+ const parsed = JSON.parse(reader.result as string) as Array<{ name?: string; clusterUrl?: string; database?: string }>;
369
+ if (!Array.isArray(parsed)) {
370
+ return;
371
+ }
372
+ const existingUrls = new Set(draft.map((c) => c.clusterUrl.toLowerCase()));
373
+ let colorIdx = draft.length;
374
+ const newConns: KustoConnection[] = [];
375
+ for (const item of parsed) {
376
+ if (!item.clusterUrl || existingUrls.has(item.clusterUrl.toLowerCase())) {
377
+ continue;
378
+ }
379
+ existingUrls.add(item.clusterUrl.toLowerCase());
380
+ newConns.push({
381
+ id: `conn-${Date.now()}-${colorIdx}`,
382
+ name: item.name || shortenClusterUrl(item.clusterUrl),
383
+ clusterUrl: item.clusterUrl,
384
+ database: item.database || '',
385
+ color: CONNECTION_COLORS[colorIdx % CONNECTION_COLORS.length],
386
+ });
387
+ colorIdx++;
388
+ }
389
+ if (newConns.length > 0) {
390
+ setDraft((prev) => [...prev, ...newConns]);
391
+ }
392
+ } catch {
393
+ // Invalid JSON — ignore
394
+ }
395
+ };
396
+ reader.readAsText(file);
397
+ // Reset so the same file can be re-selected
398
+ e.target.value = '';
399
+ }, [draft]);
400
+
401
+ // --- Export split button ---
402
+ const [exportLabel, setExportLabel] = useState('Export');
403
+
404
+ const buildExportJson = useCallback(() => {
405
+ return JSON.stringify(draft.map((c) => ({
406
+ name: c.name,
407
+ clusterUrl: c.clusterUrl,
408
+ database: c.database,
409
+ })), null, 2);
410
+ }, [draft]);
411
+
412
+ const handleExportClipboard = useCallback(() => {
413
+ const json = buildExportJson();
414
+ void navigator.clipboard.writeText(json).then(() => {
415
+ setExportLabel('Copied!');
416
+ setTimeout(() => setExportLabel('Export'), 2000);
417
+ }).catch(() => {
418
+ // Clipboard failed — fallback to download
419
+ const blob = new Blob([json], { type: 'application/json' });
420
+ const url = URL.createObjectURL(blob);
421
+ const a = document.createElement('a');
422
+ a.href = url;
423
+ a.download = 'traverse-connections.json';
424
+ a.click();
425
+ URL.revokeObjectURL(url);
426
+ });
427
+ }, [buildExportJson]);
428
+
429
+ const handleExportToFile = useCallback(() => {
430
+ const json = buildExportJson();
431
+ const blob = new Blob([json], { type: 'application/json' });
432
+ const url = URL.createObjectURL(blob);
433
+ const a = document.createElement('a');
434
+ a.href = url;
435
+ a.download = 'traverse-connections.json';
436
+ a.click();
437
+ URL.revokeObjectURL(url);
438
+ setExportLabel('Downloaded!');
439
+ setTimeout(() => setExportLabel('Export'), 2000);
440
+ }, [buildExportJson]);
441
+
442
+ // --- Save with validation ---
443
+ const handleSave = useCallback(async () => {
444
+ const toValidate = draft.filter((c) => isNewConnection(c) || isModifiedConnection(c));
445
+
446
+ if (toValidate.length === 0) {
447
+ saveConnections(draft);
448
+ dispatch({ type: 'SET_CONNECTIONS', connections: draft });
449
+ onClose();
450
+ return;
451
+ }
452
+
453
+ setSaving(true);
454
+ setSaveSummary('');
455
+
456
+ // Mark all targets as validating
457
+ const validatingStatus: Record<string, ValidationStatus> = {};
458
+ for (const c of toValidate) {
459
+ validatingStatus[c.id] = 'validating';
460
+ }
461
+ setValidationStatus((prev) => ({ ...prev, ...validatingStatus }));
462
+
463
+ const results = await Promise.all(
464
+ toValidate.map(async (conn) => {
465
+ if (!conn.clusterUrl.startsWith('https://')) {
466
+ return { id: conn.id, ok: false, dbs: [] as string[] };
467
+ }
468
+ try {
469
+ const dbs = await listDatabases(client, conn.clusterUrl);
470
+ return { id: conn.id, ok: dbs.length > 0, dbs };
471
+ } catch {
472
+ return { id: conn.id, ok: false, dbs: [] as string[] };
473
+ }
474
+ }),
475
+ );
476
+
477
+ const newStatus: Record<string, ValidationStatus> = {};
478
+ const failedIds = new Set<string>();
479
+ let updatedDraft = [...draft];
480
+
481
+ for (const r of results) {
482
+ if (r.ok) {
483
+ newStatus[r.id] = 'valid';
484
+ persistDatabases(
485
+ updatedDraft.find((c) => c.id === r.id)!.clusterUrl,
486
+ r.dbs,
487
+ );
488
+ setDbCache((prev) => ({
489
+ ...prev,
490
+ [updatedDraft.find((c) => c.id === r.id)!.clusterUrl]: r.dbs,
491
+ }));
492
+ // Auto-select first database if none set
493
+ const conn = updatedDraft.find((c) => c.id === r.id)!;
494
+ if (!conn.database && r.dbs.length > 0) {
495
+ updatedDraft = updatedDraft.map((c) =>
496
+ c.id === r.id ? { ...c, database: r.dbs[0] } : c,
497
+ );
498
+ }
499
+ } else {
500
+ newStatus[r.id] = 'invalid';
501
+ failedIds.add(r.id);
502
+ }
503
+ }
504
+
505
+ setValidationStatus((prev) => ({ ...prev, ...newStatus }));
506
+ setDraft(updatedDraft);
507
+
508
+ if (failedIds.size > 0) {
509
+ const validConns = updatedDraft.filter((c) => !failedIds.has(c.id));
510
+ const failedCount = failedIds.size;
511
+ setSaveSummary(`${failedCount} connection${failedCount !== 1 ? 's' : ''} failed validation and were not saved.`);
512
+
513
+ // Save only the valid connections
514
+ if (validConns.length > 0) {
515
+ saveConnections(validConns);
516
+ dispatch({ type: 'SET_CONNECTIONS', connections: validConns });
517
+ }
518
+ } else {
519
+ saveConnections(updatedDraft);
520
+ dispatch({ type: 'SET_CONNECTIONS', connections: updatedDraft });
521
+ onClose();
522
+ }
523
+
524
+ setSaving(false);
525
+ }, [draft, isNewConnection, isModifiedConnection, client, dispatch, onClose]);
526
+
527
+ const hasChanges = useMemo(() => {
528
+ if (draft.length !== connections.length) {
529
+ return true;
530
+ }
531
+ return draft.some((c, i) => {
532
+ const orig = connections[i];
533
+ return !orig || c.id !== orig.id || c.name !== orig.name || c.clusterUrl !== orig.clusterUrl || c.database !== orig.database || c.color !== orig.color;
534
+ });
535
+ }, [draft, connections]);
536
+
537
+ return (
538
+ <div style={backdropStyle} role="dialog" onClick={handleBackdropClick} onKeyDown={handleBackdropKeyDown}>
539
+ <div style={modalStyle} role="dialog" onClick={stopPropagation} onKeyDown={stopPropagationKeyDown}>
540
+ <div style={headerStyle}>
541
+ <span style={titleStyle}>Manage Connections</span>
542
+ <Button appearance="subtle" icon={dismissIcon} size="small" onClick={onClose} />
543
+ </div>
544
+
545
+ <div style={listStyle}>
546
+ {draft.map((conn, i) => (
547
+ <ConnectionRow key={conn.id} conn={conn} idx={i}
548
+ isNew={isNewConnection(conn)}
549
+ canDelete={draft.length > 1}
550
+ databases={dbCache[conn.clusterUrl] ?? emptyDbs}
551
+ dbLoading={dbLoading.has(conn.clusterUrl)}
552
+ dbLoadFailed={dbLoadFailed.has(conn.clusterUrl)}
553
+ isDragOver={dragOverIdx === i}
554
+ validationStatus={validationStatus[conn.id] ?? 'none'}
555
+ onUpdate={updateField} onRemove={removeConnection}
556
+ onLoadDatabases={loadDatabases}
557
+ onRefreshSchema={handleRefreshSchema}
558
+ onDragStart={handleDragStart} onDragOver={handleDragOver} onDragEnd={handleDragEnd} />
559
+ ))}
560
+ </div>
561
+
562
+ {showImportText && (
563
+ <div style={importAreaStyle}>
564
+ <div style={importHintStyle}>Paste cluster URLs, one per line (e.g., https://mycluster.kusto.windows.net)</div>
565
+ <Textarea
566
+ value={importText}
567
+ onChange={handleImportTextChange}
568
+ placeholder="https://cluster1.kusto.windows.net&#10;https://cluster2.kusto.windows.net"
569
+ resize="vertical"
570
+ disabled={importLoading}
571
+ style={importTextareaStyle}
572
+ />
573
+ {importResults.length > 0 && (
574
+ <div style={importResultsContainerStyle}>
575
+ {importResults.map((r) => (
576
+ <div key={r.url} style={r.status === 'success' ? importResultSuccessStyle : importResultErrorStyle}>
577
+ {r.status === 'success' ? '✓' : '✗'} {shortenClusterUrl(r.url)}
578
+ {r.status === 'success' ? ` (${r.dbs.length} databases)` : ' — unreachable or unauthorized'}
579
+ </div>
580
+ ))}
581
+ </div>
582
+ )}
583
+ <div style={importActionsStyle}>
584
+ {importLoading && <Spinner size="tiny" />}
585
+ <Button appearance="subtle" size="small" onClick={handleImportTextClose} disabled={importLoading}>Cancel</Button>
586
+ <Button appearance="primary" size="small" onClick={handleImportTextConfirm} disabled={importLoading}>
587
+ {importLoading ? 'Validating...' : 'Add Clusters'}
588
+ </Button>
589
+ </div>
590
+ </div>
591
+ )}
592
+
593
+ {saveSummary && (
594
+ <div style={saveSummaryStyle}>{saveSummary}</div>
595
+ )}
596
+ {hasDuplicateUrls && (
597
+ <div style={saveSummaryStyle}>Duplicate cluster URLs are not allowed. Remove duplicates to save.</div>
598
+ )}
599
+
600
+ <input
601
+ ref={fileInputRef}
602
+ type="file"
603
+ accept=".json"
604
+ style={hiddenInputStyle}
605
+ onChange={handleFileChange}
606
+ />
607
+
608
+ <div style={footerStyle}>
609
+ <div style={footerLeftStyle}>
610
+ <Menu>
611
+ <MenuSplitGroup>
612
+ <Button appearance="subtle" size="small" icon={addIcon} onClick={handleAddEmpty}>
613
+ Add
614
+ </Button>
615
+ <MenuTrigger disableButtonEnhancement>
616
+ <Button appearance="subtle" size="small" icon={chevronDownIcon} style={menuTriggerButtonStyle} />
617
+ </MenuTrigger>
618
+ </MenuSplitGroup>
619
+ <MenuPopover>
620
+ <MenuList>
621
+ <MenuItem onClick={handleImportFromTextOpen}>Import from text</MenuItem>
622
+ <MenuItem onClick={handleImportFromFile}>Import from file</MenuItem>
623
+ </MenuList>
624
+ </MenuPopover>
625
+ </Menu>
626
+ <Menu>
627
+ <MenuSplitGroup>
628
+ <Button appearance="subtle" size="small" icon={exportIcon} onClick={handleExportClipboard}>
629
+ {exportLabel}
630
+ </Button>
631
+ <MenuTrigger disableButtonEnhancement>
632
+ <Button appearance="subtle" size="small" icon={chevronDownIcon} style={menuTriggerButtonStyle} />
633
+ </MenuTrigger>
634
+ </MenuSplitGroup>
635
+ <MenuPopover>
636
+ <MenuList>
637
+ <MenuItem onClick={handleExportToFile}>Export to file</MenuItem>
638
+ </MenuList>
639
+ </MenuPopover>
640
+ </Menu>
641
+ </div>
642
+ <div style={footerRightStyle}>
643
+ <Button appearance="subtle" size="small" onClick={onClose} disabled={saving}>Cancel</Button>
644
+ <Button appearance="primary" size="small" onClick={handleSave} disabled={saving || !hasChanges || hasDuplicateUrls}>
645
+ {saving ? <><Spinner size="tiny" />&nbsp;Saving…</> : 'Save'}
646
+ </Button>
647
+ </div>
648
+ </div>
649
+ </div>
650
+ </div>
651
+ );
652
+ }