-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutilities.js
More file actions
462 lines (416 loc) · 12.2 KB
/
Copy pathutilities.js
File metadata and controls
462 lines (416 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// ========== utilities.js ==========
// Funciones reutilizables consolidadas para todo el proyecto
// Consolida seguridad, DOM, modal, y utilidades generales
// ========== SECURITY: XSS Prevention ==========
/**
* Sanitiza HTML para prevenir XSS attacks
* @param {string} str - Texto a sanitizar
* @returns {string} HTML seguro escapado
*/
function sanitizeHTML(str) {
if (!str) return '';
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
/**
* Crea un elemento HTML seguro sin vulnerabilidad de inyección
* @param {string} tag - Etiqueta HTML (div, span, p, etc.)
* @param {string} className - Clases CSS (opcional)
* @param {string} htmlContent - Contenido HTML conocido como seguro (opcional)
* @returns {HTMLElement} Elemento creado
*/
function createSafeElement(tag, className, htmlContent = null) {
const element = document.createElement(tag);
if (className) element.className = className;
if (htmlContent) {
element.innerHTML = htmlContent;
}
return element;
}
/**
* Establece texto de forma segura (no HTML)
* @param {HTMLElement} element - Elemento a modificar
* @param {string} text - Texto a establecer
*/
function setElementText(element, text) {
if (!element) return;
element.textContent = text;
}
/**
* Establece HTML seguro con sanitización
* @param {HTMLElement} element - Elemento a modificar
* @param {string} html - HTML a establecer (será sanitizado si es dinámico)
* @param {boolean} trusted - Si es contenido de confianza (templates internos)
*/
function setElementHTML(element, html, trusted = false) {
if (!element) return;
if (trusted) {
element.innerHTML = html;
} else {
element.textContent = '';
element.appendChild(createSafeElement('div', '', html));
}
}
// ========== DOM UTILITIES ==========
/**
* Muestra un elemento con fade-in opcional
* @param {HTMLElement} element - Elemento a mostrar
* @param {boolean} animate - Aplicar animación de fade-in
*/
function showElement(element, animate = true) {
if (!element) return;
element.classList.remove('hidden');
if (animate) {
element.classList.add('fade-in');
}
}
/**
* Oculta un elemento
* @param {HTMLElement} element - Elemento a ocultar
*/
function hideElement(element) {
if (!element) return;
element.classList.add('hidden');
element.classList.remove('fade-in');
}
/**
* Toggle de visibility con animate opcional
* @param {HTMLElement} element - Elemento a toglear
* @param {boolean} animate - Aplicar animación
* @returns {boolean} Visible ahora?
*/
function toggleElement(element, animate = false) {
if (!element) return false;
const isHidden = element.classList.contains('hidden');
if (isHidden) {
showElement(element, animate);
} else {
hideElement(element);
}
return isHidden; // Devuelve lo que era antes
}
/**
* Limpia el contenido HTML de un elemento
* @param {HTMLElement} element - Elemento a limpiar
*/
function clearElement(element) {
if (!element) return;
element.innerHTML = '';
}
/**
* Agrega múltiples clases a un elemento
* @param {HTMLElement} element - Elemento a modificar
* @param {string|array} classes - Clases a agregar
*/
function addClasses(element, classes) {
if (!element) return;
if (typeof classes === 'string') {
element.classList.add(classes);
} else if (Array.isArray(classes)) {
element.classList.add(...classes);
}
}
/**
* Remueve múltiples clases de un elemento
* @param {HTMLElement} element - Elemento a modificar
* @param {string|array} classes - Clases a remover
*/
function removeClasses(element, classes) {
if (!element) return;
if (typeof classes === 'string') {
element.classList.remove(classes);
} else if (Array.isArray(classes)) {
element.classList.remove(...classes);
}
}
/**
* Verifica si un elemento tiene una clase
* @param {HTMLElement} element - Elemento a verificar
* @param {string} className - Clase a buscar
* @returns {boolean}
*/
function hasClass(element, className) {
if (!element) return false;
return element.classList.contains(className);
}
// ========== MODAL UTILITIES ==========
/**
* Abre un modal con validación
* @param {HTMLElement} modal - Elemento modal
* @param {boolean} animate - Aplicar animación
*/
function openModal(modal, animate = true) {
if (!modal) return;
if (hasClass(modal, 'show')) return; // Ya está abierto
addClasses(modal, 'show');
if (animate) {
addClasses(modal, 'fade-in');
}
}
/**
* Cierra un modal con validación
* @param {HTMLElement} modal - Elemento modal
*/
function closeModal(modal) {
if (!modal) return;
removeClasses(modal, ['show', 'fade-in']);
}
/**
* Toggle de modal (abrir/cerrar)
* @param {HTMLElement} modal - Elemento modal
* @returns {boolean} Abierto ahora?
*/
function toggleModal(modal) {
if (!modal) return false;
if (hasClass(modal, 'show')) {
closeModal(modal);
return false;
} else {
openModal(modal);
return true;
}
}
/**
* Cierra todos los modales excepto uno (opcional)
* @param {HTMLElement} exceptModal - Modal a dejar abierto (opcional)
*/
function closeAllModals(exceptModal = null) {
const modals = document.querySelectorAll('[role="dialog"], .modal');
modals.forEach(modal => {
if (modal !== exceptModal) {
closeModal(modal);
}
});
}
// ========== WAIT FOR DOM ==========
/**
* Espera a que un elemento esté disponible (optimizada)
* @param {string} selector - Selector CSS
* @param {function} callback - Función a ejecutar
* @param {number} maxAttempts - Máximo de intentos
* @param {number} maxTime - Tiempo máximo en ms
*/
function waitForElement(selector, callback, maxAttempts = 60, maxTime = 6000) {
let attempts = 0;
const startTime = Date.now();
const checkElement = () => {
attempts++;
const element = document.querySelector(selector);
if (element) {
console.log(`✅ Elemento encontrado: ${selector}`);
callback(element);
return true;
} else if (attempts < maxAttempts && (Date.now() - startTime) < maxTime) {
requestAnimationFrame(checkElement);
} else {
console.error(`❌ Elemento no encontrado: ${selector}`);
return false;
}
};
// Primera búsqueda inmediata
if (document.querySelector(selector)) {
callback(document.querySelector(selector));
return;
}
checkElement();
}
/**
* Espera múltiples elementos
* @param {object} selectors - {key: 'selector', ...}
* @param {function} callback - Función a ejecutar
* @param {number} maxAttempts - Máximo de intentos
* @param {number} maxTime - Tiempo máximo en ms
*/
function waitForElements(selectors, callback, maxAttempts = 60, maxTime = 6000) {
let attempts = 0;
const startTime = Date.now();
const checkElements = () => {
attempts++;
const elements = {};
let allFound = true;
for (const [key, selector] of Object.entries(selectors)) {
elements[key] = document.querySelector(selector);
if (!elements[key]) {
allFound = false;
}
}
if (allFound) {
console.log("✅ Todos los elementos encontrados");
callback(elements);
return true;
} else if (attempts < maxAttempts && (Date.now() - startTime) < maxTime) {
requestAnimationFrame(checkElements);
} else {
console.error("❌ Elementos no encontrados");
return false;
}
};
checkElements();
}
// ========== EVENT UTILITIES ==========
/**
* Agrega listener con deduplicación automática
* @param {HTMLElement} element - Elemento
* @param {string} event - Nombre del evento
* @param {function} handler - Handler
* @param {boolean} useCapture - Usar capture (opcional)
*/
function safeAddListener(element, event, handler, useCapture = false) {
if (!element) return;
// Remover listener anterior si existe (evita duplicados)
element.removeEventListener(event, handler, useCapture);
element.addEventListener(event, handler, useCapture);
}
/**
* Agrega listeners múltiples a un elemento
* @param {HTMLElement} element - Elemento
* @param {object} listeners - {event: handler, ...}
*/
function addListeners(element, listeners) {
if (!element) return;
for (const [event, handler] of Object.entries(listeners)) {
safeAddListener(element, event, handler);
}
}
// ========== DATA UTILITIES ==========
/**
* Valida estructura de datos JSON
* @param {object} data - Datos a validar
* @param {array} requiredFields - Campos requeridos
* @returns {object} {valid: boolean, errors: []}
*/
function validateDataStructure(data, requiredFields = []) {
const errors = [];
if (!data) {
errors.push('Datos vacíos');
return { valid: false, errors };
}
for (const field of requiredFields) {
if (!(field in data)) {
errors.push(`Campo requerido faltante: ${field}`);
}
}
return {
valid: errors.length === 0,
errors
};
}
/**
* Obtiene valor anidado de objeto con fallback
* @param {object} obj - Objeto
* @param {string} path - Path tipo "a.b.c"
* @param {*} fallback - Valor por defecto
* @returns {*} Valor encontrado o fallback
*/
function getNestedValue(obj, path, fallback = null) {
if (!obj || !path) return fallback;
const keys = path.split('.');
let value = obj;
for (const key of keys) {
if (value && typeof value === 'object' && key in value) {
value = value[key];
} else {
return fallback;
}
}
return value;
}
// ========== TIMING UTILITIES ==========
/**
* Debounce de función (ejecuta después de N ms sin llamadas)
* @param {function} func - Función a debounce
* @param {number} delay - Delay en ms
* @returns {function} Función debounced
*/
function debounce(func, delay = 300) {
let timeoutId = null;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
/**
* Throttle de función (ejecuta máximo cada N ms)
* @param {function} func - Función a throttle
* @param {number} limit - Límite en ms
* @returns {function} Función throttled
*/
function throttle(func, limit = 300) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// ========== FETCH UTILITIES ==========
/**
* Fetch con timeout automático
* @param {string} url - URL a hacer fetch
* @param {number} timeout - Timeout en ms (default 10000)
* @param {object} options - Opciones de fetch
* @returns {Promise} Response
*/
async function fetchWithTimeout(url, timeout = 10000, options = {}) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
...options,
signal: controller.signal
});
clearTimeout(timeoutId);
return response;
} catch (error) {
clearTimeout(timeoutId);
throw error;
}
}
/**
* Carga JSON con validación
* @param {string} url - URL del JSON
* @param {number} timeout - Timeout en ms
* @returns {Promise<object>} JSON parseado
*/
async function loadJSON(url, timeout = 10000) {
try {
const response = await fetchWithTimeout(url, timeout);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error(`Error cargando JSON de ${url}:`, error);
throw error;
}
}
// ========== CONSOLE UTILITIES ==========
/**
* Logger con prefijo y timestamp
* @param {string} type - 'info', 'warn', 'error', 'success'
* @param {string} message - Mensaje
* @param {*} data - Datos opcionales
*/
function log(type = 'info', message, data = null) {
const timestamp = new Date().toLocaleTimeString();
const prefix = {
'info': '📘',
'warn': '⚠️',
'error': '❌',
'success': '✅'
}[type] || '📝';
const style = {
'info': 'color: #0066cc',
'warn': 'color: #ff9900',
'error': 'color: #cc0000',
'success': 'color: #00cc00'
}[type] || 'color: #000';
console.log(`%c${prefix} [${timestamp}] ${message}`, style, data || '');
}
// ========== EXPORT FOR USE ==========
// Si se usa en módulo context, descomentar:
// export { sanitizeHTML, createSafeElement, showElement, hideElement, ... }
console.log('✅ utilities.js cargado');