@cngx/common 0.1.0-rc.8 → 0.3.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 (90) hide show
  1. package/a11y/README.md +15 -2
  2. package/button/README.md +258 -0
  3. package/command/README.md +42 -2
  4. package/data/README.md +15 -12
  5. package/fesm2022/cngx-common-a11y.mjs +1076 -319
  6. package/fesm2022/cngx-common-a11y.mjs.map +1 -1
  7. package/fesm2022/cngx-common-audio.mjs +99 -77
  8. package/fesm2022/cngx-common-audio.mjs.map +1 -1
  9. package/fesm2022/cngx-common-button.mjs +1084 -0
  10. package/fesm2022/cngx-common-button.mjs.map +1 -0
  11. package/fesm2022/cngx-common-card.mjs +138 -78
  12. package/fesm2022/cngx-common-card.mjs.map +1 -1
  13. package/fesm2022/cngx-common-chart.mjs +799 -327
  14. package/fesm2022/cngx-common-chart.mjs.map +1 -1
  15. package/fesm2022/cngx-common-command.mjs +101 -25
  16. package/fesm2022/cngx-common-command.mjs.map +1 -1
  17. package/fesm2022/cngx-common-data.mjs +861 -423
  18. package/fesm2022/cngx-common-data.mjs.map +1 -1
  19. package/fesm2022/cngx-common-dialog.mjs +198 -160
  20. package/fesm2022/cngx-common-dialog.mjs.map +1 -1
  21. package/fesm2022/cngx-common-display.mjs +693 -329
  22. package/fesm2022/cngx-common-display.mjs.map +1 -1
  23. package/fesm2022/cngx-common-interactive.mjs +7303 -2774
  24. package/fesm2022/cngx-common-interactive.mjs.map +1 -1
  25. package/fesm2022/cngx-common-layout.mjs +2174 -442
  26. package/fesm2022/cngx-common-layout.mjs.map +1 -1
  27. package/fesm2022/cngx-common-menu-button.mjs +557 -0
  28. package/fesm2022/cngx-common-menu-button.mjs.map +1 -0
  29. package/fesm2022/cngx-common-popover.mjs +2109 -557
  30. package/fesm2022/cngx-common-popover.mjs.map +1 -1
  31. package/fesm2022/cngx-common-stepper.mjs +548 -419
  32. package/fesm2022/cngx-common-stepper.mjs.map +1 -1
  33. package/fesm2022/cngx-common-tabs.mjs +442 -331
  34. package/fesm2022/cngx-common-tabs.mjs.map +1 -1
  35. package/fesm2022/cngx-common-timeline.mjs +44 -71
  36. package/fesm2022/cngx-common-timeline.mjs.map +1 -1
  37. package/fesm2022/cngx-common.mjs +10 -10
  38. package/fesm2022/cngx-common.mjs.map +1 -1
  39. package/interactive/README.md +30 -19
  40. package/layout/README.md +17 -1
  41. package/menu-button/README.md +234 -0
  42. package/package.json +31 -8
  43. package/popover/README.md +81 -4
  44. package/popover/tooltip-indicator.scss +52 -0
  45. package/schematics/collection.json +9 -0
  46. package/schematics/ng-add/index.js +9 -0
  47. package/schematics/ng-add/schema.json +96 -0
  48. package/schematics/package.json +3 -0
  49. package/stepper/README.md +5 -5
  50. package/theming/components/cngx-accordion.css +36 -7
  51. package/theming/components/cngx-async.css +185 -37
  52. package/theming/components/cngx-backdrop.css +3 -1
  53. package/theming/components/cngx-badge.css +20 -5
  54. package/theming/components/cngx-bottom-sheet.css +2 -0
  55. package/theming/components/cngx-breadcrumb.css +3 -1
  56. package/theming/components/cngx-button-group.css +325 -0
  57. package/theming/components/cngx-button-toggle.css +55 -23
  58. package/theming/components/cngx-button.css +975 -0
  59. package/theming/components/cngx-data-grid.css +2 -0
  60. package/theming/components/cngx-dialog.css +3 -1
  61. package/theming/components/cngx-divider.css +24 -9
  62. package/theming/components/cngx-drawer.css +153 -0
  63. package/theming/components/cngx-icon-glyph.css +76 -0
  64. package/theming/components/cngx-listbox.css +79 -25
  65. package/theming/components/cngx-menu.css +112 -52
  66. package/theming/components/cngx-nav.css +1220 -0
  67. package/theming/components/cngx-popover-sheet.css +434 -0
  68. package/theming/components/cngx-popover.css +37 -9
  69. package/theming/components/cngx-recycler-placeholder.css +2 -0
  70. package/theming/components/cngx-ripple.css +74 -16
  71. package/theming/components/cngx-sidebar.css +71 -0
  72. package/theming/components/cngx-slider.css +3 -1
  73. package/theming/components/cngx-tooltip.css +2 -0
  74. package/timeline/README.md +2 -2
  75. package/types/cngx-common-a11y.d.ts +488 -112
  76. package/types/cngx-common-audio.d.ts +60 -88
  77. package/types/cngx-common-button.d.ts +698 -0
  78. package/types/cngx-common-card.d.ts +104 -78
  79. package/types/cngx-common-chart.d.ts +677 -389
  80. package/types/cngx-common-command.d.ts +55 -41
  81. package/types/cngx-common-data.d.ts +506 -360
  82. package/types/cngx-common-dialog.d.ts +94 -127
  83. package/types/cngx-common-display.d.ts +475 -300
  84. package/types/cngx-common-interactive.d.ts +4383 -1721
  85. package/types/cngx-common-layout.d.ts +1399 -288
  86. package/types/cngx-common-menu-button.d.ts +382 -0
  87. package/types/cngx-common-popover.d.ts +990 -268
  88. package/types/cngx-common-stepper.d.ts +374 -465
  89. package/types/cngx-common-tabs.d.ts +309 -403
  90. package/types/cngx-common-timeline.d.ts +50 -109
@@ -1,10 +1,21 @@
1
1
  import * as i0 from '@angular/core';
2
- import { input, Directive, inject, PLATFORM_ID, Injectable, ElementRef, Injector, DestroyRef, afterNextRender, effect, signal, computed, untracked, model, contentChildren, InjectionToken, output } from '@angular/core';
2
+ import { InjectionToken, input, booleanAttribute, inject, Injector, computed, Directive, PLATFORM_ID, Injectable, DestroyRef, ElementRef, afterNextRender, effect, untracked, signal, model, contentChildren, output, linkedSignal } from '@angular/core';
3
3
  import { DOCUMENT, isPlatformBrowser } from '@angular/common';
4
+ import { createTransitionTracker, isComposingKeydown, isTextEntryTarget, injectLocale, createTypeaheadWalker, CNGX_NESTED_INTERACTIVE_SELECTOR, createMediaQuerySignal } from '@cngx/core/utils';
4
5
  import { FocusTrapFactory } from '@angular/cdk/a11y';
5
6
  import { injectDirection, resolveInlineStep, resolveStepFrom, resolveBoundaryStep } from '@cngx/core';
6
- import { injectLocale, createTypeaheadMatcher, createMediaQuerySignal } from '@cngx/core/utils';
7
7
 
8
+ /**
9
+ * Injection token for a {@link CngxAriaExpandedDriver}. A composer provides it
10
+ * on its own element (`useExisting`) to override `[cngxAriaExpanded]` of its
11
+ * `CngxAriaExpanded` host directive; `aria-controls` still follows
12
+ * `[controls]`. Used by `CngxExpandable`.
13
+ *
14
+ * @relatedTo CngxAriaExpanded
15
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/aria/aria-expanded.directive.ts
16
+ * @since 0.3.0
17
+ */
18
+ const CNGX_ARIA_EXPANDED_DRIVER = new InjectionToken('CngxAriaExpandedDriver');
8
19
  /**
9
20
  * Manages `aria-expanded` and optionally `aria-controls` on the host element.
10
21
  *
@@ -36,21 +47,35 @@ import { injectLocale, createTypeaheadMatcher, createMediaQuerySignal } from '@c
36
47
  * }
37
48
  * ```
38
49
  *
39
- * @category common/a11y
40
50
  * @wcag AA
41
51
  * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/aria/aria-expanded.directive.ts
42
- * @since 0.1.0
52
+ * @since 0.3.0
43
53
  * @relatedTo CngxLiveRegion, CngxExpandable, CngxDisclosure
44
- * <example-url>http://localhost:4200/#/common/a11y/aria-expanded/accordion-multiple-panels</example-url>
45
- * <example-url>http://localhost:4200/#/common/a11y/aria-expanded/disclosure-pattern</example-url>
54
+ * <example-url>/#/common/a11y/aria-expanded/accordion-multiple-panels</example-url>
55
+ * <example-url>/#/common/a11y/aria-expanded/disclosure-pattern</example-url>
56
+ * @axis level atom
46
57
  */
47
58
  class CngxAriaExpanded {
48
59
  /** Whether the controlled element is currently expanded. Sets `aria-expanded`. */
49
- expanded = input(false, { ...(ngDevMode ? { debugName: "expanded" } : /* istanbul ignore next */ {}), alias: 'cngxAriaExpanded' });
60
+ expanded = input(false, { ...(ngDevMode ? { debugName: "expanded" } : /* istanbul ignore next */ {}), alias: 'cngxAriaExpanded',
61
+ transform: booleanAttribute });
50
62
  /** The `id` of the controlled element. Sets `aria-controls`. */
51
63
  controls = input(undefined, ...(ngDevMode ? [{ debugName: "controls" }] : /* istanbul ignore next */ []));
64
+ injector = inject(Injector);
65
+ resolvedDriver = undefined;
66
+ driver() {
67
+ if (this.resolvedDriver === undefined) {
68
+ this.resolvedDriver = this.injector.get(CNGX_ARIA_EXPANDED_DRIVER, null, { self: true });
69
+ }
70
+ return this.resolvedDriver;
71
+ }
72
+ /** @internal The written attribute value: the driver's when composed, else the input. */
73
+ ariaExpanded = computed(() => {
74
+ const driver = this.driver();
75
+ return driver ? driver.ariaExpanded() : this.expanded();
76
+ }, ...(ngDevMode ? [{ debugName: "ariaExpanded" }] : /* istanbul ignore next */ []));
52
77
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAriaExpanded, deps: [], target: i0.ɵɵFactoryTarget.Directive });
53
- 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 });
78
+ 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": "ariaExpanded()", "attr.aria-controls": "controls() ?? null" } }, exportAs: ["cngxAriaExpanded"], ngImport: i0 });
54
79
  }
55
80
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAriaExpanded, decorators: [{
56
81
  type: Directive,
@@ -59,7 +84,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
59
84
  exportAs: 'cngxAriaExpanded',
60
85
  standalone: true,
61
86
  host: {
62
- '[attr.aria-expanded]': 'expanded()',
87
+ '[attr.aria-expanded]': 'ariaExpanded()',
63
88
  '[attr.aria-controls]': 'controls() ?? null',
64
89
  },
65
90
  }]
@@ -75,9 +100,9 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
75
100
  * Sets `role="alert"` for assertive regions and `role="status"` for polite regions
76
101
  * via a host binding - no manual attribute wiring needed.
77
102
  *
78
- * Unlike CDK's `LiveAnnouncer` service (which creates a hidden DOM element and
79
- * requires imperative `announce()` calls), this directive decorates your own
80
- * element declaratively - the content you render IS the announcement.
103
+ * Unlike `CngxLiveAnnouncer` (hidden regions it owns, imperative
104
+ * `announce()` calls), this directive decorates your own element
105
+ * declaratively - the content you render IS the announcement.
81
106
  *
82
107
  * ### Status message
83
108
  * ```html
@@ -94,13 +119,13 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
94
119
  * </div>
95
120
  * ```
96
121
  *
97
- * @category common/a11y
98
122
  * @wcag AA
99
123
  * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/aria/live-region.directive.ts
100
- * @since 0.1.0
101
- * @relatedTo CngxAriaExpanded
102
- * <example-url>http://localhost:4200/#/common/a11y/live-region/form-validation-assertive-error-announcements</example-url>
103
- * <example-url>http://localhost:4200/#/common/a11y/live-region/polite-vs-assertive</example-url>
124
+ * @since 0.3.0
125
+ * @relatedTo CngxLiveAnnouncer
126
+ * <example-url>/#/common/a11y/live-region/form-validation-assertive-error-announcements</example-url>
127
+ * <example-url>/#/common/a11y/live-region/polite-vs-assertive</example-url>
128
+ * @axis level atom
104
129
  */
105
130
  class CngxLiveRegion {
106
131
  /**
@@ -135,6 +160,142 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
135
160
  // One frame. Clear the region this long before writing so an intentionally
136
161
  // repeated identical string still registers as a content change for the SR.
137
162
  const CLEAR_DELAY_MS = 16;
163
+ // How long a written message stays in its region before it is cleared. A
164
+ // screen reader takes the text when the change event fires, so the clear is
165
+ // silent; it stops a stale message from being read by browsing to the end
166
+ // of the document, or after a route change.
167
+ const HOLD_MS = 7000;
168
+ const POLITENESS = ['polite', 'assertive'];
169
+ /**
170
+ * @internal Browser only: callers guard the server path. Each region is a
171
+ * visually hidden `aria-live` + `aria-atomic="true"` span (the attribute
172
+ * contract of `CngxLiveRegion`), created lazily on the first announce of its
173
+ * politeness or by `ensure()`. A written message is cleared again after a
174
+ * hold, so the region never keeps stale text.
175
+ *
176
+ * `redirect` is asked when a write is due: returning `true` means the caller
177
+ * took the message elsewhere (its container stopped being readable while the
178
+ * write was pending), so nothing is written here.
179
+ */
180
+ function createLiveRegionPair(container, doc, redirect) {
181
+ const regions = {
182
+ polite: null,
183
+ assertive: null,
184
+ };
185
+ const pending = {
186
+ polite: null,
187
+ assertive: null,
188
+ };
189
+ const holds = {
190
+ polite: null,
191
+ assertive: null,
192
+ };
193
+ const cancelHold = (politeness) => {
194
+ const hold = holds[politeness];
195
+ if (hold !== null) {
196
+ clearTimeout(hold);
197
+ holds[politeness] = null;
198
+ }
199
+ };
200
+ const ensureRegion = (politeness) => {
201
+ const existing = regions[politeness];
202
+ if (existing) {
203
+ return existing;
204
+ }
205
+ const span = doc.createElement('span');
206
+ span.setAttribute('aria-live', politeness);
207
+ span.setAttribute('aria-atomic', 'true');
208
+ span.className = 'cngx-sr-only';
209
+ span.style.position = 'absolute';
210
+ span.style.width = '1px';
211
+ span.style.height = '1px';
212
+ span.style.padding = '0';
213
+ span.style.margin = '-1px';
214
+ span.style.overflow = 'hidden';
215
+ span.style.clip = 'rect(0, 0, 0, 0)';
216
+ span.style.whiteSpace = 'nowrap';
217
+ span.style.border = '0';
218
+ container.appendChild(span);
219
+ regions[politeness] = span;
220
+ return span;
221
+ };
222
+ const cancel = (politeness) => {
223
+ const write = pending[politeness];
224
+ if (write) {
225
+ clearTimeout(write.timer);
226
+ pending[politeness] = null;
227
+ }
228
+ return write;
229
+ };
230
+ return {
231
+ announce(message, politeness, delayMs = CLEAR_DELAY_MS) {
232
+ const region = ensureRegion(politeness);
233
+ // Clear first, then write one frame later so repeating the same string
234
+ // still registers as a content change for the SR. Polite and assertive
235
+ // keep independent timers so one politeness never cancels the other.
236
+ region.textContent = '';
237
+ cancel(politeness);
238
+ cancelHold(politeness);
239
+ pending[politeness] = {
240
+ message,
241
+ timer: setTimeout(() => {
242
+ pending[politeness] = null;
243
+ if (redirect?.({ message, politeness })) {
244
+ return;
245
+ }
246
+ region.textContent = message;
247
+ holds[politeness] = setTimeout(() => {
248
+ holds[politeness] = null;
249
+ region.textContent = '';
250
+ }, HOLD_MS);
251
+ }, delayMs),
252
+ };
253
+ },
254
+ ensure() {
255
+ for (const politeness of POLITENESS) {
256
+ ensureRegion(politeness);
257
+ }
258
+ },
259
+ takePending() {
260
+ const taken = [];
261
+ for (const politeness of POLITENESS) {
262
+ const write = cancel(politeness);
263
+ if (write) {
264
+ taken.push({ message: write.message, politeness });
265
+ }
266
+ }
267
+ return taken;
268
+ },
269
+ destroy() {
270
+ for (const politeness of POLITENESS) {
271
+ cancel(politeness);
272
+ cancelHold(politeness);
273
+ regions[politeness]?.remove();
274
+ regions[politeness] = null;
275
+ }
276
+ },
277
+ };
278
+ }
279
+
280
+ // A screen reader commonly misses a change to a live region that entered the
281
+ // DOM a frame earlier. A modal pair is created on the announcement that needs
282
+ // it, so its first write waits until the regions have settled.
283
+ const FIRST_MODAL_WRITE_DELAY_MS = 100;
284
+ const MODAL_SELECTOR = '[aria-modal="true"]';
285
+ /** A modal container a screen reader currently reads. */
286
+ function isOpenModal(el) {
287
+ if (!el.isConnected || el.getAttribute('aria-modal') !== 'true') {
288
+ return false;
289
+ }
290
+ return !(el instanceof HTMLDialogElement) || el.open;
291
+ }
292
+ // Overlays such as CngxDialog are appended to the body, and a nested modal
293
+ // follows its container, so document order is stacking order: the last open
294
+ // modal outside an inert subtree is the one a screen reader still reads.
295
+ function topmostOpenModal(doc) {
296
+ const open = Array.from(doc.querySelectorAll(MODAL_SELECTOR)).filter((el) => isOpenModal(el) && !el.closest('[inert]'));
297
+ return open.at(-1) ?? null;
298
+ }
138
299
  /**
139
300
  * Imperative, reusable polite/assertive live-region announcer.
140
301
  *
@@ -146,11 +307,32 @@ const CLEAR_DELAY_MS = 16;
146
307
  * directives and event handlers (e.g. `CngxCopyValue` copy success,
147
308
  * `CngxOtpInput` completion).
148
309
  *
149
- * Each region is created lazily on the first announcement of its politeness and
150
- * reused thereafter. Because polite and assertive live in separate fixed-
151
- * politeness nodes, an assertive announcement never clobbers a concurrent
152
- * polite one. Per region, the text is cleared and re-set one frame later so an
153
- * identical consecutive message is still re-read by the screen reader.
310
+ * Both body regions are created when the service is created, so they are in
311
+ * the DOM before the first announcement (a screen reader commonly misses a
312
+ * change to a region inserted a frame earlier), and reused thereafter.
313
+ * Because polite and assertive live in separate fixed-politeness nodes, an
314
+ * assertive announcement never clobbers a concurrent polite one. Per region,
315
+ * the text is cleared and re-set one frame later so an identical consecutive
316
+ * message is still re-read by the screen reader. A written message is cleared
317
+ * again after 7 s, so no stale text stays in the region.
318
+ *
319
+ * A modal dialog hides everything outside it from assistive technology, so a
320
+ * body region is silent while one is open. Pass the announcing element as the
321
+ * third argument and the message goes to a region pair inside its enclosing
322
+ * `[aria-modal="true"]` container instead; without a modal ancestor it goes to
323
+ * the body regions as before. When another modal covers that one, the topmost
324
+ * open modal receives it: the last `[aria-modal="true"]` element in document
325
+ * order that is open and not inside an `[inert]` subtree. That covers a modal
326
+ * nested inside the scope's own one as well as a sibling stacked on top of it,
327
+ * which is how `CngxDialog` stacks dialogs (every host is appended to
328
+ * `document.body`); a covered modal is hidden from assistive technology, so
329
+ * its region would be silent. The pair is created with both regions on first
330
+ * use and its first write waits until the regions have settled in the DOM. A
331
+ * message still pending when its modal closes moves to the next enclosing open
332
+ * modal, else to the topmost modal still open, else to the body regions, and
333
+ * the pair is removed. The scope is opt-in per call - an unscoped announcement
334
+ * never guesses a modal. {@link injectScopedLiveRegion} is the injection-time
335
+ * alternative when the caller knows its overlay host up front.
154
336
  *
155
337
  * SSR-safe: all DOM access is guarded by `isPlatformBrowser`; on the server
156
338
  * `announce()` is a no-op and no region is created.
@@ -159,23 +341,31 @@ const CLEAR_DELAY_MS = 16;
159
341
  * const announcer = inject(CngxLiveAnnouncer);
160
342
  * announcer.announce('Copied');
161
343
  * announcer.announce('Save failed', 'assertive');
344
+ * announcer.announce('Alert dismissed', 'polite', hostElement); // inside a modal
162
345
  * ```
163
346
  *
164
- * @category common/a11y
165
347
  * @wcag AA
166
348
  * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/aria/live-announcer.ts
167
- * @since 0.1.0
349
+ * @since 0.3.0
168
350
  * @relatedTo CngxLiveRegion
351
+ * <example-url>/#/common/a11y/live-announcer/polite-vs-assertive</example-url>
169
352
  */
170
353
  class CngxLiveAnnouncer {
171
354
  doc = inject(DOCUMENT);
172
355
  isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
173
- politeRegion = null;
174
- assertiveRegion = null;
175
- pending = {
176
- polite: null,
177
- assertive: null,
178
- };
356
+ regions = null;
357
+ constructor() {
358
+ if (this.isBrowser) {
359
+ this.regions = createLiveRegionPair(this.doc.body, this.doc);
360
+ this.regions.ensure();
361
+ }
362
+ }
363
+ /**
364
+ * One pair per open `aria-modal` container, released once it closes.
365
+ * `outer` is the container's parent at creation, the route for its unwritten
366
+ * messages when it is removed from the DOM.
367
+ */
368
+ modalRegions = new Map();
179
369
  /**
180
370
  * Announces `message` through the fixed-politeness live region.
181
371
  *
@@ -183,64 +373,103 @@ class CngxLiveAnnouncer {
183
373
  * @param politeness `'polite'` (default) queues after the current
184
374
  * utterance; `'assertive'` interrupts immediately. Each politeness owns its
185
375
  * own region, so the two never overwrite each other.
376
+ * @param scope The announcing element. When it sits inside an
377
+ * `[aria-modal="true"]` container, the message is written into a region
378
+ * inside the topmost open modal (that container unless another modal
379
+ * covers it), which a screen reader still reads while the modal hides the
380
+ * rest of the page. `null` / omitted: the body regions.
186
381
  */
187
- announce(message, politeness = 'polite') {
382
+ announce(message, politeness = 'polite', scope) {
188
383
  if (!this.isBrowser) {
189
384
  return;
190
385
  }
191
- const region = this.ensureRegion(politeness);
192
- // Clear first, then write one frame later so repeating the same string
193
- // still registers as a content change for the SR. Polite and assertive
194
- // keep independent timers so one politeness never cancels the other.
195
- region.textContent = '';
196
- const existing = this.pending[politeness];
197
- if (existing !== null) {
198
- clearTimeout(existing);
199
- }
200
- this.pending[politeness] = setTimeout(() => {
201
- region.textContent = message;
202
- this.pending[politeness] = null;
203
- }, CLEAR_DELAY_MS);
386
+ this.releaseClosedModals();
387
+ this.route(scope, { message, politeness });
204
388
  }
205
389
  ngOnDestroy() {
206
- for (const politeness of ['polite', 'assertive']) {
207
- const timer = this.pending[politeness];
208
- if (timer !== null) {
209
- clearTimeout(timer);
210
- this.pending[politeness] = null;
211
- }
390
+ this.regions?.destroy();
391
+ this.regions = null;
392
+ for (const { pair } of this.modalRegions.values()) {
393
+ pair.destroy();
212
394
  }
213
- this.politeRegion?.remove();
214
- this.assertiveRegion?.remove();
215
- this.politeRegion = null;
216
- this.assertiveRegion = null;
395
+ this.modalRegions.clear();
217
396
  }
218
- ensureRegion(politeness) {
219
- const existing = politeness === 'polite' ? this.politeRegion : this.assertiveRegion;
397
+ /**
398
+ * `fromModal` marks a message that was already scoped to a modal which has
399
+ * since closed: with no open modal around its new scope it still goes to the
400
+ * topmost open modal rather than to the silent body regions.
401
+ */
402
+ route(scope, announcement, fromModal = false) {
403
+ const modal = this.targetModal(scope, fromModal);
404
+ if (!modal) {
405
+ this.regions ??= createLiveRegionPair(this.doc.body, this.doc);
406
+ this.regions.announce(announcement.message, announcement.politeness);
407
+ return;
408
+ }
409
+ const existing = this.modalRegions.get(modal);
220
410
  if (existing) {
221
- return existing;
411
+ existing.pair.announce(announcement.message, announcement.politeness);
412
+ return;
222
413
  }
223
- const span = this.doc.createElement('span');
224
- span.setAttribute('aria-live', politeness);
225
- span.setAttribute('aria-atomic', 'true');
226
- span.className = 'cngx-sr-only';
227
- span.style.position = 'absolute';
228
- span.style.width = '1px';
229
- span.style.height = '1px';
230
- span.style.padding = '0';
231
- span.style.margin = '-1px';
232
- span.style.overflow = 'hidden';
233
- span.style.clip = 'rect(0, 0, 0, 0)';
234
- span.style.whiteSpace = 'nowrap';
235
- span.style.border = '0';
236
- this.doc.body.appendChild(span);
237
- if (politeness === 'polite') {
238
- this.politeRegion = span;
414
+ const pair = createLiveRegionPair(modal, this.doc, (due) => this.redirectIfClosed(modal, due));
415
+ pair.ensure();
416
+ this.modalRegions.set(modal, { pair, outer: modal.parentElement });
417
+ pair.announce(announcement.message, announcement.politeness, FIRST_MODAL_WRITE_DELAY_MS);
418
+ }
419
+ /**
420
+ * The topmost open modal when `scope` sits in an open modal (or the message
421
+ * comes from a closed one), else `null` for the body regions. Falls back to
422
+ * the scope's own modal when no candidate outside an inert subtree is open.
423
+ */
424
+ targetModal(scope, fromModal) {
425
+ const own = this.enclosingOpenModal(scope);
426
+ if (!own && !fromModal) {
427
+ return null;
239
428
  }
240
- else {
241
- this.assertiveRegion = span;
429
+ return topmostOpenModal(this.doc) ?? own;
430
+ }
431
+ enclosingOpenModal(scope) {
432
+ let candidate = scope?.closest(MODAL_SELECTOR) ?? null;
433
+ while (candidate) {
434
+ if (candidate instanceof HTMLElement && isOpenModal(candidate)) {
435
+ return candidate;
436
+ }
437
+ candidate = candidate.parentElement?.closest(MODAL_SELECTOR) ?? null;
242
438
  }
243
- return span;
439
+ return null;
440
+ }
441
+ redirectIfClosed(modal, due) {
442
+ if (isOpenModal(modal)) {
443
+ return false;
444
+ }
445
+ const outer = this.outerOf(modal);
446
+ this.release(modal);
447
+ this.route(outer, due, true);
448
+ return true;
449
+ }
450
+ releaseClosedModals() {
451
+ for (const modal of Array.from(this.modalRegions.keys())) {
452
+ if (!isOpenModal(modal)) {
453
+ this.release(modal);
454
+ }
455
+ }
456
+ }
457
+ /** Drop the pair of a closed modal; its unwritten messages move outward. */
458
+ release(modal) {
459
+ const entry = this.modalRegions.get(modal);
460
+ if (!entry) {
461
+ return;
462
+ }
463
+ const outer = this.outerOf(modal);
464
+ this.modalRegions.delete(modal);
465
+ const unwritten = entry.pair.takePending();
466
+ entry.pair.destroy();
467
+ for (const announcement of unwritten) {
468
+ this.route(outer, announcement, true);
469
+ }
470
+ }
471
+ outerOf(modal) {
472
+ return modal.parentElement ?? this.modalRegions.get(modal)?.outer ?? null;
244
473
  }
245
474
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxLiveAnnouncer, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
246
475
  static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxLiveAnnouncer, providedIn: 'root' });
@@ -248,7 +477,77 @@ class CngxLiveAnnouncer {
248
477
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxLiveAnnouncer, decorators: [{
249
478
  type: Injectable,
250
479
  args: [{ providedIn: 'root' }]
251
- }] });
480
+ }], ctorParameters: () => [] });
481
+
482
+ /**
483
+ * Create a polite + assertive live-region pair inside `host`.
484
+ *
485
+ * The scoped counterpart to {@link CngxLiveAnnouncer}: same regions, same
486
+ * clear-then-set timing, but appended to an overlay host instead of
487
+ * `document.body`. Use it for modal overlays: under `aria-modal` VoiceOver
488
+ * drops body-level live regions and speaks them late after the overlay
489
+ * closes, while a region inside the modal is spoken on every platform.
490
+ * Polite and assertive keep separate regions, so an assertive error never
491
+ * clobbers a polite status.
492
+ *
493
+ * Must run in an injection context; the regions are removed when that context
494
+ * is destroyed, and later calls are no-ops. No-op on the server.
495
+ *
496
+ * ```typescript
497
+ * private readonly region = injectScopedLiveRegion(inject(ElementRef).nativeElement);
498
+ *
499
+ * protected handleSaveFailed(): void {
500
+ * this.region.announce('Save failed', 'assertive');
501
+ * }
502
+ * ```
503
+ *
504
+ * @param host - Element that receives the two visually hidden regions.
505
+ *
506
+ * @wcag AA
507
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/aria/scoped-live-region.ts
508
+ * @since 0.3.0
509
+ * @relatedTo CngxLiveAnnouncer, CngxLiveRegion
510
+ * <example-url>/#/common/a11y/live-announcer/scoped-announcing-in-a-modal</example-url>
511
+ */
512
+ function injectScopedLiveRegion(host) {
513
+ const doc = inject(DOCUMENT);
514
+ const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
515
+ let pair = null;
516
+ // A manual destroy() may be followed by a new ensure() (an overlay that
517
+ // reopens); a destroyed host never takes regions again.
518
+ let hostDestroyed = false;
519
+ const usable = () => isBrowser && !hostDestroyed;
520
+ const ensurePair = () => {
521
+ pair ??= createLiveRegionPair(host, doc);
522
+ return pair;
523
+ };
524
+ const region = {
525
+ announce(message, politeness = 'polite') {
526
+ if (!usable()) {
527
+ return;
528
+ }
529
+ ensurePair().announce(message, politeness);
530
+ },
531
+ ensure() {
532
+ if (!usable()) {
533
+ return;
534
+ }
535
+ ensurePair().ensure();
536
+ },
537
+ takePending() {
538
+ return pair?.takePending() ?? [];
539
+ },
540
+ destroy() {
541
+ pair?.destroy();
542
+ pair = null;
543
+ },
544
+ };
545
+ inject(DestroyRef).onDestroy(() => {
546
+ hostDestroyed = true;
547
+ region.destroy();
548
+ });
549
+ return region;
550
+ }
252
551
 
253
552
  /**
254
553
  * Reactive autofocus for dynamically inserted elements.
@@ -277,17 +576,18 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
277
576
  * <input cngxAutofocus [autofocusDelay]="200" />
278
577
  * ```
279
578
  *
280
- * @category common/a11y
281
579
  * @wcag AA
282
580
  * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/focus/autofocus.directive.ts
283
- * @since 0.1.0
581
+ * @since 0.3.0
284
582
  * @relatedTo CngxFocusRestore, CngxFocusTrap, CngxFocusVisible
285
- * <example-url>http://localhost:4200/#/common/a11y/autofocus/conditional-focus</example-url>
286
- * <example-url>http://localhost:4200/#/common/a11y/autofocus/focus-on-insert</example-url>
583
+ * <example-url>/#/common/a11y/autofocus/conditional-focus</example-url>
584
+ * <example-url>/#/common/a11y/autofocus/focus-on-insert</example-url>
585
+ * @axis level atom
287
586
  */
288
587
  class CngxAutofocus {
289
588
  /** Whether to focus the element. Defaults to `true` (always focus on render). */
290
- when = input(true, { ...(ngDevMode ? { debugName: "when" } : /* istanbul ignore next */ {}), alias: 'cngxAutofocus' });
589
+ when = input(true, { ...(ngDevMode ? { debugName: "when" } : /* istanbul ignore next */ {}), alias: 'cngxAutofocus',
590
+ transform: booleanAttribute });
291
591
  /** Delay in ms before focusing - useful when the element appears during a transition. */
292
592
  delay = input(0, { ...(ngDevMode ? { debugName: "delay" } : /* istanbul ignore next */ {}), alias: 'autofocusDelay' });
293
593
  /** `FocusOptions` passed to `element.focus()`. */
@@ -355,27 +655,40 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
355
655
 
356
656
  /**
357
657
  * CSS selector matching natively-focusable elements: links with an
358
- * `href`, the enabled form controls, and anything with an explicit
359
- * non-negative `tabindex`. Form controls carry `:not(:disabled)` because
360
- * a disabled control is not in the tab order - without it a descendant
361
- * probe would count a disabled button as focusable and a restore target
362
- * could land on an unfocusable element. Single source of truth for "is
363
- * this focusable" - the element-level {@link CngxFocusRestore} predicate
364
- * matches against it, and descendant probes (e.g. "does this panel
365
- * contain a focusable child?") query against it. Keeping one selector
366
- * stops the two uses from drifting apart.
367
- *
368
- * @category common/a11y
369
- * @since 0.1.0
658
+ * `href`, the enabled form controls, the summary of a `<details>`,
659
+ * editable content, and anything with an explicit non-negative `tabindex`.
660
+ * Form controls carry `:not(:disabled)` because a disabled control is not in
661
+ * the tab order - without it a descendant probe would count a disabled button
662
+ * as focusable and a restore target could land on an unfocusable element.
663
+ * Single source of truth for "is this focusable" - the element-level
664
+ * {@link CngxFocusRestore} predicate matches against it, and descendant probes
665
+ * (e.g. "does this panel contain a focusable child?") query against it.
666
+ * Keeping one selector stops the two uses from drifting apart.
667
+ *
668
+ * @since 0.3.0
669
+ */
670
+ const CNGX_FOCUSABLE_SELECTOR = 'a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), details > summary:first-of-type, [contenteditable]:not([contenteditable="false"]), [tabindex]:not([tabindex="-1"])';
671
+ /**
672
+ * Injection token for a {@link CngxFocusRestoreDriver}. A composer provides it
673
+ * on its own element (`useExisting`) to override `[cngxFocusRestoreWhile]`
674
+ * and `[fallback]` of its `CngxFocusRestore` host directive. Used by
675
+ * `CngxDrawerSurface`.
676
+ *
677
+ * @relatedTo CngxFocusRestore
678
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/focus/focus-restore.directive.ts
679
+ * @since 0.3.0
370
680
  */
371
- const CNGX_FOCUSABLE_SELECTOR = 'a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';
681
+ const CNGX_FOCUS_RESTORE_DRIVER = new InjectionToken('CngxFocusRestoreDriver');
372
682
  /**
373
- * Stores the previously focused element and restores focus on destroy.
683
+ * Stores the previously focused element and restores focus on destroy, or on
684
+ * the falling edge of `[cngxFocusRestoreWhile]` for a surface that stays in
685
+ * the DOM while closed.
374
686
  *
375
687
  * Prevents focus from falling to `<body>` when dynamic content is removed
376
688
  * (dialogs closing, panels collapsing, tabs switching). The directive captures
377
689
  * `document.activeElement` at initialization time and restores it when the
378
- * host element is destroyed.
690
+ * host element is destroyed while focus is inside it or has dropped to
691
+ * `<body>`. Focus the user moved elsewhere before the destroy stays put.
379
692
  *
380
693
  * Fallback chain: stored element → provided fallback → nearest focusable ancestor.
381
694
  * When none resolves, focus is left where the browser put it - `<body>` is
@@ -391,50 +704,102 @@ const CNGX_FOCUSABLE_SELECTOR = 'a[href], button:not(:disabled), input:not(:disa
391
704
  * }
392
705
  * ```
393
706
  *
707
+ * ### Persistent surface (drawer, sidebar overlay)
708
+ * ```html
709
+ * <aside cngxFocusRestore [cngxFocusRestoreWhile]="open()">…</aside>
710
+ * ```
711
+ * `true` captures the focused element, `false` restores it when focus is
712
+ * still inside the host or has dropped to `<body>`. Focus the user moved
713
+ * elsewhere in the meantime stays where it is. A target that is still
714
+ * `inert` at the falling edge (a backdrop released in the same pass) is
715
+ * focused after the next render instead.
716
+ *
394
717
  * ### With explicit fallback
395
718
  * ```html
396
- * <div cngxFocusRestore [focusRestoreFallback]="fallbackBtn">
719
+ * <div cngxFocusRestore [fallback]="fallbackBtn">
397
720
  * Dynamic content…
398
721
  * </div>
399
722
  * <button #fallbackBtn>Fallback target</button>
400
723
  * ```
401
724
  *
402
- * @category common/a11y
403
725
  * @wcag AA
404
726
  * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/focus/focus-restore.directive.ts
405
- * @since 0.1.0
727
+ * @since 0.3.0
406
728
  * @relatedTo CngxAutofocus, CngxFocusTrap, CngxFocusVisible
407
- * <example-url>http://localhost:4200/#/common/a11y/focus-restore/inline-details</example-url>
408
- * <example-url>http://localhost:4200/#/common/a11y/focus-restore/panel-with-automatic-restore</example-url>
729
+ * <example-url>/#/common/a11y/focus-restore/inline-details</example-url>
730
+ * <example-url>/#/common/a11y/focus-restore/panel-with-automatic-restore</example-url>
731
+ * <example-url>/#/common/a11y/focus-restore/persistent-panel-restore-while-open</example-url>
732
+ * @axis level atom
409
733
  */
410
734
  class CngxFocusRestore {
411
- /** Whether to restore focus when the host element is destroyed. */
735
+ /**
736
+ * Whether to restore focus when the host element is destroyed. Applies only
737
+ * when focus is inside the host or on `<body>` at that moment.
738
+ */
412
739
  restoreOnDestroy = input(true, ...(ngDevMode ? [{ debugName: "restoreOnDestroy" }] : /* istanbul ignore next */ []));
413
740
  /** Explicit fallback element if the stored element is no longer in the DOM. */
414
741
  fallback = input(null, ...(ngDevMode ? [{ debugName: "fallback" }] : /* istanbul ignore next */ []));
742
+ /**
743
+ * Bind to the open state of a surface that stays in the DOM while closed.
744
+ * The `false -> true` edge captures the focused element, the
745
+ * `true -> false` edge restores it when focus is inside the host or on
746
+ * `<body>`. While bound, destroying the host restores only when it is
747
+ * engaged. Unbound (`undefined`), only destroy and the manual
748
+ * `capture()` / `restore()` apply.
749
+ */
750
+ whileActive = input(undefined, { ...(ngDevMode ? { debugName: "whileActive" } : /* istanbul ignore next */ {}), alias: 'cngxFocusRestoreWhile' });
415
751
  doc = inject(DOCUMENT);
416
752
  el = inject((ElementRef));
417
- storedElement = signal(null, ...(ngDevMode ? [{ debugName: "storedElement" }] : /* istanbul ignore next */ []));
753
+ injector = inject(Injector);
754
+ // Read only inside the restore paths (untracked edge, destroy, manual
755
+ // restore()); nothing derives from it, so it is not a signal.
756
+ storedElement = null;
757
+ // The host is already detached when DestroyRef fires, so the ancestor
758
+ // walk starts from the parent recorded while it was still attached.
759
+ lastParent = null;
760
+ resolvedDriver = undefined;
761
+ driver() {
762
+ if (this.resolvedDriver === undefined) {
763
+ this.resolvedDriver = this.injector.get(CNGX_FOCUS_RESTORE_DRIVER, null, { self: true });
764
+ }
765
+ return this.resolvedDriver;
766
+ }
767
+ engaged = computed(() => this.driver()?.focusRestoreActive() ?? this.whileActive() === true, ...(ngDevMode ? [{ debugName: "engaged" }] : /* istanbul ignore next */ []));
768
+ engagement = createTransitionTracker(() => this.engaged());
418
769
  constructor() {
419
770
  const activeEl = this.doc.activeElement;
420
771
  if (activeEl instanceof HTMLElement) {
421
- this.storedElement.set(activeEl);
772
+ this.storedElement = activeEl;
422
773
  }
774
+ afterNextRender({ read: () => (this.lastParent = this.host().parentElement) });
775
+ effect(() => {
776
+ const current = this.engagement.current();
777
+ if (current === this.engagement.previous()) {
778
+ return;
779
+ }
780
+ untracked(() => (current ? this.captureOutside() : this.restoreIfFocusInside()));
781
+ });
423
782
  inject(DestroyRef).onDestroy(() => {
424
783
  if (!this.restoreOnDestroy()) {
425
784
  return;
426
785
  }
427
- const target = this.resolveTarget();
428
- if (target) {
429
- target.focus();
786
+ // A closed edge-driven surface already restored (or never captured);
787
+ // tearing it down must not pull focus from wherever the user is.
788
+ if (this.edgeDriven() && !untracked(this.engaged)) {
789
+ return;
790
+ }
791
+ // Focus the user moved elsewhere in the meantime stays where it is.
792
+ if (!this.focusLost()) {
793
+ return;
430
794
  }
795
+ this.resolveTarget()?.focus();
431
796
  });
432
797
  }
433
798
  /** Manually store the current focus target for later restoration. */
434
799
  capture() {
435
800
  const activeEl = this.doc.activeElement;
436
801
  if (activeEl instanceof HTMLElement) {
437
- this.storedElement.set(activeEl);
802
+ this.storedElement = activeEl;
438
803
  }
439
804
  }
440
805
  /** Manually restore focus to the stored element. */
@@ -444,22 +809,66 @@ class CngxFocusRestore {
444
809
  target.focus();
445
810
  }
446
811
  }
812
+ edgeDriven() {
813
+ return this.driver() !== null || untracked(this.whileActive) !== undefined;
814
+ }
815
+ // A composer's trap can move focus inside before this edge runs; the
816
+ // element inside is never the one to return to.
817
+ captureOutside() {
818
+ const activeEl = this.doc.activeElement;
819
+ if (activeEl instanceof HTMLElement && !this.host().contains(activeEl)) {
820
+ this.storedElement = activeEl;
821
+ }
822
+ }
823
+ restoreIfFocusInside() {
824
+ if (!this.focusLost()) {
825
+ return;
826
+ }
827
+ const target = this.resolveTarget();
828
+ if (!target) {
829
+ return;
830
+ }
831
+ if (!target.closest('[inert]')) {
832
+ target.focus();
833
+ return;
834
+ }
835
+ // Another owner (a backdrop) can still hold `inert` on the target in
836
+ // this pass; focus() on an inert element is a no-op. Its release runs in
837
+ // the same change detection, so retry once after the render.
838
+ afterNextRender(() => {
839
+ if (this.focusLost() && !target.closest('[inert]')) {
840
+ target.focus();
841
+ }
842
+ }, { injector: this.injector });
843
+ }
844
+ // A detached host still contains the element that had focus in it, so the
845
+ // check also holds on destroy, where the browser may report either that
846
+ // element or `<body>`.
847
+ focusLost() {
848
+ const activeEl = this.doc.activeElement;
849
+ return !activeEl || activeEl === this.doc.body || this.host().contains(activeEl);
850
+ }
851
+ host() {
852
+ return this.el.nativeElement;
853
+ }
447
854
  /**
448
855
  * Walks the fallback chain:
449
856
  * 1. Stored element (if still in DOM and not body/self)
450
- * 2. Explicit fallback input
857
+ * 2. The driver's fallback, else the explicit fallback input
451
858
  * 3. Nearest focusable ancestor
452
859
  */
453
860
  resolveTarget() {
454
- const stored = this.storedElement();
455
- // Skip body - it signals "nothing meaningful was focused", not a real restore target.
861
+ const stored = this.storedElement;
862
+ // Skip body - it signals "nothing meaningful was focused", not a real
863
+ // restore target - and anything inside the host, which is the focus
864
+ // being restored away from (engaged while focus was already inside).
456
865
  if (stored &&
457
866
  stored !== this.doc.body &&
458
867
  this.doc.contains(stored) &&
459
- stored !== this.el.nativeElement) {
868
+ !this.host().contains(stored)) {
460
869
  return stored;
461
870
  }
462
- const fallback = this.fallback();
871
+ const fallback = this.driver()?.focusRestoreFallback?.() ?? this.fallback();
463
872
  if (fallback && this.doc.contains(fallback)) {
464
873
  return fallback;
465
874
  }
@@ -467,7 +876,7 @@ class CngxFocusRestore {
467
876
  }
468
877
  /** Traverses up the DOM tree looking for the first natively focusable element. */
469
878
  findFocusableAncestor() {
470
- let current = this.el.nativeElement.parentElement;
879
+ let current = this.host().parentElement ?? this.lastParent;
471
880
  while (current) {
472
881
  if (this.isFocusable(current)) {
473
882
  return current;
@@ -486,7 +895,7 @@ class CngxFocusRestore {
486
895
  return el.matches(CNGX_FOCUSABLE_SELECTOR);
487
896
  }
488
897
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFocusRestore, deps: [], target: i0.ɵɵFactoryTarget.Directive });
489
- 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 });
898
+ 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 }, whileActive: { classPropertyName: "whileActive", publicName: "cngxFocusRestoreWhile", isSignal: true, isRequired: false, transformFunction: null } }, exportAs: ["cngxFocusRestore"], ngImport: i0 });
490
899
  }
491
900
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFocusRestore, decorators: [{
492
901
  type: Directive,
@@ -495,8 +904,19 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
495
904
  exportAs: 'cngxFocusRestore',
496
905
  standalone: true,
497
906
  }]
498
- }], ctorParameters: () => [], propDecorators: { restoreOnDestroy: [{ type: i0.Input, args: [{ isSignal: true, alias: "restoreOnDestroy", required: false }] }], fallback: [{ type: i0.Input, args: [{ isSignal: true, alias: "fallback", required: false }] }] } });
907
+ }], ctorParameters: () => [], propDecorators: { restoreOnDestroy: [{ type: i0.Input, args: [{ isSignal: true, alias: "restoreOnDestroy", required: false }] }], fallback: [{ type: i0.Input, args: [{ isSignal: true, alias: "fallback", required: false }] }], whileActive: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxFocusRestoreWhile", required: false }] }] } });
499
908
 
909
+ /**
910
+ * Injection token for a {@link CngxFocusTrapDriver}. A composer provides it on
911
+ * its own element (`useExisting`) to override `[enabled]` and `[autoFocus]` of
912
+ * its `CngxFocusTrap` host directive. Used by `CngxDrawerSurface` and
913
+ * `CngxPopoverSheet`.
914
+ *
915
+ * @relatedTo CngxFocusTrap
916
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/focus/focus-trap.directive.ts
917
+ * @since 0.3.0
918
+ */
919
+ const CNGX_FOCUS_TRAP_DRIVER = new InjectionToken('CngxFocusTrapDriver');
500
920
  /**
501
921
  * Traps keyboard focus within the host element using the CDK `FocusTrap`.
502
922
  *
@@ -531,51 +951,85 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
531
951
  * </nav>
532
952
  * ```
533
953
  *
534
- * @category common/a11y
535
- * @docsKind primary
536
954
  * @wcag AA
537
955
  * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/focus/focus-trap.directive.ts
538
- * @since 0.1.0
956
+ * @since 0.3.0
539
957
  * @relatedTo CngxAutofocus, CngxFocusRestore, CngxDialog
540
- * <example-url>http://localhost:4200/#/common/a11y/focus-trap/modal-dialog</example-url>
541
- * <example-url>http://localhost:4200/#/common/a11y/focus-trap/slide-out-drawer</example-url>
958
+ * <example-url>/#/common/a11y/focus-trap/modal-dialog</example-url>
959
+ * <example-url>/#/common/a11y/focus-trap/slide-out-drawer</example-url>
960
+ * @axis level atom
542
961
  */
543
962
  class CngxFocusTrap {
544
963
  /** Whether the focus trap is active. When `false`, Tab navigates normally. */
545
964
  enabled = input(false, ...(ngDevMode ? [{ debugName: "enabled" }] : /* istanbul ignore next */ []));
546
965
  /** Whether to auto-focus the first tabbable element when the trap activates. */
547
966
  autoFocus = input(true, ...(ngDevMode ? [{ debugName: "autoFocus" }] : /* istanbul ignore next */ []));
967
+ injector = inject(Injector);
968
+ resolvedDriver = undefined;
969
+ driver() {
970
+ if (this.resolvedDriver === undefined) {
971
+ this.resolvedDriver = this.injector.get(CNGX_FOCUS_TRAP_DRIVER, null, { self: true });
972
+ }
973
+ return this.resolvedDriver;
974
+ }
975
+ /**
976
+ * The enabled state the trap actually follows: a composer's driver
977
+ * (see {@link CngxFocusTrapDriver}) wins over the `[enabled]` input.
978
+ */
979
+ effectiveEnabled = computed(() => this.driver()?.focusTrapEnabled() ?? this.enabled(), ...(ngDevMode ? [{ debugName: "effectiveEnabled" }] : /* istanbul ignore next */ []));
548
980
  /**
549
- * Readable alias of `enabled` for `exportAs` consumers
981
+ * Readable alias of the effective enabled state for `exportAs` consumers
550
982
  * (`trap.isActive()` reads better than re-binding the input).
551
983
  */
552
- isActive = computed(() => this.enabled(), ...(ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []));
553
- trap;
984
+ isActive = computed(() => this.effectiveEnabled(), ...(ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []));
985
+ host = inject(ElementRef).nativeElement;
986
+ factory = inject(FocusTrapFactory);
987
+ trap = null;
554
988
  constructor() {
555
- const el = inject((ElementRef));
556
- this.trap = inject(FocusTrapFactory).create(el.nativeElement);
557
- // Track ONLY enabled: with autoFocus inside the tracked zone, flipping
558
- // [autoFocus] while the trap is active would re-run the effect and yank
559
- // focus back to the first tabbable element. The CDK calls are service
560
- // work, not dependencies.
989
+ // Track ONLY the effective enabled state: with autoFocus inside the
990
+ // tracked zone, flipping [autoFocus] while the trap is active would
991
+ // re-run the effect and yank focus back to the first tabbable element.
992
+ // The CDK calls are service work, not dependencies.
561
993
  effect(() => {
562
- const enabled = this.enabled();
994
+ const enabled = this.effectiveEnabled();
563
995
  untracked(() => {
564
- this.trap.enabled = enabled;
565
- if (enabled && this.autoFocus()) {
566
- void this.trap.focusFirstTabbableElementWhenReady();
996
+ if (!enabled && !this.trap) {
997
+ return;
998
+ }
999
+ const trap = this.ensureTrap();
1000
+ trap.enabled = enabled;
1001
+ if (enabled && !trap.hasAttached()) {
1002
+ trap.attachAnchors();
1003
+ }
1004
+ if (enabled && (this.driver()?.focusTrapAutoFocus ?? this.autoFocus())) {
1005
+ void trap.focusFirstTabbableElementWhenReady();
567
1006
  }
568
1007
  });
569
1008
  });
570
- inject(DestroyRef).onDestroy(() => this.trap.destroy());
1009
+ inject(DestroyRef).onDestroy(() => this.trap?.destroy());
571
1010
  }
572
1011
  /** Programmatically focus the first tabbable element within the trap. */
573
1012
  focusFirst() {
574
- void this.trap.focusFirstTabbableElementWhenReady();
1013
+ void this.ensureTrap().focusFirstTabbableElementWhenReady();
575
1014
  }
576
1015
  /** Programmatically focus the last tabbable element within the trap. */
577
1016
  focusLast() {
578
- void this.trap.focusLastTabbableElementWhenReady();
1017
+ void this.ensureTrap().focusLastTabbableElementWhenReady();
1018
+ }
1019
+ /**
1020
+ * @internal Focus the first tabbable element right now, in the caller's
1021
+ * stack. `focusFirst()` waits for the next render, which is too late for a
1022
+ * composer that must move focus inside the user gesture that opened it.
1023
+ * Returns `false` when nothing inside is tabbable.
1024
+ */
1025
+ focusFirstNow() {
1026
+ return this.ensureTrap().focusFirstTabbableElement();
1027
+ }
1028
+ // Deferred anchors: the CDK sentinels are inserted on the first enable,
1029
+ // so a trap that is never enabled leaves the DOM untouched.
1030
+ ensureTrap() {
1031
+ this.trap ??= this.factory.create(this.host, true);
1032
+ return this.trap;
579
1033
  }
580
1034
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFocusTrap, deps: [], target: i0.ɵɵFactoryTarget.Directive });
581
1035
  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 });
@@ -602,13 +1056,13 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
602
1056
  * </button>
603
1057
  * ```
604
1058
  *
605
- * @category common/a11y
606
1059
  * @wcag AA
607
1060
  * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/focus/focus-visible.directive.ts
608
- * @since 0.1.0
1061
+ * @since 0.3.0
609
1062
  * @relatedTo CngxAutofocus, CngxFocusRestore, CngxFocusTrap
610
- * <example-url>http://localhost:4200/#/common/a11y/focus-visible/form-fields-custom-focus-ring</example-url>
611
- * <example-url>http://localhost:4200/#/common/a11y/focus-visible/keyboard-vs-pointer</example-url>
1063
+ * <example-url>/#/common/a11y/focus-visible/form-fields-custom-focus-ring</example-url>
1064
+ * <example-url>/#/common/a11y/focus-visible/keyboard-vs-pointer</example-url>
1065
+ * @axis level atom
612
1066
  */
613
1067
  class CngxFocusVisible {
614
1068
  doc = inject(DOCUMENT);
@@ -617,6 +1071,12 @@ class CngxFocusVisible {
617
1071
  focusVisible = this.focusVisibleState.asReadonly();
618
1072
  pointerActive = false;
619
1073
  pointerClearTimer = null;
1074
+ // pointercancel (touch scroll start, OS gesture) ends a press without a
1075
+ // pointerup; either release clears the flag and drops both listeners.
1076
+ releasePointer = () => {
1077
+ this.removeReleaseListeners();
1078
+ this.schedulePointerClear();
1079
+ };
620
1080
  schedulePointerClear = () => {
621
1081
  // One macrotask of grace: on touch, the compat mousedown and the focusin
622
1082
  // fire AFTER pointerup, so a synchronous clear here would misread a tap
@@ -632,7 +1092,7 @@ class CngxFocusVisible {
632
1092
  };
633
1093
  constructor() {
634
1094
  inject(DestroyRef).onDestroy(() => {
635
- this.doc.removeEventListener('pointerup', this.schedulePointerClear, true);
1095
+ this.removeReleaseListeners();
636
1096
  if (this.pointerClearTimer !== null) {
637
1097
  clearTimeout(this.pointerClearTimer);
638
1098
  }
@@ -650,10 +1110,12 @@ class CngxFocusVisible {
650
1110
  // (disabled child, text selection, drag released off-host) would
651
1111
  // otherwise suppress the ring on the NEXT keyboard Tab-in. Document-level
652
1112
  // capture catches the release wherever it lands.
653
- this.doc.addEventListener('pointerup', this.schedulePointerClear, {
654
- once: true,
655
- capture: true,
656
- });
1113
+ this.doc.addEventListener('pointerup', this.releasePointer, true);
1114
+ this.doc.addEventListener('pointercancel', this.releasePointer, true);
1115
+ }
1116
+ removeReleaseListeners() {
1117
+ this.doc.removeEventListener('pointerup', this.releasePointer, true);
1118
+ this.doc.removeEventListener('pointercancel', this.releasePointer, true);
657
1119
  }
658
1120
  /** @internal Sets focus-visible state; clears pointer flag. */
659
1121
  handleFocus() {
@@ -682,6 +1144,27 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
682
1144
  }]
683
1145
  }], ctorParameters: () => [] });
684
1146
 
1147
+ /**
1148
+ * Widgets whose arrow keys are their own. A key from inside one that sits in
1149
+ * the roving group (a slider in a toolbar item, a nested listbox) belongs to
1150
+ * it, not to the group.
1151
+ */
1152
+ const ARROW_KEY_WIDGETS = [
1153
+ 'input[type="range"]',
1154
+ '[role="slider"]',
1155
+ '[role="spinbutton"]',
1156
+ '[role="scrollbar"]',
1157
+ '[role="combobox"]',
1158
+ '[role="listbox"]',
1159
+ '[role="tree"]',
1160
+ '[role="treegrid"]',
1161
+ '[role="grid"]',
1162
+ '[role="menu"]',
1163
+ '[role="menubar"]',
1164
+ '[role="tablist"]',
1165
+ '[role="radiogroup"]',
1166
+ '[role="toolbar"]',
1167
+ ].join(', ');
685
1168
  /**
686
1169
  * Marker directive for items managed by `CngxRovingTabindex`.
687
1170
  *
@@ -697,13 +1180,12 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
697
1180
  * </div>
698
1181
  * ```
699
1182
  *
700
- * @category common/a11y
701
1183
  * @wcag AA
702
1184
  * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/roving/roving-tabindex.directive.ts
703
- * @since 0.1.0
1185
+ * @since 0.3.0
704
1186
  * @relatedTo CngxRovingTabindex, CngxButtonToggle
705
- * <example-url>http://localhost:4200/#/common/a11y/roving-tabindex/horizontal-toolbar</example-url>
706
- * <example-url>http://localhost:4200/#/common/a11y/roving-tabindex/vertical-menu</example-url>
1187
+ * <example-url>/#/common/a11y/roving-tabindex/horizontal-toolbar</example-url>
1188
+ * <example-url>/#/common/a11y/roving-tabindex/vertical-menu</example-url>
707
1189
  */
708
1190
  class CngxRovingItem {
709
1191
  /** @internal Reference used by the parent `CngxRovingTabindex` to set `tabindex`. */
@@ -735,6 +1217,17 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
735
1217
  * Works for toolbars, tab lists, card grids, menu bars, and any composite
736
1218
  * widget where only one item should be in the tab order at a time.
737
1219
  *
1220
+ * ### Keys the group leaves alone
1221
+ *
1222
+ * A key from a text field (an `<input>` item, a field inside an item), a key
1223
+ * of an IME composition, and an arrow from inside a nested widget that owns
1224
+ * its arrows (a range input or an element with a slider, spinbutton,
1225
+ * scrollbar, combobox, listbox, tree, treegrid, grid, menu, menubar,
1226
+ * tablist, radiogroup or toolbar role)
1227
+ * stays with that element. A custom widget without one of those roles keeps
1228
+ * its arrows by calling `preventDefault()` on the keys it handles: the group
1229
+ * skips every key that arrives already handled.
1230
+ *
738
1231
  * ### Virtual mode
739
1232
  *
740
1233
  * When `virtualCount` is set, `activeIndex` ranges from 0 to `virtualCount - 1`
@@ -772,14 +1265,13 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
772
1265
  * </div>
773
1266
  * ```
774
1267
  *
775
- * @category common/a11y
776
- * @docsKind primary
777
1268
  * @wcag AA
778
1269
  * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/roving/roving-tabindex.directive.ts
779
- * @since 0.1.0
1270
+ * @since 0.3.0
780
1271
  * @relatedTo CngxRovingItem, CngxActiveDescendant
781
- * <example-url>http://localhost:4200/#/common/a11y/roving-tabindex/horizontal-toolbar</example-url>
782
- * <example-url>http://localhost:4200/#/common/a11y/roving-tabindex/vertical-menu</example-url>
1272
+ * <example-url>/#/common/a11y/roving-tabindex/horizontal-toolbar</example-url>
1273
+ * <example-url>/#/common/a11y/roving-tabindex/vertical-menu</example-url>
1274
+ * @axis level atom
783
1275
  */
784
1276
  class CngxRovingTabindex {
785
1277
  /**
@@ -802,8 +1294,15 @@ class CngxRovingTabindex {
802
1294
  virtualCount = input(undefined, ...(ngDevMode ? [{ debugName: "virtualCount" }] : /* istanbul ignore next */ []));
803
1295
  /** All `CngxRovingItem` children discovered via `contentChildren`. */
804
1296
  items = contentChildren(CngxRovingItem, ...(ngDevMode ? [{ debugName: "items" }] : /* istanbul ignore next */ []));
805
- /** Guards against setting `tabindex` before the DOM is ready. */
806
- initialized = signal(false, ...(ngDevMode ? [{ debugName: "initialized" }] : /* istanbul ignore next */ []));
1297
+ /**
1298
+ * Flips after the first browser render. Virtual mode waits for it: it reads
1299
+ * the `data-cngx-recycle-index` attributes, which the item bindings write
1300
+ * during that render. Standard mode writes before it (so a server render
1301
+ * carries the tab stops) and once more after it, because an item's own
1302
+ * `[attr.tabindex]` binding (null under a roving parent) clears the
1303
+ * attribute during that render.
1304
+ */
1305
+ rendered = signal(false, ...(ngDevMode ? [{ debugName: "rendered" }] : /* istanbul ignore next */ []));
807
1306
  /** Host element for `data-cngx-recycle-index` queries in virtual mode. */
808
1307
  hostEl = inject((ElementRef));
809
1308
  pendingFocusState = signal(null, ...(ngDevMode ? [{ debugName: "pendingFocusState" }] : /* istanbul ignore next */ []));
@@ -823,15 +1322,20 @@ class CngxRovingTabindex {
823
1322
  */
824
1323
  pendingFocus = this.pendingFocusState.asReadonly();
825
1324
  constructor() {
826
- afterNextRender(() => this.initialized.set(true));
1325
+ // The item list and the index the last run settled on: a list change with
1326
+ // an unchanged index re-finds the item that held the tab stop.
1327
+ let previousItems = [];
1328
+ let previousActive = -1;
1329
+ afterNextRender(() => this.rendered.set(true));
827
1330
  effect(() => {
828
- if (!this.initialized()) {
829
- return;
830
- }
1331
+ const rendered = this.rendered();
831
1332
  const items = this.items();
832
1333
  const active = this.activeIndex();
833
1334
  const vc = this.virtualCount();
834
1335
  if (vc != null) {
1336
+ if (!rendered) {
1337
+ return;
1338
+ }
835
1339
  // Virtual mode: match by data-cngx-recycle-index attribute. Clamp the
836
1340
  // model itself when the virtual space shrinks below it - a ghost
837
1341
  // index would otherwise anchor the next arrow press. An empty space
@@ -840,31 +1344,38 @@ class CngxRovingTabindex {
840
1344
  if (clamped !== active) {
841
1345
  untracked(() => this.activeIndex.set(clamped));
842
1346
  }
843
- items.forEach((item) => {
844
- const el = item.elementRef.nativeElement;
845
- const idx = el.dataset['cngxRecycleIndex'];
846
- el.setAttribute('tabindex', idx != null && Number(idx) === clamped ? '0' : '-1');
847
- });
1347
+ const stop = virtualTabStop(items, clamped);
1348
+ items.forEach((item) => item.elementRef.nativeElement.setAttribute('tabindex', item === stop ? '0' : '-1'));
1349
+ return;
848
1350
  }
849
- else {
850
- // Standard mode: match by array index. The tab stop must land on an
851
- // enabled item - fall back to the first enabled one when the clamped
852
- // target is disabled (initial index into a disabled leaf, or the
853
- // active item got disabled). The model is written back so keyboard
854
- // navigation anchors where the tab stop actually sits. An empty list
855
- // keeps the model untouched so a repopulated list restores it.
856
- if (items.length === 0) {
857
- return;
858
- }
859
- let target = Math.max(0, Math.min(active, items.length - 1));
860
- if (items[target]?.disabled()) {
861
- target = this.findFirst(items) ?? target;
862
- }
863
- if (target !== active) {
864
- untracked(() => this.activeIndex.set(target));
865
- }
866
- items.forEach((item, i) => item.elementRef.nativeElement.setAttribute('tabindex', i === target ? '0' : '-1'));
1351
+ // Standard mode: match by array index. When the list changed under an
1352
+ // unchanged index, the item that held the tab stop is looked up again,
1353
+ // so a removal or reorder before it does not hand the stop to another
1354
+ // item. The tab stop must land on an enabled item - fall back to the
1355
+ // first enabled one when the target is disabled (initial index into a
1356
+ // disabled leaf, or the active item got disabled). The model is written
1357
+ // back so keyboard navigation anchors where the tab stop actually sits.
1358
+ // An empty list keeps the model untouched so a repopulated list
1359
+ // restores it.
1360
+ if (items.length === 0) {
1361
+ return;
1362
+ }
1363
+ let anchor = active;
1364
+ if (items !== previousItems && active === previousActive) {
1365
+ const held = previousItems[active];
1366
+ const moved = held ? items.indexOf(held) : -1;
1367
+ anchor = moved >= 0 ? moved : active;
867
1368
  }
1369
+ let target = Math.max(0, Math.min(anchor, items.length - 1));
1370
+ if (items[target]?.disabled()) {
1371
+ target = this.findFirst(items) ?? target;
1372
+ }
1373
+ previousItems = items;
1374
+ previousActive = target;
1375
+ if (target !== active) {
1376
+ untracked(() => this.activeIndex.set(target));
1377
+ }
1378
+ items.forEach((item, i) => item.elementRef.nativeElement.setAttribute('tabindex', i === target ? '0' : '-1'));
868
1379
  });
869
1380
  }
870
1381
  /**
@@ -900,6 +1411,9 @@ class CngxRovingTabindex {
900
1411
  if (event.ctrlKey || event.metaKey || event.altKey) {
901
1412
  return;
902
1413
  }
1414
+ if (!this.ownsKey(event)) {
1415
+ return;
1416
+ }
903
1417
  const vc = this.virtualCount();
904
1418
  const allItems = this.items();
905
1419
  const isVirtual = vc != null;
@@ -952,6 +1466,24 @@ class CngxRovingTabindex {
952
1466
  event.preventDefault();
953
1467
  }
954
1468
  }
1469
+ /**
1470
+ * Whether the group may take the key: not one a nested widget already
1471
+ * handled, not part of an IME composition, not from a text field (an
1472
+ * `<input>` item or one inside an item keeps its caret keys) and not from
1473
+ * inside a nested widget that owns its arrows.
1474
+ */
1475
+ ownsKey(event) {
1476
+ if (event.defaultPrevented || isComposingKeydown(event)) {
1477
+ return false;
1478
+ }
1479
+ const target = event.target;
1480
+ if (isTextEntryTarget(target)) {
1481
+ return false;
1482
+ }
1483
+ const host = this.hostEl.nativeElement;
1484
+ const widget = target?.closest(ARROW_KEY_WIDGETS) ?? null;
1485
+ return widget === null || widget === host || !host.contains(widget);
1486
+ }
955
1487
  /**
956
1488
  * Keeps `activeIndex` in sync with real focus (APG): when an item gains
957
1489
  * focus by any means - pointer click, script focus, assistive tech - the
@@ -1052,6 +1584,28 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1052
1584
  },
1053
1585
  }]
1054
1586
  }], ctorParameters: () => [], propDecorators: { orientation: [{ type: i0.Input, args: [{ isSignal: true, alias: "orientation", required: false }] }, { type: i0.Output, args: ["orientationChange"] }], 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 }] }] } });
1587
+ /**
1588
+ * @internal The rendered item that holds the tab stop in virtual mode: the
1589
+ * one at the active index, or, while that index is outside the rendered
1590
+ * window, the rendered item nearest to it, so the group never drops out of
1591
+ * the Tab order. Focusing it moves the active index there (`focusin`).
1592
+ */
1593
+ function virtualTabStop(items, active) {
1594
+ let nearest = null;
1595
+ let distance = Infinity;
1596
+ for (const item of items) {
1597
+ const raw = item.elementRef.nativeElement.dataset['cngxRecycleIndex'];
1598
+ if (raw == null) {
1599
+ continue;
1600
+ }
1601
+ const gap = Math.abs(Number(raw) - active);
1602
+ if (gap < distance) {
1603
+ nearest = item;
1604
+ distance = gap;
1605
+ }
1606
+ }
1607
+ return nearest;
1608
+ }
1055
1609
 
1056
1610
  /**
1057
1611
  * DI token for content-projected items that should register with the
@@ -1066,10 +1620,9 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1066
1620
  * The contained directive must expose `id`, `value`, `label`, and optionally
1067
1621
  * `disabled` as signals - the AD reads them reactively.
1068
1622
  *
1069
- * @category common/a11y
1070
1623
  * @wcag AA
1071
1624
  * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/active-descendant/ad-item.token.ts
1072
- * @since 0.1.0
1625
+ * @since 0.3.0
1073
1626
  */
1074
1627
  const CNGX_AD_ITEM = new InjectionToken('CNGX_AD_ITEM');
1075
1628
 
@@ -1100,21 +1653,22 @@ const CNGX_AD_ITEM = new InjectionToken('CNGX_AD_ITEM');
1100
1653
  * checks, typeahead labels) map absolute indices onto the rendered subset.
1101
1654
  * Targets outside the window surface as `pendingHighlight`; the consumer
1102
1655
  * scrolls them into view (`connectRecyclerToActiveDescendant`) and the
1103
- * directive clears the pending state once the target renders.
1656
+ * directive clears the pending state once the target renders; no
1657
+ * `clearPendingHighlight()` call is needed.
1104
1658
  *
1105
1659
  * ### Material/CDK equivalent
1106
1660
  *
1107
1661
  * Same model as `cdk-listbox` and `mat-select`, without the visual shell and
1108
1662
  * driven by signals instead of `ListKeyManager`.
1109
1663
  *
1110
- * @category common/a11y
1111
- * @docsKind primary
1112
1664
  * @wcag AA
1113
1665
  * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/active-descendant/active-descendant.directive.ts
1114
- * @since 0.1.0
1666
+ * @since 0.3.0
1115
1667
  * @relatedTo CngxRovingTabindex, CngxListbox, CngxMenu
1116
- * <example-url>http://localhost:4200/#/common/a11y/active-descendant/listbox-with-items-input</example-url>
1117
- * <example-url>http://localhost:4200/#/common/a11y/active-descendant/typeahead</example-url>
1668
+ * <example-url>/#/common/a11y/active-descendant/listbox-with-items-input</example-url>
1669
+ * <example-url>/#/common/a11y/active-descendant/typeahead</example-url>
1670
+ * <example-url>/#/common/a11y/active-descendant/horizontal-option-row</example-url>
1671
+ * @axis level atom
1118
1672
  */
1119
1673
  class CngxActiveDescendant {
1120
1674
  /**
@@ -1150,6 +1704,23 @@ class CngxActiveDescendant {
1150
1704
  * Ignored when `virtualCount` is unset.
1151
1705
  */
1152
1706
  windowStart = input(0, ...(ngDevMode ? [{ debugName: "windowStart" }] : /* istanbul ignore next */ []));
1707
+ /**
1708
+ * The full list in absolute index space, for a windowed list whose rendered
1709
+ * rows are only part of it. When bound, typeahead searches this list and a
1710
+ * match anywhere in it becomes the highlight; `typeaheadMissed` then means no
1711
+ * match in the whole list. Unbound, the rendered window stays the search
1712
+ * space. Items are read for `label` and `disabled` only, so `id` may be empty.
1713
+ */
1714
+ typeaheadItems = input(undefined, ...(ngDevMode ? [{ debugName: "typeaheadItems" }] : /* istanbul ignore next */ []));
1715
+ /**
1716
+ * Equality used to find the previously active value again after the item
1717
+ * list changes. Defaults to `Object.is`; pass the same comparator as the
1718
+ * surrounding listbox / select when options are re-fetched as new objects
1719
+ * with equal identity, or the highlight drops on every refresh. The
1720
+ * parameters are typed `never` so a comparator over any value type binds
1721
+ * while the directive itself stays non-generic.
1722
+ */
1723
+ compareWith = input(Object.is, ...(ngDevMode ? [{ debugName: "compareWith" }] : /* istanbul ignore next */ []));
1153
1724
  /** Emitted when `activateCurrent()` is called with an active item. */
1154
1725
  activated = output();
1155
1726
  /** Emitted whenever the highlighted item changes. */
@@ -1168,13 +1739,18 @@ class CngxActiveDescendant {
1168
1739
  registered = contentChildren(CNGX_AD_ITEM, { ...(ngDevMode ? { debugName: "registered" } : /* istanbul ignore next */ {}), descendants: true });
1169
1740
  /** Document writing direction - flips the horizontal-arrow steps under `rtl` (APG). */
1170
1741
  direction = injectDirection();
1171
- /** Guards host attribute writes until after first render. */
1742
+ /** Holds `autoHighlightFirst` back until after first render. */
1172
1743
  initialized = signal(false, ...(ngDevMode ? [{ debugName: "initialized" }] : /* istanbul ignore next */ []));
1173
- /** -1 means "no active item". Range is [0, resolvedItems().length). */
1174
- activeIndexState = signal(-1, ...(ngDevMode ? [{ debugName: "activeIndexState" }] : /* istanbul ignore next */ []));
1175
- /** Index of an item that should be highlighted but is not in the DOM. */
1176
- pendingHighlightState = signal(null, ...(ngDevMode ? [{ debugName: "pendingHighlightState" }] : /* istanbul ignore next */ []));
1177
- pendingHighlight = this.pendingHighlightState.asReadonly();
1744
+ /**
1745
+ * A highlight gesture that fired while the option rows were not in the DOM
1746
+ * (a deferred-render panel just opened, OD5): the id space does not exist
1747
+ * yet, so the gesture is kept as INTENT - not a resolved index, which an
1748
+ * empty item space resolves to nothing. It is a source of
1749
+ * `activeIndexState` and resolves there once the rows render. Written only
1750
+ * by the imperative highlight methods; every index write clears it.
1751
+ * Non-virtual path only; the virtual path uses `pendingHighlight`.
1752
+ */
1753
+ pendingIntentState = signal(null, ...(ngDevMode ? [{ debugName: "pendingIntentState" }] : /* istanbul ignore next */ []));
1178
1754
  /**
1179
1755
  * Resolved item list. Input `items` wins; otherwise the contentChildren
1180
1756
  * handles are projected into `ActiveDescendantItem` shape.
@@ -1186,6 +1762,43 @@ class CngxActiveDescendant {
1186
1762
  }
1187
1763
  return this.registered().map(handleToItem);
1188
1764
  }, ...(ngDevMode ? [{ debugName: "resolvedItems" }] : /* istanbul ignore next */ []));
1765
+ /**
1766
+ * -1 means "no active item". Range is `[0, totalCount())`.
1767
+ *
1768
+ * Navigation writes the index; a change of the item space re-derives it.
1769
+ * In a plain list the highlight follows its value: after the item list
1770
+ * changes, the previously active value is looked up again with `compareWith`,
1771
+ * and gone means no highlight. In a virtual window it holds its absolute
1772
+ * index, because the rendered rows trail `windowStart` and cannot say where a
1773
+ * value sits; a window turning plain drops it. The result is clamped to the
1774
+ * new item space, so the next arrow press never starts from a ghost index.
1775
+ *
1776
+ * A pending open gesture (`pendingIntentState`) resolves here against every
1777
+ * populated item space until an index write clears it, so rows that arrive
1778
+ * in several passes settle on the gesture's target.
1779
+ */
1780
+ activeIndexState = linkedSignal({ ...(ngDevMode ? { debugName: "activeIndexState" } : /* istanbul ignore next */ {}), source: () => ({
1781
+ items: this.resolvedItems(),
1782
+ total: this.totalCount(),
1783
+ virtual: this.virtualCount() != null,
1784
+ offset: this.windowOffset(),
1785
+ compareWith: this.compareWith(),
1786
+ skipDisabled: this.skipDisabled(),
1787
+ intent: this.pendingIntentState(),
1788
+ }),
1789
+ computation: (source, previous) => {
1790
+ const { intent } = source;
1791
+ if (intent !== null && source.items.length > 0) {
1792
+ return resolveIntent({ ...source, intent });
1793
+ }
1794
+ if (!previous) {
1795
+ return -1;
1796
+ }
1797
+ const index = clampIndex(reResolveIndex(source, previous.source, previous.value), source.total);
1798
+ // An item that turned disabled cannot hold a highlight navigation skips.
1799
+ const disabled = source.skipDisabled && !!source.items[index - source.offset]?.disabled;
1800
+ return disabled ? -1 : index;
1801
+ } });
1189
1802
  /** Current active index. `-1` when no item is highlighted. */
1190
1803
  activeIndex = computed(() => {
1191
1804
  const idx = this.activeIndexState();
@@ -1195,6 +1808,33 @@ class CngxActiveDescendant {
1195
1808
  }
1196
1809
  return idx;
1197
1810
  }, ...(ngDevMode ? [{ debugName: "activeIndex" }] : /* istanbul ignore next */ []));
1811
+ /**
1812
+ * The highlight plus whether its row is rendered. Structural equal: a window
1813
+ * move that leaves both unchanged notifies nobody.
1814
+ */
1815
+ highlightPlacement = computed(() => {
1816
+ const index = this.activeIndex();
1817
+ return {
1818
+ index,
1819
+ rendered: index >= 0 && this.isRendered(index),
1820
+ virtual: this.virtualCount() != null,
1821
+ };
1822
+ }, { ...(ngDevMode ? { debugName: "highlightPlacement" } : /* istanbul ignore next */ {}), equal: (a, b) => a.index === b.index && a.rendered === b.rendered && a.virtual === b.virtual });
1823
+ /**
1824
+ * Index the highlight moved to while its row is not rendered. Armed by the
1825
+ * highlight change alone and cleared when the row renders; the same highlight
1826
+ * leaving the window later stays cleared, so scrolling a virtual list away
1827
+ * never asks to be scrolled back.
1828
+ */
1829
+ pendingHighlightState = linkedSignal({ ...(ngDevMode ? { debugName: "pendingHighlightState" } : /* istanbul ignore next */ {}), source: this.highlightPlacement,
1830
+ computation: (placement, previous) => {
1831
+ if (!placement.virtual || placement.index < 0 || placement.rendered) {
1832
+ return null;
1833
+ }
1834
+ return previous?.source.index === placement.index ? previous.value : placement.index;
1835
+ } });
1836
+ /** Index of an item that should be highlighted but is not in the DOM. */
1837
+ pendingHighlight = this.pendingHighlightState.asReadonly();
1198
1838
  /**
1199
1839
  * `activeIndex` always mapped back to an item. `null` when no active index
1200
1840
  * or the item is out of rendered range (virtual mode).
@@ -1215,8 +1855,17 @@ class CngxActiveDescendant {
1215
1855
  highlightedItem = computed(() => this.activeItem(), { ...(ngDevMode ? { debugName: "highlightedItem" } : /* istanbul ignore next */ {}), equal: (a, b) => a === b || (a !== null && b !== null && a.id === b.id) });
1216
1856
  activeId = computed(() => this.activeItem()?.id ?? null, ...(ngDevMode ? [{ debugName: "activeId" }] : /* istanbul ignore next */ []));
1217
1857
  activeValue = computed(() => this.activeItem()?.value ?? null, ...(ngDevMode ? [{ debugName: "activeValue" }] : /* istanbul ignore next */ []));
1218
- typeaheadBuffer = signal('', ...(ngDevMode ? [{ debugName: "typeaheadBuffer" }] : /* istanbul ignore next */ []));
1219
- typeaheadTimer = null;
1858
+ typeaheadWalker = createTypeaheadWalker({
1859
+ debounceMs: this.typeaheadDebounce,
1860
+ locale: this.locale,
1861
+ });
1862
+ /**
1863
+ * `true` while a typeahead term is being typed (the buffer has not reset
1864
+ * yet). A space typed then belongs to the term ("new y" reaches "New
1865
+ * York") instead of activating the highlight. External keyboard hosts read
1866
+ * it to route Space through {@link typeaheadChar}.
1867
+ */
1868
+ typeaheadActive = computed(() => this.typeaheadWalker.buffer() !== '', ...(ngDevMode ? [{ debugName: "typeaheadActive" }] : /* istanbul ignore next */ []));
1220
1869
  constructor() {
1221
1870
  afterNextRender(() => this.initialized.set(true));
1222
1871
  effect(() => {
@@ -1238,58 +1887,95 @@ class CngxActiveDescendant {
1238
1887
  hadHighlight = true;
1239
1888
  this.highlighted.emit(item);
1240
1889
  });
1890
+ // One DOM scroll per highlight change, delayed until the row renders. A
1891
+ // window move alone never scrolls: the row of an unchanged highlight
1892
+ // re-entering the window must not pull the list back to it.
1893
+ let lastIndex = -1;
1894
+ let scrollDue = false;
1241
1895
  effect(() => {
1242
- const idx = this.activeIndex();
1243
- if (idx < 0) {
1244
- return;
1896
+ const { index, rendered } = this.highlightPlacement();
1897
+ if (index !== lastIndex) {
1898
+ lastIndex = index;
1899
+ scrollDue = index >= 0;
1245
1900
  }
1246
- if (this.virtualCount() != null) {
1247
- if (!this.isRendered(idx)) {
1248
- this.pendingHighlightState.set(idx);
1249
- return;
1250
- }
1251
- this.pendingHighlightState.set(null);
1901
+ if (!scrollDue || !rendered) {
1902
+ return;
1252
1903
  }
1904
+ scrollDue = false;
1253
1905
  queueMicrotask(() => this.scrollActiveIntoView());
1254
1906
  });
1255
- // Clamp the active STATE, not just the derived display, when the item
1256
- // space shrinks below it - otherwise the next arrow press navigates
1257
- // relative to a ghost index.
1258
- effect(() => {
1259
- const total = this.totalCount();
1260
- const idx = this.activeIndexState();
1261
- if (idx >= total) {
1262
- untracked(() => this.activeIndexState.set(total > 0 ? total - 1 : -1));
1263
- }
1264
- });
1265
- inject(DestroyRef).onDestroy(() => {
1266
- if (this.typeaheadTimer !== null) {
1267
- clearTimeout(this.typeaheadTimer);
1268
- }
1269
- });
1907
+ inject(DestroyRef).onDestroy(() => this.typeaheadWalker.clear());
1908
+ }
1909
+ /**
1910
+ * Non-virtual path with no rendered rows yet (a deferred-render panel just
1911
+ * opened, OD5): the option id space does not exist, so a highlight resolves
1912
+ * against nothing and is lost. Remember the gesture as intent -
1913
+ * `activeIndexState` resolves it once the rows render - and report that it
1914
+ * was deferred. The virtual path never defers here; its out-of-window
1915
+ * targets surface through `pendingHighlight` instead.
1916
+ */
1917
+ deferIfUnrendered(intent) {
1918
+ if (this.virtualCount() == null && this.resolvedItems().length === 0) {
1919
+ this.pendingIntentState.set(intent);
1920
+ return true;
1921
+ }
1922
+ return false;
1923
+ }
1924
+ /** Index write of a navigation step; a resolved intent never re-applies after it. */
1925
+ writeIndex(index) {
1926
+ this.pendingIntentState.set(null);
1927
+ this.activeIndexState.set(index);
1270
1928
  }
1929
+ /**
1930
+ * Moves the highlight to the next item after the active one. Disabled items
1931
+ * are skipped while `skipDisabled` is true; past the last item it wraps to the
1932
+ * first when `loop` is true and stays put otherwise. With no rows it does
1933
+ * nothing: a step inside an empty list is not an open gesture to keep.
1934
+ */
1271
1935
  highlightNext() {
1272
1936
  const next = this.findFrom(this.activeIndexState(), 1);
1273
1937
  if (next !== null) {
1274
- this.activeIndexState.set(next);
1938
+ this.writeIndex(next);
1275
1939
  }
1276
1940
  }
1941
+ /**
1942
+ * Moves the highlight to the item before the active one. Disabled items are
1943
+ * skipped while `skipDisabled` is true; before the first item it wraps to the
1944
+ * last when `loop` is true and stays put otherwise. With no rows it does
1945
+ * nothing.
1946
+ */
1277
1947
  highlightPrev() {
1278
1948
  const next = this.findFrom(this.activeIndexState(), -1);
1279
1949
  if (next !== null) {
1280
- this.activeIndexState.set(next);
1950
+ this.writeIndex(next);
1281
1951
  }
1282
1952
  }
1953
+ /**
1954
+ * Moves the highlight to the first enabled item (the first item when
1955
+ * `skipDisabled` is false). Does nothing when no item qualifies.
1956
+ */
1283
1957
  highlightFirst() {
1958
+ if (this.deferIfUnrendered({ kind: 'first' })) {
1959
+ return;
1960
+ }
1284
1961
  const first = this.findBoundary(1);
1285
1962
  if (first !== null) {
1286
- this.activeIndexState.set(first);
1963
+ this.writeIndex(first);
1287
1964
  }
1288
1965
  }
1966
+ /**
1967
+ * Moves the highlight to the last enabled item (the last item when
1968
+ * `skipDisabled` is false). With a virtual count it targets the last absolute
1969
+ * index even when that item is not rendered yet. Does nothing when no item
1970
+ * qualifies.
1971
+ */
1289
1972
  highlightLast() {
1973
+ if (this.deferIfUnrendered({ kind: 'last' })) {
1974
+ return;
1975
+ }
1290
1976
  const last = this.findBoundary(-1);
1291
1977
  if (last !== null) {
1292
- this.activeIndexState.set(last);
1978
+ this.writeIndex(last);
1293
1979
  }
1294
1980
  }
1295
1981
  /**
@@ -1297,6 +1983,9 @@ class CngxActiveDescendant {
1297
1983
  * Disabled items are rejected when `skipDisabled()` is true.
1298
1984
  */
1299
1985
  highlightByIndex(index) {
1986
+ if (this.deferIfUnrendered({ kind: 'byIndex', index })) {
1987
+ return;
1988
+ }
1300
1989
  const total = this.totalCount();
1301
1990
  if (index < 0 || index >= total) {
1302
1991
  return;
@@ -1304,27 +1993,32 @@ class CngxActiveDescendant {
1304
1993
  if (this.skipDisabled() && this.isDisabledAt(index)) {
1305
1994
  return;
1306
1995
  }
1307
- this.activeIndexState.set(index);
1996
+ this.writeIndex(index);
1308
1997
  }
1309
1998
  /**
1310
- * Highlight the first rendered item whose value matches (via `Object.is`).
1999
+ * Highlight the first rendered item whose value matches (via `compareWith`).
1311
2000
  * No-op if no match. Disabled items are rejected when `skipDisabled()` is
1312
2001
  * true. In virtual mode only the rendered window is searched; the resolved
1313
2002
  * index is absolute.
1314
2003
  */
1315
2004
  highlightByValue(value) {
2005
+ if (this.deferIfUnrendered({ kind: 'byValue', value })) {
2006
+ return;
2007
+ }
1316
2008
  const items = this.resolvedItems();
1317
- const idx = items.findIndex((it) => Object.is(it.value, value));
2009
+ const compare = this.compareWith();
2010
+ const idx = items.findIndex((it) => compare(it.value, value));
1318
2011
  if (idx < 0) {
1319
2012
  return;
1320
2013
  }
1321
2014
  if (this.skipDisabled() && items[idx].disabled) {
1322
2015
  return;
1323
2016
  }
1324
- this.activeIndexState.set(idx + this.windowOffset());
2017
+ this.writeIndex(idx + this.windowOffset());
1325
2018
  }
1326
- /** Clear the highlight. */
2019
+ /** Clear the highlight, including a gesture still pending a deferred render. */
1327
2020
  resetHighlight() {
2021
+ this.pendingIntentState.set(null);
1328
2022
  this.activeIndexState.set(-1);
1329
2023
  }
1330
2024
  /** Emit `activated` with the current item's value. No-op if nothing active. */
@@ -1334,7 +2028,11 @@ class CngxActiveDescendant {
1334
2028
  this.activated.emit(item.value);
1335
2029
  }
1336
2030
  }
1337
- /** Called by recycler bridges after scrolling the pending index into view. */
2031
+ /**
2032
+ * Drops `pendingHighlight` without waiting for the row to render. Optional:
2033
+ * the directive clears it on its own once the target row renders, and
2034
+ * `connectRecyclerToActiveDescendant` never calls this.
2035
+ */
1338
2036
  clearPendingHighlight() {
1339
2037
  this.pendingHighlightState.set(null);
1340
2038
  }
@@ -1342,30 +2040,49 @@ class CngxActiveDescendant {
1342
2040
  // Never hijack browser/app shortcuts: Ctrl/Cmd/Alt combos pass through
1343
2041
  // untouched (Ctrl+C would otherwise hit the typeahead branch and get
1344
2042
  // preventDefault'd). Shift stays allowed - it produces printable chars.
2043
+ // A key a nested widget already handled, and every key of an IME
2044
+ // composition (the commit Enter included), is not ours either.
1345
2045
  if (event.ctrlKey || event.metaKey || event.altKey) {
1346
2046
  return;
1347
2047
  }
2048
+ if (event.defaultPrevented || isComposingKeydown(event)) {
2049
+ return;
2050
+ }
1348
2051
  // Skip events from editable descendants. Without this, every
1349
2052
  // printable key typed into a descendant <input> hits AD's typeahead
1350
2053
  // branch, gets preventDefault'd, and never reaches the input.
1351
2054
  const target = event.target;
1352
- if (target && target !== event.currentTarget && isEditableTarget(target)) {
2055
+ if (target !== event.currentTarget && isTextEntryTarget(target)) {
1353
2056
  return;
1354
2057
  }
2058
+ // A text host (combobox input, textarea) keeps the caret keys and the
2059
+ // characters it types: only the arrows and Enter drive the list.
2060
+ const textHost = isTextEntryTarget(this.hostEl.nativeElement);
1355
2061
  const key = event.key;
1356
2062
  if (this.isNavKey(key)) {
2063
+ if (textHost && (key === 'Home' || key === 'End')) {
2064
+ return;
2065
+ }
1357
2066
  const before = this.activeIndexState();
2067
+ const intentBefore = this.pendingIntentState();
1358
2068
  this.dispatchNav(key);
1359
- if (this.activeIndexState() !== before) {
2069
+ const moved = this.activeIndexState() !== before;
2070
+ const deferred = this.pendingIntentState() !== intentBefore;
2071
+ if (moved || deferred) {
1360
2072
  event.preventDefault();
1361
2073
  }
1362
2074
  return;
1363
2075
  }
2076
+ if (textHost && (key === ' ' || isPrintableChar(key))) {
2077
+ return;
2078
+ }
2079
+ if (key === ' ' && this.typeahead() && this.typeaheadActive()) {
2080
+ event.preventDefault();
2081
+ this.handleTypeahead(key);
2082
+ return;
2083
+ }
1364
2084
  if (key === 'Enter' || key === ' ') {
1365
- if (this.activeItem()) {
1366
- event.preventDefault();
1367
- this.activateCurrent();
1368
- }
2085
+ this.handleActivationKey(event, key);
1369
2086
  return;
1370
2087
  }
1371
2088
  if (this.typeahead() && isPrintableChar(key)) {
@@ -1373,6 +2090,41 @@ class CngxActiveDescendant {
1373
2090
  this.handleTypeahead(key);
1374
2091
  }
1375
2092
  }
2093
+ /** @internal True when `el` renders one of the host's own items. */
2094
+ isOwnItemElement(el) {
2095
+ const id = el.id;
2096
+ return id !== '' && this.resolvedItems().some((item) => item.id === id);
2097
+ }
2098
+ /** Descendants that own Enter / Space; `CNGX_NESTED_INTERACTIVE_SELECTOR`. */
2099
+ nestedInteractive = inject(CNGX_NESTED_INTERACTIVE_SELECTOR);
2100
+ handleActivationKey(event, key) {
2101
+ const host = this.hostEl.nativeElement;
2102
+ // A focused control inside the host (a Retry button in an error banner)
2103
+ // owns its Enter / Space: no preventDefault, so its native activation runs,
2104
+ // and the active item stays untouched. The host's own item elements
2105
+ // (a role="menuitem" row that took focus from a click) are not such a
2106
+ // control: their keys still activate through the directive.
2107
+ const target = event.target;
2108
+ const interactive = target?.closest(this.nestedInteractive);
2109
+ if (interactive &&
2110
+ interactive !== host &&
2111
+ host.contains(interactive) &&
2112
+ !this.isOwnItemElement(interactive)) {
2113
+ return;
2114
+ }
2115
+ if (this.activeItem()) {
2116
+ event.preventDefault();
2117
+ this.activateCurrent();
2118
+ return;
2119
+ }
2120
+ // Nothing to activate: Space would scroll the page from a focused host.
2121
+ // A text host never gets here with Space (the keydown handler leaves it
2122
+ // to the field). Enter stays untouched so a consumer's own Enter handler
2123
+ // still runs.
2124
+ if (key === ' ') {
2125
+ event.preventDefault();
2126
+ }
2127
+ }
1376
2128
  isNavKey(key) {
1377
2129
  switch (key) {
1378
2130
  case 'ArrowDown':
@@ -1429,7 +2181,8 @@ class CngxActiveDescendant {
1429
2181
  * semantics on a separate listbox.
1430
2182
  *
1431
2183
  * Consumers should only forward single-character printable keys (`length === 1`,
1432
- * non-whitespace). Navigation keys and non-printables must not be forwarded.
2184
+ * non-whitespace), plus a space while {@link typeaheadActive} is `true`.
2185
+ * Navigation keys and non-printables must not be forwarded.
1433
2186
  */
1434
2187
  typeaheadChar(ch) {
1435
2188
  if (!this.typeahead()) {
@@ -1438,48 +2191,24 @@ class CngxActiveDescendant {
1438
2191
  this.handleTypeahead(ch);
1439
2192
  }
1440
2193
  handleTypeahead(ch) {
1441
- const locale = this.locale();
1442
- const next = this.typeaheadBuffer() + ch.toLocaleLowerCase(locale);
1443
- this.typeaheadBuffer.set(next);
1444
- if (this.typeaheadTimer !== null) {
1445
- clearTimeout(this.typeaheadTimer);
1446
- }
1447
- this.typeaheadTimer = setTimeout(() => {
1448
- this.typeaheadBuffer.set('');
1449
- this.typeaheadTimer = null;
1450
- }, this.typeaheadDebounce());
1451
- // Labels exist only for rendered items, so the search space is the
1452
- // rendered window; matches map back to absolute indices in virtual mode.
1453
- const items = this.resolvedItems();
1454
- const skip = this.skipDisabled();
1455
- const count = items.length;
1456
- // APG cycle: a single-character query (including a repeated letter, whose
1457
- // buffer collapses back to that letter) searches AFTER the active item so
1458
- // each press advances through the matches. A genuine multi-character query
1459
- // keeps matching the current item first.
1460
- const sameChar = next.length > 1 && [...next].every((c) => c === next[0]);
1461
- const term = sameChar ? next[0] : next;
1462
- if (count === 0) {
2194
+ const term = this.typeaheadWalker.type(ch);
2195
+ // Labels exist only for rendered items unless the host hands the full list
2196
+ // over, so the search space is the rendered window by default; matches map
2197
+ // back to absolute indices in virtual mode.
2198
+ const fullList = this.typeaheadItems();
2199
+ const items = fullList ?? this.resolvedItems();
2200
+ if (items.length === 0) {
1463
2201
  this.typeaheadMissed.emit(term);
1464
2202
  return;
1465
2203
  }
1466
- const windowOffset = this.windowOffset();
1467
- const activeRel = this.activeIndexState() < 0 ? -1 : this.activeIndexState() - windowOffset;
1468
- const cycles = term.length === 1;
1469
- const startRel = cycles ? activeRel + 1 : Math.max(0, activeRel);
1470
- const matches = createTypeaheadMatcher(term, locale);
1471
- for (let step = 0; step < count; step++) {
1472
- const rel = (((startRel + step) % count) + count) % count;
1473
- const candidate = items[rel];
1474
- if (skip && candidate.disabled) {
1475
- continue;
1476
- }
1477
- if (matches(candidate.label, candidate)) {
1478
- this.activeIndexState.set(rel + windowOffset);
1479
- return;
1480
- }
2204
+ const offset = fullList ? 0 : this.windowOffset();
2205
+ const activeRel = this.activeIndexState() < 0 ? -1 : this.activeIndexState() - offset;
2206
+ const rel = this.typeaheadWalker.find(items, term, activeRel, this.skipDisabled());
2207
+ if (rel < 0) {
2208
+ this.typeaheadMissed.emit(term);
2209
+ return;
1481
2210
  }
1482
- this.typeaheadMissed.emit(term);
2211
+ this.writeIndex(rel + offset);
1483
2212
  }
1484
2213
  findFrom(current, direction) {
1485
2214
  return resolveStepFrom(current, direction, {
@@ -1540,7 +2269,7 @@ class CngxActiveDescendant {
1540
2269
  }
1541
2270
  }
1542
2271
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxActiveDescendant, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1543
- 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 }, windowStart: { classPropertyName: "windowStart", publicName: "windowStart", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { activated: "activated", highlighted: "highlighted", typeaheadMissed: "typeaheadMissed" }, 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 });
2272
+ 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 }, windowStart: { classPropertyName: "windowStart", publicName: "windowStart", isSignal: true, isRequired: false, transformFunction: null }, typeaheadItems: { classPropertyName: "typeaheadItems", publicName: "typeaheadItems", isSignal: true, isRequired: false, transformFunction: null }, compareWith: { classPropertyName: "compareWith", publicName: "compareWith", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { activated: "activated", highlighted: "highlighted", typeaheadMissed: "typeaheadMissed" }, 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 });
1544
2273
  }
1545
2274
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxActiveDescendant, decorators: [{
1546
2275
  type: Directive,
@@ -1553,7 +2282,60 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1553
2282
  '(keydown)': 'handleKeydown($event)',
1554
2283
  },
1555
2284
  }]
1556
- }], 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 }] }], windowStart: [{ type: i0.Input, args: [{ isSignal: true, alias: "windowStart", required: false }] }], activated: [{ type: i0.Output, args: ["activated"] }], highlighted: [{ type: i0.Output, args: ["highlighted"] }], typeaheadMissed: [{ type: i0.Output, args: ["typeaheadMissed"] }], registered: [{ type: i0.ContentChildren, args: [i0.forwardRef(() => CNGX_AD_ITEM), { ...{ descendants: true }, isSignal: true }] }] } });
2285
+ }], 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 }] }], windowStart: [{ type: i0.Input, args: [{ isSignal: true, alias: "windowStart", required: false }] }], typeaheadItems: [{ type: i0.Input, args: [{ isSignal: true, alias: "typeaheadItems", required: false }] }], compareWith: [{ type: i0.Input, args: [{ isSignal: true, alias: "compareWith", required: false }] }], activated: [{ type: i0.Output, args: ["activated"] }], highlighted: [{ type: i0.Output, args: ["highlighted"] }], typeaheadMissed: [{ type: i0.Output, args: ["typeaheadMissed"] }], registered: [{ type: i0.ContentChildren, args: [i0.forwardRef(() => CNGX_AD_ITEM), { ...{ descendants: true }, isSignal: true }] }] } });
2286
+ /** @internal Resolves an open gesture against a populated item space; -1 when nothing qualifies. */
2287
+ function resolveIntent(source) {
2288
+ const { items, offset, total, intent } = source;
2289
+ const isDisabledAt = source.skipDisabled
2290
+ ? (i) => !!items[i - offset]?.disabled
2291
+ : undefined;
2292
+ switch (intent.kind) {
2293
+ case 'first':
2294
+ return resolveBoundaryStep(1, { count: total, isDisabledAt }) ?? -1;
2295
+ case 'last':
2296
+ return resolveBoundaryStep(-1, { count: total, isDisabledAt }) ?? -1;
2297
+ case 'byIndex': {
2298
+ const outside = intent.index < 0 || intent.index >= total;
2299
+ return outside || isDisabledAt?.(intent.index) ? -1 : intent.index;
2300
+ }
2301
+ case 'byValue': {
2302
+ const idx = items.findIndex((it) => source.compareWith(it.value, intent.value));
2303
+ return idx < 0 || (source.skipDisabled && items[idx].disabled) ? -1 : idx + offset;
2304
+ }
2305
+ }
2306
+ }
2307
+ /**
2308
+ * @internal
2309
+ * Re-derives the index for a new item space. A virtual window keeps its
2310
+ * absolute index while its total holds (a window move); a changed total is a
2311
+ * new list, so the index is dropped rather than left on another option. The
2312
+ * index also means nothing once the list turns plain. In a
2313
+ * plain list the previously active value is looked up again; unchanged items,
2314
+ * no previous highlight, or an index past the old items keep the index.
2315
+ */
2316
+ function reResolveIndex(source, previousSource, previousIndex) {
2317
+ if (source.virtual) {
2318
+ return source.total === previousSource.total ? previousIndex : -1;
2319
+ }
2320
+ if (previousSource.virtual) {
2321
+ return -1;
2322
+ }
2323
+ if (previousSource.items === source.items || previousIndex < 0) {
2324
+ return previousIndex;
2325
+ }
2326
+ const previous = previousSource.items[previousIndex];
2327
+ if (!previous) {
2328
+ return previousIndex;
2329
+ }
2330
+ return source.items.findIndex((it) => source.compareWith(it.value, previous.value));
2331
+ }
2332
+ /** @internal Pulls an index that ran past the item space back onto its last item. */
2333
+ function clampIndex(index, total) {
2334
+ if (index < total) {
2335
+ return index;
2336
+ }
2337
+ return total > 0 ? total - 1 : -1;
2338
+ }
1557
2339
  /** @internal */
1558
2340
  function handleToItem(handle) {
1559
2341
  return {
@@ -1567,36 +2349,6 @@ function handleToItem(handle) {
1567
2349
  function isPrintableChar(key) {
1568
2350
  return key.length === 1 && /\S/.exec(key) !== null;
1569
2351
  }
1570
- /**
1571
- * True when the element would capture text input natively - a text
1572
- * `<input>`, `<textarea>`, or any `contenteditable` host. Read-only /
1573
- * button-type inputs (submit, radio, checkbox) are NOT editable; AD's
1574
- * keyboard navigation still applies when focus lands on them.
1575
- *
1576
- * @internal
1577
- */
1578
- function isEditableTarget(el) {
1579
- if (el.isContentEditable) {
1580
- return true;
1581
- }
1582
- const tag = el.tagName;
1583
- if (tag === 'TEXTAREA') {
1584
- return true;
1585
- }
1586
- if (tag === 'INPUT') {
1587
- const type = el.type.toLowerCase();
1588
- return (type !== 'button' &&
1589
- type !== 'submit' &&
1590
- type !== 'reset' &&
1591
- type !== 'checkbox' &&
1592
- type !== 'radio' &&
1593
- type !== 'range' &&
1594
- type !== 'color' &&
1595
- type !== 'file' &&
1596
- type !== 'image');
1597
- }
1598
- return false;
1599
- }
1600
2352
  /** @internal */
1601
2353
  function cssEscape(id) {
1602
2354
  const api = globalThis.CSS;
@@ -1618,6 +2370,11 @@ function cssEscape(id) {
1618
2370
  * directive makes the preference available in component logic (e.g., to pick
1619
2371
  * a different animation strategy or suppress requestAnimationFrame loops).
1620
2372
  *
2373
+ * This is the OS preference only. An in-app pick through `provideMotion` /
2374
+ * `injectMotion` (`CNGX_MOTION`, `<html data-motion>`) is not seen here; to
2375
+ * decide on the motion the user actually gets, read `injectEffectiveMotion()`
2376
+ * from `@cngx/core` instead.
2377
+ *
1621
2378
  * ### Conditional animation
1622
2379
  * ```html
1623
2380
  * <div cngxReducedMotion #rm="cngxReducedMotion"
@@ -1631,15 +2388,15 @@ function cssEscape(id) {
1631
2388
  * readonly duration = computed(() => this.rm()?.prefersReducedMotion() ? 0 : 300);
1632
2389
  * ```
1633
2390
  *
1634
- * @category common/a11y
1635
2391
  * @wcag AA
1636
2392
  * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/motion/reduced-motion.directive.ts
1637
- * @since 0.1.0
1638
- * <example-url>http://localhost:4200/#/common/a11y/reduced-motion/animation-toggle</example-url>
1639
- * <example-url>http://localhost:4200/#/common/a11y/reduced-motion/toast-notifications-motion-aware</example-url>
2393
+ * @since 0.3.0
2394
+ * <example-url>/#/common/a11y/reduced-motion/animation-toggle</example-url>
2395
+ * <example-url>/#/common/a11y/reduced-motion/toast-notifications-motion-aware</example-url>
2396
+ * @axis level atom
1640
2397
  */
1641
2398
  class CngxReducedMotion {
1642
- /** `true` when the user's OS is set to prefer reduced motion. Updates reactively. */
2399
+ /** `true` when the user's OS is set to prefer reduced motion (ignores `CNGX_MOTION`). Updates reactively. */
1643
2400
  prefersReducedMotion;
1644
2401
  constructor() {
1645
2402
  this.prefersReducedMotion = createMediaQuerySignal('(prefers-reduced-motion: reduce)', inject(DestroyRef), inject(DOCUMENT).defaultView);
@@ -1658,12 +2415,12 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1658
2415
  }], ctorParameters: () => [] });
1659
2416
 
1660
2417
  /**
1661
- * @module @cngx/common/a11y
2418
+ * @module `@cngx/common/a11y`
1662
2419
  */
1663
2420
 
1664
2421
  /**
1665
2422
  * Generated bundle index. Do not edit.
1666
2423
  */
1667
2424
 
1668
- export { CNGX_AD_ITEM, CNGX_FOCUSABLE_SELECTOR, CngxActiveDescendant, CngxAriaExpanded, CngxAutofocus, CngxFocusRestore, CngxFocusTrap, CngxFocusVisible, CngxLiveAnnouncer, CngxLiveRegion, CngxReducedMotion, CngxRovingItem, CngxRovingTabindex };
2425
+ export { CNGX_AD_ITEM, CNGX_ARIA_EXPANDED_DRIVER, CNGX_FOCUSABLE_SELECTOR, CNGX_FOCUS_RESTORE_DRIVER, CNGX_FOCUS_TRAP_DRIVER, CngxActiveDescendant, CngxAriaExpanded, CngxAutofocus, CngxFocusRestore, CngxFocusTrap, CngxFocusVisible, CngxLiveAnnouncer, CngxLiveRegion, CngxReducedMotion, CngxRovingItem, CngxRovingTabindex, injectScopedLiveRegion };
1669
2426
  //# sourceMappingURL=cngx-common-a11y.mjs.map