-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.js
More file actions
599 lines (500 loc) · 17.9 KB
/
editor.js
File metadata and controls
599 lines (500 loc) · 17.9 KB
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
// vim: set sw=2:ts=2:
// Available instruments (excluding Win which is for victory only)
// Volume property controls per-sample loudness (0.0 to 1.0)
const AVAILABLE_INSTRUMENTS = [
{ name: "Snare", file: "snare.wav", volume: 0.5 },
{ name: "Kick", file: "kick.wav", volume: 0.5 },
{ name: "Hi-Hat", file: "hihat_closed.wav", volume: 0.5 },
{ name: "Open Hi-Hat", file: "hihat_open.wav", volume: 0.5 },
{ name: "Crash", file: "crash.wav", volume: 0.5 },
{ name: "Cowbell", file: "cowbell.wav", volume: 0.5 },
{ name: "Stick", file: "stick.wav", volume: 0.5 },
];
class LevelEditor {
constructor() {
this.levels = [];
this.currentLevelIndex = -1;
this.audioLibrary = null;
this.isPlaying = false;
this.playTimeouts = [];
this.initAudio();
this.loadLevels();
this.bindEvents();
}
initAudio() {
// Include Win sound for potential preview feedback
const samples = [
...AVAILABLE_INSTRUMENTS,
{ name: "Win", file: "win.wav", volume: 0.2 },
];
this.audioLibrary = new AudioLibrary(samples);
}
async loadLevels() {
try {
const response = await fetch("./levels.json");
if (!response.ok) {
throw new Error(`Failed to load levels: ${response.status}`);
}
this.levels = await response.json();
this.renderLevelList();
// Select first level if available
if (this.levels.length > 0) {
this.selectLevel(0);
}
} catch (error) {
console.error("Error loading levels:", error);
this.levels = [];
this.renderLevelList();
}
}
bindEvents() {
// Sidebar buttons
document.getElementById("addLevelBtn").addEventListener("click", () => {
this.addLevel();
});
document.getElementById("duplicateLevelBtn").addEventListener("click", () => {
this.duplicateLevel();
});
document.getElementById("downloadBtn").addEventListener("click", () => {
this.downloadJSON();
});
// Level list event delegation
document.getElementById("levelList").addEventListener("click", (e) => {
const li = e.target.closest("li");
if (!li) return;
const index = parseInt(li.dataset.index, 10);
if (e.target.classList.contains("move-up")) {
this.moveLevel(index, -1);
} else if (e.target.classList.contains("move-down")) {
this.moveLevel(index, 1);
} else if (e.target.classList.contains("delete")) {
this.deleteLevel(index);
} else {
this.selectLevel(index);
}
});
}
// ============ Level List Management ============
renderLevelList() {
const list = document.getElementById("levelList");
list.innerHTML = this.levels
.map(
(level, index) => `
<li data-index="${index}" class="${index === this.currentLevelIndex ? "selected" : ""}">
<span class="level-name">${this.escapeHtml(level.name)}</span>
<span class="level-actions">
<button class="level-action-btn move-up" title="Move up">↑</button>
<button class="level-action-btn move-down" title="Move down">↓</button>
<button class="level-action-btn delete" title="Delete">×</button>
</span>
</li>
`
)
.join("");
}
selectLevel(index) {
if (index < 0 || index >= this.levels.length) return;
this.stopPreview();
this.currentLevelIndex = index;
this.renderLevelList();
this.renderEditor();
}
addLevel() {
const newLevel = {
name: "New Level",
bpm: 90,
resolution: 4,
groupSize: 4,
description: "",
pattern: [
{ name: "Snare", steps: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] },
{ name: "Kick", steps: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] },
],
};
this.levels.push(newLevel);
this.selectLevel(this.levels.length - 1);
}
duplicateLevel() {
if (this.currentLevelIndex < 0) return;
const original = this.levels[this.currentLevelIndex];
const duplicate = JSON.parse(JSON.stringify(original));
duplicate.name = `${original.name} (copy)`;
// Insert after current level
this.levels.splice(this.currentLevelIndex + 1, 0, duplicate);
this.selectLevel(this.currentLevelIndex + 1);
}
deleteLevel(index) {
if (this.levels.length <= 1) {
alert("Cannot delete the last level.");
return;
}
const level = this.levels[index];
if (!confirm(`Delete level "${level.name}"?`)) return;
this.levels.splice(index, 1);
// Adjust current selection
if (this.currentLevelIndex >= this.levels.length) {
this.currentLevelIndex = this.levels.length - 1;
} else if (this.currentLevelIndex > index) {
this.currentLevelIndex--;
}
this.renderLevelList();
if (this.currentLevelIndex >= 0) {
this.selectLevel(this.currentLevelIndex);
}
}
moveLevel(index, direction) {
const newIndex = index + direction;
if (newIndex < 0 || newIndex >= this.levels.length) return;
// Swap levels
const temp = this.levels[index];
this.levels[index] = this.levels[newIndex];
this.levels[newIndex] = temp;
// Update selection if we moved the current level
if (this.currentLevelIndex === index) {
this.currentLevelIndex = newIndex;
} else if (this.currentLevelIndex === newIndex) {
this.currentLevelIndex = index;
}
this.renderLevelList();
}
// ============ Editor Rendering ============
renderEditor() {
const container = document.getElementById("editorContent");
if (this.currentLevelIndex < 0) {
container.innerHTML = `
<div class="empty-state">
<p>Select a level from the sidebar to edit, or create a new one.</p>
</div>
`;
return;
}
const level = this.levels[this.currentLevelIndex];
container.innerHTML = `
<!-- Metadata Form -->
<div class="metadata-form">
<div class="form-row">
<div class="form-group wide">
<label for="levelName">Name</label>
<input type="text" id="levelName" value="${this.escapeHtml(level.name)}">
</div>
<div class="form-group">
<label for="levelBpm">BPM</label>
<input type="number" id="levelBpm" min="50" max="500" value="${level.bpm}">
</div>
<div class="form-group">
<label for="levelGroupSize">Group Size</label>
<input type="number" id="levelGroupSize" min="1" max="16" value="${level.groupSize}">
</div>
<div class="form-group">
<label for="levelResolution">Resolution</label>
<select id="levelResolution">
<option value="1" ${level.resolution === 1 ? "selected" : ""}>1 (Quarter notes)</option>
<option value="2" ${level.resolution === 2 ? "selected" : ""}>2 (Eighth notes)</option>
<option value="4" ${(level.resolution === 4 || !level.resolution) ? "selected" : ""}>4 (16th notes)</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group wide">
<label for="levelDescription">Description (optional)</label>
<input type="text" id="levelDescription" value="${this.escapeHtml(level.description || "")}">
</div>
</div>
</div>
<!-- Pattern Editor -->
<div class="pattern-editor">
<h3>Pattern</h3>
<div id="patternTracks">
${this.renderTracks(level)}
</div>
<div class="pattern-controls">
<div class="add-track-container">
<select id="newTrackSelect">
${this.renderInstrumentOptions(level)}
</select>
<button class="pattern-btn" id="addTrackBtn">+ Add Track</button>
</div>
<button class="pattern-btn" id="addStepBtn">+ Add Step</button>
<button class="pattern-btn" id="removeStepBtn">- Remove Step</button>
</div>
</div>
<!-- Actions -->
<div class="editor-actions">
<button class="action-btn preview" id="previewBtn">Preview</button>
<button class="action-btn preview" id="stopBtn" style="display: none;">Stop</button>
</div>
`;
this.bindEditorEvents();
}
renderTracks(level) {
if (!level.pattern || level.pattern.length === 0) {
return '<p class="empty-state">No tracks yet. Add one below.</p>';
}
const groupSize = level.groupSize || 4;
return level.pattern
.map((track, trackIndex) => {
// Group steps into beat groups (no wrapping in editor)
const beatGroups = [];
for (let i = 0; i < track.steps.length; i += groupSize) {
const groupSteps = track.steps.slice(i, i + groupSize);
const groupHtml = `
<div class="editor-beat-group">
${groupSteps
.map(
(step, j) => `
<div class="editor-box ${step ? "active" : ""}"
data-track-index="${trackIndex}"
data-step-index="${i + j}">
</div>
`
)
.join("")}
</div>
`;
beatGroups.push(groupHtml);
}
return `
<div class="editor-track" data-track-index="${trackIndex}">
<select class="track-instrument" data-track-index="${trackIndex}">
${AVAILABLE_INSTRUMENTS.map(
(inst) =>
`<option value="${inst.name}" ${inst.name === track.name ? "selected" : ""}>${inst.name}</option>`
).join("")}
</select>
<div class="editor-boxes">
${beatGroups.join("")}
</div>
<button class="remove-track-btn" data-track-index="${trackIndex}" title="Remove track">×</button>
</div>
`;
})
.join("");
}
renderInstrumentOptions(level) {
const usedInstruments = level.pattern.map((t) => t.name);
return AVAILABLE_INSTRUMENTS.map(
(inst) =>
`<option value="${inst.name}" ${usedInstruments.includes(inst.name) ? "disabled" : ""}>${inst.name}</option>`
).join("");
}
bindEditorEvents() {
const level = this.levels[this.currentLevelIndex];
// Metadata inputs
document.getElementById("levelName").addEventListener("input", (e) => {
this.updateMetadata("name", e.target.value);
});
document.getElementById("levelBpm").addEventListener("input", (e) => {
this.updateMetadata("bpm", parseInt(e.target.value, 10) || 180);
});
document.getElementById("levelGroupSize").addEventListener("input", (e) => {
const value = parseInt(e.target.value, 10) || 4;
this.updateMetadata("groupSize", value);
// Re-render to update group separators
this.renderEditor();
});
document.getElementById("levelResolution").addEventListener("change", (e) => {
this.updateMetadata("resolution", parseInt(e.target.value, 10) || 4);
});
document.getElementById("levelDescription").addEventListener("input", (e) => {
this.updateMetadata("description", e.target.value);
});
// Pattern grid clicks
document.getElementById("patternTracks").addEventListener("click", (e) => {
if (e.target.classList.contains("editor-box")) {
const trackIndex = parseInt(e.target.dataset.trackIndex, 10);
const stepIndex = parseInt(e.target.dataset.stepIndex, 10);
this.toggleStep(trackIndex, stepIndex);
e.target.classList.toggle("active");
}
if (e.target.classList.contains("remove-track-btn")) {
const trackIndex = parseInt(e.target.dataset.trackIndex, 10);
this.removeTrack(trackIndex);
}
});
// Track instrument change
document.getElementById("patternTracks").addEventListener("change", (e) => {
if (e.target.classList.contains("track-instrument")) {
const trackIndex = parseInt(e.target.dataset.trackIndex, 10);
this.changeTrackInstrument(trackIndex, e.target.value);
}
});
// Add track
document.getElementById("addTrackBtn").addEventListener("click", () => {
const select = document.getElementById("newTrackSelect");
const instrumentName = select.value;
if (instrumentName) {
this.addTrack(instrumentName);
}
});
// Add/remove steps
document.getElementById("addStepBtn").addEventListener("click", () => {
this.addStep();
});
document.getElementById("removeStepBtn").addEventListener("click", () => {
this.removeStep();
});
// Preview
document.getElementById("previewBtn").addEventListener("click", () => {
this.previewPattern();
});
document.getElementById("stopBtn").addEventListener("click", () => {
this.stopPreview();
});
}
// ============ Level Editing ============
updateMetadata(field, value) {
if (this.currentLevelIndex < 0) return;
this.levels[this.currentLevelIndex][field] = value;
this.renderLevelList(); // Update name in sidebar
}
toggleStep(trackIndex, stepIndex) {
if (this.currentLevelIndex < 0) return;
const track = this.levels[this.currentLevelIndex].pattern[trackIndex];
track.steps[stepIndex] = track.steps[stepIndex] ? 0 : 1;
// Play sound when enabling
if (track.steps[stepIndex] && this.audioLibrary.ready) {
this.audioLibrary.playSampleAfter(track.name, 0);
}
}
addTrack(instrumentName) {
if (this.currentLevelIndex < 0) return;
const level = this.levels[this.currentLevelIndex];
const numSteps = level.pattern.length > 0 ? level.pattern[0].steps.length : 8;
level.pattern.push({
name: instrumentName,
steps: new Array(numSteps).fill(0),
});
this.renderEditor();
}
removeTrack(trackIndex) {
if (this.currentLevelIndex < 0) return;
const level = this.levels[this.currentLevelIndex];
if (level.pattern.length <= 1) {
alert("Cannot remove the last track.");
return;
}
level.pattern.splice(trackIndex, 1);
this.renderEditor();
}
changeTrackInstrument(trackIndex, newInstrument) {
if (this.currentLevelIndex < 0) return;
this.levels[this.currentLevelIndex].pattern[trackIndex].name = newInstrument;
this.renderEditor();
}
addStep() {
if (this.currentLevelIndex < 0) return;
const level = this.levels[this.currentLevelIndex];
level.pattern.forEach((track) => {
track.steps.push(0);
});
this.renderEditor();
}
removeStep() {
if (this.currentLevelIndex < 0) return;
const level = this.levels[this.currentLevelIndex];
if (level.pattern[0]?.steps.length <= 1) {
alert("Cannot remove the last step.");
return;
}
level.pattern.forEach((track) => {
track.steps.pop();
});
this.renderEditor();
}
// ============ Preview ============
previewPattern() {
if (this.currentLevelIndex < 0 || !this.audioLibrary.ready) return;
if (this.isPlaying) {
this.stopPreview();
return;
}
this.isPlaying = true;
document.getElementById("previewBtn").style.display = "none";
document.getElementById("stopBtn").style.display = "";
const level = this.levels[this.currentLevelIndex];
const startTime = this.audioLibrary.getCurrentTime();
const resolution = level.resolution || 4;
const internalBpm = level.bpm * resolution;
const beatDuration = 60 / internalBpm;
const numSteps = level.pattern[0]?.steps.length || 8;
const barDuration = beatDuration * numSteps;
const repeat = 2;
// Clear any existing classes
document.querySelectorAll(".editor-box.playing").forEach((box) => {
box.classList.remove("playing");
});
for (let currentBar = 0; currentBar < repeat; currentBar++) {
for (let step = 0; step < numSteps; step++) {
const durationSecs = currentBar * barDuration + step * beatDuration;
// Visual cursor update
const timeoutId = setTimeout(() => {
// Remove previous playing state
document.querySelectorAll(".editor-box.playing").forEach((box) => {
box.classList.remove("playing");
});
// Add playing state to current column
document
.querySelectorAll(`.editor-box[data-step-index="${step}"]`)
.forEach((box) => {
box.classList.add("playing");
});
}, durationSecs * 1000);
this.playTimeouts.push(timeoutId);
// Play sounds
level.pattern.forEach((track) => {
if (track.steps[step] === 1) {
this.audioLibrary.playSampleAfter(
track.name,
0.05 + startTime + durationSecs
);
}
});
}
}
// End of playback
const endTimeout = setTimeout(() => {
this.stopPreview();
}, barDuration * repeat * 1000);
this.playTimeouts.push(endTimeout);
}
stopPreview() {
this.isPlaying = false;
// Clear timeouts
this.playTimeouts.forEach((id) => clearTimeout(id));
this.playTimeouts = [];
// Reset audio
if (this.audioLibrary) {
this.audioLibrary.stopAll();
this.audioLibrary.restart();
}
// Reset UI
document.querySelectorAll(".editor-box.playing").forEach((box) => {
box.classList.remove("playing");
});
const previewBtn = document.getElementById("previewBtn");
const stopBtn = document.getElementById("stopBtn");
if (previewBtn) previewBtn.style.display = "";
if (stopBtn) stopBtn.style.display = "none";
}
// ============ Export ============
downloadJSON() {
const json = JSON.stringify(this.levels, null, 2);
const blob = new Blob([json], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "levels.json";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// ============ Utilities ============
escapeHtml(text) {
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}
}
// Initialize editor
const editor = new LevelEditor();