import { Component, useCallback, useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react' import { useLocation, useNavigate, useParams } from 'react-router-dom' import type { ButtonHTMLAttributes, CSSProperties, ErrorInfo, KeyboardEvent as ReactKeyboardEvent, ReactNode, RefObject, } from 'react' import { AlertCircle, AlertTriangle, Check, CheckCircle2, CloudOff, Copy, Info, Loader2, RotateCw, Trash2, X, } from 'lucide-react' import clsx from 'clsx' import { CATALOG_LABELS, catalogListState, useCatalog } from '../store/catalog' import type { CatalogKey } from '../store/catalog' import { humanizeError } from '../lib/errors' import { actorHeader } from '../api/http' import { ariaShortcut, formatShortcut } from '../lib/keys' import { STATUS, statusMeta } from '../lib/status' import type { StatusShape } from '../lib/status' import { formatDateTime, formatDuration, formatRelative, formatTime } from '../lib/format' import type { HealthRecord } from '../lib/health' import { useRunClock } from '../run/useRunClock' /** * 输入法正在组字吗。组字期间的回车是"选词",不是"提交"——不判这一条,中文 * 用户每选一个词就把半句话发出去一次(问数据页就这么把半句问题送去建图、跑图)。 * Safari 在结束组字的那一下 keydown 上 isComposing 已经是 false,keyCode 还是 * 229,两个都得看。所有"回车即提交"的输入框都要过这一关,Esc 关弹窗也一样: * 组字时按 Esc 是在取消候选词。 */ export function isComposing(e: ReactKeyboardEvent | KeyboardEvent): boolean { const native = 'nativeEvent' in e ? e.nativeEvent : e return native.isComposing || e.keyCode === 229 } /** * 错误边界。没有它,任何一个组件渲染时抛错,React 会卸掉整棵树——整站白屏, * 导航栏也没了,用户只能刷新,没保存的编辑跟着丢。 * * scope 说明兜的是哪一层: * - page(默认):App 里包在路由外面,出错只换掉内容区,导航还在,换一页(resetKey * 变了)就自动恢复; * - shell:main.tsx 里包着整个 App,这时导航也没了,文案不能再说「这一页」。 * title 可以再覆盖标题。编辑中的图在 store 里、不在组件树上,点「重试」重新渲染时它还在。 * * 技术信息(error.message)收进「技术细节」折叠区并能复制:对用户是噪音,对 * 排障是全部线索。role=alert 只包标题和那句说明:按钮和技术细节也在里面的话, * 读屏会把「重试 刷新页面 技术细节…」连同堆栈摘要一起当成警报念出来。 */ export class ErrorBoundary extends Component< { resetKey?: string; scope?: 'page' | 'shell' | 'block'; title?: string; children: ReactNode }, { error: Error | null } > { state: { error: Error | null } = { error: null } static getDerivedStateFromError(error: Error) { return { error } } componentDidCatch(error: Error, info: ErrorInfo) { console.error('页面渲染出错', error, info.componentStack) } componentDidUpdate(prev: { resetKey?: string }) { if (prev.resetKey !== this.props.resetKey && this.state.error) this.setState({ error: null }) } render() { const { error } = this.state if (!error) return this.props.children // V8 的 stack 第一行就是「类名: 消息」,再拼一遍就重复了 const raw = error.stack?.includes(error.message) ? error.stack : `${error.name}: ${error.message}${error.stack ? `\n\n${error.stack}` : ''}` const shell = this.props.scope === 'shell' // 页面里的一块(应用页的一个组件):只坏它自己,就地一行说明,不占整页 if (this.props.scope === 'block') { return (
{this.props.title ?? '这一块无法显示'}
) } return (
{this.props.title ?? (shell ? '界面发生错误' : '页面发生错误')}
{shell ? '导航和页面已停止响应。' : ''}未保存的编辑仍保留在内存中:请先点击「重试」,恢复后尽快保存。
) } } /** 「技术细节」折叠区:原文给运维复制用,默认收起 */ export function TechDetails({ raw, summary, className }: { raw: string; summary?: string; className?: string }) { return (
技术细节{summary ? · {summary.length > 60 ? `${summary.slice(0, 60)}…` : summary} : null}
          {raw}
        
) } // ------------------------------------------------------------------------- // Toast // ------------------------------------------------------------------------- /** * 全站最主要的提示手段,所以错误和成功不能一样权重、一样寿命: * - 普通和成功的约 4 秒消失,悬停或聚焦时暂停计时; * - 出错的常驻,直到点 ×,并且能复制详情——长错误 4 秒读不完,也要能贴给运维; * - 带动作的(「打开」「撤销」)多留一会儿; * - 同样的内容不叠,计数 ×N;最多露 3 条,其余收成「还有 N 条」。 * * 状态放在模块里而不是 Context:store、lib 里也要能弹(toast.error(e)), * 不必把 hook 一路传下去。useToast() 照旧可用,返回的就是这个 toast。 */ export type ToastKind = 'info' | 'ok' | 'warn' | 'error' export interface ToastAction { label: string onClick: () => void } export interface ToastOptions { /** 详情:出错时的原文、长说明。折叠显示,复制按钮复制它 */ detail?: string action?: ToastAction /** 常驻到手动关闭。error 默认常驻 */ sticky?: boolean /** 自动消失前停留多久(ms)。默认 4000,带动作的 6000 */ duration?: number /** 去重键。默认按「类型 + 文字」去重 */ key?: string } interface ToastItem { id: number kind: ToastKind text: string detail?: string action?: ToastAction sticky: boolean duration: number count: number key: string /** 重复触发时加一,计时从头算 */ bump: number } let toastSeq = 0 let toastItems: ToastItem[] = [] const toastListeners = new Set<() => void>() const emitToasts = () => toastListeners.forEach((l) => l()) const subscribeToasts = (l: () => void) => { toastListeners.add(l) return () => { toastListeners.delete(l) } } function pushToast(text: string, kind: ToastKind = 'info', opts: ToastOptions = {}): number { const key = opts.key ?? `${kind}:${text}` const same = toastItems.find((t) => t.key === key) if (same) { toastItems = toastItems.map((t) => (t === same ? { ...t, count: t.count + 1, bump: t.bump + 1, detail: opts.detail ?? t.detail, action: opts.action ?? t.action } : t)) emitToasts() return same.id } const id = ++toastSeq toastItems = [...toastItems, { id, kind, text, key, count: 1, bump: 0, detail: opts.detail, action: opts.action, sticky: opts.sticky ?? kind === 'error', duration: opts.duration ?? (opts.action ? 6000 : 4000), }] emitToasts() return id } function dismissToast(id?: number) { toastItems = id == null ? [] : toastItems.filter((t) => t.id !== id) emitToasts() } export interface ToastFn { /** 老写法:toast(text, kind) 照旧可用 */ (text: string, kind?: ToastKind, opts?: ToastOptions): number ok: (text: string, opts?: ToastOptions) => number info: (text: string, opts?: ToastOptions) => number warn: (text: string, opts?: ToastOptions) => number /** * 出错提示。msg 可以直接给捕获到的异常:会翻成人话(humanizeError),原文放进 * detail。常驻、可关、可复制。 */ error: (msg: unknown, opts?: ToastOptions) => number dismiss: (id?: number) => void } export const toast: ToastFn = Object.assign( (text: string, kind?: ToastKind, opts?: ToastOptions) => pushToast(text, kind, opts), { ok: (text: string, opts?: ToastOptions) => pushToast(text, 'ok', opts), info: (text: string, opts?: ToastOptions) => pushToast(text, 'info', opts), warn: (text: string, opts?: ToastOptions) => pushToast(text, 'warn', opts), error: (msg: unknown, opts?: ToastOptions) => { if (typeof msg === 'string') return pushToast(msg, 'error', opts) const h = humanizeError(msg) const text = h.reason ? `${h.title}:${h.reason}` : h.title return pushToast(text, 'error', { ...opts, detail: opts?.detail ?? h.raw }) }, dismiss: dismissToast, }, ) export const useToast = () => toast const TOAST_VISIBLE = 3 /** * 挂在应用根部,包住整个应用(main.tsx 里已经这样挂着)。顺带渲染 DialogHost: * 两者都是"根部浮层",挂一处就都有了;App 里再显式挂一个 DialogHost 也不会 * 重复弹——只有第一个挂上的会渲染。 * * 位置在内容区顶部居中、各页工具栏的下沿之下:右下角正好压在助手栏的输入区 * 上,问数据页的输入框又在底部居中;贴着顶边又会盖住工具栏右侧的按钮(1280 宽 * 时画布的 Copilot 按钮),而出错的 toast 是常驻的,一直盖着。工具栏最高 48px, * 离线横幅出现时再让出它的高度。左边让出 64px 的导航栏(App 里的 w-16),在内容区 * 里居中。 */ export function ToastHost({ children }: { children?: ReactNode }) { const items = useSyncExternalStore(subscribeToasts, () => toastItems, () => toastItems) const [expanded, setExpanded] = useState(false) const hidden = expanded ? 0 : Math.max(0, items.length - TOAST_VISIBLE) const shown = items.slice(hidden) useEffect(() => { if (items.length <= TOAST_VISIBLE) setExpanded(false) }, [items.length]) return ( <> {children}
{hidden > 0 && ( )} {/* 两个播报区要一直在:读屏只播报「已存在的 live 区域里新增的内容」 */}
{shown.filter((t) => t.kind === 'error').map((t) => )}
{shown.filter((t) => t.kind !== 'error').map((t) => )}
{expanded && items.length > TOAST_VISIBLE && ( )}
) } const TOAST_ICON: Record = { ok: { Icon: CheckCircle2, color: 'var(--ok)' }, info: { Icon: Info, color: 'var(--text-dim)' }, warn: { Icon: AlertTriangle, color: 'var(--warn)' }, error: { Icon: AlertCircle, color: 'var(--err)' }, } function ToastCard({ item }: { item: ToastItem }) { const [paused, setPaused] = useState(false) const remaining = useRef(item.duration) const startedAt = useRef(0) // 重复触发时计时从头算:同一条提示又来了一次,说明它仍然是新鲜的 useEffect(() => { remaining.current = item.duration }, [item.bump, item.duration]) useEffect(() => { if (item.sticky || paused) return startedAt.current = Date.now() const timer = setTimeout(() => dismissToast(item.id), remaining.current) return () => { clearTimeout(timer) remaining.current = Math.max(800, remaining.current - (Date.now() - startedAt.current)) } }, [item.sticky, item.id, paused, item.bump]) const { Icon, color } = TOAST_ICON[item.kind] const copyText = item.detail ? `${item.text}\n\n${item.detail}` : item.text return (
setPaused(true)} onMouseLeave={() => setPaused(false)} onFocus={() => setPaused(true)} onBlur={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node)) setPaused(false) }} >
{item.text} {item.count > 1 && ×{item.count}}
{item.detail && (
详情
              {item.detail}
            
)}
{item.action && ( )} {item.kind === 'error' && }
) } function CopyIconButton({ text, label = '复制详情' }: { text: string; label?: string }) { const [done, setDone] = useState(false) return ( ) } // ------------------------------------------------------------------------- // Modal // ------------------------------------------------------------------------- /** 打开着的弹窗,后开的在上。键盘只归最上面那个管,嵌套时 Esc 只关一层 */ const modalStack: object[] = [] const isTopModal = (token: object) => modalStack[modalStack.length - 1] === token const FOCUSABLE = [ 'a[href]', 'button:not([disabled])', 'input:not([disabled]):not([type="hidden"])', 'select:not([disabled])', 'textarea:not([disabled])', 'summary', '[tabindex]:not([tabindex="-1"])', '[contenteditable="true"]', ].join(',') function focusables(root: HTMLElement): HTMLElement[] { return Array.from(root.querySelectorAll(FOCUSABLE)) .filter((el) => el.getClientRects().length > 0 && !el.closest('[inert]')) } /** * 弹窗。 * * - 焦点困在弹窗里(Tab / Shift+Tab 循环),关闭后回到打开前的那个元素; * - 打开时聚焦:initialFocus → 带 data-autofocus 的元素 → 第一个输入框 → 弹窗本身; * - Esc 过输入法组字判断:中文输入法里按 Esc 是在取消候选词,不是要关窗; * - 点遮罩关闭要求按下和松开都落在遮罩上:在输入框里拖选文字拖出了界,不该关; * - dirty 时 Esc、点遮罩、点 × 都先在底部问一句「放弃 / 继续编辑」。Skill 指令、 * 自定义工具代码、数据源连接信息都是难重填的长内容,误触一下就全没了。 * footer 里调用方自己的「取消」按钮是明确意图,不拦。 */ export function Modal({ open, onClose, title, children, footer, width = 560, dirty = false, initialFocus, describedBy, }: { open: boolean; onClose: () => void; title: ReactNode children: ReactNode; footer?: ReactNode; width?: number /** 有未保存的改动:关闭前先问 */ dirty?: boolean /** 打开时要聚焦的元素 */ initialFocus?: RefObject /** 正文说明的元素 id,接到 aria-describedby */ describedBy?: string }) { const titleId = useId() const rootRef = useRef(null) const panelRef = useRef(null) const keepRef = useRef(null) const tokenRef = useRef({}) const downOnBackdrop = useRef(false) const upOnBackdrop = useRef(false) const lastInside = useRef(null) const [asking, setAsking] = useState(false) const onCloseRef = useRef(onClose) onCloseRef.current = onClose const dirtyRef = useRef(dirty) dirtyRef.current = dirty // 改动撤回了(比如用户把内容删回原样),询问条就没有意义了 useEffect(() => { if (!dirty) setAsking(false) }, [dirty]) useEffect(() => { if (!open) setAsking(false) }, [open]) const requestClose = useCallback(() => { if (!dirtyRef.current) { onCloseRef.current(); return } const active = document.activeElement if (active instanceof HTMLElement && panelRef.current?.contains(active)) lastInside.current = active setAsking(true) }, []) // 询问条出现时把焦点给「继续编辑」:这时按回车应当是最安全的那个选择 useEffect(() => { if (asking) keepRef.current?.focus() }, [asking]) const keepEditing = () => { setAsking(false) const back = lastInside.current requestAnimationFrame(() => (back?.isConnected ? back : panelRef.current)?.focus()) } useEffect(() => { if (!open) return const token = tokenRef.current const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null modalStack.push(token) const frame = requestAnimationFrame(() => { const panel = panelRef.current if (!panel || panel.contains(document.activeElement)) return // 调用方自己 autoFocus 过了 const target = initialFocus?.current ?? panel.querySelector('[data-autofocus]') ?? panel.querySelector( '[data-modal-body] input:not([disabled]):not([type="hidden"]):not([type="checkbox"]):not([type="radio"]), [data-modal-body] textarea:not([disabled]), [data-modal-body] select:not([disabled])') ?? panel target.focus({ preventScroll: true }) }) // 焦点落在弹窗外(比如点了遮罩上的空白,焦点掉到 body)时,键盘仍然归它管 const onWindowKey = (e: KeyboardEvent) => { if (!isTopModal(token) || rootRef.current?.contains(e.target as Node)) return if (e.key === 'Escape' && !isComposing(e) && !e.defaultPrevented) { e.preventDefault() requestClose() } else if (e.key === 'Tab') { e.preventDefault() const panel = panelRef.current if (panel) (focusables(panel)[0] ?? panel).focus() } } window.addEventListener('keydown', onWindowKey) return () => { cancelAnimationFrame(frame) window.removeEventListener('keydown', onWindowKey) const i = modalStack.lastIndexOf(token) if (i >= 0) modalStack.splice(i, 1) // 焦点还给打开它的那个元素;如果焦点已经被别处拿走(比如关窗后跳了页),不抢 const active = document.activeElement const stillOurs = !active || active === document.body || rootRef.current?.contains(active) if (opener?.isConnected && stillOurs) opener.focus({ preventScroll: true }) } // initialFocus 只在打开那一刻用,不进依赖 }, [open, requestClose]) const onKeyDown = (e: ReactKeyboardEvent) => { if (!isTopModal(tokenRef.current)) return if (e.key === 'Escape') { // 里面的组件(补全弹层、下拉)自己处理过 Esc 的,不再关窗 if (isComposing(e) || e.defaultPrevented) return e.preventDefault() // 拦住冒泡:画布属性面板之类在 window 上监听 Esc 的,不该跟着一起关 e.stopPropagation() if (asking) keepEditing() else requestClose() return } if (e.key === 'Tab') { const panel = panelRef.current if (!panel) return const list = focusables(panel) if (!list.length) { e.preventDefault(); panel.focus(); return } const first = list[0] const last = list[list.length - 1] const active = document.activeElement if (e.shiftKey && (active === first || active === panel || !panel.contains(active))) { e.preventDefault() last.focus() } else if (!e.shiftKey && (active === last || !panel.contains(active))) { e.preventDefault() first.focus() } } } if (!open) return null return (
{ downOnBackdrop.current = e.target === e.currentTarget // 按在遮罩上不让焦点掉到 body:弹窗还开着,键盘(回车、Tab)得还归它 if (downOnBackdrop.current) e.preventDefault() }} onMouseUp={(e) => { upOnBackdrop.current = e.target === e.currentTarget }} onClick={(e) => { const both = downOnBackdrop.current && upOnBackdrop.current && e.target === e.currentTarget downOnBackdrop.current = false upOnBackdrop.current = false if (both) requestClose() }} onKeyDown={onKeyDown} >

{title}

{children}
{asking && (
有未保存的修改,关闭后将丢失。
)} {footer &&
{footer}
}
) } // ------------------------------------------------------------------------- // 确认 / 输入对话框(命令式) // ------------------------------------------------------------------------- export interface DialogOptions { /** 用动词写:「删除工作流「⑥ 多 Agent 协作」?」 */ title: string body?: ReactNode /** 后果清单:「连同 4 条运行记录一起删除」「不可恢复」 */ consequences?: string[] /** 写具体动作:「删除 5 条记录」,不写「确定」 */ confirmLabel?: string cancelLabel?: string /** 危险操作:确认按钮标红,初始焦点放在「取消」上,回车不会误触 */ danger?: boolean /** 要求照抄这段文字才能确认(高代价操作) */ requireText?: string placeholder?: string /** promptDialog 的初值 */ initial?: string /** promptDialog 的输入框标签 */ label?: string /** promptDialog:返回错误文字则不让提交。allowEmpty 时空输入不经过它 */ validate?: (value: string) => string | null | undefined /** * promptDialog:允许不填,空输入(含只有空白)也能确认,返回空字符串。默认关:多数输入框(名称、必填的理由) * 空着提交没有意义,照旧报「不能为空」。用于可选的理由这类「填了更好、不填也成立」的输入,否则调用方只能 * 退回不带输入框的 confirmDialog,想写的人也没处写 */ allowEmpty?: boolean } interface DialogRequest { id: number kind: 'confirm' | 'prompt' opts: DialogOptions resolve: (value: any) => void } let dialogSeq = 0 let dialogQueue: DialogRequest[] = [] let dialogHosts: object[] = [] let dialogSnapshot = { queue: dialogQueue, host: dialogHosts[0] as object | undefined } const dialogListeners = new Set<() => void>() const emitDialogs = () => { dialogSnapshot = { queue: dialogQueue, host: dialogHosts[0] } dialogListeners.forEach((l) => l()) } const subscribeDialogs = (l: () => void) => { dialogListeners.add(l) return () => { dialogListeners.delete(l) } } function plainText(opts: DialogOptions): string { const lines = [opts.title] if (typeof opts.body === 'string') lines.push(opts.body) if (opts.consequences?.length) lines.push(...opts.consequences.map((c) => `· ${c}`)) return lines.join('\n\n') } function enqueue(kind: DialogRequest['kind'], opts: DialogOptions): Promise { return new Promise((resolve) => { dialogQueue = [...dialogQueue, { id: ++dialogSeq, kind, opts, resolve }] emitDialogs() }) } /** * 确认对话框,替代 window.confirm:样式跟主题走、能写后果、危险操作回车不误触。 * * if (!(await confirmDialog({ title: '删除这条运行记录?', danger: true, * consequences: ['事件流和产出物一起删除,不可恢复'], confirmLabel: '删除记录' }))) return * * 没有挂 DialogHost 时退回原生 confirm,调用方不会因此永远等下去。 */ export function confirmDialog(opts: DialogOptions): Promise { if (!dialogHosts.length) return Promise.resolve(window.confirm(plainText(opts))) return enqueue('confirm', opts) } /** 输入对话框,替代 window.prompt。取消返回 null,确定返回去掉首尾空白的文字(allowEmpty 时可能是空字符串) */ export function promptDialog(opts: DialogOptions): Promise { if (!dialogHosts.length) { const v = window.prompt(plainText(opts), opts.initial ?? '') return Promise.resolve(v == null ? null : v.trim()) } return enqueue('prompt', opts) } /** * 渲染 confirmDialog / promptDialog 的地方。ToastHost 已经带了一个;多挂几个也 * 只有第一个生效。 */ export function DialogHost() { const [token] = useState(() => ({})) useEffect(() => { dialogHosts = [...dialogHosts, token] emitDialogs() return () => { dialogHosts = dialogHosts.filter((t) => t !== token) emitDialogs() } }, [token]) const { queue, host } = useSyncExternalStore(subscribeDialogs, () => dialogSnapshot, () => dialogSnapshot) if (host !== token || !queue.length) return null const req = queue[0] return } function DialogView({ req }: { req: DialogRequest }) { const { opts, kind } = req const [value, setValue] = useState(opts.initial ?? '') const [open, setOpen] = useState(true) const inputId = useId() const bodyId = useId() const finish = (result: unknown) => { setOpen(false) req.resolve(result) dialogQueue = dialogQueue.filter((d) => d !== req) emitDialogs() } const cancel = () => finish(kind === 'prompt' ? null : false) const trimmed = value.trim() const invalid = kind === 'prompt' ? (!trimmed ? (opts.allowEmpty ? null : '不能为空') : opts.validate?.(trimmed) || null) : null const textOk = opts.requireText == null || value === opts.requireText const canConfirm = kind === 'prompt' ? !invalid && textOk : textOk const confirm = () => { if (!canConfirm) return finish(kind === 'prompt' ? trimmed : true) } const onEnter = (e: ReactKeyboardEvent) => { if (e.key === 'Enter' && !isComposing(e)) { e.preventDefault() confirm() } } const confirmLabel = opts.confirmLabel ?? (opts.danger ? '删除' : '确定') const showInput = kind === 'prompt' || opts.requireText != null return ( } >
{(opts.body || opts.consequences?.length) && (
{opts.body &&
{opts.body}
} {!!opts.consequences?.length && (
    {opts.consequences.map((c, i) => (
  • {c}
  • ))}
)}
)} {showInput && ( 输入「{opts.requireText}」以确认} htmlFor={inputId} error={kind === 'prompt' && value && invalid ? invalid : undefined} > setValue(e.target.value)} onKeyDown={onEnter} onFocus={(e) => { if (kind === 'prompt') e.currentTarget.select() }} autoComplete="off" spellCheck={false} aria-invalid={kind === 'prompt' && !!value && !!invalid} data-autofocus="" /> )}
) } // ------------------------------------------------------------------------- // 空态、错误、离线、加载 // ------------------------------------------------------------------------- export const Spinner = ({ size = 14 }: { size?: number }) => ( ) /** * 空态。 * * 默认感知连接状态:后端断开时"空"不代表"没有",改说「暂时拿不到数据」并把 * 「新建」这类动作收起来——之前后端挂了,整站都在说「还没有工作流」并引导新建, * 用户照做就是一堆重复配置。纯本地的空(比如搜索没匹配)传 offline={false}。 * * 后端连着也可能是假的空:某张表卡着没回来、超时或报错,列表照样是 []。这份空 * 来自 catalog 的哪张表,就把 source 传进来(source="workflows"),那张表从没 * 取回来过时改说「还在读取 / 没取回来」,同样收起动作。 */ export function EmptyState({ icon, title, body, action, offline = 'auto', source, className }: { icon?: ReactNode; title: string; body?: ReactNode; action?: ReactNode offline?: 'auto' | false /** 这份空来自 catalog 的哪张表。页面自己拉的列表不传,自己区分加载中和出错 */ source?: CatalogKey className?: string }) { const backend = useCatalog((s) => s.backend) const checkBackend = useCatalog((s) => s.checkBackend) const list = useCatalog((s) => (source && offline === 'auto' ? catalogListState(s, source) : 'ok')) const listError = useCatalog((s) => (source && offline === 'auto' && catalogListState(s, source) === 'error' ? s.checks.find((c) => c.key === source)?.error ?? null : null)) if (offline === 'auto' && source && (list === 'loading' || list === 'error')) { const label = CATALOG_LABELS[source] const loading = list === 'loading' return (
{loading ? : }
{loading ? `正在读取${label}` : `${label}加载失败`}
{loading ? '正在从服务端加载列表。加载完成前,列表为空不代表没有数据。' : <>{listError ? `${humanizeError(listError).title.replace(/[。.!!]$/, '')}。` : ''}此处显示为空不代表没有数据。}
{!loading && ( )}
) } if (offline === 'auto' && backend === 'down') { return (
暂时无法获取数据
{/* 不写「连上后会自动刷新」:页面自己拉的列表要接了 useOnReconnect 才会重拉, 这句话对没接的页面是假的 */}
未连接到服务端。此处显示为空不代表没有数据。
) } return (
{icon &&
{icon}
}
{title}
{body &&
{body}
} {action &&
{action}
}
) } /** 老名字。hint 就是 EmptyState 的 body */ export function Empty({ icon, title, hint, action, offline, source }: { icon?: ReactNode; title: string; hint?: string; action?: ReactNode; offline?: 'auto' | false; source?: CatalogKey }) { return } /** * 出错态:先一句人话,再原因和怎么办,原文收进「技术细节」。 * compact 用在对话轮次、运行流这类行内位置(左对齐、不撑满)。 */ export function ErrorState({ error, onRetry, compact = false, className }: { error: unknown; onRetry?: () => void; compact?: boolean; className?: string }) { const h = humanizeError(error) const Icon = h.kind === 'network' ? CloudOff : AlertCircle if (compact) { return (
{h.title}
{h.reason &&
{h.reason}
} {h.action &&
{h.action}
} {h.raw && h.raw !== h.title && }
{onRetry && }
) } return (
{h.title}
{h.reason &&
{h.reason}
} {h.action &&
{h.action}
} {onRetry && ( )} {h.raw && h.raw !== h.title && }
) } /** 同 ErrorState compact:对话轮次、运行流里轮次级的报错 */ export function ErrorNotice(props: { error: unknown; onRetry?: () => void; className?: string }) { return } export type NoticeTone = 'warn' | 'err' | 'info' /** * 页面里的提示条:一句结论加可选的细节(children),按语气配色和图标。info 是 status(读屏礼貌播报), * warn / err 是 alert。attr 原样挂到根节点上,给检查脚本定位(data-wizard-notice 之类)。 * * 原来是导入向导的局部组件,期 3 的修复面板、累积计划和版本页都要用,挪到这里共用,不各造一份 */ export function Notice({ tone, children, attr, className }: { tone: NoticeTone; children: ReactNode; attr?: Record; className?: string }) { const color = tone === 'err' ? 'var(--err)' : tone === 'warn' ? 'var(--warn)' : 'var(--accent)' return (
{tone === 'info' ? : }
{children}
) } /** * 每 ms 毫秒重渲染一次的「现在」,给倒计时、「3 分钟前」这类相对时间保鲜。 * 只在 active 时计时,不做常驻定时器;页面不可见时不跳,回到前台立刻补一拍, * 不让人看到一个停在几分钟前的数。 * * 算相对时间时要现取 Date.now():返回值是上一拍的时刻,比刚到的结果还早,拿它 * 算会把「刚刚」写成一个钟点。运行计时(100ms 一跳、全站同拍)用 useRunClock。 */ export function useTicker(ms: number, active = true): number { const [now, setNow] = useState(() => Date.now()) const started = useRef(false) useEffect(() => { // 挂载那一次不补:初值就是此刻。之后(从停着变成走着)要补,否则头一拍要等满 // ms,离线横幅刚出来时的倒计时就是拿挂载时刻算的 const first = !started.current started.current = true if (!active) return if (!first) setNow(Date.now()) const tick = () => { if (!document.hidden) setNow(Date.now()) } const t = setInterval(tick, ms) document.addEventListener('visibilitychange', tick) return () => { clearInterval(t) document.removeEventListener('visibilitychange', tick) } }, [ms, active]) return now } /** * 后端断开时的顶部横幅。连着时什么都不画。 * 挂在主内容区顶上(App 里
的第一个孩子),全站共享一份连接状态。 */ export function OfflineBanner({ className }: { className?: string }) { const backend = useCatalog((s) => s.backend) const backendError = useCatalog((s) => s.backendError) const retryAt = useCatalog((s) => s.retryAt) const lastOkAt = useCatalog((s) => s.lastOkAt) const checkBackend = useCatalog((s) => s.checkBackend) const down = backend === 'down' const now = useTicker(1000, down) const [busy, setBusy] = useState(false) const ref = useRef(null) // 横幅把工具栏往下推了,toast 也得跟着让:把自己的高度(窄屏会折行)写到 // --offline-banner-h 上,ToastHost 的 top 加上它 useLayoutEffect(() => { const el = ref.current if (!down || !el) return const root = document.documentElement const sync = () => root.style.setProperty('--offline-banner-h', `${el.offsetHeight}px`) sync() const ro = new ResizeObserver(sync) ro.observe(el) return () => { ro.disconnect(); root.style.removeProperty('--offline-banner-h') } }, [down]) if (!down) return null const secs = retryAt ? Math.max(0, Math.ceil((retryAt - now) / 1000)) : null return (
{/* 播报区只放不变的那几句:role=alert 是整块重念的,倒计时一秒一跳,放进来 读屏就一秒念一遍整条横幅 */} 服务端未连接 当前显示的空列表不代表数据丢失 {lastOkAt && ( · 最后连通 {formatTime(lastOkAt)} )} {secs != null && !busy && {secs} 秒后自动重试}
) } /** * 骨架屏:按真实布局画占位,数据回来时不跳。 * * rows × cols 个占位条;文字行宽度错落,看着像段落而不是一堵墙。动效只有透明度 * 呼吸,减少动效时停在静态灰块上。 */ export function Skeleton({ rows = 3, cols = 1, height = 12, gap = 10, className, style }: { rows?: number; cols?: number; height?: number; gap?: number; className?: string; style?: CSSProperties }) { const widths = ['100%', '86%', '72%', '94%', '64%'] return (
{Array.from({ length: rows * cols }, (_, i) => (
))}
) } // ------------------------------------------------------------------------- // Tabs // ------------------------------------------------------------------------- /** * 把 Tabs 的选中项接到 URL 的最后一段上:/settings/datasources。 * * 和 Tabs 放在一起而不是单开一个 hooks 文件——tab 和它的地址是同一件事, * 拆到两处迟早各改各的。三个 tab 页(知识 / 工具 / 设置)各接一行。 * * 用 replace 而不是 push:切 tab 不该在后退历史里堆一串,按后退是想离开 * 这一页,不是想把四个标签倒着走一遍。 * * 认不出的 tab 名(链接过期、手输错了)回落到 fallback,并把地址一起纠正过来, * 免得地址栏和眼前这一屏说的不是同一件事。 */ export function useTabRoute( valid: readonly string[], fallback: string, ): [string, (key: string) => void] { const { tab } = useParams() const navigate = useNavigate() const { pathname } = useLocation() const base = '/' + pathname.split('/').filter(Boolean)[0] const active = tab && valid.includes(tab) ? tab : fallback useEffect(() => { if (tab !== active) navigate(`${base}/${active}`, { replace: true }) }, [tab, active, base, navigate]) return [active, (key: string) => navigate(`${base}/${key}`, { replace: true })] } /** * 标签页。带 tablist / tab 语义,←→ Home End 切换(自动激活)。 * 给了 idPrefix 时,配套用 包内容,两边互相指认。 */ export function Tabs({ tabs, active, onChange, label, idPrefix }: { tabs: { key: string; label: string; badge?: number }[] active: string onChange: (key: string) => void /** 读屏用的整组名字 */ label?: string idPrefix?: string }) { const refs = useRef>({}) const move = (e: ReactKeyboardEvent, i: number) => { const next = rovingTarget(e, i, tabs.length, 'horizontal') if (next < 0) return e.preventDefault() const key = tabs[next].key onChange(key) refs.current[key]?.focus() } return (
{tabs.map((t, i) => { const selected = active === t.key return ( ) })}
) } /** * 一组「只占一个 Tab 位、组内用方向键走」的控件(标签页、单选组)里,这一键要 * 去第几个。首尾相接,Home / End 到两头;不是移动键返回 -1。带 Alt / ⌘ / Ctrl 的 * 不接:Alt+← 是浏览器后退 */ export function rovingTarget(e: ReactKeyboardEvent, i: number, n: number, axis: 'horizontal' | 'both'): number { if (!n || e.altKey || e.metaKey || e.ctrlKey) return -1 if (e.key === 'ArrowRight' || (axis === 'both' && e.key === 'ArrowDown')) return (i + 1) % n if (e.key === 'ArrowLeft' || (axis === 'both' && e.key === 'ArrowUp')) return (i - 1 + n) % n if (e.key === 'Home') return 0 if (e.key === 'End') return n - 1 return -1 } /** * 单选组(role=radiogroup)的键盘约定:整组只占一个 Tab 位,落在选中项上; * ←→↑↓ 在组内移动并选中,首尾相接,Home / End 到两头。标了 radio 却每项一个 * Tab 位、方向键没反应,等于对读屏用户许了个做不到的诺。 * * 用法:const radio = useRadioGroup(values, value, onChange),每个选项展开 * {...radio(v)},点击照旧自己写 onClick;外层容器自己写 role="radiogroup" 和名字。 */ export function useRadioGroup(values: readonly T[], value: T | undefined, onChange: (v: T) => void) { const refs = useRef(new Map()) // 选中的值不在选项里(还没加载完之类):让第一项接住 Tab const focusable = value !== undefined && values.includes(value) ? value : values[0] return (v: T) => ({ ref: (el: HTMLElement | null) => { refs.current.set(v, el) }, role: 'radio' as const, 'aria-checked': v === value, tabIndex: v === focusable ? 0 : -1, onKeyDown: (e: ReactKeyboardEvent) => { const i = rovingTarget(e, values.indexOf(v), values.length, 'both') if (i < 0) return e.preventDefault() const next = values[i] if (next !== value) onChange(next) refs.current.get(next)?.focus() }, }) } export function TabPanel({ idPrefix, tabKey, children, className }: { idPrefix: string; tabKey: string; children: ReactNode; className?: string }) { return (
{children}
) } export function Section({ title, right, children, defaultOpen = true }: { title: string; right?: ReactNode; children: ReactNode; defaultOpen?: boolean }) { const [open, setOpen] = useState(defaultOpen) return (
{right}
{open &&
{children}
}
) } // ------------------------------------------------------------------------- // 状态徽标 // ------------------------------------------------------------------------- /** * 状态徽标:每个状态一个剪影,去掉颜色也认得出(灰度打印、色弱、投影偏色)。 * 圆环=运行中、虚线环=排队、实心圆角方=完成、菱形=等人、三角=失败、斜杠圆=跳过、 * 实心小方=取消、虚线方加×=阻断、横杠=未到达;挂起画暂停符,未运行画小空心点。 * * 唯一的常驻动效是运行中那段弧的旋转(transform),减少动效时停住,圆环和 * 中心点照样说明它在运行。 */ export function StatusBadge({ status, size = 14, pendingApproval, animate = true, decorative = false, className, style }: { status: string size?: number /** 运行状态是 interrupted 时,有没有待审批(决定画菱形还是暂停符) */ pendingApproval?: boolean animate?: boolean /** 旁边已经有文字时设为 true,读屏不重复念 */ decorative?: boolean className?: string style?: CSSProperties }) { const meta = statusMeta(status, { pendingApproval }) const maskId = 'sb' + useId().replace(/[^a-zA-Z0-9_-]/g, '') return ( {!decorative && {meta.label}} ) } function BadgeShape({ shape, maskId, animate }: { shape: StatusShape; maskId: string; animate: boolean }) { const c = 'currentColor' switch (shape) { case 'ring': return ( <> ) case 'dashed-ring': return ( <> ) case 'square': return ( <> ) case 'diamond': return ( <> ) case 'triangle': return ( <> ) case 'slashed': return ( <> ) case 'stop': return case 'dashed-x': return ( <> ) case 'bar': return case 'pause': return ( <> ) case 'dot': default: return } } /** * 徽标加中文。正常态安静(只有字色),异常态(失败、等人、挂起、阻断)才铺淡底。 * 文字从 lib/status 取,全站只有这一份说法。 */ export function StatusPill({ status, pendingApproval, short = false, plain = false, label, title, className }: { status: string pendingApproval?: boolean /** 用短叫法:「待审批」「完成」 */ short?: boolean /** 服务端给的说法(流程实例的结论,如「已退回」「等待核实写入结果」):剪影和颜色仍按 status,文字用它 */ label?: string /** 不要底色和内边距,行内用 */ plain?: boolean title?: string className?: string }) { const meta = statusMeta(status, { pendingApproval }) const tint = !plain && meta.alert return ( {label || (short ? meta.short : meta.label)} ) } /** 老名字,行内的状态标记。新代码用 StatusPill */ export function StatusDot({ status, pendingApproval }: { status: string; pendingApproval?: boolean }) { return } /** 老名字。状态码 → 中文,来自 lib/status 的同一份表 */ export const STATUS_LABEL: Record = { ...Object.fromEntries(Object.values(STATUS).map((m) => [m.code, m.label])), interrupted: STATUS.waiting.label, } // ------------------------------------------------------------------------- // 小件:图标按钮、键帽、表单字段 // ------------------------------------------------------------------------- /** * 纯图标按钮。label 必填:同时写进 aria-label 和 title,读屏不再只念「按钮」, * 鼠标悬停也有说明。shortcut 会拼进 title,并写进 aria-keyshortcuts。 */ export function IconButton({ label, shortcut, icon, children, className, variant = 'ghost', size = 'sm', title, ...rest }: Omit, 'aria-label'> & { label: string shortcut?: string icon?: ReactNode variant?: 'ghost' | 'default' | 'danger' size?: 'sm' | 'md' }) { const tip = title ?? (shortcut ? `${label}(${formatShortcut(shortcut)})` : label) return ( ) } /** 键帽。combo 按平台显示:'Mod+K' 在 Mac 上是 ⌘K,其他平台是 Ctrl+K */ export function Kbd({ combo, children, className }: { combo?: string; children?: ReactNode; className?: string }) { return ( {combo ? formatShortcut(combo) : children} ) } /** * 带标签的表单字段:label 用 htmlFor 接到输入框,提示和报错接到 aria-describedby。 * * 两种用法: * * {(p) => } * 第二种自动生成 id,并把 aria-describedby / aria-invalid 一起给到输入框。 */ export function Field({ label, htmlFor, hint, error, required, children, className }: { label: ReactNode htmlFor?: string hint?: ReactNode error?: ReactNode required?: boolean children: ReactNode | ((props: { id: string; 'aria-describedby'?: string; 'aria-invalid'?: boolean }) => ReactNode) className?: string }) { const auto = useId() const id = htmlFor ?? `f${auto.replace(/[^a-zA-Z0-9_-]/g, '')}` const hintId = `${id}-hint` const errorId = `${id}-error` const describedBy = error ? errorId : hint ? hintId : undefined return (
{typeof children === 'function' ? children({ id, 'aria-describedby': describedBy, 'aria-invalid': error ? true : undefined }) : children} {error ?
{error}
: hint ?
{hint}
: null}
) } /** * 受控的 JSON 编辑框:输入过程中允许非法 JSON,失焦或合法时才回写。 * * aria-describedby / aria-invalid 照 Field 的 render-prop 原样传进来:外面(比如后端 * 422)说这一项有错时,框要标成出错、描红,读屏聚焦到框上就念出那句原因 */ export function JsonInput({ value, onChange, rows = 5, placeholder, id, 'aria-describedby': describedBy, 'aria-invalid': invalid }: { value: any; onChange: (v: any) => void; rows?: number; placeholder?: string; id?: string 'aria-describedby'?: string; 'aria-invalid'?: boolean }) { const [text, setText] = useState(() => (value == null ? '' : JSON.stringify(value, null, 2))) const [bad, setBad] = useState(false) const touched = useRef(false) const autoId = useId() const badId = `${id ?? `json${autoId.replace(/[^a-zA-Z0-9_-]/g, '')}`}-json` useEffect(() => { if (touched.current) return setText(value == null ? '' : JSON.stringify(value, null, 2)) }, [value]) return (