Files
jimmyandClaude Opus 5.5 bfeeb958df feat: main's import/export, zones, audio API and web UI
Profiles, presets and sequences export and import as main's bundles.
Zones carry group_ids, preset_group_ids, sequence_ids, content_kind and
brightness; profiles seed rainbow as colour_cycle, and deleting a
profile also deletes its sequences. Groups, zones and sequences written
by older versions are migrated at boot.

/api/audio (status, event stream, start/stop, reset, anchor-bar,
devices) maps main's audio detector onto the mic's beat detector. Audio
start/stop picks whether mic beats or the BPM clock time sequences; the
clock's beats also go to the drivers while the mic is off.
/ws now greets from a post-handshake callback (httpd does not call the
handler for the upgrade).

The web UI is main's, plus v2's outputs editor, list search and
hostname/static IP settings; the bridge, Wi-Fi AP and led-tool parts
are gone. API tests follow main's behaviour (119 pass on the board).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 20:34:22 +13:00

377 lines
12 KiB
JavaScript

document.addEventListener("DOMContentLoaded", () => {
const profilesButton = document.getElementById("profiles-btn");
const profilesModal = document.getElementById("profiles-modal");
const profilesCloseButton = document.getElementById("profiles-close-btn");
const profilesList = document.getElementById("profiles-list");
const newProfileInput = document.getElementById("new-profile-name");
const newProfileSeedDjInput = document.getElementById("new-profile-seed-dj");
const createProfileButton = document.getElementById("create-profile-btn");
const importProfileButton = document.getElementById("import-profile-btn");
if (!profilesButton || !profilesModal || !profilesList) {
return;
}
const isEditModeActive = () => {
if (typeof window.getPresetUiMode === 'function') {
return window.getPresetUiMode() === 'edit';
}
const toggle = document.querySelector('.ui-mode-toggle');
return !!(toggle && toggle.getAttribute('aria-pressed') === 'true');
};
const updateProfileEditorControlsVisibility = () => {
const editMode = isEditModeActive();
const actions = profilesModal.querySelector('.profiles-actions');
if (actions) {
actions.style.display = editMode ? '' : 'none';
}
};
const openModal = () => {
profilesModal.classList.add("active");
updateProfileEditorControlsVisibility();
loadProfiles();
};
const closeModal = () => {
profilesModal.classList.remove("active");
};
const refreshTabsForActiveProfile = async () => {
// Clear stale current zone so zone controller falls back to first zone of applied profile.
document.cookie = "current_zone=; path=/; max-age=0";
if (window.tabsManager && typeof window.tabsManager.loadTabs === "function") {
await window.tabsManager.loadTabs();
}
if (window.tabsManager && typeof window.tabsManager.loadTabsModal === "function") {
await window.tabsManager.loadTabsModal();
}
};
const renderProfiles = (profiles, currentProfileId) => {
profilesList.innerHTML = "";
let entries = [];
if (Array.isArray(profiles)) {
entries = profiles.map((profileId) => [profileId, {}]);
} else if (profiles && typeof profiles === "object") {
// Make sure we're iterating over profile entries, not metadata
entries = Object.entries(profiles).filter(([key]) => {
// Skip metadata keys like 'current_profile_id' if they exist
return key !== 'current_profile_id' && key !== 'profiles';
});
}
if (entries.length === 0) {
const empty = document.createElement("p");
empty.className = "muted-text";
empty.textContent = "No profiles found.";
profilesList.appendChild(empty);
return;
}
const editMode = isEditModeActive();
entries.forEach(([profileId, profile]) => {
const row = document.createElement("div");
row.className = "profiles-row";
const label = document.createElement("span");
label.textContent = (profile && profile.name) || profileId;
if (String(profileId) === String(currentProfileId)) {
label.textContent = `✓ ${label.textContent}`;
label.style.fontWeight = "bold";
label.style.color = "#FFD700";
}
const applyButton = document.createElement("button");
applyButton.className = "btn btn-secondary btn-small profiles-apply-btn";
applyButton.textContent = "Apply";
applyButton.addEventListener("click", async () => {
try {
const response = await fetch(`/profiles/${profileId}/apply`, {
method: "POST",
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error("Failed to apply profile");
}
await loadProfiles();
await refreshTabsForActiveProfile();
} catch (error) {
console.error("Apply profile failed:", error);
alert("Failed to apply profile.");
}
});
const exportButton = document.createElement("button");
exportButton.className = "btn btn-secondary btn-small";
exportButton.textContent = "Export";
exportButton.addEventListener("click", async () => {
try {
const response = await fetch(`/profiles/${profileId}/export`, {
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error("Export failed");
}
const bundle = await response.json();
const safeName = ((profile && profile.name) || profileId).replace(/[^\w.-]+/g, "_");
window.downloadJsonFile(`profile-${safeName}.json`, bundle);
} catch (error) {
console.error("Export profile failed:", error);
alert("Failed to export profile.");
}
});
const cloneButton = document.createElement("button");
cloneButton.className = "btn btn-secondary btn-small";
cloneButton.textContent = "Clone";
cloneButton.addEventListener("click", async () => {
const baseName = (profile && profile.name) || profileId;
const suggested = `${baseName}`;
const name = prompt("New profile name:", suggested);
if (name === null) {
return;
}
const trimmed = String(name).trim();
if (!trimmed) {
alert("Profile name cannot be empty.");
return;
}
try {
const response = await fetch(`/profiles/${profileId}/clone`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ name: trimmed }),
});
if (!response.ok) {
throw new Error("Failed to clone profile");
}
const data = await response.json().catch(() => null);
let newProfileId = null;
if (data && typeof data === "object") {
if (data.id) {
newProfileId = String(data.id);
} else {
const ids = Object.keys(data);
if (ids.length > 0) {
newProfileId = String(ids[0]);
}
}
}
if (newProfileId) {
await fetch(`/profiles/${newProfileId}/apply`, {
method: "POST",
headers: { Accept: "application/json" },
});
}
await loadProfiles();
await refreshTabsForActiveProfile();
} catch (error) {
console.error("Clone profile failed:", error);
alert("Failed to clone profile.");
}
});
const deleteButton = document.createElement("button");
deleteButton.className = "btn btn-danger btn-small";
deleteButton.textContent = "Delete";
deleteButton.addEventListener("click", async () => {
const confirmed = confirm(`Delete profile "${label.textContent}"?`);
if (!confirmed) {
return;
}
try {
const response = await fetch(`/profiles/${profileId}`, {
method: "DELETE",
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error("Failed to delete profile");
}
await loadProfiles();
} catch (error) {
console.error("Delete profile failed:", error);
alert("Failed to delete profile.");
}
});
row.appendChild(label);
row.appendChild(applyButton);
if (editMode) {
row.appendChild(exportButton);
row.appendChild(cloneButton);
row.appendChild(deleteButton);
}
profilesList.appendChild(row);
});
};
const loadProfiles = async () => {
profilesList.innerHTML = "";
const loading = document.createElement("p");
loading.className = "muted-text";
loading.textContent = "Loading profiles...";
profilesList.appendChild(loading);
try {
const response = await fetch("/profiles", {
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error("Failed to load profiles");
}
const data = await response.json();
// Handle both old format (just profiles object) and new format (with current_profile_id)
const profiles = data.profiles || data;
const currentProfileId = data.current_profile_id || null;
renderProfiles(profiles, currentProfileId);
} catch (error) {
console.error("Load profiles failed:", error);
profilesList.innerHTML = "";
const errorMessage = document.createElement("p");
errorMessage.className = "muted-text";
errorMessage.textContent = "Failed to load profiles.";
profilesList.appendChild(errorMessage);
}
};
const createProfile = async () => {
if (!isEditModeActive()) {
return;
}
if (!newProfileInput) {
return;
}
const name = newProfileInput.value.trim();
if (!name) {
alert("Profile name cannot be empty.");
return;
}
try {
const response = await fetch("/profiles", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
seed_dj_zone: !!(newProfileSeedDjInput && newProfileSeedDjInput.checked),
}),
});
if (!response.ok) {
throw new Error("Failed to create profile");
}
const data = await response.json().catch(() => null);
let newProfileId = null;
if (data && typeof data === "object") {
if (data.id) {
newProfileId = String(data.id);
} else {
const ids = Object.keys(data);
if (ids.length > 0) {
newProfileId = String(ids[0]);
}
}
}
if (newProfileId) {
await fetch(`/profiles/${newProfileId}/apply`, {
method: "POST",
headers: { Accept: "application/json" },
});
}
newProfileInput.value = "";
if (newProfileSeedDjInput) {
newProfileSeedDjInput.checked = false;
}
await loadProfiles();
await refreshTabsForActiveProfile();
} catch (error) {
console.error("Create profile failed:", error);
alert("Failed to create profile.");
}
};
profilesButton.addEventListener("click", openModal);
if (profilesCloseButton) {
profilesCloseButton.addEventListener("click", closeModal);
}
if (createProfileButton) {
createProfileButton.addEventListener("click", createProfile);
}
const importProfile = async () => {
if (!isEditModeActive()) {
return;
}
const text = await window.pickJsonFile();
if (!text) {
return;
}
const bundle = window.parseJsonFileText(text);
if (!bundle || typeof bundle !== "object") {
alert("Invalid JSON file.");
return;
}
const defaultName =
(bundle.profile && bundle.profile.name) || "Imported profile";
const name = prompt("Profile name for import:", defaultName);
if (name === null) {
return;
}
const trimmed = String(name).trim();
if (!trimmed) {
alert("Profile name cannot be empty.");
return;
}
try {
const response = await fetch("/profiles/import", {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ bundle, name: trimmed, apply: true }),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err.error || "Import failed");
}
const data = await response.json();
const newProfileId = data.id || Object.keys(data).find((k) => k !== "id");
if (newProfileId) {
await fetch(`/profiles/${newProfileId}/apply`, {
method: "POST",
headers: { Accept: "application/json" },
});
}
await loadProfiles();
await refreshTabsForActiveProfile();
} catch (error) {
console.error("Import profile failed:", error);
alert(error.message || "Failed to import profile.");
}
};
if (importProfileButton) {
importProfileButton.addEventListener("click", importProfile);
}
if (newProfileInput) {
newProfileInput.addEventListener("keypress", (event) => {
if (event.key === "Enter") {
createProfile();
}
});
}
// Keep modal controls in sync with run/edit mode.
document.querySelectorAll('.ui-mode-toggle').forEach((btn) => {
btn.addEventListener('click', () => {
if (profilesModal.classList.contains('active')) {
updateProfileEditorControlsVisibility();
loadProfiles();
}
});
});
});