All files / chatbot-root chatbot-root.component.ts

80.76% Statements 21/26
64.28% Branches 9/14
100% Functions 6/6
80.76% Lines 21/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                      1x 6x   6x   6x   6x   6x 6x 6x                   6x         1x 1x       2x 2x 1x 1x 1x 1x         1x 1x         1x 1x        
import { ChangeDetectionStrategy, Component, computed, HostListener, inject, signal } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { AppElizaService, IChatMessage } from '@app/client-util-eliza';
 
@Component({
  selector: 'app-chatbot-root',
  templateUrl: './chatbot-root.component.html',
  styleUrls: ['./chatbot-root.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: false,
})
export class AppChatbotRootComponent {
  private readonly fb = inject(FormBuilder);
 
  private readonly eliza = inject(AppElizaService);
 
  public readonly messages$ = this.eliza.messages$;
 
  private readonly nextUserMessage$ = signal<IChatMessage | null>(null);
 
  public readonly respond$ = computed(async () => {
    const message = this.nextUserMessage$();
    Iif (message !== null && !message.bot) {
      const text = message.text;
      const response = await this.eliza.getResponse(text);
      this.botResponse(response.reply);
      if (response.final) {
        this.form.disable();
      }
    }
  });
 
  public readonly form = this.fb.group({
    message: [''],
  });
 
  public resetBot() {
    this.eliza.reset();
    this.form.enable();
  }
 
  public userMessage() {
    const text = this.form.controls.message.value;
    if (text !== null && text !== '') {
      const message: IChatMessage = { bot: false, text };
      this.nextUserMessage$.set(message);
      this.eliza.nextMessage(message);
      this.form.reset();
    }
  }
 
  public botResponse(text: string) {
    const message: IChatMessage = { bot: true, text };
    this.eliza.nextMessage(message);
  }
 
  @HostListener('window:keyup', ['$event'])
  public keyUp(event: KeyboardEvent) {
    Eif (event.ctrlKey && event.key === 'Enter') {
      this.userMessage();
    }
  }
}