Anupriya commited on
Commit ·
59fecf2
1
Parent(s): 16002bb
Added Chat stop method and image
Browse filesFiles changed (6)
1123457867895 unmodified lines1516172018192021222523242528293026272829303113 unmodified lines454647505152484950565758515253605455567 unmodified lines64656674757677787980676883697071727374897576779278798081978283841008586878889105106107108109909111211311411511692939495969711912098991001011021241251261271281031041311321331341351361371051061071081091101111121391131141151162 unmodified lines11912012114812215015115215315415512312412512612712812913013113216013316216316416516613413513613713813914016917017117214117417514214314414514617914714814915015115218615315418915515615715819315916016116216319819916420116516616716816917020717117217317418 unmodified lines1931941952321961971981992362002012022032402412042052062072082092462102112122132 unmodified lines2162172182552562192202212221 unmodified line2242252262642652662672272282293 unmodified lines2332342352772782362372382392402412422432852442452462882472482492912502932512522532962542552562573002582592606 unmodified lines2672682693132703152712722733183192742752762772782793242802813273282822832842852862873332882892902913382922932942953423432962972982993001 unmodified line3023033043513053063543073083093103583113603123133143153163653173183193203693213223236 unmodified lines3303313323823833333343863353363373383393403413933943953963423433443453463473483494013503513524044054063533543553563573584133593603613623633643654203663673683 unmodified lines37237337443037537637737837943638038138238338444238538638725 unmodified lines4134144154744164174183 unmodified lines4224234244844254264276 unmodified lines4344354364974374384396 unmodified lines4464474485104494504516 unmodified lines4584594605235245255265274614625305314634644655334664675355364684694705385395404714724734744755434764775464784794804814824835524844854864875564885585594894904914925624934944955665674964974984995002 unmodified lines5035045055765775785795065075085095845105115125875135145154 unmodified lines5205215225985235245258 unmodified lines5345355366136145375385396 unmodified lines5465475486275495505512 unmodified lines5545555566366375575585595605616435625635645655665676495685695705 unmodified lines576577578661662579580581582583668584585670586587588589590675591592678593594595596597598684599600601687602603690691604605606607608609696610611612/* Header Container Styling */.header-container { display: flex; justify-content: space-between; align-items: center; padding: 0vw 1vw; background-color: #03182d; /* background-color: #c19929;*/ background-color: #03182d; box-shadow: 0 0.4vw 0.8vw rgba(0, 0, 0, 0.2); width: 100%; position: sticky;5 unmodified lines max-width: 5vw; height: auto; background: #e5e7eb; border-radius: 1vw; border-radius: 50%; margin: 0.5vw;}
.home-btn img { width: 5vw; /* Adjust the size of the home icon */ width: 5vw;}
.home-btn img:hover { transform: scale(1.1); /* Slight zoom-in effect on hover */} .home-btn img:hover { transform: scale(1.1); }
h1 { font-size: 3vw;13 unmodified lines font-display: swap;}
/* Full-Screen Chat Container */.chat-container { display: flex; flex-direction: column; height: 100vh; /* Full viewport height */ width: 100%; /* Full viewport width */ /*background: linear-gradient(to bottom right, #fefefe, #f3f4f6);*/ /* Soft white-gray gradient */ height: 100vh; width: 100%; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.chat-bg {7 unmodified lines opacity: 0.2;}
/*.chat-box { position: relative;}*/
/* Chat Header */.chat-header { text-align: center; background: linear-gradient(to right, #4ca1af, #6ac5cb); /* Modern purple-pink gradient */ background: linear-gradient(to right, #4ca1af, #6ac5cb); color: white; padding: 0px 0; font-size: 2.2rem; font-weight: bold; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); flex-shrink: 0; /* Prevent shrinking */ flex-shrink: 0;}
.chat-box { display: flex; flex-direction: column; overflow-y: auto; height: calc(100vh - 180px); /* Adjust height as needed */ height: calc(100vh - 180px); padding: 2vw; background-color: rgba(35, 34, 32, 0.43); scroll-behavior: smooth; /* Smooth scrolling */ scroll-behavior: smooth; flex-grow: 1; padding-bottom: 90px;}
.input-box { display: flex; gap: 10px; /* Reduce gap between elements */ padding: 8px; /* Reduce padding */ background: #03182d; /* Blue background */ /*background: #c19929;*/ /* Blue background */ box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); /* Lighter shadow for a subtle effect */ gap: 10px; padding: 8px; background: #03182d; box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); flex-shrink: 0; width: 100%; height: auto; /* Adjust height dynamically */ min-height: 40px; /* Ensure it doesn't shrink too much */ height: auto; min-height: 40px; font-weight: bold;}
.input-box textarea { flex: 1; height: auto; /* Automatically adjust height */ max-height: 80px; /* Limit the maximum height */ overflow-y: auto; /* Allow scrolling if needed */ resize: none; /* Disable manual resizing */ padding: 8px; /* Adjust padding for proper alignment */ font-size: 1rem; /* Font size for input text */ line-height: 1.2; /* Adjust line height for vertical centering */ height: auto; max-height: 80px; overflow-y: auto; resize: none; padding: 8px; font-size: 1rem; line-height: 1.2; border: 1px solid rgb(93, 145, 195); border-radius: 8px; /* Smaller border radius */ border-radius: 8px; background: rgba(255, 255, 255, 0.04); color: white; outline: none;2 unmodified lines box-sizing: border-box; }
.input-box textarea:focus { border-color: rgb(135, 185, 235); /* Lighter shade of original color */ box-shadow: 0 0 5px rgba(93, 145, 195, 0.6); /* Soft glow effect */ text-align: left; /* Align text to the left */ vertical-align: middle; /* This helps maintain proper alignment */ line-height: normal; /* Ensures proper vertical centering */ font-size: 1rem; /* Adjust font size if needed */ border-color: rgb(135, 185, 235); box-shadow: 0 0 5px rgba(93, 145, 195, 0.6); text-align: left; vertical-align: middle; line-height: normal; font-size: 1rem; color: white; font-weight: bold; }
.input-box textarea::placeholder { text-align: left; /* Align text to the left */ vertical-align: middle; /* This helps maintain proper alignment */ line-height: normal; /* Ensures proper vertical centering */ font-size: 1rem; /* Adjust font size if needed */ color: rgba(255, 255, 255, 0.5); /* Subtle color for placeholder */ text-align: left; vertical-align: middle; line-height: normal; font-size: 1rem; color: rgba(255, 255, 255, 0.5); }
.input-box button { width: 55px; /* Fixed button size */ height: 55px; /* Fixed button size */ width: 55px; height: 55px; display: flex; align-items: center; justify-content: center; /*background: #a855f7;*/ background: #5d91c3; border: none; border-radius: 8px; cursor: pointer; }
.input-box button:hover { transform: scale(1.05); box-shadow: 0px 4px 10px rgba(14, 165, 233, 0.4); /* Subtle hover effect */ box-shadow: 0px 4px 10px rgba(14, 165, 233, 0.4); }
.button-icon { width: 34px; /* Default size for all icons */ width: 34px; height: 34px; object-fit: contain;}
.resume-icon { width: 40px; /* Slightly larger for balance */ width: 40px; height: 40px; object-fit: contain;}
.pause-icon { width: 31px; /* Custom size for pause icon */ width: 31px; height: 31px; object-fit: contain;}18 unmodified lines }
.suggestion-box li { padding: 8px 12px; /* Spacing inside each suggestion */ padding: 8px 12px; cursor: pointer; font-size: 1rem; transition: background-color 0.3s ease; color: rgb(67 65 65); /* Text color */ color: rgb(67 65 65); }
.suggestion-box li:hover { background-color: rgba(0, 0, 0, 0.1); /* Subtle hover effect */ border-radius: 4px; /* Rounded corners for hover */ background-color: rgba(0, 0, 0, 0.1); border-radius: 4px; }
.input-container { display: flex; flex-direction: column-reverse; /* Reverse order to place suggestions above input */ flex-direction: column-reverse; position: relative; width: 100%;}2 unmodified lines display: flex; gap: 10px; padding: 8px; background: #03182d; /* Background color of the input box */ /*background: #c19929;*/ /* Background color of the input box */ background: #03182d; box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); flex-shrink: 0; width: 100%;1 unmodified line min-height: 40px;}
/* Glass Transparent Listening Indicator (Fully Centered) */.listening-box { position: fixed; top: 50%;3 unmodified lines padding: 45px; border-radius: 20px; width: 30vw; height: auto; /* Adjust height dynamically */ min-height: 40vh; /* Ensure height remains balanced */ height: auto; min-height: 40vh; box-shadow: 0px 8px 20px rgba(0, 0, 0, 0.15); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); animation: fadeInScale 0.3s ease-in-out; display: flex; flex-direction: column; align-items: center; /* Ensure all elements stay centered */ align-items: center; justify-content: center; border: 1px solid rgba(255, 255, 255, 0.2); text-align: center; /* Center text alignment */ text-align: center;}
/* Microphone Image (Centered Properly) */.microphone-image { width: 100px; /* Slightly bigger */ width: 100px; height: 100px; display: block; margin: 0 auto 20px; /* Ensures it's centered with space below */ margin: 0 auto 20px; animation: pulse 1.5s infinite alternate ease-in-out;}
/* Pulse Effect */@keyframes pulse { from { transform: scale(1);6 unmodified lines }}
/* Listening Text (Fully Centered) */.listening-box p { font-size: 15px; /* Increased size */ font-size: 15px; color: black; font-weight: bold; text-align: center; /* Ensure it's aligned centrally */ margin: 10px 0; /* Adjusted margin */ text-align: center; margin: 10px 0; text-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3); margin-top: 3vw;}
/* Mute & Close Buttons (Evenly Spaced & Centered) */.listening-actions { display: flex; justify-content: center; /* Ensure icons are centered */ gap: 70px; /* More space between icons */ justify-content: center; gap: 70px; margin-top: 65px; width: 100%;}
/* Button Icons (Increased Size) */.mute-btn,.close-btn { background: rgba(255, 255, 255, 0.3); border: none; padding: 15px; /* Increased padding for larger buttons */ padding: 15px; border-radius: 50%; cursor: pointer; transition: transform 0.2s ease-in-out, background 0.3s; width: 75px; /* Increased button width */ height: 75px; /* Increased button height */ width: 75px; height: 75px; display: flex; align-items: center; justify-content: center;1 unmodified line -webkit-backdrop-filter: blur(12px);}
/* Mute and Close Icon Styles (Proper Scaling) */ .mute-btn img, .close-btn img { width: 50px; /* Bigger icons */ width: 50px; height: 50px; }
/* Hover Effects */ .mute-btn:hover { background: rgba(255, 0, 0, 0.5); /* Red for mute */ background: rgba(255, 0, 0, 0.5); transform: scale(1.15); }
.close-btn:hover { background: rgba(0, 0, 0, 0.5); /* Dark for close */ background: rgba(0, 0, 0, 0.5); transform: scale(1.15); }
/* Fade-in with Scale Animation */@keyframes fadeInScale { from { opacity: 0;6 unmodified lines }}
.error-text { color: black; background: #ffccccad; /* Light red */ background: #ffccccad; font-size: 2vw; font-weight: bold; text-align: center; padding: 8px 12px; border-radius: 5px; cursor: pointer; width: auto; /* Auto width based on text */ margin-top: 10px; /* Space below buttons */ display: inline-block; /* Single line */ white-space: nowrap; /* Prevent text wrapping */ width: auto; margin-top: 10px; display: inline-block; white-space: nowrap; transition: background 0.3s;}
.error-text:hover { background: #ffaaaa; /* Slightly darker red on hover */ background: #ffaaaa; }
/* Popup Overlay */.popup-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); /* Dark transparent background */ background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; z-index: 1000;}
/* Popup Box */.popup-box { background: white; padding: 20px;3 unmodified lines box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);}
/* Popup Title */ .popup-box h3 { font-size: 18px; margin-bottom: 10px; }
/* Popup Text */ .popup-box p { font-size: 14px; color: #555; }
/* Popup Button */.popup-button { background: #007bff; color: white;25 unmodified lines animation: fadeIn 0.3s ease-in-out;}
/* Typing dots animation */ .typing-indicator span { width: 10px; height: 10px;3 unmodified lines animation: typingDots 1.5s infinite ease-in-out; }
/* Add animation delays for each dot */ .typing-indicator span:nth-child(1) { animation-delay: 0s; }6 unmodified lines animation-delay: 0.4s; }
/* Keyframes for the typing dots */@keyframes typingDots { 0%, 100% { transform: scale(0.8);6 unmodified lines }}
/* Smooth fade-in effect */@keyframes fadeIn { from { opacity: 0;6 unmodified lines }}
/* Container for hardcoded questions - Aligned left above the text field */.hardcoded-questions-container { display: flex; justify-content: flex-start; /* Align to the left */ gap: 15px; /* Space between tabs */ justify-content: flex-start; gap: 15px; padding: 10px; background: rgba(255, 255, 255, 0.1); /* Subtle background */ background: rgba(255, 255, 255, 0.1); border-radius: 8px; margin-bottom: 5px; /* Space between questions and input box */ flex-wrap: wrap; /* Allow wrapping on smaller screens */ margin-bottom: 5px; flex-wrap: wrap; position: absolute; bottom: 60px; /* Adjust based on text field height */ left: 10px; /* Align to the left side */ width: auto; /* Adjust width dynamically */ bottom: 60px; left: 10px; width: auto;}
/* Individual question tab */.hardcoded-question { padding: 10px 15px; background: rgba(200, 200, 200, 0.3); /* Light grey faded color */ background: rgba(200, 200, 200, 0.3); border-radius: 5px; font-size: 14px; font-weight: bold; cursor: pointer; transition: background 0.3s ease, transform 0.2s ease; white-space: nowrap; /* Prevent wrapping */ white-space: nowrap; border: 1px solid rgba(0, 0, 0, 0.2);}
/* Hover effect */ .hardcoded-question:hover { background: rgba(180, 180, 180, 0.5); /* Slightly darker grey on hover */ transform: scale(1.05); /* Subtle pop effect */ background: rgba(180, 180, 180, 0.5); transform: scale(1.05); }
/* Ensure responsiveness */@media (max-width: 600px) { .hardcoded-questions-container { width: 90%; bottom: 80px; /* Adjust spacing for smaller screens */ left: 10px; /* Keep it left aligned */ bottom: 80px; left: 10px; }
.hardcoded-question {2 unmodified lines }}
/* Message wrapper for each chat bubble */.message-wrapper { display: flex; align-items: flex-start; gap: 1vw; margin-bottom: 1vw; /* Space between each message */ margin-bottom: 1vw;}
/* Separate AI and user styles */ .message-wrapper.user { flex-direction: row-reverse; text-align: right;4 unmodified lines text-align: left; }
/* Profile Picture Styling */.profile-pic { width: 4vw; height: 4vw;8 unmodified lines object-fit: cover; }
/* Separate paragraph blocks */.ai .message { align-self: flex-start; background: #2b6296;6 unmodified lines color: white;}
/* Timestamp Styling */.message-timestamp { font-size: 0.8vw; color: rgba(255, 255, 255, 0.8);2 unmodified lines text-align: right;}
.paragraph-block { background: #2b6296; color: white; padding: 1vw; border-radius: 1vw; margin-bottom: 0.5vw; /* ✅ Adjusted for better spacing */ margin-bottom: 0.5vw; box-shadow: 0 0.3vw 0.8vw rgba(0, 0, 0, 0.1); line-height: 1.5; max-width: 48vw;}
/* Normal messages remain in a single block */.message { max-width: 50vw; padding: 1vw 2vw;5 unmodified lines color: white;}
.structured-response { background: #2b6296; color: white; padding: 1vw; border-radius: 1vw; margin-bottom: 0.3vw; /* ✅ Reduced spacing */ margin-bottom: 0.3vw; box-shadow: 0 0.3vw 0.8vw rgba(0, 0, 0, 0.1); line-height: 1.4; /* ✅ Adjusted line height */ line-height: 1.4; max-width: 48vw; word-break: break-word;}
/* ✅ Reduce space between numbered and bulleted list items */ .structured-response b { display: inline-block; margin-top: 0.3vw; /* ✅ Reduced margin for numbers */ margin-top: 0.3vw; }
.structured-response br { display: block; content: ""; margin: 0.2vw 0; /* ✅ Reduce line spacing */ margin: 0.2vw 0; }
/* ✅ Ensure numbered and bulleted lists have proper spacing */ .structured-response ul, .structured-response ol { padding-left: 1.2vw; /* ✅ Slightly reduced indentation */ margin-bottom: 0; /* ✅ Remove extra bottom margin */ padding-left: 1.2vw; margin-bottom: 0; }
.structured-response ul li, .structured-response ol li { margin-bottom: 0.2vw; /* ✅ Reduced space between list items */ margin-bottom: 0.2vw; line-height: 1.4; }1231523458 unmodified lines141516202122232417182627281920303121322223243 unmodified lines28293042433132333 unmodified lines373839535455564041424344454662636465666768474870495051521 unmodified line5455567879808182835758596061626364656687886768691 unmodified line7172739674759899767778791038081822 unmodified lines858687112113881141158990911199293942 unmodified lines979899128
<div class="chat-container"> <div class="header-container"> <header class="header-container"> <div class="logo"> <a (click)="goToHome()" routerLink="/home" class="brand-link"> <img src="assets/images/pykara-logo.png" alt="Pykara Logo" />8 unmodified lines <img src="assets/images/home.png" alt="Home" class="home-icon" /> </a> </div> </div>
</header>
<div class="chat-box" #chatBox> <main class="chat-box" #chatBox> <img src="assets/images/chat/chatbg.png" alt="Chat Background" class="chat-bg" />
<div *ngFor="let message of messages"> <ng-container *ngFor="let message of messages"> <!-- User Messages --> <div *ngIf="message.from === 'user'" class="message-wrapper user"> <div class="profile-pic"> <img src="assets/images/chat/rabbit.png" alt="User Profile Picture" />3 unmodified lines <div class="message-timestamp">{{ message.timestamp }}</div> </div> </div>
<!-- AI Messages --> <div *ngIf="message.from === 'ai'" class="message-wrapper ai"> <div class="profile-pic"> <img src="assets/images/chat/lion.png" alt="AI Profile Picture" />3 unmodified lines <div class="message-timestamp">{{ message.timestamp }}</div> </div> </div> </div>
<!-- AI typing indicator --> <div *ngIf="isTyping" class="typing-indicator"> </ng-container> <div *ngIf="isTyping" class="typing-indicator" role="status" aria-live="polite"> AI is typing <span></span> <span></span> <span></span> </div> </div>
</main>
<div class="input-container"> <section class="input-container"> <div class="input-box"> <textarea [(ngModel)]="userInput" (focus)="showHardcodedQuestions()"1 unmodified line (input)="adjustTextareaHeight($event); getSuggestions()" (keydown)="handleEnterPress($event)" placeholder="Type your message here..." [disabled]="isSpeaking"> </textarea>
<button (click)="isSpeaking ? (isAudioPaused ? resumeAudio() : pauseAudio()) : handleButtonClick()"> <img [src]="isSpeaking ? (isAudioPaused ? 'assets/images/chat/resume-icon.png' : 'assets/images/chat/pause-icon.png') : getButtonIcon()" alt="Button Icon" [disabled]="isSpeaking" aria-label="Message input"></textarea> <button (click)="isSpeaking ? stopSpeaking() : handleButtonClick()" [disabled]="isSubmitting" aria-label="Send or voice"> <img [src]="isSpeaking ? 'assets/images/chat/stop.png' : getButtonIcon()" alt="Action" class="button-icon" /> </button> </div>
<!-- Hardcoded questions (Shown only when focused) --> <div class="hardcoded-questions-container" *ngIf="showQuestions"> <div class="hardcoded-question" (click)="selectHardcodedQuestion('What is grammar?')">What is grammar?</div> <div class="hardcoded-question" (click)="selectHardcodedQuestion('What are the rules to be followed in grammar?')">What are the rules to be followed in grammar?</div>1 unmodified line <div class="hardcoded-question" (click)="selectHardcodedQuestion('Why do we need to follow grammar rules while writing and speaking?')">Why do we need to follow grammar rules while writing and speaking?</div> <div class="hardcoded-question" (click)="selectHardcodedQuestion('How do you identify a subject and a predicate in a sentence?')">How do you identify a subject and a predicate in a sentence?</div> </div> </div> </section>
<!-- Listening Box --> <div class="listening-box" *ngIf="isListening"> <div class="listening-box" *ngIf="isListening" role="dialog" aria-modal="true"> <div class="listening-content"> <img src="assets/images/chat/microphone-icon.png" alt="Microphone" class="microphone-image" /> <p *ngIf="!errorMessage">Listening...</p>
<div class="listening-actions"> <button class="mute-btn" (click)="muteMicrophone()"> <img src="assets/images/chat/mic.png" alt="Mute" />2 unmodified lines <img src="assets/images/chat/cross.png" alt="Close" /> </button> </div>
<p *ngIf="errorMessage" class="error-text" (click)="openMicrophoneSettings()"> <p *ngIf="errorMessage" class="error-text" (click)="openMicrophoneSettings()">{{ errorMessage }}</p> {{ errorMessage }} </p> </div> </div>
<!-- Microphone Access Popup --> <div class="popup-overlay" *ngIf="showMicPopup"> <div class="popup-box"> <h3>Microphone access required</h3>2 unmodified lines </div> </div></div>
12323456789101191011123 unmodified lines161718211920212422232427252627302829303334353631323334383536403738394041434243464445464947484950515256575354555657585960616263626465666 unmodified lines737475757677787976777881798081828384878586878889929091959293989495969798991051001011021031041111051061076 unmodified lines1141151161241251261271281291301171181191341201211221371231241251411261271281441291461471301311321491501511331341351361371541551381391581401411421432 unmodified lines1461471481671681491501511521535 unmodified lines1591601611801811821831621631861871641651661671901911921681691702 unmodified lines1731741752011762031771781792061801812081821831842111851861871881891901912171921931941951961971981992002012022032192202212042052062072082272282292302092102112122132142152162172182192202212222232242362372382392402412422252262452462472482492502272282292302312322332342542552562572582592602612622632642352362372 unmodified lines2402412422732432442452772462472482812492502512852522532872542552562912572582592952962602612622632992642653022662672683 unmodified lines2722732743122752763152772783172792802812823212832842853252862872882893292902912922933343353363373383393403413423433443453462942952961 unmodified line2982993003543013023033583593043053063073083653093103113123693133143713153163173753183193203213223233813243253262 unmodified lines3293303313903323333341 unmodified line3363373383983994003393403413423434063443453463472 unmodified lines3503513524153533543553564194204213573584243593604274284293614314323623633643653663 unmodified lines37037137244237337437537637744837837938038138245438338445738538646038738838946339046539139239339419 unmodified lines4144154164914174184194202 unmodified lines4234244255004264275024284294304315065074324334345114354364375154384394404415204424434445244454465264474484494504514525334534544554564575394584594604615445454624634644655504664674684695544704715564724734744754764774785635645655664794804814825715724834845755765775784854864874884894904913 unmodified lines49549649758858949849959250050159450250359650450559850650750850960260351051160660751251351451551661151751861461561661761861962062162262362462562662762862963063163263351952052152263663763863952352452552652752864652953053153211 unmodified lines544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578import { Component, Inject, OnDestroy, PLATFORM_ID, ChangeDetectorRef } from '@angular/core';import { ApiService } from './api.service'; // Import ApiServiceimport { FormsModule } from '@angular/forms'; // Import FormsModule for two-way bindingimport { ApiService } from './api.service';import { FormsModule } from '@angular/forms';import { CommonModule } from '@angular/common';import { Router, RouterModule } from '@angular/router';import { isPlatformBrowser } from '@angular/common';import { ViewChild, ElementRef } from '@angular/core';import { Renderer2 } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({ selector: 'app-chat',3 unmodified lines styleUrl: './chat.component.css'})export class ChatComponent implements OnDestroy { showQuestions: boolean = false; // Flag to show hardcoded questions showQuestions: boolean = false; userInput: string = ''; messages: { from: string, text: string, timestamp: string; isPlaying?: boolean }[] = []; isTyping: boolean = false; // Typing indicator isTyping: boolean = false; @ViewChild('chatBox') chatBox!: ElementRef;
isLoadingSpeech: boolean = false; // ✅ Add this line to fix the error isLoadingSpeech: boolean = false; selectedVoice: SpeechSynthesisVoice | null = null; errorMessage: string = ""; recognition: any; // SpeechRecognition object recognition: any; speechSynthesisInstance: SpeechSynthesisUtterance | null = null; isListening: boolean = false; isProcessingSpeech: boolean = false; // Flag to prevent duplicate processing // isVoiceInput: boolean = false; // Indicates if the input is from voice isSpeaking: boolean = false; // Track if text-to-speech is ongoing isAudioPaused: boolean = false; // Indicates if the audio is paused isProcessingSpeech: boolean = false; isSpeaking: boolean = false; isAudioPaused: boolean = false; isInputValid: boolean = false; suggestions: string[] = []; // Holds suggested grammar questions suggestions: string[] = []; showMicPopup: boolean = false;
isSubmitting: boolean = false; private responseSub?: Subscription; private lastFullAiText: string = '';
ngAfterViewChecked() { // Adding a delay for smooth scrolling setTimeout(() => { this.scrollToBottom(); }, 100); // Adjust the timeout if necessary }, 100); }
// Function to scroll to the bottom of the chat private scrollToBottom(): void { try { this.chatBox.nativeElement.scrollTop = this.chatBox.nativeElement.scrollHeight; } catch (err) { } }
constructor(private apiService: ApiService, private cdr: ChangeDetectorRef, @Inject(PLATFORM_ID,) private platformId: object, private router: Router, private renderer: Renderer2) {
constructor( private apiService: ApiService, private cdr: ChangeDetectorRef, @Inject(PLATFORM_ID,) private platformId: object, private router: Router, private renderer: Renderer2 ) { window.speechSynthesis.onvoiceschanged = () => { console.log("Available Voices:", window.speechSynthesis.getVoices()); };
// Initialize SpeechRecognition if supported if (isPlatformBrowser(this.platformId)) { const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition; if (SpeechRecognition) {6 unmodified lines if (event.results && event.results[0]) { const transcript = event.results[0][0].transcript.trim(); console.log('Recognized speech:', transcript);
this.userInput = transcript; // Set the recognized speech as input this.sendMessage(); // Automatically send the message after recognition
// Stop recognition to prevent multiple triggers this.userInput = transcript; this.sendMessage(); this.recognition.stop(); this.isListening = false; // Hide the overlay this.isListening = false; } };
this.recognition.onerror = (event: any) => { console.error('Speech Recognition Error:', event.error); this.isProcessingSpeech = false; // Reset the flag on error this.isProcessingSpeech = false; }; } else { console.warn('Speech Recognition is not supported in this browser.'); } // Add beforeunload listener to stop audio on page refresh or unload window.addEventListener('beforeunload', this.handleUnload); }
}
// Handle page unload to stop audio private handleUnload = (): void => { if (window.speechSynthesis) { window.speechSynthesis.cancel(); } };
// Lifecycle hook to clean up resources ngOnDestroy(): void { if (isPlatformBrowser(this.platformId)) { if (window.speechSynthesis) { window.speechSynthesis.cancel(); } // Remove the unload event listener window.removeEventListener('beforeunload', this.handleUnload); } }6 unmodified lines this.showMicPopup = false; }
// Show hardcoded questions when user focuses on input showHardcodedQuestions(): void { setTimeout(() => { this.showQuestions = true; }, 100); // Small delay to prevent blur from closing it immediately }, 100); }
// Hide hardcoded questions when user clicks outside hideHardcodedQuestions(): void { setTimeout(() => { this.showQuestions = false; }, 200); // Allow time for click event to register }, 200); }
selectHardcodedQuestion(question: string): void { this.userInput = question; // Set the selected question this.showQuestions = false; // Hide the hardcoded questions this.userInput = question; this.showQuestions = false; setTimeout(() => { this.sendMessage(); // Send the selected question this.userInput = ''; // Clear the text field after sending }, 100); // Small delay to ensure UI updates before clearing this.sendMessage(); this.userInput = ''; }, 100); }
getSuggestions(): void { if (!this.userInput || this.userInput.trim().length < 1 || this.isSpeaking) { this.suggestions = []; // Clear suggestions if no input or AI is speaking this.suggestions = []; return; }
2 unmodified lines console.log("API Response:", response); if (response.suggestions) { this.suggestions = response.suggestions .filter((s: string) => s && s.trim().length > 0) // Remove empty suggestions .map((s: string) => s.replace(/^\d+\.\s*/, "")); // Remove numbering .filter((s: string) => s && s.trim().length > 0) .map((s: string) => s.replace(/^\d+\.\s*/, "")); } else { this.suggestions = []; }5 unmodified lines ); }
// When a user selects a suggestion, send it as a message selectSuggestion(suggestion: string): void { this.userInput = suggestion; this.suggestions = []; // Clear suggestions after selection this.sendMessage(); // Send the selected suggestion this.suggestions = []; this.sendMessage(); }
sendMessage(inputText?: string): void { const message = inputText ? inputText.trim() : this.userInput.trim(); if (!message) {2 unmodified lines
let sessionId = localStorage.getItem('session_id');
// ✅ Add user message to chat this.messages.push({ from: 'user', text: message, timestamp: new Date().toLocaleTimeString() }); this.userInput = ''; // ✅ Clear input field after sending this.userInput = ''; this.isTyping = true; this.cdr.detectChanges(); this.scrollToBottom(); // ✅ Scroll after adding user message this.scrollToBottom();
this.apiService.askQuestion(message, sessionId).subscribe( this.responseSub = this.apiService.askQuestion(message, sessionId).subscribe( (response) => { this.isTyping = false; let explanation = response?.response || 'No explanation available.';
const explanation = (response?.response || 'No explanation available.').trim();
if (response.session_id && !sessionId) { localStorage.setItem('session_id', response.session_id); }
let formattedExplanation = explanation.trim().split('\n').map((para: string) => para.trim()).join('\n'); const lines: string[] = String(explanation).split('\n'); const formatted: string = lines.map((line: string) => line.trim()).join('\n'); this.messages.push({ from: 'ai', text: formatted, timestamp: new Date().toLocaleTimeString(), }); this.cdr.detectChanges(); this.scrollToBottom();
this.lastFullAiText = formatted;
this.messages.push({ from: 'ai', text: formattedExplanation, timestamp: new Date().toLocaleTimeString() }); this.cdr.detectChanges(); this.scrollToBottom(); // ✅ Scroll after AI response this.speakResponse(explanation); }, (error) => { this.isTyping = false; const errorMessage = 'Error: Could not get a response from the server.'; console.error("API Error:", error); this.messages.push({ from: 'ai', text: errorMessage, timestamp: new Date().toLocaleTimeString() }); this.cdr.detectChanges(); this.scrollToBottom(); // ✅ Scroll even if an error occurs console.error('API Error:', error);
this.messages.push({ from: 'ai', text: errorMessage, timestamp: new Date().toLocaleTimeString(), }); this.cdr.detectChanges(); this.scrollToBottom();
this.lastFullAiText = errorMessage; this.speakResponse(errorMessage); } ); }
formatStructuredResponse(text: string): string { let formattedText = text .replace(/\n/g, '<br>') // Preserve line breaks .replace(/(\d+)\.\s/g, '<b>$1.</b> ') // Bold numbered lists .replace(/\•\s/g, '✔️ ') // Replace bullets with custom emojis .replace(/\-\s/g, '🔹 ') // Replace hyphen bullets with emoji .replace(/(\*\*)(.*?)\1/g, '<b>$2</b>'); // Convert "**bold text**" to <b>bold text</b>
.replace(/\n/g, '<br>') .replace(/(\d+)\.\s/g, '<b>$1.</b> ') .replace(/\•\s/g, '✔️ ') .replace(/\-\s/g, '🔹 ') .replace(/(\*\*)(.*?)\1/g, '<b>$2</b>'); return formattedText; }
speakResponse(responseText: string): void { if (!responseText) { console.warn('No response text provided for speech.');2 unmodified lines
console.log('Initiating text-to-speech with response:', responseText);
// Find the last AI message and update it dynamically let lastAiMessage = this.messages.slice().reverse().find((msg) => msg.from === 'ai');
if (!lastAiMessage) { // If no AI message exists, create one lastAiMessage = { from: 'ai', text: '', timestamp: new Date().toLocaleTimeString() }; this.messages.push(lastAiMessage); } else { // Clear existing text before speaking lastAiMessage.text = ''; }
this.cdr.detectChanges(); // Ensure UI updates immediately this.cdr.detectChanges();
// Split response text into words for live updates const words = responseText.split(' '); let currentWordIndex = 0;
// Create SpeechSynthesisUtterance const speech = new SpeechSynthesisUtterance(); speech.text = responseText; speech.lang = 'en-US'; speech.pitch = 1; // Adjust pitch (higher values sound more feminine) speech.rate = 1; // Normal speaking speed speech.pitch = 1; speech.rate = 1; this.isSpeaking = true;
// Fetch available voices const voices = window.speechSynthesis.getVoices();
// ✅ Use Microsoft Zira for a female voice let femaleVoice = voices.find(voice => voice.name === "Microsoft Zira - English (United States)");
if (femaleVoice) {3 unmodified lines console.warn("Microsoft Zira not found, using default."); }
// Update AI response dynamically as words are spoken speech.onboundary = (event) => { if (event.name === 'word' && currentWordIndex < words.length) { lastAiMessage!.text = words.slice(0, currentWordIndex + 1).join(' '); // Update text word by word lastAiMessage!.text = words.slice(0, currentWordIndex + 1).join(' '); currentWordIndex++; this.cdr.detectChanges(); // Update UI dynamically this.cdr.detectChanges(); } };
// When speech ends, keep the full response or leave the last word speech.onend = () => { console.log('Speech ended.'); this.isSpeaking = false; lastAiMessage!.text = responseText; // Show full response after speech ends lastAiMessage!.text = responseText; this.cdr.detectChanges(); };
// Start speaking console.log('Starting speech synthesis...'); window.speechSynthesis.speak(speech); }
ngOnInit(): void { if (window.speechSynthesis.onvoiceschanged !== undefined) { window.speechSynthesis.onvoiceschanged = () => {1 unmodified line }; }
// Load voices immediately in case they are already available this.loadVoices(); }
loadVoices(): void { const voices = window.speechSynthesis.getVoices();
if (!voices.length) { console.warn("No voices available yet, retrying..."); setTimeout(() => this.loadVoices(), 500); // Retry loading voices setTimeout(() => this.loadVoices(), 500); return; }
console.log("Available Voices:", voices.map(v => v.name)); // Debugging console.log("Available Voices:", voices.map(v => v.name));
// ✅ Preferred female voices const preferredVoices = [ "Google UK English Female", "Google US English Female", "Microsoft Zira - English (United States)", // Edge/Windows "Microsoft Zira - English (United States)", "Microsoft Hazel - English (United Kingdom)", "Google en-GB Female", "Google en-US Female" ];
// Try to find a preferred female voice for (let voiceName of preferredVoices) { const foundVoice = voices.find(voice => voice.name === voiceName); if (foundVoice) {2 unmodified lines } }
// If no preferred female voice found, pick any available female voice if (!this.selectedVoice) { this.selectedVoice = voices.find(voice => voice.name.toLowerCase().includes("female")) || voices[0]; }1 unmodified line console.log("Selected AI Voice:", this.selectedVoice?.name); }
pauseAudio(): void { if (window.speechSynthesis.speaking && !window.speechSynthesis.paused) { window.speechSynthesis.pause(); this.isAudioPaused = true; console.log('AI Speech Paused'); this.cdr.detectChanges(); // Update UI this.cdr.detectChanges(); } }
2 unmodified lines window.speechSynthesis.resume(); this.isAudioPaused = false; console.log('AI Speech Resumed'); this.cdr.detectChanges(); // Update UI this.cdr.detectChanges(); } }
muteMicrophone(): void { console.log("Microphone muted"); // Logic to mute the microphone }
// Start listening for voice input startListening(): void { this.isListening = true; // Show the overlay this.isProcessingSpeech = false; // Reset the flag before starting this.isListening = true; this.isProcessingSpeech = false;
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices3 unmodified lines console.log('Starting speech recognition...'); this.recognition.start();
// Debugging events this.recognition.onaudiostart = () => console.log('Audio capturing started.'); this.recognition.onspeechstart = () => console.log('Speech has been detected.'); this.recognition.onspeechend = () => console.log('Speech ended, processing...'); this.recognition.onaudioend = () => console.log('Audio capturing ended.');
// Automatically process recognized speech this.recognition.onresult = (event: any) => { if (event.results && event.results[0]) { const transcript = event.results[0][0].transcript.trim(); console.log('Recognized speech:', transcript);
// Set the recognized speech as input this.userInput = transcript;
// Automatically send the message if (this.userInput.trim()) { console.log('Sending question automatically:', this.userInput); this.sendMessage(); // Call sendMessage to process the question this.sendMessage(); }
// Stop recognition to prevent multiple triggers this.recognition.stop(); this.isListening = false; // Hide the overlay this.isListening = false; } };
19 unmodified lines .catch((error) => { console.error('Microphone access denied:', error); this.errorMessage = 'Please enable microphone access to use this feature.'; this.isListening = true; // Keep the overlay visible this.isListening = true; });
} else {2 unmodified lines }
stopListening(): void { this.isListening = false; // Hide the overlay this.isListening = false; if (this.recognition) { this.recognition.stop(); // Stop speech recognition this.recognition.stop(); } }
// Toggle between play and pause for a specific message toggleAudio(message: { text: string, isPlaying?: boolean }): void { if (this.speechSynthesisInstance && this.speechSynthesisInstance.text === message.text) { if (message.isPlaying) { // Pause the currently playing audio window.speechSynthesis.pause(); message.isPlaying = false; } else { // Resume the paused audio window.speechSynthesis.resume(); message.isPlaying = true; } } else { // Stop any currently playing audio if (this.speechSynthesisInstance) { window.speechSynthesis.cancel(); } this.messages.forEach((msg) => (msg.isPlaying = false)); // Reset all states this.messages.forEach((msg) => (msg.isPlaying = false));
// Start playback for the selected message message.isPlaying = true; this.speechSynthesisInstance = new SpeechSynthesisUtterance(message.text); this.speechSynthesisInstance.lang = 'en-US'; this.speechSynthesisInstance.pitch = 1; this.speechSynthesisInstance.rate = 1;
// When playback ends, reset the state this.speechSynthesisInstance.onend = () => { message.isPlaying = false; this.speechSynthesisInstance = null; };
// Play the audio window.speechSynthesis.speak(this.speechSynthesisInstance); } }
goToHome() { this.router.navigate(['/home']); }
copySuccessIndex: number | null = null; // Track copied message index copySuccessIndex: number | null = null;
copyToClipboard(text: string, index: number): void { navigator.clipboard.writeText(text).then(() => { this.copySuccessIndex = index; // Show tick icon for copied message this.copySuccessIndex = index; setTimeout(() => { this.copySuccessIndex = null; // Hide tick after 2 seconds this.copySuccessIndex = null; }, 2000); }).catch(err => { console.error('Failed to copy: ', err); }); }
// Function to check input validity checkInput() { this.isInputValid = this.userInput.trim().length > 0; }
handleButtonClick(): void { if (this.userInput.trim().length > 0) { this.showQuestions = false; // Hide tabs when user manually enters text const messageToSend = this.userInput; // Store input before clearing this.userInput = ''; // Clear input for UI update this.sendMessage(messageToSend); // Send the stored message this.showQuestions = false; const messageToSend = this.userInput; this.userInput = ''; this.sendMessage(messageToSend); } else if (this.isSpeaking) { this.pauseAudio(); } else if (this.isAudioPaused) {3 unmodified lines } }
getButtonIcon(): string { if (this.userInput.trim().length > 0) { return 'assets/images/chat/send-icon.png'; // Replace with your send icon image return 'assets/images/chat/send-icon.png'; } else if (this.isSpeaking) { return 'assets/images/chat/pause-icon.png'; // Replace with your pause icon image return 'assets/images/chat/pause-icon.png'; } else if (this.isAudioPaused) { return 'assets/images/chat/resume-icon.png'; // Replace with your resume icon image return 'assets/images/chat/resume-icon.png'; } else { return 'assets/images/chat/microphone-icon.png'; // Replace with your microphone icon image return 'assets/images/chat/microphone-icon.png'; } }
addNewLine(event: KeyboardEvent): void { if (event.key === 'Enter' && event.shiftKey) { event.preventDefault(); // Prevent form submission this.userInput += '\n'; // Add a new line to the textarea event.preventDefault(); this.userInput += '\n'; } }
adjustTextareaHeight(event: Event): void { const textarea = event.target as HTMLTextAreaElement; textarea.style.height = 'auto'; // Reset height to calculate new height textarea.style.height = `${textarea.scrollHeight}px`; // Adjust height based on content }
handleEnterPress(event: KeyboardEvent): void { if (this.isSpeaking) { event.preventDefault(); // Prevent typing when AI is speaking return; }
if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); this.handleButtonClick(); } else if (event.key === 'Enter' && event.shiftKey) { event.preventDefault(); this.userInput += '\n'; } textarea.style.height = 'auto'; textarea.style.height = `${textarea.scrollHeight}px`; }
getButtonIconClass(): string { return this.userInput.trim().length > 0 ? 'send-icon' : this.isSpeaking ? 'pause-icon' : this.isAudioPaused ? 'resume-icon' // Class for resume icon ? 'resume-icon' : 'microphone-icon'; }
11 unmodified lines } }
stopSpeaking(): void { try { if (window.speechSynthesis.speaking || window.speechSynthesis.paused) { window.speechSynthesis.cancel(); } } catch { }
(this as any).speechSynthesisInstance = null;
if (this.responseSub && !this.responseSub.closed) { this.responseSub.unsubscribe(); }
this.isSpeaking = false; this.isAudioPaused = false; this.isTyping = false; }
handleEnterPress(event: KeyboardEvent): void { if (this.isSpeaking) { event.preventDefault(); return; } if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); const text = (this.userInput || '').trim(); if (text) this.sendMessage(); } }
}src/app/chat/chat.component.css+96-182
src/app/chat/chat.component.html+18-47
src/app/chat/chat.component.ts+133-222
src/assets/images/chat/control.pngAdded

Large File Pointer Details
- SHA256: 2d37166a1708f4d6e27babc1b9bc408c505e5b79e27a7a81ef0ef29f1680ac65
- Pointer size: 129 Bytes
- Size of remote file: 5.89 kB
src/assets/images/chat/stop-button.pngAdded

Large File Pointer Details
- SHA256: a01d5cf4aa76de7da282c98decad20b19a4fe37076ec9f195e850966cdae8389
- Pointer size: 129 Bytes
- Size of remote file: 4.08 kB
src/assets/images/chat/stop.pngAdded

Large File Pointer Details
- SHA256: 5c10275efe01a0421881c8a70652110158155578243833c1434472f6cbad805f
- Pointer size: 130 Bytes
- Size of remote file: 31.7 kB