@cngx/common 0.1.0-rc.7 → 0.1.0-rc.8
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.
- package/card/README.md +2 -1
- package/data/README.md +10 -1
- package/dialog/README.md +23 -1
- package/fesm2022/cngx-common-a11y.mjs +125 -111
- package/fesm2022/cngx-common-a11y.mjs.map +1 -1
- package/fesm2022/cngx-common-audio.mjs +47 -5
- package/fesm2022/cngx-common-audio.mjs.map +1 -1
- package/fesm2022/cngx-common-card.mjs +300 -46
- package/fesm2022/cngx-common-card.mjs.map +1 -1
- package/fesm2022/cngx-common-chart.mjs +1176 -453
- package/fesm2022/cngx-common-chart.mjs.map +1 -1
- package/fesm2022/cngx-common-command.mjs +37 -10
- package/fesm2022/cngx-common-command.mjs.map +1 -1
- package/fesm2022/cngx-common-data.mjs +1318 -469
- package/fesm2022/cngx-common-data.mjs.map +1 -1
- package/fesm2022/cngx-common-dialog.mjs +151 -14
- package/fesm2022/cngx-common-dialog.mjs.map +1 -1
- package/fesm2022/cngx-common-display.mjs +340 -73
- package/fesm2022/cngx-common-display.mjs.map +1 -1
- package/fesm2022/cngx-common-interactive.mjs +1744 -952
- package/fesm2022/cngx-common-interactive.mjs.map +1 -1
- package/fesm2022/cngx-common-layout.mjs +841 -114
- package/fesm2022/cngx-common-layout.mjs.map +1 -1
- package/fesm2022/cngx-common-popover.mjs +350 -60
- package/fesm2022/cngx-common-popover.mjs.map +1 -1
- package/fesm2022/cngx-common-stepper.mjs +727 -317
- package/fesm2022/cngx-common-stepper.mjs.map +1 -1
- package/fesm2022/cngx-common-tabs.mjs +1601 -1243
- package/fesm2022/cngx-common-tabs.mjs.map +1 -1
- package/fesm2022/cngx-common-timeline.mjs +137 -53
- package/fesm2022/cngx-common-timeline.mjs.map +1 -1
- package/fesm2022/cngx-common.mjs +1 -1
- package/interactive/README.md +15 -4
- package/layout/README.md +21 -1
- package/package.json +3 -3
- package/popover/README.md +18 -2
- package/stepper/README.md +6 -4
- package/theming/components/cngx-accordion.css +1 -1
- package/theming/components/cngx-backdrop.css +12 -0
- package/theming/components/cngx-button-toggle.css +29 -3
- package/theming/components/cngx-data-grid.css +168 -1
- package/theming/components/cngx-dialog.css +13 -0
- package/theming/components/cngx-listbox.css +21 -12
- package/theming/components/cngx-menu.css +56 -16
- package/theming/components/cngx-popover.css +24 -0
- package/theming/components/cngx-recycler-placeholder.css +196 -0
- package/theming/components/cngx-ripple.css +1 -1
- package/theming/components/cngx-slider.css +32 -1
- package/theming/components/cngx-tooltip.css +12 -0
- package/timeline/README.md +155 -0
- package/types/cngx-common-a11y.d.ts +42 -18
- package/types/cngx-common-card.d.ts +201 -17
- package/types/cngx-common-chart.d.ts +343 -47
- package/types/cngx-common-command.d.ts +31 -8
- package/types/cngx-common-data.d.ts +581 -68
- package/types/cngx-common-dialog.d.ts +158 -3
- package/types/cngx-common-display.d.ts +356 -142
- package/types/cngx-common-interactive.d.ts +859 -210
- package/types/cngx-common-layout.d.ts +567 -28
- package/types/cngx-common-popover.d.ts +262 -39
- package/types/cngx-common-stepper.d.ts +366 -116
- package/types/cngx-common-tabs.d.ts +214 -50
- package/types/cngx-common-timeline.d.ts +82 -16
|
@@ -1,16 +1,24 @@
|
|
|
1
1
|
import * as i0 from '@angular/core';
|
|
2
|
-
import { input, signal, afterNextRender, computed, output, Directive, inject, TemplateRef, model, contentChild,
|
|
2
|
+
import { input, signal, afterNextRender, computed, output, Directive, inject, TemplateRef, model, contentChild, effect, untracked, ChangeDetectionStrategy, Component, DestroyRef, InjectionToken, Injector, Injectable, makeEnvironmentProviders, ViewContainerRef, ViewEncapsulation, isDevMode, 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
6
|
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
|
|
7
7
|
import { Router, ActivatedRoute } from '@angular/router';
|
|
8
8
|
import { DataSource } from '@angular/cdk/collections';
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { isObservable, firstValueFrom, defer, tap, filter, map
|
|
9
|
+
import { foldForMatching, memoize, injectLocale, buildAsyncStateView, nextUid, createAggregateAsyncState, CNGX_STATEFUL, createLatencyProbe, numberFormatterFor, createOverrideMerge, createVisibilityGate, createTransitionTracker, createMediaQuerySignal } from '@cngx/core/utils';
|
|
10
|
+
import { arrayEqual, clamp } from '@cngx/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.
|
|
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.
|
|
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 ?
|
|
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 =
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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.**
|
|
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.
|
|
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.**
|
|
478
|
-
*
|
|
479
|
-
*
|
|
480
|
-
*
|
|
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
|
|
@@ -589,7 +626,6 @@ class CngxFilterChips {
|
|
|
589
626
|
* `CngxFilter.predicate`.
|
|
590
627
|
*/
|
|
591
628
|
selectedValues = model([], ...(ngDevMode ? [{ debugName: "selectedValues" }] : /* istanbul ignore next */ []));
|
|
592
|
-
registered = false;
|
|
593
629
|
constructor() {
|
|
594
630
|
const predicateFn = (item) => {
|
|
595
631
|
const values = this.selectedValues();
|
|
@@ -600,15 +636,42 @@ class CngxFilterChips {
|
|
|
600
636
|
const key = extract(this.optionValue()(item));
|
|
601
637
|
return values.some((v) => Object.is(extract(v), key));
|
|
602
638
|
};
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
639
|
+
// Binding effect: tracks only filterRef/filterKey, so a rebind moves the
|
|
640
|
+
// registration. Cleanup is identity-guarded - it removes the key only
|
|
641
|
+
// while it still maps to THIS strip's predicate, so tearing down one of
|
|
642
|
+
// two strips sharing a key never detaches the live sibling.
|
|
643
|
+
effect((onCleanup) => {
|
|
644
|
+
const filter = this.filterRef();
|
|
645
|
+
const key = this.filterKey();
|
|
646
|
+
untracked(() => filter.addPredicate(key, predicateFn));
|
|
647
|
+
onCleanup(() => {
|
|
648
|
+
if (untracked(filter.predicates).get(key) === predicateFn) {
|
|
649
|
+
untracked(() => filter.removePredicate(key));
|
|
650
|
+
}
|
|
651
|
+
});
|
|
606
652
|
});
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
653
|
+
// Eviction watcher: filter.clear() wipes the whole predicate map while
|
|
654
|
+
// the chips stay visually selected. Re-register when our key is missing
|
|
655
|
+
// so UI and predicate stack cannot diverge. A foreign same-key
|
|
656
|
+
// registration is present, not missing - it is left alone (no fighting,
|
|
657
|
+
// no loop).
|
|
658
|
+
effect(() => {
|
|
659
|
+
const filter = this.filterRef();
|
|
660
|
+
const key = this.filterKey();
|
|
661
|
+
if (!filter.predicates().has(key)) {
|
|
662
|
+
untracked(() => filter.addPredicate(key, predicateFn));
|
|
663
|
+
}
|
|
664
|
+
});
|
|
665
|
+
// Prune selections whose option vanished from [options]: without this a
|
|
666
|
+
// removed option keeps filtering invisibly (no chip renders for it).
|
|
667
|
+
effect(() => {
|
|
668
|
+
const extract = this.keyFn();
|
|
669
|
+
const valid = new Set(this.options().map((o) => extract(this.optionValue()(o))));
|
|
670
|
+
const current = untracked(this.selectedValues);
|
|
671
|
+
const pruned = current.filter((v) => valid.has(extract(v)));
|
|
672
|
+
if (pruned.length !== current.length) {
|
|
673
|
+
untracked(() => this.selectedValues.set(pruned));
|
|
610
674
|
}
|
|
611
|
-
this.filterRef().removePredicate(this.filterKey());
|
|
612
675
|
});
|
|
613
676
|
}
|
|
614
677
|
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFilterChips, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
@@ -635,7 +698,7 @@ class CngxFilterChips {
|
|
|
635
698
|
</cngx-chip>
|
|
636
699
|
}
|
|
637
700
|
</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 });
|
|
701
|
+
`, 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
702
|
}
|
|
640
703
|
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFilterChips, decorators: [{
|
|
641
704
|
type: Component,
|
|
@@ -754,6 +817,22 @@ class CngxPaginate {
|
|
|
754
817
|
* stops a fresh-array identity from cascading downstream.
|
|
755
818
|
*/
|
|
756
819
|
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] });
|
|
820
|
+
/**
|
|
821
|
+
* `range()` with both bounds capped at `total` - the honest in-bounds window
|
|
822
|
+
* for readouts and announcements. `range()`'s upper bound is
|
|
823
|
+
* `start + pageSize`, so a partial final page overshoots `total`; this caps
|
|
824
|
+
* it (and yields `[0, 0]` while the list is empty). The capped end doubles as
|
|
825
|
+
* the cumulative reveal count for load-more consumers: `range()[1]` and
|
|
826
|
+
* `cumulativeRange()[1]` are the same number (`(pageIndex + 1) * pageSize`),
|
|
827
|
+
* so `clampedRange()[1]` is "items shown so far" in both replace and append
|
|
828
|
+
* modes. The explicit tuple `equal` stops a fresh-array identity from
|
|
829
|
+
* cascading downstream.
|
|
830
|
+
*/
|
|
831
|
+
clampedRange = computed(() => {
|
|
832
|
+
const total = this.total();
|
|
833
|
+
const [start, end] = this.range();
|
|
834
|
+
return [Math.min(start, total), Math.min(end, total)];
|
|
835
|
+
}, { ...(ngDevMode ? { debugName: "clampedRange" } : /* istanbul ignore next */ {}), equal: (a, b) => a[0] === b[0] && a[1] === b[1] });
|
|
757
836
|
/** Emitted when the page index changes. */
|
|
758
837
|
pageChange = output();
|
|
759
838
|
/** Emitted when the page size changes. */
|
|
@@ -893,7 +972,10 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
|
|
|
893
972
|
* brain's `pageIndex()` stays pinned to the input until the consumer feeds it
|
|
894
973
|
* back;
|
|
895
974
|
* - an `effect()` reads the effective `pageIndex()` / `pageSize()` and covers a
|
|
896
|
-
* `total`-shrink clamp the nav-only output misses.
|
|
975
|
+
* `total`-shrink clamp the nav-only output misses. The index half of the
|
|
976
|
+
* clamp path is suppressed while the brain is busy or `total` is 0, so a
|
|
977
|
+
* transient total drop during a refetch never persists a page-0 clamp into a
|
|
978
|
+
* controlled consumer; a clamp that survives the settle emits then.
|
|
897
979
|
*
|
|
898
980
|
* The shared guard makes a value one path already emitted a no-op on the other,
|
|
899
981
|
* so each change emits exactly once. Seeded with the current effective values,
|
|
@@ -938,16 +1020,27 @@ function connectPaginateEmit(paginate, handlers) {
|
|
|
938
1020
|
// nav path already emitted is a no-op here, so each change emits once.
|
|
939
1021
|
effect(() => {
|
|
940
1022
|
const index = paginate.pageIndex();
|
|
1023
|
+
// A transient total drop (a refetch clearing [total] to 0) clamps the
|
|
1024
|
+
// effective index to 0; forwarding that would persist the clamp into a
|
|
1025
|
+
// controlled consumer's two-way state and pin page 0 after the data
|
|
1026
|
+
// returns, where the brain's read-time clamp alone would recover. Both
|
|
1027
|
+
// gates are tracked reads, so a clamp that survives the settle (a real
|
|
1028
|
+
// total shrink) emits when busy flips off / total refills.
|
|
1029
|
+
if (paginate.isBusy() || paginate.total() === 0) {
|
|
1030
|
+
return;
|
|
1031
|
+
}
|
|
941
1032
|
if (index !== lastIndex) {
|
|
942
1033
|
lastIndex = index;
|
|
943
|
-
handlers
|
|
1034
|
+
// Consumer handlers run synchronously - keep their signal reads/writes
|
|
1035
|
+
// out of this effect's dependency graph.
|
|
1036
|
+
untracked(() => handlers.onIndex(index));
|
|
944
1037
|
}
|
|
945
1038
|
});
|
|
946
1039
|
effect(() => {
|
|
947
1040
|
const size = paginate.pageSize();
|
|
948
1041
|
if (size !== lastSize) {
|
|
949
1042
|
lastSize = size;
|
|
950
|
-
handlers.onSize(size);
|
|
1043
|
+
untracked(() => handlers.onSize(size));
|
|
951
1044
|
}
|
|
952
1045
|
});
|
|
953
1046
|
}
|
|
@@ -987,9 +1080,18 @@ class CngxPaginateRouting {
|
|
|
987
1080
|
pageParam = input('page', { ...(ngDevMode ? { debugName: "pageParam" } : /* istanbul ignore next */ {}), alias: 'cngxPaginatePageParam' });
|
|
988
1081
|
/** Query-param name for the page size. */
|
|
989
1082
|
sizeParam = input('pageSize', { ...(ngDevMode ? { debugName: "sizeParam" } : /* istanbul ignore next */ {}), alias: 'cngxPaginateSizeParam' });
|
|
990
|
-
// Set
|
|
991
|
-
//
|
|
1083
|
+
// Set synchronously around brain writes driven by the URL, so the
|
|
1084
|
+
// pageChange subscription below can tell a URL-driven change from a user
|
|
1085
|
+
// navigation (setPage/setPageSize emit synchronously).
|
|
992
1086
|
applyingFromUrl = false;
|
|
1087
|
+
// A deep-linked page index the brain could not represent yet: setPage
|
|
1088
|
+
// clamps against totalPages (1 while the default total=0 is still in
|
|
1089
|
+
// effect) and no-ops entirely while the bound async state is busy. The raw
|
|
1090
|
+
// index is parked here and re-applied once total/busy settle; while it is
|
|
1091
|
+
// parked, the brain -> URL effect leaves the URL alone so the deep link
|
|
1092
|
+
// survives until the data lands. `size` is null once the size half has
|
|
1093
|
+
// been applied.
|
|
1094
|
+
pendingUrl = signal(null, { ...(ngDevMode ? { debugName: "pendingUrl" } : /* istanbul ignore next */ {}), equal: (a, b) => a?.index === b?.index && a?.size === b?.size });
|
|
993
1095
|
constructor() {
|
|
994
1096
|
const router = this.router;
|
|
995
1097
|
const route = this.route;
|
|
@@ -1000,17 +1102,38 @@ class CngxPaginateRouting {
|
|
|
1000
1102
|
}
|
|
1001
1103
|
return;
|
|
1002
1104
|
}
|
|
1105
|
+
// A user navigation supersedes a still-parked deep link. The brain is
|
|
1106
|
+
// resolved through the element injector and may live on an ancestor, so
|
|
1107
|
+
// the subscription is torn down explicitly instead of relying on shared
|
|
1108
|
+
// lifecycles.
|
|
1109
|
+
const pageChangeSub = this.paginate.pageChange.subscribe(() => {
|
|
1110
|
+
if (!this.applyingFromUrl) {
|
|
1111
|
+
this.pendingUrl.set(null);
|
|
1112
|
+
}
|
|
1113
|
+
});
|
|
1114
|
+
this.destroyRef.onDestroy(() => pageChangeSub.unsubscribe());
|
|
1003
1115
|
// brain -> URL. Tracks the effective page / size; merges into the existing
|
|
1004
1116
|
// query string and replaces history so paging does not stack back entries.
|
|
1005
1117
|
// 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.
|
|
1118
|
+
// alias is already set by the time the first navigation fires. Skipped
|
|
1119
|
+
// while a deep link is parked and when the URL already carries the values
|
|
1120
|
+
// (the echo after a URL -> brain apply must not renavigate).
|
|
1007
1121
|
effect(() => {
|
|
1008
1122
|
const page = this.paginate.pageIndex() + 1;
|
|
1009
1123
|
const size = this.paginate.pageSize();
|
|
1010
|
-
if (this.
|
|
1124
|
+
if (this.pendingUrl() !== null) {
|
|
1011
1125
|
return;
|
|
1012
1126
|
}
|
|
1013
1127
|
untracked(() => {
|
|
1128
|
+
// Snapshot read while router.navigate is async: a still-pending
|
|
1129
|
+
// navigation can slip past this check and renavigate - benign under
|
|
1130
|
+
// replaceUrl + merge (same params, no history entry).
|
|
1131
|
+
const params = route.snapshot.queryParamMap;
|
|
1132
|
+
const samePage = Number(params.get(this.pageParam())) === page;
|
|
1133
|
+
const sameSize = Number(params.get(this.sizeParam())) === size;
|
|
1134
|
+
if (samePage && sameSize) {
|
|
1135
|
+
return;
|
|
1136
|
+
}
|
|
1014
1137
|
void router.navigate([], {
|
|
1015
1138
|
relativeTo: route,
|
|
1016
1139
|
queryParams: { [this.pageParam()]: page, [this.sizeParam()]: size },
|
|
@@ -1019,6 +1142,20 @@ class CngxPaginateRouting {
|
|
|
1019
1142
|
});
|
|
1020
1143
|
});
|
|
1021
1144
|
});
|
|
1145
|
+
// Re-apply a parked deep link whenever the clamp inputs move (total
|
|
1146
|
+
// landed, busy released). Only those two triggers are tracked; the parked
|
|
1147
|
+
// value is read untracked, so the re-park write inside applyFromUrl can
|
|
1148
|
+
// never feed back into this effect's own dependency graph.
|
|
1149
|
+
effect(() => {
|
|
1150
|
+
this.paginate.totalPages();
|
|
1151
|
+
this.paginate.isBusy();
|
|
1152
|
+
untracked(() => {
|
|
1153
|
+
const pending = this.pendingUrl();
|
|
1154
|
+
if (pending !== null) {
|
|
1155
|
+
this.applyFromUrl(pending.index, pending.size);
|
|
1156
|
+
}
|
|
1157
|
+
});
|
|
1158
|
+
});
|
|
1022
1159
|
}
|
|
1023
1160
|
ngOnInit() {
|
|
1024
1161
|
const route = this.route;
|
|
@@ -1030,22 +1167,41 @@ class CngxPaginateRouting {
|
|
|
1030
1167
|
// deep-linked page / size therefore lands before first paint). The
|
|
1031
1168
|
// subscription stays live for back / forward navigation.
|
|
1032
1169
|
route.queryParamMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
|
|
1033
|
-
const
|
|
1034
|
-
const
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1170
|
+
const rawSize = Number(params.get(this.sizeParam()));
|
|
1171
|
+
const rawPage = Number(params.get(this.pageParam()));
|
|
1172
|
+
const size = Number.isFinite(rawSize) && rawSize > 0 ? rawSize : null;
|
|
1173
|
+
const index = (Number.isFinite(rawPage) && rawPage > 0 ? rawPage : 1) - 1;
|
|
1174
|
+
this.applyFromUrl(index, size);
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
applyFromUrl(index, size) {
|
|
1178
|
+
const paginate = this.paginate;
|
|
1179
|
+
if (paginate.isBusy()) {
|
|
1180
|
+
// Both setters no-op while busy - park the whole request and retry.
|
|
1181
|
+
this.pendingUrl.set({ index, size });
|
|
1182
|
+
return;
|
|
1183
|
+
}
|
|
1184
|
+
this.applyingFromUrl = true;
|
|
1185
|
+
try {
|
|
1186
|
+
if (size !== null && size !== paginate.pageSize()) {
|
|
1187
|
+
paginate.setPageSize(size, false);
|
|
1044
1188
|
}
|
|
1045
|
-
|
|
1046
|
-
|
|
1189
|
+
if (index !== paginate.pageIndex()) {
|
|
1190
|
+
paginate.setPage(index);
|
|
1047
1191
|
}
|
|
1048
|
-
}
|
|
1192
|
+
}
|
|
1193
|
+
finally {
|
|
1194
|
+
this.applyingFromUrl = false;
|
|
1195
|
+
}
|
|
1196
|
+
if (paginate.pageIndex() === index || paginate.total() > 0) {
|
|
1197
|
+
// Landed, or clamped against a real total - the deep link is resolved.
|
|
1198
|
+
this.pendingUrl.set(null);
|
|
1199
|
+
}
|
|
1200
|
+
else {
|
|
1201
|
+
// Clamped against the default total=0: the real total has not arrived
|
|
1202
|
+
// yet, so keep the raw index parked (size, if any, is applied already).
|
|
1203
|
+
this.pendingUrl.set({ index, size: null });
|
|
1204
|
+
}
|
|
1049
1205
|
}
|
|
1050
1206
|
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxPaginateRouting, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
1051
1207
|
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 +1387,61 @@ function injectDataSource(data) {
|
|
|
1231
1387
|
return new CngxDataSource(data);
|
|
1232
1388
|
}
|
|
1233
1389
|
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1390
|
+
/**
|
|
1391
|
+
* @internal Folded field values per row object. Keyed by the row, so it
|
|
1392
|
+
* cannot thrash and is collected with the rows; the raw strings are compared
|
|
1393
|
+
* on every read, so a row mutated in place is folded again.
|
|
1394
|
+
*/
|
|
1395
|
+
const FOLDED_FIELDS = new WeakMap();
|
|
1396
|
+
function rawFieldsOf(item) {
|
|
1397
|
+
const raw = [];
|
|
1398
|
+
for (const v of Object.values(item)) {
|
|
1399
|
+
if (v !== null && v !== undefined && typeof v !== 'object') {
|
|
1400
|
+
raw.push(String(v));
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
return raw;
|
|
1404
|
+
}
|
|
1405
|
+
function foldedFieldsOf(item, locale) {
|
|
1406
|
+
const raw = rawFieldsOf(item);
|
|
1407
|
+
const cached = FOLDED_FIELDS.get(item);
|
|
1408
|
+
if (cached?.locale === locale && arrayEqual(cached.raw, raw)) {
|
|
1409
|
+
return cached.folded;
|
|
1410
|
+
}
|
|
1411
|
+
const folded = raw.map((value) => foldForMatching(value, locale));
|
|
1412
|
+
FOLDED_FIELDS.set(item, { locale, raw, folded });
|
|
1413
|
+
return folded;
|
|
1241
1414
|
}
|
|
1242
|
-
|
|
1415
|
+
/**
|
|
1416
|
+
* @internal The default search: primitive field values, case and accents
|
|
1417
|
+
* ignored in `locale`. The term is folded once per term, each row's field
|
|
1418
|
+
* values once per row and locale, not on every keystroke.
|
|
1419
|
+
*/
|
|
1420
|
+
const defaultSearchFnFor = memoize((locale) => {
|
|
1421
|
+
let lastTerm = '';
|
|
1422
|
+
let lastFolded = '';
|
|
1423
|
+
return (item, term) => {
|
|
1424
|
+
if (term !== lastTerm) {
|
|
1425
|
+
lastTerm = term;
|
|
1426
|
+
lastFolded = foldForMatching(term, locale);
|
|
1427
|
+
}
|
|
1428
|
+
if (typeof item !== 'object' || item === null) {
|
|
1429
|
+
return foldForMatching(String(item), locale).includes(lastFolded);
|
|
1430
|
+
}
|
|
1431
|
+
return foldedFieldsOf(item, locale).some((value) => value.includes(lastFolded));
|
|
1432
|
+
};
|
|
1433
|
+
}, { cacheLimit: 8 });
|
|
1434
|
+
const collatorFor = memoize((locale) => new Intl.Collator(locale, { numeric: true, sensitivity: 'base' }), { cacheLimit: 32 });
|
|
1435
|
+
/** @internal The default comparator: field values as text, collated in `locale`. */
|
|
1436
|
+
function defaultSortFnFor(locale) {
|
|
1437
|
+
const collator = collatorFor(locale);
|
|
1243
1438
|
const toStr = (v) => v === null || v === undefined || typeof v === 'object'
|
|
1244
1439
|
? ''
|
|
1245
1440
|
: String(v);
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1441
|
+
return (a, b, field, dir) => {
|
|
1442
|
+
const cmp = collator.compare(toStr(a[field]), toStr(b[field]));
|
|
1443
|
+
return dir === 'asc' ? cmp : -cmp;
|
|
1444
|
+
};
|
|
1250
1445
|
}
|
|
1251
1446
|
function isAsyncState(source) {
|
|
1252
1447
|
return 'status' in source && 'data' in source && 'isFirstLoad' in source;
|
|
@@ -1306,6 +1501,7 @@ class CngxSmartDataSource extends DataSource {
|
|
|
1306
1501
|
// matching options thunk instead.
|
|
1307
1502
|
injectedSearch = inject(CngxSearch, { optional: true });
|
|
1308
1503
|
injectedPaginate = inject(CngxPaginate, { optional: true });
|
|
1504
|
+
locale = injectLocale();
|
|
1309
1505
|
/**
|
|
1310
1506
|
* Items after filter and search are applied, before sort and pagination.
|
|
1311
1507
|
* Use `filteredCount()` to get the pre-pagination count for paginator `total`.
|
|
@@ -1358,7 +1554,7 @@ class CngxSmartDataSource extends DataSource {
|
|
|
1358
1554
|
const search = this.options?.search?.() ?? this.injectedSearch;
|
|
1359
1555
|
const predicate = filter?.predicate();
|
|
1360
1556
|
const term = search?.term();
|
|
1361
|
-
const searchFn = this.options?.searchFn ?? (
|
|
1557
|
+
const searchFn = this.options?.searchFn ?? defaultSearchFnFor(this.locale());
|
|
1362
1558
|
// Pipeline: raw → filter → search. Cast required: CngxFilter injected as unknown.
|
|
1363
1559
|
return data()
|
|
1364
1560
|
.filter((v) => !predicate || predicate(v))
|
|
@@ -1375,7 +1571,7 @@ class CngxSmartDataSource extends DataSource {
|
|
|
1375
1571
|
this.processed = computed(() => {
|
|
1376
1572
|
const sort = this.options?.sort?.() ?? this.injectedSort;
|
|
1377
1573
|
const sorts = sort?.sorts() ?? [];
|
|
1378
|
-
const sortFn = this.options?.sortFn ?? (
|
|
1574
|
+
const sortFn = this.options?.sortFn ?? defaultSortFnFor(this.locale());
|
|
1379
1575
|
const sorted = sorts.length > 0
|
|
1380
1576
|
? [...this.filtered()].sort((a, b) => sorts.reduce((cmp, { active, direction }) => cmp || sortFn(a, b, active, direction), 0))
|
|
1381
1577
|
: this.filtered();
|
|
@@ -1452,6 +1648,10 @@ function createManualState() {
|
|
|
1452
1648
|
set(newStatus) {
|
|
1453
1649
|
statusState.set(newStatus);
|
|
1454
1650
|
if (newStatus === 'success') {
|
|
1651
|
+
// Parity with setSuccess: a success transition must not leave stale
|
|
1652
|
+
// error/progress residue behind.
|
|
1653
|
+
errorState.set(undefined);
|
|
1654
|
+
progressState.set(undefined);
|
|
1455
1655
|
hadSuccess.set(true);
|
|
1456
1656
|
lastUpdatedState.set(new Date());
|
|
1457
1657
|
}
|
|
@@ -1483,134 +1683,6 @@ function createManualState() {
|
|
|
1483
1683
|
};
|
|
1484
1684
|
}
|
|
1485
1685
|
|
|
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
|
-
};
|
|
1612
|
-
}
|
|
1613
|
-
|
|
1614
1686
|
/** @internal Length-then-key-set equality for the operations Map signal. */
|
|
1615
1687
|
function mapKeySetEqual(a, b) {
|
|
1616
1688
|
if (a === b) {
|
|
@@ -1746,6 +1818,143 @@ function injectAsyncRegistry() {
|
|
|
1746
1818
|
return inject(CngxAsyncRegistry, { optional: true });
|
|
1747
1819
|
}
|
|
1748
1820
|
|
|
1821
|
+
/**
|
|
1822
|
+
* Create a mutation async state - for explicit user-triggered actions.
|
|
1823
|
+
*
|
|
1824
|
+
* Must be called in an injection context (field initializer or constructor)
|
|
1825
|
+
* because it uses `inject(DestroyRef)` for cleanup.
|
|
1826
|
+
*
|
|
1827
|
+
* ```typescript
|
|
1828
|
+
* readonly saveResident = createAsyncState<Resident>();
|
|
1829
|
+
*
|
|
1830
|
+
* async handleSave(): Promise<void> {
|
|
1831
|
+
* await this.saveResident.execute(
|
|
1832
|
+
* () => this.api.save(this.form().value())
|
|
1833
|
+
* );
|
|
1834
|
+
* }
|
|
1835
|
+
* ```
|
|
1836
|
+
*
|
|
1837
|
+
* @category common/data/async-state
|
|
1838
|
+
*/
|
|
1839
|
+
function createAsyncState(options) {
|
|
1840
|
+
const destroyRef = inject(DestroyRef);
|
|
1841
|
+
const state = createManualState();
|
|
1842
|
+
let abortController;
|
|
1843
|
+
destroyRef.onDestroy(() => {
|
|
1844
|
+
abortController?.abort();
|
|
1845
|
+
abortController = undefined;
|
|
1846
|
+
});
|
|
1847
|
+
// Same opt-in observability injectAsyncState offers: without it, mutations
|
|
1848
|
+
// built here are invisible to CngxAsyncRegistry.isAnythingLoading.
|
|
1849
|
+
if (options?.register) {
|
|
1850
|
+
const registry = injectAsyncRegistry();
|
|
1851
|
+
if (registry) {
|
|
1852
|
+
const operationId = registry.register(state, options.label);
|
|
1853
|
+
destroyRef.onDestroy(() => registry.unregister(operationId));
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
return {
|
|
1857
|
+
status: state.status,
|
|
1858
|
+
data: state.data,
|
|
1859
|
+
error: state.error,
|
|
1860
|
+
progress: state.progress,
|
|
1861
|
+
isLoading: state.isLoading,
|
|
1862
|
+
isPending: state.isPending,
|
|
1863
|
+
isRefreshing: state.isRefreshing,
|
|
1864
|
+
isBusy: state.isBusy,
|
|
1865
|
+
isFirstLoad: state.isFirstLoad,
|
|
1866
|
+
isEmpty: state.isEmpty,
|
|
1867
|
+
hasData: state.hasData,
|
|
1868
|
+
isSettled: state.isSettled,
|
|
1869
|
+
lastUpdated: state.lastUpdated,
|
|
1870
|
+
async execute(fn) {
|
|
1871
|
+
abortController?.abort();
|
|
1872
|
+
const controller = new AbortController();
|
|
1873
|
+
abortController = controller;
|
|
1874
|
+
state.set('pending');
|
|
1875
|
+
state.setProgress(undefined);
|
|
1876
|
+
try {
|
|
1877
|
+
const result$ = fn();
|
|
1878
|
+
const result = isObservable(result$) ? await firstValueFrom(result$) : await result$;
|
|
1879
|
+
if (controller.signal.aborted) {
|
|
1880
|
+
return;
|
|
1881
|
+
}
|
|
1882
|
+
state.setSuccess(result);
|
|
1883
|
+
}
|
|
1884
|
+
catch (err) {
|
|
1885
|
+
if (controller.signal.aborted) {
|
|
1886
|
+
return;
|
|
1887
|
+
}
|
|
1888
|
+
state.setError(err);
|
|
1889
|
+
}
|
|
1890
|
+
finally {
|
|
1891
|
+
if (abortController === controller) {
|
|
1892
|
+
abortController = undefined;
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
},
|
|
1896
|
+
reportProgress(value) {
|
|
1897
|
+
state.setProgress(value);
|
|
1898
|
+
},
|
|
1899
|
+
reset() {
|
|
1900
|
+
abortController?.abort();
|
|
1901
|
+
abortController = undefined;
|
|
1902
|
+
state.reset();
|
|
1903
|
+
},
|
|
1904
|
+
};
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
/**
|
|
1908
|
+
* Wraps a *changing* source of async state in a stable
|
|
1909
|
+
* {@link CngxAsyncState} façade.
|
|
1910
|
+
*
|
|
1911
|
+
* A component that receives its state through an `Input` cannot publish that
|
|
1912
|
+
* object through `CNGX_STATEFUL` directly: the token is resolved once when a
|
|
1913
|
+
* bridge injects it, while the input can be rebound or absent. Capturing the
|
|
1914
|
+
* object would hand the bridge a stale state - or `undefined` before the
|
|
1915
|
+
* first binding.
|
|
1916
|
+
*
|
|
1917
|
+
* This returns one object whose every member is a `computed()` that reads the
|
|
1918
|
+
* source on each access, so bridges observe transitions of whatever is bound
|
|
1919
|
+
* right now. With nothing bound it reports a quiet `idle` state rather than
|
|
1920
|
+
* throwing, which is what lets a bridge sit inside a timeline that has not
|
|
1921
|
+
* been given a state yet.
|
|
1922
|
+
*
|
|
1923
|
+
* Contrast the select family, which provides `CNGX_STATEFUL` with
|
|
1924
|
+
* `useFactory` over a concrete `commitState` field - no forwarding needed
|
|
1925
|
+
* there, because the state is created by the component rather than passed in.
|
|
1926
|
+
* The split is not about the component, it is about where the state is born:
|
|
1927
|
+
* created locally, capture it; arriving through an `Input`, forward it.
|
|
1928
|
+
*
|
|
1929
|
+
* ```ts
|
|
1930
|
+
* readonly asyncState = createForwardedAsyncState(this.state);
|
|
1931
|
+
*
|
|
1932
|
+
* // providers:
|
|
1933
|
+
* { provide: CNGX_STATEFUL, useFactory: () => ({ state: inject(Host).asyncState }) }
|
|
1934
|
+
* ```
|
|
1935
|
+
*
|
|
1936
|
+
* @category common/data/async-state
|
|
1937
|
+
* @relatedTo createAsyncState, createManualState
|
|
1938
|
+
* @since 0.1.0
|
|
1939
|
+
*/
|
|
1940
|
+
function createForwardedAsyncState(source) {
|
|
1941
|
+
return {
|
|
1942
|
+
status: computed(() => source()?.status() ?? 'idle'),
|
|
1943
|
+
data: computed(() => source()?.data()),
|
|
1944
|
+
error: computed(() => source()?.error()),
|
|
1945
|
+
progress: computed(() => source()?.progress()),
|
|
1946
|
+
isLoading: computed(() => source()?.isLoading() ?? false),
|
|
1947
|
+
isPending: computed(() => source()?.isPending() ?? false),
|
|
1948
|
+
isRefreshing: computed(() => source()?.isRefreshing() ?? false),
|
|
1949
|
+
isBusy: computed(() => source()?.isBusy() ?? false),
|
|
1950
|
+
isFirstLoad: computed(() => source()?.isFirstLoad() ?? true),
|
|
1951
|
+
isEmpty: computed(() => source()?.isEmpty() ?? true),
|
|
1952
|
+
hasData: computed(() => source()?.hasData() ?? false),
|
|
1953
|
+
isSettled: computed(() => source()?.isSettled() ?? false),
|
|
1954
|
+
lastUpdated: computed(() => source()?.lastUpdated()),
|
|
1955
|
+
};
|
|
1956
|
+
}
|
|
1957
|
+
|
|
1749
1958
|
/**
|
|
1750
1959
|
* Create a reactive async state that auto-loads when signal dependencies change.
|
|
1751
1960
|
*
|
|
@@ -1859,6 +2068,13 @@ function injectAsyncState(fn, options) {
|
|
|
1859
2068
|
clearTimeout(debounceTimer);
|
|
1860
2069
|
}
|
|
1861
2070
|
const captured = result;
|
|
2071
|
+
if (!isObservable(captured)) {
|
|
2072
|
+
// The promise's work is already running (the invocation is the
|
|
2073
|
+
// tracking probe). A rapid follow-up change supersedes this capture
|
|
2074
|
+
// before the timer consumes it - observe the rejection here so a
|
|
2075
|
+
// superseded failure never surfaces as an unhandled rejection.
|
|
2076
|
+
captured.then(undefined, () => undefined);
|
|
2077
|
+
}
|
|
1862
2078
|
debounceTimer = setTimeout(() => {
|
|
1863
2079
|
debounceTimer = undefined;
|
|
1864
2080
|
void executeQuery(() => captured);
|
|
@@ -1982,37 +2198,25 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
|
|
|
1982
2198
|
}], propDecorators: { sources: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxAsyncBoundary", required: true }] }] } });
|
|
1983
2199
|
|
|
1984
2200
|
/**
|
|
1985
|
-
*
|
|
1986
|
-
*
|
|
1987
|
-
*
|
|
1988
|
-
* `
|
|
1989
|
-
*
|
|
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
|
-
* });
|
|
2201
|
+
* Shared projection core for the two resource bridges (`fromResource`,
|
|
2202
|
+
* `fromHttpResource`). Derives every flag through `buildAsyncStateView`, so
|
|
2203
|
+
* the family semantics (`isLoading` includes pending/refreshing,
|
|
2204
|
+
* `isBusy === isLoading`) cannot drift between the bridges and the factories.
|
|
2000
2205
|
*
|
|
2001
|
-
*
|
|
2002
|
-
* // items.status(), items.data(), items.isFirstLoad() - all work
|
|
2003
|
-
* // <cngx-async-container [state]="items"> - direct binding
|
|
2004
|
-
* ```
|
|
2206
|
+
* Must be called in an injection context (the tracking `effect()` requires one).
|
|
2005
2207
|
*
|
|
2006
|
-
* @
|
|
2208
|
+
* @internal
|
|
2007
2209
|
*/
|
|
2008
|
-
function
|
|
2009
|
-
//
|
|
2010
|
-
//
|
|
2210
|
+
function buildResourceBridge(ref, progress) {
|
|
2211
|
+
// ResourceStatus has no "first load" concept, so a successful load is
|
|
2212
|
+
// latched here together with its timestamp.
|
|
2011
2213
|
const hadSuccess = signal(false, ...(ngDevMode ? [{ debugName: "hadSuccess" }] : /* istanbul ignore next */ []));
|
|
2214
|
+
const lastUpdated = signal(undefined, ...(ngDevMode ? [{ debugName: "lastUpdated" }] : /* istanbul ignore next */ []));
|
|
2012
2215
|
effect(() => {
|
|
2013
2216
|
const s = ref.status();
|
|
2014
2217
|
if (s === 'resolved' || s === 'local') {
|
|
2015
2218
|
hadSuccess.set(true);
|
|
2219
|
+
lastUpdated.set(new Date());
|
|
2016
2220
|
}
|
|
2017
2221
|
});
|
|
2018
2222
|
const status = computed(() => {
|
|
@@ -2030,44 +2234,44 @@ function fromResource(ref) {
|
|
|
2030
2234
|
return 'error';
|
|
2031
2235
|
}
|
|
2032
2236
|
}, ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
|
|
2033
|
-
|
|
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 {
|
|
2237
|
+
return buildAsyncStateView({
|
|
2057
2238
|
status,
|
|
2058
|
-
data,
|
|
2059
|
-
error,
|
|
2060
|
-
progress
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
isBusy,
|
|
2065
|
-
isFirstLoad,
|
|
2066
|
-
isEmpty,
|
|
2067
|
-
hasData,
|
|
2068
|
-
isSettled,
|
|
2239
|
+
data: computed(() => (ref.hasValue() ? ref.value() : undefined)),
|
|
2240
|
+
error: computed(() => ref.error()),
|
|
2241
|
+
progress,
|
|
2242
|
+
// Idle counts as "before the first load": a not-yet-triggered resource
|
|
2243
|
+
// still shows the skeleton, not the empty state.
|
|
2244
|
+
isFirstLoad: computed(() => !hadSuccess() && (ref.isLoading() || status() === 'idle')),
|
|
2069
2245
|
lastUpdated: lastUpdated.asReadonly(),
|
|
2070
|
-
};
|
|
2246
|
+
});
|
|
2247
|
+
}
|
|
2248
|
+
|
|
2249
|
+
/**
|
|
2250
|
+
* Bridge that projects an Angular `Resource<T>` onto `CngxAsyncState<T>`.
|
|
2251
|
+
*
|
|
2252
|
+
* Must be called in an injection context (the `effect()` that tracks
|
|
2253
|
+
* `hadSuccess` requires one).
|
|
2254
|
+
*
|
|
2255
|
+
* All signals are derived reactively from the resource - no manual
|
|
2256
|
+
* synchronization. The resource stays the single source of truth.
|
|
2257
|
+
*
|
|
2258
|
+
* ```typescript
|
|
2259
|
+
* private readonly res = resource({
|
|
2260
|
+
* request: () => ({ filter: this.filter() }),
|
|
2261
|
+
* loader: ({ request, abortSignal }) =>
|
|
2262
|
+
* fetch(`/api/items?q=${request.filter}`, { signal: abortSignal })
|
|
2263
|
+
* .then(r => r.json()),
|
|
2264
|
+
* });
|
|
2265
|
+
*
|
|
2266
|
+
* readonly items = fromResource(this.res);
|
|
2267
|
+
* // items.status(), items.data(), items.isFirstLoad() - all work
|
|
2268
|
+
* // <cngx-async-container [state]="items"> - direct binding
|
|
2269
|
+
* ```
|
|
2270
|
+
*
|
|
2271
|
+
* @category common/data/async-state
|
|
2272
|
+
*/
|
|
2273
|
+
function fromResource(ref) {
|
|
2274
|
+
return buildResourceBridge(ref);
|
|
2071
2275
|
}
|
|
2072
2276
|
|
|
2073
2277
|
/**
|
|
@@ -2092,31 +2296,7 @@ function fromResource(ref) {
|
|
|
2092
2296
|
* @category common/data/async-state
|
|
2093
2297
|
*/
|
|
2094
2298
|
function fromHttpResource(ref) {
|
|
2095
|
-
|
|
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
|
|
2299
|
+
// Map HTTP progress (0-1 float) to 0-100 integer, clamped.
|
|
2120
2300
|
const progress = computed(() => {
|
|
2121
2301
|
const p = ref.progress();
|
|
2122
2302
|
if (p == null) {
|
|
@@ -2124,50 +2304,18 @@ function fromHttpResource(ref) {
|
|
|
2124
2304
|
}
|
|
2125
2305
|
return Math.round(Math.min(p, 1) * 100);
|
|
2126
2306
|
}, ...(ngDevMode ? [{ debugName: "progress" }] : /* istanbul ignore next */ []));
|
|
2127
|
-
|
|
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
|
-
};
|
|
2307
|
+
return buildResourceBridge(ref, progress);
|
|
2163
2308
|
}
|
|
2164
2309
|
|
|
2165
2310
|
/**
|
|
2166
2311
|
* RxJS operator that wires an Observable's lifecycle to a `ManualAsyncState`.
|
|
2167
2312
|
*
|
|
2168
|
-
* On subscribe: sets `loading` (or `refreshing` if data was already loaded
|
|
2313
|
+
* On subscribe: sets `loading` (or `refreshing` if data was already loaded,
|
|
2314
|
+
* read via the sink's `isFirstLoad`; an explicit `options.status` wins).
|
|
2169
2315
|
* On next: calls `setSuccess(value)`.
|
|
2170
2316
|
* On error: calls `setError(err)` and **re-throws** (does not swallow).
|
|
2317
|
+
* On teardown without a value (unsubscribe mid-flight, empty complete):
|
|
2318
|
+
* resets the sink to `idle` so a cancelled request never leaves it busy.
|
|
2171
2319
|
*
|
|
2172
2320
|
* The Observable passes through unchanged - `tapAsyncState` is a side-effect operator.
|
|
2173
2321
|
*
|
|
@@ -2186,10 +2334,23 @@ function fromHttpResource(ref) {
|
|
|
2186
2334
|
*/
|
|
2187
2335
|
function tapAsyncState(state, options) {
|
|
2188
2336
|
return (source) => defer(() => {
|
|
2189
|
-
state.set(options?.status ?? 'loading');
|
|
2337
|
+
state.set(options?.status ?? (state.isFirstLoad?.() === false ? 'refreshing' : 'loading'));
|
|
2338
|
+
let settled = false;
|
|
2190
2339
|
return source.pipe(tap({
|
|
2191
|
-
next: (value) =>
|
|
2192
|
-
|
|
2340
|
+
next: (value) => {
|
|
2341
|
+
settled = true;
|
|
2342
|
+
state.setSuccess(value);
|
|
2343
|
+
},
|
|
2344
|
+
error: (err) => {
|
|
2345
|
+
settled = true;
|
|
2346
|
+
state.setError(err);
|
|
2347
|
+
},
|
|
2348
|
+
}), finalize(() => {
|
|
2349
|
+
// Torn down without ever settling (cancelled mid-flight or an
|
|
2350
|
+
// empty complete) - do not leave the sink busy forever.
|
|
2351
|
+
if (!settled) {
|
|
2352
|
+
state.set('idle');
|
|
2353
|
+
}
|
|
2193
2354
|
}));
|
|
2194
2355
|
});
|
|
2195
2356
|
}
|
|
@@ -2266,6 +2427,7 @@ function tapAsyncProgress(state) {
|
|
|
2266
2427
|
function tapHttpAsyncState(state, options) {
|
|
2267
2428
|
return (source) => defer(() => {
|
|
2268
2429
|
state.set(options?.status ?? 'loading');
|
|
2430
|
+
let settled = false;
|
|
2269
2431
|
return source.pipe(tapAsyncProgress(state), filter((event) => {
|
|
2270
2432
|
return event.type === RESPONSE;
|
|
2271
2433
|
}), map((response) => {
|
|
@@ -2274,8 +2436,18 @@ function tapHttpAsyncState(state, options) {
|
|
|
2274
2436
|
}
|
|
2275
2437
|
return response.body;
|
|
2276
2438
|
}), tap({
|
|
2277
|
-
next: (value) =>
|
|
2278
|
-
|
|
2439
|
+
next: (value) => {
|
|
2440
|
+
settled = true;
|
|
2441
|
+
state.setSuccess(value);
|
|
2442
|
+
},
|
|
2443
|
+
error: (err) => {
|
|
2444
|
+
settled = true;
|
|
2445
|
+
state.setError(err);
|
|
2446
|
+
},
|
|
2447
|
+
}), finalize(() => {
|
|
2448
|
+
if (!settled) {
|
|
2449
|
+
state.set('idle');
|
|
2450
|
+
}
|
|
2279
2451
|
}));
|
|
2280
2452
|
});
|
|
2281
2453
|
}
|
|
@@ -2429,7 +2601,10 @@ function provideAsyncHttpObservability() {
|
|
|
2429
2601
|
* - **success + empty** → empty template (or nothing)
|
|
2430
2602
|
* - **error (first load)** → error template (or nothing)
|
|
2431
2603
|
* - **refreshing / loading (with data)** → content template (old data stays visible)
|
|
2432
|
-
* - **error (with data)** → content template (old data stays visible)
|
|
2604
|
+
* - **error (with data)** → content template (old data stays visible) -
|
|
2605
|
+
* `resolveAsyncView` reports this as `content+error`, but a structural
|
|
2606
|
+
* directive renders exactly one template, so the error half is flattened
|
|
2607
|
+
* away here; surface it separately (toast, alert) when it must be visible
|
|
2433
2608
|
*
|
|
2434
2609
|
* ### Minimal - just content
|
|
2435
2610
|
* ```html
|
|
@@ -2486,7 +2661,10 @@ class CngxAsync {
|
|
|
2486
2661
|
const s = this.cngxAsync();
|
|
2487
2662
|
return resolveAsyncView(s.status(), s.isFirstLoad(), s.isEmpty());
|
|
2488
2663
|
}, ...(ngDevMode ? [{ debugName: "view" }] : /* istanbul ignore next */ []));
|
|
2489
|
-
|
|
2664
|
+
// Plain field, not a signal: it is only ever read and written inside the
|
|
2665
|
+
// render effect - as a signal it fed the effect's own dependency graph and
|
|
2666
|
+
// caused one spurious re-run per view switch.
|
|
2667
|
+
currentView = 'none';
|
|
2490
2668
|
contentViewRef = null;
|
|
2491
2669
|
constructor() {
|
|
2492
2670
|
effect(() => {
|
|
@@ -2494,13 +2672,13 @@ class CngxAsync {
|
|
|
2494
2672
|
const s = this.cngxAsync();
|
|
2495
2673
|
// content+error → show content (structural directive has no dual-render)
|
|
2496
2674
|
const effective = view === 'content+error' ? 'content' : view;
|
|
2497
|
-
if (effective === this.currentView
|
|
2675
|
+
if (effective === this.currentView) {
|
|
2498
2676
|
this.updateContentContext(s);
|
|
2499
2677
|
return;
|
|
2500
2678
|
}
|
|
2501
2679
|
this.vcr.clear();
|
|
2502
2680
|
this.contentViewRef = null;
|
|
2503
|
-
this.currentView
|
|
2681
|
+
this.currentView = effective;
|
|
2504
2682
|
this.renderView(effective, s);
|
|
2505
2683
|
});
|
|
2506
2684
|
}
|
|
@@ -2558,11 +2736,139 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
|
|
|
2558
2736
|
}]
|
|
2559
2737
|
}], 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
2738
|
|
|
2739
|
+
/**
|
|
2740
|
+
* The English kpi section: the single source of the KPI atoms' English copy.
|
|
2741
|
+
* `CNGX_KPI_I18N` defaults to it.
|
|
2742
|
+
*
|
|
2743
|
+
* @category common/data/i18n
|
|
2744
|
+
* @since 0.1.0
|
|
2745
|
+
* @relatedTo CNGX_KPI_I18N
|
|
2746
|
+
*/
|
|
2747
|
+
const CNGX_KPI_LANGUAGE_EN = {
|
|
2748
|
+
deltaLabel: '{value} {sentiment}',
|
|
2749
|
+
deltaImproved: 'improved',
|
|
2750
|
+
deltaDeclined: 'declined',
|
|
2751
|
+
deltaUnchanged: 'unchanged',
|
|
2752
|
+
trendLabel: '{value} {direction}',
|
|
2753
|
+
trendUp: 'up',
|
|
2754
|
+
trendDown: 'down',
|
|
2755
|
+
trendFlat: 'unchanged',
|
|
2756
|
+
goalValueText: '{now} of {max}',
|
|
2757
|
+
metricValueWithUnit: '{value} {unit}',
|
|
2758
|
+
metricPlaceholder: '\u2013',
|
|
2759
|
+
metricNoValue: 'No value',
|
|
2760
|
+
};
|
|
2761
|
+
|
|
2762
|
+
const GOAL_NUMBER = {};
|
|
2763
|
+
/** @internal Turns a kpi section into the token's keys for a locale. */
|
|
2764
|
+
function kpiBundleFrom(section, locale) {
|
|
2765
|
+
const sentiment = {
|
|
2766
|
+
positive: section.deltaImproved,
|
|
2767
|
+
negative: section.deltaDeclined,
|
|
2768
|
+
neutral: section.deltaUnchanged,
|
|
2769
|
+
};
|
|
2770
|
+
const direction = {
|
|
2771
|
+
up: section.trendUp,
|
|
2772
|
+
down: section.trendDown,
|
|
2773
|
+
flat: section.trendFlat,
|
|
2774
|
+
};
|
|
2775
|
+
const goalNumber = numberFormatterFor(locale, GOAL_NUMBER);
|
|
2776
|
+
return {
|
|
2777
|
+
deltaLabel: (value, s) => formatMessage(section.deltaLabel, { value, sentiment: sentiment[s] }, locale),
|
|
2778
|
+
trendLabel: (value, d) => formatMessage(section.trendLabel, { value, direction: direction[d] }, locale),
|
|
2779
|
+
goalValueText: (now, max) => formatMessage(section.goalValueText, { now: goalNumber.format(now), max: goalNumber.format(max) }, locale),
|
|
2780
|
+
metricValueWithUnit: section.metricValueWithUnit,
|
|
2781
|
+
metricPlaceholder: section.metricPlaceholder,
|
|
2782
|
+
metricNoValue: section.metricNoValue,
|
|
2783
|
+
};
|
|
2784
|
+
}
|
|
2785
|
+
/** @internal The kpi section of the active pack over English. */
|
|
2786
|
+
const injectKpiSection = createLanguageSection('kpi', CNGX_KPI_LANGUAGE_EN);
|
|
2787
|
+
/** @internal Builds and reads the token, formatted for the reading locale. */
|
|
2788
|
+
const kpiBundle = createSectionBundle({
|
|
2789
|
+
section: injectKpiSection,
|
|
2790
|
+
toBundle: kpiBundleFrom,
|
|
2791
|
+
});
|
|
2792
|
+
/**
|
|
2793
|
+
* DI token for the KPI i18n bundle. `providedIn: 'root'`: the kpi section
|
|
2794
|
+
* of the active language pack over the English defaults, formatted for the
|
|
2795
|
+
* app locale; the value is a `Signal`, shared by every reader under one
|
|
2796
|
+
* injector.
|
|
2797
|
+
*
|
|
2798
|
+
* @category common/data/i18n
|
|
2799
|
+
* @wcag AA
|
|
2800
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/data/display/shared/kpi-i18n.ts
|
|
2801
|
+
* @since 0.1.0
|
|
2802
|
+
* @relatedTo CngxDelta, CngxTrend, CngxGoal
|
|
2803
|
+
*/
|
|
2804
|
+
const CNGX_KPI_I18N = new InjectionToken('CngxKpiI18n', {
|
|
2805
|
+
providedIn: 'root',
|
|
2806
|
+
factory: () => kpiBundle.build(),
|
|
2807
|
+
});
|
|
2808
|
+
/** @internal */
|
|
2809
|
+
function defineKpiI18nFeature(fn) {
|
|
2810
|
+
return Object.assign(fn, { _target: 'i18n' });
|
|
2811
|
+
}
|
|
2812
|
+
/**
|
|
2813
|
+
* Override KPI labels via a partial bundle - unset keys keep the language
|
|
2814
|
+
* pack's copy, or the English default. Pass a `Signal` of a partial bundle to switch languages at
|
|
2815
|
+
* runtime.
|
|
2816
|
+
*
|
|
2817
|
+
* @category common/data/i18n
|
|
2818
|
+
* @since 0.1.0
|
|
2819
|
+
*/
|
|
2820
|
+
function withKpiI18nLabels(overrides) {
|
|
2821
|
+
return defineKpiI18nFeature((bundle) => createOverrideMerge(bundle, overrides));
|
|
2822
|
+
}
|
|
2823
|
+
/**
|
|
2824
|
+
* Provider for the KPI i18n bundle. Returns a plain `Provider`, so it also
|
|
2825
|
+
* scopes a subtree through `viewProviders`. The features apply on top of the
|
|
2826
|
+
* active language pack.
|
|
2827
|
+
*
|
|
2828
|
+
* ```ts
|
|
2829
|
+
* bootstrapApplication(AppComponent, {
|
|
2830
|
+
* providers: [
|
|
2831
|
+
* provideKpiI18n(
|
|
2832
|
+
* withKpiI18nLabels({
|
|
2833
|
+
* goalValueText: (now, max) => `${now} von ${max}`,
|
|
2834
|
+
* }),
|
|
2835
|
+
* ),
|
|
2836
|
+
* ],
|
|
2837
|
+
* });
|
|
2838
|
+
* ```
|
|
2839
|
+
*
|
|
2840
|
+
* @category common/data/i18n
|
|
2841
|
+
* @since 0.1.0
|
|
2842
|
+
*/
|
|
2843
|
+
function provideKpiI18n(...features) {
|
|
2844
|
+
return {
|
|
2845
|
+
provide: CNGX_KPI_I18N,
|
|
2846
|
+
useFactory: () => kpiBundle.build(features),
|
|
2847
|
+
};
|
|
2848
|
+
}
|
|
2849
|
+
/**
|
|
2850
|
+
* Inject the resolved KPI i18n bundle signal. Read it inside a `computed()`
|
|
2851
|
+
* or template so a runtime override flip re-derives.
|
|
2852
|
+
*
|
|
2853
|
+
* @category common/data/i18n
|
|
2854
|
+
* @since 0.1.0
|
|
2855
|
+
*/
|
|
2856
|
+
function injectKpiI18n() {
|
|
2857
|
+
return kpiBundle.resolve(inject(CNGX_KPI_I18N));
|
|
2858
|
+
}
|
|
2859
|
+
|
|
2860
|
+
const UNIT_PLACEHOLDER = /\{(value|unit)\}/;
|
|
2861
|
+
/** @internal `true` when the language reads the unit before the value. */
|
|
2862
|
+
function readsUnitFirst(message) {
|
|
2863
|
+
const [, first] = UNIT_PLACEHOLDER.exec(message) ?? [];
|
|
2864
|
+
return first === 'unit';
|
|
2865
|
+
}
|
|
2561
2866
|
/**
|
|
2562
2867
|
* Displays a formatted numeric value with optional unit.
|
|
2563
2868
|
*
|
|
2564
|
-
* Uses `Intl.NumberFormat` with the
|
|
2565
|
-
*
|
|
2869
|
+
* Uses `Intl.NumberFormat` with the app locale (`CNGX_LOCALE`, falling back to
|
|
2870
|
+
* the nearest `LOCALE_ID`) for locale-aware formatting; a locale flip
|
|
2871
|
+
* re-formats. A `null` value renders the placeholder glyph without its unit.
|
|
2566
2872
|
*
|
|
2567
2873
|
* Composable - works inside any card variant, header, body, or standalone.
|
|
2568
2874
|
*
|
|
@@ -2595,8 +2901,12 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
|
|
|
2595
2901
|
* <example-url>http://localhost:4200/#/common/data/metric/standalone-metrics</example-url>
|
|
2596
2902
|
*/
|
|
2597
2903
|
class CngxMetric {
|
|
2598
|
-
locale =
|
|
2599
|
-
|
|
2904
|
+
locale = injectLocale();
|
|
2905
|
+
i18n = injectKpiI18n();
|
|
2906
|
+
/**
|
|
2907
|
+
* Numeric or string value. `null` renders the `metricPlaceholder` glyph of
|
|
2908
|
+
* the kpi language section and is announced as its `metricNoValue` text.
|
|
2909
|
+
*/
|
|
2600
2910
|
value = input.required(...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
|
|
2601
2911
|
/** Unit suffix (e.g. "bpm", "h", "%", "kg"). */
|
|
2602
2912
|
unit = input(undefined, ...(ngDevMode ? [{ debugName: "unit" }] : /* istanbul ignore next */ []));
|
|
@@ -2606,26 +2916,41 @@ class CngxMetric {
|
|
|
2606
2916
|
formattedValue = computed(() => {
|
|
2607
2917
|
const v = this.value();
|
|
2608
2918
|
if (v === null) {
|
|
2609
|
-
return
|
|
2919
|
+
return this.i18n().metricPlaceholder;
|
|
2610
2920
|
}
|
|
2611
2921
|
if (typeof v === 'string') {
|
|
2612
2922
|
return v;
|
|
2613
2923
|
}
|
|
2614
|
-
return this.format()
|
|
2615
|
-
? new Intl.NumberFormat(this.locale, this.format()).format(v)
|
|
2616
|
-
: v.toLocaleString(this.locale);
|
|
2924
|
+
return numberFormatterFor(this.locale(), this.format() ?? {}).format(v);
|
|
2617
2925
|
}, ...(ngDevMode ? [{ debugName: "formattedValue" }] : /* istanbul ignore next */ []));
|
|
2926
|
+
/**
|
|
2927
|
+
* @internal The unit to render, `undefined` while there is no value: a
|
|
2928
|
+
* missing reading has no unit, so "No value km" is never shown or spoken.
|
|
2929
|
+
*/
|
|
2930
|
+
shownUnit = computed(() => {
|
|
2931
|
+
const unit = this.unit();
|
|
2932
|
+
return this.value() === null || unit === '' ? undefined : unit;
|
|
2933
|
+
}, ...(ngDevMode ? [{ debugName: "shownUnit" }] : /* istanbul ignore next */ []));
|
|
2934
|
+
/** @internal Unit before value, per the `metricValueWithUnit` message. */
|
|
2935
|
+
unitFirst = computed(() => readsUnitFirst(this.i18n().metricValueWithUnit), ...(ngDevMode ? [{ debugName: "unitFirst" }] : /* istanbul ignore next */ []));
|
|
2618
2936
|
/** @internal Full accessible description including unit. */
|
|
2619
2937
|
accessibleValue = computed(() => {
|
|
2620
|
-
const
|
|
2621
|
-
|
|
2622
|
-
|
|
2938
|
+
const i18n = this.i18n();
|
|
2939
|
+
if (this.value() === null) {
|
|
2940
|
+
return i18n.metricNoValue;
|
|
2941
|
+
}
|
|
2942
|
+
const value = this.formattedValue();
|
|
2943
|
+
const unit = this.shownUnit();
|
|
2944
|
+
return unit ? formatMessage(i18n.metricValueWithUnit, { value, unit }, this.locale()) : value;
|
|
2623
2945
|
}, ...(ngDevMode ? [{ debugName: "accessibleValue" }] : /* istanbul ignore next */ []));
|
|
2624
2946
|
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxMetric, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
2625
2947
|
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: `
|
|
2948
|
+
@if (shownUnit() && unitFirst()) {
|
|
2949
|
+
<span class="cngx-metric__unit">{{ shownUnit() }}</span>
|
|
2950
|
+
}
|
|
2626
2951
|
<span class="cngx-metric__value">{{ formattedValue() }}</span>
|
|
2627
|
-
@if (
|
|
2628
|
-
<span class="cngx-metric__unit">{{
|
|
2952
|
+
@if (shownUnit() && !unitFirst()) {
|
|
2953
|
+
<span class="cngx-metric__unit">{{ shownUnit() }}</span>
|
|
2629
2954
|
}
|
|
2630
2955
|
`, 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
2956
|
}
|
|
@@ -2640,9 +2965,12 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
|
|
|
2640
2965
|
role: 'img',
|
|
2641
2966
|
'[attr.aria-label]': 'accessibleValue()',
|
|
2642
2967
|
}, template: `
|
|
2968
|
+
@if (shownUnit() && unitFirst()) {
|
|
2969
|
+
<span class="cngx-metric__unit">{{ shownUnit() }}</span>
|
|
2970
|
+
}
|
|
2643
2971
|
<span class="cngx-metric__value">{{ formattedValue() }}</span>
|
|
2644
|
-
@if (
|
|
2645
|
-
<span class="cngx-metric__unit">{{
|
|
2972
|
+
@if (shownUnit() && !unitFirst()) {
|
|
2973
|
+
<span class="cngx-metric__unit">{{ shownUnit() }}</span>
|
|
2646
2974
|
}
|
|
2647
2975
|
`, 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
2976
|
}], 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 +3011,26 @@ function directionGlyph(direction) {
|
|
|
2683
3011
|
/**
|
|
2684
3012
|
* Format the magnitude. The sign is carried by the arrow and colour, not the
|
|
2685
3013
|
* digits: a positive value gains a leading `+`, everything else prints its
|
|
2686
|
-
* absolute value unsigned. Percent mode
|
|
2687
|
-
* and defaults to one fraction digit;
|
|
3014
|
+
* absolute value unsigned. Percent mode formats with `Intl` `style: 'percent'`
|
|
3015
|
+
* (so the locale places the `%` sign) and defaults to one fraction digit;
|
|
3016
|
+
* absolute mode uses the locale grouping.
|
|
2688
3017
|
* A supplied `Intl.NumberFormatOptions` overrides the default digit handling
|
|
2689
3018
|
* in both modes.
|
|
2690
3019
|
*/
|
|
2691
3020
|
function formatDelta(value, mode, locale, format) {
|
|
2692
3021
|
const abs = Math.abs(value);
|
|
2693
|
-
|
|
3022
|
+
// The locale places and draws the plus sign; a negative prints unsigned.
|
|
3023
|
+
const signDisplay = value > 0 ? 'exceptZero' : 'never';
|
|
2694
3024
|
if (mode === 'percent') {
|
|
2695
|
-
|
|
2696
|
-
|
|
3025
|
+
// The input is already in percent units; Intl's percent style multiplies
|
|
3026
|
+
// by 100, so scale down first.
|
|
3027
|
+
return numberFormatterFor(locale, {
|
|
3028
|
+
...(format ?? { minimumFractionDigits: 1, maximumFractionDigits: 1 }),
|
|
3029
|
+
style: 'percent',
|
|
3030
|
+
signDisplay,
|
|
3031
|
+
}).format(abs / 100);
|
|
2697
3032
|
}
|
|
2698
|
-
|
|
2699
|
-
return `${prefix}${num}`;
|
|
3033
|
+
return numberFormatterFor(locale, { ...format, signDisplay }).format(abs);
|
|
2700
3034
|
}
|
|
2701
3035
|
|
|
2702
3036
|
/**
|
|
@@ -2737,7 +3071,8 @@ function formatDelta(value, mode, locale, format) {
|
|
|
2737
3071
|
* <example-url>http://localhost:4200/#/common/data/trend/trend-directions</example-url>
|
|
2738
3072
|
*/
|
|
2739
3073
|
class CngxTrend {
|
|
2740
|
-
locale =
|
|
3074
|
+
locale = injectLocale();
|
|
3075
|
+
i18n = injectKpiI18n();
|
|
2741
3076
|
/** Trend percentage. Positive = up, negative = down, zero = flat. */
|
|
2742
3077
|
value = input.required(...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
|
|
2743
3078
|
/** Consumer-provided SR label override. When set, replaces the generated default. */
|
|
@@ -2745,16 +3080,10 @@ class CngxTrend {
|
|
|
2745
3080
|
/** @internal */
|
|
2746
3081
|
icon = computed(() => directionGlyph(deltaDirection(this.value())), ...(ngDevMode ? [{ debugName: "icon" }] : /* istanbul ignore next */ []));
|
|
2747
3082
|
/** @internal */
|
|
2748
|
-
formattedValue = computed(() => formatDelta(this.value(), 'percent', this.locale), ...(ngDevMode ? [{ debugName: "formattedValue" }] : /* istanbul ignore next */ []));
|
|
3083
|
+
formattedValue = computed(() => formatDelta(this.value(), 'percent', this.locale()), ...(ngDevMode ? [{ debugName: "formattedValue" }] : /* istanbul ignore next */ []));
|
|
2749
3084
|
/** @internal */
|
|
2750
|
-
resolvedLabel = computed(() =>
|
|
2751
|
-
|
|
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 */ []));
|
|
3085
|
+
resolvedLabel = computed(() => this.label() ??
|
|
3086
|
+
this.i18n().trendLabel(this.formattedValue(), deltaDirection(this.value())), ...(ngDevMode ? [{ debugName: "resolvedLabel" }] : /* istanbul ignore next */ []));
|
|
2758
3087
|
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTrend, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
2759
3088
|
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
3089
|
<span aria-hidden="true">{{ icon() }}</span>
|
|
@@ -2778,11 +3107,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
|
|
|
2778
3107
|
`, 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
3108
|
}], propDecorators: { value: [{ type: i0.Input, args: [{ isSignal: true, alias: "value", required: true }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }] } });
|
|
2780
3109
|
|
|
2781
|
-
const SENTIMENT_WORD = {
|
|
2782
|
-
positive: 'improved',
|
|
2783
|
-
negative: 'declined',
|
|
2784
|
-
neutral: 'unchanged',
|
|
2785
|
-
};
|
|
2786
3110
|
/**
|
|
2787
3111
|
* Sentiment-aware delta indicator. Where `CngxTrend` colours strictly by
|
|
2788
3112
|
* direction (up = green), `CngxDelta` colours by **sentiment**: a `polarity`
|
|
@@ -2821,7 +3145,8 @@ const SENTIMENT_WORD = {
|
|
|
2821
3145
|
* <example-url>http://localhost:4200/#/common/data/delta/sentiment-polarity</example-url>
|
|
2822
3146
|
*/
|
|
2823
3147
|
class CngxDelta {
|
|
2824
|
-
locale =
|
|
3148
|
+
locale = injectLocale();
|
|
3149
|
+
i18n = injectKpiI18n();
|
|
2825
3150
|
/** Signed delta. Positive = up, negative = down, zero = flat. */
|
|
2826
3151
|
value = input.required(...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
|
|
2827
3152
|
/**
|
|
@@ -2843,15 +3168,12 @@ class CngxDelta {
|
|
|
2843
3168
|
/** @internal Arrow glyph bound from direction only. */
|
|
2844
3169
|
glyph = computed(() => directionGlyph(this.direction()), ...(ngDevMode ? [{ debugName: "glyph" }] : /* istanbul ignore next */ []));
|
|
2845
3170
|
/** @internal Formatted magnitude. */
|
|
2846
|
-
formattedValue = computed(() => formatDelta(this.value(), this.mode(), this.locale, this.format()), ...(ngDevMode ? [{ debugName: "formattedValue" }] : /* istanbul ignore next */ []));
|
|
2847
|
-
/**
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
}
|
|
2853
|
-
return `${this.formattedValue()} ${SENTIMENT_WORD[this.sentiment()]}`;
|
|
2854
|
-
}, ...(ngDevMode ? [{ debugName: "resolvedLabel" }] : /* istanbul ignore next */ []));
|
|
3171
|
+
formattedValue = computed(() => formatDelta(this.value(), this.mode(), this.locale(), this.format()), ...(ngDevMode ? [{ debugName: "formattedValue" }] : /* istanbul ignore next */ []));
|
|
3172
|
+
/**
|
|
3173
|
+
* @internal Full SR label: magnitude plus the sentiment word, composed by
|
|
3174
|
+
* `CNGX_KPI_I18N.deltaLabel` unless `[label]` is bound.
|
|
3175
|
+
*/
|
|
3176
|
+
resolvedLabel = computed(() => this.label() ?? this.i18n().deltaLabel(this.formattedValue(), this.sentiment()), ...(ngDevMode ? [{ debugName: "resolvedLabel" }] : /* istanbul ignore next */ []));
|
|
2855
3177
|
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxDelta, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
2856
3178
|
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
3179
|
<span aria-hidden="true">{{ glyph() }}</span>
|
|
@@ -2914,8 +3236,13 @@ class CngxStatCoordinator {
|
|
|
2914
3236
|
this.slots.update((prev) => new Map(prev).set(kind, id));
|
|
2915
3237
|
}
|
|
2916
3238
|
/** {@inheritDoc CngxStatRegistry.unregister} */
|
|
2917
|
-
unregister(kind) {
|
|
3239
|
+
unregister(kind, id) {
|
|
2918
3240
|
this.slots.update((prev) => {
|
|
3241
|
+
if (id !== undefined && prev.get(kind) !== id) {
|
|
3242
|
+
// Register-before-destroy replacement: the outgoing slot must not
|
|
3243
|
+
// evict the live slot's id from aria-labelledby.
|
|
3244
|
+
return prev;
|
|
3245
|
+
}
|
|
2919
3246
|
const next = new Map(prev);
|
|
2920
3247
|
next.delete(kind);
|
|
2921
3248
|
return next;
|
|
@@ -3027,7 +3354,7 @@ function useStatSlot(kind) {
|
|
|
3027
3354
|
const registry = inject(CNGX_STAT, { optional: true });
|
|
3028
3355
|
const id = nextUid(`cngx-stat-${kind}`);
|
|
3029
3356
|
registry?.register(kind, id);
|
|
3030
|
-
inject(DestroyRef).onDestroy(() => registry?.unregister(kind));
|
|
3357
|
+
inject(DestroyRef).onDestroy(() => registry?.unregister(kind, id));
|
|
3031
3358
|
return id;
|
|
3032
3359
|
}
|
|
3033
3360
|
/**
|
|
@@ -3132,7 +3459,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
|
|
|
3132
3459
|
* derived percent bound as a CSS custom property.
|
|
3133
3460
|
*
|
|
3134
3461
|
* ```html
|
|
3135
|
-
* <cngx-goal [value]="73" [max]="100" />
|
|
3462
|
+
* <cngx-goal [value]="73" [max]="100" label="Quota attainment" />
|
|
3136
3463
|
* <cngx-goal [value]="q()" [max]="target()" [valueTextFormat]="quotaText" />
|
|
3137
3464
|
* ```
|
|
3138
3465
|
*
|
|
@@ -3146,14 +3473,23 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
|
|
|
3146
3473
|
* <example-url>http://localhost:4200/#/common/data/goal/quota-attainment</example-url>
|
|
3147
3474
|
*/
|
|
3148
3475
|
class CngxGoal {
|
|
3476
|
+
i18n = injectKpiI18n();
|
|
3149
3477
|
/** Current attainment. Clamped to `[0, max]`. */
|
|
3150
3478
|
value = input.required(...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
|
|
3151
3479
|
/** Target the value works toward. Defaults to `100`. */
|
|
3152
3480
|
max = input(100, ...(ngDevMode ? [{ debugName: "max" }] : /* istanbul ignore next */ []));
|
|
3481
|
+
/**
|
|
3482
|
+
* Accessible name for the progressbar (what the attainment measures, e.g.
|
|
3483
|
+
* "Quarterly quota"). Mirrors the `label` input of the sibling KPI atoms;
|
|
3484
|
+
* omit it only when an external `aria-labelledby` (e.g. a `cngxStatLabel`)
|
|
3485
|
+
* names the bar instead.
|
|
3486
|
+
*/
|
|
3487
|
+
label = input(undefined, ...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
|
|
3153
3488
|
/**
|
|
3154
3489
|
* Override the `aria-valuetext` string. Receives `(now, max)` - the clamped
|
|
3155
|
-
* value and the target.
|
|
3156
|
-
*
|
|
3490
|
+
* value and the target. Wins over the app-wide `CNGX_KPI_I18N.goalValueText`
|
|
3491
|
+
* (English default `(now, max) => \`${now} of ${max}\``). Supply a closure
|
|
3492
|
+
* for richer per-instance text (e.g.
|
|
3157
3493
|
* `(n, m) => \`${n} of ${m}, ${Math.round((n / m) * 100)}% of quota\``).
|
|
3158
3494
|
*/
|
|
3159
3495
|
valueTextFormat = input(undefined, ...(ngDevMode ? [{ debugName: "valueTextFormat" }] : /* istanbul ignore next */ []));
|
|
@@ -3168,11 +3504,11 @@ class CngxGoal {
|
|
|
3168
3504
|
}, ...(ngDevMode ? [{ debugName: "fillPercent" }] : /* istanbul ignore next */ []));
|
|
3169
3505
|
/** `aria-valuetext` - human-readable attainment via the resolved closure. */
|
|
3170
3506
|
valueText = computed(() => {
|
|
3171
|
-
const fmt = this.valueTextFormat() ?? (
|
|
3507
|
+
const fmt = this.valueTextFormat() ?? this.i18n().goalValueText;
|
|
3172
3508
|
return fmt(this.now(), this.maxValue());
|
|
3173
3509
|
}, ...(ngDevMode ? [{ debugName: "valueText" }] : /* istanbul ignore next */ []));
|
|
3174
3510
|
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 });
|
|
3511
|
+
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
3512
|
}
|
|
3177
3513
|
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxGoal, decorators: [{
|
|
3178
3514
|
type: Component,
|
|
@@ -3183,9 +3519,28 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
|
|
|
3183
3519
|
'[attr.aria-valuemax]': 'maxValue()',
|
|
3184
3520
|
'[attr.aria-valuenow]': 'now()',
|
|
3185
3521
|
'[attr.aria-valuetext]': 'valueText()',
|
|
3522
|
+
'[attr.aria-label]': 'label() ?? null',
|
|
3186
3523
|
'[style.--cngx-goal-fill.%]': 'fillPercent()',
|
|
3187
3524
|
}, 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 }] }] } });
|
|
3525
|
+
}], 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 }] }] } });
|
|
3526
|
+
|
|
3527
|
+
/**
|
|
3528
|
+
* The English recycler section: the single source of the recycler's English
|
|
3529
|
+
* copy. `CNGX_RECYCLER_I18N` defaults to it.
|
|
3530
|
+
*
|
|
3531
|
+
* @category common/data/i18n
|
|
3532
|
+
* @since 0.1.0
|
|
3533
|
+
* @relatedTo CNGX_RECYCLER_I18N
|
|
3534
|
+
*/
|
|
3535
|
+
const CNGX_RECYCLER_LANGUAGE_EN = {
|
|
3536
|
+
loaded: {
|
|
3537
|
+
one: '{count} more item loaded. {total} total.',
|
|
3538
|
+
other: '{count} more items loaded. {total} total.',
|
|
3539
|
+
},
|
|
3540
|
+
filtered: { one: '{count} result found.', other: '{count} results found.' },
|
|
3541
|
+
empty: 'No results',
|
|
3542
|
+
error: 'Error loading data',
|
|
3543
|
+
};
|
|
3189
3544
|
|
|
3190
3545
|
const EMPTY_RANGE = {
|
|
3191
3546
|
start: 0,
|
|
@@ -3204,31 +3559,58 @@ const EMPTY_RANGE = {
|
|
|
3204
3559
|
* @param clientHeight Viewport height in px.
|
|
3205
3560
|
* @param totalCount Total number of items.
|
|
3206
3561
|
* @param estimateSize Fixed item height in px, or a function returning height per index.
|
|
3207
|
-
* @param
|
|
3562
|
+
* @param overscanBefore Extra items to render above the viewport (leading edge
|
|
3563
|
+
* when scrolling up).
|
|
3208
3564
|
* @param columns Column count for grid mode (default 1). When > 1, range is row-aligned.
|
|
3209
3565
|
* Variable `estimateSize` ignores columns (grid + variable heights not supported).
|
|
3566
|
+
* @param overscanAfter Extra items to render below the viewport (leading edge when
|
|
3567
|
+
* scrolling down). Defaults to `overscanBefore` for a symmetric range. Callers pass
|
|
3568
|
+
* an asymmetric pair to pre-render into the scroll direction.
|
|
3210
3569
|
* @returns The computed range with spacer offsets.
|
|
3211
3570
|
* @internal
|
|
3212
3571
|
*/
|
|
3213
|
-
function computeRange(scrollTop, clientHeight, totalCount, estimateSize,
|
|
3214
|
-
if (totalCount <= 0
|
|
3572
|
+
function computeRange(scrollTop, clientHeight, totalCount, estimateSize, overscanBefore, columns = 1, overscanAfter = overscanBefore) {
|
|
3573
|
+
if (totalCount <= 0) {
|
|
3215
3574
|
return EMPTY_RANGE;
|
|
3216
3575
|
}
|
|
3576
|
+
if (clientHeight <= 0) {
|
|
3577
|
+
// Degenerate viewport (0px). A content-driven scrollport gets its height
|
|
3578
|
+
// FROM the spacers this result sizes, so reporting `totalSize: 0` here
|
|
3579
|
+
// deadlocks: no spacer, no height, no spacer. Report the full totalSize
|
|
3580
|
+
// with an empty window instead - the after-spacer gives the viewport its
|
|
3581
|
+
// height, the ResizeObserver-fed `clientHeight` turns non-zero, and the
|
|
3582
|
+
// next computation renders the real range.
|
|
3583
|
+
const totalSize = estimateTotalSize(totalCount, estimateSize, columns);
|
|
3584
|
+
return { start: 0, end: 0, offsetBefore: 0, offsetAfter: totalSize, totalSize };
|
|
3585
|
+
}
|
|
3217
3586
|
if (typeof estimateSize === 'number') {
|
|
3218
|
-
return computeFixedRange(scrollTop, clientHeight, totalCount, estimateSize,
|
|
3587
|
+
return computeFixedRange(scrollTop, clientHeight, totalCount, estimateSize, overscanBefore, overscanAfter, columns);
|
|
3219
3588
|
}
|
|
3220
3589
|
// variable heights: grid mode unsupported, columns ignored
|
|
3221
|
-
return computeVariableRange(scrollTop, clientHeight, totalCount, estimateSize,
|
|
3590
|
+
return computeVariableRange(scrollTop, clientHeight, totalCount, estimateSize, overscanBefore, overscanAfter);
|
|
3591
|
+
}
|
|
3592
|
+
function estimateTotalSize(totalCount, estimateSize, columns) {
|
|
3593
|
+
if (typeof estimateSize === 'number') {
|
|
3594
|
+
const rows = columns > 1 ? Math.ceil(totalCount / columns) : totalCount;
|
|
3595
|
+
return rows * estimateSize;
|
|
3596
|
+
}
|
|
3597
|
+
// variable heights: grid mode unsupported, columns ignored (same contract
|
|
3598
|
+
// as computeVariableRange)
|
|
3599
|
+
let totalSize = 0;
|
|
3600
|
+
for (let i = 0; i < totalCount; i++) {
|
|
3601
|
+
totalSize += estimateSize(i);
|
|
3602
|
+
}
|
|
3603
|
+
return totalSize;
|
|
3222
3604
|
}
|
|
3223
|
-
function computeFixedRange(scrollTop, clientHeight, totalCount, itemSize,
|
|
3605
|
+
function computeFixedRange(scrollTop, clientHeight, totalCount, itemSize, overscanBefore, overscanAfter, columns) {
|
|
3224
3606
|
if (columns > 1) {
|
|
3225
|
-
return computeGridRange(scrollTop, clientHeight, totalCount, itemSize,
|
|
3607
|
+
return computeGridRange(scrollTop, clientHeight, totalCount, itemSize, overscanBefore, overscanAfter, columns);
|
|
3226
3608
|
}
|
|
3227
3609
|
const totalSize = totalCount * itemSize;
|
|
3228
3610
|
const rawStart = Math.floor(scrollTop / itemSize);
|
|
3229
3611
|
const rawEnd = Math.ceil((scrollTop + clientHeight) / itemSize);
|
|
3230
|
-
const start = Math.max(0, rawStart -
|
|
3231
|
-
const end = Math.min(totalCount, rawEnd +
|
|
3612
|
+
const start = Math.max(0, rawStart - overscanBefore);
|
|
3613
|
+
const end = Math.min(totalCount, rawEnd + overscanAfter);
|
|
3232
3614
|
return {
|
|
3233
3615
|
start,
|
|
3234
3616
|
end,
|
|
@@ -3245,16 +3627,17 @@ function computeFixedRange(scrollTop, clientHeight, totalCount, itemSize, oversc
|
|
|
3245
3627
|
*
|
|
3246
3628
|
* @internal
|
|
3247
3629
|
*/
|
|
3248
|
-
function computeGridRange(scrollTop, clientHeight, totalCount, rowHeight,
|
|
3630
|
+
function computeGridRange(scrollTop, clientHeight, totalCount, rowHeight, overscanBefore, overscanAfter, columns) {
|
|
3249
3631
|
const totalRows = Math.ceil(totalCount / columns);
|
|
3250
3632
|
const totalSize = totalRows * rowHeight;
|
|
3251
3633
|
// raw rows (inherently row-aligned)
|
|
3252
3634
|
const rawStartRow = Math.floor(scrollTop / rowHeight);
|
|
3253
3635
|
const rawEndRow = Math.ceil((scrollTop + clientHeight) / rowHeight);
|
|
3254
3636
|
// overscan applied in rows so full rows always render
|
|
3255
|
-
const
|
|
3256
|
-
const
|
|
3257
|
-
const
|
|
3637
|
+
const overscanRowsBefore = Math.ceil(overscanBefore / columns);
|
|
3638
|
+
const overscanRowsAfter = Math.ceil(overscanAfter / columns);
|
|
3639
|
+
const startRow = Math.max(0, rawStartRow - overscanRowsBefore);
|
|
3640
|
+
const endRow = Math.min(totalRows, rawEndRow + overscanRowsAfter);
|
|
3258
3641
|
const start = startRow * columns;
|
|
3259
3642
|
const end = Math.min(endRow * columns, totalCount);
|
|
3260
3643
|
return {
|
|
@@ -3265,7 +3648,7 @@ function computeGridRange(scrollTop, clientHeight, totalCount, rowHeight, oversc
|
|
|
3265
3648
|
totalSize,
|
|
3266
3649
|
};
|
|
3267
3650
|
}
|
|
3268
|
-
function computeVariableRange(scrollTop, clientHeight, totalCount, estimateSize,
|
|
3651
|
+
function computeVariableRange(scrollTop, clientHeight, totalCount, estimateSize, overscanBefore, overscanAfter) {
|
|
3269
3652
|
let totalSize = 0;
|
|
3270
3653
|
const offsets = new Array(totalCount + 1);
|
|
3271
3654
|
offsets[0] = 0;
|
|
@@ -3276,8 +3659,8 @@ function computeVariableRange(scrollTop, clientHeight, totalCount, estimateSize,
|
|
|
3276
3659
|
// binary search: first item whose bottom edge is past scrollTop
|
|
3277
3660
|
const rawStart = binarySearch(offsets, scrollTop, totalCount);
|
|
3278
3661
|
const rawEnd = binarySearch(offsets, scrollTop + clientHeight, totalCount);
|
|
3279
|
-
const start = Math.max(0, rawStart -
|
|
3280
|
-
const end = Math.min(totalCount, rawEnd + 1 +
|
|
3662
|
+
const start = Math.max(0, rawStart - overscanBefore);
|
|
3663
|
+
const end = Math.min(totalCount, rawEnd + 1 + overscanAfter);
|
|
3281
3664
|
return {
|
|
3282
3665
|
start,
|
|
3283
3666
|
end,
|
|
@@ -3348,28 +3731,21 @@ function createScrollObserver(elementRef, destroyRef) {
|
|
|
3348
3731
|
elementState.set(el);
|
|
3349
3732
|
scrollTopState.set(el.scrollTop);
|
|
3350
3733
|
clientHeightState.set(el.clientHeight);
|
|
3351
|
-
|
|
3734
|
+
// Read scrollTop synchronously on the scroll event rather than deferring to
|
|
3735
|
+
// a requestAnimationFrame. The rAF hop delayed the range by a frame, so a
|
|
3736
|
+
// fast scroll outran the rendered window and flashed a blank strip. Scroll
|
|
3737
|
+
// events already fire at most once per frame, and the signal scheduler
|
|
3738
|
+
// coalesces bursts, so the synchronous read carries no extra recompute cost.
|
|
3352
3739
|
const handleScroll = () => {
|
|
3353
|
-
|
|
3354
|
-
return;
|
|
3355
|
-
}
|
|
3356
|
-
rafId = requestAnimationFrame(() => {
|
|
3357
|
-
rafId = null;
|
|
3358
|
-
scrollTopState.set(el.scrollTop);
|
|
3359
|
-
clientHeightState.set(el.clientHeight);
|
|
3360
|
-
});
|
|
3740
|
+
scrollTopState.set(el.scrollTop);
|
|
3361
3741
|
};
|
|
3362
3742
|
el.addEventListener('scroll', handleScroll, { passive: true });
|
|
3363
|
-
const
|
|
3743
|
+
const stopResize = observeResize(doc.defaultView, el, 'content-box', () => {
|
|
3364
3744
|
clientHeightState.set(el.clientHeight);
|
|
3365
3745
|
});
|
|
3366
|
-
resizeObserver.observe(el);
|
|
3367
3746
|
onCleanup(() => {
|
|
3368
3747
|
el.removeEventListener('scroll', handleScroll);
|
|
3369
|
-
|
|
3370
|
-
cancelAnimationFrame(rafId);
|
|
3371
|
-
}
|
|
3372
|
-
resizeObserver.disconnect();
|
|
3748
|
+
stopResize();
|
|
3373
3749
|
elementState.set(null);
|
|
3374
3750
|
});
|
|
3375
3751
|
}
|
|
@@ -3483,9 +3859,27 @@ function createSizeCache() {
|
|
|
3483
3859
|
};
|
|
3484
3860
|
}
|
|
3485
3861
|
|
|
3862
|
+
/** @internal Turns a recycler section into the token's keys for a locale. */
|
|
3863
|
+
function recyclerBundleFrom(section, locale) {
|
|
3864
|
+
return {
|
|
3865
|
+
loaded: (count, total) => formatMessage(section.loaded, { count, total }, locale),
|
|
3866
|
+
filtered: (count) => formatMessage(section.filtered, { count }, locale),
|
|
3867
|
+
empty: () => section.empty,
|
|
3868
|
+
error: () => section.error,
|
|
3869
|
+
};
|
|
3870
|
+
}
|
|
3871
|
+
/** @internal The recycler section of the active pack over English. */
|
|
3872
|
+
const injectRecyclerSection = createLanguageSection('recycler', CNGX_RECYCLER_LANGUAGE_EN);
|
|
3873
|
+
/** @internal Builds and reads the token, formatted for the reading locale. */
|
|
3874
|
+
const recyclerBundle = createSectionBundle({
|
|
3875
|
+
section: injectRecyclerSection,
|
|
3876
|
+
toBundle: recyclerBundleFrom,
|
|
3877
|
+
});
|
|
3486
3878
|
/**
|
|
3487
|
-
* Injection token for recycler SR announcement texts
|
|
3488
|
-
*
|
|
3879
|
+
* Injection token for recycler SR announcement texts, a `Signal` so the
|
|
3880
|
+
* texts follow a runtime language switch. Defaults to the recycler section
|
|
3881
|
+
* of the active language pack over English, counts formatted for the app
|
|
3882
|
+
* locale. Override with `provideRecyclerI18n()`.
|
|
3489
3883
|
*
|
|
3490
3884
|
* @category common/data/recycler
|
|
3491
3885
|
* @wcag AA
|
|
@@ -3493,29 +3887,44 @@ function createSizeCache() {
|
|
|
3493
3887
|
* @since 0.1.0
|
|
3494
3888
|
*/
|
|
3495
3889
|
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
|
-
}),
|
|
3890
|
+
factory: () => recyclerBundle.build(),
|
|
3502
3891
|
});
|
|
3892
|
+
/** @internal */
|
|
3893
|
+
function defineRecyclerI18nFeature(fn) {
|
|
3894
|
+
return Object.assign(fn, { _target: 'i18n' });
|
|
3895
|
+
}
|
|
3896
|
+
/**
|
|
3897
|
+
* Override recycler announcements via a partial bundle - keys you leave out
|
|
3898
|
+
* keep the language pack's text, or the English default. Pass a `Signal` to
|
|
3899
|
+
* switch the language at runtime.
|
|
3900
|
+
*
|
|
3901
|
+
* @category common/data/recycler
|
|
3902
|
+
*/
|
|
3903
|
+
function withRecyclerI18nLabels(overrides) {
|
|
3904
|
+
return defineRecyclerI18nFeature((bundle) => createOverrideMerge(bundle, overrides));
|
|
3905
|
+
}
|
|
3503
3906
|
/**
|
|
3504
|
-
* Provider
|
|
3907
|
+
* Provider for the recycler announcement texts. The features apply on top of
|
|
3908
|
+
* the active language pack.
|
|
3505
3909
|
*
|
|
3506
3910
|
* ```typescript
|
|
3507
|
-
* providers: [
|
|
3508
|
-
*
|
|
3509
|
-
*
|
|
3510
|
-
*
|
|
3511
|
-
*
|
|
3512
|
-
*
|
|
3911
|
+
* providers: [
|
|
3912
|
+
* provideRecyclerI18n(
|
|
3913
|
+
* withRecyclerI18nLabels({
|
|
3914
|
+
* empty: () => 'Keine Ergebnisse.',
|
|
3915
|
+
* error: () => 'Fehler beim Laden.',
|
|
3916
|
+
* }),
|
|
3917
|
+
* ),
|
|
3918
|
+
* ]
|
|
3513
3919
|
* ```
|
|
3514
3920
|
*
|
|
3515
3921
|
* @category common/data/recycler
|
|
3516
3922
|
*/
|
|
3517
|
-
function provideRecyclerI18n(
|
|
3518
|
-
return {
|
|
3923
|
+
function provideRecyclerI18n(...features) {
|
|
3924
|
+
return {
|
|
3925
|
+
provide: CNGX_RECYCLER_I18N,
|
|
3926
|
+
useFactory: () => recyclerBundle.build(features),
|
|
3927
|
+
};
|
|
3519
3928
|
}
|
|
3520
3929
|
/**
|
|
3521
3930
|
* Creates a Signal-based virtualizer for DOM recycling.
|
|
@@ -3548,7 +3957,7 @@ function provideRecyclerI18n(i18n) {
|
|
|
3548
3957
|
*/
|
|
3549
3958
|
function injectRecycler(config) {
|
|
3550
3959
|
const destroyRef = inject(DestroyRef);
|
|
3551
|
-
const i18n = inject(CNGX_RECYCLER_I18N);
|
|
3960
|
+
const i18n = recyclerBundle.resolve(inject(CNGX_RECYCLER_I18N));
|
|
3552
3961
|
const overscan = config.overscan ?? 5;
|
|
3553
3962
|
const isGrid = (config.layout ?? 'list') === 'grid';
|
|
3554
3963
|
if (isGrid && config.columns == null && isDevMode()) {
|
|
@@ -3565,9 +3974,7 @@ function injectRecycler(config) {
|
|
|
3565
3974
|
// per-index measurement - it carries no O(n) per-frame cost, so exclude it
|
|
3566
3975
|
// from the variable-height warning (a reactive scalar estimate is a
|
|
3567
3976
|
// sanctioned pattern; see the resolveSize note below).
|
|
3568
|
-
if (typeof config.estimateSize === 'function' &&
|
|
3569
|
-
!isSignal(config.estimateSize) &&
|
|
3570
|
-
isDevMode()) {
|
|
3977
|
+
if (typeof config.estimateSize === 'function' && !isSignal(config.estimateSize) && isDevMode()) {
|
|
3571
3978
|
const count = config.totalCount();
|
|
3572
3979
|
if (count > 10_000) {
|
|
3573
3980
|
console.warn(`[CngxRecycler] estimateSize as a function with ${count} items has O(n) ` +
|
|
@@ -3583,12 +3990,40 @@ function injectRecycler(config) {
|
|
|
3583
3990
|
sizeCache.version(); // track dependency
|
|
3584
3991
|
return sizeCache.resolve(index, config.estimateSize);
|
|
3585
3992
|
};
|
|
3993
|
+
// Signed scroll delta between consecutive scrollTop updates. A fast flick
|
|
3994
|
+
// produces large per-event deltas, so this doubles as a velocity proxy
|
|
3995
|
+
// regardless of whether scrollTop is sampled per-frame or per-event.
|
|
3996
|
+
const scrollVelocity = signal(0, ...(ngDevMode ? [{ debugName: "scrollVelocity" }] : /* istanbul ignore next */ []));
|
|
3997
|
+
let lastScrollTop = 0;
|
|
3998
|
+
effect(() => {
|
|
3999
|
+
const st = scrollState.scrollTop();
|
|
4000
|
+
untracked(() => {
|
|
4001
|
+
scrollVelocity.set(st - lastScrollTop);
|
|
4002
|
+
lastScrollTop = st;
|
|
4003
|
+
});
|
|
4004
|
+
});
|
|
3586
4005
|
// Grid mode uses raw estimateSize (uniform row height, no SizeCache).
|
|
3587
4006
|
// List mode uses resolveSize (SizeCache-backed).
|
|
3588
4007
|
const range = computed(() => {
|
|
3589
4008
|
const cols = columns();
|
|
3590
4009
|
const size = isGrid ? config.estimateSize : resolveSize;
|
|
3591
|
-
|
|
4010
|
+
const scrollTop = scrollState.scrollTop();
|
|
4011
|
+
const clientHeight = scrollState.clientHeight();
|
|
4012
|
+
const total = config.totalCount();
|
|
4013
|
+
// Directional overscan: the rendered range trails scroll by up to a frame,
|
|
4014
|
+
// so pre-render extra items into the scroll direction to keep the leading
|
|
4015
|
+
// edge populated (otherwise a fast scroll flashes a blank strip). Scale the
|
|
4016
|
+
// lead with velocity, capped at one viewport of items so a teleport jump
|
|
4017
|
+
// never expands the window unbounded. Trailing edge keeps the base overscan.
|
|
4018
|
+
const estimate = config.estimateSize;
|
|
4019
|
+
const refPx = typeof estimate === 'number' && estimate > 0 ? estimate : Math.max(1, clientHeight / 8);
|
|
4020
|
+
const itemsPerViewport = Math.max(1, Math.ceil(clientHeight / refPx));
|
|
4021
|
+
const velocity = scrollVelocity();
|
|
4022
|
+
const leadItems = Math.min(Math.ceil(Math.abs(velocity) / refPx), itemsPerViewport);
|
|
4023
|
+
const scrollingDown = velocity >= 0;
|
|
4024
|
+
const overscanBefore = overscan + (scrollingDown ? 0 : leadItems);
|
|
4025
|
+
const overscanAfter = overscan + (scrollingDown ? leadItems : 0);
|
|
4026
|
+
return computeRange(scrollTop, clientHeight, total, size, overscanBefore, cols, overscanAfter);
|
|
3592
4027
|
}, ...(ngDevMode ? [{ debugName: "range" }] : /* istanbul ignore next */ []));
|
|
3593
4028
|
const start = computed(() => range().start, ...(ngDevMode ? [{ debugName: "start" }] : /* istanbul ignore next */ []));
|
|
3594
4029
|
const end = computed(() => range().end, ...(ngDevMode ? [{ debugName: "end" }] : /* istanbul ignore next */ []));
|
|
@@ -3596,6 +4031,23 @@ function injectRecycler(config) {
|
|
|
3596
4031
|
const offsetBefore = computed(() => (isGrid ? 0 : range().offsetBefore), ...(ngDevMode ? [{ debugName: "offsetBefore" }] : /* istanbul ignore next */ []));
|
|
3597
4032
|
const offsetAfter = computed(() => (isGrid ? 0 : range().offsetAfter), ...(ngDevMode ? [{ debugName: "offsetAfter" }] : /* istanbul ignore next */ []));
|
|
3598
4033
|
const totalSize = computed(() => range().totalSize, ...(ngDevMode ? [{ debugName: "totalSize" }] : /* istanbul ignore next */ []));
|
|
4034
|
+
// Representative row height for a placeholder layer's repeat interval. Derived,
|
|
4035
|
+
// never stored: a uniform estimate (number or signal) is the rhythm directly;
|
|
4036
|
+
// a per-index estimate has no single height, so the running average stands in.
|
|
4037
|
+
const rowSizeHint = computed(() => {
|
|
4038
|
+
const estimate = config.estimateSize;
|
|
4039
|
+
if (typeof estimate === 'number') {
|
|
4040
|
+
return estimate;
|
|
4041
|
+
}
|
|
4042
|
+
if (isSignal(estimate)) {
|
|
4043
|
+
return estimate();
|
|
4044
|
+
}
|
|
4045
|
+
const total = config.totalCount();
|
|
4046
|
+
if (total <= 0) {
|
|
4047
|
+
return 0;
|
|
4048
|
+
}
|
|
4049
|
+
return totalSize() / total;
|
|
4050
|
+
}, ...(ngDevMode ? [{ debugName: "rowSizeHint" }] : /* istanbul ignore next */ []));
|
|
3599
4051
|
const placeholdersBefore = computed(() => (isGrid ? start() : 0), ...(ngDevMode ? [{ debugName: "placeholdersBefore" }] : /* istanbul ignore next */ []));
|
|
3600
4052
|
const placeholdersAfter = computed(() => (isGrid ? Math.max(0, config.totalCount() - end()) : 0), ...(ngDevMode ? [{ debugName: "placeholdersAfter" }] : /* istanbul ignore next */ []));
|
|
3601
4053
|
// start/end include overscan. firstVisible/lastVisible strip it back
|
|
@@ -3620,7 +4072,7 @@ function injectRecycler(config) {
|
|
|
3620
4072
|
if (total === 0) {
|
|
3621
4073
|
return 0;
|
|
3622
4074
|
}
|
|
3623
|
-
return
|
|
4075
|
+
return clamp(end() - effectiveOverscan() - 1, 0, total - 1);
|
|
3624
4076
|
}, ...(ngDevMode ? [{ debugName: "lastVisible" }] : /* istanbul ignore next */ []));
|
|
3625
4077
|
const visibleCount = computed(() => {
|
|
3626
4078
|
const total = config.totalCount();
|
|
@@ -3664,21 +4116,24 @@ function injectRecycler(config) {
|
|
|
3664
4116
|
if (previous === current) {
|
|
3665
4117
|
return;
|
|
3666
4118
|
}
|
|
3667
|
-
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
4119
|
+
// Copy is read untracked: a language switch must not re-run the
|
|
4120
|
+
// effect and re-voice the region; the next transition speaks it.
|
|
4121
|
+
untracked(() => {
|
|
4122
|
+
const copy = i18n();
|
|
4123
|
+
// Route by result first: a load that settles with zero items is the
|
|
4124
|
+
// empty phrase, no matter which busy status preceded it - "0 results
|
|
4125
|
+
// found" is the filtered phrase, not the empty one.
|
|
4126
|
+
if (current === 'success' && total === 0) {
|
|
4127
|
+
announcementState.set(copy.empty());
|
|
3671
4128
|
}
|
|
3672
|
-
else {
|
|
3673
|
-
|
|
4129
|
+
else if (current === 'success' && (previous === 'loading' || previous === 'refreshing')) {
|
|
4130
|
+
const diff = total - prevTotal;
|
|
4131
|
+
announcementState.set(diff > 0 ? copy.loaded(diff, total) : copy.filtered(total));
|
|
3674
4132
|
}
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
}
|
|
3679
|
-
else if (current === 'success' && total === 0) {
|
|
3680
|
-
announcementState.set(i18n.empty());
|
|
3681
|
-
}
|
|
4133
|
+
else if (current === 'error') {
|
|
4134
|
+
announcementState.set(copy.error());
|
|
4135
|
+
}
|
|
4136
|
+
});
|
|
3682
4137
|
untracked(() => previousTotal.set(total));
|
|
3683
4138
|
});
|
|
3684
4139
|
}
|
|
@@ -3689,12 +4144,15 @@ function injectRecycler(config) {
|
|
|
3689
4144
|
// untracked: previousTotal is bookkeeping, not a dependency
|
|
3690
4145
|
const prevTotal = untracked(() => previousTotal());
|
|
3691
4146
|
const diff = total - prevTotal;
|
|
3692
|
-
|
|
3693
|
-
|
|
3694
|
-
|
|
3695
|
-
|
|
3696
|
-
|
|
3697
|
-
|
|
4147
|
+
untracked(() => {
|
|
4148
|
+
const copy = i18n();
|
|
4149
|
+
if (prevTotal > 0 && diff > 0) {
|
|
4150
|
+
announcementState.set(copy.loaded(diff, total));
|
|
4151
|
+
}
|
|
4152
|
+
else if (prevTotal > 0 && total === 0) {
|
|
4153
|
+
announcementState.set(copy.empty());
|
|
4154
|
+
}
|
|
4155
|
+
});
|
|
3698
4156
|
untracked(() => previousTotal.set(total));
|
|
3699
4157
|
});
|
|
3700
4158
|
}
|
|
@@ -3796,6 +4254,7 @@ function injectRecycler(config) {
|
|
|
3796
4254
|
offsetBefore,
|
|
3797
4255
|
offsetAfter,
|
|
3798
4256
|
totalSize,
|
|
4257
|
+
rowSizeHint,
|
|
3799
4258
|
placeholdersBefore,
|
|
3800
4259
|
placeholdersAfter,
|
|
3801
4260
|
isLoading,
|
|
@@ -3893,19 +4352,19 @@ class CngxMeasure {
|
|
|
3893
4352
|
/** The absolute index of this item in the full dataset. */
|
|
3894
4353
|
cngxMeasureIndex = input.required(...(ngDevMode ? [{ debugName: "cngxMeasureIndex" }] : /* istanbul ignore next */ []));
|
|
3895
4354
|
el = inject((ElementRef));
|
|
4355
|
+
win = inject(DOCUMENT).defaultView;
|
|
3896
4356
|
constructor() {
|
|
3897
4357
|
effect((onCleanup) => {
|
|
3898
4358
|
const recycler = this.cngxMeasure();
|
|
3899
4359
|
const index = this.cngxMeasureIndex();
|
|
3900
4360
|
const element = this.el.nativeElement;
|
|
3901
4361
|
recycler.measure(index, element);
|
|
3902
|
-
|
|
4362
|
+
// The observed element follows the inputs, so the subscription is
|
|
4363
|
+
// re-wired per effect run - the low-level kernel form, not the
|
|
4364
|
+
// DestroyRef-scoped one.
|
|
4365
|
+
onCleanup(observeResize(this.win, element, 'content-box', () => {
|
|
3903
4366
|
recycler.measure(index, element);
|
|
3904
|
-
});
|
|
3905
|
-
observer.observe(element);
|
|
3906
|
-
onCleanup(() => {
|
|
3907
|
-
observer.disconnect();
|
|
3908
|
-
});
|
|
4367
|
+
}));
|
|
3909
4368
|
});
|
|
3910
4369
|
}
|
|
3911
4370
|
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxMeasure, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
@@ -3980,6 +4439,380 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
|
|
|
3980
4439
|
}]
|
|
3981
4440
|
}], propDecorators: { cngxVirtualItem: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxVirtualItem", required: true }] }], cngxVirtualItemIndex: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxVirtualItemIndex", required: true }] }] } });
|
|
3982
4441
|
|
|
4442
|
+
/**
|
|
4443
|
+
* Paints a row-aligned skeleton background under a virtualized scroll region so
|
|
4444
|
+
* a fast fling or teleport jump reveals placeholder bars instead of the bare
|
|
4445
|
+
* panel/page surface for the single frame the rendered rows lag `scrollTop`.
|
|
4446
|
+
*
|
|
4447
|
+
* The mechanism is a static CSS layer, not a reactive template: by the time a
|
|
4448
|
+
* `@for` over "uncovered indices" could render, change detection has already
|
|
4449
|
+
* produced the real rows, so the lag frame is never painted reactively. A
|
|
4450
|
+
* `background` on the offset element always paints and also covers teleport
|
|
4451
|
+
* jumps no reactive window can, at zero per-frame cost.
|
|
4452
|
+
*
|
|
4453
|
+
* Host it on the **offset spacer element(s)** - the empty divs (or presentation
|
|
4454
|
+
* `<li>`s) whose height reserves `offsetBefore` / `offsetAfter` - one directive
|
|
4455
|
+
* instance per spacer. Do NOT host it on a `padding-block`ed content element
|
|
4456
|
+
* that also contains the rows: a background paints across the whole padding box,
|
|
4457
|
+
* so it would show through *behind* every rendered row, not just in the gap.
|
|
4458
|
+
* The spacers carry no rows, so the layer is only ever visible where the window
|
|
4459
|
+
* has not caught up.
|
|
4460
|
+
*
|
|
4461
|
+
* The repeat interval keys off a single representative row height: bind the
|
|
4462
|
+
* recycler to read its `rowSizeHint`, or pass an explicit `[rowHeight]`
|
|
4463
|
+
* fallback so the directive is usable standalone. Visuals are driven by
|
|
4464
|
+
* `--cngx-recycler-placeholder-*` CSS custom properties (see
|
|
4465
|
+
* `@cngx/common/theming/components/cngx-recycler-placeholder.css`); the shimmer
|
|
4466
|
+
* drops under `prefers-reduced-motion` via a spec-observable host class.
|
|
4467
|
+
*
|
|
4468
|
+
* ### One instance per offset spacer, keyed off the recycler's rhythm
|
|
4469
|
+
* ```html
|
|
4470
|
+
* <ul>
|
|
4471
|
+
* @if (recycler.offsetBefore(); as before) {
|
|
4472
|
+
* <li role="presentation" aria-hidden="true"
|
|
4473
|
+
* [cngxRecyclerPlaceholder]="recycler" [style.height.px]="before"></li>
|
|
4474
|
+
* }
|
|
4475
|
+
* @for (item of visibleItems(); track item.id) { <li>...</li> }
|
|
4476
|
+
* @if (recycler.offsetAfter(); as after) {
|
|
4477
|
+
* <li role="presentation" aria-hidden="true"
|
|
4478
|
+
* [cngxRecyclerPlaceholder]="recycler" [style.height.px]="after"></li>
|
|
4479
|
+
* }
|
|
4480
|
+
* </ul>
|
|
4481
|
+
* ```
|
|
4482
|
+
*
|
|
4483
|
+
* ### Standalone with an explicit row height
|
|
4484
|
+
* ```html
|
|
4485
|
+
* <div cngxRecyclerPlaceholder [rowHeight]="48"
|
|
4486
|
+
* [style.height.px]="recycler.offsetBefore()"></div>
|
|
4487
|
+
* ```
|
|
4488
|
+
*
|
|
4489
|
+
* @category common/data/recycler
|
|
4490
|
+
* @docsKind primary
|
|
4491
|
+
* @wcag AA
|
|
4492
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/data/recycler/recycler-placeholder.directive.ts
|
|
4493
|
+
* @since 0.1.0
|
|
4494
|
+
* @relatedTo injectRecycler, CngxRecyclerRow, CngxVirtualItem, CngxMeasure
|
|
4495
|
+
* <example-url>http://localhost:4200/#/common/data/recycler/fast-fling-placeholders</example-url>
|
|
4496
|
+
*/
|
|
4497
|
+
class CngxRecyclerPlaceholder {
|
|
4498
|
+
/**
|
|
4499
|
+
* The recycler whose `rowSizeHint` sets the placeholder repeat rhythm.
|
|
4500
|
+
* Optional: the directive also works from an explicit `[rowHeight]`, so this
|
|
4501
|
+
* follows the bridge-input shape (optional + empty-string transform) rather
|
|
4502
|
+
* than `input.required` - a bare `cngxRecyclerPlaceholder` attribute paired
|
|
4503
|
+
* with `[rowHeight]` is a valid, unbound usage.
|
|
4504
|
+
*/
|
|
4505
|
+
recycler = input(undefined, { ...(ngDevMode ? { debugName: "recycler" } : /* istanbul ignore next */ {}), alias: 'cngxRecyclerPlaceholder',
|
|
4506
|
+
transform: (value) => (typeof value === 'string' ? undefined : value) });
|
|
4507
|
+
/** Explicit row height (px) used when no recycler is bound, or as a fallback. */
|
|
4508
|
+
rowHeight = input(undefined, ...(ngDevMode ? [{ debugName: "rowHeight" }] : /* istanbul ignore next */ []));
|
|
4509
|
+
prefersReducedMotion;
|
|
4510
|
+
constructor() {
|
|
4511
|
+
this.prefersReducedMotion = createMediaQuerySignal('(prefers-reduced-motion: reduce)', inject(DestroyRef), inject(DOCUMENT).defaultView);
|
|
4512
|
+
}
|
|
4513
|
+
/**
|
|
4514
|
+
* Representative row height (px) for the repeat interval. The recycler's
|
|
4515
|
+
* `rowSizeHint` wins when it resolves to a positive value; otherwise the
|
|
4516
|
+
* explicit `[rowHeight]` fallback applies.
|
|
4517
|
+
*/
|
|
4518
|
+
resolvedRowHeight = computed(() => {
|
|
4519
|
+
const fromRecycler = this.recycler()?.rowSizeHint() ?? 0;
|
|
4520
|
+
if (fromRecycler > 0) {
|
|
4521
|
+
return fromRecycler;
|
|
4522
|
+
}
|
|
4523
|
+
return this.rowHeight() ?? 0;
|
|
4524
|
+
}, ...(ngDevMode ? [{ debugName: "resolvedRowHeight" }] : /* istanbul ignore next */ []));
|
|
4525
|
+
/**
|
|
4526
|
+
* The `--cngx-recycler-placeholder-row-height` style value. `null` when no
|
|
4527
|
+
* row height resolves, so the registered `@property` default (or an inherited
|
|
4528
|
+
* token from an ancestor mapping) applies instead of a broken `0px` interval.
|
|
4529
|
+
*/
|
|
4530
|
+
rowHeightVar = computed(() => {
|
|
4531
|
+
const height = this.resolvedRowHeight();
|
|
4532
|
+
return height > 0 ? `${height}px` : null;
|
|
4533
|
+
}, ...(ngDevMode ? [{ debugName: "rowHeightVar" }] : /* istanbul ignore next */ []));
|
|
4534
|
+
/** Whether the shimmer host class is applied (dropped under reduced-motion). */
|
|
4535
|
+
showShimmer = computed(() => !this.prefersReducedMotion(), ...(ngDevMode ? [{ debugName: "showShimmer" }] : /* istanbul ignore next */ []));
|
|
4536
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRecyclerPlaceholder, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
4537
|
+
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 });
|
|
4538
|
+
}
|
|
4539
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRecyclerPlaceholder, decorators: [{
|
|
4540
|
+
type: Directive,
|
|
4541
|
+
args: [{
|
|
4542
|
+
selector: '[cngxRecyclerPlaceholder]',
|
|
4543
|
+
standalone: true,
|
|
4544
|
+
host: {
|
|
4545
|
+
class: 'cngx-recycler-placeholder',
|
|
4546
|
+
// The layer is a decorative background on an offset spacer. Hide it from the
|
|
4547
|
+
// a11y tree at the host so it stays out regardless of the call site, not only
|
|
4548
|
+
// when a consumer remembers to add aria-hidden.
|
|
4549
|
+
'aria-hidden': 'true',
|
|
4550
|
+
'[class.cngx-recycler-placeholder--shimmer]': 'showShimmer()',
|
|
4551
|
+
'[style.--cngx-recycler-placeholder-row-height]': 'rowHeightVar()',
|
|
4552
|
+
},
|
|
4553
|
+
}]
|
|
4554
|
+
}], ctorParameters: () => [], propDecorators: { recycler: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxRecyclerPlaceholder", required: false }] }], rowHeight: [{ type: i0.Input, args: [{ isSignal: true, alias: "rowHeight", required: false }] }] } });
|
|
4555
|
+
|
|
4556
|
+
/**
|
|
4557
|
+
* App-wide default placeholder template for `*cngxRecyclerRow`. Middle rung of
|
|
4558
|
+
* the cascade: microsyntax `placeholder:` template wins over this, and this wins
|
|
4559
|
+
* over the built-in imperative `<li>` default. Defaults to `null` (imperative
|
|
4560
|
+
* default applies).
|
|
4561
|
+
*
|
|
4562
|
+
* @category common/data/recycler
|
|
4563
|
+
*/
|
|
4564
|
+
const CNGX_RECYCLER_PLACEHOLDER_ROW = new InjectionToken('CNGX_RECYCLER_PLACEHOLDER_ROW', { providedIn: 'root', factory: () => null });
|
|
4565
|
+
/**
|
|
4566
|
+
* Provides an app-wide default placeholder template for every `*cngxRecyclerRow`
|
|
4567
|
+
* that supplies no `placeholder:` template of its own.
|
|
4568
|
+
*
|
|
4569
|
+
* @category common/data/recycler
|
|
4570
|
+
*/
|
|
4571
|
+
function provideRecyclerPlaceholderRow(template) {
|
|
4572
|
+
return { provide: CNGX_RECYCLER_PLACEHOLDER_ROW, useValue: template };
|
|
4573
|
+
}
|
|
4574
|
+
/**
|
|
4575
|
+
* Per-window-position render switch for a sparse/windowed recycler: renders the
|
|
4576
|
+
* consumer's real-row template when the sliced item is defined, and a
|
|
4577
|
+
* placeholder branch when the item is still `undefined` (loaded window, data
|
|
4578
|
+
* not yet resolved).
|
|
4579
|
+
*
|
|
4580
|
+
* Mirrors the `*cngxAsync` structural-directive shape (own `TemplateRef` +
|
|
4581
|
+
* microsyntax alternate template + `ngTemplateContextGuard`). The switch axis is
|
|
4582
|
+
* data availability, not async status, so the two are siblings, not the same
|
|
4583
|
+
* class. Unlike `*cngxAsync` (which clears on every switch) the real-row view is
|
|
4584
|
+
* cached and re-attached across a placeholder detour, so a
|
|
4585
|
+
* defined -> undefined -> defined flip never remounts the expensive real row.
|
|
4586
|
+
*
|
|
4587
|
+
* The placeholder branch resolves through a 3-stage cascade: the microsyntax
|
|
4588
|
+
* `placeholder:` template, then {@link CNGX_RECYCLER_PLACEHOLDER_ROW}, then a
|
|
4589
|
+
* built-in imperative `<li>` default. The default assumes a `<ul>`/`<li>` list;
|
|
4590
|
+
* a non-`<li>` container (`<div role="list">`) supplies a `placeholder:`
|
|
4591
|
+
* template or the config token instead.
|
|
4592
|
+
*
|
|
4593
|
+
* The two placeholder layers are orthogonal and non-overlapping by
|
|
4594
|
+
* construction: {@link CngxRecyclerPlaceholder} paints a decorative background
|
|
4595
|
+
* on the offset spacers (indices outside the rendered window), while this
|
|
4596
|
+
* directive fills holes inside the window whose item is still `undefined`.
|
|
4597
|
+
*
|
|
4598
|
+
* ### Windowed list with the built-in placeholder row
|
|
4599
|
+
* ```html
|
|
4600
|
+
* <ul>
|
|
4601
|
+
* @for (item of visibleItems(); track item?.id ?? ('ph:' + (recycler.start() + $index)); let i = $index) {
|
|
4602
|
+
* <li *cngxRecyclerRow="item; index: recycler.start() + i; recycler: recycler; let row">
|
|
4603
|
+
* {{ row?.name }}
|
|
4604
|
+
* </li>
|
|
4605
|
+
* }
|
|
4606
|
+
* </ul>
|
|
4607
|
+
* ```
|
|
4608
|
+
*
|
|
4609
|
+
* ### Custom placeholder template
|
|
4610
|
+
* ```html
|
|
4611
|
+
* <ul>
|
|
4612
|
+
* @for (item of visibleItems(); track item?.id ?? ('ph:' + (recycler.start() + $index)); let i = $index) {
|
|
4613
|
+
* <li *cngxRecyclerRow="item; index: recycler.start() + i; recycler: recycler; placeholder: ph; let row">
|
|
4614
|
+
* {{ row?.name }}
|
|
4615
|
+
* </li>
|
|
4616
|
+
* }
|
|
4617
|
+
* <ng-template #ph let-index let-setSize="setSize">
|
|
4618
|
+
* <li role="listitem" aria-busy="true" [attr.aria-posinset]="index + 1" [attr.aria-setsize]="setSize">
|
|
4619
|
+
* Loading row {{ index + 1 }}
|
|
4620
|
+
* </li>
|
|
4621
|
+
* </ng-template>
|
|
4622
|
+
* </ul>
|
|
4623
|
+
* ```
|
|
4624
|
+
*
|
|
4625
|
+
* @category common/data/recycler
|
|
4626
|
+
* @docsKind primary
|
|
4627
|
+
* @wcag AA
|
|
4628
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/data/recycler/recycler-row.directive.ts
|
|
4629
|
+
* @since 0.1.0
|
|
4630
|
+
* @relatedTo injectRecycler, CngxRecyclerPlaceholder, CngxVirtualItem, CngxMeasure
|
|
4631
|
+
* <example-url>http://localhost:4200/#/common/data/recycler/windowed-data-availability</example-url>
|
|
4632
|
+
*/
|
|
4633
|
+
class CngxRecyclerRow {
|
|
4634
|
+
vcr = inject(ViewContainerRef);
|
|
4635
|
+
rowTpl = inject(TemplateRef);
|
|
4636
|
+
renderer = inject(Renderer2);
|
|
4637
|
+
configTpl = inject(CNGX_RECYCLER_PLACEHOLDER_ROW);
|
|
4638
|
+
/** The sliced item at this window position. `undefined` selects the placeholder branch. */
|
|
4639
|
+
cngxRecyclerRow = input(undefined, ...(ngDevMode ? [{ debugName: "cngxRecyclerRow" }] : /* istanbul ignore next */ []));
|
|
4640
|
+
/** Absolute dataset index of this slot (`recycler.start() + $index`). */
|
|
4641
|
+
cngxRecyclerRowIndex = input.required(...(ngDevMode ? [{ debugName: "cngxRecyclerRowIndex" }] : /* istanbul ignore next */ []));
|
|
4642
|
+
/** The recycler driving the window, read for `rowSizeHint` (-> `top`) and `ariaSetSize`. */
|
|
4643
|
+
cngxRecyclerRowRecycler = input.required(...(ngDevMode ? [{ debugName: "cngxRecyclerRowRecycler" }] : /* istanbul ignore next */ []));
|
|
4644
|
+
/** Optional placeholder template for the `undefined` branch. Context: {@link CngxRecyclerRowContext}. */
|
|
4645
|
+
cngxRecyclerRowPlaceholder = input(undefined, ...(ngDevMode ? [{ debugName: "cngxRecyclerRowPlaceholder" }] : /* istanbul ignore next */ []));
|
|
4646
|
+
// Plain fields, not signals: read and written only inside the render effect.
|
|
4647
|
+
// As signals they would feed the effect's own dependency graph and double-fire
|
|
4648
|
+
// per branch switch (the trap documented in async.directive.ts).
|
|
4649
|
+
currentBranch = 'none';
|
|
4650
|
+
rowViewRef = null;
|
|
4651
|
+
placeholderViewRef = null;
|
|
4652
|
+
defaultEl = null;
|
|
4653
|
+
constructor() {
|
|
4654
|
+
effect(() => {
|
|
4655
|
+
const item = this.cngxRecyclerRow();
|
|
4656
|
+
if (item === undefined) {
|
|
4657
|
+
// Placeholder branch tracks index + ariaSetSize (via buildPlaceholderContext)
|
|
4658
|
+
// so the announced position/size stay live while the slot remains unloaded
|
|
4659
|
+
// across a window shift or an infinite-scroll setSize growth - Pillar 2
|
|
4660
|
+
// keeps a11y in the reactive graph, never a one-time write. The row branch
|
|
4661
|
+
// tracks only the item value; the placeholder template ref is read untracked.
|
|
4662
|
+
this.showPlaceholder(this.buildPlaceholderContext());
|
|
4663
|
+
}
|
|
4664
|
+
else {
|
|
4665
|
+
this.showRow(item);
|
|
4666
|
+
}
|
|
4667
|
+
});
|
|
4668
|
+
inject(DestroyRef).onDestroy(() => {
|
|
4669
|
+
// The cached row view may be detached (not owned by the VCR), so the VCR
|
|
4670
|
+
// will not tear it down; destroy both views explicitly, guarding the
|
|
4671
|
+
// already-destroyed case when the VCR got there first.
|
|
4672
|
+
if (this.rowViewRef && !this.rowViewRef.destroyed) {
|
|
4673
|
+
this.rowViewRef.destroy();
|
|
4674
|
+
}
|
|
4675
|
+
this.teardownPlaceholder();
|
|
4676
|
+
});
|
|
4677
|
+
}
|
|
4678
|
+
showRow(item) {
|
|
4679
|
+
if (this.currentBranch === 'row') {
|
|
4680
|
+
this.setRowContext(item);
|
|
4681
|
+
this.rowViewRef?.markForCheck();
|
|
4682
|
+
return;
|
|
4683
|
+
}
|
|
4684
|
+
this.teardownPlaceholder();
|
|
4685
|
+
if (this.rowViewRef) {
|
|
4686
|
+
this.setRowContext(item);
|
|
4687
|
+
this.vcr.insert(this.rowViewRef);
|
|
4688
|
+
this.rowViewRef.markForCheck();
|
|
4689
|
+
}
|
|
4690
|
+
else {
|
|
4691
|
+
this.rowViewRef = this.vcr.createEmbeddedView(this.rowTpl, {
|
|
4692
|
+
$implicit: item,
|
|
4693
|
+
cngxRecyclerRow: item,
|
|
4694
|
+
});
|
|
4695
|
+
}
|
|
4696
|
+
this.currentBranch = 'row';
|
|
4697
|
+
}
|
|
4698
|
+
showPlaceholder(ctx) {
|
|
4699
|
+
if (this.currentBranch === 'placeholder') {
|
|
4700
|
+
this.refreshPlaceholder(ctx);
|
|
4701
|
+
return;
|
|
4702
|
+
}
|
|
4703
|
+
this.detachRow();
|
|
4704
|
+
this.renderPlaceholder(ctx);
|
|
4705
|
+
this.currentBranch = 'placeholder';
|
|
4706
|
+
}
|
|
4707
|
+
setRowContext(item) {
|
|
4708
|
+
if (this.rowViewRef) {
|
|
4709
|
+
this.rowViewRef.context.$implicit = item;
|
|
4710
|
+
this.rowViewRef.context.cngxRecyclerRow = item;
|
|
4711
|
+
}
|
|
4712
|
+
}
|
|
4713
|
+
// Remove the cached row view from the container WITHOUT destroying it, so the
|
|
4714
|
+
// next 'row' branch re-attaches the same EmbeddedViewRef (no remount).
|
|
4715
|
+
detachRow() {
|
|
4716
|
+
if (!this.rowViewRef) {
|
|
4717
|
+
return;
|
|
4718
|
+
}
|
|
4719
|
+
const at = this.vcr.indexOf(this.rowViewRef);
|
|
4720
|
+
if (at !== -1) {
|
|
4721
|
+
this.vcr.detach(at);
|
|
4722
|
+
}
|
|
4723
|
+
}
|
|
4724
|
+
teardownPlaceholder() {
|
|
4725
|
+
if (this.placeholderViewRef) {
|
|
4726
|
+
this.placeholderViewRef.destroy();
|
|
4727
|
+
this.placeholderViewRef = null;
|
|
4728
|
+
}
|
|
4729
|
+
this.removeDefault();
|
|
4730
|
+
}
|
|
4731
|
+
renderPlaceholder(ctx) {
|
|
4732
|
+
const tpl = untracked(() => this.cngxRecyclerRowPlaceholder()) ?? this.configTpl ?? null;
|
|
4733
|
+
if (tpl) {
|
|
4734
|
+
this.placeholderViewRef = this.vcr.createEmbeddedView(tpl, ctx);
|
|
4735
|
+
}
|
|
4736
|
+
else {
|
|
4737
|
+
this.stampDefault(ctx);
|
|
4738
|
+
}
|
|
4739
|
+
}
|
|
4740
|
+
// Slot stayed unloaded but its index/setSize moved: refresh the live a11y
|
|
4741
|
+
// position/size in place - custom template context or default element attrs -
|
|
4742
|
+
// without remounting the placeholder.
|
|
4743
|
+
refreshPlaceholder(ctx) {
|
|
4744
|
+
if (this.placeholderViewRef) {
|
|
4745
|
+
const context = this.placeholderViewRef.context;
|
|
4746
|
+
context.$implicit = ctx.$implicit;
|
|
4747
|
+
context.index = ctx.index;
|
|
4748
|
+
context.top = ctx.top;
|
|
4749
|
+
context.setSize = ctx.setSize;
|
|
4750
|
+
this.placeholderViewRef.markForCheck();
|
|
4751
|
+
}
|
|
4752
|
+
else if (this.defaultEl) {
|
|
4753
|
+
this.applyDefaultAttrs(this.defaultEl, ctx);
|
|
4754
|
+
}
|
|
4755
|
+
}
|
|
4756
|
+
// Terminal fallback: a module-level TemplateRef cannot exist, so the built-in
|
|
4757
|
+
// default is one imperative <li> reusing the shipped `cngx-recycler-placeholder`
|
|
4758
|
+
// ghost-row CSS. It holds a real dataset position, so it stays in the a11y tree
|
|
4759
|
+
// (aria-busy / role=listitem / posinset / setsize) - never aria-hidden.
|
|
4760
|
+
stampDefault(ctx) {
|
|
4761
|
+
const anchor = this.vcr.element.nativeElement;
|
|
4762
|
+
const parent = this.renderer.parentNode(anchor);
|
|
4763
|
+
if (!parent) {
|
|
4764
|
+
return;
|
|
4765
|
+
}
|
|
4766
|
+
const li = this.renderer.createElement('li');
|
|
4767
|
+
this.renderer.addClass(li, 'cngx-recycler-placeholder');
|
|
4768
|
+
this.renderer.setAttribute(li, 'role', 'listitem');
|
|
4769
|
+
this.renderer.setAttribute(li, 'aria-busy', 'true');
|
|
4770
|
+
this.applyDefaultAttrs(li, ctx);
|
|
4771
|
+
this.renderer.insertBefore(parent, li, anchor);
|
|
4772
|
+
this.defaultEl = li;
|
|
4773
|
+
}
|
|
4774
|
+
applyDefaultAttrs(li, ctx) {
|
|
4775
|
+
const height = untracked(() => this.cngxRecyclerRowRecycler().rowSizeHint());
|
|
4776
|
+
this.renderer.setAttribute(li, 'aria-posinset', String(ctx.index + 1));
|
|
4777
|
+
this.renderer.setAttribute(li, 'aria-setsize', String(ctx.setSize));
|
|
4778
|
+
this.renderer.setStyle(li, 'height', `${height}px`);
|
|
4779
|
+
this.renderer.setStyle(li, '--cngx-recycler-placeholder-row-height', `${height}px`);
|
|
4780
|
+
}
|
|
4781
|
+
removeDefault() {
|
|
4782
|
+
if (!this.defaultEl) {
|
|
4783
|
+
return;
|
|
4784
|
+
}
|
|
4785
|
+
const parent = this.renderer.parentNode(this.defaultEl);
|
|
4786
|
+
if (parent) {
|
|
4787
|
+
this.renderer.removeChild(parent, this.defaultEl);
|
|
4788
|
+
}
|
|
4789
|
+
this.defaultEl = null;
|
|
4790
|
+
}
|
|
4791
|
+
// Called only from the placeholder branch of the render effect: reading index
|
|
4792
|
+
// + ariaSetSize here (tracked) is what keeps the announced position/size
|
|
4793
|
+
// reactive. rowSizeHint is a stable layout hint, read untracked for `top`.
|
|
4794
|
+
buildPlaceholderContext() {
|
|
4795
|
+
const index = this.cngxRecyclerRowIndex();
|
|
4796
|
+
const recycler = this.cngxRecyclerRowRecycler();
|
|
4797
|
+
const setSize = recycler.ariaSetSize();
|
|
4798
|
+
const top = untracked(() => recycler.rowSizeHint()) * index;
|
|
4799
|
+
return { $implicit: index, index, top, setSize };
|
|
4800
|
+
}
|
|
4801
|
+
/** Narrows the directive's own template context to the loaded item type. */
|
|
4802
|
+
static ngTemplateContextGuard(_dir, _ctx) {
|
|
4803
|
+
return true;
|
|
4804
|
+
}
|
|
4805
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRecyclerRow, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
4806
|
+
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 });
|
|
4807
|
+
}
|
|
4808
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRecyclerRow, decorators: [{
|
|
4809
|
+
type: Directive,
|
|
4810
|
+
args: [{
|
|
4811
|
+
selector: '[cngxRecyclerRow]',
|
|
4812
|
+
standalone: true,
|
|
4813
|
+
}]
|
|
4814
|
+
}], 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 }] }] } });
|
|
4815
|
+
|
|
3983
4816
|
/**
|
|
3984
4817
|
* Convenience component that renders the `aria-live="polite"` region
|
|
3985
4818
|
* for recycler SR announcements. Eliminates manual boilerplate.
|
|
@@ -4211,17 +5044,24 @@ function createCommitController() {
|
|
|
4211
5044
|
isCommitting: computed(() => slot.isPending()),
|
|
4212
5045
|
intendedValue: intendedState.asReadonly(),
|
|
4213
5046
|
begin(runner, intended, previous, handlers) {
|
|
4214
|
-
//
|
|
4215
|
-
//
|
|
4216
|
-
|
|
5047
|
+
// bump commitId BEFORE tearing down the previous runner: a runner that
|
|
5048
|
+
// cancels synchronously would otherwise still pass the supersede check
|
|
5049
|
+
// and fire its callbacks after all
|
|
4217
5050
|
const id = ++commitId;
|
|
5051
|
+
active?.cancel();
|
|
4218
5052
|
intendedState.set(intended);
|
|
4219
5053
|
slot.set('pending');
|
|
4220
|
-
|
|
5054
|
+
// A runner may settle synchronously, i.e. before its handle is even
|
|
5055
|
+
// returned. The settled flag keeps such a finished handle out of
|
|
5056
|
+
// `active`, so a later begin()/cancel() never calls cancel() on a
|
|
5057
|
+
// completed runner (CngxCommitHandle does not require idempotence).
|
|
5058
|
+
let settled = false;
|
|
5059
|
+
const handle = runner({
|
|
4221
5060
|
onSuccess: (committed) => {
|
|
4222
5061
|
if (id !== commitId) {
|
|
4223
5062
|
return;
|
|
4224
5063
|
}
|
|
5064
|
+
settled = true;
|
|
4225
5065
|
slot.setSuccess(committed);
|
|
4226
5066
|
active = null;
|
|
4227
5067
|
handlers.onSuccess(committed);
|
|
@@ -4230,17 +5070,26 @@ function createCommitController() {
|
|
|
4230
5070
|
if (id !== commitId) {
|
|
4231
5071
|
return;
|
|
4232
5072
|
}
|
|
5073
|
+
settled = true;
|
|
4233
5074
|
slot.setError(err);
|
|
4234
5075
|
active = null;
|
|
4235
5076
|
handlers.onError(err, previous);
|
|
4236
5077
|
},
|
|
4237
5078
|
});
|
|
5079
|
+
active = settled ? null : handle;
|
|
4238
5080
|
},
|
|
4239
|
-
cancel() {
|
|
5081
|
+
cancel(options) {
|
|
5082
|
+
// bump first: callbacks of a synchronously-cancelling runner must
|
|
5083
|
+
// already see themselves superseded
|
|
5084
|
+
commitId++;
|
|
4240
5085
|
active?.cancel();
|
|
4241
5086
|
active = null;
|
|
4242
|
-
|
|
4243
|
-
|
|
5087
|
+
if (options?.settle) {
|
|
5088
|
+
// Full settle: idle status plus cleared data/error, so a stale
|
|
5089
|
+
// rejection cannot resurface on the next commit window.
|
|
5090
|
+
slot.reset();
|
|
5091
|
+
intendedState.set(undefined);
|
|
5092
|
+
}
|
|
4244
5093
|
},
|
|
4245
5094
|
};
|
|
4246
5095
|
}
|
|
@@ -4396,5 +5245,5 @@ function createMaterialBidirectionalSync(opts) {
|
|
|
4396
5245
|
* Generated bundle index. Do not edit.
|
|
4397
5246
|
*/
|
|
4398
5247
|
|
|
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 };
|
|
5248
|
+
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, createSortHeaderState, fromHttpResource, fromResource, injectAsyncRegistry, injectAsyncState, injectDataSource, injectKpiI18n, injectLatencyProbe, injectRecycler, injectSmartDataSource, provideAsyncHttpObservability, provideAsyncRegistry, provideKpiI18n, provideRecyclerI18n, provideRecyclerPlaceholderRow, resolveAsyncView, tapAsyncProgress, tapAsyncState, tapHttpAsyncState, withAsyncLabel, withAsyncSkip, withKpiI18nLabels, withRecyclerI18nLabels };
|
|
4400
5249
|
//# sourceMappingURL=cngx-common-data.mjs.map
|