Skip to content
Open
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
3 changes: 3 additions & 0 deletions .prettierrc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
tabWidth: 4
semi: false
singleQuote: true
12 changes: 12 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import globals from 'globals'
import pluginJs from '@eslint/js'
import config from 'eslint-config-prettier'
import plugin from 'eslint-plugin-prettier/recommended'

/** @type {import('eslint').Linter.Config[]} */
export default [
{ languageOptions: { globals: globals.browser } },
pluginJs.configs.recommended,
config,
plugin,
]
97 changes: 31 additions & 66 deletions index.html
Original file line number Diff line number Diff line change
@@ -1,71 +1,36 @@
<!DOCTYPE html>
<!doctype html>
<html>
<head>
<title>Проект "Комменты"</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="styles.css" />
</head>
<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">
Это будет первый комментарий на этой странице
<body>
<div class="container">
<!-- <ul class="comments"></ul>
<div class="add-form">
<input
type="text"
class="add-form-name"
placeholder="Введите ваше имя"
id="name-input"
/>
<textarea
type="textarea"
class="add-form-text"
placeholder="Введите ваш коментарий"
rows="4"
id="text-input"
></textarea>
<div class="add-form-row">
<button class="add-form-button">Написать</button>
</div>
</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 class="form-loading" style="display: none; margin-top: 20px">
Комментарий добавляется...
</div> -->
</div>
</div>
</div>
</body>

<script>
"use strict";
// Код писать здесь
console.log("It works!");
</script>
<script type="module" src="./index.js"></script>
</body>
</html>
20 changes: 20 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { fetchComments } from './modules/api.js'
import { updateComments } from './modules/comments.js'
import { renderComments } from './modules/renderComments.js'

export const fetchAndRenderComments = (isFirstLoading) => {
const container = document.querySelector('.container')

if (isFirstLoading) {
container.innerHTML =
'<p>Пожалуйста подождите, загружаю комментарии...</p>'
}

fetchComments().then((data) => {
updateComments(data)

renderComments()
})
}

fetchAndRenderComments(true)
75 changes: 75 additions & 0 deletions modules/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// const host = 'https://webdev-hw-api.vercel.app/api/v1/vladislav-chechulin'
const host = ' https://wedev-api.sky.pro/api/v2/vladislav-chechulin'
const authHost = 'https://wedev-api.sky.pro/api/user'

export let token = ''
export let name = ''

export const setToken = (newToken) => {
token = newToken
}

export const setName = (newName) => {
name = newName
}

export const login = (login, password) => {
return fetch(authHost + '/login', {
method: 'POST',
body: JSON.stringify({ login: login, password: password }),
})
}

export const registration = (name, login, password) => {
return fetch(authHost, {
method: 'POST',
body: JSON.stringify({ name: name, login: login, password: password }),
})
}

export const fetchComments = () => {
return fetch(host + '/comments')
.then((res) => res.json())
.then((responseData) => {
const appComments = responseData.comments.map((comment) => {
return {
name: comment.author.name,
date: new Date(comment.date),
text: comment.text,
likes: comment.likes,
isLiked: false,
}
})

return appComments
})
}

export const postComment = (text, name) => {
return fetch(host + '/comments', {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
text,
name,
}),
})
.then((response) => {
if (response.status === 500) {
throw new Error('Ошибка сервера')
}

if (response.status === 401) {
throw new Error('Пользователь не авторизован')
}

if (response.status === 400) {
throw new Error('Неверный запрос')
}
})
.then(() => {
return fetchComments()
})
}
20 changes: 20 additions & 0 deletions modules/comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export let comments = [
// {
// name: 'Глеб Фокин',
// date: new Date(),
// text: 'Это будет первый комментарий на этой странице',
// likes: 3,
// isLiked: false,
// },
// {
// name: 'Варвара Н.',
// date: new Date(),
// text: 'Мне нравится как оформлена эта страница! ❤',
// likes: 75,
// isLiked: true,
// },
]

export const updateComments = (newComments) => {
comments = newComments
}
85 changes: 85 additions & 0 deletions modules/initListeners.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { postComment } from './api.js'
import { comments, updateComments } from './comments.js'
import { sanitizeHtml } from './sanitizeHtml.js'

export const initLikeListeners = (renderComments) => {
const likeButtons = document.querySelectorAll('.like-button')

for (const likeButton of likeButtons) {
likeButton.addEventListener('click', (event) => {
event.stopPropagation()

const index = likeButton.dataset.index
const comment = comments[index]

comment.likes = comment.isLiked
? comment.likes - 1
: comment.likes + 1

comment.isLiked = !comment.isLiked

renderComments()
})
}
}

export const initReplyListeners = () => {
const text = document.getElementById('text-input')
const commentsElements = document.querySelectorAll('.comment')

for (const commentElement of commentsElements) {
commentElement.addEventListener('click', () => {
const currentComment = comments[commentElement.dataset.index]
text.value = `${currentComment.name}: ${currentComment.text}`
})
}
}

export const initAddCommentListener = (renderComments) => {
const name = document.getElementById('name-input')
const text = document.getElementById('text-input')
const addButton = document.querySelector('.add-form-button')

addButton.addEventListener('click', () => {
if (!name.value || !text.value) {
console.error('заполните форму')
return
}

document.querySelector('.form-loading').style.display = 'block'
document.querySelector('.add-form').style.display = 'none'

postComment(sanitizeHtml(text.value), sanitizeHtml(name.value))
.then((data) => {
updateComments(data)
renderComments()

name.value = ''
text.value = ''
})
.catch((error) => {
document.querySelector('.form-loading').style.display = 'none'
document.querySelector('.add-form').style.display = 'flex'

if (error.message === 'Ошибка сервера') {
alert('Сервер сломался, попробуй позже')
}

if (error.message === 'Failed to fetch') {
alert('Нет интернета, попробуй позже')
}

if (error.message === 'Неверный запрос') {
alert('Имя и комментарий должны быть не короче 3х символов')

name.classList.add('-error')
text.classList.add('-error')

setTimeout(() => {
name.classList.remove('-error')
text.classList.remove('-error')
}, 2000)
}
})
})
}
Loading