SLOPSHOPPER

techno

A long techno set above your chat box: three drops, auto mixing into the next track, favorites, Mac media keys. Claude changes it from chat.

bandguardcommandtoastprompttool
★ 2v0.10.8MITupdated 2026-10-22ruslanshchuchkin/claude-techno-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · techno
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /techno ╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ ♪ techno techno needs node (brew install node) [ try again ] hide │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
╭──────────────────────────────────────────────────────────────────────────────────────────────────╮ │ ♪ techno techno needs node (brew install node) [ try again ] hide │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯ ⟨Claude Code's own drawing⟩
README

😈 claude-techno-mod

Type a phrase. Get a seven-minute techno set. Keep coding.

GitHub stars macOS Claude Code License: MIT

https://github.com/user-attachments/assets/46ea094d-1790-4cb2-94a0-cd0940f2e1a9

A Claude Code mod that plays a real techno set in a band above your chat box.

  • 🎛️ One phrase, a whole set. Kick, then bass, then hats. Three drops, breakdowns between them, about seven minutes.
  • 🤖 Claude is the DJ. Say "add congas", "more energy", "next track" and it turns the knobs.
  • 🌀 It never stops. When a track ends, it mixes into the next one, layer by layer, at the same tempo.
  • 🖤 No samples. No AI audio. No account. Every sound is synthesized on your Mac.

⚡ Install

[!IMPORTANT] You need a Mac (macOS 12+), Claude Code 2.1.286+ and Node 20+ (brew install node).

1. Add the marketplace, in Terminal:

claude plugin marketplace add ruslanshchuchkin/claude-techno-mod

2. Install the mod:

claude plugin install techno@techno-mod

3. Open a new chat (terminal or the desktop app's Code tab) and grow your first track. Any phrase works:

/techno late night deploy

Press play. 🔊

[!TIP] Both apps share the same plugins, so one install covers the CLI and the desktop app. Already inside a claude session? Type /plugin marketplace add ruslanshchuchkin/claude-techno-mod, then /plugin install techno@techno-mod.

🎚️ The deck

The band in the video above, part by part:

On the deckWhat it does
♡ / shareKeep the track in favorites / copy its share line
vol − 80% +The volume, in steps of 20%. vol mutes. Or ask Claude: "quieter"
▰▰▱▱ drop 1The whole song, one block per 15 seconds, and where you are: intro, groove, build, drop, break, outro
the dancerA little Claude dances over the grid: it walks to the beat, hops in the drops and says "wait for it" before one. Click it for Nyan Cat, flying across on its rainbow (after djui/nyancat). Your own: /techno dancer (•_•);( •_•)>⌐■-■;(⌐■_■) (frames split by ;). /techno dancer off hides it. Or ask Claude: "bring in nyan cat"
the gridThe loop that plays now. Click a cell to add a hit, click a name to mute it
autoOn: it plays the whole set and moves on by itself. Off: it stays on one part
dark · 133 bpmAlways dark, never the same: every song picks its own bass lines, kick, room and tempo, and some bring congas, a shaker, a drone or a soft hypnotic melody. Each song has its own key, and the next song always moves to another
+ new songType any name, or press a number: one of your recent chats or a classic
editThe studio: instruments, patterns, notes, grit, filters, tempo, and the song's parts
<kbd>⏯</kbd> <kbd>⏭</kbd> <kbd>⏮</kbd>The Mac media keys work too, and the track shows in Control Center

🗣️ It talks

The free macOS voices say the name of the track: Whisper in the second breakdown, Daniel in the last drop, pitched down and drowned in reverb.

A robot whispering "fix flaky login test" over a riser at 133 bpm never gets old.

🧬 Your work is the playlist

When a track ends, auto plays your previous chat. It walks back through your Claude Code chats, newest first, and each chat's title becomes a song. Every fourth song is a classic, so it never runs dry.

now:       anonymous season statistics by country
up next:   mrr 10k 50k project opportunities
then:      fae court quiz business design and seo
then:      segfault on sunday   ← a classic

The mod reads the titles on your Mac, from the chats Claude Code already keeps there, and uploads them nowhere. (The chat you're in does hear what's playing, so Claude can change it.)

🔗 Share a track

A whole track, with your edits, is one line. Press share and it's on your clipboard:

/techno late-night-deploy@133m0e4k2a5

A friend pastes it into their chat and hears the same track, because the code is the track. Want audio? edit → ↓ mp3 saves a minute to ~/Music/techno.

🔊 How the sound is made

Every sound is math in plain JavaScript (hooks/engine.js). Nothing is sampled or downloaded.

SoundHow it's made
kickA sine wave that falls in pitch, with a click on top
bassA sine sub under two detuned saws, through a filter
hatsFiltered noise
padsDark minor chords, never bright ones

[!NOTE] 🎧 Mixed for long sessions, not one loud minute. About −14 LUFS (the level Spotify plays at), no clipping, and the harsh 2 to 5 kHz range sits about 20 dB under the bass.

The music does not belong to one chat. A small background player makes it, and every Claude Code chat is a remote control for it, terminal and desktop alike. Three chats: one track, three remotes. Quit the last Claude Code and the music stops with it.

chat ─┐
chat ─┼─ socket ──▶ techno player (node) ──▶ TechnoPlayer.app ──▶ 🔊
chat ─┘                renders bars ahead       gapless audio,
                                                Control Center, media keys

The music never touches the network. The one request: when a chat starts, it reads the version number on GitHub to tell you an update is ready. The helper app ships prebuilt (one universal binary for Apple silicon and Intel), so you do not need Xcode.

When a new version is out, the deck says techno 0.x.y is ready. Press update, then open a new chat. That's it.

Want it fully automatic? /plugin → Marketplaces → techno-mod → Enable auto-update. It's off by default, and that's a good default: with it on, whatever lands in this repo runs on your Mac without you looking. The button lets you pick the moment.

Or by hand:

claude plugin marketplace update techno-mod
claude plugin update techno@techno-mod

To remove it: claude plugin uninstall techno@techno-mod. Then delete ~/Library/Application Support/techno (your favorites) and ~/Library/Caches/techno (the player's cache).

You seeDo this
The band says the player did not startRun node -v. If it's missing or older than 20, install Node and press play again
/techno does not existOpen a new chat. A chat that was open before the install keeps its old plugins
"hooks modules are turned off"Run claude in a terminal once, run /login, then open a new chat
The media keys control SpotifymacOS gives them to the app that played last. Press play in the deck once
Still stuckOpen an issue with the last lines of ~/Library/Caches/techno/player.log
git clone https://github.com/ruslanshchuchkin/claude-techno-mod && cd claude-techno-mod
claude --plugin-dir .

It reloads when you save. Listen without Claude Code at all:

node scripts/set.mjs "ship it" "warehouse 4am" set.wav && afplay set.wav
FileWhat it is
hooks/engine.jsThe synth, the set plan, transitions, share codes
hooks/conductor.jsWhat each loop plays, and how auto moves on
hooks/register.jsThe chat side: /techno, the jam tool, the remote control
hooks/views.jsThe deck, the edit card, favorites
hooks/words.jsWhich words of a prompt become a track
hooks/dancers.js, hooks/dancer.client.jsThe dancers, and how they move to the beat
player/techno.mjsThe background player
player/TechnoPlayer.swiftThe helper app. After a change, run node scripts/build-helper.mjs

Checks: node scripts/smoke.mjs, claude plugin validate ., claude plugin test.


MIT. Make some noise. 🖤

⭐ Star it if it played you through a long night.

Source 9 files
hooks/register.js 526 lines
1// techno: a long techno set that plays while you work with Claude. One
2// background player (player/techno.mjs) makes the music for every chat; this
3// module is a remote control for it: the band above the chat box, the
4// /techno command, and the mcp__techno__jam tool Claude uses to change the
5// music. The Mac's play, next and previous keys work too (the player's
6// TechnoPlayer.app is in Control Center as "Now Playing").
7//
8// /techno              show or hide the app
9// /techno <phrase>     a new track from the phrase (or from a share code)
10// /techno stop | save | code
11// /techno dancer [clawd | nyan | off | your own frames]
12import { parseCode, encodeCode, describe, render, toWav, grid, activeLayers, cleanTrack, soundInfo, planOf, planAdds, LAYERS, GRID_LAYERS, PLAN, BPM_MIN, BPM_MAX, trackFor, styleName } from './engine.js'
13import { appView, miniView } from './views.js'
14import { keyWords } from './words.js'
15import { CLASSICS } from './classics.js'
16import { dancerFor, nextDancer, DANCER_NAMES, DEFAULT_DANCER, MOVES, SAYS } from './dancers.js'
17
18const TOOL = 'mcp__techno__jam'
19// The plugin version: in the jam tool's answer, and the player of an older
20// version is replaced by this one. Keep it equal to plugin.json (a test checks).
21const VERSION = '0.10.8'
22// [accent, normal] fill of a hit in the step grid
23const LAYER_COLORS = {
24  kick: ['#e85a5a', '#c94040'],
25  hats: ['#3fb6d9', '#2a93b5'],
26  bass: ['#e8b03a', '#c99320'],
27  perc: ['#7b93f0', '#5b77e0'],
28  clap: ['#e070c0', '#c0509f'],
29  ride: ['#4cc4a0', '#2fa583'],
30  acid: ['#8fdc50', '#6fbf30'],
31  stab: ['#b88ae8', '#9a6ad0'],
32  conga: ['#e8864a', '#c96a30'],
33  shaker: ['#a8b8c8', '#8090a0'],
34}
35// Where a new version is announced: the plugin.json on GitHub's main branch.
36const LATEST = 'https://raw.githubusercontent.com/ruslanshchuchkin/claude-techno-mod/main/.claude-plugin/plugin.json'
37// Runs the update with the Claude Code that runs this chat (the desktop
38// app's own copy, or the CLI), found among the shell's parents.
39const UPDATE_SH = 'p=$PPID; c=; for i in 1 2 3 4; do x=$(ps -o comm= -p "$p"); case "$x" in */MacOS/claude|*/claude/versions/*|*/bin/claude) c=$x; break;; esac; p=$(ps -o ppid= -p "$p" | tr -d " "); done; ' +
40  '[ -n "$c" ] || c=$(sh -lc "command -v claude"); [ -n "$c" ] || { echo "claude not found" >&2; exit 2; }; ' +
41  '"$c" plugin marketplace update techno-mod && "$c" plugin update techno@techno-mod'
42
43// Module state. The player holds the music state; this is the chat's view of it.
44const s = {
45  home: '',
46  sock: '',
47  ps: null, // the player's last answer to GET /state
48  down: '', // why the player is not there, for the pane
49  starting: null,
50  isOpen: false,
51  screen: 'deck', // deck | favorites | crate
52  editOpen: false,
53  editTab: null,
54  used: false,
55  barClosed: false,
56  repo: [],
57  lastPrompt: '',
58  you: '',
59  status: '',
60  context: null, // how full Claude's context window is, 0..100, or null before the first answer
61  pollTimer: null,
62  grids: new Map(),
63  classicTurn: Math.floor(Math.random() * 9), // which four classics the new song screen shows
64  update: null, // { latest, state: 'ready' | 'working' | 'done' | 'failed', why }
65  dancer: DEFAULT_DANCER, // who dances over the grid (dancers.js), kept in $.store for every chat
66  debug: [], // dev only: TECHNO_DEBUG=crate,update with the mod loaded from a folder (--plugin-dir)
67}
68
69const shareLine = (code) => '/techno ' + code
70const versionAtLeast = (a, b) => {
71  const x = String(a).split('.').map(Number), y = String(b).split('.').map(Number)
72  for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0)
73  return true
74}
75
76// ---------- the player ----------
77
78async function ask($, body) {
79  const r = await $.http.fetch('http://techno' + (body ? '/cmd' : '/state'), body ? { method: 'POST', body: JSON.stringify(body), socketPath: s.sock } : { socketPath: s.sock })
80  if (!r.ok) throw new Error('player answered ' + r.status)
81  return JSON.parse(r.text)
82}
83
84// Starts the player when no player (or an older one) answers. It runs in its
85// own process group, so it outlives this chat; it quits when no Claude Code
86// process is left.
87async function ensurePlayer($) {
88  if (s.starting) return s.starting
89  s.starting = (async () => {
90    try {
91      const ps = await ask($).catch(() => null)
92      if (ps && versionAtLeast(ps.version, VERSION)) { s.ps = ps; s.down = ''; return true }
93      if (ps) { await ask($, { op: 'quit' }).catch(() => {}); await $.clock.sleep(400) }
94      // Homebrew's node first, then the one the login shell finds (18 or later)
95      const node = await $.process.run(['sh', '-lc', 'for n in /opt/homebrew/bin/node "$(command -v node)" /usr/local/bin/node; do [ -x "$n" ] && echo "$n" && break; done'], { timeoutMs: 10000 })
96      const bin = node.stdout.trim().split('\n')[0]
97      if (!bin) { s.down = 'techno needs node (brew install node)'; return false }
98      const log = s.home + '/Library/Caches/techno/daemon.out'
99      // what the player says from here on: a line starting "techno: " is why it quit
100      const from = Number((await $.process.run(['sh', '-c', 'wc -c < "$1" 2>/dev/null || echo 0', 'sh', log], { timeoutMs: 5000 })).stdout.trim()) || 0
101      const said = async () => (await $.process.run(['sh', '-c', 'tail -c +"$2" "$1" 2>/dev/null | grep "^techno: " | tail -n 1', 'sh', log, String(from + 1)], { timeoutMs: 5000 })).stdout.trim().replace(/^techno: /, '')
102      await $.process.run(['sh', '-c', 'mkdir -p "$(dirname "$3")"; perl -MPOSIX -e "POSIX::setsid(); exec @ARGV" "$1" "$2" </dev/null >>"$3" 2>&1 &', 'sh', bin, $.plugin.root + '/player/techno.mjs', log], { timeoutMs: 10000 })
103      // the first start compiles TechnoPlayer.app (swiftc), which takes a while
104      for (let i = 0; i < 120; i++) {
105        await $.clock.sleep(500)
106        const up = await ask($).catch(() => null)
107        if (up) { s.ps = up; s.down = ''; return true }
108        if (i % 4 === 3) { const why = await said(); if (why) { s.down = why; return false } }
109      }
110      s.down = (await said()) || 'the player did not start: see ~/Library/Caches/techno/daemon.out'
111      return false
112    } finally {
113      s.starting = null
114    }
115  })()
116  return s.starting
117}
118
119// Sends a command; starts the player first when it is not there.
120async function cmd($, body) {
121  try {
122    s.ps = await ask($, body)
123  } catch {
124    if (!(await ensurePlayer($))) { $.ui.invalidate('ui.render'); return null }
125    s.ps = await ask($, body).catch(() => s.ps)
126  }
127  markUsed($)
128  $.ui.invalidate('ui.render')
129  return s.ps
130}
131
132async function poll($) {
133  const before = s.ps?.rev
134  try {
135    s.ps = await ask($)
136    s.down = ''
137  } catch {
138    if (s.ps) { s.ps = null; s.down = 'the player stopped' }
139  }
140  // the context window, as the status line reads it (free to ask)
141  let context = s.context
142  try { context = (await $.session.usage()).context.percent ?? null } catch {}
143  const moved = context !== s.context
144  s.context = context
145  if (s.ps?.rev !== before || s.ps?.playing || moved) $.ui.invalidate('ui.render')
146}
147
148// ---------- saving ----------
149
150// Writes one minute (four loops) of a track to ~/Music/techno as an mp3
151// (or a wav without ffmpeg), shows it in Finder.
152async function save($, code) {
153  const t = parseCode(code)
154  if (!t) return 'Nothing to save yet.'
155  const dir = s.home + '/Music/techno'
156  const name = code.replace(/[@+*]/g, '_')
157  const tmp = dir + '/.' + name + '.wav'
158  s.status = 'saving…'
159  $.ui.invalidate('ui.render')
160  try {
161    const audio = render(t)
162    await $.process.run(['mkdir', '-p', dir])
163    const dec = await $.process.run(['sh', '-c', 'base64 --decode > "$1"', 'sh', tmp], { stdin: toWav(audio).toBase64(), timeoutMs: 30000 })
164    if (dec.exitCode !== 0) throw new Error(dec.stderr.trim() || 'base64 failed')
165    let out = dir + '/' + name + '.mp3'
166    const ff = await $.process.run(['ffmpeg', '-y', '-loglevel', 'error', '-stream_loop', '3', '-i', tmp, '-af', 'afade=t=in:d=0.5,afade=t=out:st=' + (audio.seconds * 4 - 4).toFixed(2) + ':d=4', '-b:a', '192k', out], { timeoutMs: 120000 }).catch(() => ({ exitCode: 1 }))
167    if (ff.exitCode === 0) await $.process.run(['rm', '-f', tmp])
168    else { out = dir + '/' + name + '.wav'; await $.process.run(['mv', tmp, out]) }
169    await $.process.run(['open', '-R', out], { timeoutMs: 5000 }).catch(() => {})
170    s.status = 'saved ' + out.replace(s.home, '~')
171    return 'Saved ' + out
172  } catch (err) {
173    s.status = 'save failed: ' + String(err?.message ?? err)
174    return s.status
175  } finally {
176    $.ui.invalidate('ui.render')
177  }
178}
179
180async function copyLine($, code) {
181  let ok = false
182  try { ok = (await $.ui.copy({ text: shareLine(code) }))?.isCopied !== false } catch {
183    try { ok = (await $.process.run(['pbcopy'], { stdin: shareLine(code), timeoutMs: 5000 })).exitCode === 0 } catch { /* no clipboard */ }
184  }
185  s.status = ok ? '✓ copied: ' + shareLine(code) : shareLine(code)
186  if (!s.isOpen) $.ui.toast(s.status)
187  $.ui.invalidate('ui.render')
188}
189
190// Share: one minute as an mp3, shown in Finder, and the play line copied.
191async function share($, code) {
192  await save($, code)
193  const where = s.status
194  await copyLine($, code)
195  if (where.startsWith('saved')) s.status = where + ' · play line copied'
196  $.ui.invalidate('ui.render')
197}
198
199// ---------- updates ----------
200
201// Ruslan, 2026-10-08: auto-update runs a new push without a look, so the
202// mod only says "update ready" and the person presses update.
203async function checkUpdate($) {
204  if (s.debug.includes('update')) { s.update = { latest: '9.9.9', state: 'ready' }; $.ui.invalidate('ui.render'); return }
205  try {
206    const r = await $.http.fetch(LATEST)
207    const latest = r.ok ? JSON.parse(r.text).version : null
208    if (latest && !versionAtLeast(VERSION, latest)) { s.update = { latest, state: 'ready' }; $.ui.invalidate('ui.render') }
209  } catch { /* offline: no notice */ }
210}
211
212async function runUpdate($) {
213  if (!s.update || s.update.state === 'working') return
214  s.update = { ...s.update, state: 'working' }
215  $.ui.invalidate('ui.render')
216  try {
217    // the debug run finds claude and stops there
218    const r = await $.process.run(['sh', '-c', s.debug.includes('update') ? UPDATE_SH.replace(/; "\$c" plugin.*$/, '; echo "$c"') : UPDATE_SH], { timeoutMs: 180000 })
219    s.update = r.exitCode === 0 ? { ...s.update, state: 'done' } : { ...s.update, state: 'failed', why: (r.stderr || r.stdout).trim().split('\n').pop()?.slice(0, 120) }
220  } catch (err) {
221    s.update = { ...s.update, state: 'failed', why: String(err?.message ?? err).slice(0, 120) }
222  }
223  $.ui.invalidate('ui.render')
224}
225
226// ---------- the app ----------
227
228function markUsed($) {
229  if (s.used && !s.barClosed) return
230  s.used = true
231  s.barClosed = false
232  $.store.set('bar', true)
233}
234
235function gridFor(code) {
236  if (!s.grids.has(code)) {
237    if (s.grids.size > 64) s.grids.clear()
238    const t = parseCode(code)
239    s.grids.set(code, t ? grid({ ...t, layers: Object.fromEntries(LAYERS.map((n) => [n, true])) }, 0) : {})
240  }
241  return s.grids.get(code)
242}
243
244// Reads the session's repo: the project, its branch and recent commits. The
245// player mixes these names into the tracks auto picks.
246async function loadRepo($) {
247  try {
248    const cwd = await $.session.cwd()
249    const out = [cwd.split('/').filter(Boolean).pop() ?? '']
250    const branch = await $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], { timeoutMs: 5000 })
251    if (branch.exitCode === 0 && branch.stdout.trim()) out.push(branch.stdout.trim())
252    const log = await $.process.run(['git', 'log', '-3', '--pretty=%s'], { timeoutMs: 5000 })
253    if (log.exitCode === 0) for (const line of log.stdout.split('\n').map((l) => l.trim()).filter(Boolean)) out.push(line.slice(0, 40))
254    s.repo = out.filter((x, i, all) => x && !x.startsWith('scratch') && all.indexOf(x) === i)
255  } catch {
256    s.repo = []
257  }
258}
259
260// The dancer: a name of dancers.js, off, or your own frames. Every chat
261// keeps it ($.store); a chat open now picks it up at its next start.
262function setDancer($, word) {
263  s.dancer = String(word ?? '').trim().slice(0, 200) || DEFAULT_DANCER
264  $.store.set('dancer', s.dancer)
265  $.ui.invalidate('ui.render')
266  const d = dancerFor(s.dancer)
267  return d ? 'dancer: ' + (d.name === 'own' ? s.dancer : d.name) : 'dancer: off'
268}
269const DANCER_HELP = 'Pick one: ' + DANCER_NAMES.join(', ') + ', off, or your own frames split by ";", like /techno dancer (•_•);( •_•)>⌐■-■;(⌐■_■)'
270
271function describeNow() {
272  const v = s.ps?.view
273  if (!v) return 'nothing'
274  const t = parseCode(v.code)
275  return `"${v.phrase}", ${t ? describe(t) : v.mood}, ${v.section === 'handover' ? 'mixing in from ' + v.from : v.name + ` (part ${(v.at ?? v.part) + 1} of ${(v.plan ?? PLAN).length})`}`
276}
277
278// ---------- hooks ----------
279
280export function register(on) {
281  on('session.start', async ($, e, next) => {
282    s.home = (await $.env.get('HOME')) ?? ''
283    s.sock = s.home + '/Library/Caches/techno/techno.sock'
284    if ((await $.store.get('bar')) === true) s.used = true
285    const dancer = await $.store.get('dancer')
286    if (typeof dancer === 'string') s.dancer = dancer
287    // never from an installed copy: those live in the plugin cache
288    if (!$.plugin.root.includes('/.claude/plugins/')) s.debug = String((await $.env.get('TECHNO_DEBUG')) ?? '').split(',').filter(Boolean)
289    if (s.debug.includes('crate')) s.screen = 'crate'
290    await $.tool.register({
291      name: 'jam',
292      description:
293        "Change the techno music in the user's techno pane (the techno mod). Use it when the user asks to change the music: more or less energy, faster or slower, add or drop a layer, new patterns, the next part, the next or previous track, a new phrase, auto on or off, play or stop. Pass only what changes. " +
294        'Every song is dark techno, 128-136 bpm. The song name picks its bass lines and sounds, and some songs bring congas, a shaker, a drone or a soft looping melody (the acid layer, shown as melody). There is no 303. dice: true gives new bass lines and patterns. energy: 0 minimal, 1 rolling, 2 driving, 3 peak, 4 rave. ' +
295        'A track is a long set: intro, groove, build, three drops with breakdowns between them, an outro that mixes into the next track. next: true moves to the next part. track: "next" mixes into the next track now, "previous" goes back to the one before. ' +
296        'layers (kick, bass, hats, clap, perc, ride, pad, rumble, acid, voice, stab, conga, shaker, drone): true forces a layer on, false off, "auto" gives it back to the arrangement. dice: true rolls new patterns. phrase: a new phrase starts a new track. favorite: true adds the track to the favorites. volume: 0 mute .. 5 loudest, 4 is the default (each step about 6 dB); for "quieter" or "louder" move it one step. ' +
297        'dancer: who dances over the grid: ' + DANCER_NAMES.join(', ') + ', off, or custom frames split by ";" (one line each, like "(•_•);(⌐■_■)"). ' +
298        'note: a few words for the pane that say what you changed. Reply to the user in one short line.',
299      inputSchema: {
300        type: 'object',
301        properties: {
302          phrase: { type: 'string', description: 'A new phrase. It seeds a whole new track; its letters become the riff.' },
303          next: { type: 'boolean', description: 'Move to the next part of the track' },
304          track: { enum: ['next', 'previous'], description: 'Mix into the next track now, or go back to the previous one' },
305          bpm: { type: 'integer', minimum: BPM_MIN, maximum: BPM_MAX },
306          energy: { type: 'integer', minimum: 0, maximum: 4 },
307          swing: { type: 'integer', minimum: 0, maximum: 3, description: '0 straight, 3 most shuffle on hats and percussion' },
308          transpose: { type: 'integer', minimum: 0, maximum: 11, description: 'Semitones up from the phrase key' },
309          dice: { type: 'boolean', description: 'Roll new patterns for the same phrase' },
310          layers: { type: 'object', properties: Object.fromEntries(LAYERS.map((n) => [n, { enum: [true, false, 'auto'] }])), additionalProperties: false },
311          favorite: { type: 'boolean', description: 'true adds the playing track to the favorites, false removes it' },
312          play: { type: 'boolean', description: 'true starts the music, false stops it' },
313          volume: { type: 'integer', minimum: 0, maximum: 5, description: '0 mute, 4 the default, 5 loudest' },
314          auto: { type: 'boolean', description: 'true lets the set play by itself (parts, drops, then the next track); false stays on a part until next' },
315          dancer: { type: 'string', description: 'Who dances over the grid: ' + DANCER_NAMES.join(', ') + ', off, or your own frames split by ";"' },
316          note: { type: 'string', description: 'A few words for the pane, like "more energy, congas on"' },
317        },
318      },
319    })
320    await $.command.register({ name: 'techno', description: 'Show or hide the techno app', argumentHint: '[phrase or share code]', immediate: true })
321    // The player may take a while (its first start compiles the helper app):
322    // the command and the tool are there at once, the player comes up behind.
323    void (async () => {
324      await loadRepo($)
325      void checkUpdate($)
326      // the first chat on 0.8 hands the kept tracks and the last track to the player
327      const kept = await $.store.get('saved')
328      const track = await $.store.get('track')
329      if (await ensurePlayer($)) await cmd($, { op: 'hello', repo: s.repo, saved: Array.isArray(kept) ? kept : [], track: track && typeof track === 'object' ? encodeCode(cleanTrack(track)) : null })
330      if (!s.pollTimer) s.pollTimer = $.clock.every(1000, () => { poll($).catch(() => {}) })
331      $.ui.invalidate('ui.render')
332    })().catch(() => {})
333    return next(e)
334  })
335
336  on('command.run', { command: 'techno' }, async ($, e) => {
337    const arg = String(e.args ?? '').trim()
338    const word = arg.toLowerCase()
339    if (word === 'stop') { await cmd($, { op: 'pause' }); return { text: 'Stopped.' } }
340    if (word === 'save') return { text: s.ps ? await save($, s.ps.view.code) : 'Nothing plays yet.' }
341    if (word === 'code') return { text: s.ps ? shareLine(s.ps.view.code) : 'No track yet. Start with /techno <phrase>.' }
342    if (word === 'dancer' || word.startsWith('dancer ')) {
343      const pick = arg.slice(6).trim()
344      if (!pick) return { text: 'The dancer is ' + s.dancer + '. ' + DANCER_HELP }
345      return { text: setDancer($, pick) + '. A click on the dancer picks the next one.' }
346    }
347    if (word === 'play') await cmd($, { op: 'play' })
348    else if (arg) { await cmd($, { op: 'pick', code: arg }); s.screen = 'deck' }
349    else if (s.isOpen) { s.isOpen = false; $.ui.invalidate('ui.render'); return {} }
350    s.isOpen = true
351    markUsed($)
352    $.ui.invalidate('ui.render')
353    return {}
354  })
355
356  on('tool.call', { tool: TOOL }, async ($, e) => {
357    const done = []
358    if (e.phrase) { await cmd($, { op: 'pick', code: e.phrase }); done.push('new track ' + e.phrase) }
359    if (e.track === 'next') { await cmd($, { op: 'skip' }); done.push('mixing into the next track') }
360    if (e.track === 'previous') { await cmd($, { op: 'prev' }); done.push('back to the previous track') }
361    if (e.next) { await cmd($, { op: 'next' }); done.push('next part') }
362    const jam = { op: 'jam', note: e.note }
363    for (const k of ['bpm', 'energy', 'swing', 'transpose', 'dice', 'layers']) if (e[k] !== undefined) jam[k] = e[k]
364    if (Object.keys(jam).length > 2) { await cmd($, jam); done.push('changed ' + Object.keys(jam).filter((k) => k !== 'op' && k !== 'note').join(', ')) }
365    if (typeof e.auto === 'boolean') { await cmd($, { op: 'auto', on: e.auto }); done.push('auto ' + (e.auto ? 'on' : 'off')) }
366    if (typeof e.favorite === 'boolean' && s.ps && s.ps.fav !== e.favorite) { await cmd($, { op: 'fav' }); done.push(e.favorite ? 'added to favorites' : 'removed from favorites') }
367    if (Number.isInteger(e.volume)) { await cmd($, { op: 'volume', level: e.volume }); done.push('volume ' + e.volume) }
368    if (typeof e.dancer === 'string') done.push(setDancer($, e.dancer))
369    if (e.play === true) await cmd($, { op: 'play' })
370    if (e.play === false) await cmd($, { op: 'pause' })
371    else if (!s.ps?.playing && (e.phrase || e.track)) await cmd($, { op: 'play' })
372    if (!s.ps) return { result: 'The techno player is not running: ' + (s.down || 'unknown reason') }
373    s.you = s.lastPrompt
374    s.isOpen = true
375    s.screen = 'deck'
376    $.ui.invalidate('ui.render')
377    return { result: `${done.join('; ') || 'no change'}. Now: ${describeNow()}. Auto ${s.ps.auto ? 'on' : 'off'}, ${s.ps.playing ? 'playing' : 'stopped'}, volume ${s.ps.volume ?? 4} of 5. Share line: ${shareLine(s.ps.view.code)} (techno v${VERSION})` }
378  })
379
380  // Remember what the user asked, for the pane. While music plays, tell Claude about it.
381  on('prompt.submit', async ($, e, next) => {
382    s.lastPrompt = String(e.text ?? '').replace(/\s+/g, ' ').trim().slice(0, 80)
383    // the prompt's key words join the tracks auto picks; never starts the player
384    const words = keyWords(e.text)
385    if (words) await ask($, { op: 'words', phrase: words }).catch(() => {})
386    if (!s.ps?.playing) return next(e)
387    const note = `The techno mod is playing in the user's techno pane: ${describeNow()}, auto ${s.ps.auto ? 'on' : 'off'}. If this prompt is about the music, change it with the ${TOOL} tool and reply in one short line.`
388    return next({ ...e, context: [...(e.context ?? []), note] })
389  })
390
391  // The app, drawn in the band above the chat box. Hidden: a one-line bar,
392  // once techno was used, until its ×.
393  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
394    if (!s.isOpen && !(s.used && !s.barClosed && (s.ps || s.down))) return next(e)
395    const ui = $.ui.resolve(e)
396    const ps = s.ps
397    const v = ps?.view
398    const t = v ? parseCode(v.code) : null
399    const now = await $.clock.now()
400    const heard = t ? activeLayers(t) : {}
401    const all = v ? gridFor(v.code) : {}
402    // the rows: every layer that plays, plus the next one as a dashed row
403    const rows = t ? GRID_LAYERS.filter((n) => heard[n] || t.layers[n] === false).map((n) => [n, all[n] ?? '.'.repeat(16), LAYER_COLORS[n], !!heard[n], t.layers[n] === false]) : []
404    if (v?.next?.layer && GRID_LAYERS.includes(v.next.layer) && !rows.some((r) => r[0] === v.next.layer)) rows.push([v.next.layer, all[v.next.layer] ?? '.'.repeat(16), LAYER_COLORS[v.next.layer], false, false, true])
405    const looping = !!(ps?.playing && ps.barStartedAt)
406    const sinceBar = looping ? Math.max(0, now - ps.barStartedAt) : 0
407    const step = looping ? (v.bar * 16 + Math.min(15, Math.floor(sinceBar / ps.stepMs))) % 128 : 0
408    const nextIn = ps?.nextInMs !== null && ps?.nextInMs !== undefined ? Math.max(0, ps.nextInMs - (now - ps.now)) : null
409    // where the set is, for the section words: the parts of the plan and
410    // how far in the set it plays (in loops)
411    let where = null
412    if (v) {
413      const barMs = ps.barMs || 1800
414      const plan = v.plan ?? PLAN.map((_, k) => k)
415      const loops = plan.map((k) => PLAN[k].loops)
416      const totalLoops = loops.reduce((n, x) => n + x, 0)
417      const at = v.part === null ? plan.length : v.at ?? Math.max(0, plan.indexOf(v.part))
418      const before = loops.slice(0, at).reduce((n, x) => n + x, 0)
419      const inPart = v.part === null ? 0 : Math.max(0, loops[at] - v.loopsLeft)
420      const pos = Math.min(totalLoops, before + inPart + (v.part === null ? 0 : (v.bar + Math.min(1, sinceBar / barMs)) / 8))
421      where = { parts: plan.map((k) => ({ name: PLAN[k].name, section: PLAN[k].section, loops: PLAN[k].loops })), pos, loopMs: 8 * barMs, elapsed: pos * 8 * barMs, total: totalLoops * 8 * barMs }
422    }
423    // the edit card opens on the bass (or the first sound that plays)
424    const editTab = s.editTab ?? (heard.bass ? 'bass' : ['kick', 'hats', 'acid'].find((n) => heard[n]) ?? 'kick')
425    const vm = {
426      surface: e.surface,
427      columns: e.viewport?.columns ?? null, // the band's width in cells: the bar drops parts to stay one line
428      screen: s.screen,
429      down: s.down,
430      ps,
431      view: v,
432      playing: !!ps?.playing,
433      auto: !!ps?.auto,
434      fav: !!ps?.fav,
435      volume: ps?.volume ?? 4,
436      context: s.context,
437      nextIn,
438      where,
439      editOpen: s.editOpen,
440      editTab,
441      heard,
442      info: t && editTab && !['song', 'master', 'add'].includes(editTab) ? soundInfo(t, editTab) : null,
443      master: t?.master ?? [0, 0, 0],
444      plan: t ? planOf(t).map((k, i) => ({ k: i, name: PLAN[k].name, now: v.part !== null && i === (v.at ?? -1) })) : [],
445      planAdds: t ? planAdds(t) : [],
446      planEdited: !!t?.plan,
447      favorites: ps?.favorites ?? [],
448      recent: ps?.recent ?? [],
449      playlist: ps?.playlist ?? null,
450      canUndo: !!ps?.canUndo,
451      said: ps?.said ?? '',
452      you: s.you,
453      status: s.status,
454      crate: (() => {
455        const classics = Array.from({ length: 4 }, (_, i) => CLASSICS[(s.classicTurn * 4 + i) % CLASSICS.length])
456        const ex = trackFor(classics[0])
457        return { chats: ps?.chats ?? [], classics, example: { phrase: ex.phrase, mood: styleName(ex), bpm: ex.bpm }, now }
458      })(),
459      update: s.update,
460      dancerEl: (() => {
461        const d = v && ui.Client ? dancerFor(s.dancer) : null
462        if (!d) return null
463        const section = v.section ?? 'groove'
464        return ui.Client({ key: 'dancer', module: './dancer.client.js', width: '100%', props: { frames: d.frames, color: d.color, bold: !!d.bold, rows: d.rows ?? 4, wrap: !!d.wrap, trail: d.trail ?? null, move: MOVES[section] ?? MOVES.groove, says: SAYS[section] ?? [], section, playing: looping, step, stepMs: ps?.stepMs || 115, stamp: ps?.barStartedAt ?? 0 } })
465      })(),
466      gridEl: rows.length ? ui.Client({ key: 'grid', module: './grid.client.js', props: { rows, step, stepMs: ps?.stepMs || 115, playing: looping, stamp: ps?.barStartedAt ?? 0 } }) : null,
467    }
468    const go = (body) => () => cmd($, body)
469    const act = {
470      play: go({ op: 'play' }),
471      stop: go({ op: 'pause' }),
472      auto: go({ op: 'auto', on: !ps?.auto }),
473      next: go({ op: 'next' }),
474      skip: go({ op: 'skip' }),
475      prev: go({ op: 'prev' }),
476      fav: go({ op: 'fav' }),
477      volume: (level) => cmd($, { op: 'volume', level }),
478      toggleFav: (code) => cmd($, { op: 'fav', code }),
479      dice: go({ op: 'dice' }),
480      undo: go({ op: 'undo' }),
481      bpm: (d) => cmd($, { op: 'jam', bpm: Math.max(BPM_MIN, Math.min(BPM_MAX, (v?.bpm ?? 128) + d)) }),
482      pick: (code) => { s.screen = 'deck'; return cmd($, { op: 'pick', code, playlist: null }) },
483      playFavorite: (code) => { s.screen = 'deck'; return cmd($, { op: 'pick', code, playlist: 'favorites' }) },
484      playFavorites: () => { s.screen = 'deck'; return cmd($, { op: 'playlist', name: 'favorites' }) },
485      phrase: (text) => (String(text).trim() ? act.pick(String(text).trim()) : undefined),
486      share: (code) => share($, code ?? v.code),
487      copy: (code) => copyLine($, code ?? v.code),
488      screen: (id) => { s.screen = id; $.ui.invalidate('ui.render') },
489      edit: () => { s.editOpen = !s.editOpen; $.ui.invalidate('ui.render') },
490      editTab: (id) => { s.editTab = id; $.ui.invalidate('ui.render') },
491      tweak: (e) => cmd($, { op: 'edit', ...e }),
492      layer: (name) => cmd($, { op: 'layer', name }),
493      open: () => { s.isOpen = true; s.screen = 'deck'; $.ui.invalidate('ui.render') },
494      close: () => { s.isOpen = false; $.ui.invalidate('ui.render') },
495      closeBar: () => { s.barClosed = true; $.store.set('bar', false); $.ui.invalidate('ui.render') },
496      retry: () => ensurePlayer($).then(() => $.ui.invalidate('ui.render')),
497      moreClassics: () => { s.classicTurn++; $.ui.invalidate('ui.render') },
498      update: () => runUpdate($),
499    }
500    const theirs = await next(e)
501    return ui.Box({ flexDirection: 'column', children: [s.isOpen ? appView(ui, vm, act) : miniView(ui, vm, act), theirs] })
502  })
503
504  // The grid posts { toggle: layer } for a click on a row name, and
505  // { step, layer } for a click on a cell. The dancer posts { dancer: 'next' }.
506  on('ui.message', async ($, e, next) => {
507    if (e.element === 'dancer' && e.data?.dancer === 'next') {
508      s.status = setDancer($, nextDancer(s.dancer)) + ' · /techno dancer off hides it'
509      if (!s.isOpen) $.ui.toast(s.status)
510      return {}
511    }
512    const d = e.element === 'grid' ? e.data : null
513    if (d && typeof d.toggle === 'string' && LAYERS.includes(d.toggle)) { await cmd($, { op: 'layer', name: d.toggle }); return {} }
514    if (d && typeof d.layer === 'string' && GRID_LAYERS.includes(d.layer) && Number.isInteger(d.step)) { await cmd($, { op: 'step', layer: d.layer, i: d.step }); return {} }
515    return next(e)
516  })
517
518  // The player plays on for the other chats; it stops when the last Claude
519  // Code process ends.
520  on('session.end', async ($, e, next) => {
521    if (s.pollTimer) s.pollTimer.cancel()
522    s.pollTimer = null
523    return next(e)
524  })
525}
526
hooks/engine.js 1706 lines
1// Techno loop synth. Plain JavaScript with no Node or browser APIs, so the
2// same file runs inside the mod, in node (scripts/render.mjs), and in a page.
3//
4// A track is a small state object. The phrase seeds everything: the key, the
5// patterns, and the riff, whose notes are the phrase's own letters.
6
7export const LAYERS = ['kick', 'bass', 'hats', 'clap', 'perc', 'acid', 'stab', 'rumble', 'voice', 'ride', 'pad', 'conga', 'shaker', 'drone']
8export const MOODS = ['pitch black', 'dark', 'deep', 'warm', 'bright']
9export const ENERGIES = ['minimal', 'rolling', 'driving', 'peak', 'rave']
10const NOTE_NAMES = ['c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#', 'a', 'a#', 'b']
11// Low keys only: the sub root lands on e1..a1 (41..55 Hz), where techno sits.
12const KEY_CLASSES = [4, 5, 6, 7, 9, 5, 7, 9] // e, f, f#, g, a, f, g, a
13// The scales you can pick. Without a pick, the mood picks one:
14// pitch black phrygian, dark and deep minor, warm and bright dorian.
15export const SCALES = [
16  { name: 'minor', steps: [0, 2, 3, 5, 7, 8, 10] }, // sad, the classic
17  { name: 'dorian', steps: [0, 2, 3, 5, 7, 9, 10] }, // cool, a little hope
18  { name: 'phrygian', steps: [0, 1, 3, 5, 7, 8, 10] }, // dark, tense
19  { name: 'hijaz', steps: [0, 1, 4, 5, 7, 8, 10] }, // arabic
20  { name: 'harmonic', steps: [0, 2, 3, 5, 7, 8, 11] }, // dramatic
21]
22// The three moods you pick from. Each sets the sound (the old mood number:
23// filters, rumble, room) and the scale together, so they never disagree.
24// Old codes keep their own m and k; a pair that is no preset shows its nearest.
25// A mood also sets the tempo and lifts or lowers the energy of every part.
26export const VIBES = [
27  { name: 'sad', mood: 2, scale: 0, bpm: 122, lift: -1 }, // minor, a little more air, slower
28  { name: 'mysterious', mood: 1, scale: 3, bpm: 127, lift: 0 }, // hijaz, the arabic one
29  { name: 'dark', mood: 0, scale: 2, bpm: 132, lift: 1 }, // phrygian, pitch black, harder
30]
31export function vibeOf(t) {
32  const exact = VIBES.findIndex((v) => v.mood === t.mood && v.scale === scaleOf(t))
33  if (exact >= 0) return exact
34  return t.mood >= 2 ? 0 : scaleOf(t) === 3 ? 1 : t.mood === 0 ? 2 : 1
35}
36export const moodName = (t) => VIBES[vibeOf(t)].name
37
38// The track in another mood: its sound, scale, tempo, and the energy of its part.
39export function withVibe(input, name) {
40  const t = cleanTrack(input)
41  const v = VIBES.find((it) => it.name === name)
42  if (!v) return t
43  const energy = t.part === null || t.part === undefined ? t.energy : clamp(PLAN[t.part].energy + v.lift, 0, 4)
44  return { ...t, mood: v.mood, scale: v.scale, bpm: v.bpm, energy }
45}
46const scaleOf = (t) => t.scale ?? (t.mood === 0 ? 2 : t.mood >= 3 ? 1 : 0)
47
48// The style (Ruslan, 2026-10-12: "i want my techno to ONLY be dark ... all
49// tracks honestly feel too much the same"; hard, industrial, minimal and
50// deep were built and dropped: "ok dark only"). Every new track is dark:
51// mood 0 and a dark scale (minor, phrygian, harmonic). So a song differs
52// from the next one inside the style: the phrase picks the tempo, how hard
53// every part hits (`lifts`), the swing, each sound (indexes into
54// INSTRUMENTS), its two bass lines (BASS_LINES), the extra instruments it
55// brings (EXTRAS), the room, and a lead line (LEADS). A track with
56// `style: null` is an old code and plays as it always did. `y<n>` in the
57// share code. STYLES stays a list, so a style can come back later.
58//   leads   weights of none, hypnotic, acid (see LEADS)
59//   rooms   the reverb sizes to pick from; `echo` more of the ping-pong on perc and acid
60//   gain    the level into the master's soft clip
61export const STYLES = [
62  { name: 'dark', bpm: [128, 136], mood: 0, lifts: [0, 1, 1], scales: [2, 0, 4], swing: [0, 0, 1], kick: [0, 1, 2], bass: [0, 1, 2, 4, 5, 6], hats: [0, 1, 2, 3, 4], clap: [0, 1, 2], perc: [1, 2, 3, 4, 5], drops: [], adds: {}, leads: [3, 1], rooms: [0.8, 0.86, 0.92], echo: 1.2, gain: 0.95 },
63]
64// The extra instruments (Ruslan, 2026-10-12: "you add more other
65// instruments?"). The phrase picks each one with even odds, so one song has
66// congas and a drone, the next only a shaker, the next none. Each plays in
67// these PLAN parts.
68//   conga   tuned hand drums, low, mid and high, from the second groove on
69//   shaker  16ths on top of the hats, in the build and the drops
70//   drone   a low held chord, root, fifth and octave, in the intro and the breakdowns
71export const EXTRAS = { conga: [3, 4, 5, 7, 9], shaker: [4, 5, 7, 9], drone: [0, 1, 6, 8] }
72export function extrasOf(t) {
73  if (!styleOf(t)) return []
74  const r = rng(hash32('extra:' + t.phrase + ':' + t.style))
75  return Object.keys(EXTRAS).filter(() => r() < 0.5)
76}
77// The lead lines a style may bring, picked by the phrase (Ruslan's answer
78// on 2026-10-12: hypnotic and acid are no buttons, they come by themselves):
79//   hypnotic  a soft line that loops over 3, 5 or 7 steps against the bar,
80//             from the first breakdown to drop 3
81// About one song in four has it ("sometimes too much melody", Ruslan,
82// 2026-10-12). The 303 lead is gone ("i don't like acid samples/instrument
83// ... remove it"): a style song never picks the acid or square sound, and
84// the edit card does not offer them (or the acid bass) on a style song.
85// Each sets the acid layer's sound (indexes into INSTRUMENTS.acid) and its
86// level (the hypnotic line plays on most steps, so it sits lower).
87export const LEADS = {
88  hypnotic: { parts: [6, 7, 8, 9], acid: [2, 3], level: 0.5 },
89}
90const LEAD_NAMES = [null, 'hypnotic']
91// The sounds a style song never offers: the 303 and its square, the acid bass
92const NOT_IN_STYLE = { acid: ['acid', 'square'], bass: ['acid'] }
93const styleOf = (t) => (t?.style === null || t?.style === undefined ? null : STYLES[t.style] ?? null)
94// The lead line of a style track (null: none), the same for a phrase and its style
95export function leadOf(t) {
96  const st = styleOf(t)
97  if (!st) return null
98  return weighted(rng(hash32('lead:' + t.phrase + ':' + t.style)), LEAD_NAMES, st.leads)
99}
100// What the pane calls the track's sound: its style, or the old mood
101export const styleName = (t) => styleOf(t)?.name ?? moodName(t)
102// The sound of each layer: an explicit pick wins, else the style's pick for
103// this phrase, else the phrase's own (index 0).
104export function instOf(t) {
105  const st = styleOf(t)
106  const r = rng(hash32('inst:' + t.phrase + ':' + t.style))
107  const out = {}
108  const lead = leadOf(t)
109  for (const name of Object.keys(INSTRUMENTS)) {
110    // the melody of a style song is a soft one, even when you turn it on by hand
111    const own = !st ? 0 : name === 'acid' ? pick(r, LEADS[lead ?? 'hypnotic'].acid) : pick(r, st[name])
112    out[name] = t.inst?.[name] ?? own
113  }
114  return out
115}
116// The track in another style: its tempo, swing, scale and sounds (your own
117// sound picks go, since the style picks them), and the energy of its part.
118export function withStyle(input, name) {
119  const t = cleanTrack(input)
120  const i = STYLES.findIndex((it) => it.name === name)
121  return i < 0 ? t : styled(t, i)
122}
123// (no cleanTrack here: trackFor builds on it, and cleanTrack on trackFor)
124function styled(t, i) {
125  const st = STYLES[i]
126  const r = rng(hash32('style:' + t.phrase + ':' + i))
127  const bpm = st.bpm[0] + Math.floor(r() * (st.bpm[1] - st.bpm[0] + 1))
128  const scale = st.scales.includes(t.scale) ? t.scale : pick(r, st.scales)
129  const lifted = { ...t, style: i }
130  const energy = t.part === null || t.part === undefined ? t.energy : clamp(PLAN[t.part].energy + liftOf(lifted), 0, 4)
131  return { ...t, style: i, mood: st.mood, scale, bpm, swing: pick(r, st.swing), energy, inst: {} }
132}
133// How hard a style song hits: 0 rolling drops, 1 peak drops (16th hats, clap rolls)
134function liftOf(t) {
135  const st = styleOf(t)
136  return st ? st.lifts[hash32('lift:' + t.phrase + ':' + t.style) % st.lifts.length] : VIBES[vibeOf(t)].lift
137}
138const CHORDS = [[0, 3, 7, 12], [0, 3, 7, 10], [0, 3, 7, 10], [0, 3, 7, 10, 14], [0, 5, 7, 10, 14]]
139export const BARS = 8
140export const STEPS = 16
141export const BPM_MIN = 110
142export const BPM_MAX = 150
143
144// The layers the step grid shows (rumble has no steps of its own: it is the
145// kick's tail; the pad is one long swell; the voice says the name once).
146export const GRID_LAYERS = ['kick', 'hats', 'bass', 'perc', 'clap', 'ride', 'acid', 'stab', 'conga', 'shaker']
147
148// The edit card (Ruslan, 2026-10-04, layout B "focus card"): per sound, its
149// instrument, its pattern, its notes and its tone; for the whole track, the
150// master filters. Index 0 is always the sound the phrase gives (for perc,
151// the phrase's own pick of rim, tom or bell).
152export const INSTRUMENTS = {
153  kick: ['deep', 'punchy', 'boom', 'hard', 'distorted', 'click'],
154  bass: ['rolling', 'sub', 'growl', 'acid', 'pluck', 'reese', 'fm'],
155  hats: ['tight', 'long', 'metal', 'dusty', 'brush'],
156  clap: ['room', 'snap', 'snare', 'industrial'],
157  perc: ['phrase', 'rim', 'tom', 'bell', 'metal', 'wood'],
158  acid: ['acid', 'square', 'pluck', 'soft'],
159}
160// Patterns to try, one bar of 16 steps. A pick becomes step edits, so it
161// rides in the share code like a click on the grid.
162export const PATTERNS = {
163  kick: { 'four on the floor': 'x...x...x...x...', broken: 'x...x...x..x..x.', 'half time': 'x.......x.......', skip: 'x...x...x...x.x.' },
164  bass: { offbeat: '..x...x...x...x.', rolling: '.xx..xx..xx..xx.', gallop: '.xxx.xxx.xxx.xxx', sparse: '..x.......x.....' },
165  hats: { offbeat: '..x...x...x...x.', '8ths': 'x.x.x.x.x.x.x.x.', '16ths': 'xxxxxxxxxxxxxxxx', shuffle: '..x..xx...x..xx.' },
166  clap: { '2 and 4': '....x.......x...', 'on 4': '............x...', push: '....x.....x.x...' },
167  perc: { skip: '.x..x.....x..x..', shuffle: '...x..x....x..x.', steady: 'x..x..x..x..x...', broken: '.x.x...x.x...x..' },
168  ride: { '8ths': 'x.x.x.x.x.x.x.x.', offbeat: '..x...x...x...x.', '16ths': 'xxxxxxxxxxxxxxxx' },
169  acid: { '16ths': 'xxxxxxxxxxxxxxxx', sparse: 'x..x..x...x..x..', offbeat: '..x...x...x...x.', rolling: 'x.xx.xx.x.xx.xx.' },
170}
171// Sounds with notes you can set: one scale degree per step (0..14, written
172// 0-9a-e; '.' keeps the pattern's note), the same in every bar.
173export const NOTE_LAYERS = ['bass', 'acid']
174// Sounds with a tone: [cut -3..3 (dark .. thin), grit 0..3].
175export const TONE_LAYERS = ['kick', 'bass', 'hats', 'clap', 'perc', 'acid', 'ride', 'pad', 'rumble']
176const NOTE_RE = /^[.0-9a-e]{16}$/
177
178// The build: a track starts with the kick alone and NEXT walks it through a
179// long set, one part at a time. `part` in a track is an index here; null means
180// the old full-track behaviour where mood and energy pick the layers.
181export const SECTIONS = ['intro', 'groove', 'build', 'drop', 'break', 'outro']
182// Minimal on purpose: music to work to. About seven minutes with auto: a long
183// intro, three drops with a breakdown between them, and an outro that hands
184// over to the next track layer by layer. No chord stabs (Ruslan, 2026-10-03:
185// "they make the track less serious"); the ride and the dark pad take their place.
186// `name` is what the part brings, for the pane ("rumble in 0:12"); `adds` is
187// true when that is a new sound and not a new section. `layer` is the one new
188// layer, for the dashed "next" row in the grid. `loops` is how long auto plays
189// it. `rise` puts a riser on its last loop (a drop comes next). The voice says
190// the track's name: a whisper in the second breakdown, a deep voice on drop 3.
191const FULL = ['kick', 'bass', 'hats', 'rumble', 'perc', 'clap']
192export const PLAN = [
193  { section: 'intro', energy: 0, loops: 2, layers: ['kick'], name: 'kick', adds: true, layer: 'kick', go: 'start', tip: 'Just the kick' },
194  { section: 'intro', energy: 0, loops: 2, layers: ['kick', 'bass'], name: 'deep bass', adds: true, layer: 'bass', go: 'add the deep bass', tip: 'Kick and a deep sub' },
195  { section: 'groove', energy: 1, loops: 2, layers: ['kick', 'bass', 'hats'], name: 'hats', adds: true, layer: 'hats', go: 'add hats', tip: 'Offbeat hats, the groove rolls' },
196  { section: 'groove', energy: 1, loops: 2, layers: ['kick', 'bass', 'hats', 'rumble'], name: 'rumble', adds: true, layer: 'rumble', go: 'add the rumble', tip: 'The rumble fills the low end' },
197  { section: 'build', energy: 2, loops: 2, rise: true, layers: ['kick', 'bass', 'hats', 'rumble', 'perc'], name: 'percussion', adds: true, layer: 'perc', go: 'add percussion', tip: 'Percussion, then a rise' },
198  { section: 'drop', energy: 3, loops: 4, layers: FULL, name: 'drop 1', adds: true, layer: 'clap', go: 'drop 1', tip: 'Drop 1: the clap comes in' },
199  { section: 'break', energy: 1, loops: 2, rise: true, layers: ['hats', 'perc', 'pad'], name: 'breakdown', adds: true, layer: 'pad', go: 'the breakdown', tip: 'The kick drops out. A dark pad' },
200  { section: 'drop', energy: 3, loops: 4, layers: [...FULL, 'ride'], name: 'drop 2', adds: true, layer: 'ride', go: 'drop 2', tip: 'Drop 2: the ride on top' },
201  { section: 'break', energy: 1, loops: 2, rise: true, layers: ['perc', 'pad', 'voice'], name: 'breakdown 2', adds: false, go: 'the second breakdown', tip: 'Only the pad and a whisper' },
202  { section: 'drop', energy: 3, loops: 4, layers: [...FULL, 'ride', 'voice'], name: 'drop 3', adds: false, go: 'drop 3', tip: 'Drop 3: everything, the last peak' },
203  { section: 'outro', energy: 1, loops: 1, layers: ['kick', 'bass', 'hats', 'rumble', 'perc'], name: 'outro', adds: false, go: 'the outro', tip: 'The next track comes in' },
204]
205// A track's own order of parts (Ruslan, 2026-10-04: "remove a part like
206// groove or add a new part ... with something recommended"): PLAN indexes,
207// null for PLAN as it is. Auto walks it; a part can come twice.
208export const planOf = (t) => t?.plan ?? PLAN.map((_, i) => i)
209const sameAsPlan = (p) => p.length === PLAN.length && p.every((x, i) => x === i)
210
211// What the song tab offers to add, the first fitting one recommended.
212//   drop    a breakdown and a drop before the outro
213//   groove  one more groove part after the groove
214//   build   one more build before the first drop
215//   break   a breakdown before the last drop
216export function planAdds(input) {
217  const plan = planOf(input)
218  const drops = plan.filter((i) => PLAN[i].section === 'drop').length
219  const grooves = plan.filter((i) => PLAN[i].section === 'groove').length
220  const best = drops < 3 ? 'drop' : grooves < 2 ? 'groove' : drops < 5 ? 'drop' : 'build'
221  return [['drop', 'breakdown and a drop'], ['groove', 'longer groove'], ['build', 'longer build'], ['break', 'a breakdown']].map(([id, label]) => ({ id, label, best: id === best }))
222}
223
224// Inserts a suggestion into the plan: { plan, at, count } (where it went).
225export function planAdd(input, id) {
226  const plan = [...planOf(input)]
227  const lastIndex = (f) => { for (let k = plan.length - 1; k >= 0; k--) if (f(PLAN[plan[k]])) return k; return -1 }
228  const firstIndex = (f) => plan.findIndex((i) => f(PLAN[i]))
229  let at, parts
230  if (id === 'drop') { const o = lastIndex((p) => p.section === 'outro'); at = o < 0 ? plan.length : o; parts = [6, 9] }
231  else if (id === 'groove') { const g = lastIndex((p) => p.section === 'groove'); at = g < 0 ? Math.min(1, plan.length) : g + 1; parts = [3] }
232  else if (id === 'build') { const d = firstIndex((p) => p.section === 'drop'); at = d < 0 ? plan.length : d; parts = [4] }
233  else if (id === 'break') { const d = lastIndex((p) => p.section === 'drop'); at = d < 0 ? plan.length : d; parts = [6] }
234  else return { plan, at: 0, count: 0 }
235  if (plan.length + parts.length > 24) return { plan, at: 0, count: 0 }
236  plan.splice(at, 0, ...parts)
237  return { plan, at, count: parts.length }
238}
239
240// Old codes (p0..p9) named parts of the old ten-part build; `parseCode` moves
241// them to the same section here. New codes use a<n>.
242const OLD_PARTS = [0, 1, 2, 3, 4, 5, 7, 6, 9, 10]
243
244// The handover (auto, after the outro): the old track takes its layers out
245// while the new one comes in, and the new song starts from its beginning
246// (Ruslan, 2026-10-04: "start the next song from the kick or hihats").
247// Two shapes, picked by `transitionsOf(old).land`:
248//   kick  the old track thins to its kick and hats, then the new song starts
249//         from its own kick (part 0)
250//   hats  the new song's hats come in over the old low end, then its kick and
251//         bass land under them (part 2, "hats")
252// Each step plays HANDOVER_LOOPS loops. The last loop builds up, the landing
253// gets a crash and a boom.
254export const HANDOVERS = {
255  kick: { to: 0, steps: [{ from: ['kick', 'bass', 'hats', 'rumble', 'perc'], to: [] }, { from: ['kick', 'hats'], to: [] }] },
256  hats: { to: 2, steps: [{ from: ['kick', 'bass', 'rumble', 'perc'], to: ['hats'] }, { from: ['kick', 'bass'], to: ['hats'] }] },
257}
258export const HANDOVER_LOOPS = 2
259
260// The transitions auto plays (Ruslan, 2026-10-04: "i love all 3 ... do it
261// randomly ... but so that it always fits the song"). The track's phrase and
262// dice seed every pick, so a share code always plays the same transitions.
263//   build: the loop before each drop (parts with `rise`)
264//   fall:  the last loop of each drop, into the breakdown or the outro
265//   swell: a short reversed cymbal into a new sound in the intro and groove
266//   swap:  the build-up before the low end swaps in the handover
267//   land:  where the next song starts after the handover, `kick` or `hats`
268// The rules that make a pick fit: the mood weights the packs (sad leans on
269// the riser and the filter, dark on the filter, echo and stutter), a song
270// never plays the same build or fall twice in a row, and the last drop gets
271// one of the two biggest builds.
272export const BUILDS = ['riser', 'filter', 'echo', 'stutter']
273export const FALLS = ['tapestop', 'washout', 'downlifter']
274const BUILD_WEIGHTS = { sad: [3, 3, 2, 1], mysterious: [2, 2, 3, 2], dark: [1, 3, 3, 3] }
275const FALL_WEIGHTS = { sad: [1, 3, 2], mysterious: [2, 2, 2], dark: [3, 1, 2] }
276const LAND_WEIGHTS = { sad: [2, 1], mysterious: [1, 1], dark: [1, 2] }
277const weighted = (r, names, weights, not = []) => {
278  const ok = names.map((n, i) => (not.includes(n) ? 0 : weights[i]))
279  let x = r() * ok.reduce((a, b) => a + b, 0)
280  for (let i = 0; i < names.length; i++) if ((x -= ok[i]) < 0) return names[i]
281  return names.find((n) => !not.includes(n))
282}
283export function transitionsOf(input) {
284  const t = cleanTrack(input)
285  const r = rng(hash32('fx:' + t.phrase + ':' + t.dice))
286  const mood = moodName(t)
287  const plan = planOf(t)
288  const at = (k) => PLAN[plan[k]]
289  // keyed by the position in the track's plan; a build goes on the part
290  // right before a drop, a fall on the last loop of a drop
291  const out = { build: {}, fall: {}, swell: {}, swap: null, land: 'kick' }
292  let last = null
293  const rises = plan.map((_, k) => (at(k).section !== 'drop' && at(k + 1)?.section === 'drop' ? k : -1)).filter((k) => k >= 0)
294  for (const k of rises) {
295    const final = k === rises[rises.length - 1]
296    last = out.build[k] = weighted(r, BUILDS, BUILD_WEIGHTS[mood], [last, ...(final ? ['echo', 'stutter'] : [])])
297  }
298  last = null
299  plan.forEach((_, k) => { if (at(k).section === 'drop') last = out.fall[k] = weighted(r, FALLS, FALL_WEIGHTS[mood], [last]) })
300  plan.forEach((_, k) => { if (at(k + 1)?.adds && !rises.includes(k) && at(k).section !== 'drop' && at(k).section !== 'break') out.swell[k] = r() < 0.6 })
301  out.swap = weighted(r, BUILDS, BUILD_WEIGHTS[mood], [out.build[rises[rises.length - 1]]])
302  out.land = weighted(r, ['kick', 'hats'], LAND_WEIGHTS[mood])
303  return out
304}
305
306// ---------- seed helpers ----------
307
308export function normalizePhrase(text) {
309  return String(text ?? '')
310    .toLowerCase()
311    .normalize('NFKD')
312    .replace(/[̀-ͯ]/g, '')
313    .replace(/[^a-z0-9]+/g, ' ')
314    .trim()
315    .slice(0, 60)
316    .trim()
317}
318
319function hash32(str) {
320  let h = 0x811c9dc5
321  for (let i = 0; i < str.length; i++) {
322    h ^= str.charCodeAt(i)
323    h = Math.imul(h, 0x01000193)
324  }
325  return h >>> 0
326}
327
328function rng(seed) {
329  let a = seed >>> 0
330  return () => {
331    a = (a + 0x6d2b79f5) >>> 0
332    let t = a
333    t = Math.imul(t ^ (t >>> 15), t | 1)
334    t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
335    return ((t ^ (t >>> 14)) >>> 0) / 4294967296
336  }
337}
338
339const pick = (r, list) => list[Math.floor(r() * list.length)]
340const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v))
341const toInt = (v, lo, hi, fallback) => (Number.isFinite(Number(v)) ? clamp(Math.round(Number(v)), lo, hi) : fallback)
342
343// ---------- the track state ----------
344
345// The default track for a phrase. Everything not given here comes from the phrase.
346export function trackFor(phrase) {
347  const p = normalizePhrase(phrase) || 'techno'
348  const r = rng(hash32('track:' + p))
349  // every new track is dark; the phrase picks its style (0.10)
350  const style = Math.floor(r() * STYLES.length)
351  const base = { phrase: p, bpm: 130, mood: 0, energy: 2, dice: 0, swing: 0, transpose: 0, scale: null, part: null, layers: {}, steps: {}, inst: {}, notes: {}, tone: {}, master: [0, 0, 0], plan: null, style: null }
352  return styled(base, style)
353}
354
355// The track at a part of the build: the plan's energy, the plan's layers
356// (explicit mutes cleared), your own step edits kept.
357export function atPart(input, part) {
358  const t = cleanTrack(input)
359  const p = clamp(part, 0, PLAN.length - 1)
360  const lift = liftOf(t)
361  return { ...t, part: p, energy: clamp(PLAN[p].energy + lift, 0, 4), layers: {} }
362}
363
364// Fills gaps and clamps every field, so a state from a code or a tool call is safe.
365export function cleanTrack(t) {
366  const base = trackFor(t?.phrase)
367  const layers = {}
368  for (const name of LAYERS) {
369    const v = t?.layers?.[name]
370    if (v === true || v === false) layers[name] = v
371  }
372  const steps = {}
373  for (const name of GRID_LAYERS) {
374    const v = t?.steps?.[name]
375    if (!Array.isArray(v)) continue
376    const on = toInt(v[0], 0, 0xffff, 0), off = toInt(v[1], 0, 0xffff, 0) & ~on
377    if (on || off) steps[name] = [on, off]
378  }
379  const part = t?.part === null || t?.part === undefined ? null : toInt(t.part, 0, PLAN.length - 1, null)
380  // a style track keeps an explicit 0 (the style would pick another sound)
381  const style = t?.style === null || t?.style === undefined ? null : toInt(t.style, 0, STYLES.length - 1, null)
382  const inst = {}
383  for (const [name, list] of Object.entries(INSTRUMENTS)) {
384    const raw = t?.inst?.[name]
385    if (raw === undefined || raw === null) continue
386    const v = toInt(raw, 0, list.length - 1, 0)
387    if (v || style !== null) inst[name] = v
388  }
389  const notes = {}
390  for (const name of NOTE_LAYERS) { const v = t?.notes?.[name]; if (typeof v === 'string' && NOTE_RE.test(v) && /[^.]/.test(v)) notes[name] = v }
391  const tone = {}
392  for (const name of TONE_LAYERS) {
393    const v = t?.tone?.[name]
394    if (!Array.isArray(v)) continue
395    const cut = toInt(v[0], -3, 3, 0), grit = toInt(v[1], 0, 3, 0)
396    if (cut || grit) tone[name] = [cut, grit]
397  }
398  let plan = Array.isArray(t?.plan) && t.plan.length >= 2 && t.plan.length <= 24 ? t.plan.map((x) => toInt(x, 0, PLAN.length - 1, 0)) : null
399  if (plan && sameAsPlan(plan)) plan = null
400  const mv = Array.isArray(t?.master) ? t.master : []
401  const master = [toInt(mv[0], -3, 0, 0), toInt(mv[1], 0, 3, 0), toInt(mv[2], -2, 2, 0)]
402  return {
403    phrase: base.phrase,
404    bpm: toInt(t?.bpm, BPM_MIN, BPM_MAX, base.bpm),
405    mood: toInt(t?.mood, 0, 4, base.mood),
406    energy: toInt(t?.energy, 0, 4, base.energy),
407    dice: toInt(t?.dice, 0, 999, 0),
408    swing: toInt(t?.swing, 0, 3, 0),
409    transpose: toInt(t?.transpose, 0, 11, 0),
410    scale: t?.scale === null ? null : t?.scale === undefined ? base.scale : toInt(t.scale, 0, SCALES.length - 1, null),
411    part,
412    layers,
413    steps,
414    inst,
415    notes,
416    tone,
417    master,
418    plan,
419    style,
420  }
421}
422
423function character(t) {
424  const r = rng(hash32('char:' + t.phrase))
425  return { flavor: r() < 0.5 ? 'acid' : 'dub', keyClass: pick(r, KEY_CLASSES) }
426}
427
428// Which layers play: an explicit on/off wins, otherwise mood and energy decide.
429export function activeLayers(t) {
430  if (t.part !== null && t.part !== undefined) {
431    const st = styleOf(t)
432    const plan = PLAN[t.part].layers
433    const lead = leadOf(t)
434    const extras = extrasOf(t)
435    const inPlan = (name) => st ? !st.drops.includes(name) && (plan.includes(name) || !!st.adds[name]?.includes(t.part) || (name === 'acid' && !!lead && LEADS[lead].parts.includes(t.part)) || (extras.includes(name) && EXTRAS[name].includes(t.part))) : plan.includes(name)
436    const out = {}
437    for (const name of LAYERS) out[name] = t.layers[name] ?? (inPlan(name) && (name !== 'rumble' || t.mood <= 2))
438    return out
439  }
440  const auto = {
441    kick: true,
442    bass: true,
443    hats: true,
444    clap: t.energy >= 1,
445    perc: t.energy >= 2,
446    acid: false,
447    stab: false,
448    rumble: t.mood <= 1 && t.energy >= 1,
449    voice: false,
450    ride: t.energy >= 4,
451    pad: false,
452  }
453  const out = {}
454  for (const name of LAYERS) out[name] = t.layers[name] ?? auto[name]
455  return out
456}
457
458export function noteName(t) {
459  return NOTE_NAMES[(character(t).keyClass + t.transpose) % 12]
460}
461
462export function scaleName(t) {
463  return SCALES[scaleOf(t)].name
464}
465
466export function keyName(t) {
467  return noteName(t) + ' ' + scaleName(t)
468}
469
470export function describe(t) {
471  return `${t.bpm} bpm · key ${keyName(t)} · ${styleOf(t) ? 'style ' + styleName(t) : 'mood ' + moodName(t)} · energy ${ENERGIES[t.energy]}`
472}
473
474// ---------- share codes ----------
475// late-night-deploy@128m1e2d3s1t5p4+acid-perc*kick00040000
476// a<n> is the part of the build (p<n> in old codes); *<layer><on hex4><off hex4> are step edits.
477
478const hex4 = (n) => n.toString(16).padStart(4, '0')
479
480export function encodeCode(t) {
481  let code = t.phrase.replace(/ /g, '-') + '@' + t.bpm + 'm' + t.mood + 'e' + t.energy
482  if (t.dice) code += 'd' + t.dice
483  if (t.swing) code += 's' + t.swing
484  if (t.transpose) code += 't' + t.transpose
485  if (t.scale !== null && t.scale !== undefined) code += 'k' + t.scale
486  if (t.part !== null && t.part !== undefined) code += 'a' + t.part
487  for (const name of LAYERS) if (name in t.layers) code += (t.layers[name] ? '+' : '-') + name
488  for (const name of GRID_LAYERS) if (t.steps?.[name]) code += '*' + name + hex4(t.steps[name][0]) + hex4(t.steps[name][1])
489  for (const name of Object.keys(INSTRUMENTS)) if (t.inst?.[name] !== undefined && (t.inst[name] || styleOf(t))) code += '%' + name + t.inst[name]
490  for (const name of NOTE_LAYERS) if (t.notes?.[name]) code += '~' + name + t.notes[name]
491  for (const name of TONE_LAYERS) if (t.tone?.[name]) code += '^' + name + (t.tone[name][0] + 3) + t.tone[name][1]
492  const m = t.master ?? [0, 0, 0]
493  if (m[0] || m[1] || m[2]) code += '!' + (m[0] + 3) + m[1] + (m[2] + 2)
494  if (t.plan) code += '/' + t.plan.map((i) => i.toString(16)).join('')
495  if (styleOf(t)) code += 'y' + t.style
496  return code
497}
498const alt = (list) => '(?:' + list.join('|') + ')'
499const CODE_RE = new RegExp('^(\\d{2,3})(?:m([0-4]))?(?:e([0-4]))?(?:d(\\d{1,3}))?(?:s([0-3]))?(?:t(\\d{1,2}))?(?:k([0-4]))?(?:p(\\d))?(?:a(\\d{1,2}))?((?:[+-][a-z]+)*)((?:\\*[a-z]+[0-9a-f]{8})*)' +
500  '((?:%' + alt(Object.keys(INSTRUMENTS)) + '\\d)*)((?:~' + alt(NOTE_LAYERS) + '[.0-9a-e]{16})*)((?:\\^' + alt(TONE_LAYERS) + '[0-6][0-3])*)(?:!([0-3][0-3][0-4]))?(?:/([0-9a]{2,24}))?(?:y(\\d))?$')
501
502export function parseCode(text) {
503  const s = String(text ?? '').trim().toLowerCase().replace(/^\/?techno\s+/, '')
504  const at = s.lastIndexOf('@')
505  if (at <= 0) return null
506  const m = s.slice(at + 1).match(CODE_RE)
507  if (!m) return null
508  const layers = {}
509  for (const flag of m[10].match(/[+-][a-z]+/g) ?? []) {
510    const name = flag.slice(1)
511    if (!LAYERS.includes(name)) return null
512    layers[name] = flag[0] === '+'
513  }
514  const steps = {}
515  for (const edit of m[11].match(/\*[a-z]+[0-9a-f]{8}/g) ?? []) {
516    const name = edit.slice(1, -8)
517    if (!GRID_LAYERS.includes(name)) return null
518    steps[name] = [parseInt(edit.slice(-8, -4), 16), parseInt(edit.slice(-4), 16)]
519  }
520  const inst = {}, notes = {}, tone = {}
521  for (const x of m[12].match(/%[a-z]+\d/g) ?? []) inst[x.slice(1, -1)] = Number(x.slice(-1))
522  for (const x of m[13].match(/~[a-z]+[.0-9a-e]{16}/g) ?? []) notes[x.slice(1, -16)] = x.slice(-16)
523  for (const x of m[14].match(/\^[a-z]+\d\d/g) ?? []) tone[x.slice(1, -2)] = [Number(x.slice(-2, -1)) - 3, Number(x.slice(-1))]
524  const master = m[15] ? [Number(m[15][0]) - 3, Number(m[15][1]), Number(m[15][2]) - 2] : [0, 0, 0]
525  return cleanTrack({ phrase: s.slice(0, at), bpm: m[1], mood: m[2], energy: m[3], dice: m[4], swing: m[5], transpose: m[6], scale: m[7] ?? null, part: m[9] ?? (m[8] === undefined ? null : OLD_PARTS[m[8]]), layers, steps, inst, notes, tone, master, plan: m[16] ? [...m[16]].map((c) => parseInt(c, 16)) : null, style: m[17] ?? null })
526}
527
528// ---------- the arrangement: what plays on each of the 128 steps ----------
529
530const BASS_PATTERNS = ['..x...x...x...x.', '.xx..xx..xx..xx.', '..xx..xx..xx..xx', '.xxx.xxx.xxx.xxx', '..x..xx...x..xx.', '...x..x...x..x.x']
531const PERC_PATTERNS = ['.x..x.....x..x..', '...x..x....x..x.', 'x..x..x..x..x...', '.x.x...x.x...x..', '..x....x..x...x.']
532const CONGA_PATTERNS = ['..l..m.h..l..m..', 'h..m..l.h..m.l..', '.m.l..h..m.l..h.', 'l.mh..m.l.mh..m.', '..h.l..m..h.l.m.', 'm..l.h..m..l.hh.']
533const STAB_PATTERNS = ['..x.......x.....', '...x......x.....', '..x..x....x.....', '.......x..x....x']
534// The bass lines of a style song (Ruslan, 2026-10-12: "make the bass lines a
535// bit more diverse ... it feels like it's always the same"; then "too much
536// melody ... i'd prefer the whole song to be in one tonality"). They differ
537// in rhythm, not in melody: the root, its octave, and at most one step
538// under the root. Two bars each, 16 steps a bar: '.' a rest, '-' holds the
539// note before, a digit a scale degree (0 the root, 7 the octave), 'a' one
540// degree under the root. A song plays one line in its intro, groove and
541// build, and a busier one in its drops; a new rhythm (dice) picks again.
542export const BASS_LINES = [
543  ['..0...0...0...0.', '..0...0...0...0.'], // offbeat, the classic
544  ['.07..07..07..07.', '.07..07..07..07.'], // rolling, up the octave
545  ['.000.000.000.000', '.000.000.000.077'], // gallop, the octave at the end
546  ['0000000000000000', '0000000000007777'], // a 16th roll
547  ['0..0..0.0..0..0.', '0..0..0.0..0..7.'], // 3-3-2
548  ['0-------....0---', '0-------....7-0-'], // long notes
549  ['..0...0...0..7.0', '..0...0...0..7.0'], // offbeat with an octave pickup
550  ['..0...0...0...0a', '..0...0...0...0a'], // offbeat, a step under the root into the bar
551  ['..0-....0-....7-', '..0-....0-....0-'], // dub, held and sparse
552  ['0..0..0..0..0..0', '..0..0..0..0..0.'], // three against four
553  ['...0......0..0..', '...0......0..7..'], // sparse
554  ['.0.0.7.0.0.7.0.0', '.0.0.7.0.0.7.0.7'], // bouncing on the octave
555]
556const BUSY = [1, 2, 3, 4, 6, 7, 9, 11] // the lines a drop may play
557const ACID_PALETTE = [0, 7, 0, 4, 0, 2, 0, 6, 0, 9, 3, 0, 4, 7, 0, 1, 0, 5, 0, 4, 2, 0, 7, 0, 6, 0, 3, 4, 0, 7, 2, 0, 9, 0, 4, 5]
558
559function charCode(ch) {
560  const c = ch.charCodeAt(0)
561  return c >= 97 ? c - 97 : 26 + (c - 48)
562}
563
564export function arrange(input) {
565  const t = cleanTrack(input)
566  const { keyClass } = character(t)
567  const on = activeLayers(t)
568  const st = styleOf(t)
569  const inst = instOf(t)
570  const r = rng(hash32('arr:' + t.phrase + ':' + t.dice))
571  const scale = SCALES[scaleOf(t)].steps
572  // the sub's root, e1..d#2: low enough to feel, the growl sits an octave up
573  const root = 28 + (((keyClass + t.transpose) % 12) + 8) % 12
574  // without a picked scale the mood keeps its old chord; a picked scale stacks its own
575  // Chords stay dark: a minor triad and the octave where the scale has a minor
576  // third, and root, fifth, octave where it has none (hijaz, the mysterious
577  // mood). A major third or a seventh sounded bright and bluesy there
578  // (Ruslan, 2026-10-04: "they destroy the vibe, something is off").
579  const minorThird = scale[2] === 3
580  const chordShape = t.scale === null ? CHORDS[t.mood] : minorThird ? [0, 3, 7, 12] : [0, 7, 12]
581  const degree = (d) => scale[((d % 7) + 7) % 7] + 12 * Math.floor(d / 7)
582
583  const bassPattern = t.energy === 0 ? BASS_PATTERNS[0] : pick(r, BASS_PATTERNS)
584  // a style song's two bass lines: one for the groove, a busier one for the drops
585  const lineSeed = hash32('bass:' + t.phrase + ':' + t.dice)
586  const grooveLine = lineSeed % BASS_LINES.length
587  let dropLine = BUSY[(lineSeed >>> 8) % BUSY.length]
588  if (dropLine === grooveLine) dropLine = BUSY[((lineSeed >>> 8) + 1) % BUSY.length]
589  const line = st ? BASS_LINES[t.part !== null && t.part !== undefined && PLAN[t.part].section === 'drop' ? dropLine : grooveLine] : null
590  const lineDegree = (c) => (c === 'a' ? -1 : Number(c))
591  const bassIntervals = [0, 0, 12, 0, 0, 7, 0, 0].map((v) => (scale[1] === 1 && v === 7 ? 1 : v))
592  const percPattern = pick(r, PERC_PATTERNS)
593  const percPick = pick(r, ['rim', 'tom', 'bell'])
594  const percKind = inst.perc ? INSTRUMENTS.perc[inst.perc] : percPick
595  const stabSlot = Math.floor(r() * STAB_PATTERNS.length)
596  const kickGhost = t.energy >= 4 && r() < 0.6
597  // the extras' patterns, picked by the phrase
598  const congaPattern = CONGA_PATTERNS[hash32('conga:' + t.phrase + ':' + t.dice) % CONGA_PATTERNS.length]
599  // the hypnotic lead loops its line over 3, 5 or 7 steps against the bar
600  const cycle = leadOf(t) === 'hypnotic' ? [3, 5, 7][hash32('cyc:' + t.phrase + ':' + t.dice) % 3] : 0
601
602  // The riff: one phrase character per step, so the phrase is the melody.
603  // A space is a rest; a vowel is an accent.
604  const chars = [...t.phrase]
605  const offset = (t.dice * 3) % Math.max(1, chars.length)
606  const riff = []
607  for (let i = 0; i < (cycle || STEPS); i++) {
608    const ch = chars[(i + offset) % chars.length] ?? ' '
609    if (ch === ' ') { riff.push(null); continue }
610    const c = charCode(ch)
611    const next = chars[(i + offset + 1) % chars.length] ?? ' '
612    riff.push({
613      note: root + 24 + degree(ACID_PALETTE[(c * 7 + t.dice * 5) % ACID_PALETTE.length]),
614      accent: 'aeiou'.includes(ch),
615      slide: next !== ' ' && (c * 13 + i) % 5 === 0,
616    })
617  }
618
619  const ev = { kick: [], bass: [], hats: [], clap: [], perc: [], acid: [], stab: [], ride: [], pad: [], conga: [], shaker: [], drone: [] }
620  for (let bar = 0; bar < BARS; bar++) {
621    const last = bar === BARS - 1
622    for (let s = 0; s < STEPS; s++) {
623      const step = bar * STEPS + s
624      // kick: four on the floor, dropped on the last beat of the loop for a lift
625      if (s % 4 === 0 && !(last && s === 12 && t.energy <= 2)) ev.kick.push({ step, vel: 1 })
626      if (kickGhost && s === 14 && bar % 2 === 1) ev.kick.push({ step, vel: 0.55 })
627      // bass
628      if (line) {
629        const c = line[bar % 2][s]
630        if (c === '-' && ev.bass.length) ev.bass[ev.bass.length - 1].len++
631        else if (c !== '.' && c !== '-') ev.bass.push({ step, note: root + degree(lineDegree(c)), vel: s % 4 === 2 ? 1 : s % 2 ? 0.75 : 0.85, len: 1 })
632      } else if (bassPattern[s] === 'x') ev.bass.push({ step, note: root + bassIntervals[(s + bar) % bassIntervals.length], vel: s % 4 === 2 ? 1 : 0.8 })
633      // hats: closed on the offbeat, then 8ths, then a ghost 16th, then 16ths; open hats from peak energy
634      const open = (t.energy >= 3 || t.mood >= 4) && s % 4 === 2
635      if (open) ev.hats.push({ step, vel: 0.9, open: true })
636      else if (t.energy === 0 ? s % 4 === 2 : t.energy === 1 ? s % 2 === 0 : t.energy === 2 ? s % 2 === 0 || s % 4 === 3 : true) ev.hats.push({ step, vel: s % 4 === 2 ? 1 : s % 2 === 0 ? 0.55 : 0.3, open: false })
637      // clap on 2 and 4, with a roll into the loop point
638      if (s === 4 || s === 12) ev.clap.push({ step, vel: 1 })
639      if (last && t.energy >= 3 && s >= 13) ev.clap.push({ step, vel: 0.35 + 0.2 * (s - 13) })
640      // perc, with a fill in bar 4
641      if (percPattern[s] === 'x' || (bar === 3 && s >= 12 && s % 2 === 1)) ev.perc.push({ step, vel: s % 3 === 0 ? 1 : 0.7, kind: percKind })
642      // acid
643      const n = cycle ? riff[step % cycle] : riff[s]
644      if (n) ev.acid.push({ step, ...n })
645      // stab: the pattern shifts every other bar so the chords breathe
646      const stabPattern = STAB_PATTERNS[(stabSlot + (bar % 2)) % STAB_PATTERNS.length]
647      if (stabPattern[s] === 'x') ev.stab.push({ step, notes: chordShape.map((i) => root + 24 + i), vel: 1 })
648      // conga: l, m, h are three tuned drums; a fill on the last beat of bar 8
649      const cg = last && s >= 12 ? 'hmhl'[s - 12] : congaPattern[s]
650      if (cg !== '.') ev.conga.push({ step, drum: 'lmh'.indexOf(cg), vel: s % 4 === 0 ? 1 : 0.75 })
651      // shaker: every 16th, the offbeat leans in
652      ev.shaker.push({ step, vel: [0.45, 0.25, 0.9, 0.3][s % 4] })
653      // ride: every 8th, the offbeat ones ring out
654      if (s % 2 === 0) ev.ride.push({ step, vel: s % 4 === 2 ? 1 : 0.55 })
655    }
656  }
657  // the drone: root, fifth and octave, held through the loop
658  ev.drone.push({ step: 0, notes: [root + 24, root + 31, root + 36] })
659  // the pad: one long swell over the loop, the root, the fifth, and the minor third above (or the octave)
660  ev.pad.push({ step: 0, notes: minorThird ? [root + 12, root + 19, root + 27] : [root + 12, root + 19, root + 24] })
661  // your step edits: the same on/off mask in every bar of the loop
662  const chord = chordShape.map((i) => root + 24 + i)
663  const fresh = { kick: () => ({ vel: 1 }), hats: () => ({ vel: 0.8, open: false }), bass: () => ({ note: root, vel: 0.9 }), perc: () => ({ vel: 0.85, kind: percKind }), clap: () => ({ vel: 1 }), acid: () => ({ note: root + 24, accent: false, slide: false }), stab: () => ({ notes: chord, vel: 1 }), ride: () => ({ vel: 0.8 }), conga: () => ({ drum: 1, vel: 0.85 }), shaker: () => ({ vel: 0.6 }) }
664  for (const [name, [onMask, offMask]] of Object.entries(t.steps)) {
665    ev[name] = ev[name].filter((e) => !(offMask & (1 << (e.step % STEPS))))
666    for (let bar = 0; bar < BARS; bar++) {
667      for (let s = 0; s < STEPS; s++) {
668        const step = bar * STEPS + s
669        if (onMask & (1 << s) && !ev[name].some((e) => e.step === step)) ev[name].push({ step, ...fresh[name]() })
670      }
671    }
672    ev[name].sort((x, y) => x.step - y.step)
673  }
674  // your notes: a scale degree per step, over the bass root (or the riff's octave)
675  for (const name of NOTE_LAYERS) {
676    const line = t.notes[name]
677    if (!line) continue
678    const base = name === 'bass' ? root : root + 24
679    for (const e of ev[name]) { const c = line[e.step % STEPS]; if (c !== '.') e.note = base + degree(parseInt(c, 36)) }
680  }
681  for (const name of Object.keys(ev)) if (!on[name]) ev[name] = []
682  return { track: t, on, root, scale, events: ev, stepSeconds: 60 / t.bpm / 4, steps: BARS * STEPS, percKind, percPick, inst, style: st }
683}
684
685// Adds or removes the hit at step `i` (0..15) of one layer, in every bar.
686// An edit that puts the step back the way the pattern has it is dropped, so
687// the share code stays short.
688export function toggleStep(input, layer, i) {
689  const t = cleanTrack(input)
690  if (!GRID_LAYERS.includes(layer) || i < 0 || i >= STEPS) return t
691  const all = { ...t, layers: Object.fromEntries(LAYERS.map((n) => [n, true])) }
692  const want = grid(all)[layer][i] === '.'
693  const rest = { ...t.steps }
694  delete rest[layer]
695  const base = grid({ ...all, steps: rest })[layer][i] !== '.'
696  let [onMask, offMask] = t.steps[layer] ?? [0, 0]
697  const bit = 1 << i
698  onMask &= ~bit; offMask &= ~bit
699  if (want !== base) { if (want) onMask |= bit; else offMask |= bit }
700  return cleanTrack({ ...t, steps: { ...rest, ...(onMask || offMask ? { [layer]: [onMask, offMask] } : {}) } })
701}
702
703// Sets one bar of a layer to a pattern (16 chars, 'x' a hit) as step edits
704// against the phrase's own pattern, so the code stays short.
705export function setPattern(input, layer, pattern) {
706  const t = cleanTrack(input)
707  if (!GRID_LAYERS.includes(layer) || !/^[x.]{16}$/.test(pattern)) return t
708  const rest = { ...t.steps }
709  delete rest[layer]
710  const base = grid({ ...t, steps: rest, layers: Object.fromEntries(LAYERS.map((n) => [n, true])) })[layer]
711  let on = 0, off = 0
712  for (let i = 0; i < STEPS; i++) {
713    if (pattern[i] === 'x' && base[i] === '.') on |= 1 << i
714    if (pattern[i] === '.' && base[i] !== '.') off |= 1 << i
715  }
716  return cleanTrack({ ...t, steps: { ...rest, ...(on || off ? { [layer]: [on, off] } : {}) } })
717}
718
719// The scale degree (0..14) a note sits on over `base`, the nearest one.
720function degreeOf(scale, base, note) {
721  let best = 0, gap = 99
722  for (let d = 0; d < 15; d++) {
723    const semis = scale[d % 7] + 12 * Math.floor(d / 7)
724    if (Math.abs(base + semis - note) < gap) { gap = Math.abs(base + semis - note); best = d }
725  }
726  return best
727}
728
729// A new note line that fits the scale: the bass leans on the root, the fifth
730// and the octave; the melody walks the scale and leaps now and then.
731export function suggestNotes(input, layer, seed) {
732  const t = cleanTrack(input)
733  const r = rng(hash32('notes:' + t.phrase + ':' + layer + ':' + seed))
734  let line = ''
735  if (layer === 'bass') {
736    const pool = [0, 0, 0, 0, 0, 0, 7, 7, 4, 4, 2, 5]
737    for (let i = 0; i < STEPS; i++) line += (i === 0 ? 0 : pool[Math.floor(r() * pool.length)]).toString(36)
738  } else {
739    let d = r() < 0.5 ? 0 : 4
740    for (let i = 0; i < STEPS; i++) {
741      line += d.toString(36)
742      d = r() < 0.15 ? (d + 7) % 12 : clamp(d + Math.floor(r() * 5) - 2, 0, 11)
743    }
744  }
745  return cleanTrack({ ...t, notes: { ...t.notes, [layer]: line } })
746}
747
748// The edit card's actions, as data: { kind, layer, ... }. Pure, so the
749// player, the tests and Claude's jam tool all go through the same door.
750export function editTrack(input, e) {
751  const t = cleanTrack(input)
752  const L = e?.layer
753  switch (e?.kind) {
754    case 'inst': return INSTRUMENTS[L] ? cleanTrack({ ...t, inst: { ...t.inst, [L]: toInt(e.value, 0, INSTRUMENTS[L].length - 1, 0) } }) : t
755    case 'pattern': return PATTERNS[L]?.[e.name] ? setPattern(t, L, PATTERNS[L][e.name]) : t
756    case 'reset-pattern': { const steps = { ...t.steps }; delete steps[L]; return cleanTrack({ ...t, steps }) }
757    case 'note': {
758      if (!NOTE_LAYERS.includes(L) || !(e.i >= 0 && e.i < STEPS)) return t
759      const a = arrange({ ...t, layers: { ...t.layers, [L]: true } })
760      const base = L === 'bass' ? a.root : a.root + 24
761      const line = [...(t.notes[L] ?? '.'.repeat(STEPS))]
762      const hit = a.events[L].find((x) => x.step === e.i)
763      const now = line[e.i] !== '.' ? parseInt(line[e.i], 36) : hit ? degreeOf(a.scale, base, hit.note) : 0
764      line[e.i] = (((now + (e.dir ?? 1)) % 8) + 8) % 8 + ''
765      return cleanTrack({ ...t, notes: { ...t.notes, [L]: line.join('') } })
766    }
767    case 'suggest-notes': return NOTE_LAYERS.includes(L) ? suggestNotes(t, L, e.seed ?? 0) : t
768    case 'reset-notes': { const notes = { ...t.notes }; delete notes[L]; return cleanTrack({ ...t, notes }) }
769    case 'tone': {
770      if (!TONE_LAYERS.includes(L)) return t
771      const [cut, grit] = t.tone[L] ?? [0, 0]
772      return cleanTrack({ ...t, tone: { ...t.tone, [L]: [clamp(cut + (e.cut ?? 0), -3, 3), clamp(grit + (e.grit ?? 0), 0, 3)] } })
773    }
774    case 'master': {
775      const m = [...t.master]
776      if (e.lp) m[0] = clamp(m[0] + e.lp, -3, 0)
777      if (e.hp) m[1] = clamp(m[1] + e.hp, 0, 3)
778      if (e.space) m[2] = clamp(m[2] + e.space, -2, 2)
779      if (e.reset) m.fill(0)
780      return cleanTrack({ ...t, master: m })
781    }
782    default: return t
783  }
784}
785
786// What the edit card shows for one sound: its instruments, the pattern to
787// try (and which one plays), its notes per step (names, or null on a rest),
788// the scale's notes, and its tone.
789export function soundInfo(input, layer) {
790  const t = cleanTrack(input)
791  const a = arrange({ ...t, layers: { ...t.layers, [layer]: true } })
792  const row = GRID_LAYERS.includes(layer) ? grid({ ...t, layers: { ...t.layers, [layer]: true } })[layer] ?? '.'.repeat(STEPS) : null
793  const hide = styleOf(t) ? NOT_IN_STYLE[layer] ?? [] : []
794  const insts = INSTRUMENTS[layer] ? INSTRUMENTS[layer].map((name, i) => ({ name: (layer === 'perc' && i === 0) || hide.includes(name) ? null : name, value: i })).filter((x) => x.name) : []
795  const inst = layer === 'perc' ? a.percKind : INSTRUMENTS[layer]?.[a.inst[layer] ?? 0] ?? null
796  const presets = Object.entries(PATTERNS[layer] ?? {}).map(([name, p]) => ({ name, on: !!row && [...p].every((c, i) => (c === 'x') === (row[i] !== '.')) }))
797  let notes = null
798  if (NOTE_LAYERS.includes(layer)) {
799    notes = Array(STEPS).fill(null)
800    for (const e of a.events[layer]) if (e.step < STEPS) notes[e.step] = NOTE_NAMES[e.note % 12]
801  }
802  const root = a.root % 12
803  return {
804    layer,
805    insts,
806    inst,
807    presets,
808    edited: !!t.steps[layer],
809    notes,
810    notesEdited: !!t.notes[layer],
811    scale: a.scale.map((x) => NOTE_NAMES[(root + x) % 12]),
812    tone: t.tone[layer] ?? [0, 0],
813    hasTone: TONE_LAYERS.includes(layer),
814  }
815}
816
817// One bar of the arrangement as text, for the pane: 'x' a hit, 'X' an accent.
818export function grid(input, bar = 0) {
819  const a = arrange(input)
820  const out = {}
821  for (const name of GRID_LAYERS) {
822    if (!a.on[name]) continue
823    const row = Array(STEPS).fill('.')
824    for (const e of a.events[name]) {
825      if (Math.floor(e.step / STEPS) !== bar) continue
826      row[e.step % STEPS] = e.accent || e.open ? 'X' : 'x'
827    }
828    out[name] = row.join('')
829  }
830  return out
831}
832
833// ---------- DSP ----------
834
835const TAU = Math.PI * 2
836const mtof = (m) => 440 * Math.pow(2, (m - 69) / 12)
837
838function soft(x) {
839  if (x > 3) return 1
840  if (x < -3) return -1
841  const x2 = x * x
842  return (x * (27 + x2)) / (27 + 9 * x2)
843}
844
845function polyblep(t, dt) {
846  if (t < dt) { t /= dt; return t + t - t * t - 1 }
847  if (t > 1 - dt) { t = (t - 1) / dt; return t * t + t + t + 1 }
848  return 0
849}
850
851// State-variable filter (Simper's trapezoidal form). mode: 0 low, 1 band, 2 high.
852function svf() {
853  let ic1 = 0, ic2 = 0, a1 = 0, a2 = 0, a3 = 0, k = 1
854  return {
855    set(fc, sr, q) {
856      const g = Math.tan(Math.PI * Math.min(fc, sr * 0.45) / sr)
857      k = 1 / q
858      a1 = 1 / (1 + g * (g + k)); a2 = g * a1; a3 = g * a2
859    },
860    run(v0, mode) {
861      const v3 = v0 - ic2
862      const v1 = a1 * ic1 + a2 * v3
863      const v2 = ic2 + a2 * ic1 + a3 * v3
864      ic1 = 2 * v1 - ic1; ic2 = 2 * v2 - ic2
865      return mode === 0 ? v2 : mode === 1 ? v1 : v0 - k * v1 - v2
866    },
867  }
868}
869
870function noiseSource(seed) {
871  let s = seed >>> 0 || 1
872  return () => {
873    s ^= s << 13; s ^= s >>> 17; s ^= s << 5
874    return ((s >>> 0) / 4294967296) * 2 - 1
875  }
876}
877
878// The kick: a sine that falls from a click to a deep tail, driven into a
879// soft clipper, with a short filtered-noise transient on top.
880function renderKick(buf, sr, at, vel, k, noise) {
881  const start = Math.round(at * sr)
882  const len = Math.min(Math.round(Math.max(0.55, k.ampDecay * 2.4) * sr), buf.length - start)
883  const fade = Math.round(0.04 * sr)
884  const hp = svf(); hp.set(3500, sr, 0.7)
885  const lp = k.lp ? svf() : null
886  if (lp) lp.set(k.lp, sr, 0.8)
887  let ph = 0
888  for (let i = 0; i < len; i++) {
889    const t = i / sr
890    const f = k.f1 + (k.f0 - k.f1) * Math.exp(-t / k.pitchDecay) + (k.click ?? 260) * Math.exp(-t / 0.0045)
891    ph += (TAU * f) / sr
892    let amp = Math.exp(-t / k.ampDecay) * (0.75 + 0.25 * Math.exp(-t / 0.04))
893    if (i > len - fade) amp *= (len - i) / fade
894    let s = soft(Math.sin(ph) * amp * k.drive) * 0.95
895    if (lp) s = lp.run(s, 0) * 1.1
896    if (t < 0.006) s += hp.run(noise(), 2) * 0.45 * (1 - t / 0.006)
897    buf[start + i] += s * vel
898  }
899}
900
901// The bass: a driven sine sub at the note (e1..d#2, felt more than heard)
902// under two detuned saws an octave up through a 4-pole low-pass, so it rolls
903// and growls and still reads on laptop speakers. Saturated at the end.
904// mode 'reese': the saws sit at the note itself, wider apart, and the filter
905// does not snap, so it beats slowly and dark. mode 'fm': a sine that a second
906// sine at the same pitch bends, hard at the start, a metallic knock.
907function renderBass(buf, sr, at, dur, midi, vel, cutoff, grit, noise, q = 0.8, mode = null) {
908  const start = Math.round(at * sr)
909  const len = Math.min(Math.round(dur * sr), buf.length - start)
910  const f = mtof(midi)
911  const wide = mode === 'reese' ? [1.009, 0.991] : [2.012, 1.988]
912  const d1 = (f * wide[0]) / sr, d2 = (f * wide[1]) / sr, d0 = f / sr
913  const lp1 = svf(), lp2 = svf()
914  let p0 = 0, p1 = noise() * 0.5 + 0.5, p2 = noise() * 0.5 + 0.5
915  const rel = Math.min(len, Math.round(0.008 * sr))
916  for (let i = 0; i < len; i++) {
917    const t = i / sr
918    p0 += d0; if (p0 >= 1) p0 -= 1
919    p1 += d1; if (p1 >= 1) p1 -= 1
920    p2 += d2; if (p2 >= 1) p2 -= 1
921    const saws = mode === 'fm' ? Math.sin(TAU * p0 + 3.2 * Math.exp(-t / 0.05) * Math.sin(TAU * p1 * 0.5)) * 2 : (2 * p1 - 1 - polyblep(p1, d1)) + (2 * p2 - 1 - polyblep(p2, d2))
922    if ((i & 15) === 0) {
923      const fc = cutoff * (1 + (mode === 'reese' ? 0.3 : 2.4) * Math.exp(-t / 0.045))
924      lp1.set(fc, sr, q); lp2.set(fc, sr, q + 0.1)
925    }
926    const body = lp2.run(lp1.run(saws * 0.45, 0), 0)
927    const sub = soft(Math.sin(TAU * p0) * 1.7)
928    const env = Math.min(1, t / 0.004) * (0.7 + 0.3 * Math.exp(-t / 0.12)) * (i > len - rel ? (len - i) / rel : 1)
929    buf[start + i] += soft((body * grit * 0.85 + sub) * 1.35) * 0.8 * env * vel
930  }
931}
932
933// Hats: mostly high-passed noise with a little metal, so they hiss like a
934// real 909 instead of buzzing like a chip.
935const HAT_FREQS = [205.3, 304.4, 369.6, 522.7, 540, 800]
936// tight, long, metal, dusty
937// tight, long, metal, dusty, brush (a slow attack, no metal)
938const HAT_KINDS = [{ decay: 1, metal: 0.035, hp: 8200 }, { decay: 2.4, metal: 0.035, hp: 7600 }, { decay: 1.3, metal: 0.28, hp: 6500 }, { decay: 1.1, metal: 0.02, hp: 4200 }, { decay: 1.9, metal: 0, hp: 5200, attack: 0.007 }]
939
940function renderHat(buf, sr, at, vel, open, tone, noise, v = HAT_KINDS[0]) {
941  const start = Math.round(at * sr)
942  const decay = (open ? 0.2 : 0.026) * v.decay
943  const len = Math.min(Math.round(decay * 6 * sr), buf.length - start)
944  const hp = svf(); hp.set(v.hp, sr, 0.7)
945  const bp = svf(); bp.set(11500, sr, 0.6)
946  const phases = HAT_FREQS.map(() => 0)
947  for (let i = 0; i < len; i++) {
948    const t = i / sr
949    let metal = 0
950    for (let j = 0; j < 6; j++) {
951      phases[j] += (HAT_FREQS[j] * tone * 2) / sr
952      if (phases[j] >= 1) phases[j] -= 1
953      metal += phases[j] < 0.5 ? 1 : -1
954    }
955    const x = metal * v.metal + noise() * 0.9
956    const env = Math.min(1, t / (v.attack ?? 0.0008)) * Math.exp(-t / decay)
957    const y = hp.run(x, 2)
958    buf[start + i] += (y * 0.6 + bp.run(y, 1) * 0.8) * env * vel
959  }
960}
961
962// room (the 909-ish clap), snap (short and higher), snare (a body under the
963// noise), industrial (a lower snare driven hard; no style picks it, the edit card does)
964function renderClap(buf, sr, at, vel, noise, kind = 0) {
965  const start = Math.round(at * sr)
966  const len = Math.min(Math.round(0.35 * sr), buf.length - start)
967  const snare = kind === 2 || kind === 3
968  const bp = svf(); bp.set(kind === 1 ? 1700 : kind === 2 ? 1900 : kind === 3 ? 1300 : 1050, sr, kind === 3 ? 0.6 : kind === 2 ? 0.8 : 1.5)
969  const tail = kind === 1 ? 0.04 : kind === 2 ? 0.13 : kind === 3 ? 0.16 : 0.11
970  let ph = 0
971  for (let i = 0; i < len; i++) {
972    const t = i / sr
973    let env = 0
974    for (const o of snare ? [0] : [0, 0.011, 0.022]) if (t >= o) env = Math.max(env, Math.exp(-(t - o) / 0.0045))
975    if (t >= 0.03 || snare) env = Math.max(env, 0.55 * Math.exp(-Math.max(0, t - (snare ? 0.004 : 0.03)) / tail))
976    let x = bp.run(noise(), 1) * env * 2.2
977    if (snare) { ph += ((kind === 3 ? 150 : 185) * (1 + 0.5 * Math.exp(-t / 0.01))) / sr; x += Math.sin(TAU * ph) * Math.exp(-t / 0.07) * 0.8 }
978    if (kind === 3) x = Math.tanh(x * 2.6) * 0.75
979    buf[start + i] += x * vel
980  }
981}
982
983function renderPerc(buf, sr, at, vel, kind, pitch, noise) {
984  const start = Math.round(at * sr)
985  const len = Math.min(Math.round((kind === 'tom' || kind === 'metal' ? 0.3 : 0.12) * sr), buf.length - start)
986  const hp = kind === 'metal' ? svf() : null
987  if (hp) hp.set(700, sr, 0.7)
988  let ph = 0, ph2 = 0, ph3 = 0
989  for (let i = 0; i < len; i++) {
990    const t = i / sr
991    let s
992    if (kind === 'tom') {
993      const f = pitch * (1 + 0.8 * Math.exp(-t / 0.02))
994      ph += f / sr
995      s = Math.sin(TAU * ph) * Math.exp(-t / 0.09)
996    } else if (kind === 'metal') {
997      // an inharmonic clang: a sine through two detuned modulators, high-passed
998      ph += (pitch * 3.1) / sr; ph2 += (pitch * 3.1 * 1.414) / sr; ph3 += (pitch * 3.1 * 2.76) / sr
999      const m = 2.2 * Math.exp(-t / 0.05)
1000      s = hp.run(Math.sin(TAU * ph + m * Math.sin(TAU * ph2) + 0.8 * m * Math.sin(TAU * ph3)) + noise() * 0.25 * Math.exp(-t / 0.006), 2) * Math.exp(-t / 0.07) * 0.8
1001    } else if (kind === 'wood') {
1002      // a woodblock: a high sine that dies at once, with a hollow overtone
1003      ph += (pitch * 5.5) / sr; ph2 += (pitch * 5.5 * 2.3) / sr
1004      s = (Math.sin(TAU * ph) + 0.3 * Math.sin(TAU * ph2) * Math.exp(-t / 0.006)) * Math.exp(-t / 0.022)
1005    } else if (kind === 'bell') {
1006      ph += (pitch * 4) / sr; ph2 += (pitch * 4 * 1.48) / sr
1007      s = Math.sin(TAU * ph + 1.5 * Math.sin(TAU * ph2)) * Math.exp(-t / 0.045) * 0.7
1008    } else {
1009      ph += (pitch * 6) / sr
1010      s = (Math.sin(TAU * ph) * 0.6 + noise() * 0.4) * Math.exp(-t / 0.012)
1011    }
1012    buf[start + i] += s * vel
1013  }
1014}
1015
1016function renderStab(buf, sr, at, notes, vel, cutoff, noise) {
1017  const start = Math.round(at * sr)
1018  const len = Math.min(Math.round(0.4 * sr), buf.length - start)
1019  const flt = svf()
1020  const osc = []
1021  for (const n of notes) for (const d of [-0.12, 0, 0.12]) osc.push({ dt: mtof(n + d) / sr, ph: noise() * 0.5 + 0.5 })
1022  const gain = 0.5 / Math.sqrt(osc.length)
1023  for (let i = 0; i < len; i++) {
1024    const t = i / sr
1025    let x = 0
1026    for (const o of osc) {
1027      o.ph += o.dt; if (o.ph >= 1) o.ph -= 1
1028      x += 2 * o.ph - 1 - polyblep(o.ph, o.dt)
1029    }
1030    if ((i & 15) === 0) flt.set(cutoff * (1 + 1.5 * Math.exp(-t / 0.05)), sr, 1.4)
1031    const env = Math.min(1, t / 0.003) * Math.exp(-t / 0.11)
1032    buf[start + i] += flt.run(x * gain, 0) * env * vel
1033  }
1034}
1035
1036// The acid line is one monophonic voice through the whole loop, so notes can
1037// slide into each other the way a TB-303 does.
1038function renderAcid(buf, sr, a, total, sweep) {
1039  const { stepSeconds, track: t } = a
1040  const byStep = new Map(a.events.acid.map((e) => [e.step, e]))
1041  const stepLen = stepSeconds * sr
1042  let ph = 0, freq = 110, target = 110, env = 0, amp = 0, accentAmt = 0
1043  let y1 = 0, y2 = 0, y3 = 0, y4 = 0
1044  // acid, square, pluck, soft
1045  const kind = a.inst.acid
1046  const res = (0.55 + 0.08 * t.energy + (t.mood <= 1 ? 0.08 : 0)) * [1, 0.85, 0.6, 0.3][kind]
1047  const fb = res * 3.6
1048  const decay = (0.12 + 0.05 * t.mood) * [1, 1, 0.35, 1.6][kind]
1049  const glide = Math.exp(-1 / (0.035 * sr))
1050  let gateEnd = -1
1051  for (let i = 0; i < total; i++) {
1052    const stepF = i / stepLen
1053    const step = Math.floor(stepF) % a.steps
1054    if (i === Math.round(Math.floor(stepF) * stepLen)) {
1055      const e = byStep.get(step)
1056      const prev = byStep.get((step + a.steps - 1) % a.steps)
1057      if (e) {
1058        target = mtof(e.note)
1059        if (!(prev && prev.slide)) { env = 1; accentAmt = e.accent ? 1 : 0; freq = target }
1060        gateEnd = i + Math.round(stepLen * (e.slide ? 1.05 : 0.55))
1061      }
1062    }
1063    freq = target + (freq - target) * glide
1064    const gate = i < gateEnd ? 1 : 0
1065    amp += ((gate ? 1 : 0) - amp) * (gate ? 0.02 : 0.004)
1066    env *= Math.exp(-1 / (decay * sr))
1067    const dt = freq / sr
1068    ph += dt; if (ph >= 1) ph -= 1
1069    const saw = kind === 1 ? (ph < 0.5 ? 1 : -1) + polyblep(ph, dt) - polyblep((ph + 0.5) % 1, dt) : 2 * ph - 1 - polyblep(ph, dt)
1070    const fc = clamp(sweep(i) * (kind === 3 ? 0.55 : 1) * (1 + (3.5 + 3 * accentAmt) * env), 60, 9000)
1071    const g = 1 - Math.exp((-TAU * fc) / sr)
1072    const x = soft(saw - fb * y4)
1073    y1 += g * (x - y1); y2 += g * (y1 - y2); y3 += g * (y2 - y3); y4 += g * (y3 - y4)
1074    buf[i] += soft(y4 * (2.2 + fb * 0.5)) * amp * (0.75 + 0.35 * accentAmt * env)
1075  }
1076}
1077
1078// Freeverb: 8 combs and 4 allpasses per side.
1079function reverbSide(input, sr, room, damp, spread) {
1080  const scale = sr / 44100
1081  const combT = [1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617]
1082  const apT = [556, 441, 341, 225]
1083  {
1084    const combs = combT.map((n) => ({ b: new Float32Array(Math.round((n + spread) * scale)), i: 0, f: 0 }))
1085    const aps = apT.map((n) => ({ b: new Float32Array(Math.round((n + spread) * scale)), i: 0 }))
1086    const out = new Float32Array(input.length)
1087    for (let n = 0; n < input.length; n++) {
1088      const x = input[n] * 0.015
1089      let y = 0
1090      for (const c of combs) {
1091        const o = c.b[c.i]
1092        c.f = o * (1 - damp) + c.f * damp
1093        c.b[c.i] = x + c.f * room
1094        if (++c.i >= c.b.length) c.i = 0
1095        y += o
1096      }
1097      for (const a of aps) {
1098        const o = a.b[a.i]
1099        a.b[a.i] = y + o * 0.5
1100        if (++a.i >= a.b.length) a.i = 0
1101        y = o - y
1102      }
1103      out[n] = y
1104    }
1105    return out
1106  }
1107}
1108
1109function reverb(inL, inR, sr, room, damp) {
1110  return [reverbSide(inL, sr, room, damp, 0), reverbSide(inR, sr, room, damp, 23)]
1111}
1112
1113function pingPong(input, sr, delaySeconds, feedback) {
1114  const n = Math.round(delaySeconds * sr)
1115  const bl = new Float32Array(n), br = new Float32Array(n)
1116  const outL = new Float32Array(input.length), outR = new Float32Array(input.length)
1117  let i = 0, lpL = 0, lpR = 0, hpL = 0, hpR = 0
1118  const lp = 1 - Math.exp((-TAU * 2600) / sr)
1119  const hp = 1 - Math.exp((-TAU * 280) / sr)
1120  for (let s = 0; s < input.length; s++) {
1121    const dl = bl[i], dr = br[i]
1122    lpL += lp * (dl - lpL); lpR += lp * (dr - lpR)
1123    hpL += hp * (lpL - hpL); hpR += hp * (lpR - hpR)
1124    bl[i] = input[s] + (lpR - hpR) * feedback
1125    br[i] = (lpL - hpL) * feedback
1126    if (++i >= n) i = 0
1127    outL[s] = dl; outR[s] = dr
1128  }
1129  return [outL, outR]
1130}
1131
1132// ---------- the voice ----------
1133// The mod records the track's name with a free macOS voice (`say`) and hands
1134// the clips in; the engine stays pure. A clip is { data: Float32Array, rate }.
1135
1136// A 16-bit PCM WAV (as `say --file-format=WAVE` writes it) to a mono clip at
1137// peak 1. Walks the chunks, since `say` puts an FLLR chunk before the data.
1138export function decodeWav(bytes) {
1139  const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
1140  const tag = (o) => String.fromCharCode(bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3])
1141  if (bytes.length < 44 || tag(0) !== 'RIFF' || tag(8) !== 'WAVE') return null
1142  let o = 12, rate = 0, channels = 1, bits = 16
1143  while (o + 8 <= bytes.length) {
1144    const id = tag(o), size = v.getUint32(o + 4, true)
1145    if (id === 'fmt ') { channels = v.getUint16(o + 10, true); rate = v.getUint32(o + 12, true); bits = v.getUint16(o + 22, true) }
1146    if (id === 'data') {
1147      if (bits !== 16 || !rate) return null
1148      const n = Math.floor(Math.min(size, bytes.length - o - 8) / 2 / channels)
1149      const data = new Float32Array(n)
1150      let peak = 0
1151      for (let i = 0; i < n; i++) { data[i] = v.getInt16(o + 8 + i * 2 * channels, true) / 32768; peak = Math.max(peak, Math.abs(data[i])) }
1152      if (peak > 0) for (let i = 0; i < n; i++) data[i] /= peak
1153      return { data, rate }
1154    }
1155    o += 8 + size + (size & 1)
1156  }
1157  return null
1158}
1159
1160// Pitched down (the whisper three semitones, the deep voice four), band-passed
1161// like an old radio and driven a little. The echo and the room come from the sends.
1162function renderVoice(buf, sr, at, clip, pitch, gain) {
1163  const start = Math.round(at * sr)
1164  const inc = (clip.rate / sr) * pitch
1165  const n = Math.min(Math.floor((clip.data.length - 1) / inc), buf.length - start)
1166  const hp = svf(); hp.set(190, sr, 0.7)
1167  const lp = svf(); lp.set(4800, sr, 0.8)
1168  for (let i = 0; i < n; i++) {
1169    const p = i * inc, k = Math.floor(p), f = p - k
1170    const x = clip.data[k] * (1 - f) + clip.data[k + 1] * f
1171    buf[start + i] += soft(lp.run(hp.run(x, 2), 0) * 1.8) * gain
1172  }
1173}
1174
1175// ---------- render ----------
1176
1177// Renders one hit into its own buffer, so a drum is synthesized once per
1178// render and then copied to each step.
1179function template(sr, seconds, draw) {
1180  const buf = new Float32Array(Math.round(seconds * sr))
1181  draw(buf)
1182  return buf
1183}
1184
1185function stamp(buf, tpl, at, vel, sr) {
1186  const start = Math.round(at * sr)
1187  const n = Math.min(tpl.length, buf.length - start)
1188  for (let i = 0; i < n; i++) buf[start + i] += tpl[i] * vel
1189}
1190
1191// The ride: brighter, longer metal than the hats, so a drop opens up on top.
1192function renderRide(buf, sr, at, vel, tone, noise) {
1193  const start = Math.round(at * sr)
1194  const len = Math.min(Math.round(1.4 * sr), buf.length - start)
1195  const bp = svf(); bp.set(6800, sr, 0.9)
1196  const hp = svf(); hp.set(4200, sr, 0.7)
1197  const phases = HAT_FREQS.map(() => 0)
1198  for (let i = 0; i < len; i++) {
1199    const t = i / sr
1200    let metal = 0
hooks/views.js 423 lines
1// The app's screens, drawn in the band above the chat box. Pure functions:
2// they get the element table (`ui`), a view model (`vm`) and the click
3// handlers (`act`), and return a tree. No mods API here; register.js owns
4// the calls to the player.
5//
6// Layout A with the part bar (Ruslan, 2026-10-04): one line on top (previous,
7// play and next track side by side, the track, favorite, share, the volume;
8// auto and hide on the right), the part bar with the section, the style and
9// the tempo, the dancer, the grid, one line under it (new song, next part, edit, favorites), and the edit card
10// when edit is open.
11// Three screens: the deck, the favorites (with the tracks you heard), and new
12// tracks.
13//
14// A selected thing (the style, auto on) is a filled primary button, not
15// brighter text: dim against normal text cannot be read in the light theme.
16
17import { sectionLabel } from './conductor.js'
18
19const row = (ui, children, extra = {}) => ui.Box({ flexDirection: 'row', flexWrap: 'wrap', columnGap: 1, alignItems: 'center', children: children.filter(Boolean), ...extra })
20const col = (ui, children, extra = {}) => ui.Box({ flexDirection: 'column', children: children.filter(Boolean), ...extra })
21const dim = (ui, text, extra = {}) => ui.Text({ dimColor: true, children: [text], ...extra })
22const spread = (ui, left, right, key) => ui.Box({ key, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', columnGap: 2, children: [row(ui, left), row(ui, right)] })
23
24// A button that is on or off: on is the filled primary button.
25const toggle = (ui, key, label, isOn, onPress, extra = {}) => ui.Button({ key, label, onPress, ...(isOn ? { variant: 'primary' } : {}), ...extra })
26const link = (ui, key, label, onPress) => ui.Button({ key, label, plain: true, dimColor: true, onPress })
27const clock = (ms) => { const s = Math.floor(ms / 1000); return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0') }
28
29// The transport, shared by the deck and the bar: previous, play or stop,
30// next track, then the track, its heart and share, and the volume (Ruslan,
31// 2026-10-05, option B: "remove dark and 132 bpm ... move it down"; the mood
32// and the tempo sit in the bottom line now).
33function transport(ui, vm, act, prefix, hide = new Set()) {
34  const v = vm.view
35  const name = ui.Text({ bold: true, wrap: 'truncate-end', children: [v.phrase] })
36  return [
37    vm.recent.length && !hide.has('prev') ? ui.Button({ key: prefix + 'prev', label: '⏮', onPress: () => act.prev() }) : null,
38    toggle(ui, prefix + 'play', vm.playing ? '■ stop' : '▶ play', !vm.playing, () => (vm.playing ? act.stop() : act.play()), prefix ? {} : { hotkey: 'p' }),
39    ui.Button({ key: prefix + 'skip', label: '⏭', onPress: () => act.skip() }),
40    // in the bar the name gives way first: it shrinks and ends in …
41    prefix ? ui.Box({ key: prefix + 'name', flexShrink: 1, minWidth: 0, overflow: 'hidden', children: [name] }) : name,
42    hide.has('fav') ? null : ui.Button({ key: prefix + 'fav', label: vm.fav ? '♥' : '♡', plain: true, onPress: () => act.fav() }),
43    // the word, not an arrow (Ruslan, 2026-10-05, option B of arrow / word / under the grid)
44    hide.has('share') ? null : ui.Button({ key: prefix + 'share', label: 'share', onPress: () => act.copy() }),
45    hide.has('volume') ? null : volume(ui, vm, act, prefix),
46  ]
47}
48
49// The volume as one value (Ruslan, 2026-10-05, option B of digit, percent,
50// one bar: "let's keep volume as %"): `vol − 80% +`, 0 to 100 in steps of 20.
51// − and + step it; muted reads `off`; a click on `vol` mutes and brings back
52// the default.
53function volume(ui, vm, act, prefix) {
54  const level = vm.volume ?? 4
55  return ui.Box({ key: prefix + 'volume', flexDirection: 'row', flexShrink: 0, columnGap: 1, children: [
56    ui.Button({ key: prefix + 'vol-mute', label: 'vol', plain: true, dimColor: true, onPress: () => act.volume(level ? 0 : 4) }),
57    ui.Button({ key: prefix + 'vol-down', label: '−', plain: true, dimColor: !level, onPress: () => act.volume(Math.max(0, level - 1)) }),
58    ui.Text({ key: prefix + 'vol-value', bold: !!level, dimColor: !level, children: [level ? level * 20 + '%' : 'off'] }),
59    ui.Button({ key: prefix + 'vol-up', label: '+', plain: true, dimColor: level === 5, onPress: () => act.volume(Math.min(5, level + 1)) }),
60  ] })
61}
62
63// How full Claude's context window is (Ruslan, 2026-10-15: "just a circle or
64// %"): a circle that fills by quarters, then the percent. Dim until 70%, the
65// warning color from 70%, the error color from 90%. Nothing before the first
66// answer of the chat.
67const PIE = ['○', '◔', '◑', '◕', '●']
68export function contextLabel(percent) {
69  if (percent === null || percent === undefined) return null
70  return { text: PIE[Math.min(4, Math.round(percent / 25))] + ' ' + percent + '%', color: percent >= 90 ? 'error' : percent >= 70 ? 'warning' : null }
71}
72function contextFill(ui, vm, prefix) {
73  const c = contextLabel(vm.context)
74  if (!c) return null
75  return ui.Text({ key: prefix + 'context', ...(c.color ? { color: c.color } : { dimColor: true }), children: [c.text] })
76}
77
78function topLine(ui, vm, act) {
79  return spread(ui, transport(ui, vm, act, ''), [
80    contextFill(ui, vm, ''),
81    toggle(ui, 'auto', vm.auto ? '● auto' : '○ auto', vm.auto, () => act.auto(), { hotkey: 'a' }),
82    ui.Button({ key: 'close', label: 'hide', role: 'dismiss', plain: true, dimColor: true, onPress: () => act.close() }),
83  ], 'top')
84}
85
86// Where the song is, option A (Ruslan, 2026-10-04: "inline bar, one line,
87// the part name after the bar"; the section words were "too many words"):
88// one block per loop (about 15 s), so a block is the same time everywhere and
89// the bar agrees with the clock. The part that plays is in the accent, ▰ for
90// what of it played and ▱ for what is left of it (how long until the next
91// part); played parts ▰, the rest ▱ dim. Then the part's name and the time.
92export function partBar(parts, pos) {
93  let from = 0
94  return parts.flatMap((p) => {
95    const cells = Array.from({ length: p.loops }, (_, i) => {
96      const part = pos >= from + p.loops ? 'played' : pos >= from ? 'now' : 'next'
97      return part === 'now' ? (pos >= from + i + 1 ? 'now-played' : 'now-left') : part
98    })
99    from += p.loops
100    return cells
101  })
102}
103
104function whereLine(ui, vm) {
105  const v = vm.view, w = vm.where
106  if (!w) return null
107  const cells = partBar(w.parts, w.pos)
108  const runs = []
109  for (const c of cells) { const last = runs[runs.length - 1]; if (last && last.c === c) last.n++; else runs.push({ c, n: 1 }) }
110  const look = {
111    played: (n) => ui.Text({ children: ['▰'.repeat(n)] }),
112    'now-played': (n) => ui.Text({ color: 'claude', bold: true, children: ['▰'.repeat(n)] }),
113    'now-left': (n) => ui.Text({ color: 'claude', children: ['▱'.repeat(n)] }),
114    next: (n) => dim(ui, '▱'.repeat(n)),
115  }
116  return row(ui, [
117    ui.Box({ key: 'bar', flexDirection: 'row', flexShrink: 0, children: runs.map((r, i) => ({ ...look[r.c](r.n), key: 'run-' + i })) }),
118    ui.Text({ color: 'claude', bold: true, children: [sectionLabel(v)] }),
119    v.from ? dim(ui, '← from ' + v.from, { wrap: 'truncate-end' }) : null,
120    dim(ui, '· ' + clock(w.elapsed) + ' / ' + clock(w.total)),
121  ], { key: 'where', columnGap: 1 })
122}
123
124// The style and the tempo, under the song's progress and over the grid
125// (Ruslan, 2026-10-05: "progress of the song ... under it the mood, then
126// the grid"). 0.10: every song is dark ("ok dark only", Ruslan,
127// 2026-10-12), so the mood buttons are gone; the line says the sound (an
128// old song says its old mood) and the tempo.
129function styleLine(ui, vm) {
130  return row(ui, [dim(ui, vm.view.mood + ' · ' + vm.view.bpm + ' bpm', { key: 'bpm' })], { key: 'style' })
131}
132
133function bottomLine(ui, vm, act) {
134  return spread(ui, [
135    ui.Button({ key: 'new-song', label: '+ new song', onPress: () => act.screen('crate') }),
136  ], [
137    vm.auto ? null : ui.Button({ key: 'next', label: 'next part ›', onPress: () => act.next(), hotkey: 'n' }),
138    toggle(ui, 'edit', 'edit', vm.editOpen, () => act.edit(), { hotkey: 'e' }),
139    ui.Button({ key: 'favorites', label: '♥ favorites ' + vm.favorites.length, onPress: () => act.screen('favorites') }),
140  ], 'bottom')
141}
142
143// The edit card, layout B (Ruslan, 2026-10-04): tabs for the sounds that
144// play, + sound, song and master; one short card for the tab you are on.
145// Every change goes to the player as { op: 'edit', kind, ... } (editTrack).
146const SOUND_TABS = ['kick', 'bass', 'hats', 'rumble', 'clap', 'perc', 'ride', 'pad', 'acid']
147const tabName = (n) => (n === 'acid' ? 'melody' : n)
148const CUT_WORDS = ['muffled', 'dark', 'warm', 'as is', 'clear', 'bright', 'thin']
149const GRIT_WORDS = ['clean', 'warm', 'driven', 'crushed']
150const LP_WORDS = ['closed', 'dark', 'soft', 'open']
151const HP_WORDS = ['full', 'lighter', 'thin', 'tiny']
152const SPACE_WORDS = ['dry', 'tight', 'as is', 'wide', 'huge']
153const label = (ui, text) => ui.Box({ width: 8, flexShrink: 0, children: [dim(ui, text)] })
154const line = (ui, key, name, children) => ui.Box({ key, flexDirection: 'row', alignItems: 'center', columnGap: 1, children: [label(ui, name), row(ui, children)] })
155const stepper = (ui, key, words, i, onMinus, onPlus) => [
156  ui.Button({ key: key + '-down', label: '−', onPress: onMinus }),
157  ui.Box({ width: Math.max(...words.map((w) => w.length)), justifyContent: 'center', children: [ui.Text({ bold: true, children: [words[i]] })] }),
158  ui.Button({ key: key + '-up', label: '+', onPress: onPlus }),
159]
160
161function editTabs(ui, vm, act) {
162  const tabs = SOUND_TABS.filter((n) => vm.heard[n] || n === vm.editTab)
163  return spread(ui, [
164    ...tabs.map((n) => toggle(ui, 'tab-' + n, tabName(n), vm.editTab === n, () => act.editTab(n))),
165    toggle(ui, 'tab-add', '+ sound', vm.editTab === 'add', () => act.editTab('add')),
166    dim(ui, '│'),
167    toggle(ui, 'tab-song', 'song', vm.editTab === 'song', () => act.editTab('song')),
168    toggle(ui, 'tab-master', 'master', vm.editTab === 'master', () => act.editTab('master')),
169  ], [
170    vm.canUndo ? ui.Button({ key: 'undo', label: '↶ undo', onPress: () => act.undo(), hotkey: 'u' }) : null,
171    ui.Button({ key: 'save-mp3', label: '↓ mp3', onPress: () => act.share() }),
172    ui.Button({ key: 'edit-done', label: 'done', onPress: () => act.edit() }),
173  ], 'edit-tabs')
174}
175
176function soundCard(ui, vm, act) {
177  const x = vm.info, L = x.layer
178  const tweak = (e) => () => act.tweak({ layer: L, ...e })
179  const rows = []
180  rows.push(line(ui, 'ed-sound', 'sound', x.insts.length
181    ? x.insts.map((it) => toggle(ui, 'inst-' + L + '-' + it.name, it.name, it.name === x.inst, tweak({ kind: 'inst', value: it.value })))
182    : [dim(ui, L === 'rumble' ? 'the kick through a long dark room' : L === 'pad' ? 'a dark chord, one swell a loop' : 'one sound')]))
183  rows.push(line(ui, 'ed-pattern', 'pattern', x.presets.length
184    ? [dim(ui, 'try:'), ...x.presets.map((p) => toggle(ui, 'pat-' + L + '-' + p.name, p.name, p.on, tweak({ kind: 'pattern', name: p.name }))), x.edited ? link(ui, 'pat-reset-' + L, 'as written', tweak({ kind: 'reset-pattern' })) : null, dim(ui, '· or click the grid')]
185    : [dim(ui, L === 'rumble' ? 'follows the kick' : 'one long swell')]))
186  if (x.notes) {
187    rows.push(line(ui, 'ed-notes', 'notes', [
188      ...x.notes.map((n, i) => (n ? ui.Button({ key: 'note-' + L + '-' + i, label: n, onPress: tweak({ kind: 'note', i }) }) : dim(ui, '·', { key: 'rest-' + L + '-' + i }))),
189      ui.Button({ key: 'notes-suggest-' + L, label: '⚄ suggest', onPress: tweak({ kind: 'suggest-notes' }) }),
190      x.notesEdited ? link(ui, 'notes-reset-' + L, 'as written', tweak({ kind: 'reset-notes' })) : null,
191    ]))
192    rows.push(line(ui, 'ed-scale', '', [dim(ui, 'scale ' + x.scale.join(' ') + ' · tap a note to move it up the scale')]))
193  }
194  if (x.hasTone) rows.push(line(ui, 'ed-tone', 'tone', [
195    ...stepper(ui, 'cut-' + L, CUT_WORDS, x.tone[0] + 3, tweak({ kind: 'tone', cut: -1 }), tweak({ kind: 'tone', cut: 1 })),
196    dim(ui, '·'), dim(ui, 'grit'),
197    ...stepper(ui, 'grit-' + L, GRIT_WORDS, x.tone[1], tweak({ kind: 'tone', grit: -1 }), tweak({ kind: 'tone', grit: 1 })),
198    dim(ui, '·'),
199    ui.Button({ key: 'mute-' + L, label: vm.heard[L] ? 'mute' : 'play it', onPress: () => act.layer(L) }),
200  ]))
201  return rows
202}
203
204function masterCard(ui, vm, act) {
205  const m = vm.master
206  const tw = (e) => () => act.tweak({ kind: 'master', ...e })
207  return [
208    line(ui, 'ed-lp', 'filter', [...stepper(ui, 'lp', LP_WORDS, m[0] + 3, tw({ lp: -1 }), tw({ lp: 1 })), dim(ui, '· close it for a muffled, far away sound')]),
209    line(ui, 'ed-hp', 'low cut', [...stepper(ui, 'hp', HP_WORDS, m[1], tw({ hp: -1 }), tw({ hp: 1 })), dim(ui, '· take the low end out')]),
210    line(ui, 'ed-space', 'space', [...stepper(ui, 'space', SPACE_WORDS, m[2] + 2, tw({ space: -1 }), tw({ space: 1 })), dim(ui, '· the room around it')]),
211    line(ui, 'ed-tempo', 'tempo', [ui.Button({ key: 'slower', label: '−', onPress: () => act.bpm(-2) }), ui.Text({ bold: true, children: [vm.view.bpm + ' bpm'] }), ui.Button({ key: 'faster', label: '+', onPress: () => act.bpm(2) }), m[0] || m[1] || m[2] ? link(ui, 'master-reset', 'as written', tw({ reset: true })) : null]),
212  ]
213}
214
215function addCard(ui, vm, act) {
216  const absent = SOUND_TABS.filter((n) => !vm.heard[n])
217  return [line(ui, 'ed-add', 'add', absent.length ? absent.map((n) => ui.Button({ key: 'add-' + n, label: '+ ' + tabName(n), onPress: () => { act.layer(n); act.editTab(n) } })) : [dim(ui, 'every sound plays')])]
218}
219
220// The song: its parts in order (× takes one out; not the one that plays),
221// the parts to add (★ the recommended one), and a new rhythm.
222function songCard(ui, vm, act) {
223  const tw = (e) => () => act.tweak(e)
224  return [
225    line(ui, 'ed-parts', 'parts', vm.plan.flatMap((p) => [
226      p.now ? ui.Text({ key: 'part-' + p.k, color: 'claude', bold: true, children: [p.name] }) : ui.Text({ key: 'part-' + p.k, children: [p.name] }),
227      p.now || vm.plan.length <= 2 ? null : link(ui, 'part-x-' + p.k, '×', tw({ kind: 'plan-remove', k: p.k })),
228    ].filter(Boolean))),
229    line(ui, 'ed-add-part', 'add', [
230      ...vm.planAdds.map((a) => ui.Button({ key: 'part-add-' + a.id, label: '+ ' + a.label + (a.best ? ' ★' : ''), onPress: tw({ kind: 'plan-add', id: a.id }) })),
231      vm.planEdited ? link(ui, 'plan-reset', 'as written', tw({ kind: 'plan-reset' })) : null,
232    ]),
233    line(ui, 'ed-rhythm', 'rhythm', [ui.Button({ key: 'dice', label: '⚄ new rhythm', onPress: () => act.dice(), hotkey: 'd' }), dim(ui, '· new patterns from the same name')]),
234  ]
235}
236
237function editCard(ui, vm, act) {
238  const body = vm.editTab === 'master' ? masterCard(ui, vm, act) : vm.editTab === 'song' ? songCard(ui, vm, act) : vm.editTab === 'add' ? addCard(ui, vm, act) : vm.info ? soundCard(ui, vm, act) : []
239  return col(ui, [editTabs(ui, vm, act), ...body], { key: 'edit-card', borderStyle: 'single', borderDimColor: true, paddingX: 1 })
240}
241
242const talkLine = (ui, vm) => (vm.said || vm.you ? row(ui, [vm.you ? dim(ui, 'you: ' + vm.you, { wrap: 'truncate-end' }) : null, vm.said ? ui.Text({ wrap: 'truncate-end', children: ['› ' + vm.said] }) : null], { key: 'talk', columnGap: 2 }) : null)
243
244function deck(ui, vm, act) {
245  return [
246    topLine(ui, vm, act),
247    whereLine(ui, vm),
248    styleLine(ui, vm),
249    vm.dancerEl,
250    vm.gridEl,
251    bottomLine(ui, vm, act),
252    vm.editOpen ? editCard(ui, vm, act) : null,
253    talkLine(ui, vm),
254  ]
255}
256
257// The favorites, the tracks you heard (to find a lost one), and a way back.
258function trackRow(ui, vm, act, it, { isFav, prefix }) {
259  const here = vm.view?.id === it.code
260  return row(ui, [
261    toggle(ui, prefix + 'play-' + it.code, here ? '▶ ' + it.label : it.label, here, () => (isFav ? act.playFavorite(it.code) : act.pick(it.code))),
262    dim(ui, it.mood + ' · ' + it.bpm),
263    isFav ? link(ui, prefix + 'share-' + it.code, 'copy line', () => act.copy(it.code)) : null,
264    isFav ? link(ui, prefix + 'rm-' + it.code, 'remove', () => act.toggleFav(it.code)) : link(ui, prefix + 'fav-' + it.code, '♡ keep', () => act.toggleFav(it.code)),
265  ], { key: prefix + it.code, columnGap: 2 })
266}
267
268function favorites(ui, vm, act) {
269  const favCodes = new Set(vm.favorites.map((f) => f.code))
270  const recent = vm.recent.filter((r) => !favCodes.has(r.code))
271  return [
272    spread(ui, [ui.Text({ bold: true, children: ['♥ favorites'] }), dim(ui, vm.favorites.length + ' tracks')], [
273      vm.favorites.length ? toggle(ui, 'play-all', vm.playlist === 'favorites' ? '● playing them in turn' : '▶ play them in turn', vm.playlist === 'favorites', () => act.playFavorites()) : null,
274      link(ui, 'to-crate', 'new song', () => act.screen('crate')),
275      link(ui, 'back', '‹ back', () => act.screen('deck')),
276    ], 'fav-top'),
277    vm.favorites.length ? null : dim(ui, 'Press ♡ while a track plays to keep it here.'),
278    ...vm.favorites.map((it) => trackRow(ui, vm, act, it, { isFav: true, prefix: 'f-' })),
279    recent.length ? dim(ui, 'heard before', { key: 'heard' }) : null,
280    ...recent.map((it) => trackRow(ui, vm, act, it, { isFav: false, prefix: 'h-' })),
281  ]
282}
283
284// New song, option B (Ruslan, 2026-10-08: "B is the best but user can just
285// click on 1 2 3 etc or type themselves"): the name box first, with one
286// example of what a name gives; under it your recent chats and a few
287// classics, numbered. A click or the digit (in an empty chat box) plays one.
288const ago = (ms) => {
289  const m = Math.max(1, Math.round(ms / 60000))
290  if (m < 60) return m + ' min ago'
291  const h = Math.round(m / 60)
292  if (h < 24) return h + ' h ago'
293  const d = Math.round(h / 24)
294  return d === 1 ? 'yesterday' : d + ' d ago'
295}
296
297function numbered(ui, act, key, n, phrase, meta) {
298  return ui.Box({ key, flexDirection: 'row', columnGap: 2, children: [
299    ui.Box({ flexShrink: 1, children: [ui.Button({ key: key + '-play', label: phrase, plain: true, hotkey: String(n), onPress: () => act.pick(phrase) })] }),
300    meta ? dim(ui, meta, { key: key + '-meta', wrap: 'truncate-end' }) : null,
301  ].filter(Boolean) })
302}
303
304function crate(ui, vm, act) {
305  const { chats, classics, example, now } = vm.crate
306  let n = 0
307  const chatRows = chats.map((c) => numbered(ui, act, 'chat-' + c.phrase, ++n, c.phrase, [c.project, ago(now - c.at)].filter(Boolean).join(' · ')))
308  const classicRows = classics.map((p) => numbered(ui, act, 'classic-' + p, ++n, p, ''))
309  return [
310    spread(ui, [ui.Text({ bold: true, children: ['new song'] }), dim(ui, `· type a name, get a song: "${example.phrase}" plays ${example.mood}, ${example.bpm} bpm`, { wrap: 'truncate-end' })], [link(ui, 'back', '‹ back', () => act.screen('deck'))], 'crate-top'),
311    ui.Input({ key: 'phrase', label: 'name', placeholder: 'type any name…', value: '', submitLabel: 'play', onSubmit: (v) => act.phrase(v) }),
312    ui.Box({ key: 'lists', flexDirection: 'row', flexWrap: 'wrap', columnGap: 4, children: [
313      chats.length ? col(ui, [dim(ui, 'or press a number · your recent chats', { key: 'chats-head' }), ...chatRows], { key: 'chats', width: '58%', minWidth: 34, flexGrow: 1 }) : null,
314      col(ui, [
315        ui.Box({ key: 'classics-head', flexDirection: 'row', columnGap: 2, children: [dim(ui, chats.length ? 'classics' : 'or press a number · classics'), link(ui, 'classics-more', '⚄ others', () => act.moreClassics())] }),
316        ...classicRows,
317      ], { key: 'classics', minWidth: 26, flexGrow: 1 }),
318    ].filter(Boolean) }),
319  ]
320}
321
322function down(ui, vm, act) {
323  return [
324    spread(ui, [ui.Text({ bold: true, children: ['♪ techno'] }), dim(ui, vm.down || 'starting the player…')], [
325      ui.Button({ key: 'retry', label: 'try again', onPress: () => act.retry() }),
326      ui.Button({ key: 'close', label: 'hide', role: 'dismiss', plain: true, dimColor: true, onPress: () => act.close() }),
327    ], 'down'),
328  ]
329}
330
331// A new version on GitHub: one line with an update button (Ruslan,
332// 2026-10-08: "just give an update ready ... maybe we build a button").
333function updateLine(ui, vm, act) {
334  const u = vm.update
335  if (!u) return null
336  const say = {
337    ready: [ui.Text({ color: 'claude', bold: true, children: ['techno ' + u.latest + ' is ready'] }), ui.Button({ key: 'update', label: 'update', variant: 'primary', onPress: () => act.update() })],
338    working: [dim(ui, 'updating to ' + u.latest + '…')],
339    done: [ui.Text({ color: 'claude', bold: true, children: ['✓ updated to ' + u.latest] }), dim(ui, '· open a new chat to use it')],
340    failed: [ui.Text({ children: ['the update failed: ' + (u.why || 'unknown')] }), ui.Button({ key: 'update', label: 'try again', onPress: () => act.update() })],
341  }[u.state]
342  return row(ui, say, { key: 'update-line' })
343}
344
345export function appView(ui, vm, act) {
346  const body = !vm.view ? down(ui, vm, act) : vm.screen === 'favorites' ? favorites(ui, vm, act) : vm.screen === 'crate' ? crate(ui, vm, act) : deck(ui, vm, act)
347  return col(ui, [...body, updateLine(ui, vm, act), vm.status ? dim(ui, vm.status, { key: 'status', wrap: 'truncate-end' }) : null], { borderStyle: 'round', paddingX: 1 })
348}
349
350// The bar always stays one line (Ruslan, 2026-10-22: "on shorter windows
351// it's fucked up", the volume and × wrapped under it). It has no volume
352// ("VOL takes too much space, let's add it only when you click open"). The
353// name shrinks first; when even a short name does not fit, the bar drops
354// these, in turn.
355export const BAR_DROPS = ['share', 'context', 'prev', 'fav', 'open']
356const NAME_MIN = 12 // cells the name keeps before the bar drops anything
357
358// About how many cells the bar takes without the name, without `hide`. The
359// desktop draws in its own font with bordered buttons, so a cell of text
360// costs more there than its count (measured on a desktop screenshot, about 88
361// cells for the whole bar but the name, volume included; this gave 93).
362function barCells(vm, hide) {
363  const desk = vm.surface !== 'terminal'
364  const chars = (s) => [...String(s)].length * (desk ? 1.1 : 1)
365  const gap = desk ? 2 : 1
366  const btn = (s) => chars(s) + (desk ? 4 : 2) + gap
367  const plain = (s) => chars(s) + (desk ? 1 : 0) + gap
368  const ctx = contextLabel(vm.context)
369  const parts = {
370    note: plain('♪'),
371    prev: vm.recent.length ? btn('⏮') : 0,
372    play: btn('▶ play'),
373    skip: btn('⏭'),
374    fav: plain('♡'),
375    share: btn('share'),
376    context: ctx ? plain(ctx.text) : 0,
377    update: vm.update?.state === 'ready' ? btn('↑ update') : vm.update?.state === 'done' ? plain('✓ updated · new chat') : 0,
378    auto: btn('● auto'),
379    open: plain('open'),
380    close: plain('×'),
381  }
382  return Object.entries(parts).reduce((n, [k, w]) => n + (hide.has(k) ? 0 : w), gap)
383}
384
385// What the bar leaves out: always the volume (the open app has it), and
386// more at this width (`vm.columns`, the band's cells; nothing more when the
387// surface has not measured it).
388export function barHides(vm) {
389  const hide = new Set(['volume'])
390  if (!vm.columns) return hide
391  const room = vm.columns - 4 - NAME_MIN // the band's own border and padding
392  for (const part of BAR_DROPS) {
393    if (barCells(vm, hide) <= room) break
394    hide.add(part)
395  }
396  return hide
397}
398
399// The bar above the chat box while the app is hidden: the same transport as
400// the deck (no section word: "i don't want to see these intro drop 1 at all
401// here"), then auto, open and × on the right. No dancer: hidden is hidden
402// (Paul, 2026-10-22). Neither side wraps: the left one shrinks (the name),
403// the right one keeps its size.
404export function miniView(ui, vm, act) {
405  if (!vm.view) return spread(ui, [ui.Text({ bold: true, children: ['♪'] }), dim(ui, vm.down || 'starting the player…')], [link(ui, 'mini-close', '×', () => act.closeBar())], 'mini')
406  const hide = barHides(vm)
407  const side = (children, extra) => row(ui, children, { flexWrap: 'nowrap', ...extra })
408  return ui.Box({ key: 'mini', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', columnGap: 2, children: [
409    side([
410      ui.Text({ bold: true, children: ['♪'] }),
411      ...transport(ui, vm, act, 'mini-', hide),
412    ], { flexShrink: 1, minWidth: 0, overflow: 'hidden' }),
413    side([
414      vm.update?.state === 'ready' ? ui.Button({ key: 'mini-update', label: '↑ update', variant: 'primary', onPress: () => act.update() }) : null,
415      vm.update?.state === 'done' ? dim(ui, '✓ updated · new chat') : null,
416      hide.has('context') ? null : contextFill(ui, vm, 'mini-'),
417      toggle(ui, 'mini-auto', vm.auto ? '● auto' : '○ auto', vm.auto, () => act.auto()),
418      hide.has('open') ? null : link(ui, 'mini-open', 'open', () => act.open()),
419      link(ui, 'mini-close', '×', () => act.closeBar()),
420    ], { flexShrink: 0 }),
421  ] })
422}
423
hooks/words.js 51 lines
1// Chat words: the two or three most unusual words of a prompt become a
2// phrase that auto can pick as a track (Ruslan, 2026-10-05: "use the data
3// from chats to randomize the track"). The phrase is the track's name and
4// sits in its share code, so only plain words pass: no paths, links, emails,
5// numbers, or anything that looks like a key. Pure, so the tests call it.
6
7const COMMON = new Set(`
8a about above after again against all also always am an and any are aren around as ask at back be because been before
9being below between both but by can cannot could did didn do does doesn doing don done down during each else even
10ever every few find first for from further get gets getting give go goes going gone good got had has hasn have having
11he her here hers herself him himself his how however i if in into is isn it its itself just keep know last let like
12look looks make makes making many may maybe me might more most much must my myself need needs never new next no nor
13not now of off ok okay on once one only or other our ours out over own please put quite rather really right said same
14say see seem seems shall she should show so some something still such sure take than thank thanks that the their
15theirs them themselves then there these they thing things think this those though through thus to too try trying
16twice under until up upon us use used using very want wants was wasn way we well were weren what when where whether
17which while who whom why will with without won would wouldn yes yet you your yours yourself
18again best less lets thats whats
19add added change changes changed check code create delete doesnt dont error file files fix fixed help hey hi im
20issue line lines move remove rename run running set start stop test tests update write wrong work works working
21claude
22techno track tracks music song songs beat beats bass kick hats clap drop drops acid swing tempo bpm mood sad dark
23mysterious louder quieter darker lighter faster slower play playing pause skip previous favorite favorites
24`.split(/\s+/).filter(Boolean))
25
26// A word that can carry a track name: letters only, 3 to 14 of them.
27const plain = (w) => /^[a-z]{3,14}$/.test(w) && !COMMON.has(w)
28
29// The phrase for a prompt, or null when it has fewer than two such words.
30export function keyWords(text) {
31  const clean = String(text ?? '')
32    .replace(/<[^>]*>/g, ' ') // tags
33    .replace(/\S*[/\\@:=_`$#{}[\]<>|~]\S*/g, ' ') // paths, links, emails, code
34    .replace(/\S*\d\S*/g, ' ') // anything with a digit
35    .replace(/\b[A-Z][A-Z0-9]{3,}\b/g, ' ') // SHOUTED names and keys
36  if (/^\s*\//.test(String(text ?? ''))) return null // a slash command
37  const words = clean.toLowerCase().split(/[^a-z']+/).map((w) => w.replace(/'.*$/, ''))
38  const seen = new Set()
39  const picked = words
40    .map((w, i) => ({ w, i }))
41    .filter(({ w }) => plain(w) && !seen.has(w) && seen.add(w))
42  if (picked.length < 2) return null
43  // the longest words are the rarest; keep them in the order they were said
44  return picked
45    .sort((a, b) => b.w.length - a.w.length || a.i - b.i)
46    .slice(0, 3)
47    .sort((a, b) => a.i - b.i)
48    .map(({ w }) => w)
49    .join(' ')
50}
51
hooks/classics.js 22 lines
1// The classics: names that are good songs on their own. The new song screen
2// shows a few of them, and auto plays one after every three of your chats
3// (Ruslan, 2026-10-08: "let's generate more classics as well! maybe we
4// sometimes wire them in"). Pure data, shared by the chat and the player.
5// The first eight are the old starters; keep them, old favorites point at them.
6export const CLASSICS = [
7  'late night deploy', 'coffee at 3am', 'merge conflict', 'friday deploy', 'null pointer', 'ship it', 'warehouse 4am', 'rooftop sunrise',
8  // the city at night, 5am
9  'empty tram at 5am', 'neon on wet asphalt', 'last train home', 'streetlights going out', 'still awake at 5am', 'sodium lights', 'underpass echo', 'the city exhales',
10  // space, 3am
11  'drifting past the moon', 'orbit at 3am', 'signal from deep space', 'falling through stars', 'cold sleep', 'launch window', 'chasing the comet', 'mission control at 3am',
12  // the errors you meet on a sunday
13  'segfault on sunday', 'connection refused', 'kernel panic', 'permission denied', 'race condition', 'deadlock', 'cache miss', 'timeout exceeded', 'out of memory', 'sunday hotfix', 'rollback at midnight', 'build failed again',
14]
15
16// A small stable hash, so a pick from the classics is the same in every call.
17export function pickIndex(text, n) {
18  let h = 2166136261
19  for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 16777619)
20  return (h >>> 0) % n
21}
22
hooks/dancers.js 116 lines
1// The dancer over the grid: who dances, as frames of text. Pure: register.js
2// picks the dancer and hands its frames to dancer.client.js, which moves it
3// to the beat.
4//
5// A dancer is one word in $.store ('dancer'): a name below, `off`, or your
6// own frames separated by `;` ("(•_•);( •_•)>⌐■-■;(⌐■_■)"), one line each.
7// A frame is a list of lines, all frames of one dancer as tall as each other.
8
9// clawd (the creature of the Claude Code welcome screen) is pixel art: 18
10// pixels wide, 6 tall, `#` on, `.` off. `px` turns two by two pixels into
11// one quadrant block (▘▝▀▖▌▞▛▗▚▐▜▄▙▟█), so a frame is three lines of nine
12// cells. Eyes sit on the bottom half of a line (the notch in ▛ ▜ ▙ ▟).
13const QUAD = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█'
14export function px(art) {
15  const rows = art.trim().split('\n').map((r) => r.trim())
16  const on = (y, x) => (rows[y]?.[x] === '#' ? 1 : 0)
17  const out = []
18  for (let y = 0; y < rows.length; y += 2) {
19    let line = ''
20    for (let x = 0; x < rows[0].length; x += 2) line += QUAD[on(y, x) | (on(y, x + 1) << 1) | (on(y + 1, x) << 2) | (on(y + 1, x + 1) << 3)]
21    out.push(line)
22  }
23  return out
24}
25
26// Each: { color (a theme key or a hex), bold, frames, and for a flyer:
27// rows (how tall its region is), wrap (it flies out on the right and comes
28// back on the left, never turns), trail (a rainbow behind it: the
29// characters, one color per row, and how much shorter each row above is) }.
30// Frame 0 is the rest pose; the dance walks the others.
31export const DANCERS = {
32  // rest, both arms up, eyes up, one arm up
33  clawd: { color: 'claude', frames: [`
34    ...############...
35    ...##.######.##...
36    .################.
37    ...############...
38    ....#.#....#.#....
39    ..................`, `
40    #..############..#
41    .#.##.######.##.#.
42    ..##############..
43    ...############...
44    ...#.#......#.#...
45    ..................`, `
46    ...##.######.##...
47    ...############...
48    .################.
49    ...############...
50    .....#.#..#.#.....
51    ..................`, `
52    #..############...
53    .#.##.######.##...
54    ..###############.
55    ...############...
56    ....#.#....#.#....
57    ..................`].map(px) },
58  // after djui/nyancat (github.com/djui/nyancat): the cat, its legs in two
59  // frames, and the slanted rainbow of `*.,*'^ that shimmers behind it
60  nyan: {
61    color: 'text',
62    bold: true,
63    frames: [
64      [' ,---/V\\ ', '~|__(o.o)', ' U U U U '],
65      [' ,---/V\\ ', '~|__(o.o)', '  UU  UU '],
66    ],
67    rows: 5,
68    wrap: true,
69    trail: { chars: "`*.,*'^", colors: ['#ff4b4b', '#ffd23f', '#3ccf5a', '#3f9bff', '#b46bff'], angle: 4 },
70  },
71}
72export const DANCER_NAMES = Object.keys(DANCERS)
73export const DEFAULT_DANCER = 'clawd'
74
75// What the band hands the dancer for a word, or null for off. An unknown
76// word is your own dancer: its frames split on `;` (one frame bounces).
77export function dancerFor(word) {
78  const w = String(word ?? DEFAULT_DANCER).trim()
79  if (!w) return dancerFor(DEFAULT_DANCER)
80  if (w.toLowerCase() === 'off') return null
81  const known = DANCERS[w.toLowerCase()]
82  if (known) return { name: w.toLowerCase(), ...known }
83  const frames = w.split(';').map((f) => f.trim()).filter(Boolean).slice(0, 8).map((f) => [f.slice(0, 24)])
84  return frames.length ? { name: 'own', color: 'claude', frames } : dancerFor(DEFAULT_DANCER)
85}
86
87// The dancer after this one, for a click on it: the names in turn, then off,
88// then the first again. Your own dancer goes to the first name.
89export function nextDancer(word) {
90  const w = String(word ?? DEFAULT_DANCER).trim().toLowerCase()
91  const i = DANCER_NAMES.indexOf(w)
92  return i === -1 ? DANCER_NAMES[0] : DANCER_NAMES[(i + 1) % DANCER_NAMES.length]
93}
94
95// What the dancer does in each section: how many steps between two poses,
96// how many steps between two columns of its walk (0 stands still), whether
97// it jumps on the offbeat, and notes around it. A handover moonwalks.
98export const MOVES = {
99  intro: { pose: 8, walk: 8, jump: false, notes: false },
100  outro: { pose: 8, walk: 8, jump: false, notes: false },
101  groove: { pose: 4, walk: 4, jump: false, notes: false },
102  break: { pose: 8, walk: 0, jump: false, notes: false },
103  build: { pose: 2, walk: 2, jump: false, notes: false },
104  drop: { pose: 2, walk: 2, jump: true, notes: true },
105  handover: { pose: 4, walk: -4, jump: false, notes: false },
106}
107
108// What it says when a section starts, for two beats.
109export const SAYS = {
110  build: ['wait for it', 'here it comes', 'hold on'],
111  drop: ['DROP', 'oonts oonts', 'ship it', 'lets gooo'],
112  break: ['…breathe', 'ahh', 'mm'],
113  outro: ['gg', 'one more?'],
114  handover: ['next!', 'mixing…'],
115}
116
hooks/dancer.client.js 125 lines
1// The dancer: a little character that walks across the deck and dances to
2// the beat, on the surface's own frame clock (like the grid), so it moves
3// without a redraw of the whole band. Four rows (or the dancer's `rows`):
4// the top one for its jumps, notes and what it says, the dancer at the bottom.
5//
6// props: { frames, color, bold, rows, wrap, trail, move, says, section,
7// playing, step, stepMs, stamp }. Everything up to trail comes from
8// dancers.js (dancerFor), move is MOVES[section], says the lines for the
9// section it plays. A click on it posts { dancer: 'next' }: the next dancer.
10//
11// It walks one column every |move.walk| steps (back the other way when it is
12// negative, a moonwalk), bounces off the edges, takes the next pose every
13// move.pose steps, and with move.jump hops on the offbeat. Stopped, it sleeps.
14// A dancer with `wrap` flies on to the right instead, out of the right edge
15// and back in on the left, its `trail` (a rainbow) behind it from the left edge.
16const len = (s) => [...s].length
17
18export default function Dancer(props, surface) {
19  const { Box, Text } = surface.elements
20  const prev = surface.state
21  let st = prev ?? { t: 0, step: props.step, stamp: props.stamp, x: null, dir: 1, section: props.section, bubble: null, ref: { props }, stop: null, stepMs: 0 }
22  if (!prev) surface.onPointer((ev) => { if (ev.type === 'down') surface.post({ dancer: 'next' }) })
23  st.ref.props = props
24
25  let changed = !prev
26  if (props.stamp !== st.stamp) { st = { ...st, step: props.step, stamp: props.stamp }; changed = true }
27  // a new section: it says so for two beats
28  if (props.section !== st.section) {
29    const says = props.playing && props.says?.length ? props.says[st.t % props.says.length] : null
30    st = { ...st, section: props.section, bubble: says ? { text: says, until: st.t + 8 } : null }
31    changed = true
32  }
33  const wantMs = props.playing ? props.stepMs : 0
34  if (wantMs !== st.stepMs) {
35    if (st.stop) st.stop()
36    const tick = () => {
37      const s = surface.state
38      const p = s.ref.props
39      const t = s.t + 1
40      const W = surface.columns || 60
41      const room = p.wrap ? W - 1 : Math.max(0, W - width(p.frames))
42      let x = Math.min(startX(s.x, p, W), room), dir = s.dir
43      const walk = p.move?.walk ?? 0
44      if (walk && t % Math.abs(walk) === 0) {
45        if (p.wrap) x = x >= room ? 0 : x + 1
46        else {
47          x += dir * Math.sign(walk)
48          if (x < 0 || x > room) { dir = -dir; x = Math.max(0, Math.min(room, x + 2 * dir * Math.sign(walk))) }
49        }
50      }
51      surface.setState({ ...s, t, step: (s.step + 1) % 128, x, dir, bubble: s.bubble && t < s.bubble.until ? s.bubble : null })
52    }
53    st = { ...st, stepMs: wantMs, stop: wantMs ? surface.every(wantMs, tick) : null }
54    changed = true
55  }
56  if (changed) surface.setState(st)
57
58  const W = surface.columns || 60
59  const frames = props.frames?.length ? props.frames : [['?']]
60  const sw = width(frames)
61  const move = props.move ?? {}
62  const playing = !!props.playing
63  // a flyer may slip out on the right while it flies; standing, it is whole
64  const x = Math.max(0, Math.min(startX(st.x, props, W), props.wrap && playing ? W - 1 : W - sw))
65  const frame = playing ? frames[Math.floor(st.t / Math.max(1, move.pose ?? 4)) % frames.length] : frames[0]
66  const ROWS = Math.max(4, props.rows ?? 4, frame.length + 1)
67  const base = ROWS - frame.length
68  const lift = playing && move.jump && st.step % 4 === 2 ? base - 1 : base
69  const rows = Array.from({ length: ROWS }, () => [])
70  frame.forEach((line, i) => rows[i + lift]?.push({ x, text: line, color: props.color, bold: !!props.bold }))
71  // the rainbow: one color a row, each row above `angle` shorter, its
72  // characters moving on every step, so it shimmers; it hops with the dancer
73  const trail = playing ? props.trail : null
74  if (trail) {
75    const n = trail.chars.length
76    for (let r = base - lift; r < ROWS; r++) {
77      const end = x - (trail.angle ?? 0) * (ROWS - 1 - r)
78      if (end > 0) rows[r - (base - lift)].push({ x: 0, text: Array.from({ length: end }, (_, c) => trail.chars[(c + n - (r % n) + st.t) % n]).join(''), color: trail.colors[r % trail.colors.length], bold: true })
79    }
80  }
81  // notes trail behind it in a drop, rising
82  if (playing && move.notes && !trail) {
83    for (let i = 0; i < 2; i++) {
84      const nx = x + (st.dir > 0 ? -3 - i * 3 : sw + 2 + i * 3)
85      const ny = 3 - ((Math.floor(st.t / 2) + i * 2) % 4)
86      if (ny !== 0 || lift === base) rows[base - 1 + ny]?.push({ x: nx, text: i ? '♫' : '♪', dim: true })
87    }
88  }
89  const bubble = !playing ? 'z Z z' : st.bubble?.text
90  if (bubble) {
91    const right = x + sw + 1
92    rows[0].push({ x: right + len(bubble) <= W ? right : Math.max(0, x - len(bubble) - 1), text: bubble, dim: !playing, bold: playing })
93  }
94
95  return Box({
96    flexDirection: 'column',
97    children: rows.map((items, r) => Box({ key: 'd' + r, flexDirection: 'row', height: 1, children: line(Text, items, W, r) })),
98  })
99}
100
101// where it is; before its first step a flyer starts a third of the way in,
102// so its rainbow shows at once
103const startX = (x, props, W) => x ?? (props.wrap ? Math.floor(W / 3) : 0)
104
105function width(frames) {
106  let w = 1
107  for (const f of frames ?? []) for (const l of f) w = Math.max(w, len(l))
108  return w
109}
110
111// One row: the items in order, the gaps as spaces, nothing past the edge.
112function line(Text, items, W, r) {
113  const out = []
114  let at = 0
115  for (const it of items.filter((i) => i.x >= 0).sort((a, b) => a.x - b.x)) {
116    if (it.x < at) continue
117    const text = [...it.text].slice(0, Math.max(0, W - it.x)).join('')
118    if (!text) continue
119    if (it.x > at) out.push(Text({ key: 'g' + r + '-' + at, children: [' '.repeat(it.x - at)] }))
120    out.push(Text({ key: 'i' + r + '-' + it.x, ...(it.color ? { color: it.color } : {}), ...(it.dim ? { dimColor: true } : {}), ...(it.bold ? { bold: true } : {}), children: [text] }))
121    at = it.x + len(text)
122  }
123  return out.length ? out : [Text({ key: 'e' + r, children: [' '] })]
124}
125
hooks/grid.client.js 116 lines
1// The step sequencer, drawn on the surface's own frame clock so the playhead
2// moves without a redraw of the whole pane. Every step is a Box of the same
3// width, so the columns line up in any font.
4//
5// A click on a row name posts { toggle: layer } (mute). A click on a cell
6// posts { step: i, layer } (add or remove that hit in every bar).
7//
8// props: { rows: [[name, pattern, color, isOn, isMuted, isNext]], step, stepMs, playing, stamp }
9// stamp is when the current bar started; a new stamp resyncs the playhead.
10// A layer the build has not brought in (or took out) is dim; one you muted is struck through.
11// The next sound of the build is a dashed row: where it will play, not yet clickable.
12const LABEL = 8
13// what a row is called where its layer name says too little (the edit card
14// calls the acid layer "melody" too)
15const SHOW = { acid: 'melody' }
16const TOP = 1 // the beat ruler (no "bar n/8" line: Ruslan, 2026-10-04)
17const cellX = (i) => LABEL + i * 3 + Math.floor(i / 4)
18
19// Theme keys, not raw colors, so the grid reads in the light and the dark
20// theme alike: an empty step is the theme's subtle grey, the playhead its text color.
21const REST = 'subtle'
22const REST_BEAT = 'subtle'
23const MUTED = 'inactive'
24const HEAD_REST = 'suggestion'
25const HEAD_HIT = 'text'
26const HOVER = 'inactive'
27
28function cellAt(x) {
29  for (let i = 0; i < 16; i++) if (x >= cellX(i) && x <= cellX(i) + 2) return i
30  return -1
31}
32
33export default function Grid(props, surface) {
34  const { Box, Text } = surface.elements
35  const prev = surface.state
36  let st = prev ?? { step: props.step, stamp: props.stamp, ref: { props }, stop: null, stepMs: 0, hover: null }
37  if (!prev) {
38    surface.onPointer((ev) => {
39      const cur = surface.state ?? st
40      const rows = cur.ref.props.rows
41      const r = ev.y - TOP
42      const row = ev.type === 'leave' ? null : rows[r]
43      const i = row ? (ev.x < LABEL ? -1 : cellAt(ev.x)) : null
44      if (ev.type === 'down' && row && !row[5]) {
45        if (i === -1) surface.post({ toggle: row[0] })
46        else if (i !== null && i >= 0) surface.post({ step: i, layer: row[0] })
47      }
48      const hover = row && i !== null ? { r, i } : null
49      const same = (hover && cur.hover && hover.r === cur.hover.r && hover.i === cur.hover.i) || (!hover && !cur.hover)
50      if (!same) surface.setState({ ...cur, hover })
51    })
52  }
53  st.ref.props = props
54
55  // resync to the pane's clock whenever the pane hands a new stamp
56  let changed = !prev
57  if (props.stamp !== st.stamp) {
58    st = { ...st, step: props.step, stamp: props.stamp }
59    changed = true
60  }
61  const wantMs = props.playing ? props.stepMs : 0
62  if (wantMs !== st.stepMs) {
63    if (st.stop) st.stop()
64    const tick = () => {
65      const s = surface.state
66      surface.setState({ ...s, step: (s.step + 1) % 128 })
67    }
68    st = { ...st, stepMs: wantMs, stop: wantMs ? surface.every(wantMs, tick) : null }
69    changed = true
70  }
71  if (changed) surface.setState(st)
72
73  const col = props.playing ? st.step % 16 : -1
74  const hover = st.hover
75  const gap = (i) => (i % 4 === 3 ? 2 : 1)
76
77  const ruler = Box({
78    key: 'gr',
79    flexDirection: 'row',
80    children: [
81      Box({ key: 'rl', width: LABEL, children: [Text({ children: [' '] })] }),
82      ...Array.from({ length: 16 }, (_, i) =>
83        Box({ key: 'r' + i, width: 2, marginRight: gap(i), children: [Text({ dimColor: i !== col, bold: i === col, children: [i % 4 === 0 ? String(i / 4 + 1) : '·'] })] }),
84      ),
85    ],
86  })
87  const rows = props.rows.map(([name, pattern, color, isOn, isMuted, isNext], r) => {
88    if (isNext) {
89      const cells = [...pattern].map((c, i) => Box({ key: name + i, width: 2, height: 1, marginRight: gap(i), children: [Text({ dimColor: true, children: [c !== '.' ? '▪▪' : '╌╌'] })] }))
90      return Box({ key: 'g-' + name, flexDirection: 'row', children: [Box({ key: 'l-' + name, width: LABEL, children: [Text({ dimColor: true, italic: true, children: [SHOW[name] ?? name] })] }), ...cells] })
91    }
92    const label = Text({
93      bold: isOn,
94      dimColor: !isOn,
95      strikethrough: !!isMuted,
96      underline: hover?.r === r && hover.i === -1,
97      children: [SHOW[name] ?? name],
98    })
99    const cells = [...pattern].map((c, i) => {
100      const hit = c !== '.'
101      let bg
102      if (i === col) bg = hit && isOn ? HEAD_HIT : HEAD_REST
103      else if (hover?.r === r && hover.i === i) bg = HOVER
104      else if (!hit) bg = i % 4 === 0 ? REST_BEAT : REST
105      else bg = isOn ? color[c === 'X' ? 0 : 1] : MUTED
106      return Box({ key: name + i, width: 2, height: 1, marginRight: gap(i), backgroundColor: bg, children: [Text({ children: [' '] })] })
107    })
108    return Box({
109      key: 'g-' + name,
110      flexDirection: 'row',
111      children: [Box({ key: 'l-' + name, width: LABEL, children: [label] }), ...cells],
112    })
113  })
114  return Box({ flexDirection: 'column', children: [ruler, ...rows] })
115}
116
hooks/conductor.js 182 lines
1// The conductor: what each loop of a long set plays, and the mixer that cuts
2// the rendered loops into bars for a gapless stream. Plain JavaScript like
3// the engine, so the background player (player/techno.mjs) and the scripts
4// share it.
5//
6// A set is the current track at a part of PLAN, plus how many loops it has
7// played there. With auto on, each part plays its `loops`, then the next one;
8// after the outro the next track comes in through a HANDOVERS shape and goes
9// on from its build. With auto, the transitions come from `transitionsOf`
10// (seeded by the track): a build-up on the last loop of a part with `rise`,
11// a fall on the last loop of a drop, a swell into a new sound, a build-up
12// before the low end swaps in the handover. The first loop of a drop (and of
13// the new track after a swap) gets a crash, with auto a boom too.
14import { PLAN, HANDOVERS, HANDOVER_LOOPS, atPart, onlyLayers, cleanTrack, encodeCode, transitionsOf, planOf, noteName } from './engine.js'
15
16// The next song in a set is never in the key of the one before (Ruslan,
17// 2026-10-12: "don't want a whole set in 1 key tho, change keys"). A song
18// keeps one key from start to end; when the next one would land on the same
19// key, it moves to another of the low keys (e, f, f#, g, a, where the sub
20// sits at 41..55 Hz), picked by its name.
21const NOTES = ['c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#', 'a', 'a#', 'b']
22const LOW_KEYS = ['e', 'f', 'f#', 'g', 'a']
23export function freshKey(next, prev) {
24  const t = cleanTrack(next)
25  const here = noteName(cleanTrack(prev ?? {}))
26  if (!prev || noteName(t) !== here) return t
27  let h = 0
28  for (const c of t.phrase) h = (h * 31 + c.charCodeAt(0)) >>> 0
29  const others = LOW_KEYS.filter((k) => k !== here)
30  const to = others[h % others.length]
31  return { ...t, transpose: (t.transpose + NOTES.indexOf(to) - NOTES.indexOf(here) + 12) % 12 }
32}
33
34// A fresh set on a track (from its first part unless it has one). `at` is
35// the position in the track's plan (a part can come twice in it).
36export function newSet(track) {
37  const t = cleanTrack(track)
38  const plan = planOf(t)
39  const k = t.part === null ? 0 : Math.max(0, plan.indexOf(t.part))
40  return { track: atPart(t, plan[k]), loop: 0, handover: null, at: k }
41}
42
43// The position in the plan, for a set saved before 0.9 (no `at`).
44export const posOf = (set) => set.at ?? Math.max(0, planOf(set.track).indexOf(set.track.part))
45
46// What the next loop plays: the arguments of renderLoop. Only auto adds the
47// transitions, since only auto knows what comes next.
48export function loopSpec(set, { auto }) {
49  const none = { rise: false, impact: false, build: null, fall: null, swell: false }
50  if (set.handover) {
51    const shape = HANDOVERS[set.handover.shape]
52    const h = shape.steps[set.handover.step]
53    const swap = auto && set.handover.step === shape.steps.length - 1 && set.handover.loop >= HANDOVER_LOOPS - 1
54    return { ...none, track: onlyLayers(set.handover.from, h.from), with: h.to.length ? onlyLayers(atPart(set.track, shape.to), h.to) : null, ...(swap ? { rise: true, build: transitionsOf(set.handover.from).swap } : {}) }
55  }
56  const k = posOf(set), p = PLAN[set.track.part]
57  const last = set.loop >= p.loops - 1
58  const fx = auto ? transitionsOf(set.track) : null
59  const rise = !!fx && last && fx.build[k] !== undefined
60  const drop = p.section === 'drop' && set.loop === 0
61  const landed = !!set.swapped && set.loop === 0
62  return {
63    track: set.track,
64    with: null,
65    rise,
66    impact: drop || landed,
67    build: rise ? fx.build[k] : fx && drop ? fx.build[k - 1] ?? null : fx && landed ? set.swapped : null,
68    fall: fx && last ? fx.fall[k] ?? null : null,
69    swell: !!(fx && last && fx.swell[k]),
70  }
71}
72
73// The key of a spec, so the player renders a loop once and reuses it.
74export const specKey = (spec) => [encodeCode(spec.track), spec.with ? encodeCode(spec.with) : '', spec.rise ? 'r' : '', spec.impact ? 'i' : '', spec.build ?? '', spec.fall ?? '', spec.swell ? 's' : ''].join('|')
75
76// Moves on by one part, or one handover step. `nextTrack()` gives the track
77// that comes in after the outro. Returns the set (mutated).
78export function stepOn(set, nextTrack) {
79  set.loop = 0
80  set.swapped = null
81  if (set.handover) {
82    set.handover.step++
83    set.handover.loop = 0
84    const shape = HANDOVERS[set.handover.shape]
85    if (set.handover.step >= shape.steps.length) {
86      // the new song lands with the crash and the boom of the swap build-up
87      set.swapped = transitionsOf(set.handover.from).swap
88      set.handover = null
89      const plan = planOf(set.track)
90      set.at = Math.max(0, plan.indexOf(shape.to))
91      set.track = atPart(set.track, plan[set.at])
92    }
93    return set
94  }
95  const plan = planOf(set.track), k = posOf(set)
96  if (k < plan.length - 1) {
97    set.at = k + 1
98    set.track = atPart(set.track, plan[k + 1])
99    return set
100  }
101  const next = freshKey(nextTrack(), set.track)
102  const shape = transitionsOf(set.track).land
103  set.handover = { from: set.track, step: 0, loop: 0, shape }
104  set.track = { ...atPart(next, HANDOVERS[shape].to), bpm: set.track.bpm }
105  // the new song mixes in at the old tempo, then glides to its own
106  set.bpmTo = next.bpm !== set.track.bpm ? next.bpm : null
107  return set
108}
109
110// After a loop played to its end: with auto, count it and move on when the
111// part (or the handover step) has had its loops.
112export function afterLoop(set, { auto, nextTrack }) {
113  glide(set)
114  if (!auto) return set
115  if (set.handover) {
116    set.handover.loop++
117    if (set.handover.loop >= HANDOVER_LOOPS) stepOn(set, nextTrack)
118    return set
119  }
120  set.loop++
121  if (set.loop >= PLAN[set.track.part].loops) stepOn(set, nextTrack)
122  return set
123}
124
125// After the handover, the tempo moves GLIDE bpm a loop toward the new song's
126// own (0.10: a hard song at 148 and a minimal one at 125 both keep their
127// tempo; 2 bpm at a loop's edge is not heard as a jump).
128export const GLIDE = 2
129function glide(set) {
130  if (!set.bpmTo || set.handover) return
131  const d = set.bpmTo - set.track.bpm
132  set.track = { ...set.track, bpm: set.track.bpm + Math.sign(d) * Math.min(GLIDE, Math.abs(d)) }
133  if (set.track.bpm === set.bpmTo) set.bpmTo = null
134}
135
136// The track as it is meant to be: at its own tempo while the tempo still glides.
137export const homeOf = (set) => (set.bpmTo ? { ...set.track, bpm: set.bpmTo } : set.track)
138
139// How many loops are left in this part (or handover step), this one included.
140export function loopsLeft(set) {
141  if (set.handover) return HANDOVER_LOOPS - set.handover.loop
142  return Math.max(1, PLAN[set.track.part].loops - set.loop)
143}
144
145// A soft knee over 0.9, so a tail added on a full bar never clips.
146const knee = (v) => (v > 0.9 ? 0.9 + 0.09 * Math.tanh((v - 0.9) / 0.09) : v < -0.9 ? -0.9 - 0.09 * Math.tanh((-v - 0.9) / 0.09) : v)
147
148// The mixer cuts a rendered loop into its 8 bars and adds the tail of the
149// loop before (reverb, delay) onto the start of the next one. A bar is one
150// interleaved stereo Float32Array.
151export function mixer() {
152  let carryL = new Float32Array(0), carryR = new Float32Array(0)
153  return {
154    // bar `k` (0..7) of the render `r`; the last bar hands the render's tail on
155    bar(r, k) {
156      const from = Math.round((k * r.loop) / 8), to = Math.round(((k + 1) * r.loop) / 8)
157      const n = to - from
158      const out = new Float32Array(n * 2)
159      for (let i = 0; i < n; i++) {
160        out[i * 2] = knee(r.left[from + i] + (i < carryL.length ? carryL[i] : 0))
161        out[i * 2 + 1] = knee(r.right[from + i] + (i < carryR.length ? carryR[i] : 0))
162      }
163      carryL = carryL.length > n ? carryL.subarray(n) : new Float32Array(0)
164      carryR = carryR.length > n ? carryR.subarray(n) : new Float32Array(0)
165      if (k === 7) {
166        const tl = r.left.subarray(r.loop), tr = r.right.subarray(r.loop)
167        const len = Math.max(tl.length, carryL.length)
168        const nl = new Float32Array(len), nr = new Float32Array(len)
169        nl.set(carryL); nr.set(carryR)
170        for (let i = 0; i < tl.length; i++) { nl[i] += tl[i]; nr[i] += tr[i] }
171        carryL = nl; carryR = nr
172      }
173      return out
174    },
175  }
176}
177
178// What the deck calls the part that plays: its section (intro, groove,
179// build, break, outro), a drop with its number, "mixing in" in a handover
180// (Ruslan, 2026-10-05, option A: "kick - it's not clear what it means").
181export const sectionLabel = (v) => (!v ? '' : v.section === 'handover' ? 'mixing in' : v.section === 'drop' ? v.name : v.section)
182