From 3eadb197a8c574dbd0393623591d371e64cc22e3 Mon Sep 17 00:00:00 2001 From: Armine Ercheva Date: Thu, 19 Dec 2024 14:39:40 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A0=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=20=D1=81?= =?UTF-8?q?=20=D1=81=D0=B5=D1=80=D0=B2=D0=B5=D1=80=D0=BE=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- js/api.js | 14 ++++++++++ js/constans.js | 10 +++++++ js/data.js | 75 -------------------------------------------------- js/form.js | 33 +++++++++++++++++++--- js/function.js | 68 --------------------------------------------- js/main.js | 16 +++++++++-- js/popup.js | 20 ++++++++++++++ js/util.js | 24 +++++++++++----- 8 files changed, 103 insertions(+), 157 deletions(-) create mode 100644 js/api.js delete mode 100644 js/data.js delete mode 100644 js/function.js create mode 100644 js/popup.js diff --git a/js/api.js b/js/api.js new file mode 100644 index 0000000..54b56cd --- /dev/null +++ b/js/api.js @@ -0,0 +1,14 @@ +export const getData = () => + fetch('https://31.javascript.htmlacademy.pro/kekstagram/data') + .then((response) => { + if(!response.ok){ + throw new Error() + } +return response.json() +}); + +export const sendData = (body) => +fetch('https://31.javascript.htmlacademy.pro/kekstagram/', { + body, + method: 'POST' +}) diff --git a/js/constans.js b/js/constans.js index 8c8df6d..9c07b6c 100644 --- a/js/constans.js +++ b/js/constans.js @@ -66,3 +66,13 @@ export const EffectsSetting = { }; export const DEFAULT_EFFECT = EFFECTS.NONE; + +export const POPUPS = { + SUCCESS: 'success', + ERROR: 'error' +} + +export const SUBMIT_TEXT = { + IDLE: 'Опубликовать', + SENDING: 'Публикую...' +} diff --git a/js/data.js b/js/data.js deleted file mode 100644 index a3bb3ce..0000000 --- a/js/data.js +++ /dev/null @@ -1,75 +0,0 @@ -import {getRandomInteger} from './util.js'; - - -const COUNT_PHOTOS = 25; -const DESCRIPTIONS = [ - 'Котик', - 'Вкусная еда', - 'Пляж', - 'Машина', - 'Вечерняя прогулка' -]; -const MIN_LIKES = 15; -const MAX_LIKES = 200; -const COUNT_COMMENTS = 30; -const MIN_AVATAR = 1; -const MAX_AVATAR = 6; -const MESSAGES = [ - 'Всё отлично!', - 'В целом всё неплохо. Но не всё.', - 'Когда вы делаете фотографию, хорошо бы убирать палец из кадра. В конце концов это просто непрофессионально.', - 'Моя бабушка случайно чихнула с фотоаппаратом в руках и у неё получилась фотография лучше.', - 'Я поскользнулся на банановой кожуре и уронил фотоаппарат на кота и у меня получилась фотография лучше.', - 'Лица у людей на фотке перекошены, как будто их избивают. Как можно было поймать такой неудачный момент?!' -]; -const USERS_NAME = [ - 'Анна', - 'Андрей', - 'Иван', - 'Мария', - 'Вера' -] - - -const getComments = () => { - const comments = []; - const countComments = getRandomInteger(0, COUNT_COMMENTS); - for (let i = 0; i <= countComments; i++) { - comments.push({ - id: generatePhotoId(), - avatar: `img/avatar-${getRandomInteger(MIN_AVATAR, MAX_AVATAR)}.svg`, - message: MESSAGES[getRandomInteger(0, MESSAGES.length - 1)], - name: USERS_NAME[getRandomInteger(0, USERS_NAME.length - 1)], - }) - } - return comments -} - -const getPhoto = (i) => { - return { - id: i, - url: `photos/${i}.jpg`, - description: DESCRIPTIONS[getRandomInteger(0, DESCRIPTIONS.length - 1)], - likes: getRandomInteger(MIN_LIKES, MAX_LIKES), - comments:getComments() - } -} - -const createIdGenerator = () => { - let lastGeneratedId = 0; - return () => { - lastGeneratedId += 1; - return lastGeneratedId; - }; -} -const generatePhotoId = createIdGenerator(); - -const getDescriptionPhoto = () => { - const descriptionPhoto = []; - for (let i = 1; i <= COUNT_PHOTOS; i++) { - descriptionPhoto.push(getPhoto(i)) - } - return descriptionPhoto; -} - -export {getDescriptionPhoto}; diff --git a/js/form.js b/js/form.js index 9b1074e..d7933f7 100644 --- a/js/form.js +++ b/js/form.js @@ -1,12 +1,16 @@ import { isValid, reset as resetValidation } from './validation.js'; -import {reset as resetScale} from './scale.js'; -import {reset as resetEffects} from './effect.js'; +import { reset as resetScale } from './scale.js'; +import { reset as resetEffects } from './effect.js'; +import { showPopup } from './popup.js'; +import { POPUPS, SUBMIT_TEXT } from './constans.js'; +import { sendData } from './api.js'; const uploadForm = document.querySelector('.img-upload__form'); const uploadOverlay = uploadForm.querySelector('.img-upload__overlay'); const body = document.body; const uploadCancel = uploadForm.querySelector('.img-upload__cancel'); const uploadFile = uploadForm.querySelector('#upload-file'); +const submitButton = uploadForm.querySelector('.img-upload__submit') const openForm = () => { uploadOverlay.classList.remove('hidden'); @@ -39,9 +43,30 @@ document.addEventListener('keydown', (evt) => { } }); +const blockSubmitButton = (isBlocked = true) => { + submitButton.disabled = isBlocked; + submitButton.textContent = isBlocked ? SUBMIT_TEXT.SENDING : SUBMIT_TEXT.IDLE; +} + const onFormSubmit = (evt) => { - if (!isValid()) { - evt.preventDefault(); + evt.preventDefault(); + if (isValid()) { + + blockSubmitButton(); + sendData(new FormData(uploadForm)) + .then((response) => { + if (!response.ok) { + throw new Error() + } + closeForm(); + showPopup(POPUPS.SUCCESS); + }) + .catch(() => { + showPopup(POPUPS.ERROR); + }) + .finally(() => { + blockSubmitButton(false); + }) } }; diff --git a/js/function.js b/js/function.js deleted file mode 100644 index 9d81009..0000000 --- a/js/function.js +++ /dev/null @@ -1,68 +0,0 @@ -// task 1 -const checkLengthString = (line, maxlenght) => line.length <= maxlenght; - -// console.log(checkLengthString('hjhjhjh', 20)) - -// task 2 -const isPalindrome = (text) => { - const normalizedText = text.replaceAll(' ', '').toLowerCase(); - let reversedText = ''; - - for (let i = normalizedText.length - 1; i >= 0; i--) { - reversedText += normalizedText.at(i); - } - return normalizedText === reversedText; -}; - -console.log (isPalindrome('довод')); - -// task 3 - -const cutNumbers = (text) => { - const currentText = String(text); - let result = ''; - for (let i = 0; i < currentText.length; i++) { - if(!Number.isNaN(parseInt(currentText[i], 10))){ - result +=currentText[i] - } - } - return parseInt(result, 10) - -} - -console.log(cutNumbers('asdasdasd')) - -// task 4 - -// '8:00' - начало рабочего дня startWork -// '17:30' - конец рабочего дня endWork -// '14:00' - начало встречи meetingStart -// 90 - продолжительность встречи в минутах meetingDiraction - -const timeInMinutes = (timeInHour = '') => { - const [hour, minut] = timeInHour.split(':'); - return hour * 60 + Number(minut); -} - -const isMeetInLimit = (startWork, endWork, meetingStart, meetingDiraction) => { -const startWorkInMinutes = timeInMinutes(startWork); -const endWorkInMinutes = timeInMinutes(endWork); -const meetingStartInMinutes = timeInMinutes(meetingStart); -const meetingendInMinutes = timeInMinutes(meetingStart) + meetingDiraction; - -return (meetingStartInMinutes >= startWorkInMinutes && meetingendInMinutes <= endWorkInMinutes) -} -console.log(isMeetInLimit('08:00', '17:30', '14:00', 90)); //true -console.log(isMeetInLimit('8:0', '10:0', '8:0', 120)); //true -console.log(isMeetInLimit('08:00', '14:30', '14:00', 90)); //false -console.log(isMeetInLimit('14:00', '17:30', '08:0', 90)); //false -console.log(isMeetInLimit('8:00', '17:30', '08:00', 900)); //false - - - - - - - - - diff --git a/js/main.js b/js/main.js index 60cdd0c..0faa7d4 100644 --- a/js/main.js +++ b/js/main.js @@ -1,10 +1,20 @@ -import {getDescriptionPhoto} from './data.js'; +// import {getDescriptionPhoto} from './data.js'; import {render} from './render-thumbnail.js'; import './form.js'; +import { showErrorMessage } from './util.js'; +import { getData } from './api.js'; -const data = getDescriptionPhoto(); +// const data = getDescriptionPhoto(); +// render(data); -render(data); + +getData() +.then((data)=>{ +render(data) +}) +.catch(()=>{ + showErrorMessage() +}) diff --git a/js/popup.js b/js/popup.js new file mode 100644 index 0000000..a51cf40 --- /dev/null +++ b/js/popup.js @@ -0,0 +1,20 @@ +import { POPUPS } from "./constans.js"; + +const successTemplate = document.querySelector('#success').content.querySelector('.success'); +const errorTemplate = document.querySelector('#error').content.querySelector('.error'); +const body = document.body; + +const templates = { +[POPUPS.SUCCESS]: successTemplate, +[POPUPS.ERROR]: errorTemplate +} + +export const showPopup = (type) => { + const newPopup = templates[type].cloneNode(true); + body.append(newPopup); + newPopup.addEventListener('click', ({target}) => { + if(target.classList.contains(type) || target.classList.contains(`${type}__button`)){ + newPopup.remove(); + }; + }); +} diff --git a/js/util.js b/js/util.js index eddcfa9..7a8ea5b 100644 --- a/js/util.js +++ b/js/util.js @@ -1,9 +1,19 @@ -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 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); +// }; -export {getRandomInteger}; +// export {getRandomInteger}; +const dataErrorTemplate = document.querySelector('#data-error').content.querySelector('.data-error'); +const body = document.body; +const SHOW_TIME = 5000; +export const showErrorMessage = () => { +const newDataError = dataErrorTemplate.cloneNode(true); +body.append(newDataError); +setTimeout(() => { + newDataError.remove(); +}, SHOW_TIME) +}