+ @if (monacoError is not null)
+ {
+ Der Editor konnte nicht geladen werden: @monacoError
+ }
+ else if (monacoLoaded)
+ {
+
+ }
+ else
+ {
+
+ }
+
+
+
+ Gespeichert wird nur gültiges JSON mit bekannten Feldern, eindeutigen Ids und (bei Buchungen) existierenden Konten.
+ Vor dem Speichern wird die bisherige Datei unter backup/… gesichert. Suchen und Ersetzen können reguläre Ausdrücke (.*).
+
+
diff --git a/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.cs b/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.cs
new file mode 100644
index 0000000..4831b8b
--- /dev/null
+++ b/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.cs
@@ -0,0 +1,239 @@
+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;
+
+///
+/// Plain-text editor for the data files of the selected year and mandator. Saving is validated
+/// and backed up by ; this page only handles the editor.
+///
+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 bool monacoLoaded;
+ private string? monacoError;
+ private RawDataFile? file;
+ private string fileName = "";
+ private int savedVersion;
+ private bool dirty;
+ private bool saving;
+ private IReadOnlyList errors = [];
+
+ protected override async Task OnParametersSetAsync()
+ {
+ var requested = repository.FileNames.Contains(FileParameter ?? "") ? FileParameter! : repository.FileNames[0];
+ if (requested == fileName)
+ {
+ return;
+ }
+ fileName = requested;
+ file = await repository.LoadAsync(fileName);
+ errors = [];
+ if (editor is not null)
+ {
+ await ShowFileAsync();
+ }
+ }
+
+ protected override async Task OnAfterRenderAsync(bool firstRender)
+ {
+ if (firstRender == false)
+ {
+ return;
+ }
+ unsavedGuard = await js.InvokeAsync("import", "./js/unsaved-guard.js");
+ try
+ {
+ await using var module = await js.InvokeAsync("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 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();
+ }
+
+ // Switching goes through the URL, so the file is part of bookmarks and back/forward.
+ private async Task OnFileChanged(string name)
+ {
+ if (name == fileName)
+ {
+ return;
+ }
+ if (dirty)
+ {
+ if (await ConfirmDiscardAsync() == false)
+ {
+ // Re-render puts the select back on the current file.
+ StateHasChanged();
+ return;
+ }
+ await SetDirtyAsync(false);
+ }
+ navigation.NavigateTo(navigation.GetUriWithQueryParameter("file", name));
+ }
+
+ private async Task 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();
+ }
+ }
+ 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()}";
+}
diff --git a/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.css b/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.css
new file mode 100644
index 0000000..c3f96a2
--- /dev/null
+++ b/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.css
@@ -0,0 +1,74 @@
+.json-editor {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.toolbar {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-end;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.actions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px;
+}
+
+.separator {
+ width: 1px;
+ align-self: stretch;
+ background: #e1e0d9;
+ margin: 0 4px;
+}
+
+.status {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 16px;
+ color: #52514e;
+ font-size: 12px;
+}
+
+.dirty {
+ color: #c50f1f;
+ font-weight: 600;
+}
+
+.errors {
+ margin: 4px 0 0;
+ padding-left: 18px;
+}
+
+/* A button, not a link: it only moves the cursor, it must not navigate. */
+.errors .link {
+ border: none;
+ background: none;
+ padding: 0;
+ font: inherit;
+ color: #0f6cbd;
+ text-align: left;
+ text-decoration: underline;
+ cursor: pointer;
+}
+
+.editor-frame {
+ height: calc(100vh - 290px);
+ min-height: 380px;
+ border: 1px solid #e1e0d9;
+ border-radius: 4px;
+ overflow: hidden;
+}
+
+.editor-frame ::deep .monaco-host {
+ height: 100%;
+}
+
+.hint {
+ color: #52514e;
+ font-size: 12px;
+}
diff --git a/Schaad.Accounting.UI/Extensions.cs b/Schaad.Accounting.UI/Extensions.cs
index 1c7e815..16cc13d 100644
--- a/Schaad.Accounting.UI/Extensions.cs
+++ b/Schaad.Accounting.UI/Extensions.cs
@@ -25,6 +25,7 @@ namespace Schaad.Accounting.UI
services.AddScoped();
services.AddScoped();
services.AddScoped();
+ services.AddScoped();
services.AddScoped();
services.AddScoped();
diff --git a/Schaad.Accounting.UI/Program.cs b/Schaad.Accounting.UI/Program.cs
index 5475d30..6591285 100644
--- a/Schaad.Accounting.UI/Program.cs
+++ b/Schaad.Accounting.UI/Program.cs
@@ -15,7 +15,10 @@ namespace Schaad.Accounting.UI
// Add services to the container.
builder.Services.AddRazorComponents()
- .AddInteractiveServerComponents();
+ .AddInteractiveServerComponents()
+ // The JSON editor sends whole data files (Transactions.json is several hundred KB)
+ // from the browser; the default limit is 32 KB per message.
+ .AddHubOptions(options => options.MaximumReceiveMessageSize = 8 * 1024 * 1024);
builder.Services.AddFluentUIComponents();
diff --git a/Schaad.Accounting.UI/Schaad.Accounting.UI.csproj b/Schaad.Accounting.UI/Schaad.Accounting.UI.csproj
index d9c617f..d8ecedb 100644
--- a/Schaad.Accounting.UI/Schaad.Accounting.UI.csproj
+++ b/Schaad.Accounting.UI/Schaad.Accounting.UI.csproj
@@ -21,6 +21,7 @@
+
diff --git a/Schaad.Accounting.UI/wwwroot/js/monaco.js b/Schaad.Accounting.UI/wwwroot/js/monaco.js
new file mode 100644
index 0000000..cc18080
--- /dev/null
+++ b/Schaad.Accounting.UI/wwwroot/js/monaco.js
@@ -0,0 +1,27 @@
+// Loads the Monaco editor (shipped inside the BlazorMonaco package) on first use, so only the
+// JSON editor page pays for it. BlazorMonaco normally expects three script tags in App.razor;
+// this loads the same three in the same order.
+
+let loading;
+
+function loadScript(src) {
+ return new Promise((resolve, reject) => {
+ const script = document.createElement('script');
+ script.src = src;
+ script.onload = resolve;
+ script.onerror = () => reject(new Error(`${src} could not be loaded`));
+ document.head.appendChild(script);
+ });
+}
+
+export function ensureLoaded() {
+ loading ??= (async () => {
+ // Sets the AMD path config (var require = ...) and window.blazorMonaco.
+ await loadScript('_content/BlazorMonaco/jsInterop.js');
+ await loadScript('_content/BlazorMonaco/lib/monaco-editor/min/vs/loader.js');
+ await loadScript('_content/BlazorMonaco/lib/monaco-editor/min/vs/editor/editor.main.js');
+ // editor.main registers itself as an AMD module; wait until it (and window.monaco) is ready.
+ await new Promise(resolve => window.require(['vs/editor/editor.main'], resolve));
+ })();
+ return loading;
+}
diff --git a/Schaad.Accounting.UI/wwwroot/js/unsaved-guard.js b/Schaad.Accounting.UI/wwwroot/js/unsaved-guard.js
new file mode 100644
index 0000000..015c124
--- /dev/null
+++ b/Schaad.Accounting.UI/wwwroot/js/unsaved-guard.js
@@ -0,0 +1,44 @@
+// Asks before leaving a page with unsaved changes. Blazor's NavigationLock can't do this here:
+// pages are interactive one by one, so navigation between them runs through the static router
+// (enhanced navigation), which doesn't consult interactive components.
+
+let message = null;
+
+function onClick(event) {
+ if (message === null || event.defaultPrevented || event.button !== 0
+ || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) {
+ return;
+ }
+ const link = event.target.closest?.('a[href]');
+ if (!link || link.target === '_blank' || link.hasAttribute('download')) {
+ return;
+ }
+ const url = new URL(link.href, document.baseURI);
+ if (url.origin !== location.origin || (url.pathname === location.pathname && url.search === location.search)) {
+ return;
+ }
+ if (confirm(message)) {
+ // Leaving for good; don't ask a second time on unload.
+ message = null;
+ } else {
+ // Runs in the capture phase, before Blazor's own link handling.
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+}
+
+function onBeforeUnload(event) {
+ if (message !== null) {
+ // Browsers show their own text; the call just has to ask.
+ event.preventDefault();
+ event.returnValue = '';
+ }
+}
+
+document.addEventListener('click', onClick, true);
+window.addEventListener('beforeunload', onBeforeUnload);
+
+/** Ask with this message before leaving the page; null stops asking. */
+export function set(newMessage) {
+ message = newMessage ?? null;
+}