Skip to content

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

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

Merged
merged 4 commits into from
May 30, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 1 addition & 6 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,7 @@
<!-- Фильтрация изображений от других пользователей -->
<section class="img-filters img-filters--inactive container">
<h2 class="img-filters__title visually-hidden">Фильтр фотографий</h2>
<form
class="img-filters__form"
action="index.html"
method="get"
autocomplete="off"
>
<form class="img-filters__form" autocomplete="off">
<button
type="button"
class="img-filters__button img-filters__button--active"
Expand Down
25 changes: 25 additions & 0 deletions js/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const BASE_URL = 'https://31.javascript.htmlacademy.pro/kekstagram';

const getUrl = (endpoint) =>
`${BASE_URL}/${endpoint[0] === '/' ? endpoint.slice(1) : endpoint}`;

const dataHandler = async (response) => {
if (response.status < 400) {
Copy link
Collaborator

@Spearance Spearance May 29, 2025

Choose a reason for hiding this comment

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

400 — магическое и должен быть 200

return response.json();
} else {
const text = await response.text();
throw new Error(text);
}
};

const api = {
get: (endpoint, config) => fetch(getUrl(endpoint), config).then(dataHandler),
post: (endpoint, body, config) =>
fetch(getUrl(endpoint), {
method: 'POST',
body,
...config,
}).then(dataHandler),
};

export { api };
32 changes: 26 additions & 6 deletions js/form.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Modal } from './modal.js';
import * as imageProcessing from './image-proccessing.js';
import { api } from './api.js';
import { notification } from './notification.js';

const uploadInputEl = document.querySelector('input.img-upload__input');
const uploadOverlayEl = document.querySelector('.img-upload__overlay');
Expand Down Expand Up @@ -28,19 +30,32 @@ const addValidator = (inputEl, callback, message) => {
);
};

submitEl.addEventListener('click', (evt) => {
if (!pristine.validate()) {
evt.preventDefault();
}
});

const modal = new Modal(uploadOverlayEl, uploadCancelEl, {
onClose: () => {
uploadInputEl.value = '';
imageProcessing.reset();
formEl.reset();
resetErrors();
},
});

submitEl.addEventListener('click', (evt) => {
evt.preventDefault();
if (!pristine.validate()) {
return;
}
const body = new FormData(formEl);
api
.post('/', body)
.then(() => {
notification.success();
modal.close();
})
.catch(() => {
notification.error();
});
});

const initializeForm = () => {
uploadInputEl.addEventListener('change', () => {
modal.open();
Expand Down Expand Up @@ -110,4 +125,9 @@ addValidator(
''
);

function resetErrors() {
descriptionError.style.display = 'none';
hashtagError.style.display = 'none';
}

export { initializeForm };
95 changes: 6 additions & 89 deletions js/get-posts.js
Original file line number Diff line number Diff line change
@@ -1,92 +1,9 @@
import { getRandomArrayElement, getRandomInteger } from './util.js';
import { api } from './api.js';
import { notification } from './notification.js';

const DESCRIPTION = [
'5 минут, полет нормальный',
'Терпение и труд-инфаркт и инсульт',
'Никогда такого не было и вот опять',
'Утро началось с третьей попытки',
'В 20:31 прибыл Годжо Сатору',
'Сидим с бобром за столом',
];
const AVATAR = [1, 2, 3, 4, 5, 6];
const MESSAGE = [
'Всё отлично!',
'В целом всё неплохо. Но не всё.',
'Когда вы делаете фотографию, хорошо бы убирать палец из кадра. В конце концов это просто непрофессионально.',
'Моя бабушка случайно чихнула с фотоаппаратом в руках и у неё получилась фотография лучше.',
'Я поскользнулся на банановой кожуре и уронил фотоаппарат на кота и у меня получилась фотография лучше.',
'Лица у людей на фотке перекошены, как будто их избивают.',
'Как можно было поймать такой неудачный момент?!',
];
const NAME = [
'Александр',
'Егор',
'Леонид',
'Иван',
'Максим',
'Владислав',
'Фёдор',
'Алексей',
'Матвей',
'Никита',
'Илья',
'Евгений',
'Михаил',
'Даниил',
'Кирилл',
'Ксения',
'Матвей',
'Юлия',
'Татьяна',
'Дарья',
'Галима',
'Маргарита',
'Алиса',
'Виктория',
'Мила',
'Елизавета',
'Ольга',
'Кира',
'Нина',
'Злата',
];

const LIKES = [];
for (let i = 15; i <= 200; ++i) {
LIKES.push(i);
}

const NUMBER_COMMENTS_MIN = 0;
const NUMBER_COMMENTS_MAX = 30;

const ID = [
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,
];

let lastCommentId = 1;

const createComment = () => ({
id: ++lastCommentId, // 1
avatar: `img/avatar-${getRandomArrayElement(AVATAR)}.svg`,
message: getRandomArrayElement(MESSAGE),
name: getRandomArrayElement(NAME),
});

const getRandomSimilarComments = () =>
Array.from(
{ length: getRandomInteger(NUMBER_COMMENTS_MIN, NUMBER_COMMENTS_MAX) },
createComment
);

const createPost = () => ({
id: getRandomArrayElement(ID),
url: `photos/${getRandomArrayElement(ID)}.jpg`,
description: getRandomArrayElement(DESCRIPTION),
likes: getRandomArrayElement(LIKES),
comments: getRandomSimilarComments(),
});

const getPosts = (length = 25) => Array.from({ length }, createPost);
const getPosts = () =>
api.get('data').catch(() => {
notification.dataError();
});

export { getPosts };
8 changes: 5 additions & 3 deletions js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { drawMiniatures } from './draw-miniatures.js';
import { initializeForm } from './form.js';
import { getPosts } from './get-posts.js';

const posts = getPosts();

drawMiniatures(posts);
getPosts()
.then((posts) => {
drawMiniatures(posts);
})
.catch(() => {});
Copy link
Collaborator

Choose a reason for hiding this comment

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

добавить ошибку


initializeForm();
39 changes: 39 additions & 0 deletions js/notification.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const dataErrorTemplate = document.getElementById('data-error').content;
const errorTemplate = document.getElementById('error').content;
const successTemplate = document.getElementById('success').content;

const showMessage = (template, config = {}) => {
const timeout = (config.timeout ?? 5) * 1000;
Copy link
Collaborator

Choose a reason for hiding this comment

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

магические значения

const message = template.cloneNode(true).children[0];
document.body.appendChild(message);
setTimeout(() => {
message?.remove();
}, timeout);
return message;
};

const notification = {
dataError: (config = {}) => {
showMessage(dataErrorTemplate, config);
},
error: (config = {}) => {
const message = showMessage(errorTemplate, config);
const button = message.querySelector('button.error__button');
button.onclick = (evt) => {
if (!config.onRetry?.(evt)) {
message.remove();
}
};
},
success: (config = {}) => {
const message = showMessage(successTemplate, config);
const button = message.querySelector('button.success__button');
button.onclick = (evt) => {
if (!config.onClose?.(evt)) {
message.remove();
}
};
},
};

export { notification };