Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | 1x 3x 3x 3x 3x 2x 3x 2x 2x 1x 1x 3x 4x 2x 2x 2x 11x 8x 2x 2x 5x 3x 3x 2x 2x 1x 1x 3x 2x 3x 2x 7x 7x 7x 7x 7x 7x 7x 7x 60x 60x 60x 655x 60x 60x 60x 7x 7x 7x 56x 7x 84x 7x 7x 7x 56x 56x 54x 7x 7x 7x 7x 4x 4x 7x 7x 7x 7x 211x 52x 159x 159x 159x 159x 211x 211x 7x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 91x 91x 91x 91x 91x 91x 91x 91x 91x 1x 7x 211x 3x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 60x 1x 60x 1x | import { INSTRUMENTS } from "../model/instruments.js";
import { chordName } from "../model/theory.js";
/**
* Bundle of compose-result rendering helpers wired into the Alpine "app" data object via spread.
* @type {Object}
* @property {function(midi: {combinedB64: string, voicesB64: string[]}): void} wireMidiToPlayer
* Wire combined + per-voice MIDI URLs into player and visualizers; caller awaits $nextTick.
* @property {function(result: Object, voiceConfig: {voices: number, voice: Object[]}): Object} buildResultTable
* Shape compose result + voice config into the Alpine-rendered result table.
* @property {function(voiceLabels: {color: string}[]): void} applyVoiceStyles
* Stylesheet that colors midi-visualizer notes by voice index (sigma).
* @property {function(graph: Object, path: ?Object, keyIndex: number, mode: 'major'|'minor'): string} plotChordGraph
* Plots the chord graph as an SVG string; diatonic gray + 30% opacity, path edges gradient + full opacity.
*/
export const PLOTTING = {
wireMidiToPlayer,
buildResultTable,
applyVoiceStyles,
plotChordGraph,
};
/** @private */
function wireMidiToPlayer({ combinedB64, voicesB64 }) {
const player = document.getElementById("midi-player");
const visualizer = document.getElementById("midi-visualizer");
const dataUrl = `data:audio/midi;base64,${combinedB64}`;
if (visualizer) {
visualizer.src = dataUrl;
}
if (player) {
player.src = dataUrl;
if (!player._vizBound && visualizer) {
player.addVisualizer(visualizer);
player._vizBound = true;
}
}
document.querySelectorAll(".midi-visualizer").forEach((vis, idx) => {
if (voicesB64?.[idx]) {
vis.src = `data:audio/midi;base64,${voicesB64[idx]}`;
}
});
}
/** @private */
function buildResultTable(result, voiceConfig) {
const { parts, labelCache } = result;
const { voices, voice } = voiceConfig;
const labelOf = (p, i) => p.label || `Part ${i + 1}`;
const cached = (k, p, i) => labelCache[labelOf(p, i)]?.[k];
const names = Object.values(INSTRUMENTS).flat();
return {
headers: parts.map(labelOf),
cells: Array.from({ length: voices }, (_, v) =>
parts.map((p, i) => cached("voicesB64", p, i)?.[v] || null),
),
voices,
voiceLabels: voice.slice(0, voices).map((vc, i) => ({
num: i + 1,
instrument: names[vc?.instrument ?? 0],
color: vc?.color || "#888888",
})),
partChordNames: parts.map(
(p, i) => cached("concreteProgression", p, i) || "",
),
};
}
/** @private */
function applyVoiceStyles(voiceLabels) {
let el = document.getElementById("voice-colors");
if (!el) {
el = document.head.appendChild(document.createElement("style"));
el.id = "voice-colors";
}
const sel = (i) => `midi-visualizer svg rect.note[data-instrument="${i}"]`;
const rule = (vl, i) =>
`${sel(i)} { stroke: ${vl.color}; fill: ${vl.color}; }`;
el.textContent = voiceLabels.map(rule).join("\n");
}
/** @private */
function plotChordGraph(graph, path, keyIndex = 0, mode = "major") {
const { nodes, edges, costs } = graph;
const costMap = costs instanceof Map ? costs : new Map(Object.entries(costs));
const { positions, colorMap, diatonic, chromatic } = layoutFor(nodes, mode);
const pathEdges = path?.edges ?? new Set();
const pathNodeSet = new Set(path?.nodes ?? []);
const edgeSvg = renderEdges(edges, positions, costMap, pathEdges);
const gradientDefs = buildGradients(edges, positions, colorMap, pathEdges);
const nodeSvg = [...diatonic, ...chromatic]
.map((node) => {
const pos = positions[node];
const color = colorMap[node] || LAYOUT.general.fallbackColor;
const op = pathNodeSet.has(node) ? 1 : 0.5;
const hasLoop = edges.some(([u, v]) => u === node && v === node);
const loop = hasLoop
? renderSelfLoop(pos, color, pathEdges.has(`${node}->${node}`))
: "";
const subLabel =
diatonic.includes(node) && node !== "NC"
? chordName(node, keyIndex)
: "";
return `${nodeCircle(pos, color, op)}${loop}${renderLabel(node, pos, op, subLabel)}`;
})
.join("");
const viewH = chromatic.length > 0 ? 440 : 300;
return [
`<svg viewBox="0 0 860 ${viewH}" xmlns="http://www.w3.org/2000/svg" style="max-width:860px; width:100%;">`,
`<defs>`,
`<marker id="ah" markerWidth="6" markerHeight="5" refX="5" refY="2.5" orient="auto" overflow="visible">`,
`<polygon points="0,0 6,2.5 0,5" fill="context-stroke"/>`,
`</marker>`,
gradientDefs,
`</defs>`,
edgeSvg,
nodeSvg,
`</svg>`,
].join("");
}
/** @private Per-mode (mu) layout: positions, colors, diatonic and chromatic split. */
function layoutFor(nodes, mode) {
const layout = LAYOUT[mode];
const diatonic = layout.map((s) => s.chord);
const darken = (rgb) =>
rgb.replace(/\d+/g, (v) => `${Math.round(Number(v) * 0.6)}`);
const positions = {};
const colorMap = {};
for (const { chord, x, y, color } of layout) {
positions[chord] = { x, y };
colorMap[chord] = y > 150 ? darken(color) : color;
}
const chromatic = nodes.filter((n) => !positions[n]);
const row3Y = 360;
const row3Left = 130;
const row3Right = 730;
chromatic.forEach((name, i) => {
const x =
chromatic.length === 1
? (row3Left + row3Right) / 2
: row3Left + (i * (row3Right - row3Left)) / (chromatic.length - 1);
positions[name] = { x, y: row3Y };
});
return { positions, colorMap, diatonic, chromatic };
}
/** @private Render non-loop edges; gradient ids match buildGradients order. */
function renderEdges(edges, positions, costMap, pathEdges) {
let edgeIdx = 0;
let svg = "";
for (const [u, v] of edges) {
if (u === v) {
continue;
}
const from = positions[u];
const to = positions[v];
const isPath = pathEdges.has(`${u}->${v}`);
const attrs = {
stroke: isPath ? `url(#eg${edgeIdx})` : "#999",
width: (6 / costMap.get(`${u}->${v}`)) * (isPath ? 1.5 : 1),
opacity: isPath ? 1 : 0.3,
};
svg +=
from.y === to.y ? edgeCurve(from, to, attrs) : edgeLine(from, to, attrs);
edgeIdx += isPath ? 1 : 0;
}
return svg;
}
/** @private Same-row edge as quadratic Bezier curve to avoid overlap. */
function edgeCurve(from, to, attrs) {
const xGap = Math.abs(to.x - from.x);
const isNeighbor = xGap <= 200;
const curveDir = isNeighbor
? to.x > from.x
? -1
: 1
: from.y <= 150
? -1
: 1;
const cx = (from.x + to.x) / 2;
const cy = from.y + curveDir * xGap * 0.15;
const x1 =
from.x +
(to.x > from.x ? LAYOUT.general.nodeRadius : -LAYOUT.general.nodeRadius);
const y1 = from.y + curveDir * 4;
const x2 =
to.x +
(from.x > to.x ? LAYOUT.general.nodeRadius : -LAYOUT.general.nodeRadius);
const y2 = to.y + curveDir * 4;
return `<path
d="M${x1.toFixed(1)},${y1.toFixed(1)} Q${cx.toFixed(1)},${cy.toFixed(1)} ${x2.toFixed(1)},${y2.toFixed(1)}"
fill="none"
stroke="${attrs.stroke}"
stroke-width="${attrs.width}"
marker-end="url(#ah)"
opacity="${attrs.opacity}"/>`;
}
/** @private Cross-row edge as straight line, shrunk to circle perimeters. */
function edgeLine(from, to, attrs) {
const dx = to.x - from.x;
const dy = to.y - from.y;
const dist = Math.sqrt(dx * dx + dy * dy);
const shrink = (LAYOUT.general.nodeRadius + 4) / dist;
const x1 = from.x + dx * shrink;
const y1 = from.y + dy * shrink;
const x2 = to.x - dx * shrink;
const y2 = to.y - dy * shrink;
return `<line
x1="${x1.toFixed(1)}" y1="${y1.toFixed(1)}"
x2="${x2.toFixed(1)}" y2="${y2.toFixed(1)}"
stroke="${attrs.stroke}"
stroke-width="${attrs.width}"
marker-end="url(#ah)"
opacity="${attrs.opacity}"/>`;
}
/** @private Linear-gradient defs for path edges in encounter order. */
const buildGradients = (edges, positions, colorMap, pathEdges) =>
edges
.filter(([u, v]) => u !== v && pathEdges.has(`${u}->${v}`))
.map(
([u, v], i) => `<linearGradient id="eg${i}" gradientUnits="userSpaceOnUse"
x1="${positions[u].x}" y1="${positions[u].y}" x2="${positions[v].x}" y2="${positions[v].y}">
<stop offset="0%" stop-color="${colorMap[u] || LAYOUT.general.fallbackColor}"/>
<stop offset="100%" stop-color="${colorMap[v] || LAYOUT.general.fallbackColor}"/>
</linearGradient>`,
)
.join("");
/** @private Self-loop arc, lit when the loop edge is on the highlighted path. */
function renderSelfLoop(pos, color, isLit) {
const a1 = (23 * Math.PI) / 180;
const a2 = (67 * Math.PI) / 180;
const ac = (45 * Math.PI) / 180;
const p1x = pos.x + LAYOUT.general.nodeRadius * Math.sin(a1);
const p1y = pos.y - LAYOUT.general.nodeRadius * Math.cos(a1);
const p2x = pos.x + LAYOUT.general.nodeRadius * Math.sin(a2);
const p2y = pos.y - LAYOUT.general.nodeRadius * Math.cos(a2);
const cx = pos.x + (LAYOUT.general.nodeRadius + 22) * Math.sin(ac);
const cy = pos.y - (LAYOUT.general.nodeRadius + 22) * Math.cos(ac);
const stroke = isLit ? color : "#999";
const opacity = isLit ? 1 : 0.3;
return `<path
d="M${p1x.toFixed(1)},${p1y.toFixed(1)} Q${cx.toFixed(1)},${cy.toFixed(1)} ${p2x.toFixed(1)},${p2y.toFixed(1)}"
fill="none"
stroke="${stroke}"
stroke-width="2"
marker-end="url(#ah)"
opacity="${opacity}"/>`;
}
/** @private White-fill ring drawn around every node. */
const nodeCircle = (pos, color, op) => `<circle
cx="${pos.x}" cy="${pos.y}" r="${LAYOUT.general.nodeRadius}"
fill="#fff"
stroke="${color}"
stroke-width="4"
opacity="${op}"/>`;
/** @private Roman-numeral label; subLabel adds a chord-name subscript. */
const renderLabel = (node, pos, op, subLabel) =>
subLabel
? `<text
x="${pos.x}" y="${pos.y - 7}"
text-anchor="middle" dominant-baseline="central"
font-size="13" font-family="serif" font-weight="bold"
fill="#000" opacity="${op}">${node}</text>
<text
x="${pos.x}" y="${pos.y + 10}"
text-anchor="middle" dominant-baseline="central"
font-size="12" font-family="sans-serif"
fill="#000" opacity="${op * 0.7}">${subLabel}</text>`
: `<text
x="${pos.x}" y="${pos.y}"
text-anchor="middle" dominant-baseline="central"
font-size="11" font-family="serif"
fill="#000" opacity="${op}">${node}</text>`;
/** @private Per-mode (mu) layout + general visual constants. */
const LAYOUT = {
general: { nodeRadius: 30, fallbackColor: "rgb(120,120,120)" },
major: [
{ chord: "IV", x: 130, y: 80, color: "rgb(0,0,255)" },
{ chord: "I", x: 330, y: 80, color: "rgb(0,255,0)" },
{ chord: "V", x: 530, y: 80, color: "rgb(255,0,0)" },
{ chord: "ii", x: 130, y: 220, color: "rgb(0,0,191)" },
{ chord: "vi", x: 330, y: 220, color: "rgb(0,191,0)" },
{ chord: "iii", x: 530, y: 220, color: "rgb(191,191,0)" },
{ chord: "viio", x: 730, y: 220, color: "rgb(191,0,191)" },
{ chord: "NC", x: 730, y: 80, color: "rgb(0,0,0)" },
],
minor: [
{ chord: "bVI", x: 130, y: 80, color: "rgb(0,0,255)" },
{ chord: "III", x: 330, y: 80, color: "rgb(0,255,0)" },
{ chord: "bVII", x: 530, y: 80, color: "rgb(255,0,0)" },
{ chord: "iv", x: 130, y: 220, color: "rgb(0,0,191)" },
{ chord: "i", x: 330, y: 220, color: "rgb(0,191,0)" },
{ chord: "V", x: 530, y: 220, color: "rgb(191,191,0)" },
{ chord: "iio", x: 730, y: 220, color: "rgb(191,0,191)" },
{ chord: "NC", x: 730, y: 80, color: "rgb(0,0,0)" },
],
};
|