-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathtoolbar.tsx
1386 lines (1267 loc) · 37.4 KB
/
toolbar.tsx
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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { Button } from '@jupyter/react-components';
import {
addJupyterLabThemeChangeListener,
jpButton,
jpToolbar,
provideJupyterDesignSystem
} from '@jupyter/web-components';
import { ITranslator, nullTranslator } from '@jupyterlab/translation';
import { find, map, some } from '@lumino/algorithm';
import { CommandRegistry } from '@lumino/commands';
import { ReadonlyJSONObject } from '@lumino/coreutils';
import { Message, MessageLoop } from '@lumino/messaging';
import { AttachedProperty } from '@lumino/properties';
import { Layout, PanelLayout, Widget } from '@lumino/widgets';
import { Throttler } from '@lumino/polling';
import * as React from 'react';
import { ellipsesIcon, LabIcon } from '../icon';
import { classes } from '../utils';
import { ReactWidget, UseSignal } from './vdom';
provideJupyterDesignSystem().register([jpButton(), jpToolbar()]);
addJupyterLabThemeChangeListener();
/**
* The class name added to toolbars.
*/
const TOOLBAR_CLASS = 'jp-Toolbar';
/**
* The class name added to toolbar items.
*/
const TOOLBAR_ITEM_CLASS = 'jp-Toolbar-item';
/**
* Toolbar pop-up opener button name
*/
const TOOLBAR_OPENER_NAME = 'toolbar-popup-opener';
/**
* The class name added to toolbar spacer.
*/
const TOOLBAR_SPACER_CLASS = 'jp-Toolbar-spacer';
/**
* A layout for toolbars.
*
* #### Notes
* This layout automatically collapses its height if there are no visible
* toolbar widgets, and expands to the standard toolbar height if there are
* visible toolbar widgets.
*/
class ToolbarLayout extends PanelLayout {
/**
* A message handler invoked on a `'fit-request'` message.
*
* If any child widget is visible, expand the toolbar height to the normal
* toolbar height.
*/
protected onFitRequest(msg: Message): void {
super.onFitRequest(msg);
if (this.parent!.isAttached) {
// If there are any widgets not explicitly hidden, expand the toolbar to
// accommodate them.
if (some(this.widgets, w => !w.isHidden)) {
this.parent!.node.style.minHeight = 'var(--jp-private-toolbar-height)';
this.parent!.removeClass('jp-Toolbar-micro');
} else {
this.parent!.node.style.minHeight = '';
this.parent!.addClass('jp-Toolbar-micro');
}
}
// Set the dirty flag to ensure only a single update occurs.
this._dirty = true;
// Notify the ancestor that it should fit immediately. This may
// cause a resize of the parent, fulfilling the required update.
if (this.parent!.parent) {
MessageLoop.sendMessage(this.parent!.parent!, Widget.Msg.FitRequest);
}
// If the dirty flag is still set, the parent was not resized.
// Trigger the required update on the parent widget immediately.
if (this._dirty) {
MessageLoop.sendMessage(this.parent!, Widget.Msg.UpdateRequest);
}
}
/**
* A message handler invoked on an `'update-request'` message.
*/
protected onUpdateRequest(msg: Message): void {
super.onUpdateRequest(msg);
if (this.parent!.isVisible) {
this._dirty = false;
}
}
/**
* A message handler invoked on a `'child-shown'` message.
*/
protected onChildShown(msg: Widget.ChildMessage): void {
super.onChildShown(msg);
// Post a fit request for the parent widget.
this.parent!.fit();
}
/**
* A message handler invoked on a `'child-hidden'` message.
*/
protected onChildHidden(msg: Widget.ChildMessage): void {
super.onChildHidden(msg);
// Post a fit request for the parent widget.
this.parent!.fit();
}
/**
* A message handler invoked on a `'before-attach'` message.
*/
protected onBeforeAttach(msg: Message): void {
super.onBeforeAttach(msg);
// Post a fit request for the parent widget.
this.parent!.fit();
}
/**
* Attach a widget to the parent's DOM node.
*
* @param index - The current index of the widget in the layout.
*
* @param widget - The widget to attach to the parent.
*
* #### Notes
* This is a reimplementation of the superclass method.
*/
protected attachWidget(index: number, widget: Widget): void {
super.attachWidget(index, widget);
// Post a fit request for the parent widget.
this.parent!.fit();
}
/**
* Detach a widget from the parent's DOM node.
*
* @param index - The previous index of the widget in the layout.
*
* @param widget - The widget to detach from the parent.
*
* #### Notes
* This is a reimplementation of the superclass method.
*/
protected detachWidget(index: number, widget: Widget): void {
super.detachWidget(index, widget);
// Post a fit request for the parent widget.
this.parent!.fit();
}
private _dirty = false;
}
/**
* A class which provides a toolbar widget.
*/
export class Toolbar<T extends Widget = Widget> extends Widget {
/**
* Construct a new toolbar widget.
*/
constructor(options: Toolbar.IOptions = {}) {
super({ node: document.createElement('jp-toolbar') });
this.addClass(TOOLBAR_CLASS);
this.layout = options.layout ?? new ToolbarLayout();
this.noFocusOnClick = options.noFocusOnClick ?? false;
}
/**
* Get an iterator over the ordered toolbar item names.
*
* @returns An iterator over the toolbar item names.
*/
names(): IterableIterator<string> {
const layout = this.layout as ToolbarLayout;
return map(layout.widgets, widget => {
return Private.nameProperty.get(widget);
});
}
/**
* Add an item to the end of the toolbar.
*
* @param name - The name of the widget to add to the toolbar.
*
* @param widget - The widget to add to the toolbar.
*
* @returns Whether the item was added to toolbar. Returns false if
* an item of the same name is already in the toolbar.
*
* #### Notes
* The item can be removed from the toolbar by setting its parent to `null`.
*/
addItem(name: string, widget: T): boolean {
const layout = this.layout as ToolbarLayout;
return this.insertItem(layout.widgets.length, name, widget);
}
/**
* Insert an item into the toolbar at the specified index.
*
* @param index - The index at which to insert the item.
*
* @param name - The name of the item.
*
* @param widget - The widget to add.
*
* @returns Whether the item was added to the toolbar. Returns false if
* an item of the same name is already in the toolbar.
*
* #### Notes
* The index will be clamped to the bounds of the items.
* The item can be removed from the toolbar by setting its parent to `null`.
*/
insertItem(index: number, name: string, widget: T): boolean {
const existing = find(this.names(), value => value === name);
if (existing) {
return false;
}
widget.addClass(TOOLBAR_ITEM_CLASS);
const layout = this.layout as ToolbarLayout;
const j = Math.max(0, Math.min(index, layout.widgets.length));
layout.insertWidget(j, widget);
Private.nameProperty.set(widget, name);
widget.node.dataset['jpItemName'] = name;
if (this.noFocusOnClick) {
widget.node.dataset['noFocusOnClick'] = 'true';
}
return true;
}
/**
* Insert an item into the toolbar at the after a target item.
*
* @param at - The target item to insert after.
*
* @param name - The name of the item.
*
* @param widget - The widget to add.
*
* @returns Whether the item was added to the toolbar. Returns false if
* an item of the same name is already in the toolbar.
*
* #### Notes
* The index will be clamped to the bounds of the items.
* The item can be removed from the toolbar by setting its parent to `null`.
*/
insertAfter(at: string, name: string, widget: T): boolean {
return this.insertRelative(at, 1, name, widget);
}
/**
* Insert an item into the toolbar at the before a target item.
*
* @param at - The target item to insert before.
*
* @param name - The name of the item.
*
* @param widget - The widget to add.
*
* @returns Whether the item was added to the toolbar. Returns false if
* an item of the same name is already in the toolbar.
*
* #### Notes
* The index will be clamped to the bounds of the items.
* The item can be removed from the toolbar by setting its parent to `null`.
*/
insertBefore(at: string, name: string, widget: T): boolean {
return this.insertRelative(at, 0, name, widget);
}
/**
* Insert an item relatively to an other item.
*/
protected insertRelative(
at: string,
offset: number,
name: string,
widget: T
): boolean {
const nameWithIndex = map(this.names(), (name, i) => {
return { name: name, index: i };
});
const target = find(nameWithIndex, x => x.name === at);
if (target) {
return this.insertItem(target.index + offset, name, widget);
}
return false;
}
/**
* Handle the DOM events for the widget.
*
* @param event - The DOM event sent to the widget.
*
* #### Notes
* This method implements the DOM `EventListener` interface and is
* called in response to events on the dock panel's node. It should
* not be called directly by user code.
*/
handleEvent(event: Event): void {
switch (event.type) {
case 'click':
this.handleClick(event);
break;
default:
break;
}
}
/**
* Handle a DOM click event.
*/
protected handleClick(event: Event): void {
// Stop propagating the click outside the toolbar
event.stopPropagation();
// Clicking a label focuses the corresponding control
// that is linked with `for` attribute, so let it be.
if (event.target instanceof HTMLLabelElement) {
const forId = event.target.getAttribute('for');
if (forId && this.node.querySelector(`#${forId}`)) {
return;
}
}
// If this click already focused a control, let it be.
if (this.node.contains(document.activeElement)) {
return;
}
// Otherwise, activate the parent widget, which may take focus if desired.
if (this.parent) {
this.parent.activate();
}
}
/**
* Handle `after-attach` messages for the widget.
*/
protected onAfterAttach(msg: Message): void {
this.node.addEventListener('click', this);
}
/**
* Handle `before-detach` messages for the widget.
*/
protected onBeforeDetach(msg: Message): void {
this.node.removeEventListener('click', this);
}
noFocusOnClick: boolean;
}
/**
* A class which provides a toolbar widget.
*/
export class ReactiveToolbar extends Toolbar<Widget> {
/**
* Construct a new toolbar widget.
*/
constructor(options: Toolbar.IOptions = {}) {
super(options);
this.insertItem(0, TOOLBAR_OPENER_NAME, this.popupOpener);
this.popupOpener.hide();
this._resizer = new Throttler(async (callTwice = false) => {
await this._onResize(callTwice);
}, 500);
}
/**
* Dispose of the widget and its descendant widgets.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
if (this._resizer) {
this._resizer.dispose();
}
super.dispose();
}
/**
* Insert an item into the toolbar at the after a target item.
*
* @param at - The target item to insert after.
*
* @param name - The name of the item.
*
* @param widget - The widget to add.
*
* @returns Whether the item was added to the toolbar. Returns false if
* an item of the same name is already in the toolbar or if the target
* is the toolbar pop-up opener.
*
* #### Notes
* The index will be clamped to the bounds of the items.
* The item can be removed from the toolbar by setting its parent to `null`.
*/
insertAfter(at: string, name: string, widget: Widget): boolean {
if (at === TOOLBAR_OPENER_NAME) {
return false;
}
return super.insertAfter(at, name, widget);
}
/**
* Insert an item relatively to an other item.
*/
protected insertRelative(
at: string,
offset: number,
name: string,
widget: Widget
): boolean {
const targetPosition = this._widgetPositions.get(at);
const position = (targetPosition ?? 0) + offset;
return this.insertItem(position, name, widget);
}
/**
* Insert an item into the toolbar at the specified index.
*
* @param index - The index at which to insert the item.
*
* @param name - The name of the item.
*
* @param widget - The widget to add.
*
* @returns Whether the item was added to the toolbar. Returns false if
* an item of the same name is already in the toolbar.
*
* #### Notes
* The index will be clamped to the bounds of the items.
* The item can be removed from the toolbar by setting its parent to `null`.
*/
insertItem(index: number, name: string, widget: Widget): boolean {
let status: boolean;
if (widget instanceof ToolbarPopupOpener) {
status = super.insertItem(index, name, widget);
} else {
// Insert the widget in the toolbar at expected index if possible, otherwise
// before the popup opener. This position may change when invoking the resizer
// at the end of this function.
const j = Math.max(
0,
Math.min(index, (this.layout as ToolbarLayout).widgets.length - 1)
);
status = super.insertItem(j, name, widget);
if (j !== index) {
// This happens if the widget has been inserted at a wrong position:
// - not enough widgets in the toolbar to insert it at the expected index
// - the widget at the expected index should be in the popup
// In the first situation, the stored index should be changed to match a
// realistic index.
index = Math.max(0, Math.min(index, this._widgetPositions.size));
}
}
// Save the widgets position when a widget is inserted or moved.
if (
name !== TOOLBAR_OPENER_NAME &&
this._widgetPositions.get(name) !== index
) {
// If the widget is inserted, set its current position as last.
const currentPosition =
this._widgetPositions.get(name) ?? this._widgetPositions.size;
// Change the position of moved widgets.
this._widgetPositions.forEach((value, key) => {
if (key !== TOOLBAR_OPENER_NAME) {
if (value >= index && value < currentPosition) {
this._widgetPositions.set(key, value + 1);
} else if (value <= index && value > currentPosition) {
this._widgetPositions.set(key, value - 1);
}
}
});
// Save the new position of the widget.
this._widgetPositions.set(name, index);
// Invokes resizing to ensure correct display of items after an addition, only
// if the toolbar is rendered.
if (this.isVisible) {
void this._resizer.invoke();
}
}
return status;
}
/**
* A message handler invoked on an `'after-show'` message.
*
* Invokes resizing to ensure correct display of items.
*/
onAfterShow(msg: Message): void {
void this._resizer.invoke(true);
}
/**
* A message handler invoked on a `'before-hide'` message.
*
* It will hide the pop-up panel
*/
onBeforeHide(msg: Message): void {
this.popupOpener.hidePopup();
super.onBeforeHide(msg);
}
protected onResize(msg: Widget.ResizeMessage): void {
super.onResize(msg);
// Check if the resize event is due to a zoom change.
const zoom = Math.round((window.outerWidth / window.innerWidth) * 100);
if (zoom !== this._zoom) {
this._zoomChanged = true;
this._zoom = zoom;
}
if (msg.width > 0 && this._resizer) {
void this._resizer.invoke();
}
}
/**
* Move the toolbar items between the reactive toolbar and the popup toolbar,
* depending on the width of the toolbar and the width of each item.
*
* @param callTwice - whether to call the function twice.
*
* **NOTES**
* The `callTwice` parameter is useful when the toolbar is displayed the first time,
* because the size of the items is unknown before their first rendering. The first
* call will usually add all the items in the main toolbar, and the second call will
* reorganize the items between the main toolbar and the popup toolbar.
*/
private async _onResize(callTwice = false) {
if (!(this.parent && this.parent.isAttached)) {
return;
}
const toolbarWidth = this.node.clientWidth;
const opener = this.popupOpener;
const openerWidth = 32;
// left and right padding.
const toolbarPadding = 2 + 5;
let width = opener.isHidden ? toolbarPadding : toolbarPadding + openerWidth;
return this._getWidgetsToRemove(width, toolbarWidth, openerWidth)
.then(async values => {
let { width, widgetsToRemove } = values;
while (widgetsToRemove.length > 0) {
// Insert the widget at the right position in the opener popup, relatively
// to the saved position of the first item of the popup toolbar.
// Get the saved position of the widget to insert.
const widget = widgetsToRemove.pop() as Widget;
const name = Private.nameProperty.get(widget);
width -= this._widgetWidths.get(name) || 0;
const position = this._widgetPositions.get(name) ?? 0;
// Get the saved position of the first item in the popup toolbar.
// If there is no widget, set the value at last item.
let openerFirstIndex = this._widgetPositions.size;
const openerFirst = opener.widgetAt(0);
if (openerFirst) {
const openerFirstName = Private.nameProperty.get(openerFirst);
openerFirstIndex =
this._widgetPositions.get(openerFirstName) ?? openerFirstIndex;
}
// Insert the widget in the popup toolbar.
const index = position - openerFirstIndex;
opener.insertWidget(index, widget);
}
if (opener.widgetCount() > 0) {
const widgetsToAdd = [];
let index = 0;
const widgetCount = opener.widgetCount();
while (index < widgetCount) {
let widget = opener.widgetAt(index);
if (widget) {
width += this._getWidgetWidth(widget);
if (widgetCount - widgetsToAdd.length === 1) {
width -= openerWidth;
}
} else {
break;
}
if (width < toolbarWidth) {
widgetsToAdd.push(widget);
} else {
break;
}
index++;
}
while (widgetsToAdd.length > 0) {
// Insert the widget in the right position in the toolbar.
const widget = widgetsToAdd.shift()!;
const name = Private.nameProperty.get(widget);
if (this._widgetPositions.has(name)) {
this.insertItem(this._widgetPositions.get(name)!, name, widget);
} else {
this.addItem(name, widget);
}
}
}
if (opener.widgetCount() > 0) {
opener.updatePopup();
opener.show();
} else {
opener.hide();
}
if (callTwice) {
await this._onResize();
}
})
.catch(msg => {
console.error('Error while computing the ReactiveToolbar', msg);
});
}
private async _getWidgetsToRemove(
width: number,
toolbarWidth: number,
openerWidth: number
) {
const opener = this.popupOpener;
const widgets = [...(this.layout as ToolbarLayout).widgets];
const toIndex = widgets.length - 1;
const widgetsToRemove = [];
let index = 0;
while (index < toIndex) {
const widget = widgets[index];
const name = Private.nameProperty.get(widget);
// Compute the widget size only if
// - the zoom has changed.
// - the widget size has not been computed yet.
let widgetWidth: number;
if (this._zoomChanged) {
widgetWidth = await this._saveWidgetWidth(name, widget);
} else {
// The widget widths can be 0px if it has been added to the toolbar but
// not rendered, this is why we must use '||' instead of '??'.
widgetWidth =
this._getWidgetWidth(widget) ||
(await this._saveWidgetWidth(name, widget));
}
width += widgetWidth;
if (
widgetsToRemove.length === 0 &&
opener.isHidden &&
width + openerWidth > toolbarWidth
) {
width += openerWidth;
}
// Remove the widget if it is out of the toolbar or incorrectly positioned.
// Incorrect positioning can occur when the widget is added after the toolbar
// has been rendered and should be in the popup. E.g. debugger icon with a
// narrow notebook toolbar.
if (
width > toolbarWidth ||
(this._widgetPositions.get(name) ?? 0) > index
) {
widgetsToRemove.push(widget);
}
index++;
}
this._zoomChanged = false;
return {
width: width,
widgetsToRemove: widgetsToRemove
};
}
private async _saveWidgetWidth(
name: string,
widget: Widget
): Promise<number> {
if (widget instanceof ReactWidget) {
await widget.renderPromise;
}
const widgetWidth = widget.hasClass(TOOLBAR_SPACER_CLASS)
? 2
: widget.node.clientWidth;
this._widgetWidths.set(name, widgetWidth);
return widgetWidth;
}
private _getWidgetWidth(widget: Widget): number {
const widgetName = Private.nameProperty.get(widget);
return this._widgetWidths.get(widgetName) || 0;
}
protected readonly popupOpener: ToolbarPopupOpener = new ToolbarPopupOpener();
private readonly _resizer: Throttler;
private readonly _widgetWidths = new Map<string, number>();
private _widgetPositions = new Map<string, number>();
// The zoom property is not the real browser zoom, but a value proportional to
// the zoom, which is modified when the zoom changes.
private _zoom: number;
private _zoomChanged = true;
}
/**
* The namespace for Toolbar class statics.
*/
export namespace Toolbar {
/**
* The options used to create a toolbar.
*/
export interface IOptions {
/**
* Toolbar widget layout.
*/
layout?: Layout;
/**
* Do not give the focus to the button on click.
*/
noFocusOnClick?: boolean;
}
/**
* Widget with associated toolbar
*/
export interface IWidgetToolbar extends Widget {
/**
* Toolbar of actions on the widget
*/
toolbar?: Toolbar;
}
/**
* Create a toolbar spacer item.
*
* #### Notes
* It is a flex spacer that separates the left toolbar items
* from the right toolbar items.
*/
export function createSpacerItem(): Widget {
return new Private.Spacer();
}
}
/**
* Namespace for ToolbarButtonComponent.
*/
export namespace ToolbarButtonComponent {
/**
* Interface for ToolbarButtonComponent props.
*/
export interface IProps {
className?: string;
/**
* Data set of the button
*/
dataset?: DOMStringMap;
label?: string;
icon?: LabIcon.IMaybeResolvable;
iconClass?: string;
iconLabel?: string;
tooltip?: string;
onClick?: () => void;
enabled?: boolean;
pressed?: boolean;
pressedIcon?: LabIcon.IMaybeResolvable;
pressedTooltip?: string;
disabledTooltip?: string;
/**
* Trigger the button on onMouseDown event rather than onClick, to avoid giving
* the focus on the button.
*/
noFocusOnClick?: boolean;
/**
* The application language translator.
*/
translator?: ITranslator;
}
}
/**
* React component for a toolbar button.
*
* @param props - The props for ToolbarButtonComponent.
*/
export function ToolbarButtonComponent(
props: ToolbarButtonComponent.IProps
): JSX.Element {
// In some browsers, a button click event moves the focus from the main
// content to the button (see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus).
const handleClick =
props.noFocusOnClick ?? false
? undefined
: (event: React.MouseEvent) => {
if (event.button === 0) {
props.onClick?.();
// In safari, the focus do not move to the button on click (see
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus).
(event.target as HTMLElement).focus();
}
};
// To avoid focusing the button, we avoid a click event by calling preventDefault in
// mousedown, and we bind the button action to `mousedown`.
// Currently this is mostly useful for the notebook panel, to retrieve the focused
// cell before the click event.
const handleMouseDown =
props.noFocusOnClick ?? false
? (event: React.MouseEvent) => {
// Fire action only when left button is pressed.
if (event.button === 0) {
event.preventDefault();
props.onClick?.();
}
}
: undefined;
const handleKeyDown = (event: React.KeyboardEvent) => {
const { key } = event;
if (key === 'Enter' || key === ' ') {
props.onClick?.();
}
};
const getTooltip = () => {
if (props.enabled === false && props.disabledTooltip) {
return props.disabledTooltip;
} else if (props.pressed && props.pressedTooltip) {
return props.pressedTooltip;
} else {
return props.tooltip || props.iconLabel;
}
};
const title = getTooltip();
const disabled = props.enabled === false;
return (
<Button
appearance="stealth"
className={
props.className
? props.className + ' jp-ToolbarButtonComponent'
: 'jp-ToolbarButtonComponent'
}
aria-disabled={disabled}
aria-label={props.label || title}
aria-pressed={props.pressed}
{...props.dataset}
disabled={disabled}
onClick={handleClick}
onMouseDown={handleMouseDown}
onKeyDown={handleKeyDown}
title={title}
>
{(props.icon || props.iconClass) && (
<LabIcon.resolveReact
icon={props.pressed ? props.pressedIcon ?? props.icon : props.icon}
iconClass={
// add some extra classes for proper support of icons-as-css-background
classes(props.iconClass, 'jp-Icon')
}
tag={null}
/>
)}
{props.label && (
<span className="jp-ToolbarButtonComponent-label">{props.label}</span>
)}
</Button>
);
}
/**
* Adds the toolbar button class to the toolbar widget.
* @param w Toolbar button widget.
*/
export function addToolbarButtonClass<T extends Widget = Widget>(w: T): T {
w.addClass('jp-ToolbarButton');
return w;
}
/**
* Lumino Widget version of static ToolbarButtonComponent.
*/
export class ToolbarButton extends ReactWidget {
/**
* Creates a toolbar button
* @param props props for underlying `ToolbarButton` component
*/
constructor(private props: ToolbarButtonComponent.IProps = {}) {
super();
addToolbarButtonClass(this);
this._enabled = props.enabled ?? true;
this._pressed = this._enabled! && (props.pressed ?? false);
this._onClick = props.onClick!;
}
/**
* Sets the pressed state for the button
* @param value true if button is pressed, false otherwise
*/
set pressed(value: boolean) {
if (this.enabled && value !== this._pressed) {
this._pressed = value;
this.update();
}
}
/**
* Returns true if button is pressed, false otherwise
*/
get pressed(): boolean {
return this._pressed!;
}
/**
* Sets the enabled state for the button
* @param value true to enable the button, false otherwise
*/
set enabled(value: boolean) {
if (value != this._enabled) {
this._enabled = value;
if (!this._enabled) {
this._pressed = false;
}
this.update();
}
}
/**
* Returns true if button is enabled, false otherwise
*/
get enabled(): boolean {
return this._enabled;
}
/**
* Sets the click handler for the button
* @param value click handler
*/
set onClick(value: () => void) {
if (value !== this._onClick) {
this._onClick = value;
this.update();
}
}
/**
* Returns the click handler for the button
*/
get onClick(): () => void {
return this._onClick!;
}
render(): JSX.Element {
return (
<ToolbarButtonComponent
{...this.props}
noFocusOnClick={this.props.noFocusOnClick}
pressed={this.pressed}
enabled={this.enabled}
onClick={this.onClick}
/>
);
}
private _pressed: boolean;
private _enabled: boolean;
private _onClick: () => void;
}
/**
* Namespace for CommandToolbarButtonComponent.
*/
export namespace CommandToolbarButtonComponent {
/**