diff --git a/NOTIFICATIONS.md b/NOTIFICATIONS.md index 2815c9c..b4f447c 100644 --- a/NOTIFICATIONS.md +++ b/NOTIFICATIONS.md @@ -4,9 +4,16 @@ Every notification in Homelab Manager is sent through the same pipe (`server/src/services/notify.ts`) to whichever channels are enabled under **Settings → Notifications**: Gotify, ntfy, SMTP (email), and a generic JSON webhook. All four fire for every notification below — there's no -per-event channel routing, only a per-event on/off toggle (the "Notify -on" list on that same page) and, for the daily ones, one shared -time/timezone. +per-event channel routing, only a per-event on/off toggle and, for the +daily ones, one shared time/timezone. + +The settings page has three tabs, with one Save button for all of them (it +shows "Unsaved changes" until you save, and the browser asks before the page +is closed with changes unsaved): **Channels** (the four channels, each a row +you open to fill in and send a test), **What to send** (the event toggles +grouped by topic, each group's thresholds beside its switches) and **When** +(the time zone, the daily reminder time, quiet hours and the weekly digest). +The address keeps the tab, e.g. `/settings/notifications?tab=when`. Two settings apply to *every* notification regardless of what triggered it: diff --git a/web/src/pages/settings/NotificationSettings.tsx b/web/src/pages/settings/NotificationSettings.tsx index fc186a3..ffe5a75 100644 --- a/web/src/pages/settings/NotificationSettings.tsx +++ b/web/src/pages/settings/NotificationSettings.tsx @@ -1,4 +1,5 @@ -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; +import { useSearchParams } from "react-router-dom"; import { api, type AppSettings, @@ -74,6 +75,14 @@ const DIGEST_DAYS: { value: number; label: string }[] = [ const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14 }; type TestResult = { ok: boolean; message: string } | null; +type EventKey = { [K in keyof NotificationEvents]: NotificationEvents[K] extends boolean ? K : never }[keyof NotificationEvents]; + +const TABS = [ + { id: "channels", label: "Channels" }, + { id: "events", label: "What to send" }, + { id: "when", label: "When" }, +] as const; +type TabId = (typeof TABS)[number]["id"]; function TestBadge({ result }: { result: TestResult }) { if (!result) return null; @@ -84,12 +93,126 @@ function TestBadge({ result }: { result: TestResult }) { ); } +/** The host of an address, for a channel's one-line summary — never the whole address, which can carry a token. */ +function hostOf(address: string): string { + try { + return new URL(address).host; + } catch { + return address; + } +} + +/** One channel in the list: its name, whether it is on and filled in, and (opened) its settings. */ +function ChannelRow({ + name, + description, + enabled, + onToggle, + summary, + complete, + open, + onOpen, + children, +}: { + name: string; + description: ReactNode; + enabled: boolean; + onToggle: (on: boolean) => void; + /** What it is set to send to, once filled in ("elsa.lab", "my-topic"). */ + summary: string; + complete: boolean; + open: boolean; + onOpen: () => void; + children: ReactNode; +}) { + const panelId = `channel-${name.replace(/\W+/g, "-").toLowerCase()}`; + return ( +
+
+
+ +
+
+ {name}{" "} + {enabled && complete && On} + {enabled && !complete && On, but not filled in} + {!enabled && complete && Off} + {!enabled && !complete && Not set up} +
+
{complete && summary ? summary : description}
+
+ +
+
+ {open && ( +
+ {complete && summary &&

{description}

} + {children} +
+ )} +
+ ); +} + +function EventToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (on: boolean) => void }) { + return ( + + ); +} + +function NumberField({ + label, + value, + min, + max, + unit, + hint, + disabled, + onChange, +}: { + label: string; + value: number; + min: number; + max: number; + unit: string; + hint?: ReactNode; + disabled?: boolean; + onChange: (value: number) => void; +}) { + return ( +
+ +
+ onChange(Number(e.target.value))} /> + {unit} +
+ {hint &&
{hint}
} +
+ ); +} + export default function NotificationSettings() { + const [params, setParams] = useSearchParams(); + const tabParam = params.get("tab"); + const tab: TabId = TABS.some((t) => t.id === tabParam) ? (tabParam as TabId) : "channels"; + const tabRefs = useRef>({}); + const [openChannel, setOpenChannel] = useState(null); + const [loading, setLoading] = useState(true); const [loadError, setLoadError] = useState(null); const [saving, setSaving] = useState(false); const [saved, setSaved] = useState(false); const [saveError, setSaveError] = useState(null); + /** The settings as last loaded or saved, so what has been changed since can be told. */ + const [baseline, setBaseline] = useState(null); const [gotify, setGotify] = useState(DEFAULT_GOTIFY); const [ntfy, setNtfy] = useState(DEFAULT_NTFY); @@ -115,18 +238,24 @@ export default function NotificationSettings() { const [testingWebhook, setTestingWebhook] = useState(false); const [testWebhookResult, setTestWebhookResult] = useState(null); + const snapshot = JSON.stringify({ gotify, ntfy, smtp, webhook, notifications, quietHours, healthChecks, digest }); + const dirty = baseline !== null && snapshot !== baseline; + useEffect(() => { api.settings .get() .then((res: { settings: AppSettings }) => { - setGotify(res.settings.gotify); - setNtfy(res.settings.ntfy); - setSmtp(res.settings.smtp); - setWebhook(res.settings.webhook); - setNotifications(res.settings.notifications); - setQuietHours(res.settings.quietHours); - setHealthChecks(res.settings.healthChecks); - setDigest(res.settings.digest ?? DEFAULT_DIGEST); + const s = res.settings; + setGotify(s.gotify); + setNtfy(s.ntfy); + setSmtp(s.smtp); + setWebhook(s.webhook); + setNotifications(s.notifications); + setQuietHours(s.quietHours); + setHealthChecks(s.healthChecks); + const d = s.digest ?? DEFAULT_DIGEST; + setDigest(d); + setBaseline(JSON.stringify({ gotify: s.gotify, ntfy: s.ntfy, smtp: s.smtp, webhook: s.webhook, notifications: s.notifications, quietHours: s.quietHours, healthChecks: s.healthChecks, digest: d })); }) .catch((err) => setLoadError(err instanceof Error ? err.message : String(err))) .finally(() => setLoading(false)); @@ -136,12 +265,45 @@ export default function NotificationSettings() { .catch(() => {}); }, []); + // The browser asks before the tab is closed or reloaded with changes that haven't been saved. + useEffect(() => { + if (!dirty) return; + const warn = (e: BeforeUnloadEvent) => { + e.preventDefault(); + e.returnValue = ""; + }; + window.addEventListener("beforeunload", warn); + return () => window.removeEventListener("beforeunload", warn); + }, [dirty]); + + function selectTab(id: TabId) { + setParams( + (prev) => { + const next = new URLSearchParams(prev); + if (id === "channels") next.delete("tab"); + else next.set("tab", id); + return next; + }, + { replace: true }, + ); + } + + function onTabKey(e: KeyboardEvent) { + const at = TABS.findIndex((t) => t.id === tab); + const to = e.key === "ArrowRight" ? (at + 1) % TABS.length : e.key === "ArrowLeft" ? (at + TABS.length - 1) % TABS.length : e.key === "Home" ? 0 : e.key === "End" ? TABS.length - 1 : -1; + if (to === -1) return; + e.preventDefault(); + selectTab(TABS[to].id); + tabRefs.current[TABS[to].id]?.focus(); + } + async function handleSave() { setSaving(true); setSaveError(null); setSaved(false); try { await api.settings.update({ gotify, ntfy, smtp, webhook, notifications, quietHours, healthChecks, digest }); + setBaseline(snapshot); setSaved(true); setTimeout(() => setSaved(false), 3000); } catch (err) { @@ -245,599 +407,469 @@ export default function NotificationSettings() { if (loading) return ; + const gotifyComplete = !!(gotify.url && gotify.token); + const ntfyComplete = !!(ntfy.url && ntfy.topic); + const smtpComplete = !!(smtp.host && smtp.from && smtp.to); + const webhookComplete = !!webhook.url; + const channelsOn = [gotify.enabled && gotifyComplete, ntfy.enabled && ntfyComplete, smtp.enabled && smtpComplete, webhook.enabled && webhookComplete].filter(Boolean).length; + + const toggle = (key: EventKey, label: string) => setNotifications((n) => ({ ...n, [key]: on }))} />; + const dailyChecksEnabled = notifications.secretCheck || notifications.tailscaleKeyCheck || notifications.dockerUpdateCheck || notifications.proxmoxBackupCheck || notifications.pbsVerificationCheck || notifications.domainExpiryCheck; + return ( <> -
-

Notifications

-
- {saveError && {saveError}} - {saved && ✓ Settings saved} - +
+
+

Notifications

+
+ {saveError && {saveError}} + {saved && ✓ Settings saved} + {dirty && !saved && Unsaved changes} + +
+
    + {TABS.map((t) => ( +
  • + +
  • + ))} +
-
-
-
-
-

Gotify

+ {/* ── Channels ── */} +