@jupyterlab/apputils 4.0.0-alpha.8 → 4.0.0-beta.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 (81) hide show
  1. package/lib/clipboard.d.ts +1 -1
  2. package/lib/dialog.d.ts +66 -4
  3. package/lib/dialog.js +126 -29
  4. package/lib/dialog.js.map +1 -1
  5. package/lib/domutils.js.map +1 -1
  6. package/lib/index.d.ts +1 -0
  7. package/lib/index.js +1 -0
  8. package/lib/index.js.map +1 -1
  9. package/lib/inputdialog.d.ts +35 -3
  10. package/lib/inputdialog.js +122 -12
  11. package/lib/inputdialog.js.map +1 -1
  12. package/lib/kernelstatuses.js +26 -25
  13. package/lib/kernelstatuses.js.map +1 -1
  14. package/lib/mainareawidget.d.ts +9 -0
  15. package/lib/mainareawidget.js +29 -4
  16. package/lib/mainareawidget.js.map +1 -1
  17. package/lib/menufactory.js +14 -15
  18. package/lib/menufactory.js.map +1 -1
  19. package/lib/notification.d.ts +336 -0
  20. package/lib/notification.js +310 -0
  21. package/lib/notification.js.map +1 -0
  22. package/lib/runningSessions.js +2 -2
  23. package/lib/runningSessions.js.map +1 -1
  24. package/lib/sanitizer.d.ts +20 -7
  25. package/lib/sanitizer.js +34 -7
  26. package/lib/sanitizer.js.map +1 -1
  27. package/lib/semanticCommand.js +11 -2
  28. package/lib/semanticCommand.js.map +1 -1
  29. package/lib/sessioncontext.d.ts +53 -6
  30. package/lib/sessioncontext.js +100 -68
  31. package/lib/sessioncontext.js.map +1 -1
  32. package/lib/testutils.d.ts +5 -0
  33. package/lib/testutils.js +46 -0
  34. package/lib/testutils.js.map +1 -0
  35. package/lib/thememanager.js +20 -5
  36. package/lib/thememanager.js.map +1 -1
  37. package/lib/tokens.d.ts +21 -42
  38. package/lib/tokens.js.map +1 -1
  39. package/lib/toolbar/factory.d.ts +2 -1
  40. package/lib/toolbar/factory.js +132 -105
  41. package/lib/toolbar/factory.js.map +1 -1
  42. package/lib/toolbar/index.js +4 -0
  43. package/lib/toolbar/index.js.map +1 -1
  44. package/lib/toolbar/registry.d.ts +11 -0
  45. package/lib/toolbar/registry.js +20 -3
  46. package/lib/toolbar/registry.js.map +1 -1
  47. package/lib/toolbar/widget.d.ts +3 -0
  48. package/lib/toolbar/widget.js +8 -5
  49. package/lib/toolbar/widget.js.map +1 -1
  50. package/lib/widgettracker.d.ts +13 -1
  51. package/lib/widgettracker.js +29 -2
  52. package/lib/widgettracker.js.map +1 -1
  53. package/package.json +31 -30
  54. package/src/clipboard.ts +107 -0
  55. package/src/commandlinker.ts +209 -0
  56. package/src/commandpalette.ts +175 -0
  57. package/src/dialog.tsx +1133 -0
  58. package/src/domutils.ts +53 -0
  59. package/src/index.ts +78 -0
  60. package/src/inputdialog.ts +551 -0
  61. package/src/kernelstatuses.tsx +279 -0
  62. package/src/mainareawidget.ts +362 -0
  63. package/src/menufactory.ts +201 -0
  64. package/src/notification.ts +559 -0
  65. package/src/printing.ts +180 -0
  66. package/src/runningSessions.tsx +233 -0
  67. package/src/sanitizer.ts +986 -0
  68. package/src/semanticCommand.ts +77 -0
  69. package/src/sessioncontext.tsx +1774 -0
  70. package/src/testutils.ts +49 -0
  71. package/src/thememanager.ts +530 -0
  72. package/src/tokens.ts +351 -0
  73. package/src/toolbar/factory.ts +422 -0
  74. package/src/toolbar/index.ts +8 -0
  75. package/src/toolbar/registry.ts +158 -0
  76. package/src/toolbar/widget.tsx +242 -0
  77. package/src/widgettracker.ts +391 -0
  78. package/src/windowresolver.ts +218 -0
  79. package/style/dialog.css +16 -1
  80. package/style/inputdialog.css +5 -0
  81. package/style/materialcolors.css +5 -0
package/src/dialog.tsx ADDED
@@ -0,0 +1,1133 @@
1
+ // Copyright (c) Jupyter Development Team.
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import { ITranslator, nullTranslator } from '@jupyterlab/translation';
5
+ import {
6
+ Button,
7
+ closeIcon,
8
+ LabIcon,
9
+ ReactWidget,
10
+ Styling
11
+ } from '@jupyterlab/ui-components';
12
+ import { ArrayExt } from '@lumino/algorithm';
13
+ import { PromiseDelegate } from '@lumino/coreutils';
14
+ import { Message, MessageLoop } from '@lumino/messaging';
15
+ import { Panel, PanelLayout, Widget } from '@lumino/widgets';
16
+ import * as React from 'react';
17
+ import { WidgetTracker } from './widgettracker';
18
+
19
+ /**
20
+ * Create and show a dialog.
21
+ *
22
+ * @param options - The dialog setup options.
23
+ *
24
+ * @returns A promise that resolves with whether the dialog was accepted.
25
+ */
26
+ export function showDialog<T>(
27
+ options: Partial<Dialog.IOptions<T>> = {}
28
+ ): Promise<Dialog.IResult<T>> {
29
+ const dialog = new Dialog(options);
30
+ return dialog.launch();
31
+ }
32
+
33
+ /**
34
+ * Show an error message dialog.
35
+ *
36
+ * @param title - The title of the dialog box.
37
+ *
38
+ * @param error - the error to show in the dialog body (either a string
39
+ * or an object with a string `message` property).
40
+ */
41
+ export function showErrorMessage(
42
+ title: string,
43
+ error: string | Dialog.IError,
44
+ buttons?: ReadonlyArray<Dialog.IButton>
45
+ ): Promise<void> {
46
+ const trans = Dialog.translator.load('jupyterlab');
47
+ buttons = buttons ?? [Dialog.okButton({ label: trans.__('Dismiss') })];
48
+ console.warn('Showing error:', error);
49
+
50
+ // Cache promises to prevent multiple copies of identical dialogs showing
51
+ // to the user.
52
+ const body = typeof error === 'string' ? error : error.message;
53
+ const key = title + '----' + body;
54
+ const promise = Private.errorMessagePromiseCache.get(key);
55
+ if (promise) {
56
+ return promise;
57
+ } else {
58
+ const dialogPromise = showDialog({
59
+ title: title,
60
+ body: body,
61
+ buttons: buttons
62
+ }).then(
63
+ () => {
64
+ Private.errorMessagePromiseCache.delete(key);
65
+ },
66
+ error => {
67
+ // TODO: Use .finally() above when supported
68
+ Private.errorMessagePromiseCache.delete(key);
69
+ throw error;
70
+ }
71
+ );
72
+ Private.errorMessagePromiseCache.set(key, dialogPromise);
73
+ return dialogPromise;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * A modal dialog widget.
79
+ */
80
+ export class Dialog<T> extends Widget {
81
+ /**
82
+ * Create a dialog panel instance.
83
+ *
84
+ * @param options - The dialog setup options.
85
+ */
86
+ constructor(options: Partial<Dialog.IOptions<T>> = {}) {
87
+ super();
88
+ this.addClass('jp-Dialog');
89
+ const normalized = Private.handleOptions(options);
90
+ const renderer = normalized.renderer;
91
+
92
+ this._host = normalized.host;
93
+ this._defaultButton = normalized.defaultButton;
94
+ this._buttons = normalized.buttons;
95
+ this._hasClose = normalized.hasClose;
96
+ this._buttonNodes = this._buttons.map(b => renderer.createButtonNode(b));
97
+ this._checkboxNode = null;
98
+ this._lastMouseDownInDialog = false;
99
+
100
+ if (normalized.checkbox) {
101
+ const {
102
+ label = '',
103
+ caption = '',
104
+ checked = false,
105
+ className = ''
106
+ } = normalized.checkbox;
107
+ this._checkboxNode = renderer.createCheckboxNode({
108
+ label,
109
+ caption: caption ?? label,
110
+ checked,
111
+ className
112
+ });
113
+ }
114
+
115
+ const layout = (this.layout = new PanelLayout());
116
+ const content = new Panel();
117
+ content.addClass('jp-Dialog-content');
118
+ if (typeof options.body === 'string') {
119
+ content.addClass('jp-Dialog-content-small');
120
+ }
121
+ layout.addWidget(content);
122
+
123
+ this._body = normalized.body;
124
+
125
+ const header = renderer.createHeader(
126
+ normalized.title,
127
+ () => this.reject(),
128
+ options
129
+ );
130
+ const body = renderer.createBody(normalized.body);
131
+ const footer = renderer.createFooter(this._buttonNodes, this._checkboxNode);
132
+ content.addWidget(header);
133
+ content.addWidget(body);
134
+ content.addWidget(footer);
135
+
136
+ this._bodyWidget = body;
137
+ this._primary = this._buttonNodes[this._defaultButton];
138
+ this._focusNodeSelector = options.focusNodeSelector;
139
+
140
+ // Add new dialogs to the tracker.
141
+ void Dialog.tracker.add(this);
142
+ }
143
+
144
+ /**
145
+ * A promise that resolves when the Dialog first rendering is done.
146
+ */
147
+ get ready(): Promise<void> {
148
+ return this._ready.promise;
149
+ }
150
+
151
+ /**
152
+ * Dispose of the resources used by the dialog.
153
+ */
154
+ dispose(): void {
155
+ const promise = this._promise;
156
+ if (promise) {
157
+ this._promise = null;
158
+ promise.reject(void 0);
159
+ ArrayExt.removeFirstOf(Private.launchQueue, promise.promise);
160
+ }
161
+ super.dispose();
162
+ }
163
+
164
+ /**
165
+ * Launch the dialog as a modal window.
166
+ *
167
+ * @returns a promise that resolves with the result of the dialog.
168
+ */
169
+ launch(): Promise<Dialog.IResult<T>> {
170
+ // Return the existing dialog if already open.
171
+ if (this._promise) {
172
+ return this._promise.promise;
173
+ }
174
+ const promise = (this._promise = new PromiseDelegate<Dialog.IResult<T>>());
175
+ const promises = Promise.all(Private.launchQueue);
176
+ Private.launchQueue.push(this._promise.promise);
177
+ return promises.then(() => {
178
+ // Do not show Dialog if it was disposed of before it was at the front of the launch queue
179
+ if (!this._promise) {
180
+ return Promise.resolve({
181
+ button: Dialog.cancelButton(),
182
+ isChecked: null,
183
+ value: null
184
+ });
185
+ }
186
+ Widget.attach(this, this._host);
187
+ return promise.promise;
188
+ });
189
+ }
190
+
191
+ /**
192
+ * Resolve the current dialog.
193
+ *
194
+ * @param index - An optional index to the button to resolve.
195
+ *
196
+ * #### Notes
197
+ * Will default to the defaultIndex.
198
+ * Will resolve the current `show()` with the button value.
199
+ * Will be a no-op if the dialog is not shown.
200
+ */
201
+ resolve(index?: number): void {
202
+ if (!this._promise) {
203
+ return;
204
+ }
205
+ if (index === undefined) {
206
+ index = this._defaultButton;
207
+ }
208
+ this._resolve(this._buttons[index]);
209
+ }
210
+
211
+ /**
212
+ * Reject the current dialog with a default reject value.
213
+ *
214
+ * #### Notes
215
+ * Will be a no-op if the dialog is not shown.
216
+ */
217
+ reject(): void {
218
+ if (!this._promise) {
219
+ return;
220
+ }
221
+ this._resolve(Dialog.cancelButton());
222
+ }
223
+
224
+ /**
225
+ * Handle the DOM events for the directory listing.
226
+ *
227
+ * @param event - The DOM event sent to the widget.
228
+ *
229
+ * #### Notes
230
+ * This method implements the DOM `EventListener` interface and is
231
+ * called in response to events on the panel's DOM node. It should
232
+ * not be called directly by user code.
233
+ */
234
+ handleEvent(event: Event): void {
235
+ switch (event.type) {
236
+ case 'keydown':
237
+ this._evtKeydown(event as KeyboardEvent);
238
+ break;
239
+ case 'mousedown':
240
+ this._evtMouseDown(event as MouseEvent);
241
+ break;
242
+ case 'click':
243
+ this._evtClick(event as MouseEvent);
244
+ break;
245
+ case 'focus':
246
+ this._evtFocus(event as FocusEvent);
247
+ break;
248
+ case 'contextmenu':
249
+ event.preventDefault();
250
+ event.stopPropagation();
251
+ break;
252
+ default:
253
+ break;
254
+ }
255
+ }
256
+
257
+ /**
258
+ * A message handler invoked on an `'after-attach'` message.
259
+ */
260
+ protected onAfterAttach(msg: Message): void {
261
+ const node = this.node;
262
+ node.addEventListener('keydown', this, true);
263
+ node.addEventListener('contextmenu', this, true);
264
+ node.addEventListener('click', this, true);
265
+ document.addEventListener('mousedown', this, true);
266
+ document.addEventListener('focus', this, true);
267
+ this._first = Private.findFirstFocusable(this.node);
268
+ this._original = document.activeElement as HTMLElement;
269
+
270
+ const setFocus = () => {
271
+ if (this._focusNodeSelector) {
272
+ const body = this.node.querySelector('.jp-Dialog-body');
273
+ const el = body?.querySelector(this._focusNodeSelector);
274
+
275
+ if (el) {
276
+ this._primary = el as HTMLElement;
277
+ }
278
+ }
279
+ this._primary?.focus();
280
+ this._ready.resolve();
281
+ };
282
+
283
+ if (
284
+ this._bodyWidget instanceof ReactWidget &&
285
+ (this._bodyWidget as ReactWidget).renderPromise !== undefined
286
+ ) {
287
+ (this._bodyWidget as ReactWidget)
288
+ .renderPromise!.then(() => {
289
+ setFocus();
290
+ })
291
+ .catch(() => {
292
+ console.error("Error while loading Dialog's body");
293
+ });
294
+ } else {
295
+ setFocus();
296
+ }
297
+ }
298
+
299
+ /**
300
+ * A message handler invoked on an `'after-detach'` message.
301
+ */
302
+ protected onAfterDetach(msg: Message): void {
303
+ const node = this.node;
304
+ node.removeEventListener('keydown', this, true);
305
+ node.removeEventListener('contextmenu', this, true);
306
+ node.removeEventListener('click', this, true);
307
+ document.removeEventListener('focus', this, true);
308
+ document.removeEventListener('mousedown', this, true);
309
+ this._original.focus();
310
+ }
311
+
312
+ /**
313
+ * A message handler invoked on a `'close-request'` message.
314
+ */
315
+ protected onCloseRequest(msg: Message): void {
316
+ if (this._promise) {
317
+ this.reject();
318
+ }
319
+ super.onCloseRequest(msg);
320
+ }
321
+
322
+ /**
323
+ * Handle the `'click'` event for a dialog button.
324
+ *
325
+ * @param event - The DOM event sent to the widget
326
+ */
327
+ protected _evtClick(event: MouseEvent): void {
328
+ const content = this.node.getElementsByClassName(
329
+ 'jp-Dialog-content'
330
+ )[0] as HTMLElement;
331
+ if (!content.contains(event.target as HTMLElement)) {
332
+ event.stopPropagation();
333
+ event.preventDefault();
334
+ if (this._hasClose && !this._lastMouseDownInDialog) {
335
+ this.reject();
336
+ }
337
+ return;
338
+ }
339
+ for (const buttonNode of this._buttonNodes) {
340
+ if (buttonNode.contains(event.target as HTMLElement)) {
341
+ const index = this._buttonNodes.indexOf(buttonNode);
342
+ this.resolve(index);
343
+ }
344
+ }
345
+ }
346
+
347
+ /**
348
+ * Handle the `'keydown'` event for the widget.
349
+ *
350
+ * @param event - The DOM event sent to the widget
351
+ */
352
+ protected _evtKeydown(event: KeyboardEvent): void {
353
+ // Check for escape key
354
+ switch (event.keyCode) {
355
+ case 27: // Escape.
356
+ event.stopPropagation();
357
+ event.preventDefault();
358
+ if (this._hasClose) {
359
+ this.reject();
360
+ }
361
+ break;
362
+ case 37: {
363
+ // Left arrow
364
+ const activeEl = document.activeElement;
365
+
366
+ if (activeEl instanceof HTMLButtonElement) {
367
+ let idx = this._buttonNodes.indexOf(activeEl as HTMLElement) - 1;
368
+
369
+ // Handle a left arrows on the first button
370
+ if (idx < 0) {
371
+ idx = this._buttonNodes.length - 1;
372
+ }
373
+
374
+ const node = this._buttonNodes[idx];
375
+ event.stopPropagation();
376
+ event.preventDefault();
377
+ node.focus();
378
+ }
379
+ break;
380
+ }
381
+ case 39: {
382
+ // Right arrow
383
+ const activeEl = document.activeElement;
384
+
385
+ if (activeEl instanceof HTMLButtonElement) {
386
+ let idx = this._buttonNodes.indexOf(activeEl as HTMLElement) + 1;
387
+
388
+ // Handle a right arrows on the last button
389
+ if (idx == this._buttons.length) {
390
+ idx = 0;
391
+ }
392
+
393
+ const node = this._buttonNodes[idx];
394
+ event.stopPropagation();
395
+ event.preventDefault();
396
+ node.focus();
397
+ }
398
+ break;
399
+ }
400
+ case 9: {
401
+ // Tab.
402
+ // Handle a tab on the last button.
403
+ const node = this._buttonNodes[this._buttons.length - 1];
404
+ if (document.activeElement === node && !event.shiftKey) {
405
+ event.stopPropagation();
406
+ event.preventDefault();
407
+ this._first.focus();
408
+ }
409
+ break;
410
+ }
411
+ case 13: {
412
+ // Enter.
413
+ event.stopPropagation();
414
+ event.preventDefault();
415
+
416
+ const activeEl = document.activeElement;
417
+ let index: number | undefined;
418
+
419
+ if (activeEl instanceof HTMLButtonElement) {
420
+ index = this._buttonNodes.indexOf(activeEl as HTMLElement);
421
+ }
422
+ this.resolve(index);
423
+ break;
424
+ }
425
+ default:
426
+ break;
427
+ }
428
+ }
429
+
430
+ /**
431
+ * Handle the `'focus'` event for the widget.
432
+ *
433
+ * @param event - The DOM event sent to the widget
434
+ */
435
+ protected _evtFocus(event: FocusEvent): void {
436
+ const target = event.target as HTMLElement;
437
+ if (!this.node.contains(target as HTMLElement)) {
438
+ event.stopPropagation();
439
+ this._buttonNodes[this._defaultButton]?.focus();
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Handle the `'mousedown'` event for the widget.
445
+ *
446
+ * @param event - The DOM event sent to the widget
447
+ */
448
+ protected _evtMouseDown(event: MouseEvent): void {
449
+ const content = this.node.getElementsByClassName(
450
+ 'jp-Dialog-content'
451
+ )[0] as HTMLElement;
452
+ const target = event.target as HTMLElement;
453
+ this._lastMouseDownInDialog = content.contains(target as HTMLElement);
454
+ }
455
+
456
+ /**
457
+ * Resolve a button item.
458
+ */
459
+ private _resolve(button: Dialog.IButton): void {
460
+ // Prevent loopback.
461
+ const promise = this._promise;
462
+ if (!promise) {
463
+ this.dispose();
464
+ return;
465
+ }
466
+ this._promise = null;
467
+ ArrayExt.removeFirstOf(Private.launchQueue, promise.promise);
468
+ const body = this._body;
469
+ let value: T | null = null;
470
+ if (
471
+ button.accept &&
472
+ body instanceof Widget &&
473
+ typeof body.getValue === 'function'
474
+ ) {
475
+ value = body.getValue();
476
+ }
477
+ this.dispose();
478
+ promise.resolve({
479
+ button,
480
+ isChecked:
481
+ this._checkboxNode?.querySelector<HTMLInputElement>('input')?.checked ??
482
+ null,
483
+ value
484
+ });
485
+ }
486
+
487
+ private _ready: PromiseDelegate<void> = new PromiseDelegate<void>();
488
+ private _buttonNodes: ReadonlyArray<HTMLElement>;
489
+ private _buttons: ReadonlyArray<Dialog.IButton>;
490
+ private _checkboxNode: HTMLElement | null;
491
+ private _original: HTMLElement;
492
+ private _first: HTMLElement;
493
+ private _primary: HTMLElement;
494
+ private _promise: PromiseDelegate<Dialog.IResult<T>> | null;
495
+ private _defaultButton: number;
496
+ private _host: HTMLElement;
497
+ private _hasClose: boolean;
498
+ private _body: Dialog.Body<T>;
499
+ private _lastMouseDownInDialog: boolean;
500
+ private _focusNodeSelector: string | undefined = '';
501
+ private _bodyWidget: Widget;
502
+ }
503
+
504
+ /**
505
+ * The namespace for Dialog class statics.
506
+ */
507
+ export namespace Dialog {
508
+ /**
509
+ * Translator object.
510
+ */
511
+ export let translator: ITranslator = nullTranslator;
512
+
513
+ /**
514
+ * The body input types.
515
+ */
516
+ export type Body<T> = IBodyWidget<T> | React.ReactElement<any> | string;
517
+
518
+ /**
519
+ * The header input types.
520
+ */
521
+ export type Header = React.ReactElement<any> | string;
522
+
523
+ /**
524
+ * A widget used as a dialog body.
525
+ */
526
+ export interface IBodyWidget<T = string> extends Widget {
527
+ /**
528
+ * Get the serialized value of the widget.
529
+ */
530
+ getValue?(): T;
531
+ }
532
+
533
+ /**
534
+ * The options used to make a button item.
535
+ */
536
+ export interface IButton {
537
+ /**
538
+ * The label for the button.
539
+ */
540
+ label: string;
541
+
542
+ /**
543
+ * The icon class for the button.
544
+ */
545
+ iconClass: string;
546
+
547
+ /**
548
+ * The icon label for the button.
549
+ */
550
+ iconLabel: string;
551
+
552
+ /**
553
+ * The caption for the button.
554
+ */
555
+ caption: string;
556
+
557
+ /**
558
+ * The extra class name for the button.
559
+ */
560
+ className: string;
561
+
562
+ /**
563
+ * The dialog action to perform when the button is clicked.
564
+ */
565
+ accept: boolean;
566
+
567
+ /**
568
+ * The additional dialog actions to perform when the button is clicked.
569
+ */
570
+ actions: Array<string>;
571
+
572
+ /**
573
+ * The button display type.
574
+ */
575
+ displayType: 'default' | 'warn';
576
+ }
577
+
578
+ /**
579
+ * The options used to make a checkbox item.
580
+ */
581
+ export interface ICheckbox {
582
+ /**
583
+ * The label for the checkbox.
584
+ */
585
+ label: string;
586
+
587
+ /**
588
+ * The caption for the checkbox.
589
+ */
590
+ caption: string;
591
+
592
+ /**
593
+ * The initial checkbox state.
594
+ */
595
+ checked: boolean;
596
+
597
+ /**
598
+ * The extra class name for the checkbox.
599
+ */
600
+ className: string;
601
+ }
602
+
603
+ /**
604
+ * Error object interface
605
+ */
606
+ export interface IError {
607
+ /**
608
+ * Error message
609
+ */
610
+ message: string | React.ReactElement<any>;
611
+ }
612
+
613
+ /**
614
+ * The options used to create a dialog.
615
+ */
616
+ export interface IOptions<T> {
617
+ /**
618
+ * The top level text for the dialog. Defaults to an empty string.
619
+ */
620
+ title: Header;
621
+
622
+ /**
623
+ * The main body element for the dialog or a message to display.
624
+ * Defaults to an empty string.
625
+ *
626
+ * #### Notes
627
+ * If a widget is given as the body, it will be disposed after the
628
+ * dialog is resolved. If the widget has a `getValue()` method,
629
+ * the method will be called prior to disposal and the value
630
+ * will be provided as part of the dialog result.
631
+ * A string argument will be used as raw `textContent`.
632
+ * All `input` and `select` nodes will be wrapped and styled.
633
+ */
634
+ body: Body<T>;
635
+
636
+ /**
637
+ * The host element for the dialog. Defaults to `document.body`.
638
+ */
639
+ host: HTMLElement;
640
+
641
+ /**
642
+ * The buttons to display. Defaults to cancel and accept buttons.
643
+ */
644
+ buttons: ReadonlyArray<IButton>;
645
+
646
+ /**
647
+ * The checkbox to display in the footer. Defaults no checkbox.
648
+ */
649
+ checkbox: Partial<ICheckbox> | null;
650
+
651
+ /**
652
+ * The index of the default button. Defaults to the last button.
653
+ */
654
+ defaultButton: number;
655
+
656
+ /**
657
+ * A selector for the primary element that should take focus in the dialog.
658
+ * Defaults to an empty string, causing the [[defaultButton]] to take
659
+ * focus.
660
+ */
661
+ focusNodeSelector: string;
662
+
663
+ /**
664
+ * When "false", disallows user from dismissing the dialog by clicking outside it
665
+ * or pressing escape. Defaults to "true", which renders a close button.
666
+ */
667
+ hasClose: boolean;
668
+
669
+ /**
670
+ * An optional renderer for dialog items. Defaults to a shared
671
+ * default renderer.
672
+ */
673
+ renderer: IRenderer;
674
+ }
675
+
676
+ /**
677
+ * A dialog renderer.
678
+ */
679
+ export interface IRenderer {
680
+ /**
681
+ * Create the header of the dialog.
682
+ *
683
+ * @param title - The title of the dialog.
684
+ *
685
+ * @returns A widget for the dialog header.
686
+ */
687
+ createHeader<T>(
688
+ title: Header,
689
+ reject: () => void,
690
+ options: Partial<Dialog.IOptions<T>>
691
+ ): Widget;
692
+
693
+ /**
694
+ * Create the body of the dialog.
695
+ *
696
+ * @param body - The input value for the body.
697
+ *
698
+ * @returns A widget for the body.
699
+ */
700
+ createBody(body: Body<any>): Widget;
701
+
702
+ /**
703
+ * Create the footer of the dialog.
704
+ *
705
+ * @param buttons - The button nodes to add to the footer.
706
+ * @param checkbox - The checkbox node to add to the footer.
707
+ *
708
+ * @returns A widget for the footer.
709
+ */
710
+ createFooter(
711
+ buttons: ReadonlyArray<HTMLElement>,
712
+ checkbox: HTMLElement | null
713
+ ): Widget;
714
+
715
+ /**
716
+ * Create a button node for the dialog.
717
+ *
718
+ * @param button - The button data.
719
+ *
720
+ * @returns A node for the button.
721
+ */
722
+ createButtonNode(button: IButton): HTMLElement;
723
+
724
+ /**
725
+ * Create a checkbox node for the dialog.
726
+ *
727
+ * @param checkbox - The checkbox data.
728
+ *
729
+ * @returns A node for the checkbox.
730
+ */
731
+ createCheckboxNode(checkbox: ICheckbox): HTMLElement;
732
+ }
733
+
734
+ /**
735
+ * The result of a dialog.
736
+ */
737
+ export interface IResult<T> {
738
+ /**
739
+ * The button that was pressed.
740
+ */
741
+ button: IButton;
742
+
743
+ /**
744
+ * State of the dialog checkbox.
745
+ *
746
+ * #### Notes
747
+ * It will be null if no checkbox is defined for the dialog.
748
+ */
749
+ isChecked: boolean | null;
750
+
751
+ /**
752
+ * The value retrieved from `.getValue()` if given on the widget.
753
+ */
754
+ value: T | null;
755
+ }
756
+
757
+ /**
758
+ * Create a button item.
759
+ */
760
+ export function createButton(value: Partial<IButton>): Readonly<IButton> {
761
+ value.accept = value.accept !== false;
762
+ const trans = translator.load('jupyterlab');
763
+ const defaultLabel = value.accept ? trans.__('Ok') : trans.__('Cancel');
764
+ return {
765
+ label: value.label || defaultLabel,
766
+ iconClass: value.iconClass || '',
767
+ iconLabel: value.iconLabel || '',
768
+ caption: value.caption || '',
769
+ className: value.className || '',
770
+ accept: value.accept,
771
+ actions: value.actions || [],
772
+ displayType: value.displayType || 'default'
773
+ };
774
+ }
775
+
776
+ /**
777
+ * Create a reject button.
778
+ */
779
+ export function cancelButton(
780
+ options: Partial<IButton> = {}
781
+ ): Readonly<IButton> {
782
+ options.accept = false;
783
+ return createButton(options);
784
+ }
785
+
786
+ /**
787
+ * Create an accept button.
788
+ */
789
+ export function okButton(options: Partial<IButton> = {}): Readonly<IButton> {
790
+ options.accept = true;
791
+ return createButton(options);
792
+ }
793
+
794
+ /**
795
+ * Create a warn button.
796
+ */
797
+ export function warnButton(
798
+ options: Partial<IButton> = {}
799
+ ): Readonly<IButton> {
800
+ options.displayType = 'warn';
801
+ return createButton(options);
802
+ }
803
+
804
+ /**
805
+ * Disposes all dialog instances.
806
+ *
807
+ * #### Notes
808
+ * This function should only be used in tests or cases where application state
809
+ * may be discarded.
810
+ */
811
+ export function flush(): void {
812
+ tracker.forEach(dialog => {
813
+ dialog.dispose();
814
+ });
815
+ }
816
+
817
+ /**
818
+ * The default implementation of a dialog renderer.
819
+ */
820
+ export class Renderer {
821
+ /**
822
+ * Create the header of the dialog.
823
+ *
824
+ * @param title - The title of the dialog.
825
+ *
826
+ * @returns A widget for the dialog header.
827
+ */
828
+ createHeader<T>(
829
+ title: Header,
830
+ reject: () => void = () => {
831
+ /* empty */
832
+ },
833
+ options: Partial<Dialog.IOptions<T>> = {}
834
+ ): Widget {
835
+ let header: Widget;
836
+
837
+ const handleMouseDown = (event: React.MouseEvent) => {
838
+ // Fire action only when left button is pressed.
839
+ if (event.button === 0) {
840
+ event.preventDefault();
841
+ reject();
842
+ }
843
+ };
844
+
845
+ const handleKeyDown = (event: React.KeyboardEvent) => {
846
+ const { key } = event;
847
+ if (key === 'Enter' || key === ' ') {
848
+ reject();
849
+ }
850
+ };
851
+
852
+ if (typeof title === 'string') {
853
+ const trans = translator.load('jupyterlab');
854
+ header = ReactWidget.create(
855
+ <>
856
+ {title}
857
+ {options.hasClose && (
858
+ <Button
859
+ className="jp-Dialog-close-button"
860
+ onMouseDown={handleMouseDown}
861
+ onKeyDown={handleKeyDown}
862
+ title={trans.__('Cancel')}
863
+ minimal
864
+ >
865
+ <LabIcon.resolveReact
866
+ icon={closeIcon}
867
+ iconClass="jp-Icon"
868
+ className="jp-ToolbarButtonComponent-icon"
869
+ tag="span"
870
+ />
871
+ </Button>
872
+ )}
873
+ </>
874
+ );
875
+ } else {
876
+ header = ReactWidget.create(title);
877
+ }
878
+ header.addClass('jp-Dialog-header');
879
+ Styling.styleNode(header.node);
880
+ return header;
881
+ }
882
+
883
+ /**
884
+ * Create the body of the dialog.
885
+ *
886
+ * @param value - The input value for the body.
887
+ *
888
+ * @returns A widget for the body.
889
+ */
890
+ createBody(value: Body<any>): Widget {
891
+ const styleReactWidget = (widget: ReactWidget) => {
892
+ if (widget.renderPromise !== undefined) {
893
+ widget.renderPromise
894
+ .then(() => {
895
+ Styling.styleNode(widget.node);
896
+ })
897
+ .catch(() => {
898
+ console.error("Error while loading Dialog's body");
899
+ });
900
+ } else {
901
+ Styling.styleNode(widget.node);
902
+ }
903
+ };
904
+
905
+ let body: Widget;
906
+ if (typeof value === 'string') {
907
+ body = new Widget({ node: document.createElement('span') });
908
+ body.node.textContent = value;
909
+ } else if (value instanceof Widget) {
910
+ body = value;
911
+ if (body instanceof ReactWidget) {
912
+ styleReactWidget(body);
913
+ } else {
914
+ Styling.styleNode(body.node);
915
+ }
916
+ } else {
917
+ body = ReactWidget.create(value);
918
+ // Immediately update the body even though it has not yet attached in
919
+ // order to trigger a render of the DOM nodes from the React element.
920
+ MessageLoop.sendMessage(body, Widget.Msg.UpdateRequest);
921
+ styleReactWidget(body as ReactWidget);
922
+ }
923
+ body.addClass('jp-Dialog-body');
924
+ return body;
925
+ }
926
+
927
+ /**
928
+ * Create the footer of the dialog.
929
+ *
930
+ * @param buttons - The buttons nodes to add to the footer.
931
+ * @param checkbox - The checkbox node to add to the footer.
932
+ *
933
+ * @returns A widget for the footer.
934
+ */
935
+ createFooter(
936
+ buttons: ReadonlyArray<HTMLElement>,
937
+ checkbox: HTMLElement | null
938
+ ): Widget {
939
+ const footer = new Widget();
940
+
941
+ footer.addClass('jp-Dialog-footer');
942
+ if (checkbox) {
943
+ footer.node.appendChild(checkbox);
944
+ footer.node.insertAdjacentHTML(
945
+ 'beforeend',
946
+ '<div class="jp-Dialog-spacer"></div>'
947
+ );
948
+ }
949
+ for (const button of buttons) {
950
+ footer.node.appendChild(button);
951
+ }
952
+ Styling.styleNode(footer.node);
953
+
954
+ return footer;
955
+ }
956
+
957
+ /**
958
+ * Create a button node for the dialog.
959
+ *
960
+ * @param button - The button data.
961
+ *
962
+ * @returns A node for the button.
963
+ */
964
+ createButtonNode(button: IButton): HTMLElement {
965
+ const e = document.createElement('button');
966
+ e.className = this.createItemClass(button);
967
+ e.appendChild(this.renderIcon(button));
968
+ e.appendChild(this.renderLabel(button));
969
+ return e;
970
+ }
971
+
972
+ /**
973
+ * Create a checkbox node for the dialog.
974
+ *
975
+ * @param checkbox - The checkbox data.
976
+ *
977
+ * @returns A node for the checkbox.
978
+ */
979
+ createCheckboxNode(checkbox: ICheckbox): HTMLElement {
980
+ const e = document.createElement('label');
981
+ e.className = 'jp-Dialog-checkbox';
982
+ if (checkbox.className) {
983
+ e.classList.add(checkbox.className);
984
+ }
985
+ e.title = checkbox.caption;
986
+ e.textContent = checkbox.label;
987
+ const input = document.createElement('input') as HTMLInputElement;
988
+ input.type = 'checkbox';
989
+ input.checked = !!checkbox.checked;
990
+ e.insertAdjacentElement('afterbegin', input);
991
+ return e;
992
+ }
993
+
994
+ /**
995
+ * Create the class name for the button.
996
+ *
997
+ * @param data - The data to use for the class name.
998
+ *
999
+ * @returns The full class name for the button.
1000
+ */
1001
+ createItemClass(data: IButton): string {
1002
+ // Setup the initial class name.
1003
+ let name = 'jp-Dialog-button';
1004
+
1005
+ // Add the other state classes.
1006
+ if (data.accept) {
1007
+ name += ' jp-mod-accept';
1008
+ } else {
1009
+ name += ' jp-mod-reject';
1010
+ }
1011
+ if (data.displayType === 'warn') {
1012
+ name += ' jp-mod-warn';
1013
+ }
1014
+
1015
+ // Add the extra class.
1016
+ const extra = data.className;
1017
+ if (extra) {
1018
+ name += ` ${extra}`;
1019
+ }
1020
+
1021
+ // Return the complete class name.
1022
+ return name;
1023
+ }
1024
+
1025
+ /**
1026
+ * Render an icon element for a dialog item.
1027
+ *
1028
+ * @param data - The data to use for rendering the icon.
1029
+ *
1030
+ * @returns An HTML element representing the icon.
1031
+ */
1032
+ renderIcon(data: IButton): HTMLElement {
1033
+ const e = document.createElement('div');
1034
+ e.className = this.createIconClass(data);
1035
+ e.appendChild(document.createTextNode(data.iconLabel));
1036
+ return e;
1037
+ }
1038
+
1039
+ /**
1040
+ * Create the class name for the button icon.
1041
+ *
1042
+ * @param data - The data to use for the class name.
1043
+ *
1044
+ * @returns The full class name for the item icon.
1045
+ */
1046
+ createIconClass(data: IButton): string {
1047
+ const name = 'jp-Dialog-buttonIcon';
1048
+ const extra = data.iconClass;
1049
+ return extra ? `${name} ${extra}` : name;
1050
+ }
1051
+
1052
+ /**
1053
+ * Render the label element for a button.
1054
+ *
1055
+ * @param data - The data to use for rendering the label.
1056
+ *
1057
+ * @returns An HTML element representing the item label.
1058
+ */
1059
+ renderLabel(data: IButton): HTMLElement {
1060
+ const e = document.createElement('div');
1061
+ e.className = 'jp-Dialog-buttonLabel';
1062
+ e.title = data.caption;
1063
+ e.appendChild(document.createTextNode(data.label));
1064
+ return e;
1065
+ }
1066
+ }
1067
+
1068
+ /**
1069
+ * The default renderer instance.
1070
+ */
1071
+ export const defaultRenderer = new Renderer();
1072
+
1073
+ /**
1074
+ * The dialog widget tracker.
1075
+ */
1076
+ export const tracker = new WidgetTracker<Dialog<any>>({
1077
+ namespace: '@jupyterlab/apputils:Dialog'
1078
+ });
1079
+ }
1080
+
1081
+ /**
1082
+ * The namespace for module private data.
1083
+ */
1084
+ namespace Private {
1085
+ /**
1086
+ * The queue for launching dialogs.
1087
+ */
1088
+ export const launchQueue: Promise<Dialog.IResult<any>>[] = [];
1089
+
1090
+ export const errorMessagePromiseCache: Map<string, Promise<void>> = new Map();
1091
+
1092
+ /**
1093
+ * Handle the input options for a dialog.
1094
+ *
1095
+ * @param options - The input options.
1096
+ *
1097
+ * @returns A new options object with defaults applied.
1098
+ */
1099
+ export function handleOptions<T>(
1100
+ options: Partial<Dialog.IOptions<T>> = {}
1101
+ ): Dialog.IOptions<T> {
1102
+ const buttons = options.buttons ?? [
1103
+ Dialog.cancelButton(),
1104
+ Dialog.okButton()
1105
+ ];
1106
+ return {
1107
+ title: options.title ?? '',
1108
+ body: options.body ?? '',
1109
+ host: options.host ?? document.body,
1110
+ checkbox: options.checkbox ?? null,
1111
+ buttons,
1112
+ defaultButton: options.defaultButton ?? buttons.length - 1,
1113
+ renderer: options.renderer ?? Dialog.defaultRenderer,
1114
+ focusNodeSelector: options.focusNodeSelector ?? '',
1115
+ hasClose: options.hasClose ?? true
1116
+ };
1117
+ }
1118
+
1119
+ /**
1120
+ * Find the first focusable item in the dialog.
1121
+ */
1122
+ export function findFirstFocusable(node: HTMLElement): HTMLElement {
1123
+ const candidateSelectors = [
1124
+ 'input',
1125
+ 'select',
1126
+ 'a[href]',
1127
+ 'textarea',
1128
+ 'button',
1129
+ '[tabindex]'
1130
+ ].join(',');
1131
+ return node.querySelectorAll(candidateSelectors)[0] as HTMLElement;
1132
+ }
1133
+ }