-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.tsx
472 lines (427 loc) · 12.7 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/**
* @class ReactConsole
*/
import React, { CSSProperties } from 'react'
import classnames from 'classnames'
import styles from './styles.css'
// @ts-ignore
const isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
type CommandsProp = {
[command: string]: {
description?: string,
fn: (...args: any[]) => Promise<any>
}
}
export type ReactConsoleProps = {
// general props
commands: CommandsProp,
noCommandFound: (...str: string[]) => Promise<string>,
autoFocus: boolean,
prompt: string,
welcomeMessage?: string | undefined,
// className props
wrapperClassName?: string,
promptWrapperClassName?: string,
promptClassName?: string,
lineClassName?: string,
inputClassName?: string,
// style props
wrapperStyle: CSSProperties,
promptWrapperStyle: CSSProperties,
promptStyle: CSSProperties,
lineStyle: CSSProperties,
inputStyle: CSSProperties,
// history props
history?: string[],
onAddHistoryItem?: (entry: string) => void,
onSanitizeOutputLine?: (line: string) => string,
}
type ReactConsoleState = {
output: string[],
commandInProgress: boolean,
input: string,
historyPosition: number,
reverseSearchString?: string,
reverseSearchPosition: number,
}
export default class ReactConsole extends React.Component<ReactConsoleProps, ReactConsoleState> {
inputRef: any = null;
wrapperRef: any = null;
reverseStringRef: any = null;
static defaultProps = {
prompt: '$',
autoFocus: false,
noCommandFound: (cmd: string) => Promise.resolve(`Command ${cmd} does not exist`),
wrapperStyle: {},
promptWrapperStyle: {},
promptStyle: {},
lineStyle: {},
inputStyle: {},
};
state = {
input: '',
output: [],
commandInProgress: false,
reverseSearchString: undefined,
historyPosition: Infinity,
reverseSearchPosition: Infinity,
};
componentDidMount() {
const {welcomeMessage} = this.props;
if (welcomeMessage) {
this.setState({
output: [welcomeMessage],
})
}
if (this.props.history !== undefined) {
this.setState({
historyPosition: this.props.history.length,
})
}
}
public clear = () => {
this.setState({output: [], input: ''})
};
public scrollToBottom = () => {
setTimeout(() => {
this.wrapperRef.scrollTop = this.wrapperRef.scrollHeight
})
};
/**
* Get filtered history entries based on reverse search string
*/
private getReverseHistory = (): Array<boolean> => {
const {reverseSearchString} = this.state;
return this.props.history === undefined ?
[]
: this.props.history.map(entry => (reverseSearchString === undefined || reverseSearchString === '') ?
// @ts-ignore
false : entry.indexOf(reverseSearchString) !== -1)
};
/**
* Takes current text of a main input and generates a string that will be outputted as a log.
* @param input the input string provided to the control; when omitted, retrieves from state.input
*/
private getCurrentTextSnapshot = (input:string): string => {
const {prompt} = this.props;
const inputString: string = input;
return `${prompt}\xa0${inputString}`;
};
/**
* Accept an external command to run, and run it as if it were entered directly on the console
* @param input command to run
* @returns completion promise
*/
public handleInput = async (input:string) => {
return this.onProcessInput(input);
}
/**
* Process input submitted from the input control
* @param e input control reference
* @returns completion promise
*/
private onSubmit = async (e:any) => {
e.preventDefault(); // stop event bubbling
return this.onProcessInput(this.state.input);
}
/**
* Process input (from any source) and execute it as a command
* @param inputString command input string
* @returns completiong promise
*/
private onProcessInput = async (inputString:string) => {
if (inputString === null) {
return
}
const log = this.getCurrentTextSnapshot(inputString);
if (inputString === '') {
this.setState({
output: [...this.state.output, log],
input: '',
});
this.scrollToBottom();
return
}
this.addHistoryEntry(inputString);
const [cmd, ...args] = inputString.split(" ");
if (cmd === 'clear') {
this.clear();
return
}
const command = this.props.commands[cmd];
this.setState({commandInProgress: true});
if (command) {
const ret = await command.fn(...args);
this.setState({
output: [...this.state.output, log, ret]
})
} else {
const cmdNotFound = await this.props.noCommandFound(cmd, ...args);
this.setState({
output: [...this.state.output, log, cmdNotFound]
})
}
this.setState({commandInProgress: false, input: ''});
this.inputRef.focus()
this.scrollToBottom()
};
render() {
const {
wrapperClassName,
promptWrapperClassName,
promptClassName,
lineClassName,
inputClassName,
wrapperStyle,
promptWrapperStyle,
promptStyle,
lineStyle,
inputStyle,
prompt,
autoFocus,
} = this.props;
const sanitizeOutputLine = (line: string): string => {
const {onSanitizeOutputLine} = this.props;
if (typeof onSanitizeOutputLine === 'function') {
return onSanitizeOutputLine(line)
}
return line
}
return (
<div
className={classnames(styles.wrapper, wrapperClassName)}
style={{
overflowY: isIE11 ? "scroll" : "auto",
...wrapperStyle,
}}
onClick={this.focusConsole}
ref={ref => this.wrapperRef = ref}
>
<div>
{this.state.output
.map(line => sanitizeOutputLine(line))
.map((line, key) =>
<pre
key={key}
className={classnames(styles.line, lineClassName)}
style={lineStyle}
dangerouslySetInnerHTML={{__html: line}}
/>
)}
</div>
<form
onSubmit={this.onSubmit}
>
<div
className={classnames(styles.promptWrapper, promptWrapperClassName)}
style={promptWrapperStyle}
>
<span
className={classnames(styles.prompt, promptClassName)}
style={promptStyle}
>{prompt} </span>
<input
disabled={this.state.commandInProgress || this.isReverseSearchOn()}
ref={ref => this.inputRef = ref}
autoFocus={autoFocus}
value={this.state.input}
onChange={this.onInputChange}
onKeyDown={this.onKeyDown}
autoComplete={'off'}
spellCheck={false}
autoCapitalize={'false'}
name="input"
className={classnames([styles.input, inputClassName])}
style={inputStyle}
/>
</div>
</form>
{this.isReverseSearchOn() && <form onSubmit={this.onReverseSearchSubmit}>bck-i-search: <input
value={this.state.reverseSearchString}
ref={ref => this.reverseStringRef = ref}
onKeyDown={this.onReverseKeyDown}
className={classnames([styles.input, inputClassName])}
onChange={this.onReverseStringInputChange}
/>
</form>}
</div>
)
}
/**
* Reverse search input handler
* @param event
*/
private onReverseStringInputChange = (event: any) => {
this.setState({
reverseSearchString: event.target.value,
}, () => {
const history: Array<boolean> = this.getReverseHistory();
const historyIndex: number = history.lastIndexOf(true);
this.executeNextReverseSearch(historyIndex)
})
};
/**
* Invoked when pressed ctrl+r and already in a reverse search mode.
*/
private nextReverseSearch = () => {
const history: Array<boolean> = this.getReverseHistory();
const endOffset = Math.max(0, this.state.reverseSearchPosition - 1); // so that we don't go from the end again
const historyIndex: number = history.lastIndexOf(true, endOffset);
this.executeNextReverseSearch(historyIndex)
};
/**
* Helper function that sets the history preview based on a requested history index.
* @param historyIndex
*/
private executeNextReverseSearch = (historyIndex: number) => {
this.setState({
reverseSearchPosition: historyIndex,
});
if (historyIndex !== -1) {
this.setPreviewPosition(historyIndex)
}
if (this.state.reverseSearchString === '') {
this.setPreviewPosition(Infinity);
}
};
/**
* This function sets a given history entry as a main input element content.
* It's called when changing the preview of a 'current' history entry e.g. by ctrl+r call, or
* when pressing up/down arrow.
* @param historyPosition
*/
private setPreviewPosition = (historyPosition: number) => {
if(this.props.history === undefined) {
return
}
this.setState({
historyPosition,
input: this.props.history[historyPosition] || '', // if an element history is out of bounds, we just set ''
});
};
/**
* Enables reverse search.
* The side effect is that we focus o reverse search input.
*/
private onReverseSearch = () => {
// we enabled reverse search
this.setState({
reverseSearchString: '',
}, () => {
this.reverseStringRef.focus()
})
};
/**
* When reverse search is confirmed, we disable reverse search mode and keep the result.
* @param e
*/
private onReverseSearchSubmit = (event: any) => {
event.preventDefault();
this.disableReverseSearch();
};
/**
* Main input change handler.
* @param event
*/
private onInputChange = (event: any) => {
this.setState({
input: event.target.value,
})
};
/**
* Helper function to determine whether reverse search is active or not.
*/
private isReverseSearchOn = (): boolean => this.state.reverseSearchString !== undefined;
/**
* Disables reverse search mode.
* @param keepPreviewString - determines whether the result of a reverse search should be kept or not
*/
private disableReverseSearch = (keepPreviewString: boolean = true) => {
this.setState({
reverseSearchString: undefined,
});
if (!keepPreviewString) {
this.setState({
input: '',
})
}
setTimeout(() => {
this.inputRef.focus();
});
};
/**
* onKeyDown implementation of a reverse search input.
* @param event
*/
private onReverseKeyDown = (event: any) => {
if (event.which === 38 || event.which === 40) { // up or down
this.disableReverseSearch()
event.preventDefault();
} else if (event.which === 67 && event.ctrlKey) { // ctrl + c
this.disableReverseSearch(false);
event.preventDefault();
} else if (event.which === 82 && event.ctrlKey) { // ctrl + r
this.nextReverseSearch();
event.preventDefault();
}
};
/**
* onKeyDown implementation of a main input.
* @param event
*/
private onKeyDown = (event: any) => {
if (event.which === 38) { // key up
if(this.props.history === undefined) {
return
}
const currentPos = Math.min(this.state.historyPosition, this.props.history.length);
const historyPosition = Math.max(0, currentPos - 1);
this.setPreviewPosition(historyPosition);
event.preventDefault()
} else if (event.which === 40) {
if(this.props.history === undefined) {
return
}
const historyPosition = Math.min(this.props.history.length, this.state.historyPosition + 1);
this.setPreviewPosition(historyPosition);
event.preventDefault()
} else if (event.which === 82 && event.ctrlKey) { // ctrl + r
if(this.props.history === undefined) {
return
}
this.onReverseSearch()
event.preventDefault()
} else if (event.which === 67 && event.ctrlKey) { // ctrl + c
this.setState({
output: [...this.state.output, this.getCurrentTextSnapshot(this.state.input)],
input: '',
});
this.scrollToBottom();
event.preventDefault()
}
};
/**
* Focuses console input.
* Whenever an user clicks on a terminal, we want to focus an actual input where he/she can type.
*/
public focusConsole = () => {
if (this.inputRef) {
if (document.getSelection()!.isCollapsed) {
this.inputRef.focus()
}
}
};
/**
* Calls onAddHistoryItem property and sets historyPosition to a default value.
* @param inputString
*/
private addHistoryEntry = (inputString: string) => {
const {onAddHistoryItem} = this.props;
if (typeof onAddHistoryItem === 'function') {
onAddHistoryItem(inputString);
}
this.setState({
historyPosition: Infinity,
})
}
}