Skip to content

Commit

Permalink
Merge pull request #12 from NikitaKir98/module11-task1
Browse files Browse the repository at this point in the history
  • Loading branch information
keksobot authored Dec 12, 2024
2 parents 12958b5 + fd8cca6 commit 8d864f7
Show file tree
Hide file tree
Showing 11 changed files with 195 additions and 127 deletions.
47 changes: 24 additions & 23 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -208,34 +208,35 @@ <h2 class="big-picture__title visually-hidden">Просмотр фотогра
</li>
</template>

<!-- Сообщение с ошибкой загрузки изображения -->
<template id="error">
<section class="error">
<div class="error__inner">
<h2 class="error__title">Ошибка загрузки файла</h2>
<button type="button" class="error__button">Попробовать ещё раз</button>
</div>
</section>
</template>
<!-- Сообщение с ошибкой загрузки изображения -->
<template id="error">
<section class="error">
<div class="error__inner">
<h2 class="error__title">Ошибка загрузки файла</h2>
<button type="button" class="error__button">Попробовать ещё раз</button>
</div>
</section>
</template>

<!-- Сообщение об успешной загрузке изображения -->
<template id="success">
<section class="success">
<div class="success__inner">
<h2 class="success__title">Изображение успешно загружено</h2>
<button type="button" class="success__button">Круто!</button>
</div>
</section>
</template>

<!-- Сообщение об успешной загрузке изображения -->
<template id="success">
<section class="success">
<div class="success__inner">
<h2 class="success__title">Изображение успешно загружено</h2>
<button type="button" class="success__button">Круто!</button>
</div>
<!-- Сообщение с ошибкой загрузки изображений от других пользователей -->
<template id="data-error">
<section class="data-error">
<h2 class="data-error__title">Не удалось загрузить данные</h2>
</section>
</template>

<!-- Сообщение с ошибкой загрузки изображений от других пользователей -->
<template id="data-error">
<section class="data-error">
<h2 class="data-error__title">Не удалось загрузить данные</h2>
</section>
</template>
<script src="./js/main.js" type="module"></script>
<script src="./vendor/pristine/pristine.min.js"></script>
<script src="./vendor/nouislider/nouislider.js"></script>
<script src="./js/main.js" type="module"></script>
</body>
</html>
43 changes: 43 additions & 0 deletions js/alert-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { isEscapeKey } from './utils.js';

const alertTemplateError = document.querySelector('#error').content;

const removeAlert = () => {
const currentAlert = document.querySelector('.error');
if (currentAlert) {
document.body.removeChild(currentAlert);
document.removeEventListener('keydown', onDocumentKeydown);
}
};

function onDocumentKeydown (evt) {
if (isEscapeKey(evt)) {
evt.preventDefault();
removeAlert();
}
}

const showAlertError = (message) => {
const alert = alertTemplateError.cloneNode(true);

const alertTitle = alert.querySelector('.error__title');
alertTitle.textContent = message;

const alertButton = alert.querySelector('button');

alertButton.addEventListener('click', (evt) => {
evt.preventDefault();
removeAlert();
});

const alertSection = alert.querySelector('section');

alertSection.addEventListener('click', () => {
removeAlert();
});

document.addEventListener('keydown', onDocumentKeydown);
document.body.append(alert);
};

export {showAlertError};
40 changes: 40 additions & 0 deletions js/alert-success.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { isEscapeKey } from './utils.js';

const alertTemplateSuccess = document.querySelector('#success').content;

const removeAlert = () => {
const currentAlert = document.querySelector('.success');
if (currentAlert) {
document.body.removeChild(currentAlert);
document.removeEventListener('keydown', onDocumentKeydown);
}
};

function onDocumentKeydown (evt) {
if (isEscapeKey(evt)) {
evt.preventDefault();
removeAlert();
}
}

const showAlertSucces = () => {
const alert = alertTemplateSuccess.cloneNode(true);

const alertButton = alert.querySelector('.success__button');

alertButton.addEventListener('click', (evt) => {
evt.preventDefault();
removeAlert();
});

const alertSection = alert.querySelector('.success');

alertSection.addEventListener('click', () => {
removeAlert();
});

document.addEventListener('keydown', onDocumentKeydown);
document.body.append(alert);
};

export { showAlertSucces };
31 changes: 31 additions & 0 deletions js/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const BASE_URL = 'https://31.Javascript.htmlacademy.pro/kekstagram';
const Route = {
GET_DATA: '/data',
SEND_DATA: '/',
};
const Method = {
GET: 'GET',
POST: 'POST',
};
const ErrorText = {
GET_DATA: 'Не удалось загрузить данные. Попробуйте обновить страницу',
SEND_DATA: 'Не удалось отправить форму',
};

const load = (route, errorText, method = Method.GET, body = null) =>
fetch(`${BASE_URL}${route}`, {method, body})
.then((response) => {
if (!response.ok) {
throw new Error();
}
return response.json();
})
.catch(() => {
throw new Error(errorText);
});

const getData = () => load(Route.GET_DATA, ErrorText.GET_DATA);

const sendData = (body) => load(Route.SEND_DATA, ErrorText.SEND_DATA, Method.POST, body);

export {getData, sendData};
67 changes: 0 additions & 67 deletions js/create-pictures-description.js

This file was deleted.

2 changes: 1 addition & 1 deletion js/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ effects.none();
let currentEffect = '';

const onEffectsListClick = (evt) => {
let target = evt.target;
const target = evt.target;

if (target.classList.contains('effects__preview')) {
sliderElement.noUiSlider.set(Slider.MAX);
Expand Down
24 changes: 24 additions & 0 deletions js/form-upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import { validateHashtags, errorHashtags } from './validate-hashtags.js';
import { validateDescription, errorDescription } from './validate-description.js';
import { resetEffect } from './filters.js';
import {resetZoom, changeZoom} from './zoom.js';
import { sendData } from './api.js';
import { showAlertSucces } from './alert-success.js';
import {showAlertError} from './alert-error.js';

const imgUploadForm = document.querySelector('.img-upload__form');
const imgUploadSubmit = imgUploadForm.querySelector('.img-upload__submit');
Expand Down Expand Up @@ -113,3 +116,24 @@ inputHashtags.addEventListener('input', onHashtagsInput);

pristine.addValidator(inputDescription, validateDescription, errorDescription, 2, false);
inputDescription.addEventListener('input', onDescriptionInput);

const onFormImgUploadSubmit = (evt) => {
evt.preventDefault();
imgUploadSubmit.disabled = true;

const formData = new FormData(imgUploadForm);

sendData(formData)
.then(() => {
showAlertSucces();
formImgUploadClose();
})
.catch((err) => {
showAlertError(err.message);
})
.finally(() => {
imgUploadSubmit.disabled = false;
});
};

imgUploadForm.addEventListener('submit', onFormImgUploadSubmit);
19 changes: 12 additions & 7 deletions js/insert-thumbnails.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import {similarDescriptionPhoto} from './create-pictures-description.js';
import {createThumbnail} from './rendering-pictures.js';
import {getData} from './api.js';
import {showPopup} from './popup-error.js';

const pictures = document.querySelector('.pictures');
const picturesContainer = document.querySelector('.pictures');
const fragment = document.createDocumentFragment();

similarDescriptionPhoto.forEach((photo) => {
fragment.append(createThumbnail(photo));
pictures.append(fragment);
});
const insertThumbnails = (pictures) => {
pictures.forEach((photo) => {
fragment.append(createThumbnail(photo));
picturesContainer.append(fragment);
});
};

export {similarDescriptionPhoto};
getData()
.then((pictures)=> insertThumbnails(pictures))
.catch((err) => showPopup(err.message));
4 changes: 1 addition & 3 deletions js/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import {similarDescriptionPhoto} from './insert-thumbnails.js';
import './insert-thumbnails.js';
import './form-upload.js';
import './filters.js';

similarDescriptionPhoto();
18 changes: 18 additions & 0 deletions js/popup-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const popupErroreTemplate = document.querySelector('#data-error').content;

const showPopup = (message) => {
const popupError = popupErroreTemplate.cloneNode(true);

const popupTitle = popupError.querySelector('.data-error__title');
popupTitle.textContent = message;

document.body.append(popupError);

setTimeout(removePopup, 5000);
};

function removePopup(){
document.querySelector('.data-error').remove();
}

export { showPopup };
27 changes: 1 addition & 26 deletions js/utils.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,4 @@
// возвращает рандомное число в диапазоне от a до b
const getRandomInteger = (a, b) => {
const lower = Math.ceil(Math.min(a, b));
const upper = Math.floor(Math.max(a, b));
const result = Math.random() * (upper - lower + 1) + lower;
return Math.floor(result);
};

// возвращает рандомный элемент переданного массива
const getRandomArrayElement = (elements) => elements[getRandomInteger(0, elements.length - 1)];

//возвращает id по порядку с 1
function createIdGenerator () {
let lastGeneratedId = 0;
return function () {
lastGeneratedId += 1;
return lastGeneratedId;
};
}

//Проверка на escape
const isEscapeKey = (evt) => evt.key === 'Escape';

export {
getRandomInteger,
getRandomArrayElement,
createIdGenerator,
isEscapeKey
};
export {isEscapeKey};

0 comments on commit 8d864f7

Please sign in to comment.