Skip to content

Commit

Permalink
fix: scroll to the bottom on message send
Browse files Browse the repository at this point in the history
  • Loading branch information
rasulov1337 committed Dec 18, 2024
1 parent 521ff3f commit 7e5d7e0
Showing 1 changed file with 28 additions and 18 deletions.
46 changes: 28 additions & 18 deletions src/components/ChatWindow/ChatWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ export default class ChatWindow extends BaseComponent {

socket.onopen = (e) => {
console.log('[open] Соединение установлено');
console.log('Отправляем данные на сервер');
};

socket.onmessage = (e) => this.handleMessageReceive(e);
Expand Down Expand Up @@ -99,6 +98,7 @@ export default class ChatWindow extends BaseComponent {
'.js-message-input'
) as HTMLInputElement;

/** Resizes <textarea> to fit the content */
const resizeTextArea = () => {
textArea.style.cssText = 'height: auto';
textArea.style.cssText = 'height:' + textArea.scrollHeight + 'px';
Expand Down Expand Up @@ -132,22 +132,29 @@ export default class ChatWindow extends BaseComponent {
}

private sendMessage(text: string) {
globalStore.chat.socket?.send(
JSON.stringify({
receiverId: this.recipientId,
content: text,
})
);
if (!globalStore.chat.socket) return;

this.addNewMessageElement({
content: text,
receiverId: '',
senderId: globalStore.auth.userId!,
id: 0,
createdAt: new Date().toISOString(),
});

this.emit('new-message', text);
try {
globalStore.chat.socket.send(
JSON.stringify({
receiverId: this.recipientId,
content: text,
})
);

this.addNewMessageElement({
content: text,
receiverId: '',
senderId: globalStore.auth.userId!,
id: 0,
createdAt: new Date().toISOString(),
});
this.scrollToTheBottom();

this.emit('new-message', text);
} catch (e) {
console.error('Error:', e);
}
}

private handleMessageReceive(event: MessageEvent) {
Expand All @@ -165,8 +172,7 @@ export default class ChatWindow extends BaseComponent {
this.emit('new-message', message.content);
this.addNewMessageElement(message);

this.messagesContainer.scrollTop =
this.messagesContainer.scrollHeight;
this.scrollToTheBottom();
} else {
console.log('other type of message');
}
Expand All @@ -192,4 +198,8 @@ export default class ChatWindow extends BaseComponent {

this.messagesContainer.appendChild(newMessage);
}

private scrollToTheBottom() {
this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
}
}

0 comments on commit 7e5d7e0

Please sign in to comment.