import { useCallback, useEffect, useRef, useState } from 'react'; import { motion } from 'motion/react'; import { DEFAULT_WEBHOOK_BODY } from '@snowluma/common/notification-templates'; import { Bell, Loader2, Pencil, Plus, Send, Trash2 } from 'lucide-react'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { SkeletonSwap } from '@/components/interior/skeleton-swap'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { ToggleSwitch } from '@/components/ui/toggle-switch'; import { useActionFeedback } from '@/contexts/ActionFeedbackContext'; import { useApi } from '@/lib/api'; import { useFlashMessage } from '@/hooks/use-flash-message'; import { useTheme } from '@/contexts/ThemeContext'; import { cn } from '@/lib/utils'; import { notificationChannelType, type NotificationChannel, type NotificationsConfig, } from '@/types'; import { NotificationChannelDialog } from './notification-channel-dialog'; /** 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: '', type: 'webhook', url: '', bodyTemplate: DEFAULT_WEBHOOK_BODY, enabled: true, }; } interface DialogState { index: number | null; // null → create seed: NotificationChannel; } export function NotificationsPanel() { const api = useApi(); const { runAction } = useActionFeedback(); const [config, setConfig] = useState(null); const [loading, setLoading] = useState(true); const [dialog, setDialog] = useState(null); const [testing, setTesting] = useState(null); const { msg, flash, setMsg } = useFlashMessage(); const saveTimer = useRef(null); const saveGen = useRef(0); const load = useCallback(async () => { setLoading(true); setMsg(null); try { setConfig(await api.notifications.getConfig()); } catch (error) { console.error('load notifications config failed', error); setMsg({ kind: 'err', text: '加载通知配置失败' }); } finally { setLoading(false); } }, [api, setMsg]); useEffect(() => { void load(); }, [load]); useEffect( () => () => { if (saveTimer.current) { clearTimeout(saveTimer.current); } }, [], ); /** 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, copy: { title: string; successTitle: string } = { title: '正在更新通知配置', successTitle: '通知配置已更新', }, ) => { setConfig(next); const gen = ++saveGen.current; if (saveTimer.current) { clearTimeout(saveTimer.current); } saveTimer.current = window.setTimeout(() => { saveTimer.current = null; void runAction( { title: copy.title, detail: '正在同步通知渠道设置', successTitle: copy.successTitle, successDetail: '通知配置已同步', errorTitle: '通知配置更新失败', }, () => 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((error) => { if (saveGen.current !== gen) { return; } console.error('save notifications config failed', error); flash('err', '保存失败,请检查服务器日志'); }); }, 350); }; if (loading || !config) { return ( {!loading && !config ? (
{msg?.text ?? '加载通知配置失败'}
) : null}
); } const channels = config.channels; const setChannels = ( next: NotificationChannel[], copy?: { title: string; successTitle: string }, ) => commit({ ...config, channels: next }, copy); const otherIds = (index: number | null) => channels.filter((_, i) => i !== index).map((c) => c.id); const openCreate = () => setDialog({ index: null, seed: blankChannel(channels) }); const openEdit = (i: number) => setDialog({ index: i, seed: channels[i] }); const submitChannel = (ch: NotificationChannel, index: number | null) => { if (index === null) { setChannels([...channels, ch], { title: '正在新增通知渠道', successTitle: '通知渠道已新增', }); } else { setChannels( channels.map((c, idx) => (idx === index ? ch : c)), { title: '正在更新通知渠道', successTitle: '通知渠道已更新' }, ); } }; const test = async (id: string) => { setTesting(id); // Persist any pending edit first — the server tests the stored channel by id. if (saveTimer.current) { clearTimeout(saveTimer.current); saveTimer.current = null; } try { const res = await runAction( { title: '正在测试通知渠道', detail: id, successTitle: '测试通知已发送', successDetail: id, errorTitle: '通知渠道测试失败', resultError: (result) => result.success ? null : result.message || '测试发送失败', }, async () => { await api.notifications.saveConfig(config); return api.notifications.test(id); }, ); flash( res.success ? 'ok' : 'err', res.message ?? (res.success ? '测试发送成功' : '测试发送失败'), ); } catch (error) { console.error('test notification channel failed', error); flash('err', '测试请求失败'); } finally { setTesting(null); } }; return (
{/* Global settings */}

在此管理通知渠道,再到账号「配置」页选择启用。

{ const n = Math.trunc(Number(e.target.value)); commit({ ...config, debounceSeconds: Number.isFinite(n) ? Math.min(3600, Math.max(0, n)) : 0, }); }} />

下线持续超过此时长才通知,恢复时再通知。0 表示立即通知。

{/* Channels */}

通知渠道

{channels.length > 0 && ( )}
{channels.length === 0 ? (

还没有通知渠道

) : (
{channels.map((ch, i) => ( setChannels( channels.map((c, idx) => idx === i ? { ...c, enabled: v } : c, ), { title: '正在更新通知渠道', successTitle: '通知渠道已更新', }, ) } onTest={() => void test(ch.id)} onEdit={() => openEdit(i)} onDelete={() => setChannels( channels.filter((_, idx) => idx !== i), { title: '正在删除通知渠道', successTitle: '通知渠道已删除', }, ) } /> ))}
)}
{msg && (

{msg.text}

)} {dialog && ( !open && setDialog(null)} isEdit={dialog.index != null} initial={dialog.seed} otherIds={otherIds(dialog.index)} onSubmit={(channel) => submitChannel(channel, dialog.index)} /> )}
); } 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 (
{channel.name || channel.id} {channel.id} {notificationChannelType(channel) === 'email' ? '邮件' : 'Webhook'} {!channel.enabled && ( 已停用 )}
{notificationChannelType(channel) === 'email' ? [channel.to, channel.smtpHost].filter(Boolean).join(' · ') : channel.url}
{notificationChannelType(channel) === 'email' ? channel.subjectTemplate || channel.bodyTemplate : channel.bodyTemplate}
); }