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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/card/README.md +2 -1
  2. package/command/README.md +29 -0
  3. package/data/README.md +15 -3
  4. package/dialog/README.md +23 -1
  5. package/fesm2022/cngx-common-a11y.mjs +517 -184
  6. package/fesm2022/cngx-common-a11y.mjs.map +1 -1
  7. package/fesm2022/cngx-common-audio.mjs +62 -17
  8. package/fesm2022/cngx-common-audio.mjs.map +1 -1
  9. package/fesm2022/cngx-common-card.mjs +301 -46
  10. package/fesm2022/cngx-common-card.mjs.map +1 -1
  11. package/fesm2022/cngx-common-chart.mjs +1221 -479
  12. package/fesm2022/cngx-common-chart.mjs.map +1 -1
  13. package/fesm2022/cngx-common-command.mjs +97 -16
  14. package/fesm2022/cngx-common-command.mjs.map +1 -1
  15. package/fesm2022/cngx-common-data.mjs +1496 -499
  16. package/fesm2022/cngx-common-data.mjs.map +1 -1
  17. package/fesm2022/cngx-common-dialog.mjs +236 -61
  18. package/fesm2022/cngx-common-dialog.mjs.map +1 -1
  19. package/fesm2022/cngx-common-display.mjs +364 -93
  20. package/fesm2022/cngx-common-display.mjs.map +1 -1
  21. package/fesm2022/cngx-common-interactive.mjs +2040 -1046
  22. package/fesm2022/cngx-common-interactive.mjs.map +1 -1
  23. package/fesm2022/cngx-common-layout.mjs +955 -125
  24. package/fesm2022/cngx-common-layout.mjs.map +1 -1
  25. package/fesm2022/cngx-common-popover.mjs +1293 -89
  26. package/fesm2022/cngx-common-popover.mjs.map +1 -1
  27. package/fesm2022/cngx-common-stepper.mjs +997 -453
  28. package/fesm2022/cngx-common-stepper.mjs.map +1 -1
  29. package/fesm2022/cngx-common-tabs.mjs +1794 -1265
  30. package/fesm2022/cngx-common-tabs.mjs.map +1 -1
  31. package/fesm2022/cngx-common-timeline.mjs +151 -61
  32. package/fesm2022/cngx-common-timeline.mjs.map +1 -1
  33. package/fesm2022/cngx-common.mjs +1 -1
  34. package/interactive/README.md +15 -4
  35. package/layout/README.md +37 -1
  36. package/package.json +20 -7
  37. package/popover/README.md +58 -2
  38. package/schematics/collection.json +9 -0
  39. package/schematics/ng-add/index.js +9 -0
  40. package/schematics/ng-add/schema.json +91 -0
  41. package/schematics/package.json +3 -0
  42. package/stepper/README.md +11 -8
  43. package/theming/components/cngx-accordion.css +1 -1
  44. package/theming/components/cngx-backdrop.css +12 -0
  45. package/theming/components/cngx-button-toggle.css +29 -3
  46. package/theming/components/cngx-data-grid.css +168 -1
  47. package/theming/components/cngx-dialog.css +13 -0
  48. package/theming/components/cngx-listbox.css +21 -12
  49. package/theming/components/cngx-menu.css +56 -16
  50. package/theming/components/cngx-popover-sheet.css +402 -0
  51. package/theming/components/cngx-popover.css +28 -0
  52. package/theming/components/cngx-recycler-placeholder.css +196 -0
  53. package/theming/components/cngx-ripple.css +1 -1
  54. package/theming/components/cngx-slider.css +32 -1
  55. package/theming/components/cngx-tooltip.css +12 -0
  56. package/timeline/README.md +155 -0
  57. package/types/cngx-common-a11y.d.ts +205 -28
  58. package/types/cngx-common-card.d.ts +201 -17
  59. package/types/cngx-common-chart.d.ts +345 -48
  60. package/types/cngx-common-command.d.ts +50 -10
  61. package/types/cngx-common-data.d.ts +743 -92
  62. package/types/cngx-common-dialog.d.ts +161 -10
  63. package/types/cngx-common-display.d.ts +356 -142
  64. package/types/cngx-common-interactive.d.ts +910 -226
  65. package/types/cngx-common-layout.d.ts +603 -32
  66. package/types/cngx-common-popover.d.ts +612 -49
  67. package/types/cngx-common-stepper.d.ts +526 -237
  68. package/types/cngx-common-tabs.d.ts +358 -75
  69. package/types/cngx-common-timeline.d.ts +108 -22
@@ -1,12 +1,14 @@
1
1
  import * as i0 from '@angular/core';
2
- import { input, output, inject, ElementRef, signal, afterNextRender, effect, Directive, computed, DestroyRef, isSignal, untracked, isDevMode, model, contentChild, ViewEncapsulation, ChangeDetectionStrategy, Component } from '@angular/core';
3
- import { DOCUMENT, NgTemplateOutlet } from '@angular/common';
4
- import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
5
- import { fromEvent } from 'rxjs';
2
+ import { input, output, inject, ElementRef, signal, afterNextRender, effect, Directive, computed, untracked, DestroyRef, InjectionToken, PLATFORM_ID, model, TemplateRef, contentChild, ViewEncapsulation, ChangeDetectionStrategy, Component } from '@angular/core';
3
+ import { DOCUMENT, isPlatformBrowser, NgTemplateOutlet } from '@angular/common';
4
+ import { toObservable, outputToObservable, takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
5
+ import { switchMap, fromEvent } from 'rxjs';
6
+ import { createTransitionTracker, observeMediaQuery, createMediaQuerySignal, coerceSignal, createOverrideMerge } from '@cngx/core/utils';
6
7
  import * as i1 from '@cngx/common/a11y';
7
8
  import { CngxFocusTrap } from '@cngx/common/a11y';
8
- import { observeMediaQuery, createMediaQuerySignal } from '@cngx/core/utils';
9
+ import { cngxDevWarn } from '@cngx/utils';
9
10
  import { Router, ActivatedRoute } from '@angular/router';
11
+ import { createLanguageSection } from '@cngx/core/i18n';
10
12
 
11
13
  /**
12
14
  * Manages backdrop overlay behavior: visibility, click-to-close, and
@@ -14,7 +16,12 @@ import { Router, ActivatedRoute } from '@angular/router';
14
16
  *
15
17
  * When visible, all sibling elements of the host receive the `inert`
16
18
  * attribute, preventing focus and interaction behind the backdrop.
17
- * This is critical for a11y in modal/drawer overlays.
19
+ * This is critical for a11y in modal/drawer overlays. A sibling drawer
20
+ * panel (`.cngx-drawer-panel`) is excluded - it is the surface the
21
+ * backdrop guards, not content behind it. Siblings that already carry
22
+ * `inert` are left alone, so a consumer-set `inert` survives the
23
+ * show/hide cycle. The sibling set is re-queried on every show, so
24
+ * siblings rendered after init are covered too.
18
25
  *
19
26
  * The directive is purely behavioral - it toggles the
20
27
  * `.cngx-backdrop--visible` class and `aria-hidden` attribute. Visual
@@ -76,18 +83,28 @@ class CngxBackdrop {
76
83
  /** Emitted when the backdrop is clicked (and `closeOnClick` is true). */
77
84
  backdropClick = output();
78
85
  el = inject((ElementRef));
79
- siblings = signal([], ...(ngDevMode ? [{ debugName: "siblings" }] : /* istanbul ignore next */ []));
86
+ domReady = signal(false, ...(ngDevMode ? [{ debugName: "domReady" }] : /* istanbul ignore next */ []));
80
87
  constructor() {
81
- afterNextRender(() => {
88
+ afterNextRender(() => this.domReady.set(true));
89
+ effect((onCleanup) => {
90
+ if (!this.domReady() || !this.visible()) {
91
+ return;
92
+ }
93
+ // Re-queried on every show: siblings rendered after init (@if/@defer)
94
+ // must be inerted too. The drawer panel keeps working - it is the
95
+ // surface the backdrop guards, not content behind it.
82
96
  const el = this.el.nativeElement;
83
97
  const parent = el.parentElement;
84
- this.siblings.set(parent
85
- ? Array.from(parent.children).filter((child) => child !== el && child instanceof HTMLElement)
86
- : []);
87
- });
88
- effect(() => {
89
- const visible = this.visible();
90
- this.siblings().forEach((el) => visible ? el.setAttribute('inert', '') : el.removeAttribute('inert'));
98
+ // skip siblings that are already inert - removing it on cleanup
99
+ // would clobber a consumer-set attribute that predated the show
100
+ const targets = parent
101
+ ? Array.from(parent.children).filter((child) => child !== el &&
102
+ child instanceof HTMLElement &&
103
+ !child.classList.contains('cngx-drawer-panel') &&
104
+ !child.hasAttribute('inert'))
105
+ : [];
106
+ targets.forEach((target) => target.setAttribute('inert', ''));
107
+ onCleanup(() => targets.forEach((target) => target.removeAttribute('inert')));
91
108
  });
92
109
  }
93
110
  /** @internal */
@@ -97,7 +114,7 @@ class CngxBackdrop {
97
114
  }
98
115
  }
99
116
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxBackdrop, deps: [], target: i0.ɵɵFactoryTarget.Directive });
100
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxBackdrop, isStandalone: true, selector: "[cngxBackdrop]", inputs: { visible: { classPropertyName: "visible", publicName: "cngxBackdrop", isSignal: true, isRequired: false, transformFunction: null }, closeOnClick: { classPropertyName: "closeOnClick", publicName: "closeOnClick", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { backdropClick: "backdropClick" }, host: { listeners: { "click": "handleHostClick()" }, properties: { "class.cngx-backdrop--visible": "visible()", "attr.aria-hidden": "!visible()" } }, exportAs: ["cngxBackdrop"], ngImport: i0 });
117
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxBackdrop, isStandalone: true, selector: "[cngxBackdrop]", inputs: { visible: { classPropertyName: "visible", publicName: "cngxBackdrop", isSignal: true, isRequired: false, transformFunction: null }, closeOnClick: { classPropertyName: "closeOnClick", publicName: "closeOnClick", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { backdropClick: "backdropClick" }, host: { attributes: { "aria-hidden": "true" }, listeners: { "click": "handleHostClick()" }, properties: { "class.cngx-backdrop--visible": "visible()" } }, exportAs: ["cngxBackdrop"], ngImport: i0 });
101
118
  }
102
119
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxBackdrop, decorators: [{
103
120
  type: Directive,
@@ -107,7 +124,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
107
124
  standalone: true,
108
125
  host: {
109
126
  '[class.cngx-backdrop--visible]': 'visible()',
110
- '[attr.aria-hidden]': '!visible()',
127
+ 'aria-hidden': 'true',
111
128
  '(click)': 'handleHostClick()',
112
129
  },
113
130
  }]
@@ -165,8 +182,11 @@ class CngxDrawer {
165
182
  openedChange = output();
166
183
  /** Emitted when the drawer closes. Convenience shorthand for close-only listeners. */
167
184
  closed = output();
168
- /** Opens the drawer. */
185
+ /** Opens the drawer. No-op when already open. */
169
186
  open() {
187
+ if (this.opened()) {
188
+ return;
189
+ }
170
190
  this.openedState.set(true);
171
191
  this.openedChange.emit(true);
172
192
  }
@@ -212,10 +232,19 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
212
232
  * the `[enabled]` and `[autoFocus]` inputs from the template.
213
233
  *
214
234
  * Optionally closes the drawer when the user clicks outside the panel
215
- * (`closeOnClickOutside`, default `true`).
235
+ * (`closeOnClickOutside`, default `true`). The click that opened the
236
+ * drawer never counts as an outside click. While closed (except in
237
+ * `side` mode) the panel is `aria-hidden` AND `inert`, so its focusable
238
+ * children are unreachable for keyboard and AT alike. On close, focus
239
+ * returns to the element that was focused when the drawer opened -
240
+ * unless the user moved focus to another focusable element themselves
241
+ * (a click on a focusable outside target keeps its focus).
242
+ *
243
+ * The `role` input defaults to `complementary`. On a `<nav>` host pass
244
+ * `[role]="null"` so the implicit navigation landmark survives:
216
245
  *
217
246
  * ```html
218
- * <nav [cngxDrawerPanel]="drawer" position="left" mode="over"
247
+ * <nav [cngxDrawerPanel]="drawer" position="left" mode="over" [role]="null"
219
248
  * [enabled]="drawer.opened()" [autoFocus]="true">
220
249
  * <a href="/home">Home</a>
221
250
  * </nav>
@@ -247,16 +276,69 @@ class CngxDrawerPanel {
247
276
  mode = input('over', ...(ngDevMode ? [{ debugName: "mode" }] : /* istanbul ignore next */ []));
248
277
  /** Whether clicking outside the panel closes the drawer. */
249
278
  closeOnClickOutside = input(true, ...(ngDevMode ? [{ debugName: "closeOnClickOutside" }] : /* istanbul ignore next */ []));
279
+ /**
280
+ * Landmark role rendered on the panel. Defaults to `complementary`;
281
+ * pass `navigation` for nav drawers or `null` to keep the element's
282
+ * implicit role (e.g. on a `<nav>` host).
283
+ */
284
+ role = input('complementary', ...(ngDevMode ? [{ debugName: "role" }] : /* istanbul ignore next */ []));
250
285
  /** Whether the drawer is currently open (derived from the drawer ref). In `side` mode, always `true`. */
251
286
  isOpen = computed(() => this.mode() === 'side' || this.drawerRef().opened(), ...(ngDevMode ? [{ debugName: "isOpen" }] : /* istanbul ignore next */ []));
287
+ suppressOutsideClick = false;
288
+ restoreTarget = null;
252
289
  constructor() {
253
290
  const doc = inject(DOCUMENT);
291
+ const el = inject((ElementRef));
292
+ // Focus restoration: closing puts `inert` on the panel, which would
293
+ // silently drop focus to <body>. Capture the focused element at the
294
+ // open transition and hand focus back at the close transition when
295
+ // focus is still inside the panel (Escape) or already fell to <body>
296
+ // (outside click on a non-focusable area). A focusable outside target
297
+ // the user clicked keeps its focus.
298
+ const openTransition = createTransitionTracker(() => this.isOpen());
299
+ effect(() => {
300
+ const open = openTransition.current();
301
+ const wasOpen = openTransition.previous();
302
+ if (open === wasOpen) {
303
+ return;
304
+ }
305
+ untracked(() => {
306
+ if (open) {
307
+ const active = doc.activeElement;
308
+ this.restoreTarget = active instanceof HTMLElement ? active : null;
309
+ return;
310
+ }
311
+ const active = doc.activeElement;
312
+ const focusLost = active === null ||
313
+ active === doc.body ||
314
+ el.nativeElement.contains(active);
315
+ if (focusLost && this.restoreTarget?.isConnected) {
316
+ this.restoreTarget.focus();
317
+ }
318
+ this.restoreTarget = null;
319
+ });
320
+ });
321
+ // A click on a toggle OUTSIDE the container opens the drawer and then
322
+ // bubbles on to the document listener below within the same dispatch -
323
+ // without suppression it would close its own drawer instantly. The
324
+ // openedChange emit is synchronous inside that dispatch; the flag is
325
+ // lifted on the next macrotask, after the bubble phase has finished
326
+ // (a microtask checkpoint can run between listeners of a native event).
327
+ toObservable(this.drawerRef)
328
+ .pipe(switchMap((drawer) => outputToObservable(drawer.openedChange)), takeUntilDestroyed())
329
+ .subscribe((opened) => {
330
+ if (opened) {
331
+ this.suppressOutsideClick = true;
332
+ setTimeout(() => (this.suppressOutsideClick = false));
333
+ }
334
+ });
254
335
  // Hit-test against the container, not the panel - toggle buttons and backdrops
255
336
  // sit inside the container and must not count as outside clicks.
256
337
  fromEvent(doc, 'click')
257
338
  .pipe(takeUntilDestroyed())
258
339
  .subscribe((e) => {
259
- if (this.mode() !== 'side' &&
340
+ if (!this.suppressOutsideClick &&
341
+ this.mode() !== 'side' &&
260
342
  this.isOpen() &&
261
343
  this.closeOnClickOutside() &&
262
344
  !this.drawerRef().elementRef.nativeElement.contains(e.target)) {
@@ -265,7 +347,7 @@ class CngxDrawerPanel {
265
347
  });
266
348
  }
267
349
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxDrawerPanel, deps: [], target: i0.ɵɵFactoryTarget.Directive });
268
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxDrawerPanel, isStandalone: true, selector: "[cngxDrawerPanel]", inputs: { drawerRef: { classPropertyName: "drawerRef", publicName: "cngxDrawerPanel", isSignal: true, isRequired: true, transformFunction: null }, position: { classPropertyName: "position", publicName: "position", isSignal: true, isRequired: false, transformFunction: null }, mode: { classPropertyName: "mode", publicName: "mode", isSignal: true, isRequired: false, transformFunction: null }, closeOnClickOutside: { classPropertyName: "closeOnClickOutside", publicName: "closeOnClickOutside", isSignal: true, isRequired: false, transformFunction: null } }, host: { attributes: { "role": "complementary" }, properties: { "class.cngx-drawer-panel": "true", "class.cngx-drawer-panel--open": "isOpen()", "class.cngx-drawer-panel--left": "position() === 'left'", "class.cngx-drawer-panel--right": "position() === 'right'", "class.cngx-drawer-panel--top": "position() === 'top'", "class.cngx-drawer-panel--bottom": "position() === 'bottom'", "class.cngx-drawer-panel--over": "mode() === 'over'", "class.cngx-drawer-panel--push": "mode() === 'push'", "class.cngx-drawer-panel--side": "mode() === 'side'", "attr.aria-hidden": "mode() === 'side' ? null : !isOpen()" } }, exportAs: ["cngxDrawerPanel"], hostDirectives: [{ directive: i1.CngxFocusTrap, inputs: ["enabled", "enabled", "autoFocus", "autoFocus"] }], ngImport: i0 });
350
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxDrawerPanel, isStandalone: true, selector: "[cngxDrawerPanel]", inputs: { drawerRef: { classPropertyName: "drawerRef", publicName: "cngxDrawerPanel", isSignal: true, isRequired: true, transformFunction: null }, position: { classPropertyName: "position", publicName: "position", isSignal: true, isRequired: false, transformFunction: null }, mode: { classPropertyName: "mode", publicName: "mode", isSignal: true, isRequired: false, transformFunction: null }, closeOnClickOutside: { classPropertyName: "closeOnClickOutside", publicName: "closeOnClickOutside", isSignal: true, isRequired: false, transformFunction: null }, role: { classPropertyName: "role", publicName: "role", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "class.cngx-drawer-panel": "true", "class.cngx-drawer-panel--open": "isOpen()", "class.cngx-drawer-panel--left": "position() === 'left'", "class.cngx-drawer-panel--right": "position() === 'right'", "class.cngx-drawer-panel--top": "position() === 'top'", "class.cngx-drawer-panel--bottom": "position() === 'bottom'", "class.cngx-drawer-panel--over": "mode() === 'over'", "class.cngx-drawer-panel--push": "mode() === 'push'", "class.cngx-drawer-panel--side": "mode() === 'side'", "attr.aria-hidden": "mode() !== 'side' && !isOpen() ? true : null", "attr.inert": "mode() !== 'side' && !isOpen() ? '' : null", "attr.role": "role()" } }, exportAs: ["cngxDrawerPanel"], hostDirectives: [{ directive: i1.CngxFocusTrap, inputs: ["enabled", "enabled", "autoFocus", "autoFocus"] }], ngImport: i0 });
269
351
  }
270
352
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxDrawerPanel, decorators: [{
271
353
  type: Directive,
@@ -284,11 +366,12 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
284
366
  '[class.cngx-drawer-panel--over]': "mode() === 'over'",
285
367
  '[class.cngx-drawer-panel--push]': "mode() === 'push'",
286
368
  '[class.cngx-drawer-panel--side]': "mode() === 'side'",
287
- '[attr.aria-hidden]': "mode() === 'side' ? null : !isOpen()",
288
- role: 'complementary',
369
+ '[attr.aria-hidden]': "mode() !== 'side' && !isOpen() ? true : null",
370
+ '[attr.inert]': "mode() !== 'side' && !isOpen() ? '' : null",
371
+ '[attr.role]': 'role()',
289
372
  },
290
373
  }]
291
- }], ctorParameters: () => [], propDecorators: { drawerRef: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxDrawerPanel", required: true }] }], position: [{ type: i0.Input, args: [{ isSignal: true, alias: "position", required: false }] }], mode: [{ type: i0.Input, args: [{ isSignal: true, alias: "mode", required: false }] }], closeOnClickOutside: [{ type: i0.Input, args: [{ isSignal: true, alias: "closeOnClickOutside", required: false }] }] } });
374
+ }], ctorParameters: () => [], propDecorators: { drawerRef: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxDrawerPanel", required: true }] }], position: [{ type: i0.Input, args: [{ isSignal: true, alias: "position", required: false }] }], mode: [{ type: i0.Input, args: [{ isSignal: true, alias: "mode", required: false }] }], closeOnClickOutside: [{ type: i0.Input, args: [{ isSignal: true, alias: "closeOnClickOutside", required: false }] }], role: [{ type: i0.Input, args: [{ isSignal: true, alias: "role", required: false }] }] } });
292
375
 
293
376
  /**
294
377
  * Marks the main content area adjacent to a drawer panel.
@@ -405,8 +488,13 @@ class CngxIntersectionObserver {
405
488
  const rootMargin = this.rootMargin();
406
489
  const threshold = this.threshold();
407
490
  const resolvedRoot = root ? this.doc.querySelector(root) : null;
491
+ if (typeof ngDevMode !== 'undefined' && ngDevMode && root && !resolvedRoot) {
492
+ cngxDevWarn('CNGX1032', `[cngxIntersectionObserver] root selector "${root}" matched no element - ` +
493
+ 'falling back to the viewport. A late-rendered root needs a re-bind of [root].');
494
+ }
408
495
  const observer = new IntersectionObserver((entries) => {
409
- const entry = entries[0];
496
+ // batched records arrive oldest-first; only the newest reflects reality
497
+ const entry = entries[entries.length - 1];
410
498
  const wasIntersecting = this.entryState()?.isIntersecting ?? false;
411
499
  this.entryState.set(entry);
412
500
  this.intersectionChange.emit(entry);
@@ -533,13 +621,16 @@ function injectMediaQuery(query) {
533
621
  * not provided. Mirrors {@link warnTabsRouterAbsent} in `@cngx/common/tabs`
534
622
  * so the message stays identical across the two sync surfaces; only the
535
623
  * `enables` clause differs. A deliberate small copy rather than a shared
536
- * import - sharing would force the helper onto a `public-api.ts`, and `warn*`
537
- * matches no approved public-API prefix.
624
+ * import - sharing would force the helper onto a `public-api.ts`, and
625
+ * `warn*` matches no approved public-API prefix.
538
626
  *
539
627
  * @internal
540
628
  */
541
- function warnRouterAbsent(directive, enables) {
542
- console.warn(`${directive}: no Router available - directive is a no-op. ` +
629
+ function warnRouterAbsent(enables) {
630
+ if (!(typeof ngDevMode !== 'undefined' && ngDevMode)) {
631
+ return;
632
+ }
633
+ cngxDevWarn('CNGX1031', `injectQueryParamSync(): no Router / ActivatedRoute available - the URL sync is a no-op. ` +
543
634
  `Provide @angular/router via provideRouter(...) to enable ${enables}.`);
544
635
  }
545
636
 
@@ -572,12 +663,16 @@ function warnRouterAbsent(directive, enables) {
572
663
  */
573
664
  function injectQueryParamSync(state, opts) {
574
665
  const router = inject(Router, { optional: true });
575
- if (!router) {
576
- warnRouterAbsent('injectQueryParamSync', 'query-param URL sync');
666
+ // Router is providedIn: 'root' and resolves without provideRouter(...);
667
+ // ActivatedRoute does not, so it is the "router is set up" signal.
668
+ const route = inject(ActivatedRoute, { optional: true });
669
+ if (!router || !route) {
670
+ if (typeof ngDevMode !== 'undefined' && ngDevMode) {
671
+ warnRouterAbsent('query-param URL sync');
672
+ }
577
673
  return;
578
674
  }
579
- const route = inject(ActivatedRoute);
580
- const paramSignal = isSignal(opts.param) ? opts.param : signal(opts.param);
675
+ const paramSignal = coerceSignal(opts.param);
581
676
  const serialize = opts.serialize ?? ((value) => (value ? 'open' : null));
582
677
  const deserialize = opts.deserialize ?? ((raw) => (raw != null));
583
678
  // Closure bookkeeping, seeded from the initial URL read. `lastWritten` is
@@ -662,6 +757,75 @@ function injectQueryParamSync(state, opts) {
662
757
  });
663
758
  }
664
759
 
760
+ /**
761
+ * Subscribes `apply` to size changes of `element` on `host`.
762
+ *
763
+ * Re-applies on every observation and returns the teardown that disconnects
764
+ * the observer. On a host without `ResizeObserver` (SSR, jsdom) nothing is
765
+ * wired, `apply` never fires, and the returned teardown is a no-op. Unlike the
766
+ * media-query twin there is no synchronous seed: the first size is whatever the
767
+ * observer reports after the next layout.
768
+ *
769
+ * Reach for this low-level form when the observed element or the box model is
770
+ * reactive and the subscription must follow it (re-wire per `effect` run via
771
+ * `onCleanup`); for a static target, {@link createResizeSignal} owns the
772
+ * teardown via `DestroyRef`.
773
+ *
774
+ * @param host The window-like object to read `ResizeObserver` from.
775
+ * @param element The element to observe.
776
+ * @param box Which box model to report.
777
+ * @param apply Receives the first entry of every observation batch.
778
+ * @returns Teardown that disconnects the observer.
779
+ * @category common/layout/observers
780
+ * @relatedTo createResizeSignal, observeMediaQuery
781
+ * @since 0.1.0
782
+ */
783
+ function observeResize(host, element, box, apply) {
784
+ if (!host || typeof host.ResizeObserver !== 'function') {
785
+ return () => undefined;
786
+ }
787
+ const observer = new host.ResizeObserver((entries) => apply(entries[0]));
788
+ observer.observe(element, { box });
789
+ return () => observer.disconnect();
790
+ }
791
+ /**
792
+ * Creates a `Signal<ResizeObserverEntry | null>` that carries the most recent
793
+ * observation of `element`, `null` until the first one arrives.
794
+ *
795
+ * Disconnects when `destroyRef` is destroyed. On a host without
796
+ * `ResizeObserver` (SSR, jsdom) the signal stays `null` and no observer is
797
+ * created, so it never throws off the browser.
798
+ *
799
+ * This is the shared kernel behind `CngxResizeObserver` and
800
+ * `createContainerSize`; consumers that hand-roll a `ResizeObserver` should
801
+ * route through it instead.
802
+ *
803
+ * ```typescript
804
+ * const entry = createResizeSignal(
805
+ * host,
806
+ * 'border-box',
807
+ * inject(DestroyRef),
808
+ * inject(DOCUMENT).defaultView,
809
+ * );
810
+ * const width = computed(() => entry()?.borderBoxSize[0]?.inlineSize ?? 0);
811
+ * ```
812
+ *
813
+ * @param element The element to observe.
814
+ * @param box Which box model to report.
815
+ * @param destroyRef Scope whose destruction disconnects the observer.
816
+ * @param host The window-like object to read `ResizeObserver` from.
817
+ * @returns A readonly signal carrying the latest entry.
818
+ * @category common/layout/observers
819
+ * @relatedTo observeResize, createMediaQuerySignal
820
+ * @since 0.1.0
821
+ */
822
+ function createResizeSignal(element, box, destroyRef, host) {
823
+ const entry = signal(null, ...(ngDevMode ? [{ debugName: "entry" }] : /* istanbul ignore next */ []));
824
+ const unsubscribe = observeResize(host, element, box, (value) => entry.set(value));
825
+ destroyRef.onDestroy(unsubscribe);
826
+ return entry.asReadonly();
827
+ }
828
+
665
829
  /**
666
830
  * Observes size changes of the host element via the `ResizeObserver` API.
667
831
  *
@@ -710,18 +874,16 @@ class CngxResizeObserver {
710
874
  el = inject((ElementRef));
711
875
  constructor() {
712
876
  const win = inject(DOCUMENT).defaultView;
713
- if (!win) {
714
- return;
715
- }
716
- const observer = new win.ResizeObserver((entries) => {
717
- this.entryState.set(entries[0]);
718
- this.resize.emit(entries[0]);
719
- });
720
- effect(() => {
721
- observer.disconnect();
722
- observer.observe(this.el.nativeElement, { box: this.box() });
877
+ // One subscription per `box` value: `onCleanup` disconnects the previous
878
+ // observer before `observeResize` wires the next, which is also the
879
+ // teardown on destroy. The kernel no-ops when the host ships no
880
+ // `ResizeObserver` (SSR, jsdom), so no host guard is needed here.
881
+ effect((onCleanup) => {
882
+ onCleanup(observeResize(win, this.el.nativeElement, this.box(), (entry) => {
883
+ this.entryState.set(entry);
884
+ this.resize.emit(entry);
885
+ }));
723
886
  });
724
- inject(DestroyRef).onDestroy(() => observer.disconnect());
725
887
  }
726
888
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxResizeObserver, deps: [], target: i0.ɵɵFactoryTarget.Directive });
727
889
  static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxResizeObserver, isStandalone: true, selector: "[cngxResizeObserver]", inputs: { box: { classPropertyName: "box", publicName: "box", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { resize: "resize" }, exportAs: ["cngxResizeObserver"], ngImport: i0 });
@@ -735,6 +897,187 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
735
897
  }]
736
898
  }], ctorParameters: () => [], propDecorators: { box: [{ type: i0.Input, args: [{ isSignal: true, alias: "box", required: false }] }], resize: [{ type: i0.Output, args: ["resize"] }] } });
737
899
 
900
+ /**
901
+ * The nearest query container declared by {@link CngxContainer}.
902
+ *
903
+ * Deliberately has no root factory: absence is meaningful. A component that
904
+ * needs a container and finds none must say so (a dev-mode warning), not
905
+ * silently observe itself.
906
+ *
907
+ * @category common/layout/observers
908
+ * @since 0.1.0
909
+ */
910
+ const CNGX_CONTAINER_SIZE = new InjectionToken('CNGX_CONTAINER_SIZE');
911
+ /**
912
+ * Creates a {@link CngxContainerSize} over `element`.
913
+ *
914
+ * Observes the border box, so the reported size matches what an
915
+ * `inline-size` container query measures. The `property()` reads are plain
916
+ * `computed()`s over the same resize signal - the browser has already
917
+ * re-evaluated every container query by the time a `ResizeObserver` callback
918
+ * runs, so the read returns the current value without a second scheduling hop.
919
+ *
920
+ * @param element The container host.
921
+ * @param destroyRef Scope whose destruction disconnects the observer.
922
+ * @param win The window-like object providing `ResizeObserver` and `getComputedStyle`.
923
+ * @category common/layout/observers
924
+ * @relatedTo injectContainerSize, CngxContainer
925
+ * @since 0.1.0
926
+ */
927
+ function createContainerSize(element, destroyRef, win) {
928
+ const entry = createResizeSignal(element, 'border-box', destroyRef, win);
929
+ const inlineSize = computed(() => entry()?.borderBoxSize?.[0]?.inlineSize ?? 0, ...(ngDevMode ? [{ debugName: "inlineSize" }] : /* istanbul ignore next */ []));
930
+ const blockSize = computed(() => entry()?.borderBoxSize?.[0]?.blockSize ?? 0, ...(ngDevMode ? [{ debugName: "blockSize" }] : /* istanbul ignore next */ []));
931
+ const isReady = computed(() => entry() !== null, ...(ngDevMode ? [{ debugName: "isReady" }] : /* istanbul ignore next */ []));
932
+ // Weak on the element: the container outlives descendants that get
933
+ // destroyed, so a strong Map would pin every dead node it ever read.
934
+ const cache = new WeakMap();
935
+ const property = (name, on, pseudo) => {
936
+ const target = on ?? element;
937
+ let byName = cache.get(target);
938
+ if (!byName) {
939
+ byName = new Map();
940
+ cache.set(target, byName);
941
+ }
942
+ const key = `${pseudo ?? ''}|${name}`;
943
+ const cached = byName.get(key);
944
+ if (cached) {
945
+ return cached;
946
+ }
947
+ // A DOM read inside a computed() is deliberate here, not an oversight: the
948
+ // only tracked dependency is the resize entry, and a ResizeObserver
949
+ // callback runs after layout, when every container query has already been
950
+ // re-evaluated. The read is therefore idempotent for a given entry and
951
+ // never forces a recalc of its own. An effect writing into a signal would
952
+ // add a scheduling hop for nothing.
953
+ const value = computed(() => {
954
+ if (entry() === null || !win?.getComputedStyle) {
955
+ return '';
956
+ }
957
+ return win
958
+ .getComputedStyle(target, pseudo ?? null)
959
+ .getPropertyValue(name)
960
+ .trim();
961
+ }, ...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
962
+ byName.set(key, value);
963
+ return value;
964
+ };
965
+ return { inlineSize, blockSize, isReady, property };
966
+ }
967
+ /**
968
+ * Reads the nearest query container declared by a `[cngxContainer]` ancestor,
969
+ * or observes `target` (default: the host element) when there is none.
970
+ *
971
+ * Use it where a component must branch structurally on the width it was given
972
+ * - a different template, a focus move, an `aria-modal` flip. Purely visual
973
+ * adaptation needs no TypeScript at all: write a `@container` rule.
974
+ *
975
+ * ```typescript
976
+ * private readonly container = inject(CNGX_CONTAINER_SIZE, { optional: true });
977
+ * private readonly wide = this.container?.property('--cngx-thing-wide', this.host) ?? signal('').asReadonly();
978
+ * readonly mode = computed(() => (this.wide() === '1' ? 'side' : 'over'));
979
+ * ```
980
+ *
981
+ * A component that declares the container in its own stylesheet and reads it
982
+ * itself passes its host explicitly and reads the property off `::after` -
983
+ * there is no descendant to carry the value:
984
+ *
985
+ * ```typescript
986
+ * private readonly host = inject(ElementRef).nativeElement as Element;
987
+ * private readonly container = injectContainerSize(this.host);
988
+ * private readonly narrow = this.container.property('--cngx-thing-narrow', this.host, '::after');
989
+ * ```
990
+ *
991
+ * @param target Element to observe when no ancestor container exists.
992
+ * @category common/layout/observers
993
+ * @relatedTo CngxContainer, injectMediaQuery
994
+ * @since 0.1.0
995
+ */
996
+ function injectContainerSize(target) {
997
+ const ancestor = inject(CNGX_CONTAINER_SIZE, { optional: true, skipSelf: true });
998
+ if (ancestor && !target) {
999
+ return ancestor;
1000
+ }
1001
+ const resolved = target instanceof ElementRef
1002
+ ? target.nativeElement
1003
+ : (target ?? inject(ElementRef).nativeElement);
1004
+ return createContainerSize(resolved, inject(DestroyRef), inject(DOCUMENT).defaultView);
1005
+ }
1006
+
1007
+ /**
1008
+ * Observes a query container and publishes its size to descendants through
1009
+ * {@link CNGX_CONTAINER_SIZE}.
1010
+ *
1011
+ * The directive declares nothing visual. **Both `container-type` and
1012
+ * `container-name` belong in the stylesheet**, next to the `@container` rules
1013
+ * that use them: the name is API (an unnamed query matches the nearest
1014
+ * container of any name, so a consumer wrapping the component in their own
1015
+ * container would silently re-target it), and containment is a layout
1016
+ * decision a skin must be able to opt out of with a plain CSS rule rather
1017
+ * than `!important` against a host style.
1018
+ *
1019
+ * ```css
1020
+ * cngx-thing-layout {
1021
+ * container-type: inline-size;
1022
+ * container-name: cngx-thing-layout;
1023
+ * }
1024
+ *
1025
+ * cngx-thing-layout > cngx-thing { --cngx-thing-wide: 0; }
1026
+ *
1027
+ * @container cngx-thing-layout (min-inline-size: 64rem) {
1028
+ * cngx-thing-layout > cngx-thing { --cngx-thing-wide: 1; }
1029
+ * }
1030
+ * ```
1031
+ *
1032
+ * ```html
1033
+ * <div cngxContainer>
1034
+ * <app-panel />
1035
+ * </div>
1036
+ * ```
1037
+ *
1038
+ * A descendant reads the resolved value with `injectContainerSize()`, so the
1039
+ * breakpoint exists exactly once - in CSS. Note that `container-type:
1040
+ * inline-size` applies size containment: an element that must shrink-wrap its
1041
+ * content (an inline chip, a `width: max-content` bar) must not be a
1042
+ * container.
1043
+ *
1044
+ * @category common/layout
1045
+ * @docsKind primary
1046
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/layout/observers/container.directive.ts
1047
+ * @since 0.1.0
1048
+ * @relatedTo injectContainerSize, CngxResizeObserver, CngxMediaQuery
1049
+ * <example-url>http://localhost:4200/#/common/layout/container/css-decides-js-reads</example-url>
1050
+ */
1051
+ class CngxContainer {
1052
+ size = createContainerSize(inject(ElementRef).nativeElement, inject(DestroyRef), inject(DOCUMENT).defaultView);
1053
+ /** Border-box inline size in pixels. `0` before the first observation. */
1054
+ inlineSize = this.size.inlineSize;
1055
+ /** Border-box block size in pixels. `0` before the first observation. */
1056
+ blockSize = this.size.blockSize;
1057
+ /** `true` once the first observation has arrived. */
1058
+ isReady = this.size.isReady;
1059
+ /**
1060
+ * The resolved value of a custom property on `on` (default: this host),
1061
+ * re-read on every resize. The `@container` rule must style a descendant,
1062
+ * or a pseudo-element of the container itself - see
1063
+ * {@link CngxContainerSize.property}.
1064
+ */
1065
+ property(name, on, pseudo) {
1066
+ return this.size.property(name, on, pseudo);
1067
+ }
1068
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxContainer, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1069
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxContainer, isStandalone: true, selector: "[cngxContainer]", providers: [{ provide: CNGX_CONTAINER_SIZE, useExisting: CngxContainer }], exportAs: ["cngxContainer"], ngImport: i0 });
1070
+ }
1071
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxContainer, decorators: [{
1072
+ type: Directive,
1073
+ args: [{
1074
+ selector: '[cngxContainer]',
1075
+ exportAs: 'cngxContainer',
1076
+ standalone: true,
1077
+ providers: [{ provide: CNGX_CONTAINER_SIZE, useExisting: CngxContainer }],
1078
+ }]
1079
+ }] });
1080
+
738
1081
  /**
739
1082
  * Ref-count per document root. Module-private on purpose: this file is the
740
1083
  * single owner of the lock state. A second copy of this map (the pre-extraction
@@ -800,6 +1143,102 @@ function createScrollLock(html) {
800
1143
  }
801
1144
  };
802
1145
  }
1146
+ // The body properties the pin writes. Only these are saved and restored, so a
1147
+ // style another owner sets on body while the pin is held survives the release.
1148
+ const PINNED_BODY_PROPERTIES = ['position', 'top', 'inset-inline', 'overflow'];
1149
+ /**
1150
+ * Pin state per document root, separate from `lockCounts`: a pin also holds
1151
+ * one `createScrollLock` acquisition, so the html overflow stays shared with
1152
+ * every other owner.
1153
+ *
1154
+ * @internal
1155
+ */
1156
+ const pins = new WeakMap();
1157
+ /**
1158
+ * Acquire a ref-counted scroll lock that pins the page body in place, for
1159
+ * overlays that must hold on iOS Safari.
1160
+ *
1161
+ * `overflow: hidden` on the root does not stop iOS Safari from scrolling a
1162
+ * page that was already scrolled, and the visual viewport drifts with it, so
1163
+ * a bottom-fixed overlay ends above the visible bottom. The first pin saves
1164
+ * the body's inline `position`, `top`, `inset-inline` and `overflow` and the
1165
+ * scroll position, fixes the body at `top: -scrollY`, and acquires
1166
+ * {@link createScrollLock} on the root. The last
1167
+ * release restores the body, releases the root lock and scrolls back to the
1168
+ * saved position. The returned release function is idempotent.
1169
+ *
1170
+ * `CngxDialog` and `CngxScrollLock` keep {@link createScrollLock}; reach for
1171
+ * this one when the overlay is pinned to the viewport bottom on touch devices.
1172
+ *
1173
+ * ```typescript
1174
+ * const release = createPinnedScrollLock(document.documentElement);
1175
+ * // ... sheet open ...
1176
+ * release();
1177
+ * ```
1178
+ *
1179
+ * @param html - The document root (`document.documentElement`) to lock.
1180
+ * @returns Release function for this acquisition. Idempotent.
1181
+ *
1182
+ * @category common/layout
1183
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/layout/scroll/scroll-lock-core.ts
1184
+ * @since 0.1.0
1185
+ * @relatedTo createScrollLock, CngxPopoverSheet
1186
+ */
1187
+ function createPinnedScrollLock(html) {
1188
+ const body = html.ownerDocument.body;
1189
+ const view = html.ownerDocument.defaultView;
1190
+ const existing = pins.get(html);
1191
+ if (existing) {
1192
+ existing.count += 1;
1193
+ }
1194
+ else {
1195
+ const scrollX = view?.scrollX ?? 0;
1196
+ const scrollY = view?.scrollY ?? 0;
1197
+ pins.set(html, {
1198
+ count: 1,
1199
+ saved: new Map(PINNED_BODY_PROPERTIES.map((name) => [
1200
+ name,
1201
+ {
1202
+ value: body.style.getPropertyValue(name),
1203
+ priority: body.style.getPropertyPriority(name),
1204
+ },
1205
+ ])),
1206
+ scrollX,
1207
+ scrollY,
1208
+ releaseHtml: createScrollLock(html),
1209
+ });
1210
+ body.style.position = 'fixed';
1211
+ body.style.top = `${-scrollY}px`;
1212
+ body.style.insetInline = '0';
1213
+ body.style.overflow = 'hidden';
1214
+ }
1215
+ let released = false;
1216
+ return () => {
1217
+ if (released) {
1218
+ return;
1219
+ }
1220
+ released = true;
1221
+ const state = pins.get(html);
1222
+ if (!state) {
1223
+ return;
1224
+ }
1225
+ state.count -= 1;
1226
+ if (state.count > 0) {
1227
+ return;
1228
+ }
1229
+ pins.delete(html);
1230
+ for (const [name, { value, priority }] of state.saved) {
1231
+ if (value) {
1232
+ body.style.setProperty(name, value, priority);
1233
+ }
1234
+ else {
1235
+ body.style.removeProperty(name);
1236
+ }
1237
+ }
1238
+ state.releaseHtml();
1239
+ view?.scrollTo({ left: state.scrollX, top: state.scrollY, behavior: 'instant' });
1240
+ };
1241
+ }
803
1242
 
804
1243
  /**
805
1244
  * Prevents scrolling on the document body when enabled.
@@ -861,6 +1300,240 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
861
1300
  }]
862
1301
  }], ctorParameters: () => [], propDecorators: { enabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxScrollLock", required: false }] }] } });
863
1302
 
1303
+ /** Distances up to this many px count as "at the edge" (sub-pixel and zoom rounding). */
1304
+ const EDGE_TOLERANCE = 1;
1305
+ const NO_EDGES = {
1306
+ blockStart: false,
1307
+ blockEnd: false,
1308
+ inlineStart: false,
1309
+ inlineEnd: false,
1310
+ };
1311
+ function sameEdges(a, b) {
1312
+ return (a.blockStart === b.blockStart &&
1313
+ a.blockEnd === b.blockEnd &&
1314
+ a.inlineStart === b.inlineStart &&
1315
+ a.inlineEnd === b.inlineEnd);
1316
+ }
1317
+ /**
1318
+ * One read of the six scroll metrics. RTL `scrollLeft` runs over `[-max, 0]`
1319
+ * in every evergreen engine and LTR over `[0, max]`, so its magnitude is the
1320
+ * distance from the inline-start edge in both directions - no direction lookup
1321
+ * and no `getComputedStyle` in the scroll path.
1322
+ */
1323
+ function readEdges(element) {
1324
+ const inlineOffset = Math.abs(element.scrollLeft);
1325
+ return {
1326
+ blockStart: element.scrollTop > EDGE_TOLERANCE,
1327
+ blockEnd: element.scrollHeight - element.clientHeight - element.scrollTop > EDGE_TOLERANCE,
1328
+ inlineStart: inlineOffset > EDGE_TOLERANCE,
1329
+ inlineEnd: element.scrollWidth - element.clientWidth - inlineOffset > EDGE_TOLERANCE,
1330
+ };
1331
+ }
1332
+ /**
1333
+ * Tracks which edges of a scrollport still hide content, as four boolean
1334
+ * signals.
1335
+ *
1336
+ * Triggers are a passive `scroll` listener, one `observeResize` per observed
1337
+ * element (the scrollport itself plus every direct element child) and a
1338
+ * `childList`-only `MutationObserver` that keeps that child set current. All
1339
+ * of them only schedule work: the metrics are read once per animation frame
1340
+ * however many triggers fired, and the result lands in one snapshot signal
1341
+ * with a structural `equal`, so the four projections only notify when an edge
1342
+ * actually flips. A distance of 1px or less counts as "at the edge".
1343
+ *
1344
+ * Only direct children are resize-observed. A long item list should sit inside
1345
+ * one content element rather than be N direct children (one observer each);
1346
+ * growth deep inside a fixed-size child is picked up on the next scroll.
1347
+ *
1348
+ * A `null` host (SSR) wires nothing and all four signals stay `false`.
1349
+ *
1350
+ * ```typescript
1351
+ * const edges = createScrollEdges(
1352
+ * inject(ElementRef).nativeElement,
1353
+ * inject(DestroyRef),
1354
+ * inject(DOCUMENT).defaultView,
1355
+ * );
1356
+ * const showTopShadow = edges.canScrollBlockStart;
1357
+ * ```
1358
+ *
1359
+ * @param element The scrollport to read.
1360
+ * @param destroyRef Scope whose destruction removes the listener, disconnects
1361
+ * every observer and cancels a pending frame.
1362
+ * @param host The window-like object to read the observer and frame APIs from.
1363
+ * @returns The four per-edge signals.
1364
+ * @category common/layout
1365
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/layout/scroll/scroll-edges-core.ts
1366
+ * @since 0.1.0
1367
+ * @relatedTo CngxScrollEdges, observeResize
1368
+ */
1369
+ function createScrollEdges(element, destroyRef, host) {
1370
+ const edges = signal(NO_EDGES, { ...(ngDevMode ? { debugName: "edges" } : /* istanbul ignore next */ {}), equal: sameEdges });
1371
+ const state = {
1372
+ canScrollBlockStart: computed(() => edges().blockStart),
1373
+ canScrollBlockEnd: computed(() => edges().blockEnd),
1374
+ canScrollInlineStart: computed(() => edges().inlineStart),
1375
+ canScrollInlineEnd: computed(() => edges().inlineEnd),
1376
+ };
1377
+ if (!host) {
1378
+ return state;
1379
+ }
1380
+ let destroyed = false;
1381
+ let framePending = false;
1382
+ let frameHandle = 0;
1383
+ const read = () => {
1384
+ framePending = false;
1385
+ if (destroyed) {
1386
+ return;
1387
+ }
1388
+ edges.set(readEdges(element));
1389
+ };
1390
+ const schedule = () => {
1391
+ if (destroyed || framePending) {
1392
+ return;
1393
+ }
1394
+ if (typeof host.requestAnimationFrame !== 'function') {
1395
+ read();
1396
+ return;
1397
+ }
1398
+ framePending = true;
1399
+ frameHandle = host.requestAnimationFrame(read);
1400
+ };
1401
+ const resizeTeardowns = new Map();
1402
+ const observe = (target) => {
1403
+ if (resizeTeardowns.has(target)) {
1404
+ return;
1405
+ }
1406
+ resizeTeardowns.set(target, observeResize(host, target, 'border-box', () => schedule()));
1407
+ };
1408
+ const syncChildren = () => {
1409
+ const children = new Set(Array.from(element.children));
1410
+ for (const [target, teardown] of resizeTeardowns) {
1411
+ if (target !== element && !children.has(target)) {
1412
+ teardown();
1413
+ resizeTeardowns.delete(target);
1414
+ }
1415
+ }
1416
+ children.forEach(observe);
1417
+ };
1418
+ element.addEventListener('scroll', schedule, { passive: true });
1419
+ observe(element);
1420
+ syncChildren();
1421
+ let mutationObserver = null;
1422
+ if (typeof host.MutationObserver === 'function') {
1423
+ mutationObserver = new host.MutationObserver(() => {
1424
+ syncChildren();
1425
+ schedule();
1426
+ });
1427
+ mutationObserver.observe(element, { childList: true });
1428
+ }
1429
+ schedule();
1430
+ destroyRef.onDestroy(() => {
1431
+ destroyed = true;
1432
+ element.removeEventListener('scroll', schedule);
1433
+ mutationObserver?.disconnect();
1434
+ resizeTeardowns.forEach((teardown) => teardown());
1435
+ resizeTeardowns.clear();
1436
+ if (framePending && typeof host.cancelAnimationFrame === 'function') {
1437
+ host.cancelAnimationFrame(frameHandle);
1438
+ }
1439
+ framePending = false;
1440
+ });
1441
+ return state;
1442
+ }
1443
+
1444
+ /**
1445
+ * Reports which edges of a scrollport still hide content and reflects them as
1446
+ * host attributes, so an edge shadow or fade appears only while there really
1447
+ * is something to scroll to in that direction.
1448
+ *
1449
+ * Put it on the element that scrolls (`overflow: auto` / `scroll`). The four
1450
+ * signals and the four logical host attributes are derived from one read of
1451
+ * the scroll metrics per animation frame; the attributes are present (empty
1452
+ * value) while true and absent otherwise:
1453
+ *
1454
+ * - `data-scroll-block-start` / `canScrollBlockStart()` - content hidden above
1455
+ * - `data-scroll-block-end` / `canScrollBlockEnd()` - content hidden below
1456
+ * - `data-scroll-inline-start` / `canScrollInlineStart()` - hidden toward inline start
1457
+ * - `data-scroll-inline-end` / `canScrollInlineEnd()` - hidden toward inline end
1458
+ *
1459
+ * Inline start / end follow the writing direction: in `dir="rtl"` the start
1460
+ * edge is on the right. The direction is derived from the scroll offset
1461
+ * itself, so a `dir="rtl"` subtree inside an LTR page reports correctly.
1462
+ *
1463
+ * The directive paints nothing. The four attributes (present only while true)
1464
+ * are its public, stable contract; every visual belongs to the consumer CSS,
1465
+ * keyed on them. Three common cues:
1466
+ *
1467
+ * Shadow (Material 2 elevate-on-scroll):
1468
+ *
1469
+ * ```css
1470
+ * .sheet[data-scroll-block-start] .bar { box-shadow: 0 2px 4px -2px rgb(0 0 0 / 0.3); }
1471
+ * ```
1472
+ *
1473
+ * Hairline that appears (iOS scroll-edge appearance; transparent border at rest):
1474
+ *
1475
+ * ```css
1476
+ * .sheet[data-scroll-block-start] .bar { border-block-end-color: var(--cngx-color-border); }
1477
+ * ```
1478
+ *
1479
+ * Tonal surface change (Material 3 top app bar):
1480
+ *
1481
+ * ```css
1482
+ * .sheet[data-scroll-block-start] .bar { background: var(--app-bar-scrolled-surface); }
1483
+ * ```
1484
+ *
1485
+ * Forced colors strips `box-shadow`, so a shadow-only cue disappears there;
1486
+ * prefer a border or pair the shadow with one under `forced-colors: active`.
1487
+ *
1488
+ * ```html
1489
+ * <div class="sheet" cngxScrollEdges #edges="cngxScrollEdges">...</div>
1490
+ * ```
1491
+ *
1492
+ * The edge state is purely visual and is not announced: the hidden content
1493
+ * stays in the DOM and in the reading order, and the scrollport remains
1494
+ * reachable by keyboard scrolling. Make the scrollport focusable (and named)
1495
+ * when it holds no focusable content of its own.
1496
+ *
1497
+ * Upgrade path: the attributes map 1:1 onto CSS
1498
+ * `@container scroll-state(scrollable: block-start)` and its siblings, so the
1499
+ * CSS can swap to native scroll-state queries once they are Baseline.
1500
+ *
1501
+ * @category common/layout
1502
+ * @docsKind primary
1503
+ * @wcag AA
1504
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/layout/scroll/scroll-edges.directive.ts
1505
+ * @since 0.1.0
1506
+ * @relatedTo CngxStickyHeader, CngxScrollSpy, createScrollEdges
1507
+ * <example-url>http://localhost:4200/#/common/layout/scroll-edges/edge-shadows</example-url>
1508
+ */
1509
+ class CngxScrollEdges {
1510
+ edges = createScrollEdges(inject(ElementRef).nativeElement, inject(DestroyRef), isPlatformBrowser(inject(PLATFORM_ID)) ? inject(DOCUMENT).defaultView : null);
1511
+ /** Content is hidden toward the block-start edge (above). */
1512
+ canScrollBlockStart = this.edges.canScrollBlockStart;
1513
+ /** Content is hidden toward the block-end edge (below). */
1514
+ canScrollBlockEnd = this.edges.canScrollBlockEnd;
1515
+ /** Content is hidden toward the inline-start edge (left in LTR, right in RTL). */
1516
+ canScrollInlineStart = this.edges.canScrollInlineStart;
1517
+ /** Content is hidden toward the inline-end edge (right in LTR, left in RTL). */
1518
+ canScrollInlineEnd = this.edges.canScrollInlineEnd;
1519
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxScrollEdges, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1520
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxScrollEdges, isStandalone: true, selector: "[cngxScrollEdges]", host: { properties: { "attr.data-scroll-block-start": "canScrollBlockStart() ? '' : null", "attr.data-scroll-block-end": "canScrollBlockEnd() ? '' : null", "attr.data-scroll-inline-start": "canScrollInlineStart() ? '' : null", "attr.data-scroll-inline-end": "canScrollInlineEnd() ? '' : null" } }, exportAs: ["cngxScrollEdges"], ngImport: i0 });
1521
+ }
1522
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxScrollEdges, decorators: [{
1523
+ type: Directive,
1524
+ args: [{
1525
+ selector: '[cngxScrollEdges]',
1526
+ exportAs: 'cngxScrollEdges',
1527
+ standalone: true,
1528
+ host: {
1529
+ '[attr.data-scroll-block-start]': "canScrollBlockStart() ? '' : null",
1530
+ '[attr.data-scroll-block-end]': "canScrollBlockEnd() ? '' : null",
1531
+ '[attr.data-scroll-inline-start]': "canScrollInlineStart() ? '' : null",
1532
+ '[attr.data-scroll-inline-end]': "canScrollInlineEnd() ? '' : null",
1533
+ },
1534
+ }]
1535
+ }] });
1536
+
864
1537
  /**
865
1538
  * Headless skeleton loading placeholder.
866
1539
  *
@@ -954,7 +1627,9 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
954
1627
  *
955
1628
  * The observer is automatically recreated when `root`, `rootMargin`, or
956
1629
  * `threshold` inputs change, and disconnected on destroy or when `enabled`
957
- * is set to `false`.
1630
+ * is set to `false`. When `loading` settles back to `false` the sentinel is
1631
+ * re-observed, so a fetched page that did not push the sentinel out of view
1632
+ * still re-fires `loadMore` instead of stalling the list.
958
1633
  *
959
1634
  * ### Basic infinite list
960
1635
  * ```html
@@ -1016,6 +1691,7 @@ class CngxInfiniteScroll {
1016
1691
  el = inject((ElementRef));
1017
1692
  doc = inject(DOCUMENT);
1018
1693
  lastEmitTime = 0;
1694
+ observer = null;
1019
1695
  constructor() {
1020
1696
  const win = this.doc.defaultView;
1021
1697
  if (!win) {
@@ -1032,8 +1708,13 @@ class CngxInfiniteScroll {
1032
1708
  }
1033
1709
  const isLoading = () => this.loading();
1034
1710
  const resolvedRoot = root ? this.doc.querySelector(root) : null;
1711
+ if (typeof ngDevMode !== 'undefined' && ngDevMode && root && !resolvedRoot) {
1712
+ cngxDevWarn('CNGX1032', `[cngxInfiniteScroll] root selector "${root}" matched no element - ` +
1713
+ 'falling back to the viewport. A late-rendered root needs a re-bind of [root].');
1714
+ }
1035
1715
  const observer = new IntersectionObserver((entries) => {
1036
- const entry = entries[0];
1716
+ // batched records arrive oldest-first; only the newest reflects reality
1717
+ const entry = entries[entries.length - 1];
1037
1718
  if (!entry.isIntersecting) {
1038
1719
  return;
1039
1720
  }
@@ -1048,7 +1729,29 @@ class CngxInfiniteScroll {
1048
1729
  this.loadMore.emit();
1049
1730
  }, { root: resolvedRoot, rootMargin, threshold });
1050
1731
  observer.observe(this.el.nativeElement);
1051
- onCleanup(() => observer.disconnect());
1732
+ this.observer = observer;
1733
+ onCleanup(() => {
1734
+ observer.disconnect();
1735
+ this.observer = null;
1736
+ });
1737
+ });
1738
+ const loadingTransition = createTransitionTracker(() => this.loading());
1739
+ effect(() => {
1740
+ const loading = loadingTransition.current();
1741
+ const wasLoading = loadingTransition.previous();
1742
+ if (!wasLoading || loading) {
1743
+ return;
1744
+ }
1745
+ // IO reports intersection CHANGES only: when a fetched page does not
1746
+ // push the sentinel out of view there is no new entry after loading
1747
+ // settles, and the list stalls. Re-observing forces a fresh entry;
1748
+ // the debounce window is reset so that entry may emit immediately.
1749
+ untracked(() => {
1750
+ const sentinel = this.el.nativeElement;
1751
+ this.lastEmitTime = 0;
1752
+ this.observer?.unobserve(sentinel);
1753
+ this.observer?.observe(sentinel);
1754
+ });
1052
1755
  });
1053
1756
  }
1054
1757
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxInfiniteScroll, deps: [], target: i0.ɵɵFactoryTarget.Directive });
@@ -1083,7 +1786,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1083
1786
  * `isSticky()` reports the state the host actually has. A scrollport whose
1084
1787
  * height is content-driven never scrolls in the block axis, so a header inside
1085
1788
  * it never pins; in dev mode the directive warns once when it resolves against
1086
- * such a scrollport.
1789
+ * such a scrollport. The observer is recreated when `threshold` changes,
1790
+ * matching the sibling observer directives.
1087
1791
  *
1088
1792
  * ### Sticky header with shadow
1089
1793
  * ```html
@@ -1115,6 +1819,8 @@ class CngxStickyHeader {
1115
1819
  isSticky = this.isStickyState.asReadonly();
1116
1820
  el = inject((ElementRef));
1117
1821
  doc = inject(DOCUMENT);
1822
+ /** Sentinel + scrollport resolved once after render; the observer effect keys on it. */
1823
+ observeSetup = signal(null, ...(ngDevMode ? [{ debugName: "observeSetup" }] : /* istanbul ignore next */ []));
1118
1824
  constructor() {
1119
1825
  const destroyRef = inject(DestroyRef);
1120
1826
  // IntersectionObserver sentinel pattern - host is stuck once the 1px sentinel leaves
@@ -1126,15 +1832,17 @@ class CngxStickyHeader {
1126
1832
  // header inside a never-scrolling scrollport would read `isSticky() === true` while
1127
1833
  // it visibly scrolls away with its content.
1128
1834
  const scrollport = this.resolveScrollParent(host);
1129
- // A scrollport whose content fits (client height equals scroll height) never
1130
- // scrolls in the block axis, so a header inside it can never pin - `isSticky()`
1131
- // stays false while the whole scrollport moves. Flag the misconfiguration once,
1132
- // in dev only; a one-shot read here is exactly what `afterNextRender` is for
1133
- // (no reactive-graph node, unlike a dep-less effect).
1134
- if (isDevMode() &&
1835
+ // A scrollport whose content fits never scrolls in the block axis, so a header
1836
+ // inside it can never pin - `isSticky()` stays false while the whole scrollport
1837
+ // moves. Flag the misconfiguration once, in dev only; a one-shot read here is
1838
+ // exactly what `afterNextRender` is for (no reactive-graph node, unlike a
1839
+ // dep-less effect). The 1px tolerance absorbs sub-pixel layout and browser-zoom
1840
+ // rounding: "cannot meaningfully scroll" instead of exact equality.
1841
+ if (typeof ngDevMode !== 'undefined' &&
1842
+ ngDevMode &&
1135
1843
  scrollport &&
1136
- scrollport.clientHeight === scrollport.scrollHeight) {
1137
- console.warn('[cngxStickyHeader] resolves against a scroll container that cannot scroll ' +
1844
+ scrollport.scrollHeight - scrollport.clientHeight <= 1) {
1845
+ cngxDevWarn('CNGX1034', '[cngxStickyHeader] resolves against a scroll container that cannot scroll ' +
1138
1846
  'in the block axis (client height equals scroll height), so this header ' +
1139
1847
  'will never pin. Give the scrollport a bounded block-size, or drop ' +
1140
1848
  'cngxStickyHeader.', { host, scrollport });
@@ -1147,33 +1855,43 @@ class CngxStickyHeader {
1147
1855
  sentinel.style.pointerEvents = 'none';
1148
1856
  sentinel.setAttribute('aria-hidden', 'true');
1149
1857
  host.parentElement?.insertBefore(sentinel, host);
1858
+ this.observeSetup.set({ sentinel, scrollport });
1859
+ destroyRef.onDestroy(() => sentinel.remove());
1860
+ });
1861
+ // Observer creation lives in an effect so a later threshold change
1862
+ // recreates it - the one-shot afterNextRender above only resolves DOM.
1863
+ effect((onCleanup) => {
1864
+ const setup = this.observeSetup();
1865
+ const threshold = this.threshold();
1866
+ if (!setup) {
1867
+ return;
1868
+ }
1150
1869
  const observer = new IntersectionObserver((entries) => {
1151
- const isSticky = !entries[0].isIntersecting;
1870
+ // batched records arrive oldest-first; only the newest reflects reality
1871
+ const isSticky = !entries[entries.length - 1].isIntersecting;
1152
1872
  if (isSticky !== this.isStickyState()) {
1153
1873
  this.isStickyState.set(isSticky);
1154
1874
  this.stickyChange.emit(isSticky);
1155
1875
  }
1156
- }, { threshold: this.threshold(), root: scrollport });
1157
- observer.observe(sentinel);
1158
- destroyRef.onDestroy(() => {
1159
- observer.disconnect();
1160
- sentinel.remove();
1161
- });
1876
+ }, { threshold, root: setup.scrollport });
1877
+ observer.observe(setup.sentinel);
1878
+ onCleanup(() => observer.disconnect());
1162
1879
  });
1163
1880
  }
1164
1881
  /**
1165
1882
  * The nearest ancestor that is a scroll container in the block axis - the scrollport
1166
1883
  * `position: sticky` resolves against. Walks up from the host's parent to the first
1167
- * ancestor whose computed `overflow-y` is not `visible`; `null` means no such
1168
- * ancestor, i.e. the header sticks to the viewport. A used `overflow-x` other than
1169
- * `visible` coerces the computed `overflow-y` to `auto`, so this also catches a
1170
- * horizontal scroll container (e.g. a data grid that scrolls sideways).
1884
+ * ancestor whose computed `overflow-y` is `auto`, `scroll` or `hidden`; `null` means
1885
+ * no such ancestor, i.e. the header sticks to the viewport. `clip` clips without
1886
+ * creating a scroll container, so it is skipped. A used `overflow-x` of `auto`,
1887
+ * `scroll` or `hidden` coerces the computed `overflow-y` to `auto`, so this also
1888
+ * catches a horizontal scroll container (e.g. a data grid that scrolls sideways).
1171
1889
  */
1172
1890
  resolveScrollParent(host) {
1173
1891
  const view = this.doc.defaultView;
1174
1892
  for (let node = host.parentElement; node; node = node.parentElement) {
1175
1893
  const overflowY = view?.getComputedStyle(node).overflowY;
1176
- if (overflowY && overflowY !== 'visible') {
1894
+ if (overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'hidden') {
1177
1895
  return node;
1178
1896
  }
1179
1897
  }
@@ -1202,6 +1920,10 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1202
1920
  * and reports the one with the highest intersection ratio as the active section.
1203
1921
  * Ideal for scroll-based navigation highlighting and reading progress.
1204
1922
  *
1923
+ * Section IDs are resolved when the inputs change - sections rendered later
1924
+ * (`@if`/`@defer`) are not picked up automatically; re-bind `[cngxScrollSpy]`
1925
+ * once they exist. In dev mode the directive warns about IDs it cannot find.
1926
+ *
1205
1927
  * ### Navigation highlighting
1206
1928
  * ```html
1207
1929
  * <nav [cngxScrollSpy]="['intro', 'features', 'pricing']"
@@ -1274,10 +1996,19 @@ class CngxScrollSpy {
1274
1996
  const elements = ids
1275
1997
  .map((id) => this.doc.getElementById(id))
1276
1998
  .filter((el) => el !== null);
1999
+ if (typeof ngDevMode !== 'undefined' && ngDevMode && elements.length < ids.length) {
2000
+ const missing = ids.filter((id) => !this.doc.getElementById(id));
2001
+ cngxDevWarn('CNGX1033', `[cngxScrollSpy] section id(s) not found: ${missing.join(', ')}. ` +
2002
+ 'Late-rendered sections are not observed - re-bind [cngxScrollSpy] once they exist.');
2003
+ }
1277
2004
  if (elements.length === 0) {
1278
2005
  return undefined;
1279
2006
  }
1280
2007
  const resolvedRoot = rootSelector ? this.doc.querySelector(rootSelector) : null;
2008
+ if (typeof ngDevMode !== 'undefined' && ngDevMode && rootSelector && !resolvedRoot) {
2009
+ cngxDevWarn('CNGX1032', `[cngxScrollSpy] root selector "${rootSelector}" matched no element - ` +
2010
+ 'falling back to the viewport. A late-rendered root needs a re-bind of [root].');
2011
+ }
1281
2012
  const observer = new IntersectionObserver((entries) => {
1282
2013
  entries.forEach((entry) => this.ratios.set(entry.target.id, entry.intersectionRatio));
1283
2014
  const best = Array.from(this.ratios).reduce((acc, [id, ratio]) => ratio >= thresholdValue && ratio > acc.ratio ? { id, ratio } : acc, { id: null, ratio: 0 });
@@ -1344,23 +2075,27 @@ class CngxTruncate {
1344
2075
  /** Whether the text content actually exceeds the line limit and is being clamped. */
1345
2076
  isClamped = this.isClampedState.asReadonly();
1346
2077
  el = inject((ElementRef));
1347
- observer = null;
2078
+ stopResize = null;
1348
2079
  rafHandle = null;
1349
2080
  // null strips the host binding - preferred over an empty string for -webkit-line-clamp.
1350
2081
  /** @internal */
1351
- clampValue = () => (this.expanded() ? null : String(this.lines()));
2082
+ clampValue = computed(() => (this.expanded() ? null : String(this.lines())), ...(ngDevMode ? [{ debugName: "clampValue" }] : /* istanbul ignore next */ []));
1352
2083
  /** @internal */
1353
- displayValue = () => (this.expanded() ? null : '-webkit-box');
2084
+ displayValue = computed(() => (this.expanded() ? null : '-webkit-box'), ...(ngDevMode ? [{ debugName: "displayValue" }] : /* istanbul ignore next */ []));
1354
2085
  /** @internal */
1355
- orientValue = () => (this.expanded() ? null : 'vertical');
2086
+ orientValue = computed(() => (this.expanded() ? null : 'vertical'), ...(ngDevMode ? [{ debugName: "orientValue" }] : /* istanbul ignore next */ []));
1356
2087
  /** @internal */
1357
- overflowValue = () => (this.expanded() ? null : 'hidden');
2088
+ overflowValue = computed(() => (this.expanded() ? null : 'hidden'), ...(ngDevMode ? [{ debugName: "overflowValue" }] : /* istanbul ignore next */ []));
1358
2089
  constructor() {
1359
2090
  const destroyRef = inject(DestroyRef);
2091
+ // SSR guard: no window, no measuring - the style bindings above still render.
2092
+ const win = inject(DOCUMENT).defaultView;
2093
+ if (!win) {
2094
+ return;
2095
+ }
1360
2096
  afterNextRender(() => {
1361
2097
  this.checkClamped();
1362
- this.observer = new ResizeObserver(() => this.checkClamped());
1363
- this.observer.observe(this.el.nativeElement);
2098
+ this.stopResize = observeResize(win, this.el.nativeElement, 'content-box', () => this.checkClamped());
1364
2099
  });
1365
2100
  // Re-check after expanded/lines change; RAF ensures styles are applied first.
1366
2101
  effect(() => {
@@ -1370,7 +2105,7 @@ class CngxTruncate {
1370
2105
  this.rafHandle = requestAnimationFrame(() => this.checkClamped());
1371
2106
  });
1372
2107
  destroyRef.onDestroy(() => {
1373
- this.observer?.disconnect();
2108
+ this.stopResize?.();
1374
2109
  this.cancelRaf();
1375
2110
  });
1376
2111
  }
@@ -1419,7 +2154,9 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1419
2154
  * construction. The `<mark>` element has correct native SR semantics (announced
1420
2155
  * as "highlighted" in most screen readers).
1421
2156
  *
1422
- * Original DOM structure is restored when the term changes or the directive is destroyed.
2157
+ * The original text nodes are kept by reference and re-inserted when the
2158
+ * term changes or the directive is destroyed - Angular bindings targeting
2159
+ * them (interpolations, structural directives) stay live.
1423
2160
  *
1424
2161
  * ### Search result highlighting
1425
2162
  * ```html
@@ -1454,20 +2191,26 @@ class CngxHighlight {
1454
2191
  matchCount = this.matchCountState.asReadonly();
1455
2192
  el = inject((ElementRef));
1456
2193
  doc = inject(DOCUMENT);
1457
- /** Snapshot of original child nodes - restored before each re-highlight. */
1458
- originalNodes = null;
2194
+ /**
2195
+ * The text nodes replaced by the current highlight pass, by reference,
2196
+ * with the nodes standing in for them. Undone before every re-highlight
2197
+ * and on destroy - re-inserting the original references keeps LView
2198
+ * bindings (interpolations) attached to live DOM.
2199
+ */
2200
+ replacements = [];
1459
2201
  initialized = signal(false, ...(ngDevMode ? [{ debugName: "initialized" }] : /* istanbul ignore next */ []));
1460
2202
  constructor() {
1461
- inject(DestroyRef).onDestroy(() => this.restore());
2203
+ inject(DestroyRef).onDestroy(() => this.restoreNodes());
1462
2204
  afterNextRender(() => {
1463
2205
  this.initialized.set(true);
1464
2206
  });
1465
- // matchCountState is written via untracked path - re-entering the effect would loop.
2207
+ // The highlight pass writes matchCountState - untracked, so the write
2208
+ // cannot re-trigger this effect.
1466
2209
  effect(() => {
1467
2210
  const term = this.term();
1468
2211
  const caseSensitive = this.caseSensitive();
1469
2212
  if (this.initialized()) {
1470
- this.applyHighlight(term, caseSensitive);
2213
+ untracked(() => this.applyHighlight(term, caseSensitive));
1471
2214
  }
1472
2215
  });
1473
2216
  }
@@ -1477,12 +2220,7 @@ class CngxHighlight {
1477
2220
  */
1478
2221
  applyHighlight(term, caseSensitive) {
1479
2222
  const host = this.el.nativeElement;
1480
- if (this.originalNodes === null) {
1481
- this.originalNodes = Array.from(host.childNodes).map((n) => n.cloneNode(true));
1482
- }
1483
- else {
1484
- this.restoreNodes(host);
1485
- }
2223
+ this.restoreNodes();
1486
2224
  if (!term) {
1487
2225
  this.matchCountState.set(0);
1488
2226
  return;
@@ -1520,26 +2258,28 @@ class CngxHighlight {
1520
2258
  if (lastIndex < text.length) {
1521
2259
  fragment.appendChild(this.doc.createTextNode(text.slice(lastIndex)));
1522
2260
  }
2261
+ // Capture before replaceChild - inserting a fragment empties it.
2262
+ const inserted = Array.from(fragment.childNodes);
1523
2263
  textNode.parentNode.replaceChild(fragment, textNode);
2264
+ this.replacements.push({ original: textNode, inserted });
1524
2265
  }
1525
2266
  this.matchCountState.set(count);
1526
2267
  }
1527
- /** Restores the original DOM structure. */
1528
- restore() {
1529
- if (this.originalNodes !== null) {
1530
- this.restoreNodes(this.el.nativeElement);
1531
- }
1532
- }
1533
- restoreNodes(host) {
1534
- if (!this.originalNodes) {
1535
- return;
1536
- }
1537
- while (host.firstChild) {
1538
- host.removeChild(host.firstChild);
1539
- }
1540
- for (const node of this.originalNodes) {
1541
- host.appendChild(node.cloneNode(true));
2268
+ /** Puts the original text nodes back and removes the highlight nodes. */
2269
+ restoreNodes() {
2270
+ for (const { original, inserted } of this.replacements) {
2271
+ const parent = inserted[0]?.parentNode;
2272
+ if (!parent) {
2273
+ continue;
2274
+ }
2275
+ parent.insertBefore(original, inserted[0]);
2276
+ for (const node of inserted) {
2277
+ if (node.parentNode === parent) {
2278
+ parent.removeChild(node);
2279
+ }
2280
+ }
1542
2281
  }
2282
+ this.replacements = [];
1543
2283
  }
1544
2284
  /** Escapes special regex characters in the search term. */
1545
2285
  escapeRegex(str) {
@@ -1557,6 +2297,86 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1557
2297
  }]
1558
2298
  }], ctorParameters: () => [], propDecorators: { term: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxHighlight", required: false }] }], caseSensitive: [{ type: i0.Input, args: [{ isSignal: true, alias: "highlightCaseSensitive", required: false }] }] } });
1559
2299
 
2300
+ /**
2301
+ * The English layout section: the single source of the layout atoms'
2302
+ * English copy. `CNGX_LAYOUT_I18N` defaults to it.
2303
+ *
2304
+ * @category common/layout/i18n
2305
+ * @since 0.1.0
2306
+ * @relatedTo CNGX_LAYOUT_I18N
2307
+ */
2308
+ const CNGX_LAYOUT_LANGUAGE_EN = {
2309
+ expandableTextMore: 'Show more',
2310
+ expandableTextLess: 'Show less',
2311
+ };
2312
+
2313
+ /** @internal The English section with the active pack's layout section on top. */
2314
+ const layoutBundleFromPack = createLanguageSection('layout', CNGX_LAYOUT_LANGUAGE_EN);
2315
+ /**
2316
+ * DI token for the layout i18n bundle. `providedIn: 'root'`: the layout
2317
+ * section of the active language pack over the English defaults; the value
2318
+ * is a `Signal`, shared by every reader under one injector.
2319
+ *
2320
+ * @category common/layout/i18n
2321
+ * @wcag AA
2322
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/layout/i18n/layout-i18n.ts
2323
+ * @since 0.1.0
2324
+ * @relatedTo CngxExpandableText
2325
+ */
2326
+ const CNGX_LAYOUT_I18N = new InjectionToken('CngxLayoutI18n', {
2327
+ providedIn: 'root',
2328
+ factory: layoutBundleFromPack,
2329
+ });
2330
+ /** @internal */
2331
+ function defineLayoutI18nFeature(fn) {
2332
+ return Object.assign(fn, { _target: 'i18n' });
2333
+ }
2334
+ /**
2335
+ * Override layout labels via a partial bundle - unset keys keep the
2336
+ * language pack's copy, or the English default. Pass a `Signal` of a partial
2337
+ * bundle to switch languages at runtime.
2338
+ *
2339
+ * @category common/layout/i18n
2340
+ * @since 0.1.0
2341
+ */
2342
+ function withLayoutI18nLabels(overrides) {
2343
+ return defineLayoutI18nFeature((bundle) => createOverrideMerge(bundle, overrides));
2344
+ }
2345
+ /**
2346
+ * Provider for the layout i18n bundle. Returns a plain `Provider`, so it
2347
+ * also scopes a subtree through `viewProviders`. The features apply on top
2348
+ * of the active language pack.
2349
+ *
2350
+ * ```ts
2351
+ * bootstrapApplication(AppComponent, {
2352
+ * providers: [
2353
+ * provideLayoutI18n(
2354
+ * withLayoutI18nLabels({ expandableTextMore: 'Mehr anzeigen', expandableTextLess: 'Weniger anzeigen' }),
2355
+ * ),
2356
+ * ],
2357
+ * });
2358
+ * ```
2359
+ *
2360
+ * @category common/layout/i18n
2361
+ * @since 0.1.0
2362
+ */
2363
+ function provideLayoutI18n(...features) {
2364
+ return {
2365
+ provide: CNGX_LAYOUT_I18N,
2366
+ useFactory: () => features.reduce((bundle, feat) => feat(bundle), layoutBundleFromPack()),
2367
+ };
2368
+ }
2369
+ /**
2370
+ * Inject the resolved layout i18n bundle signal. Read it inside a
2371
+ * `computed()` or template so a runtime override flip re-derives.
2372
+ *
2373
+ * @category common/layout/i18n
2374
+ * @since 0.1.0
2375
+ */
2376
+ function injectLayoutI18n() {
2377
+ return inject(CNGX_LAYOUT_I18N);
2378
+ }
2379
+
1560
2380
  /**
1561
2381
  * Marks a custom toggle template inside `cngx-expandable-text`.
1562
2382
  *
@@ -1577,11 +2397,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1577
2397
  * @relatedTo CngxExpandableText, CngxTruncate
1578
2398
  */
1579
2399
  class CngxExpandableToggle {
1580
- templateRef;
1581
- constructor(templateRef) {
1582
- this.templateRef = templateRef;
1583
- }
1584
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxExpandableToggle, deps: [{ token: i0.TemplateRef }], target: i0.ɵɵFactoryTarget.Directive });
2400
+ templateRef = inject(TemplateRef);
2401
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxExpandableToggle, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1585
2402
  static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxExpandableToggle, isStandalone: true, selector: "ng-template[cngxExpandableToggle]", ngImport: i0 });
1586
2403
  }
1587
2404
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxExpandableToggle, decorators: [{
@@ -1590,7 +2407,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1590
2407
  selector: 'ng-template[cngxExpandableToggle]',
1591
2408
  standalone: true,
1592
2409
  }]
1593
- }], ctorParameters: () => [{ type: i0.TemplateRef }] });
2410
+ }] });
1594
2411
  /**
1595
2412
  * Molecule wrapping `CngxTruncate` with a built-in expand/collapse toggle.
1596
2413
  *
@@ -1637,24 +2454,37 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1637
2454
  * <example-url>http://localhost:4200/#/common/layout/expandable-text/custom-toggle-template</example-url>
1638
2455
  */
1639
2456
  class CngxExpandableText {
2457
+ i18n = injectLayoutI18n();
1640
2458
  /** Maximum visible lines when collapsed. */
1641
2459
  lines = input(3, ...(ngDevMode ? [{ debugName: "lines" }] : /* istanbul ignore next */ []));
1642
2460
  /** Whether the text is expanded. Supports two-way `[(expanded)]` binding. */
1643
2461
  expanded = model(false, ...(ngDevMode ? [{ debugName: "expanded" }] : /* istanbul ignore next */ []));
1644
- /** Label for the "show more" button. */
1645
- moreLabel = input('Show more', ...(ngDevMode ? [{ debugName: "moreLabel" }] : /* istanbul ignore next */ []));
1646
- /** Label for the "show less" button. */
1647
- lessLabel = input('Show less', ...(ngDevMode ? [{ debugName: "lessLabel" }] : /* istanbul ignore next */ []));
2462
+ /**
2463
+ * Label for the "show more" button. Unbound, it follows
2464
+ * `CNGX_LAYOUT_I18N.expandableTextMore`.
2465
+ */
2466
+ moreLabel = input(undefined, ...(ngDevMode ? [{ debugName: "moreLabel" }] : /* istanbul ignore next */ []));
2467
+ /**
2468
+ * Label for the "show less" button. Unbound, it follows
2469
+ * `CNGX_LAYOUT_I18N.expandableTextLess`.
2470
+ */
2471
+ lessLabel = input(undefined, ...(ngDevMode ? [{ debugName: "lessLabel" }] : /* istanbul ignore next */ []));
2472
+ resolvedMoreLabel = computed(() => this.moreLabel() ?? this.i18n().expandableTextMore, ...(ngDevMode ? [{ debugName: "resolvedMoreLabel" }] : /* istanbul ignore next */ []));
2473
+ resolvedLessLabel = computed(() => this.lessLabel() ?? this.i18n().expandableTextLess, ...(ngDevMode ? [{ debugName: "resolvedLessLabel" }] : /* istanbul ignore next */ []));
1648
2474
  /** Optional custom toggle template projected by the consumer. */
1649
2475
  customToggle = contentChild(CngxExpandableToggle, ...(ngDevMode ? [{ debugName: "customToggle" }] : /* istanbul ignore next */ []));
1650
- /** Template context for the custom toggle. */
1651
- toggleContext() {
1652
- return {
1653
- $implicit: this.expanded(),
1654
- expanded: this.expanded(),
1655
- toggle: () => this.expanded.set(!this.expanded()),
1656
- };
1657
- }
2476
+ /** Stable toggle closure - a fresh closure per context would defeat the equal fn below. */
2477
+ toggleFn = () => this.expanded.set(!this.expanded());
2478
+ /**
2479
+ * Template context for the custom toggle. Structural `equal` fn so
2480
+ * `ngTemplateOutletContext` does not rebind the embedded view on every
2481
+ * CD cycle (same rule as the CngxTag slot contexts).
2482
+ */
2483
+ toggleContext = computed(() => ({
2484
+ $implicit: this.expanded(),
2485
+ expanded: this.expanded(),
2486
+ toggle: this.toggleFn,
2487
+ }), { ...(ngDevMode ? { debugName: "toggleContext" } : /* istanbul ignore next */ {}), equal: (a, b) => a.expanded === b.expanded });
1658
2488
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxExpandableText, deps: [], target: i0.ɵɵFactoryTarget.Component });
1659
2489
  static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.4", type: CngxExpandableText, isStandalone: true, selector: "cngx-expandable-text", inputs: { lines: { classPropertyName: "lines", publicName: "lines", isSignal: true, isRequired: false, transformFunction: null }, expanded: { classPropertyName: "expanded", publicName: "expanded", isSignal: true, isRequired: false, transformFunction: null }, moreLabel: { classPropertyName: "moreLabel", publicName: "moreLabel", isSignal: true, isRequired: false, transformFunction: null }, lessLabel: { classPropertyName: "lessLabel", publicName: "lessLabel", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { expanded: "expandedChange" }, host: { styleAttribute: "display:block" }, queries: [{ propertyName: "customToggle", first: true, predicate: CngxExpandableToggle, descendants: true, isSignal: true }], exportAs: ["cngxExpandableText"], ngImport: i0, template: `
1660
2490
  <div [cngxTruncate]="lines()" [(expanded)]="expanded" #trunc="cngxTruncate">
@@ -1673,7 +2503,7 @@ class CngxExpandableText {
1673
2503
  [attr.aria-expanded]="expanded()"
1674
2504
  (click)="expanded.set(!expanded())"
1675
2505
  >
1676
- {{ expanded() ? lessLabel() : moreLabel() }}
2506
+ {{ expanded() ? resolvedLessLabel() : resolvedMoreLabel() }}
1677
2507
  </button>
1678
2508
  }
1679
2509
  }
@@ -1708,7 +2538,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1708
2538
  [attr.aria-expanded]="expanded()"
1709
2539
  (click)="expanded.set(!expanded())"
1710
2540
  >
1711
- {{ expanded() ? lessLabel() : moreLabel() }}
2541
+ {{ expanded() ? resolvedLessLabel() : resolvedMoreLabel() }}
1712
2542
  </button>
1713
2543
  }
1714
2544
  }
@@ -1724,5 +2554,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1724
2554
  * Generated bundle index. Do not edit.
1725
2555
  */
1726
2556
 
1727
- export { CngxBackdrop, CngxDrawer, CngxDrawerContent, CngxDrawerPanel, CngxExpandableText, CngxExpandableToggle, CngxHighlight, CngxInfiniteScroll, CngxIntersectionObserver, CngxMediaQuery, CngxResizeObserver, CngxScrollLock, CngxScrollSpy, CngxSkeleton, CngxStickyHeader, CngxTruncate, createScrollLock, injectMediaQuery, injectQueryParamSync };
2557
+ export { CNGX_CONTAINER_SIZE, CNGX_LAYOUT_I18N, CNGX_LAYOUT_LANGUAGE_EN, CngxBackdrop, CngxContainer, CngxDrawer, CngxDrawerContent, CngxDrawerPanel, CngxExpandableText, CngxExpandableToggle, CngxHighlight, CngxInfiniteScroll, CngxIntersectionObserver, CngxMediaQuery, CngxResizeObserver, CngxScrollEdges, CngxScrollLock, CngxScrollSpy, CngxSkeleton, CngxStickyHeader, CngxTruncate, createContainerSize, createPinnedScrollLock, createResizeSignal, createScrollEdges, createScrollLock, injectContainerSize, injectLayoutI18n, injectMediaQuery, injectQueryParamSync, observeResize, provideLayoutI18n, withLayoutI18nLabels };
1728
2558
  //# sourceMappingURL=cngx-common-layout.mjs.map