aarnal80 commited on
Commit
48c63b1
·
verified ·
1 Parent(s): 3cc36f4

Update js/proa.js

Browse files
Files changed (1) hide show
  1. js/proa.js +79 -135
js/proa.js CHANGED
@@ -1,28 +1,27 @@
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');
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'; // 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
  // ======================================================================
@@ -32,7 +31,7 @@ window.addEventListener('DOMContentLoaded', () => {
32
  // ======================================================================
33
  let allGuides = [];
34
  let currentGuideFile = null;
35
- let categories = [];
36
  // ======================================================================
37
  // BLOCK END: State Variables
38
  // ======================================================================
@@ -41,50 +40,43 @@ window.addEventListener('DOMContentLoaded', () => {
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>';
49
  allGuides = [];
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,87 +87,48 @@ window.addEventListener('DOMContentLoaded', () => {
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
  // ======================================================================
@@ -183,16 +136,14 @@ window.addEventListener('DOMContentLoaded', () => {
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;
@@ -203,25 +154,24 @@ window.addEventListener('DOMContentLoaded', () => {
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
  }
@@ -233,24 +183,19 @@ window.addEventListener('DOMContentLoaded', () => {
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
  // ======================================================================
@@ -258,12 +203,11 @@ window.addEventListener('DOMContentLoaded', () => {
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.");
 
1
+ // js/proa.js - Lógica para el visor de Guías PROA (v10 - Un Solo Desplegable)
2
 
3
  // ======================================================================
4
  // BLOCK START: DOM Elements Selection & Initial Setup
5
  // ======================================================================
6
+ console.log("[proa.js v10] Script cargado. Esperando DOMContentLoaded...");
7
 
8
  window.addEventListener('DOMContentLoaded', () => {
9
+ console.log("[proa.js v10] DOMContentLoaded detectado. Iniciando setup...");
10
 
11
+ // Selector ÚNICO de Guías
 
12
  const guideSelector = document.getElementById('guideSelector');
 
13
  const guideContentDisplay = document.getElementById('guide-content-display');
14
  const togglePediatricCheckbox = document.getElementById('togglePediatric');
15
 
16
  const guidesDataUrl = 'guides_data.json'; // Asume que está en proa/
17
 
18
+ // Verificar elementos críticos
19
+ if (!guideSelector || !guideContentDisplay || !togglePediatricCheckbox) {
20
+ console.error("[proa.js v10] Error Crítico: No se encontraron elementos DOM esenciales (selector, display o checkbox).");
21
  guideContentDisplay.innerHTML = '<p class="text-red-500 font-semibold text-center py-10">Error: Interfaz no inicializada.</p>';
22
  return;
23
  }
24
+ console.log("[proa.js v10] Elementos DOM encontrados.");
25
  // ======================================================================
26
  // BLOCK END: DOM Elements Selection & Initial Setup
27
  // ======================================================================
 
31
  // ======================================================================
32
  let allGuides = [];
33
  let currentGuideFile = null;
34
+ // Ya no necesitamos la variable 'categories' para la UI
35
  // ======================================================================
36
  // BLOCK END: State Variables
37
  // ======================================================================
 
40
  // BLOCK START: Function to Fetch Guides Data (from JSON)
41
  // ======================================================================
42
  async function loadGuidesData() {
43
+ console.log(`[proa.js v10] Iniciando loadGuidesData desde: ${guidesDataUrl}`);
44
+ guideSelector.innerHTML = '<option value="">Cargando...</option>';
45
+ guideSelector.disabled = true; // Deshabilitar mientras carga
46
+ guideContentDisplay.innerHTML = '<div class="text-center py-16 text-gray-400"><i class="fas fa-spinner fa-spin text-3xl"></i><p class="mt-2">Cargando datos...</p></div>';
 
47
  allGuides = [];
 
48
 
49
  try {
50
+ console.log("[proa.js v10] Realizando fetch...");
51
  const response = await fetch(guidesDataUrl);
52
+ console.log(`[proa.js v10] Fetch completado. Status: ${response.status}`);
53
+ if (!response.ok) throw new Error(`Error HTTP ${response.status} al cargar ${guidesDataUrl}.`);
 
 
54
 
55
+ console.log("[proa.js v10] Parseando JSON...");
56
  allGuides = await response.json();
57
+ console.log("[proa.js v10] JSON parseado.");
58
 
59
+ if (!Array.isArray(allGuides)) throw new Error("JSON no es un array válido.");
 
 
 
60
 
 
61
  allGuides = allGuides.filter(g => g.id && g.title && g.category && g.file);
62
+ console.log(`[proa.js v10] Guías válidas filtradas: ${allGuides.length}`);
63
+
64
+ if (allGuides.length === 0) throw new Error("No hay guías válidas en los datos.");
65
 
66
+ // Ordenar guías (opcional, pero útil para el desplegable)
67
+ allGuides.sort((a, b) => a.title.localeCompare(b.title));
 
 
68
 
69
+ console.log("[proa.js v10] Llamando a populateGuideSelector para mostrar Adultos por defecto...");
70
+ populateGuideSelector(); // Poblar el desplegable (mostrará Adultos por defecto)
71
+ resetContentArea(); // Mostrar mensaje inicial en área de contenido
72
+ guideSelector.disabled = false; // Habilitar selector
73
+ console.log("[proa.js v10] Carga inicial completada.");
74
 
75
  } catch (error) {
76
+ console.error("[proa.js v10] Error durante loadGuidesData:", error);
77
+ guideSelector.innerHTML = '<option value="">Error carga</option>';
78
+ guideSelector.disabled = true;
79
+ guideContentDisplay.innerHTML = `<p class="text-red-600 font-semibold text-center py-10">Error al cargar datos: ${error.message}. Revisa la consola y el archivo JSON.</p>`;
80
  }
81
  }
82
  // ======================================================================
 
87
  // BLOCK START: UI Update Functions
88
  // ======================================================================
89
 
90
+ function resetContentArea() {
91
+ 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 guía del desplegable.</p></div>';
92
+ currentGuideFile = null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  }
94
 
95
+ // Llena el selector ÚNICO de guías aplicando el filtro
96
  function populateGuideSelector() {
 
97
  const showOnlyPediatric = togglePediatricCheckbox.checked;
98
+ console.log(`[proa.js v10] Poblando selector de guías. Mostrar solo Pediátricas: ${showOnlyPediatric}`);
99
 
100
+ // Limpiar selector ANTES del try-catch
101
+ guideSelector.innerHTML = `<option value="">-- Seleccione Guía (${showOnlyPediatric ? 'Pediátricas' : 'Adultos'}) --</option>`;
102
+ currentGuideFile = null; // Deseleccionar guía al repoblar
 
 
 
 
 
 
 
103
 
104
+ try {
105
+ // Filtrar por Adulto o Pediátrico ESTRICTAMENTE
106
+ const filteredGuides = allGuides.filter(guide => guide.isPediatric === showOnlyPediatric);
107
+
108
+ // Ordenar alfabéticamente las guías filtradas
109
+ filteredGuides.sort((a, b) => a.title.localeCompare(b.title));
110
+
111
+ if (filteredGuides.length > 0) {
112
+ const fragment = document.createDocumentFragment();
113
+ filteredGuides.forEach(guide => {
114
  const option = document.createElement('option');
115
+ option.value = guide.file; // El valor es el nombre del archivo
116
+ option.textContent = guide.title; // El texto es el título
117
+ // Añadir "(PED)" al texto si es pediátrica para mayor claridad en el desplegable
118
+ if (guide.isPediatric) {
119
+ option.textContent += " (PED)";
120
+ }
121
+ fragment.appendChild(option);
122
  });
123
+ guideSelector.appendChild(fragment); // Añadir opciones
124
+ console.log(`[proa.js v10] Selector poblado con ${filteredGuides.length} guías.`);
 
 
 
 
125
  } else {
126
+ guideSelector.innerHTML = `<option value="">-- No hay guías ${showOnlyPediatric ? 'Pediátricas' : 'Adultos'} --</option>`;
127
+ console.log(`[proa.js v10] No se encontraron guías para el filtro actual.`);
 
 
128
  }
129
  } catch (e) {
130
+ console.error("[proa.js v10] Error en populateGuideSelector:", e);
131
  guideSelector.innerHTML = '<option value="">Error</option>';
 
132
  }
133
  }
134
  // ======================================================================
 
136
  // ======================================================================
137
 
138
  // ======================================================================
139
+ // BLOCK START: Function to Load External Guide Content (Sin cambios v6.2->v10)
140
  // ======================================================================
141
  async function loadGuideContent(guideFileName) {
142
  if (!guideFileName) {
143
+ resetContentArea();
 
 
144
  return;
145
  }
146
+ console.log(`[proa.js v10] Solicitando contenido de: ${guideFileName}`);
147
  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>';
148
  const guideUrl = guideFileName;
149
  currentGuideFile = guideFileName;
 
154
  const htmlText = await response.text();
155
  const parser = new DOMParser();
156
  const doc = parser.parseFromString(htmlText, 'text/html');
 
157
  const contentNode = doc.querySelector('.max-w-4xl.mx-auto.px-4.py-8') || doc.body;
158
 
159
  if (contentNode) {
160
  const clonedContent = contentNode.cloneNode(true);
161
  const scripts = clonedContent.querySelectorAll('script');
162
  scripts.forEach(script => script.remove());
163
+ if (scripts.length > 0) console.log(`[proa.js v10] Eliminados ${scripts.length} script(s) de ${guideFileName}.`);
164
 
165
  guideContentDisplay.innerHTML = '';
166
  guideContentDisplay.appendChild(clonedContent);
167
+ console.log(`[proa.js v10] Contenido de ${guideFileName} mostrado.`);
168
  guideContentDisplay.scrollTop = 0;
169
 
170
  } else {
171
  throw new Error(`No se encontró nodo de contenido en '${guideFileName}'.`);
172
  }
173
  } catch (error) {
174
+ console.error(`[proa.js v10] Error al cargar/mostrar ${guideFileName}:`, error);
175
  guideContentDisplay.innerHTML = `<div class="text-center py-20 text-red-600">Error: ${error.message}</div>`;
176
  currentGuideFile = null;
177
  }
 
183
  // ======================================================================
184
  // BLOCK START: Event Listeners Setup
185
  // ======================================================================
186
+ // Cuando cambia la guía específica seleccionada
 
 
 
 
 
187
  guideSelector.addEventListener('change', (event) => {
188
+ console.log("[proa.js v10] Cambió la guía seleccionada.");
189
+ loadGuideContent(event.target.value); // Cargar el contenido del archivo seleccionado
190
  });
191
 
192
+ // Cuando cambia el filtro pediátrico
193
  togglePediatricCheckbox.addEventListener('change', () => {
194
+ console.log('[proa.js v10] Cambiado filtro pediátrico.');
195
+ resetContentArea(); // Limpiar área de contenido
196
+ populateGuideSelector(); // Repoblar el ÚNICO desplegable con las guías filtradas
 
197
  });
198
+ console.log("[proa.js v10] Listeners añadidos.");
199
  // ======================================================================
200
  // BLOCK END: Event Listeners Setup
201
  // ======================================================================
 
203
  // ======================================================================
204
  // BLOCK START: Initial Execution
205
  // ======================================================================
206
+ loadGuidesData(); // Cargar JSON, poblar desplegable (adultos por defecto) e iniciar UI
 
207
  // ======================================================================
208
  // BLOCK END: Initial Execution
209
  // ======================================================================
210
 
211
  }); // Fin DOMContentLoaded
212
 
213
+ console.log("[proa.js v10] Script completamente definido.");