-
Notifications
You must be signed in to change notification settings - Fork 717
/
Copy pathstate.ts
1213 lines (1084 loc) · 36.9 KB
/
state.ts
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
import {
action,
autorun,
computed,
makeObservable,
observable,
runInAction,
when,
} from 'mobx';
import { Bisector } from './bisect';
import { EditorMosaic } from './editor-mosaic';
import { ELECTRON_MIRROR } from './mirror-constants';
import { normalizeVersion } from './utils/normalize-version';
import { sortVersions } from './utils/sort-versions';
import {
addLocalVersion,
fetchVersions,
getDefaultVersion,
getElectronVersions,
getLocalVersions,
getReleaseChannel,
makeRunnable,
saveLocalVersions,
} from './versions';
import {
AppStateBroadcastChannel,
AppStateBroadcastMessage,
AppStateBroadcastMessageType,
BlockableAccelerator,
ElectronReleaseChannel,
GenericDialogOptions,
GenericDialogType,
GistActionState,
GlobalSetting,
IPackageManager,
InstallState,
OutputEntry,
OutputOptions,
ProgressObject,
RunnableVersion,
SetFiddleOptions,
Version,
VersionSource,
WindowSpecificSetting,
} from '../interfaces';
/**
* The application's state. Exported as a singleton below.
*/
export class AppState {
private readonly timeFmt = new Intl.DateTimeFormat([], {
timeStyle: 'medium',
});
private genericTypeGuard(_: never, errorMessage: string): never {
throw new Error(errorMessage);
}
// -- Persisted settings ------------------
public theme: string | null = localStorage.getItem(GlobalSetting.theme);
public gitHubAvatarUrl: string | null = localStorage.getItem(
GlobalSetting.gitHubAvatarUrl,
);
public gitHubName: string | null = localStorage.getItem(
GlobalSetting.gitHubName,
);
public gitHubLogin: string | null = localStorage.getItem(
GlobalSetting.gitHubLogin,
);
public gitHubToken: string | null =
localStorage.getItem(GlobalSetting.gitHubToken) || null;
public gitHubPublishAsPublic = !!this.retrieve(
WindowSpecificSetting.gitHubPublishAsPublic,
);
public channelsToShow: Array<ElectronReleaseChannel> = (this.retrieve(
GlobalSetting.channelsToShow,
) as Array<ElectronReleaseChannel>) || [
ElectronReleaseChannel.stable,
ElectronReleaseChannel.beta,
];
public showObsoleteVersions = !!(
this.retrieve(GlobalSetting.showObsoleteVersions) ?? false
);
public showUndownloadedVersions = !!(
this.retrieve(GlobalSetting.showUndownloadedVersions) ?? true
);
public isKeepingUserDataDirs = !!this.retrieve(
GlobalSetting.isKeepingUserDataDirs,
);
public isEnablingElectronLogging = !!this.retrieve(
GlobalSetting.isEnablingElectronLogging,
);
public isClearingConsoleOnRun = !!this.retrieve(
GlobalSetting.isClearingConsoleOnRun,
);
public isUsingSystemTheme = !!(
this.retrieve(GlobalSetting.isUsingSystemTheme) ?? true
);
public isPublishingGistAsRevision = !!(
this.retrieve(GlobalSetting.isPublishingGistAsRevision) ?? true
);
public executionFlags: Array<string> =
(this.retrieve(GlobalSetting.executionFlags) as Array<string>) === null
? []
: (this.retrieve(GlobalSetting.executionFlags) as Array<string>);
public environmentVariables: Array<string> =
(this.retrieve(GlobalSetting.environmentVariables) as Array<string>) ===
null
? []
: (this.retrieve(GlobalSetting.environmentVariables) as Array<string>);
public packageManager: IPackageManager =
(localStorage.getItem(GlobalSetting.packageManager) as IPackageManager) ||
'npm';
public acceleratorsToBlock: Array<BlockableAccelerator> =
(this.retrieve(
GlobalSetting.acceleratorsToBlock,
) as Array<BlockableAccelerator>) || [];
public packageAuthor =
(localStorage.getItem(GlobalSetting.packageAuthor) as string) ??
window.ElectronFiddle.getUsername();
public electronMirror: typeof ELECTRON_MIRROR =
(this.retrieve(GlobalSetting.electronMirror) as typeof ELECTRON_MIRROR) ===
null
? {
...ELECTRON_MIRROR,
sourceType: navigator.language === 'zh-CN' ? 'CHINA' : 'DEFAULT',
}
: (this.retrieve(GlobalSetting.electronMirror) as typeof ELECTRON_MIRROR);
public fontFamily: string | undefined =
(localStorage.getItem(GlobalSetting.fontFamily) as string) || undefined;
public fontSize: number | undefined =
parseInt(localStorage.getItem(GlobalSetting.fontSize)!) || undefined;
// -- Various session-only state ------------------
public gistId: string | undefined = undefined;
public readonly versions: Record<string, RunnableVersion> = {};
public version = '';
public output: Array<OutputEntry> = [];
public localPath: string | undefined = undefined;
public genericDialogOptions: GenericDialogOptions = {
type: GenericDialogType.warning,
label: '' as string | JSX.Element,
ok: 'Okay',
cancel: 'Cancel',
wantsInput: false,
placeholder: '',
};
public readonly editorMosaic = new EditorMosaic();
public genericDialogLastResult: boolean | null = null;
public genericDialogLastInput: string | null = null;
public templateName: string | undefined = undefined;
public Bisector: Bisector | undefined = undefined;
public modules: Map<string, string> = new Map();
public activeGistAction: GistActionState = GistActionState.none;
// -- Various "isShowing" settings ------------------
public isAddVersionDialogShowing = false;
public isAutoBisecting = false;
public isBisectCommandShowing = false;
public isBisectDialogShowing = false;
public isConsoleShowing = false;
public isGenericDialogShowing = false;
public isInstallingModules = false;
public isOnline = navigator.onLine;
public isQuitting = false;
public isRunning = false;
public isSettingsShowing = false;
public isThemeDialogShowing = false;
public isTokenDialogShowing = false;
public isTourShowing = !localStorage.getItem(GlobalSetting.hasShownTour);
public isUpdatingElectronVersions = false;
public isDownloadingAll = false;
public isDeletingAll = false;
// -- Editor Values stored when we close the editor ------------------
private outputBuffer = '';
private name: string;
private readonly defaultVersion: string;
public appData: string;
// Used for communications between windows
private broadcastChannel: AppStateBroadcastChannel = new BroadcastChannel(
'AppState',
);
// Notifies other windows that this version has changed so they can update their state to reflect that.
private broadcastVersionStates(versions: RunnableVersion[]) {
this.broadcastChannel.postMessage({
type: AppStateBroadcastMessageType.syncVersions,
// the RunnableVersion proxies can't be cloned by structuredClone,
// so we have to create plain objects out of them
payload: versions.map((version) => ({ ...version })),
});
}
constructor(versions: RunnableVersion[]) {
makeObservable<AppState, 'setPageHash' | 'setVersionStates'>(this, {
Bisector: observable,
acceleratorsToBlock: observable,
activeGistAction: observable,
addAcceleratorToBlock: action,
addLocalVersion: action,
addNewVersions: action,
channelsToShow: observable,
clearConsole: action,
currentElectronVersion: computed,
disableTour: action,
downloadVersion: action,
editorMosaic: observable,
electronMirror: observable,
environmentVariables: observable,
executionFlags: observable,
flushOutput: action,
fontFamily: observable,
fontSize: observable,
genericDialogLastInput: observable,
genericDialogLastResult: observable,
genericDialogOptions: observable,
gistId: observable,
gitHubAvatarUrl: observable,
gitHubLogin: observable,
gitHubName: observable,
gitHubPublishAsPublic: observable,
gitHubToken: observable,
hideChannels: action,
isAddVersionDialogShowing: observable,
isAutoBisecting: observable,
isBisectCommandShowing: observable,
isBisectDialogShowing: observable,
isClearingConsoleOnRun: observable,
isConsoleShowing: observable,
isEnablingElectronLogging: observable,
isGenericDialogShowing: observable,
isInstallingModules: observable,
isKeepingUserDataDirs: observable,
isOnline: observable,
isPublishingGistAsRevision: observable,
isQuitting: observable,
isRunning: observable,
isSettingsShowing: observable,
isThemeDialogShowing: observable,
isTokenDialogShowing: observable,
isTourShowing: observable,
isUpdatingElectronVersions: observable,
isDeletingAll: observable,
isDownloadingAll: observable,
isUsingSystemTheme: observable,
localPath: observable,
modules: observable,
output: observable,
packageAuthor: observable,
packageManager: observable,
pushError: action,
pushOutput: action,
removeAcceleratorToBlock: action,
removeVersion: action,
resetView: action,
setIsQuitting: action,
setPageHash: action,
setTheme: action,
setVersion: action,
setVersionStates: action,
showChannels: action,
showConfirmDialog: action,
showErrorDialog: action,
showGenericDialog: action,
showInfoDialog: action,
showInputDialog: action,
showObsoleteVersions: observable,
showTour: action,
showUndownloadedVersions: observable,
signOutGitHub: action,
templateName: observable,
theme: observable,
title: computed,
toggleAddMonacoThemeDialog: action,
toggleAddVersionDialog: action,
toggleAuthDialog: action,
toggleBisectCommands: action,
toggleBisectDialog: action,
toggleConsole: action,
toggleSettings: action,
updateDownloadProgress: action,
updateElectronVersions: action,
version: observable,
versions: observable,
versionsToShow: computed,
changeRunnableState: action,
startDownloadingAll: action,
stopDownloadingAll: action,
startDeletingAll: action,
stopDeletingAll: action,
});
// Bind all actions
this.downloadVersion = this.downloadVersion.bind(this);
this.pushError = this.pushError.bind(this);
this.pushOutput = this.pushOutput.bind(this);
this.flushOutput = this.flushOutput.bind(this);
this.getVersion = this.getVersion.bind(this);
this.hasVersion = this.hasVersion.bind(this);
this.removeVersion = this.removeVersion.bind(this);
this.setVersion = this.setVersion.bind(this);
this.showTour = this.showTour.bind(this);
this.signOutGitHub = this.signOutGitHub.bind(this);
this.toggleBisectCommands = this.toggleBisectCommands.bind(this);
this.toggleAuthDialog = this.toggleAuthDialog.bind(this);
this.toggleConsole = this.toggleConsole.bind(this);
this.clearConsole = this.clearConsole.bind(this);
this.toggleSettings = this.toggleSettings.bind(this);
this.toggleBisectDialog = this.toggleBisectDialog.bind(this);
this.updateDownloadProgress = this.updateDownloadProgress.bind(this);
this.updateElectronVersions = this.updateElectronVersions.bind(this);
this.setIsQuitting = this.setIsQuitting.bind(this);
this.addAcceleratorToBlock = this.addAcceleratorToBlock.bind(this);
this.removeAcceleratorToBlock = this.removeAcceleratorToBlock.bind(this);
this.hideChannels = this.hideChannels.bind(this);
this.showChannels = this.showChannels.bind(this);
this.changeRunnableState = this.changeRunnableState.bind(this);
this.startDownloadingAll = this.startDownloadingAll.bind(this);
this.stopDownloadingAll = this.stopDownloadingAll.bind(this);
this.startDeletingAll = this.startDeletingAll.bind(this);
this.stopDeletingAll = this.stopDeletingAll.bind(this);
// Populating the current state of every version present
versions.forEach((ver: RunnableVersion) => {
// A local electron build's `state` is setup in versions.ts
if (ver.source !== 'local') {
const { version } = ver;
ver.state = this.getVersionState(version);
}
});
// init fields
this.versions = Object.fromEntries(versions.map((v) => [v.version, v]));
this.defaultVersion = getDefaultVersion(versions);
this.version = this.defaultVersion;
window.ElectronFiddle.removeAllListeners('before-quit');
window.ElectronFiddle.removeAllListeners('toggle-bisect');
window.ElectronFiddle.removeAllListeners('clear-console');
window.ElectronFiddle.removeAllListeners('open-settings');
window.ElectronFiddle.removeAllListeners('show-welcome-tour');
window.ElectronFiddle.removeAllListeners('version-download-progress');
window.ElectronFiddle.addEventListener(
'open-settings',
this.toggleSettings,
);
window.ElectronFiddle.addEventListener('show-welcome-tour', this.showTour);
window.ElectronFiddle.addEventListener('clear-console', this.clearConsole);
window.ElectronFiddle.addEventListener(
'toggle-bisect',
this.toggleBisectCommands,
);
window.ElectronFiddle.addEventListener('before-quit', this.setIsQuitting);
window.ElectronFiddle.addEventListener(
'version-download-progress',
this.updateDownloadProgress,
);
/**
* Listens for changes in the app settings made in other windows
* and refreshes the current window settings accordingly.
*/
window.addEventListener('storage', (event) => {
const key = event.key as GlobalSetting;
const { newValue } = event;
let parsedValue: unknown;
try {
parsedValue = JSON.parse(newValue as string) as unknown;
} catch {
// The new value is a plain string, not a well-formed stringified object.
parsedValue = newValue;
}
if (Object.values(GlobalSetting).includes(key)) {
switch (key) {
case GlobalSetting.theme: {
this.setTheme(parsedValue as string);
break;
}
case GlobalSetting.hasShownTour: {
this['isTourShowing'] = !(parsedValue as boolean);
break;
}
// This key is deprecated, so do nothing
case GlobalSetting.knownVersion: {
break;
}
// Refresh local versions
case GlobalSetting.localVersion: {
this.refreshLocalVersions(getLocalVersions());
break;
}
case GlobalSetting.acceleratorsToBlock:
case GlobalSetting.channelsToShow:
case GlobalSetting.electronMirror:
case GlobalSetting.environmentVariables:
case GlobalSetting.executionFlags:
case GlobalSetting.fontFamily:
case GlobalSetting.fontSize:
case GlobalSetting.gitHubAvatarUrl:
case GlobalSetting.gitHubLogin:
case GlobalSetting.gitHubName:
case GlobalSetting.gitHubToken:
case GlobalSetting.isClearingConsoleOnRun:
case GlobalSetting.isEnablingElectronLogging:
case GlobalSetting.isKeepingUserDataDirs:
case GlobalSetting.isPublishingGistAsRevision:
case GlobalSetting.isUsingSystemTheme:
case GlobalSetting.packageAuthor:
case GlobalSetting.packageManager:
case GlobalSetting.showObsoleteVersions:
case GlobalSetting.showUndownloadedVersions: {
// Fall back to updating the state.
(this[key] as any) = parsedValue;
break;
}
default: {
this.genericTypeGuard(
key,
`Unhandled setting "${key}", please handle it in the \`AppState\`.`,
);
}
}
} else if (
!Object.values(WindowSpecificSetting).includes(
key as unknown as WindowSpecificSetting,
)
) {
console.warn(
`"${key}" is not a recognized localStorage key. If you're using this key to persist a setting, please add it to the relevant enum.`,
);
}
});
/**
* Handles communications between windows.
*/
this.broadcastChannel.addEventListener(
'message',
(event: MessageEvent<AppStateBroadcastMessage>) => {
const { type, payload } = event.data;
switch (type) {
case AppStateBroadcastMessageType.isDownloadingAll: {
this.isDownloadingAll = payload;
break;
}
case AppStateBroadcastMessageType.syncVersions: {
this.setVersionStates(payload);
break;
}
default: {
this.genericTypeGuard(
type,
`Unhandled BroadcastChannel message "${type}", please handle it in the \`AppState\`.`,
);
}
}
},
);
// Setup auto-runs
autorun(() => this.save(GlobalSetting.theme, this.theme));
autorun(() =>
this.save(
GlobalSetting.isClearingConsoleOnRun,
this.isClearingConsoleOnRun,
),
);
autorun(() =>
this.save(GlobalSetting.isUsingSystemTheme, this.isUsingSystemTheme),
);
autorun(() =>
this.save(
GlobalSetting.isPublishingGistAsRevision,
this.isPublishingGistAsRevision,
),
);
autorun(() =>
this.save(GlobalSetting.gitHubAvatarUrl, this.gitHubAvatarUrl),
);
autorun(() => this.save(GlobalSetting.gitHubLogin, this.gitHubLogin));
autorun(() => this.save(GlobalSetting.gitHubName, this.gitHubName));
autorun(() => this.save(GlobalSetting.gitHubToken, this.gitHubToken));
autorun(() =>
this.save(
WindowSpecificSetting.gitHubPublishAsPublic,
this.gitHubPublishAsPublic,
),
);
autorun(() =>
this.save(
GlobalSetting.isKeepingUserDataDirs,
this.isKeepingUserDataDirs,
),
);
autorun(() =>
this.save(
GlobalSetting.isEnablingElectronLogging,
this.isEnablingElectronLogging,
),
);
autorun(() => this.save(GlobalSetting.executionFlags, this.executionFlags));
autorun(() =>
this.save(GlobalSetting.environmentVariables, this.environmentVariables),
);
autorun(() => this.save(WindowSpecificSetting.version, this.version));
autorun(() => this.save(GlobalSetting.channelsToShow, this.channelsToShow));
autorun(() =>
this.save(
GlobalSetting.showUndownloadedVersions,
this.showUndownloadedVersions,
),
);
autorun(() =>
this.save(GlobalSetting.showObsoleteVersions, this.showObsoleteVersions),
);
autorun(() =>
this.save(GlobalSetting.packageManager, this.packageManager ?? 'npm'),
);
autorun(() =>
this.save(GlobalSetting.acceleratorsToBlock, this.acceleratorsToBlock),
);
autorun(() => this.save(GlobalSetting.packageAuthor, this.packageAuthor));
autorun(() => this.save(GlobalSetting.electronMirror, this.electronMirror));
autorun(() => this.save(GlobalSetting.fontFamily, this.fontFamily));
autorun(() => this.save(GlobalSetting.fontSize, this.fontSize));
// Update our known versions
this.updateElectronVersions();
// Make sure the console isn't all empty and sad
this.pushOutput('Console ready 🔬');
// set blocked shortcuts
window.ElectronFiddle.blockAccelerators([...this.acceleratorsToBlock]);
this.setVersion(this.version);
// Trigger the change state event
window.ElectronFiddle.removeAllListeners('version-state-changed');
window.ElectronFiddle.addEventListener(
'version-state-changed',
({ version, state }) => {
this.changeRunnableState(version, state);
},
);
}
/**
* @returns the title, e.g. appname, fiddle name, state
*/
get title(): string {
const { isEdited } = this.editorMosaic;
return isEdited ? 'Electron Fiddle - Unsaved' : 'Electron Fiddle';
}
/**
* Returns the current RunnableVersion or the first
* one that can be found.
*/
get currentElectronVersion(): RunnableVersion {
return this.versions[this.version] || this.versions[this.defaultVersion];
}
/**
* Returns an array of Electron versions to show given the
* current settings for states and channels to display
*/
get versionsToShow(): Array<RunnableVersion> {
const {
channelsToShow,
showObsoleteVersions,
showUndownloadedVersions,
versions,
} = this;
const oldest = window.ElectronFiddle.getOldestSupportedMajor();
const filter = (ver: RunnableVersion) =>
ver &&
(showUndownloadedVersions ||
ver.state === InstallState.installing ||
ver.state === InstallState.installed ||
ver.state === InstallState.downloaded) &&
(showObsoleteVersions ||
!oldest ||
oldest <= Number.parseInt(ver.version)) &&
channelsToShow.includes(getReleaseChannel(ver));
return sortVersions(Object.values(versions).filter(filter));
}
/**
* Update the Electron versions: First, fetch them from GitHub,
* then update their respective downloaded state.
*
* Fails silently.
*/
public async updateElectronVersions() {
this.isUpdatingElectronVersions = true;
try {
const fullVersions = await fetchVersions();
this.addNewVersions(
fullVersions
.filter((ver) => !(ver.version in this.versions))
.map((ver) => makeRunnable(ver)),
);
} catch (error) {
console.warn(`State: Could not update Electron versions`, error);
}
this.isUpdatingElectronVersions = false;
}
public startDownloadingAll() {
this.isDownloadingAll = true;
this.broadcastChannel.postMessage({
type: AppStateBroadcastMessageType.isDownloadingAll,
payload: true,
});
}
public stopDownloadingAll() {
this.isDownloadingAll = false;
this.broadcastChannel.postMessage({
type: AppStateBroadcastMessageType.isDownloadingAll,
payload: false,
});
}
public startDeletingAll() {
this.isDeletingAll = true;
}
public stopDeletingAll() {
this.isDeletingAll = false;
}
public async getName() {
this.name ||= await window.ElectronFiddle.getProjectName(this.localPath);
return this.name;
}
public hideChannels(channels: Array<ElectronReleaseChannel>) {
this.channelsToShow = this.channelsToShow.filter(
(ch) => !channels.includes(ch),
);
}
public showChannels(channels: Array<ElectronReleaseChannel>) {
const s = new Set<ElectronReleaseChannel>([
...this.channelsToShow,
...channels,
]);
this.channelsToShow = [...s.values()];
}
public toggleConsole() {
this.isConsoleShowing = !this.isConsoleShowing;
}
public clearConsole() {
this.output = [];
}
public toggleBisectCommands() {
// guard against hiding the commands when executing a bisect
if (!this.Bisector && !this.isBisectDialogShowing) {
this.isBisectCommandShowing = !this.isBisectCommandShowing;
}
}
public toggleAddVersionDialog() {
this.isAddVersionDialogShowing = !this.isAddVersionDialogShowing;
}
public toggleAddMonacoThemeDialog() {
this.isThemeDialogShowing = !this.isThemeDialogShowing;
}
public toggleAuthDialog() {
this.isTokenDialogShowing = !this.isTokenDialogShowing;
}
public toggleBisectDialog() {
this.isBisectDialogShowing = !this.isBisectDialogShowing;
}
public toggleSettings() {
// We usually don't lose editor focus,
// so you can still type. Let's force-blur.
(document.activeElement as HTMLInputElement).blur();
this.resetView({ isSettingsShowing: !this.isSettingsShowing });
}
public updateDownloadProgress(version: string, progress: ProgressObject) {
const percent = Math.round(progress.percent * 100) / 100;
const ver = this.versions[version];
// Stop if its undefined or has same downloadProgress percent
if (ver === undefined || ver.downloadProgress === percent) {
return;
}
ver.downloadProgress = percent;
this.versions[version] = ver;
this.broadcastVersionStates([ver]);
}
public setIsQuitting() {
this.isQuitting = true;
}
public disableTour() {
this.resetView();
localStorage.setItem(GlobalSetting.hasShownTour, 'true');
}
public showTour() {
this.resetView({ isTourShowing: true });
}
public setTheme(fileName?: string) {
this.theme = fileName || '';
window.app.loadTheme(this.theme);
}
public addLocalVersion(input: Version) {
addLocalVersion(input);
this.addNewVersions(getElectronVersions());
}
public refreshLocalVersions(versions: Version[]) {
const localVersions = versions.map((ver) => ver.version);
// Remove any local versions not in the provided list
for (const ver of Object.keys(this.versions)) {
if (
this.versions[ver].source === VersionSource.local &&
!localVersions.includes(ver)
) {
delete this.versions[ver];
}
}
// Add any new local versions
this.addNewVersions(versions.map((ver) => makeRunnable(ver)));
}
public addNewVersions(versions: RunnableVersion[]) {
for (const ver of versions) {
this.versions[ver.version] ||= ver;
}
this.broadcastVersionStates(versions);
}
// Updates the version states in the current window to reflect updates made by other windows.
private setVersionStates(versions: RunnableVersion[]) {
for (const ver of versions) {
this.versions[ver.version] = ver;
}
}
/**
* Remove a version of Electron
*/
public async removeVersion(ver: RunnableVersion): Promise<void> {
const { version, state, source } = ver;
if (ver === this.currentElectronVersion) {
console.log(`State: Not removing active version ${version}`);
return;
}
console.log(`State: Removing Electron ${version}`);
if (source === VersionSource.local) {
if (version in this.versions) {
delete this.versions[version];
saveLocalVersions(Object.values(this.versions));
} else {
console.log(`State: Version ${version} already removed, doing nothing`);
}
} else {
if (
state === InstallState.installed ||
state == InstallState.downloaded
) {
if (
(await window.ElectronFiddle.removeVersion(version)) ===
InstallState.missing
) {
await window.app.electronTypes.uncache(ver);
this.broadcastVersionStates([ver]);
}
} else {
console.log(`State: Version ${version} already removed, doing nothing`);
}
}
}
/**
* Download a version of Electron.
*/
public async downloadVersion(ver: RunnableVersion): Promise<void> {
const { source, state, version } = ver;
const { electronMirror, electronNightlyMirror } =
this.electronMirror.sources[this.electronMirror.sourceType];
const isRemote = source === VersionSource.remote;
const isDownloaded = state === InstallState.downloaded;
const isDownloading = state === InstallState.downloading;
const isInstalling = state === InstallState.installing;
const isReady = state === InstallState.installed;
if (isDownloaded || isDownloading || isInstalling) {
console.log(`State: Already ${state} ${version}.`);
return;
}
if (!isRemote || isReady) {
console.log(`State: Already have version ${version}; not downloading.`);
return;
}
console.log(`State: Downloading Electron ${version}`);
this.broadcastVersionStates([
{
...ver,
state: InstallState.downloading,
},
]);
// Download the version without setting it as the current version.
await window.ElectronFiddle.downloadVersion(version, {
mirror: {
electronMirror,
electronNightlyMirror,
},
});
this.broadcastVersionStates([ver]);
}
/**
* Changes the RunnableVersion state of the version passed
* and triggers a rerun in components
*/
public changeRunnableState(version: string, state: InstallState) {
const ver = this.versions[version];
if (ver === undefined) {
return;
}
ver.state = state;
this.versions[version] = ver;
}
public hasVersion(input: string): boolean {
return !!this.getVersion(input);
}
public getVersion(input: string): RunnableVersion | null {
return this.versions[normalizeVersion(input)];
}
/**
* Helper to test if the current version is available and would work.
*
* Returns a RunnableVersion if it would work, or an error string otherwise.
*/
public isVersionUsable(input: string): {
ver?: RunnableVersion;
err?: string;
} {
const ver = this.getVersion(input);
if (!ver) {
return { err: `Unknown version ${input}` };
}
const { localPath, version } = ver;
if (localPath && !window.ElectronFiddle.pathExists(localPath)) {
const err = `Local Electron build missing for version ${version} - please verify it is in the correct location or remove and re-add it.`;
return { err };
}
return { ver };
}
/**
* Helper to find a usable fallback version.
*/
public findUsableVersion(): RunnableVersion | undefined {
return this.versionsToShow.find((version) => {
const { ver } = this.isVersionUsable(version.version);
return !!ver;
});
}
/**
* Select a version of Electron (and download it if necessary).
*/
public async setVersion(input: string): Promise<void> {
const fallback = this.findUsableVersion();
const { err, ver } = this.isVersionUsable(input);
if (!ver) {
console.error(`setVersion('${input}') failed: ${err}`);
this.showErrorDialog(err!);
if (fallback) await this.setVersion(fallback.version);
return;
}
const { version } = ver;
console.log(`State: Switching to Electron ${version}`);
this.version = version;
try {
await this.downloadVersion(ver);
} catch {
await this.removeVersion(ver);
console.error(
`setVersion('${input}') failed: Couldn't download ${version}`,
);
this.showErrorDialog(`Failed to download Electron version ${version}`);
if (fallback) await this.setVersion(fallback.version);
return;
}
// If there's no current fiddle,
// or if the current fiddle is the previous version's template,
// then load the new version's template.
const shouldReplace = () =>
this.editorMosaic.files.size === 0 || // no current fiddle
(this.templateName && !this.editorMosaic.isEdited); // unedited template
if (shouldReplace()) {
const options: SetFiddleOptions = { templateName: version };
const values = await window.ElectronFiddle.getTemplate(version);
// test again just in case something happened while we awaited
if (shouldReplace()) {
await window.app.replaceFiddle(values, options);
}
}
}
/**
* The equivalent of signing out.
*/
public signOutGitHub(): void {
this.gitHubAvatarUrl = null;
this.gitHubLogin = null;
this.gitHubToken = null;
this.gitHubName = null;
}
public async showGenericDialog(
opts: GenericDialogOptions,
): Promise<{ confirm: boolean; input: string }> {
// Wait for any existing dialog to be closed and cleaned up.
await when(() => {
if (
!this.isGenericDialogShowing &&
this.genericDialogLastResult === null
) {
// Set dialog immediately to prevent any other queued dialogs from
// showing.
runInAction(() => {
this.genericDialogOptions = opts;
this.isGenericDialogShowing = true;
});
return true;
}
return false;
});
// Wait for dialog to be closed.
await when(() => !this.isGenericDialogShowing);
const confirm = Boolean(this.genericDialogLastResult);
const input = this.genericDialogLastInput || opts.defaultInput || '';