-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathPage.razor
More file actions
1705 lines (1472 loc) · 62.5 KB
/
Copy pathPage.razor
File metadata and controls
1705 lines (1472 loc) · 62.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
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
@page "/"
@implements IAsyncDisposable
@inject IJSRuntime JSRuntime
@inject NavigationManager NavigationManager
@inject WorkerController Worker
@inject LanguageServicesClient LanguageServices
@inject InputOutputCache Cache
@inject TemplateCache TemplateCache
@inject BlazorMonacoInterop BlazorMonacoInterop
@inject ILocalStorageService LocalStorage
@inject CursorSynchronizer.Services CursorSynchronizerServices
@inject IAppHostEnvironment HostEnvironment
@inject IUpdateChecker UpdateChecker
@inject IScreenInfo ScreenInfo
@inject ICompilerOutputPlugin CompilerOutputPlugin
@inject ILogger<Page> Logger
@using BlazorMonaco.Editor
<PageTitle>.NET Lab</PageTitle>
<FluentHeader Class="lab-header" Height="null">
<div style="flex-grow: 1; justify-content: start">
@* Logo *@
@* Need to handle clicks to work around https://github.com/jjonescz/DotNetLab/issues/75. *@
@* Empty slug is used to go to "initial state + loaded user preferences". *@
<a href="/#" style="text-decoration: none" @onclick="@(() => OnLocationChanged(""))" @onclick:preventDefault>
<img style="vertical-align: middle" src="_content/DotNetLab.App/favicon.png" alt="Logo" title=".NET Lab" width="24" height="24" />@*
*@<span style="margin-left: 0.5em; vertical-align: middle">.NET Lab</span>
</a>
@* Input presets (quick-start templates) *@
<FluentMenuButton Text="Template" Items="WellKnownSlugs.ShorthandToTitle" OnMenuChanged="OnInputPresetSelectedAsync"
ButtonStyle="margin-left: 0.5em" />
</div>
<div>
@* Format document button *@
<FluentButton OnClick="() => FormatCurrentFileAsync()" Title="Format document (Ctrl+I)"
IconStart="@(new Icons.Regular.Size20.CodeText())" Disabled="!IsCurrentInputCSharp" />
@* URL buttons *@
<FluentStack Orientation="Orientation.Horizontal" HorizontalGap="0" Style="width: initial">
@* Copy URL button *@
<FluentButton OnClick="() => CopyUrlToClipboardAsync()" Title="Copy URL to clipboard (Ctrl+;)"
Style="border-top-right-radius: 0; border-bottom-right-radius: 0"
IconStart="@(urlCopied ? new Icons.Regular.Size20.Checkmark() : new Icons.Regular.Size20.Copy())" />
@* Load URL button *@
<FluentButton OnClick="() => LoadUrlFromClipboardAsync()" Title="Load URL from clipboard"
Style="border-top-left-radius: 0; border-bottom-left-radius: 0"
IconStart="@(new Icons.Regular.Size20.ClipboardPaste())"
Disabled="!canPasteUrlFromClipboard" />
</FluentStack>
@* Compile button *@
<FluentButton Appearance="Appearance.Accent" OnClick="() => CompileAsync()" Loading="compilationInProgress"
Title="Compile (Ctrl+S)" IconStart="@(new Icons.Regular.Size20.FlashPlay())" Disabled="!initialized">
Compile
</FluentButton>
@* Settings button *@
<FluentButton OnClick="() => settings.OpenModalAsync()"
IconStart="@(new Icons.Regular.Size20.Settings())">
Settings
@if (UpdateChecker.UpdateIsAvailable)
{
<FluentSpacer Width="4" />
<FluentBadge Appearance="Appearance.Accent" title="Update is available">1</FluentBadge>
}
</FluentButton>
</div>
<div style="flex-grow: 1">
<div style="flex-grow: 1; min-width: 10rem">
@* Outdated output info *@
@if (IsOutputOutdated)
{
<FluentStack title="Output is outdated, click Compile or press Ctrl+S"
Style="font-size: 0.8rem; font-style: normal; width: auto"
HorizontalAlignment="HorizontalAlignment.Center">
<FluentIcon Value="@(new Icons.Regular.Size20.Save())" Color="Color.Fill" />
Ctrl+S to re-compile
</FluentStack>
}
@* Cached info *@
else if (compiled is { CacheInfo: { } cacheInfo, CachedOutput: null })
{
var title = cacheInfo.Timestamp.HasValue
? "The currently displayed output has been fetched from a server cache."
: "The currently displayed output comes from a built-in cache.";
<FluentStack title="@title" Style="font-size: 0.8rem; font-style: normal; width: auto"
HorizontalAlignment="HorizontalAlignment.Center">
<FluentIcon Value="@(new Icons.Regular.Size20.CloudCheckmark())" Color="Color.Fill" />
Cached
@if (cacheInfo.Timestamp is { } cacheTimestamp)
{
@FormatCacheTimestamp(cacheTimestamp)
}
else
{
@:template
}
</FluentStack>
}
</div>
@* Memory usage info *@
@if (enableMemoryUsageView)
{
<MemoryUsageView />
}
<div>
@* Keyboard button *@
<FluentButton OnClick="ToggleInputVirtualKeyboardAsync"
Appearance="@(disableInputVirtualKeyboard ? Appearance.Accent : Appearance.Neutral)"
Title="@(disableInputVirtualKeyboard ? "Enable the on-screen keyboard for the input editor" : "Disable the on-screen keyboard for the input editor")">
<FluentIcon Value="@(new Icons.Regular.Size20.Keyboard())" Color="Color.Neutral" />
</FluentButton>
@* Orientation button *@
@if (orientation == Orientation.Horizontal)
{
<FluentButton OnClick="() => orientation = Orientation.Vertical"
Title="Display editors in a column">
<FluentIcon Value="@(new Icons.Regular.Size20.LayoutRowTwo())" Color="Color.Neutral" />
</FluentButton>
}
else
{
<FluentButton OnClick="() => orientation = Orientation.Horizontal"
Title="Display editors in a row">
<FluentIcon Value="@(new Icons.Regular.Size20.LayoutColumnTwo())" Color="Color.Neutral" />
</FluentButton>
}
</div>
</div>
</FluentHeader>
<CascadingValue IsFixed="true" Value="this">
<Settings @ref="settings" InputEditor="inputEditor" OutputEditor="outputEditor" @bind-WordWrap="wordWrap" @bind-UseVim="useVim" @bind-EnableMemoryUsageView="enableMemoryUsageView" />
</CascadingValue>
@* Input / output panels *@
@* Panels have `overflow: hidden` by default, which would cause Monaco Editor popups to get cropped, hence we reset it to `overflow: initial`. *@
<FluentMultiSplitter Orientation="orientation" Style="flex-grow: 1" Class="@(displayHintSquiggles ? null : "no-squiggly-hint")">
@* Input panel *@
<FluentMultiSplitterPane Collapsible Style="overflow: initial">
<div style="display: flex; flex-direction: column; height: 100%">
@* Input tabs *@
<FluentTabs @bind-ActiveTabId="activeInputTabId" @bind-ActiveTabId:after="OnActiveInputTabIdChangedAsync"
ShowClose="inputs.Count > 1 || configuration != null" OnTabClose="OnInputTabClosedAsync"
Style="padding: 0 0.2em">
@* Normal files *@
@foreach (var (index, input) in inputs.Index())
{
var id = IndexToInputTabId(index);
@* Clicking on an active tab goes into rename mode and we don't want to interfere with that, hence the condition inside @onclick. *@
<FluentTab Id="@id" Label="@(input.FileName)"
LabelEditable LabelChanged="(newName) => OnInputTabRenamedAsync(input, newName)"
@onclick="activeInputTabId != id ? OnInputTabClickAsync : null!" />
}
@* Special configuration file *@
@if (configuration != null)
{
@* NOTE: Label is shown in the overflow menu, so it needs to be set even though Header is also set. *@
<FluentTab Id="@IndexToInputTabId((int)SpecialInput.Configuration)" Label="Configuration">
<Header>
<FluentIcon Value="@(new Icons.Regular.Size16.DocumentSettings())" />
<span style="margin-left: 0.2em">Configuration</span>
</Header>
</FluentTab>
}
@* Add new file button *@
<div slot="end">
<FluentMenuButton IconStart="@(new Icons.Filled.Size20.DocumentAdd())" Text="Add"
ButtonAppearance="Appearance.Neutral" OnMenuChanged="OnAddInputTabAsync">
<FluentMenuItem Id="cs">.cs</FluentMenuItem>
<FluentMenuItem Id="razor">.razor</FluentMenuItem>
<FluentMenuItem Id="cshtml">.cshtml</FluentMenuItem>
<FluentDivider />
<FluentMenuItem Id="directives" title="Simple configuration using #: directives">Directives</FluentMenuItem>
<FluentMenuItem Id="config" title="Complex configuration using Roslyn APIs">
<FluentIcon Slot="start" Value="@(new Icons.Regular.Size16.DocumentSettings())" />
Configuration
</FluentMenuItem>
</FluentMenuButton>
</div>
</FluentTabs>
@* VIM status bar *@
<div id="vim-status" class="vim-status-bar" hidden="@(!useVim)" />
@* Input editor *@
<div style="flex-grow: 1">
<StandaloneCodeEditor @ref="inputEditor" Id="input-editor"
ConstructionOptions="InputConstructionOptions" OnDidInit="EditorInitAsync"
OnDidChangeModel="LanguageServices.OnDidChangeModel"
OnDidChangeModelContent="OnDidChangeModelContentAsync"
OnDidBlurEditorText="() => SaveStateToUrlAsync()" />
</div>
</div>
</FluentMultiSplitterPane>
@* Output panel *@
<FluentMultiSplitterPane Collapsible Style="overflow: initial">
<div style="display: flex; flex-direction: column; height: 100%">
@* Worker status message *@
@if (workerError != null)
{
<FluentMessageBar Title="Compiler worker failed." Intent="MessageIntent.Error" AllowDismiss="false">
<div style="white-space-collapse: preserve">@workerError</div>
<FluentButton Appearance="Appearance.Accent" Style="width: 100%; margin-top: 0.5em" OnClick="ReloadWorkerAsync"
IconStart="@(new Icons.Regular.Size16.ArrowClockwise())">Re-create the worker</FluentButton>
</FluentMessageBar>
}
@* Output tabs *@
@* NOTE: @key is needed - otherwise, when AllOutputs change,
the FluentTabs might render incorrect selected tab
even though ActiveTabId is set correctly (probably a bug). *@
<FluentTabs @bind-ActiveTabId="DisplayOutputType" @bind-ActiveTabId:after="UpdateOutputDisplayAsync" @key="AllOutputsKey"
Style="padding: 0 0.2em">
@foreach (var output in AllOutputs)
{
@* NOTE: Label is shown in the overflow menu, so it needs to be set even though Header is also set. *@
<FluentTab Id="@output.Type" Label="@output.Label" @onclick="OnOutputTabClickAsync">
<Header>
<span title="@output.Label (@output.Type)">@output.ShortLabel</span>
@* Error List badge *@
@if (output.Type == CompiledAssembly.DiagnosticsOutputType &&
compiled?.Output is { } compiledOutput &&
compiledOutput is { NumErrors: > 0 } or { NumWarnings: > 0 })
{
var color = compiledOutput.NumErrors > 0 ? "error" : "warning";
<FluentBadge Fill="x" BackgroundColor="@($"var(--{color})")" Color="white" Style="margin-left: 0.4em">
@(compiledOutput.NumErrors > 0 ? compiledOutput.NumErrors : compiledOutput.NumWarnings)
</FluentBadge>
}
</Header>
</FluentTab>
}
<div slot="end" style="display: flex; flex-direction: row; align-items: center; gap: 0.5em">
@* Output loading indicator *@
<FluentProgressRing title="Output is loading" Visible="outputLoading" Width="1em" Style="margin-right: 0.2em" />
</div>
</FluentTabs>
@* Output toolbar *@
@if (OutputHasToolbar && GetOutput(DisplayOutputType) != null)
{
<FluentToolbar>
@switch (DisplayOutputType)
{
case "tree":
{
<FluentSelect @bind-SelectedOption:get="savedState.ShowSymbols"
@bind-SelectedOption:set="(v) => ChangePreferencesAsync((s) => s with { ShowSymbols = v })"
Items="Enum.GetValues<SymbolDisplayKinds>()"
OptionText="getSymbolDisplayKindLabel"
OptionTitle="getSymbolDisplayKindLabel"
Width="max-content"
AriaLabel="Symbols"
AdditionalAttributes="@(new Dictionary<string, object>() { ["title"] = "Displays symbol nodes in the tree - look for `.GetSymbolInfo()` and `.GetDeclaredSymbol()` under syntax nodes" })">
</FluentSelect>
static string getSymbolDisplayKindLabel(SymbolDisplayKinds kind) => kind switch
{
SymbolDisplayKinds.None => "No Symbols",
SymbolDisplayKinds.Public => "Public Symbols",
SymbolDisplayKinds.Internal => "Internal Symbols",
SymbolDisplayKinds.Both => "All Symbols",
_ => kind.ToString(),
};
<FluentCheckbox @bind-Value:get="savedState.ShowOperations"
@bind-Value:set="(v) => ChangePreferencesAsync((s) => s with { ShowOperations = v })"
Label="Operations"
title="Displays IOperation nodes in the tree - look for `.GetOperation()` under syntax nodes" />
<FluentCheckbox @bind-Value:get="savedState.ShowBoundNodes"
@bind-Value:set="(v) => ChangePreferencesAsync((s) => s with { ShowBoundNodes = v })"
Label="Bound nodes"
title="Displays bound nodes in the tree - look for `.GetBoundRoot()` under syntax nodes" />
<FluentButton OnClick="FoldAllOutputAsync" Title="Collapse all">@*
*@<FluentIcon Value="@(new Icons.Regular.Size20.ArrowCollapseAll())" Color="Color.Neutral" /></FluentButton>
}
break;
case "html":
{
<FluentCheckbox @bind-Value="showRenderedHtml" Label="Rendered" Disabled="htmlOutput == null"
title="Displays the HTML code rendered inside an iframe" />
}
break;
case "il":
{
<FluentCheckbox @bind-Value:get="savedState.DecodeCustomAttributeBlobs"
@bind-Value:set="(v) => ChangePreferencesAsync((s) => s with { DecodeCustomAttributeBlobs = v })"
Label="Decode custom attribute blobs" />
<FluentCheckbox @bind-Value:get="savedState.ShowSequencePoints"
@bind-Value:set="(v) => ChangePreferencesAsync((s) => s with { ShowSequencePoints = v })"
Label="Sequence points" />
<FluentCheckbox @bind-Value:get="savedState.FullIl"
@bind-Value:set="(v) => ChangePreferencesAsync((s) => s with { FullIl = v })"
Label="Full IL" />
}
break;
case CompiledAssembly.DiagnosticsOutputType:
{
<FluentCheckbox @bind-Value:get="savedState.ExcludeSingleFileNameInDiagnostics"
@bind-Value:set="(v) => ChangePreferencesAsync((s) => s with { ExcludeSingleFileNameInDiagnostics = v })"
Label="Exclude single file name" />
<FluentCheckbox @bind-Value:get="savedState.IncludeHiddenDiagnostics"
@bind-Value:set="(v) => ChangePreferencesAsync((s) => s with { IncludeHiddenDiagnostics = v })"
Label="Include hidden diagnostics" />
}
break;
}
</FluentToolbar>
}
@* Output disclaimer *@
@if (outputDisclaimer == OutputDisclaimer.JitAsmUnavailableUsingCached)
{
<FluentMessageBar Intent="MessageIntent.Info" AllowDismiss="false">
JIT disassembler is not available on this platform
(it's only available in the <a href="@App.DesktopAppLink" target="_blank" rel="noopener noreferrer">desktop app</a>).<br/>
Displaying cached output@(compiled?.CacheInfo?.Timestamp is { } cacheTimestamp ? $" ({FormatCacheTimestamp(cacheTimestamp)})" : "").
</FluentMessageBar>
}
<div style="flex-grow: 1">
@* Rendered HTML *@
@{
bool actuallyShowRenderedHtml = showRenderedHtml && htmlOutput != null;
}
@if (actuallyShowRenderedHtml)
{
<iframe srcdoc="@htmlOutput" style="width: 100%; height: 100%"></iframe>
}
@* Output editor *@
@{
string style = actuallyShowRenderedHtml ? "display:none" : "display:contents";
}
<div style="@style">
<StandaloneCodeEditor @ref="outputEditor" Id="output-editor"
OnDidInit="OutputEditorInitAsync"
ConstructionOptions="OutputConstructionOptions" />
</div>
</div>
</div>
</FluentMultiSplitterPane>
</FluentMultiSplitter>
@code {
/// <summary>
/// Should be used whenever <see cref="inputs"/> are manipulated across <see langword="await"/>.
/// </summary>
private readonly AsyncLock inputsLock = new();
private readonly TaskCompletionSource editorInitialized = new();
private readonly List<Input> inputs = new();
private readonly Dictionary<string, EditorState> outputStates = new();
private CursorSynchronizer? cursorSynchronizer;
private bool editorInitializationStarted;
private bool initialized;
private bool monacoThemeDefined;
private DotNetObjectReference<Page>? dotNetObjectReference;
private Action? unregisterEventListeners;
private IJSObjectReference module = null!;
private Input? configuration;
private string activeInputTabId = IndexToInputTabId(0);
private StandaloneCodeEditor inputEditor = null!;
private StandaloneCodeEditor outputEditor = null!;
private Input? currentInput;
private EditorState? currentOutput;
private string? userSelectedOutputType;
private bool temporarilyShowErrorListIfOutputTextEmpty;
private int urlCopiedToken;
private bool urlCopied;
private bool canPasteUrlFromClipboard = true;
private bool compilationInProgress;
private DateTimeOffset inputChanged;
private bool outputLoading;
private OutputDisclaimer outputDisclaimer;
private CompiledState? compiled;
private Settings settings = null!;
private bool wordWrap;
private bool useVim;
private bool enableMemoryUsageView;
private bool displayHintSquiggles;
private bool disableInputVirtualKeyboard;
private bool showRenderedHtml;
private Orientation orientation;
private string? workerError;
private string? htmlOutput;
private sealed record CompiledState
{
public required CompilationInput Input { get; init; }
public required CompiledAssembly Output { get; init; }
public CacheInfo? CacheInfo { get; init; }
public required DateTimeOffset Start { get; init; }
public required DateTimeOffset End { get; init; }
public required bool AutoLoadLazyOutputs { get; init; }
/// <summary>
/// Only set if this <see cref="CompiledState"/> instance represents compiled (not cached) state
/// but we also have cached output loaded for it.
/// </summary>
public CompiledAssembly? CachedOutput { get; init; }
}
private record EditorState(TextModel Model) : IAsyncDisposable
{
public MonacoEditorViewState ViewState { get; set; }
public async ValueTask DisposeAsync()
{
await Model.DisposeModel();
await ViewState.DisposeAsync();
}
}
private sealed record Input(string FileName, TextModel Model) : EditorState(Model)
{
public string FileName { get; set; } = FileName;
public required string? NewContent { get; set; }
}
private readonly record struct CacheInfo(DateTimeOffset? Timestamp);
private enum SpecialInput
{
Configuration = -1,
}
private enum Layout
{
Split,
InputOnly,
OutputOnly,
}
private Input? CurrentInput
{
get
{
var i = InputTabIdToIndex(activeInputTabId);
if (i == (int)SpecialInput.Configuration)
{
return configuration;
}
if (i < 0 || i >= inputs.Count)
{
return null;
}
return inputs[i];
}
}
private IEnumerable<(Input Input, bool IsConfiguration)> InputsAndConfiguration
{
get
{
foreach (var input in inputs)
{
yield return (input, false);
}
if (configuration is { } config)
{
yield return (config, true);
}
}
}
private IEnumerable<CompiledFileOutput> AllOutputs
{
get => (CurrentCompiledFile?.Outputs)
.TryConcat(compiled?.Output.GlobalOutputs);
}
private string AllOutputsKey
{
get => AllOutputs.Select(o => o.Type).JoinToString(",");
}
private bool TemporarilyShowErrorList
{
get
{
return temporarilyShowErrorListIfOutputTextEmpty &&
userSelectedOutputType is { } outputType &&
GetOutput(outputType) is { } output &&
HasEmptyText(output) == true;
}
}
private string? DisplayOutputType
{
get
{
return TemporarilyShowErrorList
? CompiledAssembly.DiagnosticsOutputType
: userSelectedOutputType;
}
set
{
userSelectedOutputType = value;
temporarilyShowErrorListIfOutputTextEmpty = false;
}
}
/// <remarks>
/// We don't check equality of last compiled input and current input
/// because we might not have current input fully loaded
/// (parts can live only in the editor until Compile is clicked).
/// </remarks>
private bool IsOutputOutdated
=> compiled is not { Start: var compileStart } || compileStart < inputChanged;
private bool OutputHasToolbar
=> DisplayOutputType is "tree" or "html" or "il" or CompiledAssembly.DiagnosticsOutputType;
protected override async Task OnInitializedAsync()
{
orientation = GetAutoOrientation();
NavigationManager.LocationChanged += OnLocationChanged;
UpdateChecker.UpdateStatusChanged += StateHasChanged;
ScreenInfo.Updated += OnScreenInfoUpdated;
Worker.Failed += OnWorkerFailed;
displayHintSquiggles = await LocalStorage.TryLoadOptionAsync(nameof(displayHintSquiggles), defaultValue: false);
disableInputVirtualKeyboard = await LocalStorage.TryLoadOptionAsync(nameof(disableInputVirtualKeyboard), defaultValue: false);
}
private async Task EditorInitAsync()
{
// This might get called twice when an editor is hidden and unhidden, or during hot reload,
// but we don't want to continue initialization in those cases.
if (editorInitializationStarted)
{
return;
}
editorInitializationStarted = true;
await BlazorMonacoInterop.EnableSemanticHighlightingAsync();
await BlazorMonacoInterop.RegisterLanguageAsync(CompiledAssembly.OutputLanguageId);
await (await JSRuntime.InvokeAsync<IJSObjectReference>("import", "../_content/DotNetLab.App/js/asm.js")).InvokeVoidAsync("registerX86Language");
await DefineMonacoThemeAsync();
await RegisterWordWrapActionAsync();
await RegisterFormatActionAsync();
await RegisterSquigglyHintActionAsync();
module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/DotNetLab.App/Lab/Page.razor.js");
dotNetObjectReference = DotNetObjectReference.Create(this);
unregisterEventListeners = await module.InvokeAsync<Action>("registerEventListeners", dotNetObjectReference);
cursorSynchronizer = new CursorSynchronizer(CursorSynchronizerServices, inputEditor, outputEditor);
await cursorSynchronizer.InitAsync();
await settings.InitializeAsync();
await LoadStateFromUrlAsync();
if (disableInputVirtualKeyboard)
{
await module.InvokeVoidAsync("setVirtualKeyboardDisabled", inputEditor.Id, true);
}
if (await HostEnvironment.HasHardwareKeyboardAsync())
{
await inputEditor.Focus();
}
if (!editorInitialized.TrySetResult())
{
Logger.LogError("Failed to set editor initialized result.");
}
initialized = true;
StateHasChanged();
if (settings.AutoCompileOnStart && !compilationInProgress)
{
// Avoid storing the first auto compilation in cache
// (the same shared snippet would be stored multiple times unnecessarily and
// users can always store their snippet separately by compiling manually).
await CompileAsync(storeInCache: false);
}
}
private async Task OutputEditorInitAsync()
{
await editorInitialized.Task;
await module.InvokeVoidAsync("setVirtualKeyboardDisabled", outputEditor.Id, true);
}
private async Task ToggleInputVirtualKeyboardAsync()
{
disableInputVirtualKeyboard = !disableInputVirtualKeyboard;
StateHasChanged();
await LocalStorage.SetItemAsync(nameof(disableInputVirtualKeyboard), disableInputVirtualKeyboard);
await module.InvokeVoidAsync("setVirtualKeyboardDisabled", inputEditor.Id, disableInputVirtualKeyboard);
}
async ValueTask IAsyncDisposable.DisposeAsync()
{
NavigationManager.LocationChanged -= OnLocationChanged;
UpdateChecker.UpdateStatusChanged -= StateHasChanged;
ScreenInfo.Updated -= OnScreenInfoUpdated;
Worker.Failed -= OnWorkerFailed;
unregisterEventListeners?.Invoke();
await cursorSynchronizer?.DisposeAsync();
foreach (var input in inputs)
{
await input.DisposeAsync();
}
foreach (var outputModel in outputStates.Values)
{
await outputModel.DisposeAsync();
}
if (module is not null)
{
try
{
await module.DisposeAsync();
}
catch (JSDisconnectedException) { }
}
dotNetObjectReference?.Dispose();
inputsLock.Dispose();
}
private async Task OnLocationChanged(string targetSlug)
{
currentSlug = targetSlug;
await LoadStateFromUrlAsync();
}
private async void OnLocationChanged(object? sender, LocationChangedEventArgs e)
{
RefreshCurrentSlug();
await LoadStateFromUrlAsync();
StateHasChanged();
}
[JSInvokable]
public async Task CopyUrlToClipboardAsync()
{
await SaveStateToUrlAsync();
await module.InvokeVoidAsync("copyUrlToClipboard", HostEnvironment.LabUrlPrefix);
urlCopied = true;
StateHasChanged();
var token = Interlocked.Increment(ref urlCopiedToken);
_ = Task.Delay(TimeSpan.FromSeconds(2)).ContinueWith(_ =>
{
if (token == urlCopiedToken)
{
urlCopied = false;
StateHasChanged();
}
});
}
public async Task LoadUrlFromClipboardAsync()
{
var text = await module.InvokeAsync<string>("getClipboardText");
if (NavigateToSlug(GetSlugFromClipboardText(text)))
{
await LoadStateFromUrlAsync();
}
}
[JSInvokable]
public void OnClipboardTextChanged(string? text)
{
var slug = GetSlugFromClipboardText(text);
canPasteUrlFromClipboard = TryGetSavedStateFromSlug(slug, out _);
StateHasChanged();
}
private static string GetSlugFromClipboardText(string? text)
{
text ??= "";
var hashIndex = text.IndexOf('#');
return hashIndex >= 0 ? text[(hashIndex + 1)..] : text;
}
private static bool TryGetSavedStateFromSlug(string slug, out SavedState? state)
{
if (WellKnownSlugs.ShorthandToState.TryGetValue(slug, out var wellKnownState))
{
state = wellKnownState;
return true;
}
return Compressor.TryUncompress(slug, out state, out _);
}
private StandaloneEditorConstructionOptions InputConstructionOptions(StandaloneCodeEditor editor)
{
return EditorConstructionOptions(editor, output: false);
}
private StandaloneEditorConstructionOptions OutputConstructionOptions(StandaloneCodeEditor editor)
{
return EditorConstructionOptions(editor, output: true);
}
private StandaloneEditorConstructionOptions EditorConstructionOptions(StandaloneCodeEditor editor, bool output)
{
return new()
{
AutomaticLayout = true,
ReadOnly = output,
// This avoids a virtual keyboard showing up on mobile on the output (readonly) editor.
DomReadOnly = output,
WordWrap = wordWrap ? "on" : "off",
BracketPairColorization = output ? new() { Enabled = false } : null,
Padding = new() { Top = 10 },
Scrollbar = new()
{
// This allows Ctrl+Wheel on the editor to zoom the whole app
// (not ideal because it also scrolls if possible, but better than nothing).
AlwaysConsumeMouseWheel = false,
},
StickyScroll = new()
{
Enabled = true,
MaxLineCount = 100,
},
};
}
public string GetMonacoTheme(bool dark)
{
if (monacoThemeDefined)
{
return dark ? CustomMonacoTheme.Dark : CustomMonacoTheme.Light;
}
return dark ? BuiltInMonacoTheme.Dark : BuiltInMonacoTheme.Light;
}
private async Task DefineMonacoThemeAsync()
{
Debug.Assert(!monacoThemeDefined);
await CustomMonacoTheme.DefineAsync(JSRuntime);
monacoThemeDefined = true;
bool dark = settings.Theme switch
{
DesignThemeModes.Dark => true,
DesignThemeModes.Light => false,
_ => await BlazorMonacoInterop.HasDarkThemeAsync(inputEditor.Id),
};
await BlazorMonaco.Editor.Global.SetTheme(JSRuntime, GetMonacoTheme(dark: dark));
}
private async Task RegisterWordWrapActionAsync()
{
var action = new ActionDescriptor
{
Id = "word-wrap",
Label = "Toggle Word Wrap",
ContextMenuGroupId = "navigation",
Keybindings = [(int)KeyMod.Alt | (int)BlazorMonaco.KeyCode.KeyZ],
Run = _ => InvokeAsync(settings.ToggleWordWrapAsync),
};
await inputEditor.AddAction(action);
await outputEditor.AddAction(action);
}
private async Task RegisterFormatActionAsync()
{
var action = new ActionDescriptor
{
Id = "format",
Label = "Format Document",
ContextMenuGroupId = "1_modification",
Keybindings = [(int)KeyMod.CtrlCmd | (int)BlazorMonaco.KeyCode.KeyI],
Run = _ => InvokeAsync(FormatCurrentFileAsync),
};
await inputEditor.AddAction(action);
await outputEditor.AddAction(action);
}
private async Task RegisterSquigglyHintActionAsync()
{
var action = new ActionDescriptor
{
Id = "squiggly-hint",
Label = ".NET Lab: Toggle Squiggly Hint (Hidden Diagnostic Decoration)",
Run = _ => InvokeAsync(ToggleSquigglyHintAsync),
};
await inputEditor.AddAction(action);
async Task ToggleSquigglyHintAsync()
{
displayHintSquiggles = !displayHintSquiggles;
StateHasChanged();
await LocalStorage.SetItemAsync(nameof(displayHintSquiggles), displayHintSquiggles);
}
}
private async Task OnInputPresetSelectedAsync(MenuChangeEventArgs args)
{
if (args.Id is { } slug && NavigateToSlug(slug))
{
await LoadStateFromUrlAsync();
}
}
private const string inputTabIdPrefix = "i";
private static int InputTabIdToIndex(string tabId)
{
return TabIdToIndex(inputTabIdPrefix, tabId);
}
private static int TabIdToIndex(string prefix, string tabId)
{
return int.Parse(tabId.Substring(prefix.Length));
}
private static string IndexToInputTabId(int index)
{
return IndexToTabId(inputTabIdPrefix, index);
}
private static string IndexToTabId(string prefix, int index)
{
return $"{prefix}{index}";
}
private async Task OnActiveInputTabIdChangedAsync()
{
var i = InputTabIdToIndex(activeInputTabId);
if (i == (int)SpecialInput.Configuration)
{
await SelectConfigurationAsync();
}
else if (i >= 0 && i < inputs.Count)
{
await SelectInputTabAsync(inputs[i], i);
}
else
{
return;
}
}
private async Task OnInputTabClosedAsync(FluentTab tab)
{
await SaveStateToUrlAsync();
var i = InputTabIdToIndex(tab.Id!);
var activeInputTabIndex = InputTabIdToIndex(activeInputTabId);
if (i == (int)SpecialInput.Configuration)
{
configuration = null;
}
else if (inputs.Count > 1)
{
using var _ = await inputsLock.LockAsync();
var removedInput = inputs[i];
inputs.RemoveAt(i);
await removedInput.DisposeAsync();
}
else
{
return;
}
await OnWorkspaceChangedAsync();
await SaveStateToUrlAsync();
}
private async Task OnInputTabRenamedAsync(Input input, string newName)
{
await SaveStateToUrlAsync();
if (input.FileName != newName)
{
var oldLanguage = GetLanguageForFileExtension(Path.GetExtension(input.FileName));
var newLanguage = GetLanguageForFileExtension(Path.GetExtension(newName));
input.FileName = newName;
if (oldLanguage != newLanguage)
{
await BlazorMonaco.Editor.Global.SetModelLanguage(JSRuntime, input.Model, newLanguage);
}
await OnWorkspaceChangedAsync();
}
await SaveStateToUrlAsync();
}
private async Task OnAddInputTabAsync(MenuChangeEventArgs args)
{
await SaveStateToUrlAsync();
if (args.Id == "config")
{
await SelectConfigurationAsync();
}
else if (args.Id switch
{
"cs" => InitialCode.CSharp,
"razor" => InitialCode.Razor,
"cshtml" => InitialCode.Cshtml,
"directives" => InitialCode.Directives,
_ => null,
} is { } initialCode)
{
await AddInputAsync(initialCode);
}
else
{
return;
}
await SaveStateToUrlAsync();
if (await HostEnvironment.HasHardwareKeyboardAsync())
{
await inputEditor.Focus();
}
}
internal async Task SelectConfigurationAsync()
{
if (configuration is null)
{
await SaveStateToUrlAsync();
var fileName = InitialCode.Configuration.SuggestedFileName;
var inputCode = InitialCode.Configuration.ToInputCode();
var model = await CreateModelAsync(inputCode);
configuration = new(fileName, model) { NewContent = inputCode.Text };
await OnWorkspaceChangedAsync();
await SaveStateToUrlAsync();
}
await SelectInputTabAsync(configuration, (int)SpecialInput.Configuration);
}
private async Task SelectInputTabAsync(Input input, int index)
{
if (currentInput is { } previousInput)
{
previousInput.ViewState = await inputEditor.SaveViewStateAsync(module);
}
currentInput = input;
// Update the editor.
await inputEditor.SetModel(input.Model);
await inputEditor.RestoreViewStateAsync(input.ViewState, module);
// Update the tabs.
activeInputTabId = IndexToInputTabId(index);
// Display output corresponding to the selected input.
await AutoSelectOutputAsync(
updateTimestampMode: OutputActionMode.IfLazyTextIsResolved,
storeInCacheMode: OutputActionMode.IfLazyTextIsResolved);
}
private async Task AddInputAsync(InitialCode initialCode, bool selectAsCurrent = true)
{
var fileName = FindUniqueName(initialCode);
var inputCode = initialCode.ToInputCode(fileName);
var model = await CreateModelAsync(inputCode);
var input = new Input(fileName, model) { NewContent = inputCode.Text };
inputs.Add(input);