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

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 (72) hide show
  1. package/card/README.md +2 -1
  2. package/chart/README.md +85 -0
  3. package/command/README.md +157 -0
  4. package/data/README.md +33 -1
  5. package/dialog/README.md +23 -1
  6. package/fesm2022/cngx-common-a11y.mjs +356 -180
  7. package/fesm2022/cngx-common-a11y.mjs.map +1 -1
  8. package/fesm2022/cngx-common-audio.mjs +84 -42
  9. package/fesm2022/cngx-common-audio.mjs.map +1 -1
  10. package/fesm2022/cngx-common-card.mjs +311 -53
  11. package/fesm2022/cngx-common-card.mjs.map +1 -1
  12. package/fesm2022/cngx-common-chart.mjs +4360 -1625
  13. package/fesm2022/cngx-common-chart.mjs.map +1 -1
  14. package/fesm2022/cngx-common-command.mjs +171 -0
  15. package/fesm2022/cngx-common-command.mjs.map +1 -0
  16. package/fesm2022/cngx-common-data.mjs +1556 -616
  17. package/fesm2022/cngx-common-data.mjs.map +1 -1
  18. package/fesm2022/cngx-common-dialog.mjs +518 -112
  19. package/fesm2022/cngx-common-dialog.mjs.map +1 -1
  20. package/fesm2022/cngx-common-display.mjs +468 -87
  21. package/fesm2022/cngx-common-display.mjs.map +1 -1
  22. package/fesm2022/cngx-common-interactive.mjs +2725 -1303
  23. package/fesm2022/cngx-common-interactive.mjs.map +1 -1
  24. package/fesm2022/cngx-common-layout.mjs +943 -164
  25. package/fesm2022/cngx-common-layout.mjs.map +1 -1
  26. package/fesm2022/cngx-common-popover.mjs +769 -103
  27. package/fesm2022/cngx-common-popover.mjs.map +1 -1
  28. package/fesm2022/cngx-common-stepper.mjs +816 -348
  29. package/fesm2022/cngx-common-stepper.mjs.map +1 -1
  30. package/fesm2022/cngx-common-tabs.mjs +2330 -1554
  31. package/fesm2022/cngx-common-tabs.mjs.map +1 -1
  32. package/fesm2022/cngx-common-timeline.mjs +1170 -0
  33. package/fesm2022/cngx-common-timeline.mjs.map +1 -0
  34. package/fesm2022/cngx-common.mjs +2 -2
  35. package/fesm2022/cngx-common.mjs.map +1 -1
  36. package/interactive/README.md +15 -4
  37. package/layout/README.md +21 -1
  38. package/package.json +11 -1
  39. package/popover/README.md +18 -2
  40. package/stepper/README.md +7 -5
  41. package/theming/components/cngx-accordion.css +4 -1
  42. package/theming/components/cngx-backdrop.css +12 -0
  43. package/theming/components/cngx-badge.css +22 -0
  44. package/theming/components/cngx-bottom-sheet.css +14 -2
  45. package/theming/components/cngx-breadcrumb.css +8 -0
  46. package/theming/components/cngx-button-toggle.css +73 -5
  47. package/theming/components/cngx-data-grid.css +234 -1
  48. package/theming/components/cngx-dialog.css +25 -0
  49. package/theming/components/cngx-divider.css +12 -0
  50. package/theming/components/cngx-listbox.css +48 -12
  51. package/theming/components/cngx-menu.css +91 -15
  52. package/theming/components/cngx-popover.css +24 -0
  53. package/theming/components/cngx-recycler-placeholder.css +196 -0
  54. package/theming/components/cngx-ripple.css +2 -2
  55. package/theming/components/cngx-slider.css +32 -1
  56. package/theming/components/cngx-tooltip.css +23 -0
  57. package/timeline/README.md +155 -0
  58. package/types/cngx-common-a11y.d.ts +101 -31
  59. package/types/cngx-common-audio.d.ts +32 -32
  60. package/types/cngx-common-card.d.ts +211 -20
  61. package/types/cngx-common-chart.d.ts +1605 -169
  62. package/types/cngx-common-command.d.ts +190 -0
  63. package/types/cngx-common-data.d.ts +842 -163
  64. package/types/cngx-common-dialog.d.ts +372 -28
  65. package/types/cngx-common-display.d.ts +432 -148
  66. package/types/cngx-common-interactive.d.ts +1553 -370
  67. package/types/cngx-common-layout.d.ts +613 -27
  68. package/types/cngx-common-popover.d.ts +376 -36
  69. package/types/cngx-common-stepper.d.ts +414 -114
  70. package/types/cngx-common-tabs.d.ts +597 -72
  71. package/types/cngx-common-timeline.d.ts +1125 -0
  72. package/types/cngx-common.d.ts +1 -1
@@ -1,11 +1,14 @@
1
1
  import * as i0 from '@angular/core';
2
- import { InjectionToken, model, input, inject, Injector, computed, output, signal, Directive, TemplateRef, contentChild, DestroyRef, Renderer2, ElementRef, effect, afterNextRender, untracked, makeEnvironmentProviders, isDevMode, linkedSignal, runInInjectionContext } from '@angular/core';
2
+ import { InjectionToken, inject, computed, makeEnvironmentProviders, model, input, Injector, output, signal, Directive, TemplateRef, contentChild, DestroyRef, Renderer2, ElementRef, effect, afterNextRender, untracked, isDevMode, linkedSignal, runInInjectionContext } from '@angular/core';
3
3
  import { CNGX_COMMIT_CONTROLLER_FACTORY } from '@cngx/common/data';
4
- import { createTransitionTracker, CNGX_STATEFUL, nextUid } from '@cngx/core/utils';
4
+ import { createOverrideMerge, createTransitionTracker, CNGX_STATEFUL, nextUid, coerceSignal, createAnnouncementPhrase } from '@cngx/core/utils';
5
+ import { recordEqual, arrayEqual } from '@cngx/utils';
6
+ import { createLanguageSection, formatMessage, createSectionBundle } from '@cngx/core/i18n';
5
7
  import { isObservable, Observable } from 'rxjs';
8
+ import { PRIMARY_OUTLET, Router, NavigationEnd, ActivatedRoute } from '@angular/router';
6
9
  import { toSignal, takeUntilDestroyed } from '@angular/core/rxjs-interop';
7
- import { Router, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';
8
- import { filter, take } from 'rxjs/operators';
10
+ import { filter } from 'rxjs/operators';
11
+ import { resolveInlineStep } from '@cngx/core';
9
12
 
10
13
  /**
11
14
  * DI fallback the presenter reads when its `[commitAction]` input is
@@ -21,1632 +24,2263 @@ import { filter, take } from 'rxjs/operators';
21
24
  const CNGX_TABS_COMMIT_ACTION = new InjectionToken('CngxTabsCommitAction');
22
25
 
23
26
  /**
24
- * Wraps a {@link CngxCommitController} with the action-shape adapter
25
- * that collapses `Observable<boolean>` / `Promise<boolean>` /
26
- * `boolean` returns into a single `accept: boolean` outcome.
27
+ * The English tabs section: the single source of the tabs' English copy.
28
+ * `CNGX_TABS_I18N` and the `CNGX_TABS_CONFIG` labels default to it.
27
29
  *
28
- * @category common/tabs
30
+ * @category common/tabs/i18n
31
+ * @since 0.1.0
32
+ * @relatedTo CNGX_TABS_I18N, CNGX_TABS_CONFIG
29
33
  */
30
- function createTabsCommitHandler(opts) {
31
- const { controller } = opts;
34
+ const CNGX_TABS_LANGUAGE_EN = {
35
+ tabsRegion: 'Tabs',
36
+ tabsLabel: 'Tabs',
37
+ tabRoleDescription: 'tab list',
38
+ tabPanelRoleDescription: 'tab panel',
39
+ selectedTab: 'Tab {position} of {count}: {label}',
40
+ tabLabelWithDetail: '{label}, {detail}',
41
+ tabHasErrors: { one: '{count} error', other: '{count} errors' },
42
+ moreTabsLabel: '{count} more',
43
+ unlabeledTab: 'Tab {position}',
44
+ previousTab: 'Previous tab: {tab}',
45
+ nextTab: 'Next tab: {tab}',
46
+ closeTab: 'Close "{label}"',
47
+ addTab: 'Add tab',
48
+ closedTab: 'Closed "{label}"',
49
+ closedUnlabeledTab: 'Tab closed',
50
+ commitFailedRetry: 'Could not switch tab - retry?',
51
+ commitInFlight: 'Switching tab…',
52
+ commitRolledBackTo: 'Could not save changes - reverted to "{origin}".',
53
+ };
54
+
55
+ /**
56
+ * @internal The English tabs section with the active pack's tabs section on
57
+ * top. Feeds both `CNGX_TABS_I18N` and the `CNGX_TABS_CONFIG` labels.
58
+ */
59
+ const injectTabsLanguage = createLanguageSection('tabs', CNGX_TABS_LANGUAGE_EN);
60
+ /** @internal Turns a tabs section into the token's keys for a locale. */
61
+ function tabsBundleFrom(section, locale) {
32
62
  return {
33
- isCommitting: controller.isCommitting,
34
- beginTransition(fromIndex, toIndex, action, onResolve) {
35
- controller.begin((handlers) => runTabsAction(action, fromIndex, toIndex, handlers), toIndex, fromIndex, {
36
- onSuccess: () => onResolve(true),
37
- onError: () => onResolve(false),
38
- });
39
- },
40
- cancel() {
41
- controller.cancel();
42
- },
63
+ tabsLabel: section.tabsLabel,
64
+ selectedTab: (label, position, count) => formatMessage(section.selectedTab, { label, position, count }, locale),
65
+ tabLabelWithDetail: (label, detail) => formatMessage(section.tabLabelWithDetail, { label, detail }, locale),
66
+ tabHasErrors: (count) => formatMessage(section.tabHasErrors, { count }, locale),
67
+ moreTabsLabel: (count) => formatMessage(section.moreTabsLabel, { count }, locale),
68
+ unlabeledTab: (position) => formatMessage(section.unlabeledTab, { position }, locale),
69
+ previousTab: (tab) => formatMessage(section.previousTab, { tab }, locale),
70
+ nextTab: (tab) => formatMessage(section.nextTab, { tab }, locale),
71
+ closeTab: (label) => formatMessage(section.closeTab, { label }, locale),
72
+ addTab: section.addTab,
73
+ closedTab: (label) => label ? formatMessage(section.closedTab, { label }, locale) : section.closedUnlabeledTab,
74
+ commitFailedRetry: section.commitFailedRetry,
75
+ commitInFlight: section.commitInFlight,
76
+ commitRolledBackTo: (origin) => formatMessage(section.commitRolledBackTo, { origin }, locale),
43
77
  };
44
78
  }
45
- function runTabsAction(action, fromIndex, toIndex, handlers) {
46
- let cancelled = false;
47
- let unsubscribe = null;
48
- const safeSuccess = (accept) => {
49
- if (cancelled) {
50
- return;
51
- }
52
- if (accept) {
53
- handlers.onSuccess(toIndex);
54
- }
55
- else {
56
- handlers.onError(new Error('Tab transition refused by commitAction'));
57
- }
58
- };
59
- const safeError = (err) => {
60
- if (cancelled) {
61
- return;
62
- }
63
- handlers.onError(err);
64
- };
65
- let result;
66
- try {
67
- result = action(fromIndex, toIndex);
68
- }
69
- catch (err) {
70
- safeError(err);
71
- return {
72
- cancel: () => {
73
- cancelled = true;
74
- },
75
- };
76
- }
77
- if (isObservable(result)) {
78
- // Synchronous Observables (`of(true)`) emit inside `.subscribe` before
79
- // the assignment binds - close over a pre-declared `let` to avoid TDZ.
80
- let sub = null;
81
- sub = result.subscribe({
82
- next: (accept) => {
83
- safeSuccess(accept);
84
- sub?.unsubscribe();
85
- },
86
- error: (err) => safeError(err),
87
- });
88
- unsubscribe = () => sub?.unsubscribe();
89
- }
90
- else if (result != null && typeof result.then === 'function') {
91
- result.then(safeSuccess, safeError);
92
- }
93
- else {
94
- safeSuccess(result);
95
- }
96
- return {
97
- cancel: () => {
98
- cancelled = true;
99
- unsubscribe?.();
100
- },
101
- };
79
+ /** @internal The tabs section of the active pack over English. */
80
+ function injectTabsSection() {
81
+ return injectTabsLanguage();
102
82
  }
83
+ /** @internal Builds and reads the token, formatted for the reading locale. */
84
+ const tabsBundle = createSectionBundle({
85
+ section: injectTabsSection,
86
+ toBundle: tabsBundleFrom,
87
+ });
103
88
  /**
104
- * DI token for the commit-handler factory. \
105
- * Defaults to {@link createTabsCommitHandler}. \
106
- * Sibling to
107
- * - `CNGX_ARRAY_COMMIT_HANDLER_FACTORY` (select) and
108
- * - `CNGX_STEPPER_COMMIT_HANDLER_FACTORY`.
89
+ * DI token for the tabs i18n bundle, as a `Signal` so a runtime language
90
+ * switch re-renders every label it feeds. `providedIn: 'root'`: the tabs
91
+ * section of the active language pack over the English defaults, formatted
92
+ * for the app locale. Provide it through {@link provideTabsI18n}; a
93
+ * `{ provide, useValue }` entry must supply a `Signal<CngxTabsI18n>`.
109
94
  *
110
- * @category common/tabs
111
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/commit-handler.ts
95
+ * @category common/tabs/i18n
96
+ * @wcag AA
97
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/i18n/tabs-i18n.ts
112
98
  * @since 0.1.0
113
99
  */
114
- const CNGX_TABS_COMMIT_HANDLER_FACTORY = new InjectionToken('CngxTabsCommitHandlerFactory', {
100
+ const CNGX_TABS_I18N = new InjectionToken('CngxTabsI18n', {
115
101
  providedIn: 'root',
116
- factory: () => createTabsCommitHandler,
102
+ factory: () => tabsBundle.build(),
117
103
  });
104
+ /**
105
+ * Brands an i18n-mutator with the `_target` discriminator.
106
+ *
107
+ * @internal
108
+ */
109
+ function defineTabsI18nFeature(fn) {
110
+ return Object.assign(fn, { _target: 'i18n' });
111
+ }
112
+ /**
113
+ * Override i18n labels via a partial bundle - unset keys keep the
114
+ * language pack's copy, or the English default. Same shape as `withTabsAriaLabels` /
115
+ * `withTabsFallbackLabels` so `provideCngxTabs` composes both
116
+ * surfaces uniformly. Pass a `Signal` to switch the language at runtime.
117
+ *
118
+ * @category common/tabs/i18n
119
+ */
120
+ function withTabsI18nLabels(overrides) {
121
+ return defineTabsI18nFeature((bundle) => createOverrideMerge(bundle, overrides));
122
+ }
123
+ /**
124
+ * Provider for the tabs i18n bundle. Compose `withTabsI18nLabels(...)`
125
+ * (and future i18n `with*` features); unset keys fall back to the
126
+ * language pack, then English. The features apply on top of the active pack.
127
+ *
128
+ * ```ts
129
+ * bootstrapApplication(AppComponent, {
130
+ * providers: [
131
+ * provideTabsI18n(
132
+ * withTabsI18nLabels({ tabsLabel: 'Reiter', addTab: 'Neuer Reiter' }),
133
+ * ),
134
+ * ],
135
+ * });
136
+ * ```
137
+ *
138
+ * @category common/tabs/i18n
139
+ */
140
+ function provideTabsI18n(...features) {
141
+ return {
142
+ provide: CNGX_TABS_I18N,
143
+ useFactory: () => tabsBundle.build(features),
144
+ };
145
+ }
146
+ /**
147
+ * Inject the resolved tabs i18n bundle. Read it inside a `computed()`,
148
+ * template or handler so a language switch reaches the label.
149
+ *
150
+ * @category common/tabs/i18n
151
+ */
152
+ function injectTabsI18n() {
153
+ return tabsBundle.resolve(inject(CNGX_TABS_I18N));
154
+ }
118
155
 
119
156
  /**
120
- * DI token for the tab presenter's contract. \
121
- * Presenter provides via `useExisting`; `CngxTab` injects to register; the organism injects
122
- * to drive the APG tablist keyboard model (automatic activation via
123
- * `select()`, roving stop derived from `activeId`) through
124
- * `createTabKeyboardNav`.
157
+ * @internal - library defaults of {@link CNGX_TABS_CONFIG}. Exported from
158
+ * this file (not from `public-api.ts`) so the announcement factory falls
159
+ * back to the same `fallbackLabels` strings instead of repeating them.
160
+ */
161
+ const TABS_CONFIG_DEFAULTS = {
162
+ defaultOrientation: 'horizontal',
163
+ defaultLoop: true,
164
+ defaultCommitMode: 'optimistic',
165
+ fragmentSyncMode: 'fragment',
166
+ fragmentSyncParam: 'tab',
167
+ // routeMatch stays unset: the host-flavour default is the right answer
168
+ // for both organisms, and pinning one here would silently flip the
169
+ // other. linkAriaCurrent defaults at the link, not here.
170
+ linkAriaCurrent: 'page',
171
+ ariaLabels: {
172
+ tabsRegion: CNGX_TABS_LANGUAGE_EN.tabsRegion,
173
+ },
174
+ fallbackLabels: {
175
+ // W3C ARIA tablist convention - kept distinct from
176
+ // `i18n.tabsLabel` so AT doesn't read the same string twice
177
+ // back-to-back across `aria-roledescription` and `aria-label`.
178
+ tabRoleDescription: CNGX_TABS_LANGUAGE_EN.tabRoleDescription,
179
+ tabPanelRoleDescription: CNGX_TABS_LANGUAGE_EN.tabPanelRoleDescription,
180
+ },
181
+ overflowStabilizeMs: 100,
182
+ overflowMaxDeferMs: 250,
183
+ templates: {},
184
+ };
185
+ /**
186
+ * DI token for the resolved tabs config. \
187
+ * `providedIn: 'root'` with the library defaults; override via {@link provideTabsConfig}
188
+ * (root) or {@link provideTabsConfigAt} (component scope).
125
189
  *
126
190
  * @category common/tabs
127
191
  * @wcag AA
128
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab-group-host.token.ts
192
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tabs-config.ts
129
193
  * @since 0.1.0
130
194
  */
131
- const CNGX_TAB_GROUP_HOST = new InjectionToken('CngxTabGroupHost');
132
-
195
+ const CNGX_TABS_CONFIG = new InjectionToken('CngxTabsConfig', {
196
+ providedIn: 'root',
197
+ factory: () => resolveFeatures([]),
198
+ });
133
199
  /**
134
- * Tab-group presenter - brain of every CNGX tab flow. \
135
- * Owns the active-index model, the tab registry, orientation, loop policy,
136
- * and the commit-controller lifecycle. \
137
- * Provides {@link CNGX_TAB_GROUP_HOST} for atoms and {@link CNGX_STATEFUL}
138
- * so `<cngx-toast-on />` / `<cngx-banner-on />` compose without
139
- * `[state]` wiring.
200
+ * Internal helper that brands a config-mutator function with the
201
+ * `_target` discriminator. \
202
+ * Every `with*` config feature returns one
203
+ * of these.
140
204
  *
141
- * **Layer:** `@cngx/common/tabs`. \
142
- * Directive-only - organisms compose via `hostDirectives`, consumers attach
143
- * `[cngxTabGroup]` directly.
205
+ * @internal
206
+ */
207
+ function defineTabsConfigFeature(fn) {
208
+ return Object.assign(fn, { _target: 'config' });
209
+ }
210
+ /**
211
+ * Override the default orientation. Per-instance `[orientation]`
212
+ * still wins; this changes the cascade default only.
144
213
  *
145
214
  * @category common/tabs
146
- * @docsKind primary
147
- * @wcag AA
148
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/presenter.directive.ts
149
- * @since 0.1.0
150
- * @relatedTo CngxTab, CngxTabContent, CngxTabLabel, CngxTabsFragmentSync
151
- * <example-url>http://localhost:4200/#/ui/tabs/tab-commit-action/optimistic-pessimistic-commits-with-bridge-directives</example-url>
152
215
  */
153
- class CngxTabGroupPresenter {
154
- activeIndex = model(0, ...(ngDevMode ? [{ debugName: "activeIndex" }] : /* istanbul ignore next */ []));
155
- orientation = input('horizontal', ...(ngDevMode ? [{ debugName: "orientation" }] : /* istanbul ignore next */ []));
156
- loop = input(true, ...(ngDevMode ? [{ debugName: "loop" }] : /* istanbul ignore next */ []));
157
- /**
158
- * Async-commit action gating the transition.
159
- * When non-null, `select(...)` routes through {@link CngxTabsCommitHandler}; the
160
- * action's resolution decides whether the change lands. Supersede
161
- * semantics come from the commit-controller - a rapid second
162
- * `select(...)` cancels the in-flight runner.
163
- *
164
- * @internal Two-field alias - bind the public `[commitAction]`; read
165
- * the resolved {@link commitAction} computed (input ?? DI fallback).
166
- */
167
- commitActionInput = input(null, { ...(ngDevMode ? { debugName: "commitActionInput" } : /* istanbul ignore next */ {}), alias: 'commitAction' });
168
- /**
169
- * Default `'optimistic'` - tab change is navigation, not a save,
170
- * so eager visual feedback matches the user's mental model.
171
- * Switch to `'pessimistic'` when the new tab must wait for the
172
- * action to confirm.
173
- *
174
- * @internal Two-field alias - bind the public `[commitMode]`; read
175
- * the resolved {@link commitMode} computed (DI fallback mode wins
176
- * when a routed action is active).
177
- */
178
- commitModeInput = input('optimistic', { ...(ngDevMode ? { debugName: "commitModeInput" } : /* istanbul ignore next */ {}), alias: 'commitMode' });
179
- injector = inject(Injector);
180
- // Resolved lazily, never in a field initialiser: a sync directive
181
- // (e.g. [cngxTabsRouteSync]) provides CNGX_TABS_COMMIT_ACTION via
182
- // useExisting and itself injects this presenter as its host, so
183
- // eager injection here would close a construction cycle (NG0200).
184
- // First read happens at select()/template time - after both
185
- // directives exist. The source is static per element, so memoising
186
- // the resolution is safe.
187
- injectedActionSource;
188
- resolveInjectedAction() {
189
- if (this.injectedActionSource === undefined) {
190
- this.injectedActionSource = this.injector.get(CNGX_TABS_COMMIT_ACTION, null);
191
- }
192
- return this.injectedActionSource;
193
- }
194
- /**
195
- * Resolved commit-action: the `[commitAction]` input when bound, else
196
- * the {@link CNGX_TABS_COMMIT_ACTION} DI fallback (routed path), else
197
- * `null`. `select()` reads this.
198
- */
199
- commitAction = computed(() => this.commitActionInput() ?? this.resolveInjectedAction()?.action() ?? null, ...(ngDevMode ? [{ debugName: "commitAction" }] : /* istanbul ignore next */ []));
200
- /**
201
- * Resolved commit mode. When the DI fallback supplies an active
202
- * action its `mode` wins - the routed path pins `'pessimistic'` so a
203
- * stray `[commitMode]="'optimistic'"` cannot break the
204
- * route-follows-resolution invariant. Otherwise the `[commitMode]`
205
- * input drives.
206
- */
207
- commitMode = computed(() => {
208
- const source = this.resolveInjectedAction();
209
- return source?.action() ? source.mode() : this.commitModeInput();
210
- }, ...(ngDevMode ? [{ debugName: "commitMode" }] : /* istanbul ignore next */ []));
211
- /**
212
- * Emitted when a tab's close affordance is activated (the close
213
- * button or Delete/Backspace on the focused tab). The presenter has
214
- * already moved the active index onto the surviving neighbour; the
215
- * consumer removes the tab from its own data in the handler.
216
- */
217
- tabClose = output();
218
- /**
219
- * Emitted when the add-tab affordance is activated. The consumer
220
- * appends a tab to its own data; the presenter owns no creation logic.
221
- */
222
- tabAdd = output();
223
- genericFactory = inject(CNGX_COMMIT_CONTROLLER_FACTORY);
224
- commitController = this.genericFactory();
225
- commitHandler = inject(CNGX_TABS_COMMIT_HANDLER_FACTORY)({
226
- controller: this.commitController,
227
- });
228
- /** Producer surface for the `CNGX_STATEFUL` bridge contract. */
229
- state = this.commitController.state;
230
- commitState = this.commitController.state;
231
- /**
232
- * Index the user is currently trying to commit to. Tracked
233
- * separately from `state.data()` (which only updates on success)
234
- * to drive per-tab `aria-busy`.
235
- */
236
- intendedIndex = this.commitController.intendedValue;
237
- /**
238
- * Current/previous pair for `commitState.status()`. Skin
239
- * sub-components feed `<span cngxLiveRegion>` from this tracker
240
- * for declarative SR announcements. Shared across consumers so
241
- * the tracker's `linkedSignal` is allocated once per presenter.
242
- */
243
- commitTransition = createTransitionTracker(() => this.commitController.state.status());
244
- // Persistence-of-error surface - see `CngxTabGroupHost.lastFailedIndex`
245
- // and `originIndexDuringCommit` for the contract.
246
- lastFailedIndexState = signal(undefined, ...(ngDevMode ? [{ debugName: "lastFailedIndexState" }] : /* istanbul ignore next */ []));
247
- originIndexDuringCommitState = signal(undefined, ...(ngDevMode ? [{ debugName: "originIndexDuringCommitState" }] : /* istanbul ignore next */ []));
248
- /** {@inheritDoc CngxTabGroupHost.lastFailedIndex} */
249
- lastFailedIndex = this.lastFailedIndexState.asReadonly();
250
- /** {@inheritDoc CngxTabGroupHost.originIndexDuringCommit} */
251
- originIndexDuringCommit = this.originIndexDuringCommitState.asReadonly();
252
- tabsState = signal([], { ...(ngDevMode ? { debugName: "tabsState" } : /* istanbul ignore next */ {}), equal: tabsEqual });
253
- tabs = this.tabsState.asReadonly();
254
- clampedIndex = computed(() => {
255
- const count = this.tabs().length;
256
- if (count === 0) {
257
- return 0;
258
- }
259
- return Math.max(0, Math.min(this.activeIndex(), count - 1));
260
- }, ...(ngDevMode ? [{ debugName: "clampedIndex" }] : /* istanbul ignore next */ []));
261
- activeId = computed(() => this.tabs()[this.clampedIndex()]?.id ?? null, { ...(ngDevMode ? { debugName: "activeId" } : /* istanbul ignore next */ {}), equal: Object.is });
262
- register(handle) {
263
- const current = this.tabsState();
264
- const idx = current.findIndex((h) => h.id === handle.id);
265
- if (idx >= 0) {
266
- const next = current.slice();
267
- next[idx] = handle;
268
- this.tabsState.set(next);
269
- return;
270
- }
271
- this.tabsState.set([...current, handle]);
272
- }
273
- unregister(id) {
274
- const current = this.tabsState();
275
- const next = current.filter((h) => h.id !== id);
276
- if (next.length !== current.length) {
277
- this.tabsState.set(next);
278
- }
279
- }
280
- /** {@inheritDoc CngxTabGroupHost.clearLastFailed} */
281
- clearLastFailed() {
282
- this.lastFailedIndexState.set(undefined);
283
- }
284
- select(index) {
285
- const tabs = this.tabs();
286
- if (tabs.length === 0) {
287
- return;
288
- }
289
- const target = Math.max(0, Math.min(index, tabs.length - 1));
290
- if (tabs[target].disabled()) {
291
- return;
292
- }
293
- const previous = this.activeIndex();
294
- if (target === previous) {
295
- return;
296
- }
297
- const action = this.commitAction();
298
- if (!action) {
299
- // No-action fast path - `originIndexDuringCommit` stays
300
- // untouched, so a stale origin can never leak into the
301
- // live-region announcement.
302
- this.activeIndex.set(target);
303
- if (this.lastFailedIndexState() === target) {
304
- this.lastFailedIndexState.set(undefined);
305
- }
306
- return;
307
- }
308
- // Open the commit window - origin is captured ONLY here so a
309
- // stale value never lingers into a non-commit navigation.
310
- this.originIndexDuringCommitState.set(previous);
311
- const mode = this.commitMode();
312
- if (mode === 'optimistic') {
313
- this.activeIndex.set(target);
314
- }
315
- this.commitHandler.beginTransition(previous, target, action, (accept) => {
316
- if (accept) {
317
- // Window closes on success - origin label no longer needed;
318
- // clear the rejection flag if the user re-picked the failed
319
- // target successfully.
320
- this.originIndexDuringCommitState.set(undefined);
321
- if (this.lastFailedIndexState() === target) {
322
- this.lastFailedIndexState.set(undefined);
323
- }
324
- if (mode === 'pessimistic') {
325
- this.activeIndex.set(target);
326
- }
327
- }
328
- else {
329
- // Reject - flag the refused target; RETAIN the origin so
330
- // the organism's `liveAnnouncement` computed can resolve
331
- // the origin label for the rich rollback phrase. Optimistic
332
- // rolls back; pessimistic never moved.
333
- this.lastFailedIndexState.set(target);
334
- if (mode === 'optimistic') {
335
- this.activeIndex.set(previous);
336
- }
337
- }
338
- });
339
- }
340
- selectNext() {
341
- const tabs = this.tabs();
342
- if (tabs.length === 0) {
343
- return;
344
- }
345
- let next = this.activeIndex() + 1;
346
- while (next < tabs.length && tabs[next].disabled()) {
347
- next++;
348
- }
349
- if (next < tabs.length) {
350
- this.select(next);
351
- return;
352
- }
353
- if (this.loop()) {
354
- let i = 0;
355
- while (i < tabs.length && tabs[i].disabled()) {
356
- i++;
357
- }
358
- if (i < tabs.length && i !== this.activeIndex()) {
359
- this.select(i);
360
- }
361
- }
362
- }
363
- selectPrevious() {
364
- const tabs = this.tabs();
365
- if (tabs.length === 0) {
366
- return;
367
- }
368
- let prev = this.activeIndex() - 1;
369
- while (prev >= 0 && tabs[prev].disabled()) {
370
- prev--;
371
- }
372
- if (prev >= 0) {
373
- this.select(prev);
374
- return;
375
- }
376
- if (this.loop()) {
377
- let i = tabs.length - 1;
378
- while (i >= 0 && tabs[i].disabled()) {
379
- i--;
380
- }
381
- if (i >= 0 && i !== this.activeIndex()) {
382
- this.select(i);
383
- }
384
- }
385
- }
386
- selectById(id) {
387
- const tabs = this.tabs();
388
- const idx = tabs.findIndex((h) => h.id === id);
389
- if (idx >= 0) {
390
- this.select(idx);
391
- }
392
- }
393
- requestClose(id) {
394
- const tabs = this.tabs();
395
- const index = tabs.findIndex((h) => h.id === id);
396
- if (index < 0) {
397
- return;
398
- }
399
- const active = this.clampedIndex();
400
- // Only closing a tab BEFORE the active one needs a pre-emptive
401
- // index shift: the active tab moves down one slot once the consumer
402
- // removes the closed tab, so decrement to keep the same tab active.
403
- // Closing the active tab (or one after it) needs no write -
404
- // `clampedIndex` re-derives against the shorter array and lands on
405
- // the next tab (or the new last when the closed tab was last).
406
- if (index < active) {
407
- this.activeIndex.set(active - 1);
408
- }
409
- this.tabClose.emit({ id, index });
410
- }
411
- requestAdd() {
412
- this.tabAdd.emit();
413
- }
414
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabGroupPresenter, deps: [], target: i0.ɵɵFactoryTarget.Directive });
415
- 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: [
416
- { provide: CNGX_TAB_GROUP_HOST, useExisting: CngxTabGroupPresenter },
417
- { provide: CNGX_STATEFUL, useExisting: CngxTabGroupPresenter },
418
- ], exportAs: ["cngxTabGroup"], ngImport: i0 });
216
+ function withTabsDefaultOrientation(orientation) {
217
+ return defineTabsConfigFeature((cfg) => ({
218
+ ...cfg,
219
+ defaultOrientation: orientation,
220
+ }));
419
221
  }
420
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabGroupPresenter, decorators: [{
421
- type: Directive,
422
- args: [{
423
- selector: '[cngxTabGroup]',
424
- exportAs: 'cngxTabGroup',
425
- standalone: true,
426
- providers: [
427
- { provide: CNGX_TAB_GROUP_HOST, useExisting: CngxTabGroupPresenter },
428
- { provide: CNGX_STATEFUL, useExisting: CngxTabGroupPresenter },
429
- ],
430
- }]
431
- }], 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"] }] } });
432
222
  /**
433
- * Structural equality for the tab registry. Compares length and
434
- * per-entry `id`, `disabled()`, `label()`, `subLabel()`, and
435
- * `closable()`.
436
- *
437
- * `errorAggregator`, `hasError`, and `errorMessage` are left out on
438
- * purpose. The handle is a stable per-tab reference injected once, and
439
- * the organism reads `tab.hasError()` / `tab.errorMessage()` reactively
440
- * off that handle (not off array identity), so the badge + descriptor
441
- * update on error-state changes without the registry array re-emitting.
442
- * Comparing them here would push the memoisation burden onto consumers
443
- * and break the structural-equal contract.
223
+ * @deprecated Use {@link withTabsDefaultOrientation}. The unprefixed name
224
+ * collides with the stepper family's identical symbol when both libs
225
+ * are auto-imported. The alias stays for one minor release before
226
+ * removal.
444
227
  *
445
- * Reading the signals here doesn't subscribe - the comparator runs
446
- * synchronously inside `signal.set()`, outside any tracking context.
228
+ * @category common/tabs
229
+ */
230
+ const withDefaultOrientation = withTabsDefaultOrientation;
231
+ /**
232
+ * Override whether roving-tabindex navigation loops from last back to
233
+ * first (and vice versa). Per-instance `[loop]` Input still wins.
447
234
  *
448
- * @internal
235
+ * @category common/tabs
449
236
  */
450
- function tabsEqual(a, b) {
451
- if (a === b) {
452
- return true;
453
- }
454
- if (a.length !== b.length) {
455
- return false;
456
- }
457
- for (let i = 0; i < a.length; i++) {
458
- if (a[i].id !== b[i].id ||
459
- a[i].disabled() !== b[i].disabled() ||
460
- a[i].label() !== b[i].label() ||
461
- a[i].subLabel() !== b[i].subLabel() ||
462
- a[i].closable() !== b[i].closable()) {
463
- return false;
464
- }
465
- }
466
- return true;
237
+ function withTabsRovingLoop(loop) {
238
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, defaultLoop: loop }));
467
239
  }
468
-
469
240
  /**
470
- * DI token the organism provides via `useExisting`.\
471
- * The overflow molecule and consumer-authored skin sub-components inject this
472
- * instead of the concrete component class.
241
+ * Override the default commit mode for async tab transitions.
242
+ * `'optimistic'` activates the tab on action dispatch and rolls back
243
+ * on error; `'pessimistic'` waits for success. Per-instance
244
+ * `[commitMode]` Input still wins.
473
245
  *
474
246
  * @category common/tabs
475
- * @wcag AA
476
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab-panel-host.token.ts
477
- * @since 0.1.0
478
247
  */
479
- const CNGX_TAB_PANEL_HOST = new InjectionToken('CngxTabPanelHost');
480
-
248
+ function withTabsCommitMode(mode) {
249
+ return defineTabsConfigFeature((cfg) => ({
250
+ ...cfg,
251
+ defaultCommitMode: mode,
252
+ }));
253
+ }
481
254
  /**
482
- * Structural slot directive marking the per-tab panel-body template. \
483
- * Discovered by `<cngx-tab-group>` via `contentChild` on each
484
- * `CngxTab` and projected into the matching `role="tabpanel"`.
255
+ * Configure URL fragment / query-param deep-linking for the active tab
256
+ * (the {@link CngxTabsFragmentSync} directive). \
257
+ * `mode` chooses the URL surface (URL fragment or query parameter); `param` names the key
258
+ * (default `'tab'`).
485
259
  *
486
- * ```html
487
- * <div cngxTab [label]="'Settings'">
488
- * <ng-template cngxTabContent>
489
- * <p>Settings panel body…</p>
490
- * </ng-template>
491
- * </div>
492
- * ```
260
+ * Not to be confused with `[cngxTabsRouteSync]`, the router-outlet
261
+ * integration - this feature configures fragment deep-linking only.
493
262
  *
494
263
  * @category common/tabs
495
- * @wcag AA
496
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab-content.directive.ts
497
- * @since 0.1.0
498
- * @relatedTo CngxTab, CngxTabLabel
499
264
  */
500
- class CngxTabContent {
501
- templateRef = inject((TemplateRef));
502
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabContent, deps: [], target: i0.ɵɵFactoryTarget.Directive });
503
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxTabContent, isStandalone: true, selector: "ng-template[cngxTabContent]", exportAs: ["cngxTabContent"], ngImport: i0 });
265
+ function withTabsFragmentSync(mode, param = 'tab') {
266
+ return defineTabsConfigFeature((cfg) => ({
267
+ ...cfg,
268
+ fragmentSyncMode: mode,
269
+ fragmentSyncParam: param,
270
+ }));
504
271
  }
505
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabContent, decorators: [{
506
- type: Directive,
507
- args: [{
508
- selector: 'ng-template[cngxTabContent]',
509
- exportAs: 'cngxTabContent',
510
- standalone: true,
511
- }]
512
- }] });
513
-
514
272
  /**
515
- * Structural slot directive marking the per-tab label template. \
516
- * Discovered by `<cngx-tab-group>` via `contentChild` on each
517
- * `CngxTab` and projected into the tab strip.
273
+ * Force one URL-matching mode app-wide for `[cngxTabsRouteSync]`. \
274
+ * `'suffix'` treats every tab as a leaf route, `'prefix'` as a section
275
+ * that stays active for URLs beneath it.
518
276
  *
519
- * ```html
520
- * <div cngxTab id="settings">
521
- * <ng-template cngxTabLabel>Settings</ng-template>
522
- * ... tab content ...
523
- * </div>
524
- * ```
277
+ * Reach for this only when the host-flavour default is wrong for your
278
+ * app. Unset, a `<cngx-tab-nav>` matches by prefix and a
279
+ * `<cngx-tab-group>` by suffix, which is what each markup implies; this
280
+ * feature overrides *both*. Per-instance `[match]` still wins.
281
+ *
282
+ * Changes which policy runs, not the policies themselves - swap those via
283
+ * {@link CNGX_TAB_URL_MATCH_STRATEGY}.
525
284
  *
526
285
  * @category common/tabs
527
- * @wcag AA
528
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab-label.directive.ts
529
- * @since 0.1.0
530
- * @relatedTo CngxTab, CngxTabContent
531
286
  */
532
- class CngxTabLabel {
533
- templateRef = inject((TemplateRef));
534
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabLabel, deps: [], target: i0.ɵɵFactoryTarget.Directive });
535
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxTabLabel, isStandalone: true, selector: "ng-template[cngxTabLabel]", exportAs: ["cngxTabLabel"], ngImport: i0 });
287
+ function withTabsRouteMatch(mode) {
288
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, routeMatch: mode }));
536
289
  }
537
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabLabel, decorators: [{
538
- type: Directive,
539
- args: [{
540
- selector: 'ng-template[cngxTabLabel]',
541
- exportAs: 'cngxTabLabel',
542
- standalone: true,
543
- }]
544
- }] });
545
-
546
290
  /**
547
- * Structural slot directive marking a tab's secondary label template. \
548
- * Discovered by `<cngx-tab-group>` via `contentChild` on each
549
- * `CngxTab` and rendered as a stacked second line under the primary
550
- * label. \
291
+ * Set the `aria-current` token `[cngxTabLink]` publishes while active. \
292
+ * Default `'page'`.
551
293
  *
552
- * Per-tab content, mirroring `CngxTabLabel` - the convenience
553
- * `[subLabel]` string input on `CngxTab` covers the plain-text case.
554
- *
555
- * ```html
556
- * <div cngxTab id="bookmarks">
557
- * <ng-template cngxTabLabel>Bookmarks</ng-template>
558
- * <ng-template cngxTabSubLabel>45 saved</ng-template>
559
- * <ng-template cngxTabContent>...</ng-template>
560
- * </div>
561
- * ```
294
+ * Use `'true'` for a section nav whose links stay active across a whole
295
+ * subtree: the active link is then the current *section*, and `page`
296
+ * would tell AT it is the page being viewed. Scope it to one nav with
297
+ * `provideTabsConfigAt` in that component's `viewProviders` rather than
298
+ * setting it app-wide, unless every nav in the app is section-shaped.
299
+ * Per-link `[ariaCurrent]` still wins.
562
300
  *
563
- * @category common/tabs/slots
564
- * @wcag AA
565
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/slots/tab-sub-label.directive.ts
566
- * @since 0.1.0
567
- * @relatedTo CngxTab, CngxTabLabel, CngxTabContent
568
- * <example-url>http://localhost:4200/#/ui/tabs/tab-sub-label/label-with-count</example-url>
569
- */
570
- class CngxTabSubLabel {
571
- /**
572
- * The captured `<ng-template>`, projected by `<cngx-tab-group>` as the
573
- * tab's secondary label line under the primary label.
574
- */
575
- templateRef = inject((TemplateRef));
576
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabSubLabel, deps: [], target: i0.ɵɵFactoryTarget.Directive });
577
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxTabSubLabel, isStandalone: true, selector: "ng-template[cngxTabSubLabel]", exportAs: ["cngxTabSubLabel"], ngImport: i0 });
578
- }
579
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabSubLabel, decorators: [{
580
- type: Directive,
581
- args: [{
582
- selector: 'ng-template[cngxTabSubLabel]',
583
- exportAs: 'cngxTabSubLabel',
584
- standalone: true,
585
- }]
586
- }] });
587
-
588
- /**
589
- * Single-tab atom. \
590
- * Registers with the enclosing presenter via
591
- * {@link CNGX_TAB_GROUP_HOST} on construction; deregisters via
592
- * {@link DestroyRef} on teardown. \
593
- * The presenter holds the atom's
594
- * input signals by reference, so input changes propagate without
595
- * re-registration. \
596
- * `labelTemplate` / `contentTemplate` are projected
597
- * by the organism - the atom carries no rendering logic.
598
- *
599
- * ```html
600
- * <div cngxTab [label]="'Settings'">
601
- * ... content templates here ...
602
- * </div>
603
- * ```
604
301
  * @category common/tabs
605
- * @docsKind primary
606
- * @wcag AA
607
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab.directive.ts
608
- * @since 0.1.0
609
- * @relatedTo CngxTabGroupPresenter, CngxTabLabel, CngxTabContent, CngxTabErrorBadge
610
302
  */
611
- class CngxTab {
612
- id = input(nextUid('cngx-tab-'), ...(ngDevMode ? [{ debugName: "id" }] : /* istanbul ignore next */ []));
613
- disabled = input(false, ...(ngDevMode ? [{ debugName: "disabled" }] : /* istanbul ignore next */ []));
614
- label = input(undefined, ...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
615
- /**
616
- * Optional secondary text line under the primary label (a count, a
617
- * status word, a short detail). Convenience for the common text
618
- * case, parallel to `[label]`; the `*cngxTabSubLabel` slot covers
619
- * richer content. Folds into the tab's accessible name.
620
- */
621
- subLabel = input(undefined, ...(ngDevMode ? [{ debugName: "subLabel" }] : /* istanbul ignore next */ []));
622
- errorAggregator = input(undefined, ...(ngDevMode ? [{ debugName: "errorAggregator" }] : /* istanbul ignore next */ []));
623
- /**
624
- * Direct error flag for the common "this tab is invalid" case - no
625
- * `errorAggregator` boilerplate required. `true` or a non-empty string
626
- * drives the error state; a string doubles as the inline message
627
- * (surfaced via the `*cngxTabErrorBadge` slot context). `false` / `''`
628
- * clear it. The aggregator stays the rich multi-source forms path; the
629
- * two channels compose (either errors). Mirrors `CngxStep.error`.
630
- */
631
- error = input(false, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
632
- /**
633
- * Resolved direct-error message: the `[error]` string when non-empty,
634
- * else `undefined`. Carried onto the registration handle so the error
635
- * badge slot can render it. `computed` over the input - never written.
636
- */
637
- errorMessage = computed(() => {
638
- const value = this.error();
639
- return typeof value === 'string' && value !== '' ? value : undefined;
640
- }, ...(ngDevMode ? [{ debugName: "errorMessage" }] : /* istanbul ignore next */ []));
641
- /**
642
- * Per-tab error fold driving the badge + SR descriptor. `true` when
643
- * the direct `[error]` flag is set OR the optional aggregator wants to
644
- * reveal (`shouldShow()` = `hasError` AND scope reveal-state). The
645
- * aggregator arm reads `shouldShow`, not `hasError`, so deferred-reveal
646
- * validation stays silent until revealed - the direct flag has no
647
- * reveal concept (the consumer sets it when it wants it shown). A
648
- * boolean, not a status enum: tabs carry no success/completed/disabled
649
- * model (Pillar 3).
650
- */
651
- hasError = computed(() => {
652
- const directError = this.error();
653
- return ((directError !== false && directError !== '') ||
654
- (this.errorAggregator()?.shouldShow?.() ?? false));
655
- }, { ...(ngDevMode ? { debugName: "hasError" } : /* istanbul ignore next */ {}), equal: Object.is });
656
- /**
657
- * Per-tab close-affordance override. `undefined` (default) inherits
658
- * the group-level `[closable]` resolution; set `false` to pin this
659
- * tab open inside a dismissable group, or `true` to make a single tab
660
- * closable while the group default is off.
661
- */
662
- closable = input(undefined, ...(ngDevMode ? [{ debugName: "closable" }] : /* istanbul ignore next */ []));
663
- labelTemplate = contentChild(CngxTabLabel, ...(ngDevMode ? [{ debugName: "labelTemplate" }] : /* istanbul ignore next */ []));
664
- subLabelTemplate = contentChild(CngxTabSubLabel, ...(ngDevMode ? [{ debugName: "subLabelTemplate" }] : /* istanbul ignore next */ []));
665
- contentTemplate = contentChild(CngxTabContent, ...(ngDevMode ? [{ debugName: "contentTemplate" }] : /* istanbul ignore next */ []));
666
- host = inject(CNGX_TAB_GROUP_HOST, { optional: true });
667
- destroyRef = inject(DestroyRef);
668
- /** `true` when the presenter's `activeId` equals this tab's id. */
669
- selected = computed(() => this.host?.activeId() === this.id(), { ...(ngDevMode ? { debugName: "selected" } : /* istanbul ignore next */ {}), equal: Object.is });
670
- constructor() {
671
- if (!this.host) {
672
- throw new Error('CngxTab: no enclosing CngxTabGroupPresenter found. Wrap the tab inside an element carrying [cngxTabGroup] (or place it inside <cngx-tab-group>).');
673
- }
674
- }
675
- ngOnInit() {
676
- // Register in ngOnInit, NOT the constructor: a dynamically-bound
677
- // `[id]` (or `[label]`) signal input is not applied until the first
678
- // change detection, so a constructor read would capture the default
679
- // auto-id. The handle id is the stable key consumers map `(tabClose)`
680
- // back to their data with, so it must reflect the bound `[id]`.
681
- const host = this.host;
682
- const tabId = this.id();
683
- host.register({
684
- id: tabId,
685
- label: this.label,
686
- subLabel: this.subLabel,
687
- disabled: this.disabled,
688
- errorAggregator: this.errorAggregator,
689
- hasError: this.hasError,
690
- errorMessage: this.errorMessage,
691
- closable: this.closable,
692
- });
693
- this.destroyRef.onDestroy(() => host.unregister(tabId));
694
- }
695
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTab, deps: [], target: i0.ɵɵFactoryTarget.Directive });
696
- 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 });
303
+ function withTabsLinkAriaCurrent(token) {
304
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, linkAriaCurrent: token }));
697
305
  }
698
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTab, decorators: [{
699
- type: Directive,
700
- args: [{
701
- selector: '[cngxTab]',
702
- exportAs: 'cngxTab',
703
- standalone: true,
704
- }]
705
- }], 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 }] }] } });
706
-
707
306
  /**
708
- * Turns a consumer `<a routerLink>` into a registered {@link CngxTabHandle}
709
- * inside a {@link CngxTabNav}. \
710
- * Native parallel of {@link CngxMatTabLink}: in a
711
- * navigation bar the link IS the tab, so this per-anchor directive is the
712
- * registration seam - symmetric with how `CngxTab` registers each `[cngxTab]`.
713
- *
714
- * Carries no rendering and no click handler. Navigation is the native
715
- * `routerLink` (middle-click, open-in-new-tab and the hover URL all work),
716
- * gating is the link's own `CanDeactivate`, and the active marker comes from
717
- * the route: `[cngxTabsRouteSync]` on the nav reflects `NavigationEnd` onto the
718
- * presenter's `activeId`, which this link matches against its own `id`. \
719
- * There is no `select()` call - invoking it would re-enter the commit path the
720
- * routed-nav model deliberately keeps dormant.
721
- *
722
- * **Error communication is reactive:** `aria-invalid` plus the
723
- * `--error` skin glyph signal the state, and an injected screen-reader
724
- * descriptor span (referenced by a permanent `aria-describedby`) carries the
725
- * direct `[error]` message string so assistive tech reads *why* the link is
726
- * invalid.
727
- *
728
- * ```html
729
- * <cngx-tab-nav cngxTabsRouteSync>
730
- * <a cngxTabLink id="overview" routerLink="overview">Overview</a>
731
- * <a cngxTabLink id="profile" routerLink="profile" [error]="profileInvalid">Profile</a>
732
- * </cngx-tab-nav>
733
- * ```
307
+ * @deprecated Use {@link withTabsFragmentSync}. "Router sync" collided
308
+ * with the new `[cngxTabsRouteSync]` router-outlet directive; this
309
+ * feature only ever configured fragment / query-param deep-linking. The
310
+ * alias stays for one minor release before removal.
734
311
  *
735
312
  * @category common/tabs
736
- * @docsKind primary
737
- * @wcag AA
738
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab-link.directive.ts
739
- * @since 0.1.0
740
- * @relatedTo CngxTabNav, CngxTabsRouteSync, CngxTab, CngxMatTabLink
741
313
  */
742
- class CngxTabLink {
743
- host = inject(CNGX_TAB_GROUP_HOST, { optional: true });
744
- destroyRef = inject(DestroyRef);
745
- renderer = inject(Renderer2);
746
- hostEl = inject(ElementRef).nativeElement;
747
- /**
748
- * Handle id. Set it to the link's route segment so the nav's
749
- * `[cngxTabsRouteSync]` reflects the active route onto this link via the
750
- * default `(h) => [h.id]` mapping. Defaults to a fresh uid when route-sync
751
- * is not used.
752
- */
753
- id = input(nextUid('cngx-tab-link-'), ...(ngDevMode ? [{ debugName: "id" }] : /* istanbul ignore next */ []));
754
- /** Accessible label fed to the nav's live-region announcer. */
755
- label = input(undefined, ...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
756
- /**
757
- * Direct error flag for the link - `true` or a non-empty string marks it
758
- * invalid (the string doubles as the message). Mirrors `CngxTab.error`.
759
- */
760
- error = input(false, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
761
- /** Optional rich error aggregator for the link. */
762
- errorAggregator = input(undefined, ...(ngDevMode ? [{ debugName: "errorAggregator" }] : /* istanbul ignore next */ []));
763
- /**
764
- * Resolved direct-error message: the `[error]` string when non-empty, else
765
- * `undefined`. Carried onto the registration handle by reference.
766
- * `computed` over the input - never written.
767
- */
768
- errorMessage = computed(() => {
769
- const value = this.error();
770
- return typeof value === 'string' && value !== '' ? value : undefined;
771
- }, ...(ngDevMode ? [{ debugName: "errorMessage" }] : /* istanbul ignore next */ []));
772
- /**
773
- * Per-link error fold driving `aria-invalid` and the `--error` class.
774
- * `true` when the direct `[error]` flag is set OR the optional aggregator
775
- * wants to reveal (`shouldShow()`, so deferred-reveal validation stays
776
- * silent until revealed). Mirrors `CngxTab.hasError`.
777
- */
778
- hasError = computed(() => {
779
- const direct = this.error();
780
- return ((direct !== false && direct !== '') || (this.errorAggregator()?.shouldShow?.() ?? false));
781
- }, { ...(ngDevMode ? { debugName: "hasError" } : /* istanbul ignore next */ {}), equal: Object.is });
782
- /** `true` when the presenter's `activeId` equals this link's id. */
783
- selected = computed(() => this.host?.activeId() === this.id(), { ...(ngDevMode ? { debugName: "selected" } : /* istanbul ignore next */ {}), equal: Object.is });
784
- /**
785
- * Id of the injected SR error-message descriptor. Always referenced by the
786
- * `aria-describedby` host binding (Pillar 2 - the id is permanent; the
787
- * span's content and `aria-hidden` toggle, never the id itself).
788
- */
789
- descriptorId = computed(() => `${this.id()}-desc`, ...(ngDevMode ? [{ debugName: "descriptorId" }] : /* istanbul ignore next */ []));
790
- /** The injected descriptor `<span>`, created in {@link ngOnInit}. */
791
- descriptorEl = null;
792
- constructor() {
793
- if (!this.host) {
794
- throw new Error('CngxTabLink: no enclosing CngxTabGroupPresenter found. Wrap the link inside <cngx-tab-nav> (or an element carrying [cngxTabGroup]).');
795
- }
796
- // Mirror the direct-error message into the describedby span. DOM side
797
- // effect only - no signal writes. Guards until the span exists (created
798
- // in ngOnInit); errorMessage / descriptorId changes re-run it after.
799
- effect(() => {
800
- const el = this.descriptorEl;
801
- if (el) {
802
- this.syncDescriptor(el);
803
- }
804
- });
805
- }
806
- ngOnInit() {
807
- // Register in ngOnInit, NOT the constructor: a dynamically-bound `[id]`
808
- // signal input is not applied until the first change detection, so a
809
- // constructor read would capture the default auto-id. The handle id is the
810
- // stable key the nav's route-sync matches the URL segment against.
811
- const host = this.host;
812
- const handle = {
813
- id: this.id(),
814
- label: this.label,
815
- subLabel: signal(undefined),
816
- disabled: signal(false),
817
- errorAggregator: this.errorAggregator,
818
- hasError: this.hasError,
819
- errorMessage: this.errorMessage,
820
- closable: signal(undefined),
821
- };
822
- host.register(handle);
823
- // Inject the SR error-message descriptor as a SIBLING of the anchor: a
824
- // child span would fold into the link's accessible name, so it lives
825
- // beside it and is reached only via the aria-describedby id.
826
- const descriptor = this.renderer.createElement('span');
827
- this.renderer.addClass(descriptor, 'cngx-sr-only');
828
- const parent = this.renderer.parentNode(this.hostEl);
829
- if (parent) {
830
- this.renderer.insertBefore(parent, descriptor, this.renderer.nextSibling(this.hostEl));
831
- }
832
- this.descriptorEl = descriptor;
833
- this.syncDescriptor(descriptor);
834
- this.destroyRef.onDestroy(() => {
835
- host.unregister(handle.id);
836
- if (parent) {
837
- this.renderer.removeChild(parent, descriptor);
838
- }
839
- });
840
- }
841
- /**
842
- * Write the current direct-error message into the descriptor span and
843
- * toggle its `aria-hidden` so a clear link exposes no description. Keeps
844
- * the span id in sync with {@link descriptorId} (read here so the effect
845
- * tracks an id change too).
846
- */
847
- syncDescriptor(el) {
848
- this.renderer.setAttribute(el, 'id', this.descriptorId());
849
- const message = this.errorMessage() ?? '';
850
- this.renderer.setProperty(el, 'textContent', message);
851
- if (message) {
852
- this.renderer.removeAttribute(el, 'aria-hidden');
853
- }
854
- else {
855
- this.renderer.setAttribute(el, 'aria-hidden', 'true');
856
- }
857
- }
858
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabLink, deps: [], target: i0.ɵɵFactoryTarget.Directive });
859
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxTabLink, isStandalone: true, selector: "[cngxTabLink]", inputs: { id: { classPropertyName: "id", publicName: "id", isSignal: true, isRequired: false, transformFunction: null }, label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null }, error: { classPropertyName: "error", publicName: "error", isSignal: true, isRequired: false, transformFunction: null }, errorAggregator: { classPropertyName: "errorAggregator", publicName: "errorAggregator", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "attr.aria-current": "selected() ? 'page' : null", "attr.aria-invalid": "hasError() ? 'true' : null", "attr.aria-describedby": "descriptorId()", "class.cngx-tab-nav__link--active": "selected()", "class.cngx-tab-nav__link--error": "hasError()" }, classAttribute: "cngx-tab-nav__link" }, exportAs: ["cngxTabLink"], ngImport: i0 });
314
+ const withTabsRouterSync = withTabsFragmentSync;
315
+ /**
316
+ * Select the app-wide default visual skin for `<cngx-tab-group>`. \
317
+ * Default `'line'`. Per-instance `[skin]` Input still wins; this moves
318
+ * the cascade default. Structure, slots, ARIA, and keyboard behaviour
319
+ * are identical across skins - only the `[data-skin]` host attribute
320
+ * changes the CSS layer. The Material twin (`[cngxMatTabs]`) ignores it.
321
+ *
322
+ * @category common/tabs
323
+ */
324
+ function withTabsSkin(skin) {
325
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, skin }));
860
326
  }
861
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabLink, decorators: [{
862
- type: Directive,
863
- args: [{
864
- selector: '[cngxTabLink]',
865
- exportAs: 'cngxTabLink',
866
- standalone: true,
867
- host: {
868
- class: 'cngx-tab-nav__link',
869
- '[attr.aria-current]': "selected() ? 'page' : null",
870
- '[attr.aria-invalid]': "hasError() ? 'true' : null",
871
- '[attr.aria-describedby]': 'descriptorId()',
872
- '[class.cngx-tab-nav__link--active]': 'selected()',
873
- '[class.cngx-tab-nav__link--error]': 'hasError()',
874
- },
875
- }]
876
- }], ctorParameters: () => [], propDecorators: { id: [{ type: i0.Input, args: [{ isSignal: true, alias: "id", required: false }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }], error: [{ type: i0.Input, args: [{ isSignal: true, alias: "error", required: false }] }], errorAggregator: [{ type: i0.Input, args: [{ isSignal: true, alias: "errorAggregator", required: false }] }] } });
877
-
878
327
  /**
879
- * Single dev-warning both tab sync directives emit when `@angular/router`
880
- * is not provided. Shared so the message stays identical across
881
- * {@link CngxTabsFragmentSync} (deep-linking) and {@link CngxTabsRouteSync}
882
- * (router-outlet); only the `enables` clause differs. The URL readers
883
- * themselves stay separate - they target different surfaces (fragment /
884
- * query-param vs route path) and must not converge.
328
+ * Set the app-wide default icon layout for `<cngx-tab-group>`. \
329
+ * Default`'start'`. Per-instance `[iconLayout]` Input still wins. Orthogonal to
330
+ * skin and orientation - only the `[data-icon-layout]` host attribute
331
+ * changes.
885
332
  *
886
- * @internal
333
+ * @category common/tabs
887
334
  */
888
- function warnTabsRouterAbsent(directive, enables) {
889
- console.warn(`${directive}: no Router available - directive is a no-op. ` +
890
- `Provide @angular/router via provideRouter(...) to enable ${enables}.`);
335
+ function withTabsIconLayout(layout) {
336
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, iconLayout: layout }));
891
337
  }
892
-
893
338
  /**
894
- * URL deep-linking for tab groups. \
895
- * Bidirectional sync between `activeId` and a URL fragment or query-param. Opt-in via
896
- * `[cngxTabsFragmentSync]` on the presenter element.
339
+ * Set the app-wide default panel render strategy for `<cngx-tab-group>`. \
340
+ * Default `'eager'` (every panel's content rendered up front, toggled
341
+ * via `[hidden]`). `'lazy'` keep-alives content after first activation;
342
+ * `'lazy-destroy'` renders only the active panel's content. Per-instance
343
+ * `[panelMode]` Input still wins. The panel `<div>` always stays in the
344
+ * DOM regardless of mode (the `aria-controls` target).
897
345
  *
898
- * - `mode = 'fragment'` (default) → `#tab=settings`
899
- * - `mode = 'queryParam'` with `paramName = 'tab'` → `?tab=settings`
346
+ * Under `'lazy'`, a deep link mounts only the panel it names: both sync
347
+ * directives seed the active tab before the first panel render.
900
348
  *
901
- * `Router` is optional - without it the directive logs a dev warning
902
- * via `afterNextRender` and becomes a no-op. \
903
- * Every `router.navigate` and `host.selectById` inside the effects sits in `untracked()`.
349
+ * @category common/tabs
350
+ */
351
+ function withTabsPanelMode(mode) {
352
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, panelMode: mode }));
353
+ }
354
+ /**
355
+ * Set the app-wide default for stretching tabs to the full strip width
356
+ * (horizontal only). \
357
+ * Default `false`. Per-instance `[fitted]` Input still
358
+ * wins. No effect under `orientation="vertical"`.
904
359
  *
905
- * ```html
906
- * <!-- Default fragment mode: the active tab reflects to #tab=<id>, and a
907
- * deep link like /account#tab=settings selects that tab on load. -->
908
- * <cngx-tab-group cngxTabsFragmentSync>
909
- * <div cngxTab id="overview" label="Overview"></div>
910
- * <div cngxTab id="settings" label="Settings"></div>
911
- * </cngx-tab-group>
360
+ * @category common/tabs
361
+ */
362
+ function withTabsFitted(fitted) {
363
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, fitted }));
364
+ }
365
+ /**
366
+ * Set the app-wide default tab-cluster alignment (horizontal only). \
367
+ * Default `'start'`. Per-instance `[tabAlign]` Input still wins. Ignored
368
+ * under `orientation="vertical"` and when the group is `fitted`.
912
369
  *
913
- * <!-- Query-param mode with a custom name -> ?section=settings -->
914
- * <cngx-tab-group cngxTabsFragmentSync mode="queryParam" paramName="section">
915
- * <!-- ...tabs... -->
916
- * </cngx-tab-group>
370
+ * @category common/tabs
371
+ */
372
+ function withTabsAlign(align) {
373
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, tabAlign: align }));
374
+ }
375
+ /**
376
+ * Set the app-wide default for whether tabs render a close affordance. \
377
+ * Default `false`. Per-instance `[closable]` Input wins; a per-`CngxTab`
378
+ * `[closable]` override wins over both.
379
+ *
380
+ * @category common/tabs
381
+ */
382
+ function withTabsClosable(closable) {
383
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, closable }));
384
+ }
385
+ /**
386
+ * Set the app-wide default for whether the group renders an add-tab
387
+ * button. \
388
+ * Default `false`. Per-instance `[addable]` Input wins.
389
+ *
390
+ * @category common/tabs
391
+ */
392
+ function withTabsAddable(addable) {
393
+ return defineTabsConfigFeature((cfg) => ({ ...cfg, addable }));
394
+ }
395
+ /** @internal - shared empty base, so label merges over an unset key memoize. */
396
+ const NO_LABELS = {};
397
+ /**
398
+ * Merge ARIA labels into the cascade. Keys not provided keep their
399
+ * library defaults; per-instance overrides on the tab group still win.
400
+ * Pass a `Signal` to switch the language at runtime.
401
+ *
402
+ * @category common/tabs
403
+ */
404
+ function withTabsAriaLabels(labels) {
405
+ return defineTabsConfigFeature((cfg) => ({
406
+ ...cfg,
407
+ ariaLabels: createOverrideMerge(cfg.ariaLabels ?? NO_LABELS, labels),
408
+ }));
409
+ }
410
+ /**
411
+ * Merge the tablist / tab-panel `aria-roledescription` fallbacks into the
412
+ * cascade. Keys not provided keep their library defaults. Pass a `Signal`
413
+ * to switch the language at runtime.
414
+ *
415
+ * @category common/tabs
416
+ */
417
+ function withTabsFallbackLabels(labels) {
418
+ return defineTabsConfigFeature((cfg) => ({
419
+ ...cfg,
420
+ fallbackLabels: createOverrideMerge(cfg.fallbackLabels ?? NO_LABELS, labels),
421
+ }));
422
+ }
423
+ /**
424
+ * Override the IO-debounce window (ms). See
425
+ * {@link CngxTabsConfig.overflowStabilizeMs}.
426
+ *
427
+ * @category common/tabs
428
+ */
429
+ function withTabOverflowStabilizeMs(ms) {
430
+ return defineTabsConfigFeature((cfg) => ({
431
+ ...cfg,
432
+ overflowStabilizeMs: ms,
433
+ }));
434
+ }
435
+ /**
436
+ * Override the worst-case staleness ceiling on the visibility-map
437
+ * commit. See {@link CngxTabsConfig.overflowMaxDeferMs}.
438
+ *
439
+ * @category common/tabs
440
+ */
441
+ function withTabOverflowMaxDeferMs(ms) {
442
+ return defineTabsConfigFeature((cfg) => ({
443
+ ...cfg,
444
+ overflowMaxDeferMs: ms,
445
+ }));
446
+ }
447
+ /**
448
+ * App-wide override for the More-button label. Middle tier; \
449
+ * per-instance `*cngxTabOverflowTrigger` still wins.
450
+ *
451
+ * ```ts
452
+ * readonly moreTrigger = viewChild.required<TemplateRef<CngxTabOverflowTriggerContext>>(
453
+ * 'moreTrigger',
454
+ * { read: TemplateRef },
455
+ * );
456
+ *
457
+ * providers: [provideTabsConfig(withTabOverflowTriggerTemplate(this.moreTrigger()))]
917
458
  * ```
918
459
  *
919
460
  * @category common/tabs
920
- * @docsKind primary
921
- * @wcag AA
922
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/router-sync.directive.ts
923
- * @since 0.1.0
924
- * @relatedTo CngxTabGroupPresenter, CngxTab
925
461
  */
926
- class CngxTabsFragmentSync {
927
- mode = input('fragment', ...(ngDevMode ? [{ debugName: "mode" }] : /* istanbul ignore next */ []));
928
- paramName = input('tab', ...(ngDevMode ? [{ debugName: "paramName" }] : /* istanbul ignore next */ []));
929
- host = inject(CNGX_TAB_GROUP_HOST, { host: true });
930
- router = inject(Router, { optional: true });
931
- constructor() {
932
- if (!this.router) {
933
- afterNextRender(() => warnTabsRouterAbsent('CngxTabsFragmentSync', 'deep-linking'));
934
- return;
935
- }
936
- const router = this.router;
937
- const destroyRef = inject(DestroyRef);
938
- afterNextRender(() => {
939
- const initial = this.readUrlValue(router);
940
- if (initial) {
941
- untracked(() => this.host.selectById(initial));
942
- }
943
- });
944
- effect(() => {
945
- const id = this.host.activeId();
946
- if (!id) {
947
- return;
948
- }
949
- untracked(() => {
950
- const navigation = this.mode() === 'fragment'
951
- ? router.navigate([], {
952
- fragment: `${this.paramName()}=${id}`,
953
- queryParamsHandling: 'merge',
954
- replaceUrl: true,
955
- })
956
- : router.navigate([], {
957
- queryParams: { [this.paramName()]: id },
958
- queryParamsHandling: 'merge',
959
- replaceUrl: true,
960
- });
961
- // Router rejection (e.g. cancelled navigation) has no recovery path.
962
- navigation.catch?.(() => undefined);
963
- });
964
- });
965
- const navEnd = toSignal(router.events.pipe(filter((e) => e instanceof NavigationEnd), takeUntilDestroyed(destroyRef)), { initialValue: null });
966
- effect(() => {
967
- const e = navEnd();
968
- if (!e) {
969
- return;
970
- }
971
- untracked(() => {
972
- const next = this.readUrlValue(router);
973
- if (next && next !== this.host.activeId()) {
974
- this.host.selectById(next);
975
- }
976
- });
977
- });
978
- }
979
- readUrlValue(router) {
980
- if (this.mode() === 'fragment') {
981
- const fragment = router.routerState.snapshot.root.fragment ?? '';
982
- return this.parseFragment(fragment);
983
- }
984
- return router.routerState.snapshot.root.queryParamMap.get(this.paramName()) ?? null;
985
- }
986
- parseFragment(fragment) {
987
- const param = this.paramName();
988
- const segments = fragment.split('&');
989
- for (const seg of segments) {
990
- const [key, val] = seg.split('=');
991
- if (key === param && val) {
992
- return val;
993
- }
994
- }
995
- return null;
996
- }
997
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabsFragmentSync, deps: [], target: i0.ɵɵFactoryTarget.Directive });
998
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxTabsFragmentSync, isStandalone: true, selector: "[cngxTabsFragmentSync]", inputs: { mode: { classPropertyName: "mode", publicName: "mode", isSignal: true, isRequired: false, transformFunction: null }, paramName: { classPropertyName: "paramName", publicName: "paramName", isSignal: true, isRequired: false, transformFunction: null } }, exportAs: ["cngxTabsFragmentSync"], ngImport: i0 });
462
+ function withTabOverflowTriggerTemplate(template) {
463
+ return defineTabsConfigFeature((cfg) => ({
464
+ ...cfg,
465
+ templates: { ...cfg.templates, overflowTrigger: template },
466
+ }));
467
+ }
468
+ /**
469
+ * App-wide override for each row inside the overflow popover. \
470
+ * Middle tier; per-instance `*cngxTabOverflowItem` still wins.
471
+ *
472
+ * @category common/tabs
473
+ */
474
+ function withTabOverflowItemTemplate(template) {
475
+ return defineTabsConfigFeature((cfg) => ({
476
+ ...cfg,
477
+ templates: { ...cfg.templates, overflowItem: template },
478
+ }));
479
+ }
480
+ /**
481
+ * App-wide override for the error-badge decoration. Middle tier;
482
+ * per-instance `*cngxTabErrorBadge` still wins. Sibling of the
483
+ * stepper family's `withStepBadgeTemplate`.
484
+ *
485
+ * @category common/tabs
486
+ */
487
+ function withTabErrorBadgeTemplate(template) {
488
+ return defineTabsConfigFeature((cfg) => ({
489
+ ...cfg,
490
+ templates: { ...cfg.templates, errorBadge: template },
491
+ }));
999
492
  }
1000
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabsFragmentSync, decorators: [{
1001
- type: Directive,
1002
- args: [{
1003
- selector: '[cngxTabsFragmentSync]',
1004
- exportAs: 'cngxTabsFragmentSync',
1005
- standalone: true,
1006
- }]
1007
- }], ctorParameters: () => [], propDecorators: { mode: [{ type: i0.Input, args: [{ isSignal: true, alias: "mode", required: false }] }], paramName: [{ type: i0.Input, args: [{ isSignal: true, alias: "paramName", required: false }] }] } });
1008
-
1009
493
  /**
1010
- * Default tab-to-route mapping: the tab id is the child segment.
1011
- * Shared so the factory and `[cngxTabsRouteSync]` reference one
1012
- * definition instead of inlining the closure twice.
494
+ * App-wide override for the rejection-icon decoration. Middle
495
+ * tier; \
496
+ * per-instance `*cngxTabRejectionIcon` still wins. Sibling
497
+ * of {@link withStepRejectionTemplate}.
1013
498
  *
1014
- * @internal
499
+ * @category common/tabs
1015
500
  */
1016
- const cngxDefaultTabRoute = (handle) => [handle.id];
501
+ function withTabRejectionIconTemplate(template) {
502
+ return defineTabsConfigFeature((cfg) => ({
503
+ ...cfg,
504
+ templates: { ...cfg.templates, rejectionIcon: template },
505
+ }));
506
+ }
1017
507
  /**
1018
- * Builds a {@link CngxTabsCommitAction} that gates a tab switch through
1019
- * `@angular/router`. The action navigates to the target tab's route and
1020
- * resolves on the router's own outcome:
508
+ * App-wide override for the commit-pending busy-spinner overlay.
509
+ * Middle tier; per-instance `*cngxTabBusySpinner` still wins.
510
+ * Sibling of {@link withStepBusySpinnerTemplate}.
1021
511
  *
1022
- * - `NavigationEnd` → `true` (commit the switch)
1023
- * - `NavigationCancel` (a `CanDeactivate` guard blocked) → `false`
1024
- * - `NavigationError` (guard/resolver threw) → `false`
512
+ * @category common/tabs
513
+ */
514
+ function withTabBusySpinnerTemplate(template) {
515
+ return defineTabsConfigFeature((cfg) => ({
516
+ ...cfg,
517
+ templates: { ...cfg.templates, busySpinner: template },
518
+ }));
519
+ }
520
+ /**
521
+ * App-wide override for the tab-icon slot. Middle tier of the 3-stage
522
+ * cascade; per-instance `*cngxTabIcon` still wins. Sibling of
523
+ * {@link withStepIndicatorTemplate}.
1025
524
  *
1026
- * Routed tabs reuse the presenter's commit lifecycle verbatim - the
1027
- * router navigation is simply the async op. \
1028
- * In pessimistic mode the active tab follows the *resolved* route, so a cancelled guard keeps
1029
- * the old tab with zero extra gate machinery. The events subscription
1030
- * is opened *before* `navigate(...)` so a synchronously-resolving
1031
- * navigation cannot emit before the action is listening; the commit
1032
- * controller's `cancel()` unsubscribes on supersede.
525
+ * @category common/tabs
526
+ */
527
+ function withTabIconTemplate(template) {
528
+ return defineTabsConfigFeature((cfg) => ({
529
+ ...cfg,
530
+ templates: { ...cfg.templates, icon: template },
531
+ }));
532
+ }
533
+ /**
534
+ * App-wide override for a tab's close-button glyph. Middle tier;
535
+ * per-instance `*cngxTabCloseIcon` still wins.
1033
536
  *
1034
537
  * @category common/tabs
1035
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/router-commit.ts
1036
- * @since 0.1.0
1037
538
  */
1038
- function createTabRouterCommit(opts) {
1039
- const routeFor = opts.routeFor ?? cngxDefaultTabRoute;
1040
- return (_fromIndex, toIndex) => new Observable((subscriber) => {
1041
- const target = opts.tabs()[toIndex];
1042
- if (!target) {
1043
- subscriber.next(false);
1044
- subscriber.complete();
1045
- return;
1046
- }
1047
- const sub = opts.router.events
1048
- .pipe(filter((e) => e instanceof NavigationEnd ||
1049
- e instanceof NavigationCancel ||
1050
- e instanceof NavigationError), take(1))
1051
- .subscribe((event) => {
1052
- subscriber.next(event instanceof NavigationEnd);
1053
- subscriber.complete();
1054
- });
1055
- // A rejected promise surfaces on the events stream as
1056
- // NavigationError, so the subscription above is the single
1057
- // resolution path; swallow the promise rejection to avoid an
1058
- // unhandled-rejection warning.
1059
- opts.router.navigate(routeFor(target)).catch(() => undefined);
1060
- return () => sub.unsubscribe();
1061
- });
539
+ function withTabCloseIconTemplate(template) {
540
+ return defineTabsConfigFeature((cfg) => ({
541
+ ...cfg,
542
+ templates: { ...cfg.templates, closeIcon: template },
543
+ }));
1062
544
  }
1063
-
1064
545
  /**
1065
- * Router-outlet integration for tab groups. \
1066
- * Opt-in via `[cngxTabsRouteSync]` on the presenter element. Each tab is an
1067
- * Angular child route whose component renders into a `<router-outlet>`;
1068
- * switching tabs navigates, and a `CanDeactivate` guard can gate the
1069
- * leave.
546
+ * App-wide override for the add-tab button glyph. Middle tier;
547
+ * per-instance `*cngxTabAddIcon` still wins.
1070
548
  *
1071
- * Supplies the presenter's commit-action through the
1072
- * {@link CNGX_TABS_COMMIT_ACTION} DI fallback (no consumer
1073
- * `[commitAction]` hand-binding) and pins **pessimistic** mode so the
1074
- * active tab follows the *resolved* route - a guard-cancelled switch
1075
- * keeps the old tab. The routing gate reuses the presenter's commit
1076
- * lifecycle verbatim; the router navigation is the async op.
549
+ * @category common/tabs
550
+ */
551
+ function withTabAddIconTemplate(template) {
552
+ return defineTabsConfigFeature((cfg) => ({
553
+ ...cfg,
554
+ templates: { ...cfg.templates, addIcon: template },
555
+ }));
556
+ }
557
+ /**
558
+ * @internal The defaults with the copy keys read from the tabs section of
559
+ * the active language pack. Runs in an injection context.
560
+ */
561
+ function tabsConfigDefaultsFromPack() {
562
+ const language = injectTabsLanguage();
563
+ return {
564
+ ...TABS_CONFIG_DEFAULTS,
565
+ ariaLabels: computed(() => ({ tabsRegion: language().tabsRegion }), { equal: recordEqual }),
566
+ fallbackLabels: computed(() => ({
567
+ tabRoleDescription: language().tabRoleDescription,
568
+ tabPanelRoleDescription: language().tabPanelRoleDescription,
569
+ }), { equal: recordEqual }),
570
+ };
571
+ }
572
+ /** @internal Runs in an injection context; features apply on top of the pack. */
573
+ function resolveFeatures(features) {
574
+ return features.reduce((cfg, feat) => feat(cfg), tabsConfigDefaultsFromPack());
575
+ }
576
+ /**
577
+ * Root-level provider. Apply once in `bootstrapApplication` /
578
+ * `appConfig.providers`. Returns {@link EnvironmentProviders} per
579
+ * the canonical cngx config-cascade signature.
1077
580
  *
1078
- * Seeds the active tab from the current URL on mount and reflects
1079
- * external navigations (back/forward, direct URL) into `activeIndex`
1080
- * *without* re-navigating - those writes bypass the commit-action,
1081
- * since the router is already at the resolved route.
581
+ * @category common/tabs
582
+ */
583
+ function provideTabsConfig(...features) {
584
+ return makeEnvironmentProviders([
585
+ { provide: CNGX_TABS_CONFIG, useFactory: () => resolveFeatures(features) },
586
+ ]);
587
+ }
588
+ /**
589
+ * Component-scoped override. Returns `Provider[]` (not
590
+ * {@link EnvironmentProviders}) because `viewProviders` rejects
591
+ * opaque environment providers. Resolution priority: per-instance
592
+ * Input > viewProviders (`At`) > root > default.
1082
593
  *
1083
- * `Router` is optional - without it the directive logs a single dev
1084
- * warning via `afterNextRender`, exposes a null action, and becomes a
1085
- * no-op. Mirrors {@link CngxTabsFragmentSync}; every `activeIndex`
1086
- * write inside an effect sits in `untracked()`.
594
+ * ```ts
595
+ * @Component({
596
+ * viewProviders: [...provideTabsConfigAt(withTabsDefaultOrientation('vertical'))],
597
+ * })
598
+ * ```
1087
599
  *
1088
- * **The mental model.** It turns the tab group into the router's view
1089
- * switcher: the tabs choose *which child route* renders in the
1090
- * `<router-outlet>`, not which inline template shows. \
1091
- * Concretely, a Settings page with Profile / Security / Billing tabs then gets, for
1092
- * free: each tab its own URL (`/settings/profile`) so a refresh or a
1093
- * shared link stays on the tab; browser back/forward between tabs;
1094
- * `Billing` lazy-loading its chunk only when first opened; and `Profile`
1095
- * blocking the switch via a `CanDeactivate` guard while its form is
1096
- * dirty - all while keeping the `role="tab"` keyboard and ARIA model.
600
+ * @category common/tabs
601
+ */
602
+ function provideTabsConfigAt(...features) {
603
+ return [{ provide: CNGX_TABS_CONFIG, useFactory: () => resolveFeatures(features) }];
604
+ }
605
+ /**
606
+ * Inject the resolved tabs config in an injection context.
1097
607
  *
1098
- * **Use it when** each tab's content is a real Angular route - a lazy
1099
- * chunk, a resolver, or a `CanActivate` / `CanDeactivate` guard -
1100
- * rendered into a `<router-outlet>`, and you want browser back/forward
1101
- * and deep links to move between tabs while the route's own guard gates
1102
- * the switch (e.g. an unsaved-changes prompt on leave). \
1103
- * If the tabs are purely visual, use a plain `<cngx-tab-group>` with no sync directive;
1104
- * if you only want the active tab reflected in the URL while content
1105
- * stays inline, use {@link CngxTabsFragmentSync}.
608
+ * @category common/tabs
609
+ */
610
+ function injectTabsConfig() {
611
+ return inject(CNGX_TABS_CONFIG);
612
+ }
613
+
614
+ /**
615
+ * Wraps a {@link CngxCommitController} with the action-shape adapter
616
+ * that collapses `Observable<boolean>` / `Promise<boolean>` /
617
+ * `boolean` returns into a single `accept: boolean` outcome.
1106
618
  *
1107
- * **What this is not.** \
1108
- * Not a per-tab `routerLink`: \
1109
- * the tabs stay `role="tab"` buttons and the directive drives `router.navigate`
1110
- * centrally through the commit lifecycle, so there are no anchors, no
1111
- * `href`, and no native open-in-new-tab / middle-click / copy-link. \
1112
- * For real link semantics (right-click, ctrl-click) reach for the CNGX
1113
- * `<cngx-tab-nav>` and `<a cngx-tab-link routerLink>` variant
1114
- * instead. \
1115
- * Not URL deep-linking either - that is {@link CngxTabsFragmentSync} (a `#tab=` fragment or `?tab=`
1116
- * query-param); this directive renders child route *components* into a
1117
- * `<router-outlet>`. \
1118
- * And not optimistic: the active tab moves only once
1119
- * the route resolves, so a `CanDeactivate` guard can cancel the switch.
619
+ * @category common/tabs
620
+ */
621
+ function createTabsCommitHandler(opts) {
622
+ const { controller } = opts;
623
+ return {
624
+ isCommitting: controller.isCommitting,
625
+ beginTransition(fromIndex, toIndex, action, onResolve) {
626
+ controller.begin((handlers) => runTabsAction(action, fromIndex, toIndex, handlers), toIndex, fromIndex, {
627
+ onSuccess: () => onResolve(true),
628
+ onError: () => onResolve(false),
629
+ });
630
+ },
631
+ cancel() {
632
+ controller.cancel();
633
+ },
634
+ };
635
+ }
636
+ function runTabsAction(action, fromIndex, toIndex, handlers) {
637
+ let cancelled = false;
638
+ let unsubscribe = null;
639
+ const safeSuccess = (accept) => {
640
+ if (cancelled) {
641
+ return;
642
+ }
643
+ if (accept) {
644
+ handlers.onSuccess(toIndex);
645
+ }
646
+ else {
647
+ handlers.onError(new Error('Tab transition refused by commitAction'));
648
+ }
649
+ };
650
+ const safeError = (err) => {
651
+ if (cancelled) {
652
+ return;
653
+ }
654
+ handlers.onError(err);
655
+ };
656
+ let result;
657
+ try {
658
+ result = action(fromIndex, toIndex);
659
+ }
660
+ catch (err) {
661
+ safeError(err);
662
+ return {
663
+ cancel: () => {
664
+ cancelled = true;
665
+ },
666
+ };
667
+ }
668
+ if (isObservable(result)) {
669
+ // Synchronous Observables (`of(true)`) emit inside `.subscribe` before
670
+ // the assignment binds - close over a pre-declared `let` to avoid TDZ.
671
+ let sub = null;
672
+ let done = false;
673
+ sub = result.subscribe({
674
+ next: (accept) => {
675
+ if (done) {
676
+ return;
677
+ }
678
+ // Done-latch, not just unsubscribe: a synchronous emission fires
679
+ // while `sub` is still null, so a non-completing source would
680
+ // otherwise stay live and re-resolve on its next emission.
681
+ done = true;
682
+ safeSuccess(accept);
683
+ sub?.unsubscribe();
684
+ },
685
+ error: (err) => {
686
+ if (done) {
687
+ return;
688
+ }
689
+ safeError(err);
690
+ },
691
+ complete: () => {
692
+ // EMPTY-style sources complete without emitting; without this arm
693
+ // the commit stays 'pending' forever and busy() latches true.
694
+ if (!done) {
695
+ safeError(new Error('Tabs commitAction completed without emitting'));
696
+ }
697
+ },
698
+ });
699
+ if (done) {
700
+ // The in-next unsubscribe was a no-op for a sync emission; close
701
+ // the still-live subscription now that `sub` is bound.
702
+ sub.unsubscribe();
703
+ }
704
+ unsubscribe = () => sub?.unsubscribe();
705
+ }
706
+ else if (result != null && typeof result.then === 'function') {
707
+ result.then(safeSuccess, safeError);
708
+ }
709
+ else {
710
+ safeSuccess(result);
711
+ }
712
+ return {
713
+ cancel: () => {
714
+ cancelled = true;
715
+ unsubscribe?.();
716
+ },
717
+ };
718
+ }
719
+ /**
720
+ * DI token for the commit-handler factory. \
721
+ * Defaults to {@link createTabsCommitHandler}. \
722
+ * Sibling to
723
+ * - `CNGX_ARRAY_COMMIT_HANDLER_FACTORY` (select) and
724
+ * - `CNGX_STEPPER_COMMIT_HANDLER_FACTORY`.
1120
725
  *
1121
- * ```ts
1122
- * // Each tab is a child route; the editor guards its own exit.
1123
- * const ROUTES: Routes = [
1124
- * { path: '', pathMatch: 'full', redirectTo: 'editor' },
1125
- * { path: 'editor', component: EditorPage, canDeactivate: [unsavedChangesGuard] },
1126
- * { path: 'preview', component: PreviewPage },
1127
- * { path: 'settings', component: SettingsPage },
1128
- * ];
1129
- * ```
726
+ * @category common/tabs
727
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/commit-handler.ts
728
+ * @since 0.1.0
729
+ */
730
+ const CNGX_TABS_COMMIT_HANDLER_FACTORY = new InjectionToken('CngxTabsCommitHandlerFactory', {
731
+ providedIn: 'root',
732
+ factory: () => createTabsCommitHandler,
733
+ });
734
+
735
+ /**
736
+ * DI token for the tab presenter's contract. \
737
+ * Presenter provides via `useExisting`; `CngxTab` injects to register; the organism injects
738
+ * to drive the APG tablist keyboard model (automatic activation via
739
+ * `select()`, roving stop derived from `activeId`) through
740
+ * `createTabKeyboardNav`.
1130
741
  *
1131
- * ```html
1132
- * <!-- Tab ids match the child segments (default routeFor = (h) => [h.id]).
1133
- * Switching a tab navigates; the guard gates leaving the editor;
1134
- * back/forward and /account/settings deep links move the active tab. -->
1135
- * <cngx-tab-group cngxTabsRouteSync aria-label="Account">
1136
- * <div cngxTab id="editor" label="Editor"></div>
1137
- * <div cngxTab id="preview" label="Preview"></div>
1138
- * <div cngxTab id="settings" label="Settings"></div>
1139
- * </cngx-tab-group>
742
+ * @category common/tabs
743
+ * @wcag AA
744
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab-group-host.token.ts
745
+ * @since 0.1.0
746
+ */
747
+ const CNGX_TAB_GROUP_HOST = new InjectionToken('CngxTabGroupHost');
748
+
749
+ /**
750
+ * Tab-group presenter - brain of every CNGX tab flow. \
751
+ * Owns the active-index model, the tab registry, orientation, loop policy,
752
+ * and the commit-controller lifecycle. \
753
+ * Provides {@link CNGX_TAB_GROUP_HOST} for atoms and {@link CNGX_STATEFUL}
754
+ * so `<cngx-toast-on />` / `<cngx-banner-on />` compose without
755
+ * `[state]` wiring.
1140
756
  *
1141
- * <!-- The active tab's routed component renders here. -->
1142
- * <router-outlet></router-outlet>
1143
- * ```
757
+ * **Layer:** `@cngx/common/tabs`. \
758
+ * Directive-only - organisms compose via `hostDirectives`, consumers attach
759
+ * `[cngxTabGroup]` directly.
1144
760
  *
1145
761
  * @category common/tabs
1146
762
  * @docsKind primary
1147
763
  * @wcag AA
1148
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/route-sync.directive.ts
764
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/presenter.directive.ts
1149
765
  * @since 0.1.0
1150
- * @relatedTo CngxTabGroupPresenter, CngxTabsFragmentSync, createTabRouterCommit, CngxTabNav, CngxTabLink
766
+ * @relatedTo CngxTab, CngxTabContent, CngxTabLabel, CngxTabsFragmentSync
767
+ * <example-url>http://localhost:4200/#/ui/tabs/tab-commit-action/optimistic-pessimistic-commits-with-bridge-directives</example-url>
1151
768
  */
1152
- class CngxTabsRouteSync {
769
+ class CngxTabGroupPresenter {
770
+ config = injectTabsConfig();
771
+ activeIndex = model(0, ...(ngDevMode ? [{ debugName: "activeIndex" }] : /* istanbul ignore next */ []));
1153
772
  /**
1154
- * Maps a tab handle to its router command array. Default
1155
- * `(handle) => [handle.id]` - the tab id is the child segment.
1156
- * Override for real route paths.
773
+ * @internal Two-field alias - bind the public `[orientation]`; read
774
+ * the resolved {@link orientation} computed (input ?? config ?? default).
1157
775
  */
1158
- routeFor = input(cngxDefaultTabRoute, ...(ngDevMode ? [{ debugName: "routeFor" }] : /* istanbul ignore next */ []));
1159
- host = inject(CNGX_TAB_GROUP_HOST, { host: true });
1160
- router = inject(Router, { optional: true });
776
+ orientationInput = input(undefined, { ...(ngDevMode ? { debugName: "orientationInput" } : /* istanbul ignore next */ {}), alias: 'orientation' });
777
+ orientation = computed(() => this.orientationInput() ?? this.config.defaultOrientation ?? 'horizontal', ...(ngDevMode ? [{ debugName: "orientation" }] : /* istanbul ignore next */ []));
1161
778
  /**
1162
- * Pessimistic-only - not exposed as an input. The route-sync owns the
1163
- * mode so optimistic (show-then-revert) can never flash the target
1164
- * tab before a `CanDeactivate` guard decides.
779
+ * @internal Two-field alias - bind the public `[loop]`; read the
780
+ * resolved {@link loop} computed (input ?? config ?? default).
1165
781
  */
1166
- mode = signal('pessimistic', ...(ngDevMode ? [{ debugName: "mode" }] : /* istanbul ignore next */ []));
782
+ loopInput = input(undefined, { ...(ngDevMode ? { debugName: "loopInput" } : /* istanbul ignore next */ {}), alias: 'loop' });
783
+ loop = computed(() => this.loopInput() ?? this.config.defaultLoop ?? true, ...(ngDevMode ? [{ debugName: "loop" }] : /* istanbul ignore next */ []));
1167
784
  /**
1168
- * Router commit-action read by the presenter via the DI fallback.
1169
- * `null` when no `Router` is available (graceful no-op). Rebuilt only
1170
- * when `routeFor` changes; the navigation gate itself is the async
1171
- * op inside the action.
785
+ * Async-commit action gating the transition.
786
+ * When non-null, `select(...)` routes through {@link CngxTabsCommitHandler}; the
787
+ * action's resolution decides whether the change lands. Supersede
788
+ * semantics come from the commit-controller - a rapid second
789
+ * `select(...)` cancels the in-flight runner.
790
+ *
791
+ * @internal Two-field alias - bind the public `[commitAction]`; read
792
+ * the resolved {@link commitAction} computed (input ?? DI fallback).
1172
793
  */
1173
- action = computed(() => {
1174
- const router = this.router;
1175
- if (!router) {
1176
- return null;
794
+ commitActionInput = input(null, { ...(ngDevMode ? { debugName: "commitActionInput" } : /* istanbul ignore next */ {}), alias: 'commitAction' });
795
+ /**
796
+ * Default `'optimistic'` - tab change is navigation, not a save,
797
+ * so eager visual feedback matches the user's mental model.
798
+ * Switch to `'pessimistic'` when the new tab must wait for the
799
+ * action to confirm.
800
+ *
801
+ * @internal Two-field alias - bind the public `[commitMode]`; read
802
+ * the resolved {@link commitMode} computed (DI fallback mode wins
803
+ * when a routed action is active, else input ?? config ?? default).
804
+ */
805
+ commitModeInput = input(undefined, { ...(ngDevMode ? { debugName: "commitModeInput" } : /* istanbul ignore next */ {}), alias: 'commitMode' });
806
+ injector = inject(Injector);
807
+ // Resolved lazily, never in a field initialiser: a sync directive
808
+ // (e.g. [cngxTabsRouteSync]) provides CNGX_TABS_COMMIT_ACTION via
809
+ // useExisting and itself injects this presenter as its host, so
810
+ // eager injection here would close a construction cycle (NG0200).
811
+ // First read happens at select()/template time - after both
812
+ // directives exist. The source is static per element, so memoising
813
+ // the resolution is safe.
814
+ injectedActionSource;
815
+ resolveInjectedAction() {
816
+ if (this.injectedActionSource === undefined) {
817
+ this.injectedActionSource = this.injector.get(CNGX_TABS_COMMIT_ACTION, null);
1177
818
  }
1178
- return createTabRouterCommit({
1179
- router,
1180
- tabs: this.host.tabs,
1181
- routeFor: this.routeFor(),
819
+ return this.injectedActionSource;
820
+ }
821
+ /**
822
+ * Resolved commit-action: the `[commitAction]` input when bound, else
823
+ * the {@link CNGX_TABS_COMMIT_ACTION} DI fallback (routed path), else
824
+ * `null`. `select()` reads this.
825
+ */
826
+ commitAction = computed(() => this.commitActionInput() ?? this.resolveInjectedAction()?.action() ?? null, ...(ngDevMode ? [{ debugName: "commitAction" }] : /* istanbul ignore next */ []));
827
+ /**
828
+ * Resolved commit mode. When the DI fallback supplies an active
829
+ * action its `mode` wins - the routed path pins `'pessimistic'` so a
830
+ * stray `[commitMode]="'optimistic'"` cannot break the
831
+ * route-follows-resolution invariant. Otherwise the `[commitMode]`
832
+ * input drives.
833
+ */
834
+ commitMode = computed(() => {
835
+ const source = this.resolveInjectedAction();
836
+ if (source?.action()) {
837
+ return source.mode();
838
+ }
839
+ return this.commitModeInput() ?? this.config.defaultCommitMode ?? 'optimistic';
840
+ }, ...(ngDevMode ? [{ debugName: "commitMode" }] : /* istanbul ignore next */ []));
841
+ /**
842
+ * Emitted when a tab's close affordance is activated (the close
843
+ * button or Delete on the focused tab). The presenter has
844
+ * already moved the active index onto the surviving neighbour; the
845
+ * consumer removes the tab from its own data in the handler.
846
+ */
847
+ tabClose = output();
848
+ /**
849
+ * Emitted when the add-tab affordance is activated. The consumer
850
+ * appends a tab to its own data; the presenter owns no creation logic.
851
+ */
852
+ tabAdd = output();
853
+ genericFactory = inject(CNGX_COMMIT_CONTROLLER_FACTORY);
854
+ commitController = this.genericFactory();
855
+ commitHandler = inject(CNGX_TABS_COMMIT_HANDLER_FACTORY)({
856
+ controller: this.commitController,
857
+ });
858
+ /** Producer surface for the `CNGX_STATEFUL` bridge contract. */
859
+ state = this.commitController.state;
860
+ commitState = this.commitController.state;
861
+ /**
862
+ * Index the user is currently trying to commit to. Tracked
863
+ * separately from `state.data()` (which only updates on success)
864
+ * to drive per-tab `aria-busy`.
865
+ */
866
+ intendedIndex = this.commitController.intendedValue;
867
+ /**
868
+ * Current/previous pair for `commitState.status()`. Skin
869
+ * sub-components feed `<span cngxLiveRegion>` from this tracker
870
+ * for declarative SR announcements. Shared across consumers so
871
+ * the tracker's `linkedSignal` is allocated once per presenter.
872
+ */
873
+ commitTransition = createTransitionTracker(() => this.commitController.state.status());
874
+ // Persistence-of-error surface - see `CngxTabGroupHost.lastFailedIndex`
875
+ // and `originIndexDuringCommit` for the contract.
876
+ lastFailedIndexState = signal(undefined, ...(ngDevMode ? [{ debugName: "lastFailedIndexState" }] : /* istanbul ignore next */ []));
877
+ originIndexDuringCommitState = signal(undefined, ...(ngDevMode ? [{ debugName: "originIndexDuringCommitState" }] : /* istanbul ignore next */ []));
878
+ /** {@inheritDoc CngxTabGroupHost.lastFailedIndex} */
879
+ lastFailedIndex = this.lastFailedIndexState.asReadonly();
880
+ /** {@inheritDoc CngxTabGroupHost.originIndexDuringCommit} */
881
+ originIndexDuringCommit = this.originIndexDuringCommitState.asReadonly();
882
+ tabsState = signal([], { ...(ngDevMode ? { debugName: "tabsState" } : /* istanbul ignore next */ {}), equal: tabsEqual });
883
+ tabs = this.tabsState.asReadonly();
884
+ clampedIndex = computed(() => {
885
+ const count = this.tabs().length;
886
+ if (count === 0) {
887
+ return 0;
888
+ }
889
+ return Math.max(0, Math.min(this.activeIndex(), count - 1));
890
+ }, ...(ngDevMode ? [{ debugName: "clampedIndex" }] : /* istanbul ignore next */ []));
891
+ activeId = computed(() => this.tabs()[this.clampedIndex()]?.id ?? null, { ...(ngDevMode ? { debugName: "activeId" } : /* istanbul ignore next */ {}), equal: Object.is });
892
+ register(handle) {
893
+ const current = this.tabsState();
894
+ const idx = current.findIndex((h) => h.id === handle.id);
895
+ if (idx >= 0) {
896
+ const next = current.slice();
897
+ next[idx] = handle;
898
+ this.tabsState.set(next);
899
+ return;
900
+ }
901
+ this.tabsState.set([...current, handle]);
902
+ }
903
+ unregister(id, handle) {
904
+ const current = this.tabsState();
905
+ const entry = current.find((h) => h.id === id);
906
+ if (entry === undefined) {
907
+ return;
908
+ }
909
+ // Instance guard: after an idempotent re-register replaced the stored
910
+ // handle, the superseded instance's destroy is a no-op.
911
+ if (handle !== undefined && entry !== handle) {
912
+ return;
913
+ }
914
+ this.tabsState.set(current.filter((h) => h !== entry));
915
+ }
916
+ /** {@inheritDoc CngxTabGroupHost.clearLastFailed} */
917
+ clearLastFailed() {
918
+ this.lastFailedIndexState.set(undefined);
919
+ }
920
+ select(index) {
921
+ const tabs = this.tabs();
922
+ if (tabs.length === 0) {
923
+ return;
924
+ }
925
+ const target = Math.max(0, Math.min(index, tabs.length - 1));
926
+ if (tabs[target].disabled()) {
927
+ return;
928
+ }
929
+ const previous = this.activeIndex();
930
+ if (target === previous) {
931
+ return;
932
+ }
933
+ const action = this.commitAction();
934
+ if (!action) {
935
+ // No-action fast path - `originIndexDuringCommit` stays
936
+ // untouched, so a stale origin can never leak into the
937
+ // live-region announcement.
938
+ this.activeIndex.set(target);
939
+ if (this.lastFailedIndexState() === target) {
940
+ this.lastFailedIndexState.set(undefined);
941
+ }
942
+ return;
943
+ }
944
+ // Open the commit window - origin is captured ONLY here so a
945
+ // stale value never lingers into a non-commit navigation.
946
+ this.originIndexDuringCommitState.set(previous);
947
+ const mode = this.commitMode();
948
+ if (mode === 'optimistic') {
949
+ this.activeIndex.set(target);
950
+ }
951
+ this.commitHandler.beginTransition(previous, target, action, (accept) => {
952
+ if (accept) {
953
+ // Window closes on success - origin label no longer needed;
954
+ // clear the rejection flag if the user re-picked the failed
955
+ // target successfully.
956
+ this.originIndexDuringCommitState.set(undefined);
957
+ if (this.lastFailedIndexState() === target) {
958
+ this.lastFailedIndexState.set(undefined);
959
+ }
960
+ if (mode === 'pessimistic') {
961
+ this.activeIndex.set(target);
962
+ }
963
+ }
964
+ else {
965
+ // Reject - flag the refused target; RETAIN the origin so
966
+ // the organism's `liveAnnouncement` computed can resolve
967
+ // the origin label for the rich rollback phrase. Optimistic
968
+ // rolls back; pessimistic never moved.
969
+ this.lastFailedIndexState.set(target);
970
+ if (mode === 'optimistic') {
971
+ this.activeIndex.set(previous);
972
+ }
973
+ }
1182
974
  });
1183
- }, ...(ngDevMode ? [{ debugName: "action" }] : /* istanbul ignore next */ []));
1184
- constructor() {
1185
- if (!this.router) {
1186
- afterNextRender(() => warnTabsRouterAbsent('CngxTabsRouteSync', 'routed tabs'));
975
+ }
976
+ selectNext() {
977
+ const tabs = this.tabs();
978
+ if (tabs.length === 0) {
1187
979
  return;
1188
980
  }
1189
- const router = this.router;
1190
- const destroyRef = inject(DestroyRef);
1191
- // Seed from the current URL once the registry has populated.
1192
- afterNextRender(() => {
1193
- untracked(() => this.reflectFromUrl(router));
1194
- });
1195
- const navEnd = toSignal(router.events.pipe(filter((e) => e instanceof NavigationEnd), takeUntilDestroyed(destroyRef)), { initialValue: null });
1196
- effect(() => {
1197
- const e = navEnd();
1198
- if (!e) {
1199
- return;
981
+ let next = this.activeIndex() + 1;
982
+ while (next < tabs.length && tabs[next].disabled()) {
983
+ next++;
984
+ }
985
+ if (next < tabs.length) {
986
+ this.select(next);
987
+ return;
988
+ }
989
+ if (this.loop()) {
990
+ let i = 0;
991
+ while (i < tabs.length && tabs[i].disabled()) {
992
+ i++;
1200
993
  }
1201
- untracked(() => this.reflectFromUrl(router));
1202
- });
994
+ if (i < tabs.length && i !== this.activeIndex()) {
995
+ this.select(i);
996
+ }
997
+ }
1203
998
  }
1204
- /**
1205
- * Mirror the URL's active tab onto `activeIndex` without navigating.
1206
- * Writing the index directly (not via `select()`) is the re-entry
1207
- * guard: `select()` would re-run the commit-action and navigate to
1208
- * the route the router is already on, leaving the commit pending
1209
- * forever.
1210
- */
1211
- reflectFromUrl(router) {
1212
- const next = this.readActiveId(router);
1213
- if (!next || next === this.host.activeId()) {
999
+ selectPrevious() {
1000
+ const tabs = this.tabs();
1001
+ if (tabs.length === 0) {
1214
1002
  return;
1215
1003
  }
1216
- const index = this.host.tabs().findIndex((t) => t.id === next);
1217
- if (index >= 0) {
1218
- this.host.activeIndex.set(index);
1004
+ let prev = this.activeIndex() - 1;
1005
+ while (prev >= 0 && tabs[prev].disabled()) {
1006
+ prev--;
1219
1007
  }
1220
- }
1221
- /**
1222
- * Find the tab whose route is the trailing segment(s) of the current
1223
- * URL path. Anchors on position (a suffix match), not a loose
1224
- * "appears anywhere" scan - a tab id that happens to equal an
1225
- * unrelated parent segment cannot win. The path is taken before any
1226
- * query/fragment. If two tabs produce the same trailing segment(s)
1227
- * (only possible with a custom `routeFor` that collides), the first
1228
- * registered tab wins - the default id-based mapping never collides.
1229
- */
1230
- readActiveId(router) {
1231
- const path = router.url.split(/[?#]/)[0];
1232
- const segments = path.split('/').filter(Boolean);
1233
- const routeFor = this.routeFor();
1234
- for (const tab of this.host.tabs()) {
1235
- const route = routeFor(tab).map((command) => String(command));
1236
- if (route.length === 0 || route.length > segments.length) {
1237
- continue;
1008
+ if (prev >= 0) {
1009
+ this.select(prev);
1010
+ return;
1011
+ }
1012
+ if (this.loop()) {
1013
+ let i = tabs.length - 1;
1014
+ while (i >= 0 && tabs[i].disabled()) {
1015
+ i--;
1238
1016
  }
1239
- const tail = segments.slice(-route.length);
1240
- if (tail.every((segment, i) => segment === route[i])) {
1241
- return tab.id;
1017
+ if (i >= 0 && i !== this.activeIndex()) {
1018
+ this.select(i);
1242
1019
  }
1243
1020
  }
1244
- return null;
1245
1021
  }
1246
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabsRouteSync, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1247
- 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 });
1022
+ selectById(id) {
1023
+ const tabs = this.tabs();
1024
+ const idx = tabs.findIndex((h) => h.id === id);
1025
+ if (idx >= 0) {
1026
+ this.select(idx);
1027
+ }
1028
+ }
1029
+ requestClose(id) {
1030
+ const tabs = this.tabs();
1031
+ const index = tabs.findIndex((h) => h.id === id);
1032
+ if (index < 0) {
1033
+ return;
1034
+ }
1035
+ const active = this.clampedIndex();
1036
+ // Closing a tab BEFORE the active one needs a pre-emptive index
1037
+ // shift: the active tab moves down one slot once the consumer
1038
+ // removes the closed tab, so decrement to keep the same tab active.
1039
+ // Closing the active tab mid-strip (or one after the active) needs
1040
+ // no write - `clampedIndex` re-derives against the shorter array
1041
+ // and lands on the next tab.
1042
+ if (index < active) {
1043
+ this.activeIndex.set(active - 1);
1044
+ }
1045
+ else if (index === active && index === tabs.length - 1 && index > 0) {
1046
+ // Closing the ACTIVE LAST tab: the derived clamp would land on the
1047
+ // new last, but the [(activeIndex)] model itself would keep the
1048
+ // now out-of-range value - clamp-write so two-way consumers see
1049
+ // the real position.
1050
+ this.activeIndex.set(index - 1);
1051
+ }
1052
+ // The rejection markers are flat indices into the same registry, so a
1053
+ // close before them drifts the decoration onto the wrong tab (reachable
1054
+ // only via the dismissable affordance the organism layers on top). Shift
1055
+ // them the same way `activeIndex` shifts, and drop the marker outright
1056
+ // when its own tab is the one closed.
1057
+ this.lastFailedIndexState.update((failed) => shiftIndexOnClose(failed, index));
1058
+ this.originIndexDuringCommitState.update((origin) => shiftIndexOnClose(origin, index));
1059
+ this.tabClose.emit({ id, index });
1060
+ }
1061
+ requestAdd() {
1062
+ this.tabAdd.emit();
1063
+ }
1064
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabGroupPresenter, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1065
+ 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 }, orientationInput: { classPropertyName: "orientationInput", publicName: "orientation", isSignal: true, isRequired: false, transformFunction: null }, loopInput: { classPropertyName: "loopInput", 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: [
1066
+ { provide: CNGX_TAB_GROUP_HOST, useExisting: CngxTabGroupPresenter },
1067
+ { provide: CNGX_STATEFUL, useExisting: CngxTabGroupPresenter },
1068
+ ], exportAs: ["cngxTabGroup"], ngImport: i0 });
1248
1069
  }
1249
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabsRouteSync, decorators: [{
1070
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabGroupPresenter, decorators: [{
1250
1071
  type: Directive,
1251
1072
  args: [{
1252
- selector: '[cngxTabsRouteSync]',
1253
- exportAs: 'cngxTabsRouteSync',
1073
+ selector: '[cngxTabGroup]',
1074
+ exportAs: 'cngxTabGroup',
1254
1075
  standalone: true,
1255
- providers: [{ provide: CNGX_TABS_COMMIT_ACTION, useExisting: CngxTabsRouteSync }],
1076
+ providers: [
1077
+ { provide: CNGX_TAB_GROUP_HOST, useExisting: CngxTabGroupPresenter },
1078
+ { provide: CNGX_STATEFUL, useExisting: CngxTabGroupPresenter },
1079
+ ],
1256
1080
  }]
1257
- }], ctorParameters: () => [], propDecorators: { routeFor: [{ type: i0.Input, args: [{ isSignal: true, alias: "routeFor", required: false }] }] } });
1258
-
1259
- const TABS_CONFIG_DEFAULTS = {
1260
- defaultOrientation: 'horizontal',
1261
- defaultLoop: true,
1262
- defaultCommitMode: 'optimistic',
1263
- fragmentSyncMode: 'fragment',
1264
- fragmentSyncParam: 'tab',
1265
- ariaLabels: {
1266
- tabsRegion: 'Tabs',
1267
- },
1268
- fallbackLabels: {
1269
- // W3C ARIA tablist convention - kept distinct from
1270
- // `i18n.tabsLabel` so AT doesn't read the same string twice
1271
- // back-to-back across `aria-roledescription` and `aria-label`.
1272
- tabRoleDescription: 'tab list',
1273
- tabPanelRoleDescription: 'tab panel',
1274
- },
1275
- overflowStabilizeMs: 100,
1276
- overflowMaxDeferMs: 250,
1277
- templates: {},
1278
- };
1081
+ }], propDecorators: { activeIndex: [{ type: i0.Input, args: [{ isSignal: true, alias: "activeIndex", required: false }] }, { type: i0.Output, args: ["activeIndexChange"] }], orientationInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "orientation", required: false }] }], loopInput: [{ 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"] }] } });
1279
1082
  /**
1280
- * DI token for the resolved tabs config. \
1281
- * `providedIn: 'root'` with the library defaults; override via {@link provideTabsConfig}
1282
- * (root) or {@link provideTabsConfigAt} (component scope).
1083
+ * Follow a stored flat rejection index across the removal of the tab at
1084
+ * `removed`. The referenced tab going away drops the marker (`undefined`);
1085
+ * a removal ahead of it shifts it down one slot; a removal after it leaves
1086
+ * it put. Keeps `lastFailedIndex` / `originIndexDuringCommit` pointing at the
1087
+ * same handle once the consumer removes a dismissed tab from its data.
1283
1088
  *
1284
- * @category common/tabs
1285
- * @wcag AA
1286
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tabs-config.ts
1287
- * @since 0.1.0
1089
+ * @internal
1288
1090
  */
1289
- const CNGX_TABS_CONFIG = new InjectionToken('CngxTabsConfig', {
1290
- providedIn: 'root',
1291
- factory: () => TABS_CONFIG_DEFAULTS,
1292
- });
1091
+ function shiftIndexOnClose(stored, removed) {
1092
+ if (stored === undefined || removed === stored) {
1093
+ return undefined;
1094
+ }
1095
+ return removed < stored ? stored - 1 : stored;
1096
+ }
1293
1097
  /**
1294
- * Internal helper that brands a config-mutator function with the
1295
- * `_target` discriminator. \
1296
- * Every `with*` config feature returns one
1297
- * of these.
1098
+ * Registry equality for the tab registry signal: element-wise reference
1099
+ * identity, not structural comparison. Two arrays are equal only when
1100
+ * they carry the exact same handle instances in the same order.
1101
+ *
1102
+ * Handles are stable per-tab references - `label`, `disabled`,
1103
+ * `hasError` and friends propagate through the handle's signals, so
1104
+ * consumers update off the handle without the registry array
1105
+ * re-emitting, and value comparison here would be redundant for an
1106
+ * unchanged handle. For a REPLACED handle (idempotent re-register
1107
+ * under an id collision) a value compare is actively wrong: it reports
1108
+ * the value-identical new instance as equal, discards the write, and
1109
+ * leaves the registry serving the destroyed instance's signals.
1110
+ * Reference inequality is the change signal.
1298
1111
  *
1299
1112
  * @internal
1300
1113
  */
1301
- function defineTabsConfigFeature(fn) {
1302
- return Object.assign(fn, { _target: 'config' });
1114
+ function tabsEqual(a, b) {
1115
+ if (a === b) {
1116
+ return true;
1117
+ }
1118
+ if (a.length !== b.length) {
1119
+ return false;
1120
+ }
1121
+ for (let i = 0; i < a.length; i++) {
1122
+ if (a[i] !== b[i]) {
1123
+ return false;
1124
+ }
1125
+ }
1126
+ return true;
1303
1127
  }
1128
+
1304
1129
  /**
1305
- * Override the default orientation. Per-instance `[orientation]`
1306
- * still wins; this changes the cascade default only.
1130
+ * DI token the organism provides via `useExisting`.\
1131
+ * The overflow molecule and consumer-authored skin sub-components inject this
1132
+ * instead of the concrete component class.
1307
1133
  *
1308
1134
  * @category common/tabs
1135
+ * @wcag AA
1136
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab-panel-host.token.ts
1137
+ * @since 0.1.0
1309
1138
  */
1310
- function withTabsDefaultOrientation(orientation) {
1311
- return defineTabsConfigFeature((cfg) => ({
1312
- ...cfg,
1313
- defaultOrientation: orientation,
1314
- }));
1315
- }
1139
+ const CNGX_TAB_PANEL_HOST = new InjectionToken('CngxTabPanelHost');
1140
+
1316
1141
  /**
1317
- * @deprecated Use {@link withTabsDefaultOrientation}. The unprefixed name
1318
- * collides with the stepper family's identical symbol when both libs
1319
- * are auto-imported. The alias stays for one minor release before
1320
- * removal.
1142
+ * Marks a tab presenter as the **navigation** flavour rather than the
1143
+ * tablist flavour. \
1144
+ * Provided by `<cngx-tab-nav>` (`@cngx/ui/tabs`) and `[cngxMatTabNav]`
1145
+ * (`@cngx/ui/mat-tabs`); deliberately not provided by `<cngx-tab-group>`.
1146
+ *
1147
+ * Presence-only by design. There is no contract interface: providers
1148
+ * register `{ provide: CNGX_TAB_NAV_HOST, useValue: true }` and readers
1149
+ * only ever test `navHost != null`. Nothing here can be widened into a
1150
+ * second host contract - {@link CNGX_TAB_GROUP_HOST} already owns the
1151
+ * presenter surface, and this token sits beside it so the tablist path
1152
+ * gains no dead field.
1153
+ *
1154
+ * **Why a token and not the host class.** A sub-directive talks to its
1155
+ * host through DI, never through a concrete class: importing `CngxTabNav`
1156
+ * from `@cngx/common` would be a `common -> ui` edge that Sheriff rejects,
1157
+ * and element-tag sniffing breaks the moment a decomposed skin renames the
1158
+ * element.
1159
+ *
1160
+ * **What reads it.** {@link CngxTabsRouteSync} injects it
1161
+ * `{ optional: true, host: true }` to pick its URL-matching semantics: a
1162
+ * nav link owns a whole subtree and stays current for every URL beneath it
1163
+ * (prefix), while a tablist tab is a leaf and matches only its own route
1164
+ * (suffix). The `[match]` input overrides the token-derived default when a
1165
+ * consumer needs the other mode.
1166
+ *
1167
+ * ```ts
1168
+ * @Component({
1169
+ * selector: 'my-section-nav',
1170
+ * providers: [{ provide: CNGX_TAB_NAV_HOST, useValue: true }],
1171
+ * hostDirectives: [CngxTabGroupPresenter],
1172
+ * })
1173
+ * export class MySectionNav {}
1174
+ * ```
1321
1175
  *
1322
1176
  * @category common/tabs
1177
+ * @wcag AA
1178
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab-nav-host.token.ts
1179
+ * @since 0.1.0
1180
+ * @relatedTo CngxTabsRouteSync, CNGX_TAB_GROUP_HOST, CngxTabNav, CngxMatTabNav
1323
1181
  */
1324
- const withDefaultOrientation = withTabsDefaultOrientation;
1182
+ const CNGX_TAB_NAV_HOST = new InjectionToken('CngxTabNavHost');
1183
+
1325
1184
  /**
1326
- * Override whether roving-tabindex navigation loops from last back to
1327
- * first (and vice versa). Per-instance `[loop]` Input still wins.
1185
+ * Path-segment count of a resolved `UrlTree`, used to rank prefix
1186
+ * matches: `/rounds/explorer` outranks `/rounds` on a URL both match.
1187
+ */
1188
+ function urlTreeSegmentCount(tree) {
1189
+ let count = 0;
1190
+ const walk = (group) => {
1191
+ count += group.segments.length;
1192
+ for (const key of Object.keys(group.children)) {
1193
+ walk(group.children[key]);
1194
+ }
1195
+ };
1196
+ walk(tree.root);
1197
+ return count;
1198
+ }
1199
+ /**
1200
+ * Primary-outlet path segments of the current URL, decoded. Going
1201
+ * through `router.parseUrl` (not a hand-rolled split) keeps matrix
1202
+ * params (`;theme=dark`) out of the compared paths, decodes
1203
+ * percent-encoded segments so they compare against raw `routeFor`
1204
+ * commands, and confines the walk to the primary outlet so an aux
1205
+ * outlet (`(aside:x)`) can neither pollute the tail nor match.
1206
+ */
1207
+ function primaryPathSegments(router) {
1208
+ const segments = [];
1209
+ let group = router.parseUrl(router.url).root;
1210
+ while (group !== undefined) {
1211
+ segments.push(...group.segments.map((segment) => segment.path));
1212
+ group = group.children[PRIMARY_OUTLET];
1213
+ }
1214
+ return segments;
1215
+ }
1216
+ /**
1217
+ * Find the tab whose route is the trailing segment(s) of the current URL
1218
+ * path. Anchors on position, not a loose "appears anywhere" scan - a tab
1219
+ * id that happens to equal an unrelated parent segment cannot win. The
1220
+ * path is the decoded primary-outlet segment list (query, fragment,
1221
+ * matrix params, and aux outlets excluded). If two tabs produce the same
1222
+ * trailing segment(s) (only possible with a colliding custom `routeFor`),
1223
+ * the first registered tab wins; the default id-based mapping never
1224
+ * collides.
1225
+ */
1226
+ function resolveBySuffix(ctx) {
1227
+ const segments = primaryPathSegments(ctx.router);
1228
+ for (const tab of ctx.tabs) {
1229
+ const route = ctx.routeFor(tab).map((command) => String(command));
1230
+ if (route.length === 0 || route.length > segments.length) {
1231
+ continue;
1232
+ }
1233
+ const tail = segments.slice(-route.length);
1234
+ if (tail.every((segment, i) => segment === route[i])) {
1235
+ return tab.id;
1236
+ }
1237
+ }
1238
+ return null;
1239
+ }
1240
+ /**
1241
+ * Find the tab that owns the current URL's subtree: the one whose
1242
+ * resolved `UrlTree` is a subset of the active tree, ignoring query
1243
+ * params, fragment, and matrix params.
1244
+ *
1245
+ * Routes resolve `{ relativeTo: ActivatedRoute }` rather than against the
1246
+ * URL root. A root-anchored segment compare breaks a nav mounted under a
1247
+ * base path - at `/app/rounds` a `['rounds']` route would compare
1248
+ * `'app' === 'rounds'`, resolve `null`, and hand the first link a wrong
1249
+ * `aria-current`, which is the exact defect prefix mode exists to fix.
1250
+ * Relative resolution is safe on the read side because the nav path is
1251
+ * commit-free: links navigate through their own `routerLink`, so nothing
1252
+ * here can diverge from a commit navigation.
1253
+ *
1254
+ * Longest route wins, so a `/rounds` tab cannot shadow `/rounds/explorer`
1255
+ * in the same set.
1256
+ */
1257
+ function resolveByPrefix(ctx) {
1258
+ let winner = null;
1259
+ let winnerDepth = -1;
1260
+ for (const tab of ctx.tabs) {
1261
+ const route = ctx.routeFor(tab);
1262
+ if (route.length === 0) {
1263
+ continue;
1264
+ }
1265
+ const tree = ctx.router.createUrlTree(route, { relativeTo: ctx.activatedRoute });
1266
+ const active = ctx.router.isActive(tree, {
1267
+ paths: 'subset',
1268
+ queryParams: 'ignored',
1269
+ fragment: 'ignored',
1270
+ matrixParams: 'ignored',
1271
+ });
1272
+ if (!active) {
1273
+ continue;
1274
+ }
1275
+ const depth = urlTreeSegmentCount(tree);
1276
+ if (depth > winnerDepth) {
1277
+ winner = tab.id;
1278
+ winnerDepth = depth;
1279
+ }
1280
+ }
1281
+ return winner;
1282
+ }
1283
+ /**
1284
+ * The two URL-matching policies `[cngxTabsRouteSync]` ships, dispatched
1285
+ * on {@link CngxTabUrlMatchContext.mode}. Same exact-versus-prefix
1286
+ * distinction `routerLinkActive` draws.
1287
+ *
1288
+ * Pure: no injection context, no signal reads. The directive resolves the
1289
+ * mode cascade and the tab registry, then hands both in.
1328
1290
  *
1329
1291
  * @category common/tabs
1330
1292
  */
1331
- function withTabsRovingLoop(loop) {
1332
- return defineTabsConfigFeature((cfg) => ({ ...cfg, defaultLoop: loop }));
1293
+ function createTabUrlMatch() {
1294
+ return {
1295
+ resolve(ctx) {
1296
+ return ctx.mode === 'prefix' ? resolveByPrefix(ctx) : resolveBySuffix(ctx);
1297
+ },
1298
+ };
1333
1299
  }
1334
1300
  /**
1335
- * Override the default commit mode for async tab transitions.
1336
- * `'optimistic'` activates the tab on action dispatch and rolls back
1337
- * on error; `'pessimistic'` waits for success. Per-instance
1338
- * `[commitMode]` Input still wins.
1301
+ * Swap point for how a routed tab set decides which tab the URL belongs
1302
+ * to. Default {@link createTabUrlMatch}.
1303
+ *
1304
+ * Override when neither shipped policy fits: locale-segment-insensitive
1305
+ * comparison (`/de/rounds` and `/en/rounds` are the same tab), matching
1306
+ * on a route `data` key instead of the path, or a permission-aware read
1307
+ * that skips tabs the user cannot open. `routeFor` only changes what a
1308
+ * tab's route *is*; this changes how it is *compared*.
1309
+ *
1310
+ * Mirrors {@link CNGX_TABS_COMMIT_ACTION} on the write side: the
1311
+ * navigation a tab switch performs is already swappable, so the read that
1312
+ * mirrors navigation back onto `activeIndex` should be too.
1339
1313
  *
1340
1314
  * @category common/tabs
1315
+ * @wcag AA
1316
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/url-match.ts
1317
+ * @since 0.1.0
1318
+ * @relatedTo CngxTabsRouteSync, createTabUrlMatch, createTabRouterCommit
1341
1319
  */
1342
- function withTabsCommitMode(mode) {
1343
- return defineTabsConfigFeature((cfg) => ({
1344
- ...cfg,
1345
- defaultCommitMode: mode,
1346
- }));
1347
- }
1320
+ const CNGX_TAB_URL_MATCH_STRATEGY = new InjectionToken('CngxTabUrlMatchStrategy', {
1321
+ providedIn: 'root',
1322
+ factory: () => createTabUrlMatch(),
1323
+ });
1324
+
1348
1325
  /**
1349
- * Configure URL fragment / query-param deep-linking for the active tab
1350
- * (the {@link CngxTabsFragmentSync} directive). \
1351
- * `mode` chooses the URL surface (URL fragment or query parameter); `param` names the key
1352
- * (default `'tab'`).
1326
+ * Structural slot directive marking the per-tab panel-body template. \
1327
+ * Discovered by `<cngx-tab-group>` via `contentChild` on each
1328
+ * `CngxTab` and projected into the matching `role="tabpanel"`.
1353
1329
  *
1354
- * Not to be confused with `[cngxTabsRouteSync]`, the router-outlet
1355
- * integration - this feature configures fragment deep-linking only.
1330
+ * ```html
1331
+ * <div cngxTab [label]="'Settings'">
1332
+ * <ng-template cngxTabContent>
1333
+ * <p>Settings panel body…</p>
1334
+ * </ng-template>
1335
+ * </div>
1336
+ * ```
1356
1337
  *
1357
1338
  * @category common/tabs
1339
+ * @wcag AA
1340
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab-content.directive.ts
1341
+ * @since 0.1.0
1342
+ * @relatedTo CngxTab, CngxTabLabel
1358
1343
  */
1359
- function withTabsFragmentSync(mode, param = 'tab') {
1360
- return defineTabsConfigFeature((cfg) => ({
1361
- ...cfg,
1362
- fragmentSyncMode: mode,
1363
- fragmentSyncParam: param,
1364
- }));
1344
+ class CngxTabContent {
1345
+ templateRef = inject((TemplateRef));
1346
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabContent, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1347
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxTabContent, isStandalone: true, selector: "ng-template[cngxTabContent]", exportAs: ["cngxTabContent"], ngImport: i0 });
1365
1348
  }
1349
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabContent, decorators: [{
1350
+ type: Directive,
1351
+ args: [{
1352
+ selector: 'ng-template[cngxTabContent]',
1353
+ exportAs: 'cngxTabContent',
1354
+ standalone: true,
1355
+ }]
1356
+ }] });
1357
+
1366
1358
  /**
1367
- * @deprecated Use {@link withTabsFragmentSync}. "Router sync" collided
1368
- * with the new `[cngxTabsRouteSync]` router-outlet directive; this
1369
- * feature only ever configured fragment / query-param deep-linking. The
1370
- * alias stays for one minor release before removal.
1359
+ * Structural slot directive marking the per-tab label template. \
1360
+ * Discovered by `<cngx-tab-group>` via `contentChild` on each
1361
+ * `CngxTab` and projected into the tab strip.
1371
1362
  *
1372
- * @category common/tabs
1373
- */
1374
- const withTabsRouterSync = withTabsFragmentSync;
1375
- /**
1376
- * Select the app-wide default visual skin for `<cngx-tab-group>`. \
1377
- * Default `'line'`. Per-instance `[skin]` Input still wins; this moves
1378
- * the cascade default. Structure, slots, ARIA, and keyboard behaviour
1379
- * are identical across skins - only the `[data-skin]` host attribute
1380
- * changes the CSS layer. The Material twin (`[cngxMatTabs]`) ignores it.
1363
+ * ```html
1364
+ * <div cngxTab id="settings">
1365
+ * <ng-template cngxTabLabel>Settings</ng-template>
1366
+ * ... tab content ...
1367
+ * </div>
1368
+ * ```
1381
1369
  *
1382
1370
  * @category common/tabs
1371
+ * @wcag AA
1372
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab-label.directive.ts
1373
+ * @since 0.1.0
1374
+ * @relatedTo CngxTab, CngxTabContent
1383
1375
  */
1384
- function withTabsSkin(skin) {
1385
- return defineTabsConfigFeature((cfg) => ({ ...cfg, skin }));
1376
+ class CngxTabLabel {
1377
+ templateRef = inject((TemplateRef));
1378
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabLabel, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1379
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxTabLabel, isStandalone: true, selector: "ng-template[cngxTabLabel]", exportAs: ["cngxTabLabel"], ngImport: i0 });
1386
1380
  }
1381
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabLabel, decorators: [{
1382
+ type: Directive,
1383
+ args: [{
1384
+ selector: 'ng-template[cngxTabLabel]',
1385
+ exportAs: 'cngxTabLabel',
1386
+ standalone: true,
1387
+ }]
1388
+ }] });
1389
+
1387
1390
  /**
1388
- * Set the app-wide default icon layout for `<cngx-tab-group>`. \
1389
- * Default`'start'`. Per-instance `[iconLayout]` Input still wins. Orthogonal to
1390
- * skin and orientation - only the `[data-icon-layout]` host attribute
1391
- * changes.
1391
+ * Structural slot directive marking a tab's secondary label template. \
1392
+ * Discovered by `<cngx-tab-group>` via `contentChild` on each
1393
+ * `CngxTab` and rendered as a stacked second line under the primary
1394
+ * label. \
1392
1395
  *
1393
- * @category common/tabs
1396
+ * Per-tab content, mirroring `CngxTabLabel` - the convenience
1397
+ * `[subLabel]` string input on `CngxTab` covers the plain-text case.
1398
+ *
1399
+ * ```html
1400
+ * <div cngxTab id="bookmarks">
1401
+ * <ng-template cngxTabLabel>Bookmarks</ng-template>
1402
+ * <ng-template cngxTabSubLabel>45 saved</ng-template>
1403
+ * <ng-template cngxTabContent>...</ng-template>
1404
+ * </div>
1405
+ * ```
1406
+ *
1407
+ * @category common/tabs/slots
1408
+ * @wcag AA
1409
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/slots/tab-sub-label.directive.ts
1410
+ * @since 0.1.0
1411
+ * @relatedTo CngxTab, CngxTabLabel, CngxTabContent
1412
+ * <example-url>http://localhost:4200/#/ui/tabs/tab-sub-label/label-with-count</example-url>
1394
1413
  */
1395
- function withTabsIconLayout(layout) {
1396
- return defineTabsConfigFeature((cfg) => ({ ...cfg, iconLayout: layout }));
1414
+ class CngxTabSubLabel {
1415
+ /**
1416
+ * The captured `<ng-template>`, projected by `<cngx-tab-group>` as the
1417
+ * tab's secondary label line under the primary label.
1418
+ */
1419
+ templateRef = inject((TemplateRef));
1420
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabSubLabel, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1421
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: CngxTabSubLabel, isStandalone: true, selector: "ng-template[cngxTabSubLabel]", exportAs: ["cngxTabSubLabel"], ngImport: i0 });
1397
1422
  }
1423
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabSubLabel, decorators: [{
1424
+ type: Directive,
1425
+ args: [{
1426
+ selector: 'ng-template[cngxTabSubLabel]',
1427
+ exportAs: 'cngxTabSubLabel',
1428
+ standalone: true,
1429
+ }]
1430
+ }] });
1431
+
1398
1432
  /**
1399
- * Set the app-wide default panel render strategy for `<cngx-tab-group>`. \
1400
- * Default `'eager'` (every panel's content rendered up front, toggled
1401
- * via `[hidden]`). `'lazy'` keep-alives content after first activation;
1402
- * `'lazy-destroy'` renders only the active panel's content. Per-instance
1403
- * `[panelMode]` Input still wins. The panel `<div>` always stays in the
1404
- * DOM regardless of mode (the `aria-controls` target).
1433
+ * Single-tab atom. \
1434
+ * Registers with the enclosing presenter via
1435
+ * {@link CNGX_TAB_GROUP_HOST} on construction; deregisters via
1436
+ * {@link DestroyRef} on teardown. \
1437
+ * The presenter holds the atom's
1438
+ * input signals by reference, so input changes propagate without
1439
+ * re-registration. \
1440
+ * `labelTemplate` / `contentTemplate` are projected
1441
+ * by the organism - the atom carries no rendering logic.
1405
1442
  *
1443
+ * ```html
1444
+ * <div cngxTab [label]="'Settings'">
1445
+ * ... content templates here ...
1446
+ * </div>
1447
+ * ```
1406
1448
  * @category common/tabs
1449
+ * @docsKind primary
1450
+ * @wcag AA
1451
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab.directive.ts
1452
+ * @since 0.1.0
1453
+ * @relatedTo CngxTabGroupPresenter, CngxTabLabel, CngxTabContent, CngxTabErrorBadge
1454
+ * @slot cngxTabLabel The tab's own header label.
1455
+ * @slot cngxTabSubLabel Secondary line under the label, e.g. a count or status.
1456
+ * @slot cngxTabContent The panel body, rendered lazily when the tab activates.
1407
1457
  */
1408
- function withTabsPanelMode(mode) {
1409
- return defineTabsConfigFeature((cfg) => ({ ...cfg, panelMode: mode }));
1458
+ class CngxTab {
1459
+ id = input(nextUid('cngx-tab-'), ...(ngDevMode ? [{ debugName: "id" }] : /* istanbul ignore next */ []));
1460
+ disabled = input(false, ...(ngDevMode ? [{ debugName: "disabled" }] : /* istanbul ignore next */ []));
1461
+ label = input(undefined, ...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
1462
+ /**
1463
+ * Optional secondary text line under the primary label (a count, a
1464
+ * status word, a short detail). Convenience for the common text
1465
+ * case, parallel to `[label]`; the `*cngxTabSubLabel` slot covers
1466
+ * richer content. Folds into the tab's accessible name.
1467
+ */
1468
+ subLabel = input(undefined, ...(ngDevMode ? [{ debugName: "subLabel" }] : /* istanbul ignore next */ []));
1469
+ errorAggregator = input(undefined, ...(ngDevMode ? [{ debugName: "errorAggregator" }] : /* istanbul ignore next */ []));
1470
+ /**
1471
+ * Direct error flag for the common "this tab is invalid" case - no
1472
+ * `errorAggregator` boilerplate required. `true` or a non-empty string
1473
+ * drives the error state; a string doubles as the inline message
1474
+ * (surfaced via the `*cngxTabErrorBadge` slot context). `false` / `''`
1475
+ * clear it. The aggregator stays the rich multi-source forms path; the
1476
+ * two channels compose (either errors). Mirrors `CngxStep.error`.
1477
+ */
1478
+ error = input(false, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
1479
+ /**
1480
+ * Resolved direct-error message: the `[error]` string when non-empty,
1481
+ * else `undefined`. Carried onto the registration handle so the error
1482
+ * badge slot can render it. `computed` over the input - never written.
1483
+ */
1484
+ errorMessage = computed(() => {
1485
+ const value = this.error();
1486
+ return typeof value === 'string' && value !== '' ? value : undefined;
1487
+ }, ...(ngDevMode ? [{ debugName: "errorMessage" }] : /* istanbul ignore next */ []));
1488
+ /**
1489
+ * Per-tab error fold driving the badge + SR descriptor. `true` when
1490
+ * the direct `[error]` flag is set OR the optional aggregator wants to
1491
+ * reveal (`shouldShow()` = `hasError` AND scope reveal-state). The
1492
+ * aggregator arm reads `shouldShow`, not `hasError`, so deferred-reveal
1493
+ * validation stays silent until revealed - the direct flag has no
1494
+ * reveal concept (the consumer sets it when it wants it shown). A
1495
+ * boolean, not a status enum: tabs carry no success/completed/disabled
1496
+ * model (Pillar 3).
1497
+ */
1498
+ hasError = computed(() => {
1499
+ const directError = this.error();
1500
+ return ((directError !== false && directError !== '') ||
1501
+ (this.errorAggregator()?.shouldShow?.() ?? false));
1502
+ }, { ...(ngDevMode ? { debugName: "hasError" } : /* istanbul ignore next */ {}), equal: Object.is });
1503
+ /**
1504
+ * Per-tab close-affordance override. `undefined` (default) inherits
1505
+ * the group-level `[closable]` resolution; set `false` to pin this
1506
+ * tab open inside a dismissable group, or `true` to make a single tab
1507
+ * closable while the group default is off.
1508
+ */
1509
+ closable = input(undefined, ...(ngDevMode ? [{ debugName: "closable" }] : /* istanbul ignore next */ []));
1510
+ labelTemplate = contentChild(CngxTabLabel, ...(ngDevMode ? [{ debugName: "labelTemplate" }] : /* istanbul ignore next */ []));
1511
+ subLabelTemplate = contentChild(CngxTabSubLabel, ...(ngDevMode ? [{ debugName: "subLabelTemplate" }] : /* istanbul ignore next */ []));
1512
+ contentTemplate = contentChild(CngxTabContent, ...(ngDevMode ? [{ debugName: "contentTemplate" }] : /* istanbul ignore next */ []));
1513
+ host = inject(CNGX_TAB_GROUP_HOST, { optional: true });
1514
+ destroyRef = inject(DestroyRef);
1515
+ /** `true` when the presenter's `activeId` equals this tab's id. */
1516
+ selected = computed(() => this.host?.activeId() === this.id(), { ...(ngDevMode ? { debugName: "selected" } : /* istanbul ignore next */ {}), equal: Object.is });
1517
+ constructor() {
1518
+ if (!this.host) {
1519
+ throw new Error('CngxTab: no enclosing CngxTabGroupPresenter found. Wrap the tab inside an element carrying [cngxTabGroup] (or place it inside <cngx-tab-group>).');
1520
+ }
1521
+ }
1522
+ ngOnInit() {
1523
+ // Register in ngOnInit, NOT the constructor: a dynamically-bound
1524
+ // `[id]` (or `[label]`) signal input is not applied until the first
1525
+ // change detection, so a constructor read would capture the default
1526
+ // auto-id. The handle id is the stable key consumers map `(tabClose)`
1527
+ // back to their data with, so it must reflect the bound `[id]`.
1528
+ // The id is captured once here - init-stable by contract. A later
1529
+ // `[id]` rebind does not re-register; the auto-uid default makes a
1530
+ // stable consumer-supplied id the normal case. Mirrors CngxStep.
1531
+ const host = this.host;
1532
+ const tabId = this.id();
1533
+ const handle = {
1534
+ id: tabId,
1535
+ label: this.label,
1536
+ subLabel: this.subLabel,
1537
+ disabled: this.disabled,
1538
+ errorAggregator: this.errorAggregator,
1539
+ hasError: this.hasError,
1540
+ errorMessage: this.errorMessage,
1541
+ closable: this.closable,
1542
+ };
1543
+ host.register(handle);
1544
+ this.destroyRef.onDestroy(() => host.unregister(tabId, handle));
1545
+ }
1546
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTab, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1547
+ 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 });
1410
1548
  }
1549
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTab, decorators: [{
1550
+ type: Directive,
1551
+ args: [{
1552
+ selector: '[cngxTab]',
1553
+ exportAs: 'cngxTab',
1554
+ standalone: true,
1555
+ }]
1556
+ }], 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 }] }] } });
1557
+
1411
1558
  /**
1412
- * Set the app-wide default for stretching tabs to the full strip width
1413
- * (horizontal only). \
1414
- * Default `false`. Per-instance `[fitted]` Input still
1415
- * wins. No effect under `orientation="vertical"`.
1559
+ * Turns a consumer `<a routerLink>` into a registered {@link CngxTabHandle}
1560
+ * inside a {@link CngxTabNav}. \
1561
+ * Native parallel of {@link CngxMatTabLink}: in a
1562
+ * navigation bar the link IS the tab, so this per-anchor directive is the
1563
+ * registration seam - symmetric with how `CngxTab` registers each `[cngxTab]`.
1564
+ *
1565
+ * Carries no rendering and no click handler. Navigation is the native
1566
+ * `routerLink` (middle-click, open-in-new-tab and the hover URL all work),
1567
+ * gating is the link's own `CanDeactivate`, and the active marker comes from
1568
+ * the route: `[cngxTabsRouteSync]` on the nav reflects `NavigationEnd` onto the
1569
+ * presenter's `activeId`, which this link matches against its own `id`. \
1570
+ * There is no `select()` call - invoking it would re-enter the commit path the
1571
+ * routed-nav model deliberately keeps dormant.
1572
+ *
1573
+ * **Error communication is reactive:** `aria-invalid` plus the
1574
+ * `--error` skin glyph signal the state, and an injected screen-reader
1575
+ * descriptor span (referenced by a permanent `aria-describedby`) carries the
1576
+ * direct `[error]` message string so assistive tech reads *why* the link is
1577
+ * invalid.
1578
+ *
1579
+ * ```html
1580
+ * <cngx-tab-nav cngxTabsRouteSync>
1581
+ * <a cngxTabLink id="overview" routerLink="overview">Overview</a>
1582
+ * <a cngxTabLink id="profile" routerLink="profile" [error]="profileInvalid">Profile</a>
1583
+ * </cngx-tab-nav>
1584
+ * ```
1416
1585
  *
1417
1586
  * @category common/tabs
1587
+ * @docsKind primary
1588
+ * @wcag AA
1589
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/tab-link.directive.ts
1590
+ * @since 0.1.0
1591
+ * @relatedTo CngxTabNav, CngxTabsRouteSync, CngxTab, CngxMatTabLink
1418
1592
  */
1419
- function withTabsFitted(fitted) {
1420
- return defineTabsConfigFeature((cfg) => ({ ...cfg, fitted }));
1593
+ class CngxTabLink {
1594
+ host = inject(CNGX_TAB_GROUP_HOST, { optional: true });
1595
+ config = injectTabsConfig();
1596
+ destroyRef = inject(DestroyRef);
1597
+ renderer = inject(Renderer2);
1598
+ hostEl = inject(ElementRef).nativeElement;
1599
+ /**
1600
+ * Handle id. Set it to the link's route segment so the nav's
1601
+ * `[cngxTabsRouteSync]` reflects the active route onto this link via the
1602
+ * default `(h) => [h.id]` mapping. Defaults to a fresh uid when route-sync
1603
+ * is not used.
1604
+ */
1605
+ id = input(nextUid('cngx-tab-link-'), ...(ngDevMode ? [{ debugName: "id" }] : /* istanbul ignore next */ []));
1606
+ /** Accessible label fed to the nav's live-region announcer. */
1607
+ label = input(undefined, ...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
1608
+ /**
1609
+ * Direct error flag for the link - `true` or a non-empty string marks it
1610
+ * invalid (the string doubles as the message). Mirrors `CngxTab.error`.
1611
+ */
1612
+ error = input(false, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
1613
+ /** Optional rich error aggregator for the link. */
1614
+ errorAggregator = input(undefined, ...(ngDevMode ? [{ debugName: "errorAggregator" }] : /* istanbul ignore next */ []));
1615
+ /**
1616
+ * Resolved direct-error message: the `[error]` string when non-empty, else
1617
+ * `undefined`. Carried onto the registration handle by reference.
1618
+ * `computed` over the input - never written.
1619
+ */
1620
+ errorMessage = computed(() => {
1621
+ const value = this.error();
1622
+ return typeof value === 'string' && value !== '' ? value : undefined;
1623
+ }, ...(ngDevMode ? [{ debugName: "errorMessage" }] : /* istanbul ignore next */ []));
1624
+ /**
1625
+ * Per-link error fold driving `aria-invalid` and the `--error` class.
1626
+ * `true` when the direct `[error]` flag is set OR the optional aggregator
1627
+ * wants to reveal (`shouldShow()`, so deferred-reveal validation stays
1628
+ * silent until revealed). Mirrors `CngxTab.hasError`.
1629
+ */
1630
+ hasError = computed(() => {
1631
+ const direct = this.error();
1632
+ return ((direct !== false && direct !== '') || (this.errorAggregator()?.shouldShow?.() ?? false));
1633
+ }, { ...(ngDevMode ? { debugName: "hasError" } : /* istanbul ignore next */ {}), equal: Object.is });
1634
+ /**
1635
+ * Which `aria-current` token the link publishes while it is active.
1636
+ * Cascade: this input -> `CngxTabsConfig.linkAriaCurrent`
1637
+ * ({@link withTabsLinkAriaCurrent}) -> `'page'`.
1638
+ *
1639
+ * Use `'true'` when the link owns a *subtree* and stays active for URLs
1640
+ * beneath it - a section nav driven by `[cngxTabsRouteSync]` in its
1641
+ * prefix mode. WAI-ARIA reserves `page` for the current page itself, so
1642
+ * `page` on an ancestor section over-claims: AT reads "current page" for
1643
+ * something that is not the page being viewed. A whole nav switches at
1644
+ * once via `provideTabsConfigAt(withTabsLinkAriaCurrent('true'))`; this
1645
+ * input is the per-link escape hatch.
1646
+ *
1647
+ * Not derived from the sync directive's match mode on purpose. `selected`
1648
+ * has exactly one source, the presenter's `activeId` (Pillar 1); reading
1649
+ * a sibling directive's mode here would fork that derivation and couple
1650
+ * the atom to a directive it does not otherwise know about.
1651
+ */
1652
+ ariaCurrent = input(undefined, ...(ngDevMode ? [{ debugName: "ariaCurrent" }] : /* istanbul ignore next */ []));
1653
+ /** Resolved token: input -> config -> `'page'`. */
1654
+ resolvedAriaCurrent = computed(() => this.ariaCurrent() ?? this.config.linkAriaCurrent ?? 'page', ...(ngDevMode ? [{ debugName: "resolvedAriaCurrent" }] : /* istanbul ignore next */ []));
1655
+ /** `true` when the presenter's `activeId` equals this link's id. */
1656
+ selected = computed(() => this.host?.activeId() === this.id(), { ...(ngDevMode ? { debugName: "selected" } : /* istanbul ignore next */ {}), equal: Object.is });
1657
+ /**
1658
+ * Id of the injected SR error-message descriptor. The `aria-describedby`
1659
+ * host binding emits it only while `hasError()` - `aria-hidden` on a
1660
+ * directly-referenced node does not suppress it (accname 1.2 traverses
1661
+ * the reference), so the id reference itself is gated, not just the
1662
+ * span's visibility.
1663
+ */
1664
+ descriptorId = computed(() => `${this.id()}-desc`, ...(ngDevMode ? [{ debugName: "descriptorId" }] : /* istanbul ignore next */ []));
1665
+ /** The injected descriptor `<span>`, created in {@link ngOnInit}. */
1666
+ descriptorEl = null;
1667
+ constructor() {
1668
+ if (!this.host) {
1669
+ throw new Error('CngxTabLink: no enclosing CngxTabGroupPresenter found. Wrap the link inside <cngx-tab-nav> (or an element carrying [cngxTabGroup]).');
1670
+ }
1671
+ // Mirror the direct-error message into the describedby span. DOM side
1672
+ // effect only - no signal writes. Guards until the span exists (created
1673
+ // in ngOnInit); errorMessage / descriptorId changes re-run it after.
1674
+ effect(() => {
1675
+ const el = this.descriptorEl;
1676
+ if (el) {
1677
+ this.syncDescriptor(el);
1678
+ }
1679
+ });
1680
+ }
1681
+ ngOnInit() {
1682
+ // Register in ngOnInit, NOT the constructor: a dynamically-bound `[id]`
1683
+ // signal input is not applied until the first change detection, so a
1684
+ // constructor read would capture the default auto-id. The handle id is the
1685
+ // stable key the nav's route-sync matches the URL segment against.
1686
+ const host = this.host;
1687
+ const handle = {
1688
+ id: this.id(),
1689
+ label: this.label,
1690
+ subLabel: signal(undefined),
1691
+ disabled: signal(false),
1692
+ errorAggregator: this.errorAggregator,
1693
+ hasError: this.hasError,
1694
+ errorMessage: this.errorMessage,
1695
+ closable: signal(undefined),
1696
+ };
1697
+ host.register(handle);
1698
+ // Inject the SR error-message descriptor as a SIBLING of the anchor: a
1699
+ // child span would fold into the link's accessible name, so it lives
1700
+ // beside it and is reached only via the aria-describedby id.
1701
+ const descriptor = this.renderer.createElement('span');
1702
+ this.renderer.addClass(descriptor, 'cngx-sr-only');
1703
+ const parent = this.renderer.parentNode(this.hostEl);
1704
+ if (parent) {
1705
+ this.renderer.insertBefore(parent, descriptor, this.renderer.nextSibling(this.hostEl));
1706
+ }
1707
+ this.descriptorEl = descriptor;
1708
+ this.syncDescriptor(descriptor);
1709
+ this.destroyRef.onDestroy(() => {
1710
+ host.unregister(handle.id, handle);
1711
+ if (parent) {
1712
+ this.renderer.removeChild(parent, descriptor);
1713
+ }
1714
+ });
1715
+ }
1716
+ /**
1717
+ * Write the current direct-error message into the descriptor span and
1718
+ * toggle its `aria-hidden` so a clear link exposes no description. Keeps
1719
+ * the span id in sync with {@link descriptorId} (read here so the effect
1720
+ * tracks an id change too).
1721
+ */
1722
+ syncDescriptor(el) {
1723
+ this.renderer.setAttribute(el, 'id', this.descriptorId());
1724
+ const message = this.errorMessage() ?? '';
1725
+ this.renderer.setProperty(el, 'textContent', message);
1726
+ if (message) {
1727
+ this.renderer.removeAttribute(el, 'aria-hidden');
1728
+ }
1729
+ else {
1730
+ this.renderer.setAttribute(el, 'aria-hidden', 'true');
1731
+ }
1732
+ }
1733
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabLink, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1734
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxTabLink, isStandalone: true, selector: "[cngxTabLink]", inputs: { id: { classPropertyName: "id", publicName: "id", isSignal: true, isRequired: false, transformFunction: null }, label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null }, error: { classPropertyName: "error", publicName: "error", isSignal: true, isRequired: false, transformFunction: null }, errorAggregator: { classPropertyName: "errorAggregator", publicName: "errorAggregator", isSignal: true, isRequired: false, transformFunction: null }, ariaCurrent: { classPropertyName: "ariaCurrent", publicName: "ariaCurrent", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "attr.aria-current": "selected() ? resolvedAriaCurrent() : null", "attr.aria-invalid": "hasError() ? 'true' : null", "attr.aria-describedby": "hasError() ? descriptorId() : null", "class.cngx-tab-nav__link--active": "selected()", "class.cngx-tab-nav__link--error": "hasError()" }, classAttribute: "cngx-tab-nav__link" }, exportAs: ["cngxTabLink"], ngImport: i0 });
1421
1735
  }
1736
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabLink, decorators: [{
1737
+ type: Directive,
1738
+ args: [{
1739
+ selector: '[cngxTabLink]',
1740
+ exportAs: 'cngxTabLink',
1741
+ standalone: true,
1742
+ host: {
1743
+ class: 'cngx-tab-nav__link',
1744
+ '[attr.aria-current]': 'selected() ? resolvedAriaCurrent() : null',
1745
+ '[attr.aria-invalid]': "hasError() ? 'true' : null",
1746
+ '[attr.aria-describedby]': 'hasError() ? descriptorId() : null',
1747
+ '[class.cngx-tab-nav__link--active]': 'selected()',
1748
+ '[class.cngx-tab-nav__link--error]': 'hasError()',
1749
+ },
1750
+ }]
1751
+ }], ctorParameters: () => [], propDecorators: { id: [{ type: i0.Input, args: [{ isSignal: true, alias: "id", required: false }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }], error: [{ type: i0.Input, args: [{ isSignal: true, alias: "error", required: false }] }], errorAggregator: [{ type: i0.Input, args: [{ isSignal: true, alias: "errorAggregator", required: false }] }], ariaCurrent: [{ type: i0.Input, args: [{ isSignal: true, alias: "ariaCurrent", required: false }] }] } });
1752
+
1422
1753
  /**
1423
- * Set the app-wide default tab-cluster alignment (horizontal only). \
1424
- * Default `'start'`. Per-instance `[tabAlign]` Input still wins. Ignored
1425
- * under `orientation="vertical"` and when the group is `fitted`.
1754
+ * Single dev-warning both tab sync directives emit when `@angular/router`
1755
+ * is not provided. Shared so the message stays identical across
1756
+ * {@link CngxTabsFragmentSync} (deep-linking) and {@link CngxTabsRouteSync}
1757
+ * (router-outlet); only the `enables` clause differs. The URL readers
1758
+ * themselves stay separate - they target different surfaces (fragment /
1759
+ * query-param vs route path) and must not converge.
1426
1760
  *
1427
- * @category common/tabs
1761
+ * @internal
1428
1762
  */
1429
- function withTabsAlign(align) {
1430
- return defineTabsConfigFeature((cfg) => ({ ...cfg, tabAlign: align }));
1763
+ function warnTabsRouterAbsent(directive, enables) {
1764
+ console.warn(`${directive}: no Router available - directive is a no-op. ` +
1765
+ `Provide @angular/router via provideRouter(...) to enable ${enables}.`);
1431
1766
  }
1767
+
1432
1768
  /**
1433
- * Set the app-wide default for whether tabs render a close affordance. \
1434
- * Default `false`. Per-instance `[closable]` Input wins; a per-`CngxTab`
1435
- * `[closable]` override wins over both.
1769
+ * URL deep-linking for tab groups. \
1770
+ * Bidirectional sync between `activeId` and a URL fragment or query-param. Opt-in via
1771
+ * `[cngxTabsFragmentSync]` on the presenter element.
1436
1772
  *
1437
- * @category common/tabs
1438
- */
1439
- function withTabsClosable(closable) {
1440
- return defineTabsConfigFeature((cfg) => ({ ...cfg, closable }));
1441
- }
1442
- /**
1443
- * Set the app-wide default for whether the group renders an add-tab
1444
- * button. \
1445
- * Default `false`. Per-instance `[addable]` Input wins.
1773
+ * - `mode = 'fragment'` (default) → `#tab=settings`
1774
+ * - `mode = 'queryParam'` with `paramName = 'tab'` → `?tab=settings`
1446
1775
  *
1447
- * @category common/tabs
1448
- */
1449
- function withTabsAddable(addable) {
1450
- return defineTabsConfigFeature((cfg) => ({ ...cfg, addable }));
1451
- }
1452
- /**
1453
- * Merge ARIA labels into the cascade. Keys not provided keep their
1454
- * library defaults; per-instance overrides on the tab group still win.
1776
+ * Reflecting the active tab replaces the current history entry by
1777
+ * default, so browser-back leaves the page instead of stepping through
1778
+ * the tabs opened on the way. Set `[replaceUrl]="false"` when the tabs
1779
+ * read as distinct destinations.
1455
1780
  *
1456
- * @category common/tabs
1457
- */
1458
- function withTabsAriaLabels(labels) {
1459
- return defineTabsConfigFeature((cfg) => ({
1460
- ...cfg,
1461
- ariaLabels: { ...cfg.ariaLabels, ...labels },
1462
- }));
1463
- }
1464
- /**
1465
- * Merge text fallback labels (overflow trigger, busy / rejection text)
1466
- * into the cascade. Used when a slot directive is not present.
1781
+ * `Router` is optional - without it the directive logs a dev warning
1782
+ * via `afterNextRender` and becomes a no-op. \
1783
+ * Every `router.navigate` and `host.selectById` inside the effects sits in `untracked()`.
1467
1784
  *
1468
- * @category common/tabs
1469
- */
1470
- function withTabsFallbackLabels(labels) {
1471
- return defineTabsConfigFeature((cfg) => ({
1472
- ...cfg,
1473
- fallbackLabels: { ...cfg.fallbackLabels, ...labels },
1474
- }));
1475
- }
1476
- /**
1477
- * Override the IO-debounce window (ms). See
1478
- * {@link CngxTabsConfig.overflowStabilizeMs}.
1785
+ * ```html
1786
+ * <!-- Default fragment mode: the active tab reflects to #tab=<id>, and a
1787
+ * deep link like /account#tab=settings selects that tab on load. -->
1788
+ * <cngx-tab-group cngxTabsFragmentSync>
1789
+ * <div cngxTab id="overview" label="Overview"></div>
1790
+ * <div cngxTab id="settings" label="Settings"></div>
1791
+ * </cngx-tab-group>
1792
+ *
1793
+ * <!-- Query-param mode with a custom name -> ?section=settings -->
1794
+ * <cngx-tab-group cngxTabsFragmentSync mode="queryParam" paramName="section">
1795
+ * <!-- ...tabs... -->
1796
+ * </cngx-tab-group>
1797
+ * ```
1479
1798
  *
1480
1799
  * @category common/tabs
1800
+ * @docsKind primary
1801
+ * @wcag AA
1802
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/router-sync.directive.ts
1803
+ * @since 0.1.0
1804
+ * @relatedTo CngxTabGroupPresenter, CngxTab
1481
1805
  */
1482
- function withTabOverflowStabilizeMs(ms) {
1483
- return defineTabsConfigFeature((cfg) => ({
1484
- ...cfg,
1485
- overflowStabilizeMs: ms,
1486
- }));
1806
+ class CngxTabsFragmentSync {
1807
+ // Default undefined so the cascade resolves through CNGX_TABS_CONFIG.
1808
+ // Init-only: the seed and the write effect capture the resolved mode /
1809
+ // param on their first run; changing either after init leaves the old
1810
+ // URL key behind. Rebuild the directive to change them.
1811
+ modeInput = input(undefined, { ...(ngDevMode ? { debugName: "modeInput" } : /* istanbul ignore next */ {}), alias: 'mode' });
1812
+ paramNameInput = input(undefined, { ...(ngDevMode ? { debugName: "paramNameInput" } : /* istanbul ignore next */ {}), alias: 'paramName' });
1813
+ config = injectTabsConfig();
1814
+ mode = computed(() => this.modeInput() ?? this.config.fragmentSyncMode ?? 'fragment', ...(ngDevMode ? [{ debugName: "mode" }] : /* istanbul ignore next */ []));
1815
+ paramName = computed(() => this.paramNameInput() ?? this.config.fragmentSyncParam ?? 'tab', ...(ngDevMode ? [{ debugName: "paramName" }] : /* istanbul ignore next */ []));
1816
+ /**
1817
+ * Whether reflecting the active tab into the URL replaces the current
1818
+ * history entry instead of pushing a new one. Default `true`, which is
1819
+ * right for a view toggle: browser-back leaves the page rather than
1820
+ * stepping through the tabs the user opened on the way.
1821
+ *
1822
+ * Set `false` when the tabs read as distinct destinations and back
1823
+ * should step between them. Note that every tab switch then costs a
1824
+ * history entry.
1825
+ */
1826
+ replaceUrl = input(true, ...(ngDevMode ? [{ debugName: "replaceUrl" }] : /* istanbul ignore next */ []));
1827
+ host = inject(CNGX_TAB_GROUP_HOST, { host: true });
1828
+ router = inject(Router, { optional: true });
1829
+ /**
1830
+ * Latched once the URL seed has reached a registered tab, so the
1831
+ * `afterNextRender` fallback cannot run it twice.
1832
+ *
1833
+ * Not symmetric with {@link CngxTabsRouteSync}, and it has to be: that
1834
+ * sibling writes `activeIndex` directly, so its second seed bails on
1835
+ * the already-matching id. This one goes through `select()`, and under
1836
+ * a pessimistic commit `activeIndex` still holds the *previous* value
1837
+ * while the action is in flight - so the presenter's `target ===
1838
+ * previous` bail does not catch the repeat, and a consumer's async
1839
+ * commit action would fire a second time and supersede the first.
1840
+ */
1841
+ seeded = false;
1842
+ constructor() {
1843
+ if (!this.router) {
1844
+ afterNextRender(() => warnTabsRouterAbsent('CngxTabsFragmentSync', 'deep-linking'));
1845
+ return;
1846
+ }
1847
+ const router = this.router;
1848
+ const destroyRef = inject(DestroyRef);
1849
+ // Fallback seed for tabs that register after content-init (a
1850
+ // dynamic @for over an async list). Idempotent against the
1851
+ // content-init seed: selectById is a no-op when the id is already
1852
+ // active.
1853
+ afterNextRender(() => {
1854
+ this.seedFromUrl(router);
1855
+ });
1856
+ let initialReflect = true;
1857
+ effect(() => {
1858
+ const id = this.host.activeId();
1859
+ if (!id) {
1860
+ return;
1861
+ }
1862
+ if (initialReflect) {
1863
+ // Bare mount is not an interaction: the first resolved active id
1864
+ // (default tab or URL seed) must not stamp the URL - a page that
1865
+ // merely renders tabs would otherwise rewrite its own history
1866
+ // entry. The URL starts changing when the active tab does.
1867
+ initialReflect = false;
1868
+ return;
1869
+ }
1870
+ untracked(() => this.writeUrl(router, id));
1871
+ });
1872
+ const navEnd = toSignal(router.events.pipe(filter((e) => e instanceof NavigationEnd), takeUntilDestroyed(destroyRef)), { initialValue: null });
1873
+ effect(() => {
1874
+ const e = navEnd();
1875
+ if (!e) {
1876
+ return;
1877
+ }
1878
+ untracked(() => {
1879
+ const next = this.readUrlValue(router);
1880
+ if (next && next !== this.host.activeId()) {
1881
+ this.host.selectById(next);
1882
+ }
1883
+ });
1884
+ });
1885
+ }
1886
+ /**
1887
+ * Seed from the URL before the group renders its panels. `CngxTab`
1888
+ * registers in `ngOnInit`, so the registry is populated by the time
1889
+ * this runs, and the group's own view has not rendered yet - which is
1890
+ * what keeps `panelMode="lazy"` from counting the default tab's first
1891
+ * render as its first activation on a deep link.
1892
+ *
1893
+ * Unlike {@link CngxTabsRouteSync}, this seed goes through
1894
+ * `selectById`, so it runs `select()` and any consumer-bound
1895
+ * commit-action. Moving it earlier therefore also moves when that
1896
+ * action first fires; it still fires exactly once for the seed.
1897
+ *
1898
+ * Its own router guard: the constructor's early return does not stop
1899
+ * lifecycle hooks from running.
1900
+ */
1901
+ ngAfterContentInit() {
1902
+ if (!this.router) {
1903
+ return;
1904
+ }
1905
+ this.seedFromUrl(this.router);
1906
+ }
1907
+ seedFromUrl(router) {
1908
+ if (this.seeded) {
1909
+ return;
1910
+ }
1911
+ const initial = this.readUrlValue(router);
1912
+ if (!initial) {
1913
+ return;
1914
+ }
1915
+ // Only latch once the target is actually registered. A seed that
1916
+ // found no matching tab leaves the fallback armed for tabs that
1917
+ // register after content-init.
1918
+ if (!this.host.tabs().some((tab) => tab.id === initial)) {
1919
+ return;
1920
+ }
1921
+ this.seeded = true;
1922
+ untracked(() => this.host.selectById(initial));
1923
+ }
1924
+ /**
1925
+ * Reflect `id` into the URL. Fragment mode re-serializes the existing
1926
+ * fragment params so foreign state (`#foo=1&tab=x`) survives the
1927
+ * write; values are URI-encoded symmetric to {@link parseFragment}.
1928
+ */
1929
+ writeUrl(router, id) {
1930
+ const replaceUrl = this.replaceUrl();
1931
+ const navigation = this.mode() === 'fragment'
1932
+ ? router.navigate([], {
1933
+ fragment: this.serializeFragment(router, id),
1934
+ queryParamsHandling: 'merge',
1935
+ replaceUrl,
1936
+ })
1937
+ : router.navigate([], {
1938
+ queryParams: { [this.paramName()]: id },
1939
+ queryParamsHandling: 'merge',
1940
+ replaceUrl,
1941
+ });
1942
+ // Router rejection (e.g. cancelled navigation) has no recovery path.
1943
+ navigation.catch?.(() => undefined);
1944
+ }
1945
+ serializeFragment(router, id) {
1946
+ const param = this.paramName();
1947
+ const current = router.routerState.snapshot.root.fragment ?? '';
1948
+ const segments = current
1949
+ .split('&')
1950
+ .filter((seg) => seg !== '' && seg.split('=')[0] !== param);
1951
+ segments.push(`${param}=${encodeURIComponent(id)}`);
1952
+ return segments.join('&');
1953
+ }
1954
+ readUrlValue(router) {
1955
+ if (this.mode() === 'fragment') {
1956
+ const fragment = router.routerState.snapshot.root.fragment ?? '';
1957
+ return this.parseFragment(fragment);
1958
+ }
1959
+ return router.routerState.snapshot.root.queryParamMap.get(this.paramName()) ?? null;
1960
+ }
1961
+ parseFragment(fragment) {
1962
+ const param = this.paramName();
1963
+ const segments = fragment.split('&');
1964
+ for (const seg of segments) {
1965
+ const [key, val] = seg.split('=');
1966
+ if (key === param && val) {
1967
+ return decodeURIComponent(val);
1968
+ }
1969
+ }
1970
+ return null;
1971
+ }
1972
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabsFragmentSync, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1973
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxTabsFragmentSync, isStandalone: true, selector: "[cngxTabsFragmentSync]", inputs: { modeInput: { classPropertyName: "modeInput", publicName: "mode", isSignal: true, isRequired: false, transformFunction: null }, paramNameInput: { classPropertyName: "paramNameInput", publicName: "paramName", isSignal: true, isRequired: false, transformFunction: null }, replaceUrl: { classPropertyName: "replaceUrl", publicName: "replaceUrl", isSignal: true, isRequired: false, transformFunction: null } }, exportAs: ["cngxTabsFragmentSync"], ngImport: i0 });
1487
1974
  }
1975
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabsFragmentSync, decorators: [{
1976
+ type: Directive,
1977
+ args: [{
1978
+ selector: '[cngxTabsFragmentSync]',
1979
+ exportAs: 'cngxTabsFragmentSync',
1980
+ standalone: true,
1981
+ }]
1982
+ }], ctorParameters: () => [], propDecorators: { modeInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "mode", required: false }] }], paramNameInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "paramName", required: false }] }], replaceUrl: [{ type: i0.Input, args: [{ isSignal: true, alias: "replaceUrl", required: false }] }] } });
1983
+
1488
1984
  /**
1489
- * Override the worst-case staleness ceiling on the visibility-map
1490
- * commit. See {@link CngxTabsConfig.overflowMaxDeferMs}.
1985
+ * Default tab-to-route mapping: the tab id is the child segment.
1986
+ * Shared so the factory and `[cngxTabsRouteSync]` reference one
1987
+ * definition instead of inlining the closure twice.
1491
1988
  *
1492
- * @category common/tabs
1989
+ * @internal
1493
1990
  */
1494
- function withTabOverflowMaxDeferMs(ms) {
1495
- return defineTabsConfigFeature((cfg) => ({
1496
- ...cfg,
1497
- overflowMaxDeferMs: ms,
1498
- }));
1499
- }
1991
+ const cngxDefaultTabRoute = (handle) => [handle.id];
1500
1992
  /**
1501
- * App-wide override for the More-button label. Middle tier; \
1502
- * per-instance `*cngxTabOverflowTrigger` still wins.
1503
- *
1504
- * ```ts
1505
- * readonly moreTrigger = viewChild.required<TemplateRef<CngxTabOverflowTriggerContext>>(
1506
- * 'moreTrigger',
1507
- * { read: TemplateRef },
1508
- * );
1993
+ * Builds a {@link CngxTabsCommitAction} that gates a tab switch through
1994
+ * `@angular/router`. The action navigates to the target tab's route and
1995
+ * resolves on this navigation's own `navigate()` promise:
1509
1996
  *
1510
- * providers: [provideTabsConfig(withTabOverflowTriggerTemplate(this.moreTrigger()))]
1511
- * ```
1997
+ * - resolved `true` (`NavigationEnd`) → `true` (commit the switch)
1998
+ * - resolved `false` (`NavigationCancel` - a `CanDeactivate` guard
1999
+ * blocked, or a newer navigation superseded this one) → `false`
2000
+ * - rejected (`NavigationError` - guard/resolver threw) → `false`
1512
2001
  *
1513
- * @category common/tabs
1514
- */
1515
- function withTabOverflowTriggerTemplate(template) {
1516
- return defineTabsConfigFeature((cfg) => ({
1517
- ...cfg,
1518
- templates: { ...cfg.templates, overflowTrigger: template },
1519
- }));
1520
- }
1521
- /**
1522
- * App-wide override for each row inside the overflow popover. \
1523
- * Middle tier; per-instance `*cngxTabOverflowItem` still wins.
2002
+ * Routed tabs reuse the presenter's commit lifecycle verbatim - the
2003
+ * router navigation is simply the async op. \
2004
+ * In pessimistic mode the active tab follows the *resolved* route, so a cancelled guard keeps
2005
+ * the old tab with zero extra gate machinery. Correlating on the
2006
+ * promise (not `router.events`) means a concurrent unrelated
2007
+ * navigation's outcome can never resolve this commit; the commit
2008
+ * controller's `cancel()` closes the subscriber on supersede, and a
2009
+ * late promise resolution lands on the closed subscriber and is
2010
+ * dropped by RxJS itself.
1524
2011
  *
1525
2012
  * @category common/tabs
2013
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/router-commit.ts
2014
+ * @since 0.1.0
1526
2015
  */
1527
- function withTabOverflowItemTemplate(template) {
1528
- return defineTabsConfigFeature((cfg) => ({
1529
- ...cfg,
1530
- templates: { ...cfg.templates, overflowItem: template },
1531
- }));
2016
+ function createTabRouterCommit(opts) {
2017
+ const routeFor = opts.routeFor ?? cngxDefaultTabRoute;
2018
+ return (_fromIndex, toIndex) => new Observable((subscriber) => {
2019
+ const target = opts.tabs()[toIndex];
2020
+ if (!target) {
2021
+ subscriber.next(false);
2022
+ subscriber.complete();
2023
+ return;
2024
+ }
2025
+ // Resolve from THIS call's promise - correlated by construction.
2026
+ // A take(1) on router.events would grab the first terminal event
2027
+ // of ANY navigation, so a concurrent unrelated navigation could
2028
+ // resolve this commit with a foreign outcome.
2029
+ opts.router.navigate(routeFor(target)).then((result) => {
2030
+ // `false` is a cancelled or superseded navigation. A skipped
2031
+ // same-URL navigation resolves `null` - the tab's route is
2032
+ // already active, which commits.
2033
+ subscriber.next(result !== false);
2034
+ subscriber.complete();
2035
+ }, () => {
2036
+ subscriber.next(false);
2037
+ subscriber.complete();
2038
+ });
2039
+ });
1532
2040
  }
2041
+
1533
2042
  /**
1534
- * App-wide override for the error-badge decoration. Middle tier;
1535
- * per-instance `*cngxTabErrorBadge` still wins. Sibling of the
1536
- * stepper family's `withStepBadgeTemplate`.
2043
+ * Router-outlet integration for tab groups. \
2044
+ * Opt-in via `[cngxTabsRouteSync]` on the presenter element. Each tab is an
2045
+ * Angular child route whose component renders into a `<router-outlet>`;
2046
+ * switching tabs navigates, and a `CanDeactivate` guard can gate the
2047
+ * leave.
1537
2048
  *
1538
- * @category common/tabs
1539
- */
1540
- function withTabErrorBadgeTemplate(template) {
1541
- return defineTabsConfigFeature((cfg) => ({
1542
- ...cfg,
1543
- templates: { ...cfg.templates, errorBadge: template },
1544
- }));
1545
- }
1546
- /**
1547
- * App-wide override for the rejection-icon decoration. Middle
1548
- * tier; \
1549
- * per-instance `*cngxTabRejectionIcon` still wins. Sibling
1550
- * of {@link withStepRejectionTemplate}.
2049
+ * Supplies the presenter's commit-action through the
2050
+ * {@link CNGX_TABS_COMMIT_ACTION} DI fallback (no consumer
2051
+ * `[commitAction]` hand-binding) and pins **pessimistic** mode so the
2052
+ * active tab follows the *resolved* route - a guard-cancelled switch
2053
+ * keeps the old tab. The routing gate reuses the presenter's commit
2054
+ * lifecycle verbatim; the router navigation is the async op.
1551
2055
  *
1552
- * @category common/tabs
1553
- */
1554
- function withTabRejectionIconTemplate(template) {
1555
- return defineTabsConfigFeature((cfg) => ({
1556
- ...cfg,
1557
- templates: { ...cfg.templates, rejectionIcon: template },
1558
- }));
1559
- }
1560
- /**
1561
- * App-wide override for the commit-pending busy-spinner overlay.
1562
- * Middle tier; per-instance `*cngxTabBusySpinner` still wins.
1563
- * Sibling of {@link withStepBusySpinnerTemplate}.
2056
+ * Seeds the active tab from the current URL at content-init - before
2057
+ * the group renders its panels, so a deep link under
2058
+ * `panelMode="lazy"` mounts only the target panel - and reflects
2059
+ * external navigations (back/forward, direct URL) into `activeIndex`
2060
+ * *without* re-navigating - those writes bypass the commit-action,
2061
+ * since the router is already at the resolved route.
1564
2062
  *
1565
- * @category common/tabs
1566
- */
1567
- function withTabBusySpinnerTemplate(template) {
1568
- return defineTabsConfigFeature((cfg) => ({
1569
- ...cfg,
1570
- templates: { ...cfg.templates, busySpinner: template },
1571
- }));
1572
- }
1573
- /**
1574
- * App-wide override for the tab-icon slot. Middle tier of the 3-stage
1575
- * cascade; per-instance `*cngxTabIcon` still wins. Sibling of
1576
- * {@link withStepIndicatorTemplate}.
2063
+ * **Two URL-matching modes, defaulted from the host flavour.** On a
2064
+ * `<cngx-tab-group>` tablist each tab is a *leaf* route, so the default
2065
+ * is `'suffix'`: a tab owns the trailing segment(s) of the URL and
2066
+ * nothing else. On a `<cngx-tab-nav>` (or `[cngxMatTabNav]`) each link is
2067
+ * an application *section* that owns a whole subtree, so the default
2068
+ * flips to `'prefix'` and the section stays current for every URL beneath
2069
+ * it - the non-exact flavour of `routerLinkActive`. The flavour is read
2070
+ * from the {@link CNGX_TAB_NAV_HOST} marker the nav organisms provide, so
2071
+ * neither default needs a consumer flag; `[match]` overrides both for the
2072
+ * mixed case.
1577
2073
  *
1578
- * @category common/tabs
1579
- */
1580
- function withTabIconTemplate(template) {
1581
- return defineTabsConfigFeature((cfg) => ({
1582
- ...cfg,
1583
- templates: { ...cfg.templates, icon: template },
1584
- }));
1585
- }
1586
- /**
1587
- * App-wide override for a tab's close-button glyph. Middle tier;
1588
- * per-instance `*cngxTabCloseIcon` still wins.
2074
+ * `Router` is optional - without it the directive logs a single dev
2075
+ * warning via `afterNextRender`, exposes a null action, and becomes a
2076
+ * no-op. Mirrors {@link CngxTabsFragmentSync}; every `activeIndex`
2077
+ * write inside an effect sits in `untracked()`.
1589
2078
  *
1590
- * @category common/tabs
1591
- */
1592
- function withTabCloseIconTemplate(template) {
1593
- return defineTabsConfigFeature((cfg) => ({
1594
- ...cfg,
1595
- templates: { ...cfg.templates, closeIcon: template },
1596
- }));
1597
- }
1598
- /**
1599
- * App-wide override for the add-tab button glyph. Middle tier;
1600
- * per-instance `*cngxTabAddIcon` still wins.
2079
+ * **The mental model.** It turns the tab group into the router's view
2080
+ * switcher: the tabs choose *which child route* renders in the
2081
+ * `<router-outlet>`, not which inline template shows. \
2082
+ * Concretely, a Settings page with Profile / Security / Billing tabs then gets, for
2083
+ * free: each tab its own URL (`/settings/profile`) so a refresh or a
2084
+ * shared link stays on the tab; browser back/forward between tabs;
2085
+ * `Billing` lazy-loading its chunk only when first opened; and `Profile`
2086
+ * blocking the switch via a `CanDeactivate` guard while its form is
2087
+ * dirty - all while keeping the `role="tab"` keyboard and ARIA model.
1601
2088
  *
1602
- * @category common/tabs
1603
- */
1604
- function withTabAddIconTemplate(template) {
1605
- return defineTabsConfigFeature((cfg) => ({
1606
- ...cfg,
1607
- templates: { ...cfg.templates, addIcon: template },
1608
- }));
1609
- }
1610
- function resolveFeatures(features) {
1611
- return features.reduce((cfg, feat) => feat(cfg), TABS_CONFIG_DEFAULTS);
1612
- }
1613
- /**
1614
- * Root-level provider. Apply once in `bootstrapApplication` /
1615
- * `appConfig.providers`. Returns {@link EnvironmentProviders} per
1616
- * the canonical cngx config-cascade signature.
2089
+ * **Use it when** each tab's content is a real Angular route - a lazy
2090
+ * chunk, a resolver, or a `CanActivate` / `CanDeactivate` guard -
2091
+ * rendered into a `<router-outlet>`, and you want browser back/forward
2092
+ * and deep links to move between tabs while the route's own guard gates
2093
+ * the switch (e.g. an unsaved-changes prompt on leave). \
2094
+ * If the tabs are purely visual, use a plain `<cngx-tab-group>` with no sync directive;
2095
+ * if you only want the active tab reflected in the URL while content
2096
+ * stays inline, use {@link CngxTabsFragmentSync}.
1617
2097
  *
1618
- * @category common/tabs
1619
- */
1620
- function provideTabsConfig(...features) {
1621
- return makeEnvironmentProviders([
1622
- { provide: CNGX_TABS_CONFIG, useValue: resolveFeatures(features) },
1623
- ]);
1624
- }
1625
- /**
1626
- * Component-scoped override. Returns `Provider[]` (not
1627
- * {@link EnvironmentProviders}) because `viewProviders` rejects
1628
- * opaque environment providers. Resolution priority: per-instance
1629
- * Input > viewProviders (`At`) > root > default.
2098
+ * **What this is not.** \
2099
+ * Not a per-tab `routerLink`: \
2100
+ * the tabs stay `role="tab"` buttons and the directive drives `router.navigate`
2101
+ * centrally through the commit lifecycle, so there are no anchors, no
2102
+ * `href`, and no native open-in-new-tab / middle-click / copy-link. \
2103
+ * For real link semantics (right-click, ctrl-click) reach for the CNGX
2104
+ * `<cngx-tab-nav>` and `<a cngx-tab-link routerLink>` variant
2105
+ * instead. \
2106
+ * Not URL deep-linking either - that is {@link CngxTabsFragmentSync} (a `#tab=` fragment or `?tab=`
2107
+ * query-param); this directive renders child route *components* into a
2108
+ * `<router-outlet>`. \
2109
+ * And not optimistic: the active tab moves only once
2110
+ * the route resolves, so a `CanDeactivate` guard can cancel the switch.
1630
2111
  *
1631
2112
  * ```ts
1632
- * @Component({
1633
- * viewProviders: [...provideTabsConfigAt(withTabsDefaultOrientation('vertical'))],
1634
- * })
2113
+ * // Each tab is a child route; the editor guards its own exit.
2114
+ * const ROUTES: Routes = [
2115
+ * { path: '', pathMatch: 'full', redirectTo: 'editor' },
2116
+ * { path: 'editor', component: EditorPage, canDeactivate: [unsavedChangesGuard] },
2117
+ * { path: 'preview', component: PreviewPage },
2118
+ * { path: 'settings', component: SettingsPage },
2119
+ * ];
1635
2120
  * ```
1636
2121
  *
1637
- * @category common/tabs
1638
- */
1639
- function provideTabsConfigAt(...features) {
1640
- return [{ provide: CNGX_TABS_CONFIG, useValue: resolveFeatures(features) }];
1641
- }
1642
- /**
1643
- * Inject the resolved tabs config in an injection context.
2122
+ * ```html
2123
+ * <!-- Tab ids match the child segments (default routeFor = (h) => [h.id]).
2124
+ * Switching a tab navigates; the guard gates leaving the editor;
2125
+ * back/forward and /account/settings deep links move the active tab. -->
2126
+ * <cngx-tab-group cngxTabsRouteSync aria-label="Account">
2127
+ * <div cngxTab id="editor" label="Editor"></div>
2128
+ * <div cngxTab id="preview" label="Preview"></div>
2129
+ * <div cngxTab id="settings" label="Settings"></div>
2130
+ * </cngx-tab-group>
2131
+ *
2132
+ * <!-- The active tab's routed component renders here. -->
2133
+ * <router-outlet></router-outlet>
2134
+ * ```
1644
2135
  *
1645
2136
  * @category common/tabs
2137
+ * @docsKind primary
2138
+ * @wcag AA
2139
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/route-sync.directive.ts
2140
+ * @since 0.1.0
2141
+ * @relatedTo CngxTabGroupPresenter, CngxTabsFragmentSync, createTabRouterCommit, CngxTabNav, CngxTabLink
1646
2142
  */
1647
- function injectTabsConfig() {
1648
- return inject(CNGX_TABS_CONFIG);
2143
+ class CngxTabsRouteSync {
2144
+ /**
2145
+ * Maps a tab handle to its router command array. Default
2146
+ * `(handle) => [handle.id]` - the tab id is the child segment.
2147
+ * Override for real route paths.
2148
+ */
2149
+ routeFor = input(cngxDefaultTabRoute, ...(ngDevMode ? [{ debugName: "routeFor" }] : /* istanbul ignore next */ []));
2150
+ /**
2151
+ * How a tab's route is matched against the current URL.
2152
+ *
2153
+ * - `'suffix'` - the tab owns the trailing segment(s). A leaf tab in a
2154
+ * tablist: `/settings/billing` activates the `billing` tab, and
2155
+ * `/billing/invoices/42` activates nothing.
2156
+ * - `'prefix'` - the tab owns a subtree. A section link in a nav:
2157
+ * `/rounds/explorer` activates the `rounds` link. Matching is a
2158
+ * `UrlTree` subset test anchored at the host's own `ActivatedRoute`,
2159
+ * so a nav mounted under a base path still resolves. When several
2160
+ * tabs match, the one with the most path segments wins.
2161
+ *
2162
+ * Cascade: this input -> `CngxTabsConfig.routeMatch`
2163
+ * ({@link withTabsRouteMatch}) -> the host flavour, which is `'prefix'`
2164
+ * when {@link CNGX_TAB_NAV_HOST} is present and `'suffix'` otherwise.
2165
+ *
2166
+ * This picks *which* policy runs. {@link CNGX_TAB_URL_MATCH_STRATEGY}
2167
+ * replaces the policies themselves.
2168
+ */
2169
+ match = input(undefined, ...(ngDevMode ? [{ debugName: "match" }] : /* istanbul ignore next */ []));
2170
+ host = inject(CNGX_TAB_GROUP_HOST, { host: true });
2171
+ router = inject(Router, { optional: true });
2172
+ navHost = inject(CNGX_TAB_NAV_HOST, { optional: true, host: true });
2173
+ config = injectTabsConfig();
2174
+ urlMatch = inject(CNGX_TAB_URL_MATCH_STRATEGY);
2175
+ /** Resolved match mode: input -> config -> host flavour. */
2176
+ effectiveMatch = computed(() => this.match() ?? this.config.routeMatch ?? (this.navHost ? 'prefix' : 'suffix'), ...(ngDevMode ? [{ debugName: "effectiveMatch" }] : /* istanbul ignore next */ []));
2177
+ activatedRoute = inject(ActivatedRoute, { optional: true });
2178
+ /**
2179
+ * Pessimistic-only - not exposed as an input. The route-sync owns the
2180
+ * mode so optimistic (show-then-revert) can never flash the target
2181
+ * tab before a `CanDeactivate` guard decides.
2182
+ */
2183
+ mode = signal('pessimistic', ...(ngDevMode ? [{ debugName: "mode" }] : /* istanbul ignore next */ []));
2184
+ /**
2185
+ * Router commit-action read by the presenter via the DI fallback.
2186
+ * `null` when no `Router` is available (graceful no-op). Rebuilt only
2187
+ * when `routeFor` changes; the navigation gate itself is the async
2188
+ * op inside the action.
2189
+ */
2190
+ action = computed(() => {
2191
+ const router = this.router;
2192
+ if (!router) {
2193
+ return null;
2194
+ }
2195
+ return createTabRouterCommit({
2196
+ router,
2197
+ tabs: this.host.tabs,
2198
+ routeFor: this.routeFor(),
2199
+ });
2200
+ }, ...(ngDevMode ? [{ debugName: "action" }] : /* istanbul ignore next */ []));
2201
+ constructor() {
2202
+ if (!this.router) {
2203
+ afterNextRender(() => warnTabsRouterAbsent('CngxTabsRouteSync', 'routed tabs'));
2204
+ return;
2205
+ }
2206
+ const router = this.router;
2207
+ const destroyRef = inject(DestroyRef);
2208
+ // Fallback seed for tabs that register after content-init (a
2209
+ // dynamic @for over an async list). Idempotent against the
2210
+ // content-init seed: reflectFromUrl bails when the id already
2211
+ // matches.
2212
+ afterNextRender(() => {
2213
+ untracked(() => this.reflectFromUrl(router));
2214
+ });
2215
+ const navEnd = toSignal(router.events.pipe(filter((e) => e instanceof NavigationEnd), takeUntilDestroyed(destroyRef)), { initialValue: null });
2216
+ effect(() => {
2217
+ const e = navEnd();
2218
+ if (!e) {
2219
+ return;
2220
+ }
2221
+ untracked(() => this.reflectFromUrl(router));
2222
+ });
2223
+ }
2224
+ /**
2225
+ * Seed from the URL before the group renders its panels. `CngxTab`
2226
+ * registers in `ngOnInit`, so the registry is populated by the time
2227
+ * this runs, and the group's own view has not rendered yet - which is
2228
+ * what keeps `panelMode="lazy"` from counting the default tab's first
2229
+ * render as its first activation on a deep link.
2230
+ *
2231
+ * Its own router guard: the constructor's early return does not stop
2232
+ * lifecycle hooks from running.
2233
+ */
2234
+ ngAfterContentInit() {
2235
+ if (!this.router) {
2236
+ return;
2237
+ }
2238
+ const router = this.router;
2239
+ untracked(() => this.reflectFromUrl(router));
2240
+ }
2241
+ /**
2242
+ * Mirror the URL's active tab onto `activeIndex` without navigating.
2243
+ * Writing the index directly (not via `select()`) is the re-entry
2244
+ * guard: `select()` would re-run the commit-action and navigate to
2245
+ * the route the router is already on, leaving the commit pending
2246
+ * forever.
2247
+ */
2248
+ reflectFromUrl(router) {
2249
+ const next = this.readActiveId(router);
2250
+ if (!next || next === this.host.activeId()) {
2251
+ return;
2252
+ }
2253
+ const index = this.host.tabs().findIndex((t) => t.id === next);
2254
+ if (index >= 0) {
2255
+ this.host.activeIndex.set(index);
2256
+ }
2257
+ }
2258
+ /**
2259
+ * Resolve the active tab id through the swappable match strategy.
2260
+ * The directive owns the mode cascade (input -> config -> host
2261
+ * flavour); the strategy owns the comparison.
2262
+ */
2263
+ readActiveId(router) {
2264
+ return this.urlMatch.resolve({
2265
+ router,
2266
+ activatedRoute: this.activatedRoute,
2267
+ tabs: this.host.tabs(),
2268
+ routeFor: this.routeFor(),
2269
+ mode: this.effectiveMatch(),
2270
+ });
2271
+ }
2272
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabsRouteSync, deps: [], target: i0.ɵɵFactoryTarget.Directive });
2273
+ 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 }, match: { classPropertyName: "match", publicName: "match", isSignal: true, isRequired: false, transformFunction: null } }, providers: [{ provide: CNGX_TABS_COMMIT_ACTION, useExisting: CngxTabsRouteSync }], exportAs: ["cngxTabsRouteSync"], ngImport: i0 });
1649
2274
  }
2275
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxTabsRouteSync, decorators: [{
2276
+ type: Directive,
2277
+ args: [{
2278
+ selector: '[cngxTabsRouteSync]',
2279
+ exportAs: 'cngxTabsRouteSync',
2280
+ standalone: true,
2281
+ providers: [{ provide: CNGX_TABS_COMMIT_ACTION, useExisting: CngxTabsRouteSync }],
2282
+ }]
2283
+ }], ctorParameters: () => [], propDecorators: { routeFor: [{ type: i0.Input, args: [{ isSignal: true, alias: "routeFor", required: false }] }], match: [{ type: i0.Input, args: [{ isSignal: true, alias: "match", required: false }] }] } });
1650
2284
 
1651
2285
  /**
1652
2286
  * Helper resolving the host-attribute cascades for
@@ -1672,87 +2306,6 @@ function createTabsHostAttrs(inputs) {
1672
2306
  };
1673
2307
  }
1674
2308
 
1675
- const TABS_I18N_DEFAULTS = {
1676
- tabsLabel: 'Tabs',
1677
- selectedTab: (label, position, count) => `Tab ${position} of ${count}: ${label}`,
1678
- tabLabelWithDetail: (label, detail) => `${label}, ${detail}`,
1679
- tabHasErrors: (count) => `${count} error${count === 1 ? '' : 's'}`,
1680
- moreTabsLabel: (count) => `${count} more`,
1681
- previousTab: 'Previous tab',
1682
- nextTab: 'Next tab',
1683
- closeTab: (label) => `Close "${label}"`,
1684
- addTab: 'Add tab',
1685
- commitFailedRetry: 'Tab change refused — retry?',
1686
- commitInFlight: 'Switching tab…',
1687
- commitRolledBackTo: (originLabel) => `Could not save changes — reverted to "${originLabel}".`,
1688
- };
1689
- /**
1690
- * DI token for the tabs i18n bundle. `providedIn: 'root'` with
1691
- * English defaults.
1692
- *
1693
- * @category common/tabs/i18n
1694
- * @wcag AA
1695
- * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/i18n/tabs-i18n.ts
1696
- * @since 0.1.0
1697
- */
1698
- const CNGX_TABS_I18N = new InjectionToken('CngxTabsI18n', {
1699
- providedIn: 'root',
1700
- factory: () => TABS_I18N_DEFAULTS,
1701
- });
1702
- /**
1703
- * Brands an i18n-mutator with the `_target` discriminator.
1704
- *
1705
- * @internal
1706
- */
1707
- function defineTabsI18nFeature(fn) {
1708
- return Object.assign(fn, { _target: 'i18n' });
1709
- }
1710
- /**
1711
- * Override i18n labels via a partial bundle - unset keys keep the
1712
- * English default. Same shape as `withTabsAriaLabels` /
1713
- * `withTabsFallbackLabels` so `provideCngxTabs` composes both
1714
- * surfaces uniformly.
1715
- *
1716
- * @category common/tabs/i18n
1717
- */
1718
- function withTabsI18nLabels(overrides) {
1719
- return defineTabsI18nFeature((bundle) => ({ ...bundle, ...overrides }));
1720
- }
1721
- function resolveI18nFeatures(features) {
1722
- return features.reduce((bundle, feat) => feat(bundle), TABS_I18N_DEFAULTS);
1723
- }
1724
- /**
1725
- * Provider for the tabs i18n bundle. Compose `withTabsI18nLabels(...)`
1726
- * (and future i18n `with*` features); unset keys fall back to the
1727
- * English default.
1728
- *
1729
- * ```ts
1730
- * bootstrapApplication(AppComponent, {
1731
- * providers: [
1732
- * provideTabsI18n(
1733
- * withTabsI18nLabels({ tabsLabel: 'Reiter', previousTab: 'Vorheriger' }),
1734
- * ),
1735
- * ],
1736
- * });
1737
- * ```
1738
- *
1739
- * @category common/tabs/i18n
1740
- */
1741
- function provideTabsI18n(...features) {
1742
- return {
1743
- provide: CNGX_TABS_I18N,
1744
- useValue: resolveI18nFeatures(features),
1745
- };
1746
- }
1747
- /**
1748
- * Inject the resolved tabs i18n bundle.
1749
- *
1750
- * @category common/tabs/i18n
1751
- */
1752
- function injectTabsI18n() {
1753
- return inject(CNGX_TABS_I18N);
1754
- }
1755
-
1756
2309
  function partitionFeatures(features) {
1757
2310
  const config = [];
1758
2311
  const i18n = [];
@@ -1765,7 +2318,7 @@ function partitionFeatures(features) {
1765
2318
  config.push(feat);
1766
2319
  continue;
1767
2320
  }
1768
- // Unbranded feature — runtime escape from the `_target` type.
2321
+ // Unbranded feature - runtime escape from the `_target` type.
1769
2322
  // Drop with dev-warn so an i18n-shaped override never lands
1770
2323
  // silently in `CNGX_TABS_CONFIG`.
1771
2324
  if (isDevMode()) {
@@ -1785,7 +2338,7 @@ function partitionFeatures(features) {
1785
2338
  * - `provideCngxSelect`;
1786
2339
  * apply once in the app providers array. \
1787
2340
  * Returns {@link EnvironmentProviders}; for
1788
- * - `viewProviders` use {@link provideCngxTabsAt} — opaque
2341
+ * - `viewProviders` use {@link provideCngxTabsAt} - opaque
1789
2342
  * - `EnvironmentProviders` cannot live there.
1790
2343
  *
1791
2344
  * ```ts
@@ -1837,7 +2390,9 @@ function provideCngxTabs(...features) {
1837
2390
  function provideCngxTabsAt(...features) {
1838
2391
  const { config, i18n } = partitionFeatures(features);
1839
2392
  return [
1840
- ...provideTabsConfigAt(...config),
2393
+ // Gate like i18n: an i18n-only call must not plant an empty config
2394
+ // at this injector level and shadow an app-wide provideTabsConfig.
2395
+ ...(config.length > 0 ? provideTabsConfigAt(...config) : []),
1841
2396
  ...(i18n.length > 0 ? [provideTabsI18n(...i18n)] : []),
1842
2397
  ];
1843
2398
  }
@@ -2309,33 +2864,107 @@ function createTabDismissals(opts) {
2309
2864
  const resolvedAddable = computed(() => opts.addable() ?? opts.config.addable ?? false, ...(ngDevMode ? [{ debugName: "resolvedAddable" }] : /* istanbul ignore next */ []));
2310
2865
  const closeIconContextCache = new WeakMap();
2311
2866
  const isTabClosable = (tab) => tab.closable() ?? resolvedClosable();
2867
+ // 1-based position per tab id, derived once per tab list, so a close-button
2868
+ // label never scans the strip.
2869
+ const tabIds = computed(() => opts.host.tabs().map((tab) => tab.id), { ...(ngDevMode ? { debugName: "tabIds" } : /* istanbul ignore next */ {}), equal: arrayEqual });
2870
+ const positionById = computed(() => new Map(tabIds().map((id, index) => [id, index + 1])), ...(ngDevMode ? [{ debugName: "positionById" }] : /* istanbul ignore next */ []));
2871
+ // The close request only ASKS the consumer to remove the tab - the
2872
+ // removal may land asynchronously (or never). Focus restore and the
2873
+ // closed announcement key on a requested id actually leaving the
2874
+ // registry, not on the next render after the request. Requests enter
2875
+ // via handleClose (the only writer); landed ids are pruned on the
2876
+ // next request, so the map stays interaction-bounded.
2877
+ const pendingCloseLabels = signal(new Map(), ...(ngDevMode ? [{ debugName: "pendingCloseLabels" }] : /* istanbul ignore next */ []));
2878
+ // Landed-close phrase, purely derived from the registry transition:
2879
+ // an id that was present in the previous registry emission, carries a
2880
+ // pending close request, and is gone from the current one has landed.
2881
+ // `prev.source` supplies the departed handle (and its label) without
2882
+ // a managed side-slot.
2883
+ const closedAnnouncement = linkedSignal({ ...(ngDevMode ? { debugName: "closedAnnouncement" } : /* istanbul ignore next */ {}), source: () => opts.host.tabs(),
2884
+ computation: (tabs, prev) => {
2885
+ if (prev === undefined) {
2886
+ return '';
2887
+ }
2888
+ const pending = pendingCloseLabels();
2889
+ const currentIds = new Set(tabs.map((tab) => tab.id));
2890
+ const landed = prev.source.find((tab) => !currentIds.has(tab.id) && pending.has(tab.id));
2891
+ if (landed === undefined) {
2892
+ return prev.value;
2893
+ }
2894
+ // Feeds the live region: copy is read untracked so a language
2895
+ // switch does not re-announce the last close.
2896
+ const label = pending.get(landed.id) ?? '';
2897
+ return untracked(() => opts.i18n().closedTab(label));
2898
+ } });
2899
+ const restoreFocus = () => {
2900
+ // Skin-agnostic lookup: `[role="tab"]` + `data-tab-id` are the
2901
+ // ARIA/data contract every skin must honour (mirrors the keyboard
2902
+ // nav's focus targeting); class names are skin-owned and a rename
2903
+ // must not silently break focus restoration.
2904
+ const activeId = opts.host.activeId();
2905
+ const active = activeId === null
2906
+ ? null
2907
+ : (Array.from(opts.hostElement.querySelectorAll('[role="tab"]')).find((button) => button.getAttribute('data-tab-id') === activeId) ?? null);
2908
+ const add = opts.hostElement.querySelector('[data-tab-add]');
2909
+ const target = active ?? add;
2910
+ if (target) {
2911
+ target.focus();
2912
+ return;
2913
+ }
2914
+ opts.hostElement.tabIndex = -1;
2915
+ opts.hostElement.focus();
2916
+ };
2917
+ // Pure side effect - no signal writes. The once-per-landing guard is
2918
+ // plain imperative bookkeeping, not reactive state.
2919
+ const focusRestoredIds = new Set();
2920
+ effect(() => {
2921
+ const tabs = opts.host.tabs();
2922
+ const pending = pendingCloseLabels();
2923
+ untracked(() => {
2924
+ const landed = [...pending.keys()].filter((id) => !tabs.some((tab) => tab.id === id) && !focusRestoredIds.has(id));
2925
+ if (landed.length === 0) {
2926
+ return;
2927
+ }
2928
+ for (const id of landed) {
2929
+ focusRestoredIds.add(id);
2930
+ }
2931
+ // Restore focus once the removal has rendered: the new active
2932
+ // tab, then the add button, and finally the group element itself
2933
+ // (made programmatically focusable) so focus never falls to
2934
+ // `<body>` when the strip empties with no add button (APG).
2935
+ afterNextRender(restoreFocus, { injector: opts.injector });
2936
+ });
2937
+ }, { injector: opts.injector });
2312
2938
  const handleClose = (tab, event) => {
2313
2939
  event?.stopPropagation();
2314
2940
  if (!isTabClosable(tab)) {
2315
2941
  return;
2316
2942
  }
2943
+ pendingCloseLabels.update((current) => {
2944
+ const next = new Map(
2945
+ // Prune requests that already landed - keeps the map bounded and
2946
+ // stops a later consumer-driven removal of a RE-ADDED same id
2947
+ // from reading as a close.
2948
+ [...current].filter(([id]) => opts.host.tabs().some((tab2) => tab2.id === id)));
2949
+ next.set(tab.id, tab.label() ?? '');
2950
+ focusRestoredIds.delete(tab.id);
2951
+ return next;
2952
+ });
2317
2953
  opts.host.requestClose(tab.id);
2318
- // Restore focus once the consumer's removal has rendered: the new
2319
- // active tab, then the add button, and finally the group element
2320
- // itself (made programmatically focusable) so focus never falls to
2321
- // `<body>` when the strip empties with no add button (APG).
2322
- afterNextRender(() => {
2323
- const active = opts.hostElement.querySelector('.cngx-tabs__tab[aria-selected="true"]');
2324
- const add = opts.hostElement.querySelector('.cngx-tabs__add');
2325
- const target = active ?? add;
2326
- if (target) {
2327
- target.focus();
2328
- return;
2329
- }
2330
- opts.hostElement.tabIndex = -1;
2331
- opts.hostElement.focus();
2332
- }, { injector: opts.injector });
2333
2954
  };
2334
2955
  return {
2335
2956
  resolvedClosable,
2336
2957
  resolvedAddable,
2337
2958
  isTabClosable,
2338
- closeButtonLabel: (tab) => opts.i18n.closeTab(tab.label() ?? ''),
2959
+ // An unlabelled tab is named by position, never as `Close ""`.
2960
+ closeButtonLabel: (tab) => {
2961
+ const i18n = opts.i18n();
2962
+ const label = tab.label() ?? '';
2963
+ if (label !== '') {
2964
+ return i18n.closeTab(label);
2965
+ }
2966
+ return i18n.closeTab(i18n.unlabeledTab(positionById().get(tab.id) ?? 0));
2967
+ },
2339
2968
  closeIconContextFor: (tab) => {
2340
2969
  let ctx = closeIconContextCache.get(tab);
2341
2970
  if (!ctx) {
@@ -2344,6 +2973,7 @@ function createTabDismissals(opts) {
2344
2973
  }
2345
2974
  return ctx;
2346
2975
  },
2976
+ closedAnnouncement: closedAnnouncement.asReadonly(),
2347
2977
  handleClose,
2348
2978
  handleTabKeydown: (tab, event) => {
2349
2979
  if (event.key === 'Delete' && isTabClosable(tab)) {
@@ -2446,17 +3076,50 @@ function createTabKeyboardNav(opts) {
2446
3076
  const buttons = Array.from(opts.hostElement.querySelectorAll('[role="tab"]'));
2447
3077
  buttons.find((button) => button.getAttribute('data-tab-id') === id)?.focus();
2448
3078
  };
3079
+ if (opts.injector) {
3080
+ effect(() => {
3081
+ if (opts.host.commitTransition.current() !== 'error') {
3082
+ return;
3083
+ }
3084
+ untracked(() => {
3085
+ // Only release focus that this tablist is actually holding on a
3086
+ // non-active tab button - never steal focus from elsewhere.
3087
+ const focused = document.activeElement;
3088
+ if (!(focused instanceof HTMLElement) || !opts.hostElement.contains(focused)) {
3089
+ return;
3090
+ }
3091
+ if (focused.getAttribute('role') !== 'tab') {
3092
+ return;
3093
+ }
3094
+ const activeId = opts.host.activeId();
3095
+ if (activeId === null || focused.getAttribute('data-tab-id') === activeId) {
3096
+ return;
3097
+ }
3098
+ const idx = opts.host.tabs().findIndex((tab) => tab.id === activeId);
3099
+ if (idx >= 0) {
3100
+ focusTabAt(idx);
3101
+ }
3102
+ });
3103
+ }, { injector: opts.injector });
3104
+ }
2449
3105
  return {
2450
3106
  tabTabindex: (tab) => (tab.id === opts.host.activeId() ? 0 : -1),
2451
3107
  handleKeydown: (event) => {
2452
3108
  const horizontal = opts.host.orientation() === 'horizontal';
3109
+ const inlineStep = (key) => {
3110
+ if (!horizontal) {
3111
+ return null;
3112
+ }
3113
+ const dir = resolveInlineStep(key, opts.direction());
3114
+ return dir === null ? null : step(dir);
3115
+ };
2453
3116
  let target;
2454
3117
  switch (event.key) {
2455
3118
  case 'ArrowRight':
2456
- target = horizontal ? step(1) : null;
3119
+ target = inlineStep('ArrowRight');
2457
3120
  break;
2458
3121
  case 'ArrowLeft':
2459
- target = horizontal ? step(-1) : null;
3122
+ target = inlineStep('ArrowLeft');
2460
3123
  break;
2461
3124
  case 'ArrowDown':
2462
3125
  target = horizontal ? null : step(1);
@@ -2497,10 +3160,10 @@ function createTabKeyboardNav(opts) {
2497
3160
  * span for the state decorations, the `CNGX_TABS_GLYPHS` glyph for
2498
3161
  * `closeIcon` / `addIcon`, and nothing for `icon`.
2499
3162
  *
2500
- * Pure — no DI, no side effects. Safe in field-init. Sibling to
3163
+ * Pure - no DI, no side effects. Safe in field-init. Sibling to
2501
3164
  * `createStepperTemplateBindings` and `createTabOverflowTemplateBindings`.
2502
3165
  *
2503
- * Single-consumer today: `[cngxMatTabs]` does not consume this —
3166
+ * Single-consumer today: `[cngxMatTabs]` does not consume this -
2504
3167
  * Material owns the rendered tab-button chrome via its own MDC
2505
3168
  * template, leaving no DOM seam. See `tabs-accepted-debt §9`.
2506
3169
  *
@@ -2531,13 +3194,13 @@ function createTabGroupTemplateBindings(opts) {
2531
3194
  };
2532
3195
  }
2533
3196
 
2534
- // Single-consumer factory — staged under family-uniformity
3197
+ // Single-consumer factory - staged under family-uniformity
2535
3198
  // (`createTabGroupTemplateBindings` and `CngxMatTabAggregatorContent`).
2536
3199
  // Re-eval on second consumer or sibling debt closure.
2537
3200
  /**
2538
3201
  * Pure factory bundling the `<cngx-tab-group>` AT-announcement +
2539
3202
  * descriptor surfaces. Owns one internal `linkedSignal`
2540
- * (prior-active-index, drives the success-arm direction prefix) —
3203
+ * (prior-active-index, drives the success-arm direction prefix) -
2541
3204
  * lazy by `linkedSignal` semantics, so the organism reads
2542
3205
  * `liveAnnouncement` once at construction to seed it.
2543
3206
  *
@@ -2567,39 +3230,66 @@ function createTabGroupTemplateBindings(opts) {
2567
3230
  */
2568
3231
  function createTabGroupAnnouncements(options) {
2569
3232
  const { presenter, i18n, config, ariaLabel, ariaLabelledBy } = options;
2570
- const tabsRoleDescription = computed(() => config.fallbackLabels?.tabRoleDescription ?? 'tab list', ...(ngDevMode ? [{ debugName: "tabsRoleDescription" }] : /* istanbul ignore next */ []));
2571
- const tabPanelRoleDescription = computed(() => config.fallbackLabels?.tabPanelRoleDescription ?? 'tab panel', ...(ngDevMode ? [{ debugName: "tabPanelRoleDescription" }] : /* istanbul ignore next */ []));
3233
+ const closedAnnouncement = options.closedAnnouncement ?? (() => '');
3234
+ const fallbackLabels = coerceSignal(config.fallbackLabels);
3235
+ const defaultFallbackLabels = coerceSignal(TABS_CONFIG_DEFAULTS.fallbackLabels);
3236
+ const ariaLabels = coerceSignal(config.ariaLabels);
3237
+ const tabsRoleDescription = computed(() => fallbackLabels()?.tabRoleDescription ?? defaultFallbackLabels().tabRoleDescription, ...(ngDevMode ? [{ debugName: "tabsRoleDescription" }] : /* istanbul ignore next */ []));
3238
+ const tabPanelRoleDescription = computed(() => fallbackLabels()?.tabPanelRoleDescription ??
3239
+ defaultFallbackLabels().tabPanelRoleDescription, ...(ngDevMode ? [{ debugName: "tabPanelRoleDescription" }] : /* istanbul ignore next */ []));
2572
3240
  const resolvedAriaLabel = computed(() => {
2573
3241
  if (ariaLabelledBy()) {
2574
3242
  return null;
2575
3243
  }
2576
- return ariaLabel() ?? config.ariaLabels?.tabsRegion ?? i18n.tabsLabel;
3244
+ return ariaLabel() ?? ariaLabels()?.tabsRegion ?? i18n().tabsLabel;
2577
3245
  }, ...(ngDevMode ? [{ debugName: "resolvedAriaLabel" }] : /* istanbul ignore next */ []));
2578
- // `prev?.source` = source value before the most recent change —
3246
+ // `prev?.source` = source value before the most recent change -
2579
3247
  // prior activeIndex without an `effect`-driven slot (Pillar 1).
2580
3248
  // Coalesce to current on first emission.
2581
3249
  const priorActiveIndex = linkedSignal({ ...(ngDevMode ? { debugName: "priorActiveIndex" } : /* istanbul ignore next */ {}), source: () => presenter.activeIndex(),
2582
3250
  computation: (curr, prev) => prev?.source ?? curr,
2583
3251
  equal: Object.is });
3252
+ // Close phrase with commit-activity expiry: a NEW phrase (re)arms; a
3253
+ // commit status change while armed spends the phrase, so a later
3254
+ // return to idle re-renders '' instead of re-announcing the stale
3255
+ // close. Mount seeds with the current phrase (never empty-coerced).
3256
+ const closedPhrase = createAnnouncementPhrase({
3257
+ source: () => ({
3258
+ phrase: closedAnnouncement(),
3259
+ status: presenter.commitTransition.current(),
3260
+ }),
3261
+ arm: (curr, prev) => (curr.phrase !== prev.phrase ? curr.phrase : null),
3262
+ spend: (curr, prev) => curr.status !== prev.status,
3263
+ seed: (src) => src.phrase,
3264
+ });
3265
+ // Copy and tab labels (which a consumer may translate) are read untracked
3266
+ // in the live region: a language switch must not re-speak the last phrase;
3267
+ // the next transition speaks the new language.
2584
3268
  const liveAnnouncement = computed(() => {
3269
+ // Read the close phrase EAGERLY: linkedSignal only observes status
3270
+ // snapshots it is actually read under, so a lazy read at the idle
3271
+ // arm would skip the intermediate 'pending' and never spend the
3272
+ // phrase.
3273
+ const closeConfirmation = closedPhrase();
2585
3274
  const current = presenter.commitTransition.current();
2586
3275
  if (current === 'pending') {
2587
- return i18n.commitInFlight;
3276
+ return untracked(() => i18n().commitInFlight);
2588
3277
  }
2589
3278
  if (current === 'error') {
2590
- // No `previous === 'pending'` guard — sync rejections collapse
3279
+ // No `previous === 'pending'` guard - sync rejections collapse
2591
3280
  // pending → error in one flush, so the tracker captures
2592
3281
  // `previous = 'idle'` and an unguarded read keeps the
2593
3282
  // announcement reachable for `commitAction = () => false`.
2594
3283
  const failedIdx = presenter.lastFailedIndex();
2595
3284
  const originIdx = presenter.originIndexDuringCommit();
2596
3285
  if (failedIdx !== undefined && originIdx !== undefined) {
2597
- const originLabel = presenter.tabs()[originIdx]?.label();
3286
+ const origin = presenter.tabs()[originIdx];
3287
+ const originLabel = origin ? untracked(origin.label) : undefined;
2598
3288
  if (originLabel) {
2599
- return i18n.commitRolledBackTo(originLabel);
3289
+ return untracked(() => i18n().commitRolledBackTo(originLabel));
2600
3290
  }
2601
3291
  }
2602
- return i18n.commitFailedRetry;
3292
+ return untracked(() => i18n().commitFailedRetry);
2603
3293
  }
2604
3294
  if (current === 'success') {
2605
3295
  const tabs = presenter.tabs();
@@ -2608,18 +3298,24 @@ function createTabGroupAnnouncements(options) {
2608
3298
  if (!tab) {
2609
3299
  return '';
2610
3300
  }
2611
- const label = tab.label() ?? '';
2612
- const positionPhrase = i18n.selectedTab(label, idx + 1, tabs.length);
3301
+ const label = untracked(tab.label) ?? '';
3302
+ const count = tabs.length;
2613
3303
  const prevIdx = priorActiveIndex();
2614
- if (idx > prevIdx) {
2615
- return `${i18n.nextTab}: ${positionPhrase}`;
2616
- }
2617
- if (idx < prevIdx) {
2618
- return `${i18n.previousTab}: ${positionPhrase}`;
2619
- }
2620
- return positionPhrase;
3304
+ return untracked(() => {
3305
+ const copy = i18n();
3306
+ const positionPhrase = copy.selectedTab(label, idx + 1, count);
3307
+ if (idx > prevIdx) {
3308
+ return copy.nextTab(positionPhrase);
3309
+ }
3310
+ if (idx < prevIdx) {
3311
+ return copy.previousTab(positionPhrase);
3312
+ }
3313
+ return positionPhrase;
3314
+ });
2621
3315
  }
2622
- return '';
3316
+ // Idle: the landed-close confirmation is the only phrase that may
3317
+ // hold the region, and only until the next commit activity.
3318
+ return closeConfirmation;
2623
3319
  }, ...(ngDevMode ? [{ debugName: "liveAnnouncement" }] : /* istanbul ignore next */ []));
2624
3320
  function statusPhrase(tab) {
2625
3321
  if (!tab.hasError()) {
@@ -2634,16 +3330,17 @@ function createTabGroupAnnouncements(options) {
2634
3330
  if (directMessage) {
2635
3331
  return directMessage;
2636
3332
  }
2637
- return i18n.tabHasErrors(aggregator?.errorCount() ?? 1);
3333
+ return i18n().tabHasErrors(aggregator?.errorCount() ?? 1);
2638
3334
  }
2639
3335
  function tabAriaLabel(tab, position) {
2640
3336
  const tabs = presenter.tabs();
2641
3337
  const label = tab.label() ?? '';
2642
3338
  const detail = tab.subLabel();
2643
- const labelPart = detail ? i18n.tabLabelWithDetail(label, detail) : label;
2644
- return i18n.selectedTab(labelPart, position, tabs.length);
3339
+ const copy = i18n();
3340
+ const labelPart = detail ? copy.tabLabelWithDetail(label, detail) : label;
3341
+ return copy.selectedTab(labelPart, position, tabs.length);
2645
3342
  }
2646
- // Eager seed — `linkedSignal` is lazy and the success arm doesn't
3343
+ // Eager seed - `linkedSignal` is lazy and the success arm doesn't
2647
3344
  // touch the tracker at construction (commitTransition is `idle`),
2648
3345
  // so without this read `prev?.source` is undefined on the first
2649
3346
  // nav and the direction prefix is silently lost.
@@ -2658,6 +3355,72 @@ function createTabGroupAnnouncements(options) {
2658
3355
  };
2659
3356
  }
2660
3357
 
3358
+ /**
3359
+ * Live-region content for the link-driven nav flavour: the active link's
3360
+ * accessible label, announced only when the active id actually changes.
3361
+ *
3362
+ * **Why this is not {@link createTabGroupAnnouncements}.** That bundle's
3363
+ * phrasing is built around the commit lifecycle (`pending -> success`,
3364
+ * rollback, direction prefix) and it gates on the commit transition, so
3365
+ * it stays silent at rest for free. The nav path is commit-free by
3366
+ * design: links navigate through their own `routerLink` and nothing calls
3367
+ * `presenter.select()`. Its only meaningful announcement is the landing
3368
+ * label, and it needs a different silence gate.
3369
+ *
3370
+ * **The mount window.** `announcing` stays `false` through the first
3371
+ * render and the microtask after it. On a deep link the active link is
3372
+ * the page's *initial state*, not a change, and the browser already
3373
+ * announces the document; pushing the landing section into a polite
3374
+ * region there is noise. `queueMicrotask` rather than the
3375
+ * `afterNextRender` body: every `afterNextRender` callback for one render
3376
+ * runs in a single synchronous batch, so deferring past it makes the gate
3377
+ * independent of whether a `[cngxTabsRouteSync]` seed registered before
3378
+ * or after this one.
3379
+ *
3380
+ * The prior-id tracker is seeded when that window closes, not at
3381
+ * construction, so whatever the seed resolved counts as the starting
3382
+ * point instead of as the first announcement. Returning to a section
3383
+ * that was active at mount still announces.
3384
+ *
3385
+ * @category common/tabs/announcements
3386
+ * @wcag AA
3387
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/tabs/announcements/tab-nav-announcement.ts
3388
+ * @since 0.1.0
3389
+ * @relatedTo CngxTabNav, CngxLiveRegion, createTabGroupAnnouncements
3390
+ */
3391
+ function createTabNavAnnouncement(options) {
3392
+ const { presenter, injector } = options;
3393
+ const announcing = signal(false, ...(ngDevMode ? [{ debugName: "announcing" }] : /* istanbul ignore next */ []));
3394
+ // `prev?.source` = the id before the most recent change. Mirrors the
3395
+ // tablist bundle's prior-index tracker, keyed on id.
3396
+ const priorActiveId = linkedSignal({ ...(ngDevMode ? { debugName: "priorActiveId" } : /* istanbul ignore next */ {}), source: () => presenter.activeId(),
3397
+ computation: (curr, prev) => prev?.source ?? curr,
3398
+ equal: Object.is });
3399
+ const liveAnnouncement = computed(() => {
3400
+ if (!announcing()) {
3401
+ return '';
3402
+ }
3403
+ const id = presenter.activeId();
3404
+ if (id === null || id === priorActiveId()) {
3405
+ return '';
3406
+ }
3407
+ // The label may be translated by the consumer; read untracked so a
3408
+ // language switch does not re-announce the landing section.
3409
+ const landed = presenter.tabs().find((tab) => tab.id === id);
3410
+ if (!landed) {
3411
+ return '';
3412
+ }
3413
+ return untracked(landed.label) ?? '';
3414
+ }, ...(ngDevMode ? [{ debugName: "liveAnnouncement" }] : /* istanbul ignore next */ []));
3415
+ afterNextRender(() => {
3416
+ queueMicrotask(() => {
3417
+ priorActiveId();
3418
+ announcing.set(true);
3419
+ });
3420
+ }, { injector });
3421
+ return { liveAnnouncement };
3422
+ }
3423
+
2661
3424
  /**
2662
3425
  * Default glyph fallbacks for `<cngx-tab-group>` skin slots. Read by
2663
3426
  * the organism when neither a per-instance slot directive nor
@@ -2704,10 +3467,12 @@ function triggerContextEqual(a, b) {
2704
3467
  return a.count === b.count && a.hiddenTabs === b.hiddenTabs;
2705
3468
  }
2706
3469
  /**
2707
- * Structural equal - same length + per-index `id` and `disabled`.
2708
- * Without this, every IO emission yields fresh
3470
+ * Structural equal - same length + per-index `id`, `label`, and
3471
+ * `disabled`. Without this, every IO emission yields fresh
2709
3472
  * `ActiveDescendantItem[]` references and AD's `resolvedItems`
2710
- * cascade fires for an unchanged visible-tab set.
3473
+ * cascade fires for an unchanged visible-tab set. `label` is compared
3474
+ * because typeahead matches on it - omitting it would leave the
3475
+ * overflow list matching against stale labels after a rename.
2711
3476
  *
2712
3477
  * @internal
2713
3478
  */
@@ -2719,7 +3484,7 @@ function adItemsEqual(a, b) {
2719
3484
  return false;
2720
3485
  }
2721
3486
  for (let i = 0; i < a.length; i++) {
2722
- if (a[i].id !== b[i].id || a[i].disabled !== b[i].disabled) {
3487
+ if (a[i].id !== b[i].id || a[i].label !== b[i].label || a[i].disabled !== b[i].disabled) {
2723
3488
  return false;
2724
3489
  }
2725
3490
  }
@@ -2762,10 +3527,20 @@ function createTabOverflowTemplateBindings(opts) {
2762
3527
  itemContextCache.set(tab, { context, disabled, index });
2763
3528
  return context;
2764
3529
  };
3530
+ // 1-based strip position per tab id, derived once per tab list.
3531
+ const tabIds = computed(() => opts.tabs().map((tab) => tab.id), { ...(ngDevMode ? { debugName: "tabIds" } : /* istanbul ignore next */ {}), equal: arrayEqual });
3532
+ const positionById = computed(() => new Map(tabIds().map((id, index) => [id, index + 1])), ...(ngDevMode ? [{ debugName: "positionById" }] : /* istanbul ignore next */ []));
3533
+ const itemLabel = (tab) => {
3534
+ const label = tab.label() ?? '';
3535
+ if (label !== '') {
3536
+ return label;
3537
+ }
3538
+ return opts.i18n().unlabeledTab(positionById().get(tab.id) ?? 0);
3539
+ };
2765
3540
  const adItems = computed(() => opts.hiddenTabs().map((tab) => ({
2766
3541
  id: tabOverflowOptionId(tab),
2767
3542
  value: tab,
2768
- label: tab.label() ?? tab.id,
3543
+ label: itemLabel(tab),
2769
3544
  disabled: tab.disabled(),
2770
3545
  })), { ...(ngDevMode ? { debugName: "adItems" } : /* istanbul ignore next */ {}), equal: adItemsEqual });
2771
3546
  return {
@@ -2773,6 +3548,7 @@ function createTabOverflowTemplateBindings(opts) {
2773
3548
  itemTemplate,
2774
3549
  triggerContext,
2775
3550
  buildItemContext,
3551
+ itemLabel,
2776
3552
  adItems,
2777
3553
  };
2778
3554
  }
@@ -2987,5 +3763,5 @@ const CNGX_DIRECTIVE_BY_ID_MAP_FACTORY = new InjectionToken('CngxDirectiveByIdMa
2987
3763
  * Generated bundle index. Do not edit.
2988
3764
  */
2989
3765
 
2990
- 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, CngxTabLink, 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 };
3766
+ 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_TABS_LANGUAGE_EN, CNGX_TAB_GROUP_HOST, CNGX_TAB_NAV_HOST, CNGX_TAB_OVERFLOW_DOM_ADAPTER_FACTORY, CNGX_TAB_PANEL_HOST, CNGX_TAB_URL_MATCH_STRATEGY, CngxTab, CngxTabAddIcon, CngxTabBusySpinner, CngxTabCloseIcon, CngxTabContent, CngxTabErrorBadge, CngxTabGroupPresenter, CngxTabIcon, CngxTabLabel, CngxTabLink, CngxTabOverflowItem, CngxTabOverflowTrigger, CngxTabRejectionIcon, CngxTabSubLabel, CngxTabsFragmentSync, CngxTabsRouteSync, createCngxTabOverflowDefaultDomAdapter, createDirectiveByIdMap, createDomAnchorRetry, createOrganismScrollSync, createOverflowPopoverHighlightSync, createTabDismissals, createTabGroupAnnouncements, createTabGroupTemplateBindings, createTabKeyboardNav, createTabNavAnnouncement, createTabOverflowTemplateBindings, createTabRouterCommit, createTabUrlMatch, 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, withTabsLinkAriaCurrent, withTabsPanelMode, withTabsRouteMatch, withTabsRouterSync, withTabsRovingLoop, withTabsSkin };
2991
3767
  //# sourceMappingURL=cngx-common-tabs.mjs.map