-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathCollectionView.tsx
More file actions
739 lines (668 loc) · 32.7 KB
/
Copy pathCollectionView.tsx
File metadata and controls
739 lines (668 loc) · 32.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Badge, ProgressBar, Tab, TabList } from '@fluentui/react-components';
import { useConfiguration } from '@microsoft/vscode-ext-webview/react';
import * as l10n from '@vscode/l10n';
import { type JSX, useEffect, useRef, useState } from 'react';
import { type TableDataEntry } from '../../../documentdb/ClusterSession';
import { UsageImpact } from '../../../utils/surveyTypes';
import { useTrpcClient } from '../../_integration/useTrpcClient';
import { Announcer } from '../../components/accessibility';
import { useSelectiveContextMenuPrevention } from '../../components/useSelectiveContextMenuPrevention';
import { setCompletionContext } from '../../query-language-support';
import { IndexesTab } from '../indexView/IndexesTab';
import './collectionView.scss';
import {
CollectionViewContext,
type CollectionViewContextType,
DefaultCollectionViewContext,
Views,
} from './collectionViewContext';
import { type CollectionViewWebviewConfigurationType } from './collectionViewController';
import { QueryEditor } from './components/queryEditor/QueryEditor';
import { QueryInsightsMain } from './components/queryInsightsTab/QueryInsightsTab';
import { DataViewPanelJSON } from './components/resultsTab/DataViewPanelJSON';
import { DataViewPanelTable } from './components/resultsTab/DataViewPanelTable';
import { DataViewPanelTree } from './components/resultsTab/DataViewPanelTree';
import { ToolbarDocumentManipulation } from './components/toolbar/ToolbarDocumentManipulation';
import { ToolbarMainView } from './components/toolbar/ToolbarMainView';
import { ToolbarTableNavigation } from './components/toolbar/ToolbarTableNavigation';
import { ToolbarViewNavigation } from './components/toolbar/ToolbarViewNavigation';
import { ViewSwitcher } from './components/toolbar/ViewSwitcher';
import { stage1Failed, stage1Succeeded, startStage1Load } from './queryInsightsReducer';
import { extractErrorCode } from './utils/errorCodeExtractor';
interface QueryResults {
tableHeaders?: string[];
tableData?: TableDataEntry[]; // 'x-objectid': string;
tableCurrentPath?: string[];
treeData?: { [key: string]: unknown }[];
jsonDocuments?: string[];
/** Number of documents returned by the query (for screen reader announcements) */
documentCount?: number;
}
export const CollectionView = (): JSX.Element => {
/**
* Use the configuration object to access the data passed to the webview at its creation.
* Feel free to update the content of the object. It won't be synced back to the extension though.
*/
const configuration = useConfiguration<CollectionViewWebviewConfigurationType>();
/**
* Use the `useTrpcClient` hook to get the tRPC client
*/
const trpcClient = useTrpcClient();
/**
* Please note: using the context and states inside of closures can lead to stale data.
*
* Closures capture state at the time of the closure creation, and do not update when the state changes.
* This can lead to unexpected and surprising bugs where the state is not updated as expected (or rather 'assumed').
*
* There are two ways I know to work around this:
* 1. Use the useRef hook to store the state and access it in the closure.
* 2. Define the closure inside the useEffect hook, so it captures the state at the time of the effect.
*
* We can't use 2 in this case, because we need to define the handleMessage function outside of the useEffect hook.
* As it could happen that the message arrives while we're reconfiguring the event listener.
*
* We're using the useRef hook to store the state and access it in the closure.
*/
// that's our current global context of the view
const [currentContext, setCurrentContext] = useState<CollectionViewContextType>(() => ({
...DefaultCollectionViewContext,
activeQuery: {
...DefaultCollectionViewContext.activeQuery,
pageSize: configuration.defaultPageSize,
},
}));
useSelectiveContextMenuPrevention();
// Apply initial query from cross-feature navigation (e.g., Playground → Collection View)
useEffect(() => {
if (configuration.initialQuery) {
const iq = configuration.initialQuery;
// Populate the query editors with the initial values
setCurrentContext((prev) => ({
...prev,
pendingPaste: {
filter: iq.filter,
project: iq.project,
sort: iq.sort,
skip: iq.skip,
limit: iq.limit,
},
// Execute the query immediately
activeQuery: {
...prev.activeQuery,
queryText: iq.filter ?? prev.activeQuery.queryText,
filter: iq.filter ?? prev.activeQuery.filter,
project: iq.project ?? prev.activeQuery.project,
sort: iq.sort ?? prev.activeQuery.sort,
skip: iq.skip ?? prev.activeQuery.skip,
limit: iq.limit ?? prev.activeQuery.limit,
pageNumber: 1,
executionIntent: 'initial',
},
}));
}
// Only run on mount — configuration is stable after creation
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// that's the local view of query results
// TODO: it's a potential data duplication in the end, consider moving it into the global context of the view
const [currentQueryResults, setCurrentQueryResults] = useState<QueryResults>();
// Track which tab is currently active. Honors `configuration.initialTab`
// so an external caller (e.g. the "Indexes" tree node) can open the view
// pre-pinned to the Index Management tab.
const [selectedTab, setSelectedTab] = useState<'tab_result' | 'tab_indexes' | 'tab_queryInsights'>(
() => configuration.initialTab ?? 'tab_result',
);
// keep Refs updated with the current state
const currentQueryResultsRef = useRef(currentQueryResults);
const currentContextRef = useRef(currentContext);
useEffect(() => {
currentQueryResultsRef.current = currentQueryResults;
currentContextRef.current = currentContext;
}, [currentQueryResults, currentContext]);
/**
* Reset query insights when query changes (not on pagination)
* Only reset when executionIntent is 'initial' or 'refresh'
* On 'pagination', preserve Query Insights data since the query hasn't changed
*/
useEffect(() => {
const intent = currentContext.activeQuery.executionIntent;
// Only reset on actual query changes, not pagination
if (intent === 'initial' || intent === 'refresh') {
console.trace('[CollectionView] Query changed (intent: {0}), resetting Query Insights', intent);
setCurrentContext((prev) => ({
...prev,
queryInsights: DefaultCollectionViewContext.queryInsights,
}));
}
// On 'pagination' → preserve existing Query Insights state
}, [currentContext.activeQuery]);
/**
* Non-blocking Stage 1 prefetch after query execution. Populates the
* ClusterSession cache so data is ready when the user switches to the
* Query Insights tab. Called only for a fresh query (`initial`/`refresh`)
* — see the intent gate at the call site.
*
* Dedupe contract (shared with the fallback fetch in
* QueryInsightsTab.tsx): the claim below flips the pipeline to
* `s1Loading`, so whichever of the two paths gets there first "claims"
* the load and the other observes `kind === 's1Loading'` and bails. See
* `startStage1Load` in `queryInsightsReducer.ts`.
*/
const prefetchQueryInsights = (): void => {
// Claim the Stage 1 load from inside the functional updater so the
// gate reads React's latest queued state via `prev`, never the render
// closure or a ref. The reset effect's `queryInsights → idle` is
// queued synchronously in the same effect phase, strictly before this
// promise microtask, so it is already composed into `prev`: on a fresh
// query `prev.queryInsights` is `idle` here. This is what makes the
// stale pre-reset read (F2) structurally impossible rather than merely
// unlikely — a closure read saw the previous run's terminal state and
// a ref lags by one commit. If the tab fallback already claimed the
// load, `prev` is `s1Loading`/later and we leave it untouched.
setCurrentContext((prev) => {
if (prev.queryInsights.kind !== 'idle') {
return prev;
}
return { ...prev, queryInsights: startStage1Load(prev.queryInsights) };
});
// Fire the warm-up request. In the rare both-paths race the fallback
// fetches too; the F8 guards below drop whichever result lands second,
// and `getQueryInsightsStage1` is an idempotent cache read.
// Query parameters are now retrieved from ClusterSession - no need to pass them
void trpcClient.mongoClusters.collectionView.queryInsights.getQueryInsightsStage1
.query()
.then((stage1Data) => {
// The reducer auto-chains `s1Loading → s2Loading` so the
// Stage 2 fetch effect in QueryInsightsTab picks up
// immediately when the user lands on the tab.
setCurrentContext((prev) => {
// F8 guard (mirror of the .catch guard below): if the
// pipeline has moved past `s1Loading` (typically because
// the user kicked off a newer query / reset), the
// resolved payload is stale — drop it rather than
// clobber the live state.
if (prev.queryInsights.kind !== 's1Loading') {
return prev;
}
return {
...prev,
queryInsights: stage1Succeeded(prev.queryInsights, stage1Data),
};
});
console.debug('Stage 1 data prefetched:', stage1Data);
})
.catch((error) => {
const errorCode = extractErrorCode(error);
const message = error instanceof Error ? error.message : String(error);
setCurrentContext((prev) => {
// F8: only fold the failure into the state machine if
// the current pipeline is still the one we kicked off.
// Stage 1 is short-lived and the only way to leave
// `s1Loading` is for our `.then`/`.catch` to fire or
// for a query reset/new run to start a fresh pipeline —
// in the latter case the stale failure must not
// overwrite the new state. Note: doesn't fully cover a
// second `s1Loading` racing the first (would need a
// requestKey, like Stage 3); accepted as Low risk
// because Stage 1 typically completes in well under
// the time it takes a user to retrigger.
if (prev.queryInsights.kind !== 's1Loading') {
return prev;
}
return {
...prev,
queryInsights: stage1Failed(prev.queryInsights, message, errorCode),
};
});
console.warn('Stage 1 prefetch failed:', error);
});
};
/**
* This is used to run the query. We control it by setting the query configuration
* in the currentContext state. Whenever the query configuration changes,
* we run the query.
*
* It helps us manage the query runs as the configuration changes from
* within various controls (query panel, paging, etc.).
*/
function getDataForView(selectedView: Views): void {
switch (selectedView) {
case Views.TABLE: {
const path = currentContext.currentViewState?.currentPath ?? [];
trpcClient.mongoClusters.collectionView.getCurrentPageAsTable
.query(path)
.then((result) => {
let tableHeaders: string[];
/*
* If the _id is not in the headers, we add it as the first column.
* This is a presentation detail, not a data detail, that's why it's done
* here, in the view, not in the controller.
*/
if (result.headers.find((header) => header === '_id') === undefined) {
tableHeaders = ['_id', ...result.headers];
} else {
tableHeaders = result.headers ?? [];
}
setCurrentQueryResults((prev) => ({
...prev,
tableHeaders: tableHeaders,
tableData: (result.data as TableDataEntry[]) ?? [],
}));
})
.catch((error) => {
void trpcClient.common.displayErrorMessage.mutate({
message: l10n.t('Error while loading the data'),
modal: false,
cause: error instanceof Error ? error.message : String(error),
});
});
break;
}
case Views.TREE:
trpcClient.mongoClusters.collectionView.getCurrentPageAsTree
.query()
.then((result) => {
setCurrentQueryResults((prev) => ({
...prev,
treeData: result,
}));
})
.catch((error) => {
void trpcClient.common.displayErrorMessage.mutate({
message: l10n.t('Error while loading the data'),
modal: false,
cause: error instanceof Error ? error.message : String(error),
});
});
break;
case Views.JSON:
trpcClient.mongoClusters.collectionView.getCurrentPageAsJson
.query()
.then((result) => {
setCurrentQueryResults((prev) => ({
...prev,
jsonDocuments: result,
}));
})
.catch((error) => {
void trpcClient.common.displayErrorMessage.mutate({
message: l10n.t('Error while loading the data'),
modal: false,
cause: error instanceof Error ? error.message : String(error),
});
});
break;
default:
break;
}
}
function updateAutoCompletionData(): void {
trpcClient.mongoClusters.collectionView.getFieldCompletionData
.query()
.then((fields) => {
setCompletionContext(configuration.sessionId, { fields });
})
.catch((error) => {
console.debug('Failed to update field completion data:', error);
// Non-blocking — completion will work without fields
trpcClient.common.reportEvent
.mutate({
eventName: 'fieldCompletionDataFetchFailed',
properties: {
error: error instanceof Error ? error.message : String(error),
},
})
.catch(() => {
// best-effort telemetry, swallow errors
});
});
}
useEffect(() => {
setCurrentContext((prev) => ({ ...prev, isLoading: true }));
// 1. Run the query, this operation only acknowledges the request.
// Next we need to load the ones we need.
trpcClient.mongoClusters.collectionView.runFindQuery
.query({
filter: currentContext.activeQuery.filter,
project: currentContext.activeQuery.project,
sort: currentContext.activeQuery.sort,
skip: currentContext.activeQuery.skip,
limit: currentContext.activeQuery.limit,
pageNumber: currentContext.activeQuery.pageNumber,
pageSize: currentContext.activeQuery.pageSize,
executionIntent: currentContext.activeQuery.executionIntent ?? 'pagination',
})
.then((response) => {
// Store document count for screen reader announcements (skip pagination)
if (currentContext.activeQuery.executionIntent !== 'pagination') {
setCurrentQueryResults((prev) => ({ ...prev, documentCount: response.documentCount }));
}
// 2. This is the time to update the auto-completion data
// Since now we do know more about the data returned from the query
updateAutoCompletionData();
// 3. Load the data for the current view
getDataForView(currentContext.currentView);
// 4. Non-blocking Stage 1 prefetch to populate cache. Only on a
// fresh query (initial/refresh): pagination keeps the same
// query, so the existing Query Insights pipeline (and any
// Stage 1+ data) stays valid and must not be reset. This
// mirrors the reset effect's own intent gate, so the prefetch
// fires exactly when the pipeline is being reset to `idle`.
const prefetchIntent = currentContext.activeQuery.executionIntent;
if (prefetchIntent === 'initial' || prefetchIntent === 'refresh') {
prefetchQueryInsights();
}
setCurrentContext((prev) => ({ ...prev, isLoading: false, isFirstTimeLoad: false }));
})
.catch((error) => {
void trpcClient.common.displayErrorMessage.mutate({
message: l10n.t('Error while running the query'),
modal: true,
cause: error instanceof Error ? error.message : String(error),
});
})
.finally(() => {
setCurrentContext((prev) => ({ ...prev, isLoading: false, isFirstTimeLoad: false }));
});
}, [currentContext.activeQuery]);
useEffect(() => {
if (currentContext.currentView === Views.TABLE && currentContext.currentViewState?.currentPath) {
getDataForView(currentContext.currentView);
}
}, [currentContext.currentViewState?.currentPath]);
const handleViewChanged = (_optionValue: string) => {
let selection: Views;
switch (_optionValue) {
case 'Table View':
selection = Views.TABLE;
break;
case 'Tree View':
selection = Views.TREE;
break;
case 'JSON View':
selection = Views.JSON;
break;
default:
selection = Views.TABLE;
break;
}
trpcClient.common.reportEvent
.mutate({
eventName: 'viewChanged',
properties: {
view: selection,
},
})
.catch((error) => {
console.debug('Failed to report an event:', error);
});
setCurrentContext((prev) => ({ ...prev, currentView: selection }));
getDataForView(selection);
trpcClient.common.surveyPing.mutate({ usageImpact: UsageImpact.Medium }).catch(() => {});
};
function handleDeleteDocumentRequest(): void {
trpcClient.mongoClusters.collectionView.deleteDocumentsById
.mutate(currentContext.dataSelection.selectedDocumentObjectIds)
.then((acknowledged) => {
if (!acknowledged) {
return;
}
/**
* The data on the server has been deleted and our extension code has updated its
* cache as well. Now we need to update the view locally, so that the user sees
* the changes immediately without potential focus/table resizing issues etc.
*/
setCurrentQueryResults((prev) => ({
...prev,
tableData: prev?.tableData?.filter(
(row) =>
!currentContextRef.current.dataSelection.selectedDocumentObjectIds.includes(
row['x-objectid'] ?? '',
),
),
}));
setCurrentContext((prev) => ({
...prev,
dataSelection: {
selectedDocumentIndexes: [],
selectedDocumentObjectIds: [],
},
}));
})
.catch((error) => {
void trpcClient.common.displayErrorMessage.mutate({
message: l10n.t('Error deleting selected documents'),
modal: false,
cause: error instanceof Error ? error.message : String(error),
});
});
}
function handleViewDocumentRequest(): void {
trpcClient.mongoClusters.collectionView.viewDocumentById
.mutate(currentContext.dataSelection.selectedDocumentObjectIds[0])
.catch((error) => {
void trpcClient.common.displayErrorMessage.mutate({
message: l10n.t('Error opening the document view'),
modal: false,
cause: error instanceof Error ? error.message : String(error),
});
});
}
function handleEditDocumentRequest(): void {
trpcClient.mongoClusters.collectionView.editDocumentById
.mutate(currentContext.dataSelection.selectedDocumentObjectIds[0])
.catch((error) => {
void trpcClient.common.displayErrorMessage.mutate({
message: l10n.t('Error opening the document view'),
modal: false,
cause: error instanceof Error ? error.message : String(error),
});
});
}
function handleAddDocumentRequest(): void {
trpcClient.mongoClusters.collectionView.addDocument.mutate().catch((error) => {
void trpcClient.common.displayErrorMessage.mutate({
message: l10n.t('Error opening the document view'),
modal: false,
cause: error instanceof Error ? error.message : String(error),
});
});
}
function handleStepInRequest(row: number, cell: number): void {
// Always use the ref to access latest data
const queryResults = currentQueryResultsRef.current;
const activeDocument: TableDataEntry = queryResults?.tableData?.[row] ?? {};
const activeColumn: string = queryResults?.tableHeaders?.[cell] ?? '';
// Add proper property existence check
if (!(activeColumn in activeDocument)) {
console.debug('Column does not exist in document:', activeColumn);
return;
}
const activeCell = activeDocument[activeColumn];
// Add proper null check
if (activeCell === undefined || activeCell === null) {
console.debug('Cell value is undefined for column:', activeColumn);
return;
}
console.debug('Step-in requested on cell', activeCell, 'in row', row, 'column', cell);
if (activeColumn === '_id') {
console.debug('Cell is an _id, skipping step-in');
return;
}
// Type guard for safer property access
if (
typeof activeCell !== 'object' ||
activeCell === null ||
!('type' in activeCell) ||
activeCell.type !== 'object'
) {
console.debug('Cell is not an object, skipping step-in');
return;
}
const newPath = [...(currentContextRef.current.currentViewState?.currentPath ?? []), activeColumn];
setCurrentContext((prev) => ({
...prev,
currentViewState: {
currentPath: newPath,
},
}));
trpcClient.common.reportEvent
.mutate({
eventName: 'stepIn',
properties: {
source: 'step-in-button',
},
measurements: {
depth: newPath.length ?? 0,
},
})
.catch((error) => {
console.debug('Failed to report an event:', error);
});
}
return (
<CollectionViewContext.Provider value={[currentContext, setCurrentContext]}>
<div className="collectionView">
{currentContext.isLoading && (
<ProgressBar thickness="large" shape="square" className="progressBar" aria-hidden={true} />
)}
{/* Screen reader announcement when query completes */}
<Announcer
when={!currentContext.isLoading && currentQueryResults?.documentCount !== undefined}
politeness="assertive"
message={
(currentQueryResults?.documentCount ?? 0) > 0
? l10n.t('Results found')
: l10n.t('No results found')
}
/>
<div className="toolbarMainView">
<ToolbarMainView selectedTab={selectedTab} />
</div>
{selectedTab !== 'tab_indexes' && (
<QueryEditor
onExecuteRequest={() => {
// Get all query values from the editor at once
const query = currentContext.queryEditor?.getCurrentQuery() ?? {
filter: '{ }',
project: '{ }',
sort: '{ }',
skip: 0,
limit: 0,
};
setCurrentContext((prev) => ({
...prev,
activeQuery: {
...prev.activeQuery,
queryText: query.filter, // deprecated: kept in sync with filter
filter: query.filter,
project: query.project,
sort: query.sort,
skip: query.skip,
limit: query.limit,
pageNumber: 1,
executionIntent: 'initial',
},
}));
trpcClient.common.reportEvent
.mutate({
eventName: 'executeQuery',
properties: {
ui: 'shortcut',
},
measurements: {
queryLenth: query.filter.length,
},
})
.catch((error) => {
console.debug('Failed to report an event:', error);
});
}}
/>
)}
<TabList
selectedValue={selectedTab}
onTabSelect={(_event, data) => {
const newTab = data.value as 'tab_result' | 'tab_indexes' | 'tab_queryInsights';
// Report tab switching telemetry
trpcClient.common.reportEvent
.mutate({
eventName: 'tabChanged',
properties: {
previousTab: selectedTab,
newTab: newTab,
},
})
.catch((error) => {
console.debug('Failed to report tab change:', error);
});
setSelectedTab(newTab);
}}
style={{ marginTop: '-10px' }}
>
<Tab id="tab.results" value="tab_result">
{l10n.t('Documents')}
</Tab>
<Tab id="tab.indexes" value="tab_indexes">
{l10n.t('Indexes')}
</Tab>
<Tab id="tab.queryInsights" value="tab_queryInsights">
<div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
Query Insights
<Badge
appearance="tint"
size="small"
shape="rounded"
color="brand"
aria-label={l10n.t('Query Insights feature is in preview')}
>
PREVIEW
</Badge>
</div>
</Tab>
</TabList>
{selectedTab === 'tab_result' && (
<>
<div className="resultsActionBar">
<ToolbarViewNavigation />
<ToolbarDocumentManipulation
onDeleteClick={handleDeleteDocumentRequest}
onEditClick={handleEditDocumentRequest}
onViewClick={handleViewDocumentRequest}
onAddClick={handleAddDocumentRequest}
/>
<ViewSwitcher onViewChanged={handleViewChanged} />
</div>
<div className="resultsDisplayArea" id="resultsDisplayAreaId">
{
{
'Table View': (
<DataViewPanelTable
liveHeaders={currentQueryResults?.tableHeaders ?? []}
liveData={currentQueryResults?.tableData ?? []}
handleStepIn={handleStepInRequest}
/>
),
'Tree View': <DataViewPanelTree liveData={currentQueryResults?.treeData ?? []} />,
'JSON View': <DataViewPanelJSON value={currentQueryResults?.jsonDocuments ?? []} />,
default: <div>error '{currentContext.currentView}'</div>,
}[currentContext.currentView] // switch-statement
}
</div>
{currentContext.currentView === Views.TABLE && (
<div className="toolbarTableNavigation">
<ToolbarTableNavigation />
</div>
)}
</>
)}
{selectedTab === 'tab_indexes' && <IndexesTab collectionName={configuration.collectionName} />}
{selectedTab === 'tab_queryInsights' && <QueryInsightsMain />}
</div>
</CollectionViewContext.Provider>
);
};