JSON editor: fix switching files and returning to the page #13

Merged
clayschaad merged 1 commit from fix-json-editor-file-switch into main 2026-10-30 21:09:28 +00:00
4 changed files with 67 additions and 25 deletions
Showing only changes of commit 04bf48feb6 - Show all commits

View file

@ -76,7 +76,7 @@ Pages live in `Schaad.Accounting.UI/Components/Pages/`. Each page typically has
- `Microsoft.FluentUI.AspNetCore.Components` — UI components (FluentDataGrid, FluentDialog, etc.)
- `Plotly.Blazor` — charts on the older chart pages
- `BlazorMonaco` — Monaco editor for the JSON editor page; loaded on demand by `wwwroot/js/monaco.js` instead of script tags in `App.razor`
- `BlazorMonaco` — Monaco editor for the JSON editor page; loaded on demand by `wwwroot/js/monaco.js` instead of script tags in `App.razor`. Pages are interactive one by one, so `NavigationManager.NavigateTo` and menu links run enhanced navigation, which syncs `<head>` (removing Monaco's styles; `monaco.js` puts them back) and re-renders the page on the server. The editor therefore switches files in place and only rewrites the URL (`wwwroot/js/url.js`)
- Chart.js 4 + `chartjs-chart-treemap` — charts on the Analyse page; vendored in `wwwroot/lib/` (no CDN), wrapped by `wwwroot/js/charts.js` and `ChartJsChart.razor`
- `FreeSpire.PDF` — PDF parsing for bank statement imports
- `Schaad.Finance.dll` / `Schaad.Finance.Api.dll` — proprietary DLLs for MT940/CAMT053 parsing and FX rate lookups (FixerIo API key in `appsettings.Development.json`)

View file

@ -39,6 +39,7 @@ public partial class JsonEditor : ComponentBase, IAsyncDisposable
private StandaloneCodeEditor? editor;
private IJSObjectReference? unsavedGuard;
private IJSObjectReference? url;
private bool monacoLoaded;
private string? monacoError;
private RawDataFile? file;
@ -48,20 +49,12 @@ public partial class JsonEditor : ComponentBase, IAsyncDisposable
private bool saving;
private IReadOnlyList<string> errors = [];
protected override async Task OnParametersSetAsync()
// 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()
{
var requested = repository.FileNames.Contains(FileParameter ?? "") ? FileParameter! : repository.FileNames[0];
if (requested == fileName)
{
return;
}
fileName = requested;
fileName = repository.FileNames.Contains(FileParameter ?? "") ? FileParameter! : repository.FileNames[0];
file = await repository.LoadAsync(fileName);
errors = [];
if (editor is not null)
{
await ShowFileAsync();
}
}
protected override async Task OnAfterRenderAsync(bool firstRender)
@ -71,6 +64,7 @@ public partial class JsonEditor : ComponentBase, IAsyncDisposable
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");
@ -166,24 +160,33 @@ public partial class JsonEditor : ComponentBase, IAsyncDisposable
await ShowFileAsync();
}
// Switching goes through the URL, so the file is part of bookmarks and back/forward.
// 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)
{
if (await ConfirmDiscardAsync() == false)
if (dirty && await ConfirmDiscardAsync() == false)
{
// Re-render puts the select back on the current file.
StateHasChanged();
return;
}
await SetDirtyAsync(false);
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));
}
navigation.NavigateTo(navigation.GetUriWithQueryParameter("file", name));
}
private async Task<bool> ConfirmDiscardAsync()
@ -226,6 +229,10 @@ public partial class JsonEditor : ComponentBase, IAsyncDisposable
await unsavedGuard.InvokeVoidAsync("set", (object?)null);
await unsavedGuard.DisposeAsync();
}
if (url is not null)
{
await url.DisposeAsync();
}
}
catch (JSDisconnectedException)
{

View file

@ -4,6 +4,25 @@
let loading;
// Enhanced navigation (moving between pages without a full reload) syncs <head> with the
// server-rendered page and so removes the stylesheets Monaco added at runtime. Monaco itself stays
// loaded in the window, so remember those elements and put them back before the next editor is
// created. Monaco keeps references to its <style> elements (e.g. the theme colors) and updates
// them in place, so they have to be the same elements, not copies.
const monacoStyles = new Set();
function isMonacoStyle(node) {
return node.tagName === 'STYLE' || (node.tagName === 'LINK' && node.href?.includes('/BlazorMonaco/'));
}
function restoreStyles() {
for (const node of monacoStyles) {
if (node.isConnected === false) {
document.head.appendChild(node);
}
}
}
function loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
@ -14,7 +33,14 @@ function loadScript(src) {
});
}
export function ensureLoaded() {
export async function ensureLoaded() {
if (loading === undefined) {
new MutationObserver(records => {
for (const record of records) {
record.addedNodes.forEach(node => isMonacoStyle(node) && monacoStyles.add(node));
}
}).observe(document.head, { childList: true });
}
loading ??= (async () => {
// Sets the AMD path config (var require = ...) and window.blazorMonaco.
await loadScript('_content/BlazorMonaco/jsInterop.js');
@ -23,5 +49,6 @@ export function ensureLoaded() {
// 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;
await loading;
restoreStyles();
}

View file

@ -0,0 +1,8 @@
// Changes the address bar without navigating. Pages are interactive one by one, so
// NavigationManager.NavigateTo runs an enhanced navigation (the page is rendered again on the
// server and merged into the DOM), which the JSON editor can't survive.
/** Replaces the current history entry's URL, keeping Blazor's history state. */
export function replace(url) {
history.replaceState(history.state, '', url);
}