Files
netwatch/app/assets/js/app.js
2026-02-16 13:56:01 +01:00

111 lines
3.2 KiB
JavaScript

/**
* app/assets/js/app.js
*/
window.APP = {
state: {
deviceTypes: [],
devices: [],
racks: [],
floors: [],
connections: [],
},
capabilities: {
hasGlobalDataApi: false,
}
};
document.addEventListener('DOMContentLoaded', () => {
initViewModules();
initEventHandlers();
});
function initViewModules() {
if (typeof window.Dashboard?.init === 'function') {
window.Dashboard.init();
}
// Both modules are loaded via script tags in header.php.
// They are self-initializing and only run when expected DOM nodes exist.
window.dispatchEvent(new CustomEvent('app:modules-initialized'));
}
function initEventHandlers() {
bindFormSubmitButton('#save-device-type', 'form[action*="module=device_types"][action*="save"]');
bindFormSubmitButton('#save-device', 'form[action*="module=devices"][action*="save"]');
bindFormSubmitButton('#save-floor', 'form[action*="module=floors"][action*="save"]');
bindFormSubmitButton('#save-rack', 'form[action*="module=racks"][action*="save"]');
document.querySelectorAll('[data-confirm-delete]').forEach((btn) => {
btn.addEventListener('click', (event) => {
event.preventDefault();
const message = btn.getAttribute('data-confirm-message') || 'Aktion ausfuehren?';
if (confirm(message)) {
const href = btn.getAttribute('href') || btn.dataset.href;
if (href) {
window.location.href = href;
}
}
});
});
document.querySelectorAll('[data-filter-submit]').forEach((el) => {
el.addEventListener('change', () => {
const form = el.closest('form');
if (form) {
form.requestSubmit();
}
});
});
}
function bindFormSubmitButton(buttonSelector, formSelector) {
const button = document.querySelector(buttonSelector);
if (!button) {
return;
}
button.addEventListener('click', (event) => {
event.preventDefault();
const form = button.closest('form') || document.querySelector(formSelector);
if (form) {
form.requestSubmit();
}
});
}
function ajaxPost(url, data, callback, onError) {
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.onload = function onLoad() {
if (xhr.status >= 200 && xhr.status < 300) {
let parsed = null;
try {
parsed = JSON.parse(xhr.responseText);
} catch (error) {
if (typeof onError === 'function') {
onError(error);
}
return;
}
callback(parsed);
return;
}
if (typeof onError === 'function') {
onError(new Error('AJAX error: ' + xhr.status));
}
};
xhr.onerror = function onXhrError() {
if (typeof onError === 'function') {
onError(new Error('Netzwerkfehler'));
}
};
xhr.send(JSON.stringify(data));
}
window.APP.ajaxPost = ajaxPost;