feat(notifications): node-config-style channel manager + lock disabled-channel opt-in

Settings → 通知 now mirrors the node-config UX: info-only channel cards
(name / id / url / template + an inline enable toggle), create + edit via a
dialog, and all changes debounced-auto-save (no save button). The save path
is generation-guarded so a superseded in-flight save can't clobber a newer
edit; the test action flushes the pending save first so it never hits an
unsaved channel. The channel id is locked while editing to keep per-account
channelIds references from orphaning.

Per-account opt-in: a globally-disabled channel's toggle is now locked +
forced off (it can never fire). The id is kept in channelIds — the backend
already filters disabled channels — so re-enabling globally restores the
prior selection.

New: notification-channel-dialog.tsx. webui typecheck + build green.
Adversarial review: 0 blockers / 0 should-fix (2 nits applied).
This commit is contained in:
DrSmoothl committed 2026-06-16 21:54:19 +08:00
1 parent 0b7fb0c69d
commit f014defd54
3 files changed
+390 -175

No files matched your search

@@ -71,9 +71,12 @@ export function NotificationOptIn({ selectedIds, onChange }: NotificationOptInPr
<p className="truncate text-[11px] text-muted-foreground">{ch.url}</p>
</div>
<ToggleSwitch
value={selected.has(ch.id)}
// Globally-disabled channel: lock the switch and force it off
// (it can never fire, so the per-account opt-in must read off).
value={ch.enabled && selected.has(ch.id)}
onChange={(v) => toggle(ch.id, v)}
ariaLabel={`为该账号启用渠道 ${ch.name || ch.id}`}
disabled={!ch.enabled}
/>
</div>
))}
@@ -0,0 +1,176 @@
// Modal editor for a notification channel — used for both create and edit,
// mirroring NodeEditDialog. Holds a local draft until 保存 (cancel discards).
// The channel id is the stable key per-account opt-ins reference, so it's
// editable only on create and locked on edit.
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { cn } from '@/lib/utils';
import type { NotificationChannel } from '@/types';
const CHANNEL_ID_RE = /^[\w.-]+$/;
function isHttpUrl(u: string): boolean {
try {
const x = new URL(u.trim());
return x.protocol === 'http:' || x.protocol === 'https:';
} catch {
return false;
}
}
interface NotificationChannelDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
isEdit: boolean;
/** Seed draft — a blank channel for create, the existing one for edit. */
initial: NotificationChannel;
/** Ids of every other channel, for the duplicate check. */
otherIds: string[];
onSubmit: (channel: NotificationChannel) => void;
}
export function NotificationChannelDialog(props: NotificationChannelDialogProps) {
const { open, onOpenChange, isEdit, initial, otherIds, onSubmit } = props;
// Parent unmounts on close, so each open re-seeds via lazy init.
const [draft, setDraft] = useState<NotificationChannel>(initial);
const patch = (p: Partial<NotificationChannel>) => setDraft({ ...draft, ...p });
const id = draft.id.trim();
const idBlank = id.length === 0;
const idBad = !idBlank && (!CHANNEL_ID_RE.test(id) || id.length > 64);
const idDup = !idBlank && otherIds.includes(id);
const urlBlank = draft.url.trim().length === 0;
const urlBad = !urlBlank && !isHttpUrl(draft.url);
const canSave = !idBlank && !idBad && !idDup && !urlBlank && !urlBad;
const idError = idBlank
? '请填写渠道 ID'
: idBad
? '只能用字母 / 数字 / . _ - ,≤64 字符'
: idDup
? 'ID 与其它渠道重复'
: undefined;
const urlError = urlBlank ? '请填写 Webhook URL' : urlBad ? '必须是 http(s) 地址' : undefined;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-xl">
<DialogHeader>
<DialogTitle>{isEdit ? '编辑渠道' : '新建渠道'}</DialogTitle>
<DialogDescription>账号上线 / 下线时向该 Webhook POST 一条渲染后的通知。</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-3">
<div className="grid gap-3 sm:grid-cols-2">
<Field
label="渠道 ID"
placeholder="dingtalk"
value={draft.id}
disabled={isEdit}
hint={isEdit ? '创建后不可更改' : '账号据此勾选;字母/数字/. _ -'}
error={idError}
onChange={(v) => patch({ id: v })}
/>
<Field
label="显示名"
placeholder="钉钉群机器人"
value={draft.name}
onChange={(v) => patch({ name: v })}
/>
</div>
<Field
label="Webhook URL"
type="url"
placeholder="https://oapi.dingtalk.com/robot/send?access_token=…"
value={draft.url}
error={urlError}
onChange={(v) => patch({ url: v })}
/>
<div className="flex flex-col gap-1.5">
<Label>Body 模板</Label>
<textarea
value={draft.bodyTemplate}
rows={3}
spellCheck={false}
onChange={(e) => patch({ bodyTemplate: e.target.value })}
className="w-full rounded-md border border-border bg-transparent px-3 py-2 font-mono text-xs leading-relaxed shadow-xs outline-none transition-[color,box-shadow] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40"
/>
<p className="text-[11px] leading-relaxed text-muted-foreground">
变量:<code className="font-mono">{'{uin}'}</code> <code className="font-mono">{'{nickname}'}</code>{' '}
<code className="font-mono">{'{event}'}</code>(offline/online) <code className="font-mono">{'{time}'}</code>
</p>
</div>
<div className="flex items-center justify-between rounded-lg border bg-card/40 p-3">
<div className="min-w-0">
<Label className="text-sm">启用</Label>
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
关闭后保留配置但不推送;账号侧对应开关会被锁定并关闭。
</p>
</div>
<ToggleSwitch value={draft.enabled} onChange={(v) => patch({ enabled: v })} ariaLabel="启用渠道" />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
取消
</Button>
<Button
disabled={!canSave}
onClick={() => {
onSubmit({ ...draft, id, name: draft.name.trim(), url: draft.url.trim() });
onOpenChange(false);
}}
>
{isEdit ? '保存修改' : '创建渠道'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
interface FieldProps {
label: string;
value: string;
onChange: (v: string) => void;
placeholder?: string;
type?: 'text' | 'url';
error?: string;
hint?: string;
disabled?: boolean;
}
function Field({ label, value, onChange, placeholder, type = 'text', error, hint, disabled }: FieldProps) {
return (
<div className="flex flex-col gap-1.5">
<Label>{label}</Label>
<Input
type={type}
value={value}
disabled={disabled}
placeholder={placeholder}
onChange={(e) => onChange(e.target.value)}
className={cn(error && 'border-destructive focus-visible:ring-destructive/40', disabled && 'opacity-60')}
/>
{error ? (
<p className="text-[11px] text-destructive">{error}</p>
) : hint ? (
<p className="text-[11px] text-muted-foreground">{hint}</p>
) : null}
</div>
);
}
@@ -1,41 +1,54 @@
// Settings → 通知 tab. Global webhook-channel store (CRUD + per-channel test
// send) and the global debounce window. Channels are global; each account opts
// in from its own Config page. The server total-normalizes on save (a channel
// with an invalid slug id or a non-http(s) URL is dropped), so after 保存 the
// list reflects exactly what was accepted.
import { useEffect, useMemo, useState } from 'react';
import { Bell, Loader2, Plus, Send, Trash2 } from 'lucide-react';
// Settings → 通知 tab. Mirrors the node-config UX: the first screen is
// info-only cards (name / url / template + an inline enable toggle); creating
// and editing always go through a dialog. All changes auto-save (debounced),
// like the per-account config page — no explicit save button.
import { useEffect, useRef, useState } from 'react';
import { motion } from 'motion/react';
import { Bell, Loader2, Pencil, Plus, Send, Trash2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { useApi } from '@/lib/api';
import { useTheme } from '@/contexts/ThemeContext';
import { cn } from '@/lib/utils';
import type { NotificationChannel, NotificationsConfig } from '@/types';
import { NotificationChannelDialog } from './notification-channel-dialog';
const DEFAULT_TEMPLATE = '{nickname}({uin}) {event} @ {time}';
function blankChannel(n: number): NotificationChannel {
/** A fresh channel with a non-colliding default id. */
function blankChannel(existing: NotificationChannel[]): NotificationChannel {
const used = new Set(existing.map((c) => c.id));
let n = existing.length + 1;
while (used.has(`channel-${n}`)) n += 1;
return { id: `channel-${n}`, name: '', url: '', bodyTemplate: DEFAULT_TEMPLATE, enabled: true };
}
interface DialogState {
open: boolean;
index: number | null; // null → create
seed: NotificationChannel;
}
export function NotificationsPanel() {
const api = useApi();
const [config, setConfig] = useState<NotificationsConfig | null>(null);
const [saved, setSaved] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [dialog, setDialog] = useState<DialogState>({ open: false, index: null, seed: blankChannel([]) });
const [testing, setTesting] = useState<string | null>(null);
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
const saveTimer = useRef<number | null>(null);
const msgTimer = useRef<number | null>(null);
const saveGen = useRef(0);
useEffect(() => {
let cancelled = false;
void (async () => {
try {
const cfg = await api.notifications.getConfig();
if (cancelled) return;
setConfig(cfg);
setSaved(JSON.stringify(cfg));
if (!cancelled) setConfig(cfg);
} catch {
if (!cancelled) setMsg({ kind: 'err', text: '加载通知配置失败' });
} finally {
@@ -47,7 +60,39 @@ export function NotificationsPanel() {
};
}, [api]);
const dirty = useMemo(() => (config ? JSON.stringify(config) !== saved : false), [config, saved]);
useEffect(
() => () => {
if (saveTimer.current) clearTimeout(saveTimer.current);
if (msgTimer.current) clearTimeout(msgTimer.current);
},
[],
);
const flash = (kind: 'ok' | 'err', text: string) => {
setMsg({ kind, text });
if (msgTimer.current) clearTimeout(msgTimer.current);
msgTimer.current = window.setTimeout(() => setMsg(null), 2400);
};
/** Apply locally + debounced auto-save. A generation guard reconciles with
* the server's normalized result only if no newer edit landed meanwhile. */
const commit = (next: NotificationsConfig) => {
setConfig(next);
const gen = ++saveGen.current;
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = window.setTimeout(() => {
void api.notifications
.saveConfig(next)
.then((result) => {
// Only the latest save reconciles + confirms; a superseded in-flight
// save stays silent (its successor will confirm).
if (saveGen.current !== gen) return;
setConfig(result);
flash('ok', '已保存');
})
.catch(() => flash('err', '保存失败,请检查服务器日志'));
}, 350);
};
if (loading || !config) {
return (
@@ -57,47 +102,30 @@ export function NotificationsPanel() {
);
}
const patch = (p: Partial<NotificationsConfig>) => setConfig({ ...config, ...p });
const patchChannel = (i: number, p: Partial<NotificationChannel>) =>
setConfig({ ...config, channels: config.channels.map((c, idx) => (idx === i ? { ...c, ...p } : c)) });
const addChannel = () => {
// Avoid a default id colliding with an existing one (e.g. after deletes),
// which the server would dedup-drop on save.
const used = new Set(config.channels.map((c) => c.id));
let n = config.channels.length + 1;
while (used.has(`channel-${n}`)) n += 1;
setConfig({ ...config, channels: [...config.channels, blankChannel(n)] });
};
const removeChannel = (i: number) =>
setConfig({ ...config, channels: config.channels.filter((_, idx) => idx !== i) });
const channels = config.channels;
const setChannels = (next: NotificationChannel[]) => commit({ ...config, channels: next });
const otherIds = (index: number | null) => channels.filter((_, i) => i !== index).map((c) => c.id);
const save = async () => {
setSaving(true);
setMsg(null);
try {
const result = await api.notifications.saveConfig(config);
setConfig(result);
setSaved(JSON.stringify(result));
const dropped = config.channels.length - result.channels.length;
setMsg({
kind: 'ok',
text: dropped > 0 ? `已保存(${dropped} 个无效渠道被丢弃,需有效 slug id + http(s) URL)` : '已保存',
});
} catch {
setMsg({ kind: 'err', text: '保存失败,请检查服务器日志' });
} finally {
setSaving(false);
}
const openCreate = () => setDialog({ open: true, index: null, seed: blankChannel(channels) });
const openEdit = (i: number) => setDialog({ open: true, index: i, seed: channels[i] });
const submitChannel = (ch: NotificationChannel) => {
if (dialog.index == null) setChannels([...channels, ch]);
else setChannels(channels.map((c, idx) => (idx === dialog.index ? ch : c)));
};
const test = async (id: string) => {
setTesting(id);
setMsg(null);
// Persist any pending edit first — the server tests the stored channel by id.
if (saveTimer.current) {
clearTimeout(saveTimer.current);
saveTimer.current = null;
}
try {
await api.notifications.saveConfig(config);
const res = await api.notifications.test(id);
setMsg({ kind: res.success ? 'ok' : 'err', text: res.message ?? (res.success ? '测试发送成功' : '测试发送失败') });
flash(res.success ? 'ok' : 'err', res.message ?? (res.success ? '测试发送成功' : '测试发送失败'));
} catch {
setMsg({ kind: 'err', text: '测试请求失败' });
flash('err', '测试请求失败');
} finally {
setTesting(null);
}
@@ -105,140 +133,148 @@ export function NotificationsPanel() {
return (
<div className="flex flex-col gap-4">
<div className="flex items-start gap-2 rounded-lg border bg-card/40 p-4 text-[11px] leading-relaxed text-muted-foreground">
<Bell className="mt-0.5 size-3.5 shrink-0" />
<p>
账号上线 / 下线时,向启用的渠道 POST 一条渲染后的通知(机械转发,仅去抖防刷屏)。渠道在此全局定义,
每个账号在其「配置」页勾选启用哪些。模板变量:
<code className="font-mono">{'{uin}'}</code> <code className="font-mono">{'{nickname}'}</code>{' '}
<code className="font-mono">{'{event}'}</code>(offline/online) <code className="font-mono">{'{time}'}</code>。
</p>
</div>
{/* Global debounce */}
<div className="flex flex-col gap-1.5 rounded-lg border bg-card/40 p-4">
<Label>去抖窗口(秒)</Label>
<Input
type="number"
min={0}
max={3600}
className="w-32 tabular-nums"
value={config.debounceSeconds}
onChange={(e) => {
const n = Math.trunc(Number(e.target.value));
patch({ debounceSeconds: Number.isFinite(n) ? Math.min(3600, Math.max(0, n)) : 0 });
}}
/>
<p className="text-[11px] leading-relaxed text-muted-foreground">
下线后在该秒数内自愈则不发(抑制闪断);超时才发「下线」,恢复时再发「上线」。<code className="font-mono">0</code> 表示不去抖、立即发。
</p>
{/* Global settings */}
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
<div className="flex items-start gap-2 text-[11px] leading-relaxed text-muted-foreground">
<Bell className="mt-0.5 size-3.5 shrink-0" />
<p>
账号上线 / 下线时向启用的渠道 POST 一条通知(机械转发,仅去抖防刷屏)。渠道在此全局定义,每个账号在其「配置」页勾选启用哪些。
</p>
</div>
<div className="flex flex-col gap-1.5 border-t pt-3">
<Label>去抖窗口(秒)</Label>
<Input
type="number"
min={0}
max={3600}
className="w-32 tabular-nums"
value={config.debounceSeconds}
onChange={(e) => {
const n = Math.trunc(Number(e.target.value));
commit({ ...config, debounceSeconds: Number.isFinite(n) ? Math.min(3600, Math.max(0, n)) : 0 });
}}
/>
<p className="text-[11px] leading-relaxed text-muted-foreground">
下线后在该秒数内自愈则不发;超时才发「下线」,恢复时再发「上线」。<code className="font-mono">0</code> = 立即发、不去抖。
</p>
</div>
</div>
{/* Channels */}
<div className="flex flex-col gap-3">
{config.channels.length === 0 && (
<p className="rounded-lg border border-dashed bg-card/20 p-6 text-center text-sm text-muted-foreground">
还没有渠道。点下方「新增渠道」添加一个 webhook。
</p>
)}
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold tracking-tight">通知渠道</h3>
{channels.length > 0 && (
<Button variant="outline" size="sm" onClick={openCreate}>
<Plus className="size-3.5" /> 新增渠道
</Button>
)}
</div>
{config.channels.map((ch, i) => (
<div key={i} className="flex flex-col gap-3 rounded-lg border bg-card/40 p-4">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<ToggleSwitch
value={ch.enabled}
onChange={(v) => patchChannel(i, { enabled: v })}
ariaLabel={`启用渠道 ${ch.name || ch.id}`}
/>
<span className={cn('text-sm font-medium', ch.enabled ? undefined : 'text-muted-foreground')}>
{ch.name || ch.id || '未命名渠道'}
</span>
</div>
<div className="flex items-center gap-1.5">
<Button
type="button"
variant="outline"
size="sm"
disabled={dirty || testing === ch.id}
title={dirty ? '请先保存再测试' : '向该渠道发送一条测试消息'}
onClick={() => void test(ch.id)}
>
{testing === ch.id ? <Loader2 className="size-3.5 animate-spin" /> : <Send className="size-3.5" />}
测试
</Button>
<Button
type="button"
variant="ghost"
size="sm"
aria-label="删除渠道"
onClick={() => removeChannel(i)}
>
<Trash2 className="size-3.5" />
</Button>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label className="text-xs">渠道 ID(slug,账号据此勾选)</Label>
<Input
value={ch.id}
placeholder="dingtalk"
onChange={(e) => patchChannel(i, { id: e.target.value })}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-xs">显示名</Label>
<Input
value={ch.name}
placeholder="钉钉群机器人"
onChange={(e) => patchChannel(i, { name: e.target.value })}
/>
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-xs">Webhook URL(http/https)</Label>
<Input
type="url"
value={ch.url}
placeholder="https://oapi.dingtalk.com/robot/send?access_token=…"
onChange={(e) => patchChannel(i, { url: e.target.value })}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-xs">Body 模板</Label>
<textarea
value={ch.bodyTemplate}
rows={3}
spellCheck={false}
onChange={(e) => patchChannel(i, { bodyTemplate: e.target.value })}
className={cn(
'w-full rounded-md border border-border bg-transparent px-3 py-2 font-mono text-xs leading-relaxed shadow-xs outline-none transition-[color,box-shadow]',
'placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40',
)}
/>
</div>
{channels.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16 text-muted-foreground">
<Bell className="size-8 opacity-40" strokeWidth={1.5} />
<p className="text-sm">还没有通知渠道</p>
<Button variant="outline" size="sm" onClick={openCreate}>
<Plus className="size-3.5" /> 创建第一个
</Button>
</div>
) : (
<div className="flex flex-col gap-2">
{channels.map((ch, i) => (
<ChannelCard
key={ch.id}
channel={ch}
testing={testing === ch.id}
onToggle={(v) => setChannels(channels.map((c, idx) => (idx === i ? { ...c, enabled: v } : c)))}
onTest={() => void test(ch.id)}
onEdit={() => openEdit(i)}
onDelete={() => setChannels(channels.filter((_, idx) => idx !== i))}
/>
))}
</div>
))}
<Button type="button" variant="outline" size="sm" className="self-start" onClick={addChannel}>
<Plus className="size-3.5" /> 新增渠道
</Button>
</div>
{/* Save bar */}
<div className="flex items-center gap-3 border-t pt-4">
<Button type="button" disabled={!dirty || saving} onClick={() => void save()}>
{saving && <Loader2 className="size-3.5 animate-spin" />} 保存
</Button>
{dirty && <span className="text-[11px] text-muted-foreground">有未保存的更改</span>}
{msg && (
<span className={cn('text-xs', msg.kind === 'ok' ? 'text-emerald-500' : 'text-destructive')}>{msg.text}</span>
)}
</div>
{msg && <p className={cn('text-xs', msg.kind === 'ok' ? 'text-success' : 'text-destructive')}>{msg.text}</p>}
{dialog.open && (
<NotificationChannelDialog
open={dialog.open}
onOpenChange={(open) => !open && setDialog((d) => ({ ...d, open: false }))}
isEdit={dialog.index != null}
initial={dialog.seed}
otherIds={otherIds(dialog.index)}
onSubmit={submitChannel}
/>
)}
</div>
);
}
interface ChannelCardProps {
channel: NotificationChannel;
testing: boolean;
onToggle: (v: boolean) => void;
onTest: () => void;
onEdit: () => void;
onDelete: () => void;
}
/** Info-only row + inline actions. No live-typed fields — editing is the dialog. */
function ChannelCard({ channel, testing, onToggle, onTest, onEdit, onDelete }: ChannelCardProps) {
const off = useTheme().appearance.disableMotion;
return (
<motion.div
initial={off ? false : { opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
transition={off ? { duration: 0 } : { duration: 0.18 }}
className={cn(
'flex flex-col gap-2 rounded-xl border bg-card/40 p-3.5 transition-all hover:bg-accent/20 sm:flex-row sm:items-center sm:gap-3',
!channel.enabled && 'opacity-60',
)}
>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">{channel.name || channel.id}</span>
<Badge variant="secondary" className="font-mono font-normal">{channel.id}</Badge>
{!channel.enabled && <Badge variant="secondary" className="font-normal">已停用</Badge>}
</div>
<div className="mt-0.5 truncate font-mono text-xs text-muted-foreground">{channel.url}</div>
<div className="mt-1 truncate font-mono text-[11px] text-muted-foreground/80">{channel.bodyTemplate}</div>
</div>
<div className="flex items-center gap-1.5 sm:justify-end">
<ToggleSwitch value={channel.enabled} onChange={onToggle} ariaLabel={`启用 ${channel.name || channel.id}`} />
<Button
variant="ghost"
size="icon-sm"
onClick={onTest}
disabled={testing}
aria-label="测试发送"
className="text-muted-foreground hover:text-foreground"
>
{testing ? <Loader2 className="size-4 animate-spin" /> : <Send className="size-4" />}
</Button>
<Button
variant="ghost"
size="icon-sm"
onClick={onEdit}
aria-label="编辑"
className="text-muted-foreground hover:text-foreground"
>
<Pencil className="size-4" />
</Button>
<Button
variant="ghost"
size="icon-sm"
onClick={onDelete}
aria-label="删除"
className="text-muted-foreground hover:text-destructive"
>
<Trash2 className="size-4" />
</Button>
</div>
</motion.div>
);
}