Oviya commited on
Commit ·
e4ab6d0
0
Parent(s):
Deploy Angular to HF Space
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .editorconfigAdded+16
- .gitattributesAdded+12
- .gitignoreAdded+42
- .vscode/extensions.jsonAdded+4
- .vscode/launch.jsonAdded+19
- .vscode/tasks.jsonAdded+42
- GrammAI.esprojAdded+10
- GrammAI.esproj.userAdded+8
- README.mdAdded+38
- angular.jsonAdded+110
- canvas-confetti.d.tsAdded+1
- karma.conf.jsAdded+44
- nuget.configAdded+10
- obj/Debug/GrammAI.esproj.CoreCompileInputs.cacheAdded
- obj/Debug/GrammAI.esproj.FileListAbsolute.txtAdded+6
- package-lock.jsonAdded
- package.jsonAdded+48
- src/app/app-routing.module.tsAdded+52
- src/app/app.component.cssAdded+12
- src/app/app.component.htmlAdded+2
- src/app/app.component.spec.tsAdded+35
- src/app/app.component.tsAdded+20
- src/app/app.module.tsAdded+56
- src/app/auth/auth.component.cssAdded+211
- src/app/auth/auth.component.htmlAdded+101
- src/app/auth/auth.component.spec.tsAdded+23
- src/app/auth/auth.component.tsAdded+55
- src/app/auth/auth.guard.spec.tsAdded+17
- src/app/auth/auth.guard.tsAdded+30
- src/app/auth/auth.service.spec.tsAdded+16
- src/app/auth/auth.service.tsAdded+188
- src/app/auth/root-redirect.guard.spec.tsAdded+17
- src/app/auth/root-redirect.guard.tsAdded+29
- src/app/authentication/authentication.component.cssAdded+133
- src/app/authentication/authentication.component.htmlAdded+47
- src/app/authentication/authentication.component.spec.tsAdded+23
- src/app/authentication/authentication.component.tsAdded+47
- src/app/authentication/authentication.guard.spec.tsAdded+17
- src/app/authentication/authentication.guard.tsAdded+24
- src/app/authentication/authentication.service.spec.tsAdded+16
- src/app/authentication/authentication.service.tsAdded+203
- src/app/chat/api.service.spec.tsAdded+16
- src/app/chat/api.service.tsAdded+81
- src/app/chat/chat.component.cssAdded+960
- src/app/chat/chat.component.htmlAdded+127
- src/app/chat/chat.component.spec.tsAdded+23
- src/app/chat/chat.component.tsAdded+667
- src/app/findword/findword.component.cssAdded+1095
- src/app/findword/findword.component.htmlAdded+213
- src/app/findword/findword.component.spec.tsAdded+23
12345678910111213141516# Editor configuration, see https://editorconfig.orgroot = true
[*]charset = utf-8indent_style = spaceindent_size = 2insert_final_newline = truetrim_trailing_whitespace = true
[*.ts]quote_type = single
[*.md]max_line_length = offtrim_trailing_whitespace = false123456789101112*.png filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.gif filter=lfs diff=lfs merge=lfs -text*.svg filter=lfs diff=lfs merge=lfs -text*.ttf filter=lfs diff=lfs merge=lfs -text*.woff filter=lfs diff=lfs merge=lfs -text*.woff2 filter=lfs diff=lfs merge=lfs -text*.eot filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.mp4 filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output/dist/tmp/out-tsc/bazel-out
# Node/node_modulesnpm-debug.logyarn-error.log
# IDEs and editors.idea/.project.classpath.c9/*.launch.settings/*.sublime-workspace
# Visual Studio Code.vscode/*!.vscode/settings.json!.vscode/tasks.json!.vscode/launch.json!.vscode/extensions.json.history/*
# Miscellaneous/.angular/cache.sass-cache//connect.lock/coverage/libpeerconnection.logtestem.log/typings
# System files.DS_StoreThumbs.db1234{ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846 "recommendations": ["angular.ng-template"]}12345678910111213141516171819{ "version": "0.2.0", "configurations": [ { "type": "edge", "request": "launch", "name": "localhost (Edge)", "url": "http://localhost:4200", "webRoot": "${workspaceFolder}" }, { "type": "chrome", "request": "launch", "name": "localhost (Chrome)", "url": "http://localhost:4200", "webRoot": "${workspaceFolder}" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142{ // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558 "version": "2.0.0", "tasks": [ { "type": "npm", "script": "start", "isBackground": true, "problemMatcher": { "owner": "typescript", "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": { "regexp": "(.*?)" }, "endsPattern": { "regexp": "bundle generation complete" } } } }, { "type": "npm", "script": "test", "isBackground": true, "problemMatcher": { "owner": "typescript", "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": { "regexp": "(.*?)" }, "endsPattern": { "regexp": "bundle generation complete" } } } } ]}12345678910<Project Sdk="Microsoft.VisualStudio.JavaScript.Sdk/0.5.128-alpha"> <PropertyGroup> <StartupCommand>npm start</StartupCommand> <JavaScriptTestFramework>Jasmine</JavaScriptTestFramework> <!-- Allows the build (or compile) script located on package.json to run on Build --> <ShouldRunBuildScript>false</ShouldRunBuildScript> <!-- Folder where production build objects will be placed --> <PublishAssetsDirectory>$(MSBuildProjectDirectory)\dist\GrammAI\</PublishAssetsDirectory> </PropertyGroup></Project>12345678<?xml version="1.0" encoding="utf-8"?><Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DebuggerFlavor>LaunchJsonDebugger</DebuggerFlavor> <LaunchJsonTarget> </LaunchJsonTarget> </PropertyGroup></Project>1234567891011121314151617181920212223242526272829303132333435363738
---title: py-learn (Angular 17)sdk: staticapp_build_command: npm ci && npm run build -- --configuration=productionapp_file: dist/gramm-ai/browser/index.htmlemoji: 🅰️---
# GrammAI
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 17.1.2.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "GrammAI": { "projectType": "application", "schematics": { "@schematics/angular:component": { "standalone": false }, "@schematics/angular:directive": { "standalone": false }, "@schematics/angular:pipe": { "standalone": false } }, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "outputPath": "dist/gramm-ai", "index": "src/index.html", "browser": "src/main.ts", "polyfills": [ "zone.js" ], "tsConfig": "tsconfig.app.json", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "node_modules/@fortawesome/fontawesome-free/css/all.min.css", "src/styles.css" ], "scripts": [] }, "configurations": { "production": { "budgets": [ { "type": "initial", "maximumWarning": "900kb", "maximumError": "2mb" }, { "type": "anyComponentStyle", "maximumWarning": "16kb", "maximumError": "32kb" } ], "outputHashing": "all" }, "development": { "optimization": false, "extractLicenses": false, "sourceMap": true } }, "defaultConfiguration": "production" }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "configurations": { "production": { "buildTarget": "GrammAI:build:production" }, "development": { "buildTarget": "GrammAI:build:development" } }, "defaultConfiguration": "development" }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "buildTarget": "GrammAI:build" } }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "polyfills": [ "zone.js", "zone.js/testing" ], "tsConfig": "tsconfig.spec.json", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.css" ], "scripts": [], "karmaConfig": "karma.conf.js" } } } } }, "cli": { "analytics": false }}1declare module 'canvas-confetti';1234567891011121314151617181920212223242526272829303132333435363738394041424344module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage'), require('@angular-devkit/build-angular/plugins/karma') ], client: { jasmine: { // you can add configuration options for Jasmine here // the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html // for example, you can disable the random execution with `random: false` // or set a specific seed with `seed: 4321` }, clearContext: false // leave Jasmine Spec Runner output visible in browser }, jasmineHtmlReporter: { suppressAll: true // removes the duplicated traces }, coverageReporter: { dir: require('path').join(__dirname, './coverage/'), subdir: '.', reporters: [ { type: 'html' }, { type: 'text-summary' } ] }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, restartOnFileChange: true, listenAddress: 'localhost', hostname: 'localhost' });};
12345678910<?xml version="1.0" encoding="utf-8"?><configuration> <packageSources> <clear /> <add key="nuget.org" value="https://api.nuget.org/v3/index.json" /> </packageSources> <disabledPackageSources> <clear /> </disabledPackageSources></configuration>123456C:\Users\Admin\Desktop\GrammAI\GrammAI\obj\Debug\GrammAI.esproj.CoreCompileInputs.cacheC:\Users\Admin\Desktop\LE_AI\frontend\GrammAI\GrammAI\obj\Debug\GrammAI.esproj.CoreCompileInputs.cacheC:\Users\Admin\Desktop\LE_AI\New folder\frontend\GrammAI\GrammAI\obj\Debug\GrammAI.esproj.CoreCompileInputs.cacheC:\Users\Admin\Desktop\LE_AI\Frontend-saranya\frontend\GrammAI\GrammAI\obj\Debug\GrammAI.esproj.CoreCompileInputs.cacheC:\Users\Admin\Desktop\pylearn\GrammAI\GrammAI\obj\Debug\GrammAI.esproj.CoreCompileInputs.cacheC:\Users\Admin\Desktop\LE_AI\Frontend\py-learn\GrammAI\GrammAI\obj\Debug\GrammAI.esproj.CoreCompileInputs.cache123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{ "name": "gramm-ai", "version": "0.0.0", "engines": { "node": ">=18" }, "scripts": { "ng": "ng", "start": "ng serve --host=127.0.0.1 ", "build": "ng build", "watch": "ng build --watch --configuration development", "test": "ng test" }, "private": true, "dependencies": { "@angular/animations": "^17.1.0", "@angular/common": "^17.1.0", "@angular/compiler": "^17.1.0", "@angular/core": "^17.1.0", "@angular/forms": "^17.1.0", "@angular/platform-browser": "^17.1.0", "@angular/platform-browser-dynamic": "^17.1.0", "@angular/router": "^17.1.0", "@fortawesome/fontawesome-free": "^6.7.2", "@ngx-translate/core": "^16.0.4", "@ngx-translate/http-loader": "^16.0.1", "autoprefixer": "^10.4.20", "canvas-confetti": "^1.9.3", "jest-editor-support": "*", "postcss": "^8.4.49", "rxjs": "~7.8.0", "tailwindcss": "^3.4.17", "tslib": "^2.3.0", "zone.js": "~0.14.3" }, "devDependencies": { "@angular-devkit/build-angular": "^17.1.2", "@angular/cli": "^17.1.2", "@angular/compiler-cli": "^17.1.0", "@types/canvas-confetti": "^1.9.0", "@types/jasmine": "~5.1.0", "jasmine-core": "~5.1.0", "karma": "~6.4.0", "karma-chrome-launcher": "~3.2.0", "karma-coverage": "~2.2.0", "karma-jasmine": "~5.1.0", "karma-jasmine-html-reporter": "~2.1.0", "typescript": "~5.3.2" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import { NgModule } from '@angular/core';import { RouterModule, Routes } from '@angular/router';import { ChatComponent } from './chat/chat.component';import { HomeComponent } from './home/home.component';import { ListenComponent } from './listen/listen.component';
import { GenerateQuestionsComponent } from './generate-questions/generate-questions.component';import { VoiceComponent } from './voice/voice.component';import { WritingComponent } from './writing/writing.component';import { VocabularyBuilderComponent } from './vocabulary-builder/vocabulary-builder.component';import { FindwordComponent } from './findword/findword.component';import { ReadingComponent } from './reading/reading.component';import { AuthenticationComponent } from './authentication/authentication.component';import { authenticationGuard } from './authentication/authentication.guard'; // Use correct import
import { AuthComponent } from './auth/auth.component';import { authGuard } from './auth/auth.guard';import { rootRedirectGuard } from './auth/root-redirect.guard';import { RootRedirectComponent } from './root-redirect/root-redirect.component';
// Define and export routesexport const routes: Routes = [ //{ path: '', redirectTo: 'authentication', pathMatch: 'full' }, { path: '', component: RootRedirectComponent, canActivate: [rootRedirectGuard], pathMatch: 'full' },
{ path: 'home', component: HomeComponent, canActivate: [authGuard] }, { path: 'chat', component: ChatComponent, canActivate: [authGuard] }, { path: 'generate-questions', component: GenerateQuestionsComponent, canActivate: [authGuard] }, { path: 'voice', component: VoiceComponent, canActivate: [authGuard] }, { path: 'listen', component: ListenComponent, canActivate: [authGuard] }, { path: 'writing', component: WritingComponent, canActivate: [authGuard] }, { path: 'vocabulary-builder', component: VocabularyBuilderComponent, canActivate: [authGuard] }, { path: 'findword', component: FindwordComponent, canActivate: [authGuard] }, { path: 'reading', component: ReadingComponent, canActivate: [authGuard] }, { path: 'authentication', component: AuthenticationComponent }, { path: 'auth', component: AuthComponent }, { path: '**', redirectTo: 'auth' },
//{ path: 'generate-questions', component: GenerateQuestionsComponent }, //{ path: 'chat', component: ChatComponent}, //{ path: 'findword', component: FindwordComponent }, //{ path: 'reading', component: ReadingComponent},
];
@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule]})export class AppRoutingModule { }123456789101112nav { margin: 20px;}
button { margin-right: 10px; padding: 10px 20px; font-size: 16px; cursor: pointer;}
12
<router-outlet></router-outlet>1234567891011121314151617181920212223242526272829303132333435import { TestBed } from '@angular/core/testing';import { RouterTestingModule } from '@angular/router/testing';import { AppComponent } from './app.component';
describe('AppComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ AppComponent ], }).compileComponents(); });
it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app).toBeTruthy(); });
it(`should have as title 'GrammAI'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app.title).toEqual('GrammAI'); });
it('should render title', () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.nativeElement as HTMLElement; expect(compiled.querySelector('h1')?.textContent).toContain('Hello, GrammAI'); });});1234567891011121314151617181920import { Component } from '@angular/core';import { AuthService } from './auth/auth.service';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrl: './app.component.css'})export class AppComponent { constructor(private authService: AuthService) { } title = 'Py-Learn';
ngOnInit(): void { this.authService.checkSession().subscribe((status) => { if (status) { this.authService.startAutoRefresh(); // ✅ Start auto-refresh once app loads and session is valid } }); }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { HttpClientModule } from '@angular/common/http';import { AppRoutingModule } from './app-routing.module';
// Componentsimport { AppComponent } from './app.component';import { GenerateQuestionsComponent } from './generate-questions/generate-questions.component';import { HomeComponent } from './home/home.component';import { VoiceComponent } from './voice/voice.component';import { ListenComponent } from './listen/listen.component';import { WritingComponent } from './writing/writing.component';import { VocabularyBuilderComponent } from './vocabulary-builder/vocabulary-builder.component';import { FindwordComponent } from './findword/findword.component';import { ReadingComponent } from './reading/reading.component';import { AuthenticationComponent } from './authentication/authentication.component';import { AuthComponent } from './auth/auth.component';
import { RootRedirectComponent } from './root-redirect/root-redirect.component';
@NgModule({ declarations: [ AppComponent, // Add AppComponent here //GenerateQuestionsComponent, HomeComponent, VoiceComponent, ListenComponent, WritingComponent, VocabularyBuilderComponent, FindwordComponent, ReadingComponent, AuthenticationComponent, AuthComponent, RootRedirectComponent
], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule, ], providers: [], bootstrap: [AppComponent] // Bootstrap AppComponent})export class AppModule { }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211.py-learn-text { font-size: 4vw; font-weight: 600; color: #073879; font-family: Amonk_Outline;}
.self-learning-system { font-size: 1.2vw; font-weight: 500; color: #073879; margin-top: -0.8vw;}
.logo-header { display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center;}
.login-wrapper { height: 100vh; display: flex; justify-content: center; align-items: center; background-color: #05234b;}
.login-container { display: flex; width: 66vw; height: 600px; background-color: white; border-radius: 24px; /*box-shadow: #ffffff 0px 5px 15px;*/ box-shadow: #ffffff 1px 1px 51px; overflow: hidden;}
.login-image { flex: 1; background-color: #e8f0fe; display: flex; align-items: center;}
.bgImage { width: 100%; height: 66vh;}
.login-box { flex: 1; padding: 48px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: flex; flex-direction: column; justify-content: center;}
.logo { width: 6vw; position: absolute; top: 1vw; left: 1vw; background-color: #ffffff; border-radius: 1vw;}
h2 { font-size: 1.7vw; margin-bottom: 6px; text-align: left; margin-top: 1vw; font-weight: 500;}
.subtitle { font-size: 18px; color: #1a73e8; text-align: center; font-weight: bold;}
input[type="text"],input[type="password"] { width: 100%; padding: 16px; /* margin: 12px 0; */ border: 1px solid #dadce0; border-radius: 6px; font-size: 18px; margin-bottom: 1vw;}
button { background-color: #1a73e8; color: white; border: none; padding: 14px; font-size: 1.2vw; border-radius: 6px; width: 100%; margin-top: 20px; cursor: pointer; font-weight: 700;}
button:hover { background-color: #1669c1; }
.error { color: red; margin-top: 10px; font-size: 15px;}
.language-switcher, .grade-switcher { margin-top: 30px;}
.password-field { position: relative; width: 100%;}
.password-field input { padding-right: 40px; }
.toggle-password { position: absolute; right: 12px; top: 41%; transform: translateY(-50%); cursor: pointer; font-size: 1.2vw; color: #555; user-select: none;}
.footer-link { position: absolute; bottom: 1vw; right: 6vw; font-size: 14px; color: #1a73e8;}
.footer-link a { text-decoration: none; color: white; font-size: 1.2vw; font-weight: bold; }
.footer-link a:hover { text-decoration: underline; }
/* Positioning the social media icons at the top-right corner */.social-media-icons { position: absolute; top: 1vw; right: 2vw; display: flex; gap: 15px;}
.social-icon img { width: 3vw; height: 3vw; transition: transform 0.3s;}
.social-icon img:hover { transform: scale(1.1); /* Slight zoom effect on hover */ }
.language-grade-container { display: flex; gap: 13vw; /* Gap between Language and Grade sections */ align-items: center;}
.language-switcher,.grade-switcher { display: flex; align-items: center; gap: 0.5vw; /* Gap between label and select box */}
.language-label, .grade-label { color: #007bff; /* Blue for Language label */ font-size: 1vw; font-weight: bold;}
.dropdown-select { /* padding: 0.5vw; */ font-size: 1vw; border-radius: 5px; /* border: 1px solid #000; */}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101<div class="login-wrapper"> <div class="login-container"> <!-- Left side image and logo --> <div class="login-image"> <img src="assets/images/login/lion.png" alt="Login Illustration" class="bgImage" /> <img src="assets/images/pykara-logo.png" alt="Pykara Logo" class="logo" /> </div>
<!-- Right side form --> <div class="login-box"> <div class="logo-header"> <span class="py-learn-text">Py- Learn</span> <!-- Added self-learning system text here --> <div class="self-learning-system">(A Self-Learning System)</div> </div>
<h2>Login</h2> <!--<p class="subtitle">Use your Pykara account</p>--> <!--<input type="text" [(ngModel)]="username" placeholder="Username or Email" />
<div class="password-field"> <input [type]="showPassword ? 'text' : 'password'" [(ngModel)]="password" placeholder="Password" /> <span class="toggle-password" (click)="togglePasswordVisibility()"> <i class="{{ showPassword ? 'fas fa-eye' : 'fas fa-eye-slash' }}"></i> </span> </div>
<p *ngIf="errorMessage" class="error">{{ errorMessage }}</p>
<button (click)="login()">Login</button>-->
<form (ngSubmit)="login()" #loginForm="ngForm" autocomplete="on"> <input type="text" name="username" [(ngModel)]="username" placeholder="Username or Email" required />
<div class="password-field"> <input [type]="showPassword ? 'text' : 'password'" name="password" [(ngModel)]="password" placeholder="Password" required autocomplete="current-password" (keydown.enter)="login(); $event.preventDefault()"/> <span class="toggle-password" (click)="togglePasswordVisibility()"> <i class="{{ showPassword ? 'fas fa-eye' : 'fas fa-eye-slash' }}"></i> </span> </div>
<p *ngIf="errorMessage" class="error">{{ errorMessage }}</p>
<button type="submit">Login</button> </form>
<div class="language-grade-container"> <div class="language-switcher"> <label for="lang-select" class="language-label">Language:</label> <select id="lang-select" class="dropdown-select"> <option value="en-GB">English (UK)</option> <option value="en-US">English (US)</option> <option value="sv">Svenska</option> <option value="fr">Français</option> <option value="de">Deutsch</option> <option value="es">Español</option> </select> </div>
<div class="grade-switcher"> <label for="grade-select" class="grade-label">Grade:</label> <select id="grade-select" class="dropdown-select"> <option value="4th">4th</option> <option value="5th">5th</option> <option value="6th">6th</option> </select> </div> </div>
</div> </div>
<div class="footer-link"> <a href="https://pykara.ai" target="_blank">www.pykara.ai</a> </div>
<!-- Social Media Icons at the top-right --> <div class="social-media-icons"> <a href="https://www.youtube.com/@PykaraTechnologies/videos" target="_blank" class="social-icon">
<img src="assets/images/home/youtube-icon.png" alt="YouTube"> </a> <a href="https://www.linkedin.com/in/pykara-technologies" target="_blank" class="social-icon">
<img src="assets/images/home/linkedin-icon.png" alt="LinkedIn"> </a> </div>
</div>1234567891011121314151617181920212223import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AuthComponent } from './auth.component';
describe('AuthComponent', () => { let component: AuthComponent; let fixture: ComponentFixture<AuthComponent>;
beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [AuthComponent] }) .compileComponents(); fixture = TestBed.createComponent(AuthComponent); component = fixture.componentInstance; fixture.detectChanges(); });
it('should create', () => { expect(component).toBeTruthy(); });});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import { Component } from '@angular/core';import { AuthService } from './auth.service';import { Router } from '@angular/router';
@Component({ selector: 'app-auth', templateUrl: './auth.component.html', styleUrl: './auth.component.css'})export class AuthComponent {
username: string = ''; password: string = ''; errorMessage: string = ''; showPassword: boolean = false;
constructor(private authService: AuthService, private router: Router) { }
//ngOnInit(): void { // this.authService.checkSession(); //} // ✅ Handle Login login(): void { this.authService.login(this.username, this.password).subscribe( (response) => { console.log('✅ Login success. Redirecting to /home...'); this.authService.setLoggedIn(true); this.authService.startAutoRefresh(); /*this.router.navigate(['/home']); // Redirect to dashboard after login*/ // 🔁 Redirect to stored URL or default to /home const redirectUrl = localStorage.getItem('redirectAfterLogin') || '/home'; localStorage.removeItem('redirectAfterLogin'); this.router.navigate([redirectUrl]); }, (error) => { this.errorMessage = 'Invalid username or password'; } ); }
// ✅ Check if user is logged in isLoggedIn(): boolean { return this.authService.isLoggedIn(); }
togglePasswordVisibility(): void { this.showPassword = !this.showPassword; }
}1234567891011121314151617import { TestBed } from '@angular/core/testing';import { CanActivateFn } from '@angular/router';
import { authGuard } from './auth.guard';
describe('authGuard', () => { const executeGuard: CanActivateFn = (...guardParameters) => TestBed.runInInjectionContext(() => authGuard(...guardParameters));
beforeEach(() => { TestBed.configureTestingModule({}); });
it('should be created', () => { expect(executeGuard).toBeTruthy(); });});123456789101112131415161718192021222324252627282930import { inject } from '@angular/core';import { CanActivateFn, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';import { AuthService } from './auth.service';import { map, catchError } from 'rxjs/operators';import { of } from 'rxjs';
export const authGuard: CanActivateFn = ( route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { const authService = inject(AuthService); const router = inject(Router);
return authService.checkSession().pipe( map(() => { if (authService.isLoggedIn()) { return true; } else { localStorage.setItem('redirectAfterLogin', state.url); router.navigate(['/auth']); return false; } }), catchError(() => { localStorage.setItem('redirectAfterLogin', state.url); router.navigate(['/auth']); return of(false); }) );};12345678910111213141516import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => { let service: AuthService;
beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(AuthService); });
it('should be created', () => { expect(service).toBeTruthy(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188import { Injectable } from '@angular/core';import { HttpClient } from '@angular/common/http';import { BehaviorSubject, Observable, of, throwError } from 'rxjs';import { tap, catchError } from 'rxjs/operators';import { Router } from '@angular/router';
@Injectable({ providedIn: 'root'})
export class AuthService { private apiUrl = 'http://localhost:5000'; // Your Flask API base URL private loggedInSubject = new BehaviorSubject<boolean>(false); // Shared state public isLoggedIn$ = this.loggedInSubject.asObservable(); private refreshIntervalId: any; constructor(private http: HttpClient, private router: Router) { }
// ✅ Called to check current status isLoggedIn(): boolean { return this.loggedInSubject.value; }
// ✅ Set login status manually setLoggedIn(status: boolean): void { this.loggedInSubject.next(status); } // ✅ Login Method
login(username: string, password: string): Observable<any> { return this.http.post(`${this.apiUrl}/login`, { username, password }, { withCredentials: true }); }
startAutoRefresh(): void { if (this.refreshIntervalId) return; this.refreshIntervalId = setInterval(() => { this.refreshAccessToken(); }, 12 * 60 * 1000); }
clearAutoRefresh(): void { clearInterval(this.refreshIntervalId); this.refreshIntervalId = null; }
refreshAccessToken(): void { this.http.post(`${this.apiUrl}/refresh`, {}, { withCredentials: true }).subscribe( (response: any) => { console.log("✅ Access token refreshed:", response.access_token); //alert("🔄 Access token has been refreshed!"); }, (error) => { console.error("❌ Refresh failed:", error);
if ( error.status === 401 && error.error && (error.error.message === 'Refresh token has expired' || error.error.message === 'Invalid refresh token') ) { //alert("⚠️ Your session has expired. Please log in again.");
// Clear cookies manually (if needed) this.clearTokens();
// Redirect to login this.router.navigate(['/auth']); } } ); }
logout(): Observable<any> { console.log("🔧 Sending logout request with credentials");
return this.http.post(`${this.apiUrl}/logout`, {}, { withCredentials: true }).pipe( tap(response => { console.log('🔙 Response from backend:', response); this.clearTokens(); this.clearAutoRefresh(); // ✅ Stop auto-refresh }), catchError(error => { console.error('❌ Error from backend:', error); return throwError(() => error); }) ); }
clearTokens(): void { document.cookie = 'access_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'; document.cookie = 'refresh_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'; this.clearAutoRefresh(); // ✅ }
//// ✅ Check if user is logged in (check for presence of cookies) //isLoggedIn(): boolean { // // Check cookies directly (this will happen automatically when the browser sends cookies) // // Check if the cookies are present (you can do it manually using a service or via backend) // return document.cookie.includes('access_token'); //}
// ✅ Get access token (using cookies) getAccessToken(): string | null { const cookies = document.cookie.split('; '); for (let cookie of cookies) { if (cookie.startsWith('access_token=')) { return cookie.split('=')[1]; } } return null; }
// ✅ Save tokens (Not necessary, as tokens are managed via cookies) saveTokens(accessToken: string, refreshToken: string): void { // No need for this if you're using cookies, but if you want to persist in localStorage, use: localStorage.setItem('access_token', accessToken); localStorage.setItem('refresh_token', refreshToken); }
//checkSession(): Observable<boolean> { // return this.http.get(`${this.apiUrl}/check-auth`, { withCredentials: true }).pipe( // tap((res: any) => { // console.log('✅ Session valid:', res); // this.setLoggedIn(true); // }), // catchError((err) => { // console.warn('❌ Session check failed:', err); // this.setLoggedIn(false); // return [false]; // Return false on error // }) // ); //}
checkSession(): Observable<boolean> { return this.http.get(`${this.apiUrl}/check-auth`, { withCredentials: true }).pipe( tap((res: any) => { console.log('✅ Session valid:', res); this.setLoggedIn(true); this.startAutoRefresh(); return true; // ✅ Important! }), catchError((err) => { if (err.status === 401) { // Access token may be expired. Try refresh console.warn('🔄 Access token expired. Trying to refresh...');
return this.http.post(`${this.apiUrl}/refresh`, {}, { withCredentials: true }).pipe( tap((refreshRes: any) => { console.log("✅ Token refreshed during checkSession."); //alert("✅ Token refreshed during checkSession."); this.setLoggedIn(true); this.startAutoRefresh(); }), catchError((refreshErr) => { console.error("❌ Refresh token failed during checkSession.", refreshErr); this.setLoggedIn(false); return of(false); }) ); } else { console.error("❌ Unknown error during checkSession", err); this.setLoggedIn(false); return of(false); } }) ); }
}1234567891011121314151617import { TestBed } from '@angular/core/testing';import { CanActivateFn } from '@angular/router';
import { rootRedirectGuard } from './root-redirect.guard';
describe('rootRedirectGuard', () => { const executeGuard: CanActivateFn = (...guardParameters) => TestBed.runInInjectionContext(() => rootRedirectGuard(...guardParameters));
beforeEach(() => { TestBed.configureTestingModule({}); });
it('should be created', () => { expect(executeGuard).toBeTruthy(); });});1234567891011121314151617181920212223242526272829import { inject } from '@angular/core';import { ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot } from '@angular/router';import { AuthService } from './auth.service';import { map, catchError, of } from 'rxjs';
export const rootRedirectGuard: CanActivateFn = ( route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { const authService = inject(AuthService); const router = inject(Router);
return authService.checkSession().pipe( map(() => { if (authService.isLoggedIn()) { router.navigate(['/home']); } else { router.navigate(['/auth']); } return false; }), catchError(() => { router.navigate(['/auth']); return of(false); }) );
};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
.py-learn-text { font-size: 4vw; font-weight: 600; color: #073879; font-family: Amonk_Outline;}
/* Wrapper for the full screen */.login-wrapper { height: 100vh; display: flex; justify-content: center; align-items: center; background-color: #05234b;}
/* Container for left and right split */.login-container { display: flex; width: 1100px; height: 600px; background-color: white; border-radius: 24px; box-shadow: #ffffff 0px 5px 15px; overflow: hidden;}
/* Left section (image) */.login-image { flex: 1; background-color: #e8f0fe; display: flex; align-items: center;}
.bgImage { width: 100%; height: 66vh; /*opacity: 0.5;*/}
/* Right section (form) */.login-box { flex: 1; padding: 60px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: flex; flex-direction: column; justify-content: center;
}
.logo { width: 6vw; position: absolute; top: 1vw; left: 1vw; background-color: #ffffff; border-radius: 1vw;}
.login-box h2 { font-size: 36px; margin-bottom: 10px;}
.subtitle { font-size: 18px; color: #1a73e8; margin-bottom: 30px; font-weight: bold}
input[type="text"],input[type="password"] { width: 100%; padding: 16px; margin: 12px 0; border: 1px solid #dadce0; border-radius: 6px; font-size: 16px;}
button { background-color: #1a73e8; color: white; border: none; padding: 14px; font-size: 16px; border-radius: 6px; width: 100%; margin-top: 20px; cursor: pointer;}
button:hover { background-color: #1669c1; }
.error { color: red; margin-top: 10px; font-size: 15px;}
.language-switcher { margin-top: 30px; font-size: 15px;}.password-field { position: relative; width: 100%;}
.password-field input { width: 100%; padding-right: 40px; /* space for the icon */ }
.toggle-password { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); cursor: pointer; font-size: 1.2vw; color: #555; user-select: none;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647<div class="login-wrapper"> <div class="login-container"> <!-- Left side image --> <div class="login-image"> <img src="assets/images/lion1.png" alt="Login Illustration" class="bgImage"/> <img src="assets/images/pykara-logo.png" alt="Pykara Logo" class="logo" /> </div>
<!-- Right side form --> <div class="login-box">
<div class="logo-header"> <span class="py-learn-text">Py Learn</span> </div>
<h2>Sign in</h2> <p class="subtitle">Use your Pykara account</p>
<div *ngIf="!isLoggedIn"> <input type="text" [(ngModel)]="username" placeholder="Email or phone" /> <div class="password-field"> <input [type]="showPassword ? 'text' : 'password'" [(ngModel)]="password" placeholder="Password" /> <span class="toggle-password" (click)="togglePasswordVisibility()"> <i class="{{ showPassword ? 'fas fa-eye' : 'fas fa-eye-slash' }}"></i> <!-- {{ showPassword ? '👁️' : '🙈' }}--> </span> </div>
<p *ngIf="errorMessage" class="error">{{ errorMessage }}</p>
<button (click)="login()">Login</button> </div>
<div class="language-switcher"> <label for="lang-select">Language:</label> <select id="lang-select"> <option value="en">English</option> <option value="fr">Français</option> <option value="sv">Svenska</option> <option value="de">Deutsch</option> </select> </div> </div> </div></div>1234567891011121314151617181920212223import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AuthenticationComponent } from './authentication.component';
describe('AuthenticationComponent', () => { let component: AuthenticationComponent; let fixture: ComponentFixture<AuthenticationComponent>;
beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [AuthenticationComponent] }) .compileComponents(); fixture = TestBed.createComponent(AuthenticationComponent); component = fixture.componentInstance; fixture.detectChanges(); });
it('should create', () => { expect(component).toBeTruthy(); });});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647import { Component } from '@angular/core';import { AuthenticationService } from './authentication.service'; // Import the AuthenticationServiceimport { Router } from '@angular/router';
@Component({ selector: 'app-authentication', templateUrl: './authentication.component.html', styleUrl: './authentication.component.css'})export class AuthenticationComponent { username: string = ''; password: string = ''; errorMessage: string = '';
constructor(private authService: AuthenticationService, private router: Router) { }
// ✅ Login functionality login(): void { this.authService.login(this.username, this.password).subscribe( (response: any) => { // Directly access the tokens from the response body const token = response.access_token; // Access the access token directly from the body this.authService.storeToken(token); this.router.navigate(['/home']); // Redirect to the home page or dashboard after successful login }, (error) => { this.errorMessage = 'Invalid username or password'; // Show error message if login fails } ); }
// ✅ Check if the user is logged in (token is stored in localStorage) get isLoggedIn(): boolean { return this.authService.isLoggedIn(); }
showPassword: boolean = false;
togglePasswordVisibility(): void { this.showPassword = !this.showPassword; }
}1234567891011121314151617import { TestBed } from '@angular/core/testing';import { CanActivateFn } from '@angular/router';
import { authenticationGuard } from './authentication.guard';
describe('authenticationGuard', () => { const executeGuard: CanActivateFn = (...guardParameters) => TestBed.runInInjectionContext(() => authenticationGuard(...guardParameters));
beforeEach(() => { TestBed.configureTestingModule({}); });
it('should be created', () => { expect(executeGuard).toBeTruthy(); });});123456789101112131415161718192021222324import { inject } from '@angular/core';import { CanActivateFn, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';import { AuthenticationService } from './authentication.service';
//export const authenticationGuard: CanActivateFn = (route, state) => {// return true;//};
export const authenticationGuard: CanActivateFn = ( route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { const authService = inject(AuthenticationService); const router = inject(Router);
if (authService.isLoggedIn()) { return true; // Allow access to the requested route } else { // Optionally, you can save the intended URL for redirection after login router.navigate(['/authentication']); return false; // Deny access and redirect to login page }};
12345678910111213141516import { TestBed } from '@angular/core/testing';
import { AuthenticationService } from './authentication.service';
describe('AuthenticationService', () => { let service: AuthenticationService;
beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(AuthenticationService); });
it('should be created', () => { expect(service).toBeTruthy(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203import { Injectable } from '@angular/core';import { BehaviorSubject } from 'rxjs';import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';import { Observable } from 'rxjs/internal/Observable';import { tap } from 'rxjs/operators';import { catchError } from 'rxjs/operators';import { throwError } from 'rxjs';@Injectable({ providedIn: 'root'})export class AuthenticationService { private apiUrl = 'http://127.0.0.1:5000'; // Your backend URL private loggedInSubject = new BehaviorSubject<boolean>(this.isLoggedIn()); // BehaviorSubject to track login status
constructor(private http: HttpClient) { // Change from 5 minutes to 30 seconds setInterval(() => this.checkAndRefreshToken(), 30 * 1000); // Every 30 seconds
// Periodically check for token expiry and refresh it if necessary //setInterval(() => this.checkAndRefreshToken(), 5 * 60 * 1000); // Check every 5 minutes }
// ✅ Login Method // ✅ Login Method (returns an Observable) login(username: string, password: string): Observable<any> { const loginData = { username, password }; return this.http.post(`${this.apiUrl}/login`, loginData).pipe( tap((response: any) => { //const now = new Date(); // Store tokens in localStorage localStorage.setItem('access_token', response.access_token); localStorage.setItem('refresh_token', response.refresh_token);
// Optionally store expiry time of the access token (2 minutes) const accessTokenExpiry = Date.now() + 2 * 60 * 1000; // 2 minutes expiration for access token localStorage.setItem('access_token_expiry', accessTokenExpiry.toString());
// Optionally store expiry time of the refresh token (5 minutes) const refreshTokenExpiry = Date.now() + 10 * 60 * 1000; // 5 minutes expiration for refresh token localStorage.setItem('refresh_token_expiry', refreshTokenExpiry.toString());
this.loggedInSubject.next(true);
}), catchError(error => { // Handle error (token expiry / invalid login) if (error.status === 401 && error.error.message === 'Token has expired') { //alert('Your session has expired, please log in again.'); } return throwError(error); }) ); }
logout(): Observable<any> { const token = this.getToken(); console.log('🔑 Token at logout start:', token);
this.removeToken(); // Remove token first this.loggedInSubject.next(false);
if (!token) { console.warn('⚠️ No token found. Emitting success anyway.'); return new Observable(observer => { observer.next(true); observer.complete(); }); }
const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`); console.log('📤 Sending logout request with headers:', headers);
return this.http.post(`${this.apiUrl}/logout`, {}, { headers }).pipe( tap(() => { console.log('✅ Logout API request completed'); // This should now appear }), catchError((error) => { console.error('❌ Logout error in service:', error); return new Observable(observer => { observer.next(true); // Continue flow even on error observer.complete(); }); }) ); }
// ✅ Get Token (to use for making authorized requests) getToken(): string | null { return localStorage.getItem('access_token'); }
// ✅ Store Token storeToken(token: string): void { localStorage.setItem('access_token', token); console.log('Token stored:', token); // Log the token to confirm it's saved this.loggedInSubject.next(true); // Update login status } // ✅ Remove Token removeToken(): void { localStorage.removeItem('access_token'); localStorage.removeItem('refresh_token'); localStorage.removeItem('access_token_expiry'); this.loggedInSubject.next(false); // Update login status }
// ✅ Check if the user is logged in isLoggedIn(): boolean { return !!this.getToken(); } // ✅ Observable to track login status get isLoggedIn$(): Observable<boolean> { return this.loggedInSubject.asObservable(); }
checkAndRefreshToken() { const accessTokenExpiry = localStorage.getItem('access_token_expiry'); if (accessTokenExpiry && Date.now() >= (+accessTokenExpiry - 5000)) { // Refresh 5 seconds before expiry this.refreshAccessToken(); }
}
// Check token every 5 minutes
// ✅ Refresh Access Token Method // ✅ Refresh Access Token Method //refreshAccessToken() { // const refreshToken = localStorage.getItem('refresh_token'); // if (refreshToken) { // this.http.post(`${this.apiUrl}/refresh`, { refresh_token: refreshToken }).subscribe((response: any) => { // // Store the new access token // localStorage.setItem('access_token', response.access_token);
// // Optionally, update the expiry time of the new access token (2 minutes) // const newAccessTokenExpiry = Date.now() + 2 * 60 * 1000; // 2 minutes // localStorage.setItem('access_token_expiry', newAccessTokenExpiry.toString()); // alert('Your access token has been refreshed successfully!'); // }, error => { // console.log("Error refreshing token", error); // // Handle token refresh failure (e.g., log out the user) // this.logout(); // }); // } //} refreshAccessToken() { const refreshToken = localStorage.getItem('refresh_token');
if (refreshToken) { this.http.post(`${this.apiUrl}/refresh`, { refresh_token: refreshToken }).subscribe( (response: any) => { // Store the new access token localStorage.setItem('access_token', response.access_token);
// Update expiry const newAccessTokenExpiry = Date.now() + 2 * 60 * 1000; // 2 minutes localStorage.setItem('access_token_expiry', newAccessTokenExpiry.toString());
//alert('Your access token has been refreshed successfully!'); }, error => { console.log("Error refreshing token", error);
if ( error.status === 401 && (error.error.message === 'Refresh token has expired' || error.error.message === 'Invalid refresh token') ) { //alert('Your session has expired. Please log in again.');
// ✅ Remove tokens and redirect to login this.removeToken(); this.loggedInSubject.next(false); window.location.href = '/authentication'; // Adjust this if your login route is different } else { // Other errors can be handled differently console.error("Unexpected error:", error); } } ); } }
}12345678910111213141516import { TestBed } from '@angular/core/testing';
import { ApiService } from './api.service';
describe('ApiService', () => { let service: ApiService;
beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(ApiService); });
it('should be created', () => { expect(service).toBeTruthy(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081/*import { Injectable } from '@angular/core';import { HttpClient } from '@angular/common/http';import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root'})export class ApiService {
//private apiUrl = 'http://127.0.0.1:5000'; // Flask backend URL
private apiUrl = 'http://localhost:5000/explain-grammar';
constructor(private http: HttpClient) { }
// Method to send the grammar question and receive the explanation from Flask backend //askQuestion(question: string): Observable<any> { // const body = { topic: question }; // Prepare the request body // return this.http.post<any>(`${this.apiUrl}/explain-grammar`, body); // Call the Flask API and return the observable //}
// Method to send the user's question to the Flask backend askQuestion(userInput: string): Observable<any> { const data = { topic: userInput }; // Assuming you're sending the user input as a topic
return this.http.post<any>(this.apiUrl, data); // POST request to Flask backend }
}*/
import { Injectable } from '@angular/core';import { HttpClient, HttpHeaders } from '@angular/common/http';import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root'})export class ApiService { private baseUrl = 'http://localhost:5012'; //private apiUrl = 'http://localhost:5012/explain-grammar'; constructor(private http: HttpClient) { }
//askQuestion(userInput: string, sessionId: string | null): Observable<any> { // const headers = { 'Content-Type': 'application/json' };
// // Include `session_id` in request only if available // const data = sessionId // ? { topic: userInput, session_id: sessionId } // : { topic: userInput };
// console.log("Sending request to Flask:", this.apiUrl, data);
// return this.http.post<any>(this.apiUrl, data, { headers }); //}
// Fetch grammar question suggestions
//getGrammarSuggestions(input: string): Observable<any> { // const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
// return this.http.post<any>(this.apiUrl, { topic: input }, { headers }); // ✅ Fix: Send input as "topic" //}
askQuestion(userInput: string, sessionId: string | null): Observable<any> { const headers = { 'Content-Type': 'application/json' }; const data = sessionId ? { topic: userInput, session_id: sessionId } : { topic: userInput };
return this.http.post<any>(`${this.baseUrl}/explain-grammar`, data, { headers }); }
getGrammarSuggestions(input: string): Observable<any> { const headers = { 'Content-Type': 'application/json' }; return this.http.post<any>(`${this.baseUrl}/suggest-grammar-questions`, { input }, { headers }); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960/* Header Container Styling */.header-container { display: flex; justify-content: space-between; align-items: center; padding: 0vw 1vw; background-color: #03182d; /* background-color: #c19929;*/ box-shadow: 0 0.4vw 0.8vw rgba(0, 0, 0, 0.2); width: 100%; position: sticky; top: 0; z-index: 1000;}
.logo img { max-width: 5vw; height: auto; background: #e5e7eb; border-radius: 1vw; margin: 0.5vw;}
.home-btn img { width: 5vw; /* Adjust the size of the home icon */}
.home-btn img:hover { transform: scale(1.1); /* Slight zoom-in effect on hover */}
h1 { font-size: 3vw; color: white; font-family: Super Cartoon;}
@font-face { font-family: 'Super Cartoon'; src: url('../../assets/font/Super Cartoon.ttf') format('truetype'); font-weight: normal; font-style: normal; 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 */ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.chat-bg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: fill; z-index: -1; 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 */ 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 */}
/* Wrapper for Message and Profile Picture *//*.message-wrapper { display: flex; align-items: flex-start; gap: 1vw;*/ /* Space between profile picture and message */ /*margin-bottom: 1.5vw;}
.message-wrapper.user { flex-direction: row-reverse;*/ /* User messages on the right */ /*text-align: right;}*/
/* Profile Picture Styling *//*.profile-pic { flex-shrink: 0; width: 4vw;*/ /* Responsive profile picture size */ /*height: 4vw; border-radius: 50%; overflow: hidden; background-color: #ddd;*/ /* Fallback color *//*}
.profile-pic img { width: 100%; height: 100%; object-fit: cover;*/ /* Ensure image fits nicely *//*}*/
/* Message Styles *//*.message { max-width: 50vw;*/ /* Adjust message width for smaller screens */ /*padding: 1vw 2vw; border-radius: 2vw; font-size: 1.2vw; line-height: 1.5; box-shadow: 0 0.3vw 0.8vw rgba(0, 0, 0, 0.1); animation: fadeIn 0.5s ease;}
.message-content { text-align: justify;}*/
/* User and AI Message Colors *//*.user .message { align-self: flex-end; background: #2b6296; color: white;}
.ai .message { align-self: flex-start;*/ /* background: #a855f7;*/ /* background: #404d95f7;*/ /*background: #2b6296; color: white;}*/
/* Timestamp Styling *//*.message-timestamp { font-size: 1vw; color: rgba(255, 255, 255, 0.8); margin-top: 0.5vw; display: block; text-align: right;}*/
/*.typing-indicator { font-style: italic; color: #888; font-size: 1.2vw; text-align: left; margin: 1vw 0; display: flex; align-items: center;}*/
/*.typing-indicator::after { content: "⠿"; display: inline-block; font-size: 1.5vw; color: #888; animation: typing-animation 1s infinite; }
@keyframes typing-animation { 0% { opacity: 0.2; }
50% { opacity: 1; }
100% { opacity: 0.2; }}*/
/* General Flexbox Adjustments *//*.chat-box { padding: 2vw; display: flex; flex: 1; flex-direction: column; gap: 1vw;*/ /* Adjust spacing between messages */ /*background-color: #f9fafb;*/ /* Light background */ /*overflow-y: auto; height: 80vh;*/ /* Maintain height of the chat box *//*}*/
/*.chat-box { display: flex; flex-direction: column; gap: 1vw; overflow-y: auto; height: calc(100vh - 120px); padding: 2vw;*/ /*background-color: rgb(35 34 32 / 45%);*/ /* background-color: rgb(35 34 32 / 23%);*/ /*background-color: rgb(35 34 32 / 43%);}*/
/*.chat-box { display: flex; flex-direction: column; gap: 1vw; overflow-y: auto;*/ /* ✅ Enables scrolling */ /*height: calc(100vh - 120px); padding: 2vw; background-color: rgba(35, 34, 32, 0.43); scroll-behavior: smooth;*/ /* ✅ Smooth scrolling *//*}*/
/*.chat-box { display: flex; flex-direction: column; overflow-y: auto;*/ /* ✅ Enables scrolling */ /*height: calc(100vh - 120px); padding: 2vw; background-color: rgba(35, 34, 32, 0.43); scroll-behavior: smooth;*/ /* ✅ Smooth scrolling *//*}*/
.chat-box { display: flex; flex-direction: column; overflow-y: auto; height: calc(100vh - 180px); /* Adjust height as needed */ padding: 2vw; background-color: rgba(35, 34, 32, 0.43); scroll-behavior: smooth; /* Smooth scrolling */ flex-grow: 1; padding-bottom: 90px;}
/*.chat-box { display: flex; flex-direction: column; overflow-y: auto; height: calc(100vh - 180px);*/ /* Adjust height to create space */ /*padding: 2vw; background-color: rgba(35, 34, 32, 0.43); scroll-behavior: smooth; flex-grow: 1; overflow-y: auto; padding-bottom: 90px;*/ /* ✅ Creates gap between chat and input field *//*}*/
/*.message-wrapper { display: flex; align-items: flex-start; margin-bottom: 1.5vw;}*/
.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 */ flex-shrink: 0; width: 100%; height: auto; /* Adjust height dynamically */ min-height: 40px; /* Ensure it doesn't shrink too much */ 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 */ /* border: 1px solid rgba(255, 255, 255, 0.13);*/ /*border: 1px solid rgb(93 145 195); border-radius: 8px;*/ /* Smaller border radius */ /*background: rgba(255, 255, 255, 0.04); color: white; outline: none; transition: border-color 0.3s ease, box-shadow 0.3s ease; width: 100%; box-sizing: border-box; }*/
.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 */ border: 1px solid rgb(93, 145, 195); border-radius: 8px; /* Smaller border radius */ background: rgba(255, 255, 255, 0.04); color: white; outline: none; transition: border-color 0.3s ease, box-shadow 0.3s ease; width: 100%; 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 */ 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 */ }
/*.input-box button { font-size: 1rem;*/ /* Smaller font size */ /*padding: 6px 12px;*/ /* Smaller button padding */ /*border-radius: 8px;*/ /* Match text area border radius */ /*background: #a855f7; color: white; cursor: pointer; transition: all 0.3s ease; }*/
.input-box button { width: 55px; /* Fixed button size */ height: 55px; /* Fixed button size */ 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 */ }
.button-icon { width: 34px; /* Default size for all icons */ height: 34px; object-fit: contain;}
.resume-icon { width: 40px; /* Slightly larger for balance */ height: 40px; object-fit: contain;}
.pause-icon { width: 31px; /* Custom size for pause icon */ height: 31px; object-fit: contain;}
.suggestion-box { position: absolute; bottom: 100%; width: 100%; background: #d1dae3; border: 1px solid rgba(0, 0, 0, 0.2); border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); color: black; z-index: 100; padding: 8px 0;}
.suggestion-box ul { list-style: none; margin: 0; padding: 0; }
.suggestion-box li { padding: 8px 12px; /* Spacing inside each suggestion */ cursor: pointer; font-size: 1rem; transition: background-color 0.3s ease; color: rgb(67 65 65); /* Text color */ }
.suggestion-box li:hover { background-color: rgba(0, 0, 0, 0.1); /* Subtle hover effect */ border-radius: 4px; /* Rounded corners for hover */ }
.input-container { display: flex; flex-direction: column-reverse; /* Reverse order to place suggestions above input */ position: relative; width: 100%;}
.input-box { display: flex; gap: 10px; padding: 8px; background: #03182d; /* Background color of the input box */ /*background: #c19929;*/ /* Background color of the input box */ box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); flex-shrink: 0; width: 100%; height: auto; min-height: 40px;}
/* Glass Transparent Listening Indicator (Fully Centered) */.listening-box { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgb(171 188 205); padding: 45px; border-radius: 20px; width: 30vw; height: auto; /* Adjust height dynamically */ min-height: 40vh; /* Ensure height remains balanced */ 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 */ justify-content: center; border: 1px solid rgba(255, 255, 255, 0.2); text-align: center; /* Center text alignment */}
/* Microphone Image (Centered Properly) */.microphone-image { width: 100px; /* Slightly bigger */ height: 100px; display: block; margin: 0 auto 20px; /* Ensures it's centered with space below */ animation: pulse 1.5s infinite alternate ease-in-out;}
/* Pulse Effect */@keyframes pulse { from { transform: scale(1); filter: drop-shadow(0px 0px 8px rgba(0, 0, 0, 0.4)); }
to { transform: scale(1.2); filter: drop-shadow(0px 0px 14px rgba(0, 0, 0, 0.7)); }}
/* Listening Text (Fully Centered) */.listening-box p { font-size: 15px; /* Increased size */ color: black; font-weight: bold; text-align: center; /* Ensure it's aligned centrally */ margin: 10px 0; /* Adjusted margin */ 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 */ 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 */ 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 */ display: flex; align-items: center; justify-content: center; backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);}
/* Mute and Close Icon Styles (Proper Scaling) */ .mute-btn img, .close-btn img { width: 50px; /* Bigger icons */ height: 50px; }
/* Hover Effects */ .mute-btn:hover { background: rgba(255, 0, 0, 0.5); /* Red for mute */ transform: scale(1.15); }
.close-btn:hover { background: rgba(0, 0, 0, 0.5); /* Dark for close */ transform: scale(1.15); }
/* Fade-in with Scale Animation */@keyframes fadeInScale { from { opacity: 0; transform: translate(-50%, -50%) scale(0.85); }
to { opacity: 1; transform: translate(-50%, -50%) scale(1); }}
/* Centered Error Message *//*.error-box { position: fixed; top: 60%; left: 50%; transform: translate(-50%, -50%); background: rgba(255, 0, 0, 0.8); color: white; padding: 12px 20px; border-radius: 8px; font-size: 14px; text-align: center; z-index: 1000; animation: fadeIn 0.3s ease-in-out;}*/
.error-text { color: black; background: #ffccccad; /* Light red */ 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 */ transition: background 0.3s;}
.error-text:hover { background: #ffaaaa; /* Slightly darker red on hover */ }
/* Popup Overlay */.popup-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); /* Dark transparent background */ display: flex; justify-content: center; align-items: center; z-index: 1000;}
/* Popup Box */.popup-box { background: white; padding: 20px; border-radius: 8px; width: 300px; text-align: center; 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; border: none; padding: 10px 20px; font-size: 14px; border-radius: 5px; cursor: pointer; margin-top: 10px;}
.popup-button:hover { background: #0056b3; }
.typing-indicator { display: flex; align-items: center; gap: 8px; font-style: italic; color: #ffffff; font-size: 1.2vw; margin-left: 4vw; margin-top: 1vw; background: rgba(255, 255, 255, 0.2); padding: 0.8vw 1.5vw; border-radius: 2vw; width: fit-content; animation: fadeIn 0.3s ease-in-out;}
/* Typing dots animation */ .typing-indicator span { width: 10px; height: 10px; background-color: #ffffff; border-radius: 50%; display: inline-block; animation: typingDots 1.5s infinite ease-in-out; }
/* Add animation delays for each dot */ .typing-indicator span:nth-child(1) { animation-delay: 0s; }
.typing-indicator span:nth-child(2) { animation-delay: 0.2s; }
.typing-indicator span:nth-child(3) { animation-delay: 0.4s; }
/* Keyframes for the typing dots */@keyframes typingDots { 0%, 100% { transform: scale(0.8); opacity: 0.3; }
50% { transform: scale(1); opacity: 1; }}
/* Smooth fade-in effect */@keyframes fadeIn { from { opacity: 0; transform: translateY(5px); }
to { opacity: 1; transform: translateY(0); }}
/*Oviya - Hardcoded*//*.hardcoded-questions { position: absolute; background: white; border: 1px solid #ccc; border-radius: 5px; padding: 10px; width: 90%; max-width: 400px; box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1); margin-top: 5px; z-index: 1000;}
.hardcoded-questions ul { list-style: none; padding: 0; margin: 0; }
.hardcoded-questions li { padding: 8px; cursor: pointer; transition: background 0.3s; }
.hardcoded-questions li:hover { background: #f0f0f0; }*/
/* 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 */ padding: 10px; background: rgba(255, 255, 255, 0.1); /* Subtle background */ border-radius: 8px; margin-bottom: 5px; /* Space between questions and input box */ flex-wrap: wrap; /* Allow wrapping on smaller screens */ position: absolute; bottom: 60px; /* Adjust based on text field height */ left: 10px; /* Align to the left side */ width: auto; /* Adjust width dynamically */}
/* Individual question tab */.hardcoded-question { padding: 10px 15px; background: rgba(200, 200, 200, 0.3); /* Light grey faded color */ 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 */ 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 */ }
/* Ensure responsiveness */@media (max-width: 600px) { .hardcoded-questions-container { width: 90%; bottom: 80px; /* Adjust spacing for smaller screens */ left: 10px; /* Keep it left aligned */ }
.hardcoded-question { font-size: 12px; padding: 8px 12px; }}
/*.paragraph-block { background: #2b6296; color: white; padding: 1vw; border-radius: 1vw; margin-bottom: 0.3vw;*/ /* Reduce space between paragraphs */ /*box-shadow: 0 0.3vw 0.8vw rgba(0, 0, 0, 0.1); line-height: 1.5; max-width: 48vw;}*/
/* Message wrapper for each chat bubble */.message-wrapper { display: flex; align-items: flex-start; gap: 1vw; margin-bottom: 1vw; /* Space between each message */}
/* Separate AI and user styles */ .message-wrapper.user { flex-direction: row-reverse; text-align: right; }
.message-wrapper.ai { flex-direction: row; text-align: left; }
/* Profile Picture Styling */.profile-pic { width: 4vw; height: 4vw; border-radius: 50%; overflow: hidden; background-color: #ddd;}
.profile-pic img { width: 100%; height: 100%; object-fit: cover; }
/* Individual Message Styling *//*.message { max-width: 50vw; padding: 1vw 2vw; border-radius: 2vw; font-size: 1.2vw; line-height: 1.5; box-shadow: 0 0.3vw 0.8vw rgba(0, 0, 0, 0.1); background: #2b6296; color: white;}*/
/* Separate paragraph blocks */.ai .message { align-self: flex-start; background: #2b6296; color: white;}
.user .message { align-self: flex-end; background: #2b6296; color: white;}
/* Timestamp Styling */.message-timestamp { font-size: 0.8vw; color: rgba(255, 255, 255, 0.8); margin-top: 0.5vw; display: block; text-align: right;}
.paragraph-block { background: #2b6296; color: white; padding: 1vw; border-radius: 1vw; margin-bottom: 0.5vw; /* ✅ Adjusted for better spacing */ 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; border-radius: 2vw; font-size: 1.2vw; line-height: 1.5; box-shadow: 0 0.3vw 0.8vw rgba(0, 0, 0, 0.1); background: #2b6296; color: white;}
.structured-response { background: #2b6296; color: white; padding: 1vw; border-radius: 1vw; margin-bottom: 0.3vw; /* ✅ Reduced spacing */ box-shadow: 0 0.3vw 0.8vw rgba(0, 0, 0, 0.1); line-height: 1.4; /* ✅ Adjusted line height */ 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 */ }
.structured-response br { display: block; content: ""; margin: 0.2vw 0; /* ✅ Reduce line spacing */ }
/* ✅ 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 */ }
.structured-response ul li, .structured-response ol li { margin-bottom: 0.2vw; /* ✅ Reduced space between list items */ line-height: 1.4; }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
<div class="chat-container"> <div class="header-container"> <div class="logo"> <a (click)="goToHome()" routerLink="/home"> <img src="assets/images/pykara-logo.png" alt="Pykara Logo" /> </a> </div> <div class="header-title"> <h1>Grammar Chat</h1> </div> <div class="home-btn"> <a (click)="goToHome()" routerLink="/home"> <img src="assets/images/home.png" alt="Home" class="home-icon" /> </a> </div> </div>
<div class="chat-box" #chatBox> <img src="assets/images/chat/chatbg.png" alt="Chat Background" class="chat-bg" />
<div *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" /> </div> <div class="message"> {{ message.text }} <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" /> </div> <div class="message structured-response"> <div [innerHTML]="formatStructuredResponse(message.text)"></div> <div class="message-timestamp">{{ message.timestamp }}</div> </div> </div> </div>
<!-- AI typing indicator --> <div *ngIf="isTyping" class="typing-indicator"> AI is typing <span></span> <span></span> <span></span> </div> </div>
<div class="input-container"> <div class="input-box"> <textarea [(ngModel)]="userInput" (focus)="showHardcodedQuestions()" (blur)="hideHardcodedQuestions()" (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" 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> <div class="hardcoded-question" (click)="selectHardcodedQuestion('What are the types of tenses?')">What are the types of tenses?</div> <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>
<!-- Listening Box --> <div class="listening-box" *ngIf="isListening"> <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" /> </button> <button class="close-btn" (click)="stopListening()"> <img src="assets/images/chat/cross.png" alt="Close" /> </button> </div>
<p *ngIf="errorMessage" class="error-text" (click)="openMicrophoneSettings()"> {{ errorMessage }} </p> </div> </div>
<!-- Microphone Access Popup --> <div class="popup-overlay" *ngIf="showMicPopup"> <div class="popup-box"> <h3>Microphone access required</h3> <p>To use voice mode, you'll need to enable your microphone and try again.</p> <button class="popup-button" (click)="closeMicrophonePopup()">OK</button> </div> </div></div>
1234567891011121314151617181920212223import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ChatComponent } from './chat.component';
describe('ChatComponent', () => { let component: ChatComponent; let fixture: ComponentFixture<ChatComponent>;
beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ChatComponent] }) .compileComponents(); fixture = TestBed.createComponent(ChatComponent); component = fixture.componentInstance; fixture.detectChanges(); });
it('should create', () => { expect(component).toBeTruthy(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667import { 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 { 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';
@Component({ selector: 'app-chat', standalone: true, imports: [FormsModule, CommonModule, RouterModule], templateUrl: './chat.component.html', styleUrl: './chat.component.css'})export class ChatComponent implements OnDestroy { showQuestions: boolean = false; // Flag to show hardcoded questions userInput: string = ''; messages: { from: string, text: string, timestamp: string; isPlaying?: boolean }[] = []; isTyping: boolean = false; // Typing indicator @ViewChild('chatBox') chatBox!: ElementRef;
isLoadingSpeech: boolean = false; // ✅ Add this line to fix the error selectedVoice: SpeechSynthesisVoice | null = null; errorMessage: string = ""; recognition: any; // SpeechRecognition object 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 isInputValid: boolean = false; suggestions: string[] = []; // Holds suggested grammar questions showMicPopup: boolean = false;
ngAfterViewChecked() { // Adding a delay for smooth scrolling setTimeout(() => { this.scrollToBottom(); }, 100); // Adjust the timeout if necessary }
// 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) {
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) { this.recognition = new SpeechRecognition(); this.recognition.continuous = false; this.recognition.lang = 'en-US'; this.recognition.interimResults = false;
this.recognition.onresult = (event: any) => { 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.recognition.stop(); this.isListening = false; // Hide the overlay } };
this.recognition.onerror = (event: any) => { console.error('Speech Recognition Error:', event.error); this.isProcessingSpeech = false; // Reset the flag on error }; } 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); } }
openMicrophonePopup(): void { this.showMicPopup = true; }
closeMicrophonePopup(): void { 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 }
// Hide hardcoded questions when user clicks outside hideHardcodedQuestions(): void { setTimeout(() => { this.showQuestions = false; }, 200); // Allow time for click event to register }
selectHardcodedQuestion(question: string): void { this.userInput = question; // Set the selected question this.showQuestions = false; // Hide the hardcoded questions setTimeout(() => { this.sendMessage(); // Send the selected question this.userInput = ''; // Clear the text field after sending }, 100); // Small delay to ensure UI updates before clearing }
getSuggestions(): void { if (!this.userInput || this.userInput.trim().length < 1 || this.isSpeaking) { this.suggestions = []; // Clear suggestions if no input or AI is speaking return; }
this.apiService.getGrammarSuggestions(this.userInput).subscribe( (response) => { 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 } else { this.suggestions = []; } }, (error) => { console.error("Error fetching suggestions:", error); this.suggestions = []; } ); }
// 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 }
sendMessage(inputText?: string): void { const message = inputText ? inputText.trim() : this.userInput.trim(); if (!message) { return; }
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.isTyping = true; this.cdr.detectChanges(); this.scrollToBottom(); // ✅ Scroll after adding user message
this.apiService.askQuestion(message, sessionId).subscribe( (response) => { this.isTyping = false; let explanation = response?.response || 'No explanation available.';
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');
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 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>
return formattedText; }
speakResponse(responseText: string): void { if (!responseText) { console.warn('No response text provided for speech.'); return; }
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
// 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 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) { speech.voice = femaleVoice; console.log("Using voice:", femaleVoice.name); } else { 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 currentWordIndex++; this.cdr.detectChanges(); // Update UI dynamically } };
// 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 this.cdr.detectChanges(); };
// Start speaking console.log('Starting speech synthesis...'); window.speechSynthesis.speak(speech); }
ngOnInit(): void { if (window.speechSynthesis.onvoiceschanged !== undefined) { window.speechSynthesis.onvoiceschanged = () => { this.loadVoices(); }; }
// 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 return; }
console.log("Available Voices:", voices.map(v => v.name)); // Debugging
// ✅ Preferred female voices const preferredVoices = [ "Google UK English Female", "Google US English Female", "Microsoft Zira - English (United States)", // Edge/Windows "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) { this.selectedVoice = foundVoice; break; } }
// 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]; }
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 } }
resumeAudio(): void { if (window.speechSynthesis.paused) { window.speechSynthesis.resume(); this.isAudioPaused = false; console.log('AI Speech Resumed'); this.cdr.detectChanges(); // Update UI } }
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
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices .getUserMedia({ audio: true }) .then(() => { if (this.recognition) { 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 }
// Stop recognition to prevent multiple triggers this.recognition.stop(); this.isListening = false; // Hide the overlay } };
this.recognition.onnomatch = () => alert('No speech detected. Please try again.'); this.recognition.onend = () => { console.log('Speech recognition service disconnected.'); this.isListening = false; }; this.recognition.onerror = (error: any) => { console.error('Speech Recognition Error:', error); this.isListening = false; if (error.error === 'not-allowed') { alert('Microphone permission denied.'); } else if (error.error === 'no-speech') { alert('No speech detected. Please try speaking clearly.'); } }; } else { alert('Speech Recognition is not supported in this browser.'); } }) .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 });
} else { alert('Microphone access is not supported in this browser.'); } }
stopListening(): void { this.isListening = false; // Hide the overlay if (this.recognition) { this.recognition.stop(); // Stop speech recognition } }
// 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
// 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
copyToClipboard(text: string, index: number): void { navigator.clipboard.writeText(text).then(() => { this.copySuccessIndex = index; // Show tick icon for copied message setTimeout(() => { this.copySuccessIndex = null; // Hide tick after 2 seconds }, 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 } else if (this.isSpeaking) { this.pauseAudio(); } else if (this.isAudioPaused) { this.resumeAudio(); } else { this.startListening(); } }
getButtonIcon(): string { if (this.userInput.trim().length > 0) { return 'assets/images/chat/send-icon.png'; // Replace with your send icon image } else if (this.isSpeaking) { return 'assets/images/chat/pause-icon.png'; // Replace with your pause icon image } else if (this.isAudioPaused) { return 'assets/images/chat/resume-icon.png'; // Replace with your resume icon image } else { return 'assets/images/chat/microphone-icon.png'; // Replace with your microphone icon image } }
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 } }
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'; } }
getButtonIconClass(): string { return this.userInput.trim().length > 0 ? 'send-icon' : this.isSpeaking ? 'pause-icon' : this.isAudioPaused ? 'resume-icon' // Class for resume icon : 'microphone-icon'; }
openMicrophoneSettings(): void { const userAgent = navigator.userAgent;
if (userAgent.includes("Chrome")) { window.open("chrome://settings/content/microphone", "_blank"); } else if (userAgent.includes("Firefox")) { window.open("about:preferences#privacy", "_blank"); } else if (userAgent.includes("Edge")) { window.open("edge://settings/content/microphone", "_blank"); } else { alert("Please check your browser's settings to enable the microphone."); } }
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095/* General Styles */body { font-family: 'Roboto', sans-serif; background-color: #f9f9f9; margin: 0; padding: 0;}
/* Header */.header-container { display: flex; justify-content: space-between; align-items: center; padding: 0vw 2vw; background-color: #009688; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); width: 100%; position: sticky; top: 0;}
.logo img { max-width: 5vw; height: auto; background: #fff; border-radius: 1vw; margin: 0.5vw;}
.header-title { font-size: 2.6vw; font-family: Super Cartoon; color: #009688; font-size: 3vw; color: #fff; margin: 0;}
.home-btn img { width: 5vw;}
.home-btn img:hover { transform: scale(1.1); }
/* Background */.imgbgcontainter { background-image: url(/assets/images/grammar-bg.png); background-size: auto; background-position: center; background-attachment: fixed; width: 100%; height: 100%;}
.grammar-bg { position: absolute; top: 10%; left: 0; width: 100%; height: auto; max-height: calc(100vh - 100px); object-fit: fill; z-index: -1; opacity: 0.2;}
/* Responsive Card */.card1 { background: #fff; width: 80vw; /*max-width: 1000px;*/ margin: 4vh auto; padding: 2vw; border: 10px solid #009688; border-radius: 1vw; box-shadow: 0 0.4vw 0.8vw rgba(0, 0, 0, 0.6); position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);}
.content-container { display: flex; flex-direction: row; gap: 2vw; flex-wrap: wrap; justify-content: center; align-items: center;}
.image-container { flex: 1 1 300px; text-align: center;}
.quiz-image { width: 100%; /*max-width: 350px;*/ height: auto; border-radius: 10px;}
.description-container { flex: 1 1 300px;}
h2 { font-size: 2vw; color: #006780; margin-bottom: 1vw; font-weight: 800;}
.description-container p { font-size: 1.2vw; text-align: justify; margin-bottom: 2vw;}
.submit-button { font-size: 1.2vw; padding: 0.8vw 2vw; background-color: #006780; color: white; border: none; border-radius: 0.5vw; cursor: pointer; font-weight: bold;}
.submit-button:hover { background-color: #bdc3c7; box-shadow: 0 12px 16px rgba(0,0,0,0.24), 0 17px 50px rgba(0,0,0,0.19); }
.submit-button:disabled { background-color: #ccc; cursor: not-allowed; }
/* Media Queries for Responsiveness */
@media (max-width: 768px) { .content-container { flex-direction: column; }
h2 { font-size: 5vw; }
.description-container p { font-size: 3.5vw; }
.submit-button { font-size: 3.5vw; padding: 3vw 6vw; height: auto; margin-top: 2vw; }}
@media (max-width: 480px) { .card1 { padding: 5vw; }
.submit-button { width: 100%; font-size: 4vw; }}
/* Game Screen */.game-screen { height: 71vh; display: flex; flex-direction: column; justify-content: space-evenly; background: #fff; width: 85vw; margin: 4vh auto; padding: 2vw; border: 10px solid #009688; border-radius: 1vw; box-shadow: 0 0.4vw 0.8vw rgba(0, 0, 0, 0.6); position: absolute; top: 52%; left: 50%; transform: translate(-50%, -50%);}
/* Game Content Layout */.game-content { display: flex; justify-content: space-between; gap: 2rem; align-items: center;}
/* Cards */.audio-card, .input-card { width: 50%; height: 20vw; padding: 4rem; background-color: #deefef; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); text-align: center; display: flex; flex-direction: column; justify-content: space-between; align-items: center;}
/* Input Wrapper */.input-card { display: flex; flex-direction: column; justify-content: space-between; align-items: center; padding-bottom: 1rem;}
.input-wrapper { width: 100%; display: flex; flex-direction: column; gap: 1rem; align-items: center;}
.input-wrapper input { width: 80%; font-weight: bold; padding: 1rem; border-radius: 8px; border: 2px solid #007bff; font-size: 1.2rem; text-align: center; transition: border-color 0.3s; }
.input-wrapper input:disabled { background-color: #e0e0e0; color: #7a7a7a; border-color: #bdbdbd; cursor: not-allowed; opacity: 0.8; }
/* Green border for correct input */ .input-wrapper input.correct { border: 2px solid #4caf50 !important; /* green */ background-color: #e8f5e9; }
/* Red border for incorrect input */ .input-wrapper input.error { border: 2px solid #f44336 !important; /* red */ background-color: #ffebee; }
.error-message { color: #ff4d4d; font-weight: bold; font-size: 1.1rem; margin-top: 0.5rem; text-align: center;}
/* Submit Button */.submit-btn { width: 85%; background-color: #006780; color: white; font-size: 1rem; padding: 1rem; border: none; border-radius: 8px; cursor: pointer; transition: background-color 0.3s; text-align: center;}
.submit-btn:hover { background-color: #004d5c; }
.submit-btn:disabled { background-color: #cccccc; cursor: not-allowed; }
/* Action Buttons */.action-buttons { width: 100%; display: flex; justify-content: space-between; margin-top: 0.5rem; padding: 0 1rem; align-items: center;}
.left-buttons { display: flex; gap: 10px;}
.right-button { margin-left: auto;}
.action-buttons .btn { padding: 0.8rem 1.5rem; font-size: 1rem; border-radius: 8px; cursor: pointer; transition: background-color 0.3s;}
.info-btn { background-color: #f8c102; color: white; font-weight: bold;}
.info-btn:hover { background-color: #e6a500; }
.next-btn { background-color: #006780; color: white; font-weight: bold;}
.next-btn:hover { background-color: #004d5c; }
.next-btn:disabled { background-color: #cccccc; cursor: not-allowed; }
/* Generate Button Section */.generate-buttons { display: flex; gap: 10px;}
.generate-btn { background-color: #006780; color: white; border: none; padding: 15px 32px; font-size: 1.2vw; border-radius: 0.5vw; cursor: pointer; transition: background-color 0.3s, transform 0.3s; font-weight: bold;}
.generate-btn:disabled { background-color: #cccccc !important; color: #666666; cursor: not-allowed; opacity: 0.7; box-shadow: none; transition: none; }
.extra-btn { background-color: #ff9800; color: white; padding: 0.8rem 1.5rem; font-size: 1rem; border-radius: 8px; cursor: pointer; transition: background-color 0.3s; border: none;}
.extra-btn:hover { background-color: #e68900; }
/* Responsive */@media (max-width: 768px) { .game-content { flex-direction: column; align-items: center; }
.audio-card, .input-card { width: 90%; height: auto; }
.submit-btn, .action-buttons { width: 90%; }
.action-buttons { flex-direction: column; gap: 0.5rem; }}
/* Popup */.popup-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; z-index: 20;}
.popup-content { background-color: #daf5ff; padding: 2vw; border-radius: 8px; text-align: center;}
.popup-content p { font-size: 1vw; margin-bottom: 2vw; color: #004d5c; font-weight: bold; }
@keyframes fadeInCenter { 0% { opacity: 0; transform: translateY(50px); }
100% { opacity: 1; transform: translateY(0); }}
.close-btn { padding: 0.7vw; font-size: 1vw; background-color: #009688; color: white; border: none; border-radius: 8px; cursor: pointer; transition: background-color 0.3s; font-weight: bold;}
.close-btn:hover { background-color: #00796b; }
/* Game Header */.game-header { position: relative; width: 100%; display: flex; justify-content: center; align-items: center; padding-bottom: 1rem;}
.back-btn { position: absolute; left: 0; top: 40%; transform: translateY(-50%); background: transparent; border: none; font-size: 2rem; color: #006780; cursor: pointer; padding: 0 1rem; transition: transform 0.3s; width: 6vw;}
.back-btn:hover { transform: translateY(-50%) scale(1.1); }
.game-title { font-size: 2vw; color: #004d5c; /*font-family: 'Super Cartoon', sans-serif;*/ margin: 0; text-align: center;}
/* Optional: Modify the appearance of the disabled "Sentence" button specifically */.info-btn:disabled { background-color: #b0bec5; /* Light gray color for the disabled button */ color: #757575; /* Dark gray color for text */ cursor: not-allowed; opacity: 0.6;}
/*step 2 left aside css start here*/
/* ===== Step 2: Left Audio Panel — Kid-friendly Player ===== */.audio-card--kids { --primary: #006780; --accent: #009688; --soft: #deefef; --bar: rgba(0, 103, 128, 0.28); --bar-strong: rgba(0, 103, 128, 0.65); background: var(--soft); padding: 2rem; border-radius: 14px; border: 3px solid var(--accent); position: relative;}
.ac-header { width: 100%; display: flex; justify-content: center; margin-bottom: 1rem;}
.ac-generate { border-radius: 999px; font-weight: 700; min-width: 230px; display: inline-flex; align-items: center; gap: 10px; text-align: center; display: flex; justify-content: center;}
.spinner { width: 16px; height: 16px; display: inline-block; border: 3px solid #fff; border-top-color: transparent; border-radius: 50%; animation: spin 0.8s linear infinite;}
@keyframes spin { to { transform: rotate(360deg); }}
.ac-player { display: grid; grid-template-rows: auto auto auto auto; gap: 1rem; place-items: center; padding: 1rem 0 0.5rem;}
.ac-player.is-disabled { opacity: 0.6; filter: grayscale(0.2); }
/* Big circular play button */.play-btn { position: relative; width: 65px; height: 65px; border-radius: 50%; border: none; background: var(--primary); color: #fff; cursor: pointer; box-shadow: 0 8px 20px rgba(0,0,0,0.18); display: grid; place-items: center; transition: transform 0.12s ease, box-shadow 0.2s ease, background 0.3s ease; outline: none;}
.play-btn:disabled { cursor: not-allowed; opacity: 0.7; }
.play-btn:hover:not(:disabled) { transform: translateY(-2px) scale(1.02); }
.play-btn:active:not(:disabled) { transform: translateY(0) scale(0.98); }
.play-btn .icon { width: 40px; height: 40px; fill: #fff; }
.play-btn .pulse { position: absolute; inset: -8px; border-radius: 50%; border: 2px solid var(--primary); opacity: 0.18; transform: scale(0.9); }
.ac-player.is-playing .play-btn .pulse { animation: pulse 1.6s ease-out infinite;}
@keyframes pulse { 0% { transform: scale(0.9); opacity: 0.22; }
70% { transform: scale(1.25); opacity: 0; }
100% { transform: scale(1.25); opacity: 0; }}
/* Wave shell (equalizer bars) */.wave-shell { display: flex; align-items: flex-end; justify-content: center; gap: 6px; height: 46px; width: 80%; max-width: 420px;}
.wave-shell .bar { width: 6px; height: 16px; background: var(--bar); border-radius: 4px; animation: wave 1s ease-in-out infinite; animation-play-state: paused; /* start paused */ }
.ac-player.is-playing .wave-shell .bar { animation-play-state: running;}
@keyframes wave { 0%, 100% { height: 12px; background: var(--bar); }
50% { height: 38px; background: var(--bar-strong); }}
/* Timeline / progress */.timeline { position: relative; height: 10px; width: 80%; max-width: 520px; background: #e9f3f3; border-radius: 999px; overflow: hidden; border: 1px solid rgba(0,0,0,0.06);}
.timeline.is-disabled { opacity: 0.5; }
.timeline .progress { height: 100%; width: 0%; background: linear-gradient(90deg, var(--primary), var(--accent)); border-radius: 999px 0 0 999px; transition: width 0.15s linear; }
/* Time labels */.time { width: 80%; max-width: 520px; display: flex; justify-content: space-between; font-weight: 700; color: #004d5c;}
/* Small helper text */.ac-hint { font-size: 0.95rem; color: #004d5c; background: #ffffffa6; border: 1px dashed var(--accent); padding: 8px 12px; border-radius: 10px;}
/* Responsive */@media (max-width: 768px) { .play-btn { width: 84px; height: 84px; }
.play-btn .icon { width: 34px; height: 34px; }
.wave-shell { width: 92%; }
.timeline, .time { width: 92%; }}
/*step =2 right aside css wstart herwe */
/* === Step 2: Right-side kid panel === */.kid-panel { --primary: #006780; --accent: #009688; --soft: #deefef; background: var(--soft); border: 3px solid var(--accent); border-radius: 14px; padding: 1.2rem 1.4rem 1.4rem; display: flex; flex-direction: column; gap: 0.9rem; position: relative;}
/* top row */.kp-top { display: flex; align-items: center; justify-content: space-between;}
.kp-title { margin: 0; font-size: 1.25rem; color: #004d5c; font-weight: 800;}
/* attempts (hearts) */.kp-attempts .heart { font-size: 1.15rem; margin-left: 6px; transition: opacity 0.25s ease, transform 0.25s ease;
}
.kp-attempts .heart.is-off { opacity: 0.25; transform: scale(0.88); }
/* input with subtle animation */.kp-input-wrap { position: relative; display: grid; place-items: center;}
.kp-input { width: 100%; font-weight: 700; padding: 0.95rem 1rem; border-radius: 10px; border: 2px solid var(--primary); font-size: 1.15rem; text-align: center; background: #fff; box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06); transition: transform 0.1s ease, box-shadow 0.2s ease, border-color 0.3s ease; caret-color: var(--primary);}
.kp-input:focus { outline: none; transform: translateY(-1px); box-shadow: 0 10px 24px rgba(0, 0, 0, 0.1); border-color: var(--accent); }
/* success + error states (reuse your classes) */ .kp-input.correct { border-color: #4caf50 !important; background: #e8f5e9; }
.kp-input.error { border-color: #f44336 !important; background: #ffebee; }
/* pop tick */.ok-badge { position: absolute; right: 8%; top: 50%; transform: translateY(-50%) scale(0.6); animation: okPop 0.6s ease forwards; pointer-events: none;}
.ok-icon { width: 42px; height: 42px; display: block;}
.ok-icon circle { fill: rgba(0, 103, 128, 0.12); stroke: var(--primary); stroke-width: 2; }
.ok-icon path { fill: none; stroke: #2e7d32; stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }
@keyframes okPop { 0% { transform: translateY(-50%) scale(0); opacity: 0; }
60% { transform: translateY(-50%) scale(1.08); opacity: 1; }
100% { transform: translateY(-50%) scale(1); opacity: 1; }}
/* subtle shake on wrong */.kid-panel.is-shake .kp-input { animation: kpShake 0.35s ease;}
@keyframes kpShake { 0%, 100% { transform: translateX(0); }
25% { transform: translateX(-6px); }
50% { transform: translateX(6px); }
75% { transform: translateX(-4px); }}
/* primary submit re-using your color token */.kp-submit { width: 44%; margin: 0 auto; font-weight: 800; letter-spacing: 0.3px; font-size: 1.2vw;}
/* info panel for meaning/example */.info-panel { background: #ffffffd9; border: 1px dashed var(--accent); border-radius: 12px; padding: 0.75rem 1rem; display: flex; flex-direction: column; gap: 0.65rem;}
.info-line { display: grid; grid-template-columns: auto 1fr; align-items: start; gap: 0.6rem;}
.info-chip { background: var(--primary); color: #fff; font-weight: 700; font-size: 0.85rem; padding: 0.25rem 0.55rem; border-radius: 999px; white-space: nowrap;}
.info-text { margin: 0; color: #004d5c; line-height: 1.35rem; font-size: 0.98rem;}
/* responsive tweaks */@media (max-width: 768px) { .kp-title { font-size: 1.05rem; }
.kp-input { width: 92%; font-size: 1.05rem; }
.ok-badge { right: 4%; }
.kp-submit { width: 92%; }}
/* Shared action bar layout */.action-bar { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-top: 10px;}
.action-bar .left-buttons { display: flex; gap: 10px; flex-wrap: wrap; }
/* Base button using your spec */.py-btn { background-color: #006780; color: #ffffff; border: none; padding: 15px 32px; font-size: 1.2vw; /* per your request */ border-radius: 0.5vw; /* per your request */ cursor: pointer; transition: background-color 0.3s, transform 0.3s; font-weight: bold; display: inline-flex; align-items: center; gap: 10px; line-height: 1;}
/* Hover (your spec) */ .py-btn:hover:not(:disabled) { background-color: #18788f; transform: scale(1.05); }
/* Press feedback */ .py-btn:active:not(:disabled) { transform: scale(0.98); }
/* Disabled */ .py-btn:disabled { opacity: 0.55; cursor: not-allowed; transform: none; }
/* Focus ring for keyboard users */ .py-btn:focus-visible { outline: 3px solid #94c7d6; outline-offset: 2px; }
/* Optional tiny icon motion on hover */ .py-btn .btn__icon { display: inline-block; transform: translateY(0); transition: transform 0.25s ease; }
.py-btn:hover:not(:disabled) .btn__icon { transform: translateY(-2px); }
/* Small-screen fallback so 1.5vw does not get too small */@media (max-width: 768px) { .py-btn { font-size: 16px; /* fallback for phones/tablets */ border-radius: 10px; /* visual balance on small screens */ padding: 12px 22px; }}
.close-btn1 { background-color: #ffffff; color: #0097a7; border: none; padding: 0.4vw 0.9vw; border-radius: 50%; cursor: pointer; border: 1px solid black; width: 3vw; top: -5vw; right: -3.5vw; position: absolute; height: 3vw; font-size: 1vw; font-weight: bold;}
/* Clean, static image at the left side (no blur, no animation) */.left-illustration { position: absolute; left: -2vw; top: 50%; transform: translateY(-50%); width: 19vw; height: auto; z-index: 1; pointer-events: none; filter: none !important; image-rendering: auto; image-rendering: -webkit-optimize-contrast; image-rendering: crisp-edges;}
/* Smaller width on narrow screens */@media (max-width: 768px) { .left-illustration { width: 170px; left: 8px; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213<div class="full-container"> <div class="header-container"> <div class="logo"> <a (click)="goToHome()" routerLink="/home"> <img src="assets/images/pykara-logo.png" alt="Pykara Logo" /> </a> </div> <div class="header-title"> <h1>Find the Word</h1> </div> <div class="home-btn"> <a (click)="goToHome()" routerLink="/home"> <img src="assets/images/home.png" alt="Home" class="home-icon" /> </a> </div> </div>
<img src="assets/images/grammar-bg.png" alt="Chat Background" class="grammar-bg" />
<div class="findword-container"> <div *ngIf="step === 1" class="card1"> <div class="content-container"> <div class="image-container"> <img src="assets/images/find_word/4.png" alt="Vocabulary Image" class="quiz-image" /> </div> <div class="description-container"> <h2>Improve Your Word Skills!</h2> <p> Find the Word is a fun and educational activity that helps students improve their listening, spelling, and vocabulary skills. Students hear a word through audio and then type what they hear. They get instant feedback to know if their answer is right or wrong. If needed, they can listen again. The exercise also has buttons to show the word’s meaning and an example sentence. A reset option lets students try again. This activity helps students practice listening and writing skills in an easy and engaging way, making learning more enjoyable and effective. </p> <button (click)="startGame()" class="submit-button">Start Learning</button> </div> </div> </div>
<div *ngIf="step === 2" class="game-screen"> <div class="game-header"> <img src="assets/images/back.png" alt="Go Back" class="back-btn" (click)="goBack()" /> <h2 class="game-title">Listen & Type</h2> <!--<img class="wave-photo" src="assets/images/find_word/audio.png" alt="Learning image">--> <button class="close-btn1" (click)=" closeToStart()" aria-label="Close">✖</button> </div>
<div class="game-content">
<!-- Audio Section --> <!-- Audio Section (Left) --> <div class="audio-card audio-card--kids"> <div class="ac-header"> <button (click)="fetchAudio()" [disabled]="isGenerateDisabled" class="btn generate-btn ac-generate" aria-label="Generate a new question"> <span *ngIf="!isLoading">Generate audio</span> <!-- <span *ngIf="isLoading" class="spinner" aria-hidden="true"></span>--> <span *ngIf="isLoading">Generating</span> </button> </div> <!-- Left mascot (decorative) --> <img class="left-illustration" src="assets/images/find_word/audio.png" alt="" /> <!-- Player Shell --> <div class="ac-player" [class.is-disabled]="!audioUrl" [class.is-playing]="isPlaying"> <button class="play-btn" [disabled]="!audioUrl" (click)="togglePlayback()" [attr.aria-pressed]="isPlaying" [attr.aria-label]="isPlaying ? 'Pause audio' : 'Play audio'"> <!-- Inline SVG icons (no external deps) --> <svg *ngIf="!isPlaying" viewBox="0 0 24 24" class="icon"> <path d="M8 5v14l11-7z"></path> </svg> <svg *ngIf="isPlaying" viewBox="0 0 24 24" class="icon"> <path d="M6 5h4v14H6zM14 5h4v14h-4z"></path> </svg> <span class="pulse" aria-hidden="true"></span> </button>
<!-- Wave shell (animated bars while playing) --> <div class="wave-shell" aria-hidden="true"> <span class="bar" *ngFor="let b of bars; let i = index" [style.animation-delay.ms]="(i%6)*120"></span> </div>
<!-- Timeline --> <div class="timeline" [class.is-disabled]="!audioUrl"> <div class="progress" [style.width.%]="progress"></div> </div>
<div class="ac-hint" *ngIf="!audioUrl"> Tap <strong>Generate audio</strong> to load the audio. </div> </div>
<!-- Keep the audio element; wire player events --> <audio #audioPlayer (timeupdate)="onTimeUpdate()" (ended)="onAudioEnded()" (loadedmetadata)="onLoadedMeta()" hidden> <source [src]="audioUrl" type="audio/mp3" /> Your browser does not support the audio tag. </audio> </div>
<!-- RIGHT SIDE: Kid-friendly input panel --> <div class="input-card kid-panel" [class.is-correct]="isCorrect" [class.is-shake]="ui.shake">
<!-- Top row: title + attempts --> <div class="kp-top"> <h3 class="kp-title">Type the word</h3>
<!-- Attempts with hearts --> <div class="kp-attempts" aria-label="Attempts left"> <span class="heart" [class.is-off]="attemptsLeft < 1"></span> <span class="heart" [class.is-off]="attemptsLeft < 2"></span> <span class="heart" [class.is-off]="attemptsLeft < 3"></span> </div> </div>
<!-- Input + success badge --> <div class="kp-input-wrap"> <input type="text" class="kp-input" [(ngModel)]="userInput" [disabled]="!audioFinished" (ngModelChange)="onInputChange()" placeholder="Type what you heard" [ngClass]="{ 'correct': isCorrect, 'error': !isCorrect && validationMessage }" />
<!-- Pop tick on correct --> <div class="ok-badge" *ngIf="isCorrect || ui?.pulseOk" aria-hidden="true"> <svg viewBox="0 0 24 24" class="ok-icon"> <circle cx="12" cy="12" r="10"></circle> <path d="M7 12l3 3 7-7"></path> </svg> </div> </div>
<!-- Validation message (only when needed) --> <p *ngIf="validationMessage" class="error-message">{{ validationMessage }}</p>
<!-- Primary action --> <button (click)="validateWord()" [disabled]="!canSubmit || attemptsLeft === 0" class="btn submit-btn kp-submit"> Submit </button>
<div class="action-bar"> <div class="left-buttons"> <button class="py-btn" (click)="showMeaningPanel()" [disabled]="isMeaningButtonDisabled"> <span class="btn__icon" aria-hidden="true">📘</span> <span>Meaning</span> </button>
<button class="py-btn" (click)="showSentencePanel()" [disabled]="isExampleButtonDisabled"> <span class="btn__icon" aria-hidden="true">✍️</span> <span>Example</span> </button> </div>
<button class="py-btn" (click)="nextQuestion()" [disabled]="attemptsLeft > 0 && !isCorrect"> <span class="btn__icon" aria-hidden="true">⟲</span> <span>Reset</span> </button> </div>
</div>
</div> </div>
<div *ngIf="isPopupVisible" class="popup-overlay"> <div class="popup-content"> <p>{{ popupMessage }}</p> <button class="btn close-btn" (click)="closePopup()">Close</button> </div> </div> </div></div>1234567891011121314151617181920212223import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FindwordComponent } from './findword.component';
describe('FindwordComponent', () => { let component: FindwordComponent; let fixture: ComponentFixture<FindwordComponent>;
beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [FindwordComponent] }) .compileComponents(); fixture = TestBed.createComponent(FindwordComponent); component = fixture.componentInstance; fixture.detectChanges(); });
it('should create', () => { expect(component).toBeTruthy(); });});.editorconfigAdded+16
.gitattributesAdded+12
.gitignoreAdded+42
.vscode/extensions.jsonAdded+4
.vscode/launch.jsonAdded+19
.vscode/tasks.jsonAdded+42
GrammAI.esprojAdded+10
GrammAI.esproj.userAdded+8
README.mdAdded+38
angular.jsonAdded+110
canvas-confetti.d.tsAdded+1
karma.conf.jsAdded+44
nuget.configAdded+10
obj/Debug/GrammAI.esproj.CoreCompileInputs.cacheAdded
obj/Debug/GrammAI.esproj.FileListAbsolute.txtAdded+6
package-lock.jsonAdded
package.jsonAdded+48
src/app/app-routing.module.tsAdded+52
src/app/app.component.cssAdded+12
src/app/app.component.htmlAdded+2
src/app/app.component.spec.tsAdded+35
src/app/app.component.tsAdded+20
src/app/app.module.tsAdded+56
src/app/auth/auth.component.cssAdded+211
src/app/auth/auth.component.htmlAdded+101
src/app/auth/auth.component.spec.tsAdded+23
src/app/auth/auth.component.tsAdded+55
src/app/auth/auth.guard.spec.tsAdded+17
src/app/auth/auth.guard.tsAdded+30
src/app/auth/auth.service.spec.tsAdded+16
src/app/auth/auth.service.tsAdded+188
src/app/auth/root-redirect.guard.spec.tsAdded+17
src/app/auth/root-redirect.guard.tsAdded+29
src/app/authentication/authentication.component.cssAdded+133
src/app/authentication/authentication.component.htmlAdded+47
src/app/authentication/authentication.component.spec.tsAdded+23
src/app/authentication/authentication.component.tsAdded+47
src/app/authentication/authentication.guard.spec.tsAdded+17
src/app/authentication/authentication.guard.tsAdded+24
src/app/authentication/authentication.service.spec.tsAdded+16
src/app/authentication/authentication.service.tsAdded+203
src/app/chat/api.service.spec.tsAdded+16
src/app/chat/api.service.tsAdded+81
src/app/chat/chat.component.cssAdded+960
src/app/chat/chat.component.htmlAdded+127
src/app/chat/chat.component.spec.tsAdded+23
src/app/chat/chat.component.tsAdded+667
src/app/findword/findword.component.cssAdded+1095
src/app/findword/findword.component.htmlAdded+213
src/app/findword/findword.component.spec.tsAdded+23