@vibes.diy/prompts 14.3.249 → 14.3.250

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 (114) hide show
  1. package/generation-variety.js +1 -1
  2. package/index.d.ts +1 -1
  3. package/index.js +1 -1
  4. package/index.js.map +1 -1
  5. package/llms/backend.js +1 -0
  6. package/llms/backend.js.map +1 -1
  7. package/llms/blockly.js +1 -0
  8. package/llms/blockly.js.map +1 -1
  9. package/llms/blockly.md +2 -3
  10. package/llms/board-games.js +9 -4
  11. package/llms/board-games.js.map +1 -1
  12. package/llms/board-games.md +3 -153
  13. package/llms/callai.js +1 -0
  14. package/llms/callai.js.map +1 -1
  15. package/llms/callai.md +1 -1
  16. package/llms/canvas-theme-colors.d.ts +2 -0
  17. package/llms/canvas-theme-colors.js +7 -0
  18. package/llms/canvas-theme-colors.js.map +1 -0
  19. package/llms/canvas-theme-colors.md +70 -0
  20. package/llms/image-gen.js +1 -0
  21. package/llms/image-gen.js.map +1 -1
  22. package/llms/image-gen.md +1 -1
  23. package/llms/index.d.ts +20 -1
  24. package/llms/index.js +55 -0
  25. package/llms/index.js.map +1 -1
  26. package/llms/keepsake.d.ts +2 -0
  27. package/llms/keepsake.js +9 -0
  28. package/llms/keepsake.js.map +1 -0
  29. package/llms/keepsake.md +74 -0
  30. package/llms/live-rooms.d.ts +2 -0
  31. package/llms/live-rooms.js +28 -0
  32. package/llms/live-rooms.js.map +1 -0
  33. package/llms/live-rooms.md +288 -0
  34. package/llms/media-capture.d.ts +2 -0
  35. package/llms/media-capture.js +27 -0
  36. package/llms/media-capture.js.map +1 -0
  37. package/llms/media-capture.md +190 -0
  38. package/llms/mic-capture.d.ts +2 -0
  39. package/llms/mic-capture.js +7 -0
  40. package/llms/mic-capture.js.map +1 -0
  41. package/llms/mic-capture.md +76 -0
  42. package/llms/needs.d.ts +12 -0
  43. package/llms/needs.js +71 -0
  44. package/llms/needs.js.map +1 -0
  45. package/llms/p5.js +1 -0
  46. package/llms/p5.js.map +1 -1
  47. package/llms/p5.md +15 -69
  48. package/llms/photo-input.d.ts +2 -0
  49. package/llms/photo-input.js +7 -0
  50. package/llms/photo-input.js.map +1 -0
  51. package/llms/photo-input.md +141 -0
  52. package/llms/physics.js +1 -0
  53. package/llms/physics.js.map +1 -1
  54. package/llms/physics.md +7 -16
  55. package/llms/reskin.js +3 -8
  56. package/llms/reskin.js.map +1 -1
  57. package/llms/reskin.md +4 -72
  58. package/llms/richtext.md +2 -0
  59. package/llms/social-post.js +1 -0
  60. package/llms/social-post.js.map +1 -1
  61. package/llms/social-post.md +22 -4
  62. package/llms/sound-core.d.ts +2 -0
  63. package/llms/sound-core.js +7 -0
  64. package/llms/sound-core.js.map +1 -0
  65. package/llms/sound-core.md +131 -0
  66. package/llms/strudel.js +2 -0
  67. package/llms/strudel.js.map +1 -1
  68. package/llms/strudel.md +24 -25
  69. package/llms/surface-board.d.ts +2 -0
  70. package/llms/surface-board.js +8 -0
  71. package/llms/surface-board.js.map +1 -0
  72. package/llms/surface-board.md +140 -0
  73. package/llms/surface-play-area.d.ts +2 -0
  74. package/llms/surface-play-area.js +8 -0
  75. package/llms/surface-play-area.js.map +1 -0
  76. package/llms/surface-play-area.md +51 -0
  77. package/llms/surface-presence.d.ts +2 -0
  78. package/llms/surface-presence.js +9 -0
  79. package/llms/surface-presence.js.map +1 -0
  80. package/llms/surface-presence.md +118 -0
  81. package/llms/three-js.js +1 -1
  82. package/llms/three-js.js.map +1 -1
  83. package/llms/three-js.md +52 -18
  84. package/llms/touch-games.js +11 -11
  85. package/llms/touch-games.js.map +1 -1
  86. package/llms/touch-games.md +59 -354
  87. package/llms/types.d.ts +5 -0
  88. package/llms/ui-chat.js +2 -1
  89. package/llms/ui-chat.js.map +1 -1
  90. package/llms/ui-chat.md +25 -14
  91. package/llms/use-vibe.js +1 -0
  92. package/llms/use-vibe.js.map +1 -1
  93. package/llms/use-viewer.js +1 -0
  94. package/llms/use-viewer.js.map +1 -1
  95. package/llms/voxel.js +1 -0
  96. package/llms/voxel.js.map +1 -1
  97. package/llms/voxel.md +33 -109
  98. package/llms/web-audio.js +4 -21
  99. package/llms/web-audio.js.map +1 -1
  100. package/llms/web-audio.md +19 -951
  101. package/llms/web-music.d.ts +2 -0
  102. package/llms/web-music.js +8 -0
  103. package/llms/web-music.js.map +1 -0
  104. package/llms/web-music.md +895 -0
  105. package/llms/world-controls.d.ts +2 -0
  106. package/llms/world-controls.js +14 -0
  107. package/llms/world-controls.js.map +1 -0
  108. package/llms/world-controls.md +262 -0
  109. package/llms/worlds.js +2 -1
  110. package/llms/worlds.js.map +1 -1
  111. package/llms/worlds.md +5 -14
  112. package/package.json +5 -5
  113. package/prompts.js +5 -19
  114. package/prompts.js.map +1 -1
package/llms/web-audio.md CHANGED
@@ -1,25 +1,15 @@
1
- # Web Audio API: Fundamentals, Echo with FX-in-Feedback, Mic Monitoring + Metronome, Timing Architecture, and a Complete Drum Machine
1
+ # Web Audio API: fundamentals, and heavyweight engines that arrive by runtime import
2
2
 
3
3
  Authoritative source: Issue #228 research threads — comments 3192681700, 3192696052, 3192806626.
4
4
 
5
- > **Web Audio is a browser built-in.** Use `window.AudioContext` (with the
6
- > `window.webkitAudioContext` fallback) directly, gated on a user gesture as shown below.
7
- >
8
- > **iOS Safari: unlock audio synchronously inside the gesture.** WebKit requires
9
- > playback to *directly result* from a trusted handler (`pointerdown`, `touchend`,
10
- > `click`, `keydown`). Inside that handler you must, synchronously and before any
11
- > async work: create-or-resume the `AudioContext` **and start at least one real
12
- > sound** (a ~10ms blip at `gain ≈ 0.0001` is enough). A resume/start that runs
13
- > from a downstream `setTimeout`, `Promise.then`, `await`, `requestAnimationFrame`,
14
- > a React state-update→effect, a worker/scheduler task, or a media
15
- > `canplay`/`canplaythrough` callback **does not count** and will stay silent on
16
- > iOS. Once the context is `running`, all of those are fine for scheduling. iOS
17
- > also suspends audio after backgrounding/lock, so **re-check `audioCtx.state` on
18
- > every gesture** and resume again if needed. See the `unlockAudio()` gate in §1.
19
- >
20
- > **A drum machine, beat maker or step sequencer starts from §9** — a complete,
21
- > runnable one with a synthesized kit, sixteen steps, tempo, swing, saturation
22
- > and volume.
5
+ > **The context comes from the sound core above.** Its `unlockAudio()` gate runs
6
+ > first, synchronously, in the gesture, and it holds the iOS rules, short effects,
7
+ > the mute toggle and the restraint rule. Everything below builds on the context it
8
+ > returns. A worker/scheduler task or a media `canplay`/`canplaythrough` callback is
9
+ > as late as a timer for the first sound.
10
+
11
+ Music built on this context (a master bus, echo, a mic with a metronome, audio-clock
12
+ scheduling, a drum machine) is the `web-music` skill.
23
13
 
24
14
  ## 1) Fundamentals and Core Nodes
25
15
 
@@ -33,39 +23,8 @@ Authoritative source: Issue #228 research threads — comments 3192681700, 31926
33
23
  Examples
34
24
 
35
25
  ```js
36
- // 1) Context + iOS-safe unlock gate.
37
- let audioCtx;
38
- function unlockAudio() {
39
- audioCtx ||= new (window.AudioContext || window.webkitAudioContext)();
40
- // Re-check every gesture — iOS suspends audio after backgrounding/lock.
41
- if (audioCtx.state !== "running") {
42
- audioCtx.resume();
43
- // Start one real (silent) sound synchronously, inside the gesture, so WebKit
44
- // actually unlocks output. This is the part a resume()-alone often misses.
45
- const osc = audioCtx.createOscillator();
46
- const gain = audioCtx.createGain();
47
- gain.gain.value = 0.0001;
48
- osc.connect(gain).connect(audioCtx.destination);
49
- osc.start();
50
- osc.stop(audioCtx.currentTime + 0.01);
51
- }
52
- return audioCtx;
53
- }
54
-
55
- // Call unlockAudio() FIRST, synchronously, in a trusted gesture — before any
56
- // app/audio logic. After it returns, the context is running and timers,
57
- // requestAnimationFrame, sequencers, and workers are all safe to schedule with.
58
- document.querySelector("#start-audio")?.addEventListener("pointerdown", () => {
59
- unlockAudio();
60
- // now safe to create/start nodes, kick off the transport, etc.
61
- });
62
-
63
- // ✗ What breaks on iOS — the unlock does NOT count if audio first starts from a
64
- // downstream callback, because it no longer "directly results" from the gesture:
65
- // el.addEventListener("click", () => requestAnimationFrame(() => audioCtx.resume())); // risky
66
- // setTimeout(...), Promise.then(...), await fetch(...), await import(...),
67
- // a React state update then effect, a scheduler/task-queue callback, or a
68
- // media canplay/canplaythrough callback — all too late. Unlock in the handler.
26
+ // 1) The context: the sound core's unlockAudio(), called FIRST in the gesture.
27
+ const audioCtx = unlockAudio();
69
28
 
70
29
  // 2) Simple tone
71
30
  const osc = audioCtx.createOscillator();
@@ -96,264 +55,25 @@ osc.connect(filter).connect(gain).connect(audioCtx.destination);
96
55
 
97
56
  Practical: clean up disconnected nodes; check browser support; use headphones to avoid feedback when monitoring.
98
57
 
99
- ## 1b) Master bus — every audio toy ships Saturation and Volume
100
-
101
- Every audio toy ships one master bus with a Saturation control and a Volume control that act on everything it plays. A drum machine, a synth, a generative drone, a theremin: whatever the person asked for, these two sit in the main controls with plain labels, always visible, and they shape notes that are already sounding as well as the next ones.
102
-
103
- - Route every voice through one master `GainNode` and give the person a Volume control that sets its gain.
104
- - Put one `WaveShaperNode` on the master bus and give the person a Saturation control that sets how hard it drives.
105
-
106
- Graph: `voices → bus:GainNode → saturation:WaveShaperNode → master:GainNode → destination`. Build the bus once, next to the context, and connect each new voice to `bus` instead of `destination`. Saturation at zero is a clean pass-through, so the toy sounds the same until the person turns it up.
107
-
108
- ```js
109
- // Build once, beside the context (inside unlockAudio() or the engine's init).
110
- function makeSaturationCurve(amount) {
111
- // amount 0..1 → 0 is no curve at all (a true bypass; a straight-line curve would still
112
- // clamp summed voices above 1.0), 1 is hard tanh drive.
113
- if (amount === 0) return null;
114
- const k = amount * 50;
115
- const n = 1024;
116
- const curve = new Float32Array(n);
117
- for (let i = 0; i < n; i++) {
118
- const x = (i / (n - 1)) * 2 - 1;
119
- curve[i] = Math.tanh(k * x) / Math.tanh(k);
120
- }
121
- return curve;
122
- }
123
-
124
- const bus = audioCtx.createGain();
125
- const saturation = audioCtx.createWaveShaper();
126
- saturation.curve = makeSaturationCurve(0);
127
- saturation.oversample = "4x";
128
- const master = audioCtx.createGain();
129
- master.gain.value = 0.8;
130
- bus.connect(saturation).connect(master).connect(audioCtx.destination);
131
-
132
- // Every voice lands on the bus, never on destination directly.
133
- // voiceGain.connect(bus);
134
-
135
- // The two global controls.
136
- function setSaturation(amount) {
137
- saturation.curve = makeSaturationCurve(amount);
138
- }
139
- function setVolume(value) {
140
- master.gain.setTargetAtTime(value, audioCtx.currentTime, 0.02);
141
- }
142
- ```
143
-
144
- ```jsx
145
- import { Slider } from "@vibes.diy/ui/interactive";
146
-
147
- <Slider label="Saturation" min={0} max={1} step={0.01} value={[drive]} onChange={([v]) => { setDrive(v); setSaturation(v); }} />
148
- <Slider label="Volume" min={0} max={1} step={0.01} value={[volume]} onChange={([v]) => { setVolumeState(v); setVolume(v); }} />
149
- ```
58
+ ## 2) Practical Notes
150
59
 
151
- With an engine from §8, the same two controls sit on its output: a `Tone.Distortion` (or `Tone.Chebyshev`) before `Tone.Destination`, with Saturation setting the `Tone.Distortion`'s `distortion` (or the `Tone.Chebyshev`'s `order`), and Volume setting `Tone.Destination.volume`.
152
-
153
- ## 2) Echo/Delay with Effects Inside the Feedback Loop
154
-
155
- Graph (node names are exact):
156
-
157
- - Dry: `source → dryGain:GainNode → destination`
158
- - Wet: `source → delay:DelayNode → wetGain:GainNode → destination`
159
- - Feedback loop with FX: `delay → filter:BiquadFilterNode → distortion:WaveShaperNode → reverb:ConvolverNode → feedbackGain:GainNode → delay`
160
-
161
- Parameters to expose
162
-
163
- - `delay.delayTime` (s), `feedbackGain.gain` (0–1, keep < 1.0)
164
- - `filter.type`, `filter.frequency`
165
- - `distortion.curve` (Float32Array)
166
- - `convolver.buffer` (IR AudioBuffer)
167
- - `wetGain.gain`, `dryGain.gain`
168
-
169
- Notes: Prevent runaway by capping feedback below 1.0; `ConvolverNode` requires a loaded impulse response; zero-delay cycles are disallowed.
170
-
171
- ```js
172
- const delay = audioCtx.createDelay(5.0);
173
- const feedbackGain = audioCtx.createGain();
174
- const filter = audioCtx.createBiquadFilter();
175
- const distortion = audioCtx.createWaveShaper();
176
- const reverb = audioCtx.createConvolver();
177
- const wetGain = audioCtx.createGain();
178
- const dryGain = audioCtx.createGain();
179
-
180
- delay.delayTime.value = 0.35;
181
- feedbackGain.gain.value = 0.5; // < 1.0
182
- filter.type = "lowpass";
183
- filter.frequency.value = 8000;
184
- // distortion.curve = yourFloat32Curve;
185
- // reverb.buffer = yourImpulseResponseAudioBuffer;
186
- wetGain.gain.value = 0.4;
187
- dryGain.gain.value = 1.0;
188
-
189
- // Dry and wet
190
- source.connect(dryGain).connect(audioCtx.destination);
191
- source.connect(delay);
192
- delay.connect(wetGain).connect(audioCtx.destination);
193
-
194
- // Feedback with FX
195
- delay.connect(filter);
196
- filter.connect(distortion);
197
- distortion.connect(reverb);
198
- reverb.connect(feedbackGain);
199
- feedbackGain.connect(delay);
200
- ```
201
-
202
- Helper (load IR):
203
-
204
- ```js
205
- async function loadImpulseResponse(url) {
206
- const res = await fetch(url, { mode: "cors" });
207
- if (!res.ok) throw new Error(`Failed to fetch IR ${url}: ${res.status} ${res.statusText}`);
208
- const ab = await res.arrayBuffer();
209
- try {
210
- return await audioCtx.decodeAudioData(ab);
211
- } catch (err) {
212
- console.error("decodeAudioData failed for IR", url, err);
213
- throw err; // Surface decoding/CORS-related failures clearly
214
- }
215
- }
216
- ```
217
-
218
- ## 3) Microphone Monitoring + Metronome Overlay
219
-
220
- Mic capture: request permission with `navigator.mediaDevices.getUserMedia({ audio: { echoCancellation, noiseSuppression, autoGainControl } })`. Create `MediaStreamAudioSourceNode` and route to a `GainNode` → destination.
221
-
222
- Metronome: synthesize a short click (e.g., square/sine burst through a gain envelope). Schedule by audio clock at `AudioContext.currentTime` with lookahead.
223
-
224
- Mix graph: `micGain + metronomeGain → master → destination`.
225
-
226
- ```js
227
- const master = audioCtx.createGain();
228
- master.connect(audioCtx.destination);
229
- const micGain = audioCtx.createGain();
230
- const metronomeGain = audioCtx.createGain();
231
- micGain.connect(master);
232
- metronomeGain.connect(master);
233
-
234
- async function initMic() {
235
- const stream = await navigator.mediaDevices.getUserMedia({
236
- audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: false },
237
- });
238
- const micSrc = audioCtx.createMediaStreamSource(stream);
239
- micSrc.connect(micGain);
240
- }
241
-
242
- function scheduleClick(atTime, downbeat = false) {
243
- const osc = audioCtx.createOscillator();
244
- const env = audioCtx.createGain();
245
- osc.type = "square";
246
- osc.frequency.setValueAtTime(downbeat ? 2000 : 1600, atTime);
247
- env.gain.setValueAtTime(0.0001, atTime);
248
- env.gain.exponentialRampToValueAtTime(1.0, atTime + 0.001);
249
- env.gain.exponentialRampToValueAtTime(0.0001, atTime + 0.03);
250
- osc.connect(env).connect(metronomeGain);
251
- osc.start(atTime);
252
- osc.stop(atTime + 0.05);
253
- // Cleanup to avoid accumulating nodes during long sessions
254
- osc.onended = () => {
255
- try {
256
- osc.disconnect();
257
- } catch {}
258
- try {
259
- env.disconnect();
260
- } catch {}
261
- };
262
- }
263
-
264
- function startMetronome({ bpm = 120, beatsPerBar = 4 } = {}) {
265
- const spb = 60 / bpm; // seconds per beat
266
- let next = audioCtx.currentTime + 0.1;
267
- let beat = 0;
268
- const lookaheadMs = 25,
269
- ahead = 0.2;
270
- const id = setInterval(() => {
271
- while (next < audioCtx.currentTime + ahead) {
272
- scheduleClick(next, beat % beatsPerBar === 0);
273
- next += spb;
274
- beat = (beat + 1) % beatsPerBar;
275
- }
276
- }, lookaheadMs);
277
- return () => clearInterval(id);
278
- }
279
- ```
280
-
281
- Latency and safety: start/resume on user gesture; clean up per-tick nodes after `ended` to prevent buildup in long-running metronomes; use headphones while monitoring; mobile devices have higher base latency.
282
-
283
- ## 4) Time Synchronization and Scheduling Model
284
-
285
- Clocks/time domains
286
-
287
- - Master: `AudioContext.currentTime` — sample-accurate; schedule everything on this timeline.
288
- - UI/high-res: `performance.now()` — for UI timers and Web MIDI timestamps.
289
- - Mapping: capture `(tPerf0 = performance.now(), tAudio0 = audioCtx.currentTime)`, convert MIDI/perf timestamps with `tAudio = tAudio0 + (timeStamp - tPerf0)/1000`.
290
- - Hints: `audioCtx.baseLatency`, `audioCtx.getOutputTimestamp?.()` — estimate DAC/output delay if aligning to “heard” time.
291
-
292
- Scheduling primitives
293
-
294
- - `AudioBufferSourceNode.start(when, offset?, duration?)` for one-shots/loops.
295
- - `AudioParam` automation (`setValueAtTime`, `linearRampToValueAtTime`, `setTargetAtTime`, `setValueCurveAtTime`).
296
- - Avoid `requestAnimationFrame`/`setTimeout` for timing; use an AudioWorklet for custom DSP/tight jitter when needed.
297
-
298
- Tempo transport and lookahead
299
-
300
- - Tempo mapping: `secondsPerBeat = 60 / bpm`; compute bars:beats:ticks → seconds on the audio clock (choose PPQ, e.g., 480/960).
301
- - Lookahead window: maintain ~50–200 ms rolling schedule; enqueue with absolute `when` times in audio seconds.
302
-
303
- Multi‑channel sample playback
304
-
305
- - Pre‑decode all samples; never decode on hit.
306
- - Per hit: create a fresh `AudioBufferSourceNode` and call `.start(when)`.
307
- - For phase‑aligned layers (kick+clap, etc.), schedule all sources with the same `when` to guarantee sample‑accurate overlap.
308
- - Routing: per‑track `GainNode`/optional FX → master bus; allow overlapping retriggers; compute flams as small `when` offsets.
309
- - Pattern changes: compute the next bar boundary on the audio clock and enqueue new pattern hits relative to that time.
310
-
311
- MIDI synth playback
312
-
313
- - Live input: map `MIDIMessageEvent.timeStamp` (perf.now domain) → audio clock as above; buffer a short lookahead (5–20 ms) to reduce jitter.
314
- - SMF playback: convert PPQ ticks using the tempo map; schedule noteOn/noteOff separately; sustain (CC64) defers noteOff until pedal release.
315
- - Voice management: one voice per active note; allow overlapping envelopes; define voice‑steal policy if a polyphony cap is hit.
316
-
317
- External sync and drift
318
-
319
- - For MIDI Clock/MTC, derive BPM/phase from incoming ticks, convert to audio time, and drive the transport. Correct small phase error between beats with bounded micro‑nudges—avoid discontinuities.
320
-
321
- ## 5) Practical Notes
322
-
323
- - User gesture required to start/resume `AudioContext` and to access the mic. On
324
- iOS Safari the unlock must be **synchronous inside the gesture and start one
325
- real sound** (the `unlockAudio()` gate in §1); a resume from a downstream
326
- timer/promise/`await`/rAF/effect/media callback is too late. Re-check
327
- `audioCtx.state` on every gesture, since iOS suspends audio after
328
- backgrounding/lock.
60
+ - User gesture required to start/resume `AudioContext` (the sound core's
61
+ `unlockAudio()` gate) and to access the mic.
329
62
  - Convolver IRs: host with CORS if cross‑origin; decode before use.
330
63
  - Latency budget: device `baseLatency` + your lookahead + any Worklet buffering.
331
64
  - Headphones recommended for monitoring to avoid acoustic feedback.
332
65
 
333
- ## 6) File layout — audio apps split, proactively
334
-
335
- Audio apps run long: an engine (context/graph/scheduler), a playable surface (keyboard, pads, step grid), transport/parameter controls, and a preset list each carry real code. A single-file synth blows past the ~500-line `App.jsx` split threshold almost immediately — so split from the start rather than after the fact. The sandbox serves raw ES modules: relative imports work, local `.css` imports do not (style stays in `App.jsx`).
336
-
337
- The shape that works (filenames illustrative — split by responsibility, matched to the app's actual surfaces, not by count):
66
+ ## 3) Restraint
338
67
 
339
- - `lib/audio-engine.js` — everything that touches `AudioContext`: the `unlockAudio()` gate, node graph construction, voice management, the lookahead scheduler. Plain module, no React; export functions/objects the UI calls. Keeping the engine React-free is what makes gesture-synchronous unlock (§1) and clean scheduling (§4) easy — no re-render can rebuild the graph.
340
- - `components/Keyboard.jsx` (or `StepGrid.jsx`, `Pads.jsx`) — the playable surface; calls engine functions from `pointerdown`-family handlers.
341
- - `components/TransportControls.jsx`, `components/PresetList.jsx` — parameter knobs/sliders and preset browsing; presets live in the database, the engine consumes plain parameter objects.
342
- - `App.jsx` — layout, styling, database wiring; imports the above (`import { createEngine } from "./lib/audio-engine.js"`).
68
+ The sound core's restraint rule holds here too: an audio toy plays what the person plays, and an app whose sound is feedback keeps it to the core actions.
343
69
 
344
- ## 7) Restraint — sound belongs on the core actions
345
-
346
- - No sound on every keystroke, hover, or list render — that reads as noise, not life.
347
- - Never autoplay audio on load; playback must follow a user gesture (the `unlockAudio()` gate in §1).
348
- - Wire brief feedback to the app's one or two satisfying core actions — the "it worked" beats (a point scored, a post landing, a match made) — and route it through the resume-on-user-gesture unlock so it sounds on mobile. Quiet/utility apps skip audio entirely.
349
-
350
- ## 8) Heavyweight audio engines arrive by runtime import
70
+ ## 4) Heavyweight audio engines arrive by runtime import
351
71
 
352
72
  Music written as text patterns — Strudel, Tidal-style mini-notation, a groovebox whose pads write a pattern — has its own skill, `strudel`, built on the same runtime-import shape; this section is the general rule for any engine.
353
73
 
354
74
  When the app needs a serious sound engine — sampled drums, a full synth framework — rather than hand-built oscillators, import the engine with its full pinned esm.sh URL in a memoized module-level loader, and call that loader only from a user gesture. Laziness is doing two jobs here: a body-position `await import("engine-name")` with a bare specifier ships unrewritten — the import rewrite covers only the top-of-file import region — and dies at runtime with `Failed to resolve module specifier`, so the specifier is the complete versioned URL; and an engine plus its sample bank stays off first paint entirely.
355
75
 
356
- The gesture handler unlocks synchronously FIRST, before any await: call `unlockAudio()` (§1) at the top of the handler and keep its return — the context the gesture unlocked. Then await the loader, and bind the engine to that SAME context before creating any voice: `Tone.setContext(ctx)` drives the engine on the already-running context, and `Tone.getContext().rawContext === ctx` verifies the identity. Without the bind, `Tone.start()` resumes a context the engine created lazily after the await — a different context from the one the gesture unlocked. Verified on desktop Chromium; on mobile the engine's first sound still follows the loader's await, so claim only what desktop evidence shows (iOS counts a synchronous start inside the gesture, and a lazily imported engine starts after an await).
76
+ The gesture handler unlocks synchronously FIRST, before any await: call `unlockAudio()` (the sound core) at the top of the handler and keep its return — the context the gesture unlocked. Then await the loader, and bind the engine to that SAME context before creating any voice: `Tone.setContext(ctx)` drives the engine on the already-running context, and `Tone.getContext().rawContext === ctx` verifies the identity. Without the bind, `Tone.start()` resumes a context the engine created lazily after the await — a different context from the one the gesture unlocked. Verified on desktop Chromium; on mobile the engine's first sound still follows the loader's await, so claim only what desktop evidence shows (iOS counts a synchronous start inside the gesture, and a lazily imported engine starts after an await).
357
77
 
358
78
  A stop control silences everything — pending playback, retained voices, the transport and its future callbacks. Plays and stops share one generation counter: Stop increments it, and a playback still awaiting the loader checks it after every await and stays silent when it moved — otherwise Play → Stop → load-resolves creates and plays a voice after Stop cleared the set. Then release the retained voices and stop/cancel the transport: stopping the transport alone leaves sounding voices droning on.
359
79
 
@@ -376,7 +96,7 @@ let playEpoch = 0;
376
96
 
377
97
  ```js
378
98
  async function handlePlay() {
379
- const ctx = unlockAudio(); // §1 gate — synchronous, in the gesture
99
+ const ctx = unlockAudio(); // the sound core's gate — synchronous, in the gesture
380
100
  const myTurn = playEpoch;
381
101
  const Tone = await loadTone();
382
102
  if (myTurn !== playEpoch) return; // Stop ran while loading — stay silent
@@ -412,655 +132,3 @@ function handleStop() {
412
132
  ```
413
133
 
414
134
  The Play button names what it plays ("Play the drums"), the Stop button is beside it from the first sound, and a small line credits the engine ("Sounds by Tone.js (MIT)") — the audience hears drums, not infrastructure.
415
-
416
- ## 9) A complete drum machine — the shell every beat vibe starts from
417
-
418
- Build the first version of any beat app (a drum machine, beat maker, step
419
- sequencer or groovebox) from this section: the engine as written, and an
420
- instrument face whose picks you choose (§ "Make it yours" below). The
421
- `data-instrument` panel is how a drum machine looks from its very first build,
422
- under any look, layout or skin the turn also carries. The `App.jsx` below
423
- holds the parts every arrangement shares, followed by three short arrangement
424
- sketches: pick one and write the app around it.
425
-
426
- This is a two-file kit: a synthesized four-voice kit (kick,
427
- snare, closed and open hat), a sixteen-step sequencer, tempo and swing, and
428
- global saturation and volume on the master bus. No samples, no downloads —
429
- every sound is built from oscillators and noise, so it plays the moment the
430
- person taps. Start here for any drum machine, beat maker, step sequencer or groovebox and grow
431
- it: more voices, more steps, accents, pattern banks.
432
-
433
- Why it sounds good, in four moves:
434
-
435
- - **Kick** — a sine that sweeps 150 Hz → 55 Hz in 50 ms, then settles to 45 Hz:
436
- the sweep is the punch, the tail is the boom. A few milliseconds of
437
- band-passed noise on top is the beater, so the kick still reads on phone
438
- speakers that cannot reproduce 45 Hz.
439
- - **Snare** — two tuned triangle "shell" tones under high-passed noise with a
440
- presence lift at 5 kHz for the wires.
441
- - **Hats** — the 808 recipe: six square waves at inharmonic ratios of 40 Hz,
442
- band-passed at 10 kHz and high-passed at 7 kHz. A closed hat chokes a ringing
443
- open hat through the open hat's own gate gain, like the real machine.
444
- - **Master bus** — voices → bus (headroom) → drive gain → `tanh` WaveShaper
445
- (4× oversampled, so the new harmonics do not alias into fizz) → makeup gain →
446
- volume → a fast `DynamicsCompressor` as a limiter. The makeup gain falls as
447
- the drive rises, so Saturation changes the colour, not the loudness; Volume
448
- is squared so the slider feels even.
449
-
450
- The engine is a plain module (§6): the gate from §1, the lookahead scheduler
451
- from §4, and a `playhead()` the interface polls each animation frame, so the
452
- lit step follows what is reaching the speakers rather than the timer. The steps
453
- are `StepGrid` rows of `Pad`s from `@vibes.diy/ui/interactive`: square pads
454
- in beats of four, a light on the playing step, sixteen across on a laptop and
455
- eight a line on a phone. A pad is an instrument's square, so the grid reads as a
456
- drum machine, never as a column of settings toggles; a single `Pad` is the
457
- finger-drumming pad of an MPC-style kit or a launch cell. The
458
- interface calls `getDrums()` synchronously at the top of every tap handler —
459
- Play, and each step — which is what unlocks sound on iOS.
460
-
461
- ### `lib/drum-engine.js`
462
- ```js
463
- // Everything that touches AudioContext lives here — no React, so a re-render never rebuilds the graph.
464
- export const STEPS = 16;
465
- export const TRACKS = [
466
- { id: "kick", label: "Kick" },
467
- { id: "snare", label: "Snare" },
468
- { id: "closed", label: "Closed hat" },
469
- { id: "open", label: "Open hat" },
470
- ];
471
-
472
- let audioCtx;
473
- let drums;
474
-
475
- // §1's gate: synchronous, inside the tap, with one real (silent) sound.
476
- function unlockAudio() {
477
- audioCtx ||= new (window.AudioContext || window.webkitAudioContext)();
478
- if (audioCtx.state !== "running") {
479
- audioCtx.resume();
480
- const osc = audioCtx.createOscillator();
481
- const gain = audioCtx.createGain();
482
- gain.gain.value = 0.0001;
483
- osc.connect(gain).connect(audioCtx.destination);
484
- osc.start();
485
- osc.stop(audioCtx.currentTime + 0.01);
486
- }
487
- return audioCtx;
488
- }
489
-
490
- // Call from a tap handler, synchronously: unlocks audio and builds the one engine on that context.
491
- export function getDrums() {
492
- const ctx = unlockAudio();
493
- drums ||= createDrums(ctx);
494
- return drums;
495
- }
496
-
497
- function createDrums(ctx) {
498
- const settings = { pattern: {}, bpm: 112, swing: 0, drive: 0.3, volume: 0.8 };
499
-
500
- // Master chain: voices → bus → drive → tanh shaper → makeup → volume → limiter → speakers.
501
- const bus = ctx.createGain();
502
- const drive = ctx.createGain();
503
- const shaper = ctx.createWaveShaper();
504
- const makeup = ctx.createGain();
505
- const volume = ctx.createGain();
506
- const limiter = ctx.createDynamicsCompressor();
507
- bus.gain.value = 0.7; // headroom: a kick and a hat on the same step stay under full scale
508
- shaper.curve = tanhCurve(MAX_DRIVE);
509
- shaper.oversample = "4x"; // keeps the new harmonics from folding back down as fizz
510
- limiter.threshold.value = -3;
511
- limiter.knee.value = 0;
512
- limiter.ratio.value = 20;
513
- limiter.attack.value = 0.002;
514
- limiter.release.value = 0.1;
515
- bus.connect(drive).connect(shaper).connect(makeup).connect(volume).connect(limiter).connect(ctx.destination);
516
-
517
- const noise = noiseBuffer(ctx);
518
- const live = new Set(); // every scheduled source and its start time, so Stop can cancel the future
519
- let openChoke = null; // the ringing open hat's gate — a closed hat shuts it, like the real machine
520
-
521
- function chokeOpen(at) {
522
- openChoke?.gain.setTargetAtTime(0, at, 0.006);
523
- openChoke = null;
524
- }
525
-
526
- function play(source, at, end, nodes = []) {
527
- const entry = { source, at };
528
- live.add(entry);
529
- source.onended = () => {
530
- live.delete(entry);
531
- source.disconnect();
532
- for (const node of nodes) node.disconnect();
533
- };
534
- source.start(at);
535
- source.stop(end);
536
- }
537
-
538
- // A percussive envelope: 2 ms attack, exponential decay to silence.
539
- function envelope(at, peak, decay, out = bus) {
540
- const amp = ctx.createGain();
541
- amp.gain.setValueAtTime(0.0001, at);
542
- amp.gain.exponentialRampToValueAtTime(peak, at + 0.002);
543
- amp.gain.exponentialRampToValueAtTime(0.0001, at + decay);
544
- amp.connect(out);
545
- return amp;
546
- }
547
-
548
- function filter(type, frequency, q = 0.7) {
549
- const node = ctx.createBiquadFilter();
550
- node.type = type;
551
- node.frequency.value = frequency;
552
- node.Q.value = q;
553
- return node;
554
- }
555
-
556
- // 808-style metal: six square waves at inharmonic ratios, band-passed high.
557
- function hat(at, decay, peak, out) {
558
- const band = filter("bandpass", 10000);
559
- const high = filter("highpass", 7000);
560
- const amp = envelope(at, peak, decay, out);
561
- band.connect(high).connect(amp);
562
- [2, 3, 4.16, 5.43, 6.79, 8.21].forEach((ratio, i) => {
563
- const osc = ctx.createOscillator();
564
- osc.type = "square";
565
- osc.frequency.value = 40 * ratio;
566
- osc.connect(band);
567
- play(osc, at, at + decay + 0.02, i === 0 ? [band, high, amp] : []);
568
- });
569
- }
570
-
571
- const voices = {
572
- kick(at) {
573
- // A sine that drops from 150 Hz to 45 Hz: the pitch sweep is the punch, the tail is the boom.
574
- const body = ctx.createOscillator();
575
- body.frequency.setValueAtTime(150, at);
576
- body.frequency.exponentialRampToValueAtTime(55, at + 0.05);
577
- body.frequency.exponentialRampToValueAtTime(45, at + 0.4);
578
- const amp = envelope(at, 1, 0.5);
579
- body.connect(amp);
580
- play(body, at, at + 0.55, [amp]);
581
- // The beater: a few ms of filtered noise, so the kick still reads on phone speakers.
582
- const click = ctx.createBufferSource();
583
- click.buffer = noise;
584
- const tone = filter("bandpass", 3500, 0.8);
585
- const clickAmp = envelope(at, 0.3, 0.012);
586
- click.connect(tone).connect(clickAmp);
587
- play(click, at, at + 0.03, [tone, clickAmp]);
588
- },
589
- snare(at) {
590
- // Two tuned shell tones under a bright burst of noise for the wires.
591
- for (const [freq, level] of [[185, 0.45], [330, 0.25]]) {
592
- const shell = ctx.createOscillator();
593
- shell.type = "triangle";
594
- shell.frequency.setValueAtTime(freq, at);
595
- shell.frequency.exponentialRampToValueAtTime(freq * 0.85, at + 0.1);
596
- const amp = envelope(at, level, 0.14);
597
- shell.connect(amp);
598
- play(shell, at, at + 0.16, [amp]);
599
- }
600
- const wires = ctx.createBufferSource();
601
- wires.buffer = noise;
602
- const high = filter("highpass", 1500);
603
- const air = filter("peaking", 5000);
604
- air.gain.value = 6;
605
- const amp = envelope(at, 0.6, 0.22);
606
- wires.connect(high).connect(air).connect(amp);
607
- play(wires, at, at + 0.25, [high, air, amp]);
608
- },
609
- closed(at) {
610
- chokeOpen(at);
611
- hat(at, 0.06, 0.32, bus);
612
- },
613
- open(at) {
614
- chokeOpen(at); // one open hat at a time, so the next closed hat always silences it
615
- openChoke = ctx.createGain();
616
- openChoke.connect(bus);
617
- hat(at, 0.45, 0.24, openChoke);
618
- },
619
- };
620
-
621
- // The scheduler: a 25 ms timer tops up 120 ms of sound ahead of the audio clock (§4).
622
- const LOOKAHEAD = 0.12;
623
- let timer = 0;
624
- let step = 0;
625
- let gridTime = 0;
626
- let lit = -1;
627
- const lights = []; // { step, at }: the playhead follows the sound, not the timer
628
-
629
- function tick() {
630
- const sixteenth = 60 / settings.bpm / 4;
631
- // A throttled background tab can fall far behind the audio clock: skip the missed steps
632
- // (keeping the beat's phase) instead of scheduling a burst of hits in the past.
633
- if (gridTime < ctx.currentTime) {
634
- const missed = Math.ceil((ctx.currentTime - gridTime) / sixteenth);
635
- gridTime += missed * sixteenth;
636
- step = (step + missed) % STEPS;
637
- }
638
- while (gridTime < ctx.currentTime + LOOKAHEAD) {
639
- // Swing pushes every off-beat sixteenth late; 1 is a full triplet shuffle.
640
- const at = gridTime + (step % 2 ? (settings.swing * sixteenth) / 3 : 0);
641
- for (const { id } of TRACKS) if (settings.pattern[id]?.[step]) voices[id](at);
642
- lights.push({ step, at });
643
- gridTime += sixteenth;
644
- step = (step + 1) % STEPS;
645
- }
646
- }
647
-
648
- function update(next) {
649
- Object.assign(settings, next);
650
- const now = ctx.currentTime;
651
- // Drive 0 is warm, 1 is crunchy. Makeup gain keeps loudness level as the drive rises,
652
- // so the slider changes the colour, not the volume.
653
- const gain = 1 + settings.drive * (MAX_DRIVE - 1);
654
- drive.gain.setTargetAtTime(gain / MAX_DRIVE, now, 0.02);
655
- makeup.gain.setTargetAtTime(1.3 / Math.sqrt(gain), now, 0.02);
656
- volume.gain.setTargetAtTime(settings.volume ** 2, now, 0.02); // squared, so the slider feels even
657
- }
658
- update({});
659
-
660
- return {
661
- update,
662
- start() {
663
- if (timer) return;
664
- step = 0;
665
- gridTime = ctx.currentTime + 0.05;
666
- tick();
667
- timer = setInterval(tick, 25);
668
- },
669
- stop() {
670
- clearInterval(timer);
671
- timer = 0;
672
- lights.length = 0;
673
- lit = -1;
674
- // Cancel every hit that is scheduled but not yet sounding; ringing tails finish on their own.
675
- for (const entry of live) if (entry.at > ctx.currentTime) entry.source.stop();
676
- },
677
- // Audition one sound now — a tap on a step while stopped.
678
- hit(id) {
679
- voices[id](ctx.currentTime + 0.005);
680
- },
681
- // The newest step whose sound has reached the speakers; poll it from requestAnimationFrame.
682
- playhead() {
683
- // currentTime is what the engine has rendered; subtract the output latency for what is heard
684
- // (it matters on Bluetooth headphones).
685
- const heard = ctx.currentTime - (ctx.outputLatency || ctx.baseLatency || 0);
686
- while (lights.length && lights[0].at <= heard) lit = lights.shift().step;
687
- return lit;
688
- },
689
- };
690
- }
691
-
692
- const MAX_DRIVE = 10;
693
-
694
- // tanh(MAX_DRIVE·x) across the shaper's −1…1 input; the drive gain picks how far up the curve we go.
695
- function tanhCurve(k) {
696
- const curve = new Float32Array(4096);
697
- for (let i = 0; i < curve.length; i++) curve[i] = Math.tanh(k * ((i / (curve.length - 1)) * 2 - 1));
698
- return curve;
699
- }
700
-
701
- function noiseBuffer(ctx) {
702
- const buffer = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate);
703
- const data = buffer.getChannelData(0);
704
- for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
705
- return buffer;
706
- }
707
- ```
708
-
709
- A tap on a step toggles it, and while stopped it plays that sound so the
710
- person hears what they placed. Every knob writes through to the engine, and
711
- the scheduler reads the settings on its next step, so edits land in time
712
- without a restart. Grooves save to the database as one document each; the
713
- save button waits on `can.create`, the same verdict the server enforces.
714
-
715
- ### `App.jsx`
716
- ```jsx
717
- // The parts every arrangement shares. `App` composes them with one of the three arrangements below.
718
- import React, { useEffect, useRef, useState } from "react";
719
- import { Button, Row, Spacer, Stack } from "@vibes.diy/ui";
720
- import { StepGrid } from "@vibes.diy/ui/interactive";
721
- import { STEPS, TRACKS, getDrums } from "./lib/drum-engine.js";
722
-
723
- const START = {
724
- kick: [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
725
- snare: [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
726
- closed: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0],
727
- open: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
728
- };
729
-
730
- const FACE = `
731
- /* picks: arrangement = … · pad = … · panel = … · led = … · transport = … (name yours; this sheet's defaults are square key, brushed, --info) */
732
- [data-instrument] {
733
- --panel: color-mix(in oklab, var(--surface) 80%, var(--ink));
734
- --well: color-mix(in oklab, var(--surface) 75%, var(--ink));
735
- --screen: color-mix(in oklab, var(--surface) 88%, var(--ink));
736
- --led: var(--info);
737
- --pad-off: color-mix(in oklab, var(--surface) 90%, var(--ink));
738
- position: relative; display: grid; gap: var(--s3); padding: var(--s5) var(--s3) var(--s3);
739
- border: 2px solid var(--ink); border-radius: var(--r-card); color: var(--ink);
740
- background: repeating-linear-gradient(90deg, var(--panel) 0 2px, color-mix(in oklab, var(--panel) 92%, var(--surface)) 2px 4px);
741
- box-shadow: inset 0 1px 0 color-mix(in oklab, var(--surface) 60%, transparent), 0 6px 0 color-mix(in oklab, var(--ink) 70%, transparent);
742
- }
743
- [data-instrument] .ix-screw { position: absolute; width: 10px; height: 10px; border-radius: 50%; border: 1px solid var(--ink);
744
- background: radial-gradient(circle at 35% 35%, var(--surface), var(--well)); }
745
- [data-instrument] .ix-screw--tl { top: 8px; left: 8px; } [data-instrument] .ix-screw--tr { top: 8px; right: 8px; }
746
- [data-instrument] .ix-screw--bl { bottom: 8px; left: 8px; } [data-instrument] .ix-screw--br { bottom: 8px; right: 8px; }
747
- [data-instrument] .ix-plate { justify-self: start; padding: 4px 10px; border: 1px solid var(--ink); border-radius: var(--r-control);
748
- background: var(--surface); font: 700 12px/1.3 var(--font-family); letter-spacing: .16em; text-transform: uppercase; }
749
- [data-instrument] .ix-label { font-size: 11px; letter-spacing: .14em; text-transform: uppercase; color: color-mix(in oklab, var(--ink) 75%, var(--panel)); }
750
- [data-instrument] .ix-well { display: grid; gap: var(--s2); padding: var(--s2); border-radius: var(--r-control); background: var(--well);
751
- box-shadow: inset 0 2px 5px color-mix(in oklab, var(--ink) 45%, transparent); }
752
- [data-instrument] .ix-lcd { padding: 4px 10px; border-radius: 4px; border: 1px solid var(--ink); background: var(--screen);
753
- box-shadow: inset 0 2px 4px color-mix(in oklab, var(--ink) 35%, transparent); font: 700 18px/1.2 ui-monospace, monospace;
754
- font-variant-numeric: tabular-nums; color: color-mix(in oklab, var(--ink) 80%, var(--led));
755
- text-shadow: 0 0 6px color-mix(in oklab, var(--led) 50%, transparent); }
756
- [data-instrument] .ix-lights { display: grid; grid-template-columns: repeat(16, 1fr); gap: 4px; }
757
- [data-instrument] .ix-light { height: 6px; border-radius: 3px; background: color-mix(in oklab, var(--led) 18%, var(--well)); }
758
- [data-instrument] .ix-light[data-on] { background: var(--led); box-shadow: 0 0 8px var(--led); }
759
- [data-instrument] .ui-pad { border: 1px solid var(--ink); border-radius: 4px; box-shadow: 0 3px 0 var(--ink); }
760
- [data-instrument] .ui-pad[data-state="off"] { background: var(--pad-off); }
761
- [data-instrument] .ui-pad[data-state="on"][data-group="0"] { background: var(--purple); }
762
- [data-instrument] .ui-pad[data-state="on"][data-group="1"] { background: var(--orange); }
763
- [data-instrument] .ui-pad[data-state="on"][data-group="2"] { background: var(--up); }
764
- [data-instrument] .ui-pad[data-state="on"][data-group="3"] { background: color-mix(in oklab, var(--purple) 50%, var(--orange)); }
765
- [data-instrument] .ui-pad[data-state="on"] .ui-pad__led { background: var(--on-accent); box-shadow: 0 0 8px var(--on-accent); }
766
- [data-instrument] .ui-pad__ring { box-shadow: inset 0 0 0 3px var(--led), 0 0 10px var(--led); }
767
- [data-instrument] .ix-knob { display: grid; justify-items: center; gap: 4px; }
768
- [data-instrument] .ix-knob__cap { position: relative; width: 56px; height: 56px; border-radius: 50%; border: 2px solid var(--ink);
769
- touch-action: none; cursor: ns-resize; box-shadow: 0 3px 0 var(--ink);
770
- background: radial-gradient(circle at 40% 35%, color-mix(in oklab, var(--surface) 92%, var(--ink)), var(--well) 72%);
771
- transform: rotate(calc(-135deg + var(--turn) * 270deg)); }
772
- [data-instrument] .ix-knob__cap::after { content: ""; position: absolute; left: calc(50% - 2px); top: 5px; width: 4px; height: 16px;
773
- border-radius: 2px; background: var(--led); box-shadow: 0 0 6px var(--led); }
774
- [data-instrument] .ix-knob__cap:focus-visible { outline: 3px solid var(--ink); outline-offset: 3px; }
775
- /* arrangement helpers: a pad grid lays one voice's steps four by four; a rack stacks voice units */
776
- [data-instrument] .ix-grid4 .ui-stepgrid { --ui-steps: 4; --ui-steps-narrow: 4; }
777
- [data-instrument] .ix-voices { display: grid; grid-template-columns: repeat(2, 1fr); gap: var(--s2); }
778
- [data-instrument] .ix-unit { position: relative; display: grid; gap: var(--s2); padding: var(--s3); border: 1px solid var(--ink);
779
- border-radius: var(--r-control); background: var(--well); }
780
- `;
781
-
782
- // A knob turns: drag up to raise it, arrow keys step it. Its value shows on a small readout.
783
- function Knob({ label, value, min, max, shown, onChange }) {
784
- const drag = useRef(null);
785
- const clamp = (v) => Math.min(max, Math.max(min, Math.round(v)));
786
- const turn = { "--turn": (value - min) / (max - min) };
787
- return (
788
- <div className="ix-knob">
789
- <div
790
- role="slider"
791
- tabIndex={0}
792
- aria-label={label}
793
- aria-valuemin={min}
794
- aria-valuemax={max}
795
- aria-valuenow={value}
796
- className="ix-knob__cap"
797
- style={turn}
798
- onPointerDown={(e) => {
799
- e.currentTarget.setPointerCapture(e.pointerId);
800
- drag.current = { y: e.clientY, v: value };
801
- }}
802
- onPointerMove={(e) => drag.current && onChange(clamp(drag.current.v + ((drag.current.y - e.clientY) / 160) * (max - min)))}
803
- onPointerUp={() => (drag.current = null)}
804
- onPointerCancel={() => (drag.current = null)}
805
- onKeyDown={(e) => {
806
- const d = { ArrowUp: 1, ArrowRight: 1, ArrowDown: -1, ArrowLeft: -1 }[e.key];
807
- if (d) {
808
- e.preventDefault();
809
- onChange(clamp(value + d));
810
- }
811
- }}
812
- />
813
- <span className="ix-label">{label}</span>
814
- <span className="ix-lcd">{shown}</span>
815
- </div>
816
- );
817
- }
818
-
819
- // The engine wiring every arrangement shares: state, the iOS unlock, and a playhead that follows the sound.
820
- function useDrumMachine() {
821
- const [grid, setGrid] = useState(START);
822
- const [bpm, setBpm] = useState(112);
823
- const [swing, setSwing] = useState(0);
824
- const [drive, setDrive] = useState(30);
825
- const [volume, setVolume] = useState(80);
826
- const [playing, setPlaying] = useState(false);
827
- const [step, setStep] = useState(-1);
828
- const drumsRef = useRef(null);
829
- const settings = { pattern: grid, bpm, swing: swing / 100, drive: drive / 100, volume: volume / 100 };
830
-
831
- useEffect(() => {
832
- drumsRef.current?.update(settings);
833
- }, [grid, bpm, swing, drive, volume]);
834
- useEffect(() => () => drumsRef.current?.stop(), []);
835
- useEffect(() => {
836
- if (!playing) return;
837
- let raf = 0;
838
- const frame = () => {
839
- setStep(drumsRef.current.playhead());
840
- raf = requestAnimationFrame(frame);
841
- };
842
- raf = requestAnimationFrame(frame);
843
- return () => cancelAnimationFrame(raf);
844
- }, [playing]);
845
-
846
- // Called synchronously at the top of every tap handler: that is what unlocks audio on iOS.
847
- function drums() {
848
- const engine = getDrums();
849
- if (!drumsRef.current) engine.update(settings);
850
- drumsRef.current = engine;
851
- return engine;
852
- }
853
- function togglePlay() {
854
- const engine = drums();
855
- if (playing) {
856
- engine.stop();
857
- setStep(-1);
858
- } else engine.start();
859
- setPlaying(!playing);
860
- }
861
- function toggleStep(track, i) {
862
- const engine = drums();
863
- const on = !grid[track][i];
864
- setGrid({ ...grid, [track]: grid[track].map((v, j) => (j === i ? (on ? 1 : 0) : v)) });
865
- if (on && !playing) engine.hit(track); // hear the sound you just placed
866
- }
867
- const hit = (track) => drums().hit(track);
868
- const clear = () => setGrid(Object.fromEntries(TRACKS.map(({ id }) => [id, Array(STEPS).fill(0)])));
869
- return { grid, setGrid, bpm, setBpm, swing, setSwing, drive, setDrive, volume, setVolume, playing, step, togglePlay, toggleStep, hit, clear };
870
- }
871
-
872
- // Four corner screws; a rack unit carries its own set.
873
- function Screws() {
874
- return ["tl", "tr", "bl", "br"].map((at) => <span key={at} className={`ix-screw ix-screw--${at}`} aria-hidden="true" />);
875
- }
876
-
877
- // The panel itself: bezel, sheet, screws and a printed name plate.
878
- function Panel({ label, plate, children }) {
879
- return (
880
- <section data-instrument aria-label={label}>
881
- <style>{FACE}</style>
882
- <Screws />
883
- <span className="ix-plate">{plate}</span>
884
- {children}
885
- </section>
886
- );
887
- }
888
-
889
- // Sixteen step lights; the lit one follows the playhead.
890
- function Lights({ step }) {
891
- return (
892
- <div className="ix-lights" aria-hidden="true">
893
- {Array.from({ length: STEPS }, (_, i) => (
894
- <span key={i} className="ix-light" data-on={i === step || undefined} />
895
- ))}
896
- </div>
897
- );
898
- }
899
-
900
- // Play, Clear and the tempo readout.
901
- function Transport({ m }) {
902
- return (
903
- <Row gap={3} align="center" wrap>
904
- <Button onClick={m.togglePlay}>{m.playing ? "Stop" : "Play"}</Button>
905
- <Button size="sm" variant="quiet" onClick={m.clear}>
906
- Clear
907
- </Button>
908
- <Spacer />
909
- <span className="ix-lcd">{String(m.bpm).padStart(3, "0")} BPM</span>
910
- </Row>
911
- );
912
- }
913
-
914
- // Tempo, Swing, Drive and Volume: four 56px knobs fit a phone's width in one row.
915
- function Knobs({ m }) {
916
- return (
917
- <Row gap={2} align="center" justify="between">
918
- <Knob label="Tempo" value={m.bpm} min={60} max={180} shown={m.bpm} onChange={m.setBpm} />
919
- <Knob label="Swing" value={m.swing} min={0} max={100} shown={`${m.swing}%`} onChange={m.setSwing} />
920
- <Knob label="Drive" value={m.drive} min={0} max={100} shown={`${m.drive}%`} onChange={m.setDrive} />
921
- <Knob label="Volume" value={m.volume} min={0} max={100} shown={`${m.volume}%`} onChange={m.setVolume} />
922
- </Row>
923
- );
924
- }
925
- // Three arrangements. Choose one, name it in the picks line, and render it inside App after
926
- // `const m = useDrumMachine();`. Saving, sharing and the list of saved beats are the app's own,
927
- // built from the Fireproof and access docs as ordinary Cards outside the panel.
928
-
929
- // Rows: every voice is a line of steps, the classic drum machine.
930
- function RowsPanel({ m }) {
931
- return (
932
- <Panel label="Drum machine" plate="Jam box · 16-step">
933
- <Transport m={m} />
934
- <Knobs m={m} />
935
- <Lights step={m.step} />
936
- <div className="ix-well">
937
- {TRACKS.map(({ id, label }) => (
938
- <Stack key={id} gap={1}>
939
- <span className="ix-label">{label}</span>
940
- <StepGrid label={label} steps={m.grid[id]} playhead={m.step} onToggle={(i) => m.toggleStep(id, i)} />
941
- </Stack>
942
- ))}
943
- </div>
944
- </Panel>
945
- );
946
- }
947
-
948
- // Pad grid: big voice pads choose a sound (and play it); its sixteen steps sit four by four.
949
- function PadGridPanel({ m }) {
950
- const [voice, setVoice] = useState(TRACKS[0].id);
951
- return (
952
- <Panel label="Drum pads" plate="Pad 16">
953
- <div className="ix-voices">
954
- {TRACKS.map(({ id, label }) => (
955
- <Button key={id} variant={voice === id ? undefined : "quiet"} onClick={() => { m.hit(id); setVoice(id); }}>
956
- {label}
957
- </Button>
958
- ))}
959
- </div>
960
- <div className="ix-well ix-grid4">
961
- <StepGrid label={voice} steps={m.grid[voice]} playhead={m.step} onToggle={(i) => m.toggleStep(voice, i)} />
962
- </div>
963
- <Transport m={m} />
964
- <Knobs m={m} />
965
- </Panel>
966
- );
967
- }
968
-
969
- // Vertical rack: each voice is its own rack unit, stacked, with its name plate and a hit button.
970
- function RackPanel({ m }) {
971
- return (
972
- <Panel label="Drum rack" plate="Rack · 4 voices">
973
- <Transport m={m} />
974
- {TRACKS.map(({ id, label }) => (
975
- <div key={id} className="ix-unit">
976
- <Screws />
977
- <Row gap={2} align="center">
978
- <span className="ix-plate">{label}</span>
979
- <Spacer />
980
- <Button size="sm" variant="quiet" onClick={() => m.hit(id)}>
981
- Hit
982
- </Button>
983
- </Row>
984
- <StepGrid label={label} steps={m.grid[id]} playhead={m.step} onToggle={(i) => m.toggleStep(id, i)} />
985
- </div>
986
- ))}
987
- <Knobs m={m} />
988
- </Panel>
989
- );
990
- }
991
- ```
992
-
993
- ### The instrument face — hardware painted from the look
994
-
995
- Every drum machine wears an instrument face from its first build: one
996
- `<section data-instrument>` panel that holds the pads, the transport and the
997
- knobs, so it reads as a machine you could pick up. The face is the app's own
998
- instrument, so a look brief, a layout archetype or a reskin dose on the same
999
- turn dresses the page around it, and the face keeps its knobs, pads and
1000
- token-painted panel. The heading, the save row and the saved list stay ordinary
1001
- `Card`s outside the panel, so the rest of the app keeps the look's own
1002
- components. When the person names a machine or a material ("an 808", "a
1003
- vintage beat box", "an MPC", "brushed metal"), this face is how it gets there.
1004
-
1005
- **Paint from the look's tokens.** Every colour in the face is a `color-mix` of
1006
- the look's tokens: `--bg --surface --ink --purple --orange --info --up
1007
- --on-accent`, with `--r-card --r-control` for corners and `--font-family` for
1008
- type. The face assigns no value to a token and writes no hex colour, so the
1009
- Look tab's colours and every look in the look picker, light and dark,
1010
- repaint the whole machine, and each look gives the same
1011
- drum machine a different body. **Every fill starts from `--surface`.** The panel,
1012
- the well, the readout window, the knob caps and the unlit pads are `--surface`
1013
- with a small share of `--ink` (75% `--surface` or more), so they stay a body
1014
- the look's own colour on light looks and on dark ones like Terminal, where
1015
- `--ink` is the light colour. Text, borders, bezels and shadows are where `--ink`
1016
- leads. The readout is a recessed `--surface` window with `--ink` glyphs tinted
1017
- by the LED colour, readable in both polarities; the LEDs are the LED role on
1018
- that body. Focus outlines are `--ink`, since an LED colour can sit close to the
1019
- panel.
1020
-
1021
- **The pads stay `StepGrid`.** Style them from the panel through their hooks:
1022
- `.ui-pad[data-state="on"]` and `[data-state="off"]` (give both a fill, because
1023
- a look's button rule paints a pad otherwise), `[data-group]` (0 to 3 across a
1024
- bar), `[data-playhead]`, `.ui-pad__led` and `.ui-pad__ring`.
1025
-
1026
- **Make it yours: every first build chooses one per axis** and names the picks
1027
- as the first line of `FACE`, in the reference's shape:
1028
- `/* picks: arrangement = … · pad = … · panel = … · led = … · transport = … */`.
1029
- Choose from what the person asked for and what the app is about; when the
1030
- turn carries an "Instrument arrangement" section, that is this app's
1031
- arrangement. The
1032
- reference's picks are one combination; keep one only when it is the right one
1033
- for this app, so two drum machines rarely share all five. Each pick is a few
1034
- lines of the sheet or the markup.
1035
-
1036
- - **Arrangement:** tracks as rows (one `StepGrid` per voice, stacked, as in the
1037
- reference); a pad grid (four big voice pads choose which voice to edit, and a
1038
- single `StepGrid` for that voice is laid out four by four with
1039
- `--ui-steps: 4; --ui-steps-narrow: 4` on `.ui-stepgrid`, MPC style); or a
1040
- vertical rack (each voice its own rack unit, stacked: a name plate, a mute
1041
- or level knob and its step row, with a rail and screws per unit).
1042
-
1043
- - **Pad shape:** square key (small radius, hard bottom edge), rubber pad
1044
- (`border-radius: 30%`, inset shadow), or round cap (`50%`).
1045
- - **Panel material:** flat plate, brushed metal (a `repeating-linear-gradient`
1046
- of two `--surface`-led mixes), or wood cheeks (thick side borders mixed from `--orange`
1047
- and `--ink`).
1048
- - **LED colour role:** `--info`, `--orange` or `--up`, which lights the
1049
- playhead ring, the step lights and the readout.
1050
- - **Transport layout:** a strip above the grid, a deck below it, or a column
1051
- beside it on wide screens.
1052
- - **Beat-group colours:** four accents across the bar, two-tone by parity, or
1053
- one tone with the lights doing the work.
1054
-
1055
- **Hardware cues, all from tokens:** a bezel (`2px solid var(--ink)`,
1056
- `var(--r-card)`), four screws, a printed name plate, a row of step lights over
1057
- the grid, a readout for the tempo, and knobs. A knob is a plain `div` with
1058
- `role="slider"`: drag up to turn it, arrow keys step it, at least 56px across.
1059
- On a phone the grid runs eight pads a line, so every pad, button and knob stays
1060
- thumb-sized.
1061
-
1062
- The parts above carry this face (`FACE`, `Knob`, `Screws`, `Lights`,
1063
- `Transport`, `Knobs`), and each sketch is one arrangement of them. A first build
1064
- picks an arrangement and the other axes; keep every colour a token mix.
1065
-
1066
- — End —