aarnal80 commited on
Commit
3cc36f4
·
verified ·
1 Parent(s): 8a66038

Update js/proa.js

Browse files
Files changed (1) hide show
  1. js/proa.js +202 -45
js/proa.js CHANGED
@@ -1,12 +1,12 @@
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');
@@ -15,14 +15,14 @@ window.addEventListener('DOMContentLoaded', () => {
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
28
  // ======================================================================
@@ -30,9 +30,9 @@ window.addEventListener('DOMContentLoaded', () => {
30
  // ======================================================================
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
  // ======================================================================
@@ -41,9 +41,8 @@ window.addEventListener('DOMContentLoaded', () => {
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>';
@@ -51,24 +50,41 @@ window.addEventListener('DOMContentLoaded', () => {
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
  // ======================================================================
@@ -79,34 +95,175 @@ window.addEventListener('DOMContentLoaded', () => {
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
 
1
+ // js/proa.js - Lógica para el visor de Guías PROA (v6.1 - Dropdowns + Debugging)
2
 
3
  // ======================================================================
4
  // BLOCK START: DOM Elements Selection & Initial Setup
5
  // ======================================================================
6
+ console.log("[proa.js v6.1] Script cargado. Esperando DOMContentLoaded...");
7
 
8
  window.addEventListener('DOMContentLoaded', () => {
9
+ console.log("[proa.js v6.1] DOMContentLoaded detectado. Iniciando setup...");
10
 
11
  // Selectores principales
12
  const categorySelector = document.getElementById('categorySelector');
 
15
  const guideContentDisplay = document.getElementById('guide-content-display');
16
  const togglePediatricCheckbox = document.getElementById('togglePediatric');
17
 
18
+ const guidesDataUrl = 'guides_data.json'; // Asume que está en proa/
19
 
 
20
  if (!categorySelector || !guideSelector || !guideSelectorContainer || !guideContentDisplay || !togglePediatricCheckbox) {
21
+ console.error("[proa.js v6.1] Error Crítico: No se encontraron elementos DOM esenciales.");
22
+ guideContentDisplay.innerHTML = '<p class="text-red-500 font-semibold text-center py-10">Error: Interfaz no inicializada.</p>';
23
  return;
24
  }
25
+ console.log("[proa.js v6.1] Elementos DOM encontrados.");
26
  // ======================================================================
27
  // BLOCK END: DOM Elements Selection & Initial Setup
28
  // ======================================================================
 
30
  // ======================================================================
31
  // BLOCK START: State Variables
32
  // ======================================================================
33
+ let allGuides = [];
34
+ let currentGuideFile = null;
35
+ let categories = [];
36
  // ======================================================================
37
  // BLOCK END: State Variables
38
  // ======================================================================
 
41
  // BLOCK START: Function to Fetch Guides Data (from JSON)
42
  // ======================================================================
43
  async function loadGuidesData() {
44
+ console.log(`[proa.js v6.1] Iniciando loadGuidesData desde: ${guidesDataUrl}`);
45
+ categorySelector.innerHTML = '<option value="">Cargando...</option>';
 
46
  guideSelector.innerHTML = '<option value="">-- Seleccione Guía --</option>';
47
  guideSelectorContainer.classList.add('hidden');
48
  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
  categories = [];
51
 
52
  try {
53
+ console.log("[proa.js v6.1] Realizando fetch...");
54
+ const response = await fetch(guidesDataUrl);
55
+ console.log(`[proa.js v6.1] Fetch completado. Status: ${response.status}`);
56
+ if (!response.ok) {
57
+ throw new Error(`Error HTTP ${response.status} al cargar ${guidesDataUrl}. ¿Existe el archivo en proa/ y es accesible?`);
58
+ }
59
+
60
+ console.log("[proa.js v6.1] Parseando JSON...");
61
+ allGuides = await response.json();
62
+ console.log("[proa.js v6.1] JSON parseado.");
63
+
64
+ if (!Array.isArray(allGuides)) {
65
+ console.error("[proa.js v6.1] El contenido parseado no es un Array:", allGuides);
66
+ throw new Error("El archivo JSON no contiene un array válido.");
67
+ }
68
+
69
+ // Filtrar por si alguna entrada no tiene los campos mínimos
70
  allGuides = allGuides.filter(g => g.id && g.title && g.category && g.file);
71
+ console.log(`[proa.js v6.1] Guías válidas filtradas: ${allGuides.length}`);
72
 
73
  // Extraer y ordenar categorías únicas
74
+ console.log("[proa.js v6.1] Extrayendo y ordenando categorías...");
75
  categories = [...new Set(allGuides.map(g => g.category))].sort();
76
+ console.log(`[proa.js v6.1] Categorías encontradas: ${categories.join(', ')}`);
77
 
78
+ console.log("[proa.js v6.1] Llamando a populateCategorySelector...");
79
+ populateCategorySelector();
80
+ console.log("[proa.js v6.1] Llamando a resetToInitialState...");
81
+ resetToInitialState();
82
+ console.log("[proa.js v6.1] Carga inicial completada con éxito.");
83
 
84
  } catch (error) {
85
+ console.error("[proa.js v6.1] Error durante loadGuidesData:", error);
86
+ categorySelector.innerHTML = '<option value="">Error carga</option>';
87
+ guideContentDisplay.innerHTML = `<p class="text-red-600 font-semibold text-center py-10">Error al cargar datos: ${error.message}. Revisa la consola.</p>`;
88
  }
89
  }
90
  // ======================================================================
 
95
  // BLOCK START: UI Update Functions
96
  // ======================================================================
97
 
 
98
  function resetToInitialState() {
99
+ console.log("[proa.js v6.1] Reseteando a estado inicial.");
100
+ try {
101
+ categorySelector.value = "";
102
+ guideSelector.innerHTML = '<option value="">-- Seleccione Guía --</option>';
103
+ guideSelectorContainer.classList.add('hidden');
104
+ guideContentDisplay.innerHTML = '<div class="text-center py-16 text-gray-400"><i class="fas fa-file-alt text-5xl mb-4"></i><p>Selecciona una categoría y guía.</p></div>';
105
+ currentGuideFile = null;
106
+ } catch (e) {
107
+ console.error("[proa.js v6.1] Error en resetToInitialState:", e);
108
+ }
109
  }
110
 
 
111
  function populateCategorySelector() {
112
+ console.log("[proa.js v6.1] Poblando selector de categorías...");
113
+ try {
114
+ categorySelector.innerHTML = '<option value="">-- Seleccione Categoría --</option>';
115
+ if (categories.length === 0) {
116
+ console.warn("[proa.js v6.1] No hay categorías para poblar.");
117
+ categorySelector.innerHTML = '<option value="">No hay categorías</option>';
118
+ return;
119
+ }
120
+ categories.forEach(category => {
121
+ const option = document.createElement('option');
122
+ option.value = category;
123
+ option.textContent = category;
124
+ categorySelector.appendChild(option);
125
+ });
126
+ console.log("[proa.js v6.1] Selector de categorías poblado OK.");
127
+ } catch (e) {
128
+ console.error("[proa.js v6.1] Error en populateCategorySelector:", e);
129
+ categorySelector.innerHTML = '<option value="">Error</option>';
130
+ }
131
  }
132
 
 
133
  function populateGuideSelector() {
134
  const selectedCategory = categorySelector.value;
135
  const showOnlyPediatric = togglePediatricCheckbox.checked;
136
+ console.log(`[proa.js v6.1] Poblando selector de guías para Categoría: '${selectedCategory}', Solo Pediátricas: ${showOnlyPediatric}`);
137
+
138
+ try {
139
+ guideSelector.innerHTML = '<option value="">-- Seleccione Guía --</option>';
140
+ currentGuideFile = null;
141
+
142
+ if (!selectedCategory) {
143
+ guideSelectorContainer.classList.add('hidden');
144
+ // No resetear contenido aquí, solo ocultar selector
145
+ console.log("[proa.js v6.1] No hay categoría seleccionada, ocultando selector de guías.");
146
+ return;
147
+ }
148
+
149
+ const guidesInCategory = allGuides.filter(guide =>
150
+ guide.category === selectedCategory &&
151
+ guide.isPediatric === showOnlyPediatric
152
+ );
153
+
154
+ guidesInCategory.sort((a,b) => a.title.localeCompare(b.title));
155
+
156
+ if (guidesInCategory.length > 0) {
157
+ guidesInCategory.forEach(guide => {
158
+ const option = document.createElement('option');
159
+ option.value = guide.file;
160
+ option.textContent = guide.title;
161
+ guideSelector.appendChild(option);
162
+ });
163
+ guideSelectorContainer.classList.remove('hidden');
164
+ console.log(`[proa.js v6.1] Selector de guías poblado con ${guidesInCategory.length} guías.`);
165
+ // Si el contenido estaba mostrando algo, lo limpiamos al cambiar las opciones de guía
166
+ if (guideContentDisplay.firstChild && !guideContentDisplay.firstChild.classList?.contains('text-gray-400')) {
167
+ guideContentDisplay.innerHTML = '<div class="text-center py-16 text-gray-400"><i class="fas fa-hand-pointer text-5xl mb-4"></i><p>Selecciona una guía específica.</p></div>';
168
+ }
169
+ } else {
170
+ guideSelector.innerHTML = '<option value="">-- No hay guías --</option>';
171
+ guideSelectorContainer.classList.remove('hidden');
172
+ guideContentDisplay.innerHTML = `<div class="text-center py-16 text-gray-400"><i class="fas fa-info-circle text-5xl mb-4"></i><p>No hay guías ${showOnlyPediatric ? 'pediátricas' : 'de adultos'} para '${selectedCategory}'.</p></div>`;
173
+ console.log(`[proa.js v6.1] No se encontraron guías para los filtros actuales.`);
174
+ }
175
+ } catch (e) {
176
+ console.error("[proa.js v6.1] Error en populateGuideSelector:", e);
177
+ guideSelector.innerHTML = '<option value="">Error</option>';
178
+ guideSelectorContainer.classList.add('hidden');
179
+ }
180
+ }
181
+ // ======================================================================
182
+ // BLOCK END: UI Update Functions
183
+ // ======================================================================
184
+
185
+ // ======================================================================
186
+ // BLOCK START: Function to Load External Guide Content (Sin cambios v5->v6.1)
187
+ // ======================================================================
188
+ async function loadGuideContent(guideFileName) {
189
+ if (!guideFileName) {
190
+ // Si se selecciona "-- Seleccione Guía --", limpiar contenido
191
+ guideContentDisplay.innerHTML = '<div class="text-center py-16 text-gray-400"><i class="fas fa-hand-pointer text-5xl mb-4"></i><p>Selecciona una guía específica.</p></div>';
192
+ currentGuideFile = null;
193
+ return;
194
+ }
195
+ console.log(`[proa.js v6.1] Solicitando contenido de: ${guideFileName}`);
196
+ guideContentDisplay.innerHTML = '<div class="text-center py-20"><i class="fas fa-spinner fa-spin text-3xl text-gray-400"></i><p class="mt-2 text-gray-500">Cargando contenido...</p></div>';
197
+ const guideUrl = guideFileName;
198
+ currentGuideFile = guideFileName;
199
+
200
+ try {
201
+ const response = await fetch(guideUrl);
202
+ if (!response.ok) throw new Error(`Error HTTP ${response.status} al cargar ${guideUrl}`);
203
+ const htmlText = await response.text();
204
+ const parser = new DOMParser();
205
+ const doc = parser.parseFromString(htmlText, 'text/html');
206
+ // Selector del contenido principal en las guías individuales
207
+ const contentNode = doc.querySelector('.max-w-4xl.mx-auto.px-4.py-8') || doc.body;
208
+
209
+ if (contentNode) {
210
+ const clonedContent = contentNode.cloneNode(true);
211
+ const scripts = clonedContent.querySelectorAll('script');
212
+ scripts.forEach(script => script.remove());
213
+ if (scripts.length > 0) console.log(`[proa.js v6.1] Eliminados ${scripts.length} script(s) de ${guideFileName}.`);
214
+
215
+ guideContentDisplay.innerHTML = '';
216
+ guideContentDisplay.appendChild(clonedContent);
217
+ console.log(`[proa.js v6.1] Contenido de ${guideFileName} mostrado.`);
218
+ guideContentDisplay.scrollTop = 0;
219
+
220
+ } else {
221
+ throw new Error(`No se encontró nodo de contenido en '${guideFileName}'.`);
222
+ }
223
+ } catch (error) {
224
+ console.error(`[proa.js v6.1] Error al cargar/mostrar ${guideFileName}:`, error);
225
+ guideContentDisplay.innerHTML = `<div class="text-center py-20 text-red-600">Error: ${error.message}</div>`;
226
+ currentGuideFile = null;
227
+ }
228
+ }
229
+ // ======================================================================
230
+ // BLOCK END: Function to Load External Guide Content
231
+ // ======================================================================
232
+
233
+ // ======================================================================
234
+ // BLOCK START: Event Listeners Setup
235
+ // ======================================================================
236
+ categorySelector.addEventListener('change', () => {
237
+ console.log("[proa.js v6.1] Cambió la categoría.");
238
+ guideContentDisplay.innerHTML = ''; // Limpiar contenido
239
+ populateGuideSelector();
240
+ });
241
+
242
+ guideSelector.addEventListener('change', (event) => {
243
+ console.log("[proa.js v6.1] Cambió la guía específica.");
244
+ loadGuideContent(event.target.value);
245
+ });
246
+
247
+ togglePediatricCheckbox.addEventListener('change', () => {
248
+ console.log('[proa.js v6.1] Cambiado filtro pediátrico.');
249
+ // Limpiar contenido y repoblar selector de guías (manteniendo categoría)
250
+ guideContentDisplay.innerHTML = '';
251
+ populateGuideSelector();
252
+ });
253
+ console.log("[proa.js v6.1] Listeners añadidos.");
254
+ // ======================================================================
255
+ // BLOCK END: Event Listeners Setup
256
+ // ======================================================================
257
+
258
+ // ======================================================================
259
+ // BLOCK START: Initial Execution
260
+ // ======================================================================
261
+ loadGuidesData(); // Cargar JSON e iniciar UI
262
+ console.log("[proa.js v6.1] Llamada inicial a loadGuidesData() realizada.");
263
+ // ======================================================================
264
+ // BLOCK END: Initial Execution
265
+ // ======================================================================
266
+
267
+ }); // Fin DOMContentLoaded
268
 
269
+ console.log("[proa.js v6.1] Script completamente definido.");