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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/command/README.md +29 -0
  2. package/data/README.md +5 -2
  3. package/fesm2022/cngx-common-a11y.mjs +403 -84
  4. package/fesm2022/cngx-common-a11y.mjs.map +1 -1
  5. package/fesm2022/cngx-common-audio.mjs +16 -13
  6. package/fesm2022/cngx-common-audio.mjs.map +1 -1
  7. package/fesm2022/cngx-common-card.mjs +4 -3
  8. package/fesm2022/cngx-common-card.mjs.map +1 -1
  9. package/fesm2022/cngx-common-chart.mjs +55 -36
  10. package/fesm2022/cngx-common-chart.mjs.map +1 -1
  11. package/fesm2022/cngx-common-command.mjs +60 -6
  12. package/fesm2022/cngx-common-command.mjs.map +1 -1
  13. package/fesm2022/cngx-common-data.mjs +185 -37
  14. package/fesm2022/cngx-common-data.mjs.map +1 -1
  15. package/fesm2022/cngx-common-dialog.mjs +86 -48
  16. package/fesm2022/cngx-common-dialog.mjs.map +1 -1
  17. package/fesm2022/cngx-common-display.mjs +27 -23
  18. package/fesm2022/cngx-common-display.mjs.map +1 -1
  19. package/fesm2022/cngx-common-interactive.mjs +324 -122
  20. package/fesm2022/cngx-common-interactive.mjs.map +1 -1
  21. package/fesm2022/cngx-common-layout.mjs +129 -26
  22. package/fesm2022/cngx-common-layout.mjs.map +1 -1
  23. package/fesm2022/cngx-common-popover.mjs +947 -33
  24. package/fesm2022/cngx-common-popover.mjs.map +1 -1
  25. package/fesm2022/cngx-common-stepper.mjs +300 -166
  26. package/fesm2022/cngx-common-stepper.mjs.map +1 -1
  27. package/fesm2022/cngx-common-tabs.mjs +251 -80
  28. package/fesm2022/cngx-common-tabs.mjs.map +1 -1
  29. package/fesm2022/cngx-common-timeline.mjs +16 -10
  30. package/fesm2022/cngx-common-timeline.mjs.map +1 -1
  31. package/fesm2022/cngx-common.mjs +1 -1
  32. package/layout/README.md +16 -0
  33. package/package.json +20 -7
  34. package/popover/README.md +40 -0
  35. package/schematics/collection.json +9 -0
  36. package/schematics/ng-add/index.js +9 -0
  37. package/schematics/ng-add/schema.json +91 -0
  38. package/schematics/package.json +3 -0
  39. package/stepper/README.md +5 -4
  40. package/theming/components/cngx-popover-sheet.css +402 -0
  41. package/theming/components/cngx-popover.css +10 -6
  42. package/types/cngx-common-a11y.d.ts +167 -14
  43. package/types/cngx-common-chart.d.ts +8 -7
  44. package/types/cngx-common-command.d.ts +19 -2
  45. package/types/cngx-common-data.d.ts +164 -26
  46. package/types/cngx-common-dialog.d.ts +3 -7
  47. package/types/cngx-common-interactive.d.ts +52 -17
  48. package/types/cngx-common-layout.d.ts +37 -5
  49. package/types/cngx-common-popover.d.ts +353 -13
  50. package/types/cngx-common-stepper.d.ts +168 -129
  51. package/types/cngx-common-tabs.d.ts +149 -30
  52. package/types/cngx-common-timeline.d.ts +27 -7
@@ -1,5 +1,5 @@
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 { input, Directive, inject, PLATFORM_ID, Injectable, DestroyRef, ElementRef, Injector, afterNextRender, effect, signal, InjectionToken, computed, untracked, model, contentChildren, output, linkedSignal } from '@angular/core';
3
3
  import { DOCUMENT, isPlatformBrowser } from '@angular/common';
4
4
  import { FocusTrapFactory } from '@angular/cdk/a11y';
5
5
  import { injectDirection, resolveInlineStep, resolveStepFrom, resolveBoundaryStep } from '@cngx/core';
@@ -135,6 +135,119 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
135
135
  // One frame. Clear the region this long before writing so an intentionally
136
136
  // repeated identical string still registers as a content change for the SR.
137
137
  const CLEAR_DELAY_MS = 16;
138
+ const POLITENESS = ['polite', 'assertive'];
139
+ /**
140
+ * @internal Browser only: callers guard the server path. Each region is a
141
+ * visually hidden `aria-live` + `aria-atomic="true"` span (the attribute
142
+ * contract of `CngxLiveRegion`), created lazily on the first announce of its
143
+ * politeness or by `ensure()`.
144
+ *
145
+ * `redirect` is asked when a write is due: returning `true` means the caller
146
+ * took the message elsewhere (its container stopped being readable while the
147
+ * write was pending), so nothing is written here.
148
+ */
149
+ function createLiveRegionPair(container, doc, redirect) {
150
+ const regions = {
151
+ polite: null,
152
+ assertive: null,
153
+ };
154
+ const pending = {
155
+ polite: null,
156
+ assertive: null,
157
+ };
158
+ const ensureRegion = (politeness) => {
159
+ const existing = regions[politeness];
160
+ if (existing) {
161
+ return existing;
162
+ }
163
+ const span = doc.createElement('span');
164
+ span.setAttribute('aria-live', politeness);
165
+ span.setAttribute('aria-atomic', 'true');
166
+ span.className = 'cngx-sr-only';
167
+ span.style.position = 'absolute';
168
+ span.style.width = '1px';
169
+ span.style.height = '1px';
170
+ span.style.padding = '0';
171
+ span.style.margin = '-1px';
172
+ span.style.overflow = 'hidden';
173
+ span.style.clip = 'rect(0, 0, 0, 0)';
174
+ span.style.whiteSpace = 'nowrap';
175
+ span.style.border = '0';
176
+ container.appendChild(span);
177
+ regions[politeness] = span;
178
+ return span;
179
+ };
180
+ const cancel = (politeness) => {
181
+ const write = pending[politeness];
182
+ if (write) {
183
+ clearTimeout(write.timer);
184
+ pending[politeness] = null;
185
+ }
186
+ return write;
187
+ };
188
+ return {
189
+ announce(message, politeness, delayMs = CLEAR_DELAY_MS) {
190
+ const region = ensureRegion(politeness);
191
+ // Clear first, then write one frame later so repeating the same string
192
+ // still registers as a content change for the SR. Polite and assertive
193
+ // keep independent timers so one politeness never cancels the other.
194
+ region.textContent = '';
195
+ cancel(politeness);
196
+ pending[politeness] = {
197
+ message,
198
+ timer: setTimeout(() => {
199
+ pending[politeness] = null;
200
+ if (redirect?.({ message, politeness })) {
201
+ return;
202
+ }
203
+ region.textContent = message;
204
+ }, delayMs),
205
+ };
206
+ },
207
+ ensure() {
208
+ for (const politeness of POLITENESS) {
209
+ ensureRegion(politeness);
210
+ }
211
+ },
212
+ takePending() {
213
+ const taken = [];
214
+ for (const politeness of POLITENESS) {
215
+ const write = cancel(politeness);
216
+ if (write) {
217
+ taken.push({ message: write.message, politeness });
218
+ }
219
+ }
220
+ return taken;
221
+ },
222
+ destroy() {
223
+ for (const politeness of POLITENESS) {
224
+ cancel(politeness);
225
+ regions[politeness]?.remove();
226
+ regions[politeness] = null;
227
+ }
228
+ },
229
+ };
230
+ }
231
+
232
+ // A screen reader commonly misses a change to a live region that entered the
233
+ // DOM a frame earlier. A modal pair is created on the announcement that needs
234
+ // it, so its first write waits until the regions have settled.
235
+ const FIRST_MODAL_WRITE_DELAY_MS = 100;
236
+ const MODAL_SELECTOR = '[aria-modal="true"]';
237
+ /** A modal container a screen reader currently reads. */
238
+ function isOpenModal(el) {
239
+ if (!el.isConnected || el.getAttribute('aria-modal') !== 'true') {
240
+ return false;
241
+ }
242
+ return !(el instanceof HTMLDialogElement) || el.open;
243
+ }
244
+ // Overlays such as CngxDialog are appended to the body, and a nested modal
245
+ // follows its container, so document order is stacking order: the last open
246
+ // modal outside an inert subtree is the one a screen reader still reads.
247
+ function topmostOpenModal(doc) {
248
+ const open = Array.from(doc.querySelectorAll(MODAL_SELECTOR)).filter((el) => isOpenModal(el) && !el.closest('[inert]'));
249
+ return open.at(-1) ?? null;
250
+ }
138
251
  /**
139
252
  * Imperative, reusable polite/assertive live-region announcer.
140
253
  *
@@ -152,6 +265,24 @@ const CLEAR_DELAY_MS = 16;
152
265
  * polite one. Per region, the text is cleared and re-set one frame later so an
153
266
  * identical consecutive message is still re-read by the screen reader.
154
267
  *
268
+ * A modal dialog hides everything outside it from assistive technology, so a
269
+ * body region is silent while one is open. Pass the announcing element as the
270
+ * third argument and the message goes to a region pair inside its enclosing
271
+ * `[aria-modal="true"]` container instead; without a modal ancestor it goes to
272
+ * the body regions as before. When another modal covers that one, the topmost
273
+ * open modal receives it: the last `[aria-modal="true"]` element in document
274
+ * order that is open and not inside an `[inert]` subtree. That covers a modal
275
+ * nested inside the scope's own one as well as a sibling stacked on top of it,
276
+ * which is how `CngxDialog` stacks dialogs (every host is appended to
277
+ * `document.body`); a covered modal is hidden from assistive technology, so
278
+ * its region would be silent. The pair is created with both regions on first
279
+ * use and its first write waits until the regions have settled in the DOM. A
280
+ * message still pending when its modal closes moves to the next enclosing open
281
+ * modal, else to the topmost modal still open, else to the body regions, and
282
+ * the pair is removed. The scope is opt-in per call - an unscoped announcement
283
+ * never guesses a modal. {@link injectScopedLiveRegion} is the injection-time
284
+ * alternative when the caller knows its overlay host up front.
285
+ *
155
286
  * SSR-safe: all DOM access is guarded by `isPlatformBrowser`; on the server
156
287
  * `announce()` is a no-op and no region is created.
157
288
  *
@@ -159,6 +290,7 @@ const CLEAR_DELAY_MS = 16;
159
290
  * const announcer = inject(CngxLiveAnnouncer);
160
291
  * announcer.announce('Copied');
161
292
  * announcer.announce('Save failed', 'assertive');
293
+ * announcer.announce('Alert dismissed', 'polite', hostElement); // inside a modal
162
294
  * ```
163
295
  *
164
296
  * @category common/a11y
@@ -170,12 +302,13 @@ const CLEAR_DELAY_MS = 16;
170
302
  class CngxLiveAnnouncer {
171
303
  doc = inject(DOCUMENT);
172
304
  isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
173
- politeRegion = null;
174
- assertiveRegion = null;
175
- pending = {
176
- polite: null,
177
- assertive: null,
178
- };
305
+ regions = null;
306
+ /**
307
+ * One pair per open `aria-modal` container, released once it closes.
308
+ * `outer` is the container's parent at creation, the route for its unwritten
309
+ * messages when it is removed from the DOM.
310
+ */
311
+ modalRegions = new Map();
179
312
  /**
180
313
  * Announces `message` through the fixed-politeness live region.
181
314
  *
@@ -183,64 +316,103 @@ class CngxLiveAnnouncer {
183
316
  * @param politeness `'polite'` (default) queues after the current
184
317
  * utterance; `'assertive'` interrupts immediately. Each politeness owns its
185
318
  * own region, so the two never overwrite each other.
319
+ * @param scope The announcing element. When it sits inside an
320
+ * `[aria-modal="true"]` container, the message is written into a region
321
+ * inside the topmost open modal (that container unless another modal
322
+ * covers it), which a screen reader still reads while the modal hides the
323
+ * rest of the page. `null` / omitted: the body regions.
186
324
  */
187
- announce(message, politeness = 'polite') {
325
+ announce(message, politeness = 'polite', scope) {
188
326
  if (!this.isBrowser) {
189
327
  return;
190
328
  }
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);
329
+ this.releaseClosedModals();
330
+ this.route(scope, { message, politeness });
204
331
  }
205
332
  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
- }
333
+ this.regions?.destroy();
334
+ this.regions = null;
335
+ for (const { pair } of this.modalRegions.values()) {
336
+ pair.destroy();
212
337
  }
213
- this.politeRegion?.remove();
214
- this.assertiveRegion?.remove();
215
- this.politeRegion = null;
216
- this.assertiveRegion = null;
338
+ this.modalRegions.clear();
217
339
  }
218
- ensureRegion(politeness) {
219
- const existing = politeness === 'polite' ? this.politeRegion : this.assertiveRegion;
340
+ /**
341
+ * `fromModal` marks a message that was already scoped to a modal which has
342
+ * since closed: with no open modal around its new scope it still goes to the
343
+ * topmost open modal rather than to the silent body regions.
344
+ */
345
+ route(scope, announcement, fromModal = false) {
346
+ const modal = this.targetModal(scope, fromModal);
347
+ if (!modal) {
348
+ this.regions ??= createLiveRegionPair(this.doc.body, this.doc);
349
+ this.regions.announce(announcement.message, announcement.politeness);
350
+ return;
351
+ }
352
+ const existing = this.modalRegions.get(modal);
220
353
  if (existing) {
221
- return existing;
354
+ existing.pair.announce(announcement.message, announcement.politeness);
355
+ return;
222
356
  }
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;
357
+ const pair = createLiveRegionPair(modal, this.doc, (due) => this.redirectIfClosed(modal, due));
358
+ pair.ensure();
359
+ this.modalRegions.set(modal, { pair, outer: modal.parentElement });
360
+ pair.announce(announcement.message, announcement.politeness, FIRST_MODAL_WRITE_DELAY_MS);
361
+ }
362
+ /**
363
+ * The topmost open modal when `scope` sits in an open modal (or the message
364
+ * comes from a closed one), else `null` for the body regions. Falls back to
365
+ * the scope's own modal when no candidate outside an inert subtree is open.
366
+ */
367
+ targetModal(scope, fromModal) {
368
+ const own = this.enclosingOpenModal(scope);
369
+ if (!own && !fromModal) {
370
+ return null;
239
371
  }
240
- else {
241
- this.assertiveRegion = span;
372
+ return topmostOpenModal(this.doc) ?? own;
373
+ }
374
+ enclosingOpenModal(scope) {
375
+ let candidate = scope?.closest(MODAL_SELECTOR) ?? null;
376
+ while (candidate) {
377
+ if (candidate instanceof HTMLElement && isOpenModal(candidate)) {
378
+ return candidate;
379
+ }
380
+ candidate = candidate.parentElement?.closest(MODAL_SELECTOR) ?? null;
242
381
  }
243
- return span;
382
+ return null;
383
+ }
384
+ redirectIfClosed(modal, due) {
385
+ if (isOpenModal(modal)) {
386
+ return false;
387
+ }
388
+ const outer = this.outerOf(modal);
389
+ this.release(modal);
390
+ this.route(outer, due, true);
391
+ return true;
392
+ }
393
+ releaseClosedModals() {
394
+ for (const modal of Array.from(this.modalRegions.keys())) {
395
+ if (!isOpenModal(modal)) {
396
+ this.release(modal);
397
+ }
398
+ }
399
+ }
400
+ /** Drop the pair of a closed modal; its unwritten messages move outward. */
401
+ release(modal) {
402
+ const entry = this.modalRegions.get(modal);
403
+ if (!entry) {
404
+ return;
405
+ }
406
+ const outer = this.outerOf(modal);
407
+ this.modalRegions.delete(modal);
408
+ const unwritten = entry.pair.takePending();
409
+ entry.pair.destroy();
410
+ for (const announcement of unwritten) {
411
+ this.route(outer, announcement, true);
412
+ }
413
+ }
414
+ outerOf(modal) {
415
+ return modal.parentElement ?? this.modalRegions.get(modal)?.outer ?? null;
244
416
  }
245
417
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxLiveAnnouncer, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
246
418
  static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxLiveAnnouncer, providedIn: 'root' });
@@ -250,6 +422,69 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
250
422
  args: [{ providedIn: 'root' }]
251
423
  }] });
252
424
 
425
+ /**
426
+ * Create a polite + assertive live-region pair inside `host`.
427
+ *
428
+ * The scoped counterpart to {@link CngxLiveAnnouncer}: same regions, same
429
+ * clear-then-set timing, but appended to an overlay host instead of
430
+ * `document.body`. Use it for modal overlays: under `aria-modal` VoiceOver
431
+ * drops body-level live regions and speaks them late after the overlay
432
+ * closes, while a region inside the modal is spoken on every platform.
433
+ * Polite and assertive keep separate regions, so an assertive error never
434
+ * clobbers a polite status.
435
+ *
436
+ * Must run in an injection context; the regions are removed when that context
437
+ * is destroyed. No-op on the server.
438
+ *
439
+ * ```typescript
440
+ * private readonly region = injectScopedLiveRegion(inject(ElementRef).nativeElement);
441
+ *
442
+ * protected handleSaveFailed(): void {
443
+ * this.region.announce('Save failed', 'assertive');
444
+ * }
445
+ * ```
446
+ *
447
+ * @param host - Element that receives the two visually hidden regions.
448
+ *
449
+ * @category common/a11y
450
+ * @wcag AA
451
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/aria/scoped-live-region.ts
452
+ * @since 0.1.0
453
+ * @relatedTo CngxLiveAnnouncer, CngxLiveRegion
454
+ */
455
+ function injectScopedLiveRegion(host) {
456
+ const doc = inject(DOCUMENT);
457
+ const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
458
+ let pair = null;
459
+ const ensurePair = () => {
460
+ pair ??= createLiveRegionPair(host, doc);
461
+ return pair;
462
+ };
463
+ const region = {
464
+ announce(message, politeness = 'polite') {
465
+ if (!isBrowser) {
466
+ return;
467
+ }
468
+ ensurePair().announce(message, politeness);
469
+ },
470
+ ensure() {
471
+ if (!isBrowser) {
472
+ return;
473
+ }
474
+ ensurePair().ensure();
475
+ },
476
+ takePending() {
477
+ return pair?.takePending() ?? [];
478
+ },
479
+ destroy() {
480
+ pair?.destroy();
481
+ pair = null;
482
+ },
483
+ };
484
+ inject(DestroyRef).onDestroy(() => region.destroy());
485
+ return region;
486
+ }
487
+
253
488
  /**
254
489
  * Reactive autofocus for dynamically inserted elements.
255
490
  *
@@ -497,6 +732,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
497
732
  }]
498
733
  }], ctorParameters: () => [], propDecorators: { restoreOnDestroy: [{ type: i0.Input, args: [{ isSignal: true, alias: "restoreOnDestroy", required: false }] }], fallback: [{ type: i0.Input, args: [{ isSignal: true, alias: "fallback", required: false }] }] } });
499
734
 
735
+ /** @internal See {@link CngxFocusTrapDriver}. */
736
+ const CNGX_FOCUS_TRAP_DRIVER = new InjectionToken('CngxFocusTrapDriver');
500
737
  /**
501
738
  * Traps keyboard focus within the host element using the CDK `FocusTrap`.
502
739
  *
@@ -545,37 +782,72 @@ class CngxFocusTrap {
545
782
  enabled = input(false, ...(ngDevMode ? [{ debugName: "enabled" }] : /* istanbul ignore next */ []));
546
783
  /** Whether to auto-focus the first tabbable element when the trap activates. */
547
784
  autoFocus = input(true, ...(ngDevMode ? [{ debugName: "autoFocus" }] : /* istanbul ignore next */ []));
785
+ injector = inject(Injector);
786
+ resolvedDriver = undefined;
787
+ driver() {
788
+ if (this.resolvedDriver === undefined) {
789
+ this.resolvedDriver = this.injector.get(CNGX_FOCUS_TRAP_DRIVER, null, { self: true });
790
+ }
791
+ return this.resolvedDriver;
792
+ }
793
+ /**
794
+ * The enabled state the trap actually follows: a composer's driver
795
+ * (see {@link CngxFocusTrapDriver}) wins over the `[enabled]` input.
796
+ */
797
+ effectiveEnabled = computed(() => this.driver()?.focusTrapEnabled() ?? this.enabled(), ...(ngDevMode ? [{ debugName: "effectiveEnabled" }] : /* istanbul ignore next */ []));
548
798
  /**
549
- * Readable alias of `enabled` for `exportAs` consumers
799
+ * Readable alias of the effective enabled state for `exportAs` consumers
550
800
  * (`trap.isActive()` reads better than re-binding the input).
551
801
  */
552
- isActive = computed(() => this.enabled(), ...(ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []));
553
- trap;
802
+ isActive = computed(() => this.effectiveEnabled(), ...(ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []));
803
+ host = inject(ElementRef).nativeElement;
804
+ factory = inject(FocusTrapFactory);
805
+ trap = null;
554
806
  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.
807
+ // Track ONLY the effective enabled state: with autoFocus inside the
808
+ // tracked zone, flipping [autoFocus] while the trap is active would
809
+ // re-run the effect and yank focus back to the first tabbable element.
810
+ // The CDK calls are service work, not dependencies.
561
811
  effect(() => {
562
- const enabled = this.enabled();
812
+ const enabled = this.effectiveEnabled();
563
813
  untracked(() => {
564
- this.trap.enabled = enabled;
565
- if (enabled && this.autoFocus()) {
566
- void this.trap.focusFirstTabbableElementWhenReady();
814
+ if (!enabled && !this.trap) {
815
+ return;
816
+ }
817
+ const trap = this.ensureTrap();
818
+ trap.enabled = enabled;
819
+ if (enabled && !trap.hasAttached()) {
820
+ trap.attachAnchors();
821
+ }
822
+ if (enabled && (this.driver()?.focusTrapAutoFocus ?? this.autoFocus())) {
823
+ void trap.focusFirstTabbableElementWhenReady();
567
824
  }
568
825
  });
569
826
  });
570
- inject(DestroyRef).onDestroy(() => this.trap.destroy());
827
+ inject(DestroyRef).onDestroy(() => this.trap?.destroy());
571
828
  }
572
829
  /** Programmatically focus the first tabbable element within the trap. */
573
830
  focusFirst() {
574
- void this.trap.focusFirstTabbableElementWhenReady();
831
+ void this.ensureTrap().focusFirstTabbableElementWhenReady();
575
832
  }
576
833
  /** Programmatically focus the last tabbable element within the trap. */
577
834
  focusLast() {
578
- void this.trap.focusLastTabbableElementWhenReady();
835
+ void this.ensureTrap().focusLastTabbableElementWhenReady();
836
+ }
837
+ /**
838
+ * @internal Focus the first tabbable element right now, in the caller's
839
+ * stack. `focusFirst()` waits for the next render, which is too late for a
840
+ * composer that must move focus inside the user gesture that opened it.
841
+ * Returns `false` when nothing inside is tabbable.
842
+ */
843
+ focusFirstNow() {
844
+ return this.ensureTrap().focusFirstTabbableElement();
845
+ }
846
+ // Deferred anchors: the CDK sentinels are inserted on the first enable,
847
+ // so a trap that is never enabled leaves the DOM untouched.
848
+ ensureTrap() {
849
+ this.trap ??= this.factory.create(this.host, true);
850
+ return this.trap;
579
851
  }
580
852
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxFocusTrap, deps: [], target: i0.ɵɵFactoryTarget.Directive });
581
853
  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 });
@@ -1150,6 +1422,15 @@ class CngxActiveDescendant {
1150
1422
  * Ignored when `virtualCount` is unset.
1151
1423
  */
1152
1424
  windowStart = input(0, ...(ngDevMode ? [{ debugName: "windowStart" }] : /* istanbul ignore next */ []));
1425
+ /**
1426
+ * Equality used to find the previously active value again after the item
1427
+ * list changes. Defaults to `Object.is`; pass the same comparator as the
1428
+ * surrounding listbox / select when options are re-fetched as new objects
1429
+ * with equal identity, or the highlight drops on every refresh. The
1430
+ * parameters are typed `never` so a comparator over any value type binds
1431
+ * while the directive itself stays non-generic.
1432
+ */
1433
+ compareWith = input(Object.is, ...(ngDevMode ? [{ debugName: "compareWith" }] : /* istanbul ignore next */ []));
1153
1434
  /** Emitted when `activateCurrent()` is called with an active item. */
1154
1435
  activated = output();
1155
1436
  /** Emitted whenever the highlighted item changes. */
@@ -1170,8 +1451,6 @@ class CngxActiveDescendant {
1170
1451
  direction = injectDirection();
1171
1452
  /** Guards host attribute writes until after first render. */
1172
1453
  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
1454
  /** Index of an item that should be highlighted but is not in the DOM. */
1176
1455
  pendingHighlightState = signal(null, ...(ngDevMode ? [{ debugName: "pendingHighlightState" }] : /* istanbul ignore next */ []));
1177
1456
  pendingHighlight = this.pendingHighlightState.asReadonly();
@@ -1186,6 +1465,29 @@ class CngxActiveDescendant {
1186
1465
  }
1187
1466
  return this.registered().map(handleToItem);
1188
1467
  }, ...(ngDevMode ? [{ debugName: "resolvedItems" }] : /* istanbul ignore next */ []));
1468
+ /**
1469
+ * -1 means "no active item". Range is `[0, totalCount())`.
1470
+ *
1471
+ * Navigation writes the index; a change of the item space re-derives it.
1472
+ * The highlight follows its value, not its index: after the item list
1473
+ * changes, the previously active value is looked up again with
1474
+ * `compareWith`. Gone from a plain list means no highlight; in a virtual
1475
+ * window a value that merely scrolled out keeps its absolute index. The result is clamped to the new
1476
+ * item space, so the next arrow press never starts from a ghost index.
1477
+ */
1478
+ activeIndexState = linkedSignal({ ...(ngDevMode ? { debugName: "activeIndexState" } : /* istanbul ignore next */ {}), source: () => ({
1479
+ items: this.resolvedItems(),
1480
+ total: this.totalCount(),
1481
+ offset: this.windowOffset(),
1482
+ virtual: this.virtualCount() != null,
1483
+ compareWith: this.compareWith(),
1484
+ }),
1485
+ computation: (source, previous) => {
1486
+ if (!previous) {
1487
+ return -1;
1488
+ }
1489
+ return clampIndex(reResolveIndex(source, previous.source, previous.value), source.total);
1490
+ } });
1189
1491
  /** Current active index. `-1` when no item is highlighted. */
1190
1492
  activeIndex = computed(() => {
1191
1493
  const idx = this.activeIndexState();
@@ -1252,16 +1554,6 @@ class CngxActiveDescendant {
1252
1554
  }
1253
1555
  queueMicrotask(() => this.scrollActiveIntoView());
1254
1556
  });
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
1557
  inject(DestroyRef).onDestroy(() => {
1266
1558
  if (this.typeaheadTimer !== null) {
1267
1559
  clearTimeout(this.typeaheadTimer);
@@ -1540,7 +1832,7 @@ class CngxActiveDescendant {
1540
1832
  }
1541
1833
  }
1542
1834
  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 });
1835
+ 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 }, 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
1836
  }
1545
1837
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxActiveDescendant, decorators: [{
1546
1838
  type: Directive,
@@ -1553,7 +1845,34 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1553
1845
  '(keydown)': 'handleKeydown($event)',
1554
1846
  },
1555
1847
  }]
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 }] }] } });
1848
+ }], 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 }] }], 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 }] }] } });
1849
+ /**
1850
+ * @internal
1851
+ * Looks the previously active value up in the new item list. Unchanged items,
1852
+ * no previous highlight, or a previous index outside the old rendered window
1853
+ * keep the index as it is.
1854
+ */
1855
+ function reResolveIndex(source, previousSource, previousIndex) {
1856
+ if (previousSource.items === source.items || previousIndex < 0) {
1857
+ return previousIndex;
1858
+ }
1859
+ const previous = previousSource.items[previousIndex - previousSource.offset];
1860
+ if (!previous) {
1861
+ return previousIndex;
1862
+ }
1863
+ const match = source.items.findIndex((it) => source.compareWith(it.value, previous.value));
1864
+ if (match >= 0) {
1865
+ return match + source.offset;
1866
+ }
1867
+ return source.virtual ? previousIndex : -1;
1868
+ }
1869
+ /** @internal Pulls an index that ran past the item space back onto its last item. */
1870
+ function clampIndex(index, total) {
1871
+ if (index < total) {
1872
+ return index;
1873
+ }
1874
+ return total > 0 ? total - 1 : -1;
1875
+ }
1557
1876
  /** @internal */
1558
1877
  function handleToItem(handle) {
1559
1878
  return {
@@ -1665,5 +1984,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1665
1984
  * Generated bundle index. Do not edit.
1666
1985
  */
1667
1986
 
1668
- export { CNGX_AD_ITEM, CNGX_FOCUSABLE_SELECTOR, CngxActiveDescendant, CngxAriaExpanded, CngxAutofocus, CngxFocusRestore, CngxFocusTrap, CngxFocusVisible, CngxLiveAnnouncer, CngxLiveRegion, CngxReducedMotion, CngxRovingItem, CngxRovingTabindex };
1987
+ export { CNGX_AD_ITEM, CNGX_FOCUSABLE_SELECTOR, CNGX_FOCUS_TRAP_DRIVER, CngxActiveDescendant, CngxAriaExpanded, CngxAutofocus, CngxFocusRestore, CngxFocusTrap, CngxFocusVisible, CngxLiveAnnouncer, CngxLiveRegion, CngxReducedMotion, CngxRovingItem, CngxRovingTabindex, injectScopedLiveRegion };
1669
1988
  //# sourceMappingURL=cngx-common-a11y.mjs.map