@cngx/common 0.1.0-rc.7 → 0.1.0-rc.9

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 (69) hide show
  1. package/card/README.md +2 -1
  2. package/command/README.md +29 -0
  3. package/data/README.md +15 -3
  4. package/dialog/README.md +23 -1
  5. package/fesm2022/cngx-common-a11y.mjs +517 -184
  6. package/fesm2022/cngx-common-a11y.mjs.map +1 -1
  7. package/fesm2022/cngx-common-audio.mjs +62 -17
  8. package/fesm2022/cngx-common-audio.mjs.map +1 -1
  9. package/fesm2022/cngx-common-card.mjs +301 -46
  10. package/fesm2022/cngx-common-card.mjs.map +1 -1
  11. package/fesm2022/cngx-common-chart.mjs +1221 -479
  12. package/fesm2022/cngx-common-chart.mjs.map +1 -1
  13. package/fesm2022/cngx-common-command.mjs +97 -16
  14. package/fesm2022/cngx-common-command.mjs.map +1 -1
  15. package/fesm2022/cngx-common-data.mjs +1496 -499
  16. package/fesm2022/cngx-common-data.mjs.map +1 -1
  17. package/fesm2022/cngx-common-dialog.mjs +236 -61
  18. package/fesm2022/cngx-common-dialog.mjs.map +1 -1
  19. package/fesm2022/cngx-common-display.mjs +364 -93
  20. package/fesm2022/cngx-common-display.mjs.map +1 -1
  21. package/fesm2022/cngx-common-interactive.mjs +2040 -1046
  22. package/fesm2022/cngx-common-interactive.mjs.map +1 -1
  23. package/fesm2022/cngx-common-layout.mjs +955 -125
  24. package/fesm2022/cngx-common-layout.mjs.map +1 -1
  25. package/fesm2022/cngx-common-popover.mjs +1293 -89
  26. package/fesm2022/cngx-common-popover.mjs.map +1 -1
  27. package/fesm2022/cngx-common-stepper.mjs +997 -453
  28. package/fesm2022/cngx-common-stepper.mjs.map +1 -1
  29. package/fesm2022/cngx-common-tabs.mjs +1794 -1265
  30. package/fesm2022/cngx-common-tabs.mjs.map +1 -1
  31. package/fesm2022/cngx-common-timeline.mjs +151 -61
  32. package/fesm2022/cngx-common-timeline.mjs.map +1 -1
  33. package/fesm2022/cngx-common.mjs +1 -1
  34. package/interactive/README.md +15 -4
  35. package/layout/README.md +37 -1
  36. package/package.json +20 -7
  37. package/popover/README.md +58 -2
  38. package/schematics/collection.json +9 -0
  39. package/schematics/ng-add/index.js +9 -0
  40. package/schematics/ng-add/schema.json +91 -0
  41. package/schematics/package.json +3 -0
  42. package/stepper/README.md +11 -8
  43. package/theming/components/cngx-accordion.css +1 -1
  44. package/theming/components/cngx-backdrop.css +12 -0
  45. package/theming/components/cngx-button-toggle.css +29 -3
  46. package/theming/components/cngx-data-grid.css +168 -1
  47. package/theming/components/cngx-dialog.css +13 -0
  48. package/theming/components/cngx-listbox.css +21 -12
  49. package/theming/components/cngx-menu.css +56 -16
  50. package/theming/components/cngx-popover-sheet.css +402 -0
  51. package/theming/components/cngx-popover.css +28 -0
  52. package/theming/components/cngx-recycler-placeholder.css +196 -0
  53. package/theming/components/cngx-ripple.css +1 -1
  54. package/theming/components/cngx-slider.css +32 -1
  55. package/theming/components/cngx-tooltip.css +12 -0
  56. package/timeline/README.md +155 -0
  57. package/types/cngx-common-a11y.d.ts +205 -28
  58. package/types/cngx-common-card.d.ts +201 -17
  59. package/types/cngx-common-chart.d.ts +345 -48
  60. package/types/cngx-common-command.d.ts +50 -10
  61. package/types/cngx-common-data.d.ts +743 -92
  62. package/types/cngx-common-dialog.d.ts +161 -10
  63. package/types/cngx-common-display.d.ts +356 -142
  64. package/types/cngx-common-interactive.d.ts +910 -226
  65. package/types/cngx-common-layout.d.ts +603 -32
  66. package/types/cngx-common-popover.d.ts +612 -49
  67. package/types/cngx-common-stepper.d.ts +526 -237
  68. package/types/cngx-common-tabs.d.ts +358 -75
  69. package/types/cngx-common-timeline.d.ts +108 -22
@@ -1,16 +1,24 @@
1
1
  import * as i0 from '@angular/core';
2
- import { input, signal, afterNextRender, computed, output, Directive, inject, TemplateRef, model, contentChild, DestroyRef, ChangeDetectionStrategy, Component, effect, untracked, InjectionToken, Injector, Injectable, makeEnvironmentProviders, ViewContainerRef, LOCALE_ID, ViewEncapsulation, isDevMode, isSignal, ElementRef, runInInjectionContext } from '@angular/core';
2
+ import { input, signal, afterNextRender, computed, output, Directive, inject, TemplateRef, model, contentChild, effect, untracked, ChangeDetectionStrategy, Component, DestroyRef, InjectionToken, Injector, Injectable, makeEnvironmentProviders, ViewContainerRef, ViewEncapsulation, isSignal, ElementRef, Renderer2, runInInjectionContext } from '@angular/core';
3
3
  import { NgTemplateOutlet, DOCUMENT } from '@angular/common';
4
4
  import { CngxChip } from '@cngx/common/display';
5
5
  import { CngxMultiChipGroup, CngxChipInGroup, CngxSearch } from '@cngx/common/interactive';
6
+ import { CngxRuntimeError, cngxDevWarn, arrayEqual, cngxDevError, clamp } from '@cngx/utils';
6
7
  import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
7
8
  import { Router, ActivatedRoute } from '@angular/router';
8
9
  import { DataSource } from '@angular/cdk/collections';
9
- import { arrayEqual } from '@cngx/utils';
10
- import { buildAsyncStateView, nextUid, createAggregateAsyncState, CNGX_STATEFUL, createLatencyProbe, createVisibilityGate, createTransitionTracker } from '@cngx/core/utils';
11
- import { isObservable, firstValueFrom, defer, tap, filter, map, finalize } from 'rxjs';
10
+ import { foldForMatching, memoize, injectLocale, buildAsyncStateView, CNGX_DEV_DESCRIPTORS, nextUid, createAggregateAsyncState, CNGX_STATEFUL, createLatencyProbe, numberFormatterFor, createOverrideMerge, createVisibilityGate, createTransitionTracker, createMediaQuerySignal, createAnnouncementPhrase } from '@cngx/core/utils';
11
+ import { isObservable, firstValueFrom, defer, tap, finalize, filter, map } from 'rxjs';
12
12
  import { HttpContextToken, HttpContext, HttpEventType, provideHttpClient, withInterceptors } from '@angular/common/http';
13
+ import { formatMessage, createLanguageSection, createSectionBundle } from '@cngx/core/i18n';
14
+ import { observeResize } from '@cngx/common/layout';
13
15
 
16
+ function entryEqual(a, b) {
17
+ return a === b || (!!a && !!b && a.active === b.active && a.direction === b.direction);
18
+ }
19
+ function entriesEqual(a, b) {
20
+ return a === b || (a.length === b.length && a.every((entry, i) => entryEqual(entry, b[i])));
21
+ }
14
22
  /**
15
23
  * Atom directive that tracks sort state (active field + direction).
16
24
  *
@@ -28,6 +36,8 @@ import { HttpContextToken, HttpContext, HttpEventType, provideHttpClient, withIn
28
36
  * adds it as a secondary (tertiary, …) sort key instead of replacing the
29
37
  * primary one. Shift-clicking an active column cycles it asc → desc → removed.
30
38
  * Multi-sort state is always uncontrolled; use `sortsChange` to read it.
39
+ * While a controlled pin is bound, additive clicks degrade to the
40
+ * single-sort cycle.
31
41
  *
32
42
  * Consumer connects this to a table or list via a `computed()` - nothing is
33
43
  * injected automatically.
@@ -73,19 +83,31 @@ class CngxSort {
73
83
  });
74
84
  }
75
85
  /** The active sort column of the primary entry (controlled takes precedence in single-sort mode). */
76
- active = computed(() => this.activeInput() ?? this.sortsState()[0]?.active, ...(ngDevMode ? [{ debugName: "active" }] : /* istanbul ignore next */ []));
86
+ active = computed(() => this.activeInput() ?? this.sorts()[0]?.active, ...(ngDevMode ? [{ debugName: "active" }] : /* istanbul ignore next */ []));
77
87
  /** The active sort direction of the primary entry (controlled takes precedence in single-sort mode). */
78
- direction = computed(() => this.directionInput() ?? this.sortsState()[0]?.direction, ...(ngDevMode ? [{ debugName: "direction" }] : /* istanbul ignore next */ []));
88
+ direction = computed(() => this.directionInput() ?? this.sorts()[0]?.direction, ...(ngDevMode ? [{ debugName: "direction" }] : /* istanbul ignore next */ []));
79
89
  /**
80
90
  * The primary sort state, or `null` when no sort is active.
81
91
  * In multi-sort mode this is the first entry in `sorts`.
82
92
  */
83
- sort = computed(() => this.active() ? { active: this.active(), direction: this.direction() ?? 'asc' } : null, ...(ngDevMode ? [{ debugName: "sort" }] : /* istanbul ignore next */ []));
93
+ sort = computed(() => (this.active() ? { active: this.active(), direction: this.direction() ?? 'asc' } : null), { ...(ngDevMode ? { debugName: "sort" } : /* istanbul ignore next */ {}), equal: entryEqual });
84
94
  /**
85
95
  * All active sort entries in priority order.
86
96
  * Contains at most one entry when additive mode has not been used.
97
+ * In controlled mode the entry is derived from `cngxSortActive` /
98
+ * `cngxSortDirection` (a falsy active key means no sort); headers and
99
+ * data sources read this signal, so the controlled pin drives them too.
87
100
  */
88
- sorts = this.sortsState.asReadonly();
101
+ sorts = computed(() => {
102
+ const controlledActive = this.activeInput();
103
+ if (controlledActive !== undefined) {
104
+ if (!controlledActive) {
105
+ return [];
106
+ }
107
+ return [{ active: controlledActive, direction: this.directionInput() ?? 'asc' }];
108
+ }
109
+ return this.sortsState();
110
+ }, { ...(ngDevMode ? { debugName: "sorts" } : /* istanbul ignore next */ {}), equal: entriesEqual });
89
111
  /** `true` when at least one sort is active. */
90
112
  isActive = computed(() => this.sorts().length > 0, ...(ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []));
91
113
  /** Emitted when the primary sort state changes. Emits `undefined` on clear. */
@@ -106,9 +128,15 @@ class CngxSort {
106
128
  * - Field not in stack → append as asc
107
129
  * - Field in stack as asc → change to desc
108
130
  * - Field in stack as desc → remove from stack
131
+ *
132
+ * With a controlled `cngxSortActive` pin bound, the sort is event-only: the
133
+ * cycle is computed off the effective entry and emitted, the internal state
134
+ * stays untouched (nothing stale surfaces if the pin unbinds later). Since
135
+ * multi-sort is always uncontrolled, an additive call degrades to the
136
+ * non-additive controlled cycle while a pin is bound.
109
137
  */
110
138
  setSort(field, additive = false) {
111
- if (additive) {
139
+ if (additive && this.activeInput() === undefined) {
112
140
  const current = this.sortsState();
113
141
  const idx = current.findIndex((s) => s.active === field);
114
142
  let next;
@@ -126,17 +154,27 @@ class CngxSort {
126
154
  this.sortChange.emit(next[0]);
127
155
  }
128
156
  else {
129
- const current = this.sortsState();
157
+ // Cycle off the effective state: with a controlled pin bound, the first
158
+ // click on the pinned column must continue the cycle (asc -> desc), not
159
+ // restart it from the empty internal state. In that case the write is
160
+ // skipped too - the consumer owns the state, and a shadow copy would
161
+ // surface as stale sort once the pin unbinds.
162
+ const controlled = this.activeInput() !== undefined;
163
+ const current = this.sorts();
130
164
  if (field === current[0]?.active && current[0].direction === 'desc') {
131
165
  // Third click on the active column: cycle desc -> cleared.
132
- this.sortsState.set([]);
166
+ if (!controlled) {
167
+ this.sortsState.set([]);
168
+ }
133
169
  this.sortChange.emit(undefined);
134
170
  this.sortsChange.emit([]);
135
171
  }
136
172
  else {
137
173
  const dir = field === current[0]?.active ? 'desc' : 'asc';
138
174
  const entry = { active: field, direction: dir };
139
- this.sortsState.set([entry]);
175
+ if (!controlled) {
176
+ this.sortsState.set([entry]);
177
+ }
140
178
  this.sortChange.emit(entry);
141
179
  this.sortsChange.emit([entry]);
142
180
  }
@@ -454,17 +492,19 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
454
492
  * is intentionally out of scope. Consumers needing a single-select
455
493
  * filter wire `<cngx-chip-group>` to a custom predicate themselves.
456
494
  *
457
- * **Sync contract - derivation, not effect.** The bridge calls
458
- * `filterRef.addPredicate(filterKey, predicateFn)` EXACTLY ONCE
459
- * during mount (in `afterNextRender`, because `input.required()`
460
- * cannot be read from the constructor body). `predicateFn` is a
495
+ * **Sync contract - derivation, not effect.** `predicateFn` is a
461
496
  * closure that reads `this.selectedValues()` and
462
- * `this.optionValueFn()` on every invocation. Because
497
+ * `this.optionValue()` on every invocation. Because
463
498
  * `CngxFilter.predicate` is itself a `computed()` consumed by
464
499
  * downstream filtered lists, each item-evaluation flows through
465
500
  * `selectedValues()` in the consumer's reactive context - chip
466
501
  * toggles propagate without any `effect()` writing back into the
467
- * filter.
502
+ * filter. Registration itself is reactive: a binding effect tracks
503
+ * `filterRef`/`filterKey` (a rebind moves the registration), and an
504
+ * eviction watcher re-registers the key after `filter.clear()` wiped
505
+ * the stack, so visible chip selection and predicate stack cannot
506
+ * diverge. Selections whose option vanished from `[options]` are
507
+ * pruned - a removed option never keeps filtering invisibly.
468
508
  *
469
509
  * **Empty-selection semantics.** When `selectedValues()` is `[]`,
470
510
  * the closure returns `true` for every item - equivalent to "no
@@ -474,13 +514,10 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
474
514
  * re-registering on every empty/non-empty boundary, and keeps the
475
515
  * predicate-stack stable (no `predicatesChange` emission churn).
476
516
  *
477
- * **Teardown.** `DestroyRef.onDestroy` calls `removePredicate` only
478
- * when registration actually happened (`registered` flag) - guards
479
- * against the case where the component is destroyed before
480
- * `afterNextRender` fires. The destroy callback reads `filterRef`
481
- * and `filterKey` lazily so a consumer that re-binds these between
482
- * mount and unmount cleans the latest binding (per
483
- * `reference_signal_architecture` memory-hygiene rule).
517
+ * **Teardown.** The binding effect's cleanup removes the key only
518
+ * while it still maps to this strip's own `predicateFn` (identity
519
+ * guard) - destroying one of two strips that share a key never
520
+ * detaches the live sibling's registration.
484
521
  *
485
522
  * **Visible caption.** The required `label` renders as a
486
523
  * `.cngx-filter-chips__label` caption above the strip so a sighted user
@@ -527,6 +564,15 @@ class CngxFilterChips {
527
564
  optionLabel = input.required(...(ngDevMode ? [{ debugName: "optionLabel" }] : /* istanbul ignore next */ []));
528
565
  optionValue = input.required(...(ngDevMode ? [{ debugName: "optionValue" }] : /* istanbul ignore next */ []));
529
566
  filterRef = input.required(...(ngDevMode ? [{ debugName: "filterRef" }] : /* istanbul ignore next */ []));
567
+ /**
568
+ * Extracts the comparable value from a filtered list item, when the list
569
+ * is shaped unlike the chip options: role options `{ id, label }` filtering
570
+ * an employee list by `employee.roleId`. Return an array for an item that
571
+ * carries several values (`employee.tags`); it matches when any of them is
572
+ * selected. Unbound, the predicate applies `optionValue` to the list items,
573
+ * which fits a list shaped like the options.
574
+ */
575
+ itemValue = input(undefined, ...(ngDevMode ? [{ debugName: "itemValue" }] : /* istanbul ignore next */ []));
530
576
  filterKey = input.required(...(ngDevMode ? [{ debugName: "filterKey" }] : /* istanbul ignore next */ []));
531
577
  state = input(undefined, ...(ngDevMode ? [{ debugName: "state" }] : /* istanbul ignore next */ []));
532
578
  /**
@@ -563,14 +609,14 @@ class CngxFilterChips {
563
609
  /**
564
610
  * Build the slot context for a given chip option. `optionValue` is
565
611
  * invoked here per option for the chip rendering pass; the predicate
566
- * closure invokes it again per LIST item for membership filtering.
567
- * Both invocations are necessary because option items (the chip
568
- * pool) and filtered list items (the consumer's filtered data) are
569
- * separate data paths - they happen to share a shape under the
570
- * Phase-5 single-shape limitation, but the bridge cannot memoise
571
- * across the two paths without conflating them. Consumers should
572
- * keep `optionValue` cheap (typically a property lookup); a future
573
- * `[itemValue]` input will separate the two extractors.
612
+ * closure invokes it again per LIST item for membership filtering
613
+ * while `[itemValue]` is unbound. Both invocations are necessary
614
+ * because option items (the chip pool) and filtered list items (the
615
+ * consumer's filtered data) are separate data paths - they share a
616
+ * shape only when `[itemValue]` is unbound, and the bridge cannot
617
+ * memoise across the two paths without conflating them. Consumers
618
+ * should keep `optionValue` cheap (typically a property lookup); bind
619
+ * `[itemValue]` when the list is shaped unlike the options.
574
620
  */
575
621
  chipContext = (option) => {
576
622
  const value = this.optionValue()(option);
@@ -589,7 +635,6 @@ class CngxFilterChips {
589
635
  * `CngxFilter.predicate`.
590
636
  */
591
637
  selectedValues = model([], ...(ngDevMode ? [{ debugName: "selectedValues" }] : /* istanbul ignore next */ []));
592
- registered = false;
593
638
  constructor() {
594
639
  const predicateFn = (item) => {
595
640
  const values = this.selectedValues();
@@ -597,22 +642,65 @@ class CngxFilterChips {
597
642
  return true;
598
643
  }
599
644
  const extract = this.keyFn();
600
- const key = extract(this.optionValue()(item));
601
- return values.some((v) => Object.is(extract(v), key));
645
+ const keys = this.itemKeys(item, extract);
646
+ return values.some((v) => {
647
+ const selected = extract(v);
648
+ return keys.some((key) => Object.is(selected, key));
649
+ });
602
650
  };
603
- afterNextRender(() => {
604
- this.filterRef().addPredicate(this.filterKey(), predicateFn);
605
- this.registered = true;
651
+ // Binding effect: tracks only filterRef/filterKey, so a rebind moves the
652
+ // registration. Cleanup is identity-guarded - it removes the key only
653
+ // while it still maps to THIS strip's predicate, so tearing down one of
654
+ // two strips sharing a key never detaches the live sibling.
655
+ effect((onCleanup) => {
656
+ const filter = this.filterRef();
657
+ const key = this.filterKey();
658
+ untracked(() => filter.addPredicate(key, predicateFn));
659
+ onCleanup(() => {
660
+ if (untracked(filter.predicates).get(key) === predicateFn) {
661
+ untracked(() => filter.removePredicate(key));
662
+ }
663
+ });
606
664
  });
607
- inject(DestroyRef).onDestroy(() => {
608
- if (!this.registered) {
609
- return;
665
+ // Eviction watcher: filter.clear() wipes the whole predicate map while
666
+ // the chips stay visually selected. Re-register when our key is missing
667
+ // so UI and predicate stack cannot diverge. A foreign same-key
668
+ // registration is present, not missing - it is left alone (no fighting,
669
+ // no loop).
670
+ effect(() => {
671
+ const filter = this.filterRef();
672
+ const key = this.filterKey();
673
+ if (!filter.predicates().has(key)) {
674
+ untracked(() => filter.addPredicate(key, predicateFn));
675
+ }
676
+ });
677
+ // Prune selections whose option vanished from [options]: without this a
678
+ // removed option keeps filtering invisibly (no chip renders for it).
679
+ effect(() => {
680
+ const extract = this.keyFn();
681
+ const valid = new Set(this.options().map((o) => extract(this.optionValue()(o))));
682
+ const current = untracked(this.selectedValues);
683
+ const pruned = current.filter((v) => valid.has(extract(v)));
684
+ if (pruned.length !== current.length) {
685
+ untracked(() => this.selectedValues.set(pruned));
610
686
  }
611
- this.filterRef().removePredicate(this.filterKey());
612
687
  });
613
688
  }
689
+ itemKeys(item, extract) {
690
+ const itemValue = this.itemValue();
691
+ if (!itemValue) {
692
+ // Without [itemValue] the list is shaped like the options (the
693
+ // `TListItem = TItem` default), and an array-valued option stays one value.
694
+ const optionValue = this.optionValue();
695
+ return [extract(optionValue(item))];
696
+ }
697
+ const values = itemValue(item);
698
+ return Array.isArray(values)
699
+ ? values.map(extract)
700
+ : [extract(values)];
701
+ }
614
702
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFilterChips, deps: [], target: i0.ɵɵFactoryTarget.Component });
615
- 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" }, host: { properties: { "class.cngx-filter-chips--vertical": "orientation() === \"vertical\"" }, classAttribute: "cngx-filter-chips" }, queries: [{ propertyName: "chipTemplate", first: true, predicate: (CngxFilterChip), descendants: true, isSignal: true }], exportAs: ["cngxFilterChips"], ngImport: i0, template: `
703
+ 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 }, itemValue: { classPropertyName: "itemValue", publicName: "itemValue", isSignal: true, isRequired: false, 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" }, host: { properties: { "class.cngx-filter-chips--vertical": "orientation() === \"vertical\"" }, classAttribute: "cngx-filter-chips" }, queries: [{ propertyName: "chipTemplate", first: true, predicate: (CngxFilterChip), descendants: true, isSignal: true }], exportAs: ["cngxFilterChips"], ngImport: i0, template: `
616
704
  <span class="cngx-filter-chips__label" aria-hidden="true">{{ label() }}</span>
617
705
  <cngx-multi-chip-group
618
706
  [label]="label()"
@@ -635,7 +723,7 @@ class CngxFilterChips {
635
723
  </cngx-chip>
636
724
  }
637
725
  </cngx-multi-chip-group>
638
- `, isInline: true, styles: [":host{display:flex;flex-direction:row;align-items:center;--cngx-filter-chips-gap: var(--cngx-space-sm, 8px);gap:var(--cngx-filter-chips-gap, 8px)}:host(.cngx-filter-chips--vertical){flex-direction:column;align-items:flex-start}.cngx-filter-chips__label{color:var(--cngx-filter-chips-label-color, inherit);font-size:var(--cngx-filter-chips-label-font-size, .8125rem);font-weight:var(--cngx-filter-chips-label-font-weight, 600)}\n"], 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 });
726
+ `, isInline: true, styles: [":host{display:flex;flex-direction:row;align-items:center;--cngx-filter-chips-gap: var(--cngx-space-sm, 8px);gap:var(--cngx-filter-chips-gap, 8px)}:host(.cngx-filter-chips--vertical){flex-direction:column;align-items:flex-start}.cngx-filter-chips__label{color:var(--cngx-filter-chips-label-color, inherit);font-size:var(--cngx-filter-chips-label-font-size, .8125rem);font-weight:var(--cngx-filter-chips-label-font-weight, 600)}\n"], 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", "labelledBy", "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 });
639
727
  }
640
728
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFilterChips, decorators: [{
641
729
  type: Component,
@@ -666,7 +754,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
666
754
  }
667
755
  </cngx-multi-chip-group>
668
756
  `, styles: [":host{display:flex;flex-direction:row;align-items:center;--cngx-filter-chips-gap: var(--cngx-space-sm, 8px);gap:var(--cngx-filter-chips-gap, 8px)}:host(.cngx-filter-chips--vertical){flex-direction:column;align-items:flex-start}.cngx-filter-chips__label{color:var(--cngx-filter-chips-label-color, inherit);font-size:var(--cngx-filter-chips-label-font-size, .8125rem);font-weight:var(--cngx-filter-chips-label-font-weight, 600)}\n"] }]
669
- }], 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"] }] } });
757
+ }], 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 }] }], itemValue: [{ type: i0.Input, args: [{ isSignal: true, alias: "itemValue", required: false }] }], 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"] }] } });
670
758
 
671
759
  /**
672
760
  * Atom directive that tracks pagination state (current page index and page size).
@@ -754,6 +842,22 @@ class CngxPaginate {
754
842
  * stops a fresh-array identity from cascading downstream.
755
843
  */
756
844
  cumulativeRange = computed(() => [0, (this.pageIndex() + 1) * this.pageSize()], { ...(ngDevMode ? { debugName: "cumulativeRange" } : /* istanbul ignore next */ {}), equal: (a, b) => a[0] === b[0] && a[1] === b[1] });
845
+ /**
846
+ * `range()` with both bounds capped at `total` - the honest in-bounds window
847
+ * for readouts and announcements. `range()`'s upper bound is
848
+ * `start + pageSize`, so a partial final page overshoots `total`; this caps
849
+ * it (and yields `[0, 0]` while the list is empty). The capped end doubles as
850
+ * the cumulative reveal count for load-more consumers: `range()[1]` and
851
+ * `cumulativeRange()[1]` are the same number (`(pageIndex + 1) * pageSize`),
852
+ * so `clampedRange()[1]` is "items shown so far" in both replace and append
853
+ * modes. The explicit tuple `equal` stops a fresh-array identity from
854
+ * cascading downstream.
855
+ */
856
+ clampedRange = computed(() => {
857
+ const total = this.total();
858
+ const [start, end] = this.range();
859
+ return [Math.min(start, total), Math.min(end, total)];
860
+ }, { ...(ngDevMode ? { debugName: "clampedRange" } : /* istanbul ignore next */ {}), equal: (a, b) => a[0] === b[0] && a[1] === b[1] });
757
861
  /** Emitted when the page index changes. */
758
862
  pageChange = output();
759
863
  /** Emitted when the page size changes. */
@@ -813,6 +917,24 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
813
917
  }]
814
918
  }], 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"] }] } });
815
919
 
920
+ /**
921
+ * Inject the surrounding {@link CngxPaginate} from a paginate add-on
922
+ * directive. Throws a `CngxRuntimeError` with code `CNGX1063` when no
923
+ * `[cngxPaginate]` is on the element or above it, in development and
924
+ * production alike. `selector` names the add-on in the development message.
925
+ *
926
+ * @internal
927
+ */
928
+ function injectPaginate(selector) {
929
+ const paginate = inject(CngxPaginate, { optional: true });
930
+ if (!paginate) {
931
+ throw new CngxRuntimeError('CNGX1063', typeof ngDevMode !== 'undefined' &&
932
+ ngDevMode &&
933
+ `[${selector}] must be placed on or inside an element with [cngxPaginate], such as <cngx-paginator>.`);
934
+ }
935
+ return paginate;
936
+ }
937
+
816
938
  /**
817
939
  * Wires the reset-on-change behaviour onto a {@link CngxPaginate} brain: when
818
940
  * `key()` changes (after the initial run) the paginator jumps to the first
@@ -866,7 +988,7 @@ function connectPaginateResetOn(paginate, key) {
866
988
  * @relatedTo CngxPaginate, CngxPaginator, CngxMatPaginator
867
989
  */
868
990
  class CngxPaginateResetOn {
869
- paginate = inject(CngxPaginate);
991
+ paginate = injectPaginate('cngxPaginateResetOn');
870
992
  /** The reset key. A change (after mount) jumps the paginator to page 0. */
871
993
  key = input(undefined, { ...(ngDevMode ? { debugName: "key" } : /* istanbul ignore next */ {}), alias: 'cngxPaginateResetOn' });
872
994
  constructor() {
@@ -893,7 +1015,10 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
893
1015
  * brain's `pageIndex()` stays pinned to the input until the consumer feeds it
894
1016
  * back;
895
1017
  * - an `effect()` reads the effective `pageIndex()` / `pageSize()` and covers a
896
- * `total`-shrink clamp the nav-only output misses.
1018
+ * `total`-shrink clamp the nav-only output misses. The index half of the
1019
+ * clamp path is suppressed while the brain is busy or `total` is 0, so a
1020
+ * transient total drop during a refetch never persists a page-0 clamp into a
1021
+ * controlled consumer; a clamp that survives the settle emits then.
897
1022
  *
898
1023
  * The shared guard makes a value one path already emitted a no-op on the other,
899
1024
  * so each change emits exactly once. Seeded with the current effective values,
@@ -938,16 +1063,27 @@ function connectPaginateEmit(paginate, handlers) {
938
1063
  // nav path already emitted is a no-op here, so each change emits once.
939
1064
  effect(() => {
940
1065
  const index = paginate.pageIndex();
1066
+ // A transient total drop (a refetch clearing [total] to 0) clamps the
1067
+ // effective index to 0; forwarding that would persist the clamp into a
1068
+ // controlled consumer's two-way state and pin page 0 after the data
1069
+ // returns, where the brain's read-time clamp alone would recover. Both
1070
+ // gates are tracked reads, so a clamp that survives the settle (a real
1071
+ // total shrink) emits when busy flips off / total refills.
1072
+ if (paginate.isBusy() || paginate.total() === 0) {
1073
+ return;
1074
+ }
941
1075
  if (index !== lastIndex) {
942
1076
  lastIndex = index;
943
- handlers.onIndex(index);
1077
+ // Consumer handlers run synchronously - keep their signal reads/writes
1078
+ // out of this effect's dependency graph.
1079
+ untracked(() => handlers.onIndex(index));
944
1080
  }
945
1081
  });
946
1082
  effect(() => {
947
1083
  const size = paginate.pageSize();
948
1084
  if (size !== lastSize) {
949
1085
  lastSize = size;
950
- handlers.onSize(size);
1086
+ untracked(() => handlers.onSize(size));
951
1087
  }
952
1088
  });
953
1089
  }
@@ -979,7 +1115,7 @@ function connectPaginateEmit(paginate, handlers) {
979
1115
  * <example-url>http://localhost:4200/#/ui/paginator/paginator-behaviors/url-synced-paging</example-url>
980
1116
  */
981
1117
  class CngxPaginateRouting {
982
- paginate = inject(CngxPaginate);
1118
+ paginate = injectPaginate('cngxPaginateRouting');
983
1119
  router = inject(Router, { optional: true });
984
1120
  route = inject(ActivatedRoute, { optional: true });
985
1121
  destroyRef = inject(DestroyRef);
@@ -987,30 +1123,60 @@ class CngxPaginateRouting {
987
1123
  pageParam = input('page', { ...(ngDevMode ? { debugName: "pageParam" } : /* istanbul ignore next */ {}), alias: 'cngxPaginatePageParam' });
988
1124
  /** Query-param name for the page size. */
989
1125
  sizeParam = input('pageSize', { ...(ngDevMode ? { debugName: "sizeParam" } : /* istanbul ignore next */ {}), alias: 'cngxPaginateSizeParam' });
990
- // Set while applying a URL change to the brain, so the brain -> URL effect
991
- // does not bounce the same value straight back as a redundant navigation.
1126
+ // Set synchronously around brain writes driven by the URL, so the
1127
+ // pageChange subscription below can tell a URL-driven change from a user
1128
+ // navigation (setPage/setPageSize emit synchronously).
992
1129
  applyingFromUrl = false;
1130
+ // A deep-linked page index the brain could not represent yet: setPage
1131
+ // clamps against totalPages (1 while the default total=0 is still in
1132
+ // effect) and no-ops entirely while the bound async state is busy. The raw
1133
+ // index is parked here and re-applied once total/busy settle; while it is
1134
+ // parked, the brain -> URL effect leaves the URL alone so the deep link
1135
+ // survives until the data lands. `size` is null once the size half has
1136
+ // been applied.
1137
+ pendingUrl = signal(null, { ...(ngDevMode ? { debugName: "pendingUrl" } : /* istanbul ignore next */ {}), equal: (a, b) => a?.index === b?.index && a?.size === b?.size });
993
1138
  constructor() {
994
1139
  const router = this.router;
995
1140
  const route = this.route;
996
1141
  if (!router || !route) {
997
1142
  if (typeof ngDevMode !== 'undefined' && ngDevMode) {
998
- console.warn('[cngxPaginateRouting]: no Router available - directive is a no-op. ' +
1143
+ cngxDevWarn('CNGX1031', '[cngxPaginateRouting] no Router / ActivatedRoute available - the URL sync is a no-op. ' +
999
1144
  'Provide @angular/router via provideRouter(...) to enable URL-synced pagination.');
1000
1145
  }
1001
1146
  return;
1002
1147
  }
1148
+ // A user navigation supersedes a still-parked deep link. The brain is
1149
+ // resolved through the element injector and may live on an ancestor, so
1150
+ // the subscription is torn down explicitly instead of relying on shared
1151
+ // lifecycles.
1152
+ const pageChangeSub = this.paginate.pageChange.subscribe(() => {
1153
+ if (!this.applyingFromUrl) {
1154
+ this.pendingUrl.set(null);
1155
+ }
1156
+ });
1157
+ this.destroyRef.onDestroy(() => pageChangeSub.unsubscribe());
1003
1158
  // brain -> URL. Tracks the effective page / size; merges into the existing
1004
1159
  // query string and replaces history so paging does not stack back entries.
1005
1160
  // The param-name inputs are read lazily inside untracked, so a late-bound
1006
- // alias is already set by the time the first navigation fires.
1161
+ // alias is already set by the time the first navigation fires. Skipped
1162
+ // while a deep link is parked and when the URL already carries the values
1163
+ // (the echo after a URL -> brain apply must not renavigate).
1007
1164
  effect(() => {
1008
1165
  const page = this.paginate.pageIndex() + 1;
1009
1166
  const size = this.paginate.pageSize();
1010
- if (this.applyingFromUrl) {
1167
+ if (this.pendingUrl() !== null) {
1011
1168
  return;
1012
1169
  }
1013
1170
  untracked(() => {
1171
+ // Snapshot read while router.navigate is async: a still-pending
1172
+ // navigation can slip past this check and renavigate - benign under
1173
+ // replaceUrl + merge (same params, no history entry).
1174
+ const params = route.snapshot.queryParamMap;
1175
+ const samePage = Number(params.get(this.pageParam())) === page;
1176
+ const sameSize = Number(params.get(this.sizeParam())) === size;
1177
+ if (samePage && sameSize) {
1178
+ return;
1179
+ }
1014
1180
  void router.navigate([], {
1015
1181
  relativeTo: route,
1016
1182
  queryParams: { [this.pageParam()]: page, [this.sizeParam()]: size },
@@ -1019,6 +1185,20 @@ class CngxPaginateRouting {
1019
1185
  });
1020
1186
  });
1021
1187
  });
1188
+ // Re-apply a parked deep link whenever the clamp inputs move (total
1189
+ // landed, busy released). Only those two triggers are tracked; the parked
1190
+ // value is read untracked, so the re-park write inside applyFromUrl can
1191
+ // never feed back into this effect's own dependency graph.
1192
+ effect(() => {
1193
+ this.paginate.totalPages();
1194
+ this.paginate.isBusy();
1195
+ untracked(() => {
1196
+ const pending = this.pendingUrl();
1197
+ if (pending !== null) {
1198
+ this.applyFromUrl(pending.index, pending.size);
1199
+ }
1200
+ });
1201
+ });
1022
1202
  }
1023
1203
  ngOnInit() {
1024
1204
  const route = this.route;
@@ -1030,22 +1210,41 @@ class CngxPaginateRouting {
1030
1210
  // deep-linked page / size therefore lands before first paint). The
1031
1211
  // subscription stays live for back / forward navigation.
1032
1212
  route.queryParamMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
1033
- const size = Number(params.get(this.sizeParam()));
1034
- const page = Number(params.get(this.pageParam()));
1035
- this.applyingFromUrl = true;
1036
- try {
1037
- if (Number.isFinite(size) && size > 0 && size !== this.paginate.pageSize()) {
1038
- this.paginate.setPageSize(size, false);
1039
- }
1040
- const index = (Number.isFinite(page) && page > 0 ? page : 1) - 1;
1041
- if (index !== this.paginate.pageIndex()) {
1042
- this.paginate.setPage(index);
1043
- }
1213
+ const rawSize = Number(params.get(this.sizeParam()));
1214
+ const rawPage = Number(params.get(this.pageParam()));
1215
+ const size = Number.isFinite(rawSize) && rawSize > 0 ? rawSize : null;
1216
+ const index = (Number.isFinite(rawPage) && rawPage > 0 ? rawPage : 1) - 1;
1217
+ this.applyFromUrl(index, size);
1218
+ });
1219
+ }
1220
+ applyFromUrl(index, size) {
1221
+ const paginate = this.paginate;
1222
+ if (paginate.isBusy()) {
1223
+ // Both setters no-op while busy - park the whole request and retry.
1224
+ this.pendingUrl.set({ index, size });
1225
+ return;
1226
+ }
1227
+ this.applyingFromUrl = true;
1228
+ try {
1229
+ if (size !== null && size !== paginate.pageSize()) {
1230
+ paginate.setPageSize(size, false);
1044
1231
  }
1045
- finally {
1046
- this.applyingFromUrl = false;
1232
+ if (index !== paginate.pageIndex()) {
1233
+ paginate.setPage(index);
1047
1234
  }
1048
- });
1235
+ }
1236
+ finally {
1237
+ this.applyingFromUrl = false;
1238
+ }
1239
+ if (paginate.pageIndex() === index || paginate.total() > 0) {
1240
+ // Landed, or clamped against a real total - the deep link is resolved.
1241
+ this.pendingUrl.set(null);
1242
+ }
1243
+ else {
1244
+ // Clamped against the default total=0: the real total has not arrived
1245
+ // yet, so keep the raw index parked (size, if any, is applied already).
1246
+ this.pendingUrl.set({ index, size: null });
1247
+ }
1049
1248
  }
1050
1249
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxPaginateRouting, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1051
1250
  static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxPaginateRouting, isStandalone: true, selector: "[cngxPaginateRouting]", inputs: { pageParam: { classPropertyName: "pageParam", publicName: "cngxPaginatePageParam", isSignal: true, isRequired: false, transformFunction: null }, sizeParam: { classPropertyName: "sizeParam", publicName: "cngxPaginateSizeParam", isSignal: true, isRequired: false, transformFunction: null } }, exportAs: ["cngxPaginateRouting"], ngImport: i0 });
@@ -1231,22 +1430,61 @@ function injectDataSource(data) {
1231
1430
  return new CngxDataSource(data);
1232
1431
  }
1233
1432
 
1234
- function defaultSearchFn(item, term) {
1235
- const lower = term.toLowerCase();
1236
- return Object.values(item).some((v) => v === null || v === undefined || typeof v === 'object'
1237
- ? false
1238
- : String(v)
1239
- .toLowerCase()
1240
- .includes(lower));
1433
+ /**
1434
+ * @internal Folded field values per row object. Keyed by the row, so it
1435
+ * cannot thrash and is collected with the rows; the raw strings are compared
1436
+ * on every read, so a row mutated in place is folded again.
1437
+ */
1438
+ const FOLDED_FIELDS = new WeakMap();
1439
+ function rawFieldsOf(item) {
1440
+ const raw = [];
1441
+ for (const v of Object.values(item)) {
1442
+ if (v !== null && v !== undefined && typeof v !== 'object') {
1443
+ raw.push(String(v));
1444
+ }
1445
+ }
1446
+ return raw;
1447
+ }
1448
+ function foldedFieldsOf(item, locale) {
1449
+ const raw = rawFieldsOf(item);
1450
+ const cached = FOLDED_FIELDS.get(item);
1451
+ if (cached?.locale === locale && arrayEqual(cached.raw, raw)) {
1452
+ return cached.folded;
1453
+ }
1454
+ const folded = raw.map((value) => foldForMatching(value, locale));
1455
+ FOLDED_FIELDS.set(item, { locale, raw, folded });
1456
+ return folded;
1241
1457
  }
1242
- function defaultSortFn(a, b, field, dir) {
1458
+ /**
1459
+ * @internal The default search: primitive field values, case and accents
1460
+ * ignored in `locale`. The term is folded once per term, each row's field
1461
+ * values once per row and locale, not on every keystroke.
1462
+ */
1463
+ const defaultSearchFnFor = memoize((locale) => {
1464
+ let lastTerm = '';
1465
+ let lastFolded = '';
1466
+ return (item, term) => {
1467
+ if (term !== lastTerm) {
1468
+ lastTerm = term;
1469
+ lastFolded = foldForMatching(term, locale);
1470
+ }
1471
+ if (typeof item !== 'object' || item === null) {
1472
+ return foldForMatching(String(item), locale).includes(lastFolded);
1473
+ }
1474
+ return foldedFieldsOf(item, locale).some((value) => value.includes(lastFolded));
1475
+ };
1476
+ }, { cacheLimit: 8 });
1477
+ const collatorFor = memoize((locale) => new Intl.Collator(locale, { numeric: true, sensitivity: 'base' }), { cacheLimit: 32 });
1478
+ /** @internal The default comparator: field values as text, collated in `locale`. */
1479
+ function defaultSortFnFor(locale) {
1480
+ const collator = collatorFor(locale);
1243
1481
  const toStr = (v) => v === null || v === undefined || typeof v === 'object'
1244
1482
  ? ''
1245
1483
  : String(v);
1246
- const av = toStr(a[field]);
1247
- const bv = toStr(b[field]);
1248
- const cmp = av.localeCompare(bv, undefined, { numeric: true, sensitivity: 'base' });
1249
- return dir === 'asc' ? cmp : -cmp;
1484
+ return (a, b, field, dir) => {
1485
+ const cmp = collator.compare(toStr(a[field]), toStr(b[field]));
1486
+ return dir === 'asc' ? cmp : -cmp;
1487
+ };
1250
1488
  }
1251
1489
  function isAsyncState(source) {
1252
1490
  return 'status' in source && 'data' in source && 'isFirstLoad' in source;
@@ -1306,6 +1544,7 @@ class CngxSmartDataSource extends DataSource {
1306
1544
  // matching options thunk instead.
1307
1545
  injectedSearch = inject(CngxSearch, { optional: true });
1308
1546
  injectedPaginate = inject(CngxPaginate, { optional: true });
1547
+ locale = injectLocale();
1309
1548
  /**
1310
1549
  * Items after filter and search are applied, before sort and pagination.
1311
1550
  * Use `filteredCount()` to get the pre-pagination count for paginator `total`.
@@ -1358,7 +1597,7 @@ class CngxSmartDataSource extends DataSource {
1358
1597
  const search = this.options?.search?.() ?? this.injectedSearch;
1359
1598
  const predicate = filter?.predicate();
1360
1599
  const term = search?.term();
1361
- const searchFn = this.options?.searchFn ?? (defaultSearchFn);
1600
+ const searchFn = this.options?.searchFn ?? defaultSearchFnFor(this.locale());
1362
1601
  // Pipeline: raw → filter → search. Cast required: CngxFilter injected as unknown.
1363
1602
  return data()
1364
1603
  .filter((v) => !predicate || predicate(v))
@@ -1375,7 +1614,7 @@ class CngxSmartDataSource extends DataSource {
1375
1614
  this.processed = computed(() => {
1376
1615
  const sort = this.options?.sort?.() ?? this.injectedSort;
1377
1616
  const sorts = sort?.sorts() ?? [];
1378
- const sortFn = this.options?.sortFn ?? (defaultSortFn);
1617
+ const sortFn = this.options?.sortFn ?? defaultSortFnFor(this.locale());
1379
1618
  const sorted = sorts.length > 0
1380
1619
  ? [...this.filtered()].sort((a, b) => sorts.reduce((cmp, { active, direction }) => cmp || sortFn(a, b, active, direction), 0))
1381
1620
  : this.filtered();
@@ -1444,14 +1683,20 @@ function createManualState() {
1444
1683
  data: dataState.asReadonly(),
1445
1684
  error: errorState.asReadonly(),
1446
1685
  progress: progressState.asReadonly(),
1447
- isFirstLoad: computed(() => !hadSuccess()),
1686
+ isFirstLoad: computed(() => !hadSuccess(), typeof ngDevMode !== 'undefined' && ngDevMode
1687
+ ? { debugName: 'manualState.isFirstLoad' }
1688
+ : undefined),
1448
1689
  lastUpdated: lastUpdatedState.asReadonly(),
1449
1690
  });
1450
- return {
1691
+ const state = {
1451
1692
  ...view,
1452
1693
  set(newStatus) {
1453
1694
  statusState.set(newStatus);
1454
1695
  if (newStatus === 'success') {
1696
+ // Parity with setSuccess: a success transition must not leave stale
1697
+ // error/progress residue behind.
1698
+ errorState.set(undefined);
1699
+ progressState.set(undefined);
1455
1700
  hadSuccess.set(true);
1456
1701
  lastUpdatedState.set(new Date());
1457
1702
  }
@@ -1469,6 +1714,11 @@ function createManualState() {
1469
1714
  progressState.set(undefined);
1470
1715
  statusState.set('error');
1471
1716
  },
1717
+ setIdle() {
1718
+ errorState.set(undefined);
1719
+ progressState.set(undefined);
1720
+ statusState.set('idle');
1721
+ },
1472
1722
  setProgress(value) {
1473
1723
  progressState.set(value);
1474
1724
  },
@@ -1481,134 +1731,14 @@ function createManualState() {
1481
1731
  hadSuccess.set(false);
1482
1732
  },
1483
1733
  };
1484
- }
1485
-
1486
- /**
1487
- * Create a mutation async state - for explicit user-triggered actions.
1488
- *
1489
- * Must be called in an injection context (field initializer or constructor)
1490
- * because it uses `inject(DestroyRef)` for cleanup.
1491
- *
1492
- * ```typescript
1493
- * readonly saveResident = createAsyncState<Resident>();
1494
- *
1495
- * async handleSave(): Promise<void> {
1496
- * await this.saveResident.execute(
1497
- * () => this.api.save(this.form().value())
1498
- * );
1499
- * }
1500
- * ```
1501
- *
1502
- * @category common/data/async-state
1503
- */
1504
- function createAsyncState() {
1505
- const destroyRef = inject(DestroyRef);
1506
- const state = createManualState();
1507
- let abortController;
1508
- destroyRef.onDestroy(() => {
1509
- abortController?.abort();
1510
- abortController = undefined;
1511
- });
1512
- return {
1513
- status: state.status,
1514
- data: state.data,
1515
- error: state.error,
1516
- progress: state.progress,
1517
- isLoading: state.isLoading,
1518
- isPending: state.isPending,
1519
- isRefreshing: state.isRefreshing,
1520
- isBusy: state.isBusy,
1521
- isFirstLoad: state.isFirstLoad,
1522
- isEmpty: state.isEmpty,
1523
- hasData: state.hasData,
1524
- isSettled: state.isSettled,
1525
- lastUpdated: state.lastUpdated,
1526
- async execute(fn) {
1527
- abortController?.abort();
1528
- const controller = new AbortController();
1529
- abortController = controller;
1530
- state.set('pending');
1531
- state.setProgress(undefined);
1532
- try {
1533
- const result$ = fn();
1534
- const result = isObservable(result$) ? await firstValueFrom(result$) : await result$;
1535
- if (controller.signal.aborted) {
1536
- return;
1537
- }
1538
- state.setSuccess(result);
1539
- }
1540
- catch (err) {
1541
- if (controller.signal.aborted) {
1542
- return;
1543
- }
1544
- state.setError(err);
1545
- }
1546
- finally {
1547
- if (abortController === controller) {
1548
- abortController = undefined;
1549
- }
1550
- }
1551
- },
1552
- reportProgress(value) {
1553
- state.setProgress(value);
1554
- },
1555
- reset() {
1556
- abortController?.abort();
1557
- abortController = undefined;
1558
- state.reset();
1559
- },
1560
- };
1561
- }
1562
-
1563
- /**
1564
- * Wraps a *changing* source of async state in a stable
1565
- * {@link CngxAsyncState} façade.
1566
- *
1567
- * A component that receives its state through an `Input` cannot publish that
1568
- * object through `CNGX_STATEFUL` directly: the token is resolved once when a
1569
- * bridge injects it, while the input can be rebound or absent. Capturing the
1570
- * object would hand the bridge a stale state - or `undefined` before the
1571
- * first binding.
1572
- *
1573
- * This returns one object whose every member is a `computed()` that reads the
1574
- * source on each access, so bridges observe transitions of whatever is bound
1575
- * right now. With nothing bound it reports a quiet `idle` state rather than
1576
- * throwing, which is what lets a bridge sit inside a timeline that has not
1577
- * been given a state yet.
1578
- *
1579
- * Contrast the select family, which provides `CNGX_STATEFUL` with
1580
- * `useFactory` over a concrete `commitState` field - no forwarding needed
1581
- * there, because the state is created by the component rather than passed in.
1582
- * The split is not about the component, it is about where the state is born:
1583
- * created locally, capture it; arriving through an `Input`, forward it.
1584
- *
1585
- * ```ts
1586
- * readonly asyncState = createForwardedAsyncState(this.state);
1587
- *
1588
- * // providers:
1589
- * { provide: CNGX_STATEFUL, useFactory: () => ({ state: inject(Host).asyncState }) }
1590
- * ```
1591
- *
1592
- * @category common/data/async-state
1593
- * @relatedTo createAsyncState, createManualState
1594
- * @since 0.1.0
1595
- */
1596
- function createForwardedAsyncState(source) {
1597
- return {
1598
- status: computed(() => source()?.status() ?? 'idle'),
1599
- data: computed(() => source()?.data()),
1600
- error: computed(() => source()?.error()),
1601
- progress: computed(() => source()?.progress()),
1602
- isLoading: computed(() => source()?.isLoading() ?? false),
1603
- isPending: computed(() => source()?.isPending() ?? false),
1604
- isRefreshing: computed(() => source()?.isRefreshing() ?? false),
1605
- isBusy: computed(() => source()?.isBusy() ?? false),
1606
- isFirstLoad: computed(() => source()?.isFirstLoad() ?? true),
1607
- isEmpty: computed(() => source()?.isEmpty() ?? true),
1608
- hasData: computed(() => source()?.hasData() ?? false),
1609
- isSettled: computed(() => source()?.isSettled() ?? false),
1610
- lastUpdated: computed(() => source()?.lastUpdated()),
1611
- };
1734
+ if (typeof ngDevMode !== 'undefined' && ngDevMode) {
1735
+ CNGX_DEV_DESCRIPTORS.tag(state, {
1736
+ kind: 'cngx-dev:factory',
1737
+ factory: 'createManualState',
1738
+ inputs: {},
1739
+ });
1740
+ }
1741
+ return state;
1612
1742
  }
1613
1743
 
1614
1744
  /** @internal Length-then-key-set equality for the operations Map signal. */
@@ -1746,6 +1876,154 @@ function injectAsyncRegistry() {
1746
1876
  return inject(CngxAsyncRegistry, { optional: true });
1747
1877
  }
1748
1878
 
1879
+ /**
1880
+ * Create a mutation async state - for explicit user-triggered actions.
1881
+ *
1882
+ * Must be called in an injection context (field initializer or constructor)
1883
+ * because it uses `inject(DestroyRef)` for cleanup.
1884
+ *
1885
+ * ```typescript
1886
+ * readonly saveResident = createAsyncState<Resident>();
1887
+ *
1888
+ * async handleSave(): Promise<void> {
1889
+ * await this.saveResident.execute(
1890
+ * () => this.api.save(this.form().value())
1891
+ * );
1892
+ * }
1893
+ * ```
1894
+ *
1895
+ * @category common/data/async-state
1896
+ */
1897
+ function createAsyncState(options) {
1898
+ const destroyRef = inject(DestroyRef);
1899
+ const state = createManualState();
1900
+ let abortController;
1901
+ destroyRef.onDestroy(() => {
1902
+ abortController?.abort();
1903
+ abortController = undefined;
1904
+ });
1905
+ // Same opt-in observability injectAsyncState offers: without it, mutations
1906
+ // built here are invisible to CngxAsyncRegistry.isAnythingLoading.
1907
+ if (options?.register) {
1908
+ const registry = injectAsyncRegistry();
1909
+ if (registry) {
1910
+ const operationId = registry.register(state, options.label);
1911
+ destroyRef.onDestroy(() => registry.unregister(operationId));
1912
+ }
1913
+ }
1914
+ const mutation = {
1915
+ status: state.status,
1916
+ data: state.data,
1917
+ error: state.error,
1918
+ progress: state.progress,
1919
+ isLoading: state.isLoading,
1920
+ isPending: state.isPending,
1921
+ isRefreshing: state.isRefreshing,
1922
+ isBusy: state.isBusy,
1923
+ isFirstLoad: state.isFirstLoad,
1924
+ isEmpty: state.isEmpty,
1925
+ hasData: state.hasData,
1926
+ isSettled: state.isSettled,
1927
+ lastUpdated: state.lastUpdated,
1928
+ async execute(fn) {
1929
+ abortController?.abort();
1930
+ const controller = new AbortController();
1931
+ abortController = controller;
1932
+ state.set('pending');
1933
+ state.setProgress(undefined);
1934
+ try {
1935
+ const result$ = fn();
1936
+ const result = isObservable(result$) ? await firstValueFrom(result$) : await result$;
1937
+ if (controller.signal.aborted) {
1938
+ return;
1939
+ }
1940
+ state.setSuccess(result);
1941
+ }
1942
+ catch (err) {
1943
+ if (controller.signal.aborted) {
1944
+ return;
1945
+ }
1946
+ state.setError(err);
1947
+ }
1948
+ finally {
1949
+ if (abortController === controller) {
1950
+ abortController = undefined;
1951
+ }
1952
+ }
1953
+ },
1954
+ reportProgress(value) {
1955
+ state.setProgress(value);
1956
+ },
1957
+ reset() {
1958
+ abortController?.abort();
1959
+ abortController = undefined;
1960
+ state.reset();
1961
+ },
1962
+ };
1963
+ if (typeof ngDevMode !== 'undefined' && ngDevMode) {
1964
+ CNGX_DEV_DESCRIPTORS.tag(mutation, {
1965
+ kind: 'cngx-dev:factory',
1966
+ factory: 'createAsyncState',
1967
+ // The inner manual state carries its own tag; listing it here is the
1968
+ // only way an inspector reaches it, since the mutation exposes its
1969
+ // signals, not the state object.
1970
+ inputs: { options, state },
1971
+ });
1972
+ }
1973
+ return mutation;
1974
+ }
1975
+
1976
+ /**
1977
+ * Wraps a *changing* source of async state in a stable
1978
+ * {@link CngxAsyncState} façade.
1979
+ *
1980
+ * A component that receives its state through an `Input` cannot publish that
1981
+ * object through `CNGX_STATEFUL` directly: the token is resolved once when a
1982
+ * bridge injects it, while the input can be rebound or absent. Capturing the
1983
+ * object would hand the bridge a stale state - or `undefined` before the
1984
+ * first binding.
1985
+ *
1986
+ * This returns one object whose every member is a `computed()` that reads the
1987
+ * source on each access, so bridges observe transitions of whatever is bound
1988
+ * right now. With nothing bound it reports a quiet `idle` state rather than
1989
+ * throwing, which is what lets a bridge sit inside a timeline that has not
1990
+ * been given a state yet.
1991
+ *
1992
+ * Contrast the select family, which provides `CNGX_STATEFUL` with
1993
+ * `useFactory` over a concrete `commitState` field - no forwarding needed
1994
+ * there, because the state is created by the component rather than passed in.
1995
+ * The split is not about the component, it is about where the state is born:
1996
+ * created locally, capture it; arriving through an `Input`, forward it.
1997
+ *
1998
+ * ```ts
1999
+ * readonly asyncState = createForwardedAsyncState(this.state);
2000
+ *
2001
+ * // providers:
2002
+ * { provide: CNGX_STATEFUL, useFactory: () => ({ state: inject(Host).asyncState }) }
2003
+ * ```
2004
+ *
2005
+ * @category common/data/async-state
2006
+ * @relatedTo createAsyncState, createManualState
2007
+ * @since 0.1.0
2008
+ */
2009
+ function createForwardedAsyncState(source) {
2010
+ return {
2011
+ status: computed(() => source()?.status() ?? 'idle'),
2012
+ data: computed(() => source()?.data()),
2013
+ error: computed(() => source()?.error()),
2014
+ progress: computed(() => source()?.progress()),
2015
+ isLoading: computed(() => source()?.isLoading() ?? false),
2016
+ isPending: computed(() => source()?.isPending() ?? false),
2017
+ isRefreshing: computed(() => source()?.isRefreshing() ?? false),
2018
+ isBusy: computed(() => source()?.isBusy() ?? false),
2019
+ isFirstLoad: computed(() => source()?.isFirstLoad() ?? true),
2020
+ isEmpty: computed(() => source()?.isEmpty() ?? true),
2021
+ hasData: computed(() => source()?.hasData() ?? false),
2022
+ isSettled: computed(() => source()?.isSettled() ?? false),
2023
+ lastUpdated: computed(() => source()?.lastUpdated()),
2024
+ };
2025
+ }
2026
+
1749
2027
  /**
1750
2028
  * Create a reactive async state that auto-loads when signal dependencies change.
1751
2029
  *
@@ -1859,6 +2137,13 @@ function injectAsyncState(fn, options) {
1859
2137
  clearTimeout(debounceTimer);
1860
2138
  }
1861
2139
  const captured = result;
2140
+ if (!isObservable(captured)) {
2141
+ // The promise's work is already running (the invocation is the
2142
+ // tracking probe). A rapid follow-up change supersedes this capture
2143
+ // before the timer consumes it - observe the rejection here so a
2144
+ // superseded failure never surfaces as an unhandled rejection.
2145
+ captured.then(undefined, () => undefined);
2146
+ }
1862
2147
  debounceTimer = setTimeout(() => {
1863
2148
  debounceTimer = undefined;
1864
2149
  void executeQuery(() => captured);
@@ -1982,37 +2267,25 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1982
2267
  }], propDecorators: { sources: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxAsyncBoundary", required: true }] }] } });
1983
2268
 
1984
2269
  /**
1985
- * Bridge that projects an Angular `Resource<T>` onto `CngxAsyncState<T>`.
2270
+ * Shared projection core for the two resource bridges (`fromResource`,
2271
+ * `fromHttpResource`). Derives every flag through `buildAsyncStateView`, so
2272
+ * the family semantics (`isLoading` includes pending/refreshing,
2273
+ * `isBusy === isLoading`) cannot drift between the bridges and the factories.
1986
2274
  *
1987
- * Must be called in an injection context (the `effect()` that tracks
1988
- * `hadSuccess` requires one).
2275
+ * Must be called in an injection context (the tracking `effect()` requires one).
1989
2276
  *
1990
- * All signals are derived reactively from the resource - no manual
1991
- * synchronization. The resource stays the single source of truth.
1992
- *
1993
- * ```typescript
1994
- * private readonly res = resource({
1995
- * request: () => ({ filter: this.filter() }),
1996
- * loader: ({ request, abortSignal }) =>
1997
- * fetch(`/api/items?q=${request.filter}`, { signal: abortSignal })
1998
- * .then(r => r.json()),
1999
- * });
2000
- *
2001
- * readonly items = fromResource(this.res);
2002
- * // items.status(), items.data(), items.isFirstLoad() - all work
2003
- * // <cngx-async-container [state]="items"> - direct binding
2004
- * ```
2005
- *
2006
- * @category common/data/async-state
2277
+ * @internal
2007
2278
  */
2008
- function fromResource(ref) {
2009
- // Track whether a successful load has ever occurred.
2010
- // Needed because ResourceStatus has no "first load" concept.
2279
+ function buildResourceBridge(ref, progress) {
2280
+ // ResourceStatus has no "first load" concept, so a successful load is
2281
+ // latched here together with its timestamp.
2011
2282
  const hadSuccess = signal(false, ...(ngDevMode ? [{ debugName: "hadSuccess" }] : /* istanbul ignore next */ []));
2283
+ const lastUpdated = signal(undefined, ...(ngDevMode ? [{ debugName: "lastUpdated" }] : /* istanbul ignore next */ []));
2012
2284
  effect(() => {
2013
2285
  const s = ref.status();
2014
2286
  if (s === 'resolved' || s === 'local') {
2015
2287
  hadSuccess.set(true);
2288
+ lastUpdated.set(new Date());
2016
2289
  }
2017
2290
  });
2018
2291
  const status = computed(() => {
@@ -2030,51 +2303,54 @@ function fromResource(ref) {
2030
2303
  return 'error';
2031
2304
  }
2032
2305
  }, ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
2033
- const data = computed(() => (ref.hasValue() ? ref.value() : undefined), ...(ngDevMode ? [{ debugName: "data" }] : /* istanbul ignore next */ []));
2034
- const error = computed(() => ref.error(), ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
2035
- const isLoading = computed(() => status() === 'loading', ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
2036
- const isPending = computed(() => false, ...(ngDevMode ? [{ debugName: "isPending" }] : /* istanbul ignore next */ [])); // resource() has no mutation concept
2037
- const isRefreshing = computed(() => status() === 'refreshing', ...(ngDevMode ? [{ debugName: "isRefreshing" }] : /* istanbul ignore next */ []));
2038
- const isBusy = computed(() => ref.isLoading(), ...(ngDevMode ? [{ debugName: "isBusy" }] : /* istanbul ignore next */ []));
2039
- const isFirstLoad = computed(() => !hadSuccess() && (isBusy() || status() === 'idle'), ...(ngDevMode ? [{ debugName: "isFirstLoad" }] : /* istanbul ignore next */ []));
2040
- const isEmpty = computed(() => {
2041
- const d = data();
2042
- return d == null || (Array.isArray(d) && d.length === 0);
2043
- }, ...(ngDevMode ? [{ debugName: "isEmpty" }] : /* istanbul ignore next */ []));
2044
- const hasData = computed(() => ref.hasValue() && !isEmpty(), ...(ngDevMode ? [{ debugName: "hasData" }] : /* istanbul ignore next */ []));
2045
- const isSettled = computed(() => {
2046
- const s = status();
2047
- return s === 'success' || s === 'error';
2048
- }, ...(ngDevMode ? [{ debugName: "isSettled" }] : /* istanbul ignore next */ []));
2049
- const lastUpdated = signal(undefined, ...(ngDevMode ? [{ debugName: "lastUpdated" }] : /* istanbul ignore next */ []));
2050
- effect(() => {
2051
- const s = ref.status();
2052
- if (s === 'resolved' || s === 'local') {
2053
- lastUpdated.set(new Date());
2054
- }
2055
- });
2056
- return {
2306
+ return buildAsyncStateView({
2057
2307
  status,
2058
- data,
2059
- error,
2060
- progress: signal(undefined).asReadonly(),
2061
- isLoading,
2062
- isPending,
2063
- isRefreshing,
2064
- isBusy,
2065
- isFirstLoad,
2066
- isEmpty,
2067
- hasData,
2068
- isSettled,
2308
+ data: computed(() => (ref.hasValue() ? ref.value() : undefined)),
2309
+ error: computed(() => ref.error()),
2310
+ progress,
2311
+ // Idle counts as "before the first load": a not-yet-triggered resource
2312
+ // still shows the skeleton, not the empty state.
2313
+ isFirstLoad: computed(() => !hadSuccess() && (ref.isLoading() || status() === 'idle')),
2069
2314
  lastUpdated: lastUpdated.asReadonly(),
2070
- };
2315
+ });
2316
+ }
2317
+
2318
+ /**
2319
+ * Bridge that projects an Angular `Resource<T>` onto `CngxAsyncState<T>`.
2320
+ *
2321
+ * Must be called in an injection context (the `effect()` that tracks
2322
+ * `hadSuccess` requires one).
2323
+ *
2324
+ * All signals are derived reactively from the resource - no manual
2325
+ * synchronization. The resource stays the single source of truth.
2326
+ *
2327
+ * ```typescript
2328
+ * private readonly res = resource({
2329
+ * request: () => ({ filter: this.filter() }),
2330
+ * loader: ({ request, abortSignal }) =>
2331
+ * fetch(`/api/items?q=${request.filter}`, { signal: abortSignal })
2332
+ * .then(r => r.json()),
2333
+ * });
2334
+ *
2335
+ * readonly items = fromResource(this.res);
2336
+ * // items.status(), items.data(), items.isFirstLoad() - all work
2337
+ * // <cngx-async-container [state]="items"> - direct binding
2338
+ * ```
2339
+ *
2340
+ * @category common/data/async-state
2341
+ */
2342
+ function fromResource(ref) {
2343
+ return buildResourceBridge(ref);
2071
2344
  }
2072
2345
 
2073
2346
  /**
2074
2347
  * Bridge that projects an Angular `httpResource()` ref onto `CngxAsyncState<T>`.
2075
2348
  *
2076
2349
  * Identical to `fromResource` but additionally maps the HTTP progress
2077
- * signal to `CngxAsyncState.progress` (0–100 scale).
2350
+ * signal to `CngxAsyncState.progress` (0-100 scale): `loaded / total`,
2351
+ * rounded and clamped. With an unknown or zero `total` the progress is
2352
+ * `undefined` (indeterminate). Angular only emits progress events when the
2353
+ * request sets `reportProgress: true`.
2078
2354
  *
2079
2355
  * Must be called in an injection context.
2080
2356
  *
@@ -2082,92 +2358,37 @@ function fromResource(ref) {
2082
2358
  * private readonly res = httpResource<Item[]>(() => ({
2083
2359
  * url: '/api/items',
2084
2360
  * params: { q: this.filter() },
2361
+ * reportProgress: true,
2085
2362
  * }));
2086
2363
  *
2087
2364
  * readonly items = fromHttpResource(this.res);
2088
- * // items.progress() tracks upload/download progress
2365
+ * // items.progress() tracks download progress 0-100
2089
2366
  * // <cngx-progress [state]="items"> - auto-wired progress bar
2090
2367
  * ```
2091
2368
  *
2092
2369
  * @category common/data/async-state
2093
2370
  */
2094
2371
  function fromHttpResource(ref) {
2095
- const hadSuccess = signal(false, ...(ngDevMode ? [{ debugName: "hadSuccess" }] : /* istanbul ignore next */ []));
2096
- effect(() => {
2097
- const s = ref.status();
2098
- if (s === 'resolved' || s === 'local') {
2099
- hadSuccess.set(true);
2100
- }
2101
- });
2102
- const status = computed(() => {
2103
- switch (ref.status()) {
2104
- case 'idle':
2105
- return 'idle';
2106
- case 'loading':
2107
- return 'loading';
2108
- case 'reloading':
2109
- return 'refreshing';
2110
- case 'resolved':
2111
- case 'local':
2112
- return 'success';
2113
- case 'error':
2114
- return 'error';
2115
- }
2116
- }, ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
2117
- const data = computed(() => (ref.hasValue() ? ref.value() : undefined), ...(ngDevMode ? [{ debugName: "data" }] : /* istanbul ignore next */ []));
2118
- const error = computed(() => ref.error(), ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
2119
- // Map HTTP progress (0–1 float) to 0–100 integer, clamped
2372
+ // Map loaded/total bytes to a 0-100 integer, clamped; no total = indeterminate.
2120
2373
  const progress = computed(() => {
2121
- const p = ref.progress();
2122
- if (p == null) {
2374
+ const event = ref.progress();
2375
+ if (event?.total == null || event.total <= 0) {
2123
2376
  return undefined;
2124
2377
  }
2125
- return Math.round(Math.min(p, 1) * 100);
2378
+ return Math.round(Math.min(event.loaded / event.total, 1) * 100);
2126
2379
  }, ...(ngDevMode ? [{ debugName: "progress" }] : /* istanbul ignore next */ []));
2127
- const isLoading = computed(() => status() === 'loading', ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
2128
- const isPending = computed(() => false, ...(ngDevMode ? [{ debugName: "isPending" }] : /* istanbul ignore next */ []));
2129
- const isRefreshing = computed(() => status() === 'refreshing', ...(ngDevMode ? [{ debugName: "isRefreshing" }] : /* istanbul ignore next */ []));
2130
- const isBusy = computed(() => ref.isLoading(), ...(ngDevMode ? [{ debugName: "isBusy" }] : /* istanbul ignore next */ []));
2131
- const isFirstLoad = computed(() => !hadSuccess() && isBusy(), ...(ngDevMode ? [{ debugName: "isFirstLoad" }] : /* istanbul ignore next */ []));
2132
- const isEmpty = computed(() => {
2133
- const d = data();
2134
- return d == null || (Array.isArray(d) && d.length === 0);
2135
- }, ...(ngDevMode ? [{ debugName: "isEmpty" }] : /* istanbul ignore next */ []));
2136
- const hasData = computed(() => ref.hasValue() && !isEmpty(), ...(ngDevMode ? [{ debugName: "hasData" }] : /* istanbul ignore next */ []));
2137
- const isSettled = computed(() => {
2138
- const s = status();
2139
- return s === 'success' || s === 'error';
2140
- }, ...(ngDevMode ? [{ debugName: "isSettled" }] : /* istanbul ignore next */ []));
2141
- const lastUpdated = signal(undefined, ...(ngDevMode ? [{ debugName: "lastUpdated" }] : /* istanbul ignore next */ []));
2142
- effect(() => {
2143
- const s = ref.status();
2144
- if (s === 'resolved' || s === 'local') {
2145
- lastUpdated.set(new Date());
2146
- }
2147
- });
2148
- return {
2149
- status,
2150
- data,
2151
- error,
2152
- progress,
2153
- isLoading,
2154
- isPending,
2155
- isRefreshing,
2156
- isBusy,
2157
- isFirstLoad,
2158
- isEmpty,
2159
- hasData,
2160
- isSettled,
2161
- lastUpdated: lastUpdated.asReadonly(),
2162
- };
2380
+ return buildResourceBridge(ref, progress);
2163
2381
  }
2164
2382
 
2165
2383
  /**
2166
2384
  * RxJS operator that wires an Observable's lifecycle to a `ManualAsyncState`.
2167
2385
  *
2168
- * On subscribe: sets `loading` (or `refreshing` if data was already loaded).
2386
+ * On subscribe: sets `loading` (or `refreshing` if data was already loaded,
2387
+ * read via the sink's `isFirstLoad`; an explicit `options.status` wins).
2169
2388
  * On next: calls `setSuccess(value)`.
2170
2389
  * On error: calls `setError(err)` and **re-throws** (does not swallow).
2390
+ * On teardown without a value (unsubscribe mid-flight, empty complete):
2391
+ * resets the sink to `idle` so a cancelled request never leaves it busy.
2171
2392
  *
2172
2393
  * The Observable passes through unchanged - `tapAsyncState` is a side-effect operator.
2173
2394
  *
@@ -2186,10 +2407,23 @@ function fromHttpResource(ref) {
2186
2407
  */
2187
2408
  function tapAsyncState(state, options) {
2188
2409
  return (source) => defer(() => {
2189
- state.set(options?.status ?? 'loading');
2410
+ state.set(options?.status ?? (state.isFirstLoad?.() === false ? 'refreshing' : 'loading'));
2411
+ let settled = false;
2190
2412
  return source.pipe(tap({
2191
- next: (value) => state.setSuccess(value),
2192
- error: (err) => state.setError(err),
2413
+ next: (value) => {
2414
+ settled = true;
2415
+ state.setSuccess(value);
2416
+ },
2417
+ error: (err) => {
2418
+ settled = true;
2419
+ state.setError(err);
2420
+ },
2421
+ }), finalize(() => {
2422
+ // Torn down without ever settling (cancelled mid-flight or an
2423
+ // empty complete) - do not leave the sink busy forever.
2424
+ if (!settled) {
2425
+ state.set('idle');
2426
+ }
2193
2427
  }));
2194
2428
  });
2195
2429
  }
@@ -2244,7 +2478,8 @@ function tapAsyncProgress(state) {
2244
2478
  * 5. Call `setError(err)` on error
2245
2479
  *
2246
2480
  * The output Observable emits the **response body** (not HttpEvents).
2247
- * Throws if the response body is `null`.
2481
+ * Throws a `CngxRuntimeError` with code `CNGX1054` if the response body is
2482
+ * `null`; the sink receives it through `setError(err)`.
2248
2483
  *
2249
2484
  * ```typescript
2250
2485
  * readonly upload = createManualState<UploadResult>();
@@ -2266,16 +2501,29 @@ function tapAsyncProgress(state) {
2266
2501
  function tapHttpAsyncState(state, options) {
2267
2502
  return (source) => defer(() => {
2268
2503
  state.set(options?.status ?? 'loading');
2504
+ let settled = false;
2269
2505
  return source.pipe(tapAsyncProgress(state), filter((event) => {
2270
2506
  return event.type === RESPONSE;
2271
2507
  }), map((response) => {
2272
2508
  if (response.body == null) {
2273
- throw new Error('tapHttpAsyncState: response body is null');
2509
+ throw new CngxRuntimeError('CNGX1054', typeof ngDevMode !== 'undefined' &&
2510
+ ngDevMode &&
2511
+ 'tapHttpAsyncState(): response body is null');
2274
2512
  }
2275
2513
  return response.body;
2276
2514
  }), tap({
2277
- next: (value) => state.setSuccess(value),
2278
- error: (err) => state.setError(err),
2515
+ next: (value) => {
2516
+ settled = true;
2517
+ state.setSuccess(value);
2518
+ },
2519
+ error: (err) => {
2520
+ settled = true;
2521
+ state.setError(err);
2522
+ },
2523
+ }), finalize(() => {
2524
+ if (!settled) {
2525
+ state.set('idle');
2526
+ }
2279
2527
  }));
2280
2528
  });
2281
2529
  }
@@ -2429,7 +2677,10 @@ function provideAsyncHttpObservability() {
2429
2677
  * - **success + empty** → empty template (or nothing)
2430
2678
  * - **error (first load)** → error template (or nothing)
2431
2679
  * - **refreshing / loading (with data)** → content template (old data stays visible)
2432
- * - **error (with data)** → content template (old data stays visible)
2680
+ * - **error (with data)** → content template (old data stays visible) -
2681
+ * `resolveAsyncView` reports this as `content+error`, but a structural
2682
+ * directive renders exactly one template, so the error half is flattened
2683
+ * away here; surface it separately (toast, alert) when it must be visible
2433
2684
  *
2434
2685
  * ### Minimal - just content
2435
2686
  * ```html
@@ -2486,7 +2737,10 @@ class CngxAsync {
2486
2737
  const s = this.cngxAsync();
2487
2738
  return resolveAsyncView(s.status(), s.isFirstLoad(), s.isEmpty());
2488
2739
  }, ...(ngDevMode ? [{ debugName: "view" }] : /* istanbul ignore next */ []));
2489
- currentView = signal('none', ...(ngDevMode ? [{ debugName: "currentView" }] : /* istanbul ignore next */ []));
2740
+ // Plain field, not a signal: it is only ever read and written inside the
2741
+ // render effect - as a signal it fed the effect's own dependency graph and
2742
+ // caused one spurious re-run per view switch.
2743
+ currentView = 'none';
2490
2744
  contentViewRef = null;
2491
2745
  constructor() {
2492
2746
  effect(() => {
@@ -2494,13 +2748,13 @@ class CngxAsync {
2494
2748
  const s = this.cngxAsync();
2495
2749
  // content+error → show content (structural directive has no dual-render)
2496
2750
  const effective = view === 'content+error' ? 'content' : view;
2497
- if (effective === this.currentView()) {
2751
+ if (effective === this.currentView) {
2498
2752
  this.updateContentContext(s);
2499
2753
  return;
2500
2754
  }
2501
2755
  this.vcr.clear();
2502
2756
  this.contentViewRef = null;
2503
- this.currentView.set(effective);
2757
+ this.currentView = effective;
2504
2758
  this.renderView(effective, s);
2505
2759
  });
2506
2760
  }
@@ -2558,11 +2812,139 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
2558
2812
  }]
2559
2813
  }], 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 }] }] } });
2560
2814
 
2815
+ /**
2816
+ * The English kpi section: the single source of the KPI atoms' English copy.
2817
+ * `CNGX_KPI_I18N` defaults to it.
2818
+ *
2819
+ * @category common/data/i18n
2820
+ * @since 0.1.0
2821
+ * @relatedTo CNGX_KPI_I18N
2822
+ */
2823
+ const CNGX_KPI_LANGUAGE_EN = {
2824
+ deltaLabel: '{value} {sentiment}',
2825
+ deltaImproved: 'improved',
2826
+ deltaDeclined: 'declined',
2827
+ deltaUnchanged: 'unchanged',
2828
+ trendLabel: '{value} {direction}',
2829
+ trendUp: 'up',
2830
+ trendDown: 'down',
2831
+ trendFlat: 'unchanged',
2832
+ goalValueText: '{now} of {max}',
2833
+ metricValueWithUnit: '{value} {unit}',
2834
+ metricPlaceholder: '\u2013',
2835
+ metricNoValue: 'No value',
2836
+ };
2837
+
2838
+ const GOAL_NUMBER = {};
2839
+ /** @internal Turns a kpi section into the token's keys for a locale. */
2840
+ function kpiBundleFrom(section, locale) {
2841
+ const sentiment = {
2842
+ positive: section.deltaImproved,
2843
+ negative: section.deltaDeclined,
2844
+ neutral: section.deltaUnchanged,
2845
+ };
2846
+ const direction = {
2847
+ up: section.trendUp,
2848
+ down: section.trendDown,
2849
+ flat: section.trendFlat,
2850
+ };
2851
+ const goalNumber = numberFormatterFor(locale, GOAL_NUMBER);
2852
+ return {
2853
+ deltaLabel: (value, s) => formatMessage(section.deltaLabel, { value, sentiment: sentiment[s] }, locale),
2854
+ trendLabel: (value, d) => formatMessage(section.trendLabel, { value, direction: direction[d] }, locale),
2855
+ goalValueText: (now, max) => formatMessage(section.goalValueText, { now: goalNumber.format(now), max: goalNumber.format(max) }, locale),
2856
+ metricValueWithUnit: section.metricValueWithUnit,
2857
+ metricPlaceholder: section.metricPlaceholder,
2858
+ metricNoValue: section.metricNoValue,
2859
+ };
2860
+ }
2861
+ /** @internal The kpi section of the active pack over English. */
2862
+ const injectKpiSection = createLanguageSection('kpi', CNGX_KPI_LANGUAGE_EN);
2863
+ /** @internal Builds and reads the token, formatted for the reading locale. */
2864
+ const kpiBundle = createSectionBundle({
2865
+ section: injectKpiSection,
2866
+ toBundle: kpiBundleFrom,
2867
+ });
2868
+ /**
2869
+ * DI token for the KPI i18n bundle. `providedIn: 'root'`: the kpi section
2870
+ * of the active language pack over the English defaults, formatted for the
2871
+ * app locale; the value is a `Signal`, shared by every reader under one
2872
+ * injector.
2873
+ *
2874
+ * @category common/data/i18n
2875
+ * @wcag AA
2876
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/data/display/shared/kpi-i18n.ts
2877
+ * @since 0.1.0
2878
+ * @relatedTo CngxDelta, CngxTrend, CngxGoal
2879
+ */
2880
+ const CNGX_KPI_I18N = new InjectionToken('CngxKpiI18n', {
2881
+ providedIn: 'root',
2882
+ factory: () => kpiBundle.build(),
2883
+ });
2884
+ /** @internal */
2885
+ function defineKpiI18nFeature(fn) {
2886
+ return Object.assign(fn, { _target: 'i18n' });
2887
+ }
2888
+ /**
2889
+ * Override KPI labels via a partial bundle - unset keys keep the language
2890
+ * pack's copy, or the English default. Pass a `Signal` of a partial bundle to switch languages at
2891
+ * runtime.
2892
+ *
2893
+ * @category common/data/i18n
2894
+ * @since 0.1.0
2895
+ */
2896
+ function withKpiI18nLabels(overrides) {
2897
+ return defineKpiI18nFeature((bundle) => createOverrideMerge(bundle, overrides));
2898
+ }
2899
+ /**
2900
+ * Provider for the KPI i18n bundle. Returns a plain `Provider`, so it also
2901
+ * scopes a subtree through `viewProviders`. The features apply on top of the
2902
+ * active language pack.
2903
+ *
2904
+ * ```ts
2905
+ * bootstrapApplication(AppComponent, {
2906
+ * providers: [
2907
+ * provideKpiI18n(
2908
+ * withKpiI18nLabels({
2909
+ * goalValueText: (now, max) => `${now} von ${max}`,
2910
+ * }),
2911
+ * ),
2912
+ * ],
2913
+ * });
2914
+ * ```
2915
+ *
2916
+ * @category common/data/i18n
2917
+ * @since 0.1.0
2918
+ */
2919
+ function provideKpiI18n(...features) {
2920
+ return {
2921
+ provide: CNGX_KPI_I18N,
2922
+ useFactory: () => kpiBundle.build(features),
2923
+ };
2924
+ }
2925
+ /**
2926
+ * Inject the resolved KPI i18n bundle signal. Read it inside a `computed()`
2927
+ * or template so a runtime override flip re-derives.
2928
+ *
2929
+ * @category common/data/i18n
2930
+ * @since 0.1.0
2931
+ */
2932
+ function injectKpiI18n() {
2933
+ return kpiBundle.resolve(inject(CNGX_KPI_I18N));
2934
+ }
2935
+
2936
+ const UNIT_PLACEHOLDER = /\{(value|unit)\}/;
2937
+ /** @internal `true` when the language reads the unit before the value. */
2938
+ function readsUnitFirst(message) {
2939
+ const [, first] = UNIT_PLACEHOLDER.exec(message) ?? [];
2940
+ return first === 'unit';
2941
+ }
2561
2942
  /**
2562
2943
  * Displays a formatted numeric value with optional unit.
2563
2944
  *
2564
- * Uses `Intl.NumberFormat` with the injected `LOCALE_ID` for locale-aware
2565
- * formatting. Null values render as an em-dash.
2945
+ * Uses `Intl.NumberFormat` with the app locale (`CNGX_LOCALE`, falling back to
2946
+ * the nearest `LOCALE_ID`) for locale-aware formatting; a locale flip
2947
+ * re-formats. A `null` value renders the placeholder glyph without its unit.
2566
2948
  *
2567
2949
  * Composable - works inside any card variant, header, body, or standalone.
2568
2950
  *
@@ -2595,8 +2977,12 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
2595
2977
  * <example-url>http://localhost:4200/#/common/data/metric/standalone-metrics</example-url>
2596
2978
  */
2597
2979
  class CngxMetric {
2598
- locale = inject(LOCALE_ID);
2599
- /** Numeric or string value. `null` renders as a placeholder hyphen. */
2980
+ locale = injectLocale();
2981
+ i18n = injectKpiI18n();
2982
+ /**
2983
+ * Numeric or string value. `null` renders the `metricPlaceholder` glyph of
2984
+ * the kpi language section and is announced as its `metricNoValue` text.
2985
+ */
2600
2986
  value = input.required(...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
2601
2987
  /** Unit suffix (e.g. "bpm", "h", "%", "kg"). */
2602
2988
  unit = input(undefined, ...(ngDevMode ? [{ debugName: "unit" }] : /* istanbul ignore next */ []));
@@ -2606,26 +2992,41 @@ class CngxMetric {
2606
2992
  formattedValue = computed(() => {
2607
2993
  const v = this.value();
2608
2994
  if (v === null) {
2609
- return '\u2014';
2995
+ return this.i18n().metricPlaceholder;
2610
2996
  }
2611
2997
  if (typeof v === 'string') {
2612
2998
  return v;
2613
2999
  }
2614
- return this.format()
2615
- ? new Intl.NumberFormat(this.locale, this.format()).format(v)
2616
- : v.toLocaleString(this.locale);
3000
+ return numberFormatterFor(this.locale(), this.format() ?? {}).format(v);
2617
3001
  }, ...(ngDevMode ? [{ debugName: "formattedValue" }] : /* istanbul ignore next */ []));
3002
+ /**
3003
+ * @internal The unit to render, `undefined` while there is no value: a
3004
+ * missing reading has no unit, so "No value km" is never shown or spoken.
3005
+ */
3006
+ shownUnit = computed(() => {
3007
+ const unit = this.unit();
3008
+ return this.value() === null || unit === '' ? undefined : unit;
3009
+ }, ...(ngDevMode ? [{ debugName: "shownUnit" }] : /* istanbul ignore next */ []));
3010
+ /** @internal Unit before value, per the `metricValueWithUnit` message. */
3011
+ unitFirst = computed(() => readsUnitFirst(this.i18n().metricValueWithUnit), ...(ngDevMode ? [{ debugName: "unitFirst" }] : /* istanbul ignore next */ []));
2618
3012
  /** @internal Full accessible description including unit. */
2619
3013
  accessibleValue = computed(() => {
2620
- const v = this.formattedValue();
2621
- const u = this.unit();
2622
- return u ? `${v} ${u}` : v;
3014
+ const i18n = this.i18n();
3015
+ if (this.value() === null) {
3016
+ return i18n.metricNoValue;
3017
+ }
3018
+ const value = this.formattedValue();
3019
+ const unit = this.shownUnit();
3020
+ return unit ? formatMessage(i18n.metricValueWithUnit, { value, unit }, this.locale()) : value;
2623
3021
  }, ...(ngDevMode ? [{ debugName: "accessibleValue" }] : /* istanbul ignore next */ []));
2624
3022
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxMetric, deps: [], target: i0.ɵɵFactoryTarget.Component });
2625
3023
  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: { attributes: { "role": "img" }, properties: { "attr.aria-label": "accessibleValue()" }, classAttribute: "cngx-metric" }, ngImport: i0, template: `
3024
+ @if (shownUnit() && unitFirst()) {
3025
+ <span class="cngx-metric__unit">{{ shownUnit() }}</span>
3026
+ }
2626
3027
  <span class="cngx-metric__value">{{ formattedValue() }}</span>
2627
- @if (unit()) {
2628
- <span class="cngx-metric__unit">{{ unit() }}</span>
3028
+ @if (shownUnit() && !unitFirst()) {
3029
+ <span class="cngx-metric__unit">{{ shownUnit() }}</span>
2629
3030
  }
2630
3031
  `, isInline: true, styles: ["@layer cngx.tokens{@property --cngx-metric-gap{syntax: \"<length>\"; inherits: false; initial-value: 2px;}@property --cngx-metric-value-size{syntax: \"*\"; inherits: true; initial-value: 1.75rem;}@property --cngx-metric-value-weight{syntax: \"<number>\"; inherits: true; initial-value: 600;}@property --cngx-metric-value-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.2 .01 290);}@property --cngx-metric-unit-size{syntax: \"*\"; inherits: true; initial-value: .875rem;}@property --cngx-metric-unit-weight{syntax: \"<number>\"; inherits: true; initial-value: 400;}@property --cngx-metric-unit-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.36 .02 290);}@media(prefers-color-scheme:dark){:root:not([data-color-scheme=light]):not(.light){--cngx-metric-value-color: oklch(.95 .01 290);--cngx-metric-unit-color: oklch(.7 .01 290)}}[data-color-scheme=dark],.dark{--cngx-metric-value-color: oklch(.95 .01 290);--cngx-metric-unit-color: oklch(.7 .01 290)}[data-color-scheme=light],.light{--cngx-metric-value-color: oklch(.2 .01 290);--cngx-metric-unit-color: oklch(.36 .02 290)}}@layer cngx.components{@scope(.cngx-metric){:scope{--cngx-metric-gap: var(--cngx-space-xs);display:inline-flex;align-items:baseline;gap:var(--cngx-metric-gap, 2px)}.cngx-metric__value{font-size:var(--cngx-metric-value-size, 1.75rem);font-weight:var(--cngx-metric-value-weight, 600);color:var(--cngx-metric-value-color, var(--cngx-color-text, oklch(.2 .01 290)));line-height:1.2;unicode-bidi:var(--cngx-metric-bidi, isolate)}.cngx-metric__unit{font-size:var(--cngx-metric-unit-size, .875rem);font-weight:var(--cngx-metric-unit-weight, 400);color:var(--cngx-metric-unit-color, oklch(.36 .02 290))}}}\n"], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
2631
3032
  }
@@ -2640,9 +3041,12 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
2640
3041
  role: 'img',
2641
3042
  '[attr.aria-label]': 'accessibleValue()',
2642
3043
  }, template: `
3044
+ @if (shownUnit() && unitFirst()) {
3045
+ <span class="cngx-metric__unit">{{ shownUnit() }}</span>
3046
+ }
2643
3047
  <span class="cngx-metric__value">{{ formattedValue() }}</span>
2644
- @if (unit()) {
2645
- <span class="cngx-metric__unit">{{ unit() }}</span>
3048
+ @if (shownUnit() && !unitFirst()) {
3049
+ <span class="cngx-metric__unit">{{ shownUnit() }}</span>
2646
3050
  }
2647
3051
  `, styles: ["@layer cngx.tokens{@property --cngx-metric-gap{syntax: \"<length>\"; inherits: false; initial-value: 2px;}@property --cngx-metric-value-size{syntax: \"*\"; inherits: true; initial-value: 1.75rem;}@property --cngx-metric-value-weight{syntax: \"<number>\"; inherits: true; initial-value: 600;}@property --cngx-metric-value-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.2 .01 290);}@property --cngx-metric-unit-size{syntax: \"*\"; inherits: true; initial-value: .875rem;}@property --cngx-metric-unit-weight{syntax: \"<number>\"; inherits: true; initial-value: 400;}@property --cngx-metric-unit-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.36 .02 290);}@media(prefers-color-scheme:dark){:root:not([data-color-scheme=light]):not(.light){--cngx-metric-value-color: oklch(.95 .01 290);--cngx-metric-unit-color: oklch(.7 .01 290)}}[data-color-scheme=dark],.dark{--cngx-metric-value-color: oklch(.95 .01 290);--cngx-metric-unit-color: oklch(.7 .01 290)}[data-color-scheme=light],.light{--cngx-metric-value-color: oklch(.2 .01 290);--cngx-metric-unit-color: oklch(.36 .02 290)}}@layer cngx.components{@scope(.cngx-metric){:scope{--cngx-metric-gap: var(--cngx-space-xs);display:inline-flex;align-items:baseline;gap:var(--cngx-metric-gap, 2px)}.cngx-metric__value{font-size:var(--cngx-metric-value-size, 1.75rem);font-weight:var(--cngx-metric-value-weight, 600);color:var(--cngx-metric-value-color, var(--cngx-color-text, oklch(.2 .01 290)));line-height:1.2;unicode-bidi:var(--cngx-metric-bidi, isolate)}.cngx-metric__unit{font-size:var(--cngx-metric-unit-size, .875rem);font-weight:var(--cngx-metric-unit-weight, 400);color:var(--cngx-metric-unit-color, oklch(.36 .02 290))}}}\n"] }]
2648
3052
  }], 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 }] }] } });
@@ -2683,20 +3087,26 @@ function directionGlyph(direction) {
2683
3087
  /**
2684
3088
  * Format the magnitude. The sign is carried by the arrow and colour, not the
2685
3089
  * digits: a positive value gains a leading `+`, everything else prints its
2686
- * absolute value unsigned. Percent mode appends a narrow-no-break-space + `%`
2687
- * and defaults to one fraction digit; absolute mode uses the locale grouping.
3090
+ * absolute value unsigned. Percent mode formats with `Intl` `style: 'percent'`
3091
+ * (so the locale places the `%` sign) and defaults to one fraction digit;
3092
+ * absolute mode uses the locale grouping.
2688
3093
  * A supplied `Intl.NumberFormatOptions` overrides the default digit handling
2689
3094
  * in both modes.
2690
3095
  */
2691
3096
  function formatDelta(value, mode, locale, format) {
2692
3097
  const abs = Math.abs(value);
2693
- const prefix = value > 0 ? '+' : '';
3098
+ // The locale places and draws the plus sign; a negative prints unsigned.
3099
+ const signDisplay = value > 0 ? 'exceptZero' : 'never';
2694
3100
  if (mode === 'percent') {
2695
- const num = format ? new Intl.NumberFormat(locale, format).format(abs) : abs.toFixed(1);
2696
- return `${prefix}${num}\u202f%`;
3101
+ // The input is already in percent units; Intl's percent style multiplies
3102
+ // by 100, so scale down first.
3103
+ return numberFormatterFor(locale, {
3104
+ ...(format ?? { minimumFractionDigits: 1, maximumFractionDigits: 1 }),
3105
+ style: 'percent',
3106
+ signDisplay,
3107
+ }).format(abs / 100);
2697
3108
  }
2698
- const num = format ? new Intl.NumberFormat(locale, format).format(abs) : abs.toLocaleString(locale);
2699
- return `${prefix}${num}`;
3109
+ return numberFormatterFor(locale, { ...format, signDisplay }).format(abs);
2700
3110
  }
2701
3111
 
2702
3112
  /**
@@ -2737,7 +3147,8 @@ function formatDelta(value, mode, locale, format) {
2737
3147
  * <example-url>http://localhost:4200/#/common/data/trend/trend-directions</example-url>
2738
3148
  */
2739
3149
  class CngxTrend {
2740
- locale = inject(LOCALE_ID);
3150
+ locale = injectLocale();
3151
+ i18n = injectKpiI18n();
2741
3152
  /** Trend percentage. Positive = up, negative = down, zero = flat. */
2742
3153
  value = input.required(...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
2743
3154
  /** Consumer-provided SR label override. When set, replaces the generated default. */
@@ -2745,16 +3156,10 @@ class CngxTrend {
2745
3156
  /** @internal */
2746
3157
  icon = computed(() => directionGlyph(deltaDirection(this.value())), ...(ngDevMode ? [{ debugName: "icon" }] : /* istanbul ignore next */ []));
2747
3158
  /** @internal */
2748
- formattedValue = computed(() => formatDelta(this.value(), 'percent', this.locale), ...(ngDevMode ? [{ debugName: "formattedValue" }] : /* istanbul ignore next */ []));
3159
+ formattedValue = computed(() => formatDelta(this.value(), 'percent', this.locale()), ...(ngDevMode ? [{ debugName: "formattedValue" }] : /* istanbul ignore next */ []));
2749
3160
  /** @internal */
2750
- resolvedLabel = computed(() => {
2751
- if (this.label()) {
2752
- return this.label();
2753
- }
2754
- const direction = deltaDirection(this.value());
2755
- const dir = direction === 'up' ? 'up' : direction === 'down' ? 'down' : 'unchanged';
2756
- return `${this.formattedValue()} ${dir}`;
2757
- }, ...(ngDevMode ? [{ debugName: "resolvedLabel" }] : /* istanbul ignore next */ []));
3161
+ resolvedLabel = computed(() => this.label() ??
3162
+ this.i18n().trendLabel(this.formattedValue(), deltaDirection(this.value())), ...(ngDevMode ? [{ debugName: "resolvedLabel" }] : /* istanbul ignore next */ []));
2758
3163
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTrend, deps: [], target: i0.ɵɵFactoryTarget.Component });
2759
3164
  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: { attributes: { "role": "img" }, properties: { "class.cngx-trend--up": "value() > 0", "class.cngx-trend--down": "value() < 0", "attr.aria-label": "resolvedLabel()" }, classAttribute: "cngx-trend" }, ngImport: i0, template: `
2760
3165
  <span aria-hidden="true">{{ icon() }}</span>
@@ -2778,11 +3183,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
2778
3183
  `, styles: ["@layer cngx.tokens{@property --cngx-trend-gap{syntax: \"<length>\"; inherits: false; initial-value: 2px;}@property --cngx-trend-size{syntax: \"*\"; inherits: true; initial-value: .8125rem;}@property --cngx-trend-weight{syntax: \"<number>\"; inherits: true; initial-value: 500;}@property --cngx-trend-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.36 .02 290);}@property --cngx-trend-up-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.65 .18 145);}@property --cngx-trend-down-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.65 .22 25);}@media(prefers-color-scheme:dark){:root:not([data-color-scheme=light]):not(.light){--cngx-trend-color: oklch(.7 .01 290);--cngx-trend-up-color: oklch(.78 .16 145);--cngx-trend-down-color: oklch(.75 .18 25)}}[data-color-scheme=dark],.dark{--cngx-trend-color: oklch(.7 .01 290);--cngx-trend-up-color: oklch(.78 .16 145);--cngx-trend-down-color: oklch(.75 .18 25)}[data-color-scheme=light],.light{--cngx-trend-color: oklch(.36 .02 290);--cngx-trend-up-color: oklch(.65 .18 145);--cngx-trend-down-color: oklch(.65 .22 25)}}@layer cngx.components{@scope(.cngx-trend){:scope{--cngx-trend-gap: var(--cngx-space-xs);display:inline-flex;align-items:center;gap:var(--cngx-trend-gap, 2px);font-size:var(--cngx-trend-size, .8125rem);font-weight:var(--cngx-trend-weight, 500);color:var(--cngx-trend-color, oklch(.36 .02 290));unicode-bidi:var(--cngx-trend-bidi, isolate);direction:var(--cngx-trend-direction, ltr)}:scope.cngx-trend--up{color:var(--cngx-trend-up-color, var(--cngx-color-success, oklch(.65 .18 145)))}:scope.cngx-trend--down{color:var(--cngx-trend-down-color, var(--cngx-color-danger, oklch(.65 .22 25)))}}}\n"] }]
2779
3184
  }], propDecorators: { value: [{ type: i0.Input, args: [{ isSignal: true, alias: "value", required: true }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }] } });
2780
3185
 
2781
- const SENTIMENT_WORD = {
2782
- positive: 'improved',
2783
- negative: 'declined',
2784
- neutral: 'unchanged',
2785
- };
2786
3186
  /**
2787
3187
  * Sentiment-aware delta indicator. Where `CngxTrend` colours strictly by
2788
3188
  * direction (up = green), `CngxDelta` colours by **sentiment**: a `polarity`
@@ -2821,7 +3221,8 @@ const SENTIMENT_WORD = {
2821
3221
  * <example-url>http://localhost:4200/#/common/data/delta/sentiment-polarity</example-url>
2822
3222
  */
2823
3223
  class CngxDelta {
2824
- locale = inject(LOCALE_ID);
3224
+ locale = injectLocale();
3225
+ i18n = injectKpiI18n();
2825
3226
  /** Signed delta. Positive = up, negative = down, zero = flat. */
2826
3227
  value = input.required(...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
2827
3228
  /**
@@ -2843,15 +3244,12 @@ class CngxDelta {
2843
3244
  /** @internal Arrow glyph bound from direction only. */
2844
3245
  glyph = computed(() => directionGlyph(this.direction()), ...(ngDevMode ? [{ debugName: "glyph" }] : /* istanbul ignore next */ []));
2845
3246
  /** @internal Formatted magnitude. */
2846
- formattedValue = computed(() => formatDelta(this.value(), this.mode(), this.locale, this.format()), ...(ngDevMode ? [{ debugName: "formattedValue" }] : /* istanbul ignore next */ []));
2847
- /** @internal Full SR label: magnitude plus the sentiment word. */
2848
- resolvedLabel = computed(() => {
2849
- const override = this.label();
2850
- if (override) {
2851
- return override;
2852
- }
2853
- return `${this.formattedValue()} ${SENTIMENT_WORD[this.sentiment()]}`;
2854
- }, ...(ngDevMode ? [{ debugName: "resolvedLabel" }] : /* istanbul ignore next */ []));
3247
+ formattedValue = computed(() => formatDelta(this.value(), this.mode(), this.locale(), this.format()), ...(ngDevMode ? [{ debugName: "formattedValue" }] : /* istanbul ignore next */ []));
3248
+ /**
3249
+ * @internal Full SR label: magnitude plus the sentiment word, composed by
3250
+ * `CNGX_KPI_I18N.deltaLabel` unless `[label]` is bound.
3251
+ */
3252
+ resolvedLabel = computed(() => this.label() ?? this.i18n().deltaLabel(this.formattedValue(), this.sentiment()), ...(ngDevMode ? [{ debugName: "resolvedLabel" }] : /* istanbul ignore next */ []));
2855
3253
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxDelta, deps: [], target: i0.ɵɵFactoryTarget.Component });
2856
3254
  static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "21.2.4", type: CngxDelta, isStandalone: true, selector: "cngx-delta", inputs: { value: { classPropertyName: "value", publicName: "value", isSignal: true, isRequired: true, transformFunction: null }, polarity: { classPropertyName: "polarity", publicName: "polarity", isSignal: true, isRequired: false, transformFunction: null }, mode: { classPropertyName: "mode", publicName: "mode", isSignal: true, isRequired: false, transformFunction: null }, format: { classPropertyName: "format", publicName: "format", isSignal: true, isRequired: false, transformFunction: null }, label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null } }, host: { attributes: { "role": "img" }, properties: { "class.cngx-delta--positive": "sentiment() === 'positive'", "class.cngx-delta--negative": "sentiment() === 'negative'", "class.cngx-delta--neutral": "sentiment() === 'neutral'", "attr.aria-label": "resolvedLabel()" }, classAttribute: "cngx-delta" }, ngImport: i0, template: `
2857
3255
  <span aria-hidden="true">{{ glyph() }}</span>
@@ -2914,8 +3312,13 @@ class CngxStatCoordinator {
2914
3312
  this.slots.update((prev) => new Map(prev).set(kind, id));
2915
3313
  }
2916
3314
  /** {@inheritDoc CngxStatRegistry.unregister} */
2917
- unregister(kind) {
3315
+ unregister(kind, id) {
2918
3316
  this.slots.update((prev) => {
3317
+ if (id !== undefined && prev.get(kind) !== id) {
3318
+ // Register-before-destroy replacement: the outgoing slot must not
3319
+ // evict the live slot's id from aria-labelledby.
3320
+ return prev;
3321
+ }
2919
3322
  const next = new Map(prev);
2920
3323
  next.delete(kind);
2921
3324
  return next;
@@ -3027,7 +3430,7 @@ function useStatSlot(kind) {
3027
3430
  const registry = inject(CNGX_STAT, { optional: true });
3028
3431
  const id = nextUid(`cngx-stat-${kind}`);
3029
3432
  registry?.register(kind, id);
3030
- inject(DestroyRef).onDestroy(() => registry?.unregister(kind));
3433
+ inject(DestroyRef).onDestroy(() => registry?.unregister(kind, id));
3031
3434
  return id;
3032
3435
  }
3033
3436
  /**
@@ -3132,7 +3535,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
3132
3535
  * derived percent bound as a CSS custom property.
3133
3536
  *
3134
3537
  * ```html
3135
- * <cngx-goal [value]="73" [max]="100" />
3538
+ * <cngx-goal [value]="73" [max]="100" label="Quota attainment" />
3136
3539
  * <cngx-goal [value]="q()" [max]="target()" [valueTextFormat]="quotaText" />
3137
3540
  * ```
3138
3541
  *
@@ -3146,14 +3549,23 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
3146
3549
  * <example-url>http://localhost:4200/#/common/data/goal/quota-attainment</example-url>
3147
3550
  */
3148
3551
  class CngxGoal {
3552
+ i18n = injectKpiI18n();
3149
3553
  /** Current attainment. Clamped to `[0, max]`. */
3150
3554
  value = input.required(...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
3151
3555
  /** Target the value works toward. Defaults to `100`. */
3152
3556
  max = input(100, ...(ngDevMode ? [{ debugName: "max" }] : /* istanbul ignore next */ []));
3557
+ /**
3558
+ * Accessible name for the progressbar (what the attainment measures, e.g.
3559
+ * "Quarterly quota"). Mirrors the `label` input of the sibling KPI atoms;
3560
+ * omit it only when an external `aria-labelledby` (e.g. a `cngxStatLabel`)
3561
+ * names the bar instead.
3562
+ */
3563
+ label = input(undefined, ...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
3153
3564
  /**
3154
3565
  * Override the `aria-valuetext` string. Receives `(now, max)` - the clamped
3155
- * value and the target. The default is `(now, max) => \`${now} of ${max}\``.
3156
- * Supply a localised closure for richer text (e.g.
3566
+ * value and the target. Wins over the app-wide `CNGX_KPI_I18N.goalValueText`
3567
+ * (English default `(now, max) => \`${now} of ${max}\``). Supply a closure
3568
+ * for richer per-instance text (e.g.
3157
3569
  * `(n, m) => \`${n} of ${m}, ${Math.round((n / m) * 100)}% of quota\``).
3158
3570
  */
3159
3571
  valueTextFormat = input(undefined, ...(ngDevMode ? [{ debugName: "valueTextFormat" }] : /* istanbul ignore next */ []));
@@ -3168,11 +3580,11 @@ class CngxGoal {
3168
3580
  }, ...(ngDevMode ? [{ debugName: "fillPercent" }] : /* istanbul ignore next */ []));
3169
3581
  /** `aria-valuetext` - human-readable attainment via the resolved closure. */
3170
3582
  valueText = computed(() => {
3171
- const fmt = this.valueTextFormat() ?? ((now, max) => `${now} of ${max}`);
3583
+ const fmt = this.valueTextFormat() ?? this.i18n().goalValueText;
3172
3584
  return fmt(this.now(), this.maxValue());
3173
3585
  }, ...(ngDevMode ? [{ debugName: "valueText" }] : /* istanbul ignore next */ []));
3174
3586
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxGoal, deps: [], target: i0.ɵɵFactoryTarget.Component });
3175
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "21.2.4", type: CngxGoal, isStandalone: true, selector: "cngx-goal", inputs: { value: { classPropertyName: "value", publicName: "value", isSignal: true, isRequired: true, transformFunction: null }, max: { classPropertyName: "max", publicName: "max", isSignal: true, isRequired: false, transformFunction: null }, valueTextFormat: { classPropertyName: "valueTextFormat", publicName: "valueTextFormat", isSignal: true, isRequired: false, transformFunction: null } }, host: { attributes: { "role": "progressbar" }, properties: { "attr.aria-valuemin": "0", "attr.aria-valuemax": "maxValue()", "attr.aria-valuenow": "now()", "attr.aria-valuetext": "valueText()", "style.--cngx-goal-fill.%": "fillPercent()" }, classAttribute: "cngx-goal" }, ngImport: i0, template: `<span class="cngx-goal__track"><span class="cngx-goal__fill"></span></span>`, isInline: true, styles: ["@layer cngx.tokens{@property --cngx-goal-fill{syntax: \"<percentage>\"; inherits: true; initial-value: 0%;}@property --cngx-goal-height{syntax: \"<length>\"; inherits: false; initial-value: 8px;}@property --cngx-goal-radius{syntax: \"<length>\"; inherits: false; initial-value: 999px;}@property --cngx-goal-track-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.92 .01 290);}@property --cngx-goal-fill-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.65 .18 145);}@media(prefers-color-scheme:dark){:root:not([data-color-scheme=light]):not(.light){--cngx-goal-track-color: oklch(.3 .01 290);--cngx-goal-fill-color: oklch(.78 .16 145)}}[data-color-scheme=dark],.dark{--cngx-goal-track-color: oklch(.3 .01 290);--cngx-goal-fill-color: oklch(.78 .16 145)}[data-color-scheme=light],.light{--cngx-goal-track-color: oklch(.92 .01 290);--cngx-goal-fill-color: oklch(.65 .18 145)}}@layer cngx.components{@scope(.cngx-goal){:scope{display:block;inline-size:100%}.cngx-goal__track{display:block;inline-size:100%;block-size:var(--cngx-goal-height, 8px);border-radius:var(--cngx-goal-radius, 999px);background:var(--cngx-goal-track-color, oklch(.92 .01 290));overflow:hidden}.cngx-goal__fill{display:block;block-size:100%;inline-size:var(--cngx-goal-fill, 0%);border-radius:inherit;background:var(--cngx-goal-fill-color, var(--cngx-color-success, oklch(.65 .18 145)))}}}@media(forced-colors:active){.cngx-goal__track{box-sizing:border-box;border:1px solid CanvasText}.cngx-goal__fill{background:Highlight}}\n"], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
3587
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "21.2.4", type: CngxGoal, isStandalone: true, selector: "cngx-goal", inputs: { value: { classPropertyName: "value", publicName: "value", isSignal: true, isRequired: true, transformFunction: null }, max: { classPropertyName: "max", publicName: "max", isSignal: true, isRequired: false, transformFunction: null }, label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null }, valueTextFormat: { classPropertyName: "valueTextFormat", publicName: "valueTextFormat", isSignal: true, isRequired: false, transformFunction: null } }, host: { attributes: { "role": "progressbar" }, properties: { "attr.aria-valuemin": "0", "attr.aria-valuemax": "maxValue()", "attr.aria-valuenow": "now()", "attr.aria-valuetext": "valueText()", "attr.aria-label": "label() ?? null", "style.--cngx-goal-fill.%": "fillPercent()" }, classAttribute: "cngx-goal" }, ngImport: i0, template: `<span class="cngx-goal__track"><span class="cngx-goal__fill"></span></span>`, isInline: true, styles: ["@layer cngx.tokens{@property --cngx-goal-fill{syntax: \"<percentage>\"; inherits: true; initial-value: 0%;}@property --cngx-goal-height{syntax: \"<length>\"; inherits: false; initial-value: 8px;}@property --cngx-goal-radius{syntax: \"<length>\"; inherits: false; initial-value: 999px;}@property --cngx-goal-track-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.92 .01 290);}@property --cngx-goal-fill-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.65 .18 145);}@media(prefers-color-scheme:dark){:root:not([data-color-scheme=light]):not(.light){--cngx-goal-track-color: oklch(.3 .01 290);--cngx-goal-fill-color: oklch(.78 .16 145)}}[data-color-scheme=dark],.dark{--cngx-goal-track-color: oklch(.3 .01 290);--cngx-goal-fill-color: oklch(.78 .16 145)}[data-color-scheme=light],.light{--cngx-goal-track-color: oklch(.92 .01 290);--cngx-goal-fill-color: oklch(.65 .18 145)}}@layer cngx.components{@scope(.cngx-goal){:scope{display:block;inline-size:100%}.cngx-goal__track{display:block;inline-size:100%;block-size:var(--cngx-goal-height, 8px);border-radius:var(--cngx-goal-radius, 999px);background:var(--cngx-goal-track-color, oklch(.92 .01 290));overflow:hidden}.cngx-goal__fill{display:block;block-size:100%;inline-size:var(--cngx-goal-fill, 0%);border-radius:inherit;background:var(--cngx-goal-fill-color, var(--cngx-color-success, oklch(.65 .18 145)))}}}@media(forced-colors:active){.cngx-goal__track{box-sizing:border-box;border:1px solid CanvasText}.cngx-goal__fill{background:Highlight}}\n"], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
3176
3588
  }
3177
3589
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxGoal, decorators: [{
3178
3590
  type: Component,
@@ -3183,9 +3595,28 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
3183
3595
  '[attr.aria-valuemax]': 'maxValue()',
3184
3596
  '[attr.aria-valuenow]': 'now()',
3185
3597
  '[attr.aria-valuetext]': 'valueText()',
3598
+ '[attr.aria-label]': 'label() ?? null',
3186
3599
  '[style.--cngx-goal-fill.%]': 'fillPercent()',
3187
3600
  }, template: `<span class="cngx-goal__track"><span class="cngx-goal__fill"></span></span>`, styles: ["@layer cngx.tokens{@property --cngx-goal-fill{syntax: \"<percentage>\"; inherits: true; initial-value: 0%;}@property --cngx-goal-height{syntax: \"<length>\"; inherits: false; initial-value: 8px;}@property --cngx-goal-radius{syntax: \"<length>\"; inherits: false; initial-value: 999px;}@property --cngx-goal-track-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.92 .01 290);}@property --cngx-goal-fill-color{syntax: \"<color>\"; inherits: true; initial-value: oklch(.65 .18 145);}@media(prefers-color-scheme:dark){:root:not([data-color-scheme=light]):not(.light){--cngx-goal-track-color: oklch(.3 .01 290);--cngx-goal-fill-color: oklch(.78 .16 145)}}[data-color-scheme=dark],.dark{--cngx-goal-track-color: oklch(.3 .01 290);--cngx-goal-fill-color: oklch(.78 .16 145)}[data-color-scheme=light],.light{--cngx-goal-track-color: oklch(.92 .01 290);--cngx-goal-fill-color: oklch(.65 .18 145)}}@layer cngx.components{@scope(.cngx-goal){:scope{display:block;inline-size:100%}.cngx-goal__track{display:block;inline-size:100%;block-size:var(--cngx-goal-height, 8px);border-radius:var(--cngx-goal-radius, 999px);background:var(--cngx-goal-track-color, oklch(.92 .01 290));overflow:hidden}.cngx-goal__fill{display:block;block-size:100%;inline-size:var(--cngx-goal-fill, 0%);border-radius:inherit;background:var(--cngx-goal-fill-color, var(--cngx-color-success, oklch(.65 .18 145)))}}}@media(forced-colors:active){.cngx-goal__track{box-sizing:border-box;border:1px solid CanvasText}.cngx-goal__fill{background:Highlight}}\n"] }]
3188
- }], propDecorators: { value: [{ type: i0.Input, args: [{ isSignal: true, alias: "value", required: true }] }], max: [{ type: i0.Input, args: [{ isSignal: true, alias: "max", required: false }] }], valueTextFormat: [{ type: i0.Input, args: [{ isSignal: true, alias: "valueTextFormat", required: false }] }] } });
3601
+ }], propDecorators: { value: [{ type: i0.Input, args: [{ isSignal: true, alias: "value", required: true }] }], max: [{ type: i0.Input, args: [{ isSignal: true, alias: "max", required: false }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }], valueTextFormat: [{ type: i0.Input, args: [{ isSignal: true, alias: "valueTextFormat", required: false }] }] } });
3602
+
3603
+ /**
3604
+ * The English recycler section: the single source of the recycler's English
3605
+ * copy. `CNGX_RECYCLER_I18N` defaults to it.
3606
+ *
3607
+ * @category common/data/i18n
3608
+ * @since 0.1.0
3609
+ * @relatedTo CNGX_RECYCLER_I18N
3610
+ */
3611
+ const CNGX_RECYCLER_LANGUAGE_EN = {
3612
+ loaded: {
3613
+ one: '{count} more item loaded. {total} total.',
3614
+ other: '{count} more items loaded. {total} total.',
3615
+ },
3616
+ filtered: { one: '{count} result found.', other: '{count} results found.' },
3617
+ empty: 'No results',
3618
+ error: 'Error loading data',
3619
+ };
3189
3620
 
3190
3621
  const EMPTY_RANGE = {
3191
3622
  start: 0,
@@ -3204,31 +3635,58 @@ const EMPTY_RANGE = {
3204
3635
  * @param clientHeight Viewport height in px.
3205
3636
  * @param totalCount Total number of items.
3206
3637
  * @param estimateSize Fixed item height in px, or a function returning height per index.
3207
- * @param overscan Number of extra items to render above/below the viewport.
3638
+ * @param overscanBefore Extra items to render above the viewport (leading edge
3639
+ * when scrolling up).
3208
3640
  * @param columns Column count for grid mode (default 1). When > 1, range is row-aligned.
3209
3641
  * Variable `estimateSize` ignores columns (grid + variable heights not supported).
3642
+ * @param overscanAfter Extra items to render below the viewport (leading edge when
3643
+ * scrolling down). Defaults to `overscanBefore` for a symmetric range. Callers pass
3644
+ * an asymmetric pair to pre-render into the scroll direction.
3210
3645
  * @returns The computed range with spacer offsets.
3211
3646
  * @internal
3212
3647
  */
3213
- function computeRange(scrollTop, clientHeight, totalCount, estimateSize, overscan, columns = 1) {
3214
- if (totalCount <= 0 || clientHeight <= 0) {
3648
+ function computeRange(scrollTop, clientHeight, totalCount, estimateSize, overscanBefore, columns = 1, overscanAfter = overscanBefore) {
3649
+ if (totalCount <= 0) {
3215
3650
  return EMPTY_RANGE;
3216
3651
  }
3652
+ if (clientHeight <= 0) {
3653
+ // Degenerate viewport (0px). A content-driven scrollport gets its height
3654
+ // FROM the spacers this result sizes, so reporting `totalSize: 0` here
3655
+ // deadlocks: no spacer, no height, no spacer. Report the full totalSize
3656
+ // with an empty window instead - the after-spacer gives the viewport its
3657
+ // height, the ResizeObserver-fed `clientHeight` turns non-zero, and the
3658
+ // next computation renders the real range.
3659
+ const totalSize = estimateTotalSize(totalCount, estimateSize, columns);
3660
+ return { start: 0, end: 0, offsetBefore: 0, offsetAfter: totalSize, totalSize };
3661
+ }
3217
3662
  if (typeof estimateSize === 'number') {
3218
- return computeFixedRange(scrollTop, clientHeight, totalCount, estimateSize, overscan, columns);
3663
+ return computeFixedRange(scrollTop, clientHeight, totalCount, estimateSize, overscanBefore, overscanAfter, columns);
3219
3664
  }
3220
3665
  // variable heights: grid mode unsupported, columns ignored
3221
- return computeVariableRange(scrollTop, clientHeight, totalCount, estimateSize, overscan);
3666
+ return computeVariableRange(scrollTop, clientHeight, totalCount, estimateSize, overscanBefore, overscanAfter);
3667
+ }
3668
+ function estimateTotalSize(totalCount, estimateSize, columns) {
3669
+ if (typeof estimateSize === 'number') {
3670
+ const rows = columns > 1 ? Math.ceil(totalCount / columns) : totalCount;
3671
+ return rows * estimateSize;
3672
+ }
3673
+ // variable heights: grid mode unsupported, columns ignored (same contract
3674
+ // as computeVariableRange)
3675
+ let totalSize = 0;
3676
+ for (let i = 0; i < totalCount; i++) {
3677
+ totalSize += estimateSize(i);
3678
+ }
3679
+ return totalSize;
3222
3680
  }
3223
- function computeFixedRange(scrollTop, clientHeight, totalCount, itemSize, overscan, columns) {
3681
+ function computeFixedRange(scrollTop, clientHeight, totalCount, itemSize, overscanBefore, overscanAfter, columns) {
3224
3682
  if (columns > 1) {
3225
- return computeGridRange(scrollTop, clientHeight, totalCount, itemSize, overscan, columns);
3683
+ return computeGridRange(scrollTop, clientHeight, totalCount, itemSize, overscanBefore, overscanAfter, columns);
3226
3684
  }
3227
3685
  const totalSize = totalCount * itemSize;
3228
3686
  const rawStart = Math.floor(scrollTop / itemSize);
3229
3687
  const rawEnd = Math.ceil((scrollTop + clientHeight) / itemSize);
3230
- const start = Math.max(0, rawStart - overscan);
3231
- const end = Math.min(totalCount, rawEnd + overscan);
3688
+ const start = Math.max(0, rawStart - overscanBefore);
3689
+ const end = Math.min(totalCount, rawEnd + overscanAfter);
3232
3690
  return {
3233
3691
  start,
3234
3692
  end,
@@ -3245,16 +3703,17 @@ function computeFixedRange(scrollTop, clientHeight, totalCount, itemSize, oversc
3245
3703
  *
3246
3704
  * @internal
3247
3705
  */
3248
- function computeGridRange(scrollTop, clientHeight, totalCount, rowHeight, overscan, columns) {
3706
+ function computeGridRange(scrollTop, clientHeight, totalCount, rowHeight, overscanBefore, overscanAfter, columns) {
3249
3707
  const totalRows = Math.ceil(totalCount / columns);
3250
3708
  const totalSize = totalRows * rowHeight;
3251
3709
  // raw rows (inherently row-aligned)
3252
3710
  const rawStartRow = Math.floor(scrollTop / rowHeight);
3253
3711
  const rawEndRow = Math.ceil((scrollTop + clientHeight) / rowHeight);
3254
3712
  // overscan applied in rows so full rows always render
3255
- const overscanRows = Math.ceil(overscan / columns);
3256
- const startRow = Math.max(0, rawStartRow - overscanRows);
3257
- const endRow = Math.min(totalRows, rawEndRow + overscanRows);
3713
+ const overscanRowsBefore = Math.ceil(overscanBefore / columns);
3714
+ const overscanRowsAfter = Math.ceil(overscanAfter / columns);
3715
+ const startRow = Math.max(0, rawStartRow - overscanRowsBefore);
3716
+ const endRow = Math.min(totalRows, rawEndRow + overscanRowsAfter);
3258
3717
  const start = startRow * columns;
3259
3718
  const end = Math.min(endRow * columns, totalCount);
3260
3719
  return {
@@ -3265,7 +3724,7 @@ function computeGridRange(scrollTop, clientHeight, totalCount, rowHeight, oversc
3265
3724
  totalSize,
3266
3725
  };
3267
3726
  }
3268
- function computeVariableRange(scrollTop, clientHeight, totalCount, estimateSize, overscan) {
3727
+ function computeVariableRange(scrollTop, clientHeight, totalCount, estimateSize, overscanBefore, overscanAfter) {
3269
3728
  let totalSize = 0;
3270
3729
  const offsets = new Array(totalCount + 1);
3271
3730
  offsets[0] = 0;
@@ -3276,8 +3735,8 @@ function computeVariableRange(scrollTop, clientHeight, totalCount, estimateSize,
3276
3735
  // binary search: first item whose bottom edge is past scrollTop
3277
3736
  const rawStart = binarySearch(offsets, scrollTop, totalCount);
3278
3737
  const rawEnd = binarySearch(offsets, scrollTop + clientHeight, totalCount);
3279
- const start = Math.max(0, rawStart - overscan);
3280
- const end = Math.min(totalCount, rawEnd + 1 + overscan);
3738
+ const start = Math.max(0, rawStart - overscanBefore);
3739
+ const end = Math.min(totalCount, rawEnd + 1 + overscanAfter);
3281
3740
  return {
3282
3741
  start,
3283
3742
  end,
@@ -3348,28 +3807,21 @@ function createScrollObserver(elementRef, destroyRef) {
3348
3807
  elementState.set(el);
3349
3808
  scrollTopState.set(el.scrollTop);
3350
3809
  clientHeightState.set(el.clientHeight);
3351
- let rafId = null;
3810
+ // Read scrollTop synchronously on the scroll event rather than deferring to
3811
+ // a requestAnimationFrame. The rAF hop delayed the range by a frame, so a
3812
+ // fast scroll outran the rendered window and flashed a blank strip. Scroll
3813
+ // events already fire at most once per frame, and the signal scheduler
3814
+ // coalesces bursts, so the synchronous read carries no extra recompute cost.
3352
3815
  const handleScroll = () => {
3353
- if (rafId != null) {
3354
- return;
3355
- }
3356
- rafId = requestAnimationFrame(() => {
3357
- rafId = null;
3358
- scrollTopState.set(el.scrollTop);
3359
- clientHeightState.set(el.clientHeight);
3360
- });
3816
+ scrollTopState.set(el.scrollTop);
3361
3817
  };
3362
3818
  el.addEventListener('scroll', handleScroll, { passive: true });
3363
- const resizeObserver = new ResizeObserver(() => {
3819
+ const stopResize = observeResize(doc.defaultView, el, 'content-box', () => {
3364
3820
  clientHeightState.set(el.clientHeight);
3365
3821
  });
3366
- resizeObserver.observe(el);
3367
3822
  onCleanup(() => {
3368
3823
  el.removeEventListener('scroll', handleScroll);
3369
- if (rafId != null) {
3370
- cancelAnimationFrame(rafId);
3371
- }
3372
- resizeObserver.disconnect();
3824
+ stopResize();
3373
3825
  elementState.set(null);
3374
3826
  });
3375
3827
  }
@@ -3406,8 +3858,12 @@ function createScrollObserver(elementRef, destroyRef) {
3406
3858
  if (typeof elementRef !== 'string' || typeof MutationObserver === 'undefined') {
3407
3859
  return;
3408
3860
  }
3409
- if (isDevMode()) {
3410
- console.warn(`recycler scrollElement '${elementRef}' not found on first render; ` +
3861
+ // Mounted between the first effect run and now: the bump above attaches it.
3862
+ if (resolveElement(elementRef, doc) != null) {
3863
+ return;
3864
+ }
3865
+ if (typeof ngDevMode !== 'undefined' && ngDevMode) {
3866
+ cngxDevWarn('CNGX1013', `injectRecycler(): scrollElement '${elementRef}' not found on first render; ` +
3411
3867
  'it will attach automatically once it mounts. If it never does, check the selector.');
3412
3868
  }
3413
3869
  mutationObserver = new MutationObserver(() => {
@@ -3483,9 +3939,27 @@ function createSizeCache() {
3483
3939
  };
3484
3940
  }
3485
3941
 
3942
+ /** @internal Turns a recycler section into the token's keys for a locale. */
3943
+ function recyclerBundleFrom(section, locale) {
3944
+ return {
3945
+ loaded: (count, total) => formatMessage(section.loaded, { count, total }, locale),
3946
+ filtered: (count) => formatMessage(section.filtered, { count }, locale),
3947
+ empty: () => section.empty,
3948
+ error: () => section.error,
3949
+ };
3950
+ }
3951
+ /** @internal The recycler section of the active pack over English. */
3952
+ const injectRecyclerSection = createLanguageSection('recycler', CNGX_RECYCLER_LANGUAGE_EN);
3953
+ /** @internal Builds and reads the token, formatted for the reading locale. */
3954
+ const recyclerBundle = createSectionBundle({
3955
+ section: injectRecyclerSection,
3956
+ toBundle: recyclerBundleFrom,
3957
+ });
3486
3958
  /**
3487
- * Injection token for recycler SR announcement texts.
3488
- * Provides English defaults via factory. Override with `provideRecyclerI18n()`.
3959
+ * Injection token for recycler SR announcement texts, a `Signal` so the
3960
+ * texts follow a runtime language switch. Defaults to the recycler section
3961
+ * of the active language pack over English, counts formatted for the app
3962
+ * locale. Override with `provideRecyclerI18n()`.
3489
3963
  *
3490
3964
  * @category common/data/recycler
3491
3965
  * @wcag AA
@@ -3493,29 +3967,44 @@ function createSizeCache() {
3493
3967
  * @since 0.1.0
3494
3968
  */
3495
3969
  const CNGX_RECYCLER_I18N = new InjectionToken('CngxRecyclerI18n', {
3496
- factory: () => ({
3497
- loaded: (n, t) => `${n} more items loaded. ${t} total.`,
3498
- filtered: (c) => `${c} results found.`,
3499
- empty: () => 'No results.',
3500
- error: () => 'Error loading data.',
3501
- }),
3970
+ factory: () => recyclerBundle.build(),
3502
3971
  });
3972
+ /** @internal */
3973
+ function defineRecyclerI18nFeature(fn) {
3974
+ return Object.assign(fn, { _target: 'i18n' });
3975
+ }
3503
3976
  /**
3504
- * Provider function for custom recycler i18n texts.
3977
+ * Override recycler announcements via a partial bundle - keys you leave out
3978
+ * keep the language pack's text, or the English default. Pass a `Signal` to
3979
+ * switch the language at runtime.
3980
+ *
3981
+ * @category common/data/recycler
3982
+ */
3983
+ function withRecyclerI18nLabels(overrides) {
3984
+ return defineRecyclerI18nFeature((bundle) => createOverrideMerge(bundle, overrides));
3985
+ }
3986
+ /**
3987
+ * Provider for the recycler announcement texts. The features apply on top of
3988
+ * the active language pack.
3505
3989
  *
3506
3990
  * ```typescript
3507
- * providers: [provideRecyclerI18n({
3508
- * loaded: (n, t) => `${n} weitere Einträge. ${t} gesamt.`,
3509
- * filtered: (c) => `${c} Ergebnisse.`,
3510
- * empty: () => 'Keine Ergebnisse.',
3511
- * error: () => 'Fehler beim Laden.',
3512
- * })]
3991
+ * providers: [
3992
+ * provideRecyclerI18n(
3993
+ * withRecyclerI18nLabels({
3994
+ * empty: () => 'Keine Ergebnisse.',
3995
+ * error: () => 'Fehler beim Laden.',
3996
+ * }),
3997
+ * ),
3998
+ * ]
3513
3999
  * ```
3514
4000
  *
3515
4001
  * @category common/data/recycler
3516
4002
  */
3517
- function provideRecyclerI18n(i18n) {
3518
- return { provide: CNGX_RECYCLER_I18N, useValue: i18n };
4003
+ function provideRecyclerI18n(...features) {
4004
+ return {
4005
+ provide: CNGX_RECYCLER_I18N,
4006
+ useFactory: () => recyclerBundle.build(features),
4007
+ };
3519
4008
  }
3520
4009
  /**
3521
4010
  * Creates a Signal-based virtualizer for DOM recycling.
@@ -3548,11 +4037,11 @@ function provideRecyclerI18n(i18n) {
3548
4037
  */
3549
4038
  function injectRecycler(config) {
3550
4039
  const destroyRef = inject(DestroyRef);
3551
- const i18n = inject(CNGX_RECYCLER_I18N);
4040
+ const i18n = recyclerBundle.resolve(inject(CNGX_RECYCLER_I18N));
3552
4041
  const overscan = config.overscan ?? 5;
3553
4042
  const isGrid = (config.layout ?? 'list') === 'grid';
3554
- if (isGrid && config.columns == null && isDevMode()) {
3555
- console.error('[CngxRecycler] layout: "grid" requires explicit `columns`. Falling back to columns=1.');
4043
+ if (typeof ngDevMode !== 'undefined' && ngDevMode && isGrid && config.columns == null) {
4044
+ cngxDevError('CNGX1011', 'injectRecycler(): layout: "grid" requires explicit `columns`. Falling back to columns=1.');
3556
4045
  }
3557
4046
  // Reactive columns - reactive only if the function reads a Signal internally
3558
4047
  const columns = computed(() => {
@@ -3565,12 +4054,13 @@ function injectRecycler(config) {
3565
4054
  // per-index measurement - it carries no O(n) per-frame cost, so exclude it
3566
4055
  // from the variable-height warning (a reactive scalar estimate is a
3567
4056
  // sanctioned pattern; see the resolveSize note below).
3568
- if (typeof config.estimateSize === 'function' &&
3569
- !isSignal(config.estimateSize) &&
3570
- isDevMode()) {
4057
+ if (typeof ngDevMode !== 'undefined' &&
4058
+ ngDevMode &&
4059
+ typeof config.estimateSize === 'function' &&
4060
+ !isSignal(config.estimateSize)) {
3571
4061
  const count = config.totalCount();
3572
4062
  if (count > 10_000) {
3573
- console.warn(`[CngxRecycler] estimateSize as a function with ${count} items has O(n) ` +
4063
+ cngxDevWarn('CNGX1012', `injectRecycler(): estimateSize as a function with ${count} items has O(n) ` +
3574
4064
  `per-frame cost. Consider using a fixed estimateSize for large datasets.`);
3575
4065
  }
3576
4066
  }
@@ -3583,12 +4073,40 @@ function injectRecycler(config) {
3583
4073
  sizeCache.version(); // track dependency
3584
4074
  return sizeCache.resolve(index, config.estimateSize);
3585
4075
  };
4076
+ // Signed scroll delta between consecutive scrollTop updates. A fast flick
4077
+ // produces large per-event deltas, so this doubles as a velocity proxy
4078
+ // regardless of whether scrollTop is sampled per-frame or per-event.
4079
+ const scrollVelocity = signal(0, ...(ngDevMode ? [{ debugName: "scrollVelocity" }] : /* istanbul ignore next */ []));
4080
+ let lastScrollTop = 0;
4081
+ effect(() => {
4082
+ const st = scrollState.scrollTop();
4083
+ untracked(() => {
4084
+ scrollVelocity.set(st - lastScrollTop);
4085
+ lastScrollTop = st;
4086
+ });
4087
+ });
3586
4088
  // Grid mode uses raw estimateSize (uniform row height, no SizeCache).
3587
4089
  // List mode uses resolveSize (SizeCache-backed).
3588
4090
  const range = computed(() => {
3589
4091
  const cols = columns();
3590
4092
  const size = isGrid ? config.estimateSize : resolveSize;
3591
- return computeRange(scrollState.scrollTop(), scrollState.clientHeight(), config.totalCount(), size, overscan, cols);
4093
+ const scrollTop = scrollState.scrollTop();
4094
+ const clientHeight = scrollState.clientHeight();
4095
+ const total = config.totalCount();
4096
+ // Directional overscan: the rendered range trails scroll by up to a frame,
4097
+ // so pre-render extra items into the scroll direction to keep the leading
4098
+ // edge populated (otherwise a fast scroll flashes a blank strip). Scale the
4099
+ // lead with velocity, capped at one viewport of items so a teleport jump
4100
+ // never expands the window unbounded. Trailing edge keeps the base overscan.
4101
+ const estimate = config.estimateSize;
4102
+ const refPx = typeof estimate === 'number' && estimate > 0 ? estimate : Math.max(1, clientHeight / 8);
4103
+ const itemsPerViewport = Math.max(1, Math.ceil(clientHeight / refPx));
4104
+ const velocity = scrollVelocity();
4105
+ const leadItems = Math.min(Math.ceil(Math.abs(velocity) / refPx), itemsPerViewport);
4106
+ const scrollingDown = velocity >= 0;
4107
+ const overscanBefore = overscan + (scrollingDown ? 0 : leadItems);
4108
+ const overscanAfter = overscan + (scrollingDown ? leadItems : 0);
4109
+ return computeRange(scrollTop, clientHeight, total, size, overscanBefore, cols, overscanAfter);
3592
4110
  }, ...(ngDevMode ? [{ debugName: "range" }] : /* istanbul ignore next */ []));
3593
4111
  const start = computed(() => range().start, ...(ngDevMode ? [{ debugName: "start" }] : /* istanbul ignore next */ []));
3594
4112
  const end = computed(() => range().end, ...(ngDevMode ? [{ debugName: "end" }] : /* istanbul ignore next */ []));
@@ -3596,6 +4114,23 @@ function injectRecycler(config) {
3596
4114
  const offsetBefore = computed(() => (isGrid ? 0 : range().offsetBefore), ...(ngDevMode ? [{ debugName: "offsetBefore" }] : /* istanbul ignore next */ []));
3597
4115
  const offsetAfter = computed(() => (isGrid ? 0 : range().offsetAfter), ...(ngDevMode ? [{ debugName: "offsetAfter" }] : /* istanbul ignore next */ []));
3598
4116
  const totalSize = computed(() => range().totalSize, ...(ngDevMode ? [{ debugName: "totalSize" }] : /* istanbul ignore next */ []));
4117
+ // Representative row height for a placeholder layer's repeat interval. Derived,
4118
+ // never stored: a uniform estimate (number or signal) is the rhythm directly;
4119
+ // a per-index estimate has no single height, so the running average stands in.
4120
+ const rowSizeHint = computed(() => {
4121
+ const estimate = config.estimateSize;
4122
+ if (typeof estimate === 'number') {
4123
+ return estimate;
4124
+ }
4125
+ if (isSignal(estimate)) {
4126
+ return estimate();
4127
+ }
4128
+ const total = config.totalCount();
4129
+ if (total <= 0) {
4130
+ return 0;
4131
+ }
4132
+ return totalSize() / total;
4133
+ }, ...(ngDevMode ? [{ debugName: "rowSizeHint" }] : /* istanbul ignore next */ []));
3599
4134
  const placeholdersBefore = computed(() => (isGrid ? start() : 0), ...(ngDevMode ? [{ debugName: "placeholdersBefore" }] : /* istanbul ignore next */ []));
3600
4135
  const placeholdersAfter = computed(() => (isGrid ? Math.max(0, config.totalCount() - end()) : 0), ...(ngDevMode ? [{ debugName: "placeholdersAfter" }] : /* istanbul ignore next */ []));
3601
4136
  // start/end include overscan. firstVisible/lastVisible strip it back
@@ -3620,7 +4155,7 @@ function injectRecycler(config) {
3620
4155
  if (total === 0) {
3621
4156
  return 0;
3622
4157
  }
3623
- return Math.min(Math.max(0, end() - effectiveOverscan() - 1), total - 1);
4158
+ return clamp(end() - effectiveOverscan() - 1, 0, total - 1);
3624
4159
  }, ...(ngDevMode ? [{ debugName: "lastVisible" }] : /* istanbul ignore next */ []));
3625
4160
  const visibleCount = computed(() => {
3626
4161
  const total = config.totalCount();
@@ -3664,21 +4199,24 @@ function injectRecycler(config) {
3664
4199
  if (previous === current) {
3665
4200
  return;
3666
4201
  }
3667
- if (current === 'success' && (previous === 'loading' || previous === 'refreshing')) {
3668
- const diff = total - prevTotal;
3669
- if (diff > 0) {
3670
- announcementState.set(i18n.loaded(diff, total));
4202
+ // Copy is read untracked: a language switch must not re-run the
4203
+ // effect and re-voice the region; the next transition speaks it.
4204
+ untracked(() => {
4205
+ const copy = i18n();
4206
+ // Route by result first: a load that settles with zero items is the
4207
+ // empty phrase, no matter which busy status preceded it - "0 results
4208
+ // found" is the filtered phrase, not the empty one.
4209
+ if (current === 'success' && total === 0) {
4210
+ announcementState.set(copy.empty());
3671
4211
  }
3672
- else {
3673
- announcementState.set(i18n.filtered(total));
4212
+ else if (current === 'success' && (previous === 'loading' || previous === 'refreshing')) {
4213
+ const diff = total - prevTotal;
4214
+ announcementState.set(diff > 0 ? copy.loaded(diff, total) : copy.filtered(total));
3674
4215
  }
3675
- }
3676
- else if (current === 'error') {
3677
- announcementState.set(i18n.error());
3678
- }
3679
- else if (current === 'success' && total === 0) {
3680
- announcementState.set(i18n.empty());
3681
- }
4216
+ else if (current === 'error') {
4217
+ announcementState.set(copy.error());
4218
+ }
4219
+ });
3682
4220
  untracked(() => previousTotal.set(total));
3683
4221
  });
3684
4222
  }
@@ -3689,12 +4227,15 @@ function injectRecycler(config) {
3689
4227
  // untracked: previousTotal is bookkeeping, not a dependency
3690
4228
  const prevTotal = untracked(() => previousTotal());
3691
4229
  const diff = total - prevTotal;
3692
- if (prevTotal > 0 && diff > 0) {
3693
- announcementState.set(i18n.loaded(diff, total));
3694
- }
3695
- else if (prevTotal > 0 && total === 0) {
3696
- announcementState.set(i18n.empty());
3697
- }
4230
+ untracked(() => {
4231
+ const copy = i18n();
4232
+ if (prevTotal > 0 && diff > 0) {
4233
+ announcementState.set(copy.loaded(diff, total));
4234
+ }
4235
+ else if (prevTotal > 0 && total === 0) {
4236
+ announcementState.set(copy.empty());
4237
+ }
4238
+ });
3698
4239
  untracked(() => previousTotal.set(total));
3699
4240
  });
3700
4241
  }
@@ -3796,6 +4337,7 @@ function injectRecycler(config) {
3796
4337
  offsetBefore,
3797
4338
  offsetAfter,
3798
4339
  totalSize,
4340
+ rowSizeHint,
3799
4341
  placeholdersBefore,
3800
4342
  placeholdersAfter,
3801
4343
  isLoading,
@@ -3893,19 +4435,19 @@ class CngxMeasure {
3893
4435
  /** The absolute index of this item in the full dataset. */
3894
4436
  cngxMeasureIndex = input.required(...(ngDevMode ? [{ debugName: "cngxMeasureIndex" }] : /* istanbul ignore next */ []));
3895
4437
  el = inject((ElementRef));
4438
+ win = inject(DOCUMENT).defaultView;
3896
4439
  constructor() {
3897
4440
  effect((onCleanup) => {
3898
4441
  const recycler = this.cngxMeasure();
3899
4442
  const index = this.cngxMeasureIndex();
3900
4443
  const element = this.el.nativeElement;
3901
4444
  recycler.measure(index, element);
3902
- const observer = new ResizeObserver(() => {
4445
+ // The observed element follows the inputs, so the subscription is
4446
+ // re-wired per effect run - the low-level kernel form, not the
4447
+ // DestroyRef-scoped one.
4448
+ onCleanup(observeResize(this.win, element, 'content-box', () => {
3903
4449
  recycler.measure(index, element);
3904
- });
3905
- observer.observe(element);
3906
- onCleanup(() => {
3907
- observer.disconnect();
3908
- });
4450
+ }));
3909
4451
  });
3910
4452
  }
3911
4453
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxMeasure, deps: [], target: i0.ɵɵFactoryTarget.Directive });
@@ -3980,6 +4522,380 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
3980
4522
  }]
3981
4523
  }], propDecorators: { cngxVirtualItem: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxVirtualItem", required: true }] }], cngxVirtualItemIndex: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxVirtualItemIndex", required: true }] }] } });
3982
4524
 
4525
+ /**
4526
+ * Paints a row-aligned skeleton background under a virtualized scroll region so
4527
+ * a fast fling or teleport jump reveals placeholder bars instead of the bare
4528
+ * panel/page surface for the single frame the rendered rows lag `scrollTop`.
4529
+ *
4530
+ * The mechanism is a static CSS layer, not a reactive template: by the time a
4531
+ * `@for` over "uncovered indices" could render, change detection has already
4532
+ * produced the real rows, so the lag frame is never painted reactively. A
4533
+ * `background` on the offset element always paints and also covers teleport
4534
+ * jumps no reactive window can, at zero per-frame cost.
4535
+ *
4536
+ * Host it on the **offset spacer element(s)** - the empty divs (or presentation
4537
+ * `<li>`s) whose height reserves `offsetBefore` / `offsetAfter` - one directive
4538
+ * instance per spacer. Do NOT host it on a `padding-block`ed content element
4539
+ * that also contains the rows: a background paints across the whole padding box,
4540
+ * so it would show through *behind* every rendered row, not just in the gap.
4541
+ * The spacers carry no rows, so the layer is only ever visible where the window
4542
+ * has not caught up.
4543
+ *
4544
+ * The repeat interval keys off a single representative row height: bind the
4545
+ * recycler to read its `rowSizeHint`, or pass an explicit `[rowHeight]`
4546
+ * fallback so the directive is usable standalone. Visuals are driven by
4547
+ * `--cngx-recycler-placeholder-*` CSS custom properties (see
4548
+ * `@cngx/common/theming/components/cngx-recycler-placeholder.css`); the shimmer
4549
+ * drops under `prefers-reduced-motion` via a spec-observable host class.
4550
+ *
4551
+ * ### One instance per offset spacer, keyed off the recycler's rhythm
4552
+ * ```html
4553
+ * <ul>
4554
+ * @if (recycler.offsetBefore(); as before) {
4555
+ * <li role="presentation" aria-hidden="true"
4556
+ * [cngxRecyclerPlaceholder]="recycler" [style.height.px]="before"></li>
4557
+ * }
4558
+ * @for (item of visibleItems(); track item.id) { <li>...</li> }
4559
+ * @if (recycler.offsetAfter(); as after) {
4560
+ * <li role="presentation" aria-hidden="true"
4561
+ * [cngxRecyclerPlaceholder]="recycler" [style.height.px]="after"></li>
4562
+ * }
4563
+ * </ul>
4564
+ * ```
4565
+ *
4566
+ * ### Standalone with an explicit row height
4567
+ * ```html
4568
+ * <div cngxRecyclerPlaceholder [rowHeight]="48"
4569
+ * [style.height.px]="recycler.offsetBefore()"></div>
4570
+ * ```
4571
+ *
4572
+ * @category common/data/recycler
4573
+ * @docsKind primary
4574
+ * @wcag AA
4575
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/data/recycler/recycler-placeholder.directive.ts
4576
+ * @since 0.1.0
4577
+ * @relatedTo injectRecycler, CngxRecyclerRow, CngxVirtualItem, CngxMeasure
4578
+ * <example-url>http://localhost:4200/#/common/data/recycler/fast-fling-placeholders</example-url>
4579
+ */
4580
+ class CngxRecyclerPlaceholder {
4581
+ /**
4582
+ * The recycler whose `rowSizeHint` sets the placeholder repeat rhythm.
4583
+ * Optional: the directive also works from an explicit `[rowHeight]`, so this
4584
+ * follows the bridge-input shape (optional + empty-string transform) rather
4585
+ * than `input.required` - a bare `cngxRecyclerPlaceholder` attribute paired
4586
+ * with `[rowHeight]` is a valid, unbound usage.
4587
+ */
4588
+ recycler = input(undefined, { ...(ngDevMode ? { debugName: "recycler" } : /* istanbul ignore next */ {}), alias: 'cngxRecyclerPlaceholder',
4589
+ transform: (value) => (typeof value === 'string' ? undefined : value) });
4590
+ /** Explicit row height (px) used when no recycler is bound, or as a fallback. */
4591
+ rowHeight = input(undefined, ...(ngDevMode ? [{ debugName: "rowHeight" }] : /* istanbul ignore next */ []));
4592
+ prefersReducedMotion;
4593
+ constructor() {
4594
+ this.prefersReducedMotion = createMediaQuerySignal('(prefers-reduced-motion: reduce)', inject(DestroyRef), inject(DOCUMENT).defaultView);
4595
+ }
4596
+ /**
4597
+ * Representative row height (px) for the repeat interval. The recycler's
4598
+ * `rowSizeHint` wins when it resolves to a positive value; otherwise the
4599
+ * explicit `[rowHeight]` fallback applies.
4600
+ */
4601
+ resolvedRowHeight = computed(() => {
4602
+ const fromRecycler = this.recycler()?.rowSizeHint() ?? 0;
4603
+ if (fromRecycler > 0) {
4604
+ return fromRecycler;
4605
+ }
4606
+ return this.rowHeight() ?? 0;
4607
+ }, ...(ngDevMode ? [{ debugName: "resolvedRowHeight" }] : /* istanbul ignore next */ []));
4608
+ /**
4609
+ * The `--cngx-recycler-placeholder-row-height` style value. `null` when no
4610
+ * row height resolves, so the registered `@property` default (or an inherited
4611
+ * token from an ancestor mapping) applies instead of a broken `0px` interval.
4612
+ */
4613
+ rowHeightVar = computed(() => {
4614
+ const height = this.resolvedRowHeight();
4615
+ return height > 0 ? `${height}px` : null;
4616
+ }, ...(ngDevMode ? [{ debugName: "rowHeightVar" }] : /* istanbul ignore next */ []));
4617
+ /** Whether the shimmer host class is applied (dropped under reduced-motion). */
4618
+ showShimmer = computed(() => !this.prefersReducedMotion(), ...(ngDevMode ? [{ debugName: "showShimmer" }] : /* istanbul ignore next */ []));
4619
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRecyclerPlaceholder, deps: [], target: i0.ɵɵFactoryTarget.Directive });
4620
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxRecyclerPlaceholder, isStandalone: true, selector: "[cngxRecyclerPlaceholder]", inputs: { recycler: { classPropertyName: "recycler", publicName: "cngxRecyclerPlaceholder", isSignal: true, isRequired: false, transformFunction: null }, rowHeight: { classPropertyName: "rowHeight", publicName: "rowHeight", isSignal: true, isRequired: false, transformFunction: null } }, host: { attributes: { "aria-hidden": "true" }, properties: { "class.cngx-recycler-placeholder--shimmer": "showShimmer()", "style.--cngx-recycler-placeholder-row-height": "rowHeightVar()" }, classAttribute: "cngx-recycler-placeholder" }, ngImport: i0 });
4621
+ }
4622
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRecyclerPlaceholder, decorators: [{
4623
+ type: Directive,
4624
+ args: [{
4625
+ selector: '[cngxRecyclerPlaceholder]',
4626
+ standalone: true,
4627
+ host: {
4628
+ class: 'cngx-recycler-placeholder',
4629
+ // The layer is a decorative background on an offset spacer. Hide it from the
4630
+ // a11y tree at the host so it stays out regardless of the call site, not only
4631
+ // when a consumer remembers to add aria-hidden.
4632
+ 'aria-hidden': 'true',
4633
+ '[class.cngx-recycler-placeholder--shimmer]': 'showShimmer()',
4634
+ '[style.--cngx-recycler-placeholder-row-height]': 'rowHeightVar()',
4635
+ },
4636
+ }]
4637
+ }], ctorParameters: () => [], propDecorators: { recycler: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxRecyclerPlaceholder", required: false }] }], rowHeight: [{ type: i0.Input, args: [{ isSignal: true, alias: "rowHeight", required: false }] }] } });
4638
+
4639
+ /**
4640
+ * App-wide default placeholder template for `*cngxRecyclerRow`. Middle rung of
4641
+ * the cascade: microsyntax `placeholder:` template wins over this, and this wins
4642
+ * over the built-in imperative `<li>` default. Defaults to `null` (imperative
4643
+ * default applies).
4644
+ *
4645
+ * @category common/data/recycler
4646
+ */
4647
+ const CNGX_RECYCLER_PLACEHOLDER_ROW = new InjectionToken('CNGX_RECYCLER_PLACEHOLDER_ROW', { providedIn: 'root', factory: () => null });
4648
+ /**
4649
+ * Provides an app-wide default placeholder template for every `*cngxRecyclerRow`
4650
+ * that supplies no `placeholder:` template of its own.
4651
+ *
4652
+ * @category common/data/recycler
4653
+ */
4654
+ function provideRecyclerPlaceholderRow(template) {
4655
+ return { provide: CNGX_RECYCLER_PLACEHOLDER_ROW, useValue: template };
4656
+ }
4657
+ /**
4658
+ * Per-window-position render switch for a sparse/windowed recycler: renders the
4659
+ * consumer's real-row template when the sliced item is defined, and a
4660
+ * placeholder branch when the item is still `undefined` (loaded window, data
4661
+ * not yet resolved).
4662
+ *
4663
+ * Mirrors the `*cngxAsync` structural-directive shape (own `TemplateRef` +
4664
+ * microsyntax alternate template + `ngTemplateContextGuard`). The switch axis is
4665
+ * data availability, not async status, so the two are siblings, not the same
4666
+ * class. Unlike `*cngxAsync` (which clears on every switch) the real-row view is
4667
+ * cached and re-attached across a placeholder detour, so a
4668
+ * defined -> undefined -> defined flip never remounts the expensive real row.
4669
+ *
4670
+ * The placeholder branch resolves through a 3-stage cascade: the microsyntax
4671
+ * `placeholder:` template, then {@link CNGX_RECYCLER_PLACEHOLDER_ROW}, then a
4672
+ * built-in imperative `<li>` default. The default assumes a `<ul>`/`<li>` list;
4673
+ * a non-`<li>` container (`<div role="list">`) supplies a `placeholder:`
4674
+ * template or the config token instead.
4675
+ *
4676
+ * The two placeholder layers are orthogonal and non-overlapping by
4677
+ * construction: {@link CngxRecyclerPlaceholder} paints a decorative background
4678
+ * on the offset spacers (indices outside the rendered window), while this
4679
+ * directive fills holes inside the window whose item is still `undefined`.
4680
+ *
4681
+ * ### Windowed list with the built-in placeholder row
4682
+ * ```html
4683
+ * <ul>
4684
+ * @for (item of visibleItems(); track item?.id ?? ('ph:' + (recycler.start() + $index)); let i = $index) {
4685
+ * <li *cngxRecyclerRow="item; index: recycler.start() + i; recycler: recycler; let row">
4686
+ * {{ row?.name }}
4687
+ * </li>
4688
+ * }
4689
+ * </ul>
4690
+ * ```
4691
+ *
4692
+ * ### Custom placeholder template
4693
+ * ```html
4694
+ * <ul>
4695
+ * @for (item of visibleItems(); track item?.id ?? ('ph:' + (recycler.start() + $index)); let i = $index) {
4696
+ * <li *cngxRecyclerRow="item; index: recycler.start() + i; recycler: recycler; placeholder: ph; let row">
4697
+ * {{ row?.name }}
4698
+ * </li>
4699
+ * }
4700
+ * <ng-template #ph let-index let-setSize="setSize">
4701
+ * <li role="listitem" aria-busy="true" [attr.aria-posinset]="index + 1" [attr.aria-setsize]="setSize">
4702
+ * Loading row {{ index + 1 }}
4703
+ * </li>
4704
+ * </ng-template>
4705
+ * </ul>
4706
+ * ```
4707
+ *
4708
+ * @category common/data/recycler
4709
+ * @docsKind primary
4710
+ * @wcag AA
4711
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/data/recycler/recycler-row.directive.ts
4712
+ * @since 0.1.0
4713
+ * @relatedTo injectRecycler, CngxRecyclerPlaceholder, CngxVirtualItem, CngxMeasure
4714
+ * <example-url>http://localhost:4200/#/common/data/recycler/windowed-data-availability</example-url>
4715
+ */
4716
+ class CngxRecyclerRow {
4717
+ vcr = inject(ViewContainerRef);
4718
+ rowTpl = inject(TemplateRef);
4719
+ renderer = inject(Renderer2);
4720
+ configTpl = inject(CNGX_RECYCLER_PLACEHOLDER_ROW);
4721
+ /** The sliced item at this window position. `undefined` selects the placeholder branch. */
4722
+ cngxRecyclerRow = input(undefined, ...(ngDevMode ? [{ debugName: "cngxRecyclerRow" }] : /* istanbul ignore next */ []));
4723
+ /** Absolute dataset index of this slot (`recycler.start() + $index`). */
4724
+ cngxRecyclerRowIndex = input.required(...(ngDevMode ? [{ debugName: "cngxRecyclerRowIndex" }] : /* istanbul ignore next */ []));
4725
+ /** The recycler driving the window, read for `rowSizeHint` (-> `top`) and `ariaSetSize`. */
4726
+ cngxRecyclerRowRecycler = input.required(...(ngDevMode ? [{ debugName: "cngxRecyclerRowRecycler" }] : /* istanbul ignore next */ []));
4727
+ /** Optional placeholder template for the `undefined` branch. Context: {@link CngxRecyclerRowContext}. */
4728
+ cngxRecyclerRowPlaceholder = input(undefined, ...(ngDevMode ? [{ debugName: "cngxRecyclerRowPlaceholder" }] : /* istanbul ignore next */ []));
4729
+ // Plain fields, not signals: read and written only inside the render effect.
4730
+ // As signals they would feed the effect's own dependency graph and double-fire
4731
+ // per branch switch (the trap documented in async.directive.ts).
4732
+ currentBranch = 'none';
4733
+ rowViewRef = null;
4734
+ placeholderViewRef = null;
4735
+ defaultEl = null;
4736
+ constructor() {
4737
+ effect(() => {
4738
+ const item = this.cngxRecyclerRow();
4739
+ if (item === undefined) {
4740
+ // Placeholder branch tracks index + ariaSetSize (via buildPlaceholderContext)
4741
+ // so the announced position/size stay live while the slot remains unloaded
4742
+ // across a window shift or an infinite-scroll setSize growth - Pillar 2
4743
+ // keeps a11y in the reactive graph, never a one-time write. The row branch
4744
+ // tracks only the item value; the placeholder template ref is read untracked.
4745
+ this.showPlaceholder(this.buildPlaceholderContext());
4746
+ }
4747
+ else {
4748
+ this.showRow(item);
4749
+ }
4750
+ });
4751
+ inject(DestroyRef).onDestroy(() => {
4752
+ // The cached row view may be detached (not owned by the VCR), so the VCR
4753
+ // will not tear it down; destroy both views explicitly, guarding the
4754
+ // already-destroyed case when the VCR got there first.
4755
+ if (this.rowViewRef && !this.rowViewRef.destroyed) {
4756
+ this.rowViewRef.destroy();
4757
+ }
4758
+ this.teardownPlaceholder();
4759
+ });
4760
+ }
4761
+ showRow(item) {
4762
+ if (this.currentBranch === 'row') {
4763
+ this.setRowContext(item);
4764
+ this.rowViewRef?.markForCheck();
4765
+ return;
4766
+ }
4767
+ this.teardownPlaceholder();
4768
+ if (this.rowViewRef) {
4769
+ this.setRowContext(item);
4770
+ this.vcr.insert(this.rowViewRef);
4771
+ this.rowViewRef.markForCheck();
4772
+ }
4773
+ else {
4774
+ this.rowViewRef = this.vcr.createEmbeddedView(this.rowTpl, {
4775
+ $implicit: item,
4776
+ cngxRecyclerRow: item,
4777
+ });
4778
+ }
4779
+ this.currentBranch = 'row';
4780
+ }
4781
+ showPlaceholder(ctx) {
4782
+ if (this.currentBranch === 'placeholder') {
4783
+ this.refreshPlaceholder(ctx);
4784
+ return;
4785
+ }
4786
+ this.detachRow();
4787
+ this.renderPlaceholder(ctx);
4788
+ this.currentBranch = 'placeholder';
4789
+ }
4790
+ setRowContext(item) {
4791
+ if (this.rowViewRef) {
4792
+ this.rowViewRef.context.$implicit = item;
4793
+ this.rowViewRef.context.cngxRecyclerRow = item;
4794
+ }
4795
+ }
4796
+ // Remove the cached row view from the container WITHOUT destroying it, so the
4797
+ // next 'row' branch re-attaches the same EmbeddedViewRef (no remount).
4798
+ detachRow() {
4799
+ if (!this.rowViewRef) {
4800
+ return;
4801
+ }
4802
+ const at = this.vcr.indexOf(this.rowViewRef);
4803
+ if (at !== -1) {
4804
+ this.vcr.detach(at);
4805
+ }
4806
+ }
4807
+ teardownPlaceholder() {
4808
+ if (this.placeholderViewRef) {
4809
+ this.placeholderViewRef.destroy();
4810
+ this.placeholderViewRef = null;
4811
+ }
4812
+ this.removeDefault();
4813
+ }
4814
+ renderPlaceholder(ctx) {
4815
+ const tpl = untracked(() => this.cngxRecyclerRowPlaceholder()) ?? this.configTpl ?? null;
4816
+ if (tpl) {
4817
+ this.placeholderViewRef = this.vcr.createEmbeddedView(tpl, ctx);
4818
+ }
4819
+ else {
4820
+ this.stampDefault(ctx);
4821
+ }
4822
+ }
4823
+ // Slot stayed unloaded but its index/setSize moved: refresh the live a11y
4824
+ // position/size in place - custom template context or default element attrs -
4825
+ // without remounting the placeholder.
4826
+ refreshPlaceholder(ctx) {
4827
+ if (this.placeholderViewRef) {
4828
+ const context = this.placeholderViewRef.context;
4829
+ context.$implicit = ctx.$implicit;
4830
+ context.index = ctx.index;
4831
+ context.top = ctx.top;
4832
+ context.setSize = ctx.setSize;
4833
+ this.placeholderViewRef.markForCheck();
4834
+ }
4835
+ else if (this.defaultEl) {
4836
+ this.applyDefaultAttrs(this.defaultEl, ctx);
4837
+ }
4838
+ }
4839
+ // Terminal fallback: a module-level TemplateRef cannot exist, so the built-in
4840
+ // default is one imperative <li> reusing the shipped `cngx-recycler-placeholder`
4841
+ // ghost-row CSS. It holds a real dataset position, so it stays in the a11y tree
4842
+ // (aria-busy / role=listitem / posinset / setsize) - never aria-hidden.
4843
+ stampDefault(ctx) {
4844
+ const anchor = this.vcr.element.nativeElement;
4845
+ const parent = this.renderer.parentNode(anchor);
4846
+ if (!parent) {
4847
+ return;
4848
+ }
4849
+ const li = this.renderer.createElement('li');
4850
+ this.renderer.addClass(li, 'cngx-recycler-placeholder');
4851
+ this.renderer.setAttribute(li, 'role', 'listitem');
4852
+ this.renderer.setAttribute(li, 'aria-busy', 'true');
4853
+ this.applyDefaultAttrs(li, ctx);
4854
+ this.renderer.insertBefore(parent, li, anchor);
4855
+ this.defaultEl = li;
4856
+ }
4857
+ applyDefaultAttrs(li, ctx) {
4858
+ const height = untracked(() => this.cngxRecyclerRowRecycler().rowSizeHint());
4859
+ this.renderer.setAttribute(li, 'aria-posinset', String(ctx.index + 1));
4860
+ this.renderer.setAttribute(li, 'aria-setsize', String(ctx.setSize));
4861
+ this.renderer.setStyle(li, 'height', `${height}px`);
4862
+ this.renderer.setStyle(li, '--cngx-recycler-placeholder-row-height', `${height}px`);
4863
+ }
4864
+ removeDefault() {
4865
+ if (!this.defaultEl) {
4866
+ return;
4867
+ }
4868
+ const parent = this.renderer.parentNode(this.defaultEl);
4869
+ if (parent) {
4870
+ this.renderer.removeChild(parent, this.defaultEl);
4871
+ }
4872
+ this.defaultEl = null;
4873
+ }
4874
+ // Called only from the placeholder branch of the render effect: reading index
4875
+ // + ariaSetSize here (tracked) is what keeps the announced position/size
4876
+ // reactive. rowSizeHint is a stable layout hint, read untracked for `top`.
4877
+ buildPlaceholderContext() {
4878
+ const index = this.cngxRecyclerRowIndex();
4879
+ const recycler = this.cngxRecyclerRowRecycler();
4880
+ const setSize = recycler.ariaSetSize();
4881
+ const top = untracked(() => recycler.rowSizeHint()) * index;
4882
+ return { $implicit: index, index, top, setSize };
4883
+ }
4884
+ /** Narrows the directive's own template context to the loaded item type. */
4885
+ static ngTemplateContextGuard(_dir, _ctx) {
4886
+ return true;
4887
+ }
4888
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRecyclerRow, deps: [], target: i0.ɵɵFactoryTarget.Directive });
4889
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxRecyclerRow, isStandalone: true, selector: "[cngxRecyclerRow]", inputs: { cngxRecyclerRow: { classPropertyName: "cngxRecyclerRow", publicName: "cngxRecyclerRow", isSignal: true, isRequired: false, transformFunction: null }, cngxRecyclerRowIndex: { classPropertyName: "cngxRecyclerRowIndex", publicName: "cngxRecyclerRowIndex", isSignal: true, isRequired: true, transformFunction: null }, cngxRecyclerRowRecycler: { classPropertyName: "cngxRecyclerRowRecycler", publicName: "cngxRecyclerRowRecycler", isSignal: true, isRequired: true, transformFunction: null }, cngxRecyclerRowPlaceholder: { classPropertyName: "cngxRecyclerRowPlaceholder", publicName: "cngxRecyclerRowPlaceholder", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0 });
4890
+ }
4891
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRecyclerRow, decorators: [{
4892
+ type: Directive,
4893
+ args: [{
4894
+ selector: '[cngxRecyclerRow]',
4895
+ standalone: true,
4896
+ }]
4897
+ }], ctorParameters: () => [], propDecorators: { cngxRecyclerRow: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxRecyclerRow", required: false }] }], cngxRecyclerRowIndex: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxRecyclerRowIndex", required: true }] }], cngxRecyclerRowRecycler: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxRecyclerRowRecycler", required: true }] }], cngxRecyclerRowPlaceholder: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxRecyclerRowPlaceholder", required: false }] }] } });
4898
+
3983
4899
  /**
3984
4900
  * Convenience component that renders the `aria-live="polite"` region
3985
4901
  * for recycler SR announcements. Eliminates manual boilerplate.
@@ -4208,20 +5124,29 @@ function createCommitController() {
4208
5124
  const intendedState = signal(undefined, ...(ngDevMode ? [{ debugName: "intendedState" }] : /* istanbul ignore next */ []));
4209
5125
  return {
4210
5126
  state: slot,
4211
- isCommitting: computed(() => slot.isPending()),
5127
+ isCommitting: computed(() => slot.isPending(), typeof ngDevMode !== 'undefined' && ngDevMode
5128
+ ? { debugName: 'commitController.isCommitting' }
5129
+ : undefined),
4212
5130
  intendedValue: intendedState.asReadonly(),
4213
5131
  begin(runner, intended, previous, handlers) {
4214
- // tear down previous runner BEFORE bumping commitId, otherwise its
4215
- // supersede-check would pass and fire after all
4216
- active?.cancel();
5132
+ // bump commitId BEFORE tearing down the previous runner: a runner that
5133
+ // cancels synchronously would otherwise still pass the supersede check
5134
+ // and fire its callbacks after all
4217
5135
  const id = ++commitId;
5136
+ active?.cancel();
4218
5137
  intendedState.set(intended);
4219
5138
  slot.set('pending');
4220
- active = runner({
5139
+ // A runner may settle synchronously, i.e. before its handle is even
5140
+ // returned. The settled flag keeps such a finished handle out of
5141
+ // `active`, so a later begin()/cancel() never calls cancel() on a
5142
+ // completed runner (CngxCommitHandle does not require idempotence).
5143
+ let settled = false;
5144
+ const handle = runner({
4221
5145
  onSuccess: (committed) => {
4222
5146
  if (id !== commitId) {
4223
5147
  return;
4224
5148
  }
5149
+ settled = true;
4225
5150
  slot.setSuccess(committed);
4226
5151
  active = null;
4227
5152
  handlers.onSuccess(committed);
@@ -4230,21 +5155,93 @@ function createCommitController() {
4230
5155
  if (id !== commitId) {
4231
5156
  return;
4232
5157
  }
5158
+ settled = true;
4233
5159
  slot.setError(err);
4234
5160
  active = null;
4235
5161
  handlers.onError(err, previous);
4236
5162
  },
5163
+ onRefused: () => {
5164
+ if (id !== commitId) {
5165
+ return;
5166
+ }
5167
+ settled = true;
5168
+ slot.setIdle();
5169
+ intendedState.set(undefined);
5170
+ active = null;
5171
+ handlers.onRefused?.(previous);
5172
+ },
4237
5173
  });
5174
+ active = settled ? null : handle;
4238
5175
  },
4239
- cancel() {
5176
+ cancel(options) {
5177
+ // bump first: callbacks of a synchronously-cancelling runner must
5178
+ // already see themselves superseded
5179
+ commitId++;
4240
5180
  active?.cancel();
4241
5181
  active = null;
4242
- // bump id so late callbacks from the aborted runner are superseded
4243
- commitId++;
5182
+ if (options?.settle) {
5183
+ // Full settle: idle status plus cleared data/error, so a stale
5184
+ // rejection cannot resurface on the next commit window.
5185
+ slot.reset();
5186
+ intendedState.set(undefined);
5187
+ }
4244
5188
  },
4245
5189
  };
4246
5190
  }
4247
5191
 
5192
+ /**
5193
+ * Live-region phrase for a refused commit-gated transition (a step
5194
+ * change or tab switch whose `commitAction` answered `false`).
5195
+ *
5196
+ * A refusal settles the commit status back to `'idle'`, so no status
5197
+ * edge can voice it. This phrase arms on each new refused outcome (a new
5198
+ * `sequence`) and is spent by the next commit status change, an
5199
+ * active-index move, a cleared outcome or, when given, a changed
5200
+ * `extraSpend` value. A failed outcome never arms it. Arm wins over
5201
+ * spend in the same flush, so an optimistic rollback that moves the
5202
+ * active index still voices the refusal.
5203
+ *
5204
+ * Built on {@link createAnnouncementPhrase}: fully derived, no `effect`.
5205
+ * The same eager-read caveat applies - read the phrase before branching
5206
+ * on another arm of the live announcement, otherwise a spend transition
5207
+ * can be skipped.
5208
+ *
5209
+ * ```ts
5210
+ * const refusedPhrase = createRefusedPhrase({
5211
+ * outcome: () => presenter.lastOutcome(),
5212
+ * status: () => presenter.commitTransition.current(),
5213
+ * activeIndex: () => presenter.activeIndex(),
5214
+ * copy: () => i18n().commitRefusedGeneric,
5215
+ * });
5216
+ * ```
5217
+ *
5218
+ * @category common/data/commit
5219
+ * @wcag AA
5220
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/data/commit/refused-phrase.ts
5221
+ * @since 0.1.0
5222
+ * @relatedTo CngxTransitionOutcome, createAnnouncementPhrase
5223
+ */
5224
+ function createRefusedPhrase(options) {
5225
+ const { outcome, status, activeIndex, copy, extraSpend } = options;
5226
+ return createAnnouncementPhrase({
5227
+ source: () => {
5228
+ const current = outcome();
5229
+ return {
5230
+ sequence: current?.sequence,
5231
+ kind: current?.kind,
5232
+ status: status(),
5233
+ activeIndex: activeIndex(),
5234
+ extra: extraSpend?.(),
5235
+ };
5236
+ },
5237
+ arm: (curr, prev) => curr.kind === 'refused' && curr.sequence !== prev.sequence ? untracked(copy) : null,
5238
+ spend: (curr, prev) => curr.status !== prev.status ||
5239
+ curr.activeIndex !== prev.activeIndex ||
5240
+ curr.sequence === undefined ||
5241
+ curr.extra !== prev.extra,
5242
+ });
5243
+ }
5244
+
4248
5245
  /**
4249
5246
  * DI token carrying the factory that every cngx feature uses to
4250
5247
  * allocate its commit controller. Default `providedIn: 'root'`
@@ -4396,5 +5393,5 @@ function createMaterialBidirectionalSync(opts) {
4396
5393
  * Generated bundle index. Do not edit.
4397
5394
  */
4398
5395
 
4399
- export { CNGX_ASYNC_LABEL, CNGX_ASYNC_SKIP, CNGX_BUCKET_PAGINATE_HOST, CNGX_COMMIT_CONTROLLER_FACTORY, CNGX_RECYCLER_I18N, CNGX_STAT, CngxAsync, CngxAsyncBoundary, CngxAsyncRegistry, CngxBucketPaginate, CngxDataSource, CngxDelta, CngxFilter, CngxFilterChip, CngxFilterChips, CngxGoal, CngxMeasure, CngxMetric, CngxPaginate, CngxPaginateResetOn, CngxPaginateRouting, CngxRecyclerAnnouncer, CngxSmartDataSource, CngxSort, CngxSortHeader, CngxStat, CngxStatCaption, CngxStatCoordinator, CngxStatDelta, CngxStatLabel, CngxStatValue, CngxTrend, CngxVirtualItem, cngxAsyncInterceptor, connectPaginateEmit, connectPaginateResetOn, connectRecyclerToActiveDescendant, connectRecyclerToRoving, createAsyncState, createCommitController, createForwardedAsyncState, createManualState, createMaterialBidirectionalSync, createSortHeaderState, fromHttpResource, fromResource, injectAsyncRegistry, injectAsyncState, injectDataSource, injectLatencyProbe, injectRecycler, injectSmartDataSource, provideAsyncHttpObservability, provideAsyncRegistry, provideRecyclerI18n, resolveAsyncView, tapAsyncProgress, tapAsyncState, tapHttpAsyncState, withAsyncLabel, withAsyncSkip };
5396
+ export { CNGX_ASYNC_LABEL, CNGX_ASYNC_SKIP, CNGX_BUCKET_PAGINATE_HOST, CNGX_COMMIT_CONTROLLER_FACTORY, CNGX_KPI_I18N, CNGX_KPI_LANGUAGE_EN, CNGX_RECYCLER_I18N, CNGX_RECYCLER_LANGUAGE_EN, CNGX_RECYCLER_PLACEHOLDER_ROW, CNGX_STAT, CngxAsync, CngxAsyncBoundary, CngxAsyncRegistry, CngxBucketPaginate, CngxDataSource, CngxDelta, CngxFilter, CngxFilterChip, CngxFilterChips, CngxGoal, CngxMeasure, CngxMetric, CngxPaginate, CngxPaginateResetOn, CngxPaginateRouting, CngxRecyclerAnnouncer, CngxRecyclerPlaceholder, CngxRecyclerRow, CngxSmartDataSource, CngxSort, CngxSortHeader, CngxStat, CngxStatCaption, CngxStatCoordinator, CngxStatDelta, CngxStatLabel, CngxStatValue, CngxTrend, CngxVirtualItem, cngxAsyncInterceptor, connectPaginateEmit, connectPaginateResetOn, connectRecyclerToActiveDescendant, connectRecyclerToRoving, createAsyncState, createCommitController, createForwardedAsyncState, createManualState, createMaterialBidirectionalSync, createRefusedPhrase, createSortHeaderState, fromHttpResource, fromResource, injectAsyncRegistry, injectAsyncState, injectDataSource, injectKpiI18n, injectLatencyProbe, injectRecycler, injectSmartDataSource, provideAsyncHttpObservability, provideAsyncRegistry, provideKpiI18n, provideRecyclerI18n, provideRecyclerPlaceholderRow, resolveAsyncView, tapAsyncProgress, tapAsyncState, tapHttpAsyncState, withAsyncLabel, withAsyncSkip, withKpiI18nLabels, withRecyclerI18nLabels };
4400
5397
  //# sourceMappingURL=cngx-common-data.mjs.map