CODEX - Added modal colours for the Bells

This commit is contained in:
2026-02-23 19:20:30 +02:00
parent a46e296dc3
commit cd218a55fe
6 changed files with 246 additions and 10 deletions

View File

@@ -1,11 +1,19 @@
from pydantic import BaseModel from pydantic import BaseModel
from typing import List, Optional from typing import List, Optional
DEFAULT_NOTE_ASSIGNMENT_COLORS: List[str] = [
"#67E8F9", "#5EEAD4", "#6EE7B7", "#86EFAC",
"#BEF264", "#FDE68A", "#FCD34D", "#FBBF24",
"#FDBA74", "#FB923C", "#F97316", "#FB7185",
"#F87171", "#EF4444", "#DC2626", "#B91C1C",
]
class MelodySettings(BaseModel): class MelodySettings(BaseModel):
available_languages: List[str] = ["en", "el", "sr"] available_languages: List[str] = ["en", "el", "sr"]
primary_language: str = "en" primary_language: str = "en"
quick_colors: List[str] = ["#FF5733", "#33FF57", "#3357FF", "#FFD700", "#FF69B4", "#8B4513"] quick_colors: List[str] = ["#FF5733", "#33FF57", "#3357FF", "#FFD700", "#FF69B4", "#8B4513"]
note_assignment_colors: List[str] = DEFAULT_NOTE_ASSIGNMENT_COLORS
duration_values: List[int] = [ duration_values: List[int] = [
0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
240, 300, 360, 420, 480, 540, 600, 900, 240, 300, 360, 420, 480, 540, 600, 900,
@@ -16,4 +24,5 @@ class MelodySettingsUpdate(BaseModel):
available_languages: Optional[List[str]] = None available_languages: Optional[List[str]] = None
primary_language: Optional[str] = None primary_language: Optional[str] = None
quick_colors: Optional[List[str]] = None quick_colors: Optional[List[str]] = None
note_assignment_colors: Optional[List[str]] = None
duration_values: Optional[List[int]] = None duration_values: Optional[List[int]] = None

View File

@@ -10,7 +10,10 @@ def get_melody_settings() -> MelodySettings:
db = get_db() db = get_db()
doc = db.collection(COLLECTION).document(DOC_ID).get() doc = db.collection(COLLECTION).document(DOC_ID).get()
if doc.exists: if doc.exists:
return MelodySettings(**doc.to_dict()) settings = MelodySettings(**doc.to_dict())
# Backfill newly introduced defaults into stored settings.
db.collection(COLLECTION).document(DOC_ID).set(settings.model_dump())
return settings
# Create with defaults # Create with defaults
defaults = MelodySettings() defaults = MelodySettings()
db.collection(COLLECTION).document(DOC_ID).set(defaults.model_dump()) db.collection(COLLECTION).document(DOC_ID).set(defaults.model_dump())
@@ -35,5 +38,6 @@ def update_melody_settings(data: MelodySettingsUpdate) -> MelodySettings:
if "duration_values" in existing: if "duration_values" in existing:
existing["duration_values"] = sorted(existing["duration_values"]) existing["duration_values"] = sorted(existing["duration_values"])
doc_ref.set(existing) normalized = MelodySettings(**existing)
return MelodySettings(**existing) doc_ref.set(normalized.model_dump())
return normalized

View File

@@ -1,4 +1,5 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import api from "../api/client";
const NOTE_LABELS = "ABCDEFGHIJKLMNOP"; const NOTE_LABELS = "ABCDEFGHIJKLMNOP";
@@ -51,6 +52,18 @@ function noteDotGlow(noteNumber) {
return `hsla(${hue}, 78%, 56%, 0.45)`; return `hsla(${hue}, 78%, 56%, 0.45)`;
} }
function noteDotColorFromSettings(noteNumber, colorPalette) {
const n = Number(noteNumber || 1);
const custom = colorPalette?.[n - 1];
return custom || noteDotColor(n);
}
function noteDotGlowFromSettings(noteNumber, colorPalette) {
const n = Number(noteNumber || 1);
const custom = colorPalette?.[n - 1];
return custom ? `${custom}66` : noteDotGlow(n);
}
function normalizeFileUrl(url) { function normalizeFileUrl(url) {
if (!url || typeof url !== "string") return null; if (!url || typeof url !== "string") return null;
if (url.startsWith("http") || url.startsWith("/api")) return url; if (url.startsWith("http") || url.startsWith("/api")) return url;
@@ -97,6 +110,7 @@ export default function BinaryTableModal({ open, melody, builtMelody, files, arc
const [steps, setSteps] = useState([]); const [steps, setSteps] = useState([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState(""); const [error, setError] = useState("");
const [noteColors, setNoteColors] = useState([]);
useEffect(() => { useEffect(() => {
if (!open) { if (!open) {
@@ -138,6 +152,20 @@ export default function BinaryTableModal({ open, melody, builtMelody, files, arc
setError("No binary or archetype data available for this melody."); setError("No binary or archetype data available for this melody.");
}, [open]); // eslint-disable-line react-hooks/exhaustive-deps }, [open]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!open) return;
let canceled = false;
api.get("/settings/melody")
.then((s) => {
if (canceled) return;
setNoteColors((s?.note_assignment_colors || []).slice(0, 16));
})
.catch(() => {
if (!canceled) setNoteColors([]);
});
return () => { canceled = true; };
}, [open]);
if (!open) return null; if (!open) return null;
const detectedNoteCount = steps.reduce((max, stepValue) => { const detectedNoteCount = steps.reduce((max, stepValue) => {
@@ -226,10 +254,10 @@ export default function BinaryTableModal({ open, melody, builtMelody, files, arc
width: "60%", width: "60%",
height: "60%", height: "60%",
borderRadius: "9999px", borderRadius: "9999px",
backgroundColor: noteDotColor(noteIdx + 1), backgroundColor: noteDotColorFromSettings(noteIdx + 1, noteColors),
opacity: enabled ? 1 : 0, opacity: enabled ? 1 : 0,
transform: enabled ? "scale(1)" : "scale(0.4)", transform: enabled ? "scale(1)" : "scale(0.4)",
boxShadow: enabled ? `0 0 10px 3px ${noteDotGlow(noteIdx + 1)}` : "none", boxShadow: enabled ? `0 0 10px 3px ${noteDotGlowFromSettings(noteIdx + 1, noteColors)}` : "none",
transition: "opacity 140ms ease, transform 140ms ease, box-shadow 180ms ease", transition: "opacity 140ms ease, transform 140ms ease, box-shadow 180ms ease",
}} }}
/> />

View File

@@ -55,6 +55,18 @@ function noteDotGlow(noteNumber) {
return `hsla(${hue}, 78%, 56%, 0.45)`; return `hsla(${hue}, 78%, 56%, 0.45)`;
} }
function noteDotColorFromSettings(noteNumber, colorPalette) {
const n = Number(noteNumber || 1);
const custom = colorPalette?.[n - 1];
return custom || noteDotColor(n);
}
function noteDotGlowFromSettings(noteNumber, colorPalette) {
const n = Number(noteNumber || 1);
const custom = colorPalette?.[n - 1];
return custom ? `${custom}66` : noteDotGlow(n);
}
function playStep(audioCtx, stepValue, noteDurationMs) { function playStep(audioCtx, stepValue, noteDurationMs) {
if (!audioCtx) return; if (!audioCtx) return;
@@ -101,6 +113,7 @@ export default function MelodyComposer() {
const [deployPid, setDeployPid] = useState(""); const [deployPid, setDeployPid] = useState("");
const [deployError, setDeployError] = useState(""); const [deployError, setDeployError] = useState("");
const [deploying, setDeploying] = useState(false); const [deploying, setDeploying] = useState(false);
const [noteColors, setNoteColors] = useState([]);
const audioCtxRef = useRef(null); const audioCtxRef = useRef(null);
const playbackRef = useRef(null); const playbackRef = useRef(null);
@@ -181,6 +194,19 @@ export default function MelodyComposer() {
}; };
}, [stopPlayback]); }, [stopPlayback]);
useEffect(() => {
let canceled = false;
api.get("/settings/melody")
.then((s) => {
if (canceled) return;
setNoteColors((s?.note_assignment_colors || []).slice(0, 16));
})
.catch(() => {
if (!canceled) setNoteColors([]);
});
return () => { canceled = true; };
}, []);
const toggleCell = (noteIndex, stepIndex) => { const toggleCell = (noteIndex, stepIndex) => {
const bit = 1 << noteIndex; const bit = 1 << noteIndex;
setSteps((prev) => { setSteps((prev) => {
@@ -560,10 +586,10 @@ export default function MelodyComposer() {
width: "54%", width: "54%",
height: "54%", height: "54%",
borderRadius: "9999px", borderRadius: "9999px",
backgroundColor: noteDotColor(noteIndex + 1), backgroundColor: noteDotColorFromSettings(noteIndex + 1, noteColors),
opacity: enabled ? 1 : 0, opacity: enabled ? 1 : 0,
transform: enabled ? "scale(1)" : "scale(0.4)", transform: enabled ? "scale(1)" : "scale(0.4)",
boxShadow: enabled ? `0 0 10px 3px ${noteDotGlow(noteIndex + 1)}` : "none", boxShadow: enabled ? `0 0 10px 3px ${noteDotGlowFromSettings(noteIndex + 1, noteColors)}` : "none",
transition: "opacity 140ms ease, transform 140ms ease, box-shadow 180ms ease", transition: "opacity 140ms ease, transform 140ms ease, box-shadow 180ms ease",
}} }}
/> />

View File

@@ -7,6 +7,13 @@ import {
normalizeColor, normalizeColor,
} from "./melodyUtils"; } from "./melodyUtils";
const DEFAULT_NOTE_ASSIGNMENT_COLORS = [
"#67E8F9", "#5EEAD4", "#6EE7B7", "#86EFAC",
"#BEF264", "#FDE68A", "#FCD34D", "#FBBF24",
"#FDBA74", "#FB923C", "#F97316", "#FB7185",
"#F87171", "#EF4444", "#DC2626", "#B91C1C",
];
const sectionStyle = { const sectionStyle = {
backgroundColor: "var(--bg-card)", backgroundColor: "var(--bg-card)",
borderColor: "var(--border-primary)", borderColor: "var(--border-primary)",
@@ -29,6 +36,9 @@ export default function MelodySettings() {
const [colorToAdd, setColorToAdd] = useState(cssColorDefault); const [colorToAdd, setColorToAdd] = useState(cssColorDefault);
const [colorHexInput, setColorHexInput] = useState(cssColorDefault); const [colorHexInput, setColorHexInput] = useState(cssColorDefault);
const [durationToAdd, setDurationToAdd] = useState(""); const [durationToAdd, setDurationToAdd] = useState("");
const [colorModalBell, setColorModalBell] = useState(null);
const [modalColor, setModalColor] = useState("#67E8F9");
const [modalColorInput, setModalColorInput] = useState("#67E8F9");
useEffect(() => { useEffect(() => {
loadSettings(); loadSettings();
@@ -38,7 +48,10 @@ export default function MelodySettings() {
setLoading(true); setLoading(true);
try { try {
const data = await api.get("/settings/melody"); const data = await api.get("/settings/melody");
setSettings(data); setSettings({
...data,
note_assignment_colors: (data.note_assignment_colors || DEFAULT_NOTE_ASSIGNMENT_COLORS).slice(0, 16),
});
} catch (err) { } catch (err) {
setError(err.message); setError(err.message);
} finally { } finally {
@@ -128,6 +141,30 @@ export default function MelodySettings() {
saveSettings(updated); saveSettings(updated);
}; };
const openNoteColorModal = (index) => {
const current = settings.note_assignment_colors?.[index] || DEFAULT_NOTE_ASSIGNMENT_COLORS[index];
setModalColor(current);
setModalColorInput(current);
setColorModalBell(index);
};
const applyNoteColor = () => {
if (colorModalBell == null) return;
const candidate = modalColorInput.startsWith("#") ? modalColorInput : `#${modalColorInput}`;
if (!/^#[0-9A-Fa-f]{6}$/.test(candidate)) return;
const next = [...(settings.note_assignment_colors || DEFAULT_NOTE_ASSIGNMENT_COLORS)];
next[colorModalBell] = candidate;
saveSettings({ ...settings, note_assignment_colors: next.slice(0, 16) });
setColorModalBell(null);
};
const resetNoteColor = () => {
if (colorModalBell == null) return;
const fallback = DEFAULT_NOTE_ASSIGNMENT_COLORS[colorModalBell];
setModalColor(fallback);
setModalColorInput(fallback);
};
if (loading) { if (loading) {
return <div className="text-center py-8" style={mutedStyle}>Loading...</div>; return <div className="text-center py-8" style={mutedStyle}>Loading...</div>;
} }
@@ -278,7 +315,115 @@ export default function MelodySettings() {
<button type="button" onClick={addDuration} disabled={saving || !durationToAdd} className={btnPrimary} style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}>Add</button> <button type="button" onClick={addDuration} disabled={saving || !durationToAdd} className={btnPrimary} style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}>Add</button>
</div> </div>
</section> </section>
{/* --- Note Assignment Colors --- */}
<section className="rounded-lg p-6 xl:col-span-2 border" style={sectionStyle}>
<h2 className="text-lg font-semibold mb-2" style={headingStyle}>Note Assignment Color Coding</h2>
<p className="text-xs mb-4" style={mutedStyle}>
Colors used in Composer, Playback, and View table dots. Click a bell to customize.
</p>
<div className="grid gap-3" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(86px, 1fr))" }}>
{Array.from({ length: 16 }, (_, idx) => {
const color = settings.note_assignment_colors?.[idx] || DEFAULT_NOTE_ASSIGNMENT_COLORS[idx];
return (
<button
key={idx}
type="button"
onClick={() => openNoteColorModal(idx)}
className="flex flex-col items-center gap-1.5 rounded-md py-2 border"
style={{ borderColor: "var(--border-primary)", backgroundColor: "var(--bg-primary)" }}
title={`Bell ${idx + 1}`}
>
<span
className="inline-flex items-center justify-center rounded-full text-xs font-semibold"
style={{
width: "30px",
height: "30px",
backgroundColor: color,
color: "#111827",
boxShadow: `0 0 8px 2px ${color}66`,
}}
>
{idx + 1}
</span>
<span className="text-[11px] font-mono" style={{ color: "var(--text-muted)" }}>
{color}
</span>
</button>
);
})}
</div> </div>
</section>
</div>
{colorModalBell != null && (
<div
className="fixed inset-0 z-50 flex items-center justify-center p-4"
style={{ backgroundColor: "rgba(0,0,0,0.55)" }}
onClick={() => setColorModalBell(null)}
>
<div
className="w-full max-w-md rounded-lg border shadow-xl p-5"
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
onClick={(e) => e.stopPropagation()}
>
<h3 className="text-base font-semibold mb-1" style={headingStyle}>Bell {colorModalBell + 1} Color</h3>
<p className="text-xs mb-4" style={mutedStyle}>Pick a custom color for this bell number.</p>
<div className="flex items-center gap-3 mb-4">
<input
type="color"
value={modalColor}
onChange={(e) => { setModalColor(e.target.value); setModalColorInput(e.target.value); }}
className="w-14 h-10 rounded cursor-pointer border"
style={{ borderColor: "var(--border-primary)" }}
/>
<input
type="text"
value={modalColorInput}
onChange={(e) => {
const v = e.target.value;
setModalColorInput(v);
if (/^#[0-9A-Fa-f]{6}$/.test(v)) setModalColor(v);
}}
className="flex-1 px-3 py-2 rounded-md text-sm font-mono border"
/>
<span
className="inline-flex items-center justify-center rounded-full text-xs font-semibold"
style={{ width: "30px", height: "30px", backgroundColor: modalColor, color: "#111827" }}
>
{colorModalBell + 1}
</span>
</div>
<div className="flex justify-end gap-2">
<button
type="button"
onClick={resetNoteColor}
className="px-3 py-1.5 text-sm rounded-md border"
style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)", backgroundColor: "var(--bg-card-hover)" }}
>
Reset
</button>
<button
type="button"
onClick={() => setColorModalBell(null)}
className="px-3 py-1.5 text-sm rounded-md border"
style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)", backgroundColor: "var(--bg-card-hover)" }}
>
Cancel
</button>
<button
type="button"
onClick={applyNoteColor}
disabled={!/^#[0-9A-Fa-f]{6}$/.test(modalColorInput.startsWith("#") ? modalColorInput : `#${modalColorInput}`)}
className="px-3 py-1.5 text-sm rounded-md"
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
>
Save Color
</button>
</div>
</div>
</div>
)}
</div> </div>
); );
} }

View File

@@ -1,4 +1,6 @@
import { useState, useEffect, useRef, useCallback } from "react"; import { useState, useEffect, useRef, useCallback } from "react";
import api from "../api/client";
function bellFrequency(bellNumber) { function bellFrequency(bellNumber) {
return 880 * Math.pow(Math.pow(2, 1 / 12), -2 * (bellNumber - 1)); return 880 * Math.pow(Math.pow(2, 1 / 12), -2 * (bellNumber - 1));
@@ -145,6 +147,11 @@ function bellDotGlow(assignedBell) {
return `hsla(${hue}, 78%, 56%, 0.45)`; return `hsla(${hue}, 78%, 56%, 0.45)`;
} }
function bellCustomGlow(color) {
if (!color || typeof color !== "string") return null;
return `${color}66`;
}
const mutedStyle = { color: "var(--text-muted)" }; const mutedStyle = { color: "var(--text-muted)" };
const labelStyle = { color: "var(--text-secondary)" }; const labelStyle = { color: "var(--text-secondary)" };
const NOTE_LABELS = "ABCDEFGHIJKLMNOP"; const NOTE_LABELS = "ABCDEFGHIJKLMNOP";
@@ -165,6 +172,7 @@ export default function PlaybackModal({ open, melody, builtMelody, files, archet
const [toneLengthMs, setToneLengthMs] = useState(80); const [toneLengthMs, setToneLengthMs] = useState(80);
const [loopEnabled, setLoopEnabled] = useState(true); const [loopEnabled, setLoopEnabled] = useState(true);
const [activeBells, setActiveBells] = useState(new Set()); const [activeBells, setActiveBells] = useState(new Set());
const [noteColors, setNoteColors] = useState([]);
const audioCtxRef = useRef(null); const audioCtxRef = useRef(null);
const playbackRef = useRef(null); const playbackRef = useRef(null);
@@ -181,6 +189,19 @@ export default function PlaybackModal({ open, melody, builtMelody, files, archet
useEffect(() => { toneLengthRef.current = toneLengthMs; }, [toneLengthMs]); useEffect(() => { toneLengthRef.current = toneLengthMs; }, [toneLengthMs]);
useEffect(() => { noteAssignmentsRef.current = noteAssignments; }, [noteAssignments]); useEffect(() => { noteAssignmentsRef.current = noteAssignments; }, [noteAssignments]);
useEffect(() => { loopEnabledRef.current = loopEnabled; }, [loopEnabled]); useEffect(() => { loopEnabledRef.current = loopEnabled; }, [loopEnabled]);
useEffect(() => {
if (!open) return;
let canceled = false;
api.get("/settings/melody")
.then((s) => {
if (canceled) return;
setNoteColors((s?.note_assignment_colors || []).slice(0, 16));
})
.catch(() => {
if (!canceled) setNoteColors([]);
});
return () => { canceled = true; };
}, [open]);
const stopPlayback = useCallback(() => { const stopPlayback = useCallback(() => {
if (playbackRef.current) { if (playbackRef.current) {
@@ -495,6 +516,7 @@ export default function PlaybackModal({ open, melody, builtMelody, files, archet
const enabled = Boolean(stepValue & (1 << noteIdx)); const enabled = Boolean(stepValue & (1 << noteIdx));
const isCurrent = currentStep === stepIdx; const isCurrent = currentStep === stepIdx;
const assignedBell = Number(noteAssignments[noteIdx] || 0); const assignedBell = Number(noteAssignments[noteIdx] || 0);
const assignedColor = assignedBell > 0 ? noteColors?.[assignedBell - 1] : null;
const dotLabel = assignedBell > 0 ? assignedBell : ""; const dotLabel = assignedBell > 0 ? assignedBell : "";
const isUnassigned = assignedBell <= 0; const isUnassigned = assignedBell <= 0;
const dotVisible = enabled || (isUnassigned && Boolean(stepValue & (1 << noteIdx))); const dotVisible = enabled || (isUnassigned && Boolean(stepValue & (1 << noteIdx)));
@@ -516,12 +538,12 @@ export default function PlaybackModal({ open, melody, builtMelody, files, archet
width: "68%", width: "68%",
height: "68%", height: "68%",
borderRadius: "9999px", borderRadius: "9999px",
backgroundColor: isUnassigned ? "rgba(100,116,139,0.7)" : bellDotColor(assignedBell), backgroundColor: isUnassigned ? "rgba(100,116,139,0.7)" : (assignedColor || bellDotColor(assignedBell)),
color: "#111827", color: "#111827",
opacity: dotVisible ? 1 : 0, opacity: dotVisible ? 1 : 0,
transform: dotVisible ? "scale(1)" : "scale(0.4)", transform: dotVisible ? "scale(1)" : "scale(0.4)",
boxShadow: dotVisible boxShadow: dotVisible
? (isUnassigned ? "0 0 8px 2px rgba(100,116,139,0.35)" : `0 0 10px 3px ${bellDotGlow(assignedBell)}`) ? (isUnassigned ? "0 0 8px 2px rgba(100,116,139,0.35)" : `0 0 10px 3px ${bellCustomGlow(assignedColor) || bellDotGlow(assignedBell)}`)
: "none", : "none",
transition: "opacity 140ms ease, transform 140ms ease, box-shadow 180ms ease", transition: "opacity 140ms ease, transform 140ms ease, box-shadow 180ms ease",
}} }}
@@ -557,3 +579,5 @@ export default function PlaybackModal({ open, melody, builtMelody, files, archet
</div> </div>
); );
} }