forked from woprzech/warsawjs-workshop-26-my-photos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
58 lines (45 loc) · 1.6 KB
/
index.js
File metadata and controls
58 lines (45 loc) · 1.6 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
import {Image} from './image';
console.log('warsawJS workshop');
let currentImages;
let fileInput = document.getElementById('file-input');
fileInput.onchange = () => {
if (fileInput.files && fileInput.files[0]) {
const reader = new FileReader();
reader.onload = async (e) => {
const fileName = e.target.result;
await fetch(`http://localhost:3000/photos`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({url: fileName, isFavourite: false})
});
render();
};
reader.readAsDataURL(fileInput.files[0]);
}
};
document.getElementById('show-favourites').addEventListener('click', async () => {
const allImages = await getAllImages();
currentImages = allImages.filter(image => image.isFavourite());
renderGallery();
});
document.getElementById('sort-images').addEventListener('click', () => {
currentImages.sort((i1, i2) => i1.isFavourite() && i2.isFavourite() ? 0 : i1.isFavourite() ? -1 : 1);
renderGallery();
});
function renderGallery() {
document.getElementById('images').innerHTML = '';
currentImages
.forEach((image) => image.show());
}
async function getAllImages() {
const response = await fetch('http://localhost:3000/photos');
const imagesData = await response.json();
return imagesData.map(image => new Image(image.id, image.url, image.isFavourite));
};
async function render() {
currentImages = await getAllImages();
renderGallery();
}
render();