/** * Webhook 配置表单(域名级/邮箱级共用;全局版本在设置模态窗口内)。 * key 语义:留空保留现有;填空格清除;非空设置新 key。 */ import { useEffect, useState } from "react"; import { Button, Form, Input, Space, App } from "antd"; import { putDomainWebhook, putMailboxWebhook } from "../api.ts"; /** # 成员变量: 表单当前值(由父组件传入) **/ export interface WebhookValue { url: string | null; headers: string | null; hasKey: boolean; } /** # 函数 * 解析 headers JSON 串为对象(失败返回 {}) */ export function parseHeaders(s: string | null): Record { if (!s) return {}; try { const v = JSON.parse(s); return v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : {}; } catch { return {}; } } /** # 函数 * Webhook 配置表单组件 * 参数: scope - "domain" | "mailbox";targetId - 域名/邮箱 ID;value - 当前配置;onSaved - 保存后回调 */ export function WebhookForm({ scope, targetId, value, onSaved, }: { scope: "domain" | "mailbox"; targetId: string; value: WebhookValue; onSaved: () => void; }) { const { message } = App.useApp(); const [form] = Form.useForm<{ url: string; headers: string; key?: string }>(); const [saving, setSaving] = useState(false); useEffect(() => { form.setFieldsValue({ url: value.url ?? "", headers: value.url ? JSON.stringify(parseHeaders(value.headers), null, 2) : "", }); }, [value, form, targetId]); const save = async () => { const values = await form.validateFields(); let headers: Record = {}; if (values.headers.trim()) { try { headers = JSON.parse(values.headers) as Record; } catch { message.error("自定义请求头必须是合法 JSON 对象"); return; } } const key = values.key ?? undefined; // "填空格清除 key":把单个空格翻译成空串 const normalizedKey = key !== undefined && key.trim() === "" && key.length > 0 ? "" : key; setSaving(true); try { const body = { url: values.url.trim(), headers, key: normalizedKey }; if (scope === "domain") await putDomainWebhook(targetId, body); else await putMailboxWebhook(targetId, body); message.success("Webhook 已保存"); form.setFieldValue("key", undefined); onSaved(); } catch (err) { message.error(err instanceof Error ? err.message : "保存失败"); } finally { setSaving(false); } }; const clear = async () => { setSaving(true); try { if (scope === "domain") await putDomainWebhook(targetId, { url: "" }); else await putMailboxWebhook(targetId, { url: "" }); message.success("已清除该级 Webhook(将回退到上一级配置)"); form.resetFields(); onSaved(); } catch (err) { message.error(err instanceof Error ? err.message : "清除失败"); } finally { setSaving(false); } }; return (
携带,并用于投递签名" } > {value.url && ( )}
); }