@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,648 @@
1
+ import { Editor } from '@monaco-editor/react';
2
+ import type { Monaco } from '@monaco-editor/react';
3
+ import type { editor } from 'monaco-editor';
4
+ import React, { useState, useCallback, useRef, useEffect, useMemo } from 'react';
5
+
6
+ import { useExplorerColors } from '../../context/ExplorerColorContext';
7
+ import type { KustoTarget } from '../../services/kusto';
8
+ import { normalizeQuery, getHistory, saveHistoryEntry, recallResult } from '../../services/queryHistory';
9
+ import type { QueryHistoryEntry } from '../../services/queryHistory';
10
+ import { getSchema, loadSchema } from '../../services/schema';
11
+ import { EditorToolbar } from '../EditorToolbar/EditorToolbar';
12
+ import { ResultsPanel } from '../ResultsPanel/ResultsPanel';
13
+ import { SchemaSidebar } from '../SchemaSidebar/SchemaSidebar';
14
+ import { TabBar } from '../TabBar/TabBar';
15
+ import { useExplorerState, useExplorerDispatch, useActiveTabs, useFocusedConnection } from '../../context/ExplorerStateContext';
16
+ import {
17
+ formatKql,
18
+ getQueryToRunFromEditor,
19
+ parseResultColumns,
20
+ buildSuccessEntry,
21
+ buildErrorEntry,
22
+ saveActiveConnectionId,
23
+ getEditorDropTarget,
24
+ getShortcutAction,
25
+ } from '../ExplorerWorkspace/ExplorerWorkspace.logic';
26
+ import { useExplorerStyles } from './ExplorerWorkspace.styles';
27
+ import type { ExplorerProps } from '../Explorer/Explorer';
28
+ import { useKustoClient } from '../../context/KustoClientContext';
29
+ import { registerKqlLanguage, setKqlSchemaResolver } from './kqlLanguage';
30
+
31
+
32
+ const positionRelativeStyle = { position: 'relative' as const } as const;
33
+ const editorOptions = {
34
+ minimap: { enabled: false }, fontSize: 13, fontFamily: 'Consolas, Monaco, monospace',
35
+ lineNumbers: 'on' as const, scrollBeyondLastLine: false, wordWrap: 'on' as const, automaticLayout: true,
36
+ suggestOnTriggerCharacters: true, quickSuggestions: true, tabSize: 4,
37
+ renderLineHighlight: 'line' as const, overviewRulerLanes: 0, hideCursorInOverviewRuler: true,
38
+ overviewRulerBorder: false, padding: { top: 4, bottom: 4 }, lineDecorationsWidth: 8,
39
+ glyphMargin: false, folding: false,
40
+ dropIntoEditor: { enabled: false },
41
+ } as const;
42
+
43
+ export function ExplorerWorkspace(props: ExplorerProps) {
44
+ const styles = useExplorerStyles();
45
+ const { isDark = false } = props;
46
+ const explorerColors = useExplorerColors();
47
+ const client = useKustoClient();
48
+ const state = useExplorerState();
49
+ const dispatch = useExplorerDispatch();
50
+ const { activeTab, splitTab } = useActiveTabs();
51
+ const focusedConnection = useFocusedConnection();
52
+
53
+ const {
54
+ schema, connections,
55
+ activeTabId, splitEnabled, splitDirection, splitTabId, focusedPane,
56
+ loading, runningQueryKey,
57
+ rows, columns, columnTypes, resultSets, activeResultSet,
58
+ history, editorHeight,
59
+ } = state;
60
+
61
+ // --- Cmd/Ctrl+T / Cmd/Ctrl+W tab shortcuts (desktop only) ---
62
+ const activeTabKql = state.tabs.find((t) => t.id === state.activeTabId)?.kql ?? '';
63
+ const tabCount = state.tabs.length;
64
+ useEffect(() => {
65
+ if (!props.enableTabShortcuts) {
66
+ return;
67
+ }
68
+ function handleKeyDown(e: KeyboardEvent) {
69
+ const action = getShortcutAction(e, tabCount, activeTabKql);
70
+ if (!action) {
71
+ return;
72
+ }
73
+ e.preventDefault();
74
+ if (action === 'add-tab') {
75
+ dispatch({ type: 'ADD_TAB' });
76
+ } else if (action === 'close-tab') {
77
+ dispatch({ type: 'CLOSE_TAB', tabId: state.activeTabId });
78
+ } else if (action === 'close-tab-confirm') {
79
+ if (window.confirm('This tab has unsaved content that will be lost. Close it?')) {
80
+ dispatch({ type: 'CLOSE_TAB', tabId: state.activeTabId });
81
+ }
82
+ }
83
+ }
84
+ window.addEventListener('keydown', handleKeyDown);
85
+ return () => window.removeEventListener('keydown', handleKeyDown);
86
+ }, [props.enableTabShortcuts, dispatch, tabCount, state.activeTabId, activeTabKql]);
87
+
88
+ // --- Live schema (per-connection) ---
89
+ const focusedTabConnectionId = focusedPane === 'primary'
90
+ ? (activeTab?.connectionId ?? '')
91
+ : (splitTab?.connectionId ?? activeTab?.connectionId ?? '');
92
+ const focusedConn = connections.find((c) => c.id === focusedTabConnectionId) ?? connections[0] ?? focusedConnection;
93
+ const targetCluster = focusedConn.clusterUrl;
94
+ const targetDatabase = focusedConn.database;
95
+ const [schemaLoading, setSchemaLoading] = useState(false);
96
+ const [schemaWidth, setSchemaWidth] = useState(220);
97
+
98
+ useEffect(() => {
99
+ if (!targetCluster) {
100
+ dispatch({ type: 'SET_SCHEMA', schema: [] });
101
+ return;
102
+ }
103
+ const target: KustoTarget = { clusterUrl: targetCluster, database: targetDatabase };
104
+ setSchemaLoading(true);
105
+ void loadSchema(client, target).then(() => {
106
+ // getSchema with the original target — loadSchema caches under both discovered and original keys
107
+ dispatch({ type: 'SET_SCHEMA', schema: getSchema(target) });
108
+ }).finally(() => setSchemaLoading(false));
109
+ }, [client, dispatch, targetCluster, targetDatabase]);
110
+
111
+ // Target for query execution
112
+ const focusedTarget: KustoTarget = useMemo(
113
+ () => ({ clusterUrl: targetCluster, database: targetDatabase }),
114
+ [targetCluster, targetDatabase],
115
+ );
116
+
117
+ useEffect(() => {
118
+ setKqlSchemaResolver(() => getSchema(focusedTarget));
119
+ saveActiveConnectionId(focusedConn.id);
120
+ }, [focusedConn.id, focusedTarget]);
121
+
122
+ // Setter shims — dispatch to reducer, keep same call signatures for existing callbacks
123
+ const setHasSelection = useCallback((v: boolean) => dispatch({ type: 'SET_HAS_SELECTION', hasSelection: v }), [dispatch]);
124
+ const setCanRecall = useCallback((v: boolean) => dispatch({ type: 'SET_CAN_RECALL', canRecall: v }), [dispatch]);
125
+ const setHistory = useCallback((v: QueryHistoryEntry[]) => dispatch({ type: 'SET_HISTORY', history: v }), [dispatch]);
126
+ const setEditorHeight = useCallback((v: number) => dispatch({ type: 'SET_EDITOR_HEIGHT', height: v }), [dispatch]);
127
+ const setFocusedPane = useCallback((v: 'primary' | 'secondary') => dispatch({ type: 'SET_FOCUSED_PANE', pane: v }), [dispatch]);
128
+
129
+ // Tab management — dispatch to reducer
130
+ const updateTabKql = useCallback((tabId: string, kql: string) => dispatch({ type: 'UPDATE_TAB_KQL', tabId, kql }), [dispatch]);
131
+ const closeSplit = useCallback(() => dispatch({ type: 'CLOSE_SPLIT' }), [dispatch]);
132
+
133
+ // --- Editor refs (primary + secondary for split) ---
134
+ const primaryEditorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
135
+ const secondaryEditorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
136
+ const primaryDecorationsRef = useRef<editor.IEditorDecorationsCollection | null>(null);
137
+ const secondaryDecorationsRef = useRef<editor.IEditorDecorationsCollection | null>(null);
138
+ const runQueryRef = useRef<() => void>(() => {});
139
+ const recallQueryRef = useRef<() => void>(() => {});
140
+ const containerRef = useRef<HTMLDivElement | null>(null);
141
+ const isDragging = useRef(false);
142
+ const historyKeysRef = useRef<Set<string>>(new Set());
143
+ const abortRef = useRef<AbortController | null>(null);
144
+
145
+ // Convenience: the focused editor
146
+ const getFocusedEditor = useCallback(() => {
147
+ return focusedPane === 'primary' ? primaryEditorRef.current : secondaryEditorRef.current;
148
+ }, [focusedPane]);
149
+
150
+
151
+ // Load history from IndexedDB on mount
152
+ useEffect(() => { void getHistory().then(setHistory); }, [setHistory]);
153
+
154
+ // Keep a ref of history keys for synchronous lookup in cursor change handlers
155
+ useEffect(() => {
156
+ historyKeysRef.current = new Set(history.filter((h) => h.status === 'success' && h.rows).map((h) => h.key));
157
+ // Recheck recall availability when history changes
158
+ const ed = getFocusedEditor();
159
+ if (ed) {
160
+ const toRun = getQueryToRunFromEditor(ed);
161
+ setCanRecall(toRun ? historyKeysRef.current.has(normalizeQuery(toRun.query)) : false);
162
+ }
163
+ }, [history, getFocusedEditor, setCanRecall]);
164
+
165
+ const checkCanRecall = useCallback((ed: editor.IStandaloneCodeEditor) => {
166
+ const toRun = getQueryToRunFromEditor(ed);
167
+ if (!toRun) { setCanRecall(false); return; }
168
+ setCanRecall(historyKeysRef.current.has(normalizeQuery(toRun.query)));
169
+ }, [setCanRecall]);
170
+
171
+ const updateStatementHighlight = useCallback((ed: editor.IStandaloneCodeEditor) => {
172
+ const decRef = ed === primaryEditorRef.current ? primaryDecorationsRef : secondaryDecorationsRef;
173
+ if (!decRef.current) {
174
+ return;
175
+ }
176
+ const selection = ed.getSelection();
177
+ // When the user has an explicit selection, don't show the block highlight
178
+ if (selection && !selection.isEmpty()) {
179
+ decRef.current.set([]);
180
+ checkCanRecall(ed);
181
+ return;
182
+ }
183
+ const model = ed.getModel();
184
+ if (!model) {
185
+ return;
186
+ }
187
+ const cursorLine = ed.getPosition()?.lineNumber ?? 1;
188
+ const totalLines = model.getLineCount();
189
+
190
+ let startLine = cursorLine;
191
+ while (startLine > 1 && model.getLineContent(startLine - 1).trim() !== '') {
192
+ startLine--;
193
+ }
194
+ let endLine = cursorLine;
195
+ while (endLine < totalLines && model.getLineContent(endLine + 1).trim() !== '') {
196
+ endLine++;
197
+ }
198
+
199
+ decRef.current.set([{
200
+ range: {
201
+ startLineNumber: startLine,
202
+ startColumn: 1,
203
+ endLineNumber: endLine,
204
+ endColumn: model.getLineMaxColumn(endLine),
205
+ },
206
+ options: {
207
+ isWholeLine: true,
208
+ className: 'traverse-run-highlight',
209
+ },
210
+ }]);
211
+ checkCanRecall(ed);
212
+ }, [checkCanRecall]);
213
+
214
+ const cancelQuery = useCallback(() => {
215
+ abortRef.current?.abort();
216
+ }, []);
217
+
218
+ const runQuery = useCallback(async () => {
219
+ const ed = getFocusedEditor();
220
+ if (!ed) {
221
+ return;
222
+ }
223
+ const toRun = getQueryToRunFromEditor(ed);
224
+ if (!toRun) {
225
+ return;
226
+ }
227
+
228
+ abortRef.current?.abort();
229
+ const abort = new AbortController();
230
+ abortRef.current = abort;
231
+ const queryKey = normalizeQuery(toRun.query);
232
+
233
+ dispatch({ type: 'QUERY_START', queryKey });
234
+ const start = performance.now();
235
+ try {
236
+ const result = await client.queryKusto(toRun.query, abort.signal, undefined, focusedTarget, { bypassCache: true });
237
+ const elapsedMs = Math.round(performance.now() - start);
238
+ const { columns: cols, columnTypes: types } = parseResultColumns(result.columns);
239
+ const resultRows = result.rows;
240
+
241
+ dispatch({
242
+ type: 'QUERY_SUCCESS',
243
+ rows: resultRows,
244
+ columns: cols,
245
+ columnTypes: types,
246
+ elapsed: elapsedMs,
247
+ stats: result.stats ?? null,
248
+ resultSets: result.resultSets,
249
+ });
250
+
251
+ try { window.history.replaceState(null, '', `?query=${encodeURIComponent(toRun.query)}`); } catch { /* ignore */ }
252
+
253
+ const entry = buildSuccessEntry(toRun.query, normalizeQuery(toRun.query), elapsedMs, cols, resultRows);
254
+ void saveHistoryEntry(entry).then(() => getHistory().then((h) => dispatch({ type: 'SET_HISTORY', history: h })));
255
+ } catch (err) {
256
+ if (abort.signal.aborted) {
257
+ dispatch({ type: 'QUERY_CANCEL' });
258
+ } else {
259
+ const errorMsg = err instanceof Error ? err.message : String(err);
260
+ dispatch({ type: 'QUERY_ERROR', error: errorMsg });
261
+
262
+ const entry = buildErrorEntry(toRun.query, normalizeQuery(toRun.query), errorMsg);
263
+ void saveHistoryEntry(entry).then(() => getHistory().then((h) => dispatch({ type: 'SET_HISTORY', history: h })));
264
+ }
265
+ } finally {
266
+ abortRef.current = null;
267
+ }
268
+ }, [getFocusedEditor, dispatch, focusedTarget, client]);
269
+
270
+ const doRecall = useCallback(async () => {
271
+ const ed = getFocusedEditor();
272
+ if (!ed) {
273
+ return;
274
+ }
275
+ const toRun = getQueryToRunFromEditor(ed);
276
+ if (!toRun) {
277
+ return;
278
+ }
279
+
280
+ const entry = await recallResult(toRun.query);
281
+ if (entry?.columns && entry?.rows) {
282
+ dispatch({
283
+ type: 'QUERY_SUCCESS',
284
+ rows: entry.rows,
285
+ columns: entry.columns,
286
+ columnTypes: {},
287
+ elapsed: entry.elapsed ?? 0,
288
+ stats: null,
289
+ resultSets: [],
290
+ });
291
+ }
292
+ }, [getFocusedEditor, dispatch]);
293
+
294
+ runQueryRef.current = runQuery;
295
+ recallQueryRef.current = doRecall;
296
+
297
+ const formatQuery = useCallback(() => {
298
+ const ed = getFocusedEditor();
299
+ if (!ed) {
300
+ return;
301
+ }
302
+ const model = ed.getModel();
303
+ if (!model) {
304
+ return;
305
+ }
306
+ const formatted = formatKql(model.getValue());
307
+ model.setValue(formatted);
308
+ // Update the tab's KQL
309
+ const tabId = focusedPane === 'primary' ? activeTabId : splitTabId;
310
+ if (tabId) {
311
+ updateTabKql(tabId, formatted);
312
+ }
313
+ }, [getFocusedEditor, focusedPane, activeTabId, splitTabId, updateTabKql]);
314
+ const formatQueryRef = useRef<() => void>(() => {});
315
+ formatQueryRef.current = formatQuery;
316
+
317
+ const createEditorMountHandler = useCallback((pane: 'primary' | 'secondary') => {
318
+ return (ed: editor.IStandaloneCodeEditor, monaco: Monaco) => {
319
+ const edRef = pane === 'primary' ? primaryEditorRef : secondaryEditorRef;
320
+ const decRef = pane === 'primary' ? primaryDecorationsRef : secondaryDecorationsRef;
321
+ edRef.current = ed;
322
+ decRef.current = ed.createDecorationsCollection([]);
323
+ registerKqlLanguage(monaco);
324
+ ed.addAction({
325
+ id: 'run-query',
326
+ label: 'Run Query',
327
+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.Enter],
328
+ run: () => { runQueryRef.current(); },
329
+ });
330
+ ed.addAction({
331
+ id: 'recall-query',
332
+ label: 'Recall Query',
333
+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KeyR],
334
+ run: () => { recallQueryRef.current(); },
335
+ });
336
+ ed.addAction({
337
+ id: 'format-query',
338
+ label: 'Format Query',
339
+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KeyF],
340
+ run: () => { formatQueryRef.current(); },
341
+ });
342
+
343
+ ed.onDidChangeCursorPosition(() => updateStatementHighlight(ed));
344
+ ed.onDidChangeCursorSelection((e) => {
345
+ setHasSelection(!e.selection.isEmpty());
346
+ updateStatementHighlight(ed);
347
+ });
348
+ ed.onDidChangeModelContent(() => updateStatementHighlight(ed));
349
+ ed.onDidFocusEditorWidget(() => setFocusedPane(pane));
350
+
351
+ updateStatementHighlight(ed);
352
+ if (pane === 'primary') {
353
+ ed.focus();
354
+ }
355
+ };
356
+ }, [updateStatementHighlight, setHasSelection, setFocusedPane]);
357
+
358
+ useEffect(() => { runQueryRef.current = runQuery; }, [runQuery]);
359
+ useEffect(() => { recallQueryRef.current = doRecall; }, [doRecall]);
360
+
361
+ // Inject global CSS for the run-highlight decoration (Monaco needs a real class)
362
+ useEffect(() => {
363
+ const id = 'traverse-run-highlight-style';
364
+ if (!document.getElementById(id)) {
365
+ const style = document.createElement('style');
366
+ style.id = id;
367
+ style.textContent = `.traverse-run-highlight { background-color: ${explorerColors.semantic.selectionBg}; transition: background-color 0.3s ease; }`;
368
+ document.head.appendChild(style);
369
+ }
370
+ }, [explorerColors.semantic.selectionBg]);
371
+
372
+ const insertText = useCallback((text: string) => {
373
+ const ed = getFocusedEditor();
374
+ if (!ed) {
375
+ return;
376
+ }
377
+ const position = ed.getPosition();
378
+ if (position) {
379
+ ed.executeEdits('insert-schema', [{
380
+ range: { startLineNumber: position.lineNumber, startColumn: position.column, endLineNumber: position.lineNumber, endColumn: position.column },
381
+ text,
382
+ }]);
383
+ ed.focus();
384
+ }
385
+ }, [getFocusedEditor]);
386
+
387
+ const schemaContextRunQuery = useCallback((kql: string) => {
388
+ // Set the query in the active tab and run it
389
+ updateTabKql(activeTabId, kql);
390
+ const ed = primaryEditorRef.current;
391
+ if (ed) {
392
+ ed.setValue(kql);
393
+ ed.focus();
394
+ }
395
+ // Trigger run after state update
396
+ setTimeout(() => runQueryRef.current(), 50);
397
+ }, [activeTabId, updateTabKql]);
398
+
399
+ // Drag resize handler
400
+ const onDragStart = useCallback((e: React.MouseEvent) => {
401
+ e.preventDefault();
402
+ isDragging.current = true;
403
+ const startY = e.clientY;
404
+ const startHeight = editorHeight;
405
+ const container = containerRef.current;
406
+ if (!container) {
407
+ return;
408
+ }
409
+ const containerHeight = container.getBoundingClientRect().height - 36; // minus toolbar
410
+
411
+ const onMove = (ev: MouseEvent) => {
412
+ if (!isDragging.current) {
413
+ return;
414
+ }
415
+ const delta = ev.clientY - startY;
416
+ const newPct = Math.min(80, Math.max(20, startHeight + (delta / containerHeight) * 100));
417
+ setEditorHeight(newPct);
418
+ };
419
+ const onUp = () => {
420
+ isDragging.current = false;
421
+ document.removeEventListener('mousemove', onMove);
422
+ document.removeEventListener('mouseup', onUp);
423
+ };
424
+ document.addEventListener('mousemove', onMove);
425
+ document.addEventListener('mouseup', onUp);
426
+ }, [editorHeight, setEditorHeight]);
427
+
428
+ // Schema sidebar resize handler
429
+ const onSchemaResizeStart = useCallback((e: React.MouseEvent) => {
430
+ e.preventDefault();
431
+ const startX = e.clientX;
432
+ const startWidth = schemaWidth;
433
+ const onMove = (ev: MouseEvent) => {
434
+ const newWidth = Math.min(500, Math.max(140, startWidth + ev.clientX - startX));
435
+ setSchemaWidth(newWidth);
436
+ };
437
+ const onUp = () => {
438
+ document.removeEventListener('mousemove', onMove);
439
+ document.removeEventListener('mouseup', onUp);
440
+ };
441
+ document.addEventListener('mousemove', onMove);
442
+ document.addEventListener('mouseup', onUp);
443
+ }, [schemaWidth]);
444
+
445
+ const schemaWidthStyle = useMemo(() => ({ width: `${schemaWidth}px` }), [schemaWidth]);
446
+
447
+ // Derive active result set columns/rows for display
448
+ const displayColumns = useMemo(() => resultSets.length > 1 && resultSets[activeResultSet]
449
+ ? resultSets[activeResultSet].columns.map((c: { ColumnName: string; ColumnType: string }) => c.ColumnName) : columns,
450
+ [resultSets, activeResultSet, columns]);
451
+ const displayColumnTypes = useMemo(() => resultSets.length > 1 && resultSets[activeResultSet]
452
+ ? Object.fromEntries(resultSets[activeResultSet].columns.map((c: { ColumnName: string; ColumnType: string }) => [c.ColumnName, c.ColumnType])) : columnTypes,
453
+ [resultSets, activeResultSet, columnTypes]);
454
+ const displayRows = useMemo(() => resultSets.length > 1 && resultSets[activeResultSet]
455
+ ? resultSets[activeResultSet].rows : rows,
456
+ [resultSets, activeResultSet, rows]);
457
+
458
+ const currentQueryKey = (() => {
459
+ const ed = getFocusedEditor();
460
+ if (!ed) {
461
+ return null;
462
+ }
463
+ const toRun = getQueryToRunFromEditor(ed);
464
+ return toRun ? normalizeQuery(toRun.query) : null;
465
+ })();
466
+ const showCancel = loading && runningQueryKey !== null && currentQueryKey === runningQueryKey;
467
+
468
+ const [editorDropTarget, setEditorDropTarget] = useState<'left' | 'right' | 'top' | 'bottom' | null>(null);
469
+ const dragTabIdRef = useRef<string | null>(null);
470
+
471
+
472
+ const handleHistoryRecall = useCallback(async (entry: QueryHistoryEntry) => {
473
+ if (entry.columns && entry.rows) {
474
+ dispatch({
475
+ type: 'QUERY_SUCCESS',
476
+ rows: entry.rows,
477
+ columns: entry.columns,
478
+ columnTypes: {},
479
+ elapsed: entry.elapsed ?? 0,
480
+ stats: null,
481
+ resultSets: [],
482
+ });
483
+ dispatch({ type: 'SET_RESULTS_TAB', tab: 'results' });
484
+ const ed = primaryEditorRef.current;
485
+ if (ed) {
486
+ ed.setValue(entry.query);
487
+ dispatch({ type: 'UPDATE_TAB_KQL', tabId: activeTabId, kql: entry.query });
488
+ }
489
+ }
490
+ }, [activeTabId, dispatch]);
491
+
492
+ // --- Extracted handlers for JSX props ---
493
+ const focusPrimaryPane = useCallback(() => setFocusedPane('primary'), [setFocusedPane]);
494
+ const focusPrimaryPaneKeyDown = useCallback((e: React.KeyboardEvent) => {
495
+ if (e.key === 'Enter' || e.key === ' ') {
496
+ setFocusedPane('primary');
497
+ }
498
+ }, [setFocusedPane]);
499
+ const focusSecondaryPane = useCallback(() => setFocusedPane('secondary'), [setFocusedPane]);
500
+ const focusSecondaryPaneKeyDown = useCallback((e: React.KeyboardEvent) => {
501
+ if (e.key === 'Enter' || e.key === ' ') {
502
+ setFocusedPane('secondary');
503
+ }
504
+ }, [setFocusedPane]);
505
+ const handlePrimaryEditorChange = useCallback((v: string | undefined) => updateTabKql(activeTabId, v ?? ''), [updateTabKql, activeTabId]);
506
+ const handleSecondaryEditorChange = useCallback((v: string | undefined) => {
507
+ if (splitTabId) {
508
+ updateTabKql(splitTabId, v ?? '');
509
+ }
510
+ }, [updateTabKql, splitTabId]);
511
+ const handlePrimaryMount = useMemo(() => createEditorMountHandler('primary'), [createEditorMountHandler]);
512
+ const handleSecondaryMount = useMemo(() => createEditorMountHandler('secondary'), [createEditorMountHandler]);
513
+ const handleClearResults = useCallback(() => {
514
+ dispatch({ type: 'QUERY_SUCCESS', rows: [], columns: [], columnTypes: {}, elapsed: 0, stats: null, resultSets: [] });
515
+ }, [dispatch]);
516
+ const handlePrimaryDragOver = useCallback((e: React.DragEvent) => {
517
+ if (!dragTabIdRef.current) {
518
+ return;
519
+ }
520
+ e.preventDefault();
521
+ e.dataTransfer.dropEffect = 'move';
522
+ if (dragTabIdRef.current === activeTabId) {
523
+ return;
524
+ }
525
+ const rect = e.currentTarget.getBoundingClientRect();
526
+ setEditorDropTarget(getEditorDropTarget(rect, e.clientX, e.clientY));
527
+ }, [dragTabIdRef, activeTabId]);
528
+ const handleDragLeave = useCallback(() => setEditorDropTarget(null), []);
529
+ const handlePrimaryDrop = useCallback((e: React.DragEvent) => {
530
+ e.preventDefault();
531
+ if (dragTabIdRef.current && dragTabIdRef.current !== activeTabId && editorDropTarget) {
532
+ const dir = (editorDropTarget === 'left' || editorDropTarget === 'right') ? 'vertical' : 'horizontal';
533
+ dispatch({ type: 'TOGGLE_SPLIT', direction: dir, splitTabId: dragTabIdRef.current });
534
+ dispatch({ type: 'SET_FOCUSED_PANE', pane: 'secondary' });
535
+ }
536
+ setEditorDropTarget(null);
537
+ dragTabIdRef.current = null;
538
+ }, [dragTabIdRef, activeTabId, editorDropTarget, dispatch]);
539
+
540
+ // --- Extracted style objects ---
541
+ const editorAreaStyle = useMemo(() => ({ flex: `0 0 ${editorHeight}%` }), [editorHeight]);
542
+ const editorSplitStyle = useMemo(() => ({ flexDirection: splitDirection === 'horizontal' ? 'column' as const : 'row' as const }), [splitDirection]);
543
+ const splitHandleStyle = useMemo(() =>
544
+ splitDirection === 'vertical'
545
+ ? { width: '4px', cursor: 'col-resize' as const, position: 'relative' as const }
546
+ : { height: '4px', cursor: 'row-resize' as const, position: 'relative' as const },
547
+ [splitDirection]);
548
+ const resultsPanelStyle = useMemo(() => ({ flex: `0 0 ${100 - editorHeight}%` }), [editorHeight]);
549
+ const dropTargetStyle = useMemo(() =>
550
+ editorDropTarget === 'left' ? { top: 0, left: 0, bottom: 0, width: '50%' }
551
+ : editorDropTarget === 'right' ? { top: 0, right: 0, bottom: 0, width: '50%' }
552
+ : editorDropTarget === 'top' ? { top: 0, left: 0, right: 0, height: '50%' }
553
+ : { bottom: 0, left: 0, right: 0, height: '50%' },
554
+ [editorDropTarget]);
555
+
556
+ return (
557
+ <div className={props.className ?? styles.page}>
558
+ <TabBar
559
+ dragTabIdRef={dragTabIdRef}
560
+ onSetEditorDropTarget={setEditorDropTarget}
561
+ />
562
+
563
+ <EditorToolbar
564
+ showCancel={showCancel}
565
+ onRun={runQuery}
566
+ onCancel={cancelQuery}
567
+ onRecall={doRecall}
568
+ onFormat={formatQuery}
569
+ connections={connections}
570
+ focusedConnection={focusedConnection}
571
+ />
572
+
573
+ <div className={styles.splitContainer} ref={containerRef}>
574
+ {/* Editor + Schema sidebar */}
575
+ <div className={styles.editorArea} style={editorAreaStyle}>
576
+ <div style={schemaWidthStyle}>
577
+ <SchemaSidebar schema={schema} insertText={insertText} schemaContextRunQuery={schemaContextRunQuery} loading={schemaLoading} />
578
+ </div>
579
+ <div className={styles.schemaResizeHandle} role="separator" onMouseDown={onSchemaResizeStart} />
580
+ <div className={styles.editorSplitArea} style={editorSplitStyle}>
581
+ {/* Primary editor pane */}
582
+ <div className={focusedPane === 'primary' ? styles.editorPaneFocused : styles.editorPaneUnfocused}
583
+ role="tabpanel"
584
+ style={positionRelativeStyle}
585
+ onClick={focusPrimaryPane}
586
+ onKeyDown={focusPrimaryPaneKeyDown}
587
+ onDragOver={handlePrimaryDragOver}
588
+ onDragLeave={handleDragLeave}
589
+ onDrop={handlePrimaryDrop}>
590
+ {editorDropTarget && (
591
+ <div className={styles.editorDropTarget}
592
+ style={dropTargetStyle}>
593
+ {(editorDropTarget === 'left' || editorDropTarget === 'right') ? '⬓ Vertical split' : '⬔ Horizontal split'}
594
+ </div>
595
+ )}
596
+ <Editor
597
+ height="100%"
598
+ language="kql"
599
+ theme={isDark ? 'vs-dark' : 'vs'}
600
+ value={activeTab.kql}
601
+ onChange={handlePrimaryEditorChange}
602
+ onMount={handlePrimaryMount}
603
+ options={editorOptions}
604
+ />
605
+ </div>
606
+ {/* Split handle + secondary editor */}
607
+ {splitEnabled && splitTab && (
608
+ <>
609
+ <div className={styles.editorSplitHandle}
610
+ style={splitHandleStyle}
611
+ onDoubleClick={closeSplit} title="Double-click to close split" />
612
+ <div className={focusedPane === 'secondary' ? styles.editorPaneFocused : styles.editorPaneUnfocused}
613
+ role="tabpanel"
614
+ onClick={focusSecondaryPane}
615
+ onKeyDown={focusSecondaryPaneKeyDown}>
616
+ <Editor
617
+ height="100%"
618
+ language="kql"
619
+ theme={isDark ? 'vs-dark' : 'vs'}
620
+ value={splitTab.kql}
621
+ onChange={handleSecondaryEditorChange}
622
+ onMount={handleSecondaryMount}
623
+ options={editorOptions}
624
+ />
625
+ </div>
626
+ </>
627
+ )}
628
+ </div>
629
+ </div>
630
+
631
+ {/* Drag handle */}
632
+ <div className={styles.dragHandle} role="separator" onMouseDown={onDragStart} />
633
+
634
+ {/* Results */}
635
+ <div className={styles.resultsPanel} style={resultsPanelStyle}>
636
+ <ResultsPanel
637
+ isDark={isDark}
638
+ displayRows={displayRows}
639
+ displayColumns={displayColumns}
640
+ displayColumnTypes={displayColumnTypes}
641
+ onRecall={handleHistoryRecall}
642
+ onClear={handleClearResults}
643
+ />
644
+ </div>
645
+ </div>
646
+ </div>
647
+ );
648
+ }