Compare commits

...

3 Commits

Author SHA1 Message Date
d33eb00377 docs: 完善前端样式开发规范 2026-05-28 16:57:46 +08:00
e09ced44ee docs: 前端开发规范分层整理
- openspec/config.yaml 保留最高级前端规约和样式红线
- docs/development/README.md 引用前端专题文档避免重复
- docs/development/frontend.md 补充 antd、组件、样式、表单、测试等具体规范
2026-05-28 16:19:34 +08:00
b5301ec7d1 refactor: 前端 antd 组件使用最佳实践重构
- 修正 API 响应类型,增加 ProjectResponse 包装类型
- ConfigProvider 配置中文 locale (zhCN)
- 生产入口启用 ErrorBoundary,使用 Result 组件
- ReactQueryDevtools 仅开发环境渲染
- Sider 增加 collapsible 配置,使用 antd 默认折叠行为
- 项目页面拆分为 ProjectToolbar/ProjectTable/ProjectFormModal
- 搜索改用 Input.Search,表单增加 whitespace 校验
- 404/ErrorBoundary/Dashboard 使用 antd Result/Typography/Card/Descriptions
- 清理未使用的 ProtectedRoute 和冗余样式类
- styles.css 仅保留必要布局样式,无 antd 内部类覆盖
- 更新测试覆盖,避免依赖 antd 内部类名
- 更新 docs/development/frontend.md 开发规范
2026-05-28 16:09:01 +08:00
24 changed files with 556 additions and 451 deletions

View File

@@ -7,11 +7,11 @@
"dependencies": {
"@ant-design/icons": "^6.2.3",
"@sinclair/typebox": "^0.34.49",
"@tanstack/react-query": "^5.100.10",
"@tanstack/react-query": "^5.100.14",
"ajv": "^8.20.0",
"antd": "^6.4.3",
"drizzle-orm": "^0.45.2",
"es-toolkit": "^1.46.1",
"es-toolkit": "^1.47.0",
"pino": "^10.3.1",
"pino-pretty": "^13.1.3",
"pino-roll": "^4.0.0",
@@ -24,15 +24,15 @@
"@commitlint/cli": "^21.0.1",
"@commitlint/config-conventional": "^21.0.1",
"@eslint/js": "^10.0.1",
"@tanstack/react-query-devtools": "^5.100.10",
"@tanstack/react-query-devtools": "^5.100.14",
"@testing-library/react": "^16.3.2",
"@types/bun": "^1.3.14",
"@types/jsdom": "^28.0.3",
"@types/react": "^19.2.14",
"@types/react": "^19.2.15",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.2",
"drizzle-kit": "^0.31.10",
"eslint": "^10.3.0",
"eslint": "^10.4.0",
"eslint-config-prettier": "^10.1.8",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
@@ -42,11 +42,11 @@
"eslint-plugin-react-refresh": "^0.5.2",
"husky": "^9.1.7",
"jsdom": "^29.1.1",
"lint-staged": "^17.0.4",
"lint-staged": "^17.0.5",
"prettier": "^3.8.3",
"typescript": "^6.0.3",
"typescript-eslint": "^8.59.3",
"vite": "^8.0.13",
"typescript-eslint": "^8.60.0",
"vite": "^8.0.14",
},
},
},

View File

@@ -57,8 +57,7 @@
- 运行工具使用 bunx禁止使用 npx、pnpx。
- 新增代码优先复用已有组件、工具和依赖库,不引入新依赖;确需新增依赖时先说明原因。
- 后端优先使用 Bun 内置 API其次是 es-toolkit、标准 Web API、主流三方库最后才自行实现。
- 前端样式优先使用 antd 组件、组件 props、antd Design Token / CSS 变量、styles.css CSS 类,最后才自行开发组件
- 前端禁止组件内联 style、覆盖 antd 内部类名、使用 !important、硬编码色值。
- 前端优先使用 Ant Design 组件默认能力和组件 props 组合界面,具体组件、样式、数据流和测试细节见 [frontend.md](frontend.md)
- 当前项目无需考虑向前兼容。
## 包管理、依赖与提交

View File

@@ -22,43 +22,120 @@
- 每个 React 组件一个 .tsx 文件,文件名使用 PascalCase
- 组件 props 定义为 interface XxxProps紧邻组件函数声明
- 类型从 src/shared/api.ts 导入,使用 import type
- 展示组件放在 components/,通过 props 接收数据,通过回调返回事件
- 容器逻辑放在 hooks 中,组件只做数据消费
- 展示组件放在 components/,通过 props 接收数据,通过回调返回事件;页面专属展示组件可就近放在 pages/\*/components/
- 容器逻辑放在 hooks 中,组件只做数据消费;全局共享查询可提取为独立 hook如 use-meta
- 工具函数放在 utils/,保持纯函数无副作用
页面组件保持编排职责,组合 hooks 和展示组件;当页面同时承担查询、筛选、分页、表格列、弹窗表单和 mutation 时,应按工具栏、表格、表单弹窗等功能边界拆分。拆分以降低职责复杂度为目标,避免为了拆分而拆分。
## Ant Design 使用规范
- 优先使用 antd 组件默认状态和官方交互模式;没有明确产品定制需求时,不额外改写组件视觉。
- 优先通过组件 props 配置行为和外观,例如 `collapsible``theme``scroll``locale``status``variant``color`
- 全局使用 `ConfigProvider` 配置 antd 中文 locale`antd/locale/zh_CN` 导入 `zhCN`
- 需要 message、modal、notification 等 antd 应用级能力时,在 `ConfigProvider` 内包裹 `App`(代码中可别名为 `AntApp`),组件内通过 `App.useApp()` 获取。
- 状态页、异常页、空结果优先使用 `Result``Empty``Alert``Spin` 等 antd 组件。
- 信息展示优先使用 `Typography``Card``Descriptions``Table` 等 antd 组件,避免用原生标签加自定义 CSS 复刻。
- 搜索输入优先使用 `Input.Search`,保持回车搜索、按钮搜索和清空行为一致。
- 表格在窄屏有挤压风险时必须提供明确的 `scroll` 或响应式列策略。
## 样式开发规范
前端基于 Ant Design 构建 UI,样式开发优先级:
前端基于 Ant Design 构建 UI。样式管理目标是让 antd 继续承担主视觉系统,项目 CSS 只补足页面外壳、局部布局和自有组件视觉,不另起一套与 antd 竞争的样式体系。
1. antd 组件
2. 组件 props
3. antd Design Token / CSS 变量(--ant-\*
4. styles.css CSS 类
5. 自行开发组件
样式开发优先级:
1. antd 组件默认能力,例如 `Button``Card``Table``Form``Result``Empty`
2. antd 组件 props例如 `size``type``variant``color``status``layout``scroll``gutter`
3. antd 布局组件,例如 `Layout``Flex``Space``Row``Col`,避免为普通排列关系新增 CSS。
4. `ConfigProvider` theme token 和 antd 组件 token处理主题级或组件级统一调整。
5. antd CSS 变量(`--ant-*`),用于项目自有 CSS 中引用颜色、间距、字体、圆角和阴影等设计值。
6. 全局 CSS仅承载应用外壳、全局基础样式和少量明确复用的工具类。
7. CSS Modules用于页面专属布局或项目自有组件视觉仅在局部样式增长到需要就近维护时使用。
8. 自行开发视觉组件,仅在 antd 组件和组合方式无法表达明确产品需求时使用。
红线:
- 严禁在组件中使用 style 属性内联调整样式
- 严禁通过 CSS 覆盖 antd 组件内部类名
- 严禁使用 !important
- 颜色统一使用 antd Design Token / CSS 变量,不使用硬编码色值
- 严禁在组件中使用 `style` 属性内联调整样式
- 严禁通过 CSS 覆盖 antd 组件内部类名,例如 `.ant-*`
- 严禁使用 `!important`
- 颜色统一使用 antd Design Token / CSS 变量,不使用硬编码色值
- 默认不引入 Tailwind、UnoCSS、Sass、Less、CSS-in-JS 或额外 PostCSS 插件;确需引入时必须先说明现有 antd + CSS Modules 无法满足的具体问题、影响范围和迁移成本。
styles.css 组织:
默认状态原则:如果 antd 组件默认样式已经满足当前需求,不为其增加额外 CSS 类;不要通过外层 CSS 修改 Sider、Menu、Table、Modal 等组件内部结构样式。
- 自定义 CSS 变量定义在 :root 中
- 布局类定义全局页面结构
- 组件修饰类为自定义视觉组件提供样式变体
- 通用工具类提供公用排版能力
全局 CSS 归属:
- 当前入口保留 `src/web/styles.css`;当文件继续增长时,优先拆分为 `src/web/styles/global.css``src/web/styles/app-shell.css``src/web/styles/utilities.css` 等按职责命名的文件,再由入口样式文件集中导入。
- `global.css` 仅放 `html``body``:root`、字体渲染、全局背景等应用级基础样式。
- `app-shell.css` 仅放应用外壳样式,例如 `app-layout``app-header``app-content`、Header 内容分布和主内容间距。
- `utilities.css` 只放至少两处复用、语义稳定、不会与 antd props 重叠的工具类;只有一处使用时优先改为 antd 布局组件或局部 CSS Modules。
- 全局类名必须带有明确前缀,应用外壳使用 `app-*`,工具类使用 `u-*`;禁止新增 `.container``.title``.content` 等容易跨页面冲突的泛名类。
CSS Modules 归属:
- 页面专属样式与页面就近放置,例如 `src/web/pages/projects/projects.module.css`
- 自有组件样式与组件就近放置,例如 `src/web/components/FooCard/foo-card.module.css`
- CSS Modules 中类名使用职责语义,例如 `.root``.toolbar``.summaryCard``.emptyState`;通过导入对象绑定到组件,避免字符串拼写散落。
- 同一类样式只服务当前页面或组件;一旦被多处复用,应先判断能否用 antd 组件或 props 表达,再考虑提取共享组件,而不是直接提升为全局 CSS。
- 首次实际使用 `*.module.css` 时,同步补全 TypeScript 声明和必要测试,确保类型检查与构建链路稳定。
antd 定制边界:
- 优先使用官方 props、theme token 和组件 token不要因为视觉微调直接写 CSS。
- antd v6 组件暴露 `classNames` 语义插槽时,可以把项目自有类绑定到官方稳定插槽;仍然不得选择 `.ant-*` 内部 DOM 类名。
- 避免使用 antd `styles` 语义插槽写内联样式;如果必须使用,应先评估是否可以通过 token、CSS 变量或 CSS Modules 表达。
- 弹窗、下拉、表格、菜单等复杂组件不依赖内部 DOM 结构做布局修补;发现必须修补时,优先调整组件组合或交互设计。
token 和 CSS 变量规则:
- 颜色使用 `var(--ant-color-*)`,例如文本、边框、背景和状态色。
- 间距、字号、圆角和阴影优先使用 `var(--ant-padding-*)``var(--ant-margin-*)``var(--ant-font-size-*)``var(--ant-border-radius*)``var(--ant-box-shadow*)` 等 antd 变量。
- 项目自定义 CSS 变量只能定义在 `:root` 或清晰的主题容器上,并且必须基于 antd token 派生;不要创建与 antd 平行的颜色、间距、字号体系。
- 主题切换统一通过 `ConfigProvider` theme algorithm 和 token 控制,不在 CSS 中硬编码亮色或暗色分支。
响应式规则:
- 页面必须在桌面和移动端正常加载和可读。
- 优先使用 antd `Flex``Grid``Table scroll`、响应式列配置处理布局收缩。
- 媒体查询只处理页面或自有组件的布局断点;不要用媒体查询覆盖 antd 内部结构。
- 移动端适配优先保证内容可访问、操作可点击和横向溢出可控,不追求与桌面完全一致的排版。
新增样式前检查:
1. 这个需求是否可以由 antd 组件或 props 完成?
2. 这个样式是否属于主题级统一调整,应该放到 `ConfigProvider` theme token
3. 这个样式是否只服务页面外壳,应该留在全局 CSS
4. 这个样式是否只服务单个页面或自有组件,应该使用 CSS Modules
5. 这个样式是否在覆盖 antd 内部结构?如果是,应重新设计组件组合。
6. 这个样式是否引入了硬编码色值、`style``.ant-*``!important`?如果是,不应合入。
## 表单与交互规范
- Modal + Form 提交使用 `Form onFinish` 处理业务提交,`Modal onOk` 只触发 `form.submit()`
- 不在 `Modal onOk` 中直接执行异步 `validateFields` 和提交逻辑,也不通过 lint disable 绕过该问题。
- 文本必填字段同时配置 `required: true``whitespace: true`,保持前端校验与后端 trim 后校验一致。
- 提交中状态传给 antd 组件的 loading/confirmLoading 等 props避免自行实现重复状态样式。
- 操作确认优先使用 `Popconfirm`,成功/失败反馈优先使用 antd message。
## 运行时外壳规范
- 生产入口必须启用 `ErrorBoundary`,运行时渲染异常使用 antd `Result status="500"` 或等价组件展示。
- `ReactQueryDevtools` 仅在 `import.meta.env.DEV` 条件下渲染,不进入生产渲染路径。
- 主题切换统一通过 `ConfigProvider` 的 antd theme algorithm 控制,不使用硬编码主题色。
## TanStack Query 规范
- Query key 使用 structured array使用 as const 保持字面量类型
- 全局面板级查询可持续刷新,详情级查询必须按状态条件启用
- 多处页面使用同一后端资源时,应提取共享 hook避免重复定义 fetch 函数。
## fetch 封装
统一使用 fetch不引入 axios。错误抛异常由 TanStack Query 的 error 状态承接。
前后端共享的请求和响应类型定义在 src/shared/api.ts。前端 fetch 函数的返回类型必须匹配后端真实 JSON 形状;如果后端返回包装对象,例如 `{ project: Project }`,应声明对应响应类型并在 hook 内提取业务对象。
## 前端测试
- 测试目录为 tests/web/,结构对应 src/web/
@@ -67,6 +144,8 @@ styles.css 组织:
- 测试用户行为而非实现细节
- 只 mock 系统边界,使用真实的 QueryClientProvider 包裹组件
- 组件测试环境由 tests/setup.ts 和 bunfig.toml preload 提供
- 断言优先基于用户可见文本、role、按钮和交互结果不依赖 `.ant-*` 内部类名。
- 对 antd 组件只断言本项目传入的可观察行为或配置结果,避免把 antd 内部 DOM 结构当作稳定契约。
## 更新触发条件

View File

@@ -17,8 +17,9 @@ context: |
- src/server目录下是基于bun实现的后端代码
- 后端库使用优先级Bun 内置 API > es-toolkit > 主流三方库 > 项目公共工具 > 自行实现
- src/web目录下是基于Bun HTML import、React、Ant Design实现的前端代码
- 前端样式开发优先级:antd组件 > 组件props > antd Design Token/CSS变量(--ant-*) > styles.css CSS类 > 自行开发组件
- 前端严禁组件内联style属性、CSS覆盖antd内部类名、使用!important、硬编码色值
- 前端最高规约:优先使用 antd 组件默认能力和组件 props 组合界面,具体组件、样式、数据流和测试细节遵循 docs/development/frontend.md
- 前端样式管理antd 组件/props/token 优先AppShell 使用最小全局 CSS页面和自有组件样式增长后使用就近 CSS Modules默认不引入 Tailwind、UnoCSS、Sass、Less、CSS-in-JS 等额外样式体系
- 前端样式红线:禁止组件内联 style、覆盖 antd 内部类名、使用 !important、硬编码色值
- Git提交: 仅中文; 格式"类型: 简短描述", 类型: feat/fix/refactor/docs/style/test/chore; 多行描述空行后写详细说明
- 禁止创建git操作task
- 积极使用subagents精心设计并行任务节省上下文空间加速任务执行

View File

@@ -5,13 +5,13 @@
"source": "ant-design/antd-skill",
"sourceType": "github",
"skillPath": "skills/ant-design/SKILL.md",
"computedHash": "4d0447d48fced080b2825ecc0fb4d7ca836c8015882899c643acca0b864d5179"
"computedHash": "096d4ac9513e43030f960aab49b50168a3d5eb35be86926ac6e96e5998ea9466"
},
"antd": {
"source": "ant-design/antd-skill",
"sourceType": "github",
"skillPath": "skills/antd/SKILL.md",
"computedHash": "4295010f09f85855cab9e9de9ec7f96c14541474b4f3f9d6ef89006430931b94"
"computedHash": "5e26c8042060bb811118927b5daf637af7929a00fa973dd8f5f804f3ba6e2bf2"
}
}
}

View File

@@ -37,6 +37,10 @@ export interface ProjectListResponse {
total: number;
}
export interface ProjectResponse {
project: Project;
}
export type ProjectStatus = "active" | "archived";
export type RuntimeMode = "development" | "production" | "test";

View File

@@ -1,16 +1,13 @@
import { MenuFoldOutlined, MenuUnfoldOutlined } from "@ant-design/icons";
import { useQuery } from "@tanstack/react-query";
import { App as AntApp, ConfigProvider, Layout, Segmented, theme } from "antd";
import zhCN from "antd/locale/zh_CN";
import { useEffect } from "react";
import { useLocation } from "react-router";
import type { MetaResponse } from "../shared/api";
import { APP } from "../shared/app";
import { Sidebar } from "./components/Sidebar";
import { useMeta } from "./hooks/use-meta";
import { useSidebarCollapsed } from "./hooks/use-sidebar-collapsed";
import { type ThemePreference, useThemePreference } from "./hooks/use-theme-preference";
import { MENU_ITEMS } from "./menu";
import { AppRoutes } from "./routes";
const { Content, Header, Sider } = Layout;
@@ -24,13 +21,7 @@ const THEME_OPTIONS = [
export function App() {
const { effectiveTheme, preference: themePreference, setPreference: setThemePreference } = useThemePreference();
const { collapsed, setCollapsed } = useSidebarCollapsed();
const location = useLocation();
const { data: meta } = useQuery({
queryFn: fetchMeta,
queryKey: ["meta"],
refetchInterval: 30000,
staleTime: 5000,
});
const { data: meta } = useMeta();
useEffect(() => {
document.title = APP.title;
@@ -41,15 +32,12 @@ export function App() {
setThemePreference(value as ThemePreference);
};
const currentPath = location.pathname;
const currentItem = MENU_ITEMS.find((item) => item.path === currentPath);
const pageTitle = currentItem?.label ?? APP.title;
const versionDisplay = meta?.version ? `v${meta.version}` : null;
const themeAlgorithm = effectiveTheme === "dark" ? theme.darkAlgorithm : theme.defaultAlgorithm;
return (
<ConfigProvider theme={{ algorithm: themeAlgorithm }}>
<ConfigProvider locale={zhCN} theme={{ algorithm: themeAlgorithm }}>
<AntApp>
<Layout className="app-layout">
<Header className="app-header">
@@ -58,7 +46,6 @@ export function App() {
<span className="app-brand">{APP.title}</span>
{versionDisplay && <span className="app-version">{versionDisplay}</span>}
</span>
<span className="app-page-title">{pageTitle}</span>
</div>
<div className="app-header-right">
<Segmented
@@ -70,10 +57,11 @@ export function App() {
</Header>
<Layout>
<Sider
className="app-sidebar"
collapsed={collapsed}
collapsedWidth={64}
collapsible
onCollapse={(collapsed) => setCollapsed(collapsed)}
theme="light"
trigger={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
width={232}
>
@@ -90,9 +78,3 @@ export function App() {
</ConfigProvider>
);
}
async function fetchMeta(): Promise<MetaResponse> {
const response = await fetch("/api/meta");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json() as Promise<MetaResponse>;
}

View File

@@ -1,6 +1,6 @@
import type { ErrorInfo, ReactNode } from "react";
import { Alert, Button, Space } from "antd";
import { Button, Result } from "antd";
import { Component } from "react";
interface Props {
@@ -25,12 +25,16 @@ export class ErrorBoundary extends Component<Props, State> {
override render() {
if (this.state.hasError) {
return (
<Space align="center" className="error-boundary-fallback" size="large" vertical>
<Alert showIcon title="页面渲染出现异常,请刷新重试" type="error" />
<Button onClick={() => window.location.reload()} type="primary">
</Button>
</Space>
<Result
extra={
<Button onClick={() => window.location.reload()} type="primary">
</Button>
}
status="500"
subTitle="页面渲染出现异常,请刷新重试"
title="渲染错误"
/>
);
}
return this.props.children;

View File

@@ -28,13 +28,5 @@ export function Sidebar() {
}
};
return (
<Menu
className="app-sidebar-menu"
items={menuItems}
mode="inline"
onClick={handleMenuClick}
selectedKeys={selectedKeys}
/>
);
return <Menu items={menuItems} mode="inline" onClick={handleMenuClick} selectedKeys={selectedKeys} />;
}

18
src/web/hooks/use-meta.ts Normal file
View File

@@ -0,0 +1,18 @@
import { useQuery } from "@tanstack/react-query";
import type { MetaResponse } from "../../shared/api";
export function useMeta() {
return useQuery({
queryFn: fetchMeta,
queryKey: ["meta"],
refetchInterval: 30000,
staleTime: 5000,
});
}
async function fetchMeta(): Promise<MetaResponse> {
const response = await fetch("/api/meta");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json() as Promise<MetaResponse>;
}

View File

@@ -4,6 +4,7 @@ import type {
CreateProjectRequest,
Project,
ProjectListResponse,
ProjectResponse,
ProjectStatus,
UpdateProjectRequest,
} from "../../shared/api";
@@ -81,7 +82,8 @@ async function archiveProject(id: string): Promise<Project> {
const body = (await response.json().catch(() => null)) as null | { error?: string };
throw new Error(body?.error ?? `HTTP ${response.status}`);
}
return response.json() as Promise<Project>;
const data = (await response.json()) as ProjectResponse;
return data.project;
}
async function createProject(data: CreateProjectRequest): Promise<Project> {
@@ -94,7 +96,8 @@ async function createProject(data: CreateProjectRequest): Promise<Project> {
const body = (await response.json().catch(() => null)) as null | { error?: string };
throw new Error(body?.error ?? `HTTP ${response.status}`);
}
return response.json() as Promise<Project>;
const result = (await response.json()) as ProjectResponse;
return result.project;
}
async function deleteProject(id: string): Promise<void> {
@@ -111,7 +114,8 @@ async function fetchProject(id: string): Promise<Project> {
const body = (await response.json().catch(() => null)) as null | { error?: string };
throw new Error(body?.error ?? `HTTP ${response.status}`);
}
return response.json() as Promise<Project>;
const data = (await response.json()) as ProjectResponse;
return data.project;
}
async function fetchProjectList(params: {
@@ -141,7 +145,8 @@ async function restoreProject(id: string): Promise<Project> {
const body = (await response.json().catch(() => null)) as null | { error?: string };
throw new Error(body?.error ?? `HTTP ${response.status}`);
}
return response.json() as Promise<Project>;
const data = (await response.json()) as ProjectResponse;
return data.project;
}
async function updateProject(id: string, data: UpdateProjectRequest): Promise<Project> {
@@ -154,5 +159,6 @@ async function updateProject(id: string, data: UpdateProjectRequest): Promise<Pr
const body = (await response.json().catch(() => null)) as null | { error?: string };
throw new Error(body?.error ?? `HTTP ${response.status}`);
}
return response.json() as Promise<Project>;
const result = (await response.json()) as ProjectResponse;
return result.project;
}

View File

@@ -22,11 +22,7 @@ export function useSidebarCollapsed() {
writeSidebarCollapsed(nextCollapsed);
};
const toggleCollapsed = () => {
setCollapsed(!collapsed);
};
return { collapsed, setCollapsed, toggleCollapsed };
return { collapsed, setCollapsed };
}
export function writeSidebarCollapsed(collapsed: boolean, storage: Storage = window.localStorage) {

View File

@@ -5,6 +5,7 @@ import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router";
import { App } from "./app";
import { ErrorBoundary } from "./components/ErrorBoundary";
import "./styles.css";
const queryClient = new QueryClient({
@@ -25,11 +26,13 @@ if (!rootElement) {
createRoot(rootElement).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<App />
</BrowserRouter>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
<ErrorBoundary>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<App />
</BrowserRouter>
{import.meta.env["DEV"] && <ReactQueryDevtools initialIsOpen={false} />}
</QueryClientProvider>
</ErrorBoundary>
</StrictMode>,
);

View File

@@ -1,22 +1,19 @@
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { Button, Space } from "antd";
import { Button, Result } from "antd";
import { useNavigate } from "react-router";
export function NotFoundPage() {
const navigate = useNavigate();
const handleGoHome = () => {
void navigate("/");
};
return (
<Space align="center" className="not-found-page" size="large" vertical>
<ExclamationCircleOutlined className="not-found-icon" />
<h1>404</h1>
<p>访</p>
<Button onClick={handleGoHome} type="primary">
</Button>
</Space>
<Result
extra={
<Button onClick={() => void navigate("/")} type="primary">
</Button>
}
status="404"
subTitle="您访问的页面不存在"
title="404"
/>
);
}

View File

@@ -1,29 +1,32 @@
import { useQuery } from "@tanstack/react-query";
import { Space } from "antd";
import type { DescriptionsProps } from "antd";
import type { MetaResponse } from "../../../shared/api";
import { Alert, Card, Descriptions, Space, Spin, Typography } from "antd";
import { APP } from "../../../shared/app";
import { useMeta } from "../../hooks/use-meta";
export function DashboardPage() {
const { data: meta } = useQuery({
queryFn: fetchMeta,
queryKey: ["meta"],
refetchInterval: 30000,
staleTime: 5000,
});
const { data: meta, error, isLoading } = useMeta();
const descriptionItems: DescriptionsProps["items"] = meta
? [
{ children: meta.service, key: "service", label: "服务" },
{ children: meta.version, key: "version", label: "版本" },
{ children: meta.timestamp, key: "timestamp", label: "时间戳" },
]
: [];
return (
<Space className="full-width-space" size="large" vertical>
<h2>使 {APP.title}</h2>
<p> /api/meta </p>
{meta && <pre className="meta-response">{JSON.stringify(meta, null, 2)}</pre>}
<Space size="large" vertical>
<Typography.Title level={2}>使 {APP.title}</Typography.Title>
<Typography.Paragraph> /api/meta </Typography.Paragraph>
{isLoading && <Spin size="large" />}
{error && <Alert description={error.message} showIcon title="加载失败" type="error" />}
{meta && (
<Card>
<Descriptions column={1} items={descriptionItems} title="服务信息" />
</Card>
)}
</Space>
);
}
async function fetchMeta(): Promise<MetaResponse> {
const response = await fetch("/api/meta");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json() as Promise<MetaResponse>;
}

View File

@@ -0,0 +1,86 @@
import { App as AntApp, Form, Input, Modal } from "antd";
import type { CreateProjectRequest, Project, UpdateProjectRequest } from "../../../../shared/api";
interface FormValues {
description?: string;
name: string;
}
interface ProjectFormModalProps {
editingProject: null | Project;
onCancel: () => void;
onCreate: (data: CreateProjectRequest) => Promise<unknown>;
onOpenChange: (open: boolean) => void;
onUpdate: (args: { data: UpdateProjectRequest; id: string }) => Promise<unknown>;
open: boolean;
submitting: boolean;
}
export function ProjectFormModal({
editingProject,
onCancel,
onCreate,
onOpenChange,
onUpdate,
open,
submitting,
}: ProjectFormModalProps) {
const { message } = AntApp.useApp();
const [form] = Form.useForm<FormValues>();
const handleFinish = async (values: FormValues) => {
try {
if (editingProject) {
const reqData: UpdateProjectRequest = {};
if (values.name !== editingProject.name) reqData.name = values.name;
if ((values.description ?? "") !== (editingProject.description ?? "")) reqData.description = values.description;
await onUpdate({ data: reqData, id: editingProject.id });
message.success("项目已更新");
} else {
const reqData: CreateProjectRequest = { description: values.description, name: values.name };
await onCreate(reqData);
message.success("项目已创建");
}
onOpenChange(false);
} catch (err) {
if (err instanceof Error) {
message.error(err.message);
}
}
};
return (
<Modal
afterOpenChange={(visible) => {
if (visible) {
if (editingProject) {
form.setFieldsValue({ description: editingProject.description, name: editingProject.name });
} else {
form.resetFields();
}
}
}}
confirmLoading={submitting}
destroyOnHidden
okText="确定"
onCancel={onCancel}
onOk={() => void form.submit()}
open={open}
title={editingProject ? "编辑项目" : "新建项目"}
>
<Form form={form} layout="vertical" onFinish={(values) => void handleFinish(values)}>
<Form.Item
label="项目名称"
name="name"
rules={[{ message: "项目名称不能为空", required: true, whitespace: true }]}
>
<Input maxLength={100} placeholder="请输入项目名称" />
</Form.Item>
<Form.Item label="项目描述" name="description">
<Input.TextArea autoSize={{ minRows: 5 }} maxLength={500} placeholder="请输入项目描述" />
</Form.Item>
</Form>
</Modal>
);
}

View File

@@ -0,0 +1,159 @@
import type { ColumnsType } from "antd/es/table";
import { DeleteOutlined, EditOutlined, InboxOutlined, RedoOutlined } from "@ant-design/icons";
import { App as AntApp, Button, Popconfirm, Space, Table, Tag } from "antd";
import type { Project, ProjectListResponse } from "../../../../shared/api";
interface ProjectTableProps {
data: ProjectListResponse | undefined;
loading: boolean;
onArchive: (id: string) => Promise<unknown>;
onDelete: (id: string) => Promise<unknown>;
onEdit: (project: Project) => void;
onPageChange: (page: number, pageSize: number) => void;
onRestore: (id: string) => Promise<unknown>;
page: number;
pageSize: number;
}
const COLUMNS: ColumnsType<Project> = [
{ dataIndex: "name", ellipsis: true, title: "项目名称", width: 160 },
{ dataIndex: "description", ellipsis: true, title: "项目描述" },
{
align: "center",
dataIndex: "status",
render: (_value, record: Project) => {
if (record.status === "archived") {
return <Tag></Tag>;
}
return <Tag color="blue"></Tag>;
},
title: "状态",
width: 100,
},
{
align: "center",
dataIndex: "createdAt",
render: (_value, record: Project) => formatDatetime(record.createdAt),
title: "创建时间",
width: 185,
},
{
align: "center",
dataIndex: "updatedAt",
render: (_value, record: Project) => formatDatetime(record.updatedAt),
title: "更新时间",
width: 185,
},
];
export function ProjectTable({
data,
loading,
onArchive,
onDelete,
onEdit,
onPageChange,
onRestore,
page,
pageSize,
}: ProjectTableProps) {
const { message } = AntApp.useApp();
const handleArchive = async (id: string) => {
try {
await onArchive(id);
message.success("项目已归档");
} catch (err) {
message.error((err as Error).message);
}
};
const handleRestore = async (id: string) => {
try {
await onRestore(id);
message.success("项目已恢复");
} catch (err) {
message.error((err as Error).message);
}
};
const handleDelete = async (id: string) => {
try {
await onDelete(id);
message.success("项目已永久删除");
} catch (err) {
message.error((err as Error).message);
}
};
const operationColumn: ColumnsType<Project>[number] = {
dataIndex: "op",
fixed: "right",
render: (_value, record: Project) => {
if (record.status === "active") {
return (
<Space size="small">
<Button icon={<EditOutlined />} onClick={() => onEdit(record)} size="small" type="link">
</Button>
<Popconfirm
description="归档后项目将变为只读。"
onConfirm={() => void handleArchive(record.id)}
title="确认归档此项目?"
>
<Button color="orange" icon={<InboxOutlined />} size="small" variant="link">
</Button>
</Popconfirm>
</Space>
);
}
return (
<Space size="small">
<Popconfirm onConfirm={() => void handleRestore(record.id)} title="确认恢复此项目?">
<Button icon={<RedoOutlined />} size="small" type="link">
</Button>
</Popconfirm>
<Popconfirm
description="此操作不可恢复。"
onConfirm={() => void handleDelete(record.id)}
title="确认永久删除此项目?"
>
<Button danger icon={<DeleteOutlined />} size="small" type="link">
</Button>
</Popconfirm>
</Space>
);
},
title: "操作",
width: 180,
};
return (
<Table
columns={[...COLUMNS, operationColumn]}
dataSource={data?.items ?? []}
loading={loading}
pagination={{
current: page,
hideOnSinglePage: false,
onChange: onPageChange,
pageSize,
showSizeChanger: true,
total: data?.total ?? 0,
}}
rowKey="id"
scroll={{ x: 900 }}
/>
);
}
function formatDatetime(dateStr: string): string {
const d = new Date(dateStr);
const pad = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

View File

@@ -0,0 +1,48 @@
import { PlusOutlined } from "@ant-design/icons";
import { Button, Flex, Input, Tabs } from "antd";
import type { ProjectStatus } from "../../../../shared/api";
interface ProjectToolbarProps {
activeTab: ProjectStatus;
keyword: string;
onSearch: (value: string) => void;
onSearchClear: () => void;
onTabChange: (key: string) => void;
openCreateDialog: () => void;
}
const STATUS_TAB_ITEMS = [
{ key: "active", label: "进行中" },
{ key: "archived", label: "已归档" },
];
export function ProjectToolbar({
activeTab,
keyword,
onSearch,
onSearchClear,
onTabChange,
openCreateDialog,
}: ProjectToolbarProps) {
return (
<Flex align="center" gap="var(--ant-margin-lg)" justify="space-between" wrap="wrap">
<Tabs activeKey={activeTab} items={STATUS_TAB_ITEMS} onChange={onTabChange} />
<Flex align="center" gap="small">
<Input.Search
allowClear
enterButton="搜索"
onClear={onSearchClear}
onSearch={onSearch}
placeholder="搜索项目名称或描述"
value={keyword}
/>
{activeTab === "active" && (
<Button icon={<PlusOutlined />} onClick={openCreateDialog} type="primary">
</Button>
)}
</Flex>
</Flex>
);
}

View File

@@ -1,17 +1,7 @@
import type { ColumnsType } from "antd/es/table";
import {
DeleteOutlined,
EditOutlined,
InboxOutlined,
PlusOutlined,
RedoOutlined,
SearchOutlined,
} from "@ant-design/icons";
import { App as AntApp, Button, Form, Input, Modal, Popconfirm, Space, Table, Tabs, Tag } from "antd";
import { Flex } from "antd";
import { useState } from "react";
import type { CreateProjectRequest, Project, ProjectStatus, UpdateProjectRequest } from "../../../shared/api";
import type { Project, ProjectStatus } from "../../../shared/api";
import {
useArchiveProject,
@@ -21,29 +11,18 @@ import {
useRestoreProject,
useUpdateProject,
} from "../../hooks/use-projects";
const STATUS_TAB_ITEMS = [
{ key: "active", label: "进行中" },
{ key: "archived", label: "已归档" },
];
interface FormValues {
description?: string;
name: string;
}
import { ProjectFormModal } from "./components/ProjectFormModal";
import { ProjectTable } from "./components/ProjectTable";
import { ProjectToolbar } from "./components/ProjectToolbar";
export function ProjectsPage() {
const { message } = AntApp.useApp();
const [tabValue, setTabValue] = useState<ProjectStatus>("active");
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [keyword, setKeyword] = useState("");
const [searchValue, setSearchValue] = useState("");
const [dialogOpen, setDialogOpen] = useState(false);
const [editingProject, setEditingProject] = useState<null | Project>(null);
const [form] = Form.useForm<FormValues>();
const { data, isLoading } = useProjectList({ keyword: keyword || undefined, page, pageSize, status: tabValue });
const createMutation = useCreateProject();
@@ -52,236 +31,59 @@ export function ProjectsPage() {
const restoreMutation = useRestoreProject();
const deleteMutation = useDeleteProject();
const handleSearch = () => {
setKeyword(searchValue);
setPage(1);
};
const handleSearchKeydown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
handleSearch();
}
};
const handleTabChange = (key: string) => {
setTabValue(key as ProjectStatus);
setPage(1);
};
const openCreateDialog = () => {
setEditingProject(null);
setDialogOpen(true);
};
const openEditDialog = (project: Project) => {
setEditingProject(project);
setDialogOpen(true);
};
const handleDialogOk = async () => {
try {
const values = await form.validateFields();
if (editingProject) {
const reqData: UpdateProjectRequest = {};
if (values.name !== editingProject.name) reqData.name = values.name;
if ((values.description ?? "") !== (editingProject.description ?? "")) reqData.description = values.description;
await updateMutation.mutateAsync({ data: reqData, id: editingProject.id });
message.success("项目已更新");
} else {
const reqData: CreateProjectRequest = { description: values.description, name: values.name };
await createMutation.mutateAsync(reqData);
message.success("项目已创建");
}
setDialogOpen(false);
} catch (err) {
if (err instanceof Error) {
message.error(err.message);
}
}
};
const handleArchive = async (id: string) => {
try {
await archiveMutation.mutateAsync(id);
message.success("项目已归档");
} catch (err) {
message.error((err as Error).message);
}
};
const handleRestore = async (id: string) => {
try {
await restoreMutation.mutateAsync(id);
message.success("项目已恢复");
} catch (err) {
message.error((err as Error).message);
}
};
const handleDelete = async (id: string) => {
try {
await deleteMutation.mutateAsync(id);
message.success("项目已永久删除");
} catch (err) {
message.error((err as Error).message);
}
};
const columns: ColumnsType<Project> = [
{ dataIndex: "name", ellipsis: true, title: "项目名称", width: 160 },
{ dataIndex: "description", ellipsis: true, title: "项目描述" },
{
align: "center",
dataIndex: "status",
render: (_value, record: Project) => {
if (record.status === "archived") {
return <Tag></Tag>;
}
return <Tag color="blue"></Tag>;
},
title: "状态",
width: 100,
},
{
align: "center",
dataIndex: "createdAt",
render: (_value, record: Project) => formatDatetime(record.createdAt),
title: "创建时间",
width: 185,
},
{
align: "center",
dataIndex: "updatedAt",
render: (_value, record: Project) => formatDatetime(record.updatedAt),
title: "更新时间",
width: 185,
},
{
dataIndex: "op",
fixed: "right",
render: (_value, record: Project) => {
if (record.status === "active") {
return (
<Space size="small">
<Button icon={<EditOutlined />} onClick={() => openEditDialog(record)} size="small" type="link">
</Button>
<Popconfirm
description="归档后项目将变为只读。"
onConfirm={() => void handleArchive(record.id)}
title="确认归档此项目?"
>
<Button icon={<InboxOutlined />} size="small" type="link">
</Button>
</Popconfirm>
</Space>
);
}
return (
<Space size="small">
<Popconfirm onConfirm={() => void handleRestore(record.id)} title="确认恢复此项目?">
<Button icon={<RedoOutlined />} size="small" type="link">
</Button>
</Popconfirm>
<Popconfirm
description="此操作不可恢复。"
onConfirm={() => void handleDelete(record.id)}
title="确认永久删除此项目?"
>
<Button danger icon={<DeleteOutlined />} size="small" type="link">
</Button>
</Popconfirm>
</Space>
);
},
title: "操作",
width: 180,
},
];
const isSubmitting = createMutation.isPending || updateMutation.isPending;
const isRowActionPending = archiveMutation.isPending || restoreMutation.isPending || deleteMutation.isPending;
return (
<Space className="full-width-space" size="large" vertical>
<div className="projects-header">
<Tabs activeKey={tabValue} items={STATUS_TAB_ITEMS} onChange={handleTabChange} />
<Space>
<Input
allowClear
onChange={(e) => setSearchValue(e.target.value)}
onClear={() => {
setKeyword("");
setSearchValue("");
setPage(1);
}}
onKeyDown={handleSearchKeydown}
placeholder="搜索项目名称或描述"
value={searchValue}
/>
<Button icon={<SearchOutlined />} onClick={handleSearch}>
</Button>
{tabValue === "active" && (
<Button icon={<PlusOutlined />} onClick={openCreateDialog} type="primary">
</Button>
)}
</Space>
</div>
<Table
columns={columns}
dataSource={data?.items ?? []}
loading={isLoading || archiveMutation.isPending || restoreMutation.isPending || deleteMutation.isPending}
pagination={{
current: page,
onChange: (p, ps) => {
setPage(p);
setPageSize(ps);
},
pageSize,
total: data?.total ?? 0,
<Flex flex={1} gap="var(--ant-margin-lg)" vertical>
<ProjectToolbar
activeTab={tabValue}
keyword={keyword}
onSearch={(value) => {
setKeyword(value);
setPage(1);
}}
onSearchClear={() => {
setKeyword("");
setPage(1);
}}
onTabChange={(key) => {
setTabValue(key as ProjectStatus);
setPage(1);
}}
openCreateDialog={() => {
setEditingProject(null);
setDialogOpen(true);
}}
rowKey="id"
/>
<Modal
afterOpenChange={(open) => {
if (open) {
if (editingProject) {
form.setFieldsValue({ description: editingProject.description, name: editingProject.name });
} else {
form.resetFields();
}
}
<ProjectTable
data={data}
loading={isLoading || isRowActionPending}
onArchive={(id) => archiveMutation.mutateAsync(id)}
onDelete={(id) => deleteMutation.mutateAsync(id)}
onEdit={(project) => {
setEditingProject(project);
setDialogOpen(true);
}}
confirmLoading={isSubmitting}
destroyOnHidden
okText="确定"
onPageChange={(p, ps) => {
setPage(p);
setPageSize(ps);
}}
onRestore={(id) => restoreMutation.mutateAsync(id)}
page={page}
pageSize={pageSize}
/>
<ProjectFormModal
editingProject={editingProject}
onCancel={() => setDialogOpen(false)}
// eslint-disable-next-line @typescript-eslint/no-misused-promises -- handleDialogOk 是 async 但最终返回 voidlint 规则误报
onOk={handleDialogOk}
onCreate={(data) => createMutation.mutateAsync(data)}
onOpenChange={setDialogOpen}
onUpdate={(args) => updateMutation.mutateAsync(args)}
open={dialogOpen}
title={editingProject ? "编辑项目" : "新建项目"}
>
<Form form={form} layout="vertical">
<Form.Item label="项目名称" name="name" rules={[{ message: "项目名称不能为空", required: true }]}>
<Input maxLength={100} placeholder="请输入项目名称" />
</Form.Item>
<Form.Item label="项目描述" name="description">
<Input.TextArea autoSize={{ minRows: 5 }} maxLength={500} placeholder="请输入项目描述" />
</Form.Item>
</Form>
</Modal>
</Space>
submitting={isSubmitting}
/>
</Flex>
);
}
function formatDatetime(dateStr: string): string {
const d = new Date(dateStr);
const pad = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

View File

@@ -1,5 +1,3 @@
import type { ReactNode } from "react";
import { Route, Routes } from "react-router";
import { NotFoundPage } from "./pages/404";
@@ -15,7 +13,3 @@ export function AppRoutes() {
</Routes>
);
}
export function ProtectedRoute({ children }: { children: ReactNode }) {
return children;
}

View File

@@ -1,7 +1,10 @@
html,
body {
margin: 0;
}
.app-layout {
min-height: 100vh;
background: var(--ant-color-bg-layout);
width: 100%;
}
.app-header {
@@ -11,7 +14,6 @@
padding: 0 var(--ant-padding-lg);
background: var(--ant-color-bg-container);
border-bottom: 1px solid var(--ant-color-border-secondary);
height: 64px;
}
.app-header-left {
@@ -47,75 +49,6 @@
line-height: 1;
}
.app-sidebar-collapse-btn {
width: 100%;
justify-content: center;
color: var(--ant-color-text-secondary);
}
.app-page-title {
color: var(--ant-color-text-secondary);
font-size: var(--ant-font-size-heading-3);
font-weight: 500;
}
.app-sidebar {
background: var(--ant-color-bg-container);
border-right: 1px solid var(--ant-color-border-secondary);
height: calc(100vh - 64px);
overflow: hidden;
}
.app-sidebar-menu {
height: 100%;
overflow-y: auto;
}
.app-content {
box-sizing: border-box;
padding: var(--ant-padding-xl) var(--ant-padding-xl);
min-height: calc(100vh - 64px);
}
.meta-response {
background: var(--ant-color-fill-tertiary);
border-radius: var(--ant-border-radius);
padding: var(--ant-padding-lg) var(--ant-padding-lg);
font-size: var(--ant-font-size);
color: var(--ant-color-text);
overflow-x: auto;
}
.error-boundary-fallback {
padding-top: 20vh;
width: 100%;
}
.full-width {
width: 100%;
}
.text-disabled {
color: var(--ant-color-text-disabled);
}
.full-width-space {
width: 100%;
}
.not-found-icon {
color: var(--ant-color-warning);
font-size: 64px;
}
.tabular-nums {
font-variant-numeric: tabular-nums;
}
.projects-header {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--ant-margin-lg);
}

View File

@@ -59,7 +59,7 @@ describe("App", () => {
const sider = document.querySelector(".ant-layout-sider");
expect(sider).not.toBeNull();
const menu = document.querySelector(".app-sidebar-menu");
const menu = document.querySelector(".ant-menu");
expect(menu).not.toBeNull();
});
});

View File

@@ -11,14 +11,13 @@ describe("NotFoundPage", () => {
expect(screen.getByText("404")).not.toBeNull();
expect(screen.getByText("您访问的页面不存在")).not.toBeNull();
expect(screen.getByText("返回首页")).not.toBeNull();
expect(screen.getByRole("button", { name: "返回首页" })).not.toBeNull();
});
test("返回首页按钮存在且可点击", () => {
renderWithProviders(createElement(NotFoundPage));
const button = screen.getByText("返回首页");
const button = screen.getByRole("button", { name: "返回首页" });
expect(button).not.toBeNull();
expect(button.closest("button")).not.toBeNull();
});
});

View File

@@ -11,8 +11,8 @@ describe("ProjectsPage", () => {
expect(screen.getByText("进行中")).not.toBeNull();
expect(screen.getByText("已归档")).not.toBeNull();
expect(screen.getByText("搜索")).not.toBeNull();
expect(screen.getByText("新建项目")).not.toBeNull();
expect(screen.getByPlaceholderText("搜索项目名称或描述")).not.toBeNull();
await waitFor(
() => {