index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Harmonic Minimal | Chord Discoverer</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.8.49/Tone.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&family=JetBrains+Mono&display=swap');
body {
background-color: #050505;
color: #ededed;
font-family: 'Inter', sans-serif;
overflow-y: auto;
overflow-x: hidden;
}
.glass {
background: rgba(255, 255, 255, 0.02);
backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.05);
}
/* Radial Background Grid */
#grid-overlay {
position: absolute;
inset: 0;
pointer-events: none;
opacity: 0.15;
background-image:
radial-gradient(circle at center, transparent 0, transparent 1px, rgba(255,255,255,0.1) 1px),
radial-gradient(circle at center, transparent 0, transparent 100px, rgba(255,255,255,0.05) 101px, transparent 102px),
radial-gradient(circle at center, transparent 0, transparent 200px, rgba(255,255,255,0.05) 201px, transparent 202px),
radial-gradient(circle at center, transparent 0, transparent 300px, rgba(255,255,255,0.05) 301px, transparent 302px),
radial-gradient(circle at center, transparent 0, transparent 400px, rgba(255,255,255,0.05) 401px, transparent 402px);
}
.spoke {
position: absolute;
top: 50%;
left: 50%;
width: 800px;
height: 1px;
background: linear-gradient(90deg, rgba(255,255,255,0.06) 0%, transparent 70%);
transform-origin: left center;
}
.piano-key {
height: 140px;
width: 52px;
border: 1px solid #222;
cursor: pointer;
position: relative;
transition: all 0.12s ease;
border-radius: 0 0 5px 5px;
}
.piano-key.white { background: #111; z-index: 1; }
.piano-key.black {
background: #000;
height: 86px;
width: 32px;
margin-left: -16px;
margin-right: -16px;
z-index: 2;
border-radius: 0 0 4px 4px;
}
.piano-key.selected {
background: #ffffff !important;
box-shadow: 0 0 15px rgba(255, 255, 255, 0.3);
border-color: #fff;
}
.piano-key.black.selected { background: #e2e2e2 !important; }
/* Queued chord tones: additive grayscale density (tone in ALL queued chords = full white) */
.piano-key.queued::after {
content: '';
position: absolute;
inset: 0;
border-radius: inherit;
background: #fff;
opacity: var(--q, 0);
pointer-events: none;
transition: opacity 0.25s ease;
}
.piano-key.queued .key-label {
color: rgba(0, 0, 0, calc(var(--q, 0) * 0.55));
}
@keyframes keyPulse {
0%, 100% { box-shadow: 0 0 8px rgba(255,255,255,0.25); }
50% { box-shadow: 0 0 24px rgba(255,255,255,0.6); }
}
.piano-key.playing {
background: #e8e8e8 !important;
border-color: #fff;
animation: keyPulse 1.1s ease-in-out infinite;
}
.piano-key.black.playing { background: #c9c9c9 !important; }
.key-label {
position: absolute;
z-index: 2;
bottom: 6px;
left: 0;
right: 0;
text-align: center;
font-family: 'JetBrains Mono', monospace;
font-size: 9px;
letter-spacing: 0.1em;
color: rgba(255,255,255,0.25);
pointer-events: none;
}
.piano-key.selected .key-label { color: #000; }
.piano-key.playing .key-label { color: #555; }
#harmonic-map {
width: 100%;
height: 650px;
position: relative;
user-select: none;
overflow: hidden;
}
@keyframes nodeIn { from { opacity: 0; } }
.chord-node {
position: absolute;
transform: translate(-50%, -50%);
transition: all 0.7s cubic-bezier(0.22, 1, 0.36, 1);
cursor: pointer;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
border-radius: 50%;
border: 1px solid rgba(255,255,255,0.08);
background: rgba(10,10,10,0.92);
box-shadow: 0 10px 30px rgba(0,0,0,0.7);
animation: nodeIn 0.45s ease-out;
}
.chord-node:hover {
filter: brightness(1.35);
transform: translate(-50%, -50%) scale(1.05);
z-index: 50;
}
.q-dot {
width: 6px;
height: 6px;
border-radius: 50%;
margin-bottom: 3px;
}
.chord-node.queued {
outline: 1px dashed rgba(255,255,255,0.45);
outline-offset: 3px;
}
.chord-node.center-node {
background: #fff;
color: #000;
border-color: #fff;
box-shadow: 0 0 50px rgba(255,255,255,0.1);
z-index: 100;
}
.chord-node.center-node span { color: #000 !important; }
select {
background: #111;
border: 1px solid #333;
color: white;
padding: 0.25rem 0.5rem;
border-radius: 4px;
font-size: 10px;
}
input[type=range] {
accent-color: #ffffff;
background: rgba(255,255,255,0.1);
height: 2px;
appearance: none;
}
.led { width: 5px; height: 5px; border-radius: 50%; background: #222; }
.led.active { background: #fff; box-shadow: 0 0 8px #fff; }
.mode-btn {
border: 1px solid rgba(255,255,255,0.08);
background: rgba(255,255,255,0.02);
color: rgba(255,255,255,0.35);
padding: 8px 10px;
border-radius: 10px;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.2em;
text-transform: uppercase;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
transition: all 0.15s ease;
cursor: pointer;
}
.mode-btn:hover { border-color: rgba(255,255,255,0.3); color: rgba(255,255,255,0.7); }
.mode-btn.active {
background: #fff;
color: #000;
border-color: #fff;
box-shadow: 0 0 20px rgba(255,255,255,0.12);
}
.mode-btn.active .led { background: #000; box-shadow: none; }
.queued-item {
pointer-events: auto;
display: flex;
align-items: center;
gap: 6px;
background: rgba(10,10,10,0.85);
border: 1px solid rgba(255,255,255,0.10);
padding: 3px 8px;
border-radius: 6px;
font-family: 'JetBrains Mono', monospace;
font-size: 10px;
color: rgba(255,255,255,0.75);
cursor: pointer;
backdrop-filter: blur(8px);
}
.queued-item .rm { color: rgba(255,255,255,0.3); }
.queued-item:hover { border-color: rgba(255,255,255,0.35); }
.queued-item:hover .rm { color: #fff; }
/* Tone lamps directly above the keys — brightness follows queued-chord density (--q) */
.key-lamp {
position: absolute;
top: -18px;
left: 50%;
transform: translateX(-50%);
width: 7px;
height: 7px;
border-radius: 50%;
background: rgba(255, 255, 255, calc(var(--q, 0) * 0.9));
border: 1px solid rgba(255, 255, 255, calc(0.08 + var(--q, 0) * 0.3));
box-shadow: 0 0 calc(var(--q, 0) * 9px) rgba(255, 255, 255, calc(var(--q, 0) * 0.65));
transition: background 0.2s ease, box-shadow 0.2s ease;
pointer-events: none;
z-index: 2;
}
.piano-key.playing .key-lamp,
.piano-key.selected .key-lamp {
background: #fff;
box-shadow: 0 0 10px rgba(255,255,255,0.8);
}
@keyframes lampFlash {
0% { transform: translateX(-50%) scale(1.7); }
100% { transform: translateX(-50%) scale(1); }
}
.key-lamp.flash {
background: #fff !important;
box-shadow: 0 0 16px rgba(255,255,255,0.95), 0 0 4px #fff !important;
animation: lampFlash 0.3s ease-out;
}
</style>
</head>
<body class="min-h-screen flex items-center justify-center p-4">
<div class="max-w-7xl w-full space-y-4">
<!-- Header -->
<div class="flex justify-between items-center border-b border-white/5 pb-3">
<div class="flex items-baseline gap-3">
<h1 class="text-sm font-light tracking-[0.3em]">HARMONIC <span class="font-bold">MINIMAL</span></h1>
<div id="audio-status" class="flex items-center gap-2 text-[8px] text-white/20 tracking-widest uppercase">
<div class="led" id="status-led"></div>
<span id="status-text">Standby</span>
</div>
</div>
<div class="flex items-center gap-6">
<div class="flex items-center gap-2">
<span class="text-[8px] text-white/20 uppercase font-bold">Volume</span>
<input type="range" id="master-vol" min="-40" max="0" value="-12" class="w-20">
</div>
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
<!-- Map (Radial Grid) + Keyboard -->
<div class="lg:col-span-8 space-y-4">
<div class="glass rounded-3xl overflow-hidden relative">
<div id="harmonic-map">
<div id="grid-overlay"></div>
<div id="spoke-container"></div>
<div id="map-inner" class="absolute inset-0"></div>
<div class="absolute top-6 left-6 flex flex-col pointer-events-none">
<span class="text-[10px] text-white/40 uppercase tracking-[0.2em] font-bold">Harmonic Neighborhood</span>
<span id="map-hint" class="text-[7px] text-white/10 uppercase mt-1">Ctrl+Click = queue chord · Right-click = set as core</span>
</div>
<div id="quality-legend" class="absolute top-6 right-6 flex flex-col items-end gap-1.5 pointer-events-none"></div>
<div id="queued-list" class="absolute top-[70px] left-6 flex flex-col gap-1 items-start pointer-events-none"></div>
</div>
</div>
<div class="glass rounded-3xl p-5">
<div class="flex justify-between items-center mb-7">
<label class="text-[8px] text-white/40 uppercase font-bold tracking-widest">Keyboard</label>
<span class="text-[8px] text-white/15 uppercase tracking-widest">Lamps above keys = active tones</span>
</div>
<div id="piano-container" class="flex justify-center select-none"></div>
<div class="mt-4 border-t border-white/5 pt-3">
<span class="text-[8px] text-white/15 uppercase tracking-widest">White fill = queued-tone share · Bright = selected · Flash = triggered</span>
</div>
</div>
</div>
<!-- Controls & Piano -->
<div class="lg:col-span-4 space-y-4">
<div class="glass p-6 rounded-3xl space-y-6">
<div class="flex justify-between items-start">
<div class="space-y-1">
<label class="text-[8px] text-white/40 uppercase font-bold tracking-widest">Active Analysis</label>
<div class="flex items-center gap-3">
<h2 id="active-chord-name" class="text-4xl font-light tracking-tighter text-white uppercase">SELECT</h2>
<button id="force-detect" title="Force Re-scan" class="p-1.5 hover:bg-white/10 rounded border border-white/5 opacity-40 hover:opacity-100 transition-all">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/><path d="M9 12l2 2 4-4"/></svg>
</button>
</div>
<div id="intervals-display" class="text-[10px] font-mono text-white/30 tracking-widest">---</div>
</div>
<button id="clear-notes" class="text-[9px] text-white/40 hover:text-white underline underline-offset-4 uppercase">Clear</button>
</div>
<div class="grid grid-cols-2 gap-3">
<button id="toggle-hold" class="mode-btn"><span class="led"></span>Hold</button>
<button id="toggle-arp" class="mode-btn"><span class="led"></span>Arpeggio</button>
</div>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-1">
<label class="text-[8px] text-white/20 uppercase tracking-tighter">Instrument</label>
<select id="sound-select" class="w-full">
<option value="silk_air">Silk Air</option>
<option value="silk_deep">Silk Deep</option>
<option value="soft_pad">Soft Pad</option>
<option value="velvet_keys">Velvet Keys</option>
<option value="air_strings">Air Strings</option>
<option value="warm_aura">Warm Aura</option>
<option value="glass_bells">Glass Bells</option>
<option value="wind_chimes">Wind Chimes</option>
<option value="music_box">Music Box</option>
</select>
</div>
<div class="space-y-1">
<label class="text-[8px] text-white/20 uppercase tracking-tighter">Register</label>
<div class="flex items-center justify-between bg-black/40 rounded px-2 py-1.5 border border-white/5">
<button id="octave-down" class="px-2 opacity-50 hover:opacity-100 font-bold">-</button>
<span id="octave-val" class="text-xs font-mono">3</span>
<button id="octave-up" class="px-2 opacity-50 hover:opacity-100 font-bold">+</button>
</div>
</div>
</div>
</div>
<!-- Active Tones panel removed — tones now show as lamps above the keys -->
</div>
</div>
</div>
<script>
const NOTES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
const FIFTHS = ["C", "G", "D", "A", "E", "B", "F#", "C#", "G#", "D#", "A#", "F"];
const KEY_MAP = { 'a': 'C', 'w': 'C#', 's': 'D', 'e': 'D#', 'd': 'E', 'f': 'F', 't': 'F#', 'g': 'G', 'y': 'G#', 'h': 'A', 'u': 'A#', 'j': 'B' };
const CHORD_TEMPLATES = [
{ intervals: [0, 4, 7], suffix: "" },
{ intervals: [0, 3, 7], suffix: "m" },
{ intervals: [0, 3, 6], suffix: "dim" },
{ intervals: [0, 4, 7, 11], suffix: "maj7" },
{ intervals: [0, 4, 7, 10], suffix: "7" },
{ intervals: [0, 3, 7, 10], suffix: "m7" },
{ intervals: [0, 2, 7], suffix: "sus2" },
{ intervals: [0, 5, 7], suffix: "sus4" },
{ intervals: [0, 4, 8], suffix: "aug" },
{ intervals: [0, 4, 7, 11, 14], suffix: "maj9" },
{ intervals: [0, 3, 7, 10, 14], suffix: "m9" },
{ intervals: [0, 3, 6, 10], suffix: "m7b5" }
];
// Chord quality colors (#3): quick visual read of major/minor/character
const QUALITY_COLORS = {
major: "#ffb86b", minor: "#7fb2ff", dom7: "#ff7a5c",
dim: "#c792ea", aug: "#64e3c1", sus: "#9aa4ad", other: "#d4d4d4"
};
const QUALITY_BY_SUFFIX = {
"": "major", "maj7": "major", "maj9": "major",
"m": "minor", "m7": "minor", "m9": "minor",
"7": "dom7", "dim": "dim", "m7b5": "dim",
"aug": "aug", "sus2": "sus", "sus4": "sus"
};
function hexToRgba(hex, alpha) {
const n = parseInt(hex.slice(1), 16);
return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
}
let currentOctave = 3;
let isStarted = false;
let selectedNotes = new Set();
let currentSynth;
let holdMode = false;
let arpMode = false;
let heldState = null; // { name, notes, timers[], momentary }
const queuedChords = new Map(); // name -> chord (Ctrl multi-select)
const ARP_INTERVAL = 150; // ms between arpeggio steps
const ARP_RELEASE = 0.5; // short release while arpeggio runs (avoids voice pile-up / crackle)
const SOUND_RELEASE = {
silk_air: 1.4, silk_deep: 2, soft_pad: 2.6, velvet_keys: 2,
air_strings: 2.6, warm_aura: 3, glass_bells: 1.8, wind_chimes: 2.2, music_box: 1.6
};
let currentSoundType = 'silk_air';
// Lamp flash above the keys when a tone is triggered
const lampFlashTimers = {};
function flashLamp(noteName) {
const bare = noteName.replace(/[0-9]/g, '');
const lamps = document.querySelectorAll(`[data-note="${bare}"] .key-lamp`);
lamps.forEach(el => { el.classList.remove('flash'); void el.offsetWidth; el.classList.add('flash'); });
clearTimeout(lampFlashTimers[bare]);
lampFlashTimers[bare] = setTimeout(() => {
lamps.forEach(el => el.classList.remove('flash'));
}, 300);
}
const limiter = new Tone.Limiter(-1).toDestination();
const mainVol = new Tone.Volume(-12).connect(limiter);
const reverb = new Tone.Reverb({ decay: 5, wet: 0.35 }).connect(mainVol);
const globalFilter = new Tone.Filter(2200, "lowpass").connect(reverb);
const synths = {
silk_air: () => new Tone.PolySynth(Tone.Synth, { oscillator: { type: "fatsawtooth", count: 3, spread: 20 }, envelope: { attack: 0.15, release: 1.4 }, volume: -8 }).connect(globalFilter),
silk_deep: () => new Tone.PolySynth(Tone.Synth, { oscillator: { type: "fatsawtooth", count: 6, spread: 40 }, envelope: { attack: 0.4, release: 2 }, volume: -10 }).connect(new Tone.Filter(600, "lowpass").connect(reverb)),
soft_pad: () => new Tone.PolySynth(Tone.Synth, { oscillator: { type: "triangle" }, envelope: { attack: 0.6, decay: 0.4, sustain: 0.8, release: 2.6 }, volume: -9 }).connect(new Tone.Filter(1600, "lowpass").connect(reverb)),
velvet_keys: () => new Tone.PolySynth(Tone.FMSynth, { harmonicity: 3, modulationIndex: 1.8, envelope: { attack: 0.02, decay: 1.4, sustain: 0.35, release: 2 }, volume: -9 }).connect(new Tone.Filter(2400, "lowpass").connect(reverb)),
air_strings: () => new Tone.PolySynth(Tone.Synth, { oscillator: { type: "fatsawtooth", count: 2, spread: 12 }, envelope: { attack: 0.9, decay: 0.5, sustain: 0.85, release: 2.6 }, volume: -13 }).connect(new Tone.Filter(1100, "lowpass").connect(reverb)),
warm_aura: () => new Tone.PolySynth(Tone.Synth, { oscillator: { type: "sine" }, envelope: { attack: 1.0, decay: 0.5, sustain: 0.9, release: 3 }, volume: -7 }).connect(new Tone.Filter(900, "lowpass").connect(reverb)),
glass_bells: () => new Tone.PolySynth(Tone.FMSynth, { harmonicity: 6.5, modulationIndex: 10, envelope: { attack: 0.001, decay: 1.6, sustain: 0, release: 1.8 }, modulation: { type: "sine" }, modulationEnvelope: { attack: 0.001, decay: 0.4, sustain: 0, release: 0.4 }, volume: -12 }).connect(new Tone.Filter(6000, "lowpass").connect(reverb)),
wind_chimes: () => new Tone.PolySynth(Tone.AMSynth, { harmonicity: 2.5, envelope: { attack: 0.002, decay: 1.8, sustain: 0.05, release: 2.2 }, volume: -12 }).connect(new Tone.Filter(5000, "lowpass").connect(reverb)),
music_box: () => new Tone.PolySynth(Tone.Synth, { oscillator: { type: "triangle" }, envelope: { attack: 0.002, decay: 1.2, sustain: 0, release: 1.6 }, volume: -10 }).connect(new Tone.Filter(4000, "lowpass").connect(reverb))
};
function initAudio() {
if (!isStarted) {
Tone.start();
isStarted = true;
document.getElementById('status-led').classList.add('active');
document.getElementById('status-text').innerText = "Engine Live";
}
}
function setSound(type) {
releaseHeld();
if (currentSynth) {
const old = currentSynth;
try { old.releaseAll(); } catch (e) {}
setTimeout(() => { try { old.dispose(); } catch (e) {} }, 120);
}
currentSoundType = type;
currentSynth = synths[type]();
currentSynth.maxPolyphony = 16; // guard against voice pile-up (crackle)
if (arpMode) currentSynth.set({ envelope: { release: ARP_RELEASE } });
}
function createGridSpokes() {
const container = document.getElementById('spoke-container');
container.innerHTML = '';
for(let i=0; i<12; i++) {
const spoke = document.createElement('div');
spoke.className = 'spoke';
spoke.style.transform = `rotate(${i * 30 - 90}deg)`;
container.appendChild(spoke);
}
}
function buildPiano() {
const container = document.getElementById('piano-container');
container.innerHTML = '';
NOTES.forEach(noteName => {
const isBlack = noteName.includes('#');
const key = document.createElement('div');
key.className = `piano-key ${isBlack ? 'black' : 'white'}`;
key.dataset.note = noteName;
if (!isBlack) {
const label = document.createElement('span');
label.className = 'key-label';
label.innerText = noteName;
key.appendChild(label);
}
const lamp = document.createElement('span');
lamp.className = 'key-lamp';
key.appendChild(lamp);
key.onmousedown = (e) => { e.preventDefault(); initAudio(); toggleNoteSelection(noteName); playNote(noteName); };
key.onmouseup = () => stopNote(noteName);
key.onmouseleave = () => stopNote(noteName);
container.appendChild(key);
});
}
function toggleNoteSelection(note) {
if (selectedNotes.has(note)) selectedNotes.delete(note);
else selectedNotes.add(note);
updatePianoUI();
updateHarmonicMap();
}
function updatePianoUI() {
// Additive queue density: brightness = how many queued chords contain the tone (1 of 3 = 33%, 3 of 3 = 100%)
const counts = new Array(12).fill(0);
queuedChords.forEach(chord => chord.indices.forEach(idx => {
counts[idx % 12]++;
}));
const total = queuedChords.size;
document.querySelectorAll('.piano-key').forEach(key => {
const isSel = selectedNotes.has(key.dataset.note);
const ratio = (total > 0 && !isSel) ? counts[NOTES.indexOf(key.dataset.note)] / total : 0;
key.classList.toggle('selected', isSel);
key.classList.toggle('queued', ratio > 0);
key.style.setProperty('--q', ratio.toFixed(2));
});
}
function playNote(noteName) {
if (!currentSynth) return;
currentSynth.triggerAttack(noteName + currentOctave);
flashLamp(noteName);
document.querySelectorAll(`[data-note="${noteName}"]`).forEach(el => el.classList.add('playing'));
}
function stopNote(noteName) {
if (!currentSynth) return;
currentSynth.triggerRelease(noteName + currentOctave);
document.querySelectorAll(`[data-note="${noteName}"]`).forEach(el => el.classList.remove('playing'));
}
// ---------- Keyboard playback highlight (#1) ----------
function setKeyPlaying(noteName, on) {
document.querySelectorAll(`[data-note="${noteName}"]`).forEach(el => el.classList.toggle('playing', on));
}
function clearAllPlaying() {
document.querySelectorAll('.piano-key.playing').forEach(el => el.classList.remove('playing'));
}
// ---------- Hold / Arpeggio engine (#4) ----------
function releaseHeld() {
if (heldState) heldState.timers.forEach(clearTimeout);
heldState = null;
if (currentSynth) currentSynth.releaseAll();
clearAllPlaying();
}
function startChordPlayback(chord) {
const notes = chord.intervals.map(int => {
const idx = NOTES.indexOf(chord.root) + int;
return NOTES[idx % 12] + (currentOctave + Math.floor(idx / 12));
});
heldState = { name: chord.name, notes, timers: [], momentary: !holdMode && !arpMode };
if (arpMode) {
stepArp(notes, 0);
} else {
currentSynth.triggerAttack(notes);
notes.forEach(n => { setKeyPlaying(n, true); flashLamp(n); });
}
}
function stepArp(notes, i) {
if (!heldState) return;
if (i >= notes.length) {
if (holdMode) {
// Loop the arpeggio while held; long releases ring through the gap
heldState.timers.push(setTimeout(() => {
if (!heldState) return;
currentSynth.releaseAll();
clearAllPlaying();
stepArp(heldState.notes, 0);
}, ARP_INTERVAL + 120));
} else {
// One-shot arpeggio: release shortly after the last note
heldState.timers.push(setTimeout(() => releaseHeld(), ARP_INTERVAL + 600));
}
return;
}
currentSynth.triggerAttack(notes[i]);
setKeyPlaying(notes[i], true);
flashLamp(notes[i]);
heldState.timers.push(setTimeout(() => stepArp(notes, i + 1), ARP_INTERVAL));
}
function getChordInfo(noteSet) {
const indices = Array.from(noteSet).map(n => NOTES.indexOf(n)).sort((a,b)=>a-b);
if (indices.length === 0) return { name: "SELECT", intervals: [], root: "", noteIndices: [] };
for (let rootIdx = 0; rootIdx < 12; rootIdx++) {
for (let tmpl of CHORD_TEMPLATES) {
const tmplIndices = tmpl.intervals.map(i => (rootIdx + i) % 12).sort((a,b)=>a-b);
const uniqueIndices = Array.from(new Set(indices.map(i => i % 12))).sort((a,b)=>a-b);
const uniqueTmpl = Array.from(new Set(tmplIndices.map(i => i % 12))).sort((a,b)=>a-b);
if (uniqueIndices.length === uniqueTmpl.length && uniqueIndices.every((v, i) => v === uniqueTmpl[i])) {
return { name: NOTES[rootIdx] + tmpl.suffix, root: NOTES[rootIdx], intervals: tmpl.intervals, noteIndices: uniqueIndices };
}
}
}
for (let rootIdx = 0; rootIdx < 12; rootIdx++) {
if (indices.includes(rootIdx)) {
const hasThird = indices.includes((rootIdx + 4) % 12) || indices.includes((rootIdx + 3) % 12);
const hasFifth = indices.includes((rootIdx + 7) % 12);
if (hasThird && !hasFifth) return { name: NOTES[rootIdx] + "(no 5)", root: NOTES[rootIdx], intervals: [0, 3], noteIndices: indices };
if (!hasThird && hasFifth) return { name: NOTES[rootIdx] + "5", root: NOTES[rootIdx], intervals: [0, 7], noteIndices: indices };
}
}
return { name: "Cluster", root: NOTES[indices[0]], intervals: [], noteIndices: indices };
}
function calculateSimilarity(indicesA, indicesB) {
const setA = new Set(indicesA);
const setB = new Set(indicesB);
let shared = 0;
setA.forEach(val => { if (setB.has(val)) shared++; });
return shared / Math.max(setA.size, setB.size);
}
// ---------- Map rendering: persistent nodes (CSS transitions glide them on re-layout) ----------
const nodeRegistry = new Map(); // chord name -> element
const MAP_HINT_DEFAULT = 'Ctrl+Click = queue chord · Right-click = set as core';
const MAP_HINT_RADAR = 'Selection Radar · matching chords highlighted · Ctrl+Click toggles';
function setMapHint(text) {
const el = document.getElementById('map-hint');
if (el) el.innerText = text;
}
function clearMapNodes() {
nodeRegistry.forEach(el => el.remove());
nodeRegistry.clear();
}
function attachNodeHandlers(node, chord) {
node.onmousedown = (e) => {
if (e.button === 2) return;
e.preventDefault();
if (e.ctrlKey || e.metaKey) { toggleQueuedChord(chord); return; }
initAudio();
if (heldState && heldState.name === chord.name && !heldState.momentary) { releaseHeld(); return; }
releaseHeld();
startChordPlayback(chord);
};
node.onmouseup = () => { if (heldState && heldState.momentary) releaseHeld(); };
node.onmouseleave = () => { if (heldState && heldState.momentary) releaseHeld(); };
node.oncontextmenu = (e) => {
e.preventDefault();
selectedNotes.clear();
chord.indices.forEach(idx => selectedNotes.add(NOTES[idx]));
updatePianoUI();
updateHarmonicMap();
};
}
function applyNodeStyle(node, chord, x, y, size, style) {
const tint = QUALITY_COLORS[chord.quality] || QUALITY_COLORS.other;
node.className = `chord-node ${style.extraClass || ''}`;
node.style.width = `${size}px`;
node.style.height = `${size}px`;
node.style.left = `${x}px`;
node.style.top = `${y}px`;
node.style.opacity = style.opacity !== undefined ? style.opacity : '';
const rootLine = style.compact ? '' :
`<span class="text-[8px] uppercase font-bold tracking-tighter" style="color:${hexToRgba(tint, 0.9)}">${chord.root}</span>`;
const fitLine = style.fit !== undefined ?
`<span class="text-[7px] font-mono tracking-tighter" style="color:rgba(255,255,255,0.4)">${Math.round(style.fit * 100)}%</span>` : '';
node.innerHTML = `
<span class="q-dot" style="background:${tint}; box-shadow:0 0 8px ${hexToRgba(tint, 0.7)}"></span>
${rootLine}
<span class="${style.compact ? 'text-[10px]' : 'text-[12px]'} font-bold tracking-tighter leading-none mt-0.5">${chord.name}</span>
${fitLine}
`;
node.style.borderColor = '';
node.style.boxShadow = '';
node.style.background = '';
if (style.center) {
node.style.borderColor = tint;
node.style.boxShadow = `0 0 45px ${hexToRgba(tint, 0.4)}, 0 10px 30px rgba(0,0,0,0.7)`;
} else {
node.style.borderColor = hexToRgba(tint, style.borderAlpha !== undefined ? style.borderAlpha : 0.45);
node.style.background = `linear-gradient(155deg, ${hexToRgba(tint, style.bgAlpha !== undefined ? style.bgAlpha : 0.16)} 0%, rgba(10,10,10,0.92) 62%)`;
if (style.ring) node.style.boxShadow = '0 0 0 2px rgba(255,255,255,0.55)';
}
}
// Create-or-update a node for `chord`; existing elements are re-styled in place so they glide
function upsertNode(chord, x, y, size, style) {
let node = nodeRegistry.get(chord.name);
if (!node) {
node = document.createElement('div');
attachNodeHandlers(node, chord);
document.getElementById('map-inner').appendChild(node);
nodeRegistry.set(chord.name, node);
}
applyNodeStyle(node, chord, x, y, size, style);
}
function updateHarmonicMap() {
const mapInner = document.getElementById('map-inner');
const activeChord = getChordInfo(selectedNotes);
document.getElementById('active-chord-name').innerText = activeChord.name;
document.getElementById('intervals-display').innerText = Array.from(selectedNotes).length > 0 ? Array.from(selectedNotes).join(' ') : "---";
const centerX = mapInner.offsetWidth / 2;
const centerY = mapInner.offsetHeight / 2;
// Selection Radar: 2+ queued chords move to the center, matching chords ring around them
if (queuedChords.size >= 2) {
setMapHint(MAP_HINT_RADAR);
renderSelectionRadar(centerX, centerY, activeChord);
return;
}
setMapHint(MAP_HINT_DEFAULT);
if (selectedNotes.size === 0) {
clearMapNodes();
return;
}
renderNeighborhood(centerX, centerY, activeChord);
}
// Single-core view (unchanged look): similarity ring around the active chord
function renderNeighborhood(centerX, centerY, activeChord) {
const desired = new Set();
const candidates = [];
NOTES.forEach(root => {
CHORD_TEMPLATES.forEach(tmpl => {
const noteIndices = tmpl.intervals.map(i => (NOTES.indexOf(root) + i) % 12);
const similarity = calculateSimilarity(activeChord.noteIndices, noteIndices);
if (similarity > 0.35 || root === activeChord.root) {
candidates.push({
name: root + tmpl.suffix,
root: root,
intervals: tmpl.intervals,
indices: noteIndices,
quality: QUALITY_BY_SUFFIX[tmpl.suffix] || 'other',
similarity: similarity
});
}
});
});
candidates.sort((a,b) => b.similarity - a.similarity);
const displaySet = candidates.slice(0, 32);
displaySet.forEach(chord => {
desired.add(chord.name);
const isCenter = chord.name === activeChord.name;
const fifthsIndex = FIFTHS.indexOf(chord.root);
const angle = (fifthsIndex / 12) * Math.PI * 2 - Math.PI / 2;
let dist = isCenter ? 0 : (1.15 - chord.similarity) * 280;
if (!isCenter && chord.root === activeChord.root) dist = 100;
const x = centerX + Math.cos(angle) * dist;
const y = centerY + Math.sin(angle) * dist;
const size = isCenter ? 86 : 60;
upsertNode(chord, x, y, size, {
center: isCenter,
extraClass: `${isCenter ? 'center-node' : ''} ${queuedChords.has(chord.name) ? 'queued' : ''}`.trim()
});
});
nodeRegistry.forEach((el, name) => { if (!desired.has(name)) { el.remove(); nodeRegistry.delete(name); } });
}
// Selection Radar: queued chords cluster in the center, matching chords ring around them.
// Fit = average similarity of a candidate to ALL queued chords; size/opacity/border scale with it.
function renderSelectionRadar(centerX, centerY, activeChord) {
const desired = new Set();
const queued = Array.from(queuedChords.values());
const n = queued.length;
// The selected chords themselves wander into the center as a small cluster
const clusterRadius = n <= 4 ? 54 : 24 + n * 8;
queued.forEach((chord, i) => {
desired.add(chord.name);
const angle = -Math.PI / 2 + (i * 2 * Math.PI / n);
const x = centerX + Math.cos(angle) * clusterRadius;
const y = centerY + Math.sin(angle) * clusterRadius;
upsertNode(chord, x, y, 62, { center: true, extraClass: 'center-node queued' });
});
// Score every remaining chord by average similarity across the whole selection
const scored = [];
NOTES.forEach(root => {
CHORD_TEMPLATES.forEach((tmpl, ti) => {
const name = root + tmpl.suffix;
if (queuedChords.has(name)) return;
const indices = tmpl.intervals.map(i => (NOTES.indexOf(root) + i) % 12);
let sum = 0;
queued.forEach(q => { sum += calculateSimilarity(indices, q.indices); });
const fit = sum / queued.length;
if (fit >= 0.3) {
scored.push({
name: name, root: root, intervals: tmpl.intervals, indices: indices,
quality: QUALITY_BY_SUFFIX[tmpl.suffix] || 'other', fit: fit
});
}
});
});
scored.sort((a, b) => b.fit - a.fit);
scored.slice(0, 24).forEach(chord => {
desired.add(chord.name);
const fifthsIndex = FIFTHS.indexOf(chord.root);
const ti = CHORD_TEMPLATES.findIndex(t => chord.root + t.suffix === chord.name);
const angle = (fifthsIndex / 12) * Math.PI * 2 - Math.PI / 2 + (ti - 5.5) * 0.045;
const dist = 116 + n * 6 + (1 - chord.fit) * 150;
const x = centerX + Math.cos(angle) * dist;
const y = centerY + Math.sin(angle) * dist;
const size = Math.round(48 + chord.fit * 18);
upsertNode(chord, x, y, size, {
compact: true,
fit: chord.fit,
opacity: (0.35 + chord.fit * 0.65).toFixed(2),
borderAlpha: (0.18 + chord.fit * 0.45).toFixed(2),
bgAlpha: (0.07 + chord.fit * 0.22).toFixed(2),
ring: activeChord.name === chord.name
});
});
nodeRegistry.forEach((el, name) => { if (!desired.has(name)) { el.remove(); nodeRegistry.delete(name); } });
}
// ---------- Ctrl multi-select queue (#2) ----------
function toggleQueuedChord(chord) {
if (queuedChords.has(chord.name)) queuedChords.delete(chord.name);
else queuedChords.set(chord.name, chord);
refreshQueuedUI();
}
function refreshQueuedUI() {
updatePianoUI();
renderQueuedList();
updateHarmonicMap();
}
function renderQueuedList() {
const list = document.getElementById('queued-list');
list.innerHTML = '';
if (queuedChords.size === 0) return;
const header = document.createElement('div');
header.className = 'text-[7px] text-white/25 uppercase tracking-widest mb-0.5 pointer-events-none';
header.innerText = `Queued (${queuedChords.size})`;
list.appendChild(header);
queuedChords.forEach((chord, name) => {
const row = document.createElement('div');
row.className = 'queued-item';
row.title = 'Click to remove';
row.innerHTML = `<span>${name}</span><span class="rm">×</span>`;
row.onclick = () => { queuedChords.delete(name); refreshQueuedUI(); };
list.appendChild(row);
});
}
// ---------- Quality color legend (#3) ----------
function buildQualityLegend() {
const el = document.getElementById('quality-legend');
const items = [
['Major', 'major'], ['Minor', 'minor'], ['Dom 7', 'dom7'],
['Dim', 'dim'], ['Aug', 'aug'], ['Sus', 'sus']
];
items.forEach(([label, key]) => {
const row = document.createElement('div');
row.className = 'flex items-center gap-1.5';
row.innerHTML = `<span class="text-[7px] text-white/30 uppercase tracking-widest">${label}</span>
<span class="q-dot" style="background:${QUALITY_COLORS[key]}; box-shadow:0 0 6px ${hexToRgba(QUALITY_COLORS[key], 0.6)}"></span>`;
el.appendChild(row);
});
}
// Global Listeners
window.addEventListener('keydown', (e) => {
if (e.repeat) return;
const note = KEY_MAP[e.key.toLowerCase()];
if (note) {
initAudio();
playNote(note);
}
});
window.addEventListener('keyup', (e) => {
const note = KEY_MAP[e.key.toLowerCase()];
if (note) stopNote(note);
});
document.getElementById('toggle-hold').onclick = (e) => {
holdMode = !holdMode;
e.currentTarget.classList.toggle('active', holdMode);
if (!holdMode) releaseHeld();
};
document.getElementById('toggle-arp').onclick = (e) => {
arpMode = !arpMode;
e.currentTarget.classList.toggle('active', arpMode);
releaseHeld();
// Short release while arpeggio runs, restore sound's own release when off
if (currentSynth) currentSynth.set({ envelope: { release: arpMode ? ARP_RELEASE : (SOUND_RELEASE[currentSoundType] || 2) } });
};
document.getElementById('clear-notes').onclick = () => { selectedNotes.clear(); queuedChords.clear(); releaseHeld(); updatePianoUI(); renderQueuedList(); updateHarmonicMap(); };
document.getElementById('force-detect').onclick = () => updateHarmonicMap();
document.getElementById('master-vol').oninput = (e) => { mainVol.volume.value = parseFloat(e.target.value); };
document.getElementById('sound-select').onchange = (e) => setSound(e.target.value);
document.getElementById('octave-up').onclick = () => { if (currentOctave < 6) currentOctave++; document.getElementById('octave-val').innerText = currentOctave; updateHarmonicMap(); };
document.getElementById('octave-down').onclick = () => { if (currentOctave > 1) currentOctave--; document.getElementById('octave-val').innerText = currentOctave; updateHarmonicMap(); };
// Initialization
createGridSpokes();
buildPiano();
buildQualityLegend();
renderQueuedList();
setSound('silk_air');
</script>
</body>
</html>