From d22cd65e28c85fb7a5ea9dd914f9d99fc887319f Mon Sep 17 00:00:00 2001 From: PeymanHonarjoo Date: Tue, 6 Oct 2026 17:27:52 +0330 Subject: [PATCH] feat(ui): implement voice interaction and enhanced home page animations Introduces a comprehensive voice interaction system and upgrades the home page experience with dynamic typing effects and improved layout transitions. Key changes: - Added `MicrophoneService` for managing media stream lifecycle and permissions. - Added `SpeechRecognitionService` for continuous speech-to-text processing. - Added `VoiceOrbService` using Three.js to render an animated audio-reactive orb. - Enhanced `HomePage` with a randomized typing effect for welcome titles and improved state management for message transitions. - Refactored `AiChatInputComponent` to support seamless switching between text composer and voice recording modes. - Improved `SidebarComponent` navigation logic and styling. - Updated global styles and component CSS for better theme consistency and smoother animations. --- src/app/layout/layout.component.html | 2 +- src/app/layout/layout.component.ts | 2 +- src/app/pages/home/home.page.css | 143 ++++- src/app/pages/home/home.page.html | 40 +- src/app/pages/home/home.page.ts | 107 +++- src/app/pages/settings/settings.page.css | 7 +- .../services/microphone/microphone.service.ts | 85 +++ .../speech-recognition.service.ts | 337 +++++++++++ .../services/voice-orb/voice-orb.service.ts | 378 ++++++------ .../ai-chat-input/ai-chat-input.component.css | 312 ++++++++-- .../ai-chat-input.component.html | 237 ++++---- .../ai-chat-input/ai-chat-input.component.ts | 550 ++++++++++++++---- .../shared/ui/sidebar/sidebar.component.css | 3 +- .../shared/ui/sidebar/sidebar.component.html | 1 + .../shared/ui/sidebar/sidebar.component.ts | 1 + src/styles.css | 9 +- 16 files changed, 1736 insertions(+), 478 deletions(-) create mode 100644 src/app/services/microphone/microphone.service.ts create mode 100644 src/app/services/speech-recognition/speech-recognition.service.ts diff --git a/src/app/layout/layout.component.html b/src/app/layout/layout.component.html index 7f1d709..1cbdacf 100644 --- a/src/app/layout/layout.component.html +++ b/src/app/layout/layout.component.html @@ -3,7 +3,7 @@ [isOpen]="sidebarOpen()" [chatHistory]="chatHistory()" (close)="sidebarOpen.set(false)" - (navClick)="sidebarOpen.set(false)" + (navClick)="sidebarOpen.set(true)" (open)="sidebarOpen.set(true)" (profileClick)="onProfile()" (logoutClick)="onLogout()" diff --git a/src/app/layout/layout.component.ts b/src/app/layout/layout.component.ts index 513c484..ac0e068 100644 --- a/src/app/layout/layout.component.ts +++ b/src/app/layout/layout.component.ts @@ -17,7 +17,7 @@ export class LayoutComponent { private readonly authService = inject(AuthService); private readonly themeService = inject(ThemeService); - readonly sidebarOpen = signal(false); + readonly sidebarOpen = signal(true); readonly chatHistory = signal([]); readonly isDarkMode = this.themeService.isDarkMode; diff --git a/src/app/pages/home/home.page.css b/src/app/pages/home/home.page.css index 263d522..f5886b4 100644 --- a/src/app/pages/home/home.page.css +++ b/src/app/pages/home/home.page.css @@ -3,19 +3,69 @@ flex-direction: column; align-items: center; justify-content: center; - min-height: 100%; + min-height: 100vh; padding: 2rem 1rem; + transition: padding 0.4s ease; + position: relative; + background: + radial-gradient(ellipse 50% 40% at 50% 45%, rgba(59, 130, 246, 0.1), transparent 70%), + var(--app-bg); +} + +.home-page::before { + content: ''; + position: absolute; + inset: 0; + background: + radial-gradient(circle at 50% 40%, rgba(59, 130, 246, 0.07), transparent 55%), + radial-gradient(circle at 35% 55%, rgba(99, 102, 241, 0.05), transparent 50%), + radial-gradient(circle at 65% 50%, rgba(59, 130, 246, 0.04), transparent 45%); + pointer-events: none; + z-index: 0; +} + +.home-page > .home-content { + position: relative; + z-index: 1; +} + +.home-page.has-messages { + justify-content: flex-end; + padding-bottom: 2rem; + background: var(--app-bg); +} + +.home-page.has-messages::before { + opacity: 0; +} + +.home-header { + position: absolute; + top: 2rem; + left: 50%; + transform: translateX(-50%); + text-align: center; + transition: + opacity 0.35s ease, + transform 0.35s ease, + margin 0.35s ease; + opacity: 1; +} + +.home-page.has-messages .home-header { + opacity: 0; + transform: translateX(-50%) translateY(-8px); + pointer-events: none; +} + +.home-page.has-messages .home-title { + opacity: 0; + pointer-events: none; } .home-content { width: 100%; max-width: 800px; - margin: 0 auto; -} - -.home-header { - text-align: center; - margin-bottom: 2rem; } .home-icon-wrapper { @@ -38,18 +88,57 @@ } .home-title { - font-size: 1.75rem; - font-weight: 600; + width: 100%; + margin: 0 0 1rem; + + display: flex; + align-items: center; + justify-content: center; + + text-align: center; + direction: rtl; + + font-size: 1.5rem; + font-weight: 400; + line-height: 1.5; color: var(--text-primary); - margin: 0 0 0.5rem; - line-height: 1.3; } -.home-subtitle { - font-size: 0.9375rem; - color: var(--text-muted); - margin: 0; - line-height: 1.5; +.home-title-text { + white-space: pre-wrap; +} + +.cursor { + display: inline-block; + + width: 2px; + height: 1.15em; + + margin-right: 3px; + + background-color: var(--text-primary); + + border-radius: 1px; + + animation: cursorBlink 0.8s ease-in-out infinite; + + flex-shrink: 0; +} + +.cursor-hidden { + display: none; +} + +@keyframes cursorBlink { + 0%, + 45% { + opacity: 1; + } + + 46%, + 100% { + opacity: 0; + } } @media (max-width: 640px) { @@ -57,14 +146,17 @@ padding: 1.25rem 0.75rem; } + .home-page.has-messages { + padding-bottom: 1.25rem; + } + .home-header { - margin-bottom: 1.25rem; + top: 1.25rem; } .home-icon-wrapper { width: 100px; height: 100px; - margin-bottom: 1.25rem; padding: 0.5rem; } @@ -76,10 +168,6 @@ .home-title { font-size: 1.375rem; } - - .home-subtitle { - font-size: 0.875rem; - } } @media (prefers-reduced-motion: reduce) { @@ -90,3 +178,14 @@ animation: none !important; } } + +@keyframes fadeInUp { + from { + opacity: 0; + transform: translateY(20px); + } + to { + opacity: 1; + transform: translateY(0); + } +} diff --git a/src/app/pages/home/home.page.html b/src/app/pages/home/home.page.html index 7034df8..4ba7612 100644 --- a/src/app/pages/home/home.page.html +++ b/src/app/pages/home/home.page.html @@ -1,22 +1,36 @@ -
-
-
-
- -
-

دستیار هوشمند

-

سوال خود را بپرسید، من اینجا هستم

+
+ +
+
+
+
+ +
+ +

+ + {{ streamedText() }} + + + +

+
-
+
\ No newline at end of file diff --git a/src/app/pages/home/home.page.ts b/src/app/pages/home/home.page.ts index d9eade3..225e5a5 100644 --- a/src/app/pages/home/home.page.ts +++ b/src/app/pages/home/home.page.ts @@ -1,7 +1,30 @@ -import { ChangeDetectionStrategy, Component, inject } from '@angular/core'; +import { + ChangeDetectionStrategy, + Component, + inject, + signal, + OnInit, + OnDestroy, +} from '@angular/core'; import { CommonModule } from '@angular/common'; import { AiChatInputComponent } from '../../shared/ui/ai-chat-input/ai-chat-input.component'; +import { Router, NavigationEnd } from '@angular/router'; +import { filter } from 'rxjs/operators'; import { ThemeService } from '../../services/theme/theme.service'; +import { Subscription } from 'rxjs'; + +const HOME_TITLES = [ + 'چه چیزی می‌خواهید بدانید؟...', + 'سوالتان را بپرسید، با شما هستم...', + 'هر سوالی دارید، از من بپرسید...', + 'از هر چیزی که می‌خواهید شروع کنید...', + 'سوالتان را مطرح کنید، پاسخ می‌دهم...', + 'بپرسید؛ با هم به پاسخ می‌رسیم...', + 'هر سوالی در ذهن دارید، بپرسید...', + 'دنبال یک پاسخ دقیق هستید؟...', + 'سوالتان را همین‌جا مطرح کنید...', + 'آماده‌ام به سوالتان پاسخ بدهم...', +]; @Component({ selector: 'app-home', @@ -11,14 +34,92 @@ import { ThemeService } from '../../services/theme/theme.service'; templateUrl: './home.page.html', styleUrl: './home.page.css', }) -export class HomePage { +export class HomePage implements OnInit, OnDestroy { private readonly themeService = inject(ThemeService); + private readonly router = inject(Router); readonly isDarkMode = this.themeService.isDarkMode; - readonly logoSrc = () => this.isDarkMode() ? 'assets/images/RaymandLogo.png' : 'assets/images/login.png'; + readonly logoSrc = () => + this.isDarkMode() ? 'assets/images/RaymandLogo.png' : 'assets/images/login.png'; + + readonly hasMessages = signal(false); + + readonly homeTitle = signal(''); + readonly streamedText = signal(''); + readonly isStreaming = signal(false); + + private typingTimer: ReturnType | null = null; + private routerSubscription?: Subscription; + + constructor() { + this.routerSubscription = this.router.events + .pipe(filter((event) => event instanceof NavigationEnd)) + .subscribe((event: NavigationEnd) => { + if (event.url === '/' || event.url === '') { + this.hasMessages.set(false); + this.setRandomTitle(); + } + }); + } + + ngOnInit(): void { + this.setRandomTitle(); + } + + ngOnDestroy(): void { + this.stopTyping(); + this.routerSubscription?.unsubscribe(); + } + + private setRandomTitle(): void { + this.stopTyping(); + + const index = Math.floor(Math.random() * HOME_TITLES.length); + const title = HOME_TITLES[index]; + + this.homeTitle.set(title); + this.startTyping(title); + } + + private startTyping(text: string): void { + this.streamedText.set(''); + this.isStreaming.set(true); + + let index = 0; + + const typeNextCharacter = () => { + if (index >= text.length) { + this.streamedText.set(text); + this.isStreaming.set(false); + this.typingTimer = null; + return; + } + + index++; + + this.streamedText.set(text.substring(0, index)); + + // Slightly random timing makes it feel more natural + const delay = 12 + Math.random() * 8; + + this.typingTimer = setTimeout(typeNextCharacter, delay); + }; + + typeNextCharacter(); + } + + private stopTyping(): void { + if (this.typingTimer !== null) { + clearTimeout(this.typingTimer); + this.typingTimer = null; + } + + this.isStreaming.set(false); + } onMessageSent(message: string): void { + this.hasMessages.set(true); console.log('Message sent:', message); } diff --git a/src/app/pages/settings/settings.page.css b/src/app/pages/settings/settings.page.css index 2ab4558..002c44e 100644 --- a/src/app/pages/settings/settings.page.css +++ b/src/app/pages/settings/settings.page.css @@ -1,5 +1,8 @@ .settings-page { min-height: 100vh; + display: flex; + flex-direction: column; + justify-content: center; } .settings-header { @@ -104,7 +107,9 @@ } .setting-item { - animation: fadeInUp 0.4s ease-out; + opacity: 0; + transform: translateY(20px); + animation: fadeInUp 0.4s ease-out forwards; } .setting-item:nth-child(1) { animation-delay: 0.05s; } diff --git a/src/app/services/microphone/microphone.service.ts b/src/app/services/microphone/microphone.service.ts new file mode 100644 index 0000000..b26ad4f --- /dev/null +++ b/src/app/services/microphone/microphone.service.ts @@ -0,0 +1,85 @@ +import { Injectable } from '@angular/core'; + +export type MicrophoneErrorCode = 'unsupported' | 'denied' | 'unavailable' | 'unknown'; + +export class MicrophoneError extends Error { + constructor(readonly code: MicrophoneErrorCode, message?: string) { + super(message ?? code); + this.name = 'MicrophoneError'; + } +} + +/** + * Owns the microphone MediaStream. It does nothing except capture: + * the orb (audio level) and speech recognition consume it separately. + */ +@Injectable({ providedIn: 'root' }) +export class MicrophoneService { + private stream: MediaStream | null = null; + private endedCleanup: (() => void) | null = null; + + /** `mediaDevices` is undefined on non-secure (http) origins other than localhost. */ + get isSupported(): boolean { + return typeof navigator !== 'undefined' && !!navigator.mediaDevices?.getUserMedia; + } + + /** + * Requests microphone permission and returns the stream. + * @param onEnded called if the capture track ends unexpectedly (e.g. device unplugged). + */ + async request(onEnded?: () => void): Promise { + if (!this.isSupported) { + throw new MicrophoneError('unsupported'); + } + + this.release(); + + let stream: MediaStream; + try { + stream = await navigator.mediaDevices.getUserMedia({ audio: true }); + } catch (err) { + throw this.mapError(err); + } + + this.stream = stream; + + const track = stream.getAudioTracks()[0]; + if (track && onEnded) { + const handler = (): void => onEnded(); + track.addEventListener('ended', handler); + this.endedCleanup = () => track.removeEventListener('ended', handler); + } + + return stream; + } + + /** Stops every track of the given stream (defaults to the current one). */ + release(stream: MediaStream | null = this.stream): void { + if (!stream) return; + + if (stream === this.stream) { + this.endedCleanup?.(); + this.endedCleanup = null; + this.stream = null; + } + stream.getTracks().forEach((track) => track.stop()); + } + + private mapError(err: unknown): MicrophoneError { + const name = err instanceof DOMException ? err.name : ''; + switch (name) { + case 'NotAllowedError': + case 'SecurityError': + case 'PermissionDeniedError': + return new MicrophoneError('denied'); + case 'NotFoundError': + case 'DevicesNotFoundError': + case 'NotReadableError': + case 'TrackStartError': + case 'OverconstrainedError': + return new MicrophoneError('unavailable'); + default: + return new MicrophoneError('unknown'); + } + } +} \ No newline at end of file diff --git a/src/app/services/speech-recognition/speech-recognition.service.ts b/src/app/services/speech-recognition/speech-recognition.service.ts new file mode 100644 index 0000000..3ebf1d5 --- /dev/null +++ b/src/app/services/speech-recognition/speech-recognition.service.ts @@ -0,0 +1,337 @@ +import { Injectable, NgZone, inject } from '@angular/core'; + +/* Minimal typings: SpeechRecognition is not part of TypeScript's lib.dom. */ +interface SpeechRecognitionAlternativeLike { + transcript: string; +} +interface SpeechRecognitionResultLike { + readonly isFinal: boolean; + readonly length: number; + [index: number]: SpeechRecognitionAlternativeLike; +} +interface SpeechRecognitionEventLike { + readonly resultIndex: number; + readonly results: { readonly length: number; [index: number]: SpeechRecognitionResultLike }; +} +interface SpeechRecognitionErrorEventLike { + readonly error: string; +} +interface SpeechRecognitionLike { + lang: string; + continuous: boolean; + interimResults: boolean; + maxAlternatives: number; + onresult: ((event: SpeechRecognitionEventLike) => void) | null; + onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null; + onend: (() => void) | null; + onspeechend: (() => void) | null; + start(): void; + stop(): void; + abort(): void; +} +type SpeechRecognitionCtor = new () => SpeechRecognitionLike; + +export const DEFAULT_SPEECH_LANGUAGE = 'fa-IR'; + +export type SpeechErrorKind = + | 'permission-denied' + | 'audio-capture' + | 'network' + | 'no-speech' + | 'language-not-supported' + | 'unsupported' + | 'unknown'; + +export interface SpeechTranscript { + /** Confirmed text for the whole session (never contains duplicates). */ + final: string; + /** Text still being recognized; may change or disappear on the next event. */ + interim: string; +} + +export interface SpeechSessionHandlers { + onTranscript(transcript: SpeechTranscript): void; + onSpeechEnd?(): void; + /** Fatal errors only. The session is already over when this is called. */ + onError(kind: SpeechErrorKind): void; +} + +/** Silent restarts allowed (Chrome ends sessions after pauses) before reporting "no speech". */ +const MAX_SILENT_RESTARTS = 4; +const RESTART_DELAY_MS = 250; +const STOP_TIMEOUT_MS = 1500; + +@Injectable({ providedIn: 'root' }) +export class SpeechRecognitionService { + private readonly ngZone = inject(NgZone); + private readonly ctor: SpeechRecognitionCtor | null = this.resolveCtor(); + + private recognition: SpeechRecognitionLike | null = null; + private handlers: SpeechSessionHandlers | null = null; + private lang = DEFAULT_SPEECH_LANGUAGE; + private running = false; + + private finalText = ''; + private interimText = ''; + private silentRestarts = 0; + + private restartTimer: ReturnType | null = null; + private stopTimer: ReturnType | null = null; + private stopResolver: ((text: string) => void) | null = null; + + get isSupported(): boolean { + return this.ctor !== null; + } + + /** Final + interim text right now. */ + currentText(): string { + return this.join(this.finalText, this.interimText); + } + + /** Starts a continuous session. Returns false if it could not be started. */ + start(lang: string, handlers: SpeechSessionHandlers): boolean { + if (!this.ctor) return false; + + this.abort(); + + this.lang = lang || DEFAULT_SPEECH_LANGUAGE; + this.handlers = handlers; + this.finalText = ''; + this.interimText = ''; + this.silentRestarts = 0; + this.running = true; + + if (!this.startRecognition()) { + this.abort(); + return false; + } + return true; + } + + /** + * Stops listening and resolves with the confirmed text, including any + * interim text the engine had not finalized yet. + */ + stop(): Promise { + this.clearRestartTimer(); + this.running = false; + + const recognition = this.recognition; + if (!recognition) { + return Promise.resolve(this.promoteInterim()); + } + + return new Promise((resolve) => { + this.stopResolver = resolve; + this.stopTimer = setTimeout(() => this.resolveStop(true), STOP_TIMEOUT_MS); + try { + recognition.stop(); // late final results still arrive via onresult, then onend + } catch { + this.resolveStop(true); + } + }); + } + + /** Immediately terminates the session and discards callbacks. */ + abort(): void { + this.running = false; + this.clearRestartTimer(); + if (this.stopTimer) { + clearTimeout(this.stopTimer); + this.stopTimer = null; + } + + const resolver = this.stopResolver; + this.stopResolver = null; + + this.detachRecognition(true); + this.handlers = null; + resolver?.(this.promoteInterim()); + } + + dispose(): void { + this.abort(); + } + + // --------------------------------------------------------------------------- + + private startRecognition(): boolean { + if (!this.ctor) return false; + + const recognition = new this.ctor(); + recognition.lang = this.lang; + recognition.continuous = true; + recognition.interimResults = true; + recognition.maxAlternatives = 1; + + recognition.onresult = (event) => this.handleResult(event); + recognition.onerror = (event) => this.handleError(event); + recognition.onspeechend = () => this.emit((h) => h.onSpeechEnd?.()); + recognition.onend = () => this.handleEnd(); + + this.recognition = recognition; + try { + recognition.start(); + return true; + } catch { + this.recognition = null; + return false; + } + } + + private handleResult(event: SpeechRecognitionEventLike): void { + // Entries before resultIndex were delivered (and finalized) in earlier events, + // so only entries from resultIndex onward are processed: no duplicated words. + let interim = ''; + for (let i = event.resultIndex; i < event.results.length; i++) { + const result = event.results[i]; + const text = (result[0]?.transcript ?? '').trim(); + if (!text) continue; + + if (result.isFinal) { + this.finalText = this.join(this.finalText, text); + } else { + interim = this.join(interim, text); + } + } + + this.interimText = interim; + this.silentRestarts = 0; + this.emitTranscript(); + } + + private handleError(event: SpeechRecognitionErrorEventLike): void { + switch (event.error) { + case 'no-speech': // not fatal: onend decides whether to restart + case 'aborted': + return; + case 'not-allowed': + case 'service-not-allowed': + this.fail('permission-denied'); + return; + case 'audio-capture': + this.fail('audio-capture'); + return; + case 'network': + this.fail('network'); + return; + case 'language-not-supported': + this.fail('language-not-supported'); + return; + default: + this.fail('unknown'); + } + } + + private handleEnd(): void { + if (this.stopResolver) { + this.resolveStop(false); + return; + } + if (!this.running) return; + + // The engine ended on its own (pause, timeout, ...): keep what we have and restart. + this.detachRecognition(false); + this.promoteInterim(); + this.emitTranscript(); + + this.silentRestarts++; + if (this.silentRestarts > MAX_SILENT_RESTARTS) { + this.fail('no-speech'); + return; + } + + this.restartTimer = setTimeout(() => { + this.restartTimer = null; + if (this.running && !this.startRecognition()) { + this.fail('unknown'); + } + }, RESTART_DELAY_MS); + } + + private fail(kind: SpeechErrorKind): void { + const handlers = this.handlers; + this.running = false; + this.clearRestartTimer(); + this.detachRecognition(true); + this.emitWith(handlers, (h) => h.onError(kind)); + } + + private resolveStop(abortEngine: boolean): void { + if (this.stopTimer) { + clearTimeout(this.stopTimer); + this.stopTimer = null; + } + const resolver = this.stopResolver; + this.stopResolver = null; + + const text = this.promoteInterim(); + this.detachRecognition(abortEngine); + resolver?.(text); + } + + /** Commits interim text to final text (used when a session ends mid-phrase). */ + private promoteInterim(): string { + if (this.interimText) { + this.finalText = this.join(this.finalText, this.interimText); + this.interimText = ''; + } + return this.finalText; + } + + private detachRecognition(abortEngine: boolean): void { + const recognition = this.recognition; + this.recognition = null; + if (!recognition) return; + + recognition.onresult = null; + recognition.onerror = null; + recognition.onend = null; + recognition.onspeechend = null; + if (abortEngine) { + try { + recognition.abort(); + } catch { + /* already stopped */ + } + } + } + + private clearRestartTimer(): void { + if (this.restartTimer) { + clearTimeout(this.restartTimer); + this.restartTimer = null; + } + } + + private emitTranscript(): void { + const transcript: SpeechTranscript = { final: this.finalText, interim: this.interimText }; + this.emit((h) => h.onTranscript(transcript)); + } + + private emit(fn: (handlers: SpeechSessionHandlers) => void): void { + this.emitWith(this.handlers, fn); + } + + /** Speech events may fire outside Angular's zone; always hand results back inside it. */ + private emitWith( + handlers: SpeechSessionHandlers | null, + fn: (handlers: SpeechSessionHandlers) => void, + ): void { + if (!handlers) return; + this.ngZone.run(() => fn(handlers)); + } + + private join(a: string, b: string): string { + return a && b ? `${a} ${b}` : a || b; + } + + private resolveCtor(): SpeechRecognitionCtor | null { + if (typeof window === 'undefined') return null; + const w = window as unknown as { + SpeechRecognition?: SpeechRecognitionCtor; + webkitSpeechRecognition?: SpeechRecognitionCtor; + }; + return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null; + } +} \ No newline at end of file diff --git a/src/app/services/voice-orb/voice-orb.service.ts b/src/app/services/voice-orb/voice-orb.service.ts index c8869f5..2c179de 100644 --- a/src/app/services/voice-orb/voice-orb.service.ts +++ b/src/app/services/voice-orb/voice-orb.service.ts @@ -1,57 +1,77 @@ import { Injectable, NgZone, inject } from '@angular/core'; import * as THREE from 'three'; +import { mergeVertices } from 'three/examples/jsm/utils/BufferGeometryUtils.js'; +/** Icosphere subdivision. 20 → ~4.4k shared vertices: smooth and cheap to deform every frame. */ +const ORB_DETAIL = 20; +const FALLBACK_SIZE = 260; + +/** + * Renders the animated voice orb and derives an audio level from a MediaStream. + * It never requests the microphone itself: MicrophoneService owns the stream, + * this service only analyses it (attachStream / detachAudio). + */ @Injectable({ providedIn: 'root' }) export class VoiceOrbService { + private readonly ngZone = inject(NgZone); + private readonly reducedMotion = + typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches; + private scene: THREE.Scene | null = null; private camera: THREE.PerspectiveCamera | null = null; private renderer: THREE.WebGLRenderer | null = null; private orb: THREE.Mesh | null = null; - private orbGeometry: THREE.IcosahedronGeometry | null = null; + private orbGeometry: THREE.BufferGeometry | null = null; private glowShell: THREE.Mesh | null = null; private originalPositions: Float32Array | null = null; + private resizeObserver: ResizeObserver | null = null; private animationId: number | null = null; + private audioContext: AudioContext | null = null; private analyser: AnalyserNode | null = null; - private mediaStream: MediaStream | null = null; - private audioDataArray: Uint8Array | null = null; - private isListening = false; - private readonly reducedMotion: boolean; + private sourceNode: MediaStreamAudioSourceNode | null = null; + private audioData: Uint8Array | null = null; + private smoothedLevel = 0; - constructor(private readonly ngZone: NgZone) { - this.reducedMotion = typeof window !== 'undefined' - && window.matchMedia('(prefers-reduced-motion: reduce)').matches; - } - - init(container: HTMLElement): void { - if (this.scene) { - if (this.renderer && this.renderer.domElement.parentNode !== container) { + /** + * Creates the scene once and reuses it on later calls (re-attaching the canvas if needed). + * Returns false if WebGL is unavailable so the caller can show a fallback. + */ + init(container: HTMLElement): boolean { + if (this.scene && this.renderer) { + if (this.renderer.domElement.parentNode !== container) { container.appendChild(this.renderer.domElement); } this.resize(container); - return; + return true; } - const width = container.clientWidth || 280; - const height = container.clientHeight || 280; + const width = container.clientWidth || FALLBACK_SIZE; + const height = container.clientHeight || FALLBACK_SIZE; + + let renderer: THREE.WebGLRenderer; + try { + renderer = new THREE.WebGLRenderer({ + antialias: true, + alpha: true, + powerPreference: 'high-performance', + }); + } catch (err) { + console.warn('VoiceOrbService: WebGL is not available.', err); + return false; + } + + this.renderer = renderer; + renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); + renderer.setSize(width, height, false); // CSS controls the displayed size + renderer.setClearColor(0x000000, 0); + container.appendChild(renderer.domElement); this.scene = new THREE.Scene(); - this.camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100); this.camera.position.z = 4; - this.renderer = new THREE.WebGLRenderer({ - antialias: true, - alpha: true, - powerPreference: 'high-performance', - }); - this.renderer.setSize(width, height); - this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); - this.renderer.setClearColor(0x000000, 0); - container.appendChild(this.renderer.domElement); - - const ambientLight = new THREE.AmbientLight(0x404060, 2); - this.scene.add(ambientLight); + this.scene.add(new THREE.AmbientLight(0x404060, 2)); const pointLight1 = new THREE.PointLight(0x3b82f6, 12, 10); pointLight1.position.set(0, 0, 3); @@ -65,7 +85,16 @@ export class VoiceOrbService { pointLight3.position.set(2, -1, 2); this.scene.add(pointLight3); - this.orbGeometry = new THREE.IcosahedronGeometry(1, 48); + // Icosahedron geometry is non-indexed (faceted normals). Dropping normal/uv and + // merging vertices gives a shared-vertex mesh, so computeVertexNormals() is smooth. + let geometry: THREE.BufferGeometry = new THREE.IcosahedronGeometry(1, ORB_DETAIL); + geometry.deleteAttribute('normal'); + geometry.deleteAttribute('uv'); + geometry = mergeVertices(geometry, 1e-4); + geometry.computeVertexNormals(); + this.orbGeometry = geometry; + this.originalPositions = new Float32Array(geometry.attributes['position'].array); + const orbMaterial = new THREE.MeshPhysicalMaterial({ color: 0x60a5fa, emissive: 0x1e3a5f, @@ -75,12 +104,9 @@ export class VoiceOrbService { clearcoat: 1, clearcoatRoughness: 0.08, }); - this.orb = new THREE.Mesh(this.orbGeometry, orbMaterial); + this.orb = new THREE.Mesh(geometry, orbMaterial); this.scene.add(this.orb); - this.originalPositions = new Float32Array(this.orbGeometry.attributes['position'].array); - - const glowGeometry = new THREE.IcosahedronGeometry(1.18, 32); const glowMaterial = new THREE.MeshBasicMaterial({ color: 0x3b82f6, transparent: true, @@ -89,31 +115,29 @@ export class VoiceOrbService { side: THREE.BackSide, depthWrite: false, }); - this.glowShell = new THREE.Mesh(glowGeometry, glowMaterial); + this.glowShell = new THREE.Mesh(new THREE.IcosahedronGeometry(1.18, 16), glowMaterial); this.scene.add(this.glowShell); - this.setupResizeObserver(container); + this.observeResize(container); + this.renderer.render(this.scene, this.camera); // first frame, even before animation starts + return true; } - private setupResizeObserver(container: HTMLElement): void { - if (typeof ResizeObserver === 'undefined') return; - - const observer = new ResizeObserver((entries) => { - for (const entry of entries) { - const { width, height } = entry.contentRect; - if (width > 0 && height > 0 && this.renderer && this.camera) { - this.renderer.setSize(width, height); - this.camera.aspect = width / height; - this.camera.updateProjectionMatrix(); - } - } - }); - observer.observe(container); + resize(container: HTMLElement): void { + if (!this.renderer || !this.camera) return; + const width = container.clientWidth || FALLBACK_SIZE; + const height = container.clientHeight || FALLBACK_SIZE; + this.renderer.setSize(width, height, false); + this.camera.aspect = width / height; + this.camera.updateProjectionMatrix(); } + // ---- animation loop ------------------------------------------------------- + startAnimation(): void { - if (this.animationId !== null) return; + if (this.animationId !== null || !this.renderer) return; + // The loop runs outside Angular so 60 frames/s never trigger change detection. this.ngZone.runOutsideAngular(() => { const animate = (): void => { this.animationId = requestAnimationFrame(animate); @@ -130,158 +154,69 @@ export class VoiceOrbService { } } - private renderFrame(): void { - if (!this.scene || !this.camera || !this.renderer || !this.orb || !this.orbGeometry) { - return; - } - - const time = performance.now() * 0.001; - const audioLevel = this.getAudioLevel(); - const speed = this.reducedMotion ? 0.35 : 1; - const t = time * speed; - - this.updateOrbGeometry(t, audioLevel); - - if (this.glowShell) { - const glowOpacity = 0.05 + audioLevel * 0.18; - const glowScale = 1 + Math.sin(t * 1.5) * 0.025 + audioLevel * 0.06; - this.glowShell.scale.setScalar(glowScale); - if (this.glowShell.material instanceof THREE.MeshBasicMaterial) { - this.glowShell.material.opacity = glowOpacity; - } - } - - const pulse = 1 + Math.sin(t * 2) * 0.018 + audioLevel * 0.07; - this.orb.scale.setScalar(pulse); - - this.orb.rotation.y = t * 0.08; - this.orb.rotation.x = Math.sin(t * 0.15) * 0.1; - - this.renderer.render(this.scene, this.camera); - } - - private updateOrbGeometry(time: number, audioLevel: number): void { - if (!this.orbGeometry || !this.originalPositions) return; - - const positions = this.orbGeometry.attributes['position']; - const original = this.originalPositions; - - for (let i = 0; i < positions.count; i++) { - const ox = original[i * 3]; - const oy = original[i * 3 + 1]; - const oz = original[i * 3 + 2]; - - const n1 = - Math.sin(ox * 3 + time * 1.2) * - Math.cos(oy * 3 + time * 0.8) * - Math.sin(oz * 3 + time * 1.5) * - 0.06; - - const n2 = - Math.sin(ox * 6 + time * 2.3) * - Math.cos(oy * 6 + time * 1.7) * - Math.sin(oz * 6 + time * 2.1) * - 0.02; - - const n3 = - Math.cos(ox * 2 + time * 0.6) * - Math.sin(oy * 2 + time * 1.1) * - 0.015; - - const displacement = 1 + n1 + n2 + n3 + audioLevel * 0.12; - - positions.setXYZ(i, ox * displacement, oy * displacement, oz * displacement); - } - - positions.needsUpdate = true; - this.orbGeometry.computeVertexNormals(); - } - resetOrbGeometry(): void { if (!this.orbGeometry || !this.originalPositions) return; const positions = this.orbGeometry.attributes['position']; - const original = this.originalPositions; - for (let i = 0; i < positions.count; i++) { - positions.setXYZ(i, original[i * 3], original[i * 3 + 1], original[i * 3 + 2]); - } + positions.array.set(this.originalPositions); positions.needsUpdate = true; this.orbGeometry.computeVertexNormals(); + this.smoothedLevel = 0; } - resize(container: HTMLElement): void { - if (!this.renderer || !this.camera) return; - const width = container.clientWidth || 280; - const height = container.clientHeight || 280; - this.renderer.setSize(width, height); - this.camera.aspect = width / height; - this.camera.updateProjectionMatrix(); - } - - async startListening(): Promise { - if (this.isListening) return; + // ---- audio ---------------------------------------------------------------- + /** Starts analysing the stream. The stream stays owned (and stopped) by the caller. */ + attachStream(stream: MediaStream): void { + this.detachAudio(); try { - this.mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true }); this.audioContext = new AudioContext(); - const source = this.audioContext.createMediaStreamSource(this.mediaStream); + void this.audioContext.resume().catch(() => undefined); + this.sourceNode = this.audioContext.createMediaStreamSource(stream); this.analyser = this.audioContext.createAnalyser(); this.analyser.fftSize = 256; this.analyser.smoothingTimeConstant = 0.75; - source.connect(this.analyser); - this.audioDataArray = new Uint8Array(this.analyser.frequencyBinCount); - this.isListening = true; + this.sourceNode.connect(this.analyser); + this.audioData = new Uint8Array(this.analyser.frequencyBinCount); } catch (err) { - console.warn('VoiceOrbService: unable to access microphone.', err); - this.isListening = false; + // The orb keeps animating from time alone. + console.warn('VoiceOrbService: audio analysis unavailable.', err); + this.detachAudio(); } } - stopListening(): void { - if (this.mediaStream) { - this.mediaStream.getTracks().forEach((track) => track.stop()); - this.mediaStream = null; - } + /** Stops audio-reactive processing (does not stop the MediaStream tracks). */ + detachAudio(): void { + this.sourceNode?.disconnect(); + this.sourceNode = null; + this.analyser = null; + this.audioData = null; + this.smoothedLevel = 0; if (this.audioContext && this.audioContext.state !== 'closed') { - this.audioContext.close().catch(() => {}); + this.audioContext.close().catch(() => undefined); } this.audioContext = null; - this.analyser = null; - this.audioDataArray = null; - this.isListening = false; } - private getAudioLevel(): number { - if (!this.isListening || !this.analyser || !this.audioDataArray) return 0; - this.analyser.getByteFrequencyData(this.audioDataArray as Uint8Array); - let sum = 0; - for (let i = 0; i < this.audioDataArray.length; i++) { - sum += this.audioDataArray[i]; - } - return Math.min(1, sum / this.audioDataArray.length / 200); - } + // ---- cleanup -------------------------------------------------------------- dispose(): void { this.stopAnimation(); - this.stopListening(); + this.detachAudio(); + + this.resizeObserver?.disconnect(); + this.resizeObserver = null; + + [this.orb, this.glowShell].forEach((mesh) => { + if (!mesh) return; + mesh.geometry.dispose(); + (Array.isArray(mesh.material) ? mesh.material : [mesh.material]).forEach((m) => m.dispose()); + }); + this.scene?.clear(); - if (this.orbGeometry) this.orbGeometry.dispose(); - if (this.orb && this.orb.material instanceof THREE.Material) { - this.orb.material.dispose(); - } - if (this.glowShell) { - if (this.glowShell.material instanceof THREE.Material) { - this.glowShell.material.dispose(); - } - if (this.glowShell.geometry) { - this.glowShell.geometry.dispose(); - } - } if (this.renderer) { - this.renderer.dispose(); const canvas = this.renderer.domElement; - if (canvas.parentNode) { - canvas.parentNode.removeChild(canvas); - } + this.renderer.dispose(); + canvas.parentNode?.removeChild(canvas); } this.scene = null; @@ -292,4 +227,95 @@ export class VoiceOrbService { this.glowShell = null; this.originalPositions = null; } -} + + // ---- internals ------------------------------------------------------------ + + private observeResize(container: HTMLElement): void { + if (typeof ResizeObserver === 'undefined') return; + this.resizeObserver?.disconnect(); + this.resizeObserver = new ResizeObserver((entries) => { + for (const entry of entries) { + const { width, height } = entry.contentRect; + if (width > 0 && height > 0 && this.renderer && this.camera) { + this.renderer.setSize(width, height, false); + this.camera.aspect = width / height; + this.camera.updateProjectionMatrix(); + } + } + }); + this.resizeObserver.observe(container); + } + + private renderFrame(): void { + if (!this.scene || !this.camera || !this.renderer || !this.orb) return; + + const speed = this.reducedMotion ? 0.35 : 1; + const t = performance.now() * 0.001 * speed; + const level = this.updateAudioLevel(); + + this.updateOrbGeometry(t, level); + + if (this.glowShell) { + this.glowShell.scale.setScalar(1 + Math.sin(t * 1.5) * 0.025 + level * 0.06); + if (this.glowShell.material instanceof THREE.MeshBasicMaterial) { + this.glowShell.material.opacity = 0.05 + level * 0.18; + } + } + + this.orb.scale.setScalar(1 + Math.sin(t * 2) * 0.018 + level * 0.07); + this.orb.rotation.y = t * 0.08; + this.orb.rotation.x = Math.sin(t * 0.15) * 0.1; + + this.renderer.render(this.scene, this.camera); + } + + private updateOrbGeometry(time: number, level: number): void { + if (!this.orbGeometry || !this.originalPositions) return; + + const positions = this.orbGeometry.attributes['position']; + const original = this.originalPositions; + const amplitude = (this.reducedMotion ? 0.4 : 1) * (1 + level * 2.2); + const swell = level * 0.08; + + for (let i = 0; i < positions.count; i++) { + const ox = original[i * 3]; + const oy = original[i * 3 + 1]; + const oz = original[i * 3 + 2]; + + const n1 = + Math.sin(ox * 3 + time * 1.2) * Math.cos(oy * 3 + time * 0.8) * Math.sin(oz * 3 + time * 1.5) * 0.06; + const n2 = + Math.sin(ox * 6 + time * 2.3) * Math.cos(oy * 6 + time * 1.7) * Math.sin(oz * 6 + time * 2.1) * 0.02; + const n3 = Math.cos(ox * 2 + time * 0.6) * Math.sin(oy * 2 + time * 1.1) * 0.015; + + const k = 1 + (n1 + n2 + n3) * amplitude + swell; + positions.setXYZ(i, ox * k, oy * k, oz * k); + } + + positions.needsUpdate = true; + this.orbGeometry.computeVertexNormals(); + } + + /** Fast attack, slow release: loud sounds are visible immediately but never jitter. */ + private updateAudioLevel(): number { + const target = this.readAudioLevel(); + const smoothing = target > this.smoothedLevel ? 0.35 : 0.08; + this.smoothedLevel += (target - this.smoothedLevel) * smoothing; + return this.smoothedLevel; + } + + private readAudioLevel(): number { + if (!this.analyser || !this.audioData) return 0; + + this.analyser.getByteFrequencyData(this.audioData); + + // Voice band only (roughly 200 Hz – 9 kHz at 48 kHz sample rate). + const end = Math.min(48, this.audioData.length); + let sum = 0; + for (let i = 1; i < end; i++) sum += this.audioData[i]; + const average = sum / (end - 1); + + const gain = this.reducedMotion ? 0.5 : 1; + return Math.min(1, Math.max(0, (average - 8) / 110)) * gain; + } +} \ No newline at end of file diff --git a/src/app/shared/ui/ai-chat-input/ai-chat-input.component.css b/src/app/shared/ui/ai-chat-input/ai-chat-input.component.css index 9037007..988a330 100644 --- a/src/app/shared/ui/ai-chat-input/ai-chat-input.component.css +++ b/src/app/shared/ui/ai-chat-input/ai-chat-input.component.css @@ -1,33 +1,40 @@ +:host { + display: block; +} + .ai-chat-input-wrapper { width: 100%; max-width: 800px; margin: 0 auto; position: relative; min-height: 72px; + transition: min-height 0.4s cubic-bezier(0.22, 1, 0.36, 1); } +/* Height of the voice view; the wrapper animates to it so the page never jumps. */ .ai-chat-input-wrapper.voice-active { - min-height: 380px; + min-height: 460px; } -/* Layers transition */ +/* Layers cross-fade */ .composer-layer, .voice-layer { - transition: opacity 0.35s ease, transform 0.35s ease; + transition: + opacity 0.35s ease, + transform 0.35s ease; } .composer-layer { position: relative; opacity: 1; transform: translateY(0); - pointer-events: auto; } .voice-layer { position: absolute; inset: 0; opacity: 0; - transform: translateY(10px); + transform: translateY(10px) scale(0.98); pointer-events: none; } @@ -38,32 +45,39 @@ } .ai-chat-input-wrapper.voice-active .voice-layer { - position: relative; opacity: 1; - transform: translateY(0); + transform: translateY(0) scale(1); pointer-events: auto; } -/* Chat Composer */ +/* ---------- Chat composer ---------- */ .chat-composer { + /* The composer lays itself out RTL explicitly: Plus on the right edge, Send on the left. + Icons are SVGs, so they are never mirrored by direction. */ + direction: rtl; display: flex; - align-items: flex-end; + align-items: center; gap: 0.375rem; padding: 0.625rem 0.75rem; background: var(--surface-bg); border: 1px solid var(--surface-border); - border-radius: 1.5rem; - box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03); - transition: box-shadow 0.2s ease, border-color 0.2s ease; + border-radius: 2rem; + box-shadow: + 0 2px 12px rgba(0, 0, 0, 0.05), + 0 1px 3px rgba(0, 0, 0, 0.03); + transition: + box-shadow 0.2s ease, + border-color 0.2s ease; position: relative; } .chat-composer:focus-within { border-color: var(--color-primary); - box-shadow: 0 4px 20px rgba(59, 130, 246, 0.12), 0 1px 3px rgba(0, 0, 0, 0.03); + box-shadow: + 0 4px 20px rgba(59, 130, 246, 0.12), + 0 1px 3px rgba(0, 0, 0, 0.03); } -/* Textarea */ .composer-textarea-wrapper { flex: 1; min-width: 0; @@ -98,17 +112,15 @@ cursor: not-allowed; } -/* Remove scrollbar but keep functionality */ .composer-textarea::-webkit-scrollbar { width: 4px; } .composer-textarea::-webkit-scrollbar-thumb { background: var(--muted); border-radius: 9999px; - opacity: 0.3; } -/* Action Buttons */ +/* ---------- Action buttons ---------- */ .composer-btn { display: flex; align-items: center; @@ -120,7 +132,10 @@ background: transparent; color: var(--muted); cursor: pointer; - transition: background 0.2s ease, color 0.2s ease, transform 0.15s ease; + transition: + background 0.2s ease, + color 0.2s ease, + transform 0.15s ease; flex-shrink: 0; user-select: none; } @@ -155,7 +170,28 @@ color: #ffffff; } -/* Attachment Menu */ +/* Mic: waiting for the browser permission prompt */ +.mic-btn.is-pending { + color: var(--color-primary); + animation: micPending 1.1s ease-in-out infinite; +} + +/* Mic: voice transcription not available in this browser (stays clickable to explain why) */ +.mic-btn.is-unsupported { + opacity: 0.45; +} + +@keyframes micPending { + 0%, + 100% { + box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.35); + } + 50% { + box-shadow: 0 0 0 6px rgba(59, 130, 246, 0); + } +} + +/* ---------- Attachment menu ---------- */ .attachment-menu { position: absolute; bottom: calc(100% + 0.5rem); @@ -164,7 +200,9 @@ background: var(--surface-bg); border: 1px solid var(--surface-border); border-radius: 0.875rem; - box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.06); + box-shadow: + 0 8px 30px rgba(0, 0, 0, 0.12), + 0 2px 8px rgba(0, 0, 0, 0.06); overflow: hidden; z-index: 50; animation: menuFadeIn 0.15s ease; @@ -186,7 +224,8 @@ transition: background 0.15s ease; } -.attachment-menu-item:hover { +.attachment-menu-item:hover, +.attachment-menu-item:focus-visible { background: var(--sidebar-hover); color: var(--text-primary); } @@ -194,7 +233,6 @@ .attachment-menu-item:focus-visible { outline: 2px solid var(--color-primary); outline-offset: -2px; - background: var(--sidebar-hover); } @keyframes menuFadeIn { @@ -208,28 +246,84 @@ } } -/* Voice Mode */ +/* ---------- Notice (permission denied, unsupported browser, ...) ---------- */ +.voice-notice { + direction: rtl; + display: flex; + align-items: center; + gap: 0.5rem; + margin-top: 0.625rem; + padding: 0.5rem 0.75rem; + border: 1px solid var(--surface-border); + border-radius: 0.875rem; + background: var(--surface-bg); + color: var(--text-secondary); + font-size: 0.8125rem; + line-height: 1.6; + animation: menuFadeIn 0.2s ease; +} + +.voice-notice.is-error { + border-color: rgba(239, 68, 68, 0.45); + color: #dc2626; +} + +.voice-notice-text { + flex: 1; + min-width: 0; +} + +.voice-notice-close { + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + border: none; + border-radius: 50%; + background: transparent; + color: inherit; + cursor: pointer; + flex-shrink: 0; +} + +.voice-notice-close:hover { + background: var(--sidebar-hover); +} + +.voice-notice-close:focus-visible { + outline: 2px solid var(--color-primary); + outline-offset: 1px; +} + +/* ---------- Voice mode ---------- */ .voice-mode { + direction: rtl; + box-sizing: border-box; + height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; - gap: 1.25rem; - padding: 1.5rem; + gap: 1rem; + padding: 1.25rem; background: var(--surface-bg); border: 1px solid var(--surface-border); border-radius: 1.5rem; - box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03); - min-height: 320px; + box-shadow: + 0 2px 12px rgba(0, 0, 0, 0.05), + 0 1px 3px rgba(0, 0, 0, 0.03); } .orb-container { - width: 260px; - height: 260px; + width: 220px; + height: 220px; + max-width: 100%; position: relative; display: flex; align-items: center; justify-content: center; + flex-shrink: 0; } .orb-container canvas { @@ -238,6 +332,58 @@ height: 100% !important; } +/* Shown only when WebGL is unavailable */ +.orb-fallback { + width: 70%; + height: 70%; + border-radius: 50%; + background: radial-gradient(circle at 35% 30%, #93c5fd, #3b82f6 55%, #1e3a5f); + box-shadow: 0 0 40px rgba(59, 130, 246, 0.35); + animation: orbFallbackPulse 2.4s ease-in-out infinite; +} + +@keyframes orbFallbackPulse { + 0%, + 100% { + transform: scale(1); + } + 50% { + transform: scale(1.06); + } +} + +/* Recording indicator + status text */ +.voice-status { + display: flex; + align-items: center; + gap: 0.5rem; +} + +.rec-dot { + width: 10px; + height: 10px; + border-radius: 50%; + background: #ef4444; + flex-shrink: 0; + animation: recPulse 1.4s ease-in-out infinite; +} + +.voice-status.is-speaking .rec-dot { + animation-duration: 0.7s; +} + +@keyframes recPulse { + 0%, + 100% { + opacity: 1; + box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.5); + } + 50% { + opacity: 0.7; + box-shadow: 0 0 0 6px rgba(239, 68, 68, 0); + } +} + .voice-mode-text { font-size: 0.9375rem; color: var(--text-secondary); @@ -245,6 +391,41 @@ text-align: center; } +/* Live transcript preview (the textarea is updated at the same time) */ +.voice-transcript { + box-sizing: border-box; + width: 100%; + max-width: 560px; + height: 3.25rem; + overflow-y: auto; + padding: 0.25rem 0.5rem; + color: var(--text-primary); + font-size: 0.9375rem; + line-height: 1.6; + text-align: right; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.t-interim, +.t-placeholder { + color: var(--muted); +} + +.t-placeholder { + display: block; + text-align: center; + font-size: 0.875rem; +} + +.voice-actions { + display: flex; + align-items: center; + justify-content: center; + gap: 0.625rem; + flex-wrap: wrap; +} + .voice-stop-btn { display: inline-flex; align-items: center; @@ -258,27 +439,47 @@ font-family: inherit; font-size: 0.875rem; cursor: pointer; - transition: all 0.2s ease; + transition: + background 0.2s ease, + color 0.2s ease, + border-color 0.2s ease, + transform 0.15s ease; user-select: none; } -.voice-stop-btn:hover { - background: #ef4444; - color: #ffffff; - border-color: #ef4444; +.voice-stop-btn:hover:not(:disabled) { + background: var(--sidebar-hover); + color: var(--text-primary); transform: scale(1.03); } -.voice-stop-btn:active { +.voice-stop-btn.is-primary { + background: var(--color-primary); + border-color: var(--color-primary); + color: #ffffff; +} + +.voice-stop-btn.is-primary:hover:not(:disabled) { + background: #2563eb; + border-color: #2563eb; + color: #ffffff; +} + +.voice-stop-btn:active:not(:disabled) { transform: scale(0.97); } +.voice-stop-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + .voice-stop-btn:focus-visible { outline: 2px solid var(--color-primary); outline-offset: 2px; } -/* Screen reader only */ +/* ---------- Screen reader only ---------- */ .sr-only { position: absolute; width: 1px; @@ -291,25 +492,37 @@ border: 0; } -/* Reduced motion */ +/* ---------- Reduced motion ---------- */ @media (prefers-reduced-motion: reduce) { + .ai-chat-input-wrapper, .composer-layer, .voice-layer, .chat-composer, .composer-btn, .voice-stop-btn, - .attachment-menu { + .attachment-menu, + .voice-notice { transition: none !important; animation: none !important; } + + .rec-dot, + .orb-fallback, + .mic-btn.is-pending { + animation: none !important; + } } -/* Mobile responsiveness */ +/* ---------- Mobile ---------- */ @media (max-width: 640px) { .ai-chat-input-wrapper { max-width: 100%; } + .ai-chat-input-wrapper.voice-active { + min-height: 410px; + } + .chat-composer { gap: 0.25rem; padding: 0.5rem 0.625rem; @@ -327,17 +540,22 @@ } .composer-textarea { - font-size: 0.875rem; - } - - .orb-container { - width: 200px; - height: 200px; + /* 16px prevents iOS from zooming the page when the field is focused */ + font-size: 1rem; } .voice-mode { - min-height: 280px; - gap: 1rem; + gap: 0.75rem; + padding: 1rem; + } + + .orb-container { + width: 170px; + height: 170px; + } + + .voice-stop-btn { + padding: 0.5rem 1rem; } .attachment-menu { diff --git a/src/app/shared/ui/ai-chat-input/ai-chat-input.component.html b/src/app/shared/ui/ai-chat-input/ai-chat-input.component.html index 0497d6d..b502b8a 100644 --- a/src/app/shared/ui/ai-chat-input/ai-chat-input.component.html +++ b/src/app/shared/ui/ai-chat-input/ai-chat-input.component.html @@ -1,24 +1,25 @@ -
-
+
+ +
{{ statusText() }}
+ +
@@ -40,20 +41,17 @@ @if (isAttachmentMenuOpen()) { - } @@ -136,38 +111,84 @@ #fileInput type="file" class="sr-only" + tabindex="-1" (change)="onFileChange($event)" aria-hidden="true" />
+ + @if (notice(); as n) { +
+ {{ n.text }} + +
+ }
-
-
-
-

در حال گوش دادن...

- + + پایان و ویرایش + + +
-
+
\ No newline at end of file diff --git a/src/app/shared/ui/ai-chat-input/ai-chat-input.component.ts b/src/app/shared/ui/ai-chat-input/ai-chat-input.component.ts index fa88342..39835b3 100644 --- a/src/app/shared/ui/ai-chat-input/ai-chat-input.component.ts +++ b/src/app/shared/ui/ai-chat-input/ai-chat-input.component.ts @@ -1,91 +1,195 @@ import { ChangeDetectionStrategy, Component, + ElementRef, + Injector, + OnDestroy, + afterNextRender, + computed, + effect, + inject, input, output, signal, - ViewChild, - ElementRef, - AfterViewChecked, - OnInit, - OnDestroy, - inject, + viewChild, } from '@angular/core'; -import { CommonModule } from '@angular/common'; +import { MicrophoneError, MicrophoneService } from '../../../services/microphone/microphone.service'; +import { + DEFAULT_SPEECH_LANGUAGE, + SpeechErrorKind, + SpeechRecognitionService, + SpeechTranscript, +} from '../../../services/speech-recognition/speech-recognition.service'; import { VoiceOrbService } from '../../../services/voice-orb/voice-orb.service'; +export type VoiceState = + | 'idle' + | 'requesting-permission' + | 'recording' + | 'transcribing' + | 'stopping' + | 'error'; + +export interface AttachmentAction { + id: string; + label: string; + icon: 'file' | 'image'; + /** Value for the file input's `accept` attribute ('' = any file). */ + accept: string; +} + +interface Notice { + kind: 'error' | 'info'; + text: string; +} + +export const DEFAULT_ATTACHMENT_ACTIONS: readonly AttachmentAction[] = [ + { id: 'file', label: 'آپلود فایل', icon: 'file', accept: '' }, + { id: 'image', label: 'آپلود تصویر', icon: 'image', accept: 'image/*' }, +]; + +const NOTICE_TIMEOUT_MS = 7000; + +const MIC_ERRORS: Record = { + unsupported: 'مرورگر شما از دسترسی به میکروفون پشتیبانی نمی‌کند (اتصال امن HTTPS لازم است).', + denied: 'دسترسی به میکروفون رد شد. اجازه‌ی دسترسی را در تنظیمات مرورگر فعال کنید.', + unavailable: 'میکروفونی پیدا نشد یا در حال استفاده‌ی برنامه‌ی دیگری است.', + unknown: 'دسترسی به میکروفون ممکن نشد. دوباره تلاش کنید.', +}; + +const SPEECH_ERRORS: Record = { + 'permission-denied': 'اجازه‌ی استفاده از تشخیص گفتار داده نشد. تنظیمات مرورگر را بررسی کنید.', + 'audio-capture': 'میکروفون در دسترس نیست. اتصال آن را بررسی کنید.', + network: 'اتصال به سرویس تشخیص گفتار برقرار نشد. اینترنت خود را بررسی کنید.', + 'no-speech': 'گفتاری شناسایی نشد. دوباره تلاش کنید.', + 'language-not-supported': 'این زبان توسط تشخیص گفتار مرورگر پشتیبانی نمی‌شود.', + unsupported: 'تبدیل گفتار به متن در این مرورگر پشتیبانی نمی‌شود. از Chrome یا Edge استفاده کنید.', + unknown: 'تشخیص گفتار با خطا متوقف شد. دوباره تلاش کنید.', +}; + @Component({ selector: 'app-ai-chat-input', standalone: true, - imports: [CommonModule], changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: './ai-chat-input.component.html', styleUrl: './ai-chat-input.component.css', }) -export class AiChatInputComponent implements AfterViewChecked, OnInit, OnDestroy { - private readonly voiceOrbService = inject(VoiceOrbService); +export class AiChatInputComponent implements OnDestroy { + private readonly injector = inject(Injector); + private readonly voiceOrb = inject(VoiceOrbService); + private readonly mic = inject(MicrophoneService); + private readonly speech = inject(SpeechRecognitionService); + // ---- API ------------------------------------------------------------------ readonly placeholder = input('پیام خود را بنویسید...'); readonly disabled = input(false); + readonly hasMessages = input(false); + /** Speech recognition language (BCP-47), e.g. 'fa-IR' or 'en-US'. */ + readonly language = input(DEFAULT_SPEECH_LANGUAGE); + readonly attachmentActions = input(DEFAULT_ATTACHMENT_ACTIONS); readonly messageSent = output(); readonly fileSelected = output(); readonly voiceToggled = output(); + // ---- state ---------------------------------------------------------------- readonly message = signal(''); - readonly isVoiceMode = signal(false); readonly isAttachmentMenuOpen = signal(false); - @ViewChild('textarea') textareaRef!: ElementRef; - @ViewChild('composer') composerRef!: ElementRef; - @ViewChild('voiceContainer') voiceContainerRef!: ElementRef; - @ViewChild('orbContainer') orbContainerRef!: ElementRef; - @ViewChild('fileInput') fileInputRef!: ElementRef; + readonly voiceState = signal('idle'); + readonly notice = signal(null); + readonly liveFinal = signal(''); + readonly liveInterim = signal(''); + readonly orbAvailable = signal(true); - private orbInited = false; - private menuCloseHandler: ((event: MouseEvent) => void) | null = null; - private escapeHandler: ((event: KeyboardEvent) => void) | null = null; + readonly voiceSupported = this.mic.isSupported && this.speech.isSupported; - selectFile(): void { - this.fileInputRef?.nativeElement.click(); - } + /** The orb view replaces the composer while recording, transcribing and stopping. */ + readonly isVoiceMode = computed(() => { + const state = this.voiceState(); + return state === 'recording' || state === 'transcribing' || state === 'stopping'; + }); - ngOnInit(): void { - this.attachDocumentListeners(); - } - - ngAfterViewChecked(): void { - if (this.isVoiceMode() && !this.orbInited && this.orbContainerRef) { - this.orbInited = true; - this.voiceOrbService.init(this.orbContainerRef.nativeElement); - this.voiceOrbService.resetOrbGeometry(); - this.voiceOrbService.startAnimation(); - this.voiceOrbService.startListening().catch(() => { - /* orb continues without audio reactivity */ - }); + readonly statusText = computed(() => { + switch (this.voiceState()) { + case 'requesting-permission': + return 'در حال درخواست دسترسی به میکروفون...'; + case 'recording': + return 'در حال گوش دادن...'; + case 'transcribing': + return 'در حال تبدیل گفتار به متن...'; + case 'stopping': + return 'در حال پایان دادن...'; + case 'error': + return 'خطا در ضبط صدا'; + default: + return ''; } + }); + + readonly micLabel = computed(() => { + if (!this.voiceSupported) return 'تبدیل گفتار به متن در این مرورگر پشتیبانی نمی‌شود'; + switch (this.voiceState()) { + case 'requesting-permission': + return 'در حال درخواست دسترسی به میکروفون (برای لغو کلیک کنید)'; + case 'recording': + case 'transcribing': + return 'توقف ضبط صدا'; + default: + return 'شروع ضبط صدا'; + } + }); + + // ---- view refs ------------------------------------------------------------ + private readonly textareaRef = viewChild>('textarea'); + private readonly composerRef = viewChild>('composer'); + private readonly fileInputRef = viewChild>('fileInput'); + private readonly plusBtnRef = viewChild>('plusBtn'); + private readonly menuRef = viewChild>('attachmentMenu'); + private readonly orbContainerRef = viewChild>('orbContainer'); + private readonly transcriptRef = viewChild>('transcript'); + + // ---- internals ------------------------------------------------------------ + /** Incremented whenever a voice session ends/cancels so stale async callbacks are ignored. */ + private voiceSession = 0; + /** Textarea content when recording started; dictated text is appended to it. */ + private baseText = ''; + private noticeTimer: ReturnType | null = null; + + constructor() { + // The outside-click listener only exists while the menu is open. + effect((onCleanup) => { + if (!this.isAttachmentMenuOpen()) return; + + const onMouseDown = (event: MouseEvent): void => { + const target = event.target as Node; + if (this.composerRef()?.nativeElement.contains(target)) return; + this.closeAttachmentMenu(); + }; + document.addEventListener('mousedown', onMouseDown); + onCleanup(() => document.removeEventListener('mousedown', onMouseDown)); + }); } ngOnDestroy(): void { - this.detachDocumentListeners(); - this.voiceOrbService.dispose(); + this.voiceSession++; + this.speech.dispose(); + this.mic.release(); + this.voiceOrb.dispose(); + this.clearNoticeTimer(); } + // ---- text input ----------------------------------------------------------- + onTextareaInput(): void { - const textarea = this.textareaRef?.nativeElement; + const textarea = this.textareaRef()?.nativeElement; if (!textarea) return; - this.message.set(textarea.value); - - textarea.style.height = 'auto'; - const scrollHeight = textarea.scrollHeight; - const maxHeight = 192; - const newHeight = Math.min(scrollHeight, maxHeight); - textarea.style.height = newHeight + 'px'; + this.autoResize(textarea); } onKeyDown(event: KeyboardEvent): void { - if (event.key === 'Enter' && !event.shiftKey) { + if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); this.sendMessage(); } @@ -93,85 +197,323 @@ export class AiChatInputComponent implements AfterViewChecked, OnInit, OnDestroy sendMessage(): void { const text = this.message().trim(); - if (!text) return; + if (!text || this.disabled()) return; this.messageSent.emit(text); - this.message.set(''); - - const textarea = this.textareaRef?.nativeElement; - if (textarea) { - textarea.value = ''; - textarea.style.height = 'auto'; - } + this.setTextareaValue(''); } + private setTextareaValue(value: string): void { + const textarea = this.textareaRef()?.nativeElement; + this.message.set(value); + if (!textarea) return; + textarea.value = value; + this.autoResize(textarea); + } + + private autoResize(textarea: HTMLTextAreaElement): void { + textarea.style.height = 'auto'; + textarea.style.height = Math.min(textarea.scrollHeight, 192) + 'px'; + } + + private focusTextarea(): void { + afterNextRender( + () => { + const textarea = this.textareaRef()?.nativeElement; + if (!textarea) return; + textarea.focus(); + textarea.setSelectionRange(textarea.value.length, textarea.value.length); + }, + { injector: this.injector }, + ); + } + + // ---- attachments ---------------------------------------------------------- + toggleAttachmentMenu(): void { - this.isAttachmentMenuOpen.update((open) => !open); + const opening = !this.isAttachmentMenuOpen(); + this.isAttachmentMenuOpen.set(opening); + if (opening) { + afterNextRender( + () => this.menuItems()[0]?.focus(), + { injector: this.injector }, + ); + } } closeAttachmentMenu(): void { this.isAttachmentMenuOpen.set(false); } + selectAction(action: AttachmentAction): void { + const input = this.fileInputRef()?.nativeElement; + this.closeAttachmentMenu(); + if (!input) return; + input.accept = action.accept; + input.click(); + } + onFileChange(event: Event): void { const input = event.target as HTMLInputElement; const file = input.files?.[0]; if (file) { this.fileSelected.emit(file); } - if (input.value) { - input.value = ''; - } - this.closeAttachmentMenu(); + input.value = ''; } - toggleVoiceMode(): void { - if (this.isVoiceMode()) { - this.exitVoiceMode(); - } else { - this.enterVoiceMode(); - } - } + onMenuKeydown(event: KeyboardEvent): void { + const items = this.menuItems(); + if (!items.length) return; + const index = items.indexOf(document.activeElement as HTMLElement); - private enterVoiceMode(): void { - this.isVoiceMode.set(true); - this.orbInited = false; - this.voiceToggled.emit(true); - } - - exitVoiceMode(): void { - this.voiceOrbService.stopAnimation(); - this.voiceOrbService.stopListening(); - this.isVoiceMode.set(false); - this.voiceToggled.emit(false); - } - - private attachDocumentListeners(): void { - this.menuCloseHandler = (event: MouseEvent) => { - if (!this.isAttachmentMenuOpen()) return; - const target = event.target as Node; - if (this.composerRef && this.composerRef.nativeElement.contains(target)) { + let next = -1; + switch (event.key) { + case 'ArrowDown': + next = (index + 1) % items.length; + break; + case 'ArrowUp': + next = (index - 1 + items.length) % items.length; + break; + case 'Home': + next = 0; + break; + case 'End': + next = items.length - 1; + break; + default: return; - } + } + event.preventDefault(); + items[next].focus(); + } + + private menuItems(): HTMLElement[] { + const menu = this.menuRef()?.nativeElement; + return menu ? Array.from(menu.querySelectorAll('[role="menuitem"]')) : []; + } + + onEscape(): void { + if (this.isAttachmentMenuOpen()) { this.closeAttachmentMenu(); - }; - - this.escapeHandler = (event: KeyboardEvent) => { - if (event.key === 'Escape' && this.isAttachmentMenuOpen()) { - this.closeAttachmentMenu(); - } - }; - - document.addEventListener('mousedown', this.menuCloseHandler); - document.addEventListener('keydown', this.escapeHandler); - } - - private detachDocumentListeners(): void { - if (this.menuCloseHandler) { - document.removeEventListener('mousedown', this.menuCloseHandler); - } - if (this.escapeHandler) { - document.removeEventListener('keydown', this.escapeHandler); + this.plusBtnRef()?.nativeElement.focus(); + } else if (this.isVoiceMode()) { + void this.stopVoice(true); } } -} + + // ---- voice: start --------------------------------------------------------- + + async toggleVoiceMode(): Promise { + switch (this.voiceState()) { + case 'recording': + case 'transcribing': + await this.stopVoice(true); + break; + case 'requesting-permission': + this.voiceSession++; // the pending permission request is released when it resolves + this.voiceState.set('idle'); + break; + case 'stopping': + break; + default: + await this.startVoice(); + } + } + + private async startVoice(): Promise { + if (this.disabled()) return; + + this.dismissNotice(); + this.closeAttachmentMenu(); + + if (!this.mic.isSupported) { + this.failBeforeStart(MIC_ERRORS['unsupported']); + return; + } + if (!this.speech.isSupported) { + this.failBeforeStart(SPEECH_ERRORS.unsupported); + return; + } + + const session = ++this.voiceSession; + this.voiceState.set('requesting-permission'); + + let stream: MediaStream; + try { + stream = await this.mic.request(() => this.onMicEnded(session)); + } catch (err) { + if (session !== this.voiceSession) return; // cancelled while the prompt was open + const code = err instanceof MicrophoneError ? err.code : 'unknown'; + this.failBeforeStart(MIC_ERRORS[code] ?? MIC_ERRORS['unknown']); + return; + } + + if (session !== this.voiceSession) { + this.mic.release(stream); // user cancelled while the prompt was open + return; + } + + this.baseText = this.message(); + this.liveFinal.set(''); + this.liveInterim.set(''); + + const started = this.speech.start(this.language(), { + onTranscript: (transcript) => this.onTranscript(transcript, session), + onSpeechEnd: () => this.onSpeechEnd(session), + onError: (kind) => this.onSpeechError(kind, session), + }); + if (!started) { + this.mic.release(stream); + this.failBeforeStart(SPEECH_ERRORS.unknown); + return; + } + + this.voiceState.set('recording'); + this.voiceToggled.emit(true); + this.startOrb(stream); + } + + private startOrb(stream: MediaStream): void { + const container = this.orbContainerRef()?.nativeElement; + if (!container) return; + + const ready = this.voiceOrb.init(container); + this.orbAvailable.set(ready); + if (!ready) return; // CSS fallback orb is shown; recording still works + + this.voiceOrb.resetOrbGeometry(); + this.voiceOrb.attachStream(stream); + this.voiceOrb.startAnimation(); + } + + // ---- voice: events -------------------------------------------------------- + + private onTranscript(transcript: SpeechTranscript, session: number): void { + if (session !== this.voiceSession) return; + + this.liveFinal.set(transcript.final); + this.liveInterim.set(transcript.interim); + this.setTextareaValue(this.composeText(transcript.final, transcript.interim)); + + const state = this.voiceState(); + if (state === 'recording' || state === 'transcribing') { + this.voiceState.set(transcript.interim ? 'transcribing' : 'recording'); + } + + requestAnimationFrame(() => { + const el = this.transcriptRef()?.nativeElement; + if (el) el.scrollTop = el.scrollHeight; + }); + } + + private onSpeechEnd(session: number): void { + if (session === this.voiceSession && this.voiceState() === 'transcribing') { + this.voiceState.set('recording'); + } + } + + private onSpeechError(kind: SpeechErrorKind, session: number): void { + if (session !== this.voiceSession || !this.isListening()) return; + this.endSessionWithNotice({ + kind: kind === 'no-speech' ? 'info' : 'error', + text: SPEECH_ERRORS[kind], + }); + } + + private onMicEnded(session: number): void { + if (session !== this.voiceSession || !this.isListening()) return; + this.endSessionWithNotice({ kind: 'error', text: MIC_ERRORS['unavailable'] }); + } + + // ---- voice: stop ---------------------------------------------------------- + + /** + * @param commit true keeps the dictated text in the textarea; false restores the + * text that was there before recording started. + */ + async stopVoice(commit: boolean): Promise { + if (!this.isListening()) return; + + this.voiceState.set('stopping'); + const transcript = await this.speech.stop(); // flushes late final results + this.finishVoice(commit ? transcript : null); + } + + private endSessionWithNotice(notice: Notice): void { + this.voiceState.set('stopping'); + const transcript = this.speech.currentText(); + this.speech.abort(); + this.finishVoice(transcript, notice); + } + + private finishVoice(transcript: string | null, notice?: Notice): void { + this.voiceSession++; + + // Everything that could keep running is released here, on every exit path. + this.speech.abort(); + this.voiceOrb.stopAnimation(); + this.voiceOrb.detachAudio(); + this.mic.release(); + + if (transcript === null) { + this.setTextareaValue(this.baseText); + } else { + this.setTextareaValue(this.composeText(transcript, '')); + } + + this.liveFinal.set(''); + this.liveInterim.set(''); + this.voiceState.set(notice?.kind === 'error' ? 'error' : 'idle'); + this.voiceToggled.emit(false); + + if (notice) { + this.showNotice(notice); + } else if (transcript !== null && !transcript.trim()) { + this.showNotice({ kind: 'info', text: SPEECH_ERRORS['no-speech'] }); + } + + this.focusTextarea(); + } + + private failBeforeStart(text: string): void { + this.voiceState.set('error'); + this.showNotice({ kind: 'error', text }); + } + + private isListening(): boolean { + const state = this.voiceState(); + return state === 'recording' || state === 'transcribing'; + } + + // ---- helpers -------------------------------------------------------------- + + private composeText(final: string, interim: string): string { + const spoken = [final, interim].filter(Boolean).join(' '); + const base = this.baseText; + if (!base) return spoken; + if (!spoken) return base; + return /\s$/.test(base) ? base + spoken : `${base} ${spoken}`; + } + + private showNotice(notice: Notice): void { + this.clearNoticeTimer(); + this.notice.set(notice); + this.noticeTimer = setTimeout(() => this.dismissNotice(), NOTICE_TIMEOUT_MS); + } + + dismissNotice(): void { + this.clearNoticeTimer(); + this.notice.set(null); + if (this.voiceState() === 'error') { + this.voiceState.set('idle'); + } + } + + private clearNoticeTimer(): void { + if (this.noticeTimer) { + clearTimeout(this.noticeTimer); + this.noticeTimer = null; + } + } +} \ No newline at end of file diff --git a/src/app/shared/ui/sidebar/sidebar.component.css b/src/app/shared/ui/sidebar/sidebar.component.css index 06c3aba..517402a 100644 --- a/src/app/shared/ui/sidebar/sidebar.component.css +++ b/src/app/shared/ui/sidebar/sidebar.component.css @@ -178,7 +178,8 @@ border-radius: 0.5rem; color: var(--sidebar-muted); text-decoration: none; - font-size: 0.875rem; + font-size: 1rem; + font-weight: 500; transition: background 0.2s; } diff --git a/src/app/shared/ui/sidebar/sidebar.component.html b/src/app/shared/ui/sidebar/sidebar.component.html index cff0966..2afb24e 100644 --- a/src/app/shared/ui/sidebar/sidebar.component.html +++ b/src/app/shared/ui/sidebar/sidebar.component.html @@ -34,6 +34,7 @@ [routerLink]="item.route" class="nav-item" routerLinkActive="active" + [routerLinkActiveOptions]="{ exact: true }" (click)="onNavClick()" >