-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscreen.js
More file actions
333 lines (302 loc) · 12.5 KB
/
Copy pathscreen.js
File metadata and controls
333 lines (302 loc) · 12.5 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
// Drum School — lesson hub controller.
//
// Renders the curriculum grid, manages household profiles, launches lesson
// feedpaks via window.playSong, and records progress when a lesson run
// finishes (rating overlay on song:ended; auto-filled when a drum scorer
// reports accuracy via the `drum_school:score` event — see README).
(function () {
'use strict';
const API = '/api/plugins/drum_school';
const UNLOCK_ALL_KEY = 'drum_school_unlock_all';
// Plugin event bus: the platform rename (Slopsmith -> feedBack) moved the
// JS global from window.slopsmith to window.feedBack. Prefer the new name,
// fall back to the legacy one so the plugin runs on older installs too.
const bus = window.feedBack || window.slopsmith;
if (!bus) {
console.warn('[drum_school] no plugin event bus (window.feedBack) — host too old?');
return;
}
let status = null; // GET /status payload
let progress = null; // GET /profiles payload
let activeLesson = null; // lesson meta while one is playing
let lastScore = null; // accuracy pushed by a scorer plugin, if any
let pollTimer = null;
const $ = (id) => document.getElementById(id);
async function fetchJson(url, opts) {
const resp = await fetch(url, opts);
if (!resp.ok) throw new Error(`${url} -> HTTP ${resp.status}`);
return resp.json();
}
async function refresh() {
try {
[status, progress] = await Promise.all([
fetchJson(`${API}/status`),
fetchJson(`${API}/profiles`),
]);
} catch (e) {
console.warn('[drum_school] refresh failed:', e);
return;
}
render();
// Poll while the pack is building so the banner live-updates.
if (status.install && status.install.state === 'building') {
clearTimeout(pollTimer);
pollTimer = setTimeout(refresh, 2000);
}
}
// ── Profiles ──────────────────────────────────────────────────────────
function activeProfile() {
return progress && progress.active ? progress.profiles[progress.active] : null;
}
async function postProfiles(body) {
const out = await fetchJson(`${API}/profiles`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (out.ok === false) {
alert(out.error || 'That did not work.');
} else {
progress = out;
render();
}
return out;
}
function renderProfiles() {
const host = $('ds-profiles');
if (!host) return;
host.innerHTML = '';
const names = progress ? Object.keys(progress.profiles) : [];
names.forEach((name) => {
const chip = document.createElement('button');
chip.className = 'ds-profile-chip px-3 py-1.5 rounded-full bg-dark-600 text-sm text-gray-300 hover:bg-dark-500'
+ (progress.active === name ? ' active' : '');
chip.textContent = name;
chip.onclick = () => postProfiles({ action: 'select', name });
host.appendChild(chip);
});
const add = document.createElement('button');
add.className = 'px-3 py-1.5 rounded-full bg-dark-700 text-sm text-gray-400 hover:bg-dark-500 border border-dashed border-dark-400';
add.textContent = '+ add drummer';
add.onclick = async () => {
const name = prompt('Name for the new drummer:');
if (name && name.trim()) await postProfiles({ action: 'create', name: name.trim() });
};
host.appendChild(add);
}
// ── Curriculum grid ───────────────────────────────────────────────────
function lessonProgress(lessonId) {
const prof = activeProfile();
return (prof && prof.lessons && prof.lessons[lessonId]) || null;
}
function unlocked(lesson) {
if (localStorage.getItem(UNLOCK_ALL_KEY) === '1') return true;
if (lesson.index === 0) return true;
const prev = status.lessons[lesson.index - 1];
const p = lessonProgress(prev.id);
return !!(p && p.stars >= 1);
}
function stars(n) {
let out = '';
for (let i = 1; i <= 3; i++) out += `<span class="ds-star${i <= n ? ' on' : ''}">★</span>`;
return out;
}
function fmtDuration(s) {
const m = Math.floor(s / 60), r = Math.round(s % 60);
return `${m}:${String(r).padStart(2, '0')}`;
}
function renderBanner() {
const banner = $('ds-banner');
if (!banner || !status) return;
banner.classList.add('hidden');
const inst = status.install || {};
if (!status.dlc_configured) {
banner.innerHTML = 'Set your <strong>DLC folder</strong> in Settings first — lesson tracks are installed there.';
banner.classList.remove('hidden');
} else if (!status.ffmpeg) {
banner.innerHTML = 'ffmpeg was not found on the server, so lesson audio cannot be generated.';
banner.classList.remove('hidden');
} else if (inst.state === 'building') {
banner.innerHTML = `Building lesson tracks… ${inst.built}/${inst.total}. They appear below as soon as the pack is ready.`;
banner.classList.remove('hidden');
} else if (inst.state === 'error') {
banner.innerHTML = `Lesson install failed: ${inst.error || 'unknown error'} <button id="ds-retry-install" class="ml-2 underline">Retry</button>`;
banner.classList.remove('hidden');
} else if (!status.installed) {
banner.innerHTML = 'Lesson tracks are not installed yet. <button id="ds-install" class="ml-2 px-3 py-1 rounded bg-accent text-white">Install lessons</button>';
banner.classList.remove('hidden');
}
const installBtn = $('ds-install') || $('ds-retry-install');
if (installBtn) {
installBtn.onclick = async () => {
await fetchJson(`${API}/install`, { method: 'POST' });
refresh();
};
}
}
function renderLevels() {
const host = $('ds-levels');
if (!host || !status) return;
host.innerHTML = '';
const levelColors = { 1: '#4ade80', 2: '#22d3ee', 3: '#e8c040', 4: '#f97316', 5: '#ef4444' };
const byLevel = new Map();
status.lessons.forEach((l) => {
if (!byLevel.has(l.level)) byLevel.set(l.level, []);
byLevel.get(l.level).push(l);
});
for (const [level, lessons] of byLevel) {
const section = document.createElement('div');
section.className = 'mb-8';
section.innerHTML = `
<h2 class="text-lg font-semibold text-white mb-3">
<span class="ds-level-dot" style="background:${levelColors[level] || '#9ca3af'}"></span>
Level ${level} — ${status.levels[level] || ''}
</h2>
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"></div>`;
const grid = section.querySelector('.grid');
lessons.forEach((lesson) => {
const prog = lessonProgress(lesson.id);
const isUnlocked = unlocked(lesson);
const playable = status.installed && isUnlocked;
const card = document.createElement('div');
card.className = 'ds-card rounded-xl bg-dark-600 border border-dark-500 p-4'
+ (playable ? ' playable' : '') + (isUnlocked ? '' : ' locked');
card.innerHTML = `
<div class="flex items-start justify-between">
<div class="text-xs text-gray-500">${lesson.id.slice(0, 2)} · ${lesson.bpm} BPM · ${fmtDuration(lesson.duration)}</div>
<div>${isUnlocked ? stars(prog ? prog.stars : 0) : '🔒'}</div>
</div>
<div class="text-white font-semibold mt-1">${lesson.title}</div>
<div class="text-xs text-gray-400 mt-1 leading-relaxed">${lesson.blurb}</div>
<div class="mt-2 flex flex-wrap gap-1">
${lesson.skills.map((s) => `<span class="text-xs px-2 py-0.5 rounded-full bg-dark-700 text-gray-400">${s}</span>`).join('')}
</div>`;
if (playable) card.onclick = () => playLesson(lesson);
grid.appendChild(card);
});
host.appendChild(section);
}
}
function render() {
renderProfiles();
renderBanner();
renderLevels();
}
// ── Playing + completion ──────────────────────────────────────────────
async function playLesson(lesson) {
if (!progress || !progress.active) {
const name = prompt('Who is drumming? Enter a name to track progress:');
if (name && name.trim()) {
const out = await postProfiles({ action: 'create', name: name.trim() });
if (out.ok === false) return;
} else {
return; // no profile, no tracked run
}
}
activeLesson = lesson;
lastScore = null;
const filename = status.play_prefix + lesson.file;
try {
await window.playSong(filename, 0);
} catch (e) {
console.warn('[drum_school] playSong failed:', e);
activeLesson = null;
}
}
function openCompleteOverlay() {
const overlay = $('ds-complete-overlay');
if (!overlay || !activeLesson) return;
$('ds-complete-title').textContent = `${activeLesson.title} — done!`;
$('ds-complete-sub').textContent = lastScore != null
? `Your kit scored this run at ${Math.round(lastScore)}%. Lock it in?`
: 'How did that run feel? (1 = made it through, 3 = nailed it)';
overlay.querySelectorAll('.ds-big-star').forEach((el) => el.classList.remove('lit'));
if (lastScore != null) {
const auto = lastScore >= 92 ? 3 : lastScore >= 75 ? 2 : 1;
overlay.querySelectorAll('.ds-big-star').forEach((el) => {
if (Number(el.dataset.stars) <= auto) el.classList.add('lit');
});
}
overlay.classList.add('open');
}
function closeCompleteOverlay() {
const overlay = $('ds-complete-overlay');
if (overlay) overlay.classList.remove('open');
}
async function recordRun(starsEarned) {
if (!activeLesson) return;
const body = { action: 'record', lesson: activeLesson.id, stars: starsEarned };
if (lastScore != null) body.accuracy = lastScore;
activeLesson = null;
closeCompleteOverlay();
await postProfiles(body);
}
function wireOverlay() {
const overlay = $('ds-complete-overlay');
if (!overlay) return;
overlay.querySelectorAll('.ds-big-star').forEach((el) => {
el.addEventListener('click', () => recordRun(Number(el.dataset.stars)));
el.addEventListener('mouseenter', () => {
const n = Number(el.dataset.stars);
overlay.querySelectorAll('.ds-big-star').forEach((s) => {
s.classList.toggle('lit', Number(s.dataset.stars) <= n);
});
});
});
$('ds-complete-skip').addEventListener('click', () => {
activeLesson = null;
closeCompleteOverlay();
});
$('ds-complete-retry').addEventListener('click', () => {
const lesson = activeLesson;
closeCompleteOverlay();
if (lesson) playLesson(lesson);
});
}
// A drum-scoring plugin (e.g. feedBack-plugin-drums) can report a run's
// accuracy so the rating pre-fills:
// window.feedBack.emit('drum_school:score', { accuracy: 0-100 })
bus.on('drum_school:score', (event) => {
const detail = event.detail || {};
if (typeof detail.accuracy === 'number') lastScore = detail.accuracy;
});
bus.on('song:ended', () => {
if (activeLesson) openCompleteOverlay();
});
bus.on('song:stop', () => {
// Bailed out early (back to library, next song…) — not a completed run.
if (activeLesson && !$('ds-complete-overlay').classList.contains('open')) {
activeLesson = null;
}
});
// Settings panel wiring (settings.html is injected into the Settings
// screen; delegate so it works whenever that DOM appears).
document.addEventListener('change', (e) => {
if (e.target && e.target.id === 'ds-unlock-all') {
localStorage.setItem(UNLOCK_ALL_KEY, e.target.checked ? '1' : '0');
render();
}
});
document.addEventListener('click', async (e) => {
if (e.target && e.target.id === 'ds-reset-progress') {
if (confirm('Really wipe ALL Drum School profiles and progress?')) {
await postProfiles({ action: 'reset_all' });
}
}
});
// Refresh whenever the user lands on our screen.
const origShowScreen = window.showScreen;
if (typeof origShowScreen === 'function') {
window.showScreen = function (name, ...rest) {
const out = origShowScreen.call(this, name, ...rest);
if (name === 'plugin-drum_school') refresh();
const unlockAll = document.getElementById('ds-unlock-all');
if (name === 'settings' && unlockAll) {
unlockAll.checked = localStorage.getItem(UNLOCK_ALL_KEY) === '1';
}
return out;
};
}
wireOverlay();
refresh();
})();