Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Надо подкачаться #14

Merged
merged 6 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="vendor/nouislider/nouislider.css">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<title>Кекстаграм</title>
</head>
Expand Down Expand Up @@ -234,6 +235,5 @@ <h2 class="data-error__title">Не удалось загрузить данны
</section>
</template>
<script src="js/main.js" type="module"></script>
<script src="js/functions.js"></script>
</body>
</html>
19 changes: 19 additions & 0 deletions js/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const BASE_URL = 'https://31.javascript.htmlacademy.pro/kekstagram';
const Route = {
GET_DATA: '/data',
SEND_DATA: '/',
};
const Method = {
GET: 'GET',
POST: 'POST',
};

const load = (route, method = Method.GET, body = null) =>
fetch(`${BASE_URL}${route}`, {method, body})
.then((response) => response.json());

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

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

export { getData, sendData };
118 changes: 0 additions & 118 deletions js/data.js

This file was deleted.

51 changes: 42 additions & 9 deletions js/form.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import { isEscapeKey } from './util.js';
import { isEscapeKey, showSendErrorAlert, showSendSuccessAlert } from './util.js';
import { runValidator, stopValidator } from './validator.js';
import { runImageEditor } from './image-editor.js';
import { sendData } from './api.js';

const imgUploadElement = document.querySelector('.img-upload__input');
const imgEditElement = document.querySelector('.img-upload__overlay');
const imgEditCloseButtonElement = document.querySelector('.img-upload__cancel');
const bodyContainerElement = document.body;
const newCommentElement = document.querySelector('.text__description');
const newHashTagsElement = document.querySelector('.text__hashtags');
const formElement = document.querySelector('.img-upload__form');
const submitButtonElement = formElement.querySelector('.img-upload__submit');
const imgUploadElement = formElement.querySelector('.img-upload__input');
const imgEditElement = formElement.querySelector('.img-upload__overlay');
const imgEditCloseButtonElement = formElement.querySelector('.img-upload__cancel');
const newCommentElement = formElement.querySelector('.text__description');
const newHashTagsElement = formElement.querySelector('.text__hashtags');

const setupFormEventListeners = () => {
imgUploadElement.addEventListener('change', () => {
runValidator();
runImageEditor();
imgEditElement.classList.remove('hidden');
bodyContainerElement.classList.add('modal-open');
document.body.classList.add('modal-open');
formElement.addEventListener('submit', setUserFormSubmit);
imgEditCloseButtonElement.addEventListener('click', onClickCloseButton);
imgEditElement.addEventListener('click', onOverlayClick);
document.addEventListener('keydown', onKeydownDocument);
Expand Down Expand Up @@ -44,9 +47,39 @@ function onKeydownDocument(evt) {
// Закрытие редактирования изображения
function closeImgEdit() {
imgEditElement.classList.add('hidden');
bodyContainerElement.classList.remove('modal-open');
document.body.classList.remove('modal-open');
imgUploadElement.value = '';
stopValidator();
resetSettings();
}

function resetSettings() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У формы должно быть собственное api для сброса параметров
Скорее всего вот это https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset, я точно не помню

imgUploadElement.value = '';
newCommentElement.value = '';
newHashTagsElement.value = '';
}

// Обработчик событий на кнопку отправить
function setUserFormSubmit(evt) {
evt.preventDefault();
submitButtonElement.setAttribute('disabled', '');
sendData(new FormData(evt.target))
.then(() => {
closeImgEdit();
resetSettings();
showSendSuccessAlert();
}
)
.catch(
() => {
showSendErrorAlert();
}
)
.finally(
() => {
submitButtonElement.removeAttribute('disabled');
});
}


export { setupFormEventListeners };
13 changes: 6 additions & 7 deletions js/image-editor.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import '../vendor/nouislider/nouislider.js';
import '../vendor/nouislider/nouislider.css';

const buttonDecrementElement = document.querySelector('.scale__control--smaller');
const buttonIncrementElement = document.querySelector('.scale__control--bigger');
Expand All @@ -8,7 +7,7 @@ const scaleValueElement = document.querySelector('.scale__control--value');
const sliderContainerElement = document.querySelector('.img-upload__effect-level');
const sliderElement = sliderContainerElement.querySelector('.effect-level__slider');
const effectLevelElement = sliderContainerElement.querySelector('.effect-level__value');
const ImageElement = document.querySelector('.img-upload__preview');
const imageElement = document.querySelector('.img-upload__preview');
const effectListElement = document.querySelector('.effects__list');
const originalElement = effectListElement.querySelector('#effect-none');

Expand Down Expand Up @@ -70,7 +69,7 @@ const formatScale = (value) => `${value * 100}%`;

const changeScale = (value) => {
scaleValue = value;
ImageElement.style.transform = `scale(${scaleValue})`;
imageElement.style.setProperty('transform', `scale(${scaleValue})`);
scaleValueElement.value = formatScale(scaleValue);
};

Expand Down Expand Up @@ -102,7 +101,7 @@ const createSlider = ({ MIN, MAX, START, STEP, STYLE, UNIT }) => {
sliderElement.noUiSlider.on('update', () => {
const value = sliderElement.noUiSlider.get();
effectLevelElement.value = value;
ImageElement.style.filter = `${STYLE}(${value}${UNIT})`;
imageElement.style.setProperty('filter', `${STYLE}(${value}${UNIT})`);
});
};

Expand All @@ -111,7 +110,7 @@ const addEffect = () => {
sliderElement.noUiSlider.destroy();
}
if (originalElement.checked) {
ImageElement.style.filter = 'none';
imageElement.style.setProperty('filter', 'none');
sliderContainerElement.classList.add('hidden');
return;
}
Expand All @@ -122,11 +121,11 @@ const addEffect = () => {
};

const runImageEditor = () => {
ImageElement.style.filter = 'none';
imageElement.style.setProperty('filter', 'none');
sliderContainerElement.classList.add('hidden');
effectListElement.addEventListener('change', addEffect);
scaleValue = SCALE.DEFAULT;
ImageElement.style.transform = `scale(${SCALE.DEFAULT})`;
imageElement.style.setProperty('transform', `scale(${SCALE.DEFAULT})`);
scaleValueElement.value = formatScale(scaleValue);
buttonDecrementElement.addEventListener('click', decrementScale);
buttonIncrementElement.addEventListener('click', incrementScale);
Expand Down
20 changes: 14 additions & 6 deletions js/main.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import { generateArrObj } from './data.js';
import { renderGallery } from './thumbnails.js';
import { getData } from './api.js';
import { renderGallery, setupFilterListeners } from './thumbnails.js';
import { setupPictureEventListeners } from './photo-modal.js';
import { setupFormEventListeners } from './form.js';
import { showGetErrorAlert } from './util.js';

const photoCollection = generateArrObj();
renderGallery(photoCollection);
setupPictureEventListeners(photoCollection);
setupFormEventListeners();
getData()
.then((photoCollection) => {
renderGallery(photoCollection);
setupPictureEventListeners(photoCollection);
setupFilterListeners(photoCollection);
})
.then(() => document.querySelector('.img-filters').classList.remove('img-filters--inactive'))
.catch(() => {
showGetErrorAlert();
});

setupFormEventListeners();
13 changes: 3 additions & 10 deletions js/photo-modal.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { isEscapeKey } from './util.js';
import { initComments } from './comments-loader.js';

// Общий контейнер
const body = document.body;

// Контейнер с картинками
const picturesContainerElement = document.querySelector('.pictures');

Expand All @@ -26,7 +23,7 @@ const renderBigPicture = ({ url, likes, comments, description }) => {
document.addEventListener('keydown', onKeydownDocument);
initComments(comments); // Инициализируем комментарии
containerElement.classList.remove('hidden'); // включаем видимость контейнера большой картинки
body.classList.add('modal-open'); // блокируем прокрутку body
document.body.classList.add('modal-open'); // блокируем прокрутку body
};

// Вызов закрытия картинки нажатием на закрывающий элемент
Expand Down Expand Up @@ -54,17 +51,13 @@ function closeBigPicture () {
containerElement.removeEventListener('click', onOverlayClick);
document.removeEventListener('keydown', onKeydownDocument);
containerElement.classList.add('hidden');
body.classList.remove('modal-open');
document.body.classList.remove('modal-open');
}

// Функция добавления обработчика событий на контейнер с картинками и вычисление ID картинки, по которой был клик
const setupPictureEventListeners = (photoCollection) => {
picturesContainerElement.addEventListener('click', (evt) => {
const target = evt.target.closest('.picture');
if (!target) {
return;
}
const id = target.dataset.pictureId; // поиск по установленному атрибуту data-set-id
const id = evt.target.closest('.picture').dataset.pictureId; // поиск по установленному атрибуту data-set-id
if (id) {
const foundedPhoto = photoCollection.find((picture) => picture.id === Number(id));
renderBigPicture(foundedPhoto);
Expand Down
Loading
Loading