Loading cleanup #660 🔄

This commit is contained in:
jokob-sk
2024-05-01 20:47:54 +10:00
parent 584fdb7734
commit 1dcca191d9
8 changed files with 144 additions and 172 deletions

View File

@@ -627,7 +627,7 @@
<script src="lib/AdminLTE/bower_components/fullcalendar/dist/fullcalendar.min.js"></script>
<script src="lib/AdminLTE/bower_components/fullcalendar/dist/locale-all.js"></script>
<!-- ----------------------------------------------------------------------- -->
<script src="js/ui_components.js?v=<?php include 'php/templates/version.php'; ?>"></script>
<script src="js/db_methods.js?v=<?php include 'php/templates/version.php'; ?>"></script>
<!-- ----------------------------------------------------------------------- -->

View File

@@ -25,7 +25,6 @@
checkPermissions([$dbPath, $confPath]);
?>
<script src="js/ui_components.js?v=<?php include 'php/templates/version.php'; ?>"></script>
<!-- Page ------------------------------------------------------------------ -->
<div class="content-wrapper">
@@ -251,7 +250,11 @@ function main () {
handleLoadingDialog()
// Hide UI elements as per settings
hideUIelements("UI_DEV_SECTIONS")
// setTimeout(() => {
hideUIelements("UI_DEV_SECTIONS")
// }, 10);
// get from cookie if available (need to use decodeURI as saved as part of URI in PHP)
cookieColumnsVisibleStr = decodeURI(getCookie("Front_Devices_Columns_Visible")).replaceAll('%2C',',')

View File

@@ -1043,167 +1043,127 @@ function arraysContainSameValues(arr1, arr2) {
// -----------------------------------------------------------------------------
// Define a unique key for storing the flag in sessionStorage
var sessionStorageKey = "myScriptExecuted_common_js";
// -----------------------------------------------------------------------------
// Clearing all the caches
function clearCache()
{
showSpinner()
resetInitializedFlag()
window.location.reload()
}
// -----------------------------------------------------------------------------
function resetInitializedFlag()
{
// Clear local storage
localStorage.clear();
// Set the flag in sessionStorage to indicate that the code and cahce needs to be reloaded
sessionStorage.setItem(sessionStorageKey, "false");
}
// -----------------------------------------------------------------------------
// check if cache needs to be refreshed because of setting changes
$.get('api/app_state.json?nocache=' + Date.now(), function(appState) {
console.log(appState["settingsImported"]*1000)
importedMiliseconds = parseInt((appState["settingsImported"]*1000));
lastReloaded = parseInt(sessionStorage.getItem(sessionStorageKey + '_time'));
if(importedMiliseconds > lastReloaded)
{
console.log("Cache needs to be refreshed because of setting changes");
setTimeout(() => {
resetInitializedFlag()
location.reload();
}, 500);
}
});
// -----------------------------------------------------------------------------
// Display spinner and reload page if not yet initialized
function handleFirstLoad(callback)
{
if(!isAppInitialized())
{
setTimeout(function() {
callback();
}, 1000);
}
}
// -----------------------------------------------------------------------------
// Check if the code has been executed before by checking sessionStorage
const sessionStorageKey = "myScriptExecuted_common_js";
var completedCalls = []
var completedCalls_final = ['cacheSettings', 'cacheStrings', 'cacheDevices'];
// -----------------------------------------------------------------------------
function isAppInitialized()
{
return arraysContainSameValues(getCache("completedCalls").split(',').filter(Boolean), completedCalls_final)
// Clearing all the caches
function clearCache() {
showSpinner();
resetInitializedFlag();
window.location.reload();
}
// Define a function that will execute the code only once
function executeOnce() {
// -----------------------------------------------------------------------------
function resetInitializedFlag() {
// Clear both sessionStorage and localStorage
sessionStorage.clear();
localStorage.clear();
}
showSpinner('')
// -----------------------------------------------------------------------------
// Function to check if cache needs to be refreshed because of setting changes
function checkSettingChanges() {
$.get('api/app_state.json?nocache=' + Date.now(), function(appState) {
const importedMilliseconds = parseInt(appState["settingsImported"] * 1000);
const lastReloaded = parseInt(sessionStorage.getItem(sessionStorageKey + '_time'));
if ( !isAppInitialized()) {
// Use cache to keep track of completed AJAX calls
var tmp_completedCalls = getCache("completedCalls")
// initialize from cache if values present
if(tmp_completedCalls != "")
{
completedCalls = tmp_completedCalls.split(',');
if (importedMilliseconds > lastReloaded) {
console.log("Cache needs to be refreshed because of setting changes");
setTimeout(() => {
resetInitializedFlag();
location.reload();
}, 500);
}
});
}
// cache everything in the right order
cacheStrings()
.then(cacheSettings)
.then(cacheDevices)
.then(() => {
// All callbacks have completed
console.log("✅ All AJAX callbacks have completed");
// location.reload()
onAllCallsComplete();
})
.catch((error) => {
console.error("Error:", error);
});
// -----------------------------------------------------------------------------
// Display spinner and reload page if not yet initialized
async function handleFirstLoad(callback) {
if (!isAppInitialized()) {
await new Promise(resolve => setTimeout(resolve, 1000));
callback();
}
}
// -----------------------------------------------------------------------------
// Check if the code has been executed before by checking sessionStorage
function isAppInitialized() {
return arraysContainSameValues(getCache("completedCalls").split(',').filter(Boolean), completedCalls_final);
}
// Define a function that will execute the code only once
async function executeOnce() {
showSpinner();
if (!isAppInitialized()) {
try {
await cacheStrings();
await cacheSettings();
await cacheDevices();
console.log("✅ All AJAX callbacks have completed");
onAllCallsComplete();
} catch (error) {
console.error("Error:", error);
}
}
}
// -----------------------------------------------------------------------------
// Function to handle successful completion of an AJAX call
const handleSuccess = (callName) => {
console.log(`AJAX call successful: ${callName} `);
// store completed call
completedCalls.push(callName)
setCache('completedCalls', mergeUniqueArrays(getCache('completedCalls').split(','), [callName]))
console.log(`AJAX call successful: ${callName}`);
completedCalls.push(callName);
setCache('completedCalls', mergeUniqueArrays(getCache('completedCalls').split(','), [callName]));
};
// -----------------------------------------------------------------------------
// Function to handle failure of an AJAX call
const handleFailure = (callName, callback) => {
// Handle AJAX call failure here
console.error(`AJAX call ${callName} failed`);
// try until successful
// callback()
// Implement retry logic here if needed
};
// -----------------------------------------------------------------------------
// Function to execute when all AJAX calls have completed
const onAllCallsComplete = () => {
// Merge local completedCalls with completedCalls_cached array - ensure uniqueness
// if cache contains values, merge those two arrays
completedCalls = mergeUniqueArrays(getCache('completedCalls').split(','), completedCalls)
// Update cache with merged completedCalls
completedCalls = mergeUniqueArrays(getCache('completedCalls').split(','), completedCalls);
setCache('completedCalls', completedCalls);
// Set the flag in sessionStorage to indicate that the code has been executed
// and save time when last time the page was initialized
sessionStorage.setItem(sessionStorageKey, "true");
const millisecondsNow = Date.now();
sessionStorage.setItem(sessionStorageKey + '_time', millisecondsNow);
// Check if all necessary strings are initialized
if (areAllStringsInitialized()) {
sessionStorage.setItem(sessionStorageKey, "true");
const millisecondsNow = Date.now();
sessionStorage.setItem(sessionStorageKey + '_time', millisecondsNow);
console.log('✔ Cache intialized');
console.log('✔ Cache initialized');
} else {
// If not all strings are initialized, retry initialization
console.log('❌ Not all strings are initialized. Retrying...');
executeOnce();
return;
}
location.reload();
// Call any other initialization functions here if needed
// No need for location.reload() here
};
// Function to check if all necessary strings are initialized
const areAllStringsInitialized = () => {
// Implement logic to check if all necessary strings are initialized
// Return true if all strings are initialized, false otherwise
return getString('UI_LANG') != ""
};
// Call the function to execute the code
executeOnce();
// Set timer for page refresh if configured
setTimeout(() => {
const refreshTime = getSetting("UI_REFRESH");
if (refreshTime && refreshTime !== "0" && refreshTime !== "") {
newTimerRefreshData(clearCache, parseInt(refreshTime)*1000);
}
}, 10000);
// Set timer for page refresh if configured
setTimeout(checkSettingChanges, 10000);
console.log("init common.js");
@@ -1212,3 +1172,4 @@ console.log("init common.js");

View File

@@ -13,13 +13,13 @@
// -----------------------------------------------------------------------------
function initDeviceSelectors() {
console.log(devicesList)
// console.log(devicesList)
// Retrieve device list from session variable
var devicesListAll_JSON = getCache('devicesListAll_JSON');
var devicesList = JSON.parse(devicesListAll_JSON);
console.log(devicesList);
// console.log(devicesList);
// Check if both device list exists
@@ -78,35 +78,8 @@ function initDeviceSelectors() {
}
// --------------------------------------------------------
//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');
}
});
});
});
@@ -281,6 +254,43 @@ function updateIconPreview (inputId) {
// initialize
// -----------------------------------------------------------------------------
initDeviceSelectors();
setTimeout(() => {
initDeviceSelectors();
// --------------------------------------------------------
//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');
}
});
});
});
}, 500);
console.log("init ui_components.js")

View File

@@ -948,8 +948,6 @@ window.onload = function asyncFooter()
</script>
<link rel="stylesheet" href="lib/AdminLTE/bower_components/select2/dist/css/select2.min.css">
<script src="lib/AdminLTE/bower_components/select2/dist/js/select2.full.min.js"></script>
<script src="lib/AdminLTE/bower_components/jquery-ui/jquery-ui.min.js"></script>

View File

@@ -15,7 +15,7 @@
<h3 class="box-title"><?= lang('Gen_Selected_Devices');?></h3>
</div>
<div class="deviceSelector col-md-9"></div>
<div class="deviceSelector col-md-9" style="z-index:5"></div>
<div class="col-md-3">
<button type="button" class="btn btn-default" onclick="markAllSelected()">
@@ -325,7 +325,7 @@ getData();
</script>
<!-- ----------------------------------------------------------------------- -->
<script src="js/ui_components.js?v=<?php include 'php/templates/version.php'; ?>"></script>
<script src="js/db_methods.js?v=<?php include 'php/templates/version.php'; ?>"></script>
<!-- ----------------------------------------------------------------------- -->

View File

@@ -41,23 +41,24 @@
<!-- ./wrapper -->
<!-- Bootstrap 3.3.7 -->
<script src="lib/AdminLTE/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="lib/AdminLTE/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- jQuery UI -->
<script src="lib/AdminLTE/bower_components/jquery-ui/jquery-ui.min.js"></script>
<!-- AdminLTE App -->
<script src="lib/AdminLTE/dist/js/adminlte.min.js"></script>
<script src="lib/AdminLTE/dist/js/adminlte.min.js"></script>
<!-- Optionally, you can add Slimscroll and FastClick plugins.
Both of these plugins are recommended to enhance the
user experience. -->
<!-- Select2 CSS -->
<link rel="stylesheet" href="lib/AdminLTE/bower_components/select2/dist/css/select2.min.css">
<!-- SlimScroll -->
<!-- <script src="lib/AdminLTE/bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script> -->
<!-- FastClick -->
<!-- <script src="lib/AdminLTE/bower_components/fastclick/lib/fastclick.js"></script> -->
<!-- NetAlertX -->
<script src="js/handle_version.js"></script>
<script src="js/ui_components.js?v=<?php include 'php/templates/version.php'; ?>"></script>
<!-- NetAlertX -------------------------------------------------------------- -->
<!-- Select2 JavaScript -->
<script src="lib/AdminLTE/bower_components/select2/dist/js/select2.full.min.js" defer></script>
<script src="js/handle_version.js"></script>
<?php
require 'migrationCheck.php';

View File

@@ -55,7 +55,6 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
<script src="js/settings_utils.js?v=<?php include 'php/templates/version.php'; ?>"></script>
<script src="js/db_methods.js?v=<?php include 'php/templates/version.php'; ?>"></script>
<script src="js/ui_components.js?v=<?php include 'php/templates/version.php'; ?>"></script>
<script src="lib/crypto/crypto-js.min.js"></script>