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.
This commit is contained in:
PeymanHonarjoo
2026-10-06 17:27:52 +03:30
parent 3a0001c30d
commit d22cd65e28
16 changed files with 1736 additions and 478 deletions
+1 -1
View File
@@ -3,7 +3,7 @@
[isOpen]="sidebarOpen()" [isOpen]="sidebarOpen()"
[chatHistory]="chatHistory()" [chatHistory]="chatHistory()"
(close)="sidebarOpen.set(false)" (close)="sidebarOpen.set(false)"
(navClick)="sidebarOpen.set(false)" (navClick)="sidebarOpen.set(true)"
(open)="sidebarOpen.set(true)" (open)="sidebarOpen.set(true)"
(profileClick)="onProfile()" (profileClick)="onProfile()"
(logoutClick)="onLogout()" (logoutClick)="onLogout()"
+1 -1
View File
@@ -17,7 +17,7 @@ export class LayoutComponent {
private readonly authService = inject(AuthService); private readonly authService = inject(AuthService);
private readonly themeService = inject(ThemeService); private readonly themeService = inject(ThemeService);
readonly sidebarOpen = signal(false); readonly sidebarOpen = signal(true);
readonly chatHistory = signal<ChatHistoryItem[]>([]); readonly chatHistory = signal<ChatHistoryItem[]>([]);
readonly isDarkMode = this.themeService.isDarkMode; readonly isDarkMode = this.themeService.isDarkMode;
+121 -22
View File
@@ -3,19 +3,69 @@
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
min-height: 100%; min-height: 100vh;
padding: 2rem 1rem; 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 { .home-content {
width: 100%; width: 100%;
max-width: 800px; max-width: 800px;
margin: 0 auto;
}
.home-header {
text-align: center;
margin-bottom: 2rem;
} }
.home-icon-wrapper { .home-icon-wrapper {
@@ -38,18 +88,57 @@
} }
.home-title { .home-title {
font-size: 1.75rem; width: 100%;
font-weight: 600; 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); color: var(--text-primary);
margin: 0 0 0.5rem;
line-height: 1.3;
} }
.home-subtitle { .home-title-text {
font-size: 0.9375rem; white-space: pre-wrap;
color: var(--text-muted); }
margin: 0;
line-height: 1.5; .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) { @media (max-width: 640px) {
@@ -57,14 +146,17 @@
padding: 1.25rem 0.75rem; padding: 1.25rem 0.75rem;
} }
.home-page.has-messages {
padding-bottom: 1.25rem;
}
.home-header { .home-header {
margin-bottom: 1.25rem; top: 1.25rem;
} }
.home-icon-wrapper { .home-icon-wrapper {
width: 100px; width: 100px;
height: 100px; height: 100px;
margin-bottom: 1.25rem;
padding: 0.5rem; padding: 0.5rem;
} }
@@ -76,10 +168,6 @@
.home-title { .home-title {
font-size: 1.375rem; font-size: 1.375rem;
} }
.home-subtitle {
font-size: 0.875rem;
}
} }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
@@ -90,3 +178,14 @@
animation: none !important; animation: none !important;
} }
} }
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
+19 -5
View File
@@ -1,6 +1,6 @@
<div class="home-page"> <div class="home-page" [class.has-messages]="hasMessages()">
<div class="home-content">
<div class="home-header"> <div class="home-header" [class.header-hidden]="hasMessages()">
<div class="home-icon-wrapper"> <div class="home-icon-wrapper">
<img <img
class="home-logo" class="home-logo"
@@ -8,15 +8,29 @@
alt="Raymand" alt="Raymand"
/> />
</div> </div>
<h1 class="home-title">دستیار هوشمند</h1>
<p class="home-subtitle">سوال خود را بپرسید، من اینجا هستم</p>
</div> </div>
<div class="home-content">
<h1 class="home-title">
<span class="home-title-text">
{{ streamedText() }}
</span>
<span
class="cursor"
[class.cursor-hidden]="!isStreaming()"
aria-hidden="true"
></span>
</h1>
<app-ai-chat-input <app-ai-chat-input
placeholder="پیام خود را بنویسید..." placeholder="پیام خود را بنویسید..."
[hasMessages]="hasMessages()"
(messageSent)="onMessageSent($event)" (messageSent)="onMessageSent($event)"
(fileSelected)="onFileSelected($event)" (fileSelected)="onFileSelected($event)"
(voiceToggled)="onVoiceToggled($event)" (voiceToggled)="onVoiceToggled($event)"
/> />
</div> </div>
</div> </div>
+104 -3
View File
@@ -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 { CommonModule } from '@angular/common';
import { AiChatInputComponent } from '../../shared/ui/ai-chat-input/ai-chat-input.component'; 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 { ThemeService } from '../../services/theme/theme.service';
import { Subscription } from 'rxjs';
const HOME_TITLES = [
'چه چیزی می‌خواهید بدانید؟...',
'سوالتان را بپرسید، با شما هستم...',
'هر سوالی دارید، از من بپرسید...',
'از هر چیزی که می‌خواهید شروع کنید...',
'سوالتان را مطرح کنید، پاسخ می‌دهم...',
'بپرسید؛ با هم به پاسخ می‌رسیم...',
'هر سوالی در ذهن دارید، بپرسید...',
'دنبال یک پاسخ دقیق هستید؟...',
'سوالتان را همین‌جا مطرح کنید...',
'آماده‌ام به سوالتان پاسخ بدهم...',
];
@Component({ @Component({
selector: 'app-home', selector: 'app-home',
@@ -11,14 +34,92 @@ import { ThemeService } from '../../services/theme/theme.service';
templateUrl: './home.page.html', templateUrl: './home.page.html',
styleUrl: './home.page.css', styleUrl: './home.page.css',
}) })
export class HomePage { export class HomePage implements OnInit, OnDestroy {
private readonly themeService = inject(ThemeService); private readonly themeService = inject(ThemeService);
private readonly router = inject(Router);
readonly isDarkMode = this.themeService.isDarkMode; 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<typeof setTimeout> | 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 { onMessageSent(message: string): void {
this.hasMessages.set(true);
console.log('Message sent:', message); console.log('Message sent:', message);
} }
+6 -1
View File
@@ -1,5 +1,8 @@
.settings-page { .settings-page {
min-height: 100vh; min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
} }
.settings-header { .settings-header {
@@ -104,7 +107,9 @@
} }
.setting-item { .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; } .setting-item:nth-child(1) { animation-delay: 0.05s; }
@@ -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<MediaStream> {
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');
}
}
}
@@ -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<typeof setTimeout> | null = null;
private stopTimer: ReturnType<typeof setTimeout> | 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<string> {
this.clearRestartTimer();
this.running = false;
const recognition = this.recognition;
if (!recognition) {
return Promise.resolve(this.promoteInterim());
}
return new Promise<string>((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;
}
}
+198 -172
View File
@@ -1,57 +1,77 @@
import { Injectable, NgZone, inject } from '@angular/core'; import { Injectable, NgZone, inject } from '@angular/core';
import * as THREE from 'three'; 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' }) @Injectable({ providedIn: 'root' })
export class VoiceOrbService { 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 scene: THREE.Scene | null = null;
private camera: THREE.PerspectiveCamera | null = null; private camera: THREE.PerspectiveCamera | null = null;
private renderer: THREE.WebGLRenderer | null = null; private renderer: THREE.WebGLRenderer | null = null;
private orb: THREE.Mesh | 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 glowShell: THREE.Mesh | null = null;
private originalPositions: Float32Array | null = null; private originalPositions: Float32Array | null = null;
private resizeObserver: ResizeObserver | null = null;
private animationId: number | null = null; private animationId: number | null = null;
private audioContext: AudioContext | null = null; private audioContext: AudioContext | null = null;
private analyser: AnalyserNode | null = null; private analyser: AnalyserNode | null = null;
private mediaStream: MediaStream | null = null; private sourceNode: MediaStreamAudioSourceNode | null = null;
private audioDataArray: Uint8Array | null = null; private audioData: Uint8Array<ArrayBuffer> | null = null;
private isListening = false; private smoothedLevel = 0;
private readonly reducedMotion: boolean;
constructor(private readonly ngZone: NgZone) { /**
this.reducedMotion = typeof window !== 'undefined' * Creates the scene once and reuses it on later calls (re-attaching the canvas if needed).
&& window.matchMedia('(prefers-reduced-motion: reduce)').matches; * Returns false if WebGL is unavailable so the caller can show a fallback.
} */
init(container: HTMLElement): boolean {
init(container: HTMLElement): void { if (this.scene && this.renderer) {
if (this.scene) { if (this.renderer.domElement.parentNode !== container) {
if (this.renderer && this.renderer.domElement.parentNode !== container) {
container.appendChild(this.renderer.domElement); container.appendChild(this.renderer.domElement);
} }
this.resize(container); this.resize(container);
return; return true;
} }
const width = container.clientWidth || 280; const width = container.clientWidth || FALLBACK_SIZE;
const height = container.clientHeight || 280; const height = container.clientHeight || FALLBACK_SIZE;
this.scene = new THREE.Scene(); let renderer: THREE.WebGLRenderer;
try {
this.camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100); renderer = new THREE.WebGLRenderer({
this.camera.position.z = 4;
this.renderer = new THREE.WebGLRenderer({
antialias: true, antialias: true,
alpha: true, alpha: true,
powerPreference: 'high-performance', powerPreference: 'high-performance',
}); });
this.renderer.setSize(width, height); } catch (err) {
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); console.warn('VoiceOrbService: WebGL is not available.', err);
this.renderer.setClearColor(0x000000, 0); return false;
container.appendChild(this.renderer.domElement); }
const ambientLight = new THREE.AmbientLight(0x404060, 2); this.renderer = renderer;
this.scene.add(ambientLight); 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.scene.add(new THREE.AmbientLight(0x404060, 2));
const pointLight1 = new THREE.PointLight(0x3b82f6, 12, 10); const pointLight1 = new THREE.PointLight(0x3b82f6, 12, 10);
pointLight1.position.set(0, 0, 3); pointLight1.position.set(0, 0, 3);
@@ -65,7 +85,16 @@ export class VoiceOrbService {
pointLight3.position.set(2, -1, 2); pointLight3.position.set(2, -1, 2);
this.scene.add(pointLight3); 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({ const orbMaterial = new THREE.MeshPhysicalMaterial({
color: 0x60a5fa, color: 0x60a5fa,
emissive: 0x1e3a5f, emissive: 0x1e3a5f,
@@ -75,12 +104,9 @@ export class VoiceOrbService {
clearcoat: 1, clearcoat: 1,
clearcoatRoughness: 0.08, clearcoatRoughness: 0.08,
}); });
this.orb = new THREE.Mesh(this.orbGeometry, orbMaterial); this.orb = new THREE.Mesh(geometry, orbMaterial);
this.scene.add(this.orb); 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({ const glowMaterial = new THREE.MeshBasicMaterial({
color: 0x3b82f6, color: 0x3b82f6,
transparent: true, transparent: true,
@@ -89,31 +115,29 @@ export class VoiceOrbService {
side: THREE.BackSide, side: THREE.BackSide,
depthWrite: false, 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.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 { resize(container: HTMLElement): void {
if (typeof ResizeObserver === 'undefined') return; if (!this.renderer || !this.camera) return;
const width = container.clientWidth || FALLBACK_SIZE;
const observer = new ResizeObserver((entries) => { const height = container.clientHeight || FALLBACK_SIZE;
for (const entry of entries) { this.renderer.setSize(width, height, false);
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.aspect = width / height;
this.camera.updateProjectionMatrix(); this.camera.updateProjectionMatrix();
} }
}
}); // ---- animation loop -------------------------------------------------------
observer.observe(container);
}
startAnimation(): void { 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(() => { this.ngZone.runOutsideAngular(() => {
const animate = (): void => { const animate = (): void => {
this.animationId = requestAnimationFrame(animate); 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 { resetOrbGeometry(): void {
if (!this.orbGeometry || !this.originalPositions) return; if (!this.orbGeometry || !this.originalPositions) return;
const positions = this.orbGeometry.attributes['position']; const positions = this.orbGeometry.attributes['position'];
const original = this.originalPositions; positions.array.set(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.needsUpdate = true; positions.needsUpdate = true;
this.orbGeometry.computeVertexNormals(); this.orbGeometry.computeVertexNormals();
this.smoothedLevel = 0;
} }
resize(container: HTMLElement): void { // ---- audio ----------------------------------------------------------------
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<void> {
if (this.isListening) return;
/** Starts analysing the stream. The stream stays owned (and stopped) by the caller. */
attachStream(stream: MediaStream): void {
this.detachAudio();
try { try {
this.mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true });
this.audioContext = new AudioContext(); 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 = this.audioContext.createAnalyser();
this.analyser.fftSize = 256; this.analyser.fftSize = 256;
this.analyser.smoothingTimeConstant = 0.75; this.analyser.smoothingTimeConstant = 0.75;
source.connect(this.analyser); this.sourceNode.connect(this.analyser);
this.audioDataArray = new Uint8Array(this.analyser.frequencyBinCount); this.audioData = new Uint8Array(this.analyser.frequencyBinCount);
this.isListening = true;
} catch (err) { } catch (err) {
console.warn('VoiceOrbService: unable to access microphone.', err); // The orb keeps animating from time alone.
this.isListening = false; console.warn('VoiceOrbService: audio analysis unavailable.', err);
this.detachAudio();
} }
} }
stopListening(): void { /** Stops audio-reactive processing (does not stop the MediaStream tracks). */
if (this.mediaStream) { detachAudio(): void {
this.mediaStream.getTracks().forEach((track) => track.stop()); this.sourceNode?.disconnect();
this.mediaStream = null; this.sourceNode = null;
} this.analyser = null;
this.audioData = null;
this.smoothedLevel = 0;
if (this.audioContext && this.audioContext.state !== 'closed') { if (this.audioContext && this.audioContext.state !== 'closed') {
this.audioContext.close().catch(() => {}); this.audioContext.close().catch(() => undefined);
} }
this.audioContext = null; this.audioContext = null;
this.analyser = null;
this.audioDataArray = null;
this.isListening = false;
} }
private getAudioLevel(): number { // ---- cleanup --------------------------------------------------------------
if (!this.isListening || !this.analyser || !this.audioDataArray) return 0;
this.analyser.getByteFrequencyData(this.audioDataArray as Uint8Array<ArrayBuffer>);
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);
}
dispose(): void { dispose(): void {
this.stopAnimation(); 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) { if (this.renderer) {
this.renderer.dispose();
const canvas = this.renderer.domElement; const canvas = this.renderer.domElement;
if (canvas.parentNode) { this.renderer.dispose();
canvas.parentNode.removeChild(canvas); canvas.parentNode?.removeChild(canvas);
}
} }
this.scene = null; this.scene = null;
@@ -292,4 +227,95 @@ export class VoiceOrbService {
this.glowShell = null; this.glowShell = null;
this.originalPositions = 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;
}
} }
@@ -1,33 +1,40 @@
:host {
display: block;
}
.ai-chat-input-wrapper { .ai-chat-input-wrapper {
width: 100%; width: 100%;
max-width: 800px; max-width: 800px;
margin: 0 auto; margin: 0 auto;
position: relative; position: relative;
min-height: 72px; 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 { .ai-chat-input-wrapper.voice-active {
min-height: 380px; min-height: 460px;
} }
/* Layers transition */ /* Layers cross-fade */
.composer-layer, .composer-layer,
.voice-layer { .voice-layer {
transition: opacity 0.35s ease, transform 0.35s ease; transition:
opacity 0.35s ease,
transform 0.35s ease;
} }
.composer-layer { .composer-layer {
position: relative; position: relative;
opacity: 1; opacity: 1;
transform: translateY(0); transform: translateY(0);
pointer-events: auto;
} }
.voice-layer { .voice-layer {
position: absolute; position: absolute;
inset: 0; inset: 0;
opacity: 0; opacity: 0;
transform: translateY(10px); transform: translateY(10px) scale(0.98);
pointer-events: none; pointer-events: none;
} }
@@ -38,32 +45,39 @@
} }
.ai-chat-input-wrapper.voice-active .voice-layer { .ai-chat-input-wrapper.voice-active .voice-layer {
position: relative;
opacity: 1; opacity: 1;
transform: translateY(0); transform: translateY(0) scale(1);
pointer-events: auto; pointer-events: auto;
} }
/* Chat Composer */ /* ---------- 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; display: flex;
align-items: flex-end; align-items: center;
gap: 0.375rem; gap: 0.375rem;
padding: 0.625rem 0.75rem; padding: 0.625rem 0.75rem;
background: var(--surface-bg); background: var(--surface-bg);
border: 1px solid var(--surface-border); border: 1px solid var(--surface-border);
border-radius: 1.5rem; border-radius: 2rem;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03); box-shadow:
transition: box-shadow 0.2s ease, border-color 0.2s ease; 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; position: relative;
} }
.chat-composer:focus-within { .chat-composer:focus-within {
border-color: var(--color-primary); 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 { .composer-textarea-wrapper {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
@@ -98,17 +112,15 @@
cursor: not-allowed; cursor: not-allowed;
} }
/* Remove scrollbar but keep functionality */
.composer-textarea::-webkit-scrollbar { .composer-textarea::-webkit-scrollbar {
width: 4px; width: 4px;
} }
.composer-textarea::-webkit-scrollbar-thumb { .composer-textarea::-webkit-scrollbar-thumb {
background: var(--muted); background: var(--muted);
border-radius: 9999px; border-radius: 9999px;
opacity: 0.3;
} }
/* Action Buttons */ /* ---------- Action buttons ---------- */
.composer-btn { .composer-btn {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -120,7 +132,10 @@
background: transparent; background: transparent;
color: var(--muted); color: var(--muted);
cursor: pointer; 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; flex-shrink: 0;
user-select: none; user-select: none;
} }
@@ -155,7 +170,28 @@
color: #ffffff; 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 { .attachment-menu {
position: absolute; position: absolute;
bottom: calc(100% + 0.5rem); bottom: calc(100% + 0.5rem);
@@ -164,7 +200,9 @@
background: var(--surface-bg); background: var(--surface-bg);
border: 1px solid var(--surface-border); border: 1px solid var(--surface-border);
border-radius: 0.875rem; 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; overflow: hidden;
z-index: 50; z-index: 50;
animation: menuFadeIn 0.15s ease; animation: menuFadeIn 0.15s ease;
@@ -186,7 +224,8 @@
transition: background 0.15s ease; transition: background 0.15s ease;
} }
.attachment-menu-item:hover { .attachment-menu-item:hover,
.attachment-menu-item:focus-visible {
background: var(--sidebar-hover); background: var(--sidebar-hover);
color: var(--text-primary); color: var(--text-primary);
} }
@@ -194,7 +233,6 @@
.attachment-menu-item:focus-visible { .attachment-menu-item:focus-visible {
outline: 2px solid var(--color-primary); outline: 2px solid var(--color-primary);
outline-offset: -2px; outline-offset: -2px;
background: var(--sidebar-hover);
} }
@keyframes menuFadeIn { @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 { .voice-mode {
direction: rtl;
box-sizing: border-box;
height: 100%;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
gap: 1.25rem; gap: 1rem;
padding: 1.5rem; padding: 1.25rem;
background: var(--surface-bg); background: var(--surface-bg);
border: 1px solid var(--surface-border); border: 1px solid var(--surface-border);
border-radius: 1.5rem; border-radius: 1.5rem;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03); box-shadow:
min-height: 320px; 0 2px 12px rgba(0, 0, 0, 0.05),
0 1px 3px rgba(0, 0, 0, 0.03);
} }
.orb-container { .orb-container {
width: 260px; width: 220px;
height: 260px; height: 220px;
max-width: 100%;
position: relative; position: relative;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
flex-shrink: 0;
} }
.orb-container canvas { .orb-container canvas {
@@ -238,6 +332,58 @@
height: 100% !important; 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 { .voice-mode-text {
font-size: 0.9375rem; font-size: 0.9375rem;
color: var(--text-secondary); color: var(--text-secondary);
@@ -245,6 +391,41 @@
text-align: center; 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 { .voice-stop-btn {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -258,27 +439,47 @@
font-family: inherit; font-family: inherit;
font-size: 0.875rem; font-size: 0.875rem;
cursor: pointer; 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; user-select: none;
} }
.voice-stop-btn:hover { .voice-stop-btn:hover:not(:disabled) {
background: #ef4444; background: var(--sidebar-hover);
color: #ffffff; color: var(--text-primary);
border-color: #ef4444;
transform: scale(1.03); 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); transform: scale(0.97);
} }
.voice-stop-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.voice-stop-btn:focus-visible { .voice-stop-btn:focus-visible {
outline: 2px solid var(--color-primary); outline: 2px solid var(--color-primary);
outline-offset: 2px; outline-offset: 2px;
} }
/* Screen reader only */ /* ---------- Screen reader only ---------- */
.sr-only { .sr-only {
position: absolute; position: absolute;
width: 1px; width: 1px;
@@ -291,25 +492,37 @@
border: 0; border: 0;
} }
/* Reduced motion */ /* ---------- Reduced motion ---------- */
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
.ai-chat-input-wrapper,
.composer-layer, .composer-layer,
.voice-layer, .voice-layer,
.chat-composer, .chat-composer,
.composer-btn, .composer-btn,
.voice-stop-btn, .voice-stop-btn,
.attachment-menu { .attachment-menu,
.voice-notice {
transition: none !important; transition: none !important;
animation: none !important; animation: none !important;
} }
.rec-dot,
.orb-fallback,
.mic-btn.is-pending {
animation: none !important;
}
} }
/* Mobile responsiveness */ /* ---------- Mobile ---------- */
@media (max-width: 640px) { @media (max-width: 640px) {
.ai-chat-input-wrapper { .ai-chat-input-wrapper {
max-width: 100%; max-width: 100%;
} }
.ai-chat-input-wrapper.voice-active {
min-height: 410px;
}
.chat-composer { .chat-composer {
gap: 0.25rem; gap: 0.25rem;
padding: 0.5rem 0.625rem; padding: 0.5rem 0.625rem;
@@ -327,17 +540,22 @@
} }
.composer-textarea { .composer-textarea {
font-size: 0.875rem; /* 16px prevents iOS from zooming the page when the field is focused */
} font-size: 1rem;
.orb-container {
width: 200px;
height: 200px;
} }
.voice-mode { .voice-mode {
min-height: 280px; gap: 0.75rem;
gap: 1rem; padding: 1rem;
}
.orb-container {
width: 170px;
height: 170px;
}
.voice-stop-btn {
padding: 0.5rem 1rem;
} }
.attachment-menu { .attachment-menu {
@@ -1,24 +1,25 @@
<div class="ai-chat-input-wrapper" [class.voice-active]="isVoiceMode()"> <div
<div class="composer-layer" [class.layer-hidden]="isVoiceMode()"> class="ai-chat-input-wrapper"
[class.voice-active]="isVoiceMode()"
[attr.data-voice-state]="voiceState()"
(keydown.escape)="onEscape()"
>
<!-- Announces every voice state change to screen readers -->
<div class="sr-only" role="status" aria-live="polite">{{ statusText() }}</div>
<div class="composer-layer" [attr.inert]="isVoiceMode() ? '' : null">
<div class="chat-composer" #composer> <div class="chat-composer" #composer>
<button <button
#plusBtn
type="button" type="button"
class="composer-btn plus-btn" class="composer-btn plus-btn"
(click)="toggleAttachmentMenu()" (click)="toggleAttachmentMenu()"
[attr.aria-expanded]="isAttachmentMenuOpen()"
aria-label="افزودن پیوست" aria-label="افزودن پیوست"
aria-haspopup="menu"
aria-controls="attachment-menu"
[attr.aria-expanded]="isAttachmentMenuOpen()"
> >
<svg <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 5v14M5 12h14" /> <path d="M12 5v14M5 12h14" />
</svg> </svg>
</button> </button>
@@ -40,20 +41,17 @@
<button <button
type="button" type="button"
class="composer-btn mic-btn" class="composer-btn mic-btn"
[class.is-pending]="voiceState() === 'requesting-permission'"
[class.is-unsupported]="!voiceSupported"
[disabled]="disabled()"
[attr.aria-label]="micLabel()"
[attr.title]="micLabel()"
[attr.aria-pressed]="isVoiceMode()"
[attr.aria-busy]="voiceState() === 'requesting-permission'"
[attr.aria-disabled]="voiceSupported ? null : 'true'"
(click)="toggleVoiceMode()" (click)="toggleVoiceMode()"
aria-label="حالت صوتی"
>
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
> >
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" /> <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" />
<path d="M19 10v2a7 7 0 0 1-14 0v-2" /> <path d="M19 10v2a7 7 0 0 1-14 0v-2" />
<line x1="12" x2="12" y1="19" y2="22" /> <line x1="12" x2="12" y1="19" y2="22" />
@@ -67,68 +65,45 @@
(click)="sendMessage()" (click)="sendMessage()"
aria-label="ارسال پیام" aria-label="ارسال پیام"
> >
<svg <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 19V5M5 12l7-7 7 7" /> <path d="M12 19V5M5 12l7-7 7 7" />
</svg> </svg>
</button> </button>
@if (isAttachmentMenuOpen()) { @if (isAttachmentMenuOpen()) {
<div class="attachment-menu" role="menu"> <div
#attachmentMenu
id="attachment-menu"
class="attachment-menu"
role="menu"
aria-label="پیوست‌ها"
(keydown)="onMenuKeydown($event)"
>
@for (action of attachmentActions(); track action.id) {
<button <button
type="button" type="button"
class="attachment-menu-item" class="attachment-menu-item"
role="menuitem" role="menuitem"
(click)="selectFile(); closeAttachmentMenu();" (click)="selectAction(action)"
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" />
<polyline points="14 2 14 8 20 8" />
</svg>
<span>آپلود فایل</span>
</button>
<button
type="button"
class="attachment-menu-item"
role="menuitem"
(click)="selectFile(); closeAttachmentMenu();"
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
> >
@switch (action.icon) {
@case ('image') {
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2" /> <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
<circle cx="8.5" cy="8.5" r="1.5" /> <circle cx="8.5" cy="8.5" r="1.5" />
<polyline points="21 15 16 10 5 21" /> <polyline points="21 15 16 10 5 21" />
</svg> </svg>
<span>آپلود تصویر</span> }
@default {
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" />
<polyline points="14 2 14 8 20 8" />
</svg>
}
}
<span>{{ action.label }}</span>
</button> </button>
}
</div> </div>
} }
@@ -136,38 +111,84 @@
#fileInput #fileInput
type="file" type="file"
class="sr-only" class="sr-only"
tabindex="-1"
(change)="onFileChange($event)" (change)="onFileChange($event)"
aria-hidden="true" aria-hidden="true"
/> />
</div> </div>
</div>
<div class="voice-layer" [class.layer-hidden]="!isVoiceMode()"> @if (notice(); as n) {
<div class="voice-mode" #voiceContainer> <div
<div class="orb-container" #orbContainer></div> class="voice-notice"
<p class="voice-mode-text">در حال گوش دادن...</p> [class.is-error]="n.kind === 'error'"
<button [attr.role]="n.kind === 'error' ? 'alert' : 'status'"
type="button"
class="voice-stop-btn"
(click)="exitVoiceMode()"
aria-label="خروج از حالت صوتی"
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
> >
<span class="voice-notice-text">{{ n.text }}</span>
<button type="button" class="voice-notice-close" aria-label="بستن پیام" (click)="dismissNotice()">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="18" x2="6" y1="6" y2="18" /> <line x1="18" x2="6" y1="6" y2="18" />
<line x1="6" x2="18" y1="6" y2="18" /> <line x1="6" x2="18" y1="6" y2="18" />
</svg> </svg>
<span>پایان گفتگو</span> </button>
</div>
}
</div>
<div
class="voice-layer"
[attr.inert]="isVoiceMode() ? null : ''"
[attr.aria-hidden]="isVoiceMode() ? null : 'true'"
>
<div class="voice-mode" role="region" aria-label="حالت صوتی">
<div class="orb-container" #orbContainer aria-hidden="true">
@if (!orbAvailable()) {
<div class="orb-fallback"></div>
}
</div>
<div class="voice-status" [class.is-speaking]="voiceState() === 'transcribing'">
<span class="rec-dot" aria-hidden="true"></span>
<p class="voice-mode-text">{{ statusText() }}</p>
</div>
<div class="voice-transcript" #transcript dir="rtl">
@if (liveFinal() || liveInterim()) {
<span class="t-final">{{ liveFinal() }}</span>
@if (liveInterim()) {
<span class="t-interim"> {{ liveInterim() }}</span>
}
} @else {
<span class="t-placeholder">صحبت کنید؛ متن اینجا نمایش داده می‌شود</span>
}
</div>
<div class="voice-actions">
<button
type="button"
class="voice-stop-btn is-primary"
[disabled]="voiceState() === 'stopping'"
(click)="stopVoice(true)"
aria-label="پایان ضبط و ویرایش متن"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<rect x="6" y="6" width="12" height="12" rx="2" />
</svg>
<span>پایان و ویرایش</span>
</button>
<button
type="button"
class="voice-stop-btn"
[disabled]="voiceState() === 'stopping'"
(click)="stopVoice(false)"
aria-label="لغو ضبط و حذف متن گفتاری"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="18" x2="6" y1="6" y2="18" />
<line x1="6" x2="18" y1="6" y2="18" />
</svg>
<span>لغو</span>
</button> </button>
</div> </div>
</div> </div>
</div>
</div> </div>
@@ -1,91 +1,195 @@
import { import {
ChangeDetectionStrategy, ChangeDetectionStrategy,
Component, Component,
ElementRef,
Injector,
OnDestroy,
afterNextRender,
computed,
effect,
inject,
input, input,
output, output,
signal, signal,
ViewChild, viewChild,
ElementRef,
AfterViewChecked,
OnInit,
OnDestroy,
inject,
} from '@angular/core'; } 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'; 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<string, string> = {
unsupported: 'مرورگر شما از دسترسی به میکروفون پشتیبانی نمی‌کند (اتصال امن HTTPS لازم است).',
denied: 'دسترسی به میکروفون رد شد. اجازه‌ی دسترسی را در تنظیمات مرورگر فعال کنید.',
unavailable: 'میکروفونی پیدا نشد یا در حال استفاده‌ی برنامه‌ی دیگری است.',
unknown: 'دسترسی به میکروفون ممکن نشد. دوباره تلاش کنید.',
};
const SPEECH_ERRORS: Record<SpeechErrorKind, string> = {
'permission-denied': 'اجازه‌ی استفاده از تشخیص گفتار داده نشد. تنظیمات مرورگر را بررسی کنید.',
'audio-capture': 'میکروفون در دسترس نیست. اتصال آن را بررسی کنید.',
network: 'اتصال به سرویس تشخیص گفتار برقرار نشد. اینترنت خود را بررسی کنید.',
'no-speech': 'گفتاری شناسایی نشد. دوباره تلاش کنید.',
'language-not-supported': 'این زبان توسط تشخیص گفتار مرورگر پشتیبانی نمی‌شود.',
unsupported: 'تبدیل گفتار به متن در این مرورگر پشتیبانی نمی‌شود. از Chrome یا Edge استفاده کنید.',
unknown: 'تشخیص گفتار با خطا متوقف شد. دوباره تلاش کنید.',
};
@Component({ @Component({
selector: 'app-ai-chat-input', selector: 'app-ai-chat-input',
standalone: true, standalone: true,
imports: [CommonModule],
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './ai-chat-input.component.html', templateUrl: './ai-chat-input.component.html',
styleUrl: './ai-chat-input.component.css', styleUrl: './ai-chat-input.component.css',
}) })
export class AiChatInputComponent implements AfterViewChecked, OnInit, OnDestroy { export class AiChatInputComponent implements OnDestroy {
private readonly voiceOrbService = inject(VoiceOrbService); private readonly injector = inject(Injector);
private readonly voiceOrb = inject(VoiceOrbService);
private readonly mic = inject(MicrophoneService);
private readonly speech = inject(SpeechRecognitionService);
// ---- API ------------------------------------------------------------------
readonly placeholder = input<string>('پیام خود را بنویسید...'); readonly placeholder = input<string>('پیام خود را بنویسید...');
readonly disabled = input<boolean>(false); readonly disabled = input<boolean>(false);
readonly hasMessages = input<boolean>(false);
/** Speech recognition language (BCP-47), e.g. 'fa-IR' or 'en-US'. */
readonly language = input<string>(DEFAULT_SPEECH_LANGUAGE);
readonly attachmentActions = input<readonly AttachmentAction[]>(DEFAULT_ATTACHMENT_ACTIONS);
readonly messageSent = output<string>(); readonly messageSent = output<string>();
readonly fileSelected = output<File>(); readonly fileSelected = output<File>();
readonly voiceToggled = output<boolean>(); readonly voiceToggled = output<boolean>();
// ---- state ----------------------------------------------------------------
readonly message = signal(''); readonly message = signal('');
readonly isVoiceMode = signal(false);
readonly isAttachmentMenuOpen = signal(false); readonly isAttachmentMenuOpen = signal(false);
@ViewChild('textarea') textareaRef!: ElementRef<HTMLTextAreaElement>; readonly voiceState = signal<VoiceState>('idle');
@ViewChild('composer') composerRef!: ElementRef<HTMLDivElement>; readonly notice = signal<Notice | null>(null);
@ViewChild('voiceContainer') voiceContainerRef!: ElementRef<HTMLDivElement>; readonly liveFinal = signal('');
@ViewChild('orbContainer') orbContainerRef!: ElementRef<HTMLDivElement>; readonly liveInterim = signal('');
@ViewChild('fileInput') fileInputRef!: ElementRef<HTMLInputElement>; readonly orbAvailable = signal(true);
private orbInited = false; readonly voiceSupported = this.mic.isSupported && this.speech.isSupported;
private menuCloseHandler: ((event: MouseEvent) => void) | null = null;
private escapeHandler: ((event: KeyboardEvent) => void) | null = null;
selectFile(): void { /** The orb view replaces the composer while recording, transcribing and stopping. */
this.fileInputRef?.nativeElement.click(); 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<ElementRef<HTMLTextAreaElement>>('textarea');
private readonly composerRef = viewChild<ElementRef<HTMLDivElement>>('composer');
private readonly fileInputRef = viewChild<ElementRef<HTMLInputElement>>('fileInput');
private readonly plusBtnRef = viewChild<ElementRef<HTMLButtonElement>>('plusBtn');
private readonly menuRef = viewChild<ElementRef<HTMLDivElement>>('attachmentMenu');
private readonly orbContainerRef = viewChild<ElementRef<HTMLDivElement>>('orbContainer');
private readonly transcriptRef = viewChild<ElementRef<HTMLDivElement>>('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<typeof setTimeout> | 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 { ngOnDestroy(): void {
this.detachDocumentListeners(); this.voiceSession++;
this.voiceOrbService.dispose(); this.speech.dispose();
this.mic.release();
this.voiceOrb.dispose();
this.clearNoticeTimer();
} }
// ---- text input -----------------------------------------------------------
onTextareaInput(): void { onTextareaInput(): void {
const textarea = this.textareaRef?.nativeElement; const textarea = this.textareaRef()?.nativeElement;
if (!textarea) return; if (!textarea) return;
this.message.set(textarea.value); this.message.set(textarea.value);
this.autoResize(textarea);
textarea.style.height = 'auto';
const scrollHeight = textarea.scrollHeight;
const maxHeight = 192;
const newHeight = Math.min(scrollHeight, maxHeight);
textarea.style.height = newHeight + 'px';
} }
onKeyDown(event: KeyboardEvent): void { onKeyDown(event: KeyboardEvent): void {
if (event.key === 'Enter' && !event.shiftKey) { if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
event.preventDefault(); event.preventDefault();
this.sendMessage(); this.sendMessage();
} }
@@ -93,85 +197,323 @@ export class AiChatInputComponent implements AfterViewChecked, OnInit, OnDestroy
sendMessage(): void { sendMessage(): void {
const text = this.message().trim(); const text = this.message().trim();
if (!text) return; if (!text || this.disabled()) return;
this.messageSent.emit(text); this.messageSent.emit(text);
this.message.set(''); this.setTextareaValue('');
}
const textarea = this.textareaRef?.nativeElement; private setTextareaValue(value: string): void {
if (textarea) { const textarea = this.textareaRef()?.nativeElement;
textarea.value = ''; 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 = '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 { 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 { closeAttachmentMenu(): void {
this.isAttachmentMenuOpen.set(false); 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 { onFileChange(event: Event): void {
const input = event.target as HTMLInputElement; const input = event.target as HTMLInputElement;
const file = input.files?.[0]; const file = input.files?.[0];
if (file) { if (file) {
this.fileSelected.emit(file); this.fileSelected.emit(file);
} }
if (input.value) {
input.value = ''; input.value = '';
} }
this.closeAttachmentMenu();
}
toggleVoiceMode(): void { onMenuKeydown(event: KeyboardEvent): void {
if (this.isVoiceMode()) { const items = this.menuItems();
this.exitVoiceMode(); if (!items.length) return;
} else { const index = items.indexOf(document.activeElement as HTMLElement);
this.enterVoiceMode();
}
}
private enterVoiceMode(): void { let next = -1;
this.isVoiceMode.set(true); switch (event.key) {
this.orbInited = false; case 'ArrowDown':
this.voiceToggled.emit(true); next = (index + 1) % items.length;
} break;
case 'ArrowUp':
exitVoiceMode(): void { next = (index - 1 + items.length) % items.length;
this.voiceOrbService.stopAnimation(); break;
this.voiceOrbService.stopListening(); case 'Home':
this.isVoiceMode.set(false); next = 0;
this.voiceToggled.emit(false); break;
} case 'End':
next = items.length - 1;
private attachDocumentListeners(): void { break;
this.menuCloseHandler = (event: MouseEvent) => { default:
if (!this.isAttachmentMenuOpen()) return;
const target = event.target as Node;
if (this.composerRef && this.composerRef.nativeElement.contains(target)) {
return; return;
} }
event.preventDefault();
items[next].focus();
}
private menuItems(): HTMLElement[] {
const menu = this.menuRef()?.nativeElement;
return menu ? Array.from(menu.querySelectorAll<HTMLElement>('[role="menuitem"]')) : [];
}
onEscape(): void {
if (this.isAttachmentMenuOpen()) {
this.closeAttachmentMenu(); this.closeAttachmentMenu();
}; this.plusBtnRef()?.nativeElement.focus();
} else if (this.isVoiceMode()) {
void this.stopVoice(true);
}
}
this.escapeHandler = (event: KeyboardEvent) => { // ---- voice: start ---------------------------------------------------------
if (event.key === 'Escape' && this.isAttachmentMenuOpen()) {
async toggleVoiceMode(): Promise<void> {
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<void> {
if (this.disabled()) return;
this.dismissNotice();
this.closeAttachmentMenu(); this.closeAttachmentMenu();
}
};
document.addEventListener('mousedown', this.menuCloseHandler); if (!this.mic.isSupported) {
document.addEventListener('keydown', this.escapeHandler); this.failBeforeStart(MIC_ERRORS['unsupported']);
return;
}
if (!this.speech.isSupported) {
this.failBeforeStart(SPEECH_ERRORS.unsupported);
return;
} }
private detachDocumentListeners(): void { const session = ++this.voiceSession;
if (this.menuCloseHandler) { this.voiceState.set('requesting-permission');
document.removeEventListener('mousedown', this.menuCloseHandler);
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 (this.escapeHandler) {
document.removeEventListener('keydown', this.escapeHandler); 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<void> {
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;
} }
} }
} }
@@ -178,7 +178,8 @@
border-radius: 0.5rem; border-radius: 0.5rem;
color: var(--sidebar-muted); color: var(--sidebar-muted);
text-decoration: none; text-decoration: none;
font-size: 0.875rem; font-size: 1rem;
font-weight: 500;
transition: background 0.2s; transition: background 0.2s;
} }
@@ -34,6 +34,7 @@
[routerLink]="item.route" [routerLink]="item.route"
class="nav-item" class="nav-item"
routerLinkActive="active" routerLinkActive="active"
[routerLinkActiveOptions]="{ exact: true }"
(click)="onNavClick()" (click)="onNavClick()"
> >
<svg <svg
@@ -32,6 +32,7 @@ export class SidebarComponent {
{ {
icon: 'M12 5v14M5 12h14', icon: 'M12 5v14M5 12h14',
label: 'چت جدید', label: 'چت جدید',
route: '/',
}, },
{ {
icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.573-1.066zM15 12a3 3 0 11-6 0 3 3 0 016 0z', icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.573-1.066zM15 12a3 3 0 11-6 0 3 3 0 016 0z',
+8 -1
View File
@@ -10,7 +10,7 @@
--color-info: #06b6d4; --color-info: #06b6d4;
--color-card-bg: #ffffff; --color-card-bg: #ffffff;
--color-card-border: #e2e8f0; --color-card-border: #e2e8f0;
--color-text-primary: #122033; --color-text-primary: #1D3557;
--color-text-secondary: #374151; --color-text-secondary: #374151;
--color-text-muted: #64748b; --color-text-muted: #64748b;
--color-input-bg: #ffffff; --color-input-bg: #ffffff;
@@ -36,6 +36,9 @@
--main-content-bg: #f8fafc; --main-content-bg: #f8fafc;
--toggle-bg: #e5e7eb; --toggle-bg: #e5e7eb;
--toggle-slider: #ffffff; --toggle-slider: #ffffff;
--text-primary: var(--color-text-primary);
--text-secondary: var(--color-text-secondary);
--text-muted: var(--color-text-muted);
} }
[data-bs-theme="dark"] { [data-bs-theme="dark"] {
@@ -65,6 +68,10 @@
--color-input-border: #3e3e3e; --color-input-border: #3e3e3e;
--color-dropzone-bg: rgba(23, 23, 23, 0.6); --color-dropzone-bg: rgba(23, 23, 23, 0.6);
--color-dropzone-border: #3e3e3e; --color-dropzone-border: #3e3e3e;
--text-primary: var(--color-text-primary);
--text-secondary: var(--color-text-secondary);
--text-muted: var(--color-text-muted);
} }
* { * {