@cngx/common 0.0.1-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -0
  3. package/a11y/README.md +77 -0
  4. package/card/README.md +79 -0
  5. package/chart/README.md +31 -0
  6. package/data/README.md +883 -0
  7. package/dialog/README.md +84 -0
  8. package/display/README.md +30 -0
  9. package/fesm2022/cngx-common-a11y.mjs +1260 -0
  10. package/fesm2022/cngx-common-a11y.mjs.map +1 -0
  11. package/fesm2022/cngx-common-card.mjs +765 -0
  12. package/fesm2022/cngx-common-card.mjs.map +1 -0
  13. package/fesm2022/cngx-common-chart.mjs +2943 -0
  14. package/fesm2022/cngx-common-chart.mjs.map +1 -0
  15. package/fesm2022/cngx-common-data.mjs +2886 -0
  16. package/fesm2022/cngx-common-data.mjs.map +1 -0
  17. package/fesm2022/cngx-common-dialog.mjs +1366 -0
  18. package/fesm2022/cngx-common-dialog.mjs.map +1 -0
  19. package/fesm2022/cngx-common-display.mjs +1603 -0
  20. package/fesm2022/cngx-common-display.mjs.map +1 -0
  21. package/fesm2022/cngx-common-interactive.mjs +8185 -0
  22. package/fesm2022/cngx-common-interactive.mjs.map +1 -0
  23. package/fesm2022/cngx-common-layout.mjs +1335 -0
  24. package/fesm2022/cngx-common-layout.mjs.map +1 -0
  25. package/fesm2022/cngx-common-popover.mjs +1200 -0
  26. package/fesm2022/cngx-common-popover.mjs.map +1 -0
  27. package/fesm2022/cngx-common-stepper.mjs +1350 -0
  28. package/fesm2022/cngx-common-stepper.mjs.map +1 -0
  29. package/fesm2022/cngx-common-tabs.mjs +1551 -0
  30. package/fesm2022/cngx-common-tabs.mjs.map +1 -0
  31. package/fesm2022/cngx-common.mjs +34 -0
  32. package/fesm2022/cngx-common.mjs.map +1 -0
  33. package/interactive/README.md +211 -0
  34. package/layout/README.md +117 -0
  35. package/package.json +100 -0
  36. package/popover/README.md +218 -0
  37. package/stepper/README.md +102 -0
  38. package/tabs/README.md +32 -0
  39. package/types/cngx-common-a11y.d.ts +616 -0
  40. package/types/cngx-common-card.d.ts +413 -0
  41. package/types/cngx-common-chart.d.ts +1081 -0
  42. package/types/cngx-common-data.d.ts +1460 -0
  43. package/types/cngx-common-dialog.d.ts +772 -0
  44. package/types/cngx-common-display.d.ts +1136 -0
  45. package/types/cngx-common-interactive.d.ts +5013 -0
  46. package/types/cngx-common-layout.d.ts +737 -0
  47. package/types/cngx-common-popover.d.ts +520 -0
  48. package/types/cngx-common-stepper.d.ts +982 -0
  49. package/types/cngx-common-tabs.d.ts +1237 -0
  50. package/types/cngx-common.d.ts +13 -0
package/data/README.md ADDED
@@ -0,0 +1,883 @@
1
+ # @cngx/common/data — Async State System
2
+
3
+ Signal-based state machine for async operations. One typed source drives
4
+ skeleton, loading bar, empty state, error, toast, and ARIA — automatically.
5
+
6
+ ## This Is UX State, Not Data State
7
+
8
+ `CngxAsyncState` is **not** a data store. It does not replace NgRx,
9
+ SignalStore, Akita, or any state management library. It answers a
10
+ different question:
11
+
12
+ | | Data State (SignalStore, NgRx) | UX State (CngxAsyncState) |
13
+ |-|-|-|
14
+ | Question | "What is the data right now?" | "What should the user see right now?" |
15
+ | Owns | Entities, collections, selections | Status, progress, error, timestamps |
16
+ | Drives | Business logic, computed selectors | Skeleton, loading bar, toast, ARIA |
17
+ | Scope | App-wide or feature-wide | Per-operation (one GET, one POST) |
18
+ | Lifecycle | Lives as long as the store | Lives as long as the operation |
19
+
20
+ A SignalStore holds your `Resident[]` collection and knows which
21
+ residents are selected. A `CngxAsyncState<Resident[]>` knows whether
22
+ that collection is currently loading, refreshing, empty, or failed —
23
+ and tells every UI component about it.
24
+
25
+ They compose naturally:
26
+
27
+ ```typescript
28
+ // SignalStore owns the data
29
+ readonly store = inject(ResidentStore);
30
+
31
+ // CngxAsyncState owns the operation lifecycle
32
+ readonly loadState = injectAsyncState(() =>
33
+ this.api.getAll(this.store.filter())
34
+ );
35
+
36
+ // Store updates from state
37
+ constructor() {
38
+ effect(() => {
39
+ const data = this.loadState.data();
40
+ if (data) {
41
+ this.store.setResidents(data);
42
+ }
43
+ });
44
+ }
45
+ ```
46
+
47
+ The store is the truth for data. The async state is the truth for
48
+ what the user should see. Both are signals. Both compose. Neither
49
+ replaces the other.
50
+
51
+ ## The Problem
52
+
53
+ ```typescript
54
+ // Without cngx: 5 booleans, manual sync, no ARIA, no toast
55
+ isLoading = false;
56
+ isRefreshing = false;
57
+ hasError = false;
58
+ isEmpty = false;
59
+ errorMessage = '';
60
+ data: Resident[] = [];
61
+
62
+ async load() {
63
+ this.isLoading = true;
64
+ try {
65
+ this.data = await firstValueFrom(this.http.get<Resident[]>('/api'));
66
+ this.isEmpty = this.data.length === 0;
67
+ } catch (e) {
68
+ this.hasError = true;
69
+ this.errorMessage = e.message;
70
+ } finally {
71
+ this.isLoading = false;
72
+ }
73
+ }
74
+ ```
75
+
76
+ ## The Solution
77
+
78
+ ```typescript
79
+ // With cngx: one source, everything derived
80
+ readonly residents = injectAsyncState(() =>
81
+ this.http.get<Resident[]>('/api/residents', {
82
+ params: { filter: this.filter() },
83
+ })
84
+ );
85
+ // residents.status(), residents.data(), residents.isFirstLoad(),
86
+ // residents.isEmpty(), residents.error(), residents.isBusy()
87
+ // — all computed(), all reactive, all consistent
88
+ ```
89
+
90
+ ---
91
+
92
+ ## Five Factories
93
+
94
+ | Factory | Use Case | Injection Context |
95
+ |-|-|-|
96
+ | `injectAsyncState(fn)` | Reactive query (GET) — auto-reloads on signal change | Required |
97
+ | `createAsyncState()` | Mutation (POST/PUT/DELETE) — explicit `execute()` | Required |
98
+ | `createManualState()` | Full manual control — Web Workers, computations | Not needed |
99
+ | `fromResource(ref)` | Bridge for Angular `resource()` | Required |
100
+ | `fromHttpResource(ref)` | Bridge for Angular `httpResource()` with progress | Required |
101
+
102
+ All return `CngxAsyncState<T>` — the same interface every UI component accepts.
103
+
104
+ ---
105
+
106
+ ## 1. injectAsyncState — Reactive Query
107
+
108
+ Auto-loads when signal dependencies change. First load is `loading`,
109
+ subsequent loads are `refreshing` (old data stays visible).
110
+
111
+ ### Basic GET
112
+
113
+ ```typescript
114
+ private readonly http = inject(HttpClient);
115
+ private readonly filterText = signal('');
116
+
117
+ readonly residents = injectAsyncState(() =>
118
+ this.http.get<Resident[]>('/api/residents', {
119
+ params: { q: this.filterText() }, // tracked — re-queries on change
120
+ })
121
+ );
122
+ ```
123
+
124
+ ### With debounce
125
+
126
+ ```typescript
127
+ readonly results = injectAsyncState(
128
+ () => this.http.get<Item[]>('/api/search', {
129
+ params: { q: this.searchTerm() },
130
+ }),
131
+ { debounce: 300 }, // default: 50ms
132
+ );
133
+ ```
134
+
135
+ ### Manual refresh
136
+
137
+ ```typescript
138
+ // In a "Refresh" button handler:
139
+ this.residents.refresh();
140
+ ```
141
+
142
+ ### Status lifecycle
143
+
144
+ ```text
145
+ Component init: idle → loading → success
146
+ Filter changes: success → refreshing → success (data stays visible)
147
+ Network error: loading → error
148
+ Refresh: success → refreshing → success
149
+ ```
150
+
151
+ ### Template — Structural Directive
152
+
153
+ ```html
154
+ <ul *cngxAsync="residents; let data; skeleton: skelTpl; empty: emptyTpl; error: errTpl">
155
+ @for (r of data; track r.id) {
156
+ <li>{{ r.name }}</li>
157
+ }
158
+ </ul>
159
+
160
+ <ng-template #skelTpl>
161
+ @for (i of [1,2,3]; track i) {
162
+ <div class="skeleton-line"></div>
163
+ }
164
+ </ng-template>
165
+
166
+ <ng-template #emptyTpl>
167
+ <cngx-empty-state title="No residents" />
168
+ </ng-template>
169
+
170
+ <ng-template #errTpl let-err>
171
+ <cngx-alert severity="error">{{ err }}</cngx-alert>
172
+ </ng-template>
173
+ ```
174
+
175
+ ### Template — Async Container (named slots)
176
+
177
+ ```html
178
+ <cngx-async-container [state]="residents" ariaLabel="Residents"
179
+ toastSuccess="Loaded" toastError="Failed to load">
180
+
181
+ <ng-template cngxAsyncSkeleton>
182
+ @for (i of [1,2,3]; track i) {
183
+ <div class="skeleton-card"></div>
184
+ }
185
+ </ng-template>
186
+
187
+ <ng-template cngxAsyncContent let-data>
188
+ @for (r of data; track r.id) {
189
+ <app-resident-card [resident]="r" />
190
+ }
191
+ </ng-template>
192
+
193
+ <ng-template cngxAsyncEmpty>
194
+ <cngx-empty-state title="No residents" />
195
+ </ng-template>
196
+
197
+ <ng-template cngxAsyncError let-err>
198
+ <cngx-alert severity="error">
199
+ {{ err }}
200
+ <button cngxAlertAction (click)="residents.refresh()">Retry</button>
201
+ </cngx-alert>
202
+ </ng-template>
203
+ </cngx-async-container>
204
+ ```
205
+
206
+ ---
207
+
208
+ ## 2. createAsyncState — Mutation
209
+
210
+ For user-triggered actions (POST, PUT, DELETE). Uses `execute(fn)` which
211
+ sets `pending`, then `success` or `error`.
212
+
213
+ ### Save form
214
+
215
+ ```typescript
216
+ readonly saveAction = createAsyncState<Resident>();
217
+
218
+ protected handleSave(): void {
219
+ void this.saveAction.execute(() =>
220
+ firstValueFrom(this.api.save(this.form.value()))
221
+ );
222
+ }
223
+ ```
224
+
225
+ ### Template with action button
226
+
227
+ ```html
228
+ <cngx-action-button [action]="handleSave" variant="primary"
229
+ pendingLabel="Saving..." succeededLabel="Saved">
230
+ Save Resident
231
+ </cngx-action-button>
232
+ ```
233
+
234
+ ### Template with manual status
235
+
236
+ ```html
237
+ <button (click)="handleSave()"
238
+ [disabled]="saveAction.isPending()">
239
+ {{ saveAction.isPending() ? 'Saving...' : 'Save' }}
240
+ </button>
241
+
242
+ <cngx-toast severity="success" message="Saved"
243
+ [when]="saveAction.status() === 'success'" />
244
+ <cngx-toast severity="error" message="Save failed"
245
+ [when]="saveAction.status() === 'error'" />
246
+ ```
247
+
248
+ ### Delete with refresh
249
+
250
+ ```typescript
251
+ readonly deleteAction = createAsyncState<void>();
252
+
253
+ protected handleDelete(id: string): void {
254
+ void this.deleteAction.execute(
255
+ () => firstValueFrom(this.api.delete(id))
256
+ ).then(() => this.residents.refresh());
257
+ }
258
+ ```
259
+
260
+ ### In a dialog
261
+
262
+ ```html
263
+ <dialog cngxDialog #dlg="cngxDialog" [state]="saveAction">
264
+ <h2 cngxDialogTitle>Edit Resident</h2>
265
+ <!-- form content -->
266
+ <button [cngxDialogClose]="true" [disabled]="saveAction.isPending()">
267
+ Save
268
+ </button>
269
+ </dialog>
270
+ ```
271
+
272
+ When `saveAction` is `pending`: dialog prevents close, shows `aria-busy`.
273
+ When `saveAction` is `error`: dialog shows `cngx-dialog--error` class.
274
+
275
+ ---
276
+
277
+ ## 3. createManualState — Full Control
278
+
279
+ No HTTP, no injection context. For Web Workers, heavy computations,
280
+ WebSocket streams, or any scenario where you drive the state yourself.
281
+
282
+ ### Web Worker
283
+
284
+ ```typescript
285
+ readonly computation = createManualState<AnalysisResult>();
286
+
287
+ protected runAnalysis(): void {
288
+ this.computation.set('loading');
289
+ this.computation.setProgress(0);
290
+
291
+ this.worker.postMessage({ type: 'analyze', data: this.dataset() });
292
+ }
293
+
294
+ // In worker message handler:
295
+ handleWorkerMessage(event: MessageEvent): void {
296
+ switch (event.data.type) {
297
+ case 'progress':
298
+ this.computation.setProgress(event.data.value);
299
+ break;
300
+ case 'result':
301
+ this.computation.setSuccess(event.data.result);
302
+ break;
303
+ case 'error':
304
+ this.computation.setError(event.data.message);
305
+ break;
306
+ }
307
+ }
308
+ ```
309
+
310
+ ### Template with progress
311
+
312
+ ```html
313
+ <cngx-progress [state]="computation" variant="linear" />
314
+
315
+ <cngx-async-container [state]="computation" ariaLabel="Analysis">
316
+ <ng-template cngxAsyncSkeleton>
317
+ <p>Running analysis...</p>
318
+ </ng-template>
319
+
320
+ <ng-template cngxAsyncContent let-result>
321
+ <app-analysis-chart [data]="result" />
322
+ </ng-template>
323
+ </cngx-async-container>
324
+ ```
325
+
326
+ ### WebSocket stream
327
+
328
+ ```typescript
329
+ readonly liveData = createManualState<StockPrice[]>();
330
+
331
+ constructor() {
332
+ this.liveData.set('loading');
333
+
334
+ this.ws.messages$.pipe(
335
+ takeUntilDestroyed(),
336
+ ).subscribe({
337
+ next: (prices) => this.liveData.setSuccess(prices),
338
+ error: (err) => this.liveData.setError(err),
339
+ });
340
+ }
341
+ ```
342
+
343
+ ---
344
+
345
+ ## RxJS Operators
346
+
347
+ Three operators that wire Observable pipelines to `ManualAsyncState`
348
+ automatically. No manual `subscribe({ next, error })` boilerplate.
349
+
350
+ | Operator | Input | Output | What it does |
351
+ |-|-|-|-|
352
+ | `tapAsyncState(state)` | `Observable<T>` | `Observable<T>` | `loading` on subscribe, `setSuccess` on next, `setError` on error |
353
+ | `tapAsyncProgress(state)` | `Observable<HttpEvent>` | `Observable<HttpEvent>` | Extracts progress events, calls `setProgress(0-100)` |
354
+ | `tapHttpAsyncState(state)` | `Observable<HttpEvent>` | `Observable<T>` | Combines: loading + progress + body extraction + success/error |
355
+
356
+ ### tapAsyncState — Simple Observable Wiring
357
+
358
+ ```typescript
359
+ readonly residents = createManualState<Resident[]>();
360
+
361
+ load(): void {
362
+ this.http.get<Resident[]>('/api/residents').pipe(
363
+ tapAsyncState(this.residents),
364
+ takeUntilDestroyed(this.destroyRef),
365
+ ).subscribe();
366
+ // residents.status() is 'loading', then 'success' or 'error'
367
+ // No manual subscribe({ next, error }) needed
368
+ }
369
+ ```
370
+
371
+ Works with any Observable, not just HTTP:
372
+
373
+ ```typescript
374
+ // WebSocket
375
+ this.ws.messages$.pipe(
376
+ tapAsyncState(this.liveData),
377
+ takeUntilDestroyed(),
378
+ ).subscribe();
379
+
380
+ // Timer-based polling
381
+ interval(5000).pipe(
382
+ switchMap(() => this.http.get<Status>('/api/status')),
383
+ tapAsyncState(this.status),
384
+ takeUntilDestroyed(),
385
+ ).subscribe();
386
+ ```
387
+
388
+ Refresh mode — pass `{ status: 'refreshing' }` for subsequent loads:
389
+
390
+ ```typescript
391
+ refresh(): void {
392
+ this.http.get<Resident[]>('/api/residents').pipe(
393
+ tapAsyncState(this.residents, { status: 'refreshing' }),
394
+ takeUntilDestroyed(this.destroyRef),
395
+ ).subscribe();
396
+ // Old data stays visible, loading bar appears
397
+ }
398
+ ```
399
+
400
+ ### tapAsyncProgress — HTTP Progress Tracking
401
+
402
+ Use with `{ observe: 'events', reportProgress: true }`:
403
+
404
+ ```typescript
405
+ readonly upload = createManualState<UploadResult>();
406
+
407
+ handleUpload(file: File): void {
408
+ this.upload.set('loading');
409
+
410
+ this.http.post('/api/upload', file, {
411
+ reportProgress: true,
412
+ observe: 'events',
413
+ }).pipe(
414
+ tapAsyncProgress(this.upload), // maps UploadProgress → setProgress(0-100)
415
+ filter(e => e.type === HttpEventType.Response),
416
+ map(e => (e as HttpResponse<UploadResult>).body!),
417
+ takeUntilDestroyed(this.destroyRef),
418
+ ).subscribe({
419
+ next: (result) => this.upload.setSuccess(result),
420
+ error: (err) => this.upload.setError(err),
421
+ });
422
+ }
423
+ ```
424
+
425
+ ### tapHttpAsyncState — All-in-One HTTP Operator
426
+
427
+ Combines `tapAsyncState` + `tapAsyncProgress` + response body extraction.
428
+ One operator, zero boilerplate:
429
+
430
+ ```typescript
431
+ readonly upload = createManualState<UploadResult>();
432
+
433
+ handleUpload(file: File): void {
434
+ this.http.post('/api/upload', file, {
435
+ reportProgress: true,
436
+ observe: 'events',
437
+ }).pipe(
438
+ tapHttpAsyncState(this.upload),
439
+ takeUntilDestroyed(this.destroyRef),
440
+ ).subscribe();
441
+ // upload.status() → 'loading' → 'success'
442
+ // upload.progress() → 0 → 25 → 50 → 75 → 100
443
+ // upload.data() → UploadResult
444
+ }
445
+ ```
446
+
447
+ Template — everything wired from one source:
448
+
449
+ ```html
450
+ <!-- Progress bar during upload -->
451
+ <cngx-progress [state]="upload" variant="linear" />
452
+
453
+ <!-- Status text -->
454
+ @if (upload.isBusy()) {
455
+ <p>Uploading... {{ upload.progress() ?? 0 }}%</p>
456
+ }
457
+
458
+ <!-- Result -->
459
+ @if (upload.hasData()) {
460
+ <p>Uploaded: {{ upload.data()!.filename }}</p>
461
+ }
462
+
463
+ <!-- Error -->
464
+ @if (upload.error(); as err) {
465
+ <cngx-alert severity="error">Upload failed: {{ err }}</cngx-alert>
466
+ }
467
+
468
+ <!-- Toast -->
469
+ <cngx-toast severity="success" message="Upload complete"
470
+ [when]="upload.status() === 'success'" />
471
+ ```
472
+
473
+ ### Comparison: With and Without Operators
474
+
475
+ **Without operators (manual wiring):**
476
+ ```typescript
477
+ handleSave(): void {
478
+ this.saveState.set('pending');
479
+ this.http.put<Resident>('/api/residents', this.form.value()).pipe(
480
+ takeUntilDestroyed(this.destroyRef),
481
+ ).subscribe({
482
+ next: (result) => {
483
+ this.saveState.setSuccess(result);
484
+ this.residents.refresh();
485
+ },
486
+ error: (err) => this.saveState.setError(err),
487
+ });
488
+ }
489
+ ```
490
+
491
+ **With `tapAsyncState` operator:**
492
+ ```typescript
493
+ handleSave(): void {
494
+ this.http.put<Resident>('/api/residents', this.form.value()).pipe(
495
+ tapAsyncState(this.saveState, { status: 'pending' }),
496
+ tap(() => this.residents.refresh()),
497
+ takeUntilDestroyed(this.destroyRef),
498
+ ).subscribe();
499
+ }
500
+ ```
501
+
502
+ ---
503
+
504
+ ## 4. fromResource — Angular resource() Bridge
505
+
506
+ Wraps Angular's `resource()` as `CngxAsyncState<T>`. The resource stays
507
+ the single source of truth — all signals are derived projections.
508
+
509
+ ```typescript
510
+ private readonly res = resource({
511
+ request: () => ({ q: this.filter() }),
512
+ loader: ({ request, abortSignal }) =>
513
+ fetch(`/api/items?q=${request.q}`, { signal: abortSignal })
514
+ .then(r => r.json()),
515
+ });
516
+
517
+ readonly items = fromResource(this.res);
518
+ ```
519
+
520
+ ### Template — same as any CngxAsyncState
521
+
522
+ ```html
523
+ <cngx-async-container [state]="items" ariaLabel="Items">
524
+ <!-- identical template slots — UI doesn't know the source -->
525
+ </cngx-async-container>
526
+ ```
527
+
528
+ ---
529
+
530
+ ## 5. fromHttpResource — Angular httpResource() Bridge
531
+
532
+ Like `fromResource` but maps HTTP progress (0-1 float) to
533
+ `CngxAsyncState.progress` (0-100 integer).
534
+
535
+ ```typescript
536
+ private readonly res = httpResource<Report>(() => ({
537
+ url: '/api/reports/generate',
538
+ method: 'POST',
539
+ body: { params: this.reportParams() },
540
+ }));
541
+
542
+ readonly report = fromHttpResource(this.res);
543
+ ```
544
+
545
+ ### Template with progress bar
546
+
547
+ ```html
548
+ <cngx-progress [state]="report" variant="linear" />
549
+
550
+ <cngx-async-container [state]="report" ariaLabel="Report">
551
+ <ng-template cngxAsyncSkeleton>
552
+ <p>Generating report... {{ report.progress() ?? 0 }}%</p>
553
+ </ng-template>
554
+
555
+ <ng-template cngxAsyncContent let-data>
556
+ <app-report-viewer [report]="data" />
557
+ </ng-template>
558
+ </cngx-async-container>
559
+ ```
560
+
561
+ ---
562
+
563
+ ## Full Example: Resident Management
564
+
565
+ A complete feature combining query, mutation, skeleton, loading bar,
566
+ error handling, toast, and empty state — all from typed sources.
567
+
568
+ ### Service
569
+
570
+ ```typescript
571
+ @Injectable({ providedIn: 'root' })
572
+ export class ResidentApi {
573
+ private readonly http = inject(HttpClient);
574
+
575
+ getAll(filter: string): Observable<Resident[]> {
576
+ return this.http.get<Resident[]>('/api/residents', {
577
+ params: filter ? { q: filter } : {},
578
+ });
579
+ }
580
+
581
+ save(resident: Resident): Observable<Resident> {
582
+ return this.http.put<Resident>(`/api/residents/${resident.id}`, resident);
583
+ }
584
+
585
+ delete(id: string): Observable<void> {
586
+ return this.http.delete<void>(`/api/residents/${id}`);
587
+ }
588
+ }
589
+ ```
590
+
591
+ ### Component
592
+
593
+ ```typescript
594
+ @Component({
595
+ selector: 'app-resident-list',
596
+ template: `
597
+ <input placeholder="Search..." (input)="setFilter($event)" />
598
+
599
+ <cngx-async-container [state]="residents" ariaLabel="Residents"
600
+ toastSuccess="Residents loaded" toastError="Failed to load">
601
+
602
+ <ng-template cngxAsyncSkeleton>
603
+ <cngx-card-grid minWidth="280px">
604
+ @for (i of [1,2,3,4,5,6]; track i) {
605
+ <cngx-card loading><cngx-card-skeleton /></cngx-card>
606
+ }
607
+ </cngx-card-grid>
608
+ </ng-template>
609
+
610
+ <ng-template cngxAsyncContent let-data>
611
+ <cngx-card-grid [items]="data" minWidth="280px">
612
+ @for (r of data; track r.id) {
613
+ <cngx-card>
614
+ <header cngxCardHeader>{{ r.name }}</header>
615
+ <div cngxCardBody>Room {{ r.room }}</div>
616
+ <footer cngxCardFooter>
617
+ <cngx-action-button [action]="makeDelete(r.id)"
618
+ variant="ghost" pendingLabel="Deleting...">
619
+ Delete
620
+ </cngx-action-button>
621
+ </footer>
622
+ </cngx-card>
623
+ }
624
+ </cngx-card-grid>
625
+ </ng-template>
626
+
627
+ <ng-template cngxAsyncEmpty>
628
+ <cngx-empty-state title="No residents"
629
+ description="No residents match your search." />
630
+ </ng-template>
631
+
632
+ <ng-template cngxAsyncError let-err>
633
+ <cngx-alert severity="error" title="Load failed">
634
+ {{ err }}
635
+ <button cngxAlertAction (click)="residents.refresh()">Retry</button>
636
+ </cngx-alert>
637
+ </ng-template>
638
+ </cngx-async-container>
639
+
640
+ <!-- Delete toasts (rising-edge trigger) -->
641
+ <cngx-toast severity="success" message="Resident deleted"
642
+ [when]="deleteState.status() === 'success'" />
643
+ <cngx-toast severity="error" message="Delete failed"
644
+ [when]="deleteState.status() === 'error'" />
645
+ `,
646
+ imports: [
647
+ CngxAsyncContainer, CngxAsyncSkeletonTpl, CngxAsyncContentTpl,
648
+ CngxAsyncEmptyTpl, CngxAsyncErrorTpl,
649
+ CngxCardGrid, CngxCard, CngxCardHeader, CngxCardBody,
650
+ CngxCardFooter, CngxCardSkeleton,
651
+ CngxActionButton, CngxAlert, CngxEmptyState, CngxToast,
652
+ ],
653
+ })
654
+ export class ResidentList {
655
+ private readonly api = inject(ResidentApi);
656
+ private readonly filterText = signal('');
657
+
658
+ // Query — auto-reloads when filter changes
659
+ readonly residents = injectAsyncState(() =>
660
+ this.api.getAll(this.filterText())
661
+ );
662
+
663
+ // Mutation — explicit execute()
664
+ readonly deleteState = createAsyncState<void>();
665
+
666
+ protected makeDelete(id: string): () => Promise<void> {
667
+ return () => this.deleteState.execute(
668
+ () => firstValueFrom(this.api.delete(id))
669
+ ).then(() => this.residents.refresh());
670
+ }
671
+
672
+ protected setFilter(event: Event): void {
673
+ this.filterText.set((event.target as HTMLInputElement).value);
674
+ }
675
+ }
676
+ ```
677
+
678
+ ### What happens automatically
679
+
680
+ | Moment | Status | UI Feedback |
681
+ |-|-|-|
682
+ | Component init | `idle` -> `loading` | 6 skeleton cards |
683
+ | Data loaded | `loading` -> `success` | Cards appear, toast "Residents loaded" |
684
+ | Empty array | `success` + `isEmpty` | Empty state with description |
685
+ | Type in filter | `success` -> `refreshing` | Loading bar at top, old cards stay visible |
686
+ | Filter results | `refreshing` -> `success` | New cards, bar disappears |
687
+ | Network error | `loading` -> `error` | Alert with retry button, toast "Failed to load" |
688
+ | Click delete | `idle` -> `pending` | Button shows "Deleting...", `aria-busy` |
689
+ | Delete OK | `pending` -> `success` | Toast "Resident deleted", list refreshes |
690
+ | Delete fails | `pending` -> `error` | Toast "Delete failed" |
691
+
692
+ ### What you do NOT need to write
693
+
694
+ - No `isLoading` / `isRefreshing` / `hasError` booleans
695
+ - No `@if` / `@switch` chains for state management
696
+ - No manual `aria-busy` or screen reader announcements
697
+ - No manual toast timing or deduplication
698
+ - No manual subscription cleanup
699
+ - No manual error-to-UI mapping
700
+
701
+ Everything is derived from a single source. The state machine
702
+ cannot become inconsistent.
703
+
704
+ ---
705
+
706
+ ## CngxAsyncState Interface
707
+
708
+ Every factory returns this interface — every UI component accepts it.
709
+
710
+ | Signal | Type | Description |
711
+ |-|-|-|
712
+ | `status` | `AsyncStatus` | `idle`, `loading`, `pending`, `refreshing`, `success`, `error` |
713
+ | `data` | `T \| undefined` | Most recent successful result |
714
+ | `error` | `unknown` | Most recent error |
715
+ | `progress` | `number \| undefined` | 0-100 or undefined |
716
+ | `isLoading` | `boolean` | `loading`, `pending`, or `refreshing` |
717
+ | `isPending` | `boolean` | Only `pending` (mutation in flight) |
718
+ | `isRefreshing` | `boolean` | Only `refreshing` (re-query, data visible) |
719
+ | `isBusy` | `boolean` | Same as `isLoading` — maps to `aria-busy` |
720
+ | `isFirstLoad` | `boolean` | No successful load yet |
721
+ | `isEmpty` | `boolean` | Data is `null`, `undefined`, or empty array |
722
+ | `hasData` | `boolean` | Inverse of `isEmpty` |
723
+ | `isSettled` | `boolean` | `success` or `error` |
724
+ | `lastUpdated` | `Date \| undefined` | Timestamp of last success |
725
+
726
+ ## SmartDataSource — Table with Full UX State
727
+
728
+ Pass a `CngxAsyncState<T[]>` to `injectSmartDataSource` and the table
729
+ receives skeleton, error, empty, and loading-bar projections automatically.
730
+
731
+ ### Setup
732
+
733
+ ```typescript
734
+ // Service
735
+ readonly residents = injectAsyncState(() =>
736
+ this.api.getAll(this.filter())
737
+ );
738
+
739
+ // DataSource — accepts CngxAsyncState directly
740
+ readonly dataSource = injectSmartDataSource(this.residents);
741
+ ```
742
+
743
+ ### Template — every state mapped to a table view
744
+
745
+ ```html
746
+ <div cngxPaginate #pg="cngxPaginate"
747
+ [total]="dataSource.filteredCount()" [state]="residents">
748
+
749
+ <!-- Skeleton during first load -->
750
+ @if (dataSource.isFirstLoad()) {
751
+ <table>
752
+ @for (i of [1,2,3,4,5]; track i) {
753
+ <tr><td><div class="skeleton-line"></div></td></tr>
754
+ }
755
+ </table>
756
+ }
757
+
758
+ <!-- Error state -->
759
+ @else if (dataSource.error(); as err) {
760
+ <cngx-alert severity="error">
761
+ {{ err }}
762
+ <button cngxAlertAction (click)="residents.refresh()">Retry</button>
763
+ </cngx-alert>
764
+ }
765
+
766
+ <!-- Empty state -->
767
+ @else if (dataSource.isEmpty()) {
768
+ <cngx-empty-state title="No residents" />
769
+ }
770
+
771
+ <!-- Content — with loading bar during refresh -->
772
+ @else {
773
+ @if (dataSource.isRefreshing()) {
774
+ <cngx-loading-indicator [loading]="true" variant="bar" />
775
+ }
776
+ <table mat-table [dataSource]="dataSource" [trackBy]="trackBy">
777
+ <!-- columns -->
778
+ </table>
779
+ }
780
+
781
+ <cngx-mat-paginator [cngxPaginateRef]="pg" />
782
+ </div>
783
+ ```
784
+
785
+ ### What the DataSource exposes
786
+
787
+ | Signal | Source | Description |
788
+ |-|-|-|
789
+ | `isLoading` | `state.isLoading()` | True during any load |
790
+ | `isFirstLoad` | `state.isFirstLoad()` | True only on initial load (skeleton) |
791
+ | `isRefreshing` | `state.isRefreshing()` | True during re-query (loading bar) |
792
+ | `isBusy` | `state.isBusy()` | True during any operation (aria-busy) |
793
+ | `error` | `state.error()` | Error from the async operation |
794
+ | `isEmpty` | derived | True when not busy AND filteredCount is 0 |
795
+ | `filteredCount` | derived | Items after filter/search, before pagination |
796
+ | `asyncState` | ref | The original CngxAsyncState for binding to other components |
797
+
798
+ ### Server-side pagination
799
+
800
+ ```typescript
801
+ readonly residents = injectAsyncState(() =>
802
+ this.api.getPage(this.pageIndex(), this.pageSize(), this.filter())
803
+ );
804
+ // Page change triggers signal change → auto-reload
805
+ // Paginator disabled while loading via [state]
806
+ ```
807
+
808
+ ---
809
+
810
+ ## CngxPaginate — Async-Aware Pagination
811
+
812
+ The paginator accepts `[state]` and blocks navigation while busy:
813
+
814
+ ```html
815
+ <div cngxPaginate #pg="cngxPaginate"
816
+ [total]="dataSource.filteredCount()" [state]="residents">
817
+ <!-- table -->
818
+ <cngx-mat-paginator [cngxPaginateRef]="pg" />
819
+ </div>
820
+ ```
821
+
822
+ - `setPage()`, `next()`, `previous()`, `setPageSize()` are no-ops while `isBusy`
823
+ - `CngxMatPaginator` auto-disables via `[disabled]="ref().isBusy()"`
824
+ - No manual disabled management needed
825
+
826
+ ---
827
+
828
+ ## CngxFileDrop — Upload State
829
+
830
+ The file drop accepts `[state]` for upload lifecycle feedback:
831
+
832
+ ```html
833
+ <div cngxFileDrop #drop="cngxFileDrop"
834
+ [accept]="['image/*']" [state]="uploadState"
835
+ (filesChange)="handleUpload($event)">
836
+
837
+ @if (drop.uploading()) {
838
+ <cngx-progress [state]="uploadState" variant="circular" />
839
+ <p>Uploading... {{ drop.uploadProgress() ?? 0 }}%</p>
840
+ } @else if (drop.uploadError()) {
841
+ <cngx-alert severity="error">Upload failed</cngx-alert>
842
+ } @else {
843
+ <p>Drop files or <button (click)="drop.browse()">browse</button></p>
844
+ }
845
+ </div>
846
+ ```
847
+
848
+ ```typescript
849
+ readonly uploadState = createManualState<UploadResult>();
850
+
851
+ handleUpload(files: File[]): void {
852
+ this.http.post('/api/upload', files[0], {
853
+ reportProgress: true, observe: 'events',
854
+ }).pipe(
855
+ tapHttpAsyncState(this.uploadState),
856
+ takeUntilDestroyed(this.destroyRef),
857
+ ).subscribe();
858
+ }
859
+ ```
860
+
861
+ - `browse()` and drop are blocked while uploading
862
+ - `aria-busy` applied automatically
863
+ - `cngx-file-drop--uploading` CSS class for styling
864
+
865
+ ---
866
+
867
+ ## UI Components That Accept `[state]`
868
+
869
+ | Component | What it derives |
870
+ |-|-|
871
+ | `cngx-async-container` | Template slot selection, refresh bar, SR announcements, toast |
872
+ | `*cngxAsync` | Template slot selection via microsyntax |
873
+ | `cngx-skeleton` | `isLoading` from `isFirstLoad()` |
874
+ | `cngx-empty-state` | Auto-hides during loading and when data present |
875
+ | `cngx-loading-overlay` | `isBusy` or `isFirstLoad` (with `firstLoadOnly`) |
876
+ | `cngx-progress` | Determinate/indeterminate from `progress()` |
877
+ | `cngx-card-grid` | `isLoading` + `aria-busy`, empty override |
878
+ | `cngx-popover-panel` | Loading/error/empty slot selection |
879
+ | `cngx-treetable` | `aria-busy`, `isLoading`, `error`, `isEmpty` |
880
+ | `dialog[cngxDialog]` | `isPending` blocks close, `aria-busy`, error announcement |
881
+ | `[cngxPaginate]` | `isBusy` blocks navigation, disabled paginator |
882
+ | `[cngxFileDrop]` | `uploading`, `uploadProgress`, `uploadError`, blocks drop/browse |
883
+ | `injectSmartDataSource` | `isLoading`, `isRefreshing`, `error`, `isEmpty`, `filteredCount` |