89 lines
2.5 KiB
TypeScript
89 lines
2.5 KiB
TypeScript
import { ChangeDetectorRef, Component, OnInit, EventEmitter, Output, ElementRef } from '@angular/core';
|
|
import {MessageData, Message, MessageButton, MessageButtonMap} from '../message-types/bot-messages';
|
|
import { MarkdownService } from '../services/markdown.service';
|
|
import { WebSocketService } from '../services/websocket.service';
|
|
import { Subject } from 'rxjs';
|
|
|
|
@Component({
|
|
selector: 'app-messages',
|
|
templateUrl: './messages.component.html',
|
|
styleUrls: ['./messages.component.scss']
|
|
})
|
|
export class MessagesComponent implements OnInit {
|
|
@Output() newMessageEvent: EventEmitter<any> = new EventEmitter();
|
|
newMessage: Subject<MessageData> = new Subject<MessageData>();
|
|
showTypingIndicator = false;
|
|
messages: MessageData[] = [];
|
|
buttonMap: MessageButtonMap = {
|
|
fix: {caption: 'Ready to fix'},
|
|
solution: {caption: 'Show solution'},
|
|
hint: {caption: 'Hint'},
|
|
next: {caption: 'Next'},
|
|
yes: {caption: 'Yes'},
|
|
no: {caption: 'No'},
|
|
};
|
|
|
|
constructor(
|
|
private markdownService: MarkdownService,
|
|
private websocketService: WebSocketService,
|
|
private changeDetectorRef: ChangeDetectorRef,
|
|
private ref: ElementRef
|
|
) {}
|
|
|
|
ngOnInit() {
|
|
this.newMessage.subscribe(
|
|
message => {
|
|
this.writeMessage(message);
|
|
this.newMessageEvent.emit();
|
|
this.scrollToBottom();
|
|
});
|
|
|
|
this.websocketService.connect();
|
|
this.websocketService.observeControl<Message>('message.send').subscribe(
|
|
message => this.newMessage.next(message)
|
|
);
|
|
}
|
|
|
|
writeMessage(message: MessageData) {
|
|
this.transformMessage(message);
|
|
this.messages.push(message);
|
|
this.changeDetectorRef.detectChanges();
|
|
}
|
|
|
|
scrollToBottom() {
|
|
const element = this.ref.nativeElement.parentElement;
|
|
element.scrollTop = element.scrollHeight;
|
|
}
|
|
|
|
transformMessage(message: MessageData) {
|
|
message.message = this.convertMarkdownToHTML(message.message);
|
|
if (!message.timestamp) {
|
|
message.timestamp = new Date();
|
|
}
|
|
this.showTypingIndicator = message.typing;
|
|
}
|
|
|
|
convertMarkdownToHTML(text: string) {
|
|
return this.markdownService.convertToHtml(text);
|
|
}
|
|
|
|
drainMessageQueue() {
|
|
this.websocketService.send({
|
|
'key': 'message.queue.drain'
|
|
});
|
|
}
|
|
|
|
sendMessageCommand(message: MessageData) {
|
|
if ('command' in message) {
|
|
this.websocketService.send(message.command);
|
|
}
|
|
}
|
|
|
|
sendButtonCommand(messageButton: MessageButton) {
|
|
this.websocketService.send({
|
|
'key': 'message.button.click',
|
|
'value': messageButton
|
|
});
|
|
}
|
|
}
|