/* ----------------------------------------------------------------------------- * NetAlertX * Open Source Network Guard / WIFI & LAN intrusion detector * * ui_components.js - Front module. Common UI components *------------------------------------------------------------------------------- # jokob jokob@duck.com GNU GPLv3 ----------------------------------------------------------------------------- */ // ----------------------------------------------------------------------------- // Initialize device selectors / pickers fields // ----------------------------------------------------------------------------- function initDeviceSelectors(devicesListAll_JSON) { // Check if both device list exists if (devicesListAll_JSON) { // Parse the JSON string to get the device list array var devicesList = JSON.parse(devicesListAll_JSON); var selectorFieldsHTML = '' // Loop through the devices list devicesList.forEach(function(device) { selectorFieldsHTML += ``; }); selector = `
`);
updateModalState()
}
})
} else if (["add_option"].includes(feEvent)) {
showModalFieldInput (
' ' + getString('Gen_Add'),
getString('Gen_Add'),
getString('Gen_Cancel'),
getString('Gen_Okay'),
'', // curValue
'addOptionFromModalInput',
feSourceId // triggered by id
);
} else if (["add_icon"].includes(feEvent)) {
// Add new icon as base64 string
showModalInput (
' ' + getString('DevDetail_button_AddIcon'),
getString('DevDetail_button_AddIcon_Help'),
getString('Gen_Cancel'),
getString('Gen_Okay'),
() => addIconAsBase64(element), // Wrap in an arrow function
feSourceId // triggered by id
);
} else if (["copy_icons"].includes(feEvent)) {
// Ask overwrite icon types
showModalWarning (
getString('DevDetail_button_OverwriteIcons'),
getString('DevDetail_button_OverwriteIcons_Warning'),
getString('Gen_Cancel'),
getString('Gen_Okay'),
'overwriteIconType'
);
} else if (["go_to_node"].includes(feEvent)) {
goToNetworkNode('NEWDEV_devParentMAC');
} else {
console.warn(`🔺Not implemented: ${feEvent}`)
}
}
// -----------------------------------------------------------------------------
// Go to the correct network node in the Network section
function goToNetworkNode(dropdownId)
{
setCache('activeNetworkTab', $('#'+dropdownId).val().replaceAll(":","_")+'_id');
window.location.href = './network.php';
}
// --------------------------------------------------------
// Updating the execution queue in in modal pop-up
function updateModalState() {
setTimeout(function() {
// Fetch the content from the log file using an AJAX request
$.ajax({
url: '/log/execution_queue.log',
type: 'GET',
success: function(data) {
// Update the content of the HTML element (e.g., a div with id 'logContent')
$('#'+modalEventStatusId).html(data);
updateModalState();
},
error: function() {
// Handle error, such as the file not being found
$('#logContent').html('Error: Log file not found.');
}
});
}, 2000);
}
// --------------------------------------------------------
// A method to add option to select and make it selected
function addOptionFromModalInput() {
var inputVal = $(`#modal-field-input-field`).val();
console.log($('#modal-field-input-field'));
var triggeredBy = $('#modal-field-input').attr("data-myparam-triggered-by");
var targetId = $('#' + triggeredBy).attr("data-myparam-setkey");
// Add new option and set it as selected
$('#' + targetId).append(new Option(inputVal, inputVal)).val(inputVal);
}
// --------------------------------------------------------
// Generate a random MAC address starting 00:1A
function generate_NEWDEV_devMac() {
const randomHexPair = () => Math.floor(Math.random() * 256).toString(16).padStart(2, '0').toUpperCase();
$('#NEWDEV_devMac').val(`00:1A:${randomHexPair()}:${randomHexPair()}:${randomHexPair()}:${randomHexPair()}`.toLowerCase());
}
// --------------------------------------------------------
// Generate a random IP address starting 192.
function generate_NEWDEV_devLastIP() {
const randomByte = () => Math.floor(Math.random() * 256);
$('#NEWDEV_devLastIP').val(`192.${randomByte()}.${randomByte()}.${Math.floor(Math.random() * 254) + 1}`);
}
// -----------------------------------------------------------------------------
// A method to add an Icon as an option to select and make it selected
function addIconAsBase64 (el) {
var iconHtml = $('#modal-input-textarea').val();
console.log(iconHtml);
iconHtmlBase64 = btoa(iconHtml.replace(/"/g, "'"));
console.log(iconHtmlBase64);
console.log($('#modal-field-input-field'));
var triggeredBy = $('#modal-input').attr("data-myparam-triggered-by");
var targetId = $('#' + triggeredBy).attr("data-myparam-setkey");
// $('#'+targetId).val(iconHtmlBase64);
// Add new option and set it as selected
$('#' + targetId).append(new Option(iconHtmlBase64, iconHtmlBase64)).val(iconHtmlBase64);
updateIconPreview(el)
}
// -----------------------------------------------------------------------------
// initialize
// -----------------------------------------------------------------------------
function initSelect2() {
// Retrieve device list from session variable
var devicesListAll_JSON = getCache('devicesListAll_JSON');
// check if cache ready
if(isValidJSON(devicesListAll_JSON))
{
// prepare HTML DOM before initializing the frotend
initDeviceSelectors(devicesListAll_JSON)
// --------------------------------------------------------
//Initialize Select2 Elements and make them sortable
$(function () {
// Iterate over each Select2 dropdown
$('.select2').each(function() {
var selectEl = $(this).select2();
// Apply sortable functionality to the dropdown's dropdown-container
selectEl.next().children().children().children().sortable({
containment: 'parent',
update: function () {
var sortedValues = $(this).children().map(function() {
return $(this).attr('title');
}).get();
var sortedOptions = selectEl.find('option').sort(function(a, b) {
return sortedValues.indexOf($(a).text()) - sortedValues.indexOf($(b).text());
});
// Replace all options in selectEl
selectEl.empty().append(sortedOptions);
// Trigger change event on Select2
selectEl.trigger('change');
}
});
});
});
} else // cache not ready try later
{
setTimeout(() => {
initSelect2()
}, 1000);
}
}
// init functions after dom loaded
window.addEventListener("load", function() {
// try to initialize
setTimeout(() => {
initSelect2()
initializeiCheck();
}, 1000);
});
console.log("init ui_components.js")