@cngx/common 0.0.1-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -0
  3. package/a11y/README.md +77 -0
  4. package/card/README.md +79 -0
  5. package/chart/README.md +31 -0
  6. package/data/README.md +883 -0
  7. package/dialog/README.md +84 -0
  8. package/display/README.md +30 -0
  9. package/fesm2022/cngx-common-a11y.mjs +1260 -0
  10. package/fesm2022/cngx-common-a11y.mjs.map +1 -0
  11. package/fesm2022/cngx-common-card.mjs +765 -0
  12. package/fesm2022/cngx-common-card.mjs.map +1 -0
  13. package/fesm2022/cngx-common-chart.mjs +2943 -0
  14. package/fesm2022/cngx-common-chart.mjs.map +1 -0
  15. package/fesm2022/cngx-common-data.mjs +2886 -0
  16. package/fesm2022/cngx-common-data.mjs.map +1 -0
  17. package/fesm2022/cngx-common-dialog.mjs +1366 -0
  18. package/fesm2022/cngx-common-dialog.mjs.map +1 -0
  19. package/fesm2022/cngx-common-display.mjs +1603 -0
  20. package/fesm2022/cngx-common-display.mjs.map +1 -0
  21. package/fesm2022/cngx-common-interactive.mjs +8185 -0
  22. package/fesm2022/cngx-common-interactive.mjs.map +1 -0
  23. package/fesm2022/cngx-common-layout.mjs +1335 -0
  24. package/fesm2022/cngx-common-layout.mjs.map +1 -0
  25. package/fesm2022/cngx-common-popover.mjs +1200 -0
  26. package/fesm2022/cngx-common-popover.mjs.map +1 -0
  27. package/fesm2022/cngx-common-stepper.mjs +1350 -0
  28. package/fesm2022/cngx-common-stepper.mjs.map +1 -0
  29. package/fesm2022/cngx-common-tabs.mjs +1551 -0
  30. package/fesm2022/cngx-common-tabs.mjs.map +1 -0
  31. package/fesm2022/cngx-common.mjs +34 -0
  32. package/fesm2022/cngx-common.mjs.map +1 -0
  33. package/interactive/README.md +211 -0
  34. package/layout/README.md +117 -0
  35. package/package.json +100 -0
  36. package/popover/README.md +218 -0
  37. package/stepper/README.md +102 -0
  38. package/tabs/README.md +32 -0
  39. package/types/cngx-common-a11y.d.ts +616 -0
  40. package/types/cngx-common-card.d.ts +413 -0
  41. package/types/cngx-common-chart.d.ts +1081 -0
  42. package/types/cngx-common-data.d.ts +1460 -0
  43. package/types/cngx-common-dialog.d.ts +772 -0
  44. package/types/cngx-common-display.d.ts +1136 -0
  45. package/types/cngx-common-interactive.d.ts +5013 -0
  46. package/types/cngx-common-layout.d.ts +737 -0
  47. package/types/cngx-common-popover.d.ts +520 -0
  48. package/types/cngx-common-stepper.d.ts +982 -0
  49. package/types/cngx-common-tabs.d.ts +1237 -0
  50. package/types/cngx-common.d.ts +13 -0
@@ -0,0 +1,1260 @@
1
+ import * as i0 from '@angular/core';
2
+ import { input, Directive, inject, ElementRef, Injector, DestroyRef, afterNextRender, effect, signal, computed, model, contentChildren, InjectionToken, output } from '@angular/core';
3
+ import { DOCUMENT } from '@angular/common';
4
+ import { FocusTrapFactory } from '@angular/cdk/a11y';
5
+
6
+ /**
7
+ * Manages `aria-expanded` and optionally `aria-controls` on the host element.
8
+ *
9
+ * Pairs a disclosure trigger (button) with its controlled region via standard
10
+ * WAI-ARIA attributes. Supports accordions, dropdowns, tree items, and any
11
+ * disclosure pattern where a control toggles visibility of another element.
12
+ *
13
+ * Unlike manual `[attr.aria-expanded]` binding, this directive couples both
14
+ * attributes (`aria-expanded` + `aria-controls`) in a single declaration,
15
+ * preventing mismatches where one is set without the other.
16
+ *
17
+ * ### Simple disclosure
18
+ * ```html
19
+ * <button [cngxAriaExpanded]="open()" [controls]="'panel-id'" (click)="open.set(!open())">
20
+ * Toggle
21
+ * </button>
22
+ * <div id="panel-id" role="region" [hidden]="!open()">Panel content</div>
23
+ * ```
24
+ *
25
+ * ### Accordion with multiple panels
26
+ * ```html
27
+ * @for (panel of panels(); track panel.id) {
28
+ * <button [cngxAriaExpanded]="panel.open" [controls]="panel.id" (click)="toggle(panel)">
29
+ * {{ panel.label }}
30
+ * </button>
31
+ * @if (panel.open) {
32
+ * <div [id]="panel.id" role="region">{{ panel.content }}</div>
33
+ * }
34
+ * }
35
+ * ```
36
+ */
37
+ class CngxAriaExpanded {
38
+ /** Whether the controlled element is currently expanded. Sets `aria-expanded`. */
39
+ expanded = input(false, { ...(ngDevMode ? { debugName: "expanded" } : /* istanbul ignore next */ {}), alias: 'cngxAriaExpanded' });
40
+ /** The `id` of the controlled element. Sets `aria-controls`. */
41
+ controls = input(undefined, ...(ngDevMode ? [{ debugName: "controls" }] : /* istanbul ignore next */ []));
42
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAriaExpanded, deps: [], target: i0.ɵɵFactoryTarget.Directive });
43
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxAriaExpanded, isStandalone: true, selector: "[cngxAriaExpanded]", inputs: { expanded: { classPropertyName: "expanded", publicName: "cngxAriaExpanded", isSignal: true, isRequired: false, transformFunction: null }, controls: { classPropertyName: "controls", publicName: "controls", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "attr.aria-expanded": "expanded()", "attr.aria-controls": "controls() ?? null" } }, exportAs: ["cngxAriaExpanded"], ngImport: i0 });
44
+ }
45
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAriaExpanded, decorators: [{
46
+ type: Directive,
47
+ args: [{
48
+ selector: '[cngxAriaExpanded]',
49
+ exportAs: 'cngxAriaExpanded',
50
+ standalone: true,
51
+ host: {
52
+ '[attr.aria-expanded]': 'expanded()',
53
+ '[attr.aria-controls]': 'controls() ?? null',
54
+ },
55
+ }]
56
+ }], propDecorators: { expanded: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxAriaExpanded", required: false }] }], controls: [{ type: i0.Input, args: [{ isSignal: true, alias: "controls", required: false }] }] } });
57
+
58
+ /**
59
+ * Configures the host element as an ARIA live region.
60
+ *
61
+ * Screen readers monitor live regions and announce content changes automatically.
62
+ * `polite` announcements are queued after the current utterance finishes;
63
+ * `assertive` announcements interrupt immediately. `off` disables announcements.
64
+ *
65
+ * Sets `role="alert"` for assertive regions and `role="status"` for polite regions
66
+ * via a host binding — no manual attribute wiring needed.
67
+ *
68
+ * Unlike CDK's `LiveAnnouncer` service (which creates a hidden DOM element and
69
+ * requires imperative `announce()` calls), this directive decorates your own
70
+ * element declaratively — the content you render IS the announcement.
71
+ *
72
+ * ### Status message
73
+ * ```html
74
+ * <div cngxLiveRegion [politeness]="'polite'">
75
+ * {{ statusMessage() }}
76
+ * </div>
77
+ * ```
78
+ *
79
+ * ### Form validation error (assertive)
80
+ * ```html
81
+ * <div cngxLiveRegion [politeness]="'assertive'"
82
+ * [style.color]="error() ? 'red' : 'transparent'">
83
+ * {{ error() }}
84
+ * </div>
85
+ * ```
86
+ */
87
+ class CngxLiveRegion {
88
+ /**
89
+ * Controls the urgency of announcements.
90
+ * - `'polite'` — queued after current speech (default)
91
+ * - `'assertive'` — interrupts immediately
92
+ * - `'off'` — no announcements
93
+ */
94
+ politeness = input('polite', ...(ngDevMode ? [{ debugName: "politeness" }] : /* istanbul ignore next */ []));
95
+ /** Whether the entire region should be announced as a whole. */
96
+ atomic = input(true, ...(ngDevMode ? [{ debugName: "atomic" }] : /* istanbul ignore next */ []));
97
+ /** Which types of content changes to announce. Space-separated: `additions`, `removals`, `text`. */
98
+ relevant = input('additions text', ...(ngDevMode ? [{ debugName: "relevant" }] : /* istanbul ignore next */ []));
99
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxLiveRegion, deps: [], target: i0.ɵɵFactoryTarget.Directive });
100
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxLiveRegion, isStandalone: true, selector: "[cngxLiveRegion]", inputs: { politeness: { classPropertyName: "politeness", publicName: "politeness", isSignal: true, isRequired: false, transformFunction: null }, atomic: { classPropertyName: "atomic", publicName: "atomic", isSignal: true, isRequired: false, transformFunction: null }, relevant: { classPropertyName: "relevant", publicName: "relevant", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "attr.aria-live": "politeness()", "attr.aria-atomic": "atomic()", "attr.aria-relevant": "relevant()", "attr.role": "politeness() === 'off' ? null : politeness() === 'assertive' ? 'alert' : 'status'" } }, exportAs: ["cngxLiveRegion"], ngImport: i0 });
101
+ }
102
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxLiveRegion, decorators: [{
103
+ type: Directive,
104
+ args: [{
105
+ selector: '[cngxLiveRegion]',
106
+ exportAs: 'cngxLiveRegion',
107
+ standalone: true,
108
+ host: {
109
+ '[attr.aria-live]': 'politeness()',
110
+ '[attr.aria-atomic]': 'atomic()',
111
+ '[attr.aria-relevant]': 'relevant()',
112
+ '[attr.role]': "politeness() === 'off' ? null : politeness() === 'assertive' ? 'alert' : 'status'",
113
+ },
114
+ }]
115
+ }], propDecorators: { politeness: [{ type: i0.Input, args: [{ isSignal: true, alias: "politeness", required: false }] }], atomic: [{ type: i0.Input, args: [{ isSignal: true, alias: "atomic", required: false }] }], relevant: [{ type: i0.Input, args: [{ isSignal: true, alias: "relevant", required: false }] }] } });
116
+
117
+ /**
118
+ * Reactive autofocus for dynamically inserted elements.
119
+ *
120
+ * The native `autofocus` HTML attribute only works on initial page load.
121
+ * This directive handles dynamic content: dialogs, panels, stepper steps,
122
+ * and any element that appears after the initial render.
123
+ *
124
+ * Focuses the host element after the next render frame using `afterNextRender`.
125
+ * When `when` changes to `true`, focus is re-applied.
126
+ *
127
+ * ### Focus on insertion
128
+ * ```html
129
+ * @if (showSearch()) {
130
+ * <input cngxAutofocus placeholder="Search…" />
131
+ * }
132
+ * ```
133
+ *
134
+ * ### Conditional focus
135
+ * ```html
136
+ * <input [cngxAutofocus]="isActive()" />
137
+ * ```
138
+ *
139
+ * ### With delay for transitions
140
+ * ```html
141
+ * <input cngxAutofocus [autofocusDelay]="200" />
142
+ * ```
143
+ */
144
+ class CngxAutofocus {
145
+ /** Whether to focus the element. Defaults to `true` (always focus on render). */
146
+ when = input(true, { ...(ngDevMode ? { debugName: "when" } : /* istanbul ignore next */ {}), alias: 'cngxAutofocus' });
147
+ /** Delay in ms before focusing — useful when the element appears during a transition. */
148
+ delay = input(0, { ...(ngDevMode ? { debugName: "delay" } : /* istanbul ignore next */ {}), alias: 'autofocusDelay' });
149
+ /** `FocusOptions` passed to `element.focus()`. */
150
+ options = input({}, { ...(ngDevMode ? { debugName: "options" } : /* istanbul ignore next */ {}), alias: 'autofocusOptions' });
151
+ el = inject((ElementRef));
152
+ injector = inject(Injector);
153
+ pendingTimer = null;
154
+ initialized = false;
155
+ constructor() {
156
+ inject(DestroyRef).onDestroy(() => this.clearPending());
157
+ afterNextRender(() => {
158
+ if (this.when()) {
159
+ this.scheduleFocus();
160
+ }
161
+ this.initialized = true;
162
+ });
163
+ // Re-focus on false→true transitions only; `previousWhen` starts as `true`
164
+ // so the initial effect run does not double-trigger alongside afterNextRender.
165
+ let previousWhen = true;
166
+ effect(() => {
167
+ const current = this.when();
168
+ if (this.initialized && current && !previousWhen) {
169
+ this.scheduleFocus();
170
+ }
171
+ previousWhen = current;
172
+ });
173
+ }
174
+ scheduleFocus() {
175
+ this.clearPending();
176
+ const delayMs = this.delay();
177
+ if (delayMs > 0) {
178
+ this.pendingTimer = setTimeout(() => this.applyFocus(), delayMs);
179
+ }
180
+ else {
181
+ afterNextRender(() => this.applyFocus(), { injector: this.injector });
182
+ }
183
+ }
184
+ applyFocus() {
185
+ this.el.nativeElement.focus(this.options());
186
+ }
187
+ clearPending() {
188
+ if (this.pendingTimer !== null) {
189
+ clearTimeout(this.pendingTimer);
190
+ this.pendingTimer = null;
191
+ }
192
+ }
193
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAutofocus, deps: [], target: i0.ɵɵFactoryTarget.Directive });
194
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxAutofocus, isStandalone: true, selector: "[cngxAutofocus]", inputs: { when: { classPropertyName: "when", publicName: "cngxAutofocus", isSignal: true, isRequired: false, transformFunction: null }, delay: { classPropertyName: "delay", publicName: "autofocusDelay", isSignal: true, isRequired: false, transformFunction: null }, options: { classPropertyName: "options", publicName: "autofocusOptions", isSignal: true, isRequired: false, transformFunction: null } }, exportAs: ["cngxAutofocus"], ngImport: i0 });
195
+ }
196
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAutofocus, decorators: [{
197
+ type: Directive,
198
+ args: [{
199
+ selector: '[cngxAutofocus]',
200
+ exportAs: 'cngxAutofocus',
201
+ standalone: true,
202
+ }]
203
+ }], ctorParameters: () => [], propDecorators: { when: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxAutofocus", required: false }] }], delay: [{ type: i0.Input, args: [{ isSignal: true, alias: "autofocusDelay", required: false }] }], options: [{ type: i0.Input, args: [{ isSignal: true, alias: "autofocusOptions", required: false }] }] } });
204
+
205
+ /**
206
+ * Stores the previously focused element and restores focus on destroy.
207
+ *
208
+ * Prevents focus from falling to `<body>` when dynamic content is removed
209
+ * (dialogs closing, panels collapsing, tabs switching). The directive captures
210
+ * `document.activeElement` at initialization time and restores it when the
211
+ * host element is destroyed.
212
+ *
213
+ * Fallback chain: stored element → provided fallback → nearest focusable ancestor → body.
214
+ *
215
+ * ### Panel that restores focus on close
216
+ * ```html
217
+ * @if (panelOpen()) {
218
+ * <div cngxFocusRestore>
219
+ * Panel content…
220
+ * <button (click)="panelOpen.set(false)">Close</button>
221
+ * </div>
222
+ * }
223
+ * ```
224
+ *
225
+ * ### With explicit fallback
226
+ * ```html
227
+ * <div cngxFocusRestore [focusRestoreFallback]="fallbackBtn">
228
+ * Dynamic content…
229
+ * </div>
230
+ * <button #fallbackBtn>Fallback target</button>
231
+ * ```
232
+ */
233
+ class CngxFocusRestore {
234
+ /** Whether to restore focus when the host element is destroyed. */
235
+ restoreOnDestroy = input(true, ...(ngDevMode ? [{ debugName: "restoreOnDestroy" }] : /* istanbul ignore next */ []));
236
+ /** Explicit fallback element if the stored element is no longer in the DOM. */
237
+ fallback = input(null, ...(ngDevMode ? [{ debugName: "fallback" }] : /* istanbul ignore next */ []));
238
+ doc = inject(DOCUMENT);
239
+ el = inject((ElementRef));
240
+ storedElement = signal(null, ...(ngDevMode ? [{ debugName: "storedElement" }] : /* istanbul ignore next */ []));
241
+ constructor() {
242
+ const activeEl = this.doc.activeElement;
243
+ if (activeEl instanceof HTMLElement) {
244
+ this.storedElement.set(activeEl);
245
+ }
246
+ inject(DestroyRef).onDestroy(() => {
247
+ if (!this.restoreOnDestroy()) {
248
+ return;
249
+ }
250
+ const target = this.resolveTarget();
251
+ if (target) {
252
+ target.focus();
253
+ }
254
+ });
255
+ }
256
+ /** Manually store the current focus target for later restoration. */
257
+ capture() {
258
+ const activeEl = this.doc.activeElement;
259
+ if (activeEl instanceof HTMLElement) {
260
+ this.storedElement.set(activeEl);
261
+ }
262
+ }
263
+ /** Manually restore focus to the stored element. */
264
+ restore() {
265
+ const target = this.resolveTarget();
266
+ if (target) {
267
+ target.focus();
268
+ }
269
+ }
270
+ /**
271
+ * Walks the fallback chain:
272
+ * 1. Stored element (if still in DOM and not body/self)
273
+ * 2. Explicit fallback input
274
+ * 3. Nearest focusable ancestor
275
+ */
276
+ resolveTarget() {
277
+ const stored = this.storedElement();
278
+ // Skip body — it signals "nothing meaningful was focused", not a real restore target.
279
+ if (stored &&
280
+ stored !== this.doc.body &&
281
+ this.doc.contains(stored) &&
282
+ stored !== this.el.nativeElement) {
283
+ return stored;
284
+ }
285
+ const fallback = this.fallback();
286
+ if (fallback && this.doc.contains(fallback)) {
287
+ return fallback;
288
+ }
289
+ return this.findFocusableAncestor();
290
+ }
291
+ /** Traverses up the DOM tree looking for the first natively focusable element. */
292
+ findFocusableAncestor() {
293
+ let current = this.el.nativeElement.parentElement;
294
+ while (current) {
295
+ if (this.isFocusable(current)) {
296
+ return current;
297
+ }
298
+ current = current.parentElement;
299
+ }
300
+ return null;
301
+ }
302
+ /** Checks if an element is natively focusable (tabindex, links, form controls). */
303
+ isFocusable(el) {
304
+ if (el.tabIndex >= 0) {
305
+ return true;
306
+ }
307
+ const tag = el.tagName.toLowerCase();
308
+ return ((tag === 'a' && el.hasAttribute('href')) ||
309
+ tag === 'button' ||
310
+ tag === 'input' ||
311
+ tag === 'select' ||
312
+ tag === 'textarea');
313
+ }
314
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFocusRestore, deps: [], target: i0.ɵɵFactoryTarget.Directive });
315
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxFocusRestore, isStandalone: true, selector: "[cngxFocusRestore]", inputs: { restoreOnDestroy: { classPropertyName: "restoreOnDestroy", publicName: "restoreOnDestroy", isSignal: true, isRequired: false, transformFunction: null }, fallback: { classPropertyName: "fallback", publicName: "fallback", isSignal: true, isRequired: false, transformFunction: null } }, exportAs: ["cngxFocusRestore"], ngImport: i0 });
316
+ }
317
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFocusRestore, decorators: [{
318
+ type: Directive,
319
+ args: [{
320
+ selector: '[cngxFocusRestore]',
321
+ exportAs: 'cngxFocusRestore',
322
+ standalone: true,
323
+ }]
324
+ }], ctorParameters: () => [], propDecorators: { restoreOnDestroy: [{ type: i0.Input, args: [{ isSignal: true, alias: "restoreOnDestroy", required: false }] }], fallback: [{ type: i0.Input, args: [{ isSignal: true, alias: "fallback", required: false }] }] } });
325
+
326
+ /**
327
+ * Traps keyboard focus within the host element using the CDK `FocusTrap`.
328
+ *
329
+ * When enabled, Tab and Shift+Tab cycle only within the host element's
330
+ * focusable children. When `autoFocus` is `true` (default), focus moves to
331
+ * the first tabbable element automatically on activation.
332
+ *
333
+ * Wraps CDK's `FocusTrapFactory` with a declarative, Signal-driven API.
334
+ * The CDK's imperative `create()` / `destroy()` / `enabled` setter lifecycle
335
+ * is handled internally via `effect()` and `DestroyRef`.
336
+ *
337
+ * ### Modal dialog
338
+ * ```html
339
+ * <div cngxFocusTrap [enabled]="isOpen()" [autoFocus]="true"
340
+ * tabindex="-1" role="dialog" aria-modal="true"
341
+ * (keydown.escape)="isOpen.set(false)">
342
+ * <input placeholder="First input" />
343
+ * <button (click)="isOpen.set(false)">Close</button>
344
+ * </div>
345
+ * ```
346
+ *
347
+ * ### Drawer / sidebar
348
+ * ```html
349
+ * <nav cngxFocusTrap [enabled]="drawerOpen()" tabindex="-1">
350
+ * <a href="/home">Home</a>
351
+ * <a href="/settings">Settings</a>
352
+ * </nav>
353
+ * ```
354
+ */
355
+ class CngxFocusTrap {
356
+ /** Whether the focus trap is active. When `false`, Tab navigates normally. */
357
+ enabled = input(false, ...(ngDevMode ? [{ debugName: "enabled" }] : /* istanbul ignore next */ []));
358
+ /** Whether to auto-focus the first tabbable element when the trap activates. */
359
+ autoFocus = input(true, ...(ngDevMode ? [{ debugName: "autoFocus" }] : /* istanbul ignore next */ []));
360
+ /** Computed signal reflecting the current trap state. */
361
+ isActive = computed(() => this.enabled(), ...(ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []));
362
+ trap;
363
+ constructor() {
364
+ const el = inject((ElementRef));
365
+ this.trap = inject(FocusTrapFactory).create(el.nativeElement);
366
+ effect(() => {
367
+ const enabled = this.enabled();
368
+ this.trap.enabled = enabled;
369
+ if (enabled && this.autoFocus()) {
370
+ void this.trap.focusFirstTabbableElementWhenReady();
371
+ }
372
+ });
373
+ inject(DestroyRef).onDestroy(() => this.trap.destroy());
374
+ }
375
+ /** Programmatically focus the first tabbable element within the trap. */
376
+ focusFirst() {
377
+ void this.trap.focusFirstTabbableElementWhenReady();
378
+ }
379
+ /** Programmatically focus the last tabbable element within the trap. */
380
+ focusLast() {
381
+ void this.trap.focusLastTabbableElementWhenReady();
382
+ }
383
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFocusTrap, deps: [], target: i0.ɵɵFactoryTarget.Directive });
384
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxFocusTrap, isStandalone: true, selector: "[cngxFocusTrap]", inputs: { enabled: { classPropertyName: "enabled", publicName: "enabled", isSignal: true, isRequired: false, transformFunction: null }, autoFocus: { classPropertyName: "autoFocus", publicName: "autoFocus", isSignal: true, isRequired: false, transformFunction: null } }, exportAs: ["cngxFocusTrap"], ngImport: i0 });
385
+ }
386
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFocusTrap, decorators: [{
387
+ type: Directive,
388
+ args: [{
389
+ selector: '[cngxFocusTrap]',
390
+ exportAs: 'cngxFocusTrap',
391
+ standalone: true,
392
+ }]
393
+ }], ctorParameters: () => [], propDecorators: { enabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "enabled", required: false }] }], autoFocus: [{ type: i0.Input, args: [{ isSignal: true, alias: "autoFocus", required: false }] }] } });
394
+
395
+ /**
396
+ * Tracks keyboard-initiated focus on the host element.
397
+ *
398
+ * Adds `cngx-focus-visible` CSS class when the element receives focus via keyboard
399
+ * and removes it on blur or when focus was initiated by pointer interaction.
400
+ *
401
+ *
402
+ * ```html
403
+ * <button cngxFocusVisible #fv="cngxFocusVisible">
404
+ * @if (fv.focusVisible()) { Focus ring visible }
405
+ * </button>
406
+ * ```
407
+ */
408
+ class CngxFocusVisible {
409
+ focusVisibleState = signal(false, ...(ngDevMode ? [{ debugName: "focusVisibleState" }] : /* istanbul ignore next */ []));
410
+ /** `true` when focus was initiated via keyboard (not pointer). */
411
+ focusVisible = this.focusVisibleState.asReadonly();
412
+ /** @internal Cleared on `focusin` after being set by `pointerdown`. */
413
+ pointerActive = false;
414
+ /** @internal Sets focus-visible state; clears pointer flag. */
415
+ handleFocus() {
416
+ this.focusVisibleState.set(!this.pointerActive);
417
+ this.pointerActive = false;
418
+ }
419
+ /** @internal Clears focus-visible state on blur. */
420
+ handleBlur() {
421
+ this.focusVisibleState.set(false);
422
+ }
423
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFocusVisible, deps: [], target: i0.ɵɵFactoryTarget.Directive });
424
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxFocusVisible, isStandalone: true, selector: "[cngxFocusVisible]", host: { listeners: { "pointerdown": "pointerActive = true", "focusin": "handleFocus()", "focusout": "handleBlur()" }, properties: { "class.cngx-focus-visible": "focusVisible()" } }, exportAs: ["cngxFocusVisible"], ngImport: i0 });
425
+ }
426
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFocusVisible, decorators: [{
427
+ type: Directive,
428
+ args: [{
429
+ selector: '[cngxFocusVisible]',
430
+ exportAs: 'cngxFocusVisible',
431
+ standalone: true,
432
+ host: {
433
+ '(pointerdown)': 'pointerActive = true',
434
+ '(focusin)': 'handleFocus()',
435
+ '(focusout)': 'handleBlur()',
436
+ '[class.cngx-focus-visible]': 'focusVisible()',
437
+ },
438
+ }]
439
+ }] });
440
+
441
+ /**
442
+ * Marker directive for items managed by `CngxRovingTabindex`.
443
+ *
444
+ * Place on each focusable child inside a `[cngxRovingTabindex]` container.
445
+ * The roving tabindex controller sets `tabindex="0"` on the active item
446
+ * and `tabindex="-1"` on all others.
447
+ *
448
+ * ```html
449
+ * <div cngxRovingTabindex>
450
+ * <button cngxRovingItem>One</button>
451
+ * <button cngxRovingItem>Two</button>
452
+ * <button cngxRovingItem>Three</button>
453
+ * </div>
454
+ * ```
455
+ */
456
+ class CngxRovingItem {
457
+ /** @internal Reference used by the parent `CngxRovingTabindex` to set `tabindex`. */
458
+ elementRef = inject((ElementRef));
459
+ /** Whether this item is disabled and should be skipped during navigation. */
460
+ disabled = input(false, { ...(ngDevMode ? { debugName: "disabled" } : /* istanbul ignore next */ {}), alias: 'cngxRovingItemDisabled' });
461
+ /** Programmatically focus this item. Called by the parent on arrow-key navigation. */
462
+ focus() {
463
+ this.elementRef.nativeElement.focus();
464
+ }
465
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRovingItem, deps: [], target: i0.ɵɵFactoryTarget.Directive });
466
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxRovingItem, isStandalone: true, selector: "[cngxRovingItem]", inputs: { disabled: { classPropertyName: "disabled", publicName: "cngxRovingItemDisabled", isSignal: true, isRequired: false, transformFunction: null } }, exportAs: ["cngxRovingItem"], ngImport: i0 });
467
+ }
468
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRovingItem, decorators: [{
469
+ type: Directive,
470
+ args: [{
471
+ selector: '[cngxRovingItem]',
472
+ exportAs: 'cngxRovingItem',
473
+ standalone: true,
474
+ }]
475
+ }], propDecorators: { disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxRovingItemDisabled", required: false }] }] } });
476
+ /**
477
+ * Implements the WAI-ARIA roving tabindex pattern for composite widgets.
478
+ *
479
+ * Only the active item in the group has `tabindex="0"` — all others get
480
+ * `tabindex="-1"`. Arrow keys move focus within the group; Tab leaves it.
481
+ * Home/End jump to first/last item.
482
+ *
483
+ * Works for toolbars, tab lists, card grids, menu bars, and any composite
484
+ * widget where only one item should be in the tab order at a time.
485
+ *
486
+ * ### Virtual mode
487
+ *
488
+ * When `virtualCount` is set, `activeIndex` ranges from 0 to `virtualCount - 1`
489
+ * instead of being bounded by `contentChildren.length`. Items are matched by
490
+ * `data-cngx-recycle-index` attribute. When the target item is not in the DOM
491
+ * (out of rendered range), `pendingFocus` is set so a wiring function like
492
+ * `connectRecyclerToRoving()` can scroll it into view.
493
+ *
494
+ * ### Horizontal toolbar
495
+ * ```html
496
+ * <div cngxRovingTabindex orientation="horizontal" #rv="cngxRovingTabindex">
497
+ * <button cngxRovingItem>Cut</button>
498
+ * <button cngxRovingItem>Copy</button>
499
+ * <button cngxRovingItem>Paste</button>
500
+ * </div>
501
+ * ```
502
+ *
503
+ * ### Vertical menu with controlled index
504
+ * ```html
505
+ * <ul cngxRovingTabindex orientation="vertical" [(activeIndex)]="selectedIdx">
506
+ * @for (item of items(); track item.id) {
507
+ * <li cngxRovingItem>{{ item.label }}</li>
508
+ * }
509
+ * </ul>
510
+ * ```
511
+ *
512
+ * ### Virtual scroll integration
513
+ * ```html
514
+ * <div cngxRovingTabindex orientation="vertical" [virtualCount]="recycler.ariaSetSize()">
515
+ * @for (item of visibleItems(); track item.id; let i = $index) {
516
+ * <div cngxRovingItem [cngxVirtualItem]="recycler" [cngxVirtualItemIndex]="recycler.start() + i">
517
+ * {{ item.name }}
518
+ * </div>
519
+ * }
520
+ * </div>
521
+ * ```
522
+ */
523
+ class CngxRovingTabindex {
524
+ /** Arrow key navigation axis. `'both'` enables both horizontal and vertical arrows. */
525
+ orientation = input('horizontal', ...(ngDevMode ? [{ debugName: "orientation" }] : /* istanbul ignore next */ []));
526
+ /** Whether navigation wraps from last to first and vice versa. */
527
+ loop = input(true, ...(ngDevMode ? [{ debugName: "loop" }] : /* istanbul ignore next */ []));
528
+ /** Index of the currently active (focusable) item. Supports two-way `[(activeIndex)]` binding. */
529
+ activeIndex = model(0, ...(ngDevMode ? [{ debugName: "activeIndex" }] : /* istanbul ignore next */ []));
530
+ /**
531
+ * Total item count for virtual mode. When set, `activeIndex` ranges from 0 to
532
+ * `virtualCount - 1` and items are matched by `data-cngx-recycle-index` attribute.
533
+ * When not set, standard `contentChildren`-based navigation is used.
534
+ */
535
+ virtualCount = input(undefined, ...(ngDevMode ? [{ debugName: "virtualCount" }] : /* istanbul ignore next */ []));
536
+ /** All `CngxRovingItem` children discovered via `contentChildren`. */
537
+ items = contentChildren(CngxRovingItem, ...(ngDevMode ? [{ debugName: "items" }] : /* istanbul ignore next */ []));
538
+ /** Guards against setting `tabindex` before the DOM is ready. */
539
+ initialized = signal(false, ...(ngDevMode ? [{ debugName: "initialized" }] : /* istanbul ignore next */ []));
540
+ /** Host element for `data-cngx-recycle-index` queries in virtual mode. */
541
+ hostEl = inject((ElementRef));
542
+ pendingFocusState = signal(null, ...(ngDevMode ? [{ debugName: "pendingFocusState" }] : /* istanbul ignore next */ []));
543
+ /**
544
+ * Index of the item that should receive focus but is not currently in the DOM.
545
+ * Non-null when virtual navigation targets an out-of-range item.
546
+ * Used by `connectRecyclerToRoving()` to scroll the item into view and focus it.
547
+ */
548
+ pendingFocus = this.pendingFocusState.asReadonly();
549
+ constructor() {
550
+ afterNextRender(() => this.initialized.set(true));
551
+ // Sync tabindex on every items/activeIndex change: active = "0", others = "-1".
552
+ effect(() => {
553
+ if (!this.initialized()) {
554
+ return;
555
+ }
556
+ const items = this.items();
557
+ const active = this.activeIndex();
558
+ const vc = this.virtualCount();
559
+ if (vc != null) {
560
+ // Virtual mode: match by data-cngx-recycle-index attribute
561
+ items.forEach((item) => {
562
+ const el = item.elementRef.nativeElement;
563
+ const idx = el.getAttribute('data-cngx-recycle-index');
564
+ el.setAttribute('tabindex', idx != null && Number(idx) === active ? '0' : '-1');
565
+ });
566
+ }
567
+ else {
568
+ // Standard mode: match by array index
569
+ const clamped = Math.max(0, Math.min(active, items.length - 1));
570
+ items.forEach((item, i) => item.elementRef.nativeElement.setAttribute('tabindex', i === clamped ? '0' : '-1'));
571
+ }
572
+ });
573
+ }
574
+ /**
575
+ * Clears the pending focus target. Called by `connectRecyclerToRoving()`
576
+ * after the item has been scrolled into view and focused.
577
+ */
578
+ clearPendingFocus() {
579
+ this.pendingFocusState.set(null);
580
+ }
581
+ /**
582
+ * Handles arrow-key, Home, and End navigation within the group.
583
+ * Prevents default scrolling on arrow keys.
584
+ *
585
+ * Unified handler — delegates to virtual or contentChildren navigation
586
+ * based on whether `virtualCount` is set.
587
+ */
588
+ handleKeyDown(event) {
589
+ const vc = this.virtualCount();
590
+ const allItems = this.items();
591
+ const isVirtual = vc != null;
592
+ const total = isVirtual ? vc : allItems.length;
593
+ if (total === 0) {
594
+ return;
595
+ }
596
+ if (!isVirtual && this.enabledItems().length === 0) {
597
+ return;
598
+ }
599
+ const currentActive = this.activeIndex();
600
+ const navigate = (direction) => isVirtual
601
+ ? this.findNextVirtual(currentActive, total, direction)
602
+ : this.findNext(currentActive, allItems, direction);
603
+ const keyMap = {
604
+ ArrowRight: () => (this.isHorizontal() ? navigate(1) : null),
605
+ ArrowLeft: () => (this.isHorizontal() ? navigate(-1) : null),
606
+ ArrowDown: () => (this.isVertical() ? navigate(1) : null),
607
+ ArrowUp: () => (this.isVertical() ? navigate(-1) : null),
608
+ Home: () => (isVirtual ? 0 : this.findFirst(allItems)),
609
+ End: () => (isVirtual ? total - 1 : this.findLast(allItems)),
610
+ };
611
+ const handler = keyMap[event.key];
612
+ if (!handler) {
613
+ return;
614
+ }
615
+ const nextIndex = handler();
616
+ if (nextIndex !== null && nextIndex !== currentActive) {
617
+ event.preventDefault();
618
+ this.activeIndex.set(nextIndex);
619
+ if (isVirtual) {
620
+ this.focusVirtualItem(nextIndex);
621
+ }
622
+ else {
623
+ allItems[nextIndex].focus();
624
+ }
625
+ }
626
+ else if (nextIndex === currentActive) {
627
+ event.preventDefault();
628
+ }
629
+ }
630
+ /**
631
+ * Attempts to focus a virtual item by querying `data-cngx-recycle-index`.
632
+ * If the element is not in the DOM, sets `pendingFocus` for external resolution.
633
+ */
634
+ focusVirtualItem(index) {
635
+ const el = this.hostEl.nativeElement.querySelector(`[data-cngx-recycle-index="${index}"]`);
636
+ if (el instanceof HTMLElement) {
637
+ el.focus();
638
+ this.pendingFocusState.set(null);
639
+ }
640
+ else {
641
+ this.pendingFocusState.set(index);
642
+ }
643
+ }
644
+ /**
645
+ * Finds the next index in virtual mode. No disabled-item skipping — can't check
646
+ * disabled state of items not in the DOM.
647
+ */
648
+ findNextVirtual(current, total, direction) {
649
+ if (total === 0) {
650
+ return null;
651
+ }
652
+ const idx = current + direction;
653
+ if (this.loop()) {
654
+ return ((idx % total) + total) % total;
655
+ }
656
+ if (idx < 0 || idx >= total) {
657
+ return null;
658
+ }
659
+ return idx;
660
+ }
661
+ enabledItems() {
662
+ return this.items().filter((item) => !item.disabled());
663
+ }
664
+ isHorizontal() {
665
+ const o = this.orientation();
666
+ return o === 'horizontal' || o === 'both';
667
+ }
668
+ isVertical() {
669
+ const o = this.orientation();
670
+ return o === 'vertical' || o === 'both';
671
+ }
672
+ /**
673
+ * Searches for the next enabled item starting from `current + direction`.
674
+ * Respects `loop` — wraps around or stops at the boundary.
675
+ * Skips disabled items.
676
+ */
677
+ findNext(current, items, direction) {
678
+ const len = items.length;
679
+ if (len === 0) {
680
+ return null;
681
+ }
682
+ let idx = current + direction;
683
+ const loop = this.loop();
684
+ for (let i = 0; i < len; i++) {
685
+ if (loop) {
686
+ idx = ((idx % len) + len) % len;
687
+ }
688
+ else if (idx < 0 || idx >= len) {
689
+ return null;
690
+ }
691
+ if (!items[idx].disabled()) {
692
+ return idx;
693
+ }
694
+ idx += direction;
695
+ }
696
+ return null;
697
+ }
698
+ findFirst(items) {
699
+ const idx = items.findIndex((item) => !item.disabled());
700
+ return idx >= 0 ? idx : null;
701
+ }
702
+ findLast(items) {
703
+ for (let i = items.length - 1; i >= 0; i--) {
704
+ if (!items[i].disabled()) {
705
+ return i;
706
+ }
707
+ }
708
+ return null;
709
+ }
710
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRovingTabindex, deps: [], target: i0.ɵɵFactoryTarget.Directive });
711
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.2.0", version: "21.2.4", type: CngxRovingTabindex, isStandalone: true, selector: "[cngxRovingTabindex]", inputs: { orientation: { classPropertyName: "orientation", publicName: "orientation", isSignal: true, isRequired: false, transformFunction: null }, loop: { classPropertyName: "loop", publicName: "loop", isSignal: true, isRequired: false, transformFunction: null }, activeIndex: { classPropertyName: "activeIndex", publicName: "activeIndex", isSignal: true, isRequired: false, transformFunction: null }, virtualCount: { classPropertyName: "virtualCount", publicName: "virtualCount", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { activeIndex: "activeIndexChange" }, host: { listeners: { "keydown": "handleKeyDown($event)" } }, queries: [{ propertyName: "items", predicate: CngxRovingItem, isSignal: true }], exportAs: ["cngxRovingTabindex"], ngImport: i0 });
712
+ }
713
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxRovingTabindex, decorators: [{
714
+ type: Directive,
715
+ args: [{
716
+ selector: '[cngxRovingTabindex]',
717
+ exportAs: 'cngxRovingTabindex',
718
+ standalone: true,
719
+ host: {
720
+ '(keydown)': 'handleKeyDown($event)',
721
+ },
722
+ }]
723
+ }], ctorParameters: () => [], propDecorators: { orientation: [{ type: i0.Input, args: [{ isSignal: true, alias: "orientation", required: false }] }], loop: [{ type: i0.Input, args: [{ isSignal: true, alias: "loop", required: false }] }], activeIndex: [{ type: i0.Input, args: [{ isSignal: true, alias: "activeIndex", required: false }] }, { type: i0.Output, args: ["activeIndexChange"] }], virtualCount: [{ type: i0.Input, args: [{ isSignal: true, alias: "virtualCount", required: false }] }], items: [{ type: i0.ContentChildren, args: [i0.forwardRef(() => CngxRovingItem), { isSignal: true }] }] } });
724
+
725
+ /**
726
+ * DI token for content-projected items that should register with the
727
+ * surrounding `CngxActiveDescendant`.
728
+ *
729
+ * Consumers like `CngxOption` and `CngxMenuItem` expose themselves via:
730
+ *
731
+ * ```typescript
732
+ * providers: [{ provide: CNGX_AD_ITEM, useExisting: MyItem }]
733
+ * ```
734
+ *
735
+ * The contained directive must expose `id`, `value`, `label`, and optionally
736
+ * `disabled` as signals — the AD reads them reactively.
737
+ */
738
+ const CNGX_AD_ITEM = new InjectionToken('CNGX_AD_ITEM');
739
+
740
+ /**
741
+ * Implements the WAI-ARIA active-descendant keyboard pattern for composite
742
+ * widgets where focus stays on a single host element and the currently active
743
+ * option is communicated via `aria-activedescendant`.
744
+ *
745
+ * ### When to use this vs. `CngxRovingTabindex`
746
+ *
747
+ * - **Active-descendant** when focus should stay on one container and you need
748
+ * `role="listbox"`, `role="menu"`, combobox inputs, or any widget where
749
+ * individual options should not be tab-stops. Screen readers announce the
750
+ * referenced option while keeping the focus ring on the host.
751
+ * - **Roving tabindex** when individual items should be tab-stops (toolbar,
752
+ * tab list, grid cells). See `CngxRovingTabindex`.
753
+ *
754
+ * ### Item registration
755
+ *
756
+ * Items register either by providing `CNGX_AD_ITEM` via `hostDirectives` or
757
+ * `providers`, or by passing a `Signal<ActiveDescendantItem[]>` through the
758
+ * `items` input. The latter takes precedence and is intended for combobox-style
759
+ * consumers driven by a dynamic data source.
760
+ *
761
+ * ### Virtualization
762
+ *
763
+ * When `virtualCount` is set, navigation targets can address indices not
764
+ * currently in the DOM. `pendingHighlight` signals the consumer to scroll the
765
+ * missing item into view; after scroll, the consumer calls
766
+ * `clearPendingHighlight()`.
767
+ *
768
+ * ### Material/CDK equivalent
769
+ *
770
+ * Mirrors the model used by `cdk-listbox` and `mat-select` but exposes it as a
771
+ * standalone primitive — not coupled to any visual shell, signal-reactive end
772
+ * to end, and unified across listbox/menu/combobox stacks.
773
+ */
774
+ class CngxActiveDescendant {
775
+ /**
776
+ * Optional explicit item list. When provided, takes precedence over items
777
+ * registered via `CNGX_AD_ITEM`. Useful for combobox-style consumers that
778
+ * drive the menu from a dynamic data source — pass the unwrapped array
779
+ * (typically the result of a `computed()`), Angular's signal inputs make it
780
+ * reactive automatically.
781
+ */
782
+ items = input(undefined, ...(ngDevMode ? [{ debugName: "items" }] : /* istanbul ignore next */ []));
783
+ /** Arrow-key navigation axis. Defaults to `'vertical'` (listbox/menu style). */
784
+ orientation = input('vertical', ...(ngDevMode ? [{ debugName: "orientation" }] : /* istanbul ignore next */ []));
785
+ /** Whether navigation wraps from last to first and vice versa. */
786
+ loop = input(true, ...(ngDevMode ? [{ debugName: "loop" }] : /* istanbul ignore next */ []));
787
+ /** Whether alphanumeric typeahead navigation is enabled. */
788
+ typeahead = input(true, ...(ngDevMode ? [{ debugName: "typeahead" }] : /* istanbul ignore next */ []));
789
+ /** Buffer reset window for typeahead, in milliseconds. */
790
+ typeaheadDebounce = input(300, ...(ngDevMode ? [{ debugName: "typeaheadDebounce" }] : /* istanbul ignore next */ []));
791
+ /** Whether the first non-disabled item is highlighted automatically. */
792
+ autoHighlightFirst = input(false, ...(ngDevMode ? [{ debugName: "autoHighlightFirst" }] : /* istanbul ignore next */ []));
793
+ /** Whether disabled items are skipped during navigation and value lookup. */
794
+ skipDisabled = input(true, ...(ngDevMode ? [{ debugName: "skipDisabled" }] : /* istanbul ignore next */ []));
795
+ /**
796
+ * When set, navigation treats the range `[0, virtualCount)` as the item
797
+ * space even if only a subset is rendered. Targets outside the rendered
798
+ * range surface as `pendingHighlight` for scroll-and-retry protocols.
799
+ */
800
+ virtualCount = input(undefined, ...(ngDevMode ? [{ debugName: "virtualCount" }] : /* istanbul ignore next */ []));
801
+ /** Emitted when `activateCurrent()` is called with an active item. */
802
+ activated = output();
803
+ /** Emitted whenever the highlighted item changes. */
804
+ highlighted = output();
805
+ hostEl = inject((ElementRef));
806
+ registered = contentChildren(CNGX_AD_ITEM, { ...(ngDevMode ? { debugName: "registered" } : /* istanbul ignore next */ {}), descendants: true });
807
+ /** Guards host attribute writes until after first render. */
808
+ initialized = signal(false, ...(ngDevMode ? [{ debugName: "initialized" }] : /* istanbul ignore next */ []));
809
+ /** -1 means "no active item". Range is [0, resolvedItems().length). */
810
+ activeIndexState = signal(-1, ...(ngDevMode ? [{ debugName: "activeIndexState" }] : /* istanbul ignore next */ []));
811
+ /** Index of an item that should be highlighted but is not in the DOM. */
812
+ pendingHighlightState = signal(null, ...(ngDevMode ? [{ debugName: "pendingHighlightState" }] : /* istanbul ignore next */ []));
813
+ pendingHighlight = this.pendingHighlightState.asReadonly();
814
+ /**
815
+ * Resolved item list. Input `items` wins; otherwise the contentChildren
816
+ * handles are projected into `ActiveDescendantItem` shape.
817
+ */
818
+ resolvedItems = computed(() => {
819
+ const explicit = this.items();
820
+ if (explicit) {
821
+ return explicit;
822
+ }
823
+ return this.registered().map(handleToItem);
824
+ }, ...(ngDevMode ? [{ debugName: "resolvedItems" }] : /* istanbul ignore next */ []));
825
+ /** Current active index. `-1` when no item is highlighted. */
826
+ activeIndex = computed(() => {
827
+ const idx = this.activeIndexState();
828
+ const total = this.totalCount();
829
+ if (idx < 0 || idx >= total) {
830
+ return -1;
831
+ }
832
+ return idx;
833
+ }, ...(ngDevMode ? [{ debugName: "activeIndex" }] : /* istanbul ignore next */ []));
834
+ /**
835
+ * `activeIndex` always mapped back to an item. `null` when no active index
836
+ * or the item is out of rendered range (virtual mode).
837
+ */
838
+ activeItem = computed(() => {
839
+ const idx = this.activeIndex();
840
+ if (idx < 0) {
841
+ return null;
842
+ }
843
+ const list = this.resolvedItems();
844
+ return list[idx] ?? null;
845
+ }, ...(ngDevMode ? [{ debugName: "activeItem" }] : /* istanbul ignore next */ []));
846
+ activeId = computed(() => this.activeItem()?.id ?? null, ...(ngDevMode ? [{ debugName: "activeId" }] : /* istanbul ignore next */ []));
847
+ activeValue = computed(() => this.activeItem()?.value ?? null, ...(ngDevMode ? [{ debugName: "activeValue" }] : /* istanbul ignore next */ []));
848
+ typeaheadBuffer = signal('', ...(ngDevMode ? [{ debugName: "typeaheadBuffer" }] : /* istanbul ignore next */ []));
849
+ typeaheadTimer = null;
850
+ constructor() {
851
+ afterNextRender(() => this.initialized.set(true));
852
+ effect(() => {
853
+ if (!this.initialized()) {
854
+ return;
855
+ }
856
+ if (this.autoHighlightFirst() && this.activeIndexState() === -1) {
857
+ this.highlightFirst();
858
+ }
859
+ });
860
+ effect(() => {
861
+ this.highlighted.emit(this.activeItem());
862
+ });
863
+ effect(() => {
864
+ const idx = this.activeIndex();
865
+ if (idx < 0) {
866
+ return;
867
+ }
868
+ if (this.virtualCount() != null) {
869
+ if (!this.isRendered(idx)) {
870
+ this.pendingHighlightState.set(idx);
871
+ return;
872
+ }
873
+ this.pendingHighlightState.set(null);
874
+ }
875
+ queueMicrotask(() => this.scrollActiveIntoView());
876
+ });
877
+ inject(DestroyRef).onDestroy(() => {
878
+ if (this.typeaheadTimer !== null) {
879
+ clearTimeout(this.typeaheadTimer);
880
+ }
881
+ });
882
+ }
883
+ highlightNext() {
884
+ const next = this.findFrom(this.activeIndexState(), 1);
885
+ if (next !== null) {
886
+ this.activeIndexState.set(next);
887
+ }
888
+ }
889
+ highlightPrev() {
890
+ const next = this.findFrom(this.activeIndexState(), -1);
891
+ if (next !== null) {
892
+ this.activeIndexState.set(next);
893
+ }
894
+ }
895
+ highlightFirst() {
896
+ const first = this.findBoundary(1);
897
+ if (first !== null) {
898
+ this.activeIndexState.set(first);
899
+ }
900
+ }
901
+ highlightLast() {
902
+ const last = this.findBoundary(-1);
903
+ if (last !== null) {
904
+ this.activeIndexState.set(last);
905
+ }
906
+ }
907
+ /**
908
+ * Highlight by zero-based index. Out-of-range indices are ignored.
909
+ * Disabled items are rejected when `skipDisabled()` is true.
910
+ */
911
+ highlightByIndex(index) {
912
+ const total = this.totalCount();
913
+ if (index < 0 || index >= total) {
914
+ return;
915
+ }
916
+ if (this.skipDisabled() && this.isDisabledAt(index)) {
917
+ return;
918
+ }
919
+ this.activeIndexState.set(index);
920
+ }
921
+ /**
922
+ * Highlight the first item whose value matches (via `Object.is`). No-op if
923
+ * no match. Disabled items are rejected when `skipDisabled()` is true.
924
+ */
925
+ highlightByValue(value) {
926
+ const items = this.resolvedItems();
927
+ const idx = items.findIndex((it) => Object.is(it.value, value));
928
+ if (idx < 0) {
929
+ return;
930
+ }
931
+ if (this.skipDisabled() && items[idx].disabled) {
932
+ return;
933
+ }
934
+ this.activeIndexState.set(idx);
935
+ }
936
+ /** Clear the highlight. */
937
+ resetHighlight() {
938
+ this.activeIndexState.set(-1);
939
+ }
940
+ /** Emit `activated` with the current item's value. No-op if nothing active. */
941
+ activateCurrent() {
942
+ const item = this.activeItem();
943
+ if (item) {
944
+ this.activated.emit(item.value);
945
+ }
946
+ }
947
+ /** Called by recycler bridges after scrolling the pending index into view. */
948
+ clearPendingHighlight() {
949
+ this.pendingHighlightState.set(null);
950
+ }
951
+ handleKeydown(event) {
952
+ // Skip events from editable descendants. Without this, every
953
+ // printable key typed into a descendant <input> hits AD's typeahead
954
+ // branch, gets preventDefault'd, and never reaches the input.
955
+ const target = event.target;
956
+ if (target && target !== event.currentTarget && isEditableTarget(target)) {
957
+ return;
958
+ }
959
+ const key = event.key;
960
+ if (this.isNavKey(key)) {
961
+ const before = this.activeIndexState();
962
+ this.dispatchNav(key);
963
+ if (this.activeIndexState() !== before) {
964
+ event.preventDefault();
965
+ }
966
+ return;
967
+ }
968
+ if (key === 'Enter' || key === ' ') {
969
+ if (this.activeItem()) {
970
+ event.preventDefault();
971
+ this.activateCurrent();
972
+ }
973
+ return;
974
+ }
975
+ if (this.typeahead() && isPrintableChar(key)) {
976
+ event.preventDefault();
977
+ this.handleTypeahead(key);
978
+ }
979
+ }
980
+ isNavKey(key) {
981
+ switch (key) {
982
+ case 'ArrowDown':
983
+ case 'ArrowUp':
984
+ case 'ArrowLeft':
985
+ case 'ArrowRight':
986
+ case 'Home':
987
+ case 'End':
988
+ return true;
989
+ default:
990
+ return false;
991
+ }
992
+ }
993
+ dispatchNav(key) {
994
+ const orientation = this.orientation();
995
+ switch (key) {
996
+ case 'ArrowDown':
997
+ if (orientation === 'vertical') {
998
+ this.highlightNext();
999
+ }
1000
+ return;
1001
+ case 'ArrowUp':
1002
+ if (orientation === 'vertical') {
1003
+ this.highlightPrev();
1004
+ }
1005
+ return;
1006
+ case 'ArrowRight':
1007
+ if (orientation === 'horizontal') {
1008
+ this.highlightNext();
1009
+ }
1010
+ return;
1011
+ case 'ArrowLeft':
1012
+ if (orientation === 'horizontal') {
1013
+ this.highlightPrev();
1014
+ }
1015
+ return;
1016
+ case 'Home':
1017
+ this.highlightFirst();
1018
+ return;
1019
+ case 'End':
1020
+ this.highlightLast();
1021
+ return;
1022
+ }
1023
+ }
1024
+ /**
1025
+ * Push a printable character into the typeahead buffer and jump to the next
1026
+ * matching option. Exposed for external keyboard hosts (e.g. a select
1027
+ * trigger) that keep focus on themselves while using active-descendant
1028
+ * semantics on a separate listbox.
1029
+ *
1030
+ * Consumers should only forward single-character printable keys (`length === 1`,
1031
+ * non-whitespace). Navigation keys and non-printables must not be forwarded.
1032
+ */
1033
+ typeaheadChar(ch) {
1034
+ if (!this.typeahead()) {
1035
+ return;
1036
+ }
1037
+ this.handleTypeahead(ch);
1038
+ }
1039
+ handleTypeahead(ch) {
1040
+ const next = this.typeaheadBuffer() + ch.toLowerCase();
1041
+ this.typeaheadBuffer.set(next);
1042
+ if (this.typeaheadTimer !== null) {
1043
+ clearTimeout(this.typeaheadTimer);
1044
+ }
1045
+ this.typeaheadTimer = setTimeout(() => {
1046
+ this.typeaheadBuffer.set('');
1047
+ this.typeaheadTimer = null;
1048
+ }, this.typeaheadDebounce());
1049
+ const items = this.resolvedItems();
1050
+ const skip = this.skipDisabled();
1051
+ const start = Math.max(0, this.activeIndexState());
1052
+ const total = items.length;
1053
+ for (let offset = 0; offset < total; offset++) {
1054
+ const i = (start + offset) % total;
1055
+ const candidate = items[i];
1056
+ if (skip && candidate.disabled) {
1057
+ continue;
1058
+ }
1059
+ if (candidate.label.toLowerCase().startsWith(next)) {
1060
+ this.activeIndexState.set(i);
1061
+ return;
1062
+ }
1063
+ }
1064
+ }
1065
+ findFrom(current, direction) {
1066
+ const total = this.totalCount();
1067
+ if (total === 0) {
1068
+ return null;
1069
+ }
1070
+ const items = this.resolvedItems();
1071
+ const skip = this.skipDisabled();
1072
+ const loop = this.loop();
1073
+ let idx = current < 0 ? (direction === 1 ? -1 : total) : current;
1074
+ for (let step = 0; step < total; step++) {
1075
+ idx += direction;
1076
+ if (idx < 0 || idx >= total) {
1077
+ if (!loop) {
1078
+ return null;
1079
+ }
1080
+ idx = ((idx % total) + total) % total;
1081
+ }
1082
+ if (!skip || !items[idx]?.disabled) {
1083
+ return idx;
1084
+ }
1085
+ }
1086
+ return null;
1087
+ }
1088
+ findBoundary(direction) {
1089
+ const items = this.resolvedItems();
1090
+ const total = items.length;
1091
+ if (total === 0) {
1092
+ return null;
1093
+ }
1094
+ const skip = this.skipDisabled();
1095
+ if (direction === 1) {
1096
+ for (let i = 0; i < total; i++) {
1097
+ if (!skip || !items[i].disabled) {
1098
+ return i;
1099
+ }
1100
+ }
1101
+ }
1102
+ else {
1103
+ for (let i = total - 1; i >= 0; i--) {
1104
+ if (!skip || !items[i].disabled) {
1105
+ return i;
1106
+ }
1107
+ }
1108
+ }
1109
+ return null;
1110
+ }
1111
+ totalCount() {
1112
+ const vc = this.virtualCount();
1113
+ if (vc != null) {
1114
+ return vc;
1115
+ }
1116
+ return this.resolvedItems().length;
1117
+ }
1118
+ isDisabledAt(index) {
1119
+ const items = this.resolvedItems();
1120
+ return !!items[index]?.disabled;
1121
+ }
1122
+ isRendered(index) {
1123
+ const items = this.resolvedItems();
1124
+ return index >= 0 && index < items.length && !!items[index];
1125
+ }
1126
+ scrollActiveIntoView() {
1127
+ const id = this.activeId();
1128
+ if (!id) {
1129
+ return;
1130
+ }
1131
+ const el = this.hostEl.nativeElement.querySelector(`#${cssEscape(id)}`);
1132
+ if (el instanceof HTMLElement && typeof el.scrollIntoView === 'function') {
1133
+ el.scrollIntoView({ block: 'nearest', inline: 'nearest' });
1134
+ }
1135
+ }
1136
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxActiveDescendant, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1137
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.2.0", version: "21.2.4", type: CngxActiveDescendant, isStandalone: true, selector: "[cngxActiveDescendant]", inputs: { items: { classPropertyName: "items", publicName: "items", isSignal: true, isRequired: false, transformFunction: null }, orientation: { classPropertyName: "orientation", publicName: "orientation", isSignal: true, isRequired: false, transformFunction: null }, loop: { classPropertyName: "loop", publicName: "loop", isSignal: true, isRequired: false, transformFunction: null }, typeahead: { classPropertyName: "typeahead", publicName: "typeahead", isSignal: true, isRequired: false, transformFunction: null }, typeaheadDebounce: { classPropertyName: "typeaheadDebounce", publicName: "typeaheadDebounce", isSignal: true, isRequired: false, transformFunction: null }, autoHighlightFirst: { classPropertyName: "autoHighlightFirst", publicName: "autoHighlightFirst", isSignal: true, isRequired: false, transformFunction: null }, skipDisabled: { classPropertyName: "skipDisabled", publicName: "skipDisabled", isSignal: true, isRequired: false, transformFunction: null }, virtualCount: { classPropertyName: "virtualCount", publicName: "virtualCount", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { activated: "activated", highlighted: "highlighted" }, host: { listeners: { "keydown": "handleKeydown($event)" }, properties: { "attr.aria-activedescendant": "activeId()" } }, queries: [{ propertyName: "registered", predicate: CNGX_AD_ITEM, descendants: true, isSignal: true }], exportAs: ["cngxActiveDescendant"], ngImport: i0 });
1138
+ }
1139
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxActiveDescendant, decorators: [{
1140
+ type: Directive,
1141
+ args: [{
1142
+ selector: '[cngxActiveDescendant]',
1143
+ exportAs: 'cngxActiveDescendant',
1144
+ standalone: true,
1145
+ host: {
1146
+ '[attr.aria-activedescendant]': 'activeId()',
1147
+ '(keydown)': 'handleKeydown($event)',
1148
+ },
1149
+ }]
1150
+ }], ctorParameters: () => [], propDecorators: { items: [{ type: i0.Input, args: [{ isSignal: true, alias: "items", required: false }] }], orientation: [{ type: i0.Input, args: [{ isSignal: true, alias: "orientation", required: false }] }], loop: [{ type: i0.Input, args: [{ isSignal: true, alias: "loop", required: false }] }], typeahead: [{ type: i0.Input, args: [{ isSignal: true, alias: "typeahead", required: false }] }], typeaheadDebounce: [{ type: i0.Input, args: [{ isSignal: true, alias: "typeaheadDebounce", required: false }] }], autoHighlightFirst: [{ type: i0.Input, args: [{ isSignal: true, alias: "autoHighlightFirst", required: false }] }], skipDisabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "skipDisabled", required: false }] }], virtualCount: [{ type: i0.Input, args: [{ isSignal: true, alias: "virtualCount", required: false }] }], activated: [{ type: i0.Output, args: ["activated"] }], highlighted: [{ type: i0.Output, args: ["highlighted"] }], registered: [{ type: i0.ContentChildren, args: [i0.forwardRef(() => CNGX_AD_ITEM), { ...{ descendants: true }, isSignal: true }] }] } });
1151
+ function handleToItem(handle) {
1152
+ return {
1153
+ id: handle.id,
1154
+ value: handle.value(),
1155
+ label: handle.label(),
1156
+ disabled: handle.disabled?.() ?? false,
1157
+ };
1158
+ }
1159
+ function isPrintableChar(key) {
1160
+ return key.length === 1 && /\S/.exec(key) !== null;
1161
+ }
1162
+ /**
1163
+ * True when the element would capture text input natively — a text
1164
+ * `<input>`, `<textarea>`, or any `contenteditable` host. Read-only /
1165
+ * button-type inputs (submit, radio, checkbox) are NOT editable; AD's
1166
+ * keyboard navigation still applies when focus lands on them.
1167
+ */
1168
+ function isEditableTarget(el) {
1169
+ if (el.isContentEditable) {
1170
+ return true;
1171
+ }
1172
+ const tag = el.tagName;
1173
+ if (tag === 'TEXTAREA') {
1174
+ return true;
1175
+ }
1176
+ if (tag === 'INPUT') {
1177
+ const type = el.type.toLowerCase();
1178
+ return (type !== 'button' &&
1179
+ type !== 'submit' &&
1180
+ type !== 'reset' &&
1181
+ type !== 'checkbox' &&
1182
+ type !== 'radio' &&
1183
+ type !== 'range' &&
1184
+ type !== 'color' &&
1185
+ type !== 'file' &&
1186
+ type !== 'image');
1187
+ }
1188
+ return false;
1189
+ }
1190
+ function cssEscape(id) {
1191
+ const api = globalThis.CSS;
1192
+ if (api && typeof api.escape === 'function') {
1193
+ return api.escape(id);
1194
+ }
1195
+ return id.replace(/[^a-zA-Z0-9_-]/g, (m) => `\\${m}`);
1196
+ }
1197
+
1198
+ /**
1199
+ * Reflects the user's `prefers-reduced-motion` media query as a reactive signal.
1200
+ *
1201
+ * Adds the `cngx-reduced-motion` CSS class to the host when the user prefers
1202
+ * reduced motion. The `prefersReducedMotion()` signal updates live when the
1203
+ * OS preference changes — use it in TypeScript to skip animations, disable
1204
+ * auto-playing media, or choose between animated and instant transitions.
1205
+ *
1206
+ * Unlike a CSS-only `@media (prefers-reduced-motion: reduce)` approach, this
1207
+ * directive makes the preference available in component logic (e.g., to pick
1208
+ * a different animation strategy or suppress requestAnimationFrame loops).
1209
+ *
1210
+ * ### Conditional animation
1211
+ * ```html
1212
+ * <div cngxReducedMotion #rm="cngxReducedMotion"
1213
+ * [style.animation]="rm.prefersReducedMotion() ? 'none' : 'spin 2s linear infinite'">
1214
+ * </div>
1215
+ * ```
1216
+ *
1217
+ * ### TypeScript logic
1218
+ * ```typescript
1219
+ * readonly rm = viewChild(CngxReducedMotion);
1220
+ * readonly duration = computed(() => this.rm()?.prefersReducedMotion() ? 0 : 300);
1221
+ * ```
1222
+ */
1223
+ class CngxReducedMotion {
1224
+ /** `true` when the user's OS is set to prefer reduced motion. Updates reactively. */
1225
+ prefersReducedMotion;
1226
+ constructor() {
1227
+ const win = inject(DOCUMENT).defaultView;
1228
+ const pref = signal(false, ...(ngDevMode ? [{ debugName: "pref" }] : /* istanbul ignore next */ []));
1229
+ if (win) {
1230
+ const mq = win.matchMedia('(prefers-reduced-motion: reduce)');
1231
+ pref.set(mq.matches);
1232
+ const listener = (e) => pref.set(e.matches);
1233
+ mq.addEventListener('change', listener);
1234
+ inject(DestroyRef).onDestroy(() => mq.removeEventListener('change', listener));
1235
+ }
1236
+ this.prefersReducedMotion = pref.asReadonly();
1237
+ }
1238
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxReducedMotion, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1239
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxReducedMotion, isStandalone: true, selector: "[cngxReducedMotion]", host: { properties: { "class.cngx-reduced-motion": "prefersReducedMotion()" } }, exportAs: ["cngxReducedMotion"], ngImport: i0 });
1240
+ }
1241
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxReducedMotion, decorators: [{
1242
+ type: Directive,
1243
+ args: [{
1244
+ selector: '[cngxReducedMotion]',
1245
+ exportAs: 'cngxReducedMotion',
1246
+ standalone: true,
1247
+ host: { '[class.cngx-reduced-motion]': 'prefersReducedMotion()' },
1248
+ }]
1249
+ }], ctorParameters: () => [] });
1250
+
1251
+ /**
1252
+ * @module @cngx/common/a11y
1253
+ */
1254
+
1255
+ /**
1256
+ * Generated bundle index. Do not edit.
1257
+ */
1258
+
1259
+ export { CNGX_AD_ITEM, CngxActiveDescendant, CngxAriaExpanded, CngxAutofocus, CngxFocusRestore, CngxFocusTrap, CngxFocusVisible, CngxLiveRegion, CngxReducedMotion, CngxRovingItem, CngxRovingTabindex };
1260
+ //# sourceMappingURL=cngx-common-a11y.mjs.map