forked from deephaven/web-client-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotebookPanel.tsx
More file actions
1513 lines (1355 loc) · 42 KB
/
NotebookPanel.tsx
File metadata and controls
1513 lines (1355 loc) · 42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
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
// Wrapper for the Notebook for use in a golden layout container
import React, { Component, type ReactElement, Suspense, lazy } from 'react';
import ReactDOM from 'react-dom';
import memoize from 'memoize-one';
import { connect } from 'react-redux';
import type { editor } from 'monaco-editor';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
BasicModal,
ContextActions,
DropdownMenu,
Tooltip,
GLOBAL_SHORTCUTS,
Button,
type DropdownAction,
LoadingOverlay,
} from '@deephaven/components';
import {
MonacoUtils,
ScriptEditor,
ScriptEditorUtils,
SHORTCUTS,
} from '@deephaven/console';
import {
type FileStorage,
FileUtils,
NewItemModal,
type File,
} from '@deephaven/file-explorer';
import {
vsSave,
vsKebabVertical,
dhFileSearch,
vsPlay,
dhRunSelection,
vsCheck,
vsCopy,
dhICursor,
vsTrash,
} from '@deephaven/icons';
import {
getFileStorage,
updateNotebookSettings as updateNotebookSettingsAction,
type RootState,
type WorkspaceSettings,
getNotebookSettings,
} from '@deephaven/redux';
import classNames from 'classnames';
import debounce from 'lodash.debounce';
import {
type DashboardPanelProps,
PanelEvent,
type PanelMetadata,
} from '@deephaven/dashboard';
import Log from '@deephaven/log';
import { assertNotNull, Pending, PromiseUtils } from '@deephaven/utils';
import type { Tab, CloseOptions } from '@deephaven/golden-layout';
import type { dh } from '@deephaven/jsapi-types';
import { ConsoleEvent, NotebookEvent } from '../events';
import { getDashboardSessionWrapper } from '../redux';
import Panel from './CorePanel';
import './NotebookPanel.scss';
const MarkdownNotebook = lazy(() => import('./MarkdownNotebook'));
const log = Log.module('NotebookPanel');
const DEBOUNCE_PANEL_STATE_UPDATE = 400;
interface Metadata extends PanelMetadata {
id: string;
}
interface NotebookSetting {
isMinimapEnabled?: boolean;
formatOnSave?: boolean;
}
interface FileMetadata {
itemName: string;
id: string;
}
interface PanelState {
isPreview?: boolean;
settings: editor.IStandaloneEditorConstructionOptions;
fileMetadata: FileMetadata | null;
}
interface NotebookPanelMappedProps {
notebookSettings: NotebookSetting;
fileStorage: FileStorage;
session?: dh.IdeSession;
sessionLanguage?: string;
}
interface NotebookPanelProps
extends DashboardPanelProps,
NotebookPanelMappedProps {
isDashboardActive: boolean;
isPreview: boolean;
metadata: Metadata;
panelState: PanelState;
notebooksUrl: string;
updateNotebookSettings: (
settings: Partial<WorkspaceSettings['notebookSettings']>
) => void;
}
interface NotebookPanelState {
error?: {
message?: string | undefined;
};
isDashboardActive: boolean;
isLoading: boolean;
isLoaded: boolean;
isPreview: boolean;
savedChangeCount: number;
changeCount: number;
fileMetadata: FileMetadata | null;
settings: editor.IStandaloneEditorConstructionOptions;
session?: dh.IdeSession;
sessionLanguage?: string;
// eslint-disable-next-line react/no-unused-state
panelState: PanelState;
showCloseModal: boolean;
showDeleteModal: boolean;
showSaveAsModal: boolean;
scriptCode: string;
itemName?: string;
formatOnSave: boolean;
}
class NotebookPanel extends Component<NotebookPanelProps, NotebookPanelState> {
static COMPONENT = 'NotebookPanel';
static POPPER_OPTIONS = { placement: 'bottom-end' } as const;
static DEFAULT_NAME = 'Untitled';
static UNSAVED_INDICATOR_CLASS_NAME = 'editor-unsaved-indicator';
static UNSAVED_STATUS_CLASS_NAME = 'is-unsaved';
static handleError(error: unknown): void {
if (PromiseUtils.isCanceled(error)) {
return;
}
log.error(error);
}
/**
* Returns number of unsaved notebooks.
*/
static unsavedNotebookCount(): number {
return document.querySelectorAll(
`.${NotebookPanel.UNSAVED_INDICATOR_CLASS_NAME}.${NotebookPanel.UNSAVED_STATUS_CLASS_NAME}`
).length;
}
static defaultProps = {
isDashboardActive: true,
isPreview: false,
session: null,
sessionLanguage: null,
notebookSettings: { isMinimapEnabled: true },
};
static languageFromFileName(fileName: string): string | null {
const extension = FileUtils.getExtension(fileName).toLowerCase();
switch (extension) {
case 'py':
case 'python':
return 'python';
case 'groovy':
return 'groovy';
case 'scala':
return 'scala';
default:
return null;
}
}
constructor(props: NotebookPanelProps) {
super(props);
this.handleCloseCancel = this.handleCloseCancel.bind(this);
this.handleCloseDiscard = this.handleCloseDiscard.bind(this);
this.handleCloseSave = this.handleCloseSave.bind(this);
this.handleCopy = this.handleCopy.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.handleDeleteConfirm = this.handleDeleteConfirm.bind(this);
this.handleDeleteCancel = this.handleDeleteCancel.bind(this);
this.handleEditorInitialized = this.handleEditorInitialized.bind(this);
this.handleEditorWillDestroy = this.handleEditorWillDestroy.bind(this);
this.handleEditorChange = this.handleEditorChange.bind(this);
this.handleFind = this.handleFind.bind(this);
this.handleMinimapChange = this.handleMinimapChange.bind(this);
this.handleWordWrapChange = this.handleWordWrapChange.bind(this);
this.handleFormatOnSaveChange = this.handleFormatOnSaveChange.bind(this);
this.handleLinkClick = this.handleLinkClick.bind(this);
this.handleLoadSuccess = this.handleLoadSuccess.bind(this);
this.handleLoadError = this.handleLoadError.bind(this);
this.handlePanelDropped = this.handlePanelDropped.bind(this);
this.handleRenameFile = this.handleRenameFile.bind(this);
this.handleResize = this.handleResize.bind(this);
this.handleRunCommand = this.handleRunCommand.bind(this);
this.handleRunAll = this.handleRunAll.bind(this);
this.handleRunSelected = this.handleRunSelected.bind(this);
this.handleSave = this.handleSave.bind(this);
this.handleSaveAsCancel = this.handleSaveAsCancel.bind(this);
this.handleSaveAsSubmit = this.handleSaveAsSubmit.bind(this);
this.handleSaveError = this.handleSaveError.bind(this);
this.handleSaveSuccess = this.handleSaveSuccess.bind(this);
this.handleSessionOpened = this.handleSessionOpened.bind(this);
this.handleSessionClosed = this.handleSessionClosed.bind(this);
this.handleShow = this.handleShow.bind(this);
this.handleShowRename = this.handleShowRename.bind(this);
this.handleTab = this.handleTab.bind(this);
this.handleTabBlur = this.handleTabBlur.bind(this);
this.handleTabClick = this.handleTabClick.bind(this);
this.handleTabFocus = this.handleTabFocus.bind(this);
this.handleTransformLinkUri = this.handleTransformLinkUri.bind(this);
this.handleOverwrite = this.handleOverwrite.bind(this);
this.handlePreviewPromotion = this.handlePreviewPromotion.bind(this);
this.handleFormat = this.handleFormat.bind(this);
this.canFormat = this.canFormat.bind(this);
this.getDropdownOverflowActions =
this.getDropdownOverflowActions.bind(this);
this.pending = new Pending();
this.debouncedSavePanelState = debounce(
this.savePanelState.bind(this),
DEBOUNCE_PANEL_STATE_UPDATE
);
this.debouncedLoad = debounce(
this.load.bind(this),
DEBOUNCE_PANEL_STATE_UPDATE
);
this.notebook = null;
this.tabTitleElement = null;
this.tabInitOnce = false;
const { isDashboardActive, session, sessionLanguage, panelState } = props;
let settings: editor.IStandaloneEditorConstructionOptions = {
value: '',
language: '',
wordWrap: 'off',
};
let fileMetadata = null;
let { isPreview } = props;
if (panelState != null) {
({
fileMetadata = fileMetadata,
isPreview = isPreview,
settings = settings,
} = panelState);
}
// Not showing the unsaved indicator for null file id and editor content === '',
// may need to implement some other indication that this notebook has never been saved
const hasFileId =
fileMetadata != null && FileUtils.hasPath(fileMetadata.itemName);
// Unsaved if file id != null and content != null
// OR file id is null AND content is not null or ''
const isUnsaved =
(hasFileId === true && settings.value != null) ||
(!hasFileId && settings.value != null && settings.value.length > 0);
const changeCount = isUnsaved ? 1 : 0;
this.state = {
error: undefined,
isDashboardActive,
isLoading: true,
isLoaded: false,
isPreview,
savedChangeCount: 0,
changeCount,
fileMetadata,
settings,
session,
sessionLanguage,
// eslint-disable-next-line react/no-unused-state
panelState: {
fileMetadata,
settings,
},
showCloseModal: false,
showDeleteModal: false,
showSaveAsModal: false,
scriptCode: '',
formatOnSave: false,
};
log.debug('constructor', props, this.state);
}
componentDidMount(): void {
const { glContainer, glEventHub } = this.props;
const { tab } = glContainer;
if (tab != null) this.initTab(tab);
this.initNotebookContent();
glEventHub.on(NotebookEvent.RENAME_FILE, this.handleRenameFile);
glEventHub.on(PanelEvent.DROPPED, this.handlePanelDropped);
glContainer.on(
NotebookEvent.PROMOTE_FROM_PREVIEW,
this.handlePreviewPromotion
);
}
componentDidUpdate(
prevProps: NotebookPanelProps,
prevState: NotebookPanelState
): void {
const { isPreview, settings } = this.state;
const { wordWrap } = settings;
const { notebookSettings } = this.props;
if (isPreview !== prevState.isPreview) {
this.setPreviewStatus();
}
if (wordWrap !== prevState.settings.wordWrap) {
this.updateEditorWordWrap();
this.debouncedSavePanelState();
}
if (
notebookSettings.isMinimapEnabled !==
prevProps.notebookSettings.isMinimapEnabled
) {
this.updateEditorMinimap();
}
}
componentWillUnmount(): void {
this.debouncedSavePanelState.flush();
this.pending.cancel();
const { glEventHub, glContainer } = this.props;
const { fileMetadata, isPreview } = this.state;
glEventHub.off(NotebookEvent.RENAME_FILE, this.handleRenameFile);
glEventHub.off(PanelEvent.DROPPED, this.handlePanelDropped);
glContainer.off(
NotebookEvent.PROMOTE_FROM_PREVIEW,
this.handlePreviewPromotion
);
glEventHub.emit(NotebookEvent.UNREGISTER_FILE, fileMetadata, isPreview);
}
pending: Pending;
debouncedSavePanelState;
debouncedLoad;
notebook: ScriptEditor | null;
tabTitleElement: Element | null;
tabInitOnce: boolean;
editor?: editor.IStandaloneCodeEditor;
// Called by TabEvent. Happens once when created, but also each time its moved.
// when moved, need to re-init the unsaved indicators on title elements
initTab(tab: Tab): void {
if (!this.tabInitOnce) {
this.tabInitOnce = true;
this.initTabCloseOverride();
}
this.initTabClasses(tab);
}
/**
* Adds a beforeClose handler to check if a notebook needs to be saved
* Call panel close with force if the check can be skipped
*
* Note that firing a close event manually may trigger before state update occurs
* In those instances, use force
*/
initTabCloseOverride(): void {
const { glContainer } = this.props;
glContainer.beforeClose((options?: CloseOptions) => {
if (options?.force === true) {
return true;
}
const { changeCount, savedChangeCount } = this.state;
if (changeCount !== savedChangeCount) {
this.setState({ showCloseModal: true });
return false;
}
return true;
});
}
initTabClasses(tab: Tab): void {
const tabElement = tab.element.get(0);
assertNotNull(tabElement);
const titleElement = tabElement.querySelector('.lm_title');
this.tabTitleElement = titleElement;
titleElement?.classList.add('notebook-title');
this.setPreviewStatus();
}
getNotebookValue(): string | undefined {
const { changeCount, savedChangeCount, settings } = this.state;
const { value } = settings;
if (changeCount !== savedChangeCount && this.notebook) {
const notebookValue = this.notebook.getValue();
return notebookValue != null ? notebookValue : value;
}
return value;
}
initNotebookContent(): void {
// Init from file,
// fallback to content from settings for unsaved notebook
const { fileMetadata, settings, isPreview } = this.state;
if (fileMetadata && fileMetadata.id) {
log.debug('Init content from file');
this.registerFileMetadata(fileMetadata, isPreview);
this.load();
return;
}
if (settings.value != null) {
log.debug('Use content passed in the settings prop');
this.handleLoadSuccess();
return;
}
// No settings, no metadata
this.handleLoadError(new Error('Missing file metadata'));
}
closeFileTabById(id: string): void {
const { glEventHub } = this.props;
glEventHub.emit(NotebookEvent.CLOSE_FILE, { id });
}
// Associate file id with the current tab
// so the next time the file is opened this tab can be focused instead of opening a new tab
registerFileMetadata(fileMetadata: FileMetadata, isPreview: boolean): void {
const { glEventHub, metadata } = this.props;
const { id: tabId } = metadata;
glEventHub.emit(
NotebookEvent.REGISTER_FILE,
tabId,
fileMetadata,
isPreview
);
}
renameTab(id: string, title: string): void {
const { glEventHub } = this.props;
glEventHub.emit(NotebookEvent.RENAME, id, title);
}
load(): void {
const { fileMetadata, settings } = this.state;
assertNotNull(fileMetadata);
const { id } = fileMetadata;
const { fileStorage } = this.props;
this.pending
.add(fileStorage.loadFile(id))
.then(loadedFile => {
log.debug('Loaded file', loadedFile);
const { filename: itemName } = loadedFile;
const { itemName: prevItemName } = this.state;
if (itemName !== prevItemName) {
const { metadata } = this.props;
const { id: tabId } = metadata;
this.renameTab(tabId, FileUtils.getBaseName(itemName));
}
const updatedSettings = {
...settings,
language: NotebookPanel.languageFromFileName(itemName) ?? '',
};
if (settings.value == null) {
updatedSettings.value = loadedFile.content;
}
if (settings.wordWrap === undefined) {
settings.wordWrap = 'off';
}
this.setState({
fileMetadata: { id: itemName, itemName },
settings: updatedSettings,
});
this.debouncedSavePanelState();
})
.then(this.handleLoadSuccess)
.catch(this.handleLoadError);
}
/**
* Attempts to save the notebook.
* @returns Returns true if save has begun, false if user needed to be prompted
*/
save(): boolean {
const { fileMetadata } = this.state;
if (fileMetadata && FileUtils.hasPath(fileMetadata.itemName)) {
const content = this.getNotebookValue();
if (content !== undefined) {
this.saveContent(fileMetadata.itemName, content);
return true;
}
return false;
}
this.setState({ showSaveAsModal: true });
return false;
}
/**
* Update existing file content
* @param filename The name of the file
* @param content New file content
*/
saveContent(filename: string, content: string): void {
log.debug('saveContent', filename, content);
this.updateSavedChangeCount();
const { fileStorage } = this.props;
this.pending
.add(fileStorage.saveFile({ filename, content, basename: filename }))
.then(this.handleSaveSuccess)
.catch(this.handleSaveError);
}
updateSavedChangeCount(): void {
this.setState(({ changeCount }) => ({ savedChangeCount: changeCount }));
}
setPreviewStatus(): void {
if (!this.tabTitleElement) {
return;
}
const { isPreview } = this.state;
log.debug('setPreviewStatus', this.tabTitleElement, isPreview);
if (isPreview) {
this.tabTitleElement.classList.add('is-preview');
} else {
this.tabTitleElement.classList.remove('is-preview');
}
}
handlePreviewPromotion(): void {
this.removePreviewStatus();
}
getSettings = memoize(
(
initialSettings: editor.IStandaloneEditorConstructionOptions,
isMinimapEnabled: boolean
): editor.IStandaloneEditorConstructionOptions => ({
...initialSettings,
minimap: { enabled: isMinimapEnabled },
})
);
getOverflowActions = memoize(
(
isMinimapEnabled: boolean,
isWordWrapEnabled: boolean,
formatOnSave: boolean
) => {
const actions: DropdownAction[] = [
{
title: 'Find',
icon: dhFileSearch,
action: this.handleFind,
group: ContextActions.groups.high,
shortcut: SHORTCUTS.NOTEBOOK.FIND,
order: 10,
},
{
title: 'Copy File',
icon: vsCopy,
action: this.handleCopy,
group: ContextActions.groups.medium,
order: 20,
},
{
title: 'Rename File',
icon: dhICursor,
action: this.handleShowRename,
group: ContextActions.groups.medium,
order: 30,
},
{
title: 'Delete File',
icon: vsTrash,
action: this.handleDelete,
group: ContextActions.groups.medium,
order: 40,
},
{
title: 'Show Minimap',
icon: isMinimapEnabled ? vsCheck : undefined,
action: this.handleMinimapChange,
group: ContextActions.groups.low,
shortcut: SHORTCUTS.NOTEBOOK.MINIMAP,
order: 20,
},
{
title: 'Word Wrap',
icon: isWordWrapEnabled ? vsCheck : undefined,
action: this.handleWordWrapChange,
group: ContextActions.groups.low,
shortcut: SHORTCUTS.NOTEBOOK.WORDWRAP,
order: 30,
},
];
if (this.canFormat()) {
actions.push({
title: 'Format Document',
action: this.handleFormat,
group: ContextActions.groups.low,
order: 10,
});
actions.push({
title: 'Format on Save',
icon: formatOnSave ? vsCheck : undefined,
action: this.handleFormatOnSaveChange,
group: ContextActions.groups.low,
order: 15,
});
}
return actions;
}
);
savePanelState(): void {
this.setState(state => {
const {
changeCount,
savedChangeCount,
fileMetadata,
isPreview,
settings: initialSettings,
} = state;
const value = this.getNotebookValue();
// notebooks with no unsaved changes have value === null in dehydrated state
// content will be loaded from file when hydrating
const dehydratedValue =
changeCount !== savedChangeCount ? value : undefined;
const settings = {
...initialSettings,
value,
};
const dehydratedSettings = {
...initialSettings,
value: dehydratedValue,
};
const panelState = {
settings: dehydratedSettings,
fileMetadata,
isPreview,
};
log.debug('Saving panel state', panelState);
return {
settings,
// eslint-disable-next-line react/no-unused-state
panelState,
};
});
}
handleCloseDiscard(): void {
this.setState({ showCloseModal: false });
const { glContainer } = this.props;
glContainer.close({ force: true });
}
handleCloseSave(): void {
this.setState({ showCloseModal: false });
if (this.save()) {
const { glContainer } = this.props;
glContainer.close({ force: true });
}
}
handleCloseCancel(): void {
this.setState({ showCloseModal: false });
}
/**
* Closes overwritten tabs
* @param fileName The name of the file to be overwritten
*/
handleOverwrite(fileName: string): void {
const { glEventHub } = this.props;
glEventHub.emit(
NotebookEvent.CLOSE_FILE,
{
id: fileName,
itemName: fileName,
},
{ force: true }
);
this.focus();
}
async handleCopy(): Promise<void> {
const { fileStorage, glEventHub, session } = this.props;
const { fileMetadata, settings } = this.state;
assertNotNull(fileMetadata);
const { language } = settings;
const { itemName } = fileMetadata;
const copyName = await FileUtils.getUniqueCopyFileName(
fileStorage,
itemName
);
log.debug('handleCopy', fileMetadata, itemName, copyName);
await fileStorage.copyFile(itemName, copyName);
const newFileMetadata = { id: copyName, itemName: copyName };
const notebookSettings = {
value: null,
language,
};
glEventHub.emit(
NotebookEvent.SELECT_NOTEBOOK,
session,
language,
notebookSettings,
newFileMetadata,
true
);
}
handleDelete(): void {
log.debug('handleDelete, pending confirmation');
this.setState({ showDeleteModal: true });
}
async handleDeleteConfirm(): Promise<void> {
const { fileStorage, glContainer, glEventHub } = this.props;
const { fileMetadata } = this.state;
log.debug('handleDeleteConfirm', fileMetadata?.itemName);
this.setState({ showDeleteModal: false });
if (!fileMetadata) {
return;
}
if (
FileUtils.hasPath(fileMetadata.itemName) &&
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
(await FileUtils.fileExists(fileStorage, fileMetadata.itemName))
) {
glEventHub.emit(NotebookEvent.CLOSE_FILE, fileMetadata, { force: true });
fileStorage.deleteFile(fileMetadata.itemName);
} else {
glContainer.close({ force: true });
}
}
handleDeleteCancel(): void {
this.setState({ showDeleteModal: false });
}
handleEditorInitialized(innerEditor: editor.IStandaloneCodeEditor): void {
this.editor = innerEditor;
}
handleEditorWillDestroy(): void {
this.editor = undefined;
}
handleEditorChange(e: editor.IModelContentChangedEvent): void {
log.debug2('handleEditorChanged', e);
this.removePreviewStatus();
this.setState(state => {
const { changeCount, savedChangeCount } = state;
const { isUndoing, isRedoing } = e;
if (isUndoing) {
// Note that it's possible to undo past where the user last saved, if they save and then undo for example
return { changeCount: changeCount - 1, savedChangeCount };
}
if (!isRedoing && changeCount < savedChangeCount) {
// We made another change after undoing some changes from the previous save
// Just reset the saved counter to zero and increase the unchanged saves
// It'll be set correctly on the next save
return { changeCount: changeCount + 1, savedChangeCount: 0 };
}
return { changeCount: changeCount + 1, savedChangeCount };
});
this.debouncedSavePanelState();
}
handleFind(): void {
if (this.notebook) {
this.notebook.toggleFind();
}
}
updateEditorMinimap(): void {
if (this.editor) {
const { notebookSettings } = this.props;
this.editor.updateOptions({
minimap: { enabled: notebookSettings.isMinimapEnabled },
});
}
}
handleMinimapChange(): void {
const { notebookSettings, updateNotebookSettings } = this.props;
const newSettings = {
isMinimapEnabled: !(notebookSettings.isMinimapEnabled ?? false),
};
updateNotebookSettings(newSettings);
}
updateEditorWordWrap(): void {
if (this.editor) {
const { settings } = this.state;
const { wordWrap } = settings;
this.editor.updateOptions({
wordWrap,
});
}
}
handleWordWrapChange(): void {
if (this.editor) {
this.setState(prevState => {
const { settings } = prevState;
const wordWrap = settings.wordWrap === 'on' ? 'off' : 'on';
return {
settings: {
...settings,
wordWrap,
},
};
});
}
}
handleFormatOnSaveChange(): void {
const { notebookSettings, updateNotebookSettings } = this.props;
const newSettings = {
formatOnSave: !(notebookSettings.formatOnSave ?? false),
};
updateNotebookSettings(newSettings);
}
/**
* @param event The click event from clicking on the link
*/
handleLinkClick(event: React.MouseEvent<HTMLAnchorElement>): void {
const { notebooksUrl, session, sessionLanguage } = this.props;
const { href } = event.currentTarget;
if (!href || !href.startsWith(notebooksUrl)) {
return;
}
event.stopPropagation();
event.preventDefault();
const notebookPath = `/${href.substring(notebooksUrl.length)}`.replace(
/%20/g,
' '
);
if (notebookPath === '/') {
log.debug('Ignoring invalid notebook link', notebookPath);
return;
}
log.debug('Notebook link clicked, opening', notebookPath);
const { glEventHub } = this.props;
const notebookSettings = {
value: null,
language: sessionLanguage,
};
const fileMetadata = { id: notebookPath, itemName: notebookPath };
glEventHub.emit(
NotebookEvent.SELECT_NOTEBOOK,
session,
sessionLanguage,
notebookSettings,
fileMetadata
);
}
handleLoadSuccess(): void {
this.setState({
error: undefined,
isLoaded: true,
isLoading: false,
});
}
handleLoadError(errorParam: { message?: string | undefined }): void {
let error = errorParam;
if (PromiseUtils.isCanceled(error)) {
return;
}
if (PromiseUtils.isTimedOut(error)) {
error = new Error('File not found.');
}
log.error(error);
this.setState({ error, isLoading: false });
}
async handleSave(): Promise<void> {
log.debug('handleSave');
const { notebookSettings } = this.props;
const { formatOnSave = false } = notebookSettings;
if (formatOnSave) {
await this.handleFormat();
}
this.save();
}
handleSaveSuccess(file: File): void {
const { fileStorage } = this.props;
const fileMetadata = { id: file.filename, itemName: file.filename };
const language = NotebookPanel.languageFromFileName(file.filename) ?? '';
this.setState(state => {
const { fileMetadata: oldMetadata } = state;
const settings = {
...state.settings,
language,
};
log.debug('handleSaveSuccess', fileMetadata, oldMetadata, settings);
if (
oldMetadata &&
FileUtils.hasPath(oldMetadata.itemName) &&
oldMetadata.itemName !== fileMetadata.itemName
) {
log.debug('handleSaveSuccess deleting old file', oldMetadata.itemName);
fileStorage
.deleteFile(oldMetadata.itemName)
.catch(NotebookPanel.handleError);
}
return {
fileMetadata,
settings,
isPreview: false,
};
});
this.debouncedSavePanelState();
this.registerFileMetadata(fileMetadata, false);
}
handleSaveError(error: unknown): void {
if (PromiseUtils.isCanceled(error)) {
return;
}
// There was an error saving, just reset the savedChangeCount
// It's possible if they undo changes they'll be back at the spot where it was last saved successfully,
// But we may as well continue showing the error until they actually save again
this.setState({ savedChangeCount: 0 });
log.error(error);
}
handleSaveAsCancel(): void {
this.setState({ showSaveAsModal: false });
}
handleSaveAsSubmit(name: string, isOverwrite = false): void {
if (isOverwrite) {
this.handleOverwrite(name);
}
log.debug('handleSaveAsSubmit', name);
const { fileMetadata } = this.state;
if (!fileMetadata) {
return;
}
const { itemName: prevItemName } = fileMetadata;
const content = this.getNotebookValue() ?? '';
this.setState({
showSaveAsModal: false,