forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainPanel.tsx
More file actions
1104 lines (942 loc) · 42.6 KB
/
MainPanel.tsx
File metadata and controls
1104 lines (942 loc) · 42.6 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import { min } from 'lodash';
import * as monacoEditor from 'monaco-editor/esm/vs/editor/editor.api';
import * as React from 'react';
import * as uuid from 'uuid/v4';
import { createDeferred, Deferred } from '../../client/common/utils/async';
import { noop } from '../../client/common/utils/misc';
import { CellMatcher } from '../../client/datascience/cellMatcher';
import { generateMarkdownFromCodeLines } from '../../client/datascience/common';
import { Identifiers } from '../../client/datascience/constants';
import { IInteractiveWindowMapping, InteractiveWindowMessages } from '../../client/datascience/interactive-window/interactiveWindowTypes';
import { CellState, ICell, IInteractiveWindowInfo, IJupyterVariable, IJupyterVariablesResponse } from '../../client/datascience/types';
import { ErrorBoundary } from '../react-common/errorBoundary';
import { getLocString } from '../react-common/locReactSide';
import { IMessageHandler, PostOffice } from '../react-common/postOffice';
import { getSettings, updateSettings } from '../react-common/settingsReactSide';
import { StyleInjector } from '../react-common/styleInjector';
import { Cell, ICellViewModel } from './cell';
import { ContentPanel, IContentPanelProps } from './contentPanel';
import { InputHistory } from './inputHistory';
import { IntellisenseProvider } from './intellisenseProvider';
import { createCellVM, createEditableCellVM, extractInputText, generateTestState, IMainPanelState } from './mainPanelState';
import { initializeTokenizer, registerMonacoLanguage } from './tokenizer';
import { IToolbarPanelProps, ToolbarPanel } from './toolbarPanel';
import { VariableExplorer } from './variableExplorer';
import { IVariablePanelProps, VariablePanel } from './variablePanel';
import './mainPanel.css';
export interface IMainPanelProps {
skipDefault?: boolean;
testMode?: boolean;
baseTheme: string;
codeTheme: string;
}
export class MainPanel extends React.Component<IMainPanelProps, IMainPanelState> implements IMessageHandler {
private stackLimit = 10;
private updateCount = 0;
private renderCount = 0;
private editCellRef: Cell | null = null;
private mainPanel: HTMLDivElement | null = null;
private variableExplorerRef: React.RefObject<VariableExplorer>;
private styleInjectorRef: React.RefObject<StyleInjector>;
private contentPanelRef: React.RefObject<ContentPanel>;
private postOffice: PostOffice = new PostOffice();
private intellisenseProvider: IntellisenseProvider;
private onigasmPromise: Deferred<ArrayBuffer> | undefined;
private tmlangugePromise: Deferred<string> | undefined;
private monacoIdToCellId: Map<string, string> = new Map<string, string>();
// tslint:disable-next-line:max-func-body-length
constructor(props: IMainPanelProps, _state: IMainPanelState) {
super(props);
// Default state should show a busy message
this.state = {
cellVMs: [],
busy: true,
undoStack: [],
redoStack : [],
submittedText: false,
history: new InputHistory(),
editCellVM: getSettings && getSettings().allowInput ? createEditableCellVM(1) : undefined,
editorOptions: this.computeEditorOptions(),
currentExecutionCount: 0,
debugging: false
};
// Add test state if necessary
if (!this.props.skipDefault) {
this.state = generateTestState(this.inputBlockToggled);
}
// Create the ref to hold our variable explorer
this.variableExplorerRef = React.createRef<VariableExplorer>();
// Create the ref to hold our style injector
this.styleInjectorRef = React.createRef<StyleInjector>();
// Create the ref to hold our content panel
this.contentPanelRef = React.createRef<ContentPanel>();
// Setup the completion provider for monaco. We only need one
this.intellisenseProvider = new IntellisenseProvider(this.postOffice, this.getCellId);
// Setup the tokenizer for monaco if running inside of vscode
if (this.props.skipDefault) {
if (this.props.testMode) {
// Running a test, skip the tokenizer. We want the UI to display synchronously
this.state = {tokenizerLoaded: true, ...this.state};
// However we still need to register python as a language
registerMonacoLanguage();
} else {
initializeTokenizer(this.loadOnigasm, this.loadTmlanguage, this.tokenizerLoaded).ignoreErrors();
}
}
}
public componentWillMount() {
// Add ourselves as a handler for the post office
this.postOffice.addHandler(this);
// Tell the interactive window code we have started.
this.postOffice.sendMessage<IInteractiveWindowMapping, 'started'>(InteractiveWindowMessages.Started);
}
public componentDidUpdate(_prevProps: Readonly<IMainPanelProps>, _prevState: Readonly<IMainPanelState>, _snapshot?: {}) {
// If in test mode, update our outputs
if (this.props.testMode) {
this.updateCount = this.updateCount + 1;
}
}
public componentWillUnmount() {
// Remove ourselves as a handler for the post office
this.postOffice.removeHandler(this);
// Get rid of our completion provider
this.intellisenseProvider.dispose();
// Get rid of our post office
this.postOffice.dispose();
}
public render() {
// If in test mode, update our outputs
if (this.props.testMode) {
this.renderCount = this.renderCount + 1;
}
const baseTheme = this.computeBaseTheme();
return (
<div id='main-panel' ref={this.updateSelf}>
<StyleInjector
expectingDark={baseTheme !== 'vscode-light'}
postOffice={this.postOffice}
darkChanged={this.darkChanged}
monacoThemeChanged={this.monacoThemeChanged}
ref={this.styleInjectorRef} />
<header id='main-panel-toolbar'>
{this.renderToolbarPanel(baseTheme)}
</header>
<section id='main-panel-variable' aria-label={getLocString('DataScience.collapseVariableExplorerLabel', 'Variables')}>
{this.renderVariablePanel(baseTheme)}
</section>
<main id='main-panel-content'>
{this.renderContentPanel(baseTheme)}
</main>
<section id='main-panel-footer' aria-label={getLocString('DataScience.editSection', 'Input new cells here')}>
{this.renderFooterPanel(baseTheme)}
</section>
</div>
);
}
// tslint:disable-next-line:no-any cyclomatic-complexity max-func-body-length
public handleMessage = (msg: string, payload?: any) => {
switch (msg) {
case InteractiveWindowMessages.StartCell:
this.startCell(payload);
return true;
case InteractiveWindowMessages.FinishCell:
this.finishCell(payload);
return true;
case InteractiveWindowMessages.UpdateCell:
this.updateCell(payload);
return true;
case InteractiveWindowMessages.GetAllCells:
this.getAllCells();
return true;
case InteractiveWindowMessages.ExpandAll:
this.expandAllSilent();
return true;
case InteractiveWindowMessages.CollapseAll:
this.collapseAllSilent();
return true;
case InteractiveWindowMessages.DeleteAllCells:
this.clearAllSilent();
return true;
case InteractiveWindowMessages.Redo:
this.redo();
return true;
case InteractiveWindowMessages.Undo:
this.undo();
return true;
case InteractiveWindowMessages.StartProgress:
if (!this.props.testMode) {
this.setState({busy: true});
}
break;
case InteractiveWindowMessages.StopProgress:
if (!this.props.testMode) {
this.setState({busy: false});
}
break;
case InteractiveWindowMessages.UpdateSettings:
this.updateSettings(payload);
break;
case InteractiveWindowMessages.Activate:
this.activate();
break;
case InteractiveWindowMessages.GetVariablesResponse:
this.getVariablesResponse(payload);
break;
case InteractiveWindowMessages.GetVariableValueResponse:
this.getVariableValueResponse(payload);
break;
case InteractiveWindowMessages.LoadOnigasmAssemblyResponse:
this.handleOnigasmResponse(payload);
break;
case InteractiveWindowMessages.LoadTmLanguageResponse:
this.handleTmLanguageResponse(payload);
break;
case InteractiveWindowMessages.RestartKernel:
// this should be the response from a restart.
this.setState({currentExecutionCount: 0});
if (this.variableExplorerRef.current && this.variableExplorerRef.current.state.open) {
this.refreshVariables(0);
}
break;
case InteractiveWindowMessages.StartDebugging:
this.setState({debugging: true});
break;
case InteractiveWindowMessages.StopDebugging:
this.setState({debugging: false});
break;
case InteractiveWindowMessages.ScrollToCell:
if (this.contentPanelRef && this.contentPanelRef.current) {
this.contentPanelRef.current.scrollToCell(payload.id);
}
break;
default:
break;
}
return false;
}
// Uncomment this to use for debugging messages. Add a call to this to stick in dummy sys info messages.
// private addDebugMessageCell(message: string) {
// const cell: ICell = {
// id: '0',
// file: '',
// line: 0,
// state: CellState.finished,
// data: {
// cell_type: 'sys_info',
// version: '0.0.0.0',
// notebook_version: '0',
// path: '',
// message: message,
// connection: '',
// source: '',
// metadata: {}
// }
// };
// this.addCell(cell);
// }
private renderToolbarPanel(baseTheme: string) {
const toolbarProps = this.getToolbarProps(baseTheme);
return <ToolbarPanel {...toolbarProps} />;
}
private renderVariablePanel(baseTheme: string) {
const variableProps = this.getVariableProps(baseTheme);
return <VariablePanel {...variableProps} />;
}
private renderContentPanel(baseTheme: string) {
// Skip if the tokenizer isn't finished yet. It needs
// to finish loading so our code editors work.
if (!this.state.tokenizerLoaded && !this.props.testMode) {
return null;
}
// Otherwise render our cells.
const contentProps = this.getContentProps(baseTheme);
return <ContentPanel {...contentProps} ref={this.contentPanelRef} />;
}
private renderFooterPanel(baseTheme: string) {
// Skip if the tokenizer isn't finished yet. It needs
// to finish loading so our code editors work.
// We also skip rendering if we're in debug mode (for now). We can't run other cells when debugging
if (!this.state.tokenizerLoaded || !this.state.editCellVM || this.state.debugging) {
return null;
}
const maxOutputSize = getSettings().maxOutputSize;
const maxTextSize = maxOutputSize && maxOutputSize < 10000 && maxOutputSize > 0 ? maxOutputSize : undefined;
const executionCount = this.getInputExecutionCount();
const editPanelClass = getSettings().colorizeInputBox ? 'edit-panel-colorized' : 'edit-panel';
return (
<div className={editPanelClass}>
<ErrorBoundary>
<Cell
editorOptions={this.state.editorOptions}
history={this.state.history}
maxTextSize={maxTextSize}
autoFocus={document.hasFocus()}
testMode={this.props.testMode}
cellVM={this.state.editCellVM}
submitNewCode={this.submitInput}
baseTheme={baseTheme}
codeTheme={this.props.codeTheme}
showWatermark={true}
ref={this.saveEditCellRef}
gotoCode={noop}
copyCode={noop}
delete={noop}
editExecutionCount={executionCount}
onCodeCreated={this.editableCodeCreated}
onCodeChange={this.codeChange}
monacoTheme={this.state.monacoTheme}
openLink={this.openLink}
expandImage={noop}
/>
</ErrorBoundary>
</div>
);
}
private computeEditorOptions() : monacoEditor.editor.IEditorOptions {
const intellisenseOptions = getSettings().intellisenseOptions;
const extraSettings = getSettings().extraSettings;
if (intellisenseOptions && extraSettings) {
return {
quickSuggestions: {
other: intellisenseOptions.quickSuggestions.other,
comments: intellisenseOptions.quickSuggestions.comments,
strings: intellisenseOptions.quickSuggestions.strings
},
acceptSuggestionOnEnter: intellisenseOptions.acceptSuggestionOnEnter,
quickSuggestionsDelay: intellisenseOptions.quickSuggestionsDelay,
suggestOnTriggerCharacters: intellisenseOptions.suggestOnTriggerCharacters,
tabCompletion: intellisenseOptions.tabCompletion,
suggest: {
localityBonus: intellisenseOptions.suggestLocalityBonus
},
suggestSelection: intellisenseOptions.suggestSelection,
wordBasedSuggestions: intellisenseOptions.wordBasedSuggestions,
parameterHints: {
enabled: intellisenseOptions.parameterHintsEnabled
},
cursorStyle: extraSettings.editorCursor,
cursorBlinking: extraSettings.editorCursorBlink
};
}
return {};
}
private darkChanged = (newDark: boolean) => {
// update our base theme if allowed. Don't do this
// during testing as it will mess up the expected render count.
if (!this.props.testMode) {
this.setState(
{
forceDark: newDark
}
);
}
}
private monacoThemeChanged = (theme: string) => {
// update our base theme if allowed. Don't do this
// during testing as it will mess up the expected render count.
if (!this.props.testMode) {
this.setState(
{
monacoTheme: theme
}
);
}
}
private computeBaseTheme(): string {
// If we're ignoring, always light
if (getSettings && getSettings().ignoreVscodeTheme) {
return 'vscode-light';
}
// Otherwise see if the style injector has figured out
// the theme is dark or not
if (this.state.forceDark !== undefined) {
return this.state.forceDark ? 'vscode-dark' : 'vscode-light';
}
return this.props.baseTheme;
}
private showPlot = (imageHtml: string) => {
this.sendMessage(InteractiveWindowMessages.ShowPlot, imageHtml);
}
private getContentProps = (baseTheme: string): IContentPanelProps => {
return {
editorOptions: this.state.editorOptions,
baseTheme: baseTheme,
cellVMs: this.state.cellVMs,
history: this.state.history,
testMode: this.props.testMode,
codeTheme: this.props.codeTheme,
submittedText: this.state.submittedText,
gotoCellCode: this.gotoCellCode,
copyCellCode: this.copyCellCode,
deleteCell: this.deleteCell,
skipNextScroll: this.state.skipNextScroll ? true : false,
monacoTheme: this.state.monacoTheme,
onCodeCreated: this.readOnlyCodeCreated,
onCodeChange: this.codeChange,
openLink: this.openLink,
expandImage: this.showPlot
};
}
private getToolbarProps = (baseTheme: string): IToolbarPanelProps => {
return {
addMarkdown: this.addMarkdown,
collapseAll: this.collapseAll,
expandAll: this.expandAll,
export: this.export,
restartKernel: this.restartKernel,
interruptKernel: this.interruptKernel,
undo: this.undo,
redo: this.redo,
clearAll: this.clearAll,
skipDefault: this.props.skipDefault,
canCollapseAll: this.canCollapseAll(),
canExpandAll: this.canExpandAll(),
canExport: this.canExport(),
canUndo: this.canUndo(),
canRedo: this.canRedo(),
baseTheme: baseTheme
};
}
private getVariableProps = (baseTheme: string): IVariablePanelProps => {
return {
debugging: this.state.debugging,
busy: this.state.busy,
showDataExplorer: this.showDataViewer,
skipDefault: this.props.skipDefault,
testMode: this.props.testMode,
variableExplorerRef: this.variableExplorerRef,
refreshVariables: this.refreshVariables,
variableExplorerToggled: this.variableExplorerToggled,
baseTheme: baseTheme
};
}
private activate() {
// Make sure the input cell gets focus
if (getSettings && getSettings().allowInput) {
// Delay this so that we make sure the outer frame has focus first.
setTimeout(() => {
// First we have to give ourselves focus (so that focus actually ends up in the code cell)
if (this.mainPanel) {
this.mainPanel.focus({preventScroll: true});
}
if (this.editCellRef) {
this.editCellRef.giveFocus();
}
}, 100);
}
}
// tslint:disable-next-line:no-any
private updateSettings = (payload?: any) => {
if (payload) {
const prevShowInputs = getSettings().showCellInputCode;
updateSettings(payload as string);
// If our settings change updated show inputs we need to fix up our cells
const showInputs = getSettings().showCellInputCode;
// Also save the editor options. Intellisense options may have changed.
this.setState({
editorOptions: this.computeEditorOptions()
});
if (prevShowInputs !== showInputs) {
this.toggleCellInputVisibility(showInputs, getSettings().collapseCellInputCodeByDefault);
}
}
}
private showDataViewer = (targetVariable: string, numberOfColumns: number) => {
this.sendMessage(InteractiveWindowMessages.ShowDataViewer, { variableName: targetVariable, columnSize: numberOfColumns });
}
private sendMessage<M extends IInteractiveWindowMapping, T extends keyof M>(type: T, payload?: M[T]) {
this.postOffice.sendMessage<M, T>(type, payload);
}
private openLink = (uri: monacoEditor.Uri) => {
this.sendMessage(InteractiveWindowMessages.OpenLink, uri.toString());
}
private getAllCells = () => {
// Send all of our cells back to the other side
const cells = this.state.cellVMs.map((cellVM : ICellViewModel) => {
return cellVM.cell;
});
this.sendMessage(InteractiveWindowMessages.ReturnAllCells, cells);
}
private saveEditCellRef = (ref: Cell | null) => {
this.editCellRef = ref;
}
private addMarkdown = () => {
this.addCell({
data : {
cell_type: 'markdown',
metadata: {},
source: [
'## Cell 3\n',
'Here\'s some markdown\n',
'- A List\n',
'- Of Items'
]
},
id : '1111',
file : 'foo.py',
line : 0,
state : CellState.finished
});
}
private getNonEditCellVMs() : ICellViewModel [] {
return this.state.cellVMs.filter(c => !c.editable);
}
private canCollapseAll = () => {
return this.getNonEditCellVMs().length > 0;
}
private canExpandAll = () => {
return this.getNonEditCellVMs().length > 0;
}
private canExport = () => {
return this.getNonEditCellVMs().length > 0;
}
private canRedo = () => {
return this.state.redoStack.length > 0 ;
}
private canUndo = () => {
return this.state.undoStack.length > 0 ;
}
private pushStack = (stack : ICellViewModel[][], cells : ICellViewModel[]) => {
// Get the undo stack up to the maximum length
const slicedUndo = stack.slice(0, min([stack.length, this.stackLimit]));
// Combine this with our set of cells
return [...slicedUndo, cells];
}
private gotoCellCode = (index: number) => {
// Find our cell
const cellVM = this.state.cellVMs[index];
// Send a message to the other side to jump to a particular cell
this.sendMessage(InteractiveWindowMessages.GotoCodeCell, { file : cellVM.cell.file, line: cellVM.cell.line });
}
private copyCellCode = (index: number) => {
// Find our cell
const cellVM = this.state.cellVMs[index];
// Send a message to the other side to jump to a particular cell
this.sendMessage(InteractiveWindowMessages.CopyCodeCell, { source: extractInputText(cellVM.cell, getSettings()) });
}
private deleteCell = (index: number) => {
this.sendMessage(InteractiveWindowMessages.DeleteCell);
const cellVM = this.state.cellVMs[index];
if (cellVM) {
this.sendMessage(InteractiveWindowMessages.RemoveCell, {id: cellVM.cell.id});
}
// Update our state
const newVMs = this.state.cellVMs.filter((_c : ICellViewModel, i: number) => {
return i !== index;
});
this.setState({
cellVMs: newVMs,
undoStack : this.pushStack(this.state.undoStack, this.state.cellVMs),
skipNextScroll: true
});
this.sendInfo(newVMs);
}
private collapseAll = () => {
this.sendMessage(InteractiveWindowMessages.CollapseAll);
this.collapseAllSilent();
}
private expandAll = () => {
this.sendMessage(InteractiveWindowMessages.ExpandAll);
this.expandAllSilent();
}
private clearAll = () => {
this.sendMessage(InteractiveWindowMessages.DeleteAllCells);
this.clearAllSilent();
}
private clearAllSilent = () => {
// Update our state
this.setState({
cellVMs: [],
undoStack : this.pushStack(this.state.undoStack, this.state.cellVMs),
skipNextScroll: true,
busy: false // No more progress on delete all
});
// Tell other side, we changed our number of cells
this.sendInfo([]);
}
private redo = () => {
// Pop one off of our redo stack and update our undo
const cells = this.state.redoStack[this.state.redoStack.length - 1];
const redoStack = this.state.redoStack.slice(0, this.state.redoStack.length - 1);
const undoStack = this.pushStack(this.state.undoStack, this.state.cellVMs);
this.sendMessage(InteractiveWindowMessages.Redo);
this.setState({
cellVMs: cells,
undoStack: undoStack,
redoStack: redoStack,
skipNextScroll: true
});
// Tell other side, we changed our number of cells
this.sendInfo(cells);
}
private undo = () => {
// Pop one off of our undo stack and update our redo
const cells = this.state.undoStack[this.state.undoStack.length - 1];
const undoStack = this.state.undoStack.slice(0, this.state.undoStack.length - 1);
const redoStack = this.pushStack(this.state.redoStack, this.state.cellVMs);
this.sendMessage(InteractiveWindowMessages.Undo);
this.setState({
cellVMs: cells,
undoStack : undoStack,
redoStack : redoStack,
skipNextScroll : true
});
// Tell other side, we changed our number of cells
this.sendInfo(cells);
}
private restartKernel = () => {
// Send a message to the other side to restart the kernel
this.sendMessage(InteractiveWindowMessages.RestartKernel);
}
private interruptKernel = () => {
// Send a message to the other side to restart the kernel
this.sendMessage(InteractiveWindowMessages.Interrupt);
}
private export = () => {
// Send a message to the other side to export our current list
const cellContents: ICell[] = this.state.cellVMs.map((cellVM: ICellViewModel, _index: number) => { return cellVM.cell; });
this.sendMessage(InteractiveWindowMessages.Export, cellContents);
}
private updateSelf = (r: HTMLDivElement) => {
this.mainPanel = r;
}
// tslint:disable-next-line:no-any
private addCell = (payload?: any) => {
// Get our settings for if we should display input code and if we should collapse by default
const showInputs = getSettings().showCellInputCode;
const collapseInputs = getSettings().collapseCellInputCodeByDefault;
if (payload) {
const cell = payload as ICell;
let cellVM: ICellViewModel = createCellVM(cell, getSettings(), this.inputBlockToggled);
// Set initial cell visibility and collapse
cellVM = this.alterCellVM(cellVM, showInputs, !collapseInputs);
if (cellVM) {
const newList = [...this.state.cellVMs, cellVM];
this.setState({
cellVMs: newList,
undoStack: this.pushStack(this.state.undoStack, this.state.cellVMs),
redoStack: this.state.redoStack,
skipNextScroll: false
});
// Tell other side, we changed our number of cells
this.sendInfo(newList);
}
}
}
private getEditCell() : ICellViewModel | undefined {
return this.state.editCellVM;
}
private inputBlockToggled = (id: string) => {
// Create a shallow copy of the array, let not const as this is the shallow array copy that we will be changing
const cellVMArray: ICellViewModel[] = [...this.state.cellVMs];
const cellVMIndex = cellVMArray.findIndex((value: ICellViewModel) => {
return value.cell.id === id;
});
if (cellVMIndex >= 0) {
// Const here as this is the state object pulled off of our shallow array copy, we don't want to mutate it
const targetCellVM = cellVMArray[cellVMIndex];
// Mutate the shallow array copy
cellVMArray[cellVMIndex] = this.alterCellVM(targetCellVM, true, !targetCellVM.inputBlockOpen);
this.setState({
skipNextScroll: true,
cellVMs: cellVMArray
});
}
}
private toggleCellInputVisibility = (visible: boolean, collapse: boolean) => {
this.alterAllCellVMs(visible, !collapse);
}
private collapseAllSilent = () => {
if (getSettings().showCellInputCode) {
this.alterAllCellVMs(true, false);
}
}
private expandAllSilent = () => {
if (getSettings().showCellInputCode) {
this.alterAllCellVMs(true, true);
}
}
private alterAllCellVMs = (visible: boolean, expanded: boolean) => {
const newCells = this.state.cellVMs.map((value: ICellViewModel) => {
return this.alterCellVM(value, visible, expanded);
});
this.setState({
skipNextScroll: true,
cellVMs: newCells
});
}
// Adjust the visibility or collapsed state of a cell
private alterCellVM = (cellVM: ICellViewModel, visible: boolean, expanded: boolean) => {
if (cellVM.cell.data.cell_type === 'code') {
// If we are already in the correct state, return back our initial cell vm
if (cellVM.inputBlockShow === visible && cellVM.inputBlockOpen === expanded) {
return cellVM;
}
const newCellVM = {...cellVM};
if (cellVM.inputBlockShow !== visible) {
if (visible) {
// Show the cell, the rest of the function will add on correct collapse state
newCellVM.inputBlockShow = true;
} else {
// Hide this cell
newCellVM.inputBlockShow = false;
}
}
// No elseif as we want newly visible cells to pick up the correct expand / collapse state
if (cellVM.inputBlockOpen !== expanded && cellVM.inputBlockCollapseNeeded && cellVM.inputBlockShow) {
if (expanded) {
// Expand the cell
const newText = extractInputText(cellVM.cell, getSettings());
newCellVM.inputBlockOpen = true;
newCellVM.inputBlockText = newText;
} else {
// Collapse the cell
let newText = extractInputText(cellVM.cell, getSettings());
if (newText.length > 0) {
newText = newText.split('\n', 1)[0];
newText = newText.slice(0, 255); // Slice to limit length, slicing past length is fine
newText = newText.concat('...');
}
newCellVM.inputBlockOpen = false;
newCellVM.inputBlockText = newText;
}
}
return newCellVM;
}
return cellVM;
}
private sendInfo = (cellVMs: ICellViewModel[]) => {
const visibleCells = cellVMs.filter(vm => !vm.editable).map(vm => vm.cell);
const info : IInteractiveWindowInfo = {
cellCount: visibleCells.length,
undoCount: this.state.undoStack.length,
redoCount: this.state.redoStack.length,
visibleCells: visibleCells
};
this.sendMessage(InteractiveWindowMessages.SendInfo, info);
}
private updateOrAdd = (cell: ICell, allowAdd? : boolean) => {
const index = this.state.cellVMs.findIndex((c : ICellViewModel) => {
return c.cell.id === cell.id &&
c.cell.line === cell.line &&
c.cell.file === cell.file;
});
if (index >= 0) {
// This means the cell existed already so it was actual executed code.
// Use its execution count to update our execution count.
const newExecutionCount = cell.data.execution_count ?
Math.max(this.state.currentExecutionCount, parseInt(cell.data.execution_count.toString(), 10)) :
this.state.currentExecutionCount;
if (newExecutionCount !== this.state.currentExecutionCount) {
// We also need to update our variable explorer when the execution count changes
// Use the ref here to maintain var explorer independence
if (this.variableExplorerRef.current && this.variableExplorerRef.current.state.open) {
this.refreshVariables(newExecutionCount);
}
}
// Update our state but only the cell vms.
const newVMs = [...this.state.cellVMs];
newVMs[index].cell = cell;
this.setState({
cellVMs : newVMs,
currentExecutionCount : newExecutionCount
});
} else if (allowAdd) {
// This is an entirely new cell (it may have started out as finished)
this.addCell(cell);
}
}
private isCellSupported(cell: ICell) : boolean {
return !this.props.testMode || cell.data.cell_type !== 'messages';
}
// tslint:disable-next-line:no-any
private finishCell = (payload?: any) => {
if (payload) {
const cell = payload as ICell;
if (cell && this.isCellSupported(cell)) {
this.updateOrAdd(cell, true);
// Update info as we have a finished cell now.
this.sendInfo(this.state.cellVMs);
}
}
}
// tslint:disable-next-line:no-any
private startCell = (payload?: any) => {
if (payload) {
const cell = payload as ICell;
if (cell && this.isCellSupported(cell)) {
this.updateOrAdd(cell, true);
}
}
}
// tslint:disable-next-line:no-any
private updateCell = (payload?: any) => {
if (payload) {
const cell = payload as ICell;
if (cell && this.isCellSupported(cell)) {
this.updateOrAdd(cell, false);
}
}
}
private getInputExecutionCount = () : number => {
return this.state.currentExecutionCount + 1;
}
private submitInput = (code: string) => {
// This should be from our last entry. Switch this entry to read only, and add a new item to our list
let editCell = this.getEditCell();
if (editCell) {
// Change this editable cell to not editable.
editCell.cell.state = CellState.executing;
editCell.cell.data.source = code;
// Change type to markdown if necessary
const split = code.splitLines({trim: false});
const firstLine = split[0];
const matcher = new CellMatcher(getSettings());
if (matcher.isMarkdown(firstLine)) {
editCell.cell.data.cell_type = 'markdown';
editCell.cell.data.source = generateMarkdownFromCodeLines(split);
editCell.cell.state = CellState.finished;
}
// Update input controls (always show expanded since we just edited it.)
editCell = createCellVM(editCell.cell, getSettings(), this.inputBlockToggled);
const collapseInputs = getSettings().collapseCellInputCodeByDefault;
editCell = this.alterCellVM(editCell, true, !collapseInputs);
// Generate a new id (as the edit cell always has the same one)
editCell.cell.id = uuid();
// Indicate this is direct input so that we don't hide it if the user has
// hide all inputs turned on.
editCell.directInput = true;
// Stick in a new cell at the bottom that's editable and update our state
// so that the last cell becomes busy
this.setState({
cellVMs: [...this.state.cellVMs, editCell],
editCellVM: createEditableCellVM(this.getInputExecutionCount()),
undoStack : this.pushStack(this.state.undoStack, this.state.cellVMs),
redoStack: this.state.redoStack,
skipNextScroll: false,
submittedText: true
});
// Send a message to execute this code if necessary.
if (editCell.cell.state !== CellState.finished) {
this.sendMessage(InteractiveWindowMessages.SubmitNewCell, { code, id: editCell.cell.id });
}
}
}
private variableExplorerToggled = (open: boolean) => {
this.sendMessage(InteractiveWindowMessages.VariableExplorerToggle, open);
}
// When the variable explorer wants to refresh state (say if it was expanded)
private refreshVariables = (newExecutionCount?: number) => {
this.sendMessage(InteractiveWindowMessages.GetVariablesRequest, newExecutionCount === undefined ? this.state.currentExecutionCount : newExecutionCount);
}
// Find the display value for one specific variable
private refreshVariable = (targetVar: IJupyterVariable) => {
this.sendMessage(InteractiveWindowMessages.GetVariableValueRequest, targetVar);
}
// When we get a variable value back use the ref to pass to the variable explorer
// tslint:disable-next-line:no-any
private getVariableValueResponse = (payload?: any) => {
if (payload) {
const variable = payload as IJupyterVariable;
// Only send the updated variable data if we are on the same execution count as when we requsted it
if (variable && variable.executionCount !== undefined && variable.executionCount === this.state.currentExecutionCount) {
if (this.variableExplorerRef.current) {
this.variableExplorerRef.current.newVariableData(variable);
}
}
}
}