feat(webui): per-widget config — alerts levels/count, sessions sort/filter (phase 5)

Overview widgets can carry an opaque `config` (stored per grid item). v1:
- alerts: how many entries + which log levels (was fixed at 5 warn/error);
  the alert row colour now uses the full 6-level palette instead of a
  warn/error binary.
- sessions: sort (recent / uin / nickname) + a nickname/uin filter.

A gear in the layout editor opens an inline config form per configurable
widget; edits apply live (no grid re-init — config isn't in the grid key) and
persist via the section-merge save. Config is parsed client-side with total,
clamping parsers (count 1-50, known levels only, filter <=100 chars); the
server stores it opaquely within a 4KB bound. Widgets with no config render
exactly as before. Verified across 2 adversarial review rounds.
This commit is contained in:
DrSmoothl committed 2026-06-13 21:17:23 +08:00
1 parent f07f309c51
commit 3258300539
6 files changed
+233 -50

No files matched your search

+13
View File
@@ -102,6 +102,12 @@ export interface UiLayoutItem {
y?: number; y?: number;
w?: number; w?: number;
h?: number; h?: number;
/**
* Per-widget settings (overview blocks only) — an opaque object the client
* interprets by widget type (e.g. alerts: count + levels). The server only
* checks it's a plain object within a size bound; it never reads the keys.
*/
config?: Record<string, unknown>;
} }
export interface UiLayout { export interface UiLayout {
@@ -245,6 +251,13 @@ function normalizeLayoutItems(value: unknown, fallback: UiLayoutItem[]): UiLayou
item.w = clampInt(raw.w, 1, 12, 1); item.w = clampInt(raw.w, 1, 12, 1);
item.h = clampInt(raw.h, 1, 100, 1); item.h = clampInt(raw.h, 1, 100, 1);
} }
// Opaque per-widget config: keep only a plain object within a size bound;
// the server never interprets the keys (the client does, per widget type).
if (isObject(raw.config)) {
try {
if (JSON.stringify(raw.config).length <= 4096) item.config = raw.config;
} catch { /* unserializable (cycles) → drop */ }
}
out.push(item); out.push(item);
} }
// An array that parsed to nothing usable is indistinguishable from corrupt; // An array that parsed to nothing usable is indistinguishable from corrupt;
@@ -16,7 +16,7 @@ interface DashboardGridProps {
cols: number; cols: number;
/** Fired (debounced upstream) after a drag/resize settles. */ /** Fired (debounced upstream) after a drag/resize settles. */
onChange: (coords: GridCoord[]) => void; onChange: (coords: GridCoord[]) => void;
renderWidget: (id: string) => ReactNode; renderWidget: (block: UiLayoutItem) => ReactNode;
} }
/** /**
@@ -98,7 +98,7 @@ export function DashboardGrid({ blocks, editing, cols, onChange, renderWidget }:
contentEls[b.id] contentEls[b.id]
? createPortal( ? createPortal(
<div className={cn('h-full w-full overflow-auto', editing && 'pointer-events-none select-none')}> <div className={cn('h-full w-full overflow-auto', editing && 'pointer-events-none select-none')}>
{renderWidget(b.id)} {renderWidget(b)}
</div>, </div>,
contentEls[b.id], contentEls[b.id],
) )
@@ -1,11 +1,18 @@
import { useMemo } from 'react'; import { useMemo, useState } from 'react';
import { Reorder } from 'motion/react'; import { Reorder } from 'motion/react';
import { Check, Eye, EyeOff, GripVertical, Lock, RotateCcw } from 'lucide-react'; import { Check, Eye, EyeOff, GripVertical, Lock, RotateCcw, Settings2 } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import {
ALL_LOG_LEVELS, CONFIGURABLE_WIDGETS, parseAlertsConfig, parseSessionsConfig,
} from '@/lib/dashboard-layout';
import type { UiLayoutItem } from '@/types'; import type { UiLayoutItem } from '@/types';
type SortOpt = 'recent' | 'uin' | 'nickname';
const SORT_LABELS: Record<SortOpt, string> = { recent: '最近', uin: 'QQ 号', nickname: '昵称' };
// Edit panel for the overview's "编辑布局" mode. Overview-card POSITION/SIZE is // Edit panel for the overview's "编辑布局" mode. Overview-card POSITION/SIZE is
// edited in place on the gridstack grid below; this panel only toggles which // edited in place on the gridstack grid below; this panel only toggles which
// cards are shown, and (re)orders the sidebar nav (a 1-D list, so it keeps the // cards are shown, and (re)orders the sidebar nav (a 1-D list, so it keeps the
@@ -13,31 +20,126 @@ import type { UiLayoutItem } from '@/types';
// ── widget visibility (no drag — grid owns position) ── // ── widget visibility (no drag — grid owns position) ──
function AlertsConfigForm({ config, onChange }: { config: Record<string, unknown> | undefined; onChange: (c: Record<string, unknown>) => void }) {
const c = parseAlertsConfig(config);
return (
<div className="flex flex-col gap-3 border-t bg-muted/20 px-3 py-3">
<label className="flex items-center justify-between gap-3 text-xs">
<span className="text-muted-foreground">显示条数</span>
<Input
type="number" min={1} max={50} value={c.count}
onChange={(e) => onChange({ count: Math.min(50, Math.max(1, Math.trunc(Number(e.target.value) || 1))) })}
className="h-8 w-20"
/>
</label>
<div className="flex flex-col gap-1.5">
<span className="text-xs text-muted-foreground">级别</span>
<div className="flex flex-wrap gap-1.5">
{ALL_LOG_LEVELS.map((lv) => {
const on = c.levels.includes(lv);
return (
<button
key={lv}
type="button"
onClick={() => {
const next = on ? c.levels.filter((x) => x !== lv) : [...c.levels, lv];
if (next.length > 0) onChange({ levels: next });
}}
className={cn(
'rounded-md border px-2 py-1 text-[11px] uppercase transition-colors cursor-pointer',
on ? 'border-primary bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:bg-accent/40',
)}
>
{lv}
</button>
);
})}
</div>
</div>
</div>
);
}
function SessionsConfigForm({ config, onChange }: { config: Record<string, unknown> | undefined; onChange: (c: Record<string, unknown>) => void }) {
const c = parseSessionsConfig(config);
return (
<div className="flex flex-col gap-3 border-t bg-muted/20 px-3 py-3">
<div className="flex flex-col gap-1.5">
<span className="text-xs text-muted-foreground">排序</span>
<div className="flex flex-wrap gap-1.5">
{(['recent', 'uin', 'nickname'] as SortOpt[]).map((s) => (
<button
key={s}
type="button"
onClick={() => onChange({ sort: s })}
className={cn(
'rounded-md border px-2 py-1 text-[11px] transition-colors cursor-pointer',
c.sort === s ? 'border-primary bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:bg-accent/40',
)}
>
{SORT_LABELS[s]}
</button>
))}
</div>
</div>
<label className="flex flex-col gap-1.5 text-xs">
<span className="text-muted-foreground">筛选(昵称 / QQ 号)</span>
<Input value={c.filter} placeholder="留空显示全部" maxLength={100} onChange={(e) => onChange({ filter: e.target.value })} className="h-8" />
</label>
</div>
);
}
function VisibilityList({ function VisibilityList({
items, labelFor, onToggle, items, labelFor, onToggle, onConfig,
}: { items: UiLayoutItem[]; labelFor: (id: string) => string; onToggle: (id: string) => void }) { }: {
items: UiLayoutItem[];
labelFor: (id: string) => string;
onToggle: (id: string) => void;
onConfig: (id: string, config: Record<string, unknown>) => void;
}) {
const [open, setOpen] = useState<string | null>(null);
return ( return (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
{items.map((item) => ( {items.map((item) => {
<div const configurable = CONFIGURABLE_WIDGETS.has(item.id);
key={item.id} const isOpen = open === item.id;
className={cn( return (
'flex items-center gap-3 rounded-lg border bg-card/50 px-3 py-2.5', <div key={item.id} className={cn('overflow-hidden rounded-lg border bg-card/50', !item.visible && 'opacity-50')}>
!item.visible && 'opacity-50', <div className="flex items-center gap-3 px-3 py-2.5">
)} <span className="flex-1 truncate text-sm font-medium">{labelFor(item.id)}</span>
> {configurable && (
<span className="flex-1 truncate text-sm font-medium">{labelFor(item.id)}</span> <button
<button type="button"
type="button" onClick={() => setOpen(isOpen ? null : item.id)}
onClick={() => onToggle(item.id)} title="设置"
title={item.visible ? '隐藏' : '显示'} aria-label="设置"
aria-label={item.visible ? '隐藏' : '显示'} className={cn(
className="inline-flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent/40 hover:text-foreground" 'inline-flex size-8 cursor-pointer items-center justify-center rounded-md transition-colors hover:bg-accent/40',
> isOpen ? 'text-primary' : 'text-muted-foreground hover:text-foreground',
{item.visible ? <Eye className="size-4" /> : <EyeOff className="size-4" />} )}
</button> >
</div> <Settings2 className="size-4" />
))} </button>
)}
<button
type="button"
onClick={() => onToggle(item.id)}
title={item.visible ? '隐藏' : '显示'}
aria-label={item.visible ? '隐藏' : '显示'}
className="inline-flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent/40 hover:text-foreground"
>
{item.visible ? <Eye className="size-4" /> : <EyeOff className="size-4" />}
</button>
</div>
{configurable && isOpen && (
item.id === 'alerts'
? <AlertsConfigForm config={item.config} onChange={(c) => onConfig('alerts', c)} />
: <SessionsConfigForm config={item.config} onChange={(c) => onConfig('sessions', c)} />
)}
</div>
);
})}
</div> </div>
); );
} }
@@ -102,13 +204,14 @@ export interface LayoutEditorProps {
navLabelFor: (id: string) => string; navLabelFor: (id: string) => string;
navPinned: readonly string[]; navPinned: readonly string[];
onToggleBlock: (id: string) => void; onToggleBlock: (id: string) => void;
onBlockConfig: (id: string, config: Record<string, unknown>) => void;
onNav: (items: UiLayoutItem[]) => void; onNav: (items: UiLayoutItem[]) => void;
onReset: () => void; onReset: () => void;
onDone: () => void; onDone: () => void;
} }
export function LayoutEditor({ export function LayoutEditor({
blocks, blockLabelFor, navItems, navLabelFor, navPinned, onToggleBlock, onNav, onReset, onDone, blocks, blockLabelFor, navItems, navLabelFor, navPinned, onToggleBlock, onBlockConfig, onNav, onReset, onDone,
}: LayoutEditorProps) { }: LayoutEditorProps) {
return ( return (
<Card> <Card>
@@ -128,8 +231,8 @@ export function LayoutEditor({
</CardHeader> </CardHeader>
<CardContent className="grid gap-6 md:grid-cols-2"> <CardContent className="grid gap-6 md:grid-cols-2">
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<p className="text-xs font-medium text-muted-foreground">总览卡片(显隐)</p> <p className="text-xs font-medium text-muted-foreground">总览卡片(显隐 / 设置)</p>
<VisibilityList items={blocks} labelFor={blockLabelFor} onToggle={onToggleBlock} /> <VisibilityList items={blocks} labelFor={blockLabelFor} onToggle={onToggleBlock} onConfig={onBlockConfig} />
</div> </div>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<p className="text-xs font-medium text-muted-foreground">导航栏(拖动排序)</p> <p className="text-xs font-medium text-muted-foreground">导航栏(拖动排序)</p>
@@ -13,14 +13,17 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton'; import { Skeleton } from '@/components/ui/skeleton';
import { cn, formatBytes, formatUptime } from '@/lib/utils'; import { cn, formatBytes, formatUptime } from '@/lib/utils';
import type { AppPath } from '@/router'; import type { AppPath } from '@/router';
import type { AdapterStatus, AdapterStatusLevel, LogEntry } from '@/types'; import type { AdapterStatus, AdapterStatusLevel, LogEntry, LogLevel, UiLayoutItem } from '@/types';
import { useApi } from '@/lib/api'; import { useApi } from '@/lib/api';
import { useAppState } from '@/contexts/AppStateContext'; import { useAppState } from '@/contexts/AppStateContext';
import { useSession } from '@/contexts/SessionContext'; import { useSession } from '@/contexts/SessionContext';
import { useTheme } from '@/contexts/ThemeContext'; import { useTheme } from '@/contexts/ThemeContext';
import { reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext'; import { reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext';
import { useMediaQuery } from '@/hooks/use-media-query'; import { useMediaQuery } from '@/hooks/use-media-query';
import { GRID_COLS, widgetLabel } from '@/lib/dashboard-layout'; import {
GRID_COLS, parseAlertsConfig, parseSessionsConfig, widgetLabel,
type AlertsConfig, type SessionsConfig,
} from '@/lib/dashboard-layout';
import { NAV_ITEMS, PINNED_NAV } from '@/components/layout/sidebar'; import { NAV_ITEMS, PINNED_NAV } from '@/components/layout/sidebar';
import { DashboardGrid, type GridCoord } from '@/components/pages/dashboard-grid'; import { DashboardGrid, type GridCoord } from '@/components/pages/dashboard-grid';
import { LayoutEditor } from '@/components/pages/overview-layout-editor'; import { LayoutEditor } from '@/components/pages/overview-layout-editor';
@@ -31,13 +34,13 @@ function qqAvatarUrl(uin: string) {
const navLabelFor = (id: string) => NAV_ITEMS.find((n) => n.to === id)?.label ?? id; const navLabelFor = (id: string) => NAV_ITEMS.find((n) => n.to === id)?.label ?? id;
function renderWidget(id: string): ReactNode { function renderWidget(block: UiLayoutItem): ReactNode {
if (id.startsWith('stat:')) return <StatTileWidget id={id} />; if (block.id.startsWith('stat:')) return <StatTileWidget id={block.id} />;
switch (id) { switch (block.id) {
case 'connections': return <ConnectionsBlock />; case 'connections': return <ConnectionsBlock />;
case 'alerts': return <RecentAlertsCard />; case 'alerts': return <RecentAlertsCard config={parseAlertsConfig(block.config)} />;
case 'host': return <HostBlock />; case 'host': return <HostBlock />;
case 'sessions': return <SessionsBlock />; case 'sessions': return <SessionsBlock config={parseSessionsConfig(block.config)} />;
default: return null; default: return null;
} }
} }
@@ -68,6 +71,9 @@ export function OverviewPage() {
const toggleBlock = (id: string) => const toggleBlock = (id: string) =>
setOverviewBlocks(overviewBlocks.map((b) => (b.id === id ? { ...b, visible: !b.visible } : b))); setOverviewBlocks(overviewBlocks.map((b) => (b.id === id ? { ...b, visible: !b.visible } : b)));
const setBlockConfig = (id: string, config: Record<string, unknown>) =>
setOverviewBlocks(overviewBlocks.map((b) => (b.id === id ? { ...b, config: { ...b.config, ...config } } : b)));
const loadableProcs = processList.filter((p) => !p.injected).length; const loadableProcs = processList.filter((p) => !p.injected).length;
return ( return (
@@ -89,6 +95,7 @@ export function OverviewPage() {
navLabelFor={navLabelFor} navLabelFor={navLabelFor}
navPinned={PINNED_NAV} navPinned={PINNED_NAV}
onToggleBlock={toggleBlock} onToggleBlock={toggleBlock}
onBlockConfig={setBlockConfig}
onNav={setNavItems} onNav={setNavItems}
onReset={resetLayout} onReset={resetLayout}
onDone={() => setEditingOn(false)} onDone={() => setEditingOn(false)}
@@ -348,24 +355,37 @@ function HostBlock() {
// ─────────────── online sessions ─────────────── // ─────────────── online sessions ───────────────
function SessionsBlock() { function SessionsBlock({ config }: { config: SessionsConfig }) {
const { qqList } = useAppState(); const { qqList } = useAppState();
const list = useMemo(() => {
const f = config.filter.trim().toLowerCase();
let arr = f
? qqList.filter((q) => (q.nickname ?? '').toLowerCase().includes(f) || q.uin.includes(f))
: qqList;
if (config.sort === 'uin') arr = [...arr].sort((a, b) => a.uin.localeCompare(b.uin, undefined, { numeric: true }));
else if (config.sort === 'nickname') arr = [...arr].sort((a, b) => (a.nickname ?? '').localeCompare(b.nickname ?? ''));
// 'recent' keeps the server/insertion order.
return arr;
}, [qqList, config.sort, config.filter]);
return ( return (
<Card className="flex h-full flex-col"> <Card className="flex h-full flex-col">
<CardHeader> <CardHeader>
<CardTitle>在线会话</CardTitle> <CardTitle>在线会话</CardTitle>
<CardDescription>当前已接入并完成登录的 QQ 账号</CardDescription> <CardDescription>
当前已接入并完成登录的 QQ 账号{config.filter.trim() ? `(筛选:${config.filter.trim()})` : ''}
</CardDescription>
</CardHeader> </CardHeader>
<CardContent className="min-h-0 flex-1"> <CardContent className="min-h-0 flex-1">
{qqList.length === 0 ? ( {list.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground"> <div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
<Users className="size-7" strokeWidth={1.5} /> <Users className="size-7" strokeWidth={1.5} />
<p className="text-sm">暂无在线会话</p> <p className="text-sm">{qqList.length === 0 ? '暂无在线会话' : '无匹配的会话'}</p>
</div> </div>
) : ( ) : (
<ScrollArea className="h-full" viewportClassName="[&>div]:!block"> <ScrollArea className="h-full" viewportClassName="[&>div]:!block">
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4"> <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
{qqList.map((q, idx) => ( {list.map((q, idx) => (
<motion.div <motion.div
key={q.uin} key={q.uin}
initial={{ opacity: 0, y: 6 }} initial={{ opacity: 0, y: 6 }}
@@ -463,28 +483,40 @@ function ConnectionsBlock() {
// ─────────────── recent alerts ─────────────── // ─────────────── recent alerts ───────────────
function RecentAlertsCard() { const ALERT_LEVEL_CLASS: Record<LogLevel, string> = {
trace: 'text-muted-foreground/60',
debug: 'text-muted-foreground',
info: 'text-primary',
success: 'text-success',
warn: 'text-warning',
error: 'text-destructive',
};
function RecentAlertsCard({ config }: { config: AlertsConfig }) {
const api = useApi(); const api = useApi();
const { formatClock } = useTheme(); const { formatClock } = useTheme();
const [alerts, setAlerts] = useState<LogEntry[]>([]); const [alerts, setAlerts] = useState<LogEntry[]>([]);
const { count } = config;
const levelsKey = config.levels.join(',');
useEffect(() => { useEffect(() => {
const levels = new Set(levelsKey.split(',') as LogLevel[]);
let active = true; let active = true;
api.logs api.logs
.list(200) .list(Math.max(200, count * 4))
.then((list) => { .then((list) => {
if (!active) return; if (!active) return;
setAlerts(list.filter((l) => l.level === 'warn' || l.level === 'error').slice(-5)); setAlerts(list.filter((l) => levels.has(l.level)).slice(-count));
}) })
.catch(() => { /* ignore */ }); .catch(() => { /* ignore */ });
const stop = api.logs.stream({ const stop = api.logs.stream({
onLine: (entry) => { onLine: (entry) => {
if (entry.level !== 'warn' && entry.level !== 'error') return; if (!levels.has(entry.level)) return;
setAlerts((prev) => [...prev.filter((a) => a.id !== entry.id), entry].slice(-5)); setAlerts((prev) => [...prev.filter((a) => a.id !== entry.id), entry].slice(-count));
}, },
}); });
return () => { active = false; stop(); }; return () => { active = false; stop(); };
}, [api]); }, [api, count, levelsKey]);
return ( return (
<Card className="flex h-full flex-col"> <Card className="flex h-full flex-col">
@@ -493,7 +525,7 @@ function RecentAlertsCard() {
<CardTitle className="flex items-center gap-2"> <CardTitle className="flex items-center gap-2">
<Bell className="size-4 text-primary" /> 最近告警 <Bell className="size-4 text-primary" /> 最近告警
</CardTitle> </CardTitle>
<CardDescription>最近的 warn / error 级别日志</CardDescription> <CardDescription>最近 {count} 条 · {config.levels.map((l) => l.toUpperCase()).join(' / ')}</CardDescription>
</div> </div>
<Link to="/logs" className="inline-flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"> <Link to="/logs" className="inline-flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground">
查看日志 <ArrowRight className="size-3" /> 查看日志 <ArrowRight className="size-3" />
@@ -510,7 +542,7 @@ function RecentAlertsCard() {
{alerts.map((a) => ( {alerts.map((a) => (
<div key={a.id} className="flex gap-2 rounded px-2 py-1 hover:bg-accent/30"> <div key={a.id} className="flex gap-2 rounded px-2 py-1 hover:bg-accent/30">
<span className="shrink-0 text-muted-foreground tabular-nums">{formatClock(a.time)}</span> <span className="shrink-0 text-muted-foreground tabular-nums">{formatClock(a.time)}</span>
<span className={cn('shrink-0 font-semibold', a.level === 'error' ? 'text-destructive' : 'text-warning')}> <span className={cn('shrink-0 font-semibold', ALERT_LEVEL_CLASS[a.level])}>
{a.level.toUpperCase()} {a.level.toUpperCase()}
</span> </span>
<span className="min-w-0 flex-1 truncate" title={a.message}>[{a.scope}] {a.message}</span> <span className="min-w-0 flex-1 truncate" title={a.message}>[{a.scope}] {a.message}</span>
+34 -1
View File
@@ -1,4 +1,4 @@
import type { UiLayoutItem } from '@/types'; import type { LogLevel, UiLayoutItem } from '@/types';
// The overview dashboard is a free 12-column gridstack grid. This module is // The overview dashboard is a free 12-column gridstack grid. This module is
// the pure (React-free) catalogue + migration so it can be shared by the // the pure (React-free) catalogue + migration so it can be shared by the
@@ -97,3 +97,36 @@ export function minSizeOf(id: string): { minW: number; minH: number } {
const spec = WIDGET_BY_ID.get(id); const spec = WIDGET_BY_ID.get(id);
return { minW: spec?.minW ?? 1, minH: spec?.minH ?? 1 }; return { minW: spec?.minW ?? 1, minH: spec?.minH ?? 1 };
} }
// ─── Per-widget config (interpreted client-side from the opaque block.config) ───
export const ALL_LOG_LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
export interface AlertsConfig { count: number; levels: LogLevel[] }
export interface SessionsConfig { sort: 'recent' | 'uin' | 'nickname'; filter: string }
export const DEFAULT_ALERTS_CONFIG: AlertsConfig = { count: 5, levels: ['warn', 'error'] };
export const DEFAULT_SESSIONS_CONFIG: SessionsConfig = { sort: 'recent', filter: '' };
/** Widgets that expose a config form (gear) in the layout editor. */
export const CONFIGURABLE_WIDGETS = new Set(['alerts', 'sessions']);
export function parseAlertsConfig(config: Record<string, unknown> | undefined): AlertsConfig {
const c = config ?? {};
const count = typeof c.count === 'number' && Number.isFinite(c.count)
? Math.min(50, Math.max(1, Math.trunc(c.count)))
: DEFAULT_ALERTS_CONFIG.count;
const levels = Array.isArray(c.levels)
? ALL_LOG_LEVELS.filter((l) => (c.levels as unknown[]).includes(l))
: DEFAULT_ALERTS_CONFIG.levels;
return { count, levels: levels.length > 0 ? levels : DEFAULT_ALERTS_CONFIG.levels };
}
export function parseSessionsConfig(config: Record<string, unknown> | undefined): SessionsConfig {
const c = config ?? {};
const sort = c.sort === 'uin' || c.sort === 'nickname' || c.sort === 'recent'
? c.sort
: DEFAULT_SESSIONS_CONFIG.sort;
const filter = typeof c.filter === 'string' ? c.filter.slice(0, 100) : '';
return { sort, filter };
}
+2
View File
@@ -214,6 +214,8 @@ export interface UiLayoutItem {
y?: number; y?: number;
w?: number; w?: number;
h?: number; h?: number;
/** Per-widget settings; interpreted client-side by widget type. */
config?: Record<string, unknown>;
} }
export interface UiLayout { export interface UiLayout {