-
Notifications
You must be signed in to change notification settings - Fork 756
Expand file tree
/
Copy pathapp.tsx
More file actions
337 lines (292 loc) · 9.14 KB
/
app.tsx
File metadata and controls
337 lines (292 loc) · 9.14 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
import { autorun, reaction, when } from 'mobx';
import { ElectronTypes } from './electron-types';
import { FileManager } from './file-manager';
import { RemoteLoader } from './remote-loader';
import { Runner } from './runner';
import { AppState } from './state';
import { TaskRunner } from './task-runner';
import { activateTheme, getTheme } from './themes';
import { getPackageJson } from './utils/get-package';
import { getElectronVersions } from './versions';
import {
EditorId,
EditorValues,
PACKAGE_NAME,
PackageJsonOptions,
SetFiddleOptions,
Version,
} from '../interfaces';
import { defaultDark, defaultLight } from '../themes-defaults';
// Importing styles files
import '../less/root.less';
/**
* The top-level class controlling the whole app. This is *not* a React component,
* but it does eventually render all components.
*/
export class App {
public state = new AppState(getElectronVersions());
public fileManager = new FileManager(this.state);
public remoteLoader = new RemoteLoader(this.state);
public runner = new Runner(this.state);
public readonly taskRunner: TaskRunner;
public readonly electronTypes: ElectronTypes;
constructor() {
this.getEditorValues = this.getEditorValues.bind(this);
this.taskRunner = new TaskRunner(this);
this.electronTypes = new ElectronTypes(window.monaco);
}
private confirmReplaceUnsaved(): Promise<boolean> {
return this.state.showConfirmDialog({
label: `Opening this Fiddle will replace your unsaved changes. Do you want to proceed?`,
ok: 'Open',
});
}
private confirmExitUnsaved(): Promise<boolean> {
return this.state.showConfirmDialog({
label: 'The current Fiddle is unsaved. Do you want to exit anyway?',
ok: 'Exit',
});
}
public async replaceFiddle(
editorValues: EditorValues,
{ localFiddle, gistId, templateName }: Partial<SetFiddleOptions>,
) {
const { state } = this;
const { editorMosaic } = state;
if (editorMosaic.isEdited && !(await this.confirmReplaceUnsaved())) {
return false;
}
this.state.editorMosaic.set(editorValues);
this.state.gistId = gistId || '';
this.state.localPath = localFiddle?.filePath;
this.state.templateName = templateName;
// update menu when a new Fiddle is loaded
window.ElectronFiddle.setShowMeTemplate(templateName);
return true;
}
/**
* Retrieves the contents of all editor panes.
*/
public async getEditorValues(
options?: PackageJsonOptions,
): Promise<EditorValues> {
const values = this.state.editorMosaic.values();
if (options) {
values[PACKAGE_NAME as EditorId] = await getPackageJson(
this.state,
options,
);
}
return values;
}
/**
* Initial setup call, loading Monaco and kicking off the React
* render process.
*/
public async setup(): Promise<void | Element | React.Component> {
await this.loadTheme(this.state.theme || '');
const [
{ default: React },
{ render },
{ Dialogs },
{ OutputEditorsWrapper },
{ Header },
] = await Promise.all([
import('react'),
import('react-dom'),
import('./components/dialogs'),
import('./components/output-editors-wrapper'),
import('./components/header'),
]);
// The AppState constructor started loading a fiddle.
// Wait for it here so the UI doesn't start life in `nonIdealState`.
await when(() => this.state.editorMosaic.files.size !== 0);
const app = (
<div className="container">
<Header appState={this.state} />
<OutputEditorsWrapper appState={this.state} />
<Dialogs appState={this.state} />
</div>
);
const rendered = render(app, document.getElementById('app'));
this.setupResizeListener();
this.setupOfflineListener();
this.setupThemeListeners();
this.setupTitleListeners();
this.setupUnloadListeners();
this.setupTypeListeners();
this.setupProtocolListeners();
window.ElectronFiddle.sendReady();
window.ElectronFiddle.addEventListener('set-show-me-template', () => {
window.ElectronFiddle.setShowMeTemplate(this.state.templateName);
});
return rendered;
}
private setupTypeListeners() {
const updateTypes = () =>
this.electronTypes.setVersion(this.state.currentElectronVersion);
reaction(
() => this.state.version,
() => updateTypes(),
);
updateTypes();
}
public async setupThemeListeners() {
const setSystemTheme = (prefersDark: boolean) => {
if (prefersDark) {
this.state.setTheme(defaultDark.file);
} else {
this.state.setTheme(defaultLight.file);
}
};
// match theme to system when box is ticked
reaction(
() => this.state.isUsingSystemTheme,
() => {
if (this.state.isUsingSystemTheme) {
window.ElectronFiddle.setNativeTheme('system');
if (!!window.matchMedia) {
const { matches } = window.matchMedia(
'(prefers-color-scheme: dark)',
);
setSystemTheme(matches);
}
}
},
);
// change theme when system theme changes
if (!!window.matchMedia) {
window
.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', ({ matches }) => {
if (this.state.isUsingSystemTheme) {
setSystemTheme(matches);
}
});
}
}
/**
* Opens a fiddle from the specified location.
*
* @param fiddle - The fiddle to open
*/
public async openFiddle(fiddle: SetFiddleOptions) {
const { localFiddle, gistId } = fiddle;
if (localFiddle) {
await this.fileManager.openFiddle(
localFiddle.filePath,
localFiddle.files,
);
} else if (gistId) {
await this.remoteLoader.fetchGistAndLoad(gistId);
}
}
/**
* Loads theme CSS into the HTML document.
*/
public async loadTheme(name: string): Promise<void> {
const tag: HTMLStyleElement | null =
document.querySelector('style#fiddle-theme');
const theme = await getTheme(name);
activateTheme(theme);
if (tag && theme.css) {
tag.innerHTML = theme.css;
}
if (theme.isDark || theme.name.includes('dark')) {
document.body.classList.add('bp3-dark');
if (!this.state.isUsingSystemTheme) {
window.ElectronFiddle.setNativeTheme('dark');
}
} else {
document.body.classList.remove('bp3-dark');
if (!this.state.isUsingSystemTheme) {
window.ElectronFiddle.setNativeTheme('light');
}
}
}
public setupOfflineListener(): void {
window.addEventListener('online', async () => {
this.state.isOnline = true;
this.state.setVersion(this.state.version);
});
window.addEventListener('offline', () => {
this.state.isOnline = false;
});
}
/**
* We need to possibly recalculate the layout whenever the window
* is resized. This method sets up the listener.
*/
public setupResizeListener(): void {
window.addEventListener('resize', this.state.editorMosaic.layout);
}
/**
* Have document.title track state.title
*/
public setupTitleListeners() {
// the observables used for the title usually change in a batch,
// so when setting document title, wait a tick to avoid flicker.
let titleIdle: any;
reaction(
() => this.state.title,
(title) => {
clearTimeout(titleIdle);
titleIdle = setTimeout(() => {
document.title = title;
titleIdle = null;
});
},
);
}
public setupUnloadListeners() {
autorun(async () => {
const { state } = this;
const { editorMosaic } = state;
if (!editorMosaic.isEdited) {
window.onbeforeunload = null;
return;
}
window.onbeforeunload = (e: BeforeUnloadEvent) => {
// On Mac OS, quitting can be triggered from the dock,
// show the window so the dialog is visible
setTimeout(() => {
this.confirmExitUnsaved().then((quit) => {
if (quit) {
// isQuitting checks if we're trying to quit the app
// or just close the window
if (state.isQuitting) {
window.ElectronFiddle.confirmQuit();
}
window.onbeforeunload = null;
window.close();
} else {
state.isQuitting = false;
}
});
window.ElectronFiddle.showWindow();
});
// return value doesn't matter, we just want to cancel the event
e.returnValue = false;
};
});
}
public setupProtocolListeners() {
window.ElectronFiddle.addEventListener(
'register-local-version',
async ({ name, path, version }) => {
const confirm = await this.state.showConfirmDialog({
label: `Are you sure you want to register "${path}" with version "${version}"? Only register and run it if you trust the source.`,
ok: 'Register',
});
if (!confirm) return;
const toAdd: Version = {
localPath: path,
version,
name,
};
this.state.addLocalVersion(toAdd);
this.state.setVersion(version);
},
);
}
}