Added Draft Melodies. Further improvements to the UI

This commit is contained in:
2026-02-18 19:33:59 +02:00
parent a6e0b1d46e
commit aad8942d65
12 changed files with 1080 additions and 518 deletions

View File

@@ -178,7 +178,7 @@ function DeviceLogsPanel({ deviceSerial }) {
const [searchText, setSearchText] = useState("");
const [autoRefresh, setAutoRefresh] = useState(false);
const [liveLogs, setLiveLogs] = useState([]);
const limit = 15;
const limit = 25;
const fetchLogs = useCallback(async () => {
if (!deviceSerial) return;
@@ -278,9 +278,9 @@ function DeviceLogsPanel({ deviceSerial }) {
<p className="text-xs" style={{ color: "var(--text-muted)" }}>No logs found.</p>
) : (
<div className="rounded-md overflow-hidden border" style={{ borderColor: "var(--border-primary)" }}>
<div className="overflow-x-auto">
<div className="overflow-x-auto" style={{ maxHeight: 220, overflowY: "auto" }}>
<table className="w-full text-xs">
<thead>
<thead style={{ position: "sticky", top: 0, zIndex: 1 }}>
<tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
<th className="px-3 py-2 text-left font-medium w-40" style={{ color: "var(--text-secondary)" }}>Time</th>
<th className="px-3 py-2 text-left font-medium w-16" style={{ color: "var(--text-secondary)" }}>Level</th>
@@ -322,6 +322,24 @@ function DeviceLogsPanel({ deviceSerial }) {
);
}
// --- Breakpoint hook ---
function useBreakpoint() {
const [cols, setCols] = useState(() => {
const w = window.innerWidth;
return w >= 2100 ? 3 : w >= 900 ? 2 : 1;
});
useEffect(() => {
const onResize = () => {
const w = window.innerWidth;
setCols(w >= 2100 ? 3 : w >= 900 ? 2 : 1);
};
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, []);
return cols;
}
// --- Main component ---
export default function DeviceDetail() {
@@ -429,6 +447,456 @@ export default function DeviceDetail() {
const nextMaintenance = maintainedOn && stats.maintainancePeriod ? addDays(maintainedOn, stats.maintainancePeriod) : null;
const maintenanceDaysLeft = nextMaintenance ? daysUntil(nextMaintenance) : null;
const cols = useBreakpoint();
// ===== Section definitions =====
const deviceInfoSection = (
<section className="rounded-lg border p-5" style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}>
<div className="device-info-row">
{/* Status */}
<div className="device-info-item">
<div
className="w-10 h-10 rounded-full flex items-center justify-center shrink-0"
style={{ backgroundColor: isOnline ? "var(--success-bg)" : "var(--bg-card-hover)" }}
>
<span
className="w-3 h-3 rounded-full inline-block"
style={{ backgroundColor: isOnline ? "var(--success-text)" : "var(--text-muted)" }}
/>
</div>
<div>
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Status</div>
<div className="text-sm font-semibold" style={{ color: isOnline ? "var(--success-text)" : "var(--text-muted)" }}>
{isOnline ? "Online" : "Offline"}
{mqttStatus && (
<span className="ml-2 text-xs font-normal" style={{ color: "var(--text-muted)" }}>
{mqttStatus.seconds_since_heartbeat}s ago
</span>
)}
</div>
</div>
</div>
{/* Serial + Hardware Variant */}
<div className="device-info-item">
<div>
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Serial Number</div>
<div className="text-sm font-mono mt-0.5" style={{ color: "var(--text-primary)" }}>{device.device_id}</div>
<div className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>HW: VesperCore</div>
</div>
</div>
{/* Admin Note */}
<div className="device-info-item">
<div>
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Admin Note</div>
<div className="text-sm mt-0.5" style={{ color: "var(--text-muted)" }}>-</div>
</div>
</div>
{/* Document ID */}
<div className="device-info-item">
<div>
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Document ID</div>
<div className="text-xs font-mono mt-0.5" style={{ color: "var(--text-muted)" }}>{device.id}</div>
</div>
</div>
</div>
</section>
);
const subscriptionSection = (
<SectionCard title="Subscription">
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
<Field label="Tier">
<span className="px-2 py-0.5 text-xs rounded-full capitalize" style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}>
{sub.subscrTier}
</span>
</Field>
<Field label="Start Date">{formatDate(sub.subscrStart)}</Field>
<Field label="Duration">{sub.subscrDuration ? daysToDisplay(sub.subscrDuration) : "-"}</Field>
<Field label="Expiration Date">{subscrEnd ? formatDateNice(subscrEnd) : "-"}</Field>
<Field label="Time Left">
{subscrDaysLeft === null ? "-" : subscrDaysLeft <= 0 ? (
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }}>
Subscription Expired
</span>
) : (
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--success-bg)", color: "var(--success-text)" }}>
{subscrDaysLeft} days left
</span>
)}
</Field>
<Field label="Max Users">{sub.maxUsers}</Field>
<Field label="Max Outputs">{sub.maxOutputs}</Field>
</dl>
</SectionCard>
);
const locationSection = (
<SectionCard title="Location">
{coords ? (
<div className="location-split">
<div className="location-fields">
<dl className="space-y-4">
<Field label="Location">{device.device_location}</Field>
<Field label="Coordinates">
<div className="flex flex-wrap items-center gap-2">
<span>{formatCoordinates(coords)}</span>
<a
href={`https://www.google.com/maps?q=${coords.lat},${coords.lng}`}
target="_blank"
rel="noopener noreferrer"
className="px-2 py-0.5 text-xs rounded-md inline-block"
style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}
onClick={(e) => e.stopPropagation()}
>
Open in Maps
</a>
</div>
</Field>
{locationName && <Field label="Nearest Place">{locationName}</Field>}
</dl>
</div>
<div className="location-map">
<div className="rounded-md overflow-hidden border w-full" style={{ borderColor: "var(--border-primary)", height: 250 }}>
<MapContainer center={[coords.lat, coords.lng]} zoom={13} style={{ height: "100%", width: "100%" }} scrollWheelZoom={false}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[coords.lat, coords.lng]} />
</MapContainer>
</div>
</div>
</div>
) : (
<dl className="space-y-4">
<Field label="Location">{device.device_location}</Field>
<Field label="Coordinates">{device.device_location_coordinates || "-"}</Field>
</dl>
)}
</SectionCard>
);
const deviceSettingsSection = (
<SectionCard title="Device Settings">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Left Column */}
<div>
<Subsection title="Basic Attributes" isFirst>
<FieldRow>
<Field label="Bell Guard"><BoolBadge value={attr.bellGuardOn} /></Field>
<Field label="Warnings On"><BoolBadge value={attr.warningsOn} /></Field>
<Field label="Bell Guard Safety"><BoolBadge value={attr.bellGuardSafetyOn} /></Field>
</FieldRow>
</Subsection>
<Subsection title="Alert Settings">
<FieldRow>
<Field label="Alerts Status"><BoolBadge value={clock.ringAlertsMasterOn} yesLabel="ON" noLabel="OFF" /></Field>
<Field label="Alerts Type"><span className="capitalize">{clock.ringAlerts || "-"}</span></Field>
<Field label="Ring Intervals">{clock.ringIntervals}</Field>
</FieldRow>
<FieldRow>
<Field label="Hour Bell">{clock.hourAlertsBell}</Field>
<Field label="Half-Hour Bell">{clock.halfhourAlertsBell}</Field>
<Field label="Quarter Bell">{clock.quarterAlertsBell}</Field>
</FieldRow>
<FieldRow>
<Field label="Daytime Silence"><BoolBadge value={clock.isDaySilenceOn} yesLabel="ON" noLabel="OFF" /></Field>
<Field label="Day-Time Period">
{formatTimestamp(clock.daySilenceFrom)} - {formatTimestamp(clock.daySilenceTo)}
</Field>
</FieldRow>
<FieldRow>
<Field label="Nighttime Silence"><BoolBadge value={clock.isNightSilenceOn} yesLabel="ON" noLabel="OFF" /></Field>
<Field label="Nighttime Period">
{formatTimestamp(clock.nightSilenceFrom)} - {formatTimestamp(clock.nightSilenceTo)}
</Field>
</FieldRow>
</Subsection>
<Subsection title="Backlight Settings">
<FieldRow>
<Field label="Auto Backlight"><BoolBadge value={clock.isBacklightAutomationOn} yesLabel="ON" noLabel="OFF" /></Field>
<Field label="Backlight Output">{clock.backlightOutput}</Field>
<Field label="Period">
{formatTimestamp(clock.backlightTurnOnTime)} - {formatTimestamp(clock.backlightTurnOffTime)}
</Field>
</FieldRow>
</Subsection>
<Subsection title="Logging">
<FieldRow>
<Field label="Serial Log Level">{attr.serialLogLevel}</Field>
<Field label="SD Log Level">{attr.sdLogLevel}</Field>
<Field label="MQTT Log Level">{attr.mqttLogLevel ?? 0}</Field>
</FieldRow>
</Subsection>
</div>
{/* Right Column */}
<div>
<Subsection title="Network" isFirst>
<FieldRow>
<Field label="Hostname">{net.hostname}</Field>
<Field label="Has Static IP"><BoolBadge value={net.useStaticIP} /></Field>
</FieldRow>
</Subsection>
<Subsection title="Clock Settings">
<FieldRow>
<Field label="Has Clock"><BoolBadge value={attr.hasClock} /></Field>
<Field label="Ring Intervals">{clock.ringIntervals}</Field>
</FieldRow>
<FieldRow>
<Field label="Odd Output">{clock.clockOutputs?.[0] ?? "-"}</Field>
<Field label="Even Output">{clock.clockOutputs?.[1] ?? "-"}</Field>
</FieldRow>
<FieldRow>
<Field label="Run Pulse">{clock.clockTimings?.[0] != null ? msToSeconds(clock.clockTimings[0]) : "-"}</Field>
<Field label="Pause Pulse">{clock.clockTimings?.[1] != null ? msToSeconds(clock.clockTimings[1]) : "-"}</Field>
</FieldRow>
</Subsection>
<Subsection title="Bell Settings">
<FieldRow>
<Field label="Bells Active"><BoolBadge value={attr.hasBells} /></Field>
<Field label="Total">{attr.totalBells ?? "-"}</Field>
</FieldRow>
{attr.bellOutputs?.length > 0 && (
<div className="mt-3">
<dt className="text-xs font-medium uppercase tracking-wide mb-2" style={{ color: "var(--text-muted)" }}>
Output &amp; Timing Map
</dt>
<div className="flex flex-wrap gap-2">
{attr.bellOutputs.map((output, i) => (
<div
key={i}
className="relative rounded-md border px-4 py-3 text-center overflow-hidden"
style={{ borderColor: "var(--border-primary)", backgroundColor: "var(--bg-primary)", minWidth: 90 }}
>
<span
className="absolute inset-0 flex items-center justify-center font-bold pointer-events-none select-none"
style={{ fontSize: "3rem", color: "var(--text-heading)", opacity: 0.06 }}
>
{i + 1}
</span>
<div className="relative">
<div className="text-xs" style={{ color: "var(--text-muted)" }}>
Output <span style={{ color: "var(--text-primary)" }}>{output}</span>
</div>
<div className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>
{attr.hammerTimings?.[i] != null ? (
<><span style={{ color: "var(--text-primary)" }}>{attr.hammerTimings[i]}</span> ms</>
) : "-"}
</div>
</div>
</div>
))}
</div>
</div>
)}
</Subsection>
</div>
</div>
</SectionCard>
);
const warrantySection = (
<SectionCard title="Warranty, Maintenance & Statistics">
<Subsection title="Warranty Information" isFirst>
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
<Field label="Warranty Status">
{warrantyDaysLeft !== null ? (
warrantyDaysLeft > 0 ? (
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--success-bg)", color: "var(--success-text)" }}>Active</span>
) : (
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }}>Expired</span>
)
) : (
<BoolBadge value={stats.warrantyActive} yesLabel="Active" noLabel="Expired" />
)}
</Field>
<Field label="Start Date">{formatDate(stats.warrantyStart)}</Field>
<Field label="Warranty Period">{stats.warrantyPeriod ? daysToDisplay(stats.warrantyPeriod) : "-"}</Field>
<Field label="Expiration Date">{warrantyEnd ? formatDateNice(warrantyEnd) : "-"}</Field>
<Field label="Remaining">
{warrantyDaysLeft === null ? "-" : warrantyDaysLeft <= 0 ? (
<span style={{ color: "var(--danger-text)" }}>Expired</span>
) : (
`${warrantyDaysLeft} days`
)}
</Field>
</dl>
</Subsection>
<Subsection title="Maintenance">
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
<Field label="Last Maintained On">{formatDate(stats.maintainedOn)}</Field>
<Field label="Maintenance Period">{stats.maintainancePeriod ? daysToDisplay(stats.maintainancePeriod) : "-"}</Field>
<Field label="Next Scheduled">
{nextMaintenance ? (
<span>
{formatDateNice(nextMaintenance)}
{maintenanceDaysLeft !== null && (
<span className="ml-1 text-xs" style={{ color: maintenanceDaysLeft <= 0 ? "var(--danger-text)" : "var(--text-muted)" }}>
({maintenanceDaysLeft <= 0 ? "overdue" : formatRelativeTime(maintenanceDaysLeft)})
</span>
)}
</span>
) : "-"}
</Field>
</dl>
</Subsection>
<Subsection title="Statistics">
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
<Field label="Total Playbacks">{stats.totalPlaybacks}</Field>
<Field label="Total Hammer Strikes">{stats.totalHammerStrikes}</Field>
<Field label="Total Warnings Given">{stats.totalWarningsGiven}</Field>
<Field label="Total Melodies">{device.device_melodies_all?.length ?? 0}</Field>
<Field label="Favorite Melodies">{device.device_melodies_favorites?.length ?? 0}</Field>
{stats.perBellStrikes?.length > 0 && (
<div style={{ gridColumn: "1 / -1" }}>
<Field label="Per Bell Strikes">
<div className="flex flex-wrap gap-2 mt-1">
{stats.perBellStrikes.slice(0, attr.totalBells || stats.perBellStrikes.length).map((count, i) => (
<span key={i} className="px-2 py-1 text-xs rounded-md border" style={{ borderColor: "var(--border-primary)", color: "var(--text-primary)" }}>
Bell {i + 1}: {count}
</span>
))}
</div>
</Field>
</div>
)}
</dl>
</Subsection>
</SectionCard>
);
const miscSection = (
<SectionCard title="Misc">
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
<Field label="Automated Events"><BoolBadge value={device.events_on} yesLabel="ON" noLabel="OFF" /></Field>
<Field label="Device Locale"><span className="capitalize">{attr.deviceLocale || "-"}</span></Field>
<Field label="WebSocket URL">{device.websocket_url}</Field>
<Field label="Has Assistant"><BoolBadge value={attr.hasAssistant} /></Field>
<div style={{ gridColumn: "1 / -1" }}>
<Field label="Church Assistant URL">{device.churchAssistantURL}</Field>
</div>
</dl>
</SectionCard>
);
const appUsersSection = (
<SectionCard title={`App Users (${deviceUsers.length})`}>
{usersLoading ? (
<p className="text-sm" style={{ color: "var(--text-muted)" }}>Loading users...</p>
) : deviceUsers.length === 0 ? (
<p className="text-sm" style={{ color: "var(--text-muted)" }}>No users assigned to this device.</p>
) : (
<div className="space-y-2">
{deviceUsers.map((user, i) => (
<div
key={user.user_id || i}
className="p-3 rounded-md border cursor-pointer hover:opacity-90 transition-colors"
style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-primary)" }}
onClick={() => user.user_id && navigate(`/users/${user.user_id}`)}
>
<div className="flex items-center justify-between">
<div className="min-w-0">
<p className="text-sm font-medium truncate" style={{ color: "var(--text-heading)" }}>
{user.display_name || user.email || "Unknown User"}
</p>
{user.email && user.display_name && (
<p className="text-xs truncate" style={{ color: "var(--text-muted)" }}>{user.email}</p>
)}
{user.user_id && (
<p className="text-xs font-mono" style={{ color: "var(--text-muted)" }}>{user.user_id}</p>
)}
</div>
{user.role && (
<span className="px-2 py-0.5 text-xs rounded-full capitalize shrink-0 ml-2" style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}>
{user.role}
</span>
)}
</div>
</div>
))}
</div>
)}
</SectionCard>
);
const notesSection = <NotesPanel deviceId={id} />;
const logsSection = <DeviceLogsPanel deviceSerial={device.device_id} />;
// ===== Layout rendering =====
const renderSingleColumn = () => (
<div className="device-column">
{deviceInfoSection}
{locationSection}
{notesSection}
{subscriptionSection}
{deviceSettingsSection}
{warrantySection}
{miscSection}
{appUsersSection}
{logsSection}
</div>
);
const renderDoubleColumn = () => (
<div style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
{/* Row 1: Device Info + Subscription — equal height */}
<div className="device-equal-row">
{deviceInfoSection}
{subscriptionSection}
</div>
{/* Row 2: Device Settings — full width */}
{deviceSettingsSection}
{/* Row 3: Location+Misc (left) vs Warranty (right) */}
<div className="device-columns">
<div className="device-flex-fill" style={{ flex: 1, gap: "1.5rem" }}>
<div className="flex-grow">{locationSection}</div>
{miscSection}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
{warrantySection}
</div>
</div>
{/* Row 4: Notes vs App Users */}
<div className="device-columns">
<div style={{ flex: 1, minWidth: 0 }}>{notesSection}</div>
<div style={{ flex: 1, minWidth: 0 }}>{appUsersSection}</div>
</div>
{/* Latest Logs */}
{logsSection}
</div>
);
const renderTripleColumn = () => (
<div style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
{/* Row 1: DevInfo+Subscription (cols 1-2 equal height) + Location (col 3) */}
<div className="device-columns">
<div className="device-equal-row" style={{ flex: 2 }}>
{deviceInfoSection}
{subscriptionSection}
</div>
<div style={{ flex: 1, minWidth: 0 }}>{locationSection}</div>
</div>
{/* Row 2: Device Settings (cols 1-2) + Warranty (col 3) */}
<div className="device-columns">
<div style={{ flex: 2, minWidth: 0 }}>{deviceSettingsSection}</div>
<div style={{ flex: 1, minWidth: 0 }}>{warrantySection}</div>
</div>
{/* Row 3: Misc (col1) + Notes (col2) + App Users (col3) */}
<div className="device-columns">
<div style={{ flex: 1, minWidth: 0 }}>{miscSection}</div>
<div style={{ flex: 1, minWidth: 0 }}>{notesSection}</div>
<div style={{ flex: 1, minWidth: 0 }}>{appUsersSection}</div>
</div>
{/* Latest Logs */}
{logsSection}
</div>
);
return (
<div>
{/* Header */}
@@ -460,393 +928,7 @@ export default function DeviceDetail() {
)}
</div>
<div className="device-sections">
{/* ===== BASIC INFORMATION (double-width) ===== */}
<div className="section-wide">
<section className="rounded-lg border p-5" style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}>
<div className="flex flex-wrap items-center gap-6 divide-x" style={{ borderColor: "var(--border-secondary)" }}>
{/* Status — fancy */}
<div className="flex items-center gap-3 pr-6">
<div
className="w-10 h-10 rounded-full flex items-center justify-center"
style={{ backgroundColor: isOnline ? "var(--success-bg)" : "var(--bg-card-hover)" }}
>
<span
className="w-3 h-3 rounded-full inline-block"
style={{ backgroundColor: isOnline ? "var(--success-text)" : "var(--text-muted)" }}
/>
</div>
<div>
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Status</div>
<div className="text-sm font-semibold" style={{ color: isOnline ? "var(--success-text)" : "var(--text-muted)" }}>
{isOnline ? "Online" : "Offline"}
{mqttStatus && (
<span className="ml-2 text-xs font-normal" style={{ color: "var(--text-muted)" }}>
(MQTT {mqttStatus.seconds_since_heartbeat}s ago)
</span>
)}
</div>
</div>
</div>
{/* Serial + Hardware Variant */}
<div className="pl-6">
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Serial Number</div>
<div className="text-sm font-mono mt-0.5" style={{ color: "var(--text-primary)" }}>
{device.device_id}
<span className="ml-3 text-xs" style={{ color: "var(--text-muted)" }}>HW: -</span>
</div>
</div>
{/* Quick Admin Notes */}
<div className="pl-6">
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Admin Notes</div>
<div className="text-sm mt-0.5" style={{ color: "var(--text-muted)" }}>-</div>
</div>
{/* Document ID */}
<div className="pl-6">
<div className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>Document ID</div>
<div className="text-xs font-mono mt-0.5" style={{ color: "var(--text-muted)" }}>{device.id}</div>
</div>
</div>
</section>
</div>
{/* ===== DEVICE SETTINGS (double-width) ===== */}
<div className="section-wide">
<SectionCard title="Device Settings">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Left Column */}
<div>
{/* Basic Attributes */}
<Subsection title="Basic Attributes" isFirst>
<FieldRow>
<Field label="Bell Guard"><BoolBadge value={attr.bellGuardOn} /></Field>
<Field label="Warnings On"><BoolBadge value={attr.warningsOn} /></Field>
<Field label="Bell Guard Safety"><BoolBadge value={attr.bellGuardSafetyOn} /></Field>
</FieldRow>
</Subsection>
{/* Alert Settings */}
<Subsection title="Alert Settings">
<FieldRow>
<Field label="Alerts Status"><BoolBadge value={clock.ringAlertsMasterOn} yesLabel="ON" noLabel="OFF" /></Field>
<Field label="Alerts Type"><span className="capitalize">{clock.ringAlerts || "-"}</span></Field>
<Field label="Ring Intervals">{clock.ringIntervals}</Field>
</FieldRow>
<FieldRow>
<Field label="Hour Bell">{clock.hourAlertsBell}</Field>
<Field label="Half-Hour Bell">{clock.halfhourAlertsBell}</Field>
<Field label="Quarter Bell">{clock.quarterAlertsBell}</Field>
</FieldRow>
<FieldRow>
<Field label="Daytime Silence"><BoolBadge value={clock.isDaySilenceOn} yesLabel="ON" noLabel="OFF" /></Field>
<Field label="Day-Time Period">
{formatTimestamp(clock.daySilenceFrom)} - {formatTimestamp(clock.daySilenceTo)}
</Field>
</FieldRow>
<FieldRow>
<Field label="Nighttime Silence"><BoolBadge value={clock.isNightSilenceOn} yesLabel="ON" noLabel="OFF" /></Field>
<Field label="Nighttime Period">
{formatTimestamp(clock.nightSilenceFrom)} - {formatTimestamp(clock.nightSilenceTo)}
</Field>
</FieldRow>
</Subsection>
{/* Backlight Settings */}
<Subsection title="Backlight Settings">
<FieldRow>
<Field label="Auto Backlight"><BoolBadge value={clock.isBacklightAutomationOn} yesLabel="ON" noLabel="OFF" /></Field>
<Field label="Backlight Output">{clock.backlightOutput}</Field>
<Field label="Period">
{formatTimestamp(clock.backlightTurnOnTime)} - {formatTimestamp(clock.backlightTurnOffTime)}
</Field>
</FieldRow>
</Subsection>
{/* Logging */}
<Subsection title="Logging">
<FieldRow>
<Field label="Serial Log Level">{attr.serialLogLevel}</Field>
<Field label="SD Log Level">{attr.sdLogLevel}</Field>
<Field label="MQTT Log Level">{attr.mqttLogLevel ?? 0}</Field>
</FieldRow>
</Subsection>
</div>
{/* Right Column */}
<div>
{/* Network */}
<Subsection title="Network" isFirst>
<FieldRow>
<Field label="Hostname">{net.hostname}</Field>
<Field label="Has Static IP"><BoolBadge value={net.useStaticIP} /></Field>
</FieldRow>
</Subsection>
{/* Clock Settings */}
<Subsection title="Clock Settings">
<FieldRow>
<Field label="Has Clock"><BoolBadge value={attr.hasClock} /></Field>
<Field label="Ring Intervals">{clock.ringIntervals}</Field>
</FieldRow>
<FieldRow>
<Field label="Odd Output">{clock.clockOutputs?.[0] ?? "-"}</Field>
<Field label="Even Output">{clock.clockOutputs?.[1] ?? "-"}</Field>
</FieldRow>
<FieldRow>
<Field label="Run Pulse">{clock.clockTimings?.[0] != null ? msToSeconds(clock.clockTimings[0]) : "-"}</Field>
<Field label="Pause Pulse">{clock.clockTimings?.[1] != null ? msToSeconds(clock.clockTimings[1]) : "-"}</Field>
</FieldRow>
</Subsection>
{/* Bell Settings */}
<Subsection title="Bell Settings">
<FieldRow>
<Field label="Bells Active"><BoolBadge value={attr.hasBells} /></Field>
<Field label="Total">{attr.totalBells ?? "-"}</Field>
</FieldRow>
{/* Bell Output-to-Timing mapping with watermark numbers */}
{attr.bellOutputs?.length > 0 && (
<div className="mt-3">
<dt className="text-xs font-medium uppercase tracking-wide mb-2" style={{ color: "var(--text-muted)" }}>
Output &amp; Timing Map
</dt>
<div className="flex flex-wrap gap-2">
{attr.bellOutputs.map((output, i) => (
<div
key={i}
className="relative rounded-md border px-4 py-3 text-center overflow-hidden"
style={{ borderColor: "var(--border-primary)", backgroundColor: "var(--bg-primary)", minWidth: 90 }}
>
{/* Watermark number */}
<span
className="absolute inset-0 flex items-center justify-center font-bold pointer-events-none select-none"
style={{ fontSize: "3rem", color: "var(--text-heading)", opacity: 0.06 }}
>
{i + 1}
</span>
{/* Content */}
<div className="relative">
<div className="text-xs" style={{ color: "var(--text-muted)" }}>
Output <span style={{ color: "var(--text-primary)" }}>{output}</span>
</div>
<div className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>
{attr.hammerTimings?.[i] != null ? (
<><span style={{ color: "var(--text-primary)" }}>{attr.hammerTimings[i]}</span> ms</>
) : "-"}
</div>
</div>
</div>
))}
</div>
</div>
)}
</Subsection>
</div>
</div>
</SectionCard>
</div>
{/* ===== SINGLE-WIDTH SECTIONS ===== */}
{/* Misc */}
<SectionCard title="Misc">
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
<Field label="Automated Events"><BoolBadge value={device.events_on} yesLabel="ON" noLabel="OFF" /></Field>
<Field label="Device Locale"><span className="capitalize">{attr.deviceLocale || "-"}</span></Field>
<Field label="WebSocket URL">{device.websocket_url}</Field>
<Field label="Has Assistant"><BoolBadge value={attr.hasAssistant} /></Field>
<div style={{ gridColumn: "1 / -1" }}>
<Field label="Church Assistant URL">{device.churchAssistantURL}</Field>
</div>
</dl>
</SectionCard>
{/* Subscription */}
<SectionCard title="Subscription">
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
<Field label="Tier">
<span className="px-2 py-0.5 text-xs rounded-full capitalize" style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}>
{sub.subscrTier}
</span>
</Field>
<Field label="Start Date">{formatDate(sub.subscrStart)}</Field>
<Field label="Duration">{sub.subscrDuration ? daysToDisplay(sub.subscrDuration) : "-"}</Field>
<Field label="Expiration Date">{subscrEnd ? formatDateNice(subscrEnd) : "-"}</Field>
<Field label="Time Left">
{subscrDaysLeft === null ? "-" : subscrDaysLeft <= 0 ? (
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }}>
Subscription Expired
</span>
) : (
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--success-bg)", color: "var(--success-text)" }}>
{subscrDaysLeft} days left
</span>
)}
</Field>
<Field label="Max Users">{sub.maxUsers}</Field>
<Field label="Max Outputs">{sub.maxOutputs}</Field>
</dl>
</SectionCard>
{/* Location */}
<SectionCard title="Location">
<div className={coords ? "grid grid-cols-1 md:grid-cols-2 gap-4" : ""}>
<dl className="space-y-4">
<Field label="Location">{device.device_location}</Field>
<Field label="Coordinates">
<div className="flex flex-wrap items-center gap-2">
<span>{coords ? formatCoordinates(coords) : device.device_location_coordinates || "-"}</span>
{coords && (
<a
href={`https://www.google.com/maps?q=${coords.lat},${coords.lng}`}
target="_blank"
rel="noopener noreferrer"
className="px-2 py-0.5 text-xs rounded-md inline-block"
style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}
onClick={(e) => e.stopPropagation()}
>
Open in Maps
</a>
)}
</div>
</Field>
{locationName && (
<Field label="Nearest Place">{locationName}</Field>
)}
</dl>
{coords && (
<div className="rounded-md overflow-hidden border" style={{ borderColor: "var(--border-primary)", minHeight: 300 }}>
<MapContainer center={[coords.lat, coords.lng]} zoom={13} style={{ height: "100%", width: "100%", minHeight: 300 }} scrollWheelZoom={false}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[coords.lat, coords.lng]} />
</MapContainer>
</div>
)}
</div>
</SectionCard>
{/* Warranty, Maintenance & Statistics */}
<SectionCard title="Warranty, Maintenance & Statistics">
<Subsection title="Warranty Information" isFirst>
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
<Field label="Warranty Status">
{warrantyDaysLeft !== null ? (
warrantyDaysLeft > 0 ? (
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--success-bg)", color: "var(--success-text)" }}>Active</span>
) : (
<span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }}>Expired</span>
)
) : (
<BoolBadge value={stats.warrantyActive} yesLabel="Active" noLabel="Expired" />
)}
</Field>
<Field label="Start Date">{formatDate(stats.warrantyStart)}</Field>
<Field label="Warranty Period">{stats.warrantyPeriod ? daysToDisplay(stats.warrantyPeriod) : "-"}</Field>
<Field label="Expiration Date">{warrantyEnd ? formatDateNice(warrantyEnd) : "-"}</Field>
<Field label="Remaining">
{warrantyDaysLeft === null ? "-" : warrantyDaysLeft <= 0 ? (
<span style={{ color: "var(--danger-text)" }}>Expired</span>
) : (
`${warrantyDaysLeft} days`
)}
</Field>
</dl>
</Subsection>
<Subsection title="Maintenance">
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
<Field label="Last Maintained On">{formatDate(stats.maintainedOn)}</Field>
<Field label="Maintenance Period">{stats.maintainancePeriod ? daysToDisplay(stats.maintainancePeriod) : "-"}</Field>
<Field label="Next Scheduled">
{nextMaintenance ? (
<span>
{formatDateNice(nextMaintenance)}
{maintenanceDaysLeft !== null && (
<span className="ml-1 text-xs" style={{ color: maintenanceDaysLeft <= 0 ? "var(--danger-text)" : "var(--text-muted)" }}>
({maintenanceDaysLeft <= 0 ? "overdue" : formatRelativeTime(maintenanceDaysLeft)})
</span>
)}
</span>
) : "-"}
</Field>
</dl>
</Subsection>
<Subsection title="Statistics">
<dl className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
<Field label="Total Playbacks">{stats.totalPlaybacks}</Field>
<Field label="Total Hammer Strikes">{stats.totalHammerStrikes}</Field>
<Field label="Total Warnings Given">{stats.totalWarningsGiven}</Field>
<Field label="Total Melodies">{device.device_melodies_all?.length ?? 0}</Field>
<Field label="Favorite Melodies">{device.device_melodies_favorites?.length ?? 0}</Field>
{stats.perBellStrikes?.length > 0 && (
<div style={{ gridColumn: "1 / -1" }}>
<Field label="Per Bell Strikes">
<div className="flex flex-wrap gap-2 mt-1">
{stats.perBellStrikes.slice(0, attr.totalBells || stats.perBellStrikes.length).map((count, i) => (
<span key={i} className="px-2 py-1 text-xs rounded-md border" style={{ borderColor: "var(--border-primary)", color: "var(--text-primary)" }}>
Bell {i + 1}: {count}
</span>
))}
</div>
</Field>
</div>
)}
</dl>
</Subsection>
</SectionCard>
{/* Users */}
<SectionCard title={`App Users (${deviceUsers.length})`}>
{usersLoading ? (
<p className="text-sm" style={{ color: "var(--text-muted)" }}>Loading users...</p>
) : deviceUsers.length === 0 ? (
<p className="text-sm" style={{ color: "var(--text-muted)" }}>No users assigned to this device.</p>
) : (
<div className="space-y-2">
{deviceUsers.map((user, i) => (
<div
key={user.user_id || i}
className="p-3 rounded-md border cursor-pointer hover:opacity-90 transition-colors"
style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-primary)" }}
onClick={() => user.user_id && navigate(`/users/${user.user_id}`)}
>
<div className="flex items-center justify-between">
<div className="min-w-0">
<p className="text-sm font-medium truncate" style={{ color: "var(--text-heading)" }}>
{user.display_name || user.email || "Unknown User"}
</p>
{user.email && user.display_name && (
<p className="text-xs truncate" style={{ color: "var(--text-muted)" }}>{user.email}</p>
)}
{user.user_id && (
<p className="text-xs font-mono" style={{ color: "var(--text-muted)" }}>{user.user_id}</p>
)}
</div>
{user.role && (
<span className="px-2 py-0.5 text-xs rounded-full capitalize shrink-0 ml-2" style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}>
{user.role}
</span>
)}
</div>
</div>
))}
</div>
)}
</SectionCard>
{/* Equipment Notes */}
<NotesPanel deviceId={id} />
{/* Latest Logs */}
<DeviceLogsPanel deviceSerial={device.device_id} />
</div>
{cols === 1 ? renderSingleColumn() : cols === 2 ? renderDoubleColumn() : renderTripleColumn()}
<ConfirmDialog
open={showDelete}

View File

@@ -145,29 +145,70 @@ input[type="range"]::-moz-range-thumb {
border: 2px solid var(--bg-primary);
}
/* Device detail grid layout */
.device-sections {
display: grid;
grid-template-columns: 1fr;
/* Device detail column layout */
.device-columns {
display: flex;
gap: 1.5rem;
align-items: start;
align-items: flex-start;
}
.device-sections > .section-wide {
grid-column: 1 / -1;
.device-column {
display: flex;
flex-direction: column;
gap: 1.5rem;
flex: 1;
min-width: 0;
}
@media (min-width: 900px) {
.device-sections {
grid-template-columns: repeat(2, 1fr);
grid-auto-flow: dense;
}
.device-full-row {
width: 100%;
margin-bottom: 1.5rem;
}
@media (min-width: 2100px) {
.device-sections {
grid-template-columns: repeat(3, 1fr);
}
.device-sections > .section-wide {
grid-column: span 2;
}
.device-equal-row {
display: flex;
gap: 1.5rem;
align-items: stretch;
}
.device-equal-row > * {
flex: 1;
min-width: 0;
}
.device-flex-fill {
display: flex;
flex-direction: column;
}
.device-flex-fill > .flex-grow {
flex: 1;
}
/* Device info horizontal subsections */
.device-info-row {
display: flex;
flex-wrap: wrap;
gap: 0;
}
.device-info-row > .device-info-item {
padding: 0 1.5rem;
border-left: 1px solid var(--border-secondary);
display: flex;
align-items: center;
gap: 0.75rem;
}
.device-info-row > .device-info-item:first-child {
padding-left: 0;
border-left: none;
}
/* Location 2-column internal layout */
.location-split {
display: flex;
gap: 1.5rem;
align-items: stretch;
}
.location-split > .location-fields {
flex: 0 0 auto;
min-width: 200px;
}
.location-split > .location-map {
flex: 1;
display: flex;
align-items: center;
}
/* File input */

View File

@@ -32,6 +32,8 @@ export default function MelodyDetail() {
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);
@@ -72,6 +74,32 @@ export default function MelodyDetail() {
}
};
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>;
}
@@ -116,6 +144,15 @@ export default function MelodyDetail() {
</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}
@@ -133,6 +170,25 @@ export default function MelodyDetail() {
</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={() => navigate(`/melodies/${id}/edit`)}
className="px-4 py-2 text-sm rounded-md transition-colors"
@@ -326,6 +382,14 @@ export default function MelodyDetail() {
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>
);
}

View File

@@ -58,6 +58,7 @@ export default function MelodyForm() {
const [url, setUrl] = useState("");
const [uid, setUid] = useState("");
const [pid, setPid] = useState("");
const [melodyStatus, setMelodyStatus] = useState("draft");
const [binaryFile, setBinaryFile] = useState(null);
const [previewFile, setPreviewFile] = useState(null);
@@ -116,6 +117,7 @@ export default function MelodyForm() {
setUrl(melody.url || "");
setUid(melody.uid || "");
setPid(melody.pid || "");
setMelodyStatus(melody.status || "published");
setExistingFiles(files);
} catch (err) {
setError(err.message);
@@ -150,33 +152,39 @@ export default function MelodyForm() {
updateInfo(fieldKey, serializeLocalizedString(dict));
};
const handleSubmit = async (e) => {
e.preventDefault();
const buildBody = () => {
const { notes, ...infoWithoutNotes } = information;
return {
information: infoWithoutNotes,
default_settings: settings,
type, url, uid, pid,
};
};
const uploadFiles = async (melodyId) => {
if (binaryFile || previewFile) {
setUploading(true);
if (binaryFile) await api.upload(`/melodies/${melodyId}/upload/binary`, binaryFile);
if (previewFile) await api.upload(`/melodies/${melodyId}/upload/preview`, previewFile);
setUploading(false);
}
};
const handleSave = async (publish) => {
setSaving(true);
setError("");
try {
const { notes, ...infoWithoutNotes } = information;
const body = {
information: infoWithoutNotes,
default_settings: settings,
type, url, uid, pid,
};
const body = buildBody();
let melodyId = id;
if (isEdit) {
await api.put(`/melodies/${id}`, body);
} else {
const created = await api.post("/melodies", body);
const created = await api.post(`/melodies?publish=${publish}`, body);
melodyId = created.id;
}
if (binaryFile || previewFile) {
setUploading(true);
if (binaryFile) await api.upload(`/melodies/${melodyId}/upload/binary`, binaryFile);
if (previewFile) await api.upload(`/melodies/${melodyId}/upload/preview`, previewFile);
setUploading(false);
}
await uploadFiles(melodyId);
navigate(`/melodies/${melodyId}`);
} catch (err) {
setError(err.message);
@@ -186,6 +194,46 @@ export default function MelodyForm() {
}
};
const handlePublishAction = async () => {
setSaving(true);
setError("");
try {
const body = buildBody();
await api.put(`/melodies/${id}`, body);
await uploadFiles(id);
await api.post(`/melodies/${id}/publish`);
navigate(`/melodies/${id}`);
} catch (err) {
setError(err.message);
setUploading(false);
} finally {
setSaving(false);
}
};
const handleUnpublishAction = async () => {
setSaving(true);
setError("");
try {
await api.post(`/melodies/${id}/unpublish`);
navigate(`/melodies/${id}`);
} catch (err) {
setError(err.message);
} finally {
setSaving(false);
}
};
const handleSubmit = async (e) => {
e.preventDefault();
// Default form submit: save as draft for new, update for existing
if (isEdit) {
await handleSave(false);
} else {
await handleSave(false);
}
};
if (loading) {
return <div className="text-center py-8" style={mutedStyle}>Loading...</div>;
}
@@ -214,15 +262,70 @@ export default function MelodyForm() {
>
Cancel
</button>
<button
type="submit"
form="melody-form"
disabled={saving || uploading}
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
>
{uploading ? "Uploading files..." : saving ? "Saving..." : isEdit ? "Update Melody" : "Create Melody"}
</button>
{!isEdit ? (
<>
<button
type="submit"
form="melody-form"
disabled={saving || uploading}
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-primary)", border: "1px solid var(--border-primary)" }}
>
{saving ? "Saving..." : "Save as Draft"}
</button>
<button
type="button"
disabled={saving || uploading}
onClick={() => handleSave(true)}
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
>
{uploading ? "Uploading files..." : "Publish Melody"}
</button>
</>
) : melodyStatus === "draft" ? (
<>
<button
type="submit"
form="melody-form"
disabled={saving || uploading}
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-primary)", border: "1px solid var(--border-primary)" }}
>
{saving ? "Saving..." : "Update Draft"}
</button>
<button
type="button"
disabled={saving || uploading}
onClick={handlePublishAction}
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
style={{ backgroundColor: "#16a34a", color: "#fff" }}
>
{uploading ? "Uploading files..." : "Publish"}
</button>
</>
) : (
<>
<button
type="submit"
form="melody-form"
disabled={saving || uploading}
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
>
{uploading ? "Uploading files..." : saving ? "Saving..." : "Update Melody"}
</button>
<button
type="button"
disabled={saving || uploading}
onClick={handleUnpublishAction}
className="px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
style={{ backgroundColor: "#ea580c", color: "#fff" }}
>
Unpublish
</button>
</>
)}
</div>
</div>

View File

@@ -16,6 +16,7 @@ const MELODY_TONES = ["", "normal", "festive", "cheerful", "lamentation"];
// All available columns with their defaults
const ALL_COLUMNS = [
{ key: "status", label: "Status", defaultOn: true },
{ key: "color", label: "Color", defaultOn: true },
{ key: "name", label: "Name", defaultOn: true, alwaysOn: true },
{ key: "description", label: "Description", defaultOn: false },
@@ -56,9 +57,12 @@ export default function MelodyList() {
const [search, setSearch] = useState("");
const [typeFilter, setTypeFilter] = useState("");
const [toneFilter, setToneFilter] = useState("");
const [statusFilter, setStatusFilter] = useState("");
const [displayLang, setDisplayLang] = useState("en");
const [melodySettings, setMelodySettings] = useState(null);
const [deleteTarget, setDeleteTarget] = useState(null);
const [unpublishTarget, setUnpublishTarget] = useState(null);
const [actionLoading, setActionLoading] = useState(null);
const [visibleColumns, setVisibleColumns] = useState(getDefaultVisibleColumns);
const [showColumnPicker, setShowColumnPicker] = useState(false);
const columnPickerRef = useRef(null);
@@ -94,6 +98,7 @@ export default function MelodyList() {
if (search) params.set("search", search);
if (typeFilter) params.set("type", typeFilter);
if (toneFilter) params.set("tone", toneFilter);
if (statusFilter) params.set("status", statusFilter);
const qs = params.toString();
const data = await api.get(`/melodies${qs ? `?${qs}` : ""}`);
setMelodies(data.melodies);
@@ -107,7 +112,7 @@ export default function MelodyList() {
useEffect(() => {
fetchMelodies();
}, [search, typeFilter, toneFilter]);
}, [search, typeFilter, toneFilter, statusFilter]);
const handleDelete = async () => {
if (!deleteTarget) return;
@@ -121,6 +126,33 @@ export default function MelodyList() {
}
};
const handlePublish = async (row) => {
setActionLoading(row.id);
try {
await api.post(`/melodies/${row.id}/publish`);
fetchMelodies();
} catch (err) {
setError(err.message);
} finally {
setActionLoading(null);
}
};
const handleUnpublish = async () => {
if (!unpublishTarget) return;
setActionLoading(unpublishTarget.id);
try {
await api.post(`/melodies/${unpublishTarget.id}/unpublish`);
setUnpublishTarget(null);
fetchMelodies();
} catch (err) {
setError(err.message);
setUnpublishTarget(null);
} finally {
setActionLoading(null);
}
};
const toggleColumn = (key) => {
const col = ALL_COLUMNS.find((c) => c.key === key);
if (col?.alwaysOn) return;
@@ -142,6 +174,18 @@ export default function MelodyList() {
const info = row.information || {};
const ds = row.default_settings || {};
switch (key) {
case "status":
return (
<span
className="px-2 py-0.5 text-xs font-semibold rounded-full"
style={row.status === "published"
? { backgroundColor: "rgba(22,163,74,0.15)", color: "#22c55e" }
: { backgroundColor: "rgba(156,163,175,0.15)", color: "#9ca3af" }
}
>
{row.status === "published" ? "Live" : "Draft"}
</span>
);
case "color":
return info.color ? (
<span
@@ -293,6 +337,15 @@ export default function MelodyList() {
</option>
))}
</select>
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className={selectClass}
>
<option value="">All Statuses</option>
<option value="published">Published (Live)</option>
<option value="draft">Drafts</option>
</select>
{languages.length > 1 && (
<select
value={displayLang}
@@ -440,6 +493,25 @@ export default function MelodyList() {
className="flex gap-2"
onClick={(e) => e.stopPropagation()}
>
{row.status === "draft" ? (
<button
onClick={() => handlePublish(row)}
disabled={actionLoading === row.id}
className="text-xs cursor-pointer disabled:opacity-50"
style={{ color: "#22c55e" }}
>
{actionLoading === row.id ? "..." : "Publish"}
</button>
) : (
<button
onClick={() => setUnpublishTarget(row)}
disabled={actionLoading === row.id}
className="text-xs cursor-pointer disabled:opacity-50"
style={{ color: "#ea580c" }}
>
Unpublish
</button>
)}
<button
onClick={() => navigate(`/melodies/${row.id}/edit`)}
className="text-xs cursor-pointer"
@@ -472,6 +544,14 @@ export default function MelodyList() {
onConfirm={handleDelete}
onCancel={() => setDeleteTarget(null)}
/>
<ConfirmDialog
open={!!unpublishTarget}
title="Unpublish Melody"
message={`This melody may be in use by devices. Unpublishing will remove "${getDisplayName(unpublishTarget?.information?.name)}" from Firestore and devices will no longer have access. The melody will be kept as a draft. Continue?`}
onConfirm={handleUnpublish}
onCancel={() => setUnpublishTarget(null)}
/>
</div>
);
}