@cngx/common 0.1.0-rc.3 → 0.1.0-rc.5

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 (43) hide show
  1. package/audio/README.md +180 -0
  2. package/display/README.md +1 -0
  3. package/fesm2022/cngx-common-a11y.mjs +123 -3
  4. package/fesm2022/cngx-common-a11y.mjs.map +1 -1
  5. package/fesm2022/cngx-common-audio.mjs +1205 -0
  6. package/fesm2022/cngx-common-audio.mjs.map +1 -0
  7. package/fesm2022/cngx-common-card.mjs +8 -8
  8. package/fesm2022/cngx-common-card.mjs.map +1 -1
  9. package/fesm2022/cngx-common-chart.mjs +2 -2
  10. package/fesm2022/cngx-common-chart.mjs.map +1 -1
  11. package/fesm2022/cngx-common-data.mjs +996 -55
  12. package/fesm2022/cngx-common-data.mjs.map +1 -1
  13. package/fesm2022/cngx-common-display.mjs +320 -8
  14. package/fesm2022/cngx-common-display.mjs.map +1 -1
  15. package/fesm2022/cngx-common-interactive.mjs +1633 -80
  16. package/fesm2022/cngx-common-interactive.mjs.map +1 -1
  17. package/fesm2022/cngx-common-layout.mjs +187 -3
  18. package/fesm2022/cngx-common-layout.mjs.map +1 -1
  19. package/fesm2022/cngx-common-popover.mjs +63 -8
  20. package/fesm2022/cngx-common-popover.mjs.map +1 -1
  21. package/fesm2022/cngx-common.mjs +1 -1
  22. package/interactive/README.md +101 -0
  23. package/layout/README.md +39 -1
  24. package/package.json +5 -1
  25. package/theming/components/cngx-accordion.css +147 -0
  26. package/theming/components/cngx-badge.css +6 -0
  27. package/theming/components/cngx-bottom-sheet.css +8 -1
  28. package/theming/components/cngx-breadcrumb.css +108 -0
  29. package/theming/components/cngx-button-toggle.css +6 -0
  30. package/theming/components/cngx-data-grid.css +154 -0
  31. package/theming/components/cngx-dialog.css +4 -0
  32. package/theming/components/cngx-divider.css +4 -0
  33. package/theming/components/cngx-listbox.css +6 -0
  34. package/theming/components/cngx-menu.css +7 -0
  35. package/theming/components/cngx-slider.css +237 -0
  36. package/theming/components/cngx-tooltip.css +6 -0
  37. package/types/cngx-common-a11y.d.ts +67 -2
  38. package/types/cngx-common-audio.d.ts +736 -0
  39. package/types/cngx-common-data.d.ts +632 -22
  40. package/types/cngx-common-display.d.ts +189 -1
  41. package/types/cngx-common-interactive.d.ts +1028 -31
  42. package/types/cngx-common-layout.d.ts +88 -3
  43. package/types/cngx-common-popover.d.ts +25 -4
@@ -0,0 +1,180 @@
1
+ # @cngx/common/audio
2
+
3
+ Signal-first audio-feedback system. A thin directive layer over a small Web Audio adapter: earcons synthesised from `OscillatorNode` (zero audio assets), a single shared `AudioContext` behind the engine, and the `provideCngxAudio(...)` aggregator. It is the fourth sense - audition - alongside the sibling feedback primitives `CngxRipple` (visual), `CngxPressable` (tactile), and `CngxSpeak` (spoken).
4
+
5
+ ## What it is
6
+
7
+ - **`[cngxAudio]`** - an attribute directive that maps DOM events to earcons with the `event:earcon` grammar (`'click:tap'`). No state, no config; drop it on any element.
8
+ - **`injectCngxAudio()`** - a typed handle to the shared engine for programmatic control (`play`, `register`, `setMuted`, `setVolume`) plus reactive `muted` / `volume` / `status` / `lastPlayed` signals.
9
+ - **`provideCngxAudio(...)`** - the app-level configuration aggregator with `with*` features.
10
+ - **Six built-in earcons**, all oscillator-generated: `tap`, `success`, `error`, `warning`, `notification`, `complete`.
11
+
12
+ ## When you reach for it
13
+
14
+ You want a state change to be *heard*, not just seen. Sound is interaction design first (analogous to a ripple) and accessibility reinforcement second - a non-visual channel that confirms an action landed. Typical reasons:
15
+
16
+ - A tactile-feeling click on buttons, toggles, and chips.
17
+ - Confirming an async outcome audibly (a rising chime on save, a low buzz on failure) so the user does not have to watch a spinner.
18
+ - Reinforcing status transitions for users who benefit from a second sensory channel.
19
+ - Branded UI sounds (a "sent" swoosh, a "received" ping) without shipping any `.wav`/`.mp3` weight.
20
+
21
+ You do **not** reach for it for background music, long samples, or spatial audio - it synthesises short earcons, nothing more. For text-to-speech, use `CngxSpeak`; the two compose freely on one element.
22
+
23
+ ## Why it is built this way
24
+
25
+ - **Web Audio, not the Vibration API.** Vibration is effectively dead (Apple never shipped it, Firefox removed it, Chrome restricts it). Web Audio is universal, needs no permission prompt, and both plays and synthesises.
26
+ - **Zero asset weight.** Earcons are oscillator sequences, so the published bundle carries 0 KB of audio. Need real samples? Swap the tone generator (see below) - the engine does not change.
27
+ - **One shared `AudioContext`.** Browsers cap the number of contexts. The engine owns exactly one, lazily created on the first allowed play, shared by every directive on the page through the injected handle.
28
+ - **Autoplay-policy-safe.** Browsers block audio until a user gesture. The engine arms itself on the first `pointerdown` / `keydown` / `touchstart` and resumes the context only then - no console warnings, no failed playback.
29
+ - **Reduced-motion aware.** Sound and motion are both sensory stimulation, so `prefers-reduced-motion: reduce` mutes audio by default. Opt out with `withRespectReducedMotion(false)`.
30
+
31
+ ## Mental model
32
+
33
+ ```
34
+ [cngxAudio] directive ──▶ injectCngxAudio() handle ──▶ shared engine (root)
35
+ │
36
+ ┌───────────────────────────────┼───────────────────────────┐
37
+ ▼ ▼ ▼
38
+ autoplay gate tone generator debouncer
39
+ (arms on first gesture) (OscillatorNode synthesis) (per-name window)
40
+ │
41
+ one AudioContext
42
+ + master gain (volume)
43
+ ```
44
+
45
+ Every `play(name)` runs through one central gate in the engine, so the four mute conditions live in a single place rather than scattered across directives:
46
+
47
+ 1. **`prefers-reduced-motion: reduce`** is active (and `respectReducedMotion` is on).
48
+ 2. The **autoplay gate is not armed** yet (no user gesture has happened).
49
+ 3. The engine is **globally muted** (`engine.muted()`).
50
+ 4. Only for `[cngxAudio]`: the element carries **`[audioDisabled]="true"`** (enforced in the directive, since it is per-element).
51
+
52
+ If none block, the same-name **debouncer** suppresses repeats inside a 100 ms window, then the earcon plays and `lastPlayed` advances.
53
+
54
+ ## Quick start
55
+
56
+ Bind an event to an earcon - the first click both arms audio and plays:
57
+
58
+ ```html
59
+ <button type="button" [cngxAudio]="'click:tap'">Save</button>
60
+ <a [cngxAudio]="'pointerenter:notification, click:complete'">Open</a>
61
+ ```
62
+
63
+ ```ts
64
+ import { CngxAudio } from '@cngx/common/audio';
65
+
66
+ @Component({ imports: [CngxAudio], /* ... */ })
67
+ export class Toolbar {}
68
+ ```
69
+
70
+ The grammar is `event:earcon`, comma-separated. Bindable DOM events: `click`, `focus`, `blur`, `pointerenter`, `pointerleave`, `submit`, `change`, `input`.
71
+
72
+ ### Programmatic control
73
+
74
+ ```ts
75
+ import { injectCngxAudio } from '@cngx/common/audio';
76
+
77
+ @Component({ /* ... */ })
78
+ export class MuteToggle {
79
+ private readonly audio = injectCngxAudio();
80
+ protected readonly muted = this.audio.muted; // Signal<boolean>
81
+
82
+ protected toggle(): void {
83
+ this.audio.setMuted(!this.muted());
84
+ }
85
+ protected save(): void {
86
+ // ... your save logic
87
+ this.audio.play('success');
88
+ }
89
+ }
90
+ ```
91
+
92
+ ### App-level configuration
93
+
94
+ ```ts
95
+ import {
96
+ provideCngxAudio,
97
+ withVolume,
98
+ withMuted,
99
+ withEarcons,
100
+ withRespectReducedMotion,
101
+ withDebounceMs,
102
+ } from '@cngx/common/audio';
103
+
104
+ bootstrapApplication(App, {
105
+ providers: [
106
+ provideCngxAudio(
107
+ withVolume(0.6),
108
+ withDebounceMs(120),
109
+ withEarcons({
110
+ send: { sequence: [{ freq: 880, duration: 60 }, { freq: 1180, duration: 90 }] },
111
+ }),
112
+ ),
113
+ ],
114
+ });
115
+ ```
116
+
117
+ Now `[cngxAudio]="'click:send'"` plays your branded earcon everywhere.
118
+
119
+ ### Runtime registration
120
+
121
+ When earcons are scope-specific (a widget that brings its own sounds), register them on the shared engine at runtime instead of at bootstrap:
122
+
123
+ ```ts
124
+ private readonly audio = injectCngxAudio();
125
+ constructor() {
126
+ this.audio.register('receive', { sequence: [{ freq: 520, duration: 90 }] });
127
+ }
128
+ ```
129
+
130
+ ## Earcon shape
131
+
132
+ An earcon is a sequence of tone steps played back-to-back:
133
+
134
+ ```ts
135
+ interface ToneStep {
136
+ freq: number; // Hz
137
+ duration: number; // ms
138
+ type?: OscillatorType; // 'sine' (default) | 'square' | 'sawtooth' | 'triangle'
139
+ gain?: number; // [0, 1] peak, default 0.2
140
+ delay?: number; // ms of silence before this step
141
+ }
142
+ ```
143
+
144
+ Each tone carries a 5 ms attack and 30 ms release envelope so `start()`/`stop()` never produce an audible click.
145
+
146
+ ## Swapping the synthesis (samples instead of oscillators)
147
+
148
+ The engine and the tone generator are boundary-layer DI factories. To play real audio files instead of oscillators, override the tone-generator factory - the engine, directives, and earcon names stay untouched:
149
+
150
+ ```ts
151
+ import { CNGX_AUDIO_TONE_GENERATOR_FACTORY } from '@cngx/common/audio';
152
+
153
+ providers: [
154
+ { provide: CNGX_AUDIO_TONE_GENERATOR_FACTORY, useValue: mySampleBackedFactory },
155
+ ];
156
+ ```
157
+
158
+ `CNGX_AUDIO_ENGINE_FACTORY` is the matching seam for wrapping the engine with telemetry or audit logging.
159
+
160
+ ## Best practices
161
+
162
+ - **Bind sound to the gesture, not to a lifecycle effect.** `[cngxAudio]="'click:tap'"` is correct; playing inside an `effect()` that reacts to route or data changes fights the autoplay policy and surprises users. For status-driven sound, prefer the Phase 2 `[cngxAudioStatus]` bridge.
163
+ - **Keep earcons short (under ~300 ms total).** Earcons confirm, they do not entertain. Long sequences feel laggy and collide with the debounce window.
164
+ - **Do not mute by removing the directive.** Use `setMuted(true)` or `[audioDisabled]`; the engine keeps one context and one mute state for the whole page.
165
+ - **Respect the user.** Leave `respectReducedMotion` on unless you have a specific reason; expose a mute control somewhere reachable. Audio is opt-out for the user, never a surprise.
166
+ - **Volume is a `[0, 1]` scalar.** `setVolume` clamps; `[audioVolume]` on `[cngxAudio]` scales one element without touching the shared master volume.
167
+ - **Earcon names are English by default.** Register branded/localised names via `withEarcons` or `register`; the built-ins stay English.
168
+ - **One engine per app.** `injectCngxAudio()` returns the shared root instance. Only re-provide it in `viewProviders` if you deliberately want an isolated context for a subtree.
169
+
170
+ ## Testing
171
+
172
+ Audio is unsniffable in headless/jsdom environments, so assert through the engine, never by listening:
173
+
174
+ - Unit tests use `createAudioContextMock()` from `@cngx/testing` - a pure stub with assertable `connect` / `start` / `stop` records; no real `AudioContext` is required.
175
+ - Read `engine.lastPlayed()` to confirm a play was accepted and `engine.status()` for the context lifecycle.
176
+ - End-to-end tests route through the same `lastPlayed()` signal (exposed on `window` under a demo guard) rather than sniffing output.
177
+
178
+ ## Status
179
+
180
+ Phase 1 ships the engine, the `[cngxAudio]` event-mode directive, the six earcons, `injectCngxAudio`, and `provideCngxAudio`. Phase 2 adds the status-bridge (`[cngxAudioStatus]`), zone (`[cngxAudioZone]`), and pitch (`[cngxAudioPitch]`) directives. Chart sonification is a later release. The public API is stable for adoption; the internal factory composition may evolve.
package/display/README.md CHANGED
@@ -7,6 +7,7 @@ Display-only atoms. Icons, avatars, badges, chips, tags, indicators, dividers -
7
7
  You need a primitive visual piece that other components compose:
8
8
 
9
9
  - An avatar that gracefully degrades from photo URL → initials → fallback.
10
+ - A stacked `CngxAvatarGroup` that overlaps avatars and collapses the extras past `[max]` into a `+N` overflow pill, with an `aria-label` summarising the hidden count.
10
11
  - A chip the user can remove (used internally by multi-select, combobox, tag-input, filter-chips - and available to you for the same purpose).
11
12
  - A tag pill that conveys status, category, or count - non-removable, theme-aware.
12
13
  - A checkbox or radio glyph for a custom row design where you want the cngx look but own the selection logic yourself.
@@ -1,6 +1,6 @@
1
1
  import * as i0 from '@angular/core';
2
- import { input, Directive, inject, ElementRef, Injector, DestroyRef, afterNextRender, effect, signal, computed, model, contentChildren, InjectionToken, output } from '@angular/core';
3
- import { DOCUMENT } from '@angular/common';
2
+ import { input, Directive, inject, PLATFORM_ID, Injectable, ElementRef, Injector, DestroyRef, afterNextRender, effect, signal, computed, model, contentChildren, InjectionToken, output } from '@angular/core';
3
+ import { DOCUMENT, isPlatformBrowser } from '@angular/common';
4
4
  import { FocusTrapFactory } from '@angular/cdk/a11y';
5
5
 
6
6
  /**
@@ -132,6 +132,102 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
132
132
  }]
133
133
  }], propDecorators: { politeness: [{ type: i0.Input, args: [{ isSignal: true, alias: "politeness", required: false }] }], atomic: [{ type: i0.Input, args: [{ isSignal: true, alias: "atomic", required: false }] }], relevant: [{ type: i0.Input, args: [{ isSignal: true, alias: "relevant", required: false }] }] } });
134
134
 
135
+ /**
136
+ * Imperative, reusable polite/assertive live-region announcer.
137
+ *
138
+ * The imperative counterpart to {@link CngxLiveRegion}: where the directive
139
+ * decorates an element you render (the content IS the announcement), this
140
+ * service owns a single visually-hidden `aria-live` element appended to
141
+ * `document.body` and exposes an `announce(message)` call for template-less
142
+ * directives and event handlers (e.g. `CngxCopyValue` copy success,
143
+ * `CngxOtpInput` completion).
144
+ *
145
+ * One root element is created lazily on the first announcement and reused for
146
+ * every subsequent call. The text is cleared and re-set on the next macrotask
147
+ * so an identical consecutive message is still re-read by the screen reader.
148
+ *
149
+ * SSR-safe: all DOM access is guarded by `isPlatformBrowser`; on the server
150
+ * `announce()` is a no-op and no element is created.
151
+ *
152
+ * ```typescript
153
+ * const announcer = inject(CngxLiveAnnouncer);
154
+ * announcer.announce('Copied');
155
+ * announcer.announce('Save failed', 'assertive');
156
+ * ```
157
+ *
158
+ * @category common/a11y
159
+ * @docsKind primary
160
+ * @wcag AA
161
+ * @github https://github.com/cngxjs/cngx/blob/main/projects/common/a11y/aria/live-announcer.ts
162
+ * @since 0.1.0
163
+ * @relatedTo CngxLiveRegion
164
+ */
165
+ class CngxLiveAnnouncer {
166
+ doc = inject(DOCUMENT);
167
+ isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
168
+ region = null;
169
+ pending = null;
170
+ /**
171
+ * Announces `message` through the shared live region.
172
+ *
173
+ * @param message Text read by the screen reader.
174
+ * @param politeness `'polite'` (default) queues after the current
175
+ * utterance; `'assertive'` interrupts immediately.
176
+ */
177
+ announce(message, politeness = 'polite') {
178
+ if (!this.isBrowser) {
179
+ return;
180
+ }
181
+ const region = this.ensureRegion();
182
+ region.setAttribute('aria-live', politeness);
183
+ // Clear first, then write on the next macrotask so repeating the same
184
+ // string still registers as a content change for the SR.
185
+ region.textContent = '';
186
+ if (this.pending !== null) {
187
+ clearTimeout(this.pending);
188
+ }
189
+ this.pending = setTimeout(() => {
190
+ region.textContent = message;
191
+ this.pending = null;
192
+ });
193
+ }
194
+ ngOnDestroy() {
195
+ if (this.pending !== null) {
196
+ clearTimeout(this.pending);
197
+ this.pending = null;
198
+ }
199
+ this.region?.remove();
200
+ this.region = null;
201
+ }
202
+ ensureRegion() {
203
+ if (this.region) {
204
+ return this.region;
205
+ }
206
+ const span = this.doc.createElement('span');
207
+ span.setAttribute('aria-live', 'polite');
208
+ span.setAttribute('aria-atomic', 'true');
209
+ span.className = 'cngx-sr-only';
210
+ span.style.position = 'absolute';
211
+ span.style.width = '1px';
212
+ span.style.height = '1px';
213
+ span.style.padding = '0';
214
+ span.style.margin = '-1px';
215
+ span.style.overflow = 'hidden';
216
+ span.style.clip = 'rect(0, 0, 0, 0)';
217
+ span.style.whiteSpace = 'nowrap';
218
+ span.style.border = '0';
219
+ this.doc.body.appendChild(span);
220
+ this.region = span;
221
+ return span;
222
+ }
223
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxLiveAnnouncer, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
224
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxLiveAnnouncer, providedIn: 'root' });
225
+ }
226
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxLiveAnnouncer, decorators: [{
227
+ type: Injectable,
228
+ args: [{ providedIn: 'root' }]
229
+ }] });
230
+
135
231
  /**
136
232
  * Reactive autofocus for dynamically inserted elements.
137
233
  *
@@ -631,6 +727,13 @@ class CngxRovingTabindex {
631
727
  /** Host element for `data-cngx-recycle-index` queries in virtual mode. */
632
728
  hostEl = inject((ElementRef));
633
729
  pendingFocusState = signal(null, ...(ngDevMode ? [{ debugName: "pendingFocusState" }] : /* istanbul ignore next */ []));
730
+ /**
731
+ * Set true just before a navigation key (arrow / Home / End) moves focus to a
732
+ * new item, cleared by {@link consumeNavigationKey}. Transient handshake, not
733
+ * reactive state: consumer groups read it synchronously from the
734
+ * newly-focused leaf's `(focus)` handler.
735
+ */
736
+ navigationKeyInFlight = false;
634
737
  /**
635
738
  * Index of the item that should receive focus but is not currently in the DOM.
636
739
  * Non-null when virtual navigation targets an out-of-range item.
@@ -668,6 +771,19 @@ class CngxRovingTabindex {
668
771
  clearPendingFocus() {
669
772
  this.pendingFocusState.set(null);
670
773
  }
774
+ /**
775
+ * Whether the last focus move was driven by a navigation key, consuming the
776
+ * flag so it reads `true` exactly once. Consumer groups (radio,
777
+ * button-toggle) call this from the newly-focused leaf's `(focus)` handler to
778
+ * decide whether to auto-select. The flag is set before `.focus()`, so it is
779
+ * already `true` when focus lands - this closes the one-press-behind race
780
+ * that a group's own `(keydown)` binding suffered (#135).
781
+ */
782
+ consumeNavigationKey() {
783
+ const inFlight = this.navigationKeyInFlight;
784
+ this.navigationKeyInFlight = false;
785
+ return inFlight;
786
+ }
671
787
  /**
672
788
  * Handles arrow-key, Home, and End navigation within the group.
673
789
  * Prevents default scrolling on arrow keys.
@@ -706,6 +822,10 @@ class CngxRovingTabindex {
706
822
  if (nextIndex !== null && nextIndex !== currentActive) {
707
823
  event.preventDefault();
708
824
  this.activeIndex.set(nextIndex);
825
+ // Expose the navigation intent before focus moves, so the newly-focused
826
+ // leaf's (focus) handler reads an already-set fact instead of racing the
827
+ // group's own late (keydown) binding (#135).
828
+ this.navigationKeyInFlight = true;
709
829
  if (isVirtual) {
710
830
  this.focusVirtualItem(nextIndex);
711
831
  }
@@ -1369,5 +1489,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImpor
1369
1489
  * Generated bundle index. Do not edit.
1370
1490
  */
1371
1491
 
1372
- export { CNGX_AD_ITEM, CNGX_FOCUSABLE_SELECTOR, CngxActiveDescendant, CngxAriaExpanded, CngxAutofocus, CngxFocusRestore, CngxFocusTrap, CngxFocusVisible, CngxLiveRegion, CngxReducedMotion, CngxRovingItem, CngxRovingTabindex };
1492
+ export { CNGX_AD_ITEM, CNGX_FOCUSABLE_SELECTOR, CngxActiveDescendant, CngxAriaExpanded, CngxAutofocus, CngxFocusRestore, CngxFocusTrap, CngxFocusVisible, CngxLiveAnnouncer, CngxLiveRegion, CngxReducedMotion, CngxRovingItem, CngxRovingTabindex };
1373
1493
  //# sourceMappingURL=cngx-common-a11y.mjs.map