Adds views script handling during global AJAX navigation

This commit is contained in:
BinaryAlley committed 2024-11-17 11:46:48 +02:00
1 parent 1eeb6661ca
commit a840364483
8 files changed
+183 -34

No files matched your search

+101 -23
View File
@@ -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.
*/