mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 05:01:10 +00:00
Merge pull request #75 from BinaryAlley/feature/add-view-script-handling-during-global-ajax-navigation
Adds views script handling during global AJAX navigation
This commit is contained in:
8 files changed
+183
-34
No files matched your search
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Provides functionality to manage unique script identifiers across views.
|
||||
/// </summary>
|
||||
public static class ScriptIdentifierHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Stores currently used script identifiers to prevent duplicates.
|
||||
/// </summary>
|
||||
private static readonly HashSet<string> s_usedIdentifiers = new();
|
||||
|
||||
/// <summary>
|
||||
/// Generates a unique script identifier using a GUID.
|
||||
/// </summary>
|
||||
/// <returns>A unique identifier in format "script_{guid}"</returns>
|
||||
/// <exception cref="InvalidOperationException">Thrown if a duplicate identifier is detected.</exception>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a script identifier from tracking when it's no longer needed.
|
||||
/// </summary>
|
||||
/// <param name="scriptId">The script identifier to remove.</param>
|
||||
public static void ClearIdentifier(string scriptId)
|
||||
{
|
||||
s_usedIdentifiers.Remove(scriptId);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
|
||||
@@ -59,7 +64,7 @@
|
||||
</div>
|
||||
</div>
|
||||
@section Scripts {
|
||||
<script type="text/javascript" defer>
|
||||
<script type="text/javascript" data-form="@scriptId" defer>
|
||||
document.getElementById('change-password-form').addEventListener('keypress', async (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
|
||||
@@ -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 LoginRequestModel
|
||||
|
||||
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
|
||||
@@ -53,7 +58,7 @@
|
||||
</form>
|
||||
</div>
|
||||
@section Scripts {
|
||||
<script type="text/javascript" defer>
|
||||
<script type="text/javascript" data-form="@scriptId" defer>
|
||||
document.getElementById('login-form').addEventListener('keypress', async (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
|
||||
@@ -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 RecoverPasswordRequestModel
|
||||
|
||||
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
|
||||
@@ -47,7 +52,7 @@
|
||||
</div>
|
||||
</div>
|
||||
@section Scripts {
|
||||
<script type="text/javascript" defer>
|
||||
<script type="text/javascript" data-form="@scriptId" defer>
|
||||
document.getElementById('recover-password-form').addEventListener('keypress', async (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
|
||||
@{
|
||||
string? registrationType = ViewData["RegistrationType"] 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();
|
||||
}
|
||||
|
||||
@inject IUrlService _urlService
|
||||
@@ -91,7 +93,8 @@
|
||||
</div>
|
||||
</div>
|
||||
@section Scripts {
|
||||
<script type="text/javascript" defer>
|
||||
<script type="text/javascript" data-form="@scriptId" defer>
|
||||
const btnLogin = document.getElementById('btn-login');
|
||||
document.getElementById('register-account-form').addEventListener('keypress', async (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
@@ -111,7 +114,6 @@
|
||||
const txtPasswordConfirm = form.querySelector('[name="PasswordConfirm"]');
|
||||
const chkUse2FA = form.querySelector('[name="Use2fa"]');
|
||||
const registerSuccess = document.getElementById('register-success');
|
||||
const btnLogin = document.getElementById('btn-login');
|
||||
const totpMessage = document.querySelector('#totp-message');
|
||||
const totpImage = document.querySelector('#totp-image');
|
||||
const formData = {
|
||||
@@ -128,7 +130,8 @@
|
||||
txtPasswordConfirm.value = '';
|
||||
form.classList.replace('inline', 'hidden');
|
||||
registerSuccess.classList.replace('hidden', 'inline');
|
||||
btnLogin.classList.replace('hidden', 'block');
|
||||
if (btnLogin)
|
||||
btnLogin.classList.replace('hidden', 'block');
|
||||
if (chkUse2FA.checked) {
|
||||
totpMessage.classList.remove('hidden');
|
||||
totpMessage.classList.add('block');
|
||||
@@ -147,8 +150,10 @@
|
||||
);
|
||||
document.getElementById('#hidden-use-two-fa').value = isChecked.toString();
|
||||
});
|
||||
document.getElementById('btn-login').addEventListener('click', () => {
|
||||
window.location.href = '@_urlService.GetAbsoluteUrl("Login", "Auth")';
|
||||
});
|
||||
if (btnLogin) {
|
||||
btnLogin.addEventListener('click', () => {
|
||||
window.location.href = '@_urlService.GetAbsoluteUrl("Login", "Auth")';
|
||||
});
|
||||
}
|
||||
</script>
|
||||
}
|
||||
@@ -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 @@
|
||||
</form>
|
||||
</div>
|
||||
@section Scripts {
|
||||
<script type="text/javascript" defer>
|
||||
<script type="text/javascript" data-form="@scriptId" defer>
|
||||
|
||||
document.getElementById('add-media-library-form').addEventListener('keypress', async (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
@@ -118,6 +122,12 @@
|
||||
showFileSystemBrowserDialogAsync('C:\\Users\\', true, false, addNewPaths); // TODO: take path and include hidden elements from settings
|
||||
});
|
||||
|
||||
document.querySelectorAll('.remove-form-table-row-icon').forEach(icon => {
|
||||
icon.addEventListener('click', function () {
|
||||
this.parentElement.remove();
|
||||
});
|
||||
});
|
||||
|
||||
function addNewPaths(selectedPaths) {
|
||||
// get the form table where the new paths will be added
|
||||
const formTable = document.querySelector('.form-table');
|
||||
|
||||
@@ -46,6 +46,8 @@
|
||||
|
||||
<script defer src="~/js/notifications.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/site.js" asp-append-version="true"></script>
|
||||
@await RenderSectionAsync("Scripts", required: false)
|
||||
<div data-section="scripts">
|
||||
@await RenderSectionAsync("Scripts", required: false)
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user