@cngx/common 0.1.0-rc.0 → 0.1.0-rc.1

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.
@@ -1,11 +1,24 @@
1
1
  import * as i0 from '@angular/core';
2
- import { InjectionToken, model, input, inject, signal, computed, Directive, TemplateRef, contentChild, DestroyRef, afterNextRender, untracked, effect, makeEnvironmentProviders, isDevMode, linkedSignal, runInInjectionContext } from '@angular/core';
2
+ import { InjectionToken, model, input, inject, Injector, computed, output, signal, Directive, TemplateRef, contentChild, DestroyRef, afterNextRender, untracked, effect, makeEnvironmentProviders, isDevMode, linkedSignal, runInInjectionContext } from '@angular/core';
3
3
  import { CNGX_COMMIT_CONTROLLER_FACTORY } from '@cngx/common/data';
4
4
  import { createTransitionTracker, CNGX_STATEFUL, nextUid } from '@cngx/core/utils';
5
- import { isObservable } from 'rxjs';
5
+ import { isObservable, Observable } from 'rxjs';
6
6
  import { toSignal, takeUntilDestroyed } from '@angular/core/rxjs-interop';
7
- import { Router, NavigationEnd } from '@angular/router';
8
- import { filter } from 'rxjs/operators';
7
+ import { Router, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';
8
+ import { filter, take } from 'rxjs/operators';
9
+
10
+ /**
11
+ * DI fallback the presenter reads when its `[commitAction]` input is
12
+ * unbound. Directives compose via DI tokens, not by hand-binding
13
+ * another directive's input (Pillar 3). When a source is present and
14
+ * exposes a non-null `action()`, its `mode()` wins over the
15
+ * `[commitMode]` input.
16
+ *
17
+ * @category common/tabs
18
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/commit-action.token.ts
19
+ * @since 0.1.0
20
+ */
21
+ const CNGX_TABS_COMMIT_ACTION = new InjectionToken('CngxTabsCommitAction');
9
22
 
10
23
  /**
11
24
  * Wraps a {@link CngxCommitController} with the action-shape adapter
@@ -105,7 +118,9 @@ const CNGX_TABS_COMMIT_HANDLER_FACTORY = new InjectionToken('CngxTabsCommitHandl
105
118
  /**
106
119
  * DI token for the tab presenter's contract. Presenter provides via
107
120
  * `useExisting`; `CngxTab` injects to register; the organism injects
108
- * to forward keyboard nav from `CngxRovingTabindex`.
121
+ * to drive the APG tablist keyboard model (automatic activation via
122
+ * `select()`, roving stop derived from `activeId`) through
123
+ * `createTabKeyboardNav`.
109
124
  *
110
125
  * @category common/tabs
111
126
  * @wcag AA
@@ -144,15 +159,66 @@ class CngxTabGroupPresenter {
144
159
  * action's resolution decides whether the change lands. Supersede
145
160
  * semantics come from the commit-controller - a rapid second
146
161
  * `select(...)` cancels the in-flight runner.
162
+ *
163
+ * @internal Two-field alias - bind the public `[commitAction]`; read
164
+ * the resolved {@link commitAction} computed (input ?? DI fallback).
147
165
  */
148
- commitAction = input(null, ...(ngDevMode ? [{ debugName: "commitAction" }] : /* istanbul ignore next */ []));
166
+ commitActionInput = input(null, { ...(ngDevMode ? { debugName: "commitActionInput" } : /* istanbul ignore next */ {}), alias: 'commitAction' });
149
167
  /**
150
168
  * Default `'optimistic'` - tab change is navigation, not a save,
151
169
  * so eager visual feedback matches the user's mental model.
152
170
  * Switch to `'pessimistic'` when the new tab must wait for the
153
171
  * action to confirm.
172
+ *
173
+ * @internal Two-field alias - bind the public `[commitMode]`; read
174
+ * the resolved {@link commitMode} computed (DI fallback mode wins
175
+ * when a routed action is active).
176
+ */
177
+ commitModeInput = input('optimistic', { ...(ngDevMode ? { debugName: "commitModeInput" } : /* istanbul ignore next */ {}), alias: 'commitMode' });
178
+ injector = inject(Injector);
179
+ // Resolved lazily, never in a field initialiser: a sync directive
180
+ // (e.g. [cngxTabsRouteSync]) provides CNGX_TABS_COMMIT_ACTION via
181
+ // useExisting and itself injects this presenter as its host, so
182
+ // eager injection here would close a construction cycle (NG0200).
183
+ // First read happens at select()/template time - after both
184
+ // directives exist. The source is static per element, so memoising
185
+ // the resolution is safe.
186
+ injectedActionSource;
187
+ resolveInjectedAction() {
188
+ if (this.injectedActionSource === undefined) {
189
+ this.injectedActionSource = this.injector.get(CNGX_TABS_COMMIT_ACTION, null);
190
+ }
191
+ return this.injectedActionSource;
192
+ }
193
+ /**
194
+ * Resolved commit-action: the `[commitAction]` input when bound, else
195
+ * the {@link CNGX_TABS_COMMIT_ACTION} DI fallback (routed path), else
196
+ * `null`. `select()` reads this.
154
197
  */
155
- commitMode = input('optimistic', ...(ngDevMode ? [{ debugName: "commitMode" }] : /* istanbul ignore next */ []));
198
+ commitAction = computed(() => this.commitActionInput() ?? this.resolveInjectedAction()?.action() ?? null, ...(ngDevMode ? [{ debugName: "commitAction" }] : /* istanbul ignore next */ []));
199
+ /**
200
+ * Resolved commit mode. When the DI fallback supplies an active
201
+ * action its `mode` wins - the routed path pins `'pessimistic'` so a
202
+ * stray `[commitMode]="'optimistic'"` cannot break the
203
+ * route-follows-resolution invariant. Otherwise the `[commitMode]`
204
+ * input drives.
205
+ */
206
+ commitMode = computed(() => {
207
+ const source = this.resolveInjectedAction();
208
+ return source?.action() ? source.mode() : this.commitModeInput();
209
+ }, ...(ngDevMode ? [{ debugName: "commitMode" }] : /* istanbul ignore next */ []));
210
+ /**
211
+ * Emitted when a tab's close affordance is activated (the close
212
+ * button or Delete/Backspace on the focused tab). The presenter has
213
+ * already moved the active index onto the surviving neighbour; the
214
+ * consumer removes the tab from its own data in the handler.
215
+ */
216
+ tabClose = output();
217
+ /**
218
+ * Emitted when the add-tab affordance is activated. The consumer
219
+ * appends a tab to its own data; the presenter owns no creation logic.
220
+ */
221
+ tabAdd = output();
156
222
  genericFactory = inject(CNGX_COMMIT_CONTROLLER_FACTORY);
157
223
  commitController = this.genericFactory();
158
224
  commitHandler = inject(CNGX_TABS_COMMIT_HANDLER_FACTORY)({
@@ -323,8 +389,29 @@ class CngxTabGroupPresenter {
323
389
  this.select(idx);
324
390
  }
325
391
  }
392
+ requestClose(id) {
393
+ const tabs = this.tabs();
394
+ const index = tabs.findIndex((h) => h.id === id);
395
+ if (index < 0) {
396
+ return;
397
+ }
398
+ const active = this.clampedIndex();
399
+ // Only closing a tab BEFORE the active one needs a pre-emptive
400
+ // index shift: the active tab moves down one slot once the consumer
401
+ // removes the closed tab, so decrement to keep the same tab active.
402
+ // Closing the active tab (or one after it) needs no write -
403
+ // `clampedIndex` re-derives against the shorter array and lands on
404
+ // the next tab (or the new last when the closed tab was last).
405
+ if (index < active) {
406
+ this.activeIndex.set(active - 1);
407
+ }
408
+ this.tabClose.emit({ id, index });
409
+ }
410
+ requestAdd() {
411
+ this.tabAdd.emit();
412
+ }
326
413
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabGroupPresenter, deps: [], target: i0.ɵɵFactoryTarget.Directive });
327
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxTabGroupPresenter, isStandalone: true, selector: "[cngxTabGroup]", inputs: { activeIndex: { classPropertyName: "activeIndex", publicName: "activeIndex", 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 }, commitAction: { classPropertyName: "commitAction", publicName: "commitAction", isSignal: true, isRequired: false, transformFunction: null }, commitMode: { classPropertyName: "commitMode", publicName: "commitMode", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { activeIndex: "activeIndexChange" }, providers: [
414
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxTabGroupPresenter, isStandalone: true, selector: "[cngxTabGroup]", inputs: { activeIndex: { classPropertyName: "activeIndex", publicName: "activeIndex", 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 }, commitActionInput: { classPropertyName: "commitActionInput", publicName: "commitAction", isSignal: true, isRequired: false, transformFunction: null }, commitModeInput: { classPropertyName: "commitModeInput", publicName: "commitMode", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { activeIndex: "activeIndexChange", tabClose: "tabClose", tabAdd: "tabAdd" }, providers: [
328
415
  { provide: CNGX_TAB_GROUP_HOST, useExisting: CngxTabGroupPresenter },
329
416
  { provide: CNGX_STATEFUL, useExisting: CngxTabGroupPresenter },
330
417
  ], exportAs: ["cngxTabGroup"], ngImport: i0 });
@@ -340,19 +427,22 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
340
427
  { provide: CNGX_STATEFUL, useExisting: CngxTabGroupPresenter },
341
428
  ],
342
429
  }]
343
- }], propDecorators: { activeIndex: [{ type: i0.Input, args: [{ isSignal: true, alias: "activeIndex", required: false }] }, { type: i0.Output, args: ["activeIndexChange"] }], orientation: [{ type: i0.Input, args: [{ isSignal: true, alias: "orientation", required: false }] }], loop: [{ type: i0.Input, args: [{ isSignal: true, alias: "loop", required: false }] }], commitAction: [{ type: i0.Input, args: [{ isSignal: true, alias: "commitAction", required: false }] }], commitMode: [{ type: i0.Input, args: [{ isSignal: true, alias: "commitMode", required: false }] }] } });
430
+ }], propDecorators: { activeIndex: [{ type: i0.Input, args: [{ isSignal: true, alias: "activeIndex", required: false }] }, { type: i0.Output, args: ["activeIndexChange"] }], orientation: [{ type: i0.Input, args: [{ isSignal: true, alias: "orientation", required: false }] }], loop: [{ type: i0.Input, args: [{ isSignal: true, alias: "loop", required: false }] }], commitActionInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "commitAction", required: false }] }], commitModeInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "commitMode", required: false }] }], tabClose: [{ type: i0.Output, args: ["tabClose"] }], tabAdd: [{ type: i0.Output, args: ["tabAdd"] }] } });
344
431
  /**
345
432
  * Structural equality for the tab registry. Compares length and
346
- * per-entry `id`, `disabled()`, and `label()`.
433
+ * per-entry `id`, `disabled()`, `label()`, `subLabel()`, and
434
+ * `closable()`.
347
435
  *
348
- * `errorAggregator` is left out on purpose. The handle is a stable
349
- * per-tab reference injected once, so comparing it would push the
350
- * memoisation burden onto consumers and break the structural-equal
351
- * contract.
436
+ * `errorAggregator`, `hasError`, and `errorMessage` are left out on
437
+ * purpose. The handle is a stable per-tab reference injected once, and
438
+ * the organism reads `tab.hasError()` / `tab.errorMessage()` reactively
439
+ * off that handle (not off array identity), so the badge + descriptor
440
+ * update on error-state changes without the registry array re-emitting.
441
+ * Comparing them here would push the memoisation burden onto consumers
442
+ * and break the structural-equal contract.
352
443
  *
353
- * Reading `disabled()` and `label()` here doesn't subscribe - the
354
- * comparator runs synchronously inside `signal.set()`, outside any
355
- * tracking context.
444
+ * Reading the signals here doesn't subscribe - the comparator runs
445
+ * synchronously inside `signal.set()`, outside any tracking context.
356
446
  *
357
447
  * @internal
358
448
  */
@@ -366,7 +456,9 @@ function tabsEqual(a, b) {
366
456
  for (let i = 0; i < a.length; i++) {
367
457
  if (a[i].id !== b[i].id ||
368
458
  a[i].disabled() !== b[i].disabled() ||
369
- a[i].label() !== b[i].label()) {
459
+ a[i].label() !== b[i].label() ||
460
+ a[i].subLabel() !== b[i].subLabel() ||
461
+ a[i].closable() !== b[i].closable()) {
370
462
  return false;
371
463
  }
372
464
  }
@@ -461,6 +553,42 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
461
553
  }]
462
554
  }] });
463
555
 
556
+ /**
557
+ * Structural slot directive marking a tab's secondary label template.
558
+ * Discovered by `<cngx-tab-group>` via `contentChild` on each
559
+ * `CngxTab` and rendered as a stacked second line under the primary
560
+ * label. Per-tab content, mirroring `CngxTabLabel` - the convenience
561
+ * `[subLabel]` string input on `CngxTab` covers the plain-text case.
562
+ *
563
+ * ```html
564
+ * <div cngxTab id="bookmarks">
565
+ * <ng-template cngxTabLabel>Bookmarks</ng-template>
566
+ * <ng-template cngxTabSubLabel>45 saved</ng-template>
567
+ * <ng-template cngxTabContent>...</ng-template>
568
+ * </div>
569
+ * ```
570
+ *
571
+ * @category common/tabs
572
+ * @wcag AA
573
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/slots/tab-sub-label.directive.ts
574
+ * @since 0.1.0
575
+ * @relatedTo CngxTab, CngxTabLabel, CngxTabContent
576
+ * <example-url>http://localhost:4200/#/ui/tabs/tab-sub-label/label-with-count</example-url>
577
+ */
578
+ class CngxTabSubLabel {
579
+ templateRef = inject((TemplateRef));
580
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabSubLabel, deps: [], target: i0.ɵɵFactoryTarget.Directive });
581
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxTabSubLabel, isStandalone: true, selector: "ng-template[cngxTabSubLabel]", exportAs: ["cngxTabSubLabel"], ngImport: i0 });
582
+ }
583
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabSubLabel, decorators: [{
584
+ type: Directive,
585
+ args: [{
586
+ selector: 'ng-template[cngxTabSubLabel]',
587
+ exportAs: 'cngxTabSubLabel',
588
+ standalone: true,
589
+ }]
590
+ }] });
591
+
464
592
  /**
465
593
  * Single-tab atom. Registers with the enclosing presenter via
466
594
  * {@link CNGX_TAB_GROUP_HOST} on construction; deregisters via
@@ -488,28 +616,88 @@ class CngxTab {
488
616
  id = input(nextUid('cngx-tab-'), ...(ngDevMode ? [{ debugName: "id" }] : /* istanbul ignore next */ []));
489
617
  disabled = input(false, ...(ngDevMode ? [{ debugName: "disabled" }] : /* istanbul ignore next */ []));
490
618
  label = input(undefined, ...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
619
+ /**
620
+ * Optional secondary text line under the primary label (a count, a
621
+ * status word, a short detail). Convenience for the common text
622
+ * case, parallel to `[label]`; the `*cngxTabSubLabel` slot covers
623
+ * richer content. Folds into the tab's accessible name.
624
+ */
625
+ subLabel = input(undefined, ...(ngDevMode ? [{ debugName: "subLabel" }] : /* istanbul ignore next */ []));
491
626
  errorAggregator = input(undefined, ...(ngDevMode ? [{ debugName: "errorAggregator" }] : /* istanbul ignore next */ []));
627
+ /**
628
+ * Direct error flag for the common "this tab is invalid" case - no
629
+ * `errorAggregator` boilerplate required. `true` or a non-empty string
630
+ * drives the error state; a string doubles as the inline message
631
+ * (surfaced via the `*cngxTabErrorBadge` slot context). `false` / `''`
632
+ * clear it. The aggregator stays the rich multi-source forms path; the
633
+ * two channels compose (either errors). Mirrors `CngxStep.error`.
634
+ */
635
+ error = input(false, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
636
+ /**
637
+ * Resolved direct-error message: the `[error]` string when non-empty,
638
+ * else `undefined`. Carried onto the registration handle so the error
639
+ * badge slot can render it. `computed` over the input - never written.
640
+ */
641
+ errorMessage = computed(() => {
642
+ const value = this.error();
643
+ return typeof value === 'string' && value !== '' ? value : undefined;
644
+ }, ...(ngDevMode ? [{ debugName: "errorMessage" }] : /* istanbul ignore next */ []));
645
+ /**
646
+ * Per-tab error fold driving the badge + SR descriptor. `true` when
647
+ * the direct `[error]` flag is set OR the optional aggregator wants to
648
+ * reveal (`shouldShow()` = `hasError` AND scope reveal-state). The
649
+ * aggregator arm reads `shouldShow`, not `hasError`, so deferred-reveal
650
+ * validation stays silent until revealed - the direct flag has no
651
+ * reveal concept (the consumer sets it when it wants it shown). A
652
+ * boolean, not a status enum: tabs carry no success/completed/disabled
653
+ * model (Pillar 3).
654
+ */
655
+ hasError = computed(() => {
656
+ const directError = this.error();
657
+ return ((directError !== false && directError !== '') ||
658
+ (this.errorAggregator()?.shouldShow?.() ?? false));
659
+ }, { ...(ngDevMode ? { debugName: "hasError" } : /* istanbul ignore next */ {}), equal: Object.is });
660
+ /**
661
+ * Per-tab close-affordance override. `undefined` (default) inherits
662
+ * the group-level `[closable]` resolution; set `false` to pin this
663
+ * tab open inside a dismissable group, or `true` to make a single tab
664
+ * closable while the group default is off.
665
+ */
666
+ closable = input(undefined, ...(ngDevMode ? [{ debugName: "closable" }] : /* istanbul ignore next */ []));
492
667
  labelTemplate = contentChild(CngxTabLabel, ...(ngDevMode ? [{ debugName: "labelTemplate" }] : /* istanbul ignore next */ []));
668
+ subLabelTemplate = contentChild(CngxTabSubLabel, ...(ngDevMode ? [{ debugName: "subLabelTemplate" }] : /* istanbul ignore next */ []));
493
669
  contentTemplate = contentChild(CngxTabContent, ...(ngDevMode ? [{ debugName: "contentTemplate" }] : /* istanbul ignore next */ []));
494
670
  host = inject(CNGX_TAB_GROUP_HOST, { optional: true });
671
+ destroyRef = inject(DestroyRef);
495
672
  /** `true` when the presenter's `activeId` equals this tab's id. */
496
673
  selected = computed(() => this.host?.activeId() === this.id(), { ...(ngDevMode ? { debugName: "selected" } : /* istanbul ignore next */ {}), equal: Object.is });
497
674
  constructor() {
498
675
  if (!this.host) {
499
676
  throw new Error('CngxTab: no enclosing CngxTabGroupPresenter found. Wrap the tab inside an element carrying [cngxTabGroup] (or place it inside <cngx-tab-group>).');
500
677
  }
678
+ }
679
+ ngOnInit() {
680
+ // Register in ngOnInit, NOT the constructor: a dynamically-bound
681
+ // `[id]` (or `[label]`) signal input is not applied until the first
682
+ // change detection, so a constructor read would capture the default
683
+ // auto-id. The handle id is the stable key consumers map `(tabClose)`
684
+ // back to their data with, so it must reflect the bound `[id]`.
685
+ const host = this.host;
501
686
  const tabId = this.id();
502
- this.host.register({
687
+ host.register({
503
688
  id: tabId,
504
689
  label: this.label,
690
+ subLabel: this.subLabel,
505
691
  disabled: this.disabled,
506
692
  errorAggregator: this.errorAggregator,
693
+ hasError: this.hasError,
694
+ errorMessage: this.errorMessage,
695
+ closable: this.closable,
507
696
  });
508
- const host = this.host;
509
- inject(DestroyRef).onDestroy(() => host.unregister(tabId));
697
+ this.destroyRef.onDestroy(() => host.unregister(tabId));
510
698
  }
511
699
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTab, deps: [], target: i0.ɵɵFactoryTarget.Directive });
512
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.2.0", version: "21.2.4", type: CngxTab, isStandalone: true, selector: "[cngxTab]", inputs: { id: { classPropertyName: "id", publicName: "id", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null }, label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null }, errorAggregator: { classPropertyName: "errorAggregator", publicName: "errorAggregator", isSignal: true, isRequired: false, transformFunction: null } }, queries: [{ propertyName: "labelTemplate", first: true, predicate: CngxTabLabel, descendants: true, isSignal: true }, { propertyName: "contentTemplate", first: true, predicate: CngxTabContent, descendants: true, isSignal: true }], exportAs: ["cngxTab"], ngImport: i0 });
700
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.2.0", version: "21.2.4", type: CngxTab, isStandalone: true, selector: "[cngxTab]", inputs: { id: { classPropertyName: "id", publicName: "id", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null }, label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null }, subLabel: { classPropertyName: "subLabel", publicName: "subLabel", isSignal: true, isRequired: false, transformFunction: null }, errorAggregator: { classPropertyName: "errorAggregator", publicName: "errorAggregator", isSignal: true, isRequired: false, transformFunction: null }, error: { classPropertyName: "error", publicName: "error", isSignal: true, isRequired: false, transformFunction: null }, closable: { classPropertyName: "closable", publicName: "closable", isSignal: true, isRequired: false, transformFunction: null } }, queries: [{ propertyName: "labelTemplate", first: true, predicate: CngxTabLabel, descendants: true, isSignal: true }, { propertyName: "subLabelTemplate", first: true, predicate: CngxTabSubLabel, descendants: true, isSignal: true }, { propertyName: "contentTemplate", first: true, predicate: CngxTabContent, descendants: true, isSignal: true }], exportAs: ["cngxTab"], ngImport: i0 });
513
701
  }
514
702
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTab, decorators: [{
515
703
  type: Directive,
@@ -518,7 +706,22 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
518
706
  exportAs: 'cngxTab',
519
707
  standalone: true,
520
708
  }]
521
- }], ctorParameters: () => [], propDecorators: { id: [{ type: i0.Input, args: [{ isSignal: true, alias: "id", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }], errorAggregator: [{ type: i0.Input, args: [{ isSignal: true, alias: "errorAggregator", required: false }] }], labelTemplate: [{ type: i0.ContentChild, args: [i0.forwardRef(() => CngxTabLabel), { isSignal: true }] }], contentTemplate: [{ type: i0.ContentChild, args: [i0.forwardRef(() => CngxTabContent), { isSignal: true }] }] } });
709
+ }], ctorParameters: () => [], propDecorators: { id: [{ type: i0.Input, args: [{ isSignal: true, alias: "id", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }], subLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "subLabel", required: false }] }], errorAggregator: [{ type: i0.Input, args: [{ isSignal: true, alias: "errorAggregator", required: false }] }], error: [{ type: i0.Input, args: [{ isSignal: true, alias: "error", required: false }] }], closable: [{ type: i0.Input, args: [{ isSignal: true, alias: "closable", required: false }] }], labelTemplate: [{ type: i0.ContentChild, args: [i0.forwardRef(() => CngxTabLabel), { isSignal: true }] }], subLabelTemplate: [{ type: i0.ContentChild, args: [i0.forwardRef(() => CngxTabSubLabel), { isSignal: true }] }], contentTemplate: [{ type: i0.ContentChild, args: [i0.forwardRef(() => CngxTabContent), { isSignal: true }] }] } });
710
+
711
+ /**
712
+ * Single dev-warning both tab sync directives emit when `@angular/router`
713
+ * is not provided. Shared so the message stays identical across
714
+ * {@link CngxTabsFragmentSync} (deep-linking) and {@link CngxTabsRouteSync}
715
+ * (router-outlet); only the `enables` clause differs. The URL readers
716
+ * themselves stay separate - they target different surfaces (fragment /
717
+ * query-param vs route path) and must not converge.
718
+ *
719
+ * @internal
720
+ */
721
+ function warnTabsRouterAbsent(directive, enables) {
722
+ console.warn(`${directive}: no Router available - directive is a no-op. ` +
723
+ `Provide @angular/router via provideRouter(...) to enable ${enables}.`);
724
+ }
522
725
 
523
726
  /**
524
727
  * URL deep-linking for tab groups. Bidirectional sync between
@@ -546,10 +749,7 @@ class CngxTabsFragmentSync {
546
749
  router = inject(Router, { optional: true });
547
750
  constructor() {
548
751
  if (!this.router) {
549
- afterNextRender(() => {
550
- console.warn('CngxTabsFragmentSync: no Router available - directive is a no-op. ' +
551
- 'Provide @angular/router via provideRouter(...) to enable deep-linking.');
552
- });
752
+ afterNextRender(() => warnTabsRouterAbsent('CngxTabsFragmentSync', 'deep-linking'));
553
753
  return;
554
754
  }
555
755
  const router = this.router;
@@ -625,12 +825,205 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
625
825
  }]
626
826
  }], ctorParameters: () => [], propDecorators: { mode: [{ type: i0.Input, args: [{ isSignal: true, alias: "mode", required: false }] }], paramName: [{ type: i0.Input, args: [{ isSignal: true, alias: "paramName", required: false }] }] } });
627
827
 
828
+ /**
829
+ * Default tab-to-route mapping: the tab id is the child segment.
830
+ * Shared so the factory and `[cngxTabsRouteSync]` reference one
831
+ * definition instead of inlining the closure twice.
832
+ *
833
+ * @internal
834
+ */
835
+ const cngxDefaultTabRoute = (handle) => [handle.id];
836
+ /**
837
+ * Builds a {@link CngxTabsCommitAction} that gates a tab switch through
838
+ * `@angular/router`. The action navigates to the target tab's route and
839
+ * resolves on the router's own outcome:
840
+ *
841
+ * - `NavigationEnd` → `true` (commit the switch)
842
+ * - `NavigationCancel` (a `CanDeactivate` guard blocked) → `false`
843
+ * - `NavigationError` (guard/resolver threw) → `false`
844
+ *
845
+ * Routed tabs reuse the presenter's commit lifecycle verbatim - the
846
+ * router navigation is simply the async op. In pessimistic mode the
847
+ * active tab follows the *resolved* route, so a cancelled guard keeps
848
+ * the old tab with zero extra gate machinery. The events subscription
849
+ * is opened *before* `navigate(...)` so a synchronously-resolving
850
+ * navigation cannot emit before the action is listening; the commit
851
+ * controller's `cancel()` unsubscribes on supersede.
852
+ *
853
+ * @category common/tabs
854
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/router-commit.ts
855
+ * @since 0.1.0
856
+ */
857
+ function createTabRouterCommit(opts) {
858
+ const routeFor = opts.routeFor ?? cngxDefaultTabRoute;
859
+ return (_fromIndex, toIndex) => new Observable((subscriber) => {
860
+ const target = opts.tabs()[toIndex];
861
+ if (!target) {
862
+ subscriber.next(false);
863
+ subscriber.complete();
864
+ return;
865
+ }
866
+ const sub = opts.router.events
867
+ .pipe(filter((e) => e instanceof NavigationEnd ||
868
+ e instanceof NavigationCancel ||
869
+ e instanceof NavigationError), take(1))
870
+ .subscribe((event) => {
871
+ subscriber.next(event instanceof NavigationEnd);
872
+ subscriber.complete();
873
+ });
874
+ // A rejected promise surfaces on the events stream as
875
+ // NavigationError, so the subscription above is the single
876
+ // resolution path; swallow the promise rejection to avoid an
877
+ // unhandled-rejection warning.
878
+ opts.router.navigate(routeFor(target)).catch(() => undefined);
879
+ return () => sub.unsubscribe();
880
+ });
881
+ }
882
+
883
+ /**
884
+ * Router-outlet integration for tab groups. Opt-in via
885
+ * `[cngxTabsRouteSync]` on the presenter element. Each tab is an
886
+ * Angular child route whose component renders into a `<router-outlet>`;
887
+ * switching tabs navigates, and a `CanDeactivate` guard can gate the
888
+ * leave.
889
+ *
890
+ * Supplies the presenter's commit-action through the
891
+ * {@link CNGX_TABS_COMMIT_ACTION} DI fallback (no consumer
892
+ * `[commitAction]` hand-binding) and pins **pessimistic** mode so the
893
+ * active tab follows the *resolved* route - a guard-cancelled switch
894
+ * keeps the old tab. The routing gate reuses the presenter's commit
895
+ * lifecycle verbatim; the router navigation is the async op.
896
+ *
897
+ * Seeds the active tab from the current URL on mount and reflects
898
+ * external navigations (back/forward, direct URL) into `activeIndex`
899
+ * *without* re-navigating - those writes bypass the commit-action,
900
+ * since the router is already at the resolved route.
901
+ *
902
+ * `Router` is optional - without it the directive logs a single dev
903
+ * warning via `afterNextRender`, exposes a null action, and becomes a
904
+ * no-op. Mirrors {@link CngxTabsFragmentSync}; every `activeIndex`
905
+ * write inside an effect sits in `untracked()`.
906
+ *
907
+ * @category common/tabs
908
+ * @docsKind primary
909
+ * @wcag AA
910
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/route-sync.directive.ts
911
+ * @since 0.1.0
912
+ * @relatedTo CngxTabGroupPresenter, CngxTabsFragmentSync, createTabRouterCommit
913
+ */
914
+ class CngxTabsRouteSync {
915
+ /**
916
+ * Maps a tab handle to its router command array. Default
917
+ * `(handle) => [handle.id]` - the tab id is the child segment.
918
+ * Override for real route paths.
919
+ */
920
+ routeFor = input(cngxDefaultTabRoute, ...(ngDevMode ? [{ debugName: "routeFor" }] : /* istanbul ignore next */ []));
921
+ host = inject(CNGX_TAB_GROUP_HOST, { host: true });
922
+ router = inject(Router, { optional: true });
923
+ /**
924
+ * Pessimistic-only - not exposed as an input. The route-sync owns the
925
+ * mode so optimistic (show-then-revert) can never flash the target
926
+ * tab before a `CanDeactivate` guard decides.
927
+ */
928
+ mode = signal('pessimistic', ...(ngDevMode ? [{ debugName: "mode" }] : /* istanbul ignore next */ []));
929
+ /**
930
+ * Router commit-action read by the presenter via the DI fallback.
931
+ * `null` when no `Router` is available (graceful no-op). Rebuilt only
932
+ * when `routeFor` changes; the navigation gate itself is the async
933
+ * op inside the action.
934
+ */
935
+ action = computed(() => {
936
+ const router = this.router;
937
+ if (!router) {
938
+ return null;
939
+ }
940
+ return createTabRouterCommit({
941
+ router,
942
+ tabs: this.host.tabs,
943
+ routeFor: this.routeFor(),
944
+ });
945
+ }, ...(ngDevMode ? [{ debugName: "action" }] : /* istanbul ignore next */ []));
946
+ constructor() {
947
+ if (!this.router) {
948
+ afterNextRender(() => warnTabsRouterAbsent('CngxTabsRouteSync', 'routed tabs'));
949
+ return;
950
+ }
951
+ const router = this.router;
952
+ const destroyRef = inject(DestroyRef);
953
+ // Seed from the current URL once the registry has populated.
954
+ afterNextRender(() => {
955
+ untracked(() => this.reflectFromUrl(router));
956
+ });
957
+ const navEnd = toSignal(router.events.pipe(filter((e) => e instanceof NavigationEnd), takeUntilDestroyed(destroyRef)), { initialValue: null });
958
+ effect(() => {
959
+ const e = navEnd();
960
+ if (!e) {
961
+ return;
962
+ }
963
+ untracked(() => this.reflectFromUrl(router));
964
+ });
965
+ }
966
+ /**
967
+ * Mirror the URL's active tab onto `activeIndex` without navigating.
968
+ * Writing the index directly (not via `select()`) is the re-entry
969
+ * guard: `select()` would re-run the commit-action and navigate to
970
+ * the route the router is already on, leaving the commit pending
971
+ * forever.
972
+ */
973
+ reflectFromUrl(router) {
974
+ const next = this.readActiveId(router);
975
+ if (!next || next === this.host.activeId()) {
976
+ return;
977
+ }
978
+ const index = this.host.tabs().findIndex((t) => t.id === next);
979
+ if (index >= 0) {
980
+ this.host.activeIndex.set(index);
981
+ }
982
+ }
983
+ /**
984
+ * Find the tab whose route is the trailing segment(s) of the current
985
+ * URL path. Anchors on position (a suffix match), not a loose
986
+ * "appears anywhere" scan - a tab id that happens to equal an
987
+ * unrelated parent segment cannot win. The path is taken before any
988
+ * query/fragment. If two tabs produce the same trailing segment(s)
989
+ * (only possible with a custom `routeFor` that collides), the first
990
+ * registered tab wins - the default id-based mapping never collides.
991
+ */
992
+ readActiveId(router) {
993
+ const path = router.url.split(/[?#]/)[0];
994
+ const segments = path.split('/').filter(Boolean);
995
+ const routeFor = this.routeFor();
996
+ for (const tab of this.host.tabs()) {
997
+ const route = routeFor(tab).map((command) => String(command));
998
+ if (route.length === 0 || route.length > segments.length) {
999
+ continue;
1000
+ }
1001
+ const tail = segments.slice(-route.length);
1002
+ if (tail.every((segment, i) => segment === route[i])) {
1003
+ return tab.id;
1004
+ }
1005
+ }
1006
+ return null;
1007
+ }
1008
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabsRouteSync, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1009
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxTabsRouteSync, isStandalone: true, selector: "[cngxTabsRouteSync]", inputs: { routeFor: { classPropertyName: "routeFor", publicName: "routeFor", isSignal: true, isRequired: false, transformFunction: null } }, providers: [{ provide: CNGX_TABS_COMMIT_ACTION, useExisting: CngxTabsRouteSync }], exportAs: ["cngxTabsRouteSync"], ngImport: i0 });
1010
+ }
1011
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabsRouteSync, decorators: [{
1012
+ type: Directive,
1013
+ args: [{
1014
+ selector: '[cngxTabsRouteSync]',
1015
+ exportAs: 'cngxTabsRouteSync',
1016
+ standalone: true,
1017
+ providers: [{ provide: CNGX_TABS_COMMIT_ACTION, useExisting: CngxTabsRouteSync }],
1018
+ }]
1019
+ }], ctorParameters: () => [], propDecorators: { routeFor: [{ type: i0.Input, args: [{ isSignal: true, alias: "routeFor", required: false }] }] } });
1020
+
628
1021
  const TABS_CONFIG_DEFAULTS = {
629
1022
  defaultOrientation: 'horizontal',
630
1023
  defaultLoop: true,
631
1024
  defaultCommitMode: 'optimistic',
632
- routerSyncMode: 'fragment',
633
- routerSyncParam: 'tab',
1025
+ fragmentSyncMode: 'fragment',
1026
+ fragmentSyncParam: 'tab',
634
1027
  ariaLabels: {
635
1028
  tabsRegion: 'Tabs',
636
1029
  },
@@ -714,19 +1107,107 @@ function withTabsCommitMode(mode) {
714
1107
  }));
715
1108
  }
716
1109
  /**
717
- * Configure router synchronisation for the active tab. `mode` chooses
718
- * the URL surface (URL fragment or query parameter); `param` names
719
- * the key (default `'tab'`).
1110
+ * Configure URL fragment / query-param deep-linking for the active tab
1111
+ * (the {@link CngxTabsFragmentSync} directive). `mode` chooses the URL
1112
+ * surface (URL fragment or query parameter); `param` names the key
1113
+ * (default `'tab'`).
1114
+ *
1115
+ * Not to be confused with `[cngxTabsRouteSync]`, the router-outlet
1116
+ * integration - this feature configures fragment deep-linking only.
720
1117
  *
721
1118
  * @category common/tabs
722
1119
  */
723
- function withTabsRouterSync(mode, param = 'tab') {
1120
+ function withTabsFragmentSync(mode, param = 'tab') {
724
1121
  return defineTabsConfigFeature((cfg) => ({
725
1122
  ...cfg,
726
- routerSyncMode: mode,
727
- routerSyncParam: param,
1123
+ fragmentSyncMode: mode,
1124
+ fragmentSyncParam: param,
728
1125
  }));
729
1126
  }
1127
+ /**
1128
+ * @deprecated Use {@link withTabsFragmentSync}. "Router sync" collided
1129
+ * with the new `[cngxTabsRouteSync]` router-outlet directive; this
1130
+ * feature only ever configured fragment / query-param deep-linking. The
1131
+ * alias stays for one minor release before removal.
1132
+ *
1133
+ * @category common/tabs
1134
+ */
1135
+ const withTabsRouterSync = withTabsFragmentSync;
1136
+ /**
1137
+ * Select the app-wide default visual skin for `<cngx-tab-group>`.
1138
+ * Default `'line'`. Per-instance `[skin]` Input still wins; this moves
1139
+ * the cascade default. Structure, slots, ARIA, and keyboard behaviour
1140
+ * are identical across skins - only the `[data-skin]` host attribute
1141
+ * changes the CSS layer. The Material twin (`[cngxMatTabs]`) ignores it.
1142
+ *
1143
+ * @category common/tabs
1144
+ */
1145
+ function withTabsSkin(skin) {
1146
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, skin }));
1147
+ }
1148
+ /**
1149
+ * Set the app-wide default icon layout for `<cngx-tab-group>`. Default
1150
+ * `'start'`. Per-instance `[iconLayout]` Input still wins. Orthogonal to
1151
+ * skin and orientation - only the `[data-icon-layout]` host attribute
1152
+ * changes.
1153
+ *
1154
+ * @category common/tabs
1155
+ */
1156
+ function withTabsIconLayout(layout) {
1157
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, iconLayout: layout }));
1158
+ }
1159
+ /**
1160
+ * Set the app-wide default panel render strategy for `<cngx-tab-group>`.
1161
+ * Default `'eager'` (every panel's content rendered up front, toggled
1162
+ * via `[hidden]`). `'lazy'` keep-alives content after first activation;
1163
+ * `'lazy-destroy'` renders only the active panel's content. Per-instance
1164
+ * `[panelMode]` Input still wins. The panel `<div>` always stays in the
1165
+ * DOM regardless of mode (the `aria-controls` target).
1166
+ *
1167
+ * @category common/tabs
1168
+ */
1169
+ function withTabsPanelMode(mode) {
1170
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, panelMode: mode }));
1171
+ }
1172
+ /**
1173
+ * Set the app-wide default for stretching tabs to the full strip width
1174
+ * (horizontal only). Default `false`. Per-instance `[fitted]` Input still
1175
+ * wins. No effect under `orientation="vertical"`.
1176
+ *
1177
+ * @category common/tabs
1178
+ */
1179
+ function withTabsFitted(fitted) {
1180
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, fitted }));
1181
+ }
1182
+ /**
1183
+ * Set the app-wide default tab-cluster alignment (horizontal only).
1184
+ * Default `'start'`. Per-instance `[tabAlign]` Input still wins. Ignored
1185
+ * under `orientation="vertical"` and when the group is `fitted`.
1186
+ *
1187
+ * @category common/tabs
1188
+ */
1189
+ function withTabsAlign(align) {
1190
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, tabAlign: align }));
1191
+ }
1192
+ /**
1193
+ * Set the app-wide default for whether tabs render a close affordance.
1194
+ * Default `false`. Per-instance `[closable]` Input wins; a per-`CngxTab`
1195
+ * `[closable]` override wins over both.
1196
+ *
1197
+ * @category common/tabs
1198
+ */
1199
+ function withTabsClosable(closable) {
1200
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, closable }));
1201
+ }
1202
+ /**
1203
+ * Set the app-wide default for whether the group renders an add-tab
1204
+ * button. Default `false`. Per-instance `[addable]` Input wins.
1205
+ *
1206
+ * @category common/tabs
1207
+ */
1208
+ function withTabsAddable(addable) {
1209
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, addable }));
1210
+ }
730
1211
  /**
731
1212
  * Merge ARIA labels into the cascade. Keys not provided keep their
732
1213
  * library defaults; per-instance overrides on the tab group still win.
@@ -845,6 +1326,43 @@ function withTabBusySpinnerTemplate(template) {
845
1326
  templates: { ...cfg.templates, busySpinner: template },
846
1327
  }));
847
1328
  }
1329
+ /**
1330
+ * App-wide override for the tab-icon slot. Middle tier of the 3-stage
1331
+ * cascade; per-instance `*cngxTabIcon` still wins. Sibling of
1332
+ * {@link withStepIndicatorTemplate}.
1333
+ *
1334
+ * @category common/tabs
1335
+ */
1336
+ function withTabIconTemplate(template) {
1337
+ return defineTabsConfigFeature((cfg) => ({
1338
+ ...cfg,
1339
+ templates: { ...cfg.templates, icon: template },
1340
+ }));
1341
+ }
1342
+ /**
1343
+ * App-wide override for a tab's close-button glyph. Middle tier;
1344
+ * per-instance `*cngxTabCloseIcon` still wins.
1345
+ *
1346
+ * @category common/tabs
1347
+ */
1348
+ function withTabCloseIconTemplate(template) {
1349
+ return defineTabsConfigFeature((cfg) => ({
1350
+ ...cfg,
1351
+ templates: { ...cfg.templates, closeIcon: template },
1352
+ }));
1353
+ }
1354
+ /**
1355
+ * App-wide override for the add-tab button glyph. Middle tier;
1356
+ * per-instance `*cngxTabAddIcon` still wins.
1357
+ *
1358
+ * @category common/tabs
1359
+ */
1360
+ function withTabAddIconTemplate(template) {
1361
+ return defineTabsConfigFeature((cfg) => ({
1362
+ ...cfg,
1363
+ templates: { ...cfg.templates, addIcon: template },
1364
+ }));
1365
+ }
848
1366
  function resolveFeatures(features) {
849
1367
  return features.reduce((cfg, feat) => feat(cfg), TABS_CONFIG_DEFAULTS);
850
1368
  }
@@ -886,13 +1404,40 @@ function injectTabsConfig() {
886
1404
  return inject(CNGX_TABS_CONFIG);
887
1405
  }
888
1406
 
1407
+ /**
1408
+ * Level-2 helper resolving the host-attribute cascades for
1409
+ * `<cngx-tab-group>` (skin / iconLayout). Keeps the organism class
1410
+ * under the LOC guard while making the cascade pattern reusable. Sibling
1411
+ * shape to `createStepperHostAttrs`; the resolved-type unions differ per
1412
+ * family, so the helpers are siblings, not shared code.
1413
+ *
1414
+ * Each computed honors Pillar 1 (Ableitung statt Verwaltung):
1415
+ * per-instance input wins over root config wins over library default. No
1416
+ * manual sync. The library defaults (`'line'` / `'start'`) live here,
1417
+ * not in `TABS_CONFIG_DEFAULTS` - mirroring the stepper.
1418
+ *
1419
+ * @internal
1420
+ */
1421
+ function createTabsHostAttrs(inputs) {
1422
+ return {
1423
+ resolvedSkin: computed(() => inputs.skin() ?? inputs.config.skin ?? 'line'),
1424
+ resolvedIconLayout: computed(() => inputs.iconLayout() ?? inputs.config.iconLayout ?? 'start'),
1425
+ resolvedPanelMode: computed(() => inputs.panelMode() ?? inputs.config.panelMode ?? 'eager'),
1426
+ resolvedFitted: computed(() => inputs.fitted() ?? inputs.config.fitted ?? false),
1427
+ resolvedTabAlign: computed(() => inputs.tabAlign() ?? inputs.config.tabAlign ?? 'start'),
1428
+ };
1429
+ }
1430
+
889
1431
  const TABS_I18N_DEFAULTS = {
890
1432
  tabsLabel: 'Tabs',
891
1433
  selectedTab: (label, position, count) => `Tab ${position} of ${count}: ${label}`,
1434
+ tabLabelWithDetail: (label, detail) => `${label}, ${detail}`,
892
1435
  tabHasErrors: (count) => `${count} error${count === 1 ? '' : 's'}`,
893
1436
  moreTabsLabel: (count) => `${count} more`,
894
1437
  previousTab: 'Previous tab',
895
1438
  nextTab: 'Next tab',
1439
+ closeTab: (label) => `Close "${label}"`,
1440
+ addTab: 'Add tab',
896
1441
  commitFailedRetry: 'Tab change refused — retry?',
897
1442
  commitInFlight: 'Switching tab…',
898
1443
  commitRolledBackTo: (originLabel) => `Could not save changes — reverted to "${originLabel}".`,
@@ -1364,11 +1909,304 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1364
1909
  }] });
1365
1910
 
1366
1911
  /**
1367
- * Wires the 3-stage template cascade for the three `<cngx-tab-group>`
1368
- * skin slots:
1912
+ * Structural slot for the tab-icon template. One group-level slot with
1913
+ * per-tab context (stepper-slot parity), not a per-`CngxTab` input.
1914
+ * 3-stage cascade: per-instance directive >
1915
+ * `CNGX_TABS_CONFIG.templates.icon` > none (no icon rendered).
1916
+ *
1917
+ * ```html
1918
+ * <cngx-tab-group iconLayout="start">
1919
+ * <ng-template cngxTabIcon let-tab="tab" let-active="active">
1920
+ * <cngx-icon [name]="active ? 'folder-open' : 'folder'" />
1921
+ * </ng-template>
1922
+ * </cngx-tab-group>
1923
+ * ```
1924
+ *
1925
+ * @category common/tabs/slots
1926
+ * @wcag AA
1927
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/slots/tab-icon.directive.ts
1928
+ * @since 0.1.0
1929
+ * @relatedTo CngxTabErrorBadge, CngxTab, CngxTabGroup
1930
+ */
1931
+ class CngxTabIcon {
1932
+ templateRef = inject(TemplateRef);
1933
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabIcon, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1934
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxTabIcon, isStandalone: true, selector: "ng-template[cngxTabIcon]", exportAs: ["cngxTabIcon"], ngImport: i0 });
1935
+ }
1936
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabIcon, decorators: [{
1937
+ type: Directive,
1938
+ args: [{
1939
+ selector: 'ng-template[cngxTabIcon]',
1940
+ exportAs: 'cngxTabIcon',
1941
+ standalone: true,
1942
+ }]
1943
+ }] });
1944
+
1945
+ /**
1946
+ * Structural slot for a tab's close-button glyph. 3-stage cascade:
1947
+ * per-instance directive > `CNGX_TABS_CONFIG.templates.closeIcon` >
1948
+ * `CNGX_TABS_GLYPHS.closeIcon`.
1949
+ *
1950
+ * ```html
1951
+ * <cngx-tab-group closable (tabClose)="remove($event.id)">
1952
+ * <ng-template cngxTabCloseIcon><cngx-icon name="close" /></ng-template>
1953
+ * ...
1954
+ * </cngx-tab-group>
1955
+ * ```
1956
+ *
1957
+ * @category common/tabs/slots
1958
+ * @wcag AA
1959
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/slots/tab-close-icon.directive.ts
1960
+ * @since 0.1.0
1961
+ * @relatedTo CngxTabAddIcon, CngxTabGroup
1962
+ */
1963
+ class CngxTabCloseIcon {
1964
+ templateRef = inject(TemplateRef);
1965
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabCloseIcon, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1966
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxTabCloseIcon, isStandalone: true, selector: "ng-template[cngxTabCloseIcon]", exportAs: ["cngxTabCloseIcon"], ngImport: i0 });
1967
+ }
1968
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabCloseIcon, decorators: [{
1969
+ type: Directive,
1970
+ args: [{
1971
+ selector: 'ng-template[cngxTabCloseIcon]',
1972
+ exportAs: 'cngxTabCloseIcon',
1973
+ standalone: true,
1974
+ }]
1975
+ }] });
1976
+
1977
+ /**
1978
+ * Structural slot for the add-tab button glyph. 3-stage cascade:
1979
+ * per-instance directive > `CNGX_TABS_CONFIG.templates.addIcon` >
1980
+ * `CNGX_TABS_GLYPHS.addIcon`. The button owns its `aria-label`; the
1981
+ * template paints only the glyph, so its context is `void`.
1982
+ *
1983
+ * ```html
1984
+ * <cngx-tab-group addable (tabAdd)="add()">
1985
+ * <ng-template cngxTabAddIcon><cngx-icon name="plus" /></ng-template>
1986
+ * ...
1987
+ * </cngx-tab-group>
1988
+ * ```
1989
+ *
1990
+ * @category common/tabs/slots
1991
+ * @wcag AA
1992
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/slots/tab-add-icon.directive.ts
1993
+ * @since 0.1.0
1994
+ * @relatedTo CngxTabCloseIcon, CngxTabGroup
1995
+ */
1996
+ class CngxTabAddIcon {
1997
+ templateRef = inject(TemplateRef);
1998
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabAddIcon, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1999
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxTabAddIcon, isStandalone: true, selector: "ng-template[cngxTabAddIcon]", exportAs: ["cngxTabAddIcon"], ngImport: i0 });
2000
+ }
2001
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabAddIcon, decorators: [{
2002
+ type: Directive,
2003
+ args: [{
2004
+ selector: 'ng-template[cngxTabAddIcon]',
2005
+ exportAs: 'cngxTabAddIcon',
2006
+ standalone: true,
2007
+ }]
2008
+ }] });
2009
+
2010
+ /**
2011
+ * Level-2 helper resolving the dismissable/addable affordances for
2012
+ * `<cngx-tab-group>`. Keeps the close/add cascade + interaction off the
2013
+ * organism class (LOC guard). Pillar 1: each cascade is one `computed()`.
2014
+ * The actual tab removal is the consumer's (Ableitung statt Verwaltung) -
2015
+ * `handleClose` only routes through the presenter's `requestClose`, which
2016
+ * moves the active index, and restores focus once the consumer's removal
2017
+ * has rendered.
2018
+ *
2019
+ * @category common/tabs
2020
+ */
2021
+ function createTabDismissals(opts) {
2022
+ const resolvedClosable = computed(() => opts.closable() ?? opts.config.closable ?? false, ...(ngDevMode ? [{ debugName: "resolvedClosable" }] : /* istanbul ignore next */ []));
2023
+ const resolvedAddable = computed(() => opts.addable() ?? opts.config.addable ?? false, ...(ngDevMode ? [{ debugName: "resolvedAddable" }] : /* istanbul ignore next */ []));
2024
+ const closeIconContextCache = new WeakMap();
2025
+ const isTabClosable = (tab) => tab.closable() ?? resolvedClosable();
2026
+ const handleClose = (tab, event) => {
2027
+ event?.stopPropagation();
2028
+ if (!isTabClosable(tab)) {
2029
+ return;
2030
+ }
2031
+ opts.host.requestClose(tab.id);
2032
+ // Restore focus once the consumer's removal has rendered: the new
2033
+ // active tab, then the add button, and finally the group element
2034
+ // itself (made programmatically focusable) so focus never falls to
2035
+ // `<body>` when the strip empties with no add button (APG).
2036
+ afterNextRender(() => {
2037
+ const active = opts.hostElement.querySelector('.cngx-tabs__tab[aria-selected="true"]');
2038
+ const add = opts.hostElement.querySelector('.cngx-tabs__add');
2039
+ const target = active ?? add;
2040
+ if (target) {
2041
+ target.focus();
2042
+ return;
2043
+ }
2044
+ opts.hostElement.tabIndex = -1;
2045
+ opts.hostElement.focus();
2046
+ }, { injector: opts.injector });
2047
+ };
2048
+ return {
2049
+ resolvedClosable,
2050
+ resolvedAddable,
2051
+ isTabClosable,
2052
+ closeButtonLabel: (tab) => opts.i18n.closeTab(tab.label() ?? ''),
2053
+ closeIconContextFor: (tab) => {
2054
+ let ctx = closeIconContextCache.get(tab);
2055
+ if (!ctx) {
2056
+ ctx = { tab };
2057
+ closeIconContextCache.set(tab, ctx);
2058
+ }
2059
+ return ctx;
2060
+ },
2061
+ handleClose,
2062
+ handleTabKeydown: (tab, event) => {
2063
+ if (event.key === 'Delete' && isTabClosable(tab)) {
2064
+ event.preventDefault();
2065
+ handleClose(tab);
2066
+ }
2067
+ },
2068
+ handleAdd: () => opts.host.requestAdd(),
2069
+ };
2070
+ }
2071
+
2072
+ /**
2073
+ * Level-2 helper implementing the WAI-ARIA APG tabs keyboard model for
2074
+ * `<cngx-tab-group>` with **automatic activation**: an arrow press moves
2075
+ * focus AND activates the target tab in one step, so focus and selection
2076
+ * never diverge. Keeps the keyboard logic off the organism class (LOC
2077
+ * guard) and out of a competing roving-tabindex state machine.
2078
+ *
2079
+ * Pillar 1 (Ableitung statt Verwaltung): the tab stop is derived from the
2080
+ * presenter's `activeId`, not managed as a second index. Pillar 2
2081
+ * (Kommunikation): activation routes through `host.select()`, which owns
2082
+ * disabled-skip, loop, commit gating, and the live-region announcement -
2083
+ * the keyboard layer adds only focus movement (a DOM concern the
2084
+ * presenter, living in `@cngx/common`, must not own).
2085
+ *
2086
+ * Navigation always originates from the active tab: under automatic
2087
+ * activation the focused tab is always the active one, so the clamped
2088
+ * active index is the correct origin.
2089
+ *
2090
+ * @category common/tabs
2091
+ */
2092
+ function createTabKeyboardNav(opts) {
2093
+ const clampedActive = () => {
2094
+ const len = opts.host.tabs().length;
2095
+ if (len === 0) {
2096
+ return 0;
2097
+ }
2098
+ return Math.max(0, Math.min(opts.host.activeIndex(), len - 1));
2099
+ };
2100
+ // Next enabled index in `direction`, honouring `loop`. Mirrors the
2101
+ // presenter's `selectNext`/`selectPrevious` geometry but returns the
2102
+ // resolved index so the caller can both activate and focus it.
2103
+ const step = (direction) => {
2104
+ const tabs = opts.host.tabs();
2105
+ const len = tabs.length;
2106
+ if (len === 0) {
2107
+ return null;
2108
+ }
2109
+ const loop = opts.host.loop();
2110
+ let idx = clampedActive() + direction;
2111
+ for (let i = 0; i < len; i++) {
2112
+ if (loop) {
2113
+ idx = ((idx % len) + len) % len;
2114
+ }
2115
+ else if (idx < 0 || idx >= len) {
2116
+ return null;
2117
+ }
2118
+ if (!tabs[idx].disabled()) {
2119
+ return idx;
2120
+ }
2121
+ idx += direction;
2122
+ }
2123
+ return null;
2124
+ };
2125
+ // First (direction 1) or last (direction -1) enabled tab, for Home/End.
2126
+ const edge = (direction) => {
2127
+ const tabs = opts.host.tabs();
2128
+ const len = tabs.length;
2129
+ if (direction === 1) {
2130
+ for (let i = 0; i < len; i++) {
2131
+ if (!tabs[i].disabled()) {
2132
+ return i;
2133
+ }
2134
+ }
2135
+ }
2136
+ else {
2137
+ for (let i = len - 1; i >= 0; i--) {
2138
+ if (!tabs[i].disabled()) {
2139
+ return i;
2140
+ }
2141
+ }
2142
+ }
2143
+ return null;
2144
+ };
2145
+ // Focus the tab button for the tab at `index`, keyed off the stable
2146
+ // tab id (the rendered `data-tab-id`) rather than a positional
2147
+ // `.cngx-tabs__tab[index]` lookup - so a skin that reorders or wraps
2148
+ // the tab buttons can't misdirect keyboard focus. `[role="tab"]` is
2149
+ // the APG contract every skin must honour, so it survives a class
2150
+ // rename too. The button already exists regardless of pending CD, so
2151
+ // focus is immediate and never waits on the activation's render.
2152
+ const focusTabAt = (index) => {
2153
+ const id = opts.host.tabs()[index]?.id;
2154
+ if (id == null) {
2155
+ return;
2156
+ }
2157
+ const buttons = Array.from(opts.hostElement.querySelectorAll('[role="tab"]'));
2158
+ buttons.find((button) => button.getAttribute('data-tab-id') === id)?.focus();
2159
+ };
2160
+ return {
2161
+ tabTabindex: (tab) => (tab.id === opts.host.activeId() ? 0 : -1),
2162
+ handleKeydown: (event) => {
2163
+ const horizontal = opts.host.orientation() === 'horizontal';
2164
+ let target;
2165
+ switch (event.key) {
2166
+ case 'ArrowRight':
2167
+ target = horizontal ? step(1) : null;
2168
+ break;
2169
+ case 'ArrowLeft':
2170
+ target = horizontal ? step(-1) : null;
2171
+ break;
2172
+ case 'ArrowDown':
2173
+ target = horizontal ? null : step(1);
2174
+ break;
2175
+ case 'ArrowUp':
2176
+ target = horizontal ? null : step(-1);
2177
+ break;
2178
+ case 'Home':
2179
+ target = edge(1);
2180
+ break;
2181
+ case 'End':
2182
+ target = edge(-1);
2183
+ break;
2184
+ default:
2185
+ return;
2186
+ }
2187
+ if (target === null) {
2188
+ return;
2189
+ }
2190
+ event.preventDefault();
2191
+ // Automatic activation: select first (content + aria-selected +
2192
+ // announcement follow), then move focus to the same tab button.
2193
+ opts.host.select(target);
2194
+ focusTabAt(target);
2195
+ },
2196
+ };
2197
+ }
2198
+
2199
+ /**
2200
+ * Wires the 3-stage template cascade for the `<cngx-tab-group>` skin
2201
+ * slots (errorBadge / rejectionIcon / busySpinner / icon / closeIcon /
2202
+ * addIcon):
1369
2203
  * per-instance directive >
1370
2204
  * `CNGX_TABS_CONFIG.templates.<key>` >
1371
- * `null` (built-in default).
2205
+ * `null`.
2206
+ *
2207
+ * `null` means the organism renders its built-in default - a default
2208
+ * span for the state decorations, the `CNGX_TABS_GLYPHS` glyph for
2209
+ * `closeIcon` / `addIcon`, and nothing for `icon`.
1372
2210
  *
1373
2211
  * Pure — no DI, no side effects. Safe in field-init. Sibling to
1374
2212
  * `createStepperTemplateBindings` and `createTabOverflowTemplateBindings`.
@@ -1390,13 +2228,17 @@ function createTabGroupTemplateBindings(opts) {
1390
2228
  busySpinner: computed(() => opts.busySpinnerSlot()?.templateRef ??
1391
2229
  opts.config.templates?.busySpinner ??
1392
2230
  null),
2231
+ icon: computed(() => opts.iconSlot()?.templateRef ?? opts.config.templates?.icon ?? null),
2232
+ closeIcon: computed(() => opts.closeIconSlot?.()?.templateRef ??
2233
+ opts.config.templates?.closeIcon ??
2234
+ null),
2235
+ addIcon: computed(() => opts.addIconSlot?.()?.templateRef ?? opts.config.templates?.addIcon ?? null),
1393
2236
  };
1394
2237
  }
1395
2238
 
1396
2239
  // Single-consumer factory — staged under family-uniformity
1397
- // (tabs-accepted-debt §9, alongside `createTabGroupTemplateBindings`
1398
- // and `CngxMatTabAggregatorContent`). Re-eval on second consumer or
1399
- // sibling debt closure.
2240
+ // (`createTabGroupTemplateBindings` and `CngxMatTabAggregatorContent`).
2241
+ // Re-eval on second consumer or sibling debt closure.
1400
2242
  /**
1401
2243
  * Pure factory bundling the `<cngx-tab-group>` AT-announcement +
1402
2244
  * descriptor surfaces. Owns one internal `linkedSignal`
@@ -1463,19 +2305,26 @@ function createTabGroupAnnouncements(options) {
1463
2305
  return '';
1464
2306
  }, ...(ngDevMode ? [{ debugName: "liveAnnouncement" }] : /* istanbul ignore next */ []));
1465
2307
  function statusPhrase(tab) {
1466
- const aggregator = tab.errorAggregator();
1467
- if (!aggregator?.shouldShow()) {
2308
+ if (!tab.hasError()) {
1468
2309
  return '';
1469
2310
  }
1470
- const announcement = aggregator.announcement();
2311
+ const aggregator = tab.errorAggregator();
2312
+ const announcement = aggregator?.announcement();
1471
2313
  if (announcement) {
1472
2314
  return announcement;
1473
2315
  }
1474
- return i18n.tabHasErrors(aggregator.errorCount());
2316
+ const directMessage = tab.errorMessage();
2317
+ if (directMessage) {
2318
+ return directMessage;
2319
+ }
2320
+ return i18n.tabHasErrors(aggregator?.errorCount() ?? 1);
1475
2321
  }
1476
2322
  function tabAriaLabel(tab, position) {
1477
2323
  const tabs = presenter.tabs();
1478
- return i18n.selectedTab(tab.label() ?? '', position, tabs.length);
2324
+ const label = tab.label() ?? '';
2325
+ const detail = tab.subLabel();
2326
+ const labelPart = detail ? i18n.tabLabelWithDetail(label, detail) : label;
2327
+ return i18n.selectedTab(labelPart, position, tabs.length);
1479
2328
  }
1480
2329
  // Eager seed — `linkedSignal` is lazy and the success arm doesn't
1481
2330
  // touch the tracker at construction (commitTransition is `idle`),
@@ -1509,6 +2358,10 @@ const CNGX_TABS_GLYPHS = {
1509
2358
  errorBadge: '!',
1510
2359
  /** Default visual for `*cngxTabRejectionIcon` when no override is bound. */
1511
2360
  rejectionIcon: '!',
2361
+ /** Default visual for a tab's close button when no override is bound. */
2362
+ closeIcon: '×',
2363
+ /** Default visual for the add-tab button when no override is bound. */
2364
+ addIcon: '+',
1512
2365
  };
1513
2366
 
1514
2367
  /**
@@ -1753,5 +2606,5 @@ const CNGX_DIRECTIVE_BY_ID_MAP_FACTORY = new InjectionToken('CngxDirectiveByIdMa
1753
2606
  * Generated bundle index. Do not edit.
1754
2607
  */
1755
2608
 
1756
- export { CNGX_DIRECTIVE_BY_ID_MAP_FACTORY, CNGX_DOM_ANCHOR_RETRY_FACTORY, CNGX_ORGANISM_SCROLL_SYNC_FACTORY, CNGX_OVERFLOW_POPOVER_HIGHLIGHT_FACTORY, CNGX_TABS_COMMIT_HANDLER_FACTORY, CNGX_TABS_CONFIG, CNGX_TABS_GLYPHS, CNGX_TABS_I18N, CNGX_TAB_GROUP_HOST, CNGX_TAB_OVERFLOW_DOM_ADAPTER_FACTORY, CNGX_TAB_PANEL_HOST, CngxTab, CngxTabBusySpinner, CngxTabContent, CngxTabErrorBadge, CngxTabGroupPresenter, CngxTabLabel, CngxTabOverflowItem, CngxTabOverflowTrigger, CngxTabRejectionIcon, CngxTabsFragmentSync, createCngxTabOverflowDefaultDomAdapter, createDirectiveByIdMap, createDomAnchorRetry, createOrganismScrollSync, createOverflowPopoverHighlightSync, createTabGroupAnnouncements, createTabGroupTemplateBindings, createTabOverflowTemplateBindings, createTabsCommitHandler, injectTabsConfig, injectTabsI18n, provideCngxTabs, provideCngxTabsAt, provideTabsConfig, provideTabsConfigAt, provideTabsI18n, tabOverflowOptionId, withDefaultOrientation, withTabBusySpinnerTemplate, withTabErrorBadgeTemplate, withTabOverflowItemTemplate, withTabOverflowMaxDeferMs, withTabOverflowStabilizeMs, withTabOverflowTriggerTemplate, withTabRejectionIconTemplate, withTabsAriaLabels, withTabsCommitMode, withTabsDefaultOrientation, withTabsFallbackLabels, withTabsI18nLabels, withTabsRouterSync, withTabsRovingLoop };
2609
+ export { CNGX_DIRECTIVE_BY_ID_MAP_FACTORY, CNGX_DOM_ANCHOR_RETRY_FACTORY, CNGX_ORGANISM_SCROLL_SYNC_FACTORY, CNGX_OVERFLOW_POPOVER_HIGHLIGHT_FACTORY, CNGX_TABS_COMMIT_ACTION, CNGX_TABS_COMMIT_HANDLER_FACTORY, CNGX_TABS_CONFIG, CNGX_TABS_GLYPHS, CNGX_TABS_I18N, CNGX_TAB_GROUP_HOST, CNGX_TAB_OVERFLOW_DOM_ADAPTER_FACTORY, CNGX_TAB_PANEL_HOST, CngxTab, CngxTabAddIcon, CngxTabBusySpinner, CngxTabCloseIcon, CngxTabContent, CngxTabErrorBadge, CngxTabGroupPresenter, CngxTabIcon, CngxTabLabel, CngxTabOverflowItem, CngxTabOverflowTrigger, CngxTabRejectionIcon, CngxTabSubLabel, CngxTabsFragmentSync, CngxTabsRouteSync, createCngxTabOverflowDefaultDomAdapter, createDirectiveByIdMap, createDomAnchorRetry, createOrganismScrollSync, createOverflowPopoverHighlightSync, createTabDismissals, createTabGroupAnnouncements, createTabGroupTemplateBindings, createTabKeyboardNav, createTabOverflowTemplateBindings, createTabRouterCommit, createTabsCommitHandler, createTabsHostAttrs, injectTabsConfig, injectTabsI18n, provideCngxTabs, provideCngxTabsAt, provideTabsConfig, provideTabsConfigAt, provideTabsI18n, tabOverflowOptionId, withDefaultOrientation, withTabAddIconTemplate, withTabBusySpinnerTemplate, withTabCloseIconTemplate, withTabErrorBadgeTemplate, withTabIconTemplate, withTabOverflowItemTemplate, withTabOverflowMaxDeferMs, withTabOverflowStabilizeMs, withTabOverflowTriggerTemplate, withTabRejectionIconTemplate, withTabsAddable, withTabsAlign, withTabsAriaLabels, withTabsClosable, withTabsCommitMode, withTabsDefaultOrientation, withTabsFallbackLabels, withTabsFitted, withTabsFragmentSync, withTabsI18nLabels, withTabsIconLayout, withTabsPanelMode, withTabsRouterSync, withTabsRovingLoop, withTabsSkin };
1757
2610
  //# sourceMappingURL=cngx-common-tabs.mjs.map