Skip to content
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 @@ -121,7 +121,7 @@ <h2 class="img-upload__title visually-hidden">Загрузка фотограф
<input class="text__hashtags" name="hashtags" placeholder="#ХэшТег">
</div>
<div class="img-upload__field-wrapper">
<textarea class="text__description" name="description" placeholder="Ваш комментарий..." maxlength="140"></textarea>
<textarea class="text__description" name="description" placeholder="Ваш комментарий..."></textarea>
</div>
</fieldset>

Expand Down
43 changes: 43 additions & 0 deletions js/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const BASE_URL = 'https://31.javascript.htmlacademy.pro/kekstagram';

const Route = {
GET_DATA: '/data',
SEND_DATA: '/',
};

const Method = {
GET: 'GET',
POST: 'POST',
};

const ErrorText = {
[Method.GET]: 'Не удалось загрузить данные. Попробуйте обновить страницу',
[Method.POST]: 'Не удалось отправить форму. Попробуйте ещё раз',
};

const load = async (route, method = Method.GET, body = null) => {
try {
const response = await fetch(`${BASE_URL}${route}`, {
method,
body,
headers: {
Accept: 'application/json',
},
});

if (!response.ok) {
throw new Error();
}

return method === Method.GET ? response.json() : response;

} catch {
throw new Error(ErrorText[method]);
}
};

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

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

export { getData, sendData };
20 changes: 16 additions & 4 deletions js/main.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { getPictures } from './mock/pictures.js';
import { getData } from './api.js';
import { renderGallery } from './ui/gallery.js';
import { initBigPicture } from './ui/big-picture/meta.js';
import { initCommentsLoader } from './ui/big-picture/comments.js';
import { initForm } from './ui/form/index.js';
import { showAlert } from './ui/messages.js';

const container = document.querySelector('.pictures');
const template = document.querySelector('#picture')?.content?.querySelector('.picture');
Expand All @@ -11,6 +12,17 @@ initBigPicture();
initCommentsLoader();
initForm();

if (container && template) {
renderGallery(getPictures(), container, template);
}
const initGallery = async () => {
if (!container || !template) {
return;
}

try {
const pictures = await getData();
renderGallery(pictures, container, template);
} catch (err) {
showAlert(err.message);
}
};

initGallery();
19 changes: 15 additions & 4 deletions js/ui/form/index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
import { initModal } from './modal.js';
import { initModal, hideModal } from './modal.js';
import { initValidation, resetValidation } from './validation.js';
import { initSubmit } from './submit.js';
import { initScale } from './scale.js';
import { initEffects } from './effect.js';
import { showSuccessMessage, showErrorMessage } from '../messages.js';

const initForm = () => {
initValidation();
initSubmit();
initScale();
initEffects();

initModal(() => {
resetValidation();
});


initScale();
initEffects();
initSubmit({
success: () => {
hideModal();
showSuccessMessage();
},
error: () => {
showErrorMessage();
},
});
};

export { initForm };
8 changes: 7 additions & 1 deletion js/ui/form/modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const body = document.body;
const form = document.querySelector('.img-upload__form');
const overlay = form.querySelector('.img-upload__overlay');
const cancelButton = form.querySelector('.img-upload__cancel');
const hashtagField = form.querySelector('.text__hashtags');
const commentField = form.querySelector('.text__description');
const fileField = form.querySelector('.img-upload__input');

let onCloseCallback = null;
Expand Down Expand Up @@ -38,8 +40,12 @@ const initModal = (cb) => {
cancelButton.addEventListener('click', hideModal);
};

const isTextFieldFocused = () =>
document.activeElement === hashtagField ||
document.activeElement === commentField;

function onDocumentKeydown(evt) {
if (isEscapeKey(evt)) {
if (isEscapeKey(evt) && !isTextFieldFocused()) {
evt.preventDefault();
hideModal();
}
Expand Down
50 changes: 43 additions & 7 deletions js/ui/form/submit.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,51 @@
import { isValid } from './validation.js';
import { sendData } from '../../api.js';

const SubmitButtonText = {
IDLE: 'Опубликовать',
SENDING: 'Публикую...',
};

const form = document.querySelector('.img-upload__form');
const submitButton = form.querySelector('.img-upload__submit');

let onSuccess = null;
let onError = null;

const blockSubmitButton = () => {
submitButton.disabled = true;
submitButton.textContent = SubmitButtonText.SENDING;
};

const unblockSubmitButton = () => {
submitButton.disabled = false;
submitButton.textContent = SubmitButtonText.IDLE;
};

const onFormSubmit = async (evt) => {
evt.preventDefault();

if (!isValid()) {
return;
}

blockSubmitButton();

try {
await sendData(new FormData(evt.target));
onSuccess?.();
} catch {
onError?.();
} finally {
unblockSubmitButton();
}
};

const initSubmit = () => {
form.addEventListener('submit', (evt) => {
const valid = isValid();
const initSubmit = ({ success, error }) => {
onSuccess = success;
onError = error;

if (!valid) {
evt.preventDefault();
}
});
form.addEventListener('submit', onFormSubmit);
};

export { initSubmit };
73 changes: 73 additions & 0 deletions js/ui/messages.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { isEscapeKey } from '../utils/common.js';

const ALERT_SHOW_TIME = 5000;

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

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

const dataErrorTemplate = document
.querySelector('#data-error')
.content.querySelector('.data-error');

const showAlert = (message) => {
const alertElement = dataErrorTemplate.cloneNode(true);

if (message) {
alertElement.querySelector('.data-error__title').textContent = message;
}

document.body.append(alertElement);

setTimeout(() => {
alertElement.remove();
}, ALERT_SHOW_TIME);
};

const showMessage = (template, buttonSelector) => {
const messageElement = template.cloneNode(true);
document.body.append(messageElement);

const closeButton = messageElement.querySelector(buttonSelector);

const removeMessage = () => {
messageElement.remove();
document.removeEventListener('keydown', onKeydown);
document.removeEventListener('click', onOutsideClick);
};

function onKeydown(evt) {
if (isEscapeKey(evt)) {
evt.preventDefault();
removeMessage();
}
}

function onOutsideClick(evt) {
const inner = messageElement.querySelector(
'.success__inner, .error__inner'
);

if (!inner.contains(evt.target)) {
removeMessage();
}
}

closeButton.addEventListener('click', removeMessage);
document.addEventListener('keydown', onKeydown);
document.addEventListener('click', onOutsideClick);
};

const showSuccessMessage = () => {
showMessage(successTemplate, '.success__button');
};

const showErrorMessage = () => {
showMessage(errorTemplate, '.error__button');
};

export { showAlert, showSuccessMessage, showErrorMessage };
Loading