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
25 changes: 1 addition & 24 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,6 @@
</head>

<body>
<div class="container">
<p class="loading">
Пожалуйста подождите, комментарии загружаются...
</p>
<ul class="comments"></ul>
<div class="add-form">
<input
type="text"
class="add-form-name"
placeholder="Введите ваше имя"
required
/>
<textarea
type="textarea"
class="add-form-text"
placeholder="Введите ваш коментарий"
rows="4"
required
></textarea>
<div class="add-form-row">
<button class="add-form-button">Написать</button>
</div>
</div>
</div>
<div class="app"></div>
</body>
</html>
74 changes: 69 additions & 5 deletions js/api/commentsAPI.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
import { comments } from '../commentsArray/commentsArray.js'
import { renderComments } from '../renderComment/renderComments.js'
import { renderComments } from '../render/renderComments.js'
import {
formTextArea,
formInput,
formComment,
formName,
} from '../handlers/formHandlers.js'

const host = 'https://wedev-api.sky.pro/api/v2/MethodGirl'

// let token = 'asb4c4boc86gasb4c4boc86g37w3cc3bo3b83k4g37k3bk3cg3c03ck4k'

export let token = ''

export const updateToken = (newToken) => {
token = newToken
}
export function getCommentsAPI() {
return fetch('https://wedev-api.sky.pro/api/v1/MethodGirl/comments', {
return fetch(host + '/comments', {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
},
}).then((response) => response.json())
}

const host = 'https://wedev-api.sky.pro/api/v1/MethodGirl'

export function postCommentAPI(newComment) {
const commentForAPI = {
name: newComment.name,
Expand All @@ -26,10 +36,12 @@ export function postCommentAPI(newComment) {

return fetch(host + '/comments', {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
text: newComment.text,
name: newComment.name,
forceError: true,
}),
}).then((response) => {
if (response.status === 400) {
Expand All @@ -47,3 +59,55 @@ export function postCommentAPI(newComment) {
response.json()
})
}

export function login({ login, password }) {
return fetch('https://wedev-api.sky.pro/api/user/login', {
method: 'POST',
body: JSON.stringify({ login, password }),
})
.then((response) => {
return response.json().then((data) => {
if (!response.ok) {
console.error('Ответ сервера:', data)
throw new Error(
data.message ||
data.error ||
`Ошибка ${response.status}`,
)
}
return data
})
})
.catch((error) => {
if (
error.message.includes('400') ||
error.message.includes('Неверный')
) {
alert('Неверный пароль или логин, попробуйте снова')
}
})
}

export function registration({ login, name, password }) {
return fetch('https://wedev-api.sky.pro/api/user', {
method: 'POST',
body: JSON.stringify({ login, name, password }),
})
.then((response) => {
return response.json().then((data) => {
if (!response.ok) {
console.error('Ответ сервера:', data)
throw new Error(
data.message ||
data.error ||
`Ошибка ${response.status}`,
)
}
return data
})
})
.catch((error) => {
console.error('Ошибка запроса:', error)
throw error
})
}
33 changes: 17 additions & 16 deletions js/handlers/addCopyCommentToFormHandlers.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { humanizeText } from "../textFormater/humanizeText.js";
import { comments } from "../commentsArray/commentsArray.js";
import { formComment } from "../handlers/formHandlers.js";
import { humanizeText } from '../textFormater/humanizeText.js'
import { comments } from '../commentsArray/commentsArray.js'

export function addCopyCommentToFormHandlers() {
let commentsEl = document.querySelectorAll(".comment");
let commentForm = document.querySelector('.add-form-text')

for (let commentEl of commentsEl) {
function copyCommentToForm() {
console.log(commentEl);
let index = commentEl.dataset.id;
let commentsEl = document.querySelectorAll('.comment')

formComment.value =
"Ответ на комментарий: " +
humanizeText(comments[index].text) +
" Автор: " +
humanizeText(comments[index].name);
}
for (let commentEl of commentsEl) {
function copyCommentToForm() {
console.log(commentEl)
let index = commentEl.dataset.id

commentForm.value =
'Ответ на комментарий: ' +
humanizeText(comments[index].text) +
' Автор: ' +
humanizeText(comments[index].name)
}

commentEl.addEventListener("click", copyCommentToForm);
}
commentEl?.addEventListener('click', copyCommentToForm)
}
}
56 changes: 37 additions & 19 deletions js/handlers/addLikeHandlers.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,42 @@
import { comments } from "../commentsArray/commentsArray.js";
import { renderComments } from "../renderComment/renderComments.js";
import { comments } from '../commentsArray/commentsArray.js'
import { renderComments } from '../render/renderComments.js'
import { token } from '../api/commentsAPI.js'

export function addLikeHandlers() {
let likeButtons = document.querySelectorAll(".like-button");
let likesCounter = document.querySelectorAll(".likes-counter");
let likeButtons = document.querySelectorAll('.like-button')
let likesCounter = document.querySelectorAll('.likes-counter')

likeButtons.forEach((button) => {
button.addEventListener("click", (event) => {
event.stopPropagation();
let index = button.dataset.index;
likeButtons.forEach((button) => {
button.addEventListener('click', (event) => {
event.stopPropagation()

if (comments[index].isLiked === true) {
comments[index].isLiked = false;
comments[index].likesCounter--;
} else {
comments[index].isLiked = true;
comments[index].likesCounter++;
}
if (token === '') {
alert('Авторизуйтесь, чтобы ставить лайки')
return
}

renderComments();
});
});
}
let index = button.dataset.index

button.classList.add('shake')
button.addEventListener(
'animationend',
() => {
button.classList.remove('shake')
},
{ once: true },
)

if (comments[index].isLiked === true) {
button.classList.remove('-active-like')
comments[index].isLiked = false
comments[index].likesCounter--
} else {
button.classList.add('-active-like')
comments[index].isLiked = true
comments[index].likesCounter++
}

likesCounter[index].textContent = comments[index].likesCounter
})
})
}
39 changes: 30 additions & 9 deletions js/handlers/formHandlers.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { comments } from '../commentsArray/commentsArray.js'
import { renderComments } from '../renderComment/renderComments.js'
import { renderComments } from '../render/renderComments.js'
import { fixText } from '../textFormater/fixText.js'
import { postCommentAPI, getCommentsAPI } from '../api/commentsAPI.js'

Expand All @@ -10,13 +10,18 @@ export let formInput = document.querySelector('.add-form-name')

let formButton = document.querySelector('.add-form-button')

function paintBackground() {
formTextArea.style.backgroundColor = 'white'
formInput.style.backgroundColor = 'white'
}
document.addEventListener('click', (event) => {
let formTextArea = event.target.closest('.add-form-text')
let formInput = event.target.closest('.add-form-name')

if (formTextArea) {
formTextArea.style.backgroundColor = 'white'
}

formTextArea.addEventListener('click', () => paintBackground(formTextArea))
formInput.addEventListener('click', () => paintBackground(formInput))
if (formInput) {
formInput.style.backgroundColor = 'white'
}
})

function delay(ms) {
let promise = new Promise((resolve) => {
Expand All @@ -28,7 +33,23 @@ function delay(ms) {
return promise
}

formButton.addEventListener('click', async () => {
document.addEventListener('click', async (event) => {
const button = event.target.closest('.add-form-button')
let formTextArea = document.querySelector('.add-form-text')
let formInput = document.querySelector('.add-form-name')

if (!button) return

const formComment = document.querySelector('.add-form-text')
const formName = document.querySelector('.add-form-name')
const form = document.querySelector('.add-form')
const commentList = document.querySelector('.comments')

if (!formComment || !formName || !form) {
console.error('Элементы не найдены')
return
}

try {
let commentValue = formComment.value
let nameValue = formName.value
Expand Down Expand Up @@ -92,8 +113,8 @@ formButton.addEventListener('click', async () => {
renderComments()

formComment.value = ''
formName.value = ''
form.style.display = 'flex'
console.log('click')
} catch (error) {
let form = document.querySelector('.add-form')
let loadingMessage = document.querySelector('.comment-creating')
Expand Down
32 changes: 30 additions & 2 deletions js/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { getCommentsAPI } from './api/commentsAPI.js'
import { comments } from './commentsArray/commentsArray.js'
import { renderComments } from './renderComment/renderComments.js'
import { renderComments } from './render/renderComments.js'
import { renderForm } from './render/renderForm.js'
import { renderLogin } from './render/renderLogin.js'
import { token } from './api/commentsAPI.js'
import { renderLoader } from './render/renderLoader.js'

renderForm()

let loadingMessage = document.querySelector('.loading')

Expand Down Expand Up @@ -29,7 +35,6 @@ const initPage = async () => {
comments.push(...convertedComments)

renderComments()

loadingMessage.style.display = 'none'
} catch (error) {
console.error('Ошибка:', error)
Expand All @@ -39,3 +44,26 @@ const initPage = async () => {
}

initPage()

renderComments()

export let nameInput = document.querySelector('.add-form-name')
export let commentInput = document.querySelector('.add-form-text')
export let addCommentButton = document.querySelector('.add-form-button')

if (token === '') {
nameInput.disabled = true
commentInput.disabled = true
addCommentButton.disabled = true
}

export let autorizationLink = document.querySelector('.autorization-link')
let container = document.querySelector('.container')

autorizationLink?.addEventListener('click', () => {
renderLogin()
window.scrollTo({
top: 0,
behavior: 'smooth',
})
})
10 changes: 10 additions & 0 deletions js/render/renderAutorizationLink.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export function renderAutorizationLink() {
let form = document.querySelector('.add-form')

let autorizationLink = document.createElement('a')

autorizationLink.className = 'autorization-link'
autorizationLink.textContent = 'Чтобы добавить комментарий, авторизуйтесь'

form.before(autorizationLink)
}
33 changes: 33 additions & 0 deletions js/render/renderComments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { comments } from '../commentsArray/commentsArray.js'
import { addLikeHandlers } from '../handlers/addLikeHandlers.js'
import { addCopyCommentToFormHandlers } from '../handlers/addCopyCommentToFormHandlers.js'
import { getFormattedDate } from '../getFormattedDate/getFormattedDate.js'

export function renderComments() {
let commentsBox = document.querySelector('.comments')
let commentElements = comments
.map((comment, index) => {
return `
<li class="comment" data-id=${index}>
<div class="comment-header">
<div class="comment-header__name">${comment.name}</div>
<div class="comment-header__date">${getFormattedDate(comment.data)}</div>
</div>
<div class="comment-body">
<div class="comment-text">${comment.text}</div>
</div>
<div class="comment-footer">
<div class="likes">
<span class="likes-counter" >${comment.likesCounter}</span>
<button class="like-button ${comment.isLiked ? '-active-like' : ''}" data-index=${index}></button>
</div>
</div>
</li>`
})
.join('')

commentsBox.innerHTML = commentElements
addCopyCommentToFormHandlers()
addLikeHandlers()
console.log(comments)
}
Loading