Jelajahi Sumber

feat: enhance refresh interval functionality and improve view state persistence

Manuel 1 tahun lalu
induk
melakukan
db5e5b4fed
1 mengubah file dengan 111 tambahan dan 17 penghapusan
  1. 111 17
      templates/index.html

+ 111 - 17
templates/index.html

@@ -1,17 +1,27 @@
 {% extends 'base.html' %} {% block title %}Inicio | Dashboard Squid{% endblock
 {% extends 'base.html' %} {% block title %}Inicio | Dashboard Squid{% endblock
 %} {% block content %}
 %} {% block content %}
 
 
+<div class="flex flex-wrap items-center gap-3 mb-4 bg-white/70 dark:bg-gray-800/60 px-3 py-2 rounded-md border border-gray-200 shadow-sm text-sm max-w-full">
+  <label for="refresh-interval" class="text-gray-700 dark:text-gray-200 font-medium select-none">⏱️</label>
+  <div class="flex items-center gap-1">
+    <input id="refresh-interval" type="number" min="10" class="w-20 px-2 py-1 border border-gray-300 dark:border-gray-600 rounded focus:ring-1 focus:ring-blue-500 focus:outline-none bg-white/80 dark:bg-gray-700/60 text-gray-700 dark:text-gray-100" placeholder="60" aria-label="Intervalo de refresco (segundos)">
+    <span class="text-gray-500 dark:text-gray-400">s</span>
+  </div>
+  <div class="flex items-center gap-1 text-gray-600 dark:text-gray-300">
+    <span class="hidden sm:inline">→</span>
+    <span id="next-refresh" class="font-mono">--</span>
+  </div>
+  <button id="set-interval-btn" class="px-3 py-1 rounded bg-blue-600 hover:bg-blue-700 text-white font-medium transition text-xs">Aplicar</button>
+  <span id="persist-status" class="text-[11px] text-gray-400 ml-auto pr-1 opacity-0 transition-opacity"></span>
+</div>
+
 <div id="datos-conexiones" class="max-w-7xl mx-auto sm:px-6 lg:px-8">
 <div id="datos-conexiones" class="max-w-7xl mx-auto sm:px-6 lg:px-8">
   {% include 'partials/conexiones.html' %}
   {% include 'partials/conexiones.html' %}
 </div>
 </div>
 
 
 <script>
 <script>
-  // --- NUEVO: Variable para guardar el estado de la vista ---
-  // Se inicializa en 'true' porque la vista por defecto es detallada.
   let isDetailedView = true;
   let isDetailedView = true;
 
 
-  // --- NUEVO: Función central para aplicar el estado a la vista ---
-  // Esta función lee la variable 'isDetailedView' y actualiza el DOM.
   function applyViewState() {
   function applyViewState() {
     const contents = document.querySelectorAll("[data-accordion-content]");
     const contents = document.querySelectorAll("[data-accordion-content]");
     const icons = document.querySelectorAll(".user-accordion .fa-chevron-down");
     const icons = document.querySelectorAll(".user-accordion .fa-chevron-down");
@@ -20,30 +30,27 @@
     if (contents.length === 0 || !toggleAllButton) return;
     if (contents.length === 0 || !toggleAllButton) return;
 
 
     if (isDetailedView) {
     if (isDetailedView) {
-      // Aplica la VISTA DETALLADA
       contents.forEach((content) => content.classList.remove("hidden"));
       contents.forEach((content) => content.classList.remove("hidden"));
       icons.forEach((icon) => icon.classList.add("rotate-180"));
       icons.forEach((icon) => icon.classList.add("rotate-180"));
       toggleAllButton.textContent = "Ver Resumen";
       toggleAllButton.textContent = "Ver Resumen";
     } else {
     } else {
-      // Aplica la VISTA DE RESUMEN
       contents.forEach((content) => content.classList.add("hidden"));
       contents.forEach((content) => content.classList.add("hidden"));
       icons.forEach((icon) => icon.classList.remove("rotate-180"));
       icons.forEach((icon) => icon.classList.remove("rotate-180"));
       toggleAllButton.textContent = "Ver Detalles";
       toggleAllButton.textContent = "Ver Detalles";
     }
     }
   }
   }
 
 
-  // Función para configurar el botón. Ahora solo cambia el estado y llama a applyViewState.
   function setupSummaryButton() {
   function setupSummaryButton() {
     const toggleAllButton = document.getElementById("toggle-all-button");
     const toggleAllButton = document.getElementById("toggle-all-button");
     if (!toggleAllButton) return;
     if (!toggleAllButton) return;
 
 
-    // Se usa cloneNode y replaceWith para evitar añadir múltiples listeners en cada refresco.
+
     const newButton = toggleAllButton.cloneNode(true);
     const newButton = toggleAllButton.cloneNode(true);
     toggleAllButton.parentNode.replaceChild(newButton, toggleAllButton);
     toggleAllButton.parentNode.replaceChild(newButton, toggleAllButton);
 
 
     newButton.addEventListener("click", () => {
     newButton.addEventListener("click", () => {
-      isDetailedView = !isDetailedView; // Cambia el estado guardado
-      applyViewState(); // Aplica el nuevo estado a la vista
+      isDetailedView = !isDetailedView; 
+      applyViewState(); 
     });
     });
   }
   }
 
 
@@ -56,23 +63,110 @@
       const container = document.getElementById("datos-conexiones");
       const container = document.getElementById("datos-conexiones");
       container.innerHTML = html;
       container.innerHTML = html;
 
 
-      // Vuelve a configurar el botón para el nuevo contenido
       setupSummaryButton();
       setupSummaryButton();
 
 
-      // --- ¡CAMBIO CLAVE! ---
-      // Después de refrescar, aplica el último estado que guardamos.
       applyViewState();
       applyViewState();
     } catch (error) {
     } catch (error) {
       console.error("Error al actualizar conexiones:", error);
       console.error("Error al actualizar conexiones:", error);
     }
     }
   }
   }
 
 
-  document.addEventListener("DOMContentLoaded", () => {
-    // Configura el botón de resumen cuando la página carga por primera vez
+  const REFRESH_KEY = 'squidstats.refreshIntervalSec';
+  const VIEW_KEY = 'squidstats.viewMode';
+  let refreshInterval = 60000; // ms
+  let refreshTimer = null;
+  let countdownTimer = null;
+  let secondsLeft = 0;
+
+  function safeGet(key) {
+    try { return localStorage.getItem(key); } catch { return null; }
+  }
+  function safeSet(key, val) {
+    try { localStorage.setItem(key, val); persistStatus('Guardado'); } catch { persistStatus('No se pudo guardar'); }
+  }
+  function persistStatus(msg) {
+    const el = document.getElementById('persist-status');
+    if (!el) return;
+    el.textContent = msg;
+    el.classList.remove('opacity-0');
+    setTimeout(() => { el.classList.add('opacity-0'); }, 1600);
+  }
+
+  function getRefreshIntervalFromStorage() {
+    const stored = safeGet(REFRESH_KEY);
+    const val = parseInt(stored);
+    return (!isNaN(val) && val >= 5) ? val : 60;
+  }
+  function setRefreshIntervalToStorage(val) { safeSet(REFRESH_KEY, String(val)); }
+
+  function restoreViewState() {
+    const stored = safeGet(VIEW_KEY);
+    if (stored === 'summary') isDetailedView = false;
+  }
+  function saveViewState() { safeSet(VIEW_KEY, isDetailedView ? 'detailed' : 'summary'); }
+
+  const originalApplyViewState = applyViewState;
+  applyViewState = function() { 
+    originalApplyViewState();
+    saveViewState();
+  };
+
+  function startRefreshTimer() {
+    if (refreshTimer) clearInterval(refreshTimer);
+    if (countdownTimer) clearInterval(countdownTimer);
+    secondsLeft = refreshInterval / 1000;
+    updateCountdown();
+    refreshTimer = setInterval(() => {
+      refrescarConexiones();
+      secondsLeft = refreshInterval / 1000; // reset
+    }, refreshInterval);
+    countdownTimer = setInterval(() => {
+      secondsLeft -= 1;
+      if (secondsLeft < 0) secondsLeft = refreshInterval / 1000;
+      updateCountdown();
+    }, 1000);
+  }
+
+  function updateCountdown() {
+    const el = document.getElementById('next-refresh');
+    if (!el) return;
+    el.textContent = secondsLeft + 's';
+  }
+
+  function applyNewInterval(valSec) {
+    refreshInterval = valSec * 1000;
+    setRefreshIntervalToStorage(valSec);
+    startRefreshTimer();
+  }
+
+  document.addEventListener('DOMContentLoaded', () => {
+    const storedRaw = safeGet(REFRESH_KEY);
+    const intervalValue = getRefreshIntervalFromStorage();
+    document.getElementById('refresh-interval').value = intervalValue;
+    refreshInterval = intervalValue * 1000;
+    if (storedRaw === null) {
+      setRefreshIntervalToStorage(intervalValue);
+      console.debug('[SquidStats] Intervalo por defecto almacenado:', intervalValue, 's');
+    }
+    restoreViewState();
+
     setupSummaryButton();
     setupSummaryButton();
+    applyViewState();
+    startRefreshTimer();
 
 
-    // Configura el refresco para que se ejecute cada 60 segundos
-    setInterval(refrescarConexiones, 60000);
+    const intervalInput = document.getElementById('refresh-interval');
+    document.getElementById('set-interval-btn').addEventListener('click', () => {
+      const val = parseInt(intervalInput.value);
+      if (!isNaN(val) && val >= 5) {
+        applyNewInterval(val);
+      } else {
+        intervalInput.value = getRefreshIntervalFromStorage();
+      }
+    });
+    intervalInput.addEventListener('change', () => {
+      const val = parseInt(intervalInput.value);
+      if (!isNaN(val) && val >= 5) applyNewInterval(val);
+    });
   });
   });
 </script>
 </script>
 {% endblock %}
 {% endblock %}