From a46043317551af9d79f8e06a9664ed8f95693e69 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 14:29:52 +0800 Subject: [PATCH] refactor(webui): redesign per-UIN config page into sidebar + tabs + modal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The original page stacked four expanded network sections vertically with inline editing, so the first view drowned in every field across every adapter at once. Restructured to a sidebar + tabs + modal layout: - Account sidebar collapses to a 56px avatar column with name/UIN tooltips; expanded it keeps the original 260px nickname + UIN layout. - Right pane swaps the stacked sections for a 5-tab strip (通用设置 / HTTP API / HTTP 客户端 / WS 服务端 / WS 客户端) with a per-tab badge count. - Each network tab is a list of summary cards: name + projected key info (host:port/path, url · role, etc.) + format/report/token badges + inline enable toggle + edit/delete buttons. No live-typed fields. - Create and edit both route through a single NodeEditDialog with kind-specific field strips; cancel truly discards the draft. - Per-kind metadata (title, summary projector, defaultEntry factory) lives in config/defaults.ts so adding a new adapter kind only needs one descriptor entry. Behavior preserved end-to-end: same per-UIN config payload, same useOneBotInstanceConfig hook, same dirty-switch confirm flow, same save endpoint. --- .../src/components/config/account-sidebar.tsx | 114 +++ .../webui/src/components/config/defaults.ts | 159 +++ .../config/general-settings-tab.tsx | 31 + .../components/config/node-edit-dialog.tsx | 407 ++++++++ .../components/config/node-summary-card.tsx | 130 +++ .../src/components/pages/config-page.tsx | 963 ++++++------------ 6 files changed, 1159 insertions(+), 645 deletions(-) create mode 100644 packages/webui/src/components/config/account-sidebar.tsx create mode 100644 packages/webui/src/components/config/defaults.ts create mode 100644 packages/webui/src/components/config/general-settings-tab.tsx create mode 100644 packages/webui/src/components/config/node-edit-dialog.tsx create mode 100644 packages/webui/src/components/config/node-summary-card.tsx diff --git a/packages/webui/src/components/config/account-sidebar.tsx b/packages/webui/src/components/config/account-sidebar.tsx new file mode 100644 index 00000000..6d0bfb47 --- /dev/null +++ b/packages/webui/src/components/config/account-sidebar.tsx @@ -0,0 +1,114 @@ +// Account selector strip. Collapsing to a 56px avatar-only column keeps +// the right-side editor breathing on smaller screens; expanded it shows +// nickname + UIN like the original. Selection routes through +// `requestSwitchUin` so the dirty-modify guard still gates the switch. + +import { motion } from 'motion/react'; +import { ChevronLeft, ChevronRight } from 'lucide-react'; +import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; +import { Button } from '@/components/ui/button'; +import { ScrollArea } from '@/components/ui/scroll-area'; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; +import { cn } from '@/lib/utils'; +import type { QQInfo } from '@/types'; + +function qqAvatarUrl(uin: string) { + return `/avatar/${encodeURIComponent(uin)}`; +} + +interface AccountSidebarProps { + accounts: QQInfo[]; + selectedUin: string | null; + onSelect: (uin: string) => void; + collapsed: boolean; + onToggleCollapsed: () => void; +} + +export function AccountSidebar({ + accounts, + selectedUin, + onSelect, + collapsed, + onToggleCollapsed, +}: AccountSidebarProps) { + return ( + +
+ {!collapsed && 在线连接} + +
+ + {accounts.length === 0 ? ( +

+ {collapsed ? '—' : '暂无在线会话'} +

+ ) : ( + + +
+ {accounts.map((q) => { + const isActive = selectedUin === q.uin; + const button = ( + onSelect(q.uin)} + className={cn( + 'flex items-center gap-2.5 rounded-lg border text-left transition-colors cursor-pointer', + collapsed ? 'justify-center p-1.5' : 'px-2.5 py-2', + isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40', + )} + > + + + {(q.nickname || q.uin).slice(0, 2)} + + {!collapsed && ( +
+
+ {q.nickname || q.uin} +
+
+ {q.uin} +
+
+ )} +
+ ); + return collapsed ? ( + + {button} + +
+ {q.nickname || q.uin} + {q.uin} +
+
+
+ ) : ( + button + ); + })} +
+
+
+ )} +
+ ); +} diff --git a/packages/webui/src/components/config/defaults.ts b/packages/webui/src/components/config/defaults.ts new file mode 100644 index 00000000..1c71ce6a --- /dev/null +++ b/packages/webui/src/components/config/defaults.ts @@ -0,0 +1,159 @@ +// Per-network-kind metadata: localized title, summary projector for the +// list view, and factory for "create new" defaults. Centralised here so the +// page / list / dialog all agree on naming and shape and a new adapter +// kind only needs one entry in NETWORK_TABS to wire end-to-end. + +import type { + HttpClientNetwork, + HttpServerNetwork, + MessageFormat, + NetworkKind, + OneBotNetworks, + WsClientNetwork, + WsRole, + WsServerNetwork, +} from '@/types'; + +export type TabKey = 'general' | NetworkKind; + +export interface NetworkTabDescriptor { + key: K; + /** Tab label and dialog title prefix. */ + title: string; + /** Short subtitle shown under the tab when active. */ + description: string; + /** Singular noun for "新建 / 编辑 X". */ + noun: string; + /** Project the adapter into a short list-card summary string. */ + summarize: (item: OneBotNetworks[K][number]) => string; + /** Factory producing a fresh adapter with a unique suffix in its name. */ + defaultEntry: (suffix: number) => OneBotNetworks[K][number]; +} + +function genToken(): string { + const bytes = new Uint8Array(32); + globalThis.crypto.getRandomValues(bytes); + return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); +} + +const httpServersTab: NetworkTabDescriptor<'httpServers'> = { + key: 'httpServers', + title: 'HTTP API', + description: '本地监听 HTTP 端口,OneBot 客户端发起请求', + noun: 'HTTP API 服务', + summarize: (it: HttpServerNetwork) => { + const host = it.host?.trim() || '0.0.0.0'; + const path = (it.path?.trim() || '/').replace(/^\/?/, '/'); + return `${host}:${it.port}${path}`; + }, + defaultEntry: (suffix): HttpServerNetwork => ({ + name: `http-${suffix}`, + host: '0.0.0.0', + port: 3000, + path: '/', + accessToken: genToken(), + messageFormat: 'array', + reportSelfMessage: false, + }), +}; + +const httpClientsTab: NetworkTabDescriptor<'httpClients'> = { + key: 'httpClients', + title: 'HTTP 客户端', + description: '主动向远端 URL POST 推送事件', + noun: 'HTTP 推送客户端', + summarize: (it: HttpClientNetwork) => it.url || '(未设置 URL)', + defaultEntry: (suffix): HttpClientNetwork => ({ + name: `httppost-${suffix}`, + url: 'http://127.0.0.1:5700', + messageFormat: 'array', + reportSelfMessage: false, + }), +}; + +const wsServersTab: NetworkTabDescriptor<'wsServers'> = { + key: 'wsServers', + title: 'WS 服务端', + description: '本地监听 WebSocket 端口,客户端建立持久连接', + noun: 'WebSocket 服务', + summarize: (it: WsServerNetwork) => { + const host = it.host?.trim() || '0.0.0.0'; + const path = (it.path?.trim() || '/').replace(/^\/?/, '/'); + const role = it.role ?? 'Universal'; + return `${host}:${it.port}${path} · ${role}`; + }, + defaultEntry: (suffix): WsServerNetwork => ({ + name: `ws-${suffix}`, + host: '0.0.0.0', + port: 3001, + path: '/', + role: 'Universal' as WsRole, + accessToken: genToken(), + messageFormat: 'array', + reportSelfMessage: false, + }), +}; + +const wsClientsTab: NetworkTabDescriptor<'wsClients'> = { + key: 'wsClients', + title: 'WS 客户端', + description: '主动连接到外部 WebSocket 服务器(reverse-ws)', + noun: 'WebSocket 反向客户端', + summarize: (it: WsClientNetwork) => { + const role = it.role ?? 'Universal'; + return `${it.url || '(未设置 URL)'} · ${role}`; + }, + defaultEntry: (suffix): WsClientNetwork => ({ + name: `wsclient-${suffix}`, + url: 'ws://127.0.0.1:8080/ws', + role: 'Universal' as WsRole, + reconnectIntervalMs: 5000, + messageFormat: 'array', + reportSelfMessage: false, + }), +}; + +/** + * Order here drives both the tab strip order and the dialog/page wiring. + * Each entry stays strictly typed on its kind so callers get the narrow + * adapter shape (no NetworkBase widening). + */ +export const NETWORK_TABS = { + httpServers: httpServersTab, + httpClients: httpClientsTab, + wsServers: wsServersTab, + wsClients: wsClientsTab, +} satisfies { [K in NetworkKind]: NetworkTabDescriptor }; + +export const NETWORK_TAB_ORDER: NetworkKind[] = [ + 'httpServers', + 'httpClients', + 'wsServers', + 'wsClients', +]; + +export const ALL_TABS: TabKey[] = ['general', ...NETWORK_TAB_ORDER]; + +/** + * Find the smallest suffix N (starting at list.length + 1) such that + * `factory(N).name` doesn't collide with any existing adapter. Used by + * the page to seed a fresh-default adapter when the user clicks "create". + */ +export function nextUniqueSuffix( + networks: { name: string }[], + factory: (suffix: number) => { name: string }, +): number { + const used = new Set(networks.map((n) => n.name)); + let suffix = networks.length + 1; + while (used.has(factory(suffix).name)) suffix += 1; + return suffix; +} + +// Re-exported for callers that just need to type a generic adapter. +export interface AdapterCommon { + name: string; + enabled?: boolean; + accessToken?: string; + messageFormat: MessageFormat; + reportSelfMessage: boolean; +} diff --git a/packages/webui/src/components/config/general-settings-tab.tsx b/packages/webui/src/components/config/general-settings-tab.tsx new file mode 100644 index 00000000..3ed5a3cc --- /dev/null +++ b/packages/webui/src/components/config/general-settings-tab.tsx @@ -0,0 +1,31 @@ +// "通用设置" tab — fields that apply to the whole OneBotInstance rather +// than any specific adapter. Currently just the music-sign service URL, +// but the layout has room for additional cross-cutting toggles. + +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import type { OneBotConfig } from '@/types'; + +interface GeneralSettingsTabProps { + config: OneBotConfig; + onChange: (next: OneBotConfig) => void; +} + +export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps) { + return ( +
+
+ + onChange({ ...config, musicSignUrl: e.target.value || undefined })} + /> +

+ 用于音乐分享卡片签名。未配置时音乐相关消息段会回落为普通文本。 +

+
+
+ ); +} diff --git a/packages/webui/src/components/config/node-edit-dialog.tsx b/packages/webui/src/components/config/node-edit-dialog.tsx new file mode 100644 index 00000000..b1ca652b --- /dev/null +++ b/packages/webui/src/components/config/node-edit-dialog.tsx @@ -0,0 +1,407 @@ +// Modal editor used for both "create" and "edit". Holds a local draft +// copy of the adapter until the user clicks save (so cancel really does +// throw away changes). Validation is minimal — blank-name and dup-name +// disable the save button; everything else is best-effort coercion. + +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 { cn } from '@/lib/utils'; +import type { + HttpClientNetwork, + HttpServerNetwork, + MessageFormat, + NetworkKind, + OneBotNetworks, + WsClientNetwork, + WsRole, + WsServerNetwork, +} from '@/types'; +import { NETWORK_TABS } from './defaults'; + +type AnyAdapter = OneBotNetworks[K][number]; + +interface NodeEditDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + kind: K; + /** Initial draft state — caller seeds it with `defaultEntry` for create + * or the existing item for edit. */ + initial: AnyAdapter; + /** True when editing an existing adapter (drives title + button copy). */ + isEdit: boolean; + /** Names of every other adapter in the same list, for duplicate check. */ + otherNames: string[]; + onSubmit: (item: AnyAdapter) => void; +} + +export function NodeEditDialog(props: NodeEditDialogProps) { + const { open, onOpenChange, kind, initial, isEdit, otherNames, onSubmit } = props; + const tab = NETWORK_TABS[kind]; + + // Local draft. The parent unmounts this component on close so each + // open gets a fresh `initial` via useState's lazy init — no effect-based + // resync needed, which keeps the lifecycle linear. + const [draft, setDraft] = useState>(initial); + + const trimmedName = draft.name?.trim() ?? ''; + const blankName = trimmedName.length === 0; + const duplicateName = !blankName && otherNames.includes(trimmedName); + + const canSave = !blankName && !duplicateName; + + const patch = (changes: Partial>) => setDraft({ ...draft, ...changes } as AnyAdapter); + + return ( + + + + {isEdit ? `编辑 ${tab.noun}` : `新建 ${tab.noun}`} + {tab.description} + + +
+ patch({ name: v } as Partial>)} + error={blankName ? '请填写名称' : duplicateName ? '名称与其它节点重复' : undefined} + /> + + + + patch({ accessToken: v || undefined } as Partial>)} + /> + +
+ patch({ messageFormat: v } as Partial>)} + /> + patch({ reportSelfMessage: v === 'on' } as Partial>)} + /> +
+ +
+
+ +

+ 关闭后保存即可保留配置但不启动该节点 +

+
+ + patch({ enabled: v ? undefined : false } as Partial>) + } + ariaLabel="启用" + /> +
+
+ + + + + +
+
+ ); +} + +// ─────────────── kind-specific field strips ─────────────── + +interface KindFieldsProps { + kind: K; + draft: AnyAdapter; + patch: (changes: Partial>) => void; +} + +function KindFields({ kind, draft, patch }: KindFieldsProps) { + // Per-branch narrowing — TS can't follow the generic relationship so + // each arm casts once. Field components receive specific shapes. + if (kind === 'httpServers') { + const it = draft as HttpServerNetwork; + const set = patch as (c: Partial) => void; + return ( +
+ set({ host: v || undefined })} + /> + set({ port: Number(v) || 0 })} + /> + set({ path: v || undefined })} + /> +
+ ); + } + if (kind === 'httpClients') { + const it = draft as HttpClientNetwork; + const set = patch as (c: Partial) => void; + return ( +
+ set({ url: v })} + /> + set({ timeoutMs: Number(v) || undefined })} + /> +
+ ); + } + if (kind === 'wsServers') { + const it = draft as WsServerNetwork; + const set = patch as (c: Partial) => void; + return ( + <> +
+ set({ host: v || undefined })} + /> + set({ port: Number(v) || 0 })} + /> + set({ path: v || undefined })} + /> +
+ set({ role: v })} + /> + + ); + } + if (kind === 'wsClients') { + const it = draft as WsClientNetwork; + const set = patch as (c: Partial) => void; + return ( + <> + set({ url: v })} + /> +
+ set({ role: v })} + /> + set({ reconnectIntervalMs: Number(v) || undefined })} + /> +
+ + ); + } + return null; +} + +// ─────────────── shared form bits ─────────────── + +interface FieldProps { + label: string; + value: string | number | undefined; + onChange: (v: string) => void; + placeholder?: string; + type?: 'text' | 'number' | 'url'; + error?: string; +} + +function Field({ label, value, onChange, placeholder, type = 'text', error }: FieldProps) { + return ( +
+ + onChange(e.target.value)} + placeholder={placeholder} + className={cn(error && 'border-destructive focus-visible:ring-destructive/40')} + /> + {error &&

{error}

} +
+ ); +} + +interface SegmentedOption { + value: T; + label: string; +} + +function SegmentedField({ + label, + value, + options, + onChange, +}: { + label: string; + value: T; + options: ReadonlyArray>; + onChange: (v: T) => void; +}) { + return ( +
+ +
+ {options.map((opt) => { + const active = value === opt.value; + return ( + + ); + })} +
+
+ ); +} + +function SelectField({ + label, + value, + options, + onChange, +}: { + label: string; + value: T; + options: ReadonlyArray>; + onChange: (v: T) => void; +}) { + return ( +
+ + +
+ ); +} + +interface ToggleSwitchProps { + value: boolean; + onChange: (v: boolean) => void; + ariaLabel: string; +} + +function ToggleSwitch({ value, onChange, ariaLabel }: ToggleSwitchProps) { + return ( + + ); +} + +const FORMAT_OPTIONS: ReadonlyArray> = [ + { value: 'array', label: '数组' }, + { value: 'string', label: 'CQ 码' }, +]; + +const REPORT_OPTIONS: ReadonlyArray> = [ + { value: 'on', label: '开启' }, + { value: 'off', label: '关闭' }, +]; + +const WS_ROLE_OPTIONS: ReadonlyArray> = [ + { value: 'Universal', label: 'Universal' }, + { value: 'Event', label: 'Event' }, + { value: 'Api', label: 'Api' }, +]; diff --git a/packages/webui/src/components/config/node-summary-card.tsx b/packages/webui/src/components/config/node-summary-card.tsx new file mode 100644 index 00000000..f2e3fae7 --- /dev/null +++ b/packages/webui/src/components/config/node-summary-card.tsx @@ -0,0 +1,130 @@ +// One row in the per-kind list view. Shows just enough to identify the +// adapter at a glance (name + projected summary + token state + the two +// flags) plus the inline enable toggle. Real editing always goes through +// the dialog — there are no live-typed inputs here. + +import { motion } from 'motion/react'; +import { Pencil, Trash2 } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Badge } from '@/components/ui/badge'; +import { cn } from '@/lib/utils'; +import type { AdapterCommon } from './defaults'; + +interface NodeSummaryCardProps { + item: T; + summary: string; + duplicateName: boolean; + onToggleEnabled: (next: boolean) => void; + onEdit: () => void; + onDelete: () => void; +} + +export function NodeSummaryCard({ + item, + summary, + duplicateName, + onToggleEnabled, + onEdit, + onDelete, +}: NodeSummaryCardProps) { + const enabled = item.enabled !== false; + const blankName = !item.name?.trim(); + + return ( + +
+
+ + {item.name || '(未命名)'} + + {duplicateName && ( + 名称重复 + )} + {!enabled && ( + 已停用 + )} +
+
{summary}
+
+ + {item.messageFormat === 'string' ? 'CQ 码' : '数组'} + + + {item.reportSelfMessage ? '上报自身' : '不上报自身'} + + {item.accessToken ? ( + + 已设 Token + + ) : ( + + 无 Token + + )} +
+
+ +
+ + + +
+
+ ); +} + +interface ToggleSwitchProps { + value: boolean; + onChange: (v: boolean) => void; + ariaLabel: string; +} + +function ToggleSwitch({ value, onChange, ariaLabel }: ToggleSwitchProps) { + return ( + + ); +} diff --git a/packages/webui/src/components/pages/config-page.tsx b/packages/webui/src/components/pages/config-page.tsx index 4154be6c..a9954fac 100644 --- a/packages/webui/src/components/pages/config-page.tsx +++ b/packages/webui/src/components/pages/config-page.tsx @@ -1,93 +1,42 @@ -import { useState } from 'react'; +// OneBot per-UIN configuration page. +// +// Layout: collapsible left sidebar for account selection + tabbed right +// pane (通用 / 4 network kinds). Each network tab is a list view of +// summary cards with inline enable/disable; create + edit both go +// through `NodeEditDialog`. The dirty-modify guard from the original +// hook is preserved end-to-end — switching accounts or kinds doesn't +// drop unsaved changes silently. + +import { useMemo, useState } from 'react'; import { motion } from 'motion/react'; -import { MousePointerClick, Plus, Save, Trash2 } from 'lucide-react'; +import { MousePointerClick, Plus, Save } from 'lucide-react'; import { Button } from '@/components/ui/button'; -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; -import { ScrollArea } from '@/components/ui/scroll-area'; -import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; -import { Badge } from '@/components/ui/badge'; import { Skeleton } from '@/components/ui/skeleton'; +import { Badge } from '@/components/ui/badge'; import { ConfirmDialog } from '@/components/confirm-dialog'; import { cn } from '@/lib/utils'; import type { - MessageFormat, NetworkKind, OneBotConfig, OneBotNetworks, - WsRole, } from '@/types'; import { useOneBotInstanceConfig } from '@/hooks/use-onebot-instance-config'; import { useAppState } from '@/contexts/AppStateContext'; +import { AccountSidebar } from '@/components/config/account-sidebar'; +import { GeneralSettingsTab } from '@/components/config/general-settings-tab'; +import { NodeSummaryCard } from '@/components/config/node-summary-card'; +import { NodeEditDialog } from '@/components/config/node-edit-dialog'; +import { + ALL_TABS, + NETWORK_TABS, + nextUniqueSuffix, + type TabKey, +} from '@/components/config/defaults'; -function qqAvatarUrl(uin: string) { - return `/avatar/${encodeURIComponent(uin)}`; -} - -function generateAccessToken(): string { - const bytes = new Uint8Array(32); - globalThis.crypto.getRandomValues(bytes); - return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); -} - -function Field({ - label, - value, - onChange, - placeholder, - type = 'text', - className, -}: { - label: string; - value: string | number | undefined; - onChange: (v: string) => void; - placeholder?: string; - type?: 'text' | 'number' | 'url'; - className?: string; -}) { - return ( -
- - onChange(e.target.value)} - placeholder={placeholder} - /> -
- ); -} - -interface SectionProps { - title: string; - description?: string; - onAdd?: () => void; - children: React.ReactNode; - count?: number; -} - -function Section({ title, description, onAdd, children, count }: SectionProps) { - return ( - - -
-
- {title} - {typeof count === 'number' && {count}} -
- {description &&

{description}

} -
- {onAdd && ( - - )} -
- {children} -
- ); -} +type DialogState = + | { open: false } + | { open: true; kind: NetworkKind; index: number | null; seed: OneBotNetworks[NetworkKind][number] }; +// index: null → create with `seed`, otherwise edit the item at that position. export function ConfigPage() { const { qqList, selectedUin, setSelectedUin } = useAppState(); @@ -105,322 +54,137 @@ export function ConfigPage() { selectedUin, onSelectedUinChange: setSelectedUin, }); - const [confirmSave, setConfirmSave] = useState(false); - const update = (next: OneBotConfig) => setConfig(next); - const pendingSwitchAccount = pendingSwitchUin - ? qqList.find((q) => q.uin === pendingSwitchUin) ?? null - : null; + const [activeTab, setActiveTab] = useState('general'); + const [sidebarCollapsed, setSidebarCollapsed] = useState(false); + const [confirmSave, setConfirmSave] = useState(false); + // The edit dialog is modal and blocks every other click in the page, + // so `selectedUin` cannot change while it's open — no defensive close + // wiring needed beyond the dialog's own open/close. + const [dialog, setDialog] = useState({ open: false }); + + const pendingSwitchAccount = useMemo( + () => (pendingSwitchUin ? qqList.find((q) => q.uin === pendingSwitchUin) ?? null : null), + [pendingSwitchUin, qqList], + ); + + // Per-kind helpers (typed at the call site so the dialog's onSubmit + // payload is exactly the kind's adapter shape). + function updateKind(kind: K, next: OneBotNetworks[K]): void { + if (!config) return; + setConfig({ ...config, networks: { ...config.networks, [kind]: next } }); + } + + function handleCreate(kind: K, item: OneBotNetworks[K][number]): void { + if (!config) return; + const list = config.networks[kind] as OneBotNetworks[K]; + updateKind(kind, [...list, item] as OneBotNetworks[K]); + } + + function handleEdit(kind: K, index: number, item: OneBotNetworks[K][number]): void { + if (!config) return; + const list = config.networks[kind] as OneBotNetworks[K]; + const next = list.map((it, i) => (i === index ? item : it)) as OneBotNetworks[K]; + updateKind(kind, next); + } + + function handleDelete(kind: K, index: number): void { + if (!config) return; + const list = config.networks[kind] as OneBotNetworks[K]; + const next = list.filter((_, i) => i !== index) as OneBotNetworks[K]; + updateKind(kind, next); + } + + function handleToggleEnabled(kind: K, index: number, enabled: boolean): void { + if (!config) return; + const list = config.networks[kind] as OneBotNetworks[K]; + const next = list.map((it, i) => + i === index ? ({ ...it, enabled: enabled ? undefined : false } as OneBotNetworks[K][number]) : it, + ) as OneBotNetworks[K]; + updateKind(kind, next); + } + + const openCreate = (kind: NetworkKind) => { + if (!config) return; + const tab = NETWORK_TABS[kind]; + const list = config.networks[kind]; + const suffix = nextUniqueSuffix(list, tab.defaultEntry); + setDialog({ open: true, kind, index: null, seed: tab.defaultEntry(suffix) }); + }; + + const openEdit = (kind: NetworkKind, index: number) => { + if (!config) return; + const item = config.networks[kind][index]; + if (!item) return; + setDialog({ open: true, kind, index, seed: item }); + }; return ( -
- {/* Account list */} - - - 在线连接 - - - {qqList.length === 0 ? ( -

暂无在线会话

- ) : ( - -
- {qqList.map((q) => { - const isActive = selectedUin === q.uin; - return ( - requestSwitchUin(q.uin)} - className={cn( - 'flex items-center gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors cursor-pointer', - isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40' - )} - > - - - {(q.nickname || q.uin).slice(0, 2)} - -
-
- {q.nickname} -
-
{q.uin}
-
-
- ); - })} -
-
- )} -
-
+
+ setSidebarCollapsed((v) => !v)} + /> - {/* Editor */} -
+
{!selectedUin ? ( -
- -

请在左栏选择会话以配置通信节点

-
+ ) : !config ? ( -
- - - -
+ ) : (
- {/* Header */} -
-
-

OneBot 协议端点

- UIN {selectedUin} -
-
- {saveStatus && ( - - {saveStatus} - - )} - {dirty && !saveStatus && ( - - 未保存 - - )} - -
-
+ setConfirmSave(true)} + activeTab={activeTab} + onCreate={ + activeTab !== 'general' ? () => openCreate(activeTab as NetworkKind) : undefined + } + /> -
- update({ ...config, musicSignUrl: v || undefined })} + + + {activeTab === 'general' ? ( + + ) : ( + openCreate(activeTab)} + onEdit={(idx) => openEdit(activeTab, idx)} + onDelete={(idx) => handleDelete(activeTab, idx)} + onToggleEnabled={(idx, v) => handleToggleEnabled(activeTab, idx, v)} /> -
- - {/* HTTP Servers */} - updateNetworks(config, update, 'httpServers', arr)} - renderFields={(item, patch) => ( - <> - patch({ host: v || undefined })} - className="sm:w-40" - /> - patch({ port: Number(v) || 0 })} - className="sm:w-28" - /> - patch({ path: v || undefined })} - className="sm:w-32" - /> - patch({ accessToken: v || undefined })} - className="flex-1" - /> - - )} - defaultEntry={(suffix) => ({ - name: `http-${suffix}`, - host: '0.0.0.0', - port: 3000, - path: '/', - accessToken: generateAccessToken(), - messageFormat: 'array', - reportSelfMessage: false, - })} - /> - - {/* HTTP Clients (POST push) */} - updateNetworks(config, update, 'httpClients', arr)} - renderFields={(item, patch) => ( - <> - patch({ url: v })} - className="flex-1" - /> - patch({ accessToken: v || undefined })} - className="sm:w-56" - /> - patch({ timeoutMs: Number(v) || undefined })} - className="sm:w-32" - /> - - )} - defaultEntry={(suffix) => ({ - name: `httppost-${suffix}`, - url: 'http://127.0.0.1:5700', - messageFormat: 'array', - reportSelfMessage: false, - })} - /> - - {/* WebSocket Servers */} - updateNetworks(config, update, 'wsServers', arr)} - renderFields={(item, patch) => ( - <> - patch({ host: v || undefined })} - className="sm:w-40" - /> - patch({ port: Number(v) || 0 })} - className="sm:w-28" - /> - patch({ path: v || undefined })} - className="sm:w-32" - /> - patch({ role: v })} - className="sm:w-32" - /> - patch({ accessToken: v || undefined })} - className="flex-1" - /> - - )} - defaultEntry={(suffix) => ({ - name: `ws-${suffix}`, - host: '0.0.0.0', - port: 3001, - path: '/', - role: 'Universal' as WsRole, - accessToken: generateAccessToken(), - messageFormat: 'array', - reportSelfMessage: false, - })} - /> - - {/* WebSocket Clients (reverse) */} - updateNetworks(config, update, 'wsClients', arr)} - renderFields={(item, patch) => ( - <> - patch({ url: v })} - className="flex-1" - /> - patch({ role: v })} - className="sm:w-32" - /> - patch({ reconnectIntervalMs: Number(v) || undefined })} - className="sm:w-36" - /> - patch({ accessToken: v || undefined })} - className="sm:w-56" - /> - - )} - defaultEntry={(suffix) => ({ - name: `wsclient-${suffix}`, - url: 'ws://127.0.0.1:8080/ws', - role: 'Universal' as WsRole, - reconnectIntervalMs: 5000, - messageFormat: 'array', - reportSelfMessage: false, - })} - /> + )}
)}
+ {/* Single dialog covers create + edit across all 4 kinds. */} + {dialog.open && config && ( + !open && setDialog({ open: false })} + kind={dialog.kind} + initial={dialog.seed} + isEdit={dialog.index != null} + otherNames={otherNames(config.networks, dialog.kind, dialog.index)} + onSubmit={(item) => { + if (dialog.index == null) handleCreate(dialog.kind, item); + else handleEdit(dialog.kind, dialog.index, item); + }} + /> + )} + {label}
- ); +// ─────────────── header ─────────────── + +interface HeaderBarProps { + selectedUin: string; + dirty: boolean; + saveStatus: string; + onSave: () => void; + activeTab: TabKey; + onCreate?: () => void; } -interface ToggleFieldProps { - label: string; - description?: string; - value: boolean; - onChange: (v: boolean) => void; -} - -function ToggleField({ label, description, value, onChange }: ToggleFieldProps) { +function HeaderBar({ selectedUin, dirty, saveStatus, onSave, activeTab, onCreate }: HeaderBarProps) { return ( -
-
- - {description && ( -

{description}

- )} +
+
+

OneBot 协议端点

+ + UIN {selectedUin} +
- + {dirty && !saveStatus && ( + + 未保存 + + )} + {onCreate && ( + + )} + +
); } -interface SegmentedOption { - value: T; - label: string; +// ─────────────── tab strip ─────────────── + +interface TabStripProps { + activeTab: TabKey; + onChange: (key: TabKey) => void; + counts: Record; } -function SegmentedField({ - label, - value, - options, - onChange, - className, -}: { - label: string; - value: T; - options: ReadonlyArray>; - onChange: (v: T) => void; - className?: string; -}) { +function TabStrip({ activeTab, onChange, counts }: TabStripProps) { return ( -
- -
- {options.map((opt) => { - const active = value === opt.value; +
+ {ALL_TABS.map((key) => { + const label = key === 'general' ? '通用设置' : NETWORK_TABS[key].title; + const count = key === 'general' ? null : counts[key]; + const active = activeTab === key; + return ( + + ); + })} +
+ ); +} + +function countMap(networks: OneBotNetworks): Record { + return { + httpServers: networks.httpServers.length, + httpClients: networks.httpClients.length, + wsServers: networks.wsServers.length, + wsClients: networks.wsClients.length, + }; +} + +// ─────────────── network tab body ─────────────── + +interface NetworkTabViewProps { + kind: NetworkKind; + config: OneBotConfig; + onCreateClick: () => void; + onEdit: (index: number) => void; + onDelete: (index: number) => void; + onToggleEnabled: (index: number, enabled: boolean) => void; +} + +function NetworkTabView({ + kind, + config, + onCreateClick, + onEdit, + onDelete, + onToggleEnabled, +}: NetworkTabViewProps) { + const tab = NETWORK_TABS[kind]; + const list = config.networks[kind]; + // `summarize` is typed per K in NETWORK_TABS; the union here forces a + // widening cast at the call site rather than ladder-of-ifs per tab. + const summarize = tab.summarize as (it: typeof list[number]) => string; + + if (list.length === 0) { + return ( +
+

暂无 {tab.title} 节点

+ +
+ ); + } + + return ( +
+

{tab.description}

+
+ {list.map((item, idx) => { + const others = list.filter((_, i) => i !== idx).map((n) => n.name); + const duplicate = !!item.name && others.includes(item.name); return ( - + onToggleEnabled(idx, v)} + onEdit={() => onEdit(idx)} + onDelete={() => onDelete(idx)} + /> ); })}
@@ -543,211 +388,39 @@ function SegmentedField({ ); } -function SelectField({ - label, - value, - options, - onChange, - className, -}: { - label: string; - value: T; - options: ReadonlyArray>; - onChange: (v: T) => void; - className?: string; -}) { +// ─────────────── empty + loading ─────────────── + +function EmptyState() { return ( -
- - +
+ +

请在左栏选择会话以配置通信节点

); } -const ADAPTER_FORMAT_OPTIONS: ReadonlyArray> = [ - { value: 'array', label: '数组' }, - { value: 'string', label: 'CQ 码' }, -]; - -const ADAPTER_REPORT_OPTIONS: ReadonlyArray> = [ - { value: 'on', label: '开启' }, - { value: 'off', label: '关闭' }, -]; - -const WS_ROLE_OPTIONS: ReadonlyArray> = [ - { value: 'Universal', label: 'Universal' }, - { value: 'Event', label: 'Event' }, - { value: 'Api', label: 'Api' }, -]; - -interface BaseAdapter { - name: string; - enabled?: boolean; - accessToken?: string; - messageFormat: MessageFormat; - reportSelfMessage: boolean; -} - -interface NetworkSectionProps { - title: string; - description?: string; - kind: NetworkKind; - networks: T[]; - onChange: (next: T[]) => void; - renderFields: (item: T, patch: (changes: Partial) => void) => React.ReactNode; - defaultEntry: (suffix: number) => T; -} - -function NetworkSection({ - title, - description, - networks, - onChange, - renderFields, - defaultEntry, -}: NetworkSectionProps) { - const handleAdd = () => { - const used = new Set(networks.map((n) => n.name)); - let suffix = networks.length + 1; - let entry = defaultEntry(suffix); - while (used.has(entry.name)) { - suffix += 1; - entry = defaultEntry(suffix); - } - onChange([...networks, entry]); - }; - - const patchAt = (idx: number, changes: Partial) => { - onChange(networks.map((it, i) => (i === idx ? { ...it, ...changes } : it))); - }; - - const removeAt = (idx: number) => { - onChange(networks.filter((_, i) => i !== idx)); - }; - +function LoadingSkeleton() { return ( -
- {networks.length === 0 ? ( - - ) : ( - networks.map((item, idx) => ( - i !== idx).map((n) => n.name)} - onPatch={(changes) => patchAt(idx, changes)} - onRemove={() => removeAt(idx)} - renderFields={renderFields} - /> - )) - )} -
+
+ + + + +
); } -interface AdapterRowProps { - item: T; - otherNames: string[]; - onPatch: (changes: Partial) => void; - onRemove: () => void; - renderFields: (item: T, patch: (changes: Partial) => void) => React.ReactNode; -} +// ─────────────── helpers ─────────────── -function AdapterRow({ - item, - otherNames, - onPatch, - onRemove, - renderFields, -}: AdapterRowProps) { - const enabled = item.enabled !== false; - const duplicateName = !!item.name && otherNames.includes(item.name); - const blankName = !item.name?.trim(); - - const formatValue: MessageFormat = item.messageFormat ?? 'array'; - const reportValue: 'on' | 'off' = item.reportSelfMessage ? 'on' : 'off'; - - return ( - -
- onPatch({ name: v } as Partial)} - className="sm:w-44" - /> - onPatch({ enabled: v ? undefined : false } as Partial)} - /> - -
- {(blankName || duplicateName) && ( -

- {blankName ? '请填写名称' : '名称与其它适配器重复'} -

- )} - -
{renderFields(item, onPatch)}
- -
- onPatch({ messageFormat: v } as Partial)} - /> - - onPatch({ - reportSelfMessage: v === 'on', - } as Partial) - } - /> -
-
- ); -} - -function updateNetworks( - config: OneBotConfig, - update: (next: OneBotConfig) => void, +/** Names of every adapter except the one currently being edited. */ +function otherNames( + networks: OneBotNetworks, kind: K, - next: OneBotNetworks[K], -): void { - update({ - ...config, - networks: { ...config.networks, [kind]: next }, - }); + excludeIndex: number | null, +): string[] { + const list = networks[kind]; + return list + .filter((_, i) => i !== excludeIndex) + .map((n) => n.name) + .filter((s): s is string => typeof s === 'string' && s.length > 0); }