@link-foundation/ui-sound 0.0.0-stage → 0.0.0

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/src/runtime.js ADDED
@@ -0,0 +1,124 @@
1
+ /** Runtime normalization is shared by config updates and explicit configure. */
2
+ export const bound = (value, min, max, fallback = min) =>
3
+ Number.isFinite(value) ? Math.max(min, Math.min(max, value)) : fallback;
4
+ export const MODES = ['random', 'cycle', 'layer'];
5
+
6
+ export function runtimeSettings(theme, maxVolume) {
7
+ return {
8
+ enabled: false,
9
+ volume: 0.5,
10
+ maxVolume,
11
+ tone: theme.bus.shelf[1],
12
+ frequency: theme.bus.shelf[0],
13
+ reverb: theme.bus.reverb,
14
+ room: theme.bus.room ?? 1.4,
15
+ pitchSpread: 15,
16
+ stereo: true,
17
+ width: 0.6,
18
+ hoverGap: 80,
19
+ mode: null,
20
+ reducedMotionEvents: ['intro', 'scan'],
21
+ events: Object.fromEntries(
22
+ Object.entries(theme.events).map(([key, value]) => [
23
+ key,
24
+ { level: 1, ...value, voices: [...value.voices] },
25
+ ])
26
+ ),
27
+ };
28
+ }
29
+
30
+ export function configureRuntime(state, values, theme) {
31
+ for (const [key, min, max] of [
32
+ ['volume', 0, state.maxVolume],
33
+ ['tone', -40, 40],
34
+ ['frequency', 1, 24000],
35
+ ['reverb', 0, 1],
36
+ ['room', 0.3, 4],
37
+ ['pitchSpread', 0, 100],
38
+ ['width', 0, 1],
39
+ ['hoverGap', 0, 500],
40
+ ]) {
41
+ if (Object.hasOwn(values, key)) {
42
+ state[key] = bound(values[key], min, max, state[key]);
43
+ }
44
+ }
45
+ for (const key of ['enabled', 'stereo']) {
46
+ if (typeof values[key] === 'boolean') {
47
+ state[key] = values[key];
48
+ }
49
+ }
50
+ if (values.mode === null || MODES.includes(values.mode)) {
51
+ state.mode = values.mode;
52
+ }
53
+ if (Array.isArray(values.reducedMotionEvents)) {
54
+ state.reducedMotionEvents = [...values.reducedMotionEvents];
55
+ }
56
+ for (const [event, changes] of Object.entries(values.events ?? {})) {
57
+ const binding = configureEvent(
58
+ Object.hasOwn(state.events, event) ? state.events[event] : undefined,
59
+ changes,
60
+ theme
61
+ );
62
+ Object.defineProperty(state.events, event, {
63
+ value: binding,
64
+ enumerable: true,
65
+ writable: true,
66
+ configurable: true,
67
+ });
68
+ }
69
+ }
70
+
71
+ export function chooseVoices(binding, mode, turn, previous, random) {
72
+ const names = binding.voices;
73
+ if (mode === 'layer') {
74
+ return [...names];
75
+ }
76
+ if (mode === 'cycle') {
77
+ return [names[turn % names.length]];
78
+ }
79
+ const candidates =
80
+ names.length > 1 ? names.filter((name) => name !== previous) : names;
81
+ const pool = candidates.length ? candidates : names;
82
+ return [
83
+ pool[
84
+ Math.min(pool.length - 1, Math.max(0, Math.floor(random() * pool.length)))
85
+ ],
86
+ ];
87
+ }
88
+
89
+ function configureEvent(initial, changes, theme) {
90
+ if (!changes || typeof changes !== 'object') {
91
+ throw new TypeError('Expected event settings');
92
+ }
93
+ const before = initial ?? {
94
+ voices: [],
95
+ mode: 'random',
96
+ level: 1,
97
+ throttle: 0,
98
+ };
99
+ const binding = { ...before };
100
+ if (changes.voices !== undefined) {
101
+ if (
102
+ !Array.isArray(changes.voices) ||
103
+ changes.voices.length > 4 ||
104
+ changes.voices.some((name) => !Object.hasOwn(theme.voices, name))
105
+ ) {
106
+ throw new TypeError('Expected zero to four known voices');
107
+ }
108
+ binding.voices = [...changes.voices];
109
+ }
110
+ if (changes.mode !== undefined) {
111
+ if (!MODES.includes(changes.mode)) {
112
+ throw new TypeError('Unknown sound mode');
113
+ }
114
+ binding.mode = changes.mode;
115
+ }
116
+ if (changes.level !== undefined) {
117
+ binding.level = bound(changes.level, 0, 2, 1);
118
+ }
119
+ if (changes.throttle !== undefined) {
120
+ binding.throttle = bound(changes.throttle, 0, 60000);
121
+ }
122
+
123
+ return binding;
124
+ }
@@ -0,0 +1,215 @@
1
+ import { formatLinks } from '@link-foundation/ui-core';
2
+ import { readSchema } from '@link-foundation/ui-settings';
3
+
4
+ const GLOBAL_FIELDS = [
5
+ ['mode', 'choice', 'random', ['options', 'random', 'cycle', 'layer']],
6
+ ['tone', 'choice', 'neutral', ['options', 'warm', 'neutral', 'bright']],
7
+ ['reverb', 'range', 0.2, ['min', 0], ['max', 1], ['step', 0.01]],
8
+ [
9
+ 'room',
10
+ 'range',
11
+ 1.4,
12
+ ['min', 0.3],
13
+ ['max', 4],
14
+ ['step', 0.1],
15
+ ['visible-when', ['not', ['sound.reverb', '0']]],
16
+ ],
17
+ ['pitchSpread', 'range', 15, ['min', 0], ['max', 100], ['step', 1]],
18
+ ['stereo', 'toggle', true],
19
+ [
20
+ 'width',
21
+ 'range',
22
+ 0.6,
23
+ ['min', 0],
24
+ ['max', 1],
25
+ ['step', 0.01],
26
+ ['visible-when', 'sound.stereo'],
27
+ ],
28
+ ['hoverGap', 'range', 80, ['min', 0], ['max', 500], ['step', 1]],
29
+ ];
30
+ export const SOUND_GLOBAL_KEYS = Object.freeze(
31
+ GLOBAL_FIELDS.map(([key]) => `sound.${key}`)
32
+ );
33
+ export const soundEventKey = (event, field) => `sound.events.${event}.${field}`;
34
+ const LABELS = {
35
+ enabled: 'Sound',
36
+ volume: 'Volume',
37
+ mode: 'Selection mode',
38
+ tone: 'Tone',
39
+ reverb: 'Reverb',
40
+ room: 'Room length',
41
+ pitchSpread: 'Pitch spread',
42
+ stereo: 'Stereo',
43
+ width: 'Stereo width',
44
+ hoverGap: 'Hover gap',
45
+ };
46
+ const tones = { warm: -7, neutral: 0, bright: 5 };
47
+
48
+ function field(key, type, value, clauses = []) {
49
+ return {
50
+ id: key,
51
+ values: [
52
+ ['type', type],
53
+ ['default', String(value)],
54
+ ['comfort'],
55
+ ...(LABELS[key.slice(6)] ? [['label', LABELS[key.slice(6)]]] : []),
56
+ ...clauses,
57
+ ],
58
+ };
59
+ }
60
+
61
+ /** Nested LiNo fields, without a schema header, ready to append to a host schema. */
62
+ export function generateSoundSettings(
63
+ theme,
64
+ events,
65
+ { slots = 4, maxVolume = 1 } = {}
66
+ ) {
67
+ validateOptions(theme, slots, maxVolume);
68
+ const fields = [
69
+ field('sound.enabled', 'toggle', false),
70
+ field('sound.volume', 'range', 0.5, [
71
+ ['min', 0],
72
+ ['max', maxVolume],
73
+ ['step', 0.01],
74
+ ]),
75
+ ...GLOBAL_FIELDS.map(([key, type, value, ...clauses]) =>
76
+ field(`sound.${key}`, type, value, clauses)
77
+ ),
78
+ ];
79
+ const names = Object.keys(theme.voices);
80
+ const labels = [
81
+ 'option-labels',
82
+ ['none', 'None'],
83
+ ...names.map((name) => [name, theme.voices[name].source.character ?? name]),
84
+ ];
85
+ const seen = new Set();
86
+ for (const entry of events) {
87
+ const { name, label = name } =
88
+ typeof entry === 'string' ? { name: entry } : entry;
89
+ if (typeof name !== 'string' || !name || seen.has(name)) {
90
+ throw new TypeError('Expected unique event names');
91
+ }
92
+ seen.add(name);
93
+ fields.push(...eventFields(theme, name, label, slots, { names, labels }));
94
+ }
95
+ const atoms = (value) =>
96
+ Array.isArray(value) ? value.map(atoms) : String(value);
97
+ return formatLinks(
98
+ fields.map((record) => ({ ...record, values: record.values.map(atoms) }))
99
+ );
100
+ }
101
+
102
+ export function createSoundSettingsSchema(theme, events, options) {
103
+ const result = readSchema(
104
+ `sound-settings: schema\n version 1\n${generateSoundSettings(theme, events, options)}`
105
+ );
106
+ if (result.diagnostics.some((d) => d.severity === 'error')) {
107
+ throw new TypeError(result.diagnostics.map((d) => d.message).join('\n'));
108
+ }
109
+ return result.schema;
110
+ }
111
+
112
+ /** Read generated keys from any compatible settings binding; unset keys preserve defaults. */
113
+ export function runtimeFromConfig(config, theme) {
114
+ if (!config) {
115
+ return {};
116
+ }
117
+ const values = {};
118
+ for (const key of [
119
+ 'enabled',
120
+ 'volume',
121
+ ...GLOBAL_FIELDS.map(([key]) => key),
122
+ ]) {
123
+ const value = config.get(`sound.${key}`);
124
+ if (value !== undefined) {
125
+ values[key] = key === 'tone' ? (tones[value] ?? value) : value;
126
+ }
127
+ }
128
+ const events = Object.create(null);
129
+ // Generated bindings expose their schema, so consumer-only events also work.
130
+ const names = new Set(Object.keys(theme.events));
131
+ for (const key of config.schema?.fields.keys() ?? []) {
132
+ if (key.startsWith('sound.events.') && key.endsWith('.voice1')) {
133
+ names.add(key.slice('sound.events.'.length, -'.voice1'.length));
134
+ }
135
+ }
136
+ for (const name of names) {
137
+ const binding = eventFromConfig(config, name);
138
+ if (binding) {
139
+ events[name] = binding;
140
+ }
141
+ }
142
+ return { ...values, events };
143
+ }
144
+
145
+ function eventFields(theme, name, label, slots, { names, labels }) {
146
+ const fields = [];
147
+ const binding = Object.hasOwn(theme.events, name)
148
+ ? theme.events[name]
149
+ : undefined;
150
+ for (let slot = 0; slot < slots; slot++) {
151
+ const key = soundEventKey(name, `voice${slot + 1}`);
152
+ fields.push(
153
+ field(key, 'choice', binding?.voices[slot] ?? 'none', [
154
+ ['label', `${label} voice ${slot + 1}`],
155
+ ['options', 'none', ...names],
156
+ labels,
157
+ ['preview', 'sound-voice'],
158
+ ...(slot
159
+ ? [
160
+ [
161
+ 'visible-when',
162
+ ['not', [soundEventKey(name, `voice${slot}`), 'none']],
163
+ ],
164
+ ]
165
+ : []),
166
+ ])
167
+ );
168
+ }
169
+ fields.push(
170
+ field(soundEventKey(name, 'level'), 'range', binding?.level ?? 1, [
171
+ ['label', `${label} level`],
172
+ ['min', 0],
173
+ ['max', 2],
174
+ ['step', 0.01],
175
+ ])
176
+ );
177
+ return fields;
178
+ }
179
+
180
+ function eventFromConfig(config, name) {
181
+ const voices = [];
182
+ let configured = false;
183
+ let ended = false;
184
+ for (let slot = 1; slot <= 4; slot++) {
185
+ const voice = config.get(soundEventKey(name, `voice${slot}`));
186
+ if (voice !== undefined) {
187
+ configured = true;
188
+ }
189
+ if (voice === 'none' || voice === undefined) {
190
+ ended = true;
191
+ }
192
+ if (!ended) {
193
+ voices.push(voice);
194
+ }
195
+ }
196
+ const level = config.get(soundEventKey(name, 'level'));
197
+ return configured || level !== undefined
198
+ ? {
199
+ ...(configured ? { voices } : {}),
200
+ ...(level === undefined ? {} : { level }),
201
+ }
202
+ : null;
203
+ }
204
+
205
+ function validateOptions(theme, slots, maxVolume) {
206
+ if (!Number.isInteger(slots) || slots < 1 || slots > 4) {
207
+ throw new RangeError('Expected one to four voice slots');
208
+ }
209
+ if (!Number.isFinite(maxVolume) || maxVolume < 1 || maxVolume > 2) {
210
+ throw new RangeError('Expected maxVolume from one to two');
211
+ }
212
+ if (Object.hasOwn(theme.voices, 'none')) {
213
+ throw new TypeError('The voice name none is reserved by sound settings');
214
+ }
215
+ }
package/src/theme.js ADDED
@@ -0,0 +1,308 @@
1
+ /** Sound graphs are data read by the official LiNo reader in ui-core. */
2
+ import { parseLinks } from '@link-foundation/ui-core';
3
+
4
+ const WAVES = ['sine', 'triangle', 'square', 'sawtooth'];
5
+ const FILTERS = [
6
+ 'lowpass',
7
+ 'highpass',
8
+ 'bandpass',
9
+ 'notch',
10
+ 'allpass',
11
+ 'peaking',
12
+ 'lowshelf',
13
+ 'highshelf',
14
+ ];
15
+
16
+ function createReader(diagnostics) {
17
+ const report = (code, message) =>
18
+ diagnostics.push({ code, severity: 'error', message });
19
+ const number = (value, min, max, fallback = min) => {
20
+ const n =
21
+ typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN;
22
+ if (!Number.isFinite(n) || n < min || n > max) {
23
+ report('invalid-number', `Expected ${min}..${max}, got ${String(value)}`);
24
+ return fallback;
25
+ }
26
+ return n;
27
+ };
28
+ const choice = (value, choices) => {
29
+ if (!choices.includes(value)) {
30
+ report('invalid-choice', `Unknown choice ${String(value)}`);
31
+ }
32
+ return choices.includes(value) ? value : choices[0];
33
+ };
34
+ const clauses = (items, handlers) => {
35
+ const seen = new Set();
36
+ for (const item of items) {
37
+ if (!Array.isArray(item) || typeof item[0] !== 'string') {
38
+ report('invalid-clause', 'Expected a named clause');
39
+ continue;
40
+ }
41
+ const [key, ...args] = item;
42
+ if (!Object.hasOwn(handlers, key)) {
43
+ report('unknown-key', `Unknown sound key ${key}`);
44
+ } else {
45
+ if (seen.has(key) && !['voice', 'event', 'part'].includes(key)) {
46
+ report('duplicate-key', `Duplicate ${key}`);
47
+ }
48
+ seen.add(key);
49
+ handlers[key](args);
50
+ }
51
+ }
52
+ };
53
+ const envelope = (args) => {
54
+ const e = { attack: 0.004, decay: 0.08, sustain: 0, release: 0.01 };
55
+ clauses(args, {
56
+ curve: ([curve]) => {
57
+ e.curve = choice(curve, ['linear', 'exponential']);
58
+ },
59
+ ...Object.fromEntries(
60
+ Object.keys(e).map((key) => [
61
+ key,
62
+ ([v]) => {
63
+ e[key] = number(v, 0, key === 'sustain' ? 1 : 10);
64
+ },
65
+ ])
66
+ ),
67
+ });
68
+ return e;
69
+ };
70
+ const filter = ([type, from, to = from, q = '1']) => ({
71
+ type: choice(type, FILTERS),
72
+ from: number(from, 1, 24000),
73
+ to: number(to, 1, 24000),
74
+ q: number(q, 0.0001, 100),
75
+ });
76
+ const part = (args) => {
77
+ const p = {
78
+ kind: 'tone',
79
+ wave: 'sine',
80
+ frequency: 440,
81
+ to: 440,
82
+ glide: null,
83
+ gain: 1,
84
+ delay: 0,
85
+ pan: 0,
86
+ detune: 0,
87
+ envelope: { attack: 0.004, decay: 0.08, sustain: 0, release: 0.01 },
88
+ };
89
+ let hasSource = false;
90
+ clauses(args, {
91
+ oscillator: ([wave, ...fields]) => {
92
+ hasSource = true;
93
+ p.wave = choice(wave, WAVES);
94
+ clauses(fields, {
95
+ frequency: ([v]) => {
96
+ p.frequency = p.to = number(v, 1, 24000);
97
+ },
98
+ glide: ([to, seconds]) => {
99
+ p.to = number(to, 1, 24000);
100
+ p.glide = number(seconds, 0, 10);
101
+ },
102
+ fm: ([ratio, index]) => {
103
+ p.fm = {
104
+ ratio: number(ratio, 0.001, 100),
105
+ index: number(index, 0, 100),
106
+ };
107
+ },
108
+ });
109
+ },
110
+ noise: (fields) => {
111
+ hasSource = true;
112
+ p.kind = 'noise';
113
+ if (fields.length) {
114
+ report('unknown-key', 'noise takes no arguments');
115
+ }
116
+ },
117
+ envelope: (fields) => {
118
+ p.envelope = envelope(fields);
119
+ },
120
+ filter: (fields) => {
121
+ p.filter = filter(fields);
122
+ },
123
+ gain: ([v]) => {
124
+ p.gain = number(v, 0, 1);
125
+ },
126
+ delay: ([v]) => {
127
+ p.delay = number(v, 0, 10);
128
+ },
129
+ pan: ([v]) => {
130
+ p.pan = number(v, -1, 1);
131
+ },
132
+ detune: ([v]) => {
133
+ p.detune = number(v, -4800, 4800);
134
+ },
135
+ });
136
+ if (!hasSource) {
137
+ report('missing-source', 'A graph part needs oscillator or noise');
138
+ }
139
+ return p;
140
+ };
141
+ return { report, number, choice, clauses, part };
142
+ }
143
+
144
+ function readVoice([name, ...args], theme, reader) {
145
+ const { report, number, clauses, part } = reader;
146
+ if (typeof name !== 'string' || Object.hasOwn(theme.voices, name)) {
147
+ report('invalid-voice', 'Missing or duplicate voice name');
148
+ return;
149
+ }
150
+ const v = { parts: [], repeat: 1, gap: 0, repeatDecay: 1, source: {} };
151
+ const direct = [];
152
+ for (const arg of args) {
153
+ if (
154
+ Array.isArray(arg) &&
155
+ [
156
+ 'oscillator',
157
+ 'noise',
158
+ 'envelope',
159
+ 'filter',
160
+ 'gain',
161
+ 'delay',
162
+ 'pan',
163
+ 'detune',
164
+ ].includes(arg[0])
165
+ ) {
166
+ direct.push(arg);
167
+ } else {
168
+ clauses([arg], {
169
+ part: (fields) => {
170
+ v.parts.push(part(fields));
171
+ },
172
+ repeat: ([n]) => {
173
+ v.repeat = number(n, 1, 8);
174
+ if (!Number.isInteger(v.repeat)) {
175
+ report('invalid-repeat', 'repeat must be an integer');
176
+ }
177
+ },
178
+ gap: ([n]) => {
179
+ v.gap = number(n, 0, 10);
180
+ },
181
+ 'repeat-decay': ([n]) => {
182
+ v.repeatDecay = number(n, 0, 1);
183
+ },
184
+ source: (fields) =>
185
+ clauses(
186
+ fields,
187
+ Object.fromEntries(
188
+ ['label', 'license', 'character', 'url', 'port'].map((key) => [
189
+ key,
190
+ ([value]) => {
191
+ if (typeof value !== 'string' || !value) {
192
+ report('invalid-source', `Missing source ${key}`);
193
+ } else {
194
+ v.source[key] = value;
195
+ }
196
+ },
197
+ ])
198
+ )
199
+ ),
200
+ });
201
+ }
202
+ }
203
+ if (direct.length) {
204
+ v.parts.unshift(part(direct));
205
+ }
206
+ if (v.parts.length === 0 || v.parts.length > 8) {
207
+ report('invalid-parts', 'A voice needs 1..8 parts');
208
+ }
209
+ if (!v.source.label || !v.source.license) {
210
+ report(
211
+ 'missing-provenance',
212
+ `Voice ${name} needs a source label and license`
213
+ );
214
+ }
215
+ theme.voices[name] = v;
216
+ }
217
+
218
+ /** Parse and validate a theme. Invalid input produces diagnostics, never a throw. */
219
+ export function readSoundTheme(text) {
220
+ const diagnostics = [];
221
+ const reader = createReader(diagnostics);
222
+ const { report, number, choice, clauses } = reader;
223
+ const theme = {
224
+ name: '',
225
+ voices: Object.create(null),
226
+ events: Object.create(null),
227
+ bus: { shelf: [4000, -6], compressor: [-18, 4], reverb: 0.2 },
228
+ };
229
+ try {
230
+ const roots = parseLinks(text, { maxInputSize: 131072, maxDepth: 32 });
231
+ if (
232
+ roots.length !== 1 ||
233
+ !Array.isArray(roots[0]) ||
234
+ roots[0][0] !== 'sound-theme'
235
+ ) {
236
+ report('invalid-theme', 'Expected one sound-theme');
237
+ } else {
238
+ const [, name, ...args] = roots[0];
239
+ if (typeof name !== 'string') {
240
+ report('invalid-theme', 'Expected theme name');
241
+ } else {
242
+ theme.name = name;
243
+ }
244
+ clauses(args, {
245
+ voice: (args) => readVoice(args, theme, reader),
246
+ event: ([event, ...fields]) => {
247
+ if (typeof event !== 'string' || Object.hasOwn(theme.events, event)) {
248
+ report('invalid-event', 'Missing or duplicate event name');
249
+ return;
250
+ }
251
+ const binding = {
252
+ mode: 'random',
253
+ voices: [],
254
+ throttle: event === 'scan' ? 120 : 0,
255
+ };
256
+ clauses(fields, {
257
+ mode: ([mode]) => {
258
+ binding.mode = choice(mode, ['random', 'cycle', 'layer']);
259
+ },
260
+ voices: (names) => {
261
+ binding.voices = names;
262
+ if (names.length > 6) {
263
+ report('too-many-voices', 'An event allows at most six voices');
264
+ }
265
+ },
266
+ throttle: ([ms]) => {
267
+ binding.throttle = number(ms, 0, 60000);
268
+ },
269
+ });
270
+ theme.events[event] = binding;
271
+ },
272
+ bus: (fields) =>
273
+ clauses(fields, {
274
+ shelf: ([hz, db]) => {
275
+ theme.bus.shelf = [number(hz, 1, 24000), number(db, -40, 40)];
276
+ },
277
+ compressor: ([db, ratio]) => {
278
+ theme.bus.compressor = [
279
+ number(db, -100, 0),
280
+ number(ratio, 1, 20),
281
+ ];
282
+ },
283
+ reverb: ([v]) => {
284
+ theme.bus.reverb = number(v, 0, 1);
285
+ },
286
+ }),
287
+ });
288
+ }
289
+ for (const binding of Object.values(theme.events)) {
290
+ for (const name of binding.voices) {
291
+ if (typeof name !== 'string' || !Object.hasOwn(theme.voices, name)) {
292
+ report('unknown-voice', `Unknown voice ${String(name)}`);
293
+ }
294
+ }
295
+ }
296
+ } catch (error) {
297
+ diagnostics.push(
298
+ ...(error.diagnostics ?? [
299
+ {
300
+ code: 'invalid-theme',
301
+ severity: 'error',
302
+ message: String(error.message),
303
+ },
304
+ ])
305
+ );
306
+ }
307
+ return { theme: diagnostics.length ? null : theme, diagnostics };
308
+ }