-
Notifications
You must be signed in to change notification settings - Fork 37
/
chat.component.ts
104 lines (88 loc) 路 2.64 KB
/
chat.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { Component, OnInit, ViewChild, ElementRef, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { CustomValidators } from '../validators/custom-validators';
import { showFormErrors } from '../shared/table-helpers';
import { ChatService } from '../shared/chat.service';
@Component({
selector: 'planet-chat',
templateUrl: './chat.component.html',
styleUrls: [ './chat.component.scss' ],
})
export class ChatComponent implements OnInit {
spinnerOn = true;
isFullscreen = false;
promptForm: FormGroup;
messages: any[] = [];
conversations: any[] = [];
@ViewChild('chat') chatContainer: ElementRef;
constructor(
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private changeDetectorRef: ChangeDetectorRef,
private chatService: ChatService
) {}
ngOnInit() {
this.createForm();
}
scrollToBottom(): void {
this.chatContainer.nativeElement.scrollTo({
top: this.chatContainer.nativeElement.scrollHeight,
behavior: 'smooth',
});
}
createForm() {
this.promptForm = this.formBuilder.group({
prompt: [ '', CustomValidators.required ],
});
}
goBack() {
this.router.navigate([ '/' ], { relativeTo: this.route });
}
onSubmit() {
if (!this.promptForm.valid) {
showFormErrors(this.promptForm.controls);
return;
}
this.submitPrompt();
}
submitPrompt() {
const content = this.promptForm.get('prompt').value;
this.messages.push({ role: 'user', content });
this.chatService.getPrompt(content).subscribe(
(completion: any) => {
this.conversations.push({
query: content,
response: completion?.chat,
});
this.spinnerOn = false;
this.changeDetectorRef.detectChanges();
this.scrollToBottom();
this.spinnerOn = true;
},
(error: any) => {
console.log(error);
this.conversations.push({
query: content,
response: 'Error: ' + error.message,
error: true,
});
}
);
}
sanitizeText(text: string): string {
// Replace newline characters with <br> tags
const textWithLineBreaks = text.replace(/\n/g, '<br>');
// Replace code block markers with <code> tags
const codeBlockStart = /```/g;
const codeBlockEnd = /```/g;
const textWithCodeBlocks = textWithLineBreaks
.replace(codeBlockStart, '<code>')
.replace(codeBlockEnd, '</code>');
return textWithCodeBlocks;
}
toggleFullScreen() {
this.isFullscreen = !this.isFullscreen;
}
}