AccountingNext/Schaad.Accounting.UI/wwwroot/js/monaco.js
Claudio Schaad 651586c4f9 JSON editor: fix switching files and returning to the page (#13)
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
2026-10-30 21:09:27 +00:00

54 lines
2.3 KiB
JavaScript

// 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;
// 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');
script.src = src;
script.onload = resolve;
script.onerror = () => reject(new Error(`${src} could not be loaded`));
document.head.appendChild(script);
});
}
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');
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));
})();
await loading;
restoreStyles();
}