-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
889 lines (758 loc) · 35.2 KB
/
index.html
File metadata and controls
889 lines (758 loc) · 35.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WallpaperStore</title>
<link rel="icon" href="Wallpapers/favicon.png" type="image/png">
<link rel="preload" href="Wallpapers/youtube-logo.png" as="image">
<style>
/* Variables de colores y fuentes */
:root {
--bg-color: #202020;
--card-bg-color: #2c2c2c;
--text-color: #e0e0e0;
--accent-color: #0078d4;
--hover-color: #383838;
--border-radius: 8px;
--font-family: 'Segoe UI', Arial, sans-serif;
}
/* Estilos generales */
body {
background-color: var(--bg-color);
color: var(--text-color);
font-family: var(--font-family);
margin: 0;
padding: 0;
display: flex;
min-height: 100vh;
}
/* Contenido principal */
.main-content {
flex-grow: 1;
padding: 20px 40px;
overflow-y: auto;
}
/* Sección de encabezado (buscador, etc) */
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
}
/* Contenedor del buscador */
.search-container {
position: relative;
width: 400px;
display: flex;
align-items: center;
}
.search-bar {
width: 100%;
padding: 10px 15px;
background-color: var(--card-bg-color);
border-radius: var(--border-radius);
border: none;
color: var(--text-color);
outline: none;
padding-right: 40px; /* Espacio para el botón de borrado */
box-sizing: border-box; /* Asegura que el padding no cambie el ancho */
}
.clear-search {
position: absolute;
right: 15px;
top: 50%;
transform: translateY(-55%);
color: #888;
font-size: 20px;
cursor: pointer;
transition: color 0.2s;
display: none;
line-height: 1;
}
.clear-search:hover {
color: var(--text-color);
}
/* Nuevo estilo para el logo de YouTube */
.youtube-logo-link {
display: flex;
align-items: center;
}
.youtube-logo {
width: 40px;
height: 40px;
border-radius: 0;
}
/* Carrusel principal */
.carousel {
height: 350px;
background-color: var(--card-bg-color);
border-radius: var(--border-radius);
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 40px;
overflow: hidden;
position: relative;
}
/* MEJORA: Transición más ligera solo para la opacidad */
.carousel-item {
width: 100%;
height: 100%;
background-size: cover;
background-position: center;
position: absolute;
opacity: 0;
transition: opacity 1s ease-in-out;
top: 0;
left: 0;
/* Agregado para lazy loading: el fondo se establece dinámicamente */
}
.carousel-item.active {
opacity: 1;
z-index: 1;
}
.carousel-item-info {
position: absolute;
bottom: 20px;
left: 20px;
color: white;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
z-index: 2;
}
.carousel-item-info h2 {
margin: 0;
font-size: 2em;
}
.carousel-item-info p {
margin: 5px 0 15px;
}
.download-btn {
background-color: var(--accent-color);
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
text-decoration: none;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s;
}
.download-btn:hover {
background-color: #005a9e;
}
/* Secciones de wallpapers */
.section {
margin-bottom: 40px;
}
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 20px;
width: 100%;
}
.section-header.clickable-title h2 {
cursor: pointer;
transition: color 0.2s;
}
.section-header.clickable-title h2:hover {
color: var(--accent-color);
}
/* Estilos del botón de retroceso */
.back-button {
width: 28px;
height: 28px;
margin-right: 15px;
cursor: pointer;
transition: opacity 0.2s;
}
.back-button:hover {
opacity: 0.7;
}
.wallpaper-grid {
display: grid;
gap: 20px;
width: 100%;
position: relative;
}
.wallpaper-grid.pc {
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
}
.wallpaper-grid.mobile {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}
/* MEJORA: Usar content-visibility: auto para optimizar renderizado */
.wallpaper-card {
background-color: var(--card-bg-color);
border-radius: var(--border-radius);
overflow: hidden;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
position: relative;
cursor: pointer;
content-visibility: auto; /* IMPORTANTE para rendimiento */
}
.wallpaper-card img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease-in-out;
}
.wallpaper-card:hover img {
transform: scale(1.05);
}
.wallpaper-card-info {
padding: 10px;
position: absolute;
bottom: 0;
width: 100%;
background: linear-gradient(to top, rgba(0,0,0,0.8), rgba(0,0,0,0));
box-sizing: border-box;
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
.wallpaper-card:hover .wallpaper-card-info {
opacity: 1;
}
.image-title-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
padding: 10px;
background-color: rgba(0, 0, 0, 0.6);
color: white;
font-weight: bold;
text-align: center;
opacity: 0;
transition: opacity 0.3s ease-in-out;
box-sizing: border-box;
pointer-events: none;
}
.wallpaper-card:hover .image-title-overlay {
opacity: 1;
}
/* Estilos para el modal de imagen en pantalla completa */
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.9);
justify-content: center;
align-items: center;
}
.modal-content {
max-width: 90%;
max-height: 90%;
object-fit: contain;
display: block;
}
.close-button {
position: absolute;
top: 20px;
right: 35px;
color: #fff;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
cursor: pointer;
}
.close-button:hover,
.close-button:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
.download-modal-btn {
background-color: var(--accent-color);
color: white;
padding: 12px 24px;
border: none;
border-radius: 5px;
text-decoration: none;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s;
z-index: 1001;
position: absolute;
bottom: 20px;
right: 20px;
}
.download-modal-btn:hover {
background-color: #005a9e;
}
/* Estilos para el título del modal de pantalla completa */
.modal-image-title {
position: absolute;
top: 5%;
padding: 10px;
background-color: rgba(0, 0, 0, 0.6);
color: white;
font-weight: bold;
text-align: center;
box-sizing: border-box;
z-index: 100;
}
</style>
</head>
<body>
<div class="main-content" id="main-content">
<div class="header">
<div class="search-container">
<input type="text" class="search-bar" placeholder="Buscar wallpapers..." id="search-input">
<span class="clear-search" id="clear-search-button">×</span>
</div>
<a href="https://www.youtube.com/@AngeL06oficial" target="_blank" class="youtube-logo-link">
<img src="Wallpapers/youtube-logo.png" alt="Logo de YouTube" class="youtube-logo">
</a>
</div>
<div id="home-view">
<div class="carousel" id="main-carousel">
</div>
<div class="section">
<div class="section-header clickable-title">
<h2 id="pc-section-title">Wallpapers para PC</h2>
</div>
<div class="wallpaper-grid pc" id="pc-wallpapers-preview">
</div>
</div>
<div class="section">
<div class="section-header clickable-title">
<h2 id="mobile-section-title">Wallpapers para Móvil</h2>
</div>
<div class="wallpaper-grid mobile" id="mobile-wallpapers-preview">
</div>
</div>
</div>
<div id="gallery-view" style="display:none;">
<div class="section">
<div class="section-header">
<h2 id="gallery-title-container">
<img src="Wallpapers/arrow-left.svg" alt="Volver" id="back-button" class="back-button">
<span id="gallery-title"></span>
</h2>
</div>
<div id="pc-gallery-container" class="wallpaper-grid pc" style="display: none;"></div>
<div id="mobile-gallery-container" class="wallpaper-grid mobile" style="display: none;"></div>
</div>
</div>
</div>
<div id="image-modal" class="modal">
<span class="close-button" id="close-modal-button">×</span>
<div class="modal-image-title" id="modal-title"></div>
<img class="modal-content" id="modal-image">
<a class="download-modal-btn" id="download-modal-btn" href="#" download>Descargar</a>
</div>
<script src="wallpapers.js"></script>
<script>
// Formatos principales para las galerías (prioridad)
const FORMATOS_PRIMARIOS = ['.png', '.jpg', '.jpeg', '.webp'];
// Formatos específicos para el carrusel (solo JPG/JPEG en prioridad)
const FORMATOS_CARRUSEL = ['.jpg', '.jpeg'];
// *******************************************************************
// * Lógica de inicialización: Si wallpapersCarrusel no existe, usa wallpapersPC
// *******************************************************************
const listaCarrusel = typeof wallpapersCarrusel !== 'undefined' ? wallpapersCarrusel : wallpapersPC;
// *******************************************************************
// * INTERSECTION OBSERVERS
// *******************************************************************
// 1. Observer para las miniaturas (secciones y galería)
const thumbObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
const baseName = img.dataset.baseName;
const folder = img.dataset.folder;
const attempts = JSON.parse(img.dataset.attempts);
function tryLoadThumb(index) {
if (index >= attempts.length) {
observer.unobserve(img);
return;
}
const currentExt = attempts[index];
const thumbUrl = `${folder}/thumbs/${baseName}${currentExt}`;
const tempImg = new Image();
tempImg.onload = function() {
img.src = thumbUrl;
observer.unobserve(img);
};
tempImg.onerror = function() {
tryLoadThumb(index + 1);
};
tempImg.src = thumbUrl;
}
tryLoadThumb(0);
}
});
}, {
rootMargin: '100px 0px', // Cargar 100px antes de que entren en vista
threshold: 0.01
});
// 2. Observer para los elementos del carrusel (el fondo)
const carouselObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const item = entry.target;
const nombreBase = item.dataset.baseName;
const carruselFolder = item.dataset.folder;
const formatos = JSON.parse(item.dataset.attempts);
// Solo cargar si aún no tiene un background (lazy load)
if (!item.style.backgroundImage) {
function tryLoadCarousel(i) {
if (i >= formatos.length) return;
const url = `${carruselFolder}/${nombreBase}${formatos[i]}`;
const img = new Image();
img.onload = () => {
item.style.backgroundImage = `url('${url}')`;
item.dataset.url = url; // Guarda la URL para la descarga
observer.unobserve(item); // Deja de observar una vez cargado
};
img.onerror = () => {
tryLoadCarousel(i + 1);
};
img.src = url;
}
tryLoadCarousel(0);
} else {
observer.unobserve(item);
}
}
});
}, {
rootMargin: '0px',
threshold: 0.1
});
// Función que genera un nombre legible a partir del nombre del archivo
function getNombreLegible(nombreArchivo) {
const nombreSinExtension = nombreArchivo.includes('.') ? nombreArchivo.split('.')[0] : nombreArchivo;
return nombreSinExtension.replace(/-/g, ' ').replace(/_/g, ' ');
}
// Función para crear un placeholder SVG con las proporciones adecuadas
function getPlaceholder(ancho, alto) {
const colorGris = '#2c2c2c';
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${ancho} ${alto}" width="${ancho}" height="${alto}" style="background-color: ${colorGris};"></svg>`;
return `data:image/svg+xml;base64,${btoa(svg)}`;
}
// *******************************************************************
// * CARRUSEL (Lazy Loading)
// *******************************************************************
function inicializarCarrusel() {
const wallpapersAleatorios = [...listaCarrusel].sort(() => 0.5 - Math.random());
const seleccionados = wallpapersAleatorios.slice(0, 5);
const contenedorCarrusel = document.getElementById('main-carousel');
const carruselFolder = 'Wallpapers/Carrusel';
seleccionados.forEach((nombreBase, index) => {
const nombre = getNombreLegible(nombreBase);
const itemCarrusel = document.createElement('div');
itemCarrusel.className = 'carousel-item';
// Setear dataset para el Observer
itemCarrusel.dataset.baseName = nombreBase;
itemCarrusel.dataset.folder = carruselFolder;
itemCarrusel.dataset.attempts = JSON.stringify(FORMATOS_CARRUSEL);
if (index === 0) itemCarrusel.classList.add('active'); // Mostrar el primero
const infoCarrusel = document.createElement('div');
infoCarrusel.className = 'carousel-item-info';
infoCarrusel.innerHTML = `
<h2>${nombre}</h2>
<p>Wallpaper aleatorio destacado.</p>
`;
const botonDescarga = document.createElement('a');
botonDescarga.className = 'download-btn';
botonDescarga.textContent = 'Descargar';
// La URL real se establecerá cuando el observer cargue la imagen
botonDescarga.href = '#';
botonDescarga.download = nombreBase;
// Listener para actualizar el enlace de descarga en el momento del click
botonDescarga.addEventListener('click', (e) => {
const url = itemCarrusel.dataset.url;
if (!url || url === '#') {
e.preventDefault();
console.warn("Imagen de carrusel no cargada aún. Intente de nuevo.");
return;
}
// Establecer el enlace final y el nombre de archivo con extensión
const finalExt = url.substring(url.lastIndexOf('.'));
botonDescarga.href = url;
botonDescarga.download = nombreBase + finalExt;
});
infoCarrusel.appendChild(botonDescarga);
itemCarrusel.appendChild(infoCarrusel);
contenedorCarrusel.appendChild(itemCarrusel);
// Observar para el lazy loading
carouselObserver.observe(itemCarrusel);
});
}
// ... (resto de funciones inalteradas) ...
// Funcionalidad del modal
const modal = document.getElementById('image-modal');
const modalImagen = document.getElementById('modal-image');
const modalTitulo = document.getElementById('modal-title');
const botonCerrarModal = document.getElementById('close-modal-button');
const botonDescargarModal = document.getElementById('download-modal-btn');
// Ahora recibe solo el nombre base y la carpeta
function abrirModal(nombreBase, folderName) {
modal.style.display = 'flex';
let formatosATrabar = FORMATOS_PRIMARIOS; // La galería sigue usando todos los formatos
let intentos = 0;
function tryLoadImage(url) {
// Función para actualizar el modal si la imagen se carga con éxito
const handleLoadSuccess = function() {
modalImagen.onload = null;
modalImagen.onerror = null;
const nombreArchivoConExt = url.substring(url.lastIndexOf('/') + 1);
const nombreLegible = getNombreLegible(nombreArchivoConExt);
const imagenAncho = modalImagen.clientWidth;
modalTitulo.style.width = `${imagenAncho}px`;
modalTitulo.style.left = `calc(50% - ${imagenAncho / 2}px)`;
modalTitulo.textContent = nombreLegible;
botonDescargarModal.href = url;
botonDescargarModal.download = nombreArchivoConExt;
botonDescargarModal.style.display = 'inline-block';
};
// Función para manejar el error de carga y probar el siguiente formato
const handleError = function() {
intentos++;
if (intentos < formatosATrabar.length) {
const nextExt = formatosATrabar[intentos];
// Intentar cargar la imagen grande
const nextUrl = `${folderName}/${nombreBase}${nextExt}`;
tryLoadImage(nextUrl);
} else {
// Fallo total
modalImagen.onload = null;
modalImagen.onerror = null;
console.error('No se pudo cargar la imagen en ningún formato alternativo:', nombreBase);
modalTitulo.textContent = 'Error: Imagen no encontrada.';
modalTitulo.style.width = '300px';
modalTitulo.style.left = 'calc(50% - 150px)';
botonDescargarModal.style.display = 'none';
}
};
// Asignar los handlers y cargar la imagen
modalImagen.onload = handleLoadSuccess;
modalImagen.onerror = handleError;
modalImagen.src = url;
}
// 4. Comenzar la carga con el primer formato de la lista
const initialUrl = `${folderName}/${nombreBase}${formatosATrabar[0]}`;
tryLoadImage(initialUrl);
}
function cerrarModal() {
modal.style.display = 'none';
modalImagen.src = "";
modalTitulo.textContent = "";
}
botonCerrarModal.addEventListener('click', cerrarModal);
window.addEventListener('click', (event) => {
if (event.target === modal) {
cerrarModal();
}
});
// Carrusel
let indiceCarruselActual = 0;
function mostrarSiguienteItemCarrusel() {
const itemsCarrusel = document.querySelectorAll('.carousel-item');
if (itemsCarrusel.length < 2) return;
itemsCarrusel[indiceCarruselActual].classList.remove('active');
indiceCarruselActual = (indiceCarruselActual + 1) % itemsCarrusel.length;
itemsCarrusel[indiceCarruselActual].classList.add('active');
}
setInterval(mostrarSiguienteItemCarrusel, 5000);
// Funcionalidad de navegación y virtualización
const vistaPrincipal = document.getElementById('home-view');
const vistaGaleria = document.getElementById('gallery-view');
const tituloGaleria = document.getElementById('gallery-title');
const galeriaPC = document.getElementById('pc-gallery-container');
const galeriaMovil = document.getElementById('mobile-gallery-container');
const tituloSeccionPC = document.getElementById('pc-section-title');
const tituloSeccionMovil = document.getElementById('mobile-section-title');
const botonVolver = document.getElementById('back-button');
const carruselPrincipal = document.getElementById('main-carousel');
let pcGalleryRendered = false;
let mobileGalleryRendered = false;
let categoriaActual = '';
// Renderiza las tarjetas de forma eficiente usando el Observer de miniaturas
function renderizarWallpapers(listaNombresBase, contenedorElemento, categoria, isPreview = false) {
// Solo limpia si es una preview o una búsqueda, NO si es la renderización inicial de galería
if (isPreview || contenedorElemento.id === 'pc-wallpapers-preview' || contenedorElemento.id === 'mobile-wallpapers-preview') {
contenedorElemento.innerHTML = '';
} else if (contenedorElemento.childElementCount > 0 && !isPreview) {
// Si la galería ya está renderizada (preRenderizarGalerias), no hacemos nada
return;
}
const folderName = categoria === 'pc' ? 'Wallpapers/PC' : 'Wallpapers/Móvil';
const thumbFormats = ['.jpg', '.png', '.jpeg', '.webp'];
listaNombresBase.forEach(nombreBase => {
const nombre = getNombreLegible(nombreBase);
const tarjeta = document.createElement('div');
tarjeta.className = 'wallpaper-card';
const imagen = document.createElement('img');
// Se asignan los datos para el observer
imagen.dataset.baseName = nombreBase;
imagen.dataset.folder = folderName;
imagen.dataset.attempts = JSON.stringify(thumbFormats);
// Usar placeholder SVG como src inicial
if (categoria === 'pc') {
imagen.src = getPlaceholder(16, 9);
imagen.naturalWidth = 16;
imagen.naturalHeight = 9;
} else {
imagen.src = getPlaceholder(9, 16);
imagen.naturalWidth = 9;
imagen.naturalHeight = 16;
}
imagen.alt = nombre;
tarjeta.onclick = () => {
abrirModal(nombreBase, folderName);
};
const superposicionNombre = document.createElement('div');
superposicionNombre.className = 'image-title-overlay';
superposicionNombre.textContent = nombre;
const infoTarjeta = document.createElement('div');
infoTarjeta.className = 'wallpaper-card-info';
const botonDescarga = document.createElement('a');
botonDescarga.className = 'download-btn';
botonDescarga.textContent = 'Descargar';
botonDescarga.href = `${folderName}/${nombreBase}${FORMATOS_PRIMARIOS[0]}`;
botonDescarga.download = nombreBase;
botonDescarga.addEventListener('click', (event) => {
event.stopPropagation();
});
infoTarjeta.appendChild(botonDescarga);
tarjeta.appendChild(imagen);
tarjeta.appendChild(superposicionNombre);
tarjeta.appendChild(infoTarjeta);
contenedorElemento.appendChild(tarjeta);
// Observar la imagen para su carga diferida
thumbObserver.observe(imagen);
});
}
// MEJORA: Pre-renderiza la galería completa una sola vez al inicio
function preRenderizarGalerias() {
if (!pcGalleryRendered) {
renderizarWallpapers(wallpapersPC, galeriaPC, 'pc');
pcGalleryRendered = true;
}
if (!mobileGalleryRendered) {
renderizarWallpapers(wallpapersMovil, galeriaMovil, 'movil');
mobileGalleryRendered = true;
}
}
// MEJORA: Solo cambia la visibilidad, sin re-renderizar
function mostrarGaleria(categoria) {
vistaPrincipal.style.display = 'none';
vistaGaleria.style.display = 'block';
galeriaPC.style.display = 'none';
galeriaMovil.style.display = 'none';
if (categoria === 'pc') {
tituloGaleria.textContent = 'Wallpapers para PC';
galeriaPC.style.display = 'grid';
categoriaActual = 'pc';
} else if (categoria === 'movil') {
tituloGaleria.textContent = 'Wallpapers para Móvil';
galeriaMovil.style.display = 'grid';
categoriaActual = 'movil';
}
if (searchInput.value) {
// Re-filtrar si hay búsqueda activa
manejarBusqueda(true);
} else {
// Asegurar que todas se muestren si no hay búsqueda
(categoriaActual === 'pc' ? galeriaPC : galeriaMovil).querySelectorAll('.wallpaper-card').forEach(t => t.style.display = 'block');
}
}
function volver() {
vistaGaleria.style.display = 'none';
vistaPrincipal.style.display = 'block';
if (searchInput.value === '') {
carruselPrincipal.style.display = 'flex';
document.querySelectorAll('.section-header.clickable-title').forEach(h => h.style.display = 'flex');
} else {
// Si hay búsqueda, mostrar los resultados de la preview
manejarBusqueda();
}
}
tituloSeccionPC.addEventListener('click', () => mostrarGaleria('pc'));
tituloSeccionMovil.addEventListener('click', () => mostrarGaleria('movil'));
botonVolver.addEventListener('click', volver);
// Funcionalidad de búsqueda
const searchInput = document.getElementById('search-input');
const clearSearchButton = document.getElementById('clear-search-button');
// MEJORA: Debounce para evitar ejecuciones excesivas de búsqueda
const debounce = (func, delay) => {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
};
// El parámetro forceGalleryFilter obliga a filtrar la galería si estamos en ella.
function manejarBusqueda(forceGalleryFilter = false) {
const query = searchInput.value.toLowerCase();
if (query.length > 0) {
clearSearchButton.style.display = 'block';
} else {
clearSearchButton.style.display = 'none';
}
const esVistaPrincipal = vistaPrincipal.style.display !== 'none';
const esVistaGaleria = vistaGaleria.style.display !== 'none';
const seccionesHeader = document.querySelectorAll('.section-header.clickable-title');
if (esVistaPrincipal) {
carruselPrincipal.style.display = query.length > 0 ? 'none' : 'flex';
seccionesHeader.forEach(h => h.style.display = query.length > 0 ? 'none' : 'flex');
if (query === '') {
// Carga normal de previews
renderizarWallpapers(wallpapersPC.slice(0, 4), document.getElementById('pc-wallpapers-preview'), 'pc', true);
renderizarWallpapers(wallpapersMovil.slice(0, 4), document.getElementById('mobile-wallpapers-preview'), 'movil', true);
} else {
// Filtrar y renderizar previews de búsqueda
const resultadosPC = wallpapersPC.filter(nombreBase => getNombreLegible(nombreBase).toLowerCase().includes(query)).slice(0, 4);
const resultadosMovil = wallpapersMovil.filter(nombreBase => getNombreLegible(nombreBase).toLowerCase().includes(query)).slice(0, 4);
renderizarWallpapers(resultadosPC, document.getElementById('pc-wallpapers-preview'), 'pc', true);
renderizarWallpapers(resultadosMovil, document.getElementById('mobile-wallpapers-preview'), 'movil', true);
}
}
// FILTRO DE GALERÍA (aplica en vista galería O si se le fuerza el filtro al cambiar a ella)
if (esVistaGaleria || forceGalleryFilter) {
const contenedor = categoriaActual === 'pc' ? galeriaPC : galeriaMovil;
const todasLasTarjetas = contenedor.querySelectorAll('.wallpaper-card');
todasLasTarjetas.forEach(tarjeta => {
// Aquí usamos el overlay que tiene el nombre legible completo, incluso si está oculto
const nombre = tarjeta.querySelector('.image-title-overlay').textContent.toLowerCase();
if (query === '' || nombre.includes(query)) {
tarjeta.style.display = 'block';
} else {
tarjeta.style.display = 'none';
}
});
}
}
const manejarBusquedaDebounced = debounce(manejarBusqueda, 300);
searchInput.addEventListener('input', manejarBusquedaDebounced);
// Funcionalidad para borrar el campo de búsqueda
clearSearchButton.addEventListener('click', () => {
searchInput.value = '';
manejarBusqueda();
searchInput.focus();
});
// *******************************************************************
// * INICIALIZACIÓN FINAL
// *******************************************************************
document.addEventListener('DOMContentLoaded', () => {
// 1. Inicializa el carrusel (solo estructura, el observer cargará las imágenes)
inicializarCarrusel();
// 2. Renderiza las Previews del Home (muestra las primeras 4 de cada una)
renderizarWallpapers(wallpapersPC.slice(0, 4), document.getElementById('pc-wallpapers-preview'), 'pc', true);
renderizarWallpapers(wallpapersMovil.slice(0, 4), document.getElementById('mobile-wallpapers-preview'), 'movil', true);
// 3. MEJORA: Pre-renderiza la galería COMPLETA (oculta, para evitar lag al cambiar de vista)
preRenderizarGalerias();
});
</script>
</body>
</html>