Files
bellsystems-cp/frontend/src/melodies/MelodyDetail.jsx

471 lines
17 KiB
JavaScript

import { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import api from "../api/client";
import { useAuth } from "../auth/AuthContext";
import ConfirmDialog from "../components/ConfirmDialog";
import SpeedCalculatorModal from "./SpeedCalculatorModal";
import {
getLocalizedValue,
getLanguageName,
normalizeColor,
formatDuration,
} from "./melodyUtils";
function Field({ label, children }) {
return (
<div>
<dt className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>
{label}
</dt>
<dd className="mt-1 text-sm" style={{ color: "var(--text-primary)" }}>{children || "-"}</dd>
</div>
);
}
export default function MelodyDetail() {
const { id } = useParams();
const navigate = useNavigate();
const { hasPermission } = useAuth();
const canEdit = hasPermission("melodies", "edit");
const [melody, setMelody] = useState(null);
const [files, setFiles] = useState({});
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [showDelete, setShowDelete] = useState(false);
const [showUnpublish, setShowUnpublish] = useState(false);
const [actionLoading, setActionLoading] = useState(false);
const [displayLang, setDisplayLang] = useState("en");
const [melodySettings, setMelodySettings] = useState(null);
const [builtMelody, setBuiltMelody] = useState(null);
const [codeCopied, setCodeCopied] = useState(false);
const [showSpeedCalc, setShowSpeedCalc] = useState(false);
useEffect(() => {
api.get("/settings/melody").then((ms) => {
setMelodySettings(ms);
setDisplayLang(ms.primary_language || "en");
});
}, []);
useEffect(() => {
loadData();
}, [id]);
const loadData = async () => {
setLoading(true);
try {
const [m, f] = await Promise.all([
api.get(`/melodies/${id}`),
api.get(`/melodies/${id}/files`),
]);
setMelody(m);
setFiles(f);
// Load built melody assignment (non-fatal if it fails)
try {
const bm = await api.get(`/builder/melodies/for-melody/${id}`);
setBuiltMelody(bm || null);
} catch {
setBuiltMelody(null);
}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
const handleDelete = async () => {
try {
await api.delete(`/melodies/${id}`);
navigate("/melodies");
} catch (err) {
setError(err.message);
setShowDelete(false);
}
};
const handlePublish = async () => {
setActionLoading(true);
try {
await api.post(`/melodies/${id}/publish`);
await loadData();
} catch (err) {
setError(err.message);
} finally {
setActionLoading(false);
}
};
const handleUnpublish = async () => {
setActionLoading(true);
try {
await api.post(`/melodies/${id}/unpublish`);
setShowUnpublish(false);
await loadData();
} catch (err) {
setError(err.message);
setShowUnpublish(false);
} finally {
setActionLoading(false);
}
};
if (loading) {
return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
}
if (error) {
return (
<div
className="text-sm rounded-md p-3 border"
style={{
backgroundColor: "var(--danger-bg)",
borderColor: "var(--danger)",
color: "var(--danger-text)",
}}
>
{error}
</div>
);
}
if (!melody) return null;
const info = melody.information || {};
const settings = melody.default_settings || {};
const languages = melodySettings?.available_languages || ["en"];
const displayName = getLocalizedValue(info.name, displayLang, "Untitled Melody");
const badgeStyle = (active) => ({
backgroundColor: active ? "var(--success-bg)" : "var(--bg-card-hover)",
color: active ? "var(--success-text)" : "var(--text-muted)",
});
return (
<div>
<div className="flex items-center justify-between mb-6">
<div>
<button
onClick={() => navigate("/melodies")}
className="text-sm mb-2 inline-block"
style={{ color: "var(--accent)" }}
>
&larr; Back to Melodies
</button>
<div className="flex items-center gap-3">
<h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>{displayName}</h1>
<span
className="px-2.5 py-0.5 text-xs font-semibold rounded-full"
style={melody.status === "published"
? { backgroundColor: "rgba(22,163,74,0.15)", color: "#22c55e" }
: { backgroundColor: "rgba(156,163,175,0.15)", color: "#9ca3af" }
}
>
{melody.status === "published" ? "LIVE" : "DRAFT"}
</span>
{languages.length > 1 && (
<select
value={displayLang}
onChange={(e) => setDisplayLang(e.target.value)}
className="text-xs px-2 py-1 rounded border"
>
{languages.map((l) => (
<option key={l} value={l}>
{getLanguageName(l)}
</option>
))}
</select>
)}
</div>
</div>
{canEdit && (
<div className="flex gap-2">
{melody.status === "draft" ? (
<button
onClick={handlePublish}
disabled={actionLoading}
className="px-4 py-2 text-sm rounded-md transition-colors disabled:opacity-50"
style={{ backgroundColor: "#16a34a", color: "#fff" }}
>
{actionLoading ? "Publishing..." : "Publish"}
</button>
) : (
<button
onClick={() => setShowUnpublish(true)}
disabled={actionLoading}
className="px-4 py-2 text-sm rounded-md transition-colors disabled:opacity-50"
style={{ backgroundColor: "#ea580c", color: "#fff" }}
>
Unpublish
</button>
)}
<button
onClick={() => setShowSpeedCalc(true)}
className="px-4 py-2 text-sm rounded-md transition-colors"
style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-primary)", border: "1px solid var(--border-primary)" }}
>
Speed Calculator
</button>
<button
onClick={() => navigate(`/melodies/${id}/edit`)}
className="px-4 py-2 text-sm rounded-md transition-colors"
style={{ backgroundColor: "var(--text-link)", color: "var(--text-white)" }}
>
Edit
</button>
<button
onClick={() => setShowDelete(true)}
className="px-4 py-2 text-sm rounded-md transition-colors"
style={{ backgroundColor: "var(--danger-btn)", color: "var(--text-white)" }}
>
Delete
</button>
</div>
)}
</div>
<div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
{/* Left column */}
<div className="space-y-6">
{/* Melody Information */}
<section
className="rounded-lg p-6 border"
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
>
<h2 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>
Melody Information
</h2>
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
<Field label="Type">
<span className="capitalize">{melody.type}</span>
</Field>
<Field label="Tone">
<span className="capitalize">{info.melodyTone}</span>
</Field>
<Field label="Steps">{info.steps}</Field>
<Field label="Total Active Notes (bells)">{info.totalNotes}</Field>
<Field label="Min Speed">{info.minSpeed}</Field>
<Field label="Max Speed">{info.maxSpeed}</Field>
<Field label="Color">
{info.color ? (
<span className="inline-flex items-center gap-2">
<span
className="w-4 h-4 rounded inline-block border"
style={{ backgroundColor: normalizeColor(info.color), borderColor: "var(--border-primary)" }}
/>
{info.color}
</span>
) : (
"-"
)}
</Field>
<Field label="True Ring">
<span className="px-2 py-0.5 text-xs rounded-full" style={badgeStyle(info.isTrueRing)}>
{info.isTrueRing ? "Yes" : "No"}
</span>
</Field>
<div className="col-span-2 md:col-span-3">
<Field label="Description">
{getLocalizedValue(info.description, displayLang)}
</Field>
</div>
<div className="col-span-2 md:col-span-3">
<Field label="Custom Tags">
{info.customTags?.length > 0 ? (
<div className="flex flex-wrap gap-1 mt-1">
{info.customTags.map((tag) => (
<span
key={tag}
className="px-2 py-0.5 text-xs rounded-full"
style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}
>
{tag}
</span>
))}
</div>
) : (
"-"
)}
</Field>
</div>
</dl>
</section>
{/* Identifiers */}
<section
className="rounded-lg p-6 border"
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
>
<h2 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>
Identifiers
</h2>
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
<Field label="Document ID">{melody.id}</Field>
<Field label="PID (Playback ID)">{melody.pid}</Field>
<Field label="UID">{melody.uid}</Field>
<div className="col-span-2 md:col-span-3">
<Field label="URL">{melody.url}</Field>
</div>
</dl>
</section>
</div>
{/* Right column */}
<div className="space-y-6">
{/* Default Settings */}
<section
className="rounded-lg p-6 border"
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
>
<h2 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>
Default Settings
</h2>
<dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
<Field label="Speed">{settings.speed}%</Field>
<Field label="Duration">{formatDuration(settings.duration)}</Field>
<Field label="Total Run Duration">{settings.totalRunDuration}</Field>
<Field label="Pause Duration">{settings.pauseDuration}</Field>
<Field label="Infinite Loop">
<span className="px-2 py-0.5 text-xs rounded-full" style={badgeStyle(settings.infiniteLoop)}>
{settings.infiniteLoop ? "Yes" : "No"}
</span>
</Field>
<div className="col-span-2 md:col-span-3">
<Field label="Echo Ring">
{settings.echoRing?.length > 0
? settings.echoRing.join(", ")
: "-"}
</Field>
</div>
<div className="col-span-2 md:col-span-3">
<Field label="Note Assignments">
{settings.noteAssignments?.length > 0
? settings.noteAssignments.join(", ")
: "-"}
</Field>
</div>
</dl>
</section>
{/* Files */}
<section
className="rounded-lg p-6 border"
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
>
<h2 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>Files</h2>
<dl className="space-y-4">
<Field label="Binary File">
{files.binary_url ? (
<a
href={files.binary_url}
target="_blank"
rel="noopener noreferrer"
className="underline"
style={{ color: "var(--accent)" }}
>
Download binary
</a>
) : (
<span style={{ color: "var(--text-muted)" }}>Not uploaded</span>
)}
</Field>
<Field label="Audio Preview">
{files.preview_url ? (
<div className="space-y-1">
<audio controls src={files.preview_url} className="h-8" />
<a
href={files.preview_url}
target="_blank"
rel="noopener noreferrer"
className="underline text-xs"
style={{ color: "var(--accent)" }}
>
Download preview
</a>
</div>
) : (
<span style={{ color: "var(--text-muted)" }}>Not uploaded</span>
)}
</Field>
</dl>
</section>
</div>
</div>
{/* Firmware Code section — only shown if a built melody with PROGMEM code is assigned */}
{builtMelody?.progmem_code && (
<section
className="rounded-lg p-6 border mt-6"
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
>
<div className="flex items-center justify-between mb-3">
<div>
<h2 className="text-lg font-semibold" style={{ color: "var(--text-heading)" }}>Firmware Code</h2>
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
PROGMEM code for built-in firmware playback &nbsp;·&nbsp; PID: <span className="font-mono">{builtMelody.pid}</span>
</p>
</div>
<button
onClick={() => {
navigator.clipboard.writeText(builtMelody.progmem_code).then(() => {
setCodeCopied(true);
setTimeout(() => setCodeCopied(false), 2000);
});
}}
className="px-3 py-1.5 text-xs rounded transition-colors"
style={{
backgroundColor: codeCopied ? "var(--success-bg)" : "var(--bg-card-hover)",
color: codeCopied ? "var(--success-text)" : "var(--text-secondary)",
border: "1px solid var(--border-primary)",
}}
>
{codeCopied ? "Copied!" : "Copy Code"}
</button>
</div>
<pre
className="p-4 text-xs overflow-x-auto rounded-lg"
style={{
backgroundColor: "var(--bg-primary)",
color: "var(--text-primary)",
fontFamily: "monospace",
whiteSpace: "pre",
maxHeight: "360px",
overflowY: "auto",
border: "1px solid var(--border-primary)",
}}
>
{builtMelody.progmem_code}
</pre>
</section>
)}
<SpeedCalculatorModal
open={showSpeedCalc}
melody={melody}
onClose={() => setShowSpeedCalc(false)}
onSaved={() => {
setShowSpeedCalc(false);
loadData();
}}
/>
<ConfirmDialog
open={showDelete}
title="Delete Melody"
message={`Are you sure you want to delete "${displayName}"? This will also delete any uploaded files. This action cannot be undone.`}
onConfirm={handleDelete}
onCancel={() => setShowDelete(false)}
/>
<ConfirmDialog
open={showUnpublish}
title="Unpublish Melody"
message={`This melody may be in use by devices. Unpublishing will remove it from Firestore and devices will no longer have access to "${displayName}". The melody will be kept as a draft. Continue?`}
onConfirm={handleUnpublish}
onCancel={() => setShowUnpublish(false)}
/>
</div>
);
}