style(frontend): 接入 stash-ui 设计系统

- 依赖 @stash/ui(file:../../stash-ui),统一引入 style.css 与 Toaster
- 任务面板、表单、弹窗、日志、状态标签全部迁到组件库,App.css 只保留页面布局
- 移除自写 useFocusTrap,改用基于原生 dialog 的 Modal
- 修复 LogViewer 流式追加时误判离开底部、导致不再自动跟随的问题
- 发布脚本检查 stash-ui 产物;README 补充组件库构建与 file: 依赖刷新说明
This commit is contained in:
2026-11-01 23:54:35 +08:00
parent 07ca14ea34
commit 3c1a603b90
20 changed files with 1779 additions and 2481 deletions
+13 -2
View File
@@ -6,7 +6,7 @@ TaskPilot 是一个面向 **Windows 单机** 的本地定时任务管理平台
- 三类任务:Python/Shell 脚本、HTTP 请求、二进制进程
- SQLite 持久化,重启后任务与历史仍在
- 运行日志实时推送(SSE),按窗口合并事件;断线自动回退轮询,长日志用虚拟滚动展示
- 前端零外部依赖:样式与脚本随包自带;界面字体可选,未生成时自动回退系统字体
- 前端零外部网络依赖:样式与组件来自同级的 `stash-ui` 设计系统(`file:` 依赖,构建后随包自带);界面字体可选,未生成时自动回退系统字体
> 根目录的 `task_pilot.html` 只是最初的单文件视觉原型,正式入口是 React 应用。
@@ -58,6 +58,10 @@ release/TaskPilot/
### 方式二:本地开发
```powershell
# 前端依赖 @stash/ui(file:../../stash-ui),首次使用先在组件库构建 dist
npm --prefix ..\stash-ui install
npm --prefix ..\stash-ui run build
pnpm --dir frontend install
cargo run --manifest-path backend/Cargo.toml # 终端一:API,127.0.0.1:3000
pnpm --dir frontend dev # 终端二:http://127.0.0.1:5173
@@ -66,6 +70,9 @@ pnpm --dir frontend dev # 终端二:http://127.0.0.1:
Vite 把 `/api` 代理到后端。改后端端口时(`TASK_PILOT_PORT`)需同步修改
`frontend/vite.config.ts` 的代理目标;打包版同源,不需要改前端。
`@stash/ui` 走 `file:` 依赖(pnpm 会复制一份构建产物):组件库重新 `npm run build`
之后,需要再执行一次 `pnpm --dir frontend install` 才会同步新的 `dist`。
### 方式三:用 uv 跑官方示例与自检
仓库自带一个 uv 管理的演示任务和一个端到端自检脚本:
@@ -226,7 +233,10 @@ queued ──► running ──► succeeded / failed / timed_out / cancelled
- **任务表**:名称/ID、调度周期(含时区与**下次触发时间**)、类型、状态、超时、操作。
- **编辑器**:三类动态表单、Cron 预览(实时计算未来 5/10 次)、虚拟环境状态条、调用预览。
- **目录选择**:页面内目录浏览器(盘符 → 逐级进入 → 使用此目录),同时保留手动输入。
- **日志抽屉**:运行历史筛选、SSE 实时日志、取消运行、下载日志、Escape/焦点陷阱。
- **日志弹窗**:运行历史筛选、SSE 实时日志、取消运行、下载日志、Escape/焦点陷阱。
- **设计系统**:按钮、输入框、表格、标签、分页、弹窗、Toast、排版全部来自
`@stash/ui`(同级目录 `../stash-ui`,`file:` 依赖);本仓库只保留页面级布局与
业务块(任务表单元格、日志控制台、表单栅格)。
- **视觉**:对齐 Alright 主题(`#3858f6` 主色、灰阶体系、0.3s 缓动);正文使用
`LXGW WenKai`、标题与数字使用 `Outfit-Medium`。字体二进制不入库,用
`tools/build-fonts.py` 生成,缺失时回退系统字体。
@@ -423,6 +433,7 @@ React (Vite) ──fetch──► Axum router ──security::api_guard(Origin +
| 模块 | 职责 |
| --- | --- |
| `@stash/ui`(同级 `../stash-ui`) | 设计令牌与通用组件:按钮、输入、表格、标签、弹窗、分页、Toast、排版 |
| `pages/TaskDashboard.tsx` | 列表、筛选、分页、指标卡、下次触发时间 |
| `components/TaskEditorModal.tsx` | 三类动态表单、Cron 预览、虚拟环境状态条 |
| `components/DirectoryPickerDialog.tsx` | 页面内目录浏览器 |
+4 -4
View File
@@ -77,7 +77,7 @@ test('manages a task and reads a real run log', async ({ page, request }) => {
// Cron 预览是异步渲染的,等它稳定后再点击,避免点击坐标在弹窗重排中失效。
await expect(newTaskDialog.locator('.cron-run-item').first()).toBeVisible()
await newTaskDialog.getByRole('button', { name: '选择文件夹…' }).click()
const directoryPicker = page.getByRole('dialog', { name: '选择项目工作目录' })
const directoryPicker = page.getByRole('dialog', { name: '选择工作目录' })
await expect(directoryPicker).toBeVisible()
const directoryPathInput = directoryPicker.getByLabel('目录路径')
await directoryPathInput.fill(workingDir)
@@ -140,7 +140,7 @@ test('manages a task and reads a real run log', async ({ page, request }) => {
path: 'test-results/dashboard-log-drawer.png',
fullPage: true,
})
await drawer.getByRole('button', { name: '关闭运行日志' }).click()
await drawer.getByRole('button', { name: '关闭' }).click()
await page.getByRole('button', { name: '编辑' }).click()
const editor = page.getByRole('dialog', {
@@ -161,10 +161,10 @@ test('manages a task and reads a real run log', async ({ page, request }) => {
await page.getByRole('button', { name: '删除' }).click()
await page
.getByRole('alertdialog')
.getByRole('dialog', { name: /删除任务/ })
.getByRole('button', { name: '确认删除' })
.click()
await expect(page.getByRole('heading', { name: '还没有任务' })).toBeVisible()
await expect(page.getByText('还没有任务')).toBeVisible()
})
test('keeps the dashboard usable on a narrow viewport', async ({
+1
View File
@@ -17,6 +17,7 @@
},
"dependencies": {
"@hookform/resolvers": "^5.9.2",
"@stash/ui": "file:../../stash-ui",
"@tanstack/react-query": "^5.104.3",
"react": "^19.2.8",
"react-dom": "^19.2.8",
+14
View File
@@ -11,6 +11,9 @@ importers:
'@hookform/resolvers':
specifier: ^5.9.2
version: 5.9.2([email protected](@types/[email protected])([email protected]))([email protected])
'@stash/ui':
specifier: file:../../stash-ui
version: file:../../stash-ui([email protected]([email protected]))([email protected])
'@tanstack/react-query':
specifier: ^5.104.3
version: 5.104.3([email protected])
@@ -477,6 +480,12 @@ packages:
'@standard-schema/[email protected]':
resolution: {integrity: sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==}
'@stash/ui@file:../../stash-ui':
resolution: {directory: ../../stash-ui, type: directory}
peerDependencies:
react: '>=19'
react-dom: '>=19'
'@tanstack/[email protected]':
resolution: {integrity: sha512-DZY9TuJAOgU3UyHUhXb4CcTYEHNZszlwkPg4VViIwTxOKzLprPUU+rbaPZQd3srqkGOtpaDdKpW972UV/LKlcg==}
@@ -1361,6 +1370,11 @@ snapshots:
'@standard-schema/[email protected]': {}
'@stash/ui@file:../../stash-ui([email protected]([email protected]))([email protected])':
dependencies:
react: 19.3.1
react-dom: 19.3.1([email protected])
'@tanstack/[email protected]': {}
'@tanstack/[email protected]([email protected])':
+418 -1045
View File
File diff suppressed because it is too large Load Diff
+6 -6
View File
@@ -299,7 +299,7 @@ describe('TaskDashboard', () => {
await user.click(screen.getByRole('button', { name: '选择文件夹…' }))
const dialog = await screen.findByRole('dialog', {
name: '选择项目工作目录',
name: '选择工作目录',
})
await user.click(await within(dialog).findByRole('button', { name: 'D:\\' }))
await user.click(await within(dialog).findByRole('button', { name: 'Projects' }))
@@ -307,7 +307,7 @@ describe('TaskDashboard', () => {
expect(within(dialog).getByText('D:\\Projects\\sync')).toBeInTheDocument()
await user.click(within(dialog).getByRole('button', { name: '使用此目录' }))
expect(screen.queryByRole('dialog', { name: '选择项目工作目录' })).toBeNull()
expect(screen.queryByRole('dialog', { name: '选择工作目录' })).toBeNull()
expect(screen.getByLabelText(/项目工作目录/)).toHaveValue(
'D:\\Projects\\sync',
)
@@ -346,7 +346,7 @@ describe('TaskDashboard', () => {
await user.click(screen.getByRole('button', { name: '+ 新建任务' }))
await user.click(screen.getByRole('button', { name: '选择文件夹…' }))
const dialog = await screen.findByRole('dialog', {
name: '选择项目工作目录',
name: '选择工作目录',
})
await user.click(await within(dialog).findByRole('button', { name: 'D:\\' }))
await user.click(await within(dialog).findByRole('button', { name: 'Projects' }))
@@ -380,12 +380,12 @@ describe('TaskDashboard', () => {
await user.click(screen.getByRole('button', { name: '选择文件夹…' }))
const dialog = await screen.findByRole('dialog', {
name: '选择项目工作目录',
name: '选择工作目录',
})
await user.click(within(dialog).getByRole('button', { name: '取消' }))
await waitFor(() =>
expect(screen.queryByRole('dialog', { name: '选择项目工作目录' })).toBeNull(),
expect(screen.queryByRole('dialog', { name: '选择工作目录' })).toBeNull(),
)
expect(input).toHaveValue('D:\\Manual\\path')
})
@@ -413,7 +413,7 @@ describe('TaskDashboard', () => {
await user.click(screen.getByRole('button', { name: '选择文件夹…' }))
const dialog = await screen.findByRole('dialog', {
name: '选择项目工作目录',
name: '选择工作目录',
})
expect(
await within(dialog).findByText('目录不存在: Z:\\nope'),
+10 -11
View File
@@ -1,20 +1,19 @@
import { Link, Route, Routes } from 'react-router-dom'
import { Button, Result } from '@stash/ui'
import { Route, Routes, useNavigate } from 'react-router-dom'
import { TaskDashboard } from './pages/TaskDashboard'
import './App.css'
function NotFoundPage() {
const navigate = useNavigate()
return (
<main className="app-shell">
<header className="dashboard-header">
<div>
<p className="eyebrow">404 / ROUTE NOT FOUND</p>
<h1>页面不存在</h1>
<p className="subtitle">该地址尚未配置到 TaskPilot 路由。</p>
</div>
</header>
<Link className="button button-primary" to="/">
返回任务列表
</Link>
<Result
status="info"
title="页面不存在"
description="该地址尚未配置到 TaskPilot 路由。"
actions={<Button onClick={() => navigate('/')}>返回任务列表</Button>}
/>
</main>
)
}
+24 -56
View File
@@ -1,5 +1,4 @@
import { useEffect, useRef } from 'react'
import { useFocusTrap } from '../lib/useFocusTrap'
import { Button, Modal, Text } from '@stash/ui'
interface ConfirmDialogProps {
open: boolean
@@ -10,6 +9,10 @@ interface ConfirmDialogProps {
onCancel: () => void
}
/**
* 危险操作确认。外壳交给组件库的 `Modal`(原生 dialog:焦点陷阱 / Esc / 背景 inert),
* 这里只负责文案与「取消在左、危险操作在右」的按钮顺序。
*/
export function ConfirmDialog({
open,
title,
@@ -18,66 +21,31 @@ export function ConfirmDialog({
onConfirm,
onCancel,
}: ConfirmDialogProps) {
const dialogRef = useRef<HTMLElement>(null)
useFocusTrap(open, dialogRef)
useEffect(() => {
if (!open) {
return
}
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape' && !busy) {
const requestClose = () => {
if (!busy) {
onCancel()
}
}
window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onKeyDown)
}, [busy, onCancel, open])
if (!open) {
return null
}
return (
<div
className="modal-overlay"
onMouseDown={(event) => {
if (event.currentTarget === event.target && !busy) {
onCancel()
}
}}
>
<section
ref={dialogRef}
className="confirm-card"
tabIndex={-1}
role="alertdialog"
aria-modal="true"
aria-labelledby="confirm-title"
aria-describedby="confirm-description"
>
<p className="eyebrow">CONFIRM ACTION</p>
<h2 id="confirm-title">{title}</h2>
<p className="muted-copy">{description}</p>
<div className="modal-actions">
<button
type="button"
className="button button-secondary"
onClick={onCancel}
disabled={busy}
>
<Modal
open={open}
onClose={requestClose}
title={title}
size="sm"
closeOnOverlay={!busy}
footer={
<>
<Button variant="secondary" onClick={requestClose} disabled={busy}>
取消
</button>
<button
type="button"
className="button button-danger"
onClick={onConfirm}
disabled={busy}
>
</Button>
<Button variant="danger" onClick={onConfirm} loading={busy}>
{busy ? '删除中...' : '确认删除'}
</button>
</div>
</section>
</div>
</Button>
</>
}
>
<Text tone="sub">{description}</Text>
</Modal>
)
}
+77 -103
View File
@@ -1,7 +1,16 @@
import { useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
import {
Button,
Empty,
Icon,
Input,
Modal,
Notice,
Spinner,
Text,
} from '@stash/ui'
import { useEffect, useState } from 'react'
import { listDirectories } from '../api/client'
import { useFocusTrap } from '../lib/useFocusTrap'
interface DirectoryPickerDialogProps {
open: boolean
@@ -13,6 +22,9 @@ interface DirectoryPickerDialogProps {
/**
* 页面内的目录浏览器:从盘符开始逐级进入文件夹,最终把绝对路径回填到表单。
* 浏览器拿不到系统文件对话框的真实路径,因此目录浏览由后端提供列表接口。
*
* 外壳是组件库的 `Modal`,路径输入 / 按钮 / 空态 / 错误提示分别是
* `Input` / `Button` / `Empty` / `Notice`。
*/
export function DirectoryPickerDialog({
open,
@@ -22,8 +34,6 @@ export function DirectoryPickerDialog({
}: DirectoryPickerDialogProps) {
const [currentPath, setCurrentPath] = useState<string | null>(null)
const [draftPath, setDraftPath] = useState('')
const dialogRef = useRef<HTMLElement>(null)
useFocusTrap(open, dialogRef, '[data-picker-path]')
useEffect(() => {
if (!open) {
@@ -47,23 +57,6 @@ export function DirectoryPickerDialog({
}
}, [listing.data?.path])
useEffect(() => {
if (!open) {
return
}
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
onClose()
}
}
window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onKeyDown)
}, [onClose, open])
if (!open) {
return null
}
const entries = listing.data?.entries ?? []
const currentDirectory = listing.data?.path ?? null
const parent = listing.data?.parent ?? null
@@ -74,53 +67,46 @@ export function DirectoryPickerDialog({
}
return (
<div
className="modal-overlay"
onMouseDown={(event) => {
if (event.currentTarget === event.target) {
<Modal
open={open}
onClose={onClose}
title="选择工作目录"
size="lg"
className="directory-picker-modal"
footer={
<>
<div className="directory-picker-summary">
<Text size="xs" tone="muted">
将使用
</Text>
<Text size="sm" tone="sub" truncate>
{currentDirectory ?? '尚未选择目录'}
</Text>
</div>
<Button variant="secondary" onClick={onClose}>
取消
</Button>
<Button
disabled={!currentDirectory}
onClick={() => {
if (currentDirectory) {
onSelect(currentDirectory)
onClose()
}
}}
>
<section
ref={dialogRef}
className="modal-card directory-picker"
role="dialog"
aria-modal="true"
aria-labelledby="directory-picker-title"
tabIndex={-1}
使用此目录
</Button>
</>
}
>
<header className="modal-header">
<div>
<p className="eyebrow">WORKING DIRECTORY</p>
<h2 id="directory-picker-title">选择项目工作目录</h2>
</div>
<button
type="button"
className="icon-button"
onClick={onClose}
aria-label="关闭目录选择"
>
×
</button>
</header>
<div className="directory-picker-toolbar">
<button
type="button"
className="button button-secondary button-small"
onClick={() => navigate(parent)}
disabled={!parent}
>
<Button variant="secondary" onClick={() => navigate(parent)} disabled={!parent}>
上一级
</button>
<button
type="button"
className="button button-secondary button-small"
onClick={() => navigate(null)}
>
</Button>
<Button variant="secondary" onClick={() => navigate(null)}>
盘符
</button>
</Button>
<form
className="directory-path-form"
onSubmit={(event) => {
@@ -128,13 +114,12 @@ export function DirectoryPickerDialog({
navigate(draftPath.trim() || null)
}}
>
<input
className="field-input mono"
<Input
className="directory-path-input"
value={draftPath}
onChange={(event) => setDraftPath(event.target.value)}
placeholder="输入或粘贴绝对路径,例如 D:\Projects\sync"
aria-label="目录路径"
data-picker-path
spellCheck={false}
/>
</form>
@@ -142,18 +127,32 @@ export function DirectoryPickerDialog({
<div className="directory-picker-body">
{listing.isPending ? (
<p className="muted-copy">正在读取目录…</p>
) : null}
{listing.isError ? (
<div className="inline-alert inline-alert-error" role="alert">
{listing.error.message}
<div className="picker-status">
<Spinner label="正在读取目录" />
<Text tone="sub" size="sm">
正在读取目录…
</Text>
</div>
) : null}
{!listing.isPending && !listing.isError && entries.length === 0 ? (
<p className="empty-inline">
{currentDirectory ? '该目录下没有子文件夹' : '没有可用的盘符'}
</p>
{listing.isError ? (
<Notice
tone="error"
title="目录读取失败"
className="directory-picker-error"
>
{listing.error.message}
</Notice>
) : null}
{!listing.isPending && !listing.isError && entries.length === 0 ? (
<Empty
text={
currentDirectory ? '该目录下没有子文件夹' : '没有可用的盘符'
}
/>
) : null}
{entries.length > 0 ? (
<ul className="directory-list">
{entries.map((entry) => (
@@ -164,45 +163,20 @@ export function DirectoryPickerDialog({
onClick={() => navigate(entry.path)}
title={entry.path}
>
<span className="directory-icon" aria-hidden="true">
📁
</span>
<Icon className="directory-icon" name="folder_more_line" />
<span className="directory-name">{entry.name}</span>
</button>
</li>
))}
</ul>
) : null}
{listing.data?.truncated ? (
<p className="field-hint">文件夹过多,仅列出前 500 个。</p>
<Text size="xs" tone="muted">
文件夹过多,仅列出前 500 个。
</Text>
) : null}
</div>
<footer className="directory-picker-footer">
<div className="directory-picker-summary">
<span className="section-label">将使用</span>
<code>{currentDirectory ?? '尚未选择目录'}</code>
</div>
<div className="modal-actions directory-picker-actions">
<button type="button" className="button button-secondary" onClick={onClose}>
取消
</button>
<button
type="button"
className="button button-primary"
disabled={!currentDirectory}
onClick={() => {
if (currentDirectory) {
onSelect(currentDirectory)
onClose()
}
}}
>
使用此目录
</button>
</div>
</footer>
</section>
</div>
</Modal>
)
}
+21 -7
View File
@@ -29,6 +29,7 @@ export function LogViewer({
const viewportRef = useRef<HTMLDivElement>(null)
const frameRef = useRef(0)
const followingRef = useRef(true)
const lastScrollTopRef = useRef(0)
const [following, setFollowing] = useState(true)
const [metrics, setMetrics] = useState({ scrollTop: 0, height: 0 })
@@ -62,23 +63,34 @@ export function LogViewer({
}, [])
const handleScroll = useCallback(() => {
if (frameRef.current) {
return
}
frameRef.current = requestAnimationFrame(() => {
frameRef.current = 0
const node = viewportRef.current
if (!node) {
return
}
// 只有「用户往上翻」才停止跟随。日志流式追加时 scrollTop 不变但内容变高,
// 此时不能把 following 关掉,否则后半段日志不会再自动贴底。
const previousTop = lastScrollTopRef.current
lastScrollTopRef.current = node.scrollTop
const atBottom = isNearBottom(
node.scrollTop,
node.clientHeight,
node.scrollHeight,
FOLLOW_THRESHOLD_PX,
)
followingRef.current = atBottom
setFollowing(atBottom)
if (atBottom) {
followingRef.current = true
setFollowing(true)
} else if (node.scrollTop < previousTop) {
followingRef.current = false
setFollowing(false)
}
// 可见窗口的重算仍然按帧节流,避免滚动时每像素都 setState。
if (frameRef.current) {
return
}
frameRef.current = requestAnimationFrame(() => {
frameRef.current = 0
setMetrics({ scrollTop: node.scrollTop, height: node.clientHeight })
})
}, [])
@@ -93,6 +105,7 @@ export function LogViewer({
return
}
node.scrollTop = node.scrollHeight
lastScrollTopRef.current = node.scrollTop
setMetrics({ scrollTop: node.scrollTop, height: node.clientHeight })
}, [version])
@@ -102,6 +115,7 @@ export function LogViewer({
return
}
node.scrollTop = node.scrollHeight
lastScrollTopRef.current = node.scrollTop
followingRef.current = true
setFollowing(true)
setMetrics({ scrollTop: node.scrollTop, height: node.clientHeight })
+113 -126
View File
@@ -1,4 +1,14 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
Button,
Empty,
Modal,
Notice,
Select,
Spinner,
Text,
Title,
} from '@stash/ui'
import { useCallback, useEffect, useRef, useState } from 'react'
import {
cancelRun,
@@ -18,7 +28,6 @@ import {
isTerminalRunStatus,
} from '../lib/format'
import { appendLogChunk, createLogBuffer, flushLogTail } from '../lib/logLines'
import { useFocusTrap } from '../lib/useFocusTrap'
import { LogViewer } from './LogViewer'
import { RunStatusBadge } from './StatusBadge'
@@ -29,6 +38,31 @@ interface RunLogDrawerProps {
onClose: () => void
}
const STATUS_FILTERS = [
{ value: '', label: '全部状态' },
{ value: 'queued', label: '排队中' },
{ value: 'running', label: '运行中' },
{ value: 'succeeded', label: '成功' },
{ value: 'failed', label: '失败' },
{ value: 'timed_out', label: '已超时' },
{ value: 'cancelled', label: '已取消' },
{ value: 'skipped', label: '已跳过' },
]
const TRIGGER_FILTERS = [
{ value: '', label: '全部触发' },
{ value: 'schedule', label: '定时' },
{ value: 'manual', label: '手动' },
{ value: 'retry', label: '重试' },
]
/**
* 运行历史 + 日志面板。
*
* 外壳用组件库的 `Modal`(原生 dialog:焦点陷阱、Esc、背景 inert),
* 左栏是运行列表(`Select` 筛选 + 状态标签),右栏是详情与虚拟滚动日志。
* 日志读取本身仍是页面逻辑(SSE + 轮询兜底),不放进组件库。
*/
export function RunLogDrawer({
open,
task,
@@ -43,15 +77,9 @@ export function RunLogDrawer({
const [historyTrigger, setHistoryTrigger] = useState<RunTrigger | ''>('')
const [sseConnected, setSseConnected] = useState(false)
const [logEvents] = useState(() => new EventTarget())
const drawerRef = useRef<HTMLElement>(null)
useFocusTrap(open, drawerRef)
const runsQuery = useQuery({
queryKey: [
'task-runs',
task?.id,
historyStatus,
historyTrigger,
],
queryKey: ['task-runs', task?.id, historyStatus, historyTrigger],
queryFn: ({ signal }) =>
listTaskRuns(
task!.id,
@@ -117,9 +145,7 @@ export function RunLogDrawer({
try {
const payload = JSON.parse(event.data) as ExecutionEvent
if (payload.event === 'log') {
logEvents.dispatchEvent(
new CustomEvent('log', { detail: payload }),
)
logEvents.dispatchEvent(new CustomEvent('log', { detail: payload }))
}
} catch {
setSseConnected(false)
@@ -142,116 +168,75 @@ export function RunLogDrawer({
}
}, [logEvents, open, queryClient, task])
useEffect(() => {
if (!open) {
return
}
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
onClose()
}
}
window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onKeyDown)
}, [onClose, open])
if (!open || !task) {
return null
}
return (
<div
className="modal-overlay drawer-overlay"
onMouseDown={(event) => {
if (event.currentTarget === event.target) {
onClose()
}
}}
<Modal
open={open}
onClose={onClose}
title={task.name}
size="lg"
className="run-log-modal"
closeOnOverlay
>
<aside
ref={drawerRef}
className="run-drawer"
tabIndex={-1}
role="dialog"
aria-modal="true"
aria-labelledby="run-drawer-title"
>
<header className="modal-header">
<div>
<p className="eyebrow">RUN HISTORY</p>
<h2 id="run-drawer-title">{task.name}</h2>
<p className="drawer-subtitle mono">{task.id}</p>
</div>
<button
type="button"
className="icon-button"
onClick={onClose}
aria-label="关闭运行日志"
>
×
</button>
</header>
<div className="run-drawer-body">
<div className="run-log-body">
<section className="run-history-panel">
<div className="section-heading">
<div>
<p className="section-label">RUNS</p>
<h3>最近运行</h3>
<Text className="section-label" size="xs" tone="muted">
RUN HISTORY
</Text>
<Title level={3}>最近运行</Title>
<Text className="drawer-subtitle" size="xs" tone="muted">
{task.id}
</Text>
</div>
<button
type="button"
className="button button-secondary button-small"
<Button
size="sm"
variant="secondary"
onClick={() => void runsQuery.refetch()}
disabled={runsQuery.isFetching}
loading={runsQuery.isFetching}
>
刷新
</button>
</Button>
</div>
<div className="history-filters">
<select
className="field-input compact-select"
aria-label="运行状态筛选"
<Select
className="history-select"
options={STATUS_FILTERS}
value={historyStatus}
onChange={(event) => {
setHistoryStatus(event.target.value as RunStatus | '')
onChange={(value) => {
setHistoryStatus(value as RunStatus | '')
setSelectedRunId(null)
}}
>
<option value="">全部状态</option>
<option value="queued">排队中</option>
<option value="running">运行中</option>
<option value="succeeded">成功</option>
<option value="failed">失败</option>
<option value="timed_out">已超时</option>
<option value="cancelled">已取消</option>
<option value="skipped">已跳过</option>
</select>
<select
className="field-input compact-select"
aria-label="触发方式筛选"
/>
<Select
className="history-select"
options={TRIGGER_FILTERS}
value={historyTrigger}
onChange={(event) => {
setHistoryTrigger(event.target.value as RunTrigger | '')
onChange={(value) => {
setHistoryTrigger(value as RunTrigger | '')
setSelectedRunId(null)
}}
>
<option value="">全部触发</option>
<option value="schedule">定时</option>
<option value="manual">手动</option>
<option value="retry">重试</option>
</select>
/>
</div>
{runsQuery.isPending ? (
<p className="muted-copy">正在加载运行记录...</p>
) : runsQuery.isError ? (
<div className="inline-alert inline-alert-error">
{runsQuery.error.message}
<div className="panel-status">
<Spinner label="正在加载运行记录" />
<Text size="sm" tone="sub">
正在加载运行记录...
</Text>
</div>
) : runsQuery.isError ? (
<Notice tone="error" title="运行记录加载失败">
{runsQuery.error.message}
</Notice>
) : runs.length === 0 ? (
<p className="empty-inline">该任务还没有运行记录。</p>
<Empty text="该任务还没有运行记录。" />
) : (
<div className="run-list">
{runs.map((run) => (
@@ -279,47 +264,52 @@ export function RunLogDrawer({
<section className="run-detail-panel">
<div className="section-heading">
<div>
<p className="section-label">DETAIL</p>
<h3>
<Text className="section-label" size="xs" tone="muted">
DETAIL
</Text>
<Title level={3}>
{effectiveRunId ? `运行 #${effectiveRunId}` : '运行详情'}
</h3>
</Title>
</div>
{selectedRun ? (
<div className="run-detail-actions">
<RunStatusBadge status={selectedRun.status} />
{!isTerminalRunStatus(selectedRun.status) ? (
<button
type="button"
className="button button-danger button-small"
disabled={
<Button
size="sm"
variant="danger"
loading={
cancelMutation.isPending &&
cancelMutation.variables === selectedRun.id
}
onClick={() => cancelMutation.mutate(selectedRun.id)}
>
{cancelMutation.isPending ? '取消中...' : '取消运行'}
</button>
取消运行
</Button>
) : null}
<a
className="button button-secondary button-small"
href={runLogDownloadUrl(selectedRun.id)}
<Button
size="sm"
variant="secondary"
onClick={() => {
window.location.href = runLogDownloadUrl(selectedRun.id)
}}
>
下载日志
</a>
</Button>
</div>
) : null}
</div>
{selectedRunQuery.isError ? (
<div className="inline-alert inline-alert-error">
<Notice tone="error" title="运行详情加载失败">
{selectedRunQuery.error.message}
</div>
</Notice>
) : null}
{selectedRun ? (
<RunMetadata run={selectedRun} />
) : (
<p className="empty-inline">选择一条运行记录查看日志。</p>
<Empty text="选择一条运行记录查看日志。" />
)}
{effectiveRunId ? (
@@ -335,8 +325,7 @@ export function RunLogDrawer({
) : null}
</section>
</div>
</aside>
</div>
</Modal>
)
}
@@ -471,10 +460,7 @@ function RunLogOutput({
useEffect(() => {
const onLog = (event: Event) => {
const payload = (event as CustomEvent<ExecutionEvent>).detail
if (
payload.event !== 'log' ||
payload.data.run_id !== runId
) {
if (payload.event !== 'log' || payload.data.run_id !== runId) {
return
}
if (payload.data.offset === offsetRef.current) {
@@ -511,12 +497,13 @@ function RunLogOutput({
</span>
</div>
{error ? (
<div className="inline-alert inline-alert-error">
{error}
<button
type="button"
className="text-button"
onClick={() => {
<Notice
tone="error"
title="日志读取失败"
className="log-viewer-error"
action={{
label: '重试',
onClick: () => {
bufferRef.current = createLogBuffer()
offsetRef.current = 0
setPollComplete(false)
@@ -524,11 +511,11 @@ function RunLogOutput({
setLines(bufferRef.current.lines)
setVersion((value) => value + 1)
setReloadKey((value) => value + 1)
},
}}
>
重试
</button>
</div>
{error}
</Notice>
) : null}
<LogViewer lines={lines} version={version} />
</div>
+22 -7
View File
@@ -1,16 +1,30 @@
import { Tag, type TagTone } from '@stash/ui'
import type { RunStatus } from '../api/client'
import { runStatusLabels } from '../lib/format'
const RUN_STATUS_TONE: Record<RunStatus, TagTone> = {
queued: 'primary',
running: 'warning',
succeeded: 'success',
failed: 'danger',
timed_out: 'danger',
cancelled: 'neutral',
skipped: 'neutral',
}
interface RunStatusBadgeProps {
status: RunStatus
}
export function RunStatusBadge({ status }: RunStatusBadgeProps) {
return (
<span className={`status-badge status-${status}`}>
<span className="status-dot" aria-hidden="true" />
<Tag
tone={RUN_STATUS_TONE[status]}
dot
className={`status-${status}`}
>
{runStatusLabels[status]}
</span>
</Tag>
)
}
@@ -20,11 +34,12 @@ interface EnabledBadgeProps {
export function EnabledBadge({ enabled }: EnabledBadgeProps) {
return (
<span
className={`status-badge ${enabled ? 'status-enabled' : 'status-disabled'}`}
<Tag
tone={enabled ? 'success' : 'neutral'}
dot
className={enabled ? 'status-enabled' : 'status-disabled'}
>
<span className="status-dot" aria-hidden="true" />
{enabled ? '活跃中' : '已暂停'}
</span>
</Tag>
)
}
+334 -293
View File
@@ -1,7 +1,21 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import {
Button,
Checkbox,
FormField,
Input,
Modal,
Notice,
PasswordInput,
Select,
Text,
Textarea,
TextButton,
} from '@stash/ui'
import { useEffect, useState, type ReactNode } from 'react'
import {
Controller,
type FieldPath,
type UseFormRegister,
useFieldArray,
@@ -23,7 +37,6 @@ import {
type KeyValueFormValue,
type TaskFormValues,
} from '../lib/taskForm'
import { useFocusTrap } from '../lib/useFocusTrap'
import { useDebouncedValue } from '../lib/useDebouncedValue'
interface TaskEditorModalProps {
@@ -34,6 +47,34 @@ interface TaskEditorModalProps {
onSubmit: (values: TaskFormValues) => Promise<void>
}
const ACTION_TYPE_OPTIONS = [
{ value: 'script', label: '执行脚本 (Python / Shell / Node / Lua)' },
{ value: 'http', label: '发起 HTTP 请求' },
{ value: 'process', label: '管理常驻/独立二进制' },
]
const HTTP_METHOD_OPTIONS = [
{ value: 'GET', label: 'GET' },
{ value: 'POST', label: 'POST' },
]
const TIMEZONE_SUGGESTIONS = [
'Asia/Shanghai',
'Asia/Hong_Kong',
'UTC',
'Europe/London',
'America/New_York',
]
const CRON_PREVIEW_COUNTS = [3, 5, 8, 10]
/**
* 任务编辑器。
*
* 外壳是组件库的 `Modal`(原生 dialog:焦点陷阱、Esc、背景 inert),
* 字段排版用 `FormField`,控件用 `Input` / `Select` / `Textarea` / `Checkbox`,
* 这里只保留校验(react-hook-form + zod)与业务联动。
*/
export function TaskEditorModal({
open,
task,
@@ -44,9 +85,6 @@ export function TaskEditorModal({
const [submitError, setSubmitError] = useState<string | null>(null)
const [cronPreviewCount, setCronPreviewCount] = useState(5)
const [pickerOpen, setPickerOpen] = useState(false)
const dialogRef = useRef<HTMLElement>(null)
// 目录选择弹窗打开时让出焦点管理,避免两个焦点陷阱互相争夺 Tab。
useFocusTrap(open && !pickerOpen, dialogRef, '[data-dialog-autofocus]')
const {
register,
control,
@@ -140,27 +178,20 @@ export function TaskEditorModal({
setPickerOpen(false)
}, [open, reset, task])
// 打开后把焦点给第一个可编辑字段:新建时是任务标识,编辑时 ID 已锁定,跳名称。
// 原生 dialog 默认聚焦关闭按钮,不符合编辑表单的节奏。
useEffect(() => {
if (!open) {
return
}
const previousOverflow = document.body.style.overflow
document.body.style.overflow = 'hidden'
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape' && !saving) {
document.getElementById(task ? 'task-name' : 'task-id')?.focus()
}, [open, task])
const requestClose = () => {
if (!saving) {
onClose()
}
}
window.addEventListener('keydown', onKeyDown)
return () => {
document.body.style.overflow = previousOverflow
window.removeEventListener('keydown', onKeyDown)
}
}, [onClose, open, saving])
if (!open) {
return null
}
const submit = handleSubmit(async (values) => {
setSubmitError(null)
@@ -184,108 +215,102 @@ export function TaskEditorModal({
})
return (
<div
className="modal-overlay"
onMouseDown={(event) => {
if (event.currentTarget === event.target && !saving) {
onClose()
<Modal
open={open}
onClose={requestClose}
title={task ? `编辑任务 [${task.id}]` : '新建定时任务'}
size="lg"
className="task-editor-modal"
closeOnOverlay={!saving}
footer={
<>
<Button variant="secondary" onClick={requestClose} disabled={saving}>
取消
</Button>
<Button type="submit" form="task-editor-form" loading={saving}>
{task ? '保存修改' : '保存并热刷新'}
</Button>
</>
}
}}
>
<section
ref={dialogRef}
className="modal-card task-editor"
tabIndex={-1}
role="dialog"
aria-modal="true"
aria-labelledby="task-editor-title"
>
<header className="modal-header">
<div>
<h2 id="task-editor-title">
{task ? `编辑任务 [${task.id}]` : '新建定时任务'}
</h2>
</div>
<button
type="button"
className="icon-button"
onClick={onClose}
disabled={saving}
aria-label="关闭任务编辑器"
>
×
</button>
</header>
<form
id="task-editor-form"
className="modal-body"
className="task-editor-form"
onSubmit={submit}
noValidate
>
{submitError ? (
<div className="inline-alert inline-alert-error" role="alert">
<Notice tone="error" title="保存失败">
{submitError}
</div>
</Notice>
) : null}
<div className="form-grid">
<Field
<FormField
label="任务标识 (Task ID)"
htmlFor="task-id"
error={errors.id?.message}
>
<input
<Input
id="task-id"
{...register('id')}
className="field-input mono"
className="mono-input"
placeholder="例如:sync_data"
disabled={Boolean(task)}
data-dialog-autofocus
aria-invalid={Boolean(errors.id)}
/>
</Field>
<Field label="名称" error={errors.name?.message}>
<input
</FormField>
<FormField label="名称" htmlFor="task-name" error={errors.name?.message}>
<Input
id="task-name"
{...register('name')}
className="field-input"
placeholder="业务可读名称"
aria-invalid={Boolean(errors.name)}
/>
</Field>
</FormField>
</div>
<div className="form-grid">
<div className="field">
<div className="cron-header-row">
<span className="field-label">Cron 表达式</span>
<div className="cron-n-selector">
<span>预览未来</span>
<select
value={cronPreviewCount}
onChange={(event) =>
setCronPreviewCount(Number(event.target.value))
<FormField
label="Cron 表达式"
htmlFor="task-cron"
error={errors.cron?.message}
hint={
errors.cron
? undefined
: '支持 5/6 位字段及 @daily、@hourly'
}
aria-label="Cron 预览次数"
>
<option value="3">3 次</option>
<option value="5">5 次</option>
<option value="8">8 次</option>
<option value="10">10 次</option>
</select>
</div>
</div>
<input
<Input
id="task-cron"
{...register('cron')}
className="field-input mono"
className="mono-input"
placeholder="0 0 2 * * *"
aria-invalid={Boolean(errors.cron)}
/>
<div className="cron-preview-box" aria-live="polite">
<div className="cron-preview-head">
<Text size="xs" tone="muted">
预览未来运行时间
</Text>
<Select
className="cron-count-select"
options={CRON_PREVIEW_COUNTS.map((count) => ({
value: String(count),
label: `${count} 次`,
}))}
value={String(cronPreviewCount)}
onChange={(value) => setCronPreviewCount(Number(value))}
/>
</div>
{cronPreview.isFetching ? (
<span className="cron-preview-message">正在计算...</span>
<Text size="sm" tone="sub">
正在计算...
</Text>
) : cronPreview.isError ? (
<span className="cron-preview-error">
<Text size="sm" className="cron-preview-error">
{cronPreview.error.message}
</span>
</Text>
) : cronPreview.data?.runs.length ? (
cronPreview.data.runs.map((run, index) => (
<div className="cron-run-item" key={run}>
@@ -294,171 +319,188 @@ export function TaskEditorModal({
</div>
))
) : (
<span className="cron-preview-message">
<Text size="sm" tone="sub">
等待输入有效 Cron 表达式...
</span>
</Text>
)}
</div>
{errors.cron?.message ? (
<span className="field-error">{errors.cron.message}</span>
) : (
<span className="field-hint">
支持 5/6 位字段及 @daily、@hourly
</span>
)}
</div>
<Field label="超时时间 (秒)" error={errors.timeout_secs?.message}>
<input
{...register('timeout_secs', { valueAsNumber: true })}
</FormField>
<FormField
label="超时时间 (秒)"
htmlFor="task-timeout"
error={errors.timeout_secs?.message}
hint={
errors.timeout_secs
? undefined
: '超时后将被 Windows Job Object 强制终止'
}
>
<Input
id="task-timeout"
type="number"
min="1"
max="86400"
className="field-input mono"
min={1}
max={86_400}
{...register('timeout_secs', { valueAsNumber: true })}
className="mono-input"
aria-invalid={Boolean(errors.timeout_secs)}
/>
<span className="field-hint">
超时后将被 Windows Job Object 强制终止
</span>
</Field>
</FormField>
</div>
<div className="form-grid form-grid-single">
<Field label="IANA 时区" error={errors.timezone?.message}>
<input
<FormField
label="IANA 时区"
htmlFor="task-timezone"
error={errors.timezone?.message}
>
<Input
id="task-timezone"
{...register('timezone')}
className="field-input"
list="timezone-options"
placeholder="Asia/Shanghai"
aria-invalid={Boolean(errors.timezone)}
/>
<datalist id="timezone-options">
<option value="Asia/Shanghai" />
<option value="Asia/Hong_Kong" />
<option value="UTC" />
<option value="Europe/London" />
<option value="America/New_York" />
{TIMEZONE_SUGGESTIONS.map((zone) => (
<option value={zone} key={zone} />
))}
</datalist>
</Field>
<Field label="任务类型 (Action Type)">
<select {...register('actionType')} className="field-input">
<option value="script">
执行脚本 (Python / Shell / Node / Lua)
</option>
<option value="http">发起 HTTP 请求</option>
<option value="process">管理常驻/独立二进制</option>
</select>
</Field>
</FormField>
<FormField label="任务类型 (Action Type)">
<Controller
control={control}
name="actionType"
render={({ field }) => (
<Select
className="form-select"
options={ACTION_TYPE_OPTIONS}
value={field.value}
onChange={field.onChange}
/>
)}
/>
</FormField>
</div>
{actionType === 'script' ? (
<div className="dynamic-fields">
<div className="field">
<label className="field-label" htmlFor="task-working-dir">
项目工作目录 (Working Directory)
</label>
<FormField
label="项目工作目录 (Working Directory)"
htmlFor="task-working-dir"
error={errors.script?.working_dir?.message}
>
<div className="field-with-action">
<input
<Input
id="task-working-dir"
{...register('script.working_dir')}
className="field-input mono"
className="mono-input"
placeholder="D:\Projects\sync"
aria-invalid={Boolean(errors.script?.working_dir)}
/>
<button
type="button"
className="button button-secondary pick-directory-button"
<Button
variant="secondary"
// 不夺走输入框焦点:否则 blur 校验插入错误行会让表单瞬间下移,
// 点击可能落到移位后的其它元素上。
onMouseDown={(event) => event.preventDefault()}
onClick={() => setPickerOpen(true)}
>
选择文件夹…
</button>
</div>
{errors.script?.working_dir?.message ? (
<span className="field-error">
{errors.script.working_dir.message}
</span>
) : null}
</Button>
</div>
</FormField>
<VenvDetectorBar
workingDir={debouncedWorkingDir}
probe={venvProbe.data}
pending={venvProbe.isPending}
failed={venvProbe.isError}
/>
<div className="form-grid">
<Field
<FormField
label="解释器"
htmlFor="task-interpreter"
error={errors.script?.interpreter?.message}
>
<input
<Input
id="task-interpreter"
{...register('script.interpreter')}
className="field-input mono"
className="mono-input"
placeholder="python.exe"
/>
</Field>
<Field
</FormField>
<FormField
label="虚拟环境目录 (可选)"
htmlFor="task-venv"
hint="留空时自动探测;填写后优先使用该目录"
error={errors.script?.venv?.message}
>
<input
<Input
id="task-venv"
{...register('script.venv')}
className="field-input mono"
className="mono-input"
placeholder="例如:.venv"
/>
</Field>
</FormField>
</div>
<Field
<FormField
label="脚本文件或相对路径"
htmlFor="task-script"
error={errors.script?.script?.message}
>
<input
<Input
id="task-script"
{...register('script.script')}
className="field-input mono"
className="mono-input"
placeholder="main.py 或 scripts\sync.py"
/>
</Field>
</FormField>
<div className="collection-header">
<div>
<strong>运行参数</strong>
<small>每行一个参数,不经过 Shell 拼接</small>
<Text strong size="sm">
运行参数
</Text>
<Text size="xs" tone="muted">
每行一个参数,不经过 Shell 拼接
</Text>
</div>
<button
type="button"
className="button button-secondary button-small"
onClick={() =>
scriptArgs.append({ key: '', value: '' })
}
<Button
variant="secondary"
size="sm"
onClick={() => scriptArgs.append({ key: '', value: '' })}
>
+ 添加参数
</button>
</Button>
</div>
<div className="collection-list">
{scriptArgs.fields.map((field, index) => (
<div className="argument-row" key={field.id}>
<input
<Input
{...register(`script.args.${index}.key`)}
className="field-input mono"
className="mono-input"
placeholder="参数名 (如 --mode 或 -v)"
/>
<input
<Input
{...register(`script.args.${index}.value`)}
className="field-input mono"
className="mono-input"
placeholder="参数值 (可选,无值可留空)"
/>
<button
type="button"
className="text-button danger-text"
<TextButton
tone="danger"
onClick={() => scriptArgs.remove(index)}
>
删除
</button>
</TextButton>
</div>
))}
{scriptArgs.fields.length === 0 ? (
<p className="empty-inline">暂无运行参数</p>
<Text size="sm" tone="muted">
暂无运行参数
</Text>
) : null}
{errors.script?.args?.message ? (
<span className="field-error">
@@ -469,9 +511,9 @@ export function TaskEditorModal({
<KeyValueEditor
title="环境变量"
fields={scriptEnv.fields}
registerKey={register}
name="script.env"
fields={scriptEnv.fields}
registerField={register}
error={errors.script?.env?.message}
onAdd={() => scriptEnv.append({ key: '', value: '' })}
onRemove={scriptEnv.remove}
@@ -491,10 +533,7 @@ export function TaskEditorModal({
{scriptPreview.env
.filter((item) => item.key.trim())
.map((item, index) => (
<div
className="cli-line-env"
key={`${item.key}-${index}`}
>
<div className="cli-line-env" key={`${item.key}-${index}`}>
set {item.key.trim()}=
{isSensitiveName(item.key)
? '[REDACTED]'
@@ -514,46 +553,66 @@ export function TaskEditorModal({
{actionType === 'http' ? (
<div className="dynamic-fields">
<div className="form-grid">
<Field label="请求 URL" error={errors.http?.url?.message}>
<input
<FormField
label="请求 URL"
htmlFor="task-http-url"
error={errors.http?.url?.message}
>
<Input
id="task-http-url"
{...register('http.url')}
className="field-input mono"
className="mono-input"
placeholder="https://api.example.com/health"
/>
</Field>
<Field label="请求方式">
<select {...register('http.method')} className="field-input">
<option value="GET">GET</option>
<option value="POST">POST</option>
</select>
</Field>
</FormField>
<FormField label="请求方式">
<Controller
control={control}
name="http.method"
render={({ field }) => (
<Select
className="form-select"
options={HTTP_METHOD_OPTIONS}
value={field.value}
onChange={field.onChange}
/>
)}
/>
</FormField>
</div>
<div className="form-grid">
<Field
<FormField
label="期望状态码"
htmlFor="task-http-status"
hint="使用逗号分隔,例如:200, 204"
error={errors.http?.expected_status?.message}
>
<input
<Input
id="task-http-status"
{...register('http.expected_status')}
className="field-input mono"
className="mono-input"
placeholder="200"
/>
</Field>
<Field label="JSON Body" error={errors.http?.body?.message}>
<textarea
</FormField>
<FormField
label="JSON Body"
htmlFor="task-http-body"
error={errors.http?.body?.message}
>
<Textarea
id="task-http-body"
{...register('http.body')}
className="field-input field-textarea mono"
rows={4}
className="mono-input"
placeholder='{"trigger":"manual"}'
/>
</Field>
</FormField>
</div>
<KeyValueEditor
title="请求 Header"
fields={httpHeaders.fields}
registerKey={register}
name="http.headers"
fields={httpHeaders.fields}
registerField={register}
error={errors.http?.headers?.message}
onAdd={() => httpHeaders.append({ key: '', value: '' })}
onRemove={httpHeaders.remove}
@@ -564,63 +623,69 @@ export function TaskEditorModal({
{actionType === 'process' ? (
<div className="dynamic-fields">
<div className="form-grid">
<Field
<FormField
label="可执行程序"
htmlFor="task-process-exe"
error={errors.process?.executable?.message}
>
<input
<Input
id="task-process-exe"
{...register('process.executable')}
className="field-input mono"
className="mono-input"
placeholder="C:\Tools\exporter.exe"
/>
</Field>
<Field label="工作目录">
<input
</FormField>
<FormField label="工作目录" htmlFor="task-process-dir">
<Input
id="task-process-dir"
{...register('process.working_dir')}
className="field-input mono"
className="mono-input"
placeholder="可选"
/>
</Field>
</FormField>
</div>
<div className="collection-header">
<div>
<strong>启动参数</strong>
<small>每行一个参数</small>
<Text strong size="sm">
启动参数
</Text>
<Text size="xs" tone="muted">
每行一个参数
</Text>
</div>
<button
type="button"
className="button button-secondary button-small"
onClick={() =>
processArgs.append({ key: '', value: '' })
}
<Button
variant="secondary"
size="sm"
onClick={() => processArgs.append({ key: '', value: '' })}
>
+ 添加参数
</button>
</Button>
</div>
<div className="collection-list">
{processArgs.fields.map((field, index) => (
<div className="argument-row" key={field.id}>
<input
<Input
{...register(`process.args.${index}.key`)}
className="field-input mono"
className="mono-input"
placeholder="参数名 (如 --port)"
/>
<input
<Input
{...register(`process.args.${index}.value`)}
className="field-input mono"
className="mono-input"
placeholder="参数值 (可选)"
/>
<button
type="button"
className="text-button danger-text"
<TextButton
tone="danger"
onClick={() => processArgs.remove(index)}
>
删除
</button>
</TextButton>
</div>
))}
{processArgs.fields.length === 0 ? (
<p className="empty-inline">暂无启动参数</p>
<Text size="sm" tone="muted">
暂无启动参数
</Text>
) : null}
{errors.process?.args?.message ? (
<span className="field-error">
@@ -630,9 +695,9 @@ export function TaskEditorModal({
</div>
<KeyValueEditor
title="环境变量"
fields={processEnv.fields}
registerKey={register}
name="process.env"
fields={processEnv.fields}
registerField={register}
error={errors.process?.env?.message}
onAdd={() => processEnv.append({ key: '', value: '' })}
onRemove={processEnv.remove}
@@ -640,35 +705,29 @@ export function TaskEditorModal({
</div>
) : null}
<label className="checkbox-field">
<input type="checkbox" {...register('enabled')} />
<span>
<strong>立即激活此任务调度</strong>
<small>保存后立即注册到 Cron 调度器</small>
<Controller
control={control}
name="enabled"
render={({ field }) => (
<Checkbox
className="form-toggle"
checked={field.value}
onChange={field.onChange}
label={
<span className="form-toggle-copy">
<Text strong size="sm">
立即激活此任务调度
</Text>
<Text size="xs" tone="muted">
保存后立即注册到 Cron 调度器
</Text>
</span>
</label>
}
/>
)}
/>
</form>
<footer className="modal-footer">
<button
type="button"
className="button button-secondary"
onClick={onClose}
disabled={saving}
>
取消
</button>
<button
type="submit"
form="task-editor-form"
className="button button-primary"
disabled={saving}
>
{saving ? '保存中...' : task ? '保存修改' : '保存并热刷新'}
</button>
</footer>
</section>
<DirectoryPickerDialog
open={pickerOpen}
initialPath={scriptPreview.working_dir}
@@ -680,7 +739,7 @@ export function TaskEditorModal({
}}
onClose={() => setPickerOpen(false)}
/>
</div>
</Modal>
)
}
@@ -804,39 +863,21 @@ function isSensitiveName(name: string): boolean {
].some((marker) => normalized.includes(marker))
}
interface FieldProps {
label: string
error?: string
hint?: string
children: ReactNode
}
function Field({ label, error, hint, children }: FieldProps) {
return (
<label className="field">
<span className="field-label">{label}</span>
{children}
{error ? <span className="field-error">{error}</span> : null}
{!error && hint ? <span className="field-hint">{hint}</span> : null}
</label>
)
}
interface KeyValueEditorProps {
title: string
name: 'script.env' | 'http.headers' | 'process.env'
fields: Array<{ id: string; key: string; value: string }>
registerKey: UseFormRegister<TaskFormValues>
registerField: UseFormRegister<TaskFormValues>
onAdd: () => void
onRemove: (index: number) => void
error?: string
error?: ReactNode
}
function KeyValueEditor({
title,
name,
fields,
registerKey,
registerField,
onAdd,
onRemove,
error,
@@ -845,46 +886,46 @@ function KeyValueEditor({
<div className="key-value-editor">
<div className="collection-header">
<div>
<strong>{title}</strong>
<small>名称和值会原样提交给后端</small>
<Text strong size="sm">
{title}
</Text>
<Text size="xs" tone="muted">
名称和值会原样提交给后端
</Text>
</div>
<button
type="button"
className="button button-secondary button-small"
onClick={onAdd}
>
<Button variant="secondary" size="sm" onClick={onAdd}>
+ 添加
</button>
</Button>
</div>
<div className="collection-list">
{fields.map((field, index) => (
<div className="key-value-row" key={field.id}>
<input
{...registerKey(
<Input
{...registerField(
`${name}.${index}.key` as FieldPath<TaskFormValues>,
)}
className="field-input mono"
className="mono-input"
placeholder="名称"
/>
<input
{...registerKey(
<PasswordInput
{...registerField(
`${name}.${index}.value` as FieldPath<TaskFormValues>,
)}
type="password"
autoComplete="off"
className="field-input mono"
icon={null}
className="mono-input"
placeholder="值"
autoComplete="off"
/>
<button
type="button"
className="text-button danger-text"
onClick={() => onRemove(index)}
>
<TextButton tone="danger" onClick={() => onRemove(index)}>
删除
</button>
</TextButton>
</div>
))}
{fields.length === 0 ? <p className="empty-inline">暂无配置</p> : null}
{fields.length === 0 ? (
<Text size="sm" tone="muted">
暂无配置
</Text>
) : null}
{error ? <span className="field-error">{error}</span> : null}
</div>
</div>
+50 -85
View File
@@ -23,94 +23,45 @@
font-display: swap;
}
/*
* 页面级基础:字体 / 重置 / 全局焦点兜底。
* 颜色、间距、圆角、阴影一律取自 @stash/ui 的 --su-* 令牌,这里不再定义主题色。
*/
:root {
/* 设计令牌:对齐 Alright 主题(nicetheme) */
--theme-primary: #3858f6;
--theme-primary-soft: rgba(56, 88, 246, 0.1);
--theme-dark: #1d2129;
--theme-secondary: #2c343c;
--theme-muted: #4e5969;
--theme-light: #c9cdd4;
--theme-border: #eee;
--theme-border-soft: #f6f6f6;
--theme-bg: #f7f8fa;
--theme-success: #4abd86;
--theme-danger: #ff3e3e;
--theme-warning: #ff8338;
/* 展示字体:标题用 Outfit,不参与令牌体系,页面自己持有 */
--font-display: 'Outfit-Medium', var(--su-font-sans);
--bg-color: var(--theme-bg);
--card-bg: #ffffff;
--text-main: var(--theme-dark);
--text-muted: var(--theme-muted);
--text-light: var(--theme-light);
--primary: var(--theme-primary);
--primary-hover: #2f49d6;
--primary-soft: var(--theme-primary-soft);
--border-color: var(--theme-border-soft);
--badge-bg: var(--theme-border-soft);
--radius-sm: 6px;
--radius-md: 12px;
--radius-lg: 24px;
--shadow-sm: 0 2px 8px rgba(27, 26, 49, 0.02);
--shadow-card: 0 6px 16px 0 rgba(27, 26, 49, 0.03);
--shadow-modal: 0 16px 48px rgba(27, 26, 49, 0.08);
--background: var(--bg-color);
--surface: var(--card-bg);
--surface-muted: #f7f8fa;
--text: var(--text-main);
--text-secondary: var(--text-muted);
--text-tertiary: #86909c;
--border: var(--theme-border);
--success: var(--theme-success);
--success-bg: rgba(74, 189, 134, 0.1);
--success-border: rgba(74, 189, 134, 0.3);
--danger: var(--theme-danger);
--danger-bg: rgba(255, 62, 62, 0.08);
--danger-border: rgba(255, 62, 62, 0.24);
--warning: var(--theme-warning);
--warning-bg: #fffbe8;
--shadow: var(--shadow-card);
--transition-base: 0.3s ease-in-out;
--font-sans:
'LXGW WenKai', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
'Hiragino Sans GB', 'Microsoft YaHei UI', 'Microsoft YaHei',
'Source Han Sans CN', sans-serif;
--font-display: 'Outfit-Medium', var(--font-sans);
--font-mono:
SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New',
monospace;
color: var(--text);
background: var(--background);
font-family: var(--font-sans);
color: var(--su-text-main);
background-color: var(--su-bg-page);
font-family: var(--su-font-sans);
font-size: var(--su-font-size-md);
line-height: var(--su-line-height-md);
color-scheme: light;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
h1,
h2,
h3 {
font-family: var(--font-display);
font-weight: 500;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
min-width: 320px;
background: var(--background);
html,
body,
#root {
min-height: 100%;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
line-height: 1.5;
font-size: 14px;
}
a {
color: inherit;
text-decoration: none;
}
button,
@@ -128,20 +79,34 @@ button:disabled {
cursor: not-allowed;
}
::placeholder {
color: var(--text-light);
h1,
h2,
h3 {
font-family: var(--font-display);
}
ul,
ol {
list-style: none;
}
/* 键盘焦点环由组件库统一提供;这里只给「非表单控件」补兜底。
表单控件不能加全局 outline:输入框点击时也会命中 :focus-visible,
会和组件自己的边框态叠成「双框」。 */
a:focus-visible,
button:focus-visible,
[tabindex]:not(input):focus-visible {
outline: var(--su-focus-ring);
outline-offset: var(--su-focus-ring-offset);
}
input:focus-visible,
textarea:focus-visible,
select:focus-visible {
outline: none;
}
::selection {
background: var(--theme-primary-soft);
color: var(--theme-dark);
}
:focus-visible {
outline: 3px solid rgba(56, 88, 246, 0.28);
outline-offset: 3px;
}
#root {
min-height: 100vh;
background: var(--su-color-primary-soft);
color: var(--su-text-main);
}
-64
View File
@@ -1,64 +0,0 @@
import { useEffect, type RefObject } from 'react'
const FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',')
export function useFocusTrap(
open: boolean,
containerRef: RefObject<HTMLElement | null>,
initialFocusSelector?: string,
) {
useEffect(() => {
if (!open || !containerRef.current) {
return
}
const container = containerRef.current
const previousFocus =
document.activeElement instanceof HTMLElement
? document.activeElement
: null
const focusFirst = () => {
const initial = initialFocusSelector
? container.querySelector<HTMLElement>(initialFocusSelector)
: null
const first =
initial ?? container.querySelector<HTMLElement>(FOCUSABLE_SELECTOR)
;(first ?? container).focus()
}
const frame = window.requestAnimationFrame(focusFirst)
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Tab') {
return
}
const focusable = Array.from(
container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
).filter((element) => element.offsetParent !== null)
if (focusable.length === 0) {
event.preventDefault()
container.focus()
return
}
const first = focusable[0]
const last = focusable[focusable.length - 1]
if (event.shiftKey && document.activeElement === first) {
event.preventDefault()
last.focus()
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault()
first.focus()
}
}
window.addEventListener('keydown', onKeyDown)
return () => {
window.cancelAnimationFrame(frame)
window.removeEventListener('keydown', onKeyDown)
previousFocus?.focus()
}
}, [containerRef, initialFocusSelector, open])
}
+3
View File
@@ -2,6 +2,8 @@ import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { BrowserRouter } from 'react-router-dom'
import { Toaster } from '@stash/ui'
import '@stash/ui/style.css'
import './index.css'
import App from './App.tsx'
@@ -20,6 +22,7 @@ createRoot(document.getElementById('root')!).render(
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<App />
<Toaster />
</BrowserRouter>
</QueryClientProvider>
</StrictMode>,
+249 -277
View File
@@ -4,6 +4,26 @@ import {
useQuery,
useQueryClient,
} from '@tanstack/react-query'
import {
Button,
Card,
Empty,
Grid,
Notice,
Pagination,
Result,
SearchField,
Select,
Space,
Spinner,
Table,
Tag,
Text,
TextButton,
Title,
toast,
type TableColumn,
} from '@stash/ui'
import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import {
@@ -22,11 +42,10 @@ import {
} from '../api/client'
import { ConfirmDialog } from '../components/ConfirmDialog'
import { RunLogDrawer } from '../components/RunLogDrawer'
import {
EnabledBadge,
} from '../components/StatusBadge'
import { EnabledBadge } from '../components/StatusBadge'
import { TaskEditorModal } from '../components/TaskEditorModal'
import { actionTypeLabel, formatShortDateTime } from '../lib/format'
import { useDebouncedValue } from '../lib/useDebouncedValue'
import {
type TaskFormValues,
valuesToCreateRequest,
@@ -35,6 +54,28 @@ import {
const PAGE_SIZE = 20
const ENABLED_OPTIONS = [
{ value: '', label: '全部状态' },
{ value: 'true', label: '已启用' },
{ value: 'false', label: '已停用' },
]
const ACTION_TYPE_OPTIONS = [
{ value: '', label: '全部类型' },
{ value: 'script', label: '脚本' },
{ value: 'http', label: 'HTTP' },
{ value: 'process', label: '进程' },
]
const TABLE_COLUMNS: TableColumn[] = [
{ key: 'name', title: '名称 / 任务标识', width: 260 },
{ key: 'schedule', title: '调度周期', width: 240 },
{ key: 'type', title: '类型', width: 96 },
{ key: 'status', title: '状态', width: 120 },
{ key: 'timeout', title: '超时配置', width: 100 },
{ key: 'actions', title: '操作', align: 'right', width: 300 },
]
export function TaskDashboard() {
const queryClient = useQueryClient()
const [searchParams, setSearchParams] = useSearchParams()
@@ -47,8 +88,9 @@ export function TaskDashboard() {
const [deleteTarget, setDeleteTarget] = useState<Task | null>(null)
const [logTask, setLogTask] = useState<Task | null>(null)
const [initialRunId, setInitialRunId] = useState<number | null>(null)
const [notice, setNotice] = useState<string | null>(null)
const [actionError, setActionError] = useState<string | null>(null)
const [queryDraft, setQueryDraft] = useState(q)
const debouncedQuery = useDebouncedValue(queryDraft, 300)
const enabled: boolean | undefined =
enabledValue === 'true'
@@ -59,6 +101,7 @@ export function TaskDashboard() {
const actionType = isActionType(actionTypeValue)
? actionTypeValue
: undefined
const hasFilters = Boolean(q || enabledValue || actionTypeValue)
const filters: TaskFilters = {
q: q || undefined,
enabled,
@@ -105,7 +148,7 @@ export function TaskDashboard() {
onSuccess: (task, variables) => {
setEditorOpen(false)
setEditingTask(null)
showNotice(
toast.success(
variables.task ? `任务 ${task.id} 已更新` : `任务 ${task.id} 已创建`,
)
void invalidateTaskData(queryClient)
@@ -114,7 +157,7 @@ export function TaskDashboard() {
const toggleMutation = useMutation({
mutationFn: (task: Task) => setTaskEnabled(task.id, !task.enabled),
onSuccess: (task) => {
showNotice(task.enabled ? `已启用 ${task.id}` : `已停用 ${task.id}`)
toast.success(task.enabled ? `已启用 ${task.id}` : `已停用 ${task.id}`)
void invalidateTaskData(queryClient)
},
onError: (error) => setActionError(error.message),
@@ -123,7 +166,7 @@ export function TaskDashboard() {
mutationFn: (task: Task) => deleteTask(task.id),
onSuccess: (_data, task) => {
setDeleteTarget(null)
showNotice(`任务 ${task.id} 已删除`)
toast.success(`任务 ${task.id} 已删除`)
void invalidateTaskData(queryClient)
},
onError: (error) => setActionError(error.message),
@@ -134,7 +177,7 @@ export function TaskDashboard() {
setLogTask(task)
setInitialRunId(run.id)
setActionError(null)
showNotice(
toast.success(
run.status === 'skipped'
? `任务 ${task.id} 已有运行实例,本次触发已跳过`
: `任务 ${task.id} 已提交运行`,
@@ -147,18 +190,24 @@ export function TaskDashboard() {
})
useEffect(() => {
if (!notice) {
setQueryDraft(q)
}, [q])
useEffect(() => {
const nextQuery = debouncedQuery.trim()
if (nextQuery === q) {
return
}
const timer = window.setTimeout(() => setNotice(null), 4_000)
return () => window.clearTimeout(timer)
}, [notice])
updateFilters({ q: nextQuery || undefined, page: '1' })
// updateFilters 依赖当前 searchParams,每次渲染都是新的闭包;这里只跟随防抖后的输入。
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [debouncedQuery])
const tasks = tasksQuery.data?.items ?? []
const total = tasksQuery.data?.total ?? 0
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
const updateFilters = (changes: Record<string, string | undefined>) => {
function updateFilters(changes: Record<string, string | undefined>) {
const next = new URLSearchParams(searchParams)
for (const [key, value] of Object.entries(changes)) {
if (value) {
@@ -185,49 +234,106 @@ export function TaskDashboard() {
void queryClient.invalidateQueries({ queryKey: ['health'] })
}
const showNotice = (message: string) => {
setNotice(message)
const rows = tasks.map((task) => {
const isRunning =
runMutation.isPending && runMutation.variables?.id === task.id
const isToggling =
toggleMutation.isPending && toggleMutation.variables?.id === task.id
return {
id: task.id,
name: (
<div className="task-name-cell">
<Text className="task-name" strong>
{task.name}
</Text>
<Text className="task-id" size="xs" tone="muted">
{task.id}
</Text>
</div>
),
schedule: (
<div className="schedule-cell">
<code className="code-chip">{task.cron}</code>
<Text size="xs" tone="muted">
{task.timezone}
</Text>
<Text size="xs" tone="muted">
{task.enabled
? nextRuns.get(task.id)
? `下次 ${formatShortDateTime(nextRuns.get(task.id))}`
: '调度中…'
: '未调度'}
</Text>
</div>
),
type: (
<Tag shape="rounded">{actionTypeLabel(task.action.type)}</Tag>
),
status: <EnabledBadge enabled={task.enabled} />,
timeout: (
<Text size="sm" tone="sub">
{task.timeout_secs}s
</Text>
),
actions: (
<Space justify="end" gap="xs" wrap>
<TextButton
disabled={isRunning}
title="立即运行"
onClick={() => runMutation.mutate(task)}
>
{isRunning ? '提交中' : '运行'}
</TextButton>
<TextButton
onClick={() => {
setLogTask(task)
setInitialRunId(null)
}}
>
日志
</TextButton>
<TextButton onClick={() => openEdit(task)}>编辑</TextButton>
<TextButton
disabled={isToggling}
onClick={() => toggleMutation.mutate(task)}
>
{task.enabled ? '停用' : '启用'}
</TextButton>
<TextButton tone="danger" onClick={() => setDeleteTarget(task)}>
删除
</TextButton>
</Space>
),
}
})
return (
<main className="app-shell">
<header className="dashboard-header">
<header className="page-header">
<div className="header-title">
<h1>TaskPilot</h1>
<p className="subtitle">
Rust 本地轻量化任务引擎 · Windows 原生调度中心
</p>
</div>
<div className="header-actions">
<button
type="button"
className="button button-primary"
onClick={openCreate}
>
+ 新建任务
</button>
<p className="eyebrow">TASKPILOT / WINDOWS SCHEDULER</p>
<Title level={1}>TaskPilot</Title>
<Text tone="sub">Rust 本地轻量化任务引擎 · Windows 原生调度中心</Text>
</div>
<Space gap="sm" wrap>
<Button onClick={openCreate}>+ 新建任务</Button>
</Space>
</header>
{notice ? (
<div className="toast-message" role="status">
{notice}
</div>
) : null}
{actionError ? (
<div className="inline-alert inline-alert-error page-alert" role="alert">
<span>{actionError}</span>
<button
type="button"
className="text-button"
onClick={() => setActionError(null)}
<Notice
tone="error"
title="操作失败"
className="page-alert"
action={{ label: '关闭', onClick: () => setActionError(null) }}
>
关闭
</button>
</div>
{actionError}
</Notice>
) : null}
<section className="metrics-grid" aria-label="任务统计">
<section aria-label="任务统计" className="metrics-section">
<Grid columns={4} tabletColumns={2} mobileColumns={1} gap="md">
<MetricCard
label="已托管任务"
value={statsQuery.data?.total}
@@ -243,272 +349,128 @@ export function TaskDashboard() {
value={statsQuery.data?.script}
loading={statsQuery.isPending}
/>
<article className="metric-card">
<span>Rust 引擎</span>
<strong className={healthQuery.isError ? 'metric-danger' : ''}>
{healthQuery.isPending
<MetricCard
label="Rust 引擎"
value={
healthQuery.isPending
? '...'
: healthQuery.isError
? '离线'
: '在线'}
</strong>
</article>
: '在线'
}
loading={false}
danger={healthQuery.isError}
/>
</Grid>
</section>
<section className="card task-card">
<Card padding="none" className="task-card">
<div className="toolbar">
<form
className="search-form"
onSubmit={(event) => {
event.preventDefault()
const value = String(
new FormData(event.currentTarget).get('q') ?? '',
).trim()
updateFilters({ q: value || undefined, page: '1' })
}}
>
<label className="visually-hidden" htmlFor="task-search">
搜索任务
</label>
<input
id="task-search"
key={q}
name="q"
className="field-input search-input"
defaultValue={q}
<SearchField
className="toolbar-search"
value={queryDraft}
onChange={setQueryDraft}
placeholder="搜索任务名称或 ID"
size="md"
maxWidth={420}
/>
<button type="submit" className="button button-secondary">
搜索
</button>
</form>
<div className="filter-row">
<label>
<span className="visually-hidden">启用状态</span>
<select
className="field-input compact-select"
<div className="toolbar-filters">
<Select
className="filter-select"
options={ENABLED_OPTIONS}
value={enabledValue ?? ''}
onChange={(event) =>
onChange={(value) =>
updateFilters({
enabled: event.target.value || undefined,
enabled: value || undefined,
page: '1',
})
}
>
<option value="">全部状态</option>
<option value="true">已启用</option>
<option value="false">已停用</option>
</select>
</label>
<label>
<span className="visually-hidden">任务类型</span>
<select
className="field-input compact-select"
/>
<Select
className="filter-select"
options={ACTION_TYPE_OPTIONS}
value={actionTypeValue ?? ''}
onChange={(event) =>
onChange={(value) =>
updateFilters({
action_type: event.target.value || undefined,
action_type: value || undefined,
page: '1',
})
}
>
<option value="">全部类型</option>
<option value="script">脚本</option>
<option value="http">HTTP</option>
<option value="process">进程</option>
</select>
</label>
{(q || enabledValue || actionTypeValue) && (
<button
type="button"
className="text-button"
onClick={() => {
setSearchParams({})
}}
>
/>
{hasFilters ? (
<TextButton onClick={() => setSearchParams({})}>
清除筛选
</button>
)}
<button
type="button"
className="text-button"
onClick={refreshAll}
disabled={tasksQuery.isFetching}
>
</TextButton>
) : null}
<TextButton onClick={refreshAll} disabled={tasksQuery.isFetching}>
{tasksQuery.isFetching ? '同步中...' : '刷新'}
</button>
</TextButton>
</div>
</div>
{tasksQuery.isError ? (
<div className="state-panel state-error">
<h2>任务列表加载失败</h2>
<p>{tasksQuery.error.message}</p>
<button
type="button"
className="button button-secondary"
<Result
status="error"
title="任务列表加载失败"
description={tasksQuery.error.message}
actions={
<Button
variant="secondary"
onClick={() => void tasksQuery.refetch()}
>
重试
</button>
</div>
</Button>
}
/>
) : tasksQuery.isPending ? (
<div className="state-panel">
<span className="loading-mark" aria-hidden="true" />
<p>正在读取任务...</p>
<div className="state-block">
<Spinner label="正在读取任务" />
<Text tone="sub">正在读取任务...</Text>
</div>
) : tasks.length === 0 ? (
<div className="state-panel">
<p className="section-label">EMPTY</p>
<h2>{q || enabledValue || actionTypeValue ? '没有匹配任务' : '还没有任务'}</h2>
<p>
{q || enabledValue || actionTypeValue
<Empty
className="empty-state"
text={
<span className="empty-copy">
<Text as="span" size="lg" strong>
{hasFilters ? '没有匹配任务' : '还没有任务'}
</Text>
<Text as="span" size="md" tone="sub">
{hasFilters
? '请调整搜索条件后重试。'
: '创建第一个定时任务,开始使用真实调度能力。'}
</p>
{!q && !enabledValue && !actionTypeValue ? (
<button
type="button"
className="button button-primary"
onClick={openCreate}
>
新建任务
</button>
) : null}
</div>
</Text>
</span>
}
action={
hasFilters ? undefined : (
<Button onClick={openCreate}>新建任务</Button>
)
}
/>
) : (
<>
<div className="table-container">
<table className="task-table">
<thead>
<tr>
<th>名称 / 任务标识</th>
<th>调度周期</th>
<th>类型</th>
<th>状态</th>
<th>超时配置</th>
<th className="align-right">操作</th>
</tr>
</thead>
<tbody>
{tasks.map((task) => {
const isRunning =
runMutation.isPending &&
runMutation.variables?.id === task.id
return (
<tr key={task.id}>
<td>
<div className="task-name">{task.name}</div>
<div className="task-id mono">{task.id}</div>
</td>
<td>
<code>{task.cron}</code>
<div className="cell-note">{task.timezone}</div>
<div className="cell-note">
{task.enabled
? nextRuns.get(task.id)
? `下次 ${formatShortDateTime(nextRuns.get(task.id))}`
: '调度中…'
: '未调度'}
</div>
</td>
<td>
<span className="type-badge">
{actionTypeLabel(task.action.type)}
</span>
<div className="cell-note">
超时 {task.timeout_secs}s
</div>
</td>
<td>
<EnabledBadge enabled={task.enabled} />
</td>
<td className="cell-note">超时 {task.timeout_secs}s</td>
<td>
<div className="row-actions">
<button
type="button"
className="button button-secondary button-small"
disabled={isRunning}
title="立即运行"
onClick={() => runMutation.mutate(task)}
>
{isRunning ? '提交中' : '运行'}
</button>
<button
type="button"
className="button button-secondary button-small"
onClick={() => {
setLogTask(task)
setInitialRunId(null)
}}
>
日志
</button>
<button
type="button"
className="button button-secondary button-small"
onClick={() => openEdit(task)}
>
编辑
</button>
<button
type="button"
className="button button-secondary button-small"
disabled={
toggleMutation.isPending &&
toggleMutation.variables?.id === task.id
}
onClick={() => toggleMutation.mutate(task)}
>
{task.enabled ? '停用' : '启用'}
</button>
<button
type="button"
className="button button-ghost button-small danger-text"
onClick={() => setDeleteTarget(task)}
>
删除
</button>
</div>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
<footer className="pagination">
<span>
<Table
className="task-table"
columns={TABLE_COLUMNS}
rows={rows}
size="md"
/>
<footer className="pagination-bar">
<Text size="sm" tone="sub">
共 {total} 个任务,第 {page} / {totalPages} 页
</span>
<div>
<button
type="button"
className="button button-secondary button-small"
disabled={page <= 1}
onClick={() =>
updateFilters({ page: String(Math.max(1, page - 1)) })
}
>
上一页
</button>
<button
type="button"
className="button button-secondary button-small"
disabled={page >= totalPages}
onClick={() =>
updateFilters({ page: String(Math.min(totalPages, page + 1)) })
}
>
下一页
</button>
</div>
</Text>
<Pagination
page={page}
total={total}
pageSize={PAGE_SIZE}
onChange={(next) => updateFilters({ page: String(next) })}
/>
</footer>
</>
)}
</section>
</Card>
<TaskEditorModal
open={editorOpen}
@@ -557,16 +519,26 @@ export function TaskDashboard() {
interface MetricCardProps {
label: string
value: number | undefined
value: number | string | undefined
loading: boolean
danger?: boolean
}
function MetricCard({ label, value, loading }: MetricCardProps) {
function MetricCard({ label, value, loading, danger = false }: MetricCardProps) {
return (
<article className="metric-card">
<span>{label}</span>
<strong>{loading ? '...' : (value ?? '--')}</strong>
</article>
<Card padding="md" className="metric-card" hoverable>
<Text tone="sub" size="sm">
{label}
</Text>
<Title
level={1}
as="div"
weight="medium"
className={danger ? 'metric-value metric-danger' : 'metric-value'}
>
{loading ? '...' : (value ?? '--')}
</Title>
</Card>
)
}
+15
View File
@@ -2,6 +2,21 @@ import '@testing-library/jest-dom/vitest'
import { cleanup } from '@testing-library/react'
import { afterEach, vi } from 'vitest'
/**
* jsdom 30 还没有实现 `<dialog>` 的 showModal / close,
* 而 @stash/ui 的 Modal / Drawer 依赖它们(浏览器原生支持)。
* 这里补一个最小的开关实现:只维护 open 属性,焦点与 inert 由真实浏览器负责。
*/
const dialogPrototype = window.HTMLDialogElement?.prototype
if (dialogPrototype && typeof dialogPrototype.showModal !== 'function') {
dialogPrototype.showModal = function showModal(this: HTMLDialogElement) {
this.setAttribute('open', '')
}
dialogPrototype.close = function close(this: HTMLDialogElement) {
this.removeAttribute('open')
}
}
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
+4
View File
@@ -3,6 +3,10 @@ import { defineConfig } from 'vite'
export default defineConfig({
plugins: [react()],
// @stash/ui 是本地 file 依赖(软链),去重 React,避免加载两份运行时
resolve: {
dedupe: ['react', 'react-dom'],
},
server: {
host: '127.0.0.1',
port: 5173,
+6
View File
@@ -17,6 +17,12 @@ function Assert-ExitCode {
Push-Location $projectRoot
try {
# 前端依赖同级 stash-ui(file:../../stash-ui):发布包要求先有组件库产物
$stashUiDist = [System.IO.Path]::GetFullPath((Join-Path $projectRoot '..\stash-ui\dist\stash-ui.js'))
if (-not (Test-Path -LiteralPath $stashUiDist)) {
throw "Missing @stash/ui build output: $stashUiDist. Run 'npm --prefix ..\stash-ui install' and 'npm --prefix ..\stash-ui run build' first."
}
pnpm --dir frontend build
Assert-ExitCode 'Frontend build'
cargo build --release --bin task-pilot-backend --manifest-path backend\Cargo.toml