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,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 {
@@ -1,24 +1,25 @@
<div class="ai-chat-input-wrapper" [class.voice-active]="isVoiceMode()">
<div class="composer-layer" [class.layer-hidden]="isVoiceMode()">
<div
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>
<button
#plusBtn
type="button"
class="composer-btn plus-btn"
(click)="toggleAttachmentMenu()"
[attr.aria-expanded]="isAttachmentMenuOpen()"
aria-label="افزودن پیوست"
aria-haspopup="menu"
aria-controls="attachment-menu"
[attr.aria-expanded]="isAttachmentMenuOpen()"
>
<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 5v14M5 12h14" />
</svg>
</button>
@@ -40,20 +41,17 @@
<button
type="button"
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()"
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="M19 10v2a7 7 0 0 1-14 0v-2" />
<line x1="12" x2="12" y1="19" y2="22" />
@@ -67,68 +65,45 @@
(click)="sendMessage()"
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 19V5M5 12l7-7 7 7" />
</svg>
</button>
@if (isAttachmentMenuOpen()) {
<div class="attachment-menu" role="menu">
<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"
<div
#attachmentMenu
id="attachment-menu"
class="attachment-menu"
role="menu"
aria-label="پیوست‌ها"
(keydown)="onMenuKeydown($event)"
>
@for (action of attachmentActions(); track action.id) {
<button
type="button"
class="attachment-menu-item"
role="menuitem"
(click)="selectAction(action)"
>
<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"
>
<rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
<circle cx="8.5" cy="8.5" r="1.5" />
<polyline points="21 15 16 10 5 21" />
</svg>
<span>آپلود تصویر</span>
</button>
@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" />
<circle cx="8.5" cy="8.5" r="1.5" />
<polyline points="21 15 16 10 5 21" />
</svg>
}
@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>
}
</div>
}
@@ -136,38 +111,84 @@
#fileInput
type="file"
class="sr-only"
tabindex="-1"
(change)="onFileChange($event)"
aria-hidden="true"
/>
</div>
@if (notice(); as n) {
<div
class="voice-notice"
[class.is-error]="n.kind === 'error'"
[attr.role]="n.kind === 'error' ? 'alert' : 'status'"
>
<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="6" x2="18" y1="6" y2="18" />
</svg>
</button>
</div>
}
</div>
<div class="voice-layer" [class.layer-hidden]="!isVoiceMode()">
<div class="voice-mode" #voiceContainer>
<div class="orb-container" #orbContainer></div>
<p class="voice-mode-text">در حال گوش دادن...</p>
<button
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"
<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="پایان ضبط و ویرایش متن"
>
<line x1="18" x2="6" y1="6" y2="18" />
<line x1="6" x2="18" y1="6" y2="18" />
</svg>
<span>پایان گفتگو</span>
</button>
<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>
</div>
</div>
</div>
</div>
</div>
@@ -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<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({
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<string>('پیام خود را بنویسید...');
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 fileSelected = output<File>();
readonly voiceToggled = output<boolean>();
// ---- state ----------------------------------------------------------------
readonly message = signal('');
readonly isVoiceMode = signal(false);
readonly isAttachmentMenuOpen = signal(false);
@ViewChild('textarea') textareaRef!: ElementRef<HTMLTextAreaElement>;
@ViewChild('composer') composerRef!: ElementRef<HTMLDivElement>;
@ViewChild('voiceContainer') voiceContainerRef!: ElementRef<HTMLDivElement>;
@ViewChild('orbContainer') orbContainerRef!: ElementRef<HTMLDivElement>;
@ViewChild('fileInput') fileInputRef!: ElementRef<HTMLInputElement>;
readonly voiceState = signal<VoiceState>('idle');
readonly notice = signal<Notice | null>(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<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 {
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<HTMLElement>('[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<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();
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<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;
color: var(--sidebar-muted);
text-decoration: none;
font-size: 0.875rem;
font-size: 1rem;
font-weight: 500;
transition: background 0.2s;
}
@@ -34,6 +34,7 @@
[routerLink]="item.route"
class="nav-item"
routerLinkActive="active"
[routerLinkActiveOptions]="{ exact: true }"
(click)="onNavClick()"
>
<svg
@@ -32,6 +32,7 @@ export class SidebarComponent {
{
icon: 'M12 5v14M5 12h14',
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',