-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
185 lines (161 loc) · 5.06 KB
/
app.js
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
import { TheCatAPI } from "@thatapicompany/thecatapi";
import { Fancybox } from "@fancyapps/ui";
import Swal from 'sweetalert2'
import "@fancyapps/ui/dist/fancybox/fancybox.css";
import Tabby from 'tabbyjs';
const tabs = new Tabby('[data-tabs]');
const theCatAPI = new TheCatAPI("live_s7PPBUb1ZMsADaBG8Wb4awOjPMMfbmKyLaocqJo4wIJx8Nd3wiAThaCg6zm5ewyL");
let imageId = null;
let sub_id = localStorage.getItem('sub_id') || Math.random().toString(36).substr(2, 9);
localStorage.setItem('sub_id', sub_id);
async function fetchData() {
try {
const response = await fetch('https://api.thecatapi.com/v1/images/search');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const x = data[0];
showImage(x);
} catch (error) {
console.error('Error fetching data:', error);
}
}
function showImage(data) {
const container = document.getElementById('container');
container.innerHTML = '';
const img = document.createElement('img');
img.classList.add('pure-img-responsive');
img.src = data.url;
img.dataset.id = data.id;
img.width = 400;
img.height = 400;
container.appendChild(img);
imageId = data.id;
}
function showFavourites(imagesData) {
const grid = document.getElementById('grid');
grid.innerHTML = ''; // Clear existing favorites
imagesData.forEach(function(imageData) {
const a = document.createElement('a');
a.href = imageData.image.url;
a.dataset.fancybox = 'gallery';
const img = document.createElement('img');
img.src = imageData.image.url;
img.classList.add("pure-img-responsive");
const gridCell = document.createElement('div');
gridCell.className = 'col col-lg';
a.appendChild(img);
gridCell.appendChild(a);
grid.appendChild(gridCell);
});
}
async function getUserFavourites(sub_id) {
const favourites = await theCatAPI.favourites.getFavourites(sub_id);
document.getElementById('grid').innerHTML = '';
showFavourites(favourites);
}
async function favouriteImage() {
fetchData();
if (!imageId) {
console.error('No se ha seleccionado ninguna imagen para guardar en favoritos.');
return;
}
try {
const favourite = await theCatAPI.favourites.addFavourite(imageId, sub_id);
console.log('Imagen guardada en favoritos:', favourite);
await getUserFavourites(sub_id); // Actualiza la lista de favoritos
alertSaveFavs()
} catch (error) {
console.error('Error al guardar en favoritos:', error);
}
}
async function deleteFavourites() {
try {
const favourites = await theCatAPI.favourites.getFavourites(sub_id);
for (const favourite of favourites) {
await theCatAPI.favourites.deleteFavourite(favourite.id);
}
// Limpiar la lista de favoritos en la UI
document.getElementById('grid').innerHTML = '';
} catch (error) {
console.error('Error al eliminar favoritos:', error);
Swal.fire({
position: "top-end",
icon: "error",
title: "Ocurrió un error al eliminar los favoritos.",
showConfirmButton: false,
timer: 1500
});
}
}
function deleteConfirm() {
const swalWithBootstrapButtons = Swal.mixin({
customClass: {
confirmButton: "btn btn-success",
cancelButton: "btn btn-danger"
},
buttonsStyling: false
});
swalWithBootstrapButtons.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: true
}).then((result) => {
if (result.isConfirmed) {
deleteFavourites(); // Aquí se llama a la función para eliminar los favoritos
swalWithBootstrapButtons.fire({
title: "Deleted!",
text: "Your file has been deleted.",
icon: "success"
});
} else if (
result.dismiss === Swal.DismissReason.cancel
) {
swalWithBootstrapButtons.fire({
title: "Cancelled",
text: "Your imaginary file is safe :)",
icon: "error"
});
}
});
}
function alertSaveFavs() {
Swal.fire({
position: "top-end",
icon: "success",
title: "Se ha añadido correctamente a favoritos",
showConfirmButton: false,
timer: 1500
});
}
function aboutTheApp() {
Swal.fire({
title: "Gracias por usar mi app!",
width: 600,
padding: "3em",
color: "#716add",
background: "#fff url(images/nyan-cat-nyan.gif)",
backdrop: `
rgba(0,0,123,0.4)
url("images/nyan-cat-nyan.gif")
left top
no-repeat
`
});
}
fetchData()
getUserFavourites(sub_id);
document.getElementById('deleteBtn').addEventListener('click', deleteConfirm);
document.getElementById('nextBtn').addEventListener('click', fetchData);
document.getElementById('aboutBtn').addEventListener('click', aboutTheApp);
document.getElementById('saveBtn').addEventListener('click', (event) => {
favouriteImage();
});
Fancybox.bind("[data-fancybox]", {
// Your custom options
});