aarnal80 commited on
Commit
b48436d
·
verified ·
1 Parent(s): 8177516

Update js/proa.js

Browse files
Files changed (1) hide show
  1. js/proa.js +72 -60
js/proa.js CHANGED
@@ -1,23 +1,27 @@
1
- // js/proa.js - Lógica para el visor de Guías PROA (v5 - Lista Única con Reemplazo y Botones)
2
 
3
  // ======================================================================
4
  // BLOCK START: DOM Elements Selection & Initial Setup
5
  // ======================================================================
6
- console.log("[proa.js v5] Script cargado. Esperando DOMContentLoaded...");
7
 
8
  window.addEventListener('DOMContentLoaded', () => {
9
- console.log("[proa.js v5] DOMContentLoaded detectado. Iniciando setup...");
10
 
11
- const guideIndexContainer = document.getElementById('guide-index-container');
12
- const guideContentDisplay = document.getElementById('guide-content-display');
13
- const togglePediatricCheckbox = document.getElementById('togglePediatric');
 
 
 
14
 
15
- const guidesDataUrl = 'guides_data.json'; // Asume que está en proa/
16
 
17
- if (!guideIndexContainer || !guideContentDisplay || !togglePediatricCheckbox) {
18
- console.error("[proa.js v5] Error Crítico: No se encontraron elementos DOM.");
19
- if(guideIndexContainer) guideIndexContainer.innerHTML = '<p class="text-red-500 font-semibold">Error: Interfaz no inicializada.</p>';
20
- return;
 
21
  }
22
  // ======================================================================
23
  // BLOCK END: DOM Elements Selection & Initial Setup
@@ -27,74 +31,82 @@ window.addEventListener('DOMContentLoaded', () => {
27
  // BLOCK START: State Variables
28
  // ======================================================================
29
  let allGuides = []; // Datos del JSON
30
- let currentGuideFile = null; // Archivo de la guía activa
31
- // Mapeo simple de categorías a iconos de FontAwesome (¡Añade más según necesites!)
32
- const categoryIcons = {
33
- "Infecciones Relacionadas con Dispositivos": "fa-syringe",
34
- "Digestivo y Abdominal": "fa-stomach",
35
- "Cardiovascular": "fa-heart-pulse",
36
- "Gineco-Obstetricia": "fa-person-pregnant", // O fa-venus
37
- "Onco-Hematología": "fa-shield-virus",
38
- "Oftalmología": "fa-eye",
39
- "ORL": "fa-ear-listen",
40
- "Osteoarticular": "fa-bone",
41
- "Piel y Partes Blandas": "fa-band-aid",
42
- "Respiratorio": "fa-lungs",
43
- "Neurología": "fa-brain",
44
- "Pediatría General": "fa-child",
45
- "Urología": "fa-toilet-paper", // O fa-bacteria
46
- // Añade más categorías e iconos aquí
47
- "default": "fa-book-medical" // Icono por defecto
48
- };
49
  // ======================================================================
50
  // BLOCK END: State Variables
51
  // ======================================================================
52
 
53
  // ======================================================================
54
- // BLOCK START: Function to Fetch Guides Data (from JSON) - Sin Cambios
55
  // ======================================================================
56
  async function loadGuidesData() {
57
- console.log(`[proa.js v5] Cargando datos de guías desde: ${guidesDataUrl}`);
58
- guideIndexContainer.innerHTML = '<p class="text-gray-500 text-sm">Cargando guías...</p>';
59
- allGuides = [];
 
 
 
 
 
60
 
61
  try {
62
- const response = await fetch(guidesDataUrl);
63
  if (!response.ok) throw new Error(`Error HTTP ${response.status} al cargar ${guidesDataUrl}`);
64
- allGuides = await response.json();
65
  if (!Array.isArray(allGuides)) throw new Error("JSON no es un array válido.");
66
  allGuides = allGuides.filter(g => g.id && g.title && g.category && g.file);
67
 
68
- // Ordenar: Pediátricas separadas o juntas según preferencia, luego por categoría y título
69
- allGuides.sort((a, b) => {
70
- // Puedes descomentar esto si quieres agrupar Ped vs Adulto primero
71
- // if (a.isPediatric !== b.isPediatric) return a.isPediatric ? 1 : -1; // Adultos primero
72
- if (a.category < b.category) return -1;
73
- if (a.category > b.category) return 1;
74
- if (a.title < b.title) return -1;
75
- if (a.title > b.title) return 1;
76
- return a.isPediatric ? 1 : -1; // Si mismo título, adulto primero
77
- });
78
-
79
- console.log(`[proa.js v5] Datos JSON cargados (${allGuides.length} guías).`);
80
- renderGuideIndex(); // Renderizar el índice inicial (mostrará adultos por defecto)
81
 
82
  } catch (error) {
83
- console.error("[proa.js v5] Error fatal al cargar o parsear el JSON:", error);
84
- guideIndexContainer.innerHTML = `<p class="text-red-600 font-semibold">Error: ${error.message}.</p>`;
85
- guideContentDisplay.innerHTML = '<p class="text-gray-500 text-center mt-10">Error al cargar datos.</p>';
86
  }
87
  }
88
  // ======================================================================
89
  // BLOCK END: Function to Fetch Guides Data (from JSON)
90
  // ======================================================================
91
-
92
  // ======================================================================
93
- // BLOCK START: Function to Render Guide Index (Lista de Botones Agrupados)
94
  // ======================================================================
95
- function renderGuideIndex() {
96
- console.log("[proa.js v5] Renderizando índice de guías...");
97
- guideIndexContainer.innerHTML = ''; // Limpiar contenedor
98
-
99
- // --- LÓGICA DE REEMPLAZO ---
100
- const showOnly
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // js/proa.js - Lógica para el visor de Guías PROA (v6 - Basado en JSON y Dropdowns en Cascada)
2
 
3
  // ======================================================================
4
  // BLOCK START: DOM Elements Selection & Initial Setup
5
  // ======================================================================
6
+ console.log("[proa.js v6] Script cargado. Esperando DOMContentLoaded...");
7
 
8
  window.addEventListener('DOMContentLoaded', () => {
9
+ console.log("[proa.js v6] DOMContentLoaded detectado. Iniciando setup...");
10
 
11
+ // Selectores principales
12
+ const categorySelector = document.getElementById('categorySelector');
13
+ const guideSelector = document.getElementById('guideSelector');
14
+ const guideSelectorContainer = document.getElementById('guideSelectorContainer');
15
+ const guideContentDisplay = document.getElementById('guide-content-display');
16
+ const togglePediatricCheckbox = document.getElementById('togglePediatric');
17
 
18
+ const guidesDataUrl = 'guides_data.json'; // Ruta al archivo JSON (en proa/)
19
 
20
+ // Verificar elementos críticos
21
+ if (!categorySelector || !guideSelector || !guideSelectorContainer || !guideContentDisplay || !togglePediatricCheckbox) {
22
+ console.error("[proa.js v6] Error Crítico: No se encontraron elementos DOM esenciales (selectores, contenedor o display).");
23
+ guideContentDisplay.innerHTML = '<p class="text-red-500 font-semibold text-center py-10">Error: No se pudo inicializar la interfaz.</p>';
24
+ return;
25
  }
26
  // ======================================================================
27
  // BLOCK END: DOM Elements Selection & Initial Setup
 
31
  // BLOCK START: State Variables
32
  // ======================================================================
33
  let allGuides = []; // Datos del JSON
34
+ let currentGuideFile = null; // Nombre del archivo de la guía activa
35
+ let categories = []; // Lista única de categorías
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  // ======================================================================
37
  // BLOCK END: State Variables
38
  // ======================================================================
39
 
40
  // ======================================================================
41
+ // BLOCK START: Function to Fetch Guides Data (from JSON)
42
  // ======================================================================
43
  async function loadGuidesData() {
44
+ console.log(`[proa.js v6] Cargando datos de guías desde: ${guidesDataUrl}`);
45
+ // Limpiar selectores y contenido
46
+ categorySelector.innerHTML = '<option value="">Cargando categorías...</option>';
47
+ guideSelector.innerHTML = '<option value="">-- Seleccione Guía --</option>';
48
+ guideSelectorContainer.classList.add('hidden');
49
+ guideContentDisplay.innerHTML = '<div class="text-center py-16"><i class="fas fa-spinner fa-spin text-3xl text-gray-400"></i><p class="mt-2 text-gray-500">Cargando datos...</p></div>';
50
+ allGuides = [];
51
+ categories = [];
52
 
53
  try {
54
+ const response = await fetch(guidesDataUrl);
55
  if (!response.ok) throw new Error(`Error HTTP ${response.status} al cargar ${guidesDataUrl}`);
56
+ allGuides = await response.json();
57
  if (!Array.isArray(allGuides)) throw new Error("JSON no es un array válido.");
58
  allGuides = allGuides.filter(g => g.id && g.title && g.category && g.file);
59
 
60
+ // Extraer y ordenar categorías únicas
61
+ categories = [...new Set(allGuides.map(g => g.category))].sort();
62
+
63
+ console.log(`[proa.js v6] Datos JSON cargados (${allGuides.length} guías, ${categories.length} categorías).`);
64
+
65
+ populateCategorySelector(); // Poblar el primer dropdown
66
+ resetToInitialState(); // Poner la UI en estado inicial limpio
 
 
 
 
 
 
67
 
68
  } catch (error) {
69
+ console.error("[proa.js v6] Error fatal al cargar o parsear el JSON:", error);
70
+ categorySelector.innerHTML = '<option value="">Error al cargar</option>';
71
+ guideContentDisplay.innerHTML = `<p class="text-red-600 font-semibold text-center py-10">Error: ${error.message}.</p>`;
72
  }
73
  }
74
  // ======================================================================
75
  // BLOCK END: Function to Fetch Guides Data (from JSON)
76
  // ======================================================================
77
+
78
  // ======================================================================
79
+ // BLOCK START: UI Update Functions
80
  // ======================================================================
81
+
82
+ // Pone la UI en el estado inicial (sin selecciones)
83
+ function resetToInitialState() {
84
+ categorySelector.value = "";
85
+ guideSelector.innerHTML = '<option value="">-- Seleccione Guía --</option>';
86
+ guideSelectorContainer.classList.add('hidden');
87
+ guideContentDisplay.innerHTML = '<div class="text-center py-16"><i class="fas fa-file-alt text-5xl text-gray-300 mb-4"></i><p class="text-gray-500">Selecciona una categoría y luego una guía específica.</p></div>';
88
+ currentGuideFile = null;
89
+ }
90
+
91
+ // Llena el selector de categorías
92
+ function populateCategorySelector() {
93
+ categorySelector.innerHTML = '<option value="">-- Seleccione Categoría --</option>'; // Opción por defecto
94
+ categories.forEach(category => {
95
+ const option = document.createElement('option');
96
+ option.value = category;
97
+ option.textContent = category;
98
+ categorySelector.appendChild(option);
99
+ });
100
+ console.log("[proa.js v6] Selector de categorías poblado.");
101
+ }
102
+
103
+ // Llena el selector de guías específicas basado en la categoría y el filtro pediátrico
104
+ function populateGuideSelector() {
105
+ const selectedCategory = categorySelector.value;
106
+ const showOnlyPediatric = togglePediatricCheckbox.checked;
107
+ guideSelector.innerHTML = '<option value="">-- Seleccione Guía --</option>'; // Resetear opciones
108
+ currentGuideFile = null; // Deseleccionar guía al cambiar categoría o filtro
109
+
110
+ if (!selectedCategory) {
111
+ guideSelectorContainer.classList.add('hidden'); // Ocultar si no hay categoría
112
+ resetToInitialState(); // Volver al mensaje