compact_sets/webapp/path_navigator.html

528 lines
16 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Path Navigator</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
margin: 0;
padding: 20px;
background: #1a1a2e;
color: #eee;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
h1 {
text-align: center;
margin-bottom: 10px;
}
.controls {
display: flex;
justify-content: center;
gap: 20px;
margin-bottom: 20px;
align-items: center;
}
.controls button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background: #16213e;
color: #eee;
border: 1px solid #0f3460;
border-radius: 5px;
}
.controls button:hover {
background: #0f3460;
}
.controls button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.index-display {
font-size: 18px;
font-weight: bold;
}
#graph-container {
width: 100%;
height: 500px;
border: 1px solid #0f3460;
border-radius: 8px;
background: #16213e;
}
.chord-info {
display: flex;
justify-content: space-around;
margin-top: 20px;
}
.chord-panel {
background: #16213e;
padding: 15px;
border-radius: 8px;
min-width: 250px;
}
.chord-panel h3 {
margin-top: 0;
color: #e94560;
}
.chord-panel.current {
border: 2px solid #e94560;
}
.chord-panel.prev, .chord-panel.next {
opacity: 0.7;
}
.pitch-list {
list-style: none;
padding: 0;
}
.pitch-list li {
padding: 5px 0;
font-family: monospace;
}
.file-input {
margin-bottom: 20px;
text-align: center;
}
.file-input input {
padding: 10px;
background: #16213e;
color: #eee;
border: 1px solid #0f3460;
border-radius: 5px;
}
svg {
width: 100%;
height: 100%;
}
.node circle {
stroke: #fff;
stroke-width: 2px;
}
.node.current circle {
stroke: #e94560;
stroke-width: 3px;
}
.link {
stroke: #4a5568;
stroke-width: 2px;
}
.link-label {
fill: #a0aec0;
font-size: 12px;
font-family: monospace;
}
.node-label {
fill: #eee;
font-size: 11px;
font-family: monospace;
text-anchor: middle;
}
</style>
</head>
<body>
<div class="container">
<h1>Path Navigator</h1>
<div class="file-input">
<input type="file" id="fileInput" accept=".json">
<span style="margin-left: 10px;">(default: output/output_chords.json)</span>
</div>
<div class="controls">
<button id="prevBtn" disabled>← Previous</button>
<span class="index-display">Index: <span id="currentIndex">0</span> / <span id="totalSteps">0</span></span>
<button id="nextBtn" disabled>Next →</button>
</div>
<div id="graph-container"></div>
<div class="chord-info">
<div class="chord-panel prev">
<h3>Previous</h3>
<ul class="pitch-list" id="prevPitches"></ul>
</div>
<div class="chord-panel current">
<h3>Current</h3>
<ul class="pitch-list" id="currentPitches"></ul>
</div>
<div class="chord-panel next">
<h3>Next</h3>
<ul class="pitch-list" id="nextPitches"></ul>
</div>
</div>
</div>
<script>
// Global state
let chords = [];
let currentIndex = 0;
let simulation = null;
// D3 setup
const width = 1100;
const height = 500;
const svg = d3.select("#graph-container")
.append("svg")
.attr("viewBox", `0 0 ${width} ${height}`);
const g = svg.append("g");
// Zoom behavior
const zoom = d3.zoom()
.scaleExtent([0.5, 4])
.on("zoom", (event) => {
g.attr("transform", event.transform);
});
svg.call(zoom);
// Load default file
async function loadDefaultFile() {
try {
const response = await fetch("output/output_chords.json");
if (!response.ok) throw new Error("File not found");
const data = await response.json();
loadChords(data.chords);
} catch (e) {
console.log("No default file, waiting for user upload");
}
}
// File input handler
document.getElementById("fileInput").addEventListener("change", async (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
try {
const data = JSON.parse(event.target.result);
loadChords(data.chords || data);
} catch (err) {
alert("Invalid JSON file");
}
};
reader.readAsText(file);
});
function loadChords(chordData) {
chords = chordData;
currentIndex = 0;
updateDisplay();
}
// Compute edge between two pitches if they differ by ±1 in exactly one non-dim-0 dimension
function getEdgeInfo(pitch1, pitch2) {
const hs1 = pitch1.hs_array;
const hs2 = pitch2.hs_array;
let diffCount = 0;
let diffDim = -1;
for (let i = 1; i < hs1.length; i++) { // Skip dimension 0 (prime 2)
const diff = hs2[i] - hs1[i];
if (Math.abs(diff) === 1) {
diffCount++;
diffDim = i;
} else if (diff !== 0) {
return null; // Difference > 1 in this dimension
}
}
// Must differ by exactly ±1 in exactly one dimension
if (diffCount !== 1) return null;
// Check dimension 0 (prime 2) - must be same
if (hs1[0] !== hs2[0]) return null;
// Calculate ratio
const ratio = parseFraction(pitch1.fraction) / parseFraction(pitch2.fraction);
return {
dim: diffDim,
ratio: ratio
};
}
function parseFraction(frac) {
if (typeof frac === 'number') return frac;
const parts = frac.split('/');
if (parts.length === 1) return parseFloat(parts[0]);
return parseInt(parts[0]) / parseInt(parts[1]);
}
function formatRatio(ratio) {
// Simplify ratio to simple intervals
const tolerance = 0.01;
// Common ratios
const commonRatios = [
{ r: 2, label: "2/1" },
{ r: 3/2, label: "3/2" },
{ r: 4/3, label: "4/3" },
{ r: 5/4, label: "5/4" },
{ r: 6/5, label: "6/5" },
{ r: 5/3, label: "5/3" },
{ r: 8/5, label: "8/5" },
{ r: 7/4, label: "7/4" },
{ r: 7/5, label: "7/5" },
{ r: 7/6, label: "7/6" },
{ r: 9/8, label: "9/8" },
{ r: 10/9, label: "10/9" },
{ r: 16/15, label: "16/15" },
{ r: 15/14, label: "15/14" },
{ r: 9/7, label: "9/7" },
{ r: 10/7, label: "10/7" },
{ r: 1, label: "1/1" },
];
// Check both ratio and its inverse
for (const {r, label} of commonRatios) {
if (Math.abs(ratio - r) < tolerance || Math.abs(ratio - 1/r) < tolerance) {
return ratio < 1 ? label : reverseRatio(label);
}
}
// Default: show simplified fraction
return ratio < 1 ? simplifyRatio(ratio) : simplifyRatio(1/ratio);
}
function reverseRatio(ratio) {
const parts = ratio.split('/');
if (parts.length !== 2) return ratio;
return parts[1] + "/" + parts[0];
}
function simplifyRatio(ratio) {
// Simple fraction simplification
for (let d = 2; d <= 16; d++) {
for (let n = 1; n < d; n++) {
if (Math.abs(ratio - n/d) < 0.01) {
return n + "/" + d;
}
}
}
return ratio.toFixed(2);
}
function buildGraph(chord) {
const nodes = chord.map((pitch, i) => ({
id: i,
pitch: pitch,
label: pitch.fraction,
hs: pitch.hs_array
}));
const links = [];
const labelSet = new Set();
for (let i = 0; i < nodes.length; i++) {
for (let j = i + 1; j < nodes.length; j++) {
const edgeInfo = getEdgeInfo(nodes[i].pitch, nodes[j].pitch);
if (edgeInfo) {
const label = formatRatio(edgeInfo.ratio);
links.push({
source: i,
target: j,
label: label
});
}
}
}
return { nodes, links };
}
function renderGraph(chord) {
const { nodes, links } = buildGraph(chord);
// Clear previous
g.selectAll("*").remove();
if (nodes.length === 0) {
g.append("text")
.attr("x", width / 2)
.attr("y", height / 2)
.attr("text-anchor", "middle")
.attr("fill", "#888")
.text("No chord data");
return;
}
// Force simulation
simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.id).distance(100))
.force("charge", d3.forceManyBody().strength(-300))
.force("center", d3.forceCenter(width / 2, height / 2))
.force("collision", d3.forceCollide().radius(40));
// Draw links
const link = g.selectAll(".link")
.data(links)
.enter()
.append("line")
.attr("class", "link");
// Draw link labels
const linkLabel = g.selectAll(".link-label")
.data(links)
.enter()
.append("text")
.attr("class", "link-label")
.attr("text-anchor", "middle")
.text(d => d.label);
// Draw nodes
const node = g.selectAll(".node")
.data(nodes)
.enter()
.append("g")
.attr("class", "node")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
node.append("circle")
.attr("r", 20)
.attr("fill", (d, i) => d3.schemeCategory10[i % 10]);
node.append("text")
.attr("class", "node-label")
.attr("dy", 4)
.text(d => d.label);
// Update positions on tick
simulation.on("tick", () => {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
linkLabel
.attr("x", d => (d.source.x + d.target.x) / 2)
.attr("y", d => (d.source.y + d.target.y) / 2 - 10);
node.attr("transform", d => `translate(${d.x},${d.y})`);
});
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
}
function updateChordPanel(elementId, chord) {
const ul = document.getElementById(elementId);
ul.innerHTML = "";
if (!chord || chord.length === 0) {
ul.innerHTML = "<li>(none)</li>";
return;
}
chord.forEach(pitch => {
const li = document.createElement("li");
li.textContent = `${pitch.fraction} (${pitch.hs_array.join(", ")})`;
ul.appendChild(li);
});
}
function updateDisplay() {
document.getElementById("currentIndex").textContent = currentIndex;
document.getElementById("totalSteps").textContent = chords.length - 1;
document.getElementById("prevBtn").disabled = currentIndex === 0;
document.getElementById("nextBtn").disabled = currentIndex >= chords.length - 1;
// Update chord panels
const prevChord = currentIndex > 0 ? chords[currentIndex - 1] : null;
const currentChord = chords[currentIndex];
const nextChord = currentIndex < chords.length - 1 ? chords[currentIndex + 1] : null;
updateChordPanel("prevPitches", prevChord);
updateChordPanel("currentPitches", currentChord);
updateChordPanel("nextPitches", nextChord);
// Render graph
renderGraph(currentChord);
}
// Navigation
document.getElementById("prevBtn").addEventListener("click", () => {
if (currentIndex > 0) {
currentIndex--;
updateDisplay();
}
});
document.getElementById("nextBtn").addEventListener("click", () => {
if (currentIndex < chords.length - 1) {
currentIndex++;
updateDisplay();
}
});
// Keyboard navigation
document.addEventListener("keydown", (e) => {
if (e.key === "ArrowLeft") {
if (currentIndex > 0) {
currentIndex--;
updateDisplay();
}
} else if (e.key === "ArrowRight") {
if (currentIndex < chords.length - 1) {
currentIndex++;
updateDisplay();
}
}
});
// Initialize
loadDefaultFile();
</script>
</body>
</html>