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}
)
}
// -------------------------------------------------------------------------
// 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