@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,358 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+
3
+ import {
4
+ mapRenderType,
5
+ applyVisualizationHints,
6
+ buildTreemapVegaSpec,
7
+ SUPPORTED_RENDER_TYPES,
8
+ buildSpec,
9
+ CHART_TYPES,
10
+ } from './ChartPanel.logic';
11
+ import type { KustoVisualization } from '../../services/kusto';
12
+
13
+ beforeEach(() => {
14
+ vi.spyOn(console, 'error').mockImplementation(() => {});
15
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
16
+ });
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // SUPPORTED_RENDER_TYPES
20
+ // ---------------------------------------------------------------------------
21
+
22
+ describe('SUPPORTED_RENDER_TYPES', () => {
23
+ it('contains all expected render types', () => {
24
+ const expected = [
25
+ 'timechart', 'linechart', 'barchart', 'columnchart',
26
+ 'piechart', 'areachart', 'stackedareachart', 'scatterchart',
27
+ 'treemap', 'card', 'timepivot', 'pivotchart',
28
+ ];
29
+ for (const t of expected) {
30
+ expect(SUPPORTED_RENDER_TYPES.has(t)).toBe(true);
31
+ }
32
+ });
33
+
34
+ it('is a Set', () => {
35
+ expect(SUPPORTED_RENDER_TYPES).toBeInstanceOf(Set);
36
+ });
37
+ });
38
+
39
+ // ---------------------------------------------------------------------------
40
+ // CHART_TYPES
41
+ // ---------------------------------------------------------------------------
42
+
43
+ describe('CHART_TYPES', () => {
44
+ it('contains all expected chart types with labels', () => {
45
+ const values = CHART_TYPES.map((t) => t.value);
46
+ expect(values).toContain('bar');
47
+ expect(values).toContain('line');
48
+ expect(values).toContain('area');
49
+ expect(values).toContain('donut');
50
+ expect(values).toContain('grouped-bar');
51
+ expect(values).toContain('scatter');
52
+ expect(values).toContain('heatmap');
53
+ expect(values).toContain('treemap');
54
+ expect(values).toContain('card');
55
+ expect(values).toContain('pivot');
56
+ });
57
+ });
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // mapRenderType
61
+ // ---------------------------------------------------------------------------
62
+
63
+ describe('mapRenderType', () => {
64
+ it.each([
65
+ ['timechart', 'line'],
66
+ ['linechart', 'line'],
67
+ ['barchart', 'bar'],
68
+ ['columnchart', 'grouped-bar'],
69
+ ['piechart', 'donut'],
70
+ ['areachart', 'area'],
71
+ ['stackedareachart', 'area'],
72
+ ['scatterchart', 'scatter'],
73
+ ['treemap', 'treemap'],
74
+ ['card', 'card'],
75
+ ['timepivot', 'pivot'],
76
+ ['pivotchart', 'pivot'],
77
+ ])('maps "%s" to "%s"', (input, expected) => {
78
+ expect(mapRenderType(input)).toBe(expected);
79
+ });
80
+
81
+ it('is case insensitive', () => {
82
+ expect(mapRenderType('TimeChart')).toBe('line');
83
+ expect(mapRenderType('BARCHART')).toBe('bar');
84
+ expect(mapRenderType('PieChart')).toBe('donut');
85
+ });
86
+
87
+ it('returns null for unsupported render types', () => {
88
+ expect(mapRenderType('table')).toBeNull();
89
+ expect(mapRenderType('unknown')).toBeNull();
90
+ expect(mapRenderType('')).toBeNull();
91
+ });
92
+ });
93
+
94
+ // ---------------------------------------------------------------------------
95
+ // applyVisualizationHints
96
+ // ---------------------------------------------------------------------------
97
+
98
+ describe('applyVisualizationHints', () => {
99
+ const columns = ['Timestamp', 'Count', 'Category'];
100
+ const rows = [
101
+ { Timestamp: '2024-01-01T00:00:00Z', Count: 10, Category: 'A' },
102
+ { Timestamp: '2024-01-02T00:00:00Z', Count: 20, Category: 'B' },
103
+ ];
104
+
105
+ it('returns null when viz is undefined', () => {
106
+ expect(applyVisualizationHints(undefined, columns, rows)).toBeNull();
107
+ });
108
+
109
+ it('returns null when viz type is unsupported', () => {
110
+ const viz: KustoVisualization = { type: 'table' };
111
+ expect(applyVisualizationHints(viz, columns, rows)).toBeNull();
112
+ });
113
+
114
+ it('returns null for unknown viz type', () => {
115
+ const viz: KustoVisualization = { type: 'unknown' };
116
+ expect(applyVisualizationHints(viz, columns, rows)).toBeNull();
117
+ });
118
+
119
+ it('returns config with mapped chart type for valid viz', () => {
120
+ const viz: KustoVisualization = { type: 'timechart' };
121
+ const result = applyVisualizationHints(viz, columns, rows);
122
+ expect(result).not.toBeNull();
123
+ expect(result!.chartType).toBe('line');
124
+ });
125
+
126
+ it('uses xColumn from viz when provided', () => {
127
+ const viz: KustoVisualization = { type: 'barchart', xColumn: 'Category' };
128
+ const result = applyVisualizationHints(viz, columns, rows);
129
+ expect(result!.xField).toBe('Category');
130
+ });
131
+
132
+ it('uses yColumns from viz when provided', () => {
133
+ const viz: KustoVisualization = { type: 'barchart', yColumns: ['Count'] };
134
+ const result = applyVisualizationHints(viz, columns, rows);
135
+ expect(result!.yField).toBe('Count');
136
+ });
137
+
138
+ it('uses series from viz when provided', () => {
139
+ const viz: KustoVisualization = { type: 'barchart', series: 'Category' };
140
+ const result = applyVisualizationHints(viz, columns, rows);
141
+ expect(result!.colorField).toBe('Category');
142
+ });
143
+
144
+ it('falls back to autoDetect fields when viz does not specify columns', () => {
145
+ const viz: KustoVisualization = { type: 'timechart' };
146
+ const result = applyVisualizationHints(viz, columns, rows);
147
+ expect(result).not.toBeNull();
148
+ // autoDetect should pick Timestamp as xField and Count as yField
149
+ expect(result!.xField).toBe('Timestamp');
150
+ expect(result!.yField).toBe('Count');
151
+ });
152
+ });
153
+
154
+ // ---------------------------------------------------------------------------
155
+ // buildTreemapVegaSpec
156
+ // ---------------------------------------------------------------------------
157
+
158
+ describe('buildTreemapVegaSpec', () => {
159
+ const rows = [
160
+ { category: 'A', group: 'G1', value: 10 },
161
+ { category: 'B', group: 'G1', value: 20 },
162
+ { category: 'C', group: 'G2', value: 30 },
163
+ ];
164
+ const chartColors = ['#ff0000', '#00ff00', '#0000ff'];
165
+
166
+ it('returns a valid Vega spec object', () => {
167
+ const spec = buildTreemapVegaSpec('category', 'value', null, rows, chartColors, false);
168
+ expect(spec["$schema"]).toContain('vega');
169
+ expect(spec["data"]).toBeDefined();
170
+ expect(spec["marks"]).toBeDefined();
171
+ expect(spec["scales"]).toBeDefined();
172
+ expect(spec["signals"]).toBeDefined();
173
+ });
174
+
175
+ it('includes padding and autosize', () => {
176
+ const spec = buildTreemapVegaSpec('category', 'value', null, rows, chartColors, false);
177
+ expect(spec["padding"]).toBe(2);
178
+ expect(spec["autosize"]).toBe('none');
179
+ });
180
+
181
+ it('creates flat hierarchy without colorField', () => {
182
+ const spec = buildTreemapVegaSpec('category', 'value', null, rows, chartColors, false);
183
+ const treeData = (spec["data"] as { name: string; values: unknown[] }[])[0].values as { id: string; parent: string | null }[];
184
+ // root + 3 leaves
185
+ expect(treeData).toHaveLength(4);
186
+ expect(treeData[0].id).toBe('root');
187
+ expect(treeData[0].parent).toBeNull();
188
+ expect(treeData[1].parent).toBe('root');
189
+ });
190
+
191
+ it('creates grouped hierarchy with colorField', () => {
192
+ const spec = buildTreemapVegaSpec('category', 'value', 'group', rows, chartColors, false);
193
+ const treeData = (spec["data"] as { name: string; values: unknown[] }[])[0].values as { id: string; parent: string | null }[];
194
+ // root + 2 groups + 3 leaves
195
+ expect(treeData).toHaveLength(6);
196
+ const groups = treeData.filter((d) => d.id.startsWith('group:'));
197
+ expect(groups).toHaveLength(2);
198
+ const leaves = treeData.filter((d) => d.id.startsWith('leaf:'));
199
+ expect(leaves).toHaveLength(3);
200
+ for (const leaf of leaves) {
201
+ expect(leaf.parent).toMatch(/^group:/);
202
+ }
203
+ });
204
+
205
+ it('uses dark mode text color when isDark is true', () => {
206
+ const spec = buildTreemapVegaSpec('category', 'value', null, rows, chartColors, true);
207
+ const textMark = (spec["marks"] as { type: string; encode: { enter: { fill: { value: string } } } }[]).find((m) => m.type === 'text');
208
+ expect(textMark!.encode.enter.fill.value).toBe('#fff');
209
+ });
210
+
211
+ it('uses light mode text color when isDark is false', () => {
212
+ const spec = buildTreemapVegaSpec('category', 'value', null, rows, chartColors, false);
213
+ const textMark = (spec["marks"] as { type: string; encode: { enter: { fill: { value: string } } } }[]).find((m) => m.type === 'text');
214
+ expect(textMark!.encode.enter.fill.value).toBe('#222');
215
+ });
216
+
217
+ it('uses dark mode stroke color for rects', () => {
218
+ const spec = buildTreemapVegaSpec('category', 'value', null, rows, chartColors, true);
219
+ const rectMark = (spec["marks"] as { type: string; encode: { enter: { stroke: { value: string } } } }[]).find((m) => m.type === 'rect');
220
+ expect(rectMark!.encode.enter.stroke.value).toBe('#2a2a2a');
221
+ });
222
+
223
+ it('clamps negative values to 0', () => {
224
+ const negativeRows = [{ category: 'A', value: -5 }];
225
+ const spec = buildTreemapVegaSpec('category', 'value', null, negativeRows, chartColors, false);
226
+ const treeData = (spec["data"] as { name: string; values: { size: number }[] }[])[0].values;
227
+ const leaf = treeData.find((d) => d.size !== undefined && treeData.indexOf(d) > 0);
228
+ expect(leaf!.size).toBe(0);
229
+ });
230
+ });
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // buildSpec
234
+ // ---------------------------------------------------------------------------
235
+
236
+ describe('buildSpec', () => {
237
+ const columns = ['Name', 'Value'];
238
+ const rows = [{ Name: 'A', Value: 10 }];
239
+ const chartColors = ['#4285f4', '#ea4335', '#34a853'];
240
+
241
+ it('builds a bar spec', () => {
242
+ const spec = buildSpec('bar', 'Name', 'Value', null, columns, rows, chartColors);
243
+ expect((spec as { mark: { type: string } }).mark.type).toBe('bar');
244
+ });
245
+
246
+ it('builds a line spec', () => {
247
+ const spec = buildSpec('line', 'Name', 'Value', null, columns, rows, chartColors);
248
+ expect((spec as { mark: { type: string } }).mark.type).toBe('line');
249
+ });
250
+
251
+ it('builds an area spec', () => {
252
+ const spec = buildSpec('area', 'Name', 'Value', null, columns, rows, chartColors);
253
+ expect((spec as { mark: { type: string } }).mark.type).toBe('area');
254
+ });
255
+
256
+ it('builds a donut spec', () => {
257
+ const spec = buildSpec('donut', 'Name', 'Value', null, columns, rows, chartColors);
258
+ expect((spec as { mark: { type: string; innerRadius: number } }).mark.type).toBe('arc');
259
+ expect((spec as { mark: { innerRadius: number } }).mark.innerRadius).toBe(50);
260
+ });
261
+
262
+ it('builds a grouped-bar spec', () => {
263
+ const spec = buildSpec('grouped-bar', 'Name', 'Value', null, columns, rows, chartColors);
264
+ expect((spec as { mark: { type: string } }).mark.type).toBe('bar');
265
+ });
266
+
267
+ it('builds a scatter spec', () => {
268
+ const spec = buildSpec('scatter', 'Name', 'Value', null, columns, rows, chartColors);
269
+ expect((spec as { mark: { type: string } }).mark.type).toBe('circle');
270
+ });
271
+
272
+ it('builds a heatmap spec', () => {
273
+ const spec = buildSpec('heatmap', 'Name', 'Value', null, columns, rows, chartColors);
274
+ expect((spec as { mark: { type: string } }).mark.type).toBe('rect');
275
+ const encoding = (spec as { encoding: { color: { scale: { scheme: string } } } }).encoding;
276
+ expect(encoding.color.scale.scheme).toBe('blues');
277
+ });
278
+
279
+ it('builds a card spec', () => {
280
+ const spec = buildSpec('card', 'Name', 'Value', null, columns, rows, chartColors);
281
+ expect((spec as { mark: { type: string } }).mark.type).toBe('text');
282
+ expect((spec as { mark: { fontSize: number } }).mark.fontSize).toBe(48);
283
+ });
284
+
285
+ it('builds a card spec using xField when yField value is missing', () => {
286
+ const cardRows = [{ Name: 'hello' }];
287
+ const spec = buildSpec('card', 'Name', 'Missing', null, ['Name', 'Missing'], cardRows, chartColors);
288
+ expect((spec as { data: { values: { value: string }[] } }).data.values[0].value).toBe('hello');
289
+ });
290
+
291
+ it('builds a pivot spec', () => {
292
+ const spec = buildSpec('pivot', 'Name', 'Value', null, columns, rows, chartColors);
293
+ expect((spec as { mark: { type: string } }).mark.type).toBe('rect');
294
+ const encoding = (spec as { encoding: { color: { scale: { scheme: string } } } }).encoding;
295
+ expect(encoding.color.scale.scheme).toBe('orangered');
296
+ });
297
+
298
+ it('builds a treemap spec (bar fallback)', () => {
299
+ const spec = buildSpec('treemap', 'Name', 'Value', null, columns, rows, chartColors);
300
+ expect((spec as { mark: { type: string } }).mark.type).toBe('bar');
301
+ });
302
+
303
+ it('includes color encoding with colorField when provided', () => {
304
+ const spec = buildSpec('bar', 'Name', 'Value', 'Category', ['Name', 'Value', 'Category'], rows, chartColors);
305
+ const encoding = (spec as { encoding: { color: { field: string } } }).encoding;
306
+ expect(encoding.color.field).toBe('Category');
307
+ });
308
+
309
+ it('uses single color value when colorField is null', () => {
310
+ const spec = buildSpec('bar', 'Name', 'Value', null, columns, rows, chartColors);
311
+ const encoding = (spec as { encoding: { color: { value: string } } }).encoding;
312
+ expect(encoding.color.value).toBe(chartColors[0]);
313
+ });
314
+
315
+ it('uses temporal xType for datetime columns in line chart', () => {
316
+ const timeColumns = ['Timestamp', 'Value'];
317
+ const timeRows = [{ Timestamp: '2024-01-01T00:00:00Z', Value: 10 }];
318
+ const spec = buildSpec('line', 'Timestamp', 'Value', null, timeColumns, timeRows, chartColors);
319
+ const encoding = (spec as { encoding: { x: { type: string } } }).encoding;
320
+ expect(encoding.x.type).toBe('temporal');
321
+ });
322
+
323
+ it('uses nominal xType for non-datetime columns in line chart', () => {
324
+ const spec = buildSpec('line', 'Name', 'Value', null, columns, rows, chartColors);
325
+ const encoding = (spec as { encoding: { x: { type: string } } }).encoding;
326
+ expect(encoding.x.type).toBe('nominal');
327
+ });
328
+
329
+ it('heatmap uses colorField for y axis when provided', () => {
330
+ const spec = buildSpec('heatmap', 'Name', 'Value', 'Category', ['Name', 'Value', 'Category'], rows, chartColors);
331
+ const encoding = (spec as { encoding: { y: { field: string } } }).encoding;
332
+ expect(encoding.y.field).toBe('Category');
333
+ });
334
+
335
+ it('pivot uses colorField for y axis when provided', () => {
336
+ const spec = buildSpec('pivot', 'Name', 'Value', 'Category', ['Name', 'Value', 'Category'], rows, chartColors);
337
+ const encoding = (spec as { encoding: { y: { field: string } } }).encoding;
338
+ expect(encoding.y.field).toBe('Category');
339
+ });
340
+
341
+ it('pivot includes tooltip encoding', () => {
342
+ const spec = buildSpec('pivot', 'Name', 'Value', null, columns, rows, chartColors);
343
+ const encoding = (spec as { encoding: { tooltip: unknown[] } }).encoding;
344
+ expect(encoding.tooltip).toBeDefined();
345
+ expect(encoding.tooltip).toHaveLength(2);
346
+ });
347
+
348
+ it('grouped-bar includes xOffset when colorField is present', () => {
349
+ const spec = buildSpec('grouped-bar', 'Name', 'Value', 'Cat', ['Name', 'Value', 'Cat'], rows, chartColors);
350
+ const encoding = (spec as { encoding: { xOffset: { field: string } } }).encoding;
351
+ expect(encoding.xOffset.field).toBe('Cat');
352
+ });
353
+
354
+ it('card handles empty rows', () => {
355
+ const spec = buildSpec('card', 'Name', 'Value', null, columns, [], chartColors);
356
+ expect((spec as { data: { values: { value: string }[] } }).data.values[0].value).toBe('');
357
+ });
358
+ });
@@ -0,0 +1,318 @@
1
+ import type { VisualizationSpec } from '../VegaChart/VegaChart';
2
+ import type { KustoVisualization } from '../../services/kusto';
3
+
4
+ export type ChartType = 'bar' | 'line' | 'area' | 'donut' | 'grouped-bar' | 'scatter' | 'treemap' | 'card' | 'heatmap' | 'pivot';
5
+
6
+ export const CHART_TYPES: { value: ChartType; label: string }[] = [
7
+ { value: 'bar', label: 'Bar' },
8
+ { value: 'line', label: 'Line' },
9
+ { value: 'area', label: 'Stacked Area' },
10
+ { value: 'donut', label: 'Donut' },
11
+ { value: 'grouped-bar', label: 'Grouped Bar' },
12
+ { value: 'scatter', label: 'Scatter' },
13
+ { value: 'heatmap', label: 'Heatmap' },
14
+ { value: 'treemap', label: 'Treemap' },
15
+ { value: 'card', label: 'Card' },
16
+ { value: 'pivot', label: 'Pivot' },
17
+ ];
18
+
19
+ const RENDER_TYPE_MAP: Record<string, ChartType> = {
20
+ timechart: 'line',
21
+ linechart: 'line',
22
+ barchart: 'bar',
23
+ columnchart: 'grouped-bar',
24
+ piechart: 'donut',
25
+ areachart: 'area',
26
+ stackedareachart: 'area',
27
+ scatterchart: 'scatter',
28
+ treemap: 'treemap',
29
+ card: 'card',
30
+ timepivot: 'pivot',
31
+ pivotchart: 'pivot',
32
+ };
33
+
34
+ export const SUPPORTED_RENDER_TYPES = new Set(Object.keys(RENDER_TYPE_MAP));
35
+
36
+ export function mapRenderType(renderType: string): ChartType | null {
37
+ return RENDER_TYPE_MAP[renderType.toLowerCase()] ?? null;
38
+ }
39
+
40
+ export interface DetectedConfig {
41
+ chartType: ChartType;
42
+ xField: string;
43
+ yField: string;
44
+ colorField: string | null;
45
+ }
46
+
47
+ export function classifyColumns(columns: string[], rows: Record<string, unknown>[]): { strings: string[]; numbers: string[]; datetimes: string[] } {
48
+ const strings: string[] = [];
49
+ const numbers: string[] = [];
50
+ const datetimes: string[] = [];
51
+
52
+ for (const col of columns) {
53
+ const samples = rows.slice(0, 20).map((r) => r[col]).filter((v) => v !== null && v !== undefined && v !== '');
54
+ if (samples.length === 0) { strings.push(col); continue; }
55
+
56
+ const allNumeric = samples.every((v) => !isNaN(Number(v)));
57
+ if (allNumeric) { numbers.push(col); continue; }
58
+
59
+ const allDatetime = samples.every((v) => {
60
+ const s = String(v);
61
+ return s.match(/^\d{4}-\d{2}-\d{2}/) && !isNaN(new Date(s).getTime());
62
+ });
63
+ if (allDatetime) { datetimes.push(col); continue; }
64
+
65
+ strings.push(col);
66
+ }
67
+
68
+ return { strings, numbers, datetimes };
69
+ }
70
+
71
+ export function autoDetect(columns: string[], rows: Record<string, unknown>[]): DetectedConfig {
72
+ const { strings, numbers, datetimes } = classifyColumns(columns, rows);
73
+
74
+ if (datetimes.length >= 1 && numbers.length >= 1 && strings.length >= 1) {
75
+ return { chartType: 'line', xField: datetimes[0], yField: numbers[0], colorField: strings[0] };
76
+ }
77
+ if (datetimes.length >= 1 && numbers.length >= 1) {
78
+ return { chartType: 'line', xField: datetimes[0], yField: numbers[0], colorField: null };
79
+ }
80
+ if (strings.length >= 1 && numbers.length >= 1) {
81
+ return { chartType: 'bar', xField: strings[0], yField: numbers[0], colorField: null };
82
+ }
83
+ if (numbers.length >= 2) {
84
+ return { chartType: 'scatter', xField: numbers[0], yField: numbers[1], colorField: strings[0] ?? null };
85
+ }
86
+ if (strings.length >= 2 && numbers.length >= 1) {
87
+ return { chartType: 'donut', xField: strings[0], yField: numbers[0], colorField: strings[1] };
88
+ }
89
+ return { chartType: 'bar', xField: columns[0] ?? '', yField: columns[1] ?? '', colorField: null };
90
+ }
91
+
92
+ export function applyVisualizationHints(viz: KustoVisualization | undefined, columns: string[], rows: Record<string, unknown>[]): DetectedConfig | null {
93
+ if (!viz) {
94
+ return null;
95
+ }
96
+ const mapped = mapRenderType(viz.type);
97
+ if (!mapped) {
98
+ return null;
99
+ }
100
+
101
+ const fallback = autoDetect(columns, rows);
102
+ const config: DetectedConfig = {
103
+ chartType: mapped,
104
+ xField: viz.xColumn ?? fallback.xField,
105
+ yField: viz.yColumns?.[0] ?? fallback.yField,
106
+ colorField: viz.series ?? fallback.colorField,
107
+ };
108
+
109
+ return config;
110
+ }
111
+
112
+ export function buildTreemapVegaSpec(xField: string, yField: string, colorField: string | null, rows: Record<string, unknown>[], chartColors: string[], isDark: boolean): Record<string, unknown> {
113
+ const groupField = colorField ?? xField;
114
+ const groups = [...new Set(rows.map((r) => String(r[groupField] ?? '')))];
115
+
116
+ // Build flat hierarchy: root → group → leaf
117
+ const treeData: { id: string; parent: string | null; size: number; label: string; group: string }[] = [
118
+ { id: 'root', parent: null, size: 0, label: '', group: '' },
119
+ ];
120
+
121
+ if (colorField && colorField !== xField) {
122
+ for (const g of groups) {
123
+ treeData.push({ id: `group:${g}`, parent: 'root', size: 0, label: g, group: g });
124
+ }
125
+ for (let i = 0; i < rows.length; i++) {
126
+ const r = rows[i];
127
+ const g = String(r[groupField] ?? '');
128
+ const val = Math.max(0, Number(r[yField]) || 0);
129
+ treeData.push({ id: `leaf:${i}`, parent: `group:${g}`, size: val, label: String(r[xField] ?? ''), group: g });
130
+ }
131
+ } else {
132
+ for (let i = 0; i < rows.length; i++) {
133
+ const r = rows[i];
134
+ const val = Math.max(0, Number(r[yField]) || 0);
135
+ const g = String(r[xField] ?? '');
136
+ treeData.push({ id: `leaf:${i}`, parent: 'root', size: val, label: g, group: g });
137
+ }
138
+ }
139
+
140
+ const textColor = isDark ? '#fff' : '#222';
141
+
142
+ return {
143
+ $schema: 'https://vega.github.io/schema/vega/v6.json',
144
+ padding: 2,
145
+ autosize: 'none',
146
+ signals: [
147
+ { name: 'width', update: 'containerSize()[0] - 4' },
148
+ { name: 'height', value: 300 },
149
+ ],
150
+ data: [
151
+ {
152
+ name: 'tree',
153
+ values: treeData,
154
+ transform: [
155
+ { type: 'stratify', key: 'id', parentKey: 'parent' },
156
+ { type: 'treemap', field: 'size', sort: { field: 'value' }, round: true, method: 'squarify', ratio: 1.6, size: [{ signal: 'width' }, { signal: 'height' }] },
157
+ ],
158
+ },
159
+ {
160
+ name: 'leaves',
161
+ source: 'tree',
162
+ transform: [{ type: 'filter', expr: '!datum.children' }],
163
+ },
164
+ ],
165
+ scales: [
166
+ { name: 'color', type: 'ordinal', domain: groups, range: chartColors },
167
+ ],
168
+ marks: [
169
+ {
170
+ type: 'rect',
171
+ from: { data: 'leaves' },
172
+ encode: {
173
+ enter: { stroke: { value: isDark ? '#2a2a2a' : '#fff' }, strokeWidth: { value: 1 } },
174
+ update: {
175
+ x: { field: 'x0' },
176
+ y: { field: 'y0' },
177
+ x2: { field: 'x1' },
178
+ y2: { field: 'y1' },
179
+ fill: { scale: 'color', field: 'group' },
180
+ tooltip: { signal: `{'${xField}': datum.label, '${yField}': datum.size}` },
181
+ },
182
+ hover: { fillOpacity: { value: 0.8 } },
183
+ },
184
+ },
185
+ {
186
+ type: 'text',
187
+ from: { data: 'leaves' },
188
+ interactive: false,
189
+ encode: {
190
+ enter: {
191
+ font: { value: 'sans-serif' },
192
+ align: { value: 'center' },
193
+ baseline: { value: 'middle' },
194
+ fill: { value: textColor },
195
+ fontSize: { value: 11 },
196
+ },
197
+ update: {
198
+ x: { signal: '0.5 * (datum.x0 + datum.x1)' },
199
+ y: { signal: '0.5 * (datum.y0 + datum.y1)' },
200
+ text: { signal: '(datum.x1 - datum.x0) > 50 && (datum.y1 - datum.y0) > 14 ? datum.label : ""' },
201
+ },
202
+ },
203
+ },
204
+ ],
205
+ };
206
+ }
207
+
208
+ export function buildSpec(chartType: ChartType, xField: string, yField: string, colorField: string | null, columns: string[], rows: Record<string, unknown>[], chartColors: string[]): VisualizationSpec {
209
+ const { datetimes } = classifyColumns(columns, rows);
210
+ const xIsTime = datetimes.includes(xField);
211
+ const xType = xIsTime ? 'temporal' : 'nominal';
212
+
213
+ switch (chartType) {
214
+ case 'bar':
215
+ return {
216
+ mark: { type: 'bar', cornerRadiusEnd: 3 },
217
+ encoding: {
218
+ y: { field: xField, type: 'nominal', sort: '-x', axis: { labelLimit: 200 } },
219
+ x: { field: yField, type: 'quantitative' },
220
+ ...(colorField ? { color: { field: colorField, type: 'nominal', scale: { range: chartColors } } } : { color: { value: chartColors[0] } }),
221
+ },
222
+ } as VisualizationSpec;
223
+ case 'line':
224
+ return {
225
+ mark: { type: 'line', point: { filled: true, size: 30 } },
226
+ encoding: {
227
+ x: { field: xField, type: xType },
228
+ y: { field: yField, type: 'quantitative' },
229
+ ...(colorField ? { color: { field: colorField, type: 'nominal', scale: { range: chartColors } } } : { color: { value: chartColors[0] } }),
230
+ },
231
+ } as VisualizationSpec;
232
+ case 'area':
233
+ return {
234
+ mark: { type: 'area', line: true, point: false, opacity: 0.6 },
235
+ encoding: {
236
+ x: { field: xField, type: xType },
237
+ y: { field: yField, type: 'quantitative', stack: 'zero' },
238
+ ...(colorField ? { color: { field: colorField, type: 'nominal', scale: { range: chartColors } } } : { color: { value: chartColors[0] } }),
239
+ },
240
+ } as VisualizationSpec;
241
+ case 'donut':
242
+ return {
243
+ mark: { type: 'arc', innerRadius: 50 },
244
+ encoding: {
245
+ theta: { field: yField, type: 'quantitative', stack: true },
246
+ color: { field: xField, type: 'nominal', scale: { range: chartColors } },
247
+ },
248
+ } as VisualizationSpec;
249
+ case 'grouped-bar':
250
+ return {
251
+ mark: { type: 'bar', cornerRadiusEnd: 3 },
252
+ encoding: {
253
+ x: { field: xField, type: 'nominal' },
254
+ y: { field: yField, type: 'quantitative' },
255
+ ...(colorField ? {
256
+ xOffset: { field: colorField, type: 'nominal' },
257
+ color: { field: colorField, type: 'nominal', scale: { range: chartColors } },
258
+ } : { color: { value: chartColors[0] } }),
259
+ },
260
+ } as VisualizationSpec;
261
+ case 'scatter':
262
+ return {
263
+ mark: { type: 'circle', opacity: 0.7 },
264
+ encoding: {
265
+ x: { field: xField, type: 'quantitative' },
266
+ y: { field: yField, type: 'quantitative' },
267
+ ...(colorField ? { color: { field: colorField, type: 'nominal', scale: { range: chartColors } } } : { color: { value: chartColors[0] } }),
268
+ size: { value: 60 },
269
+ },
270
+ } as VisualizationSpec;
271
+ case 'heatmap':
272
+ return {
273
+ mark: { type: 'rect' },
274
+ encoding: {
275
+ x: { field: xField, type: xIsTime ? 'temporal' : 'nominal' },
276
+ y: { field: colorField ?? yField, type: 'nominal' },
277
+ color: { field: yField, type: 'quantitative', scale: { scheme: 'blues' } },
278
+ },
279
+ } as VisualizationSpec;
280
+ case 'treemap':
281
+ // Treemap uses raw Vega spec via buildTreemapVegaSpec — this is a fallback
282
+ return {
283
+ mark: { type: 'bar', cornerRadiusEnd: 3 },
284
+ encoding: {
285
+ y: { field: xField, type: 'nominal', sort: '-x', axis: { labelLimit: 200 } },
286
+ x: { field: yField, type: 'quantitative' },
287
+ ...(colorField ? { color: { field: colorField, type: 'nominal', scale: { range: chartColors } } } : { color: { value: chartColors[0] } }),
288
+ },
289
+ } as VisualizationSpec;
290
+ case 'card': {
291
+ const value = rows[0]?.[yField] ?? rows[0]?.[xField] ?? '';
292
+ const label = yField || xField;
293
+ return {
294
+ data: { values: [{ value: String(value), label }] },
295
+ mark: { type: 'text', fontSize: 48, fontWeight: 'bold', align: 'center', baseline: 'middle' },
296
+ encoding: {
297
+ text: { field: 'value', type: 'nominal' },
298
+ color: { value: chartColors[0] },
299
+ },
300
+ } as VisualizationSpec;
301
+ }
302
+ case 'pivot':
303
+ return {
304
+ mark: { type: 'rect' },
305
+ encoding: {
306
+ x: { field: xField, type: xIsTime ? 'temporal' : 'nominal' },
307
+ y: { field: colorField ?? columns.find((c) => c !== xField && c !== yField) ?? yField, type: 'nominal' },
308
+ color: { field: yField, type: 'quantitative', scale: { scheme: 'orangered' } },
309
+ tooltip: [
310
+ { field: xField, type: xIsTime ? 'temporal' : 'nominal' },
311
+ { field: yField, type: 'quantitative' },
312
+ ],
313
+ },
314
+ } as VisualizationSpec;
315
+ default:
316
+ return { mark: 'bar' } as VisualizationSpec;
317
+ }
318
+ }