@@ -7,15 +7,15 @@ class Photo {
7
7
constructor ( json ) {
8
8
Object . assign ( this , json ) ;
9
9
}
10
- showModal ( ) {
10
+ /* showModal(){
11
11
Swal.fire({
12
12
width: '50rem',
13
13
imageUrl: this.src.original,
14
14
imageWidth: '60%',
15
15
showConfirmButton: false,
16
16
imageAlt: this.alt
17
17
});
18
- }
18
+ } */
19
19
}
20
20
21
21
// La API key que pedí a la API de Pexels.
@@ -45,112 +45,114 @@ const removeAllChild = (parent) => {
45
45
}
46
46
}
47
47
48
- // Creamos una función que nos permita crear nuevos elementos (fotos) para la galería.
49
- const createNewGalleryItem = ( photoObject ) => {
50
- // Creamos un nuevo objeto 'Photo' a partir del objeto que nos dá el 'json'.
51
- const photo = new Photo ( photoObject ) ;
52
- // Creamos un nuevo elemento article.
53
- let newGalleryItem = document . createElement ( 'article' ) ;
54
- // Le asignamos la clase que define los estilos que poseerán las fotos.
55
- newGalleryItem . classList . add ( 'gallery__item' ) ;
56
- // Y le ponemos una etiqueta img con los datos del objeto para que se muestren.
57
- newGalleryItem . innerHTML = `<img src="${ photo . src . large } " alt="${ photo . alt } "></img>` ;
58
- // Y por último le agregamos ese nuevo elemento a la galería. Utilicé el 'prepend' ya que quiero que se agregue al principio, para respetar el orden que simulo en el array.
59
- galleryContainer . prepend ( newGalleryItem ) ;
60
- // Retornamos el objeto 'Photo' para poder utilizarlo posteriormente.
61
- return photo ;
48
+ let pageIndex = 1 ;
49
+ let searchValue ;
50
+
51
+ const fetchPhotos = async ( baseURL ) => {
52
+ const res = await fetch ( baseURL , HEADERS ) ;
53
+ const data = await res . json ( ) ;
54
+ return data ;
62
55
}
63
56
64
- /* const getNextPage = (next_page) => {
65
- if (next_page){
66
- loadMoreBtn.addEventListener('click', async () => {
67
- const data = await fetchPhotos(next_page);
68
- data.photos.map((photoObject) => {
69
- let photo = createNewGalleryItem(photoObject);
70
- let galleryItem = document.querySelector('article');
71
- galleryItem.addEventListener('click', () => photo.showModal());
72
- });
73
- });
57
+ const validateSearchValue = ( searchValue ) => {
58
+ if ( searchValue . length < 3 ) {
59
+ // Avisamos el error.
60
+ errorAlert . innerText = 'Debe introducir una palabra mayor a 3 letras.' ;
61
+ // Creamos un timer que limpie el 'errorAlert' despues de 1.5 segundos.
62
+ setTimeout ( ( ) => {
63
+ errorAlert . innerText = '' ;
64
+ } , 1500 ) ;
74
65
} else {
75
- loadMoreBtn.style.display = 'none' ;
66
+ return true ;
76
67
}
77
- } */
68
+ }
69
+
70
+ const generateHTML = ( data , photoType ) => {
71
+ data . photos . forEach ( ( photoObject ) => {
72
+ const photo = new Photo ( photoObject ) ;
73
+ // Creamos un nuevo elemento article.
74
+ let newGalleryItem = document . createElement ( 'article' ) ;
75
+ // Le asignamos la clase que define los estilos que poseerán las fotos.
76
+ newGalleryItem . classList . add ( 'gallery__item' ) ;
77
+ newGalleryItem . setAttribute ( 'data-photo' , photoType ) ;
78
+ // Y le ponemos una etiqueta img con los datos del objeto para que se muestren.
79
+ newGalleryItem . innerHTML = `<img src="${ photo . src . large } " alt="${ photo . alt } "></img>` ;
80
+ // Y por último le agregamos ese nuevo elemento a la galería.
81
+ galleryContainer . append ( newGalleryItem ) ;
82
+ } ) ;
83
+ }
78
84
79
85
// Creamos una función que nos devuelva las fotos a partir de lo ingresado por el usuario en la barra de búsqueda.
80
- const getSearchedPhotos = ( searchValue ) => {
81
- fetch ( `https://api.pexels.com/v1/search?query=${ searchValue } &per_page=16` , HEADERS )
82
- . then ( ( res ) => res . json ( ) )
83
- . then ( ( data ) => {
84
- removeAllChild ( galleryContainer ) ;
85
- data . photos . map ( ( photoObject ) => {
86
- let photo = createNewGalleryItem ( photoObject ) ;
87
- let galleryItem = document . querySelector ( 'article' ) ;
88
- galleryItem . addEventListener ( 'click' , ( ) => photo . showModal ( ) ) ;
89
- } ) ;
90
- } ) ;
91
- /* getNextPage(data.next_page); */
86
+ const getSearchedPhotos = async ( e ) => {
87
+ e . preventDefault ( ) ;
88
+ searchValue = e . target . querySelector ( 'input' ) . value ;
89
+ if ( validateSearchValue ( searchValue ) === true ) {
90
+ const data = await fetchPhotos ( `https://api.pexels.com/v1/search?query=${ searchValue } &per_page=16` ) ;
91
+ if ( ! data . next_page ) {
92
+ loadMoreBtn . style . display = 'none'
93
+ }
94
+ removeAllChild ( galleryContainer ) ;
95
+ generateHTML ( data , 'search' ) ;
96
+ }
97
+ }
98
+
99
+ const getMoreSearchedPhotos = async ( index ) => {
100
+ const data = await fetchPhotos ( `https://api.pexels.com/v1/search?query=${ searchValue } &per_page=16&page=${ index } ` ) ;
101
+ if ( ! data . next_page ) {
102
+ loadMoreBtn . style . display = 'none'
103
+ }
104
+ generateHTML ( data , 'search' ) ;
92
105
}
93
106
94
107
// Creamos una función que nos devuelva fotos aleatorias.
95
- const getInitialRandomPhotos = ( ) => {
96
- fetch ( `https://api.pexels.com/v1/curated?page=1&per_page=16` , HEADERS )
97
- . then ( ( res ) => res . json ( ) )
98
- . then ( ( data ) => {
99
- console . log ( data )
100
- data . photos . map ( ( photoObject ) => {
101
- let photo = createNewGalleryItem ( photoObject ) ;
102
- let galleryItem = document . querySelector ( 'article' ) ;
103
- galleryItem . addEventListener ( 'click' , ( ) => photo . showModal ( ) ) ;
104
- } ) ;
105
- } ) ;
106
- /* getNextPage(data.next_page); */
108
+ const getInitialRandomPhotos = async ( index ) => {
109
+ const data = await fetchPhotos ( `https://api.pexels.com/v1/curated?per_page=16&page=${ index } ` ) ;
110
+ if ( ! data . next_page ) {
111
+ loadMoreBtn . style . display = 'none'
112
+ }
113
+ generateHTML ( data , 'curated' ) ;
107
114
}
108
115
109
- // Creamos una función que nos permita tomar lo que el usuario ingresa en la barra de búsqueda y fijarnos si matchea con alguna de las fotos que tenemos guardadas en el array (simulador de base de datos).
110
- const getSearcheInputValue = ( e ) => {
111
- // Evitamos el funcionamiento por defualt del evento submit.
112
- e . preventDefault ( ) ;
113
- // Tomamos al input del form y lo almacenamos.
114
- let inputSearch = e . target . querySelector ( 'input' ) ;
115
- // Y también guardamos el value en otra.
116
- const userSearch = inputSearch . value ;
117
- // Validamos el value del input.
118
- if ( userSearch . length > 3 ) {
119
- // Llamamos a la función que filtra.
120
- getSearchedPhotos ( userSearch ) ;
121
- errorAlert . innerText = '' ;
122
- } else {
123
- // Sino, avisamos el error.
124
- errorAlert . innerText = 'Debe introducir una palabra mayor a 3 letras.' ;
125
- // Creamos un timer que limpie el 'errorAlert' despues de 1.5 segundos.
126
- setTimeout ( ( ) => {
127
- errorAlert . innerText = '' ;
128
- } , 1500 ) ;
116
+ const loadMorePhotos = ( ) => {
117
+ let index = ++ pageIndex ;
118
+ let galleryItem = document . querySelector ( 'article' ) ;
119
+ let dataPhoto = galleryItem . getAttribute ( 'data-photo' )
120
+ if ( dataPhoto == 'curated' ) {
121
+ getInitialRandomPhotos ( index ) ;
122
+ } else {
123
+ getMoreSearchedPhotos ( index ) ;
129
124
}
130
125
}
131
126
132
- // Evento submit del form, donde se llama a una función que trae las fotos a partir de la búsqueda.
133
- searchForm . addEventListener ( 'submit' , ( e ) => getSearcheInputValue ( e ) ) ;
134
127
128
+ /**** EVENTOS ****/
129
+
130
+ // Evento submit del form, donde se llama a una función que trae las fotos a partir de la búsqueda.
131
+ searchForm . addEventListener ( 'submit' , ( e ) => getSearchedPhotos ( e ) ) ;
132
+ loadMoreBtn . addEventListener ( 'click' , ( ) => loadMorePhotos ( ) ) ;
135
133
// Cuando se carge la ventana, llamamos a la función que nos carga 8 fotos simulando que son fotos aleatorias.
136
- document . addEventListener ( 'DOMContentLoaded' , getInitialRandomPhotos ( ) ) ;
134
+ document . addEventListener ( 'DOMContentLoaded' , getInitialRandomPhotos ( pageIndex ) ) ;
137
135
138
136
// Botón para limpiar el input del form.
139
137
clearInputButton . addEventListener ( 'click' , ( ) => {
138
+ let pageIndex = 1 ;
140
139
// Limpiamos el input.
141
140
document . getElementById ( 'searchInput' ) . value = '' ;
142
141
// Cuando la galería tiene 3 hijos es porque no se tuvo que crear el h2 para error. Sino, si se tuvo que crear el h2 por lo que tiene más hijos.
143
- if ( gallery . childNodes . length == 3 ) {
142
+ /* if (gallery.childNodes.length == 3){
144
143
// Borra los hijos del contenedor de la galería.
145
144
removeAllChild(galleryContainer);
146
145
// Carga las fotos aleatorias del principio.
147
- getInitialRandomPhotos ( ) ;
146
+ getInitialRandomPhotos(pageIndex );
148
147
}else{
149
148
// Borra el h2 con el error.
150
149
gallery.childNodes[1].remove();
151
150
// Carga las fotos aleatorias del principio.
152
- getInitialRandomPhotos ( ) ;
153
- }
151
+ getInitialRandomPhotos(pageIndex);
152
+ } */
153
+ removeAllChild ( galleryContainer ) ;
154
+ getInitialRandomPhotos ( pageIndex ) ;
155
+ loadMoreBtn . style . display = 'flex' ;
154
156
} ) ;
155
157
156
158
0 commit comments