-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathcrud-toolbar.tsx
More file actions
503 lines (470 loc) · 14.3 KB
/
crud-toolbar.tsx
File metadata and controls
503 lines (470 loc) · 14.3 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
import React, { useCallback, useMemo } from 'react';
import {
useTelemetry,
SkillsBannerContextEnum,
useAtlasSkillsBanner,
} from '@mongodb-js/compass-telemetry/provider';
import {
Body,
DropdownMenuButton,
Icon,
IconButton,
SpinLoader,
css,
spacing,
WarningSummary,
ErrorSummary,
Select,
Option,
SignalPopover,
useContextMenuGroups,
usePersistedState,
AtlasSkillsBanner,
} from '@mongodb-js/compass-components';
import type { MenuAction, Signal } from '@mongodb-js/compass-components';
import { ViewSwitcher } from './view-switcher';
import type { DocumentView } from '../stores/crud-store';
import { AddDataMenu } from './add-data-menu';
import { usePreference } from 'compass-preferences-model/provider';
import UpdateMenu from './update-data-menu';
import DeleteMenu from './delete-data-menu';
import { QueryBar } from '@mongodb-js/compass-query-bar';
import { useConnectionInfoRef } from '@mongodb-js/compass-connections/provider';
import { DOCUMENT_NARROW_ICON_BREAKPOINT } from '../constants/document-narrow-icon-breakpoint';
const crudQueryBarStyles = css({
width: '100%',
position: 'relative',
});
const crudToolbarStyles = css({
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: spacing[300],
padding: spacing[400],
});
const crudBarStyles = css({
width: '100%',
display: 'flex',
gap: spacing[200],
justifyContent: 'space-between',
});
const toolbarLeftActionStyles = css({
display: 'flex',
alignItems: 'center',
gap: spacing[200],
});
const toolbarRightActionStyles = css({
display: 'flex',
alignItems: 'center',
gap: spacing[200],
});
const prevNextStyles = css({
display: 'flex',
alignItems: 'center',
});
const exportCollectionButtonStyles = css({
whiteSpace: 'nowrap',
});
const outputOptionsButtonStyles = css({
whiteSpace: 'nowrap',
});
const docsPerPageOptionStyles = css({
width: spacing[1600] + spacing[300],
});
const loaderContainerStyles = css({
paddingLeft: spacing[200],
paddingRight: spacing[200],
});
type ExportDataOption = 'export-query' | 'export-full-collection';
const exportDataActions: MenuAction<ExportDataOption>[] = [
{ action: 'export-query', label: 'Export query results' },
{ action: 'export-full-collection', label: 'Export the full collection' },
];
type ExpandControlsOption = 'expand-all' | 'collapse-all';
const expandControlsOptions: MenuAction<ExpandControlsOption>[] = [
{ action: 'expand-all', label: 'Expand all documents' },
{ action: 'collapse-all', label: 'Collapse all documents' },
];
const OUTDATED_WARNING = `The content is outdated and no longer in sync
with the current query. Press "Find" again to see the results for
the current query.`;
// From https://github.com/mongodb/mongo/blob/master/src/mongo/base/error_codes.yml#L86
const ERROR_CODE_OPERATION_TIMED_OUT = 50;
const INCREASE_MAX_TIME_MS_HINT =
'Operation exceeded time limit. Please try increasing the maxTimeMS for the query in the expanded filter options.';
type ErrorWithPossibleCode = Error & {
code?: {
value: number;
};
};
function isOperationTimedOutError(err: ErrorWithPossibleCode) {
return (
err.name === 'MongoServerError' &&
err.code?.value === ERROR_CODE_OPERATION_TIMED_OUT
);
}
export type CrudToolbarProps = {
activeDocumentView: DocumentView;
count?: number;
end: number;
error?: ErrorWithPossibleCode | null;
getPage: (page: number) => void;
insertDataHandler: (openInsertKey: 'insert-document' | 'import-file') => void;
instanceDescription: string;
isWritable: boolean;
isFetching: boolean;
loadingCount: boolean;
onApplyClicked: () => void;
onResetClicked: () => void;
onUpdateButtonClicked: () => void;
onDeleteButtonClicked: () => void;
onExpandAllClicked: () => void;
onCollapseAllClicked: () => void;
openExportFileDialog: (exportFullCollection?: boolean) => void;
outdated: boolean;
page: number;
readonly: boolean;
refreshDocuments: () => void;
resultId: string;
start: number;
viewSwitchHandler: (view: DocumentView) => void;
insights?: Signal;
queryLimit?: number;
querySkip?: number;
docsPerPage: number;
updateMaxDocumentsPerPage: (docsPerPage: number) => void;
};
const CrudToolbar: React.FunctionComponent<CrudToolbarProps> = ({
activeDocumentView,
count,
end,
error,
getPage,
insertDataHandler,
instanceDescription,
isWritable,
isFetching,
loadingCount,
onApplyClicked,
onResetClicked,
onUpdateButtonClicked,
onDeleteButtonClicked,
onExpandAllClicked,
onCollapseAllClicked,
openExportFileDialog,
outdated,
page,
readonly,
refreshDocuments,
resultId,
start,
viewSwitchHandler,
insights,
queryLimit,
querySkip,
docsPerPage,
updateMaxDocumentsPerPage,
}) => {
const track = useTelemetry();
const connectionInfoRef = useConnectionInfoRef();
const isImportExportEnabled = usePreference('enableImportExport');
const [dismissed, setDismissed] = usePersistedState(
'mongodb_compass_dismissedAtlasDocSkillBanner',
false
);
// @experiment Skills in Atlas | Jira Epic: CLOUDP-346311
const { shouldShowAtlasSkillsBanner } = useAtlasSkillsBanner(
SkillsBannerContextEnum.Documents
);
const displayedDocumentCount = useMemo(
() => (loadingCount ? '' : `${count ?? 'N/A'}`),
[loadingCount, count]
);
const onClickRefreshDocuments = useCallback(() => {
track('Query Results Refreshed', {}, connectionInfoRef.current);
refreshDocuments();
}, [refreshDocuments, track, connectionInfoRef]);
const prevButtonDisabled = useMemo(() => page === 0, [page]);
const nextButtonDisabled = useMemo(
// If we don't know the count, we can't know if there are more pages.
() =>
count === undefined || count === null
? false
: docsPerPage * (page + 1) >= count,
[count, page, docsPerPage]
);
const enableExplainPlan = usePreference('enableExplainPlan');
const shouldDisableBulkOp = useMemo(
() => querySkip || queryLimit,
[querySkip, queryLimit]
);
const contextMenuRef = useContextMenuGroups(
() => [
{
telemetryLabel: 'Expand all documents',
items: [
{
label: 'Expand all documents',
onAction: () => {
onExpandAllClicked();
},
},
{
label: 'Collapse all documents',
onAction: () => {
onCollapseAllClicked();
},
},
isImportExportEnabled
? {
label: 'Import JSON or CSV file',
onAction: () => {
insertDataHandler('import-file');
},
}
: undefined,
!readonly
? {
label: 'Insert document...',
onAction: () => {
insertDataHandler('insert-document');
},
}
: undefined,
...(isImportExportEnabled
? [
{
label: 'Export query results...',
onAction: () => {
openExportFileDialog(false);
},
},
{
label: 'Export full collection...',
onAction: () => {
openExportFileDialog(true);
},
},
]
: []),
...(!readonly && isWritable && !shouldDisableBulkOp
? [
{
label: 'Bulk update',
onAction: () => {
onUpdateButtonClicked();
},
},
{
label: 'Bulk delete',
onAction: () => {
onDeleteButtonClicked();
},
},
]
: []),
{
label: 'Refresh',
onAction: () => {
onClickRefreshDocuments();
},
},
],
},
],
[
isImportExportEnabled,
readonly,
isWritable,
shouldDisableBulkOp,
onCollapseAllClicked,
onExpandAllClicked,
insertDataHandler,
openExportFileDialog,
onUpdateButtonClicked,
onDeleteButtonClicked,
onClickRefreshDocuments,
]
);
return (
<div className={crudToolbarStyles} ref={contextMenuRef}>
<div className={crudQueryBarStyles}>
<QueryBar
source="crud"
resultId={resultId}
buttonLabel="Find"
onApply={onApplyClicked}
onReset={onResetClicked}
showExplainButton={enableExplainPlan}
/>
</div>
<AtlasSkillsBanner
ctaText="Practice creating, reading, updating, and deleting documents efficiently."
skillsUrl="https://learn.mongodb.com/courses/crud-operations-in-mongodb?team=growth"
onCloseSkillsBanner={() => {
setDismissed(true);
track('Atlas Skills CTA Dismissed', {
context: 'Documents Tab',
});
}}
showBanner={shouldShowAtlasSkillsBanner && !dismissed}
onCtaClick={() => {
track('Atlas Skills CTA Clicked', {
context: 'Documents Tab',
});
}}
/>
<div className={crudBarStyles}>
<div className={toolbarLeftActionStyles}>
{!readonly && (
<AddDataMenu
insertDataHandler={insertDataHandler}
isWritable={isWritable}
instanceDescription={instanceDescription}
/>
)}
{isImportExportEnabled && (
<DropdownMenuButton<ExportDataOption>
data-testid="crud-export-collection"
actions={exportDataActions}
onAction={(action: ExportDataOption) =>
openExportFileDialog(action === 'export-full-collection')
}
buttonText="Export Data"
buttonProps={{
className: exportCollectionButtonStyles,
size: 'xsmall',
leftGlyph: <Icon glyph="Export" />,
}}
narrowBreakpoint={DOCUMENT_NARROW_ICON_BREAKPOINT}
/>
)}
{!readonly && (
<UpdateMenu
isWritable={isWritable && !shouldDisableBulkOp}
disabledTooltip={
isWritable
? 'Remove limit and skip in your query to perform an update'
: instanceDescription
}
onClick={onUpdateButtonClicked}
></UpdateMenu>
)}
{!readonly && (
<DeleteMenu
isWritable={isWritable && !shouldDisableBulkOp}
disabledTooltip={
isWritable
? 'Remove limit and skip in your query to perform a delete'
: instanceDescription
}
onClick={onDeleteButtonClicked}
></DeleteMenu>
)}
{insights && <SignalPopover signals={insights} />}
</div>
<div className={toolbarRightActionStyles}>
<Select
data-testid="crud-document-per-page-selector"
size="xsmall"
disabled={isFetching}
allowDeselect={false}
dropdownWidthBasis="option"
aria-label="Update number of documents per page"
value={`${docsPerPage}`}
onChange={(value: string) =>
updateMaxDocumentsPerPage(parseInt(value))
}
>
{['25', '50', '75', '100'].map((value) => (
<Option
className={docsPerPageOptionStyles}
key={value}
value={value}
>
{value}
</Option>
))}
</Select>
<Body data-testid="crud-document-count-display">
{start} – {end}{' '}
{displayedDocumentCount && `of ${displayedDocumentCount}`}
</Body>
{loadingCount && (
<div className={loaderContainerStyles}>
<SpinLoader size="12px" title="Fetching document count…" />
</div>
)}
{!loadingCount && !isFetching && (
<IconButton
aria-label="Refresh documents"
title="Refresh documents"
data-testid="refresh-documents-button"
onClick={onClickRefreshDocuments}
>
<Icon glyph="Refresh" />
</IconButton>
)}
<div className={prevNextStyles}>
<IconButton
data-testid="docs-toolbar-prev-page-btn"
aria-label="Previous Page"
title="Previous Page"
onClick={() => getPage(page - 1)}
disabled={prevButtonDisabled}
>
<Icon glyph="ChevronLeft" />
</IconButton>
<IconButton
data-testid="docs-toolbar-next-page-btn"
aria-label="Next Page"
title="Next Page"
onClick={() => getPage(page + 1)}
disabled={nextButtonDisabled}
>
<Icon glyph="ChevronRight" />
</IconButton>
</div>
<DropdownMenuButton<ExpandControlsOption>
data-testid="crud-export-collection"
actions={expandControlsOptions}
onAction={(action: ExpandControlsOption) =>
action === 'expand-all'
? onExpandAllClicked()
: onCollapseAllClicked()
}
buttonText=""
buttonProps={{
className: outputOptionsButtonStyles,
size: 'xsmall',
title: 'Output Options',
['aria-label']: 'Output Options',
disabled: activeDocumentView === 'Table',
}}
/>
<ViewSwitcher
activeView={activeDocumentView}
onChange={viewSwitchHandler}
/>
</div>
</div>
{error && (
<ErrorSummary
data-testid="document-list-error-summary"
errors={
isOperationTimedOutError(error)
? INCREASE_MAX_TIME_MS_HINT
: error.message
}
/>
)}
{outdated && !error && (
<WarningSummary
data-testid="crud-outdated-message-id"
warnings={[OUTDATED_WARNING]}
/>
)}
</div>
);
};
export { CrudToolbar };