Pages are interactive one by one, so NavigateTo and menu links run an enhanced navigation that re-renders the page on the server and syncs <head>. That broke the editor in three ways: - Switching files navigated to ?file=...: the editor kept the old file, and with the large Transactions.json its DOM got mangled. The file is now loaded in place and only the URL is replaced (js/url.js). - Leaving the page re-ran OnParametersSetAsync on the disposing editor, which threw and terminated the circuit. The file parameter is now only read in OnInitializedAsync. - Coming back without a full reload showed Monaco unstyled, because its stylesheets had been removed from <head>. monaco.js now remembers them and puts them back. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
246 lines
8 KiB
C#
246 lines
8 KiB
C#
using System.Text.RegularExpressions;
|
|
using BlazorMonaco;
|
|
using BlazorMonaco.Editor;
|
|
using Microsoft.AspNetCore.Components;
|
|
using Microsoft.FluentUI.AspNetCore.Components;
|
|
using Microsoft.JSInterop;
|
|
using Schaad.Accounting.Interfaces;
|
|
|
|
namespace Schaad.Accounting.UI.Components.Pages;
|
|
|
|
/// <summary>
|
|
/// Plain-text editor for the data files of the selected year and mandator. Saving is validated
|
|
/// and backed up by <see cref="IRawDataRepository"/>; this page only handles the editor.
|
|
/// </summary>
|
|
public partial class JsonEditor : ComponentBase, IAsyncDisposable
|
|
{
|
|
private static readonly Regex LinePrefix = new(@"^Zeile (\d+)", RegexOptions.Compiled);
|
|
|
|
[Inject]
|
|
private IRawDataRepository repository { get; set; } = null!;
|
|
|
|
[Inject]
|
|
private ISettingsService settingsService { get; set; } = null!;
|
|
|
|
[Inject]
|
|
private IJSRuntime js { get; set; } = null!;
|
|
|
|
[Inject]
|
|
private NavigationManager navigation { get; set; } = null!;
|
|
|
|
[Inject]
|
|
private IDialogService dialogService { get; set; } = null!;
|
|
|
|
[Inject]
|
|
private IToastService toastService { get; set; } = null!;
|
|
|
|
[SupplyParameterFromQuery(Name = "file")]
|
|
public string? FileParameter { get; set; }
|
|
|
|
private StandaloneCodeEditor? editor;
|
|
private IJSObjectReference? unsavedGuard;
|
|
private IJSObjectReference? url;
|
|
private bool monacoLoaded;
|
|
private string? monacoError;
|
|
private RawDataFile? file;
|
|
private string fileName = "";
|
|
private int savedVersion;
|
|
private bool dirty;
|
|
private bool saving;
|
|
private IReadOnlyList<string> errors = [];
|
|
|
|
// The file parameter is only read here: switching files doesn't navigate (see OnFileChanged),
|
|
// and while leaving the page the query changes again for a component that is about to go.
|
|
protected override async Task OnInitializedAsync()
|
|
{
|
|
fileName = repository.FileNames.Contains(FileParameter ?? "") ? FileParameter! : repository.FileNames[0];
|
|
file = await repository.LoadAsync(fileName);
|
|
}
|
|
|
|
protected override async Task OnAfterRenderAsync(bool firstRender)
|
|
{
|
|
if (firstRender == false)
|
|
{
|
|
return;
|
|
}
|
|
unsavedGuard = await js.InvokeAsync<IJSObjectReference>("import", "./js/unsaved-guard.js");
|
|
url = await js.InvokeAsync<IJSObjectReference>("import", "./js/url.js");
|
|
try
|
|
{
|
|
await using var module = await js.InvokeAsync<IJSObjectReference>("import", "./js/monaco.js");
|
|
await module.InvokeVoidAsync("ensureLoaded");
|
|
monacoLoaded = true;
|
|
}
|
|
catch (JSException ex)
|
|
{
|
|
monacoError = ex.Message;
|
|
}
|
|
StateHasChanged();
|
|
}
|
|
|
|
private StandaloneEditorConstructionOptions EditorOptions(StandaloneCodeEditor _) => new()
|
|
{
|
|
Language = "json",
|
|
Value = file?.Text ?? "",
|
|
AutomaticLayout = true,
|
|
Folding = true,
|
|
FormatOnPaste = true,
|
|
ScrollBeyondLastLine = false,
|
|
TabSize = 2,
|
|
Minimap = new EditorMinimapOptions { Enabled = true }
|
|
};
|
|
|
|
private async Task OnEditorInit() => savedVersion = await CurrentVersionAsync();
|
|
|
|
// The alternative version id goes back to its old value on undo, so undoing all edits
|
|
// makes the file clean again.
|
|
private async Task<int> CurrentVersionAsync() => await (await editor!.GetModel()).GetAlternativeVersionId();
|
|
|
|
private async Task OnContentChanged(ModelContentChangedEvent _) => await SetDirtyAsync(await CurrentVersionAsync() != savedVersion);
|
|
|
|
// Also tells the browser-side guard to ask before leaving the page (links, reload, closing
|
|
// the tab, switching year or mandator).
|
|
private async Task SetDirtyAsync(bool value)
|
|
{
|
|
if (value == dirty)
|
|
{
|
|
return;
|
|
}
|
|
dirty = value;
|
|
if (unsavedGuard is not null)
|
|
{
|
|
await unsavedGuard.InvokeVoidAsync("set", dirty ? $"Die Änderungen an {fileName} sind noch nicht gespeichert. Seite trotzdem verlassen?" : null);
|
|
}
|
|
}
|
|
|
|
private async Task ShowFileAsync()
|
|
{
|
|
await editor!.SetValue(file!.Text);
|
|
savedVersion = await CurrentVersionAsync();
|
|
await SetDirtyAsync(false);
|
|
}
|
|
|
|
private async Task SaveAsync()
|
|
{
|
|
if (editor is null || file is null)
|
|
{
|
|
return;
|
|
}
|
|
saving = true;
|
|
try
|
|
{
|
|
var text = await editor.GetValue();
|
|
var result = await repository.SaveAsync(fileName, text, file.Hash);
|
|
errors = result.Errors;
|
|
if (result.Saved)
|
|
{
|
|
// Saved re-formatted; show what is on disk now, at the same place.
|
|
var position = await editor.GetPosition();
|
|
file = result.File!;
|
|
await ShowFileAsync();
|
|
await editor.SetPosition(position, "save");
|
|
await editor.RevealLineInCenter(position.LineNumber);
|
|
toastService.ShowToast(ToastIntent.Success, $"{fileName} gespeichert. Vorherige Version: {result.BackupPath}", 6000);
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
saving = false;
|
|
}
|
|
}
|
|
|
|
private async Task ReloadAsync()
|
|
{
|
|
if (dirty && await ConfirmDiscardAsync() == false)
|
|
{
|
|
return;
|
|
}
|
|
file = await repository.LoadAsync(fileName);
|
|
errors = [];
|
|
await ShowFileAsync();
|
|
}
|
|
|
|
// Loads the file in place and only puts it into the address bar (for bookmarks and reloads).
|
|
// Navigating instead would run an enhanced navigation, which re-renders the page on the server
|
|
// and merges it into the DOM; the editor doesn't survive that.
|
|
private async Task OnFileChanged(string name)
|
|
{
|
|
if (name == fileName)
|
|
{
|
|
return;
|
|
}
|
|
if (dirty && await ConfirmDiscardAsync() == false)
|
|
{
|
|
// Re-render puts the select back on the current file.
|
|
StateHasChanged();
|
|
return;
|
|
}
|
|
fileName = name;
|
|
file = await repository.LoadAsync(fileName);
|
|
errors = [];
|
|
// Before Monaco is up, the editor picks up the file when it is created (EditorOptions).
|
|
if (editor is not null)
|
|
{
|
|
await ShowFileAsync();
|
|
}
|
|
if (url is not null)
|
|
{
|
|
await url.InvokeVoidAsync("replace", navigation.GetUriWithQueryParameter("file", name));
|
|
}
|
|
}
|
|
|
|
private async Task<bool> ConfirmDiscardAsync()
|
|
{
|
|
var dialog = await dialogService.ShowConfirmationAsync(
|
|
$"Die Änderungen an {fileName} sind noch nicht gespeichert. Verwerfen?", "Verwerfen", "Abbrechen", "Ungespeicherte Änderungen");
|
|
var result = await dialog.Result;
|
|
return result.Cancelled == false;
|
|
}
|
|
|
|
private async Task RunEditorActionAsync(string actionId)
|
|
{
|
|
if (editor is null)
|
|
{
|
|
return;
|
|
}
|
|
await editor.Focus();
|
|
await editor.Trigger("toolbar", actionId);
|
|
}
|
|
|
|
private static int? LineOf(string error) => LinePrefix.Match(error) is { Success: true } match ? int.Parse(match.Groups[1].Value) : null;
|
|
|
|
private async Task GoToLineAsync(int line)
|
|
{
|
|
if (editor is null)
|
|
{
|
|
return;
|
|
}
|
|
await editor.SetPosition(new Position { LineNumber = line, Column = 1 }, "error");
|
|
await editor.RevealLineInCenter(line);
|
|
await editor.Focus();
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
try
|
|
{
|
|
if (unsavedGuard is not null)
|
|
{
|
|
await unsavedGuard.InvokeVoidAsync("set", (object?)null);
|
|
await unsavedGuard.DisposeAsync();
|
|
}
|
|
if (url is not null)
|
|
{
|
|
await url.DisposeAsync();
|
|
}
|
|
}
|
|
catch (JSDisconnectedException)
|
|
{
|
|
// Circuit gone; the page and its guard are gone with it.
|
|
}
|
|
}
|
|
|
|
private string SizeLabel => file is null ? "" : $"{System.Text.Encoding.UTF8.GetByteCount(file.Text) / 1024.0:0} KB";
|
|
|
|
private string Location => $"{settingsService.GetMandator()} / {settingsService.GetYear()}";
|
|
}
|