|
| 1 | +import { Component, OnInit, ViewChild, ElementRef, ChangeDetectorRef } from '@angular/core'; |
| 2 | +import { FormBuilder, FormGroup } from '@angular/forms'; |
| 3 | +import { ActivatedRoute, Router } from '@angular/router'; |
| 4 | + |
| 5 | +import { CustomValidators } from '../validators/custom-validators'; |
| 6 | +import { showFormErrors } from '../shared/table-helpers'; |
| 7 | +import { ChatService } from '../shared/chat.service'; |
| 8 | + |
| 9 | +@Component({ |
| 10 | + selector: 'planet-chat', |
| 11 | + templateUrl: './chat.component.html', |
| 12 | + styleUrls: [ './chat.component.scss' ], |
| 13 | +}) |
| 14 | +export class ChatComponent implements OnInit { |
| 15 | + spinnerOn = true; |
| 16 | + promptForm: FormGroup; |
| 17 | + messages: any[] = []; |
| 18 | + conversations: any[] = []; |
| 19 | + |
| 20 | + @ViewChild('chat') chatContainer: ElementRef; |
| 21 | + |
| 22 | + constructor( |
| 23 | + private formBuilder: FormBuilder, |
| 24 | + private route: ActivatedRoute, |
| 25 | + private router: Router, |
| 26 | + private changeDetectorRef: ChangeDetectorRef, |
| 27 | + private chatService: ChatService |
| 28 | + ) {} |
| 29 | + |
| 30 | + ngOnInit() { |
| 31 | + this.createForm(); |
| 32 | + } |
| 33 | + |
| 34 | + scrollToBottom(): void { |
| 35 | + this.chatContainer.nativeElement.scrollTo({ |
| 36 | + top: this.chatContainer.nativeElement.scrollHeight, |
| 37 | + behavior: 'smooth', |
| 38 | + }); |
| 39 | + } |
| 40 | + |
| 41 | + createForm() { |
| 42 | + this.promptForm = this.formBuilder.group({ |
| 43 | + prompt: [ '', CustomValidators.requiredMarkdown ], |
| 44 | + }); |
| 45 | + } |
| 46 | + |
| 47 | + goBack() { |
| 48 | + this.router.navigate([ '/' ], { relativeTo: this.route }); |
| 49 | + } |
| 50 | + |
| 51 | + onSubmit() { |
| 52 | + if (!this.promptForm.valid) { |
| 53 | + showFormErrors(this.promptForm.controls); |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + this.submitPrompt(); |
| 58 | + } |
| 59 | + |
| 60 | + submitPrompt() { |
| 61 | + const content = this.promptForm.get('prompt').value; |
| 62 | + this.messages.push({ role: 'user', content }); |
| 63 | + |
| 64 | + this.chatService.getPrompt(content).subscribe( |
| 65 | + (completion: any) => { |
| 66 | + this.conversations.push({ |
| 67 | + query: content, |
| 68 | + response: completion?.chat, |
| 69 | + }); |
| 70 | + this.spinnerOn = false; |
| 71 | + this.changeDetectorRef.detectChanges(); |
| 72 | + this.scrollToBottom(); |
| 73 | + this.spinnerOn = true; |
| 74 | + }, |
| 75 | + (error: any) => { |
| 76 | + console.log(error); |
| 77 | + this.conversations.push({ |
| 78 | + query: content, |
| 79 | + response: 'Error: ' + error.message, |
| 80 | + error: true, |
| 81 | + }); |
| 82 | + } |
| 83 | + ); |
| 84 | + } |
| 85 | +} |
0 commit comments