-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoutput.tsx
More file actions
238 lines (210 loc) Β· 6.96 KB
/
output.tsx
File metadata and controls
238 lines (210 loc) Β· 6.96 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
import * as React from 'react';
import { autorun, reaction } from 'mobx';
import { observer } from 'mobx-react';
import * as MonacoType from 'monaco-editor';
import {
MosaicContext,
MosaicNode,
MosaicParent,
} from 'react-mosaic-component';
import { WrapperEditorId } from './output-editors-wrapper';
import { OutputEntry } from '../../interfaces';
import { AppState } from '../state';
interface CommandsProps {
readonly appState: AppState;
readonly monaco: typeof MonacoType;
monacoOptions: MonacoType.editor.IEditorOptions;
// Used to keep testing conform
renderTimestamp?: (ts: number) => string;
}
/**
* This component represents the "console" that is shown
* whenever a Fiddle is launched in Electron.
*/
export const Output = observer(
class Output extends React.Component<CommandsProps> {
public static contextType = MosaicContext;
public context: MosaicContext<WrapperEditorId>;
public editor?: MonacoType.editor.IStandaloneCodeEditor;
public language = 'consoleOutputLanguage';
private outputRef = React.createRef<HTMLDivElement>();
private readonly model: MonacoType.editor.ITextModel;
// make it wide enough to fit all of OutputEntry's timestamps
private readonly lineNumbersMinChars =
new Date('2021-12-31T23:59:59').toLocaleTimeString().length + 1;
constructor(props: CommandsProps) {
super(props);
const { monaco } = this.props;
this.language = 'consoleOutputLanguage';
this.model = monaco.editor.createModel('', this.language);
this.updateModel();
reaction(
() => props.appState.output.length,
() => this.updateModel(),
);
}
public async componentDidMount() {
autorun(async () => {
await this.initMonaco();
this.toggleConsole();
});
}
public componentWillUnmount() {
this.destroyMonacoEditor();
}
public componentDidUpdate() {
this.toggleConsole();
}
/**
* Initialize Monaco.
*/
public async initMonaco() {
const { monaco, monacoOptions: monacoOptions } = this.props;
const ref = this.outputRef.current;
if (ref) {
this.setupCustomOutputEditorLanguage(monaco);
this.editor = monaco.editor.create(
ref,
{
language: this.language,
theme: 'main',
readOnly: true,
contextmenu: false,
automaticLayout: true,
model: this.model,
...monacoOptions,
wordWrap: 'on',
},
{
openerService: this.openerService(),
},
);
this.editor.addCommand(
monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_K,
() => {
this.props.appState.clearConsole();
this.props.appState.output.push({
timeString: new Date().toLocaleTimeString(),
text: '',
});
},
);
}
}
/**
* Destroy Monaco.
*/
public destroyMonacoEditor() {
if (typeof this.editor !== 'undefined') {
console.log('Editor: Disposing');
this.editor.dispose();
delete this.editor;
}
}
public toggleConsole() {
/**
* Type guard to check whether a react-mosaic node is a parent in the tree
* or a leaf. Leaf nodes are represented by the string value of their ID,
* whereas parent nodes are objects containing information about the nested
* binary tree.
* @param node - A react-mosaic node
* @returns Whether that node is a MosaicParent or not
*/
const isParentNode = (
node: MosaicNode<WrapperEditorId> | null,
): node is MosaicParent<WrapperEditorId> => {
return (node as MosaicParent<WrapperEditorId>)?.direction !== undefined;
};
const { isConsoleShowing } = this.props.appState;
if (this.context.mosaicActions) {
const mosaicTree = this.context.mosaicActions.getRoot();
if (isParentNode(mosaicTree)) {
// splitPercentage defines the percentage of space the first panel takes
// e.g. 25 would mean the two children panels are split 25%/75%
if (!isConsoleShowing) {
mosaicTree.splitPercentage = 0;
} else if (mosaicTree.splitPercentage === 0) {
mosaicTree.splitPercentage = 25;
}
this.context.mosaicActions.replaceWith([], mosaicTree);
}
}
}
/**
* Set up Monaco Language to catch custom regex expressions
*
* tokenizes timestamps so`main` theme can render them with a custom colour.
*/
private setupCustomOutputEditorLanguage(monaco: typeof MonacoType) {
// register a new language
monaco.languages.register({ id: 'consoleOutputLanguage' });
// Register a tokens provider for the language
monaco.languages.setMonarchTokensProvider('consoleOutputLanguage', {
tokenizer: {
root: [[/\d{1,2}:\d{2}:\d{2}\s(A|P)M/, 'custom-date']],
},
});
}
/**
* Sets the model and content on the editor
*/
private async updateModel() {
// set the lines
const lines = Output.getLines(this.props.appState.output);
this.model.setValue(lines.map(({ text }) => text).join('\n'));
// if we have an editor, tell it the line numbers and scroll to newest
const { editor, lineNumbersMinChars } = this;
if (!editor) return;
const timestrs = lines.map(({ timeString }) => timeString);
// adjust `i` here because the value passed in by monaco starts at 1, not 0
const lineNumbers = (i: number) => timestrs[i - 1] || '';
editor.updateOptions({ lineNumbers, lineNumbersMinChars });
editor.revealLine(editor.getScrollHeight());
}
/**
* An OutputEntry might span multiple lines.
* Split it into individual lines to ensure each one has a timestamp.
*
* @param entries - that may include paragraphs
* @returns single-line entries
*/
private static getLines(paragraphs: OutputEntry[]): OutputEntry[] {
const lines: OutputEntry[] = [];
paragraphs = paragraphs.slice(-1000);
for (const { text, timeString } of paragraphs) {
for (const line of text.split(/\r?\n/)) {
lines.push({ text: line, timeString });
}
}
return lines;
}
/**
* Implements external url handling for Monaco.
*/
private openerService() {
const { appState } = this.props;
return {
open: (url: string) => {
appState
.showConfirmDialog({
label: `Open ${url} in external browser?`,
ok: 'Open',
})
.then((open) => {
if (open) window.open(url);
});
},
};
}
public render(): JSX.Element | null {
const { isConsoleShowing } = this.props.appState;
return (
<div
className="output"
ref={this.outputRef}
style={{ display: 'none' }}
/>
);
}
},
);