@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.
- package/audio/README.md +180 -0
- package/display/README.md +1 -0
- package/fesm2022/cngx-common-a11y.mjs +123 -3
- package/fesm2022/cngx-common-a11y.mjs.map +1 -1
- package/fesm2022/cngx-common-audio.mjs +1205 -0
- package/fesm2022/cngx-common-audio.mjs.map +1 -0
- package/fesm2022/cngx-common-card.mjs +8 -8
- package/fesm2022/cngx-common-card.mjs.map +1 -1
- package/fesm2022/cngx-common-chart.mjs +2 -2
- package/fesm2022/cngx-common-chart.mjs.map +1 -1
- package/fesm2022/cngx-common-data.mjs +996 -55
- package/fesm2022/cngx-common-data.mjs.map +1 -1
- package/fesm2022/cngx-common-display.mjs +320 -8
- package/fesm2022/cngx-common-display.mjs.map +1 -1
- package/fesm2022/cngx-common-interactive.mjs +1633 -80
- package/fesm2022/cngx-common-interactive.mjs.map +1 -1
- package/fesm2022/cngx-common-layout.mjs +187 -3
- package/fesm2022/cngx-common-layout.mjs.map +1 -1
- package/fesm2022/cngx-common-popover.mjs +63 -8
- package/fesm2022/cngx-common-popover.mjs.map +1 -1
- package/fesm2022/cngx-common.mjs +1 -1
- package/interactive/README.md +101 -0
- package/layout/README.md +39 -1
- package/package.json +5 -1
- package/theming/components/cngx-accordion.css +147 -0
- package/theming/components/cngx-badge.css +6 -0
- package/theming/components/cngx-bottom-sheet.css +8 -1
- package/theming/components/cngx-breadcrumb.css +108 -0
- package/theming/components/cngx-button-toggle.css +6 -0
- package/theming/components/cngx-data-grid.css +154 -0
- package/theming/components/cngx-dialog.css +4 -0
- package/theming/components/cngx-divider.css +4 -0
- package/theming/components/cngx-listbox.css +6 -0
- package/theming/components/cngx-menu.css +7 -0
- package/theming/components/cngx-slider.css +237 -0
- package/theming/components/cngx-tooltip.css +6 -0
- package/types/cngx-common-a11y.d.ts +67 -2
- package/types/cngx-common-audio.d.ts +736 -0
- package/types/cngx-common-data.d.ts +632 -22
- package/types/cngx-common-display.d.ts +189 -1
- package/types/cngx-common-interactive.d.ts +1028 -31
- package/types/cngx-common-layout.d.ts +88 -3
- package/types/cngx-common-popover.d.ts +25 -4
|
@@ -0,0 +1,1205 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { InjectionToken, inject, makeEnvironmentProviders, signal, DestroyRef, effect, isDevMode, SkipSelf, Optional, ElementRef, input, booleanAttribute, computed, untracked, afterNextRender, Directive, linkedSignal } from '@angular/core';
|
|
3
|
+
import { DOCUMENT } from '@angular/common';
|
|
4
|
+
import { injectMediaQuery } from '@cngx/common/layout';
|
|
5
|
+
import { CNGX_STATEFUL, createTransitionTracker } from '@cngx/core/utils';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Library defaults — English, browser-native.
|
|
9
|
+
* @category common/audio
|
|
10
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/config/audio-config.ts
|
|
11
|
+
* @since 0.1.0
|
|
12
|
+
*/
|
|
13
|
+
const CNGX_AUDIO_DEFAULTS = {
|
|
14
|
+
muted: false,
|
|
15
|
+
volume: 1,
|
|
16
|
+
respectReducedMotion: true,
|
|
17
|
+
debounceMs: 100,
|
|
18
|
+
earcons: {},
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Injection token carrying the partial audio config contributed by
|
|
22
|
+
* `provideCngxAudio(...)`. Read the resolved, defaults-merged config with
|
|
23
|
+
* {@link injectAudioConfig}.
|
|
24
|
+
*
|
|
25
|
+
* @category common/audio
|
|
26
|
+
* @relatedTo provideCngxAudio, injectAudioConfig
|
|
27
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/config/audio-config.ts
|
|
28
|
+
* @since 0.1.0
|
|
29
|
+
*/
|
|
30
|
+
const CNGX_AUDIO_CONFIG = new InjectionToken('CngxAudioConfig', {
|
|
31
|
+
providedIn: 'root',
|
|
32
|
+
factory: () => ({}),
|
|
33
|
+
});
|
|
34
|
+
/**
|
|
35
|
+
* Resolve the effective audio config: library defaults merged with whatever
|
|
36
|
+
* `provideCngxAudio(...)` contributed. Runs in an injection context.
|
|
37
|
+
*
|
|
38
|
+
* @category common/audio
|
|
39
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/config/audio-config.ts
|
|
40
|
+
* @since 0.1.0
|
|
41
|
+
*/
|
|
42
|
+
function injectAudioConfig() {
|
|
43
|
+
return { ...CNGX_AUDIO_DEFAULTS, ...inject(CNGX_AUDIO_CONFIG, { optional: true }) };
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Fold a `with*` feature list into a single partial config.
|
|
47
|
+
*
|
|
48
|
+
* @internal — shared by {@link provideCngxAudio} and `provideCngxAudioAt`;
|
|
49
|
+
* not exported from `public-api.ts`.
|
|
50
|
+
*/
|
|
51
|
+
function foldAudioFeatures(features) {
|
|
52
|
+
let config = {};
|
|
53
|
+
for (const feature of features) {
|
|
54
|
+
config = feature._apply(config);
|
|
55
|
+
}
|
|
56
|
+
return config;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Register global audio defaults. Mirrors `provideFeedback` — a single small
|
|
60
|
+
* config object folded through `with*` features.
|
|
61
|
+
*
|
|
62
|
+
* ```ts
|
|
63
|
+
* bootstrapApplication(AppComponent, {
|
|
64
|
+
* providers: [
|
|
65
|
+
* provideCngxAudio(
|
|
66
|
+
* withVolume(0.6),
|
|
67
|
+
* withEarcons({ send: { sequence: [{ freq: 880, duration: 60 }] } }),
|
|
68
|
+
* ),
|
|
69
|
+
* ],
|
|
70
|
+
* });
|
|
71
|
+
* ```
|
|
72
|
+
*
|
|
73
|
+
* Register this at **application bootstrap**. The shared engine is
|
|
74
|
+
* `providedIn: 'root'` and reads its configuration once, when it is first built,
|
|
75
|
+
* so config registered in a lazy route's `providers` never reaches it. To
|
|
76
|
+
* configure a subtree, use `provideCngxAudioAt(...)` in `viewProviders` — it
|
|
77
|
+
* layers over this one and re-provides the engine so the scope actually applies.
|
|
78
|
+
*
|
|
79
|
+
* @category common/audio
|
|
80
|
+
* @relatedTo provideCngxAudioAt, injectAudioConfig
|
|
81
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/config/audio-config.ts
|
|
82
|
+
* @since 0.1.0
|
|
83
|
+
*/
|
|
84
|
+
function provideCngxAudio(...features) {
|
|
85
|
+
return makeEnvironmentProviders([
|
|
86
|
+
{ provide: CNGX_AUDIO_CONFIG, useValue: foldAudioFeatures(features) },
|
|
87
|
+
]);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Register or override earcons globally. Merged over the six built-ins and over
|
|
91
|
+
* any earlier `withEarcons` in the same `provideCngxAudio` call.
|
|
92
|
+
*
|
|
93
|
+
* @category common/audio
|
|
94
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/config/audio-config.ts
|
|
95
|
+
* @since 0.1.0
|
|
96
|
+
*/
|
|
97
|
+
function withEarcons(earcons) {
|
|
98
|
+
return { _apply: (c) => ({ ...c, earcons: { ...c.earcons, ...earcons } }) };
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Set the master volume in `[0, 1]`.
|
|
102
|
+
*
|
|
103
|
+
* @category common/audio
|
|
104
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/config/audio-config.ts
|
|
105
|
+
* @since 0.1.0
|
|
106
|
+
*/
|
|
107
|
+
function withVolume(volume) {
|
|
108
|
+
return { _apply: (c) => ({ ...c, volume }) };
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Start muted (or explicitly unmuted with `withMuted(false)`).
|
|
112
|
+
*
|
|
113
|
+
* @category common/audio
|
|
114
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/config/audio-config.ts
|
|
115
|
+
* @since 0.1.0
|
|
116
|
+
*/
|
|
117
|
+
function withMuted(muted = true) {
|
|
118
|
+
return { _apply: (c) => ({ ...c, muted }) };
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Toggle the `prefers-reduced-motion` mute gate. `true` by default in the
|
|
122
|
+
* library; pass `false` to keep audio playing under reduced-motion.
|
|
123
|
+
*
|
|
124
|
+
* @category common/audio
|
|
125
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/config/audio-config.ts
|
|
126
|
+
* @since 0.1.0
|
|
127
|
+
*/
|
|
128
|
+
function withRespectReducedMotion(respect) {
|
|
129
|
+
return { _apply: (c) => ({ ...c, respectReducedMotion: respect }) };
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Set the same-name suppression window in milliseconds.
|
|
133
|
+
*
|
|
134
|
+
* @category common/audio
|
|
135
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/config/audio-config.ts
|
|
136
|
+
* @since 0.1.0
|
|
137
|
+
*/
|
|
138
|
+
function withDebounceMs(ms) {
|
|
139
|
+
return { _apply: (c) => ({ ...c, debounceMs: ms }) };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The user-gesture events that satisfy the browser autoplay policy. */
|
|
143
|
+
const GESTURE_EVENTS = ['pointerdown', 'keydown', 'touchstart'];
|
|
144
|
+
/**
|
|
145
|
+
* Create the autoplay gate: a one-shot latch that flips `armed` to `true` on
|
|
146
|
+
* the first `pointerdown` / `keydown` / `touchstart` and then removes its own
|
|
147
|
+
* listeners. The engine consults `armed()` before resuming the shared
|
|
148
|
+
* `AudioContext`, honouring the browser autoplay policy without a permission
|
|
149
|
+
* prompt.
|
|
150
|
+
*
|
|
151
|
+
* Pure factory — takes its `target` and `destroyRef` as arguments rather than
|
|
152
|
+
* calling `inject()`, so it composes inside the engine's injection context yet
|
|
153
|
+
* stays testable with a fake target. No DI token: the gate has no independent
|
|
154
|
+
* swap consumer (severity ladder `concern: over-abstraction`), so it ships
|
|
155
|
+
* token-less and the engine owns it.
|
|
156
|
+
*
|
|
157
|
+
* @param deps.target The event target to listen on (typically the `Document`).
|
|
158
|
+
* @param deps.destroyRef Cleanup owner — removes any surviving listeners on destroy.
|
|
159
|
+
* @category common/audio
|
|
160
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/autoplay-gate/autoplay-gate.ts
|
|
161
|
+
* @since 0.1.0
|
|
162
|
+
*/
|
|
163
|
+
function createAutoplayGate(deps) {
|
|
164
|
+
const { target, destroyRef } = deps;
|
|
165
|
+
const armed = signal(false, ...(ngDevMode ? [{ debugName: "armed" }] : /* istanbul ignore next */ []));
|
|
166
|
+
function removeListeners() {
|
|
167
|
+
for (const type of GESTURE_EVENTS) {
|
|
168
|
+
target.removeEventListener(type, handleGesture);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function arm() {
|
|
172
|
+
if (armed()) {
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
armed.set(true);
|
|
176
|
+
removeListeners();
|
|
177
|
+
}
|
|
178
|
+
function handleGesture() {
|
|
179
|
+
arm();
|
|
180
|
+
}
|
|
181
|
+
for (const type of GESTURE_EVENTS) {
|
|
182
|
+
target.addEventListener(type, handleGesture, { passive: true });
|
|
183
|
+
}
|
|
184
|
+
destroyRef.onDestroy(removeListeners);
|
|
185
|
+
return {
|
|
186
|
+
armed: armed.asReadonly(),
|
|
187
|
+
arm,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Default suppression window in milliseconds. */
|
|
192
|
+
const DEFAULT_WINDOW_MS = 100;
|
|
193
|
+
/**
|
|
194
|
+
* Per-name time-window debouncer: suppresses repeated fires of the same earcon
|
|
195
|
+
* within `windowMs`. A separate composed factory rather than logic buried in
|
|
196
|
+
* the engine (Pillar 3). Plain factory, no DI token — `withDebounceMs` covers
|
|
197
|
+
* configuration and there is no independent swap consumer.
|
|
198
|
+
*
|
|
199
|
+
* `windowMs` accepts a getter so a caller whose window is a reactive input can
|
|
200
|
+
* hold ONE debouncer instance for its lifetime and still track changes: the
|
|
201
|
+
* window is resolved per `shouldFire` call, not captured at construction. That
|
|
202
|
+
* keeps the (stateful) debouncer out of the signal graph — minting one inside a
|
|
203
|
+
* `computed` would return a fresh object per evaluation and break the equality
|
|
204
|
+
* rule. `CngxAudioPitch` is the getter consumer; the engine passes a number.
|
|
205
|
+
*
|
|
206
|
+
* The clock is injectable (`now`) purely so specs are deterministic; production
|
|
207
|
+
* defaults to `Date.now`.
|
|
208
|
+
*
|
|
209
|
+
* @param options.windowMs Suppression window, or a getter for it. `<= 0` disables debouncing. Default `100`.
|
|
210
|
+
* @param options.now Clock source in ms. Default `Date.now`.
|
|
211
|
+
* @category common/audio
|
|
212
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/debouncer/debouncer.ts
|
|
213
|
+
* @since 0.1.0
|
|
214
|
+
*/
|
|
215
|
+
function createDebouncer(options) {
|
|
216
|
+
const windowOption = options?.windowMs ?? DEFAULT_WINDOW_MS;
|
|
217
|
+
const resolveWindow = typeof windowOption === 'function' ? windowOption : () => windowOption;
|
|
218
|
+
const now = options?.now ?? (() => Date.now());
|
|
219
|
+
const lastFiredAt = new Map();
|
|
220
|
+
return {
|
|
221
|
+
shouldFire(name) {
|
|
222
|
+
const at = now();
|
|
223
|
+
const last = lastFiredAt.get(name);
|
|
224
|
+
if (last !== undefined && at - last < resolveWindow()) {
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
lastFiredAt.set(name, at);
|
|
228
|
+
return true;
|
|
229
|
+
},
|
|
230
|
+
reset(name) {
|
|
231
|
+
if (name === undefined) {
|
|
232
|
+
lastFiredAt.clear();
|
|
233
|
+
}
|
|
234
|
+
else {
|
|
235
|
+
lastFiredAt.delete(name);
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* The six built-in earcons, synthesised entirely from `OscillatorNode` — zero
|
|
243
|
+
* audio assets. Plain `as const` (mirrors `CNGX_SELECT_GLYPHS`): tree-shakeable,
|
|
244
|
+
* compile-time exhaustive keys, and NOT exported from `public-api.ts`. The
|
|
245
|
+
* consumer override surface is `withEarcons({...})` and the engine's runtime
|
|
246
|
+
* `register()`, never this const.
|
|
247
|
+
*
|
|
248
|
+
* @internal
|
|
249
|
+
*/
|
|
250
|
+
const CNGX_AUDIO_DEFAULT_EARCONS = {
|
|
251
|
+
/** Neutral tick for taps, toggles, and generic acknowledgements. */
|
|
252
|
+
tap: { sequence: [{ freq: 660, duration: 30 }] },
|
|
253
|
+
/** Rising two-note chime for a completed positive action. */
|
|
254
|
+
success: {
|
|
255
|
+
sequence: [
|
|
256
|
+
{ freq: 660, duration: 80 },
|
|
257
|
+
{ freq: 880, duration: 120 },
|
|
258
|
+
],
|
|
259
|
+
},
|
|
260
|
+
/** Falling sawtooth pair for a failure — deliberately harsher. */
|
|
261
|
+
error: {
|
|
262
|
+
sequence: [
|
|
263
|
+
{ freq: 400, duration: 100, type: 'sawtooth', gain: 0.15 },
|
|
264
|
+
{ freq: 300, duration: 160, type: 'sawtooth', gain: 0.15 },
|
|
265
|
+
],
|
|
266
|
+
},
|
|
267
|
+
/** Two soft triangle pulses for a caution state. */
|
|
268
|
+
warning: {
|
|
269
|
+
sequence: [
|
|
270
|
+
{ freq: 520, duration: 90, type: 'triangle' },
|
|
271
|
+
{ freq: 520, duration: 90, type: 'triangle', delay: 60 },
|
|
272
|
+
],
|
|
273
|
+
},
|
|
274
|
+
/** Gentle upward two-note for an incoming notification. */
|
|
275
|
+
notification: {
|
|
276
|
+
sequence: [
|
|
277
|
+
{ freq: 780, duration: 70 },
|
|
278
|
+
{ freq: 990, duration: 90, delay: 20 },
|
|
279
|
+
],
|
|
280
|
+
},
|
|
281
|
+
/** Three-note upward arpeggio for a finished multi-step flow. */
|
|
282
|
+
complete: {
|
|
283
|
+
sequence: [
|
|
284
|
+
{ freq: 523, duration: 90 },
|
|
285
|
+
{ freq: 659, duration: 90 },
|
|
286
|
+
{ freq: 784, duration: 140 },
|
|
287
|
+
],
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
/** Attack ramp, seconds — lifts gain from 0 so the oscillator start is click-free. */
|
|
292
|
+
const ATTACK_SEC = 0.005;
|
|
293
|
+
/** Release ramp, seconds — drops gain to 0 before stop so the end is click-free. */
|
|
294
|
+
const RELEASE_SEC = 0.03;
|
|
295
|
+
/** A tone shorter than attack+release cannot host both ramps; clamp up to this floor. */
|
|
296
|
+
const MIN_DURATION_SEC = ATTACK_SEC + RELEASE_SEC;
|
|
297
|
+
/**
|
|
298
|
+
* Default peak gain for a single tone (before the engine's master volume).
|
|
299
|
+
* Exported so a per-element volume multiplier can scale against the same
|
|
300
|
+
* baseline the generator uses.
|
|
301
|
+
* @category common/audio
|
|
302
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/tone-generator/tone-generator.ts
|
|
303
|
+
* @since 0.1.0
|
|
304
|
+
*/
|
|
305
|
+
const DEFAULT_TONE_GAIN = 0.2;
|
|
306
|
+
/**
|
|
307
|
+
* Pure `OscillatorNode` synthesis — no audio assets. Each tone is an
|
|
308
|
+
* oscillator through a per-note gain envelope (5 ms attack, 30 ms release)
|
|
309
|
+
* into the engine's master-volume node. The envelope is not decoration: a
|
|
310
|
+
* bare `start()`/`stop()` on a full-amplitude oscillator produces an audible
|
|
311
|
+
* click at both ends; ramping in and out removes it.
|
|
312
|
+
*
|
|
313
|
+
* `create*` pure factory (no `inject()`), so it composes inside the engine and
|
|
314
|
+
* runs against the shared `createAudioContextMock` in specs.
|
|
315
|
+
* @category common/audio
|
|
316
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/tone-generator/tone-generator.ts
|
|
317
|
+
* @since 0.1.0
|
|
318
|
+
*/
|
|
319
|
+
const createToneGenerator = (deps) => {
|
|
320
|
+
function schedule(freq, durationMs, opts, whenSec) {
|
|
321
|
+
const ctx = deps.context();
|
|
322
|
+
const dest = deps.destination();
|
|
323
|
+
const start = ctx.currentTime + whenSec + (opts?.when ?? 0);
|
|
324
|
+
const durSec = Math.max(durationMs / 1000, MIN_DURATION_SEC);
|
|
325
|
+
const peak = opts?.gain ?? DEFAULT_TONE_GAIN;
|
|
326
|
+
const osc = ctx.createOscillator();
|
|
327
|
+
osc.type = opts?.type ?? 'sine';
|
|
328
|
+
osc.frequency.setValueAtTime(freq, start);
|
|
329
|
+
const env = ctx.createGain();
|
|
330
|
+
const holdStart = start + ATTACK_SEC;
|
|
331
|
+
const releaseStart = start + durSec - RELEASE_SEC;
|
|
332
|
+
env.gain.setValueAtTime(0, start);
|
|
333
|
+
env.gain.linearRampToValueAtTime(peak, holdStart);
|
|
334
|
+
env.gain.setValueAtTime(peak, releaseStart);
|
|
335
|
+
env.gain.linearRampToValueAtTime(0, start + durSec);
|
|
336
|
+
osc.connect(env);
|
|
337
|
+
env.connect(dest);
|
|
338
|
+
osc.start(start);
|
|
339
|
+
osc.stop(start + durSec);
|
|
340
|
+
osc.onended = () => {
|
|
341
|
+
osc.disconnect();
|
|
342
|
+
env.disconnect();
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
return {
|
|
346
|
+
tone(freq, durationMs, opts) {
|
|
347
|
+
schedule(freq, durationMs, opts, 0);
|
|
348
|
+
},
|
|
349
|
+
sequence(steps) {
|
|
350
|
+
let offsetSec = 0;
|
|
351
|
+
for (const step of steps) {
|
|
352
|
+
offsetSec += (step.delay ?? 0) / 1000;
|
|
353
|
+
schedule(step.freq, step.duration, { type: step.type, gain: step.gain }, offsetSec);
|
|
354
|
+
offsetSec += Math.max(step.duration / 1000, MIN_DURATION_SEC);
|
|
355
|
+
}
|
|
356
|
+
},
|
|
357
|
+
};
|
|
358
|
+
};
|
|
359
|
+
/**
|
|
360
|
+
* Swappable tone-generator factory. Defaults to {@link createToneGenerator}
|
|
361
|
+
* (oscillator synthesis). Override to swap in sample-based playback without
|
|
362
|
+
* forking the engine — the documented second consumer of this boundary token.
|
|
363
|
+
*
|
|
364
|
+
* @relatedTo createToneGenerator, CNGX_AUDIO_ENGINE_FACTORY
|
|
365
|
+
* @category common/audio
|
|
366
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/tone-generator/tone-generator.ts
|
|
367
|
+
* @since 0.1.0
|
|
368
|
+
*/
|
|
369
|
+
const CNGX_AUDIO_TONE_GENERATOR_FACTORY = new InjectionToken('CngxAudioToneGeneratorFactory', { providedIn: 'root', factory: () => createToneGenerator });
|
|
370
|
+
|
|
371
|
+
function clampVolume(v) {
|
|
372
|
+
return Math.max(0, Math.min(1, v));
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Apply a per-call `[0, 1]` scale to a tone's peak gain. Centralised here so
|
|
376
|
+
* every play path (`play` / `tone` / `sequence`) scales identically and an
|
|
377
|
+
* engine override sees per-element volume uniformly, rather than each caller
|
|
378
|
+
* pre-baking its own gain.
|
|
379
|
+
*/
|
|
380
|
+
function scaleGain(gain, scale) {
|
|
381
|
+
return (gain ?? DEFAULT_TONE_GAIN) * clampVolume(scale);
|
|
382
|
+
}
|
|
383
|
+
function scaleSteps(steps, scale) {
|
|
384
|
+
if (scale === undefined) {
|
|
385
|
+
return steps;
|
|
386
|
+
}
|
|
387
|
+
return steps.map((step) => ({ ...step, gain: scaleGain(step.gain, scale) }));
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Create the audio engine: composes the autoplay gate, tone generator, and
|
|
391
|
+
* debouncer over one lazily-created shared `AudioContext`. Reduced-motion muting
|
|
392
|
+
* reuses the existing `injectMediaQuery('(prefers-reduced-motion: reduce)')`
|
|
393
|
+
* primitive rather than adding another `matchMedia` reader.
|
|
394
|
+
*
|
|
395
|
+
* The four mute conditions are enforced centrally in `play()`/`tone()`/
|
|
396
|
+
* `sequence()`: global mute, reduced-motion, and autoplay-not-armed here;
|
|
397
|
+
* per-element `[audioDisabled]` in the directives.
|
|
398
|
+
*
|
|
399
|
+
* Runs in an injection context (calls `inject()` for DOCUMENT, DestroyRef, the
|
|
400
|
+
* tone-generator factory, and the reduced-motion query). The engine instance is
|
|
401
|
+
* resolved through {@link CNGX_AUDIO_ENGINE_FACTORY}; scope it to a subtree with
|
|
402
|
+
* `provideCngxAudioAt(...)` rather than calling this directly.
|
|
403
|
+
* @category common/audio
|
|
404
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/engine/audio-engine.ts
|
|
405
|
+
* @since 0.1.0
|
|
406
|
+
*/
|
|
407
|
+
const createAudioEngine = (options) => {
|
|
408
|
+
const doc = inject(DOCUMENT);
|
|
409
|
+
const destroyRef = inject(DestroyRef);
|
|
410
|
+
const toneGeneratorFactory = inject(CNGX_AUDIO_TONE_GENERATOR_FACTORY);
|
|
411
|
+
const config = injectAudioConfig();
|
|
412
|
+
const reducedMotion = injectMediaQuery('(prefers-reduced-motion: reduce)');
|
|
413
|
+
const muted = signal(config.muted, ...(ngDevMode ? [{ debugName: "muted" }] : /* istanbul ignore next */ []));
|
|
414
|
+
const volume = signal(clampVolume(config.volume), ...(ngDevMode ? [{ debugName: "volume" }] : /* istanbul ignore next */ []));
|
|
415
|
+
const status = signal('idle', ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
|
|
416
|
+
const lastPlayed = signal(null, ...(ngDevMode ? [{ debugName: "lastPlayed" }] : /* istanbul ignore next */ []));
|
|
417
|
+
const gate = createAutoplayGate({ target: doc, destroyRef });
|
|
418
|
+
const debouncer = createDebouncer({ windowMs: config.debounceMs });
|
|
419
|
+
const earcons = new Map(Object.entries({ ...CNGX_AUDIO_DEFAULT_EARCONS, ...config.earcons }));
|
|
420
|
+
let context = null;
|
|
421
|
+
let masterGain = null;
|
|
422
|
+
const contextFactory = options?.contextFactory ??
|
|
423
|
+
(() => {
|
|
424
|
+
const view = doc.defaultView;
|
|
425
|
+
const Ctor = view?.AudioContext ?? view?.webkitAudioContext;
|
|
426
|
+
return Ctor ? new Ctor() : null;
|
|
427
|
+
});
|
|
428
|
+
const toneGenerator = toneGeneratorFactory({
|
|
429
|
+
context: () => context,
|
|
430
|
+
destination: () => masterGain,
|
|
431
|
+
});
|
|
432
|
+
function resumeIfArmed() {
|
|
433
|
+
if (context && gate.armed() && context.state === 'suspended') {
|
|
434
|
+
void context.resume().then(() => status.set('running'), () => undefined);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
function ensureContext() {
|
|
438
|
+
if (context) {
|
|
439
|
+
return context;
|
|
440
|
+
}
|
|
441
|
+
const created = contextFactory();
|
|
442
|
+
if (!created) {
|
|
443
|
+
status.set('unsupported');
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
446
|
+
context = created;
|
|
447
|
+
masterGain = created.createGain();
|
|
448
|
+
masterGain.gain.value = volume();
|
|
449
|
+
masterGain.connect(created.destination);
|
|
450
|
+
status.set(created.state);
|
|
451
|
+
resumeIfArmed();
|
|
452
|
+
return context;
|
|
453
|
+
}
|
|
454
|
+
function blocked() {
|
|
455
|
+
return muted() || (config.respectReducedMotion && reducedMotion()) || !gate.armed();
|
|
456
|
+
}
|
|
457
|
+
// Volume is communicated to the master node reactively — the single writer is
|
|
458
|
+
// setVolume(), but binding through an effect keeps the node in sync from any
|
|
459
|
+
// future volume source too.
|
|
460
|
+
effect(() => {
|
|
461
|
+
const v = volume();
|
|
462
|
+
if (masterGain) {
|
|
463
|
+
masterGain.gain.value = v;
|
|
464
|
+
}
|
|
465
|
+
});
|
|
466
|
+
// Suspend on tab hide (frees the audio hardware); resume on return if armed.
|
|
467
|
+
const onVisibility = () => {
|
|
468
|
+
if (!context) {
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
if (doc.hidden) {
|
|
472
|
+
if (context.state === 'running') {
|
|
473
|
+
void context.suspend().then(() => status.set('suspended'), () => undefined);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
else {
|
|
477
|
+
resumeIfArmed();
|
|
478
|
+
}
|
|
479
|
+
};
|
|
480
|
+
doc.addEventListener('visibilitychange', onVisibility);
|
|
481
|
+
destroyRef.onDestroy(() => {
|
|
482
|
+
doc.removeEventListener('visibilitychange', onVisibility);
|
|
483
|
+
// close() rejects on an already-closed context; swallow it so a double
|
|
484
|
+
// destroy does not surface an unhandled rejection.
|
|
485
|
+
const closing = context?.close?.();
|
|
486
|
+
void closing?.then(() => undefined, () => undefined);
|
|
487
|
+
});
|
|
488
|
+
return {
|
|
489
|
+
play(name, scale) {
|
|
490
|
+
if (blocked()) {
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
if (!ensureContext()) {
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
resumeIfArmed();
|
|
497
|
+
if (!debouncer.shouldFire(name)) {
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
const earcon = earcons.get(name);
|
|
501
|
+
if (!earcon) {
|
|
502
|
+
if (isDevMode()) {
|
|
503
|
+
console.warn(`[cngxAudio] Unknown earcon "${name}". Register it via withEarcons({...}) or engine.register(name, config).`);
|
|
504
|
+
}
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
toneGenerator.sequence(scaleSteps(earcon.sequence, scale));
|
|
508
|
+
lastPlayed.set(name);
|
|
509
|
+
},
|
|
510
|
+
tone(freq, durationMs, opts, scale) {
|
|
511
|
+
if (blocked() || !ensureContext()) {
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
resumeIfArmed();
|
|
515
|
+
toneGenerator.tone(freq, durationMs, scale === undefined ? opts : { ...opts, gain: scaleGain(opts?.gain, scale) });
|
|
516
|
+
},
|
|
517
|
+
sequence(steps, scale) {
|
|
518
|
+
if (blocked() || !ensureContext()) {
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
resumeIfArmed();
|
|
522
|
+
toneGenerator.sequence(scaleSteps(steps, scale));
|
|
523
|
+
},
|
|
524
|
+
register(name, earconConfig) {
|
|
525
|
+
earcons.set(name, earconConfig);
|
|
526
|
+
},
|
|
527
|
+
armAutoplay() {
|
|
528
|
+
gate.arm();
|
|
529
|
+
resumeIfArmed();
|
|
530
|
+
},
|
|
531
|
+
setMuted(next) {
|
|
532
|
+
muted.set(next);
|
|
533
|
+
},
|
|
534
|
+
setVolume(next) {
|
|
535
|
+
volume.set(clampVolume(next));
|
|
536
|
+
},
|
|
537
|
+
muted: muted.asReadonly(),
|
|
538
|
+
volume: volume.asReadonly(),
|
|
539
|
+
status: status.asReadonly(),
|
|
540
|
+
lastPlayed: lastPlayed.asReadonly(),
|
|
541
|
+
};
|
|
542
|
+
};
|
|
543
|
+
/**
|
|
544
|
+
* Swappable engine factory. Defaults to {@link createAudioEngine}. Override to
|
|
545
|
+
* wrap the engine with telemetry/audit logging — the documented second consumer
|
|
546
|
+
* of this boundary token.
|
|
547
|
+
*
|
|
548
|
+
* Register the override at **application bootstrap**. The shared engine instance
|
|
549
|
+
* is itself `providedIn: 'root'` and is built on first use, so a factory override
|
|
550
|
+
* registered in a lazy route's `providers` is never consulted. For a subtree that
|
|
551
|
+
* needs its own engine, use `provideCngxAudioAt(...)` in `viewProviders`.
|
|
552
|
+
*
|
|
553
|
+
* An override that needs the resolved configuration reads it with
|
|
554
|
+
* {@link injectAudioConfig} (defaults merged); {@link CNGX_AUDIO_DEFAULTS} holds
|
|
555
|
+
* the library baseline. Both are exported from `@cngx/common/audio`.
|
|
556
|
+
*
|
|
557
|
+
* @relatedTo createAudioEngine, injectCngxAudio, injectAudioConfig
|
|
558
|
+
* @category common/audio
|
|
559
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/engine/audio-engine.ts
|
|
560
|
+
* @since 0.1.0
|
|
561
|
+
*/
|
|
562
|
+
const CNGX_AUDIO_ENGINE_FACTORY = new InjectionToken('CngxAudioEngineFactory', { providedIn: 'root', factory: () => createAudioEngine });
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* The shared engine instance. Lazily built from `CNGX_AUDIO_ENGINE_FACTORY` and
|
|
566
|
+
* memoised per injector so every directive shares one `AudioContext`, mute
|
|
567
|
+
* state, and volume. `@internal` — the public entry point is {@link injectCngxAudio};
|
|
568
|
+
* consumers override the swappable factory, not this instance anchor. To scope
|
|
569
|
+
* audio to a subtree, use {@link provideCngxAudioAt} — it re-provides this token
|
|
570
|
+
* for you alongside the scoped config.
|
|
571
|
+
*
|
|
572
|
+
* @internal
|
|
573
|
+
*/
|
|
574
|
+
const CNGX_AUDIO_ENGINE = new InjectionToken('CngxAudioEngineInstance', {
|
|
575
|
+
providedIn: 'root',
|
|
576
|
+
factory: () => inject(CNGX_AUDIO_ENGINE_FACTORY)(),
|
|
577
|
+
});
|
|
578
|
+
/**
|
|
579
|
+
* Resolve the shared audio handle. Must run in an injection context (field
|
|
580
|
+
* initialiser or constructor).
|
|
581
|
+
*
|
|
582
|
+
* ```typescript
|
|
583
|
+
* export class MyToggle {
|
|
584
|
+
* private readonly audio = injectCngxAudio();
|
|
585
|
+
* protected readonly muted = this.audio.muted;
|
|
586
|
+
* protected toggle(): void {
|
|
587
|
+
* this.audio.setMuted(!this.muted());
|
|
588
|
+
* }
|
|
589
|
+
* }
|
|
590
|
+
* ```
|
|
591
|
+
*
|
|
592
|
+
* @category common/audio
|
|
593
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/inject-audio.ts
|
|
594
|
+
* @since 0.1.0
|
|
595
|
+
*/
|
|
596
|
+
function injectCngxAudio() {
|
|
597
|
+
return inject(CNGX_AUDIO_ENGINE);
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Component-scope audio config — place in a component's `viewProviders` so a
|
|
601
|
+
* subtree runs its own muted / volume / earcon set, independent of the app-wide
|
|
602
|
+
* `provideCngxAudio(...)`.
|
|
603
|
+
*
|
|
604
|
+
* ```typescript
|
|
605
|
+
* @Component({
|
|
606
|
+
* selector: 'app-mixer',
|
|
607
|
+
* viewProviders: [provideCngxAudioAt(withVolume(0.3), withEarcons({ ... }))],
|
|
608
|
+
* })
|
|
609
|
+
* export class Mixer {}
|
|
610
|
+
* ```
|
|
611
|
+
*
|
|
612
|
+
* Returns `Provider[]` (not `EnvironmentProviders`) so it can sit in
|
|
613
|
+
* `viewProviders`. The root `provideCngxAudio` must be registered at
|
|
614
|
+
* **application bootstrap**: {@link CNGX_AUDIO_ENGINE} is `providedIn: 'root'`,
|
|
615
|
+
* so its factory resolves the config from the root injector and a provider
|
|
616
|
+
* registered on a lazy route never reaches it.
|
|
617
|
+
*
|
|
618
|
+
* Features **layer over** the ancestor config (root, or an enclosing scope)
|
|
619
|
+
* rather than replacing it — the `provideMenuConfigAt` pattern. Scalar fields
|
|
620
|
+
* (`muted`, `volume`, `debounceMs`, `respectReducedMotion`) override; `earcons`
|
|
621
|
+
* merge, so a subtree adds or overrides individual earcons without dropping the
|
|
622
|
+
* app-wide registry.
|
|
623
|
+
*
|
|
624
|
+
* The default shared engine is a single, process-global `AudioContext`; this
|
|
625
|
+
* deliberately re-provides {@link CNGX_AUDIO_ENGINE} so the subtree gets an
|
|
626
|
+
* **isolated engine** reading the scoped {@link CNGX_AUDIO_CONFIG} — a
|
|
627
|
+
* config-only override would be inert against the already-built root engine.
|
|
628
|
+
* That engine owns a **second `AudioContext`**, created lazily on its first play
|
|
629
|
+
* and closed with the component's `DestroyRef`. Browsers cap the number of live
|
|
630
|
+
* `AudioContext`s, so reach for this only when a subtree genuinely needs an
|
|
631
|
+
* independent audio scope — per-element `[audioVolume]` / `[audioDisabled]`
|
|
632
|
+
* cover the common case without a second context.
|
|
633
|
+
*
|
|
634
|
+
* @category common/audio
|
|
635
|
+
* @relatedTo provideCngxAudio, injectCngxAudio
|
|
636
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/inject-audio.ts
|
|
637
|
+
* @since 0.1.0
|
|
638
|
+
*/
|
|
639
|
+
function provideCngxAudioAt(...features) {
|
|
640
|
+
return [
|
|
641
|
+
{
|
|
642
|
+
provide: CNGX_AUDIO_CONFIG,
|
|
643
|
+
useFactory: (parent) => {
|
|
644
|
+
const base = parent ?? {};
|
|
645
|
+
const scoped = foldAudioFeatures(features);
|
|
646
|
+
return { ...base, ...scoped, earcons: { ...base.earcons, ...scoped.earcons } };
|
|
647
|
+
},
|
|
648
|
+
deps: [[new SkipSelf(), new Optional(), CNGX_AUDIO_CONFIG]],
|
|
649
|
+
},
|
|
650
|
+
{ provide: CNGX_AUDIO_ENGINE, useFactory: () => inject(CNGX_AUDIO_ENGINE_FACTORY)() },
|
|
651
|
+
];
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Structural equality for the `key -> earcon` maps the directive binding
|
|
656
|
+
* computeds return. Both `[cngxAudio]` and `[cngxAudioStatus]` derive a fresh
|
|
657
|
+
* `Map` from their spec string on every recompute; without an `equal` fn the
|
|
658
|
+
* `computed` would hand a new reference to any reactive consumer even when the
|
|
659
|
+
* parsed bindings are identical (the signal-hygiene Equality Rule). Same size,
|
|
660
|
+
* same value per key.
|
|
661
|
+
*
|
|
662
|
+
* @internal — not exported from `public-api.ts`.
|
|
663
|
+
*/
|
|
664
|
+
function sameStringMap(a, b) {
|
|
665
|
+
if (a.size !== b.size) {
|
|
666
|
+
return false;
|
|
667
|
+
}
|
|
668
|
+
for (const [key, value] of a) {
|
|
669
|
+
if (b.get(key) !== value) {
|
|
670
|
+
return false;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
return true;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/** DOM events `[cngxAudio]` may bind an earcon to. */
|
|
677
|
+
const CNGX_AUDIO_DOM_EVENTS = [
|
|
678
|
+
'click',
|
|
679
|
+
'focus',
|
|
680
|
+
'blur',
|
|
681
|
+
'pointerenter',
|
|
682
|
+
'pointerleave',
|
|
683
|
+
'submit',
|
|
684
|
+
'change',
|
|
685
|
+
'input',
|
|
686
|
+
];
|
|
687
|
+
/** Lifecycle keys that belong to `[cngxAudioStatus]`, rejected here. */
|
|
688
|
+
const LIFECYCLE_KEYS = [
|
|
689
|
+
'pending',
|
|
690
|
+
'succeeded',
|
|
691
|
+
'failed',
|
|
692
|
+
'loading',
|
|
693
|
+
'refreshing',
|
|
694
|
+
'success',
|
|
695
|
+
'error',
|
|
696
|
+
'idle',
|
|
697
|
+
];
|
|
698
|
+
const DOM_EVENT_SET$1 = new Set(CNGX_AUDIO_DOM_EVENTS);
|
|
699
|
+
const LIFECYCLE_SET = new Set(LIFECYCLE_KEYS);
|
|
700
|
+
/**
|
|
701
|
+
* Parse the `event:earcon` grammar (`'click:tap, focus:notification'`) into a
|
|
702
|
+
* DOM-event map. Pure — no DOM, no `inject()`. Keys are categorised so the
|
|
703
|
+
* directive can dev-warn on unknown earcon keys and, separately, on lifecycle
|
|
704
|
+
* keys that should have used `[cngxAudioStatus]`.
|
|
705
|
+
*/
|
|
706
|
+
function parseEventBindings(spec) {
|
|
707
|
+
const bindings = new Map();
|
|
708
|
+
const unknownKeys = [];
|
|
709
|
+
const lifecycleKeys = [];
|
|
710
|
+
for (const pair of spec.split(',')) {
|
|
711
|
+
const trimmed = pair.trim();
|
|
712
|
+
if (!trimmed) {
|
|
713
|
+
continue;
|
|
714
|
+
}
|
|
715
|
+
const colon = trimmed.indexOf(':');
|
|
716
|
+
if (colon === -1) {
|
|
717
|
+
unknownKeys.push(trimmed);
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
const key = trimmed.slice(0, colon).trim();
|
|
721
|
+
const earcon = trimmed.slice(colon + 1).trim();
|
|
722
|
+
if (DOM_EVENT_SET$1.has(key)) {
|
|
723
|
+
if (earcon) {
|
|
724
|
+
bindings.set(key, earcon);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
else if (LIFECYCLE_SET.has(key)) {
|
|
728
|
+
lifecycleKeys.push(key);
|
|
729
|
+
}
|
|
730
|
+
else {
|
|
731
|
+
unknownKeys.push(key);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
return { bindings, unknownKeys, lifecycleKeys };
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* Event-mode audio binder. Maps DOM events on the host to earcons via the
|
|
739
|
+
* `event:earcon` grammar — a pure DOM-event-to-sound directive with no state
|
|
740
|
+
* coupling (that is `[cngxAudioStatus]`'s job).
|
|
741
|
+
*
|
|
742
|
+
* ```html
|
|
743
|
+
* <button [cngxAudio]="'click:tap'">Save</button>
|
|
744
|
+
* <a [cngxAudio]="'pointerenter:notification, click:complete'">Open</a>
|
|
745
|
+
* ```
|
|
746
|
+
*
|
|
747
|
+
* Playback is skipped when the element is disabled (`[audioDisabled]`), when
|
|
748
|
+
* the engine is muted / reduced-motion-gated / autoplay-not-armed, or when the
|
|
749
|
+
* same earcon is still within the debounce window. `[audioVolume]` scales just
|
|
750
|
+
* this element's plays.
|
|
751
|
+
*
|
|
752
|
+
* The listener set is derived from the grammar, not fixed: `'click:tap'`
|
|
753
|
+
* registers one DOM listener, and rebinding `[cngxAudio]` at runtime adds the
|
|
754
|
+
* newly named events and removes the dropped ones. Binding happens on the first
|
|
755
|
+
* change detection after the input settles rather than at construction, so an
|
|
756
|
+
* event dispatched programmatically before the host's first tick is missed.
|
|
757
|
+
*
|
|
758
|
+
* Listeners are registered outside Angular's event dispatch. In a zoneless app
|
|
759
|
+
* that means they schedule no change detection; under zone.js the patched
|
|
760
|
+
* `addEventListener` still triggers a tick, so there the saving is registration
|
|
761
|
+
* cost alone. Either way the engine's `lastPlayed` and `status` are signals, so
|
|
762
|
+
* anything a template binds to them stays current.
|
|
763
|
+
*
|
|
764
|
+
* @category common/audio
|
|
765
|
+
* @docsKind primary
|
|
766
|
+
* @wcag AA
|
|
767
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/event-mode/audio.directive.ts
|
|
768
|
+
* @since 0.1.0
|
|
769
|
+
* @relatedTo injectCngxAudio, provideCngxAudio, CngxAudioStatus
|
|
770
|
+
* <example-url>http://localhost:4200/#/common/audio/event-mode/basic</example-url>
|
|
771
|
+
* <example-url>http://localhost:4200/#/common/audio/event-mode/custom-earcons</example-url>
|
|
772
|
+
* <example-url>http://localhost:4200/#/common/audio/event-mode/earcon-palette</example-url>
|
|
773
|
+
* <example-url>http://localhost:4200/#/common/audio/event-mode/form-feedback</example-url>
|
|
774
|
+
* <example-url>http://localhost:4200/#/common/audio/event-mode/hover-and-focus</example-url>
|
|
775
|
+
*/
|
|
776
|
+
class CngxAudio {
|
|
777
|
+
audio = injectCngxAudio();
|
|
778
|
+
host = inject(ElementRef);
|
|
779
|
+
destroyRef = inject(DestroyRef);
|
|
780
|
+
/** The listeners currently registered on the host, keyed by event type. */
|
|
781
|
+
bound = new Map();
|
|
782
|
+
/** The `event:earcon` grammar, e.g. `'click:tap, focus:notification'`. */
|
|
783
|
+
spec = input('', { ...(ngDevMode ? { debugName: "spec" } : /* istanbul ignore next */ {}), alias: 'cngxAudio' });
|
|
784
|
+
/** Per-element volume multiplier in `[0, 1]`; unset uses the engine volume. */
|
|
785
|
+
audioVolume = input(undefined, ...(ngDevMode ? [{ debugName: "audioVolume" }] : /* istanbul ignore next */ []));
|
|
786
|
+
/** Suppress this element's audio without unbinding. */
|
|
787
|
+
audioDisabled = input(false, { ...(ngDevMode ? { debugName: "audioDisabled" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
|
|
788
|
+
bindings = computed(() => parseEventBindings(this.spec()).bindings, { ...(ngDevMode ? { debugName: "bindings" } : /* istanbul ignore next */ {}), equal: sameStringMap });
|
|
789
|
+
constructor() {
|
|
790
|
+
effect(() => {
|
|
791
|
+
const wanted = this.bindings();
|
|
792
|
+
untracked(() => this.syncListeners(wanted));
|
|
793
|
+
});
|
|
794
|
+
this.destroyRef.onDestroy(() => this.unbindAll());
|
|
795
|
+
if (isDevMode()) {
|
|
796
|
+
// One-shot post-binding check, not a reactive node.
|
|
797
|
+
afterNextRender(() => {
|
|
798
|
+
const parsed = parseEventBindings(this.spec());
|
|
799
|
+
if (parsed.lifecycleKeys.length > 0) {
|
|
800
|
+
console.error(`[cngxAudio] Lifecycle keys "${parsed.lifecycleKeys.join(', ')}" are not DOM events. ` +
|
|
801
|
+
'Use [cngxAudioStatus] for lifecycle bindings.');
|
|
802
|
+
}
|
|
803
|
+
if (parsed.unknownKeys.length > 0) {
|
|
804
|
+
console.warn(`[cngxAudio] Unrecognised event keys "${parsed.unknownKeys.join(', ')}". ` +
|
|
805
|
+
'Expected one of: click, focus, blur, pointerenter, pointerleave, submit, change, input.');
|
|
806
|
+
}
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* Diff the bound listener set against the parsed spec: drop event types the
|
|
812
|
+
* grammar no longer names, add the ones it newly names, leave the rest alone.
|
|
813
|
+
* A rebuild would churn a listener that is still wanted.
|
|
814
|
+
*/
|
|
815
|
+
syncListeners(wanted) {
|
|
816
|
+
const el = this.host.nativeElement;
|
|
817
|
+
for (const [type, listener] of this.bound) {
|
|
818
|
+
if (!wanted.has(type)) {
|
|
819
|
+
el.removeEventListener(type, listener);
|
|
820
|
+
this.bound.delete(type);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
for (const type of wanted.keys()) {
|
|
824
|
+
if (this.bound.has(type)) {
|
|
825
|
+
continue;
|
|
826
|
+
}
|
|
827
|
+
// Captures the type only — the earcon is read fresh at fire time, so
|
|
828
|
+
// renaming it in the grammar needs no rebind.
|
|
829
|
+
const listener = () => this.handleEvent(type);
|
|
830
|
+
// Not passive: none of the bindable types are scroll-blocking, so the
|
|
831
|
+
// flag buys nothing and would foreclose preventDefault on submit/click.
|
|
832
|
+
el.addEventListener(type, listener);
|
|
833
|
+
this.bound.set(type, listener);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
unbindAll() {
|
|
837
|
+
const el = this.host.nativeElement;
|
|
838
|
+
for (const [type, listener] of this.bound) {
|
|
839
|
+
el.removeEventListener(type, listener);
|
|
840
|
+
}
|
|
841
|
+
this.bound.clear();
|
|
842
|
+
}
|
|
843
|
+
handleEvent(event) {
|
|
844
|
+
if (this.audioDisabled()) {
|
|
845
|
+
return;
|
|
846
|
+
}
|
|
847
|
+
const earcon = this.bindings().get(event);
|
|
848
|
+
if (!earcon) {
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
this.audio.play(earcon, this.audioVolume());
|
|
852
|
+
}
|
|
853
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAudio, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
854
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxAudio, isStandalone: true, selector: "[cngxAudio]", inputs: { spec: { classPropertyName: "spec", publicName: "cngxAudio", isSignal: true, isRequired: false, transformFunction: null }, audioVolume: { classPropertyName: "audioVolume", publicName: "audioVolume", isSignal: true, isRequired: false, transformFunction: null }, audioDisabled: { classPropertyName: "audioDisabled", publicName: "audioDisabled", isSignal: true, isRequired: false, transformFunction: null } }, exportAs: ["cngxAudio"], ngImport: i0 });
|
|
855
|
+
}
|
|
856
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAudio, decorators: [{
|
|
857
|
+
type: Directive,
|
|
858
|
+
args: [{
|
|
859
|
+
selector: '[cngxAudio]',
|
|
860
|
+
exportAs: 'cngxAudio',
|
|
861
|
+
}]
|
|
862
|
+
}], ctorParameters: () => [], propDecorators: { spec: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxAudio", required: false }] }], audioVolume: [{ type: i0.Input, args: [{ isSignal: true, alias: "audioVolume", required: false }] }], audioDisabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "audioDisabled", required: false }] }] } });
|
|
863
|
+
|
|
864
|
+
/**
|
|
865
|
+
* Lifecycle keys `[cngxAudioStatus]` accepts, mapped to the canonical
|
|
866
|
+
* `AsyncStatus` the transition tracker emits. Two friendly aliases are folded
|
|
867
|
+
* in: `succeeded -> success` and `failed -> error`, so both the raw status and
|
|
868
|
+
* the past-tense reading parse to the same earcon.
|
|
869
|
+
*/
|
|
870
|
+
const STATUS_ALIASES = {
|
|
871
|
+
idle: 'idle',
|
|
872
|
+
loading: 'loading',
|
|
873
|
+
pending: 'pending',
|
|
874
|
+
refreshing: 'refreshing',
|
|
875
|
+
success: 'success',
|
|
876
|
+
succeeded: 'success',
|
|
877
|
+
error: 'error',
|
|
878
|
+
failed: 'error',
|
|
879
|
+
};
|
|
880
|
+
/** DOM-event keys that belong to `[cngxAudio]`, rejected here. */
|
|
881
|
+
const CNGX_AUDIO_STATUS_DOM_EVENTS = [
|
|
882
|
+
'click',
|
|
883
|
+
'focus',
|
|
884
|
+
'blur',
|
|
885
|
+
'pointerenter',
|
|
886
|
+
'pointerleave',
|
|
887
|
+
'submit',
|
|
888
|
+
'change',
|
|
889
|
+
'input',
|
|
890
|
+
];
|
|
891
|
+
const DOM_EVENT_SET = new Set(CNGX_AUDIO_STATUS_DOM_EVENTS);
|
|
892
|
+
/**
|
|
893
|
+
* Parse the `status:earcon` grammar (`'pending:tap, succeeded:success'`) into a
|
|
894
|
+
* status map. Pure — no DOM, no `inject()`. Keys are categorised so the
|
|
895
|
+
* directive can dev-error on DOM-event keys that should have used `[cngxAudio]`
|
|
896
|
+
* and dev-warn on unknown keys. `succeeded`/`failed` normalise to
|
|
897
|
+
* `success`/`error` so a lookup by the tracker's raw `AsyncStatus` hits.
|
|
898
|
+
*/
|
|
899
|
+
function parseStatusBindings(spec) {
|
|
900
|
+
const bindings = new Map();
|
|
901
|
+
const domEventKeys = [];
|
|
902
|
+
const unknownKeys = [];
|
|
903
|
+
for (const pair of spec.split(',')) {
|
|
904
|
+
const trimmed = pair.trim();
|
|
905
|
+
if (!trimmed) {
|
|
906
|
+
continue;
|
|
907
|
+
}
|
|
908
|
+
const colon = trimmed.indexOf(':');
|
|
909
|
+
if (colon === -1) {
|
|
910
|
+
unknownKeys.push(trimmed);
|
|
911
|
+
continue;
|
|
912
|
+
}
|
|
913
|
+
const key = trimmed.slice(0, colon).trim();
|
|
914
|
+
const earcon = trimmed.slice(colon + 1).trim();
|
|
915
|
+
const status = STATUS_ALIASES[key];
|
|
916
|
+
if (status) {
|
|
917
|
+
if (earcon) {
|
|
918
|
+
bindings.set(status, earcon);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
else if (DOM_EVENT_SET.has(key)) {
|
|
922
|
+
domEventKeys.push(key);
|
|
923
|
+
}
|
|
924
|
+
else {
|
|
925
|
+
unknownKeys.push(key);
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
return { bindings, domEventKeys, unknownKeys };
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/**
|
|
932
|
+
* Status-mode audio bridge. Maps `CngxAsyncState` lifecycle transitions to
|
|
933
|
+
* earcons via the `status:earcon` grammar — the audition counterpart of
|
|
934
|
+
* `CngxToastOn`. Fires only on a real status transition, never on the initial
|
|
935
|
+
* `idle`, and at most once per transition.
|
|
936
|
+
*
|
|
937
|
+
* ```html
|
|
938
|
+
* <button [cngxAsyncClick]="upload"
|
|
939
|
+
* #upload="cngxAsyncClick"
|
|
940
|
+
* [state]="upload.state"
|
|
941
|
+
* [cngxAudioStatus]="'pending:tap, succeeded:success, failed:error'">
|
|
942
|
+
* Upload
|
|
943
|
+
* </button>
|
|
944
|
+
* ```
|
|
945
|
+
*
|
|
946
|
+
* The state source resolves the same way the feedback bridges do: an explicit
|
|
947
|
+
* `[state]` input wins, otherwise it falls back to an ancestor's
|
|
948
|
+
* `CNGX_STATEFUL`. The grammar keys are lifecycle statuses only — DOM-event
|
|
949
|
+
* keys (`click`, `focus`, …) belong to `[cngxAudio]` and are rejected with a
|
|
950
|
+
* dev-error. `succeeded`/`failed` are accepted as aliases for `success`/`error`.
|
|
951
|
+
*
|
|
952
|
+
* @category common/audio
|
|
953
|
+
* @docsKind primary
|
|
954
|
+
* @wcag AA
|
|
955
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/status-mode/audio-status.directive.ts
|
|
956
|
+
* @since 0.1.0
|
|
957
|
+
* @relatedTo CngxAudio, injectCngxAudio, CngxAsyncClick
|
|
958
|
+
* <example-url>http://localhost:4200/#/common/audio/status-bridge/async-click</example-url>
|
|
959
|
+
*/
|
|
960
|
+
class CngxAudioStatus {
|
|
961
|
+
audio = injectCngxAudio();
|
|
962
|
+
statefulFallback = inject(CNGX_STATEFUL, { optional: true });
|
|
963
|
+
/** The `status:earcon` grammar, e.g. `'pending:tap, succeeded:success'`. */
|
|
964
|
+
spec = input('', { ...(ngDevMode ? { debugName: "spec" } : /* istanbul ignore next */ {}), alias: 'cngxAudioStatus' });
|
|
965
|
+
/**
|
|
966
|
+
* The async state to watch. Optional — when omitted, the bridge falls back to
|
|
967
|
+
* an ancestor `CNGX_STATEFUL`. A bare `[state]` attribute (empty string) is
|
|
968
|
+
* treated as "no input bound" so the fallback kicks in.
|
|
969
|
+
*/
|
|
970
|
+
state = input(undefined, { ...(ngDevMode ? { debugName: "state" } : /* istanbul ignore next */ {}), transform: (v) => (typeof v === 'string' ? undefined : v) });
|
|
971
|
+
/** Per-element volume multiplier in `[0, 1]`; unset uses the engine volume. */
|
|
972
|
+
audioVolume = input(undefined, ...(ngDevMode ? [{ debugName: "audioVolume" }] : /* istanbul ignore next */ []));
|
|
973
|
+
/** Suppress this element's audio without unbinding. */
|
|
974
|
+
audioDisabled = input(false, { ...(ngDevMode ? { debugName: "audioDisabled" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
|
|
975
|
+
/** Effective state — explicit input wins over ancestor `CNGX_STATEFUL`. */
|
|
976
|
+
effectiveState = computed(() => this.state() ?? this.statefulFallback?.state, ...(ngDevMode ? [{ debugName: "effectiveState" }] : /* istanbul ignore next */ []));
|
|
977
|
+
bindings = computed(() => parseStatusBindings(this.spec()).bindings, { ...(ngDevMode ? { debugName: "bindings" } : /* istanbul ignore next */ {}), equal: sameStringMap });
|
|
978
|
+
constructor() {
|
|
979
|
+
if (isDevMode()) {
|
|
980
|
+
// One-shot post-binding check, not a reactive node.
|
|
981
|
+
afterNextRender(() => {
|
|
982
|
+
const parsed = parseStatusBindings(this.spec());
|
|
983
|
+
if (parsed.domEventKeys.length > 0) {
|
|
984
|
+
console.error(`[cngxAudioStatus] DOM-event keys "${parsed.domEventKeys.join(', ')}" are not lifecycle ` +
|
|
985
|
+
'statuses. Use [cngxAudio] for DOM-event bindings.');
|
|
986
|
+
}
|
|
987
|
+
if (this.state() === undefined && !this.statefulFallback) {
|
|
988
|
+
console.error('[cngxAudioStatus] No state source. Bind [state]="state" explicitly or place inside a ' +
|
|
989
|
+
'component that provides CNGX_STATEFUL.');
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
const tracker = createTransitionTracker(() => this.effectiveState()?.status() ?? 'idle');
|
|
994
|
+
effect(() => {
|
|
995
|
+
const status = tracker.current();
|
|
996
|
+
const previous = tracker.previous();
|
|
997
|
+
if (status === previous) {
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
untracked(() => {
|
|
1001
|
+
if (this.audioDisabled()) {
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
const earcon = this.bindings().get(status);
|
|
1005
|
+
if (earcon) {
|
|
1006
|
+
this.audio.play(earcon, this.audioVolume());
|
|
1007
|
+
}
|
|
1008
|
+
});
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAudioStatus, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
1012
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxAudioStatus, isStandalone: true, selector: "[cngxAudioStatus]", inputs: { spec: { classPropertyName: "spec", publicName: "cngxAudioStatus", isSignal: true, isRequired: false, transformFunction: null }, state: { classPropertyName: "state", publicName: "state", isSignal: true, isRequired: false, transformFunction: null }, audioVolume: { classPropertyName: "audioVolume", publicName: "audioVolume", isSignal: true, isRequired: false, transformFunction: null }, audioDisabled: { classPropertyName: "audioDisabled", publicName: "audioDisabled", isSignal: true, isRequired: false, transformFunction: null } }, exportAs: ["cngxAudioStatus"], ngImport: i0 });
|
|
1013
|
+
}
|
|
1014
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAudioStatus, decorators: [{
|
|
1015
|
+
type: Directive,
|
|
1016
|
+
args: [{
|
|
1017
|
+
selector: '[cngxAudioStatus]',
|
|
1018
|
+
exportAs: 'cngxAudioStatus',
|
|
1019
|
+
}]
|
|
1020
|
+
}], ctorParameters: () => [], propDecorators: { spec: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxAudioStatus", required: false }] }], state: [{ type: i0.Input, args: [{ isSignal: true, alias: "state", required: false }] }], audioVolume: [{ type: i0.Input, args: [{ isSignal: true, alias: "audioVolume", required: false }] }], audioDisabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "audioDisabled", required: false }] }] } });
|
|
1021
|
+
|
|
1022
|
+
/**
|
|
1023
|
+
* Zone-mode audio binder. Plays earcons as the pointer or keyboard focus enters
|
|
1024
|
+
* and leaves the host — a spatial complement to `[cngxAudio]`. The record input
|
|
1025
|
+
* makes the four zone transitions explicit rather than encoding them in the
|
|
1026
|
+
* `event:earcon` string grammar, because the listener set (pointer/focus zone)
|
|
1027
|
+
* and the shape (record vs string) are semantically distinct from event-mode.
|
|
1028
|
+
*
|
|
1029
|
+
* ```html
|
|
1030
|
+
* <div [cngxAudioZone]="{ enter: 'notification', leave: 'tap' }">Hover me</div>
|
|
1031
|
+
* <button [cngxAudioZone]="{ focus: 'tap', blur: 'tap' }">Focus me</button>
|
|
1032
|
+
* ```
|
|
1033
|
+
*
|
|
1034
|
+
* Playback obeys the same gates as the rest of the family: skipped when
|
|
1035
|
+
* `[audioDisabled]`, muted, reduced-motion-gated, autoplay-not-armed, or still
|
|
1036
|
+
* within the debounce window. `[audioVolume]` scales just this element's plays.
|
|
1037
|
+
*
|
|
1038
|
+
* @category common/audio
|
|
1039
|
+
* @docsKind primary
|
|
1040
|
+
* @wcag AA
|
|
1041
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/zone-mode/audio-zone.directive.ts
|
|
1042
|
+
* @since 0.1.0
|
|
1043
|
+
* @relatedTo CngxAudio, injectCngxAudio
|
|
1044
|
+
* <example-url>http://localhost:4200/#/common/audio/zone/enter-leave</example-url>
|
|
1045
|
+
*/
|
|
1046
|
+
class CngxAudioZone {
|
|
1047
|
+
audio = injectCngxAudio();
|
|
1048
|
+
host = inject(ElementRef);
|
|
1049
|
+
/** Earcon per zone transition. Any omitted key plays nothing. */
|
|
1050
|
+
zone = input({}, { ...(ngDevMode ? { debugName: "zone" } : /* istanbul ignore next */ {}), alias: 'cngxAudioZone' });
|
|
1051
|
+
/** Per-element volume multiplier in `[0, 1]`; unset uses the engine volume. */
|
|
1052
|
+
audioVolume = input(undefined, ...(ngDevMode ? [{ debugName: "audioVolume" }] : /* istanbul ignore next */ []));
|
|
1053
|
+
/** Suppress this element's audio without unbinding. */
|
|
1054
|
+
audioDisabled = input(false, { ...(ngDevMode ? { debugName: "audioDisabled" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
|
|
1055
|
+
/**
|
|
1056
|
+
* `focusin`/`focusout` bubble, so a zone wrapping focusable children would
|
|
1057
|
+
* otherwise fire on every internal tab move. Only a crossing of the zone
|
|
1058
|
+
* boundary counts — the focus counterpart of pointerenter/pointerleave.
|
|
1059
|
+
*/
|
|
1060
|
+
handleFocusCross(kind, event) {
|
|
1061
|
+
if (this.host.nativeElement.contains(event.relatedTarget)) {
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
this.handleZone(kind);
|
|
1065
|
+
}
|
|
1066
|
+
handleZone(kind) {
|
|
1067
|
+
if (this.audioDisabled()) {
|
|
1068
|
+
return;
|
|
1069
|
+
}
|
|
1070
|
+
const earcon = this.zone()[kind];
|
|
1071
|
+
if (earcon) {
|
|
1072
|
+
this.audio.play(earcon, this.audioVolume());
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAudioZone, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
1076
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxAudioZone, isStandalone: true, selector: "[cngxAudioZone]", inputs: { zone: { classPropertyName: "zone", publicName: "cngxAudioZone", isSignal: true, isRequired: false, transformFunction: null }, audioVolume: { classPropertyName: "audioVolume", publicName: "audioVolume", isSignal: true, isRequired: false, transformFunction: null }, audioDisabled: { classPropertyName: "audioDisabled", publicName: "audioDisabled", isSignal: true, isRequired: false, transformFunction: null } }, host: { listeners: { "pointerenter": "handleZone(\"enter\")", "pointerleave": "handleZone(\"leave\")", "focusin": "handleFocusCross(\"focus\", $event)", "focusout": "handleFocusCross(\"blur\", $event)" } }, exportAs: ["cngxAudioZone"], ngImport: i0 });
|
|
1077
|
+
}
|
|
1078
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAudioZone, decorators: [{
|
|
1079
|
+
type: Directive,
|
|
1080
|
+
args: [{
|
|
1081
|
+
selector: '[cngxAudioZone]',
|
|
1082
|
+
exportAs: 'cngxAudioZone',
|
|
1083
|
+
host: {
|
|
1084
|
+
'(pointerenter)': 'handleZone("enter")',
|
|
1085
|
+
'(pointerleave)': 'handleZone("leave")',
|
|
1086
|
+
'(focusin)': 'handleFocusCross("focus", $event)',
|
|
1087
|
+
'(focusout)': 'handleFocusCross("blur", $event)',
|
|
1088
|
+
},
|
|
1089
|
+
}]
|
|
1090
|
+
}], propDecorators: { zone: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxAudioZone", required: false }] }], audioVolume: [{ type: i0.Input, args: [{ isSignal: true, alias: "audioVolume", required: false }] }], audioDisabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "audioDisabled", required: false }] }] } });
|
|
1091
|
+
|
|
1092
|
+
/** Throttle key — the pitch directive plays a single ad-hoc voice. */
|
|
1093
|
+
const PITCH_VOICE = 'pitch';
|
|
1094
|
+
/**
|
|
1095
|
+
* Pitch-mode audio binder. Sonifies a continuous numeric value: each change of
|
|
1096
|
+
* `[cngxAudioPitch]` clamps against a fixed domain, linear-scales into an output
|
|
1097
|
+
* frequency range, and plays a short tone. Useful for sliders, gauges, and live
|
|
1098
|
+
* metrics — the ear tracks a value without looking.
|
|
1099
|
+
*
|
|
1100
|
+
* ```html
|
|
1101
|
+
* <input type="range" min="0" max="100"
|
|
1102
|
+
* [cngxAudioPitch]="volume()"
|
|
1103
|
+
* [pitchDomain]="[0, 100]"
|
|
1104
|
+
* [pitchRange]="[220, 880]" />
|
|
1105
|
+
* ```
|
|
1106
|
+
*
|
|
1107
|
+
* The inputs are discrete rather than an options record so `[cngxAudioPitch]`
|
|
1108
|
+
* stays a native reactive input — passing `[cngxAudioPitch]="volume()"` binds a
|
|
1109
|
+
* signal value directly, never a `Signal` smuggled inside a config object. The
|
|
1110
|
+
* domain is caller-supplied and fixed; it is never accumulated from observed
|
|
1111
|
+
* values, so the directive holds no hidden state. Value-to-frequency is a pure
|
|
1112
|
+
* derivation; rapid sweeps are throttled through the shared `createDebouncer`.
|
|
1113
|
+
*
|
|
1114
|
+
* @category common/audio
|
|
1115
|
+
* @docsKind primary
|
|
1116
|
+
* @wcag AA
|
|
1117
|
+
* @github https://github.com/cngxjs/cngx/blob/main/projects/common/audio/pitch-mode/audio-pitch.directive.ts
|
|
1118
|
+
* @since 0.1.0
|
|
1119
|
+
* @relatedTo CngxAudio, injectCngxAudio
|
|
1120
|
+
* <example-url>http://localhost:4200/#/common/audio/pitch/slider</example-url>
|
|
1121
|
+
*/
|
|
1122
|
+
class CngxAudioPitch {
|
|
1123
|
+
audio = injectCngxAudio();
|
|
1124
|
+
/** The tracked value to sonify. */
|
|
1125
|
+
value = input.required({ ...(ngDevMode ? { debugName: "value" } : /* istanbul ignore next */ {}), alias: 'cngxAudioPitch' });
|
|
1126
|
+
/** Output frequency range `[lo, hi]` in Hz. Default `[220, 880]`. */
|
|
1127
|
+
pitchRange = input([220, 880], ...(ngDevMode ? [{ debugName: "pitchRange" }] : /* istanbul ignore next */ []));
|
|
1128
|
+
/** Fixed input domain `[min, max]` the value is clamped against. */
|
|
1129
|
+
pitchDomain = input.required(...(ngDevMode ? [{ debugName: "pitchDomain" }] : /* istanbul ignore next */ []));
|
|
1130
|
+
/** Tone duration in ms. Default `120`. */
|
|
1131
|
+
pitchDurationMs = input(120, ...(ngDevMode ? [{ debugName: "pitchDurationMs" }] : /* istanbul ignore next */ []));
|
|
1132
|
+
/** Minimum ms between tones during a sweep. Default `50`. */
|
|
1133
|
+
pitchThrottleMs = input(50, ...(ngDevMode ? [{ debugName: "pitchThrottleMs" }] : /* istanbul ignore next */ []));
|
|
1134
|
+
/** Per-element volume multiplier in `[0, 1]`; unset uses the tone default. */
|
|
1135
|
+
audioVolume = input(undefined, ...(ngDevMode ? [{ debugName: "audioVolume" }] : /* istanbul ignore next */ []));
|
|
1136
|
+
/** Suppress this element's audio without unbinding. */
|
|
1137
|
+
audioDisabled = input(false, { ...(ngDevMode ? { debugName: "audioDisabled" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
|
|
1138
|
+
// One instance for the directive's lifetime, deliberately outside the signal
|
|
1139
|
+
// graph: a debouncer carries mutable throttle state, and minting one inside a
|
|
1140
|
+
// computed would hand out a fresh object per evaluation. The window is a
|
|
1141
|
+
// getter, so a changed [pitchThrottleMs] applies on the next fire.
|
|
1142
|
+
debouncer = createDebouncer({ windowMs: () => this.pitchThrottleMs() });
|
|
1143
|
+
// Fires on change, never on mount: sonifying the initial value would emit a
|
|
1144
|
+
// tone the user never asked for, and would burn the throttle window before
|
|
1145
|
+
// their first move. Same current/previous shape as createTransitionTracker.
|
|
1146
|
+
transition = linkedSignal({ ...(ngDevMode ? { debugName: "transition" } : /* istanbul ignore next */ {}), source: () => this.value(),
|
|
1147
|
+
computation: (current, prev) => ({ current, previous: prev?.value.current ?? null }),
|
|
1148
|
+
equal: (a, b) => a.current === b.current && a.previous === b.previous });
|
|
1149
|
+
constructor() {
|
|
1150
|
+
effect(() => {
|
|
1151
|
+
const { current, previous } = this.transition();
|
|
1152
|
+
if (previous === null || current === previous) {
|
|
1153
|
+
return;
|
|
1154
|
+
}
|
|
1155
|
+
untracked(() => {
|
|
1156
|
+
if (this.audioDisabled()) {
|
|
1157
|
+
return;
|
|
1158
|
+
}
|
|
1159
|
+
if (!this.debouncer.shouldFire(PITCH_VOICE)) {
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
1162
|
+
this.audio.tone(this.scale(current), this.pitchDurationMs(), undefined, this.audioVolume());
|
|
1163
|
+
});
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
/** Clamp to the domain, then linear-scale into the frequency range. */
|
|
1167
|
+
scale(value) {
|
|
1168
|
+
const [domainLo, domainHi] = this.pitchDomain();
|
|
1169
|
+
const [rangeLo, rangeHi] = this.pitchRange();
|
|
1170
|
+
const clamped = Math.max(domainLo, Math.min(domainHi, value));
|
|
1171
|
+
if (domainHi === domainLo) {
|
|
1172
|
+
return rangeLo;
|
|
1173
|
+
}
|
|
1174
|
+
const t = (clamped - domainLo) / (domainHi - domainLo);
|
|
1175
|
+
return rangeLo + t * (rangeHi - rangeLo);
|
|
1176
|
+
}
|
|
1177
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAudioPitch, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
1178
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: CngxAudioPitch, isStandalone: true, selector: "[cngxAudioPitch]", inputs: { value: { classPropertyName: "value", publicName: "cngxAudioPitch", isSignal: true, isRequired: true, transformFunction: null }, pitchRange: { classPropertyName: "pitchRange", publicName: "pitchRange", isSignal: true, isRequired: false, transformFunction: null }, pitchDomain: { classPropertyName: "pitchDomain", publicName: "pitchDomain", isSignal: true, isRequired: true, transformFunction: null }, pitchDurationMs: { classPropertyName: "pitchDurationMs", publicName: "pitchDurationMs", isSignal: true, isRequired: false, transformFunction: null }, pitchThrottleMs: { classPropertyName: "pitchThrottleMs", publicName: "pitchThrottleMs", isSignal: true, isRequired: false, transformFunction: null }, audioVolume: { classPropertyName: "audioVolume", publicName: "audioVolume", isSignal: true, isRequired: false, transformFunction: null }, audioDisabled: { classPropertyName: "audioDisabled", publicName: "audioDisabled", isSignal: true, isRequired: false, transformFunction: null } }, exportAs: ["cngxAudioPitch"], ngImport: i0 });
|
|
1179
|
+
}
|
|
1180
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: CngxAudioPitch, decorators: [{
|
|
1181
|
+
type: Directive,
|
|
1182
|
+
args: [{
|
|
1183
|
+
selector: '[cngxAudioPitch]',
|
|
1184
|
+
exportAs: 'cngxAudioPitch',
|
|
1185
|
+
}]
|
|
1186
|
+
}], ctorParameters: () => [], propDecorators: { value: [{ type: i0.Input, args: [{ isSignal: true, alias: "cngxAudioPitch", required: true }] }], pitchRange: [{ type: i0.Input, args: [{ isSignal: true, alias: "pitchRange", required: false }] }], pitchDomain: [{ type: i0.Input, args: [{ isSignal: true, alias: "pitchDomain", required: true }] }], pitchDurationMs: [{ type: i0.Input, args: [{ isSignal: true, alias: "pitchDurationMs", required: false }] }], pitchThrottleMs: [{ type: i0.Input, args: [{ isSignal: true, alias: "pitchThrottleMs", required: false }] }], audioVolume: [{ type: i0.Input, args: [{ isSignal: true, alias: "audioVolume", required: false }] }], audioDisabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "audioDisabled", required: false }] }] } });
|
|
1187
|
+
|
|
1188
|
+
/**
|
|
1189
|
+
* @module @cngx/common/audio
|
|
1190
|
+
*
|
|
1191
|
+
* Signal-first audio-feedback system. A thin directive layer over a small
|
|
1192
|
+
* Web Audio adapter: zero asset weight (earcons synthesised from
|
|
1193
|
+
* `OscillatorNode`), a single shared `AudioContext` behind the engine, and
|
|
1194
|
+
* the `provideCngxAudio(...)` aggregator. Mirrors the shape of the sibling
|
|
1195
|
+
* feedback primitives (`CngxRipple`, `CngxPressable`, `CngxSpeak`) — the
|
|
1196
|
+
* fourth sense, audition, as composable atoms.
|
|
1197
|
+
*/
|
|
1198
|
+
// Handle + component-scope provider
|
|
1199
|
+
|
|
1200
|
+
/**
|
|
1201
|
+
* Generated bundle index. Do not edit.
|
|
1202
|
+
*/
|
|
1203
|
+
|
|
1204
|
+
export { CNGX_AUDIO_CONFIG, CNGX_AUDIO_DEFAULTS, CNGX_AUDIO_ENGINE_FACTORY, CNGX_AUDIO_TONE_GENERATOR_FACTORY, CngxAudio, CngxAudioPitch, CngxAudioStatus, CngxAudioZone, createAudioEngine, createAutoplayGate, createDebouncer, createToneGenerator, injectAudioConfig, injectCngxAudio, provideCngxAudio, provideCngxAudioAt, withDebounceMs, withEarcons, withMuted, withRespectReducedMotion, withVolume };
|
|
1205
|
+
//# sourceMappingURL=cngx-common-audio.mjs.map
|