All files / src app.js

100% Statements 115/115
100% Branches 43/43
100% Functions 17/17
100% Lines 110/110

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                                          4x 4x                                                                           4x                 4x 4x 4x 4x 3x 3x 3x 3x 1x   3x 2x     4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x 1x   2x 2x 1x 1x   1x     4x   1x                 21x 21x 6x   6x   6x   21x 21x 21x                   7x 1x   6x 6x 6x 6x 7x 7x 7x 7x 7x           1x 1x     5x 1x   4x 4x 4x 1x 1x 1x   4x 4x 4x               1x   6x 6x                 7x 7x 7x 7x 7x 7x 7x 7x 7x               4x 2x   2x 2x   1x 1x                 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x                   10x 10x 9x 9x 6x   9x 5x     10x   10x             10x 1x   9x 9x 8x                  
import { compose } from "./controller/composer.js";
import {
  buildParameters,
  exportParameters,
  importParameters,
} from "./controller/parameters.js";
import { initSolvers, solveModel } from "./controller/solving.js";
import { chordGraph, chordName } from "./model/theory.js";
import { Step1Parts } from "./pipeline/step1parts.js";
import { Step2Chords } from "./pipeline/step2chords.js";
import { Step3Notes } from "./pipeline/step3notes.js";
import { CONTROLS } from "./view/controls.js";
import { submitFeedback } from "./view/feedback.js";
import { downloadBlob } from "./view/download.js";
import { PLOTTING } from "./view/plotting.js";
 
/** @external {alpinejs} https://www.npmjs.com/package/alpinejs */
/** @external {html-midi-player} https://www.npmjs.com/package/html-midi-player */
/** @external {picocss} https://www.npmjs.com/package/@picocss/pico */
 
/** Alpine "app" data object / entry point. */
document.addEventListener("alpine:init", () =>
  Alpine.data("app", () => ({
    // Solver readiness + status line
    isMiniZincReady: false,
    mznSolver: "",
    mznSolvers: [],
    statusText: "Initializing...",
 
    // Theme
    theme: "auto",
    isSystemDark: false,
 
    // Pipeline definition (loaded once at init)
    steps: [],
    schemas: {},
    parameters: {},
 
    // Pipeline outputs (populated by runSolver)
    mznModelText: [[], [], []],
    mznSolutionText: [[], [], []],
    mznStatisticsText: [[], [], []],
    musicB64Midi: null,
    chordProgressionText: [],
    resultTable: null,
 
    // Console + UI transient state
    consoleLog: [],
    showConsole: false,
    importedFileName: "",
 
    // Theory helpers exposed to templates (per-row dynamic chord options).
    chordGraph,
    chordName,
 
    ...APP_METHODS,
  })),
);
 
/** @private Methods on the Alpine "app" data object; bound to per-instance this. */
const APP_METHODS = {
  exportParameters,
  ...CONTROLS,
  downloadBlob,
  submitFeedback,
  ...PLOTTING,
 
  /** @desc Alpine lifecycle: detect dark mode, bind the midi-player autoscroll, init MiniZinc + step schemas. */
  async init() {
    const mq = window.matchMedia("(prefers-color-scheme: dark)");
    this.isSystemDark = mq.matches;
    mq.addEventListener("change", (e) => (this.isSystemDark = e.matches));
    document.getElementById("midi-player")?.addEventListener("start", () => {
      const viz = document.getElementById("midi-visualizer");
      const sel = ".waterfall-notes-container";
      const c = viz?.querySelector(sel) ?? viz?.shadowRoot?.querySelector(sel);
      if (c) {
        c.scrollTop = c.scrollHeight;
      }
      if (viz) {
        viz.scrollTop = viz.scrollHeight;
      }
    });
    this.statusText = "Initializing MiniZinc...";
    try {
      const solverList = await initSolvers();
      this.mznSolvers = solverList;
      this.mznSolver = solverList[0].id;
      this.isMiniZincReady = true;
      const newSteps = [new Step1Parts(), new Step2Chords(), new Step3Notes()];
      Object.assign(this, await buildParameters(newSteps));
      this.$watch("parameters.step2.part", () => this.updateGraph());
      this.$nextTick(() => this.updateGraph());
      document
        .getElementById("import-params")
        ?.addEventListener("change", async (e) => {
          const file = e.target.files[0];
          if (!file) {
            return;
          }
          try {
            const merged = await importParameters(file);
            this.parameters = { ...this.parameters, ...merged };
            this.importedFileName = file.name;
          } catch (err) {
            this.log("Failed to import parameters", err);
          }
        });
      this.log("Ready to compose.");
    } catch (e) {
      this.log("Failed to load solvers", e);
    }
  },
 
  /**
   * @desc Mirror msg into the status line and append a [HH:MM:SS]-stamped console-log entry;
   * optional err is console.error'd and joined into the line as "Error: msg: <detail>".
   */
  log(msg, err) {
    let line = msg;
    if (err) {
      console.error(msg, err);
      const detail =
        err?.message ??
        (typeof err === "object" ? JSON.stringify(err) : `${err}`);
      line = `Error: ${msg}: ${detail}`;
    }
    this.statusText = line;
    const t = new Date().toLocaleTimeString("de-DE");
    this.consoleLog.push(`[${t}] ${line}`);
  },
 
  /**
   * @desc Drive a full 3-step composition run via {@link compose}:
   * bind hooks to Alpine state + DOM, then map the result onto the result table,
   * voice colors, MIDI player, and status line.
   * @listens {progressionLine}
   */
  async runSolver() {
    if (!this.isMiniZincReady) {
      return;
    }
    const btn = document.getElementById("run-optimization-button");
    btn.setAttribute("aria-busy", "true");
    btn.disabled = true;
    window.Tone?.start();
    this.log("Running solver for all steps...");
    this.resetResults();
    try {
      const lines = [];
      const result = await compose(this.parameters, this.steps, {
        log: this.log.bind(this),
        loadPreset: this.loadPreset.bind(this),
        solveStep: this.solveStep.bind(this),
        updateGraph: this.updateGraph.bind(this),
        onProgressionLine: (line) => {
          lines.push(line);
          this.chordProgressionText = [...lines];
        },
      });
      if (!result) {
        return;
      }
      this.resultTable = this.buildResultTable(result, this.parameters.step3);
      this.applyVoiceStyles(this.resultTable.voiceLabels);
      if (result.midi) {
        this.musicB64Midi = result.midi.combinedB64;
        await this.$nextTick();
        this.wireMidiToPlayer(result.midi);
      }
      const { parts, failedParts: fp, solvedParts: sp } = result;
      const u = [...new Set(fp)].join(", ");
      this.log(
        fp.length === 0
          ? `Done: ${sp}/${parts.length} parts solved.`
          : sp > 0
            ? `Partial: ${sp}/${parts.length} parts solved. Overconstrained: ${u}. Try again.`
            : "No solution: Model may be overconstrained.",
      );
    } catch (e) {
      this.log("Solve failed", e);
    } finally {
      btn.removeAttribute("aria-busy");
      btn.disabled = false;
    }
  },
 
  /**
   * @desc Clear all per-run state (mzn texts, midi, progression, graph, player srcs);
   * keep the latest log line.
   */
  resetResults() {
    this.consoleLog = this.consoleLog.slice(-1);
    this.mznModelText = [[], [], []];
    this.mznSolutionText = [[], [], []];
    this.mznStatisticsText = [[], [], []];
    this.musicB64Midi = null;
    this.chordProgressionText = [];
    document.getElementById("graph")?.replaceChildren();
    const sel = "midi-visualizer, midi-player";
    document.querySelectorAll(sel).forEach((el) => el.removeAttribute("src"));
  },
 
  /**
   * @desc Hook: Fetch a corpus preset (pi) JSON by id;
   * null for "manual" or on fetch failure.
   */
  async loadPreset(style) {
    if (!style || style === "manual") {
      return null;
    }
    try {
      return await (await fetch(`scripts/presets/${style}.json`)).json();
    } catch {
      console.warn(`Could not load preset ${style}`);
      return null;
    }
  },
 
  /**
   * @desc Hook: Run one MZN model on the solver;
   * record model/solution/stats per step.index for the raw-output tabs.
   */
  async solveStep(step, partLabel, modelStr) {
    const idx = step.index - 1;
    const label = partLabel ? `${step.name}: ${partLabel}` : step.name;
    const file = `${step.id}_${Date.now()}.mzn`;
    this.mznModelText[idx].push({ label, content: modelStr });
    const r = await solveModel(file, modelStr, this.mznSolver);
    const json = r.solution?.output?.json;
    const stats = r.statistics
      ? JSON.stringify({ ...r.statistics }, null, 2)
      : "{}";
    const sol = JSON.stringify(json, null, 2);
    this.mznSolutionText[idx].push({ label, content: sol });
    this.mznStatisticsText[idx].push({ label, content: stats });
    return json;
  },
 
  /**
   * @desc Hook: Render the chord graph + sync form chord-selectors.
   * With no arg: derive from form (mode change).
   * With arg: render the compose-hook payload (path-highlighted).
   * Also resets each part's start/end chord to the mode's tonic when no longer in activeNodes.
   */
  updateGraph(svg) {
    const parts = this.parameters?.step2?.part;
    parts?.forEach((row) => {
      const { activeNodes, tonic } = chordGraph(row.mode);
      if (!activeNodes.includes(row.start_chord)) {
        row.start_chord = tonic;
      }
      if (!activeNodes.includes(row.end_chord)) {
        row.end_chord = tonic;
      }
    });
    const s2 = parts?.[0];
    const data =
      svg ??
      (s2 && {
        graph: chordGraph(s2.mode),
        path: null,
        key: Number(s2.key) || 0,
        mode: s2.mode,
      });
    if (!data) {
      return;
    }
    const el = document.getElementById("graph");
    if (el) {
      el.innerHTML = this.plotChordGraph(
        data.graph,
        data.path,
        data.key,
        data.mode,
      );
    }
  },
};