feat(webui): debug-console shared primitives, data layer, task manager
Phase 3 of the debug-console expansion — the Apple-HIG foundation the new tabs build on (reusing the existing ui kit; new controls match its idiom, no browser-native widgets). API client + types: - debug.invokeStream() reads /api/debug/invoke-stream via fetch + a body reader, parsing data:<json> SSE frames (header auth, cancellable). - debug.upload() streams a file via XHR for real upload progress. - DebugActionParam.role, DebugActionDoc.stream/invariants, FieldRole, DebugStreamFrame, DebugUploadResult. Primitives: - Tabs (sliding indicator + roving tabindex), Picker (searchable, windowed combobox with a raw-value escape hatch), JsonTree (collapsible response viewer, image-url preview, copy w/ http fallback, node cap), FileSource (URL / server-path / browser-upload tri-state), FaceGrid. Infra: - DebugTaskProvider + TaskBadge: app-level registry of in-flight upload/ stream tasks so they survive in-app tab switches, with a global progress chip and a beforeunload guard; eviction never drops a running task. Wired into App. - use-debug-contacts: lazy friend/group/member data layer, shared module cache + localStorage (version-stamped, avatars stripped to dodge quota) + TTL + request-id race guard, degrading to raw input on error. Adversarially reviewed (no automated component tests): virtualization math and SSE framing verified correct; fixed the stale-contacts-on-switch member-selection hazard, the quota-kills-persistence issue, and several low UX edges (active-row clamp, filter scroll reset, copy fallback).
This commit is contained in:
12 files changed
+1188
-2
No files matched your search
@@ -0,0 +1,122 @@
|
||||
// FileSource — the control behind a file/image/record/video param. The bot runs
|
||||
// on the SERVER, so a browser-local path is meaningless to it; this offers three
|
||||
// honest sources: a URL the bot fetches, a path that already exists on the
|
||||
// server, or a browser upload that we stream to a server temp path (and then
|
||||
// feed that path to the action). Upload progress flows through the app-level
|
||||
// task registry so it survives tab switches.
|
||||
import { useRef, useState } from 'react';
|
||||
import { FileUp, Link2, Loader2, ServerCog, X } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { useDebugTasks } from '@/contexts/DebugTaskContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { FieldRole } from '@/types';
|
||||
|
||||
type Mode = 'url' | 'server' | 'upload';
|
||||
|
||||
const ACCEPT: Partial<Record<FieldRole, string>> = {
|
||||
image: 'image/*',
|
||||
record: 'audio/*',
|
||||
video: 'video/*',
|
||||
};
|
||||
|
||||
function Seg({ active, onClick, icon, label }: { active: boolean; onClick: () => void; icon: React.ReactNode; label: string }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={cn('inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1 text-xs font-medium transition-colors',
|
||||
active ? 'bg-card text-foreground shadow-sm ring-1 ring-border/60' : 'text-muted-foreground hover:text-foreground')}
|
||||
>
|
||||
{icon}{label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function FileSource({ value, onChange, role, placeholder }: {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
role?: FieldRole;
|
||||
placeholder?: string;
|
||||
}) {
|
||||
const api = useApi();
|
||||
const { start, update, finish } = useDebugTasks();
|
||||
const [mode, setMode] = useState<Mode>('url');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadName, setUploadName] = useState<string | null>(null);
|
||||
const [uploadErr, setUploadErr] = useState<string | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const accept = role ? ACCEPT[role] : undefined;
|
||||
|
||||
const doUpload = async (file: File) => {
|
||||
setUploadErr(null);
|
||||
setUploadName(file.name);
|
||||
setUploading(true);
|
||||
const ac = new AbortController();
|
||||
const taskId = start({ kind: 'upload', label: `上传 ${file.name}`, progress: 0, cancel: () => ac.abort() });
|
||||
try {
|
||||
const res = await api.debug.upload(file, {
|
||||
signal: ac.signal,
|
||||
onProgress: (f) => update(taskId, { progress: f }),
|
||||
});
|
||||
if (!res.path) throw new Error(res.message || '上传失败');
|
||||
onChange(res.path);
|
||||
finish(taskId, 'done', res.path);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : '上传失败';
|
||||
setUploadErr(msg);
|
||||
finish(taskId, ac.signal.aborted ? 'canceled' : 'failed', msg);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="inline-flex w-fit gap-0.5 rounded-xl bg-muted/70 p-0.5">
|
||||
<Seg active={mode === 'url'} onClick={() => setMode('url')} icon={<Link2 className="h-3.5 w-3.5" />} label="URL" />
|
||||
<Seg active={mode === 'server'} onClick={() => setMode('server')} icon={<ServerCog className="h-3.5 w-3.5" />} label="服务器路径" />
|
||||
<Seg active={mode === 'upload'} onClick={() => setMode('upload')} icon={<FileUp className="h-3.5 w-3.5" />} label="上传" />
|
||||
</div>
|
||||
|
||||
{mode === 'url' && (
|
||||
<Input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder || 'https://…'} />
|
||||
)}
|
||||
|
||||
{mode === 'server' && (
|
||||
<div className="flex flex-col gap-1">
|
||||
<Input value={value} onChange={(e) => onChange(e.target.value)} placeholder="/path/on/server/file.jpg" />
|
||||
<span className="text-[11px] text-muted-foreground">这是 <strong>运行 bot 的服务器</strong> 上的路径,不是你本机的。</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{mode === 'upload' && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept={accept}
|
||||
className="hidden"
|
||||
onChange={(e) => { const f = e.target.files?.[0]; if (f) void doUpload(f); e.target.value = ''; }}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={uploading}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
className={cn('flex items-center justify-center gap-2 rounded-xl border border-dashed border-border/70 px-3 py-3 text-sm text-muted-foreground transition-colors hover:border-primary/50 hover:text-foreground disabled:opacity-60')}
|
||||
>
|
||||
{uploading ? <><Loader2 className="h-4 w-4 animate-spin" /> 上传中…</> : <><FileUp className="h-4 w-4" /> 选择文件上传到服务器</>}
|
||||
</button>
|
||||
{value && uploadName && !uploading && (
|
||||
<div className="flex items-center gap-2 rounded-lg bg-muted/40 px-2.5 py-1.5 text-[11px]">
|
||||
<span className="truncate text-muted-foreground">已上传:{uploadName}</span>
|
||||
<code className="ml-auto max-w-[55%] truncate font-mono text-muted-foreground/80" title={value}>{value}</code>
|
||||
<button type="button" onClick={() => { onChange(''); setUploadName(null); }} className="shrink-0 text-muted-foreground hover:text-destructive"><X className="h-3.5 w-3.5" /></button>
|
||||
</div>
|
||||
)}
|
||||
{uploadErr && <span className="text-[11px] text-destructive">{uploadErr}</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// TaskBadge — the app-wide floating indicator for in-flight debug tasks. Sits
|
||||
// bottom-right on every page so a streaming upload/download stays visible after
|
||||
// you switch tabs. Collapsed: a chip with a ring-progress + count. Expanded: a
|
||||
// list with per-task progress, cancel (running) / dismiss (finished). Renders
|
||||
// nothing when there are no tasks at all.
|
||||
import { useState } from 'react';
|
||||
import { AnimatePresence, motion } from 'motion/react';
|
||||
import { CheckCircle2, Loader2, X, XCircle } from 'lucide-react';
|
||||
import { useDebugTasks, useRunningTaskSummary, type DebugTask } from '@/contexts/DebugTaskContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
function StatusIcon({ status }: { status: DebugTask['status'] }) {
|
||||
if (status === 'running') return <Loader2 className="h-3.5 w-3.5 animate-spin text-primary" />;
|
||||
if (status === 'done') return <CheckCircle2 className="h-3.5 w-3.5 text-success" />;
|
||||
return <XCircle className="h-3.5 w-3.5 text-destructive" />;
|
||||
}
|
||||
|
||||
function Row({ task, onDismiss }: { task: DebugTask; onDismiss: () => void }) {
|
||||
const pct = typeof task.progress === 'number' ? Math.round(task.progress * 100) : null;
|
||||
return (
|
||||
<div className="flex flex-col gap-1 rounded-lg px-2.5 py-2 hover:bg-muted/50">
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<StatusIcon status={task.status} />
|
||||
<span className="min-w-0 flex-1 truncate text-foreground/90">{task.label}</span>
|
||||
{task.status === 'running' && task.cancel
|
||||
? <button type="button" onClick={task.cancel} className="text-muted-foreground hover:text-destructive" title="取消"><X className="h-3.5 w-3.5" /></button>
|
||||
: <button type="button" onClick={onDismiss} className="text-muted-foreground hover:text-foreground" title="移除"><X className="h-3.5 w-3.5" /></button>}
|
||||
</div>
|
||||
{task.status === 'running' && (
|
||||
<div className="h-1 overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className={cn('h-full rounded-full bg-primary transition-all', pct === null && 'animate-pulse')}
|
||||
style={{ width: pct === null ? '40%' : `${pct}%` }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{task.detail && task.status !== 'running' && (
|
||||
<span className="truncate text-[10px] text-muted-foreground" title={task.detail}>{task.detail}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TaskBadge() {
|
||||
const { tasks, remove, clearFinished } = useDebugTasks();
|
||||
const { count, progress } = useRunningTaskSummary();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
if (tasks.length === 0) return null;
|
||||
|
||||
const ringPct = progress === null ? null : Math.round(progress * 100);
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 right-4 z-[60] flex flex-col items-end gap-2">
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 8, scale: 0.97 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: 8, scale: 0.97 }}
|
||||
transition={{ type: 'spring', stiffness: 480, damping: 36 }}
|
||||
className="w-72 overflow-hidden rounded-2xl border border-border/60 bg-popover shadow-xl ring-1 ring-black/5"
|
||||
>
|
||||
<div className="flex items-center justify-between border-b border-border/60 px-3 py-2">
|
||||
<span className="text-xs font-semibold">调试任务</span>
|
||||
{tasks.some((t) => t.status !== 'running') && (
|
||||
<button type="button" onClick={clearFinished} className="text-[11px] text-muted-foreground hover:text-foreground">清除已完成</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="max-h-72 overflow-auto p-1.5">
|
||||
{tasks.map((t) => <Row key={t.id} task={t} onDismiss={() => remove(t.id)} />)}
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="flex items-center gap-2 rounded-full border border-border/60 bg-card/90 px-3 py-2 text-xs font-medium shadow-lg ring-1 ring-black/5 backdrop-blur transition-colors hover:bg-card"
|
||||
>
|
||||
{count > 0 ? <Loader2 className="h-4 w-4 animate-spin text-primary" /> : <CheckCircle2 className="h-4 w-4 text-success" />}
|
||||
{count > 0
|
||||
? <span>{count} 个任务进行中{ringPct !== null ? ` · ${ringPct}%` : ''}</span>
|
||||
: <span className="text-muted-foreground">任务完成</span>}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// FaceGrid — pick a QQ classic face id. Renders the classic face sprites from
|
||||
// QQ's long-standing public CDN; any id whose image 404s hides itself, so a
|
||||
// curated-but-imperfect id list still looks clean. A manual id box is the
|
||||
// escape hatch for faces outside the classic range.
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// Classic QQ face ids that resolve on the gtimg CDN. Curated to avoid the gaps
|
||||
// in the 0..170 range (deprecated / never-existed ids) that would 404.
|
||||
const CLASSIC_FACE_IDS: number[] = [
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22,
|
||||
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42,
|
||||
43, 46, 49, 53, 60, 63, 64, 66, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
|
||||
85, 86, 87, 88, 89, 96, 97, 98, 99, 100, 101, 102, 103, 104, 106, 109, 111,
|
||||
116, 118, 120, 122, 123, 124, 125, 129, 144, 147, 171, 173, 174, 175, 176,
|
||||
179, 180, 181, 182, 183, 201, 203, 212, 214, 219, 222, 227,
|
||||
];
|
||||
|
||||
const faceUrl = (id: number) => `https://qzonestyle.gtimg.cn/qzone/em/e${id}.png`;
|
||||
|
||||
export function FaceGrid({ value, onChange }: { value: string; onChange: (v: string) => void }) {
|
||||
const [q, setQ] = useState('');
|
||||
const [broken, setBroken] = useState<Set<number>>(() => new Set());
|
||||
|
||||
const ids = useMemo(() => {
|
||||
const qq = q.trim();
|
||||
const base = CLASSIC_FACE_IDS.filter((id) => !broken.has(id));
|
||||
if (!qq) return base;
|
||||
return base.filter((id) => String(id).includes(qq));
|
||||
}, [q, broken]);
|
||||
|
||||
const selected = value.trim();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="按 id 过滤…" className="h-8 flex-1" />
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value.replace(/[^\d]/g, ''))}
|
||||
placeholder="id"
|
||||
inputMode="numeric"
|
||||
className="h-8 w-20 text-center font-mono"
|
||||
aria-label="表情 id"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid max-h-48 grid-cols-8 gap-1 overflow-auto rounded-xl border border-border/60 bg-muted/30 p-2 sm:grid-cols-10">
|
||||
{ids.map((id) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
title={`face ${id}`}
|
||||
onClick={() => onChange(String(id))}
|
||||
className={cn('flex aspect-square items-center justify-center rounded-lg p-1 transition-colors hover:bg-accent',
|
||||
selected === String(id) && 'bg-primary/15 ring-1 ring-primary/50')}
|
||||
>
|
||||
<img
|
||||
src={faceUrl(id)}
|
||||
alt={`face ${id}`}
|
||||
className="h-full w-full object-contain"
|
||||
loading="lazy"
|
||||
onError={() => setBroken((prev) => { const n = new Set(prev); n.add(id); return n; })}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
{ids.length === 0 && <span className="col-span-full py-4 text-center text-xs text-muted-foreground">无匹配表情</span>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// JsonTree — a calm, collapsible JSON viewer for action responses / event
|
||||
// payloads. Replaces a raw <pre> dump: nodes fold, values are colour-typed, the
|
||||
// root offers copy, and a string that looks like an image URL gets an inline
|
||||
// preview toggle. Read-only; no external deps.
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { Check, ChevronRight, Copy, Image as ImageIcon } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const IMAGE_URL_RE = /^https?:\/\/[^\s]+?\.(?:png|jpe?g|gif|webp|bmp)(?:[?#][^\s]*)?$/i;
|
||||
// QQ multimedia rkey image URLs don't end in an extension but carry these hints.
|
||||
const IMAGE_HINT_RE = /^https?:\/\/[^\s]*(?:rkey=|gchatpic|multimedia|c2cpicdw|offpic|gchat\.qpic)/i;
|
||||
|
||||
function isImageUrl(s: string): boolean {
|
||||
return IMAGE_URL_RE.test(s) || IMAGE_HINT_RE.test(s);
|
||||
}
|
||||
|
||||
function Punct({ children }: { children: ReactNode }) {
|
||||
return <span className="text-muted-foreground/60">{children}</span>;
|
||||
}
|
||||
|
||||
function Leaf({ value }: { value: string | number | boolean | null }) {
|
||||
const [showImg, setShowImg] = useState(false);
|
||||
if (value === null) return <span className="text-muted-foreground/70">null</span>;
|
||||
if (typeof value === 'number') return <span className="text-sky-600 dark:text-sky-400 tabular-nums">{value}</span>;
|
||||
if (typeof value === 'boolean') return <span className="text-violet-600 dark:text-violet-400">{String(value)}</span>;
|
||||
// string
|
||||
const img = isImageUrl(value);
|
||||
return (
|
||||
<span className="break-all">
|
||||
<span className="text-emerald-700 dark:text-emerald-400">"{value}"</span>
|
||||
{img && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowImg((v) => !v)}
|
||||
className="ml-1.5 inline-flex items-center gap-0.5 rounded-md bg-muted/70 px-1 py-0.5 align-middle text-[10px] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ImageIcon className="h-3 w-3" /> {showImg ? '隐藏' : '预览'}
|
||||
</button>
|
||||
{showImg && (
|
||||
<span className="mt-1.5 block">
|
||||
<img src={value} alt="预览" className="max-h-48 rounded-lg border border-border/60" loading="lazy" />
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const NODE_CAP = 100; // render at most this many children before "show more"
|
||||
|
||||
function Node({ k, value, depth, defaultOpen }: { k?: string; value: unknown; depth: number; defaultOpen: boolean }) {
|
||||
const isObj = typeof value === 'object' && value !== null;
|
||||
const [open, setOpen] = useState(defaultOpen);
|
||||
const [limit, setLimit] = useState(NODE_CAP);
|
||||
|
||||
const keyLabel = k != null ? <><span className="text-foreground/80">{k}</span><Punct>: </Punct></> : null;
|
||||
|
||||
if (!isObj) {
|
||||
return (
|
||||
<div className="flex gap-1 py-px pl-[1.1rem]" style={{ paddingLeft: `${depth * 0.9 + 1.1}rem` }}>
|
||||
{keyLabel}
|
||||
<Leaf value={value as string | number | boolean | null} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const entries = Array.isArray(value)
|
||||
? value.map((v, i) => [String(i), v] as const)
|
||||
: Object.entries(value as Record<string, unknown>);
|
||||
const openB = Array.isArray(value) ? '[' : '{';
|
||||
const closeB = Array.isArray(value) ? ']' : '}';
|
||||
const shown = open ? Math.min(entries.length, limit) : 0;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="flex w-full items-center gap-1 py-px text-left hover:bg-muted/40"
|
||||
style={{ paddingLeft: `${depth * 0.9}rem` }}
|
||||
>
|
||||
<ChevronRight className={cn('h-3 w-3 shrink-0 text-muted-foreground/60 transition-transform', open && 'rotate-90')} />
|
||||
{keyLabel}
|
||||
<Punct>{openB}</Punct>
|
||||
{!open && <span className="text-muted-foreground/50">{entries.length}{Array.isArray(value) ? '' : ' keys'}<Punct>{closeB}</Punct></span>}
|
||||
</button>
|
||||
{open && (
|
||||
<>
|
||||
{entries.slice(0, shown).map(([ck, cv]) => (
|
||||
<Node key={ck} k={Array.isArray(value) ? undefined : ck} value={cv} depth={depth + 1} defaultOpen={depth < 1} />
|
||||
))}
|
||||
{entries.length > shown && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLimit((l) => l + 500)}
|
||||
className="py-0.5 text-[11px] text-primary hover:underline"
|
||||
style={{ paddingLeft: `${depth * 0.9 + 1.1}rem` }}
|
||||
>
|
||||
还有 {entries.length - shown} 项,点击展开…
|
||||
</button>
|
||||
)}
|
||||
<div style={{ paddingLeft: `${depth * 0.9 + 0.9}rem` }}><Punct>{closeB}</Punct></div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function JsonTree({ data, className, maxHeight = '20rem' }: { data: unknown; className?: string; maxHeight?: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const text = (() => { try { return JSON.stringify(data, null, 2); } catch { return String(data); } })();
|
||||
|
||||
const copy = async () => {
|
||||
try {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} else {
|
||||
// navigator.clipboard is undefined on http LAN deployments — fall back
|
||||
// to the legacy execCommand path so copy still works (and shows feedback).
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.opacity = '0';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(ta);
|
||||
}
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1200);
|
||||
} catch { /* clipboard blocked */ }
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn('relative rounded-xl border border-border/60 bg-muted/30', className)}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={copy}
|
||||
title="复制 JSON"
|
||||
className="absolute right-2 top-2 z-10 inline-flex items-center gap-1 rounded-md bg-card/80 px-1.5 py-1 text-[11px] text-muted-foreground shadow-sm ring-1 ring-border/50 backdrop-blur hover:text-foreground"
|
||||
>
|
||||
{copied ? <Check className="h-3 w-3 text-success" /> : <Copy className="h-3 w-3" />}
|
||||
{copied ? '已复制' : '复制'}
|
||||
</button>
|
||||
<div className="overflow-auto p-3 font-mono text-[11.5px] leading-relaxed" style={{ maxHeight }}>
|
||||
<Node value={data} depth={0} defaultOpen />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// Picker — a searchable, windowed combobox for choosing from large lists
|
||||
// (group members can be thousands). Apple-HIG flavour built on the same idiom
|
||||
// as DropdownSelect: calm trigger matching Input height, a soft floating panel
|
||||
// with a search field, virtualised rows (avatar + name + sub), keyboard nav,
|
||||
// and an always-present escape hatch — if what you typed isn't in the list you
|
||||
// can still commit it as a raw value. Loading / error / empty states degrade to
|
||||
// the raw-value input so the picker never traps you.
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { AnimatePresence, motion } from 'motion/react';
|
||||
import { ChevronDown, Loader2, RefreshCw, Search } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface PickerOption {
|
||||
value: string;
|
||||
label: string;
|
||||
/** Secondary line (e.g. the uin under a nickname). */
|
||||
sub?: string;
|
||||
/** Avatar URL. */
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
interface PickerProps {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
options: ReadonlyArray<PickerOption>;
|
||||
loading?: boolean;
|
||||
error?: string | null;
|
||||
onRefresh?: () => void;
|
||||
placeholder?: string;
|
||||
/** Validates a typed raw value before it can be committed via the escape
|
||||
* hatch. Defaults to "non-empty". */
|
||||
validateRaw?: (raw: string) => boolean;
|
||||
ariaLabel: string;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const ROW_H = 44; // px — fixed row height drives the windowing math
|
||||
const OVERSCAN = 6;
|
||||
const PANEL_MAX = 264; // px of scroll viewport
|
||||
|
||||
export function Picker({
|
||||
value, onChange, options, loading, error, onRefresh,
|
||||
placeholder = '选择…', validateRaw, ariaLabel, className, disabled,
|
||||
}: PickerProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState('');
|
||||
const [scrollTop, setScrollTop] = useState(0);
|
||||
const [active, setActive] = useState(0);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const searchRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const selected = options.find((o) => o.value === value);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return options;
|
||||
return options.filter((o) => o.label.toLowerCase().includes(q) || o.value.includes(q) || (o.sub?.toLowerCase().includes(q) ?? false));
|
||||
}, [options, query]);
|
||||
|
||||
// The escape-hatch row: show when the query is a committable raw value that
|
||||
// isn't already an exact option.
|
||||
const canRaw = query.trim() !== '' && (validateRaw ? validateRaw(query.trim()) : true)
|
||||
&& !options.some((o) => o.value === query.trim());
|
||||
const rawRow = canRaw ? query.trim() : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setScrollTop(0);
|
||||
setActive(0);
|
||||
const t = setTimeout(() => searchRef.current?.focus(), 10);
|
||||
const onPointer = (e: PointerEvent) => {
|
||||
if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
document.addEventListener('pointerdown', onPointer);
|
||||
return () => { clearTimeout(t); document.removeEventListener('pointerdown', onPointer); };
|
||||
}, [open]);
|
||||
|
||||
const totalRows = filtered.length + (rawRow ? 1 : 0);
|
||||
// Keep the keyboard cursor in range when the list shrinks (refresh / typing)
|
||||
// without a keystroke that would have reset it.
|
||||
useEffect(() => {
|
||||
setActive((a) => Math.min(a, Math.max(0, totalRows - 1)));
|
||||
}, [totalRows]);
|
||||
const viewH = Math.min(PANEL_MAX, totalRows * ROW_H);
|
||||
const start = Math.max(0, Math.floor(scrollTop / ROW_H) - OVERSCAN);
|
||||
const end = Math.min(totalRows, Math.ceil((scrollTop + viewH) / ROW_H) + OVERSCAN);
|
||||
|
||||
const commit = (v: string) => { onChange(v); setOpen(false); setQuery(''); };
|
||||
|
||||
const choose = (idx: number) => {
|
||||
if (rawRow && idx === filtered.length) commit(rawRow);
|
||||
else { const o = filtered[idx]; if (o) commit(o.value); }
|
||||
};
|
||||
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setOpen(false); return; }
|
||||
if (e.key === 'ArrowDown') { e.preventDefault(); setActive((a) => Math.min(totalRows - 1, a + 1)); }
|
||||
else if (e.key === 'ArrowUp') { e.preventDefault(); setActive((a) => Math.max(0, a - 1)); }
|
||||
else if (e.key === 'Enter') { e.preventDefault(); choose(active); }
|
||||
};
|
||||
|
||||
// Keep the active row scrolled into view.
|
||||
useEffect(() => {
|
||||
if (!open || !listRef.current) return;
|
||||
const top = active * ROW_H;
|
||||
const el = listRef.current;
|
||||
if (top < el.scrollTop) el.scrollTop = top;
|
||||
else if (top + ROW_H > el.scrollTop + el.clientHeight) el.scrollTop = top + ROW_H - el.clientHeight;
|
||||
}, [active, open]);
|
||||
|
||||
const rows: { idx: number; opt: PickerOption | null }[] = [];
|
||||
for (let i = start; i < end; i++) {
|
||||
if (rawRow && i === filtered.length) rows.push({ idx: i, opt: null });
|
||||
else rows.push({ idx: i, opt: filtered[i] ?? null });
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={rootRef} className={cn('relative', className)} onKeyDown={onKeyDown}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
aria-label={ariaLabel}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
onClick={() => !disabled && setOpen((v) => !v)}
|
||||
className={cn(
|
||||
'flex h-9 w-full items-center gap-2 rounded-md border border-border bg-transparent px-3 text-sm outline-none transition-colors',
|
||||
'focus-visible:ring-[3px] focus-visible:ring-ring/40 focus-visible:border-ring disabled:opacity-50',
|
||||
!selected && !value && 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{selected?.avatar && <img src={selected.avatar} alt="" className="h-5 w-5 shrink-0 rounded-full" />}
|
||||
<span className="min-w-0 flex-1 truncate text-left">
|
||||
{selected ? selected.label : value || placeholder}
|
||||
{selected?.sub && <span className="ml-1.5 text-xs text-muted-foreground tabular-nums">{selected.sub}</span>}
|
||||
</span>
|
||||
<ChevronDown className={cn('h-4 w-4 shrink-0 text-muted-foreground transition-transform', open && 'rotate-180')} />
|
||||
</button>
|
||||
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -4, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: -4, scale: 0.98 }}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 38 }}
|
||||
className="absolute z-50 mt-1.5 w-full overflow-hidden rounded-xl border border-border/60 bg-popover shadow-lg ring-1 ring-black/5"
|
||||
>
|
||||
<div className="flex items-center gap-2 border-b border-border/60 px-2.5 py-2">
|
||||
<Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
<input
|
||||
ref={searchRef}
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setActive(0);
|
||||
setScrollTop(0);
|
||||
if (listRef.current) listRef.current.scrollTop = 0;
|
||||
}}
|
||||
placeholder="搜索名称 / 号码…"
|
||||
className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
|
||||
/>
|
||||
{onRefresh && (
|
||||
<button type="button" title="刷新" onClick={onRefresh}
|
||||
className="shrink-0 text-muted-foreground hover:text-foreground">
|
||||
<RefreshCw className={cn('h-3.5 w-3.5', loading && 'animate-spin')} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{loading && options.length === 0 ? (
|
||||
<div className="flex items-center justify-center gap-2 py-8 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" /> 加载中…
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="px-3 py-6 text-center text-xs text-muted-foreground">
|
||||
<p className="text-destructive">{error}</p>
|
||||
<p className="mt-1">可直接在上方输入号码后回车使用</p>
|
||||
</div>
|
||||
) : totalRows === 0 ? (
|
||||
<div className="px-3 py-6 text-center text-xs text-muted-foreground">无匹配项{query && ';输入完整号码可直接使用'}</div>
|
||||
) : (
|
||||
<div
|
||||
ref={listRef}
|
||||
role="listbox"
|
||||
onScroll={(e) => setScrollTop((e.target as HTMLDivElement).scrollTop)}
|
||||
className="overflow-auto"
|
||||
style={{ height: viewH }}
|
||||
>
|
||||
<div style={{ height: totalRows * ROW_H, position: 'relative' }}>
|
||||
{rows.map(({ idx, opt }) => (
|
||||
<div
|
||||
key={opt ? opt.value : `__raw-${idx}`}
|
||||
role="option"
|
||||
aria-selected={idx === active}
|
||||
onMouseEnter={() => setActive(idx)}
|
||||
onClick={() => choose(idx)}
|
||||
className={cn(
|
||||
'absolute left-0 right-0 flex cursor-pointer items-center gap-2.5 px-3',
|
||||
idx === active ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50',
|
||||
)}
|
||||
style={{ top: idx * ROW_H, height: ROW_H }}
|
||||
>
|
||||
{opt ? (
|
||||
<>
|
||||
{opt.avatar
|
||||
? <img src={opt.avatar} alt="" className="h-7 w-7 shrink-0 rounded-full" />
|
||||
: <span className="h-7 w-7 shrink-0 rounded-full bg-muted" />}
|
||||
<span className="min-w-0 flex-1 truncate text-sm">{opt.label}</span>
|
||||
{opt.sub && <span className="shrink-0 font-mono text-[11px] text-muted-foreground tabular-nums">{opt.sub}</span>}
|
||||
</>
|
||||
) : (
|
||||
<span className="text-sm">使用 <span className="font-mono text-primary">{rawRow}</span></span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// Tabs — a horizontal tab bar with an Apple-HIG sliding indicator. Shares the
|
||||
// spring-pill idiom of the debug page's segmented control but scaled up for
|
||||
// top-level section switching, with full roving-tabindex keyboard support
|
||||
// (←/→/Home/End). Generic over a string union of tab ids.
|
||||
import { useId, useRef, type ReactNode } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface TabItem<T extends string> {
|
||||
value: T;
|
||||
label: ReactNode;
|
||||
/** Optional leading icon (already sized by the caller, ~16px). */
|
||||
icon?: ReactNode;
|
||||
/** Optional trailing count / badge. */
|
||||
badge?: ReactNode;
|
||||
}
|
||||
|
||||
interface TabsProps<T extends string> {
|
||||
value: T;
|
||||
onChange: (v: T) => void;
|
||||
items: ReadonlyArray<TabItem<T>>;
|
||||
className?: string;
|
||||
'aria-label'?: string;
|
||||
}
|
||||
|
||||
export function Tabs<T extends string>({ value, onChange, items, className, ...rest }: TabsProps<T>) {
|
||||
const layoutId = useId();
|
||||
const refs = useRef<(HTMLButtonElement | null)[]>([]);
|
||||
|
||||
const move = (from: number, dir: 1 | -1 | 'home' | 'end') => {
|
||||
const n = items.length;
|
||||
let to: number;
|
||||
if (dir === 'home') to = 0;
|
||||
else if (dir === 'end') to = n - 1;
|
||||
else to = (from + dir + n) % n;
|
||||
const next = items[to];
|
||||
if (next) { onChange(next.value); refs.current[to]?.focus(); }
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={rest['aria-label']}
|
||||
className={cn('relative flex items-center gap-1 overflow-x-auto', className)}
|
||||
>
|
||||
{items.map((it, i) => {
|
||||
const active = it.value === value;
|
||||
return (
|
||||
<button
|
||||
key={it.value}
|
||||
ref={(el) => { refs.current[i] = el; }}
|
||||
role="tab"
|
||||
type="button"
|
||||
aria-selected={active}
|
||||
tabIndex={active ? 0 : -1}
|
||||
onClick={() => onChange(it.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'ArrowRight') { e.preventDefault(); move(i, 1); }
|
||||
else if (e.key === 'ArrowLeft') { e.preventDefault(); move(i, -1); }
|
||||
else if (e.key === 'Home') { e.preventDefault(); move(i, 'home'); }
|
||||
else if (e.key === 'End') { e.preventDefault(); move(i, 'end'); }
|
||||
}}
|
||||
className={cn(
|
||||
'relative z-10 inline-flex shrink-0 items-center gap-2 rounded-xl px-3.5 py-2 text-sm font-medium outline-none transition-colors',
|
||||
'focus-visible:ring-[3px] focus-visible:ring-ring/40',
|
||||
active ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{active && (
|
||||
<motion.span
|
||||
layoutId={`tabs-${layoutId}`}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 40 }}
|
||||
className="absolute inset-0 -z-10 rounded-xl bg-card shadow-sm ring-1 ring-border/60"
|
||||
/>
|
||||
)}
|
||||
{it.icon}
|
||||
<span>{it.label}</span>
|
||||
{it.badge != null && (
|
||||
<span className={cn('rounded-full px-1.5 text-[11px] tabular-nums',
|
||||
active ? 'bg-primary/12 text-primary' : 'bg-muted text-muted-foreground')}>
|
||||
{it.badge}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user