@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
@@ -0,0 +1,2886 @@
1
+ import * as i0 from '@angular/core';
2
+ import { input, signal, computed, output, Directive, inject, TemplateRef, model, contentChild, afterNextRender, DestroyRef, ChangeDetectionStrategy, Component, Injector, untracked, effect, ViewContainerRef, LOCALE_ID, ViewEncapsulation, InjectionToken, isDevMode, ElementRef, runInInjectionContext } from '@angular/core';
3
+ import { NgTemplateOutlet, DOCUMENT } from '@angular/common';
4
+ import { CngxChip } from '@cngx/common/display';
5
+ import { CngxMultiChipGroup, CngxChipInGroup, CngxSearch } from '@cngx/common/interactive';
6
+ import { DataSource } from '@angular/cdk/collections';
7
+ import { toObservable, takeUntilDestroyed } from '@angular/core/rxjs-interop';
8
+ import { buildAsyncStateView, createTransitionTracker } from '@cngx/core/utils';
9
+ import { isObservable, firstValueFrom, defer, tap, filter, map } from 'rxjs';
10
+
11
+ /**
12
+ * Atom directive that tracks sort state (active field + direction).
13
+ *
14
+ * Supports both **uncontrolled** (internal state) and **controlled** modes.
15
+ * In controlled mode the `cngxSortActive` / `cngxSortDirection` inputs take
16
+ * precedence over the internal state — pair with `sortChange` to keep them
17
+ * in sync.
18
+ *
19
+ * When `multiSort` is `true`, holding **Shift** while clicking a sort header
20
+ * adds it as a secondary (tertiary, …) sort key instead of replacing the
21
+ * primary one. Shift-clicking an active column cycles it asc → desc → removed.
22
+ * Multi-sort state is always uncontrolled; use `sortsChange` to read it.
23
+ *
24
+ * Consumer connects this to a table or list via a `computed()` — nothing is
25
+ * injected automatically.
26
+ */
27
+ class CngxSort {
28
+ /** Controlled active column. When bound, takes precedence over internal state (single-sort only). */
29
+ activeInput = input(undefined, { ...(ngDevMode ? { debugName: "activeInput" } : /* istanbul ignore next */ {}), alias: 'cngxSortActive' });
30
+ /** Controlled direction. When bound, takes precedence over internal state (single-sort only). */
31
+ directionInput = input(undefined, { ...(ngDevMode ? { debugName: "directionInput" } : /* istanbul ignore next */ {}), alias: 'cngxSortDirection' });
32
+ /**
33
+ * When `true`, Shift+click on a sort header adds it to the sort stack instead of
34
+ * replacing the current sort.
35
+ */
36
+ multiSort = input(false, ...(ngDevMode ? [{ debugName: "multiSort" }] : /* istanbul ignore next */ []));
37
+ sortsState = signal([], ...(ngDevMode ? [{ debugName: "sortsState" }] : /* istanbul ignore next */ []));
38
+ /** The active sort column of the primary entry (controlled takes precedence in single-sort mode). */
39
+ active = computed(() => this.activeInput() ?? this.sortsState()[0]?.active, ...(ngDevMode ? [{ debugName: "active" }] : /* istanbul ignore next */ []));
40
+ /** The active sort direction of the primary entry (controlled takes precedence in single-sort mode). */
41
+ direction = computed(() => this.directionInput() ?? this.sortsState()[0]?.direction, ...(ngDevMode ? [{ debugName: "direction" }] : /* istanbul ignore next */ []));
42
+ /**
43
+ * The primary sort state, or `null` when no sort is active.
44
+ * In multi-sort mode this is the first entry in `sorts`.
45
+ */
46
+ sort = computed(() => this.active() ? { active: this.active(), direction: this.direction() ?? 'asc' } : null, ...(ngDevMode ? [{ debugName: "sort" }] : /* istanbul ignore next */ []));
47
+ /**
48
+ * All active sort entries in priority order.
49
+ * Contains at most one entry when additive mode has not been used.
50
+ */
51
+ sorts = this.sortsState.asReadonly();
52
+ /** `true` when at least one sort is active. */
53
+ isActive = computed(() => this.sorts().length > 0, ...(ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []));
54
+ /** Emitted when the primary sort state changes. Emits `undefined` on clear. */
55
+ sortChange = output();
56
+ /**
57
+ * Emitted whenever the sort stack changes (including removals and full clears).
58
+ * Always reflects the full `sorts` array at the time of emission.
59
+ */
60
+ sortsChange = output();
61
+ /**
62
+ * Sets or toggles the sort for `field`.
63
+ *
64
+ * **`additive = false`** (default, plain click):
65
+ * - Same field → toggle direction (asc → desc → asc)
66
+ * - Different field → replace stack with `{ field, asc }`
67
+ *
68
+ * **`additive = true`** (Shift+click when `multiSort` is enabled on the header):
69
+ * - Field not in stack → append as asc
70
+ * - Field in stack as asc → change to desc
71
+ * - Field in stack as desc → remove from stack
72
+ */
73
+ setSort(field, additive = false) {
74
+ if (additive) {
75
+ const current = this.sortsState();
76
+ const idx = current.findIndex((s) => s.active === field);
77
+ let next;
78
+ if (idx === -1) {
79
+ next = [...current, { active: field, direction: 'asc' }];
80
+ }
81
+ else if (current[idx].direction === 'asc') {
82
+ next = current.map((s, i) => (i === idx ? { ...s, direction: 'desc' } : s));
83
+ }
84
+ else {
85
+ next = current.filter((_, i) => i !== idx);
86
+ }
87
+ this.sortsState.set(next);
88
+ this.sortsChange.emit(next);
89
+ this.sortChange.emit(next[0]);
90
+ }
91
+ else {
92
+ const current = this.sortsState();
93
+ const dir = field === current[0]?.active ? (current[0].direction === 'asc' ? 'desc' : 'asc') : 'asc';
94
+ const entry = { active: field, direction: dir };
95
+ this.sortsState.set([entry]);
96
+ this.sortChange.emit(entry);
97
+ this.sortsChange.emit([entry]);
98
+ }
99
+ }
100
+ /** Clears all active sorts. Emits both `sortChange(undefined)` and `sortsChange([])`. */
101
+ clear() {
102
+ this.sortsState.set([]);
103
+ this.sortChange.emit(undefined);
104
+ this.sortsChange.emit([]);
105
+ }
106
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxSort, deps: [], target: i0.ɵɵFactoryTarget.Directive });
107
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxSort, isStandalone: true, selector: "[cngxSort]", inputs: { activeInput: { classPropertyName: "activeInput", publicName: "cngxSortActive", isSignal: true, isRequired: false, transformFunction: null }, directionInput: { classPropertyName: "directionInput", publicName: "cngxSortDirection", isSignal: true, isRequired: false, transformFunction: null }, multiSort: { classPropertyName: "multiSort", publicName: "multiSort", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { sortChange: "sortChange", sortsChange: "sortsChange" }, exportAs: ["cngxSort"], ngImport: i0 });
108
+ }
109
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxSort, decorators: [{
110
+ type: Directive,
111
+ args: [{
112
+ selector: '[cngxSort]',
113
+ exportAs: 'cngxSort',
114
+ standalone: true,
115
+ }]
116
+ }], propDecorators: { activeInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxSortActive", required: false }] }], directionInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxSortDirection", required: false }] }], multiSort: [{ type: i0.Input, args: [{ isSignal: true, alias: "multiSort", required: false }] }], sortChange: [{ type: i0.Output, args: ["sortChange"] }], sortsChange: [{ type: i0.Output, args: ["sortsChange"] }] } });
117
+
118
+ /**
119
+ * Molecule directive for sort-header elements.
120
+ *
121
+ * Apply to any clickable header element. Consumer provides an explicit
122
+ * `[cngxSortRef]` binding — no ancestor injection, no hidden wiring.
123
+ *
124
+ * In multi-sort mode, Shift+click adds this column to the sort stack.
125
+ * The `priority()` signal returns the 1-based position in the stack
126
+ * (0 when not active), useful for showing sort-order badges.
127
+ *
128
+ * ```html
129
+ * <div cngxSort [multiSort]="true" #sort="cngxSort">
130
+ * <button cngxSortHeader="name" [cngxSortRef]="sort" #h="cngxSortHeader">
131
+ * Name
132
+ * @if (h.isActive()) {
133
+ * {{ h.isAsc() ? '↑' : '↓' }}
134
+ * @if (sort.multiSort()) { <span>{{ h.priority() }}</span> }
135
+ * }
136
+ * </button>
137
+ * </div>
138
+ * ```
139
+ */
140
+ class CngxSortHeader {
141
+ /** The field key this header cell represents. */
142
+ field = input.required({ ...(ngDevMode ? { debugName: "field" } : /* istanbul ignore next */ {}), alias: 'cngxSortHeader' });
143
+ /** Explicit reference to the owning `CngxSort`. */
144
+ cngxSortRef = input.required(...(ngDevMode ? [{ debugName: "cngxSortRef" }] : /* istanbul ignore next */ []));
145
+ entry = computed(() => this.cngxSortRef()
146
+ .sorts()
147
+ .find((s) => s.active === this.field()), ...(ngDevMode ? [{ debugName: "entry" }] : /* istanbul ignore next */ []));
148
+ /** `true` when this column is part of the active sort (primary or secondary). */
149
+ isActive = computed(() => this.entry() !== undefined, ...(ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []));
150
+ /** `true` when this column is active and sorted ascending. */
151
+ isAsc = computed(() => this.entry()?.direction === 'asc', ...(ngDevMode ? [{ debugName: "isAsc" }] : /* istanbul ignore next */ []));
152
+ /** `true` when this column is active and sorted descending. */
153
+ isDesc = computed(() => this.entry()?.direction === 'desc', ...(ngDevMode ? [{ debugName: "isDesc" }] : /* istanbul ignore next */ []));
154
+ /**
155
+ * 1-based position of this column in the sort stack.
156
+ * Returns `0` when the column is not part of the active sort.
157
+ * Only meaningful when `multiSort` is enabled on the owning `CngxSort`.
158
+ */
159
+ priority = computed(() => {
160
+ const idx = this.cngxSortRef()
161
+ .sorts()
162
+ .findIndex((s) => s.active === this.field());
163
+ return idx === -1 ? 0 : idx + 1;
164
+ }, ...(ngDevMode ? [{ debugName: "priority" }] : /* istanbul ignore next */ []));
165
+ /** The `aria-sort` attribute value for the host element. */
166
+ ariaSort = computed(() => {
167
+ if (!this.isActive()) {
168
+ return null;
169
+ }
170
+ return this.isAsc() ? 'ascending' : 'descending';
171
+ }, ...(ngDevMode ? [{ debugName: "ariaSort" }] : /* istanbul ignore next */ []));
172
+ handleSort(event) {
173
+ const additive = this.cngxSortRef().multiSort() && (event?.shiftKey ?? false);
174
+ this.cngxSortRef().setSort(this.field(), additive);
175
+ }
176
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxSortHeader, deps: [], target: i0.ɵɵFactoryTarget.Directive });
177
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxSortHeader, isStandalone: true, selector: "[cngxSortHeader]", inputs: { field: { classPropertyName: "field", publicName: "cngxSortHeader", isSignal: true, isRequired: true, transformFunction: null }, cngxSortRef: { classPropertyName: "cngxSortRef", publicName: "cngxSortRef", isSignal: true, isRequired: true, transformFunction: null } }, host: { listeners: { "click": "handleSort($event)" }, properties: { "attr.aria-sort": "ariaSort()", "class.cngx-sort-header--active": "isActive()", "class.cngx-sort-header--asc": "isAsc()", "class.cngx-sort-header--desc": "isDesc()" } }, exportAs: ["cngxSortHeader"], ngImport: i0 });
178
+ }
179
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxSortHeader, decorators: [{
180
+ type: Directive,
181
+ args: [{
182
+ selector: '[cngxSortHeader]',
183
+ exportAs: 'cngxSortHeader',
184
+ standalone: true,
185
+ host: {
186
+ '(click)': 'handleSort($event)',
187
+ '[attr.aria-sort]': 'ariaSort()',
188
+ '[class.cngx-sort-header--active]': 'isActive()',
189
+ '[class.cngx-sort-header--asc]': 'isAsc()',
190
+ '[class.cngx-sort-header--desc]': 'isDesc()',
191
+ },
192
+ }]
193
+ }], propDecorators: { field: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxSortHeader", required: true }] }], cngxSortRef: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxSortRef", required: true }] }] } });
194
+
195
+ /**
196
+ * Atom directive that holds one or more named filter predicates.
197
+ *
198
+ * Supports both **uncontrolled** (internal state) and **controlled** modes.
199
+ * In controlled mode the `cngxFilter` input takes precedence over the internal
200
+ * `'default'` predicate — pair with `filterChange` to keep it in sync.
201
+ *
202
+ * **Multi-filter** — use `addPredicate(key, fn)` / `removePredicate(key)` to
203
+ * maintain a named stack of predicates. All active predicates are **AND-combined**
204
+ * across keys: an item must pass every registered predicate to appear in results.
205
+ *
206
+ * AND vs OR — the directive enforces AND across dimensions (keys). OR logic
207
+ * within a single dimension stays inside the predicate function itself:
208
+ *
209
+ * ```typescript
210
+ * // AND across dimensions: location AND role must both match
211
+ * filter.addPredicate('location', p => selectedLocations.has(p.location));
212
+ * filter.addPredicate('role', p => selectedRoles.has(p.role));
213
+ *
214
+ * // OR within a dimension: London OR Rome — just put a Set inside one predicate
215
+ * filter.addPredicate('location', p => selectedLocations.has(p.location));
216
+ * ```
217
+ *
218
+ * `setPredicate` / `clear` operate on the `'default'` key and remain fully
219
+ * backward-compatible with single-predicate usage.
220
+ *
221
+ * Consumer connects this to a list via a `computed()` — nothing is injected
222
+ * automatically.
223
+ *
224
+ * @typeParam T - The item type the predicate operates on.
225
+ */
226
+ class CngxFilter {
227
+ /** Controlled predicate. When bound, takes precedence over the `'default'` internal predicate. */
228
+ predicateInput = input(null, { ...(ngDevMode ? { debugName: "predicateInput" } : /* istanbul ignore next */ {}), alias: 'cngxFilter' });
229
+ predicatesState = signal(new Map(), ...(ngDevMode ? [{ debugName: "predicatesState" }] : /* istanbul ignore next */ []));
230
+ /**
231
+ * All active named predicates.
232
+ * Use `addPredicate` / `removePredicate` to manage this map.
233
+ */
234
+ predicates = this.predicatesState.asReadonly();
235
+ /** Number of active named predicates (controlled input not counted). */
236
+ activeCount = computed(() => this.predicatesState().size, ...(ngDevMode ? [{ debugName: "activeCount" }] : /* istanbul ignore next */ []));
237
+ /**
238
+ * The combined predicate — AND of all active named predicates plus the
239
+ * controlled input (when bound). Returns `null` when nothing is active.
240
+ */
241
+ predicate = computed(() => {
242
+ const controlled = this.predicateInput();
243
+ const map = this.predicatesState();
244
+ const fns = [...(controlled ? [controlled] : []), ...map.values()];
245
+ if (fns.length === 0) {
246
+ return null;
247
+ }
248
+ if (fns.length === 1) {
249
+ return fns[0];
250
+ }
251
+ return (value) => fns.every((fn) => fn(value));
252
+ }, ...(ngDevMode ? [{ debugName: "predicate" }] : /* istanbul ignore next */ []));
253
+ /** `true` when at least one predicate is active. */
254
+ isActive = computed(() => this.predicate() !== null, ...(ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []));
255
+ /** Emitted whenever the `'default'` predicate changes (backward-compat single-filter output). */
256
+ filterChange = output();
257
+ /** Emitted whenever any named predicate is added or removed. */
258
+ predicatesChange = output();
259
+ /**
260
+ * Adds or replaces the named predicate `key`.
261
+ * Emits `predicatesChange` with the updated map.
262
+ */
263
+ addPredicate(key, fn) {
264
+ const next = new Map(this.predicatesState());
265
+ next.set(key, fn);
266
+ this.predicatesState.set(next);
267
+ this.predicatesChange.emit(next);
268
+ }
269
+ /**
270
+ * Removes the named predicate `key` (no-op if not present).
271
+ * Emits `predicatesChange` with the updated map.
272
+ */
273
+ removePredicate(key) {
274
+ const current = this.predicatesState();
275
+ if (!current.has(key)) {
276
+ return;
277
+ }
278
+ const next = new Map(current);
279
+ next.delete(key);
280
+ this.predicatesState.set(next);
281
+ this.predicatesChange.emit(next);
282
+ }
283
+ /**
284
+ * Sets the `'default'` predicate and emits `filterChange`.
285
+ * Pass `null` to clear it (same as `clear()`).
286
+ */
287
+ setPredicate(fn) {
288
+ if (fn === null) {
289
+ this.removePredicate('default');
290
+ }
291
+ else {
292
+ this.addPredicate('default', fn);
293
+ }
294
+ this.filterChange.emit(fn);
295
+ }
296
+ /** Removes all named predicates and emits `filterChange` with `null`. */
297
+ clear() {
298
+ this.predicatesState.set(new Map());
299
+ this.predicatesChange.emit(new Map());
300
+ this.filterChange.emit(null);
301
+ }
302
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFilter, deps: [], target: i0.ɵɵFactoryTarget.Directive });
303
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxFilter, isStandalone: true, selector: "[cngxFilter]", inputs: { predicateInput: { classPropertyName: "predicateInput", publicName: "cngxFilter", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { filterChange: "filterChange", predicatesChange: "predicatesChange" }, exportAs: ["cngxFilter"], ngImport: i0 });
304
+ }
305
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFilter, decorators: [{
306
+ type: Directive,
307
+ args: [{
308
+ selector: '[cngxFilter]',
309
+ exportAs: 'cngxFilter',
310
+ standalone: true,
311
+ }]
312
+ }], propDecorators: { predicateInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxFilter", required: false }] }], filterChange: [{ type: i0.Output, args: ["filterChange"] }], predicatesChange: [{ type: i0.Output, args: ["predicatesChange"] }] } });
313
+
314
+ /**
315
+ * Template-slot directive overriding the default chip body inside
316
+ * `<cngx-filter-chips>`. Consumers attach
317
+ * `<ng-template cngxFilterChip>` to project decoration; the bridge
318
+ * wraps that decoration in `cngxChipInGroup`-bound chip wrappers
319
+ * automatically. Absence falls back to the default text-only label.
320
+ */
321
+ class CngxFilterChip {
322
+ template = inject(TemplateRef);
323
+ static ngTemplateContextGuard(_dir, _ctx) {
324
+ return true;
325
+ }
326
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFilterChip, deps: [], target: i0.ɵɵFactoryTarget.Directive });
327
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxFilterChip, isStandalone: true, selector: "ng-template[cngxFilterChip]", ngImport: i0 });
328
+ }
329
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFilterChip, decorators: [{
330
+ type: Directive,
331
+ args: [{
332
+ selector: 'ng-template[cngxFilterChip]',
333
+ standalone: true,
334
+ }]
335
+ }] });
336
+ /**
337
+ * Bridge that connects a multi-select chip strip to a `CngxFilter`
338
+ * predicate via Pillar-1 derivation — no `effect()` write-back, no
339
+ * manual sync. The bridge composes `<cngx-multi-chip-group>` for
340
+ * the visible chip strip and registers a single closure-style
341
+ * predicate on the parent `[filterRef]`. Chip toggles update
342
+ * `selectedValues`; the registered closure reads `selectedValues()`
343
+ * lazily on every invocation so downstream filtered consumers
344
+ * recompute without the bridge ever re-registering.
345
+ *
346
+ * Filter chips are inherently multi-select per
347
+ * `feedback_select_family_split`; a single-mode filter-chip pattern
348
+ * is intentionally out of scope. Consumers needing a single-select
349
+ * filter wire `<cngx-chip-group>` to a custom predicate themselves.
350
+ *
351
+ * **Sync contract — derivation, not effect.** The bridge calls
352
+ * `filterRef.addPredicate(filterKey, predicateFn)` EXACTLY ONCE
353
+ * during mount (in `afterNextRender`, because `input.required()`
354
+ * cannot be read from the constructor body). `predicateFn` is a
355
+ * closure that reads `this.selectedValues()` and
356
+ * `this.optionValueFn()` on every invocation. Because
357
+ * `CngxFilter.predicate` is itself a `computed()` consumed by
358
+ * downstream filtered lists, each item-evaluation flows through
359
+ * `selectedValues()` in the consumer's reactive context — chip
360
+ * toggles propagate without any `effect()` writing back into the
361
+ * filter.
362
+ *
363
+ * **Empty-selection semantics.** When `selectedValues()` is `[]`,
364
+ * the closure returns `true` for every item — equivalent to "no
365
+ * filter applied". The bridge deliberately does NOT call
366
+ * `removePredicate` on empty selection: leaving the predicate
367
+ * registered with a constant-`true` short-circuit is cheaper than
368
+ * re-registering on every empty/non-empty boundary, and keeps the
369
+ * predicate-stack stable (no `predicatesChange` emission churn).
370
+ *
371
+ * **Teardown.** `DestroyRef.onDestroy` calls `removePredicate` only
372
+ * when registration actually happened (`registered` flag) — guards
373
+ * against the case where the component is destroyed before
374
+ * `afterNextRender` fires. The destroy callback reads `filterRef`
375
+ * and `filterKey` lazily so a consumer that re-binds these between
376
+ * mount and unmount cleans the latest binding (per
377
+ * `reference_signal_architecture` memory-hygiene rule).
378
+ *
379
+ * ```html
380
+ * <cngx-filter-chips
381
+ * label="Tags"
382
+ * [options]="tagOptions"
383
+ * optionLabel="label"
384
+ * optionValue="id"
385
+ * [filterRef]="employees"
386
+ * filterKey="tags"
387
+ * />
388
+ *
389
+ * <ng-container cngxFilter #employees="cngxFilter">
390
+ * @for (emp of filteredEmployees(); track emp.id) {
391
+ * ...
392
+ * }
393
+ * </ng-container>
394
+ * ```
395
+ */
396
+ class CngxFilterChips {
397
+ label = input.required(...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
398
+ options = input.required(...(ngDevMode ? [{ debugName: "options" }] : /* istanbul ignore next */ []));
399
+ optionLabel = input.required(...(ngDevMode ? [{ debugName: "optionLabel" }] : /* istanbul ignore next */ []));
400
+ optionValue = input.required(...(ngDevMode ? [{ debugName: "optionValue" }] : /* istanbul ignore next */ []));
401
+ filterRef = input.required(...(ngDevMode ? [{ debugName: "filterRef" }] : /* istanbul ignore next */ []));
402
+ filterKey = input.required(...(ngDevMode ? [{ debugName: "filterKey" }] : /* istanbul ignore next */ []));
403
+ state = input(undefined, ...(ngDevMode ? [{ debugName: "state" }] : /* istanbul ignore next */ []));
404
+ /**
405
+ * Form-state surface forwarded transparently to the inner
406
+ * `<cngx-multi-chip-group>`. Each is a `model<boolean>` matching the
407
+ * inner shape so consumers can two-way bind with their own forms
408
+ * state without reaching past the bridge. Mirrors `CngxCheckboxGroup`
409
+ * / `CngxButtonToggleGroup` precedent.
410
+ */
411
+ disabled = model(false, ...(ngDevMode ? [{ debugName: "disabled" }] : /* istanbul ignore next */ []));
412
+ required = model(false, ...(ngDevMode ? [{ debugName: "required" }] : /* istanbul ignore next */ []));
413
+ invalid = model(false, ...(ngDevMode ? [{ debugName: "invalid" }] : /* istanbul ignore next */ []));
414
+ errorMessageId = input(null, ...(ngDevMode ? [{ debugName: "errorMessageId" }] : /* istanbul ignore next */ []));
415
+ orientation = input('horizontal', ...(ngDevMode ? [{ debugName: "orientation" }] : /* istanbul ignore next */ []));
416
+ /**
417
+ * Membership key extractor for object-valued chip values. When
418
+ * `TValue` is an object (e.g. `{ id, label }` rather than a
419
+ * primitive id), this fn extracts a stable identity key so chip
420
+ * membership survives re-emissions with fresh references. Forwarded
421
+ * to the inner `<cngx-multi-chip-group>` AND used inside the
422
+ * predicate's `Object.is` comparison. Defaults to identity — works
423
+ * for primitive values.
424
+ */
425
+ keyFn = input((v) => v, ...(ngDevMode ? [{ debugName: "keyFn" }] : /* istanbul ignore next */ []));
426
+ /**
427
+ * Resolved consumer-supplied chip template. The query uses an
428
+ * instantiation expression (`CngxFilterChip<TItem, TValue>`) so the
429
+ * bridge's class generics propagate into the slot directive type;
430
+ * absent that propagation, `contentChild(CngxFilterChip)` returns
431
+ * `Signal<CngxFilterChip<unknown, unknown> | undefined>` and the
432
+ * `chipContext()` helper would have to widen on every call.
433
+ */
434
+ chipTemplate = contentChild((CngxFilterChip), ...(ngDevMode ? [{ debugName: "chipTemplate" }] : /* istanbul ignore next */ []));
435
+ /**
436
+ * Build the slot context for a given chip option. `optionValue` is
437
+ * invoked here per option for the chip rendering pass; the predicate
438
+ * closure invokes it again per LIST item for membership filtering.
439
+ * Both invocations are necessary because option items (the chip
440
+ * pool) and filtered list items (the consumer's filtered data) are
441
+ * separate data paths — they happen to share a shape under the
442
+ * Phase-5 single-shape limitation, but the bridge cannot memoise
443
+ * across the two paths without conflating them. Consumers should
444
+ * keep `optionValue` cheap (typically a property lookup); a future
445
+ * `[itemValue]` input will separate the two extractors.
446
+ */
447
+ chipContext = (option) => {
448
+ const value = this.optionValue()(option);
449
+ return {
450
+ $implicit: option,
451
+ option,
452
+ value,
453
+ label: this.optionLabel()(option),
454
+ };
455
+ };
456
+ /**
457
+ * Internal multi-select state driven by chip toggles. Exposed as
458
+ * a `model` so consumers may seed initial selection via
459
+ * `[(selectedValues)]` if they need to; usually the consumer leaves
460
+ * this internal and reads results via the parent
461
+ * `CngxFilter.predicate`.
462
+ */
463
+ selectedValues = model([], ...(ngDevMode ? [{ debugName: "selectedValues" }] : /* istanbul ignore next */ []));
464
+ registered = false;
465
+ constructor() {
466
+ const predicateFn = (item) => {
467
+ const values = this.selectedValues();
468
+ if (values.length === 0) {
469
+ return true;
470
+ }
471
+ const extract = this.keyFn();
472
+ const key = extract(this.optionValue()(item));
473
+ return values.some((v) => Object.is(extract(v), key));
474
+ };
475
+ afterNextRender(() => {
476
+ this.filterRef().addPredicate(this.filterKey(), predicateFn);
477
+ this.registered = true;
478
+ });
479
+ inject(DestroyRef).onDestroy(() => {
480
+ if (!this.registered) {
481
+ return;
482
+ }
483
+ this.filterRef().removePredicate(this.filterKey());
484
+ });
485
+ }
486
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFilterChips, deps: [], target: i0.ɵɵFactoryTarget.Component });
487
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.4", type: CngxFilterChips, isStandalone: true, selector: "cngx-filter-chips", inputs: { label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: true, transformFunction: null }, options: { classPropertyName: "options", publicName: "options", isSignal: true, isRequired: true, transformFunction: null }, optionLabel: { classPropertyName: "optionLabel", publicName: "optionLabel", isSignal: true, isRequired: true, transformFunction: null }, optionValue: { classPropertyName: "optionValue", publicName: "optionValue", isSignal: true, isRequired: true, transformFunction: null }, filterRef: { classPropertyName: "filterRef", publicName: "filterRef", isSignal: true, isRequired: true, transformFunction: null }, filterKey: { classPropertyName: "filterKey", publicName: "filterKey", isSignal: true, isRequired: true, transformFunction: null }, state: { classPropertyName: "state", publicName: "state", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null }, required: { classPropertyName: "required", publicName: "required", isSignal: true, isRequired: false, transformFunction: null }, invalid: { classPropertyName: "invalid", publicName: "invalid", isSignal: true, isRequired: false, transformFunction: null }, errorMessageId: { classPropertyName: "errorMessageId", publicName: "errorMessageId", isSignal: true, isRequired: false, transformFunction: null }, orientation: { classPropertyName: "orientation", publicName: "orientation", isSignal: true, isRequired: false, transformFunction: null }, keyFn: { classPropertyName: "keyFn", publicName: "keyFn", isSignal: true, isRequired: false, transformFunction: null }, selectedValues: { classPropertyName: "selectedValues", publicName: "selectedValues", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { disabled: "disabledChange", required: "requiredChange", invalid: "invalidChange", selectedValues: "selectedValuesChange" }, queries: [{ propertyName: "chipTemplate", first: true, predicate: (CngxFilterChip), descendants: true, isSignal: true }], exportAs: ["cngxFilterChips"], ngImport: i0, template: `
488
+ <cngx-multi-chip-group
489
+ [label]="label()"
490
+ [(selectedValues)]="selectedValues"
491
+ [state]="state()"
492
+ [keyFn]="keyFn()"
493
+ [(disabled)]="disabled"
494
+ [(required)]="required"
495
+ [(invalid)]="invalid"
496
+ [errorMessageId]="errorMessageId()"
497
+ [orientation]="orientation()"
498
+ >
499
+ @for (option of options(); track keyFn()(optionValue()(option))) {
500
+ <cngx-chip cngxChipInGroup [value]="optionValue()(option)">
501
+ @if (chipTemplate()?.template; as tpl) {
502
+ <ng-container
503
+ *ngTemplateOutlet="tpl; context: chipContext(option)"
504
+ />
505
+ } @else {
506
+ {{ optionLabel()(option) }}
507
+ }
508
+ </cngx-chip>
509
+ }
510
+ </cngx-multi-chip-group>
511
+ `, isInline: true, dependencies: [{ kind: "component", type: CngxChip, selector: "cngx-chip", inputs: ["removable", "id", "removeAriaLabel"], outputs: ["remove"], exportAs: ["cngxChip"] }, { kind: "component", type: CngxMultiChipGroup, selector: "cngx-multi-chip-group, [cngxMultiChipGroup]", inputs: ["selectedValues", "disabled", "required", "invalid", "errorMessageId", "orientation", "label", "state", "keyFn"], outputs: ["selectedValuesChange", "disabledChange", "requiredChange", "invalidChange"], exportAs: ["cngxMultiChipGroup"] }, { kind: "directive", type: CngxChipInGroup, selector: "[cngxChipInGroup]", inputs: ["value", "disabled", "cngxDescribedBy"], exportAs: ["cngxChipInGroup"] }, { kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
512
+ }
513
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFilterChips, decorators: [{
514
+ type: Component,
515
+ args: [{
516
+ selector: 'cngx-filter-chips',
517
+ exportAs: 'cngxFilterChips',
518
+ standalone: true,
519
+ changeDetection: ChangeDetectionStrategy.OnPush,
520
+ imports: [CngxChip, CngxMultiChipGroup, CngxChipInGroup, NgTemplateOutlet],
521
+ template: `
522
+ <cngx-multi-chip-group
523
+ [label]="label()"
524
+ [(selectedValues)]="selectedValues"
525
+ [state]="state()"
526
+ [keyFn]="keyFn()"
527
+ [(disabled)]="disabled"
528
+ [(required)]="required"
529
+ [(invalid)]="invalid"
530
+ [errorMessageId]="errorMessageId()"
531
+ [orientation]="orientation()"
532
+ >
533
+ @for (option of options(); track keyFn()(optionValue()(option))) {
534
+ <cngx-chip cngxChipInGroup [value]="optionValue()(option)">
535
+ @if (chipTemplate()?.template; as tpl) {
536
+ <ng-container
537
+ *ngTemplateOutlet="tpl; context: chipContext(option)"
538
+ />
539
+ } @else {
540
+ {{ optionLabel()(option) }}
541
+ }
542
+ </cngx-chip>
543
+ }
544
+ </cngx-multi-chip-group>
545
+ `,
546
+ }]
547
+ }], ctorParameters: () => [], propDecorators: { label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: true }] }], options: [{ type: i0.Input, args: [{ isSignal: true, alias: "options", required: true }] }], optionLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "optionLabel", required: true }] }], optionValue: [{ type: i0.Input, args: [{ isSignal: true, alias: "optionValue", required: true }] }], filterRef: [{ type: i0.Input, args: [{ isSignal: true, alias: "filterRef", required: true }] }], filterKey: [{ type: i0.Input, args: [{ isSignal: true, alias: "filterKey", required: true }] }], state: [{ type: i0.Input, args: [{ isSignal: true, alias: "state", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }, { type: i0.Output, args: ["disabledChange"] }], required: [{ type: i0.Input, args: [{ isSignal: true, alias: "required", required: false }] }, { type: i0.Output, args: ["requiredChange"] }], invalid: [{ type: i0.Input, args: [{ isSignal: true, alias: "invalid", required: false }] }, { type: i0.Output, args: ["invalidChange"] }], errorMessageId: [{ type: i0.Input, args: [{ isSignal: true, alias: "errorMessageId", required: false }] }], orientation: [{ type: i0.Input, args: [{ isSignal: true, alias: "orientation", required: false }] }], keyFn: [{ type: i0.Input, args: [{ isSignal: true, alias: "keyFn", required: false }] }], chipTemplate: [{ type: i0.ContentChild, args: [i0.forwardRef(() => CngxFilterChip), { isSignal: true }] }], selectedValues: [{ type: i0.Input, args: [{ isSignal: true, alias: "selectedValues", required: false }] }, { type: i0.Output, args: ["selectedValuesChange"] }] } });
548
+
549
+ /**
550
+ * Atom directive that tracks pagination state (current page index and page size).
551
+ *
552
+ * Supports both **uncontrolled** (internal state) and **controlled** modes.
553
+ * In controlled mode the `cngxPageIndex` / `cngxPageSize` inputs take precedence
554
+ * over internal state — pair with `pageChange` / `pageSizeChange` to keep them
555
+ * in sync.
556
+ *
557
+ * Consumer connects this to a list or table via `range()` — nothing is injected
558
+ * automatically.
559
+ *
560
+ * // Headless: read range() from a template ref
561
+ * <div cngxPaginate #pg="cngxPaginate" [total]="items.length">
562
+ * @for (item of items.slice(pg.range()[0], pg.range()[1]); track item.id) { ... }
563
+ * </div>
564
+ *
565
+ * // With CngxMatPaginator:
566
+ * <cngx-mat-paginator [cngxPaginateRef]="pg" />
567
+ */
568
+ class CngxPaginate {
569
+ /** Controlled page index. When bound, takes precedence over internal state. */
570
+ pageIndexInput = input(undefined, { ...(ngDevMode ? { debugName: "pageIndexInput" } : /* istanbul ignore next */ {}), alias: 'cngxPageIndex' });
571
+ /** Controlled page size. When bound, takes precedence over internal state. */
572
+ pageSizeInput = input(undefined, { ...(ngDevMode ? { debugName: "pageSizeInput" } : /* istanbul ignore next */ {}), alias: 'cngxPageSize' });
573
+ /**
574
+ * Total number of items (before pagination). Consumer binds this from the
575
+ * filtered/sorted count so that `totalPages` stays accurate.
576
+ */
577
+ total = input(0, ...(ngDevMode ? [{ debugName: "total" }] : /* istanbul ignore next */ []));
578
+ /**
579
+ * Bind an async state — disables navigation while the data source is busy.
580
+ * When set, `isBusy` derives from `state.isBusy()`. Navigation methods
581
+ * (`setPage`, `next`, `previous`, etc.) are no-ops while busy.
582
+ */
583
+ state = input(undefined, ...(ngDevMode ? [{ debugName: "state" }] : /* istanbul ignore next */ []));
584
+ /** `true` when the bound async state is busy (loading/refreshing). */
585
+ isBusy = computed(() => this.state()?.isBusy() ?? false, ...(ngDevMode ? [{ debugName: "isBusy" }] : /* istanbul ignore next */ []));
586
+ pageIndexState = signal(0, ...(ngDevMode ? [{ debugName: "pageIndexState" }] : /* istanbul ignore next */ []));
587
+ pageSizeState = signal(10, ...(ngDevMode ? [{ debugName: "pageSizeState" }] : /* istanbul ignore next */ []));
588
+ /** Current page index (0-based). Controlled input takes precedence. Auto-clamped to totalPages. */
589
+ pageIndex = computed(() => {
590
+ const raw = this.pageIndexInput() ?? this.pageIndexState();
591
+ const max = this.totalPages() - 1;
592
+ return Math.min(raw, max);
593
+ }, ...(ngDevMode ? [{ debugName: "pageIndex" }] : /* istanbul ignore next */ []));
594
+ /** Current page size. Controlled input takes precedence. */
595
+ pageSize = computed(() => this.pageSizeInput() ?? this.pageSizeState(), ...(ngDevMode ? [{ debugName: "pageSize" }] : /* istanbul ignore next */ []));
596
+ /** Total number of pages (minimum 1). */
597
+ totalPages = computed(() => Math.max(1, Math.ceil(this.total() / this.pageSize())), ...(ngDevMode ? [{ debugName: "totalPages" }] : /* istanbul ignore next */ []));
598
+ /** `true` when on the first page. */
599
+ isFirst = computed(() => this.pageIndex() === 0, ...(ngDevMode ? [{ debugName: "isFirst" }] : /* istanbul ignore next */ []));
600
+ /** `true` when on the last page. */
601
+ isLast = computed(() => this.pageIndex() >= this.totalPages() - 1, ...(ngDevMode ? [{ debugName: "isLast" }] : /* istanbul ignore next */ []));
602
+ /**
603
+ * `[start, end]` indices for `Array.slice()` — always in-bounds.
604
+ * Consumer: `items.slice(range()[0], range()[1])`.
605
+ */
606
+ range = computed(() => {
607
+ const start = this.pageIndex() * this.pageSize();
608
+ return [start, start + this.pageSize()];
609
+ }, ...(ngDevMode ? [{ debugName: "range" }] : /* istanbul ignore next */ []));
610
+ /** Emitted when the page index changes. */
611
+ pageChange = output();
612
+ /** Emitted when the page size changes. */
613
+ pageSizeChange = output();
614
+ /**
615
+ * Navigate to `index`, clamping to `[0, totalPages - 1]`.
616
+ * Emits `pageChange`.
617
+ */
618
+ setPage(index) {
619
+ if (this.isBusy()) {
620
+ return;
621
+ }
622
+ const clamped = Math.max(0, Math.min(index, this.totalPages() - 1));
623
+ this.pageIndexState.set(clamped);
624
+ this.pageChange.emit(clamped);
625
+ }
626
+ /**
627
+ * Change page size and optionally reset to page 0.
628
+ * Emits `pageSizeChange` and, when `resetPage` is `true`, `pageChange`.
629
+ */
630
+ setPageSize(size, resetPage = true) {
631
+ if (this.isBusy()) {
632
+ return;
633
+ }
634
+ this.pageSizeState.set(size);
635
+ this.pageSizeChange.emit(size);
636
+ if (resetPage) {
637
+ this.pageIndexState.set(0);
638
+ this.pageChange.emit(0);
639
+ }
640
+ }
641
+ /** Navigate to the next page (no-op on the last page). */
642
+ next() {
643
+ this.setPage(this.pageIndex() + 1);
644
+ }
645
+ /** Navigate to the previous page (no-op on the first page). */
646
+ previous() {
647
+ this.setPage(this.pageIndex() - 1);
648
+ }
649
+ /** Navigate to the first page. */
650
+ first() {
651
+ this.setPage(0);
652
+ }
653
+ /** Navigate to the last page. */
654
+ last() {
655
+ this.setPage(this.totalPages() - 1);
656
+ }
657
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxPaginate, deps: [], target: i0.ɵɵFactoryTarget.Directive });
658
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxPaginate, isStandalone: true, selector: "[cngxPaginate]", inputs: { pageIndexInput: { classPropertyName: "pageIndexInput", publicName: "cngxPageIndex", isSignal: true, isRequired: false, transformFunction: null }, pageSizeInput: { classPropertyName: "pageSizeInput", publicName: "cngxPageSize", isSignal: true, isRequired: false, transformFunction: null }, total: { classPropertyName: "total", publicName: "total", isSignal: true, isRequired: false, transformFunction: null }, state: { classPropertyName: "state", publicName: "state", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { pageChange: "pageChange", pageSizeChange: "pageSizeChange" }, exportAs: ["cngxPaginate"], ngImport: i0 });
659
+ }
660
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxPaginate, decorators: [{
661
+ type: Directive,
662
+ args: [{
663
+ selector: '[cngxPaginate]',
664
+ exportAs: 'cngxPaginate',
665
+ standalone: true,
666
+ }]
667
+ }], propDecorators: { pageIndexInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxPageIndex", required: false }] }], pageSizeInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxPageSize", required: false }] }], total: [{ type: i0.Input, args: [{ isSignal: true, alias: "total", required: false }] }], state: [{ type: i0.Input, args: [{ isSignal: true, alias: "state", required: false }] }], pageChange: [{ type: i0.Output, args: ["pageChange"] }], pageSizeChange: [{ type: i0.Output, args: ["pageSizeChange"] }] } });
668
+
669
+ /**
670
+ * Minimal CDK `DataSource` that bridges a Signal to the CDK table's
671
+ * Observable-based data contract.
672
+ *
673
+ * No sort, filter, or search logic is included — the consumer builds a
674
+ * `computed()` with any transformations and passes the result here.
675
+ *
676
+ * ```typescript
677
+ * readonly processed = computed(() => {
678
+ * let items = this.raw();
679
+ * if (this.sort().sort()) { items = sortTree(items, ...); }
680
+ * return items;
681
+ * });
682
+ * readonly dataSource = injectDataSource(this.processed);
683
+ * ```
684
+ *
685
+ * @typeParam T - The row item type.
686
+ */
687
+ class CngxDataSource extends DataSource {
688
+ data;
689
+ injector = inject(Injector);
690
+ constructor(data) {
691
+ super();
692
+ this.data = data;
693
+ }
694
+ connect() {
695
+ return toObservable(this.data, { injector: this.injector });
696
+ }
697
+ disconnect() {
698
+ // Signal cleanup is handled by Angular's DestroyRef — no manual teardown needed.
699
+ }
700
+ }
701
+ /**
702
+ * Factory function for {@link CngxDataSource}.
703
+ *
704
+ * Must be called within an injection context (constructor or field initializer).
705
+ *
706
+ * ```typescript
707
+ * readonly dataSource = injectDataSource(this.items);
708
+ * ```
709
+ */
710
+ function injectDataSource(data) {
711
+ return new CngxDataSource(data);
712
+ }
713
+
714
+ function isAsyncState(source) {
715
+ return 'status' in source && 'data' in source && 'isFirstLoad' in source;
716
+ }
717
+ /**
718
+ * A CDK `DataSource` that optionally integrates with `CngxSort`,
719
+ * `CngxFilter`, `CngxSearch`, and `CngxPaginate` present in the injection
720
+ * tree. Each directive is injected optionally — if absent, that processing
721
+ * step is skipped.
722
+ *
723
+ * Accepts either a plain `Signal<T[]>` or a `CngxAsyncState<T[]>`.
724
+ * When a `CngxAsyncState` is provided, the data source exposes the full
725
+ * UX state (`isLoading`, `isRefreshing`, `error`, `isEmpty`) so the
726
+ * table can show skeleton rows, error states, and loading indicators.
727
+ *
728
+ * ```typescript
729
+ * // Plain signal
730
+ * readonly dataSource = injectSmartDataSource(this.items);
731
+ *
732
+ * // With async state — full UX lifecycle
733
+ * readonly residents = injectAsyncState(() => this.api.getAll(this.filter()));
734
+ * readonly dataSource = injectSmartDataSource(this.residents);
735
+ * // dataSource.isLoading(), dataSource.error(), dataSource.isRefreshing()
736
+ * ```
737
+ *
738
+ * @typeParam T - The row item type.
739
+ */
740
+ class CngxSmartDataSource extends DataSource {
741
+ options;
742
+ injector = inject(Injector);
743
+ sort = inject(CngxSort, { optional: true });
744
+ filter = inject(CngxFilter, { optional: true });
745
+ // CngxSearch typically lives on a child <input> below the component injector,
746
+ // so this inject returns null in the common case. It resolves only when CngxSearch
747
+ // is placed as a hostDirective on the same component. For child-input search,
748
+ // use injectDataSource() + manual computed() instead.
749
+ search = inject(CngxSearch, { optional: true });
750
+ paginate = inject(CngxPaginate, { optional: true });
751
+ /**
752
+ * Items after filter and search are applied, before sort and pagination.
753
+ * Use `filteredCount()` to get the pre-pagination count for paginator `total`.
754
+ */
755
+ filtered;
756
+ /** Number of items after filtering/searching, before pagination. */
757
+ filteredCount;
758
+ processed;
759
+ /** The async state source, or `undefined` if constructed from a plain signal. */
760
+ asyncState;
761
+ /** `true` during initial data load (skeleton phase). */
762
+ isLoading;
763
+ /** `true` during refresh (data stays visible, loading bar). */
764
+ isRefreshing;
765
+ /** `true` when any operation is running. Maps to `aria-busy`. */
766
+ isBusy;
767
+ /** `true` if no successful load has completed yet. */
768
+ isFirstLoad;
769
+ /** Error from the async state, or `undefined`. */
770
+ error;
771
+ /** `true` when data is empty AND no operation is running. */
772
+ isEmpty;
773
+ constructor(source, options) {
774
+ super();
775
+ this.options = options;
776
+ let data;
777
+ if (isAsyncState(source)) {
778
+ this.asyncState = source;
779
+ data = computed(() => source.data() ?? []);
780
+ }
781
+ else {
782
+ this.asyncState = undefined;
783
+ data = source;
784
+ }
785
+ const s = this.asyncState;
786
+ this.isLoading = computed(() => s?.isLoading() ?? false, ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
787
+ this.isRefreshing = computed(() => s?.isRefreshing() ?? false, ...(ngDevMode ? [{ debugName: "isRefreshing" }] : /* istanbul ignore next */ []));
788
+ this.isBusy = computed(() => s?.isBusy() ?? false, ...(ngDevMode ? [{ debugName: "isBusy" }] : /* istanbul ignore next */ []));
789
+ this.isFirstLoad = computed(() => s?.isFirstLoad() ?? false, ...(ngDevMode ? [{ debugName: "isFirstLoad" }] : /* istanbul ignore next */ []));
790
+ this.error = computed(() => s?.error(), ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
791
+ this.filtered = computed(() => {
792
+ const predicate = this.filter?.predicate();
793
+ const term = this.search?.term();
794
+ const searchFn = this.options?.searchFn ??
795
+ ((item, t) => {
796
+ const lower = t.toLowerCase();
797
+ return Object.values(item).some((v) => v === null || v === undefined || typeof v === 'object'
798
+ ? false
799
+ : String(v)
800
+ .toLowerCase()
801
+ .includes(lower));
802
+ });
803
+ // Pipeline: raw → filter → search. Cast required: CngxFilter injected as unknown.
804
+ return data()
805
+ .filter((v) => !predicate || predicate(v))
806
+ .filter((item) => !term || searchFn(item, term));
807
+ }, ...(ngDevMode ? [{ debugName: "filtered" }] : /* istanbul ignore next */ []));
808
+ this.filteredCount = computed(() => this.filtered().length, ...(ngDevMode ? [{ debugName: "filteredCount" }] : /* istanbul ignore next */ []));
809
+ this.isEmpty = computed(() => {
810
+ // During loading, not "empty" yet — show skeleton instead
811
+ if (this.isBusy()) {
812
+ return false;
813
+ }
814
+ return this.filteredCount() === 0;
815
+ }, ...(ngDevMode ? [{ debugName: "isEmpty" }] : /* istanbul ignore next */ []));
816
+ this.processed = computed(() => {
817
+ const sorts = this.sort?.sorts() ?? [];
818
+ const sortFn = this.options?.sortFn ??
819
+ ((a, b, field, dir) => {
820
+ const toStr = (v) => v === null || v === undefined || typeof v === 'object'
821
+ ? ''
822
+ : String(v);
823
+ const av = toStr(a[field]);
824
+ const bv = toStr(b[field]);
825
+ const cmp = av.localeCompare(bv, undefined, { numeric: true, sensitivity: 'base' });
826
+ return dir === 'asc' ? cmp : -cmp;
827
+ });
828
+ const sorted = sorts.length > 0
829
+ ? [...this.filtered()].sort((a, b) => sorts.reduce((cmp, { active, direction }) => cmp || sortFn(a, b, active, direction), 0))
830
+ : this.filtered();
831
+ const range = this.paginate?.range();
832
+ return range ? sorted.slice(range[0], range[1]) : sorted;
833
+ }, ...(ngDevMode ? [{ debugName: "processed" }] : /* istanbul ignore next */ []));
834
+ }
835
+ connect() {
836
+ return toObservable(this.processed, { injector: this.injector });
837
+ }
838
+ disconnect() {
839
+ // Signal cleanup is handled by Angular's DestroyRef — no manual teardown needed.
840
+ }
841
+ }
842
+ /**
843
+ * Factory function for {@link CngxSmartDataSource}.
844
+ *
845
+ * Must be called within an injection context (constructor or field initializer).
846
+ * Accepts either a plain `Signal<T[]>` or a `CngxAsyncState<T[]>` for
847
+ * full UX state integration (loading, error, refresh, empty).
848
+ *
849
+ * ```typescript
850
+ * // Plain signal
851
+ * readonly dataSource = injectSmartDataSource(this.items);
852
+ *
853
+ * // With async state — table shows skeleton, error, loading bar
854
+ * readonly residents = injectAsyncState(() => this.api.getAll());
855
+ * readonly dataSource = injectSmartDataSource(this.residents);
856
+ * ```
857
+ */
858
+ function injectSmartDataSource(source, options) {
859
+ return new CngxSmartDataSource(source, options);
860
+ }
861
+
862
+ /**
863
+ * Create a fully manual async state — no HTTP, no automatic loading.
864
+ *
865
+ * Use for local operations: heavy computations, Web Workers, complex local processes.
866
+ * Does **not** require an injection context — uses only `signal()` and `computed()`.
867
+ *
868
+ * ```typescript
869
+ * readonly processState = createManualState<ProcessResult>();
870
+ *
871
+ * async handleProcess(): Promise<void> {
872
+ * this.processState.set('loading');
873
+ * this.processState.setProgress(0);
874
+ * const result = await heavyComputation((p) => this.processState.setProgress(p));
875
+ * this.processState.setSuccess(result);
876
+ * }
877
+ * ```
878
+ */
879
+ function createManualState() {
880
+ const statusState = signal('idle', ...(ngDevMode ? [{ debugName: "statusState" }] : /* istanbul ignore next */ []));
881
+ const dataState = signal(undefined, ...(ngDevMode ? [{ debugName: "dataState" }] : /* istanbul ignore next */ []));
882
+ const errorState = signal(undefined, ...(ngDevMode ? [{ debugName: "errorState" }] : /* istanbul ignore next */ []));
883
+ const progressState = signal(undefined, ...(ngDevMode ? [{ debugName: "progressState" }] : /* istanbul ignore next */ []));
884
+ const lastUpdatedState = signal(undefined, ...(ngDevMode ? [{ debugName: "lastUpdatedState" }] : /* istanbul ignore next */ []));
885
+ const hadSuccess = signal(false, ...(ngDevMode ? [{ debugName: "hadSuccess" }] : /* istanbul ignore next */ []));
886
+ const view = buildAsyncStateView({
887
+ status: statusState.asReadonly(),
888
+ data: dataState.asReadonly(),
889
+ error: errorState.asReadonly(),
890
+ progress: progressState.asReadonly(),
891
+ isFirstLoad: computed(() => !hadSuccess()),
892
+ lastUpdated: lastUpdatedState.asReadonly(),
893
+ });
894
+ return {
895
+ ...view,
896
+ set(newStatus) {
897
+ statusState.set(newStatus);
898
+ if (newStatus === 'success') {
899
+ hadSuccess.set(true);
900
+ lastUpdatedState.set(new Date());
901
+ }
902
+ },
903
+ setSuccess(value) {
904
+ dataState.set(value);
905
+ errorState.set(undefined);
906
+ progressState.set(undefined);
907
+ hadSuccess.set(true);
908
+ lastUpdatedState.set(new Date());
909
+ statusState.set('success');
910
+ },
911
+ setError(err) {
912
+ errorState.set(err);
913
+ progressState.set(undefined);
914
+ statusState.set('error');
915
+ },
916
+ setProgress(value) {
917
+ progressState.set(value);
918
+ },
919
+ reset() {
920
+ statusState.set('idle');
921
+ dataState.set(undefined);
922
+ errorState.set(undefined);
923
+ progressState.set(undefined);
924
+ lastUpdatedState.set(undefined);
925
+ hadSuccess.set(false);
926
+ },
927
+ };
928
+ }
929
+
930
+ /**
931
+ * Create a mutation async state — for explicit user-triggered actions.
932
+ *
933
+ * Must be called in an injection context (field initializer or constructor)
934
+ * because it uses `inject(DestroyRef)` for cleanup.
935
+ *
936
+ * ```typescript
937
+ * readonly saveResident = createAsyncState<Resident>();
938
+ *
939
+ * async handleSave(): Promise<void> {
940
+ * await this.saveResident.execute(
941
+ * () => this.api.save(this.form().value())
942
+ * );
943
+ * }
944
+ * ```
945
+ */
946
+ function createAsyncState() {
947
+ const destroyRef = inject(DestroyRef);
948
+ const state = createManualState();
949
+ let abortController;
950
+ destroyRef.onDestroy(() => {
951
+ abortController?.abort();
952
+ abortController = undefined;
953
+ });
954
+ return {
955
+ status: state.status,
956
+ data: state.data,
957
+ error: state.error,
958
+ progress: state.progress,
959
+ isLoading: state.isLoading,
960
+ isPending: state.isPending,
961
+ isRefreshing: state.isRefreshing,
962
+ isBusy: state.isBusy,
963
+ isFirstLoad: state.isFirstLoad,
964
+ isEmpty: state.isEmpty,
965
+ hasData: state.hasData,
966
+ isSettled: state.isSettled,
967
+ lastUpdated: state.lastUpdated,
968
+ async execute(fn) {
969
+ abortController?.abort();
970
+ const controller = new AbortController();
971
+ abortController = controller;
972
+ state.set('pending');
973
+ state.setProgress(undefined);
974
+ try {
975
+ const result$ = fn();
976
+ const result = isObservable(result$) ? await firstValueFrom(result$) : await result$;
977
+ // Check if this execution was superseded
978
+ if (controller.signal.aborted) {
979
+ return;
980
+ }
981
+ state.setSuccess(result);
982
+ }
983
+ catch (err) {
984
+ if (controller.signal.aborted) {
985
+ return;
986
+ }
987
+ state.setError(err);
988
+ }
989
+ finally {
990
+ if (abortController === controller) {
991
+ abortController = undefined;
992
+ }
993
+ }
994
+ },
995
+ reportProgress(value) {
996
+ state.setProgress(value);
997
+ },
998
+ reset() {
999
+ abortController?.abort();
1000
+ abortController = undefined;
1001
+ state.reset();
1002
+ },
1003
+ };
1004
+ }
1005
+
1006
+ /**
1007
+ * Create a reactive async state that auto-loads when signal dependencies change.
1008
+ *
1009
+ * Must be called in an injection context (field initializer or constructor).
1010
+ * The computation function is tracked by Angular's `effect()` — any signal
1011
+ * read inside `fn` will cause a re-load when it changes.
1012
+ *
1013
+ * ```typescript
1014
+ * readonly residents = injectAsyncState(
1015
+ * () => this.api.getResidents(this.filter())
1016
+ * );
1017
+ * // Loads automatically when filter() changes.
1018
+ * // Caches last result during refresh (refreshing state).
1019
+ * // Deduplicates parallel requests.
1020
+ * ```
1021
+ */
1022
+ function injectAsyncState(fn, options) {
1023
+ const destroyRef = inject(DestroyRef);
1024
+ const state = createManualState();
1025
+ const debounceMs = options?.debounce ?? 50;
1026
+ let activeSubscription;
1027
+ let abortController;
1028
+ let debounceTimer;
1029
+ function cancelInFlight() {
1030
+ activeSubscription?.unsubscribe();
1031
+ activeSubscription = undefined;
1032
+ abortController?.abort();
1033
+ abortController = undefined;
1034
+ }
1035
+ destroyRef.onDestroy(() => {
1036
+ cancelInFlight();
1037
+ if (debounceTimer !== undefined) {
1038
+ clearTimeout(debounceTimer);
1039
+ debounceTimer = undefined;
1040
+ }
1041
+ });
1042
+ function executeQuery(computation) {
1043
+ cancelInFlight();
1044
+ // First load → 'loading', subsequent → 'refreshing'
1045
+ const status = untracked(state.isFirstLoad) ? 'loading' : 'refreshing';
1046
+ state.set(status);
1047
+ const result$ = computation();
1048
+ if (isObservable(result$)) {
1049
+ // Observable path — subscribe, cancel via unsubscribe
1050
+ let hasEmitted = false;
1051
+ activeSubscription = result$.subscribe({
1052
+ next: (value) => {
1053
+ hasEmitted = true;
1054
+ state.setSuccess(value);
1055
+ },
1056
+ error: (err) => state.setError(err),
1057
+ complete: () => {
1058
+ if (!hasEmitted) {
1059
+ // Observable completed without emitting — treat as empty success
1060
+ state.setSuccess(undefined);
1061
+ }
1062
+ },
1063
+ });
1064
+ }
1065
+ else {
1066
+ // Promise path — cancel via AbortController
1067
+ const controller = new AbortController();
1068
+ abortController = controller;
1069
+ result$
1070
+ .then((value) => {
1071
+ if (!controller.signal.aborted) {
1072
+ state.setSuccess(value);
1073
+ }
1074
+ }, (err) => {
1075
+ if (!controller.signal.aborted) {
1076
+ state.setError(err);
1077
+ }
1078
+ })
1079
+ .finally(() => {
1080
+ if (abortController === controller) {
1081
+ abortController = undefined;
1082
+ }
1083
+ });
1084
+ }
1085
+ }
1086
+ // The effect calls fn() exactly once per cycle.
1087
+ // The result is captured and forwarded to executeQuery — no double invocation.
1088
+ effect(() => {
1089
+ // fn() reads signals → tracked by effect. The returned Promise/Observable
1090
+ // is captured here and executed after debounce.
1091
+ let result;
1092
+ try {
1093
+ result = fn();
1094
+ }
1095
+ catch (err) {
1096
+ // fn() threw synchronously (e.g. required signal not yet set).
1097
+ // Schedule error state after debounce to match async behavior.
1098
+ if (debounceTimer !== undefined) {
1099
+ clearTimeout(debounceTimer);
1100
+ }
1101
+ debounceTimer = setTimeout(() => {
1102
+ debounceTimer = undefined;
1103
+ state.setError(err);
1104
+ }, debounceMs);
1105
+ return;
1106
+ }
1107
+ if (debounceTimer !== undefined) {
1108
+ clearTimeout(debounceTimer);
1109
+ }
1110
+ // Capture result in closure — executeQuery receives it directly.
1111
+ const captured = result;
1112
+ debounceTimer = setTimeout(() => {
1113
+ debounceTimer = undefined;
1114
+ void executeQuery(() => captured);
1115
+ }, debounceMs);
1116
+ });
1117
+ return {
1118
+ status: state.status,
1119
+ data: state.data,
1120
+ error: state.error,
1121
+ progress: state.progress,
1122
+ isLoading: state.isLoading,
1123
+ isPending: state.isPending,
1124
+ isRefreshing: state.isRefreshing,
1125
+ isBusy: state.isBusy,
1126
+ isFirstLoad: state.isFirstLoad,
1127
+ isEmpty: state.isEmpty,
1128
+ hasData: state.hasData,
1129
+ isSettled: state.isSettled,
1130
+ lastUpdated: state.lastUpdated,
1131
+ refresh() {
1132
+ if (debounceTimer !== undefined) {
1133
+ clearTimeout(debounceTimer);
1134
+ debounceTimer = undefined;
1135
+ }
1136
+ void executeQuery(fn);
1137
+ },
1138
+ };
1139
+ }
1140
+
1141
+ /**
1142
+ * Pure function that resolves which view to show based on async state.
1143
+ *
1144
+ * Encodes the state machine as a lookup table — no branching:
1145
+ *
1146
+ * | status | firstLoad | empty | view |
1147
+ * |-------------|-----------|-------|---------------|
1148
+ * | idle | true | * | none |
1149
+ * | loading | true | * | skeleton |
1150
+ * | refreshing | true | * | skeleton |
1151
+ * | pending | true | * | skeleton |
1152
+ * | error | true | * | error |
1153
+ * | success | * | true | empty |
1154
+ * | error | false | * | content+error |
1155
+ * | (all other) | * | * | content |
1156
+ */
1157
+ function resolveAsyncView(status, firstLoad, empty) {
1158
+ if (firstLoad) {
1159
+ switch (status) {
1160
+ case 'idle':
1161
+ return 'none';
1162
+ case 'loading':
1163
+ case 'refreshing':
1164
+ case 'pending':
1165
+ return 'skeleton';
1166
+ case 'error':
1167
+ return 'error';
1168
+ }
1169
+ }
1170
+ if (status === 'success' && empty) {
1171
+ return 'empty';
1172
+ }
1173
+ if (status === 'error') {
1174
+ return 'content+error';
1175
+ }
1176
+ return 'content';
1177
+ }
1178
+
1179
+ /**
1180
+ * Bridge that projects an Angular `Resource<T>` onto `CngxAsyncState<T>`.
1181
+ *
1182
+ * Must be called in an injection context (the `effect()` that tracks
1183
+ * `hadSuccess` requires one).
1184
+ *
1185
+ * All signals are derived reactively from the resource — no manual
1186
+ * synchronization. The resource stays the single source of truth.
1187
+ *
1188
+ * ```typescript
1189
+ * private readonly res = resource({
1190
+ * request: () => ({ filter: this.filter() }),
1191
+ * loader: ({ request, abortSignal }) =>
1192
+ * fetch(`/api/items?q=${request.filter}`, { signal: abortSignal })
1193
+ * .then(r => r.json()),
1194
+ * });
1195
+ *
1196
+ * readonly items = fromResource(this.res);
1197
+ * // items.status(), items.data(), items.isFirstLoad() — all work
1198
+ * // <cngx-async-container [state]="items"> — direct binding
1199
+ * ```
1200
+ */
1201
+ function fromResource(ref) {
1202
+ // Track whether a successful load has ever occurred.
1203
+ // Needed because ResourceStatus has no "first load" concept.
1204
+ const hadSuccess = signal(false, ...(ngDevMode ? [{ debugName: "hadSuccess" }] : /* istanbul ignore next */ []));
1205
+ effect(() => {
1206
+ const s = ref.status();
1207
+ if (s === 'resolved' || s === 'local') {
1208
+ hadSuccess.set(true);
1209
+ }
1210
+ });
1211
+ const status = computed(() => {
1212
+ switch (ref.status()) {
1213
+ case 'idle':
1214
+ return 'idle';
1215
+ case 'loading':
1216
+ return 'loading';
1217
+ case 'reloading':
1218
+ return 'refreshing';
1219
+ case 'resolved':
1220
+ case 'local':
1221
+ return 'success';
1222
+ case 'error':
1223
+ return 'error';
1224
+ }
1225
+ }, ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
1226
+ const data = computed(() => (ref.hasValue() ? ref.value() : undefined), ...(ngDevMode ? [{ debugName: "data" }] : /* istanbul ignore next */ []));
1227
+ const error = computed(() => ref.error(), ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
1228
+ const isLoading = computed(() => status() === 'loading', ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
1229
+ const isPending = computed(() => false, ...(ngDevMode ? [{ debugName: "isPending" }] : /* istanbul ignore next */ [])); // resource() has no mutation concept
1230
+ const isRefreshing = computed(() => status() === 'refreshing', ...(ngDevMode ? [{ debugName: "isRefreshing" }] : /* istanbul ignore next */ []));
1231
+ const isBusy = computed(() => ref.isLoading(), ...(ngDevMode ? [{ debugName: "isBusy" }] : /* istanbul ignore next */ []));
1232
+ const isFirstLoad = computed(() => !hadSuccess() && (isBusy() || status() === 'idle'), ...(ngDevMode ? [{ debugName: "isFirstLoad" }] : /* istanbul ignore next */ []));
1233
+ const isEmpty = computed(() => {
1234
+ const d = data();
1235
+ return d == null || (Array.isArray(d) && d.length === 0);
1236
+ }, ...(ngDevMode ? [{ debugName: "isEmpty" }] : /* istanbul ignore next */ []));
1237
+ const hasData = computed(() => ref.hasValue() && !isEmpty(), ...(ngDevMode ? [{ debugName: "hasData" }] : /* istanbul ignore next */ []));
1238
+ const isSettled = computed(() => {
1239
+ const s = status();
1240
+ return s === 'success' || s === 'error';
1241
+ }, ...(ngDevMode ? [{ debugName: "isSettled" }] : /* istanbul ignore next */ []));
1242
+ const lastUpdated = signal(undefined, ...(ngDevMode ? [{ debugName: "lastUpdated" }] : /* istanbul ignore next */ []));
1243
+ effect(() => {
1244
+ const s = ref.status();
1245
+ if (s === 'resolved' || s === 'local') {
1246
+ lastUpdated.set(new Date());
1247
+ }
1248
+ });
1249
+ return {
1250
+ status,
1251
+ data,
1252
+ error,
1253
+ progress: signal(undefined).asReadonly(),
1254
+ isLoading,
1255
+ isPending,
1256
+ isRefreshing,
1257
+ isBusy,
1258
+ isFirstLoad,
1259
+ isEmpty,
1260
+ hasData,
1261
+ isSettled,
1262
+ lastUpdated: lastUpdated.asReadonly(),
1263
+ };
1264
+ }
1265
+
1266
+ /**
1267
+ * Bridge that projects an Angular `httpResource()` ref onto `CngxAsyncState<T>`.
1268
+ *
1269
+ * Identical to `fromResource` but additionally maps the HTTP progress
1270
+ * signal to `CngxAsyncState.progress` (0–100 scale).
1271
+ *
1272
+ * Must be called in an injection context.
1273
+ *
1274
+ * ```typescript
1275
+ * private readonly res = httpResource<Item[]>(() => ({
1276
+ * url: '/api/items',
1277
+ * params: { q: this.filter() },
1278
+ * }));
1279
+ *
1280
+ * readonly items = fromHttpResource(this.res);
1281
+ * // items.progress() tracks upload/download progress
1282
+ * // <cngx-progress [state]="items"> — auto-wired progress bar
1283
+ * ```
1284
+ */
1285
+ function fromHttpResource(ref) {
1286
+ const hadSuccess = signal(false, ...(ngDevMode ? [{ debugName: "hadSuccess" }] : /* istanbul ignore next */ []));
1287
+ effect(() => {
1288
+ const s = ref.status();
1289
+ if (s === 'resolved' || s === 'local') {
1290
+ hadSuccess.set(true);
1291
+ }
1292
+ });
1293
+ const status = computed(() => {
1294
+ switch (ref.status()) {
1295
+ case 'idle':
1296
+ return 'idle';
1297
+ case 'loading':
1298
+ return 'loading';
1299
+ case 'reloading':
1300
+ return 'refreshing';
1301
+ case 'resolved':
1302
+ case 'local':
1303
+ return 'success';
1304
+ case 'error':
1305
+ return 'error';
1306
+ }
1307
+ }, ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
1308
+ const data = computed(() => (ref.hasValue() ? ref.value() : undefined), ...(ngDevMode ? [{ debugName: "data" }] : /* istanbul ignore next */ []));
1309
+ const error = computed(() => ref.error(), ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
1310
+ // Map HTTP progress (0–1 float) to 0–100 integer, clamped
1311
+ const progress = computed(() => {
1312
+ const p = ref.progress();
1313
+ if (p == null) {
1314
+ return undefined;
1315
+ }
1316
+ return Math.round(Math.min(p, 1) * 100);
1317
+ }, ...(ngDevMode ? [{ debugName: "progress" }] : /* istanbul ignore next */ []));
1318
+ const isLoading = computed(() => status() === 'loading', ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
1319
+ const isPending = computed(() => false, ...(ngDevMode ? [{ debugName: "isPending" }] : /* istanbul ignore next */ []));
1320
+ const isRefreshing = computed(() => status() === 'refreshing', ...(ngDevMode ? [{ debugName: "isRefreshing" }] : /* istanbul ignore next */ []));
1321
+ const isBusy = computed(() => ref.isLoading(), ...(ngDevMode ? [{ debugName: "isBusy" }] : /* istanbul ignore next */ []));
1322
+ const isFirstLoad = computed(() => !hadSuccess() && isBusy(), ...(ngDevMode ? [{ debugName: "isFirstLoad" }] : /* istanbul ignore next */ []));
1323
+ const isEmpty = computed(() => {
1324
+ const d = data();
1325
+ return d == null || (Array.isArray(d) && d.length === 0);
1326
+ }, ...(ngDevMode ? [{ debugName: "isEmpty" }] : /* istanbul ignore next */ []));
1327
+ const hasData = computed(() => ref.hasValue() && !isEmpty(), ...(ngDevMode ? [{ debugName: "hasData" }] : /* istanbul ignore next */ []));
1328
+ const isSettled = computed(() => {
1329
+ const s = status();
1330
+ return s === 'success' || s === 'error';
1331
+ }, ...(ngDevMode ? [{ debugName: "isSettled" }] : /* istanbul ignore next */ []));
1332
+ const lastUpdated = signal(undefined, ...(ngDevMode ? [{ debugName: "lastUpdated" }] : /* istanbul ignore next */ []));
1333
+ effect(() => {
1334
+ const s = ref.status();
1335
+ if (s === 'resolved' || s === 'local') {
1336
+ lastUpdated.set(new Date());
1337
+ }
1338
+ });
1339
+ return {
1340
+ status,
1341
+ data,
1342
+ error,
1343
+ progress,
1344
+ isLoading,
1345
+ isPending,
1346
+ isRefreshing,
1347
+ isBusy,
1348
+ isFirstLoad,
1349
+ isEmpty,
1350
+ hasData,
1351
+ isSettled,
1352
+ lastUpdated: lastUpdated.asReadonly(),
1353
+ };
1354
+ }
1355
+
1356
+ /**
1357
+ * RxJS operator that wires an Observable's lifecycle to a `ManualAsyncState`.
1358
+ *
1359
+ * On subscribe: sets `loading` (or `refreshing` if data was already loaded).
1360
+ * On next: calls `setSuccess(value)`.
1361
+ * On error: calls `setError(err)` and **re-throws** (does not swallow).
1362
+ *
1363
+ * The Observable passes through unchanged — `tapAsyncState` is a side-effect operator.
1364
+ *
1365
+ * ```typescript
1366
+ * readonly residents = createManualState<Resident[]>();
1367
+ *
1368
+ * load(): void {
1369
+ * this.http.get<Resident[]>('/api/residents').pipe(
1370
+ * tapAsyncState(this.residents),
1371
+ * takeUntilDestroyed(this.destroyRef),
1372
+ * ).subscribe();
1373
+ * }
1374
+ * ```
1375
+ */
1376
+ function tapAsyncState(state, options) {
1377
+ return (source) => defer(() => {
1378
+ state.set(options?.status ?? 'loading');
1379
+ return source.pipe(tap({
1380
+ next: (value) => state.setSuccess(value),
1381
+ error: (err) => state.setError(err),
1382
+ }));
1383
+ });
1384
+ }
1385
+ // HttpEventType values (from @angular/common/http)
1386
+ const UPLOAD_PROGRESS = 1;
1387
+ const DOWNLOAD_PROGRESS = 3;
1388
+ const RESPONSE = 4;
1389
+ /**
1390
+ * RxJS operator that extracts upload/download progress from an
1391
+ * `HttpEvent` stream and reports it to a `ManualAsyncState`.
1392
+ *
1393
+ * Filters progress events, calculates percentage, calls `setProgress()`.
1394
+ * Non-progress events pass through unchanged.
1395
+ *
1396
+ * Use with `{ observe: 'events', reportProgress: true }` on HttpClient.
1397
+ *
1398
+ * ```typescript
1399
+ * readonly upload = createManualState<UploadResult>();
1400
+ *
1401
+ * handleUpload(file: File): void {
1402
+ * this.http.post('/api/upload', file, {
1403
+ * reportProgress: true,
1404
+ * observe: 'events',
1405
+ * }).pipe(
1406
+ * tapAsyncProgress(this.upload),
1407
+ * takeUntilDestroyed(this.destroyRef),
1408
+ * ).subscribe();
1409
+ * }
1410
+ * ```
1411
+ */
1412
+ function tapAsyncProgress(state) {
1413
+ return tap((event) => {
1414
+ const e = event;
1415
+ if ((e.type === UPLOAD_PROGRESS || e.type === DOWNLOAD_PROGRESS) &&
1416
+ e.total != null &&
1417
+ e.total > 0) {
1418
+ state.setProgress(Math.round((100 * e.loaded) / e.total));
1419
+ }
1420
+ });
1421
+ }
1422
+ /**
1423
+ * RxJS operator that combines `tapAsyncState` + `tapAsyncProgress` for HTTP event streams.
1424
+ *
1425
+ * Pipe this onto an `HttpClient` call with `{ observe: 'events', reportProgress: true }`.
1426
+ * It will:
1427
+ * 1. Set `loading` on subscribe
1428
+ * 2. Report upload/download progress via `setProgress()`
1429
+ * 3. Extract the response body on `HttpEventType.Response`
1430
+ * 4. Call `setSuccess(body)` with the extracted body
1431
+ * 5. Call `setError(err)` on error
1432
+ *
1433
+ * The output Observable emits the **response body** (not HttpEvents).
1434
+ * Throws if the response body is `null`.
1435
+ *
1436
+ * ```typescript
1437
+ * readonly upload = createManualState<UploadResult>();
1438
+ *
1439
+ * handleUpload(file: File): void {
1440
+ * this.http.post('/api/upload', file, {
1441
+ * reportProgress: true,
1442
+ * observe: 'events',
1443
+ * }).pipe(
1444
+ * tapHttpAsyncState(this.upload),
1445
+ * takeUntilDestroyed(this.destroyRef),
1446
+ * ).subscribe();
1447
+ * // upload.status(), upload.progress(), upload.data() — all wired
1448
+ * }
1449
+ * ```
1450
+ */
1451
+ function tapHttpAsyncState(state, options) {
1452
+ return (source) => defer(() => {
1453
+ state.set(options?.status ?? 'loading');
1454
+ return source.pipe(tapAsyncProgress(state), filter((event) => {
1455
+ return event.type === RESPONSE;
1456
+ }), map((response) => {
1457
+ if (response.body == null) {
1458
+ throw new Error('tapHttpAsyncState: response body is null');
1459
+ }
1460
+ return response.body;
1461
+ }), tap({
1462
+ next: (value) => state.setSuccess(value),
1463
+ error: (err) => state.setError(err),
1464
+ }));
1465
+ });
1466
+ }
1467
+
1468
+ /**
1469
+ * Structural directive for async state-driven content rendering.
1470
+ *
1471
+ * Renders different views based on the current `CngxAsyncState` status:
1472
+ * - **loading (first load)** → skeleton template (or nothing)
1473
+ * - **success + has data** → content template with typed data
1474
+ * - **success + empty** → empty template (or nothing)
1475
+ * - **error (first load)** → error template (or nothing)
1476
+ * - **refreshing / loading (with data)** → content template (old data stays visible)
1477
+ * - **error (with data)** → content template (old data stays visible)
1478
+ *
1479
+ * ### Minimal — just content
1480
+ * ```html
1481
+ * <ul *cngxAsync="residents; let data">
1482
+ * @for (r of data; track r.id) { <li>{{ r.name }}</li> }
1483
+ * </ul>
1484
+ * ```
1485
+ *
1486
+ * ### With custom templates
1487
+ * ```html
1488
+ * <ul *cngxAsync="residents; let data; skeleton: skelTpl; empty: emptyTpl; error: errTpl">
1489
+ * @for (r of data; track r.id) { <li>{{ r.name }}</li> }
1490
+ * </ul>
1491
+ *
1492
+ * <ng-template #skelTpl>
1493
+ * @for (i of [1,2,3]; track i) { <li class="skeleton-line"></li> }
1494
+ * </ng-template>
1495
+ *
1496
+ * <ng-template #emptyTpl>
1497
+ * <li>No residents found.</li>
1498
+ * </ng-template>
1499
+ *
1500
+ * <ng-template #errTpl let-err>
1501
+ * <li>Error: {{ err }}</li>
1502
+ * </ng-template>
1503
+ * ```
1504
+ */
1505
+ class CngxAsync {
1506
+ vcr = inject(ViewContainerRef);
1507
+ contentTpl = inject(TemplateRef);
1508
+ /** The async state to render. */
1509
+ cngxAsync = input.required(...(ngDevMode ? [{ debugName: "cngxAsync" }] : /* istanbul ignore next */ []));
1510
+ /** Optional skeleton template shown during first load. */
1511
+ cngxAsyncSkeleton = input(undefined, ...(ngDevMode ? [{ debugName: "cngxAsyncSkeleton" }] : /* istanbul ignore next */ []));
1512
+ /** Optional empty template shown when data is empty after success. */
1513
+ cngxAsyncEmpty = input(undefined, ...(ngDevMode ? [{ debugName: "cngxAsyncEmpty" }] : /* istanbul ignore next */ []));
1514
+ /** Optional error template shown on error during first load. Context: `{ $implicit: error }`. */
1515
+ cngxAsyncError = input(undefined, ...(ngDevMode ? [{ debugName: "cngxAsyncError" }] : /* istanbul ignore next */ []));
1516
+ view = computed(() => {
1517
+ const s = this.cngxAsync();
1518
+ return resolveAsyncView(s.status(), s.isFirstLoad(), s.isEmpty());
1519
+ }, ...(ngDevMode ? [{ debugName: "view" }] : /* istanbul ignore next */ []));
1520
+ currentView = signal('none', ...(ngDevMode ? [{ debugName: "currentView" }] : /* istanbul ignore next */ []));
1521
+ contentViewRef = null;
1522
+ constructor() {
1523
+ effect(() => {
1524
+ const view = this.view();
1525
+ const s = this.cngxAsync();
1526
+ // content+error → show content (structural directive has no dual-render)
1527
+ const effective = view === 'content+error' ? 'content' : view;
1528
+ if (effective === this.currentView()) {
1529
+ this.updateContentContext(s);
1530
+ return;
1531
+ }
1532
+ this.vcr.clear();
1533
+ this.contentViewRef = null;
1534
+ this.currentView.set(effective);
1535
+ this.renderView(effective, s);
1536
+ });
1537
+ }
1538
+ updateContentContext(s) {
1539
+ if (!this.contentViewRef) {
1540
+ return;
1541
+ }
1542
+ const data = s.data();
1543
+ if (data === undefined) {
1544
+ return;
1545
+ }
1546
+ this.contentViewRef.context.$implicit = data;
1547
+ this.contentViewRef.context.cngxAsync = data;
1548
+ this.contentViewRef.markForCheck();
1549
+ }
1550
+ renderView(view, s) {
1551
+ switch (view) {
1552
+ case 'skeleton':
1553
+ this.renderTemplate(this.cngxAsyncSkeleton());
1554
+ break;
1555
+ case 'content':
1556
+ case 'content+error': {
1557
+ const data = s.data();
1558
+ this.contentViewRef = this.vcr.createEmbeddedView(this.contentTpl, {
1559
+ $implicit: data,
1560
+ cngxAsync: data,
1561
+ });
1562
+ break;
1563
+ }
1564
+ case 'empty':
1565
+ this.renderTemplate(this.cngxAsyncEmpty());
1566
+ break;
1567
+ case 'error':
1568
+ this.renderTemplate(this.cngxAsyncError(), { $implicit: s.error() });
1569
+ break;
1570
+ }
1571
+ }
1572
+ renderTemplate(tpl, context) {
1573
+ if (tpl) {
1574
+ this.vcr.createEmbeddedView(tpl, context);
1575
+ }
1576
+ }
1577
+ /** Type guard for template type inference. */
1578
+ static ngTemplateContextGuard(_dir, _ctx) {
1579
+ return true;
1580
+ }
1581
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAsync, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1582
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxAsync, isStandalone: true, selector: "[cngxAsync]", inputs: { cngxAsync: { classPropertyName: "cngxAsync", publicName: "cngxAsync", isSignal: true, isRequired: true, transformFunction: null }, cngxAsyncSkeleton: { classPropertyName: "cngxAsyncSkeleton", publicName: "cngxAsyncSkeleton", isSignal: true, isRequired: false, transformFunction: null }, cngxAsyncEmpty: { classPropertyName: "cngxAsyncEmpty", publicName: "cngxAsyncEmpty", isSignal: true, isRequired: false, transformFunction: null }, cngxAsyncError: { classPropertyName: "cngxAsyncError", publicName: "cngxAsyncError", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0 });
1583
+ }
1584
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAsync, decorators: [{
1585
+ type: Directive,
1586
+ args: [{
1587
+ selector: '[cngxAsync]',
1588
+ standalone: true,
1589
+ }]
1590
+ }], ctorParameters: () => [], propDecorators: { cngxAsync: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxAsync", required: true }] }], cngxAsyncSkeleton: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxAsyncSkeleton", required: false }] }], cngxAsyncEmpty: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxAsyncEmpty", required: false }] }], cngxAsyncError: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxAsyncError", required: false }] }] } });
1591
+
1592
+ /**
1593
+ * Displays a formatted numeric value with optional unit.
1594
+ *
1595
+ * Uses `Intl.NumberFormat` with the injected `LOCALE_ID` for locale-aware
1596
+ * formatting. Null values render as an em-dash.
1597
+ *
1598
+ * Composable — works inside any card variant, header, body, or standalone.
1599
+ *
1600
+ * ### Basic
1601
+ * ```html
1602
+ * <cngx-metric [value]="1234" unit="bpm" />
1603
+ * ```
1604
+ *
1605
+ * ### With format options
1606
+ * ```html
1607
+ * <cngx-metric [value]="99.6" unit="%" [format]="{ maximumFractionDigits: 1 }" />
1608
+ * ```
1609
+ *
1610
+ * ### Inside a card
1611
+ * ```html
1612
+ * <cngx-card>
1613
+ * <header cngxCardHeader>Puls</header>
1614
+ * <cngx-metric cngxCardBody [value]="75" unit="bpm" />
1615
+ * </cngx-card>
1616
+ * ```
1617
+ */
1618
+ class CngxMetric {
1619
+ locale = inject(LOCALE_ID);
1620
+ /** Numeric or string value. `null` renders as em-dash. */
1621
+ value = input.required(...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
1622
+ /** Unit suffix (e.g. "bpm", "h", "%", "kg"). */
1623
+ unit = input(undefined, ...(ngDevMode ? [{ debugName: "unit" }] : /* istanbul ignore next */ []));
1624
+ /** `Intl.NumberFormatOptions` for the primary value. */
1625
+ format = input(undefined, ...(ngDevMode ? [{ debugName: "format" }] : /* istanbul ignore next */ []));
1626
+ /** @internal */
1627
+ formattedValue = computed(() => {
1628
+ const v = this.value();
1629
+ if (v === null) {
1630
+ return '\u2014';
1631
+ }
1632
+ if (typeof v === 'string') {
1633
+ return v;
1634
+ }
1635
+ return this.format()
1636
+ ? new Intl.NumberFormat(this.locale, this.format()).format(v)
1637
+ : v.toLocaleString(this.locale);
1638
+ }, ...(ngDevMode ? [{ debugName: "formattedValue" }] : /* istanbul ignore next */ []));
1639
+ /** @internal Full accessible description including unit. */
1640
+ accessibleValue = computed(() => {
1641
+ const v = this.formattedValue();
1642
+ const u = this.unit();
1643
+ return u ? `${v} ${u}` : v;
1644
+ }, ...(ngDevMode ? [{ debugName: "accessibleValue" }] : /* istanbul ignore next */ []));
1645
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxMetric, deps: [], target: i0.ɵɵFactoryTarget.Component });
1646
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.4", type: CngxMetric, isStandalone: true, selector: "cngx-metric", inputs: { value: { classPropertyName: "value", publicName: "value", isSignal: true, isRequired: true, transformFunction: null }, unit: { classPropertyName: "unit", publicName: "unit", isSignal: true, isRequired: false, transformFunction: null }, format: { classPropertyName: "format", publicName: "format", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "attr.aria-label": "accessibleValue()" }, classAttribute: "cngx-metric" }, ngImport: i0, template: `
1647
+ <span class="cngx-metric__value">{{ formattedValue() }}</span>
1648
+ @if (unit()) {
1649
+ <span class="cngx-metric__unit">{{ unit() }}</span>
1650
+ }
1651
+ `, isInline: true, changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
1652
+ }
1653
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxMetric, decorators: [{
1654
+ type: Component,
1655
+ args: [{
1656
+ selector: 'cngx-metric',
1657
+ standalone: true,
1658
+ changeDetection: ChangeDetectionStrategy.OnPush,
1659
+ encapsulation: ViewEncapsulation.None,
1660
+ host: {
1661
+ class: 'cngx-metric',
1662
+ '[attr.aria-label]': 'accessibleValue()',
1663
+ },
1664
+ template: `
1665
+ <span class="cngx-metric__value">{{ formattedValue() }}</span>
1666
+ @if (unit()) {
1667
+ <span class="cngx-metric__unit">{{ unit() }}</span>
1668
+ }
1669
+ `,
1670
+ }]
1671
+ }], propDecorators: { value: [{ type: i0.Input, args: [{ isSignal: true, alias: "value", required: true }] }], unit: [{ type: i0.Input, args: [{ isSignal: true, alias: "unit", required: false }] }], format: [{ type: i0.Input, args: [{ isSignal: true, alias: "format", required: false }] }] } });
1672
+
1673
+ /**
1674
+ * Displays a trend indicator with directional arrow and formatted percentage.
1675
+ *
1676
+ * Positive values show an up arrow, negative a down arrow, zero a right arrow.
1677
+ * The consumer can override the SR label for full context
1678
+ * (e.g. "vs. last month" instead of the generic default).
1679
+ *
1680
+ * ### Basic
1681
+ * ```html
1682
+ * <cngx-trend [value]="5.3" />
1683
+ * ```
1684
+ *
1685
+ * ### With custom label
1686
+ * ```html
1687
+ * <cngx-trend [value]="-2.1" label="-2.1% vs. last quarter" />
1688
+ * ```
1689
+ *
1690
+ * ### Inside a card header
1691
+ * ```html
1692
+ * <cngx-card>
1693
+ * <header cngxCardHeader>
1694
+ * <span>Revenue</span>
1695
+ * <cngx-trend [value]="revenue().trend" />
1696
+ * </header>
1697
+ * </cngx-card>
1698
+ * ```
1699
+ */
1700
+ class CngxTrend {
1701
+ /** Trend percentage. Positive = up, negative = down, zero = flat. */
1702
+ value = input.required(...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
1703
+ /** Consumer-provided SR label override. When set, replaces the generated default. */
1704
+ label = input(undefined, ...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
1705
+ /** @internal */
1706
+ icon = computed(() => this.value() > 0 ? '\u2191' : this.value() < 0 ? '\u2193' : '\u2192', ...(ngDevMode ? [{ debugName: "icon" }] : /* istanbul ignore next */ []));
1707
+ /** @internal */
1708
+ formattedValue = computed(() => {
1709
+ const v = this.value();
1710
+ const abs = Math.abs(v);
1711
+ return `${v > 0 ? '+' : ''}${abs.toFixed(1)}\u202F%`;
1712
+ }, ...(ngDevMode ? [{ debugName: "formattedValue" }] : /* istanbul ignore next */ []));
1713
+ /** @internal */
1714
+ resolvedLabel = computed(() => {
1715
+ if (this.label()) {
1716
+ return this.label();
1717
+ }
1718
+ const dir = this.value() > 0 ? 'up' : this.value() < 0 ? 'down' : 'unchanged';
1719
+ return `${this.formattedValue()} ${dir}`;
1720
+ }, ...(ngDevMode ? [{ debugName: "resolvedLabel" }] : /* istanbul ignore next */ []));
1721
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTrend, deps: [], target: i0.ɵɵFactoryTarget.Component });
1722
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "21.2.4", type: CngxTrend, isStandalone: true, selector: "cngx-trend", inputs: { value: { classPropertyName: "value", publicName: "value", isSignal: true, isRequired: true, transformFunction: null }, label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "class.cngx-trend--up": "value() > 0", "class.cngx-trend--down": "value() < 0", "attr.aria-label": "resolvedLabel()" }, classAttribute: "cngx-trend" }, ngImport: i0, template: `
1723
+ <span aria-hidden="true">{{ icon() }}</span>
1724
+ {{ formattedValue() }}
1725
+ `, isInline: true, changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
1726
+ }
1727
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTrend, decorators: [{
1728
+ type: Component,
1729
+ args: [{
1730
+ selector: 'cngx-trend',
1731
+ standalone: true,
1732
+ changeDetection: ChangeDetectionStrategy.OnPush,
1733
+ encapsulation: ViewEncapsulation.None,
1734
+ host: {
1735
+ class: 'cngx-trend',
1736
+ '[class.cngx-trend--up]': 'value() > 0',
1737
+ '[class.cngx-trend--down]': 'value() < 0',
1738
+ '[attr.aria-label]': 'resolvedLabel()',
1739
+ },
1740
+ template: `
1741
+ <span aria-hidden="true">{{ icon() }}</span>
1742
+ {{ formattedValue() }}
1743
+ `,
1744
+ }]
1745
+ }], propDecorators: { value: [{ type: i0.Input, args: [{ isSignal: true, alias: "value", required: true }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }] } });
1746
+
1747
+ // Step 1: range-computer.ts — pure function, zero dependencies
1748
+ const EMPTY_RANGE = {
1749
+ start: 0,
1750
+ end: 0,
1751
+ offsetBefore: 0,
1752
+ offsetAfter: 0,
1753
+ totalSize: 0,
1754
+ };
1755
+ /**
1756
+ * Computes the visible range of items given scroll position, viewport size,
1757
+ * total item count, and item size estimation.
1758
+ *
1759
+ * Pure function — no DOM access, no Angular dependency. Fully testable.
1760
+ *
1761
+ * @param scrollTop Current scroll offset in px.
1762
+ * @param clientHeight Viewport height in px.
1763
+ * @param totalCount Total number of items.
1764
+ * @param estimateSize Fixed item height in px, or a function returning height per index.
1765
+ * @param overscan Number of extra items to render above/below the viewport.
1766
+ * @param columns Column count for grid mode (default 1). When > 1, range is row-aligned.
1767
+ * Variable `estimateSize` ignores columns (grid + variable heights not supported).
1768
+ * @returns The computed range with spacer offsets.
1769
+ */
1770
+ function computeRange(scrollTop, clientHeight, totalCount, estimateSize, overscan, columns = 1) {
1771
+ if (totalCount <= 0 || clientHeight <= 0) {
1772
+ return EMPTY_RANGE;
1773
+ }
1774
+ if (typeof estimateSize === 'number') {
1775
+ return computeFixedRange(scrollTop, clientHeight, totalCount, estimateSize, overscan, columns);
1776
+ }
1777
+ // Variable heights — grid mode not supported, columns ignored
1778
+ return computeVariableRange(scrollTop, clientHeight, totalCount, estimateSize, overscan);
1779
+ }
1780
+ function computeFixedRange(scrollTop, clientHeight, totalCount, itemSize, overscan, columns) {
1781
+ if (columns > 1) {
1782
+ return computeGridRange(scrollTop, clientHeight, totalCount, itemSize, overscan, columns);
1783
+ }
1784
+ const totalSize = totalCount * itemSize;
1785
+ const rawStart = Math.floor(scrollTop / itemSize);
1786
+ const rawEnd = Math.ceil((scrollTop + clientHeight) / itemSize);
1787
+ const start = Math.max(0, rawStart - overscan);
1788
+ const end = Math.min(totalCount, rawEnd + overscan);
1789
+ return {
1790
+ start,
1791
+ end,
1792
+ offsetBefore: start * itemSize,
1793
+ offsetAfter: Math.max(0, (totalCount - end) * itemSize),
1794
+ totalSize,
1795
+ };
1796
+ }
1797
+ /**
1798
+ * Grid-mode range computation. Row-aligned before overscan.
1799
+ *
1800
+ * Order: raw visible rows → overscan rows → clamp → convert to item indices.
1801
+ * This ensures full rows are always rendered.
1802
+ */
1803
+ function computeGridRange(scrollTop, clientHeight, totalCount, rowHeight, overscan, columns) {
1804
+ const totalRows = Math.ceil(totalCount / columns);
1805
+ const totalSize = totalRows * rowHeight;
1806
+ // Step 1+2: raw visible rows (inherently row-aligned)
1807
+ const rawStartRow = Math.floor(scrollTop / rowHeight);
1808
+ const rawEndRow = Math.ceil((scrollTop + clientHeight) / rowHeight);
1809
+ // Step 3: apply overscan in rows (convert item overscan to row overscan)
1810
+ const overscanRows = Math.ceil(overscan / columns);
1811
+ const startRow = Math.max(0, rawStartRow - overscanRows);
1812
+ const endRow = Math.min(totalRows, rawEndRow + overscanRows);
1813
+ // Step 4: convert to item indices, clamp end to totalCount
1814
+ const start = startRow * columns;
1815
+ const end = Math.min(endRow * columns, totalCount);
1816
+ return {
1817
+ start,
1818
+ end,
1819
+ offsetBefore: startRow * rowHeight,
1820
+ offsetAfter: Math.max(0, (totalRows - endRow) * rowHeight),
1821
+ totalSize,
1822
+ };
1823
+ }
1824
+ function computeVariableRange(scrollTop, clientHeight, totalCount, estimateSize, overscan) {
1825
+ // Accumulate heights to find the first visible item (binary search)
1826
+ let totalSize = 0;
1827
+ const offsets = new Array(totalCount + 1);
1828
+ offsets[0] = 0;
1829
+ for (let i = 0; i < totalCount; i++) {
1830
+ totalSize += estimateSize(i);
1831
+ offsets[i + 1] = totalSize;
1832
+ }
1833
+ // Binary search for the first item whose bottom edge is past scrollTop
1834
+ const rawStart = binarySearch(offsets, scrollTop, totalCount);
1835
+ const rawEnd = binarySearch(offsets, scrollTop + clientHeight, totalCount);
1836
+ const start = Math.max(0, rawStart - overscan);
1837
+ const end = Math.min(totalCount, rawEnd + 1 + overscan);
1838
+ return {
1839
+ start,
1840
+ end,
1841
+ offsetBefore: offsets[start],
1842
+ offsetAfter: Math.max(0, totalSize - offsets[end]),
1843
+ totalSize,
1844
+ };
1845
+ }
1846
+ /** Finds the index of the first item whose cumulative offset exceeds `target`. */
1847
+ function binarySearch(offsets, target, totalCount) {
1848
+ let low = 0;
1849
+ let high = totalCount - 1;
1850
+ while (low <= high) {
1851
+ const mid = (low + high) >>> 1;
1852
+ if (offsets[mid + 1] <= target) {
1853
+ low = mid + 1;
1854
+ }
1855
+ else if (offsets[mid] > target) {
1856
+ high = mid - 1;
1857
+ }
1858
+ else {
1859
+ return mid;
1860
+ }
1861
+ }
1862
+ return Math.min(low, totalCount - 1);
1863
+ }
1864
+
1865
+ // Step 2: scroll-observer.ts — addEventListener + ResizeObserver → signals
1866
+ /**
1867
+ * Creates a reactive scroll observer for a container element.
1868
+ *
1869
+ * Element resolution happens **lazily inside the effect**, not at call time.
1870
+ * This is critical because `injectRecycler` is called in a field initializer
1871
+ * where template DOM does not yet exist — `querySelector` would return `null`.
1872
+ * The effect runs after the first CD cycle when the DOM is stable.
1873
+ *
1874
+ * @internal Not exported from `@cngx/common/data` public API.
1875
+ */
1876
+ function createScrollObserver(elementRef, destroyRef) {
1877
+ const doc = inject(DOCUMENT);
1878
+ const scrollTopState = signal(0, ...(ngDevMode ? [{ debugName: "scrollTopState" }] : /* istanbul ignore next */ []));
1879
+ const clientHeightState = signal(0, ...(ngDevMode ? [{ debugName: "clientHeightState" }] : /* istanbul ignore next */ []));
1880
+ const elementState = signal(null, ...(ngDevMode ? [{ debugName: "elementState" }] : /* istanbul ignore next */ []));
1881
+ // Retry trigger — incremented by afterNextRender to re-run the effect
1882
+ // when the element wasn't found on the first attempt (routed components,
1883
+ // content projection, lazy rendering).
1884
+ const retryTick = signal(0, ...(ngDevMode ? [{ debugName: "retryTick" }] : /* istanbul ignore next */ []));
1885
+ function attachListeners(el, onCleanup) {
1886
+ elementState.set(el);
1887
+ scrollTopState.set(el.scrollTop);
1888
+ clientHeightState.set(el.clientHeight);
1889
+ let rafId = null;
1890
+ const handleScroll = () => {
1891
+ if (rafId != null) {
1892
+ return;
1893
+ }
1894
+ rafId = requestAnimationFrame(() => {
1895
+ rafId = null;
1896
+ scrollTopState.set(el.scrollTop);
1897
+ clientHeightState.set(el.clientHeight);
1898
+ });
1899
+ };
1900
+ el.addEventListener('scroll', handleScroll, { passive: true });
1901
+ const resizeObserver = new ResizeObserver(() => {
1902
+ clientHeightState.set(el.clientHeight);
1903
+ });
1904
+ resizeObserver.observe(el);
1905
+ onCleanup(() => {
1906
+ el.removeEventListener('scroll', handleScroll);
1907
+ if (rafId != null) {
1908
+ cancelAnimationFrame(rafId);
1909
+ }
1910
+ resizeObserver.disconnect();
1911
+ elementState.set(null);
1912
+ });
1913
+ }
1914
+ effect((onCleanup) => {
1915
+ retryTick(); // tracked — effect re-runs when retryTick changes
1916
+ const el = resolveElement(elementRef, doc);
1917
+ if (!el) {
1918
+ return;
1919
+ }
1920
+ attachListeners(el, onCleanup);
1921
+ });
1922
+ // If the element wasn't found on the first effect run (before DOM is ready),
1923
+ // retry after the next render cycle. Fires for ALL input shapes — string
1924
+ // selectors resolve lazily via `querySelector`, but `ElementRef` from a
1925
+ // `viewChild` also starts out with `nativeElement == null` until Angular
1926
+ // resolves the query. `HTMLElement` inputs that are non-null at call time
1927
+ // short-circuit on the first effect run so the retry is a no-op.
1928
+ afterNextRender(() => {
1929
+ // untracked: afterNextRender may run in the same microtask as the effect.
1930
+ // Reading elementState() without untracked could create an unintended dependency
1931
+ // in whatever reactive context is active.
1932
+ if (untracked(() => elementState()) == null) {
1933
+ retryTick.update((v) => v + 1);
1934
+ }
1935
+ });
1936
+ // Additional cleanup via DestroyRef as safety net
1937
+ destroyRef.onDestroy(() => {
1938
+ elementState.set(null);
1939
+ });
1940
+ return {
1941
+ scrollTop: scrollTopState.asReadonly(),
1942
+ clientHeight: clientHeightState.asReadonly(),
1943
+ element: elementState.asReadonly(),
1944
+ };
1945
+ }
1946
+ function resolveElement(ref, doc) {
1947
+ if (typeof ref === 'string') {
1948
+ return doc.querySelector(ref);
1949
+ }
1950
+ if (ref instanceof HTMLElement) {
1951
+ return ref;
1952
+ }
1953
+ // ElementRef
1954
+ return ref?.nativeElement ?? null;
1955
+ }
1956
+
1957
+ // Phase 2: size-cache.ts — Signal-based measured height cache
1958
+ /**
1959
+ * Creates a signal-based size cache for measured item heights.
1960
+ *
1961
+ * @internal
1962
+ */
1963
+ function createSizeCache() {
1964
+ const cache = new Map();
1965
+ const versionState = signal(0, ...(ngDevMode ? [{ debugName: "versionState" }] : /* istanbul ignore next */ []));
1966
+ return {
1967
+ get(index) {
1968
+ return cache.get(index);
1969
+ },
1970
+ set(index, size) {
1971
+ const current = cache.get(index);
1972
+ if (current === size) {
1973
+ return;
1974
+ }
1975
+ cache.set(index, size);
1976
+ versionState.update((v) => v + 1);
1977
+ },
1978
+ version: versionState.asReadonly(),
1979
+ resolve(index, estimateSize) {
1980
+ const measured = cache.get(index);
1981
+ if (measured != null) {
1982
+ return measured;
1983
+ }
1984
+ return typeof estimateSize === 'number' ? estimateSize : estimateSize(index);
1985
+ },
1986
+ get count() {
1987
+ return cache.size;
1988
+ },
1989
+ clear() {
1990
+ if (cache.size === 0) {
1991
+ return;
1992
+ }
1993
+ cache.clear();
1994
+ versionState.update((v) => v + 1);
1995
+ },
1996
+ };
1997
+ }
1998
+
1999
+ /**
2000
+ * Injection token for recycler SR announcement texts.
2001
+ * Provides English defaults via factory. Override with `provideRecyclerI18n()`.
2002
+ */
2003
+ const CNGX_RECYCLER_I18N = new InjectionToken('CngxRecyclerI18n', {
2004
+ factory: () => ({
2005
+ loaded: (n, t) => `${n} more items loaded. ${t} total.`,
2006
+ filtered: (c) => `${c} results found.`,
2007
+ empty: () => 'No results.',
2008
+ error: () => 'Error loading data.',
2009
+ }),
2010
+ });
2011
+ /**
2012
+ * Provider function for custom recycler i18n texts.
2013
+ *
2014
+ * ```typescript
2015
+ * providers: [provideRecyclerI18n({
2016
+ * loaded: (n, t) => `${n} weitere Einträge. ${t} gesamt.`,
2017
+ * filtered: (c) => `${c} Ergebnisse.`,
2018
+ * empty: () => 'Keine Ergebnisse.',
2019
+ * error: () => 'Fehler beim Laden.',
2020
+ * })]
2021
+ * ```
2022
+ */
2023
+ function provideRecyclerI18n(i18n) {
2024
+ return { provide: CNGX_RECYCLER_I18N, useValue: i18n };
2025
+ }
2026
+ /**
2027
+ * Inline equivalent of `createVisibilityTimer` from `@cngx/ui/feedback` (Level 4, not importable).
2028
+ *
2029
+ * Uses `setTimeout` inside an effect — this is a timer-driven side effect, not derived state.
2030
+ * Same pattern accepted in `createVisibilityTimer` for `CngxLoadingOverlay`.
2031
+ * Safe in zoneless: the `setTimeout` callback only writes a signal, which schedules
2032
+ * Angular's own change detection — no Zone.js dependency.
2033
+ *
2034
+ * @param source Boolean signal to delay. When `true`, starts the timer.
2035
+ * @param delayMs Delay in milliseconds before the flag becomes `true`.
2036
+ * @returns A readonly signal that becomes `true` after `delayMs` when `source` is `true`.
2037
+ * @internal
2038
+ */
2039
+ function createDelayedFlag(source, delayMs) {
2040
+ if (delayMs <= 0) {
2041
+ return source;
2042
+ }
2043
+ const flag = signal(false, ...(ngDevMode ? [{ debugName: "flag" }] : /* istanbul ignore next */ []));
2044
+ effect((onCleanup) => {
2045
+ const active = source();
2046
+ if (active) {
2047
+ const timer = setTimeout(() => flag.set(true), delayMs);
2048
+ onCleanup(() => {
2049
+ clearTimeout(timer);
2050
+ flag.set(false);
2051
+ });
2052
+ }
2053
+ else {
2054
+ flag.set(false);
2055
+ }
2056
+ });
2057
+ return flag.asReadonly();
2058
+ }
2059
+ /**
2060
+ * Creates a Signal-based virtualizer for DOM recycling.
2061
+ *
2062
+ * Must be called in an injection context (field initializer or constructor).
2063
+ * Internally injects `DestroyRef` and `DOCUMENT` for cleanup and selector resolution.
2064
+ *
2065
+ * ### Basic list
2066
+ * ```typescript
2067
+ * readonly recycler = injectRecycler({
2068
+ * scrollElement: '.scroll-container',
2069
+ * totalCount: () => this.items().length,
2070
+ * estimateSize: 48,
2071
+ * });
2072
+ * readonly visibleItems = this.recycler.sliced(this.items);
2073
+ * ```
2074
+ *
2075
+ * ### With async state
2076
+ * ```typescript
2077
+ * readonly state = injectAsyncState(() => this.api.getAll());
2078
+ * readonly recycler = injectRecycler({
2079
+ * scrollElement: '.scroll-container',
2080
+ * totalCount: () => (this.state.data() ?? []).length,
2081
+ * estimateSize: 64,
2082
+ * state: this.state,
2083
+ * });
2084
+ * ```
2085
+ */
2086
+ function injectRecycler(config) {
2087
+ const destroyRef = inject(DestroyRef);
2088
+ const i18n = inject(CNGX_RECYCLER_I18N);
2089
+ const overscan = config.overscan ?? 5;
2090
+ const isGrid = (config.layout ?? 'list') === 'grid';
2091
+ if (isGrid && config.columns == null && isDevMode()) {
2092
+ console.error('[CngxRecycler] layout: "grid" requires explicit `columns`. Falling back to columns=1.');
2093
+ }
2094
+ // Reactive columns — reactive only if the function reads a Signal internally
2095
+ const columns = computed(() => {
2096
+ if (!isGrid || config.columns == null) {
2097
+ return 1;
2098
+ }
2099
+ return typeof config.columns === 'function' ? config.columns() : config.columns;
2100
+ }, ...(ngDevMode ? [{ debugName: "columns" }] : /* istanbul ignore next */ []));
2101
+ if (typeof config.estimateSize === 'function' && isDevMode()) {
2102
+ const count = config.totalCount();
2103
+ if (count > 10_000) {
2104
+ console.warn(`[CngxRecycler] estimateSize as a function with ${count} items has O(n) ` +
2105
+ `per-frame cost. Consider using a fixed estimateSize for large datasets.`);
2106
+ }
2107
+ }
2108
+ const scrollState = createScrollObserver(config.scrollElement, destroyRef);
2109
+ const sizeCache = createSizeCache();
2110
+ // Resolve size for an index: measured value from cache, or estimateSize fallback.
2111
+ // Reading sizeCache.version() creates a reactive dependency so that range
2112
+ // recomputes when measurements change.
2113
+ const resolveSize = (index) => {
2114
+ sizeCache.version(); // track dependency
2115
+ return sizeCache.resolve(index, config.estimateSize);
2116
+ };
2117
+ // Grid mode uses raw estimateSize (uniform row height, no SizeCache).
2118
+ // List mode uses resolveSize (SizeCache-backed).
2119
+ const range = computed(() => {
2120
+ const cols = columns();
2121
+ const size = isGrid ? config.estimateSize : resolveSize;
2122
+ return computeRange(scrollState.scrollTop(), scrollState.clientHeight(), config.totalCount(), size, overscan, cols);
2123
+ }, ...(ngDevMode ? [{ debugName: "range" }] : /* istanbul ignore next */ []));
2124
+ const start = computed(() => range().start, ...(ngDevMode ? [{ debugName: "start" }] : /* istanbul ignore next */ []));
2125
+ const end = computed(() => range().end, ...(ngDevMode ? [{ debugName: "end" }] : /* istanbul ignore next */ []));
2126
+ // Grid mode: pixel spacers are 0 (placeholders used instead)
2127
+ const offsetBefore = computed(() => (isGrid ? 0 : range().offsetBefore), ...(ngDevMode ? [{ debugName: "offsetBefore" }] : /* istanbul ignore next */ []));
2128
+ const offsetAfter = computed(() => (isGrid ? 0 : range().offsetAfter), ...(ngDevMode ? [{ debugName: "offsetAfter" }] : /* istanbul ignore next */ []));
2129
+ const totalSize = computed(() => range().totalSize, ...(ngDevMode ? [{ debugName: "totalSize" }] : /* istanbul ignore next */ []));
2130
+ const placeholdersBefore = computed(() => (isGrid ? start() : 0), ...(ngDevMode ? [{ debugName: "placeholdersBefore" }] : /* istanbul ignore next */ []));
2131
+ const placeholdersAfter = computed(() => (isGrid ? Math.max(0, config.totalCount() - end()) : 0), ...(ngDevMode ? [{ debugName: "placeholdersAfter" }] : /* istanbul ignore next */ []));
2132
+ // start/end include overscan. firstVisible/lastVisible strip it back
2133
+ // to reflect the items actually in the viewport.
2134
+ // In grid mode, overscan is in rows (ceil(overscan/columns) * columns items).
2135
+ const effectiveOverscan = computed(() => {
2136
+ const cols = columns();
2137
+ if (cols <= 1) {
2138
+ return overscan;
2139
+ }
2140
+ return Math.ceil(overscan / cols) * cols;
2141
+ }, ...(ngDevMode ? [{ debugName: "effectiveOverscan" }] : /* istanbul ignore next */ []));
2142
+ const firstVisible = computed(() => {
2143
+ const total = config.totalCount();
2144
+ if (total === 0) {
2145
+ return 0;
2146
+ }
2147
+ return Math.min(start() + effectiveOverscan(), total - 1);
2148
+ }, ...(ngDevMode ? [{ debugName: "firstVisible" }] : /* istanbul ignore next */ []));
2149
+ const lastVisible = computed(() => {
2150
+ const total = config.totalCount();
2151
+ if (total === 0) {
2152
+ return 0;
2153
+ }
2154
+ return Math.min(Math.max(0, end() - effectiveOverscan() - 1), total - 1);
2155
+ }, ...(ngDevMode ? [{ debugName: "lastVisible" }] : /* istanbul ignore next */ []));
2156
+ const visibleCount = computed(() => {
2157
+ const total = config.totalCount();
2158
+ if (total === 0) {
2159
+ return 0;
2160
+ }
2161
+ return Math.max(0, lastVisible() - firstVisible() + 1);
2162
+ }, ...(ngDevMode ? [{ debugName: "visibleCount" }] : /* istanbul ignore next */ []));
2163
+ const state = config.state;
2164
+ const isLoading = computed(() => state?.isFirstLoad() ?? false, ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
2165
+ const isRefreshing = computed(() => state?.isRefreshing() ?? false, ...(ngDevMode ? [{ debugName: "isRefreshing" }] : /* istanbul ignore next */ []));
2166
+ const isEmpty = computed(() => {
2167
+ if (state?.isBusy()) {
2168
+ return false;
2169
+ }
2170
+ return config.totalCount() === 0;
2171
+ }, ...(ngDevMode ? [{ debugName: "isEmpty" }] : /* istanbul ignore next */ []));
2172
+ const skeletonSlots = computed(() => {
2173
+ const ch = scrollState.clientHeight();
2174
+ if (ch <= 0) {
2175
+ return 0;
2176
+ }
2177
+ // Resolve estimateSize reactively — function variant may read signals internally
2178
+ const itemHeight = typeof config.estimateSize === 'number' ? config.estimateSize : config.estimateSize(0);
2179
+ return Math.ceil(ch / itemHeight);
2180
+ }, ...(ngDevMode ? [{ debugName: "skeletonSlots" }] : /* istanbul ignore next */ []));
2181
+ const showSkeleton = createDelayedFlag(isLoading, config.skeletonDelay ?? 0);
2182
+ // previousTotal is a signal, not a mutable let — reactive, no stale-value risk.
2183
+ const announcementState = signal('', ...(ngDevMode ? [{ debugName: "announcementState" }] : /* istanbul ignore next */ []));
2184
+ const previousTotal = signal(config.totalCount(), ...(ngDevMode ? [{ debugName: "previousTotal" }] : /* istanbul ignore next */ []));
2185
+ if (state) {
2186
+ const tracker = createTransitionTracker(() => state.status());
2187
+ effect(() => {
2188
+ const current = tracker.current();
2189
+ const previous = tracker.previous();
2190
+ const total = config.totalCount();
2191
+ // untracked: previousTotal is bookkeeping, not a dependency —
2192
+ // the effect should fire on status/totalCount changes, not on its own writes.
2193
+ const prevTotal = untracked(() => previousTotal());
2194
+ // Transition-only — never announce on initial idle
2195
+ if (previous === current) {
2196
+ return;
2197
+ }
2198
+ if (current === 'success' && (previous === 'loading' || previous === 'refreshing')) {
2199
+ const diff = total - prevTotal;
2200
+ if (diff > 0) {
2201
+ announcementState.set(i18n.loaded(diff, total));
2202
+ }
2203
+ else {
2204
+ announcementState.set(i18n.filtered(total));
2205
+ }
2206
+ }
2207
+ else if (current === 'error') {
2208
+ announcementState.set(i18n.error());
2209
+ }
2210
+ else if (current === 'success' && total === 0) {
2211
+ announcementState.set(i18n.empty());
2212
+ }
2213
+ untracked(() => previousTotal.set(total));
2214
+ });
2215
+ }
2216
+ else {
2217
+ // Without async state, track totalCount changes for infinite scroll announcements
2218
+ effect(() => {
2219
+ const total = config.totalCount();
2220
+ // untracked: previousTotal is bookkeeping, not a dependency
2221
+ const prevTotal = untracked(() => previousTotal());
2222
+ const diff = total - prevTotal;
2223
+ if (prevTotal > 0 && diff > 0) {
2224
+ announcementState.set(i18n.loaded(diff, total));
2225
+ }
2226
+ else if (prevTotal > 0 && total === 0) {
2227
+ announcementState.set(i18n.empty());
2228
+ }
2229
+ untracked(() => previousTotal.set(total));
2230
+ });
2231
+ }
2232
+ const ariaSetSize = computed(() => config.serverTotal?.() ?? config.totalCount(), ...(ngDevMode ? [{ debugName: "ariaSetSize" }] : /* istanbul ignore next */ []));
2233
+ const anchorState = signal(null, ...(ngDevMode ? [{ debugName: "anchorState" }] : /* istanbul ignore next */ []));
2234
+ function computeItemTop(targetIndex, cols) {
2235
+ // Grid mode: row-based offset (uniform row height)
2236
+ if (isGrid && typeof config.estimateSize === 'number') {
2237
+ const c = cols ?? columns();
2238
+ return Math.floor(targetIndex / c) * config.estimateSize;
2239
+ }
2240
+ let top = 0;
2241
+ for (let i = 0; i < targetIndex; i++) {
2242
+ top += sizeCache.resolve(i, config.estimateSize);
2243
+ }
2244
+ return top;
2245
+ }
2246
+ // Anchor correction effect: when items shift above the anchored item,
2247
+ // correct scrollTop to keep it at the same visual position.
2248
+ effect(() => {
2249
+ const anchor = anchorState();
2250
+ if (!anchor) {
2251
+ return;
2252
+ }
2253
+ sizeCache.version(); // re-run when sizes change
2254
+ config.totalCount(); // re-run when items change
2255
+ const cols = columns(); // re-run when columns change (responsive grid)
2256
+ const el = scrollState.element();
2257
+ if (!el) {
2258
+ return;
2259
+ }
2260
+ const currentItemTop = computeItemTop(anchor.index, cols);
2261
+ const targetScrollTop = currentItemTop - anchor.offsetFromTop;
2262
+ if (Math.abs(el.scrollTop - targetScrollTop) > 1) {
2263
+ el.scrollTop = targetScrollTop;
2264
+ }
2265
+ });
2266
+ // Tracks which item has focus inside the scroll container.
2267
+ // Uses `data-cngx-recycle-index` attribute on items (set by CngxMeasure or consumer).
2268
+ // When a focused item leaves the visible range, `lostFocus` reports its index.
2269
+ const focusedIndex = signal(null, ...(ngDevMode ? [{ debugName: "focusedIndex" }] : /* istanbul ignore next */ []));
2270
+ effect((onCleanup) => {
2271
+ const el = scrollState.element();
2272
+ if (!el) {
2273
+ return;
2274
+ }
2275
+ const handleFocusIn = (e) => {
2276
+ const target = e.target.closest('[data-cngx-recycle-index]');
2277
+ if (target) {
2278
+ focusedIndex.set(Number(target.getAttribute('data-cngx-recycle-index')));
2279
+ }
2280
+ };
2281
+ const handleFocusOut = () => {
2282
+ focusedIndex.set(null);
2283
+ };
2284
+ el.addEventListener('focusin', handleFocusIn);
2285
+ el.addEventListener('focusout', handleFocusOut);
2286
+ onCleanup(() => {
2287
+ el.removeEventListener('focusin', handleFocusIn);
2288
+ el.removeEventListener('focusout', handleFocusOut);
2289
+ });
2290
+ });
2291
+ const lostFocus = computed(() => {
2292
+ const fi = focusedIndex();
2293
+ if (fi == null) {
2294
+ return null;
2295
+ }
2296
+ const s = start();
2297
+ const e = end();
2298
+ if (fi < s || fi >= e) {
2299
+ return { index: fi };
2300
+ }
2301
+ return null;
2302
+ }, ...(ngDevMode ? [{ debugName: "lostFocus" }] : /* istanbul ignore next */ []));
2303
+ const neededRange = computed(() => ({ start: start(), end: end() }), ...(ngDevMode ? [{ debugName: "neededRange" }] : /* istanbul ignore next */ []));
2304
+ const pendingScrollTarget = signal(null, ...(ngDevMode ? [{ debugName: "pendingScrollTarget" }] : /* istanbul ignore next */ []));
2305
+ const pendingTarget = computed(() => pendingScrollTarget()?.index ?? null, ...(ngDevMode ? [{ debugName: "pendingTarget" }] : /* istanbul ignore next */ []));
2306
+ // Watch totalCount — when it grows past the pending target, execute the scroll.
2307
+ // Uses untracked() for pendingScrollTarget reads/writes to avoid write-inside-read loops.
2308
+ // Only totalCount is a tracked dependency.
2309
+ effect(() => {
2310
+ const total = config.totalCount(); // tracked dependency
2311
+ const target = untracked(() => pendingScrollTarget()); // NOT tracked
2312
+ if (!target || target.index >= total) {
2313
+ return;
2314
+ }
2315
+ untracked(() => {
2316
+ pendingScrollTarget.set(null);
2317
+ const el = scrollState.element();
2318
+ if (el) {
2319
+ const top = computeItemTop(target.index);
2320
+ el.scrollTo({ top, behavior: target.behavior });
2321
+ }
2322
+ });
2323
+ });
2324
+ return {
2325
+ start,
2326
+ end,
2327
+ offsetBefore,
2328
+ offsetAfter,
2329
+ totalSize,
2330
+ placeholdersBefore,
2331
+ placeholdersAfter,
2332
+ isLoading,
2333
+ isRefreshing,
2334
+ isEmpty,
2335
+ skeletonSlots,
2336
+ showSkeleton,
2337
+ firstVisible,
2338
+ lastVisible,
2339
+ visibleCount,
2340
+ anchorTo(index) {
2341
+ const el = scrollState.element();
2342
+ if (!el) {
2343
+ return;
2344
+ }
2345
+ const itemTop = computeItemTop(index);
2346
+ anchorState.set({ index, offsetFromTop: itemTop - el.scrollTop });
2347
+ },
2348
+ releaseAnchor() {
2349
+ anchorState.set(null);
2350
+ },
2351
+ lostFocus,
2352
+ pendingTarget,
2353
+ neededRange,
2354
+ announcement: announcementState.asReadonly(),
2355
+ ariaSetSize,
2356
+ sliced(items) {
2357
+ return computed(() => items().slice(start(), end()));
2358
+ },
2359
+ measure(index, element) {
2360
+ // Grid mode assumes uniform row height — SizeCache writes would break row-based range.
2361
+ if (isGrid) {
2362
+ return;
2363
+ }
2364
+ const height = element.getBoundingClientRect().height;
2365
+ if (height > 0) {
2366
+ sizeCache.set(index, height);
2367
+ }
2368
+ },
2369
+ scrollToIndex(index, behavior = 'auto') {
2370
+ const total = config.totalCount();
2371
+ if (index >= total) {
2372
+ // Deep-link: target not loaded yet — store for later resolution
2373
+ pendingScrollTarget.set({ index, behavior });
2374
+ return;
2375
+ }
2376
+ pendingScrollTarget.set(null);
2377
+ const el = scrollState.element();
2378
+ if (el) {
2379
+ el.scrollTo({ top: computeItemTop(index), behavior });
2380
+ }
2381
+ },
2382
+ reset() {
2383
+ const el = scrollState.element();
2384
+ if (el) {
2385
+ el.scrollTop = 0;
2386
+ }
2387
+ },
2388
+ };
2389
+ }
2390
+
2391
+ // Phase 2: measure.directive.ts — CngxMeasure atom
2392
+ /**
2393
+ * Atom directive that measures the host element's height and reports it
2394
+ * to the recycler via `recycler.measure(index, element)`.
2395
+ *
2396
+ * Uses `ResizeObserver` to detect height changes (e.g. content expansion,
2397
+ * font loading). Cleanup is automatic via `DestroyRef`.
2398
+ *
2399
+ * Also sets `data-cngx-recycle-index` on the host element for focus tracking.
2400
+ *
2401
+ * ```html
2402
+ * @for (item of visibleItems(); track item.id; let i = $index) {
2403
+ * <div [cngxMeasure]="recycler" [cngxMeasureIndex]="recycler.start() + i">
2404
+ * {{ item.content }}
2405
+ * </div>
2406
+ * }
2407
+ * ```
2408
+ */
2409
+ class CngxMeasure {
2410
+ /** The recycler instance to report measurements to. */
2411
+ cngxMeasure = input.required(...(ngDevMode ? [{ debugName: "cngxMeasure" }] : /* istanbul ignore next */ []));
2412
+ /** The absolute index of this item in the full dataset. */
2413
+ cngxMeasureIndex = input.required(...(ngDevMode ? [{ debugName: "cngxMeasureIndex" }] : /* istanbul ignore next */ []));
2414
+ el = inject((ElementRef));
2415
+ constructor() {
2416
+ effect((onCleanup) => {
2417
+ const recycler = this.cngxMeasure();
2418
+ const index = this.cngxMeasureIndex();
2419
+ const element = this.el.nativeElement;
2420
+ // Initial measurement
2421
+ recycler.measure(index, element);
2422
+ // Observe size changes
2423
+ const observer = new ResizeObserver(() => {
2424
+ recycler.measure(index, element);
2425
+ });
2426
+ observer.observe(element);
2427
+ onCleanup(() => {
2428
+ observer.disconnect();
2429
+ });
2430
+ });
2431
+ }
2432
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxMeasure, deps: [], target: i0.ɵɵFactoryTarget.Directive });
2433
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxMeasure, isStandalone: true, selector: "[cngxMeasure]", inputs: { cngxMeasure: { classPropertyName: "cngxMeasure", publicName: "cngxMeasure", isSignal: true, isRequired: true, transformFunction: null }, cngxMeasureIndex: { classPropertyName: "cngxMeasureIndex", publicName: "cngxMeasureIndex", isSignal: true, isRequired: true, transformFunction: null } }, host: { properties: { "attr.data-cngx-recycle-index": "cngxMeasureIndex()" } }, ngImport: i0 });
2434
+ }
2435
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxMeasure, decorators: [{
2436
+ type: Directive,
2437
+ args: [{
2438
+ selector: '[cngxMeasure]',
2439
+ standalone: true,
2440
+ host: {
2441
+ '[attr.data-cngx-recycle-index]': 'cngxMeasureIndex()',
2442
+ },
2443
+ }]
2444
+ }], ctorParameters: () => [], propDecorators: { cngxMeasure: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxMeasure", required: true }] }], cngxMeasureIndex: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxMeasureIndex", required: true }] }] } });
2445
+
2446
+ // Phase 4: virtual-item.directive.ts — CngxVirtualItem A11y atom
2447
+ /**
2448
+ * A11y atom that sets `aria-setsize`, `aria-posinset`, and `data-cngx-recycle-index`
2449
+ * on each rendered virtual item. Replaces manual ARIA boilerplate.
2450
+ *
2451
+ * Also provides `data-cngx-recycle-index` for focus tracking — consumers who
2452
+ * don't use `CngxMeasure` (grid mode, uniform heights) get focus tracking for free.
2453
+ *
2454
+ * Does NOT set `role` — the consumer decides (`listitem`, `option`, `treeitem`, `tab`).
2455
+ *
2456
+ * ```html
2457
+ * @for (item of visibleItems(); track item.id; let i = $index) {
2458
+ * <div role="listitem"
2459
+ * [cngxVirtualItem]="recycler"
2460
+ * [cngxVirtualItemIndex]="recycler.start() + i">
2461
+ * {{ item.name }}
2462
+ * </div>
2463
+ * }
2464
+ * ```
2465
+ */
2466
+ class CngxVirtualItem {
2467
+ /** The recycler instance providing `ariaSetSize`. */
2468
+ cngxVirtualItem = input.required(...(ngDevMode ? [{ debugName: "cngxVirtualItem" }] : /* istanbul ignore next */ []));
2469
+ /** The absolute 0-based index of this item in the full dataset. */
2470
+ cngxVirtualItemIndex = input.required(...(ngDevMode ? [{ debugName: "cngxVirtualItemIndex" }] : /* istanbul ignore next */ []));
2471
+ /** Total item count for `aria-setsize`. */
2472
+ ariaSetSize = computed(() => this.cngxVirtualItem().ariaSetSize(), ...(ngDevMode ? [{ debugName: "ariaSetSize" }] : /* istanbul ignore next */ []));
2473
+ /** 1-based position for `aria-posinset`. */
2474
+ ariaPosinset = computed(() => this.cngxVirtualItemIndex() + 1, ...(ngDevMode ? [{ debugName: "ariaPosinset" }] : /* istanbul ignore next */ []));
2475
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxVirtualItem, deps: [], target: i0.ɵɵFactoryTarget.Directive });
2476
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxVirtualItem, isStandalone: true, selector: "[cngxVirtualItem]", inputs: { cngxVirtualItem: { classPropertyName: "cngxVirtualItem", publicName: "cngxVirtualItem", isSignal: true, isRequired: true, transformFunction: null }, cngxVirtualItemIndex: { classPropertyName: "cngxVirtualItemIndex", publicName: "cngxVirtualItemIndex", isSignal: true, isRequired: true, transformFunction: null } }, host: { properties: { "attr.aria-setsize": "ariaSetSize()", "attr.aria-posinset": "ariaPosinset()", "attr.data-cngx-recycle-index": "cngxVirtualItemIndex()" } }, ngImport: i0 });
2477
+ }
2478
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxVirtualItem, decorators: [{
2479
+ type: Directive,
2480
+ args: [{
2481
+ selector: '[cngxVirtualItem]',
2482
+ standalone: true,
2483
+ host: {
2484
+ '[attr.aria-setsize]': 'ariaSetSize()',
2485
+ '[attr.aria-posinset]': 'ariaPosinset()',
2486
+ '[attr.data-cngx-recycle-index]': 'cngxVirtualItemIndex()',
2487
+ },
2488
+ }]
2489
+ }], propDecorators: { cngxVirtualItem: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxVirtualItem", required: true }] }], cngxVirtualItemIndex: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxVirtualItemIndex", required: true }] }] } });
2490
+
2491
+ // Phase 4: recycler-announcer.component.ts — CngxRecyclerAnnouncer convenience
2492
+ /**
2493
+ * Convenience component that renders the `aria-live="polite"` region
2494
+ * for recycler SR announcements. Eliminates manual boilerplate.
2495
+ *
2496
+ * Uses `display: contents` — no layout impact.
2497
+ *
2498
+ * ```html
2499
+ * <cngx-recycler-announcer [cngxRecyclerAnnouncer]="recycler" />
2500
+ * ```
2501
+ */
2502
+ class CngxRecyclerAnnouncer {
2503
+ /** The recycler instance providing `announcement()`. */
2504
+ recycler = input.required({ ...(ngDevMode ? { debugName: "recycler" } : /* istanbul ignore next */ {}), alias: 'cngxRecyclerAnnouncer' });
2505
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRecyclerAnnouncer, deps: [], target: i0.ɵɵFactoryTarget.Component });
2506
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "21.2.4", type: CngxRecyclerAnnouncer, isStandalone: true, selector: "cngx-recycler-announcer", inputs: { recycler: { classPropertyName: "recycler", publicName: "cngxRecyclerAnnouncer", isSignal: true, isRequired: true, transformFunction: null } }, host: { styleAttribute: "display: contents" }, ngImport: i0, template: `<span aria-live="polite" aria-atomic="true" class="cngx-sr-only">{{
2507
+ recycler().announcement()
2508
+ }}</span>`, isInline: true, changeDetection: i0.ChangeDetectionStrategy.OnPush });
2509
+ }
2510
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRecyclerAnnouncer, decorators: [{
2511
+ type: Component,
2512
+ args: [{
2513
+ selector: 'cngx-recycler-announcer',
2514
+ standalone: true,
2515
+ template: `<span aria-live="polite" aria-atomic="true" class="cngx-sr-only">{{
2516
+ recycler().announcement()
2517
+ }}</span>`,
2518
+ host: { style: 'display: contents' },
2519
+ changeDetection: ChangeDetectionStrategy.OnPush,
2520
+ }]
2521
+ }], propDecorators: { recycler: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxRecyclerAnnouncer", required: true }] }] } });
2522
+
2523
+ // Phase 4: connect-recycler-roving.ts — wires CngxRecycler to CngxRovingTabindex virtual mode
2524
+ /**
2525
+ * Wires a `CngxRecycler` to a `CngxRovingTabindex` in virtual mode.
2526
+ *
2527
+ * When the roving tabindex navigates to an item that is not in the DOM
2528
+ * (out of rendered range), this function scrolls the recycler to that item
2529
+ * and focuses it after rendering.
2530
+ *
2531
+ * Must be called in an injection context (constructor or field initializer)
2532
+ * **on the component that hosts both the recycler's scroll container and the
2533
+ * `CngxRovingTabindex` directive**. The injected `ElementRef` is used to query
2534
+ * `[data-cngx-recycle-index]` — calling from a child component would query the
2535
+ * wrong subtree.
2536
+ *
2537
+ * ```typescript
2538
+ * @Component({
2539
+ * hostDirectives: [
2540
+ * { directive: CngxRovingTabindex, inputs: ['orientation', 'activeIndex', 'virtualCount'] },
2541
+ * ],
2542
+ * })
2543
+ * class MyVirtualList {
2544
+ * private readonly roving = inject(CngxRovingTabindex, { host: true });
2545
+ * readonly recycler = injectRecycler({ ... });
2546
+ *
2547
+ * constructor() {
2548
+ * connectRecyclerToRoving(this.recycler, this.roving);
2549
+ * }
2550
+ * }
2551
+ * ```
2552
+ */
2553
+ function connectRecyclerToRoving(recycler, roving) {
2554
+ const hostEl = inject(ElementRef).nativeElement;
2555
+ // Debounce scrollToIndex via rAF to avoid scroll jitter on rapid keypresses.
2556
+ // Each keypress overwrites pendingFocus — only the latest target is scrolled to.
2557
+ let scrollRafId = null;
2558
+ effect((onCleanup) => {
2559
+ const target = roving.pendingFocus();
2560
+ if (target == null) {
2561
+ return;
2562
+ }
2563
+ if (scrollRafId != null) {
2564
+ cancelAnimationFrame(scrollRafId);
2565
+ }
2566
+ scrollRafId = requestAnimationFrame(() => {
2567
+ scrollRafId = null;
2568
+ // Re-read to get the latest target (rapid keypresses may have updated it).
2569
+ const latest = roving.pendingFocus();
2570
+ if (latest != null) {
2571
+ recycler.scrollToIndex(latest);
2572
+ }
2573
+ });
2574
+ onCleanup(() => {
2575
+ if (scrollRafId != null) {
2576
+ cancelAnimationFrame(scrollRafId);
2577
+ scrollRafId = null;
2578
+ }
2579
+ });
2580
+ });
2581
+ // When the recycler's range changes and the pending target is within range,
2582
+ // wait for the DOM to update (rAF), then query and focus the element.
2583
+ let focusRafId = null;
2584
+ effect((onCleanup) => {
2585
+ const s = recycler.start();
2586
+ const e = recycler.end();
2587
+ const target = untracked(() => roving.pendingFocus());
2588
+ if (target == null || target < s || target >= e) {
2589
+ return;
2590
+ }
2591
+ // Target is within rendered range — DOM will be updated after CD.
2592
+ // Use rAF to wait for Angular's rendering pass to complete.
2593
+ focusRafId = requestAnimationFrame(() => {
2594
+ focusRafId = null;
2595
+ // Re-read pendingFocus in case it changed during the frame (rapid keypresses).
2596
+ const currentTarget = roving.pendingFocus();
2597
+ if (currentTarget == null) {
2598
+ return;
2599
+ }
2600
+ const el = hostEl.querySelector(`[data-cngx-recycle-index="${currentTarget}"]`);
2601
+ if (el instanceof HTMLElement) {
2602
+ el.focus();
2603
+ roving.clearPendingFocus();
2604
+ }
2605
+ });
2606
+ onCleanup(() => {
2607
+ if (focusRafId != null) {
2608
+ cancelAnimationFrame(focusRafId);
2609
+ focusRafId = null;
2610
+ }
2611
+ });
2612
+ });
2613
+ }
2614
+
2615
+ // connect-recycler-active-descendant.ts
2616
+ // Wires CngxRecycler to CngxActiveDescendant virtual mode.
2617
+ /**
2618
+ * Wires a {@link CngxRecycler} to a {@link CngxActiveDescendant} in
2619
+ * virtual mode.
2620
+ *
2621
+ * When the AD directive navigates to an item whose index is not in the
2622
+ * recycler's rendered range, it sets `pendingHighlight` (via the
2623
+ * `virtualCount` path). This helper watches that signal and scrolls
2624
+ * the recycler to the target index; AD's own effect observes the
2625
+ * resulting DOM update and clears the pending state automatically
2626
+ * (see the `pendingHighlightState.set(null)` branch in
2627
+ * `CngxActiveDescendant` after a re-render brings the target into the
2628
+ * rendered range).
2629
+ *
2630
+ * Unlike {@link /projects/common/data/src/recycler/connect-recycler-roving.ts
2631
+ * connectRecyclerToRoving}, we don't re-focus a DOM element after the
2632
+ * scroll — AD doesn't move real focus, it only rebinds
2633
+ * `aria-activedescendant`. Once the target index enters the rendered
2634
+ * range, the `[attr.aria-activedescendant]` binding on the combobox
2635
+ * trigger resolves to the now-present option element for free.
2636
+ *
2637
+ * Must be called in an injection context (typically a component
2638
+ * constructor) on the same component that owns both the recycler
2639
+ * and the AD directive.
2640
+ *
2641
+ * ```typescript
2642
+ * @Component({
2643
+ * hostDirectives: [
2644
+ * { directive: CngxActiveDescendant, inputs: ['items', 'virtualCount'] },
2645
+ * ],
2646
+ * })
2647
+ * class MyVirtualSelect {
2648
+ * private readonly ad = inject(CngxActiveDescendant, { host: true });
2649
+ * readonly recycler = injectRecycler({ ... });
2650
+ *
2651
+ * constructor() {
2652
+ * connectRecyclerToActiveDescendant(this.recycler, this.ad);
2653
+ * }
2654
+ * }
2655
+ * ```
2656
+ */
2657
+ function connectRecyclerToActiveDescendant(recycler, ad) {
2658
+ // rAF-debounced scrollToIndex — rapid keypresses (e.g. ArrowDown held)
2659
+ // otherwise enqueue one scroll call per keystroke. Each new pending
2660
+ // target overwrites the previous rAF; only the latest lands.
2661
+ let scrollRafId = null;
2662
+ effect((onCleanup) => {
2663
+ const target = ad.pendingHighlight();
2664
+ if (target == null) {
2665
+ return;
2666
+ }
2667
+ if (scrollRafId != null) {
2668
+ cancelAnimationFrame(scrollRafId);
2669
+ }
2670
+ scrollRafId = requestAnimationFrame(() => {
2671
+ scrollRafId = null;
2672
+ // Re-read pending target inside the frame — if the user continued
2673
+ // typing / arrow-pressing during the frame, the latest target wins.
2674
+ const latest = untracked(() => ad.pendingHighlight());
2675
+ if (latest != null) {
2676
+ recycler.scrollToIndex(latest);
2677
+ }
2678
+ });
2679
+ onCleanup(() => {
2680
+ if (scrollRafId != null) {
2681
+ cancelAnimationFrame(scrollRafId);
2682
+ scrollRafId = null;
2683
+ }
2684
+ });
2685
+ });
2686
+ }
2687
+
2688
+ /**
2689
+ * Factory for the commit controller.
2690
+ *
2691
+ * Plain function, not a class — matches the rest of the repo
2692
+ * (`createManualState`, `createAsyncState`, `createTransitionTracker`).
2693
+ * See `reference_api_prefix_convention.md`.
2694
+ */
2695
+ function createCommitController() {
2696
+ // Writable state slot — the `state` getter returns the read-only
2697
+ // `CngxAsyncState<T | undefined>` view so consumers can't bypass
2698
+ // the controller to flip status directly.
2699
+ const slot = createManualState();
2700
+ // Monotonic commit id. Incremented on every `begin(...)`. An
2701
+ // outcome callback checks its captured id against the current
2702
+ // counter — if a newer commit has started, the callback is
2703
+ // ignored (supersede).
2704
+ let commitId = 0;
2705
+ // Cancel handle for the runner currently in flight. Replaced on
2706
+ // each `begin(...)` and cleared after the runner settles.
2707
+ let active = null;
2708
+ // Public signal: what the user was trying to commit. Exposed so
2709
+ // the template can render a pending spinner on THAT specific row
2710
+ // and the commit-error context can surface it.
2711
+ const intendedState = signal(undefined, ...(ngDevMode ? [{ debugName: "intendedState" }] : /* istanbul ignore next */ []));
2712
+ return {
2713
+ state: slot,
2714
+ isCommitting: computed(() => slot.isPending()),
2715
+ intendedValue: intendedState.asReadonly(),
2716
+ begin(runner, intended, previous, handlers) {
2717
+ // Supersede: tear down any previous runner. Must run BEFORE
2718
+ // we bump `commitId` — otherwise the previous callback's
2719
+ // supersede-check would pass and fire after all.
2720
+ active?.cancel();
2721
+ const id = ++commitId;
2722
+ intendedState.set(intended);
2723
+ slot.set('pending');
2724
+ active = runner({
2725
+ onSuccess: (committed) => {
2726
+ // Supersede guard. `commitId` advances on every new
2727
+ // `begin`; if our captured id is stale, a newer commit
2728
+ // has taken over.
2729
+ if (id !== commitId) {
2730
+ return;
2731
+ }
2732
+ slot.setSuccess(committed);
2733
+ active = null;
2734
+ handlers.onSuccess(committed);
2735
+ },
2736
+ onError: (err) => {
2737
+ if (id !== commitId) {
2738
+ return;
2739
+ }
2740
+ slot.setError(err);
2741
+ active = null;
2742
+ handlers.onError(err, previous);
2743
+ },
2744
+ });
2745
+ },
2746
+ cancel() {
2747
+ active?.cancel();
2748
+ active = null;
2749
+ // Bump the id so any pending callbacks from the aborted
2750
+ // runner are treated as superseded and do nothing.
2751
+ commitId++;
2752
+ },
2753
+ };
2754
+ }
2755
+
2756
+ /**
2757
+ * DI token carrying the factory that every cngx feature uses to
2758
+ * allocate its commit controller. Default `providedIn: 'root'`
2759
+ * factory returns {@link createCommitController}. Override globally
2760
+ * via app providers or per-component via `viewProviders`.
2761
+ *
2762
+ * Symmetrical to `CNGX_SELECT_COMMIT_CONTROLLER_FACTORY`
2763
+ * (`@cngx/forms/select`); the select-side token's default factory
2764
+ * delegates to this one, so a single override here cascades into
2765
+ * every select variant transparently.
2766
+ *
2767
+ * ```ts
2768
+ * bootstrapApplication(App, {
2769
+ * providers: [
2770
+ * {
2771
+ * provide: CNGX_COMMIT_CONTROLLER_FACTORY,
2772
+ * useValue: <T>() => createRetryingCommitController<T>({ attempts: 3 }),
2773
+ * },
2774
+ * ],
2775
+ * });
2776
+ * ```
2777
+ */
2778
+ const CNGX_COMMIT_CONTROLLER_FACTORY = new InjectionToken('CngxCommitControllerFactory', {
2779
+ providedIn: 'root',
2780
+ factory: () => createCommitController,
2781
+ });
2782
+
2783
+ /**
2784
+ * Single shared bidirectional-sync factory for cngx organisms /
2785
+ * directives that bridge a cngx presenter against a Material parent
2786
+ * (`<mat-tab-group>`, `<mat-stepper>`, etc.).
2787
+ *
2788
+ * Lives at Level 2 in `@cngx/common/data` parallel to
2789
+ * `createCommitController`. Material types never enter the signature —
2790
+ * the caller maps Material-specific events and property accessors to a
2791
+ * host-agnostic shape at the directive boundary.
2792
+ *
2793
+ * Installs:
2794
+ *
2795
+ * 1. A presenter→Material `effect()` that tracks `presenterIndex` and
2796
+ * writes through `writeSelectedIndex`, equality-guarded against
2797
+ * `readSelectedIndex()` to suppress redundant writes. The Material
2798
+ * read+write pair runs inside `untracked()` per
2799
+ * `reference_signal_architecture` rule 2.
2800
+ * 2. A Material→presenter subscription that forwards each
2801
+ * `selectionChange$` emission to `onMaterialSelection`
2802
+ * (equality-guarded against `presenterIndex()` so a Material event
2803
+ * whose value already matches the presenter is dropped — closes
2804
+ * the re-entrancy loop).
2805
+ *
2806
+ * Both sides clean up via `destroyRef`.
2807
+ *
2808
+ * **Pessimistic-commit gate (deliberately absent).** An earlier draft
2809
+ * carried a third option `commitState: CngxAsyncState<unknown>` that
2810
+ * gated the Material write while `commitState.isPending()`. The plan
2811
+ * (`global-material-bridge-and-architecture-hardening-plan` §54)
2812
+ * specified this gate "for the pessimistic flow." Implementation
2813
+ * showed the gate is redundant: cngx commit handlers already keep
2814
+ * `presenter.activeIndex` at the origin during pessimistic-pending,
2815
+ * so the equality guard alone suppresses the Material write.
2816
+ * Conversely, in optimistic mode the presenter advances IMMEDIATELY
2817
+ * (before the commit settles); a `pending`-keyed gate would suppress
2818
+ * that legitimate advance and break the optimistic UX. Dropping the
2819
+ * gate makes both modes work via the simple presenter→Material
2820
+ * mirror — same outcome as the gate version for pessimistic, and the
2821
+ * correct outcome for optimistic.
2822
+ *
2823
+ * **Material-eager-advance reconciliation.** Material's MDC click
2824
+ * handler advances `selectedIndex` synchronously *before* the
2825
+ * Material→presenter subscription forwards the click to
2826
+ * `onMaterialSelection`. When the presenter HOLDS its index
2827
+ * (pessimistic mode + bound `commitAction`, or any future contract
2828
+ * that refuses a select), the presenter→Material `effect()` does
2829
+ * NOT fire — `presenterIndex` did not change — so Material's
2830
+ * eager-advance is never reverted, and the visual diverges from the
2831
+ * cngx semantic state. Closes `tabs-accepted-debt §6` by force-
2832
+ * writing Material back to the presenter's value when the
2833
+ * forwarding callback returns and the values still diverge. Idempotent
2834
+ * with the regular presenter→Material effect (the read-equality guard
2835
+ * at the effect site suppresses a duplicate write when the presenter
2836
+ * later changes to the same value).
2837
+ */
2838
+ function createMaterialBidirectionalSync(opts) {
2839
+ const { presenterIndex, readSelectedIndex, writeSelectedIndex, selectionChange$, onMaterialSelection, injector, destroyRef, } = opts;
2840
+ runInInjectionContext(injector, () => {
2841
+ effect(() => {
2842
+ const desired = presenterIndex();
2843
+ untracked(() => {
2844
+ if (readSelectedIndex() === desired) {
2845
+ return;
2846
+ }
2847
+ writeSelectedIndex(desired);
2848
+ });
2849
+ });
2850
+ });
2851
+ selectionChange$
2852
+ .pipe(takeUntilDestroyed(destroyRef))
2853
+ .subscribe((idx) => {
2854
+ if (presenterIndex() === idx) {
2855
+ return;
2856
+ }
2857
+ onMaterialSelection(idx);
2858
+ // Material-eager-advance reconciliation (tabs-accepted-debt §6).
2859
+ // The forwarding callback above lets the presenter run its
2860
+ // commit-action gate; in pessimistic mode the presenter holds
2861
+ // `activeIndex` at origin instead of advancing. The
2862
+ // presenter→Material effect only fires on signal CHANGE, so a
2863
+ // hold-at-origin leaves Material at the user-clicked target —
2864
+ // out of sync with the cngx semantic state. Detect the
2865
+ // post-callback divergence and force a Material write so the
2866
+ // visual snaps back to the presenter's authoritative index.
2867
+ // Loop-safe: writing `selectedIndex` re-emits `selectionChange$`,
2868
+ // but the early-return guard at the top of this subscriber
2869
+ // (`presenterIndex() === idx`) drops the re-entrant emission.
2870
+ const reconciled = presenterIndex();
2871
+ if (readSelectedIndex() !== reconciled) {
2872
+ writeSelectedIndex(reconciled);
2873
+ }
2874
+ });
2875
+ }
2876
+
2877
+ /**
2878
+ * @module @cngx/common/data
2879
+ */
2880
+
2881
+ /**
2882
+ * Generated bundle index. Do not edit.
2883
+ */
2884
+
2885
+ export { CNGX_COMMIT_CONTROLLER_FACTORY, CNGX_RECYCLER_I18N, CngxAsync, CngxDataSource, CngxFilter, CngxFilterChip, CngxFilterChips, CngxMeasure, CngxMetric, CngxPaginate, CngxRecyclerAnnouncer, CngxSmartDataSource, CngxSort, CngxSortHeader, CngxTrend, CngxVirtualItem, connectRecyclerToActiveDescendant, connectRecyclerToRoving, createAsyncState, createCommitController, createManualState, createMaterialBidirectionalSync, injectAsyncState, injectDataSource, injectRecycler, injectSmartDataSource, provideRecyclerI18n, resolveAsyncView };
2886
+ //# sourceMappingURL=cngx-common-data.mjs.map