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

2.13 #836

Closed
wants to merge 19 commits into from
Closed

2.13 #836

15 changes: 0 additions & 15 deletions .github/workflows/greetings.yml

This file was deleted.

3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"liveServer.settings.port": 5501
}
9 changes: 0 additions & 9 deletions README.md

This file was deleted.

100 changes: 36 additions & 64 deletions index.html
Original file line number Diff line number Diff line change
@@ -1,71 +1,43 @@
<!DOCTYPE html>
<html>
<head>
<title>Проект "Комменты"</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="styles.css" />
</head>

<body>
<div class="container">
<ul class="comments">
<li class="comment">
<div class="comment-header">
<div>Глеб Фокин</div>
<div>12.02.22 12:18</div>
</div>
<div class="comment-body">
<div class="comment-text">
Это будет первый комментарий на этой странице
</div>
</div>
<div class="comment-footer">
<div class="likes">
<span class="likes-counter">3</span>
<button class="like-button"></button>
</div>
</div>
</li>
<li class="comment">
<div class="comment-header">
<div>Варвара Н.</div>
<div>13.02.22 19:22</div>
</div>
<div class="comment-body">
<div class="comment-text">
Мне нравится как оформлена эта страница! ❤
</div>
</div>
<div class="comment-footer">
<div class="likes">
<span class="likes-counter">75</span>
<button class="like-button -active-like"></button>
</div>
</div>
</li>
</ul>
<div class="add-form">
<input
type="text"
class="add-form-name"
placeholder="Введите ваше имя"
/>
<textarea
type="textarea"
class="add-form-text"
placeholder="Введите ваш коментарий"
rows="4"
></textarea>
<div class="add-form-row">
<button class="add-form-button">Написать</button>
</div>
<head>
<title>Проект "Комменты"</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="styles.css" />
</head>

<body>
<div class="container">
<span id="preloader">Загрузка страницы комментариев....</span>
<ul id="list" class="comments">
<!-- Список рендерится из JS -->
</ul>
<div class="add-form">
<input id="name-input" type="text" class="add-form-name" placeholder="Введите ваше имя" />
<textarea id="comment-input" type="textarea" class="add-form-text" placeholder="Введите ваш коментарий"
rows="4"></textarea>
<div class="add-form-row">
<button id="add-button" class="add-form-button">Написать</button>
</div>
<div class="add-form-row">
<button id="delete-button" class="add-form-button">Удалить последний комментарий</button>
</div>
</div>
</body>
</div>
</body>

<style>
.error {
background-color: red;
}
.hide {
display: none;
}
</style>
<script src="script.js" defer></script>

<script>
"use strict";
// Код писать здесь
console.log("It works!");
</script>
</html>



176 changes: 176 additions & 0 deletions script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
"use strict";
const addButtonElement = document.getElementById('add-button');
const listElement = document.getElementById('list');
const nameInputElement = document.getElementById('name-input');
const commentInputElement = document.getElementById('comment-input');
const preLoadElement = document.getElementById('preloader');


// Получениe комментов с сервера
function getComments() {
return fetch(
'https://wedev-api.sky.pro/api/v1/rustam-kholov/comments',
{
method: "GET"
}
)
.then((response) => {
return response.json();
})
.then((responseData) => {
const appComments = responseData.comments.map((comment) => {
return {
name: comment.author.name,
date: new Date(comment.date).toLocaleDateString('ru-RU', { year: '2-digit', month: '2-digit', day: '2-digit' }) + ' ' + new Date(comment.date).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit', second: '2-digit' }),
comment: comment.text,
likesCounter: comment.likes,
isLiked: false,
};
});
comments = appComments;
renderComments();
preLoadElement.classList.add('hide');
});

}



// Массив для комментов
let comments = [];


// Рендер функция
const renderComments = () => {
const commentsHtml = comments.map((comment, index) => {
return `<li class="comment">
<div class="comment-header">
<div data-index="${index}">${comment.name}</div>
<div>${comment.date}</div>
</div>
<div class="comment-body">
<div data-index="${index}" class="comment-text">
${comment.comment}
</div>
</div>
<div class="comment-footer">
<div class="likes">
<span id="likes" class="likes-counter">${comment.likesCounter}</span>
<button id="button-like" data-like="${comment.likesCounter}" data-index="${index}" class="like-button ${comments[index].isLiked ? '-active-like' : ''}"></button>
</div>
</div>
</li>`
}).join('');
listElement.innerHTML = commentsHtml;

initLikeButtonListeners();
reply();
removeValidation();
};

getComments();

// Отложенный коммент
function delay(interval = 300) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, interval);
});
}

// Кнопка для лайка
const initLikeButtonListeners = () => {
const addLikesButtonsElements = document.querySelectorAll('.like-button');


for (const addLikesButtonsElement of addLikesButtonsElements) {

const index = addLikesButtonsElement.dataset.index;
const counter = addLikesButtonsElement.dataset.like;

addLikesButtonsElement.addEventListener('click', () => {

if (comments[index].isLiked === false) {

const result = Number(counter) + 1;
comments[index].likesCounter = result;

comments[index].isLiked = true;

} else {

const result = Number(counter) - 1;
comments[index].likesCounter = result;

comments[index].isLiked = false;
}
renderComments();
})
}
};


// Ответ по клику на коммент
function reply() {

const commentElements = document.querySelectorAll('.comment-body');
const formTextElement = document.querySelector('.add-form-text');

commentElements.forEach((element, index) => {
element.addEventListener('click', () => {
formTextElement.value = `> ${comments[index].name} \n ${comments[index].comment}`;
});
});
}

reply();


// Отмена валидации (чтобы не было красных полей)
function removeValidation() {

nameInputElement.addEventListener('click', () => {
nameInputElement.classList.remove('error')
});

commentInputElement.addEventListener('click', () => {
commentInputElement.classList.remove('error')
});
};
removeValidation();


// Добавление нового коммента на сервер
addButtonElement.addEventListener('click', () => {
nameInputElement.classList.remove('error');
commentInputElement.classList.remove('error');

if (nameInputElement.value.trim() === '' || commentInputElement.value.trim() === '') {
nameInputElement.classList.add('error');
commentInputElement.classList.add('error');
return;
};

addButtonElement.disabled = true;
addButtonElement.textContent = 'Комментарий добавляется.....';

fetch(
'https://wedev-api.sky.pro/api/v1/rustam-kholov/comments',
{
method: "POST",
body: JSON.stringify({
name: nameInputElement.value,
text: commentInputElement.value,
})
}
).then(() => {
return getComments();
}).then(() => {
addButtonElement.disabled = false;
addButtonElement.textContent = 'Добавить';
})
nameInputElement.value = '';
commentInputElement.value = '';
renderComments();
});
Loading
Loading