/
listing.ts
3050 lines (2770 loc) · 88.8 KB
/
listing.ts
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 {
Dialog,
DOMUtils,
showDialog,
showErrorMessage
} from '@jupyterlab/apputils';
import { PathExt, Time } from '@jupyterlab/coreutils';
import {
IDocumentManager,
isValidFileName,
renameFile
} from '@jupyterlab/docmanager';
import { DocumentRegistry } from '@jupyterlab/docregistry';
import { Contents } from '@jupyterlab/services';
import {
ITranslator,
nullTranslator,
TranslationBundle
} from '@jupyterlab/translation';
import {
caretDownIcon,
caretUpIcon,
classes,
LabIcon
} from '@jupyterlab/ui-components';
import { ArrayExt, filter, StringExt } from '@lumino/algorithm';
import { MimeData, PromiseDelegate } from '@lumino/coreutils';
import { ElementExt } from '@lumino/domutils';
import { Drag } from '@lumino/dragdrop';
import { Message, MessageLoop } from '@lumino/messaging';
import { ISignal, Signal } from '@lumino/signaling';
import { h, VirtualDOM } from '@lumino/virtualdom';
import { Widget } from '@lumino/widgets';
import { FilterFileBrowserModel } from './model';
/**
* The class name added to DirListing widget.
*/
const DIR_LISTING_CLASS = 'jp-DirListing';
/**
* The class name added to a dir listing header node.
*/
const HEADER_CLASS = 'jp-DirListing-header';
/**
* The class name added to a dir listing list header cell.
*/
const HEADER_ITEM_CLASS = 'jp-DirListing-headerItem';
/**
* The class name added to a header cell text node.
*/
const HEADER_ITEM_TEXT_CLASS = 'jp-DirListing-headerItemText';
/**
* The class name added to a header cell icon node.
*/
const HEADER_ITEM_ICON_CLASS = 'jp-DirListing-headerItemIcon';
/**
* The class name added to the dir listing content node.
*/
const CONTENT_CLASS = 'jp-DirListing-content';
/**
* The class name added to dir listing content item.
*/
const ITEM_CLASS = 'jp-DirListing-item';
/**
* The class name added to the listing item text cell.
*/
const ITEM_TEXT_CLASS = 'jp-DirListing-itemText';
/**
* The class name added to the listing item icon cell.
*/
const ITEM_ICON_CLASS = 'jp-DirListing-itemIcon';
/**
* The class name added to the listing item modified cell.
*/
const ITEM_MODIFIED_CLASS = 'jp-DirListing-itemModified';
/**
* The class name added to the listing item file size cell.
*/
const ITEM_FILE_SIZE_CLASS = 'jp-DirListing-itemFileSize';
/**
* The class name added to the label element that wraps each item's checkbox and
* the header's check-all checkbox.
*/
const CHECKBOX_WRAPPER_CLASS = 'jp-DirListing-checkboxWrapper';
/**
* The class name added to the dir listing editor node.
*/
const EDITOR_CLASS = 'jp-DirListing-editor';
/**
* The class name added to the name column header cell.
*/
const NAME_ID_CLASS = 'jp-id-name';
/**
* The class name added to the modified column header cell.
*/
const MODIFIED_ID_CLASS = 'jp-id-modified';
/**
* The class name added to the file size column header cell.
*/
const FILE_SIZE_ID_CLASS = 'jp-id-filesize';
/**
* The class name added to the narrow column header cell.
*/
const NARROW_ID_CLASS = 'jp-id-narrow';
/**
* The class name added to the modified column header cell and modified item cell when hidden.
*/
const MODIFIED_COLUMN_HIDDEN = 'jp-LastModified-hidden';
/**
* The class name added to the size column header cell and size item cell when hidden.
*/
const FILE_SIZE_COLUMN_HIDDEN = 'jp-FileSize-hidden';
/**
* The mime type for a contents drag object.
*/
const CONTENTS_MIME = 'application/x-jupyter-icontents';
/**
* The mime type for a rich contents drag object.
*/
const CONTENTS_MIME_RICH = 'application/x-jupyter-icontentsrich';
/**
* The class name added to drop targets.
*/
const DROP_TARGET_CLASS = 'jp-mod-dropTarget';
/**
* The class name added to selected rows.
*/
const SELECTED_CLASS = 'jp-mod-selected';
/**
* The class name added to drag state icons to add space between the icon and the file name
*/
const DRAG_ICON_CLASS = 'jp-DragIcon';
/**
* The class name added to the widget when there are items on the clipboard.
*/
const CLIPBOARD_CLASS = 'jp-mod-clipboard';
/**
* The class name added to cut rows.
*/
const CUT_CLASS = 'jp-mod-cut';
/**
* The class name added when there are more than one selected rows.
*/
const MULTI_SELECTED_CLASS = 'jp-mod-multiSelected';
/**
* The class name added to indicate running notebook.
*/
const RUNNING_CLASS = 'jp-mod-running';
/**
* The class name added for a descending sort.
*/
const DESCENDING_CLASS = 'jp-mod-descending';
/**
* The maximum duration between two key presses when selecting files by prefix.
*/
const PREFIX_APPEND_DURATION = 1000;
/**
* The threshold in pixels to start a drag event.
*/
const DRAG_THRESHOLD = 5;
/**
* A boolean indicating whether the platform is Mac.
*/
const IS_MAC = !!navigator.platform.match(/Mac/i);
/**
* The factory MIME type supported by lumino dock panels.
*/
const FACTORY_MIME = 'application/vnd.lumino.widget-factory';
/**
* A widget which hosts a file list area.
*/
export class DirListing extends Widget {
/**
* Construct a new file browser directory listing widget.
*
* @param options The constructor options
*/
constructor(options: DirListing.IOptions) {
super({
node: (options.renderer || DirListing.defaultRenderer).createNode()
});
this.addClass(DIR_LISTING_CLASS);
this.translator = options.translator || nullTranslator;
this._trans = this.translator.load('jupyterlab');
this._model = options.model;
this._model.fileChanged.connect(this._onFileChanged, this);
this._model.refreshed.connect(this._onModelRefreshed, this);
this._model.pathChanged.connect(this._onPathChanged, this);
this._editNode = document.createElement('input');
this._editNode.className = EDITOR_CLASS;
this._manager = this._model.manager;
this._renderer = options.renderer || DirListing.defaultRenderer;
// Get the width of the "modified" column
this._updateModifiedSize(this.node);
const headerNode = DOMUtils.findElement(this.node, HEADER_CLASS);
// hide the file size column by default
this._hiddenColumns.add('file_size');
this._renderer.populateHeaderNode(
headerNode,
this.translator,
this._hiddenColumns
);
this._manager.activateRequested.connect(this._onActivateRequested, this);
}
/**
* Dispose of the resources held by the directory listing.
*/
dispose(): void {
this._items.length = 0;
this._sortedItems.length = 0;
this._clipboard.length = 0;
super.dispose();
}
/**
* Get the model used by the listing.
*/
get model(): FilterFileBrowserModel {
return this._model;
}
/**
* Get the dir listing header node.
*
* #### Notes
* This is the node which holds the header cells.
*
* Modifying this node directly can lead to undefined behavior.
*/
get headerNode(): HTMLElement {
return DOMUtils.findElement(this.node, HEADER_CLASS);
}
/**
* Get the dir listing content node.
*
* #### Notes
* This is the node which holds the item nodes.
*
* Modifying this node directly can lead to undefined behavior.
*/
get contentNode(): HTMLElement {
return DOMUtils.findElement(this.node, CONTENT_CLASS);
}
/**
* The renderer instance used by the directory listing.
*/
get renderer(): DirListing.IRenderer {
return this._renderer;
}
/**
* The current sort state.
*/
get sortState(): DirListing.ISortState {
return this._sortState;
}
/**
* A signal fired when an item is opened.
*/
get onItemOpened(): ISignal<DirListing, Contents.IModel> {
return this._onItemOpened;
}
/**
* Create an iterator over the listing's selected items.
*
* @returns A new iterator over the listing's selected items.
*/
selectedItems(): IterableIterator<Contents.IModel> {
const items = this._sortedItems;
return filter(items, item => this.selection[item.path]);
}
/**
* Create an iterator over the listing's sorted items.
*
* @returns A new iterator over the listing's sorted items.
*/
sortedItems(): IterableIterator<Contents.IModel> {
return this._sortedItems[Symbol.iterator]();
}
/**
* Sort the items using a sort condition.
*/
sort(state: DirListing.ISortState): void {
this._sortedItems = Private.sort(
this.model.items(),
state,
this._sortNotebooksFirst
);
this._sortState = state;
this.update();
}
/**
* Rename the first currently selected item.
*
* @returns A promise that resolves with the new name of the item.
*/
rename(): Promise<string> {
return this._doRename();
}
/**
* Cut the selected items.
*/
cut(): void {
this._isCut = true;
this._copy();
this.update();
}
/**
* Copy the selected items.
*/
copy(): void {
this._copy();
}
/**
* Paste the items from the clipboard.
*
* @returns A promise that resolves when the operation is complete.
*/
paste(): Promise<void> {
if (!this._clipboard.length) {
this._isCut = false;
return Promise.resolve(undefined);
}
const basePath = this._model.path;
const promises: Promise<Contents.IModel>[] = [];
for (const path of this._clipboard) {
if (this._isCut) {
const localPath = this._manager.services.contents.localPath(path);
const parts = localPath.split('/');
const name = parts[parts.length - 1];
const newPath = PathExt.join(basePath, name);
promises.push(this._model.manager.rename(path, newPath));
} else {
promises.push(this._model.manager.copy(path, basePath));
}
}
// Remove any cut modifiers.
for (const item of this._items) {
item.classList.remove(CUT_CLASS);
}
this._clipboard.length = 0;
this._isCut = false;
this.removeClass(CLIPBOARD_CLASS);
return Promise.all(promises)
.then(() => {
return undefined;
})
.catch(error => {
void showErrorMessage(
this._trans._p('showErrorMessage', 'Paste Error'),
error
);
});
}
/**
* Delete the currently selected item(s).
*
* @returns A promise that resolves when the operation is complete.
*/
async delete(): Promise<void> {
const items = this._sortedItems.filter(item => this.selection[item.path]);
if (!items.length) {
return;
}
const message =
items.length === 1
? this._trans.__(
'Are you sure you want to permanently delete: %1?',
items[0].name
)
: this._trans._n(
'Are you sure you want to permanently delete the %1 selected item?',
'Are you sure you want to permanently delete the %1 selected items?',
items.length
);
const result = await showDialog({
title: this._trans.__('Delete'),
body: message,
buttons: [
Dialog.cancelButton({ label: this._trans.__('Cancel') }),
Dialog.warnButton({ label: this._trans.__('Delete') })
],
// By default focus on "Cancel" to protect from accidental deletion
// ("delete" and "Enter" are next to each other on many keyboards).
defaultButton: 0
});
if (!this.isDisposed && result.button.accept) {
await this._delete(items.map(item => item.path));
}
// Re-focus
let focusIndex = this._focusIndex;
const lastIndexAfterDelete = this._sortedItems.length - items.length - 1;
if (focusIndex > lastIndexAfterDelete) {
// If the focus index after deleting items is out of bounds, set it to the
// last item.
focusIndex = Math.max(0, lastIndexAfterDelete);
}
this._focusItem(focusIndex);
}
/**
* Duplicate the currently selected item(s).
*
* @returns A promise that resolves when the operation is complete.
*/
duplicate(): Promise<void> {
const basePath = this._model.path;
const promises: Promise<Contents.IModel>[] = [];
for (const item of this.selectedItems()) {
if (item.type !== 'directory') {
promises.push(this._model.manager.copy(item.path, basePath));
}
}
return Promise.all(promises)
.then(() => {
return undefined;
})
.catch(error => {
void showErrorMessage(
this._trans._p('showErrorMessage', 'Duplicate file'),
error
);
});
}
/**
* Download the currently selected item(s).
*/
async download(): Promise<void> {
await Promise.all(
Array.from(this.selectedItems())
.filter(item => item.type !== 'directory')
.map(item => this._model.download(item.path))
);
}
/**
* Shut down kernels on the applicable currently selected items.
*
* @returns A promise that resolves when the operation is complete.
*/
shutdownKernels(): Promise<void> {
const model = this._model;
const items = this._sortedItems;
const paths = items.map(item => item.path);
const promises = Array.from(this._model.sessions())
.filter(session => {
const index = ArrayExt.firstIndexOf(paths, session.path);
return this.selection[items[index].path];
})
.map(session => model.manager.services.sessions.shutdown(session.id));
return Promise.all(promises)
.then(() => {
return undefined;
})
.catch(error => {
void showErrorMessage(
this._trans._p('showErrorMessage', 'Shut down kernel'),
error
);
});
}
/**
* Select next item.
*
* @param keepExisting - Whether to keep the current selection and add to it.
*/
selectNext(keepExisting = false): void {
let index = -1;
const selected = Object.keys(this.selection);
const items = this._sortedItems;
if (selected.length === 1 || keepExisting) {
// Select the next item.
const path = selected[selected.length - 1];
index = ArrayExt.findFirstIndex(items, value => value.path === path);
index += 1;
if (index === this._items.length) {
index = 0;
}
} else if (selected.length === 0) {
// Select the first item.
index = 0;
} else {
// Select the last selected item.
const path = selected[selected.length - 1];
index = ArrayExt.findFirstIndex(items, value => value.path === path);
}
if (index !== -1) {
this._selectItem(index, keepExisting);
ElementExt.scrollIntoViewIfNeeded(this.contentNode, this._items[index]);
}
}
/**
* Select previous item.
*
* @param keepExisting - Whether to keep the current selection and add to it.
*/
selectPrevious(keepExisting = false): void {
let index = -1;
const selected = Object.keys(this.selection);
const items = this._sortedItems;
if (selected.length === 1 || keepExisting) {
// Select the previous item.
const path = selected[0];
index = ArrayExt.findFirstIndex(items, value => value.path === path);
index -= 1;
if (index === -1) {
index = this._items.length - 1;
}
} else if (selected.length === 0) {
// Select the last item.
index = this._items.length - 1;
} else {
// Select the first selected item.
const path = selected[0];
index = ArrayExt.findFirstIndex(items, value => value.path === path);
}
if (index !== -1) {
this._selectItem(index, keepExisting);
ElementExt.scrollIntoViewIfNeeded(this.contentNode, this._items[index]);
}
}
/**
* Select the first item that starts with prefix being typed.
*/
selectByPrefix(): void {
const prefix = this._searchPrefix.toLowerCase();
const items = this._sortedItems;
const index = ArrayExt.findFirstIndex(items, value => {
return value.name.toLowerCase().substr(0, prefix.length) === prefix;
});
if (index !== -1) {
this._selectItem(index, false);
ElementExt.scrollIntoViewIfNeeded(this.contentNode, this._items[index]);
}
}
/**
* Get whether an item is selected by name.
*
* @param name - The name of of the item.
*
* @returns Whether the item is selected.
*/
isSelected(name: string): boolean {
const items = this._sortedItems;
return (
Array.from(
filter(items, item => item.name === name && this.selection[item.path])
).length !== 0
);
}
/**
* Find a model given a click.
*
* @param event - The mouse event.
*
* @returns The model for the selected file.
*/
modelForClick(event: MouseEvent): Contents.IModel | undefined {
const items = this._sortedItems;
const index = Private.hitTestNodes(this._items, event);
if (index !== -1) {
return items[index];
}
return undefined;
}
/**
* Clear the selected items.
*/
clearSelectedItems(): void {
this.selection = Object.create(null);
}
/**
* Select an item by name.
*
* @param name - The name of the item to select.
* @param focus - Whether to move focus to the selected item.
*
* @returns A promise that resolves when the name is selected.
*/
async selectItemByName(name: string, focus: boolean = false): Promise<void> {
return this._selectItemByName(name, focus);
}
/**
* Select an item by name.
*
* @param name - The name of the item to select.
* @param focus - Whether to move focus to the selected item.
* @param force - Whether to proceed with selection even if the file was already selected.
*
* @returns A promise that resolves when the name is selected.
*/
private async _selectItemByName(
name: string,
focus: boolean = false,
force: boolean = false
): Promise<void> {
if (!force && this.isSelected(name)) {
// Avoid API polling and DOM updates if already selected
return;
}
// Make sure the file is available.
await this.model.refresh();
if (this.isDisposed) {
throw new Error('File browser is disposed.');
}
const items = this._sortedItems;
const index = ArrayExt.findFirstIndex(items, value => value.name === name);
if (index === -1) {
throw new Error('Item does not exist.');
}
this._selectItem(index, false, focus);
MessageLoop.sendMessage(this, Widget.Msg.UpdateRequest);
ElementExt.scrollIntoViewIfNeeded(this.contentNode, this._items[index]);
}
/**
* Handle the DOM events for the directory listing.
*
* @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 panel's DOM node. It should
* not be called directly by user code.
*/
handleEvent(event: Event): void {
switch (event.type) {
case 'mousedown':
this._evtMousedown(event as MouseEvent);
break;
case 'mouseup':
this._evtMouseup(event as MouseEvent);
break;
case 'mousemove':
this._evtMousemove(event as MouseEvent);
break;
case 'keydown':
this.evtKeydown(event as KeyboardEvent);
break;
case 'click':
this._evtClick(event as MouseEvent);
break;
case 'dblclick':
this.evtDblClick(event as MouseEvent);
break;
case 'dragenter':
case 'dragover':
this.addClass('jp-mod-native-drop');
event.preventDefault();
break;
case 'dragleave':
case 'dragend':
this.removeClass('jp-mod-native-drop');
break;
case 'drop':
this.removeClass('jp-mod-native-drop');
this.evtNativeDrop(event as DragEvent);
break;
case 'scroll':
this._evtScroll(event as MouseEvent);
break;
case 'lm-dragenter':
this.evtDragEnter(event as Drag.Event);
break;
case 'lm-dragleave':
this.evtDragLeave(event as Drag.Event);
break;
case 'lm-dragover':
this.evtDragOver(event as Drag.Event);
break;
case 'lm-drop':
this.evtDrop(event as Drag.Event);
break;
default:
break;
}
}
/**
* A message handler invoked on an `'after-attach'` message.
*/
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
const node = this.node;
const content = DOMUtils.findElement(node, CONTENT_CLASS);
node.addEventListener('mousedown', this);
node.addEventListener('keydown', this);
node.addEventListener('click', this);
node.addEventListener('dblclick', this);
content.addEventListener('dragenter', this);
content.addEventListener('dragover', this);
content.addEventListener('dragleave', this);
content.addEventListener('dragend', this);
content.addEventListener('drop', this);
content.addEventListener('scroll', this);
content.addEventListener('lm-dragenter', this);
content.addEventListener('lm-dragleave', this);
content.addEventListener('lm-dragover', this);
content.addEventListener('lm-drop', this);
}
/**
* A message handler invoked on a `'before-detach'` message.
*/
protected onBeforeDetach(msg: Message): void {
super.onBeforeDetach(msg);
const node = this.node;
const content = DOMUtils.findElement(node, CONTENT_CLASS);
node.removeEventListener('mousedown', this);
node.removeEventListener('keydown', this);
node.removeEventListener('click', this);
node.removeEventListener('dblclick', this);
content.removeEventListener('scroll', this);
content.removeEventListener('dragover', this);
content.removeEventListener('dragover', this);
content.removeEventListener('dragleave', this);
content.removeEventListener('dragend', this);
content.removeEventListener('drop', this);
content.removeEventListener('lm-dragenter', this);
content.removeEventListener('lm-dragleave', this);
content.removeEventListener('lm-dragover', this);
content.removeEventListener('lm-drop', this);
document.removeEventListener('mousemove', this, true);
document.removeEventListener('mouseup', this, true);
}
/**
* A message handler invoked on an `'after-show'` message.
*/
protected onAfterShow(msg: Message): void {
if (this._isDirty) {
// Update the sorted items.
this.sort(this.sortState);
this.update();
}
}
// Update the modified column's size
private _updateModifiedSize(node: HTMLElement) {
const modified = DOMUtils.findElement(node, ITEM_MODIFIED_CLASS);
this._modifiedWidth = modified?.getBoundingClientRect().width ?? 83;
this._modifiedStyle =
this._modifiedWidth < 90
? 'narrow'
: this._modifiedWidth > 110
? 'long'
: 'short';
}
// Update only the modified dates.
protected updateModified(items: Contents.IModel[], nodes: HTMLElement[]) {
items.forEach((item, i) => {
const node = nodes[i];
if (item.last_modified) {
const modified = DOMUtils.findElement(node, ITEM_MODIFIED_CLASS);
if (this.renderer.updateItemModified !== undefined) {
this.renderer.updateItemModified(
modified,
item.last_modified,
this._modifiedStyle
);
} else {
DirListing.defaultRenderer.updateItemModified(
modified,
item.last_modified,
this._modifiedStyle
);
}
}
});
}
// Update item nodes based on widget state.
protected updateNodes(items: Contents.IModel[], nodes: HTMLElement[]) {
items.forEach((item, i) => {
const node = nodes[i];
const ft = this._manager.registry.getFileTypeForModel(item);
this.renderer.updateItemNode(
node,
item,
ft,
this.translator,
this._hiddenColumns,
this.selection[item.path],
this._modifiedStyle
);
if (
this.selection[item.path] &&
this._isCut &&
this._model.path === this._prevPath
) {
node.classList.add(CUT_CLASS);
}
// add metadata to the node
node.setAttribute(
'data-isdir',
item.type === 'directory' ? 'true' : 'false'
);
});
// Handle the selectors on the widget node.
const selected = Object.keys(this.selection).length;
if (selected) {
this.addClass(SELECTED_CLASS);
if (selected > 1) {
this.addClass(MULTI_SELECTED_CLASS);
}
}
// Handle file session statuses.
const paths = items.map(item => item.path);
for (const session of this._model.sessions()) {
const index = ArrayExt.firstIndexOf(paths, session.path);
const node = nodes[index];
// Node may have been filtered out.
if (node) {
let name = session.kernel?.name;
const specs = this._model.specs;
node.classList.add(RUNNING_CLASS);
if (specs && name) {
const spec = specs.kernelspecs[name];
name = spec ? spec.display_name : this._trans.__('unknown');
}
node.title = this._trans.__('%1\nKernel: %2', node.title, name);
}
}
}
/**
* A handler invoked on an `'update-request'` message.
*/
protected onUpdateRequest(msg: Message): void {
this._isDirty = false;
// Fetch common variables.
const items = this._sortedItems;
const nodes = this._items;
const content = DOMUtils.findElement(this.node, CONTENT_CLASS);
const renderer = this._renderer;
this.removeClass(MULTI_SELECTED_CLASS);
this.removeClass(SELECTED_CLASS);
// Remove any excess item nodes.
while (nodes.length > items.length) {
content.removeChild(nodes.pop()!);
}
// Add any missing item nodes.
while (nodes.length < items.length) {
const node = renderer.createItemNode(this._hiddenColumns);
node.classList.add(ITEM_CLASS);
nodes.push(node);
content.appendChild(node);
}
nodes.forEach((node, i) => {
// Remove extra classes from the nodes.
node.classList.remove(SELECTED_CLASS);
node.classList.remove(RUNNING_CLASS);
node.classList.remove(CUT_CLASS);
// Uncheck each file checkbox
const checkbox = renderer.getCheckboxNode(node);
if (checkbox) {
checkbox.checked = false;
}
// Handle `tabIndex`
const nameNode = renderer.getNameNode(node);
if (nameNode) {
// Must check if the name node is there because it gets replaced by the
// edit node when editing the name of the file or directory.
nameNode.tabIndex = i === this._focusIndex ? 0 : -1;
}
});
// Put the check-all checkbox in the header into the correct state
const checkAllCheckbox = renderer.getCheckboxNode(this.headerNode);
if (checkAllCheckbox) {
const totalSelected = Object.keys(this.selection).length;
const allSelected = items.length > 0 && totalSelected === items.length;
const someSelected = !allSelected && totalSelected > 0;
checkAllCheckbox.checked = allSelected;
checkAllCheckbox.indeterminate = someSelected;
// Stash the state in data attributes so we can access them in the click
// handler (because in the click handler, checkbox.checked and
// checkbox.indeterminate do not hold the previous value; they hold the
// next value).
checkAllCheckbox.dataset.checked = String(allSelected);
checkAllCheckbox.dataset.indeterminate = String(someSelected);
const trans = this.translator.load('jupyterlab');
checkAllCheckbox?.setAttribute(
'aria-label',
allSelected || someSelected
? trans.__('Deselect all files and directories')
: trans.__('Select all files and directories')
);
}
this.updateNodes(items, nodes);
this._prevPath = this._model.path;
}
onResize(msg: Widget.ResizeMessage): void {
const { width } =
msg.width === -1 ? this.node.getBoundingClientRect() : msg;
this.toggleClass('jp-DirListing-narrow', width < 250);
// Rerender item nodes' modified dates, if the modified style has changed.
const oldModifiedStyle = this._modifiedStyle;
this._updateModifiedSize(this.node);
if (oldModifiedStyle !== this._modifiedStyle) {
this.updateModified(this._sortedItems, this._items);
}
}
setColumnVisibility(
name: DirListing.ToggleableColumn,
visible: boolean
): void {
if (visible) {