forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.tsx
More file actions
305 lines (270 loc) · 11.5 KB
/
code.tsx
File metadata and controls
305 lines (270 loc) · 11.5 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/python/python';
import * as CodeMirror from 'codemirror';
import * as React from 'react';
import * as RCM from 'react-codemirror';
import './code.css';
import { getLocString } from '../react-common/locReactSide';
import { Cursor } from './cursor';
import { InputHistory } from './inputHistory';
export interface ICodeProps {
autoFocus: boolean;
code : string;
codeTheme: string;
testMode: boolean;
readOnly: boolean;
history: InputHistory | undefined;
cursorType: string;
showWatermark: boolean;
onSubmit(code: string): void;
onChangeLineCount(lineCount: number) : void;
}
interface ICodeState {
focused: boolean;
cursorLeft: number;
cursorTop: number;
cursorBottom: number;
charUnderCursor: string;
allowWatermark: boolean;
}
export class Code extends React.Component<ICodeProps, ICodeState> {
private codeMirror: CodeMirror.Editor | undefined;
private codeMirrorOwner: HTMLDivElement | undefined;
private baseIndentation : number | undefined;
constructor(prop: ICodeProps) {
super(prop);
this.state = {focused: false, cursorLeft: 0, cursorTop: 0, cursorBottom: 0, charUnderCursor: '', allowWatermark: true};
}
public componentDidUpdate(prevProps: Readonly<ICodeProps>, _prevState: Readonly<ICodeState>, _snapshot?: {}) {
// Force our new value. the RCM control doesn't do this correctly
if (this.codeMirror && this.props.readOnly && this.codeMirror.getValue() !== this.props.code) {
this.codeMirror.setValue(this.props.code);
}
// If we are suddenly changing a readonly to not, somebody is reusing a different control. Update
// to be empty
if (this.codeMirror && !this.props.readOnly && prevProps.readOnly) {
this.codeMirror.setOption('readOnly', false);
this.codeMirror.setValue('');
}
}
public componentWillUnmount() {
if (this.codeMirrorOwner) {
const activeElement = document.activeElement as HTMLElement;
if (activeElement && this.codeMirrorOwner.contains(activeElement)) {
activeElement.blur();
}
}
}
public render() {
const readOnly = this.props.readOnly;
const classes = readOnly ? 'code-area' : 'code-area code-area-editable';
const waterMarkClass = this.props.showWatermark && this.state.allowWatermark && !readOnly ? 'code-watermark' : 'hide';
return (
<div className={classes} ref={this.updateRoot}>
<Cursor
hidden={readOnly}
codeInFocus={this.state.focused}
cursorType={this.props.cursorType}
text={this.state.charUnderCursor}
left={this.state.cursorLeft}
top={this.state.cursorTop}
bottom={this.state.cursorBottom}/>
<RCM
value={this.props.code}
autoFocus={this.props.autoFocus}
onChange={this.onChange}
options={
{
extraKeys:
{
Down: this.arrowDown,
Enter: this.enter,
'Shift-Enter': this.shiftEnter,
Up: this.arrowUp
},
theme: `${this.props.codeTheme} default`,
mode: 'python',
cursorBlinkRate: -1,
readOnly: readOnly ? true : false,
lineWrapping: true
}
}
ref={this.updateCodeMirror}
onFocusChange={this.onFocusChange}
onCursorActivity={this.onCursorActivity}
/>
<div className={waterMarkClass}>{this.getWatermarkString()}</div>
</div>
);
}
public onParentClick(ev: React.MouseEvent<HTMLDivElement>) {
const readOnly = this.props.testMode || this.props.readOnly;
if (this.codeMirror && !readOnly) {
ev.stopPropagation();
this.codeMirror.focus();
}
}
public giveFocus() {
const readOnly = this.props.testMode || this.props.readOnly;
if (this.codeMirror && !readOnly) {
this.codeMirror.focus();
}
}
private updateRoot = (div: HTMLDivElement) => {
this.codeMirrorOwner = div;
}
private getWatermarkString = () : string => {
return getLocString('DataScience.inputWatermark', 'Shift-enter to run');
}
private onCursorActivity = (codeMirror: CodeMirror.Editor) => {
// Update left/top/char for cursor
if (codeMirror) {
const doc = codeMirror.getDoc();
const selections = doc.listSelections();
const cursor = doc.getCursor();
const anchor = selections && selections.length > 0 ? selections[selections.length - 1].anchor : {ch: 10000, line: 10000};
const wantStart = cursor.line < anchor.line || cursor.line === anchor.line && cursor.ch < anchor.ch;
const coords = codeMirror.cursorCoords(wantStart, 'local');
const char = this.getCursorChar();
this.setState({
cursorLeft: coords.left,
cursorTop: coords.top,
cursorBottom: coords.bottom,
charUnderCursor: char
});
}
}
private getCursorChar = () : string => {
if (this.codeMirror) {
const doc = this.codeMirror.getDoc();
const cursorPos = doc.getCursor();
const line = doc.getLine(cursorPos.line);
if (line.length > cursorPos.ch) {
return line.slice(cursorPos.ch, cursorPos.ch + 1);
}
}
// We don't need a state update on cursor change because
// we only really need this on focus change
return '';
}
private onFocusChange = (focused: boolean) => {
this.setState({focused});
}
private updateCodeMirror = (rcm: ReactCodeMirror.ReactCodeMirror) => {
if (rcm) {
this.codeMirror = rcm.getCodeMirror();
const coords = this.codeMirror.cursorCoords(false, 'local');
const char = this.getCursorChar();
this.setState({
cursorLeft: coords.left,
cursorTop: coords.top,
cursorBottom: coords.bottom,
charUnderCursor: char
});
}
}
private getBaseIndentation(instance: CodeMirror.Editor) : number {
if (!this.baseIndentation) {
const option = instance.getOption('indentUnit');
if (option) {
this.baseIndentation = parseInt(option.toString(), 10);
} else {
this.baseIndentation = 2;
}
}
return this.baseIndentation;
}
private expectedIndent(instance: CodeMirror.Editor, line: number) : number {
// Expected should be indent on the previous line and one more if line
// ends with :
const doc = instance.getDoc();
const baseIndent = this.getBaseIndentation(instance);
const lineStr = doc.getLine(line).trimRight();
const lastChar = lineStr.length === 0 ? null : lineStr.charAt(lineStr.length - 1);
const frontIndent = lineStr.length - lineStr.trimLeft().length;
return frontIndent + (lastChar === ':' ? baseIndent : 0);
}
private shiftEnter = (instance: CodeMirror.Editor) => {
// Shift enter is always submit (for now)
const doc = instance.getDoc();
// Double check we don't have an entirely empty document
if (doc.getValue('').trim().length > 0) {
let code = doc.getValue();
const isClean = doc.isClean();
// We have to clear the history as this CodeMirror doesn't go away.
doc.clearHistory();
doc.setValue('');
// Submit without the last extra line if we have one.
if (code.endsWith('\n\n')) {
code = code.slice(0, code.length - 1);
}
// Send to the input history too if necessary
if (this.props.history) {
this.props.history.add(code, !isClean);
}
this.props.onSubmit(code);
return;
}
}
private enter = (instance: CodeMirror.Editor) => {
// See if the cursor is at the end of a single line or if on an indented line. Any indent
// or line ends with : or ;\, then don't submit
const doc = instance.getDoc();
const cursor = doc.getCursor();
const lastLine = doc.lastLine();
if (cursor.line === lastLine) {
// Check for any text
const line = doc.getLine(lastLine);
if (line.length === 0) {
// Do the same thing as shift+enter
this.shiftEnter(instance);
return;
}
}
// Otherwise add a line and indent the appropriate amount
const cursorLine = doc.getLine(cursor.line);
const afterCursor = cursorLine.slice(cursor.ch).trim();
const expectedIndents = this.expectedIndent(instance, cursor.line);
const indentString = Array(expectedIndents + 1).join(' ');
doc.replaceRange(`\n${indentString}`, { line: cursor.line, ch: afterCursor.length === 0 ? doc.getLine(cursor.line).length : cursor.ch });
doc.setCursor({line: cursor.line + 1, ch: indentString.length });
// Tell our listener we added a new line
this.props.onChangeLineCount(doc.lineCount());
}
private arrowUp = (instance: CodeMirror.Editor) => {
const doc = instance.getDoc();
const cursor = doc ? doc.getCursor() : undefined;
if (cursor && cursor.line === 0 && this.props.history) {
const currentValue = doc.getValue();
const newValue = this.props.history.completeUp(currentValue);
if (newValue !== currentValue) {
doc.setValue(newValue);
doc.setCursor(0, doc.getLine(0).length);
doc.markClean();
}
return;
}
return CodeMirror.Pass;
}
private arrowDown = (instance: CodeMirror.Editor) => {
const doc = instance.getDoc();
const cursor = doc ? doc.getCursor() : undefined;
if (cursor && cursor.line === doc.lastLine() && this.props.history) {
const currentValue = doc.getValue();
const newValue = this.props.history.completeDown(currentValue);
if (newValue !== currentValue) {
doc.setValue(newValue);
doc.setCursor(doc.lastLine(), doc.getLine(doc.lastLine()).length);
doc.markClean();
}
return;
}
return CodeMirror.Pass;
}
private onChange = (_newValue: string, _change: CodeMirror.EditorChange) => {
this.setState({allowWatermark: false});
}
}