diff --git a/src/Lumina.Presentation.Web/Common/Services/ScriptIdentifierHelper.cs b/src/Lumina.Presentation.Web/Common/Services/ScriptIdentifierHelper.cs new file mode 100644 index 00000000..5a277908 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Services/ScriptIdentifierHelper.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Common.Services; + +/// +/// Provides functionality to manage unique script identifiers across views. +/// +public static class ScriptIdentifierHelper +{ + /// + /// Stores currently used script identifiers to prevent duplicates. + /// + private static readonly HashSet s_usedIdentifiers = new(); + + /// + /// Generates a unique script identifier using a GUID. + /// + /// A unique identifier in format "script_{guid}" + /// Thrown if a duplicate identifier is detected. + public static string GenerateScriptId() + { + string scriptId = $"script_{Guid.NewGuid():N}"; + if (!s_usedIdentifiers.Add(scriptId)) + throw new InvalidOperationException($"Script identifier {scriptId} is already in use!"); + return scriptId; + } + + /// + /// Removes a script identifier from tracking when it's no longer needed. + /// + /// The script identifier to remove. + public static void ClearIdentifier(string scriptId) + { + s_usedIdentifiers.Remove(scriptId); + } +} diff --git a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml index ebae7dcd..3c71fa20 100644 --- a/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml +++ b/src/Lumina.Presentation.Web/Views/Auth/ChangePassword.cshtml @@ -7,6 +7,11 @@ @inject IUrlService _urlService +@{ + // generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler + var scriptId = ScriptIdentifierHelper.GenerateScriptId(); +} + @model ChangePasswordRequestModel
@@ -59,7 +64,7 @@
@section Scripts { - } diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml index be4ef6cb..1af0a4bd 100644 --- a/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml @@ -3,9 +3,12 @@ *@ @using Lumina.Presentation.Web.Common.Models.Libraries +@using Lumina.Presentation.Web.Common.Services @{ var id = Context.Request.RouteValues["id"] as string; + // generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler + var scriptId = ScriptIdentifierHelper.GenerateScriptId(); } @model LibraryModel @@ -84,7 +87,8 @@ @section Scripts { - - @await RenderSectionAsync("Scripts", required: false) +
+ @await RenderSectionAsync("Scripts", required: false) +
diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index 780b08d1..201a8067 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -27,13 +27,15 @@ async function callApiGetAsync(url) { const response = await fetch(url); // call the API if (response.redirected) // if a redirect is requested, perform it window.location.href = response.url; - if (!response.ok) - throw new Error('Network response was not ok'); - const jsonResponse = await response.json(); - if (jsonResponse.success) - return jsonResponse.data; - else - notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR); + else { + if (!response.ok) + throw new Error('Network response was not ok'); + const jsonResponse = await response.json(); + if (jsonResponse.success) + return jsonResponse.data; + else + notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR); + } } catch (error) { console.error('Error:', error); notificationService.show(error, NotificationType.ERROR); @@ -75,16 +77,18 @@ async function callApiPostAsync(url, data, options = {}) { }); if (response.redirected) // if a redirect is requested, perform it window.location.href = response.url; - if (!response.ok) - throw new Error(`HTTP error! status: ${response.status}`); - const jsonResponse = await response.json(); - if (jsonResponse.success) { - if (jsonResponse.message) - notificationService.show(jsonResponse.message, NotificationType.SUCCESS); - return jsonResponse.data; + else { + if (!response.ok) + throw new Error(`HTTP error! status: ${response.status}`); + const jsonResponse = await response.json(); + if (jsonResponse.success) { + if (jsonResponse.message) + notificationService.show(jsonResponse.message, NotificationType.SUCCESS); + return jsonResponse.data; + } + else + notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR); } - else - notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR); } catch (error) { console.error('Error:', error); notificationService.show(error, NotificationType.ERROR); @@ -114,7 +118,6 @@ function initializeNavigation() { window.addEventListener('popstate', handlePopState); } - /** * Binds AJAX navigation behavior to links marked with .nav-link class. */ @@ -170,10 +173,71 @@ async function updateContent(url, addToHistory) { const content = doc.querySelector('main').innerHTML; const title = doc.querySelector('title')?.textContent || document.title; + // find scripts section content + const scriptsSection = doc.querySelector('[data-section="scripts"]'); + // update the page document.querySelector('main').innerHTML = content; document.title = title; + // handle Scripts section of the loaded view + if (scriptsSection) { + // get or create scripts container + let scriptsContainer = document.querySelector('[data-section="scripts"]'); + if (!scriptsContainer) { + scriptsContainer = document.createElement('div'); + scriptsContainer.setAttribute('data-section', 'scripts'); + document.body.appendChild(scriptsContainer); + } + + // clear existing scripts in container + scriptsContainer.innerHTML = ''; + + // extract and execute scripts + const scriptElements = Array.from(scriptsSection.getElementsByTagName('script')); + + for (const script of scriptElements) { + const scriptId = script.getAttribute('data-form'); + + // remove existing script with same Id if it exists + const existingScript = document.querySelector(`script[data-form="${scriptId}"]`); + if (existingScript) + existingScript.remove(); + + const newScript = document.createElement('script'); + + // copy script attributes + Array.from(script.attributes).forEach(attr => { + newScript.setAttribute(attr.name, attr.value); + }); + + // handle both inline and external scripts + if (script.src) { + newScript.src = script.src; + // wait for external script to load + await new Promise((resolve, reject) => { + newScript.onload = resolve; + newScript.onerror = reject; + }); + } else { + // wrap inline scripts in a safety check + newScript.textContent = ` + (function() { + const safeGetElement = (id) => document.getElementById(id); + const safeAddEventListener = (element, event, handler) => { + if (element) + element.addEventListener(event, handler); + }; + ${script.textContent} + })(); + `; + } + + // add script to scripts container + scriptsContainer.appendChild(newScript); + } + } + // bind navigation links in the new content bindNavigationLinks(); @@ -191,6 +255,26 @@ async function updateContent(url, addToHistory) { } } +/** + * Dynamically loads and executes scripts within the content area once. + * @param {HTMLElement} container - The container to scan for scripts. + */ +function executeScriptsOnce(container) { + // Find all script tags inside the container + container.querySelectorAll('script').forEach(script => { + if (!script.dataset.executed) { + const newScript = document.createElement('script'); + newScript.textContent = script.textContent; // Inline scripts + if (script.src) newScript.src = script.src; // External scripts + newScript.async = script.async; + newScript.defer = script.defer; + + script.dataset.executed = 'true'; // Mark the script as executed + document.body.appendChild(newScript); + } + }); +} + //+======================================================================================+ //| Common Helper Functions | //+======================================================================================+ @@ -391,12 +475,6 @@ function getElementOffset(id) { }; } -document.querySelectorAll('.remove-form-table-row-icon').forEach(icon => { - icon.addEventListener('click', function () { - this.parentElement.remove(); - }); -}); - /** * Toggles the visibility of the audio player. */