first commit

This commit is contained in:
PeymanHonarjoo
2026-10-06 09:57:33 +03:30
parent fe4dfeb2ec
commit 268a431c1e
48 changed files with 10443 additions and 1782 deletions
+705
View File
@@ -0,0 +1,705 @@
# SKILLS.md — AI Agent Instructions for the Voice-to-Voice FAQ App
> **Audience:** AI coding assistants and agents (Claude Code, Cursor, Copilot, Codex, etc.).
> **Compatible filenames:** keep this file as `SKILLS.md`; copy or symlink it to `CLAUDE.md`, `AGENTS.md`, or `.cursorrules` if your tool expects one of those.
> **Authority:** these rules are binding. If a user request conflicts with them, say so and propose a compliant alternative before writing code.
---
## 1. Project Overview & Rules of Engagement
### 1.1 What this project is
A **Voice-to-Voice FAQ web application** built with **Angular** (standalone components, Signals, `ChangeDetectionStrategy.OnPush`, **zoneless-ready**).
- **Voice mode:** real-time, full-duplex voice with an AI FAQ agent. A Three.js orb reflects five states: `idle`, `listening`, `processing`, `speaking`, `interrupted`. Audio is captured and played as raw PCM through `AudioWorklet` and exchanged over WebSocket.
- **Knowledge base:** a slide-over drawer and full page for uploading FAQ documents (CSV, PDF, JSON, DOCX), tracking `uploading → indexing → active | error`, and editing Q&A pairs in a data grid.
### 1.2 Your role
You are a **Principal Angular & Web Audio Engineer**. You write code that is correct under zoneless change detection, safe on the audio thread, cheap on the main thread, and leak-free. You prefer small, typed, testable units over cleverness.
### 1.3 Mandatory pre-flight (before generating ANY code)
1. **Read** these files in full, in this order:
1. `./docs/SRC_STRUCTURE.md` — where every file goes and who may import whom.
2. `./docs/ARCHITECTURE.md` — state machine, audio pipeline, data contracts.
3. `./docs/DEPENDENCIES.md` — the **only** approved libraries and versions.
2. **If a file is missing or unreadable, stop and tell the user.** Do not guess its contents.
3. **Locate the target path** for every file you will create or edit in `SRC_STRUCTURE.md`. If no suitable location exists, propose one and wait for confirmation instead of inventing a folder.
4. **Reuse before you write.** Search the repo for an existing service, type, util, or component that already does the job. In particular: **HTTP → `HttpService`**, **login/auth → `AuthService` + `authGuard`**, **theme → `ThemeService`** (see §1.7).
5. **State your plan in two or three lines** (files to touch, which rules apply) before the code.
### 1.4 Document precedence
| Question | Authoritative source |
|---|---|
| Where does this file go? What may import what? | `SRC_STRUCTURE.md` |
| Which library or version may I use? | `DEPENDENCIES.md` |
| How should the system behave (states, protocol, data shapes)? | `ARCHITECTURE.md` |
| How should the code be written? | **This file** |
| HTTP, login, or theme changes | **This file §1.7** (`HttpService`, `AuthService`, `ThemeService`) |
If two project documents disagree, `SRC_STRUCTURE.md` wins for paths and `DEPENDENCIES.md` wins for packages. **Report the discrepancy** to the user; do not silently pick one.
### 1.5 Known deltas (these are intentional; do not "fix" them back)
| Topic | Rule in this repo | Do NOT write |
|---|---|---|
| Zoneless provider (Angular 20.2+ incl. 22) | `provideZonelessChangeDetection()` | `provideExperimentalZonelessChangeDetection()` (it does **not exist** in Angular 22) |
| Zoneless provider (Angular 18/19 only) | `provideExperimentalZonelessChangeDetection()` | The stable name, which is not available there |
| Worklet files | `src/assets/worklets/pcm-capture-processor.js` and `pcm-playback-processor.js` | A single `src/assets/audio/pcm-processor.js` |
| Icons | **`@lucide/angular`**, accessed only through `shared/ui/icon` | `lucide-angular` (deprecated, peer-conflicts with Angular 22) |
| CSV parsing | `Papa.parse(file, { preview: N, … })` and chunked streaming | `worker: true` (commonly breaks under bundlers) |
| `standalone` flag | Everything is standalone; on Angular 19+ the flag is the default, so **omit it** | `standalone: false`, NgModules |
| Cleanup | `DestroyRef.onDestroy()` and `effect` `onCleanup` (and `ngOnDestroy` only when a class already implements it) | Treating `untracked()` as a cleanup hook (it is not one) |
**Check the installed Angular major in `package.json` first.** Apply the matching row above.
### 1.6 Scope & dependency discipline
- **Never add a package** that is not in `DEPENDENCIES.md`. If one is needed, explain why and ask first.
- **Never edit** `angular.json`, `package.json`, `tsconfig*.json`, or CI files unless the task requires it; when you do, explain the change.
- **Never refactor unrelated code** while implementing a feature. Mention opportunities instead.
- **Never delete files or tests** to make a build pass.
- Use the path aliases: `@core/*`, `@features/*`, `@shared/*`, `@env/*`.
### 1.7 Mandatory platform services (Http / Auth / Theme)
These three services are the **only** approved way to talk to the backend, authenticate, or change theme. Do not reinvent them, do not inject raw `HttpClient` for API calls, and do not write ad-hoc `localStorage` token or theme logic.
| Need | Use | Never |
|---|---|---|
| Any REST / SSE / file download to the API | `HttpService` (`get` / `post` / `put` / `patch` / `delete` / `getStream` / `downloadFile`) | Direct `HttpClient`, bare `fetch` for API routes, or a second HTTP wrapper |
| Login, session check, route protection | `AuthService.login()`, `AuthService.isAuthenticated()`, `authGuard` | Hand-rolled login POST, reading `access_token` outside these services, custom guards that ignore `AuthService` |
| Dark / light theme init and toggle | `ThemeService` (`initTheme` at app start, `toggleDarkMode()`, `isDarkMode` / `isDarkMode$`) | Direct `document.documentElement` theme writes, independent `localStorage['theme']` writes, duplicate dark-mode subjects |
#### HttpService (canonical HTTP layer)
- **Location:** project HTTP service (typically under a path such as `http-request/http.service` or as defined in `SRC_STRUCTURE.md`). Inject with `inject(HttpService)` in field initializers.
- **Response shape:** every JSON endpoint returns `ApiResult<T>` or `ApiResultArray<T>`:
```ts
export interface ApiResult<T> {
hasError: boolean;
messages: string[];
result: T;
}
```
- **Methods:** `get<T>`, `post<T>`, `put<T>`, `patch<T>`, `delete<T>` → `Observable<ApiResult<T>>`; `getStream<T>` for SSE (auth headers included); `downloadFile` → `Observable<Blob>`.
- **Options (`HttpOptions`):** `params`, `headers`, `skipToast`, `cooldownMs`, `skipHasErrorCheck`. Prefer these flags instead of swallowing toasts in callers.
- **Auth header:** token is read from `localStorage.getItem('access_token')` and attached as `Authorization: Bearer …`. Callers never set the Bearer token themselves unless adding extra headers via `options.headers`.
- **401 handling:** clears token, dismisses modals, toasts an expiry message, navigates to `/login`. Do not re-implement this.
- **Toasts / errors:** success and error messages from `messages[]` are shown via the service's toast layer (with cooldown). Feature code should not duplicate the same toasts for the same response.
- **Base URLs:** use the service's `baseUrl` / `backendUrl` / `apiUrl` / `imagesUrl`. Do not hard-code hostnames in feature code.
Example:
```ts
private readonly http = inject(HttpService);
loadFaq(): void {
this.http.get<FaqDoc[]>('faq/documents').subscribe({
next: (res) => { /* res.result is typed; hasError already handled unless skipHasErrorCheck */ },
error: () => { /* 401 and toast already handled by HttpService */ },
});
}
```
For long-lived streams use `getStream` and tear down with `takeUntilDestroyed` / `AbortController` (the Observable already aborts on unsubscribe).
#### AuthService + authGuard
- **Location:** auth service + `authGuard` (functional `CanActivateFn`).
- **Login:** always `AuthService.login({ username, password, rememberMe })`. On success it stores `access_token` and `username`, updates `currentUserSubject`, then loads permissions and license. Do not POST to `users/login` through `HttpService` from a component and then write tokens yourself.
- **Session check:** `AuthService.isAuthenticated()` (token present). Route protection: add `canActivate: [authGuard]` (or equivalent) — the guard redirects to `/login` when unauthenticated.
- **User stream:** `currentUserSubject` / subscription for username changes. Prefer converting to a signal at the UI edge (`toSignal`) if the component is signal-driven; do not replace the service's subject with a parallel signal store unless migrating the whole auth layer.
- **Logout / token clear:** go through the same paths the service uses (token removal is also done on 401 inside `HttpService`). Do not scatter `localStorage.removeItem('access_token')` in feature components.
#### ThemeService
- **Location:** theme service. Constructor already calls `initTheme()`.
- **Init:** `initTheme()` reads `localStorage.theme`, applies `data-bs-theme` on `document.documentElement`, then reconciles with backend `GET users/get-dark-mode`. Ensure the service is instantiated once at app bootstrap (e.g. inject it in `App` or a root provider) so init runs; do not call `initTheme` from random components.
- **Toggle:** only `ThemeService.toggleDarkMode()`. It flips local state, writes `localStorage`, applies the attribute, and syncs with `POST users/update-dark-mode`. Never toggle theme by only changing a CSS class or only writing localStorage.
- **Read:** `isDarkMode` (sync getter) or `isDarkMode$` (observable). In new signal-based UI, wrap with `toSignal(this.theme.isDarkMode$, { initialValue: this.theme.isDarkMode })` rather than inventing a second theme signal.
#### Agent rules (binding)
1. **HTTP request** → inject and call `HttpService` only.
2. **Login / is-logged-in / protect a route** → `AuthService` + `authGuard` only.
3. **Change or initialize theme** → `ThemeService` only (`initTheme` / `toggleDarkMode`).
4. Do **not** introduce a competing `ApiClient`, `AuthStore`, or `ThemeStore` that bypasses these services.
5. When wrapping these services for signals/OnPush UI, keep a **single writer**: the existing service remains the source of truth; UI adapts with `toSignal` / `computed`, it does not duplicate token or theme storage.
---
## 2. Angular & Zoneless Coding Standards
### 2.1 Signals first
Use the right primitive for the job:
| Need | Use | Not |
|---|---|---|
| UI / component state | `signal()` | `BehaviorSubject`, plain fields mutated in place |
| Derived read-only state | `computed()` | duplicated state kept in sync by hand, `effect()` that writes derived values |
| Derived **but locally overridable** state (e.g., selected row that resets when the list changes) | `linkedSignal()` | `effect()` that resets a signal |
| Async data read from HTTP | `resource()` / `httpResource()` **if the installed Angular version marks them stable or the project already uses them**; otherwise **`HttpService`** + `toSignal()` / subscribe with `takeUntilDestroyed` | Direct `HttpClient`, manual `subscribe()` that sets fields without teardown |
| Component API | `input()`, `input.required()`, `output()`, `model()`, `viewChild()`, `viewChildren()`, `contentChild()` | `@Input()`, `@Output()`, `@ViewChild()` decorators |
| Dependency injection | `inject()` in field initializers | constructor parameter injection |
| Event streams over time (WebSocket messages, SSE, debounced filters) | RxJS `Observable` at the **edge**, converted with `toSignal()` / `takeUntilDestroyed()` | RxJS for plain UI state |
| Side effects reacting to state (DOM, logging, calling the visualizer) | `effect()` / `afterRenderEffect()` | `effect()` to derive state |
> `resource()` and `httpResource()` were experimental in earlier Angular majors. Verify their API stability tag in the installed version before using them; do not assume.
**RxJS is allowed, but only for event streams.** A boolean such as `isDrawerOpen` is a `signal<boolean>`, never a `BehaviorSubject<boolean>`.
#### Single-writer rule
Every piece of state has **exactly one writer**. Expose a read-only view and keep the writable signal private.
```ts
@Injectable({ providedIn: 'root' })
export class VoiceStateStore {
private readonly _voiceState = signal<VoiceState>('idle');
readonly voiceState = this._voiceState.asReadonly();
readonly isMicOpen = computed(() =>
['listening', 'speaking', 'interrupted'].includes(this._voiceState()),
);
/** Only VoiceSessionService may call this. */
_setState(next: VoiceState): void {
this._voiceState.set(next);
}
}
```
- Update objects and arrays **immutably**: `signal.update(list => [...list, item])`. Never mutate the value inside a signal.
- Do not read signals inside `computed()` through `untracked()` to "silence" dependencies; fix the dependency graph instead.
- `effect()` is for side effects only. If you are about to call `.set()` inside an `effect()`, stop and check whether `computed()` or `linkedSignal()` is the right tool.
- Never put a signal write inside a `computed()`.
### 2.2 `ChangeDetectionStrategy.OnPush` is mandatory
**Every component** declares `changeDetection: ChangeDetectionStrategy.OnPush`, with no exceptions (including tiny presentational components, dialogs, and AG Grid cell renderers).
```ts
@Component({
selector: 'app-status-badge',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [AppIconComponent],
template: `
<span class="glass inline-flex items-center gap-2 rounded-full px-3 py-1" [class]="glowClass()">
<app-icon [name]="icon()" />
{{ label() }}
</span>
`,
})
export class StatusBadgeComponent {
readonly state = input.required<VoiceState>();
protected readonly label = computed(() => STATE_LABELS[this.state()]);
protected readonly icon = computed(() => STATE_ICONS[this.state()]);
protected readonly glowClass = computed(() => `glow-${this.state()}`);
}
```
The ESLint rule `@angular-eslint/prefer-on-push-component-change-detection` must stay enabled.
### 2.3 Zoneless safety (code must work with AND without Zone.js)
Assume **Zone.js may be absent**. Under zoneless change detection, a view is re-checked only when something Angular knows about changes: a **signal read in the template is written**, an input changes, an event bound in the template fires, `markForCheck()` is called, or the `async` pipe emits.
**Do:**
- Drive every template update through a **signal write**. A WebSocket callback, `setTimeout`, `requestAnimationFrame`, `Promise.then`, or `addEventListener` callback that changes plain fields will **not** update the screen.
- Use `afterNextRender()` / `afterRenderEffect()` for DOM measurement and canvas setup instead of `ngAfterViewInit` timing tricks.
- Use `DestroyRef`, `takeUntilDestroyed()`, and effect cleanups; they do not depend on Zone.js.
- Use the correct provider for the installed major (see §1.5):
```ts
// app.config.ts: Angular 20.2+ / 22 (this repo)
provideZonelessChangeDetection(),
// Angular 18/19 only: provideExperimentalZonelessChangeDetection(),
// Temporary zone phase only (needs "zone.js" in angular.json polyfills):
// provideZoneChangeDetection({ eventCoalescing: true }),
```
**Do not:**
- `import 'zone.js'` anywhere in application code.
- Depend on `NgZone.onStable`, `NgZone.onMicrotaskEmpty`, `NgZone.isStable`, or `ApplicationRef.isStable` for correctness.
- Call `ChangeDetectorRef.detectChanges()` in hot paths. Prefer a signal write; use `markForCheck()` only for a legacy API that cannot be signal-based.
- Rely on `NgZone.run()` to "make it update". It is a no-op for correctness in zoneless mode.
- Use `fakeAsync()` / `tick()` in new tests (they require Zone.js testing patches). Use Vitest fake timers (`vi.useFakeTimers()`) and `await fixture.whenStable()`.
- Write a signal at frame rate (60 Hz) from the audio or render loop. See §3.3.
### 2.4 Standalone components, directives, and pipes
- Everything is standalone. **No NgModules, ever.** Declare dependencies in `imports: []`.
- Never write `standalone: false`. On Angular 19+ do not add the redundant `standalone: true` either (it is the default); on Angular 18 it **must** be written explicitly.
- Lazy-load features and heavy dependencies (`loadChildren`, `loadComponent`, dynamic `import()`), as listed in `DEPENDENCIES.md` §6.5.
### 2.5 Templates, naming, and style
- Control flow: `@if`, `@for (item of items(); track item.id)`, `@switch`. **No** `*ngIf`, `*ngFor`, `*ngSwitch`.
- Every `@for` has a stable `track` expression (an id, never the index unless the list is static).
- Templates call **signals and `computed()` values only**. No method calls that compute things, no `Date.now()`, no object/array literals in bindings.
- Prefer `class` and `style` bindings over `ngClass` / `ngStyle`. Use `host: { … }` metadata instead of `@HostBinding` / `@HostListener`.
- File naming (matches `angular.json` schematics): `*.component.ts`, `*.directive.ts`, `*.pipe.ts`, `*.service.ts`; route containers are `*.page.ts`; stores are `*.store.ts`. Selector prefix is `app-` (directives: `app`).
- Class members: `protected readonly` for template-only values, `readonly` for public API, `private` for internals.
- `strict` TypeScript and `strictTemplates` are on. No `any` (use `unknown` and narrow). No non-null assertions (`!`) without a comment explaining why it is safe.
- Prefer **discriminated unions** for events and messages (`VoiceEvent`, `ClientMessage`, `ServerMessage`) and handle them with an exhaustive `switch` ending in `assertNever`.
- Style with **Tailwind utilities** and the design tokens in `src/styles/theme.css`. Use the `glass`, `glass-strong`, and `glow-*` utilities. No component CSS files unless unavoidable, and no hard-coded hex colors; use tokens.
- Use **logical** properties (`ms-*`, `me-*`, `ps-*`, `pe-*`, `start-*`, `end-*`) so RTL layouts work. Never `ml-*`, `pr-*`, `left-*`, `right-*` for layout direction.
### 2.6 Icons
Icons come **only** from `shared/ui/icon` (`<app-icon name="mic" />`) backed by the registry `icons.ts` (package `@lucide/angular`). Never import Lucide directly in a feature component. To add an icon, add it to the registry.
### 2.7 Accessibility baseline
- Interactive elements are real `<button>` / `<a>` elements with accessible names.
- Voice state changes are announced via CDK `LiveAnnouncer` or an `aria-live="polite"` region.
- Drawers and dialogs use CDK `Overlay` / `Dialog` with focus trap, `Esc` to close, and focus restoration.
- Never convey state by color alone: pair it with icon + text.
- Honor `prefers-reduced-motion` in animations and in the visualizer presets.
---
## 3. Web Audio & Canvas Performance Rules
### 3.1 Thread and zone separation
| Code | Runs on | Hard rules |
|---|---|---|
| `src/assets/worklets/*.js` | Audio render thread | No allocation in `process()`, no `console.*`, no DOM, no `await`, communicate only via `port.postMessage` |
| `core/audio/*`, `core/websocket/*` | Main thread, **outside** Angular zone | No per-frame signal writes; re-enter Angular only by writing a signal on a meaningful, low-frequency change |
| `core/audio/visualizer/*` | Main thread, **outside** Angular zone, `requestAnimationFrame` | **Never** writes signals, never triggers change detection |
| Stores, `VoiceSessionService`, components | Angular domain | Signals, ~1–5 Hz updates |
**Never process audio samples on the main thread.** Capture, framing, quantization, jitter buffering, and sample-rate conversion happen in the worklets.
### 3.2 AudioWorklet rules
- The processors live at `src/assets/worklets/pcm-capture-processor.js` and `src/assets/worklets/pcm-playback-processor.js` (see §1.5). Each starts with `// @ts-check` and uses types from `@types/audioworklet`.
- In `process()`: **preallocate** all buffers in the constructor; reuse them; never create arrays, objects, closures, or strings per call.
- Capture emits fixed **20 ms Int16 PCM frames** and sends them with a **transfer list**: `this.port.postMessage(buffer, [buffer])`. Never copy large buffers.
- Playback owns a ring/jitter buffer, outputs **silence on underrun**, supports an O(1) `flush`, and reports `started`, `drained`, `underrun`.
- Load modules with a **cache-busting version** and a base-href-aware URL:
```ts
const v = inject(APP_CONFIG).workletVersion;
await ctx.audioWorklet.addModule(
new URL(`assets/worklets/pcm-capture-processor.js?v=${v}`, document.baseURI).href,
);
```
- Create the `AudioContext` **only after a user gesture** (the orb click), via the holder in `core/audio/audio-context.provider.ts`. Never at app startup. Resume it if `state === 'suspended'`.
- Request the microphone with `echoCancellation`, `noiseSuppression`, `autoGainControl`, and `channelCount: 1`. Echo cancellation is mandatory because barge-in depends on it.
- Never assume the requested sample rate: read `ctx.sampleRate` and resample in the worklet if it differs from the wire format.
### 3.3 Audio levels: the `AudioLevelBus` exception
Per-frame levels and frequency bands are written into the mutable **`AudioLevelBus`** (`core/audio/audio-level-bus.ts`) and read directly by the visualizer loop.
- **Never** create a `signal` that is updated every animation frame or every audio frame. In zoneless mode that schedules change detection at 60 Hz.
- If a UI element needs a level (e.g., a mic meter), expose a **throttled** (~10 Hz) signal for that element only. Never bind it to the canvas.
- Use `getByteFrequencyData(preallocatedUint8Array)`; never allocate arrays in the loop.
### 3.4 Bypassing Angular change detection for 60 FPS loops
**Any** `requestAnimationFrame` loop, Three.js render loop, canvas drawing loop, high-frequency timer, or `ResizeObserver`/`IntersectionObserver` callback MUST be created inside `NgZone.runOutsideAngular()`.
```ts
@Injectable()
export class VisualizerEngine {
private readonly zone = inject(NgZone);
private readonly destroyRef = inject(DestroyRef);
private readonly bus = inject(AudioLevelBus);
private rafId = 0;
private visualizer?: Visualizer;
private target = STATE_PRESETS.idle;
start(canvas: HTMLCanvasElement): void {
this.zone.runOutsideAngular(() => {
void this.boot(canvas); // renderer creation + loop start
});
this.destroyRef.onDestroy(() => this.dispose());
}
/** Called from an effect() on voiceState changes (~1–5 Hz). Cheap: swaps a preset object. */
applyState(state: VoiceState): void {
this.target = STATE_PRESETS[state];
}
private readonly loop = (t: number): void => {
this.rafId = requestAnimationFrame(this.loop); // already outside the zone
this.visualizer?.render(t, this.bus, this.target); // reads the bus; no signal reads or writes
};
private async boot(canvas: HTMLCanvasElement): Promise<void> {
const { ThreeOrbVisualizer } = await import('./three-orb.visualizer');
this.visualizer = await ThreeOrbVisualizer.create(canvas);
this.rafId = requestAnimationFrame(this.loop);
}
private dispose(): void {
cancelAnimationFrame(this.rafId);
this.visualizer?.dispose();
}
}
```
Rules for the loop:
1. Start it **outside** the zone (a harmless no-op under zoneless, which keeps the code portable).
2. **No** `new` objects, arrays, closures, or strings inside the per-frame function.
3. State reaches the loop through an `effect()` that runs on state **changes** and updates a plain target object; the loop eases toward it. The loop itself never reads signals.
4. Cap `devicePixelRatio` at 2; resize through a `ResizeObserver` created outside the zone.
5. **Pause** when the tab is hidden (`visibilitychange`) or the canvas is off-screen (`IntersectionObserver`).
6. Honor `prefers-reduced-motion` by choosing a calmer preset.
7. Provide a **Canvas 2D fallback** that implements the same `Visualizer` interface (WebGL missing or `webglcontextlost`).
8. Import Three.js lazily (`await import('three')`) and with **named imports** only.
WebSocket `onmessage`, worklet `port.onmessage`, SSE callbacks, and `AnalyserNode` polling timers also run outside the zone. Re-enter Angular only by writing a signal when something human-visible changes (state transition, transcript partial, status).
### 3.5 Cleanup & destruction lifecycle (mandatory)
Every resource that is created must have a release path registered **at the moment of creation**.
| Resource | Release |
|---|---|
| `requestAnimationFrame` handle | `cancelAnimationFrame(id)` |
| Three.js scene | `geometry.dispose()`, `material.dispose()`, every `texture.dispose()`, `renderer.dispose()`, `renderer.forceContextLoss()`, remove event listeners, null references |
| `AudioContext` | Disconnect nodes, `await ctx.close()` |
| `AudioWorkletNode` | `node.port.onmessage = null`, `node.port.close()`, `node.disconnect()` |
| `MediaStream` (microphone) | `stream.getTracks().forEach(t => t.stop())` (this turns off the browser's mic indicator) |
| `AnalyserNode`, `MediaStreamAudioSourceNode` | `disconnect()` |
| `WebSocket` | Remove handlers, `close(1000)`, clear heartbeat and reconnect timers |
| `ResizeObserver`, `IntersectionObserver`, `MutationObserver` | `disconnect()` |
| DOM listeners (`visibilitychange`, `storage`, `devicechange`) | `removeEventListener` (or register through `fromEvent` + `takeUntilDestroyed`) |
| RxJS subscriptions | `takeUntilDestroyed(this.destroyRef)` (never a bare `subscribe()` without teardown) |
| HTTP uploads / SSE | `AbortController` or unsubscribe on destroy; cancel in-flight uploads when their owner is destroyed |
| Timers (`setTimeout`, `setInterval`) | `clearTimeout` / `clearInterval` |
| CDK `OverlayRef` / `DialogRef` | `dispose()` / `close()` |
**Which hook to use**
- **Preferred:** `inject(DestroyRef).onDestroy(() => …)` right next to the creation code.
- Inside an `effect()` that creates something per run: `effect((onCleanup) => { …; onCleanup(() => release()); })`.
- `ngOnDestroy` is acceptable when a class already implements `OnDestroy`; do not add it just to call one release.
- **`untracked()` is not a cleanup mechanism.** It only prevents signal reads from becoming dependencies. Never present it as lifecycle handling.
- Cleanup must be **idempotent** (safe to call twice) and must not throw.
### 3.6 State machine and barge-in rules
- `voiceState` is written **only** by `VoiceSessionService` (`features/voice-agent/services/`), driven by the data table in `voice-transitions.ts`. Never call the store's mutators from components.
- Unlisted events in the current state are **ignored and logged**, never thrown.
- On `BARGE_IN`: **flush local playback first**, then notify the server (`interrupt` with `playedMs`). Never wait for the network.
- Agent audio frames carry a `turnId`; frames from a stale turn are dropped by `audio-stream.handler.ts`.
- `interrupted` is transient and resolves to `listening` after `FLUSH_DONE`.
- Do not introduce new states or transitions without updating `ARCHITECTURE.md` §2 in the same change.
### 3.7 Protocol and transport rules
- Use the `RealtimeTransport` abstraction (`core/websocket/realtime-transport.ts`). Feature code never touches `WebSocket` directly.
- Audio travels in **binary frames** with the documented header (`ARCHITECTURE.md` §5.2); control messages are JSON, typed by `ClientMessage` / `ServerMessage`. Set `binaryType = 'arraybuffer'`.
- Authentication ticket goes in the first JSON message, **never in the URL**.
- Malformed frames are counted and dropped, never thrown.
---
## 4. FAQ Knowledge Base & File Handling Guidelines
### 4.1 Layer separation (strict)
```text
UI components (features/faq-manager/components/*)
│ inputs/outputs only
▼
FaqStore (signals) ◄──── FaqIngestionService (orchestration)
│
┌─────────────┼───────────────────────┐
▼ ▼ ▼
FileValidatorService CsvParserService FaqApiService / IngestionEventsService
(UX validation) (preview only) (HTTP + status events to the backend)
│
▼
Backend: parsing, chunking, embedding, vector index (RAG)
```
- **UI components never call HTTP, never know about chunks, embeddings, or vector indexes.** They read `FaqStore` signals and emit events.
- **The client never performs embedding, chunking, or retrieval.** It uploads files and edits Q&A pairs; the backend owns indexing and RAG synchronization.
- All FAQ HTTP traffic goes through **`HttpService`** (via `FaqApiService` / `FaqIngestionService`). No feature injects `HttpClient` directly.
- `FaqIngestionService` is the only orchestrator of `validate → preview → upload → track status`.
- Status flows from the server through `IngestionEventsService` (SSE via `HttpService.getStream` or control messages) into `FaqStore` signals: `uploading → indexing → active | error`. Status is **never** inferred on the client.
- `features/faq-manager` must not import from `features/voice-agent` (and vice versa). Shared concerns go in `core/` or `shared/`.
- The voice session learns which documents to use only through `activeDocumentIds` in the session configuration (from `FaqStore.activeDocuments`), not by reaching into FAQ components.
### 4.2 PapaParse pre-parsing (CSV)
- **Lazy-load:** `const Papa = (await import('papaparse')).default;` inside `CsvParserService`. Never import it at the top of a component.
- **Preview** with `Papa.parse(file, { header: true, preview: N, skipEmptyLines: 'greedy', dynamicTyping: false })`, with `N` defaulting to 50.
- **Count and validate large files** with chunked streaming (`chunk` or `step`) so memory stays bounded. **Do not use `worker: true`** (see §1.5).
- Treat every cell as a **string**; never trust types, never `eval`. Strip a UTF-8 BOM, tolerate `\r\n`, and let PapaParse auto-detect the delimiter.
- Auto-detect question and answer columns with `csv-column-detect.ts`, and let the user remap them in `upload-preview-table`.
- Report row problems with `CsvRowError` (`MISSING_QUESTION`, `MISSING_ANSWER`, `TOO_LONG`, `MALFORMED`). A row error is a **warning in the preview**, not a crash.
- **The parsed rows are for preview only.** Upload the **original file** (`FormData`); the server re-parses and is the source of truth. Do not send client-parsed JSON as the dataset.
- Never log file contents or cell values (they may contain personal data).
### 4.3 Validation of all file types (client side = UX only)
- Check extension, MIME type, size limit, and **magic bytes** via `file-validator.service.ts` and `file-signatures.ts` (PDF `%PDF`; DOCX is a ZIP, `PK\x03\x04`; JSON/CSV are text).
- PDF and DOCX are **not parsed in the browser by default**. Optional previews (`pdfjs-dist`, `mammoth`) require explicit approval and a dynamic import (`DEPENDENCIES.md` §3.5).
- **Never treat client validation as a trust boundary.** The server must revalidate; write UI copy accordingly.
- Rejected files produce a typed `FaqDocumentError` with a user-readable message and a `retryable` flag.
### 4.4 Upload, status, and Q&A editing
- Upload through **`HttpService`** (or `FaqApiService` built on it). If upload progress is required, extend `HttpService` with a progress-capable method rather than injecting raw `HttpClient` in a feature. Write `progress` into the document's signal state. Cancel with unsubscribe/`AbortController` when the owner is destroyed.
- The document row has one writer (`FaqStore`). Use immutable `update()` calls keyed by `id`.
- Q&A edits are **optimistic with rollback**: apply to `FaqStore`, send the request, roll back and toast on failure. A manual edit sets `overridden: true` so re-ingestion does not overwrite it.
- **AG Grid** (`ag-grid-angular`, `ag-grid-community` on identical versions):
- Register modules once in `grid/register-grid-modules.ts`; apply the theme through the JS theme API (`grid/qa-grid.theme.ts`), not CSS imports.
- The grid is wrapped by `QaGridComponent` (signal inputs, outputs only). Feature code never touches the grid API outside that component.
- Cell renderers are OnPush standalone components in `grid/cell-renderers/`.
- Never trigger row-model refreshes at frame rate; batch updates with `applyTransaction`.
- The grid and PapaParse chunk must stay **out of the initial bundle** (lazy routes + dynamic imports).
---
## 5. Navigation Guide: where things go
| You are adding… | Put it in… |
|---|---|
| A new voice UI element (button, overlay, badge) | `features/voice-agent/components/<name>/` |
| Voice transition, guard, or side effect | `features/voice-agent/services/voice-transitions.ts` / `voice-effects.ts` |
| Anything that touches `AudioContext`, mic, or worklet nodes | `core/audio/` |
| The orb, shaders, canvas fallback | `core/audio/visualizer/` |
| WebSocket, framing, reconnect, heartbeat | `core/websocket/` |
| Global signals store, storage, telemetry, notifications | `core/services/` |
| Shared types used by core and features | `core/models/` |
| FAQ UI | `features/faq-manager/components/<name>/` |
| FAQ state, upload logic, parsing, API | `features/faq-manager/services/` |
| Reusable button/badge/dialog/spinner/pipe/directive | `shared/ui`, `shared/pipes`, `shared/directives` |
| AudioWorklet script | `src/assets/worklets/` |
| Design tokens / Tailwind utilities | `src/styles/theme.css` / `src/styles/utilities.css` |
| HTTP calls to the API | **Use existing `HttpService` only** — do not add a parallel client |
| Login, auth check, route guard | **Use existing `AuthService` + `authGuard` only** |
| Theme init / dark-mode toggle | **Use existing `ThemeService` only** (`initTheme`, `toggleDarkMode`) |
**Import boundaries** (enforced by ESLint `no-restricted-imports`):
```text
shared <- core <- features
```
- `shared` imports nothing from `core` or `features`.
- `core` imports from `shared` only, never from `features`.
- A feature never imports another feature.
- `core/audio` and `core/websocket` import no UI code (no components, no CDK), so they remain testable without a DOM.
- Use `@core/…`, `@features/…`, `@shared/…` aliases; never deep relative paths that cross layer boundaries (`../../../core/…`).
---
## 6. Security, Privacy, and Reliability
- Use `wss://` and `https://` outside local development. Authentication tickets go in message bodies or headers, **never in URLs**.
- **Never log or persist** raw audio, transcripts, uploaded file contents, or tokens. Telemetry carries counts, durations, and error codes only.
- Auth tokens (`access_token`) and username are managed **only** by `AuthService` / `HttpService` (including 401 cleanup). Theme preference may live in `localStorage` **only** via `ThemeService`. Other preferences go through `StorageService` if present. Never tokens, transcripts, or file data in ad-hoc storage.
- Never use `innerHTML`, `bypassSecurityTrust*`, or `eval`/`new Function` with user, server, or model-generated text. Transcripts and Q&A are rendered as text.
- Every error path is handled: microphone denied, `AudioContext` suspended, worklet load failure, socket drop mid-turn, token expiry, WebGL context loss, upload failure. Map to `VoiceError` / `FaqDocumentError` and tell the user what to do next.
- API user-visible messages and 401 handling are owned by `HttpService` (toasts + redirect). For non-HTTP app errors, use the project notification layer; do not swallow errors or only `console.log` them.
- Protect authenticated routes with `authGuard`. Do not implement a second guard that bypasses `AuthService.isAuthenticated()`.
---
## 7. Testing Rules
- **Colocate** `*.spec.ts` next to the file. The test runner is Vitest through the Angular builder.
- Pure logic gets pure tests: `voice-transitions.ts` (table-driven, including ignored events), `frame-codec.ts` (golden byte arrays), `pcm-utils.ts`, `connection.machine.ts`, `reconnect-policy.ts`, `csv-column-detect.ts`, `file-signatures.ts`.
- `VoiceSessionService` is tested with fake `AudioEngine` and fake `RealtimeTransport`, including barge-in races and stale `turnId` frames.
- Configure tests for zoneless (`provideZonelessChangeDetection()`); await `fixture.whenStable()`; do not use `fakeAsync`.
- Components are tested through their **signal inputs and rendered output**, not private members.
- A change to the audio path or visualizer must keep the performance assertion: **zero change-detection ticks per second** while the orb animates (see `ARCHITECTURE.md` §3.7).
- Never weaken, skip (`xit`, `.skip`), or delete a test to get green. Fix the code or ask.
---
## 8. Anti-Pattern Table (never write these)
| Forbidden | Use instead |
|---|---|
| `BehaviorSubject<boolean>` for UI state | `signal<boolean>()` |
| `@Input()` / `@Output()` / `@ViewChild()` decorators | `input()` / `output()` / `viewChild()` |
| Component without `OnPush` | `changeDetection: ChangeDetectionStrategy.OnPush` |
| `*ngIf` / `*ngFor` | `@if` / `@for … track` |
| NgModule, `standalone: false` | Standalone component with `imports: []` |
| `setInterval`/`requestAnimationFrame` started inside the zone for a render loop | `NgZone.runOutsideAngular(...)` |
| Signal updated every frame | `AudioLevelBus` (machine reads) + throttled signal (UI reads) |
| Audio sample processing or resampling on the main thread | `AudioWorklet` |
| `new AudioContext()` at startup | Lazy creation on the first user gesture |
| Subscribing without teardown | `takeUntilDestroyed()` / `DestroyRef` |
| `untracked()` described as cleanup | `DestroyRef.onDestroy()` / `effect` `onCleanup` |
| `effect()` that derives state | `computed()` / `linkedSignal()` |
| Mutating an array or object held in a signal | `signal.update()` with a new value |
| `provideExperimentalZonelessChangeDetection()` on Angular 22 | `provideZonelessChangeDetection()` |
| Importing `lucide-angular` or any Lucide package directly in a feature | `<app-icon>` via `shared/ui/icon` |
| `Papa.parse(file, { worker: true })` | `preview` + chunked streaming |
| Uploading client-parsed rows as the dataset | Upload the original file; parse client-side for preview only |
| UI component calling backend RAG/vector endpoints | Go through `FaqIngestionService` / `FaqApiService` |
| Feature importing another feature | Move shared code to `core/` or `shared/` |
| Adding a library not in `DEPENDENCIES.md` | Ask first, justify, update the doc |
| `ml-*` / `pr-*` / `left-*` / `right-*` for direction | `ms-*` / `pe-*` / `start-*` / `end-*` |
| `any`, unchecked `!`, swallowed errors, `console.log` for errors | Narrow types; `NotificationService` + `LoggerService` |
| Direct `HttpClient` / bare `fetch` for API routes | `HttpService.get/post/put/patch/delete/getStream/downloadFile` |
| Hand-rolled login POST + writing `access_token` yourself | `AuthService.login()`; protect routes with `authGuard` |
| Reading/writing theme or `data-bs-theme` outside ThemeService | `ThemeService.initTheme()` / `toggleDarkMode()` / `isDarkMode` |
| Second HTTP client, auth store, or theme store that bypasses the above | Extend or wrap the existing services; single writer |
---
## 9. Mandatory Code-Generation Checklist
**Before returning code, verify every applicable item. If an item fails, fix the code. If you cannot fix it, say so explicitly in your reply. Never claim a check passed that you did not actually perform.**
### 9.1 Core checklist (always)
- [ ] **OnPush:** Is `changeDetection: ChangeDetectionStrategy.OnPush` present on every component I created or touched?
- [ ] **Signals:** Is UI state in `signal()` / `computed()` / `linkedSignal()` (not `BehaviorSubject`, not mutable fields), and do all template updates come from signal writes, so the code works **without Zone.js**?
- [ ] **60 FPS loops:** Is every `requestAnimationFrame` / Three.js / canvas loop (and every high-frequency observer) created inside `NgZone.runOutsideAngular()`, with **no signal read or written per frame**?
- [ ] **Cleanup:** Is every subscription, `AudioContext`, `AudioWorkletNode`, `MediaStream` track, `WebSocket`, observer, timer, overlay, and Three.js object (geometry, material, texture, renderer) released through `DestroyRef` / effect cleanup / `ngOnDestroy`?
- [ ] **Paths:** Does every file path match `./docs/SRC_STRUCTURE.md`, and do the imports respect `shared <- core <- features`?
### 9.2 Angular conventions
- [ ] Standalone only (no NgModule, no `standalone: false`; flag omitted on Angular 19+, present on 18).
- [ ] `input()` / `output()` / `model()` / `viewChild()` / `inject()` used instead of decorators and constructor injection.
- [ ] `@if` / `@for` (with `track`) / `@switch`; templates call only signals/computeds.
- [ ] Zoneless provider matches the installed Angular major (§1.5); no reliance on `NgZone.onStable` or `detectChanges()` in hot paths.
- [ ] One writer per state; public API exposes `asReadonly()`.
- [ ] No `effect()` used to derive state; no signal writes inside `computed()`.
- [ ] Exhaustive `switch` on discriminated unions (`assertNever`).
- [ ] Strict typing: no `any`, no unexplained `!`.
### 9.3 Audio, canvas, and transport
- [ ] No audio-sample processing on the main thread; worklet code allocates nothing in `process()` and uses transferables.
- [ ] Worklet files are in `src/assets/worklets/` and loaded with a version query.
- [ ] `AudioContext` is created after a user gesture and resumed when suspended.
- [ ] Per-frame levels go through `AudioLevelBus`; UI meters use a throttled signal.
- [ ] Barge-in flushes playback locally first; stale `turnId` frames are dropped.
- [ ] Visualizer pauses when hidden, caps DPR at 2, honors `prefers-reduced-motion`, and has a fallback.
- [ ] `three` is lazily imported with named imports; shaders are imported as text from `core/audio/visualizer/shaders/`.
### 9.4 FAQ and file handling
- [ ] PapaParse is lazily imported, used with `preview`/chunking (never `worker: true`), and parsed rows are used for preview only.
- [ ] The **original file** is what gets uploaded; the client does no embedding, chunking, or retrieval.
- [ ] UI components do not call HTTP or backend RAG/vector APIs; they go through the store and `FaqIngestionService`.
- [ ] File validation includes size, extension/MIME, and magic bytes; no file contents are logged.
- [ ] Grid modules are registered once; AG Grid is accessed only through `QaGridComponent`.
### 9.5 Project hygiene
- [ ] Only approved libraries from `DEPENDENCIES.md`; icons through `shared/ui/icon`.
- [ ] Tailwind tokens and logical properties used; no hard-coded colors; no `ml-*`/`pr-*`.
- [ ] Accessible names, keyboard support, and `aria-live` for state changes.
- [ ] Error paths handled and surfaced; no secrets, tokens, audio, or transcripts logged or persisted.
- [ ] Tests added or updated (pure logic first); none skipped or deleted.
- [ ] Any change to states, protocol, folders, or dependencies is reflected in the matching `./docs/*.md` file in the same change.
- [ ] **Http / Auth / Theme:** all API calls go through `HttpService`; login and session via `AuthService` + `authGuard`; theme init/toggle via `ThemeService` only (no parallel clients or direct token/theme storage).
---
## 10. Response Protocol for Agents
1. **Before code:** list the files you will create/edit (with paths from `SRC_STRUCTURE.md`) and the rules that apply, in two to five lines.
2. **Code:** complete files or clear diffs. No `// ...rest of code`, no pseudo-code, no TODO placeholders for core logic.
3. **After code:** a short **Checklist result** (§9). List only items that were *not* satisfied, plus any assumption you made. If all passed, say so in one line.
4. **Ask instead of guessing** when: a doc is missing, docs conflict, a new dependency is needed, a state or protocol change is implied, the backend contract is unknown, or the Angular version is unclear.
5. **Keep changes minimal and focused.** Mention (do not perform) unrelated cleanups.
6. **Never** weaken a rule in this file to make a request easier. Explain the conflict and offer a compliant option.
---
## 11. Reference Templates
### 11.1 New component
```ts
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
@Component({
selector: 'app-example',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
template: `
@if (items().length) {
<ul class="space-y-2">
@for (item of items(); track item.id) {
<li class="glass rounded-xl px-3 py-2">
<button type="button" (click)="selected.emit(item.id)">{{ item.label }}</button>
</li>
}
</ul>
} @else {
<p class="text-slate-400">{{ emptyText() }}</p>
}
`,
})
export class ExampleComponent {
readonly items = input.required<readonly { id: string; label: string }[]>();
readonly selected = output<string>();
protected readonly emptyText = computed(() => 'Nothing here yet.');
}
```
### 11.2 Resource with guaranteed cleanup
```ts
@Injectable({ providedIn: 'root' })
export class ExampleResourceService {
private readonly destroyRef = inject(DestroyRef);
private socket?: WebSocket;
open(url: string): void {
this.close();
this.socket = new WebSocket(url); // created outside the zone by the caller
this.socket.binaryType = 'arraybuffer';
this.destroyRef.onDestroy(() => this.close()); // release registered at creation time
}
close(): void { // idempotent, never throws
if (!this.socket) return;
this.socket.onmessage = null;
this.socket.onclose = null;
try { this.socket.close(1000); } catch { /* already closed */ }
this.socket = undefined;
}
}
```
### 11.3 `effect()` that owns a resource
```ts
constructor() {
effect((onCleanup) => {
const state = this.voiceState(); // dependency
const handle = this.thing.subscribeTo(state); // per-run resource
onCleanup(() => handle.release()); // released on re-run and on destroy
});
}
```
---
## 12. Maintaining This File
- Treat this file like code: change it through a pull request, in the same PR as any architecture change.
- When `ARCHITECTURE.md`, `SRC_STRUCTURE.md`, or `DEPENDENCIES.md` change, update §1.5 (known deltas), §5 (navigation), and §8 (anti-patterns) accordingly.
- When Angular is upgraded, re-verify §1.5 (zoneless provider name, `standalone` default, `resource()` stability) and §2.3.
- Keep the checklist in §9 short enough to be followed every time. Add an item only when a real defect has slipped through twice.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Brandon Roberts
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+304
View File
@@ -0,0 +1,304 @@
---
name: angular-component
description: >-
Create modern Angular standalone components following v20+ best practices. Use
for building UI components with signal-based inputs/outputs, OnPush change
detection, host bindings, content projection, and lifecycle hooks. Triggers on
component creation, refactoring class-based inputs to signals, adding host
bindings, or implementing accessible interactive components.
metadata:
category: development
suggest_for:
filename:
- '*.component.ts'
- '*.component.html'
source:
repository: 'https://github.com/analogjs/angular-skills'
path: skills/angular-component
license_path: LICENSE
commit: 610c90eb9490194bcff703f343f97fa0e00bdb2f
---
# Angular Component
Create standalone components for Angular v20+. Components are standalone by default—do NOT set `standalone: true`.
## Component Structure
```typescript
import { Component, ChangeDetectionStrategy, input, output, computed } from '@angular/core';
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'class': 'user-card',
'[class.active]': 'isActive()',
'(click)': 'handleClick()',
},
template: `
<img [src]="avatarUrl()" [alt]="name() + ' avatar'" />
<h2>{{ name() }}</h2>
@if (showEmail()) {
<p>{{ email() }}</p>
}
`,
styles: `
:host { display: block; }
:host.active { border: 2px solid blue; }
`,
})
export class UserCard {
// Required input
name = input.required<string>();
// Optional input with default
email = input<string>('');
showEmail = input(false);
// Input with transform
isActive = input(false, { transform: booleanAttribute });
// Computed from inputs
avatarUrl = computed(() => `https://api.example.com/avatar/${this.name()}`);
// Output
selected = output<string>();
handleClick() {
this.selected.emit(this.name());
}
}
```
## Signal Inputs
```typescript
// Required - must be provided by parent
name = input.required<string>();
// Optional with default value
count = input(0);
// Optional without default (undefined allowed)
label = input<string>();
// With alias for template binding
size = input('medium', { alias: 'buttonSize' });
// With transform function
disabled = input(false, { transform: booleanAttribute });
value = input(0, { transform: numberAttribute });
```
## Signal Outputs
```typescript
import { output, outputFromObservable } from '@angular/core';
// Basic output
clicked = output<void>();
selected = output<Item>();
// With alias
valueChange = output<number>({ alias: 'change' });
// From Observable (for RxJS interop)
scroll$ = new Subject<number>();
scrolled = outputFromObservable(this.scroll$);
// Emit values
this.clicked.emit();
this.selected.emit(item);
```
## Host Bindings
Use the `host` object in `@Component`—do NOT use `@HostBinding` or `@HostListener` decorators.
```typescript
@Component({
selector: 'app-button',
host: {
// Static attributes
'role': 'button',
// Dynamic class bindings
'[class.primary]': 'variant() === "primary"',
'[class.disabled]': 'disabled()',
// Dynamic style bindings
'[style.--btn-color]': 'color()',
// Attribute bindings
'[attr.aria-disabled]': 'disabled()',
'[attr.tabindex]': 'disabled() ? -1 : 0',
// Event listeners
'(click)': 'onClick($event)',
'(keydown.enter)': 'onClick($event)',
'(keydown.space)': 'onClick($event)',
},
template: `<ng-content />`,
})
export class Button {
variant = input<'primary' | 'secondary'>('primary');
disabled = input(false, { transform: booleanAttribute });
color = input('#007bff');
clicked = output<void>();
onClick(event: Event) {
if (!this.disabled()) {
this.clicked.emit();
}
}
}
```
## Content Projection
```typescript
@Component({
selector: 'app-card',
template: `
<header>
<ng-content select="[card-header]" />
</header>
<main>
<ng-content />
</main>
<footer>
<ng-content select="[card-footer]" />
</footer>
`,
})
export class Card {}
// Usage:
// <app-card>
// <h2 card-header>Title</h2>
// <p>Main content</p>
// <button card-footer>Action</button>
// </app-card>
```
## Lifecycle Hooks
```typescript
import { OnDestroy, OnInit, afterNextRender, afterRender } from '@angular/core';
export class My implements OnInit, OnDestroy {
constructor() {
// For DOM manipulation after render (SSR-safe)
afterNextRender(() => {
// Runs once after first render
});
afterRender(() => {
// Runs after every render
});
}
ngOnInit() { /* Component initialized */ }
ngOnDestroy() { /* Cleanup */ }
}
```
## Accessibility Requirements
Components MUST:
- Pass AXE accessibility checks
- Meet WCAG AA standards
- Include proper ARIA attributes for interactive elements
- Support keyboard navigation
- Maintain visible focus indicators
```typescript
@Component({
selector: 'app-toggle',
host: {
'role': 'switch',
'[attr.aria-checked]': 'checked()',
'[attr.aria-label]': 'label()',
'tabindex': '0',
'(click)': 'toggle()',
'(keydown.enter)': 'toggle()',
'(keydown.space)': 'toggle(); $event.preventDefault()',
},
template: `<span class="toggle-track"><span class="toggle-thumb"></span></span>`,
})
export class Toggle {
label = input.required<string>();
checked = input(false, { transform: booleanAttribute });
checkedChange = output<boolean>();
toggle() {
this.checkedChange.emit(!this.checked());
}
}
```
## Template Syntax
Use native control flow—do NOT use `*ngIf`, `*ngFor`, `*ngSwitch`.
```html
<!-- Conditionals -->
@if (isLoading()) {
<app-spinner />
} @else if (error()) {
<app-error [message]="error()" />
} @else {
<app-content [data]="data()" />
}
<!-- Loops -->
@for (item of items(); track item.id) {
<app-item [item]="item" />
} @empty {
<p>No items found</p>
}
<!-- Switch -->
@switch (status()) {
@case ('pending') { <span>Pending</span> }
@case ('active') { <span>Active</span> }
@default { <span>Unknown</span> }
}
```
## Class and Style Bindings
Do NOT use `ngClass` or `ngStyle`. Use direct bindings:
```html
<!-- Class bindings -->
<div [class.active]="isActive()">Single class</div>
<div [class]="classString()">Class string</div>
<!-- Style bindings -->
<div [style.color]="textColor()">Styled text</div>
<div [style.width.px]="width()">With unit</div>
```
## Images
Use `NgOptimizedImage` for static images:
```typescript
import { NgOptimizedImage } from '@angular/common';
@Component({
imports: [NgOptimizedImage],
template: `
<img ngSrc="/assets/hero.jpg" width="800" height="600" priority />
<img [ngSrc]="imageUrl()" width="200" height="200" />
`,
})
export class Hero {
imageUrl = input.required<string>();
}
```
For detailed patterns, see [references/component-patterns.md](references/component-patterns.md).
@@ -0,0 +1,358 @@
# Angular Component Patterns
## Table of Contents
- [Model Inputs (Two-Way Binding)](#model-inputs-two-way-binding)
- [View Queries](#view-queries)
- [Content Queries](#content-queries)
- [Dependency Injection in Components](#dependency-injection-in-components)
- [Component Communication Patterns](#component-communication-patterns)
- [Dynamic Components](#dynamic-components)
## Model Inputs (Two-Way Binding)
For two-way binding with `[(value)]` syntax:
```typescript
import { Component, model } from '@angular/core';
@Component({
selector: 'app-slider',
host: {
'(input)': 'onInput($event)',
},
template: `
<input
type="range"
[value]="value()"
[min]="min()"
[max]="max()"
/>
<span>{{ value() }}</span>
`,
})
export class Slider {
// Model creates both input and output
value = model(0);
min = input(0);
max = input(100);
onInput(event: Event) {
const target = event.target as HTMLInputElement;
this.value.set(Number(target.value));
}
}
// Usage: <app-slider [(value)]="sliderValue" />
```
Required model:
```typescript
value = model.required<number>();
```
## View Queries
Query elements and components in the template:
```typescript
import { Component, viewChild, viewChildren, ElementRef } from '@angular/core';
@Component({
selector: 'app-gallery',
template: `
<div #container class="gallery">
@for (image of images(); track image.id) {
<app-image-card [image]="image" />
}
</div>
`,
})
export class Gallery {
images = input.required<Image[]>();
// Query single element
container = viewChild.required<ElementRef<HTMLDivElement>>('container');
// Query single component (optional)
firstCard = viewChild(ImageCard);
// Query all matching components
allCards = viewChildren(ImageCard);
}
```
## Content Queries
Query projected content:
```typescript
import { Component, contentChild, contentChildren, effect, signal } from '@angular/core';
@Component({
selector: 'app-tabs',
template: `
<div class="tab-headers">
@for (tab of tabs(); track tab.label()) {
<button
[class.active]="tab === activeTab()"
(click)="selectTab(tab)"
>
{{ tab.label() }}
</button>
}
</div>
<div class="tab-content">
<ng-content />
</div>
`,
})
export class Tabs {
// Query all projected Tab children
tabs = contentChildren(Tab);
// Query single projected element
header = contentChild('tabHeader');
activeTab = signal<Tab | undefined>(undefined);
constructor() {
// Set first tab as active when tabs are available
effect(() => {
const firstTab = this.tabs()[0];
if (firstTab && !this.activeTab()) {
this.activeTab.set(firstTab);
}
});
}
selectTab(tab: Tab) {
this.activeTab.set(tab);
}
}
@Component({
selector: 'app-tab',
template: `<ng-content />`,
host: {
'[class.active]': 'isActive()',
'[style.display]': 'isActive() ? "block" : "none"',
},
})
export class Tab {
label = input.required<string>();
isActive = input(false);
}
```
## Dependency Injection in Components
Use `inject()` function instead of constructor injection:
```typescript
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-dashboard',
template: `...`,
})
export class Dashboard {
private router = inject(Router);
private userService = inject(User);
private config = inject(APP_CONFIG);
// Optional injection
private analytics = inject(Analytics, { optional: true });
// Self-only injection
private localService = inject(Local, { self: true });
navigateToProfile() {
this.router.navigate(['/profile']);
}
}
```
## Component Communication Patterns
### Parent to Child (Inputs)
```typescript
// Parent
@Component({
template: `<app-child [data]="parentData()" [config]="config" />`,
})
export class Parent {
parentData = signal({ name: 'Test' });
config = { theme: 'dark' };
}
// Child
@Component({ selector: 'app-child' })
export class Child {
data = input.required<Data>();
config = input<Config>();
}
```
### Child to Parent (Outputs)
```typescript
// Child
@Component({
selector: 'app-child',
template: `<button (click)="save()">Save</button>`,
})
export class Child {
saved = output<Data>();
save() {
this.saved.emit({ id: 1, name: 'Item' });
}
}
// Parent
@Component({
template: `<app-child (saved)="onSaved($event)" />`,
})
export class Parent {
onSaved(data: Data) {
console.log('Saved:', data);
}
}
```
### Shared Service Pattern
```typescript
// Shared state service
@Injectable({ providedIn: 'root' })
export class Cart {
private items = signal<CartItem[]>([]);
readonly items$ = this.items.asReadonly();
readonly total = computed(() =>
this.items().reduce((sum, item) => sum + item.price, 0)
);
addItem(item: CartItem) {
this.items.update(items => [...items, item]);
}
removeItem(id: string) {
this.items.update(items => items.filter(i => i.id !== id));
}
}
// Component A
@Component({ template: `<button (click)="add()">Add</button>` })
export class Product {
private cart = inject(Cart);
product = input.required<Product>();
add() {
this.cart.addItem({ ...this.product(), quantity: 1 });
}
}
// Component B
@Component({ template: `<span>Total: {{ cart.total() }}</span>` })
export class CartSummary {
cart = inject(Cart);
}
```
## Dynamic Components
Using `@defer` for lazy loading:
```typescript
@Component({
template: `
@defer (on viewport) {
<app-heavy-chart [data]="chartData()" />
} @placeholder {
<div class="chart-placeholder">Loading chart...</div>
} @loading (minimum 500ms) {
<app-spinner />
} @error {
<p>Failed to load chart</p>
}
`,
})
export class Dashboard {
chartData = input.required<ChartData>();
}
```
Defer triggers:
- `on viewport` - When element enters viewport
- `on idle` - When browser is idle
- `on interaction` - On user interaction (click, focus)
- `on hover` - On mouse hover
- `on immediate` - Immediately after non-deferred content
- `on timer(500ms)` - After specified delay
- `when condition` - When expression becomes true
```typescript
@Component({
template: `
@defer (on interaction; prefetch on idle) {
<app-comments [postId]="postId()" />
} @placeholder {
<button>Load Comments</button>
}
`,
})
export class Post {
postId = input.required<string>();
}
```
## Attribute Directives on Components
```typescript
@Directive({
selector: '[appHighlight]',
host: {
'[style.backgroundColor]': 'color()',
},
})
export class Highlight {
color = input('yellow', { alias: 'appHighlight' });
}
// Usage on component
@Component({
imports: [Highlight],
template: `<app-card appHighlight="lightblue" />`,
})
export class Page {}
```
## Error Boundaries
```typescript
@Component({
selector: 'app-error-boundary',
template: `
@if (hasError()) {
<div class="error">
<h3>Something went wrong</h3>
<button (click)="retry()">Retry</button>
</div>
} @else {
<ng-content />
}
`,
})
export class ErrorBoundary {
hasError = signal(false);
private errorHandler = inject(ErrorHandler);
retry() {
this.hasError.set(false);
}
}
```
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Brandon Roberts
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+314
View File
@@ -0,0 +1,314 @@
---
name: angular-signals
description: >-
Implement signal-based reactive state management in Angular v20+. Use for
creating reactive state with signal(), derived state with computed(),
dependent state with linkedSignal(), and side effects with effect(). Triggers
on state management questions, converting from BehaviorSubject/Observable
patterns to signals, or implementing reactive data flows.
metadata:
category: development
source:
repository: 'https://github.com/analogjs/angular-skills'
path: skills/angular-signals
license_path: LICENSE
commit: 610c90eb9490194bcff703f343f97fa0e00bdb2f
---
# Angular Signals
Signals are Angular's reactive primitive for state management. They provide synchronous, fine-grained reactivity.
## Core Signal APIs
### signal() - Writable State
```typescript
import { signal } from '@angular/core';
// Create writable signal
const count = signal(0);
// Read value
console.log(count()); // 0
// Set new value
count.set(5);
// Update based on current value
count.update(c => c + 1);
// With explicit type
const user = signal<User | null>(null);
user.set({ id: 1, name: 'Alice' });
```
### computed() - Derived State
```typescript
import { signal, computed } from '@angular/core';
const firstName = signal('John');
const lastName = signal('Doe');
// Derived signal - automatically updates when dependencies change
const fullName = computed(() => `${firstName()} ${lastName()}`);
console.log(fullName()); // "John Doe"
firstName.set('Jane');
console.log(fullName()); // "Jane Doe"
// Computed with complex logic
const items = signal<Item[]>([]);
const filter = signal('');
const filteredItems = computed(() => {
const query = filter().toLowerCase();
return items().filter(item =>
item.name.toLowerCase().includes(query)
);
});
const totalPrice = computed(() =>
filteredItems().reduce((sum, item) => sum + item.price, 0)
);
```
### linkedSignal() - Dependent State with Reset
```typescript
import { signal, linkedSignal } from '@angular/core';
const options = signal(['A', 'B', 'C']);
// Resets to first option when options change
const selected = linkedSignal(() => options()[0]);
console.log(selected()); // "A"
selected.set('B'); // User selects B
console.log(selected()); // "B"
options.set(['X', 'Y']); // Options change
console.log(selected()); // "X" - auto-reset to first
// With previous value access
const items = signal<Item[]>([]);
const selectedItem = linkedSignal<Item[], Item | null>({
source: () => items(),
computation: (newItems, previous) => {
// Try to preserve selection if item still exists
const prevItem = previous?.value;
if (prevItem && newItems.some(i => i.id === prevItem.id)) {
return prevItem;
}
return newItems[0] ?? null;
},
});
```
### effect() - Side Effects
```typescript
import { signal, effect, inject, DestroyRef } from '@angular/core';
@Component({...})
export class Search {
query = signal('');
constructor() {
// Effect runs when query changes
effect(() => {
console.log('Search query:', this.query());
});
// Effect with cleanup
effect((onCleanup) => {
const timer = setInterval(() => {
console.log('Current query:', this.query());
}, 1000);
onCleanup(() => clearInterval(timer));
});
}
}
```
**Effect rules:**
- Run in injection context (constructor or with `runInInjectionContext`)
- Automatically cleaned up when component destroys
## Component State Pattern
```typescript
@Component({
selector: 'app-todo-list',
template: `
<input [value]="newTodo()" (input)="newTodo.set($any($event.target).value)" />
<button (click)="addTodo()" [disabled]="!canAdd()">Add</button>
<ul>
@for (todo of filteredTodos(); track todo.id) {
<li [class.done]="todo.done">
{{ todo.text }}
<button (click)="toggleTodo(todo.id)">Toggle</button>
</li>
}
</ul>
<p>{{ remaining() }} remaining</p>
`,
})
export class TodoList {
// State
todos = signal<Todo[]>([]);
newTodo = signal('');
filter = signal<'all' | 'active' | 'done'>('all');
// Derived state
canAdd = computed(() => this.newTodo().trim().length > 0);
filteredTodos = computed(() => {
const todos = this.todos();
switch (this.filter()) {
case 'active': return todos.filter(t => !t.done);
case 'done': return todos.filter(t => t.done);
default: return todos;
}
});
remaining = computed(() =>
this.todos().filter(t => !t.done).length
);
// Actions
addTodo() {
const text = this.newTodo().trim();
if (text) {
this.todos.update(todos => [
...todos,
{ id: crypto.randomUUID(), text, done: false }
]);
this.newTodo.set('');
}
}
toggleTodo(id: string) {
this.todos.update(todos =>
todos.map(t => t.id === id ? { ...t, done: !t.done } : t)
);
}
}
```
## RxJS Interop
### toSignal() - Observable to Signal
```typescript
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({...})
export class Timer {
private http = inject(HttpClient);
// From observable - requires initial value or allowUndefined
counter = toSignal(interval(1000), { initialValue: 0 });
// From HTTP - undefined until loaded
users = toSignal(this.http.get<User[]>('/api/users'));
// With requireSync for synchronous observables (BehaviorSubject)
private user$ = new BehaviorSubject<User | null>(null);
currentUser = toSignal(this.user$, { requireSync: true });
}
```
### toObservable() - Signal to Observable
```typescript
import { toObservable } from '@angular/core/rxjs-interop';
import { switchMap, debounceTime } from 'rxjs';
@Component({...})
export class Search {
query = signal('');
private http = inject(HttpClient);
// Convert signal to observable for RxJS operators
results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
switchMap(q => this.http.get<Result[]>(`/api/search?q=${q}`))
),
{ initialValue: [] }
);
}
```
## Signal Equality
```typescript
// Custom equality function
const user = signal<User>(
{ id: 1, name: 'Alice' },
{ equal: (a, b) => a.id === b.id }
);
// Only triggers updates when ID changes
user.set({ id: 1, name: 'Alice Updated' }); // No update
user.set({ id: 2, name: 'Bob' }); // Triggers update
```
## Untracked Reads
```typescript
import { untracked } from '@angular/core';
const a = signal(1);
const b = signal(2);
// Only depends on 'a', not 'b'
const result = computed(() => {
const aVal = a();
const bVal = untracked(() => b());
return aVal + bVal;
});
```
## Service State Pattern
```typescript
@Injectable({ providedIn: 'root' })
export class Auth {
// Private writable state
private _user = signal<User | null>(null);
private _loading = signal(false);
// Public read-only signals
readonly user = this._user.asReadonly();
readonly loading = this._loading.asReadonly();
readonly isAuthenticated = computed(() => this._user() !== null);
private http = inject(HttpClient);
async login(credentials: Credentials): Promise<void> {
this._loading.set(true);
try {
const user = await firstValueFrom(
this.http.post<User>('/api/login', credentials)
);
this._user.set(user);
} finally {
this._loading.set(false);
}
}
logout(): void {
this._user.set(null);
}
}
```
For advanced patterns including resource(), see [references/signal-patterns.md](references/signal-patterns.md).
@@ -0,0 +1,404 @@
# Angular Signal Patterns
## Table of Contents
- [Resource API](#resource-api)
- [Signal Store Pattern](#signal-store-pattern)
- [Form State with Signals](#form-state-with-signals)
- [Async Operations](#async-operations)
- [Testing Signals](#testing-signals)
## Resource API
The `resource()` API handles async data fetching with signals:
```typescript
import { resource, signal, computed } from '@angular/core';
@Component({...})
export class UserProfile {
userId = signal<string>('');
// Resource fetches data when params change
userResource = resource({
params: () => ({ id: this.userId() }),
loader: async ({ params, abortSignal }) => {
const response = await fetch(`/api/users/${params.id}`, {
signal: abortSignal,
});
return response.json() as Promise<User>;
},
});
// Access resource state
user = computed(() => this.userResource.value());
isLoading = computed(() => this.userResource.isLoading());
error = computed(() => this.userResource.error());
}
```
### Resource Status
```typescript
const userResource = resource({...});
// Status signals
userResource.value(); // Current value or undefined
userResource.hasValue(); // Boolean - has resolved value
userResource.error(); // Error or undefined
userResource.isLoading(); // Boolean - currently loading
userResource.status(); // 'idle' | 'loading' | 'reloading' | 'resolved' | 'error' | 'local'
// Manual reload
userResource.reload();
// Local updates
userResource.set(newValue);
userResource.update(current => ({ ...current, name: 'Updated' }));
```
### Resource with Default Value
```typescript
const todosResource = resource({
defaultValue: [] as Todo[],
params: () => ({ filter: this.filter() }),
loader: async ({ params }) => {
const response = await fetch(`/api/todos?filter=${params.filter}`);
return response.json();
},
});
// value() returns Todo[] (never undefined due to defaultValue)
```
### Conditional Loading
```typescript
const userId = signal<string | null>(null);
const userResource = resource({
params: () => {
const id = userId();
// Return undefined to skip loading
return id ? { id } : undefined;
},
loader: async ({ params }) => {
return fetch(`/api/users/${params.id}`).then(r => r.json());
},
});
// Status is 'idle' when params returns undefined
```
## Signal Store Pattern
For complex state, create a dedicated store:
```typescript
interface ProductState {
products: Product[];
selectedId: string | null;
filter: string;
loading: boolean;
error: string | null;
}
@Injectable({ providedIn: 'root' })
export class ProductSt {
// Private state
private state = signal<ProductState>({
products: [],
selectedId: null,
filter: '',
loading: false,
error: null,
});
// Selectors (computed signals)
readonly products = computed(() => this.state().products);
readonly selectedId = computed(() => this.state().selectedId);
readonly filter = computed(() => this.state().filter);
readonly loading = computed(() => this.state().loading);
readonly error = computed(() => this.state().error);
readonly filteredProducts = computed(() => {
const { products, filter } = this.state();
if (!filter) return products;
return products.filter(p =>
p.name.toLowerCase().includes(filter.toLowerCase())
);
});
readonly selectedProduct = computed(() => {
const { products, selectedId } = this.state();
return products.find(p => p.id === selectedId) ?? null;
});
private http = inject(HttpClient);
// Actions
setFilter(filter: string): void {
this.state.update(s => ({ ...s, filter }));
}
selectProduct(id: string | null): void {
this.state.update(s => ({ ...s, selectedId: id }));
}
async loadProducts(): Promise<void> {
this.state.update(s => ({ ...s, loading: true, error: null }));
try {
const products = await firstValueFrom(
this.http.get<Product[]>('/api/products')
);
this.state.update(s => ({ ...s, products, loading: false }));
} catch (err) {
this.state.update(s => ({
...s,
loading: false,
error: 'Failed to load products'
}));
}
}
async addProduct(product: Omit<Product, 'id'>): Promise<void> {
const newProduct = await firstValueFrom(
this.http.post<Product>('/api/products', product)
);
this.state.update(s => ({
...s,
products: [...s.products, newProduct],
}));
}
}
```
## Form State with Signals
```typescript
interface FormState<T> {
value: T;
touched: boolean;
dirty: boolean;
valid: boolean;
errors: string[];
}
function createFormField<T>(
initialValue: T,
validators: ((value: T) => string | null)[] = []
) {
const value = signal(initialValue);
const touched = signal(false);
const dirty = signal(false);
const errors = computed(() => {
return validators
.map(v => v(value()))
.filter((e): e is string => e !== null);
});
const valid = computed(() => errors().length === 0);
return {
value,
touched: touched.asReadonly(),
dirty: dirty.asReadonly(),
errors,
valid,
setValue(newValue: T) {
value.set(newValue);
dirty.set(true);
},
markTouched() {
touched.set(true);
},
reset() {
value.set(initialValue);
touched.set(false);
dirty.set(false);
},
};
}
// Usage
@Component({...})
export class Signup {
email = createFormField('', [
v => !v ? 'Email is required' : null,
v => !v.includes('@') ? 'Invalid email' : null,
]);
password = createFormField('', [
v => !v ? 'Password is required' : null,
v => v.length < 8 ? 'Password must be at least 8 characters' : null,
]);
formValid = computed(() =>
this.email.valid() && this.password.valid()
);
}
```
## Async Operations
### Debounced Search
```typescript
@Component({...})
export class Search {
query = signal('');
private http = inject(HttpClient);
// Debounced search using toObservable
results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
distinctUntilChanged(),
filter(q => q.length >= 2),
switchMap(q => this.http.get<Result[]>(`/api/search?q=${q}`)),
catchError(() => of([]))
),
{ initialValue: [] }
);
// Loading state
private searching = signal(false);
readonly isSearching = this.searching.asReadonly();
constructor() {
// Track loading state
effect(() => {
const q = this.query();
if (q.length >= 2) {
this.searching.set(true);
}
});
effect(() => {
this.results(); // Subscribe to results
this.searching.set(false);
});
}
}
```
### Optimistic Updates
```typescript
@Injectable({ providedIn: 'root' })
export class Todo {
private todos = signal<Todo[]>([]);
readonly items = this.todos.asReadonly();
private http = inject(HttpClient);
async toggleTodo(id: string): Promise<void> {
// Optimistic update
const previousTodos = this.todos();
this.todos.update(todos =>
todos.map(t => t.id === id ? { ...t, done: !t.done } : t)
);
try {
await firstValueFrom(
this.http.patch(`/api/todos/${id}/toggle`, {})
);
} catch {
// Rollback on error
this.todos.set(previousTodos);
}
}
}
```
## Testing Signals
```typescript
describe('Counter', () => {
it('should increment count', () => {
const component = new Counter();
expect(component.count()).toBe(0);
component.increment();
expect(component.count()).toBe(1);
component.increment();
expect(component.count()).toBe(2);
});
it('should compute doubled value', () => {
const component = new Counter();
expect(component.doubled()).toBe(0);
component.count.set(5);
expect(component.doubled()).toBe(10);
});
});
describe('ProductSt', () => {
let store: ProductSt;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ProductSt,
provideHttpClient(),
provideHttpClientTesting(),
],
});
store = TestBed.inject(ProductSt);
httpMock = TestBed.inject(HttpTestingController);
});
it('should filter products', () => {
// Set initial state
store['state'].set({
products: [
{ id: '1', name: 'Apple' },
{ id: '2', name: 'Banana' },
],
selectedId: null,
filter: '',
loading: false,
error: null,
});
expect(store.filteredProducts().length).toBe(2);
store.setFilter('app');
expect(store.filteredProducts().length).toBe(1);
expect(store.filteredProducts()[0].name).toBe('Apple');
});
});
```
## Signal Debugging
```typescript
// Debug effect to log signal changes
effect(() => {
console.log('State changed:', {
count: this.count(),
items: this.items(),
filter: this.filter(),
});
});
// Conditional debugging
const DEBUG = signal(false);
effect(() => {
if (untracked(() => DEBUG())) {
console.log('Debug:', this.state());
}
});
```
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Brandon Roberts
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+471
View File
@@ -0,0 +1,471 @@
---
name: angular-testing
description: >-
Write unit and integration tests for Angular v20+ applications using Vitest or
Jasmine with TestBed and modern testing patterns. Use for testing components
with signals, OnPush change detection, services with inject(), and HTTP
interactions. Triggers on test creation, testing signal-based components,
mocking dependencies, or setting up test infrastructure. Don't use for E2E
testing with Cypress or Playwright, or for testing non-Angular
JavaScript/TypeScript code.
metadata:
category: development
source:
repository: 'https://github.com/analogjs/angular-skills'
path: skills/angular-testing
license_path: LICENSE
commit: 610c90eb9490194bcff703f343f97fa0e00bdb2f
---
# Angular Testing
Test Angular v20+ applications with Vitest (recommended) or Jasmine, focusing on signal-based components and modern patterns.
## Vitest Setup (Angular v20+)
Angular v20+ has native Vitest support through the `@angular/build` package.
```bash
npm install -D vitest jsdom
```
Configure in angular.json:
```json
{
"projects": {
"your-app": {
"architect": {
"test": {
"builder": "@angular/build:unit-test",
"options": {
"tsConfig": "tsconfig.spec.json",
"buildTarget": "your-app:build"
}
}
}
}
}
}
```
Run tests:
```bash
ng test # Run tests
ng test --watch # Watch mode
ng test --code-coverage # With coverage
```
For Vitest migration from Jasmine and advanced configuration, see [references/vitest-migration.md](references/vitest-migration.md).
## Basic Component Test
```typescript
import { describe, it, expect, beforeEach } from 'vitest';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Counter } from './counter.component';
describe('Counter', () => {
let component: Counter;
let fixture: ComponentFixture<Counter>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Counter], // Standalone component
}).compileComponents();
fixture = TestBed.createComponent(Counter);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should increment count', () => {
expect(component.count()).toBe(0);
component.increment();
expect(component.count()).toBe(1);
});
it('should display count in template', () => {
component.count.set(5);
fixture.detectChanges();
const element = fixture.nativeElement.querySelector('.count');
expect(element.textContent).toContain('5');
});
});
```
## Testing Signals
### Direct Signal Testing
```typescript
import { signal, computed } from '@angular/core';
describe('Signal logic', () => {
it('should update computed when signal changes', () => {
const count = signal(0);
const doubled = computed(() => count() * 2);
expect(doubled()).toBe(0);
count.set(5);
expect(doubled()).toBe(10);
count.update(c => c + 1);
expect(doubled()).toBe(12);
});
});
```
### Testing Component Signals
```typescript
@Component({
selector: 'app-todo-list',
template: `
<ul>
@for (todo of filteredTodos(); track todo.id) {
<li>{{ todo.text }}</li>
}
</ul>
<p>{{ remaining() }} remaining</p>
`,
})
export class TodoList {
todos = signal<Todo[]>([]);
filter = signal<'all' | 'active' | 'done'>('all');
filteredTodos = computed(() => {
const todos = this.todos();
switch (this.filter()) {
case 'active': return todos.filter(t => !t.done);
case 'done': return todos.filter(t => t.done);
default: return todos;
}
});
remaining = computed(() => this.todos().filter(t => !t.done).length);
}
describe('TodoList', () => {
let component: TodoList;
let fixture: ComponentFixture<TodoList>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [TodoList],
}).compileComponents();
fixture = TestBed.createComponent(TodoList);
component = fixture.componentInstance;
});
it('should filter active todos', () => {
component.todos.set([
{ id: '1', text: 'Task 1', done: false },
{ id: '2', text: 'Task 2', done: true },
{ id: '3', text: 'Task 3', done: false },
]);
component.filter.set('active');
expect(component.filteredTodos().length).toBe(2);
expect(component.remaining()).toBe(2);
});
});
```
## Testing OnPush Components
OnPush components require explicit change detection:
```typescript
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<span>{{ data().name }}</span>`,
})
export class OnPushCmpt {
data = input.required<{ name: string }>();
}
describe('OnPushCmpt', () => {
it('should update when input signal changes', () => {
const fixture = TestBed.createComponent(OnPushCmpt);
// Set input using setInput (for signal inputs)
fixture.componentRef.setInput('data', { name: 'Initial' });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Initial');
// Update input
fixture.componentRef.setInput('data', { name: 'Updated' });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Updated');
});
});
```
## Testing Services
### Basic Service Test
```typescript
@Injectable({ providedIn: 'root' })
export class CounterService {
private _count = signal(0);
readonly count = this._count.asReadonly();
increment() { this._count.update(c => c + 1); }
reset() { this._count.set(0); }
}
describe('CounterService', () => {
let service: CounterService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(CounterService);
});
it('should increment count', () => {
expect(service.count()).toBe(0);
service.increment();
expect(service.count()).toBe(1);
});
});
```
### Service with HTTP
```typescript
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideHttpClient } from '@angular/common/http';
describe('UserService', () => {
let service: UserService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
],
});
service = TestBed.inject(UserService);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpMock.verify(); // Verify no outstanding requests
});
it('should fetch user by id', () => {
const mockUser = { id: '1', name: 'Test User' };
service.getUser('1').subscribe(user => {
expect(user).toEqual(mockUser);
});
const req = httpMock.expectOne('/api/users/1');
expect(req.request.method).toBe('GET');
req.flush(mockUser);
});
});
```
## Mocking Dependencies
### Using Vitest Mocks
```typescript
import { describe, it, expect, vi, beforeEach } from 'vitest';
describe('UserProfile', () => {
const mockUserService = {
getUser: vi.fn(),
updateUser: vi.fn(),
user: signal<User | null>(null),
};
beforeEach(async () => {
vi.clearAllMocks();
mockUserService.getUser.mockReturnValue(of({ id: '1', name: 'Test' }));
await TestBed.configureTestingModule({
imports: [UserProfile],
providers: [
{ provide: UserService, useValue: mockUserService },
],
}).compileComponents();
});
it('should call getUser on init', () => {
const fixture = TestBed.createComponent(UserProfile);
fixture.detectChanges();
expect(mockUserService.getUser).toHaveBeenCalledWith('1');
});
});
```
### Mock Signal-Based Service
```typescript
const mockAuth = {
user: signal<User | null>(null),
isAuthenticated: computed(() => mockAuth.user() !== null),
login: vi.fn(),
logout: vi.fn(),
};
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ProtectedPage],
providers: [
{ provide: AuthService, useValue: mockAuth },
],
}).compileComponents();
});
it('should show content when authenticated', () => {
mockAuth.user.set({ id: '1', name: 'Test User' });
const fixture = TestBed.createComponent(ProtectedPage);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.protected-content')).toBeTruthy();
});
```
## Testing Inputs and Outputs
```typescript
@Component({
selector: 'app-item',
template: `<div (click)="select()">{{ item().name }}</div>`,
})
export class ItemCmpt {
item = input.required<Item>();
selected = output<Item>();
select() {
this.selected.emit(this.item());
}
}
describe('ItemCmpt', () => {
it('should emit selected event on click', () => {
const fixture = TestBed.createComponent(ItemCmpt);
const item: Item = { id: '1', name: 'Test Item' };
fixture.componentRef.setInput('item', item);
fixture.detectChanges();
let emittedItem: Item | undefined;
fixture.componentInstance.selected.subscribe(i => emittedItem = i);
fixture.nativeElement.querySelector('div').click();
expect(emittedItem).toEqual(item);
});
});
```
## Testing Async Operations
### Using fakeAsync
```typescript
import { fakeAsync, tick, flush } from '@angular/core/testing';
it('should debounce search', fakeAsync(() => {
const fixture = TestBed.createComponent(SearchCmpt);
fixture.detectChanges();
fixture.componentInstance.query.set('test');
tick(300); // Advance time for debounce
fixture.detectChanges();
expect(fixture.componentInstance.results().length).toBeGreaterThan(0);
flush(); // Flush remaining timers
}));
```
### Using waitForAsync
```typescript
import { waitForAsync } from '@angular/core/testing';
it('should load data', waitForAsync(() => {
const fixture = TestBed.createComponent(DataCmpt);
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(fixture.componentInstance.data()).toBeDefined();
});
}));
```
## Testing HTTP Resources
```typescript
@Component({
template: `
@if (userResource.isLoading()) {
<p>Loading...</p>
} @else if (userResource.hasValue()) {
<p>{{ userResource.value().name }}</p>
}
`,
})
export class UserCmpt {
userId = signal('1');
userResource = httpResource<User>(() => `/api/users/${this.userId()}`);
}
describe('UserCmpt', () => {
let httpMock: HttpTestingController;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [UserCmpt],
providers: [
provideHttpClient(),
provideHttpClientTesting(),
],
}).compileComponents();
httpMock = TestBed.inject(HttpTestingController);
});
it('should display user name after loading', () => {
const fixture = TestBed.createComponent(UserCmpt);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Loading');
const req = httpMock.expectOne('/api/users/1');
req.flush({ id: '1', name: 'John Doe' });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('John Doe');
});
});
```
For advanced testing patterns including component harnesses, router testing, form testing, and directive testing, see [references/testing-patterns.md](references/testing-patterns.md).
For Vitest migration from Jasmine, see [references/vitest-migration.md](references/vitest-migration.md).
@@ -0,0 +1,707 @@
# Angular Testing Patterns
## Table of Contents
- [Vitest Advanced Patterns](#vitest-advanced-patterns)
- [Component Harnesses](#component-harnesses)
- [Testing Router](#testing-router)
- [Testing Forms](#testing-forms)
- [Testing Directives](#testing-directives)
- [Testing Pipes](#testing-pipes)
- [E2E Testing Setup](#e2e-testing-setup)
## Vitest Advanced Patterns
### Snapshot Testing
```typescript
import { describe, it, expect } from 'vitest';
describe('UserCard', () => {
it('should match snapshot', () => {
const fixture = TestBed.createComponent(UserCard);
fixture.componentRef.setInput('user', { id: '1', name: 'John', email: 'john@example.com' });
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toMatchSnapshot();
});
});
```
### Parameterized Tests
```typescript
import { describe, it, expect } from 'vitest';
describe('Validator', () => {
it.each([
{ input: '', expected: false },
{ input: 'test', expected: false },
{ input: 'test@example.com', expected: true },
{ input: 'invalid@', expected: false },
])('should validate email "$input" as $expected', ({ input, expected }) => {
expect(isValidEmail(input)).toBe(expected);
});
});
```
### Testing with Fake Timers
```typescript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
describe('Debounced Search', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('should debounce search input', async () => {
const fixture = TestBed.createComponent(Search);
fixture.detectChanges();
fixture.componentInstance.query.set('test');
// Search not called yet
expect(fixture.componentInstance.results()).toEqual([]);
// Advance timers
vi.advanceTimersByTime(300);
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.componentInstance.results().length).toBeGreaterThan(0);
});
});
```
### Module Mocking
```typescript
import { describe, it, expect, vi } from 'vitest';
// Mock entire module
vi.mock('./analytics.service', () => ({
Analytics: class {
track = vi.fn();
identify = vi.fn();
},
}));
describe('with mocked analytics', () => {
it('should track events', () => {
const fixture = TestBed.createComponent(Dashboard);
const analytics = TestBed.inject(Analytics);
fixture.detectChanges();
expect(analytics.track).toHaveBeenCalledWith('dashboard_viewed');
});
});
```
### Testing Async/Await
```typescript
import { describe, it, expect, vi } from 'vitest';
describe('User', () => {
it('should load user data', async () => {
const mockUser = { id: '1', name: 'Test' };
const httpMock = TestBed.inject(HttpTestingController);
const service = TestBed.inject(User);
const userPromise = service.loadUser('1');
httpMock.expectOne('/api/users/1').flush(mockUser);
const user = await userPromise;
expect(user).toEqual(mockUser);
});
});
```
### Coverage Configuration
```typescript
// vite.config.ts
export default defineConfig({
test: {
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
exclude: [
'node_modules/',
'src/test-setup.ts',
'**/*.spec.ts',
'**/*.d.ts',
],
thresholds: {
statements: 80,
branches: 80,
functions: 80,
lines: 80,
},
},
},
});
```
### Vitest UI Mode
```bash
# Run with UI
npx vitest --ui
# Open UI at specific port
npx vitest --ui --port 51204
```
### Concurrent Tests
```typescript
import { describe, it, expect } from 'vitest';
// Run tests in this describe block concurrently
describe.concurrent('API calls', () => {
it('should fetch users', async () => {
// ...
});
it('should fetch products', async () => {
// ...
});
it('should fetch orders', async () => {
// ...
});
});
```
### Test Fixtures
```typescript
import { describe, it, expect, beforeEach } from 'vitest';
// Shared test fixtures
const createTestUser = (overrides = {}) => ({
id: '1',
name: 'Test User',
email: 'test@example.com',
...overrides,
});
const createTestProduct = (overrides = {}) => ({
id: '1',
name: 'Test Product',
price: 99.99,
...overrides,
});
describe('Order', () => {
it('should calculate total', () => {
const fixture = TestBed.createComponent(Order);
fixture.componentRef.setInput('user', createTestUser());
fixture.componentRef.setInput('products', [
createTestProduct({ price: 10 }),
createTestProduct({ id: '2', price: 20 }),
]);
fixture.detectChanges();
expect(fixture.componentInstance.total()).toBe(30);
});
});
```
## Component Harnesses
Use Angular CDK component harnesses for more maintainable tests:
### Creating a Harness
```typescript
import { ComponentHarness, HarnessPredicate } from '@angular/cdk/testing';
export class CounterHarn extends ComponentHarness {
static hostSelector = 'app-counter';
// Locators
private getIncrementButton = this.locatorFor('button.increment');
private getDecrementButton = this.locatorFor('button.decrement');
private getCountDisplay = this.locatorFor('.count');
// Actions
async increment(): Promise<void> {
const button = await this.getIncrementButton();
await button.click();
}
async decrement(): Promise<void> {
const button = await this.getDecrementButton();
await button.click();
}
// Queries
async getCount(): Promise<number> {
const display = await this.getCountDisplay();
const text = await display.text();
return parseInt(text, 10);
}
// Filter factory
static with(options: { count?: number } = {}): HarnessPredicate<CounterHarn> {
return new HarnessPredicate(CounterHarn, options)
.addOption('count', options.count, async (harness, count) => {
return (await harness.getCount()) === count;
});
}
}
```
### Using Harnesses in Tests
```typescript
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
describe('Counter with Harness', () => {
let loader: HarnessLoader;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Counter],
}).compileComponents();
const fixture = TestBed.createComponent(Counter);
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should increment count', async () => {
const counter = await loader.getHarness(CounterHarn);
expect(await counter.getCount()).toBe(0);
await counter.increment();
expect(await counter.getCount()).toBe(1);
await counter.increment();
expect(await counter.getCount()).toBe(2);
});
it('should find counter with specific count', async () => {
const counter = await loader.getHarness(CounterHarn);
await counter.increment();
await counter.increment();
// Find counter with count of 2
const counterWith2 = await loader.getHarness(CounterHarn.with({ count: 2 }));
expect(counterWith2).toBeTruthy();
});
});
```
## Testing Router
### RouterTestingHarness
```typescript
import { RouterTestingHarness } from '@angular/router/testing';
import { provideRouter } from '@angular/router';
describe('Router Navigation', () => {
let harness: RouterTestingHarness;
beforeEach(async () => {
await TestBed.configureTestingModule({
providers: [
provideRouter([
{ path: '', component: Home },
{ path: 'users/:id', component: UserCmpt },
]),
],
}).compileComponents();
harness = await RouterTestingHarness.create();
});
it('should navigate to user page', async () => {
const component = await harness.navigateByUrl('/users/123', UserCmpt);
expect(component.id()).toBe('123');
});
it('should display user name', async () => {
await harness.navigateByUrl('/users/123');
expect(harness.routeNativeElement?.textContent).toContain('User 123');
});
});
```
### Testing Guards
```typescript
describe('AuthGuard', () => {
let authService: jasmine.SpyObj<Auth>;
beforeEach(() => {
authService = jasmine.createSpyObj('Auth', ['isAuthenticated']);
TestBed.configureTestingModule({
providers: [
{ provide: Auth, useValue: authService },
provideRouter([
{ path: 'login', component: Login },
{
path: 'dashboard',
component: Dashboard,
canActivate: [authGuard],
},
]),
],
});
});
it('should allow access when authenticated', async () => {
authService.isAuthenticated.and.returnValue(true);
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/dashboard');
expect(harness.routeNativeElement?.textContent).toContain('Dashboard');
});
it('should redirect to login when not authenticated', async () => {
authService.isAuthenticated.and.returnValue(false);
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/dashboard');
expect(TestBed.inject(Router).url).toBe('/login');
});
});
```
## Testing Forms
### Testing Signal Forms
```typescript
import { form, FormField, required, email } from '@angular/forms/signals';
@Component({
imports: [FormField],
template: `
<form (submit)="onSubmit($event)">
<input [formField]="loginForm.email" />
<input [formField]="loginForm.password" type="password" />
<button type="submit" [disabled]="loginForm().invalid()">Submit</button>
</form>
`,
})
export class Login {
model = signal({ email: '', password: '' });
loginForm = form(this.model, (schemaPath) => {
required(schemaPath.email);
email(schemaPath.email);
required(schemaPath.password);
});
submitted = signal(false);
onSubmit(event: Event) {
event.preventDefault();
if (this.loginForm().valid()) {
this.submitted.set(true);
}
}
}
describe('Login', () => {
let fixture: ComponentFixture<Login>;
let component: Login;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Login],
}).compileComponents();
fixture = TestBed.createComponent(Login);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be invalid when empty', () => {
expect(component.loginForm().invalid()).toBeTrue();
});
it('should be valid with correct data', () => {
component.model.set({
email: 'test@example.com',
password: 'password123',
});
expect(component.loginForm().valid()).toBeTrue();
});
it('should show email error for invalid email', () => {
component.loginForm.email().value.set('invalid');
fixture.detectChanges();
expect(component.loginForm.email().invalid()).toBeTrue();
expect(component.loginForm.email().errors().some(e => e.kind === 'email')).toBeTrue();
});
it('should disable submit button when invalid', () => {
const button = fixture.nativeElement.querySelector('button');
expect(button.disabled).toBeTrue();
});
});
```
### Testing Reactive Forms
```typescript
describe('ReactiveForm', () => {
it('should validate form', () => {
const fixture = TestBed.createComponent(ProfileForm);
const component = fixture.componentInstance;
expect(component.form.valid).toBeFalse();
component.form.patchValue({
name: 'John',
email: 'john@example.com',
});
expect(component.form.valid).toBeTrue();
});
it('should show validation errors', () => {
const fixture = TestBed.createComponent(ProfileForm);
fixture.detectChanges();
const emailControl = fixture.componentInstance.form.controls.email;
emailControl.setValue('invalid');
emailControl.markAsTouched();
fixture.detectChanges();
const errorElement = fixture.nativeElement.querySelector('.error');
expect(errorElement.textContent).toContain('Invalid email');
});
});
```
## Testing Directives
### Attribute Directive
```typescript
@Directive({
selector: '[appHighlight]',
host: {
'[style.backgroundColor]': 'color()',
},
})
export class Highlight {
color = input('yellow', { alias: 'appHighlight' });
}
describe('Highlight', () => {
@Component({
imports: [Highlight],
template: `<p appHighlight="lightblue">Test</p>`,
})
class Test {}
it('should apply background color', () => {
const fixture = TestBed.createComponent(Test);
fixture.detectChanges();
const p = fixture.nativeElement.querySelector('p');
expect(p.style.backgroundColor).toBe('lightblue');
});
});
```
### Structural Directive
```typescript
@Directive({
selector: '[appIf]',
})
export class If {
private templateRef = inject(TemplateRef);
private viewContainer = inject(ViewContainerRef);
condition = input.required<boolean>({ alias: 'appIf' });
constructor() {
effect(() => {
if (this.condition()) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
});
}
}
describe('If', () => {
@Component({
imports: [If],
template: `<p *appIf="show()">Visible</p>`,
})
class TestCmpt {
show = signal(false);
}
it('should show content when condition is true', () => {
const fixture = TestBed.createComponent(Test);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('p')).toBeNull();
fixture.componentInstance.show.set(true);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('p')).toBeTruthy();
});
});
```
## Testing Pipes
```typescript
@Pipe({ name: 'truncate' })
export class Truncate implements PipeTransform {
transform(value: string, length: number = 50): string {
if (value.length <= length) return value;
return value.substring(0, length) + '...';
}
}
describe('Truncate', () => {
let pipe: Truncate;
beforeEach(() => {
pipe = new Truncate();
});
it('should not truncate short strings', () => {
expect(pipe.transform('Hello', 10)).toBe('Hello');
});
it('should truncate long strings', () => {
expect(pipe.transform('Hello World', 5)).toBe('Hello...');
});
it('should use default length', () => {
const longString = 'a'.repeat(60);
const result = pipe.transform(longString);
expect(result.length).toBe(53); // 50 + '...'
});
});
```
## E2E Testing Setup
### Playwright Configuration
```typescript
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
baseURL: 'http://localhost:4200',
trace: 'on-first-retry',
},
webServer: {
command: 'npm run start',
url: 'http://localhost:4200',
reuseExistingServer: !process.env.CI,
},
});
```
### E2E Test Example
```typescript
// e2e/login.spec.ts
import { test, expect } from '@playwright/test';
test.describe('Login', () => {
test('should login successfully', async ({ page }) => {
await page.goto('/login');
await page.fill('input[name="email"]', 'test@example.com');
await page.fill('input[name="password"]', 'password123');
await page.click('button[type="submit"]');
await expect(page).toHaveURL('/dashboard');
await expect(page.locator('h1')).toContainText('Welcome');
});
test('should show error for invalid credentials', async ({ page }) => {
await page.goto('/login');
await page.fill('input[name="email"]', 'wrong@example.com');
await page.fill('input[name="password"]', 'wrongpassword');
await page.click('button[type="submit"]');
await expect(page.locator('.error')).toBeVisible();
await expect(page.locator('.error')).toContainText('Invalid credentials');
});
});
```
## Test Utilities
### Custom Test Helpers
```typescript
// test-utils.ts
export function setSignalInput<T>(
fixture: ComponentFixture<any>,
inputName: string,
value: T
): void {
fixture.componentRef.setInput(inputName, value);
fixture.detectChanges();
}
export async function waitForSignal<T>(
signal: () => T,
predicate: (value: T) => boolean,
timeout = 5000
): Promise<T> {
const start = Date.now();
while (Date.now() - start < timeout) {
const value = signal();
if (predicate(value)) return value;
await new Promise(resolve => setTimeout(resolve, 10));
}
throw new Error('Timeout waiting for signal');
}
// Usage
it('should load data', async () => {
const fixture = TestBed.createComponent(Data);
fixture.detectChanges();
await waitForSignal(
() => fixture.componentInstance.data(),
data => data !== undefined
);
expect(fixture.componentInstance.data()).toBeDefined();
});
```
@@ -0,0 +1,164 @@
# Vitest Setup and Migration Guide
## Vitest vs Jasmine Comparison
| Feature | Vitest | Jasmine/Karma |
|---------|--------|---------------|
| Speed | Faster (native ESM) | Slower |
| Watch mode | Instant feedback | Slower rebuilds |
| Mocking | `vi.fn()`, `vi.mock()` | `jasmine.createSpy()` |
| Assertions | `expect()` (Chai-style) | `expect()` (Jasmine) |
| UI | Built-in UI mode | Karma browser |
| Config | `angular.json` | `karma.conf.js` |
## Migration from Jasmine to Vitest
### Spy Migration
```typescript
// Jasmine
const spy = jasmine.createSpy('callback');
spy.and.returnValue('value');
expect(spy).toHaveBeenCalledWith('arg');
// Vitest
const spy = vi.fn();
spy.mockReturnValue('value');
expect(spy).toHaveBeenCalledWith('arg');
```
### SpyOn Migration
```typescript
// Jasmine
spyOn(service, 'method').and.returnValue(of(data));
// Vitest
vi.spyOn(service, 'method').mockReturnValue(of(data));
```
### createSpyObj Migration
```typescript
// Jasmine
const mockService = jasmine.createSpyObj('UserService', ['getUser', 'updateUser']);
mockService.getUser.and.returnValue(of({ id: '1', name: 'Test' }));
// Vitest
const mockService = {
getUser: vi.fn(),
updateUser: vi.fn(),
};
mockService.getUser.mockReturnValue(of({ id: '1', name: 'Test' }));
```
### Async Testing Migration
```typescript
// Jasmine - using done callback
it('should load data', (done) => {
service.loadData().subscribe(data => {
expect(data).toBeDefined();
done();
});
});
// Vitest - using async/await
it('should load data', async () => {
const data = await firstValueFrom(service.loadData());
expect(data).toBeDefined();
});
```
### Clock/Timer Migration
```typescript
// Jasmine
jasmine.clock().install();
jasmine.clock().tick(1000);
jasmine.clock().uninstall();
// Vitest
vi.useFakeTimers();
vi.advanceTimersByTime(1000);
vi.useRealTimers();
```
## Vitest Configuration Details
### Full angular.json Configuration
```json
{
"projects": {
"your-app": {
"architect": {
"test": {
"builder": "@angular/build:unit-test",
"options": {
"tsConfig": "tsconfig.spec.json",
"buildTarget": "your-app:build"
}
}
}
}
}
}
```
### tsconfig.spec.json
```json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"types": ["vitest/globals"]
},
"include": ["src/**/*.spec.ts"]
}
```
### Optional vite.config.ts
For advanced configuration, create a `vite.config.ts`:
```typescript
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'jsdom',
include: ['src/**/*.spec.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
exclude: [
'node_modules/',
'src/test-setup.ts',
'**/*.spec.ts',
'**/*.d.ts',
],
},
},
});
```
## Running Vitest
```bash
# Run tests
ng test
# Watch mode
ng test --watch
# Coverage
ng test --code-coverage
# Run specific file pattern
ng test --include='**/user*.spec.ts'
# CI mode (single run)
ng test --watch=false
```
+795
View File
@@ -0,0 +1,795 @@
---
name: faq-chatbot
description: Voice-to-Voice FAQ app rules and coding standards for Angular, audio, and FAQ features. Use when working on the Voice-to-Voice FAQ application, Angular components, pages, audio pipeline, WebSocket, FAQ manager, or any code in this project.
---
# SKILLS.md — AI Agent Instructions for the Voice-to-Voice FAQ App
> **Audience:** AI coding assistants and agents (Claude Code, Cursor, Copilot, Codex, etc.).
> **Compatible filenames:** keep this file as `SKILLS.md`; copy or symlink it to `CLAUDE.md`, `AGENTS.md`, or `.cursorrules` if your tool expects one of those.
> **Authority:** these rules are binding. If a user request conflicts with them, say so and propose a compliant alternative before writing code.
---
## 1. Project Overview & Rules of Engagement
### 1.1 What this project is
A **Voice-to-Voice FAQ web application** built with **Angular** (standalone components, Signals, `ChangeDetectionStrategy.OnPush`, **zoneless-ready**).
- **Voice mode:** real-time, full-duplex voice with an AI FAQ agent. A Three.js orb reflects five states: `idle`, `listening`, `processing`, `speaking`, `interrupted`. Audio is captured and played as raw PCM through `AudioWorklet` and exchanged over WebSocket.
- **Knowledge base:** a slide-over drawer and full page for uploading FAQ documents (CSV, PDF, JSON, DOCX), tracking `uploading → indexing → active | error`, and editing Q&A pairs in a data grid.
### 1.2 Your role
You are a **Principal Angular & Web Audio Engineer**. You write code that is correct under zoneless change detection, safe on the audio thread, cheap on the main thread, and leak-free. You prefer small, typed, testable units over cleverness.
### 1.3 Mandatory pre-flight (before generating ANY code)
1. **Read** these files in full, in this order:
1. `./docs/SRC_STRUCTURE.md` — where every file goes and who may import whom.
2. `./docs/ARCHITECTURE.md` — state machine, audio pipeline, data contracts.
3. `./docs/DEPENDENCIES.md` — the **only** approved libraries and versions.
2. **If a file is missing or unreadable, stop and tell the user.** Do not guess its contents.
3. **Locate the target path** for every file you will create or edit in `SRC_STRUCTURE.md`. If no suitable location exists, propose one and wait for confirmation instead of inventing a folder.
4. **Reuse before you write.** Search the repo for an existing service, type, util, or component that already does the job. In particular: **HTTP → `HttpService`**, **login/auth → `AuthService` + `authGuard`**, **theme → `ThemeService`** (see §1.7).
5. **State your plan in two or three lines** (files to touch, which rules apply) before the code.
### 1.4 Document precedence
```
| Question | Authoritative source |
| ------------------------------------------------------------- | ----------------------------------------------------------------- |
| Where does this file go? What may import what? | `SRC_STRUCTURE.md` |
| Which library or version may I use? | `DEPENDENCIES.md` |
| How should the system behave (states, protocol, data shapes)? | `ARCHITECTURE.md` |
| How should the code be written? | **This file** |
| HTTP, login, or theme changes | **This file §1.7** (`HttpService`, `AuthService`, `ThemeService`) |
```
If two project documents disagree, `SRC_STRUCTURE.md` wins for paths and `DEPENDENCIES.md` wins for packages. **Report the discrepancy** to the user; do not silently pick one.
### 1.5 Known deltas (these are intentional; do not "fix" them back)
```
| Topic | Rule in this repo | Do NOT write |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Zoneless provider (Angular 20.2+ incl. 22) | `provideZonelessChangeDetection()` | `provideExperimentalZonelessChangeDetection()` (it does **not exist** in Angular 22) |
| Zoneless provider (Angular 18/19 only) | `provideExperimentalZonelessChangeDetection()` | The stable name, which is not available there |
| Worklet files | `src/assets/worklets/pcm-capture-processor.js` and `pcm-playback-processor.js` | A single `src/assets/audio/pcm-processor.js` |
| Icons | **`@lucide/angular`**, accessed only through `shared/ui/icon` | `lucide-angular` (deprecated, peer-conflicts with Angular 22) |
| CSV parsing | `Papa.parse(file, { preview: N, … })` and chunked streaming | `worker: true` (commonly breaks under bundlers) |
| `standalone` flag | Everything is standalone; on Angular 19+ the flag is the default, so **omit it** | `standalone: false`, NgModules |
| Cleanup | `DestroyRef.onDestroy()` and `effect` `onCleanup` (and `ngOnDestroy` only when a class already implements it) | Treating `untracked()` as a cleanup hook (it is not one) |
| Component files | Always separate `.ts` + `.html` + `.css` files | Inline `template:` or `styles:` in the `@Component` decorator |
| Pages | Always under `src/app/pages/<page-name>/` | Putting pages under features/ or anywhere else |
```
**Check the installed Angular major in `package.json` first.** Apply the matching row above.
### 1.6 Scope & dependency discipline
- **Never add a package** that is not in `DEPENDENCIES.md`. If one is needed, explain why and ask first.
- **Never edit** `angular.json`, `package.json`, `tsconfig*.json`, or CI files unless the task requires it; when you do, explain the change.
- **Never refactor unrelated code** while implementing a feature. Mention opportunities instead.
- **Never delete files or tests** to make a build pass.
- Use the path aliases: `@core/*`, `@features/*`, `@shared/*`, `@env/*`.
### 1.7 Mandatory platform services (Http / Auth / Theme)
These three services are the **only** approved way to talk to the backend, authenticate, or change theme. Do not reinvent them, do not inject raw `HttpClient` for API calls, and do not write ad-hoc `localStorage` token or theme logic.
```
| Need | Use | Never |
| ----------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| Any REST / SSE / file download to the API | `HttpService` (`get` / `post` / `put` / `patch` / `delete` / `getStream` / `downloadFile`) | Direct `HttpClient`, bare `fetch` for API routes, or a second HTTP wrapper |
| Login, session check, route protection | `AuthService.login()`, `AuthService.isAuthenticated()`, `authGuard` | Hand-rolled login POST, reading `access_token` outside these services, custom guards that ignore `AuthService` |
| Dark / light theme init and toggle | `ThemeService` (`initTheme` at app start, `toggleDarkMode()`, `isDarkMode` / `isDarkMode$`) | Direct `document.documentElement` theme writes, independent `localStorage['theme']` writes, duplicate dark-mode subjects |
```
#### HttpService (canonical HTTP layer)
- **Location:** project HTTP service (typically under a path such as `http-request/http.service` or as defined in `SRC_STRUCTURE.md`). Inject with `inject(HttpService)` in field initializers.
- **Response shape:** every JSON endpoint returns `ApiResult<T>` or `ApiResultArray<T>`:
```ts
export interface ApiResult<T> {
hasError: boolean;
messages: string[];
result: T;
}
```
- **Methods:** `get<T>`, `post<T>`, `put<T>`, `patch<T>`, `delete<T>` → `Observable<ApiResult<T>>`; `getStream<T>` for SSE (auth headers included); `downloadFile` → `Observable<Blob>`.
- **Options (`HttpOptions`):** `params`, `headers`, `skipToast`, `cooldownMs`, `skipHasErrorCheck`. Prefer these flags instead of swallowing toasts in callers.
- **Auth header:** token is read from `localStorage.getItem('access_token')` and attached as `Authorization: Bearer …`. Callers never set the Bearer token themselves unless adding extra headers via `options.headers`.
- **401 handling:** clears token, dismisses modals, toasts an expiry message, navigates to `/login`. Do not re-implement this.
- **Toasts / errors:** success and error messages from `messages[]` are shown via the service's toast layer (with cooldown). Feature code should not duplicate the same toasts for the same response.
- **Base URLs:** use the service's `baseUrl` / `backendUrl` / `apiUrl` / `imagesUrl`. Do not hard-code hostnames in feature code.
Example:
```ts
private readonly http = inject(HttpService);
loadFaq(): void {
this.http.get<FaqDoc[]>('faq/documents').subscribe({
next: (res) => { /* res.result is typed; hasError already handled unless skipHasErrorCheck */ },
error: () => { /* 401 and toast already handled by HttpService */ },
});
}
```
For long-lived streams use `getStream` and tear down with `takeUntilDestroyed` / `AbortController` (the Observable already aborts on unsubscribe).
#### AuthService + authGuard
- **Location:** auth service + `authGuard` (functional `CanActivateFn`).
- **Login:** always `AuthService.login({ username, password, rememberMe })`. On success it stores `access_token` and `username`, updates `currentUserSubject`, then loads permissions and license. Do not POST to `users/login` through `HttpService` from a component and then write tokens yourself.
- **Session check:** `AuthService.isAuthenticated()` (token present). Route protection: add `canActivate: [authGuard]` (or equivalent) — the guard redirects to `/login` when unauthenticated.
- **User stream:** `currentUserSubject` / subscription for username changes. Prefer converting to a signal at the UI edge (`toSignal`) if the component is signal-driven; do not replace the service's subject with a parallel signal store unless migrating the whole auth layer.
- **Logout / token clear:** go through the same paths the service uses (token removal is also done on 401 inside `HttpService`). Do not scatter `localStorage.removeItem('access_token')` in feature components.
#### ThemeService
- **Location:** theme service. Constructor already calls `initTheme()`.
- **Init:** `initTheme()` reads `localStorage.theme`, applies `data-bs-theme` on `document.documentElement`, then reconciles with backend `GET users/get-dark-mode`. Ensure the service is instantiated once at app bootstrap (e.g. inject it in `App` or a root provider) so init runs; do not call `initTheme` from random components.
- **Toggle:** only `ThemeService.toggleDarkMode()`. It flips local state, writes `localStorage`, applies the attribute, and syncs with `POST users/update-dark-mode`. Never toggle theme by only changing a CSS class or only writing localStorage.
- **Read:** `isDarkMode` (sync getter) or `isDarkMode$` (observable). In new signal-based UI, wrap with `toSignal(this.theme.isDarkMode$, { initialValue: this.theme.isDarkMode })` rather than inventing a second theme signal.
#### Agent rules (binding)
1. **HTTP request** → inject and call `HttpService` only.
2. **Login / is-logged-in / protect a route** → `AuthService` + `authGuard` only.
3. **Change or initialize theme** → `ThemeService` only (`initTheme` / `toggleDarkMode`).
4. Do **not** introduce a competing `ApiClient`, `AuthStore`, or `ThemeStore` that bypasses these services.
5. When wrapping these services for signals/OnPush UI, keep a **single writer**: the existing service remains the source of truth; UI adapts with `toSignal` / `computed`, it does not duplicate token or theme storage.
---
## 2. Angular & Zoneless Coding Standards
### 2.1 Signals first
Use the right primitive for the job:
```
| Need | Use | Not |
| ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| UI / component state | `signal()` | `BehaviorSubject`, plain fields mutated in place |
| Derived read-only state | `computed()` | duplicated state kept in sync by hand, `effect()` that writes derived values |
| Derived **but locally overridable** state (e.g., selected row that resets when the list changes) | `linkedSignal()` | `effect()` that resets a signal |
| Async data read from HTTP | `resource()` / `httpResource()` **if the installed Angular version marks them stable or the project already uses them**; otherwise **`HttpService`** + `toSignal()` / subscribe with `takeUntilDestroyed` | Direct `HttpClient`, manual `subscribe()` that sets fields without teardown |
| Component API | `input()`, `input.required()`, `output()`, `model()`, `viewChild()`, `viewChildren()`, `contentChild()` | `@Input()`, `@Output()`, `@ViewChild()` decorators |
| Dependency injection | `inject()` in field initializers | constructor parameter injection |
| Event streams over time (WebSocket messages, SSE, debounced filters) | RxJS `Observable` at the **edge**, converted with `toSignal()` / `takeUntilDestroyed()` | RxJS for plain UI state |
| Side effects reacting to state (DOM, logging, calling the visualizer) | `effect()` / `afterRenderEffect()` | `effect()` to derive state |
```
> `resource()` and `httpResource()` were experimental in earlier Angular majors. Verify their API stability tag in the installed version before using them; do not assume.
**RxJS is allowed, but only for event streams.** A boolean such as `isDrawerOpen` is a `signal<boolean>`, never a `BehaviorSubject<boolean>`.
#### Single-writer rule
Every piece of state has **exactly one writer**. Expose a read-only view and keep the writable signal private.
```ts
@Injectable({ providedIn: 'root' })
export class VoiceStateStore {
private readonly _voiceState = signal<VoiceState>('idle');
readonly voiceState = this._voiceState.asReadonly();
readonly isMicOpen = computed(() =>
['listening', 'speaking', 'interrupted'].includes(this._voiceState()),
);
/** Only VoiceSessionService may call this. */
_setState(next: VoiceState): void {
this._voiceState.set(next);
}
}
```
- Update objects and arrays **immutably**: `signal.update(list => [...list, item])`. Never mutate the value inside a signal.
- Do not read signals inside `computed()` through `untracked()` to "silence" dependencies; fix the dependency graph instead.
- `effect()` is for side effects only. If you are about to call `.set()` inside an `effect()`, stop and check whether `computed()` or `linkedSignal()` is the right tool.
- Never put a signal write inside a `computed()`.
### 2.2 `ChangeDetectionStrategy.OnPush` is mandatory
**Every component** declares `changeDetection: ChangeDetectionStrategy.OnPush`, with no exceptions (including tiny presentational components, dialogs, and AG Grid cell renderers).
```ts
@Component({
selector: 'app-status-badge',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [AppIconComponent],
templateUrl: './status-badge.component.html',
styleUrl: './status-badge.component.css',
})
export class StatusBadgeComponent {
readonly state = input.required<VoiceState>();
protected readonly label = computed(() => STATE_LABELS[this.state()]);
protected readonly icon = computed(() => STATE_ICONS[this.state()]);
protected readonly glowClass = computed(() => `glow-${this.state()}`);
}
```
The ESLint rule `@angular-eslint/prefer-on-push-component-change-detection` must stay enabled.
### 2.3 Zoneless safety (code must work with AND without Zone.js)
Assume **Zone.js may be absent**. Under zoneless change detection, a view is re-checked only when something Angular knows about changes: a **signal read in the template is written**, an input changes, an event bound in the template fires, `markForCheck()` is called, or the `async` pipe emits.
**Do:**
- Drive every template update through a **signal write**. A WebSocket callback, `setTimeout`, `requestAnimationFrame`, `Promise.then`, or `addEventListener` callback that changes plain fields will **not** update the screen.
- Use `afterNextRender()` / `afterRenderEffect()` for DOM measurement and canvas setup instead of `ngAfterViewInit` timing tricks.
- Use `DestroyRef`, `takeUntilDestroyed()`, and effect cleanups; they do not depend on Zone.js.
- Use the correct provider for the installed major (see §1.5):
```ts
// app.config.ts: Angular 20.2+ / 22 (this repo)
provideZonelessChangeDetection(),
// Angular 18/19 only: provideExperimentalZonelessChangeDetection(),
// Temporary zone phase only (needs "zone.js" in angular.json polyfills):
// provideZoneChangeDetection({ eventCoalescing: true }),
```
**Do not:**
- `import 'zone.js'` anywhere in application code.
- Depend on `NgZone.onStable`, `NgZone.onMicrotaskEmpty`, `NgZone.isStable`, or `ApplicationRef.isStable` for correctness.
- Call `ChangeDetectorRef.detectChanges()` in hot paths. Prefer a signal write; use `markForCheck()` only for a legacy API that cannot be signal-based.
- Rely on `NgZone.run()` to "make it update". It is a no-op for correctness in zoneless mode.
- Use `fakeAsync()` / `tick()` in new tests (they require Zone.js testing patches). Use Vitest fake timers (`vi.useFakeTimers()`) and `await fixture.whenStable()`.
- Write a signal at frame rate (60 Hz) from the audio or render loop. See §3.3.
### 2.4 Standalone components, directives, and pipes
- Everything is standalone. **No NgModules, ever.** Declare dependencies in `imports: []`.
- Never write `standalone: false`. On Angular 19+ do not add the redundant `standalone: true` either (it is the default); on Angular 18 it **must** be written explicitly.
- Lazy-load features and heavy dependencies (`loadChildren`, `loadComponent`, dynamic `import()`), as listed in `DEPENDENCIES.md` §6.5.
### 2.5 Templates, naming, style, and file separation
**Mandatory file separation for every component and page:**
- Always create **three separate files**:
- `*.component.ts` (or `*.page.ts`) — TypeScript class only
- `*.component.html` (or `*.page.html`) — template markup only
- `*.component.css` (or `*.page.css`) — styles only
- Use `templateUrl` and `styleUrl` (singular) in the `@Component` decorator.
- **Never** put `template: \`...\`` or `styles: [\`...\`]` inline inside the TypeScript file.
- **Never** mix HTML or CSS into the `.ts` file.
Example of correct decorator:
```ts
@Component({
selector: 'app-example',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
templateUrl: './example.component.html',
styleUrl: './example.component.css',
})
export class ExampleComponent { ... }
```
Other rules:
- Control flow: `@if`, `@for (item of items(); track item.id)`, `@switch`. **No** `*ngIf`, `*ngFor`, `*ngSwitch`.
- Every `@for` has a stable `track` expression (an id, never the index unless the list is static).
- Templates call **signals and `computed()` values only**. No method calls that compute things, no `Date.now()`, no object/array literals in bindings.
- Prefer `class` and `style` bindings over `ngClass` / `ngStyle`. Use `host: { … }` metadata instead of `@HostBinding` / `@HostListener`.
- File naming (matches `angular.json` schematics): `*.component.ts`, `*.directive.ts`, `*.pipe.ts`, `*.service.ts`; route containers are `*.page.ts`; stores are `*.store.ts`. Selector prefix is `app-` (directives: `app`).
- Class members: `protected readonly` for template-only values, `readonly` for public API, `private` for internals.
- `strict` TypeScript and `strictTemplates` are on. No `any` (use `unknown` and narrow). No non-null assertions (`!`) without a comment explaining why it is safe.
- Prefer **discriminated unions** for events and messages (`VoiceEvent`, `ClientMessage`, `ServerMessage`) and handle them with an exhaustive `switch` ending in `assertNever`.
- Style with **Tailwind utilities** and the design tokens in `src/styles/theme.css`. Use the `glass`, `glass-strong`, and `glow-*` utilities. No component CSS files unless unavoidable, and no hard-coded hex colors; use tokens.
- Use **logical** properties (`ms-*`, `me-*`, `ps-*`, `pe-*`, `start-*`, `end-*`) so RTL layouts work. Never `ml-*`, `pr-*`, `left-*`, `right-*` for layout direction.
### 2.6 Icons
Icons come **only** from `shared/ui/icon` (`<app-icon name="mic" />`) backed by the registry `icons.ts` (package `@lucide/angular`). Never import Lucide directly in a feature component. To add an icon, add it to the registry.
### 2.7 Accessibility baseline
- Interactive elements are real `<button>` / `<a>` elements with accessible names.
- Voice state changes are announced via CDK `LiveAnnouncer` or an `aria-live="polite"` region.
- Drawers and dialogs use CDK `Overlay` / `Dialog` with focus trap, `Esc` to close, and focus restoration.
- Never convey state by color alone: pair it with icon + text.
- Honor `prefers-reduced-motion` in animations and in the visualizer presets.
---
## 3. Web Audio & Canvas Performance Rules
### 3.1 Thread and zone separation
```
| Code | Runs on | Hard rules |
| ----------------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `src/assets/worklets/*.js` | Audio render thread | No allocation in `process()`, no `console.*`, no DOM, no `await`, communicate only via `port.postMessage` |
| `core/audio/*`, `core/websocket/*` | Main thread, **outside** Angular zone | No per-frame signal writes; re-enter Angular only by writing a signal on a meaningful, low-frequency change |
| `core/audio/visualizer/*` | Main thread, **outside** Angular zone, `requestAnimationFrame` | **Never** writes signals, never triggers change detection |
| Stores, `VoiceSessionService`, components | Angular domain | Signals, ~1–5 Hz updates |
```
**Never process audio samples on the main thread.** Capture, framing, quantization, jitter buffering, and sample-rate conversion happen in the worklets.
### 3.2 AudioWorklet rules
- The processors live at `src/assets/worklets/pcm-capture-processor.js` and `src/assets/worklets/pcm-playback-processor.js` (see §1.5). Each starts with `// @ts-check` and uses types from `@types/audioworklet`.
- In `process()`: **preallocate** all buffers in the constructor; reuse them; never create arrays, objects, closures, or strings per call.
- Capture emits fixed **20 ms Int16 PCM frames** and sends them with a **transfer list**: `this.port.postMessage(buffer, [buffer])`. Never copy large buffers.
- Playback owns a ring/jitter buffer, outputs **silence on underrun**, supports an O(1) `flush`, and reports `started`, `drained`, `underrun`.
- Load modules with a **cache-busting version** and a base-href-aware URL:
```ts
const v = inject(APP_CONFIG).workletVersion;
await ctx.audioWorklet.addModule(
new URL(`assets/worklets/pcm-capture-processor.js?v=${v}`, document.baseURI).href,
);
```
- Create the `AudioContext` **only after a user gesture** (the orb click), via the holder in `core/audio/audio-context.provider.ts`. Never at app startup. Resume it if `state === 'suspended'`.
- Request the microphone with `echoCancellation`, `noiseSuppression`, `autoGainControl`, and `channelCount: 1`. Echo cancellation is mandatory because barge-in depends on it.
- Never assume the requested sample rate: read `ctx.sampleRate` and resample in the worklet if it differs from the wire format.
### 3.3 Audio levels: the `AudioLevelBus` exception
Per-frame levels and frequency bands are written into the mutable **`AudioLevelBus`** (`core/audio/audio-level-bus.ts`) and read directly by the visualizer loop.
- **Never** create a `signal` that is updated every animation frame or every audio frame. In zoneless mode that schedules change detection at 60 Hz.
- If a UI element needs a level (e.g., a mic meter), expose a **throttled** (~10 Hz) signal for that element only. Never bind it to the canvas.
- Use `getByteFrequencyData(preallocatedUint8Array)`; never allocate arrays in the loop.
### 3.4 Bypassing Angular change detection for 60 FPS loops
**Any** `requestAnimationFrame` loop, Three.js render loop, canvas drawing loop, high-frequency timer, or `ResizeObserver`/`IntersectionObserver` callback MUST be created inside `NgZone.runOutsideAngular()`.
```ts
@Injectable()
export class VisualizerEngine {
private readonly zone = inject(NgZone);
private readonly destroyRef = inject(DestroyRef);
private readonly bus = inject(AudioLevelBus);
private rafId = 0;
private visualizer?: Visualizer;
private target = STATE_PRESETS.idle;
start(canvas: HTMLCanvasElement): void {
this.zone.runOutsideAngular(() => {
void this.boot(canvas); // renderer creation + loop start
});
this.destroyRef.onDestroy(() => this.dispose());
}
/** Called from an effect() on voiceState changes (~1–5 Hz). Cheap: swaps a preset object. */
applyState(state: VoiceState): void {
this.target = STATE_PRESETS[state];
}
private readonly loop = (t: number): void => {
this.rafId = requestAnimationFrame(this.loop); // already outside the zone
this.visualizer?.render(t, this.bus, this.target); // reads the bus; no signal reads or writes
};
private async boot(canvas: HTMLCanvasElement): Promise<void> {
const { ThreeOrbVisualizer } = await import('./three-orb.visualizer');
this.visualizer = await ThreeOrbVisualizer.create(canvas);
this.rafId = requestAnimationFrame(this.loop);
}
private dispose(): void {
cancelAnimationFrame(this.rafId);
this.visualizer?.dispose();
}
}
```
Rules for the loop:
1. Start it **outside** the zone (a harmless no-op under zoneless, which keeps the code portable).
2. **No** `new` objects, arrays, closures, or strings inside the per-frame function.
3. State reaches the loop through an `effect()` that runs on state **changes** and updates a plain target object; the loop eases toward it. The loop itself never reads signals.
4. Cap `devicePixelRatio` at 2; resize through a `ResizeObserver` created outside the zone.
5. **Pause** when the tab is hidden (`visibilitychange`) or the canvas is off-screen (`IntersectionObserver`).
6. Honor `prefers-reduced-motion` by choosing a calmer preset.
7. Provide a **Canvas 2D fallback** that implements the same `Visualizer` interface (WebGL missing or `webglcontextlost`).
8. Import Three.js lazily (`await import('three')`) and with **named imports** only.
WebSocket `onmessage`, worklet `port.onmessage`, SSE callbacks, and `AnalyserNode` polling timers also run outside the zone. Re-enter Angular only by writing a signal when something human-visible changes (state transition, transcript partial, status).
### 3.5 Cleanup & destruction lifecycle (mandatory)
Every resource that is created must have a release path registered **at the moment of creation**.
```
| Resource | Release |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `requestAnimationFrame` handle | `cancelAnimationFrame(id)` |
| Three.js scene | `geometry.dispose()`, `material.dispose()`, every `texture.dispose()`, `renderer.dispose()`, `renderer.forceContextLoss()`, remove event listeners, null references |
| `AudioContext` | Disconnect nodes, `await ctx.close()` |
| `AudioWorkletNode` | `node.port.onmessage = null`, `node.port.close()`, `node.disconnect()` |
| `MediaStream` (microphone) | `stream.getTracks().forEach(t => t.stop())` (this turns off the browser's mic indicator) |
| `AnalyserNode`, `MediaStreamAudioSourceNode` | `disconnect()` |
| `WebSocket` | Remove handlers, `close(1000)`, clear heartbeat and reconnect timers |
| `ResizeObserver`, `IntersectionObserver`, `MutationObserver` | `disconnect()` |
| DOM listeners (`visibilitychange`, `storage`, `devicechange`) | `removeEventListener` (or register through `fromEvent` + `takeUntilDestroyed`) |
| RxJS subscriptions | `takeUntilDestroyed(this.destroyRef)` (never a bare `subscribe()` without teardown) |
| HTTP uploads / SSE | `AbortController` or unsubscribe on destroy; cancel in-flight uploads when their owner is destroyed |
| Timers (`setTimeout`, `setInterval`) | `clearTimeout` / `clearInterval` |
| CDK `OverlayRef` / `DialogRef` | `dispose()` / `close()` |
```
**Which hook to use**
- **Preferred:** `inject(DestroyRef).onDestroy(() => …)` right next to the creation code.
- Inside an `effect()` that creates something per run: `effect((onCleanup) => { …; onCleanup(() => release()); })`.
- `ngOnDestroy` is acceptable when a class already implements `OnDestroy`; do not add it just to call one release.
- **`untracked()` is not a cleanup mechanism.** It only prevents signal reads from becoming dependencies. Never present it as lifecycle handling.
- Cleanup must be **idempotent** (safe to call twice) and must not throw.
### 3.6 State machine and barge-in rules
- `voiceState` is written **only** by `VoiceSessionService` (`features/voice-agent/services/`), driven by the data table in `voice-transitions.ts`. Never call the store's mutators from components.
- Unlisted events in the current state are **ignored and logged**, never thrown.
- On `BARGE_IN`: **flush local playback first**, then notify the server (`interrupt` with `playedMs`). Never wait for the network.
- Agent audio frames carry a `turnId`; frames from a stale turn are dropped by `audio-stream.handler.ts`.
- `interrupted` is transient and resolves to `listening` after `FLUSH_DONE`.
- Do not introduce new states or transitions without updating `ARCHITECTURE.md` §2 in the same change.
### 3.7 Protocol and transport rules
- Use the `RealtimeTransport` abstraction (`core/websocket/realtime-transport.ts`). Feature code never touches `WebSocket` directly.
- Audio travels in **binary frames** with the documented header (`ARCHITECTURE.md` §5.2); control messages are JSON, typed by `ClientMessage` / `ServerMessage`. Set `binaryType = 'arraybuffer'`.
- Authentication ticket goes in the first JSON message, **never in the URL**.
- Malformed frames are counted and dropped, never thrown.
---
## 4. FAQ Knowledge Base & File Handling Guidelines
### 4.1 Layer separation (strict)
```text
UI components (features/faq-manager/components/*)
│ inputs/outputs only
▼
FaqStore (signals) ◄──── FaqIngestionService (orchestration)
│
┌─────────────┼───────────────────────┐
▼ ▼ ▼
FileValidatorService CsvParserService FaqApiService / IngestionEventsService
(UX validation) (preview only) (HTTP + status events to the backend)
│
▼
Backend: parsing, chunking, embedding, vector index (RAG)
```
- **UI components never call HTTP, never know about chunks, embeddings, or vector indexes.** They read `FaqStore` signals and emit events.
- **The client never performs embedding, chunking, or retrieval.** It uploads files and edits Q&A pairs; the backend owns indexing and RAG synchronization.
- All FAQ HTTP traffic goes through **`HttpService`** (via `FaqApiService` / `FaqIngestionService`). No feature injects `HttpClient` directly.
- `FaqIngestionService` is the only orchestrator of `validate → preview → upload → track status`.
- Status flows from the server through `IngestionEventsService` (SSE via `HttpService.getStream` or control messages) into `FaqStore` signals: `uploading → indexing → active | error`. Status is **never** inferred on the client.
- `features/faq-manager` must not import from `features/voice-agent` (and vice versa). Shared concerns go in `core/` or `shared/`.
- The voice session learns which documents to use only through `activeDocumentIds` in the session configuration (from `FaqStore.activeDocuments`), not by reaching into FAQ components.
### 4.2 PapaParse pre-parsing (CSV)
- **Lazy-load:** `const Papa = (await import('papaparse')).default;` inside `CsvParserService`. Never import it at the top of a component.
- **Preview** with `Papa.parse(file, { header: true, preview: N, skipEmptyLines: 'greedy', dynamicTyping: false })`, with `N` defaulting to 50.
- **Count and validate large files** with chunked streaming (`chunk` or `step`) so memory stays bounded. **Do not use `worker: true`** (see §1.5).
- Treat every cell as a **string**; never trust types, never `eval`. Strip a UTF-8 BOM, tolerate `\r\n`, and let PapaParse auto-detect the delimiter.
- Auto-detect question and answer columns with `csv-column-detect.ts`, and let the user remap them in `upload-preview-table`.
- Report row problems with `CsvRowError` (`MISSING_QUESTION`, `MISSING_ANSWER`, `TOO_LONG`, `MALFORMED`). A row error is a **warning in the preview**, not a crash.
- **The parsed rows are for preview only.** Upload the **original file** (`FormData`); the server re-parses and is the source of truth. Do not send client-parsed JSON as the dataset.
- Never log file contents or cell values (they may contain personal data).
### 4.3 Validation of all file types (client side = UX only)
- Check extension, MIME type, size limit, and **magic bytes** via `file-validator.service.ts` and `file-signatures.ts` (PDF `%PDF`; DOCX is a ZIP, `PK\x03\x04`; JSON/CSV are text).
- PDF and DOCX are **not parsed in the browser by default**. Optional previews (`pdfjs-dist`, `mammoth`) require explicit approval and a dynamic import (`DEPENDENCIES.md` §3.5).
- **Never treat client validation as a trust boundary.** The server must revalidate; write UI copy accordingly.
- Rejected files produce a typed `FaqDocumentError` with a user-readable message and a `retryable` flag.
### 4.4 Upload, status, and Q&A editing
- Upload through **`HttpService`** (or `FaqApiService` built on it). If upload progress is required, extend `HttpService` with a progress-capable method rather than injecting raw `HttpClient` in a feature. Write `progress` into the document's signal state. Cancel with unsubscribe/`AbortController` when the owner is destroyed.
- The document row has one writer (`FaqStore`). Use immutable `update()` calls keyed by `id`.
- Q&A edits are **optimistic with rollback**: apply to `FaqStore`, send the request, roll back and toast on failure. A manual edit sets `overridden: true` so re-ingestion does not overwrite it.
- **AG Grid** (`ag-grid-angular`, `ag-grid-community` on identical versions):
- Register modules once in `grid/register-grid-modules.ts`; apply the theme through the JS theme API (`grid/qa-grid.theme.ts`), not CSS imports.
- The grid is wrapped by `QaGridComponent` (signal inputs, outputs only). Feature code never touches the grid API outside that component.
- Cell renderers are OnPush standalone components in `grid/cell-renderers/`.
- Never trigger row-model refreshes at frame rate; batch updates with `applyTransaction`.
- The grid and PapaParse chunk must stay **out of the initial bundle** (lazy routes + dynamic imports).
---
## 5. Navigation Guide: where things go
```
| You are adding… | Put it in… |
| ----------------------------------------------------------- | ------------------------------------------------------------------------- |
| A new **page** (routed view) | `src/app/pages/<page-name>/` (e.g. `src/app/pages/faq-manager/`) |
| A new voice UI element (button, overlay, badge) | `features/voice-agent/components/<name>/` |
| Voice transition, guard, or side effect | `features/voice-agent/services/voice-transitions.ts` / `voice-effects.ts` |
| Anything that touches `AudioContext`, mic, or worklet nodes | `core/audio/` |
| The orb, shaders, canvas fallback | `core/audio/visualizer/` |
| WebSocket, framing, reconnect, heartbeat | `core/websocket/` |
| Global signals store, storage, telemetry, notifications | `core/services/` |
| Shared types used by core and features | `core/models/` |
| FAQ UI components | `features/faq-manager/components/<name>/` |
| FAQ state, upload logic, parsing, API | `features/faq-manager/services/` |
| Reusable button/badge/dialog/spinner/pipe/directive | `shared/ui`, `shared/pipes`, `shared/directives` |
| AudioWorklet script | `src/assets/worklets/` |
| Design tokens / Tailwind utilities | `src/styles/theme.css` / `src/styles/utilities.css` |
| HTTP calls to the API | **Use existing `HttpService` only** — do not add a parallel client |
| Login, auth check, route guard | **Use existing `AuthService` + `authGuard` only** |
| Theme init / dark-mode toggle | **Use existing `ThemeService` only** (`initTheme`, `toggleDarkMode`) |
```
**Pages rule (binding):**
- Every new page **must** live under `src/app/pages/<page-name>/`.
- A page folder contains at minimum:
- `<page-name>.page.ts`
- `<page-name>.page.html`
- `<page-name>.page.css`
- Do **not** place pages inside `features/` or any other location.
**Import boundaries** (enforced by ESLint `no-restricted-imports`):
```text
shared <- core <- features
```
- `shared` imports nothing from `core` or `features`.
- `core` imports from `shared` only, never from `features`.
- A feature never imports another feature.
- `core/audio` and `core/websocket` import no UI code (no components, no CDK), so they remain testable without a DOM.
- Use `@core/…`, `@features/…`, `@shared/…` aliases; never deep relative paths that cross layer boundaries (`../../../core/…`).
---
## 6. Security, Privacy, and Reliability
- Use `wss://` and `https://` outside local development. Authentication tickets go in message bodies or headers, **never in URLs**.
- **Never log or persist** raw audio, transcripts, uploaded file contents, or tokens. Telemetry carries counts, durations, and error codes only.
- Auth tokens (`access_token`) and username are managed **only** by `AuthService` / `HttpService` (including 401 cleanup). Theme preference may live in `localStorage` **only** via `ThemeService`. Other preferences go through `StorageService` if present. Never tokens, transcripts, or file data in ad-hoc storage.
- Never use `innerHTML`, `bypassSecurityTrust*`, or `eval`/`new Function` with user, server, or model-generated text. Transcripts and Q&A are rendered as text.
- Every error path is handled: microphone denied, `AudioContext` suspended, worklet load failure, socket drop mid-turn, token expiry, WebGL context loss, upload failure. Map to `VoiceError` / `FaqDocumentError` and tell the user what to do next.
- API user-visible messages and 401 handling are owned by `HttpService` (toasts + redirect). For non-HTTP app errors, use the project notification layer; do not swallow errors or only `console.log` them.
- Protect authenticated routes with `authGuard`. Do not implement a second guard that bypasses `AuthService.isAuthenticated()`.
---
## 7. Testing Rules
- **Colocate** `*.spec.ts` next to the file. The test runner is Vitest through the Angular builder.
- Pure logic gets pure tests: `voice-transitions.ts` (table-driven, including ignored events), `frame-codec.ts` (golden byte arrays), `pcm-utils.ts`, `connection.machine.ts`, `reconnect-policy.ts`, `csv-column-detect.ts`, `file-signatures.ts`.
- `VoiceSessionService` is tested with fake `AudioEngine` and fake `RealtimeTransport`, including barge-in races and stale `turnId` frames.
- Configure tests for zoneless (`provideZonelessChangeDetection()`); await `fixture.whenStable()`; do not use `fakeAsync`.
- Components are tested through their **signal inputs and rendered output**, not private members.
- A change to the audio path or visualizer must keep the performance assertion: **zero change-detection ticks per second** while the orb animates (see `ARCHITECTURE.md` §3.7).
- Never weaken, skip (`xit`, `.skip`), or delete a test to get green. Fix the code or ask.
---
## 8. Anti-Pattern Table (never write these)
```
| Forbidden | Use instead |
| ------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| `BehaviorSubject<boolean>` for UI state | `signal<boolean>()` |
| `@Input()` / `@Output()` / `@ViewChild()` decorators | `input()` / `output()` / `viewChild()` |
| Component without `OnPush` | `changeDetection: ChangeDetectionStrategy.OnPush` |
| `*ngIf` / `*ngFor` | `@if` / `@for … track` |
| NgModule, `standalone: false` | Standalone component with `imports: []` |
| Inline `template:` or `styles:` in `@Component` | Separate `.html` + `.css` files with `templateUrl` + `styleUrl`|
| Putting a page anywhere except `src/app/pages/<name>/` | Always `src/app/pages/<page-name>/` |
| `setInterval`/`requestAnimationFrame` started inside the zone for a render loop | `NgZone.runOutsideAngular(...)` |
| Signal updated every frame | `AudioLevelBus` (machine reads) + throttled signal (UI reads) |
| Audio sample processing or resampling on the main thread | `AudioWorklet` |
| `new AudioContext()` at startup | Lazy creation on the first user gesture |
| Subscribing without teardown | `takeUntilDestroyed()` / `DestroyRef` |
| `untracked()` described as cleanup | `DestroyRef.onDestroy()` / `effect` `onCleanup` |
| `effect()` that derives state | `computed()` / `linkedSignal()` |
| Mutating an array or object held in a signal | `signal.update()` with a new value |
| `provideExperimentalZonelessChangeDetection()` on Angular 22 | `provideZonelessChangeDetection()` |
| Importing `lucide-angular` or any Lucide package directly in a feature | `<app-icon>` via `shared/ui/icon` |
| `Papa.parse(file, { worker: true })` | `preview` + chunked streaming |
| Uploading client-parsed rows as the dataset | Upload the original file; parse client-side for preview only |
| UI component calling backend RAG/vector endpoints | Go through `FaqIngestionService` / `FaqApiService` |
| Feature importing another feature | Move shared code to `core/` or `shared/` |
| Adding a library not in `DEPENDENCIES.md` | Ask first, justify, update the doc |
| `ml-*` / `pr-*` / `left-*` / `right-*` for direction | `ms-*` / `pe-*` / `start-*` / `end-*` |
| `any`, unchecked `!`, swallowed errors, `console.log` for errors | Narrow types; `NotificationService` + `LoggerService` |
| Direct `HttpClient` / bare `fetch` for API routes | `HttpService.get/post/put/patch/delete/getStream/downloadFile` |
| Hand-rolled login POST + writing `access_token` yourself | `AuthService.login()`; protect routes with `authGuard` |
| Reading/writing theme or `data-bs-theme` outside ThemeService | `ThemeService.initTheme()` / `toggleDarkMode()` / `isDarkMode` |
| Second HTTP client, auth store, or theme store that bypasses the above | Extend or wrap the existing services; single writer |
```
---
## 9. Mandatory Code-Generation Checklist
**Before returning code, verify every applicable item. If an item fails, fix the code. If you cannot fix it, say so explicitly in your reply. Never claim a check passed that you did not actually perform.**
### 9.1 Core checklist (always)
- [ ] **OnPush:** Is `changeDetection: ChangeDetectionStrategy.OnPush` present on every component I created or touched?
- [ ] **Signals:** Is UI state in `signal()` / `computed()` / `linkedSignal()` (not `BehaviorSubject`, not mutable fields), and do all template updates come from signal writes, so the code works **without Zone.js**?
- [ ] **60 FPS loops:** Is every `requestAnimationFrame` / Three.js / canvas loop (and every high-frequency observer) created inside `NgZone.runOutsideAngular()`, with **no signal read or written per frame**?
- [ ] **Cleanup:** Is every subscription, `AudioContext`, `AudioWorkletNode`, `MediaStream` track, `WebSocket`, observer, timer, overlay, and Three.js object (geometry, material, texture, renderer) released through `DestroyRef` / effect cleanup / `ngOnDestroy`?
- [ ] **Paths:** Does every file path match `./docs/SRC_STRUCTURE.md`, and do the imports respect `shared <- core <- features`?
- [ ] **Separate files:** Does every component/page have separate `.ts` + `.html` + `.css` files (no inline template or styles)?
- [ ] **Pages location:** Are all new pages placed under `src/app/pages/<page-name>/`?
### 9.2 Angular conventions
- [ ] Standalone only (no NgModule, no `standalone: false`; flag omitted on Angular 19+, present on 18).
- [ ] `input()` / `output()` / `model()` / `viewChild()` / `inject()` used instead of decorators and constructor injection.
- [ ] `@if` / `@for` (with `track`) / `@switch`; templates call only signals/computeds.
- [ ] Zoneless provider matches the installed Angular major (§1.5); no reliance on `NgZone.onStable` or `detectChanges()` in hot paths.
- [ ] One writer per state; public API exposes `asReadonly()`.
- [ ] No `effect()` used to derive state; no signal writes inside `computed()`.
- [ ] Exhaustive `switch` on discriminated unions (`assertNever`).
- [ ] Strict typing: no `any`, no unexplained `!`.
### 9.3 Audio, canvas, and transport
- [ ] No audio-sample processing on the main thread; worklet code allocates nothing in `process()` and uses transferables.
- [ ] Worklet files are in `src/assets/worklets/` and loaded with a version query.
- [ ] `AudioContext` is created after a user gesture and resumed when suspended.
- [ ] Per-frame levels go through `AudioLevelBus`; UI meters use a throttled signal.
- [ ] Barge-in flushes playback locally first; stale `turnId` frames are dropped.
- [ ] Visualizer pauses when hidden, caps DPR at 2, honors `prefers-reduced-motion`, and has a fallback.
- [ ] `three` is lazily imported with named imports; shaders are imported as text from `core/audio/visualizer/shaders/`.
### 9.4 FAQ and file handling
- [ ] PapaParse is lazily imported, used with `preview`/chunking (never `worker: true`), and parsed rows are used for preview only.
- [ ] The **original file** is what gets uploaded; the client does no embedding, chunking, or retrieval.
- [ ] UI components do not call HTTP or backend RAG/vector APIs; they go through the store and `FaqIngestionService`.
- [ ] File validation includes size, extension/MIME, and magic bytes; no file contents are logged.
- [ ] Grid modules are registered once; AG Grid is accessed only through `QaGridComponent`.
### 9.5 Project hygiene
- [ ] Only approved libraries from `DEPENDENCIES.md`; icons through `shared/ui/icon`.
- [ ] Tailwind tokens and logical properties used; no hard-coded colors; no `ml-*`/`pr-*`.
- [ ] Accessible names, keyboard support, and `aria-live` for state changes.
- [ ] Error paths handled and surfaced; no secrets, tokens, audio, or transcripts logged or persisted.
- [ ] Tests added or updated (pure logic first); none skipped or deleted.
- [ ] Any change to states, protocol, folders, or dependencies is reflected in the matching `./docs/*.md` file in the same change.
- [ ] **Http / Auth / Theme:** all API calls go through `HttpService`; login and session via `AuthService` + `authGuard`; theme init/toggle via `ThemeService` only (no parallel clients or direct token/theme storage).
---
## 10. Response Protocol for Agents
1. **Before code:** list the files you will create/edit (with paths from `SRC_STRUCTURE.md`) and the rules that apply, in two to five lines.
2. **Code:** complete files or clear diffs. No `// ...rest of code`, no pseudo-code, no TODO placeholders for core logic.
3. **After code:** a short **Checklist result** (§9). List only items that were *not* satisfied, plus any assumption you made. If all passed, say so in one line.
4. **Ask instead of guessing** when: a doc is missing, docs conflict, a new dependency is needed, a state or protocol change is implied, the backend contract is unknown, or the Angular version is unclear.
5. **Keep changes minimal and focused.** Mention (do not perform) unrelated cleanups.
6. **Never** weaken a rule in this file to make a request easier. Explain the conflict and offer a compliant option.
---
## 11. Reference Templates
### 11.1 New component (separate files required)
**`example.component.ts`**
```ts
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
@Component({
selector: 'app-example',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
templateUrl: './example.component.html',
styleUrl: './example.component.css',
})
export class ExampleComponent {
readonly items = input.required<readonly { id: string; label: string }[]>();
readonly selected = output<string>();
protected readonly emptyText = computed(() => 'Nothing here yet.');
}
```
**`example.component.html`**
```html
@if (items().length) {
<ul class="space-y-2">
@for (item of items(); track item.id) {
<li class="glass rounded-xl px-3 py-2">
<button type="button" (click)="selected.emit(item.id)">{{ item.label }}</button>
</li>
}
</ul>
} @else {
<p class="text-slate-400">{{ emptyText() }}</p>
}
```
**`example.component.css`**
```css
/* Prefer Tailwind utilities in the template.
Add component-specific styles here only when truly necessary. */
```
### 11.2 New page (must live under `src/app/pages/`)
**Folder:** `src/app/pages/my-page/`
**`my-page.page.ts`**
```ts
import { ChangeDetectionStrategy, Component } from '@angular/core';
@Component({
selector: 'app-my-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
templateUrl: './my-page.page.html',
styleUrl: './my-page.page.css',
})
export class MyPage {
// page logic
}
```
**`my-page.page.html`** + **`my-page.page.css`** — same separation rules as components.
### 11.3 Resource with guaranteed cleanup
```ts
@Injectable({ providedIn: 'root' })
export class ExampleResourceService {
private readonly destroyRef = inject(DestroyRef);
private socket?: WebSocket;
open(url: string): void {
this.close();
this.socket = new WebSocket(url); // created outside the zone by the caller
this.socket.binaryType = 'arraybuffer';
this.destroyRef.onDestroy(() => this.close()); // release registered at creation time
}
close(): void { // idempotent, never throws
if (!this.socket) return;
this.socket.onmessage = null;
this.socket.onclose = null;
try { this.socket.close(1000); } catch { /* already closed */ }
this.socket = undefined;
}
}
```
### 11.4 `effect()` that owns a resource
```ts
constructor() {
effect((onCleanup) => {
const state = this.voiceState(); // dependency
const handle = this.thing.subscribeTo(state); // per-run resource
onCleanup(() => handle.release()); // released on re-run and on destroy
});
}
```
---
## 12. Maintaining This File
- Treat this file like code: change it through a pull request, in the same PR as any architecture change.
- When `ARCHITECTURE.md`, `SRC_STRUCTURE.md`, or `DEPENDENCIES.md` change, update §1.5 (known deltas), §5 (navigation), and §8 (anti-patterns) accordingly.
- When Angular is upgraded, re-verify §1.5 (zoneless provider name, `standalone` default, `resource()` stability) and §2.3.
- Keep the checklist in §9 short enough to be followed every time. Add an item only when a real defect has slipped through twice.
+5
View File
@@ -0,0 +1,5 @@
{
"plugins": {
"@tailwindcss/postcss": {}
}
}
+13 -1
View File
@@ -19,6 +19,11 @@
{
"glob": "**/*",
"input": "public"
},
{
"glob": "**/*",
"input": "src/assets",
"output": "assets"
}
],
"styles": [
@@ -65,13 +70,20 @@
"builder": "@angular/build:extract-i18n"
},
"test": {
"builder": "@angular/build:karma",
"builder": "@angular/build:unit-test",
"options": {
"tsConfig": "tsconfig.spec.json",
"runner": "vitest",
"buildTarget": "faq-chatbot:build:development",
"assets": [
{
"glob": "**/*",
"input": "public"
},
{
"glob": "**/*",
"input": "src/assets",
"output": "assets"
}
],
"styles": [
+909
View File
@@ -0,0 +1,909 @@
# ARCHITECTURE.md — Voice-to-Voice FAQ Web Application
> **Status:** Draft v1 · **Audience:** frontend engineers, tech leads, backend integrators
> **Stack:** Angular 18/19+ (Standalone, Signals, OnPush, zoneless-ready) · Tailwind CSS · Angular CDK · Lucide Angular · Web Audio API / AudioWorklet · Three.js · WebSocket (WebRTC optional)
---
## Table of Contents
1. [System Overview & High-Level Architecture](#1-system-overview--high-level-architecture)
2. [State Machine Specification](#2-state-machine-specification)
3. [Audio Pipeline & Performance Strategy](#3-audio-pipeline--performance-strategy)
4. [Folder Structure & Component Breakdown](#4-folder-structure--component-breakdown)
5. [Data Contracts & Types](#5-data-contracts--types)
6. [Cross-Cutting Concerns](#6-cross-cutting-concerns)
7. [Architecture Decision Records (summary)](#7-architecture-decision-records-summary)
8. [Open Questions](#8-open-questions)
9. [Next Documents](#9-next-documents)
---
## 1. System Overview & High-Level Architecture
### 1.1 Goals and non-goals
| Goal | Target |
|---|---|
| Natural, full-duplex conversation with an AI FAQ agent | Barge-in supported at any time |
| Mouth-to-ear perceived latency (user stops talking → first audio back) | **< 800 ms p50**, < 1.5 s p95 (network + backend dependent) |
| Visualizer smoothness | Steady 60 FPS, **zero Angular change-detection cycles** from the render loop |
| Main-thread safety | No audio sample processing on the main thread |
| Knowledge-base management | Upload → validate → index → inspect/edit Q&A, with live status |
| Future-proofing | Works identically with Zone.js today and zoneless tomorrow |
**Non-goals (v1):** multi-party calls, client-side speech recognition/TTS models, offline mode, mobile-native wrappers.
### 1.2 Architectural principles
1. **Three execution domains, strict boundaries.** (a) *Audio render thread* (AudioWorklet), (b) *main thread outside Angular* (canvas/WebGL loop, socket I/O hot path), (c) *Angular reactive domain* (UI state, signals, templates). Data crosses domains only through explicit, narrow channels.
2. **Signals for state that humans read; plain mutable buffers for state that machines read.** A value that changes 60 times per second and is consumed only by a shader is *not* a signal.
3. **Transport is dumb, the state machine is smart.** The WebSocket service emits typed events; only `VoiceSessionService` decides what they mean.
4. **One writer per state.** Each signal has exactly one service that writes it and exposes a read-only view (`asReadonly()`).
5. **Everything disposable.** Every `AudioContext`, `MediaStream`, `WebSocket`, `WebGLRenderer`, and `requestAnimationFrame` handle is released through `DestroyRef`.
### 1.3 High-level data flow
```mermaid
flowchart LR
subgraph Device["User Device"]
MIC["Microphone"]
SPK["Speakers"]
end
subgraph Browser["Browser"]
subgraph AudioThread["Audio Render Thread (AudioWorklet)"]
CAP["capture-processor<br/>Float32 to Int16 PCM, 20 ms frames"]
PLAY["playback-processor<br/>ring buffer / jitter buffer"]
end
subgraph MainOutside["Main Thread - outside Angular zone / CD"]
ACTX["AudioContext graph<br/>MediaStreamSource, AnalyserNode in/out"]
WS["WebSocketService<br/>binary audio + JSON control"]
VIS["VisualizerEngine<br/>Three.js orb, rAF loop"]
BUS["AudioLevelBus<br/>mutable Float32 snapshot"]
end
subgraph NG["Angular Reactive Domain (Signals, OnPush)"]
SESS["VoiceSessionService<br/>state machine orchestrator"]
VSTATE["VoiceStateStore<br/>voiceState, activeSession, transcript"]
FAQ["FaqStore<br/>faqDocuments, qaPairs, filters"]
UI["Components<br/>VoiceAgent, FaqDrawer, FaqGrid"]
end
end
subgraph Backend["Backend"]
GW["Realtime Gateway<br/>auth, session, VAD"]
RAG["RAG Retriever<br/>vector index"]
LLM["LLM"]
TTS["TTS / STT"]
ING["Ingestion API<br/>parse, chunk, embed"]
end
MIC --> ACTX
ACTX -->|"MediaStreamSource"| CAP
CAP -->|"postMessage (transfer ArrayBuffer)"| WS
WS <-->|"wss: PCM frames + control JSON"| GW
GW --> TTS
TTS --> LLM
LLM <--> RAG
GW -->|"PCM reply frames"| WS
WS -->|"postMessage (transfer)"| PLAY
PLAY --> ACTX
ACTX --> SPK
ACTX -->|"getByteFrequencyData into preallocated array"| BUS
BUS -->|"read each frame"| VIS
WS -->|"typed control events"| SESS
SESS -->|"signal.set()"| VSTATE
VSTATE -->|"voiceState read by effect"| VIS
VSTATE --> UI
FAQ --> UI
UI -->|"upload / edit"| ING
ING -->|"status events (SSE or WS)"| FAQ
ING --> RAG
```
### 1.4 Component responsibilities at a glance
| Component | Domain | Responsibility | Writes | Reads |
|---|---|---|---|---|
| `AudioEngineService` | Main (outside zone) | Owns `AudioContext`, mic stream, worklet nodes, analysers | `AudioLevelBus` | — |
| `capture-processor` | Audio thread | Downmix, resample (if needed), quantize to Int16, frame to 20 ms | — | mic samples |
| `playback-processor` | Audio thread | Jitter buffering, underrun handling, instant flush on barge-in | — | PCM frames |
| `WebSocketService` | Main (outside zone) | Connection lifecycle, reconnect, framing, heartbeat | event streams | PCM from worklet |
| `VoiceSessionService` | Angular | The **only** writer of `voiceState`; applies transition table | `VoiceStateStore` | WS events, engine events |
| `VisualizerEngine` | Main (outside zone) | Three.js scene + rAF loop; no Angular imports in the hot path | canvas | `AudioLevelBus`, state snapshot |
| `FaqStore` | Angular | Document list, Q&A pairs, filters, optimistic edits | signals | ingestion events |
| `FaqIngestionService` | Angular | Validation, PapaParse, upload with progress, status subscription | `FaqStore` | HTTP/SSE |
---
## 2. State Machine Specification
### 2.1 States
| State | Meaning | Mic capture | Playback | Visualizer behaviour |
|---|---|---|---|---|
| `idle` | Session connected (or ready); nobody speaking | Muted at the worklet (stream stays warm) | Empty | Slow ambient breathing, cool tint |
| `listening` | User is speaking / mic is open and streaming | **Streaming** | Empty | Orb deforms with **input** level |
| `processing` | User finished; backend is thinking (STT → RAG → LLM → TTS first byte) | Paused (optionally keep VAD running) | Empty | Rotating / pulsing "thinking" pattern, level-independent |
| `speaking` | Agent audio is playing | Streaming to server **for barge-in detection only** (AEC on) | **Playing** | Orb deforms with **output** level |
| `interrupted` | User barged in during `speaking`; playback is being flushed | Streaming | **Flushing** | Brief collapse/flash animation (~150–250 ms) |
> **Design note — `interrupted` is transient.** It is a real state (so the UI, analytics, and tests can observe it), but it always resolves to `listening` automatically once the flush is acknowledged locally. It never waits on the network.
### 2.2 Events
| Event | Source | Description |
|---|---|---|
| `SESSION_READY` | WS | Handshake complete, server accepted session |
| `START_LISTENING` | UI / VAD | User pressed the orb or push-to-talk, or client VAD detected speech |
| `END_OF_UTTERANCE` | Server VAD / UI | End of user turn (silence threshold or manual release) |
| `AGENT_AUDIO_START` | WS | First TTS frame received |
| `AGENT_AUDIO_END` | WS + engine | Server signalled `turn.end` **and** playback buffer drained |
| `BARGE_IN` | Client VAD / server | User speech detected while `speaking` |
| `FLUSH_DONE` | Engine | Playback ring buffer cleared (synchronous in practice) |
| `ERROR` | any | Recoverable or fatal fault |
| `STOP` | UI | User ended the session |
### 2.3 Transition diagram
```mermaid
stateDiagram-v2
[*] --> idle
idle --> listening: START_LISTENING
listening --> processing: END_OF_UTTERANCE
listening --> idle: STOP / mic muted
processing --> speaking: AGENT_AUDIO_START
processing --> listening: START_LISTENING (user talks over thinking)
processing --> idle: ERROR (recovered) / empty answer
speaking --> idle: AGENT_AUDIO_END
speaking --> interrupted: BARGE_IN
interrupted --> listening: FLUSH_DONE
speaking --> idle: STOP
idle --> idle: ERROR (recovered)
```
### 2.4 Transition table (authoritative)
| From | Event | Guard | To | Side effects (executed by `VoiceSessionService`) |
|---|---|---|---|---|
| `idle` | `START_LISTENING` | session connected, mic permission granted | `listening` | `engine.unmuteCapture()`, send `{type:'turn.start'}` |
| `listening` | `END_OF_UTTERANCE` | utterance ≥ min length (default 300 ms) | `processing` | `engine.muteCapture()`, send `{type:'turn.end'}` |
| `listening` | `END_OF_UTTERANCE` | utterance < min length | `idle` | discard, send `{type:'turn.cancel'}` |
| `processing` | `AGENT_AUDIO_START` | — | `speaking` | `engine.startPlayback()`, re-open capture for barge-in |
| `processing` | `START_LISTENING` | allowed by config `allowTalkOverThinking` | `listening` | send `{type:'turn.cancel'}`, then `turn.start` |
| `speaking` | `AGENT_AUDIO_END` | playback buffer empty | `idle` | `engine.muteCapture()` |
| `speaking` | `BARGE_IN` | debounce ≥ 120 ms of sustained speech energy | `interrupted` | `engine.flushPlayback()` (**local first**), send `{type:'interrupt', playedMs}` |
| `interrupted` | `FLUSH_DONE` | — | `listening` | send `{type:'turn.start'}`; ignore any late agent frames with a stale `turnId` |
| any | `ERROR` | fatal | `idle` | tear down socket/engine, surface toast, offer retry |
| any | `STOP` | — | `idle` | graceful teardown |
**Invariants**
- Any event not listed for the current state is **ignored and logged** (never throws).
- Agent frames carry a `turnId`; frames whose `turnId` ≠ current turn are dropped (this makes barge-in race-free).
- Barge-in flushes audio **locally before** informing the server — perceived responsiveness must not depend on RTT.
### 2.5 Signal state design
State is split by *rate of change* and *consumer*:
| Signal / store | Type | Rate | Consumer | Notes |
|---|---|---|---|---|
| `voiceState` | `Signal<VoiceState>` | events (~1–5 Hz) | templates, visualizer (via `effect`) | Written only by `VoiceSessionService` |
| `activeSession` | `Signal<VoiceSession \| null>` | rare | header, guards | id, startedAt, connection status |
| `transcript` | `Signal<TranscriptEntry[]>` | per utterance / partial | transcript drawer | Partials update the last entry immutably |
| `faqDocuments` | `Signal<FaqDocument[]>` | per upload event | drawer, grid toolbar | Keyed by `id`; status updated via `update()` |
| `qaPairs` | `Signal<QaPair[]>` | per edit | grid | Large lists: keep as `Map` internally, expose array via `computed` |
| `activeDocumentIds` | `Signal<Set<string>>` | rare | session config | Which sources feed the current session |
| `audioLevel` | **NOT a per-frame signal** | 60 Hz | visualizer only | See below |
#### The `audioLevel` rule
Per-frame levels are written into a mutable `AudioLevelBus` (a preallocated `Float32Array` + a couple of numbers). The canvas loop reads it directly. For any Angular UI that wants a level (e.g., a mic meter), expose a **throttled** signal:
```ts
// core/audio/audio-level-bus.ts
export class AudioLevelBus {
/** written by AudioEngine each frame, read by VisualizerEngine each frame */
readonly inputRms = new Float32Array(1);
readonly outputRms = new Float32Array(1);
readonly inputBands = new Uint8Array(64); // from AnalyserNode (preallocated)
readonly outputBands = new Uint8Array(64);
}
// core/audio/audio-engine.service.ts (excerpt)
private readonly _meter = signal(0);
/** 10 Hz, UI-only (e.g., mic meter). Never bind this to the canvas. */
readonly meter = this._meter.asReadonly();
```
Writing a signal at 60 Hz in a zoneless app **schedules change detection at 60 Hz**; in a zone app it is cheaper only if the write happens outside the zone, but any template reading it would still re-render. Hence: bus for machines, throttled signal for humans.
#### Reference implementation skeleton
```ts
// core/state/voice-state.store.ts
@Injectable({ providedIn: 'root' })
export class VoiceStateStore {
private readonly _voiceState = signal<VoiceState>('idle');
private readonly _activeSession = signal<VoiceSession | null>(null);
private readonly _transcript = signal<TranscriptEntry[]>([]);
readonly voiceState = this._voiceState.asReadonly();
readonly activeSession = this._activeSession.asReadonly();
readonly transcript = this._transcript.asReadonly();
readonly isMicOpen = computed(() => ['listening', 'speaking', 'interrupted'].includes(this._voiceState()));
readonly canInterrupt = computed(() => this._voiceState() === 'speaking');
readonly statusLabelKey = computed(() => `voice.state.${this._voiceState()}`);
/** Only VoiceSessionService may call these (enforced by convention + lint rule). */
_setState(next: VoiceState) { this._voiceState.set(next); }
_setSession(s: VoiceSession | null) { this._activeSession.set(s); }
_appendTranscript(e: TranscriptEntry) { this._transcript.update(list => [...list, e]); }
}
```
```ts
// features/voice-agent/services/voice-session.service.ts (transition core)
const TRANSITIONS: Record<VoiceState, Partial<Record<VoiceEvent['type'], VoiceState>>> = {
idle: { START_LISTENING: 'listening' },
listening: { END_OF_UTTERANCE: 'processing', STOP: 'idle' },
processing: { AGENT_AUDIO_START: 'speaking', START_LISTENING: 'listening', ERROR: 'idle' },
speaking: { AGENT_AUDIO_END: 'idle', BARGE_IN: 'interrupted', STOP: 'idle', ERROR: 'idle' },
interrupted: { FLUSH_DONE: 'listening', ERROR: 'idle' },
};
dispatch(event: VoiceEvent) {
const current = this.store.voiceState();
const next = TRANSITIONS[current][event.type];
if (!next) { this.log.debug('ignored', current, event.type); return; }
if (!this.guards.allow(current, event, next)) return;
this.effects.run(current, next, event); // engine + socket side effects
this.store._setState(next);
}
```
Keeping the table as data (rather than `switch` statements) makes it unit-testable and lets the docs/diagram be generated from it.
---
## 3. Audio Pipeline & Performance Strategy
### 3.1 Thread separation
| Thread | Runs | Must never |
|---|---|---|
| **Audio render thread** (`AudioWorkletGlobalScope`) | `capture-processor`, `playback-processor` | allocate in `process()`, log, touch DOM, wait on anything |
| **Main thread, outside Angular** | `AudioContext` graph management, `WebSocketService` I/O, `VisualizerEngine` | trigger change detection, write per-frame signals |
| **Main thread, Angular** | components, signals, templates | process audio samples, run the render loop |
| **(Optional) Dedicated Worker** | socket I/O + encode/decode if profiling shows main-thread jank | — |
### 3.2 Capture path (mic → server)
1. `getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, channelCount: 1 } })`. Echo cancellation is **mandatory**; barge-in during `speaking` depends on it.
2. Create `AudioContext({ latencyHint: 'interactive', sampleRate: 16000 })`. Browsers may ignore the requested rate — always read `ctx.sampleRate` and let the worklet resample to the wire rate if they differ.
3. `MediaStreamAudioSourceNode` → `AudioWorkletNode('capture-processor')`. The same source also feeds an `AnalyserNode` (`fftSize = 256`, `smoothingTimeConstant = 0.8`) for visuals.
4. In `process()`, copy 128-sample render quanta into a preallocated accumulator. Every **20 ms** (320 samples @ 16 kHz) convert Float32 → Int16 little-endian and `port.postMessage(buffer, [buffer])` (**transfer, don't copy**). Use a small pool of ArrayBuffers recycled via a return message to avoid GC churn.
5. The main thread forwards each frame to `WebSocketService.sendAudio()` as a binary message (header + payload, see §5.2). No per-frame Angular involvement.
```js
// core/audio/worklets/capture-processor.worklet.js
class CaptureProcessor extends AudioWorkletProcessor {
constructor(options) {
super();
this.frameSamples = options.processorOptions.frameSamples; // e.g. 320
this.acc = new Float32Array(this.frameSamples);
this.fill = 0;
this.active = false;
this.port.onmessage = (e) => { if (e.data.type === 'active') this.active = e.data.value; };
}
process(inputs) {
const ch = inputs[0]?.[0];
if (!ch || !this.active) return true;
for (let i = 0; i < ch.length; i++) {
this.acc[this.fill++] = ch[i];
if (this.fill === this.frameSamples) {
const out = new Int16Array(this.frameSamples); // replace with pooled buffers in production
for (let j = 0; j < out.length; j++) {
const s = Math.max(-1, Math.min(1, this.acc[j]));
out[j] = s < 0 ? s * 0x8000 : s * 0x7fff;
}
this.port.postMessage(out.buffer, [out.buffer]);
this.fill = 0;
}
}
return true;
}
}
registerProcessor('capture-processor', CaptureProcessor);
```
### 3.3 Playback path (server → speakers)
1. `WebSocketService` receives binary frames (outside the zone), validates the header, drops stale `turnId`s, and transfers the PCM payload to `playback-processor` via `port.postMessage`.
2. `playback-processor` owns a **ring buffer** sized for ~2 s of audio and a **jitter buffer target** (default 60–100 ms prebuffer before starting). On underrun it outputs silence and posts `{type:'underrun'}` (counted in telemetry).
3. Decoded Int16 → Float32 happens inside the worklet; sample-rate conversion (e.g. server 24 kHz → context rate) is linear-interpolation in the worklet, or avoided by making the server emit the context rate.
4. **Flush** (`{type:'flush'}`) resets read/write pointers in O(1) — this is what makes barge-in feel instant.
5. Playback node → `AnalyserNode` (output) → `ctx.destination`. The analyser feeds `AudioLevelBus.outputBands`.
6. When the server sends `turn.end`, the worklet reports `{type:'drained'}` once the ring buffer empties; only then does the engine emit `AGENT_AUDIO_END`.
### 3.4 Transport choice
| | **WebSocket (default)** | **WebRTC (optional phase)** |
|---|---|---|
| Latency | Good (TCP head-of-line blocking under loss) | Best (UDP, Opus, built-in jitter/AEC) |
| Complexity | Low; full control over framing | Higher: signalling, STUN/TURN, SDP |
| Audio format | Raw PCM16 (simple, bigger) or Opus via WebCodecs | Opus, handled by the browser |
| Fit | MVP, corporate networks | Lossy/mobile networks, scale |
`WebSocketService` implements an abstract `RealtimeTransport` interface (`connect`, `sendAudio`, `sendControl`, `audio$`, `control$`, `status`). A `WebRtcTransport` can later replace it without touching `VoiceSessionService`.
### 3.5 Latency budget (target, p50)
| Segment | Budget |
|---|---|
| Capture frame + worklet handoff | 20–30 ms |
| Uplink (frame to gateway) | 30–80 ms |
| End-of-utterance detection | 200–400 ms (server VAD tuning) |
| STT final + RAG retrieval + LLM first token | 250–500 ms |
| TTS first audio chunk | 100–200 ms |
| Downlink + jitter buffer + output latency | 80–150 ms |
The frontend owns roughly 100–200 ms of this; its job is not to add to it (small frames, no copies, no main-thread stalls).
### 3.6 Bypassing Angular change detection for 60 FPS rendering
**Problem.** In a Zone.js app every `requestAnimationFrame`, `WebSocket.onmessage`, and `setTimeout` callback triggers `ApplicationRef.tick()`. A 60 FPS loop would run change detection 60×/s across the app.
**Strategy.**
```ts
// features/voice-agent/services/visualizer-engine.ts
@Injectable()
export class VisualizerEngine {
private readonly zone = inject(NgZone);
private readonly destroyRef = inject(DestroyRef);
private readonly bus = inject(AudioLevelBus);
private rafId = 0;
private renderer?: THREE.WebGLRenderer;
private target = { level: 0, hue: 0.58, turbulence: 0.1 }; // eased per frame
init(canvas: HTMLCanvasElement) {
this.zone.runOutsideAngular(() => {
this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, powerPreference: 'high-performance' });
this.renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
// build scene, orb mesh, ShaderMaterial with uniforms: uTime, uLevel, uTurbulence, uColor
this.loop();
});
this.destroyRef.onDestroy(() => this.dispose());
}
/** Called from an Angular effect() when voiceState changes (~1-5 Hz): cheap, no per-frame signal reads. */
applyState(state: VoiceState) { this.target = STATE_PRESETS[state]; }
private loop = () => {
this.rafId = requestAnimationFrame(this.loop); // already outside the zone
const src = this.currentSourceBands(); // input vs output bands by state
// read this.bus.* directly, ease uniforms toward targets, renderer.render(scene, camera)
};
private dispose() { cancelAnimationFrame(this.rafId); /* dispose geometries, materials, renderer, listeners */ }
}
```
Rules:
1. **Create the renderer and start the loop inside `NgZone.runOutsideAngular`.** (Under zoneless this is a harmless no-op, so the code is portable.)
2. **Wire sockets and worklet `port.onmessage` outside the zone too**, and re-enter Angular only by *writing a signal* when something human-visible changes (state transition, transcript partial). In zoneless mode, the signal write is what schedules rendering.
3. **State → visuals via an `effect`, not per-frame signal reads.** The effect runs on state changes and updates a plain target object; the rAF loop eases toward it.
4. **Reuse everything per frame**: no `new` objects, no array allocation, no string building in the loop. Use `getByteFrequencyData(prealloc)`.
5. **Cap DPR at 2**, resize via `ResizeObserver` (outside the zone), and render at half resolution on low-power devices (`navigator.hardwareConcurrency`, frame-time monitor that steps quality down).
6. **Pause when not visible**: `document.visibilitychange` and `IntersectionObserver` stop the loop and suspend analyser polling.
7. **`prefers-reduced-motion`**: switch to a reduced preset (no turbulence, slower easing).
8. **WebGL fallback**: on `webglcontextlost` or no WebGL, swap to a `Canvas2DVisualizer` implementing the same `Visualizer` interface (ring of bars/radial waveform).
9. **Template side**: the canvas host component is `OnPush`, has no bindings that change per frame, and exposes the canvas via `viewChild.required<ElementRef<HTMLCanvasElement>>('canvas')`.
### 3.7 Performance budgets & verification
| Metric | Budget | How verified |
|---|---|---|
| Frame time (visualizer) | ≤ 8 ms avg on mid-range laptop | Chrome Performance panel, in-app dev HUD |
| Change-detection ticks during idle visualization | **0 per second** | Angular DevTools profiler; `ApplicationRef.tick` counter in dev build |
| Main-thread long tasks (> 50 ms) during a conversation | 0 | PerformanceObserver `longtask` |
| Worklet underruns per 10 min | < 2 on a stable network | Telemetry counter |
| Heap growth over 30 min session | < 10 MB | Memory profiler (buffer pooling check) |
| Initial bundle (excluding lazy Three.js chunk) | < 250 KB gz | `source-map-explorer`, CI budget |
Three.js, PapaParse, and AG Grid are **lazy-loaded** (dynamic `import()`), so first paint is not penalized by the visualizer or grid code.
---
## 4. Folder Structure & Component Breakdown
```text
src/
├─ app/
│ ├─ app.config.ts # provideRouter, provideHttpClient, zoneless provider (see note)
│ ├─ app.routes.ts # lazy routes: voice, knowledge-base
│ ├─ app.component.ts
│ │
│ ├─ core/
│ │ ├─ audio/
│ │ │ ├─ audio-engine.service.ts # AudioContext, mic stream, node graph, mute/flush/play APIs
│ │ │ ├─ audio-level-bus.ts # mutable per-frame data shared with the visualizer
│ │ │ ├─ pcm-utils.ts # float<->int16, resample helpers (shared with tests)
│ │ │ ├─ audio.tokens.ts # AUDIO_CONFIG (sample rates, frame ms, prebuffer ms)
│ │ │ └─ worklets/
│ │ │ ├─ capture-processor.worklet.js
│ │ │ └─ playback-processor.worklet.js
│ │ ├─ websocket/
│ │ │ ├─ realtime-transport.ts # abstract interface (WS today, WebRTC later)
│ │ │ ├─ websocket.service.ts # connect/reconnect/backoff/heartbeat
│ │ │ ├─ frame-codec.ts # binary header encode/decode (see §5.2)
│ │ │ └─ protocol.types.ts # ClientMessage / ServerMessage unions
│ │ ├─ state/
│ │ │ ├─ voice-state.store.ts # voiceState, activeSession, transcript
│ │ │ └─ voice-state.types.ts
│ │ ├─ http/
│ │ │ ├─ auth.interceptor.ts
│ │ │ └─ error.interceptor.ts
│ │ ├─ telemetry/
│ │ │ └─ telemetry.service.ts # underruns, latency marks, state transitions
│ │ └─ config/
│ │ └─ app-config.token.ts # wsUrl, apiBaseUrl, feature flags
│ │
│ ├─ features/
│ │ ├─ voice-agent/
│ │ │ ├─ voice-agent.page.ts # route container (smart)
│ │ │ ├─ components/
│ │ │ │ ├─ voice-orb/ # canvas host (dumb, OnPush)
│ │ │ │ ├─ voice-controls/ # mic button, push-to-talk, stop
│ │ │ │ ├─ voice-status-label/ # state text + aria-live
│ │ │ │ ├─ transcript-panel/ # collapsible transcript
│ │ │ │ └─ faq-suggestions/ # suggested questions chips
│ │ │ ├─ services/
│ │ │ │ ├─ voice-session.service.ts # state machine orchestrator
│ │ │ │ ├─ voice-transitions.ts # TRANSITIONS table + guards
│ │ │ │ └─ visualizer/
│ │ │ │ ├─ visualizer.interface.ts
│ │ │ │ ├─ three-orb.visualizer.ts # WebGL implementation
│ │ │ │ ├─ canvas2d.visualizer.ts # fallback
│ │ │ │ └─ state-presets.ts
│ │ │ └─ voice-agent.routes.ts
│ │ │
│ │ └─ faq-manager/
│ │ ├─ faq-manager.page.ts # optional full-page route
│ │ ├─ components/
│ │ │ ├─ faq-drawer/ # CDK Overlay slide-over host
│ │ │ ├─ file-dropzone/ # drag & drop, type/size validation
│ │ │ ├─ csv-preview/ # PapaParse preview (first N rows, column mapping)
│ │ │ ├─ document-list/ # rows with status badges and progress
│ │ │ ├─ qa-grid/ # AG Grid (lazy) or Tailwind table
│ │ │ └─ qa-edit-dialog/ # CDK Dialog for manual override
│ │ ├─ services/
│ │ │ ├─ faq-store.ts # signals: documents, qaPairs, filters
│ │ │ ├─ faq-ingestion.service.ts # validate, upload, status stream
│ │ │ ├─ faq-api.service.ts # HTTP client
│ │ │ └─ csv-parser.service.ts # lazy PapaParse wrapper (worker: true)
│ │ └─ faq-manager.routes.ts
│ │
│ └─ shared/
│ ├─ ui/
│ │ ├─ button/ · badge/ · drawer/ · dialog/ · toast/ · spinner/ · empty-state/
│ │ └─ icons/ # Lucide icon registration (tree-shaken)
│ ├─ directives/ # autofocus, resize-observer, click-outside
│ ├─ pipes/ # file-size, relative-time
│ └─ utils/ # assert, raf-throttle, id generation
│
├─ assets/
│ └─ worklets/ # compiled worklet files served as static assets
├─ environments/
└─ styles/
└─ tailwind.css
```
**Notes**
- **Worklet files are static assets**, loaded with `ctx.audioWorklet.addModule(new URL('./capture-processor.worklet.js', import.meta.url))` or from `assets/`. They are *not* part of the Angular bundle graph (they run in a separate global scope).
- **Zoneless provider:** use `provideExperimentalZonelessChangeDetection()` on Angular 18/19; newer majors expose the stabilized `provideZonelessChangeDetection()`. Keep Zone.js in `polyfills` until the zoneless checklist passes, then remove it.
- **Dependency rule (enforced via ESLint `no-restricted-imports` / Nx-style boundaries):**
`shared` ← `core` ← `features`; features never import from each other; `core/audio` and `core/websocket` never import Angular UI.
- **Smart vs dumb:** `*.page.ts` and services are smart; everything in `components/` is `OnPush`, input/output driven, with no service injection except for `visualizer` hosts and the dialog/overlay hosts.
### 4.1 Key component contracts
| Component | Inputs (signal `input()`) | Outputs (`output()`) | Notes |
|---|---|---|---|
| `VoiceOrbComponent` | `state: VoiceState` | `ready`, `webglUnavailable` | Owns `<canvas>`, creates visualizer in `afterNextRender` |
| `VoiceControlsComponent` | `state`, `micPermission` | `toggleMic`, `stop` | Keyboard: Space toggles, Esc stops |
| `TranscriptPanelComponent` | `entries`, `open` | `openChange` | `aria-live="polite"` for the latest entry |
| `FaqDrawerComponent` | `open` | `closed` | CDK `Overlay` + focus trap; slides from the inline-end edge |
| `FileDropzoneComponent` | `accept`, `maxBytes` | `filesSelected`, `rejected` | Validates MIME + extension + size before anything uploads |
| `DocumentListComponent` | `documents` | `retry`, `remove`, `toggleActive` | Status badge per `FaqDocumentStatus` |
| `QaGridComponent` | `rows`, `filters` | `editRow`, `toggleOverride`, `bulkDelete` | Virtualized; server-side row model if > 50k rows |
### 4.2 Component interaction (voice screen)
```mermaid
sequenceDiagram
participant U as User
participant C as VoiceControls
participant S as VoiceSessionService
participant E as AudioEngine
participant T as WebSocketService
participant B as Backend
participant V as VisualizerEngine
U->>C: click orb
C->>S: dispatch(START_LISTENING)
S->>E: unmuteCapture()
S->>T: control turn.start
loop every 20 ms
E->>T: PCM frame
T->>B: binary frame
end
B-->>T: control vad.end_of_speech
T-->>S: END_OF_UTTERANCE
S->>E: muteCapture()
B-->>T: PCM reply frames (turnId=n)
T->>E: transfer to playback worklet
T-->>S: AGENT_AUDIO_START
S-->>V: state signal changes, effect applies preset
U->>E: starts talking (VAD energy over threshold)
E-->>S: BARGE_IN
S->>E: flushPlayback() (local, immediate)
S->>T: control interrupt with playedMs
S-->>S: FLUSH_DONE, state becomes listening
```
---
## 5. Data Contracts & Types
All shared types live in `core/**/**.types.ts` and are **framework-free** (no Angular imports) so they can be shared with the backend repo or generated from an OpenAPI/AsyncAPI spec later.
### 5.1 Voice states and session
```ts
// core/state/voice-state.types.ts
export const VOICE_STATES = ['idle', 'listening', 'processing', 'speaking', 'interrupted'] as const;
export type VoiceState = (typeof VOICE_STATES)[number];
export type VoiceEvent =
| { type: 'SESSION_READY' }
| { type: 'START_LISTENING'; source: 'ui' | 'client-vad' }
| { type: 'END_OF_UTTERANCE'; source: 'server-vad' | 'ui'; durationMs: number }
| { type: 'AGENT_AUDIO_START'; turnId: string }
| { type: 'AGENT_AUDIO_END'; turnId: string }
| { type: 'BARGE_IN'; playedMs: number }
| { type: 'FLUSH_DONE' }
| { type: 'ERROR'; error: VoiceError }
| { type: 'STOP' };
export type ConnectionStatus = 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'failed';
export interface VoiceSession {
readonly id: string;
readonly startedAt: number; // epoch ms
readonly connection: ConnectionStatus;
readonly activeDocumentIds: readonly string[];
readonly locale: string; // BCP-47, e.g. 'en-US', 'fa-IR'
readonly currentTurnId: string | null;
}
export interface TranscriptEntry {
readonly id: string;
readonly turnId: string;
readonly role: 'user' | 'agent';
readonly text: string;
readonly final: boolean; // false while streaming partials
readonly timestamp: number;
readonly citations?: readonly FaqCitation[];
}
export interface FaqCitation {
readonly documentId: string;
readonly qaPairId?: string;
readonly title: string;
readonly score?: number; // retrieval relevance 0..1
}
export type VoiceErrorCode =
| 'MIC_PERMISSION_DENIED' | 'MIC_NOT_FOUND' | 'AUDIO_CONTEXT_FAILED' | 'WORKLET_LOAD_FAILED'
| 'SOCKET_FAILED' | 'AUTH_EXPIRED' | 'SERVER_ERROR' | 'RATE_LIMITED' | 'UNSUPPORTED_BROWSER';
export interface VoiceError {
readonly code: VoiceErrorCode;
readonly message: string;
readonly recoverable: boolean;
}
```
### 5.2 WebSocket protocol
A **hybrid protocol**: *binary* frames for audio (low overhead), *text/JSON* frames for control.
#### Binary audio frame layout (little-endian)
| Offset | Size | Field | Description |
|---|---|---|---|
| 0 | 1 B | `version` | Protocol version (currently `1`) |
| 1 | 1 B | `kind` | `0x01` = mic audio (client → server), `0x02` = agent audio (server → client) |
| 2 | 1 B | `flags` | bit0 = last frame of turn, bit1 = contains silence |
| 3 | 1 B | `reserved` | `0` |
| 4 | 4 B | `seq` | Monotonic per direction, wraps at 2³² |
| 8 | 4 B | `timestampMs` | Capture/synthesis offset from turn start |
| 12 | 4 B | `turnIdHash` | 32-bit hash of the `turnId` (full id is sent in control messages) |
| 16 | N | `payload` | PCM16 mono, little-endian, 20 ms per frame (e.g. 640 B @ 16 kHz) |
```ts
// core/websocket/protocol.types.ts
export type AudioEncoding = 'pcm_s16le' | 'opus';
export interface AudioFormat {
readonly encoding: AudioEncoding;
readonly sampleRate: 16000 | 24000 | 48000;
readonly channels: 1;
readonly frameMs: 10 | 20 | 40;
}
/** Decoded view of a binary audio frame */
export interface AudioFrame {
readonly version: 1;
readonly kind: 'mic' | 'agent';
readonly lastOfTurn: boolean;
readonly silent: boolean;
readonly seq: number;
readonly timestampMs: number;
readonly turnIdHash: number;
readonly payload: ArrayBuffer; // PCM bytes, transferable
}
/* ---------- Client -> Server (JSON) ---------- */
export type ClientMessage =
| { type: 'session.start'; token: string; locale: string; inputFormat: AudioFormat;
outputFormat: AudioFormat; documentIds: string[] }
| { type: 'turn.start'; turnId: string }
| { type: 'turn.end'; turnId: string }
| { type: 'turn.cancel'; turnId: string }
| { type: 'interrupt'; turnId: string; playedMs: number } // how much agent audio the user actually heard
| { type: 'config.update'; documentIds: string[] }
| { type: 'ping'; t: number }
| { type: 'session.end' };
/* ---------- Server -> Client (JSON) ---------- */
export type ServerMessage =
| { type: 'session.ready'; sessionId: string; inputFormat: AudioFormat; outputFormat: AudioFormat }
| { type: 'vad.speech_start' }
| { type: 'vad.speech_end'; durationMs: number }
| { type: 'transcript.partial'; turnId: string; role: 'user' | 'agent'; text: string }
| { type: 'transcript.final'; turnId: string; role: 'user' | 'agent'; text: string; citations?: FaqCitationDto[] }
| { type: 'agent.audio_start'; turnId: string }
| { type: 'agent.audio_end'; turnId: string }
| { type: 'suggestions'; items: string[] }
| { type: 'error'; code: string; message: string; recoverable: boolean }
| { type: 'pong'; t: number };
export interface FaqCitationDto { documentId: string; qaPairId?: string; title: string; score?: number }
```
**Protocol rules**
- Authentication happens in the first JSON message (`session.start.token`, a short-lived ticket), **not** in the URL query string (URLs are logged).
- The server must echo/choose the final `AudioFormat`s in `session.ready`; the client configures worklets from that response.
- `interrupt.playedMs` lets the server truncate the conversation history to what the user actually heard.
- Heartbeat: client `ping` every 15 s; no `pong` within 2 intervals ⇒ reconnect with exponential backoff (500 ms → 8 s, jittered). Reconnect starts a *new* session, never resumes mid-turn.
### 5.3 Worklet message contracts
```ts
// core/audio/audio.types.ts
export type CaptureCommand = { type: 'active'; value: boolean };
export type CaptureEvent = ArrayBuffer; // transferred Int16 PCM frame (raw message)
export type PlaybackCommand =
| { type: 'config'; sampleRate: number; prebufferMs: number }
| { type: 'frame'; pcm: ArrayBuffer; turnIdHash: number } // transferred
| { type: 'flush' }
| { type: 'end-of-turn' };
export type PlaybackEvent =
| { type: 'started' }
| { type: 'drained' }
| { type: 'underrun'; count: number }
| { type: 'level'; rms: number }; // optional, low-rate (~20 Hz)
```
### 5.4 FAQ knowledge base
```ts
// features/faq-manager/models/faq.types.ts
export type FaqFileType = 'pdf' | 'csv' | 'json' | 'docx';
export type FaqDocumentStatus = 'uploading' | 'indexing' | 'active' | 'error';
export interface FaqDocument {
readonly id: string; // client-generated UUID until the server assigns one
readonly serverId?: string;
readonly name: string;
readonly type: FaqFileType;
readonly sizeBytes: number;
readonly status: FaqDocumentStatus;
readonly progress: number; // 0..1 (upload progress, then indexing progress if available)
readonly itemCount: number | null; // Q&A pairs extracted; null until known
readonly enabled: boolean; // included in the voice session's retrieval scope
readonly uploadedAt: number;
readonly updatedAt: number;
readonly error?: FaqDocumentError;
}
export interface FaqDocumentError {
readonly code: 'VALIDATION_FAILED' | 'UPLOAD_FAILED' | 'PARSE_FAILED' | 'INDEX_FAILED' | 'QUOTA_EXCEEDED';
readonly message: string;
readonly retryable: boolean;
readonly rowErrors?: readonly CsvRowError[];
}
export interface QaPair {
readonly id: string;
readonly documentId: string;
readonly question: string;
readonly answer: string;
readonly tags: readonly string[];
readonly source: 'ingested' | 'manual';
readonly overridden: boolean; // manual edit wins over re-ingested content
readonly enabled: boolean;
readonly updatedAt: number;
readonly updatedBy?: string;
}
export interface QaFilter {
readonly query: string;
readonly documentIds: readonly string[];
readonly source: 'all' | 'ingested' | 'manual';
readonly onlyOverridden: boolean;
readonly onlyDisabled: boolean;
}
/* ---------- Client-side validation ---------- */
export interface FileValidationRule {
readonly maxBytes: number; // e.g. 25 MB
readonly allowedExtensions: readonly FaqFileType[];
readonly allowedMimeTypes: readonly string[];
}
export interface CsvPreview {
readonly headers: readonly string[];
readonly rows: readonly Record<string, string>[]; // first N rows only
readonly totalRowsEstimate: number;
readonly questionColumn: string | null; // auto-detected or user-mapped
readonly answerColumn: string | null;
readonly errors: readonly CsvRowError[];
}
export interface CsvRowError {
readonly row: number;
readonly code: 'MISSING_QUESTION' | 'MISSING_ANSWER' | 'TOO_LONG' | 'MALFORMED';
readonly message: string;
}
/* ---------- Server status stream (SSE or WS) ---------- */
export type IngestionEvent =
| { type: 'document.progress'; id: string; stage: 'uploading' | 'indexing'; progress: number }
| { type: 'document.active'; id: string; itemCount: number }
| { type: 'document.error'; id: string; error: FaqDocumentError };
```
**FAQ state shape (signals)**
```ts
@Injectable({ providedIn: 'root' })
export class FaqStore {
private readonly _documents = signal<readonly FaqDocument[]>([]);
private readonly _pairs = signal<ReadonlyMap<string, QaPair>>(new Map());
readonly filter = signal<QaFilter>(DEFAULT_FILTER);
readonly documents = this._documents.asReadonly();
readonly activeDocuments = computed(() => this._documents().filter(d => d.status === 'active' && d.enabled));
readonly hasProcessing = computed(() => this._documents().some(d => d.status === 'uploading' || d.status === 'indexing'));
readonly visiblePairs = computed(() => applyFilter([...this._pairs().values()], this.filter()));
readonly totalActiveItems = computed(() => this.activeDocuments().reduce((n, d) => n + (d.itemCount ?? 0), 0));
}
```
---
## 6. Cross-Cutting Concerns
### 6.1 Error handling & resilience
| Failure | Detection | Behaviour |
|---|---|---|
| Mic permission denied | `getUserMedia` rejection (`NotAllowedError`) | Inline explainer with browser-specific steps; text input fallback |
| `AudioContext` suspended (autoplay policy) | `ctx.state === 'suspended'` | Create/resume only inside a user gesture (the first orb click) |
| Worklet module fails to load | `addModule` rejection | Fatal `WORKLET_LOAD_FAILED`; show unsupported-browser message |
| Socket drop mid-turn | `onclose` / missed pong | Flush playback, state → `idle`, auto-reconnect with backoff, toast |
| Token expiry | `error` message `AUTH_EXPIRED` | Refresh ticket via HTTP, then restart session |
| Playback underrun | worklet `underrun` event | Increase prebuffer adaptively (up to 200 ms), log telemetry |
| WebGL context lost | `webglcontextlost` | Swap to `Canvas2DVisualizer`; try restore on `webglcontextrestored` |
### 6.2 Security & privacy
- `wss://` only; CSP with `connect-src` restricted to the API/gateway hosts and `worker-src`/`script-src` allowing the worklet assets.
- Mic access only after an explicit user gesture; a visible "mic live" indicator in the UI whenever capture is active.
- Uploaded files are validated by **magic bytes + extension + size** on the client for UX only; the server must re-validate (client checks are never a trust boundary).
- Do not log raw audio or transcripts to telemetry; log durations, counts, and error codes.
- `Cross-Origin-Opener-Policy` / `Cross-Origin-Embedder-Policy` headers are *only* required if `SharedArrayBuffer` ring buffers are adopted (optional optimization, see ADR-06).
### 6.3 Accessibility
- The orb is decorative; the **status label** (`aria-live="polite"`) announces state changes ("Listening…", "Thinking…", "Speaking…").
- Full keyboard operation (Space = talk/stop, Esc = end, Tab order through drawer, focus trap in CDK Dialog/Overlay).
- Transcript panel gives a complete text alternative, with captions of the agent's reply as it is spoken.
- Respect `prefers-reduced-motion`; never rely on color alone for state (icon + label + motion).
- Drawer and layout use **logical CSS properties** (`ms-*`, `ps-*`, `inset-inline-end`) and `dir`-aware Tailwind variants so RTL locales work without forks.
### 6.4 Observability
Telemetry events (no PII): `session_start`, `state_transition {from,to,ms_in_state}`, `barge_in {playedMs}`, `underrun_count`, `ttfa_ms` (end-of-utterance → first agent audio), `reconnect {attempt}`, `ingestion_complete {type,items,ms}`. A dev-only HUD shows FPS, CD tick count, jitter-buffer depth, and RTT.
### 6.5 Testing strategy (summary)
| Layer | Approach |
|---|---|
| Transition table & guards | Pure unit tests (table-driven), including "ignored event" cases |
| Frame codec / PCM utils | Unit tests with golden byte arrays |
| Worklets | Run processor classes in Node/Vitest with a fake `AudioWorkletGlobalScope`; assert pooling and flush behaviour |
| `VoiceSessionService` | Integration test with fake `AudioEngine` + fake `RealtimeTransport`; simulate barge-in races and stale `turnId` frames |
| Components | Angular Testing Library; verify `OnPush` correctness via signal inputs only |
| Zoneless safety | Run the full suite with `provideExperimentalZonelessChangeDetection()` (or the stable name) and **without** Zone.js |
| E2E | Playwright with Chromium flags `--use-fake-device-for-media-stream --use-file-for-fake-audio-capture=...` and a mock WS gateway |
| Perf | Lighthouse CI budget + scripted Chrome trace asserting zero CD ticks during a 30 s visualized idle |
---
## 7. Architecture Decision Records (summary)
| # | Decision | Rationale | Trade-off |
|---|---|---|---|
| ADR-01 | **State machine as a data table** in a single service | Testable, diagrammable, one writer | Slightly more ceremony than ad-hoc signal sets |
| ADR-02 | **Per-frame audio levels bypass signals** (`AudioLevelBus`) | Avoids 60 Hz CD scheduling in zoneless mode | Visualizer reads mutable data; documented exception to "everything is a signal" |
| ADR-03 | **Hybrid binary/JSON WebSocket protocol** | Lowest overhead for audio; readable control plane | Two codecs to maintain |
| ADR-04 | **`interrupted` is a distinct, auto-resolving state** | Observability and testability of barge-in | One extra transition |
| ADR-05 | **Local-first flush on barge-in**, server informed after | Perceived latency independent of RTT | Must handle late frames via `turnId` |
| ADR-06 | **`postMessage` with transferables** first; `SharedArrayBuffer` only if profiling demands | Avoids COOP/COEP deployment constraints | Slightly higher overhead per frame |
| ADR-07 | **`RealtimeTransport` abstraction** | WebSocket now, WebRTC later without touching the state machine | Interface must stay minimal |
| ADR-08 | **Lazy-load Three.js, PapaParse, AG Grid** | Keeps initial bundle small | First visit to each feature pays a small fetch |
| ADR-09 | **Server-side VAD for end-of-utterance; client-side energy gate only for barge-in** | Server has better models and context; client gate gives instant barge-in | Two VAD paths to tune |
| ADR-10 | **Raw PCM16 over WS for MVP**, Opus (WebCodecs) as a later optimization | Simplicity and debuggability | ~256 kbps at 16 kHz up/down vs ~24–32 kbps Opus |
---
## 8. Open Questions
These affect later documents and should be resolved with the backend team:
1. **Audio formats:** does the gateway accept 16 kHz PCM16 in and emit 24 kHz PCM16 out (assumed here), or Opus?
2. **VAD ownership:** server VAD only, or both? What are the end-of-utterance silence defaults, and is the threshold configurable per session?
3. **Barge-in semantics:** does the server stop TTS on `interrupt`, or only on its own VAD? (The client protocol sends both.)
4. **Ingestion status channel:** SSE or reuse of the realtime WebSocket? (The types support either.)
5. **Grid scale:** expected maximum Q&A pairs per knowledge base — this decides between client-side filtering and AG Grid's server-side row model.
6. **Locales:** which languages and writing directions must the voice and the UI support at launch?
7. **Auth model:** how is the short-lived WebSocket ticket issued, and how long does it live?
---
## 9. Next Documents
| File | Contents |
|---|---|
| **`ROADMAP.md`** | Sprint-by-sprint implementation plan: scope, deliverables, acceptance criteria, risks, and a dependency graph. Proposed phases: (1) worklet + visualizer spike, (2) WS duplex + voice state machine, (3) FAQ manager UI, (4) zoneless hardening, performance, and testing. |
| **`VOICE_AUDIO_PIPELINE.md`** | Implementation guide: full `AudioEngineService`, capture/playback worklets with pooled buffers, resampling, jitter-buffer tuning, `AnalyserNode` wiring, the Three.js orb (shader uniforms, state presets, quality scaling), and the Canvas 2D fallback. |
| **`FAQ_MANAGEMENT_SPEC.md`** | Ingestion UX and logic: dropzone validation, PapaParse preview with column mapping (worker mode, streaming for large files), upload with progress, status stream handling, AG Grid configuration (columns, editors, filters, optimistic edits, overrides), and error recovery. |
| **`ZONELESS_CONVENTION.md`** | Coding standards: signal conventions (one writer, `asReadonly`), `input()`/`output()`/`viewChild()` usage, `OnPush` rules, `effect` and `untracked` guidelines, `toSignal` interop rules, forbidden patterns (e.g., mutating state outside signals), and the Zone.js-removal migration checklist with a CI gate. |
> Say **"continue"** and I'll write `ROADMAP.md` next, or tell me which file you'd like first.
+374
View File
@@ -0,0 +1,374 @@
# DEPENDENCIES.md — Voice-to-Voice FAQ Web Application
> **Companion to:** `ARCHITECTURE.md` · **See also:** `SRC_STRUCTURE.md`
> **Versions verified against the npm registry on 2026-10-05.** The latest Angular line at that date is **22.2.x**. Everything below targets Angular 22; section 1 lists what changes if you must stay on 18/19.
---
## 0. Read this first: six findings that change the install
These came out of checking real peer-dependency ranges and package contents, not from memory. Each one would otherwise cost you an `ERESOLVE` error or a runtime failure.
| # | Finding | What to do |
|---|---|---|
| 1 | **`provideExperimentalZonelessChangeDetection` no longer exists in Angular 22** (it is absent from `@angular/core@22.2.1`). The stable name is `provideZonelessChangeDetection`. The experimental name is only correct for Angular 18/19. | Use `provideZonelessChangeDetection()` (see `SRC_STRUCTURE.md` → `app.config.ts`). |
| 2 | **TypeScript must be `>=6.0 <6.1`.** `@angular/compiler-cli@22.2.1` and `@angular/build@22.2.1` both declare that peer range, while `typescript@latest` is already 7.0.x. | Pin `"typescript": "~6.0.3"`. Do not run `npm i typescript@latest`. |
| 3 | **`lucide-angular` is deprecated** on npm ("Please use `@lucide/angular` instead"). Its peer range stops at Angular 21 (`13.x – 21.x`), so it will conflict with Angular 22. | Use **`@lucide/angular`** (peer `>=17`). Icons are isolated behind `shared/ui/icons`, so only that folder knows which package is in use. |
| 4 | **Tailwind CSS is v4** (`4.3.x`). It is configured in CSS (`@theme`, `@utility`), runs through `@tailwindcss/postcss`, and **does not need Autoprefixer**. | Install `tailwindcss`, `@tailwindcss/postcss`, `postcss`. Skip `autoprefixer` (explained in §3.3). |
| 5 | **Three.js is pre-1.0** (`0.186.x`), and minor versions can contain breaking changes. | Pin with a **tilde** (`~0.186.1`) and keep `@types/three` on the matching minor (`~0.186.0`). |
| 6 | **Node.js `^22.22.3 \|\| ^24.15.0 \|\| >=26`** is required by Angular 22. | Set `engines` and add an `.nvmrc` (`24`). |
---
## 1. If you must stay on Angular 18 or 19
| Topic | Angular 22 (this document) | Angular 18/19 |
|---|---|---|
| Zoneless provider | `provideZonelessChangeDetection()` | `provideExperimentalZonelessChangeDetection()` |
| TypeScript | `~6.0.3` | Use the range printed by `npm view @angular/compiler-cli@<your-version> peerDependencies` |
| Icons | `@lucide/angular` | `lucide-angular` also works (its peer range covers these versions) |
| Tailwind | v4 via `@tailwindcss/postcss` | Stay on Tailwind v3 (`tailwind.config.js`, `postcss`, `autoprefixer`) unless your CLI version documents v4 support |
| Unit tests | Vitest via `@angular/build:unit-test` | Karma + Jasmine (default for those versions) |
| Components | `OnPush` set explicitly (kept explicit for readability) | `OnPush` set explicitly (required) |
For every other package (Three.js, AG Grid, PapaParse, CDK) install the version whose `peerDependencies` match your Angular major.
---
## 2. Complete `package.json`
```json
{
"name": "voice-faq-app",
"version": "0.1.0",
"private": true,
"engines": {
"node": "^22.22.3 || ^24.15.0"
},
"scripts": {
"start": "ng serve",
"build": "ng build",
"build:prod": "ng build --configuration production",
"build:stats": "ng build --configuration production --stats-json",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"test:ci": "ng test --no-watch",
"e2e": "playwright test",
"lint": "ng lint",
"format": "prettier --write \"src/**/*.{ts,html,css,json}\"",
"format:check": "prettier --check \"src/**/*.{ts,html,css,json}\""
},
"dependencies": {
"@angular/cdk": "^22.2.1",
"@angular/common": "^22.2.1",
"@angular/compiler": "^22.2.1",
"@angular/core": "^22.2.1",
"@angular/forms": "^22.2.1",
"@angular/platform-browser": "^22.2.1",
"@angular/router": "^22.2.1",
"@lucide/angular": "^1.52.0",
"ag-grid-angular": "^36.2.0",
"ag-grid-community": "^36.2.0",
"papaparse": "^5.7.0",
"rxjs": "~7.8.2",
"three": "~0.186.1",
"tslib": "^2.8.1",
"zone.js": "~0.16.3"
},
"devDependencies": {
"@angular/build": "^22.2.1",
"@angular/cli": "^22.2.1",
"@angular/compiler-cli": "^22.2.1",
"@playwright/test": "^1.63.0",
"@tailwindcss/postcss": "^4.3.3",
"@types/audioworklet": "^0.0.100",
"@types/node": "^24.0.0",
"@types/papaparse": "^5.5.2",
"@types/three": "~0.186.0",
"angular-eslint": "^22.5.0",
"eslint": "^10.12.0",
"jsdom": "^30.1.2",
"postcss": "^8.5.28",
"prettier": "^3.9.9",
"prettier-plugin-tailwindcss": "^0.8.1",
"tailwindcss": "^4.3.3",
"typescript": "~6.0.3",
"typescript-eslint": "^8.71.0",
"vitest": "^5.0.3"
}
}
```
**About `zone.js`:** it is listed because your plan keeps Zone.js enabled during development and removes it at the zoneless milestone (`ZONELESS_CONVENTION.md`). When that milestone passes, delete it from `dependencies` and from the `polyfills` array in `angular.json`, and switch `app.config.ts` from `provideZoneChangeDetection` to `provideZonelessChangeDetection`. A project that starts zoneless can omit it from day one.
**Optional packages** (PDF/DOCX client-side previews) are intentionally **not** in the block above. See §3.5.
---
## 3. `dependencies`, justified
### 3.1 Core & framework
| Package | Version | Why it is needed | Notes |
|---|---|---|---|
| `@angular/core` | `^22.2.1` | Signals (`signal`, `computed`, `effect`, `input()`, `output()`, `viewChild()`), `DestroyRef`, `NgZone`, zoneless scheduler, `provideZonelessChangeDetection`. | **Includes `@angular/core/rxjs-interop`** (`toSignal`, `toObservable`, `takeUntilDestroyed`) as a *secondary entry point*; there is nothing separate to install. |
| `@angular/common` | `^22.2.1` | `NgOptimizedImage`, pipes, and **`@angular/common/http`** (`HttpClient`, `withFetch`, `withInterceptors`) for the FAQ REST API and upload progress. | `common/http` is also a secondary entry point of this package. |
| `@angular/compiler` | `^22.2.1` | Required at runtime by the standard CLI scaffold and by JIT paths in tests. | Keep on the same version as `core`. |
| `@angular/platform-browser` | `^22.2.1` | `bootstrapApplication`, DOM renderer, `Meta`/`Title`. | |
| `@angular/router` | `^22.2.1` | Lazy-loaded feature routes (`voice`, `knowledge-base`), functional guards, `withComponentInputBinding()`. | |
| `@angular/forms` | `^22.2.1` | Reactive forms in the Q&A editor modal and drawer filters. | Also a **peer dependency of `@angular/cdk`**. |
| `@angular/cdk` | `^22.2.1` | **`@angular/cdk/overlay`** (slide-over drawer positioning, scroll strategies), **`@angular/cdk/dialog`** (Q&A editor modal, focus trap, `aria-modal`), **`@angular/cdk/a11y`** (`FocusTrap`, `LiveAnnouncer` for state changes), `@angular/cdk/portal`, `@angular/cdk/scrolling` (virtual scroll for the transcript). | Peer range is `^22 \|\| ^23`; versions of `cdk` and `core` must match the major. |
| `rxjs` | `~7.8.2` | WebSocket event streams (`audio$`, `control$`), ingestion status stream (SSE), debouncing filters. Signals hold state; RxJS carries **events over time**. | Angular peers `^6.5.3 \|\| ^7.4.0`. |
| `tslib` | `^2.8.1` | Helper functions for emitted code (no duplication per file). | Required by the Angular build. |
| `zone.js` | `~0.16.3` | Only while the app still runs in zone mode. | Remove at the zoneless milestone (see §2). |
### 3.2 Audio & graphics
| Package | Version | Why it is needed | Notes |
|---|---|---|---|
| `three` | `~0.186.1` | WebGL renderer, scene graph, `ShaderMaterial`, icosahedron geometry for the audio-reactive orb. | Use **named imports** (`import { WebGLRenderer, Scene } from 'three'`) so esbuild can tree-shake. Load it only in the visualizer chunk via `import('three')` (lazy). Post-processing (bloom) lives in `three/addons/...` and is **not** planned for v1: the glow is computed in the fragment shader plus a CSS `drop-shadow`, which is far cheaper. |
| `@types/three` *(dev)* | `~0.186.0` | Type definitions (Three.js ships no types). | Same minor as `three`. |
**Web Audio API utilities.** The Web Audio API, `AudioWorklet`, `AnalyserNode`, and `MediaDevices` are **browser built-ins**: no runtime package is required, and none is recommended. Libraries like Tone.js or Howler.js are excluded (§5). The only audio-related package is the type shim below.
| Package | Version | Why | Notes |
|---|---|---|---|
| `@types/audioworklet` *(dev)* | `^0.0.100` | Types for `AudioWorkletProcessor`, `registerProcessor`, and the worklet global scope, used by `// @ts-check` in the `.js` processors and by any future TypeScript worklet sources. | Add `"types": ["audioworklet"]` only in a dedicated `tsconfig.worklet.json`, **not** in the app tsconfig (it conflicts with DOM lib globals). |
### 3.3 UI, layout & icons
| Package | Version | Why it is needed | Notes |
|---|---|---|---|
| `tailwindcss` *(dev)* | `^4.3.3` | Utility CSS, design tokens via `@theme` (glow shadows, state colors, glass surfaces), custom `@utility` classes (`glass`, `glow-*`). | v4 reads tokens from CSS; there is **no `tailwind.config.js`** by default. |
| `@tailwindcss/postcss` *(dev)* | `^4.3.3` | The PostCSS plugin the Angular build calls via `.postcssrc.json`. It also handles vendor prefixing and `@import` inlining. | |
| `postcss` *(dev)* | `^8.5.28` | Required by `@tailwindcss/postcss` and by the Angular CSS pipeline. | |
| `autoprefixer` | **not installed** | You asked for it, and it is the right choice on Tailwind v3. On **Tailwind v4 it is redundant**: prefixing is built into `@tailwindcss/postcss`. Adding it only adds build time. | If you stay on Tailwind v3 (Angular 18), install `autoprefixer ^10.6.1` and use `tailwind.config.js`. |
| `@lucide/angular` | `^1.52.0` | Tree-shakeable Lucide icons as Angular components. Used for mic, stop, transcript, upload, trash, edit, status icons. | Replaces the deprecated `lucide-angular`. Register only the icons you use through the wrapper in `shared/ui/icons` so unused icons never reach the bundle. Follow the package README for its exact component/directive API. |
| `ag-grid-community` | `^36.2.0` | Grid engine for the Q&A pairs: virtualized rows, inline editing, quick filter, column filters, row selection. | Register modules once (see §6.3). Keep community and angular wrapper on the **same version**. |
| `ag-grid-angular` | `^36.2.0` | Angular wrapper (`<ag-grid-angular>`), signal-friendly inputs, cell renderer components. | Peer: `@angular/core >= 20`. |
| `prettier-plugin-tailwindcss` *(dev)* | `^0.8.1` | Deterministic class ordering in templates. | |
**AG Grid vs. a custom Tailwind table.** The default plan is AG Grid because the grid needs inline editing, filtering, selection, and virtualization over potentially tens of thousands of Q&A rows. A Tailwind table remains a valid fallback for under roughly 500 rows. Both live behind `QaGridComponent`'s inputs/outputs, so swapping is a one-component change. Choosing the Tailwind table lets you drop both `ag-grid-*` packages.
### 3.4 Parsing & transport
| Package | Version | Why it is needed | Notes |
|---|---|---|---|
| `papaparse` | `^5.7.0` | Client-side CSV preview (first N rows), delimiter and header detection, row validation (`MISSING_QUESTION`, `MISSING_ANSWER`) before upload. | Lazy-load with `import('papaparse')`. Use `preview: N` for the preview and `chunk`/`step` streaming for counting rows in large files. **Do not rely on `worker: true`** under bundlers: PapaParse builds its worker from its own script URL, which commonly breaks once bundled; test it before depending on it. |
| `@types/papaparse` *(dev)* | `^5.5.2` | Types for PapaParse. | |
| WebSocket client | **none (native `WebSocket`)** | The browser's `WebSocket` supports binary frames (`binaryType = 'arraybuffer'`), which is exactly what the PCM protocol needs. Reconnect, backoff, heartbeat, and framing are ~150 lines in `core/websocket`. | See the Socket.IO note below. |
**Why not Socket.IO.** `socket.io-client` (latest `4.8.4`) speaks the Socket.IO protocol, which only works against a Socket.IO server and adds its own packet framing, optional long-polling transport, and event envelope on top of WebSocket. For a latency-critical raw-PCM stream with a custom 16-byte binary header (`ARCHITECTURE.md` §5.2), that is overhead without benefit. **Use it only if your backend is already Socket.IO.** In that case, install `socket.io-client@^4.8.4` and write a `SocketIoTransport implements RealtimeTransport` adapter; nothing else in the app changes, because everything consumes the transport interface.
### 3.5 Optional packages (add only if you need them)
The default design uploads files and lets the server do real parsing. The browser only validates type, size, and **magic bytes** (no library needed) and previews CSV. Add these only if you want richer previews:
| Package | Version | Purpose | Cost / caveat |
|---|---|---|---|
| `pdfjs-dist` | `^6.4.299` | Page count and first-page text preview of a PDF before upload. | Large; needs its worker file served as a static asset. Lazy-load behind the preview panel only. |
| `mammoth` | `^1.13.0` | DOCX → plain text/HTML preview in the browser. | Sizeable; lazy-load. A server-side preview is often simpler. |
| `socket.io-client` | `^4.8.4` | Only if the backend is Socket.IO (see §3.4). | Adds protocol overhead. |
---
## 4. `devDependencies`, justified
| Package | Version | Why |
|---|---|---|
| `@angular/cli` | `^22.2.1` | `ng serve`, `ng build`, `ng test`, `ng generate`, `ng update`. |
| `@angular/build` | `^22.2.1` | The esbuild/Vite-based builders (`application`, `dev-server`, `unit-test`). Supports the `loader` option used to import `.glsl` shader files as strings. |
| `@angular/compiler-cli` | `^22.2.1` | AOT compiler and `ngc`. Pins the supported TypeScript range (`>=6.0 <6.1`). |
| `typescript` | `~6.0.3` | Language and type checker; **tilde-pinned to the supported minor** (see §0, finding 2). |
| `tailwindcss`, `@tailwindcss/postcss`, `postcss` | see §3.3 | Styling pipeline. |
| `prettier`, `prettier-plugin-tailwindcss` | `^3.9.9`, `^0.8.1` | Formatting and class sorting. |
| `eslint`, `angular-eslint`, `typescript-eslint` | `^10.12.0`, `^22.5.0`, `^8.71.0` | Linting, including Angular template rules (`prefer-on-push-component-change-detection`, `prefer-signals`-style rules, `no-restricted-imports` to enforce the `shared ← core ← features` dependency rule). `typescript-eslint` supports TypeScript `<6.1`. |
| `vitest`, `jsdom` | `^5.0.3`, `^30.1.2` | Unit/integration tests through `@angular/build:unit-test`. Used for the transition table, frame codec, PCM utilities, stores, and components. Worklet processors are tested by loading the class into a fake worklet scope. |
| `@playwright/test` | `^1.63.0` | E2E: fake-microphone flags (`--use-fake-device-for-media-stream`), mock WebSocket gateway, and the "zero change-detection ticks" performance assertion. |
| `@types/three`, `@types/papaparse`, `@types/audioworklet`, `@types/node` | see §2 | Type packages. `@types/node` is for config files and test tooling only. |
---
## 5. Deliberately excluded
| Package | Why it is not here |
|---|---|
| `autoprefixer` | Redundant with Tailwind v4 (§3.3). |
| `lucide-angular` | Deprecated; conflicts with Angular 22 peers. Use `@lucide/angular`. |
| `socket.io-client` | Needs a Socket.IO server; unnecessary overhead for raw PCM (§3.4). Optional only. |
| `@ngrx/*` (Store, SignalStore) | The app has three small stores (`VoiceStateStore`, `FaqStore`, `AppSettingsStore`) with one writer each. Plain signals are sufficient and keep the zoneless story simple. Revisit if a fourth cross-feature store appears. |
| `@angular/material` | Duplicates CDK + Tailwind and conflicts with the glassmorphic design language. |
| `tone`, `howler`, `wavesurfer.js` | The app needs low-level PCM control through `AudioWorklet`; these add abstraction and bundle weight without helping. |
| `@angular/animations` | Not used: state transitions are CSS (Tailwind) and shader uniforms. |
| `lodash`, `moment`, `uuid` | Native `structuredClone`, `Intl`, and `crypto.randomUUID()` cover the need. |
| `ngx-papaparse`, `ngx-socket-io` | Thin, often lagging wrappers. Our own services (`CsvParserService`, `WebSocketService`) are small and zoneless-safe. |
| `three-stdlib`, `postprocessing` | Not needed for v1 (§3.2). |
---
## 6. Configuration these packages require
### 6.1 Tailwind v4 with the Angular build
`/.postcssrc.json` (project root, **not** inside `src/`):
```json
{
"plugins": {
"@tailwindcss/postcss": {}
}
}
```
`src/styles.css` starts with `@import "tailwindcss";` (full file in `SRC_STRUCTURE.md`). There is no `tailwind.config.js` and no `content` array; Tailwind v4 detects sources automatically.
### 6.2 `angular.json` fragments
```jsonc
{
"projects": {
"voice-faq-app": {
"schematics": {
// Keep ".component.ts" / ".service.ts" suffixes (Angular 20+ CLI omits them by default)
"@schematics/angular:component": { "type": "component", "changeDetection": "OnPush", "style": "none", "skipTests": false },
"@schematics/angular:directive": { "type": "directive" },
"@schematics/angular:service": { "type": "service" }
},
"architect": {
"build": {
"builder": "@angular/build:application",
"options": {
"browser": "src/main.ts",
"tsConfig": "tsconfig.app.json",
"styles": ["src/styles.css"],
// Zone phase only. Delete this line at the zoneless milestone:
"polyfills": ["zone.js"],
"assets": [
{ "glob": "favicon.ico", "input": "src", "output": "/" },
{ "glob": "**/*", "input": "src/assets", "output": "assets" }
],
// Import shader sources as strings: import vert from './orb.vert.glsl'
"loader": { ".glsl": "text", ".vert": "text", ".frag": "text" }
},
"configurations": {
"production": {
"budgets": [
{ "type": "initial", "maximumWarning": "250kB", "maximumError": "400kB" },
{ "type": "anyComponentStyle", "maximumWarning": "4kB", "maximumError": "8kB" }
],
"outputHashing": "all",
"fileReplacements": [
{ "replace": "src/environments/environment.ts", "with": "src/environments/environment.production.ts" }
]
},
"development": { "optimization": false, "extractLicenses": false, "sourceMap": true }
}
},
"test": {
"builder": "@angular/build:unit-test",
"options": { "tsConfig": "tsconfig.spec.json", "runner": "vitest", "buildTarget": "::development" }
}
}
}
}
}
```
Notes:
- `src/assets` is copied verbatim and is **not hashed**. Worklet files are fetched by URL at runtime, so load them with a version query (`pcm-capture-processor.js?v=<buildId>`) or the browser may run a stale processor after a deploy.
- The initial budget (`250 kB` warning) is what enforces lazy-loading of Three.js, AG Grid, and PapaParse.
### 6.3 AG Grid module registration (once, in the lazy `qa-grid` entry)
```ts
// features/faq-manager/grid/register-grid-modules.ts
import { AllCommunityModule, ModuleRegistry } from 'ag-grid-community';
let registered = false;
export function registerGridModules(): void {
if (registered) return;
ModuleRegistry.registerModules([AllCommunityModule]);
registered = true;
}
```
`AllCommunityModule` is the simplest correct start. Before production, replace it with only the modules you use (client-side row model, text editors, filters, row selection) following AG Grid's module-selection guide, to shrink the grid chunk. Theming uses AG Grid's JavaScript theme API, so **no AG Grid CSS imports** are needed in `styles.css`.
### 6.4 `tsconfig` essentials
```jsonc
// tsconfig.json (excerpt)
{
"compilerOptions": {
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"isolatedModules": true,
"target": "ES2022",
"module": "preserve",
"moduleResolution": "bundler",
"lib": ["ES2022", "dom", "dom.iterable"],
"paths": {
"@core/*": ["src/app/core/*"],
"@features/*": ["src/app/features/*"],
"@shared/*": ["src/app/shared/*"],
"@env/*": ["src/environments/*"]
}
},
"angularCompilerOptions": {
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
```
Add a one-line ambient declaration so shader imports type-check (`declare module '*.glsl' { const source: string; export default source; }`), kept in `src/app/core/audio/visualizer/shader-source.d.ts`.
### 6.5 Lazy-loading map (what must stay out of the initial bundle)
| Package | Loaded when | How |
|---|---|---|
| `three` | The voice page's orb mounts | `await import('three')` inside `ThreeOrbVisualizer.create()` |
| `ag-grid-*` | The FAQ grid first renders | Route-level lazy feature + dynamic import in `QaGridComponent` |
| `papaparse` | A CSV is dropped | `await import('papaparse')` inside `CsvParserService` |
| `pdfjs-dist`, `mammoth` (if used) | The preview panel opens | Dynamic import in the preview component |
| `@angular/cdk/overlay`, `/dialog` | The drawer or modal opens | Tree-shaken per entry point; opened through a small service |
---
## 7. Install & maintenance
```bash
# 1. Runtime and tooling
nvm install 24 && nvm use 24
# 2. Create the project (Angular 22), zoneless, no routing scaffolding conflicts
npx @angular/cli@22 new voice-faq-app --style=css --routing --ssr=false
cd voice-faq-app
# 3. Runtime dependencies
npm i @angular/cdk@^22.2.1 @lucide/angular@^1.52.0 \
ag-grid-angular@^36.2.0 ag-grid-community@^36.2.0 \
papaparse@^5.7.0 three@~0.186.1
# 4. Dev dependencies
npm i -D tailwindcss@^4.3.3 @tailwindcss/postcss@^4.3.3 postcss@^8.5.28 \
@types/three@~0.186.0 @types/papaparse@^5.5.2 @types/audioworklet@^0.0.100 \
prettier prettier-plugin-tailwindcss @playwright/test
# 5. Make sure TypeScript stayed in the supported range
npm ls typescript # expect 6.0.x
```
**Version policy**
- **Angular packages:** move together using `ng update @angular/core @angular/cli @angular/cdk` (never bump one alone).
- **`three` and `@types/three`:** tilde-pinned; upgrade deliberately, one minor at a time, reading the migration notes and running the visual regression screenshot of each of the five orb states.
- **AG Grid:** `ag-grid-community` and `ag-grid-angular` always share an identical version.
- **Automation:** enable Renovate or Dependabot with groups (`angular`, `ag-grid`, `three`, `tailwind`, `tooling`) and require CI (lint, unit, E2E, bundle budgets) to pass.
- **Audit:** `npm audit --omit=dev` in CI; fail on high severity in runtime dependencies.
- **Lockfile:** commit `package-lock.json`; use `npm ci` in CI.
+649
View File
@@ -0,0 +1,649 @@
# SRC_STRUCTURE.md — `src/` Directory Architecture
> **Companion to:** `ARCHITECTURE.md`, `DEPENDENCIES.md`
> **Targets:** Angular 22 · standalone components · Signals · `ChangeDetectionStrategy.OnPush` · zoneless (with a Zone.js-compatible phase)
### Changes relative to `ARCHITECTURE.md`
This document is now the canonical layout. Four things moved or were renamed:
| Was (`ARCHITECTURE.md`) | Now | Reason |
|---|---|---|
| `core/state/` | `core/services/` (stores) + `core/models/` (types) | Matches the requested `core/services/` for global state and local storage |
| `features/voice-agent/services/visualizer/` | `core/audio/visualizer/` | The Three.js engine has no feature-specific logic; the voice feature only hosts the `<canvas>` |
| `core/audio/worklets/*.worklet.js` | `src/assets/worklets/pcm-*.js` | Worklets run in their own global scope and are fetched by URL, so they live in assets |
| `provideExperimentalZonelessChangeDetection` | `provideZonelessChangeDetection` | The experimental name does not exist in Angular 22 (see `DEPENDENCIES.md` §0) |
---
## 1. Full tree
```text
voice-faq-app/
├─ .postcssrc.json # Tailwind v4 PostCSS plugin (project root)
├─ angular.json · package.json · tsconfig*.json · eslint.config.js · playwright.config.ts · .nvmrc
│
└─ src/
├─ index.html
├─ main.ts
├─ styles.css
├─ favicon.ico
│
├─ styles/
│ ├─ theme.css # @theme tokens: colors, glow shadows, fonts, keyframes
│ └─ utilities.css # @utility glass, glow-*, scrollbar, focus ring
│
├─ environments/
│ ├─ environment.ts # development defaults
│ └─ environment.production.ts # production values (file-replaced at build)
│
├─ assets/
│ ├─ worklets/
│ │ ├─ pcm-capture-processor.js # mic -> 20 ms Int16 frames (audio thread)
│ │ └─ pcm-playback-processor.js # ring/jitter buffer -> speakers (audio thread)
│ └─ textures/
│ └─ .gitkeep # empty in v1 (orb noise is procedural)
│
└─ app/
├─ app.component.ts
├─ app.config.ts
├─ app.routes.ts
│
├─ core/
│ ├─ config/
│ │ ├─ app-config.token.ts # APP_CONFIG injection token + typed AppConfig
│ │ └─ app-config.provider.ts # provideAppConfig() reads environment
│ │
│ ├─ models/
│ │ ├─ voice.types.ts # VoiceState, VoiceEvent, VoiceSession, TranscriptEntry, VoiceError
│ │ ├─ protocol.types.ts # AudioFrame, ClientMessage, ServerMessage, AudioFormat
│ │ └─ app-error.ts # AppError class + error code union
│ │
│ ├─ audio/
│ │ ├─ audio-context.provider.ts # AUDIO_CONTEXT_HOLDER token, provideAudio(), lazy AudioContext
│ │ ├─ audio.tokens.ts # AUDIO_CONFIG (sample rates, frame ms, prebuffer ms, fftSize)
│ │ ├─ audio.types.ts # worklet command/event unions
│ │ ├─ audio-engine.service.ts # orchestrates mic, nodes, analysers, mute/flush/play
│ │ ├─ mic-capture.service.ts # getUserMedia, device list, permission signal
│ │ ├─ pcm-capture.node.ts # typed wrapper around the capture AudioWorkletNode
│ │ ├─ pcm-playback.node.ts # typed wrapper around the playback AudioWorkletNode
│ │ ├─ audio-level-bus.ts # mutable per-frame levels shared with the visualizer
│ │ ├─ pcm-utils.ts # float<->int16, resample, RMS
│ │ └─ visualizer/
│ │ ├─ visualizer.interface.ts # Visualizer contract (init/applyState/resize/dispose)
│ │ ├─ visualizer.service.ts # VisualizerEngine: rAF loop outside NgZone
│ │ ├─ audio-visualizer.directive.ts# attribute directive placed on <canvas>
│ │ ├─ three-orb.visualizer.ts # WebGL implementation (lazy `import('three')`)
│ │ ├─ canvas2d.visualizer.ts # fallback when WebGL is unavailable or lost
│ │ ├─ state-presets.ts # per-state color, turbulence, easing, source
│ │ ├─ shader-source.d.ts # declare module '*.glsl'
│ │ └─ shaders/
│ │ ├─ orb.vert.glsl # displacement by level + noise
│ │ └─ orb.frag.glsl # fresnel glow, state color blend
│ │
│ ├─ websocket/
│ │ ├─ realtime-transport.ts # abstract RealtimeTransport (WS today, WebRTC later)
│ │ ├─ websocket.service.ts # WebSocket implementation of the transport
│ │ ├─ connection.machine.ts # connection state machine (pure reducer)
│ │ ├─ reconnect-policy.ts # exponential backoff with jitter
│ │ ├─ heartbeat.ts # ping/pong watchdog
│ │ ├─ frame-codec.ts # 16-byte binary header encode/decode
│ │ └─ audio-stream.handler.ts # sequencing, turnId filter, hand-off to playback node
│ │
│ ├─ services/
│ │ ├─ voice-state.store.ts # voiceState, activeSession, transcript signals
│ │ ├─ app-settings.store.ts # persisted preferences (device, volume, transcript open)
│ │ ├─ storage.service.ts # typed, versioned localStorage wrapper
│ │ ├─ auth.service.ts # short-lived WebSocket ticket and HTTP token
│ │ ├─ browser-capabilities.service.ts # AudioWorklet / getUserMedia / WebGL checks
│ │ ├─ notification.service.ts # toast queue (signal)
│ │ ├─ telemetry.service.ts # latency marks, underruns, transitions (no PII)
│ │ └─ logger.service.ts # leveled logger, silenced in production
│ │
│ ├─ guards/
│ │ ├─ auth.guard.ts
│ │ ├─ browser-support.guard.ts
│ │ └─ unsaved-changes.guard.ts
│ │
│ └─ interceptors/
│ ├─ auth.interceptor.ts
│ ├─ retry.interceptor.ts
│ └─ error.interceptor.ts
│
├─ features/
│ ├─ voice-agent/
│ │ ├─ voice-agent.routes.ts
│ │ ├─ voice-agent.page.ts
│ │ ├─ components/
│ │ │ ├─ voice-orb/
│ │ │ │ ├─ voice-orb.component.ts
│ │ │ │ └─ voice-orb.component.html
│ │ │ ├─ mic-control-bar/
│ │ │ ├─ transcript-overlay/
│ │ │ ├─ status-badge/
│ │ │ ├─ faq-suggestions/
│ │ │ └─ mic-permission-prompt/
│ │ └─ services/
│ │ ├─ voice-session.service.ts # the only writer of voiceState
│ │ ├─ voice-transitions.ts # TRANSITIONS table + guards (pure data/functions)
│ │ ├─ voice-effects.ts # side effects per transition (engine + socket)
│ │ └─ barge-in-detector.service.ts # client energy gate for instant interruption
│ │
│ └─ faq-manager/
│ ├─ faq-manager.routes.ts
│ ├─ faq-manager.page.ts
│ ├─ models/
│ │ └─ faq.types.ts
│ ├─ components/
│ │ ├─ faq-drawer/
│ │ ├─ file-dropzone/
│ │ ├─ upload-preview-table/
│ │ ├─ document-list/
│ │ ├─ qa-grid/
│ │ └─ qa-editor-modal/
│ ├─ grid/
│ │ ├─ register-grid-modules.ts
│ │ ├─ qa-grid.columns.ts
│ │ ├─ qa-grid.theme.ts
│ │ └─ cell-renderers/
│ │ ├─ status-cell.renderer.ts
│ │ ├─ tags-cell.renderer.ts
│ │ └─ actions-cell.renderer.ts
│ ├─ services/
│ │ ├─ faq-store.ts
│ │ ├─ faq-api.service.ts
│ │ ├─ faq-ingestion.service.ts
│ │ ├─ ingestion-events.service.ts
│ │ ├─ file-validator.service.ts
│ │ ├─ csv-parser.service.ts
│ │ └─ faq-drawer.service.ts
│ └─ utils/
│ ├─ file-signatures.ts
│ └─ csv-column-detect.ts
│
└─ shared/
├─ ui/
│ ├─ button/
│ ├─ icon-button/
│ ├─ badge/
│ ├─ icon/ # <app-icon> + central Lucide registry (icons.ts)
│ ├─ glass-panel/
│ ├─ drawer-shell/
│ ├─ dialog-shell/
│ ├─ toast-host/
│ ├─ spinner/
│ ├─ progress-bar/
│ ├─ skeleton/
│ └─ empty-state/
├─ directives/
│ ├─ glass-panel.directive.ts
│ ├─ state-glow.directive.ts
│ ├─ file-drop.directive.ts
│ ├─ autofocus.directive.ts
│ └─ resize-observer.directive.ts
├─ pipes/
│ ├─ file-size.pipe.ts
│ ├─ relative-time.pipe.ts
│ ├─ duration.pipe.ts
│ └─ truncate.pipe.ts
└─ utils/
├─ assert.ts
├─ id.ts
├─ math.ts
└─ raf-throttle.ts
```
### Dependency rule (enforce with ESLint `no-restricted-imports`)
```text
shared <- core <- features
```
- `shared` imports nothing from `core` or `features`.
- `core` imports from `shared` only (and never from `features`).
- A feature imports from `core` and `shared`, **never from another feature**. If both features need something, it moves to `core` or `shared`.
- `core/audio` and `core/websocket` import no UI (no components, no CDK), so they can be unit-tested without a DOM.
**Path aliases:** `@core/*`, `@features/*`, `@shared/*`, `@env/*` (see `DEPENDENCIES.md` §6.4).
---
## 2. Root configuration files (full contents)
### 2.1 `src/main.ts`
```ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));
```
### 2.2 `src/app/app.config.ts`
```ts
import {
ApplicationConfig,
provideBrowserGlobalErrorListeners,
provideZonelessChangeDetection,
// provideZoneChangeDetection, // <- zone phase: use this instead (needs "zone.js" in polyfills)
} from '@angular/core';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';
import { provideAppConfig } from '@core/config/app-config.provider';
import { provideAudio } from '@core/audio/audio-context.provider';
import { authInterceptor } from '@core/interceptors/auth.interceptor';
import { retryInterceptor } from '@core/interceptors/retry.interceptor';
import { errorInterceptor } from '@core/interceptors/error.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
// Zoneless (target). Angular 18/19 name: provideExperimentalZonelessChangeDetection().
provideZonelessChangeDetection(),
// Zone phase alternative: provideZoneChangeDetection({ eventCoalescing: true }),
provideBrowserGlobalErrorListeners(),
provideRouter(routes, withComponentInputBinding()),
provideHttpClient(
withFetch(),
withInterceptors([authInterceptor, retryInterceptor, errorInterceptor]),
),
provideAppConfig(),
provideAudio(), // registers AUDIO_CONFIG + the lazy AudioContext holder (no context is created yet)
],
};
```
### 2.3 `src/app/app.routes.ts`
```ts
import { Routes } from '@angular/router';
import { authGuard } from '@core/guards/auth.guard';
import { browserSupportGuard } from '@core/guards/browser-support.guard';
import { unsavedChangesGuard } from '@core/guards/unsaved-changes.guard';
export const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'voice' },
{
path: 'voice',
title: 'Voice FAQ',
canActivate: [browserSupportGuard, authGuard],
loadChildren: () =>
import('@features/voice-agent/voice-agent.routes').then((m) => m.VOICE_AGENT_ROUTES),
},
{
path: 'knowledge-base',
title: 'Knowledge Base',
canActivate: [authGuard],
canDeactivate: [unsavedChangesGuard],
loadChildren: () =>
import('@features/faq-manager/faq-manager.routes').then((m) => m.FAQ_MANAGER_ROUTES),
},
{
path: 'unsupported',
title: 'Browser not supported',
loadComponent: () =>
import('@shared/ui/empty-state/empty-state.component').then((m) => m.EmptyStateComponent),
data: { reason: 'unsupported-browser' },
},
{ path: '**', redirectTo: 'voice' },
];
```
### 2.4 `src/app/app.component.ts`
```ts
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ToastHostComponent } from '@shared/ui/toast-host/toast-host.component';
@Component({
selector: 'app-root',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [RouterOutlet, ToastHostComponent],
template: `
<main class="min-h-dvh bg-void-950 text-slate-100 antialiased">
<router-outlet />
</main>
<app-toast-host />
`,
})
export class AppComponent {}
```
### 2.5 `src/styles.css`
```css
@import 'tailwindcss';
@import './styles/theme.css';
@import './styles/utilities.css';
:root {
color-scheme: dark;
}
html,
body {
height: 100%;
background: var(--color-void-950);
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
```
### 2.6 `src/styles/theme.css`
```css
@theme {
/* Surfaces */
--color-void-950: #05060a;
--color-void-900: #0a0c14;
--color-void-800: #11141f;
/* Voice state colors (shared by the orb shader presets and the status badge) */
--color-state-idle: #5b6b8c;
--color-state-listening: #22d3ee;
--color-state-processing: #a78bfa;
--color-state-speaking: #34d399;
--color-state-interrupted: #fb7185;
/* Glow shadows */
--shadow-glow-idle: 0 0 24px rgb(91 107 140 / 0.35);
--shadow-glow-listening: 0 0 28px rgb(34 211 238 / 0.55), 0 0 80px rgb(34 211 238 / 0.2);
--shadow-glow-processing: 0 0 28px rgb(167 139 250 / 0.55), 0 0 80px rgb(167 139 250 / 0.2);
--shadow-glow-speaking: 0 0 28px rgb(52 211 153 / 0.55), 0 0 80px rgb(52 211 153 / 0.2);
--shadow-glow-interrupted: 0 0 28px rgb(251 113 133 / 0.6), 0 0 80px rgb(251 113 133 / 0.25);
--font-sans: 'Inter', ui-sans-serif, system-ui, sans-serif;
--animate-breathe: breathe 6s ease-in-out infinite;
--animate-slide-in-end: slide-in-end 220ms cubic-bezier(0.22, 1, 0.36, 1);
@keyframes breathe {
0%, 100% { transform: scale(1); opacity: 0.85; }
50% { transform: scale(1.04); opacity: 1; }
}
@keyframes slide-in-end {
from { transform: translateX(calc(var(--dir, 1) * 100%)); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
}
```
### 2.7 `src/styles/utilities.css`
```css
/* Glassmorphic surface: use as `class="glass"` or through GlassPanelDirective */
@utility glass {
background: rgb(15 18 30 / 0.55);
-webkit-backdrop-filter: blur(16px) saturate(140%);
backdrop-filter: blur(16px) saturate(140%);
border: 1px solid rgb(255 255 255 / 0.08);
box-shadow: inset 0 1px 0 rgb(255 255 255 / 0.06), 0 10px 40px rgb(0 0 0 / 0.45);
}
@utility glass-strong {
background: rgb(10 12 20 / 0.78);
-webkit-backdrop-filter: blur(24px) saturate(160%);
backdrop-filter: blur(24px) saturate(160%);
border: 1px solid rgb(255 255 255 / 0.1);
}
/* Glow rings per voice state */
@utility glow-idle { box-shadow: var(--shadow-glow-idle); }
@utility glow-listening { box-shadow: var(--shadow-glow-listening); }
@utility glow-processing { box-shadow: var(--shadow-glow-processing); }
@utility glow-speaking { box-shadow: var(--shadow-glow-speaking); }
@utility glow-interrupted { box-shadow: var(--shadow-glow-interrupted); }
@utility focus-ring {
outline: 2px solid var(--color-state-listening);
outline-offset: 2px;
}
@utility scrollbar-thin-dark {
scrollbar-width: thin;
scrollbar-color: rgb(255 255 255 / 0.2) transparent;
}
```
### 2.8 `src/index.html`
```html
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>Voice FAQ</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="color-scheme" content="dark" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
<noscript>This application requires JavaScript and microphone access.</noscript>
</body>
</html>
```
### 2.9 `src/environments/environment.ts`
```ts
export const environment = {
production: false,
apiBaseUrl: 'http://localhost:8080/api',
wsUrl: 'ws://localhost:8080/realtime',
workletVersion: 'dev', // appended as ?v= to worklet URLs
features: { webrtc: false, clientVad: true },
} as const;
```
`environment.production.ts` has the same shape with `production: true`, `https`/`wss` URLs, and `workletVersion` injected from the CI build id.
---
## 3. `src/app/core/` in detail
### 3.1 `core/config/` and `core/models/`
| File | Purpose |
|---|---|
| `app-config.token.ts` | `AppConfig` interface (`apiBaseUrl`, `wsUrl`, `workletVersion`, `features`) and `APP_CONFIG` `InjectionToken`. Everything that needs a URL injects this instead of importing `environment` directly (easy to override in tests). |
| `app-config.provider.ts` | `provideAppConfig()` returns `{ provide: APP_CONFIG, useValue: environment }`. |
| `voice.types.ts` | `VoiceState`, `VoiceEvent`, `VoiceSession`, `TranscriptEntry`, `VoiceError` exactly as in `ARCHITECTURE.md` §5.1. Framework-free. |
| `protocol.types.ts` | `AudioFormat`, `AudioFrame`, `ClientMessage`, `ServerMessage` (§5.2). Framework-free, shareable with the backend repo. |
| `app-error.ts` | `class AppError extends Error { code; recoverable; cause? }` plus the code union. The error interceptor and `VoiceError` mapping use it. |
### 3.2 `core/audio/`
| File | Purpose |
|---|---|
| `audio-context.provider.ts` | Exports `AUDIO_CONTEXT_HOLDER` and `provideAudio()`. The holder **does not create an `AudioContext` at startup** (autoplay policy). It exposes `ensureRunning()`, called from the first user gesture (the orb click), which creates `new AudioContext({ latencyHint: 'interactive', sampleRate })`, loads both worklet modules, and resumes the context. Exposes a `state` signal (`'none' \| 'suspended' \| 'running' \| 'closed'`). |
| `audio.tokens.ts` | `AUDIO_CONFIG`: `captureSampleRate` (16000), `playbackSampleRate` (24000), `frameMs` (20), `prebufferMs` (80), `analyserFftSize` (256), `bandCount` (64). |
| `audio.types.ts` | `CaptureCommand`, `PlaybackCommand`, `PlaybackEvent` unions (§5.3). |
| `audio-engine.service.ts` | The facade the voice feature talks to: `start()`, `stop()`, `unmuteCapture()`, `muteCapture()`, `startPlayback()`, `flushPlayback()`, `enqueueAgentFrame()`, plus event streams (`captureFrame$`, `playback$`). Builds the node graph, owns both analysers, and writes `AudioLevelBus` every frame. Creates its listeners **outside the zone**. |
| `mic-capture.service.ts` | `getUserMedia` with `echoCancellation`, `noiseSuppression`, `autoGainControl`, `channelCount: 1`; `enumerateDevices()`; exposes `permission` (`'prompt' \| 'granted' \| 'denied'`) and `devices` signals; handles device-change events and `NotAllowedError`/`NotFoundError` mapping to `VoiceError`. |
| `pcm-capture.node.ts` | Creates the `AudioWorkletNode('pcm-capture-processor')`, sends `{ type: 'active' }`, and surfaces transferred `ArrayBuffer` frames as a typed callback. Returns used buffers to a pool. |
| `pcm-playback.node.ts` | Creates `AudioWorkletNode('pcm-playback-processor')`; methods `config()`, `push(frame)`, `flush()`, `endOfTurn()`; surfaces `started`, `drained`, `underrun`, `level` events. |
| `audio-level-bus.ts` | The per-frame shared buffer (`inputRms`, `outputRms`, `inputBands`, `outputBands`). A plain class, **not signals**: this is the documented exception that keeps the render loop out of change detection. |
| `pcm-utils.ts` | `floatToInt16`, `int16ToFloat`, `resampleLinear`, `rms`, and `bytesToMs`. Pure functions, unit-tested with golden arrays. |
#### 3.2.1 `core/audio/visualizer/`
| File | Purpose |
|---|---|
| `visualizer.interface.ts` | `interface Visualizer { init(canvas): Promise<void>; applyState(state): void; resize(w, h, dpr): void; render(t): void; dispose(): void; }`. Lets WebGL and Canvas 2D be interchangeable. |
| `visualizer.service.ts` | `VisualizerEngine` (component-scoped provider). `start(canvas)` calls `NgZone.runOutsideAngular`, picks the implementation (WebGL → fallback), runs the `requestAnimationFrame` loop, pauses on `visibilitychange` and `IntersectionObserver`, monitors frame time to step quality down, and cleans up through `DestroyRef`. `applyState()` only swaps a target preset object; the loop eases toward it. |
| `audio-visualizer.directive.ts` | Selector `canvas[appAudioVisualizer]`. Inputs: `state` (signal `input<VoiceState>()`). Creates the engine in `afterNextRender`, wires a `ResizeObserver` (outside the zone), and runs an `effect()` that calls `engine.applyState(state())`. The directive is the only Angular-facing surface of the visualizer. |
| `three-orb.visualizer.ts` | `await import('three')`; builds `WebGLRenderer` (DPR capped at 2), `PerspectiveCamera`, an `IcosahedronGeometry` orb with `ShaderMaterial`, uniforms `uTime`, `uLevel`, `uTurbulence`, `uColor`, `uFresnel`. Reads `AudioLevelBus` each frame; selects input bands in `listening`, output bands in `speaking`, a synthetic pulse in `processing`. Handles `webglcontextlost`/`restored`. Disposes geometry, material, and renderer. |
| `canvas2d.visualizer.ts` | Radial bar/waveform fallback with the same preset system. Used when WebGL is unavailable, context restore fails, or `prefers-reduced-motion` requests a calmer mode. |
| `state-presets.ts` | `STATE_PRESETS: Record<VoiceState, { color, turbulence, levelGain, easing, source }>`. Colors reference the same tokens as `theme.css`. |
| `shader-source.d.ts` | `declare module '*.glsl' { const source: string; export default source; }` so shaders can be imported as strings (the `loader` option in `angular.json`). |
| `shaders/orb.vert.glsl` | Vertex displacement: simplex noise scaled by `uLevel` and `uTurbulence`. |
| `shaders/orb.frag.glsl` | Fresnel rim glow and state color blend (the glow is computed here, not with post-processing). |
> **Shader placement note.** Shaders live beside the visualizer and are imported as text at build time instead of being fetched from `assets/`. This removes a network request and the "orb appears before its shader loads" flash. `assets/textures/` exists for later texture-based effects and is intentionally empty in v1.
### 3.3 `core/websocket/`
| File | Purpose |
|---|---|
| `realtime-transport.ts` | `abstract class RealtimeTransport { connect(); disconnect(); sendAudio(buf); sendControl(msg); readonly audio$; readonly control$; readonly status: Signal<ConnectionStatus>; }`. `VoiceSessionService` depends only on this class. |
| `websocket.service.ts` | `WebSocketService extends RealtimeTransport`. Sets `binaryType = 'arraybuffer'`, sends `session.start` (with the ticket) on open, parses text frames to `ServerMessage`, routes binary frames to `AudioStreamHandler`, and runs all socket callbacks **outside the zone**. Re-enters Angular only by writing the `status` signal or emitting control events. |
| `connection.machine.ts` | The **connection** state machine as a pure reducer: `disconnected → connecting → connected → reconnecting → failed`, with events `OPEN`, `CLOSE`, `ERROR`, `RETRY`, `GIVE_UP`, `USER_DISCONNECT`. Separate from the voice machine so transport failures never leak into voice-state logic. |
| `reconnect-policy.ts` | Backoff: 500 ms → 8 s, ×2, ±25% jitter, max attempts configurable; resets after a stable connection. |
| `heartbeat.ts` | Sends `ping` every 15 s and declares the link dead after two missed `pong`s, triggering a `CLOSE` event. |
| `frame-codec.ts` | `encodeAudioFrame()` / `decodeAudioFrame()` for the 16-byte little-endian header (`ARCHITECTURE.md` §5.2). Validates `version` and payload length; returns `null` for malformed frames (counted, never thrown). |
| `audio-stream.handler.ts` | The binary audio stream handler: tracks `seq` for loss/reorder detection, drops frames whose `turnIdHash` does not match the current turn (barge-in safety), transfers payloads to `PcmPlaybackNode`, and keeps counters for telemetry (dropped, late, bytes). |
### 3.4 `core/services/`
| File | Purpose |
|---|---|
| `voice-state.store.ts` | `voiceState`, `activeSession`, `transcript` as private writable signals with read-only public views and `computed` helpers (`isMicOpen`, `canInterrupt`). Only `VoiceSessionService` calls its underscore-prefixed mutators. |
| `app-settings.store.ts` | Persisted preferences signal: preferred input device id, output volume, transcript open/closed, reduced-motion override, locale. Loads from `StorageService` on init; an `effect()` writes back (debounced). |
| `storage.service.ts` | Typed `get/set/remove` over `localStorage` with a namespaced, versioned key (`vfaq:v1:<key>`), `try/catch` on every call, JSON validation with a fallback, and `storage`-event sync between tabs. Never stores audio, transcripts, or tokens. |
| `auth.service.ts` | Holds the HTTP bearer token (in memory) and `requestRealtimeTicket()` for the short-lived WebSocket ticket. Exposes `isAuthenticated` signal. |
| `browser-capabilities.service.ts` | One-time checks: `AudioWorklet`, `getUserMedia`, `WebSocket`, WebGL2 (optional), secure context. Exposes a `capabilities` signal consumed by `browserSupportGuard` and the orb fallback logic. |
| `notification.service.ts` | `toasts` signal (`{ id, kind, message, timeoutMs }[]`) with `show()` and `dismiss()`. Rendered by `ToastHostComponent`. |
| `telemetry.service.ts` | `mark('ttfa')`, `count('underrun')`, `transition(from, to, ms)`. Batches and sends via `navigator.sendBeacon`. No audio, transcripts, or file contents. |
| `logger.service.ts` | `debug/info/warn/error`; `debug` and `info` are no-ops in production. |
### 3.5 `core/guards/`
| File | Purpose |
|---|---|
| `auth.guard.ts` | Functional `CanActivateFn`: allows if `AuthService.isAuthenticated()`, otherwise tries a silent refresh, then redirects to the configured login URL. |
| `browser-support.guard.ts` | Functional guard: if `AudioWorklet`, `getUserMedia`, or `WebSocket` is missing (or the page is not a secure context), returns `router.parseUrl('/unsupported')`. |
| `unsaved-changes.guard.ts` | `CanDeactivateFn` for the knowledge-base route: if `FaqStore` has pending edits or an upload in progress, asks for confirmation through a CDK Dialog before leaving. |
### 3.6 `core/interceptors/`
| File | Purpose |
|---|---|
| `auth.interceptor.ts` | Adds `Authorization: Bearer …` to requests whose URL starts with `apiBaseUrl`; never to third-party URLs. |
| `retry.interceptor.ts` | Retries **idempotent** requests (GET/HEAD) on network failure and 502/503/504, max 2 times, with jittered backoff. Never retries uploads or mutations. |
| `error.interceptor.ts` | Maps `HttpErrorResponse` to `AppError`, raises a toast for user-visible failures (not for 401 handled by the auth flow), and rethrows. |
---
## 4. `src/app/features/` in detail
### 4.1 `features/voice-agent/`
| File / folder | Purpose |
|---|---|
| `voice-agent.routes.ts` | `VOICE_AGENT_ROUTES` (one route to `VoiceAgentPage`); provides route-scoped services (`VoiceSessionService`, `BargeInDetectorService`). |
| `voice-agent.page.ts` | Smart container. Injects `VoiceStateStore`, `VoiceSessionService`, `FaqStore`, and `FaqDrawerService`. Lays out the orb, status badge, control bar, transcript overlay, suggestions, and the button that opens the knowledge-base drawer. Contains no audio logic. |
| `components/voice-orb/` | Hosts `<canvas appAudioVisualizer [state]="state()">` inside a glass-ringed container with the state glow (`StateGlowDirective`). Inputs: `state`. Outputs: `orbClick` (the first click is the user gesture that starts audio). OnPush; no per-frame bindings. |
| `components/mic-control-bar/` | Mic toggle / push-to-talk, stop, mute-output, input device selector (popover). Inputs: `state`, `micPermission`, `devices`. Outputs: `toggleMic`, `stop`, `deviceChange`. Keyboard: Space toggles, Esc stops. |
| `components/transcript-overlay/` | Collapsible glass panel using CDK virtual scroll. Partial entries update in place; the latest entry has `aria-live="polite"`. Shows citation chips that open the source in the knowledge-base drawer. |
| `components/status-badge/` | Pill showing state icon, localized label, and glow color. Announces changes through CDK `LiveAnnouncer`. Color is never the only signal (icon + label + motion). |
| `components/faq-suggestions/` | Suggested question chips from `suggestions` messages; clicking one sends it as text input. |
| `components/mic-permission-prompt/` | Explains how to enable the microphone per browser when permission is `denied`, with a retry button. |
| `services/voice-session.service.ts` | The **only** writer of `voiceState`. `dispatch(event)` looks up `TRANSITIONS[current][event.type]`, evaluates guards, runs effects, then sets the state signal. Subscribes to `RealtimeTransport.control$` and `AudioEngine` events and converts them to `VoiceEvent`s. |
| `services/voice-transitions.ts` | Pure `TRANSITIONS` table and `guards` (minimum utterance length, barge-in debounce). No Angular imports. Table-driven tests live beside it. |
| `services/voice-effects.ts` | Maps each `(from, to, event)` to side effects: `unmuteCapture`, `muteCapture`, `flushPlayback` (local first), `sendControl({type:'interrupt', playedMs})`, and so on. Keeps `voice-session.service.ts` small. |
| `services/barge-in-detector.service.ts` | Client-side energy gate that runs while `speaking`: if input RMS stays above a threshold for ≥120 ms (echo-cancelled input), dispatches `BARGE_IN`. Reads `AudioLevelBus` on a 20 ms timer outside the zone. |
### 4.2 `features/faq-manager/`
| File / folder | Purpose |
|---|---|
| `faq-manager.routes.ts` | `FAQ_MANAGER_ROUTES`: the full-page knowledge-base route (`FaqManagerPage`). The drawer is opened from any page via `FaqDrawerService`. |
| `faq-manager.page.ts` | Full-page layout: `DocumentList` on the left, `QaGrid` on the right, dropzone on top. |
| `models/faq.types.ts` | `FaqDocument`, `FaqDocumentStatus` (`uploading \| indexing \| active \| error`), `QaPair`, `QaFilter`, `CsvPreview`, `CsvRowError`, `IngestionEvent` (`ARCHITECTURE.md` §5.4). |
| `components/faq-drawer/` | The slide-over (CDK Overlay) containing dropzone, preview, and document list. Glass surface, focus trap, Esc to close, slides in from the inline-end edge (RTL-aware). Opened and closed through `FaqDrawerService`. |
| `components/file-dropzone/` | Uses `FileDropDirective`. Accepts `.csv .json .pdf .docx`, shows drag-over state, runs `FileValidatorService`, and emits `filesAccepted` / `filesRejected`. |
| `components/upload-preview-table/` | For CSV: shows the first N parsed rows, auto-detected question/answer columns with manual remapping, and per-row validation errors. "Confirm" starts the upload. |
| `components/document-list/` | One row per document: name, type icon, size, `Badge` with status (`Uploading`, `Indexing`, `Active`, `Error`), progress bar, item count, enable toggle, retry/delete. |
| `components/qa-grid/` | AG Grid wrapper: inputs `rows`, `filter`; outputs `editRow`, `toggleOverride`, `bulkDelete`. Lazy-registers grid modules, applies the dark glass theme, supports inline edit, quick filter, and row selection. |
| `components/qa-editor-modal/` | CDK Dialog with a reactive form (question, answer, tags, enabled, "manual override"). Validates length, warns when overriding ingested content, and returns the saved `QaPair`. |
| `grid/register-grid-modules.ts` | One-time `ModuleRegistry.registerModules(...)` (see `DEPENDENCIES.md` §6.3). |
| `grid/qa-grid.columns.ts` | `ColDef[]` factory: question, answer (large text editor), tags, source, overridden, enabled, updated, actions. |
| `grid/qa-grid.theme.ts` | AG Grid theme built with the JS theme API, colors taken from the Tailwind tokens. |
| `grid/cell-renderers/` | `status-cell.renderer.ts`, `tags-cell.renderer.ts`, `actions-cell.renderer.ts`: small OnPush Angular components used as cell renderers. |
| `services/faq-store.ts` | Signals: `documents`, `pairs` (Map), `filter`; computeds: `activeDocuments`, `visiblePairs`, `hasProcessing`, `totalActiveItems`. Single writer for FAQ state; supports optimistic edits with rollback. |
| `services/faq-api.service.ts` | `HttpClient` calls: list documents/pairs, create/update/delete pair, delete document, toggle enabled. |
| `services/faq-ingestion.service.ts` | Orchestrates `validate → (CSV preview) → upload with progress (reportProgress) → subscribe to status events`. Updates `FaqStore` as `uploading → indexing → active \| error`. |
| `services/ingestion-events.service.ts` | Server-sent events (or WebSocket control messages) for `document.progress` / `document.active` / `document.error`, with reconnect. Callbacks write to `FaqStore` signals. |
| `services/file-validator.service.ts` | Extension, MIME, size, and **magic-byte** checks against `file-signatures.ts`. Client-side UX only; the server revalidates. |
| `services/csv-parser.service.ts` | Lazy `import('papaparse')`. `preview(file, n)` uses `preview: n`; `scan(file)` uses chunked streaming to count rows and collect row errors. Avoids `worker: true` (see `DEPENDENCIES.md` §3.4). |
| `services/faq-drawer.service.ts` | `open()`, `close()`, `isOpen` signal; creates/disposes the CDK overlay and focus trap. |
| `utils/file-signatures.ts` | Magic bytes: PDF `%PDF`, DOCX/ZIP `PK\x03\x04` (plus `word/` check by the server), JSON and CSV validated as text. |
| `utils/csv-column-detect.ts` | Heuristics mapping headers (`question`, `q`, `faq`, `answer`, `a`, `response`, …) to the question/answer columns. |
---
## 5. `src/app/shared/` in detail
| Area | Contents |
|---|---|
| `ui/button`, `ui/icon-button` | Variants (`primary`, `ghost`, `danger`), sizes, loading state, `focus-ring`. Signal inputs. |
| `ui/badge` | Generic pill; `variant` input maps to state/status colors (used by `StatusBadge` and `DocumentList`). |
| `ui/icon` | `<app-icon name="mic" />` plus `icons.ts`, the **single registry** of Lucide icons used by the app. This isolates the Lucide package API so only this folder changes if the package changes. |
| `ui/glass-panel` | Container component applying the `glass` utility with optional glow state. |
| `ui/drawer-shell` | Visual frame for slide-overs (header, close button, scroll body, footer); used by `FaqDrawer`. |
| `ui/dialog-shell` | Visual frame for CDK Dialog content (title, body, actions). |
| `ui/toast-host` | Renders `NotificationService.toasts()` with `aria-live`; timers cleaned through `DestroyRef`. |
| `ui/spinner`, `ui/progress-bar`, `ui/skeleton` | Loading primitives (CSS-only animations). |
| `ui/empty-state` | Icon, title, description, optional action; also used for the unsupported-browser page. |
| `directives/glass-panel.directive.ts` | Adds the `glass`/`glass-strong` classes and optional rounded/border variants to any element. |
| `directives/state-glow.directive.ts` | Input `voiceState`; applies the matching `glow-*` utility class with a CSS transition. |
| `directives/file-drop.directive.ts` | Handles `dragenter/dragover/dragleave/drop` with a depth counter (avoids flicker), exposes `dragging` signal, emits `filesDropped`. Generic; used by the dropzone. |
| `directives/autofocus.directive.ts` | Focuses an element after render (modals, filters). |
| `directives/resize-observer.directive.ts` | Emits `ResizeObserverEntry` sizes outside the zone; re-enters only through an output when the value changes meaningfully. |
| `pipes/file-size.pipe.ts` | `1536 → "1.5 KB"`. |
| `pipes/relative-time.pipe.ts` | `Intl.RelativeTimeFormat`-based ("2 minutes ago"); pure pipe, refreshed by a parent signal rather than a timer. |
| `pipes/duration.pipe.ts` | `ms → "1:05"`. |
| `pipes/truncate.pipe.ts` | Word-safe truncation with ellipsis. |
| `utils/assert.ts`, `id.ts`, `math.ts`, `raf-throttle.ts` | `assertNever`/`invariant`; `crypto.randomUUID()` wrapper; `clamp`/`lerp`/`easeTo`; throttle a callback to one call per animation frame. |
---
## 6. `src/assets/` in detail
### 6.1 `assets/worklets/`
| File | Purpose |
|---|---|
| `pcm-capture-processor.js` | `class PcmCaptureProcessor extends AudioWorkletProcessor`, registered as `'pcm-capture-processor'`. Accumulates 128-sample render quanta into a preallocated buffer, converts every `frameMs` to Int16, and posts the buffer with a **transfer list**. Honors `{ type: 'active' }` commands. Starts with `// @ts-check` (types from `@types/audioworklet`). |
| `pcm-playback-processor.js` | Registered as `'pcm-playback-processor'`. Holds a ring buffer (~2 s), prebuffers `prebufferMs` before starting, converts Int16 → Float32, outputs silence on underrun (posting `{ type: 'underrun' }`), handles `{ type: 'flush' }` in O(1), and posts `{ type: 'drained' }` after `end-of-turn`. |
The two processors are separate files (rather than one `pcm-processor.js`) so the capture path can load without the playback code and each file can be tested in isolation. Loading, with cache-busting:
```ts
// core/audio/audio-context.provider.ts (excerpt)
const v = inject(APP_CONFIG).workletVersion;
await ctx.audioWorklet.addModule(new URL(`assets/worklets/pcm-capture-processor.js?v=${v}`, document.baseURI).href);
await ctx.audioWorklet.addModule(new URL(`assets/worklets/pcm-playback-processor.js?v=${v}`, document.baseURI).href);
```
### 6.2 `assets/textures/`
Empty in v1 (`.gitkeep`). The orb noise is procedural in `orb.vert.glsl`. Add environment maps or noise textures here later; they are copied verbatim by the `assets` glob in `angular.json` and fetched with `TextureLoader` inside `ThreeOrbVisualizer`.
---
## 7. Where things run (quick reference)
| Code | Thread / zone | Writes signals? |
|---|---|---|
| `assets/worklets/*.js` | Audio render thread | No (messages only) |
| `audio-engine.service.ts`, `websocket.service.ts`, `audio-stream.handler.ts` | Main thread, **outside** the Angular zone | Only at low frequency (status, events) |
| `visualizer.service.ts`, `three-orb.visualizer.ts` | Main thread, **outside** the zone, `requestAnimationFrame` | **Never** |
| `voice-session.service.ts`, stores, components | Angular domain | Yes (events, ~1–5 Hz) |
This split is what keeps change detection at **zero ticks per second** while the orb animates (`ARCHITECTURE.md` §3.6–3.7).
+1798 -1405
View File
File diff suppressed because it is too large Load Diff
+23 -9
View File
@@ -22,26 +22,40 @@
},
"private": true,
"dependencies": {
"@angular/animations": "20.3",
"@angular/cdk": "^20.2.14",
"@angular/common": "^20.3.0",
"@angular/compiler": "^20.3.0",
"@angular/core": "^20.3.0",
"@angular/forms": "^20.3.0",
"@angular/platform-browser": "^20.3.0",
"@angular/router": "^20.3.0",
"@lucide/angular": "^1.52.0",
"@ng-bootstrap/ng-bootstrap": "^19.0.1",
"@popperjs/core": "^2.11.8",
"ag-grid-angular": "^36.2.0",
"ag-grid-community": "^36.2.0",
"ngx-toastr": "^14.3.0",
"papaparse": "^5.7.0",
"rxjs": "~7.8.0",
"three": "^0.186.1",
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^20.3.3",
"@angular/cli": "^20.3.3",
"@angular/compiler-cli": "^20.3.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.9.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.9.2"
"@playwright/test": "^1.63.0",
"@tailwindcss/postcss": "^4.3.3",
"@types/audioworklet": "^0.0.100",
"@types/papaparse": "^5.5.2",
"@types/three": "^0.186.0",
"jsdom": "^30.1.2",
"postcss": "^8.5.29",
"prettier": "^3.9.9",
"prettier-plugin-tailwindcss": "^0.8.1",
"tailwindcss": "^4.3.3",
"typescript": "~5.9.2",
"vitest": "^3.2.7"
}
}
}
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

+13 -1
View File
@@ -1,5 +1,8 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { routes } from './app.routes';
@@ -7,6 +10,15 @@ export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideZonelessChangeDetection(),
provideRouter(routes)
provideRouter(routes),
provideAnimations(),
provideHttpClient(),
{
provide: TOAST_CONFIG,
useValue: {
default: DefaultGlobalConfig,
config: {}
}
}
]
};
+1 -342
View File
@@ -1,342 +1 @@
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * The content below * * * * * * * * * * * -->
<!-- * * * * * * * * * * is only a placeholder * * * * * * * * * * -->
<!-- * * * * * * * * * * and can be replaced. * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * Delete the template below * * * * * * * * * -->
<!-- * * * * * * * to get started with your project! * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<style>
:host {
--bright-blue: oklch(51.01% 0.274 263.83);
--electric-violet: oklch(53.18% 0.28 296.97);
--french-violet: oklch(47.66% 0.246 305.88);
--vivid-pink: oklch(69.02% 0.277 332.77);
--hot-red: oklch(61.42% 0.238 15.34);
--orange-red: oklch(63.32% 0.24 31.68);
--gray-900: oklch(19.37% 0.006 300.98);
--gray-700: oklch(36.98% 0.014 302.71);
--gray-400: oklch(70.9% 0.015 304.04);
--red-to-pink-to-purple-vertical-gradient: linear-gradient(
180deg,
var(--orange-red) 0%,
var(--vivid-pink) 50%,
var(--electric-violet) 100%
);
--red-to-pink-to-purple-horizontal-gradient: linear-gradient(
90deg,
var(--orange-red) 0%,
var(--vivid-pink) 50%,
var(--electric-violet) 100%
);
--pill-accent: var(--bright-blue);
font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
"Segoe UI Symbol";
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
h1 {
font-size: 3.125rem;
color: var(--gray-900);
font-weight: 500;
line-height: 100%;
letter-spacing: -0.125rem;
margin: 0;
font-family: "Inter Tight", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
"Segoe UI Symbol";
}
p {
margin: 0;
color: var(--gray-700);
}
main {
width: 100%;
min-height: 100%;
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
box-sizing: inherit;
position: relative;
}
.angular-logo {
max-width: 9.2rem;
}
.content {
display: flex;
justify-content: space-around;
width: 100%;
max-width: 700px;
margin-bottom: 3rem;
}
.content h1 {
margin-top: 1.75rem;
}
.content p {
margin-top: 1.5rem;
}
.divider {
width: 1px;
background: var(--red-to-pink-to-purple-vertical-gradient);
margin-inline: 0.5rem;
}
.pill-group {
display: flex;
flex-direction: column;
align-items: start;
flex-wrap: wrap;
gap: 1.25rem;
}
.pill {
display: flex;
align-items: center;
--pill-accent: var(--bright-blue);
background: color-mix(in srgb, var(--pill-accent) 5%, transparent);
color: var(--pill-accent);
padding-inline: 0.75rem;
padding-block: 0.375rem;
border-radius: 2.75rem;
border: 0;
transition: background 0.3s ease;
font-family: var(--inter-font);
font-size: 0.875rem;
font-style: normal;
font-weight: 500;
line-height: 1.4rem;
letter-spacing: -0.00875rem;
text-decoration: none;
white-space: nowrap;
}
.pill:hover {
background: color-mix(in srgb, var(--pill-accent) 15%, transparent);
}
.pill-group .pill:nth-child(6n + 1) {
--pill-accent: var(--bright-blue);
}
.pill-group .pill:nth-child(6n + 2) {
--pill-accent: var(--electric-violet);
}
.pill-group .pill:nth-child(6n + 3) {
--pill-accent: var(--french-violet);
}
.pill-group .pill:nth-child(6n + 4),
.pill-group .pill:nth-child(6n + 5),
.pill-group .pill:nth-child(6n + 6) {
--pill-accent: var(--hot-red);
}
.pill-group svg {
margin-inline-start: 0.25rem;
}
.social-links {
display: flex;
align-items: center;
gap: 0.73rem;
margin-top: 1.5rem;
}
.social-links path {
transition: fill 0.3s ease;
fill: var(--gray-400);
}
.social-links a:hover svg path {
fill: var(--gray-900);
}
@media screen and (max-width: 650px) {
.content {
flex-direction: column;
width: max-content;
}
.divider {
height: 1px;
width: 100%;
background: var(--red-to-pink-to-purple-horizontal-gradient);
margin-block: 1.5rem;
}
}
</style>
<main class="main">
<div class="content">
<div class="left-side">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 982 239"
fill="none"
class="angular-logo"
>
<g clip-path="url(#a)">
<path
fill="url(#b)"
d="M388.676 191.625h30.849L363.31 31.828h-35.758l-56.215 159.797h30.848l13.174-39.356h60.061l13.256 39.356Zm-65.461-62.675 21.602-64.311h1.227l21.602 64.311h-44.431Zm126.831-7.527v70.202h-28.23V71.839h27.002v20.374h1.392c2.782-6.71 7.2-12.028 13.255-15.956 6.056-3.927 13.584-5.89 22.503-5.89 8.264 0 15.465 1.8 21.684 5.318 6.137 3.518 10.964 8.673 14.319 15.382 3.437 6.71 5.074 14.81 4.992 24.383v76.175h-28.23v-71.92c0-8.019-2.046-14.237-6.219-18.819-4.173-4.5-9.819-6.791-17.102-6.791-4.91 0-9.328 1.063-13.174 3.272-3.846 2.128-6.792 5.237-9.001 9.328-2.046 4.009-3.191 8.918-3.191 14.728ZM589.233 239c-10.147 0-18.82-1.391-26.103-4.091-7.282-2.7-13.092-6.382-17.511-10.964-4.418-4.582-7.528-9.655-9.164-15.219l25.448-6.136c1.145 2.372 2.782 4.663 4.991 6.954 2.209 2.291 5.155 4.255 8.837 5.81 3.683 1.554 8.428 2.291 14.074 2.291 8.019 0 14.647-1.964 19.884-5.81 5.237-3.845 7.856-10.227 7.856-19.064v-22.665h-1.391c-1.473 2.946-3.601 5.892-6.383 9.001-2.782 3.109-6.464 5.645-10.965 7.691-4.582 2.046-10.228 3.109-17.101 3.109-9.165 0-17.511-2.209-25.039-6.545-7.446-4.337-13.42-10.883-17.757-19.474-4.418-8.673-6.628-19.473-6.628-32.565 0-13.091 2.21-24.301 6.628-33.383 4.419-9.082 10.311-15.955 17.839-20.7 7.528-4.746 15.874-7.037 25.039-7.037 7.037 0 12.846 1.145 17.347 3.518 4.582 2.373 8.182 5.236 10.883 8.51 2.7 3.272 4.746 6.382 6.137 9.327h1.554v-19.8h27.821v121.749c0 10.228-2.454 18.737-7.364 25.447-4.91 6.709-11.538 11.7-20.048 15.055-8.509 3.355-18.165 4.991-28.884 4.991Zm.245-71.266c5.974 0 11.047-1.473 15.302-4.337 4.173-2.945 7.446-7.118 9.573-12.519 2.21-5.482 3.274-12.027 3.274-19.637 0-7.609-1.064-14.155-3.274-19.8-2.127-5.646-5.318-10.064-9.491-13.255-4.174-3.11-9.329-4.746-15.384-4.746s-11.537 1.636-15.792 4.91c-4.173 3.272-7.365 7.772-9.492 13.418-2.128 5.727-3.191 12.191-3.191 19.392 0 7.2 1.063 13.745 3.273 19.228 2.127 5.482 5.318 9.736 9.573 12.764 4.174 3.027 9.41 4.582 15.629 4.582Zm141.56-26.51V71.839h28.23v119.786h-27.412v-21.273h-1.227c-2.7 6.709-7.119 12.191-13.338 16.446-6.137 4.255-13.747 6.382-22.748 6.382-7.855 0-14.81-1.718-20.783-5.237-5.974-3.518-10.72-8.591-14.075-15.382-3.355-6.709-5.073-14.891-5.073-24.464V71.839h28.312v71.921c0 7.609 2.046 13.664 6.219 18.083 4.173 4.5 9.655 6.709 16.365 6.709 4.173 0 8.183-.982 12.111-3.028 3.927-2.045 7.118-5.072 9.655-9.082 2.537-4.091 3.764-9.164 3.764-15.218Zm65.707-109.395v159.796h-28.23V31.828h28.23Zm44.841 162.169c-7.61 0-14.402-1.391-20.457-4.091-6.055-2.7-10.883-6.791-14.32-12.109-3.518-5.319-5.237-11.946-5.237-19.801 0-6.791 1.228-12.355 3.765-16.773 2.536-4.419 5.891-7.937 10.228-10.637 4.337-2.618 9.164-4.664 14.647-6.055 5.4-1.391 11.046-2.373 16.856-3.027 7.037-.737 12.683-1.391 17.102-1.964 4.337-.573 7.528-1.555 9.574-2.782 1.963-1.309 3.027-3.273 3.027-5.973v-.491c0-5.891-1.718-10.391-5.237-13.664-3.518-3.191-8.51-4.828-15.056-4.828-6.955 0-12.356 1.473-16.447 4.5-4.009 3.028-6.71 6.546-8.183 10.719l-26.348-3.764c2.046-7.282 5.483-13.336 10.31-18.328 4.746-4.909 10.638-8.59 17.511-11.045 6.955-2.455 14.565-3.682 22.912-3.682 5.809 0 11.537.654 17.265 2.045s10.965 3.6 15.711 6.71c4.746 3.109 8.51 7.282 11.455 12.6 2.864 5.318 4.337 11.946 4.337 19.883v80.184h-27.166v-16.446h-.9c-1.719 3.355-4.092 6.464-7.201 9.328-3.109 2.864-6.955 5.237-11.619 6.955-4.828 1.718-10.229 2.536-16.529 2.536Zm7.364-20.701c5.646 0 10.556-1.145 14.729-3.354 4.173-2.291 7.364-5.237 9.655-9.001 2.292-3.763 3.355-7.854 3.355-12.273v-14.155c-.9.737-2.373 1.391-4.5 2.046-2.128.654-4.419 1.145-7.037 1.636-2.619.491-5.155.9-7.692 1.227-2.537.328-4.746.655-6.628.901-4.173.572-8.019 1.472-11.292 2.781-3.355 1.31-5.973 3.11-7.855 5.401-1.964 2.291-2.864 5.318-2.864 8.918 0 5.237 1.882 9.164 5.728 11.782 3.682 2.782 8.51 4.091 14.401 4.091Zm64.643 18.328V71.839h27.412v19.965h1.227c2.21-6.955 5.974-12.274 11.292-16.038 5.319-3.763 11.456-5.645 18.329-5.645 1.555 0 3.355.082 5.237.163 1.964.164 3.601.328 4.91.573v25.938c-1.227-.41-3.109-.819-5.646-1.146a58.814 58.814 0 0 0-7.446-.49c-5.155 0-9.738 1.145-13.829 3.354-4.091 2.209-7.282 5.236-9.655 9.164-2.373 3.927-3.519 8.427-3.519 13.5v70.448h-28.312ZM222.077 39.192l-8.019 125.923L137.387 0l84.69 39.192Zm-53.105 162.825-57.933 33.056-57.934-33.056 11.783-28.556h92.301l11.783 28.556ZM111.039 62.675l30.357 73.803H80.681l30.358-73.803ZM7.937 165.115 0 39.192 84.69 0 7.937 165.115Z"
/>
<path
fill="url(#c)"
d="M388.676 191.625h30.849L363.31 31.828h-35.758l-56.215 159.797h30.848l13.174-39.356h60.061l13.256 39.356Zm-65.461-62.675 21.602-64.311h1.227l21.602 64.311h-44.431Zm126.831-7.527v70.202h-28.23V71.839h27.002v20.374h1.392c2.782-6.71 7.2-12.028 13.255-15.956 6.056-3.927 13.584-5.89 22.503-5.89 8.264 0 15.465 1.8 21.684 5.318 6.137 3.518 10.964 8.673 14.319 15.382 3.437 6.71 5.074 14.81 4.992 24.383v76.175h-28.23v-71.92c0-8.019-2.046-14.237-6.219-18.819-4.173-4.5-9.819-6.791-17.102-6.791-4.91 0-9.328 1.063-13.174 3.272-3.846 2.128-6.792 5.237-9.001 9.328-2.046 4.009-3.191 8.918-3.191 14.728ZM589.233 239c-10.147 0-18.82-1.391-26.103-4.091-7.282-2.7-13.092-6.382-17.511-10.964-4.418-4.582-7.528-9.655-9.164-15.219l25.448-6.136c1.145 2.372 2.782 4.663 4.991 6.954 2.209 2.291 5.155 4.255 8.837 5.81 3.683 1.554 8.428 2.291 14.074 2.291 8.019 0 14.647-1.964 19.884-5.81 5.237-3.845 7.856-10.227 7.856-19.064v-22.665h-1.391c-1.473 2.946-3.601 5.892-6.383 9.001-2.782 3.109-6.464 5.645-10.965 7.691-4.582 2.046-10.228 3.109-17.101 3.109-9.165 0-17.511-2.209-25.039-6.545-7.446-4.337-13.42-10.883-17.757-19.474-4.418-8.673-6.628-19.473-6.628-32.565 0-13.091 2.21-24.301 6.628-33.383 4.419-9.082 10.311-15.955 17.839-20.7 7.528-4.746 15.874-7.037 25.039-7.037 7.037 0 12.846 1.145 17.347 3.518 4.582 2.373 8.182 5.236 10.883 8.51 2.7 3.272 4.746 6.382 6.137 9.327h1.554v-19.8h27.821v121.749c0 10.228-2.454 18.737-7.364 25.447-4.91 6.709-11.538 11.7-20.048 15.055-8.509 3.355-18.165 4.991-28.884 4.991Zm.245-71.266c5.974 0 11.047-1.473 15.302-4.337 4.173-2.945 7.446-7.118 9.573-12.519 2.21-5.482 3.274-12.027 3.274-19.637 0-7.609-1.064-14.155-3.274-19.8-2.127-5.646-5.318-10.064-9.491-13.255-4.174-3.11-9.329-4.746-15.384-4.746s-11.537 1.636-15.792 4.91c-4.173 3.272-7.365 7.772-9.492 13.418-2.128 5.727-3.191 12.191-3.191 19.392 0 7.2 1.063 13.745 3.273 19.228 2.127 5.482 5.318 9.736 9.573 12.764 4.174 3.027 9.41 4.582 15.629 4.582Zm141.56-26.51V71.839h28.23v119.786h-27.412v-21.273h-1.227c-2.7 6.709-7.119 12.191-13.338 16.446-6.137 4.255-13.747 6.382-22.748 6.382-7.855 0-14.81-1.718-20.783-5.237-5.974-3.518-10.72-8.591-14.075-15.382-3.355-6.709-5.073-14.891-5.073-24.464V71.839h28.312v71.921c0 7.609 2.046 13.664 6.219 18.083 4.173 4.5 9.655 6.709 16.365 6.709 4.173 0 8.183-.982 12.111-3.028 3.927-2.045 7.118-5.072 9.655-9.082 2.537-4.091 3.764-9.164 3.764-15.218Zm65.707-109.395v159.796h-28.23V31.828h28.23Zm44.841 162.169c-7.61 0-14.402-1.391-20.457-4.091-6.055-2.7-10.883-6.791-14.32-12.109-3.518-5.319-5.237-11.946-5.237-19.801 0-6.791 1.228-12.355 3.765-16.773 2.536-4.419 5.891-7.937 10.228-10.637 4.337-2.618 9.164-4.664 14.647-6.055 5.4-1.391 11.046-2.373 16.856-3.027 7.037-.737 12.683-1.391 17.102-1.964 4.337-.573 7.528-1.555 9.574-2.782 1.963-1.309 3.027-3.273 3.027-5.973v-.491c0-5.891-1.718-10.391-5.237-13.664-3.518-3.191-8.51-4.828-15.056-4.828-6.955 0-12.356 1.473-16.447 4.5-4.009 3.028-6.71 6.546-8.183 10.719l-26.348-3.764c2.046-7.282 5.483-13.336 10.31-18.328 4.746-4.909 10.638-8.59 17.511-11.045 6.955-2.455 14.565-3.682 22.912-3.682 5.809 0 11.537.654 17.265 2.045s10.965 3.6 15.711 6.71c4.746 3.109 8.51 7.282 11.455 12.6 2.864 5.318 4.337 11.946 4.337 19.883v80.184h-27.166v-16.446h-.9c-1.719 3.355-4.092 6.464-7.201 9.328-3.109 2.864-6.955 5.237-11.619 6.955-4.828 1.718-10.229 2.536-16.529 2.536Zm7.364-20.701c5.646 0 10.556-1.145 14.729-3.354 4.173-2.291 7.364-5.237 9.655-9.001 2.292-3.763 3.355-7.854 3.355-12.273v-14.155c-.9.737-2.373 1.391-4.5 2.046-2.128.654-4.419 1.145-7.037 1.636-2.619.491-5.155.9-7.692 1.227-2.537.328-4.746.655-6.628.901-4.173.572-8.019 1.472-11.292 2.781-3.355 1.31-5.973 3.11-7.855 5.401-1.964 2.291-2.864 5.318-2.864 8.918 0 5.237 1.882 9.164 5.728 11.782 3.682 2.782 8.51 4.091 14.401 4.091Zm64.643 18.328V71.839h27.412v19.965h1.227c2.21-6.955 5.974-12.274 11.292-16.038 5.319-3.763 11.456-5.645 18.329-5.645 1.555 0 3.355.082 5.237.163 1.964.164 3.601.328 4.91.573v25.938c-1.227-.41-3.109-.819-5.646-1.146a58.814 58.814 0 0 0-7.446-.49c-5.155 0-9.738 1.145-13.829 3.354-4.091 2.209-7.282 5.236-9.655 9.164-2.373 3.927-3.519 8.427-3.519 13.5v70.448h-28.312ZM222.077 39.192l-8.019 125.923L137.387 0l84.69 39.192Zm-53.105 162.825-57.933 33.056-57.934-33.056 11.783-28.556h92.301l11.783 28.556ZM111.039 62.675l30.357 73.803H80.681l30.358-73.803ZM7.937 165.115 0 39.192 84.69 0 7.937 165.115Z"
/>
</g>
<defs>
<radialGradient
id="c"
cx="0"
cy="0"
r="1"
gradientTransform="rotate(118.122 171.182 60.81) scale(205.794)"
gradientUnits="userSpaceOnUse"
>
<stop stop-color="#FF41F8" />
<stop offset=".707" stop-color="#FF41F8" stop-opacity=".5" />
<stop offset="1" stop-color="#FF41F8" stop-opacity="0" />
</radialGradient>
<linearGradient
id="b"
x1="0"
x2="982"
y1="192"
y2="192"
gradientUnits="userSpaceOnUse"
>
<stop stop-color="#F0060B" />
<stop offset="0" stop-color="#F0070C" />
<stop offset=".526" stop-color="#CC26D5" />
<stop offset="1" stop-color="#7702FF" />
</linearGradient>
<clipPath id="a"><path fill="#fff" d="M0 0h982v239H0z" /></clipPath>
</defs>
</svg>
<h1>Hello, {{ title() }}</h1>
<p>Congratulations! Your app is running. 🎉</p>
</div>
<div class="divider" role="separator" aria-label="Divider"></div>
<div class="right-side">
<div class="pill-group">
@for (item of [
{ title: 'Explore the Docs', link: 'https://angular.dev' },
{ title: 'Learn with Tutorials', link: 'https://angular.dev/tutorials' },
{ title: 'Prompt and best practices for AI', link: 'https://angular.dev/ai/develop-with-ai'},
{ title: 'CLI Docs', link: 'https://angular.dev/tools/cli' },
{ title: 'Angular Language Service', link: 'https://angular.dev/tools/language-service' },
{ title: 'Angular DevTools', link: 'https://angular.dev/tools/devtools' },
]; track item.title) {
<a
class="pill"
[href]="item.link"
target="_blank"
rel="noopener"
>
<span>{{ item.title }}</span>
<svg
xmlns="http://www.w3.org/2000/svg"
height="14"
viewBox="0 -960 960 960"
width="14"
fill="currentColor"
>
<path
d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h280v80H200v560h560v-280h80v280q0 33-23.5 56.5T760-120H200Zm188-212-56-56 372-372H560v-80h280v280h-80v-144L388-332Z"
/>
</svg>
</a>
}
</div>
<div class="social-links">
<a
href="https://github.com/angular/angular"
aria-label="Github"
target="_blank"
rel="noopener"
>
<svg
width="25"
height="24"
viewBox="0 0 25 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
alt="Github"
>
<path
d="M12.3047 0C5.50634 0 0 5.50942 0 12.3047C0 17.7423 3.52529 22.3535 8.41332 23.9787C9.02856 24.0946 9.25414 23.7142 9.25414 23.3871C9.25414 23.0949 9.24389 22.3207 9.23876 21.2953C5.81601 22.0377 5.09414 19.6444 5.09414 19.6444C4.53427 18.2243 3.72524 17.8449 3.72524 17.8449C2.61064 17.082 3.81137 17.0973 3.81137 17.0973C5.04697 17.1835 5.69604 18.3647 5.69604 18.3647C6.79321 20.2463 8.57636 19.7029 9.27978 19.3881C9.39052 18.5924 9.70736 18.0499 10.0591 17.7423C7.32641 17.4347 4.45429 16.3765 4.45429 11.6618C4.45429 10.3185 4.9311 9.22133 5.72065 8.36C5.58222 8.04931 5.16694 6.79833 5.82831 5.10337C5.82831 5.10337 6.85883 4.77319 9.2121 6.36459C10.1965 6.09082 11.2424 5.95546 12.2883 5.94931C13.3342 5.95546 14.3801 6.09082 15.3644 6.36459C17.7023 4.77319 18.7328 5.10337 18.7328 5.10337C19.3942 6.79833 18.9789 8.04931 18.8559 8.36C19.6403 9.22133 20.1171 10.3185 20.1171 11.6618C20.1171 16.3888 17.2409 17.4296 14.5031 17.7321C14.9338 18.1012 15.3337 18.8559 15.3337 20.0084C15.3337 21.6552 15.3183 22.978 15.3183 23.3779C15.3183 23.7009 15.5336 24.0854 16.1642 23.9623C21.0871 22.3484 24.6094 17.7341 24.6094 12.3047C24.6094 5.50942 19.0999 0 12.3047 0Z"
/>
</svg>
</a>
<a
href="https://twitter.com/angular"
aria-label="Twitter"
target="_blank"
rel="noopener"
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
alt="Twitter"
>
<path
d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"
/>
</svg>
</a>
<a
href="https://www.youtube.com/channel/UCbn1OgGei-DV7aSRo_HaAiw"
aria-label="Youtube"
target="_blank"
rel="noopener"
>
<svg
width="29"
height="20"
viewBox="0 0 29 20"
fill="none"
xmlns="http://www.w3.org/2000/svg"
alt="Youtube"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M27.4896 1.52422C27.9301 1.96749 28.2463 2.51866 28.4068 3.12258C29.0004 5.35161 29.0004 10 29.0004 10C29.0004 10 29.0004 14.6484 28.4068 16.8774C28.2463 17.4813 27.9301 18.0325 27.4896 18.4758C27.0492 18.9191 26.5 19.2389 25.8972 19.4032C23.6778 20 14.8068 20 14.8068 20C14.8068 20 5.93586 20 3.71651 19.4032C3.11363 19.2389 2.56449 18.9191 2.12405 18.4758C1.68361 18.0325 1.36732 17.4813 1.20683 16.8774C0.613281 14.6484 0.613281 10 0.613281 10C0.613281 10 0.613281 5.35161 1.20683 3.12258C1.36732 2.51866 1.68361 1.96749 2.12405 1.52422C2.56449 1.08095 3.11363 0.76113 3.71651 0.596774C5.93586 0 14.8068 0 14.8068 0C14.8068 0 23.6778 0 25.8972 0.596774C26.5 0.76113 27.0492 1.08095 27.4896 1.52422ZM19.3229 10L11.9036 5.77905V14.221L19.3229 10Z"
/>
</svg>
</a>
</div>
</div>
</div>
</main>
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * The content above * * * * * * * * * * * * -->
<!-- * * * * * * * * * * is only a placeholder * * * * * * * * * * * -->
<!-- * * * * * * * * * * and can be replaced. * * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * End of Placeholder * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<router-outlet />
<app-layout></app-layout>
+9 -1
View File
@@ -1,3 +1,11 @@
import { Routes } from '@angular/router';
import { SettingsPage } from './pages/settings/settings.page';
export const routes: Routes = [];
export const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: '' },
{
path: 'settings',
title: 'تنظیمات',
component: SettingsPage,
},
];
-7
View File
@@ -15,11 +15,4 @@ describe('App', () => {
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it('should render title', () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, faq-chatbot');
});
});
+4 -6
View File
@@ -1,12 +1,10 @@
import { Component, signal } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { Component } from '@angular/core';
import { LayoutComponent } from './layout/layout.component';
@Component({
selector: 'app-root',
imports: [RouterOutlet],
imports: [LayoutComponent],
templateUrl: './app.html',
styleUrl: './app.css'
})
export class App {
protected readonly title = signal('faq-chatbot');
}
export class App {}
+59
View File
@@ -0,0 +1,59 @@
.header-bar {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem;
}
.app-logo {
height: 36px;
width: auto;
object-fit: contain;
}
.app-logo-link {
display: inline-flex;
align-items: center;
cursor: pointer;
}
.app-logo-link:hover .app-logo {
opacity: 0.85;
}
.menu-toggle {
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
border: none;
background: transparent;
color: var(--menu-toggle-color);
border-radius: 0.375rem;
cursor: pointer;
transition: background 0.2s;
flex-shrink: 0;
}
.menu-toggle:hover {
background: var(--menu-toggle-hover);
}
.main-content {
flex: 1;
overflow-y: auto;
background: var(--main-content-bg);
}
.main-area {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
transition: margin-right 0.3s ease;
}
.main-area.shifted {
margin-right: 260px;
}
+23
View File
@@ -0,0 +1,23 @@
<div class="app-layout">
<app-sidebar
[isOpen]="sidebarOpen()"
[chatHistory]="chatHistory()"
(close)="sidebarOpen.set(false)"
(navClick)="sidebarOpen.set(false)"
(open)="sidebarOpen.set(true)"
(profileClick)="onProfile()"
(logoutClick)="onLogout()"
></app-sidebar>
<div class="main-area" [class.shifted]="sidebarOpen()">
<!-- <div class="header-bar">
<a class="app-logo-link" routerLink="/">
<img class="app-logo" [src]="isDarkMode() ? 'assets/images/RaymandLogo.png' : 'assets/images/login.png'" alt="Raymand" />
</a>
</div> -->
<main class="main-content">
<router-outlet></router-outlet>
</main>
</div>
</div>
+33
View File
@@ -0,0 +1,33 @@
import { ChangeDetectionStrategy, Component, signal, inject } from '@angular/core';
import { RouterModule } from '@angular/router';
import { RouterOutlet } from '@angular/router';
import { SidebarComponent, ChatHistoryItem } from '../shared/ui/sidebar/sidebar.component';
import { AuthService } from '../services/auth/auth.service';
import { ThemeService } from '../services/theme/theme.service';
@Component({
selector: 'app-layout',
standalone: true,
imports: [RouterModule, RouterOutlet, SidebarComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './layout.component.html',
styleUrl: './layout.component.css',
})
export class LayoutComponent {
private readonly authService = inject(AuthService);
private readonly themeService = inject(ThemeService);
readonly sidebarOpen = signal(false);
readonly chatHistory = signal<ChatHistoryItem[]>([]);
readonly isDarkMode = this.themeService.isDarkMode;
onProfile(): void {
this.sidebarOpen.set(false);
}
onLogout(): void {
this.authService.logout();
this.sidebarOpen.set(false);
}
}
+376
View File
@@ -0,0 +1,376 @@
.settings-page {
min-height: 100vh;
}
.settings-header {
animation: fadeInDown 0.4s ease-out;
}
.settings-card {
animation: fadeInUp 0.5s ease-out;
}
.settings-tabs {
position: relative;
}
.tab-btn {
position: relative;
}
.tab-btn.tab-active {
color: var(--color-primary);
}
.tab-btn .tab-indicator {
animation: slideIn 0.3s ease-out;
}
.settings-content {
animation: fadeIn 0.3s ease-out;
}
.section-header {
animation: fadeInDown 0.3s ease-out;
}
.dropzone {
position: relative;
overflow: hidden;
}
.dropzone::before {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(135deg, var(--color-primary)/5 0%, transparent 50%);
opacity: 0;
transition: opacity 0.3s ease;
}
.dropzone:hover::before,
.dropzone-active::before {
opacity: 1;
}
.dropzone-active {
border-color: var(--color-primary) !important;
background-color: var(--color-primary)/10 !important;
transform: scale(1.01);
box-shadow: 0 0 0 3px var(--color-primary)/20, 0 10px 40px var(--color-primary)/10;
}
.dropzone-icon-wrapper {
animation: bounce 2s infinite;
}
.dropzone-active .dropzone-icon-wrapper {
animation: pulse 1s infinite;
}
.file-list {
animation: slideUp 0.4s ease-out;
}
.file-item {
animation: slideInRight 0.3s ease-out;
}
.file-item:nth-child(1) { animation-delay: 0.05s; }
.file-item:nth-child(2) { animation-delay: 0.1s; }
.file-item:nth-child(3) { animation-delay: 0.15s; }
.file-item:nth-child(4) { animation-delay: 0.2s; }
.file-item:nth-child(5) { animation-delay: 0.25s; }
.file-icon-wrapper {
transition: all 0.2s ease;
}
.file-item:hover .file-icon-wrapper {
background-color: var(--color-primary)/20;
transform: scale(1.05);
}
.file-remove-btn {
transition: all 0.2s ease;
}
.setting-item {
animation: fadeInUp 0.4s ease-out;
}
.setting-item:nth-child(1) { animation-delay: 0.05s; }
.setting-item:nth-child(2) { animation-delay: 0.1s; }
.setting-item:nth-child(3) { animation-delay: 0.15s; }
.setting-item:nth-child(4) { animation-delay: 0.2s; }
.form-select {
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: left 0.75rem center;
padding-left: 2.5rem;
}
.form-select:focus {
box-shadow: 0 0 0 3px var(--color-primary)/20;
}
.toggle-switch {
position: relative;
display: inline-flex;
height: 1.5rem;
width: 2.75rem;
flex-shrink: 0;
cursor: pointer;
align-items: center;
justify-content: flex-start;
padding: 0.125rem;
border-radius: 9999px;
border: 2px solid transparent;
transition: all 0.2s ease-in-out;
background-color: var(--toggle-bg);
box-sizing: border-box;
}
.toggle-switch input {
position: absolute;
opacity: 0;
width: 0;
height: 0;
}
.toggle-slider {
pointer-events: none;
display: inline-block;
height: 1.25rem;
width: 1.25rem;
border-radius: 9999px;
background-color: var(--toggle-slider);
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.05);
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
position: relative;
}
.toggle-slider::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 0.5rem;
height: 0.5rem;
border-radius: 50%;
background-color: var(--toggle-slider);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
opacity: 1;
}
.toggle-switch input:checked + .toggle-slider {
transform: translateX(-1.25rem);
background-color: var(--toggle-slider);
box-shadow: 0 2px 8px var(--color-primary)/40, 0 0 0 2px var(--color-primary)/20;
}
.toggle-switch input:checked + .toggle-slider::after {
background-color: var(--toggle-slider);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
}
.toggle-switch:has(input:checked) {
background-color: var(--color-primary);
border-color: var(--color-primary);
}
.toggle-switch.toggle-active {
background-color: var(--color-primary)/15;
border-color: var(--color-primary)/25;
}
.toggle-switch:focus-within {
outline: none;
box-shadow: 0 0 0 3px var(--color-primary)/30;
}
.toggle-switch:hover {
background-color: var(--color-primary)/10;
}
.toggle-switch:hover:has(input:checked) {
background-color: var(--color-primary);
}
.toggle-switch:hover.toggle-active {
background-color: var(--color-primary)/20;
}
@keyframes fadeInDown {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
@keyframes slideIn {
from {
width: 0;
opacity: 0;
}
to {
width: 1.5rem;
opacity: 1;
}
}
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {
transform: translateY(0);
}
40% {
transform: translateY(-5px);
}
60% {
transform: translateY(-3px);
}
}
@keyframes pulse {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.1);
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
@media (max-width: 640px) {
.settings-page {
padding: 1rem;
}
.settings-card {
border-radius: 1rem;
}
.settings-tabs {
flex-direction: column;
}
.tab-btn {
justify-content: flex-start;
padding: 1rem;
}
.tab-btn .tab-indicator {
display: none;
}
.tab-btn.tab-active {
background-color: var(--color-primary)/10;
}
.dropzone {
padding: 2rem 1rem;
}
.setting-item {
flex-direction: column;
align-items: flex-start;
gap: 1rem;
}
.setting-control {
width: 100%;
justify-content: flex-end;
}
.form-select {
width: 100%;
}
}
[data-bs-theme="dark"] .dropzone-icon-wrapper svg,
[data-bs-theme="dark"] .file-icon-wrapper svg,
[data-bs-theme="dark"] .section-header svg {
stroke: var(--color-primary);
}
[data-bs-theme="dark"] .form-select {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23cbd5e1' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
}
[data-bs-theme="dark"] .file-remove-btn:hover {
background-color: rgba(239, 68, 68, 0.15);
}
[data-bs-theme="dark"] .toggle-switch input:checked + .toggle-slider {
box-shadow: 0 1px 3px var(--color-primary)/40, 0 0 0 2px var(--color-primary)/30;
}
[data-bs-theme="dark"] .settings-card,
[data-bs-theme="dark"] .file-item,
[data-bs-theme="dark"] .setting-item {
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3), 0 2px 10px rgba(0, 0, 0, 0.2);
}
[data-bs-theme="dark"] .file-item:hover,
[data-bs-theme="dark"] .setting-item:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4), 0 2px 8px rgba(0, 0, 0, 0.3);
}
+326
View File
@@ -0,0 +1,326 @@
<div class="settings-page max-w-3xl mx-auto px-4 py-8">
<header class="settings-header mb-8">
<h1 class="text-3xl font-semibold text-[var(--text-primary)] mb-1">تنظیمات</h1>
<p class="text-sm text-[var(--text-muted)]">مدیریت FAQ و ترجیحات برنامه</p>
</header>
<div
class="settings-card bg-[var(--card-bg)] rounded-2xl overflow-hidden shadow-[0_10px_40px_rgba(0,0,0,0.08),_0_2px_10px_rgba(0,0,0,0.04)]"
>
<nav class="settings-tabs flex bg-[var(--sidebar-hover)]" role="tablist">
<button
type="button"
class="tab-btn flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm font-medium text-[var(--text-muted)] transition-all duration-200 hover:text-[var(--text-primary)] relative"
[class.tab-active]="activeTab() === 'faq'"
(click)="selectTab('faq')"
role="tab"
[attr.aria-selected]="activeTab() === 'faq'"
>
<svg
class="w-4 h-4 transition-colors duration-200"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="17 8 12 3 7 8" />
<line x1="12" y1="3" x2="12" y2="15" />
</svg>
<span>آپلود FAQ</span>
@if (activeTab() === 'faq') {
<span
class="tab-indicator absolute bottom-0 left-1/2 -translate-x-1/2 w-6 h-0.5 bg-primary rounded-full"
></span>
}
</button>
<button
type="button"
class="tab-btn flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm font-medium text-[var(--text-muted)] transition-all duration-200 hover:text-[var(--text-primary)] relative"
[class.tab-active]="activeTab() === 'app'"
(click)="selectTab('app')"
role="tab"
[attr.aria-selected]="activeTab() === 'app'"
>
<svg
class="w-4 h-4 transition-colors duration-200"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="3" />
<path
d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"
/>
</svg>
<span>تنظیمات برنامه</span>
@if (activeTab() === 'app') {
<span
class="tab-indicator absolute bottom-0 left-1/2 -translate-x-1/2 w-6 h-0.5 bg-primary rounded-full"
></span>
}
</button>
</nav>
<div class="settings-content p-6">
@if (activeTab() === 'faq') {
<section class="faq-section animate-fade-in">
<div class="section-header mb-6">
<h2
class="text-xl font-semibold text-[var(--text-primary)] mb-1 flex items-center gap-2"
>
<svg
class="w-5 h-5 text-primary"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="17 8 12 3 7 8" />
<line x1="12" y1="3" x2="12" y2="15" />
</svg>
آپلود سند FAQ
</h2>
<p class="text-sm text-[var(--text-muted)]">
فایل‌های PDF، DOCX یا TXT خود را بکشید و رها کنید یا برای آپلود کلیک کنید.
</p>
</div>
<div
class="dropzone relative flex flex-col items-center justify-center gap-3 p-8 border-2 border-dashed border-[var(--text-muted)]/20 rounded-xl bg-[var(--dropzone-bg)] cursor-pointer transition-all duration-300 hover:border-primary/50 hover:bg-primary/5 hover:shadow-[0_10px_30px_rgba(59,130,246,0.15)]"
[class.dropzone-active]="isDragging()"
(dragover)="onDragOver($event)"
(dragleave)="onDragLeave()"
(drop)="onDrop($event)"
(click)="fileInput.click()"
role="button"
tabindex="0"
(keydown.enter)="fileInput.click()"
(keydown.space)="$event.preventDefault(); fileInput.click()"
>
<input
#fileInput
id="faq-file-input"
type="file"
class="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
accept=".pdf,.docx,.doc,.txt"
multiple
(change)="onFileSelected($event)"
/>
<div class="dropzone-icon-wrapper">
<svg
class="w-12 h-12 text-primary transition-transform duration-300"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="17 8 12 3 7 8" />
<line x1="12" y1="3" x2="12" y2="15" />
</svg>
</div>
<div class="dropzone-text text-center">
<p class="text-sm font-medium text-[var(--text-secondary)]">
فایل‌ها را اینجا رها کنید
</p>
<p class="text-xs text-[var(--text-muted)] mt-1">یا کلیک کنید برای انتخاب</p>
<p class="text-xs text-[var(--text-muted)] mt-2">پشتیبانی: PDF، DOCX، TXT</p>
</div>
</div>
@if (fileCount > 0) {
<div class="file-list mt-6 animate-slide-up">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-medium text-[var(--text-primary)] flex items-center gap-2">
<svg
class="w-5 h-5 text-primary"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
</svg>
فایل‌های انتخاب شده ({{ fileCount }})
</h3>
<button
type="button"
class="text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors duration-200"
(click)="clearAllFiles()"
>
پاک کردن همه
</button>
</div>
<ul class="space-y-2">
@for (file of uploadedFiles(); track $index) {
<li
class="file-item flex items-center justify-between gap-3 p-4 bg-[var(--card-bg)] rounded-xl shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all duration-200 hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)] hover:-translate-y-0.5"
>
<div class="flex items-center gap-3 min-w-0">
<div class="file-icon-wrapper p-2 bg-primary/10 rounded-lg shrink-0">
<svg
class="w-5 h-5 text-primary"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
</svg>
</div>
<div class="flex flex-col min-w-0">
<span class="text-sm font-medium text-[var(--text-secondary)] truncate">{{
file.name
}}</span>
<span class="text-xs text-[var(--text-muted)]">{{
formatFileSize(file.size)
}}</span>
</div>
</div>
<button
type="button"
class="file-remove-btn p-2 text-[var(--text-muted)] rounded-lg transition-all duration-200 hover:text-red-400 hover:bg-red-400/10 hover:scale-110 shrink-0"
(click)="removeFile($index)"
aria-label="حذف فایل {{ file.name }}"
>
<svg
class="w-4 h-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
</li>
}
</ul>
</div>
}
</section>
}
@if (activeTab() === 'app') {
<section class="app-section animate-fade-in">
<div class="section-header mb-6">
<h2
class="text-xl font-semibold text-[var(--text-primary)] mb-1 flex items-center gap-2"
>
<svg
class="w-5 h-5 text-primary"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="3" />
<path
d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"
/>
</svg>
تنظیمات کلی
</h2>
</div>
<div class="settings-grid space-y-3">
<div
class="setting-item flex items-center justify-between gap-4 p-4 bg-[var(--card-bg)] rounded-xl shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all duration-200 hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)] hover:-translate-y-0.5"
>
<div class="setting-info flex flex-col gap-1 min-w-0">
<span class="text-sm font-medium text-[var(--text-secondary)]"
>زبان رابط کاربری</span
>
<span class="text-xs text-[var(--text-muted)]"
>زبان نمایش برنامه را انتخاب کنید</span
>
</div>
<div class="setting-control shrink-0">
<select
class="form-select bg-[var(--input-bg)] text-[var(--text-secondary)] border border-[var(--input-border)] rounded-lg px-3 py-2 text-sm min-w-[140px] cursor-pointer transition-all duration-200 focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 focus:shadow-[0_0_0_3px_var(--color-primary)/20]"
[(ngModel)]="language"
>
<option value="fa">فارسی</option>
<option value="en">English</option>
</select>
</div>
</div>
<div
class="setting-item flex items-center justify-between gap-4 p-4 bg-[var(--card-bg)] rounded-xl shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all duration-200 hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)] hover:-translate-y-0.5"
>
<div class="setting-info flex flex-col gap-1 min-w-0">
<span class="text-sm font-medium text-[var(--text-secondary)]">اعلان‌ها</span>
<span class="text-xs text-[var(--text-muted)]">دریافت اعلان‌های برنامه</span>
</div>
<div class="setting-control shrink-0">
<label class="toggle-switch" [class.toggle-active]="notificationsEnabled()">
<input type="checkbox" [(ngModel)]="notificationsEnabled" />
<span class="toggle-slider"></span>
</label>
</div>
</div>
<div
class="setting-item flex items-center justify-between gap-4 p-4 bg-[var(--card-bg)] rounded-xl shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all duration-200 hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)] hover:-translate-y-0.5"
>
<div class="setting-info flex flex-col gap-1 min-w-0">
<span class="text-sm font-medium text-[var(--text-secondary)]">حالت تاریک</span>
<span class="text-xs text-[var(--text-muted)]">تغییر ظاهر برنامه به حالت تیره</span>
</div>
<div class="setting-control shrink-0">
<label class="toggle-switch" [class.toggle-active]="isDarkMode()">
<input type="checkbox" [checked]="isDarkMode()" (change)="toggleDarkMode()" />
<span class="toggle-slider"></span>
</label>
</div>
</div>
<div
class="setting-item flex items-center justify-between gap-4 p-4 bg-[var(--card-bg)] rounded-xl shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all duration-200 hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)] hover:-translate-y-0.5"
>
<div class="setting-info flex flex-col gap-1 min-w-0">
<span class="text-sm font-medium text-[var(--text-secondary)]">حالت RTL</span>
<span class="text-xs text-[var(--text-muted)]"
>جهت متن راست‌به‌چپ (فارسی/عربی)</span
>
</div>
<div class="setting-control shrink-0">
<label class="toggle-switch" [class.toggle-active]="isRTL()">
<input type="checkbox" [checked]="isRTL()" (change)="toggleRTL()" />
<span class="toggle-slider"></span>
</label>
</div>
</div>
</div>
</section>
}
</div>
</div>
</div>
+89
View File
@@ -0,0 +1,89 @@
import { ChangeDetectionStrategy, Component, signal, inject, computed, effect } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ThemeService } from '../../services/theme/theme.service';
type TabId = 'faq' | 'app';
@Component({
selector: 'app-settings',
standalone: true,
imports: [CommonModule, FormsModule],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './settings.page.html',
styleUrl: './settings.page.css',
})
export class SettingsPage {
private readonly themeService = inject(ThemeService);
readonly tabs: { id: TabId; label: string }[] = [
{ id: 'faq', label: 'آپلود FAQ' },
{ id: 'app', label: 'تنظیمات برنامه' },
];
readonly activeTab = signal<TabId>('faq');
readonly uploadedFiles = signal<File[]>([]);
readonly isDragging = signal(false);
readonly language = signal('fa');
readonly notificationsEnabled = signal(true);
readonly isDarkMode = this.themeService.isDarkMode;
readonly isRTL = signal(true);
selectTab(id: TabId): void {
this.activeTab.set(id);
}
onFileSelected(event: Event): void {
const input = event.target as HTMLInputElement;
const files = input.files ? Array.from(input.files) : [];
this.uploadedFiles.set(files);
}
onDragOver(event: DragEvent): void {
event.preventDefault();
this.isDragging.set(true);
}
onDragLeave(): void {
this.isDragging.set(false);
}
onDrop(event: DragEvent): void {
event.preventDefault();
this.isDragging.set(false);
const files = event.dataTransfer?.files ? Array.from(event.dataTransfer.files) : [];
this.uploadedFiles.set(files);
}
removeFile(index: number): void {
this.uploadedFiles.update((files) => files.filter((_, i) => i !== index));
}
clearAllFiles(): void {
this.uploadedFiles.set([]);
}
formatFileSize(bytes: number): string {
if (bytes === 0) return '0 بایت';
const k = 1024;
const sizes = ['بایت', 'کیلوبایت', 'مگابایت', 'گیگابایت'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
toggleDarkMode(): void {
this.themeService.toggleDarkMode();
}
toggleRTL(): void {
this.isRTL.update(val => !val);
document.documentElement.dir = this.isRTL() ? 'rtl' : 'ltr';
document.body.style.direction = this.isRTL() ? 'rtl' : 'ltr';
}
get fileCount(): number {
return this.uploadedFiles().length;
}
}
+17
View File
@@ -0,0 +1,17 @@
import { TestBed } from '@angular/core/testing';
import { CanActivateFn } from '@angular/router';
import { authGuard } from './auth.guard';
describe('authGuard', () => {
const executeGuard: CanActivateFn = (...guardParameters) =>
TestBed.runInInjectionContext(() => authGuard(...guardParameters));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it('should be created', () => {
expect(executeGuard).toBeTruthy();
});
});
+15
View File
@@ -0,0 +1,15 @@
import { CanActivateFn, Router } from '@angular/router';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = () => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isAuthenticated()) {
return true;
}
router.navigate(['/login']);
return false;
};
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let service: AuthService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(AuthService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
+65
View File
@@ -0,0 +1,65 @@
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject, forkJoin, of } from 'rxjs';
import { tap, map, switchMap, catchError } from 'rxjs/operators';
import { HttpService } from '../http-request/http.service';
interface ApiResult<T> {
hasError: boolean;
messages: string[];
result: T;
}
interface LoginResponse {
auth: boolean;
token: string;
username: string;
}
interface LoginResult extends ApiResult<LoginResponse> {
licenseValid?: boolean;
}
@Injectable({
providedIn: 'root',
})
export class AuthService {
public currentUserSubject = new BehaviorSubject<string | null>(
localStorage.getItem('username'),
);
constructor(
private httpService: HttpService,
) {
let previousUser: string | null = this.currentUserSubject.value;
this.currentUserSubject.subscribe((username) => {
if (username !== previousUser) {
previousUser = username;
}
});
}
login(credentials: {
username: string;
password: string;
rememberMe: boolean;
}): Observable<LoginResult> {
return this.httpService.post<LoginResponse>('users/login', credentials).pipe(
tap((response: ApiResult<LoginResponse>) => {
if (!response.hasError && response.result?.auth) {
localStorage.setItem('access_token', response.result.token);
localStorage.setItem('username', response.result.username);
this.currentUserSubject.next(response.result.username);
}
}),
);
}
logout(): void {
localStorage.removeItem('access_token');
localStorage.removeItem('username');
this.currentUserSubject.next(null);
}
isAuthenticated(): boolean {
return !!localStorage.getItem('access_token');
}
}
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { HttpService } from './http.service';
describe('HttpService', () => {
let service: HttpService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(HttpService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,304 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { catchError, Observable, throwError, map } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
export interface ApiResult<T> {
hasError: boolean;
messages: string[];
result: T;
}
export interface ApiResultArray<T> {
hasError: boolean;
messages: string[];
result: {
data: T[];
};
}
export interface HttpOptions {
params?: any;
skipToast?: boolean;
cooldownMs?: number;
skipHasErrorCheck?: boolean;
headers?: Record<string, string>;
}
export const EVENT_STREAM_HEADERS = {
Accept: 'text/event-stream',
'Cache-Control': 'no-cache',
'X-Requested-With': 'XMLHttpRequest',
};
@Injectable({
providedIn: 'root',
})
export class HttpService {
private readonly baseUrl = `${window.location.protocol}//${window.location.hostname}/api`;
public readonly backendUrl = `${window.location.protocol}//${window.location.hostname}/api`;
public readonly apiUrl = `${window.location.protocol}//${window.location.hostname}/api`;
public readonly imagesUrl = `${window.location.protocol}//${window.location.hostname}`;
constructor(
private readonly http: HttpClient,
private readonly router: Router,
private readonly toast: ToastrService,
private readonly modal: NgbModal,
) {
this.messageCooldowns = new Map();
this.DEFAULT_COOLDOWN_MS = 30000;
}
private readonly messageCooldowns: Map<string, number>;
private readonly DEFAULT_COOLDOWN_MS: number;
private getToken(): string | null {
return localStorage.getItem('access_token');
}
private getHeaders(): HttpHeaders {
const token = this.getToken();
let headers = new HttpHeaders();
if (token) {
headers = headers.set('Authorization', `Bearer ${token}`);
}
return headers;
}
private shouldDisplayMessage(message: string, customCooldown?: number): boolean {
const cooldown = customCooldown ?? this.DEFAULT_COOLDOWN_MS;
const now = Date.now();
const lastShown = this.messageCooldowns.get(message);
if (lastShown !== undefined && now - lastShown < cooldown) {
return false;
}
this.messageCooldowns.set(message, now);
return true;
}
private handleUnauthorized(): void {
this.toast.clear();
localStorage.removeItem('access_token');
this.modal.dismissAll();
this.toast.error('جلسه منقضی شده است. لطفاً دوباره وارد شوید.');
this.router.navigate(['/login']);
}
private handleError(error: HttpErrorResponse, skipToast = false): Observable<never> {
if (error.status === 401) {
this.handleUnauthorized();
return throwError(() => new Error('Unauthorized'));
}
if (error.status === 422 && error.error && !skipToast) {
try {
const apiError = error.error as ApiResult<any>;
if (apiError?.hasError && Array.isArray(apiError.messages)) {
apiError.messages.forEach((msg) => {
if (this.shouldDisplayMessage(msg)) {
this.toast.error(msg);
}
});
return throwError(() => new Error(apiError.messages.join('; ')));
}
} catch (e) {
if (this.shouldDisplayMessage('خطای نامشخص در پردازش پاسخ سرور.')) {
this.toast.error('خطای نامشخص در پردازش پاسخ سرور.');
}
return throwError(() => new Error('Invalid server response'));
}
}
return throwError(() => error);
}
private processResponse<T>(response: ApiResult<T>, options?: HttpOptions): ApiResult<T> {
if (!response || !Array.isArray(response.messages)) {
if (
!options?.skipToast &&
this.shouldDisplayMessage('پاسخ سرور نامعتبر است.', options?.cooldownMs)
) {
this.toast.error('پاسخ سرور نامعتبر است.');
}
throw new Error('Invalid server response');
}
if (!options?.skipToast) {
response.messages.forEach((message) => {
if (!this.shouldDisplayMessage(message, options?.cooldownMs)) {
return;
}
response.hasError ? this.toast.error(message) : this.toast.success(message);
});
}
if (response.hasError && !options?.skipHasErrorCheck) {
throw new Error(response.messages.join('; '));
}
return response;
}
get<T>(endpoint: string, options: HttpOptions = {}): Observable<ApiResult<T>> {
const url = `${this.baseUrl}/${endpoint}`;
const headers = this.mergeHeaders(options.headers);
return this.http
.get<ApiResult<T>>(url, {
headers,
params: options.params,
})
.pipe(
map((response) => this.processResponse(response, options)),
catchError((err) => this.handleError(err, options.skipToast)),
);
}
private getAuthHeaderObject(): Record<string, string> {
const token = this.getToken();
return token ? { Authorization: `Bearer ${token}` } : {};
}
private mergeHeaders(extra?: Record<string, string>): HttpHeaders {
let headers = this.getHeaders();
if (extra) {
Object.entries(extra).forEach(([key, value]) => {
headers = headers.set(key, value as string);
});
}
return headers;
}
getStream<T = any>(endpoint: string, headers: Record<string, string> = {}): Observable<T> {
const url = `${this.baseUrl}/${endpoint}`;
return new Observable<T>((observer) => {
const controller = new AbortController();
fetch(url, {
method: 'GET',
headers: {
...EVENT_STREAM_HEADERS,
...this.getAuthHeaderObject(),
...headers,
},
signal: controller.signal,
credentials: 'omit',
})
.then((response) => {
if (!response.ok || !response.body) {
throw new Error(`Stream request failed: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
const pump = (): void => {
reader
.read()
.then(({ done, value }) => {
if (done) {
observer.complete();
return;
}
buffer += decoder.decode(value, { stream: true });
const frames = buffer.split('\n\n');
buffer = frames.pop() ?? '';
for (const frame of frames) {
const dataLines = frame
.split('\n')
.filter((line) => line.startsWith('data:'))
.map((line) => line.slice(5).trim());
if (dataLines.length === 0) continue;
const payload = dataLines.join('\n');
try {
observer.next(JSON.parse(payload) as T);
} catch {
observer.next(payload as unknown as T);
}
}
pump();
})
.catch((err) => {
if (!controller.signal.aborted) observer.error(err);
});
};
pump();
})
.catch((err) => observer.error(err));
return () => controller.abort();
});
}
post<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<ApiResult<T>> {
const url = `${this.baseUrl}/${endpoint}`;
return this.http
.post<ApiResult<T>>(url, data, {
headers: this.mergeHeaders(options.headers),
params: options.params,
})
.pipe(
map((response) => this.processResponse(response, options)),
catchError((err) => this.handleError(err, options.skipToast)),
);
}
put<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<ApiResult<T>> {
const url = `${this.baseUrl}/${endpoint}`;
return this.http
.put<ApiResult<T>>(url, data, {
headers: this.mergeHeaders(options.headers),
params: options.params,
})
.pipe(
map((response) => this.processResponse(response, options)),
catchError((err) => this.handleError(err, options.skipToast)),
);
}
patch<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<ApiResult<T>> {
const url = `${this.baseUrl}/${endpoint}`;
return this.http
.patch<ApiResult<T>>(url, data, {
headers: this.mergeHeaders(options.headers),
params: options.params,
})
.pipe(
map((response) => this.processResponse(response, options)),
catchError((err) => this.handleError(err, options.skipToast)),
);
}
delete<T>(endpoint: string, options: HttpOptions = {}): Observable<ApiResult<T>> {
const url = `${this.baseUrl}/${endpoint}`;
return this.http
.delete<ApiResult<T>>(url, {
headers: this.mergeHeaders(options.headers),
params: options.params,
})
.pipe(
map((response) => this.processResponse(response, options)),
catchError((err) => this.handleError(err, options.skipToast)),
);
}
downloadFile(endpoint: string): Observable<Blob> {
const url = `${this.baseUrl}/${endpoint}`;
return this.http
.get(url, {
headers: this.getHeaders(),
responseType: 'blob',
})
.pipe(catchError((err) => this.handleError(err, false)));
}
}
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { ThemeService } from './theme.service';
describe('ThemeService', () => {
let service: ThemeService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ThemeService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
+61
View File
@@ -0,0 +1,61 @@
import { Injectable } from '@angular/core';
import { signal } from '@angular/core';
import { HttpService } from '../http-request/http.service';
@Injectable({
providedIn: 'root'
})
export class ThemeService {
private readonly _isDarkMode = signal<boolean>(false);
readonly isDarkMode = this._isDarkMode.asReadonly();
constructor(private httpService: HttpService) {
this.initTheme();
}
initTheme(): void {
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
this.applyTheme(savedTheme);
} else {
this.applyTheme('light');
}
this.httpService.get('users/get-dark-mode').subscribe({
next: (res: any) => {
const isBackendDark = res.result.dark_mode;
const trueTheme = isBackendDark ? 'dark' : 'light';
if (savedTheme !== trueTheme) {
this.applyTheme(trueTheme);
localStorage.setItem('theme', trueTheme);
}
},
error: () => {}
});
}
toggleDarkMode(): void {
const isDark = !this._isDarkMode();
const theme = isDark ? 'dark' : 'light';
const payload = { dark_mode: isDark };
this.httpService.post('users/update-dark-mode', payload).subscribe({
next: () => {},
error: () => {}
});
this.applyTheme(theme);
localStorage.setItem('theme', theme);
}
private applyTheme(theme: string): void {
document.documentElement.setAttribute('data-bs-theme', theme);
this._isDarkMode.set(theme === 'dark');
}
get isDarkModeSync(): boolean {
return this._isDarkMode();
}
}
@@ -0,0 +1,519 @@
.sidebar {
position: fixed;
top: 0;
right: 0;
bottom: 0;
width: 260px;
background: var(--sidebar-bg);
color: var(--sidebar-text);
transform: translateX(0);
transition: width 0.3s ease;
z-index: 40;
display: flex;
flex-direction: column;
border-left: 1px solid var(--sidebar-border);
}
.sidebar.open {
width: 260px;
}
.sidebar:not(.open) {
width: 72px;
padding-bottom: 0.5rem;
}
.sidebar-inner {
display: flex;
flex-direction: column;
flex: 1;
overflow: hidden;
}
.sidebar-top {
padding: 0.75rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.sidebar-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.5rem;
min-height: 48px;
position: relative;
overflow: hidden;
}
.sidebar-logo {
height: 32px;
width: auto;
object-fit: contain;
}
.sidebar-logo-link {
display: inline-flex;
align-items: center;
cursor: pointer;
position: relative;
overflow: hidden;
}
.sidebar-logo-link:hover .sidebar-logo {
opacity: 0.85;
}
.sidebar:not(.open) .sidebar-logo-link {
justify-content: center;
width: 100%;
}
.sidebar:not(.open) .sidebar-logo {
height: 36px;
}
.sidebar:not(.open) .sidebar-header {
justify-content: center;
padding: 0.5rem 0.25rem;
}
.sidebar:not(.open) .close-btn {
display: none;
}
.sidebar-open-icon {
position: absolute;
inset: 0;
margin: auto;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 0.5rem;
background: var(--surface-bg);
color: var(--sidebar-text);
border: 1px solid var(--sidebar-border);
box-shadow: 0 8px 24px rgb(0 0 0 / 12%);
opacity: 0;
visibility: hidden;
transition: opacity 0.2s, visibility 0.2s;
}
.sidebar:not(.open) .sidebar-logo-link:hover .sidebar-logo {
opacity: 0;
visibility: hidden;
}
.sidebar:not(.open) .sidebar-logo-link:hover .sidebar-open-icon {
opacity: 1;
visibility: visible;
}
.sidebar-title {
font-size: 1rem;
font-weight: 600;
margin: 0;
color: var(--sidebar-text);
}
.close-btn {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border: none;
background: transparent;
color: var(--sidebar-muted);
border-radius: 0.375rem;
cursor: pointer;
transition: background 0.2s;
flex-shrink: 0;
}
.close-btn:hover {
background: var(--sidebar-hover);
}
.sidebar:not(.open) .close-btn {
display: none;
}
.new-chat-btn {
display: flex;
align-items: center;
gap: 0.75rem;
width: 100%;
padding: 0.75rem;
border: 1px solid var(--sidebar-border);
background: transparent;
color: var(--sidebar-text);
border-radius: 0.5rem;
cursor: pointer;
font-size: 0.875rem;
transition: background 0.2s;
text-align: start;
}
.new-chat-btn:hover {
background: var(--sidebar-hover);
}
.nav-menu {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.nav-item {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem;
border-radius: 0.5rem;
color: var(--sidebar-muted);
text-decoration: none;
font-size: 0.875rem;
transition: background 0.2s;
}
.nav-item:hover {
background: var(--sidebar-hover);
}
.nav-item.active {
background: var(--sidebar-hover);
color: var(--sidebar-text);
font-weight: 500;
}
.sidebar:not(.open) .nav-item {
justify-content: center;
padding: 0.75rem 0;
}
.sidebar:not(.open) .nav-item svg {
margin: 0;
}
.sidebar:not(.open) .nav-label {
display: none;
}
.sidebar-divider {
height: 1px;
background: var(--sidebar-border);
margin: 0 0.75rem;
}
.sidebar:not(.open) .sidebar-divider {
margin: 0 0.5rem;
}
.sidebar-bottom {
flex: 1;
overflow-y: auto;
padding: 0.75rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.sidebar:not(.open) .sidebar-bottom {
display: none;
}
.history-header {
padding: 0.25rem 0.5rem;
font-size: 0.75rem;
font-weight: 500;
color: var(--sidebar-muted);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.sidebar:not(.open) .history-header {
display: none;
}
.history-list {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.history-item {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem;
border: none;
background: transparent;
color: var(--sidebar-muted);
border-radius: 0.5rem;
cursor: pointer;
font-size: 0.875rem;
text-align: start;
transition: background 0.2s;
width: 100%;
}
.history-item:hover {
background: var(--sidebar-hover);
}
.sidebar:not(.open) .history-item {
justify-content: center;
padding: 0.75rem 0;
}
.sidebar:not(.open) .history-item svg {
margin: 0;
}
.history-icon {
flex-shrink: 0;
opacity: 0.7;
}
.history-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.sidebar:not(.open) .history-text {
display: none;
}
.history-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 1.5rem 0.75rem;
font-size: 0.875rem;
color: var(--sidebar-muted);
text-align: center;
}
.sidebar:not(.open) .history-empty {
display: none;
}
.history-empty-icon {
opacity: 0.5;
margin-bottom: 0.25rem;
}
.sidebar-footer {
padding: 0.75rem;
border-top: 1px solid var(--sidebar-border);
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-top: auto;
}
.sidebar:not(.open) .sidebar-footer {
align-items: center;
padding: 0.5rem;
margin-top: auto;
}
.sidebar:not(.open) .user-info {
display: none;
}
.sidebar:not(.open) .user-profile {
width: 56px;
height: 56px;
padding: 0;
border-radius: 50%;
justify-content: center;
}
.sidebar:not(.open) .theme-toggle span {
display: none;
}
.user-profile {
display: flex;
align-items: center;
gap: 0.75rem;
width: 100%;
padding: 0.5rem;
border: none;
border-radius: 0.75rem;
background: transparent;
color: var(--sidebar-text);
text-align: start;
cursor: pointer;
}
.user-profile:hover,
.user-profile.menu-open {
background: var(--sidebar-hover);
}
.user-profile:focus-visible,
.account-menu-item:focus-visible {
outline: 2px solid var(--sidebar-muted);
outline-offset: -2px;
}
.account-menu {
width: 236px;
max-width: calc(100vw - 24px);
padding: 0.5rem;
border: 1px solid var(--sidebar-border);
border-radius: 1.25rem;
background: var(--surface-bg);
color: var(--sidebar-text);
box-shadow: 0 8px 24px rgb(0 0 0 / 12%);
}
.account-menu-header {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem;
}
.account-menu-divider {
height: 1px;
margin: 0.375rem 0.5rem;
background: var(--sidebar-border);
}
.account-menu-item {
display: flex;
align-items: center;
gap: 0.75rem;
width: 100%;
padding: 0.625rem 0.75rem;
border: none;
border-radius: 0.5rem;
background: transparent;
color: inherit;
font-size: 0.875rem;
text-align: start;
cursor: pointer;
}
.account-menu-item:hover,
.account-menu-item:focus {
background: var(--sidebar-hover);
}
.account-menu-item svg {
flex-shrink: 0;
}
.user-avatar {
width: 32px;
height: 32px;
border-radius: 50%;
background: var(--sidebar-hover);
color: var(--sidebar-text);
display: flex;
align-items: center;
justify-content: center;
font-size: 0.75rem;
font-weight: 500;
flex-shrink: 0;
}
.user-info {
display: flex;
flex-direction: column;
gap: 0.125rem;
overflow: hidden;
}
.user-name {
font-size: 0.875rem;
font-weight: 500;
color: var(--sidebar-text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.claim-btn {
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
width: 100%;
padding: 0.625rem;
border: 1px solid var(--sidebar-border);
background: transparent;
color: var(--sidebar-text);
border-radius: 0.5rem;
cursor: pointer;
font-size: 0.875rem;
transition: background 0.2s;
}
.claim-btn:hover {
background: var(--sidebar-hover);
}
.sidebar:not(.open) .claim-btn {
width: 40px;
height: 40px;
padding: 0;
border-radius: 0.5rem;
justify-content: center;
}
.sidebar:not(.open) .claim-btn svg {
margin: 0;
}
.sidebar:not(.open) .claim-btn span {
display: none;
}
.theme-toggle {
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
width: 100%;
padding: 0.625rem;
border: 1px solid var(--sidebar-border);
background: transparent;
color: var(--sidebar-text);
border-radius: 0.5rem;
cursor: pointer;
font-size: 0.875rem;
transition: background 0.2s;
}
.theme-toggle:hover {
background: var(--sidebar-hover);
}
.sidebar:not(.open) .theme-toggle {
width: 56px;
height: 56px;
padding: 0;
border-radius: 0.5rem;
justify-content: center;
}
.sidebar:not(.open) .theme-toggle svg {
margin: 0;
}
.sidebar:not(.open) .theme-toggle span {
display: none;
}
@@ -0,0 +1,189 @@
<aside class="sidebar" [class.open]="isOpen()">
<div class="sidebar-inner">
<div class="sidebar-top">
<div class="sidebar-header">
<a
class="sidebar-logo-link"
[routerLink]="isOpen() ? '/' : null"
(click)="onLogoClick()"
>
<img class="sidebar-logo" [src]="isDarkMode() ? 'assets/images/RaymandLogo.png' : 'assets/images/login.png'" alt="Raymand" />
<span class="sidebar-open-icon" aria-hidden="true">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M4 6h16M4 12h16M4 18h16" />
</svg>
</span>
</a>
<button type="button" class="close-btn" (click)="close.emit()" aria-label="Close sidebar">
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<path d="M18 6L6 18M6 6l12 12" />
</svg>
</button>
</div>
<nav class="nav-menu">
@for (item of navItems(); track item.label) {
<a
[routerLink]="item.route"
class="nav-item"
routerLinkActive="active"
(click)="onNavClick()"
>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<path [attr.d]="item.icon" />
</svg>
<span class="nav-label">{{ item.label }}</span>
</a>
}
</nav>
</div>
<div class="sidebar-divider"></div>
<div class="sidebar-bottom">
<div class="history-header">
<span class="history-title">گفتگوهای اخیر</span>
</div>
<div class="history-list">
@for (item of chatHistory(); track item.id) {
<button type="button" class="history-item">
<svg
class="history-icon"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" />
</svg>
<span class="history-text">{{ item.title }}</span>
</button>
} @empty {
<div class="history-empty">
<svg
width="32"
height="32"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
class="history-empty-icon"
>
<path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" />
</svg>
<span>گفتگویی ثبت نشده است</span>
</div>
}
</div>
</div>
<div class="sidebar-footer">
<button
type="button"
class="user-profile"
[cdkMenuTriggerFor]="accountMenu"
[cdkMenuPosition]="[
{ originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', offsetY: -8 },
{ originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top', offsetY: 8 }
]"
#accountMenuTrigger="cdkMenuTriggerFor"
[class.menu-open]="accountMenuTrigger.isOpen()"
aria-label="Open account menu"
>
<div class="user-avatar">
{{ userInitials() }}
</div>
<div class="user-info">
<span class="user-name">{{ userName() }}</span>
</div>
</button>
<ng-template #accountMenu>
<div class="account-menu" cdkMenu aria-label="Account menu" dir="ltr">
<div class="account-menu-header">
<div class="user-avatar">{{ userInitials() }}</div>
<div class="user-info">
<span class="user-name">{{ userName() }}</span>
</div>
</div>
<div class="account-menu-divider" role="separator"></div>
<button type="button" class="account-menu-item" cdkMenuItem (cdkMenuItemTriggered)="profileClick.emit()">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="12" cy="12" r="9" />
<circle cx="12" cy="9" r="3" />
<path d="M6 18a6 6 0 0 1 12 0" />
</svg>
<span>Profile</span>
</button>
<div class="account-menu-divider" role="separator"></div>
<button type="button" class="account-menu-item" cdkMenuItem (cdkMenuItemTriggered)="logoutClick.emit()">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9" />
</svg>
<span>Log out</span>
</button>
</div>
</ng-template>
<button
type="button"
class="theme-toggle"
(click)="toggleTheme()"
aria-label="Toggle dark mode"
>
@if (isDarkMode()) {
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="5" />
<line x1="12" y1="1" x2="12" y2="3" />
<line x1="12" y1="21" x2="12" y2="23" />
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
<line x1="1" y1="12" x2="3" y2="12" />
<line x1="21" y1="12" x2="23" y2="12" />
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
</svg>
<span>حالت روشن</span>
} @else {
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
</svg>
<span>حالت تاریک</span>
}
</button>
</div>
</div>
</aside>
@@ -0,0 +1,74 @@
import { ChangeDetectionStrategy, Component, input, output, computed, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CdkMenuModule } from '@angular/cdk/menu';
import { RouterModule } from '@angular/router';
import { ThemeService } from '../../../services/theme/theme.service';
export interface NavItem {
icon: string;
label: string;
route?: string;
}
export interface ChatHistoryItem {
id: string;
title: string;
}
@Component({
selector: 'app-sidebar',
standalone: true,
imports: [CommonModule, RouterModule, CdkMenuModule],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './sidebar.component.html',
styleUrl: './sidebar.component.css'
})
export class SidebarComponent {
private readonly themeService = inject(ThemeService);
readonly isOpen = input<boolean>(false);
readonly userName = input<string>('Peyman Honarjoo');
readonly navItems = input<NavItem[]>([
{
icon: 'M12 5v14M5 12h14',
label: 'چت جدید',
},
{
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',
label: 'تنظیمات',
route: '/settings',
},
]);
readonly chatHistory = input<ChatHistoryItem[]>([]);
readonly close = output<void>();
readonly navClick = output<void>();
readonly open = output<void>();
readonly profileClick = output<void>();
readonly logoutClick = output<void>();
readonly userInitials = computed(() => {
const name = this.userName();
return name
.split(' ')
.map((n) => n[0])
.join('')
.slice(0, 2)
.toUpperCase();
});
readonly isDarkMode = this.themeService.isDarkMode;
toggleTheme(): void {
this.themeService.toggleDarkMode();
}
onNavClick(): void {
this.navClick.emit();
}
onLogoClick(): void {
if (!this.isOpen()) {
this.open.emit();
}
}
}
+82 -1
View File
@@ -1 +1,82 @@
/* You can add global styles to this file, and also import other style files */
@import "tailwindcss";
@import "@angular/cdk/overlay-prebuilt.css";
@theme {
--color-primary: #3b82f6;
--color-secondary: #64748b;
--color-success: #22c55e;
--color-warning: #f59e0b;
--color-danger: #ef4444;
--color-info: #06b6d4;
--color-card-bg: #ffffff;
--color-card-border: #e2e8f0;
--color-text-primary: #122033;
--color-text-secondary: #374151;
--color-text-muted: #64748b;
--color-input-bg: #ffffff;
--color-input-border: #d1d5db;
--color-dropzone-bg: #f8fafc;
--color-dropzone-border: #e2e8f0;
}
:root {
--app-bg: #f8fafc;
--app-text: #122033;
--sidebar-bg: #f8fafc;
--sidebar-text: #122033;
--sidebar-muted: #64748b;
--sidebar-border: #e2e8f0;
--sidebar-hover: #f1f5f9;
--surface-bg: #ffffff;
--surface-border: #e2e8f0;
--muted: #64748b;
--overlay: rgba(0, 0, 0, 0.5);
--menu-toggle-color: #122033;
--menu-toggle-hover: #f1f5f9;
--main-content-bg: #f8fafc;
--toggle-bg: #e5e7eb;
--toggle-slider: #ffffff;
}
[data-bs-theme="dark"] {
--app-bg: #212121;
--app-text: #ececec;
--sidebar-bg: #171717;
--sidebar-text: #ececec;
--sidebar-muted: #8e8e8e;
--sidebar-border: #2e2e2e;
--sidebar-hover: #2e2e2e;
--surface-bg: #171717;
--surface-border: #2e2e2e;
--muted: #8e8e8e;
--overlay: rgba(0, 0, 0, 0.6);
--menu-toggle-color: #ececec;
--menu-toggle-hover: #2e2e2e;
--main-content-bg: #212121;
--toggle-bg: #3e3e3e;
--toggle-slider: #f8fafc;
--color-card-bg: #171717;
--color-card-border: #2e2e2e;
--color-text-primary: #f8fafc;
--color-text-secondary: #cbd5e1;
--color-text-muted: #8e8e8e;
--color-input-bg: #171717;
--color-input-border: #3e3e3e;
--color-dropzone-bg: rgba(23, 23, 23, 0.6);
--color-dropzone-border: #3e3e3e;
}
* {
font-family: "Vazir", sans-serif;
}
body {
direction: rtl;
font-family: "Vazir", sans-serif;
text-align: right;
background: var(--app-bg);
color: var(--app-text);
margin: 0;
padding: 0;
}
+62
View File
@@ -0,0 +1,62 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./src/**/*.{html,ts}',
],
darkMode: ['selector', '[data-bs-theme="dark"]'],
theme: {
extend: {
colors: {
primary: {
DEFAULT: '#3b82f6',
hover: '#2563eb',
},
secondary: {
DEFAULT: '#64748b',
hover: '#475569',
},
success: {
DEFAULT: '#22c55e',
hover: '#16a34a',
},
warning: {
DEFAULT: '#f59e0b',
hover: '#d97706',
},
danger: {
DEFAULT: '#ef4444',
hover: '#dc2626',
},
info: {
DEFAULT: '#06b6d4',
hover: '#0891b2',
},
light: {
DEFAULT: '#f8fafc',
hover: '#e2e8f0',
},
dark: {
DEFAULT: '#122033',
hover: '#1e293b',
},
surface: {
DEFAULT: '#ffffff',
dark: '#1a2b42',
border: '#e2e8f0',
'border-dark': '#263c57',
},
sidebar: {
bg: '#171717',
text: '#ececec',
muted: '#c5c5c5',
border: '#2e2e2e',
hover: '#2e2e2e',
},
},
fontFamily: {
sans: ['Vazir', 'sans-serif'],
},
},
},
plugins: [],
};
+10 -1
View File
@@ -13,7 +13,16 @@
"experimentalDecorators": true,
"importHelpers": true,
"target": "ES2022",
"module": "preserve"
"module": "preserve",
"moduleResolution": "bundler",
"lib": ["ES2022", "dom", "dom.iterable"],
"baseUrl": ".",
"paths": {
"@core/*": ["src/app/core/*"],
"@features/*": ["src/app/features/*"],
"@shared/*": ["src/app/shared/*"],
"@env/*": ["src/environments/*"]
}
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
+2 -8
View File
@@ -1,14 +1,8 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
"types": ["vitest/globals"]
},
"include": [
"src/**/*.ts"
]
"include": ["src/**/*.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
}