-
Notifications
You must be signed in to change notification settings - Fork 0
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
Отправка сообщений #22
Merged
Merged
Changes from 16 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
c4a45cd
фикс роутера
oFem1m 3d7a9fe
Заготовка под вебсокеты
oFem1m dcbae6f
Включение/отключение вебсокета при авторизации/выходе
oFem1m b526e74
Работает отправка сообщений через вебсокеты
oFem1m 9d276e2
Правка config.js
oFem1m f93726c
Правка config.js
oFem1m b1dbac3
Правка ws/wss
oFem1m ffd6ccf
фикс конфига
oFem1m 9670795
Сообщения пользователя и его собеседника находятся в разных сторонах …
oFem1m eaa59aa
фикс стрелочки
oFem1m ab93ba5
UserId → userId
oFem1m 2e0a2d0
добавил trim и удаление xss
oFem1m 59a06ac
перенес санитазйер в valid.js
oFem1m fac7a82
Изменена обработка страниц
oFem1m a40ba4f
вебсокеты работают!
oFem1m 9e69a3c
фикс бага с черновиками сообщений, обновлением сообщений при переходе…
oFem1m 883a2dc
добавил обработку нажатия enter для отправки сообщения
oFem1m a702335
теперь браузер не "подсказывает" при вводе сообщения
oFem1m 4e982fb
Merge branch 'develop' into sending_messages
oFem1m 7383ac8
фикс для сливания веток
oFem1m 0027199
prettier fix
oFem1m File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,3 @@ | ||
<div class="message"> | ||
<div class="{{message_owner}}"> | ||
{{message_text}} | ||
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
export class BasePage { | ||
#parent; | ||
|
||
constructor(parent) { | ||
this.#parent = parent; | ||
} | ||
|
||
render() { | ||
throw new Error('Метод render не определен'); | ||
} | ||
|
||
async getData() {} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,23 +5,58 @@ import Chat from '../Components/Chat/Chat.js'; | |
import ChatList from '../Components/ChatList/ChatList.js'; | ||
import Message from '../Components/Message/Message.js'; | ||
import { ProfileAPI } from '../utils/API/ProfileAPI.js'; | ||
import { websocketManager } from '../utils/WebSocket.js'; | ||
import { sanitizer } from '../utils/valid.js'; | ||
import { BasePage } from './BasePage.js'; | ||
|
||
/** | ||
/* | ||
* Рендерит страницу чатов | ||
* @class Класс страницы чатов | ||
*/ | ||
export default class ChatPage { | ||
export default class ChatPage extends BasePage { | ||
#parent; | ||
#chat; | ||
#chatList; | ||
#messageDrafts = {}; | ||
#currentChatId; | ||
#profile; | ||
#chats; | ||
|
||
constructor(parent, urlParams) { | ||
super(parent); | ||
this.#parent = parent; | ||
this.#currentChatId = parseInt(urlParams.get('id')); | ||
websocketManager.connect(); | ||
websocketManager.setMessageHandler(this.handleWebSocketMessage); | ||
this.getData().then(() => this.render()); | ||
} | ||
|
||
getData = async () => { | ||
try { | ||
const chatAPI = new ChatAPI(); | ||
const profileAPI = new ProfileAPI(); | ||
|
||
const [chatsResponse, profileResponse] = await Promise.all([ | ||
chatAPI.getChats(), | ||
profileAPI.getProfile(), | ||
]); | ||
|
||
this.#chats = chatsResponse.body.chats; | ||
if (profileResponse.status !== 200) { | ||
throw new Error('Пришел не 200 статус'); | ||
} | ||
this.#profile = profileResponse.body.user; | ||
|
||
return { | ||
chats: this.#chats, | ||
profile: this.#profile, | ||
}; | ||
} catch (error) { | ||
console.error('Ошибка при получении данных:', error); | ||
throw error; | ||
} | ||
}; | ||
|
||
render() { | ||
const wrapper = document.createElement('div'); | ||
wrapper.classList = 'full-screen'; | ||
|
@@ -30,60 +65,88 @@ export default class ChatPage { | |
logoutHandler: this.handleLogout, | ||
}); | ||
this.#chatList.render(); | ||
this.#chatList.setUserName(`${this.#profile.username}`); | ||
|
||
this.#chat = new Chat(wrapper, { | ||
inputMessaegHandler: this.messageDraftHandler, | ||
inputMessageHandler: this.messageDraftHandler, | ||
sendMessageHandler: this.messageSendHandler, | ||
}); | ||
this.#chat.render(); | ||
|
||
this.#parent.appendChild(wrapper); | ||
let checkChatId = false; | ||
|
||
const chatAPI = new ChatAPI(); | ||
chatAPI | ||
.getChats() | ||
.then((chats) => { | ||
chats.body.chats.forEach((chatConfig) => { | ||
if (chatConfig.id === this.#currentChatId) { | ||
checkChatId = true; | ||
this.displayActiveChat(chatConfig); | ||
} | ||
this.#chatList.addChat(chatConfig, () => { | ||
this.#chat.setInputMessageValue( | ||
this.#messageDrafts[chatConfig.id] || '', | ||
); | ||
this.displayActiveChat(chatConfig); | ||
goToPage('/chat?id=' + chatConfig.id); | ||
}); | ||
}); | ||
if (!checkChatId && !isNaN(this.#currentChatId)) { | ||
goToPage('/chat'); | ||
this.#currentChatId = null; | ||
} | ||
}) | ||
.catch((error) => { | ||
console.error('Ошибка при получении чатов:', error); | ||
}); | ||
|
||
const profileAPI = new ProfileAPI(); | ||
profileAPI | ||
.getProfile() | ||
.then((response) => { | ||
if (response.status !== 200) { | ||
throw new Error('Пришел не 200 статус'); | ||
} | ||
const profile = response.body.user; | ||
this.#chatList.setUserName(`${profile.username}`); | ||
}) | ||
.catch((error) => { | ||
console.error('Ошибка при получении профиля:', error); | ||
}); | ||
this.displayChats(this.#chats); | ||
} | ||
|
||
messageDraftHandler = (event) => { | ||
this.#messageDrafts[this.#currentChatId] = event.target.value; | ||
}; | ||
|
||
messageSendHandler = () => { | ||
// Контейнер активного чата | ||
const inputMessage = this.#parent | ||
.querySelector('#input_message') | ||
.value.trim(); | ||
const urlParams = new URLSearchParams(window.location.search); | ||
const chatId = parseInt(urlParams.get('id')); | ||
if (inputMessage && chatId) { | ||
// Проверяем, что есть сообщение и ID чата | ||
const sanitizedInputMessage = sanitizer(inputMessage); | ||
websocketManager.sendMessage(chatId, sanitizedInputMessage); | ||
document.querySelector('#input_message').value = ''; | ||
} else { | ||
console.error('Нет текста сообщения или ID чата.'); | ||
} | ||
}; | ||
|
||
handleWebSocketMessage = (message) => { | ||
const chatIndex = this.#chats.findIndex( | ||
(chat) => chat.id === message.chat_id, | ||
); | ||
if (chatIndex !== -1) { | ||
const chat = this.#chats.splice(chatIndex, 1)[0]; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. проще сделать сортировку через css (свойство order) |
||
this.#chats.unshift(chat); | ||
const activeChatContainer = document.getElementById( | ||
'active-chat-container', | ||
); | ||
const owner = | ||
message.user_id === this.#profile.id ? 'my_message' : 'message'; | ||
const messageElement = new Message(activeChatContainer, { | ||
message_owner: owner, | ||
message_text: message.message_text, | ||
}); | ||
messageElement.render(); | ||
this.#chats[0].messages.push(message); // Добавляем сообщение в начало массива сообщений | ||
this.displayChats(this.#chats); // Обновляем отображение чатов | ||
} | ||
}; | ||
|
||
displayChats(chats) { | ||
const chatListContainer = document.getElementById( | ||
'chat-list-container', | ||
); | ||
chatListContainer.innerHTML = ''; | ||
let checkChatId = false; | ||
chats.forEach((chatConfig) => { | ||
if (chatConfig.id === this.#currentChatId) { | ||
checkChatId = true; | ||
this.displayActiveChat(chatConfig); | ||
} | ||
this.#chatList.addChat(chatConfig, () => { | ||
this.#chat.setInputMessageValue( | ||
this.#messageDrafts[chatConfig.id] || '', | ||
); | ||
this.displayActiveChat(chatConfig); | ||
this.#currentChatId = chatConfig.id; | ||
goToPage('/chat?id=' + chatConfig.id, false); | ||
}); | ||
}); | ||
this.#messageDrafts[this.#currentChatId] = ''; | ||
if (!checkChatId && !isNaN(this.#currentChatId)) { | ||
goToPage('/chat', false); | ||
this.#currentChatId = null; | ||
} | ||
} | ||
|
||
displayActiveChat(chat) { | ||
// Очищаем контейнер активного чата | ||
const activeChatContainer = document.getElementById( | ||
|
@@ -113,7 +176,13 @@ export default class ChatPage { | |
|
||
// Отображаем сообщения в чате | ||
chat.messages.forEach((message) => { | ||
// Если сообщение от акитивного юзера, то | ||
let owner = 'message'; | ||
if (this.#profile.id === message.user_id) { | ||
owner = 'my_message'; | ||
} | ||
const messageElement = new Message(activeChatContainer, { | ||
message_owner: owner, | ||
message_text: message.message_text, | ||
}); | ||
messageElement.render(); | ||
|
@@ -129,7 +198,8 @@ export default class ChatPage { | |
if (data.status === 200) { | ||
// Обработка успешной авторизации | ||
console.log('Successfully logged out'); | ||
goToPage('/login'); | ||
websocketManager.close(); | ||
goToPage('/login', true); | ||
} else { | ||
console.log('Error logged out'); | ||
} | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вот тут нет ошибки?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Там теперь логика такая, что если id пользователя совпадает с id отправителя сообщения, то используется класс my_message, для которого уже заготовлены стили
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
так это можно прямо в шаблоне проверить типа через
class="{{isCurrentUserOwner ? 'owner' : 'noOwner'}}"