Skip to content

Commit e019778

Browse files
committed
implementation of receiving and sending photos to the server
1 parent c213ff6 commit e019778

File tree

8 files changed

+130
-157
lines changed

8 files changed

+130
-157
lines changed

js/api.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const SERVER_URL = 'https://31.javascript.htmlacademy.pro/kekstagram';
2+
3+
const routes = {
4+
GET_DATA: '/data',
5+
SEND_DATA: '/',
6+
};
7+
8+
const methods = {
9+
GET: 'GET',
10+
POST: 'POST',
11+
};
12+
13+
const errorTexts = {
14+
[methods.GET]: 'Не удалось загрузить данные. Попробуйте ещё раз',
15+
[methods.POST]: 'Не удалось отправить данные формы',
16+
};
17+
18+
const load = (route, method = methods.GET, body = null) =>
19+
fetch(`${SERVER_URL}${route}`, { method, body })
20+
.then((response) => {
21+
if (!response.ok) {
22+
throw new Error(errorTexts[method]);
23+
}
24+
return response.json();
25+
});
26+
27+
const getData = () => load(routes.GET_DATA);
28+
const sendData = (body) => load(routes.SEND_DATA, methods.POST, body);
29+
30+
export { getData, sendData };

js/create-photo-descriptions.js

Lines changed: 0 additions & 40 deletions
This file was deleted.

js/data.js

Lines changed: 0 additions & 56 deletions
This file was deleted.

js/functions.js

Lines changed: 0 additions & 22 deletions
This file was deleted.

js/main.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
1-
import { photosData } from './create-photo-descriptions.js';
21
import { renderGallery } from './gallery.js';
32
import { initPhotoUploadForm } from './photo-upload-form.js';
3+
import { getData } from './api.js';
4+
import { showDataError } from './messages.js';
5+
6+
getData()
7+
.then((photos) => {
8+
renderGallery(photos);
9+
})
10+
.catch(() => {
11+
showDataError();
12+
});
413

5-
renderGallery(photosData);
614
initPhotoUploadForm();

js/messages.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
const dataErrorTemplate = document.querySelector('#data-error')?.content;
2+
const successTemplate = document.querySelector('#success')?.content;
3+
const errorTemplate = document.querySelector('#error')?.content;
4+
5+
const DATA_ERROR_TIMEOUT = 5000;
6+
7+
const showDataError = () => {
8+
const dataErrorElement = dataErrorTemplate.cloneNode(true);
9+
document.body.append(dataErrorElement);
10+
11+
const dataErrorBlock = document.body.querySelector('.data-error');
12+
13+
setTimeout(() => {
14+
dataErrorBlock?.remove();
15+
}, DATA_ERROR_TIMEOUT);
16+
};
17+
18+
const showMessage = (template, blockClass, buttonClass) => {
19+
const messageElement = template.cloneNode(true);
20+
const messageBlock = messageElement.querySelector(blockClass);
21+
22+
document.body.append(messageBlock);
23+
24+
const removeMessage = () => {
25+
messageBlock.remove();
26+
document.removeEventListener('keydown', onEscKeydown);
27+
};
28+
29+
function onEscKeydown (evt) {
30+
if (evt.key === 'Escape') {
31+
removeMessage();
32+
}
33+
}
34+
35+
messageBlock.querySelector(buttonClass).addEventListener('click', removeMessage);
36+
messageBlock.addEventListener('click', (evt) => {
37+
if (evt.target === messageBlock) {
38+
removeMessage();
39+
}
40+
});
41+
42+
document.addEventListener('keydown', onEscKeydown);
43+
};
44+
45+
const showSuccess = () => {
46+
showMessage(successTemplate, '.success', '.success__button');
47+
};
48+
49+
const showError = () => {
50+
showMessage(errorTemplate, '.error', '.error__button');
51+
};
52+
53+
export { showDataError, showSuccess, showError };
54+

js/photo-upload-form.js

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@ import { isEscapeKey, showModal } from './util.js';
22
import { isValid, resetValidation } from './validations.js';
33
import { resetScalePhoto } from './photo-scale-editor.js';
44
import { resetEffects } from './photo-effects.js';
5+
import { sendData } from './api.js';
6+
import { showSuccess, showError } from './messages.js';
7+
8+
const SUBMIT_TEXT = 'Опубликовать';
9+
const SENDING_TEXT = 'Отправка...';
510

611
const photoLoadingElement = document.querySelector('.img-upload__input');
712
const photoUploadOverlayElement = document.querySelector('.img-upload__overlay');
@@ -11,6 +16,9 @@ const photoUploadFormElement = document.querySelector('.img-upload__form');
1116
const hashtagsInputElement = photoUploadFormElement.querySelector('.text__hashtags');
1217
const commentInputElement = photoUploadFormElement.querySelector('.text__description');
1318

19+
20+
const submitButton = photoUploadFormElement.querySelector('.img-upload__submit');
21+
1422
const onDocumentKeydown = (evt) => {
1523
if (document.activeElement === hashtagsInputElement || document.activeElement === commentInputElement) {
1624
evt.stopPropagation();
@@ -47,6 +55,32 @@ const initPhotoUploadForm = () => {
4755
hashtagsInputElement.addEventListener('keydown', (evt) => evt.stopPropagation());
4856
commentInputElement.addEventListener('keydown', (evt) => evt.stopPropagation());
4957

50-
photoUploadFormElement.addEventListener('submit', (evt) => !isValid() && evt.preventDefault());
58+
const toggleSubmitButton = (isDisabled) => {
59+
submitButton.disabled = isDisabled;
60+
submitButton.textContent = isDisabled ? SENDING_TEXT : SUBMIT_TEXT;
61+
};
62+
63+
photoUploadFormElement.addEventListener('submit', (evt) => {
64+
evt.preventDefault();
65+
66+
if (!isValid()) {
67+
return;
68+
}
69+
70+
toggleSubmitButton(true);
71+
72+
sendData(new FormData(photoUploadFormElement))
73+
.then(() => {
74+
closePhotoUploadModal();
75+
showSuccess();
76+
})
77+
.catch(() => {
78+
showError();
79+
})
80+
.finally(() => {
81+
toggleSubmitButton(false);
82+
});
83+
});
84+
5185

5286
export { initPhotoUploadForm };

js/util.js

Lines changed: 1 addition & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,5 @@
11
const body = document.body;
22

3-
const getRandomInteger = (min, max) => {
4-
const lower = Math.ceil(Math.min(Math.abs(min), Math.abs(max)));
5-
const upper = Math.floor(Math.max(Math.abs(min), Math.abs(max)));
6-
const result = Math.random() * (upper - lower + 1) + lower;
7-
8-
return Math.floor(result);
9-
};
10-
11-
const createRandomIntegerFromRangeGenerator = (min, max) => {
12-
const previousValues = [];
13-
14-
return function () {
15-
let currentValue = getRandomInteger(min, max);
16-
if (previousValues.length >= (max - min + 1)) {
17-
window.console.log(`Перебраны все числа из диапазона от ${min} до ${max}`);
18-
return null;
19-
}
20-
while (previousValues.includes(currentValue)) {
21-
currentValue = getRandomInteger(min, max);
22-
}
23-
previousValues.push(currentValue);
24-
return currentValue;
25-
};
26-
};
27-
28-
const getRandomArrayElement = (elements) =>
29-
elements.length
30-
? elements[getRandomInteger(0, elements.length - 1)]
31-
: undefined;
32-
33-
const createIdGenerator = () => {
34-
let lastGeneratedId = 0;
35-
return () => ++lastGeneratedId;
36-
};
37-
383
const isEscapeKey = (evt) => evt.key === 'Escape';
394

405
const showModal = (modal, isShown = true) => {
@@ -48,4 +13,4 @@ const showModal = (modal, isShown = true) => {
4813
body.classList.remove('modal-open');
4914
};
5015

51-
export {getRandomInteger, createRandomIntegerFromRangeGenerator, getRandomArrayElement, createIdGenerator, isEscapeKey, showModal};
16+
export { isEscapeKey, showModal};

0 commit comments

Comments
 (0)